◎ HubRadar
仓库蒸馏源码 · 结构 · 取舍离线阅读

honojs/hono @ 5ca49b07 · 3 分钟卡片

覆盖:full_scan(源码 232 文件)· 证据包约 23,075 tokens / 全量约 236,440 · 结论校验 32/32 通过

本质:Hono = Web 标准 Request/Response + 可替换的路由策略(默认 SmartRouter 组合 RegExpRouter/TrieRouter)+ 洋葱式中间件 compose;单处理器请求走绕过 compose 的快路径。 作者声明✓ README.md#L21 源码事实✓ hono.ts#L20 源码事实✓ hono-base.ts#L437 源码事实✓ hono-base.ts#L449 源码事实✓ hono-base.ts#L242

解决:在任意 JS 运行时(Workers/Deno/Bun/Node/Lambda)上用同一套代码写 HTTP API,并获得强类型的路由与 RPC 客户端。
不解决:不提供 Express 中间件兼容层,也不内置 OpenAPI 文档生成(均为高票未关闭需求)。 社区信号✓ #3293 社区信号✓ #2970

核心抽象

抽象 职责 证据
Hono / HonoBase(应用) 注册路由与中间件,持有 router,#dispatch 把 Request 变成 Response 源码事实✓ hono-base.ts#L144 源码事实✓ hono-base.ts#L175 源码事实✓ hono-base.ts#L405 源码事实✓ hono-base.ts#L437
Router(路由策略接口) add/match 两个方法;多实现可替换,默认 SmartRouter 组合两种实现 源码事实✓ router.ts#L29 源码事实✓ hono.ts#L20
Context(请求上下文) 惰性持有 req/res/变量 Map,提供 c.text/c.json 等响应构造,并维护 finalized 状态 源码事实✓ context.ts#L366 源码事实✓ context.ts#L414 源码事实✓ context.ts#L557
HonoRequest(请求包装) 按 matchResult 解析路径参数,缓存 body,供校验器写入已验证数据 源码事实✓ request.ts#L217 源码事实✓ request.ts#L103
compose(中间件内核) 把匹配到的处理器链组装成洋葱模型;单处理器时被绕过 源码事实✓ hono-base.ts#L242 源码事实✓ hono-base.ts#L449

主数据流与系统全景

DSH 盒模型 · 架构全景 (可点击代码锚点)
Hono 核心系统架构与全景分层 (5ca49b07) Web 标准接入 · SmartRouter 预编译路由决策 · 单处理器特化与洋葱中间件 Hono 核心系统架构与全景分层 (5ca49b07) Web 标准接入 · SmartRouter 预编译路由决策 · 单处理器特化与洋葱中间件 多平台运行时接入平面 (Presentation & Adapters) 原生 Web 标准边缘运行时 Workers / Deno / Bun 原生标准 Request Node.js / Lambda 适配层 非标准平台 Stream 与 Request 双向转换 RPC 强类型客户端与推导 hc 客户端与 AppType 强类型声明 核心应用底座与路由决策引擎 (Application Kernel & Router) 1 HonoBase #dispatch 调度 getPath 解析路径,构造 HonoRequest this.router.match(method, path) 2 SmartRouter 组合路由 RegExpRouter(预编译) + TrieRouter(回退) this.match = router.match.bind(router) 3 Context 惰性上下文容器 ??= 按需初始化 headers、变量 Map、body this.#req ??= new HonoRequest(...) 请求执行管道分化:单处理器快路径 VS 洋葱中间件 单处理器快路径特化 (Fast Path) 当 matchResult[0].length === 1 时完全绕过 compose res = matchResult[0][0][0][0](c, async () => {}) 零中间件级联调度开销 · 直接返回 Response 对象 洋葱式中间件级联调度 (compose) compose(matchResult[0]) 串联执行与错误捕获 res = await handler(context, () => dispatch(i + 1)) 严格维护 context.finalized 状态机 · 错误冒泡守卫 Web 接入层 (Presentation) 调度与路由 (Kernel & Router) 执行管道特化 (Execution) 点击直达 GitHub 源码提交行 统一输出 Web 标准 Response (HTTP 200/404/500) · 节点点击直达 GitHub 5ca49b07 提交行
查看 Mermaid 原始流程图
正在排版…
查看 Mermaid 源码
flowchart LR
  rt["运行时事件/Request"]
  ad["Adapter(平台→Web Request)"]
  dp["HonoBase #dispatch"]
  gp["getPath 解析路径"]
  rm["router.match"]
  cx["new Context"]
  fp["单处理器快路径"]
  cp["compose 洋葱链"]
  rs["Response"]
  rt -->|非 Web 标准平台| ad
  ad -->|Request| dp
  dp --> gp
  gp -->|method+path| rm
  rm -->|matchResult| cx
  cx -->|1 个处理器| fp
  cx -->|多个处理器| cp
  fp --> rs
  cp -->|c.res| rs

状态机

Router 生命周期(注册期 → 已构建) 源码事实✓ router.ts#L21

正在排版…
查看 Mermaid 源码
stateDiagram-v2
  s0 : 注册中
  s1 : matcher 已构建
  [*] --> s0
  s0 --> s1 : 首次 match
  s1 --> s1 : add() → 抛错

Context 响应状态 源码事实✓ context.ts#L414 源码事实✓ context.ts#L519

正在排版…
查看 Mermaid 源码
stateDiagram-v2
  s0 : 未定稿(仅预备 headers)
  s1 : 已定稿 finalized
  [*] --> s0
  s0 --> s1 : set res / c.text 等
  s1 --> s1 : header() → 克隆 Response 再改

承重模式

架构权衡

最小 MVP 骨架

约 70 行 TypeScript:把 Hono 的内核压缩成可读骨架(展开)
type Next = () => Promise<void>
type Handler = (c: Ctx, next: Next) => Response | void | Promise<Response | void>

class Ctx {
  res?: Response
  finalized = false
  #vars?: Map<string, unknown>
  constructor(public req: Request, public params: Record<string, string>) {}
  set(k: string, v: unknown) { (this.#vars ??= new Map()).set(k, v) }
  get(k: string) { return this.#vars?.get(k) }
  text(body: string, status = 200) {
    this.res = new Response(body, { status })
    this.finalized = true
    return this.res
  }
}

function compose(handlers: Handler[]) {
  return async (c: Ctx) => {
    let last = -1
    const run = async (i: number): Promise<void> => {
      if (i <= last) throw new Error('next() called multiple times')
      last = i
      const h = handlers[i]
      if (!h) return
      const r = await h(c, () => run(i + 1))
      if (r instanceof Response) { c.res = r; c.finalized = true }
    }
    await run(0)
    return c
  }
}

interface Router<T> { add(m: string, p: string, h: T): void; match(m: string, p: string): [T, Record<string, string>][] }

class LinearRouter<T> implements Router<T> {
  #routes: [string, RegExp, string[], T][] = []
  add(m: string, p: string, h: T) {
    const keys: string[] = []
    const re = new RegExp('^' + p.replace(/\*/g, '.*').replace(/:(\w+)/g, (_, k) => (keys.push(k), '([^/]+)')) + '$')
    this.#routes.push([m, re, keys, h])
  }
  match(m: string, p: string) {
    const out: [T, Record<string, string>][] = []
    for (const [rm, re, keys, h] of this.#routes) {
      const hit = (rm === 'ALL' || rm === m) && re.exec(p)
      if (hit) out.push([h, Object.fromEntries(keys.map((k, i) => [k, hit[i + 1]]))])
    }
    return out
  }
}

export class MiniHono {
  router: Router<Handler> = new LinearRouter<Handler>()
  get(path: string, ...hs: Handler[]) { hs.forEach((h) => this.router.add('GET', path, h)); return this }
  use(...hs: Handler[]) { hs.forEach((h) => this.router.add('ALL', '*', h)); return this }
  fetch = async (req: Request): Promise<Response> => {
    const path = new URL(req.url).pathname
    const matched = this.router.match(req.method, path)
    const c = new Ctx(req, matched.at(-1)?.[1] ?? {})
    const notFound = () => new Response('404 Not Found', { status: 404 })
    if (matched.length === 1) {
      return (await matched[0][0](c, async () => {})) ?? c.res ?? notFound()
    }
    await compose(matched.map(([h]) => h))(c)
    return c.res ?? notFound()
  }
}

避坑

可以偷的点

判断:用 + 借鉴

做多运行时/边缘 HTTP API 可直接用;造自己的框架或中间件系统时,compose 内核、路由策略与快路径值得照搬。

阅读路线

  1. src/hono.ts — 33 行看清默认装配:HonoBase + SmartRouter
  2. src/hono-base.ts — #addRoute 与 #dispatch:请求主路径
  3. src/compose.ts — 洋葱模型内核(证据包只含签名,需回原文)
  4. src/context.ts — 惰性对象与 finalized 语义
  5. src/router/smart-router/router.ts — 路由回退策略(证据包只含类签名,需回原文)

由 dogfood 原型生成:prepare 9.89s · 宿主综合 77s · finalize 1.14s。类型:源码事实/作者声明需逐字引文锚点;✓=校验通过,✗=未通过。校验错误 0 条。