fix(types): add types to middleware correctly (#521)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Yusuke Wada · committed by GitHub · parent d12a119 · Browse files · 29 files·+105 added−104 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
29 files+105 added−104 removed
- other:+105 added−104 removed
Provenance
- Commit
e2d704f- Tree
60fa0f4- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
d12a119
29 files changed+105 added−104 removed
modified:deno_dist/deno/serve-static.ts+3 added-4 removed
12123452 unmodified lines891011131412131415161725 unmodified linesimport type { Context } from '../context.ts'import type { Next } from '../hono.ts'import type { MiddlewareHandler } from '../hono.ts'import { getFilePath } from '../utils/filepath.ts'import { getMimeType } from '../utils/mime.ts'
export type ServeStaticOptions = {2 unmodified lines}
const DEFAULT_DOCUMENT = 'index.html'
export const serveStatic = (options: ServeStaticOptions = { root: '' }) => { return async (c: Context, next: Next): Promise<Response | undefined> => {export const serveStatic = (options: ServeStaticOptions = { root: '' }): MiddlewareHandler => { return async (c, next): Promise<Response | undefined> => { // Do nothing if Response is already set if (c.finalized) { await next() }25 unmodified linesmodified:deno_dist/middleware/basic-auth/index.ts+3 added-4 removed
121234516 unmodified lines22232425272627282930313233343537363738394024 unmodified linesimport type { Context } from '../../context.ts'import type { Next } from '../../hono.ts'import type { MiddlewareHandler } from '../../hono.ts'import { timingSafeEqual } from '../../utils/buffer.ts'import { decodeBase64 } from '../../utils/encode.ts'
const CREDENTIALS_REGEXP = /^ *(?:[Bb][Aa][Ss][Ii][Cc]) +([A-Za-z0-9._~+/-]+=*) *$/16 unmodified lines
export const basicAuth = ( options: { username: string; password: string; realm?: string; hashFunction?: Function }, ...users: { username: string; password: string }[]) => {): MiddlewareHandler => { if (!options) { throw new Error('basic auth middleware requires options for "username and password"') }
if (!options.realm) { options.realm = 'Secure Area' } users.unshift({ username: options.username, password: options.password })
return async (ctx: Context, next: Next) => { return async (ctx, next) => { const requestUser = auth(ctx.req) if (requestUser) { for (const user of users) { const usernameEqual = await timingSafeEqual(24 unmodified linesmodified:deno_dist/middleware/bearer-auth/index.ts+3 added-4 removed
12123452 unmodified lines8910111312131415164 unmodified lines2122232426252627282933 unmodified linesimport type { Context } from '../../context.ts'import type { Next } from '../../hono.ts'import type { MiddlewareHandler } from '../../hono.ts'import { timingSafeEqual } from '../../utils/buffer.ts'
const TOKEN_STRINGS = '[A-Za-z0-9._~+/-]+=*'const PREFIX = 'Bearer'2 unmodified lines token: string realm?: string prefix?: string hashFunction?: Function}) => {}): MiddlewareHandler => { if (!options.token) { throw new Error('bearer auth middleware requires options for "token"') } if (!options.realm) {4 unmodified lines }
const realm = options.realm?.replace(/"/g, '\\"')
return async (c: Context, next: Next) => { return async (c, next) => { const headerToken = c.req.headers.get('Authorization')
if (!headerToken) { // No Authorization header33 unmodified linesmodified:deno_dist/middleware/cache/index.ts+7 added-4 removed
1-import type { Context } from '../../context.ts'2-import type { Next } from '../../hono.ts'1+import type { MiddlewareHandler } from '../../hono.ts'2 4-export const cache = (options: { cacheName: string; wait?: boolean; cacheControl?: string }) => {3+export const cache = (options: {4+ cacheName: string5+ wait?: boolean6+ cacheControl?: string7+}): MiddlewareHandler => {8 if (options.wait === undefined) {9 options.wait = false10 }11 12 const addHeader = (response: Response) => {13 if (options.cacheControl) response.headers.append('Cache-Control', options.cacheControl)14 }15 13- return async (c: Context, next: Next) => {16+ return async (c, next) => {17 const key = c.req18 const cache = await caches.open(options.cacheName)19 const response = await cache.match(key)20 if (!response) {13 unmodified linesmodified:deno_dist/middleware/compress/index.ts+3 added-4 removed
12123456781011910111213149 unmodified linesimport type { Context } from '../../context.ts'import type { Next } from '../../hono.ts'import type { MiddlewareHandler } from '../../hono.ts'
type EncodingType = 'gzip' | 'deflate'
interface CompressionOptions { encoding?: EncodingType}
export const compress = (options?: CompressionOptions) => { return async (ctx: Context, next: Next) => {export const compress = (options?: CompressionOptions): MiddlewareHandler => { return async (ctx, next) => { await next() const accepted = ctx.req.headers.get('Accept-Encoding') const pattern = options?.encoding ?? /gzip|deflate/ const match = accepted?.match(pattern)9 unmodified linesmodified:deno_dist/middleware/cors/index.ts+3 added-4 removed
1-import type { Context } from '../../context.ts'2-import type { Next } from '../../hono.ts'1+import type { MiddlewareHandler } from '../../hono.ts'2 3 type CORSOptions = {4 origin: string5 allowMethods?: string[]2 unmodified lines8 credentials?: boolean9 exposeHeaders?: string[]10 }11 13-export const cors = (options?: CORSOptions) => {12+export const cors = (options?: CORSOptions): MiddlewareHandler => {13 const defaults: CORSOptions = {14 origin: '*',15 allowMethods: ['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH'],16 allowHeaders: [],3 unmodified lines20 ...defaults,21 ...options,22 }23 25- return async (c: Context, next: Next) => {24+ return async (c, next) => {25 await next()26 27 function set(key: string, value: string) {28 c.res.headers.append(key, value)52 unmodified linesmodified:deno_dist/middleware/etag/index.ts+3 added-4 removed
1-import type { Context } from '../../context.ts'2-import type { Next } from '../../hono.ts'1+import type { MiddlewareHandler } from '../../hono.ts'2 import { sha1 } from '../../utils/crypto.ts'3 4 type ETagOptions = {5 weak: boolean6 }7 9-export const etag = (options: ETagOptions = { weak: false }) => {10- return async (c: Context, next: Next) => {8+export const etag = (options: ETagOptions = { weak: false }): MiddlewareHandler => {9+ return async (c, next) => {10 const ifNoneMatch = c.req.header('If-None-Match') || c.req.header('if-none-match')11 12 await next()13 19 unmodified linesmodified:deno_dist/middleware/jwt/index.ts+7 added-4 removed
1-import type { Context } from '../../context.ts'2-import type { Next } from '../../hono.ts'1+import type { MiddlewareHandler } from '../../hono.ts'2 import { Jwt } from '../../utils/jwt/index.ts'3 import type { AlgorithmTypes } from '../../utils/jwt/types.ts'4 6-export const jwt = (options: { secret: string; cookie?: string; alg?: string }) => {5+export const jwt = (options: {6+ secret: string7+ cookie?: string8+ alg?: string9+}): MiddlewareHandler => {10 if (!options) {11 throw new Error('JWT auth middleware requires options for "secret')12 }13 14 if (!crypto.subtle || !crypto.subtle.importKey) {15 throw new Error('`crypto.subtle.importKey` is undefined. JWT auth middleware requires it.')16 }17 15- return async (ctx: Context, next: Next) => {18+ return async (ctx, next) => {19 const credentials = ctx.req.headers.get('Authorization')20 let token21 if (credentials) {22 const parts = credentials.split(/\s+/)46 unmodified linesmodified:deno_dist/middleware/logger/index.ts+3 added-4 removed
1-import type { Context } from '../../context.ts'2-import type { Next } from '../../hono.ts'1+import type { MiddlewareHandler } from '../../hono.ts'2 import { getPathFromURL } from '../../utils/url.ts'3 4 enum LogPrefix {5 Outgoing = '-->',46 unmodified lines52 : ` ${prefix} ${method} ${path} ${colorStatus(status)} ${elapsed}`53 fn(out)54 }55 57-export const logger = (fn: PrintFunc = console.log) => {58- return async (c: Context, next: Next) => {56+export const logger = (fn: PrintFunc = console.log): MiddlewareHandler => {57+ return async (c, next) => {58 const { method } = c.req59 const path = getPathFromURL(c.req.url)60 61 log(fn, LogPrefix.Incoming, method, path)8 unmodified linesmodified:deno_dist/middleware/powered-by/index.ts+3 added-4 removed
1-import type { Context } from '../../context.ts'2-import type { Next } from '../../hono.ts'1+import type { MiddlewareHandler } from '../../hono.ts'2 4-export const poweredBy = () => {5- return async (c: Context, next: Next) => {3+export const poweredBy = (): MiddlewareHandler => {4+ return async (c, next) => {5 await next()6 c.res.headers.append('X-Powered-By', 'Hono')7 }8 }modified:deno_dist/middleware/pretty-json/index.ts+3 added-4 removed
1-import type { Context } from '../../context.ts'2-import type { Next } from '../../hono.ts'1+import type { MiddlewareHandler } from '../../hono.ts'2 3 type prettyOptions = {4 space: number5 }6 8-export const prettyJSON = (options: prettyOptions = { space: 2 }) => {9- return async (c: Context, next: Next) => {7+export const prettyJSON = (options: prettyOptions = { space: 2 }): MiddlewareHandler => {8+ return async (c, next) => {9 const pretty = c.req.query('pretty') || c.req.query('pretty') === '' ? true : false10 c.pretty(pretty, options.space)11 await next()12 }1 unmodified linemodified:deno_dist/middleware/serve-static/serve-static.ts+3 added-4 removed
1-import type { Context } from '../../context.ts'2-import type { Next } from '../../hono.ts'1+import type { MiddlewareHandler } from '../../hono.ts'2 import { getContentFromKVAsset } from '../../utils/cloudflare.ts'3 import { getFilePath } from '../../utils/filepath.ts'4 import { getMimeType } from '../../utils/mime.ts'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): Promise<Response | undefined> => {16+export const serveStatic = (options: ServeStaticOptions = { root: '' }): MiddlewareHandler => {17+ return async (c, next): Promise<Response | undefined> => {18 // Do nothing if Response is already set19 if (c.finalized) {20 await next()21 }27 unmodified linesmodified:deno_dist/middleware/validator/middleware.ts+2 added-2 removed
1 import type { Context } from '../../context.ts'2-import type { Handler } from '../../hono.ts'2+import type { MiddlewareHandler } from '../../hono.ts'3 import { JSONPathCopy } from '../../utils/json.ts'4 5 type Param =6 | string46 unmodified lines53 validator: Validator,54 message: (value: string) => ValidatorMessage,55 context: Context56 ) => Partial<RuleSet>57- ): Handler => {57+ ): MiddlewareHandler => {58 return async (c, next) => {59 const validations = validatorFunction(validator, message, c)60 61 const result: ResultSet = {153 unmodified linesmodified:deno_dist/hono.ts+5 added
26 unmodified lines27 c: Context<RequestParamKeyType, E>,28 next: Next29 ) => Response | Promise<Response> | Promise<void> | Promise<Response | undefined>30 31+export type MiddlewareHandler = <E extends Partial<Environment> = Environment>(32+ c: Context<string, E>,33+ next: Next34+) => Promise<void> | Promise<Response | undefined>35+36 export type NotFoundHandler<E extends Partial<Environment> = Environment> = (37 c: Context<string, E>38 ) => Response | Promise<Response>39 229 unmodified linesmodified:src/deno/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 { getFilePath } from '../utils/filepath'3 import { getMimeType } from '../utils/mime'4 5 export type ServeStaticOptions = {2 unmodified lines8 }9 10 const DEFAULT_DOCUMENT = 'index.html'11 13-export const serveStatic = (options: ServeStaticOptions = { root: '' }) => {14- return async (c: Context, next: Next): Promise<Response | undefined> => {12+export const serveStatic = (options: ServeStaticOptions = { root: '' }): MiddlewareHandler => {13+ return async (c, next): Promise<Response | undefined> => {14 // Do nothing if Response is already set15 if (c.finalized) {16 await next()17 }25 unmodified linesmodified:src/middleware/basic-auth/index.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 { timingSafeEqual } from '../../utils/buffer'3 import { decodeBase64 } from '../../utils/encode'4 5 const CREDENTIALS_REGEXP = /^ *(?:[Bb][Aa][Ss][Ii][Cc]) +([A-Za-z0-9._~+/-]+=*) *$/16 unmodified lines22 23 export const basicAuth = (24 options: { username: string; password: string; realm?: string; hashFunction?: Function },25 ...users: { username: string; password: string }[]27-) => {26+): MiddlewareHandler => {27 if (!options) {28 throw new Error('basic auth middleware requires options for "username and password"')29 }30 1 unmodified line32 options.realm = 'Secure Area'33 }34 users.unshift({ username: options.username, password: options.password })35 37- return async (ctx: Context, next: Next) => {36+ return async (ctx, next) => {37 const requestUser = auth(ctx.req)38 if (requestUser) {39 for (const user of users) {40 const usernameEqual = await timingSafeEqual(24 unmodified linesmodified:src/middleware/bearer-auth/index.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 { timingSafeEqual } from '../../utils/buffer'3 4 const TOKEN_STRINGS = '[A-Za-z0-9._~+/-]+=*'5 const PREFIX = 'Bearer'2 unmodified lines8 token: string9 realm?: string10 prefix?: string11 hashFunction?: Function13-}) => {12+}): MiddlewareHandler => {13 if (!options.token) {14 throw new Error('bearer auth middleware requires options for "token"')15 }16 if (!options.realm) {4 unmodified lines21 }22 23 const realm = options.realm?.replace(/"/g, '\\"')24 26- return async (c: Context, next: Next) => {25+ return async (c, next) => {26 const headerToken = c.req.headers.get('Authorization')27 28 if (!headerToken) {29 // No Authorization header33 unmodified linesmodified:src/middleware/cache/index.ts+7 added-4 removed
1-import type { Context } from '../../context'2-import type { Next } from '../../hono'1+import type { MiddlewareHandler } from '../../hono'2 4-export const cache = (options: { cacheName: string; wait?: boolean; cacheControl?: string }) => {3+export const cache = (options: {4+ cacheName: string5+ wait?: boolean6+ cacheControl?: string7+}): MiddlewareHandler => {8 if (options.wait === undefined) {9 options.wait = false10 }11 12 const addHeader = (response: Response) => {13 if (options.cacheControl) response.headers.append('Cache-Control', options.cacheControl)14 }15 13- return async (c: Context, next: Next) => {16+ return async (c, next) => {17 const key = c.req18 const cache = await caches.open(options.cacheName)19 const response = await cache.match(key)20 if (!response) {13 unmodified linesmodified:src/middleware/compress/index.ts+3 added-4 removed
1-import type { Context } from '../../context'2-import type { Next } from '../../hono'1+import type { MiddlewareHandler } from '../../hono'2 3 type EncodingType = 'gzip' | 'deflate'4 5 interface CompressionOptions {6 encoding?: EncodingType7 }8 10-export const compress = (options?: CompressionOptions) => {11- return async (ctx: Context, next: Next) => {9+export const compress = (options?: CompressionOptions): MiddlewareHandler => {10+ return async (ctx, next) => {11 await next()12 const accepted = ctx.req.headers.get('Accept-Encoding')13 const pattern = options?.encoding ?? /gzip|deflate/14 const match = accepted?.match(pattern)9 unmodified linesmodified:src/middleware/cors/index.ts+3 added-4 removed
1-import type { Context } from '../../context'2-import type { Next } from '../../hono'1+import type { MiddlewareHandler } from '../../hono'2 3 type CORSOptions = {4 origin: string5 allowMethods?: string[]2 unmodified lines8 credentials?: boolean9 exposeHeaders?: string[]10 }11 13-export const cors = (options?: CORSOptions) => {12+export const cors = (options?: CORSOptions): MiddlewareHandler => {13 const defaults: CORSOptions = {14 origin: '*',15 allowMethods: ['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH'],16 allowHeaders: [],3 unmodified lines20 ...defaults,21 ...options,22 }23 25- return async (c: Context, next: Next) => {24+ return async (c, next) => {25 await next()26 27 function set(key: string, value: string) {28 c.res.headers.append(key, value)52 unmodified linesmodified:src/middleware/etag/index.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 { sha1 } from '../../utils/crypto'3 4 type ETagOptions = {5 weak: boolean6 }7 9-export const etag = (options: ETagOptions = { weak: false }) => {10- return async (c: Context, next: Next) => {8+export const etag = (options: ETagOptions = { weak: false }): MiddlewareHandler => {9+ return async (c, next) => {10 const ifNoneMatch = c.req.header('If-None-Match') || c.req.header('if-none-match')11 12 await next()13 19 unmodified linesmodified:src/middleware/jwt/index.ts+7 added-4 removed
1-import type { Context } from '../../context'2-import type { Next } from '../../hono'1+import type { MiddlewareHandler } from '../../hono'2 import { Jwt } from '../../utils/jwt'3 import type { AlgorithmTypes } from '../../utils/jwt/types'4 6-export const jwt = (options: { secret: string; cookie?: string; alg?: string }) => {5+export const jwt = (options: {6+ secret: string7+ cookie?: string8+ alg?: string9+}): MiddlewareHandler => {10 if (!options) {11 throw new Error('JWT auth middleware requires options for "secret')12 }13 14 if (!crypto.subtle || !crypto.subtle.importKey) {15 throw new Error('`crypto.subtle.importKey` is undefined. JWT auth middleware requires it.')16 }17 15- return async (ctx: Context, next: Next) => {18+ return async (ctx, next) => {19 const credentials = ctx.req.headers.get('Authorization')20 let token21 if (credentials) {22 const parts = credentials.split(/\s+/)46 unmodified linesmodified:src/middleware/logger/index.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 { getPathFromURL } from '../../utils/url'3 4 enum LogPrefix {5 Outgoing = '-->',46 unmodified lines52 : ` ${prefix} ${method} ${path} ${colorStatus(status)} ${elapsed}`53 fn(out)54 }55 57-export const logger = (fn: PrintFunc = console.log) => {58- return async (c: Context, next: Next) => {56+export const logger = (fn: PrintFunc = console.log): MiddlewareHandler => {57+ return async (c, next) => {58 const { method } = c.req59 const path = getPathFromURL(c.req.url)60 61 log(fn, LogPrefix.Incoming, method, path)8 unmodified linesmodified:src/middleware/powered-by/index.ts+3 added-4 removed
1-import type { Context } from '../../context'2-import type { Next } from '../../hono'1+import type { MiddlewareHandler } from '../../hono'2 4-export const poweredBy = () => {5- return async (c: Context, next: Next) => {3+export const poweredBy = (): MiddlewareHandler => {4+ return async (c, next) => {5 await next()6 c.res.headers.append('X-Powered-By', 'Hono')7 }8 }modified:src/middleware/pretty-json/index.ts+3 added-4 removed
1-import type { Context } from '../../context'2-import type { Next } from '../../hono'1+import type { MiddlewareHandler } from '../../hono'2 3 type prettyOptions = {4 space: number5 }6 8-export const prettyJSON = (options: prettyOptions = { space: 2 }) => {9- return async (c: Context, next: Next) => {7+export const prettyJSON = (options: prettyOptions = { space: 2 }): MiddlewareHandler => {8+ return async (c, next) => {9 const pretty = c.req.query('pretty') || c.req.query('pretty') === '' ? true : false10 c.pretty(pretty, options.space)11 await next()12 }1 unmodified linemodified:src/middleware/serve-static/bun.ts+3 added-4 removed
1 // @denoify-ignore2 /* eslint-disable @typescript-eslint/ban-ts-comment */3-import type { Context } from '../../context'4-import type { Next } from '../../hono'3+import type { MiddlewareHandler } from '../../hono'4 import { getFilePath } from '../../utils/filepath'5 import { getMimeType } from '../../utils/mime'6 7 // @ts-ignore5 unmodified lines13 }14 15 const DEFAULT_DOCUMENT = 'index.html'16 18-export const serveStatic = (options: ServeStaticOptions = { root: '' }) => {19- return async (c: Context, next: Next): Promise<Response | undefined> => {17+export const serveStatic = (options: ServeStaticOptions = { root: '' }): MiddlewareHandler => {18+ return async (c, next): Promise<Response | undefined> => {19 // Do nothing if Response is already set20 if (c.res && c.finalized) {21 await next()22 }25 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): Promise<Response | undefined> => {16+export const serveStatic = (options: ServeStaticOptions = { root: '' }): MiddlewareHandler => {17+ return async (c, next): Promise<Response | undefined> => {18 // Do nothing if Response is already set19 if (c.finalized) {20 await next()21 }27 unmodified linesmodified:src/middleware/validator/middleware.ts+2 added-2 removed
1 import type { Context } from '../../context'2-import type { Handler } from '../../hono'2+import type { MiddlewareHandler } from '../../hono'3 import { JSONPathCopy } from '../../utils/json'4 5 type Param =6 | string46 unmodified lines53 validator: Validator,54 message: (value: string) => ValidatorMessage,55 context: Context56 ) => Partial<RuleSet>57- ): Handler => {57+ ): MiddlewareHandler => {58 return async (c, next) => {59 const validations = validatorFunction(validator, message, c)60 61 const result: ResultSet = {153 unmodified linesmodified:src/hono.ts+5 added
26 unmodified lines27 c: Context<RequestParamKeyType, E>,28 next: Next29 ) => Response | Promise<Response> | Promise<void> | Promise<Response | undefined>30 31+export type MiddlewareHandler = <E extends Partial<Environment> = Environment>(32+ c: Context<string, E>,33+ next: Next34+) => Promise<void> | Promise<Response | undefined>35+36 export type NotFoundHandler<E extends Partial<Environment> = Environment> = (37 c: Context<string, E>38 ) => Response | Promise<Response>39 229 unmodified lines