0
0
mirror of https://github.com/honojs/hono.git synced 2024-11-29 17:46:30 +01:00
hono/deno_dist/middleware/cors/index.ts
Taku Amano bd36ad10fc
feat(helper/dev): Introduce inspectRoutes() and showRoutes() (#1716)
* feat(dev): Introduce "dev" helper

* feat(dev): Expose "dev" helper

* refactor: Use "named function" in some middleware.

* feat: `app.showRoutes()` is now deprecated. Use `showRoutes()` in `helper` instead.

* refactor: export RouterRoute interface for utility

* refactor: remove captureRouteStackTrace, add inspectRoutes

`captureRouteStackTrace` will be implemented after some more thought.
Instead, I added `inspectRoutes` to get routes as data.

* test: add tests for helper/dev/index.ts

* fix: run `format:fix`

* refactor: use named functions for middleware

* chore: denoify

* docs: tweaks deprecation warning message

* refactor(dev): Simplification of showList options

* chore: denoify
2023-11-29 19:22:09 +09:00

94 lines
2.6 KiB
TypeScript

import type { MiddlewareHandler } from '../../types.ts'
type CORSOptions = {
origin: string | string[] | ((origin: string) => string | undefined | null)
allowMethods?: string[]
allowHeaders?: string[]
maxAge?: number
credentials?: boolean
exposeHeaders?: string[]
}
export const cors = (options?: CORSOptions): MiddlewareHandler => {
const defaults: CORSOptions = {
origin: '*',
allowMethods: ['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH'],
allowHeaders: [],
exposeHeaders: [],
}
const opts = {
...defaults,
...options,
}
const findAllowOrigin = ((optsOrigin) => {
if (typeof optsOrigin === 'string') {
return () => optsOrigin
} else if (typeof optsOrigin === 'function') {
return optsOrigin
} else {
return (origin: string) => (optsOrigin.includes(origin) ? origin : optsOrigin[0])
}
})(opts.origin)
return async function cors(c, next) {
function set(key: string, value: string) {
c.res.headers.set(key, value)
}
const allowOrigin = findAllowOrigin(c.req.header('origin') || '')
if (allowOrigin) {
set('Access-Control-Allow-Origin', allowOrigin)
}
// Suppose the server sends a response with an Access-Control-Allow-Origin value with an explicit origin (rather than the "*" wildcard).
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
if (opts.origin !== '*') {
set('Vary', 'Origin')
}
if (opts.credentials) {
set('Access-Control-Allow-Credentials', 'true')
}
if (opts.exposeHeaders?.length) {
set('Access-Control-Expose-Headers', opts.exposeHeaders.join(','))
}
if (c.req.method !== 'OPTIONS') {
await next()
} else {
// Preflight
if (opts.maxAge != null) {
set('Access-Control-Max-Age', opts.maxAge.toString())
}
if (opts.allowMethods?.length) {
set('Access-Control-Allow-Methods', opts.allowMethods.join(','))
}
let headers = opts.allowHeaders
if (!headers?.length) {
const requestHeaders = c.req.header('Access-Control-Request-Headers')
if (requestHeaders) {
headers = requestHeaders.split(/\s*,\s*/)
}
}
if (headers?.length) {
set('Access-Control-Allow-Headers', headers.join(','))
c.res.headers.append('Vary', 'Access-Control-Request-Headers')
}
c.res.headers.delete('Content-Length')
c.res.headers.delete('Content-Type')
return new Response(null, {
headers: c.res.headers,
status: 204,
statusText: c.res.statusText,
})
}
}
}