Compare commits

..

76 Commits

Author SHA1 Message Date
imbytecat 749697634a chore(env): 更新本地环境示例 2026-05-11 20:51:43 +08:00
imbytecat 6f627fe776 docs: 更新 MySQL 展示系统说明 2026-05-11 20:51:43 +08:00
imbytecat ddd077eb37 chore(dev): 添加本地 MySQL seed 环境 2026-05-11 20:51:43 +08:00
imbytecat 3040608959 refactor(db): 移除嵌入式迁移链路 2026-05-11 20:51:43 +08:00
imbytecat bec1026a94 refactor(db): 移除 PostgreSQL 运行时层 2026-05-11 20:51:43 +08:00
imbytecat e722913468 refactor(todo): 移除 Todo API 示例 2026-05-11 20:51:34 +08:00
imbytecat 334e387765 refactor(todo): 移除 Todo 前端示例 2026-05-11 20:51:34 +08:00
imbytecat b722799ca3 feat(ui): 新增电池实时状态页 2026-05-11 20:51:34 +08:00
imbytecat df7b58c2f8 feat(ui): 重建 SoH 看板首页 2026-05-11 20:51:34 +08:00
imbytecat 4e5ba4b599 feat(api): 实现电池 ORPC 路由 2026-05-11 20:51:24 +08:00
imbytecat 657c7317f7 feat(api): 暴露电池 ORPC 契约 2026-05-11 20:51:24 +08:00
imbytecat ebe0970df1 feat(mysql): 接入只读电池数据源 2026-05-11 20:51:24 +08:00
imbytecat 8b6339f34b feat(domain): 新增电池领域模型与聚合逻辑 2026-05-11 20:51:24 +08:00
imbytecat 393ff406a3 docs(readme): 强调 PostgreSQL 18+ 要求并提供 escape hatch
代码 schema 用了 PG 原生 uuidv7() 函数,PG <18 会炸。在技术栈行里把
PostgreSQL 改成 PostgreSQL 18+,快速开始顶部加 callout 说明改回
Bun.randomUUIDv7() 的方式以兼容老版本。
2026-04-25 17:34:43 +08:00
imbytecat 9073e38238 chore: gitignore瘦身154->21行 + migrate onnotice改logger.debug
gitignore: 删社区模板倒灌的死分支 (bower/jspm/snowpack/parcel/fusebox
/dynamodb/firebase/yarn-v3/sveltekit/vuepress/docusaurus/gatsby/next
/nuxt/grunt/eslintcache 等),只留实际命中的 ~20 行。KISS。

migrate: onnotice 从空函数改成 logger.debug,消除最后一处 silent
black hole。pg NOTICE 现在会出现在 LOG_LEVEL=debug 下。
2026-04-25 17:29:18 +08:00
imbytecat 27e5f3c76f chore(vite): remove server block (no need to pin port 3000 strict)
vite default already binds 3000 if available; no real requirement to
strict-port. AGENTS.md / README.md synced.
2026-04-25 17:19:27 +08:00
imbytecat 4a78ba2882 refactor(db): UUIDv7 \u751f\u6210\u4e0b\u63a8\u5230 PG18 \u539f\u751f uuidv7()\uff0c\u8005\u53ea\u6539 schema
\u53ea\u6539 schema \u5c42\u9762\uff1a
- src/server/db/fields.ts:
  $defaultFn(() => Bun.randomUUIDv7()) \u2192 default(sql`uuidv7()`)
- AGENTS.md Stack & runtime: \u52a0 PG18+ \u786c\u7ea6\u675f
- AGENTS.md Drizzle \u8282\u8bf4\u660e DB-side uuidv7\uff08\u5355\u8c03\u3001\u4f7f\u7528 DB \u65f6\u949f\uff09
- AGENTS.md Bun-native \u539f\u5219\u533a\u5206 app-code UUIDv7 \u4e0e DB PK
- AGENTS.md Don'ts \u9996\u6761\u52a0 "AI \u4e0d\u80fd\u8dd1 db:generate"

\u4f9d\u7136\u9700\u8981\u4f60\u624b\u52a8\u8dd1 `bun run db:generate` \u4ee5\uff1a
1) \u751f\u6210\u65b0 migration\uff08\u5e94\u8be5\u662f DROP \u8001\u8868 + CREATE \u65b0\u8868\uff0c
   \u6216\u4f60\u624b\u5199 ALTER COLUMN id SET DEFAULT uuidv7()\uff09
2) \u91cd\u751f migrations.gen.ts

\u672c commit \u72b6\u6001\u4e0b\u8fd0\u884c\u65f6\u5c1a\u4e0d\u53ef\u7528\uff08\u8001 migration \u672a\u8bbe DEFAULT\uff0c
\u63d2\u5165\u4f1a\u62a5 NOT NULL \u9519\uff09\uff1bdb:generate \u540e\u91cd\u65b0 build/compile/deploy \u624d\u662f
\u5b8c\u6574\u72b6\u6001\u3002fix / typecheck / test 3/3 \u5747\u8fc7\uff08\u9759\u6001\u68c0\u67e5\u4e0d\u4f9d\u8d56 migration\uff09\u3002
2026-04-25 17:12:06 +08:00
imbytecat fafe02bdbd refactor: 主动审计修复多处可观测性、依赖、代码质量缺口
通过并行 explore + librarian + 自查发现并修复:

代码缺陷
- shutdown.ts: db.$client.end().finally(...) 静默吞错——关闭失败会
  谎报 "DB pool closed" 后照常 exit 0。改用 await + try/catch
  分别记录成功/失败,setTimeout 也换成 Bun.sleep。
- interceptors.ts: 两条 instanceof ORPCError && instanceof
  ValidationError 重复检查,改用 early return + 单 if 分支区分 code。
- types.ts: 移除从未被引用的 RouterInputs 死代码(仅 RouterOutputs
  被 TodoItem 用到)。

Bun 原生 API(删/换 Node 兼容层)
- fields.ts: uuid v7 → Bun.randomUUIDv7(),删除 uuid 依赖
- migrate.ts: node:crypto.createHash → Bun.CryptoHasher.hash,
  少一个 Promise.all 项 + 一个 import
- shutdown.ts: setTimeout → Bun.sleep(顺带)

Biome 2.4 规则补强
- domains.types: "all"——开启类型感知规则集(noFloatingPromises /
  noMisusedPromises / useAwaitThenable / noUnnecessaryConditions
  等 Promise/异步陷阱)
- domains.drizzle: "recommended"、domains.react: "recommended"
- 显式开启 suspicious.noImportCycles(2.4 已 promote)

文档
- AGENTS.md 在 Stack & runtime 段加 "Prefer Bun-native APIs"
  原则,列出 UUIDv7/SHA-256/sleep/Bun.file 的优先路径
- AGENTS.md 在 Code style (Biome) 段记录本次启用的 lint domain
  与 noImportCycles 规则

验证:fix / typecheck / test 3/3 / build 568ms / compile 117M /
docker compose 全套(migrate JSON 日志 ✓、UUIDv7 写入 ✓、SIGTERM
shutdown 正确序列化 ✓)
2026-04-25 17:06:22 +08:00
imbytecat 815ee31f95 refactor(layout): 根目录脚本归位 src/ 与 scripts/,sql.d.ts 下沉到 db/
- bin.ts → src/bin.ts (生产入口归并到 src/,import 改用 #package + @/cli/*)
- compile.ts → scripts/compile.ts (开发期工具)
- embed-migrations.ts → scripts/embed-migrations.ts (codegen)
- src/sql.d.ts → src/server/db/sql.d.ts (与唯一消费者 migrations.gen.ts 共址)

效果:项目根从 3 个零散 .ts 减为 0 个,src/ 是完整应用源码,scripts/
明确区分开发期工具。所有 package.json scripts、AGENTS.md layout/CLI 章节、
compile.ts ENTRYPOINT 与 .js.map 清理路径同步更新。

验证:fix / typecheck / test 3/3 / build 570ms / compile 117M / docker
compose 全套(migrate 干净的 logger=cli.migrate JSON 日志、app /health
200、POST /api/todo/create 成功)。
2026-04-25 16:50:48 +08:00
imbytecat f8af18cff5 fix(docker): 移除 stale COPY patches 行修复 docker build
d9210b3 升级 TanStack Start 至 1.167.48 时删除了 patches/ 目录
(upstream PR #7249 已修),但漏掉同步更新 Dockerfile,导致
docker build 报 "/patches": not found 失败。

验证:docker compose build app 通过。
2026-04-25 16:37:43 +08:00
imbytecat 34d2cbb1cd refactor(logging): 二次审计修复 oracle 漏掉的可观测性缺口与占位符冗余
二次深度审计发现:

1. shutdown.ts SIGINT/SIGTERM 路径完全沉默——生产环境 k8s pod 终止时
   操作者在日志里看不到任何痕迹。补 getLogger(['shutdown']) 三条日志:
   - "Draining for shutdown" {signal, graceMs} (优雅关停起点)
   - "Forcing exit on repeated signal" {signal} (二次信号强制退出)
   - "DB pool closed, exiting" (干净退出确认)

2. interceptors.ts 与 shutdown.ts 的 {error}/{signal} 占位符在 JSON 模式
   下导致 message 字段重复 inspect 转义 properties 里的同一份内容
   (Error/对象会被 JSON.stringify 内联进 message,引号被反斜杠转义)。
   规则收敛:占位符仅用于"想要内联渲染"的基本类型(id、count、duration),
   对象/Error 直接放 properties,message 保持人类可读短句。

3. AGENTS.md Logging 段更新示例与规则,反映实际最佳实践。

端到端验证(compose + Postgres 18-alpine):
- /api/rpc/todo/list 成功 → logger=db level=INFO 输出 SQL ✓
- /api/rpc/todo/create 校验失败 → logger=api level=ERROR
  message="Unhandled error in ORPC handler" 干净,properties.error
  完整保留 code/status/message/data 字段 ✓
- SIGTERM → 三条 shutdown logger 事件按预期输出 ✓
- typecheck / test 3/3 / build / compile 117M 全绿 ✓
2026-04-25 16:24:00 +08:00
imbytecat ce39faf778 refactor(logging): 接受 oracle 审计建议打磨三处不够极致的细节
1. configureSync 用 getConfig() === null 守卫幂等初始化。原写法
   reset: true 在 ESM 缓存正常时多余、HMR 重复求值时会反复
   resetSync() + 累积 process.on('exit') 监听器。

2. ['logtape','meta'] logger 加 parentSinks: 'override'。原配置
   它既挂自己的 console sink、又继承 root sink,meta 的 warning/
   error/fatal 会被打印两次。

3. DrizzleLogger 显式传 'info' level。原默认 'debug' 与 LOG_LEVEL
   默认 'info' 形成隐形依赖:用户必须同时设两个变量才能看到 SQL。
   现在 LOG_DB=true 单开关即生效,符合"开关即可用"审美。

附带:删除未消费的 export type { LogLevel };getLogger 改成直接
re-export from '@logtape/logtape',少一层本地 import 间接。

端到端验证(compose + Postgres 18-alpine):
- LOG_DB=true 默认 LOG_LEVEL=info 下 SQL 以 level=INFO logger=db 输出 ✓
- meta logger 不再重复 sink ✓
- typecheck / test 3/3 / build / compile 117M 全绿 ✓

Oracle 审计 ses_23c5090efffe1jzPR5fVVm1y6m,KISS 评分由 8/10 升至 9.2/10。
2026-04-25 16:14:30 +08:00
imbytecat cc3a5dc5ad feat(logging): 引入 LogTape 替换 console.* 为结构化日志
为什么选 LogTape(2026 实测):
- pino 在 bun build --compile 编译产物里因 worker_threads + 动态 require 在
  /\$bunfs/ 虚拟文件系统中崩溃,与单二进制部署核心目标冲突;
- LogTape 零依赖(5.3KB)、零 worker、纯 ESM、原生 Bun 导出条件,runtime
  agnostic,配合 configureSync 完美兼容 --bytecode 模式(无裸 top-level await);
- 一等公民集成:@logtape/drizzle-orm(SQL 查询日志)、@logtape/otel(后续
  OpenTelemetry sink 留扩展点)。

变更:
- src/server/logger.ts: configureSync 引导 + getLogger 重导出。format 默认
  process.stdout.isTTY ? pretty : json,可经 LOG_FORMAT 显式覆盖(绕开 Bun
  bundler 把 process.env.NODE_ENV 在 --minify 时 inline 成字面量的特殊处理)。
- src/server/api/interceptors.ts: logError 改用 getLogger(['api']).error(...) +
  结构化 properties,弃 logger.error 顶层 API。
- src/cli/migrate.ts: 所有 console.log 改走 getLogger(['cli','migrate']),logger
  在 run() 内 lazy-import 以保持 citty subcommand 模块体 side-effect-free。
- src/server/db/index.ts: env.LOG_DB=true 时挂 DrizzleLogger 适配器,SQL 查询
  按类别 ['db'] 在 debug 级输出(含 query/params/formattedQuery 三字段)。

新增 env 旋钮(t3-oss 校验):
- LOG_LEVEL: trace|debug|info|warning|error|fatal,默认 info
- LOG_FORMAT: pretty|json,默认 TTY 自动选
- LOG_DB: stringbool,默认 false

端到端验证(compose + Postgres 18-alpine):
- TTY 终端:pretty 输出含  图标 + ANSI 彩色 + 类别·路径 ✓
- 管道/Docker:JSON Lines 一行一条,含 @timestamp/level/logger/properties ✓
- LOG_FORMAT=pretty 强制覆盖 ✓
- ./server migrate 应用 migration 并经 logger 输出 ✓
- ./server serve + RPC round-trip:interceptor logError 与 drizzle SQL 日志
  在生产 JSON 模式下结构化输出 ✓
- fix / typecheck / test 3/3 / build / compile 117M 二进制全绿
2026-04-25 16:04:31 +08:00
imbytecat d206a3315f docs(readme): 重写为面向人类用户的版本
原版本以工程术语堆砌(强约定 / 契约优先 / 不变量等)开篇,对新人不友好。重写以"是什么 → 为什么 → 怎么跑 → 怎么扩 → 怎么部署 → 参考"为线索:

- 开篇一句话讲清单二进制部署的核心卖点
- 新增"为什么用这个"突出 4 条价值点
- 新增"目录结构"帮助导航
- "加功能"步骤补充粗体小标题,每步意图一目了然
- 部署、脚本、端点全部表格化,便于扫读
- 删除对 AGENTS.md 的引用(人类读者无关)
2026-04-25 15:34:48 +08:00
imbytecat c6027590a7 docs(readme): 全文中文化
保持原结构与技术准确性,仅做语言切换。技术术语(RPC、OpenAPI、migrate、Drizzle Studio 等)保留英文。
2026-04-25 15:30:36 +08:00
imbytecat dd1facd240 refactor(imports): #nitro 重命名为 #server,imports 字段 ASCII 排序
命名上避开实现耦合:被指向的 .output/server/index.mjs 本质是"编译后的 HTTP 服务器入口",与 nitro(构建器)无关;包装器 _serve-nitro.mjs 仍持"nitro"。未来即便切换至 hono / vite-ssr / h3,#server 名字仍准确。

字段排序改为 ASCII 升序:#drizzle/*.sql < #package < #server,便于 sort-package-json 与人眼对账。

端到端验证(compose + Postgres 18):
- ./server migrate ✓ (embedded SQL)
- /health = ok ✓
- /api/spec.json title=fullstack-starter version=1.0.0 ✓ (#package)
- RPC todo create+list 完整 round-trip ✓ (#server 解析 nitro 产物)
- biome/typecheck/test/build/compile 全绿
2026-04-25 15:28:04 +08:00
imbytecat 5174cff3c5 refactor(cli): _serve-nitro 改用 #nitro subpath import
src/cli/_serve-nitro.mjs 原本用 ../../.output/server/index.mjs 跨边界导入 nitro 构建产物,与 #package / #drizzle/* 同属 "src/ 跳出根目录" 场景。统一改为 #nitro。

新增 package.json#imports:
  "#nitro": "./.output/server/index.mjs"

端到端验证(compose + Postgres 18):
- 编译二进制内嵌 nitro serve() 入口 ✓
- ./server migrate:embedded SQL 应用成功 ✓
- ./server 运行:/health、/api/spec.json (title/version)、RPC create+list 全 OK ✓
- Stack trace 印证 #nitro 由 Bun 正确解析到 .output/server/index.mjs ✓
- biome/typecheck/test/build/compile 全绿
2026-04-25 15:23:05 +08:00
imbytecat 2209ab0b27 chore: 推荐 sort-package-json/gitignore 扩展并排序 package.json 键 2026-04-25 15:20:28 +08:00
imbytecat 7f4cfc8973 refactor: 跨边界导入改用 Node # subpath imports(package.json + drizzle SQL)
业务代码沿用 @/* (shadcn 等生态约定);仅"跳出 src/"的真实跨边界场景采用 Node 标准 #name:

- #package → ./package.json:替换 @/../package.json (2 处) 这种用 alias 跳出根目录的 hack
- #drizzle/*.sql → ./drizzle/*.sql:让 codegen 输出的 migrations.gen.ts 不再走 ../../../

效果:
- tsconfig.paths 与 vite.resolve.tsconfigPaths 维持,业务代码 0 改动
- 配置仅新增 package.json#imports 4 行
- Bun runtime / Vite 8 / TS bundler / 编译产物均原生支持

端到端验证:
- 编译二进制:CREATE TABLE 和 'fullstack-starter' 内嵌 ✓
- ./server migrate:应用嵌入式迁移成功 ✓
- ./server 运行:/health、/api/spec.json (title/version)、RPC create+list、OpenAPI create、Scalar /api/docs 全部 OK ✓
- bun run dev:Vite SSR <title>fullstack-starter</title> 注入 ✓
- fix/typecheck/test/build/compile 全绿
2026-04-25 15:15:20 +08:00
imbytecat afc8b0b077 chore(deps): 升级 nitro-nightly 至 20260424 构建
全量依赖审计:bun outdated 已 0 项;package.json ^ 范围内所有包均解析至 latest(react 19.2.5、vite 8.0.10、TS 6.0.3、tailwind 4.2.4、tanstack 1.168.x、orpc 1.14.0、biome 2.4.13 等)。仅 nitro-nightly 因日构建版本号锁定到具体哈希需手动 bump。drizzle-orm/kit 维持 0.x 最新(0.45.2 / 0.31.10),未跟进 1.0 beta(AGENTS.md 政策)。
2026-04-25 14:57:59 +08:00
imbytecat d9210b3b0b chore(deps): 升级 TanStack Start 至 1.167.48,移除 start-plugin-core patch
upstream 已修(PR #7249,1.169.4 拆分 vite/rsbuild subpath,
@rsbuild/core 列为 optional peer),patches/ 不再必要。

- @tanstack/react-start ^1.167.43 → ^1.167.48
- @tanstack/react-router ^1.168.23 → ^1.168.24
  (react-start@1.167.48 exact 依赖,避免 lockfile 双版本)
- 删除 patches/@tanstack%2Fstart-plugin-core@1.168.0.patch
- 删除 package.json patchedDependencies 块
- AGENTS.md 移除 patches/ layout 说明

验证:fix / typecheck / test / build / compile 均通过;
start-plugin-core@1.169.4 dist 不再静态 import rsbuild。
2026-04-25 14:52:15 +08:00
imbytecat 4f414014a8 refactor(codegen): embed-migrations 校验 journal tag/idx/when
防止手改 _journal.json 时 tag 字符串混入路径或注入 codegen import 语句;
同时锁紧 idx/when 为非负整数。
2026-04-25 14:50:36 +08:00
imbytecat ed257fe4e6 refactor: 应用 Oracle round-4 复核,硬化 migrator 与默认安全值
- migrate: 校验已应用 migration 的 SHA-256,拒绝 schema drift;
  split 后 trim + skip empty,避免空 statement 触发 SQL 错误
- todo.contract: update 拒绝空 patch
- env: DATABASE_URL 限定 postgres(ql):// scheme,配置错误更早失败
- compile: autoloadDotenv: false,二进制部署不再吞 cwd 的 .env
- Error.tsx: 生产环境隐藏 error.message,避免内部错误泄露
- AGENTS: 同步 generatedFieldKeys / migrator 行为新描述
2026-04-25 14:38:44 +08:00
imbytecat 695e826dcf refactor(types): 消除非必要 as 逃逸,锁紧 strict 政策
按 Oracle 复核处置全仓 5 处类型断言:

- fields.ts: as const → satisfies Record<GeneratedFieldKey, true>
- compile.ts: as readonly string[] → ReadonlySet<string>.has()
- embed-migrations.ts: JSON.parse as Journal → Zod schema 运行时校验,JSON.parse 显式 unknown
- interceptors.ts: 唯一保留的跨包断言(ORPC→Zod)注释扩写为完整背景
- router.tsx: satisfies 非 cast,保留

biome.json 增配 noExplicitAny / noTsIgnore / noNonNullAssertion,防止后续漂移。
2026-04-25 14:23:08 +08:00
imbytecat f520b54ca5 docs(agents): 同步 embed-migrations 与 sql.d.ts,修陈旧描述
- CLI 帮助块与 Layout migrate.ts 注释从 "from ./drizzle" 改为 "embedded migrations"
- 补 src/sql.d.ts(with { type: 'text' } SQL 导入的载体)到 Layout
- 补 patches/(patchedDependencies 用途)到 Layout
2026-04-25 14:11:21 +08:00
imbytecat 7e27640a26 feat(deploy): migrations 嵌入二进制,实现真单文件部署
- embed-migrations.ts:扫 ./drizzle/meta/_journal.json,生成 src/server/db/migrations.gen.ts,每条 SQL 通过 `import sql_<idx> from '../../../drizzle/<tag>.sql' with { type: 'text' }` 在 bun build --compile 时被静态嵌入二进制
- migrate.ts 重写:runtime 用 createHash('sha256') 计算迁移哈希,仅用 db.execute(sql) + db.transaction() 公开 API 写入 drizzle.__drizzle_migrations 簿记表(不依赖 @internal 的 db.dialect/db.session)
- db:generate 链 db:embed,保证 SQL 改动总是同步到 migrations.gen.ts
- Dockerfile 删 COPY drizzle/,binary 是部署唯一 artifact
- 同步 README / AGENTS / biome.json
2026-04-25 14:05:58 +08:00
imbytecat e28fe9dc7b perf(compile): 启用 bytecode + minify + inline sourcemap
- Bun 官方 bytecode caching:中型应用 startup ~2x(docs.bun.sh/docs/bundler/bytecode)
- minify:减小 bytecode 体积,二进制仅 +2MB sourcemap
- sourcemap inline:嵌入二进制,保证错误堆栈可读,并在 compile.ts 清理 bundler 残留的 *.js.map
2026-04-25 14:05:35 +08:00
imbytecat 20104a6d53 docs(readme): 补 test 脚本与 query helper 步骤
- scripts 表加 `bun run test`
- Add a feature 拆出 `src/client/queries/<feature>.ts` 步骤,与 AGENTS.md 对齐
2026-04-25 13:37:05 +08:00
imbytecat a3a62c24b9 docs: 新增 README,AGENTS 同步至当前架构
- README: 用户向 quick-start、scripts 表、add-a-feature checklist、deploy 流程
- AGENTS:
  - 修订 stale 文案(VITE_APP_TITLE/experimental_defaults/.gitkeep/route 组件风格)
  - 新增 Testing 段(bun test 约定)和 Endpoints 段(/, /health, /api/*)
  - Layout 补 logger.ts、health.ts、components/、styles.css、根 drizzle/
  - 追加 10 条 room-to-grow 纪律(client query / middleware / interceptor / 测试等扩展边界)
2026-04-25 13:31:45 +08:00
imbytecat 6dc7f9f791 test: 启用 bun test 并补 todo contract 示例
- package.json 加 "test": "bun test"
- todo.contract.test.ts 给 starter 一个可复制的 colocated 测试样板
  覆盖 valid input / missing field / wrong type 三种 case
2026-04-25 13:31:34 +08:00
imbytecat 8f7744ca0d feat(server): 新增统一 logger 入口与 /health liveness 端点
- src/server/logger.ts 包一层 console.*,给后续 pino/otel 迁移留单点
- interceptors.ts 的 logError 改走 logger.error,业务侧禁止直接 console.*
- /health 返回 'ok',纯 liveness(不查 DB),DB 挂时探活仍绿
2026-04-25 13:31:25 +08:00
imbytecat 830c908712 refactor(arch): 移除 experimental_defaults,提炼 useInvalidateTodos,闭环若干悬挂配置
- orpc.ts: 改为纯 createTanstackQueryUtils,不再依赖 experimental_ API
- 抽出 src/client/queries/todo.ts 的 useInvalidateTodos,避免 query key 散落页面
- shutdown: setTimeout 内 db.$client.end() 失败也走 process.exit
- 删除 db/index.ts 未被使用的 DB 类型导出
- 删除 env.ts 未被消费的 VITE_APP_TITLE,根 title 改为 package.json name
- 清理 routes/index.tsx 的 JSX 区段注释、compose.yaml 注释掉的端口块、robots.txt URL 注释
2026-04-25 13:31:16 +08:00
imbytecat 2c5bceb826 fix(deploy): 端到端跑通编译二进制 + docker compose
端到端验证时发现 4 处细节,一起补上:

1. bin.ts 漏了 default: 'serve'——CMD ["./server"] 会直接吐 help 而
   不是起服务(在 compose 里 app 立刻 exit)。citty 原生支持 default
2. Dockerfile 在 bun install 之前就要 COPY patches/,否则 package.json
   的 patchedDependencies 找不到补丁文件,install 失败
3. drizzle/ 目录在仓库里必须存在(带 .gitkeep),否则 Dockerfile 末尾
   COPY drizzle/ 到运行镜像会失败
4. migrate.ts 之前只检查 ./drizzle 目录是否存在就跳过——空目录时仍会
   进到 drizzle 的 readMigrationFiles,报 Can't find meta/_journal.json。
   改成检查 meta/_journal.json 是否存在,更准确地区分"还没生成过迁移"
   与"有迁移待应用"

验证路径:
- docker compose up -d --build → migrate 完成退出 → app 健康
- curl /api/spec.json → 200,OpenAPI 文档含 todo.{list,create,update,remove}
2026-04-24 20:43:36 +08:00
imbytecat 5dd54ec9e9 docs(agents): 同步架构简化后的规约
- DB:module-level const db(删掉 getDB/closeDB 的描述),说明为什么
  不需要兼容 Cloudflare Workers 的 lazy init
- Routers 直接 import db,不再过 middleware;只在真正需要 per-request
  上下文时才新建 middlewares/
- Layout 刷新 db/ 与 api/ 目录的注释;Don'ts 补上不要回退到 lazy DB 单例
2026-04-24 20:38:51 +08:00
imbytecat 22ac02cbc6 refactor(db): 精简 generatedFields,删三分支 PK 策略与泛型 keys 工具
- PK 策略原本给了 native(PG18)/extension/app-side 三条路,对 base 项目
  是 YAGNI。全部落到最稳妥的 $defaultFn(uuidv7):任意 PG 版本都能跑,
  不依赖扩展或 18+ 的 uuidv7() 原生函数
- createGeneratedFieldKeys 泛型 reduce 只为了生成 { id: true, createdAt:
  true, updatedAt: true } 这三项,直接手写 as const 更直观
- 删掉 pk/id/createdAt/updatedAt 的独立 helper 导出——没人引用,它们
  只是 generatedFields 的内部组合
2026-04-24 20:37:51 +08:00
imbytecat 2678a53034 refactor(api): 删掉 db ORPC middleware,handler 直接用 db
db middleware 的存在只是为了把 db 注入到 ORPC context——这是 Cloudflare
Workers / 多租户场景的模式(db 依赖 per-request 的 env binding)。在
Bun 单进程 + 模块级 const db 下,这层中间件是纯粹的仪式:一行 import
直接拿到 db,反而更清晰。

- 删除 src/server/api/middlewares/ 整个目录(不留空脚手架,KISS)
- context.ts 去掉 DBContext 与示例注释,只留 BaseContext { headers }
  作为未来 auth/tenant 等 middleware 的扩展点
- routers/todo.router.ts 不再 .use(db),handler 内直接 db.query / db.insert

需要 per-request 上下文(auth、tenant、rate-limit)时再按 ORPC 的
os.middleware 模式新增,不在此预先铺陈。
2026-04-24 20:37:11 +08:00
imbytecat d15b22ad1b refactor(db): 去掉 lazy singleton,改为模块级 const db
getDB/closeDB + 可空单例是 Cloudflare Workers 场景的模式——每个请求独
立上下文、不允许模块加载期副作用。在 Bun 单进程长驻服务下这些都是冗余
的仪式,徒增心智。

改为模块级 const db:
- src/server/db/index.ts 直接 export drizzle(...) 实例
- shutdown 插件用 db.$client.end() 收尾
- db.middleware.ts 跟随内部重命名以避免同名遮蔽(本身的去留放到下一
  次提交)
2026-04-24 20:36:16 +08:00
imbytecat f6b6edee23 fix(deps): 补丁绕过 @tanstack/start-plugin-core 误引 @rsbuild/core
@tanstack/start-plugin-core@1.168.0 的 dist/esm/index.js 在 Vite 场景
下也会静态导入 ./rsbuild/planning.js,而后者硬依赖被标为 optional peer
的 @rsbuild/core,导致 vite build 启动阶段 ERR_MODULE_NOT_FOUND。

引入 bun patch 只保留 vite 相关导出(删掉 RSBUILD_ENVIRONMENT_NAMES
和 tanStackStartRsbuild),不安装 rsbuild 全家桶(rspack 很重)。
等上游修复再移除本补丁。
2026-04-24 20:35:22 +08:00
imbytecat 19e60d358f feat(cli): 引入 citty CLI,迁移改为显式 ./server migrate
- 顶层新增 bin.ts 作为编译入口,citty 懒加载 src/cli/ 下子命令
- src/cli/serve.ts 通过 _serve-nitro.mjs 桥接启动 Nitro(规避
  .output/server/index.mjs 顶层 serve(...) 的副作用导入)
- src/cli/migrate.ts 显式跑 drizzle migrate;env / drizzle 都在 run()
  里 await import,避免 citty --help 遍历 subCommands 时触发 env 校验
- compile.ts 入口切到 bin.ts;移除 src/server/plugins/migrate.ts
  与 vite.config.ts 中的启动时自动迁移
- compose.yaml 新增一次性 migrate 服务,app depends_on
  service_completed_successfully,保证迁移先行再起服
- tsconfig 排除 .output / out;AGENTS.md 补充 CLI 与部署规约
2026-04-24 20:32:32 +08:00
imbytecat 4518a63959 docs(agents): 同步 drizzle 0.x 降级后的指引
修正 AGENTS.md 里与 1.0 beta 相关的过时条目(drizzle-orm/zod、
defineRelations、RQB v2 对象语法等),改为记录当前真实用法:
drizzle-zod 包、`drizzle({ schema })`、RQB v1 回调写法。顺手裁掉
通用的 Biome/TS 说明,补上几条仓库特有的坑(Nitro 插件在 vite.config
里注册、distroless cc 变体、无 CI/pre-commit 等)。
2026-04-24 20:13:56 +08:00
imbytecat 75c77159b4 refactor(db): 适配 drizzle-orm 0.x API 并引入 drizzle-zod
drizzle-orm 从 1.0 beta 降级到 0.45 后,1.0 的 defineRelations、drizzle-orm/zod
子路径以及 RQB v2 的 orderBy 对象语法均不可用。改用 schema 作为 drizzle()
入参、从独立的 drizzle-zod 包导入 schema 生成器,并将 orderBy 改回 0.x 的
回调写法。同时删除因降级而失效的旧迁移。
2026-04-24 20:08:41 +08:00
imbytecat f9847e6f6e chore: 移除 opencode.jsonc 配置文件 2026-04-24 20:02:01 +08:00
imbytecat ac58950853 chore: 为 TanStack MCP 配置 Authorization 鉴权头 2026-04-24 19:51:48 +08:00
imbytecat 02757226f7 chore(deps): 锁定 Bun 版本并升级依赖
- Dockerfile 与 mise.toml 固定 bun 至 1.3.13
- 升级 ORPC/TanStack/Biome/Vite/TypeScript 等依赖
- drizzle-orm 与 drizzle-kit 回退至稳定版
2026-04-24 19:50:17 +08:00
imbytecat 934ba80c94 chore(deps): 升级 TanStack Router/Start 及 @types/bun 依赖 2026-04-11 20:53:34 +08:00
imbytecat 15118e8aa2 chore(deps): 升级 ORPC、React 与 Vite 相关依赖 2026-04-10 10:34:31 +08:00
imbytecat 1af5d4e3c0 fix: 修复编译二进制 Ctrl+C 无法退出的问题 2026-04-02 07:48:25 +08:00
imbytecat 6795730485 refactor(db): 暴露 closeDB() 函数以支持连接池清理 2026-04-02 07:48:16 +08:00
imbytecat c20cf02d9f chore: update Docker Compose configuration
- Use postgres:18-alpine image

- Update environment variable format

- Rename volume from pgdata to postgres_data

- Increase healthcheck interval to 10s
2026-04-02 03:49:38 +08:00
imbytecat 341315a01b chore: upgrade PostgreSQL to v18 and restructure compose.yaml 2026-04-02 03:43:37 +08:00
imbytecat 77b3484415 refactor: 改用 Nitro 插件实现启动时数据库迁移 2026-04-02 03:42:45 +08:00
imbytecat 5de4d5f940 chore: upgrade PostgreSQL to v18 and restructure compose.yaml 2026-04-02 02:45:00 +08:00
imbytecat ed770909ef chore: 添加 Docker 打包和 Compose 编排支持 2026-04-02 02:43:21 +08:00
imbytecat 9175909033 chore: 更新依赖 2026-04-02 00:57:49 +08:00
imbytecat 5f5f6c469a chore: remove unused shadcn MCP 2026-04-02 00:53:30 +08:00
imbytecat 087796038e chore(routes): 重新生成路由树以反映健康检查端点删除 2026-04-02 00:49:33 +08:00
imbytecat ca4e25827f chore(api): 删除未使用的健康检查端点 2026-04-02 00:48:41 +08:00
imbytecat 7700ba4520 docs: 修正 AGENTS.md 与代码库的 12 处不一致 2026-04-02 00:37:44 +08:00
imbytecat c67e773086 refactor: 抽取 UI 组件、改进错误页面、统一导入路径并简化数据库接口 2026-04-02 00:13:43 +08:00
imbytecat 4ec4576fc5 chore: remove Node.js from mise.toml (pure Bun project) 2026-04-01 23:28:35 +08:00
imbytecat 22363279c8 docs: 精简 AGENTS.md 文档结构并优化内容呈现 2026-04-01 23:24:23 +08:00
imbytecat b38d475b6f chore(deps): 升级 @orpc/* 至 1.13.13, @tanstack/react-query 至 5.96.1, @biomejs/biome 至 2.4.10 2026-04-01 23:18:42 +08:00
imbytecat 486cb7b129 chore(vscode): add promptToUseWorkspaceVersion for TypeScript SDK 2026-04-01 20:56:10 +08:00
imbytecat c894631c64 chore(db): 提交初始数据库迁移文件 2026-04-01 19:54:49 +08:00
imbytecat ce3684fdc0 fix: use relative import in drizzle.config.ts for path alias compatibility 2026-04-01 19:48:43 +08:00
imbytecat cd7b65fda4 refactor: flatten monorepo into standalone project 2026-04-01 19:43:21 +08:00
99 changed files with 2241 additions and 3307 deletions
+13
View File
@@ -0,0 +1,13 @@
node_modules/
.output/
.tanstack/
out/
.git/
.env
.env.*
*.md
*.tsbuildinfo
*.bun-build
.vscode/
+6
View File
@@ -0,0 +1,6 @@
DATABASE_URL=mysql://user:password@localhost:3306/database
# Optional logging knobs (defaults are usually fine):
# LOG_LEVEL=info # trace|debug|info|warning|error|fatal
# LOG_FORMAT=pretty # pretty|json — defaults to TTY ? pretty : json
# LOG_DB=false # reserved for database query logging if enabled later
+14 -148
View File
@@ -1,157 +1,23 @@
### Custom ###
# TanStack
.tanstack/
# Nitro
.output/
# Bun build
*.bun-build
# Turborepo
.turbo/
### Node ###
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
# Dependencies
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
# Build output
.output/
.tanstack/
.vite/
out/
*.bun-build
*.tsbuildinfo
vite.config.js.timestamp-*
vite.config.ts.timestamp-*
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional stylelint cache
.stylelintcache
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variable files
# Env
.env
.env.*
!.env.example
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Logs
*.log
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist
.output
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# vuepress v2.x temp and cache directory
.temp
.cache
# Sveltekit cache directory
.svelte-kit/
# vitepress build output
**/.vitepress/dist
# vitepress cache directory
**/.vitepress/cache
# Docusaurus cache and generated files
.docusaurus
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# Firebase cache directory
.firebase/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v3
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/sdks
!.yarn/versions
# Vite files
vite.config.js.timestamp-*
vite.config.ts.timestamp-*
.vite/
# OS
.DS_Store
+3 -1
View File
@@ -1,9 +1,11 @@
{
"recommendations": [
"biomejs.biome",
"codezombiech.gitignore",
"hverlin.mise-vscode",
"oven.bun-vscode",
"redhat.vscode-yaml",
"tamasfe.even-better-toml"
"tamasfe.even-better-toml",
"unional.vscode-sort-package-json"
]
}
+1
View File
@@ -44,6 +44,7 @@
"**/routeTree.gen.ts": true
},
"js/ts.tsdk.path": "node_modules/typescript/lib",
"js/ts.tsdk.promptToUseWorkspaceVersion": true,
"search.exclude": {
"**/routeTree.gen.ts": true
}
+78 -198
View File
@@ -1,218 +1,98 @@
# AGENTS.md - AI Coding Agent Guidelines
# AGENTS.md
Guidelines for AI agents working in this Bun monorepo.
Repo-specific notes for AI agents.
## Project Overview
## Stack
> **This project uses [Bun](https://bun.sh) exclusively as both the JavaScript runtime and package manager. Do NOT use Node.js / npm / yarn / pnpm. All commands start with `bun` — use `bun install` for dependencies and `bun run <script>` for scripts. Always prefer `bun run <script>` over `bun <script>` to avoid conflicts with Bun built-in subcommands (e.g. `bun build` invokes Bun's bundler, NOT your package.json script). Never use `npm`, `npx`, or `node`.**
- Bun-only (`mise.toml` pins `bun = 1.3.13`). Do not use `npm` / `npx` / `node` / `yarn` / `pnpm`.
- TanStack Start + React 19 SSR + Vite + Nitro `bun` preset.
- ORPC contract-first API, TanStack Query v5, Tailwind v4.
- Business data source is the customer's existing **MySQL** database. This app is read-only display software.
- There is no PostgreSQL, Drizzle schema, embedded migration flow, or local DB mutation path in this project now.
- `scripts/seed.ts` is the only local development helper allowed to create/truncate/insert sample data. The app runtime must stay read-only.
- **Monorepo**: Bun workspaces + Turborepo orchestration
- **Runtime**: Bun (see `mise.toml` for version) — **NOT Node.js**
- **Package Manager**: Bun — **NOT npm / yarn / pnpm**
- **Apps**:
- `apps/server` - TanStack Start fullstack web app (see `apps/server/AGENTS.md`)
- `apps/desktop` - Electron desktop shell, sidecar server pattern (see `apps/desktop/AGENTS.md`)
- **Packages**: `packages/tsconfig` (shared TS configs)
## Scripts
## Build / Lint / Test Commands
### Root Commands (via Turbo)
```bash
bun run dev # Start all apps in dev mode
bun run build # Build all apps
bun run compile # Compile server to standalone binary (current platform)
bun run compile:darwin # Compile server for macOS (arm64 + x64)
bun run compile:linux # Compile server for Linux (x64 + arm64)
bun run compile:windows # Compile server for Windows x64
bun run dist # Package desktop distributable (current platform)
bun run dist:linux # Package desktop for Linux (x64 + arm64)
bun run dist:mac # Package desktop for macOS (arm64 + x64)
bun run dist:win # Package desktop for Windows x64
bun run fix # Lint + format (Biome auto-fix)
bun run typecheck # TypeScript check across monorepo
bun run dev
bun run build
bun run compile
bun run seed
bun run typecheck
bun run test
bun run fix
```
### Server App (`apps/server`)
Before shipping: `bun run fix && bun run typecheck && bun run test && bun run build`.
## MySQL Source
Environment variable:
```bash
bun run dev # Vite dev server (localhost:3000)
bun run build # Production build -> .output/
bun run compile # Compile to standalone binary (current platform)
bun run compile:darwin # Compile for macOS (arm64 + x64)
bun run compile:darwin:arm64 # Compile for macOS arm64
bun run compile:darwin:x64 # Compile for macOS x64
bun run compile:linux # Compile for Linux (x64 + arm64)
bun run compile:linux:arm64 # Compile for Linux arm64
bun run compile:linux:x64 # Compile for Linux x64
bun run compile:windows # Compile for Windows (default: x64)
bun run compile:windows:x64 # Compile for Windows x64
bun run fix # Biome auto-fix
bun run typecheck # TypeScript check
# Database (Drizzle)
bun run db:generate # Generate migrations from schema
bun run db:migrate # Run migrations
bun run db:push # Push schema (dev only)
bun run db:studio # Open Drizzle Studio
DATABASE_URL=mysql://user:password@host:3306/database
```
### Desktop App (`apps/desktop`)
```bash
bun run dev # electron-vite dev mode (requires server dev running)
bun run build # electron-vite build (main + preload)
bun run dist # Build + package for current platform
bun run dist:linux # Build + package for Linux (x64 + arm64)
bun run dist:linux:x64 # Build + package for Linux x64
bun run dist:linux:arm64 # Build + package for Linux arm64
bun run dist:mac # Build + package for macOS (arm64 + x64)
bun run dist:mac:arm64 # Build + package for macOS arm64
bun run dist:mac:x64 # Build + package for macOS x64
bun run dist:win # Build + package for Windows x64
bun run fix # Biome auto-fix
bun run typecheck # TypeScript check
```
Customer table: `ls_battery_info`.
### Testing
No test framework configured yet. When adding tests:
```bash
bun test path/to/test.ts # Run single test file
bun test -t "pattern" # Run tests matching pattern
```
| Column | Type | Meaning |
| --- | --- | --- |
| `id` | `int(11)` auto increment | primary key |
| `user_id` | `int(11)` | user ID |
| `mac` | `varchar(50)` | device MAC |
| `dev_model` | `varchar(20)` | device model |
| `dev_name` | `varchar(50)` | device name |
| `is_low_power` | `varchar(10)` | `true` / `false` |
| `power_status` | `tinyint(4)` | `0` not charging, `1` charging, `2` full |
| `power` | `tinyint(4)` | current battery `0~100` |
| `create_time` | `datetime` | created time |
| `remark` | `varchar(500)` | nullable remark |
## Code Style (TypeScript)
Rules:
### Formatting (Biome)
- **Indent**: 2 spaces | **Line endings**: LF
- **Quotes**: Single `'` | **Semicolons**: Omit (ASI)
- **Arrow parentheses**: Always `(x) => x`
- Only run `SELECT` queries against this table. Do not insert, update, delete, migrate, or create tables.
- Do not add mock/fallback rows. If MySQL is unavailable, surface the error.
- `is_low_power` is stored as a string and normalized to boolean in `src/domain/battery.ts`.
- `power_status` is normalized to `0 | 1 | 2`.
- Without `mac`, battery list queries return the latest record per `mac`.
- With `mac`, battery list queries return history ordered by `create_time DESC, id DESC`, limited to 500 rows.
### Imports
Biome auto-organizes. Order: 1) External packages → 2) Internal `@/*` aliases → 3) Type imports (`import type { ... }`)
```typescript
import { createFileRoute } from '@tanstack/react-router'
import { z } from 'zod'
import { db } from '@/server/db'
import type { ReactNode } from 'react'
```
### TypeScript Strictness
- `strict: true`, `noUncheckedIndexedAccess: true`, `noImplicitOverride: true`, `verbatimModuleSyntax: true`
- Use `@/*` path aliases (maps to `src/*`)
### Naming Conventions
| Type | Convention | Example |
|------|------------|---------|
| Files (utils) | kebab-case | `auth-utils.ts` |
| Files (components) | PascalCase | `UserProfile.tsx` |
| Components | PascalCase arrow | `const Button = () => {}` |
| Functions | camelCase | `getUserById` |
| Constants | UPPER_SNAKE | `MAX_RETRIES` |
| Types/Interfaces | PascalCase | `UserProfile` |
### React Patterns
- Components: arrow functions (enforced by Biome)
- Routes: TanStack Router file conventions (`export const Route = createFileRoute(...)`)
- Data fetching: `useSuspenseQuery(orpc.feature.list.queryOptions())`
### Error Handling
- Use `try-catch` for async operations; throw descriptive errors
- ORPC: Use `ORPCError` with proper codes (`NOT_FOUND`, `INPUT_VALIDATION_FAILED`)
- Never use empty catch blocks
## Database (Drizzle ORM v1 beta + postgres-js)
- **ORM**: Drizzle ORM `1.0.0-beta` (RQBv2)
- **Driver**: `drizzle-orm/postgres-js` (NOT `bun-sql`)
- **Validation**: `drizzle-orm/zod` (built-in, NOT separate `drizzle-zod` package)
- **Relations**: Defined via `defineRelations()` in `src/server/db/relations.ts` (contains schema info, so `drizzle()` only needs `{ relations }`)
- **Query style**: RQBv2 object syntax (`orderBy: { createdAt: 'desc' }`, `where: { id: 1 }`)
```typescript
export const myTable = pgTable('my_table', {
id: uuid().primaryKey().default(sql`uuidv7()`),
name: text().notNull(),
createdAt: timestamp({ withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp({ withTimezone: true }).notNull().defaultNow().$onUpdateFn(() => new Date()),
})
```
## Environment Variables
- Use `@t3-oss/env-core` with Zod validation in `src/env.ts`
- Server vars: no prefix | Client vars: `VITE_` prefix required
- Never commit `.env` files
## Dependency Management
- All versions centralized in root `package.json` `catalog` field
- Workspace packages use `"catalog:"` — never hardcode versions
- Internal packages use `"workspace:*"` references
## Development Principles
> **These principles apply to ALL code changes. Agents MUST follow them on every task.**
1. **No backward compatibility** — This project is in rapid iteration. Always use the latest API and patterns. Never keep deprecated code paths or old API fallbacks "just in case".
2. **Always sync documentation** — When code changes, immediately update all related documentation (`AGENTS.md`, `README.md`, inline code examples). Code and docs must never drift apart. This includes updating code snippets in docs when imports, APIs, or patterns change.
3. **Forward-only migration** — When upgrading dependencies, fully adopt the new API. Don't mix old and new patterns in the same codebase.
## Critical Rules
**DO:**
- Run `bun run fix` before committing
- Use `@/*` path aliases (not relative imports)
- Include `createdAt`/`updatedAt` on all tables
- Use `catalog:` for dependency versions
- Update `AGENTS.md` and other docs whenever code patterns change
**DON'T:**
- Use `npm`, `npx`, `node`, `yarn`, `pnpm` — always use `bun` / `bunx`
- Edit `src/routeTree.gen.ts` (auto-generated)
- Use `as any`, `@ts-ignore`, `@ts-expect-error`
- Commit `.env` files
- Use empty catch blocks `catch(e) {}`
- Hardcode dependency versions in workspace packages
- Leave docs out of sync with code changes
## Git Workflow
1. Make changes following style guide
2. `bun run fix` - auto-format and lint
3. `bun run typecheck` - verify types
4. `bun run dev` - test locally
5. Commit with descriptive message
## Directory Structure
## Layout
```
.
├── apps/
│ ├── server/ # TanStack Start fullstack app
│ ├── src/
├── client/ # ORPC client + TanStack Query utils
│ │ │ ├── components/
├── routes/ # File-based routing
│ │ └── server/ # API layer + database
│ │ │ ├── api/ # ORPC contracts, routers, middlewares
│ │ │ └── db/ # Drizzle schema
│ │ └── AGENTS.md
│ └── desktop/ # Electron desktop shell
│ ├── src/
│ │ ├── main/
│ │ │ └── index.ts # Main process entry
│ │ └── preload/
│ │ └── index.ts # Preload script
│ ├── electron.vite.config.ts
│ ├── electron-builder.yml # Packaging config
│ └── AGENTS.md
├── packages/
│ └── tsconfig/ # Shared TS configs
├── biome.json # Linting/formatting config
├── turbo.json # Turbo task orchestration
└── package.json # Workspace root + dependency catalog
src/
├── routes/
│ ├── index.tsx # SoH dashboard
│ ├── batteries.tsx # battery monitor page
└── api/ # ORPC handlers
├── server/
├── api/ # contracts / routers / interceptors
└── battery/mysql.ts
├── domain/battery.ts
├── client/orpc.ts
└── styles.css
```
## See Also
## ORPC
- `apps/server/AGENTS.md` - Detailed TanStack Start / ORPC patterns
- `apps/desktop/AGENTS.md` - Electron desktop development guide
- Contracts live in `src/server/api/contracts/`.
- Routers live in `src/server/api/routers/`.
- Use `os` from `@/server/api/server`.
- Current business API:
- `battery.dashboard`
- `battery.batteries`
## CLI And Deploy
- `src/bin.ts` must keep static imports minimal. Nitro's bun preset starts the server as a side effect when `.output/server/index.mjs` is imported.
- `serve` is lazy-loaded via citty.
- `bun run compile` produces `out/server-<target>`.
- Runtime artifact is a single binary plus `DATABASE_URL` configuration.
## Code Style
- 2-space indentation, LF, single quotes, semicolons as-needed, 120-column line width.
- Route components use `function Foo()` declarations below route config.
- No `console.*` in business code; use `getLogger([...])` from `@/server/logger` if logging is needed.
- No `as any`, `@ts-ignore`, or `@ts-expect-error`.
- Do not edit `src/routeTree.gen.ts` manually.
+21
View File
@@ -0,0 +1,21 @@
FROM oven/bun:1.3.13 AS build
WORKDIR /app
COPY package.json bun.lock ./
RUN bun install --frozen-lockfile
COPY . .
RUN bun run build \
&& bun run compile \
&& mv out/server-* out/server
FROM gcr.io/distroless/cc-debian13:nonroot
WORKDIR /app
COPY --from=build --chown=nonroot:nonroot /app/out/server ./server
ENV HOST=0.0.0.0
EXPOSE 3000
CMD ["./server"]
+108
View File
@@ -0,0 +1,108 @@
# battery-soh
一个基于 **Bun + TanStack Start + ORPC** 的电池健康展示系统。应用会被打包成单个二进制文件,前端页面、SSR 服务和 ORPC API 一起发布;业务数据只读接入甲方现有 MySQL 表 `ls_battery_info`,本项目不写入、不迁移、不修改甲方数据库。
## 数据源
甲方提供的只读表结构:
| 字段名 | 数据类型 | 说明 |
| --- | --- | --- |
| `id` | `int(11)` 自增 | 主键 ID |
| `user_id` | `int(11)` | 用户 ID |
| `mac` | `varchar(50)` | 设备 MAC |
| `dev_model` | `varchar(20)` | 设备型号 |
| `dev_name` | `varchar(50)` | 设备名称 |
| `is_low_power` | `varchar(10)` | 是否低电量:`true` / `false` |
| `power_status` | `tinyint(4)` | `0` 未充电,`1` 正在充电,`2` 充电完成 |
| `power` | `tinyint(4)` | 当前电量 `0~100` |
| `create_time` | `datetime` | 创建时间 |
| `remark` | `varchar(500)` | 备注,可空 |
环境变量:
```bash
DATABASE_URL=mysql://user:password@host:3306/database
```
## 快速开始
```bash
cp .env.example .env
bun install
bun run dev
```
如果甲方暂时没有提供数据库连接,可以用 Docker Compose 启动本地 MySQL 并填充示例数据:
```bash
docker compose up --build
```
Compose 会启动三个服务:
- `db`:本地 MySQL 8.4
- `seed`:执行 `bun run seed`,用 Drizzle MySQL schema + `drizzle-seed` 重置本地 `ls_battery_info` 并写入示例数据
- `app`:使用同一个 `DATABASE_URL` 启动单二进制应用
也可以手动 seed 本地库:
```bash
DATABASE_URL=mysql://battery:battery@localhost:3306/battery_soh bun run seed
```
`seed` 是本地开发/验收脚本,会建表并重置示例数据;应用运行时仍然只执行 `SELECT`,不会写入数据库。
打开浏览器:
- `http://localhost:3000/`SoH 预测与风险洞察看板
- `http://localhost:3000/batteries`:设备电池实时状态
- `http://localhost:3000/api/docs`Scalar 渲染的 ORPC OpenAPI 文档
## 架构
```
src/
├── routes/ # TanStack Start 文件路由:页面 + API 端点
├── server/
│ ├── api/ # ORPC contract / router
│ └── battery/mysql.ts # 甲方 MySQL 只读查询
├── domain/battery.ts # 电池领域类型、归一化、展示聚合
├── client/orpc.ts # isomorphic ORPC client
└── styles.css # Tailwind v4 entry
```
接口保持模板里的 ORPC 模式:
- `battery.dashboard`:读取每个 `mac` 的最新记录并生成看板聚合数据
- `battery.batteries`:无 `mac` 时返回每台设备最新记录;带 `mac` 时返回该设备历史记录,按 `create_time desc` 限制 500 条
所有业务查询都是 `SELECT`,没有 mutation,也没有 mock/fallback 数据。
## 部署
```bash
bun run build
bun run compile
./out/server-<target>
```
Docker 镜像会在构建阶段产出单个 `./server` 二进制,运行阶段只需要配置 `DATABASE_URL`
## 脚本
| 命令 | 作用 |
| --- | --- |
| `bun run dev` | Vite 开发服务器 |
| `bun run build` | 构建到 `.output/` |
| `bun run compile` | 生成单二进制 `out/server-<target>` |
| `bun run seed` | 为本地 MySQL 创建甲方表并填充示例数据 |
| `bun run typecheck` | TypeScript 类型检查 |
| `bun run test` | 运行所有 `*.test.ts` |
| `bun run fix` | Biome 格式化 + lint + 整理 imports |
## 验证
```bash
bun run fix && bun run typecheck && bun run test && bun run build
```
-3
View File
@@ -1,3 +0,0 @@
# electron-vite build output
out/
dist/
-95
View File
@@ -1,95 +0,0 @@
# AGENTS.md - Desktop App Guidelines
Thin Electron shell hosting the fullstack server app.
## Tech Stack
> **⚠️ This project uses Bun as the package manager. Runtime is Electron (Node.js). Always use `bun run <script>` (not `bun <script>`) to avoid conflicts with Bun built-in subcommands. Never use `npm`, `npx`, `yarn`, or `pnpm`.**
- **Type**: Electron desktop shell
- **Design**: Server-driven desktop (thin native window hosting web app)
- **Runtime**: Electron (Main/Renderer) + Sidecar server binary (Bun-compiled)
- **Build Tool**: electron-vite (Vite-based, handles main + preload builds)
- **Packager**: electron-builder (installers, signing, auto-update)
- **Orchestration**: Turborepo
## Architecture
- **Server-driven design**: The desktop app is a "thin" native shell. It does not contain UI or business logic; it opens a BrowserWindow pointing to the `apps/server` TanStack Start application.
- **Dev mode**: Opens a BrowserWindow pointing to `localhost:3000`. Requires `apps/server` to be running separately (Turbo handles this).
- **Production mode**: Spawns a compiled server binary (from `resources/`) as a sidecar process, waits for readiness, then loads its URL.
## Commands
```bash
bun run dev # electron-vite dev (requires server dev running)
bun run build # electron-vite build (main + preload)
bun run dist # Build + package for current platform
bun run dist:linux # Build + package for Linux (x64 + arm64)
bun run dist:linux:x64 # Build + package for Linux x64
bun run dist:linux:arm64 # Build + package for Linux arm64
bun run dist:mac # Build + package for macOS (arm64 + x64)
bun run dist:mac:arm64 # Build + package for macOS arm64
bun run dist:mac:x64 # Build + package for macOS x64
bun run dist:win # Build + package for Windows x64
bun run fix # Biome auto-fix
bun run typecheck # TypeScript check
```
## Directory Structure
```
.
├── src/
│ ├── main/
│ │ └── index.ts # Main process (server lifecycle + BrowserWindow)
│ └── preload/
│ └── index.ts # Preload script (security isolation)
├── resources/ # Sidecar binaries (gitignored, copied from server build)
├── out/ # electron-vite build output (gitignored)
├── electron.vite.config.ts
├── electron-builder.yml # Packaging configuration
├── package.json
├── turbo.json
└── AGENTS.md
```
## Development Workflow
1. **Start server**: `bun run dev` in `apps/server` (or use root `bun run dev` via Turbo).
2. **Start desktop**: `bun run dev` in `apps/desktop`.
3. **Connection**: Main process polls `localhost:3000` until responsive, then opens BrowserWindow.
## Production Build Workflow
From monorepo root, run `bun run dist` to execute the full pipeline automatically (via Turbo task dependencies):
1. **Build server**: `apps/server``vite build``.output/`
2. **Compile server**: `apps/server``bun compile.ts --target ...``out/server-{os}-{arch}`
3. **Package desktop**: `apps/desktop``electron-vite build` + `electron-builder` → distributable
The `electron-builder.yml` `extraResources` config reads binaries directly from `../server/out/`, no manual copy needed.
To build for a specific platform explicitly, use `bun run dist:linux` / `bun run dist:mac` / `bun run dist:win` in `apps/desktop`.
For single-arch output, use `bun run dist:linux:x64`, `bun run dist:linux:arm64`, `bun run dist:mac:x64`, or `bun run dist:mac:arm64`.
## Development Principles
> **These principles apply to ALL code changes. Agents MUST follow them on every task.**
1. **No backward compatibility** — This project is in rapid iteration. Always use the latest API and patterns. Never keep deprecated code paths or old API fallbacks.
2. **Always sync documentation** — When code changes, immediately update all related documentation (`AGENTS.md`, `README.md`, inline code examples). Code and docs must never drift apart.
3. **Forward-only migration** — When upgrading dependencies, fully adopt the new API. Don't mix old and new patterns.
## Critical Rules
**DO:**
- Use arrow functions for all utility functions.
- Keep the desktop app as a thin shell — no UI or business logic.
- Use `catalog:` for all dependency versions in `package.json`.
**DON'T:**
- Use `npm`, `npx`, `yarn`, or `pnpm`. Use `bun` for package management.
- Include UI components or business logic in the desktop app.
- Use `as any` or `@ts-ignore`.
- Leave docs out of sync with code changes.
-9
View File
@@ -1,9 +0,0 @@
{
"$schema": "../../node_modules/@biomejs/biome/configuration_schema.json",
"extends": "//",
"css": {
"parser": {
"tailwindDirectives": true
}
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 83 KiB

-48
View File
@@ -1,48 +0,0 @@
# yaml-language-server: $schema=https://raw.githubusercontent.com/electron-userland/electron-builder/refs/heads/master/packages/app-builder-lib/scheme.json
appId: com.furtherverse.desktop
productName: Furtherverse
executableName: furtherverse
npmRebuild: false
asarUnpack:
- resources/**
files:
- "!**/.vscode/*"
- "!src/*"
- "!electron.vite.config.{js,ts,mjs,cjs}"
- "!{.env,.env.*,bun.lock}"
- "!{tsconfig.json,tsconfig.node.json}"
- "!{AGENTS.md,README.md,CHANGELOG.md}"
# macOS
mac:
target:
- dmg
category: public.app-category.productivity
extraResources:
- from: ../server/out/server-darwin-${arch}
to: server
dmg:
artifactName: ${productName}-${version}-${os}-${arch}.${ext}
# Windows
win:
target:
- portable
extraResources:
- from: ../server/out/server-windows-${arch}.exe
to: server.exe
portable:
artifactName: ${productName}-${version}-${os}-${arch}-Portable.${ext}
# Linux
linux:
target:
- AppImage
category: Utility
extraResources:
- from: ../server/out/server-linux-${arch}
to: server
appImage:
artifactName: ${productName}-${version}-${os}-${arch}.${ext}
-11
View File
@@ -1,11 +0,0 @@
import tailwindcss from '@tailwindcss/vite'
import react from '@vitejs/plugin-react'
import { defineConfig } from 'electron-vite'
export default defineConfig({
main: {},
preload: {},
renderer: {
plugins: [react(), tailwindcss()],
},
})
-37
View File
@@ -1,37 +0,0 @@
{
"name": "@furtherverse/desktop",
"version": "1.0.0",
"private": true,
"main": "out/main/index.js",
"scripts": {
"build": "electron-vite build",
"dev": "electron-vite dev --watch",
"dist": "electron-builder",
"dist:linux": "bun run dist:linux:x64 && bun run dist:linux:arm64",
"dist:linux:arm64": "electron-builder --linux --arm64",
"dist:linux:x64": "electron-builder --linux --x64",
"dist:mac": "bun run dist:mac:arm64 && bun run dist:mac:x64",
"dist:mac:arm64": "electron-builder --mac --arm64",
"dist:mac:x64": "electron-builder --mac --x64",
"dist:win": "electron-builder --win --x64",
"fix": "biome check --write",
"typecheck": "tsc -b"
},
"dependencies": {
"motion": "catalog:",
"react": "catalog:",
"react-dom": "catalog:",
"tree-kill": "catalog:"
},
"devDependencies": {
"@furtherverse/tsconfig": "workspace:*",
"@tailwindcss/vite": "catalog:",
"@types/node": "catalog:",
"@vitejs/plugin-react": "catalog:",
"electron": "catalog:",
"electron-builder": "catalog:",
"electron-vite": "catalog:",
"tailwindcss": "catalog:",
"vite": "catalog:"
}
}
View File
-198
View File
@@ -1,198 +0,0 @@
import { join } from 'node:path'
import { app, BrowserWindow, dialog, session, shell } from 'electron'
import { createSidecarRuntime } from './sidecar'
const DEV_SERVER_URL = 'http://localhost:3000'
const SAFE_EXTERNAL_PROTOCOLS = new Set(['https:', 'http:', 'mailto:'])
let mainWindow: BrowserWindow | null = null
let windowCreationPromise: Promise<void> | null = null
let isQuitting = false
const showErrorAndQuit = (title: string, detail: string) => {
if (isQuitting) {
return
}
dialog.showErrorBox(title, detail)
app.quit()
}
const sidecar = createSidecarRuntime({
devServerUrl: DEV_SERVER_URL,
isPackaged: app.isPackaged,
resourcesPath: process.resourcesPath,
isQuitting: () => isQuitting,
onUnexpectedStop: (detail) => {
showErrorAndQuit('Service Stopped', detail)
},
})
const toErrorMessage = (error: unknown): string => (error instanceof Error ? error.message : String(error))
const canOpenExternally = (url: string): boolean => {
try {
const parsed = new URL(url)
return SAFE_EXTERNAL_PROTOCOLS.has(parsed.protocol)
} catch {
return false
}
}
const loadSplash = async (windowRef: BrowserWindow) => {
if (process.env.ELECTRON_RENDERER_URL) {
await windowRef.loadURL(process.env.ELECTRON_RENDERER_URL)
return
}
await windowRef.loadFile(join(__dirname, '../renderer/index.html'))
}
const createWindow = async () => {
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.focus()
return
}
const windowRef = new BrowserWindow({
width: 1200,
height: 800,
show: false,
webPreferences: {
preload: join(__dirname, '../preload/index.js'),
sandbox: true,
contextIsolation: true,
nodeIntegration: false,
},
})
mainWindow = windowRef
windowRef.webContents.setWindowOpenHandler(({ url }) => {
if (!canOpenExternally(url)) {
if (!app.isPackaged) {
console.warn(`Blocked external URL: ${url}`)
}
return { action: 'deny' }
}
void shell.openExternal(url)
return { action: 'deny' }
})
windowRef.webContents.on('will-navigate', (event, url) => {
const allowed = [DEV_SERVER_URL, sidecar.lastResolvedUrl].filter((v): v is string => v != null)
const isAllowed = allowed.some((origin) => url.startsWith(origin))
if (!isAllowed) {
event.preventDefault()
if (canOpenExternally(url)) {
void shell.openExternal(url)
} else if (!app.isPackaged) {
console.warn(`Blocked navigation to: ${url}`)
}
}
})
windowRef.on('closed', () => {
if (mainWindow === windowRef) {
mainWindow = null
}
})
try {
await loadSplash(windowRef)
} catch (error) {
if (mainWindow === windowRef) {
mainWindow = null
}
if (!windowRef.isDestroyed()) {
windowRef.destroy()
}
throw error
}
if (!windowRef.isDestroyed()) {
windowRef.show()
}
const targetUrl = await sidecar.resolveUrl()
if (isQuitting || windowRef.isDestroyed()) {
return
}
try {
await windowRef.loadURL(targetUrl)
} catch (error) {
if (mainWindow === windowRef) {
mainWindow = null
}
if (!windowRef.isDestroyed()) {
windowRef.destroy()
}
throw error
}
}
const ensureWindow = async () => {
if (windowCreationPromise) {
return windowCreationPromise
}
windowCreationPromise = createWindow().finally(() => {
windowCreationPromise = null
})
return windowCreationPromise
}
const beginQuit = () => {
isQuitting = true
sidecar.stop()
}
const handleWindowCreationError = (error: unknown, context: string) => {
console.error(`${context}:`, error)
showErrorAndQuit(
"App Couldn't Start",
app.isPackaged
? 'A required component failed to start. Please reinstall the app.'
: `${context}: ${toErrorMessage(error)}`,
)
}
app
.whenReady()
.then(() => {
session.defaultSession.setPermissionRequestHandler((_webContents, _permission, callback) => {
callback(false)
})
return ensureWindow()
})
.catch((error) => {
handleWindowCreationError(error, 'Failed to create window')
})
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
if (isQuitting || BrowserWindow.getAllWindows().length > 0) {
return
}
ensureWindow().catch((error) => {
handleWindowCreationError(error, 'Failed to re-create window')
})
})
app.on('before-quit', beginQuit)
-256
View File
@@ -1,256 +0,0 @@
import { type ChildProcess, spawn } from 'node:child_process'
import { existsSync } from 'node:fs'
import { createServer } from 'node:net'
import { join } from 'node:path'
import killProcessTree from 'tree-kill'
const SERVER_HOST = '127.0.0.1'
const SERVER_READY_TIMEOUT_MS = 10_000
const SERVER_REQUEST_TIMEOUT_MS = 1_500
const SERVER_POLL_INTERVAL_MS = 250
const SERVER_PROBE_PATHS = ['/api/health', '/']
type SidecarState = {
process: ChildProcess | null
startup: Promise<string> | null
url: string | null
}
type SidecarRuntimeOptions = {
devServerUrl: string
isPackaged: boolean
resourcesPath: string
isQuitting: () => boolean
onUnexpectedStop: (detail: string) => void
}
type SidecarRuntime = {
resolveUrl: () => Promise<string>
stop: () => void
lastResolvedUrl: string | null
}
const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms))
const isProcessAlive = (processToCheck: ChildProcess | null): processToCheck is ChildProcess => {
if (!processToCheck || !processToCheck.pid) {
return false
}
return processToCheck.exitCode === null && !processToCheck.killed
}
const getAvailablePort = (): Promise<number> =>
new Promise((resolve, reject) => {
const server = createServer()
server.listen(0, () => {
const addr = server.address()
if (!addr || typeof addr === 'string') {
server.close()
reject(new Error('Failed to resolve port'))
return
}
server.close(() => resolve(addr.port))
})
server.on('error', reject)
})
const isServerReady = async (url: string): Promise<boolean> => {
for (const probePath of SERVER_PROBE_PATHS) {
try {
const probeUrl = new URL(probePath, `${url}/`)
const response = await fetch(probeUrl, {
method: 'GET',
cache: 'no-store',
signal: AbortSignal.timeout(SERVER_REQUEST_TIMEOUT_MS),
})
if (response.status < 500) {
if (probePath === '/api/health' && response.status === 404) {
continue
}
return true
}
} catch {
// Expected: probe request fails while server is still starting up
}
}
return false
}
const waitForServer = async (url: string, isQuitting: () => boolean, processRef?: ChildProcess): Promise<boolean> => {
const start = Date.now()
while (Date.now() - start < SERVER_READY_TIMEOUT_MS && !isQuitting()) {
if (processRef && processRef.exitCode !== null) {
return false
}
if (await isServerReady(url)) {
return true
}
await sleep(SERVER_POLL_INTERVAL_MS)
}
return false
}
const resolveBinaryPath = (resourcesPath: string): string => {
const binaryName = process.platform === 'win32' ? 'server.exe' : 'server'
return join(resourcesPath, binaryName)
}
const formatUnexpectedStopMessage = (
isPackaged: boolean,
code: number | null,
signal: NodeJS.Signals | null,
): string => {
if (isPackaged) {
return 'The background service stopped unexpectedly. Please restart the app.'
}
return `Server process exited unexpectedly (code ${code ?? 'unknown'}, signal ${signal ?? 'none'}).`
}
export const createSidecarRuntime = (options: SidecarRuntimeOptions): SidecarRuntime => {
const state: SidecarState = {
process: null,
startup: null,
url: null,
}
const resetState = (processRef?: ChildProcess) => {
if (processRef && state.process !== processRef) {
return
}
state.process = null
state.url = null
}
const stop = () => {
const runningServer = state.process
resetState()
if (!runningServer?.pid || runningServer.exitCode !== null) {
return
}
killProcessTree(runningServer.pid, 'SIGTERM', (error?: Error) => {
if (error) {
console.error('Failed to stop server process:', error)
}
})
}
const attachLifecycleHandlers = (processRef: ChildProcess) => {
processRef.on('error', (error) => {
if (state.process !== processRef) {
return
}
const hadReadyServer = state.url !== null
resetState(processRef)
if (!options.isQuitting() && hadReadyServer) {
options.onUnexpectedStop('The background service crashed unexpectedly. Please restart the app.')
return
}
console.error('Failed to start server process:', error)
})
processRef.on('exit', (code, signal) => {
if (state.process !== processRef) {
return
}
const hadReadyServer = state.url !== null
resetState(processRef)
if (!options.isQuitting() && hadReadyServer) {
options.onUnexpectedStop(formatUnexpectedStopMessage(options.isPackaged, code, signal))
}
})
}
const startPackagedServer = async (): Promise<string> => {
if (state.url && isProcessAlive(state.process)) {
return state.url
}
if (state.startup) {
return state.startup
}
state.startup = (async () => {
const binaryPath = resolveBinaryPath(options.resourcesPath)
if (!existsSync(binaryPath)) {
throw new Error(`Sidecar server binary is missing: ${binaryPath}`)
}
if (options.isQuitting()) {
throw new Error('Application is shutting down.')
}
const port = await getAvailablePort()
const nextServerUrl = `http://${SERVER_HOST}:${port}`
const processRef = spawn(binaryPath, [], {
env: {
...process.env,
HOST: SERVER_HOST,
PORT: String(port),
},
stdio: 'ignore',
windowsHide: true,
})
processRef.unref()
state.process = processRef
attachLifecycleHandlers(processRef)
const ready = await waitForServer(nextServerUrl, options.isQuitting, processRef)
if (ready && isProcessAlive(processRef)) {
state.url = nextServerUrl
return nextServerUrl
}
const failureReason =
processRef.exitCode !== null
? `The service exited early (code ${processRef.exitCode}).`
: `The service did not respond at ${nextServerUrl} within 10 seconds.`
stop()
throw new Error(failureReason)
})().finally(() => {
state.startup = null
})
return state.startup
}
const resolveUrl = async (): Promise<string> => {
if (options.isPackaged) {
return startPackagedServer()
}
const ready = await waitForServer(options.devServerUrl, options.isQuitting)
if (!ready) {
throw new Error('Dev server not responding. Run `bun dev` in apps/server first.')
}
state.url = options.devServerUrl
return options.devServerUrl
}
return {
resolveUrl,
stop,
get lastResolvedUrl() {
return state.url
},
}
}
-1
View File
@@ -1 +0,0 @@
export {}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 83 KiB

@@ -1,33 +0,0 @@
import { motion } from 'motion/react'
import logoImage from '../assets/logo.png'
export const SplashApp = () => {
return (
<main className="m-0 flex h-screen w-screen cursor-default select-none items-center justify-center overflow-hidden bg-white font-sans antialiased">
<motion.section
animate={{ opacity: 1, y: 0 }}
className="flex flex-col items-center gap-8"
initial={{ opacity: 0, y: 4 }}
transition={{
duration: 1,
ease: [0.16, 1, 0.3, 1],
}}
>
<img alt="Logo" className="h-20 w-auto object-contain" draggable={false} src={logoImage} />
<div className="relative h-[4px] w-36 overflow-hidden rounded-full bg-zinc-100">
<motion.div
animate={{ x: '100%' }}
className="h-full w-full bg-zinc-800"
initial={{ x: '-100%' }}
transition={{
duration: 2,
ease: [0.4, 0, 0.2, 1],
repeat: Infinity,
}}
/>
</div>
</motion.section>
</main>
)
}
-12
View File
@@ -1,12 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Furtherverse</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="./main.tsx"></script>
</body>
</html>
-11
View File
@@ -1,11 +0,0 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { SplashApp } from './components/SplashApp'
import './styles.css'
// biome-ignore lint/style/noNonNullAssertion: 一定存在
createRoot(document.getElementById('root')!).render(
<StrictMode>
<SplashApp />
</StrictMode>,
)
-8
View File
@@ -1,8 +0,0 @@
{
"extends": "@furtherverse/tsconfig/react.json",
"compilerOptions": {
"composite": true,
"types": ["vite/client"]
},
"include": ["src/renderer/**/*"]
}
-11
View File
@@ -1,11 +0,0 @@
{
"files": [],
"references": [
{
"path": "./tsconfig.app.json"
},
{
"path": "./tsconfig.node.json"
}
]
}
-8
View File
@@ -1,8 +0,0 @@
{
"extends": "@furtherverse/tsconfig/base.json",
"compilerOptions": {
"composite": true,
"types": ["node"]
},
"include": ["src/main/**/*", "src/preload/**/*", "electron.vite.config.ts"]
}
-41
View File
@@ -1,41 +0,0 @@
{
"$schema": "../../node_modules/turbo/schema.json",
"extends": ["//"],
"tasks": {
"build": {
"outputs": ["out/**"]
},
"dist": {
"dependsOn": ["build", "@furtherverse/server#compile"],
"outputs": ["dist/**"]
},
"dist:linux": {
"dependsOn": ["build", "@furtherverse/server#compile:linux:arm64", "@furtherverse/server#compile:linux:x64"],
"outputs": ["dist/**"]
},
"dist:linux:arm64": {
"dependsOn": ["build", "@furtherverse/server#compile:linux:arm64"],
"outputs": ["dist/**"]
},
"dist:linux:x64": {
"dependsOn": ["build", "@furtherverse/server#compile:linux:x64"],
"outputs": ["dist/**"]
},
"dist:mac": {
"dependsOn": ["build", "@furtherverse/server#compile:darwin:arm64", "@furtherverse/server#compile:darwin:x64"],
"outputs": ["dist/**"]
},
"dist:mac:arm64": {
"dependsOn": ["build", "@furtherverse/server#compile:darwin:arm64"],
"outputs": ["dist/**"]
},
"dist:mac:x64": {
"dependsOn": ["build", "@furtherverse/server#compile:darwin:x64"],
"outputs": ["dist/**"]
},
"dist:win": {
"dependsOn": ["build", "@furtherverse/server#compile:windows:x64"],
"outputs": ["dist/**"]
}
}
}
-1
View File
@@ -1 +0,0 @@
DATABASE_URL=postgres://postgres:postgres@localhost:5432/postgres
-278
View File
@@ -1,278 +0,0 @@
# AGENTS.md - Server App Guidelines
TanStack Start fullstack web app with ORPC (contract-first RPC).
## Tech Stack
> **⚠️ This project uses Bun — NOT Node.js / npm. All commands use `bun`. Always use `bun run <script>` (not `bun <script>`) to avoid conflicts with Bun built-in subcommands. Never use `npm`, `npx`, or `node`.**
- **Framework**: TanStack Start (React 19 SSR, file-based routing)
- **Runtime**: Bun — **NOT Node.js**
- **Package Manager**: Bun — **NOT npm / yarn / pnpm**
- **Language**: TypeScript (strict mode)
- **Styling**: Tailwind CSS v4
- **Database**: PostgreSQL + Drizzle ORM v1 beta (`drizzle-orm/postgres-js`, RQBv2)
- **State**: TanStack Query v5
- **RPC**: ORPC (contract-first, type-safe)
- **Build**: Vite + Nitro
## Commands
```bash
# Development
bun run dev # Vite dev server (localhost:3000)
bun run db:studio # Drizzle Studio GUI
# Build
bun run build # Production build → .output/
bun run compile # Compile to standalone binary (current platform, depends on build)
bun run compile:darwin # Compile for macOS (arm64 + x64)
bun run compile:darwin:arm64 # Compile for macOS arm64
bun run compile:darwin:x64 # Compile for macOS x64
bun run compile:linux # Compile for Linux (x64 + arm64)
bun run compile:linux:arm64 # Compile for Linux arm64
bun run compile:linux:x64 # Compile for Linux x64
bun run compile:windows # Compile for Windows (default: x64)
bun run compile:windows:x64 # Compile for Windows x64
# Code Quality
bun run fix # Biome auto-fix
bun run typecheck # TypeScript check
# Database
bun run db:generate # Generate migrations from schema
bun run db:migrate # Run migrations
bun run db:push # Push schema directly (dev only)
# Testing (not yet configured)
bun test path/to/test.ts # Run single test
bun test -t "pattern" # Run tests matching pattern
```
## Directory Structure
```
src/
├── client/ # Client-side code
│ └── orpc.ts # ORPC client + TanStack Query utils (single entry point)
├── components/ # React components
├── routes/ # TanStack Router file routes
│ ├── __root.tsx # Root layout
│ ├── index.tsx # Home page
│ └── api/
│ ├── $.ts # OpenAPI handler + Scalar docs
│ ├── health.ts # Health check endpoint
│ └── rpc.$.ts # ORPC RPC handler
├── server/ # Server-side code
│ ├── api/ # ORPC layer
│ │ ├── contracts/ # Input/output schemas (Zod)
│ │ ├── middlewares/ # Middleware (db provider, auth)
│ │ ├── routers/ # Handler implementations
│ │ ├── interceptors.ts # Shared error interceptors
│ │ ├── context.ts # Request context
│ │ ├── server.ts # ORPC server instance
│ │ └── types.ts # Type exports
│ └── db/
│ ├── schema/ # Drizzle table definitions
│ ├── fields.ts # Shared field builders (id, createdAt, updatedAt)
│ ├── relations.ts # Drizzle relations (defineRelations, RQBv2)
│ └── index.ts # Database instance (postgres-js driver)
├── env.ts # Environment variable validation
├── router.tsx # Router configuration
├── routeTree.gen.ts # Auto-generated (DO NOT EDIT)
└── styles.css # Tailwind entry
```
## ORPC Pattern
### 1. Define Contract (`src/server/api/contracts/feature.contract.ts`)
```typescript
import { oc } from '@orpc/contract'
import { createSelectSchema } from 'drizzle-orm/zod'
import { z } from 'zod'
import { featureTable } from '@/server/db/schema'
const selectSchema = createSelectSchema(featureTable)
export const list = oc.input(z.void()).output(z.array(selectSchema))
export const create = oc.input(insertSchema).output(selectSchema)
```
### 2. Implement Router (`src/server/api/routers/feature.router.ts`)
```typescript
import { ORPCError } from '@orpc/server'
import { db } from '../middlewares'
import { os } from '../server'
export const list = os.feature.list.use(db).handler(async ({ context }) => {
return await context.db.query.featureTable.findMany({
orderBy: { createdAt: 'desc' },
})
})
```
### 3. Register in Index Files
```typescript
// src/server/api/contracts/index.ts
import * as feature from './feature.contract'
export const contract = { feature }
// src/server/api/routers/index.ts
import * as feature from './feature.router'
export const router = os.router({ feature })
```
### 4. Use in Components
```typescript
import { useSuspenseQuery, useMutation } from '@tanstack/react-query'
import { orpc } from '@/client/orpc'
const { data } = useSuspenseQuery(orpc.feature.list.queryOptions())
const mutation = useMutation(orpc.feature.create.mutationOptions())
```
## Database (Drizzle ORM v1 beta)
- **Driver**: `drizzle-orm/postgres-js` (NOT `bun-sql`)
- **Validation**: `drizzle-orm/zod` (built-in, NOT separate `drizzle-zod` package)
- **Relations**: Defined via `defineRelations()` in `src/server/db/relations.ts`
- **Query**: RQBv2 — use `db.query.tableName.findMany()` with object-style `orderBy` and `where`
### Schema Definition
```typescript
import { pgTable, text, timestamp, uuid } from 'drizzle-orm/pg-core'
import { sql } from 'drizzle-orm'
export const myTable = pgTable('my_table', {
id: uuid().primaryKey().default(sql`uuidv7()`),
name: text().notNull(),
createdAt: timestamp({ withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp({ withTimezone: true }).notNull().defaultNow().$onUpdateFn(() => new Date()),
})
```
### Relations (RQBv2)
```typescript
// src/server/db/relations.ts
import { defineRelations } from 'drizzle-orm'
import * as schema from './schema'
export const relations = defineRelations(schema, (r) => ({
// Define relations here using r.one / r.many / r.through
}))
```
### DB Instance
```typescript
// src/server/db/index.ts
import { drizzle } from 'drizzle-orm/postgres-js'
import { relations } from '@/server/db/relations'
// In RQBv2, relations already contain schema info — no separate schema import needed
const db = drizzle({
connection: env.DATABASE_URL,
relations,
})
```
### RQBv2 Query Examples
```typescript
// Object-style orderBy (NOT callback style)
const todos = await db.query.todoTable.findMany({
orderBy: { createdAt: 'desc' },
})
// Object-style where
const todo = await db.query.todoTable.findFirst({
where: { id: someId },
})
```
## Code Style
### Formatting (Biome)
- **Indent**: 2 spaces
- **Quotes**: Single `'`
- **Semicolons**: Omit (ASI)
- **Arrow parens**: Always `(x) => x`
### Imports
Biome auto-organizes:
1. External packages
2. Internal `@/*` aliases
3. Type imports (`import type { ... }`)
```typescript
import { createFileRoute } from '@tanstack/react-router'
import { z } from 'zod'
import { db } from '@/server/db'
import type { ReactNode } from 'react'
```
### TypeScript
- `strict: true`
- `noUncheckedIndexedAccess: true` - array access returns `T | undefined`
- Use `@/*` path aliases (maps to `src/*`)
### Naming
| Type | Convention | Example |
|------|------------|---------|
| Files (utils) | kebab-case | `auth-utils.ts` |
| Files (components) | PascalCase | `UserProfile.tsx` |
| Components | PascalCase arrow | `const Button = () => {}` |
| Functions | camelCase | `getUserById` |
| Types | PascalCase | `UserProfile` |
### React
- Use arrow functions for components (Biome enforced)
- Use `useSuspenseQuery` for guaranteed data
## Environment Variables
```typescript
// src/env.ts - using @t3-oss/env-core
import { createEnv } from '@t3-oss/env-core'
import { z } from 'zod'
export const env = createEnv({
server: {
DATABASE_URL: z.string().url(),
},
clientPrefix: 'VITE_',
client: {
VITE_API_URL: z.string().optional(),
},
})
```
## Development Principles
> **These principles apply to ALL code changes. Agents MUST follow them on every task.**
1. **No backward compatibility** — This project is in rapid iteration. Always use the latest API and patterns. Never keep deprecated code paths or old API fallbacks.
2. **Always sync documentation** — When code changes, immediately update all related documentation (`AGENTS.md`, `README.md`, inline code examples). Code and docs must never drift apart.
3. **Forward-only migration** — When upgrading dependencies, fully adopt the new API. Don't mix old and new patterns.
## Critical Rules
**DO:**
- Run `bun run fix` before committing
- Use `@/*` path aliases
- Include `createdAt`/`updatedAt` on all tables
- Use `ORPCError` with proper codes
- Use `drizzle-orm/zod` (NOT `drizzle-zod`) for schema validation
- Use RQBv2 object syntax for `orderBy` and `where`
- Update `AGENTS.md` and other docs whenever code patterns change
**DON'T:**
- Use `npm`, `npx`, `node`, `yarn`, `pnpm` — always use `bun` / `bunx`
- Edit `src/routeTree.gen.ts` (auto-generated)
- Use `as any`, `@ts-ignore`, `@ts-expect-error`
- Commit `.env` files
- Use empty catch blocks
- Import from `drizzle-zod` (use `drizzle-orm/zod` instead)
- Use RQBv1 callback-style `orderBy` / old `relations()` API
- Use `drizzle-orm/bun-sql` driver (use `drizzle-orm/postgres-js`)
- Pass `schema` to `drizzle()` constructor (only `relations` is needed in RQBv2)
- Import `os` from `@orpc/server` in middleware — use `@/server/api/server` (the local typed instance)
- Leave docs out of sync with code changes
-12
View File
@@ -1,12 +0,0 @@
{
"$schema": "../../node_modules/@biomejs/biome/configuration_schema.json",
"extends": "//",
"files": {
"includes": ["**", "!**/routeTree.gen.ts"]
},
"css": {
"parser": {
"tailwindDirectives": true
}
}
}
-11
View File
@@ -1,11 +0,0 @@
import { defineConfig } from 'drizzle-kit'
import { env } from '@/env'
export default defineConfig({
out: './drizzle',
schema: './src/server/db/schema/index.ts',
dialect: 'postgresql',
dbCredentials: {
url: env.DATABASE_URL,
},
})
-58
View File
@@ -1,58 +0,0 @@
{
"name": "@furtherverse/server",
"version": "1.0.0",
"private": true,
"type": "module",
"scripts": {
"build": "bunx --bun vite build",
"compile": "bun compile.ts",
"compile:darwin": "bun run compile:darwin:arm64 && bun run compile:darwin:x64",
"compile:darwin:arm64": "bun compile.ts --target bun-darwin-arm64",
"compile:darwin:x64": "bun compile.ts --target bun-darwin-x64",
"compile:linux": "bun run compile:linux:x64 && bun run compile:linux:arm64",
"compile:linux:arm64": "bun compile.ts --target bun-linux-arm64",
"compile:linux:x64": "bun compile.ts --target bun-linux-x64",
"compile:windows": "bun run compile:windows:x64",
"compile:windows:x64": "bun compile.ts --target bun-windows-x64",
"db:generate": "drizzle-kit generate",
"db:migrate": "drizzle-kit migrate",
"db:push": "drizzle-kit push",
"db:studio": "drizzle-kit studio",
"dev": "bunx --bun vite dev",
"fix": "biome check --write",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@orpc/client": "catalog:",
"@orpc/contract": "catalog:",
"@orpc/openapi": "catalog:",
"@orpc/server": "catalog:",
"@orpc/tanstack-query": "catalog:",
"@orpc/zod": "catalog:",
"@t3-oss/env-core": "catalog:",
"@tanstack/react-query": "catalog:",
"@tanstack/react-router": "catalog:",
"@tanstack/react-router-ssr-query": "catalog:",
"@tanstack/react-start": "catalog:",
"drizzle-orm": "catalog:",
"postgres": "catalog:",
"react": "catalog:",
"react-dom": "catalog:",
"uuid": "catalog:",
"zod": "catalog:"
},
"devDependencies": {
"@furtherverse/tsconfig": "workspace:*",
"@tailwindcss/vite": "catalog:",
"@tanstack/devtools-vite": "catalog:",
"@tanstack/react-devtools": "catalog:",
"@tanstack/react-query-devtools": "catalog:",
"@tanstack/react-router-devtools": "catalog:",
"@types/bun": "catalog:",
"@vitejs/plugin-react": "catalog:",
"drizzle-kit": "catalog:",
"nitro": "catalog:",
"tailwindcss": "catalog:",
"vite": "catalog:"
}
}
-3
View File
@@ -1,3 +0,0 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:
-3
View File
@@ -1,3 +0,0 @@
export function ErrorComponent() {
return <div>An unhandled error happened!</div>
}
-3
View File
@@ -1,3 +0,0 @@
export function NotFoundComponent() {
return <div>404 - Not Found</div>
}
-14
View File
@@ -1,14 +0,0 @@
import { createEnv } from '@t3-oss/env-core'
import { z } from 'zod'
export const env = createEnv({
server: {
DATABASE_URL: z.url(),
},
clientPrefix: 'VITE_',
client: {
VITE_APP_TITLE: z.string().min(1).optional(),
},
runtimeEnv: process.env,
emptyStringAsUndefined: true,
})
-27
View File
@@ -1,27 +0,0 @@
import { createFileRoute } from '@tanstack/react-router'
import { name, version } from '@/../package.json'
const createHealthResponse = (): Response =>
Response.json(
{
status: 'ok',
service: name,
version,
timestamp: new Date().toISOString(),
},
{
status: 200,
headers: {
'cache-control': 'no-store',
},
},
)
export const Route = createFileRoute('/api/health')({
server: {
handlers: {
GET: async () => createHealthResponse(),
HEAD: async () => new Response(null, { status: 200 }),
},
},
})
-193
View File
@@ -1,193 +0,0 @@
import { useMutation, useSuspenseQuery } from '@tanstack/react-query'
import { createFileRoute } from '@tanstack/react-router'
import type { ChangeEventHandler, SubmitEventHandler } from 'react'
import { useState } from 'react'
import { orpc } from '@/client/orpc'
export const Route = createFileRoute('/')({
component: Todos,
loader: async ({ context }) => {
await context.queryClient.ensureQueryData(orpc.todo.list.queryOptions())
},
})
function Todos() {
const [newTodoTitle, setNewTodoTitle] = useState('')
const listQuery = useSuspenseQuery(orpc.todo.list.queryOptions())
const createMutation = useMutation(orpc.todo.create.mutationOptions())
const updateMutation = useMutation(orpc.todo.update.mutationOptions())
const deleteMutation = useMutation(orpc.todo.remove.mutationOptions())
const handleCreateTodo: SubmitEventHandler<HTMLFormElement> = (e) => {
e.preventDefault()
if (newTodoTitle.trim()) {
createMutation.mutate({ title: newTodoTitle.trim() })
setNewTodoTitle('')
}
}
const handleInputChange: ChangeEventHandler<HTMLInputElement> = (e) => {
setNewTodoTitle(e.target.value)
}
const handleToggleTodo = (id: string, currentCompleted: boolean) => {
updateMutation.mutate({
id,
data: { completed: !currentCompleted },
})
}
const handleDeleteTodo = (id: string) => {
deleteMutation.mutate({ id })
}
const todos = listQuery.data
const completedCount = todos.filter((todo) => todo.completed).length
const totalCount = todos.length
const progress = totalCount > 0 ? (completedCount / totalCount) * 100 : 0
return (
<div className="min-h-screen bg-slate-50 py-12 px-4 sm:px-6 font-sans">
<div className="max-w-2xl mx-auto space-y-8">
{/* Header */}
<div className="flex items-end justify-between">
<div>
<h1 className="text-3xl font-bold text-slate-900 tracking-tight"></h1>
<p className="text-slate-500 mt-1"></p>
</div>
<div className="text-right">
<div className="text-2xl font-semibold text-slate-900">
{completedCount}
<span className="text-slate-400 text-lg">/{totalCount}</span>
</div>
<div className="text-xs font-medium text-slate-400 uppercase tracking-wider"></div>
</div>
</div>
{/* Add Todo Form */}
<form onSubmit={handleCreateTodo} className="relative group z-10">
<div className="relative transform transition-all duration-200 focus-within:-translate-y-1">
<input
type="text"
value={newTodoTitle}
onChange={handleInputChange}
placeholder="添加新任务..."
className="w-full pl-6 pr-32 py-5 bg-white rounded-2xl shadow-[0_8px_30px_rgb(0,0,0,0.04)] border-0 ring-1 ring-slate-100 focus:ring-2 focus:ring-indigo-500/50 outline-none transition-all placeholder:text-slate-400 text-lg text-slate-700"
disabled={createMutation.isPending}
/>
<button
type="submit"
disabled={createMutation.isPending || !newTodoTitle.trim()}
className="absolute right-3 top-3 bottom-3 px-6 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl font-medium transition-all shadow-md shadow-indigo-200 disabled:opacity-50 disabled:shadow-none hover:shadow-lg hover:shadow-indigo-300 active:scale-95"
>
{createMutation.isPending ? '添加中' : '添加'}
</button>
</div>
</form>
{/* Progress Bar (Only visible when there are tasks) */}
{totalCount > 0 && (
<div className="h-1.5 w-full bg-slate-200 rounded-full overflow-hidden">
<div
className="h-full bg-indigo-500 transition-all duration-500 ease-out rounded-full"
style={{ width: `${progress}%` }}
/>
</div>
)}
{/* Todo List */}
<div className="space-y-3">
{todos.length === 0 ? (
<div className="py-20 text-center">
<div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-slate-100 mb-4">
<svg
className="w-8 h-8 text-slate-400"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
aria-hidden="true"
>
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
</svg>
</div>
<p className="text-slate-500 text-lg font-medium"></p>
<p className="text-slate-400 text-sm mt-1"></p>
</div>
) : (
todos.map((todo) => (
<div
key={todo.id}
className={`group relative flex items-center p-4 bg-white rounded-xl border border-slate-100 shadow-sm transition-all duration-200 hover:shadow-md hover:border-slate-200 ${
todo.completed ? 'bg-slate-50/50' : ''
}`}
>
<button
type="button"
onClick={() => handleToggleTodo(todo.id, todo.completed)}
className={`flex-shrink-0 w-6 h-6 rounded-full border-2 transition-all duration-200 flex items-center justify-center mr-4 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 ${
todo.completed
? 'bg-indigo-500 border-indigo-500'
: 'border-slate-300 hover:border-indigo-500 bg-white'
}`}
>
{todo.completed && (
<svg
className="w-3.5 h-3.5 text-white"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
strokeWidth={3}
aria-hidden="true"
>
<path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
</svg>
)}
</button>
<div className="flex-1 min-w-0">
<p
className={`text-lg transition-all duration-200 truncate ${
todo.completed
? 'text-slate-400 line-through decoration-slate-300 decoration-2'
: 'text-slate-700'
}`}
>
{todo.title}
</p>
</div>
<div className="flex items-center opacity-0 group-hover:opacity-100 transition-opacity duration-200 absolute right-4 pl-4 bg-gradient-to-l from-white via-white to-transparent sm:static sm:bg-none">
<span className="text-xs text-slate-400 mr-3 hidden sm:inline-block">
{new Date(todo.createdAt).toLocaleDateString('zh-CN')}
</span>
<button
type="button"
onClick={() => handleDeleteTodo(todo.id)}
className="p-2 text-slate-400 hover:text-red-500 hover:bg-red-50 rounded-lg transition-colors focus:outline-none"
title="删除"
>
<svg
className="w-5 h-5"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
strokeWidth={1.5}
aria-hidden="true"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
/>
</svg>
</button>
</div>
</div>
))
)}
</div>
</div>
</div>
)
}
-25
View File
@@ -1,25 +0,0 @@
import type { DB } from '@/server/db'
/**
* 基础 Context - 所有请求都包含的上下文
*/
export interface BaseContext {
headers: Headers
}
/**
* 数据库 Context - 通过 db middleware 扩展
*/
export interface DBContext extends BaseContext {
db: DB
}
/**
* 认证 Context - 通过 auth middleware 扩展(未来使用)
*
* @example
* export interface AuthContext extends DBContext {
* userId: string
* user: User
* }
*/
@@ -1,32 +0,0 @@
import { oc } from '@orpc/contract'
import { createInsertSchema, createSelectSchema, createUpdateSchema } from 'drizzle-orm/zod'
import { z } from 'zod'
import { generatedFieldKeys } from '@/server/db/fields'
import { todoTable } from '@/server/db/schema'
const selectSchema = createSelectSchema(todoTable)
const insertSchema = createInsertSchema(todoTable).omit(generatedFieldKeys)
const updateSchema = createUpdateSchema(todoTable).omit(generatedFieldKeys)
export const list = oc.input(z.void()).output(z.array(selectSchema))
export const create = oc.input(insertSchema).output(selectSchema)
export const update = oc
.input(
z.object({
id: z.uuid(),
data: updateSchema,
}),
)
.output(selectSchema)
export const remove = oc
.input(
z.object({
id: z.uuid(),
}),
)
.output(z.void())
@@ -1,11 +0,0 @@
import { os } from '@/server/api/server'
import { getDB } from '@/server/db'
export const db = os.middleware(async ({ context, next }) => {
return next({
context: {
...context,
db: getDB(),
},
})
})
@@ -1 +0,0 @@
export * from './db.middleware'
@@ -1,6 +0,0 @@
import { os } from '../server'
import * as todo from './todo.router'
export const router = os.router({
todo,
})
@@ -1,40 +0,0 @@
import { ORPCError } from '@orpc/server'
import { eq } from 'drizzle-orm'
import { todoTable } from '@/server/db/schema'
import { db } from '../middlewares'
import { os } from '../server'
export const list = os.todo.list.use(db).handler(async ({ context }) => {
const todos = await context.db.query.todoTable.findMany({
orderBy: { createdAt: 'desc' },
})
return todos
})
export const create = os.todo.create.use(db).handler(async ({ context, input }) => {
const [newTodo] = await context.db.insert(todoTable).values(input).returning()
if (!newTodo) {
throw new ORPCError('INTERNAL_SERVER_ERROR', { message: 'Failed to create todo' })
}
return newTodo
})
export const update = os.todo.update.use(db).handler(async ({ context, input }) => {
const [updatedTodo] = await context.db.update(todoTable).set(input.data).where(eq(todoTable.id, input.id)).returning()
if (!updatedTodo) {
throw new ORPCError('NOT_FOUND')
}
return updatedTodo
})
export const remove = os.todo.remove.use(db).handler(async ({ context, input }) => {
const [deleted] = await context.db.delete(todoTable).where(eq(todoTable.id, input.id)).returning({ id: todoTable.id })
if (!deleted) {
throw new ORPCError('NOT_FOUND')
}
})
-6
View File
@@ -1,6 +0,0 @@
import type { ContractRouterClient, InferContractRouterInputs, InferContractRouterOutputs } from '@orpc/contract'
import type { Contract } from './contracts'
export type RouterClient = ContractRouterClient<Contract>
export type RouterInputs = InferContractRouterInputs<Contract>
export type RouterOutputs = InferContractRouterOutputs<Contract>
-55
View File
@@ -1,55 +0,0 @@
import { sql } from 'drizzle-orm'
import { timestamp, uuid } from 'drizzle-orm/pg-core'
import { v7 as uuidv7 } from 'uuid'
// id
const id = (name: string) => uuid(name)
export const pk = (name: string, strategy?: 'native' | 'extension') => {
switch (strategy) {
// PG 18+
case 'native':
return id(name).primaryKey().default(sql`uuidv7()`)
// PG 13+ with extension
case 'extension':
return id(name).primaryKey().default(sql`uuid_generate_v7()`)
// Any PG version
default:
return id(name)
.primaryKey()
.$defaultFn(() => uuidv7())
}
}
// timestamp
export const createdAt = (name = 'created_at') => timestamp(name, { withTimezone: true }).notNull().defaultNow()
export const updatedAt = (name = 'updated_at') =>
timestamp(name, { withTimezone: true })
.notNull()
.defaultNow()
.$onUpdateFn(() => new Date())
// generated fields
export const generatedFields = {
id: pk('id'),
createdAt: createdAt('created_at'),
updatedAt: updatedAt('updated_at'),
}
// Helper to create omit keys from generatedFields
const createGeneratedFieldKeys = <T extends Record<string, unknown>>(fields: T): Record<keyof T, true> => {
return Object.keys(fields).reduce(
(acc, key) => {
acc[key as keyof T] = true
return acc
},
{} as Record<keyof T, true>,
)
}
export const generatedFieldKeys = createGeneratedFieldKeys(generatedFields)
-24
View File
@@ -1,24 +0,0 @@
import { drizzle } from 'drizzle-orm/postgres-js'
import { env } from '@/env'
import { relations } from '@/server/db/relations'
export const createDB = () =>
drizzle({
connection: env.DATABASE_URL,
relations,
})
export type DB = ReturnType<typeof createDB>
export const getDB = (() => {
let db: DB | null = null
return (singleton = true): DB => {
if (!singleton) {
return createDB()
}
db ??= createDB()
return db
}
})()
-4
View File
@@ -1,4 +0,0 @@
import { defineRelations } from 'drizzle-orm'
import * as schema from './schema'
export const relations = defineRelations(schema, (_r) => ({}))
@@ -1 +0,0 @@
export * from './todo'
-8
View File
@@ -1,8 +0,0 @@
import { boolean, pgTable, text } from 'drizzle-orm/pg-core'
import { generatedFields } from '../fields'
export const todoTable = pgTable('todo', {
...generatedFields,
title: text('title').notNull(),
completed: boolean('completed').notNull().default(false),
})
-1
View File
@@ -1 +0,0 @@
@import "tailwindcss";
-8
View File
@@ -1,8 +0,0 @@
{
"extends": "@furtherverse/tsconfig/react.json",
"compilerOptions": {
"paths": {
"@/*": ["./src/*"]
}
}
}
-47
View File
@@ -1,47 +0,0 @@
{
"$schema": "../../node_modules/turbo/schema.json",
"extends": ["//"],
"tasks": {
"build": {
"env": ["NODE_ENV", "VITE_*"],
"inputs": ["src/**", "public/**", "package.json", "tsconfig.json", "vite.config.ts"],
"outputs": [".output/**"]
},
"compile": {
"dependsOn": ["build"],
"outputs": ["out/**"]
},
"compile:darwin": {
"dependsOn": ["build"],
"outputs": ["out/**"]
},
"compile:darwin:arm64": {
"dependsOn": ["build"],
"outputs": ["out/**"]
},
"compile:darwin:x64": {
"dependsOn": ["build"],
"outputs": ["out/**"]
},
"compile:linux": {
"dependsOn": ["build"],
"outputs": ["out/**"]
},
"compile:linux:arm64": {
"dependsOn": ["build"],
"outputs": ["out/**"]
},
"compile:linux:x64": {
"dependsOn": ["build"],
"outputs": ["out/**"]
},
"compile:windows": {
"dependsOn": ["build"],
"outputs": ["out/**"]
},
"compile:windows:x64": {
"dependsOn": ["build"],
"outputs": ["out/**"]
}
}
}
+19 -1
View File
@@ -6,7 +6,8 @@
"useIgnoreFile": true
},
"files": {
"ignoreUnknown": false
"ignoreUnknown": false,
"includes": ["**", "!**/routeTree.gen.ts", "!**/migrations.gen.ts"]
},
"formatter": {
"enabled": true,
@@ -16,6 +17,10 @@
},
"linter": {
"enabled": true,
"domains": {
"react": "recommended",
"types": "all"
},
"rules": {
"recommended": true,
"complexity": {
@@ -23,6 +28,14 @@
},
"correctness": {
"noReactPropAssignments": "error"
},
"style": {
"noNonNullAssertion": "error"
},
"suspicious": {
"noExplicitAny": "error",
"noImportCycles": "error",
"noTsIgnore": "error"
}
}
},
@@ -33,6 +46,11 @@
"arrowParentheses": "always"
}
},
"css": {
"parser": {
"tailwindDirectives": true
}
},
"assist": {
"enabled": true,
"actions": {
+231 -1111
View File
File diff suppressed because it is too large Load Diff
-2
View File
@@ -1,2 +0,0 @@
[install]
publicHoistPattern = ["@types/*", "bun-types", "nitro*"]
+40
View File
@@ -0,0 +1,40 @@
services:
db:
image: mysql:8.4
ports:
- "3306:3306"
volumes:
- ./volumes/mysql/data:/var/lib/mysql
environment:
MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: battery_soh
MYSQL_USER: battery
MYSQL_PASSWORD: battery
healthcheck:
test: [ "CMD", "mysqladmin", "ping", "-h", "127.0.0.1", "-ubattery", "-pbattery" ]
interval: 5s
timeout: 5s
retries: 20
seed:
image: oven/bun:1.3.13
restart: "no"
depends_on:
db:
condition: service_healthy
volumes:
- .:/app
environment:
- DATABASE_URL=mysql://battery:battery@db:3306/battery_soh
command: [ "sh", "-lc", "bun install --frozen-lockfile && bun run seed" ]
working_dir: /app
app:
build: .
depends_on:
seed:
condition: service_completed_successfully
ports:
- "3000:3000"
environment:
- DATABASE_URL=mysql://battery:battery@db:3306/battery_soh
+1 -2
View File
@@ -1,3 +1,2 @@
[tools]
bun = "1"
node = "24"
bun = "1.3.13"
-13
View File
@@ -1,13 +0,0 @@
{
"$schema": "https://opencode.ai/config.json",
"mcp": {
"shadcn": {
"type": "local",
"command": ["bunx", "--bun", "shadcn", "mcp"]
},
"tanstack": {
"type": "remote",
"url": "https://tanstack.com/api/mcp"
}
}
}
+53 -57
View File
@@ -1,68 +1,64 @@
{
"name": "@furtherverse/monorepo",
"name": "fullstack-starter",
"version": "1.0.0",
"private": true,
"type": "module",
"workspaces": [
"apps/*",
"packages/*"
],
"imports": {
"#package": "./package.json",
"#server": "./.output/server/index.mjs"
},
"scripts": {
"build": "turbo run build",
"compile": "turbo run compile",
"compile:darwin": "turbo run compile:darwin",
"compile:linux": "turbo run compile:linux",
"compile:windows": "turbo run compile:windows",
"dev": "turbo run dev",
"dist": "turbo run dist",
"dist:linux": "turbo run dist:linux",
"dist:mac": "turbo run dist:mac",
"dist:win": "turbo run dist:win",
"fix": "turbo run fix",
"typecheck": "turbo run typecheck"
"build": "bunx --bun vite build",
"cli": "bun src/bin.ts",
"compile": "bun scripts/compile.ts",
"compile:darwin": "bun run compile:darwin:arm64 && bun run compile:darwin:x64",
"compile:darwin:arm64": "bun scripts/compile.ts --target bun-darwin-arm64",
"compile:darwin:x64": "bun scripts/compile.ts --target bun-darwin-x64",
"compile:linux": "bun run compile:linux:x64 && bun run compile:linux:arm64",
"compile:linux:arm64": "bun scripts/compile.ts --target bun-linux-arm64",
"compile:linux:x64": "bun scripts/compile.ts --target bun-linux-x64",
"compile:windows": "bun run compile:windows:x64",
"compile:windows:x64": "bun scripts/compile.ts --target bun-windows-x64",
"dev": "bunx --bun vite dev",
"fix": "biome check --write",
"seed": "bun scripts/seed.ts",
"test": "bun test",
"typecheck": "tsc --noEmit"
},
"devDependencies": {
"@biomejs/biome": "^2.4.9",
"turbo": "^2.8.20",
"typescript": "^6.0.2"
},
"catalog": {
"@orpc/client": "^1.13.11",
"@orpc/contract": "^1.13.11",
"@orpc/openapi": "^1.13.11",
"@orpc/server": "^1.13.11",
"@orpc/tanstack-query": "^1.13.11",
"@orpc/zod": "^1.13.11",
"dependencies": {
"@logtape/logtape": "^2.0.5",
"@logtape/pretty": "^2.0.5",
"@orpc/client": "^1.14.0",
"@orpc/contract": "^1.14.0",
"@orpc/openapi": "^1.14.0",
"@orpc/server": "^1.14.0",
"@orpc/tanstack-query": "^1.14.0",
"@orpc/zod": "^1.14.0",
"@t3-oss/env-core": "^0.13.11",
"@tailwindcss/vite": "^4.2.2",
"@tanstack/devtools-vite": "^0.6.0",
"@tanstack/react-devtools": "^0.10.0",
"@tanstack/react-query": "^5.95.2",
"@tanstack/react-query-devtools": "^5.95.2",
"@tanstack/react-router": "^1.168.3",
"@tanstack/react-router-devtools": "^1.166.11",
"@tanstack/react-router-ssr-query": "^1.166.10",
"@tanstack/react-start": "^1.167.6",
"@types/bun": "^1.3.11",
"@types/node": "^24.12.0",
"@vitejs/plugin-react": "^6.0.1",
"drizzle-kit": "1.0.0-beta.15-859cf75",
"drizzle-orm": "1.0.0-beta.15-859cf75",
"electron": "^34.0.0",
"electron-builder": "^26.8.1",
"electron-vite": "^5.0.0",
"motion": "^12.38.0",
"nitro": "npm:nitro-nightly@3.0.1-20260324-103046-9ce219ca",
"postgres": "^3.4.8",
"react": "^19.2.4",
"react-dom": "^19.2.4",
"tailwindcss": "^4.2.2",
"tree-kill": "^1.2.2",
"uuid": "^13.0.0",
"vite": "^8.0.2",
"@tanstack/react-query": "^5.100.1",
"@tanstack/react-router": "^1.168.24",
"@tanstack/react-router-ssr-query": "^1.166.11",
"@tanstack/react-start": "^1.167.48",
"citty": "^0.2.2",
"drizzle-orm": "^0.45.2",
"mysql2": "^3.22.3",
"react": "^19.2.5",
"react-dom": "^19.2.5",
"zod": "^4.3.6"
},
"overrides": {
"@types/node": "catalog:"
"devDependencies": {
"@biomejs/biome": "^2.4.13",
"@tailwindcss/vite": "^4.2.4",
"@tanstack/devtools-vite": "^0.6.0",
"@tanstack/react-devtools": "^0.10.2",
"@tanstack/react-query-devtools": "^5.100.1",
"@tanstack/react-router-devtools": "^1.166.13",
"@types/bun": "^1.3.13",
"@vitejs/plugin-react": "^6.0.1",
"drizzle-seed": "^0.3.1",
"nitro": "npm:nitro-nightly@3.0.1-20260424-182106-f8cf6ccc",
"tailwindcss": "^4.2.4",
"typescript": "^6.0.3",
"vite": "^8.0.10"
}
}
-8
View File
@@ -1,8 +0,0 @@
{
"$schema": "https://json.schemastore.org/tsconfig",
"display": "Bun",
"extends": "./base.json",
"compilerOptions": {
"types": ["bun-types"]
}
}
-11
View File
@@ -1,11 +0,0 @@
{
"name": "@furtherverse/tsconfig",
"version": "1.0.0",
"private": true,
"type": "module",
"exports": {
"./base.json": "./base.json",
"./bun.json": "./bun.json",
"./react.json": "./react.json"
}
}
-9
View File
@@ -1,9 +0,0 @@
{
"$schema": "https://json.schemastore.org/tsconfig",
"display": "React",
"extends": "./base.json",
"compilerOptions": {
"lib": ["ESNext", "DOM", "DOM.Iterable"],
"jsx": "react-jsx"
}
}
+2
View File
@@ -0,0 +1,2 @@
User-agent: *
Disallow:
+13 -4
View File
@@ -1,7 +1,8 @@
import { mkdir, rm } from 'node:fs/promises'
import { basename } from 'node:path'
import { parseArgs } from 'node:util'
const ENTRYPOINT = '.output/server/index.mjs'
const ENTRYPOINT = 'src/bin.ts'
const OUTDIR = 'out'
const SUPPORTED_TARGETS: readonly Bun.Build.CompileTarget[] = [
@@ -12,8 +13,9 @@ const SUPPORTED_TARGETS: readonly Bun.Build.CompileTarget[] = [
'bun-linux-arm64',
]
const isSupportedTarget = (value: string): value is Bun.Build.CompileTarget =>
(SUPPORTED_TARGETS as readonly string[]).includes(value)
const SUPPORTED_TARGET_SET: ReadonlySet<string> = new Set(SUPPORTED_TARGETS)
const isSupportedTarget = (value: string): value is Bun.Build.CompileTarget => SUPPORTED_TARGET_SET.has(value)
const { values } = parseArgs({
options: { target: { type: 'string' } },
@@ -48,13 +50,20 @@ const main = async () => {
const result = await Bun.build({
entrypoints: [ENTRYPOINT],
outdir: OUTDIR,
compile: { outfile, target },
// autoloadDotenv: false — produce a deterministic binary; it must not silently consume a .env from cwd.
compile: { outfile, target, autoloadDotenv: false },
minify: true,
bytecode: true,
sourcemap: 'inline',
})
if (!result.success) {
throw new Error(result.logs.map(String).join('\n'))
}
// Bun bundler still writes *.js.map next to the binary even with inline sourcemap.
await rm(`${OUTDIR}/${basename(ENTRYPOINT, '.ts')}.js.map`, { force: true })
console.log(`${target}${OUTDIR}/${outfile}`)
}
+116
View File
@@ -0,0 +1,116 @@
import { reset } from 'drizzle-seed'
import { drizzle } from 'drizzle-orm/mysql2'
import { datetime, index, int, mysqlTable, tinyint, varchar } from 'drizzle-orm/mysql-core'
import mysql from 'mysql2/promise'
type SeedRow = {
userId: number
mac: string
devModel: string
devName: string
isLowPower: 'true' | 'false'
powerStatus: 0 | 1 | 2
power: number
createTime: Date
remark: string | null
}
const lsBatteryInfo = mysqlTable(
'ls_battery_info',
{
id: int('id').autoincrement().primaryKey(),
userId: int('user_id').notNull(),
mac: varchar('mac', { length: 50 }).notNull(),
devModel: varchar('dev_model', { length: 20 }).notNull(),
devName: varchar('dev_name', { length: 50 }).notNull(),
isLowPower: varchar('is_low_power', { length: 10 }).notNull(),
powerStatus: tinyint('power_status').notNull(),
power: tinyint('power').notNull(),
createTime: datetime('create_time').notNull(),
remark: varchar('remark', { length: 500 }),
},
(table) => [index('idx_ls_battery_info_mac_time_id').on(table.mac, table.createTime, table.id)],
)
const databaseUrl = process.env.DATABASE_URL
if (!databaseUrl) {
throw new Error('DATABASE_URL is required, for example mysql://battery:battery@localhost:3306/battery_soh')
}
const parsedUrl = new URL(databaseUrl)
const safeSeedHosts = new Set(['localhost', '127.0.0.1', '0.0.0.0', 'db', 'mysql'])
if (!safeSeedHosts.has(parsedUrl.hostname) && process.env.SEED_ALLOW_REMOTE !== 'true') {
throw new Error(
`Refusing to seed non-local MySQL host "${parsedUrl.hostname}". Set SEED_ALLOW_REMOTE=true only for disposable test databases.`,
)
}
const devices = [
{ mac: 'RING-A03', model: 'SR-01', name: '样机-A03', basePower: 96, status: 2, remark: 'v3.8.2' },
{ mac: 'RING-B11', model: 'SR-01', name: '样机-B11', basePower: 91, status: 1, remark: 'v3.8.2' },
{ mac: 'RING-C07', model: 'SR-02', name: '样机-C07', basePower: 88, status: 0, remark: 'v3.8.1' },
{ mac: 'RING-D19', model: 'SR-02', name: '样机-D19', basePower: 84, status: 0, remark: 'v3.7.9' },
{ mac: 'RING-E21', model: 'SR-03', name: '样机-E21', basePower: 79, status: 1, remark: 'v3.7.9' },
{ mac: 'RING-F02', model: 'SR-03', name: '样机-F02', basePower: 73, status: 0, remark: null },
{ mac: 'RING-G15', model: 'SR-04', name: '样机-G15', basePower: 93, status: 2, remark: 'v3.9.0' },
{ mac: 'RING-H09', model: 'SR-04', name: '样机-H09', basePower: 86, status: 0, remark: 'v3.8.1' },
] satisfies Array<{
mac: string
model: string
name: string
basePower: number
status: 0 | 1 | 2
remark: string | null
}>
function createSeedRows(now = new Date()): SeedRow[] {
return devices.flatMap((device, deviceIndex) =>
Array.from({ length: 8 }, (_, historyIndex) => {
const createdAt = new Date(now.getTime() - (historyIndex * 24 + deviceIndex * 2) * 60 * 60 * 1000)
const power = Math.max(1, Math.min(100, device.basePower - historyIndex * 2 + (deviceIndex % 3)))
return {
userId: 1001 + (deviceIndex % 3),
mac: device.mac,
devModel: device.model,
devName: device.name,
isLowPower: power <= 20 || device.basePower <= 80 ? 'true' : 'false',
powerStatus: historyIndex === 0 ? device.status : 0,
power,
createTime: createdAt,
remark: device.remark,
}
}),
)
}
const connection = await mysql.createConnection({ uri: databaseUrl })
const db = drizzle(connection)
try {
await db.execute(`
CREATE TABLE IF NOT EXISTS ls_battery_info (
id int(11) NOT NULL AUTO_INCREMENT,
user_id int(11) NOT NULL,
mac varchar(50) NOT NULL,
dev_model varchar(20) NOT NULL,
dev_name varchar(50) NOT NULL,
is_low_power varchar(10) NOT NULL,
power_status tinyint(4) NOT NULL,
power tinyint(4) NOT NULL,
create_time datetime NOT NULL,
remark varchar(500) DEFAULT NULL,
PRIMARY KEY (id),
KEY idx_ls_battery_info_mac_time_id (mac, create_time, id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
`)
await reset(db, { lsBatteryInfo })
await db.insert(lsBatteryInfo).values(createSeedRows())
process.stdout.write(`Seeded ${devices.length} devices into ls_battery_info.\n`)
} finally {
await connection.end()
}
+20
View File
@@ -0,0 +1,20 @@
import { defineCommand, runMain } from 'citty'
import { name, version } from '#package'
// IMPORTANT: keep this file's static imports minimal. Nitro's bun preset
// emits `.output/server/index.mjs` with a top-level `serve(...)` call, so any
// eager (transitive) import of it would start the HTTP server even for
// `--help`. All subcommands are lazy-loaded via citty.
const main = defineCommand({
meta: {
name,
version,
description: 'Fullstack server binary (default subcommand: serve)',
},
default: 'serve',
subCommands: {
serve: () => import('@/cli/serve').then((m) => m.default),
},
})
runMain(main)
+1
View File
@@ -0,0 +1 @@
export default function startNitroServer(): Promise<void>
+3
View File
@@ -0,0 +1,3 @@
export default async function startNitroServer() {
await import('#server')
}
+12
View File
@@ -0,0 +1,12 @@
import { defineCommand } from 'citty'
export default defineCommand({
meta: {
name: 'serve',
description: 'Start the HTTP server',
},
async run() {
const { default: startNitroServer } = await import('./_serve-nitro.mjs')
await startNitroServer()
},
})
@@ -24,30 +24,4 @@ const getORPCClient = createIsomorphicFn()
const client: RouterClient = getORPCClient()
export const orpc = createTanstackQueryUtils(client, {
experimental_defaults: {
todo: {
create: {
mutationOptions: {
onSuccess: (_, __, ___, ctx) => {
ctx.client.invalidateQueries({ queryKey: orpc.todo.list.key() })
},
},
},
update: {
mutationOptions: {
onSuccess: (_, __, ___, ctx) => {
ctx.client.invalidateQueries({ queryKey: orpc.todo.list.key() })
},
},
},
remove: {
mutationOptions: {
onSuccess: (_, __, ___, ctx) => {
ctx.client.invalidateQueries({ queryKey: orpc.todo.list.key() })
},
},
},
},
},
})
export const orpc = createTanstackQueryUtils(client)
+40
View File
@@ -0,0 +1,40 @@
export const ErrorComponent = ({ error, reset }: { error: Error; reset: () => void }) => {
return (
<div className="min-h-screen flex items-center justify-center bg-slate-50 px-4">
<div className="max-w-md w-full text-center space-y-6">
<div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-red-100">
<svg
className="w-8 h-8 text-red-500"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
strokeWidth={1.5}
aria-hidden="true"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M12 9v3.75m9-.75a9 9 0 11-18 0 9 9 0 0118 0zm-9 3.75h.008v.008H12v-.008z"
/>
</svg>
</div>
<div>
<h1 className="text-2xl font-bold text-slate-900"></h1>
<p className="text-slate-500 mt-2">{import.meta.env.DEV ? error.message : '请求失败,请稍后重试'}</p>
</div>
<div className="flex items-center justify-center gap-4">
<button
type="button"
onClick={reset}
className="px-6 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl font-medium transition-colors"
>
</button>
<a href="/" className="px-6 py-2.5 text-slate-600 hover:text-slate-900 font-medium transition-colors">
</a>
</div>
</div>
</div>
)
}
+23
View File
@@ -0,0 +1,23 @@
import { Link } from '@tanstack/react-router'
export const NotFoundComponent = () => {
return (
<div className="min-h-screen flex items-center justify-center bg-slate-50 px-4">
<div className="max-w-md w-full text-center space-y-6">
<div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-slate-100">
<span className="text-3xl font-bold text-slate-400">404</span>
</div>
<div>
<h1 className="text-2xl font-bold text-slate-900"></h1>
<p className="text-slate-500 mt-2">访</p>
</div>
<Link
to="/"
className="inline-block px-6 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl font-medium transition-colors"
>
</Link>
</div>
</div>
)
}
+62
View File
@@ -0,0 +1,62 @@
import { describe, expect, test } from 'bun:test'
import { createBatteriesResponse, createDashboardSnapshot, getDeviceStatus, toBatteryInfo } from './battery'
const rows = [
{
id: 1,
userId: 7,
mac: 'RING-A03',
devModel: '2401-A',
devName: 'RING-A03',
isLowPower: 'false',
powerStatus: 2,
power: 94,
createTime: new Date('2026-05-10T23:00:00.000Z'),
remark: 'v3.8.2',
},
{
id: 2,
userId: 7,
mac: 'RING-B11',
devModel: '2402-B',
devName: 'RING-B11',
isLowPower: 'true',
powerStatus: 1,
power: 84,
createTime: '2026-05-10 22:00:00',
remark: null,
},
]
describe('battery domain', () => {
test('preserves legacy SOH status thresholds', () => {
expect(getDeviceStatus(91)).toBe('健康')
expect(getDeviceStatus(90)).toBe('关注')
expect(getDeviceStatus(85)).toBe('预警')
})
test('builds batteries response counters from records', () => {
const now = new Date('2026-05-11T00:00:00.000Z')
const items = rows.map(toBatteryInfo)
const response = createBatteriesResponse(items, now)
expect(response.updatedAt).toBe('2026-05-11T00:00:00.000Z')
expect(response.total).toBe(items.length)
expect(response.lowPower).toBe(1)
expect(response.charging).toBe(1)
expect(response.items[0]?.createTime).toBe('2026-05-10T23:00:00.000Z')
})
test('creates old dashboard aggregate shape from deterministic records', () => {
const now = new Date('2026-05-11T00:00:00.000Z')
const snapshot = createDashboardSnapshot(rows.map(toBatteryInfo), now)
expect(snapshot.devices).toHaveLength(2)
expect(snapshot.soh.history).toHaveLength(12)
expect(snapshot.soh.forecast).toHaveLength(4)
expect(snapshot.summary.totalDevices).toBe(snapshot.devices.length)
expect(snapshot.summary.warningCount + snapshot.summary.watchCount + snapshot.summary.healthyCount).toBe(
snapshot.devices.length,
)
})
})
+354
View File
@@ -0,0 +1,354 @@
import { z } from 'zod'
export const powerStatusSchema = z.union([z.literal(0), z.literal(1), z.literal(2)])
export type PowerStatus = z.infer<typeof powerStatusSchema>
export const deviceStatusSchema = z.union([z.literal('健康'), z.literal('关注'), z.literal('预警')])
export type DeviceStatus = z.infer<typeof deviceStatusSchema>
export const batteryInfoSchema = z.object({
id: z.number().int(),
userId: z.number().int(),
mac: z.string(),
devModel: z.string(),
devName: z.string(),
isLowPower: z.boolean(),
powerStatus: powerStatusSchema,
power: z.number().int().min(0).max(100),
createTime: z.string(),
remark: z.string().nullable(),
})
export type BatteryInfo = z.infer<typeof batteryInfoSchema>
export const fleetUnitSchema = z.object({
id: z.string(),
batch: z.string(),
firmware: z.string(),
cycles: z.number().int(),
soh: z.number(),
soh30d: z.number(),
soh60d: z.number(),
soh90d: z.number(),
temperature: z.number(),
riskScore: z.number().int(),
chargeEfficiency: z.number(),
status: deviceStatusSchema,
riskFactors: z.array(z.string()),
})
export type FleetUnit = z.infer<typeof fleetUnitSchema>
export const sohPointSchema = z.object({ month: z.string(), value: z.number() })
export const sohResponseSchema = z.object({
history: z.array(sohPointSchema),
forecast: z.array(sohPointSchema),
})
export const eventItemSchema = z.object({
time: z.string(),
title: z.string(),
detail: z.string(),
severity: z.union([z.literal('高'), z.literal('中'), z.literal('低')]),
})
export const strategyItemSchema = z.object({
name: z.string(),
impact: z.string(),
scope: z.string(),
eta: z.string(),
})
export const summaryResponseSchema = z.object({
totalDevices: z.number().int(),
avgSoh: z.number(),
avgSoh30d: z.number(),
avgSoh90d: z.number(),
warningCount: z.number().int(),
watchCount: z.number().int(),
healthyCount: z.number().int(),
batchPerformance: z.array(z.object({ batch: z.string(), avgSoh: z.number() })),
riskFactorCounts: z.array(z.object({ factor: z.string(), count: z.number().int() })),
firmwareHealth: z.array(z.object({ firmware: z.string(), avgSoh: z.number(), count: z.number().int() })),
updatedAt: z.string(),
executiveSummary: z.string(),
})
export const dashboardSnapshotSchema = z.object({
devices: z.array(fleetUnitSchema),
soh: sohResponseSchema,
events: z.array(eventItemSchema),
strategies: z.array(strategyItemSchema),
summary: summaryResponseSchema,
})
export type DashboardSnapshot = z.infer<typeof dashboardSnapshotSchema>
export const batteriesResponseSchema = z.object({
updatedAt: z.string(),
total: z.number().int(),
lowPower: z.number().int(),
charging: z.number().int(),
items: z.array(batteryInfoSchema),
})
export type BatteriesResponse = z.infer<typeof batteriesResponseSchema>
const round1 = (value: number) => Math.round(value * 10) / 10
const clamp = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value))
const pad2 = (value: number) => value.toString().padStart(2, '0')
const addMonths = (date: Date, months: number) =>
new Date(date.getFullYear(), date.getMonth() + months, date.getDate(), date.getHours(), 0, 0, 0)
const addHours = (date: Date, hours: number) => new Date(date.getTime() + hours * 60 * 60 * 1000)
const formatMonthLabel = (date: Date) => `${date.getFullYear().toString().slice(-2)}.${pad2(date.getMonth() + 1)}`
const formatDateTime = (date: Date) =>
`${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())} ${pad2(date.getHours())}:${pad2(date.getMinutes())}:${pad2(date.getSeconds())}`
const formatEventTime = (date: Date) =>
`${pad2(date.getMonth() + 1)}-${pad2(date.getDate())} ${pad2(date.getHours())}:${pad2(date.getMinutes())}`
export function getDeviceStatus(soh: number): DeviceStatus {
if (soh <= 85) return '预警'
if (soh <= 90) return '关注'
return '健康'
}
export function normalizePowerStatus(value: number): PowerStatus {
if (value === 1 || value === 2) return value
return 0
}
export function normalizeLowPower(value: string | boolean): boolean {
if (typeof value === 'boolean') return value
return value.toLowerCase() === 'true'
}
export type BatteryInfoSourceRow = {
id: number
userId: number
mac: string
devModel: string
devName: string
isLowPower: string | boolean
powerStatus: number
power: number
createTime: Date | string
remark: string | null
}
export function toBatteryInfo(row: BatteryInfoSourceRow): BatteryInfo {
return {
id: row.id,
userId: row.userId,
mac: row.mac,
devModel: row.devModel,
devName: row.devName,
isLowPower: normalizeLowPower(row.isLowPower),
powerStatus: normalizePowerStatus(row.powerStatus),
power: row.power,
createTime: row.createTime instanceof Date ? row.createTime.toISOString() : String(row.createTime),
remark: row.remark,
}
}
export function createBatteriesResponse(items: BatteryInfo[], now = new Date()): BatteriesResponse {
return {
updatedAt: now.toISOString(),
total: items.length,
lowPower: items.filter((item) => item.isLowPower).length,
charging: items.filter((item) => item.powerStatus === 1).length,
items,
}
}
function toFleetUnit(item: BatteryInfo, index: number): FleetUnit {
const soh = item.power
const status = getDeviceStatus(soh)
const riskFactors: string[] = []
if (item.isLowPower || item.power <= 20) riskFactors.push('低电量')
if (item.powerStatus === 1) riskFactors.push('充电中')
if (status === '预警') riskFactors.push('衰减加速')
if (item.remark?.includes('v3.7')) riskFactors.push('旧固件')
const thermalPressure = index % 3
const soh30d = round1(clamp(soh - 0.8 - thermalPressure * 0.25, 0, 100))
const soh60d = round1(clamp(soh - 1.7 - thermalPressure * 0.35, 0, 100))
const soh90d = round1(clamp(soh - 2.8 - thermalPressure * 0.45, 0, 100))
const temperature = round1(29.5 + thermalPressure * 2.1 + (item.isLowPower ? 1.4 : 0))
const chargeEfficiency = round1(clamp(91 + item.power / 12 - riskFactors.length * 1.8, 80, 98))
const riskScore = Math.round(clamp(12 + (100 - soh) * 1.45 + riskFactors.length * 8 + thermalPressure * 4, 8, 96))
return {
id: item.devName || item.mac,
batch: item.devModel,
firmware: item.remark ?? 'unknown',
cycles: 120 + index * 17 + Math.round((100 - soh) * 2.2),
soh,
soh30d,
soh60d,
soh90d,
temperature,
riskScore,
chargeEfficiency,
status,
riskFactors,
}
}
function createSohResponse(devices: FleetUnit[], now: Date) {
if (devices.length === 0) return { history: [], forecast: [] }
const avgSoh = devices.reduce((sum, unit) => sum + unit.soh, 0) / devices.length
const monthlyDrop = 0.45 + devices.reduce((sum, unit) => sum + unit.riskScore, 0) / devices.length / 160
const history = Array.from({ length: 12 }, (_, index) => {
const monthOffset = index - 11
return {
month: formatMonthLabel(addMonths(now, monthOffset)),
value: round1(clamp(avgSoh + Math.abs(monthOffset) * monthlyDrop, avgSoh, 100)),
}
})
const currentValue = history.at(-1)?.value ?? round1(avgSoh)
const forecast = Array.from({ length: 4 }, (_, index) => ({
month: formatMonthLabel(addMonths(now, index)),
value: index === 0 ? currentValue : round1(clamp(avgSoh - monthlyDrop * index, 0, 100)),
}))
return { history, forecast }
}
function summarizeBy<T extends string>(items: FleetUnit[], getKey: (item: FleetUnit) => T) {
return Object.entries(
items.reduce<Record<string, { sum: number; count: number }>>((acc, item) => {
const key = getKey(item)
const entry = acc[key] ?? { sum: 0, count: 0 }
entry.sum += item.soh
entry.count += 1
acc[key] = entry
return acc
}, {}),
)
}
function createSummary(devices: FleetUnit[], now: Date) {
const totalDevices = devices.length
if (totalDevices === 0) {
return {
totalDevices,
avgSoh: 0,
avgSoh30d: 0,
avgSoh90d: 0,
warningCount: 0,
watchCount: 0,
healthyCount: 0,
batchPerformance: [],
riskFactorCounts: [],
firmwareHealth: [],
updatedAt: formatDateTime(now),
executiveSummary: '当前没有可用于电池健康分析的真实设备记录。',
}
}
const avgSoh = devices.reduce((sum, unit) => sum + unit.soh, 0) / totalDevices
const avgSoh30d = devices.reduce((sum, unit) => sum + unit.soh30d, 0) / totalDevices
const avgSoh90d = devices.reduce((sum, unit) => sum + unit.soh90d, 0) / totalDevices
const warningCount = devices.filter((unit) => unit.status === '预警').length
const watchCount = devices.filter((unit) => unit.status === '关注').length
const healthyCount = devices.filter((unit) => unit.status === '健康').length
const batchPerformance = summarizeBy(devices, (unit) => unit.batch)
.map(([batch, data]) => ({ batch, avgSoh: round1(data.sum / data.count) }))
.sort((a, b) => b.avgSoh - a.avgSoh)
const firmwareHealth = summarizeBy(devices, (unit) => unit.firmware)
.map(([firmware, data]) => ({ firmware, avgSoh: round1(data.sum / data.count), count: data.count }))
.sort((a, b) => b.avgSoh - a.avgSoh)
const riskFactorCounts = Object.entries(
devices.reduce<Record<string, number>>((acc, unit) => {
for (const factor of unit.riskFactors) {
acc[factor] = (acc[factor] ?? 0) + 1
}
return acc
}, {}),
)
.map(([factor, count]) => ({ factor, count }))
.sort((a, b) => b.count - a.count)
const weakestBatch = batchPerformance.at(-1)?.batch ?? '当前设备'
const weakestFirmware = firmwareHealth.at(-1)?.firmware ?? 'unknown'
return {
totalDevices,
avgSoh: round1(avgSoh),
avgSoh30d: round1(avgSoh30d),
avgSoh90d: round1(avgSoh90d),
warningCount,
watchCount,
healthyCount,
batchPerformance,
riskFactorCounts,
firmwareHealth,
updatedAt: formatDateTime(now),
executiveSummary: `当前电池健康度总体可控,重点风险集中在 ${weakestBatch} 批次与 ${weakestFirmware} 固件设备。建议优先跟踪低电量、充电状态与未来 90 天 SoH 变化。`,
}
}
function createEvents(devices: FleetUnit[], now: Date) {
const sortedDevices = devices.slice().sort((a, b) => b.riskScore - a.riskScore)
const first = sortedDevices[0]
if (!first) return []
const second = sortedDevices[1] ?? first
return [
{
time: formatEventTime(addHours(now, -2)),
title: `${first.id} 进入重点观察队列`,
detail: `${first.id} 当前 SoH 为 ${first.soh.toFixed(1)}%,综合风险评分 ${first.riskScore}`,
severity: first.status === '预警' ? '高' : '中',
},
{
time: formatEventTime(addHours(now, -5)),
title: `${second.batch} 批次健康度趋势更新`,
detail: `${second.batch} 批次未来 90 天预测 SoH 为 ${second.soh90d.toFixed(1)}%。`,
severity: second.status === '健康' ? '低' : '中',
},
] satisfies DashboardSnapshot['events']
}
function createStrategies(devices: FleetUnit[]) {
if (devices.length === 0) return []
const warningDevices = devices.filter((unit) => unit.status === '预警')
const chargingDevices = devices.filter((unit) => unit.riskFactors.includes('充电中'))
const first = devices.slice().sort((a, b) => b.riskScore - a.riskScore)[0]
return [
{
name: '预警设备优先维护',
impact: `预计高风险设备减少 ${Math.max(10, warningDevices.length * 12)}%`,
scope: first ? `${first.id}${Math.max(1, warningDevices.length)} 台设备` : '当前设备',
eta: '48 小时内完成',
},
{
name: '充电策略复核',
impact: `覆盖 ${Math.max(1, chargingDevices.length)} 台充电中设备`,
scope: '充电中与低电量设备',
eta: '本周完成首轮验证',
},
] satisfies DashboardSnapshot['strategies']
}
export function createDashboardSnapshot(items: BatteryInfo[], now = new Date()): DashboardSnapshot {
const devices = items.map(toFleetUnit)
return {
devices,
soh: createSohResponse(devices, now),
events: createEvents(devices, now),
strategies: createStrategies(devices),
summary: createSummary(devices, now),
}
}
+15
View File
@@ -0,0 +1,15 @@
import { createEnv } from '@t3-oss/env-core'
import { z } from 'zod'
export const env = createEnv({
server: {
DATABASE_URL: z.url({ protocol: /^mysql$/ }),
LOG_DB: z.stringbool().default(false),
LOG_FORMAT: z.enum(['pretty', 'json']).optional(),
LOG_LEVEL: z.enum(['trace', 'debug', 'info', 'warning', 'error', 'fatal']).default('info'),
},
clientPrefix: 'VITE_',
client: {},
runtimeEnv: process.env,
emptyStringAsUndefined: true,
})
@@ -9,21 +9,27 @@
// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.
import { Route as rootRouteImport } from './routes/__root'
import { Route as HealthRouteImport } from './routes/health'
import { Route as BatteriesRouteImport } from './routes/batteries'
import { Route as IndexRouteImport } from './routes/index'
import { Route as ApiHealthRouteImport } from './routes/api/health'
import { Route as ApiSplatRouteImport } from './routes/api/$'
import { Route as ApiRpcSplatRouteImport } from './routes/api/rpc.$'
const HealthRoute = HealthRouteImport.update({
id: '/health',
path: '/health',
getParentRoute: () => rootRouteImport,
} as any)
const BatteriesRoute = BatteriesRouteImport.update({
id: '/batteries',
path: '/batteries',
getParentRoute: () => rootRouteImport,
} as any)
const IndexRoute = IndexRouteImport.update({
id: '/',
path: '/',
getParentRoute: () => rootRouteImport,
} as any)
const ApiHealthRoute = ApiHealthRouteImport.update({
id: '/api/health',
path: '/api/health',
getParentRoute: () => rootRouteImport,
} as any)
const ApiSplatRoute = ApiSplatRouteImport.update({
id: '/api/$',
path: '/api/$',
@@ -37,40 +43,58 @@ const ApiRpcSplatRoute = ApiRpcSplatRouteImport.update({
export interface FileRoutesByFullPath {
'/': typeof IndexRoute
'/batteries': typeof BatteriesRoute
'/health': typeof HealthRoute
'/api/$': typeof ApiSplatRoute
'/api/health': typeof ApiHealthRoute
'/api/rpc/$': typeof ApiRpcSplatRoute
}
export interface FileRoutesByTo {
'/': typeof IndexRoute
'/batteries': typeof BatteriesRoute
'/health': typeof HealthRoute
'/api/$': typeof ApiSplatRoute
'/api/health': typeof ApiHealthRoute
'/api/rpc/$': typeof ApiRpcSplatRoute
}
export interface FileRoutesById {
__root__: typeof rootRouteImport
'/': typeof IndexRoute
'/batteries': typeof BatteriesRoute
'/health': typeof HealthRoute
'/api/$': typeof ApiSplatRoute
'/api/health': typeof ApiHealthRoute
'/api/rpc/$': typeof ApiRpcSplatRoute
}
export interface FileRouteTypes {
fileRoutesByFullPath: FileRoutesByFullPath
fullPaths: '/' | '/api/$' | '/api/health' | '/api/rpc/$'
fullPaths: '/' | '/batteries' | '/health' | '/api/$' | '/api/rpc/$'
fileRoutesByTo: FileRoutesByTo
to: '/' | '/api/$' | '/api/health' | '/api/rpc/$'
id: '__root__' | '/' | '/api/$' | '/api/health' | '/api/rpc/$'
to: '/' | '/batteries' | '/health' | '/api/$' | '/api/rpc/$'
id: '__root__' | '/' | '/batteries' | '/health' | '/api/$' | '/api/rpc/$'
fileRoutesById: FileRoutesById
}
export interface RootRouteChildren {
IndexRoute: typeof IndexRoute
BatteriesRoute: typeof BatteriesRoute
HealthRoute: typeof HealthRoute
ApiSplatRoute: typeof ApiSplatRoute
ApiHealthRoute: typeof ApiHealthRoute
ApiRpcSplatRoute: typeof ApiRpcSplatRoute
}
declare module '@tanstack/react-router' {
interface FileRoutesByPath {
'/health': {
id: '/health'
path: '/health'
fullPath: '/health'
preLoaderRoute: typeof HealthRouteImport
parentRoute: typeof rootRouteImport
}
'/batteries': {
id: '/batteries'
path: '/batteries'
fullPath: '/batteries'
preLoaderRoute: typeof BatteriesRouteImport
parentRoute: typeof rootRouteImport
}
'/': {
id: '/'
path: '/'
@@ -78,13 +102,6 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof IndexRouteImport
parentRoute: typeof rootRouteImport
}
'/api/health': {
id: '/api/health'
path: '/api/health'
fullPath: '/api/health'
preLoaderRoute: typeof ApiHealthRouteImport
parentRoute: typeof rootRouteImport
}
'/api/$': {
id: '/api/$'
path: '/api/$'
@@ -104,8 +121,9 @@ declare module '@tanstack/react-router' {
const rootRouteChildren: RootRouteChildren = {
IndexRoute: IndexRoute,
BatteriesRoute: BatteriesRoute,
HealthRoute: HealthRoute,
ApiSplatRoute: ApiSplatRoute,
ApiHealthRoute: ApiHealthRoute,
ApiRpcSplatRoute: ApiRpcSplatRoute,
}
export const routeTree = rootRouteImport
@@ -4,6 +4,7 @@ import { ReactQueryDevtoolsPanel } from '@tanstack/react-query-devtools'
import { createRootRouteWithContext, HeadContent, Scripts } from '@tanstack/react-router'
import { TanStackRouterDevtoolsPanel } from '@tanstack/react-router-devtools'
import type { ReactNode } from 'react'
import { name } from '#package'
import { ErrorComponent } from '@/components/Error'
import { NotFoundComponent } from '@/components/NotFound'
import appCss from '@/styles.css?url'
@@ -23,7 +24,7 @@ export const Route = createRootRouteWithContext<RouterContext>()({
content: 'width=device-width, initial-scale=1',
},
{
title: 'Furtherverse',
title: name,
},
],
links: [
@@ -34,8 +35,8 @@ export const Route = createRootRouteWithContext<RouterContext>()({
],
}),
shellComponent: RootDocument,
errorComponent: () => <ErrorComponent />,
notFoundComponent: () => <NotFoundComponent />,
errorComponent: ErrorComponent,
notFoundComponent: NotFoundComponent,
})
function RootDocument({ children }: Readonly<{ children: ReactNode }>) {
@@ -3,7 +3,7 @@ import { OpenAPIReferencePlugin } from '@orpc/openapi/plugins'
import { onError } from '@orpc/server'
import { ZodToJsonSchemaConverter } from '@orpc/zod/zod4'
import { createFileRoute } from '@tanstack/react-router'
import { name, version } from '@/../package.json'
import { name, version } from '#package'
import { handleValidationError, logError } from '@/server/api/interceptors'
import { router } from '@/server/api/routers'
+119
View File
@@ -0,0 +1,119 @@
import { useSuspenseQuery } from '@tanstack/react-query'
import { createFileRoute, Link } from '@tanstack/react-router'
import { orpc } from '@/client/orpc'
import type { BatteryInfo } from '@/domain/battery'
export const Route = createFileRoute('/batteries')({
component: BatteriesPage,
loader: async ({ context }) => {
await context.queryClient.ensureQueryData(orpc.battery.batteries.queryOptions({ input: {} }))
},
errorComponent: ({ error }) => (
<main className="flex min-h-screen items-center justify-center bg-[#09090B]">
<div className="text-center">
<p className="text-lg text-red-400"></p>
<p className="mt-2 text-sm text-zinc-500">{error.message}</p>
</div>
</main>
),
})
const powerStatusLabel: Record<0 | 1 | 2, string> = {
0: '未充电',
1: '充电中',
2: '已充满',
}
const powerStatusColor: Record<0 | 1 | 2, string> = {
0: 'text-zinc-400',
1: 'text-teal-400',
2: 'text-emerald-400',
}
function powerBarColor(power: number, isLowPower: boolean): string {
if (isLowPower || power <= 20) return 'bg-red-500'
if (power <= 50) return 'bg-amber-500'
return 'bg-teal-500'
}
function DeviceCard({ item }: { item: BatteryInfo }) {
return (
<article className="rounded-lg border border-zinc-800 bg-zinc-950 p-4">
<header className="flex items-start justify-between">
<div>
<h3 className="font-medium text-zinc-100">{item.devName}</h3>
<p className="mt-0.5 text-xs text-zinc-500">{item.mac}</p>
</div>
<span className="rounded bg-zinc-900 px-2 py-0.5 text-xs text-zinc-400">{item.devModel}</span>
</header>
<div className="mt-4">
<div className="flex items-baseline justify-between">
<span className="font-semibold text-2xl text-zinc-100">
{item.power}
<span className="ml-0.5 font-normal text-sm text-zinc-500">%</span>
</span>
<span className={`text-xs ${powerStatusColor[item.powerStatus]}`}>{powerStatusLabel[item.powerStatus]}</span>
</div>
<div className="mt-2 h-1.5 overflow-hidden rounded-full bg-zinc-800">
<div className={`h-full ${powerBarColor(item.power, item.isLowPower)}`} style={{ width: `${item.power}%` }} />
</div>
</div>
<footer className="mt-4 flex items-center justify-between text-xs text-zinc-500">
<span> {new Date(item.createTime).toLocaleString('zh-CN')}</span>
{item.isLowPower && <span className="rounded bg-red-950 px-1.5 py-0.5 text-red-400"></span>}
</footer>
</article>
)
}
function BatteriesPage() {
const { data } = useSuspenseQuery(
orpc.battery.batteries.queryOptions({
input: {},
refetchInterval: 30_000,
}),
)
return (
<main className="min-h-screen bg-[#09090B] px-6 py-8 text-zinc-100">
<header className="mx-auto max-w-7xl">
<div className="flex items-end justify-between">
<div>
<h1 className="font-semibold text-2xl"></h1>
<p className="mt-1 text-sm text-zinc-500"> {new Date(data.updatedAt).toLocaleString('zh-CN')}</p>
</div>
<nav className="text-xs">
<Link to="/" className="text-zinc-500 hover:text-zinc-300">
SoH
</Link>
</nav>
</div>
<dl className="mt-6 grid grid-cols-3 gap-4">
<div className="rounded-lg border border-zinc-800 bg-zinc-950 p-4">
<dt className="text-xs text-zinc-500"></dt>
<dd className="mt-1 font-semibold text-2xl">{data.total}</dd>
</div>
<div className="rounded-lg border border-zinc-800 bg-zinc-950 p-4">
<dt className="text-xs text-zinc-500"></dt>
<dd className="mt-1 font-semibold text-2xl text-red-400">{data.lowPower}</dd>
</div>
<div className="rounded-lg border border-zinc-800 bg-zinc-950 p-4">
<dt className="text-xs text-zinc-500"></dt>
<dd className="mt-1 font-semibold text-2xl text-teal-400">{data.charging}</dd>
</div>
</dl>
</header>
<section className="mx-auto mt-8 grid max-w-7xl grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
{data.items.length > 0 ? (
data.items.map((item) => <DeviceCard key={item.id} item={item} />)
) : (
<div className="col-span-full py-12 text-center text-zinc-500"></div>
)}
</section>
</main>
)
}
+9
View File
@@ -0,0 +1,9 @@
import { createFileRoute } from '@tanstack/react-router'
export const Route = createFileRoute('/health')({
server: {
handlers: {
GET: () => new Response('ok', { status: 200, headers: { 'content-type': 'text/plain' } }),
},
},
})
+632
View File
@@ -0,0 +1,632 @@
import { useSuspenseQuery } from '@tanstack/react-query'
import { createFileRoute, Link } from '@tanstack/react-router'
import { orpc } from '@/client/orpc'
import type { DashboardSnapshot, DeviceStatus } from '@/domain/battery'
export const Route = createFileRoute('/')({
component: Dashboard,
loader: async ({ context }) => {
await context.queryClient.ensureQueryData(orpc.battery.dashboard.queryOptions())
},
errorComponent: ({ error }) => (
<main className="flex min-h-screen items-center justify-center bg-[#09090B]">
<div className="text-center">
<p className="text-lg text-red-400"></p>
<p className="mt-2 text-sm text-[#71717A]">{error.message}</p>
</div>
</main>
),
})
function buildChartData(soh: DashboardSnapshot['soh']) {
const chartData: { month: string; history?: number; forecast?: number }[] = soh.history.map((h) => ({
month: h.month,
history: h.value,
forecast: undefined,
}))
if (chartData.length > 0 && soh.forecast.length > 0) {
// Overlap: last history point is also first forecast point
const last = chartData[chartData.length - 1]
if (last) {
last.forecast = soh.forecast[0]?.value
}
}
for (let i = 1; i < soh.forecast.length; i++) {
const f = soh.forecast[i]
if (f) {
chartData.push({
month: f.month,
history: undefined,
forecast: f.value,
})
}
}
return chartData
}
const statusColorMap: Record<DeviceStatus, string> = {
: 'text-emerald-400',
: 'text-amber-400',
: 'text-red-400',
}
const severityColorMap: Record<DashboardSnapshot['events'][number]['severity'], string> = {
: 'text-red-400',
: 'text-amber-400',
: 'text-zinc-400',
}
function SimpleChart({ data }: { data: ReturnType<typeof buildChartData> }) {
if (data.length === 0) {
return <div className="flex h-full items-center justify-center text-[#71717A]"></div>
}
const minVal = Math.floor(Math.min(...data.map((d) => Math.min(d.history ?? 100, d.forecast ?? 100)))) - 2
const maxVal = Math.ceil(Math.max(...data.map((d) => Math.max(d.history ?? 0, d.forecast ?? 0)))) + 2
const range = maxVal - minVal
const width = 1000
const height = 280
const padding = { top: 20, right: 20, bottom: 30, left: 40 }
const innerWidth = width - padding.left - padding.right
const innerHeight = height - padding.top - padding.bottom
const getX = (index: number) => padding.left + (index / (data.length - 1)) * innerWidth
const getY = (val: number) => padding.top + innerHeight - ((val - minVal) / range) * innerHeight
const historyPoints = data
.map((d, i) => (d.history !== undefined ? `${getX(i)},${getY(d.history)}` : null))
.filter(Boolean)
.join(' ')
const forecastPoints = data
.map((d, i) => (d.forecast !== undefined ? `${getX(i)},${getY(d.forecast)}` : null))
.filter(Boolean)
.join(' ')
const lastHistoryIndex = data.findLastIndex((d) => d.history !== undefined)
const historyArea = historyPoints
? `${historyPoints} ${getX(lastHistoryIndex)},${padding.top + innerHeight} ${getX(0)},${padding.top + innerHeight}`
: ''
const forecastStartIndex = data.findIndex((d) => d.forecast !== undefined)
const forecastArea = forecastPoints
? `${forecastPoints} ${getX(data.length - 1)},${padding.top + innerHeight} ${getX(forecastStartIndex)},${padding.top + innerHeight}`
: ''
return (
<svg
viewBox={`0 0 ${width} ${height}`}
className="w-full h-full overflow-visible"
role="img"
aria-label="SoH Trend Chart"
>
<title>SoH Trend Chart</title>
<defs>
<linearGradient id="historyFill" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor="#2DD4BF" stopOpacity={0.15} />
<stop offset="100%" stopColor="#2DD4BF" stopOpacity={0} />
</linearGradient>
<linearGradient id="forecastFill" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor="#818CF8" stopOpacity={0.15} />
<stop offset="100%" stopColor="#818CF8" stopOpacity={0} />
</linearGradient>
</defs>
{/* Grid */}
{[0, 0.25, 0.5, 0.75, 1].map((ratio) => {
const y = padding.top + innerHeight * ratio
const val = maxVal - range * ratio
return (
<g key={ratio}>
<line x1={padding.left} y1={y} x2={width - padding.right} y2={y} stroke="#ffffff" strokeOpacity={0.05} />
<text x={padding.left - 10} y={y + 4} fill="#71717A" fontSize="11" textAnchor="end">
{val.toFixed(0)}%
</text>
</g>
)
})}
{/* 85% Reference Line */}
{85 >= minVal && 85 <= maxVal && (
<g>
<line
x1={padding.left}
y1={getY(85)}
x2={width - padding.right}
y2={getY(85)}
stroke="#F87171"
strokeOpacity={0.4}
strokeDasharray="4 4"
/>
<text x={width - padding.right + 10} y={getY(85) + 4} fill="#F87171" fontSize="11">
85% 线
</text>
</g>
)}
{/* X Axis */}
{data.map((d, i) => (
<text key={d.month} x={getX(i)} y={height - 5} fill="#71717A" fontSize="11" textAnchor="middle">
{d.month}
</text>
))}
{/* Areas */}
{historyArea && <polygon points={historyArea} fill="url(#historyFill)" />}
{forecastArea && <polygon points={forecastArea} fill="url(#forecastFill)" />}
{/* Lines */}
{historyPoints && <polyline points={historyPoints} fill="none" stroke="#2DD4BF" strokeWidth="2.5" />}
{forecastPoints && (
<polyline points={forecastPoints} fill="none" stroke="#818CF8" strokeWidth="2.5" strokeDasharray="4 4" />
)}
{/* Dots */}
{data.map((d, i) => {
const dots = []
if (d.history !== undefined) {
dots.push(
<circle
key={`h-${d.month}`}
cx={getX(i)}
cy={getY(d.history)}
r="3"
fill="#09090B"
stroke="#2DD4BF"
strokeWidth="2"
/>,
)
}
if (d.forecast !== undefined) {
dots.push(
<circle
key={`f-${d.month}`}
cx={getX(i)}
cy={getY(d.forecast)}
r="3"
fill="#09090B"
stroke="#818CF8"
strokeWidth="2"
/>,
)
}
return dots
})}
</svg>
)
}
function Dashboard() {
const { data } = useSuspenseQuery(orpc.battery.dashboard.queryOptions())
const { devices, soh, events, strategies, summary } = data
const {
totalDevices,
avgSoh,
avgSoh30d,
avgSoh90d,
warningCount,
watchCount,
healthyCount,
batchPerformance,
riskFactorCounts,
firmwareHealth,
updatedAt,
executiveSummary,
} = summary
const chartData = buildChartData(soh)
return (
<main className="min-h-screen w-full bg-[#09090B] font-sans text-[#F4F4F5]">
{/* Background gradient */}
<div className="pointer-events-none fixed inset-0 z-0 flex justify-center">
<div className="h-[800px] w-[1200px] -translate-y-1/2 rounded-full bg-teal-900/10 blur-[120px]" />
</div>
<div className="relative z-10 mx-auto max-w-[1400px] px-6 pb-24 pt-12 lg:px-12">
{/* Header */}
<header className="animate-fade-up mb-12 flex flex-col gap-6 lg:flex-row lg:items-end lg:justify-between">
<div className="max-w-3xl">
<div className="mb-4 inline-flex items-center gap-2 rounded-md border border-white/10 bg-white/5 px-2.5 py-1 text-xs font-medium text-teal-400">
(v2.4)
</div>
<h1 className="text-4xl font-light tracking-tight text-white sm:text-5xl">SoH </h1>
</div>
<div className="flex flex-col items-end gap-3 text-right">
<div className="flex items-center gap-6 text-sm">
<div>
<span className="text-[#71717A]"> (MAE)</span>
<span className="ml-2 font-medium tabular-nums text-teal-400">1.2%</span>
</div>
<div className="h-4 w-px bg-white/10" />
<div>
<span className="text-[#71717A]"></span>
<span className="ml-2 font-medium tabular-nums text-teal-400">94.5%</span>
</div>
</div>
<p className="text-xs tabular-nums text-[#71717A]">: {updatedAt}</p>
<Link to="/batteries" className="text-xs text-teal-400 hover:text-teal-300">
</Link>
</div>
</header>
{/* Executive Summary */}
<section className="animate-fade-up delay-100 mb-12 rounded-xl border border-teal-900/30 bg-teal-950/10 p-6">
<h2 className="mb-3 text-sm font-medium text-teal-400"></h2>
<p className="text-base leading-relaxed text-[#A1A1AA]">{executiveSummary}</p>
</section>
{/* Primary KPI Row */}
<section className="animate-fade-up delay-200 mb-12 grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-5">
{/* Hero KPI */}
<article className="relative overflow-hidden rounded-2xl border border-white/10 bg-white/[0.03] p-8 lg:col-span-2">
<div className="absolute inset-x-0 top-0 h-1 bg-gradient-to-r from-teal-500/50 to-transparent" />
<p className="text-sm font-medium text-[#A1A1AA]"> SoH</p>
<div className="mt-4 flex items-baseline gap-2">
<h2 className="text-6xl font-light tabular-nums text-white">{avgSoh.toFixed(1)}</h2>
<span className="text-2xl text-[#71717A]">%</span>
</div>
<div className="mt-6 flex items-center gap-3 text-sm">
<span className="inline-flex items-center gap-1.5 text-emerald-400">
<span className="h-1.5 w-1.5 rounded-full bg-emerald-400" />
线
</span>
<span className="text-[#71717A]">|</span>
<span className="text-[#A1A1AA]"> {totalDevices} </span>
</div>
</article>
{/* Regular KPIs */}
<article className="rounded-2xl border border-white/[0.06] bg-white/[0.02] p-6 transition-colors hover:border-white/10">
<p className="text-sm text-[#A1A1AA]">30 </p>
<div className="mt-3 flex items-baseline gap-1">
<h2 className="text-4xl font-light tabular-nums text-white">{avgSoh30d.toFixed(1)}</h2>
<span className="text-lg text-[#71717A]">%</span>
</div>
<div className="mt-4 flex items-center gap-1.5 text-sm">
<span className="text-red-400"></span>
<span className="tabular-nums text-[#A1A1AA]">{(avgSoh - avgSoh30d).toFixed(1)}% </span>
</div>
</article>
<article className="rounded-2xl border border-white/[0.06] bg-white/[0.02] p-6 transition-colors hover:border-white/10">
<p className="text-sm text-[#A1A1AA]">90 </p>
<div className="mt-3 flex items-baseline gap-1">
<h2 className="text-4xl font-light tabular-nums text-white">{avgSoh90d.toFixed(1)}</h2>
<span className="text-lg text-[#71717A]">%</span>
</div>
<div className="mt-4 flex items-center gap-1.5 text-sm">
<span className="text-red-400"></span>
<span className="tabular-nums text-[#A1A1AA]">{(avgSoh - avgSoh90d).toFixed(1)}% </span>
</div>
</article>
<article className="rounded-2xl border border-white/[0.06] bg-white/[0.02] p-6 transition-colors hover:border-white/10">
<p className="text-sm text-[#A1A1AA]"></p>
<div className="mt-3 flex items-baseline gap-1">
<h2 className="text-4xl font-light tabular-nums text-white">{warningCount}</h2>
<span className="text-lg text-[#71717A]"></span>
</div>
<div className="mt-4 flex items-center gap-1.5 text-sm">
<span className="text-amber-400"></span>
<span className="tabular-nums text-[#A1A1AA]">
{totalDevices > 0 ? ((warningCount / totalDevices) * 100).toFixed(1) : 0}%
</span>
</div>
</article>
</section>
{/* Divider */}
<hr className="my-12 border-white/5" />
{/* SoH Trend Chart */}
<section className="animate-fade-up delay-300 mb-12">
<article className="rounded-2xl border border-white/[0.06] bg-white/[0.03] p-8">
<header className="mb-8 flex flex-wrap items-end justify-between gap-4">
<div>
<h3 className="text-xl font-medium text-white">SoH 90 </h3>
<p className="mt-1 text-sm text-[#A1A1AA]"> 12 3 </p>
</div>
<div className="flex items-center gap-6 text-sm text-[#A1A1AA]">
<span className="inline-flex items-center gap-2">
<span className="h-2 w-4 rounded-full bg-teal-400" />
</span>
<span className="inline-flex items-center gap-2">
<span className="h-2 w-4 rounded-full bg-indigo-400" />
</span>
</div>
</header>
<div className="w-full h-[320px]">
<SimpleChart data={chartData} />
</div>
</article>
</section>
{/* Two-column grid */}
<section className="animate-fade-up delay-400 mb-12 grid grid-cols-1 gap-8 lg:grid-cols-2">
{/* Left Column */}
<div className="space-y-8">
{/* Risk Distribution */}
<div>
<h3 className="mb-6 text-lg font-medium text-white"></h3>
<div className="space-y-5">
<div>
<div className="mb-2 flex justify-between text-sm">
<span className="text-[#A1A1AA]"> (SoH &gt; 90%)</span>
<span className="tabular-nums text-white">
{healthyCount} {' '}
<span className="text-[#71717A]">
/ {totalDevices > 0 ? ((healthyCount / totalDevices) * 100).toFixed(1) : 0}%
</span>
</span>
</div>
<div className="h-1.5 overflow-hidden rounded-full bg-white/5">
<div
className="h-full rounded-full bg-emerald-400"
style={{ width: `${totalDevices > 0 ? (healthyCount / totalDevices) * 100 : 0}%` }}
/>
</div>
</div>
<div>
<div className="mb-2 flex justify-between text-sm">
<span className="text-[#A1A1AA]"> (85% &lt; SoH &le; 90%)</span>
<span className="tabular-nums text-white">
{watchCount} {' '}
<span className="text-[#71717A]">
/ {totalDevices > 0 ? ((watchCount / totalDevices) * 100).toFixed(1) : 0}%
</span>
</span>
</div>
<div className="h-1.5 overflow-hidden rounded-full bg-white/5">
<div
className="h-full rounded-full bg-amber-400"
style={{ width: `${totalDevices > 0 ? (watchCount / totalDevices) * 100 : 0}%` }}
/>
</div>
</div>
<div>
<div className="mb-2 flex justify-between text-sm">
<span className="text-[#A1A1AA]"> (SoH &le; 85%)</span>
<span className="tabular-nums text-white">
{warningCount} {' '}
<span className="text-[#71717A]">
/ {totalDevices > 0 ? ((warningCount / totalDevices) * 100).toFixed(1) : 0}%
</span>
</span>
</div>
<div className="h-1.5 overflow-hidden rounded-full bg-white/5">
<div
className="h-full rounded-full bg-red-400"
style={{ width: `${totalDevices > 0 ? (warningCount / totalDevices) * 100 : 0}%` }}
/>
</div>
</div>
</div>
</div>
{/* Regional Performance */}
<div>
<h3 className="mb-6 text-lg font-medium text-white"></h3>
<div className="space-y-4">
{batchPerformance.length > 0 ? (
batchPerformance.map((item) => (
<div key={item.batch} className="flex items-center gap-4">
<span className="w-20 text-sm text-[#A1A1AA]">{item.batch}</span>
<div className="flex-1">
<div className="h-1.5 overflow-hidden rounded-full bg-white/5">
<div className="h-full rounded-full bg-white/20" style={{ width: `${item.avgSoh}%` }} />
</div>
</div>
<span className="w-12 text-right text-sm tabular-nums text-white">{item.avgSoh.toFixed(1)}%</span>
</div>
))
) : (
<div className="text-sm text-[#71717A]"></div>
)}
</div>
</div>
</div>
{/* Right Column */}
<div className="space-y-8">
{/* Event Timeline */}
<div>
<h3 className="mb-6 text-lg font-medium text-white"></h3>
<div className="relative border-l border-white/10 pl-5">
{events.length > 0 ? (
events.map((event) => (
<div key={event.time + event.title} className="mb-6 last:mb-0">
<div
className={`absolute -left-[4px] mt-1.5 h-2 w-2 rounded-full ${
event.severity === '高' ? 'bg-red-400' : 'bg-amber-400'
}`}
/>
<div className="mb-1 flex items-center gap-3">
<span className="text-xs font-medium tabular-nums text-[#71717A]">{event.time}</span>
<span className={`text-xs ${severityColorMap[event.severity]}`}>{event.severity}</span>
</div>
<h4 className="text-sm font-medium text-[#F4F4F5]">{event.title}</h4>
<p className="mt-1 text-sm leading-relaxed text-[#A1A1AA]">{event.detail}</p>
</div>
))
) : (
<div className="text-sm text-[#71717A]"></div>
)}
</div>
</div>
{/* Risk Factor Frequency */}
<div>
<h3 className="mb-6 text-lg font-medium text-white"></h3>
<div className="flex flex-wrap gap-2">
{riskFactorCounts.length > 0 ? (
riskFactorCounts.map((item) => (
<div
key={item.factor}
className="flex items-center gap-2 rounded-md border border-white/5 bg-white/[0.02] px-3 py-1.5 text-sm"
>
<span className="text-[#A1A1AA]">{item.factor}</span>
<span className="rounded bg-white/10 px-1.5 py-0.5 text-xs tabular-nums text-white">
{item.count}
</span>
</div>
))
) : (
<div className="text-sm text-[#71717A]"></div>
)}
</div>
</div>
</div>
</section>
{/* Divider */}
<hr className="my-12 border-white/5" />
{/* Device Table */}
<section className="animate-fade-up delay-500 mb-12">
<div className="mb-6 flex items-end justify-between">
<div>
<h3 className="text-xl font-medium text-white"></h3>
<p className="mt-1 text-sm text-[#A1A1AA]"> 30/60/90 </p>
</div>
</div>
<div className="overflow-x-auto rounded-xl border border-white/[0.06] bg-white/[0.02]">
<table className="w-full min-w-[1000px] border-collapse text-left text-sm">
<thead>
<tr className="border-b border-white/10 bg-white/[0.02] text-[#A1A1AA]">
<th className="px-6 py-4 font-medium"></th>
<th className="px-6 py-4 font-medium"></th>
<th className="px-6 py-4 font-medium"> SoH</th>
<th className="px-6 py-4 font-medium">30</th>
<th className="px-6 py-4 font-medium">90</th>
<th className="px-6 py-4 font-medium"></th>
<th className="px-6 py-4 font-medium"></th>
<th className="px-6 py-4 font-medium"></th>
</tr>
</thead>
<tbody className="divide-y divide-white/5">
{devices.length > 0 ? (
devices
.slice()
.sort((a, b) => b.riskScore - a.riskScore)
.map((unit) => (
<tr key={unit.id} className="transition-colors hover:bg-white/[0.04]">
<td className="px-6 py-4 font-medium text-white">{unit.id}</td>
<td className="px-6 py-4 text-[#A1A1AA]">{unit.batch}</td>
<td className="px-6 py-4 tabular-nums text-white">{unit.soh.toFixed(1)}%</td>
<td className="px-6 py-4 tabular-nums text-[#A1A1AA]">{unit.soh30d.toFixed(1)}%</td>
<td className="px-6 py-4 tabular-nums text-[#A1A1AA]">{unit.soh90d.toFixed(1)}%</td>
<td className="px-6 py-4">
<div className="flex items-center gap-2">
<div className="h-1.5 w-12 overflow-hidden rounded-full bg-white/5">
<div
className={`h-full rounded-full ${
unit.riskScore >= 75
? 'bg-red-400'
: unit.riskScore >= 45
? 'bg-amber-400'
: 'bg-emerald-400'
}`}
style={{ width: `${unit.riskScore}%` }}
/>
</div>
<span className="tabular-nums text-white">{unit.riskScore}</span>
</div>
</td>
<td className="px-6 py-4">
<span className={statusColorMap[unit.status]}>{unit.status}</span>
</td>
<td className="px-6 py-4">
<div className="flex flex-wrap gap-1.5">
{unit.riskFactors.length > 0 ? (
unit.riskFactors.map((factor) => (
<span key={factor} className="text-[#A1A1AA]">
{factor}
{factor !== unit.riskFactors[unit.riskFactors.length - 1] && '、'}
</span>
))
) : (
<span className="text-[#71717A]">-</span>
)}
</div>
</td>
</tr>
))
) : (
<tr>
<td colSpan={8} className="px-6 py-8 text-center text-[#71717A]">
</td>
</tr>
)}
</tbody>
</table>
</div>
</section>
{/* Bottom Row */}
<section className="animate-fade-up delay-500 grid grid-cols-1 gap-8 lg:grid-cols-3">
{/* Strategy Cards */}
<div className="lg:col-span-2">
<h3 className="mb-6 text-lg font-medium text-white"></h3>
<div className="grid gap-4 sm:grid-cols-2">
{strategies.length > 0 ? (
strategies.map((item, index) => (
<div
key={item.name}
className="relative overflow-hidden rounded-xl border border-white/[0.06] bg-white/[0.02] p-5"
>
<div
className={`absolute bottom-0 left-0 top-0 w-1 ${index === 0 ? 'bg-red-400' : index === 1 ? 'bg-amber-400' : 'bg-teal-400'}`}
/>
<h4 className="font-medium text-white">{item.name}</h4>
<p className="mt-2 text-sm text-[#A1A1AA]">{item.impact}</p>
<div className="mt-4 flex flex-wrap gap-4 text-xs text-[#71717A]">
<span>: {item.scope}</span>
<span>: {item.eta}</span>
</div>
</div>
))
) : (
<div className="text-sm text-[#71717A] col-span-2"></div>
)}
</div>
</div>
{/* Firmware Comparison */}
<div>
<h3 className="mb-6 text-lg font-medium text-white"></h3>
<div className="rounded-xl border border-white/[0.06] bg-white/[0.02] p-5">
<div className="space-y-4">
{firmwareHealth.length > 0 ? (
firmwareHealth.map((item) => (
<div key={item.firmware} className="flex items-center justify-between">
<div>
<div className="text-sm font-medium text-white">{item.firmware}</div>
<div className="text-xs text-[#71717A]">{item.count} </div>
</div>
<div className="text-right">
<div className="text-sm tabular-nums text-white">{item.avgSoh.toFixed(1)}%</div>
<div className="text-xs text-[#71717A]"> SoH</div>
</div>
</div>
))
) : (
<div className="text-sm text-[#71717A]"></div>
)}
</div>
</div>
</div>
</section>
</div>
</main>
)
}
+3
View File
@@ -0,0 +1,3 @@
export interface BaseContext {
headers: Headers
}
@@ -0,0 +1,13 @@
import { oc } from '@orpc/contract'
import { z } from 'zod'
import { batteriesResponseSchema, dashboardSnapshotSchema } from '@/domain/battery'
export const dashboard = oc.input(z.void()).output(dashboardSnapshotSchema)
export const batteries = oc
.input(
z.object({
mac: z.string().min(1).optional(),
}),
)
.output(batteriesResponseSchema)
@@ -1,7 +1,7 @@
import * as todo from './todo.contract'
import * as battery from './battery.contract'
export const contract = {
todo,
battery,
}
export type Contract = typeof contract
@@ -1,13 +1,19 @@
import { ORPCError, ValidationError } from '@orpc/server'
import { z } from 'zod'
import { getLogger } from '@/server/logger'
const logger = getLogger(['api'])
export const logError = (error: unknown) => {
console.error(error)
logger.error('Unhandled error in ORPC handler', { error })
}
export const handleValidationError = (error: unknown) => {
if (error instanceof ORPCError && error.code === 'BAD_REQUEST' && error.cause instanceof ValidationError) {
// If you only use Zod you can safely cast to ZodIssue[] (per ORPC official docs)
if (!(error instanceof ORPCError) || !(error.cause instanceof ValidationError)) return
if (error.code === 'BAD_REQUEST') {
// ORPC widens issues to the Standard Schema shape; contracts here are built from Zod.
// Rehydrate to reuse z.prettifyError / z.flattenError.
const zodError = new z.ZodError(error.cause.issues as z.core.$ZodIssue[])
throw new ORPCError('INPUT_VALIDATION_FAILED', {
@@ -18,7 +24,7 @@ export const handleValidationError = (error: unknown) => {
})
}
if (error instanceof ORPCError && error.code === 'INTERNAL_SERVER_ERROR' && error.cause instanceof ValidationError) {
if (error.code === 'INTERNAL_SERVER_ERROR') {
throw new ORPCError('OUTPUT_VALIDATION_FAILED', {
cause: error.cause,
})
+15
View File
@@ -0,0 +1,15 @@
import { createBatteriesResponse, createDashboardSnapshot } from '@/domain/battery'
import { os } from '@/server/api/server'
import { getBatteryHistory, getLatestBatteryPerDevice } from '@/server/battery/mysql'
export const dashboard = os.battery.dashboard.handler(async () => {
const items = await getLatestBatteryPerDevice()
return createDashboardSnapshot(items)
})
export const batteries = os.battery.batteries.handler(async ({ input }) => {
const items = input.mac ? await getBatteryHistory(input.mac) : await getLatestBatteryPerDevice()
return createBatteriesResponse(items)
})
+6
View File
@@ -0,0 +1,6 @@
import { os } from '@/server/api/server'
import * as battery from './battery.router'
export const router = os.router({
battery,
})
+5
View File
@@ -0,0 +1,5 @@
import type { ContractRouterClient, InferContractRouterOutputs } from '@orpc/contract'
import type { Contract } from './contracts'
export type RouterClient = ContractRouterClient<Contract>
export type RouterOutputs = InferContractRouterOutputs<Contract>
+75
View File
@@ -0,0 +1,75 @@
import mysql, { type Pool, type RowDataPacket } from 'mysql2/promise'
import { type BatteryInfo, type BatteryInfoSourceRow, toBatteryInfo } from '@/domain/battery'
import { env } from '@/env'
const historyLimit = 500
type BatteryInfoMysqlRow = RowDataPacket & BatteryInfoSourceRow
let pool: Pool | undefined
function getBatteryPool() {
pool ??= mysql.createPool({
uri: env.DATABASE_URL,
waitForConnections: true,
connectionLimit: 5,
namedPlaceholders: true,
})
return pool
}
export async function closeBatteryPool() {
if (!pool) return
await pool.end()
pool = undefined
}
const sourceColumns = `
id,
user_id AS userId,
mac,
dev_model AS devModel,
dev_name AS devName,
is_low_power AS isLowPower,
power_status AS powerStatus,
power,
create_time AS createTime,
remark
`
export async function getBatteryHistory(mac: string): Promise<BatteryInfo[]> {
const [rows] = await getBatteryPool().query<BatteryInfoMysqlRow[]>(
`
SELECT ${sourceColumns}
FROM ls_battery_info
WHERE mac = :mac
ORDER BY create_time DESC, id DESC
LIMIT :limit
`,
{ mac, limit: historyLimit },
)
return rows.map(toBatteryInfo)
}
export async function getLatestBatteryPerDevice(): Promise<BatteryInfo[]> {
const [rows] = await getBatteryPool().query<BatteryInfoMysqlRow[]>(`
SELECT ${sourceColumns}
FROM ls_battery_info AS current_record
WHERE NOT EXISTS (
SELECT 1
FROM ls_battery_info AS newer_record
WHERE newer_record.mac = current_record.mac
AND (
newer_record.create_time > current_record.create_time
OR (newer_record.create_time = current_record.create_time AND newer_record.id > current_record.id)
)
)
ORDER BY current_record.create_time DESC, current_record.id DESC
`)
return rows.map(toBatteryInfo)
}
+19
View File
@@ -0,0 +1,19 @@
import { configureSync, getConfig, getConsoleSink, getJsonLinesFormatter } from '@logtape/logtape'
import { prettyFormatter } from '@logtape/pretty'
import { env } from '@/env'
if (getConfig() === null) {
const format = env.LOG_FORMAT ?? (process.stdout.isTTY ? 'pretty' : 'json')
configureSync({
sinks: {
console: getConsoleSink({ formatter: format === 'pretty' ? prettyFormatter : getJsonLinesFormatter() }),
},
loggers: [
{ category: [], lowestLevel: env.LOG_LEVEL, sinks: ['console'] },
{ category: ['logtape', 'meta'], lowestLevel: 'warning', sinks: ['console'], parentSinks: 'override' },
],
})
}
export { getLogger } from '@logtape/logtape'
+30
View File
@@ -0,0 +1,30 @@
import { closeBatteryPool } from '@/server/battery/mysql'
import { getLogger } from '@/server/logger'
export default () => {
if (import.meta.dev) return
const logger = getLogger(['shutdown'])
let exiting = false
const shutdown = async (signal: NodeJS.Signals) => {
if (exiting) {
logger.warn('Forcing exit on repeated signal', { signal })
process.exit(0)
}
exiting = true
logger.info('Draining for shutdown', { signal, graceMs: 500 })
await Bun.sleep(500)
try {
await closeBatteryPool()
logger.info('Battery MySQL pool closed, exiting')
} catch (error) {
logger.error('DB pool close failed during shutdown', { error })
}
process.exit(0)
}
process.on('SIGINT', () => void shutdown('SIGINT'))
process.on('SIGTERM', () => void shutdown('SIGTERM'))
}
@@ -1,9 +1,8 @@
{
"$schema": "https://json.schemastore.org/tsconfig",
"display": "Base",
"compilerOptions": {
"target": "esnext",
"lib": ["ESNext"],
"lib": ["ESNext", "DOM", "DOM.Iterable"],
"module": "preserve",
"skipLibCheck": true,
@@ -22,7 +21,12 @@
"noUncheckedIndexedAccess": true,
"noImplicitOverride": true,
"types": ["bun"]
"jsx": "react-jsx",
"types": ["bun"],
"paths": {
"@/*": ["./src/*"]
}
},
"exclude": ["node_modules"]
"exclude": ["node_modules", ".output", "out"]
}
-22
View File
@@ -1,22 +0,0 @@
{
"$schema": "./node_modules/turbo/schema.json",
"dangerouslyDisablePackageManagerCheck": true,
"globalDependencies": ["bun.lock"],
"tasks": {
"build": {
"dependsOn": ["^build"]
},
"dev": {
"cache": false,
"persistent": true
},
"fix": {
"cache": false
},
"typecheck": {
"inputs": ["package.json", "tsconfig.json", "tsconfig.*.json", "**/*.{ts,tsx,d.ts}"],
"outputs": []
}
},
"ui": "tui"
}
@@ -15,13 +15,10 @@ export default defineConfig({
nitro({
preset: 'bun',
serveStatic: 'inline',
plugins: ['./src/server/plugins/shutdown.ts'],
}),
],
resolve: {
tsconfigPaths: true,
},
server: {
port: 3000,
strictPort: true,
},
})