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
Provenance
- Commit
8627010- Tree
a3124de- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
77b0815
39 files changed+2505 added−2289 removed
modified:deno_dist/middleware/serve-static/serve-static.ts+3 added-4 removed
12123456 unmodified lines12131415171816171819202128 unmodified linesimport type { Context } from '../../context.ts'import type { Next } from '../../hono.ts'import type { MiddlewareHandler } from '../../hono.ts'import { getContentFromKVAsset } from '../../utils/cloudflare.ts'import { getFilePath } from '../../utils/filepath.ts'import { getMimeType } from '../../utils/mime.ts'
6 unmodified lines
const DEFAULT_DOCUMENT = 'index.html'
// This middleware is available only on Cloudflare Workers.export const serveStatic = (options: ServeStaticOptions = { root: '' }) => { return async (c: Context, next: Next) => {export const serveStatic = (options: ServeStaticOptions = { root: '' }): MiddlewareHandler => { return async (c, next) => { // Do nothing if Response is already set if (c.finalized) { await next() return28 unmodified linesmodified:deno_dist/middleware/validator/middleware.ts+20 added-72 removed
1 import type { Context } from '../../context.ts'2-import type { Environment, Next, ValidatedData } from '../../hono.ts'2+import type { Environment, MiddlewareHandler } from '../../hono.ts'3 import { getStatusText } from '../../utils/http-status.ts'4 import { mergeObjects } from '../../utils/object.ts'5-import { VBase, Validator, VObjectBase } from './validator.ts'6-import type {7- VString,8- VNumber,9- VBoolean,10- VObject,11- VNumberArray,12- VStringArray,13- VBooleanArray,14- ValidateResult,15- VArray,16-} from './validator.ts'5+import type { Schema } from '../../validator/schema.ts'6+import type { ValidateResult } from '../../validator/validator.ts'7+import { Validator, VBase, VObjectBase } from '../../validator/validator.ts'8 18-export type Schema = {19- [key: string]:20- | VString21- | VNumber22- | VBoolean23- | VStringArray24- | VNumberArray25- | VBooleanArray26- | Schema27- | VObject<Schema>28- | VArray<Schema>29-}30-31-type 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-}60-9 type ResultSet = {10 hasError: boolean11 messages: string[]12 results: ValidateResult[]13 }14 67-type Done<Env extends Partial<Environment>> = (15+type Done<P extends string, E extends Partial<Environment> = Environment> = (16 resultSet: ResultSet,69- context: Context<string, Env>17+ c: Context<P, E>18 ) => Response | void19 72-type ValidationFunction<T, Env extends Partial<Environment>> = (73- v: Validator,74- c: Context<string, Env>75-) => T20+type ValidationFunction<21+ P extends string,22+ E extends Partial<Environment> = Environment,23+ S extends Schema = Schema24+> = (v: Validator, c: Context<P, E>) => S25 77-type MiddlewareHandler<78- Data extends ValidatedData = ValidatedData,79- Env extends Partial<Environment> = Environment80-> = (c: Context<string, Env, Data>, next: Next) => Promise<void> | Promise<Response | undefined>81-82-export const validatorMiddleware = <T extends Schema, Env extends Partial<Environment>>(83- validationFunction: ValidationFunction<T, Env>,84- options?: { done?: Done<Env> }26+export 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 lines45 46 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 linesdeleted: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.js6-7-export 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- },17-18- 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- },38-39- isAlpha: (value: string): boolean => {40- return /^[A-Z]+$/i.test(value)41- },42-43- isNumeric: (value: string): boolean => {44- return /^[0-9]+$/.test(value)45- },46-47- 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- },62-63- 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- },71-72- match: (value: string, regExp: RegExp): boolean => {73- return regExp.test(value)74- },75-76- // number77- isGte: (value: number, min: number) => min <= value,78- isLte: (value: number, max: number) => value <= max,79-80- // boolean81- isTrue: (value: boolean) => value === true,82- isFalse: (value: boolean) => value === false,83-}deleted:deno_dist/middleware/validator/sanitizer.ts-3 removed
123export const sanitizer = { trim: (value: string) => value.trim(),}deleted:deno_dist/middleware/validator/validator.ts-492 removed
1-import { JSONPathCopy } from '../../utils/json.ts'2-import type { JSONObject, JSONPrimitive, JSONArray } from '../../utils/json.ts'3-import type { Schema } from './middleware.ts'4-import { rule } from './rule.ts'5-import { sanitizer } from './sanitizer.ts'6-7-type Target = 'query' | 'header' | 'body' | 'json'8-type Type = JSONPrimitive | JSONObject | JSONArray | File9-type RuleFunc = (value: Type) => boolean10-type Rule = {11- name: string12- func: RuleFunc13- customMessage?: string14- type: 'type' | 'value'15-}16-type Sanitizer = (value: Type) => Type17-18-export type ValidateResult = {19- isValid: boolean20- message: string | undefined21- target: Target22- key: string23- value: Type24- ruleName: string25- ruleType: 'type' | 'value'26- jsonData?: JSONObject27-}28-29-export 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- }41-42- isOptional() {43- this._isOptional = true44- return this45- }46-47- getValidators = (): VBase[] => {48- const validators: VBase[] = []49- const thisKeys: string[] = []50- Object.assign(thisKeys, this.keys)51-52- 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- }70-71- walk(this.container, this.keys, this._isOptional)72-73- return validators74- }75-}76-77-export class VObject<T extends Schema> extends VObjectBase<T> {78- constructor(container: T, key: string) {79- super(container, key)80- }81-}82-83-export class VArray<T extends Schema> extends VObjectBase<T> {84- type: 'array' = 'array'85- constructor(container: T, key: string) {86- super(container, key)87- }88-}89-90-export 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-}115-116-type VOptions = {117- target: Target118- key: string119- type?: 'string' | 'number' | 'boolean' | 'object'120- isArray?: boolean121-}122-123-export 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- }147-148- private _nested = () => (this.baseKeys.length ? true : false)149-150- 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- }160-161- addSanitizer = (sanitizer: Sanitizer) => {162- this.sanitizers.push(sanitizer)163- return this164- }165-166- message = (text: string) => {167- const len = this.rules.length168- if (len >= 1) {169- this.rules[len - 1].customMessage = text170- }171- return this172- }173-174- isRequired = () => {175- return this.addRule('isRequired', (value: unknown) => {176- if (value !== undefined && value !== null && value !== '') return true177- return false178- })179- }180-181- isOptional = () => {182- this._optional = true183- return this.addRule('isOptional', () => true)184- }185-186- isEqual = (comparison: unknown) => {187- return this.addRule('isEqual', (value: unknown) => {188- return value === comparison189- })190- }191-192- asNumber = (): VNumber | VNumberArray => {193- const newVNumber = new VNumber({ ...this, type: 'number' })194- if (this.isArray) return newVNumber.asArray()195- return newVNumber196- }197-198- asBoolean = (): VBoolean | VBooleanArray => {199- const newVBoolean = new VBoolean({ ...this, type: 'boolean' })200- if (this.isArray) return newVBoolean.asArray()201- return newVBoolean202- }203-204- get(value: string) {205- const len = this.rules.length206- if (len > 0) {207- this.rules[this.rules.length - 1].customMessage = value208- }209- return this210- }211-212- validate = async (req: Request): Promise<ValidateResult[]> => {213- let value: Type = undefined214- let jsonData: JSONObject | undefined = undefined215-216- 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- }240-241- const results: ValidateResult[] = []242-243- let typeRule = this.rules.shift()244-245- 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- }254-255- if (typeRule) {256- const typeResult = this.validateRule(typeRule, value)257- typeResult.jsonData ||= jsonData258- results.unshift(typeResult)259- }260-261- return results262- }263-264- protected getTypeRuleName(): string {265- const prefix = 'should be'266- return this.isArray ? `${prefix} "${this.type}[]"` : `${prefix} "${this.type}"`267- }268-269- private validateRule(rule: Rule, value: Type): ValidateResult {270- let isValid: boolean = false271-272- 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- }279-280- 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- }294-295- 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- }324-325- private validateValue = (func: (value: Type) => boolean, value: Type): boolean => {326- if (this._optional && typeof value === 'undefined') return true327-328- 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- }350-351- 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-}377-378-export class VString extends VBase {379- constructor(options: VOptions) {380- super(options)381- this.type = 'string'382- }383-384- asArray = () => {385- return new VStringArray(this)386- }387-388- isEmpty = (389- options: {390- ignore_whitespace: boolean391- } = { ignore_whitespace: false }392- ) => {393- return this.addRule('isEmpty', (value) => rule.isEmpty(value as string, options))394- }395-396- isLength = (options: Partial<{ min: number; max: number }> | number, arg2?: number) => {397- return this.addRule('isLength', (value) => rule.isLength(value as string, options, arg2))398- }399-400- isAlpha = () => {401- return this.addRule('isAlpha', (value) => rule.isAlpha(value as string))402- }403-404- isNumeric = () => {405- return this.addRule('isNumeric', (value) => rule.isNumeric(value as string))406- }407-408- 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- }417-418- isIn = (options: string[]) => {419- return this.addRule('isIn', (value) => rule.isIn(value as string, options))420- }421-422- match = (regExp: RegExp) => {423- return this.addRule('match', (value) => rule.match(value as string, regExp))424- }425-426- trim = () => {427- return this.addSanitizer((value) => sanitizer.trim(value as string))428- }429-}430-431-export class VNumber extends VBase {432- constructor(options: VOptions) {433- super(options)434- this.type = 'number'435- }436-437- asArray = () => {438- return new VNumberArray(this)439- }440-441- isGte = (min: number) => {442- return this.addRule('isGte', (value) => rule.isGte(value as number, min))443- }444-445- isLte = (min: number) => {446- return this.addRule('isLte', (value) => rule.isLte(value as number, min))447- }448-}449-450-export class VBoolean extends VBase {451- constructor(options: VOptions) {452- super(options)453- this.type = 'boolean'454- }455-456- asArray = () => {457- return new VBooleanArray(this)458- }459-460- isTrue = () => {461- return this.addRule('isTrue', (value) => rule.isTrue(value as boolean))462- }463-464- isFalse = () => {465- return this.addRule('isFalse', (value) => rule.isFalse(value as boolean))466- }467-}468-469-export 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-}477-export 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-}485-export 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
12345export type Expect<T extends true> = Texport type Equal<X, Y> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2 ? true : falseexport type NotEqual<X, Y> = true extends Equal<X, Y> ? false : trueadded: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.js6+7+export 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+ },17+18+ 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+ },38+39+ isAlpha: (value: string): boolean => {40+ return /^[A-Z]+$/i.test(value)41+ },42+43+ isNumeric: (value: string): boolean => {44+ return /^[0-9]+$/.test(value)45+ },46+47+ 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+ },62+63+ 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+ },71+72+ match: (value: string, regExp: RegExp): boolean => {73+ return regExp.test(value)74+ },75+76+ // number77+ isGte: (value: number, min: number) => min <= value,78+ isLte: (value: number, max: number) => value <= max,79+80+ // boolean81+ isTrue: (value: boolean) => value === true,82+ isFalse: (value: boolean) => value === false,83+}added:deno_dist/validator/sanitizer.ts+3 added
123export const sanitizer = { trim: (value: string) => value.trim(),}added:deno_dist/validator/schema.ts+54 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354import type { VString, VNumber, VBoolean, VObject, VNumberArray, VStringArray, VBooleanArray, VArray, VObjectBase,} from './validator.ts'
export type Schema = { [key: string]: | VString | VNumber | VBoolean | VStringArray | VNumberArray | VBooleanArray | Schema | VObject<Schema> | VArray<Schema>}
export type SchemaToProp<T> = { [K in keyof T]: T[K] extends VNumberArray ? number[] : T[K] extends VBooleanArray ? boolean[] : T[K] extends VStringArray ? string[] : T[K] extends VNumber ? number : T[K] extends VBoolean ? boolean : T[K] extends VString ? string : T[K] extends VObjectBase<Schema> ? T[K]['container'] extends VNumber ? number : T[K]['container'] extends VString ? string : T[K]['container'] extends VBoolean ? boolean : T[K] extends VArray<Schema> ? SchemaToProp<ReadonlyArray<T[K]['container']>> : T[K] extends VObject<Schema> ? SchemaToProp<T[K]['container']> : T[K] extends Schema ? SchemaToProp<T[K]> : never : SchemaToProp<T[K]>}added:deno_dist/validator/validator.ts+492 added
1+import { JSONPathCopy } from './../utils/json.ts'2+import type { JSONObject, JSONPrimitive, JSONArray } from './../utils/json.ts'3+import { rule } from './rule.ts'4+import { sanitizer } from './sanitizer.ts'5+import type { Schema } from './schema.ts'6+7+type Target = 'query' | 'header' | 'body' | 'json'8+type Type = JSONPrimitive | JSONObject | JSONArray | File9+type RuleFunc = (value: Type) => boolean10+type Rule = {11+ name: string12+ func: RuleFunc13+ customMessage?: string14+ type: 'type' | 'value'15+}16+type Sanitizer = (value: Type) => Type17+18+export type ValidateResult = {19+ isValid: boolean20+ message: string | undefined21+ target: Target22+ key: string23+ value: Type24+ ruleName: string25+ ruleType: 'type' | 'value'26+ jsonData?: JSONObject27+}28+29+export 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+ }41+42+ isOptional() {43+ this._isOptional = true44+ return this45+ }46+47+ getValidators = (): VBase[] => {48+ const validators: VBase[] = []49+ const thisKeys: string[] = []50+ Object.assign(thisKeys, this.keys)51+52+ 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+ }70+71+ walk(this.container, this.keys, this._isOptional)72+73+ return validators74+ }75+}76+77+export class VObject<T extends Schema> extends VObjectBase<T> {78+ constructor(container: T, key: string) {79+ super(container, key)80+ }81+}82+83+export class VArray<T extends Schema> extends VObjectBase<T> {84+ type: 'array' = 'array'85+ constructor(container: T, key: string) {86+ super(container, key)87+ }88+}89+90+export 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+}115+116+type VOptions = {117+ target: Target118+ key: string119+ type?: 'string' | 'number' | 'boolean' | 'object'120+ isArray?: boolean121+}122+123+export 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+ }147+148+ private _nested = () => (this.baseKeys.length ? true : false)149+150+ 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+ }160+161+ addSanitizer = (sanitizer: Sanitizer) => {162+ this.sanitizers.push(sanitizer)163+ return this164+ }165+166+ message = (text: string) => {167+ const len = this.rules.length168+ if (len >= 1) {169+ this.rules[len - 1].customMessage = text170+ }171+ return this172+ }173+174+ isRequired = () => {175+ return this.addRule('isRequired', (value: unknown) => {176+ if (value !== undefined && value !== null && value !== '') return true177+ return false178+ })179+ }180+181+ isOptional = () => {182+ this._optional = true183+ return this.addRule('isOptional', () => true)184+ }185+186+ isEqual = (comparison: unknown) => {187+ return this.addRule('isEqual', (value: unknown) => {188+ return value === comparison189+ })190+ }191+192+ asNumber = (): VNumber | VNumberArray => {193+ const newVNumber = new VNumber({ ...this, type: 'number' })194+ if (this.isArray) return newVNumber.asArray()195+ return newVNumber196+ }197+198+ asBoolean = (): VBoolean | VBooleanArray => {199+ const newVBoolean = new VBoolean({ ...this, type: 'boolean' })200+ if (this.isArray) return newVBoolean.asArray()201+ return newVBoolean202+ }203+204+ get(value: string) {205+ const len = this.rules.length206+ if (len > 0) {207+ this.rules[this.rules.length - 1].customMessage = value208+ }209+ return this210+ }211+212+ validate = async <R extends Request>(req: R): Promise<ValidateResult[]> => {213+ let value: Type = undefined214+ let jsonData: JSONObject | undefined = undefined215+216+ 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+ }240+241+ const results: ValidateResult[] = []242+243+ let typeRule = this.rules.shift()244+245+ 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+ }254+255+ if (typeRule) {256+ const typeResult = this.validateRule(typeRule, value)257+ typeResult.jsonData ||= jsonData258+ results.unshift(typeResult)259+ }260+261+ return results262+ }263+264+ protected getTypeRuleName(): string {265+ const prefix = 'should be'266+ return this.isArray ? `${prefix} "${this.type}[]"` : `${prefix} "${this.type}"`267+ }268+269+ private validateRule(rule: Rule, value: Type): ValidateResult {270+ let isValid: boolean = false271+272+ 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+ }279+280+ 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+ }294+295+ 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+ }324+325+ private validateValue = (func: (value: Type) => boolean, value: Type): boolean => {326+ if (this._optional && typeof value === 'undefined') return true327+328+ 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+ }350+351+ 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+}377+378+export class VString extends VBase {379+ constructor(options: VOptions) {380+ super(options)381+ this.type = 'string'382+ }383+384+ asArray = () => {385+ return new VStringArray(this)386+ }387+388+ isEmpty = (389+ options: {390+ ignore_whitespace: boolean391+ } = { ignore_whitespace: false }392+ ) => {393+ return this.addRule('isEmpty', (value) => rule.isEmpty(value as string, options))394+ }395+396+ isLength = (options: Partial<{ min: number; max: number }> | number, arg2?: number) => {397+ return this.addRule('isLength', (value) => rule.isLength(value as string, options, arg2))398+ }399+400+ isAlpha = () => {401+ return this.addRule('isAlpha', (value) => rule.isAlpha(value as string))402+ }403+404+ isNumeric = () => {405+ return this.addRule('isNumeric', (value) => rule.isNumeric(value as string))406+ }407+408+ 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+ }417+418+ isIn = (options: string[]) => {419+ return this.addRule('isIn', (value) => rule.isIn(value as string, options))420+ }421+422+ match = (regExp: RegExp) => {423+ return this.addRule('match', (value) => rule.match(value as string, regExp))424+ }425+426+ trim = () => {427+ return this.addSanitizer((value) => sanitizer.trim(value as string))428+ }429+}430+431+export class VNumber extends VBase {432+ constructor(options: VOptions) {433+ super(options)434+ this.type = 'number'435+ }436+437+ asArray = () => {438+ return new VNumberArray(this)439+ }440+441+ isGte = (min: number) => {442+ return this.addRule('isGte', (value) => rule.isGte(value as number, min))443+ }444+445+ isLte = (min: number) => {446+ return this.addRule('isLte', (value) => rule.isLte(value as number, min))447+ }448+}449+450+export class VBoolean extends VBase {451+ constructor(options: VOptions) {452+ super(options)453+ this.type = 'boolean'454+ }455+456+ asArray = () => {457+ return new VBooleanArray(this)458+ }459+460+ isTrue = () => {461+ return this.addRule('isTrue', (value) => rule.isTrue(value as boolean))462+ }463+464+ isFalse = () => {465+ return this.addRule('isFalse', (value) => rule.isFalse(value as boolean))466+ }467+}468+469+export 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+}477+export 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+}485+export 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
1234566789101011121314151617121318192021222359 unmodified linesimport { HonoContext } from './context.ts'import type { Environment, NotFoundHandler, ErrorHandler } from './hono.ts'import type { Schema } from './validator/schema.ts'
interface ComposeContext { finalized: boolean res: any res: unknown}
// Based on the code in the MIT licensed `koa-compose` package.export const compose = <C extends ComposeContext, E extends Partial<Environment> = Environment>(export const compose = < C extends ComposeContext, P extends string = string, E extends Partial<Environment> = Environment, D extends Partial<Schema> = Schema>( middleware: Function[], onNotFound?: NotFoundHandler<E>, onError?: ErrorHandler<E> onNotFound?: NotFoundHandler<P, E, D>, onError?: ErrorHandler<P, E, D>) => { const middlewareLength = middleware.length return (context: C, next?: Function) => { let index = -159 unmodified linesmodified:deno_dist/context.ts+21 added-26 removed
1-import type {2- Environment,3- NotFoundHandler,4- ContextVariableMap,5- Bindings,6- ValidatedData,7-} from './hono.ts'1+import type { Environment, NotFoundHandler, ContextVariableMap, Bindings } from './hono.ts'2 import type { CookieOptions } from './utils/cookie.ts'3 import { serialize } from './utils/cookie.ts'4 import type { StatusCode } from './utils/http-status.ts'5+import type { Schema, SchemaToProp } from './validator/schema.ts'6 7 type HeaderField = [string, string]8 type Headers = Record<string, string | string[]>9 export type Data = string | ArrayBuffer | ReadableStream10 11 export 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: boolean5 unmodified lines26 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 lines45 notFound: () => Response | Promise<Response>46 }47 48 export 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 = undefined58 59 _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>67 68 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)77 78 this.notFoundHandler = notFoundHandler79 this.finalized = false56 unmodified lines136 }137 138 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 }145 146 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 lines227 this.header('set-cookie', cookie, { append: true })228 }229 230 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 lines9 import { SmartRouter } from './router/smart-router/index.ts'10 import { StaticRouter } from './router/static-router/index.ts'11 import { TrieRouter } from './router/trie-router/index.ts'12 import { getPathFromURL, mergePath } from './utils/url.ts'13+import type { Schema } from './validator/schema.ts'14 15 export interface ContextVariableMap {}16 17 export type Bindings = Record<string, any> // For Cloudflare Workers2 unmodified lines20 Bindings: Bindings21 Variables: Variables22 }23 23-export type ValidatedData = Record<string, any> // For validated data24-24 export 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>29 34-export type MiddlewareHandler = <E extends Partial<Environment> = Environment>(35- c: Context<string, E>,36- next: Next37-) => Promise<void> | Promise<Response | undefined>30+export 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>35 39-export type NotFoundHandler<E extends Partial<Environment> = Environment> = (40- c: Context<string, E>41-) => Response | Promise<Response>36+export 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>41 43-export type ErrorHandler<E extends Partial<Environment> = Environment> = (44- err: Error,45- c: Context<string, E>46-) => Response42+export 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>) => Response47 48 export type Next = () => Promise<void>49 50 // eslint-disable-next-line @typescript-eslint/no-unused-vars8 unmodified lines59 type ParamKeys<Path> = Path extends `${infer Component}/${infer Rest}`60 ? ParamKey<Component> | ParamKeys<Rest>61 : ParamKey<Path>62 63-interface HandlerInterface<T extends string, E extends Partial<Environment>, U = Hono<E, T>> {63+interface 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>[]): U74+75 // 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 }83 84 type Methods = typeof METHODS[number] | typeof METHOD_NAME_ALL_LOWERCASE85 86 function 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 }98 99 interface 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 }108 109 export 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 = '/'120 108- routes: Route<E, D>[] = []121+ routes: Route<P, E, S>[] = []122 123 constructor(init: Partial<Pick<Hono, 'router' | 'strict'>> = {}) {124 super()125 126 extendRequestPrototype()127 128 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 line147 148 Object.assign(this, init)149 }150 138- 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 }154 142- 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 }160 148- 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 }156-169 return this170 }171 160- 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 lines187 })188 return this189 }190 179- onError(handler: ErrorHandler<E>): Hono<E, P, D> {191+ onError(handler: ErrorHandler<P, E, S>) {192 this.errorHandler = handler193 return this194 }195 184- notFound(handler: NotFoundHandler<E>): Hono<E, P, D> {196+ notFound(handler: NotFoundHandler<P, E, S>) {197 this.notFoundHandler = handler198 return this199 }200 189- 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 }210 211 private matchRoute(method: string, path: string) {212 return this.router.match(method, path)213 }214 203- 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 err9 unmodified lines229 230 const result = this.matchRoute(method, path)231 request.paramData = result?.params232 221- 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)234 235 // 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>>239 240 try {241 res = handler(c, async () => {})242 if (!res) return this.notFoundHandler(c)17 unmodified lines260 })()261 }262 263 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 linesmodified:deno_dist/request.ts+6 added-5 removed
34 unmodified lines35 (): 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 lines132 }133 return body134 } as InstanceType<typeof Request>['parseBody']135 135- 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 line144 }145 return jsonData146 } as InstanceType<typeof Request>['jsonData']147 147- 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 linesmodified:src/middleware/serve-static/serve-static.ts+3 added-4 removed
1-import type { Context } from '../../context'2-import type { Next } from '../../hono'1+import type { MiddlewareHandler } from '../../hono'2 import { getContentFromKVAsset } from '../../utils/cloudflare'3 import { getFilePath } from '../../utils/filepath'4 import { getMimeType } from '../../utils/mime'5 6 unmodified lines12 13 const DEFAULT_DOCUMENT = 'index.html'14 15 // This middleware is available only on Cloudflare Workers.17-export const serveStatic = (options: ServeStaticOptions = { root: '' }) => {18- return async (c: Context, next: Next) => {16+export 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 return28 unmodified linesmodified:src/middleware/validator/middleware.test.ts+112 added-4 removed
1+/* eslint-disable @typescript-eslint/no-unused-vars */2 import { Hono } from '../../hono'3 import { getStatusText } from '../../utils/http-status'4+import type { Expect, Equal } from '../../utils/types'5+import type { Schema } from '../../validator/schema'6 import { validator } from './index'7 8 describe('Basic - query', () => {9 const app = new Hono()94 unmodified lines104 expect(await res.text()).toBe('CUSTOM MESSAGE')105 })106 })107 105-describe('Basic - JSON', () => {108+describe('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 )124 125 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 lines586 expect(res.status).toBe(400)587 })588 })589 582-describe('Array values', () => {590+describe('Array values with type check', () => {591 const app = new Hono()592 app.post(593 '/post',594 validator((v) => ({3 unmodified lines598 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()603+604+ 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[]>>607+608+ return c.json({ tag1: post.tags[0] })609 }610 )611 612 it('Should return 200 response', async () => {129 unmodified lines742 ].join('\n')743 )744 })745 })746+747+describe('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+ })773+774+ it('Should return 200 response with correct types - validator and named parameter', async () => {775+ const app = new Hono()776+777+ const vm = validator((v) => ({778+ title: v.body('title').isRequired(),779+ }))780+781+ 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+ })786+787+ 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+ })793+794+ const body = new FormData()795+ body.append('title', 'Hello')796+797+ 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+ })810+811+ it('Should return 200 response with correct types - Context in validator function', async () => {812+ type Env = { Bindings: { FOO: 'abc' } }813+814+ const app = new Hono<Env>()815+816+ 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+ )835+836+ 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
1 import type { Context } from '../../context'2-import type { Environment, Next, ValidatedData } from '../../hono'2+import type { Environment, MiddlewareHandler } from '../../hono'3 import { getStatusText } from '../../utils/http-status'4 import { mergeObjects } from '../../utils/object'5-import { VBase, Validator, VObjectBase } from './validator'6-import type {7- VString,8- VNumber,9- VBoolean,10- VObject,11- VNumberArray,12- VStringArray,13- VBooleanArray,14- ValidateResult,15- VArray,16-} from './validator'5+import type { Schema } from '../../validator/schema'6+import type { ValidateResult } from '../../validator/validator'7+import { Validator, VBase, VObjectBase } from '../../validator/validator'8 18-export type Schema = {19- [key: string]:20- | VString21- | VNumber22- | VBoolean23- | VStringArray24- | VNumberArray25- | VBooleanArray26- | Schema27- | VObject<Schema>28- | VArray<Schema>29-}30-31-type 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-}60-9 type ResultSet = {10 hasError: boolean11 messages: string[]12 results: ValidateResult[]13 }14 67-type Done<Env extends Partial<Environment>> = (15+type Done<P extends string, E extends Partial<Environment> = Environment> = (16 resultSet: ResultSet,69- context: Context<string, Env>17+ c: Context<P, E>18 ) => Response | void19 72-type ValidationFunction<T, Env extends Partial<Environment>> = (73- v: Validator,74- c: Context<string, Env>75-) => T20+type ValidationFunction<21+ P extends string,22+ E extends Partial<Environment> = Environment,23+ S extends Schema = Schema24+> = (v: Validator, c: Context<P, E>) => S25 77-type MiddlewareHandler<78- Data extends ValidatedData = ValidatedData,79- Env extends Partial<Environment> = Environment80-> = (c: Context<string, Env, Data>, next: Next) => Promise<void> | Promise<Response | undefined>81-82-export const validatorMiddleware = <T extends Schema, Env extends Partial<Environment>>(83- validationFunction: ValidationFunction<T, Env>,84- options?: { done?: Done<Env> }26+export 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 lines45 46 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 linesdeleted:src/middleware/validator/rule.test.ts-55 removed
1-import { rule } from './rule'2-3-describe('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.js6-7-export 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- },17-18- 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- },38-39- isAlpha: (value: string): boolean => {40- return /^[A-Z]+$/i.test(value)41- },42-43- isNumeric: (value: string): boolean => {44- return /^[0-9]+$/.test(value)45- },46-47- 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- },62-63- 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- },71-72- match: (value: string, regExp: RegExp): boolean => {73- return regExp.test(value)74- },75-76- // number77- isGte: (value: number, min: number) => min <= value,78- isLte: (value: number, max: number) => value <= max,79-80- // boolean81- isTrue: (value: boolean) => value === true,82- isFalse: (value: boolean) => value === false,83-}deleted:src/middleware/validator/sanitizer.test.ts-7 removed
1-import { sanitizer } from './sanitizer'2-3-describe('Sanitizers', () => {4- test('trim', () => {5- expect(sanitizer.trim(' abc ')).toBe('abc')6- })7-})deleted:src/middleware/validator/sanitizer.ts-3 removed
1-export const sanitizer = {2- trim: (value: string) => value.trim(),3-}deleted:src/middleware/validator/validator.test.ts-732 removed
1-import { extendRequestPrototype } from '../../request'2-import { Validator } from './validator'3-4-extendRequestPrototype()5-6-describe('Basic - query', () => {7- const v = new Validator()8-9- const req = new Request('http://localhost/?q=foo&page=3')10-11- 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- })20-21- 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- })31-32- 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-})45-46-describe('Basic - header', () => {47- const v = new Validator()48-49- const req = new Request('http://localhost/', {50- headers: {51- 'x-message': 'hello world!',52- 'x-number': '12345',53- },54- })55-56- 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- })66-67- 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-})76-77-describe('Basic - body', () => {78- const v = new Validator()79-80- 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- })87-88- 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- })98-99- 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-})109-110-describe('Basic - JSON', () => {111- const v = new Validator()112-113- const post = {114- id: 1234,115- title: 'This is title',116- author: {117- name: 'Superman',118- age: 20,119- },120- }121-122- const req = new Request('http://localhost/', {123- method: 'POST',124- body: JSON.stringify(post),125- })126-127- 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- })135-136- 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- })144-145- 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-})154-155-describe('Handle required values', () => {156- const v = new Validator()157-158- const req = new Request('http://localhost/', {159- method: 'POST',160- body: JSON.stringify({ comment: null, name: 'John', admin: false }),161- })162-163- 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- })169-170- 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- })176-177- 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-})185-186-describe('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-})206-207-describe('Handling types error', () => {208- const v = new Validator()209-210- const post = {211- id: '1234',212- title: 'This is title',213- published: 'true',214- }215-216- const req = new Request('http://localhost/', {217- method: 'POST',218- body: JSON.stringify(post),219- })220-221- 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- })228-229- 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-})239-240-describe('Handle array paths', () => {241- const v = new Validator()242-243- 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- }270-271- const req = new Request('http://localhost/', {272- method: 'POST',273- body: JSON.stringify(body),274- })275-276- 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- })284-285- 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- })293-294- 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- })302-303- 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- })313-314- 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- })324-325- 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-})332-333-describe('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- }358-359- const req = new Request('http://localhost/', {360- method: 'POST',361- body: JSON.stringify(json),362- })363-364- 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- })370-371- 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- })377-378- 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)383-384- 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)388-389- // Entire responses should be equal390- expect(res1).toEqual(res2)391- })392-393- 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- })404-405- 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- })411-412- 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- })426-427- 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-})437-438-describe('Invalid HTTP request handling', () => {439- const v = new Validator()440-441- it('Should throw malformed error when JSON body absent', async () => {442- const req = new Request('http://localhost/', {443- method: 'POST',444- })445-446- 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- })456-457- 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- })462-463- 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-})474-475-describe('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- }528-529- const req = new Request('http://localhost/', {530- method: 'POST',531- body: JSON.stringify(json),532- })533-534- 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- })560-561- 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- }))573-574- 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- })580-581- 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- }))586-587- 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- }595-596- 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- })606-607- 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- }))617-618- 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- }623-624- const vArray2 = v625- .array('posts', (v) => ({626- title: v.json('title').asNumber(),627- }))628- .isOptional()629-630- 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- })639-640- 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- }))650-651- 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- })657-658- 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- }))663-664- 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- }672-673- const vObject = v.object('pager', (v) => ({674- prev: v.query('prev').asBoolean(),675- next: v.body('next').asBoolean(),676- }))677-678- 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- ]682-683- 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-})690-691-describe('Custom message', () => {692- const v = new Validator()693-694- const json = {695- title: 'foo',696- post: [697- {698- id: 123,699- },700- ],701- }702-703- const req = new Request('http://localhost/', {704- method: 'POST',705- body: JSON.stringify(json),706- })707-708- 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- })724-725- 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
1-import { JSONPathCopy } from '../../utils/json'2-import type { JSONObject, JSONPrimitive, JSONArray } from '../../utils/json'3-import type { Schema } from './middleware'4-import { rule } from './rule'5-import { sanitizer } from './sanitizer'6-7-type Target = 'query' | 'header' | 'body' | 'json'8-type Type = JSONPrimitive | JSONObject | JSONArray | File9-type RuleFunc = (value: Type) => boolean10-type Rule = {11- name: string12- func: RuleFunc13- customMessage?: string14- type: 'type' | 'value'15-}16-type Sanitizer = (value: Type) => Type17-18-export type ValidateResult = {19- isValid: boolean20- message: string | undefined21- target: Target22- key: string23- value: Type24- ruleName: string25- ruleType: 'type' | 'value'26- jsonData?: JSONObject27-}28-29-export 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- }41-42- isOptional() {43- this._isOptional = true44- return this45- }46-47- getValidators = (): VBase[] => {48- const validators: VBase[] = []49- const thisKeys: string[] = []50- Object.assign(thisKeys, this.keys)51-52- 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- }70-71- walk(this.container, this.keys, this._isOptional)72-73- return validators74- }75-}76-77-export class VObject<T extends Schema> extends VObjectBase<T> {78- constructor(container: T, key: string) {79- super(container, key)80- }81-}82-83-export class VArray<T extends Schema> extends VObjectBase<T> {84- type: 'array' = 'array'85- constructor(container: T, key: string) {86- super(container, key)87- }88-}89-90-export 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-}115-116-type VOptions = {117- target: Target118- key: string119- type?: 'string' | 'number' | 'boolean' | 'object'120- isArray?: boolean121-}122-123-export 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- }147-148- private _nested = () => (this.baseKeys.length ? true : false)149-150- 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- }160-161- addSanitizer = (sanitizer: Sanitizer) => {162- this.sanitizers.push(sanitizer)163- return this164- }165-166- message = (text: string) => {167- const len = this.rules.length168- if (len >= 1) {169- this.rules[len - 1].customMessage = text170- }171- return this172- }173-174- isRequired = () => {175- return this.addRule('isRequired', (value: unknown) => {176- if (value !== undefined && value !== null && value !== '') return true177- return false178- })179- }180-181- isOptional = () => {182- this._optional = true183- return this.addRule('isOptional', () => true)184- }185-186- isEqual = (comparison: unknown) => {187- return this.addRule('isEqual', (value: unknown) => {188- return value === comparison189- })190- }191-192- asNumber = (): VNumber | VNumberArray => {193- const newVNumber = new VNumber({ ...this, type: 'number' })194- if (this.isArray) return newVNumber.asArray()195- return newVNumber196- }197-198- asBoolean = (): VBoolean | VBooleanArray => {199- const newVBoolean = new VBoolean({ ...this, type: 'boolean' })200- if (this.isArray) return newVBoolean.asArray()201- return newVBoolean202- }203-204- get(value: string) {205- const len = this.rules.length206- if (len > 0) {207- this.rules[this.rules.length - 1].customMessage = value208- }209- return this210- }211-212- validate = async (req: Request): Promise<ValidateResult[]> => {213- let value: Type = undefined214- let jsonData: JSONObject | undefined = undefined215-216- 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- }240-241- const results: ValidateResult[] = []242-243- let typeRule = this.rules.shift()244-245- 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- }254-255- if (typeRule) {256- const typeResult = this.validateRule(typeRule, value)257- typeResult.jsonData ||= jsonData258- results.unshift(typeResult)259- }260-261- return results262- }263-264- protected getTypeRuleName(): string {265- const prefix = 'should be'266- return this.isArray ? `${prefix} "${this.type}[]"` : `${prefix} "${this.type}"`267- }268-269- private validateRule(rule: Rule, value: Type): ValidateResult {270- let isValid: boolean = false271-272- 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- }279-280- 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- }294-295- 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- }324-325- private validateValue = (func: (value: Type) => boolean, value: Type): boolean => {326- if (this._optional && typeof value === 'undefined') return true327-328- 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- }350-351- 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-}377-378-export class VString extends VBase {379- constructor(options: VOptions) {380- super(options)381- this.type = 'string'382- }383-384- asArray = () => {385- return new VStringArray(this)386- }387-388- isEmpty = (389- options: {390- ignore_whitespace: boolean391- } = { ignore_whitespace: false }392- ) => {393- return this.addRule('isEmpty', (value) => rule.isEmpty(value as string, options))394- }395-396- isLength = (options: Partial<{ min: number; max: number }> | number, arg2?: number) => {397- return this.addRule('isLength', (value) => rule.isLength(value as string, options, arg2))398- }399-400- isAlpha = () => {401- return this.addRule('isAlpha', (value) => rule.isAlpha(value as string))402- }403-404- isNumeric = () => {405- return this.addRule('isNumeric', (value) => rule.isNumeric(value as string))406- }407-408- 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- }417-418- isIn = (options: string[]) => {419- return this.addRule('isIn', (value) => rule.isIn(value as string, options))420- }421-422- match = (regExp: RegExp) => {423- return this.addRule('match', (value) => rule.match(value as string, regExp))424- }425-426- trim = () => {427- return this.addSanitizer((value) => sanitizer.trim(value as string))428- }429-}430-431-export class VNumber extends VBase {432- constructor(options: VOptions) {433- super(options)434- this.type = 'number'435- }436-437- asArray = () => {438- return new VNumberArray(this)439- }440-441- isGte = (min: number) => {442- return this.addRule('isGte', (value) => rule.isGte(value as number, min))443- }444-445- isLte = (min: number) => {446- return this.addRule('isLte', (value) => rule.isLte(value as number, min))447- }448-}449-450-export class VBoolean extends VBase {451- constructor(options: VOptions) {452- super(options)453- this.type = 'boolean'454- }455-456- asArray = () => {457- return new VBooleanArray(this)458- }459-460- isTrue = () => {461- return this.addRule('isTrue', (value) => rule.isTrue(value as boolean))462- }463-464- isFalse = () => {465- return this.addRule('isFalse', (value) => rule.isFalse(value as boolean))466- }467-}468-469-export 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-}477-export 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-}485-export 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
1+export type Expect<T extends true> = T2+export type Equal<X, Y> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 23+ ? true4+ : false5+export type NotEqual<X, Y> = true extends Equal<X, Y> ? false : trueadded:src/validator/rule.test.ts+55 added
1+import { rule } from './rule'2+3+describe('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.js6+7+export 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+ },17+18+ 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+ },38+39+ isAlpha: (value: string): boolean => {40+ return /^[A-Z]+$/i.test(value)41+ },42+43+ isNumeric: (value: string): boolean => {44+ return /^[0-9]+$/.test(value)45+ },46+47+ 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+ },62+63+ 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+ },71+72+ match: (value: string, regExp: RegExp): boolean => {73+ return regExp.test(value)74+ },75+76+ // number77+ isGte: (value: number, min: number) => min <= value,78+ isLte: (value: number, max: number) => value <= max,79+80+ // boolean81+ isTrue: (value: boolean) => value === true,82+ isFalse: (value: boolean) => value === false,83+}added:src/validator/sanitizer.test.ts+7 added
1+import { sanitizer } from './sanitizer'2+3+describe('Sanitizers', () => {4+ test('trim', () => {5+ expect(sanitizer.trim(' abc ')).toBe('abc')6+ })7+})added:src/validator/sanitizer.ts+3 added
1+export const sanitizer = {2+ trim: (value: string) => value.trim(),3+}added:src/validator/schema.ts+54 added
1+import type {2+ VString,3+ VNumber,4+ VBoolean,5+ VObject,6+ VNumberArray,7+ VStringArray,8+ VBooleanArray,9+ VArray,10+ VObjectBase,11+} from './validator'12+13+export type Schema = {14+ [key: string]:15+ | VString16+ | VNumber17+ | VBoolean18+ | VStringArray19+ | VNumberArray20+ | VBooleanArray21+ | Schema22+ | VObject<Schema>23+ | VArray<Schema>24+}25+26+export 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
1+import { extendRequestPrototype } from '../request'2+import { Validator } from './validator'3+4+extendRequestPrototype()5+6+describe('Basic - query', () => {7+ const v = new Validator()8+9+ const req = new Request('http://localhost/?q=foo&page=3')10+11+ 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+ })20+21+ 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+ })31+32+ 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+})45+46+describe('Basic - header', () => {47+ const v = new Validator()48+49+ const req = new Request('http://localhost/', {50+ headers: {51+ 'x-message': 'hello world!',52+ 'x-number': '12345',53+ },54+ })55+56+ 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+ })66+67+ 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+})76+77+describe('Basic - body', () => {78+ const v = new Validator()79+80+ 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+ })87+88+ 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+ })98+99+ 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+})109+110+describe('Basic - JSON', () => {111+ const v = new Validator()112+113+ const post = {114+ id: 1234,115+ title: 'This is title',116+ author: {117+ name: 'Superman',118+ age: 20,119+ },120+ }121+122+ const req = new Request('http://localhost/', {123+ method: 'POST',124+ body: JSON.stringify(post),125+ })126+127+ 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+ })135+136+ 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+ })144+145+ 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+})154+155+describe('Handle required values', () => {156+ const v = new Validator()157+158+ const req = new Request('http://localhost/', {159+ method: 'POST',160+ body: JSON.stringify({ comment: null, name: 'John', admin: false }),161+ })162+163+ 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+ })169+170+ 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+ })176+177+ 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+})185+186+describe('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+})206+207+describe('Handling types error', () => {208+ const v = new Validator()209+210+ const post = {211+ id: '1234',212+ title: 'This is title',213+ published: 'true',214+ }215+216+ const req = new Request('http://localhost/', {217+ method: 'POST',218+ body: JSON.stringify(post),219+ })220+221+ 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+ })228+229+ 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+})239+240+describe('Handle array paths', () => {241+ const v = new Validator()242+243+ 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+ }270+271+ const req = new Request('http://localhost/', {272+ method: 'POST',273+ body: JSON.stringify(body),274+ })275+276+ 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+ })284+285+ 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+ })293+294+ 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+ })302+303+ 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+ })313+314+ 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+ })324+325+ 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+})332+333+describe('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+ }358+359+ const req = new Request('http://localhost/', {360+ method: 'POST',361+ body: JSON.stringify(json),362+ })363+364+ 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+ })370+371+ 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+ })377+378+ 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)383+384+ 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)388+389+ // Entire responses should be equal390+ expect(res1).toEqual(res2)391+ })392+393+ 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+ })404+405+ 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+ })411+412+ 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+ })426+427+ 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+})437+438+describe('Invalid HTTP request handling', () => {439+ const v = new Validator()440+441+ it('Should throw malformed error when JSON body absent', async () => {442+ const req = new Request('http://localhost/', {443+ method: 'POST',444+ })445+446+ 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+ })456+457+ 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+ })462+463+ 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+})474+475+describe('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+ }528+529+ const req = new Request('http://localhost/', {530+ method: 'POST',531+ body: JSON.stringify(json),532+ })533+534+ 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+ })560+561+ 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+ }))573+574+ 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+ })580+581+ 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+ }))586+587+ 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+ }595+596+ 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+ })606+607+ 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+ }))617+618+ 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+ }623+624+ const vArray2 = v625+ .array('posts', (v) => ({626+ title: v.json('title').asNumber(),627+ }))628+ .isOptional()629+630+ 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+ })639+640+ 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+ }))650+651+ 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+ })657+658+ 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+ }))663+664+ 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+ }672+673+ const vObject = v.object('pager', (v) => ({674+ prev: v.query('prev').asBoolean(),675+ next: v.body('next').asBoolean(),676+ }))677+678+ 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+ ]682+683+ 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+})690+691+describe('Custom message', () => {692+ const v = new Validator()693+694+ const json = {695+ title: 'foo',696+ post: [697+ {698+ id: 123,699+ },700+ ],701+ }702+703+ const req = new Request('http://localhost/', {704+ method: 'POST',705+ body: JSON.stringify(json),706+ })707+708+ 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+ })724+725+ 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
1+import { JSONPathCopy } from './../utils/json'2+import type { JSONObject, JSONPrimitive, JSONArray } from './../utils/json'3+import { rule } from './rule'4+import { sanitizer } from './sanitizer'5+import type { Schema } from './schema'6+7+type Target = 'query' | 'header' | 'body' | 'json'8+type Type = JSONPrimitive | JSONObject | JSONArray | File9+type RuleFunc = (value: Type) => boolean10+type Rule = {11+ name: string12+ func: RuleFunc13+ customMessage?: string14+ type: 'type' | 'value'15+}16+type Sanitizer = (value: Type) => Type17+18+export type ValidateResult = {19+ isValid: boolean20+ message: string | undefined21+ target: Target22+ key: string23+ value: Type24+ ruleName: string25+ ruleType: 'type' | 'value'26+ jsonData?: JSONObject27+}28+29+export 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+ }41+42+ isOptional() {43+ this._isOptional = true44+ return this45+ }46+47+ getValidators = (): VBase[] => {48+ const validators: VBase[] = []49+ const thisKeys: string[] = []50+ Object.assign(thisKeys, this.keys)51+52+ 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+ }70+71+ walk(this.container, this.keys, this._isOptional)72+73+ return validators74+ }75+}76+77+export class VObject<T extends Schema> extends VObjectBase<T> {78+ constructor(container: T, key: string) {79+ super(container, key)80+ }81+}82+83+export class VArray<T extends Schema> extends VObjectBase<T> {84+ type: 'array' = 'array'85+ constructor(container: T, key: string) {86+ super(container, key)87+ }88+}89+90+export 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+}115+116+type VOptions = {117+ target: Target118+ key: string119+ type?: 'string' | 'number' | 'boolean' | 'object'120+ isArray?: boolean121+}122+123+export 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+ }147+148+ private _nested = () => (this.baseKeys.length ? true : false)149+150+ 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+ }160+161+ addSanitizer = (sanitizer: Sanitizer) => {162+ this.sanitizers.push(sanitizer)163+ return this164+ }165+166+ message = (text: string) => {167+ const len = this.rules.length168+ if (len >= 1) {169+ this.rules[len - 1].customMessage = text170+ }171+ return this172+ }173+174+ isRequired = () => {175+ return this.addRule('isRequired', (value: unknown) => {176+ if (value !== undefined && value !== null && value !== '') return true177+ return false178+ })179+ }180+181+ isOptional = () => {182+ this._optional = true183+ return this.addRule('isOptional', () => true)184+ }185+186+ isEqual = (comparison: unknown) => {187+ return this.addRule('isEqual', (value: unknown) => {188+ return value === comparison189+ })190+ }191+192+ asNumber = (): VNumber | VNumberArray => {193+ const newVNumber = new VNumber({ ...this, type: 'number' })194+ if (this.isArray) return newVNumber.asArray()195+ return newVNumber196+ }197+198+ asBoolean = (): VBoolean | VBooleanArray => {199+ const newVBoolean = new VBoolean({ ...this, type: 'boolean' })200+ if (this.isArray) return newVBoolean.asArray()201+ return newVBoolean202+ }203+204+ get(value: string) {205+ const len = this.rules.length206+ if (len > 0) {207+ this.rules[this.rules.length - 1].customMessage = value208+ }209+ return this210+ }211+212+ validate = async <R extends Request>(req: R): Promise<ValidateResult[]> => {213+ let value: Type = undefined214+ let jsonData: JSONObject | undefined = undefined215+216+ 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+ }240+241+ const results: ValidateResult[] = []242+243+ let typeRule = this.rules.shift()244+245+ 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+ }254+255+ if (typeRule) {256+ const typeResult = this.validateRule(typeRule, value)257+ typeResult.jsonData ||= jsonData258+ results.unshift(typeResult)259+ }260+261+ return results262+ }263+264+ protected getTypeRuleName(): string {265+ const prefix = 'should be'266+ return this.isArray ? `${prefix} "${this.type}[]"` : `${prefix} "${this.type}"`267+ }268+269+ private validateRule(rule: Rule, value: Type): ValidateResult {270+ let isValid: boolean = false271+272+ 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+ }279+280+ 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+ }294+295+ 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+ }324+325+ private validateValue = (func: (value: Type) => boolean, value: Type): boolean => {326+ if (this._optional && typeof value === 'undefined') return true327+328+ 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+ }350+351+ 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+}377+378+export class VString extends VBase {379+ constructor(options: VOptions) {380+ super(options)381+ this.type = 'string'382+ }383+384+ asArray = () => {385+ return new VStringArray(this)386+ }387+388+ isEmpty = (389+ options: {390+ ignore_whitespace: boolean391+ } = { ignore_whitespace: false }392+ ) => {393+ return this.addRule('isEmpty', (value) => rule.isEmpty(value as string, options))394+ }395+396+ isLength = (options: Partial<{ min: number; max: number }> | number, arg2?: number) => {397+ return this.addRule('isLength', (value) => rule.isLength(value as string, options, arg2))398+ }399+400+ isAlpha = () => {401+ return this.addRule('isAlpha', (value) => rule.isAlpha(value as string))402+ }403+404+ isNumeric = () => {405+ return this.addRule('isNumeric', (value) => rule.isNumeric(value as string))406+ }407+408+ 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+ }417+418+ isIn = (options: string[]) => {419+ return this.addRule('isIn', (value) => rule.isIn(value as string, options))420+ }421+422+ match = (regExp: RegExp) => {423+ return this.addRule('match', (value) => rule.match(value as string, regExp))424+ }425+426+ trim = () => {427+ return this.addSanitizer((value) => sanitizer.trim(value as string))428+ }429+}430+431+export class VNumber extends VBase {432+ constructor(options: VOptions) {433+ super(options)434+ this.type = 'number'435+ }436+437+ asArray = () => {438+ return new VNumberArray(this)439+ }440+441+ isGte = (min: number) => {442+ return this.addRule('isGte', (value) => rule.isGte(value as number, min))443+ }444+445+ isLte = (min: number) => {446+ return this.addRule('isLte', (value) => rule.isLte(value as number, min))447+ }448+}449+450+export class VBoolean extends VBase {451+ constructor(options: VOptions) {452+ super(options)453+ this.type = 'boolean'454+ }455+456+ asArray = () => {457+ return new VBooleanArray(this)458+ }459+460+ isTrue = () => {461+ return this.addRule('isTrue', (value) => rule.isTrue(value as boolean))462+ }463+464+ isFalse = () => {465+ return this.addRule('isFalse', (value) => rule.isFalse(value as boolean))466+ }467+}468+469+export 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+}477+export 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+}485+export 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
1 import { HonoContext } from './context'2 import type { Environment, NotFoundHandler, ErrorHandler } from './hono'3+import type { Schema } from './validator/schema'4 5 interface ComposeContext {6 finalized: boolean6- res: any7+ res: unknown8 }9 10 // Based on the code in the MIT licensed `koa-compose` package.10-export const compose = <C extends ComposeContext, E extends Partial<Environment> = Environment>(11+export 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 = -159 unmodified linesmodified:src/context.ts+21 added-26 removed
1-import type {2- Environment,3- NotFoundHandler,4- ContextVariableMap,5- Bindings,6- ValidatedData,7-} from './hono'1+import type { Environment, NotFoundHandler, ContextVariableMap, Bindings } from './hono'2 import type { CookieOptions } from './utils/cookie'3 import { serialize } from './utils/cookie'4 import type { StatusCode } from './utils/http-status'5+import type { Schema, SchemaToProp } from './validator/schema'6 7 type HeaderField = [string, string]8 type Headers = Record<string, string | string[]>9 export type Data = string | ArrayBuffer | ReadableStream10 11 export 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: boolean5 unmodified lines26 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 lines45 notFound: () => Response | Promise<Response>46 }47 48 export 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 = undefined58 59 _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>67 68 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)77 78 this.notFoundHandler = notFoundHandler79 this.finalized = false56 unmodified lines136 }137 138 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 }145 146 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 lines227 this.header('set-cookie', cookie, { append: true })228 }229 230 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 */2 import type { Context } from './context'2-import type { Next } from './hono'3+import type { Handler, Next } from './hono'4 import { Hono } from './hono'5 import { logger } from './middleware/logger'6 import { poweredBy } from './middleware/powered-by'7+import type { Expect, Equal } from './utils/types'8 9 describe('GET Request', () => {10 const app = new Hono()11 1126 unmodified lines1138 expect(count).toBe(4)1139 expect(log).toMatch(/404/)1140 })1141 })1142+1143+describe('Context set/get variables', () => {1144+ type Variables = {1145+ id: number1146+ title: string1147+ }1148+1149+ const app = new Hono<{ Variables: Variables }>()1150+1151+ 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+})1169+1170+describe('Context binding variables', () => {1171+ type Bindings = {1172+ USER_ID: number1173+ USER_NAME: string1174+ }1175+1176+ const app = new Hono<{ Bindings: Bindings }>()1177+1178+ 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+})1188+1189+describe('Handler as variables', () => {1190+ const app = new Hono()1191+1192+ 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)1198+1199+ 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 lines9 import { SmartRouter } from './router/smart-router'10 import { StaticRouter } from './router/static-router'11 import { TrieRouter } from './router/trie-router'12 import { getPathFromURL, mergePath } from './utils/url'13+import type { Schema } from './validator/schema'14 15 export interface ContextVariableMap {}16 17 export type Bindings = Record<string, any> // For Cloudflare Workers2 unmodified lines20 Bindings: Bindings21 Variables: Variables22 }23 23-export type ValidatedData = Record<string, any> // For validated data24-24 export 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>29 34-export type MiddlewareHandler = <E extends Partial<Environment> = Environment>(35- c: Context<string, E>,36- next: Next37-) => Promise<void> | Promise<Response | undefined>30+export 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>35 39-export type NotFoundHandler<E extends Partial<Environment> = Environment> = (40- c: Context<string, E>41-) => Response | Promise<Response>36+export 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>41 43-export type ErrorHandler<E extends Partial<Environment> = Environment> = (44- err: Error,45- c: Context<string, E>46-) => Response42+export 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>) => Response47 48 export type Next = () => Promise<void>49 50 // eslint-disable-next-line @typescript-eslint/no-unused-vars8 unmodified lines59 type ParamKeys<Path> = Path extends `${infer Component}/${infer Rest}`60 ? ParamKey<Component> | ParamKeys<Rest>61 : ParamKey<Path>62 63-interface HandlerInterface<T extends string, E extends Partial<Environment>, U = Hono<E, T>> {63+interface 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>[]): U74+75 // 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 }83 84 type Methods = typeof METHODS[number] | typeof METHOD_NAME_ALL_LOWERCASE85 86 function 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 }98 99 interface 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 }108 109 export 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 = '/'120 108- routes: Route<E, D>[] = []121+ routes: Route<P, E, S>[] = []122 123 constructor(init: Partial<Pick<Hono, 'router' | 'strict'>> = {}) {124 super()125 126 extendRequestPrototype()127 128 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 line147 148 Object.assign(this, init)149 }150 138- 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 }154 142- 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 }160 148- 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 }156-169 return this170 }171 160- 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 lines187 })188 return this189 }190 179- onError(handler: ErrorHandler<E>): Hono<E, P, D> {191+ onError(handler: ErrorHandler<P, E, S>) {192 this.errorHandler = handler193 return this194 }195 184- notFound(handler: NotFoundHandler<E>): Hono<E, P, D> {196+ notFound(handler: NotFoundHandler<P, E, S>) {197 this.notFoundHandler = handler198 return this199 }200 189- 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 }210 211 private matchRoute(method: string, path: string) {212 return this.router.match(method, path)213 }214 203- 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 err9 unmodified lines229 230 const result = this.matchRoute(method, path)231 request.paramData = result?.params232 221- 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)234 235 // 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>>239 240 try {241 res = handler(c, async () => {})242 if (!res) return this.notFoundHandler(c)17 unmodified lines260 })()261 }262 263 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 linesmodified:src/request.ts+6 added-5 removed
34 unmodified lines35 (): 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 lines132 }133 return body134 } as InstanceType<typeof Request>['parseBody']135 135- 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 line144 }145 return jsonData146 } as InstanceType<typeof Request>['jsonData']147 147- 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 linesmodified:tsconfig.build.cjs.json+2 added
3 unmodified lines4 "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 linesmodified:tsconfig.build.json+2 added
2 unmodified lines3 "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 linesmodified:tsconfig.json+2 added-2 removed
8 unmodified lines9 "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