accepts.test.ts
This file
Path
src/helper/accepts/accepts.test.ts
344 lines 路 10.9 KiB 路 TypeScript
Last changed by
fix(accepts): match media types and language tags case-insensitively (#5376)Harshit Prakashbefore adoptionf5a5346
History of this fileTake it
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345import { Hono } from '../..'import { parseAccept } from '../../utils/accept'import type { AcceptHeader } from '../../utils/headers'import type { Accept, acceptsConfig, acceptsOptions } from './accepts'import { accepts, defaultMatch } from './accepts'
describe('parseAccept', () => { test('should parse accept header', () => { const acceptHeader = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8;level=1;foo=bar' const accepts = parseAccept(acceptHeader) expect(accepts).toEqual([ { type: 'text/html', params: {}, q: 1 }, { type: 'application/xhtml+xml', params: {}, q: 1 }, { type: 'image/webp', params: {}, q: 1 }, { type: 'application/xml', params: { q: '0.9' }, q: 0.9 }, { type: '*/*', params: { q: '0.8', level: '1', foo: 'bar' }, q: 0.8 }, ]) })})
describe('defaultMatch', () => { test('should return default support', () => { const accepts: Accept[] = [ { type: 'text/html', params: {}, q: 1 }, { type: 'application/xhtml+xml', params: {}, q: 1 }, { type: 'application/xml', params: { q: '0.9' }, q: 0.9 }, { type: 'image/webp', params: {}, q: 1 }, { type: '*/*', params: { q: '0.8' }, q: 0.8 }, ] const config: acceptsConfig = { header: 'Accept', supports: ['text/html'], default: 'text/html', } const result = defaultMatch(accepts, config) expect(result).toBe('text/html') })})
describe('accepts', () => { test('should return matched support', () => { const c = { req: { header: () => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', }, // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any const options: acceptsConfig = { header: 'Accept', supports: ['application/xml', 'text/html'], default: 'application/json', } const result = accepts(c, options) expect(result).toBe('text/html') })
test('should return default support if no matched support', () => { const c = { req: { header: () => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', }, // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any const options: acceptsConfig = { header: 'Accept', supports: ['application/json'], default: 'text/html', } const result = accepts(c, options) expect(result).toBe('text/html') })
test('should match wildcard subtype application/*', () => { const c = { req: { header: () => 'application/*', }, // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any const options: acceptsConfig = { header: 'Accept', supports: ['application/json', 'text/html'], default: 'text/html', } const result = accepts(c, options) expect(result).toBe('application/json') })
test('should return default support for global wildcard */*', () => { const c = { req: { header: () => 'text/plain, */*;q=0.5', }, // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any const options: acceptsConfig = { header: 'Accept', supports: ['application/json'], default: 'text/html', } const result = accepts(c, options) expect(result).toBe('text/html') })
test('should return default support for single asterisk wildcard *', () => { const c = { req: { header: () => '*', }, // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any const options: acceptsConfig = { header: 'Accept-Encoding', supports: ['gzip', 'deflate'], default: 'identity', } const result = accepts(c, options) expect(result).toBe('identity') })
test('should prefer exact match over wildcard match at same quality factor', () => { const c = { req: { header: () => '*/*, application/json', }, // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any const options: acceptsConfig = { header: 'Accept', supports: ['text/html', 'application/json'], default: 'text/html', } const result = accepts(c, options) expect(result).toBe('application/json') })
test('should match subtype wildcard while global wildcard falls through to default', () => { const c = { req: { header: () => '*/*, text/*', }, // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any const options: acceptsConfig = { header: 'Accept', supports: ['application/json', 'text/plain'], default: 'application/json', } const result = accepts(c, options) expect(result).toBe('text/plain') })
test('should return default support if no accept header', () => { const c = { req: { header: () => undefined, }, // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any const options: acceptsConfig = { header: 'Accept', supports: ['application/json'], default: 'text/html', } const result = accepts(c, options) expect(result).toBe('text/html') })
test('should return matched support with custom match function', () => { const c = { req: { header: () => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', }, // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any // this match function will return the least q value const match = (accepts: Accept[], config: acceptsConfig) => { const { supports, default: defaultSupport } = config const accept = accepts .sort((a, b) => a.q - b.q) .find((accept) => supports.includes(accept.type)) return accept ? accept.type : defaultSupport } const options: acceptsOptions = { header: 'Accept', supports: ['application/xml', 'text/html'], default: 'application/json', match, } const result = accepts(c, options) expect(result).toBe('application/xml') })
test('should not match entries explicitly rejected with q=0', () => { const c = { req: { header: () => 'application/json;q=0', }, // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any const options: acceptsConfig = { header: 'Accept', supports: ['application/json'], default: 'text/html', } const result = accepts(c, options) expect(result).toBe('text/html') })
test('should skip q=0 entries and match the remaining ones', () => { const c = { req: { header: () => 'text/html;q=0.5, application/json;q=0', }, // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any const options: acceptsConfig = { header: 'Accept', supports: ['application/json'], default: 'application/octet-stream', } const result = accepts(c, options) expect(result).toBe('application/octet-stream') })
test('should not match a subtype wildcard the client rejected with q=0', () => { const c = { req: { header: () => 'application/*;q=0', }, // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any const options: acceptsConfig = { header: 'Accept', supports: ['application/json'], default: 'text/html', } const result = accepts(c, options) expect(result).toBe('text/html') })
describe('case insensitivity', () => { const pick = (header: AcceptHeader, value: string, supports: string[]) => { const c = { req: { header: () => value }, // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any return accepts(c, { header, supports, default: 'DEFAULT' }) }
// Media types are case-insensitive (RFC 9110 搂8.3.1) test.each(['text/html', 'TEXT/HTML', 'Text/Html', 'text/HTML'])( 'Accept: %s matches text/html', (value) => { expect(pick('Accept', value, ['text/html'])).toBe('text/html') } )
test('a case-different subtype wildcard still matches', () => { expect(pick('Accept', 'TEXT/*', ['text/html'])).toBe('text/html') })
// Language tags are case-insensitive (RFC 4647 搂2.1) test.each(['en-US', 'EN-US', 'en-us', 'En-Us'])( 'Accept-Language: %s matches en-US', (value) => { expect(pick('Accept-Language', value, ['en-US'])).toBe('en-US') } )
test('a case-different entry with q=0 is still not acceptable', () => { expect(pick('Accept-Language', 'EN;q=0', ['en'])).toBe('DEFAULT') }) })})
describe('Usage', () => { test('decide compression by Accept-Encoding header', async () => { const app = new Hono() app.get('/compressed', async (c) => { const encoding = accepts(c, { header: 'Accept-Encoding', supports: ['gzip', 'deflate'], default: 'identity', }) const COMPRESS_DATA = 'COMPRESS_DATA' const readable = new ReadableStream({ start(controller) { controller.enqueue(new TextEncoder().encode(COMPRESS_DATA)) controller.close() }, })
if (encoding === 'gzip') { c.header('Content-Encoding', 'gzip') return c.body(readable.pipeThrough(new CompressionStream('gzip'))) } if (encoding === 'deflate') { c.header('Content-Encoding', 'deflate') return c.body(readable.pipeThrough(new CompressionStream('deflate'))) }
c.body(COMPRESS_DATA) })
const req1 = await app.request('/compressed', { headers: { 'Accept-Encoding': 'deflate' } }) const req2 = await app.request('/compressed', { headers: { 'Accept-Encoding': 'gzip' } }) const req3 = await app.request('/compressed', { headers: { 'Accept-Encoding': 'gzip;q=0.5,deflate' }, }) const req4 = await app.request('/compressed', { headers: { 'Accept-Encoding': 'br' } })
expect(req1.headers.get('Content-Encoding')).toBe('deflate') expect(req2.headers.get('Content-Encoding')).toBe('gzip') expect(req3.headers.get('Content-Encoding')).toBe('deflate') expect(req4.headers.get('Content-Encoding')).toBeNull() })
test('decide language by Accept-Language header', async () => { const app = new Hono() const SUPPORTED_LANGS = ['en', 'ja', 'zh'] app.get('/*', async (c) => { const lang = accepts(c, { header: 'Accept-Language', supports: SUPPORTED_LANGS, default: 'en', }) const isLangedPath = SUPPORTED_LANGS.some((l) => c.req.path.startsWith(`/${l}`)) if (isLangedPath) { return c.body(`lang: ${lang}`) }
return c.redirect(`/${lang}${c.req.path}`) })
const req1 = await app.request('/foo', { headers: { 'Accept-Language': 'en=0.8,ja' } }) const req2 = await app.request('/en/foo', { headers: { 'Accept-Language': 'en' } })
expect(req1.status).toBe(302) expect(req1.headers.get('Location')).toBe('/ja/foo') expect(await req2.text()).toBe('lang: en') })})