Skip to content
Myr

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

48 files+1954 added−1853 removed

added:deno_dist/helper/adapter/index.ts+65 added
added:deno_dist/helper/cookie/index.ts+59 added
added:deno_dist/helper/html/index.ts+39 added
added:deno_dist/jsx/index.test.tsx+376 added
1import { html } from '../helper/html/index.ts'2import { Hono } from '../hono.ts'3import { jsx, memo, Fragment } from './index.ts'45interface SiteData {6 title: string7 children?: any8}910describe('JSX middleware', () => {11 let app: Hono1213 beforeEach(() => {14 app = new Hono()15 })1617 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 })2627 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>`3738 const Content = (props: { siteData: SiteData; name: string }) => (39 <Layout {...props.siteData}>40 <h1>{props.name}</h1>41 </Layout>42 )4344 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})6768describe('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 })7980 it('Empty elements are rended withtout closing tag', () => {81 const template = <input />82 expect(template.toString()).toBe('<input/>')83 })8485 it('Props value is null', () => {86 const template = <span data-hello={null}>Hello</span>87 expect(template.toString()).toBe('<span>Hello</span>')88 })8990 it('Props value is undefined', () => {91 const template = <span data-hello={undefined}>Hello</span>92 expect(template.toString()).toBe('<span>Hello</span>')93 })9495 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 })100101 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 })107108 // 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 })113114 it('falsy value', () => {115 const template = <span>{0}</span>116 expect(template.toString()).toBe('<span>0</span>')117 })118 })119120 // 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 })127128 // 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 })134135 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 })139140 it('no prop for checked={false}', () => {141 const template = <input type='checkbox' checked={false} />142 expect(template.toString()).toBe('<input type="checkbox"/>')143 })144145 it('default prop value for disabled', () => {146 const template = <input type='checkbox' disabled />147 expect(template.toString()).toBe('<input type="checkbox" disabled=""/>')148 })149150 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 })154155 it('no prop for disabled={false}', () => {156 const template = <input type='checkbox' disabled={false} />157 expect(template.toString()).toBe('<input type="checkbox"/>')158 })159160 it('default prop value for readonly', () => {161 const template = <input type='checkbox' readonly />162 expect(template.toString()).toBe('<input type="checkbox" readonly=""/>')163 })164165 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 })169170 it('no prop for readonly={false}', () => {171 const template = <input type='checkbox' readonly={false} />172 expect(template.toString()).toBe('<input type="checkbox"/>')173 })174175 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 })183184 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 })192193 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 })201202 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 })210211 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 })219220 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 })228229 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 })233234 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 })245246 // 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 }256257 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 }264265 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 })271272 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})292293describe('memo', () => {294 it('memoized', () => {295 let counter = 0296 const Header = memo(() => <title>Test Site {counter}</title>)297 const Body = () => <span>{counter}</span>298299 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 )312313 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 })328329 it('props are updated', () => {330 const Body = memo(({ counter }: { counter: number }) => <span>{counter}</span>)331332 let template = <Body counter={0} />333 expect(template.toString()).toBe('<span>0</span>')334335 template = <Body counter={1} />336 expect(template.toString()).toBe('<span>1</span>')337 })338339 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 )344345 let template = <Body counter={0} />346 expect(template.toString()).toBe('<span>0</span>')347348 template = <Body counter={1} />349 expect(template.toString()).toBe('<span>0</span>')350351 template = <Body counter={2} refresh={true} />352 expect(template.toString()).toBe('<span>2</span>')353 })354})355356describe('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 })366367 it('Should render nothing for empty Fragment', () => {368 const template = <></>369 expect(template.toString()).toBe('')370 })371372 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
1import { escapeToBuffer } from '../utils/html.ts'2import type { StringBuffer, HtmlEscaped, HtmlEscapedString } from '../utils/html.ts'34// eslint-disable-next-line @typescript-eslint/no-explicit-any5type Props = Record<string, any>67declare 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}1920const 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]37const 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]6465const 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}8586type Child = string | number | JSXNode | Child[]87export 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 }9798 toString(): string {99 const buffer: StringBuffer = ['']100 this.toStringToBuffer(buffer)101 return buffer[0]102 }103104 toStringToBuffer(buffer: StringBuffer): void {105 const tag = this.tag as string106 const props = this.props107 let { children } = this108109 buffer[0] += `<${tag}`110111 const propsKeys = Object.keys(props || {})112113 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 }139140 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 }149150 if (emptyTags.includes(tag as string)) {151 buffer[0] += '/>'152 return153 }154155 buffer[0] += '>'156157 childrenToStringToBuffer(children, buffer)158159 buffer[0] += `</${tag}>`160 }161}162163class JSXFunctionNode extends JSXNode {164 toStringToBuffer(buffer: StringBuffer): void {165 const { children } = this166167 const res = (this.tag as Function).call(null, {168 ...this.props,169 children: children.length <= 1 ? children[0] : children,170 })171172 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}181182class JSXFragmentNode extends JSXNode {183 toStringToBuffer(buffer: StringBuffer): void {184 childrenToStringToBuffer(this.children, buffer)185 }186}187188export { jsxFn as jsx }189const 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}200201type FC<T = Props> = (props: T) => HtmlEscapedString202203const shallowEqual = (a: Props, b: Props): boolean => {204 if (a === b) {205 return true206 }207208 const aKeys = Object.keys(a)209 const bKeys = Object.keys(b)210 if (aKeys.length !== bKeys.length) {211 return false212 }213214 for (let i = 0, len = aKeys.length; i < len; i++) {215 if (a[aKeys[i]] !== b[aKeys[i]]) {216 return false217 }218 }219220 return true221}222223export 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}237238export 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
added:deno_dist/jsx/jsx-runtime.ts+2 added
deleted:deno_dist/middleware/cookie/index.ts-59 removed
deleted:deno_dist/middleware/html/index.ts-39 removed
deleted:deno_dist/middleware/jsx/index.test.tsx-376 removed
1import { Hono } from '../../hono.ts'2import { html } from '../html/index.ts'3import { jsx, memo, Fragment } from './index.ts'45interface SiteData {6 title: string7 children?: any8}910describe('JSX middleware', () => {11 let app: Hono1213 beforeEach(() => {14 app = new Hono()15 })1617 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 })2627 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>`3738 const Content = (props: { siteData: SiteData; name: string }) => (39 <Layout {...props.siteData}>40 <h1>{props.name}</h1>41 </Layout>42 )4344 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})6768describe('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 })7980 it('Empty elements are rended withtout closing tag', () => {81 const template = <input />82 expect(template.toString()).toBe('<input/>')83 })8485 it('Props value is null', () => {86 const template = <span data-hello={null}>Hello</span>87 expect(template.toString()).toBe('<span>Hello</span>')88 })8990 it('Props value is undefined', () => {91 const template = <span data-hello={undefined}>Hello</span>92 expect(template.toString()).toBe('<span>Hello</span>')93 })9495 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 })100101 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 })107108 // 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 })113114 it('falsy value', () => {115 const template = <span>{0}</span>116 expect(template.toString()).toBe('<span>0</span>')117 })118 })119120 // 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 })127128 // 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 })134135 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 })139140 it('no prop for checked={false}', () => {141 const template = <input type='checkbox' checked={false} />142 expect(template.toString()).toBe('<input type="checkbox"/>')143 })144145 it('default prop value for disabled', () => {146 const template = <input type='checkbox' disabled />147 expect(template.toString()).toBe('<input type="checkbox" disabled=""/>')148 })149150 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 })154155 it('no prop for disabled={false}', () => {156 const template = <input type='checkbox' disabled={false} />157 expect(template.toString()).toBe('<input type="checkbox"/>')158 })159160 it('default prop value for readonly', () => {161 const template = <input type='checkbox' readonly />162 expect(template.toString()).toBe('<input type="checkbox" readonly=""/>')163 })164165 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 })169170 it('no prop for readonly={false}', () => {171 const template = <input type='checkbox' readonly={false} />172 expect(template.toString()).toBe('<input type="checkbox"/>')173 })174175 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 })183184 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 })192193 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 })201202 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 })210211 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 })219220 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 })228229 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 })233234 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 })245246 // 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 }256257 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 }264265 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 })271272 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})292293describe('memo', () => {294 it('memoized', () => {295 let counter = 0296 const Header = memo(() => <title>Test Site {counter}</title>)297 const Body = () => <span>{counter}</span>298299 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 )312313 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 })328329 it('props are updated', () => {330 const Body = memo(({ counter }: { counter: number }) => <span>{counter}</span>)331332 let template = <Body counter={0} />333 expect(template.toString()).toBe('<span>0</span>')334335 template = <Body counter={1} />336 expect(template.toString()).toBe('<span>1</span>')337 })338339 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 )344345 let template = <Body counter={0} />346 expect(template.toString()).toBe('<span>0</span>')347348 template = <Body counter={1} />349 expect(template.toString()).toBe('<span>0</span>')350351 template = <Body counter={2} refresh={true} />352 expect(template.toString()).toBe('<span>2</span>')353 })354})355356describe('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 })366367 it('Should render nothing for empty Fragment', () => {368 const template = <></>369 expect(template.toString()).toBe('')370 })371372 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
1import { escapeToBuffer } from '../../utils/html.ts'2import type { StringBuffer, HtmlEscaped, HtmlEscapedString } from '../../utils/html.ts'34// eslint-disable-next-line @typescript-eslint/no-explicit-any5type Props = Record<string, any>67declare 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}1920const 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]37const 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]6465const 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}8586type Child = string | number | JSXNode | Child[]87export 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 }9798 toString(): string {99 const buffer: StringBuffer = ['']100 this.toStringToBuffer(buffer)101 return buffer[0]102 }103104 toStringToBuffer(buffer: StringBuffer): void {105 const tag = this.tag as string106 const props = this.props107 let { children } = this108109 buffer[0] += `<${tag}`110111 const propsKeys = Object.keys(props || {})112113 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 }139140 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 }149150 if (emptyTags.includes(tag as string)) {151 buffer[0] += '/>'152 return153 }154155 buffer[0] += '>'156157 childrenToStringToBuffer(children, buffer)158159 buffer[0] += `</${tag}>`160 }161}162163class JSXFunctionNode extends JSXNode {164 toStringToBuffer(buffer: StringBuffer): void {165 const { children } = this166167 const res = (this.tag as Function).call(null, {168 ...this.props,169 children: children.length <= 1 ? children[0] : children,170 })171172 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}181182class JSXFragmentNode extends JSXNode {183 toStringToBuffer(buffer: StringBuffer): void {184 childrenToStringToBuffer(this.children, buffer)185 }186}187188export { jsxFn as jsx }189const 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}200201type FC<T = Props> = (props: T) => HtmlEscapedString202203const shallowEqual = (a: Props, b: Props): boolean => {204 if (a === b) {205 return true206 }207208 const aKeys = Object.keys(a)209 const bKeys = Object.keys(b)210 if (aKeys.length !== bKeys.length) {211 return false212 }213214 for (let i = 0, len = aKeys.length; i < len; i++) {215 if (a[aKeys[i]] !== b[aKeys[i]]) {216 return false217 }218 }219220 return true221}222223export 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}237238export 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
deleted:deno_dist/middleware/jsx/jsx-runtime.ts-2 removed
1export { jsxDEV as jsx, Fragment } from './jsx-dev-runtime.ts'2export { jsxDEV as jsxs } from './jsx-dev-runtime.ts'
modified:deno_dist/validator/validator.ts+1 added-1 removed
1import type { Context } from '../context.ts'2import { getCookie } from '../middleware/cookie/index.ts'2import { getCookie } from '../helper/cookie/index.ts'3import type { Env, ValidationTargets, MiddlewareHandler } from '../types.ts'45type ValidationTargetKeysWithBody = 'form' | 'json'6type ValidationTargetByMethod<M> = M extends 'get' | 'head' // GET and HEAD request must not have a body content.
92 unmodified lines
deleted:deno_dist/adapter.ts-30 removed
1import type { Context } from './context.ts'23export 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 any89 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 lines
357 // @ts-ignore358 return this.notFoundHandler(this)359 }360361 /** @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 lines
added:deno_dist/helper.ts+4 added
1// This file is for Deno to import helpers from `hono/helper.ts`.2export * from './helper/cookie/index.ts'3export * from './helper/html/index.ts'4export * 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`.2export * from './middleware/basic-auth/index.ts'3export * from './middleware/bearer-auth/index.ts'4export * from './middleware/cache/index.ts'5export * from './middleware/cookie/index.ts'5export * from './helper/cookie/index.ts' // will be moved to helper.ts in v46export * from './middleware/compress/index.ts'7export * from './middleware/cors/index.ts'8export * from './middleware/etag/index.ts'9export * from './middleware/html/index.ts'10export * from './middleware/jsx/index.ts'9export * from './helper/html/index.ts' // will be moved to helper.ts in v410export * from './jsx/index.ts'11export * from './middleware/jwt/index.ts'12export * from './middleware/logger/index.ts'13export * from './middleware/powered-by/index.ts'14export * from './middleware/timing/index.ts'
2 unmodified lines
modified:runtime_tests/bun/index.test.tsx+4 added-4 removed
1import { describe, expect, it } from 'bun:test'2import { env } from '../../src/adapter'2import { serveStatic } from '../../src/adapter/bun'3import { Context } from '../../src/context'4import { env, getRuntimeKey } from '../../src/helper/adapter'5import { Hono } from '../../src/index'6import { basicAuth } from '../../src/middleware/basic-auth'7import { jwt } from '../../src/middleware/jwt'8import { HonoRequest } from '../../src/request'910// Test just only minimal patterns.11// Because others are tested well in Cloudflare Workers environment already.12
14 unmodified lines
27 expect(res.headers.get('x-query')).toBe('bar')28 })2930 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})3435describe('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 lines
modified:runtime_tests/deno/hono.test.ts+2 added-3 removed
1import { env } from '../../deno_dist/adapter.ts'1import { Context } from '../../deno_dist/context.ts'2import { env, getRuntimeKey } from '../../deno_dist/helper.ts'3import { Hono } from '../../deno_dist/mod.ts'4import { HonoRequest } from '../../deno_dist/request.ts'5import { assertEquals } from './deps.ts'6
15 unmodified lines
22 assertEquals(res.headers.get('x-query'), 'bar')23})2425Deno.test('runtime', () => {26 const c = new Context(new HonoRequest(new Request('http://localhost/')))27 assertEquals(c.runtime, 'deno')26 assertEquals(getRuntimeKey(), 'deno')27})2829Deno.test('environment variables', () => {30 const c = new Context(new HonoRequest(new Request('http://localhost/')))
3 unmodified lines
modified:runtime_tests/fastly/index.test.ts+2 added-1 removed
1import { SHA256 } from 'crypto-js'2import { getRuntimeKey } from '../../src/helper/adapter'3import { Hono } from '../../src/index'4import { basicAuth } from '../../src/middleware/basic-auth'5import { jwt } from '../../src/middleware/jwt'6
5 unmodified lines
1213describe('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 })1819 it('Should return 200', async () => {20 const res = await app.request('http://localhost/')
77 unmodified lines
modified:runtime_tests/lagon/index.ts+2 added-2 removed
1import { Hono } from '../../src'2import { env } from '../../src/adapter'2import { env, getRuntimeKey } from '../../src/helper/adapter'3import { HTTPException } from '../../src/http-exception'4import { basicAuth } from '../../src/middleware/basic-auth'5import { bearerAuth } from '../../src/middleware/bearer-auth'6import { etag } from '../../src/middleware/etag'
58 unmodified lines
65app.get('/', (c) => c.text('Hono!!'))66// Use Response object directly67app.get('/hello', () => new Response('This is /hello'))6869app.get('/runtime', (c) => new Response(c.runtime))69app.get('/runtime', () => new Response(getRuntimeKey()))7071// Named parameter72app.get('/entry/:id', (c) => {73 const id = c.req.param('id')
59 unmodified lines
modified:runtime_tests/node/index.test.ts+2 added-2 removed
1import { createAdaptorServer } from '@hono/node-server'2import request from 'supertest'3import { Hono } from '../../src'4import { env } from '../../src/adapter'4import { Context } from '../../src/context'5import { env, getRuntimeKey } from '../../src/helper/adapter'6import { basicAuth } from '../../src/middleware/basic-auth'7import { jwt } from '../../src/middleware/jwt'8import { HonoRequest } from '../../src/request'9
6 unmodified lines
16 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 })2223 const server = createAdaptorServer(app)24
74 unmodified lines
modified:runtime_tests/wrangler/index.ts+1 added-1 removed
1import { env } from '../../src/adapter'1import { env } from '../../src/helper/adapter'2import { Hono } from '../../src/hono'34const app = new Hono()5
8 unmodified lines
added:src/helper/adapter/index.ts+65 added
1import type { Context } from '../../context'23export 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 any89 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}3132export const getRuntimeKey = () => {33 // eslint-disable-next-line @typescript-eslint/no-explicit-any34 const global = globalThis as any3536 if (global?.Deno !== undefined) {37 return 'deno'38 }3940 if (global?.Bun !== undefined) {41 return 'bun'42 }4344 if (typeof global?.WebSocketPair === 'function') {45 return 'workerd'46 }4748 if (typeof global?.EdgeRuntime === 'string') {49 return 'edge-light'50 }5152 if (global?.fastly !== undefined) {53 return 'fastly'54 }5556 if (global?.__lagon__ !== undefined) {57 return 'lagon'58 }5960 if (global?.process?.release?.name === 'node') {61 return 'node'62 }6364 return 'other'65}
added:src/helper/cookie/index.test.ts+251 added
1import { Hono } from '../../hono'2import { getCookie, getSignedCookie, setCookie, setSignedCookie, deleteCookie } from '.'34describe('Cookie Middleware', () => {5 describe('Parse cookie', () => {6 const apps: Record<string, Hono> = {}7 apps['get by name'] = (() => {8 const app = new Hono()910 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 })2021 return app22 })()2324 apps['get all as an object'] = (() => {25 const app = new Hono()2627 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 })3435 return app36 })()3738 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)4546 expect(res.headers.get('Yummy-Cookie')).toBe('choco')47 expect(res.headers.get('Tasty-Cookie')).toBe('strawberry')48 })49 })5051 const app = new Hono()5253 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 })6768 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 })7879 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 })8889 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 })99100 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 })108109 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 })119120 describe('Set cookie', () => {121 const app = new Hono()122123 app.get('/set-cookie', (c) => {124 setCookie(c, 'delicious_cookie', 'macha')125 return c.text('Give cookie')126 })127128 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 })134135 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 })140141 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 })147148 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 })160161 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 })169170 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 })183184 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 })192193 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 })198199 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 })206207 describe('Delete cookie', () => {208 const app = new Hono()209210 app.get('/delete-cookie', (c) => {211 deleteCookie(c, 'delicious_cookie')212 return c.text('Give cookie')213 })214215 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 })221222 app.get('/delete-cookie-multiple', (c) => {223 deleteCookie(c, 'delicious_cookie')224 deleteCookie(c, 'delicious_cookie2')225 return c.text('Give cookie')226 })227228 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 })234235 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 })243244 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
1import type { Context } from '../../context'2import { parse, parseSigned, serialize, serializeSigned } from '../../utils/cookie'3import type { CookieOptions, Cookie, SignedCookie } from '../../utils/cookie'45interface GetCookie {6 (c: Context, key: string): string | undefined7 (c: Context): Cookie8}910interface GetSignedCookie {11 (c: Context, secret: string, key: string): Promise<string | undefined | false>12 (c: Context, secret: string): Promise<SignedCookie>13}1415export 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}2728export 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}4041export 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}4546export 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}5657export 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
1import { html, raw } from '.'23describe('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 &quot;Johnny&quot; Smith.</p>")8 })910 describe('Booleans, Null, and Undefined Are Ignored', () => {11 it.each([true, false, undefined, null])('%s', (item) => {12 expect(html`${item}`.toString()).toBe('')13 })1415 it('falsy value', () => {16 expect(html`${0}`.toString()).toBe('0')17 })18 })1920 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 &quot;Johnny&quot; Smith Contact:<a href="http://example.com/">My Website</a></p>'29 )30 })31})3233describe('raw', () => {34 it('Should be marked as escaped.', () => {35 const name = 'John &quot;Johnny&quot; Smith'36 expect(html`<p>I'm ${raw(name)}.</p>`.toString()).toBe(37 // eslint-disable-next-line quotes38 "<p>I'm John &quot;Johnny&quot; Smith.</p>"39 )40 })41})
added:src/helper/html/index.ts+39 added
1import { escapeToBuffer } from '../../utils/html'2import type { StringBuffer, HtmlEscaped, HtmlEscapedString } from '../../utils/html'34export const raw = (value: unknown): HtmlEscapedString => {5 const escapedString = new String(value) as HtmlEscapedString6 escapedString.isEscaped = true78 return escapedString9}1011export const html = (strings: TemplateStringsArray, ...values: unknown[]): HtmlEscapedString => {12 const buffer: StringBuffer = ['']1314 for (let i = 0, len = strings.length - 1; i < len; i++) {15 buffer[0] += strings[i]1617 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]3738 return raw(buffer[0])39}
added:src/jsx/index.test.tsx+376 added
1import { html } from '../helper/html'2import { Hono } from '../hono'3import { jsx, memo, Fragment } from './index'45interface SiteData {6 title: string7 children?: any8}910describe('JSX middleware', () => {11 let app: Hono1213 beforeEach(() => {14 app = new Hono()15 })1617 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 })2627 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>`3738 const Content = (props: { siteData: SiteData; name: string }) => (39 <Layout {...props.siteData}>40 <h1>{props.name}</h1>41 </Layout>42 )4344 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})6768describe('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 })7980 it('Empty elements are rended withtout closing tag', () => {81 const template = <input />82 expect(template.toString()).toBe('<input/>')83 })8485 it('Props value is null', () => {86 const template = <span data-hello={null}>Hello</span>87 expect(template.toString()).toBe('<span>Hello</span>')88 })8990 it('Props value is undefined', () => {91 const template = <span data-hello={undefined}>Hello</span>92 expect(template.toString()).toBe('<span>Hello</span>')93 })9495 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 })100101 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 })107108 // 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 })113114 it('falsy value', () => {115 const template = <span>{0}</span>116 expect(template.toString()).toBe('<span>0</span>')117 })118 })119120 // 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 })127128 // 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 })134135 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 })139140 it('no prop for checked={false}', () => {141 const template = <input type='checkbox' checked={false} />142 expect(template.toString()).toBe('<input type="checkbox"/>')143 })144145 it('default prop value for disabled', () => {146 const template = <input type='checkbox' disabled />147 expect(template.toString()).toBe('<input type="checkbox" disabled=""/>')148 })149150 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 })154155 it('no prop for disabled={false}', () => {156 const template = <input type='checkbox' disabled={false} />157 expect(template.toString()).toBe('<input type="checkbox"/>')158 })159160 it('default prop value for readonly', () => {161 const template = <input type='checkbox' readonly />162 expect(template.toString()).toBe('<input type="checkbox" readonly=""/>')163 })164165 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 })169170 it('no prop for readonly={false}', () => {171 const template = <input type='checkbox' readonly={false} />172 expect(template.toString()).toBe('<input type="checkbox"/>')173 })174175 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 })183184 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 })192193 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 })201202 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 })210211 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 })219220 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 })228229 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 })233234 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 })245246 // 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 }256257 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 }264265 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 })271272 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})292293describe('memo', () => {294 it('memoized', () => {295 let counter = 0296 const Header = memo(() => <title>Test Site {counter}</title>)297 const Body = () => <span>{counter}</span>298299 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 )312313 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 })328329 it('props are updated', () => {330 const Body = memo(({ counter }: { counter: number }) => <span>{counter}</span>)331332 let template = <Body counter={0} />333 expect(template.toString()).toBe('<span>0</span>')334335 template = <Body counter={1} />336 expect(template.toString()).toBe('<span>1</span>')337 })338339 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 )344345 let template = <Body counter={0} />346 expect(template.toString()).toBe('<span>0</span>')347348 template = <Body counter={1} />349 expect(template.toString()).toBe('<span>0</span>')350351 template = <Body counter={2} refresh={true} />352 expect(template.toString()).toBe('<span>2</span>')353 })354})355356describe('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 })366367 it('Should render nothing for empty Fragment', () => {368 const template = <></>369 expect(template.toString()).toBe('')370 })371372 it('Should render nothing for undefined', () => {373 const template = <>{undefined}</>374 expect(template.toString()).toBe('')375 })376})
added:src/jsx/index.ts+240 added
1import { escapeToBuffer } from '../utils/html'2import type { StringBuffer, HtmlEscaped, HtmlEscapedString } from '../utils/html'34// eslint-disable-next-line @typescript-eslint/no-explicit-any5type Props = Record<string, any>67declare 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}1920const 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]37const 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]6465const 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}8586type Child = string | number | JSXNode | Child[]87export 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 }9798 toString(): string {99 const buffer: StringBuffer = ['']100 this.toStringToBuffer(buffer)101 return buffer[0]102 }103104 toStringToBuffer(buffer: StringBuffer): void {105 const tag = this.tag as string106 const props = this.props107 let { children } = this108109 buffer[0] += `<${tag}`110111 const propsKeys = Object.keys(props || {})112113 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 }139140 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 }149150 if (emptyTags.includes(tag as string)) {151 buffer[0] += '/>'152 return153 }154155 buffer[0] += '>'156157 childrenToStringToBuffer(children, buffer)158159 buffer[0] += `</${tag}>`160 }161}162163class JSXFunctionNode extends JSXNode {164 toStringToBuffer(buffer: StringBuffer): void {165 const { children } = this166167 const res = (this.tag as Function).call(null, {168 ...this.props,169 children: children.length <= 1 ? children[0] : children,170 })171172 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}181182class JSXFragmentNode extends JSXNode {183 toStringToBuffer(buffer: StringBuffer): void {184 childrenToStringToBuffer(this.children, buffer)185 }186}187188export { jsxFn as jsx }189const 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}200201type FC<T = Props> = (props: T) => HtmlEscapedString202203const shallowEqual = (a: Props, b: Props): boolean => {204 if (a === b) {205 return true206 }207208 const aKeys = Object.keys(a)209 const bKeys = Object.keys(b)210 if (aKeys.length !== bKeys.length) {211 return false212 }213214 for (let i = 0, len = aKeys.length; i < len; i++) {215 if (a[aKeys[i]] !== b[aKeys[i]]) {216 return false217 }218 }219220 return true221}222223export 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}237238export const Fragment = (props: { key?: string; children?: Child[] }): JSXNode => {239 return new JSXFragmentNode('', {}, props.children || [])240}
added:src/jsx/jsx-dev-runtime.ts+10 added
1import type { HtmlEscapedString } from '../utils/html'2import { jsx } from '.'3import type { JSXNode } from '.'4export { Fragment } from '.'56export 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
1export { jsxDEV as jsx, Fragment } from './jsx-dev-runtime'2export { jsxDEV as jsxs } from './jsx-dev-runtime'
deleted:src/middleware/cookie/index.test.ts-251 removed
1import { Hono } from '../../hono'2import { getCookie, getSignedCookie, setCookie, setSignedCookie, deleteCookie } from '.'34describe('Cookie Middleware', () => {5 describe('Parse cookie', () => {6 const apps: Record<string, Hono> = {}7 apps['get by name'] = (() => {8 const app = new Hono()910 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 })2021 return app22 })()2324 apps['get all as an object'] = (() => {25 const app = new Hono()2627 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 })3435 return app36 })()3738 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)4546 expect(res.headers.get('Yummy-Cookie')).toBe('choco')47 expect(res.headers.get('Tasty-Cookie')).toBe('strawberry')48 })49 })5051 const app = new Hono()5253 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 })6768 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 })7879 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 })8889 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 })99100 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 })108109 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 })119120 describe('Set cookie', () => {121 const app = new Hono()122123 app.get('/set-cookie', (c) => {124 setCookie(c, 'delicious_cookie', 'macha')125 return c.text('Give cookie')126 })127128 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 })134135 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 })140141 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 })147148 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 })160161 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 })169170 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 })183184 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 })192193 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 })198199 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 })206207 describe('Delete cookie', () => {208 const app = new Hono()209210 app.get('/delete-cookie', (c) => {211 deleteCookie(c, 'delicious_cookie')212 return c.text('Give cookie')213 })214215 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 })221222 app.get('/delete-cookie-multiple', (c) => {223 deleteCookie(c, 'delicious_cookie')224 deleteCookie(c, 'delicious_cookie2')225 return c.text('Give cookie')226 })227228 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 })234235 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 })243244 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
1import type { Context } from '../../context'2import { parse, parseSigned, serialize, serializeSigned } from '../../utils/cookie'3import type { CookieOptions, Cookie, SignedCookie } from '../../utils/cookie'45interface GetCookie {6 (c: Context, key: string): string | undefined7 (c: Context): Cookie8}910interface GetSignedCookie {11 (c: Context, secret: string, key: string): Promise<string | undefined | false>12 (c: Context, secret: string): Promise<SignedCookie>13}1415export 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}2728export 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}4041export 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}4546export 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}5657export 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
1import { html, raw } from '.'23describe('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 &quot;Johnny&quot; Smith.</p>")8 })910 describe('Booleans, Null, and Undefined Are Ignored', () => {11 it.each([true, false, undefined, null])('%s', (item) => {12 expect(html`${item}`.toString()).toBe('')13 })1415 it('falsy value', () => {16 expect(html`${0}`.toString()).toBe('0')17 })18 })1920 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 &quot;Johnny&quot; Smith Contact:<a href="http://example.com/">My Website</a></p>'29 )30 })31})3233describe('raw', () => {34 it('Should be marked as escaped.', () => {35 const name = 'John &quot;Johnny&quot; Smith'36 expect(html`<p>I'm ${raw(name)}.</p>`.toString()).toBe(37 // eslint-disable-next-line quotes38 "<p>I'm John &quot;Johnny&quot; Smith.</p>"39 )40 })41})
deleted:src/middleware/html/index.ts-39 removed
1import { escapeToBuffer } from '../../utils/html'2import type { StringBuffer, HtmlEscaped, HtmlEscapedString } from '../../utils/html'34export const raw = (value: unknown): HtmlEscapedString => {5 const escapedString = new String(value) as HtmlEscapedString6 escapedString.isEscaped = true78 return escapedString9}1011export const html = (strings: TemplateStringsArray, ...values: unknown[]): HtmlEscapedString => {12 const buffer: StringBuffer = ['']1314 for (let i = 0, len = strings.length - 1; i < len; i++) {15 buffer[0] += strings[i]1617 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]3738 return raw(buffer[0])39}
deleted:src/middleware/jsx/index.test.tsx-376 removed
1import { Hono } from '../../hono'2import { html } from '../html/index'3import { jsx, memo, Fragment } from './index'45interface SiteData {6 title: string7 children?: any8}910describe('JSX middleware', () => {11 let app: Hono1213 beforeEach(() => {14 app = new Hono()15 })1617 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 })2627 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>`3738 const Content = (props: { siteData: SiteData; name: string }) => (39 <Layout {...props.siteData}>40 <h1>{props.name}</h1>41 </Layout>42 )4344 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})6768describe('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 })7980 it('Empty elements are rended withtout closing tag', () => {81 const template = <input />82 expect(template.toString()).toBe('<input/>')83 })8485 it('Props value is null', () => {86 const template = <span data-hello={null}>Hello</span>87 expect(template.toString()).toBe('<span>Hello</span>')88 })8990 it('Props value is undefined', () => {91 const template = <span data-hello={undefined}>Hello</span>92 expect(template.toString()).toBe('<span>Hello</span>')93 })9495 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 })100101 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 })107108 // 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 })113114 it('falsy value', () => {115 const template = <span>{0}</span>116 expect(template.toString()).toBe('<span>0</span>')117 })118 })119120 // 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 })127128 // 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 })134135 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 })139140 it('no prop for checked={false}', () => {141 const template = <input type='checkbox' checked={false} />142 expect(template.toString()).toBe('<input type="checkbox"/>')143 })144145 it('default prop value for disabled', () => {146 const template = <input type='checkbox' disabled />147 expect(template.toString()).toBe('<input type="checkbox" disabled=""/>')148 })149150 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 })154155 it('no prop for disabled={false}', () => {156 const template = <input type='checkbox' disabled={false} />157 expect(template.toString()).toBe('<input type="checkbox"/>')158 })159160 it('default prop value for readonly', () => {161 const template = <input type='checkbox' readonly />162 expect(template.toString()).toBe('<input type="checkbox" readonly=""/>')163 })164165 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 })169170 it('no prop for readonly={false}', () => {171 const template = <input type='checkbox' readonly={false} />172 expect(template.toString()).toBe('<input type="checkbox"/>')173 })174175 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 })183184 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 })192193 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 })201202 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 })210211 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 })219220 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 })228229 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 })233234 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 })245246 // 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 }256257 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 }264265 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 })271272 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})292293describe('memo', () => {294 it('memoized', () => {295 let counter = 0296 const Header = memo(() => <title>Test Site {counter}</title>)297 const Body = () => <span>{counter}</span>298299 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 )312313 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 })328329 it('props are updated', () => {330 const Body = memo(({ counter }: { counter: number }) => <span>{counter}</span>)331332 let template = <Body counter={0} />333 expect(template.toString()).toBe('<span>0</span>')334335 template = <Body counter={1} />336 expect(template.toString()).toBe('<span>1</span>')337 })338339 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 )344345 let template = <Body counter={0} />346 expect(template.toString()).toBe('<span>0</span>')347348 template = <Body counter={1} />349 expect(template.toString()).toBe('<span>0</span>')350351 template = <Body counter={2} refresh={true} />352 expect(template.toString()).toBe('<span>2</span>')353 })354})355356describe('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 })366367 it('Should render nothing for empty Fragment', () => {368 const template = <></>369 expect(template.toString()).toBe('')370 })371372 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
1import { escapeToBuffer } from '../../utils/html'2import type { StringBuffer, HtmlEscaped, HtmlEscapedString } from '../../utils/html'34// eslint-disable-next-line @typescript-eslint/no-explicit-any5type Props = Record<string, any>67declare 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}1920const 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]37const 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]6465const 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}8586type Child = string | number | JSXNode | Child[]87export 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 }9798 toString(): string {99 const buffer: StringBuffer = ['']100 this.toStringToBuffer(buffer)101 return buffer[0]102 }103104 toStringToBuffer(buffer: StringBuffer): void {105 const tag = this.tag as string106 const props = this.props107 let { children } = this108109 buffer[0] += `<${tag}`110111 const propsKeys = Object.keys(props || {})112113 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 }139140 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 }149150 if (emptyTags.includes(tag as string)) {151 buffer[0] += '/>'152 return153 }154155 buffer[0] += '>'156157 childrenToStringToBuffer(children, buffer)158159 buffer[0] += `</${tag}>`160 }161}162163class JSXFunctionNode extends JSXNode {164 toStringToBuffer(buffer: StringBuffer): void {165 const { children } = this166167 const res = (this.tag as Function).call(null, {168 ...this.props,169 children: children.length <= 1 ? children[0] : children,170 })171172 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}181182class JSXFragmentNode extends JSXNode {183 toStringToBuffer(buffer: StringBuffer): void {184 childrenToStringToBuffer(this.children, buffer)185 }186}187188export { jsxFn as jsx }189const 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}200201type FC<T = Props> = (props: T) => HtmlEscapedString202203const shallowEqual = (a: Props, b: Props): boolean => {204 if (a === b) {205 return true206 }207208 const aKeys = Object.keys(a)209 const bKeys = Object.keys(b)210 if (aKeys.length !== bKeys.length) {211 return false212 }213214 for (let i = 0, len = aKeys.length; i < len; i++) {215 if (a[aKeys[i]] !== b[aKeys[i]]) {216 return false217 }218 }219220 return true221}222223export 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}237238export 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
1import type { HtmlEscapedString } from '../../utils/html'2import { jsx } from '.'3import type { JSXNode } from '.'4export { Fragment } from '.'56export 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
1export { jsxDEV as jsx, Fragment } from './jsx-dev-runtime'2export { jsxDEV as jsxs } from './jsx-dev-runtime'
modified:src/validator/validator.ts+1 added-1 removed
1import type { Context } from '../context'2import { getCookie } from '../middleware/cookie'2import { getCookie } from '../helper/cookie'3import type { Env, ValidationTargets, MiddlewareHandler } from '../types'45type ValidationTargetKeysWithBody = 'form' | 'json'6type ValidationTargetByMethod<M> = M extends 'get' | 'head' // GET and HEAD request must not have a body content.
92 unmodified lines
deleted:src/adapter.ts-30 removed
1import type { Context } from './context'23export 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 any89 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 lines
357 // @ts-ignore358 return this.notFoundHandler(this)359 }360361 /** @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 lines
added:src/helper.ts+4 added
1// This file is for Deno to import helpers from `hono/helper.ts`.2export * from './helper/cookie'3export * from './helper/html'4export * from './helper/adapter'
modified:src/hono.test.ts-1 removed
1/* eslint-disable @typescript-eslint/no-unused-vars */2import { env } from './adapter'2import type { Context } from './context'3import { Hono } from './hono'4import { HTTPException } from './http-exception'5import { logger } from './middleware/logger'
2352 unmodified lines
modified:src/middleware.ts+4 added-4 removed
1// Middleware1// This file is for Deno to import middleware from `hono/middleware.ts`.2export * from './middleware/basic-auth'3export * from './middleware/bearer-auth'4export * from './middleware/cache'5export * from './middleware/cookie'5export * from './helper/cookie' // will be moved to helper.ts in v46export * from './middleware/compress'7export * from './middleware/cors'8export * from './middleware/etag'9export * from './middleware/html'10export * from './middleware/jsx'9export * from './helper/html' // will be moved to helper.ts in v410export * from './jsx'11export * from './middleware/jwt'12export * from './middleware/logger'13export * from './middleware/powered-by'14export * from './middleware/timing'
2 unmodified lines
modified:package.json+25 added-25 removed
10 unmodified lines
11 ],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 lines
73 "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 lines
93 "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 lines
188 "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 lines
257 "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 lines
269 "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 lines
326 "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