feat: introduce "Helpers" (#1353)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* mv jsx * introduce helper * denoify & add src/helper.ts for Deno * remove `c` not used * remove `c` in lagon test * remove `src/adapter.ts` not used
authored by Yusuke Wada · committed by GitHub · parent 66b915a · Browse files · 48 files·+1954 added−1853 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
48 files+1954 added−1853 removed
- tests:+1054 added−1055 removed
- other:+900 added−798 removed
Provenance
- Commit
e070191- Tree
1399509- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
66b915a
48 files changed+1954 added−1853 removed
added:deno_dist/helper/adapter/index.ts+65 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465import type { Context } from '../../context.ts'
export const env = <T extends Record<string, string>, C extends Context = Context<{}>>( c: C): T & C['env'] => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const global = globalThis as any
if ( c.runtime === 'bun' || c.runtime === 'node' || c.runtime === 'edge-light' || c.runtime === 'lagon' ) { return global?.process?.env as T } if (c.runtime === 'deno') { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore return Deno.env.toObject() } if (c.runtime === 'workerd') { return c.env } if (c.runtime === 'fastly') { // On Fastly Compute@Edge, you can use the ConfigStore to manage user-defined data. return {} as T } return {} as T}
export const getRuntimeKey = () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const global = globalThis as any
if (global?.Deno !== undefined) { return 'deno' }
if (global?.Bun !== undefined) { return 'bun' }
if (typeof global?.WebSocketPair === 'function') { return 'workerd' }
if (typeof global?.EdgeRuntime === 'string') { return 'edge-light' }
if (global?.fastly !== undefined) { return 'fastly' }
if (global?.__lagon__ !== undefined) { return 'lagon' }
if (global?.process?.release?.name === 'node') { return 'node' }
return 'other'}added:deno_dist/helper/cookie/index.ts+59 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859import type { Context } from '../../context.ts'import { parse, parseSigned, serialize, serializeSigned } from '../../utils/cookie.ts'import type { CookieOptions, Cookie, SignedCookie } from '../../utils/cookie.ts'
interface GetCookie { (c: Context, key: string): string | undefined (c: Context): Cookie}
interface GetSignedCookie { (c: Context, secret: string, key: string): Promise<string | undefined | false> (c: Context, secret: string): Promise<SignedCookie>}
export const getCookie: GetCookie = (c, key?) => { const cookie = c.req.raw.headers.get('Cookie') if (typeof key === 'string') { if (!cookie) return undefined const obj = parse(cookie) return obj[key] } if (!cookie) return {} const obj = parse(cookie) // eslint-disable-next-line @typescript-eslint/no-explicit-any return obj as any}
export const getSignedCookie: GetSignedCookie = async (c, secret, key?) => { const cookie = c.req.raw.headers.get('Cookie') if (typeof key === 'string') { if (!cookie) return undefined const obj = await parseSigned(cookie, secret, key) return obj[key] } if (!cookie) return {} const obj = await parseSigned(cookie, secret) // eslint-disable-next-line @typescript-eslint/no-explicit-any return obj as any}
export const setCookie = (c: Context, name: string, value: string, opt?: CookieOptions): void => { const cookie = serialize(name, value, opt) c.header('set-cookie', cookie, { append: true })}
export const setSignedCookie = async ( c: Context, name: string, value: string, secret: string, opt?: CookieOptions): Promise<void> => { const cookie = await serializeSigned(name, value, secret, opt) c.header('set-cookie', cookie, { append: true })}
export const deleteCookie = (c: Context, name: string, opt?: CookieOptions): void => { setCookie(c, name, '', { ...opt, maxAge: 0 })}added:deno_dist/helper/html/index.ts+39 added
123456789101112131415161718192021222324252627282930313233343536373839import { escapeToBuffer } from '../../utils/html.ts'import type { StringBuffer, HtmlEscaped, HtmlEscapedString } from '../../utils/html.ts'
export const raw = (value: unknown): HtmlEscapedString => { const escapedString = new String(value) as HtmlEscapedString escapedString.isEscaped = true
return escapedString}
export const html = (strings: TemplateStringsArray, ...values: unknown[]): HtmlEscapedString => { const buffer: StringBuffer = ['']
for (let i = 0, len = strings.length - 1; i < len; i++) { buffer[0] += strings[i]
const children = values[i] instanceof Array ? (values[i] as Array<unknown>).flat(Infinity) : [values[i]] for (let i = 0, len = children.length; i < len; i++) { // eslint-disable-next-line @typescript-eslint/no-explicit-any const child = children[i] as any if (typeof child === 'string') { escapeToBuffer(child, buffer) } else if (typeof child === 'boolean' || child === null || child === undefined) { continue } else if ( (typeof child === 'object' && (child as HtmlEscaped).isEscaped) || typeof child === 'number' ) { buffer[0] += child } else { escapeToBuffer(child.toString(), buffer) } } } buffer[0] += strings[strings.length - 1]
return raw(buffer[0])}added:deno_dist/jsx/index.test.tsx+376 added
1+import { html } from '../helper/html/index.ts'2+import { Hono } from '../hono.ts'3+import { jsx, memo, Fragment } from './index.ts'4+5+interface SiteData {6+ title: string7+ children?: any8+}9+10+describe('JSX middleware', () => {11+ let app: Hono12+13+ beforeEach(() => {14+ app = new Hono()15+ })16+17+ it('Should render HTML strings', async () => {18+ app.get('/', (c) => {19+ return c.html(<h1>Hello</h1>)20+ })21+ const res = await app.request('http://localhost/')22+ expect(res.status).toBe(200)23+ expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')24+ expect(await res.text()).toBe('<h1>Hello</h1>')25+ })26+27+ it('Should be able to be used with html middleware', async () => {28+ const Layout = (props: SiteData) => html`<!DOCTYPE html>29+ <html>30+ <head>31+ <title>${props.title}</title>32+ </head>33+ <body>34+ ${props.children}35+ </body>36+ </html>`37+38+ const Content = (props: { siteData: SiteData; name: string }) => (39+ <Layout {...props.siteData}>40+ <h1>{props.name}</h1>41+ </Layout>42+ )43+44+ app.get('/', (c) => {45+ const props = {46+ name: 'JSX',47+ siteData: {48+ title: 'with html middleware',49+ },50+ }51+ return c.html(<Content {...props} />)52+ })53+ const res = await app.request('http://localhost/')54+ expect(res.status).toBe(200)55+ expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')56+ expect(await res.text()).toBe(`<!DOCTYPE html>57+ <html>58+ <head>59+ <title>with html middleware</title>60+ </head>61+ <body>62+ <h1>JSX</h1>63+ </body>64+ </html>`)65+ })66+})67+68+describe('render to string', () => {69+ it('Nested array', () => {70+ const template = (71+ <p>72+ {[[['a']], [['b']]].map((item1) =>73+ item1.map((item2) => item2.map((item3) => <span>{item3}</span>))74+ )}75+ </p>76+ )77+ expect(template.toString()).toBe('<p><span>a</span><span>b</span></p>')78+ })79+80+ it('Empty elements are rended withtout closing tag', () => {81+ const template = <input />82+ expect(template.toString()).toBe('<input/>')83+ })84+85+ it('Props value is null', () => {86+ const template = <span data-hello={null}>Hello</span>87+ expect(template.toString()).toBe('<span>Hello</span>')88+ })89+90+ it('Props value is undefined', () => {91+ const template = <span data-hello={undefined}>Hello</span>92+ expect(template.toString()).toBe('<span>Hello</span>')93+ })94+95+ describe('dangerouslySetInnerHTML', () => {96+ it('Should render dangerouslySetInnerHTML', () => {97+ const template = <span dangerouslySetInnerHTML={{ __html: '" is allowed here' }}></span>98+ expect(template.toString()).toBe('<span>" is allowed here</span>')99+ })100+101+ it('Should get an error if both dangerouslySetInnerHTML and children are specified', () => {102+ expect(() =>103+ (<span dangerouslySetInnerHTML={{ __html: '" is allowed here' }}>Hello</span>).toString()104+ ).toThrow()105+ })106+ })107+108+ // https://en.reactjs.org/docs/jsx-in-depth.html#booleans-null-and-undefined-are-ignored109+ describe('Booleans, Null, and Undefined Are Ignored', () => {110+ it.each([true, false, undefined, null])('%s', (item) => {111+ expect((<span>{item}</span>).toString()).toBe('<span></span>')112+ })113+114+ it('falsy value', () => {115+ const template = <span>{0}</span>116+ expect(template.toString()).toBe('<span>0</span>')117+ })118+ })119+120+ // https://en.reactjs.org/docs/jsx-in-depth.html#props-default-to-true121+ describe('Props Default to “True”', () => {122+ it('default prop value', () => {123+ const template = <span data-hello>Hello</span>124+ expect(template.toString()).toBe('<span data-hello="true">Hello</span>')125+ })126+ })127+128+ // https://html.spec.whatwg.org/#attributes-3129+ describe('Boolean attribute', () => {130+ it('default prop value for checked', () => {131+ const template = <input type='checkbox' checked />132+ expect(template.toString()).toBe('<input type="checkbox" checked=""/>')133+ })134+135+ it('default prop value for checked={true}', () => {136+ const template = <input type='checkbox' checked={true} />137+ expect(template.toString()).toBe('<input type="checkbox" checked=""/>')138+ })139+140+ it('no prop for checked={false}', () => {141+ const template = <input type='checkbox' checked={false} />142+ expect(template.toString()).toBe('<input type="checkbox"/>')143+ })144+145+ it('default prop value for disabled', () => {146+ const template = <input type='checkbox' disabled />147+ expect(template.toString()).toBe('<input type="checkbox" disabled=""/>')148+ })149+150+ it('default prop value for disabled={true}', () => {151+ const template = <input type='checkbox' disabled={true} />152+ expect(template.toString()).toBe('<input type="checkbox" disabled=""/>')153+ })154+155+ it('no prop for disabled={false}', () => {156+ const template = <input type='checkbox' disabled={false} />157+ expect(template.toString()).toBe('<input type="checkbox"/>')158+ })159+160+ it('default prop value for readonly', () => {161+ const template = <input type='checkbox' readonly />162+ expect(template.toString()).toBe('<input type="checkbox" readonly=""/>')163+ })164+165+ it('default prop value for readonly={true}', () => {166+ const template = <input type='checkbox' readonly={true} />167+ expect(template.toString()).toBe('<input type="checkbox" readonly=""/>')168+ })169+170+ it('no prop for readonly={false}', () => {171+ const template = <input type='checkbox' readonly={false} />172+ expect(template.toString()).toBe('<input type="checkbox"/>')173+ })174+175+ it('default prop value for selected', () => {176+ const template = (177+ <option value='test' selected>178+ Test179+ </option>180+ )181+ expect(template.toString()).toBe('<option value="test" selected="">Test</option>')182+ })183+184+ it('default prop value for selected={true}', () => {185+ const template = (186+ <option value='test' selected={true}>187+ Test188+ </option>189+ )190+ expect(template.toString()).toBe('<option value="test" selected="">Test</option>')191+ })192+193+ it('no prop for selected={false}', () => {194+ const template = (195+ <option value='test' selected={false}>196+ Test197+ </option>198+ )199+ expect(template.toString()).toBe('<option value="test">Test</option>')200+ })201+202+ it('default prop value for multiple select', () => {203+ const template = (204+ <select multiple>205+ <option>test</option>206+ </select>207+ )208+ expect(template.toString()).toBe('<select multiple=""><option>test</option></select>')209+ })210+211+ it('default prop value for select multiple={true}', () => {212+ const template = (213+ <select multiple={true}>214+ <option>test</option>215+ </select>216+ )217+ expect(template.toString()).toBe('<select multiple=""><option>test</option></select>')218+ })219+220+ it('no prop for select multiple={false}', () => {221+ const template = (222+ <select multiple={false}>223+ <option>test</option>224+ </select>225+ )226+ expect(template.toString()).toBe('<select><option>test</option></select>')227+ })228+229+ it('should render "false" value properly for other non-defined keys', () => {230+ const template = <input type='checkbox' testkey={false} />231+ expect(template.toString()).toBe('<input type="checkbox" testkey="false"/>')232+ })233+234+ it('should support attributes for elements other than input', () => {235+ const template = (236+ <video controls autoplay>237+ <source src='movie.mp4' type='video/mp4' />238+ </video>239+ )240+ expect(template.toString()).toBe(241+ '<video controls="" autoplay=""><source src="movie.mp4" type="video/mp4"/></video>'242+ )243+ })244+ })245+246+ // https://en.reactjs.org/docs/jsx-in-depth.html#functions-as-children247+ describe('Functions as Children', () => {248+ it('Function', () => {249+ function Repeat(props: any) {250+ const items = []251+ for (let i = 0; i < props.numTimes; i++) {252+ items.push((props.children as Function)(i))253+ }254+ return <div>{items}</div>255+ }256+257+ function ListOfTenThings() {258+ return (259+ <Repeat numTimes={10}>260+ {(index: string) => <div key={index}>This is item {index} in the list</div>}261+ </Repeat>262+ )263+ }264+265+ const template = <ListOfTenThings />266+ expect(template.toString()).toBe(267+ '<div><div key="0">This is item 0 in the list</div><div key="1">This is item 1 in the list</div><div key="2">This is item 2 in the list</div><div key="3">This is item 3 in the list</div><div key="4">This is item 4 in the list</div><div key="5">This is item 5 in the list</div><div key="6">This is item 6 in the list</div><div key="7">This is item 7 in the list</div><div key="8">This is item 8 in the list</div><div key="9">This is item 9 in the list</div></div>'268+ )269+ })270+ })271+272+ describe('style attribute', () => {273+ it('should convert the object to strings', () => {274+ const template = (275+ <h1276+ style={{277+ color: 'red',278+ fontSize: 'small',279+ }}280+ >281+ Hello282+ </h1>283+ )284+ expect(template.toString()).toBe('<h1 style="color:red;font-size:small">Hello</h1>')285+ })286+ it('should not convert the strings', () => {287+ const template = <h1 style='color:red;font-size:small'>Hello</h1>288+ expect(template.toString()).toBe('<h1 style="color:red;font-size:small">Hello</h1>')289+ })290+ })291+})292+293+describe('memo', () => {294+ it('memoized', () => {295+ let counter = 0296+ const Header = memo(() => <title>Test Site {counter}</title>)297+ const Body = () => <span>{counter}</span>298+299+ let template = (300+ <html>301+ <head>302+ <Header />303+ </head>304+ <body>305+ <Body />306+ </body>307+ </html>308+ )309+ expect(template.toString()).toBe(310+ '<html><head><title>Test Site 0</title></head><body><span>0</span></body></html>'311+ )312+313+ counter++314+ template = (315+ <html>316+ <head>317+ <Header />318+ </head>319+ <body>320+ <Body />321+ </body>322+ </html>323+ )324+ expect(template.toString()).toBe(325+ '<html><head><title>Test Site 0</title></head><body><span>1</span></body></html>'326+ )327+ })328+329+ it('props are updated', () => {330+ const Body = memo(({ counter }: { counter: number }) => <span>{counter}</span>)331+332+ let template = <Body counter={0} />333+ expect(template.toString()).toBe('<span>0</span>')334+335+ template = <Body counter={1} />336+ expect(template.toString()).toBe('<span>1</span>')337+ })338+339+ it('custom propsAreEqual', () => {340+ const Body = memo(341+ ({ counter }: { counter: number; refresh?: boolean }) => <span>{counter}</span>,342+ (_, nextProps) => (typeof nextProps.refresh == 'undefined' ? true : !nextProps.refresh)343+ )344+345+ let template = <Body counter={0} />346+ expect(template.toString()).toBe('<span>0</span>')347+348+ template = <Body counter={1} />349+ expect(template.toString()).toBe('<span>0</span>')350+351+ template = <Body counter={2} refresh={true} />352+ expect(template.toString()).toBe('<span>2</span>')353+ })354+})355+356+describe('Fragment', () => {357+ it('Should render children', () => {358+ const template = (359+ <>360+ <p>1</p>361+ <p>2</p>362+ </>363+ )364+ expect(template.toString()).toBe('<p>1</p><p>2</p>')365+ })366+367+ it('Should render nothing for empty Fragment', () => {368+ const template = <></>369+ expect(template.toString()).toBe('')370+ })371+372+ it('Should render nothing for undefined', () => {373+ const template = <>{undefined}</>374+ expect(template.toString()).toBe('')375+ })376+})added:deno_dist/jsx/index.ts+240 added
1+import { escapeToBuffer } from '../utils/html.ts'2+import type { StringBuffer, HtmlEscaped, HtmlEscapedString } from '../utils/html.ts'3+4+// eslint-disable-next-line @typescript-eslint/no-explicit-any5+type Props = Record<string, any>6+7+declare global {8+ // eslint-disable-next-line @typescript-eslint/no-namespace9+ namespace JSX {10+ type Element = HtmlEscapedString11+ interface ElementChildrenAttribute {12+ children: Child13+ }14+ interface IntrinsicElements {15+ [tagName: string]: Props16+ }17+ }18+}19+20+const emptyTags = [21+ 'area',22+ 'base',23+ 'br',24+ 'col',25+ 'embed',26+ 'hr',27+ 'img',28+ 'input',29+ 'keygen',30+ 'link',31+ 'meta',32+ 'param',33+ 'source',34+ 'track',35+ 'wbr',36+]37+const booleanAttributes = [38+ 'allowfullscreen',39+ 'async',40+ 'autofocus',41+ 'autoplay',42+ 'checked',43+ 'controls',44+ 'default',45+ 'defer',46+ 'disabled',47+ 'formnovalidate',48+ 'hidden',49+ 'inert',50+ 'ismap',51+ 'itemscope',52+ 'loop',53+ 'multiple',54+ 'muted',55+ 'nomodule',56+ 'novalidate',57+ 'open',58+ 'playsinline',59+ 'readonly',60+ 'required',61+ 'reversed',62+ 'selected',63+]64+65+const childrenToStringToBuffer = (children: Child[], buffer: StringBuffer): void => {66+ for (let i = 0, len = children.length; i < len; i++) {67+ const child = children[i]68+ if (typeof child === 'string') {69+ escapeToBuffer(child, buffer)70+ } else if (typeof child === 'boolean' || child === null || child === undefined) {71+ continue72+ } else if (child instanceof JSXNode) {73+ child.toStringToBuffer(buffer)74+ } else if (75+ typeof child === 'number' ||76+ (child as unknown as { isEscaped: boolean }).isEscaped77+ ) {78+ buffer[0] += child79+ } else {80+ // `child` type is `Child[]`, so stringify recursively81+ childrenToStringToBuffer(child, buffer)82+ }83+ }84+}85+86+type Child = string | number | JSXNode | Child[]87+export class JSXNode implements HtmlEscaped {88+ tag: string | Function89+ props: Props90+ children: Child[]91+ isEscaped: true = true as const92+ constructor(tag: string | Function, props: Props, children: Child[]) {93+ this.tag = tag94+ this.props = props95+ this.children = children96+ }97+98+ toString(): string {99+ const buffer: StringBuffer = ['']100+ this.toStringToBuffer(buffer)101+ return buffer[0]102+ }103+104+ toStringToBuffer(buffer: StringBuffer): void {105+ const tag = this.tag as string106+ const props = this.props107+ let { children } = this108+109+ buffer[0] += `<${tag}`110+111+ const propsKeys = Object.keys(props || {})112+113+ for (let i = 0, len = propsKeys.length; i < len; i++) {114+ const key = propsKeys[i]115+ const v = props[key]116+ // object to style strings117+ if (key === 'style' && typeof v === 'object') {118+ const styles = Object.keys(v)119+ .map((k) => `${k}:${v[k]}`)120+ .join(';')121+ .replace(/[A-Z]/g, (match) => `-${match.toLowerCase()}`)122+ buffer[0] += ` style="${styles}"`123+ } else if (typeof v === 'string') {124+ buffer[0] += ` ${key}="`125+ escapeToBuffer(v, buffer)126+ buffer[0] += '"'127+ } else if (typeof v === 'number') {128+ buffer[0] += ` ${key}="${v}"`129+ } else if (v === null || v === undefined) {130+ // Do nothing131+ } else if (typeof v === 'boolean' && booleanAttributes.includes(key)) {132+ if (v) {133+ buffer[0] += ` ${key}=""`134+ }135+ } else if (key === 'dangerouslySetInnerHTML') {136+ if (children.length > 0) {137+ throw 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.'138+ }139+140+ const escapedString = new String(v.__html) as HtmlEscapedString141+ escapedString.isEscaped = true142+ children = [escapedString]143+ } else {144+ buffer[0] += ` ${key}="`145+ escapeToBuffer(v.toString(), buffer)146+ buffer[0] += '"'147+ }148+ }149+150+ if (emptyTags.includes(tag as string)) {151+ buffer[0] += '/>'152+ return153+ }154+155+ buffer[0] += '>'156+157+ childrenToStringToBuffer(children, buffer)158+159+ buffer[0] += `</${tag}>`160+ }161+}162+163+class JSXFunctionNode extends JSXNode {164+ toStringToBuffer(buffer: StringBuffer): void {165+ const { children } = this166+167+ const res = (this.tag as Function).call(null, {168+ ...this.props,169+ children: children.length <= 1 ? children[0] : children,170+ })171+172+ if (res instanceof JSXNode) {173+ res.toStringToBuffer(buffer)174+ } else if (typeof res === 'number' || (res as HtmlEscaped).isEscaped) {175+ buffer[0] += res176+ } else {177+ escapeToBuffer(res, buffer)178+ }179+ }180+}181+182+class JSXFragmentNode extends JSXNode {183+ toStringToBuffer(buffer: StringBuffer): void {184+ childrenToStringToBuffer(this.children, buffer)185+ }186+}187+188+export { jsxFn as jsx }189+const jsxFn = (190+ tag: string | Function,191+ props: Props,192+ ...children: (string | HtmlEscapedString)[]193+): JSXNode => {194+ if (typeof tag === 'function') {195+ return new JSXFunctionNode(tag, props, children)196+ } else {197+ return new JSXNode(tag, props, children)198+ }199+}200+201+type FC<T = Props> = (props: T) => HtmlEscapedString202+203+const shallowEqual = (a: Props, b: Props): boolean => {204+ if (a === b) {205+ return true206+ }207+208+ const aKeys = Object.keys(a)209+ const bKeys = Object.keys(b)210+ if (aKeys.length !== bKeys.length) {211+ return false212+ }213+214+ for (let i = 0, len = aKeys.length; i < len; i++) {215+ if (a[aKeys[i]] !== b[aKeys[i]]) {216+ return false217+ }218+ }219+220+ return true221+}222+223+export const memo = <T>(224+ component: FC<T>,225+ propsAreEqual: (prevProps: Readonly<T>, nextProps: Readonly<T>) => boolean = shallowEqual226+): FC<T> => {227+ let computed = undefined228+ let prevProps: T | undefined = undefined229+ return ((props: T): HtmlEscapedString => {230+ if (prevProps && !propsAreEqual(prevProps, props)) {231+ computed = undefined232+ }233+ prevProps = props234+ return (computed ||= component(props))235+ }) as FC<T>236+}237+238+export const Fragment = (props: { key?: string; children?: Child[] }): JSXNode => {239+ return new JSXFragmentNode('', {}, props.children || [])240+}added:deno_dist/jsx/jsx-dev-runtime.ts+10 added
12345678910import type { HtmlEscapedString } from '../utils/html.ts'import { jsx } from './index.ts'import type { JSXNode } from './index.ts'export { Fragment } from './index.ts'
export function jsxDEV(tag: string | Function, props: Record<string, unknown>): JSXNode { const children = (props.children ?? []) as string | HtmlEscapedString delete props['children'] return Array.isArray(children) ? jsx(tag, props, ...children) : jsx(tag, props, children)}added:deno_dist/jsx/jsx-runtime.ts+2 added
12export { jsxDEV as jsx, Fragment } from './jsx-dev-runtime.ts'export { jsxDEV as jsxs } from './jsx-dev-runtime.ts'deleted:deno_dist/middleware/cookie/index.ts-59 removed
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859import type { Context } from '../../context.ts'import { parse, parseSigned, serialize, serializeSigned } from '../../utils/cookie.ts'import type { CookieOptions, Cookie, SignedCookie } from '../../utils/cookie.ts'
interface GetCookie { (c: Context, key: string): string | undefined (c: Context): Cookie}
interface GetSignedCookie { (c: Context, secret: string, key: string): Promise<string | undefined | false> (c: Context, secret: string): Promise<SignedCookie>}
export const getCookie: GetCookie = (c, key?) => { const cookie = c.req.raw.headers.get('Cookie') if (typeof key === 'string') { if (!cookie) return undefined const obj = parse(cookie) return obj[key] } if (!cookie) return {} const obj = parse(cookie) // eslint-disable-next-line @typescript-eslint/no-explicit-any return obj as any}
export const getSignedCookie: GetSignedCookie = async (c, secret, key?) => { const cookie = c.req.raw.headers.get('Cookie') if (typeof key === 'string') { if (!cookie) return undefined const obj = await parseSigned(cookie, secret, key) return obj[key] } if (!cookie) return {} const obj = await parseSigned(cookie, secret) // eslint-disable-next-line @typescript-eslint/no-explicit-any return obj as any}
export const setCookie = (c: Context, name: string, value: string, opt?: CookieOptions): void => { const cookie = serialize(name, value, opt) c.header('set-cookie', cookie, { append: true })}
export const setSignedCookie = async ( c: Context, name: string, value: string, secret: string, opt?: CookieOptions): Promise<void> => { const cookie = await serializeSigned(name, value, secret, opt) c.header('set-cookie', cookie, { append: true })}
export const deleteCookie = (c: Context, name: string, opt?: CookieOptions): void => { setCookie(c, name, '', { ...opt, maxAge: 0 })}deleted:deno_dist/middleware/html/index.ts-39 removed
123456789101112131415161718192021222324252627282930313233343536373839import { escapeToBuffer } from '../../utils/html.ts'import type { StringBuffer, HtmlEscaped, HtmlEscapedString } from '../../utils/html.ts'
export const raw = (value: unknown): HtmlEscapedString => { const escapedString = new String(value) as HtmlEscapedString escapedString.isEscaped = true
return escapedString}
export const html = (strings: TemplateStringsArray, ...values: unknown[]): HtmlEscapedString => { const buffer: StringBuffer = ['']
for (let i = 0, len = strings.length - 1; i < len; i++) { buffer[0] += strings[i]
const children = values[i] instanceof Array ? (values[i] as Array<unknown>).flat(Infinity) : [values[i]] for (let i = 0, len = children.length; i < len; i++) { // eslint-disable-next-line @typescript-eslint/no-explicit-any const child = children[i] as any if (typeof child === 'string') { escapeToBuffer(child, buffer) } else if (typeof child === 'boolean' || child === null || child === undefined) { continue } else if ( (typeof child === 'object' && (child as HtmlEscaped).isEscaped) || typeof child === 'number' ) { buffer[0] += child } else { escapeToBuffer(child.toString(), buffer) } } } buffer[0] += strings[strings.length - 1]
return raw(buffer[0])}deleted:deno_dist/middleware/jsx/index.test.tsx-376 removed
1-import { Hono } from '../../hono.ts'2-import { html } from '../html/index.ts'3-import { jsx, memo, Fragment } from './index.ts'4-5-interface SiteData {6- title: string7- children?: any8-}9-10-describe('JSX middleware', () => {11- let app: Hono12-13- beforeEach(() => {14- app = new Hono()15- })16-17- it('Should render HTML strings', async () => {18- app.get('/', (c) => {19- return c.html(<h1>Hello</h1>)20- })21- const res = await app.request('http://localhost/')22- expect(res.status).toBe(200)23- expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')24- expect(await res.text()).toBe('<h1>Hello</h1>')25- })26-27- it('Should be able to be used with html middleware', async () => {28- const Layout = (props: SiteData) => html`<!DOCTYPE html>29- <html>30- <head>31- <title>${props.title}</title>32- </head>33- <body>34- ${props.children}35- </body>36- </html>`37-38- const Content = (props: { siteData: SiteData; name: string }) => (39- <Layout {...props.siteData}>40- <h1>{props.name}</h1>41- </Layout>42- )43-44- app.get('/', (c) => {45- const props = {46- name: 'JSX',47- siteData: {48- title: 'with html middleware',49- },50- }51- return c.html(<Content {...props} />)52- })53- const res = await app.request('http://localhost/')54- expect(res.status).toBe(200)55- expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')56- expect(await res.text()).toBe(`<!DOCTYPE html>57- <html>58- <head>59- <title>with html middleware</title>60- </head>61- <body>62- <h1>JSX</h1>63- </body>64- </html>`)65- })66-})67-68-describe('render to string', () => {69- it('Nested array', () => {70- const template = (71- <p>72- {[[['a']], [['b']]].map((item1) =>73- item1.map((item2) => item2.map((item3) => <span>{item3}</span>))74- )}75- </p>76- )77- expect(template.toString()).toBe('<p><span>a</span><span>b</span></p>')78- })79-80- it('Empty elements are rended withtout closing tag', () => {81- const template = <input />82- expect(template.toString()).toBe('<input/>')83- })84-85- it('Props value is null', () => {86- const template = <span data-hello={null}>Hello</span>87- expect(template.toString()).toBe('<span>Hello</span>')88- })89-90- it('Props value is undefined', () => {91- const template = <span data-hello={undefined}>Hello</span>92- expect(template.toString()).toBe('<span>Hello</span>')93- })94-95- describe('dangerouslySetInnerHTML', () => {96- it('Should render dangerouslySetInnerHTML', () => {97- const template = <span dangerouslySetInnerHTML={{ __html: '" is allowed here' }}></span>98- expect(template.toString()).toBe('<span>" is allowed here</span>')99- })100-101- it('Should get an error if both dangerouslySetInnerHTML and children are specified', () => {102- expect(() =>103- (<span dangerouslySetInnerHTML={{ __html: '" is allowed here' }}>Hello</span>).toString()104- ).toThrow()105- })106- })107-108- // https://en.reactjs.org/docs/jsx-in-depth.html#booleans-null-and-undefined-are-ignored109- describe('Booleans, Null, and Undefined Are Ignored', () => {110- it.each([true, false, undefined, null])('%s', (item) => {111- expect((<span>{item}</span>).toString()).toBe('<span></span>')112- })113-114- it('falsy value', () => {115- const template = <span>{0}</span>116- expect(template.toString()).toBe('<span>0</span>')117- })118- })119-120- // https://en.reactjs.org/docs/jsx-in-depth.html#props-default-to-true121- describe('Props Default to “True”', () => {122- it('default prop value', () => {123- const template = <span data-hello>Hello</span>124- expect(template.toString()).toBe('<span data-hello="true">Hello</span>')125- })126- })127-128- // https://html.spec.whatwg.org/#attributes-3129- describe('Boolean attribute', () => {130- it('default prop value for checked', () => {131- const template = <input type='checkbox' checked />132- expect(template.toString()).toBe('<input type="checkbox" checked=""/>')133- })134-135- it('default prop value for checked={true}', () => {136- const template = <input type='checkbox' checked={true} />137- expect(template.toString()).toBe('<input type="checkbox" checked=""/>')138- })139-140- it('no prop for checked={false}', () => {141- const template = <input type='checkbox' checked={false} />142- expect(template.toString()).toBe('<input type="checkbox"/>')143- })144-145- it('default prop value for disabled', () => {146- const template = <input type='checkbox' disabled />147- expect(template.toString()).toBe('<input type="checkbox" disabled=""/>')148- })149-150- it('default prop value for disabled={true}', () => {151- const template = <input type='checkbox' disabled={true} />152- expect(template.toString()).toBe('<input type="checkbox" disabled=""/>')153- })154-155- it('no prop for disabled={false}', () => {156- const template = <input type='checkbox' disabled={false} />157- expect(template.toString()).toBe('<input type="checkbox"/>')158- })159-160- it('default prop value for readonly', () => {161- const template = <input type='checkbox' readonly />162- expect(template.toString()).toBe('<input type="checkbox" readonly=""/>')163- })164-165- it('default prop value for readonly={true}', () => {166- const template = <input type='checkbox' readonly={true} />167- expect(template.toString()).toBe('<input type="checkbox" readonly=""/>')168- })169-170- it('no prop for readonly={false}', () => {171- const template = <input type='checkbox' readonly={false} />172- expect(template.toString()).toBe('<input type="checkbox"/>')173- })174-175- it('default prop value for selected', () => {176- const template = (177- <option value='test' selected>178- Test179- </option>180- )181- expect(template.toString()).toBe('<option value="test" selected="">Test</option>')182- })183-184- it('default prop value for selected={true}', () => {185- const template = (186- <option value='test' selected={true}>187- Test188- </option>189- )190- expect(template.toString()).toBe('<option value="test" selected="">Test</option>')191- })192-193- it('no prop for selected={false}', () => {194- const template = (195- <option value='test' selected={false}>196- Test197- </option>198- )199- expect(template.toString()).toBe('<option value="test">Test</option>')200- })201-202- it('default prop value for multiple select', () => {203- const template = (204- <select multiple>205- <option>test</option>206- </select>207- )208- expect(template.toString()).toBe('<select multiple=""><option>test</option></select>')209- })210-211- it('default prop value for select multiple={true}', () => {212- const template = (213- <select multiple={true}>214- <option>test</option>215- </select>216- )217- expect(template.toString()).toBe('<select multiple=""><option>test</option></select>')218- })219-220- it('no prop for select multiple={false}', () => {221- const template = (222- <select multiple={false}>223- <option>test</option>224- </select>225- )226- expect(template.toString()).toBe('<select><option>test</option></select>')227- })228-229- it('should render "false" value properly for other non-defined keys', () => {230- const template = <input type='checkbox' testkey={false} />231- expect(template.toString()).toBe('<input type="checkbox" testkey="false"/>')232- })233-234- it('should support attributes for elements other than input', () => {235- const template = (236- <video controls autoplay>237- <source src='movie.mp4' type='video/mp4' />238- </video>239- )240- expect(template.toString()).toBe(241- '<video controls="" autoplay=""><source src="movie.mp4" type="video/mp4"/></video>'242- )243- })244- })245-246- // https://en.reactjs.org/docs/jsx-in-depth.html#functions-as-children247- describe('Functions as Children', () => {248- it('Function', () => {249- function Repeat(props: any) {250- const items = []251- for (let i = 0; i < props.numTimes; i++) {252- items.push((props.children as Function)(i))253- }254- return <div>{items}</div>255- }256-257- function ListOfTenThings() {258- return (259- <Repeat numTimes={10}>260- {(index: string) => <div key={index}>This is item {index} in the list</div>}261- </Repeat>262- )263- }264-265- const template = <ListOfTenThings />266- expect(template.toString()).toBe(267- '<div><div key="0">This is item 0 in the list</div><div key="1">This is item 1 in the list</div><div key="2">This is item 2 in the list</div><div key="3">This is item 3 in the list</div><div key="4">This is item 4 in the list</div><div key="5">This is item 5 in the list</div><div key="6">This is item 6 in the list</div><div key="7">This is item 7 in the list</div><div key="8">This is item 8 in the list</div><div key="9">This is item 9 in the list</div></div>'268- )269- })270- })271-272- describe('style attribute', () => {273- it('should convert the object to strings', () => {274- const template = (275- <h1276- style={{277- color: 'red',278- fontSize: 'small',279- }}280- >281- Hello282- </h1>283- )284- expect(template.toString()).toBe('<h1 style="color:red;font-size:small">Hello</h1>')285- })286- it('should not convert the strings', () => {287- const template = <h1 style='color:red;font-size:small'>Hello</h1>288- expect(template.toString()).toBe('<h1 style="color:red;font-size:small">Hello</h1>')289- })290- })291-})292-293-describe('memo', () => {294- it('memoized', () => {295- let counter = 0296- const Header = memo(() => <title>Test Site {counter}</title>)297- const Body = () => <span>{counter}</span>298-299- let template = (300- <html>301- <head>302- <Header />303- </head>304- <body>305- <Body />306- </body>307- </html>308- )309- expect(template.toString()).toBe(310- '<html><head><title>Test Site 0</title></head><body><span>0</span></body></html>'311- )312-313- counter++314- template = (315- <html>316- <head>317- <Header />318- </head>319- <body>320- <Body />321- </body>322- </html>323- )324- expect(template.toString()).toBe(325- '<html><head><title>Test Site 0</title></head><body><span>1</span></body></html>'326- )327- })328-329- it('props are updated', () => {330- const Body = memo(({ counter }: { counter: number }) => <span>{counter}</span>)331-332- let template = <Body counter={0} />333- expect(template.toString()).toBe('<span>0</span>')334-335- template = <Body counter={1} />336- expect(template.toString()).toBe('<span>1</span>')337- })338-339- it('custom propsAreEqual', () => {340- const Body = memo(341- ({ counter }: { counter: number; refresh?: boolean }) => <span>{counter}</span>,342- (_, nextProps) => (typeof nextProps.refresh == 'undefined' ? true : !nextProps.refresh)343- )344-345- let template = <Body counter={0} />346- expect(template.toString()).toBe('<span>0</span>')347-348- template = <Body counter={1} />349- expect(template.toString()).toBe('<span>0</span>')350-351- template = <Body counter={2} refresh={true} />352- expect(template.toString()).toBe('<span>2</span>')353- })354-})355-356-describe('Fragment', () => {357- it('Should render children', () => {358- const template = (359- <>360- <p>1</p>361- <p>2</p>362- </>363- )364- expect(template.toString()).toBe('<p>1</p><p>2</p>')365- })366-367- it('Should render nothing for empty Fragment', () => {368- const template = <></>369- expect(template.toString()).toBe('')370- })371-372- it('Should render nothing for undefined', () => {373- const template = <>{undefined}</>374- expect(template.toString()).toBe('')375- })376-})deleted:deno_dist/middleware/jsx/index.ts-240 removed
1-import { escapeToBuffer } from '../../utils/html.ts'2-import type { StringBuffer, HtmlEscaped, HtmlEscapedString } from '../../utils/html.ts'3-4-// eslint-disable-next-line @typescript-eslint/no-explicit-any5-type Props = Record<string, any>6-7-declare global {8- // eslint-disable-next-line @typescript-eslint/no-namespace9- namespace JSX {10- type Element = HtmlEscapedString11- interface ElementChildrenAttribute {12- children: Child13- }14- interface IntrinsicElements {15- [tagName: string]: Props16- }17- }18-}19-20-const emptyTags = [21- 'area',22- 'base',23- 'br',24- 'col',25- 'embed',26- 'hr',27- 'img',28- 'input',29- 'keygen',30- 'link',31- 'meta',32- 'param',33- 'source',34- 'track',35- 'wbr',36-]37-const booleanAttributes = [38- 'allowfullscreen',39- 'async',40- 'autofocus',41- 'autoplay',42- 'checked',43- 'controls',44- 'default',45- 'defer',46- 'disabled',47- 'formnovalidate',48- 'hidden',49- 'inert',50- 'ismap',51- 'itemscope',52- 'loop',53- 'multiple',54- 'muted',55- 'nomodule',56- 'novalidate',57- 'open',58- 'playsinline',59- 'readonly',60- 'required',61- 'reversed',62- 'selected',63-]64-65-const childrenToStringToBuffer = (children: Child[], buffer: StringBuffer): void => {66- for (let i = 0, len = children.length; i < len; i++) {67- const child = children[i]68- if (typeof child === 'string') {69- escapeToBuffer(child, buffer)70- } else if (typeof child === 'boolean' || child === null || child === undefined) {71- continue72- } else if (child instanceof JSXNode) {73- child.toStringToBuffer(buffer)74- } else if (75- typeof child === 'number' ||76- (child as unknown as { isEscaped: boolean }).isEscaped77- ) {78- buffer[0] += child79- } else {80- // `child` type is `Child[]`, so stringify recursively81- childrenToStringToBuffer(child, buffer)82- }83- }84-}85-86-type Child = string | number | JSXNode | Child[]87-export class JSXNode implements HtmlEscaped {88- tag: string | Function89- props: Props90- children: Child[]91- isEscaped: true = true as const92- constructor(tag: string | Function, props: Props, children: Child[]) {93- this.tag = tag94- this.props = props95- this.children = children96- }97-98- toString(): string {99- const buffer: StringBuffer = ['']100- this.toStringToBuffer(buffer)101- return buffer[0]102- }103-104- toStringToBuffer(buffer: StringBuffer): void {105- const tag = this.tag as string106- const props = this.props107- let { children } = this108-109- buffer[0] += `<${tag}`110-111- const propsKeys = Object.keys(props || {})112-113- for (let i = 0, len = propsKeys.length; i < len; i++) {114- const key = propsKeys[i]115- const v = props[key]116- // object to style strings117- if (key === 'style' && typeof v === 'object') {118- const styles = Object.keys(v)119- .map((k) => `${k}:${v[k]}`)120- .join(';')121- .replace(/[A-Z]/g, (match) => `-${match.toLowerCase()}`)122- buffer[0] += ` style="${styles}"`123- } else if (typeof v === 'string') {124- buffer[0] += ` ${key}="`125- escapeToBuffer(v, buffer)126- buffer[0] += '"'127- } else if (typeof v === 'number') {128- buffer[0] += ` ${key}="${v}"`129- } else if (v === null || v === undefined) {130- // Do nothing131- } else if (typeof v === 'boolean' && booleanAttributes.includes(key)) {132- if (v) {133- buffer[0] += ` ${key}=""`134- }135- } else if (key === 'dangerouslySetInnerHTML') {136- if (children.length > 0) {137- throw 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.'138- }139-140- const escapedString = new String(v.__html) as HtmlEscapedString141- escapedString.isEscaped = true142- children = [escapedString]143- } else {144- buffer[0] += ` ${key}="`145- escapeToBuffer(v.toString(), buffer)146- buffer[0] += '"'147- }148- }149-150- if (emptyTags.includes(tag as string)) {151- buffer[0] += '/>'152- return153- }154-155- buffer[0] += '>'156-157- childrenToStringToBuffer(children, buffer)158-159- buffer[0] += `</${tag}>`160- }161-}162-163-class JSXFunctionNode extends JSXNode {164- toStringToBuffer(buffer: StringBuffer): void {165- const { children } = this166-167- const res = (this.tag as Function).call(null, {168- ...this.props,169- children: children.length <= 1 ? children[0] : children,170- })171-172- if (res instanceof JSXNode) {173- res.toStringToBuffer(buffer)174- } else if (typeof res === 'number' || (res as HtmlEscaped).isEscaped) {175- buffer[0] += res176- } else {177- escapeToBuffer(res, buffer)178- }179- }180-}181-182-class JSXFragmentNode extends JSXNode {183- toStringToBuffer(buffer: StringBuffer): void {184- childrenToStringToBuffer(this.children, buffer)185- }186-}187-188-export { jsxFn as jsx }189-const jsxFn = (190- tag: string | Function,191- props: Props,192- ...children: (string | HtmlEscapedString)[]193-): JSXNode => {194- if (typeof tag === 'function') {195- return new JSXFunctionNode(tag, props, children)196- } else {197- return new JSXNode(tag, props, children)198- }199-}200-201-type FC<T = Props> = (props: T) => HtmlEscapedString202-203-const shallowEqual = (a: Props, b: Props): boolean => {204- if (a === b) {205- return true206- }207-208- const aKeys = Object.keys(a)209- const bKeys = Object.keys(b)210- if (aKeys.length !== bKeys.length) {211- return false212- }213-214- for (let i = 0, len = aKeys.length; i < len; i++) {215- if (a[aKeys[i]] !== b[aKeys[i]]) {216- return false217- }218- }219-220- return true221-}222-223-export const memo = <T>(224- component: FC<T>,225- propsAreEqual: (prevProps: Readonly<T>, nextProps: Readonly<T>) => boolean = shallowEqual226-): FC<T> => {227- let computed = undefined228- let prevProps: T | undefined = undefined229- return ((props: T): HtmlEscapedString => {230- if (prevProps && !propsAreEqual(prevProps, props)) {231- computed = undefined232- }233- prevProps = props234- return (computed ||= component(props))235- }) as FC<T>236-}237-238-export const Fragment = (props: { key?: string; children?: Child[] }): JSXNode => {239- return new JSXFragmentNode('', {}, props.children || [])240-}deleted:deno_dist/middleware/jsx/jsx-dev-runtime.ts-10 removed
12345678910import type { HtmlEscapedString } from '../../utils/html.ts'import { jsx } from './index.ts'import type { JSXNode } from './index.ts'export { Fragment } from './index.ts'
export function jsxDEV(tag: string | Function, props: Record<string, unknown>): JSXNode { const children = (props.children ?? []) as string | HtmlEscapedString delete props['children'] return Array.isArray(children) ? jsx(tag, props, ...children) : jsx(tag, props, children)}deleted:deno_dist/middleware/jsx/jsx-runtime.ts-2 removed
1-export { jsxDEV as jsx, Fragment } from './jsx-dev-runtime.ts'2-export { jsxDEV as jsxs } from './jsx-dev-runtime.ts'modified:deno_dist/validator/validator.ts+1 added-1 removed
1 import type { Context } from '../context.ts'2-import { getCookie } from '../middleware/cookie/index.ts'2+import { getCookie } from '../helper/cookie/index.ts'3 import type { Env, ValidationTargets, MiddlewareHandler } from '../types.ts'4 5 type ValidationTargetKeysWithBody = 'form' | 'json'6 type ValidationTargetByMethod<M> = M extends 'get' | 'head' // GET and HEAD request must not have a body content.92 unmodified linesdeleted:deno_dist/adapter.ts-30 removed
1-import type { Context } from './context.ts'2-3-export const env = <T extends Record<string, string>, C extends Context = Context<{}>>(4- c: C5-): T & C['env'] => {6- // eslint-disable-next-line @typescript-eslint/no-explicit-any7- const global = globalThis as any8-9- if (10- c.runtime === 'bun' ||11- c.runtime === 'node' ||12- c.runtime === 'edge-light' ||13- c.runtime === 'lagon'14- ) {15- return global?.process?.env as T16- }17- if (c.runtime === 'deno') {18- // eslint-disable-next-line @typescript-eslint/ban-ts-comment19- // @ts-ignore20- return Deno.env.toObject()21- }22- if (c.runtime === 'workerd') {23- return c.env24- }25- if (c.runtime === 'fastly') {26- // On Fastly Compute@Edge, you can use the ConfigStore to manage user-defined data.27- return {} as T28- }29- return {} as T30-}modified:deno_dist/context.ts+12 added
356 unmodified lines357 // @ts-ignore358 return this.notFoundHandler(this)359 }360 361+ /** @deprecated362+ * Use `getRuntimeKey()` exported from `hono/adapter` instead of `c.runtime()`. The `c.runtime()` will be removed in v4.363+ *364+ * @example365+ *366+ * import { getRuntimeKey } from 'hono/adapter'367+ * // ...368+ * app.get('/', (c) => {369+ * const key = getRuntimeKey()370+ * //...371+ * })372+ */373 get runtime(): Runtime {374 // eslint-disable-next-line @typescript-eslint/no-explicit-any375 const global = globalThis as any376 31 unmodified linesadded:deno_dist/helper.ts+4 added
1+// This file is for Deno to import helpers from `hono/helper.ts`.2+export * from './helper/cookie/index.ts'3+export * from './helper/html/index.ts'4+export * from './helper/adapter/index.ts'modified:deno_dist/middleware.ts+4 added-4 removed
1-// Middleware1+// This file is for Deno to import middleware from `hono/middleware.ts`.2 export * from './middleware/basic-auth/index.ts'3 export * from './middleware/bearer-auth/index.ts'4 export * from './middleware/cache/index.ts'5-export * from './middleware/cookie/index.ts'5+export * from './helper/cookie/index.ts' // will be moved to helper.ts in v46 export * from './middleware/compress/index.ts'7 export * from './middleware/cors/index.ts'8 export * from './middleware/etag/index.ts'9-export * from './middleware/html/index.ts'10-export * from './middleware/jsx/index.ts'9+export * from './helper/html/index.ts' // will be moved to helper.ts in v410+export * from './jsx/index.ts'11 export * from './middleware/jwt/index.ts'12 export * from './middleware/logger/index.ts'13 export * from './middleware/powered-by/index.ts'14 export * from './middleware/timing/index.ts'2 unmodified linesmodified:runtime_tests/bun/index.test.tsx+4 added-4 removed
1 import { describe, expect, it } from 'bun:test'2-import { env } from '../../src/adapter'2 import { serveStatic } from '../../src/adapter/bun'3 import { Context } from '../../src/context'4+import { env, getRuntimeKey } from '../../src/helper/adapter'5 import { Hono } from '../../src/index'6 import { basicAuth } from '../../src/middleware/basic-auth'7 import { jwt } from '../../src/middleware/jwt'8+import { HonoRequest } from '../../src/request'9 10 // Test just only minimal patterns.11 // Because others are tested well in Cloudflare Workers environment already.12 14 unmodified lines27 expect(res.headers.get('x-query')).toBe('bar')28 })29 30 it('returns current runtime (bun)', async () => {30- const c = new Context(new Request('http://localhost/'))31- expect(c.runtime).toBe('bun')31+ expect(getRuntimeKey()).toBe('bun')32 })33 })34 35 describe('Environment Variables', () => {36 it('Should return the environment variable', async () => {37- const c = new Context(new Request('http://localhost/'))37+ const c = new Context(new HonoRequest(new Request('http://localhost/')))38 const { NAME } = env<{ NAME: string }>(c)39 expect(NAME).toBe('Bun')40 })41 })157 unmodified linesmodified:runtime_tests/deno/hono.test.ts+2 added-3 removed
1-import { env } from '../../deno_dist/adapter.ts'1 import { Context } from '../../deno_dist/context.ts'2+import { env, getRuntimeKey } from '../../deno_dist/helper.ts'3 import { Hono } from '../../deno_dist/mod.ts'4 import { HonoRequest } from '../../deno_dist/request.ts'5 import { assertEquals } from './deps.ts'6 15 unmodified lines22 assertEquals(res.headers.get('x-query'), 'bar')23 })24 25 Deno.test('runtime', () => {26- const c = new Context(new HonoRequest(new Request('http://localhost/')))27- assertEquals(c.runtime, 'deno')26+ assertEquals(getRuntimeKey(), 'deno')27 })28 29 Deno.test('environment variables', () => {30 const c = new Context(new HonoRequest(new Request('http://localhost/')))3 unmodified linesmodified:runtime_tests/fastly/index.test.ts+2 added-1 removed
1 import { SHA256 } from 'crypto-js'2+import { getRuntimeKey } from '../../src/helper/adapter'3 import { Hono } from '../../src/index'4 import { basicAuth } from '../../src/middleware/basic-auth'5 import { jwt } from '../../src/middleware/jwt'6 5 unmodified lines12 13 describe('Hello World', () => {14 app.get('/', (c) => c.text('Hello! Compute!'))15 app.get('/runtime-name', (c) => {15- return c.text(c.runtime)16+ return c.text(getRuntimeKey())17 })18 19 it('Should return 200', async () => {20 const res = await app.request('http://localhost/')77 unmodified linesmodified:runtime_tests/lagon/index.ts+2 added-2 removed
1 import { Hono } from '../../src'2-import { env } from '../../src/adapter'2+import { env, getRuntimeKey } from '../../src/helper/adapter'3 import { HTTPException } from '../../src/http-exception'4 import { basicAuth } from '../../src/middleware/basic-auth'5 import { bearerAuth } from '../../src/middleware/bearer-auth'6 import { etag } from '../../src/middleware/etag'58 unmodified lines65 app.get('/', (c) => c.text('Hono!!'))66 // Use Response object directly67 app.get('/hello', () => new Response('This is /hello'))68 69-app.get('/runtime', (c) => new Response(c.runtime))69+app.get('/runtime', () => new Response(getRuntimeKey()))70 71 // Named parameter72 app.get('/entry/:id', (c) => {73 const id = c.req.param('id')59 unmodified linesmodified:runtime_tests/node/index.test.ts+2 added-2 removed
1 import { createAdaptorServer } from '@hono/node-server'2 import request from 'supertest'3 import { Hono } from '../../src'4-import { env } from '../../src/adapter'4 import { Context } from '../../src/context'5+import { env, getRuntimeKey } from '../../src/helper/adapter'6 import { basicAuth } from '../../src/middleware/basic-auth'7 import { jwt } from '../../src/middleware/jwt'8 import { HonoRequest } from '../../src/request'9 6 unmodified lines16 app.get('/', (c) => {17 return c.text('Hello! Node.js!')18 })19 app.get('/runtime-name', (c) => {20- return c.text(c.runtime)20+ return c.text(getRuntimeKey())21 })22 23 const server = createAdaptorServer(app)24 74 unmodified linesmodified:runtime_tests/wrangler/index.ts+1 added-1 removed
1-import { env } from '../../src/adapter'1+import { env } from '../../src/helper/adapter'2 import { Hono } from '../../src/hono'3 4 const app = new Hono()5 8 unmodified linesadded:src/helper/adapter/index.ts+65 added
1+import type { Context } from '../../context'2+3+export const env = <T extends Record<string, string>, C extends Context = Context<{}>>(4+ c: C5+): T & C['env'] => {6+ // eslint-disable-next-line @typescript-eslint/no-explicit-any7+ const global = globalThis as any8+9+ if (10+ c.runtime === 'bun' ||11+ c.runtime === 'node' ||12+ c.runtime === 'edge-light' ||13+ c.runtime === 'lagon'14+ ) {15+ return global?.process?.env as T16+ }17+ if (c.runtime === 'deno') {18+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment19+ // @ts-ignore20+ return Deno.env.toObject()21+ }22+ if (c.runtime === 'workerd') {23+ return c.env24+ }25+ if (c.runtime === 'fastly') {26+ // On Fastly Compute@Edge, you can use the ConfigStore to manage user-defined data.27+ return {} as T28+ }29+ return {} as T30+}31+32+export const getRuntimeKey = () => {33+ // eslint-disable-next-line @typescript-eslint/no-explicit-any34+ const global = globalThis as any35+36+ if (global?.Deno !== undefined) {37+ return 'deno'38+ }39+40+ if (global?.Bun !== undefined) {41+ return 'bun'42+ }43+44+ if (typeof global?.WebSocketPair === 'function') {45+ return 'workerd'46+ }47+48+ if (typeof global?.EdgeRuntime === 'string') {49+ return 'edge-light'50+ }51+52+ if (global?.fastly !== undefined) {53+ return 'fastly'54+ }55+56+ if (global?.__lagon__ !== undefined) {57+ return 'lagon'58+ }59+60+ if (global?.process?.release?.name === 'node') {61+ return 'node'62+ }63+64+ return 'other'65+}added:src/helper/cookie/index.test.ts+251 added
1+import { Hono } from '../../hono'2+import { getCookie, getSignedCookie, setCookie, setSignedCookie, deleteCookie } from '.'3+4+describe('Cookie Middleware', () => {5+ describe('Parse cookie', () => {6+ const apps: Record<string, Hono> = {}7+ apps['get by name'] = (() => {8+ const app = new Hono()9+10+ app.get('/cookie', (c) => {11+ const yummyCookie = getCookie(c, 'yummy_cookie')12+ const tastyCookie = getCookie(c, 'tasty_cookie')13+ const res = new Response('Good cookie')14+ if (yummyCookie && tastyCookie) {15+ res.headers.set('Yummy-Cookie', yummyCookie)16+ res.headers.set('Tasty-Cookie', tastyCookie)17+ }18+ return res19+ })20+21+ return app22+ })()23+24+ apps['get all as an object'] = (() => {25+ const app = new Hono()26+27+ app.get('/cookie', (c) => {28+ const { yummy_cookie: yummyCookie, tasty_cookie: tastyCookie } = getCookie(c)29+ const res = new Response('Good cookie')30+ res.headers.set('Yummy-Cookie', yummyCookie)31+ res.headers.set('Tasty-Cookie', tastyCookie)32+ return res33+ })34+35+ return app36+ })()37+38+ describe.each(Object.keys(apps))('%s', (name) => {39+ const app = apps[name]40+ it('Parse cookie with getCookie()', async () => {41+ const req = new Request('http://localhost/cookie')42+ const cookieString = 'yummy_cookie=choco; tasty_cookie = strawberry'43+ req.headers.set('Cookie', cookieString)44+ const res = await app.request(req)45+46+ expect(res.headers.get('Yummy-Cookie')).toBe('choco')47+ expect(res.headers.get('Tasty-Cookie')).toBe('strawberry')48+ })49+ })50+51+ const app = new Hono()52+53+ app.get('/cookie-signed-get-all', async (c) => {54+ const secret = 'secret lucky charm'55+ const { fortune_cookie: fortuneCookie, fruit_cookie: fruitCookie } = await getSignedCookie(56+ c,57+ secret58+ )59+ const res = new Response('Signed fortune cookie')60+ if (typeof fortuneCookie !== 'undefined' && typeof fruitCookie !== 'undefined') {61+ // just examples for tests sake62+ res.headers.set('Fortune-Cookie', fortuneCookie || 'INVALID')63+ res.headers.set('Fruit-Cookie', fruitCookie || 'INVALID')64+ }65+ return res66+ })67+68+ app.get('/cookie-signed-get-one', async (c) => {69+ const secret = 'secret lucky charm'70+ const fortuneCookie = await getSignedCookie(c, secret, 'fortune_cookie')71+ const res = new Response('Signed fortune cookie')72+ if (typeof fortuneCookie !== 'undefined') {73+ // just an example for tests sake74+ res.headers.set('Fortune-Cookie', fortuneCookie || 'INVALID')75+ }76+ return res77+ })78+79+ it('Get signed cookies', async () => {80+ const req = new Request('http://localhost/cookie-signed-get-all')81+ const cookieString =82+ 'fortune_cookie=lots-of-money.UO6vMygDM6NCDU4LdvBnzdVb2Xcdj+h+ZTnmS8X7iH8%3D; fruit_cookie=mango.lRwgtW9ooM9%2Fd9ZZA%2FInNRG64CbQsfWGXQyFLPM9520%3D'83+ req.headers.set('Cookie', cookieString)84+ const res = await app.request(req)85+ expect(res.headers.get('Fortune-Cookie')).toBe('lots-of-money')86+ expect(res.headers.get('Fruit-Cookie')).toBe('mango')87+ })88+89+ it('Get signed cookies invalid signature', async () => {90+ const req = new Request('http://localhost/cookie-signed-get-all')91+ // fruit_cookie has invalid signature92+ const cookieString =93+ 'fortune_cookie=lots-of-money.UO6vMygDM6NCDU4LdvBnzdVb2Xcdj+h+ZTnmS8X7iH8%3D; fruit_cookie=mango.LAa7RX43t2vCrLNcKmNG65H41OkyV02sraRPuY5RuVg%3D'94+ req.headers.set('Cookie', cookieString)95+ const res = await app.request(req)96+ expect(res.headers.get('Fortune-Cookie')).toBe('lots-of-money')97+ expect(res.headers.get('Fruit-Cookie')).toBe('INVALID')98+ })99+100+ it('Get signed cookie', async () => {101+ const req = new Request('http://localhost/cookie-signed-get-one')102+ const cookieString =103+ 'fortune_cookie=lots-of-money.UO6vMygDM6NCDU4LdvBnzdVb2Xcdj+h+ZTnmS8X7iH8%3D; fruit_cookie=mango.lRwgtW9ooM9%2Fd9ZZA%2FInNRG64CbQsfWGXQyFLPM9520%3D'104+ req.headers.set('Cookie', cookieString)105+ const res = await app.request(req)106+ expect(res.headers.get('Fortune-Cookie')).toBe('lots-of-money')107+ })108+109+ it('Get signed cookie witn invalid signature', async () => {110+ const req = new Request('http://localhost/cookie-signed-get-one')111+ // fortune_cookie has invalid signature112+ const cookieString =113+ 'fortune_cookie=lots-of-money.LAa7RX43t2vCrLNcKmNG65H41OkyV02sraRPuY5RuVg=; fruit_cookie=mango.lRwgtW9ooM9%2Fd9ZZA%2FInNRG64CbQsfWGXQyFLPM9520%3D'114+ req.headers.set('Cookie', cookieString)115+ const res = await app.request(req)116+ expect(res.headers.get('Fortune-Cookie')).toBe('INVALID')117+ })118+ })119+120+ describe('Set cookie', () => {121+ const app = new Hono()122+123+ app.get('/set-cookie', (c) => {124+ setCookie(c, 'delicious_cookie', 'macha')125+ return c.text('Give cookie')126+ })127+128+ it('Set cookie with setCookie()', async () => {129+ const res = await app.request('http://localhost/set-cookie')130+ expect(res.status).toBe(200)131+ const header = res.headers.get('Set-Cookie')132+ expect(header).toBe('delicious_cookie=macha')133+ })134+135+ app.get('/set-signed-cookie', async (c) => {136+ const secret = 'secret chocolate chips'137+ await setSignedCookie(c, 'delicious_cookie', 'macha', secret)138+ return c.text('Give signed cookie')139+ })140+141+ it('Set signed cookie with setSignedCookie()', async () => {142+ const res = await app.request('http://localhost/set-signed-cookie')143+ expect(res.status).toBe(200)144+ const header = res.headers.get('Set-Cookie')145+ expect(header).toBe('delicious_cookie=macha.diubJPY8O7hI1pLa42QSfkPiyDWQ0I4DnlACH%2FN2HaA%3D')146+ })147+148+ app.get('/set-cookie-complex', (c) => {149+ setCookie(c, 'great_cookie', 'banana', {150+ path: '/',151+ secure: true,152+ domain: 'example.com',153+ httpOnly: true,154+ maxAge: 1000,155+ expires: new Date(Date.UTC(2000, 11, 24, 10, 30, 59, 900)),156+ sameSite: 'Strict',157+ })158+ return c.text('Give cookie')159+ })160+161+ it('Complex pattern', async () => {162+ const res = await app.request('http://localhost/set-cookie-complex')163+ expect(res.status).toBe(200)164+ const header = res.headers.get('Set-Cookie')165+ expect(header).toBe(166+ 'great_cookie=banana; Max-Age=1000; Domain=example.com; Path=/; Expires=Sun, 24 Dec 2000 10:30:59 GMT; HttpOnly; Secure; SameSite=Strict'167+ )168+ })169+170+ app.get('/set-signed-cookie-complex', async (c) => {171+ const secret = 'secret chocolate chips'172+ await setSignedCookie(c, 'great_cookie', 'banana', secret, {173+ path: '/',174+ secure: true,175+ domain: 'example.com',176+ httpOnly: true,177+ maxAge: 1000,178+ expires: new Date(Date.UTC(2000, 11, 24, 10, 30, 59, 900)),179+ sameSite: 'Strict',180+ })181+ return c.text('Give signed cookie')182+ })183+184+ it('Complex pattern (signed)', async () => {185+ const res = await app.request('http://localhost/set-signed-cookie-complex')186+ expect(res.status).toBe(200)187+ const header = res.headers.get('Set-Cookie')188+ expect(header).toBe(189+ 'great_cookie=banana.hSo6gB7YT2db0WBiEAakEmh7dtwEL0DSp76G23WvHuQ%3D; Max-Age=1000; Domain=example.com; Path=/; Expires=Sun, 24 Dec 2000 10:30:59 GMT; HttpOnly; Secure; SameSite=Strict'190+ )191+ })192+193+ app.get('/set-cookie-multiple', (c) => {194+ setCookie(c, 'delicious_cookie', 'macha')195+ setCookie(c, 'delicious_cookie', 'choco')196+ return c.text('Give cookie')197+ })198+199+ it('Multiple values', async () => {200+ const res = await app.request('http://localhost/set-cookie-multiple')201+ expect(res.status).toBe(200)202+ const header = res.headers.get('Set-Cookie')203+ expect(header).toBe('delicious_cookie=macha, delicious_cookie=choco')204+ })205+ })206+207+ describe('Delete cookie', () => {208+ const app = new Hono()209+210+ app.get('/delete-cookie', (c) => {211+ deleteCookie(c, 'delicious_cookie')212+ return c.text('Give cookie')213+ })214+215+ it('Delete cookie', async () => {216+ const res2 = await app.request('http://localhost/delete-cookie')217+ expect(res2.status).toBe(200)218+ const header2 = res2.headers.get('Set-Cookie')219+ expect(header2).toBe('delicious_cookie=; Max-Age=0')220+ })221+222+ app.get('/delete-cookie-multiple', (c) => {223+ deleteCookie(c, 'delicious_cookie')224+ deleteCookie(c, 'delicious_cookie2')225+ return c.text('Give cookie')226+ })227+228+ it('Delete multile cookies', async () => {229+ const res2 = await app.request('http://localhost/delete-cookie-multiple')230+ expect(res2.status).toBe(200)231+ const header2 = res2.headers.get('Set-Cookie')232+ expect(header2).toBe('delicious_cookie=; Max-Age=0, delicious_cookie2=; Max-Age=0')233+ })234+235+ app.get('/delete-cookie-with-options', (c) => {236+ deleteCookie(c, 'delicious_cookie', {237+ path: '/',238+ secure: true,239+ domain: 'example.com',240+ })241+ return c.text('Give cookie')242+ })243+244+ it('Delete cookie with options', async () => {245+ const res2 = await app.request('http://localhost/delete-cookie-with-options')246+ expect(res2.status).toBe(200)247+ const header2 = res2.headers.get('Set-Cookie')248+ expect(header2).toBe('delicious_cookie=; Max-Age=0; Domain=example.com; Path=/; Secure')249+ })250+ })251+})added:src/helper/cookie/index.ts+59 added
1+import type { Context } from '../../context'2+import { parse, parseSigned, serialize, serializeSigned } from '../../utils/cookie'3+import type { CookieOptions, Cookie, SignedCookie } from '../../utils/cookie'4+5+interface GetCookie {6+ (c: Context, key: string): string | undefined7+ (c: Context): Cookie8+}9+10+interface GetSignedCookie {11+ (c: Context, secret: string, key: string): Promise<string | undefined | false>12+ (c: Context, secret: string): Promise<SignedCookie>13+}14+15+export const getCookie: GetCookie = (c, key?) => {16+ const cookie = c.req.raw.headers.get('Cookie')17+ if (typeof key === 'string') {18+ if (!cookie) return undefined19+ const obj = parse(cookie)20+ return obj[key]21+ }22+ if (!cookie) return {}23+ const obj = parse(cookie)24+ // eslint-disable-next-line @typescript-eslint/no-explicit-any25+ return obj as any26+}27+28+export const getSignedCookie: GetSignedCookie = async (c, secret, key?) => {29+ const cookie = c.req.raw.headers.get('Cookie')30+ if (typeof key === 'string') {31+ if (!cookie) return undefined32+ const obj = await parseSigned(cookie, secret, key)33+ return obj[key]34+ }35+ if (!cookie) return {}36+ const obj = await parseSigned(cookie, secret)37+ // eslint-disable-next-line @typescript-eslint/no-explicit-any38+ return obj as any39+}40+41+export const setCookie = (c: Context, name: string, value: string, opt?: CookieOptions): void => {42+ const cookie = serialize(name, value, opt)43+ c.header('set-cookie', cookie, { append: true })44+}45+46+export const setSignedCookie = async (47+ c: Context,48+ name: string,49+ value: string,50+ secret: string,51+ opt?: CookieOptions52+): Promise<void> => {53+ const cookie = await serializeSigned(name, value, secret, opt)54+ c.header('set-cookie', cookie, { append: true })55+}56+57+export const deleteCookie = (c: Context, name: string, opt?: CookieOptions): void => {58+ setCookie(c, name, '', { ...opt, maxAge: 0 })59+}added:src/helper/html/index.test.ts+41 added
1+import { html, raw } from '.'2+3+describe('Tagged Template Literals', () => {4+ it('Should escape special characters', () => {5+ const name = 'John "Johnny" Smith'6+ // eslint-disable-next-line quotes7+ expect(html`<p>I'm ${name}.</p>`.toString()).toBe("<p>I'm John "Johnny" Smith.</p>")8+ })9+10+ describe('Booleans, Null, and Undefined Are Ignored', () => {11+ it.each([true, false, undefined, null])('%s', (item) => {12+ expect(html`${item}`.toString()).toBe('')13+ })14+15+ it('falsy value', () => {16+ expect(html`${0}`.toString()).toBe('0')17+ })18+ })19+20+ it('Should call $array.flat(Infinity)', () => {21+ const values = [22+ 'Name:',23+ ['John "Johnny" Smith', undefined, null],24+ ' Contact:',25+ [html`<a href="http://example.com/">My Website</a>`],26+ ]27+ expect(html`<p>${values}</p>`.toString()).toBe(28+ '<p>Name:John "Johnny" Smith Contact:<a href="http://example.com/">My Website</a></p>'29+ )30+ })31+})32+33+describe('raw', () => {34+ it('Should be marked as escaped.', () => {35+ const name = 'John "Johnny" Smith'36+ expect(html`<p>I'm ${raw(name)}.</p>`.toString()).toBe(37+ // eslint-disable-next-line quotes38+ "<p>I'm John "Johnny" Smith.</p>"39+ )40+ })41+})added:src/helper/html/index.ts+39 added
1+import { escapeToBuffer } from '../../utils/html'2+import type { StringBuffer, HtmlEscaped, HtmlEscapedString } from '../../utils/html'3+4+export const raw = (value: unknown): HtmlEscapedString => {5+ const escapedString = new String(value) as HtmlEscapedString6+ escapedString.isEscaped = true7+8+ return escapedString9+}10+11+export const html = (strings: TemplateStringsArray, ...values: unknown[]): HtmlEscapedString => {12+ const buffer: StringBuffer = ['']13+14+ for (let i = 0, len = strings.length - 1; i < len; i++) {15+ buffer[0] += strings[i]16+17+ const children =18+ values[i] instanceof Array ? (values[i] as Array<unknown>).flat(Infinity) : [values[i]]19+ for (let i = 0, len = children.length; i < len; i++) {20+ // eslint-disable-next-line @typescript-eslint/no-explicit-any21+ const child = children[i] as any22+ if (typeof child === 'string') {23+ escapeToBuffer(child, buffer)24+ } else if (typeof child === 'boolean' || child === null || child === undefined) {25+ continue26+ } else if (27+ (typeof child === 'object' && (child as HtmlEscaped).isEscaped) ||28+ typeof child === 'number'29+ ) {30+ buffer[0] += child31+ } else {32+ escapeToBuffer(child.toString(), buffer)33+ }34+ }35+ }36+ buffer[0] += strings[strings.length - 1]37+38+ return raw(buffer[0])39+}added:src/jsx/index.test.tsx+376 added
1+import { html } from '../helper/html'2+import { Hono } from '../hono'3+import { jsx, memo, Fragment } from './index'4+5+interface SiteData {6+ title: string7+ children?: any8+}9+10+describe('JSX middleware', () => {11+ let app: Hono12+13+ beforeEach(() => {14+ app = new Hono()15+ })16+17+ it('Should render HTML strings', async () => {18+ app.get('/', (c) => {19+ return c.html(<h1>Hello</h1>)20+ })21+ const res = await app.request('http://localhost/')22+ expect(res.status).toBe(200)23+ expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')24+ expect(await res.text()).toBe('<h1>Hello</h1>')25+ })26+27+ it('Should be able to be used with html middleware', async () => {28+ const Layout = (props: SiteData) => html`<!DOCTYPE html>29+ <html>30+ <head>31+ <title>${props.title}</title>32+ </head>33+ <body>34+ ${props.children}35+ </body>36+ </html>`37+38+ const Content = (props: { siteData: SiteData; name: string }) => (39+ <Layout {...props.siteData}>40+ <h1>{props.name}</h1>41+ </Layout>42+ )43+44+ app.get('/', (c) => {45+ const props = {46+ name: 'JSX',47+ siteData: {48+ title: 'with html middleware',49+ },50+ }51+ return c.html(<Content {...props} />)52+ })53+ const res = await app.request('http://localhost/')54+ expect(res.status).toBe(200)55+ expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')56+ expect(await res.text()).toBe(`<!DOCTYPE html>57+ <html>58+ <head>59+ <title>with html middleware</title>60+ </head>61+ <body>62+ <h1>JSX</h1>63+ </body>64+ </html>`)65+ })66+})67+68+describe('render to string', () => {69+ it('Nested array', () => {70+ const template = (71+ <p>72+ {[[['a']], [['b']]].map((item1) =>73+ item1.map((item2) => item2.map((item3) => <span>{item3}</span>))74+ )}75+ </p>76+ )77+ expect(template.toString()).toBe('<p><span>a</span><span>b</span></p>')78+ })79+80+ it('Empty elements are rended withtout closing tag', () => {81+ const template = <input />82+ expect(template.toString()).toBe('<input/>')83+ })84+85+ it('Props value is null', () => {86+ const template = <span data-hello={null}>Hello</span>87+ expect(template.toString()).toBe('<span>Hello</span>')88+ })89+90+ it('Props value is undefined', () => {91+ const template = <span data-hello={undefined}>Hello</span>92+ expect(template.toString()).toBe('<span>Hello</span>')93+ })94+95+ describe('dangerouslySetInnerHTML', () => {96+ it('Should render dangerouslySetInnerHTML', () => {97+ const template = <span dangerouslySetInnerHTML={{ __html: '" is allowed here' }}></span>98+ expect(template.toString()).toBe('<span>" is allowed here</span>')99+ })100+101+ it('Should get an error if both dangerouslySetInnerHTML and children are specified', () => {102+ expect(() =>103+ (<span dangerouslySetInnerHTML={{ __html: '" is allowed here' }}>Hello</span>).toString()104+ ).toThrow()105+ })106+ })107+108+ // https://en.reactjs.org/docs/jsx-in-depth.html#booleans-null-and-undefined-are-ignored109+ describe('Booleans, Null, and Undefined Are Ignored', () => {110+ it.each([true, false, undefined, null])('%s', (item) => {111+ expect((<span>{item}</span>).toString()).toBe('<span></span>')112+ })113+114+ it('falsy value', () => {115+ const template = <span>{0}</span>116+ expect(template.toString()).toBe('<span>0</span>')117+ })118+ })119+120+ // https://en.reactjs.org/docs/jsx-in-depth.html#props-default-to-true121+ describe('Props Default to “True”', () => {122+ it('default prop value', () => {123+ const template = <span data-hello>Hello</span>124+ expect(template.toString()).toBe('<span data-hello="true">Hello</span>')125+ })126+ })127+128+ // https://html.spec.whatwg.org/#attributes-3129+ describe('Boolean attribute', () => {130+ it('default prop value for checked', () => {131+ const template = <input type='checkbox' checked />132+ expect(template.toString()).toBe('<input type="checkbox" checked=""/>')133+ })134+135+ it('default prop value for checked={true}', () => {136+ const template = <input type='checkbox' checked={true} />137+ expect(template.toString()).toBe('<input type="checkbox" checked=""/>')138+ })139+140+ it('no prop for checked={false}', () => {141+ const template = <input type='checkbox' checked={false} />142+ expect(template.toString()).toBe('<input type="checkbox"/>')143+ })144+145+ it('default prop value for disabled', () => {146+ const template = <input type='checkbox' disabled />147+ expect(template.toString()).toBe('<input type="checkbox" disabled=""/>')148+ })149+150+ it('default prop value for disabled={true}', () => {151+ const template = <input type='checkbox' disabled={true} />152+ expect(template.toString()).toBe('<input type="checkbox" disabled=""/>')153+ })154+155+ it('no prop for disabled={false}', () => {156+ const template = <input type='checkbox' disabled={false} />157+ expect(template.toString()).toBe('<input type="checkbox"/>')158+ })159+160+ it('default prop value for readonly', () => {161+ const template = <input type='checkbox' readonly />162+ expect(template.toString()).toBe('<input type="checkbox" readonly=""/>')163+ })164+165+ it('default prop value for readonly={true}', () => {166+ const template = <input type='checkbox' readonly={true} />167+ expect(template.toString()).toBe('<input type="checkbox" readonly=""/>')168+ })169+170+ it('no prop for readonly={false}', () => {171+ const template = <input type='checkbox' readonly={false} />172+ expect(template.toString()).toBe('<input type="checkbox"/>')173+ })174+175+ it('default prop value for selected', () => {176+ const template = (177+ <option value='test' selected>178+ Test179+ </option>180+ )181+ expect(template.toString()).toBe('<option value="test" selected="">Test</option>')182+ })183+184+ it('default prop value for selected={true}', () => {185+ const template = (186+ <option value='test' selected={true}>187+ Test188+ </option>189+ )190+ expect(template.toString()).toBe('<option value="test" selected="">Test</option>')191+ })192+193+ it('no prop for selected={false}', () => {194+ const template = (195+ <option value='test' selected={false}>196+ Test197+ </option>198+ )199+ expect(template.toString()).toBe('<option value="test">Test</option>')200+ })201+202+ it('default prop value for multiple select', () => {203+ const template = (204+ <select multiple>205+ <option>test</option>206+ </select>207+ )208+ expect(template.toString()).toBe('<select multiple=""><option>test</option></select>')209+ })210+211+ it('default prop value for select multiple={true}', () => {212+ const template = (213+ <select multiple={true}>214+ <option>test</option>215+ </select>216+ )217+ expect(template.toString()).toBe('<select multiple=""><option>test</option></select>')218+ })219+220+ it('no prop for select multiple={false}', () => {221+ const template = (222+ <select multiple={false}>223+ <option>test</option>224+ </select>225+ )226+ expect(template.toString()).toBe('<select><option>test</option></select>')227+ })228+229+ it('should render "false" value properly for other non-defined keys', () => {230+ const template = <input type='checkbox' testkey={false} />231+ expect(template.toString()).toBe('<input type="checkbox" testkey="false"/>')232+ })233+234+ it('should support attributes for elements other than input', () => {235+ const template = (236+ <video controls autoplay>237+ <source src='movie.mp4' type='video/mp4' />238+ </video>239+ )240+ expect(template.toString()).toBe(241+ '<video controls="" autoplay=""><source src="movie.mp4" type="video/mp4"/></video>'242+ )243+ })244+ })245+246+ // https://en.reactjs.org/docs/jsx-in-depth.html#functions-as-children247+ describe('Functions as Children', () => {248+ it('Function', () => {249+ function Repeat(props: any) {250+ const items = []251+ for (let i = 0; i < props.numTimes; i++) {252+ items.push((props.children as Function)(i))253+ }254+ return <div>{items}</div>255+ }256+257+ function ListOfTenThings() {258+ return (259+ <Repeat numTimes={10}>260+ {(index: string) => <div key={index}>This is item {index} in the list</div>}261+ </Repeat>262+ )263+ }264+265+ const template = <ListOfTenThings />266+ expect(template.toString()).toBe(267+ '<div><div key="0">This is item 0 in the list</div><div key="1">This is item 1 in the list</div><div key="2">This is item 2 in the list</div><div key="3">This is item 3 in the list</div><div key="4">This is item 4 in the list</div><div key="5">This is item 5 in the list</div><div key="6">This is item 6 in the list</div><div key="7">This is item 7 in the list</div><div key="8">This is item 8 in the list</div><div key="9">This is item 9 in the list</div></div>'268+ )269+ })270+ })271+272+ describe('style attribute', () => {273+ it('should convert the object to strings', () => {274+ const template = (275+ <h1276+ style={{277+ color: 'red',278+ fontSize: 'small',279+ }}280+ >281+ Hello282+ </h1>283+ )284+ expect(template.toString()).toBe('<h1 style="color:red;font-size:small">Hello</h1>')285+ })286+ it('should not convert the strings', () => {287+ const template = <h1 style='color:red;font-size:small'>Hello</h1>288+ expect(template.toString()).toBe('<h1 style="color:red;font-size:small">Hello</h1>')289+ })290+ })291+})292+293+describe('memo', () => {294+ it('memoized', () => {295+ let counter = 0296+ const Header = memo(() => <title>Test Site {counter}</title>)297+ const Body = () => <span>{counter}</span>298+299+ let template = (300+ <html>301+ <head>302+ <Header />303+ </head>304+ <body>305+ <Body />306+ </body>307+ </html>308+ )309+ expect(template.toString()).toBe(310+ '<html><head><title>Test Site 0</title></head><body><span>0</span></body></html>'311+ )312+313+ counter++314+ template = (315+ <html>316+ <head>317+ <Header />318+ </head>319+ <body>320+ <Body />321+ </body>322+ </html>323+ )324+ expect(template.toString()).toBe(325+ '<html><head><title>Test Site 0</title></head><body><span>1</span></body></html>'326+ )327+ })328+329+ it('props are updated', () => {330+ const Body = memo(({ counter }: { counter: number }) => <span>{counter}</span>)331+332+ let template = <Body counter={0} />333+ expect(template.toString()).toBe('<span>0</span>')334+335+ template = <Body counter={1} />336+ expect(template.toString()).toBe('<span>1</span>')337+ })338+339+ it('custom propsAreEqual', () => {340+ const Body = memo(341+ ({ counter }: { counter: number; refresh?: boolean }) => <span>{counter}</span>,342+ (_, nextProps) => (typeof nextProps.refresh == 'undefined' ? true : !nextProps.refresh)343+ )344+345+ let template = <Body counter={0} />346+ expect(template.toString()).toBe('<span>0</span>')347+348+ template = <Body counter={1} />349+ expect(template.toString()).toBe('<span>0</span>')350+351+ template = <Body counter={2} refresh={true} />352+ expect(template.toString()).toBe('<span>2</span>')353+ })354+})355+356+describe('Fragment', () => {357+ it('Should render children', () => {358+ const template = (359+ <>360+ <p>1</p>361+ <p>2</p>362+ </>363+ )364+ expect(template.toString()).toBe('<p>1</p><p>2</p>')365+ })366+367+ it('Should render nothing for empty Fragment', () => {368+ const template = <></>369+ expect(template.toString()).toBe('')370+ })371+372+ it('Should render nothing for undefined', () => {373+ const template = <>{undefined}</>374+ expect(template.toString()).toBe('')375+ })376+})added:src/jsx/index.ts+240 added
1+import { escapeToBuffer } from '../utils/html'2+import type { StringBuffer, HtmlEscaped, HtmlEscapedString } from '../utils/html'3+4+// eslint-disable-next-line @typescript-eslint/no-explicit-any5+type Props = Record<string, any>6+7+declare global {8+ // eslint-disable-next-line @typescript-eslint/no-namespace9+ namespace JSX {10+ type Element = HtmlEscapedString11+ interface ElementChildrenAttribute {12+ children: Child13+ }14+ interface IntrinsicElements {15+ [tagName: string]: Props16+ }17+ }18+}19+20+const emptyTags = [21+ 'area',22+ 'base',23+ 'br',24+ 'col',25+ 'embed',26+ 'hr',27+ 'img',28+ 'input',29+ 'keygen',30+ 'link',31+ 'meta',32+ 'param',33+ 'source',34+ 'track',35+ 'wbr',36+]37+const booleanAttributes = [38+ 'allowfullscreen',39+ 'async',40+ 'autofocus',41+ 'autoplay',42+ 'checked',43+ 'controls',44+ 'default',45+ 'defer',46+ 'disabled',47+ 'formnovalidate',48+ 'hidden',49+ 'inert',50+ 'ismap',51+ 'itemscope',52+ 'loop',53+ 'multiple',54+ 'muted',55+ 'nomodule',56+ 'novalidate',57+ 'open',58+ 'playsinline',59+ 'readonly',60+ 'required',61+ 'reversed',62+ 'selected',63+]64+65+const childrenToStringToBuffer = (children: Child[], buffer: StringBuffer): void => {66+ for (let i = 0, len = children.length; i < len; i++) {67+ const child = children[i]68+ if (typeof child === 'string') {69+ escapeToBuffer(child, buffer)70+ } else if (typeof child === 'boolean' || child === null || child === undefined) {71+ continue72+ } else if (child instanceof JSXNode) {73+ child.toStringToBuffer(buffer)74+ } else if (75+ typeof child === 'number' ||76+ (child as unknown as { isEscaped: boolean }).isEscaped77+ ) {78+ buffer[0] += child79+ } else {80+ // `child` type is `Child[]`, so stringify recursively81+ childrenToStringToBuffer(child, buffer)82+ }83+ }84+}85+86+type Child = string | number | JSXNode | Child[]87+export class JSXNode implements HtmlEscaped {88+ tag: string | Function89+ props: Props90+ children: Child[]91+ isEscaped: true = true as const92+ constructor(tag: string | Function, props: Props, children: Child[]) {93+ this.tag = tag94+ this.props = props95+ this.children = children96+ }97+98+ toString(): string {99+ const buffer: StringBuffer = ['']100+ this.toStringToBuffer(buffer)101+ return buffer[0]102+ }103+104+ toStringToBuffer(buffer: StringBuffer): void {105+ const tag = this.tag as string106+ const props = this.props107+ let { children } = this108+109+ buffer[0] += `<${tag}`110+111+ const propsKeys = Object.keys(props || {})112+113+ for (let i = 0, len = propsKeys.length; i < len; i++) {114+ const key = propsKeys[i]115+ const v = props[key]116+ // object to style strings117+ if (key === 'style' && typeof v === 'object') {118+ const styles = Object.keys(v)119+ .map((k) => `${k}:${v[k]}`)120+ .join(';')121+ .replace(/[A-Z]/g, (match) => `-${match.toLowerCase()}`)122+ buffer[0] += ` style="${styles}"`123+ } else if (typeof v === 'string') {124+ buffer[0] += ` ${key}="`125+ escapeToBuffer(v, buffer)126+ buffer[0] += '"'127+ } else if (typeof v === 'number') {128+ buffer[0] += ` ${key}="${v}"`129+ } else if (v === null || v === undefined) {130+ // Do nothing131+ } else if (typeof v === 'boolean' && booleanAttributes.includes(key)) {132+ if (v) {133+ buffer[0] += ` ${key}=""`134+ }135+ } else if (key === 'dangerouslySetInnerHTML') {136+ if (children.length > 0) {137+ throw 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.'138+ }139+140+ const escapedString = new String(v.__html) as HtmlEscapedString141+ escapedString.isEscaped = true142+ children = [escapedString]143+ } else {144+ buffer[0] += ` ${key}="`145+ escapeToBuffer(v.toString(), buffer)146+ buffer[0] += '"'147+ }148+ }149+150+ if (emptyTags.includes(tag as string)) {151+ buffer[0] += '/>'152+ return153+ }154+155+ buffer[0] += '>'156+157+ childrenToStringToBuffer(children, buffer)158+159+ buffer[0] += `</${tag}>`160+ }161+}162+163+class JSXFunctionNode extends JSXNode {164+ toStringToBuffer(buffer: StringBuffer): void {165+ const { children } = this166+167+ const res = (this.tag as Function).call(null, {168+ ...this.props,169+ children: children.length <= 1 ? children[0] : children,170+ })171+172+ if (res instanceof JSXNode) {173+ res.toStringToBuffer(buffer)174+ } else if (typeof res === 'number' || (res as HtmlEscaped).isEscaped) {175+ buffer[0] += res176+ } else {177+ escapeToBuffer(res, buffer)178+ }179+ }180+}181+182+class JSXFragmentNode extends JSXNode {183+ toStringToBuffer(buffer: StringBuffer): void {184+ childrenToStringToBuffer(this.children, buffer)185+ }186+}187+188+export { jsxFn as jsx }189+const jsxFn = (190+ tag: string | Function,191+ props: Props,192+ ...children: (string | HtmlEscapedString)[]193+): JSXNode => {194+ if (typeof tag === 'function') {195+ return new JSXFunctionNode(tag, props, children)196+ } else {197+ return new JSXNode(tag, props, children)198+ }199+}200+201+type FC<T = Props> = (props: T) => HtmlEscapedString202+203+const shallowEqual = (a: Props, b: Props): boolean => {204+ if (a === b) {205+ return true206+ }207+208+ const aKeys = Object.keys(a)209+ const bKeys = Object.keys(b)210+ if (aKeys.length !== bKeys.length) {211+ return false212+ }213+214+ for (let i = 0, len = aKeys.length; i < len; i++) {215+ if (a[aKeys[i]] !== b[aKeys[i]]) {216+ return false217+ }218+ }219+220+ return true221+}222+223+export const memo = <T>(224+ component: FC<T>,225+ propsAreEqual: (prevProps: Readonly<T>, nextProps: Readonly<T>) => boolean = shallowEqual226+): FC<T> => {227+ let computed = undefined228+ let prevProps: T | undefined = undefined229+ return ((props: T): HtmlEscapedString => {230+ if (prevProps && !propsAreEqual(prevProps, props)) {231+ computed = undefined232+ }233+ prevProps = props234+ return (computed ||= component(props))235+ }) as FC<T>236+}237+238+export const Fragment = (props: { key?: string; children?: Child[] }): JSXNode => {239+ return new JSXFragmentNode('', {}, props.children || [])240+}added:src/jsx/jsx-dev-runtime.ts+10 added
1+import type { HtmlEscapedString } from '../utils/html'2+import { jsx } from '.'3+import type { JSXNode } from '.'4+export { Fragment } from '.'5+6+export function jsxDEV(tag: string | Function, props: Record<string, unknown>): JSXNode {7+ const children = (props.children ?? []) as string | HtmlEscapedString8+ delete props['children']9+ return Array.isArray(children) ? jsx(tag, props, ...children) : jsx(tag, props, children)10+}added:src/jsx/jsx-runtime.ts+2 added
1+export { jsxDEV as jsx, Fragment } from './jsx-dev-runtime'2+export { jsxDEV as jsxs } from './jsx-dev-runtime'deleted:src/middleware/cookie/index.test.ts-251 removed
1-import { Hono } from '../../hono'2-import { getCookie, getSignedCookie, setCookie, setSignedCookie, deleteCookie } from '.'3-4-describe('Cookie Middleware', () => {5- describe('Parse cookie', () => {6- const apps: Record<string, Hono> = {}7- apps['get by name'] = (() => {8- const app = new Hono()9-10- app.get('/cookie', (c) => {11- const yummyCookie = getCookie(c, 'yummy_cookie')12- const tastyCookie = getCookie(c, 'tasty_cookie')13- const res = new Response('Good cookie')14- if (yummyCookie && tastyCookie) {15- res.headers.set('Yummy-Cookie', yummyCookie)16- res.headers.set('Tasty-Cookie', tastyCookie)17- }18- return res19- })20-21- return app22- })()23-24- apps['get all as an object'] = (() => {25- const app = new Hono()26-27- app.get('/cookie', (c) => {28- const { yummy_cookie: yummyCookie, tasty_cookie: tastyCookie } = getCookie(c)29- const res = new Response('Good cookie')30- res.headers.set('Yummy-Cookie', yummyCookie)31- res.headers.set('Tasty-Cookie', tastyCookie)32- return res33- })34-35- return app36- })()37-38- describe.each(Object.keys(apps))('%s', (name) => {39- const app = apps[name]40- it('Parse cookie with getCookie()', async () => {41- const req = new Request('http://localhost/cookie')42- const cookieString = 'yummy_cookie=choco; tasty_cookie = strawberry'43- req.headers.set('Cookie', cookieString)44- const res = await app.request(req)45-46- expect(res.headers.get('Yummy-Cookie')).toBe('choco')47- expect(res.headers.get('Tasty-Cookie')).toBe('strawberry')48- })49- })50-51- const app = new Hono()52-53- app.get('/cookie-signed-get-all', async (c) => {54- const secret = 'secret lucky charm'55- const { fortune_cookie: fortuneCookie, fruit_cookie: fruitCookie } = await getSignedCookie(56- c,57- secret58- )59- const res = new Response('Signed fortune cookie')60- if (typeof fortuneCookie !== 'undefined' && typeof fruitCookie !== 'undefined') {61- // just examples for tests sake62- res.headers.set('Fortune-Cookie', fortuneCookie || 'INVALID')63- res.headers.set('Fruit-Cookie', fruitCookie || 'INVALID')64- }65- return res66- })67-68- app.get('/cookie-signed-get-one', async (c) => {69- const secret = 'secret lucky charm'70- const fortuneCookie = await getSignedCookie(c, secret, 'fortune_cookie')71- const res = new Response('Signed fortune cookie')72- if (typeof fortuneCookie !== 'undefined') {73- // just an example for tests sake74- res.headers.set('Fortune-Cookie', fortuneCookie || 'INVALID')75- }76- return res77- })78-79- it('Get signed cookies', async () => {80- const req = new Request('http://localhost/cookie-signed-get-all')81- const cookieString =82- 'fortune_cookie=lots-of-money.UO6vMygDM6NCDU4LdvBnzdVb2Xcdj+h+ZTnmS8X7iH8%3D; fruit_cookie=mango.lRwgtW9ooM9%2Fd9ZZA%2FInNRG64CbQsfWGXQyFLPM9520%3D'83- req.headers.set('Cookie', cookieString)84- const res = await app.request(req)85- expect(res.headers.get('Fortune-Cookie')).toBe('lots-of-money')86- expect(res.headers.get('Fruit-Cookie')).toBe('mango')87- })88-89- it('Get signed cookies invalid signature', async () => {90- const req = new Request('http://localhost/cookie-signed-get-all')91- // fruit_cookie has invalid signature92- const cookieString =93- 'fortune_cookie=lots-of-money.UO6vMygDM6NCDU4LdvBnzdVb2Xcdj+h+ZTnmS8X7iH8%3D; fruit_cookie=mango.LAa7RX43t2vCrLNcKmNG65H41OkyV02sraRPuY5RuVg%3D'94- req.headers.set('Cookie', cookieString)95- const res = await app.request(req)96- expect(res.headers.get('Fortune-Cookie')).toBe('lots-of-money')97- expect(res.headers.get('Fruit-Cookie')).toBe('INVALID')98- })99-100- it('Get signed cookie', async () => {101- const req = new Request('http://localhost/cookie-signed-get-one')102- const cookieString =103- 'fortune_cookie=lots-of-money.UO6vMygDM6NCDU4LdvBnzdVb2Xcdj+h+ZTnmS8X7iH8%3D; fruit_cookie=mango.lRwgtW9ooM9%2Fd9ZZA%2FInNRG64CbQsfWGXQyFLPM9520%3D'104- req.headers.set('Cookie', cookieString)105- const res = await app.request(req)106- expect(res.headers.get('Fortune-Cookie')).toBe('lots-of-money')107- })108-109- it('Get signed cookie witn invalid signature', async () => {110- const req = new Request('http://localhost/cookie-signed-get-one')111- // fortune_cookie has invalid signature112- const cookieString =113- 'fortune_cookie=lots-of-money.LAa7RX43t2vCrLNcKmNG65H41OkyV02sraRPuY5RuVg=; fruit_cookie=mango.lRwgtW9ooM9%2Fd9ZZA%2FInNRG64CbQsfWGXQyFLPM9520%3D'114- req.headers.set('Cookie', cookieString)115- const res = await app.request(req)116- expect(res.headers.get('Fortune-Cookie')).toBe('INVALID')117- })118- })119-120- describe('Set cookie', () => {121- const app = new Hono()122-123- app.get('/set-cookie', (c) => {124- setCookie(c, 'delicious_cookie', 'macha')125- return c.text('Give cookie')126- })127-128- it('Set cookie with setCookie()', async () => {129- const res = await app.request('http://localhost/set-cookie')130- expect(res.status).toBe(200)131- const header = res.headers.get('Set-Cookie')132- expect(header).toBe('delicious_cookie=macha')133- })134-135- app.get('/set-signed-cookie', async (c) => {136- const secret = 'secret chocolate chips'137- await setSignedCookie(c, 'delicious_cookie', 'macha', secret)138- return c.text('Give signed cookie')139- })140-141- it('Set signed cookie with setSignedCookie()', async () => {142- const res = await app.request('http://localhost/set-signed-cookie')143- expect(res.status).toBe(200)144- const header = res.headers.get('Set-Cookie')145- expect(header).toBe('delicious_cookie=macha.diubJPY8O7hI1pLa42QSfkPiyDWQ0I4DnlACH%2FN2HaA%3D')146- })147-148- app.get('/set-cookie-complex', (c) => {149- setCookie(c, 'great_cookie', 'banana', {150- path: '/',151- secure: true,152- domain: 'example.com',153- httpOnly: true,154- maxAge: 1000,155- expires: new Date(Date.UTC(2000, 11, 24, 10, 30, 59, 900)),156- sameSite: 'Strict',157- })158- return c.text('Give cookie')159- })160-161- it('Complex pattern', async () => {162- const res = await app.request('http://localhost/set-cookie-complex')163- expect(res.status).toBe(200)164- const header = res.headers.get('Set-Cookie')165- expect(header).toBe(166- 'great_cookie=banana; Max-Age=1000; Domain=example.com; Path=/; Expires=Sun, 24 Dec 2000 10:30:59 GMT; HttpOnly; Secure; SameSite=Strict'167- )168- })169-170- app.get('/set-signed-cookie-complex', async (c) => {171- const secret = 'secret chocolate chips'172- await setSignedCookie(c, 'great_cookie', 'banana', secret, {173- path: '/',174- secure: true,175- domain: 'example.com',176- httpOnly: true,177- maxAge: 1000,178- expires: new Date(Date.UTC(2000, 11, 24, 10, 30, 59, 900)),179- sameSite: 'Strict',180- })181- return c.text('Give signed cookie')182- })183-184- it('Complex pattern (signed)', async () => {185- const res = await app.request('http://localhost/set-signed-cookie-complex')186- expect(res.status).toBe(200)187- const header = res.headers.get('Set-Cookie')188- expect(header).toBe(189- 'great_cookie=banana.hSo6gB7YT2db0WBiEAakEmh7dtwEL0DSp76G23WvHuQ%3D; Max-Age=1000; Domain=example.com; Path=/; Expires=Sun, 24 Dec 2000 10:30:59 GMT; HttpOnly; Secure; SameSite=Strict'190- )191- })192-193- app.get('/set-cookie-multiple', (c) => {194- setCookie(c, 'delicious_cookie', 'macha')195- setCookie(c, 'delicious_cookie', 'choco')196- return c.text('Give cookie')197- })198-199- it('Multiple values', async () => {200- const res = await app.request('http://localhost/set-cookie-multiple')201- expect(res.status).toBe(200)202- const header = res.headers.get('Set-Cookie')203- expect(header).toBe('delicious_cookie=macha, delicious_cookie=choco')204- })205- })206-207- describe('Delete cookie', () => {208- const app = new Hono()209-210- app.get('/delete-cookie', (c) => {211- deleteCookie(c, 'delicious_cookie')212- return c.text('Give cookie')213- })214-215- it('Delete cookie', async () => {216- const res2 = await app.request('http://localhost/delete-cookie')217- expect(res2.status).toBe(200)218- const header2 = res2.headers.get('Set-Cookie')219- expect(header2).toBe('delicious_cookie=; Max-Age=0')220- })221-222- app.get('/delete-cookie-multiple', (c) => {223- deleteCookie(c, 'delicious_cookie')224- deleteCookie(c, 'delicious_cookie2')225- return c.text('Give cookie')226- })227-228- it('Delete multile cookies', async () => {229- const res2 = await app.request('http://localhost/delete-cookie-multiple')230- expect(res2.status).toBe(200)231- const header2 = res2.headers.get('Set-Cookie')232- expect(header2).toBe('delicious_cookie=; Max-Age=0, delicious_cookie2=; Max-Age=0')233- })234-235- app.get('/delete-cookie-with-options', (c) => {236- deleteCookie(c, 'delicious_cookie', {237- path: '/',238- secure: true,239- domain: 'example.com',240- })241- return c.text('Give cookie')242- })243-244- it('Delete cookie with options', async () => {245- const res2 = await app.request('http://localhost/delete-cookie-with-options')246- expect(res2.status).toBe(200)247- const header2 = res2.headers.get('Set-Cookie')248- expect(header2).toBe('delicious_cookie=; Max-Age=0; Domain=example.com; Path=/; Secure')249- })250- })251-})deleted:src/middleware/cookie/index.ts-59 removed
1-import type { Context } from '../../context'2-import { parse, parseSigned, serialize, serializeSigned } from '../../utils/cookie'3-import type { CookieOptions, Cookie, SignedCookie } from '../../utils/cookie'4-5-interface GetCookie {6- (c: Context, key: string): string | undefined7- (c: Context): Cookie8-}9-10-interface GetSignedCookie {11- (c: Context, secret: string, key: string): Promise<string | undefined | false>12- (c: Context, secret: string): Promise<SignedCookie>13-}14-15-export const getCookie: GetCookie = (c, key?) => {16- const cookie = c.req.raw.headers.get('Cookie')17- if (typeof key === 'string') {18- if (!cookie) return undefined19- const obj = parse(cookie)20- return obj[key]21- }22- if (!cookie) return {}23- const obj = parse(cookie)24- // eslint-disable-next-line @typescript-eslint/no-explicit-any25- return obj as any26-}27-28-export const getSignedCookie: GetSignedCookie = async (c, secret, key?) => {29- const cookie = c.req.raw.headers.get('Cookie')30- if (typeof key === 'string') {31- if (!cookie) return undefined32- const obj = await parseSigned(cookie, secret, key)33- return obj[key]34- }35- if (!cookie) return {}36- const obj = await parseSigned(cookie, secret)37- // eslint-disable-next-line @typescript-eslint/no-explicit-any38- return obj as any39-}40-41-export const setCookie = (c: Context, name: string, value: string, opt?: CookieOptions): void => {42- const cookie = serialize(name, value, opt)43- c.header('set-cookie', cookie, { append: true })44-}45-46-export const setSignedCookie = async (47- c: Context,48- name: string,49- value: string,50- secret: string,51- opt?: CookieOptions52-): Promise<void> => {53- const cookie = await serializeSigned(name, value, secret, opt)54- c.header('set-cookie', cookie, { append: true })55-}56-57-export const deleteCookie = (c: Context, name: string, opt?: CookieOptions): void => {58- setCookie(c, name, '', { ...opt, maxAge: 0 })59-}deleted:src/middleware/html/index.test.ts-41 removed
1-import { html, raw } from '.'2-3-describe('Tagged Template Literals', () => {4- it('Should escape special characters', () => {5- const name = 'John "Johnny" Smith'6- // eslint-disable-next-line quotes7- expect(html`<p>I'm ${name}.</p>`.toString()).toBe("<p>I'm John "Johnny" Smith.</p>")8- })9-10- describe('Booleans, Null, and Undefined Are Ignored', () => {11- it.each([true, false, undefined, null])('%s', (item) => {12- expect(html`${item}`.toString()).toBe('')13- })14-15- it('falsy value', () => {16- expect(html`${0}`.toString()).toBe('0')17- })18- })19-20- it('Should call $array.flat(Infinity)', () => {21- const values = [22- 'Name:',23- ['John "Johnny" Smith', undefined, null],24- ' Contact:',25- [html`<a href="http://example.com/">My Website</a>`],26- ]27- expect(html`<p>${values}</p>`.toString()).toBe(28- '<p>Name:John "Johnny" Smith Contact:<a href="http://example.com/">My Website</a></p>'29- )30- })31-})32-33-describe('raw', () => {34- it('Should be marked as escaped.', () => {35- const name = 'John "Johnny" Smith'36- expect(html`<p>I'm ${raw(name)}.</p>`.toString()).toBe(37- // eslint-disable-next-line quotes38- "<p>I'm John "Johnny" Smith.</p>"39- )40- })41-})deleted:src/middleware/html/index.ts-39 removed
1-import { escapeToBuffer } from '../../utils/html'2-import type { StringBuffer, HtmlEscaped, HtmlEscapedString } from '../../utils/html'3-4-export const raw = (value: unknown): HtmlEscapedString => {5- const escapedString = new String(value) as HtmlEscapedString6- escapedString.isEscaped = true7-8- return escapedString9-}10-11-export const html = (strings: TemplateStringsArray, ...values: unknown[]): HtmlEscapedString => {12- const buffer: StringBuffer = ['']13-14- for (let i = 0, len = strings.length - 1; i < len; i++) {15- buffer[0] += strings[i]16-17- const children =18- values[i] instanceof Array ? (values[i] as Array<unknown>).flat(Infinity) : [values[i]]19- for (let i = 0, len = children.length; i < len; i++) {20- // eslint-disable-next-line @typescript-eslint/no-explicit-any21- const child = children[i] as any22- if (typeof child === 'string') {23- escapeToBuffer(child, buffer)24- } else if (typeof child === 'boolean' || child === null || child === undefined) {25- continue26- } else if (27- (typeof child === 'object' && (child as HtmlEscaped).isEscaped) ||28- typeof child === 'number'29- ) {30- buffer[0] += child31- } else {32- escapeToBuffer(child.toString(), buffer)33- }34- }35- }36- buffer[0] += strings[strings.length - 1]37-38- return raw(buffer[0])39-}deleted:src/middleware/jsx/index.test.tsx-376 removed
1-import { Hono } from '../../hono'2-import { html } from '../html/index'3-import { jsx, memo, Fragment } from './index'4-5-interface SiteData {6- title: string7- children?: any8-}9-10-describe('JSX middleware', () => {11- let app: Hono12-13- beforeEach(() => {14- app = new Hono()15- })16-17- it('Should render HTML strings', async () => {18- app.get('/', (c) => {19- return c.html(<h1>Hello</h1>)20- })21- const res = await app.request('http://localhost/')22- expect(res.status).toBe(200)23- expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')24- expect(await res.text()).toBe('<h1>Hello</h1>')25- })26-27- it('Should be able to be used with html middleware', async () => {28- const Layout = (props: SiteData) => html`<!DOCTYPE html>29- <html>30- <head>31- <title>${props.title}</title>32- </head>33- <body>34- ${props.children}35- </body>36- </html>`37-38- const Content = (props: { siteData: SiteData; name: string }) => (39- <Layout {...props.siteData}>40- <h1>{props.name}</h1>41- </Layout>42- )43-44- app.get('/', (c) => {45- const props = {46- name: 'JSX',47- siteData: {48- title: 'with html middleware',49- },50- }51- return c.html(<Content {...props} />)52- })53- const res = await app.request('http://localhost/')54- expect(res.status).toBe(200)55- expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')56- expect(await res.text()).toBe(`<!DOCTYPE html>57- <html>58- <head>59- <title>with html middleware</title>60- </head>61- <body>62- <h1>JSX</h1>63- </body>64- </html>`)65- })66-})67-68-describe('render to string', () => {69- it('Nested array', () => {70- const template = (71- <p>72- {[[['a']], [['b']]].map((item1) =>73- item1.map((item2) => item2.map((item3) => <span>{item3}</span>))74- )}75- </p>76- )77- expect(template.toString()).toBe('<p><span>a</span><span>b</span></p>')78- })79-80- it('Empty elements are rended withtout closing tag', () => {81- const template = <input />82- expect(template.toString()).toBe('<input/>')83- })84-85- it('Props value is null', () => {86- const template = <span data-hello={null}>Hello</span>87- expect(template.toString()).toBe('<span>Hello</span>')88- })89-90- it('Props value is undefined', () => {91- const template = <span data-hello={undefined}>Hello</span>92- expect(template.toString()).toBe('<span>Hello</span>')93- })94-95- describe('dangerouslySetInnerHTML', () => {96- it('Should render dangerouslySetInnerHTML', () => {97- const template = <span dangerouslySetInnerHTML={{ __html: '" is allowed here' }}></span>98- expect(template.toString()).toBe('<span>" is allowed here</span>')99- })100-101- it('Should get an error if both dangerouslySetInnerHTML and children are specified', () => {102- expect(() =>103- (<span dangerouslySetInnerHTML={{ __html: '" is allowed here' }}>Hello</span>).toString()104- ).toThrow()105- })106- })107-108- // https://en.reactjs.org/docs/jsx-in-depth.html#booleans-null-and-undefined-are-ignored109- describe('Booleans, Null, and Undefined Are Ignored', () => {110- it.each([true, false, undefined, null])('%s', (item) => {111- expect((<span>{item}</span>).toString()).toBe('<span></span>')112- })113-114- it('falsy value', () => {115- const template = <span>{0}</span>116- expect(template.toString()).toBe('<span>0</span>')117- })118- })119-120- // https://en.reactjs.org/docs/jsx-in-depth.html#props-default-to-true121- describe('Props Default to “True”', () => {122- it('default prop value', () => {123- const template = <span data-hello>Hello</span>124- expect(template.toString()).toBe('<span data-hello="true">Hello</span>')125- })126- })127-128- // https://html.spec.whatwg.org/#attributes-3129- describe('Boolean attribute', () => {130- it('default prop value for checked', () => {131- const template = <input type='checkbox' checked />132- expect(template.toString()).toBe('<input type="checkbox" checked=""/>')133- })134-135- it('default prop value for checked={true}', () => {136- const template = <input type='checkbox' checked={true} />137- expect(template.toString()).toBe('<input type="checkbox" checked=""/>')138- })139-140- it('no prop for checked={false}', () => {141- const template = <input type='checkbox' checked={false} />142- expect(template.toString()).toBe('<input type="checkbox"/>')143- })144-145- it('default prop value for disabled', () => {146- const template = <input type='checkbox' disabled />147- expect(template.toString()).toBe('<input type="checkbox" disabled=""/>')148- })149-150- it('default prop value for disabled={true}', () => {151- const template = <input type='checkbox' disabled={true} />152- expect(template.toString()).toBe('<input type="checkbox" disabled=""/>')153- })154-155- it('no prop for disabled={false}', () => {156- const template = <input type='checkbox' disabled={false} />157- expect(template.toString()).toBe('<input type="checkbox"/>')158- })159-160- it('default prop value for readonly', () => {161- const template = <input type='checkbox' readonly />162- expect(template.toString()).toBe('<input type="checkbox" readonly=""/>')163- })164-165- it('default prop value for readonly={true}', () => {166- const template = <input type='checkbox' readonly={true} />167- expect(template.toString()).toBe('<input type="checkbox" readonly=""/>')168- })169-170- it('no prop for readonly={false}', () => {171- const template = <input type='checkbox' readonly={false} />172- expect(template.toString()).toBe('<input type="checkbox"/>')173- })174-175- it('default prop value for selected', () => {176- const template = (177- <option value='test' selected>178- Test179- </option>180- )181- expect(template.toString()).toBe('<option value="test" selected="">Test</option>')182- })183-184- it('default prop value for selected={true}', () => {185- const template = (186- <option value='test' selected={true}>187- Test188- </option>189- )190- expect(template.toString()).toBe('<option value="test" selected="">Test</option>')191- })192-193- it('no prop for selected={false}', () => {194- const template = (195- <option value='test' selected={false}>196- Test197- </option>198- )199- expect(template.toString()).toBe('<option value="test">Test</option>')200- })201-202- it('default prop value for multiple select', () => {203- const template = (204- <select multiple>205- <option>test</option>206- </select>207- )208- expect(template.toString()).toBe('<select multiple=""><option>test</option></select>')209- })210-211- it('default prop value for select multiple={true}', () => {212- const template = (213- <select multiple={true}>214- <option>test</option>215- </select>216- )217- expect(template.toString()).toBe('<select multiple=""><option>test</option></select>')218- })219-220- it('no prop for select multiple={false}', () => {221- const template = (222- <select multiple={false}>223- <option>test</option>224- </select>225- )226- expect(template.toString()).toBe('<select><option>test</option></select>')227- })228-229- it('should render "false" value properly for other non-defined keys', () => {230- const template = <input type='checkbox' testkey={false} />231- expect(template.toString()).toBe('<input type="checkbox" testkey="false"/>')232- })233-234- it('should support attributes for elements other than input', () => {235- const template = (236- <video controls autoplay>237- <source src='movie.mp4' type='video/mp4' />238- </video>239- )240- expect(template.toString()).toBe(241- '<video controls="" autoplay=""><source src="movie.mp4" type="video/mp4"/></video>'242- )243- })244- })245-246- // https://en.reactjs.org/docs/jsx-in-depth.html#functions-as-children247- describe('Functions as Children', () => {248- it('Function', () => {249- function Repeat(props: any) {250- const items = []251- for (let i = 0; i < props.numTimes; i++) {252- items.push((props.children as Function)(i))253- }254- return <div>{items}</div>255- }256-257- function ListOfTenThings() {258- return (259- <Repeat numTimes={10}>260- {(index: string) => <div key={index}>This is item {index} in the list</div>}261- </Repeat>262- )263- }264-265- const template = <ListOfTenThings />266- expect(template.toString()).toBe(267- '<div><div key="0">This is item 0 in the list</div><div key="1">This is item 1 in the list</div><div key="2">This is item 2 in the list</div><div key="3">This is item 3 in the list</div><div key="4">This is item 4 in the list</div><div key="5">This is item 5 in the list</div><div key="6">This is item 6 in the list</div><div key="7">This is item 7 in the list</div><div key="8">This is item 8 in the list</div><div key="9">This is item 9 in the list</div></div>'268- )269- })270- })271-272- describe('style attribute', () => {273- it('should convert the object to strings', () => {274- const template = (275- <h1276- style={{277- color: 'red',278- fontSize: 'small',279- }}280- >281- Hello282- </h1>283- )284- expect(template.toString()).toBe('<h1 style="color:red;font-size:small">Hello</h1>')285- })286- it('should not convert the strings', () => {287- const template = <h1 style='color:red;font-size:small'>Hello</h1>288- expect(template.toString()).toBe('<h1 style="color:red;font-size:small">Hello</h1>')289- })290- })291-})292-293-describe('memo', () => {294- it('memoized', () => {295- let counter = 0296- const Header = memo(() => <title>Test Site {counter}</title>)297- const Body = () => <span>{counter}</span>298-299- let template = (300- <html>301- <head>302- <Header />303- </head>304- <body>305- <Body />306- </body>307- </html>308- )309- expect(template.toString()).toBe(310- '<html><head><title>Test Site 0</title></head><body><span>0</span></body></html>'311- )312-313- counter++314- template = (315- <html>316- <head>317- <Header />318- </head>319- <body>320- <Body />321- </body>322- </html>323- )324- expect(template.toString()).toBe(325- '<html><head><title>Test Site 0</title></head><body><span>1</span></body></html>'326- )327- })328-329- it('props are updated', () => {330- const Body = memo(({ counter }: { counter: number }) => <span>{counter}</span>)331-332- let template = <Body counter={0} />333- expect(template.toString()).toBe('<span>0</span>')334-335- template = <Body counter={1} />336- expect(template.toString()).toBe('<span>1</span>')337- })338-339- it('custom propsAreEqual', () => {340- const Body = memo(341- ({ counter }: { counter: number; refresh?: boolean }) => <span>{counter}</span>,342- (_, nextProps) => (typeof nextProps.refresh == 'undefined' ? true : !nextProps.refresh)343- )344-345- let template = <Body counter={0} />346- expect(template.toString()).toBe('<span>0</span>')347-348- template = <Body counter={1} />349- expect(template.toString()).toBe('<span>0</span>')350-351- template = <Body counter={2} refresh={true} />352- expect(template.toString()).toBe('<span>2</span>')353- })354-})355-356-describe('Fragment', () => {357- it('Should render children', () => {358- const template = (359- <>360- <p>1</p>361- <p>2</p>362- </>363- )364- expect(template.toString()).toBe('<p>1</p><p>2</p>')365- })366-367- it('Should render nothing for empty Fragment', () => {368- const template = <></>369- expect(template.toString()).toBe('')370- })371-372- it('Should render nothing for undefined', () => {373- const template = <>{undefined}</>374- expect(template.toString()).toBe('')375- })376-})deleted:src/middleware/jsx/index.ts-240 removed
1-import { escapeToBuffer } from '../../utils/html'2-import type { StringBuffer, HtmlEscaped, HtmlEscapedString } from '../../utils/html'3-4-// eslint-disable-next-line @typescript-eslint/no-explicit-any5-type Props = Record<string, any>6-7-declare global {8- // eslint-disable-next-line @typescript-eslint/no-namespace9- namespace JSX {10- type Element = HtmlEscapedString11- interface ElementChildrenAttribute {12- children: Child13- }14- interface IntrinsicElements {15- [tagName: string]: Props16- }17- }18-}19-20-const emptyTags = [21- 'area',22- 'base',23- 'br',24- 'col',25- 'embed',26- 'hr',27- 'img',28- 'input',29- 'keygen',30- 'link',31- 'meta',32- 'param',33- 'source',34- 'track',35- 'wbr',36-]37-const booleanAttributes = [38- 'allowfullscreen',39- 'async',40- 'autofocus',41- 'autoplay',42- 'checked',43- 'controls',44- 'default',45- 'defer',46- 'disabled',47- 'formnovalidate',48- 'hidden',49- 'inert',50- 'ismap',51- 'itemscope',52- 'loop',53- 'multiple',54- 'muted',55- 'nomodule',56- 'novalidate',57- 'open',58- 'playsinline',59- 'readonly',60- 'required',61- 'reversed',62- 'selected',63-]64-65-const childrenToStringToBuffer = (children: Child[], buffer: StringBuffer): void => {66- for (let i = 0, len = children.length; i < len; i++) {67- const child = children[i]68- if (typeof child === 'string') {69- escapeToBuffer(child, buffer)70- } else if (typeof child === 'boolean' || child === null || child === undefined) {71- continue72- } else if (child instanceof JSXNode) {73- child.toStringToBuffer(buffer)74- } else if (75- typeof child === 'number' ||76- (child as unknown as { isEscaped: boolean }).isEscaped77- ) {78- buffer[0] += child79- } else {80- // `child` type is `Child[]`, so stringify recursively81- childrenToStringToBuffer(child, buffer)82- }83- }84-}85-86-type Child = string | number | JSXNode | Child[]87-export class JSXNode implements HtmlEscaped {88- tag: string | Function89- props: Props90- children: Child[]91- isEscaped: true = true as const92- constructor(tag: string | Function, props: Props, children: Child[]) {93- this.tag = tag94- this.props = props95- this.children = children96- }97-98- toString(): string {99- const buffer: StringBuffer = ['']100- this.toStringToBuffer(buffer)101- return buffer[0]102- }103-104- toStringToBuffer(buffer: StringBuffer): void {105- const tag = this.tag as string106- const props = this.props107- let { children } = this108-109- buffer[0] += `<${tag}`110-111- const propsKeys = Object.keys(props || {})112-113- for (let i = 0, len = propsKeys.length; i < len; i++) {114- const key = propsKeys[i]115- const v = props[key]116- // object to style strings117- if (key === 'style' && typeof v === 'object') {118- const styles = Object.keys(v)119- .map((k) => `${k}:${v[k]}`)120- .join(';')121- .replace(/[A-Z]/g, (match) => `-${match.toLowerCase()}`)122- buffer[0] += ` style="${styles}"`123- } else if (typeof v === 'string') {124- buffer[0] += ` ${key}="`125- escapeToBuffer(v, buffer)126- buffer[0] += '"'127- } else if (typeof v === 'number') {128- buffer[0] += ` ${key}="${v}"`129- } else if (v === null || v === undefined) {130- // Do nothing131- } else if (typeof v === 'boolean' && booleanAttributes.includes(key)) {132- if (v) {133- buffer[0] += ` ${key}=""`134- }135- } else if (key === 'dangerouslySetInnerHTML') {136- if (children.length > 0) {137- throw 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.'138- }139-140- const escapedString = new String(v.__html) as HtmlEscapedString141- escapedString.isEscaped = true142- children = [escapedString]143- } else {144- buffer[0] += ` ${key}="`145- escapeToBuffer(v.toString(), buffer)146- buffer[0] += '"'147- }148- }149-150- if (emptyTags.includes(tag as string)) {151- buffer[0] += '/>'152- return153- }154-155- buffer[0] += '>'156-157- childrenToStringToBuffer(children, buffer)158-159- buffer[0] += `</${tag}>`160- }161-}162-163-class JSXFunctionNode extends JSXNode {164- toStringToBuffer(buffer: StringBuffer): void {165- const { children } = this166-167- const res = (this.tag as Function).call(null, {168- ...this.props,169- children: children.length <= 1 ? children[0] : children,170- })171-172- if (res instanceof JSXNode) {173- res.toStringToBuffer(buffer)174- } else if (typeof res === 'number' || (res as HtmlEscaped).isEscaped) {175- buffer[0] += res176- } else {177- escapeToBuffer(res, buffer)178- }179- }180-}181-182-class JSXFragmentNode extends JSXNode {183- toStringToBuffer(buffer: StringBuffer): void {184- childrenToStringToBuffer(this.children, buffer)185- }186-}187-188-export { jsxFn as jsx }189-const jsxFn = (190- tag: string | Function,191- props: Props,192- ...children: (string | HtmlEscapedString)[]193-): JSXNode => {194- if (typeof tag === 'function') {195- return new JSXFunctionNode(tag, props, children)196- } else {197- return new JSXNode(tag, props, children)198- }199-}200-201-type FC<T = Props> = (props: T) => HtmlEscapedString202-203-const shallowEqual = (a: Props, b: Props): boolean => {204- if (a === b) {205- return true206- }207-208- const aKeys = Object.keys(a)209- const bKeys = Object.keys(b)210- if (aKeys.length !== bKeys.length) {211- return false212- }213-214- for (let i = 0, len = aKeys.length; i < len; i++) {215- if (a[aKeys[i]] !== b[aKeys[i]]) {216- return false217- }218- }219-220- return true221-}222-223-export const memo = <T>(224- component: FC<T>,225- propsAreEqual: (prevProps: Readonly<T>, nextProps: Readonly<T>) => boolean = shallowEqual226-): FC<T> => {227- let computed = undefined228- let prevProps: T | undefined = undefined229- return ((props: T): HtmlEscapedString => {230- if (prevProps && !propsAreEqual(prevProps, props)) {231- computed = undefined232- }233- prevProps = props234- return (computed ||= component(props))235- }) as FC<T>236-}237-238-export const Fragment = (props: { key?: string; children?: Child[] }): JSXNode => {239- return new JSXFragmentNode('', {}, props.children || [])240-}deleted:src/middleware/jsx/jsx-dev-runtime.ts-10 removed
1-import type { HtmlEscapedString } from '../../utils/html'2-import { jsx } from '.'3-import type { JSXNode } from '.'4-export { Fragment } from '.'5-6-export function jsxDEV(tag: string | Function, props: Record<string, unknown>): JSXNode {7- const children = (props.children ?? []) as string | HtmlEscapedString8- delete props['children']9- return Array.isArray(children) ? jsx(tag, props, ...children) : jsx(tag, props, children)10-}deleted:src/middleware/jsx/jsx-runtime.ts-2 removed
1-export { jsxDEV as jsx, Fragment } from './jsx-dev-runtime'2-export { jsxDEV as jsxs } from './jsx-dev-runtime'modified:src/validator/validator.ts+1 added-1 removed
1 import type { Context } from '../context'2-import { getCookie } from '../middleware/cookie'2+import { getCookie } from '../helper/cookie'3 import type { Env, ValidationTargets, MiddlewareHandler } from '../types'4 5 type ValidationTargetKeysWithBody = 'form' | 'json'6 type ValidationTargetByMethod<M> = M extends 'get' | 'head' // GET and HEAD request must not have a body content.92 unmodified linesdeleted:src/adapter.ts-30 removed
1-import type { Context } from './context'2-3-export const env = <T extends Record<string, string>, C extends Context = Context<{}>>(4- c: C5-): T & C['env'] => {6- // eslint-disable-next-line @typescript-eslint/no-explicit-any7- const global = globalThis as any8-9- if (10- c.runtime === 'bun' ||11- c.runtime === 'node' ||12- c.runtime === 'edge-light' ||13- c.runtime === 'lagon'14- ) {15- return global?.process?.env as T16- }17- if (c.runtime === 'deno') {18- // eslint-disable-next-line @typescript-eslint/ban-ts-comment19- // @ts-ignore20- return Deno.env.toObject()21- }22- if (c.runtime === 'workerd') {23- return c.env24- }25- if (c.runtime === 'fastly') {26- // On Fastly Compute@Edge, you can use the ConfigStore to manage user-defined data.27- return {} as T28- }29- return {} as T30-}modified:src/context.ts+12 added
356 unmodified lines357 // @ts-ignore358 return this.notFoundHandler(this)359 }360 361+ /** @deprecated362+ * Use `getRuntimeKey()` exported from `hono/adapter` instead of `c.runtime()`. The `c.runtime()` will be removed in v4.363+ *364+ * @example365+ *366+ * import { getRuntimeKey } from 'hono/adapter'367+ * // ...368+ * app.get('/', (c) => {369+ * const key = getRuntimeKey()370+ * //...371+ * })372+ */373 get runtime(): Runtime {374 // eslint-disable-next-line @typescript-eslint/no-explicit-any375 const global = globalThis as any376 31 unmodified linesadded:src/helper.ts+4 added
1+// This file is for Deno to import helpers from `hono/helper.ts`.2+export * from './helper/cookie'3+export * from './helper/html'4+export * from './helper/adapter'modified:src/hono.test.ts-1 removed
1 /* eslint-disable @typescript-eslint/no-unused-vars */2-import { env } from './adapter'2 import type { Context } from './context'3 import { Hono } from './hono'4 import { HTTPException } from './http-exception'5 import { logger } from './middleware/logger'2352 unmodified linesmodified:src/middleware.ts+4 added-4 removed
1-// Middleware1+// This file is for Deno to import middleware from `hono/middleware.ts`.2 export * from './middleware/basic-auth'3 export * from './middleware/bearer-auth'4 export * from './middleware/cache'5-export * from './middleware/cookie'5+export * from './helper/cookie' // will be moved to helper.ts in v46 export * from './middleware/compress'7 export * from './middleware/cors'8 export * from './middleware/etag'9-export * from './middleware/html'10-export * from './middleware/jsx'9+export * from './helper/html' // will be moved to helper.ts in v410+export * from './jsx'11 export * from './middleware/jwt'12 export * from './middleware/logger'13 export * from './middleware/powered-by'14 export * from './middleware/timing'2 unmodified linesmodified:package.json+25 added-25 removed
10 unmodified lines11 ],12 "scripts": {13 "test": "jest",14 "test:deno": "env NAME=Deno deno test --allow-read --allow-env runtime_tests/deno",15- "test:bun": "env NAME=Bun bun test --jsx-import-source ../../src/middleware/jsx runtime_tests/bun/index.test.tsx",15+ "test:bun": "env NAME=Bun bun test --jsx-import-source ../../src/jsx runtime_tests/bun/index.test.tsx",16 "test:fastly": "jest --config ./runtime_tests/fastly/jest.config.js",17 "test:lagon": "start-server-and-test \"lagon dev runtime_tests/lagon/index.ts -e runtime_tests/lagon/.env.lagon\" http://127.0.0.1:1234 \"yarn jest runtime_tests/lagon/index.test.ts --roots runtime_tests/lagon --testMatch '**/*.test.ts'\"",18 "test:node": "env NAME=Node jest --config ./runtime_tests/node/jest.config.js",19 "test:wrangler": "jest --config ./runtime_tests/wrangler/jest.config.js",53 unmodified lines73 "import": "./dist/middleware/cache/index.js",74 "require": "./dist/cjs/middleware/cache/index.js"75 },76 "./cookie": {77- "types": "./dist/types/middleware/cookie/index.d.ts",78- "import": "./dist/middleware/cookie/index.js",79- "require": "./dist/cjs/middleware/cookie/index.js"77+ "types": "./dist/types/helper/cookie/index.d.ts",78+ "import": "./dist/helper/cookie/index.js",79+ "require": "./dist/cjs/helper/cookie/index.js"80 },81 "./compress": {82 "types": "./dist/types/middleware/compress/index.d.ts",83 "import": "./dist/middleware/compress/index.js",9 unmodified lines93 "import": "./dist/middleware/etag/index.js",94 "require": "./dist/cjs/middleware/etag/index.js"95 },96 "./html": {97- "types": "./dist/types/middleware/html/index.d.ts",98- "import": "./dist/middleware/html/index.js",99- "require": "./dist/cjs/middleware/html/index.js"97+ "types": "./dist/types/helper/html/index.d.ts",98+ "import": "./dist/helper/html/index.js",99+ "require": "./dist/cjs/helper/html/index.js"100 },101 "./jsx": {102- "types": "./dist/types/middleware/jsx/index.d.ts",103- "import": "./dist/middleware/jsx/index.js",104- "require": "./dist/cjs/middleware/jsx/index.js"102+ "types": "./dist/types/jsx/index.d.ts",103+ "import": "./dist/jsx/index.js",104+ "require": "./dist/cjs/jsx/index.js"105 },106 "./jsx/jsx-dev-runtime": {107- "types": "./dist/types/middleware/jsx/jsx-dev-runtime.d.ts",108- "import": "./dist/middleware/jsx/jsx-dev-runtime.js",109- "require": "./dist/cjs/middleware/jsx/jsx-dev-runtime.js"107+ "types": "./dist/types/jsx/jsx-dev-runtime.d.ts",108+ "import": "./dist/jsx/jsx-dev-runtime.js",109+ "require": "./dist/cjs/jsx/jsx-dev-runtime.js"110 },111 "./jsx/jsx-runtime": {112- "types": "./dist/types/middleware/jsx/jsx-runtime.d.ts",113- "import": "./dist/middleware/jsx/jsx-runtime.js",114- "require": "./dist/cjs/middleware/jsx/jsx-runtime.js"112+ "types": "./dist/types/jsx/jsx-runtime.d.ts",113+ "import": "./dist/jsx/jsx-runtime.js",114+ "require": "./dist/cjs/jsx/jsx-runtime.js"115 },116 "./jwt": {117 "types": "./dist/types/middleware/jwt/index.d.ts",118 "import": "./dist/middleware/jwt/index.js",69 unmodified lines188 "import": "./dist/client/index.js",189 "require": "./dist/cjs/client/index.js"190 },191 "./adapter": {192- "types": "./dist/types/adapter.d.ts",193- "import": "./dist/adapter.js",194- "require": "./dist/cjs/adapter.js"192+ "types": "./dist/types/helper/adapter/index.d.ts",193+ "import": "./dist/helper/adapter/index.js",194+ "require": "./dist/cjs/helper/adapter/index.js"195 },196 "./cloudflare-workers": {197 "types": "./dist/types/adapter/cloudflare-workers/index.d.ts",198 "import": "./dist/adapter/cloudflare-workers/index.js",58 unmodified lines257 "cache": [258 "./dist/types/middleware/cache"259 ],260 "cookie": [261- "./dist/types/middleware/cookie"261+ "./dist/types/helper/cookie"262 ],263 "compress": [264 "./dist/types/middleware/compress"265 ],3 unmodified lines269 "etag": [270 "./dist/types/middleware/etag"271 ],272 "html": [273- "./dist/types/middleware/html"273+ "./dist/types/helper/html"274 ],275 "jsx": [276- "./dist/types/middleware/jsx"276+ "./dist/types/jsx"277 ],278 "jsx/jsx-runtime": [279- "./dist/types/middleware/jsx/jsx-runtime.d.ts"279+ "./dist/types/jsx/jsx-runtime.d.ts"280 ],281 "jsx/jsx-dev-runtime": [282- "./dist/types/middleware/jsx/jsx-dev-runtime.d.ts"282+ "./dist/types/jsx/jsx-dev-runtime.d.ts"283 ],284 "jwt": [285 "./dist/types/middleware/jwt"286 ],39 unmodified lines326 "client": [327 "./dist/types/client/index.d.ts"328 ],329 "adapter": [330- "./dist/types/adapter.d.ts"330+ "./dist/types/helper/adapter/index.d.ts"331 ],332 "cloudflare-workers": [333 "./dist/types/adapter/cloudflare-workers"334 ],96 unmodified lines