npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@type-dom/router

v0.9.0

Published

## 1. 概述

Readme

TypeDom Router

1. 概述

TypeDom Router 是自研的企业级路由系统,基于 TypeScript 构建,深度集成 @type-dom/signals 响应式系统,支持 History、Hash、Memory 三种模式,具备完整的类型安全和导航守卫体系。

  • 核心体积: 35.6KB 路由逻辑 + 19.73KB 匹配引擎
  • 设计理念: 面向对象 + 响应式状态 + 分层守卫
  • 目标场景: 大型单页应用、微前端、跨平台路由

2. 目录结构

libs/router/
├── src/
│   ├── router/           # 核心 Router 类实现
│   ├── matcher/          # 路径匹配算法
│   ├── history/          # History/Hash/Memory 模式
│   ├── navigationGuards/ # 导航守卫体系
│   ├── types/            # 类型定义
│   ├── encoding.ts       # 编码解码工具
│   ├── errors.ts         # 错误定义
│   ├── location.ts       # 位置信息封装
│   ├── query.ts          # 查询参数处理
│   ├── scrollBehavior.ts # 滚动行为控制
│   ├── devtools.ts       # DevTools 集成
│   ├── injectionSymbols.ts # 注入符号
│   └── index.ts          # 入口导出
├── tests/                # 单元测试
│   ├── encoding.spec.ts  # 编码解码测试
│   ├── errors.spec.ts    # 错误与导航失败测试
│   └── ...               # 其它测试文件
├── dist/                 # 编译输出
└── README.md             # 简要说明

3. 核心架构

3.1 接口定义

  • RouteRecordRaw: 路由记录原始结构
  • Router: 路由实例接口
  • NavigationGuardWithThis: 带上下文的守卫类型
  • Location: 路由位置描述

3.2 核心类

  • Router: 路由管理器,负责初始化、导航、状态维护
  • RouteRecordMatcher: 路由记录匹配器,管理路由表与匹配算法
  • HTML5History / HashHistory / MemoryHistory: 不同历史模式实现

3.3 测试覆盖 - 核心架构

  • 测试文件: tests/createRouter.test-d.tstests/errors.spec.ts
  • 覆盖点:
    • Router 实例化与配置验证
    • 路由表注册与匹配结果类型检查
    • 生命周期钩子调用顺序
    • 错误类型与导航失败分类验证 (NavigationFailureType)

4. 核心算法

4.1 路径匹配算法

  • 静态路由优先匹配
  • 动态参数智能解析
  • 匹配结果评分排序(静态段 > 动态段 > 通配符)
  • 二分查找插入,复杂度 O(log n)

4.2 导航守卫执行流程

  1. 全局前置守卫 (beforeEach)
  2. 路由独享守卫 (beforeEnter)
  3. 组件内守卫 (beforeRouteEnter, beforeRouteUpdate, beforeRouteLeave)
  4. 全局解析守卫 (beforeResolve)
  5. 导航确认,触发视图更新
  6. 全局后置钩子 (afterEach)

执行策略:串行执行,确保顺序与可预测性。

4.3 测试覆盖 - 算法与守卫

  • 测试文件: tests/errors.spec.ts
  • 覆盖点:
    • next(false) 中止导航并触发 afterEach
    • next('/location') 重定向处理
    • 重复导航触发 NavigationFailureType.duplicated
    • 异步守卫挂起与新导航取消处理 (NavigationFailureType.cancelled)
    • 守卫抛出异常或返回拒绝 Promise 时触发 onError
    • History 模式下 go(-1) 与守卫交互行为

5. 历史管理模式

5.1 HTML5 History

  • 使用 pushState / replaceState 操作浏览器历史
  • 监听 popstate 事件处理前进/后退
  • 支持滚动位置持久化

5.2 Hash History

  • 基于 URL hash 实现,无需服务端配置
  • 监听 hashchange 事件

5.3 Memory History

  • 纯内存历史栈,适用于 SSR / 测试环境
  • 手动控制前进/后退

5.4 测试覆盖 - 历史管理

  • 测试文件: tests/errors.spec.ts 中的 describe('history navigation')
  • 覆盖点:
    • History 模式下 go(-1) 与守卫交互
    • next(false)next('/location')next()next(true) 在 History 回退时的行为
    • History 回退过程中守卫抛错触发 onError

6. 响应式集成

  • 路由状态(currentRoute)通过 @type-dom/signals 实现响应式
  • 状态变更自动触发依赖组件更新
  • 与框架层无缝结合,避免不必要的重渲染

6.1 测试覆盖 - 响应式

  • 响应式变化在测试中通过 router.currentRoute.get() 断言
  • errors.spec.ts 中多处对 router.currentRoute.get() 的校验

7. 类型安全

  • 完整的 TypeScript 类型定义
  • 路由名称、参数、查询参数均支持泛型
  • 编译期检查路由配置有效性
  • 运行时类型保护函数

7.1 测试覆盖 - 类型安全

  • 测试文件: tests/createRouter.test-d.ts
  • 覆盖点:
    • 路由名称、参数类型推断
    • 路由位置描述类型校验
    • isNavigationFailure 类型判断函数正确性

8. 编码与错误处理

8.1 编码解码 (encoding.ts)

  • encodeParamencodeQueryKeyencodeQueryValueencodeHash
  • 符合 RFC 3986 与 URL Living Standard

8.2 错误处理 (errors.ts)

  • NavigationFailureType 分类
  • isNavigationFailure 判断函数
  • createRouterError 统一错误构造

8.3 测试覆盖 - 编码与错误

  • 测试文件: tests/encoding.spec.ts

  • 覆盖点:

    • 不编码安全字符集(unreservedSet、safePerSpec)
    • 非 ASCII 与不可打印字符正确编码
    • Query 参数空格编码为 +,加号编码为 %2B
    • Hash 编码安全集验证
  • 测试文件: tests/errors.spec.ts

  • 覆盖点:

    • isNavigationFailure 对普通错误返回 false
    • NAVIGATION_ABORTEDNAVIGATION_CANCELLEDNAVIGATION_DUPLICATED 分类识别
    • 多类型掩码判断逻辑

9. 性能优化

  • 匹配缓存: LRU 缓存最近匹配结果
  • 预编译正则: 启动时预编译路由正则,提高匹配速度
  • 防抖导航: 高频导航请求合并处理
  • 惰性匹配: 仅在需要时才进行路径匹配
  • 内存管理: 路由卸载时清理响应式依赖

10. 扩展能力

  • DevTools: 支持 Vue DevTools 协议,便于调试
  • 滚动行为: 可自定义切换路由时的滚动位置恢复策略
  • 动态路由: 运行时添加/删除路由记录
  • 多模式并存: 同一应用可使用多种历史模式

11. 使用示例

import { createRouter, createWebHistory } from '@type-dom/router'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/', component: Home },
    { path: '/user/:id', component: User, props: true },
  ],
})

// 导航守卫
router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth && !isAuthenticated()) next('/login')
  else next()
})

12. 总结

TypeDom Router 通过面向对象设计与响应式系统集成,提供了高性能、类型安全、易扩展的路由解决方案。其分层守卫、智能匹配算法以及与 Signals 的深度结合,使其在大型应用中具备显著优势。测试用例覆盖了编码解码、错误处理、导航守卫、历史模式、类型安全等关键模块,确保核心逻辑的可靠性与健壮性