Merge branch 'main' into next
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Yusuke Wada · committed by Yusuke Wada · parents 466bf49, 5db68b5 · Browse files · 17 files·+249 added−80 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
17 files+249 added−80 removed
- tests:+154 added−46 removed
- other:+95 added−34 removed
Provenance
- Commit
a64be6d- Tree
db0c1a3- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
Yusuke Wada <yusuke@kamawada.com>- Parent 1
466bf49- Parent 2
5db68b5
17 files changed+249 added−80 removed
modified:deno_dist/helper/ssg/index.ts+4 added-8 removed
1 import { replaceUrlParam } from '../../client/utils.ts'2 import type { Context } from '../../context.ts'3 import type { Hono } from '../../hono.ts'4 import type { Env, MiddlewareHandler, Schema } from '../../types.ts'5-import { bufferToString } from '../../utils/buffer.ts'5 import { createPool } from '../../utils/concurrent.ts'6 import { getExtension } from '../../utils/mime.ts'7 import { joinPaths, dirname, filterStaticGenerateRoutes } from './utils.ts'8 234 unmodified lines243 }244 if (typeof content === 'string') {245 await fsModule.writeFile(filePath, content)246 } else if (content instanceof ArrayBuffer) {248- await fsModule.writeFile(filePath, bufferToString(content))247+ await fsModule.writeFile(filePath, new Uint8Array(content))248 }249 return filePath250 }251 1 unmodified line253 * @experimental254 * `ToSSGInterface` is an experimental feature.255 * The API might be changed.256 */258-export interface ToSSGInterface<259- E extends Env = Env,260- S extends Schema = {},261- BasePath extends string = '/'262-> {257+export interface ToSSGInterface {258 (264- app: Hono<E, S, BasePath>,259+ // eslint-disable-next-line @typescript-eslint/no-explicit-any260+ app: Hono<any, any, any>,261 fsModule: FileSystemModule,262 options?: ToSSGOptions263 ): Promise<ToSSGResult>264 }96 unmodified linesmodified:deno_dist/jsx/hooks/index.ts+11 added-1 removed
7 unmodified lines8 export const STASH_EFFECT = 19 const STASH_CALLBACK = 210 const STASH_USE = 311 const STASH_MEMO = 412+const STASH_REF = 513 14 export type EffectData = [15 readonly unknown[] | undefined, // deps16 (() => void | (() => void)) | undefined, // layout effect260 unmodified lines277 }278 279 export type RefObject<T> = { current: T | null }280 export const useRef = <T>(initialValue: T | null): RefObject<T> => {281+ const buildData = buildDataStack.at(-1) as [unknown, NodeObject]282+ if (!buildData) {280- return { current: initialValue }283+ return { current: initialValue }284+ }285+ const [, node] = buildData286+287+ const refArray = (node[DOM_STASH][1][STASH_REF] ||= [])288+ const hookIndex = node[DOM_STASH][0]++289+290+ return (refArray[hookIndex] ||= { current: initialValue })291 }292 293 export const use = <T>(promise: Promise<T>): T => {294 const cachedRes = resolvedPromiseValueMap.get(promise) as [T] | [undefined, unknown] | undefined60 unmodified linesmodified:deno_dist/jsx/jsx-runtime.ts+2 added-1 removed
123456678export { jsxDEV as jsx, Fragment } from './jsx-dev-runtime.ts'export { jsxDEV as jsxs } from './jsx-dev-runtime.ts'
import { raw, html } from '../helper/html/index.ts'export { html as jsxTemplate }export const jsxAttr = (name: string, value: string) => raw(name + '="' + html`${value}` + '"')export const jsxAttr = (name: string, value: string | Promise<string>) => typeof value === 'string' ? raw(name + '="' + html`${value}` + '"') : html`${name}="${value}"`export const jsxEscape = (value: string) => valuemodified:deno_dist/utils/stream.ts+8 added-1 removed
10 unmodified lines11121314151617181920212223242538 unmodified lines64656667616869707110 unmodified lines this.encoder = new TextEncoder()
const reader = _readable.getReader()
// in case the user disconnects, let the reader know to cancel // this in-turn results in responseReadable being closed // and writeSSE method no longer blocks indefinitely this.abortSubscribers.push(async () => { await reader.cancel() })
this.responseReadable = new ReadableStream({ async pull(controller) { const { done, value } = await reader.read() done ? controller.close() : controller.enqueue(value)38 unmodified lines await body.pipeTo(this.writable, { preventClose: true }) this.writer = this.writable.getWriter() }
async onAbort(listener: () => void | Promise<void>) { onAbort(listener: () => void | Promise<void>) { this.abortSubscribers.push(listener) }}modified:deno_dist/types.ts+21 added-5 removed
20 unmodified lines21 22 export type Next = () => Promise<void>23 24 export type Input = {25- in?: Partial<ValidationTargets>26- out?: Partial<{ [K in keyof ValidationTargets]: unknown }>25+ in?: {}26+ out?: {}27 }28 29 export type BlankSchema = {}30 export type BlankInput = {}1583 unmodified lines1614 ? {1615 input: Input extends { param: infer _ }1616 ? ExtractParams<SubPath> extends never1617 ? Input1618- : FlattenIfIntersect<Input & { param: ExtractParams<SubPath> }>1618+ : FlattenIfIntersect<1619+ Input & {1620+ param: {1621+ // Maps extracted keys, stripping braces, to a string-typed record.1622+ [K in keyof ExtractParams<SubPath> as K extends `${infer Prefix}{${infer _}}`1623+ ? Prefix1624+ : K]: string1625+ }1626+ }1627+ >1628 : RemoveBlankRecord<ExtractParams<SubPath>> extends never1629 ? Input1621- : Input & { param: ExtractParams<SubPath> }1630+ : Input & {1631+ // Maps extracted keys, stripping braces, to a string-typed record.1632+ param: {1633+ [K in keyof ExtractParams<SubPath> as K extends `${infer Prefix}{${infer _}}`1634+ ? Prefix1635+ : K]: string1636+ }1637+ }1638 output: Output1639 }1640 : never1641 }28 unmodified lines1670 ////////////////////////////////////////1671 1672 export type TypedResponse<T = unknown> = {1673 data: T1658- format: 'json' // Currently, support only `json` with `c.jsonT()`1674+ format: 'json' // Currently, support only `json` with `c.json()`1675 }1676 1677 type ExtractResponseData<T> = T extends Promise<infer T2>1678 ? T2 extends TypedResponse<infer U>93 unmodified linesmodified:runtime_tests/deno-jsx/jsx.test.tsx+25 added
12345678970 unmodified lines8081828384858687888990919293949596979899100101102103104105106/** @jsxImportSource ../../deno_dist/jsx */import { Style, css } from '../../deno_dist/helper/css/index.ts'import { Suspense, renderToReadableStream } from '../../deno_dist/jsx/streaming.ts'import type { HtmlEscapedString } from '../../deno_dist/utils/html.ts'import { resolveCallback, HtmlEscapedCallbackPhase } from '../../deno_dist/utils/html.ts'import { assertEquals } from '../deno/deps.ts'
Deno.test('JSX', () => { const Component = ({ name }: { name: string }) => <span>{name}</span>70 unmodified lines})(document)</script>`, ])})
Deno.test('JSX: css', async () => { const className = css` color: red; ` const html = ( <html> <head> <Style /> </head> <body> <div class={className}></div> </body> </html> )
const awaitedHtml = await html const htmlEscapedString = 'callbacks' in awaitedHtml ? awaitedHtml : await awaitedHtml.toString() assertEquals( await resolveCallback(htmlEscapedString, HtmlEscapedCallbackPhase.Stringify, false, {}), '<html><head><style id="hono-css">.css-3142110215{color:red}</style></head><body><div class="css-3142110215"></div></body></html>' )})modified:src/helper/ssg/index.test.tsx+38 added-2 removed
291 unmodified lines292 })293 })294 295 describe('saveContentToFile function', () => {296+ // tar.gz, testdir/test.txt297+ const gzFileBuffer = Buffer.from(298+ 'H4sIAAAAAAAAA+3SQQrCMBSE4aw9RU6gSc3LO0/FLgqukgj29qZgsQgqCEHE/9vMIoEMTMqQy3FMO9OQq1RkTq/i1rkwPkiMUXWvnXG+U/XGSstSi3MufbLWHIZ0mvLYP7v37vxHldv+c27LpbR4Yx44hvBi/3DfX3zdP0j9Eta1KPPoz/ef+mnz7Q4AAAAAAAAAAAAAAAAAPnMFqt1/BQAoAAA=',299+ 'base64'300+ )301+ const gzFileArrayBuffer = gzFileBuffer.buffer.slice(302+ gzFileBuffer.byteOffset,303+ gzFileBuffer.byteLength + gzFileBuffer.byteOffset304+ )305+ // PNG, red dot (1x1)306+ const pngFileBuffer = Buffer.from(307+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCCAAAALw',308+ 'base64'309+ )310+ const pngFileArrayBuffer = pngFileBuffer.buffer.slice(311+ pngFileBuffer.byteOffset,312+ pngFileBuffer.byteLength + pngFileBuffer.byteOffset313+ )314+315 const fileData = [316 { routePath: '/', content: 'Home Page', mimeType: 'text/html' },317 { routePath: '/index.html', content: 'Home Page2', mimeType: 'text/html' },318 { routePath: '/about', content: 'About Page', mimeType: 'text/html' },319 { routePath: '/about/', content: 'About Page', mimeType: 'text/html' },320 { routePath: '/bravo/index.html', content: 'About Page', mimeType: 'text/html' },302- { routePath: '/bravo/index.tar.gz', content: 'About Page', mimeType: 'application/gzip' },321 { routePath: '/bravo/release-4.0.0', content: 'Release 4.0.0', mimeType: 'text/html' },322 {323 routePath: '/bravo/2024.02.18-sweet-memories',324 content: 'Sweet Memories',2 unmodified lines327 { routePath: '/bravo/deep.dive.to.html', content: 'Deep Dive To HTML', mimeType: 'text/html' },328 { routePath: '/bravo/alert.js', content: 'alert("evil content")', mimeType: 'text/html' },329 { routePath: '/bravo.text/index.html', content: 'About Page', mimeType: 'text/html' },330 { routePath: '/bravo.text/', content: 'Bravo Page', mimeType: 'text/html' },331+ {332+ routePath: '/bravo/index.tar.gz',333+ content: gzFileArrayBuffer,334+ mimeType: 'application/gzip',335+ },336+ {337+ routePath: '/bravo/dot.png',338+ content: pngFileArrayBuffer,339+ mimeType: 'image/png',340+ },341 ]342 343 let fsMock: FileSystemModule344 13 unmodified lines358 expect(fsMock.writeFile).toHaveBeenCalledWith('static/index.html', 'Home Page2')359 expect(fsMock.writeFile).toHaveBeenCalledWith('static/about.html', 'About Page')360 expect(fsMock.writeFile).toHaveBeenCalledWith('static/about/index.html', 'About Page')361 expect(fsMock.writeFile).toHaveBeenCalledWith('static/bravo/index.html', 'About Page')334- expect(fsMock.writeFile).toHaveBeenCalledWith('static/bravo/index.tar.gz', 'About Page')362 expect(fsMock.writeFile).toHaveBeenCalledWith(363 'static/bravo/release-4.0.0.html',364 'Release 4.0.0'365 )10 unmodified lines376 'alert("evil content")'377 )378 expect(fsMock.writeFile).toHaveBeenCalledWith('static/bravo.text/index.html', 'About Page')379 expect(fsMock.writeFile).toHaveBeenCalledWith('static/bravo.text/index.html', 'Bravo Page')380+ // binary files381+ expect(fsMock.writeFile).toHaveBeenCalledWith(382+ 'static/bravo/index.tar.gz',383+ new Uint8Array(gzFileArrayBuffer)384+ )385+ expect(fsMock.writeFile).toHaveBeenCalledWith(386+ 'static/bravo/dot.png',387+ new Uint8Array(pngFileArrayBuffer)388+ )389 })390 391 it('should correctly create directories if they do not exist', async () => {392 await saveContentToFile(116 unmodified linesmodified:src/helper/ssg/index.ts+4 added-8 removed
1 import { replaceUrlParam } from '../../client/utils'2 import type { Context } from '../../context'3 import type { Hono } from '../../hono'4 import type { Env, MiddlewareHandler, Schema } from '../../types'5-import { bufferToString } from '../../utils/buffer'5 import { createPool } from '../../utils/concurrent'6 import { getExtension } from '../../utils/mime'7 import { joinPaths, dirname, filterStaticGenerateRoutes } from './utils'8 234 unmodified lines243 }244 if (typeof content === 'string') {245 await fsModule.writeFile(filePath, content)246 } else if (content instanceof ArrayBuffer) {248- await fsModule.writeFile(filePath, bufferToString(content))247+ await fsModule.writeFile(filePath, new Uint8Array(content))248 }249 return filePath250 }251 1 unmodified line253 * @experimental254 * `ToSSGInterface` is an experimental feature.255 * The API might be changed.256 */258-export interface ToSSGInterface<259- E extends Env = Env,260- S extends Schema = {},261- BasePath extends string = '/'262-> {257+export interface ToSSGInterface {258 (264- app: Hono<E, S, BasePath>,259+ // eslint-disable-next-line @typescript-eslint/no-explicit-any260+ app: Hono<any, any, any>,261 fsModule: FileSystemModule,262 options?: ToSSGOptions263 ): Promise<ToSSGResult>264 }96 unmodified linesmodified:src/jsx/dom/index.test.tsx+72 added-44 removed
918 unmodified lines919 expect(root.innerHTML).toBe('<div><div><p>Count: 1</p></div><button>+</button></div>')920 expect(renderCount).toBe(2)921 })922 923+ describe('useRef', async () => {923- it('useRef', async () => {924- const Input = ({ label, ref }: { label: string; ref: RefObject<HTMLInputElement> }) => {925- return (926- <div>927- <label>{label}</label>928- <input ref={ref} />929- </div>924+ it('simple', async () => {925+ const Input = ({ label, ref }: { label: string; ref: RefObject<HTMLInputElement> }) => {926+ return (927+ <div>928+ <label>{label}</label>929+ <input ref={ref} />930+ </div>931+ )932+ }933+ const Form = () => {934+ const [values, setValues] = useState<{ [key: string]: string }>({})935+ const nameRef = useRef<HTMLInputElement>(null)936+ const emailRef = useRef<HTMLInputElement>(null)937+ return (938+ <form>939+ <Input label='Name' ref={nameRef} />940+ <Input label='Email' ref={emailRef} />941+ <button942+ onClick={(ev: Event) => {943+ ev.preventDefault()944+ setValues({945+ name: nameRef.current?.value || '',946+ email: emailRef.current?.value || '',947+ })948+ }}949+ >950+ serialize951+ </button>952+ <span>{JSON.stringify(values)}</span>953+ </form>954+ )955+ }956+ const app = <Form />957+ render(app, root)958+ expect(root.innerHTML).toBe(959+ '<form><div><label>Name</label><input></div><div><label>Email</label><input></div><button>serialize</button><span>{}</span></form>'960 )931- }932- const Form = () => {933- const [values, setValues] = useState<{ [key: string]: string }>({})934- const nameRef = useRef<HTMLInputElement>(null)935- const emailRef = useRef<HTMLInputElement>(null)936- return (937- <form>938- <Input label='Name' ref={nameRef} />939- <Input label='Email' ref={emailRef} />940- <button941- onClick={(ev: Event) => {942- ev.preventDefault()943- setValues({944- name: nameRef.current?.value || '',945- email: emailRef.current?.value || '',946- })947- }}948- >949- serialize950- </button>951- <span>{JSON.stringify(values)}</span>952- </form>961+ const [nameInput, emailInput] = root.querySelectorAll('input')962+ nameInput.value = 'John'963+ emailInput.value = 'john@example.com'964+ const [button] = root.querySelectorAll('button')965+ button.click()966+ await Promise.resolve()967+ expect(root.innerHTML).toBe(968+ '<form><div><label>Name</label><input></div><div><label>Email</label><input></div><button>serialize</button><span>{"name":"John","email":"john@example.com"}</span></form>'969 )954- }955- const app = <Form />956- render(app, root)957- expect(root.innerHTML).toBe(958- '<form><div><label>Name</label><input></div><div><label>Email</label><input></div><button>serialize</button><span>{}</span></form>'959- )960- const [nameInput, emailInput] = root.querySelectorAll('input')961- nameInput.value = 'John'962- emailInput.value = 'john@example.com'963- const [button] = root.querySelectorAll('button')964- button.click()965- await Promise.resolve()966- expect(root.innerHTML).toBe(967- '<form><div><label>Name</label><input></div><div><label>Email</label><input></div><button>serialize</button><span>{"name":"John","email":"john@example.com"}</span></form>'968- )970+ })971+972+ it('update current', async () => {973+ const App = () => {974+ const [, setState] = useState(0)975+ const ref = useRef<boolean>(false)976+ return (977+ <>978+ <button979+ onClick={() => {980+ setState((c) => c + 1)981+ ref.current = true982+ }}983+ >984+ update985+ </button>986+ <span>{String(ref.current)}</span>987+ </>988+ )989+ }990+ const app = <App />991+ render(app, root)992+ expect(root.innerHTML).toBe('<button>update</button><span>false</span>')993+ root.querySelector('button')?.click()994+ await Promise.resolve()995+ expect(root.innerHTML).toBe('<button>update</button><span>true</span>')996+ })997 })998 999 describe('useEffect', () => {1000 it('simple', async () => {466 unmodified linesmodified:src/jsx/hooks/index.ts+11 added-1 removed
7 unmodified lines8 export const STASH_EFFECT = 19 const STASH_CALLBACK = 210 const STASH_USE = 311 const STASH_MEMO = 412+const STASH_REF = 513 14 export type EffectData = [15 readonly unknown[] | undefined, // deps16 (() => void | (() => void)) | undefined, // layout effect260 unmodified lines277 }278 279 export type RefObject<T> = { current: T | null }280 export const useRef = <T>(initialValue: T | null): RefObject<T> => {281+ const buildData = buildDataStack.at(-1) as [unknown, NodeObject]282+ if (!buildData) {280- return { current: initialValue }283+ return { current: initialValue }284+ }285+ const [, node] = buildData286+287+ const refArray = (node[DOM_STASH][1][STASH_REF] ||= [])288+ const hookIndex = node[DOM_STASH][0]++289+290+ return (refArray[hookIndex] ||= { current: initialValue })291 }292 293 export const use = <T>(promise: Promise<T>): T => {294 const cachedRes = resolvedPromiseValueMap.get(promise) as [T] | [undefined, unknown] | undefined60 unmodified linesmodified:src/jsx/jsx-runtime.ts+2 added-1 removed
1 unmodified line2 export { jsxDEV as jsxs } from './jsx-dev-runtime'3 4 import { raw, html } from '../helper/html'5 export { html as jsxTemplate }6-export const jsxAttr = (name: string, value: string) => raw(name + '="' + html`${value}` + '"')6+export const jsxAttr = (name: string, value: string | Promise<string>) =>7+ typeof value === 'string' ? raw(name + '="' + html`${value}` + '"') : html`${name}="${value}"`8 export const jsxEscape = (value: string) => valuemodified:src/utils/stream.ts+8 added-1 removed
10 unmodified lines11 this.encoder = new TextEncoder()12 13 const reader = _readable.getReader()14 15+ // in case the user disconnects, let the reader know to cancel16+ // this in-turn results in responseReadable being closed17+ // and writeSSE method no longer blocks indefinitely18+ this.abortSubscribers.push(async () => {19+ await reader.cancel()20+ })21+22 this.responseReadable = new ReadableStream({23 async pull(controller) {24 const { done, value } = await reader.read()25 done ? controller.close() : controller.enqueue(value)38 unmodified lines64 await body.pipeTo(this.writable, { preventClose: true })65 this.writer = this.writable.getWriter()66 }67 61- async onAbort(listener: () => void | Promise<void>) {68+ onAbort(listener: () => void | Promise<void>) {69 this.abortSubscribers.push(listener)70 }71 }modified:src/types.test.ts+19 added
679 unmodified lines680 }681 }682 type verify = Expect<Equal<Expected, Actual>>683 })684+685+ test('MergeSchemaPath - Path and SubPath have regexp path params', () => {686+ type Actual = MergeSchemaPath<ToSchema<'get', '/c/:d{.+}', {}, {}>, '/a/:b{.+}'>687+ type Expected = {688+ '/a/:b{.+}/c/:d{.+}': {689+ $get: {690+ input: {691+ param: {692+ d: string693+ } & {694+ b: string695+ }696+ }697+ output: {}698+ }699+ }700+ }701+ type verify = Expect<Equal<Expected, Actual>>702+ })703 })704 705 describe('Different types using json()', () => {706 describe('no path pattern', () => {748 unmodified linesmodified:src/types.ts+21 added-5 removed
20 unmodified lines21 22 export type Next = () => Promise<void>23 24 export type Input = {25- in?: Partial<ValidationTargets>26- out?: Partial<{ [K in keyof ValidationTargets]: unknown }>25+ in?: {}26+ out?: {}27 }28 29 export type BlankSchema = {}30 export type BlankInput = {}1583 unmodified lines1614 ? {1615 input: Input extends { param: infer _ }1616 ? ExtractParams<SubPath> extends never1617 ? Input1618- : FlattenIfIntersect<Input & { param: ExtractParams<SubPath> }>1618+ : FlattenIfIntersect<1619+ Input & {1620+ param: {1621+ // Maps extracted keys, stripping braces, to a string-typed record.1622+ [K in keyof ExtractParams<SubPath> as K extends `${infer Prefix}{${infer _}}`1623+ ? Prefix1624+ : K]: string1625+ }1626+ }1627+ >1628 : RemoveBlankRecord<ExtractParams<SubPath>> extends never1629 ? Input1621- : Input & { param: ExtractParams<SubPath> }1630+ : Input & {1631+ // Maps extracted keys, stripping braces, to a string-typed record.1632+ param: {1633+ [K in keyof ExtractParams<SubPath> as K extends `${infer Prefix}{${infer _}}`1634+ ? Prefix1635+ : K]: string1636+ }1637+ }1638 output: Output1639 }1640 : never1641 }28 unmodified lines1670 ////////////////////////////////////////1671 1672 export type TypedResponse<T = unknown> = {1673 data: T1658- format: 'json' // Currently, support only `json` with `c.jsonT()`1674+ format: 'json' // Currently, support only `json` with `c.json()`1675 }1676 1677 type ExtractResponseData<T> = T extends Promise<infer T2>1678 ? T2 extends TypedResponse<infer U>93 unmodified linesmodified:bun.lockbbinary
A binary file, modified.
modified:package.json+2 added-1 removed
1 {2 "name": "hono",3- "version": "4.0.6",3+ "version": "4.0.9",4 "description": "Ultrafast web framework for the Edges",5 "main": "dist/cjs/index.js",6 "type": "module",7 "module": "dist/index.js",519 unmodified lines527 "crypto-js": "^4.1.1",528 "denoify": "^1.6.6",529 "esbuild": "^0.15.12",530 "eslint": "^8.55.0",531+ "glob": "7.2.3",532 "jsdom": "^22.1.0",533 "msw": "1.3.2",534 "np": "7.7.0",535 "prettier": "^2.6.2",14 unmodified linesmodified:yarn.lock+1 added-1 removed
2959 unmodified lines2960 version "0.0.2"2961 resolved "https://registry.npmjs.org/gitignore-parser/-/gitignore-parser-0.0.2.tgz"2962 integrity sha512-X6mpqUv59uWLGD4n3hZ8Cu8KbF2PMWPSFYmxZjdkpm3yOU7hSUYnzTkZI1mcWqchphvqyuz3/BhgBR4E/JtkCg==2963 2964-glob@^7.1.3, glob@^7.1.4, glob@^7.1.6:2964+glob@7.2.3, glob@^7.1.3, glob@^7.1.4, glob@^7.1.6:2965 version "7.2.3"2966 resolved "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz"2967 integrity sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==2968 dependencies:3530 unmodified lines