feat(adapters): add @hono/bun as a workspace package (#5447)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* feat(adapters): add @hono/bun as a workspace package * use bun test * add ci-adapters * fix(adapter/bun): put `@deprecated` on each export * fix(adapters/bun): point `createBunWebSocket` deprecation at `@hono/bun` * feat(build): print release notes draft from release:adapter * docs: add maintainer notes for adapters * chore(adapters/bun): set initial version to 1.0.0 * ci: apply automated fixes * format ---------
authored by Yusuke Wada · committed by GitHub · parent d7fb697 · Browse files · 27 files·+886 added−12 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Diff stats
27 files+886 added−12 removed
- tests:+270 added−0 removed
- other:+616 added−12 removed
Provenance
- Commit
fc2343d- Tree
444d1e3- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
d7fb697
27 files changed+886 added−12 removed
added:.github/workflows/ci-adapters.yml+48 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748name: ci-adapterson: push: branches: [main, next] paths: - 'adapters/**' - 'src/**' - 'package.json' - 'pnpm-lock.yaml' - 'pnpm-workspace.yaml' - '.github/workflows/ci-adapters.yml' pull_request: branches: ['*'] paths: - 'adapters/**' - 'src/**' - 'package.json' - 'pnpm-lock.yaml' - 'pnpm-workspace.yaml' - '.github/workflows/ci-adapters.yml'
permissions: contents: read
jobs: adapters: name: 'Adapters' runs-on: ubuntu-latest steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 - uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6 with: node-version-file: '.tool-versions' - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 with: bun-version-file: '.tool-versions' - uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0 with: cache: true run_install: true - uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6 with: node-version-file: '.tool-versions' - run: pnpm run format - run: pnpm run lint - run: pnpm run build - run: pnpm run build:adapters - run: pnpm run test:adaptersmodified:.github/workflows/ci.yml+3 added
1 name: ci2 on:3 push:4 branches: [main, next]5+ paths-ignore:6+ - 'adapters/**'7 pull_request:8 branches: ['*']9 paths-ignore:10+ - 'adapters/**'11 - 'docs/**'12 - '.vscode/**'13 - 'README.md'14 - '.gitignore'320 unmodified linesmodified:.github/workflows/release.yml+43 added-1 removed
12345667891011121314151617181921 unmodified lines4142434445464748497 unmodified lines57585960616263646566676869707172737475767778798081828384858687888990919293949596979899name: release
on: push: tags: - '*' - 'v*' - '@hono/*'
permissions: contents: read
jobs: npm: name: publish-to-npm if: startsWith(github.ref_name, 'v') runs-on: ubuntu-latest
permissions: contents: read21 unmodified lines run: npm stage publish --provenance --access public
jsr: name: publish-to-jsr if: startsWith(github.ref_name, 'v') runs-on: ubuntu-latest
permissions: contents: read7 unmodified lines deno-version-file: '.tool-versions' - run: deno install --no-lock --allow-scripts - name: Publish to JSR run: deno run -A jsr:@david/publish-on-tag@0.1.4
adapter: name: publish-adapter-to-npm if: startsWith(github.ref_name, '@hono/') runs-on: ubuntu-latest
permissions: contents: read id-token: write
steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 - uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6 with: node-version-file: '.tool-versions' registry-url: 'https://registry.npmjs.org' - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 with: bun-version-file: '.tool-versions' - uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0 with: cache: true run_install: true - uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6 with: node-version-file: '.tool-versions' - run: npm install -g npm@11.17.0 - name: Resolve package from tag id: pkg run: | # tag: @hono/<name>@<version> pkg="${GITHUB_REF_NAME%@*}" echo "name=$pkg" >> "$GITHUB_OUTPUT" echo "dir=adapters/${pkg#@hono/}" >> "$GITHUB_OUTPUT" - run: pnpm --filter "${{ steps.pkg.outputs.name }}" run build - name: Pack run: pnpm --filter "${{ steps.pkg.outputs.name }}" pack --pack-destination "$RUNNER_TEMP" - name: Publish to npm run: npm stage publish "$RUNNER_TEMP"/*.tgz --provenance --access publicadded:adapters/bun/src/conninfo.test.ts+85 added
1+import { describe, expect, it } from 'bun:test'2+import { Context } from 'hono'3+import type { AddressType } from 'hono/conninfo'4+import { getConnInfo } from './conninfo'5+6+const createRandomBunServer = ({7+ address = Math.random().toString(),8+ port = Math.floor(Math.random() * (65535 + 1)),9+ family = 'IPv6',10+}: {11+ address?: string12+ port?: number13+ family?: AddressType | string14+} = {}) => {15+ return {16+ address,17+ port,18+ server: {19+ requestIP() {20+ return {21+ address,22+ family,23+ port,24+ }25+ },26+ },27+ }28+}29+describe('getConnInfo', () => {30+ it('Should info is valid', () => {31+ const { port, server, address } = createRandomBunServer()32+ const c = new Context(new Request('http://localhost/'), { env: server })33+ const info = getConnInfo(c)34+35+ expect(info.remote.port).toBe(port)36+ expect(info.remote.address).toBe(address)37+ expect(info.remote.addressType).toBe('IPv6')38+ expect(info.remote.transport).toBeUndefined()39+ })40+ it('Should getConnInfo works when env is { server: server }', () => {41+ const { port, server, address } = createRandomBunServer()42+ const c = new Context(new Request('http://localhost/'), { env: { server } })43+44+ const info = getConnInfo(c)45+46+ expect(info.remote.port).toBe(port)47+ expect(info.remote.address).toBe(address)48+ expect(info.remote.addressType).toBe('IPv6')49+ expect(info.remote.transport).toBeUndefined()50+ })51+ it('should return undefined when addressType is invalid string', () => {52+ const { server } = createRandomBunServer({ family: 'invalid' })53+ const c = new Context(new Request('http://localhost/'), { env: { server } })54+55+ const info = getConnInfo(c)56+57+ expect(info.remote.addressType).toBeUndefined()58+ })59+ it('Should throw error when user did not give server', () => {60+ const c = new Context(new Request('http://localhost/'), { env: {} })61+62+ expect(() => getConnInfo(c)).toThrowError(TypeError)63+ })64+ it('Should throw error when requestIP is not function', () => {65+ const c = new Context(new Request('http://localhost/'), {66+ env: {67+ requestIP: 0,68+ },69+ })70+ expect(() => getConnInfo(c)).toThrowError(TypeError)71+ })72+ it('Should return empty remote when requestIP returns null', () => {73+ const c = new Context(new Request('http://localhost/'), {74+ env: {75+ requestIP() {76+ return null77+ },78+ },79+ })80+81+ const info = getConnInfo(c)82+83+ expect(info.remote).toEqual({})84+ })85+})added:adapters/bun/src/conninfo.ts+43 added
12345678910111213141516171819202122232425262728293031323334353637383940414243import type { Context } from 'hono'import type { GetConnInfo } from 'hono/conninfo'import { getBunServer } from './server'
/** * Get ConnInfo with Bun * @param c Context * @returns ConnInfo */export const getConnInfo: GetConnInfo = (c: Context) => { const server = getBunServer<{ requestIP?: (req: Request) => { address: string family: string port: number } | null }>(c)
if (!server) { throw new TypeError('env has to include the 2nd argument of fetch.') } if (typeof server.requestIP !== 'function') { throw new TypeError('server.requestIP is not a function.') }
// https://bun.sh/docs/runtime/http/server#server-requestip-request // Returns null for closed requests or Unix domain sockets. const info = server.requestIP(c.req.raw)
if (!info) { return { remote: {}, } }
return { remote: { address: info.address, addressType: info.family === 'IPv6' || info.family === 'IPv4' ? info.family : undefined, port: info.port, }, }}added:adapters/bun/src/index.ts+11 added
1234567891011/** * @module * Bun Adapter for Hono. */
export { serveStatic } from './serve-static'export { bunFileSystemModule, toSSG } from './ssg'export { createBunWebSocket, upgradeWebSocket, websocket } from './websocket'export type { BunWebSocketData, BunWebSocketHandler } from './websocket'export { getConnInfo } from './conninfo'export { getBunServer } from './server'added:adapters/bun/src/serve-static.ts+32 added
1234567891011121314151617181920212223242526272829303132/* eslint-disable @typescript-eslint/ban-ts-comment */import { stat } from 'node:fs/promises'import { join } from 'node:path'import { serveStatic as baseServeStatic } from 'hono/serve-static'import type { ServeStaticOptions } from 'hono/serve-static'import type { Env, MiddlewareHandler } from 'hono/types'
export const serveStatic = <E extends Env = Env>( options: ServeStaticOptions<E> = {}): MiddlewareHandler => { return async function serveStatic(c, next) { const getContent = async (path: string) => { // @ts-ignore const file = Bun.file(path) return (await file.exists()) ? file : null } const isDir = async (path: string) => { let isDir try { const stats = await stat(path) isDir = stats.isDirectory() } catch {} return isDir } return baseServeStatic({ ...options, getContent, join, isDir, })(c, next) }}added:adapters/bun/src/server.test.ts+18 added
123456789101112131415161718import { describe, expect, it } from 'bun:test'import { Context } from 'hono'import { getBunServer } from './server'
describe('getBunServer', () => { it('Should success to pick Server', () => { const server = {}
expect( getBunServer<typeof server>(new Context(new Request('http://localhost/'), { env: server })) ).toBe(server) expect( getBunServer<typeof server>( new Context(new Request('http://localhost/'), { env: { server } }) ) ).toBe(server) })})added:adapters/bun/src/server.ts+14 added
1234567891011121314/** * Getting Bun Server Object for Bun adapters * @module */import type { Context } from 'hono'
/** * Get Bun Server Object from Context * @template T - The type of Bun Server * @param c Context * @returns Bun Server */export const getBunServer = <T>(c: Context): T | undefined => ('server' in c.env ? c.env.server : c.env) as T | undefinedadded:adapters/bun/src/ssg.ts+27 added
1+/* eslint-disable @typescript-eslint/ban-ts-comment */2+import { toSSG as baseToSSG } from 'hono/ssg'3+import type { FileSystemModule, ToSSGAdaptorInterface } from 'hono/ssg'4+5+// @ts-ignore6+const { write } = Bun7+8+/**9+ * @experimental10+ * `bunFileSystemModule` is an experimental feature.11+ * The API might be changed.12+ */13+export const bunFileSystemModule: FileSystemModule = {14+ writeFile: async (path, data) => {15+ await write(path, data)16+ },17+ mkdir: async () => {},18+}19+20+/**21+ * @experimental22+ * `toSSG` is an experimental feature.23+ * The API might be changed.24+ */25+export const toSSG: ToSSGAdaptorInterface = async (app, options) => {26+ return baseToSSG(app, bunFileSystemModule, options)27+}added:adapters/bun/src/websocket.test.ts+167 added
1+import { afterAll, beforeAll, describe, expect, it, mock } from 'bun:test'2+import { Context } from 'hono'3+import type { BunWebSocketData, BunServerWebSocket } from './websocket'4+import { createWSContext, websocket, upgradeWebSocket, createBunWebSocket } from './websocket'5+6+describe('createWSContext()', () => {7+ it('Should send() and close() works', () => {8+ const send = mock()9+ const close = mock()10+ const ws = createWSContext({11+ send(data) {12+ send(data)13+ },14+ close(code, reason) {15+ close(code, reason)16+ },17+ data: {},18+ } as BunServerWebSocket<BunWebSocketData>)19+ ws.send('message')20+ expect(send).toBeCalled()21+ ws.close()22+ expect(close).toBeCalled()23+ })24+})25+describe('upgradeWebSocket()', () => {26+ beforeAll(() => {27+ // @ts-expect-error patch global28+ globalThis.CloseEvent = Event29+ })30+ afterAll(() => {31+ // @ts-expect-error patch global32+ delete globalThis.CloseEvent33+ })34+ it('Should throw error when server is null', async () => {35+ const run = async () =>36+ await upgradeWebSocket(() => ({}))(37+ new Context(new Request('http://localhost'), {38+ env: {39+ server: null,40+ },41+ }),42+ () => Promise.resolve()43+ )44+45+ await expect(run()).rejects.toThrowError(/env has/)46+ })47+ it('Should response null when upgraded', async () => {48+ const upgraded = await upgradeWebSocket(() => ({}))(49+ new Context(new Request('http://localhost'), {50+ env: {51+ upgrade: () => true,52+ },53+ }),54+ () => Promise.resolve()55+ )56+ expect(upgraded).toBeTruthy()57+ })58+ it('Should response undefined when upgrade failed', async () => {59+ const upgraded = await upgradeWebSocket(() => ({}))(60+ new Context(new Request('http://localhost'), {61+ env: {62+ upgrade: () => undefined,63+ },64+ }),65+ () => Promise.resolve()66+ )67+ expect(upgraded).toBeFalsy()68+ })69+ it('Should expose the requested subprotocol on WSContext.protocol', async () => {70+ let data: BunWebSocketData | undefined71+ await upgradeWebSocket(() => ({}))(72+ new Context(73+ new Request('http://localhost/ws', {74+ headers: { 'sec-websocket-protocol': 'chat, superchat' },75+ }),76+ {77+ env: {78+ upgrade(_req: Request, options: { data: BunWebSocketData }) {79+ data = options.data80+ return true81+ },82+ },83+ }84+ ),85+ () => Promise.resolve()86+ )87+88+ const ws = createWSContext({ data, readyState: 1 } as BunServerWebSocket<BunWebSocketData>)89+ expect(ws.protocol).toBe('chat')90+ })91+ it('Should set protocol to an empty string when no subprotocol is requested', async () => {92+ let data: BunWebSocketData | undefined93+ await upgradeWebSocket(() => ({}))(94+ new Context(new Request('http://localhost/ws'), {95+ env: {96+ upgrade(_req: Request, options: { data: BunWebSocketData }) {97+ data = options.data98+ return true99+ },100+ },101+ }),102+ () => Promise.resolve()103+ )104+105+ const ws = createWSContext({ data, readyState: 1 } as BunServerWebSocket<BunWebSocketData>)106+ expect(ws.protocol).toBe('')107+ })108+ it('Should events are called', async () => {109+ const open = mock()110+ const message = mock()111+ const close = mock()112+113+ const ws = {114+ data: {115+ events: {116+ // eslint-disable-next-line @typescript-eslint/no-unused-vars117+ onOpen(evt, ws) {118+ open()119+ },120+ // eslint-disable-next-line @typescript-eslint/no-unused-vars121+ onMessage(evt, ws) {122+ message()123+ if (evt.data instanceof ArrayBuffer) {124+ receivedArrayBuffer = evt.data125+ }126+ },127+ // eslint-disable-next-line @typescript-eslint/no-unused-vars128+ onClose(evt, ws) {129+ close()130+ },131+ },132+ },133+ } as BunServerWebSocket<BunWebSocketData>134+135+ let receivedArrayBuffer: ArrayBuffer | undefined = undefined136+ await upgradeWebSocket(() => ({}))(137+ new Context(new Request('http://localhost'), {138+ env: {139+ upgrade() {140+ return true141+ },142+ },143+ }),144+ () => Promise.resolve()145+ )146+147+ websocket.open(ws)148+ expect(open).toBeCalled()149+150+ websocket.message(ws, 'message')151+ expect(message).toBeCalled()152+153+ websocket.message(ws, new Uint8Array(16))154+ expect(receivedArrayBuffer).toBeInstanceOf(ArrayBuffer)155+ expect(receivedArrayBuffer!.byteLength).toBe(16)156+ websocket.close(ws)157+ expect(close).toBeCalled()158+ })159+})160+161+describe('createBunWebSocket()', () => {162+ it('Should return upgradeWebSocket and websocket', () => {163+ const result = createBunWebSocket()164+ expect(result.upgradeWebSocket).toBe(upgradeWebSocket)165+ expect(result.websocket).toBe(websocket)166+ })167+})added:adapters/bun/src/websocket.ts+113 added
1+import type { UpgradeWebSocket, WSEvents, WSMessageReceive } from 'hono/ws'2+import { createWSMessageEvent, defineWebSocketHelper, WSContext } from 'hono/ws'3+import { getBunServer } from './server'4+5+/**6+ * @internal7+ */8+export interface BunServerWebSocket<T> {9+ send(data: string | ArrayBuffer | Uint8Array, compress?: boolean): void10+ close(code?: number, reason?: string): void11+ data: T12+ readyState: 0 | 1 | 2 | 313+}14+15+export interface BunWebSocketHandler<T> {16+ open(ws: BunServerWebSocket<T>): void17+ close(ws: BunServerWebSocket<T>, code?: number, reason?: string): void18+ message(ws: BunServerWebSocket<T>, message: string | { buffer: ArrayBufferLike }): void19+}20+interface CreateWebSocket<T> {21+ upgradeWebSocket: UpgradeWebSocket<T>22+ websocket: BunWebSocketHandler<BunWebSocketData>23+}24+export interface BunWebSocketData {25+ events: WSEvents26+ url: URL27+ protocol: string28+}29+30+/**31+ * @internal32+ */33+export const createWSContext = (ws: BunServerWebSocket<BunWebSocketData>): WSContext => {34+ return new WSContext({35+ send: (source, options) => {36+ ws.send(source, options?.compress)37+ },38+ raw: ws,39+ readyState: ws.readyState,40+ url: ws.data.url,41+ protocol: ws.data.protocol,42+ close(code, reason) {43+ ws.close(code, reason)44+ },45+ })46+}47+48+export const upgradeWebSocket: UpgradeWebSocket<any> = defineWebSocketHelper((c, events) => {49+ const server = getBunServer<{50+ upgrade<T>(51+ req: Request,52+ options?: {53+ data: T54+ }55+ ): boolean56+ }>(c)57+58+ if (!server) {59+ throw new TypeError('env has to include the 2nd argument of fetch.')60+ }61+ const upgradeResult = server.upgrade<BunWebSocketData>(c.req.raw, {62+ data: {63+ events,64+ url: new URL(c.req.url),65+ // The first requested subprotocol, exposed via WSContext.protocol to66+ // match the deno and cloudflare adapters.67+ protocol: c.req.header('sec-websocket-protocol')?.split(',')[0]?.trim() ?? '',68+ },69+ })70+ if (upgradeResult) {71+ return new Response(null)72+ }73+ return // failed74+})75+76+export const websocket: BunWebSocketHandler<BunWebSocketData> = {77+ open(ws) {78+ const websocketListeners = ws.data.events79+ if (websocketListeners.onOpen) {80+ websocketListeners.onOpen(new Event('open'), createWSContext(ws))81+ }82+ },83+ close(ws, code, reason) {84+ const websocketListeners = ws.data.events85+ if (websocketListeners.onClose) {86+ websocketListeners.onClose(87+ new CloseEvent('close', {88+ code,89+ reason,90+ }),91+ createWSContext(ws)92+ )93+ }94+ },95+ message(ws, message) {96+ const websocketListeners = ws.data.events97+ if (websocketListeners.onMessage) {98+ const normalizedReceiveData: WSMessageReceive =99+ typeof message === 'string' ? message : message.buffer100+101+ websocketListeners.onMessage(createWSMessageEvent(normalizedReceiveData), createWSContext(ws))102+ }103+ },104+}105+106+/**107+ * @deprecated Import `upgradeWebSocket` and `websocket` directly from `@hono/bun` instead.108+ * @returns A function to create a Bun WebSocket handler.109+ */110+export const createBunWebSocket = <T>(): CreateWebSocket<T> => ({111+ upgradeWebSocket,112+ websocket,113+})added:adapters/bun/package.json+39 added
1+{2+ "name": "@hono/bun",3+ "version": "1.0.0",4+ "description": "Bun adapter for Hono",5+ "type": "module",6+ "main": "dist/index.js",7+ "types": "dist/types/index.d.ts",8+ "files": [9+ "dist"10+ ],11+ "exports": {12+ ".": {13+ "types": "./dist/types/index.d.ts",14+ "import": "./dist/index.js",15+ "require": "./dist/cjs/index.js"16+ }17+ },18+ "scripts": {19+ "build": "rm -rf dist && vp pack && cp ../../package.cjs.json dist/cjs/package.json && cp ../../package.cjs.json dist/types/package.json && publint",20+ "test": "tsc -p tsconfig.json && bun test"21+ },22+ "license": "MIT",23+ "repository": {24+ "type": "git",25+ "url": "git+https://github.com/honojs/hono.git",26+ "directory": "adapters/bun"27+ },28+ "homepage": "https://hono.dev",29+ "author": "Yusuke Wada <yusuke@kamawada.com> (https://github.com/yusukebe)",30+ "peerDependencies": {31+ "hono": ">=4.13.9"32+ },33+ "engines": {34+ "node": ">=16.9.0"35+ },36+ "devDependencies": {37+ "hono": "workspace:*"38+ }39+}added:adapters/bun/README.md+22 added
1+# @hono/bun2+3+Bun adapter for [Hono](https://hono.dev).4+5+```sh6+bun add @hono/bun7+```8+9+## Migrating from `hono/bun`10+11+The exports are the same. Change the import path:12+13+```diff14+- import { serveStatic } from 'hono/bun'15++ import { serveStatic } from '@hono/bun'16+```17+18+`hono/bun` is deprecated and will be removed in Hono v5.19+20+## License21+22+MITadded:adapters/bun/tsconfig.json+11 added
1+{2+ "extends": "../../tsconfig.base.json",3+ "compilerOptions": {4+ "module": "ES2020",5+ "rootDir": "./src/",6+ "outDir": "./dist/",7+ "types": ["bun-types"],8+ "noEmit": true9+ },10+ "include": ["src/**/*.ts"]11+}added:adapters/bun/vite.config.ts+34 added
1+import { defineConfig } from 'vite-plus'2+3+const common = {4+ entry: ['src/**/*.ts', '!src/**/*.test.ts'],5+ tsconfig: 'tsconfig.json',6+ unbundle: true,7+ clean: false,8+}9+10+export default defineConfig({11+ pack: [12+ {13+ ...common,14+ format: ['esm'],15+ outDir: 'dist',16+ dts: false,17+ outExtensions: () => ({ js: '.js' }),18+ },19+ {20+ ...common,21+ format: ['cjs'],22+ outDir: 'dist/cjs',23+ dts: false,24+ outExtensions: () => ({ js: '.js' }),25+ },26+ {27+ ...common,28+ format: ['esm'],29+ outDir: 'dist/types',30+ dts: { emitDtsOnly: true },31+ outExtensions: () => ({ dts: '.d.ts' }),32+ },33+ ],34+})added:build/release-adapter.ts+68 added
1+/**2+ * Release an adapter package in `adapters/*`.3+ *4+ * Usage: pnpm run release:adapter <name> <patch|minor|major|x.y.z>5+ *6+ * Bumps the version, commits, tags `@hono/<name>@<version>` and pushes.7+ * The `release` workflow then runs `npm stage publish` for that tag.8+ * Finally prints a release-note draft built from the commits that touched9+ * the adapter since its previous tag, with a link to create a GitHub Release.10+ */11+import { execSync } from 'node:child_process'12+import { readFileSync } from 'node:fs'13+import { join } from 'node:path'14+15+const [name, bump] = process.argv.slice(2)16+if (!name || !bump) {17+ console.error('Usage: pnpm run release:adapter <name> <patch|minor|major|x.y.z>')18+ process.exit(1)19+}20+21+const dir = join('adapters', name)22+const run = (cmd: string, cwd = '.') => execSync(cmd, { cwd, stdio: 'inherit' })23+const capture = (cmd: string) =>24+ execSync(cmd, { stdio: ['ignore', 'pipe', 'ignore'] })25+ .toString()26+ .trim()27+28+if (capture('git status --porcelain')) {29+ console.error('Working tree is not clean. Commit or stash your changes first.')30+ process.exit(1)31+}32+33+const pkgPath = join(dir, 'package.json')34+const pkgName: string = JSON.parse(readFileSync(pkgPath, 'utf8')).name35+36+// Collect commits that touched the adapter since its previous tag, before creating the new one.37+let previousTag = ''38+try {39+ previousTag = capture(`git describe --tags --abbrev=0 --match "${pkgName}@*"`)40+} catch {41+ // first release: no previous tag42+}43+const range = previousTag ? `${previousTag}..HEAD` : 'HEAD'44+const changes = capture(`git log ${range} --pretty=format:"- %s" -- ${dir}`)45+ .split('\n')46+ .filter((line) => line && !line.startsWith('- chore(adapters): release '))47+48+run(`npm version ${bump} --no-git-tag-version`, dir)49+50+const version: string = JSON.parse(readFileSync(pkgPath, 'utf8')).version51+const tag = `${pkgName}@${version}`52+53+run(`git add ${pkgPath}`)54+run(`git commit -m "chore(adapters): release ${tag}"`)55+run(`git tag -a ${tag} -m ${tag}`)56+run(`git push origin HEAD ${tag}`)57+58+const notes = ["## What's Changed", '', ...changes].join('\n')59+const releaseUrl = new URL('https://github.com/honojs/hono/releases/new')60+releaseUrl.searchParams.set('tag', tag)61+releaseUrl.searchParams.set('title', tag)62+releaseUrl.searchParams.set('body', notes)63+64+console.log(65+ `\nTagged ${tag}. Approve the staged version on npm once the release workflow finishes.\n`66+)67+console.log(notes)68+console.log(`\nCreate a GitHub Release (optional):\n${releaseUrl}`)added:docs/MAINTAINING.md+62 added
1+# Maintaining2+3+Notes for maintainers of this repository.4+5+## Adapters6+7+Runtime adapters live in `adapters/*` and are published as separate packages (`@hono/bun`, ...). Each directory is a pnpm workspace package. The root package is `hono` itself.8+9+### Layout10+11+```12+adapters/bun/13+ src/ # imports hono via `hono`, `hono/ws`, ... (workspace link)14+ src/*.test.ts # runs with `bun test`15+ package.json # peerDependencies: hono >=x.y.z16+ vite.config.ts # `vp pack` config, same three-pass layout as hono17+```18+19+### Commands20+21+From the repository root:22+23+```sh24+pnpm run build:adapters # build every adapter25+pnpm run test:adapters # tsc + bun test for every adapter26+pnpm --filter @hono/bun run test27+```28+29+CI runs `ci-adapters.yml` for changes under `adapters/**` (and `src/**`, since adapters depend on `hono`). The main `ci.yml` skips changes that only touch `adapters/**`.30+31+### Versioning32+33+- Adapter versions are independent from `hono`. Do not bump them when `hono` is released.34+- Compatibility is expressed by `peerDependencies.hono` in each adapter. Raise the lower bound when an adapter starts using something newer.35+- Git tags are `@hono/<name>@<version>`. Only `hono` uses `v<version>`.36+37+### Releasing38+39+```sh40+pnpm run release:adapter bun patch # or minor, major, or an exact x.y.z41+```42+43+This bumps `adapters/bun/package.json`, commits, creates an annotated tag `@hono/bun@<version>` and pushes. The `release.yml` workflow then packs the adapter and runs `npm stage publish`. Approve the staged version on npm (2FA) to make it public.44+45+At the end the script prints a release-note draft built from the commits that touched `adapters/bun` since the previous adapter tag, plus a prefilled GitHub "new release" link. Creating a GitHub Release is optional.46+47+### Adding a new adapter48+49+1. Copy `adapters/bun` as `adapters/<name>` and adjust `package.json` (`name`, `description`) and the sources.50+2. The workspace picks it up automatically (`pnpm-workspace.yaml` has `adapters/*`).51+3. Add it to the corresponding `src/adapter/<name>` with `@deprecated` on each export, pointing to the new package.52+4. **First publish is manual.** See below.53+5. From the second release on, use `pnpm run release:adapter <name> <bump>`.54+55+#### First publish of a new adapter56+57+npm only allows a Trusted Publisher on a package that already exists, so the first version is published from a maintainer's machine:58+59+1. Set the version in `adapters/<name>/package.json` and merge it.60+2. Build it: `pnpm --filter @hono/<name> run build` (`pnpm publish` does not build).61+3. In `adapters/<name>`, run `pnpm publish --access public` with your npm 2FA.62+4. On npmjs.com, open the package settings and add a Trusted Publisher: repository `honojs/hono`, workflow `release.yml`.modified:src/adapter/bun/conninfo.ts+1 added
4 unmodified lines5 /**6 * Get ConnInfo with Bun7 * @param c Context8 * @returns ConnInfo9+ * @deprecated `hono/bun` will be removed in v5. Install `@hono/bun` and import from there instead.10 */11 export const getConnInfo: GetConnInfo = (c: Context) => {12 const server = getBunServer<{13 requestIP?: (req: Request) => {31 unmodified linesmodified:src/adapter/bun/index.ts+4 added
1 /**2 * @module3 * Bun Adapter for Hono.4+ *5+ * @deprecated6+ * This adapter will be removed from the `hono` package in v5.7+ * Install `@hono/bun` and import from there instead.8 */9 10 export { serveStatic } from './serve-static'11 export { bunFileSystemModule, toSSG } from './ssg'4 unmodified linesmodified:src/adapter/bun/serve-static.ts+3 added
3 unmodified lines4 import { serveStatic as baseServeStatic } from '../../middleware/serve-static'5 import type { ServeStaticOptions } from '../../middleware/serve-static'6 import type { Env, MiddlewareHandler } from '../../types'7 8+/**9+ * @deprecated `hono/bun` will be removed in v5. Install `@hono/bun` and import from there instead.10+ */11 export const serveStatic = <E extends Env = Env>(12 options: ServeStaticOptions<E> = {}13 ): MiddlewareHandler => {14 return async function serveStatic(c, next) {21 unmodified linesmodified:src/adapter/bun/server.ts+1 added
7 unmodified lines8 * Get Bun Server Object from Context9 * @template T - The type of Bun Server10 * @param c Context11 * @returns Bun Server12+ * @deprecated `hono/bun` will be removed in v5. Install `@hono/bun` and import from there instead.13 */14 export const getBunServer = <T>(c: Context): T | undefined =>15 ('server' in c.env ? c.env.server : c.env) as T | undefinedmodified:src/adapter/bun/ssg.ts+2 added
7 unmodified lines8 /**9 * @experimental10 * `bunFileSystemModule` is an experimental feature.11 * The API might be changed.12+ * @deprecated `hono/bun` will be removed in v5. Install `@hono/bun` and import from there instead.13 */14 export const bunFileSystemModule: FileSystemModule = {15 writeFile: async (path, data) => {16 await write(path, data)4 unmodified lines21 /**22 * @experimental23 * `toSSG` is an experimental feature.24 * The API might be changed.25+ * @deprecated `hono/bun` will be removed in v5. Install `@hono/bun` and import from there instead.26 */27 export const toSSG: ToSSGAdaptorInterface = async (app, options) => {28 return baseToSSG(app, bunFileSystemModule, options)29 }modified:src/adapter/bun/websocket.ts+14 added
2 unmodified lines3 import { getBunServer } from './server'4 5 /**6 * @internal7+ * @deprecated `hono/bun` will be removed in v5. Install `@hono/bun` and import from there instead.8 */9 export interface BunServerWebSocket<T> {10 send(data: string | ArrayBuffer | Uint8Array, compress?: boolean): void11 close(code?: number, reason?: string): void12 data: T13 readyState: 0 | 1 | 2 | 314 }15 16+/**17+ * @deprecated `hono/bun` will be removed in v5. Install `@hono/bun` and import from there instead.18+ */19 export interface BunWebSocketHandler<T> {20 open(ws: BunServerWebSocket<T>): void21 close(ws: BunServerWebSocket<T>, code?: number, reason?: string): void22 message(ws: BunServerWebSocket<T>, message: string | { buffer: ArrayBufferLike }): void1 unmodified line24 interface CreateWebSocket<T> {25 upgradeWebSocket: UpgradeWebSocket<T>26 websocket: BunWebSocketHandler<BunWebSocketData>27 }28+/**29+ * @deprecated `hono/bun` will be removed in v5. Install `@hono/bun` and import from there instead.30+ */31 export interface BunWebSocketData {32 events: WSEvents33 url: URL34 protocol: string35 }36 37 /**38 * @internal39+ * @deprecated `hono/bun` will be removed in v5. Install `@hono/bun` and import from there instead.40 */41 export const createWSContext = (ws: BunServerWebSocket<BunWebSocketData>): WSContext => {42 return new WSContext({43 send: (source, options) => {8 unmodified lines52 },53 })54 }55 56+/**57+ * @deprecated `hono/bun` will be removed in v5. Install `@hono/bun` and import from there instead.58+ */59 export const upgradeWebSocket: UpgradeWebSocket<any> = defineWebSocketHelper((c, events) => {60 const server = getBunServer<{61 upgrade<T>(62 req: Request,20 unmodified lines83 }84 return // failed85 })86 87+/**88+ * @deprecated `hono/bun` will be removed in v5. Install `@hono/bun` and import from there instead.89+ */90 export const websocket: BunWebSocketHandler<BunWebSocketData> = {91 open(ws) {92 const websocketListeners = ws.data.events93 if (websocketListeners.onOpen) {34 unmodified linesmodified:package.json+8 added-5 removed
21 unmodified lines22 "test:lambda-edge": "vp test --run --project lambda-edge",23 "test:all": "pnpm run test && pnpm run test:deno && pnpm run test:bun",24 "check": "vp check",25 "check:fix": "vp check --fix",26- "lint": "vp lint src runtime-tests build perf-measures benchmarks",27- "lint:fix": "vp lint --fix src runtime-tests build perf-measures benchmarks",28- "format": "vp fmt --check \"src/**/*.{js,ts,tsx}\" \"runtime-tests/**/*.{js,ts,tsx}\" \"build/**/*.{js,ts,tsx}\" \"perf-measures/**/*.{js,ts,tsx}\" \"benchmarks/**/*.{js,ts,tsx}\"",29- "format:fix": "vp fmt \"src/**/*.{js,ts,tsx}\" \"runtime-tests/**/*.{js,ts,tsx}\" \"build/**/*.{js,ts,tsx}\" \"perf-measures/**/*.{js,ts,tsx}\" \"benchmarks/**/*.{js,ts,tsx}\"",26+ "lint": "vp lint src runtime-tests build perf-measures benchmarks adapters",27+ "lint:fix": "vp lint --fix src runtime-tests build perf-measures benchmarks adapters",28+ "format": "vp fmt --check \"src/**/*.{js,ts,tsx}\" \"runtime-tests/**/*.{js,ts,tsx}\" \"build/**/*.{js,ts,tsx}\" \"perf-measures/**/*.{js,ts,tsx}\" \"benchmarks/**/*.{js,ts,tsx}\" \"adapters/**/*.{js,ts,tsx}\"",29+ "format:fix": "vp fmt \"src/**/*.{js,ts,tsx}\" \"runtime-tests/**/*.{js,ts,tsx}\" \"build/**/*.{js,ts,tsx}\" \"perf-measures/**/*.{js,ts,tsx}\" \"benchmarks/**/*.{js,ts,tsx}\" \"adapters/**/*.{js,ts,tsx}\"",30 "editorconfig-checker": "editorconfig-checker",31 "copy:package.cjs.json": "cp ./package.cjs.json ./dist/cjs/package.json && cp ./package.cjs.json ./dist/types/package.json",32 "build": "pnpm run remove-dist && vp pack && pnpm run copy:package.cjs.json && publint",33 "watch": "pnpm run remove-dist && vp pack --watch && pnpm run copy:package.cjs.json",34 "coverage": "vp test --run --coverage",35 "prerelease": "pnpm run test:deno && pnpm run build",36 "release": "np --no-publish",37- "remove-dist": "rm -rf dist"37+ "remove-dist": "rm -rf dist",38+ "build:adapters": "pnpm -r --filter \"./adapters/*\" run build",39+ "test:adapters": "pnpm -r --filter \"./adapters/*\" run test",40+ "release:adapter": "node ./build/release-adapter.ts"41 },42 "exports": {43 ".": {44 "types": "./dist/types/index.d.ts",664 unmodified linesmodified:pnpm-lock.yaml+12 added-6 removed
166 unmodified lines167 .:168 devDependencies:169 '@hono/node-server':170 specifier: ^2.0.12171- version: 2.1.1(hono@4.13.8)171+ version: 2.1.1(hono@4.13.9)172 '@types/jsdom':173 specifier: ^21.1.7174 version: 21.1.7175 '@types/node':56 unmodified lines232 zod:233 specifier: ^3.23.8234 version: 3.25.76235 236+ adapters/bun:237+ devDependencies:238+ hono:239+ specifier: workspace:*240+ version: link:../..241+242 packages:243 244 '@andreiltd/componentize-qjs-binding-darwin-arm64@0.4.5':245 resolution: {integrity: sha512-CW+ukVP778x2NAHAC1FvXb5KVSXmUlUQxhQTFtF0mAqqOVnYrQgy4DDNUa48EGthwtLdgLT1+eE71qmQiyMEqg==}3546 unmodified lines3792 3793 headers-polyfill@5.0.1:3794 resolution: {integrity: sha512-1TJ6Fih/b8h5TIcv+1+Hw0PDQWJTKDKzFZzcKOiW1wJza3XoAQlkCuXLbymPYB8+ZQyw8mHvdw560e8zVFIWyA==}3795 3790- hono@4.13.8:3791- resolution: {integrity: sha512-/Gng7NfoykZl2pjukW5Z6+8Yxm3BPRf86GTbQnt0SbySkvax4fyL4H3HhY1cCpBGmiW9XDRFzRV+CXK2W8QudQ==}3796+ hono@4.13.9:3797+ resolution: {integrity: sha512-7dMkQmZoC4E6F7AtaQSPhlWAdnBti+j7rreMZl8QB4jFiEhP9TWbGWUMi8WYzBCgmgulxuvLQupKqo+Co6Omyg==}3798 engines: {node: '>=16.9.0'}3799 3800 hosted-git-info@9.0.3:3801 resolution: {integrity: sha512-Hc+ghLoSt6QaYZUv0WBiIvmMDZuZZ7oaDvdH8MbfOO4lOsxdXLEvuC6ePoGs9H1X9oCLyq6+NVN0MKqD+ydxyg==}2275 unmodified lines6077 regexpu-core: 6.4.06078 optionalDependencies:6079 typescript: 6.0.36080 6075- '@hono/node-server@2.1.1(hono@4.13.8)':6081+ '@hono/node-server@2.1.1(hono@4.13.9)':6082 dependencies:6077- hono: 4.13.86083+ hono: 4.13.96084 6085 '@img/colour@1.1.0': {}6086 6087 '@img/sharp-darwin-arm64@0.34.5':2097 unmodified lines8185 dependencies:8186 '@types/set-cookie-parser': 2.4.108187 set-cookie-parser: 3.1.28188 8183- hono@4.13.8: {}8189+ hono@4.13.9: {}8190 8191 hosted-git-info@9.0.3:8192 dependencies:8193 lru-cache: 11.5.31816 unmodified linesmodified:pnpm-workspace.yaml+1 added
1 packages:2 - '.'3+ - 'adapters/*'4 5 allowBuilds:6 esbuild: false7 msw: false3 unmodified lines