import { HTTPException } from './http-exception' import { cloneRawRequest, HonoRequest } from './request' import type { RouterRoute } from './types' type RecursiveRecord = { [key in K]: T | RecursiveRecord } describe('Query', () => { test('req.query() and req.queries()', () => { const rawRequest = new Request('http://localhost?page=2&tag=A&tag=B') const req = new HonoRequest(rawRequest) const page = req.query('page') expect(page).not.toBeUndefined() expect(page).toBe('2') const q = req.query('q') expect(q).toBeUndefined() const tags = req.queries('tag') expect(tags).not.toBeUndefined() expect(tags).toEqual(['A', 'B']) const q2 = req.queries('q2') expect(q2).toBeUndefined() }) test('decode special chars', () => { const rawRequest = new Request('http://localhost?mail=framework%40hono.dev&tag=%401&tag=%402') const req = new HonoRequest(rawRequest) const mail = req.query('mail') expect(mail).toBe('framework@hono.dev') const tags = req.queries('tag') expect(tags).toEqual(['@1', '@2']) }) }) describe('Param', () => { test('req.param() should return empty string for zero-length match', () => { // Simulate a route like '/:remaining{.*}' matching '/' const rawRequest = new Request('http://localhost/') const req = new HonoRequest<'/:remaining{.*}'>(rawRequest, '/', [ [[[undefined, {} as RouterRoute], { remaining: 0 }]], [''], // ParamStash with empty string for remaining ]) // Single param access should be empty string, not undefined expect(req.param('remaining')).toBe('') // All params should include key with empty string value const all = req.param() expect(all).toEqual({ remaining: '' }) }) test('req.param() with ParamStash', () => { const rawRequest = new Request('http://localhost?page=2&tag=A&tag=B') const req = new HonoRequest<'/:id/:name'>(rawRequest, '/123/key', [ [ [[undefined, {} as RouterRoute], { id: 0 }], [[undefined, {} as RouterRoute], { id: 0, name: 1 }], ], ['123', 'key'], ]) expect(req.param('id')).toBe('123') expect(req.param('name')).toBe(undefined) req.routeIndex = 1 expect(req.param('id')).toBe('123') expect(req.param('name')).toBe('key') }) test('req.param() without ParamStash', () => { const rawRequest = new Request('http://localhost?page=2&tag=A&tag=B') const req = new HonoRequest<'/:id/:name'>(rawRequest, '/123/key', [ [ [[undefined, {} as RouterRoute], { id: '123' }], [[undefined, {} as RouterRoute], { id: '456', name: 'key' }], ], ]) expect(req.param('id')).toBe('123') expect(req.param('name')).toBe(undefined) req.routeIndex = 1 expect(req.param('id')).toBe('456') expect(req.param('name')).toBe('key') }) test('req.param() returns empty string for missing param', () => { const rawRequest = new Request('http://localhost') const req = new HonoRequest<'/:remaining'>(rawRequest, '/', [ [[[undefined, {} as RouterRoute], { remaining: 0 }]], [''], ]) expect(req.param('remaining')).toBe('') }) test('req.param() without argument returns object with empty string for missing param', () => { const rawRequest = new Request('http://localhost') const req = new HonoRequest<'/:remaining'>(rawRequest, '/', [ [[[undefined, {} as RouterRoute], { remaining: 0 }]], [''], ]) expect(req.param()).toEqual({ remaining: '' }) }) describe('Type', () => { it('param() returns string | undefined when P is any (middleware context)', () => { // When middleware uses Context without an explicit path type, P defaults to any. // param(key) should return string | undefined, not string. const rawRequest = new Request('http://localhost/users/123') const req = new HonoRequest(rawRequest, '/users/123', [ [[[undefined, {} as RouterRoute], { id: '123' }]], ]) expectTypeOf(req.param('id')).toEqualTypeOf() }) it('param() returns string when P is a known route string', () => { // When P is a concrete route, named params should still return string (non-optional). const rawRequest = new Request('http://localhost/123') const req = new HonoRequest<'/:id'>(rawRequest, '/123', [ [[[undefined, {} as RouterRoute], { id: '123' }]], ]) expectTypeOf(req.param('id')).toEqualTypeOf() }) }) }) describe('matchedRoutes', () => { test('req.routePath', () => { const handlerA = () => {} const handlerB = () => {} const rawRequest = new Request('http://localhost?page=2&tag=A&tag=B') const req = new HonoRequest<'/:id/:name'>(rawRequest, '/123/key', [ [ [ [handlerA, { basePath: '/', handler: handlerA, method: 'GET', path: '/:id' }], { id: '123' }, ], [ [handlerA, { basePath: '/', handler: handlerB, method: 'GET', path: '/:id/:name' }], { id: '456', name: 'key' }, ], ], ]) expect(req.matchedRoutes).toEqual([ { basePath: '/', handler: handlerA, method: 'GET', path: '/:id' }, { basePath: '/', handler: handlerB, method: 'GET', path: '/:id/:name' }, ]) }) }) describe('routePath', () => { test('req.routePath', () => { const handlerA = () => {} const handlerB = () => {} const rawRequest = new Request('http://localhost?page=2&tag=A&tag=B') const req = new HonoRequest<'/:id/:name'>(rawRequest, '/123/key', [ [ [ [handlerA, { basePath: '/', handler: handlerA, method: 'GET', path: '/:id' }], { id: '123' }, ], [ [handlerA, { basePath: '/', handler: handlerB, method: 'GET', path: '/:id/:name' }], { id: '456', name: 'key' }, ], ], ]) expect(req.routePath).toBe('/:id') req.routeIndex = 1 expect(req.routePath).toBe('/:id/:name') }) }) describe('req.addValidatedData() and req.data()', () => { const rawRequest = new Request('http://localhost') const payload = { title: 'hello', author: { name: 'young man', age: 20, }, } test('add data - json', () => { const req = new HonoRequest<'/', { json: typeof payload }>(rawRequest) req.addValidatedData('json', payload) const data = req.valid('json') expect(data).toEqual(payload) }) test('replace data - json', () => { const req = new HonoRequest<'/', { json: typeof payload }>(rawRequest) req.addValidatedData('json', payload) req.addValidatedData('json', { tag: ['sport', 'music'], author: { tall: 170, }, }) const data = req.valid('json') expect(data).toEqual({ author: { tall: 170, }, tag: ['sport', 'music'], }) }) }) describe('headers', () => { test('empty string is a valid header value', () => { const req = new HonoRequest(new Request('http://localhost', { headers: { foo: '' } })) const foo = req.header('foo') expect(foo).toEqual('') }) test('Keys of the arguments for req.header() are not case-sensitive', () => { const req = new HonoRequest( new Request('http://localhost', { headers: { 'Content-Type': 'application/json', apikey: 'abc', lowercase: 'lowercase value', }, }) ) expect(req.header('Content-Type')).toBe('application/json') expect(req.header('ApiKey')).toBe('abc') }) }) const text = '{"foo":"bar"}' const json = { foo: 'bar' } const buffer = new TextEncoder().encode('{"foo":"bar"}').buffer describe('Body methods with caching', () => { test('req.text()', async () => { const req = new HonoRequest( new Request('http://localhost', { method: 'POST', body: text, }) ) expect(await req.text()).toEqual(text) expect(await req.json()).toEqual(json) expect(await req.arrayBuffer()).toEqual(buffer) expect(await req.blob()).toEqual( new Blob([text], { type: 'text/plain;charset=utf-8', }) ) }) test('req.json()', async () => { const req = new HonoRequest( new Request('http://localhost', { method: 'POST', body: '{"foo":"bar"}', }) ) expect(await req.json()).toEqual(json) expect(await req.text()).toEqual(text) expect(await req.arrayBuffer()).toEqual(buffer) expect(await req.blob()).toEqual( new Blob([text], { type: 'text/plain;charset=utf-8', }) ) }) test('req.json() should keep the content as is', async () => { const text = '{ "foo" : "bar" }' const req = new HonoRequest( new Request('http://localhost', { method: 'POST', body: text, }) ) expect(await req.json()).toEqual(JSON.parse(text)) expect(await req.text()).toEqual(text) }) test('req.arrayBuffer()', async () => { const buffer = new TextEncoder().encode('{"foo":"bar"}').buffer const req = new HonoRequest( new Request('http://localhost', { method: 'POST', body: buffer, }) ) expect(await req.arrayBuffer()).toEqual(buffer) expect(await req.text()).toEqual(text) expect(await req.json()).toEqual(json) expect(await req.blob()).toEqual( new Blob([text], { type: '', }) ) }) test('req.blob()', async () => { const blob = new Blob(['{"foo":"bar"}'], { type: 'application/json', }) const req = new HonoRequest( new Request('http://localhost', { method: 'POST', body: blob, }) ) expect(await req.blob()).toEqual(blob) expect(await req.text()).toEqual(text) expect(await req.json()).toEqual(json) expect(await req.arrayBuffer()).toEqual(buffer) }) test('req.formData()', async () => { const data = new FormData() data.append('foo', 'bar') const req = new HonoRequest( new Request('http://localhost', { method: 'POST', body: data, }) ) expect((await req.formData()).get('foo')).toBe('bar') expect(async () => await req.text()).not.toThrow() expect(async () => await req.arrayBuffer()).not.toThrow() expect(async () => await req.blob()).not.toThrow() }) describe('req.parseBody()', async () => { it('should parse form data', async () => { const data = new FormData() data.append('foo', 'bar') const req = new HonoRequest( new Request('http://localhost', { method: 'POST', body: data, }) ) expect((await req.parseBody())['foo']).toBe('bar') expect(async () => await req.text()).not.toThrow() expect(async () => await req.arrayBuffer()).not.toThrow() expect(async () => await req.blob()).not.toThrow() }) describe('should not break body methods after parseBody() with non-form content-type', () => { const createReq = () => new HonoRequest( new Request('http://localhost', { method: 'POST', body: JSON.stringify({ event: 'push' }), headers: { 'Content-Type': 'application/json' }, }) ) it('text()', async () => { const req = createReq() await req.parseBody() expect(await req.text()).toBe(JSON.stringify({ event: 'push' })) }) it('json()', async () => { const req = createReq() await req.parseBody() expect(await req.json()).toEqual({ event: 'push' }) }) it('arrayBuffer()', async () => { const req = createReq() await req.parseBody() expect(await req.arrayBuffer()).toBeInstanceOf(ArrayBuffer) }) it('blob()', async () => { const req = createReq() await req.parseBody() expect(await req.blob()).toBeInstanceOf(Blob) }) it('formData()', async () => { const req = createReq() await req.parseBody() // application/json is not a valid formData content-type, so this should throw expect(req.formData()).rejects.toThrow() }) }) describe('Return type', () => { let req: HonoRequest beforeEach(() => { const data = new FormData() data.append('foo', 'bar') req = new HonoRequest( new Request('http://localhost', { method: 'POST', body: data, }) ) }) it('without options', async () => { expectTypeOf((await req.parseBody())['key']).toEqualTypeOf() }) it('{all: true}', async () => { expectTypeOf((await req.parseBody({ all: true }))['key']).toEqualTypeOf< string | File | (string | File)[] >() }) it('{dot: true}', async () => { expectTypeOf((await req.parseBody({ dot: true }))['key']).toEqualTypeOf< string | File | RecursiveRecord >() }) it('{all: true, dot: true}', async () => { expectTypeOf((await req.parseBody({ all: true, dot: true }))['key']).toEqualTypeOf< | string | File | (string | File)[] | RecursiveRecord >() }) it('specify return type explicitly', async () => { expectTypeOf( await req.parseBody<{ key1: string; key2: string }>({ all: true, dot: true }) ).toEqualTypeOf<{ key1: string; key2: string }>() }) }) }) }) describe('cloneRawRequest', () => { test('clones unconsumed request object', async () => { const req = new HonoRequest( new Request('http://localhost', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Custom-Header': 'custom-value', }, body: text, cache: 'no-cache', credentials: 'include', integrity: 'sha256-test', mode: 'cors', redirect: 'follow', referrer: 'http://example.com', referrerPolicy: 'origin', }) ) const clonedReq = await cloneRawRequest(req) expect(clonedReq.method).toBe('POST') expect(clonedReq.url).toBe('http://localhost/') expect(await clonedReq.text()).toBe(text) expect(clonedReq.headers.get('Content-Type')).toBe('application/json') expect(clonedReq.headers.get('X-Custom-Header')).toBe('custom-value') expect(clonedReq.cache).toBe('no-cache') expect(clonedReq.credentials).toBe('include') expect(clonedReq.integrity).toBe('sha256-test') expect(clonedReq.mode).toBe('cors') expect(clonedReq.redirect).toBe('follow') expect(clonedReq.referrer).toBe('http://example.com/') expect(clonedReq.referrerPolicy).toBe('origin') expect(req.raw, 'cloned request should be a different object reference').not.toBe(clonedReq) expect(req.raw, 'cloned request should contain the same properties').toMatchObject(clonedReq) }) test('clones consumed request object', async () => { const req = new HonoRequest( new Request('http://localhost', { method: 'POST', headers: { Authorization: 'Bearer token123', }, body: text, mode: 'same-origin', credentials: 'same-origin', }) ) await req.json() const clonedReq = await cloneRawRequest(req) expect(clonedReq.method).toBe('POST') expect(clonedReq.url).toBe('http://localhost/') expect(await clonedReq.json()).toEqual(json) expect(clonedReq.headers.get('Authorization')).toBe('Bearer token123') expect(clonedReq.mode).toBe('same-origin') expect(clonedReq.credentials).toBe('same-origin') expect(req.raw, 'cloned request should be a different object reference').not.toBe(clonedReq) expect(req.raw, 'cloned request should contain the same properties').toMatchObject(clonedReq) }) test('clones GET request without body', async () => { const req = new HonoRequest( new Request('http://localhost', { method: 'GET', headers: { 'User-Agent': 'test-agent', }, cache: 'default', redirect: 'manual', referrerPolicy: 'no-referrer', }) ) const clonedReq = await cloneRawRequest(req) expect(clonedReq.method).toBe('GET') expect(clonedReq.url).toBe('http://localhost/') expect(clonedReq.headers.get('User-Agent')).toBe('test-agent') expect(clonedReq.cache).toBe('default') expect(clonedReq.redirect).toBe('manual') expect(clonedReq.referrerPolicy).toBe('no-referrer') expect(req.raw, 'cloned request should be a different object reference').not.toBe(clonedReq) expect(req.raw, 'cloned request should contain the same properties').toMatchObject(clonedReq) }) test('clones request when raw body was consumed directly without HonoRequest methods', async () => { const req = new HonoRequest( new Request('http://localhost', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: text, }) ) // Consume the raw request body directly, bypassing HonoRequest methods // This means bodyCache will be empty await req.raw.text() expect(req.raw.bodyUsed).toBe(true) expect(Object.keys(req.bodyCache).length).toBe(0) let error: HTTPException | undefined = undefined try { await cloneRawRequest(req) } catch (e) { expect(e).toBeInstanceOf(HTTPException) error = e as HTTPException } expect(error).not.toBeUndefined() expect((error as HTTPException).status).toBe(500) expect((error as HTTPException).message).toContain( 'Cannot clone request: body was already consumed and not cached' ) }) })