Skip to content
Myr

index.ts

This file

Path

src/middleware/serve-static/index.ts

135 lines · 4.0 KiB · TypeScript

Last changed by

landed by oscabriel588ec13

History of this file

Take it

The walk stopped after 200 commits: lines older than f0b094d point at it.

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 1–16why, one step back
1/**
2 * @module3 * Serve Static Middleware for Hono.4 */56import type { Context, Data } from '../../context'7import type { Env, MiddlewareHandler } from '../../types'8import { COMPRESSIBLE_CONTENT_TYPE_REGEX } from '../../utils/compress'9import { getMimeType } from '../../utils/mime'10import { tryDecodeURI } from '../../utils/url'11import { defaultJoin } from './path'1213export type ServeStaticOptions<E extends Env = Env> = {14 root?: string15 path?: string16 precompressed?: boolean

Merge commit from forkTaku Amanobefore adoption8b05c77

lines 17–18why, one step back
17 /** Allow percent signs in the routed request path. Defaults to false. */
18 allowPercentInPath?: boolean

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 19–61why, one step back
19 mimes?: Record<string, string>
20 rewriteRequestPath?: (path: string) => string21 onFound?: (path: string, c: Context<E>) => void | Promise<void>22 onNotFound?: (path: string, c: Context<E>) => void | Promise<void>23}2425const ENCODINGS = {26 br: '.br',27 zstd: '.zst',28 gzip: '.gz',29} as const30const ENCODINGS_ORDERED_KEYS = Object.keys(ENCODINGS) as (keyof typeof ENCODINGS)[]3132const DEFAULT_DOCUMENT = 'index.html'3334/**35 * This middleware is not directly used by the user. Create a wrapper specifying `getContent()` by the environment such as Deno or Bun.36 */37export const serveStatic = <E extends Env = Env>(38 options: ServeStaticOptions<E> & {39 getContent: (path: string, c: Context<E>) => Promise<Data | Response | null>40 /**41 *42 * `join` option according to the runtime. Example `import { join } from 'node:path`. If not specified, it will fall back to the default join function.`43 */44 join?: (...paths: string[]) => string45 /**46 * @deprecated Currently, `pathResolve` is no longer used.47 */48 pathResolve?: (path: string) => string49 isDir?: (path: string) => boolean | undefined | Promise<boolean | undefined>50 }51): MiddlewareHandler => {52 const root = options.root ?? './'53 const optionPath = options.path54 const join = options.join ?? defaultJoin5556 return async (c, next) => {57 // Do nothing if Response is already set58 if (c.finalized) {59 return next()60 }6162 if (c.req.method !== 'GET' && c.req.method !== 'HEAD') {63 return next()64 }65

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 66–71why, one step back
66 let filename: string
6768 if (options.path) {69 filename = options.path70 } else {71 try {

Merge commit from forkTaku Amanobefore adoption8b05c77

lines 72–74why, one step back
72 if (!options.allowPercentInPath && c.req.path.includes('%')) {
73 throw new Error()74 }

Merge commit from forkYusuke Wadabefore adoptionf0b094d

line 75why, one step back
75 filename = tryDecodeURI(c.req.path)

Merge commit from forkYusuke Wadabefore adoption751ba41

line 76why, one step back
76 if (/(?:^|[\/\\])\.{1,2}(?:$|[\/\\])|[\/\\]{2,}|\\/.test(filename)) {

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 77–100why, one step back
77 throw new Error()
78 }79 } catch {80 await options.onNotFound?.(c.req.path, c)81 return next()82 }83 }8485 let path = join(86 root,87 !optionPath && options.rewriteRequestPath ? options.rewriteRequestPath(filename) : filename88 )8990 if (options.isDir && (await options.isDir(path))) {91 path = join(path, DEFAULT_DOCUMENT)92 }9394 const getContent = options.getContent95 let content = await getContent(path, c)9697 if (content instanceof Response) {98 return c.newResponse(content.body, content)99 }100

fix(serve-static): treat empty string content as found (#5062)Yusuke Wadabefore adoption03a9416

line 101why, one step back
101 if (content != null) {

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 102–135why, one step back
102 const mimeType = (options.mimes && getMimeType(path, options.mimes)) || getMimeType(path)
103 c.header('Content-Type', mimeType || 'application/octet-stream')104105 if (options.precompressed && (!mimeType || COMPRESSIBLE_CONTENT_TYPE_REGEX.test(mimeType))) {106 const acceptEncodingSet = new Set(107 c.req108 .header('Accept-Encoding')109 ?.split(',')110 .map((encoding) => encoding.trim())111 )112113 for (const encoding of ENCODINGS_ORDERED_KEYS) {114 if (!acceptEncodingSet.has(encoding)) {115 continue116 }117 const compressedContent = (await getContent(path + ENCODINGS[encoding], c)) as Data | null118119 if (compressedContent) {120 content = compressedContent121 c.header('Content-Encoding', encoding)122 c.header('Vary', 'Accept-Encoding', { append: true })123 break124 }125 }126 }127 await options.onFound?.(path, c)128 return c.body(content)129 }130131 await options.onNotFound?.(path, c)132 await next()133 return134 }135}