Compare commits
1
Commits
787544eec1
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4ff9146910 |
No files matched your search
@@ -3,12 +3,23 @@
|
|||||||
# ---- 编辑验证(M2 使用)----
|
# ---- 编辑验证(M2 使用)----
|
||||||
ADMIN_PASSWORD=change-me
|
ADMIN_PASSWORD=change-me
|
||||||
SESSION_SECRET=请替换为随机长字符串
|
SESSION_SECRET=请替换为随机长字符串
|
||||||
|
# 生产环境走 HTTPS 时设为 1;本地 http 调试保持 0
|
||||||
|
COOKIE_SECURE=0
|
||||||
|
# 站点在反向代理 / CDN 之后时设为 1:登录限速改按 X-Forwarded-For 首段计数,
|
||||||
|
# 避免所有访问者共享代理 IP 的同一个限速桶。仅在有可信代理时开启,否则该头可被伪造。
|
||||||
|
TRUST_PROXY=0
|
||||||
|
|
||||||
# ---- AI(OpenAI 兼容协议)----
|
# ---- AI(OpenAI 兼容协议)----
|
||||||
AI_BASE_URL=https://api.deepseek.com/v1
|
AI_BASE_URL=https://api.deepseek.com/v1
|
||||||
AI_API_KEY=
|
AI_API_KEY=
|
||||||
AI_MODEL=deepseek-chat
|
AI_MODEL=deepseek-chat
|
||||||
|
# Tavily 兼容搜索;不填时使用 Bing / Baidu / DuckDuckGo 公开检索 + ZOL / GSMArena 站内直查 + 白名单站点抓取
|
||||||
SEARCH_API_KEY=
|
SEARCH_API_KEY=
|
||||||
|
SEARCH_BASE_URL=https://api.tavily.com
|
||||||
|
# 可选:B 站登录态(浏览器 F12 → Application → Cookies → SESSDATA)。
|
||||||
|
# 配置后拆机视频补全会拉取视频字幕全文(马达型号、扬声器单元等细节主要在口播里);
|
||||||
|
# 不配置时仅能拿到视频标题和简介。SESSDATA 有效期较长,失效后字幕拉不到但不报错。
|
||||||
|
BILIBILI_SESSDATA=
|
||||||
|
|
||||||
# ---- 存储 ----
|
# ---- 存储 ----
|
||||||
# local | s3
|
# local | s3
|
||||||
|
|||||||
@@ -556,10 +556,10 @@ interface StorageDriver {
|
|||||||
|---|---|---|
|
|---|---|---|
|
||||||
| M0 | 脚手架、Tailwind、shadcn PoC(3 个组件)、zod schema、storage 驱动、repo 层 | 能跑的空站 |
|
| M0 | 脚手架、Tailwind、shadcn PoC(3 个组件)、zod schema、storage 驱动、repo 层 | 能跑的空站 |
|
||||||
| M1 | 只读:手机列表/详情、芯片库、搜索筛选 + sitemap、JSON-LD | 可看、可收录的站 |
|
| M1 | 只读:手机列表/详情、芯片库、搜索筛选 + sitemap、JSON-LD | 可看、可收录的站 |
|
||||||
| M2 | 编辑:登录、表单(含字段级徽章)、图片上传、修订记录 | 可维护 |
|
| M2 | 编辑:登录、表单(含字段级徽章)、图片上传、修订记录 | 可维护(✅ 已完成,本地验证) |
|
||||||
| M3 | AI 分级补全(high 自动 / medium 标黄 / low 阻塞)+ 差异预览 | 录入效率 |
|
| M3 | AI 分级补全(high 自动 / medium 标黄 / low 阻塞)+ 差异预览 | 录入效率(✅ 已完成,mock + 浏览器验证) |
|
||||||
| M4 | 对比页(差异高亮、只看差异、条形可视化)、导出导入、备份脚本 | 完整闭环 |
|
| M4 | 对比页(差异高亮、只看差异、条形可视化)、导出导入、备份脚本 | 完整闭环(✅ 已完成,本地验证) |
|
||||||
| M5 | 动效打磨、OG 图、打印样式、部署上线 | 成品 |
|
| M5 | 动效打磨、OG 图、打印样式、部署上线 | 成品(✅ 本地完成,线上部署待执行) |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -617,7 +617,7 @@ M0 完成标志:**本地 `docker compose up` 能打开首页,`/devices` 与
|
|||||||
- 筛选与排序:品牌 chip 列表 + 最新发布 / 按型号 / 按品牌三种排序,全部是 GET 链接
|
- 筛选与排序:品牌 chip 列表 + 最新发布 / 按型号 / 按品牌三种排序,全部是 GET 链接
|
||||||
- 品牌页:`/brands`、`/brands/[brand]`(品牌参数 URL 编码 + `decodeURIComponent`)
|
- 品牌页:`/brands`、`/brands/[brand]`(品牌参数 URL 编码 + `decodeURIComponent`)
|
||||||
- SEO:`/sitemap.xml` 动态端点(首页 / 列表 / 详情 / 芯片 / 品牌全覆盖)、`robots.txt`、详情页 `Product` JSON-LD、`site` 固定为 `https://specs.atie.fun`
|
- SEO:`/sitemap.xml` 动态端点(首页 / 列表 / 详情 / 芯片 / 品牌全覆盖)、`robots.txt`、详情页 `Product` JSON-LD、`site` 固定为 `https://specs.atie.fun`
|
||||||
- 详情页补充:上市日期、生命周期、标签、字段级来源列表(按 confidence 着色,low 显示红色)
|
- 详情页补充:上市日期、生命周期、标签、字段级来源列表(只对 low 显示徽章与 hover 说明,high/medium 不常驻标记,见 11.11)
|
||||||
- 验证:本地 `pnpm build` 通过;线上 10 个路由与筛选组合均为 200,sitemap 与 JSON-LD 内容正确
|
- 验证:本地 `pnpm build` 通过;线上 10 个路由与筛选组合均为 200,sitemap 与 JSON-LD 内容正确
|
||||||
|
|
||||||
### 11.5 运行环境与踩坑记录(供换机后参考)
|
### 11.5 运行环境与踩坑记录(供换机后参考)
|
||||||
@@ -647,17 +647,366 @@ M0 完成标志:**本地 `docker compose up` 能打开首页,`/devices` 与
|
|||||||
- `8430e53` M0 脚手架(已推送)
|
- `8430e53` M0 脚手架(已推送)
|
||||||
- `0c30c79` M1 只读增强(已推送)
|
- `0c30c79` M1 只读增强(已推送)
|
||||||
- `22aa0ef` 部署方式改为宿主构建 + 挂载(**本地已提交,待 `git push`**)
|
- `22aa0ef` 部署方式改为宿主构建 + 挂载(**本地已提交,待 `git push`**)
|
||||||
|
- 当前工作区:M2 编辑后台、M3 AI 补全、M4 对比 / 导入导出(未提交)
|
||||||
|
|
||||||
**线上**
|
**线上**
|
||||||
- `https://specs.atie.fun` 待用户配置反代(目标 `127.0.0.1:3010`)
|
- `https://specs.atie.fun` 待用户配置反代(目标 `127.0.0.1:3010`)
|
||||||
- 可直接访问 `http://<ECS>:3010`(需安全组放行)或内网/Tailscale 地址
|
- 可直接访问 `http://<ECS>:3010`(需安全组放行)或内网/Tailscale 地址
|
||||||
|
|
||||||
**下一步(M2 起)**
|
**下一步(收尾)**
|
||||||
1. M2 编辑后台:登录(`ADMIN_PASSWORD` + 签名 cookie)、设备/芯片表单、图片上传(`storage.ts`)、`revisions` 修订记录
|
1. 提交并推送 M2–M5,按 `scripts/deploy.sh` 部署到 ECS
|
||||||
2. M3 AI 分级补全:`/api/ai/lookup` 返回扁平字段 + 置信度,表单按 high/medium/low 着色,low 阻塞保存
|
2. 线上验收:OG 图、打印样式、对比页、导入导出、AI 真实供应商
|
||||||
3. M4 对比页(差异高亮、只看差异、数值条形化)、`/api/export` + `/admin/import`
|
3. 可选增强:对比页增加“复制链接 / 分享”按钮、更多数值字段的归一化评分
|
||||||
4. M5 动效打磨、OG 图、打印样式
|
4. 换机续作时先执行 `pnpm install`(注意 `.npmrc` 的 hoisted 配置),再 `pnpm db:seed` 起本地数据
|
||||||
5. 换机续作时先执行 `pnpm install`(注意 `.npmrc` 的 hoisted 配置),再 `pnpm db:seed` 起本地数据
|
|
||||||
|
### 11.7 M2 实施记录(已完成,本地验证)
|
||||||
|
|
||||||
|
**登录与保护**
|
||||||
|
- `src/lib/auth.ts`:`ADMIN_PASSWORD` 常量时间比较(sha256 后 `timingSafeEqual`),`SESSION_SECRET` 签发 HS256 JWT,7 天有效
|
||||||
|
- Cookie:`HttpOnly` + `SameSite=Lax` + `Path=/`,`COOKIE_SECURE=1` 时加 `Secure`
|
||||||
|
- 登录失败按 IP 限速:1 分钟内 3 次后返回 `?error=rate`
|
||||||
|
- `src/middleware.ts` 拦截 `/admin/**`,未登录跳 `/admin?next=...`
|
||||||
|
- 写接口统一 `guardWrite`:登录态 + 同源校验;`/api/auth/logout` 直接清 cookie
|
||||||
|
|
||||||
|
**页面与接口**
|
||||||
|
- `/admin`:未登录显示登录表单,已登录显示仪表盘(设备/芯片列表、最近修订、新增入口)
|
||||||
|
- `/admin/devices/[slug]`(`new` 为新增)、`/admin/chips/[slug]`:React island 表单
|
||||||
|
- 设备表单:基本信息、SoC 引用、封面图上传、9 个规格分组、前后摄逐颗增删、扬声器单元增删、扩展字段 JSON、字段来源徽章与“已核实”勾选
|
||||||
|
- 芯片表单:基本信息、GPU/NPU/ISP/DSP/基带、内存存储显示支持、编解码;核心簇/跑分/扩展字段用 JSON
|
||||||
|
- `POST /api/devices`、`POST /api/chips`:zod 校验,`?create=1` 时 slug 冲突返回 409,成功返回完整实体
|
||||||
|
- `POST /api/upload`:登录 + 同源,允许 jpg/png/webp/avif,≤10MB,key 形如 `devices/<slug>/<时间戳>-<随机>.<ext>`
|
||||||
|
|
||||||
|
**修订记录**
|
||||||
|
- `saveDevice` / `saveChip` 与 `revisions` 插入放在同一事务;保存失败整体回滚
|
||||||
|
- 修订存保存后的完整快照;编辑页展示最近 10 条(`diff_json` 暂留空,回滚 UI 未做)
|
||||||
|
|
||||||
|
**安全配置**
|
||||||
|
- 关闭 Astro 内置 `security.checkOrigin`:`@astrojs/node` 在未配置 `allowedDomains` 时会把 `request.url` 的 origin 回退到 `localhost`,导致反代后的表单提交被误判跨站
|
||||||
|
- 自实现 `sameOrigin`:把 `Origin` 的 host 与 `Host` / `X-Forwarded-Host` 比对;所有写接口均已接入
|
||||||
|
|
||||||
|
**验证**
|
||||||
|
- `pnpm typecheck`、`pnpm build` 通过
|
||||||
|
- 用独立验证库(`DB_PATH=data/verify.db`、`UPLOADS_DIR=data/verify-uploads`)启动 standalone 产物:`node dist/server/entry.mjs`
|
||||||
|
- 未登录访问编辑页 302 到登录;无 cookie 写接口 401;错误 Origin 403;空 payload 400;重复 slug 409
|
||||||
|
- 登录成功后保存设备/芯片,前台详情同步更新;`revisions` 生成快照;图片上传后 `/uploads/<key>` 返回 200 与正确 content-type
|
||||||
|
- 浏览器端到端:登录 → 仪表盘 → 编辑 Xiaomi 14 → 修改简介 → 保存 → 出现“已保存”
|
||||||
|
- 连续 3 次错误密码后第 4 次正确密码返回 `?error=rate`
|
||||||
|
- 本机受限沙箱内 `astro dev` 首次 SSR 模块读取耗时 90s+ 并触发 `transport invoke timed out`,故本地验证走生产构建产物;普通终端如遇同样问题可用 `pnpm build && node dist/server/entry.mjs`
|
||||||
|
|
||||||
|
### 11.8 M3 实施记录(已完成,mock + 浏览器验证)
|
||||||
|
|
||||||
|
**字段注册表**
|
||||||
|
- 新增 `src/lib/spec-fields.ts`:手机规格分组、摄像头字段、扬声器字段、路径读写(支持 `rearCamera[0].sensorModel` 这类扁平路径)、字段标签、AI 白名单判定
|
||||||
|
- `DeviceEditor` 改为从注册表渲染,不再内嵌字段定义
|
||||||
|
|
||||||
|
**AI 管线(`src/lib/ai/`)**
|
||||||
|
- `search.ts`:Tavily 兼容搜索,取前 5 条(标题 / URL / 内容摘要);未配置 key、无结果、请求失败都降级为模型知识并返回提示
|
||||||
|
- `prompt.ts`:系统提示要求只输出 JSON;用户提示注入品牌、型号、白名单路径、资料正文;明确 high/medium/low 判定与“无资料不得 high”
|
||||||
|
- `lookup.ts`:OpenAI 兼容 `chat/completions`(`response_format: json_object`,120s 超时),解析失败自动修复一轮
|
||||||
|
- 字段校验:只接受注册表白名单;bool / number / list / position 强转;非法路径与类型丢弃;`sourceUrl` 必须命中本次搜索 URL,否则丢来源并把 high 降为 medium;无搜索时 high 统一降 medium;按 high→medium→low 排序,最多 200 项
|
||||||
|
- 缓存:按 `phone|品牌|型号` 写入 `ai_cache`;支持 `force` 绕过并覆盖缓存
|
||||||
|
- `apply.ts`:把扁平字段合入设备 specs(摄像头 / 扬声器单元自动补槽),同步写 `meta[]`(confidence / sourceUrl / verified=false / capturedAt);提供清空字段与展示格式化
|
||||||
|
|
||||||
|
**接口与阻塞**
|
||||||
|
- `POST /api/ai/lookup`:登录 + 同源,参数 zod 校验;未配置返回 503,模型/搜索异常返回 502
|
||||||
|
- 保存接口(设备 / 芯片)新增服务端 low 检查:存在 low 且未核实且有值的字段时返回 400,附带 `path` 列表
|
||||||
|
- 前端保存前同样检查;底部显示待核对清单,可「确认全部 low」「清空全部 low」;来源区支持「全部接受 high」
|
||||||
|
|
||||||
|
**表单交互**
|
||||||
|
- 基本信息后新增 AI 补全区:品牌/型号、忽略缓存、加载态、错误提示
|
||||||
|
- 结果预览逐项显示字段标签、置信度徽章、当前值 → AI 值、是否有变化、来源链接
|
||||||
|
- 默认全选,可逐项取消;应用后写入表单与 meta,字段右侧徽章立即更新
|
||||||
|
|
||||||
|
**验证**
|
||||||
|
- `pnpm typecheck`、`pnpm build` 通过
|
||||||
|
- 本地 mock 服务同时模拟 Tavily `/search` 与 OpenAI `/v1/chat/completions`,用独立验证库跑 standalone 产物
|
||||||
|
- 返回 10 个字段:真实来源的 high 保留;伪造来源的 high 丢来源并降 medium;无来源 high 降 medium;`specs.evil` 被丢弃;`speakers.count` 字符串 "2" 转为数字 2
|
||||||
|
- 第二次请求 `cached=true`;`force=true` 返回 `cached=false`;`ai_cache` 只有一条记录
|
||||||
|
- 无 AI 配置的服务实例返回 503,并列出缺失变量
|
||||||
|
- 种子设备的 low 字段使保存返回 400;把该字段 `verified` 置 true 后保存 200
|
||||||
|
- 浏览器端到端:登录 → Xiaomi 14 → AI 补全 → 预览 high 2 / medium 7 / low 1 → 应用 10 个字段 → 保存被客户端拦截 → 确认全部 low → 保存成功(`?saved=1`,修订 #2)
|
||||||
|
- 保存后核对数据库:刷新率 144Hz、电池 5000mAh、配色数组、`rearCamera[1]` 更新为 tele + S5KJN1、扬声器数量 2,meta 来源与置信度完整
|
||||||
|
|
||||||
|
### 11.9 M4 实施记录(已完成,本地验证)
|
||||||
|
|
||||||
|
**对比页**
|
||||||
|
- `/compare`:无 ids 或不足 2 款时显示选择器;支持 `?ids=a,b` 与重复 `ids=a&ids=b`;校验 2–4 款、同类目、slug 存在
|
||||||
|
- `src/lib/compare.ts` 从字段注册表生成分组;后置影像按位置(主摄/超广角/长焦/潜望/微距/景深/黑白)分组,前置单独;扬声器单元聚合
|
||||||
|
- 差异高亮(圆点 + 行底色),缺失值 `—` 置灰;`?diff=1` 只看差异
|
||||||
|
- 每组 `<details>` 可折叠;首列 sticky;横向滚动
|
||||||
|
- 数值条形:重量、屏幕尺寸、典型/峰值亮度、刷新率、电池容量、有线/无线充电、扬声器数量;宽度按组内最大值归一
|
||||||
|
- 导航加入「对比」,详情页加入「加入对比」,选择器自动预选
|
||||||
|
|
||||||
|
**导出**
|
||||||
|
- `GET /api/export` 公开下载,`formatVersion: 1`,包含 devices / chips / exportedAt / generator
|
||||||
|
- `content-disposition` 文件名带时间戳,`cache-control: no-store`
|
||||||
|
|
||||||
|
**导入**
|
||||||
|
- `POST /api/import`:登录 + 同源;支持 JSON body 或 multipart(`file` / `json` 字段)
|
||||||
|
- 格式 `{formatVersion:1, devices, chips}`;逐条 zod 校验,全部通过才进入事务
|
||||||
|
- `repo.importEntities` 在同一事务内 upsert,任一失败回滚;保留 created_at,更新 updated_at,并写 revisions
|
||||||
|
- 上限 5000 条 / 20MB;错误返回带 `path` 的 issues
|
||||||
|
- `/admin/import` 页面:选择文件或粘贴 JSON、格式化、错误列表、导入结果;仪表盘加入导入/导出入口
|
||||||
|
|
||||||
|
**备份**
|
||||||
|
- 复用 `pnpm backup`:`VACUUM INTO` 生成一致性 DB 快照 + 复制 uploads;本次用验证库跑通并确认快照可查询
|
||||||
|
|
||||||
|
**验证**
|
||||||
|
- `pnpm typecheck`、`pnpm build` 通过
|
||||||
|
- 导出返回 formatVersion=1、devices=1、chips=1
|
||||||
|
- 将导出 JSON 克隆出 Xiaomi 14 Pro(改 slug/型号/尺寸/重量/电池/主摄)后导入,返回 devices=2/chips=1;前台详情与对比页均 200
|
||||||
|
- `/compare`(空 / 1 款)显示选择器;2 款对比页含字段列、差异圆点、数值条、分组;`diff=1` 从 10 项缩到 6 项
|
||||||
|
- 浏览器验证:表头与两款机型、只看差异切换、数值条、分组折叠均通过
|
||||||
|
- 脏数据导入 400(4 处 issue),未写入合法的那一半(`/devices/should-not-exist` 仍 404)
|
||||||
|
- formatVersion=2 返回 400;未登录导入 401
|
||||||
|
- 备份脚本产出 `backups/<时间戳>/app.db` 快照
|
||||||
|
|
||||||
|
### 11.10 M5 实施记录(本地完成,线上部署待执行)
|
||||||
|
|
||||||
|
**动效**
|
||||||
|
- BaseLayout 引入 Astro `<ClientRouter />`,`<main transition:animate="fade">` 做页面淡入
|
||||||
|
- 列表网格加 `.reveal-grid`:CSS `reveal-up` 0.35s + 40ms 级联(最多 8 个),无额外 JS
|
||||||
|
- `prefers-reduced-motion: reduce` 下关闭列表动画与 View Transition 动画;未引入 GSAP / Lenis
|
||||||
|
|
||||||
|
**OG 图**
|
||||||
|
- 新增 `src/pages/og/[slug].png.ts`:设备 slug 生成 1200×630 PNG,`site` 为通用站点卡;未知 slug 404,进程内缓存 5 分钟
|
||||||
|
- `src/lib/og.ts`:SVG 卡片模板 + sharp(density 72)转 PNG;设备卡展示品牌型号、生命周期、SoC / 屏幕 / 电池 / 重量
|
||||||
|
- OG 文字只用 Latin 字符(型号/芯片名含中文时回退 slug,尺寸/电池/重量抽取数字后统一单位),避免容器缺中文字体出现方框
|
||||||
|
- BaseLayout 输出 canonical、`og:type/title/description/url/image`、`og:image:alt`、`twitter:summary_large_image`
|
||||||
|
- 设备详情页传入 `/og/<slug>.png` 与 canonical 路径;其他页面默认 `/og/site.png`
|
||||||
|
|
||||||
|
**打印**
|
||||||
|
- 全局 `@media print`:浅色配色、隐藏 `.print-hidden`(导航、页脚、操作按钮)、取消 sticky / 横向滚动 / 阴影、`break-inside: avoid`
|
||||||
|
- 设备详情页加「打印 / 保存 PDF」按钮,调用 `window.print()`
|
||||||
|
- 对比页的切换按钮与面包屑打印时隐藏
|
||||||
|
|
||||||
|
**主题与交互细节(反馈修正)**
|
||||||
|
- 黑白主题通过 `html[data-theme]` + 同一套语义变量实现;右上角按钮切换,`localStorage` 记忆,首次访问跟随系统
|
||||||
|
- 头部主题脚本在 `<head>` 内联执行,避免首屏闪烁;切换按钮用事件委托,ClientRouter 导航后仍有效
|
||||||
|
- ClientRouter 换页会带入服务端渲染的 `<html data-theme="dark">`,因此监听 `astro:before-swap` / `astro:after-swap` / `astro:page-load`,把 `localStorage` 中的选择重新写回,避免跨页后主题失效
|
||||||
|
- 详情页关键参数卡、影像卡、规格表行增加 hover:行底色 + 字段名切强调色
|
||||||
|
- 修复手机列表卡嵌套 `<a>` 导致的布局错乱:卡片改为单一链接,品牌改为纯文本,卡片恢复紧凑网格布局
|
||||||
|
|
||||||
|
**部署**
|
||||||
|
- `sharp` 升为直接依赖
|
||||||
|
- 标准 Dockerfile runtime 阶段安装 `fontconfig` / `ttf-dejavu`
|
||||||
|
- 宿主构建 + `node:24-slim` 方案在 compose 中只读挂载宿主 `/usr/share/fonts` 与 `/etc/fonts`;线上主机需有 DejaVu 字体
|
||||||
|
|
||||||
|
**验证**
|
||||||
|
- `pnpm typecheck`、`pnpm build` 通过
|
||||||
|
- `/og/site.png`、`/og/xiaomi-14.png` 返回 200 / image/png / 1200×630,未知 slug 返回 404;读取 PNG 确认标题、四个参数卡与底部文字无重叠溢出
|
||||||
|
- 详情页 HTML 含 canonical、`og:type=article`、设备专属 `og:image`、twitter 卡;首页使用 `/og/site.png`
|
||||||
|
- 页面含 `astro-view-transitions-enabled`,列表页含 `.reveal-grid`,构建 CSS 含 `.print-hidden` 与 `reveal-up`
|
||||||
|
- 浏览器验证:首页卡片、手机列表、Xiaomi 14 详情、加入对比与打印按钮均正常;详情标题已去除“Xiaomi Xiaomi”重复
|
||||||
|
- 黑白主题实测:`data-theme` 与 `localStorage` 在 dark/light 间正确切换;手机列表卡恢复为正常紧凑卡片
|
||||||
|
- 跨页主题实测:`/devices` 切到 light 后进入 `/devices/xiaomi-14` 仍为 light,返回列表与整页刷新后也保持
|
||||||
|
- 详情页 hover 实测(dark / light 两套配色):规格行背景高亮、字段名变为强调色
|
||||||
|
- 未执行线上部署:需要先提交/推送代码,并在 ECS 安装/挂载字体后按 `scripts/deploy.sh` 上线
|
||||||
|
|
||||||
|
### 11.11 详情页参数展示改造(反馈修正)
|
||||||
|
|
||||||
|
**顶部参数卡**
|
||||||
|
- 从 6–8 张扩展到 19 张,分多排展示:SoC、屏幕、电池、主摄、超广角、长焦、影像场景、内存、存储、充电、无线充电、系统、马达、扬声器、Wi-Fi、USB、指纹、重量、防护
|
||||||
|
- 屏幕卡同时展示尺寸与分辨率,内存卡展示 RAM + 类型,充电卡展示有线/无线功率,USB 卡展示版本 + 实际速率
|
||||||
|
- 卡片改为 `<a href="#specs-…">`,点击平滑滚动到对应详细分组;分组与 `SoC` 卡均加 `scroll-mt-6`,避免被粘性头部遮挡
|
||||||
|
|
||||||
|
**详细参数**
|
||||||
|
- 分组拆为:外观、屏幕、平台、内存与存储、振动、扬声器、连接、电池与充电、传感器、系统与更新;前后摄单独分组
|
||||||
|
- 屏幕新增面板厂商 `display.vendor`(如 TCL 华星)与技术代号 `display.technology`(如 C8)
|
||||||
|
- 双扬声器按 `speakers.units[].position` 拆成“扬声器(上)/(下)”两行,分别展示型号、尺寸、功率
|
||||||
|
- 振动新增实际体积 `vibration.volume`
|
||||||
|
- 连接新增 `connectivity.bands`、`satellite`、`satelliteProvider`、`satelliteBands`、`usbSpeed`、`usbVideoOut`
|
||||||
|
- 系统新增 `software.currentVersion` 与 `software.updateTimeline`,更新时间线逐条展开为“更新记录 1/2…”
|
||||||
|
- 内存新增 `memory.storageSpeed`
|
||||||
|
|
||||||
|
**Hover 弹层与低置信度标记**
|
||||||
|
- 新增 `HoverInfo.astro`:连接分组内的“移动网络频段(N)”和“卫星通信频段”支持 hover / 键盘聚焦弹出面板;卫星面板显示运营商与频段 chip
|
||||||
|
- 新增 `LowBadge.astro`:只对 `confidence === 'low'` 渲染 `low` 徽章;hover / 聚焦显示字段名、路径、已核实/待核实、来源链接;`high` 与 `medium` 不标记
|
||||||
|
- 顶部卡片、影像字段、规格行与数据来源列表统一使用 `LowBadge`;数据来源列表移除了 high/medium/low 颜色标签,只保留核实状态与 low 徽章
|
||||||
|
|
||||||
|
**数据与后台**
|
||||||
|
- `phoneSpecsSchema` 与 `spec-fields.ts` 同步新增字段;AI 白名单、表单、路径读写自动覆盖
|
||||||
|
- 后台设备表单的 list 字段改用 `ListInput` 提交到 `specs`;`ListInput` 在外部值变化时同步输入框(AI 应用/回填)
|
||||||
|
- 扬声器单元行新增“位置”选择(上/下/左/右)
|
||||||
|
- `scripts/seed.mjs` 更新 Xiaomi 14 示例数据并重新执行 `pnpm db:seed`
|
||||||
|
|
||||||
|
**验证**
|
||||||
|
- `pnpm typecheck`、`pnpm build` 通过
|
||||||
|
- 顶部参数卡布局正常;点击“屏幕”卡后 `#specs-display` 滚动到距顶部约 24px
|
||||||
|
- 屏幕厂商/技术、上/下扬声器型号、马达体积、USB 速率/视频输出、系统更新记录均正确渲染
|
||||||
|
- “移动网络频段(18)”hover 正常显示 18 个频段
|
||||||
|
- 用临时数据库把 Xiaomi 14 改为卫星机型(天通 + T1/T2/T3),hover“卫星通信频段”正常显示运营商与频段 chip;验证后已删除临时库与测试服务器
|
||||||
|
- low 徽章 hover 显示“振动 · 马达型号 待核实”及来源;high 字段不再出现标记
|
||||||
|
|
||||||
|
### 11.12 对照“手机性能排行”补充参数(三扬声器 / 附加说明)
|
||||||
|
|
||||||
|
**数据修正(Xiaomi 14)**
|
||||||
|
- 屏幕比例改为 `20.0:9`,补 OLED 等效 PPI `375`,峰值亮度改称“局部峰值亮度”;屏幕特性补“柔性直屏”“支持类DC调光”
|
||||||
|
- 充电协议补 `QC2.0`
|
||||||
|
- 超广角补 `115°` 视场角;长焦改为 `2.6x 光学(60mm)/ 3.2x(75mm)`,对焦补“10cm 以上”
|
||||||
|
- 设备跑分补 GFXBench 曼哈顿 3.1 High、Aztec Ruins High 与综合效能;备注补玻璃版/素皮版的厚度与重量;补耳机接口说明
|
||||||
|
- SoC 补 `6 MB` 系统缓存
|
||||||
|
|
||||||
|
**新增字段与能力**
|
||||||
|
- 新增 `display.equivalentPpi`、`cameraModule.fov`、`socDetail.systemCache`
|
||||||
|
- 复用 `display.refreshNote` 表达附加说明,如“1-165Hz 自适应刷新率,最高支持 185Hz(185Hz 只在部分游戏场景生效)”
|
||||||
|
- `speakers.units[].label` 支持“上 / 下 / 中置 / 第三单元”等任意标识,`speakers.units` 可超过两个单元
|
||||||
|
|
||||||
|
**验证**
|
||||||
|
- 临时数据库将 Xiaomi 14 改为三扬声器(上 / 下 / 中置)并写入 185Hz `refreshNote`
|
||||||
|
- 页面正确渲染“扬声器(上 / 下 / 中置)”、顶部卡片“3 单元”、刷新附加说明、等效 PPI、视场角、系统缓存、QC2.0、GFXBench、备注与耳机接口
|
||||||
|
- `specs.benchmarks` 的 low 徽章 hover 正常显示说明;`pnpm typecheck`、`pnpm build` 通过;临时库与测试服务已删除
|
||||||
|
|
||||||
|
### 11.13 AI 添加设备与三机型排版优化
|
||||||
|
|
||||||
|
**AI 补全**
|
||||||
|
- `.env` 接入 DeepSeek(`AI_BASE_URL=https://api.deepseek.com/v1`、`AI_MODEL=deepseek-chat`);未配置 Tavily,仍可走模型知识
|
||||||
|
- 实测无参考资料时只返回 8 个泛化字段(且全为 low),不满足最新机型录入
|
||||||
|
- 编辑页「AI 补全」新增“补充参考资料”:官方链接 + 官网参数文本;后端 `sourceText` 随请求进入提示词,并参与缓存键,避免与无资料结果串缓存
|
||||||
|
- 提示词补全 `PHONE_TOP_LEVEL_FIELDS`(手机特点 / 影像功能 / 跑分 / 售价 / 官网),扬声器单元扩展到 `0..4`,要求逐单元用 `label` 区分上 / 下 / 中置 / 低音单元,附加条件写入 `display.refreshNote`
|
||||||
|
- 实测:K90 Pro Max 返回 76 个字段、Find X10 Pro Max 返回 80 个字段,均为 medium;应用后可用人工修正补齐
|
||||||
|
|
||||||
|
**新增设备**
|
||||||
|
- `redmi-k90-pro-max`:第五代骁龙 8 至尊版、6.9 英寸 120Hz、7560mAh、100W + 50W、BOSE 2.1 三扬声器(上 / 下 / 低音炮)、5x 潜望长焦
|
||||||
|
- `oppo-find-x10-pro-max`:天玑 9600 Pro、6.78 英寸 144Hz(1-120Hz 智能切换,144Hz 仅部分游戏)、8000mAh、80W + 50W、三颗 2 亿像素镜头 + 丹霞色彩镜头、冰河散热
|
||||||
|
- 新增 `scripts/seed-devices.json` 保存两台设备的完整规格,`seed.mjs` 改为按 slug 循环 upsert 三台设备
|
||||||
|
|
||||||
|
**排版**
|
||||||
|
- 顶部卡片改为等高、两行截断;电池 / 充电 / Wi-Fi / 相机使用短值,避免长文本溢出
|
||||||
|
- 卡片上方新增分组快捷导航
|
||||||
|
- 详情分区调整为:屏幕与外观 → 性能(SoC + 平台 + 内存 + 跑分)→ 影像 → 电池与充电 → 音频与振动 → 连接与网络 → 传感器 → 系统与更新 → 售价与补充
|
||||||
|
- 分区加编号与分组小标题,表格包进圆角卡片;相机位置改为中文标签,新增 `color`(色彩镜头)枚举与标签
|
||||||
|
- 未关联芯片库的设备显示“芯片库暂未收录”,不再出现空白性能区
|
||||||
|
|
||||||
|
**验证**
|
||||||
|
- 三台设备详情页 200;卡片、快捷导航、分区顺序、K90 三扬声器、OPPO 色彩镜头均正常
|
||||||
|
- K90 / OPPO 数据来源从 76/80 条字段级记录收敛为 1 条整机来源 + 售价记录
|
||||||
|
- `pnpm typecheck`、`pnpm build`、`pnpm db:seed` 通过
|
||||||
|
|
||||||
|
|
||||||
|
### 11.14 AI 多源检索、快速创建与字段级补全
|
||||||
|
|
||||||
|
**多来源检索**
|
||||||
|
- Tavily 仍为优先;未配置 `SEARCH_API_KEY` 时改为 Bing / Baidu 公开检索 + 白名单抓取
|
||||||
|
- 白名单:厂商官网、ZOL、PConline、Kalvo、GSMArena、IT之家、快科技、Notebookcheck、SMZDM、知乎等
|
||||||
|
- 同一域名最多 2 条,避免官网泛化页占满结果;官方 URL 按品牌 / 型号直接猜测(如 `mi.com/prod/{slug}/specs`、OPPO Find X 系列参数页)
|
||||||
|
- Kalvo 搜索作为稳定补充源:`zh.kalvo.com/search?q=型号`,可补到 ZOL / PConline 未覆盖的机型
|
||||||
|
- 检索失败才降级为模型知识;抓到的来源全部进入提示词做交叉验证
|
||||||
|
|
||||||
|
**快速创建流程**
|
||||||
|
- `/admin/devices/new` 只保留 slug 输入 + 单按钮;提交后调用 `POST /api/ai/prospect`
|
||||||
|
- 服务端从 slug 推断品牌 / 型号(redmi-k90-pro-max → Redmi / K90 Pro Max),多源补全后直接创建初稿
|
||||||
|
- 创建成功跳转 `/admin/devices/{slug}?created=1`,进入原有详细编辑页
|
||||||
|
|
||||||
|
**字段级补全**
|
||||||
|
- 每个规格字段(含摄像头字段、扬声器单元、设备补充、振动等)旁新增 `AI` 按钮
|
||||||
|
- 调用 `POST /api/ai/field`,只检索当前字段;字段旁的“补充参考资料”文本也会传入
|
||||||
|
- 适合官网不公开的扬声器单元型号、尺寸、马达型号、体积;实测 K90 Pro Max:
|
||||||
|
- 扬声器单元:`AAC 1115K`
|
||||||
|
- 马达:`瑞声 0809B`
|
||||||
|
- 均以 `medium` 写回,并保留“仅拆解资料提及”的 note
|
||||||
|
|
||||||
|
**稳定性处理**
|
||||||
|
- `max_tokens` 提升到 8192;提示词要求 `note` 只在冲突/必要补充时填写,减少输出体积
|
||||||
|
- 输出被截断时用 `salvageFields` 保留已完整的字段对象,避免整批失败
|
||||||
|
- 多来源 URL 合并为 `sourceUrls`,最多 3 个;`note` 在编辑预览中展示
|
||||||
|
|
||||||
|
**实测**
|
||||||
|
- OPPO Find X10 Pro Max:6 个来源(官网 ×2 / ZOL ×2 / PConline / Kalvo),返回 100 个字段
|
||||||
|
- REDMI K90 Pro Max:5 个来源(ZOL / Kalvo / SMZDM 等),返回 68 个字段
|
||||||
|
- OnePlus 15:公开资料不足,仅 4 个字段,仍可创建初稿后手动补充
|
||||||
|
- 浏览器验证快速创建:输入 `oneplus-15` → 生成初稿 → 自动跳转详细编辑页;每个字段的 `AI` 按钮正常渲染
|
||||||
|
- `pnpm typecheck`、`pnpm build` 通过
|
||||||
|
|
||||||
|
|
||||||
|
### 11.15 中国市场本地化与二次补全修复
|
||||||
|
|
||||||
|
**问题**
|
||||||
|
- OnePlus 16 快速创建只返回 20~41 个字段,大量英文,售价为 `€800`
|
||||||
|
- 编辑页输入官网 URL 二次补全仍缺失;ZOL 参数页正文在导航/概览后约 3600 字符才进入详细参数,3500 字符截断导致只拿到概览
|
||||||
|
|
||||||
|
**修复**
|
||||||
|
- 单来源正文上限 3500 → 9000 字符;ZOL / PConline 详细参数表可完整进入提示词
|
||||||
|
- 提示词新增中国市场规则:文本值简体中文(芯片/协议/接口/传感器代号保留英文),`pricing` 只写国行人民币;只有 EUR / USD / GBP 时直接省略
|
||||||
|
- 服务端对 `pricing` 做二次过滤,含 `€/£/$/EUR/USD/GBP/欧元/美元/英镑` 的条目直接丢弃
|
||||||
|
- 手动补充链接改为真正抓取正文:`fetchManualSources()` 不受白名单限制(仍拒绝内网),支持多行 URL(最多 4 条),并入 `sources` 后按 URL 去重
|
||||||
|
- 纯数字型号的关键词筛选回退为品牌词,避免 OnePlus 16 抓到 iPhone 16 / Meizu 16 / realme 16
|
||||||
|
- Kalvo 站内搜索改用“品牌 型号”,字段级检索同样修正
|
||||||
|
- `officialUrl` 从已抓取来源里按“官方域名 + 路径含型号 + 具体参数页”打分选出,替代模型输出的品牌列表页
|
||||||
|
- AI 缓存键加版本前缀 `v2`,检索/提示词规则变更后不再命中旧结果
|
||||||
|
|
||||||
|
**实测(OnePlus 16)**
|
||||||
|
- 整机检索:6 个来源(官网 / ZOL ×2 / PConline / OPPO shop 等),96 个字段,中文 + 人民币,
|
||||||
|
`officialUrl = https://www.oneplus.com/cn/oneplus-16/specs`
|
||||||
|
- 手动补充官网 + ZOL:93 个字段,官网来源优先,高置信度字段明显增多
|
||||||
|
- 字段级 `specs.vibration.volume` 返回 `null`:官网 / ZOL 不公开马达体积,属于资料缺失而非流程失败
|
||||||
|
- 已用最新结果刷新测试草稿 `oneplus-16`:159 个非空值,售价为 5999 / 6799 / 7499 / 8499 元
|
||||||
|
- `pnpm typecheck`、`pnpm build` 通过;详情页 200,售价、扬声器、官网链接正常渲染
|
||||||
|
|
||||||
|
|
||||||
|
### 11.16 编辑页字段核验与详情页顶部展示带
|
||||||
|
|
||||||
|
**编辑页**
|
||||||
|
- 每个带 `FieldMeta` 的输入框增加「核验」按钮:一次点击把该路径 `verified` 置为 true,low 字段保存阻塞随之解除,无需滚到底部清单
|
||||||
|
- AI 按钮与核验按钮统一放大到 `text-xs` + `px-3 py-1.5`;置信度徽章改为 `text-xs`、带底色,待核 / 已核状态更易读
|
||||||
|
- 摄像头位置、视频模式、扬声器单元等动态路径也接入同一套 AI + 核验按钮
|
||||||
|
|
||||||
|
**详情页**
|
||||||
|
- 标题下方新增 `device-hero` 展示带:配色圆点 + 中文色名;售价按版本拆成卡片,最低价高亮「起售价」
|
||||||
|
- 顶部渐变取自首个配色(`--device-accent`),叠加细网格纹理;浅色主题自动降低透明度,打印时隐藏纹理
|
||||||
|
- 初始售价从底部「售价与补充」移出,该节更名为「发布与补充」;配色从外观表移出
|
||||||
|
- 移除底部「数据来源」字段清单,字段级来源只在编辑页保留;低置信字段仍保留 hover 徽章
|
||||||
|
- 参数卡数值从 15px 提升到 17px 并加粗,标签增加字重;分组标题提升到 20~24px,表格正文 15px,镜头卡标题与分辨率加粗
|
||||||
|
- 详情页卡片网格启用 `reveal-grid` 渐入;打印仍保持浅色且隐藏装饰背景
|
||||||
|
|
||||||
|
**验证**
|
||||||
|
- `pnpm typecheck`、`pnpm build` 通过
|
||||||
|
- 浏览器验证 `oneplus-16`:顶部展示 3 个配色与 4 档售价,底部无「数据来源」清单,卡片数值层级正常
|
||||||
|
|
||||||
|
|
||||||
|
### 11.17 配色推断与字段级 AI 状态修正
|
||||||
|
|
||||||
|
**配色**
|
||||||
|
- 一加 16「明日星光」原先未命中关键词,走哈希色相得到浅蓝;新增「星光 / 星芒 / 星耀」→ 银白 `#d8dce2`
|
||||||
|
- 把绿色关键词组提到黑色之前:「黑暗森林」按森林绿而不是按“黑”取深灰
|
||||||
|
- 未知名称仍用稳定哈希色相兜底
|
||||||
|
|
||||||
|
**字段级 AI**
|
||||||
|
- 原先 `found=false` 也把按钮置为红色 `!`,与真正的接口/解析失败混淆;现在拆成三种状态:
|
||||||
|
- `✓`:成功补全
|
||||||
|
- `无`(黄色)+「无公开数据」:检索到来源但没有明确依据,hover 显示完整 notice
|
||||||
|
- `!`(红色)+「检索失败」:HTTP 错误或模型输出无法解析
|
||||||
|
- 字段补全会复用整机补全缓存里的来源 URL(过滤品牌首页 / 系列页 / 搜索页),即使 Bing / Baidu 临时限流,仍能用 ZOL / PConline / 官网正文
|
||||||
|
- 模型返回 `null` 时抛出 502,不再被误判为“无数据”
|
||||||
|
|
||||||
|
**实测(OnePlus 16)**
|
||||||
|
- 马达型号、扬声器尺寸在复用整机来源后可以补全;马达体积 / 扬声器功率 / 屏幕厂商仍返回「无公开数据」
|
||||||
|
- 字段请求 notice 会写明「复用了整机补全的 4 个来源」以及公开检索结果
|
||||||
|
- `pnpm typecheck`、`pnpm build` 通过;详情页 `--device-accent` 已变为 `#d8dce2`
|
||||||
|
|
||||||
|
|
||||||
|
### 11.18 真实配色字段与区块级 AI 补全
|
||||||
|
|
||||||
|
**配色**
|
||||||
|
- 文字色名无法稳定映射(“黑暗森林”实际为黑色),新增 `specs.body.colorHexes`,与 `colors` 顺序一一对应;AI 依据官方描述、产品图和色名语义给出 #RRGGBB
|
||||||
|
- 展示页优先使用 `colorHexes`,缺失时回退到色名推断;一加 16 实测:
|
||||||
|
- 明日星光 `#E8E8E6`(银白)
|
||||||
|
- 黑暗森林 `#1C1C1E`(近黑)
|
||||||
|
- 火星杰作 `#B5543A`(橙红)
|
||||||
|
- 已刷新 `oneplus-16` 草稿,并补入用户确认的「京东方(BOE)/ X4 发光材料」
|
||||||
|
|
||||||
|
**区块 AI**
|
||||||
|
- 新增 `POST /api/ai/section` 和 `lookupPhoneSection()`:按 `PHONE_SPEC_SECTIONS` 一次补全一个分区(外观、屏幕、平台、内存与存储、振动、连接、电池与传感器等)
|
||||||
|
- 区块 prompt 只列该分区路径,允许跨字段推导(如分辨率 + 尺寸 → PPI),并保留交叉验证与 `colorHexes` 规则
|
||||||
|
- 编辑页分区标题旁新增「区块 AI」按钮;结果以内联预览展示,可勾选后应用
|
||||||
|
- 来源策略:整机缓存来源 + 区块定向检索 + 手动链接,最多 8 个;按主域限流,过滤品牌首页 / 系列页
|
||||||
|
- Baidu 公开检索跳转链接解析从 5 条提升到 8 条并过滤广告位;Bing 中文结果噪声较大时由品牌关键词过滤兜底
|
||||||
|
|
||||||
|
**实测(OnePlus 16)**
|
||||||
|
- 外观区块:8 个字段 + `colorHexes` 三色,medium;屏幕区块:20 个字段,补到边框 1.15mm,但仍未找到面板厂商
|
||||||
|
- 面板厂商 / 发光材料主要出现在新闻稿;公开检索受限时可在「补充参考资料」粘贴对应链接后再跑区块 AI,或人工填写
|
||||||
|
- `pnpm typecheck`、`pnpm build` 通过;详情页 accent 为 `#E8E8E6`,黑暗森林色块显示为近黑
|
||||||
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
+2
-1
@@ -28,7 +28,8 @@ COPY --from=build /app/package.json ./package.json
|
|||||||
COPY --from=build /app/migrations ./migrations
|
COPY --from=build /app/migrations ./migrations
|
||||||
COPY --from=build /app/scripts ./scripts
|
COPY --from=build /app/scripts ./scripts
|
||||||
|
|
||||||
RUN mkdir -p /app/data
|
# OG 图由 sharp -> librsvg 渲染文字,需要 fontconfig + Latin 字体
|
||||||
|
RUN apk add --no-cache fontconfig ttf-dejavu && mkdir -p /app/data
|
||||||
|
|
||||||
EXPOSE 3000
|
EXPOSE 3000
|
||||||
CMD ["node", "./dist/server/entry.mjs"]
|
CMD ["node", "./dist/server/entry.mjs"]
|
||||||
@@ -4,19 +4,159 @@
|
|||||||
|
|
||||||
## 技术栈
|
## 技术栈
|
||||||
|
|
||||||
Astro 7(SSR / Node adapter)+ Tailwind CSS 4 + shadcn/ui(React islands)+ SQLite(`node:sqlite`,无原生依赖)
|
Astro 7(SSR / Node adapter)+ Tailwind CSS 4 + shadcn/ui(React islands)+ SQLite(`node:sqlite`,无原生依赖)+ sharp(OG 图生成)
|
||||||
|
|
||||||
## 本地开发
|
## 本地开发
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
pnpm install
|
pnpm install
|
||||||
cp .env.example .env # Windows: Copy-Item .env.example .env
|
cp .env.example .env # Windows: Copy-Item .env.example .env
|
||||||
pnpm db:seed # 建表 + 写入种子数据(Xiaomi 14 / 骁龙 8 Gen 3)
|
pnpm db:seed # 建表 + 写入种子数据(Xiaomi 14 / REDMI K90 Pro Max / OPPO Find X10 Pro Max / 骁龙 8 Gen 3)
|
||||||
pnpm dev # http://localhost:4321
|
pnpm dev # http://localhost:4321
|
||||||
|
pnpm typecheck # tsc --noEmit
|
||||||
```
|
```
|
||||||
|
|
||||||
组件自检页:`/poc`(验证 Button / Card / Dialog 可用,M0 验收后可删)。
|
组件自检页:`/poc`(验证 Button / Card / Dialog 可用,M0 验收后可删)。
|
||||||
|
|
||||||
|
## 编辑后台(M2)
|
||||||
|
|
||||||
|
访问 `/admin`,输入 `.env` 中的 `ADMIN_PASSWORD` 登录。登录态是 7 天有效的 HttpOnly 签名 cookie;连续 3 次密码错误会按 IP 限速 1 分钟。
|
||||||
|
|
||||||
|
- 登录后是仪表盘:设备/芯片列表、最近修订记录、新增入口。
|
||||||
|
- 设备编辑:`/admin/devices/[slug]`,新增用 `/admin/devices/new`。新增页只需输入 slug,AI 会多源检索生成初稿并跳转到详细编辑;表单覆盖手机全部规格分组,多摄逐颗编辑,扬声器单元可增删;字段来源徽章与“已核实”勾选会保留。
|
||||||
|
- 芯片编辑:`/admin/chips/[slug]`,基础信息、GPU/NPU/内存等结构化字段,CPU 核心簇、跑分、扩展字段用 JSON 编辑。
|
||||||
|
- 封面图上传:`POST /api/upload`,仅 jpg / png / webp / avif,单张 ≤ 10MB;M2 存原图,不做压缩转码。
|
||||||
|
- 每次保存写入 `revisions` 快照(与主表同一事务),编辑页底部展示最近 10 条。
|
||||||
|
|
||||||
|
写接口(`/api/devices`、`/api/chips`、`/api/upload`)都要求登录态,并校验 `Origin` 与 `Host` / `X-Forwarded-Host` 同源;读页面完全公开。
|
||||||
|
|
||||||
|
> 生产环境务必替换 `ADMIN_PASSWORD` 与 `SESSION_SECRET`,并在 HTTPS 下设置 `COOKIE_SECURE=1`。
|
||||||
|
> M2 只实现本地图片驱动;S3 驱动仍是接口占位(M4 或需要时再接)。
|
||||||
|
|
||||||
|
## AI 补全(M3)
|
||||||
|
|
||||||
|
编辑页的「AI 补全」会按当前品牌 + 型号调用 `POST /api/ai/lookup`,返回带置信度的扁平字段。
|
||||||
|
|
||||||
|
- 新增页「AI 快速创建」只需输入 slug:服务端推断品牌 / 型号,多源检索后写入初稿并跳转详细编辑页(`POST /api/ai/prospect`)。
|
||||||
|
- 未配置 Tavily 时使用 Bing / Baidu / DuckDuckGo 公开检索 + ZOL / GSMArena / Kalvo 站内直查,并只抓取白名单站点:厂商官网、ZOL、PConline、Kalvo、GSMArena、IT之家、快科技、Notebookcheck 等;按域名限流并做多源交叉验证。
|
||||||
|
- 详细编辑页每个规格分区标题旁有「区块 AI」(`POST /api/ai/section`),一次检索该区块的全部字段(如屏幕、内存与存储、电池、连接),结果可勾选后应用;比单字段补全多了区块上下文,更容易拿到面板厂商、发光材料等分散信息。
|
||||||
|
- 详细编辑页每个规格字段旁有 `AI` 按钮(`POST /api/ai/field`),只针对该字段重新检索;适合官网不公开的扬声器单元型号、尺寸、马达型号、体积等。字段旁的「补充参考资料」文本也会参与该字段检索。
|
||||||
|
- 「补充参考资料」支持多行 URL:每行一个官网 / ZOL / PConline 链接,服务端会抓取正文并与公开检索结果合并(按 URL 去重);缓存键包含 URL 与补充文本的摘要,二次补全不会命中旧结果。
|
||||||
|
- 面向中国大陆:提示词要求简体中文与国行人民币价格,`pricing` 会过滤 EUR / USD / GBP 与海外版本;`officialUrl` 从已抓取来源中自动选具体产品页,避免写成品牌首页或系列列表。
|
||||||
|
- 字段级补全会复用整机补全已抓取的来源(如 ZOL / PConline),公开检索临时失败时仍能继续;确实没有公开数据时按钮显示 `无` 并标注「无公开数据」,与真正的检索失败区分。
|
||||||
|
- 公开检索按型号做来源筛选;纯数字型号(如 `OnePlus 16`)改用品牌词排除 iPhone / Meizu 16 等同名干扰。
|
||||||
|
- 新增大模型输出截断保护:JSON 被截断时保留已完整的字段对象,避免整批结果丢失。
|
||||||
|
|
||||||
|
配置 `.env`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
AI_BASE_URL=https://api.deepseek.com/v1 # 任何 OpenAI 兼容接口
|
||||||
|
AI_API_KEY=
|
||||||
|
AI_MODEL=deepseek-chat
|
||||||
|
SEARCH_API_KEY= # 可选:Tavily 兼容搜索
|
||||||
|
SEARCH_BASE_URL=https://api.tavily.com
|
||||||
|
```
|
||||||
|
|
||||||
|
- 有搜索 key 时:优先走 Tavily,把标题 / URL / 摘要塞进提示词;抓取失败的来源会被跳过。
|
||||||
|
- 没有搜索 key 时:使用 Bing / Baidu / DuckDuckGo 公开检索 + ZOL / GSMArena / Kalvo 站内直查,只抓取白名单站点(官网、ZOL、PConline、Kalvo、GSMArena 等),同一域名最多 2 条;页面正文按"规格密度"取窗(优先参数表而非页头导航);检索完全失败才降级为模型知识,并将 `high` 降为 `medium`。资料未覆盖但属于公开常识的字段,模型可给 low 置信度并注明「模型知识,待核实」。
|
||||||
|
- 字段级与区块级补全走**全网自由检索**:不限白名单站点(评测、百科、论坛等均可作依据,白名单站仍优先排序),接受的置信度下限为 low;整机补全仍保持白名单交叉验证。
|
||||||
|
- 拆机视频通道:三处检索都会附加 `site:bilibili.com 机型 拆解` 查询,B 站视频页走官方接口获取标题 + 简介;在 `.env` 配置 `BILIBILI_SESSDATA`(B 站登录态)后还会拉取**字幕全文**——马达型号、扬声器单元等官网不公开的细节主要在拆机视频的口播里(如微机分等拆解 UP 主)。未配置 SESSDATA 时字幕接口返回空,来源价值有限。
|
||||||
|
- 编辑页「AI 补全」下方提供可选的「补充参考资料」:可粘贴官网参数文本并填写官方链接。最新机型未进模型知识库时,用它可显著提高字段覆盖;补充文本会参与缓存键,避免与无资料结果串缓存。
|
||||||
|
- 提示词覆盖全部规格分组与设备补充字段(手机特点 / 影像功能 / 跑分 / 售价 / 官网),摄像头逐颗、扬声器最多 5 个单元;`display.refreshNote` 用于表达“185Hz 仅部分游戏场景生效”这类附加条件。
|
||||||
|
- 只接受白名单路径(`src/lib/spec-fields.ts`),值类型按路径定义强转;摄像头位置只允许 `wide/ultrawide/tele/periscope/macro/depth/mono/color/front`。
|
||||||
|
- 预览显示「当前值 → AI 值」、置信度徽章与来源,可逐项勾选后应用。
|
||||||
|
- 应用后 `low` 字段阻塞保存;底部提供「确认全部 low」「清空全部 low」,来源区可「全部接受 high」。
|
||||||
|
- 结果按 `phone|品牌|型号`(有补充资料时追加文本哈希)缓存到 `ai_cache`;勾选「忽略缓存」可强制刷新。字段级检索按 `field|品牌|型号|路径` 单独缓存。
|
||||||
|
- AI 关键配置缺失时接口返回 503,页面会直接显示原因;AI key 只在服务端读取。
|
||||||
|
|
||||||
|
> M3 验收曾使用本地 mock;本轮已用 DeepSeek 实测:多源检索 OPPO Find X10 Pro Max 时抓取官网 / ZOL / PConline / Kalvo 共 6 个来源,返回 100 个字段;来源不足的机型(如 OnePlus 15)只返回少量字段,说明覆盖度取决于公开资料质量。
|
||||||
|
|
||||||
|
## 对比(M4)
|
||||||
|
|
||||||
|
设备列表和详情页的「加入对比」会把机型放进底部固定托盘(最多 4 款,选择保存在 localStorage),托盘里可直接移除或点「开始对比」进入结果页。直接访问 `/compare` 时是搜索 + 品牌筛选 + 分页的设备选择器,点「+ 加入」加入当前选择;已选 2 款以上时可从顶部「查看对比」进入结果。
|
||||||
|
|
||||||
|
- 差异项高亮并显示圆点,缺失值显示 `—` 并置灰。
|
||||||
|
- 「只看差异」用 `?diff=1` 切换,只保留有差异的行。
|
||||||
|
- 分组默认展开,可点击分组标题折叠;首列字段名在横向滚动时保持粘性。
|
||||||
|
- 重量、屏幕尺寸、亮度、刷新率、电池容量、充电功率等数值字段带相对条形图。
|
||||||
|
|
||||||
|
## 导出与导入(M4)
|
||||||
|
|
||||||
|
- `GET /api/export`:公开下载全量 JSON,`formatVersion: 1`,包含 `devices` 与 `chips`。
|
||||||
|
- `/admin/import`:登录后粘贴或选择 JSON 导入;按 slug upsert,已存在的 slug 会被覆盖,未出现在文件里的数据不会删除。
|
||||||
|
- 导入会先对整批数据跑 zod 校验,只要有一条不合法就整批拒绝,不会写入半份数据。
|
||||||
|
- 限制:单次最多 5000 条、请求体 ≤ 20MB。
|
||||||
|
|
||||||
|
> JSON 不包含图片。迁移或恢复时请同时拷贝 `data/app.db`(或备份)与 `data/uploads/`。
|
||||||
|
|
||||||
|
### 从 phonerecommend.top 同步
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pnpm sync:phonerecommend # 只产出 data/import/phonerecommend-<时间>.json
|
||||||
|
pnpm sync:phonerecommend -- --write # 同时按 slug upsert 到 data/app.db
|
||||||
|
pnpm sync:phonerecommend -- --write --images # 并下载封面 / 相册到 data/uploads
|
||||||
|
pnpm sync:phonerecommend -- --brand 华为 --brand 小米
|
||||||
|
```
|
||||||
|
|
||||||
|
- 源站列表接口 `/api/phones?limit=100&page=N` 已包含完整规格组,需要带浏览器 UA 与 `Referer`。
|
||||||
|
- 品牌转英文规范名,中文型号转拼音 slug;输出结构与本项目 `formatVersion: 1` 一致。
|
||||||
|
- 源站个别记录型号只写了品牌(如 `OPPO / OPPO`),会回退到 `product_model` 并去掉品牌前缀;同名同发布时间的重复机型会被跳过。
|
||||||
|
- 源站缺少的结构化字段(传感器型号、马达体积、无线充电等)会留空,可继续用字段级 AI 补全。
|
||||||
|
- 屏幕亮度会区分「典型亮度 / 局部峰值亮度 / 全局峰值亮度」,不再按数字出现顺序猜测;源站 `navigation` 等文本中混入的商城推荐内容会被截断。
|
||||||
|
- `--images` 会下载封面 / 相册并转成 WebP,落到 `data/uploads/devices/<slug>/`,页面通过 `/uploads/devices/<slug>/...` 读取;下载后会清理本地不存在的图片引用。slug 冲突以源站为准覆盖本地记录,执行前建议先 `pnpm backup`。
|
||||||
|
|
||||||
|
### 从 phonerecommend.top 同步处理器
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pnpm sync:processors # 只产出 data/import/processors-<时间>.json
|
||||||
|
pnpm sync:processors -- --write # 写入 chips,并按芯片名回填设备的 SoC 引用
|
||||||
|
pnpm sync:processors -- --limit 10 # 只处理前 10 颗
|
||||||
|
```
|
||||||
|
|
||||||
|
- 列表接口 `/api/processors?limit=100&page=N` 共 224 条,按 `key` 去重后为 203 颗;详情接口补充跑分、别名、来源与官方规格表。
|
||||||
|
- `chips.detail` 新增 `overview / cpuBlock / gpuBlock / npuBlock / cameraBlock / displayBlock / connectivityBlock / benchmarkInfo / traits / caveats / sourceUrls / specGroups`;芯片列表按档位分与年份排序,详情页展示 CPU 簇、跑分、内存/影像/连接与可折叠的完整规格。
|
||||||
|
- `--write` 会按 `specs.platform.chipset` 与芯片名称 / 别名匹配,回填 `devices.chipRefs.soc`,芯片详情页可直接列出搭载机型。
|
||||||
|
- 源站对高频请求返回 429 / 403,脚本已内置退避重试与低并发;个别旧处理器详情失败时仍保留列表字段。
|
||||||
|
|
||||||
|
### 从酷安补充 / 覆盖手机参数
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pnpm sync:coolapk # 只产出 data/import/coolapk-<时间>.json
|
||||||
|
pnpm sync:coolapk -- --write # 合并进 data/app.db
|
||||||
|
pnpm sync:coolapk -- --limit 10 # 只处理前 10 款
|
||||||
|
pnpm sync:coolapk -- --slug oneplus-16 # 只处理指定 slug(含自动创建的新机型)
|
||||||
|
```
|
||||||
|
|
||||||
|
- 先分页读取酷安机型目录(缓存在 `data/cache/coolapk-products.json`,当前 1505 条,去重后 1504 款),按品牌别名 + 型号匹配本地设备;名称拼接未命中时会再按「推断品牌 + 型号」精确匹配一次。
|
||||||
|
- 本地没有的酷安机型也会自动创建:从产品名前缀推断品牌与型号,用拼音生成 slug,读取「发布时间」写入上市 / 发布与状态,并生成列表摘要;封面与相册留空,后续可继续补图。
|
||||||
|
- 读取每个机型的版本列表,取基础版本参与每 4 台一组的配置对比,解析完整参数表,再映射到机身、屏幕、平台、内存、电池、网络、马达、扬声器、传感器与摄像头等字段。
|
||||||
|
- **覆盖策略**:酷安为权威源,但不让低信息度内容覆盖高信息度内容——先比较数字、单位与文本完整度,酷安更完整才覆盖;两边数值明显冲突时视为不一致,采用酷安。分辨率(防止「1.5K」覆盖精确像素)、摄像头像素、长焦焦距、传感器型号、视频规格都有单独的保护规则;频段与传感器清单使用并集。
|
||||||
|
- `specs.coolapk` 只保留产品 ID、配置 ID、价格、同步时间与酷安评分(总评 / 机主 / 续航 / 影像 / 性能 / 屏幕 / 外观质感 / 性价比);原始参数表不再入库,详情页标题下方直接展示评分与同步日期。
|
||||||
|
- 执行 `--write` 前建议先 `pnpm backup`。
|
||||||
|
|
||||||
|
## 动效、OG 图与打印(M5)
|
||||||
|
|
||||||
|
- **页面动效**:Astro `<ClientRouter />` + 主内容淡入;列表网格用 CSS `reveal-grid` 做轻量渐入与 40ms 级联。`prefers-reduced-motion: reduce` 时全部关闭,未引入 GSAP / Lenis。
|
||||||
|
- **黑白主题**:右上角按钮切换日间 / 夜间主题;首次访问跟随系统,之后用 `localStorage` 记住,跨页导航和刷新都保持。打印时强制浅色。
|
||||||
|
- **详情页参数 hover**:关键参数卡、影像卡和规格表行在鼠标悬停时高亮背景并把字段名切为强调色,便于定位当前参数;顶部参数卡可点击跳转到对应详细分组。
|
||||||
|
- **OG 图**:`GET /og/[slug].png` 动态生成 1200×630 PNG,设备页自动使用 `/og/<slug>.png`,其他页面默认 `/og/site.png`;详情页同时输出 `og:*`、`twitter:card`、canonical。
|
||||||
|
- **打印**:设备详情页有「打印 / 保存 PDF」按钮;`@media print` 切换浅色配色、隐藏导航/页脚/按钮、取消 sticky 与横向滚动,并尽量避免表格跨页断行。
|
||||||
|
- **字体依赖**:OG 图文字只使用 Latin 字符,避免容器缺中文字体时出现方框。`sharp` 通过系统字体渲染,需要 `fontconfig` + DejaVu:
|
||||||
|
- 标准 Dockerfile 已安装 `fontconfig` / `ttf-dejavu`。
|
||||||
|
- 宿主构建 + `node:24-slim` 挂载方式会把宿主机的 `/usr/share/fonts` 与 `/etc/fonts` 只读挂进容器。
|
||||||
|
|
||||||
|
## 详情页参数展示
|
||||||
|
|
||||||
|
- 标题下方是「配色 + 初始售价」展示带:配色用圆形色块 + 中文色名,售价按版本拆成卡片并高亮起售价;背景渐变取自首个配色,作为该机型的页面色彩主题。色块优先使用 `body.colorHexes`(与 `body.colors` 顺序一致,AI / 人工维护);缺失时按中文色名推断(星光→银白、森林→绿、火星→橙等),未知名称用稳定哈希色相。
|
||||||
|
- 顶部参数卡分多排展示:SoC、屏幕、电池、主摄、超广角、长焦、影像场景、内存、存储、充电、无线充电、系统、扬声器、马达、Wi-Fi、USB、指纹、重量、防护。卡片高度统一,数值加大加粗,长文本两行截断;电池、充电、Wi-Fi、相机卡使用短值 + 关键副标题,避免整段参数无法阅读。
|
||||||
|
- 卡片上方提供分组快捷导航;详细参数按“屏幕与外观 → 性能 → 影像 → 电池与充电 → 音频与振动 → 连接与网络 → 传感器 → 系统与更新 → 发布与补充”排序,每节带编号与分组小标题。
|
||||||
|
- 性能节合并 SoC 卡片、平台、内存与存储及跑分;未关联芯片库时显示芯片名与“芯片库暂未收录”,避免空白区块。影像节按后置 / 前置分组,镜头头衔使用中文位置(主摄 / 超广角 / 长焦 / 潜望式长焦 / 色彩镜头等),并显示传感器营销名。
|
||||||
|
- 屏幕补充面板厂商(如 TCL 华星)与技术代号(如 C8),并展示挖孔形态、刷新附加说明(如“最高 185Hz 仅部分游戏场景生效”)、瞬时触控采样率、色深、色域、像素密度、OLED 等效 PPI、屏占比、边框、16:9 等效尺寸、屏幕特性与其它说明。
|
||||||
|
- 扬声器按 `speakers.units[]` 任意数量拆行,支持上 / 下 / 中置 / 第三单元等自定义标识,不再限定双扬声器;每单元给出型号、尺寸与功率。马达给出型号、尺寸与实际体积;USB 给出型号、实际速率与视频输出;系统列出出厂版本、当前版本及更新时间线。
|
||||||
|
- 前后摄新增传感器营销名(如“光影猎人 900”)与视场角;影像功能、手机特点、设备跑分、官网、备注与耳机接口等补充信息单独展示;初始售价在顶部展示带中呈现。
|
||||||
|
- 连接分组内,“移动网络频段”和“卫星通信频段”在 hover / 聚焦时弹出频段面板;卫星面板同时显示运营商(天通 / 北斗等)。
|
||||||
|
- 字段级置信度只标记 `low`:低置信字段旁显示 `low` 徽章,hover / 聚焦显示字段名、路径、核实状态与来源;`high` 与 `medium` 不做常驻标记。页面底部不再展示字段级来源清单,避免信息过载。
|
||||||
|
|
||||||
## 部署
|
## 部署
|
||||||
|
|
||||||
### 小内存服务器(当前 ECS 方案)
|
### 小内存服务器(当前 ECS 方案)
|
||||||
@@ -40,6 +180,7 @@ bash scripts/deploy.sh
|
|||||||
```bash
|
```bash
|
||||||
pnpm backup # VACUUM INTO 快照 + 打包 uploads 到 backups/<时间戳>/
|
pnpm backup # VACUUM INTO 快照 + 打包 uploads 到 backups/<时间戳>/
|
||||||
pnpm db:seed # 重跑种子数据(幂等,按 slug upsert)
|
pnpm db:seed # 重跑种子数据(幂等,按 slug upsert)
|
||||||
|
pnpm typecheck # 类型检查
|
||||||
```
|
```
|
||||||
|
|
||||||
## 目录
|
## 目录
|
||||||
@@ -47,8 +188,20 @@ pnpm db:seed # 重跑种子数据(幂等,按 slug upsert)
|
|||||||
```
|
```
|
||||||
src/lib/schema/ zod 数据模型(phone / soc / FieldMeta)
|
src/lib/schema/ zod 数据模型(phone / soc / FieldMeta)
|
||||||
src/lib/db.ts SQLite 连接 + 迁移
|
src/lib/db.ts SQLite 连接 + 迁移
|
||||||
src/lib/repo.ts 唯一数据出入口
|
src/lib/repo.ts 唯一数据出入口(含修订快照)
|
||||||
src/lib/storage.ts 图片存储驱动(local / s3 接口)
|
src/lib/storage.ts 图片存储驱动(local / s3 接口)
|
||||||
|
src/lib/auth.ts 登录、签名 cookie、限速、写接口守卫
|
||||||
|
src/lib/env.ts 运行时读取 .env(standalone / 脚本共用)
|
||||||
|
src/lib/spec-fields.ts 手机字段注册表 + 路径读写工具(表单 / AI / 对比共用)
|
||||||
|
src/lib/compare.ts 对比分组、差异判定与数值提取
|
||||||
|
src/lib/og.ts OG 卡片 SVG -> PNG(sharp)
|
||||||
|
src/lib/ai/ 搜索、提示词、模型调用、字段校验、置信度与合并规则
|
||||||
|
src/middleware.ts /admin/** 登录拦截
|
||||||
|
src/pages/admin/ 登录/仪表盘、设备与芯片编辑页、导入页
|
||||||
|
src/components/admin/ 编辑表单(React islands,含 AI 差异预览、导入面板)
|
||||||
|
src/pages/api/ auth / devices / chips / upload / ai / export / import
|
||||||
migrations/ SQL 迁移,按文件名顺序执行
|
migrations/ SQL 迁移,按文件名顺序执行
|
||||||
scripts/ seed / backup
|
scripts/ seed / backup / sync-phonerecommend / sync-processors / sync-coolapk
|
||||||
```
|
```
|
||||||
|
|
||||||
|
> 在受限沙箱里 `pnpm dev` 首次 SSR 模块加载可能极慢;可改用 `pnpm build && node dist/server/entry.mjs` 在本地验证生产路径(设置 `HOST` / `PORT` 即可)。
|
||||||
@@ -11,6 +11,11 @@ export default defineConfig({
|
|||||||
output: 'server',
|
output: 'server',
|
||||||
adapter: node({ mode: 'standalone' }),
|
adapter: node({ mode: 'standalone' }),
|
||||||
integrations: [react()],
|
integrations: [react()],
|
||||||
|
security: {
|
||||||
|
// 反代后 request.url 的 origin 可能是 localhost,内置校验会误伤正常表单提交。
|
||||||
|
// 所有写接口在 src/lib/auth.ts 的 guardWrite / sameOrigin 中自行做同源校验。
|
||||||
|
checkOrigin: false,
|
||||||
|
},
|
||||||
vite: {
|
vite: {
|
||||||
plugins: [tailwindcss()],
|
plugins: [tailwindcss()],
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -15,6 +15,9 @@ services:
|
|||||||
- ./node_modules:/app/node_modules
|
- ./node_modules:/app/node_modules
|
||||||
# 唯一需要持久化的目录:SQLite 与上传图片
|
# 唯一需要持久化的目录:SQLite 与上传图片
|
||||||
- ./data:/app/data
|
- ./data:/app/data
|
||||||
|
# node:24-slim 不带字体;OG 图渲染文字需要挂载宿主字体
|
||||||
|
- /usr/share/fonts:/usr/share/fonts:ro
|
||||||
|
- /etc/fonts:/etc/fonts:ro
|
||||||
env_file:
|
env_file:
|
||||||
- .env
|
- .env
|
||||||
environment:
|
environment:
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
-- 运行时配置(如 B 站登录态),由后台界面写入;.env 仍是环境级配置的来源
|
||||||
|
CREATE TABLE IF NOT EXISTS settings (
|
||||||
|
key TEXT PRIMARY KEY,
|
||||||
|
value TEXT NOT NULL,
|
||||||
|
updated_at TEXT NOT NULL
|
||||||
|
);
|
||||||
+12
-1
@@ -9,7 +9,11 @@
|
|||||||
"dev": "astro dev",
|
"dev": "astro dev",
|
||||||
"build": "astro build",
|
"build": "astro build",
|
||||||
"preview": "astro preview",
|
"preview": "astro preview",
|
||||||
|
"typecheck": "tsc --noEmit",
|
||||||
"db:seed": "node scripts/seed.mjs",
|
"db:seed": "node scripts/seed.mjs",
|
||||||
|
"sync:phonerecommend": "tsx scripts/sync-phonerecommend.mjs",
|
||||||
|
"sync:processors": "tsx scripts/sync-processors.mjs",
|
||||||
|
"sync:coolapk": "tsx scripts/sync-coolapk.mjs",
|
||||||
"backup": "node scripts/backup.mjs",
|
"backup": "node scripts/backup.mjs",
|
||||||
"astro": "astro"
|
"astro": "astro"
|
||||||
},
|
},
|
||||||
@@ -25,15 +29,22 @@
|
|||||||
"jose": "^6.2.14",
|
"jose": "^6.2.14",
|
||||||
"lucide-react": "^1.64.0",
|
"lucide-react": "^1.64.0",
|
||||||
"motion": "^14.8.0",
|
"motion": "^14.8.0",
|
||||||
|
"qrcode": "^1.5.4",
|
||||||
"react": "^19.3.1",
|
"react": "^19.3.1",
|
||||||
"react-dom": "^19.3.1",
|
"react-dom": "^19.3.1",
|
||||||
|
"sharp": "^0.35.5",
|
||||||
"tailwind-merge": "^3.7.0",
|
"tailwind-merge": "^3.7.0",
|
||||||
"tailwindcss": "^4.3.3",
|
"tailwindcss": "^4.3.3",
|
||||||
"zod": "^4.6.7"
|
"zod": "^4.6.7"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/node": "^26.6.6",
|
"@types/node": "^26.6.6",
|
||||||
|
"@types/qrcode": "^1.5.6",
|
||||||
"@types/react": "^19.3.0",
|
"@types/react": "^19.3.0",
|
||||||
"@types/react-dom": "^19.3.0"
|
"@types/react-dom": "^19.3.0",
|
||||||
|
"cheerio": "^1.2.0",
|
||||||
|
"pinyin-pro": "^3.29.5",
|
||||||
|
"tsx": "^4.23.15",
|
||||||
|
"typescript": "^6.0.3"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Generated
+687
-23
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,69 @@
|
|||||||
|
/**
|
||||||
|
* 按型号目录回填马达 / 扬声器的尺寸、体积、功率。
|
||||||
|
*
|
||||||
|
* 示例:
|
||||||
|
* pnpm tsx scripts/apply-hardware-catalog.mjs # 只统计
|
||||||
|
* pnpm tsx scripts/apply-hardware-catalog.mjs --write # 写库
|
||||||
|
*/
|
||||||
|
import { enrichHardwareSpecs, lookupMotorModel, lookupSpeakerModel } from '../src/lib/hardware-catalog';
|
||||||
|
import { listDevices, saveDevice } from '../src/lib/repo';
|
||||||
|
|
||||||
|
const write = process.argv.includes('--write');
|
||||||
|
|
||||||
|
const stats = {
|
||||||
|
devices: 0,
|
||||||
|
changed: 0,
|
||||||
|
motors: 0,
|
||||||
|
motorSizes: 0,
|
||||||
|
motorVolumes: 0,
|
||||||
|
units: 0,
|
||||||
|
unitFilled: 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
const changedSamples = [];
|
||||||
|
|
||||||
|
for (const device of listDevices()) {
|
||||||
|
stats.devices += 1;
|
||||||
|
const before = JSON.stringify(device.specs);
|
||||||
|
const afterSpecs = enrichHardwareSpecs(device.specs);
|
||||||
|
const after = JSON.stringify(afterSpecs);
|
||||||
|
if (before === after) continue;
|
||||||
|
|
||||||
|
stats.changed += 1;
|
||||||
|
const motor = device.specs.vibration;
|
||||||
|
const nextMotor = afterSpecs.vibration;
|
||||||
|
if (motor?.model && lookupMotorModel(motor.model)) {
|
||||||
|
stats.motors += 1;
|
||||||
|
if (!motor.size && nextMotor?.size) stats.motorSizes += 1;
|
||||||
|
if (!motor.volume && nextMotor?.volume) stats.motorVolumes += 1;
|
||||||
|
}
|
||||||
|
const units = device.specs.speakers?.units ?? [];
|
||||||
|
const nextUnits = afterSpecs.speakers?.units ?? [];
|
||||||
|
units.forEach((unit, index) => {
|
||||||
|
if (!unit.model || !lookupSpeakerModel(unit.model)) return;
|
||||||
|
stats.units += 1;
|
||||||
|
if ((!unit.size && nextUnits[index]?.size) || (!unit.power && nextUnits[index]?.power)) {
|
||||||
|
stats.unitFilled += 1;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (changedSamples.length < 8) {
|
||||||
|
changedSamples.push({
|
||||||
|
slug: device.slug,
|
||||||
|
motor: afterSpecs.vibration,
|
||||||
|
units: afterSpecs.speakers?.units,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (write) saveDevice({ ...device, specs: afterSpecs });
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`扫描 ${stats.devices} 款,需回填 ${stats.changed} 款(${write ? '已写入' : '未写入,加 --write 生效'})`);
|
||||||
|
console.log(
|
||||||
|
`马达:可识别 ${stats.motors} 款,补尺寸 ${stats.motorSizes},补体积 ${stats.motorVolumes}`,
|
||||||
|
);
|
||||||
|
console.log(`扬声器:可识别单元 ${stats.units},补尺寸/功率 ${stats.unitFilled}`);
|
||||||
|
console.log('示例:');
|
||||||
|
for (const sample of changedSamples) {
|
||||||
|
console.log(JSON.stringify(sample));
|
||||||
|
}
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
import { DatabaseSync } from 'node:sqlite';
|
import { DatabaseSync } from 'node:sqlite';
|
||||||
import { cpSync, existsSync, mkdirSync } from 'node:fs';
|
import { cpSync, existsSync, mkdirSync } from 'node:fs';
|
||||||
|
|
||||||
|
if (existsSync('.env')) process.loadEnvFile('.env');
|
||||||
|
|
||||||
const DB_PATH = process.env.DB_PATH ?? 'data/app.db';
|
const DB_PATH = process.env.DB_PATH ?? 'data/app.db';
|
||||||
const UPLOADS = process.env.UPLOADS_DIR ?? 'data/uploads';
|
const UPLOADS = process.env.UPLOADS_DIR ?? 'data/uploads';
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,611 @@
|
|||||||
|
[
|
||||||
|
{
|
||||||
|
"slug": "redmi-k90-pro-max",
|
||||||
|
"category": "phone",
|
||||||
|
"brand": "Redmi",
|
||||||
|
"model": "K90 Pro Max",
|
||||||
|
"aliases": [
|
||||||
|
"红米 K90 Pro Max",
|
||||||
|
"25102RKBEC"
|
||||||
|
],
|
||||||
|
"announceDate": "2025-10-23",
|
||||||
|
"lifecycle": "released",
|
||||||
|
"gallery": [],
|
||||||
|
"tags": [
|
||||||
|
"旗舰",
|
||||||
|
"大屏",
|
||||||
|
"BOSE 三扬声器",
|
||||||
|
"潜望长焦"
|
||||||
|
],
|
||||||
|
"summary": "REDMI K 系列大屏旗舰,第五代骁龙 8 至尊版搭配 BOSE 2.1 三扬声器。",
|
||||||
|
"chipRefs": {},
|
||||||
|
"specs": {
|
||||||
|
"body": {
|
||||||
|
"dimensions": "163.33 x 77.82 x 7.9 mm (黑色/流金白); 8.3 mm (丹宁色)",
|
||||||
|
"weight": "218g (黑色/流金白); 220g (丹宁色)",
|
||||||
|
"build": {
|
||||||
|
"front": "小米龙晶玻璃",
|
||||||
|
"frame": "航空铝边框"
|
||||||
|
},
|
||||||
|
"sim": "双 Nano-SIM",
|
||||||
|
"ipRating": "IP68",
|
||||||
|
"colors": [
|
||||||
|
"黑色",
|
||||||
|
"流金白",
|
||||||
|
"丹宁色",
|
||||||
|
"冠军版"
|
||||||
|
],
|
||||||
|
"cooling": "6700mm² 3D 冰封循环冷泵"
|
||||||
|
},
|
||||||
|
"display": {
|
||||||
|
"size": "6.9 英寸",
|
||||||
|
"resolution": "2608 x 1200",
|
||||||
|
"cutout": "中孔",
|
||||||
|
"aspectRatio": "19.5:9",
|
||||||
|
"panel": "OLED 直屏",
|
||||||
|
"refreshRate": "120Hz",
|
||||||
|
"refreshRange": "",
|
||||||
|
"refreshNote": "",
|
||||||
|
"touchSampling": "最高 480Hz",
|
||||||
|
"touchSamplingInstant": "",
|
||||||
|
"colorDepth": "12bit (687亿色)",
|
||||||
|
"colorGamut": "DCI-P3 广色域",
|
||||||
|
"pixelDensity": "",
|
||||||
|
"brightnessPeak": "3500nits (多场景峰值亮度)",
|
||||||
|
"hdr": "HDR10+ / HDR Vivid / Dolby Vision",
|
||||||
|
"protection": "小米龙晶玻璃",
|
||||||
|
"pwmDimming": "全亮度 DC 调光",
|
||||||
|
"features": [
|
||||||
|
"专业原色屏",
|
||||||
|
"多屏同色",
|
||||||
|
"湿手触控 2.0",
|
||||||
|
"1nit 最低亮度"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"platform": {
|
||||||
|
"os": "Android",
|
||||||
|
"skin": "Xiaomi HyperOS 3",
|
||||||
|
"chipset": "第五代骁龙 8 至尊版"
|
||||||
|
},
|
||||||
|
"memory": {
|
||||||
|
"ram": "12GB / 16GB",
|
||||||
|
"ramType": "LPDDR5X",
|
||||||
|
"storage": "256GB / 512GB / 1TB",
|
||||||
|
"storageType": "UFS 4.1"
|
||||||
|
},
|
||||||
|
"rearCamera": [
|
||||||
|
{
|
||||||
|
"position": "wide",
|
||||||
|
"sensorAlias": "光影猎人 950",
|
||||||
|
"resolution": "50MP",
|
||||||
|
"sensorSize": "1/1.31\"",
|
||||||
|
"pixelSize": "2.4µm(4in1)",
|
||||||
|
"lensElements": "1G+6P",
|
||||||
|
"ois": true,
|
||||||
|
"eis": true,
|
||||||
|
"video": {
|
||||||
|
"max": "8K@30fps",
|
||||||
|
"modes": [
|
||||||
|
"8K@30fps",
|
||||||
|
"4K@30/60fps",
|
||||||
|
"1080P@30/60fps",
|
||||||
|
"720P@30fps",
|
||||||
|
"720P 慢动作 120/240/480/960/1920fps",
|
||||||
|
"1080P 慢动作 120/240/960fps"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"extra": {}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"position": "periscope",
|
||||||
|
"sensorModel": "Samsung S5KJN5",
|
||||||
|
"resolution": "50MP",
|
||||||
|
"aperture": "f/3.0",
|
||||||
|
"sensorSize": "1/2.76\"",
|
||||||
|
"pixelSize": "0.64µm",
|
||||||
|
"ois": true,
|
||||||
|
"zoom": "5x 光学 / 10x 无损",
|
||||||
|
"autofocusType": "全像素对焦",
|
||||||
|
"extra": {}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"position": "ultrawide",
|
||||||
|
"sensorModel": "OmniVision OV50M",
|
||||||
|
"resolution": "50MP",
|
||||||
|
"aperture": "f/2.4",
|
||||||
|
"fov": "102°",
|
||||||
|
"extra": {}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"frontCamera": [
|
||||||
|
{
|
||||||
|
"position": "front",
|
||||||
|
"resolution": "32MP",
|
||||||
|
"video": {
|
||||||
|
"max": "4K@30fps",
|
||||||
|
"modes": [
|
||||||
|
"4K@30fps",
|
||||||
|
"1080P@30/60fps",
|
||||||
|
"720P@30fps",
|
||||||
|
"720P 慢动作 120fps"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"extra": {}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"vibration": {
|
||||||
|
"type": "X 轴线性马达"
|
||||||
|
},
|
||||||
|
"speakers": {
|
||||||
|
"count": 3,
|
||||||
|
"stereo": true,
|
||||||
|
"units": [
|
||||||
|
{
|
||||||
|
"label": "上",
|
||||||
|
"model": "BOSE 对称立体声"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "下",
|
||||||
|
"model": "BOSE 对称立体声"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "低音炮",
|
||||||
|
"model": "BOSE 独立低音单元",
|
||||||
|
"size": "大尺寸"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"dolbyAtmos": true,
|
||||||
|
"hiRes": true,
|
||||||
|
"headphoneJack": false
|
||||||
|
},
|
||||||
|
"connectivity": {
|
||||||
|
"cellular": "5G / 4G / 3G / 2G,双卡双通",
|
||||||
|
"bands": [
|
||||||
|
"5G n1",
|
||||||
|
"5G n3",
|
||||||
|
"5G n5",
|
||||||
|
"5G n7",
|
||||||
|
"5G n8",
|
||||||
|
"5G n18",
|
||||||
|
"5G n26",
|
||||||
|
"5G n28",
|
||||||
|
"5G n66",
|
||||||
|
"5G n38",
|
||||||
|
"5G n40",
|
||||||
|
"5G n41",
|
||||||
|
"5G n48",
|
||||||
|
"5G n77",
|
||||||
|
"5G n78",
|
||||||
|
"5G n80",
|
||||||
|
"5G n81",
|
||||||
|
"5G n83",
|
||||||
|
"5G n84",
|
||||||
|
"5G n89",
|
||||||
|
"4G B1",
|
||||||
|
"4G B3",
|
||||||
|
"4G B4",
|
||||||
|
"4G B5",
|
||||||
|
"4G B7",
|
||||||
|
"4G B8",
|
||||||
|
"4G B18",
|
||||||
|
"4G B19",
|
||||||
|
"4G B26",
|
||||||
|
"4G B28",
|
||||||
|
"4G B66",
|
||||||
|
"4G B34",
|
||||||
|
"4G B38",
|
||||||
|
"4G B39",
|
||||||
|
"4G B40",
|
||||||
|
"4G B41",
|
||||||
|
"4G B42",
|
||||||
|
"4G B48",
|
||||||
|
"3G B1",
|
||||||
|
"3G B4",
|
||||||
|
"3G B5",
|
||||||
|
"3G B6",
|
||||||
|
"3G B8",
|
||||||
|
"3G B19",
|
||||||
|
"2G B3",
|
||||||
|
"2G B5",
|
||||||
|
"2G B8"
|
||||||
|
],
|
||||||
|
"satellite": false,
|
||||||
|
"satelliteBands": [],
|
||||||
|
"wifi": "Wi-Fi 7 / Wi-Fi 6 / Wi-Fi 5 / Wi-Fi 4",
|
||||||
|
"bluetooth": "Bluetooth 5.4",
|
||||||
|
"nfc": true,
|
||||||
|
"gps": "北斗 B1I+B1C+B2a / GPS L1+L5 / Galileo E1+E5a / GLONASS G1 / QZSS L1+L5 / NavIC",
|
||||||
|
"usb": "USB Type-C(双面充电接口)",
|
||||||
|
"usbSpeed": "",
|
||||||
|
"ir": true
|
||||||
|
},
|
||||||
|
"battery": {
|
||||||
|
"capacity": "7560mAh (typ) / 7420mAh (min)",
|
||||||
|
"type": "锂离子聚合物电池",
|
||||||
|
"wired": "100W 有线秒充",
|
||||||
|
"wireless": "50W 无线秒充",
|
||||||
|
"reverse": "22.5W 有线/无线反充",
|
||||||
|
"chargingProtocol": "QC2.0 / QC3.0 / QC3+ / PD2.0 / PD3.0"
|
||||||
|
},
|
||||||
|
"sensors": {
|
||||||
|
"fingerprint": "3D 超声波指纹",
|
||||||
|
"fingerprintType": "超声波",
|
||||||
|
"fingerprintPosition": "屏下",
|
||||||
|
"gyro": true,
|
||||||
|
"colorSensor": true,
|
||||||
|
"flickerSensor": true,
|
||||||
|
"list": [
|
||||||
|
"光学距离传感器",
|
||||||
|
"360° 前后双光感",
|
||||||
|
"加速度传感器",
|
||||||
|
"环境色温传感器",
|
||||||
|
"电子罗盘",
|
||||||
|
"陀螺仪",
|
||||||
|
"红外遥控",
|
||||||
|
"Flicker 传感器"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"software": {
|
||||||
|
"launchVersion": "Xiaomi HyperOS 3",
|
||||||
|
"updatePolicy": "",
|
||||||
|
"updateTimeline": []
|
||||||
|
},
|
||||||
|
"features": [
|
||||||
|
"AI 独显芯片 D2",
|
||||||
|
"IP68 防尘防水",
|
||||||
|
"2.1 立体声豪华三扬",
|
||||||
|
"大尺寸独立低音炮",
|
||||||
|
"小米澎湃 P3 充电芯片",
|
||||||
|
"小米澎湃 G2 自研电量计芯片",
|
||||||
|
"NFC",
|
||||||
|
"红外遥控"
|
||||||
|
],
|
||||||
|
"cameraFeatures": [
|
||||||
|
"运动抓拍",
|
||||||
|
"HDR 10+",
|
||||||
|
"胶片滤镜",
|
||||||
|
"胶片水印",
|
||||||
|
"打卡水印",
|
||||||
|
"经典水印",
|
||||||
|
"文档模式",
|
||||||
|
"声控拍照",
|
||||||
|
"倒计时",
|
||||||
|
"动态照片",
|
||||||
|
"超级微距",
|
||||||
|
"照片像素",
|
||||||
|
"超级防抖",
|
||||||
|
"提词器",
|
||||||
|
"夜景",
|
||||||
|
"测光模式",
|
||||||
|
"定时连拍",
|
||||||
|
"身份证影印模式",
|
||||||
|
"专业",
|
||||||
|
"慢动作",
|
||||||
|
"全景",
|
||||||
|
"延时摄影",
|
||||||
|
"长曝光",
|
||||||
|
"超级月亮"
|
||||||
|
],
|
||||||
|
"benchmarks": [],
|
||||||
|
"pricing": [
|
||||||
|
"12GB+256GB 3999 元",
|
||||||
|
"12GB+512GB 4499 元",
|
||||||
|
"16GB+256GB 4799 元",
|
||||||
|
"16GB+1TB 5299 元"
|
||||||
|
],
|
||||||
|
"officialUrl": "https://www.mi.com/prod/redmi-k90-pro-max",
|
||||||
|
"extra": {}
|
||||||
|
},
|
||||||
|
"meta": [
|
||||||
|
{
|
||||||
|
"path": "specs",
|
||||||
|
"confidence": "high",
|
||||||
|
"sourceUrl": "https://www.mi.com/prod/redmi-k90-pro-max/specs",
|
||||||
|
"verified": true,
|
||||||
|
"capturedAt": "2026-11-02T10:57:04.732Z"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "specs.pricing",
|
||||||
|
"confidence": "medium",
|
||||||
|
"verified": false,
|
||||||
|
"capturedAt": "2026-11-02T10:57:04.732Z"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"slug": "oppo-find-x10-pro-max",
|
||||||
|
"category": "phone",
|
||||||
|
"brand": "OPPO",
|
||||||
|
"model": "Find X10 Pro Max",
|
||||||
|
"aliases": [
|
||||||
|
"OPPO Find X10 Pro Max",
|
||||||
|
"PMX110"
|
||||||
|
],
|
||||||
|
"announceDate": "2026-09-22",
|
||||||
|
"lifecycle": "released",
|
||||||
|
"gallery": [],
|
||||||
|
"tags": [
|
||||||
|
"影像旗舰",
|
||||||
|
"2 亿三摄",
|
||||||
|
"天玑 9600 Pro",
|
||||||
|
"8000mAh"
|
||||||
|
],
|
||||||
|
"summary": "OPPO 影像旗舰,三颗 2 亿像素镜头、天玑 9600 Pro 与 8000mAh 冰川电池。",
|
||||||
|
"chipRefs": {},
|
||||||
|
"specs": {
|
||||||
|
"body": {
|
||||||
|
"dimensions": "161.32 × 76.57 × 8.40 mm",
|
||||||
|
"weight": "约 235 克(暖橙,浅钛);约 233 克(月白)",
|
||||||
|
"sim": "Nano-SIM 卡,Nano-USIM 卡",
|
||||||
|
"colors": [
|
||||||
|
"浅钛",
|
||||||
|
"暖橙",
|
||||||
|
"月白"
|
||||||
|
],
|
||||||
|
"cooling": "冰河散热系统"
|
||||||
|
},
|
||||||
|
"display": {
|
||||||
|
"size": "6.78 英寸",
|
||||||
|
"resolution": "FHD+ 2772×1272 像素",
|
||||||
|
"cutout": "中孔",
|
||||||
|
"panel": "柔性 AMOLED 直屏",
|
||||||
|
"refreshRate": "最高 144Hz",
|
||||||
|
"refreshRange": "1-120Hz 智能切换",
|
||||||
|
"refreshNote": "1-120Hz 智能切换,最高支持 144Hz(144Hz 只在部分游戏场景生效)",
|
||||||
|
"touchSampling": "288Hz",
|
||||||
|
"colorDepth": "10.7 亿色(10-bit)",
|
||||||
|
"colorGamut": "标准模式:95% BT2020;自然模式:95% BT2020;鲜明模式:95% BT2020",
|
||||||
|
"pixelDensity": "450 PPI",
|
||||||
|
"brightnessTypical": "全局默认最高亮度:800 尼特典型值",
|
||||||
|
"brightnessPeak": "全局激发最高亮度:2000 尼特典型值",
|
||||||
|
"features": [
|
||||||
|
"1nit 明眸护眼屏",
|
||||||
|
"ProXDR",
|
||||||
|
"湿手触控"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"platform": {
|
||||||
|
"os": "Android",
|
||||||
|
"skin": "ColorOS 17.0",
|
||||||
|
"chipset": "MediaTek 天玑 9600 Pro"
|
||||||
|
},
|
||||||
|
"memory": {
|
||||||
|
"ram": "12GB,16GB",
|
||||||
|
"ramType": "LPDDR5X",
|
||||||
|
"storage": "256GB,512GB,1TB",
|
||||||
|
"storageType": "UFS 4.1",
|
||||||
|
"cardSlot": "不支持"
|
||||||
|
},
|
||||||
|
"rearCamera": [
|
||||||
|
{
|
||||||
|
"position": "wide",
|
||||||
|
"resolution": "2 亿像素",
|
||||||
|
"aperture": "f/1.5",
|
||||||
|
"focalLength": "等效焦距 24 毫米",
|
||||||
|
"lensElements": "7P",
|
||||||
|
"ois": true,
|
||||||
|
"autofocusType": "AF 自动对焦",
|
||||||
|
"video": {
|
||||||
|
"max": "8K@30fps",
|
||||||
|
"modes": [],
|
||||||
|
"stabilization": "支持视频防抖拍摄"
|
||||||
|
},
|
||||||
|
"extra": {}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"position": "ultrawide",
|
||||||
|
"resolution": "2 亿像素",
|
||||||
|
"aperture": "f/2.2",
|
||||||
|
"focalLength": "等效焦距 13 毫米",
|
||||||
|
"lensElements": "7P",
|
||||||
|
"fov": "124° 广视角",
|
||||||
|
"autofocusType": "AF 自动对焦",
|
||||||
|
"extra": {}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"position": "tele",
|
||||||
|
"resolution": "2 亿像素",
|
||||||
|
"aperture": "f/2.1",
|
||||||
|
"focalLength": "等效焦距 70 毫米",
|
||||||
|
"lensElements": "3P+3P",
|
||||||
|
"ois": true,
|
||||||
|
"zoom": "3 倍光学变焦,最高 120 倍数码变焦",
|
||||||
|
"autofocusType": "AF 自动对焦",
|
||||||
|
"extra": {}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"position": "color",
|
||||||
|
"sensorAlias": "第二代丹霞色彩还原镜头",
|
||||||
|
"aperture": "f/2.4",
|
||||||
|
"focalLength": "19mm",
|
||||||
|
"lensElements": "3P",
|
||||||
|
"extra": {}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"frontCamera": [
|
||||||
|
{
|
||||||
|
"position": "front",
|
||||||
|
"resolution": "5000 万像素",
|
||||||
|
"aperture": "f/2.0",
|
||||||
|
"focalLength": "等效焦距 18 毫米",
|
||||||
|
"lensElements": "5P",
|
||||||
|
"autofocusType": "AF 自动对焦",
|
||||||
|
"video": {
|
||||||
|
"max": "4K@60fps",
|
||||||
|
"modes": []
|
||||||
|
},
|
||||||
|
"extra": {}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"vibration": {
|
||||||
|
"type": "X 轴线性马达",
|
||||||
|
"model": "仿生振感马达 Pro"
|
||||||
|
},
|
||||||
|
"speakers": {
|
||||||
|
"count": 2,
|
||||||
|
"stereo": true,
|
||||||
|
"units": [],
|
||||||
|
"dolbyAtmos": true,
|
||||||
|
"hiRes": true,
|
||||||
|
"headphoneJack": false
|
||||||
|
},
|
||||||
|
"connectivity": {
|
||||||
|
"cellular": "5G / 4G / 3G / 2G,双卡(部分场景双通)",
|
||||||
|
"bands": [
|
||||||
|
"2G GSM 850MHz",
|
||||||
|
"2G GSM 900MHz",
|
||||||
|
"2G GSM 1800MHz",
|
||||||
|
"3G WCDMA 1",
|
||||||
|
"3G WCDMA 2",
|
||||||
|
"3G WCDMA 4",
|
||||||
|
"3G WCDMA 5",
|
||||||
|
"3G WCDMA 6",
|
||||||
|
"3G WCDMA 8",
|
||||||
|
"3G WCDMA 19",
|
||||||
|
"4G FDD 1",
|
||||||
|
"4G FDD 2",
|
||||||
|
"4G FDD 3",
|
||||||
|
"4G FDD 4",
|
||||||
|
"4G FDD 5",
|
||||||
|
"4G FDD 7",
|
||||||
|
"4G FDD 8",
|
||||||
|
"4G FDD 12",
|
||||||
|
"4G FDD 17",
|
||||||
|
"4G FDD 18",
|
||||||
|
"4G FDD 19",
|
||||||
|
"4G FDD 20",
|
||||||
|
"4G FDD 25",
|
||||||
|
"4G FDD 26",
|
||||||
|
"4G FDD 28",
|
||||||
|
"4G FDD 66",
|
||||||
|
"4G TDD 34",
|
||||||
|
"4G TDD 38",
|
||||||
|
"4G TDD 39",
|
||||||
|
"4G TDD 40",
|
||||||
|
"4G TDD 41",
|
||||||
|
"4G TDD 42",
|
||||||
|
"4G TDD 43",
|
||||||
|
"4G TDD 48",
|
||||||
|
"5G n1",
|
||||||
|
"5G n2",
|
||||||
|
"5G n3",
|
||||||
|
"5G n5",
|
||||||
|
"5G n7",
|
||||||
|
"5G n8",
|
||||||
|
"5G n12",
|
||||||
|
"5G n18",
|
||||||
|
"5G n20",
|
||||||
|
"5G n25",
|
||||||
|
"5G n26",
|
||||||
|
"5G n28",
|
||||||
|
"5G n34",
|
||||||
|
"5G n38",
|
||||||
|
"5G n39",
|
||||||
|
"5G n40",
|
||||||
|
"5G n41",
|
||||||
|
"5G n48",
|
||||||
|
"5G n66",
|
||||||
|
"5G n77",
|
||||||
|
"5G n78",
|
||||||
|
"5G n79"
|
||||||
|
],
|
||||||
|
"satellite": false,
|
||||||
|
"satelliteBands": [],
|
||||||
|
"wifi": "Wi-Fi 7(802.11be),Wi-Fi 6(802.11ax),Wi-Fi 5(802.11ac),802.11a/b/g/n",
|
||||||
|
"bluetooth": "蓝牙 6.2,低功耗蓝牙,BLE Audio",
|
||||||
|
"nfc": true,
|
||||||
|
"gps": "北斗(B1I+B1C+B2a+B2b),GPS(L1+L5),GLONASS(G1),Galileo(E1+E5a+E5b),QZSS(L1+L5),NavIC(L5)",
|
||||||
|
"usb": "USB Type-C,USB 3.2 Gen 1",
|
||||||
|
"usbSpeed": "5 Gbps",
|
||||||
|
"ir": true
|
||||||
|
},
|
||||||
|
"battery": {
|
||||||
|
"capacity": "8000 mAh/29.76 Wh(典型值);7790 mAh/28.98 Wh(额定值)",
|
||||||
|
"type": "锂聚合物电池",
|
||||||
|
"wired": "80W 超级闪充 / 80W UFCS",
|
||||||
|
"wireless": "50W 无线闪充",
|
||||||
|
"reverse": "",
|
||||||
|
"chargingProtocol": "兼容 67 W 及以下超级闪充,44 W 三方 UFCS 融合快充,55 W PPS,13.5 W PD"
|
||||||
|
},
|
||||||
|
"sensors": {
|
||||||
|
"fingerprint": "屏下超声波指纹",
|
||||||
|
"fingerprintType": "超声波",
|
||||||
|
"fingerprintPosition": "屏下",
|
||||||
|
"gyro": true,
|
||||||
|
"colorSensor": true,
|
||||||
|
"list": [
|
||||||
|
"接近感应器",
|
||||||
|
"环境光传感器",
|
||||||
|
"色温传感器",
|
||||||
|
"电子罗盘",
|
||||||
|
"加速度传感器",
|
||||||
|
"陀螺仪",
|
||||||
|
"屏下超声指纹",
|
||||||
|
"霍尔传感器",
|
||||||
|
"激光对焦传感器",
|
||||||
|
"光谱传感器",
|
||||||
|
"红外遥控"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"software": {
|
||||||
|
"launchVersion": "ColorOS 17.0",
|
||||||
|
"currentVersion": "ColorOS 17.0",
|
||||||
|
"updateTimeline": []
|
||||||
|
},
|
||||||
|
"features": [
|
||||||
|
"哈苏影像",
|
||||||
|
"三颗 2 亿像素镜头",
|
||||||
|
"天玑 9600 Pro",
|
||||||
|
"8000mAh 冰川电池",
|
||||||
|
"1nit 明眸护眼屏",
|
||||||
|
"超声波指纹",
|
||||||
|
"冰河散热系统",
|
||||||
|
"对称立体声双扬声器"
|
||||||
|
],
|
||||||
|
"cameraFeatures": [
|
||||||
|
"照片",
|
||||||
|
"视频",
|
||||||
|
"人像",
|
||||||
|
"夜景",
|
||||||
|
"全景",
|
||||||
|
"慢动作",
|
||||||
|
"长曝光",
|
||||||
|
"延时摄影",
|
||||||
|
"萌拍",
|
||||||
|
"XPAN",
|
||||||
|
"水下相机",
|
||||||
|
"大师",
|
||||||
|
"AI 证件照",
|
||||||
|
"超级文本",
|
||||||
|
"扫一扫",
|
||||||
|
"专业视频",
|
||||||
|
"哈苏超清",
|
||||||
|
"哈苏增距"
|
||||||
|
],
|
||||||
|
"benchmarks": [],
|
||||||
|
"pricing": [
|
||||||
|
"12GB+256GB 6799 元",
|
||||||
|
"12GB+512GB 7499 元",
|
||||||
|
"16GB+512GB 7999 元",
|
||||||
|
"16GB+1TB 8999 元"
|
||||||
|
],
|
||||||
|
"officialUrl": "https://www.oppo.com/cn/smartphones/series-find-x/find-x10-pro-max/specs/",
|
||||||
|
"extra": {}
|
||||||
|
},
|
||||||
|
"meta": [
|
||||||
|
{
|
||||||
|
"path": "specs",
|
||||||
|
"confidence": "high",
|
||||||
|
"sourceUrl": "https://www.oppo.com/cn/smartphones/series-find-x/find-x10-pro-max/specs/",
|
||||||
|
"verified": true,
|
||||||
|
"capturedAt": "2026-11-02T10:57:04.732Z"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "specs.pricing",
|
||||||
|
"confidence": "medium",
|
||||||
|
"verified": false,
|
||||||
|
"capturedAt": "2026-11-02T10:57:04.732Z"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
+161
-44
@@ -2,6 +2,8 @@ import { DatabaseSync } from 'node:sqlite';
|
|||||||
import { existsSync, mkdirSync, readFileSync, readdirSync } from 'node:fs';
|
import { existsSync, mkdirSync, readFileSync, readdirSync } from 'node:fs';
|
||||||
import { dirname, join } from 'node:path';
|
import { dirname, join } from 'node:path';
|
||||||
|
|
||||||
|
if (existsSync('.env')) process.loadEnvFile('.env');
|
||||||
|
|
||||||
const DB_PATH = process.env.DB_PATH ?? 'data/app.db';
|
const DB_PATH = process.env.DB_PATH ?? 'data/app.db';
|
||||||
const now = new Date().toISOString();
|
const now = new Date().toISOString();
|
||||||
|
|
||||||
@@ -38,11 +40,14 @@ const soc = {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: '性能核',
|
name: '性能核',
|
||||||
cores: [{ microArch: 'Cortex-A720', count: 3, clockMax: '3.15 GHz', l2: '512 KB' }],
|
cores: [
|
||||||
|
{ microArch: 'Cortex-A720', count: 3, clockMax: '3.15 GHz', l2: '512 KB' },
|
||||||
|
{ microArch: 'Cortex-A720', count: 2, clockMax: '2.96 GHz', l2: '512 KB' },
|
||||||
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: '能效核',
|
name: '能效核',
|
||||||
cores: [{ microArch: 'Cortex-A520', count: 2, clockMax: '2.27 GHz', l2: '256 KB' }],
|
cores: [{ microArch: 'Cortex-A520', count: 2, clockMax: '2.27 GHz', l2: '512 KB' }],
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
gpuBlock: {
|
gpuBlock: {
|
||||||
@@ -52,6 +57,7 @@ const soc = {
|
|||||||
apis: ['Vulkan 1.3', 'OpenGL ES 3.2', 'OpenCL 2.0'],
|
apis: ['Vulkan 1.3', 'OpenGL ES 3.2', 'OpenCL 2.0'],
|
||||||
},
|
},
|
||||||
npuBlock: { name: 'Hexagon NPU', tops: '约 45 TOPS (INT8)' },
|
npuBlock: { name: 'Hexagon NPU', tops: '约 45 TOPS (INT8)' },
|
||||||
|
systemCache: '6 MB',
|
||||||
ispBlock: 'Spectra 18-bit',
|
ispBlock: 'Spectra 18-bit',
|
||||||
modemBlock: 'Snapdragon X75 5G',
|
modemBlock: 'Snapdragon X75 5G',
|
||||||
memorySupport: { type: 'LPDDR5X', maxClock: '4800 MHz', bandwidth: '76.8 GB/s' },
|
memorySupport: { type: 'LPDDR5X', maxClock: '4800 MHz', bandwidth: '76.8 GB/s' },
|
||||||
@@ -59,9 +65,12 @@ const soc = {
|
|||||||
displaySupport: '最高 4K@60Hz / QHD+@144Hz',
|
displaySupport: '最高 4K@60Hz / QHD+@144Hz',
|
||||||
videoCodec: { encode: ['H.264', 'H.265', 'AV1'], decode: ['H.264', 'H.265', 'AV1'] },
|
videoCodec: { encode: ['H.264', 'H.265', 'AV1'], decode: ['H.264', 'H.265', 'AV1'] },
|
||||||
benchmarks: [
|
benchmarks: [
|
||||||
{ name: 'Geekbench 6 单核', score: '2200', unit: 'pts' },
|
{ name: 'Geekbench 5 单核', score: '1700', unit: 'pts' },
|
||||||
{ name: 'Geekbench 6 多核', score: '6800', unit: 'pts' },
|
{ name: 'Geekbench 5 多核', score: '6600', unit: 'pts' },
|
||||||
{ name: '安兔兔 V10', score: '2100000', unit: 'pts' },
|
{ name: 'Geekbench 6 单核', score: '2300', unit: 'pts' },
|
||||||
|
{ name: 'Geekbench 6 多核', score: '7400', unit: 'pts' },
|
||||||
|
{ name: '安兔兔 V10', score: '2200000', unit: 'pts' },
|
||||||
|
{ name: '安兔兔 V11', score: '2300000', unit: 'pts' },
|
||||||
],
|
],
|
||||||
extra: {},
|
extra: {},
|
||||||
},
|
},
|
||||||
@@ -90,51 +99,82 @@ const phone = {
|
|||||||
chipRefs: { soc: 'snapdragon-8-gen-3' },
|
chipRefs: { soc: 'snapdragon-8-gen-3' },
|
||||||
specs: {
|
specs: {
|
||||||
body: {
|
body: {
|
||||||
dimensions: '152.8 x 71.5 x 8.2 mm',
|
dimensions: '152.8 x 71.5 x 8.20 mm(玻璃)/ 8.28 mm(科技纳米皮)',
|
||||||
weight: '188 g',
|
weight: '193 g(玻璃)/ 188 g(科技纳米皮)',
|
||||||
build: { front: '康宁大猩猩 Victus', back: '玻璃', frame: '铝合金' },
|
build: { front: '康宁大猩猩 Victus 2', back: '玻璃 / 科技纳米皮', frame: '铝合金边框' },
|
||||||
sim: 'Nano-SIM + eSIM',
|
sim: '2 × Nano-SIM',
|
||||||
ipRating: 'IP68',
|
ipRating: 'IP68',
|
||||||
colors: ['黑色', '白色', '岩石青', '雪山粉'],
|
colors: ['黑色', '白色', '岩石青', '雪山粉'],
|
||||||
buttons: '右侧电源 + 音量',
|
buttons: '右侧电源 + 音量',
|
||||||
|
cooling: '环形冷泵散热系统',
|
||||||
},
|
},
|
||||||
display: {
|
display: {
|
||||||
size: '6.36 英寸',
|
size: '6.36 英寸',
|
||||||
resolution: '2670 x 1200',
|
resolution: '2670 x 1200',
|
||||||
aspectRatio: '20:9',
|
cutout: '中孔',
|
||||||
panel: 'LTPO AMOLED',
|
aspectRatio: '20.0:9',
|
||||||
refreshRate: '120Hz',
|
panel: 'OLED',
|
||||||
|
vendor: '华星光电(TCL 华星)',
|
||||||
|
technology: 'C8 发光材质',
|
||||||
|
refreshRate: '120Hz 自适应',
|
||||||
refreshRange: '1-120Hz',
|
refreshRange: '1-120Hz',
|
||||||
touchSampling: '300Hz',
|
refreshNote: 'LTPO 1-120Hz 自适应刷新率',
|
||||||
|
touchSampling: '240Hz',
|
||||||
|
touchSamplingInstant: '最高 2160Hz',
|
||||||
|
colorDepth: '12bit / 687 亿色',
|
||||||
|
colorGamut: 'DCI-P3',
|
||||||
|
pixelDensity: '460 PPI',
|
||||||
|
equivalentPpi: '375 PPI',
|
||||||
|
screenBodyRatio: '89.3%',
|
||||||
|
bezel: '侧边 2.64mm,上+下 5.45mm',
|
||||||
|
width16x9: '5.34 英寸',
|
||||||
brightnessTypical: '600 nit',
|
brightnessTypical: '600 nit',
|
||||||
brightnessPeak: '3000 nit',
|
brightnessPeak: '3000 nit',
|
||||||
hdr: 'HDR10+ / Dolby Vision',
|
hdr: 'HDR10+ / HDR Vivid / Dolby Vision',
|
||||||
protection: '康宁大猩猩 Victus',
|
protection: '康宁大猩猩 Victus 2',
|
||||||
pwmDimming: '1920Hz PWM',
|
pwmDimming: '1920Hz PWM',
|
||||||
alwaysOn: true,
|
alwaysOn: true,
|
||||||
|
features: [
|
||||||
|
'专业原色屏',
|
||||||
|
'超动态显示',
|
||||||
|
'柔性直屏',
|
||||||
|
'前后双光感',
|
||||||
|
'心率检测',
|
||||||
|
'莱茵低蓝光认证',
|
||||||
|
'支持类DC调光',
|
||||||
|
'支持环境色温调节',
|
||||||
|
],
|
||||||
},
|
},
|
||||||
platform: { os: 'Android 14', skin: 'HyperOS', chipset: 'Snapdragon 8 Gen 3' },
|
platform: { os: 'Android 14', skin: 'Xiaomi HyperOS', chipset: 'Snapdragon 8 Gen 3' },
|
||||||
memory: {
|
memory: {
|
||||||
ram: '8 / 12 / 16 GB',
|
ram: '8 / 12 / 16 GB',
|
||||||
ramType: 'LPDDR5X',
|
ramType: 'LPDDR5X 8400 MT/s(4 × 16bit)',
|
||||||
storage: '256 / 512 GB / 1TB',
|
storage: '256 / 512 GB / 1TB',
|
||||||
storageType: 'UFS 4.0',
|
storageType: 'UFS 4.0',
|
||||||
|
storageSpeed: '约 4.2 GB/s 顺序读取',
|
||||||
cardSlot: '无',
|
cardSlot: '无',
|
||||||
},
|
},
|
||||||
rearCamera: [
|
rearCamera: [
|
||||||
{
|
{
|
||||||
position: 'wide',
|
position: 'wide',
|
||||||
sensorModel: 'OmniVision OV50H',
|
sensorModel: 'OmniVision OV50H',
|
||||||
resolution: '50MP',
|
sensorAlias: '光影猎人 900',
|
||||||
|
resolution: '50MP(默认合 1 输出 1250 万像素)',
|
||||||
aperture: 'f/1.6',
|
aperture: 'f/1.6',
|
||||||
focalLength: '23mm',
|
focalLength: '23mm',
|
||||||
sensorSize: '1/1.31"',
|
sensorSize: '1/1.31"',
|
||||||
pixelSize: '1.2µm',
|
pixelSize: '1.2µm',
|
||||||
lensElements: '7P',
|
lensElements: '7P',
|
||||||
ois: true,
|
ois: true,
|
||||||
|
eis: true,
|
||||||
zoom: '1x',
|
zoom: '1x',
|
||||||
autofocusType: '双像素 PDAF',
|
autofocusType: '全像素全向对焦 + 激光对焦',
|
||||||
video: { max: '8K@24fps', modes: ['4K@60fps', '1080p@240fps 慢动作'], stabilization: 'OIS + EIS' },
|
video: {
|
||||||
|
max: '8K@24fps',
|
||||||
|
modes: ['4K@60fps HDR10+ 录像', '1080p@240fps 慢动作', '电影模式'],
|
||||||
|
stabilization: 'OIS + EIS',
|
||||||
|
},
|
||||||
|
flash: '双色温 LED 闪光灯',
|
||||||
extra: {},
|
extra: {},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -142,13 +182,13 @@ const phone = {
|
|||||||
sensorModel: 'Samsung S5KJN1',
|
sensorModel: 'Samsung S5KJN1',
|
||||||
resolution: '50MP',
|
resolution: '50MP',
|
||||||
aperture: 'f/2.0',
|
aperture: 'f/2.0',
|
||||||
focalLength: '75mm',
|
focalLength: '75mm(60mm 裁切)',
|
||||||
sensorSize: '1/2.76"',
|
sensorSize: '1/2.76"',
|
||||||
pixelSize: '0.64µm',
|
pixelSize: '0.64µm',
|
||||||
lensElements: '6P',
|
lensElements: '6P',
|
||||||
ois: true,
|
ois: true,
|
||||||
zoom: '3.2x 光学 / 60x 数码',
|
zoom: '2.6x 光学(60mm)/ 3.2x(75mm)',
|
||||||
autofocusType: 'PDAF',
|
autofocusType: 'PDAF + 10cm 以上自动对焦',
|
||||||
extra: {},
|
extra: {},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -160,6 +200,7 @@ const phone = {
|
|||||||
sensorSize: '1/2.76"',
|
sensorSize: '1/2.76"',
|
||||||
pixelSize: '0.64µm',
|
pixelSize: '0.64µm',
|
||||||
lensElements: '6P',
|
lensElements: '6P',
|
||||||
|
fov: '115°',
|
||||||
ois: false,
|
ois: false,
|
||||||
zoom: '0.6x',
|
zoom: '0.6x',
|
||||||
extra: {},
|
extra: {},
|
||||||
@@ -168,22 +209,23 @@ const phone = {
|
|||||||
frontCamera: [
|
frontCamera: [
|
||||||
{
|
{
|
||||||
position: 'front',
|
position: 'front',
|
||||||
sensorModel: 'OmniVision OV32C',
|
sensorModel: 'OmniVision OV32B',
|
||||||
resolution: '32MP',
|
resolution: '32MP',
|
||||||
aperture: 'f/2.0',
|
aperture: 'f/2.0',
|
||||||
focalLength: '22mm',
|
focalLength: '22mm',
|
||||||
sensorSize: '1/3.14"',
|
sensorSize: '1/3.14"',
|
||||||
video: { max: '1080p@30fps', modes: [], stabilization: 'EIS' },
|
pixelSize: '0.7µm',
|
||||||
|
video: { max: '4K@60fps', modes: [], stabilization: 'EIS' },
|
||||||
extra: {},
|
extra: {},
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
vibration: { type: 'X 轴线性马达', model: 'AAC 0809', size: '0809' },
|
vibration: { type: 'X 轴线性马达', model: '瑞声 0809B', size: '0809', volume: '约 1.0 cm³' },
|
||||||
speakers: {
|
speakers: {
|
||||||
count: 2,
|
count: 2,
|
||||||
stereo: true,
|
stereo: true,
|
||||||
units: [
|
units: [
|
||||||
{ model: 'AAC 1116', size: '11 x 16 mm' },
|
{ position: 'top', label: '上', model: 'AAC 1115K', size: '11 × 15 mm' },
|
||||||
{ model: 'AAC 1012', size: '10 x 12 mm' },
|
{ position: 'bottom', label: '下', model: 'AAC 1014', size: '10 × 14 mm' },
|
||||||
],
|
],
|
||||||
dolbyAtmos: true,
|
dolbyAtmos: true,
|
||||||
hiRes: true,
|
hiRes: true,
|
||||||
@@ -191,12 +233,17 @@ const phone = {
|
|||||||
headphoneJack: false,
|
headphoneJack: false,
|
||||||
},
|
},
|
||||||
connectivity: {
|
connectivity: {
|
||||||
cellular: '5G Sub-6 / mmWave',
|
cellular: '5G 双模双卡双通',
|
||||||
wifi: 'Wi-Fi 7 (802.11be)',
|
bands: ['n1', 'n3', 'n5', 'n8', 'n28a', 'n38', 'n41', 'n77', 'n78', 'B1', 'B3', 'B5', 'B8', 'B34', 'B38', 'B39', 'B40', 'B41'],
|
||||||
bluetooth: '5.4, LDAC / LHDC 5.0',
|
satellite: false,
|
||||||
|
satelliteBands: [],
|
||||||
|
wifi: 'Wi-Fi 7(802.11be),2.4 / 5 / 6 GHz,2×2 MIMO,MLO 2.0,8×8 Sounding MU-MIMO,Wi-Fi Direct / Miracast',
|
||||||
|
bluetooth: '5.4,Dual-Bluetooth,AAC / AptX / AptX HD / AptX Adaptive / LDAC / LHDC 5.0',
|
||||||
nfc: true,
|
nfc: true,
|
||||||
gps: 'L1 + L5 双频',
|
gps: '北斗 B1I + B1C + B2a,GPS L1 + L5,Galileo E1 + E5a,GLONASS G1,QZSS L1 + L5,NavIC L5,AGNSS',
|
||||||
usb: 'USB 3.2 Gen 1 Type-C',
|
usb: 'USB 3.2 Gen 1 Type-C(双面椭圆口)',
|
||||||
|
usbSpeed: '5 Gbps',
|
||||||
|
usbVideoOut: true,
|
||||||
ir: true,
|
ir: true,
|
||||||
uwb: false,
|
uwb: false,
|
||||||
},
|
},
|
||||||
@@ -206,23 +253,76 @@ const phone = {
|
|||||||
wired: '90W',
|
wired: '90W',
|
||||||
wireless: '50W',
|
wireless: '50W',
|
||||||
reverse: '10W',
|
reverse: '10W',
|
||||||
chargingProtocol: '小米澎湃 P1 + G1',
|
chargingProtocol: 'QC4 / QC3+ / QC3.0 / QC2.0 / PD3.0 / PD2.0 / 小米 FC 2.0 快充',
|
||||||
},
|
},
|
||||||
sensors: {
|
sensors: {
|
||||||
fingerprint: '屏下光学指纹',
|
fingerprint: '短焦屏下指纹识别',
|
||||||
fingerprintType: '光学',
|
fingerprintType: '光学',
|
||||||
fingerprintPosition: '屏下短焦',
|
fingerprintPosition: '屏下短焦',
|
||||||
gyro: true,
|
gyro: true,
|
||||||
barometer: true,
|
barometer: true,
|
||||||
colorSensor: true,
|
colorSensor: true,
|
||||||
flickerSensor: true,
|
flickerSensor: true,
|
||||||
|
list: [
|
||||||
|
'距离传感器',
|
||||||
|
'屏下环境光(色温)传感器',
|
||||||
|
'后置环境光(色温)传感器',
|
||||||
|
'加速度传感器',
|
||||||
|
'陀螺仪',
|
||||||
|
'电子罗盘',
|
||||||
|
'红外线遥控器',
|
||||||
|
'flicker 传感器',
|
||||||
|
'激光对焦传感器',
|
||||||
|
'气压计',
|
||||||
|
'NFC',
|
||||||
|
],
|
||||||
},
|
},
|
||||||
software: {
|
software: {
|
||||||
launchVersion: 'Android 14 / HyperOS 1.0',
|
launchVersion: 'Xiaomi HyperOS',
|
||||||
currentVersion: 'Android 14 / HyperOS 1.0',
|
currentVersion: 'Android 15 / HyperOS 2.0',
|
||||||
updatePolicy: '4 代大版本 + 5 年安全更新',
|
updatePolicy: '4 代大版本 + 5 年安全更新',
|
||||||
|
updateTimeline: [
|
||||||
|
'2024-06-01 HyperOS 1.0.12(Android 14)',
|
||||||
|
'2025-01-15 HyperOS 2.0(Android 15)',
|
||||||
|
],
|
||||||
|
},
|
||||||
|
features: [
|
||||||
|
'轻薄小屏旗舰',
|
||||||
|
'5G 双模双卡双通',
|
||||||
|
'120Hz 自适应刷新率',
|
||||||
|
'IP68 防尘防水',
|
||||||
|
'4 麦克风',
|
||||||
|
'双扬声器(1014 + 1115K)',
|
||||||
|
'徕卡影像',
|
||||||
|
],
|
||||||
|
cameraFeatures: [
|
||||||
|
'徕卡影像',
|
||||||
|
'4K@60fps HDR10+ 录像',
|
||||||
|
'前后双景',
|
||||||
|
'10bit 色彩',
|
||||||
|
'13.5EV 高动态范围',
|
||||||
|
'电影模式',
|
||||||
|
],
|
||||||
|
benchmarks: [
|
||||||
|
'Geekbench 5 单核 1700',
|
||||||
|
'Geekbench 5 多核 6600',
|
||||||
|
'Geekbench 6 单核 2300',
|
||||||
|
'Geekbench 6 多核 7400',
|
||||||
|
'GFXBench 曼哈顿 3.1 High 95.0 fps',
|
||||||
|
'GFXBench Aztec Ruins High 95.0 fps',
|
||||||
|
'综合效能(CPU GB5 + GPU)80550',
|
||||||
|
'3DMark Wild Life Unlimited 19500',
|
||||||
|
'3DMark Wild Life Extreme 5250',
|
||||||
|
'3DMark Solar Bay 8650',
|
||||||
|
'安兔兔 V10 2200000',
|
||||||
|
'安兔兔 V11 2300000',
|
||||||
|
],
|
||||||
|
pricing: ['8GB+256GB 3999 元', '12GB+256GB 4299 元', '16GB+512GB 4599 元', '16GB+1TB 4999 元'],
|
||||||
|
officialUrl: 'https://www.mi.com/xiaomi-14',
|
||||||
|
extra: {
|
||||||
|
备注: '厚度 8.20mm(玻璃版)/ 8.28mm(科技纳米皮版);重量 193g(玻璃版)/ 188g(科技纳米皮版)',
|
||||||
|
耳机接口: 'USB Type-C(与充电口共用)',
|
||||||
},
|
},
|
||||||
extra: {},
|
|
||||||
},
|
},
|
||||||
meta: [
|
meta: [
|
||||||
{
|
{
|
||||||
@@ -238,6 +338,19 @@ const phone = {
|
|||||||
verified: false,
|
verified: false,
|
||||||
capturedAt: now,
|
capturedAt: now,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
path: 'specs.display.vendor',
|
||||||
|
confidence: 'high',
|
||||||
|
sourceUrl: 'https://www.mi.com/xiaomi-14/specs',
|
||||||
|
verified: true,
|
||||||
|
capturedAt: now,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'specs.benchmarks',
|
||||||
|
confidence: 'low',
|
||||||
|
verified: false,
|
||||||
|
capturedAt: now,
|
||||||
|
},
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -250,12 +363,15 @@ const deviceCols = [
|
|||||||
'created_at', 'updated_at',
|
'created_at', 'updated_at',
|
||||||
];
|
];
|
||||||
|
|
||||||
|
const seedDevices = [phone, ...JSON.parse(readFileSync('scripts/seed-devices.json', 'utf8'))];
|
||||||
|
|
||||||
|
for (const device of seedDevices) {
|
||||||
const deviceValues = [
|
const deviceValues = [
|
||||||
phone.slug, phone.category, null, phone.brand, phone.model,
|
device.slug, device.category, device.subCategory ?? null, device.brand, device.model,
|
||||||
JSON.stringify(phone.aliases), phone.announceDate ?? null, phone.releaseDate ?? null,
|
JSON.stringify(device.aliases ?? []), device.announceDate ?? null, device.releaseDate ?? null,
|
||||||
phone.lifecycle, null, JSON.stringify(phone.gallery ?? []),
|
device.lifecycle, device.cover ?? null, JSON.stringify(device.gallery ?? []),
|
||||||
JSON.stringify(phone.tags ?? []), phone.summary ?? null, JSON.stringify(phone.specs),
|
JSON.stringify(device.tags ?? []), device.summary ?? null, JSON.stringify(device.specs),
|
||||||
JSON.stringify(phone.chipRefs ?? {}), JSON.stringify(phone.meta ?? []), now, now,
|
JSON.stringify(device.chipRefs ?? {}), JSON.stringify(device.meta ?? []), now, now,
|
||||||
];
|
];
|
||||||
|
|
||||||
db.prepare(
|
db.prepare(
|
||||||
@@ -268,6 +384,7 @@ db.prepare(
|
|||||||
specs_json = excluded.specs_json, chip_refs_json = excluded.chip_refs_json,
|
specs_json = excluded.specs_json, chip_refs_json = excluded.chip_refs_json,
|
||||||
meta_json = excluded.meta_json, updated_at = excluded.updated_at`,
|
meta_json = excluded.meta_json, updated_at = excluded.updated_at`,
|
||||||
).run(...deviceValues);
|
).run(...deviceValues);
|
||||||
|
}
|
||||||
|
|
||||||
const chipCols = [
|
const chipCols = [
|
||||||
'slug', 'type', 'brand', 'model', 'codename', 'aliases_json',
|
'slug', 'type', 'brand', 'model', 'codename', 'aliases_json',
|
||||||
@@ -288,5 +405,5 @@ db.prepare(
|
|||||||
JSON.stringify(soc.detail), JSON.stringify(soc.meta ?? []), now, now,
|
JSON.stringify(soc.detail), JSON.stringify(soc.meta ?? []), now, now,
|
||||||
);
|
);
|
||||||
|
|
||||||
console.log('种子数据写入完成:xiaomi-14 / snapdragon-8-gen-3');
|
console.log(`种子数据写入完成:${seedDevices.map((device) => device.slug).join(' / ')} / snapdragon-8-gen-3`);
|
||||||
db.close();
|
db.close();
|
||||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,532 @@
|
|||||||
|
/**
|
||||||
|
* 从 phonerecommend.top 同步处理器(SoC)档案到本项目的 chips 表 / 导入 JSON。
|
||||||
|
*
|
||||||
|
* 示例:
|
||||||
|
* pnpm sync:processors
|
||||||
|
* pnpm sync:processors -- --write
|
||||||
|
* pnpm sync:processors -- --write --limit 10
|
||||||
|
*/
|
||||||
|
import { mkdir, writeFile } from 'node:fs/promises';
|
||||||
|
import { dirname } from 'node:path';
|
||||||
|
import { chipSchema } from '../src/lib/schema';
|
||||||
|
import { importEntities } from '../src/lib/repo';
|
||||||
|
import { getDb } from '../src/lib/db';
|
||||||
|
|
||||||
|
const BASE = 'https://www.phonerecommend.top';
|
||||||
|
const HEADERS = {
|
||||||
|
'User-Agent':
|
||||||
|
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
|
||||||
|
Accept: 'application/json, text/plain, */*',
|
||||||
|
Referer: `${BASE}/processors`,
|
||||||
|
Origin: BASE,
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 源站中文品牌 → 本项目规范名 */
|
||||||
|
const BRAND_MAP = {
|
||||||
|
高通: 'Qualcomm',
|
||||||
|
联发科: 'MediaTek',
|
||||||
|
苹果: 'Apple',
|
||||||
|
小米: 'Xiaomi',
|
||||||
|
海思: 'HiSilicon',
|
||||||
|
三星: 'Samsung',
|
||||||
|
谷歌: 'Google',
|
||||||
|
紫光展锐: 'UNISOC',
|
||||||
|
};
|
||||||
|
|
||||||
|
const BRAND_WORDS = [
|
||||||
|
'高通',
|
||||||
|
'联发科',
|
||||||
|
'苹果',
|
||||||
|
'小米',
|
||||||
|
'海思',
|
||||||
|
'三星',
|
||||||
|
'谷歌',
|
||||||
|
'紫光展锐',
|
||||||
|
'qualcomm',
|
||||||
|
'mediatek',
|
||||||
|
'apple',
|
||||||
|
'xiaomi',
|
||||||
|
'hisilicon',
|
||||||
|
'samsung',
|
||||||
|
'google',
|
||||||
|
'unisoc',
|
||||||
|
];
|
||||||
|
|
||||||
|
function clean(value) {
|
||||||
|
if (typeof value === 'string') return value.trim();
|
||||||
|
if (typeof value === 'number') return String(value);
|
||||||
|
if (value == null) return '';
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function text(value) {
|
||||||
|
if (Array.isArray(value)) return value.map(text).filter(Boolean).join(' / ');
|
||||||
|
if (value && typeof value === 'object') {
|
||||||
|
return Object.entries(value)
|
||||||
|
.map(([key, item]) => `${key}: ${text(item)}`)
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(';');
|
||||||
|
}
|
||||||
|
return clean(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeProcess(value) {
|
||||||
|
return clean(value).replace(/nanometers?/gi, 'nm').replace(/\s+/g, ' ').trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
function numberOrUndefined(value) {
|
||||||
|
return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function unique(values) {
|
||||||
|
return [...new Set(values.map(clean).filter(Boolean))];
|
||||||
|
}
|
||||||
|
|
||||||
|
function stripBrand(value, prefixes) {
|
||||||
|
for (const prefix of prefixes) {
|
||||||
|
if (prefix && value.toLowerCase().startsWith(prefix.toLowerCase())) {
|
||||||
|
return value.slice(prefix.length).trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
function splitFeatures(value) {
|
||||||
|
return unique(String(value ?? '').split(/[,,、;;]/));
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeChipName(value) {
|
||||||
|
let name = String(value ?? '')
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/[®™©]/g, '')
|
||||||
|
.replace(/\s+/g, '')
|
||||||
|
.replace(/移动平台|处理器|平台/g, '')
|
||||||
|
.replace(/[()()]/g, '');
|
||||||
|
for (const word of BRAND_WORDS) name = name.split(word).join('');
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||||
|
|
||||||
|
async function requestJson(path, attempt = 1) {
|
||||||
|
try {
|
||||||
|
await sleep(80);
|
||||||
|
const response = await fetch(`${BASE}${path}`, {
|
||||||
|
headers: HEADERS,
|
||||||
|
signal: AbortSignal.timeout(20000),
|
||||||
|
});
|
||||||
|
if (!response.ok) {
|
||||||
|
const error = new Error(`HTTP ${response.status}`);
|
||||||
|
error.status = response.status;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
const json = await response.json();
|
||||||
|
if (!json.success) throw new Error(json.message ?? '接口返回失败');
|
||||||
|
return json;
|
||||||
|
} catch (error) {
|
||||||
|
if (attempt >= 5) throw error;
|
||||||
|
// 源站对高频请求会返回 429 / 403,退避后重试
|
||||||
|
const limited = error?.status === 429 || error?.status === 403;
|
||||||
|
await sleep((limited ? 1500 : 400) * attempt);
|
||||||
|
return requestJson(path, attempt + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchAllProcessors(limit) {
|
||||||
|
const first = await requestJson('/api/processors?limit=100&page=1');
|
||||||
|
const pages = Math.max(1, Number(first.pagination?.pages ?? 1));
|
||||||
|
const items = [...(first.data ?? [])];
|
||||||
|
for (let page = 2; page <= pages; page += 1) {
|
||||||
|
const json = await requestJson(`/api/processors?limit=100&page=${page}`);
|
||||||
|
items.push(...(json.data ?? []));
|
||||||
|
}
|
||||||
|
console.log(`源站共 ${first.pagination?.total ?? items.length} 颗处理器,已获取 ${items.length} 颗`);
|
||||||
|
return limit > 0 ? items.slice(0, limit) : items;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchDetails(items, concurrency) {
|
||||||
|
const results = new Array(items.length);
|
||||||
|
let cursor = 0;
|
||||||
|
let done = 0;
|
||||||
|
|
||||||
|
async function worker() {
|
||||||
|
while (cursor < items.length) {
|
||||||
|
const index = cursor;
|
||||||
|
cursor += 1;
|
||||||
|
const item = items[index];
|
||||||
|
try {
|
||||||
|
const json = await requestJson(`/api/processors/${encodeURIComponent(item.key)}`);
|
||||||
|
results[index] = json.data ?? item;
|
||||||
|
} catch (error) {
|
||||||
|
console.warn(` 详情失败 ${item.key}:${error instanceof Error ? error.message : error}`);
|
||||||
|
results[index] = item;
|
||||||
|
}
|
||||||
|
done += 1;
|
||||||
|
if (done % 50 === 0) console.log(` 详情进度 ${done}/${items.length}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await Promise.all(Array.from({ length: Math.min(concurrency, items.length) }, () => worker()));
|
||||||
|
return results;
|
||||||
|
}
|
||||||
|
|
||||||
|
function mapProcessor(remote) {
|
||||||
|
const brandSource = clean(remote.brand);
|
||||||
|
const brand = BRAND_MAP[brandSource] ?? brandSource ?? 'Unknown';
|
||||||
|
const nameZh = clean(remote.name_zh);
|
||||||
|
const nameEn = clean(remote.name_en);
|
||||||
|
const rawName = nameZh || nameEn || clean(remote.key);
|
||||||
|
const model = stripBrand(rawName, [brandSource, brand]) || rawName;
|
||||||
|
|
||||||
|
const cpu = remote.cpu ?? {};
|
||||||
|
const gpu = remote.gpu;
|
||||||
|
const npu = remote.npu;
|
||||||
|
const benchmark = remote.benchmark ?? {};
|
||||||
|
const nanoreview = remote.nanoreview ?? {};
|
||||||
|
const nrSpecs = nanoreview.specs ?? {};
|
||||||
|
const specZh = remote.spec_zh ?? {};
|
||||||
|
const specGroupsSource =
|
||||||
|
Object.keys(specZh).length > 0 ? specZh : (remote.spec_groups ?? {});
|
||||||
|
|
||||||
|
const specGroups = {};
|
||||||
|
for (const [groupName, fields] of Object.entries(specGroupsSource)) {
|
||||||
|
if (!fields || typeof fields !== 'object' || Array.isArray(fields)) continue;
|
||||||
|
const rows = {};
|
||||||
|
for (const [key, value] of Object.entries(fields)) {
|
||||||
|
const content = text(value);
|
||||||
|
if (content) rows[key] = content;
|
||||||
|
}
|
||||||
|
if (Object.keys(rows).length > 0) specGroups[groupName] = rows;
|
||||||
|
}
|
||||||
|
|
||||||
|
const cache = cpu.cache ?? {};
|
||||||
|
const cpuClusters = (Array.isArray(cpu.clusters) ? cpu.clusters : []).map((cluster, index) => {
|
||||||
|
const type = clean(cluster.type);
|
||||||
|
return {
|
||||||
|
name: type && !/^cluster\s*\d+$/i.test(type) ? type : `簇 ${index + 1}`,
|
||||||
|
cores: [
|
||||||
|
{
|
||||||
|
microArch: clean(cluster.arch) || undefined,
|
||||||
|
count: numberOrUndefined(cluster.cores),
|
||||||
|
clockMax: clean(cluster.freq) || undefined,
|
||||||
|
l2: clean(cluster.l2) || undefined,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
const cpuCores =
|
||||||
|
numberOrUndefined(cpu.cores) ??
|
||||||
|
cpuClusters.reduce(
|
||||||
|
(sum, cluster) => sum + cluster.cores.reduce((n, core) => n + (core.count ?? 0), 0),
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
|
||||||
|
const gpuText = clean(gpu) || clean(specZh['图形']?.['名称']);
|
||||||
|
const gpuApis = splitFeatures(specZh['图形']?.['图形接口']);
|
||||||
|
const gpuFeatures = unique([specZh['图形']?.['特性']]);
|
||||||
|
const camera = remote.camera ?? {};
|
||||||
|
const display = remote.display ?? {};
|
||||||
|
const connectivity = remote.connectivity ?? {};
|
||||||
|
const memory = remote.memory ?? {};
|
||||||
|
|
||||||
|
const benchmarks = [];
|
||||||
|
const geekbenchVersion = clean(benchmark.geekbench_version) || 'Geekbench';
|
||||||
|
if (numberOrUndefined(benchmark.geekbench_single) !== undefined) {
|
||||||
|
benchmarks.push({
|
||||||
|
name: `${geekbenchVersion} 单核`,
|
||||||
|
score: String(benchmark.geekbench_single),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (numberOrUndefined(benchmark.geekbench_multi) !== undefined) {
|
||||||
|
benchmarks.push({
|
||||||
|
name: `${geekbenchVersion} 多核`,
|
||||||
|
score: String(benchmark.geekbench_multi),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (numberOrUndefined(nanoreview.gb6_single) !== undefined) {
|
||||||
|
benchmarks.push({ name: 'Geekbench 6 单核', score: String(nanoreview.gb6_single) });
|
||||||
|
}
|
||||||
|
if (numberOrUndefined(nanoreview.gb6_multi) !== undefined) {
|
||||||
|
benchmarks.push({ name: 'Geekbench 6 多核', score: String(nanoreview.gb6_multi) });
|
||||||
|
}
|
||||||
|
if (numberOrUndefined(nanoreview.antutu11_total) !== undefined) {
|
||||||
|
benchmarks.push({ name: '安兔兔 v11', score: String(nanoreview.antutu11_total), unit: '分' });
|
||||||
|
}
|
||||||
|
if (numberOrUndefined(nanoreview['3dmark_snl']) !== undefined) {
|
||||||
|
benchmarks.push({
|
||||||
|
name: '3DMark Steel Nomad Light',
|
||||||
|
score: String(nanoreview['3dmark_snl']),
|
||||||
|
unit: '分',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (numberOrUndefined(benchmark.cpu_index) !== undefined) {
|
||||||
|
benchmarks.push({
|
||||||
|
name: 'CPU 性能指数',
|
||||||
|
score: String(benchmark.cpu_index),
|
||||||
|
unit: '骁龙 865=100',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const slowMotion = clean(specZh['相机']?.['慢动作录制']);
|
||||||
|
const cameraBlock = {
|
||||||
|
isp: clean(camera.isp) || clean(specZh['相机']?.['ISP 名称']) || undefined,
|
||||||
|
maxSensor: clean(camera.max_sensor) || clean(specZh['相机']?.['单摄最高像素']) || undefined,
|
||||||
|
videoCapture: clean(camera.video_capture) || clean(specZh['相机']?.['视频录制']) || undefined,
|
||||||
|
slowMotion: slowMotion || undefined,
|
||||||
|
features: unique([specZh['相机']?.['特性']]),
|
||||||
|
};
|
||||||
|
|
||||||
|
const detail = {
|
||||||
|
overview: {
|
||||||
|
nameEn: nameEn || undefined,
|
||||||
|
nameZh: nameZh || undefined,
|
||||||
|
series: clean(remote.series) || undefined,
|
||||||
|
tier: clean(remote.performance_tier) || undefined,
|
||||||
|
tierScore: numberOrUndefined(remote.tier_score),
|
||||||
|
releaseYear: numberOrUndefined(remote.release_year),
|
||||||
|
phoneCount: numberOrUndefined(remote.phone_count),
|
||||||
|
source: clean(remote.source) || undefined,
|
||||||
|
},
|
||||||
|
cpuClusters,
|
||||||
|
cpuBlock: {
|
||||||
|
config: clean(cpu.config) || undefined,
|
||||||
|
arch: clean(cpu.arch) || undefined,
|
||||||
|
archType: clean(cpu.arch_type) || undefined,
|
||||||
|
maxFreq: clean(cpu.max_freq) || undefined,
|
||||||
|
cores: cpuCores || undefined,
|
||||||
|
cacheL3: clean(cache.l3) || undefined,
|
||||||
|
systemCache: clean(cache.system_level) || undefined,
|
||||||
|
note: clean(cache.note) || undefined,
|
||||||
|
},
|
||||||
|
gpuBlock: {
|
||||||
|
name: gpuText || undefined,
|
||||||
|
apis: gpuApis,
|
||||||
|
features: gpuFeatures,
|
||||||
|
},
|
||||||
|
npuBlock: {
|
||||||
|
name: clean(npu) || undefined,
|
||||||
|
features: [],
|
||||||
|
},
|
||||||
|
systemCache: clean(cache.system_level) || undefined,
|
||||||
|
ispBlock: cameraBlock.isp,
|
||||||
|
modemBlock: clean(remote.modem) || undefined,
|
||||||
|
memorySupport: {
|
||||||
|
type: clean(memory.type) || clean(specZh['内存']?.['类型']) || undefined,
|
||||||
|
maxClock: clean(specZh['内存']?.['频率']) || undefined,
|
||||||
|
bandwidth: clean(nrSpecs['Max bandwidth']) || undefined,
|
||||||
|
},
|
||||||
|
storageSupport:
|
||||||
|
clean(remote.storage) || clean(specZh['存储']?.['UFS']) || undefined,
|
||||||
|
displaySupport:
|
||||||
|
clean(display.max_resolution) || clean(display.max_refresh) || undefined,
|
||||||
|
displayBlock: {
|
||||||
|
maxResolution: clean(display.max_resolution) || undefined,
|
||||||
|
maxRefresh: clean(display.max_refresh) || undefined,
|
||||||
|
externalMax: clean(specZh['屏幕']?.['外接最高分辨率']) || undefined,
|
||||||
|
hdr: clean(specZh['屏幕']?.['HDR']) || undefined,
|
||||||
|
colorDepth: clean(specZh['屏幕']?.['色深']) || undefined,
|
||||||
|
colorGamut: clean(specZh['屏幕']?.['色域']) || undefined,
|
||||||
|
},
|
||||||
|
cameraBlock,
|
||||||
|
connectivityBlock: {
|
||||||
|
wifi: clean(connectivity.wifi) || undefined,
|
||||||
|
wifiStandard: clean(connectivity.wifi_standard) || undefined,
|
||||||
|
bluetooth: clean(connectivity.bluetooth) || undefined,
|
||||||
|
peakSpeed: clean(connectivity.peak_speed) || undefined,
|
||||||
|
},
|
||||||
|
benchmarkInfo: {
|
||||||
|
version: clean(benchmark.geekbench_version) || undefined,
|
||||||
|
cpuIndex: numberOrUndefined(benchmark.cpu_index),
|
||||||
|
cpuIndexNote: clean(benchmark.cpu_index_note) || undefined,
|
||||||
|
note: clean(benchmark.note) || undefined,
|
||||||
|
antutu:
|
||||||
|
nanoreview.antutu11 && typeof nanoreview.antutu11 === 'object'
|
||||||
|
? {
|
||||||
|
cpu: numberOrUndefined(nanoreview.antutu11.cpu),
|
||||||
|
gpu: numberOrUndefined(nanoreview.antutu11.gpu),
|
||||||
|
memory: numberOrUndefined(nanoreview.antutu11.memory),
|
||||||
|
ux: numberOrUndefined(nanoreview.antutu11.ux),
|
||||||
|
}
|
||||||
|
: undefined,
|
||||||
|
},
|
||||||
|
benchmarks,
|
||||||
|
traits: unique(remote.traits ?? []),
|
||||||
|
caveats: unique(remote.caveats ?? []),
|
||||||
|
sourceUrls: unique(remote.source_urls ?? []),
|
||||||
|
specGroups,
|
||||||
|
extra: {},
|
||||||
|
};
|
||||||
|
|
||||||
|
const slug = /^[a-z0-9]+(-[a-z0-9]+)*$/.test(clean(remote.key))
|
||||||
|
? clean(remote.key)
|
||||||
|
: clean(remote.key)
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/[^a-z0-9]+/g, '-')
|
||||||
|
.replace(/^-+|-+$/g, '');
|
||||||
|
|
||||||
|
return {
|
||||||
|
slug,
|
||||||
|
type: 'soc',
|
||||||
|
brand,
|
||||||
|
model,
|
||||||
|
codename:
|
||||||
|
clean(remote.codename) ||
|
||||||
|
clean(specZh['型号']?.['型号代号']) ||
|
||||||
|
undefined,
|
||||||
|
aliases: unique([nameEn, nameZh, clean(remote.codename), ...(remote.aliases ?? [])]),
|
||||||
|
process:
|
||||||
|
normalizeProcess(
|
||||||
|
clean(remote.process_node) ||
|
||||||
|
clean(specZh['制程']?.['制程']) ||
|
||||||
|
clean(nrSpecs['Process']),
|
||||||
|
) || undefined,
|
||||||
|
arch: clean(nrSpecs['Instruction set']) || clean(cpu.arch) || undefined,
|
||||||
|
detail,
|
||||||
|
meta: [],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function linkDevices(chips) {
|
||||||
|
const nameMap = new Map();
|
||||||
|
for (const chip of chips) {
|
||||||
|
const names = [
|
||||||
|
chip.model,
|
||||||
|
chip.codename,
|
||||||
|
chip.slug,
|
||||||
|
...(chip.aliases ?? []),
|
||||||
|
chip.detail.overview?.nameEn,
|
||||||
|
chip.detail.overview?.nameZh,
|
||||||
|
];
|
||||||
|
for (const name of names) {
|
||||||
|
const normalized = normalizeChipName(name);
|
||||||
|
if (normalized) nameMap.set(normalized, chip.slug);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const db = getDb();
|
||||||
|
const rows = db.prepare('SELECT slug, chip_refs_json, specs_json FROM devices').all();
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
let linked = 0;
|
||||||
|
db.exec('BEGIN');
|
||||||
|
try {
|
||||||
|
for (const row of rows) {
|
||||||
|
let specs = {};
|
||||||
|
try {
|
||||||
|
specs = JSON.parse(row.specs_json ?? '{}');
|
||||||
|
} catch {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const chipset = specs.platform?.chipset;
|
||||||
|
if (!chipset) continue;
|
||||||
|
const chipSlug = nameMap.get(normalizeChipName(chipset));
|
||||||
|
if (!chipSlug) continue;
|
||||||
|
let refs = {};
|
||||||
|
try {
|
||||||
|
refs = JSON.parse(row.chip_refs_json ?? '{}');
|
||||||
|
} catch {
|
||||||
|
refs = {};
|
||||||
|
}
|
||||||
|
if (refs.soc === chipSlug) continue;
|
||||||
|
refs.soc = chipSlug;
|
||||||
|
db.prepare('UPDATE devices SET chip_refs_json = ?, updated_at = ? WHERE slug = ?').run(
|
||||||
|
JSON.stringify(refs),
|
||||||
|
now,
|
||||||
|
row.slug,
|
||||||
|
);
|
||||||
|
linked += 1;
|
||||||
|
}
|
||||||
|
db.exec('COMMIT');
|
||||||
|
} catch (error) {
|
||||||
|
db.exec('ROLLBACK');
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
return linked;
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseArgs(argv) {
|
||||||
|
const options = { write: false, limit: 0, out: '', concurrency: 2 };
|
||||||
|
for (let index = 0; index < argv.length; index += 1) {
|
||||||
|
const arg = argv[index];
|
||||||
|
if (arg === '--write') options.write = true;
|
||||||
|
else if (arg === '--limit') options.limit = Number(argv[(index += 1)] ?? 0);
|
||||||
|
else if (arg === '--out') options.out = argv[(index += 1)] ?? '';
|
||||||
|
else if (arg === '--concurrency') options.concurrency = Number(argv[(index += 1)] ?? 6);
|
||||||
|
else throw new Error(`未知参数:${arg}`);
|
||||||
|
}
|
||||||
|
return options;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const options = parseArgs(process.argv.slice(2));
|
||||||
|
console.log(`拉取 ${BASE}/api/processors ...`);
|
||||||
|
const items = await fetchAllProcessors(options.limit);
|
||||||
|
console.log('拉取处理器详情 ...');
|
||||||
|
const details = await fetchDetails(items, options.concurrency);
|
||||||
|
|
||||||
|
const chips = [];
|
||||||
|
const issues = [];
|
||||||
|
const seen = new Set();
|
||||||
|
for (const remote of details) {
|
||||||
|
try {
|
||||||
|
const chip = mapProcessor(remote);
|
||||||
|
if (seen.has(chip.slug)) {
|
||||||
|
console.warn(` slug 重复,跳过:${chip.slug}(${chip.brand} ${chip.model})`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const parsed = chipSchema.safeParse(chip);
|
||||||
|
if (!parsed.success) {
|
||||||
|
issues.push({
|
||||||
|
name: `${chip.brand} ${chip.model}`,
|
||||||
|
issues: parsed.error.issues
|
||||||
|
.slice(0, 8)
|
||||||
|
.map((issue) => `${issue.path.join('.')}: ${issue.message}`),
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
seen.add(chip.slug);
|
||||||
|
chips.push(parsed.data);
|
||||||
|
} catch (error) {
|
||||||
|
issues.push({ name: remote?.key ?? '?', issues: [String(error)] });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (issues.length > 0) {
|
||||||
|
console.error(`\n有 ${issues.length} 颗处理器映射失败:`);
|
||||||
|
for (const issue of issues.slice(0, 20)) {
|
||||||
|
console.error(`- ${issue.name}`);
|
||||||
|
for (const line of issue.issues) console.error(` ${line}`);
|
||||||
|
}
|
||||||
|
throw new Error('映射失败,已中止,未写入任何数据');
|
||||||
|
}
|
||||||
|
console.log(`映射成功 ${chips.length} 颗`);
|
||||||
|
|
||||||
|
const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
|
||||||
|
const outPath = options.out || `data/import/processors-${stamp}.json`;
|
||||||
|
const payload = {
|
||||||
|
formatVersion: 1,
|
||||||
|
generator: 'LFSpecs / sync-processors',
|
||||||
|
exportedAt: new Date().toISOString(),
|
||||||
|
devices: [],
|
||||||
|
chips,
|
||||||
|
};
|
||||||
|
await mkdir(dirname(outPath), { recursive: true });
|
||||||
|
await writeFile(outPath, `${JSON.stringify(payload, null, 2)}\n`, 'utf8');
|
||||||
|
console.log(`JSON 已写入 ${outPath}(${chips.length} 颗)`);
|
||||||
|
|
||||||
|
if (!options.write) {
|
||||||
|
console.log('未指定 --write,本次只产出 JSON。');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('写入数据库 ...');
|
||||||
|
const counts = importEntities([], chips);
|
||||||
|
console.log(`数据库写入完成:devices ${counts.devices} / chips ${counts.chips}`);
|
||||||
|
const linked = linkDevices(chips);
|
||||||
|
console.log(`已关联 ${linked} 款设备的 SoC 引用`);
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch((error) => {
|
||||||
|
console.error(error);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
@@ -0,0 +1,179 @@
|
|||||||
|
---
|
||||||
|
// 全局对比选择条:在列表 / 详情页把机型加入最多 4 个槽位,再进入对比页
|
||||||
|
---
|
||||||
|
|
||||||
|
<div id="compare-tray" class="compare-tray" hidden aria-label="设备对比选择">
|
||||||
|
<div class="mx-auto flex max-w-6xl flex-wrap items-center gap-2 px-5 py-2.5">
|
||||||
|
<span class="shrink-0 text-xs text-muted-foreground">对比</span>
|
||||||
|
<span class="tabular shrink-0 text-xs text-muted-foreground">
|
||||||
|
<span data-compare-count>0</span>/4
|
||||||
|
</span>
|
||||||
|
<div class="flex min-w-0 flex-1 flex-wrap items-center gap-1.5" data-compare-items></div>
|
||||||
|
<span class="text-xs text-destructive" data-compare-message role="status" aria-live="polite"></span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
data-compare-clear
|
||||||
|
class="shrink-0 rounded-md border border-border px-3 py-1.5 text-xs text-muted-foreground transition-colors hover:text-foreground"
|
||||||
|
>
|
||||||
|
清空
|
||||||
|
</button>
|
||||||
|
<a
|
||||||
|
data-compare-go
|
||||||
|
href="/compare"
|
||||||
|
aria-disabled="true"
|
||||||
|
class="compare-go shrink-0 rounded-md bg-primary px-3.5 py-1.5 text-xs font-medium text-primary-foreground transition-colors hover:bg-primary/90"
|
||||||
|
>
|
||||||
|
开始对比
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script is:inline>
|
||||||
|
(() => {
|
||||||
|
const KEY = 'lfs-compare';
|
||||||
|
|
||||||
|
if (window.__lfsCompareReady) {
|
||||||
|
window.__lfsCompareRefresh?.();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
window.__lfsCompareReady = true;
|
||||||
|
|
||||||
|
const readItems = () => {
|
||||||
|
try {
|
||||||
|
const raw = localStorage.getItem(KEY);
|
||||||
|
const parsed = raw ? JSON.parse(raw) : [];
|
||||||
|
if (!Array.isArray(parsed)) return [];
|
||||||
|
return parsed
|
||||||
|
.filter((item) => item && typeof item.slug === 'string')
|
||||||
|
.map((item) => ({
|
||||||
|
slug: item.slug,
|
||||||
|
name: typeof item.name === 'string' && item.name ? item.name : item.slug,
|
||||||
|
}))
|
||||||
|
.slice(0, 4);
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const writeItems = (items) => {
|
||||||
|
try {
|
||||||
|
localStorage.setItem(KEY, JSON.stringify(items));
|
||||||
|
} catch {}
|
||||||
|
};
|
||||||
|
|
||||||
|
let messageTimer;
|
||||||
|
const setMessage = (text) => {
|
||||||
|
const el = document.querySelector('[data-compare-message]');
|
||||||
|
if (!el) return;
|
||||||
|
el.textContent = text;
|
||||||
|
window.clearTimeout(messageTimer);
|
||||||
|
messageTimer = window.setTimeout(() => {
|
||||||
|
el.textContent = '';
|
||||||
|
}, 2400);
|
||||||
|
};
|
||||||
|
|
||||||
|
const refresh = () => {
|
||||||
|
// 对比页会把当前 URL 里的选择写进页面,进入该页时同步到本地选择
|
||||||
|
const pageSelection = document.querySelector('[data-compare-selection]');
|
||||||
|
if (pageSelection) {
|
||||||
|
try {
|
||||||
|
const items = JSON.parse(pageSelection.getAttribute('data-items') || '[]');
|
||||||
|
if (Array.isArray(items) && items.length > 0) {
|
||||||
|
writeItems(items.slice(0, 4));
|
||||||
|
}
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
|
||||||
|
const items = readItems();
|
||||||
|
const tray = document.getElementById('compare-tray');
|
||||||
|
if (!tray) return;
|
||||||
|
|
||||||
|
tray.hidden = items.length === 0;
|
||||||
|
document.documentElement.classList.toggle('compare-tray-open', items.length > 0);
|
||||||
|
|
||||||
|
const count = tray.querySelector('[data-compare-count]');
|
||||||
|
if (count) count.textContent = String(items.length);
|
||||||
|
|
||||||
|
const list = tray.querySelector('[data-compare-items]');
|
||||||
|
if (list) {
|
||||||
|
list.replaceChildren();
|
||||||
|
for (const item of items) {
|
||||||
|
const chip = document.createElement('button');
|
||||||
|
chip.type = 'button';
|
||||||
|
chip.dataset.compareRemove = item.slug;
|
||||||
|
chip.className = 'compare-chip';
|
||||||
|
chip.title = `移除 ${item.name}`;
|
||||||
|
chip.textContent = item.name;
|
||||||
|
const cross = document.createElement('span');
|
||||||
|
cross.setAttribute('aria-hidden', 'true');
|
||||||
|
cross.textContent = '×';
|
||||||
|
chip.append(cross);
|
||||||
|
list.append(chip);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const go = tray.querySelector('[data-compare-go]');
|
||||||
|
if (go) {
|
||||||
|
const ready = items.length >= 2;
|
||||||
|
go.setAttribute('aria-disabled', ready ? 'false' : 'true');
|
||||||
|
go.href = ready ? `/compare?ids=${items.map((item) => item.slug).join(',')}` : '/compare';
|
||||||
|
}
|
||||||
|
|
||||||
|
document.querySelectorAll('[data-compare-toggle]').forEach((button) => {
|
||||||
|
const slug = button.getAttribute('data-slug');
|
||||||
|
const active = items.some((item) => item.slug === slug);
|
||||||
|
button.setAttribute('aria-pressed', active ? 'true' : 'false');
|
||||||
|
button.dataset.active = active ? '1' : '0';
|
||||||
|
button.textContent = active ? '已加入' : '加入对比';
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
window.__lfsCompareRefresh = refresh;
|
||||||
|
|
||||||
|
document.addEventListener('click', (event) => {
|
||||||
|
const target = event.target;
|
||||||
|
if (!(target instanceof Element)) return;
|
||||||
|
const items = readItems();
|
||||||
|
|
||||||
|
const toggle = target.closest('[data-compare-toggle]');
|
||||||
|
if (toggle) {
|
||||||
|
event.preventDefault();
|
||||||
|
const slug = toggle.getAttribute('data-slug');
|
||||||
|
const name = toggle.getAttribute('data-name') || slug;
|
||||||
|
if (!slug) return;
|
||||||
|
if (items.some((item) => item.slug === slug)) {
|
||||||
|
writeItems(items.filter((item) => item.slug !== slug));
|
||||||
|
} else if (items.length >= 4) {
|
||||||
|
setMessage('最多同时对比 4 款设备');
|
||||||
|
} else {
|
||||||
|
writeItems([...items, { slug, name }]);
|
||||||
|
}
|
||||||
|
refresh();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const remove = target.closest('[data-compare-remove]');
|
||||||
|
if (remove) {
|
||||||
|
const slug = remove.getAttribute('data-compare-remove');
|
||||||
|
writeItems(items.filter((item) => item.slug !== slug));
|
||||||
|
refresh();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (target.closest('[data-compare-clear]')) {
|
||||||
|
writeItems([]);
|
||||||
|
refresh();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const go = target.closest('[data-compare-go]');
|
||||||
|
if (go && readItems().length < 2) {
|
||||||
|
event.preventDefault();
|
||||||
|
setMessage('至少选择 2 款设备');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
document.addEventListener('astro:page-load', refresh);
|
||||||
|
refresh();
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
---
|
||||||
|
import type { Device } from '@/lib/schema';
|
||||||
|
import { deviceTitle } from '@/lib/utils';
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
device: Device;
|
||||||
|
/** 紧凑模式:隐藏简介,用于首页等轻量列表 */
|
||||||
|
compact?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
const { device, compact = false } = Astro.props;
|
||||||
|
const title = deviceTitle(device.brand, device.model);
|
||||||
|
|
||||||
|
const lifecycleText =
|
||||||
|
device.lifecycle === 'discontinued' ? '已停产' : device.lifecycle === 'announced' ? '已发布' : '在售';
|
||||||
|
|
||||||
|
const stats = [
|
||||||
|
{ label: 'SoC', value: device.specs.platform?.chipset ?? '—' },
|
||||||
|
{ label: '屏幕', value: device.specs.display?.size ?? '—' },
|
||||||
|
{ label: '电池', value: device.specs.battery?.capacity ?? '—' },
|
||||||
|
{ label: '重量', value: device.specs.body?.weight ?? '—' },
|
||||||
|
];
|
||||||
|
---
|
||||||
|
|
||||||
|
<div class="relative">
|
||||||
|
<a
|
||||||
|
href={`/devices/${device.slug}`}
|
||||||
|
class="group block rounded-lg border border-border bg-card p-5 transition-colors hover:border-primary/40 hover:bg-accent/20"
|
||||||
|
>
|
||||||
|
<div class="flex min-w-0 items-start">
|
||||||
|
<span class="truncate text-base font-semibold leading-tight group-hover:text-primary">{title}</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<dl class="tabular mt-4 grid grid-cols-2 gap-x-4 gap-y-1 text-xs">
|
||||||
|
{
|
||||||
|
stats.map((stat) => (
|
||||||
|
<>
|
||||||
|
<dt class="text-muted-foreground">{stat.label}</dt>
|
||||||
|
<dd class="truncate text-right">{stat.value}</dd>
|
||||||
|
</>
|
||||||
|
))
|
||||||
|
}
|
||||||
|
</dl>
|
||||||
|
|
||||||
|
{!compact && device.summary && <p class="mt-4 line-clamp-2 pr-20 text-xs text-muted-foreground">{device.summary}</p>}
|
||||||
|
|
||||||
|
<div class="mt-3 flex h-7 items-center">
|
||||||
|
<span class="rounded-full border border-border px-2 py-0.5 text-[11px] text-muted-foreground">
|
||||||
|
{lifecycleText}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</a>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
data-compare-toggle
|
||||||
|
data-slug={device.slug}
|
||||||
|
data-name={title}
|
||||||
|
aria-pressed="false"
|
||||||
|
class="compare-toggle absolute bottom-5 right-5 z-10 inline-flex h-7 items-center rounded-md border border-border bg-card px-2.5 text-[11px] text-muted-foreground transition-colors hover:border-primary/50 hover:text-foreground"
|
||||||
|
>
|
||||||
|
加入对比
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
---
|
||||||
|
interface Props {
|
||||||
|
trigger: string;
|
||||||
|
title: string;
|
||||||
|
items: string[];
|
||||||
|
note?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const { trigger, title, items, note } = Astro.props;
|
||||||
|
---
|
||||||
|
|
||||||
|
<span class="hover-info" tabindex="0">
|
||||||
|
<span class="hover-info-trigger">{trigger}</span>
|
||||||
|
<span class="hover-info-panel">
|
||||||
|
<span class="block font-medium text-foreground">{title}</span>
|
||||||
|
{note && <span class="mt-1 block text-muted-foreground">{note}</span>}
|
||||||
|
{items.length > 0 ? (
|
||||||
|
<span class="mt-2 flex flex-wrap gap-1">
|
||||||
|
{items.map((item) => (
|
||||||
|
<span class="rounded border border-border bg-secondary/60 px-1.5 py-0.5 font-mono text-[10px] text-foreground/80">
|
||||||
|
{item}
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<span class="mt-1 block text-muted-foreground">暂无频段数据</span>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
---
|
||||||
|
import type { FieldMeta } from '@/lib/schema/meta';
|
||||||
|
import { fieldLabelForPath } from '@/lib/spec-fields';
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
items: (FieldMeta | undefined)[];
|
||||||
|
align?: 'left' | 'right';
|
||||||
|
}
|
||||||
|
|
||||||
|
const { items, align = 'left' } = Astro.props;
|
||||||
|
const lowItems = items.filter(
|
||||||
|
(item): item is FieldMeta => Boolean(item) && item!.confidence === 'low',
|
||||||
|
);
|
||||||
|
const summary =
|
||||||
|
lowItems.length === 1
|
||||||
|
? '该参数置信度较低,信息可能不准确。'
|
||||||
|
: `有 ${lowItems.length} 个相关参数置信度较低,信息可能不准确。`;
|
||||||
|
---
|
||||||
|
|
||||||
|
{
|
||||||
|
lowItems.length > 0 && (
|
||||||
|
<span
|
||||||
|
class:list={['low-badge', align === 'right' && 'low-badge-right']}
|
||||||
|
tabindex="0"
|
||||||
|
role="note"
|
||||||
|
aria-label={summary}
|
||||||
|
title={lowItems
|
||||||
|
.map(
|
||||||
|
(item) =>
|
||||||
|
`${fieldLabelForPath(item.path)}:low,${item.verified ? '已核实' : '待核实'}${
|
||||||
|
item.sourceUrl ? `,来源 ${item.sourceUrl}` : ''
|
||||||
|
}`,
|
||||||
|
)
|
||||||
|
.join('\n')}
|
||||||
|
>
|
||||||
|
<span class="low-badge-pill">low</span>
|
||||||
|
<span class="low-badge-panel">
|
||||||
|
<span class="block font-medium text-foreground">{summary}</span>
|
||||||
|
<span class="mt-1 block text-muted-foreground">悬停或聚焦可查看记录:</span>
|
||||||
|
<ul class="mt-1.5 space-y-1">
|
||||||
|
{lowItems.map((item) => (
|
||||||
|
<li>
|
||||||
|
<span class="text-foreground/80">{fieldLabelForPath(item.path)}</span>
|
||||||
|
{item.verified ? (
|
||||||
|
<span class="ml-1 text-primary">已核实</span>
|
||||||
|
) : (
|
||||||
|
<span class="ml-1 text-destructive">待核实</span>
|
||||||
|
)}
|
||||||
|
{item.sourceUrl && (
|
||||||
|
<span class="mt-0.5 block break-all font-mono text-[10px] text-muted-foreground">
|
||||||
|
{item.sourceUrl}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
---
|
||||||
|
interface Props {
|
||||||
|
page: number;
|
||||||
|
pages: number;
|
||||||
|
/** 生成第 n 页链接,保留当前筛选条件 */
|
||||||
|
buildHref: (page: number) => string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const { page, pages, buildHref } = Astro.props;
|
||||||
|
|
||||||
|
/** 页码窗口:首页、末页固定显示,中间只保留当前页左右各 2 个 */
|
||||||
|
const numbers: (number | 'gap')[] = [];
|
||||||
|
if (pages > 1) {
|
||||||
|
const start = Math.max(2, page - 2);
|
||||||
|
const end = Math.min(pages - 1, page + 2);
|
||||||
|
numbers.push(1);
|
||||||
|
if (start > 2) numbers.push('gap');
|
||||||
|
for (let i = start; i <= end; i += 1) numbers.push(i);
|
||||||
|
if (end < pages - 1) numbers.push('gap');
|
||||||
|
numbers.push(pages);
|
||||||
|
}
|
||||||
|
|
||||||
|
const base = 'rounded-md border px-2.5 py-1.5 transition-colors';
|
||||||
|
const idle = 'border-border text-muted-foreground hover:text-foreground';
|
||||||
|
const active = 'border-primary/50 bg-primary/10 text-primary';
|
||||||
|
const disabled = 'border-border/60 text-muted-foreground/40';
|
||||||
|
---
|
||||||
|
|
||||||
|
{
|
||||||
|
pages > 1 && (
|
||||||
|
<nav class="tabular mt-6 flex flex-wrap items-center justify-center gap-1 text-xs" aria-label="分页">
|
||||||
|
{page > 1 ? (
|
||||||
|
<a href={buildHref(page - 1)} class:list={[base, idle]} rel="prev">
|
||||||
|
上一页
|
||||||
|
</a>
|
||||||
|
) : (
|
||||||
|
<span class:list={[base, disabled]}>上一页</span>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{numbers.map((item) =>
|
||||||
|
item === 'gap' ? (
|
||||||
|
<span class="px-1.5 text-muted-foreground">…</span>
|
||||||
|
) : (
|
||||||
|
<a
|
||||||
|
href={buildHref(item)}
|
||||||
|
aria-current={item === page ? 'page' : undefined}
|
||||||
|
class:list={[base, item === page ? active : idle]}
|
||||||
|
>
|
||||||
|
{item}
|
||||||
|
</a>
|
||||||
|
),
|
||||||
|
)}
|
||||||
|
|
||||||
|
{page < pages ? (
|
||||||
|
<a href={buildHref(page + 1)} class:list={[base, idle]} rel="next">
|
||||||
|
下一页
|
||||||
|
</a>
|
||||||
|
) : (
|
||||||
|
<span class:list={[base, disabled]}>下一页</span>
|
||||||
|
)}
|
||||||
|
</nav>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,176 @@
|
|||||||
|
import { useMemo, useState } from 'react';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { cn } from '@/lib/utils';
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
/** 当前是否已保存 B 站登录态(后台查 settings) */
|
||||||
|
bound: boolean;
|
||||||
|
/** .env 是否显式配置了 BILIBILI_SESSDATA(优先于后台保存的登录态) */
|
||||||
|
envConfigured: boolean;
|
||||||
|
/** 后台登录态的保存时间 */
|
||||||
|
savedAt?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
type PollStatus = 'idle' | 'waiting' | 'scanned' | 'confirmed' | 'expired' | 'error';
|
||||||
|
|
||||||
|
export default function BilibiliSetup({ bound, envConfigured, savedAt }: Props) {
|
||||||
|
const [qrImage, setQrImage] = useState('');
|
||||||
|
const [status, setStatus] = useState<PollStatus>('idle');
|
||||||
|
const [message, setMessage] = useState('');
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
|
||||||
|
const boundNow = useMemo(() => envConfigured || bound, [envConfigured, bound]);
|
||||||
|
|
||||||
|
function hint(status: PollStatus): string {
|
||||||
|
switch (status) {
|
||||||
|
case 'waiting':
|
||||||
|
return '等待扫码…请用 B 站 App 扫描二维码';
|
||||||
|
case 'scanned':
|
||||||
|
return '已扫码,请在手机上确认登录';
|
||||||
|
case 'confirmed':
|
||||||
|
return '登录成功,B 站登录态已自动保存,拆机视频字幕即可使用。';
|
||||||
|
case 'expired':
|
||||||
|
return '二维码已过期,请点击重新生成。';
|
||||||
|
case 'error':
|
||||||
|
return message || '出错了,请重试。';
|
||||||
|
default:
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function startLogin() {
|
||||||
|
setBusy(true);
|
||||||
|
setMessage('');
|
||||||
|
try {
|
||||||
|
const response = await fetch('/api/bilibili/login', { method: 'POST' });
|
||||||
|
const data = await response.json();
|
||||||
|
if (!response.ok) throw new Error(data.error ?? '生成二维码失败');
|
||||||
|
setQrImage(data.imageDataUrl);
|
||||||
|
setStatus('waiting');
|
||||||
|
|
||||||
|
// 轮询扫码结果;confirmed / expired 后停止
|
||||||
|
const key: string = data.key;
|
||||||
|
const timer = setInterval(async () => {
|
||||||
|
try {
|
||||||
|
const poll = await fetch('/api/bilibili/poll', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'content-type': 'application/json' },
|
||||||
|
body: JSON.stringify({ key }),
|
||||||
|
});
|
||||||
|
const pollData = await poll.json();
|
||||||
|
if (!poll.ok) throw new Error(pollData.error ?? '轮询失败');
|
||||||
|
const next = pollData.status as PollStatus;
|
||||||
|
if (next === 'waiting' || next === 'scanned') {
|
||||||
|
setStatus(next);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
clearInterval(timer);
|
||||||
|
if (next === 'confirmed') {
|
||||||
|
setStatus('confirmed');
|
||||||
|
setTimeout(() => window.location.reload(), 1200);
|
||||||
|
} else {
|
||||||
|
setStatus(next);
|
||||||
|
}
|
||||||
|
} catch (caught) {
|
||||||
|
clearInterval(timer);
|
||||||
|
setStatus('error');
|
||||||
|
setMessage(caught instanceof Error ? caught.message : '轮询失败');
|
||||||
|
}
|
||||||
|
}, 2000);
|
||||||
|
} catch (caught) {
|
||||||
|
setStatus('error');
|
||||||
|
setMessage(caught instanceof Error ? caught.message : '生成二维码失败');
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function unbind() {
|
||||||
|
if (!window.confirm('确定解除 B 站绑定?拆机视频字幕将不可用。')) return;
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
const response = await fetch('/api/bilibili/unbind', { method: 'POST' });
|
||||||
|
if (!response.ok) throw new Error('解绑失败');
|
||||||
|
window.location.reload();
|
||||||
|
} catch (caught) {
|
||||||
|
setMessage(caught instanceof Error ? caught.message : '解绑失败');
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="rounded-md border border-border/70 bg-secondary/20 px-3 py-2 text-xs text-muted-foreground">
|
||||||
|
绑定 B 站账号后,AI 补全可以抓取拆机视频(微机分等拆解 UP 主)的字幕全文,
|
||||||
|
提炼马达型号、扬声器单元等官网不公开的参数。登录凭证仅保存在本站数据库,不会上传第三方。
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-wrap items-center gap-3">
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
'rounded-full border px-3 py-1 text-xs font-medium',
|
||||||
|
boundNow
|
||||||
|
? 'border-primary/50 text-primary'
|
||||||
|
: 'border-border text-muted-foreground',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{envConfigured
|
||||||
|
? '已绑定(.env 配置)'
|
||||||
|
: bound
|
||||||
|
? `已绑定(扫码保存于 ${savedAt ?? '—'})`
|
||||||
|
: '未绑定'}
|
||||||
|
</span>
|
||||||
|
<Button type="button" size="sm" onClick={startLogin} disabled={busy}>
|
||||||
|
{boundNow ? '重新扫码绑定' : '扫码绑定'}
|
||||||
|
</Button>
|
||||||
|
{bound && !envConfigured && (
|
||||||
|
<Button type="button" size="sm" variant="ghost" onClick={unbind} disabled={busy}>
|
||||||
|
解除绑定
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{qrImage && status !== 'confirmed' && (
|
||||||
|
<div className="flex flex-col items-start gap-2">
|
||||||
|
<img
|
||||||
|
src={qrImage}
|
||||||
|
alt="B 站扫码登录二维码"
|
||||||
|
className="h-52 w-52 rounded-md border border-border bg-white p-1"
|
||||||
|
/>
|
||||||
|
<p
|
||||||
|
className={cn(
|
||||||
|
'text-xs',
|
||||||
|
status === 'expired' || status === 'error'
|
||||||
|
? 'text-destructive'
|
||||||
|
: 'text-muted-foreground',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{hint(status)}
|
||||||
|
</p>
|
||||||
|
{(status === 'expired' || status === 'error') && (
|
||||||
|
<Button type="button" size="sm" variant="outline" onClick={startLogin} disabled={busy}>
|
||||||
|
重新生成二维码
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{status === 'confirmed' && (
|
||||||
|
<p className="rounded-md border border-primary/40 bg-primary/10 px-3 py-2 text-xs text-primary">
|
||||||
|
{hint('confirmed')}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{message && status === 'error' && (
|
||||||
|
<p className="rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive">
|
||||||
|
{message}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<p className="text-[11px] text-muted-foreground">
|
||||||
|
也可以在 .env 中配置 <code className="font-mono">BILIBILI_SESSDATA</code>,优先级高于扫码绑定。
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,350 @@
|
|||||||
|
import { useState, type FormEvent } from 'react';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import type { Chip } from '@/lib/schema';
|
||||||
|
import {
|
||||||
|
Field,
|
||||||
|
FormError,
|
||||||
|
JsonTextArea,
|
||||||
|
ListInput,
|
||||||
|
Section,
|
||||||
|
TextInput,
|
||||||
|
issueText,
|
||||||
|
} from './controls';
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
initial: Chip | null;
|
||||||
|
isNew: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
function blankChip(): Chip {
|
||||||
|
return {
|
||||||
|
slug: '',
|
||||||
|
type: 'soc',
|
||||||
|
brand: '',
|
||||||
|
model: '',
|
||||||
|
aliases: [],
|
||||||
|
meta: [],
|
||||||
|
detail: { cpuClusters: [], benchmarks: [], traits: [], caveats: [], sourceUrls: [], specGroups: {}, extra: {} },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeSlug(brand: string, model: string): string {
|
||||||
|
return `${brand} ${model}`
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/[^a-z0-9]+/g, '-')
|
||||||
|
.replace(/^-+|-+$/g, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseJson(text: string, label: string): unknown {
|
||||||
|
try {
|
||||||
|
return JSON.parse(text || 'null');
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error(`${label} JSON 无效:${error instanceof Error ? error.message : '解析失败'}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function setIn<T>(source: T, path: string, value: unknown): T {
|
||||||
|
const clone = structuredClone(source);
|
||||||
|
const keys = path.split('.');
|
||||||
|
let cursor = clone as Record<string, unknown>;
|
||||||
|
for (const key of keys.slice(0, -1)) {
|
||||||
|
if (cursor[key] === null || typeof cursor[key] !== 'object') cursor[key] = {};
|
||||||
|
cursor = cursor[key] as Record<string, unknown>;
|
||||||
|
}
|
||||||
|
const last = keys[keys.length - 1];
|
||||||
|
if (value === undefined || value === '') delete cursor[last];
|
||||||
|
else cursor[last] = value;
|
||||||
|
return clone;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function ChipEditor({ initial, isNew }: Props) {
|
||||||
|
const [chip, setChip] = useState<Chip>(() => (initial ? structuredClone(initial) : blankChip()));
|
||||||
|
const [aliasesText, setAliasesText] = useState(initial?.aliases.join(', ') ?? '');
|
||||||
|
const [cpuClustersText, setCpuClustersText] = useState(() =>
|
||||||
|
JSON.stringify(initial?.detail.cpuClusters ?? [], null, 2),
|
||||||
|
);
|
||||||
|
const [benchmarksText, setBenchmarksText] = useState(() =>
|
||||||
|
JSON.stringify(initial?.detail.benchmarks ?? [], null, 2),
|
||||||
|
);
|
||||||
|
const [extraText, setExtraText] = useState(() => JSON.stringify(initial?.detail.extra ?? {}, null, 2));
|
||||||
|
const [error, setError] = useState('');
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
|
||||||
|
const detail = chip.detail;
|
||||||
|
|
||||||
|
function updateChip<K extends keyof Chip>(key: K, value: Chip[K]) {
|
||||||
|
setChip((prev) => ({ ...prev, [key]: value }));
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateDetail(path: string, value: unknown) {
|
||||||
|
setChip((prev) => ({ ...prev, detail: setIn(prev.detail, path, value) }));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
|
||||||
|
event.preventDefault();
|
||||||
|
setSaving(true);
|
||||||
|
setError('');
|
||||||
|
|
||||||
|
try {
|
||||||
|
const cpuClusters = parseJson(cpuClustersText, 'CPU 核心簇');
|
||||||
|
if (!Array.isArray(cpuClusters)) throw new Error('CPU 核心簇必须是数组');
|
||||||
|
const benchmarks = parseJson(benchmarksText, '跑分');
|
||||||
|
if (!Array.isArray(benchmarks)) throw new Error('跑分必须是数组');
|
||||||
|
const extra = parseJson(extraText, '扩展字段');
|
||||||
|
if (!extra || typeof extra !== 'object' || Array.isArray(extra)) {
|
||||||
|
throw new Error('扩展字段必须是 JSON 对象');
|
||||||
|
}
|
||||||
|
|
||||||
|
const payload: Chip = {
|
||||||
|
...chip,
|
||||||
|
aliases: aliasesText
|
||||||
|
.split(',')
|
||||||
|
.map((item) => item.trim())
|
||||||
|
.filter(Boolean),
|
||||||
|
detail: {
|
||||||
|
...detail,
|
||||||
|
cpuClusters: cpuClusters as typeof detail.cpuClusters,
|
||||||
|
benchmarks: benchmarks as typeof detail.benchmarks,
|
||||||
|
extra: extra as Record<string, string>,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await fetch(`/api/chips${isNew ? '?create=1' : ''}`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'content-type': 'application/json' },
|
||||||
|
body: JSON.stringify(payload),
|
||||||
|
});
|
||||||
|
const data = await response.json();
|
||||||
|
if (!response.ok) throw new Error(issueText(data));
|
||||||
|
window.location.href = `/admin/chips/${data.chip.slug}?saved=1`;
|
||||||
|
} catch (caught) {
|
||||||
|
setError(caught instanceof Error ? caught.message : '保存失败');
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<form onSubmit={handleSubmit} className="mt-6">
|
||||||
|
{error && <FormError message={error} />}
|
||||||
|
|
||||||
|
<Section title="基本信息" description="slug 创建后不可修改">
|
||||||
|
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||||
|
<Field label="slug" hint="小写字母、数字、连字符">
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<TextInput
|
||||||
|
value={chip.slug}
|
||||||
|
disabled={!isNew}
|
||||||
|
placeholder="snapdragon-8-gen-3"
|
||||||
|
onChange={(event) => updateChip('slug', event.target.value)}
|
||||||
|
/>
|
||||||
|
{isNew && (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => updateChip('slug', makeSlug(chip.brand, chip.model))}
|
||||||
|
>
|
||||||
|
生成
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</Field>
|
||||||
|
<Field label="品牌">
|
||||||
|
<TextInput value={chip.brand} onChange={(event) => updateChip('brand', event.target.value)} />
|
||||||
|
</Field>
|
||||||
|
<Field label="型号">
|
||||||
|
<TextInput value={chip.model} onChange={(event) => updateChip('model', event.target.value)} />
|
||||||
|
</Field>
|
||||||
|
<Field label="代号">
|
||||||
|
<TextInput
|
||||||
|
value={chip.codename ?? ''}
|
||||||
|
onChange={(event) => updateChip('codename', event.target.value)}
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
<Field label="别名" hint="英文逗号分隔">
|
||||||
|
<TextInput value={aliasesText} onChange={(event) => setAliasesText(event.target.value)} />
|
||||||
|
</Field>
|
||||||
|
<Field label="制程">
|
||||||
|
<TextInput
|
||||||
|
value={chip.process ?? ''}
|
||||||
|
onChange={(event) => updateChip('process', event.target.value)}
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
<Field label="架构">
|
||||||
|
<TextInput value={chip.arch ?? ''} onChange={(event) => updateChip('arch', event.target.value)} />
|
||||||
|
</Field>
|
||||||
|
</div>
|
||||||
|
</Section>
|
||||||
|
|
||||||
|
<Section title="GPU">
|
||||||
|
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||||
|
<Field label="型号">
|
||||||
|
<TextInput
|
||||||
|
value={detail.gpuBlock?.name ?? ''}
|
||||||
|
onChange={(event) => updateDetail('gpuBlock.name', event.target.value)}
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
<Field label="架构">
|
||||||
|
<TextInput
|
||||||
|
value={detail.gpuBlock?.arch ?? ''}
|
||||||
|
onChange={(event) => updateDetail('gpuBlock.arch', event.target.value)}
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
<Field label="核心数">
|
||||||
|
<TextInput
|
||||||
|
type="number"
|
||||||
|
value={detail.gpuBlock?.cores ?? ''}
|
||||||
|
onChange={(event) =>
|
||||||
|
updateDetail(
|
||||||
|
'gpuBlock.cores',
|
||||||
|
event.target.value === '' ? undefined : Number(event.target.value),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
<Field label="最高频率">
|
||||||
|
<TextInput
|
||||||
|
value={detail.gpuBlock?.clockMax ?? ''}
|
||||||
|
onChange={(event) => updateDetail('gpuBlock.clockMax', event.target.value)}
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
<Field label="图形 API" hint="英文逗号分隔">
|
||||||
|
<ListInput
|
||||||
|
value={detail.gpuBlock?.apis ?? []}
|
||||||
|
onCommit={(apis) => updateDetail('gpuBlock.apis', apis)}
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
</div>
|
||||||
|
</Section>
|
||||||
|
|
||||||
|
<Section title="NPU / 其他模块">
|
||||||
|
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||||
|
<Field label="NPU 型号">
|
||||||
|
<TextInput
|
||||||
|
value={detail.npuBlock?.name ?? ''}
|
||||||
|
onChange={(event) => updateDetail('npuBlock.name', event.target.value)}
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
<Field label="NPU 算力">
|
||||||
|
<TextInput
|
||||||
|
value={detail.npuBlock?.tops ?? ''}
|
||||||
|
onChange={(event) => updateDetail('npuBlock.tops', event.target.value)}
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
<Field label="ISP">
|
||||||
|
<TextInput
|
||||||
|
value={detail.ispBlock ?? ''}
|
||||||
|
onChange={(event) => updateDetail('ispBlock', event.target.value)}
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
<Field label="DSP">
|
||||||
|
<TextInput
|
||||||
|
value={detail.dspBlock ?? ''}
|
||||||
|
onChange={(event) => updateDetail('dspBlock', event.target.value)}
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
<Field label="基带">
|
||||||
|
<TextInput
|
||||||
|
value={detail.modemBlock ?? ''}
|
||||||
|
onChange={(event) => updateDetail('modemBlock', event.target.value)}
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
</div>
|
||||||
|
</Section>
|
||||||
|
|
||||||
|
<Section title="内存、存储与显示支持">
|
||||||
|
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||||
|
<Field label="内存类型">
|
||||||
|
<TextInput
|
||||||
|
value={detail.memorySupport?.type ?? ''}
|
||||||
|
onChange={(event) => updateDetail('memorySupport.type', event.target.value)}
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
<Field label="内存最高频率">
|
||||||
|
<TextInput
|
||||||
|
value={detail.memorySupport?.maxClock ?? ''}
|
||||||
|
onChange={(event) => updateDetail('memorySupport.maxClock', event.target.value)}
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
<Field label="内存带宽">
|
||||||
|
<TextInput
|
||||||
|
value={detail.memorySupport?.bandwidth ?? ''}
|
||||||
|
onChange={(event) => updateDetail('memorySupport.bandwidth', event.target.value)}
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
<Field label="存储支持">
|
||||||
|
<TextInput
|
||||||
|
value={detail.storageSupport ?? ''}
|
||||||
|
onChange={(event) => updateDetail('storageSupport', event.target.value)}
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
<Field label="显示支持">
|
||||||
|
<TextInput
|
||||||
|
value={detail.displaySupport ?? ''}
|
||||||
|
onChange={(event) => updateDetail('displaySupport', event.target.value)}
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
</div>
|
||||||
|
</Section>
|
||||||
|
|
||||||
|
<Section title="视频编解码">
|
||||||
|
<div className="grid gap-3 sm:grid-cols-2">
|
||||||
|
<Field label="编码格式" hint="英文逗号分隔">
|
||||||
|
<ListInput
|
||||||
|
value={detail.videoCodec?.encode ?? []}
|
||||||
|
onCommit={(encode) => updateDetail('videoCodec.encode', encode)}
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
<Field label="解码格式" hint="英文逗号分隔">
|
||||||
|
<ListInput
|
||||||
|
value={detail.videoCodec?.decode ?? []}
|
||||||
|
onCommit={(decode) => updateDetail('videoCodec.decode', decode)}
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
</div>
|
||||||
|
</Section>
|
||||||
|
|
||||||
|
<Section title="CPU 核心簇" description="JSON 数组,结构与 socDetailSchema 一致">
|
||||||
|
<JsonTextArea value={cpuClustersText} onChange={setCpuClustersText} rows={10} />
|
||||||
|
</Section>
|
||||||
|
|
||||||
|
<Section title="跑分" description="JSON 数组,每项为 { name, score, unit }">
|
||||||
|
<JsonTextArea value={benchmarksText} onChange={setBenchmarksText} rows={8} />
|
||||||
|
</Section>
|
||||||
|
|
||||||
|
<Section title="扩展字段" description="JSON 字符串键值对">
|
||||||
|
<JsonTextArea value={extraText} onChange={setExtraText} rows={6} />
|
||||||
|
</Section>
|
||||||
|
|
||||||
|
<Section title="字段来源" description="M2 可手动标记核实;M3 由 AI 自动维护">
|
||||||
|
{chip.meta.length > 0 ? (
|
||||||
|
<p className="text-xs text-muted-foreground">共 {chip.meta.length} 条来源记录。</p>
|
||||||
|
) : (
|
||||||
|
<p className="text-xs text-muted-foreground">暂无字段级来源记录。</p>
|
||||||
|
)}
|
||||||
|
</Section>
|
||||||
|
|
||||||
|
<div className="sticky bottom-4 z-20 mt-6 flex flex-wrap items-center gap-3 rounded-lg border border-border bg-card px-4 py-3 shadow-lg">
|
||||||
|
<Button type="submit" disabled={saving}>
|
||||||
|
{saving ? '保存中…' : '保存'}
|
||||||
|
</Button>
|
||||||
|
<a
|
||||||
|
href="/admin"
|
||||||
|
className="text-sm text-muted-foreground transition-colors hover:text-foreground"
|
||||||
|
>
|
||||||
|
返回后台
|
||||||
|
</a>
|
||||||
|
{!isNew && (
|
||||||
|
<a
|
||||||
|
href={`/chips/${chip.slug}`}
|
||||||
|
target="_blank"
|
||||||
|
rel="noreferrer"
|
||||||
|
className="text-sm text-muted-foreground transition-colors hover:text-foreground"
|
||||||
|
>
|
||||||
|
查看前台
|
||||||
|
</a>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,150 @@
|
|||||||
|
import { useState, type FormEvent } from 'react';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Field, FormError, TextInput, issueText } from './controls';
|
||||||
|
|
||||||
|
function titleToken(token: string): string {
|
||||||
|
if (/^\d/.test(token)) return token;
|
||||||
|
const map: Record<string, string> = {
|
||||||
|
pro: 'Pro',
|
||||||
|
max: 'Max',
|
||||||
|
ultra: 'Ultra',
|
||||||
|
plus: 'Plus',
|
||||||
|
mini: 'Mini',
|
||||||
|
gt: 'GT',
|
||||||
|
ace: 'Ace',
|
||||||
|
find: 'Find',
|
||||||
|
x: 'X',
|
||||||
|
k: 'K',
|
||||||
|
note: 'Note',
|
||||||
|
fold: 'Fold',
|
||||||
|
flip: 'Flip',
|
||||||
|
se: 'SE',
|
||||||
|
fe: 'FE',
|
||||||
|
edge: 'Edge',
|
||||||
|
neo: 'Neo',
|
||||||
|
turbo: 'Turbo',
|
||||||
|
power: 'Power',
|
||||||
|
lite: 'Lite',
|
||||||
|
};
|
||||||
|
const lower = token.toLowerCase();
|
||||||
|
if (map[lower]) return map[lower];
|
||||||
|
return token.charAt(0).toUpperCase() + token.slice(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const BRANDS: [string, string][] = [
|
||||||
|
['redmi', 'Redmi'],
|
||||||
|
['xiaomi', 'Xiaomi'],
|
||||||
|
['poco', 'POCO'],
|
||||||
|
['oppo', 'OPPO'],
|
||||||
|
['oneplus', 'OnePlus'],
|
||||||
|
['vivo', 'vivo'],
|
||||||
|
['iqoo', 'iQOO'],
|
||||||
|
['honor', 'HONOR'],
|
||||||
|
['huawei', 'HUAWEI'],
|
||||||
|
['samsung', 'Samsung'],
|
||||||
|
['apple', 'Apple'],
|
||||||
|
['iphone', 'Apple'],
|
||||||
|
['realme', 'realme'],
|
||||||
|
['meizu', 'Meizu'],
|
||||||
|
['nubia', 'nubia'],
|
||||||
|
['zte', 'ZTE'],
|
||||||
|
['lenovo', 'Lenovo'],
|
||||||
|
['motorola', 'Motorola'],
|
||||||
|
['sony', 'Sony'],
|
||||||
|
['asus', 'ASUS'],
|
||||||
|
];
|
||||||
|
|
||||||
|
function preview(slug: string): { brand: string; model: string } {
|
||||||
|
const parts = slug.split('-').filter(Boolean);
|
||||||
|
const prefix = BRANDS.find(([key]) => key === parts[0]);
|
||||||
|
const rest = prefix ? parts.slice(1) : parts;
|
||||||
|
if (!prefix) {
|
||||||
|
return {
|
||||||
|
brand: titleToken(parts[0] ?? ''),
|
||||||
|
model: rest.map(titleToken).join(' ') || '—',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const model = rest.map(titleToken).join(' ') || prefix[1];
|
||||||
|
return {
|
||||||
|
brand: prefix[1],
|
||||||
|
model: prefix[0] === 'iphone' ? `iPhone ${model}` : model,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function DeviceQuickCreate() {
|
||||||
|
const [slug, setSlug] = useState('');
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [error, setError] = useState('');
|
||||||
|
const [status, setStatus] = useState('');
|
||||||
|
|
||||||
|
const valid = /^[a-z0-9]+(-[a-z0-9]+)*$/.test(slug);
|
||||||
|
const identity = slug ? preview(slug) : undefined;
|
||||||
|
|
||||||
|
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
|
||||||
|
event.preventDefault();
|
||||||
|
if (!valid) {
|
||||||
|
setError('slug 只能用小写字母、数字和连字符。');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setLoading(true);
|
||||||
|
setError('');
|
||||||
|
setStatus('正在多来源检索与交叉验证,通常需要 30–90 秒…');
|
||||||
|
try {
|
||||||
|
const response = await fetch('/api/ai/prospect', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'content-type': 'application/json' },
|
||||||
|
body: JSON.stringify({ slug }),
|
||||||
|
});
|
||||||
|
const data = await response.json();
|
||||||
|
if (!response.ok) throw new Error(issueText(data));
|
||||||
|
setStatus(`已生成 ${data.fields ?? 0} 个字段,正在进入详细编辑页…`);
|
||||||
|
window.location.href = `/admin/devices/${data.device.slug}?created=1`;
|
||||||
|
} catch (caught) {
|
||||||
|
setError(caught instanceof Error ? caught.message : 'AI 创建失败');
|
||||||
|
setStatus('');
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<form onSubmit={handleSubmit} className="mt-6 max-w-xl">
|
||||||
|
{error && <FormError message={error} />}
|
||||||
|
|
||||||
|
<div className="rounded-lg border border-border bg-card p-5">
|
||||||
|
<h2 className="text-sm font-semibold">AI 快速创建手机</h2>
|
||||||
|
<p className="mt-1.5 text-xs text-muted-foreground">
|
||||||
|
只需输入 slug。AI 会从官网、ZOL、PConline、Kalvo、GSMArena 等白名单来源检索,交叉验证后写入初稿,
|
||||||
|
再跳转到详细编辑页逐项修改。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div className="mt-4">
|
||||||
|
<Field label="slug" hint="例如 redmi-k90-pro-max、oppo-find-x10-pro-max">
|
||||||
|
<TextInput
|
||||||
|
value={slug}
|
||||||
|
placeholder="redmi-k90-pro-max"
|
||||||
|
autoFocus
|
||||||
|
onChange={(event) => setSlug(event.target.value.trim().toLowerCase())}
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{identity && (
|
||||||
|
<p className="mt-3 text-xs text-muted-foreground">
|
||||||
|
将按 <span className="text-foreground">{identity.brand}</span> /{' '}
|
||||||
|
<span className="text-foreground">{identity.model}</span> 检索
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Button type="submit" className="mt-4 w-full" disabled={loading || !slug}>
|
||||||
|
{loading ? '检索与补全中…' : 'AI 检索并创建'}
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
{status && <p className="mt-3 text-xs text-primary">{status}</p>}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p className="mt-3 text-[11px] text-muted-foreground">
|
||||||
|
初稿中的 low 置信度字段会保留标记;进入编辑页后可逐项确认、修改,或使用字段旁的 AI 按钮继续补全。
|
||||||
|
</p>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
import { useState } from 'react';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { FormError, JsonTextArea, TextInput, issueText } from './controls';
|
||||||
|
|
||||||
|
interface ImportResult {
|
||||||
|
ok: boolean;
|
||||||
|
counts: { devices: number; chips: number };
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Issue {
|
||||||
|
path?: string;
|
||||||
|
message?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function ImportPanel() {
|
||||||
|
const [text, setText] = useState('');
|
||||||
|
const [fileName, setFileName] = useState('');
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [error, setError] = useState('');
|
||||||
|
const [issues, setIssues] = useState<Issue[]>([]);
|
||||||
|
const [result, setResult] = useState<ImportResult['counts'] | null>(null);
|
||||||
|
|
||||||
|
function formatJson() {
|
||||||
|
try {
|
||||||
|
setText(JSON.stringify(JSON.parse(text), null, 2));
|
||||||
|
setError('');
|
||||||
|
} catch (caught) {
|
||||||
|
setError(`JSON 解析失败:${caught instanceof Error ? caught.message : '格式错误'}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleImport() {
|
||||||
|
setBusy(true);
|
||||||
|
setError('');
|
||||||
|
setIssues([]);
|
||||||
|
setResult(null);
|
||||||
|
|
||||||
|
try {
|
||||||
|
JSON.parse(text);
|
||||||
|
} catch (caught) {
|
||||||
|
setError(`JSON 解析失败:${caught instanceof Error ? caught.message : '格式错误'}`);
|
||||||
|
setBusy(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch('/api/import', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'content-type': 'application/json' },
|
||||||
|
body: text,
|
||||||
|
});
|
||||||
|
const data = await response.json();
|
||||||
|
if (!response.ok) {
|
||||||
|
setError(issueText(data));
|
||||||
|
setIssues(Array.isArray(data.issues) ? data.issues : []);
|
||||||
|
setBusy(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setResult((data as ImportResult).counts);
|
||||||
|
} catch (caught) {
|
||||||
|
setError(caught instanceof Error ? caught.message : '导入失败');
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mt-6 space-y-4">
|
||||||
|
<div className="rounded-lg border border-border bg-card p-5">
|
||||||
|
<div className="flex flex-wrap items-center gap-3">
|
||||||
|
<label className="text-xs text-muted-foreground">
|
||||||
|
选择 JSON 文件
|
||||||
|
</label>
|
||||||
|
<TextInput
|
||||||
|
type="file"
|
||||||
|
accept="application/json,.json"
|
||||||
|
className="max-w-sm text-xs file:mr-3 file:rounded-md file:border file:border-border file:bg-secondary file:px-3 file:py-1.5 file:text-xs"
|
||||||
|
onChange={async (event) => {
|
||||||
|
const file = event.target.files?.[0];
|
||||||
|
if (!file) return;
|
||||||
|
setFileName(file.name);
|
||||||
|
setText(await file.text());
|
||||||
|
setError('');
|
||||||
|
setResult(null);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
{fileName && <span className="text-xs text-muted-foreground">{fileName}</span>}
|
||||||
|
<Button type="button" variant="outline" size="sm" onClick={formatJson} disabled={!text.trim()}>
|
||||||
|
格式化
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-4">
|
||||||
|
<JsonTextArea value={text} onChange={setText} rows={16} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{error && <div className="mt-3"><FormError message={error} /></div>}
|
||||||
|
|
||||||
|
{issues.length > 0 && (
|
||||||
|
<ul className="mt-3 max-h-40 space-y-1 overflow-auto rounded-md border border-destructive/40 bg-destructive/10 p-3 text-xs text-destructive">
|
||||||
|
{issues.slice(0, 40).map((issue, index) => (
|
||||||
|
<li key={`${issue.path}-${index}`}>
|
||||||
|
<span className="font-mono">{issue.path || '(根)'}</span>
|
||||||
|
<span className="mx-1.5">·</span>
|
||||||
|
{issue.message}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{result && (
|
||||||
|
<p className="mt-3 rounded-md border border-primary/40 bg-primary/10 px-3 py-2 text-sm text-primary">
|
||||||
|
导入完成:{result.devices} 台设备 / {result.chips} 颗芯片。
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="mt-4 flex flex-wrap items-center gap-3">
|
||||||
|
<Button type="button" onClick={handleImport} disabled={busy || !text.trim()}>
|
||||||
|
{busy ? '导入中…' : '开始导入'}
|
||||||
|
</Button>
|
||||||
|
<a
|
||||||
|
href="/api/export"
|
||||||
|
className="text-sm text-muted-foreground transition-colors hover:text-foreground"
|
||||||
|
>
|
||||||
|
先下载当前全量 JSON
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,215 @@
|
|||||||
|
import {
|
||||||
|
useEffect,
|
||||||
|
useState,
|
||||||
|
type InputHTMLAttributes,
|
||||||
|
type ReactNode,
|
||||||
|
type SelectHTMLAttributes,
|
||||||
|
type TextareaHTMLAttributes,
|
||||||
|
} from 'react';
|
||||||
|
import { cn } from '@/lib/utils';
|
||||||
|
import type { FieldMeta } from '@/lib/schema';
|
||||||
|
|
||||||
|
const inputClass =
|
||||||
|
'h-9 w-full rounded-md border border-border bg-background px-3 text-sm text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring';
|
||||||
|
|
||||||
|
export function Section({
|
||||||
|
title,
|
||||||
|
description,
|
||||||
|
action,
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
title: string;
|
||||||
|
description?: string;
|
||||||
|
action?: ReactNode;
|
||||||
|
children: ReactNode;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<section className="mt-5 rounded-lg border border-border bg-card p-5">
|
||||||
|
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||||
|
<div className="flex flex-wrap items-baseline gap-2">
|
||||||
|
<h2 className="text-sm font-semibold">{title}</h2>
|
||||||
|
{description && <p className="text-xs text-muted-foreground">{description}</p>}
|
||||||
|
</div>
|
||||||
|
{action}
|
||||||
|
</div>
|
||||||
|
<div className="mt-4">{children}</div>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function MetaBadge({ item }: { item?: FieldMeta }) {
|
||||||
|
if (!item) return null;
|
||||||
|
const tone =
|
||||||
|
item.confidence === 'high'
|
||||||
|
? 'border-primary/40 bg-primary/10 text-primary'
|
||||||
|
: item.confidence === 'medium'
|
||||||
|
? 'border-yellow-500/40 bg-yellow-500/10 text-yellow-500'
|
||||||
|
: 'border-destructive/40 bg-destructive/10 text-destructive';
|
||||||
|
const title = [item.sourceUrl, item.capturedAt && `抓取于 ${item.capturedAt}`].filter(Boolean).join('\n');
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
className={cn('rounded-full border px-2.5 py-1 text-xs font-medium leading-none', tone)}
|
||||||
|
title={title || undefined}
|
||||||
|
>
|
||||||
|
{item.confidence}
|
||||||
|
{item.verified ? ' · 已核' : ' · 待核'}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Field({
|
||||||
|
label,
|
||||||
|
hint,
|
||||||
|
meta,
|
||||||
|
action,
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
label: string;
|
||||||
|
hint?: string;
|
||||||
|
meta?: FieldMeta;
|
||||||
|
action?: ReactNode;
|
||||||
|
children: ReactNode;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<label className="flex min-w-0 flex-col gap-1.5">
|
||||||
|
<span className="flex flex-wrap items-center gap-1.5 text-[13px] leading-none text-muted-foreground">
|
||||||
|
{label}
|
||||||
|
<MetaBadge item={meta} />
|
||||||
|
{action}
|
||||||
|
</span>
|
||||||
|
{children}
|
||||||
|
{hint && <span className="text-[11px] text-muted-foreground">{hint}</span>}
|
||||||
|
</label>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function TextInput({ className, ...props }: InputHTMLAttributes<HTMLInputElement>) {
|
||||||
|
return <input {...props} className={cn(inputClass, className)} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function TextArea({ className, ...props }: TextareaHTMLAttributes<HTMLTextAreaElement>) {
|
||||||
|
return (
|
||||||
|
<textarea
|
||||||
|
{...props}
|
||||||
|
className={cn(
|
||||||
|
'min-h-20 w-full rounded-md border border-border bg-background px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring',
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SelectInput({ className, children, ...props }: SelectHTMLAttributes<HTMLSelectElement>) {
|
||||||
|
return (
|
||||||
|
<select {...props} className={cn(inputClass, 'appearance-none', className)}>
|
||||||
|
{children}
|
||||||
|
</select>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function BoolSelect({
|
||||||
|
value,
|
||||||
|
onChange,
|
||||||
|
}: {
|
||||||
|
value: boolean | undefined;
|
||||||
|
onChange: (next: boolean | undefined) => void;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<SelectInput
|
||||||
|
value={value === undefined ? '' : value ? 'true' : 'false'}
|
||||||
|
onChange={(event) => {
|
||||||
|
const raw = event.target.value;
|
||||||
|
onChange(raw === '' ? undefined : raw === 'true');
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<option value="">未填写</option>
|
||||||
|
<option value="true">支持</option>
|
||||||
|
<option value="false">不支持</option>
|
||||||
|
</SelectInput>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ListInput({
|
||||||
|
value,
|
||||||
|
onCommit,
|
||||||
|
placeholder,
|
||||||
|
}: {
|
||||||
|
value: string[];
|
||||||
|
onCommit: (next: string[]) => void;
|
||||||
|
placeholder?: string;
|
||||||
|
}) {
|
||||||
|
const [text, setText] = useState(value.join(', '));
|
||||||
|
const joined = value.join(', ');
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
// AI 应用或外部字段更新后,把列表重新同步到输入框
|
||||||
|
setText(joined);
|
||||||
|
}, [joined]);
|
||||||
|
|
||||||
|
function commit() {
|
||||||
|
onCommit(
|
||||||
|
text
|
||||||
|
.split(',')
|
||||||
|
.map((item) => item.trim())
|
||||||
|
.filter(Boolean),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<TextInput
|
||||||
|
value={text}
|
||||||
|
placeholder={placeholder}
|
||||||
|
onChange={(event) => setText(event.target.value)}
|
||||||
|
onBlur={commit}
|
||||||
|
onKeyDown={(event) => {
|
||||||
|
if (event.key === 'Enter') {
|
||||||
|
event.preventDefault();
|
||||||
|
commit();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function JsonTextArea({
|
||||||
|
value,
|
||||||
|
onChange,
|
||||||
|
error,
|
||||||
|
rows = 12,
|
||||||
|
}: {
|
||||||
|
value: string;
|
||||||
|
onChange: (next: string) => void;
|
||||||
|
error?: string;
|
||||||
|
rows?: number;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<TextArea
|
||||||
|
value={value}
|
||||||
|
rows={rows}
|
||||||
|
spellCheck={false}
|
||||||
|
className="font-mono text-xs"
|
||||||
|
onChange={(event) => onChange(event.target.value)}
|
||||||
|
/>
|
||||||
|
{error && <p className="mt-1 text-[11px] text-destructive">{error}</p>}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function FormError({ message }: { message: string }) {
|
||||||
|
return (
|
||||||
|
<p className="rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive">
|
||||||
|
{message}
|
||||||
|
</p>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 把接口返回的 zod 校验问题转成一行可读文本 */
|
||||||
|
export function issueText(payload: unknown): string {
|
||||||
|
if (payload && typeof payload === 'object') {
|
||||||
|
const data = payload as { error?: string; issues?: { path?: string; message?: string }[] };
|
||||||
|
const details = data.issues?.map((issue) => `${issue.path || '(根)'}: ${issue.message}`).join(';');
|
||||||
|
if (data.error && details) return `${data.error}:${details}`;
|
||||||
|
if (data.error) return data.error;
|
||||||
|
}
|
||||||
|
return '操作失败,请检查内容。';
|
||||||
|
}
|
||||||
+172
-11
@@ -1,48 +1,209 @@
|
|||||||
---
|
---
|
||||||
|
import { ClientRouter } from 'astro:transitions';
|
||||||
|
import CompareTray from '@/components/CompareTray.astro';
|
||||||
import '../styles/global.css';
|
import '../styles/global.css';
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
title?: string;
|
title?: string;
|
||||||
description?: string;
|
description?: string;
|
||||||
|
/** OG 图路径,默认站点通用图;详情页传设备 slug */
|
||||||
|
ogImage?: string;
|
||||||
|
/** 用于 og:url 与 canonical 的路径,默认取当前路径 */
|
||||||
|
path?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
const {
|
const {
|
||||||
title = 'LFSpecs',
|
title = 'LFSpecs',
|
||||||
description = '公开硬件规格库:收录手机、芯片等设备的详细参数,支持横向对比。',
|
description = '公开硬件规格库:收录手机、芯片等设备的详细参数,支持横向对比。',
|
||||||
|
ogImage,
|
||||||
|
path,
|
||||||
} = Astro.props;
|
} = Astro.props;
|
||||||
|
|
||||||
|
const site = Astro.site ?? new URL('https://specs.atie.fun');
|
||||||
|
const canonical = new URL(path ?? Astro.url.pathname, site).href;
|
||||||
|
const image = new URL(ogImage ?? '/og/site.png', site).href;
|
||||||
|
const ogType = path?.startsWith('/devices/') ? 'article' : 'website';
|
||||||
---
|
---
|
||||||
|
|
||||||
<!doctype html>
|
<!doctype html>
|
||||||
<html lang="zh-CN">
|
<html lang="zh-CN" data-theme="dark">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8" />
|
<meta charset="utf-8" />
|
||||||
|
<script is:inline>
|
||||||
|
(() => {
|
||||||
|
try {
|
||||||
|
const saved = localStorage.getItem('lfs-theme');
|
||||||
|
const theme =
|
||||||
|
saved === 'light' || saved === 'dark'
|
||||||
|
? saved
|
||||||
|
: window.matchMedia('(prefers-color-scheme: light)').matches
|
||||||
|
? 'light'
|
||||||
|
: 'dark';
|
||||||
|
document.documentElement.dataset.theme = theme;
|
||||||
|
} catch {
|
||||||
|
document.documentElement.dataset.theme = 'dark';
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
<meta name="generator" content={Astro.generator} />
|
<meta name="generator" content={Astro.generator} />
|
||||||
<meta name="description" content={description} />
|
<meta name="description" content={description} />
|
||||||
|
<link rel="canonical" href={canonical} />
|
||||||
|
|
||||||
|
<meta property="og:type" content={ogType} />
|
||||||
|
<meta property="og:site_name" content="LFSpecs" />
|
||||||
|
<meta property="og:locale" content="zh_CN" />
|
||||||
|
<meta property="og:title" content={title} />
|
||||||
|
<meta property="og:description" content={description} />
|
||||||
|
<meta property="og:url" content={canonical} />
|
||||||
|
<meta property="og:image" content={image} />
|
||||||
|
<meta property="og:image:width" content="1200" />
|
||||||
|
<meta property="og:image:height" content="630" />
|
||||||
|
<meta property="og:image:alt" content={title} />
|
||||||
|
|
||||||
|
<meta name="twitter:card" content="summary_large_image" />
|
||||||
|
<meta name="twitter:title" content={title} />
|
||||||
|
<meta name="twitter:description" content={description} />
|
||||||
|
<meta name="twitter:image" content={image} />
|
||||||
|
|
||||||
<title>{title}</title>
|
<title>{title}</title>
|
||||||
|
<ClientRouter />
|
||||||
</head>
|
</head>
|
||||||
<body class="min-h-dvh">
|
<body class="min-h-dvh">
|
||||||
<header class="border-b border-border/60">
|
<header class="site-header border-b border-border/60 print-hidden">
|
||||||
<div class="mx-auto flex h-14 max-w-6xl items-center gap-6 px-5">
|
<div class="mx-auto flex h-14 max-w-6xl items-center gap-4 px-5">
|
||||||
<a href="/" class="text-sm font-semibold tracking-tight">LFSpecs</a>
|
<a href="/" class="shrink-0 text-sm font-semibold tracking-tight">LFSpecs</a>
|
||||||
<nav class="flex items-center gap-1 text-sm text-muted-foreground">
|
<nav class="flex min-w-0 items-center gap-0.5 text-xs text-muted-foreground sm:gap-1 sm:text-sm">
|
||||||
<a href="/devices" class="rounded-md px-2.5 py-1.5 transition-colors hover:bg-accent hover:text-foreground">手机</a>
|
<a href="/devices" class="rounded-md px-2 py-1.5 transition-colors hover:bg-accent hover:text-foreground sm:px-2.5">手机</a>
|
||||||
<a href="/chips" class="rounded-md px-2.5 py-1.5 transition-colors hover:bg-accent hover:text-foreground">芯片</a>
|
<a href="/chips" class="rounded-md px-2 py-1.5 transition-colors hover:bg-accent hover:text-foreground sm:px-2.5">芯片</a>
|
||||||
<a href="/brands" class="rounded-md px-2.5 py-1.5 transition-colors hover:bg-accent hover:text-foreground">品牌</a>
|
<a href="/rankings" class="rounded-md px-2 py-1.5 transition-colors hover:bg-accent hover:text-foreground sm:px-2.5">排行</a>
|
||||||
<a href="/poc" class="rounded-md px-2.5 py-1.5 transition-colors hover:bg-accent hover:text-foreground">组件自检</a>
|
<a href="/compare" class="rounded-md px-2 py-1.5 transition-colors hover:bg-accent hover:text-foreground sm:px-2.5">对比</a>
|
||||||
|
<a href="/brands" class="rounded-md px-2 py-1.5 transition-colors hover:bg-accent hover:text-foreground sm:px-2.5">品牌</a>
|
||||||
|
<a href="/poc" class="hidden rounded-md px-2.5 py-1.5 transition-colors hover:bg-accent hover:text-foreground sm:inline-flex">组件自检</a>
|
||||||
</nav>
|
</nav>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
data-theme-toggle
|
||||||
|
aria-label="切换日间 / 夜间主题"
|
||||||
|
title="切换日间 / 夜间主题"
|
||||||
|
class="ml-auto inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md border border-border text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
|
||||||
|
>
|
||||||
|
<svg class="theme-icon-sun h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
||||||
|
<circle cx="12" cy="12" r="4"></circle>
|
||||||
|
<path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M6.34 17.66l-1.41 1.41M19.07 4.93l-1.41 1.41"></path>
|
||||||
|
</svg>
|
||||||
|
<svg class="theme-icon-moon h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
||||||
|
<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 9.79 9.79z"></path>
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<main class="mx-auto max-w-6xl px-5 py-10">
|
<main class="mx-auto max-w-6xl px-5 py-10" transition:animate="fade">
|
||||||
<slot />
|
<slot />
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
<footer class="mt-16 border-t border-border/60 py-8">
|
<footer class="site-footer mt-16 border-t border-border/60 py-8 print-hidden">
|
||||||
<div class="mx-auto max-w-6xl px-5 text-xs text-muted-foreground">
|
<div class="mx-auto max-w-6xl px-5 text-xs text-muted-foreground">
|
||||||
<p>数据由人工与 AI 辅助整理,仅供参考。</p>
|
<p>数据由人工与 AI 辅助整理,仅供参考。</p>
|
||||||
</div>
|
</div>
|
||||||
</footer>
|
</footer>
|
||||||
|
|
||||||
|
<CompareTray />
|
||||||
|
|
||||||
|
<dialog id="lfs-lightbox" class="image-lightbox" aria-label="图片预览">
|
||||||
|
<button type="button" class="image-lightbox-close" data-lightbox-close aria-label="关闭图片预览">×</button>
|
||||||
|
<img data-lightbox-image alt="" />
|
||||||
|
</dialog>
|
||||||
|
|
||||||
|
<script is:inline>
|
||||||
|
(() => {
|
||||||
|
if (window.__lfsLightboxReady) return;
|
||||||
|
window.__lfsLightboxReady = true;
|
||||||
|
|
||||||
|
document.addEventListener('click', (event) => {
|
||||||
|
const target = event.target;
|
||||||
|
if (!(target instanceof Element)) return;
|
||||||
|
|
||||||
|
const dialog = document.getElementById('lfs-lightbox');
|
||||||
|
|
||||||
|
if (target.closest('[data-lightbox-close]')) {
|
||||||
|
if (dialog && dialog.open) dialog.close();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (dialog && dialog.open && target === dialog) {
|
||||||
|
dialog.close();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const trigger = target.closest('[data-lightbox]');
|
||||||
|
if (!trigger) return;
|
||||||
|
const src = trigger.getAttribute('data-lightbox') || trigger.getAttribute('href');
|
||||||
|
const alt = trigger.getAttribute('data-alt') || '';
|
||||||
|
const image = dialog?.querySelector('[data-lightbox-image]');
|
||||||
|
if (!dialog || !image || !src) return;
|
||||||
|
|
||||||
|
if (typeof dialog.showModal !== 'function') {
|
||||||
|
window.open(src, '_blank', 'noopener');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
event.preventDefault();
|
||||||
|
image.src = src;
|
||||||
|
image.alt = alt;
|
||||||
|
dialog.showModal();
|
||||||
|
document.documentElement.classList.add('lightbox-open');
|
||||||
|
dialog.addEventListener(
|
||||||
|
'close',
|
||||||
|
() => document.documentElement.classList.remove('lightbox-open'),
|
||||||
|
{ once: true },
|
||||||
|
);
|
||||||
|
});
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<script is:inline>
|
||||||
|
(() => {
|
||||||
|
if (window.__lfsThemeReady) return;
|
||||||
|
window.__lfsThemeReady = true;
|
||||||
|
|
||||||
|
const savedTheme = () => {
|
||||||
|
try {
|
||||||
|
const saved = localStorage.getItem('lfs-theme');
|
||||||
|
return saved === 'light' || saved === 'dark' ? saved : null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const restoreTheme = () => {
|
||||||
|
const theme = savedTheme();
|
||||||
|
if (theme) document.documentElement.dataset.theme = theme;
|
||||||
|
};
|
||||||
|
|
||||||
|
document.addEventListener('click', (event) => {
|
||||||
|
const target = event.target;
|
||||||
|
if (!(target instanceof Element)) return;
|
||||||
|
if (!target.closest('[data-theme-toggle]')) return;
|
||||||
|
const next = document.documentElement.dataset.theme === 'light' ? 'dark' : 'light';
|
||||||
|
document.documentElement.dataset.theme = next;
|
||||||
|
try {
|
||||||
|
localStorage.setItem('lfs-theme', next);
|
||||||
|
} catch {}
|
||||||
|
});
|
||||||
|
|
||||||
|
// ClientRouter 会换入服务端渲染的 <html data-theme="dark">,
|
||||||
|
// 跨页导航后需要把用户选择的主题重新写回去。
|
||||||
|
document.addEventListener('astro:before-swap', (event) => {
|
||||||
|
const theme = savedTheme();
|
||||||
|
if (theme && event.newDocument?.documentElement) {
|
||||||
|
event.newDocument.documentElement.dataset.theme = theme;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
document.addEventListener('astro:after-swap', restoreTheme);
|
||||||
|
document.addEventListener('astro:page-load', restoreTheme);
|
||||||
|
restoreTheme();
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
import type { CameraModule, PhoneDevice, PhoneSpecs } from '../schema';
|
||||||
|
import { enrichHardwareSpecs } from '../hardware-catalog';
|
||||||
|
import { setValueAtPath } from '../spec-fields';
|
||||||
|
import type { AiLookupField } from './types';
|
||||||
|
|
||||||
|
const cameraPathPattern = /^specs\.(rearCamera|frontCamera)\[(\d+)\]\.(.+)$/;
|
||||||
|
|
||||||
|
/** 把 AI 返回的扁平字段合入设备,并同步写入字段级来源与置信度 */
|
||||||
|
export function applyAiFields(device: PhoneDevice, fields: AiLookupField[]): PhoneDevice {
|
||||||
|
let specs = structuredClone(device.specs);
|
||||||
|
|
||||||
|
for (const field of fields) {
|
||||||
|
const cameraMatch = cameraPathPattern.exec(field.path);
|
||||||
|
if (cameraMatch) {
|
||||||
|
const [, kind, indexText, key] = cameraMatch;
|
||||||
|
const index = Number(indexText);
|
||||||
|
const defaultPosition: CameraModule['position'] =
|
||||||
|
kind === 'frontCamera' ? 'front' : 'wide';
|
||||||
|
const list: CameraModule[] =
|
||||||
|
kind === 'frontCamera' ? specs.frontCamera : specs.rearCamera;
|
||||||
|
|
||||||
|
while (list.length <= index) {
|
||||||
|
list.push({ position: defaultPosition, extra: {} });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (key === 'position') {
|
||||||
|
list[index] = {
|
||||||
|
...list[index],
|
||||||
|
position: field.value as CameraModule['position'],
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
list[index] = setValueAtPath(list[index], key, field.value);
|
||||||
|
}
|
||||||
|
specs = { ...specs, [kind]: list } as PhoneSpecs;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
specs = setValueAtPath(specs, field.path.replace(/^specs\./, ''), field.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
const capturedAt = new Date().toISOString();
|
||||||
|
const metaMap = new Map(device.meta.map((item) => [item.path, item]));
|
||||||
|
for (const field of fields) {
|
||||||
|
metaMap.set(field.path, {
|
||||||
|
path: field.path,
|
||||||
|
confidence: field.confidence,
|
||||||
|
sourceUrl: field.sourceUrl,
|
||||||
|
verified: false,
|
||||||
|
capturedAt,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
...device,
|
||||||
|
specs: enrichHardwareSpecs(specs),
|
||||||
|
meta: [...metaMap.values()],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 清空某字段的值与来源记录;摄像头位置被清空时回退到合法默认值 */
|
||||||
|
export function clearFieldValue(device: PhoneDevice, path: string): PhoneDevice {
|
||||||
|
const cameraMatch = cameraPathPattern.exec(path);
|
||||||
|
let specs: PhoneSpecs;
|
||||||
|
|
||||||
|
if (cameraMatch) {
|
||||||
|
const [, kind, indexText, key] = cameraMatch;
|
||||||
|
const index = Number(indexText);
|
||||||
|
const list = [
|
||||||
|
...(kind === 'frontCamera' ? device.specs.frontCamera : device.specs.rearCamera),
|
||||||
|
];
|
||||||
|
if (key === 'position') {
|
||||||
|
if (list[index]) {
|
||||||
|
list[index] = {
|
||||||
|
...list[index],
|
||||||
|
position: kind === 'frontCamera' ? 'front' : 'wide',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
specs = { ...device.specs, [kind]: list } as PhoneSpecs;
|
||||||
|
} else {
|
||||||
|
specs = setValueAtPath(device.specs, path.replace(/^specs\./, ''), undefined);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
specs = setValueAtPath(device.specs, path.replace(/^specs\./, ''), undefined);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
...device,
|
||||||
|
specs,
|
||||||
|
meta: device.meta.filter((item) => item.path !== path),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatFieldValue(value: unknown): string {
|
||||||
|
if (value === undefined || value === null || value === '') return '—';
|
||||||
|
if (typeof value === 'boolean') return value ? '支持' : '不支持';
|
||||||
|
if (Array.isArray(value)) return value.length > 0 ? value.join(' / ') : '—';
|
||||||
|
if (typeof value === 'object') return JSON.stringify(value);
|
||||||
|
return String(value);
|
||||||
|
}
|
||||||
@@ -0,0 +1,905 @@
|
|||||||
|
import { createHash } from 'node:crypto';
|
||||||
|
import { z } from 'zod';
|
||||||
|
import type { Confidence } from '../schema/meta';
|
||||||
|
import { getAiCache, saveAiCache } from '../repo';
|
||||||
|
import { PHONE_SPEC_SECTIONS, resolveFieldPath } from '../spec-fields';
|
||||||
|
import {
|
||||||
|
buildFieldMessages,
|
||||||
|
buildLookupMessages,
|
||||||
|
buildSectionMessages,
|
||||||
|
buildTeardownSummaryMessages,
|
||||||
|
type ChatMessage,
|
||||||
|
} from './prompt';
|
||||||
|
import {
|
||||||
|
fetchManualSources,
|
||||||
|
searchFieldSources,
|
||||||
|
searchSectionSources,
|
||||||
|
searchSpecs,
|
||||||
|
type SearchScope,
|
||||||
|
type WebSource,
|
||||||
|
} from './search';
|
||||||
|
import type { AiFieldLookupResult, AiFieldValue, AiLookupField, AiLookupResult } from './types';
|
||||||
|
|
||||||
|
export class AiNotConfiguredError extends Error {}
|
||||||
|
|
||||||
|
export class AiLookupError extends Error {
|
||||||
|
constructor(
|
||||||
|
message: string,
|
||||||
|
readonly status = 502,
|
||||||
|
) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LookupInput {
|
||||||
|
brand: string;
|
||||||
|
model: string;
|
||||||
|
force?: boolean;
|
||||||
|
/** 用户补充的官网参数文本,用于无搜索 key 或最新机型 */
|
||||||
|
sourceText?: string;
|
||||||
|
/** 补充资料对应的官方 URL,可选 */
|
||||||
|
sourceUrl?: string;
|
||||||
|
/** 多个补充链接(官方 / ZOL / PConline 等),可选 */
|
||||||
|
sourceUrls?: string[];
|
||||||
|
/** 检索范围:源网站 / 全网 / 拆机视频;default = 各补全方式的现状行为 */
|
||||||
|
searchScope?: SearchScope;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --------------------- 拆机视频字幕提炼 --------------------- */
|
||||||
|
|
||||||
|
const TEARDOWN_SUMMARY_TTL = 24 * 60 * 60 * 1000;
|
||||||
|
const teardownSummaryCache = new Map<string, { summary: string; expires: number }>();
|
||||||
|
/** 字幕提炼判定机型不符时的缓存标记 */
|
||||||
|
const TEARDOWN_MISMATCH = '__mismatch__';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 拆机视频字幕长且口语化:先让 AI 提炼成参数清单,再作为高密度资料
|
||||||
|
* 进入补全提示词。提炼结果按视频缓存 24 小时,失败时回退原始字幕;
|
||||||
|
* 视频实际讲的是其他机型时直接丢弃,防止上一代参数混入。
|
||||||
|
*/
|
||||||
|
async function condenseTeardownSources(
|
||||||
|
config: { base: string; key: string; model: string },
|
||||||
|
brand: string,
|
||||||
|
model: string,
|
||||||
|
sources: WebSource[],
|
||||||
|
): Promise<WebSource[]> {
|
||||||
|
const results = await Promise.all(
|
||||||
|
sources.map(async (source) => {
|
||||||
|
if (source.kind !== 'teardown' || source.content.length < 1200) return source;
|
||||||
|
const cacheKey = normalizeUrl(source.url);
|
||||||
|
const cached = teardownSummaryCache.get(cacheKey);
|
||||||
|
if (cached && cached.expires > Date.now()) {
|
||||||
|
if (cached.summary === TEARDOWN_MISMATCH) return null;
|
||||||
|
return { ...source, title: `[拆机提炼] ${source.title}`, content: cached.summary };
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const content = await callChat(
|
||||||
|
config,
|
||||||
|
buildTeardownSummaryMessages({
|
||||||
|
brand,
|
||||||
|
model,
|
||||||
|
sourceTitle: source.title,
|
||||||
|
content: source.content,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const summary = content.trim();
|
||||||
|
if (/^机型不符/.test(summary)) {
|
||||||
|
teardownSummaryCache.set(cacheKey, {
|
||||||
|
summary: TEARDOWN_MISMATCH,
|
||||||
|
expires: Date.now() + TEARDOWN_SUMMARY_TTL,
|
||||||
|
});
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (summary.length < 50) return source;
|
||||||
|
teardownSummaryCache.set(cacheKey, {
|
||||||
|
summary,
|
||||||
|
expires: Date.now() + TEARDOWN_SUMMARY_TTL,
|
||||||
|
});
|
||||||
|
return { ...source, title: `[拆机提炼] ${source.title}`, content: summary };
|
||||||
|
} catch {
|
||||||
|
return source;
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
return results.filter((source): source is WebSource => source !== null);
|
||||||
|
}
|
||||||
|
|
||||||
|
const rawFieldSchema = z.object({
|
||||||
|
path: z.string().min(1),
|
||||||
|
value: z.unknown(),
|
||||||
|
confidence: z.string(),
|
||||||
|
sourceUrl: z.string().optional(),
|
||||||
|
sourceUrls: z.array(z.string()).optional(),
|
||||||
|
note: z.string().optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
/** 检索/提示词规则变化时递增,避免继续命中旧规则生成的缓存 */
|
||||||
|
const AI_CACHE_VERSION = 'v7';
|
||||||
|
/** 区块补全单独版本号:只影响区块缓存,不使整机来源复用失效 */
|
||||||
|
const SECTION_CACHE_VERSION = 'v8';
|
||||||
|
/** 来源正文总字符预算:多来源拼接时按数量摊分,避免逼近模型上下文上限(DeepSeek 64K token) */
|
||||||
|
const TOTAL_SOURCE_BUDGET = 54_000;
|
||||||
|
|
||||||
|
/** 来源数量多时压缩单源正文长度;单个来源仍不超过 9000 字符 */
|
||||||
|
function budgetSources<T extends { content: string }>(sources: T[]): T[] {
|
||||||
|
if (sources.length === 0) return sources;
|
||||||
|
const perSource = Math.min(9000, Math.floor(TOTAL_SOURCE_BUDGET / sources.length));
|
||||||
|
if (perSource >= 9000) return sources;
|
||||||
|
return sources.map((source) => ({ ...source, content: source.content.slice(0, perSource) }));
|
||||||
|
}
|
||||||
|
|
||||||
|
function cacheKey(
|
||||||
|
brand: string,
|
||||||
|
model: string,
|
||||||
|
sourceText?: string,
|
||||||
|
sourceUrls?: string[],
|
||||||
|
scope?: SearchScope,
|
||||||
|
): string {
|
||||||
|
const normalize = (value: string) => value.trim().toLowerCase().replace(/\s+/g, ' ');
|
||||||
|
const base = `${AI_CACHE_VERSION}|phone|${normalize(brand)}|${normalize(model)}`;
|
||||||
|
const scopePart = scope && scope !== 'default' ? `|scope:${scope}` : '';
|
||||||
|
const extra = [sourceText ?? '', ...(sourceUrls ?? [])].join('\n');
|
||||||
|
if (!extra.trim()) return `${base}${scopePart}`;
|
||||||
|
const digest = createHash('sha256').update(extra).digest('hex').slice(0, 16);
|
||||||
|
return `${base}${scopePart}|manual:${digest}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function readCache(key: string): AiLookupResult | null {
|
||||||
|
const cached = getAiCache(key);
|
||||||
|
const result = cached?.result as Partial<AiLookupResult> | null | undefined;
|
||||||
|
if (!result || !Array.isArray(result.fields) || result.fields.length === 0) return null;
|
||||||
|
return {
|
||||||
|
fields: result.fields as AiLookupField[],
|
||||||
|
sources: Array.isArray(result.sources) ? (result.sources as string[]) : cached!.sources,
|
||||||
|
cached: true,
|
||||||
|
searchEnabled: Boolean(result.searchEnabled),
|
||||||
|
notice: typeof result.notice === 'string' ? result.notice : undefined,
|
||||||
|
model: typeof result.model === 'string' ? result.model : undefined,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function fieldCacheKey(
|
||||||
|
brand: string,
|
||||||
|
model: string,
|
||||||
|
path: string,
|
||||||
|
sourceText?: string,
|
||||||
|
sourceUrls?: string[],
|
||||||
|
scope?: SearchScope,
|
||||||
|
): string {
|
||||||
|
const normalize = (value: string) => value.trim().toLowerCase().replace(/\s+/g, ' ');
|
||||||
|
const base = `${AI_CACHE_VERSION}|field|${normalize(brand)}|${normalize(model)}|${path}`;
|
||||||
|
const scopePart = scope && scope !== 'default' ? `|scope:${scope}` : '';
|
||||||
|
const extra = [sourceText ?? '', ...(sourceUrls ?? [])].join('\n');
|
||||||
|
if (!extra.trim()) return `${base}${scopePart}`;
|
||||||
|
const digest = createHash('sha256').update(extra).digest('hex').slice(0, 12);
|
||||||
|
return `${base}${scopePart}|manual:${digest}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function sectionCacheKey(
|
||||||
|
brand: string,
|
||||||
|
model: string,
|
||||||
|
section: string,
|
||||||
|
sourceText?: string,
|
||||||
|
sourceUrls?: string[],
|
||||||
|
scope?: SearchScope,
|
||||||
|
): string {
|
||||||
|
const normalize = (value: string) => value.trim().toLowerCase().replace(/\s+/g, ' ');
|
||||||
|
const base = `${SECTION_CACHE_VERSION}|section|${normalize(brand)}|${normalize(model)}|${section}`;
|
||||||
|
const scopePart = scope && scope !== 'default' ? `|scope:${scope}` : '';
|
||||||
|
const extra = [sourceText ?? '', ...(sourceUrls ?? [])].join('\n');
|
||||||
|
if (!extra.trim()) return `${base}${scopePart}`;
|
||||||
|
const digest = createHash('sha256').update(extra).digest('hex').slice(0, 12);
|
||||||
|
return `${base}${scopePart}|manual:${digest}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 读取整机补全缓存里的来源,供字段 / 区块补全复用 */
|
||||||
|
function cachedWholeSourceUrls(brand: string, model: string): string[] {
|
||||||
|
const cached = getAiCache(cacheKey(brand, model));
|
||||||
|
if (!Array.isArray(cached?.sources)) return [];
|
||||||
|
return cached.sources
|
||||||
|
.filter((url): url is string => typeof url === 'string')
|
||||||
|
.filter((url) => !/(\/smartphones?\/?$)|(\/series[^/]*\/?$)|search|topic/.test(url))
|
||||||
|
.slice(0, 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
function readFieldCache(key: string): AiLookupField | null | undefined {
|
||||||
|
const cached = getAiCache(key);
|
||||||
|
const result = cached?.result as { field?: AiLookupField | null } | null | undefined;
|
||||||
|
if (!result || !('field' in result)) return undefined;
|
||||||
|
return result.field ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function aiConfig(): { base: string; key: string; model: string } {
|
||||||
|
const base = (process.env.AI_BASE_URL ?? '').replace(/\/$/, '');
|
||||||
|
const key = process.env.AI_API_KEY ?? '';
|
||||||
|
const model = process.env.AI_MODEL ?? '';
|
||||||
|
const missing = [
|
||||||
|
!base && 'AI_BASE_URL',
|
||||||
|
!key && 'AI_API_KEY',
|
||||||
|
!model && 'AI_MODEL',
|
||||||
|
].filter(Boolean);
|
||||||
|
if (missing.length > 0) {
|
||||||
|
throw new AiNotConfiguredError(`未配置 ${missing.join(' / ')},AI 补全不可用。`);
|
||||||
|
}
|
||||||
|
return { base, key, model };
|
||||||
|
}
|
||||||
|
|
||||||
|
function extractJson(text: string): unknown | null {
|
||||||
|
let candidate = text.trim();
|
||||||
|
candidate = candidate.replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/i, '');
|
||||||
|
const start = candidate.indexOf('{');
|
||||||
|
const end = candidate.lastIndexOf('}');
|
||||||
|
if (start >= 0 && end > start) candidate = candidate.slice(start, end + 1);
|
||||||
|
try {
|
||||||
|
return JSON.parse(candidate) as unknown;
|
||||||
|
} catch {
|
||||||
|
const salvaged = salvageFields(candidate);
|
||||||
|
if (salvaged.length > 0) return { fields: salvaged };
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 输出被 max_tokens 截断时,尽量保留已完整的字段对象 */
|
||||||
|
function salvageFields(text: string): unknown[] {
|
||||||
|
const marker = text.indexOf('"fields"');
|
||||||
|
if (marker < 0) return [];
|
||||||
|
const arrayStart = text.indexOf('[', marker + 8);
|
||||||
|
if (arrayStart < 0) return [];
|
||||||
|
|
||||||
|
const objects: unknown[] = [];
|
||||||
|
let depth = 0;
|
||||||
|
let objectStart = -1;
|
||||||
|
let inString = false;
|
||||||
|
let escaped = false;
|
||||||
|
|
||||||
|
for (let index = arrayStart + 1; index < text.length; index += 1) {
|
||||||
|
const char = text[index];
|
||||||
|
if (inString) {
|
||||||
|
if (escaped) escaped = false;
|
||||||
|
else if (char === '\\') escaped = true;
|
||||||
|
else if (char === '"') inString = false;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (char === '"') {
|
||||||
|
inString = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (char === '{') {
|
||||||
|
if (depth === 0) objectStart = index;
|
||||||
|
depth += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (char === '}') {
|
||||||
|
depth -= 1;
|
||||||
|
if (depth === 0 && objectStart >= 0) {
|
||||||
|
try {
|
||||||
|
objects.push(JSON.parse(text.slice(objectStart, index + 1)) as unknown);
|
||||||
|
} catch {
|
||||||
|
// 丢弃不完整的对象
|
||||||
|
}
|
||||||
|
objectStart = -1;
|
||||||
|
}
|
||||||
|
if (depth < 0) break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return objects;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeUrl(value: string): string {
|
||||||
|
return value.trim().replace(/\/$/, '').replace(/^https?:\/\//i, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 品牌首页 / 系列列表页对参数补全价值低,不占用来源名额 */
|
||||||
|
function isGenericPage(url: string): boolean {
|
||||||
|
try {
|
||||||
|
const path = new URL(url).pathname.toLowerCase();
|
||||||
|
return /\/(smartphones?|series[^/]*)\/?$/.test(path);
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 部分品牌官网域名与品牌名不同,补全 officialUrl 时需要额外匹配 */
|
||||||
|
const OFFICIAL_HOST_ALIASES: Record<string, string[]> = {
|
||||||
|
xiaomi: ['mi.com'],
|
||||||
|
redmi: ['mi.com'],
|
||||||
|
poco: ['mi.com'],
|
||||||
|
apple: ['apple.com'],
|
||||||
|
iphone: ['apple.com'],
|
||||||
|
iqoo: ['iqoo.com', 'vivo.com.cn'],
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从已抓取来源里挑具体产品页作为官网地址:
|
||||||
|
* 官方域名 + 路径含型号优先,排除品牌首页 / 系列列表 / 搜索页。
|
||||||
|
*/
|
||||||
|
function pickOfficialUrl(
|
||||||
|
sources: { url: string }[],
|
||||||
|
brand: string,
|
||||||
|
model: string,
|
||||||
|
): string | undefined {
|
||||||
|
const brandKey = brand.toLowerCase().replace(/[^a-z0-9]/g, '');
|
||||||
|
const aliases = OFFICIAL_HOST_ALIASES[brandKey] ?? [];
|
||||||
|
const tokens = model
|
||||||
|
.toLowerCase()
|
||||||
|
.split(/[^a-z0-9]+/)
|
||||||
|
.filter((token) => token.length >= 2);
|
||||||
|
|
||||||
|
let best: { url: string; score: number } | undefined;
|
||||||
|
for (const source of sources) {
|
||||||
|
let path = '';
|
||||||
|
try {
|
||||||
|
path = new URL(source.url).pathname.toLowerCase();
|
||||||
|
} catch {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const host = (() => {
|
||||||
|
try {
|
||||||
|
return new URL(source.url).hostname.toLowerCase();
|
||||||
|
} catch {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
|
||||||
|
let score = 0;
|
||||||
|
if (aliases.some((domain) => host === domain || host.endsWith(`.${domain}`))) score += 4;
|
||||||
|
else if (brandKey && host.replace(/\./g, '').includes(brandKey)) score += 4;
|
||||||
|
if (tokens.some((token) => path.includes(token))) score += 3;
|
||||||
|
if (/spec|param|_detail/.test(path)) score += 1;
|
||||||
|
if (/(\/smartphones?\/?$)|(\/series[^/]*\/?$)|search|topic/.test(path)) score -= 3;
|
||||||
|
|
||||||
|
const candidateScore = score;
|
||||||
|
if (!best || candidateScore > best.score) best = { url: source.url, score: candidateScore };
|
||||||
|
}
|
||||||
|
|
||||||
|
return best && best.score >= 4 ? best.url : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 手动补充链接与检索结果可能重复,合并时按 URL 去重,避免提示词里堆同一页 */
|
||||||
|
function dedupeSources<T extends { url: string }>(sources: T[]): T[] {
|
||||||
|
const seen = new Set<string>();
|
||||||
|
const unique: T[] = [];
|
||||||
|
for (const source of sources) {
|
||||||
|
const key = normalizeUrl(source.url);
|
||||||
|
if (seen.has(key)) continue;
|
||||||
|
seen.add(key);
|
||||||
|
unique.push(source);
|
||||||
|
}
|
||||||
|
return unique;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeSourceUrl(
|
||||||
|
raw: string | undefined,
|
||||||
|
allowedSources: Set<string>,
|
||||||
|
): string | undefined {
|
||||||
|
if (!raw) return undefined;
|
||||||
|
try {
|
||||||
|
const url = new URL(raw);
|
||||||
|
if (url.protocol !== 'http:' && url.protocol !== 'https:') return undefined;
|
||||||
|
} catch {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
return allowedSources.has(normalizeUrl(raw)) ? raw : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeSourceUrls(
|
||||||
|
raw: string[] | undefined,
|
||||||
|
allowedSources: Set<string>,
|
||||||
|
): string[] {
|
||||||
|
const seen = new Set<string>();
|
||||||
|
const urls: string[] = [];
|
||||||
|
for (const value of raw ?? []) {
|
||||||
|
const url = normalizeSourceUrl(value, allowedSources);
|
||||||
|
if (!url) continue;
|
||||||
|
const key = normalizeUrl(url);
|
||||||
|
if (seen.has(key)) continue;
|
||||||
|
seen.add(key);
|
||||||
|
urls.push(url);
|
||||||
|
}
|
||||||
|
return urls.slice(0, 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
function coerceValue(
|
||||||
|
value: unknown,
|
||||||
|
kind: string,
|
||||||
|
allowedValues?: readonly string[],
|
||||||
|
): AiFieldValue | null {
|
||||||
|
if (kind === 'bool') {
|
||||||
|
if (typeof value === 'boolean') return value;
|
||||||
|
if (typeof value === 'number' && (value === 0 || value === 1)) return value === 1;
|
||||||
|
if (typeof value === 'string') {
|
||||||
|
const normalized = value.trim().toLowerCase();
|
||||||
|
if (['true', 'yes', '1', '支持', '是'].includes(normalized)) return true;
|
||||||
|
if (['false', 'no', '0', '不支持', '否'].includes(normalized)) return false;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (kind === 'number') {
|
||||||
|
const numeric = typeof value === 'number' ? value : Number(String(value).trim());
|
||||||
|
if (!Number.isFinite(numeric) || numeric < 0) return null;
|
||||||
|
return Math.round(numeric);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (kind === 'list') {
|
||||||
|
if (Array.isArray(value)) {
|
||||||
|
const items = value
|
||||||
|
.filter((item): item is string => typeof item === 'string')
|
||||||
|
.map((item) => item.trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
return items.length > 0 ? items : null;
|
||||||
|
}
|
||||||
|
if (typeof value === 'string') {
|
||||||
|
const items = value
|
||||||
|
.split(/[,,、\n]/)
|
||||||
|
.map((item) => item.trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
return items.length > 0 ? items : null;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (kind === 'position') {
|
||||||
|
if (typeof value !== 'string') return null;
|
||||||
|
const normalized = value.trim().toLowerCase();
|
||||||
|
if (!allowedValues?.includes(normalized)) return null;
|
||||||
|
return normalized;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof value === 'string') {
|
||||||
|
const text = value.trim();
|
||||||
|
return text ? text.slice(0, 300) : null;
|
||||||
|
}
|
||||||
|
if (typeof value === 'number' && Number.isFinite(value)) return String(value);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeFields(
|
||||||
|
rawFields: unknown[],
|
||||||
|
allowedSources: Set<string>,
|
||||||
|
): AiLookupField[] {
|
||||||
|
const map = new Map<string, AiLookupField>();
|
||||||
|
|
||||||
|
for (const raw of rawFields) {
|
||||||
|
const parsed = rawFieldSchema.safeParse(raw);
|
||||||
|
if (!parsed.success) continue;
|
||||||
|
|
||||||
|
const spec = resolveFieldPath(parsed.data.path);
|
||||||
|
if (!spec) continue;
|
||||||
|
|
||||||
|
let value = coerceValue(parsed.data.value, spec.kind, spec.allowedValues);
|
||||||
|
if (value === null) continue;
|
||||||
|
if (parsed.data.path === 'specs.pricing' && Array.isArray(value)) {
|
||||||
|
const cnyOnly = value.filter(
|
||||||
|
(item) => !/(€|£|\$|EUR|USD|GBP|欧元|美元|英镑)/i.test(item),
|
||||||
|
);
|
||||||
|
if (cnyOnly.length === 0) continue;
|
||||||
|
value = cnyOnly;
|
||||||
|
}
|
||||||
|
|
||||||
|
const sourceUrls = normalizeSourceUrls(
|
||||||
|
[parsed.data.sourceUrl, ...(parsed.data.sourceUrls ?? [])].filter(
|
||||||
|
(value): value is string => Boolean(value),
|
||||||
|
),
|
||||||
|
allowedSources,
|
||||||
|
);
|
||||||
|
const sourceUrl = sourceUrls[0];
|
||||||
|
let confidence = parsed.data.confidence.trim().toLowerCase() as Confidence;
|
||||||
|
if (confidence !== 'high' && confidence !== 'medium' && confidence !== 'low') {
|
||||||
|
confidence = 'low';
|
||||||
|
}
|
||||||
|
if (confidence === 'high' && !sourceUrl) confidence = 'medium';
|
||||||
|
|
||||||
|
map.set(parsed.data.path, {
|
||||||
|
path: parsed.data.path,
|
||||||
|
value,
|
||||||
|
confidence,
|
||||||
|
...(sourceUrl ? { sourceUrl } : {}),
|
||||||
|
...(sourceUrls.length > 1 ? { sourceUrls } : {}),
|
||||||
|
...(parsed.data.note ? { note: parsed.data.note.slice(0, 240) } : {}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const order: Record<Confidence, number> = { high: 0, medium: 1, low: 2 };
|
||||||
|
return [...map.values()]
|
||||||
|
.sort((left, right) => order[left.confidence] - order[right.confidence] || left.path.localeCompare(right.path))
|
||||||
|
.slice(0, 200);
|
||||||
|
}
|
||||||
|
|
||||||
|
function fieldsFromPayload(
|
||||||
|
payload: unknown,
|
||||||
|
allowedSources: Set<string>,
|
||||||
|
): AiLookupField[] {
|
||||||
|
const rawFields = Array.isArray(payload)
|
||||||
|
? payload
|
||||||
|
: (payload as { fields?: unknown } | null)?.fields;
|
||||||
|
if (!Array.isArray(rawFields)) return [];
|
||||||
|
return normalizeFields(rawFields, allowedSources);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function callChat(
|
||||||
|
config: { base: string; key: string; model: string },
|
||||||
|
messages: ChatMessage[],
|
||||||
|
): Promise<string> {
|
||||||
|
const response = await fetch(`${config.base}/chat/completions`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'content-type': 'application/json',
|
||||||
|
authorization: `Bearer ${config.key}`,
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
model: config.model,
|
||||||
|
messages,
|
||||||
|
temperature: 0.1,
|
||||||
|
max_tokens: 8192,
|
||||||
|
response_format: { type: 'json_object' },
|
||||||
|
}),
|
||||||
|
signal: AbortSignal.timeout(120_000),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const detail = (await response.text()).slice(0, 300);
|
||||||
|
throw new AiLookupError(`AI 接口返回 ${response.status}:${detail}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = (await response.json()) as {
|
||||||
|
choices?: { message?: { content?: string | { text?: string }[] } }[];
|
||||||
|
};
|
||||||
|
const content = data.choices?.[0]?.message?.content;
|
||||||
|
if (typeof content === 'string' && content.trim()) return content;
|
||||||
|
if (Array.isArray(content)) {
|
||||||
|
const merged = content.map((part) => part?.text ?? '').join('');
|
||||||
|
if (merged.trim()) return merged;
|
||||||
|
}
|
||||||
|
throw new AiLookupError('AI 返回内容为空');
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function lookupPhoneSpecs(input: LookupInput): Promise<AiLookupResult> {
|
||||||
|
const sourceText = input.sourceText?.trim().slice(0, 30_000);
|
||||||
|
const manualUrls = [
|
||||||
|
...(input.sourceUrls ?? []),
|
||||||
|
...(input.sourceUrl ? [input.sourceUrl] : []),
|
||||||
|
];
|
||||||
|
const key = cacheKey(input.brand, input.model, sourceText, manualUrls, input.searchScope);
|
||||||
|
if (!input.force) {
|
||||||
|
const cached = readCache(key);
|
||||||
|
if (cached) return cached;
|
||||||
|
}
|
||||||
|
|
||||||
|
const config = aiConfig();
|
||||||
|
const search = await searchSpecs(input.brand, input.model, input.searchScope);
|
||||||
|
const manualSources = await fetchManualSources(manualUrls);
|
||||||
|
const merged = dedupeSources([...manualSources, ...search.sources]).filter(
|
||||||
|
(source) => !isGenericPage(source.url),
|
||||||
|
);
|
||||||
|
// 拆机视频字幕先提炼成参数清单,再进入补全提示词
|
||||||
|
const sources = await condenseTeardownSources(config, input.brand, input.model, merged);
|
||||||
|
const searchEnabled = search.enabled || manualSources.length > 0;
|
||||||
|
const allowedSources = new Set(sources.map((source) => normalizeUrl(source.url)));
|
||||||
|
|
||||||
|
const messages = buildLookupMessages({
|
||||||
|
brand: input.brand,
|
||||||
|
model: input.model,
|
||||||
|
sources: budgetSources(sources),
|
||||||
|
searchEnabled,
|
||||||
|
manualSourceText: sourceText,
|
||||||
|
});
|
||||||
|
|
||||||
|
const firstContent = await callChat(config, messages);
|
||||||
|
let fields = fieldsFromPayload(extractJson(firstContent), allowedSources);
|
||||||
|
|
||||||
|
if (fields.length === 0) {
|
||||||
|
const repairMessages: ChatMessage[] = [
|
||||||
|
...messages,
|
||||||
|
{ role: 'assistant', content: firstContent.slice(0, 4000) },
|
||||||
|
{
|
||||||
|
role: 'user',
|
||||||
|
content:
|
||||||
|
'上次输出不是合法 JSON,或没有包含任何白名单字段。请严格只返回 JSON 对象 {"fields":[...]},不要 markdown,至少包含一个可用字段。资料未覆盖但属于该机型公开常识的字段也可以输出:confidence=low,note=「模型知识,待核实」。',
|
||||||
|
},
|
||||||
|
];
|
||||||
|
const repaired = await callChat(config, repairMessages);
|
||||||
|
fields = fieldsFromPayload(extractJson(repaired), allowedSources);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (fields.length === 0) {
|
||||||
|
throw new AiLookupError('模型返回内容无法解析,或没有可用字段。');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 拆机视频模式不生成官网地址:来源是视频而非官网页面,挑出来的"官网"没有意义
|
||||||
|
if (input.searchScope !== 'teardown') {
|
||||||
|
const officialUrl = pickOfficialUrl(sources, input.brand, input.model);
|
||||||
|
if (officialUrl) {
|
||||||
|
const index = fields.findIndex((field) => field.path === 'specs.officialUrl');
|
||||||
|
const officialField: AiLookupField = {
|
||||||
|
path: 'specs.officialUrl',
|
||||||
|
value: officialUrl,
|
||||||
|
confidence: 'high' as Confidence,
|
||||||
|
sourceUrl: officialUrl,
|
||||||
|
};
|
||||||
|
if (index >= 0) fields[index] = officialField;
|
||||||
|
else fields.push(officialField);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const notice = [
|
||||||
|
manualSources.length > 0 ? `已抓取 ${manualSources.length} 个补充链接。` : '',
|
||||||
|
sourceText ? '已使用补充文字。' : '',
|
||||||
|
search.notice,
|
||||||
|
]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(' ');
|
||||||
|
|
||||||
|
const result: AiLookupResult = {
|
||||||
|
fields,
|
||||||
|
sources: sources.map((source) => source.url),
|
||||||
|
cached: false,
|
||||||
|
searchEnabled,
|
||||||
|
...(notice ? { notice } : {}),
|
||||||
|
model: config.model,
|
||||||
|
};
|
||||||
|
|
||||||
|
saveAiCache(
|
||||||
|
key,
|
||||||
|
{
|
||||||
|
fields: result.fields,
|
||||||
|
sources: result.sources,
|
||||||
|
searchEnabled: result.searchEnabled,
|
||||||
|
notice: result.notice,
|
||||||
|
model: result.model,
|
||||||
|
},
|
||||||
|
result.sources,
|
||||||
|
);
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FieldLookupInput {
|
||||||
|
brand: string;
|
||||||
|
model: string;
|
||||||
|
path: string;
|
||||||
|
currentValue?: unknown;
|
||||||
|
force?: boolean;
|
||||||
|
sourceText?: string;
|
||||||
|
sourceUrls?: string[];
|
||||||
|
/** 检索范围:源网站 / 全网 / 拆机视频 */
|
||||||
|
searchScope?: SearchScope;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function lookupPhoneField(input: FieldLookupInput): Promise<AiFieldLookupResult> {
|
||||||
|
const spec = resolveFieldPath(input.path);
|
||||||
|
if (!spec) throw new AiLookupError(`不支持字段路径:${input.path}`, 400);
|
||||||
|
|
||||||
|
const sourceText = input.sourceText?.trim().slice(0, 30_000);
|
||||||
|
const key = fieldCacheKey(
|
||||||
|
input.brand,
|
||||||
|
input.model,
|
||||||
|
input.path,
|
||||||
|
sourceText,
|
||||||
|
input.sourceUrls,
|
||||||
|
input.searchScope,
|
||||||
|
);
|
||||||
|
if (!input.force) {
|
||||||
|
const cached = readFieldCache(key);
|
||||||
|
if (cached !== undefined) {
|
||||||
|
return { field: cached, sources: [], notice: '字段缓存命中。' };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const config = aiConfig();
|
||||||
|
const search = await searchFieldSources(
|
||||||
|
input.brand,
|
||||||
|
input.model,
|
||||||
|
spec.label,
|
||||||
|
input.path,
|
||||||
|
input.searchScope,
|
||||||
|
);
|
||||||
|
const manualSources = await fetchManualSources(input.sourceUrls ?? []);
|
||||||
|
// 复用整机补全时已抓到的来源,避免公开检索临时失败导致字段补全拿不到 ZOL / PConline
|
||||||
|
const cachedSources =
|
||||||
|
input.searchScope === 'teardown'
|
||||||
|
? []
|
||||||
|
: await fetchManualSources(cachedWholeSourceUrls(input.brand, input.model));
|
||||||
|
// 按类别限额合并:手动 2 + 缓存 1 + 新检索 3,保证新检索结果不被缓存来源挤占
|
||||||
|
const merged = dedupeSources([
|
||||||
|
...manualSources.slice(0, 2),
|
||||||
|
...cachedSources.slice(0, 1),
|
||||||
|
...search.sources.slice(0, 3),
|
||||||
|
])
|
||||||
|
.filter((source) => !isGenericPage(source.url))
|
||||||
|
.slice(0, 5);
|
||||||
|
// 拆机视频字幕先提炼成参数清单,再进入补全提示词
|
||||||
|
const sources = await condenseTeardownSources(config, input.brand, input.model, merged);
|
||||||
|
const searchEnabled =
|
||||||
|
search.enabled || manualSources.length > 0 || cachedSources.length > 0;
|
||||||
|
const allowedSources = new Set(sources.map((source) => normalizeUrl(source.url)));
|
||||||
|
|
||||||
|
const messages = buildFieldMessages({
|
||||||
|
brand: input.brand,
|
||||||
|
model: input.model,
|
||||||
|
path: input.path,
|
||||||
|
label: spec.label,
|
||||||
|
kind: spec.kind,
|
||||||
|
currentValue: input.currentValue,
|
||||||
|
sources,
|
||||||
|
searchEnabled,
|
||||||
|
manualSourceText: sourceText,
|
||||||
|
});
|
||||||
|
|
||||||
|
const content = await callChat(config, messages);
|
||||||
|
const payload = extractJson(content) as
|
||||||
|
| { found?: boolean; field?: unknown; [key: string]: unknown }
|
||||||
|
| null;
|
||||||
|
|
||||||
|
const notice = [
|
||||||
|
manualSources.length > 0 ? `已抓取 ${manualSources.length} 个补充链接。` : '',
|
||||||
|
cachedSources.length > 0 ? `复用了整机补全的 ${cachedSources.length} 个来源。` : '',
|
||||||
|
search.notice,
|
||||||
|
]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(' ');
|
||||||
|
|
||||||
|
if (!payload) throw new AiLookupError('模型返回内容无法解析,请重试。');
|
||||||
|
|
||||||
|
if (payload.found === false) {
|
||||||
|
return {
|
||||||
|
field: null,
|
||||||
|
sources: sources.map((source) => source.url),
|
||||||
|
notice: notice ? `未找到明确依据;${notice}` : '未找到可靠来源。',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const raw = (payload.field ?? payload) as Record<string, unknown>;
|
||||||
|
const fields = normalizeFields([{ ...raw, path: input.path }], allowedSources);
|
||||||
|
const field = fields[0] ?? null;
|
||||||
|
|
||||||
|
if (!field) {
|
||||||
|
return {
|
||||||
|
field: null,
|
||||||
|
sources: sources.map((source) => source.url),
|
||||||
|
notice: `找到资料但值不符合字段类型;${notice || '请重试或手动填写。'}`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
saveAiCache(
|
||||||
|
key,
|
||||||
|
{ field: field as unknown as Record<string, unknown> },
|
||||||
|
sources.map((source) => source.url),
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
field,
|
||||||
|
sources: sources.map((source) => source.url),
|
||||||
|
...(notice ? { notice } : {}),
|
||||||
|
model: config.model,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SectionLookupInput {
|
||||||
|
brand: string;
|
||||||
|
model: string;
|
||||||
|
section: string;
|
||||||
|
force?: boolean;
|
||||||
|
sourceText?: string;
|
||||||
|
sourceUrls?: string[];
|
||||||
|
/** 检索范围:源网站 / 全网 / 拆机视频 */
|
||||||
|
searchScope?: SearchScope;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 区块级补全:一次检索一个规格分区(如屏幕、内存与存储) */
|
||||||
|
export async function lookupPhoneSection(input: SectionLookupInput): Promise<AiLookupResult> {
|
||||||
|
const section = PHONE_SPEC_SECTIONS.find((item) => item.section === input.section);
|
||||||
|
if (!section) throw new AiLookupError(`不支持的区块:${input.section}`, 400);
|
||||||
|
|
||||||
|
const sourceText = input.sourceText?.trim().slice(0, 30_000);
|
||||||
|
const key = sectionCacheKey(
|
||||||
|
input.brand,
|
||||||
|
input.model,
|
||||||
|
input.section,
|
||||||
|
sourceText,
|
||||||
|
input.sourceUrls,
|
||||||
|
input.searchScope,
|
||||||
|
);
|
||||||
|
if (!input.force) {
|
||||||
|
const cached = readCache(key);
|
||||||
|
if (cached) return cached;
|
||||||
|
}
|
||||||
|
|
||||||
|
const config = aiConfig();
|
||||||
|
const [search, manualSources, cachedSources] = await Promise.all([
|
||||||
|
searchSectionSources(
|
||||||
|
input.brand,
|
||||||
|
input.model,
|
||||||
|
section.section,
|
||||||
|
section.title,
|
||||||
|
input.searchScope,
|
||||||
|
),
|
||||||
|
fetchManualSources(input.sourceUrls ?? []),
|
||||||
|
input.searchScope === 'teardown'
|
||||||
|
? Promise.resolve([])
|
||||||
|
: fetchManualSources(cachedWholeSourceUrls(input.brand, input.model)),
|
||||||
|
]);
|
||||||
|
// 按类别限额合并:手动 2 + 缓存 2 + 新检索 5,再截到区块上限 8
|
||||||
|
const merged = dedupeSources([
|
||||||
|
...manualSources.slice(0, 2),
|
||||||
|
...cachedSources.slice(0, 2),
|
||||||
|
...search.sources.slice(0, 5),
|
||||||
|
])
|
||||||
|
.filter((source) => !isGenericPage(source.url))
|
||||||
|
.slice(0, 8);
|
||||||
|
// 拆机视频字幕先提炼成参数清单,再进入补全提示词
|
||||||
|
const sources = await condenseTeardownSources(config, input.brand, input.model, merged);
|
||||||
|
const searchEnabled =
|
||||||
|
search.enabled || manualSources.length > 0 || cachedSources.length > 0;
|
||||||
|
const allowedSources = new Set(sources.map((source) => normalizeUrl(source.url)));
|
||||||
|
const definitions = section.fields.map((field) => ({
|
||||||
|
path: `specs.${section.section}.${field.key}`,
|
||||||
|
label: field.label,
|
||||||
|
kind: field.kind ?? 'text',
|
||||||
|
}));
|
||||||
|
const allowedPaths = new Set(definitions.map((field) => field.path));
|
||||||
|
|
||||||
|
const messages = buildSectionMessages({
|
||||||
|
brand: input.brand,
|
||||||
|
model: input.model,
|
||||||
|
sectionTitle: section.title,
|
||||||
|
fields: definitions,
|
||||||
|
sources: budgetSources(sources),
|
||||||
|
searchEnabled,
|
||||||
|
manualSourceText: sourceText,
|
||||||
|
});
|
||||||
|
|
||||||
|
const firstContent = await callChat(config, messages);
|
||||||
|
let fields = fieldsFromPayload(extractJson(firstContent), allowedSources).filter((field) =>
|
||||||
|
allowedPaths.has(field.path),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (fields.length === 0) {
|
||||||
|
const repaired = await callChat(config, [
|
||||||
|
...messages,
|
||||||
|
{ role: 'assistant', content: firstContent.slice(0, 4000) },
|
||||||
|
{
|
||||||
|
role: 'user',
|
||||||
|
content:
|
||||||
|
'上次输出不是合法 JSON,或没有包含该区块的字段。请严格只返回 JSON 对象 {"fields":[...]},不要 markdown。资料未覆盖但属于该机型公开常识的字段也请输出:confidence=low,note=「模型知识,待核实」;确实没有把握才省略。',
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
fields = fieldsFromPayload(extractJson(repaired), allowedSources).filter((field) =>
|
||||||
|
allowedPaths.has(field.path),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const notice = [
|
||||||
|
manualSources.length > 0 ? `已抓取 ${manualSources.length} 个补充链接。` : '',
|
||||||
|
cachedSources.length > 0 ? `复用了整机补全的 ${cachedSources.length} 个来源。` : '',
|
||||||
|
search.notice,
|
||||||
|
fields.length === 0 ? '没有找到可用的区块字段。' : '',
|
||||||
|
]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(' ');
|
||||||
|
|
||||||
|
const result: AiLookupResult = {
|
||||||
|
fields,
|
||||||
|
sources: sources.map((source) => source.url),
|
||||||
|
cached: false,
|
||||||
|
searchEnabled,
|
||||||
|
...(notice ? { notice } : {}),
|
||||||
|
model: config.model,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (fields.length > 0) {
|
||||||
|
saveAiCache(
|
||||||
|
key,
|
||||||
|
{
|
||||||
|
fields: result.fields,
|
||||||
|
sources: result.sources,
|
||||||
|
searchEnabled: result.searchEnabled,
|
||||||
|
notice: result.notice,
|
||||||
|
model: result.model,
|
||||||
|
},
|
||||||
|
result.sources,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
@@ -0,0 +1,284 @@
|
|||||||
|
import {
|
||||||
|
CAMERA_FIELDS,
|
||||||
|
CAMERA_POSITIONS,
|
||||||
|
PHONE_SPEC_SECTIONS,
|
||||||
|
PHONE_TOP_LEVEL_FIELDS,
|
||||||
|
SPEAKER_UNIT_FIELDS,
|
||||||
|
SPEAKERS_FIELDS,
|
||||||
|
} from '../spec-fields';
|
||||||
|
import type { WebSource } from './search';
|
||||||
|
|
||||||
|
export interface ChatMessage {
|
||||||
|
role: 'system' | 'user' | 'assistant';
|
||||||
|
content: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
function kindTag(kind?: string): string {
|
||||||
|
switch (kind) {
|
||||||
|
case 'bool':
|
||||||
|
return 'boolean';
|
||||||
|
case 'number':
|
||||||
|
return 'number';
|
||||||
|
case 'list':
|
||||||
|
return 'string[]';
|
||||||
|
default:
|
||||||
|
return 'string';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function allowedScalarPaths(): string[] {
|
||||||
|
const lines: string[] = [];
|
||||||
|
for (const section of PHONE_SPEC_SECTIONS) {
|
||||||
|
for (const field of section.fields) {
|
||||||
|
lines.push(
|
||||||
|
`- specs.${section.section}.${field.key} (${kindTag(field.kind)}) ${section.title} · ${field.label}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const field of SPEAKERS_FIELDS) {
|
||||||
|
lines.push(`- specs.speakers.${field.key} (${kindTag(field.kind)}) 扬声器 · ${field.label}`);
|
||||||
|
}
|
||||||
|
for (const field of PHONE_TOP_LEVEL_FIELDS) {
|
||||||
|
lines.push(`- specs.${field.key} (${kindTag(field.kind)}) 设备补充 · ${field.label}`);
|
||||||
|
}
|
||||||
|
lines.push(
|
||||||
|
`- specs.speakers.units[0..4].{${SPEAKER_UNIT_FIELDS.map((field) => `${field.key}`).join(',')}} (string) 扬声器单元标识/型号/尺寸/功率`,
|
||||||
|
);
|
||||||
|
return lines;
|
||||||
|
}
|
||||||
|
|
||||||
|
function allowedCameraPaths(): string[] {
|
||||||
|
const fields = CAMERA_FIELDS.map(
|
||||||
|
(field) => `${field.key}${field.kind ? `(${kindTag(field.kind)})` : ''}`,
|
||||||
|
);
|
||||||
|
fields.push('position(string)', 'video.modes(string[])');
|
||||||
|
return [
|
||||||
|
`- specs.rearCamera[0..3].{${fields.join(',')}} 后置影像`,
|
||||||
|
`- specs.frontCamera[0..1].{${fields.join(',')}} 前置影像`,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildLookupMessages(input: {
|
||||||
|
brand: string;
|
||||||
|
model: string;
|
||||||
|
sources: WebSource[];
|
||||||
|
searchEnabled: boolean;
|
||||||
|
manualSourceText?: string;
|
||||||
|
}): ChatMessage[] {
|
||||||
|
const { brand, model, sources, searchEnabled, manualSourceText } = input;
|
||||||
|
|
||||||
|
const system = `你是严谨的硬件参数整理助手。你的任务是对比多个公开来源,把资料整理成结构化字段,绝不编造。
|
||||||
|
|
||||||
|
只输出一个 JSON 对象,不要输出 markdown、注释或额外解释。格式:
|
||||||
|
{"fields":[{"path":"specs.display.size","value":"6.36 英寸","confidence":"high","sourceUrls":["https://..."],"note":"官网与 ZOL 一致"}]}
|
||||||
|
|
||||||
|
规则:
|
||||||
|
1. path 只能使用下面允许的路径,同一个 path 只出现一次;不在白名单里的字段一律不要输出。
|
||||||
|
2. value 类型必须符合路径后的标注:string / boolean / number / string[]。
|
||||||
|
3. confidence:
|
||||||
|
- high:官方规格页原文,或至少两个独立来源一致;
|
||||||
|
- medium:单一非官方来源(评测、数据库站)或由多个字段推导;
|
||||||
|
- low:模型推测、来源冲突或没有出处。
|
||||||
|
4. 交叉验证:优先官网;ZOL、PConline、Kalvo、GSMArena 可作为独立来源。来源冲突时采用官网或更新时间更晚的资料,并在 note 写明冲突;来源一致时无需写 note,避免输出过长。
|
||||||
|
5. 在证据允许的范围内尽量覆盖白名单字段:外观、屏幕、平台、内存、影像(逐颗)、振动、扬声器、连接、电池、传感器、系统、售价与跑分都应尝试填写;找不到的字段直接省略,不要填“未知”“未公布”或占位值。
|
||||||
|
6. sourceUrls 必须是资料 URL 列表中的地址;通常只填 1 个代表来源,冲突或关键参数可填 2–3 个;没有资料就不要给 sourceUrls,且 confidence 最高只能给 medium。
|
||||||
|
7. 摄像头位置 position 只能是:${CAMERA_POSITIONS.join(' / ')}。
|
||||||
|
8. 所有文本值使用简体中文(颜色、版本、价格、功能名、材质等);芯片型号、协议、接口、传感器代号等专有名词保留英文原文。
|
||||||
|
9. 目标市场是中国大陆(国行):pricing 只输出人民币价格与国行版本;如果资料只有 EUR / USD / GBP 或海外版本,直接省略 pricing,不要换算或猜测。
|
||||||
|
10. 附加条件写入对应说明字段:如“最高支持 185Hz,仅部分游戏场景生效”写入 specs.display.refreshNote;多扬声器按 specs.speakers.units 逐单元输出,用 label 区分“上 / 下 / 中置 / 低音单元”。
|
||||||
|
11. 不要输出 slug、brand、model、summary、cover、tags 等由人工维护的字段。
|
||||||
|
12. note 必须是单行短文本(不超过 60 字),不得包含换行符或未转义引号。
|
||||||
|
13. officialUrl 只填本次资料中该机型的具体产品页(官网 /specs、ZOL param.shtml、PConline _detail 等);不要填品牌首页、系列列表页或搜索结果页。
|
||||||
|
14. specs.body.colors 填中文营销色名;specs.body.colorHexes 与 colors 顺序一一对应,用 #RRGGBB 表示近似色。依据官方配色描述、产品图或色名语义判断(如“黑暗森林”近黑、“明日星光”银白);无法确定时省略 colorHexes,不要用随机色填充。
|
||||||
|
15. 资料未覆盖、但属于该机型广泛公开的常识信息(如发布会公布的参数),仍应输出:confidence 给 low,note 写「模型知识,待核实」;只有连常识都不确定时才省略。`;
|
||||||
|
|
||||||
|
const whitelist = [...allowedScalarPaths(), ...allowedCameraPaths()].join('\n');
|
||||||
|
|
||||||
|
const sourceBlock = searchEnabled
|
||||||
|
? sources
|
||||||
|
.map(
|
||||||
|
(source, index) =>
|
||||||
|
`[资料 ${index + 1}] ${source.title}\nURL: ${source.url}\n${source.content}`,
|
||||||
|
)
|
||||||
|
.join('\n\n')
|
||||||
|
: '无联网资料。所有字段最高只能给 medium;资料未覆盖但你确信的公开常识可以输出,confidence 给 low,note 写「模型知识,待核实」;确实没有把握才省略。';
|
||||||
|
|
||||||
|
const manualBlock = manualSourceText
|
||||||
|
? `\n\n用户补充资料(优先采信;没有对应 URL 时 confidence 最高 medium):\n${manualSourceText}`
|
||||||
|
: '';
|
||||||
|
|
||||||
|
const user = `请补全以下手机:
|
||||||
|
品牌:${brand}
|
||||||
|
型号:${model}
|
||||||
|
类别:phone
|
||||||
|
目标市场:中国大陆(国行)
|
||||||
|
|
||||||
|
允许的字段路径:
|
||||||
|
${whitelist}
|
||||||
|
|
||||||
|
可用资料:
|
||||||
|
${sourceBlock}${manualBlock}
|
||||||
|
|
||||||
|
请只返回 JSON 对象。`;
|
||||||
|
|
||||||
|
return [
|
||||||
|
{ role: 'system', content: system },
|
||||||
|
{ role: 'user', content: user },
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 区块级补全:只补一个规格分区的字段 */
|
||||||
|
export function buildSectionMessages(input: {
|
||||||
|
brand: string;
|
||||||
|
model: string;
|
||||||
|
sectionTitle: string;
|
||||||
|
fields: { path: string; label: string; kind: string }[];
|
||||||
|
sources: WebSource[];
|
||||||
|
searchEnabled: boolean;
|
||||||
|
manualSourceText?: string;
|
||||||
|
}): ChatMessage[] {
|
||||||
|
const { brand, model, sectionTitle, fields, sources, searchEnabled, manualSourceText } = input;
|
||||||
|
|
||||||
|
const system = `你是硬件参数核查助手。只补全「${sectionTitle}」这一个区块,不要输出其他区块的字段。
|
||||||
|
|
||||||
|
只输出一个 JSON 对象:
|
||||||
|
{"fields":[{"path":"specs.display.vendor","value":"京东方","confidence":"high","sourceUrls":["https://..."],"note":"官网与拆解一致"}]}
|
||||||
|
|
||||||
|
规则:
|
||||||
|
1. path 只能使用下面列出的路径,同一个 path 只出现一次;不在列表中的字段不要输出。
|
||||||
|
2. value 类型必须符合路径后的标注;找不到的字段直接省略,不要填“未知”或占位值。
|
||||||
|
3. confidence:官网或至少两个独立来源一致为 high;单一非官方来源为 medium;冲突或推测为 low。
|
||||||
|
4. 交叉验证:官网、ZOL、PConline、Kalvo、GSMArena、ITHome 等独立来源;冲突时采用官网或更新更晚的资料,并在 note 简短说明。
|
||||||
|
5. sourceUrls 优先从资料 URL 列表中选;列表里没有合适的 URL 时不要编造,直接省略 sourceUrls,confidence 最高 medium。资料来自全网自由检索(除官方站外还包含评测、百科、媒体、论坛等),信息在资料中有明确依据即可采信。
|
||||||
|
6. 文本值使用简体中文(芯片、协议、接口、传感器代号保留英文原文);目标是国行版本,海外价格不要输出。
|
||||||
|
7. 区块内可推导的字段可以一并输出,例如由分辨率与尺寸推导像素密度,但要在 note 说明。
|
||||||
|
8. specs.body.colorHexes 与 specs.body.colors 顺序一一对应,用 #RRGGBB 近似色;依据官方配色描述、产品图或色名语义判断(如“黑暗森林”近黑、“明日星光”银白),不确定时省略。
|
||||||
|
9. note 只写冲突或必要补充,单行短文本(不超过 60 字)。
|
||||||
|
10. 资料没有直接写出的公开信息可以给 medium,并在 note 写“模型知识,待核实”;具体型号 / 代号无法确认时省略,不要编造。`;
|
||||||
|
|
||||||
|
const whitelist = fields
|
||||||
|
.map((field) => `${field.path} (${field.kind}) — ${field.label}`)
|
||||||
|
.join('\n');
|
||||||
|
|
||||||
|
const sourceBlock = searchEnabled
|
||||||
|
? sources
|
||||||
|
.map(
|
||||||
|
(source, index) =>
|
||||||
|
`[资料 ${index + 1}] ${source.title}\nURL: ${source.url}\n${source.content}`,
|
||||||
|
)
|
||||||
|
.join('\n\n')
|
||||||
|
: '无联网资料。所有字段最高只能给 medium;资料未覆盖但你确信的公开常识可以输出,confidence 给 low,note 写「模型知识,待核实」;确实没有把握才省略。';
|
||||||
|
|
||||||
|
const manualBlock = manualSourceText
|
||||||
|
? `\n\n用户补充资料(优先采信;没有对应 URL 时 confidence 最高 medium):\n${manualSourceText}`
|
||||||
|
: '';
|
||||||
|
|
||||||
|
const user = `请补全「${sectionTitle}」区块:
|
||||||
|
品牌:${brand}
|
||||||
|
型号:${model}
|
||||||
|
目标市场:中国大陆(国行)
|
||||||
|
|
||||||
|
允许的字段路径:
|
||||||
|
${whitelist}
|
||||||
|
|
||||||
|
可用资料:
|
||||||
|
${sourceBlock}${manualBlock}
|
||||||
|
|
||||||
|
请只返回 JSON 对象。`;
|
||||||
|
|
||||||
|
return [
|
||||||
|
{ role: 'system', content: system },
|
||||||
|
{ role: 'user', content: user },
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 拆机视频字幕提炼:把口语化字幕浓缩成结构化参数清单,供补全提示词复用 */
|
||||||
|
export function buildTeardownSummaryMessages(input: {
|
||||||
|
brand: string;
|
||||||
|
model: string;
|
||||||
|
sourceTitle: string;
|
||||||
|
content: string;
|
||||||
|
}): ChatMessage[] {
|
||||||
|
const { brand, model, sourceTitle, content } = input;
|
||||||
|
|
||||||
|
const system = `你是拆机内容整理助手。下面是「${brand} ${model}」一个拆机视频的字幕(可能含部分官网/简介文字)。请把字幕中提到的所有硬件事实提炼成参数清单,供后续参数整理使用。
|
||||||
|
|
||||||
|
第一步先核对机型:如果标题或字幕明确表明视频讲的是其他机型(上一代、Pro/Ultra 版本差异、其他品牌),第一行只输出「机型不符:<视频实际讲的机型>」,不要再输出任何参数。
|
||||||
|
机型相符时,输出要求(纯文本,不要 JSON,不要 markdown 标题符号):
|
||||||
|
- 每行一条「参数名:值」,例如:马达型号:瑞声0809 X轴线性马达 / 扬声器单元:上扬声器 AAC 1115A,0.8cc 后腔 / 电池:6100mAh 硅碳负极
|
||||||
|
- 覆盖:马达、扬声器(逐单元:型号/尺寸/后腔)、电池(容量/硅碳比例)、屏幕(面板厂商/发光材料)、影像(传感器型号/底片大小)、散热(VC 均热板面积)、指纹方案、NFC/红外、防水等级等字幕里出现的一切硬件细节
|
||||||
|
- 只写视频里明确说出的内容;推测或没听清的不要写;视频里没有的方面直接跳过
|
||||||
|
- 数值和型号保留原文,不要换算或意译`;
|
||||||
|
|
||||||
|
const user = `视频标题:${sourceTitle}
|
||||||
|
|
||||||
|
字幕内容:
|
||||||
|
${content}`;
|
||||||
|
|
||||||
|
return [
|
||||||
|
{ role: 'system', content: system },
|
||||||
|
{ role: 'user', content: user },
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 单字段补全:只查一个字段,允许更细的拆解/评测来源 */
|
||||||
|
export function buildFieldMessages(input: {
|
||||||
|
brand: string;
|
||||||
|
model: string;
|
||||||
|
path: string;
|
||||||
|
label: string;
|
||||||
|
kind: string;
|
||||||
|
currentValue?: unknown;
|
||||||
|
sources: WebSource[];
|
||||||
|
searchEnabled: boolean;
|
||||||
|
manualSourceText?: string;
|
||||||
|
}): ChatMessage[] {
|
||||||
|
const { brand, model, path, label, kind, currentValue, sources, searchEnabled, manualSourceText } =
|
||||||
|
input;
|
||||||
|
|
||||||
|
const system = `你是硬件参数核查助手。只补全一个字段,不要扩展到其他字段。
|
||||||
|
|
||||||
|
只输出一个 JSON 对象:
|
||||||
|
{"found":true,"value":"型号或参数值","confidence":"high","sourceUrls":["https://..."],"note":"官网与拆解一致"}
|
||||||
|
|
||||||
|
规则:
|
||||||
|
1. found=false 表示资料没有明确依据;不要猜测,不要编造。
|
||||||
|
2. value 类型:${kind}。
|
||||||
|
3. confidence:官网或至少两个独立来源一致为 high;单一非官方来源为 medium;冲突/推测为 low。
|
||||||
|
4. sourceUrls 优先从资料 URL 列表中选 1 个代表来源,冲突或关键参数可填 2–3 个;列表里没有合适的 URL 时不要编造,直接省略 sourceUrls,confidence 最高 medium。
|
||||||
|
5. 资料来自全网自由检索(除官方站外还包含评测、百科、媒体、论坛等):只要信息在资料中有明确依据即可采信,不要求必须来自白名单大站;两个独立来源一致可给 high,单一非官方来源给 medium。
|
||||||
|
6. 优先硬参数(型号、尺寸、体积、材质、协议),不要把营销话术当参数。
|
||||||
|
7. 如果该字段是列表,value 用字符串数组;如果是布尔值,用 true / false。
|
||||||
|
8. 目标市场中国大陆(国行):文本值用简体中文;价格字段只接受人民币,海外价格直接 found=false。
|
||||||
|
9. note 只写冲突或必要补充,单行短文本(不超过 60 字),一致时省略。
|
||||||
|
10. 资料没有直接写出的公开信息可以给 medium,并在 note 写“模型知识,待核实”;具体型号 / 代号无法确认时省略,不要编造。
|
||||||
|
11. 资料未覆盖、但属于该机型广泛公开的常识信息(如发布会公布的参数、知名拆解报告的结论),必须输出:confidence 给 low,note 写「模型知识,待核实」;只有确实没有把握才 found=false。`;
|
||||||
|
|
||||||
|
const sourceBlock = searchEnabled
|
||||||
|
? sources
|
||||||
|
.map(
|
||||||
|
(source, index) =>
|
||||||
|
`[资料 ${index + 1}] ${source.title}\nURL: ${source.url}\n${source.content}`,
|
||||||
|
)
|
||||||
|
.join('\n\n')
|
||||||
|
: '无联网资料。若这是你确信的公开常识,仍要输出 value:confidence=low,note=「模型知识,待核实」;确实不知道才 found=false,不要轻易放弃。';
|
||||||
|
|
||||||
|
const manualBlock = manualSourceText
|
||||||
|
? `\n\n用户补充资料(优先采信;没有对应 URL 时 confidence 最高 medium):\n${manualSourceText}`
|
||||||
|
: '';
|
||||||
|
|
||||||
|
const user = `设备:${brand} ${model}
|
||||||
|
字段路径:${path}
|
||||||
|
字段名称:${label}
|
||||||
|
当前值:${currentValue === undefined ? '(空)' : JSON.stringify(currentValue)}
|
||||||
|
|
||||||
|
可用资料:
|
||||||
|
${sourceBlock}${manualBlock}
|
||||||
|
|
||||||
|
请只返回 JSON 对象。`;
|
||||||
|
|
||||||
|
return [
|
||||||
|
{ role: 'system', content: system },
|
||||||
|
{ role: 'user', content: user },
|
||||||
|
];
|
||||||
|
}
|
||||||
@@ -0,0 +1,278 @@
|
|||||||
|
import type { PhoneDevice } from '../schema';
|
||||||
|
import type { Confidence, FieldMeta } from '../schema/meta';
|
||||||
|
import { getValueAtPath, hasValueAtPath } from '../spec-fields';
|
||||||
|
import type { AiLookupField } from './types';
|
||||||
|
|
||||||
|
/** low 置信度且未核实、但表单里确实有值的字段:保存前必须处理 */
|
||||||
|
export function unverifiedLowFields(entity: { meta: FieldMeta[] }): FieldMeta[] {
|
||||||
|
return entity.meta.filter(
|
||||||
|
(item) => item.confidence === 'low' && !item.verified && hasValueAtPath(entity, item.path),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const CONFIDENCE_RANK: Record<Confidence, number> = { high: 3, medium: 2, low: 1 };
|
||||||
|
|
||||||
|
const PLACEHOLDER_PATTERN =
|
||||||
|
/^(?:-+|—|–|未知|不详|暂无|暂无数据|无数据|待补充|待定|n\/a|na|null|undefined|其他|无)$/i;
|
||||||
|
|
||||||
|
/** 去掉空格、全角符号、单位写法和营销修饰后再比较,避免「6.83 英寸」和「6.83英寸」被当成冲突 */
|
||||||
|
export function normalizeAiValue(value: unknown): string {
|
||||||
|
if (value === undefined || value === null) return '';
|
||||||
|
if (typeof value === 'boolean') return value ? 'true' : 'false';
|
||||||
|
if (typeof value === 'number') return String(value);
|
||||||
|
|
||||||
|
let text = String(value)
|
||||||
|
.normalize('NFKC')
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/ |\u00a0/g, ' ')
|
||||||
|
.replace(/<[^>]+>/g, '')
|
||||||
|
.replace(/([^)]*)/g, '')
|
||||||
|
.replace(/\([^)]*\)/g, '')
|
||||||
|
.replace(/[×✕]/g, 'x')
|
||||||
|
.replace(/(\d+(?:\.\d+)?)亿像素/g, (_, number) => `${Number(number) * 100}mp`)
|
||||||
|
.replace(/(\d+(?:\.\d+)?)万像素/g, (_, number) => `${Number(number) / 100}mp`)
|
||||||
|
.replace(/毫米/g, 'mm')
|
||||||
|
.replace(/厘米/g, 'cm')
|
||||||
|
.replace(/微米|μm|um/g, 'um')
|
||||||
|
.replace(/英寸|吋/g, 'in')
|
||||||
|
.replace(/尼特|nits?/g, 'nit')
|
||||||
|
.replace(/毫安时?/g, 'mah')
|
||||||
|
.replace(/克/g, 'g')
|
||||||
|
.replace(/瓦/g, 'w')
|
||||||
|
.replace(/线性马达/g, '马达')
|
||||||
|
.replace(/双扬声器/g, '2扬声器')
|
||||||
|
.replace(/单扬声器/g, '1扬声器')
|
||||||
|
.replace(/usb\s*type-?c/g, 'usbc')
|
||||||
|
.replace(/type-?c/g, 'usbc')
|
||||||
|
.replace(/usb-?c/g, 'usbc')
|
||||||
|
.replace(/wi-?fi/g, 'wifi')
|
||||||
|
.replace(/^支持(?:最高|最大)?/, '')
|
||||||
|
.replace(/^(?:配备|采用|搭载|内置)/, '')
|
||||||
|
.replace(/约/g, '')
|
||||||
|
.replace(/["'“”‘’]/g, '')
|
||||||
|
.replace(/[\s,,、;;·•]/g, '')
|
||||||
|
.replace(/[。.!!??]+$/g, '');
|
||||||
|
|
||||||
|
text = text.trim();
|
||||||
|
return PLACEHOLDER_PATTERN.test(text) ? '' : text;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeList(value: unknown): string[] {
|
||||||
|
const items = Array.isArray(value) ? value : [value];
|
||||||
|
return items
|
||||||
|
.flatMap((item) => String(item ?? '').split(/[,,、;;||]/))
|
||||||
|
.map((item) => normalizeAiValue(item))
|
||||||
|
.filter(Boolean)
|
||||||
|
.sort();
|
||||||
|
}
|
||||||
|
|
||||||
|
function numericTokens(value: unknown): string[] {
|
||||||
|
return String(value ?? '').match(/\d+(?:\.\d+)?/g) ?? [];
|
||||||
|
}
|
||||||
|
|
||||||
|
function comparableNumbers(value: unknown): string {
|
||||||
|
return numericTokens(value).join('|');
|
||||||
|
}
|
||||||
|
|
||||||
|
function stripUnitWords(value: unknown): string {
|
||||||
|
return normalizeAiValue(value).replace(
|
||||||
|
/gb|tb|mhz|ghz|hz|mah|nit|ppi|gbps|mbps|mm|cm|nm|um|mp|in|w|g|fps/g,
|
||||||
|
'',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function toBooleanLike(value: unknown): boolean | undefined {
|
||||||
|
if (typeof value === 'boolean') return value;
|
||||||
|
const text = normalizeAiValue(value);
|
||||||
|
if (/^(?:支持|是|有|true|yes)$/.test(text)) return true;
|
||||||
|
if (/^(?:不支持|否|没有|false|no)$/.test(text)) return false;
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 当前值与 AI 值是否表达同一件事(顺序、空格、单位写法差异都视为一致) */
|
||||||
|
export function aiValuesEquivalent(current: unknown, incoming: unknown): boolean {
|
||||||
|
if (Array.isArray(current) || Array.isArray(incoming)) {
|
||||||
|
const left = normalizeList(current);
|
||||||
|
const right = normalizeList(incoming);
|
||||||
|
return left.length > 0 && left.length === right.length && left.every((item, index) => item === right[index]);
|
||||||
|
}
|
||||||
|
|
||||||
|
const leftBoolean = toBooleanLike(current);
|
||||||
|
const rightBoolean = toBooleanLike(incoming);
|
||||||
|
if (leftBoolean !== undefined && rightBoolean !== undefined) return leftBoolean === rightBoolean;
|
||||||
|
|
||||||
|
const left = normalizeAiValue(current);
|
||||||
|
const right = normalizeAiValue(incoming);
|
||||||
|
if (!left || !right) return false;
|
||||||
|
if (left === right) return true;
|
||||||
|
|
||||||
|
// 「120」和「120Hz」「234.5」和「234.5g」这类只差单位省略的写法
|
||||||
|
const leftNumbers = comparableNumbers(current);
|
||||||
|
const rightNumbers = comparableNumbers(incoming);
|
||||||
|
if (leftNumbers && leftNumbers === rightNumbers) {
|
||||||
|
return stripUnitWords(current) === stripUnitWords(incoming);
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 当前值已经完整包含 AI 值:属于「信息更少」的重复项,直接忽略,避免列表噪音 */
|
||||||
|
function isRedundantReply(current: unknown, incoming: unknown): boolean {
|
||||||
|
if (Array.isArray(current) || Array.isArray(incoming)) {
|
||||||
|
const currentList = normalizeList(current);
|
||||||
|
const incomingList = normalizeList(incoming);
|
||||||
|
return (
|
||||||
|
incomingList.length > 0 &&
|
||||||
|
incomingList.length < currentList.length &&
|
||||||
|
incomingList.every((item) => currentList.includes(item))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (typeof current !== 'string' || typeof incoming !== 'string') return false;
|
||||||
|
|
||||||
|
const loose = (value: string) =>
|
||||||
|
value.normalize('NFKC').replace(/\u00a0/g, ' ').replace(/\s+/g, ' ').trim();
|
||||||
|
const whole = loose(current);
|
||||||
|
const part = loose(incoming);
|
||||||
|
// 末尾是数字时容易把 UFS4 当成 UFS4.1 的子串,交给信息量规则处理
|
||||||
|
if (!part || /\d$/.test(part)) return false;
|
||||||
|
|
||||||
|
const index = whole.indexOf(part);
|
||||||
|
if (index < 0) return false;
|
||||||
|
const isBoundary = (char: string | undefined) =>
|
||||||
|
!char || /[\s,,、;;/·|()()<>]/.test(char);
|
||||||
|
return isBoundary(whole[index - 1]) && isBoundary(whole[index + part.length]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isBlankValue(value: unknown): boolean {
|
||||||
|
if (value === undefined || value === null) return true;
|
||||||
|
if (typeof value === 'string') return normalizeAiValue(value) === '';
|
||||||
|
if (Array.isArray(value)) return value.every((item) => isBlankValue(item));
|
||||||
|
if (typeof value === 'object') return Object.keys(value).length === 0;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 粗略的信息量评分:数字、单位越多,信息越具体;营销词会被扣分 */
|
||||||
|
function informationScore(value: unknown): number {
|
||||||
|
if (isBlankValue(value)) return 0;
|
||||||
|
if (Array.isArray(value)) {
|
||||||
|
return value.reduce((total, item) => total + Math.max(1, informationScore(item)), 0) + value.length * 2;
|
||||||
|
}
|
||||||
|
if (typeof value === 'boolean') return 1;
|
||||||
|
|
||||||
|
const text = String(value).trim();
|
||||||
|
const numbers = (text.match(/\d+(?:\.\d+)?/g) ?? []).length;
|
||||||
|
const units = (
|
||||||
|
text.match(/(?:mm|cm|g|克|英寸|寸|hz|nit|nits|mah|w|gb|tb|mp|ppi|gbps|nm|ghz|mhz|fps|核|台|个)/gi) ?? []
|
||||||
|
).length;
|
||||||
|
const vague = (text.match(/大电池|快充|超大|高性能|旗舰|优秀|支持|其他/g) ?? []).length;
|
||||||
|
return numbers * 6 + units * 3 + Math.min(text.length, 100) / 50 - vague * 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
function currentConfidence(device: PhoneDevice, path: string): Confidence {
|
||||||
|
const meta = device.meta.find((item) => item.path === path);
|
||||||
|
const syncedAt = device.specs.coolapk?.syncedAt;
|
||||||
|
// 酷安同步会覆盖字段值;比同步时间更早的字段置信度已经失效,按酷安默认 high 处理
|
||||||
|
if (meta && syncedAt && new Date(meta.capturedAt).getTime() < new Date(syncedAt).getTime()) {
|
||||||
|
return 'high';
|
||||||
|
}
|
||||||
|
if (meta) return meta.confidence;
|
||||||
|
return device.specs.coolapk ? 'high' : 'low';
|
||||||
|
}
|
||||||
|
|
||||||
|
export type AiSuggestionAction = 'fill' | 'replace' | 'lower-info' | 'review';
|
||||||
|
|
||||||
|
export interface AiFieldJudgement {
|
||||||
|
action: AiSuggestionAction;
|
||||||
|
defaultSelected: boolean;
|
||||||
|
reason: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 判断单个 AI 字段与当前库中值的差异,用于决定是否展示、默认是否勾选 */
|
||||||
|
export function judgeAiField(device: PhoneDevice, field: AiLookupField): AiFieldJudgement | null {
|
||||||
|
if (isBlankValue(field.value)) return null;
|
||||||
|
|
||||||
|
const current = getValueAtPath(device, field.path);
|
||||||
|
if (isBlankValue(current)) {
|
||||||
|
return { action: 'fill', defaultSelected: true, reason: '数据库为空,默认补全' };
|
||||||
|
}
|
||||||
|
if (aiValuesEquivalent(current, field.value)) return null;
|
||||||
|
if (isRedundantReply(current, field.value)) return null;
|
||||||
|
|
||||||
|
const oldScore = informationScore(current);
|
||||||
|
const newScore = informationScore(field.value);
|
||||||
|
const oldConfidence = currentConfidence(device, field.path);
|
||||||
|
const meta = device.meta.find((item) => item.path === field.path);
|
||||||
|
|
||||||
|
if (meta?.verified && CONFIDENCE_RANK[field.confidence] <= CONFIDENCE_RANK[oldConfidence]) {
|
||||||
|
return { action: 'review', defaultSelected: false, reason: '现有值已核实,默认不覆盖' };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (newScore < oldScore) {
|
||||||
|
if (CONFIDENCE_RANK[field.confidence] > CONFIDENCE_RANK[oldConfidence]) {
|
||||||
|
return { action: 'replace', defaultSelected: true, reason: '信息量较少,但置信度更高' };
|
||||||
|
}
|
||||||
|
return { action: 'lower-info', defaultSelected: false, reason: '信息量少于当前值,默认不勾选' };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (CONFIDENCE_RANK[field.confidence] < CONFIDENCE_RANK[oldConfidence]) {
|
||||||
|
return { action: 'review', defaultSelected: false, reason: '置信度低于当前值,需人工确认' };
|
||||||
|
}
|
||||||
|
|
||||||
|
return { action: 'replace', defaultSelected: true, reason: '信息更新' };
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PreparedAiFields {
|
||||||
|
fields: AiLookupField[];
|
||||||
|
selected: Record<string, boolean>;
|
||||||
|
ignored: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 过滤 AI 结果:去掉空值、占位符、与当前一致的字段、重复字段;
|
||||||
|
* 按「补空 → 替换 → 需人工确认」排序,并给出默认勾选状态。
|
||||||
|
*/
|
||||||
|
export function prepareAiFields(device: PhoneDevice, fields: AiLookupField[]): PreparedAiFields {
|
||||||
|
const bestByPath = new Map<string, AiLookupField>();
|
||||||
|
for (const field of fields) {
|
||||||
|
if (isBlankValue(field.value)) continue;
|
||||||
|
const current = bestByPath.get(field.path);
|
||||||
|
if (!current) {
|
||||||
|
bestByPath.set(field.path, field);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const currentRank = CONFIDENCE_RANK[current.confidence];
|
||||||
|
const nextRank = CONFIDENCE_RANK[field.confidence];
|
||||||
|
if (
|
||||||
|
nextRank > currentRank ||
|
||||||
|
(nextRank === currentRank && informationScore(field.value) > informationScore(current.value))
|
||||||
|
) {
|
||||||
|
bestByPath.set(field.path, field);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const judged: { field: AiLookupField; judgement: AiFieldJudgement }[] = [];
|
||||||
|
for (const field of bestByPath.values()) {
|
||||||
|
const judgement = judgeAiField(device, field);
|
||||||
|
if (!judgement) continue;
|
||||||
|
judged.push({ field, judgement });
|
||||||
|
}
|
||||||
|
|
||||||
|
const order: Record<AiSuggestionAction, number> = { fill: 0, replace: 1, 'lower-info': 2, review: 3 };
|
||||||
|
judged.sort(
|
||||||
|
(left, right) =>
|
||||||
|
Number(right.judgement.defaultSelected) - Number(left.judgement.defaultSelected) ||
|
||||||
|
order[left.judgement.action] - order[right.judgement.action] ||
|
||||||
|
left.field.path.localeCompare(right.field.path),
|
||||||
|
);
|
||||||
|
|
||||||
|
const selected: Record<string, boolean> = {};
|
||||||
|
for (const item of judged) {
|
||||||
|
selected[item.field.path] = item.judgement.defaultSelected;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
fields: judged.map((item) => item.field),
|
||||||
|
selected,
|
||||||
|
ignored: fields.length - judged.length,
|
||||||
|
};
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,42 @@
|
|||||||
|
import { z } from 'zod';
|
||||||
|
import { confidenceSchema } from '../schema/meta';
|
||||||
|
|
||||||
|
export const aiFieldValueSchema = z.union([
|
||||||
|
z.string(),
|
||||||
|
z.number(),
|
||||||
|
z.boolean(),
|
||||||
|
z.array(z.string()),
|
||||||
|
]);
|
||||||
|
|
||||||
|
export const aiLookupFieldSchema = z.object({
|
||||||
|
path: z.string().min(1).max(200),
|
||||||
|
value: aiFieldValueSchema,
|
||||||
|
confidence: confidenceSchema,
|
||||||
|
sourceUrl: z.url().optional(),
|
||||||
|
sourceUrls: z.array(z.url()).max(3).optional(),
|
||||||
|
note: z.string().max(240).optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const aiLookupPayloadSchema = z.object({
|
||||||
|
fields: z.array(aiLookupFieldSchema).min(1),
|
||||||
|
sources: z.array(z.url()).default([]),
|
||||||
|
});
|
||||||
|
|
||||||
|
export type AiFieldValue = z.infer<typeof aiFieldValueSchema>;
|
||||||
|
export type AiLookupField = z.infer<typeof aiLookupFieldSchema>;
|
||||||
|
|
||||||
|
export interface AiLookupResult {
|
||||||
|
fields: AiLookupField[];
|
||||||
|
sources: string[];
|
||||||
|
cached: boolean;
|
||||||
|
searchEnabled: boolean;
|
||||||
|
notice?: string;
|
||||||
|
model?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AiFieldLookupResult {
|
||||||
|
field: AiLookupField | null;
|
||||||
|
sources: string[];
|
||||||
|
notice?: string;
|
||||||
|
model?: string;
|
||||||
|
}
|
||||||
+155
@@ -0,0 +1,155 @@
|
|||||||
|
import { createHash, timingSafeEqual } from 'node:crypto';
|
||||||
|
import { SignJWT, jwtVerify } from 'jose';
|
||||||
|
import { loadEnv } from './env';
|
||||||
|
|
||||||
|
loadEnv();
|
||||||
|
|
||||||
|
export const SESSION_COOKIE = 'lfs_admin';
|
||||||
|
const SESSION_MAX_AGE = 60 * 60 * 24 * 7;
|
||||||
|
|
||||||
|
/** 只依赖 AstroCookies 的读写方法,避免把 astro 运行时类型带进 lib */
|
||||||
|
interface CookieJar {
|
||||||
|
get(name: string): { value: string } | undefined;
|
||||||
|
set(name: string, value: string, options: Record<string, unknown>): void;
|
||||||
|
delete(name: string, options?: Record<string, unknown>): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function authConfigured(): boolean {
|
||||||
|
return Boolean(process.env.ADMIN_PASSWORD && process.env.SESSION_SECRET);
|
||||||
|
}
|
||||||
|
|
||||||
|
function sessionSecret(): Uint8Array {
|
||||||
|
const secret = process.env.SESSION_SECRET;
|
||||||
|
if (!secret) throw new Error('缺少 SESSION_SECRET');
|
||||||
|
return new TextEncoder().encode(secret);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createSessionToken(): Promise<string> {
|
||||||
|
return new SignJWT({ role: 'admin' })
|
||||||
|
.setProtectedHeader({ alg: 'HS256' })
|
||||||
|
.setIssuedAt()
|
||||||
|
.setExpirationTime('7d')
|
||||||
|
.sign(sessionSecret());
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function verifySessionToken(token: string | undefined): Promise<boolean> {
|
||||||
|
if (!token || !process.env.SESSION_SECRET) return false;
|
||||||
|
try {
|
||||||
|
const { payload } = await jwtVerify(token, sessionSecret(), { algorithms: ['HS256'] });
|
||||||
|
return payload.role === 'admin';
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function isAuthed(cookies: CookieJar): Promise<boolean> {
|
||||||
|
return verifySessionToken(cookies.get(SESSION_COOKIE)?.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function cookieSecure(): boolean {
|
||||||
|
return process.env.COOKIE_SECURE === '1';
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function setSessionCookie(cookies: CookieJar): Promise<void> {
|
||||||
|
cookies.set(SESSION_COOKIE, await createSessionToken(), {
|
||||||
|
httpOnly: true,
|
||||||
|
sameSite: 'lax',
|
||||||
|
path: '/',
|
||||||
|
secure: cookieSecure(),
|
||||||
|
maxAge: SESSION_MAX_AGE,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function clearSessionCookie(cookies: CookieJar): void {
|
||||||
|
cookies.delete(SESSION_COOKIE, { path: '/' });
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 常量时间比较:先做 sha256 再比较,避免密码长度差异导致的时间侧信道。
|
||||||
|
*/
|
||||||
|
export function passwordMatches(input: string): boolean {
|
||||||
|
const expected = process.env.ADMIN_PASSWORD;
|
||||||
|
if (!expected) return false;
|
||||||
|
const left = createHash('sha256').update(input).digest();
|
||||||
|
const right = createHash('sha256').update(expected).digest();
|
||||||
|
return timingSafeEqual(left, right);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ----------------------------- 登录失败限速 ----------------------------- */
|
||||||
|
|
||||||
|
const MAX_ATTEMPTS = 3;
|
||||||
|
const WINDOW_MS = 60_000;
|
||||||
|
const attempts = new Map<string, { count: number; resetAt: number }>();
|
||||||
|
|
||||||
|
export function loginRateLimited(ip: string): boolean {
|
||||||
|
const now = Date.now();
|
||||||
|
const entry = attempts.get(ip);
|
||||||
|
if (!entry || entry.resetAt <= now) {
|
||||||
|
attempts.delete(ip);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return entry.count >= MAX_ATTEMPTS;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function recordLoginFailure(ip: string): void {
|
||||||
|
const now = Date.now();
|
||||||
|
const entry = attempts.get(ip);
|
||||||
|
if (!entry || entry.resetAt <= now) {
|
||||||
|
attempts.set(ip, { count: 1, resetAt: now + WINDOW_MS });
|
||||||
|
} else {
|
||||||
|
entry.count += 1;
|
||||||
|
}
|
||||||
|
// 防止长期运行后 Map 无限增长
|
||||||
|
if (attempts.size > 1000) {
|
||||||
|
for (const [key, value] of attempts) {
|
||||||
|
if (value.resetAt <= now) attempts.delete(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function clearLoginFailures(ip: string): void {
|
||||||
|
attempts.delete(ip);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 限速 / 审计用的客户端标识。
|
||||||
|
* 反代部署(TRUST_PROXY=1)时取 X-Forwarded-For 首段,避免所有访问者共享代理 IP
|
||||||
|
* 的同一个限速桶、被低成本锁死全站登录;仅在确有可信代理时开启,
|
||||||
|
* 否则该头可被伪造从而绕过限速。
|
||||||
|
*/
|
||||||
|
export function clientIp(request: Request, fallback: string | undefined): string {
|
||||||
|
if (process.env.TRUST_PROXY === '1') {
|
||||||
|
const first = request.headers.get('x-forwarded-for')?.split(',')[0]?.trim();
|
||||||
|
if (first) return first;
|
||||||
|
}
|
||||||
|
return fallback || 'unknown';
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------- 写接口守卫 ------------------------------- */
|
||||||
|
|
||||||
|
export function sameOrigin(request: Request): boolean {
|
||||||
|
const origin = request.headers.get('origin');
|
||||||
|
// 非浏览器客户端(curl / 脚本)不一定带 Origin;带上了就必须同源
|
||||||
|
if (!origin) return true;
|
||||||
|
try {
|
||||||
|
// 以 Host / X-Forwarded-Host 为准:反代后 request.url 的 host 可能与浏览器实际访问的域名不同
|
||||||
|
const originHost = new URL(origin).host;
|
||||||
|
const hosts = [request.headers.get('host'), request.headers.get('x-forwarded-host')]
|
||||||
|
.filter((value): value is string => Boolean(value))
|
||||||
|
.map((value) => value.split(',')[0].trim());
|
||||||
|
return hosts.includes(originHost);
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 写接口统一守卫:登录态 + 同源校验。返回 null 表示放行 */
|
||||||
|
export async function guardWrite(request: Request, cookies: CookieJar): Promise<Response | null> {
|
||||||
|
if (!(await isAuthed(cookies))) {
|
||||||
|
return Response.json({ error: '未登录或会话已过期' }, { status: 401 });
|
||||||
|
}
|
||||||
|
if (!sameOrigin(request)) {
|
||||||
|
return Response.json({ error: 'Origin 校验失败' }, { status: 403 });
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
import { randomUUID } from 'node:crypto';
|
||||||
|
import { getSetting, saveSetting, deleteSetting } from './repo';
|
||||||
|
|
||||||
|
export const BILIBILI_SESSDATA_KEY = 'bilibili_sessdata';
|
||||||
|
|
||||||
|
const UA =
|
||||||
|
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36';
|
||||||
|
|
||||||
|
/** 登录态优先级:.env 显式配置 > 后台扫码保存的 SESSDATA */
|
||||||
|
export function getBilibiliSessdata(): string | undefined {
|
||||||
|
return process.env.BILIBILI_SESSDATA?.trim() || getSetting(BILIBILI_SESSDATA_KEY);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ----------------------------- 扫码登录状态 ----------------------------- */
|
||||||
|
|
||||||
|
interface PendingLogin {
|
||||||
|
/** generate 时的会话 cookie(buvid3),poll 时需复用同一会话 */
|
||||||
|
cookie: string;
|
||||||
|
expiresAt: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** qrcode_key → 会话 cookie。单进程内存即可,二维码本身 3 分钟有效 */
|
||||||
|
const pendingLogins = new Map<string, PendingLogin>();
|
||||||
|
|
||||||
|
function sweepPendingLogins(): void {
|
||||||
|
const now = Date.now();
|
||||||
|
if (pendingLogins.size < 50) return;
|
||||||
|
for (const [key, entry] of pendingLogins) {
|
||||||
|
if (entry.expiresAt <= now) pendingLogins.delete(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
interface BilibiliResponse<T> {
|
||||||
|
code: number;
|
||||||
|
data?: T;
|
||||||
|
message?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function bilibiliGet<T>(url: string, cookie?: string): Promise<BilibiliResponse<T>> {
|
||||||
|
const headers: Record<string, string> = { 'user-agent': UA };
|
||||||
|
if (cookie) {
|
||||||
|
headers.cookie = cookie;
|
||||||
|
headers.referer = 'https://www.bilibili.com/';
|
||||||
|
}
|
||||||
|
const response = await fetch(url, { headers, signal: AbortSignal.timeout(15_000) });
|
||||||
|
if (!response.ok) throw new Error(`B 站接口返回 ${response.status}`);
|
||||||
|
return (await response.json()) as BilibiliResponse<T>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 生成扫码登录二维码,返回 { key, imageDataUrl };key 用于后续轮询 */
|
||||||
|
export async function createLoginQRCode(): Promise<{ key: string; imageDataUrl: string }> {
|
||||||
|
const { default: QRCode } = await import('qrcode');
|
||||||
|
const buvid = randomUUID().replace(/-/g, '');
|
||||||
|
const result = await bilibiliGet<{ url?: string; qrcode_key?: string }>(
|
||||||
|
'https://passport.bilibili.com/x/passport-login/web/qrcode/generate',
|
||||||
|
`buvid3=${buvid}`,
|
||||||
|
);
|
||||||
|
const { url, qrcode_key: key } = result.data ?? {};
|
||||||
|
if (result.code !== 0 || !url || !key) {
|
||||||
|
throw new Error(result.message || '获取 B 站登录二维码失败');
|
||||||
|
}
|
||||||
|
sweepPendingLogins();
|
||||||
|
pendingLogins.set(key, { cookie: `buvid3=${buvid}`, expiresAt: Date.now() + 3 * 60_000 });
|
||||||
|
const imageDataUrl = await QRCode.toDataURL(url, { margin: 1, width: 220 });
|
||||||
|
return { key, imageDataUrl };
|
||||||
|
}
|
||||||
|
|
||||||
|
export type QRCodePollStatus = 'waiting' | 'scanned' | 'confirmed' | 'expired';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 轮询扫码结果。confirmed 时从 Set-Cookie 提取 SESSDATA 存入 settings 表,
|
||||||
|
* 之后 AI 补全拉字幕立即生效,无需重启。
|
||||||
|
*/
|
||||||
|
export async function pollLoginQRCode(
|
||||||
|
key: string,
|
||||||
|
): Promise<{ status: QRCodePollStatus; message?: string }> {
|
||||||
|
const pending = pendingLogins.get(key);
|
||||||
|
if (!pending || pending.expiresAt <= Date.now()) {
|
||||||
|
pendingLogins.delete(key);
|
||||||
|
return { status: 'expired', message: '二维码已过期,请重新生成。' };
|
||||||
|
}
|
||||||
|
|
||||||
|
const response = await fetch(
|
||||||
|
`https://passport.bilibili.com/x/passport-login/web/qrcode/poll?qrcode_key=${encodeURIComponent(key)}`,
|
||||||
|
{
|
||||||
|
headers: {
|
||||||
|
'user-agent': UA,
|
||||||
|
referer: 'https://www.bilibili.com/',
|
||||||
|
cookie: pending.cookie,
|
||||||
|
},
|
||||||
|
signal: AbortSignal.timeout(15_000),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if (!response.ok) throw new Error(`B 站接口返回 ${response.status}`);
|
||||||
|
const result = (await response.json()) as BilibiliResponse<{ code?: number; message?: string }>;
|
||||||
|
if (result.code !== 0) throw new Error(result.message || '轮询 B 站登录状态失败');
|
||||||
|
|
||||||
|
switch (result.data?.code) {
|
||||||
|
case 0: {
|
||||||
|
// 登录成功:SESSDATA 在 Set-Cookie 里
|
||||||
|
const cookies = response.headers.getSetCookie?.() ?? [];
|
||||||
|
const sessdata = cookies
|
||||||
|
.map((item) => /^SESSDATA=([^;]+)/.exec(item)?.[1])
|
||||||
|
.find((value): value is string => Boolean(value));
|
||||||
|
if (!sessdata) {
|
||||||
|
return { status: 'expired', message: '登录成功但未取到凭证,请重试。' };
|
||||||
|
}
|
||||||
|
saveSetting(BILIBILI_SESSDATA_KEY, sessdata);
|
||||||
|
saveSetting(`${BILIBILI_SESSDATA_KEY}_saved_at`, new Date().toISOString());
|
||||||
|
pendingLogins.delete(key);
|
||||||
|
return { status: 'confirmed' };
|
||||||
|
}
|
||||||
|
case 86101: // 未扫码
|
||||||
|
case 86090: // 已扫码未确认
|
||||||
|
return {
|
||||||
|
status: result.data.code === 86090 ? 'scanned' : 'waiting',
|
||||||
|
message: result.data.code === 86090 ? '已扫码,请在手机上确认登录。' : undefined,
|
||||||
|
};
|
||||||
|
case 86038:
|
||||||
|
pendingLogins.delete(key);
|
||||||
|
return { status: 'expired', message: '二维码已过期,请重新生成。' };
|
||||||
|
default:
|
||||||
|
return { status: 'waiting' };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function unbindBilibili(): void {
|
||||||
|
deleteSetting(BILIBILI_SESSDATA_KEY);
|
||||||
|
}
|
||||||
@@ -0,0 +1,198 @@
|
|||||||
|
import type { PhoneDevice } from './schema';
|
||||||
|
import {
|
||||||
|
CAMERA_FIELDS,
|
||||||
|
CAMERA_POSITIONS,
|
||||||
|
PHONE_SPEC_SECTIONS,
|
||||||
|
SPEAKERS_FIELDS,
|
||||||
|
getValueAtPath,
|
||||||
|
} from './spec-fields';
|
||||||
|
|
||||||
|
export interface CompareRow {
|
||||||
|
key: string;
|
||||||
|
label: string;
|
||||||
|
values: unknown[];
|
||||||
|
formatted: string[];
|
||||||
|
/** 仅数值型字段有值,用于条形可视化 */
|
||||||
|
numeric: (number | null)[] | null;
|
||||||
|
numericMax: number;
|
||||||
|
different: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CompareGroup {
|
||||||
|
title: string;
|
||||||
|
rows: CompareRow[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CompareResult {
|
||||||
|
groups: CompareGroup[];
|
||||||
|
diffCount: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
const POSITION_LABELS: Record<string, string> = {
|
||||||
|
wide: '主摄',
|
||||||
|
ultrawide: '超广角',
|
||||||
|
tele: '长焦',
|
||||||
|
periscope: '潜望长焦',
|
||||||
|
macro: '微距',
|
||||||
|
depth: '景深',
|
||||||
|
mono: '黑白',
|
||||||
|
front: '前摄',
|
||||||
|
};
|
||||||
|
|
||||||
|
const NUMERIC_PATHS = new Set([
|
||||||
|
'specs.body.weight',
|
||||||
|
'specs.display.size',
|
||||||
|
'specs.display.brightnessTypical',
|
||||||
|
'specs.display.brightnessPeak',
|
||||||
|
'specs.display.refreshRate',
|
||||||
|
'specs.battery.capacity',
|
||||||
|
'specs.battery.wired',
|
||||||
|
'specs.battery.wireless',
|
||||||
|
]);
|
||||||
|
|
||||||
|
function displayValue(value: unknown): string {
|
||||||
|
if (value === undefined || value === null || value === '') return '—';
|
||||||
|
if (typeof value === 'boolean') return value ? '支持' : '不支持';
|
||||||
|
if (Array.isArray(value)) return value.length > 0 ? value.map(String).join(' / ') : '—';
|
||||||
|
if (typeof value === 'object') return JSON.stringify(value);
|
||||||
|
return String(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function toNumeric(value: unknown): number | null {
|
||||||
|
if (typeof value === 'number' && Number.isFinite(value)) return value;
|
||||||
|
if (typeof value !== 'string') return null;
|
||||||
|
const matches = value.match(/\d+(?:\.\d+)?/g);
|
||||||
|
if (!matches || matches.length === 0) return null;
|
||||||
|
return Math.max(...matches.map(Number));
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildRow(
|
||||||
|
key: string,
|
||||||
|
label: string,
|
||||||
|
values: unknown[],
|
||||||
|
numericPath?: string,
|
||||||
|
): CompareRow {
|
||||||
|
const formatted = values.map(displayValue);
|
||||||
|
const numeric =
|
||||||
|
numericPath && NUMERIC_PATHS.has(numericPath) ? values.map(toNumeric) : null;
|
||||||
|
const numericMax = numeric
|
||||||
|
? Math.max(0, ...numeric.filter((value): value is number => value !== null))
|
||||||
|
: 0;
|
||||||
|
return {
|
||||||
|
key,
|
||||||
|
label,
|
||||||
|
values,
|
||||||
|
formatted,
|
||||||
|
numeric,
|
||||||
|
numericMax,
|
||||||
|
different: new Set(formatted).size > 1,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function sectionRows(devices: PhoneDevice[], sectionKey: string): CompareRow[] {
|
||||||
|
const section = PHONE_SPEC_SECTIONS.find((item) => item.section === sectionKey);
|
||||||
|
if (!section) return [];
|
||||||
|
const rows: CompareRow[] = [];
|
||||||
|
for (const field of section.fields) {
|
||||||
|
const path = `specs.${sectionKey}.${field.key}`;
|
||||||
|
const values = devices.map((device) => getValueAtPath(device, path));
|
||||||
|
if (values.every((value) => displayValue(value) === '—')) continue;
|
||||||
|
rows.push(buildRow(path, field.label, values, path));
|
||||||
|
}
|
||||||
|
return rows;
|
||||||
|
}
|
||||||
|
|
||||||
|
function speakerRows(devices: PhoneDevice[]): CompareRow[] {
|
||||||
|
const rows: CompareRow[] = [];
|
||||||
|
for (const field of SPEAKERS_FIELDS) {
|
||||||
|
const path = `specs.speakers.${field.key}`;
|
||||||
|
const values = devices.map((device) => getValueAtPath(device, path));
|
||||||
|
if (values.every((value) => displayValue(value) === '—')) continue;
|
||||||
|
const label = field.key === 'count' ? '扬声器数量' : field.label;
|
||||||
|
rows.push(buildRow(path, label, values, path));
|
||||||
|
}
|
||||||
|
|
||||||
|
const unitValues = devices.map((device) => device.specs.speakers?.units ?? []);
|
||||||
|
const formattedUnits = unitValues.map((units) =>
|
||||||
|
units.length > 0
|
||||||
|
? units
|
||||||
|
.map((unit) => [unit.model, unit.size, unit.power].filter(Boolean).join(' '))
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(' / ')
|
||||||
|
: '—',
|
||||||
|
);
|
||||||
|
if (formattedUnits.some((value) => value !== '—')) {
|
||||||
|
rows.push(buildRow('specs.speakers.units', '扬声器单元', unitValues));
|
||||||
|
}
|
||||||
|
return rows;
|
||||||
|
}
|
||||||
|
|
||||||
|
function rearCameraRows(devices: PhoneDevice[]): CompareRow[] {
|
||||||
|
const positions = CAMERA_POSITIONS.filter((position) =>
|
||||||
|
position !== 'front' &&
|
||||||
|
devices.some((device) =>
|
||||||
|
device.specs.rearCamera.some((camera) => camera.position === position),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
const rows: CompareRow[] = [];
|
||||||
|
for (const position of positions) {
|
||||||
|
const positionLabel = POSITION_LABELS[position] ?? position;
|
||||||
|
for (const field of CAMERA_FIELDS) {
|
||||||
|
const key = `specs.rearCamera.${position}.${field.key}`;
|
||||||
|
const values = devices.map((device) => {
|
||||||
|
const camera = device.specs.rearCamera.find((item) => item.position === position);
|
||||||
|
return camera ? getValueAtPath(camera, field.key) : undefined;
|
||||||
|
});
|
||||||
|
if (values.every((value) => displayValue(value) === '—')) continue;
|
||||||
|
rows.push(buildRow(key, `${positionLabel} · ${field.label}`, values));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return rows;
|
||||||
|
}
|
||||||
|
|
||||||
|
function frontCameraRows(devices: PhoneDevice[]): CompareRow[] {
|
||||||
|
const rows: CompareRow[] = [];
|
||||||
|
for (const field of CAMERA_FIELDS) {
|
||||||
|
const key = `specs.frontCamera.front.${field.key}`;
|
||||||
|
const values = devices.map((device) =>
|
||||||
|
device.specs.frontCamera[0]
|
||||||
|
? getValueAtPath(device.specs.frontCamera[0], field.key)
|
||||||
|
: undefined,
|
||||||
|
);
|
||||||
|
if (values.every((value) => displayValue(value) === '—')) continue;
|
||||||
|
rows.push(buildRow(key, `前置 · ${field.label}`, values));
|
||||||
|
}
|
||||||
|
return rows;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildComparison(devices: PhoneDevice[]): CompareResult {
|
||||||
|
const groups: CompareGroup[] = [
|
||||||
|
{ title: '外观', rows: sectionRows(devices, 'body') },
|
||||||
|
{ title: '屏幕', rows: sectionRows(devices, 'display') },
|
||||||
|
{
|
||||||
|
title: '平台与存储',
|
||||||
|
rows: [...sectionRows(devices, 'platform'), ...sectionRows(devices, 'memory')],
|
||||||
|
},
|
||||||
|
{ title: '后置影像', rows: rearCameraRows(devices) },
|
||||||
|
{ title: '前置影像', rows: frontCameraRows(devices) },
|
||||||
|
{
|
||||||
|
title: '振动',
|
||||||
|
rows: sectionRows(devices, 'vibration'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '扬声器',
|
||||||
|
rows: speakerRows(devices),
|
||||||
|
},
|
||||||
|
{ title: '连接', rows: sectionRows(devices, 'connectivity') },
|
||||||
|
{ title: '电池与充电', rows: sectionRows(devices, 'battery') },
|
||||||
|
{ title: '传感器', rows: sectionRows(devices, 'sensors') },
|
||||||
|
{ title: '系统与更新', rows: sectionRows(devices, 'software') },
|
||||||
|
].filter((group) => group.rows.length > 0);
|
||||||
|
|
||||||
|
const allRows = groups.flatMap((group) => group.rows);
|
||||||
|
return {
|
||||||
|
groups,
|
||||||
|
diffCount: allRows.filter((row) => row.different).length,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1,6 +1,9 @@
|
|||||||
import { DatabaseSync } from 'node:sqlite';
|
import { DatabaseSync } from 'node:sqlite';
|
||||||
import { existsSync, mkdirSync, readdirSync, readFileSync } from 'node:fs';
|
import { existsSync, mkdirSync, readdirSync, readFileSync } from 'node:fs';
|
||||||
import { dirname, join } from 'node:path';
|
import { dirname, join } from 'node:path';
|
||||||
|
import { loadEnv } from './env';
|
||||||
|
|
||||||
|
loadEnv();
|
||||||
|
|
||||||
const DB_PATH = process.env.DB_PATH ?? 'data/app.db';
|
const DB_PATH = process.env.DB_PATH ?? 'data/app.db';
|
||||||
const MIGRATIONS_DIR = 'migrations';
|
const MIGRATIONS_DIR = 'migrations';
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import { existsSync } from 'node:fs';
|
||||||
|
|
||||||
|
let loaded = false;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 运行时补读 .env。Astro 的构建期环境变量在 standalone 部署时不可靠,
|
||||||
|
* 而 standalone 运行时以 process.env 为准;这里保证直接 `node dist/server/entry.mjs`
|
||||||
|
* 或脚本运行也能读到项目根目录的 .env。
|
||||||
|
*/
|
||||||
|
export function loadEnv(): void {
|
||||||
|
if (loaded) return;
|
||||||
|
loaded = true;
|
||||||
|
if (!existsSync('.env')) return;
|
||||||
|
try {
|
||||||
|
process.loadEnvFile('.env');
|
||||||
|
} catch {
|
||||||
|
// .env 格式错误时不阻塞启动,缺配置会在具体功能处报错
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,422 @@
|
|||||||
|
import type { PhoneSpecs } from './schema';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 马达 / 扬声器型号参数库。
|
||||||
|
*
|
||||||
|
* 数据只收录能对应到具体型号的公开参数:
|
||||||
|
* - official:厂商官方规格(瑞声 RichTap、安和精密等);
|
||||||
|
* - brand:手机品牌官方口径(如小米、真我发布会);
|
||||||
|
* - media:媒体 / 电商实测或规格页;
|
||||||
|
* - derived:按行业型号命名规则推定(前两位 × 后两位,单位 mm)。
|
||||||
|
*
|
||||||
|
* 回填优先保留已有值;只有型号变体尺寸不同,或已有体积与厂商数据明显冲突时才覆盖。
|
||||||
|
*/
|
||||||
|
export type CatalogConfidence = 'official' | 'brand' | 'media' | 'derived';
|
||||||
|
|
||||||
|
export interface MotorCatalogEntry {
|
||||||
|
/** 归一化后的型号代号,如 0809 / 0916 */
|
||||||
|
code: string;
|
||||||
|
/** 外形尺寸,如 "8 × 9 × 3.5 mm" */
|
||||||
|
size?: string;
|
||||||
|
/** 体积,如 "252 mm³";没有官方数据时给出带「估算」字样的预估值 */
|
||||||
|
volume?: string;
|
||||||
|
/** 体积是否为估算值 */
|
||||||
|
estimated?: boolean;
|
||||||
|
/** 谐振频率 */
|
||||||
|
resonance?: string;
|
||||||
|
/** 稳态振动量 @100g */
|
||||||
|
grms?: string;
|
||||||
|
/** 瞬态振动量 @10ms */
|
||||||
|
transient?: string;
|
||||||
|
/** 型号对应变体(如 0809E 厚度 4.0mm)需要覆盖旧尺寸时置为 true */
|
||||||
|
overrideSize?: boolean;
|
||||||
|
confidence: CatalogConfidence;
|
||||||
|
source?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SpeakerCatalogEntry {
|
||||||
|
/** 归一化后的型号代号,如 1115 / 1216 */
|
||||||
|
code: string;
|
||||||
|
/** 振膜尺寸(长 × 宽),如 "15 × 11 mm" */
|
||||||
|
size?: string;
|
||||||
|
/** 厚度,仅在厂商公开时填写 */
|
||||||
|
thickness?: string;
|
||||||
|
/** 额定功率 */
|
||||||
|
power?: string;
|
||||||
|
confidence: CatalogConfidence;
|
||||||
|
source?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 马达目录:官方参数来自瑞声 RichTap、品牌发布会与用户整理的《主流手机马达型号参数表》;
|
||||||
|
* 7514 / 8282 / 9593 无官方体积,按型号尺寸 × 常见厚度估算并标注「估算」。
|
||||||
|
*/
|
||||||
|
export const MOTOR_CATALOG: MotorCatalogEntry[] = [
|
||||||
|
{
|
||||||
|
code: '0620',
|
||||||
|
size: '6 × 20 × 3.4 mm',
|
||||||
|
volume: '408 mm³',
|
||||||
|
resonance: '160 Hz',
|
||||||
|
grms: '1.14 Grms',
|
||||||
|
transient: '2.20 Gpp',
|
||||||
|
confidence: 'official',
|
||||||
|
source: 'https://www.richtap-haptics.com/product/component',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
code: '0809',
|
||||||
|
size: '8 × 9 × 3.5 mm',
|
||||||
|
volume: '252 mm³',
|
||||||
|
resonance: '170 Hz',
|
||||||
|
grms: '0.66 Grms',
|
||||||
|
transient: '1.21 Gpp',
|
||||||
|
confidence: 'official',
|
||||||
|
source: 'https://www.richtap-haptics.com/product/component',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
code: '0809E',
|
||||||
|
size: '8 × 9 × 4.0 mm',
|
||||||
|
volume: '288 mm³',
|
||||||
|
overrideSize: true,
|
||||||
|
confidence: 'media',
|
||||||
|
source: '《主流手机马达型号参数表》:厚度 4.0mm,体积按尺寸计算',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
code: '0815',
|
||||||
|
size: '8 × 15 × 3.0 mm',
|
||||||
|
volume: '360 mm³',
|
||||||
|
resonance: '170 Hz',
|
||||||
|
grms: '1.01 Grms',
|
||||||
|
transient: '1.85 Gpp',
|
||||||
|
confidence: 'official',
|
||||||
|
source: 'https://www.richtap-haptics.com/product/component',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
code: '0816',
|
||||||
|
size: '8 × 16 × 3.5 mm',
|
||||||
|
volume: '448 mm³',
|
||||||
|
confidence: 'brand',
|
||||||
|
source: 'https://www.ithome.com/0/755/695.htm',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
code: '0916',
|
||||||
|
size: '9.0 × 16.3 × 4.1 mm',
|
||||||
|
volume: '602 mm³',
|
||||||
|
resonance: '130 Hz',
|
||||||
|
grms: '1.4 Grms',
|
||||||
|
transient: '4.2 Gpp',
|
||||||
|
confidence: 'official',
|
||||||
|
source: 'https://www.richtap-haptics.com/product/component',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
code: '1010',
|
||||||
|
size: '10 × 10 × 3.5 mm',
|
||||||
|
volume: '350 mm³',
|
||||||
|
resonance: '170 Hz',
|
||||||
|
grms: '0.86 Grms',
|
||||||
|
transient: '2.10 Gpp',
|
||||||
|
confidence: 'official',
|
||||||
|
source: 'https://www.richtap-haptics.com/product/component',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
code: '1016',
|
||||||
|
size: '10 × 16 × 3.5 mm',
|
||||||
|
volume: '560 mm³',
|
||||||
|
resonance: '130 Hz',
|
||||||
|
grms: '1.1 Grms',
|
||||||
|
transient: '3.65 Gpp',
|
||||||
|
confidence: 'official',
|
||||||
|
source: 'https://www.richtap-haptics.com/product/component',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
code: '9595',
|
||||||
|
size: '9.5 × 9.5 × 3.5 mm',
|
||||||
|
volume: '316 mm³',
|
||||||
|
resonance: '170 Hz',
|
||||||
|
grms: '0.84 Grms',
|
||||||
|
transient: '1.56 Gpp',
|
||||||
|
confidence: 'official',
|
||||||
|
source: 'https://www.richtap-haptics.com/product/component',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
code: '7514',
|
||||||
|
size: '7.5 × 14 mm',
|
||||||
|
volume: '约 420 mm³',
|
||||||
|
estimated: true,
|
||||||
|
grms: '1.1 Grms',
|
||||||
|
confidence: 'derived',
|
||||||
|
source: '《主流手机马达型号参数表》:官方仅公布 1.1Grms;体积按 7.5×14×4.0mm 估算',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
code: '8282',
|
||||||
|
size: '8.2 × 8.2 mm',
|
||||||
|
volume: '约 235 mm³',
|
||||||
|
estimated: true,
|
||||||
|
confidence: 'official',
|
||||||
|
source: '安和精密 8282 系列公开尺寸;体积按 8.2×8.2×3.5mm 估算',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
code: '9593',
|
||||||
|
size: '9.5 × 9.3 mm',
|
||||||
|
volume: '约 309 mm³',
|
||||||
|
estimated: true,
|
||||||
|
confidence: 'derived',
|
||||||
|
source: '歌尔 9593 系列;体积按 9.5×9.3×3.5mm 估算',
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 扬声器目录:手机微型扬声器型号通常以「长 × 宽」命名,例如 1115 = 15 × 11 mm、1216 = 12 × 16 mm。
|
||||||
|
* 功率仅在厂商 / 电商规格明确时填写。
|
||||||
|
*/
|
||||||
|
export const SPEAKER_CATALOG: SpeakerCatalogEntry[] = [
|
||||||
|
{
|
||||||
|
code: '1115',
|
||||||
|
size: '15 × 11 mm',
|
||||||
|
thickness: '3.0 mm',
|
||||||
|
confidence: 'media',
|
||||||
|
source: '合翔 UGSP111508 规格书 / 电商 1511 规格',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
code: '1511',
|
||||||
|
size: '15 × 11 mm',
|
||||||
|
confidence: 'media',
|
||||||
|
source: '电商 1511 规格(15 × 11 mm)',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
code: '1216',
|
||||||
|
size: '12 × 16 mm',
|
||||||
|
confidence: 'media',
|
||||||
|
source: '小米 10 Pro 双 1216 扬声器公开资料',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
code: '1612',
|
||||||
|
size: '12 × 16 mm',
|
||||||
|
confidence: 'derived',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
code: '1217',
|
||||||
|
size: '12 × 17 × 2.7 mm',
|
||||||
|
power: '0.6 W',
|
||||||
|
confidence: 'media',
|
||||||
|
source: '瑞声 AAC1217 电商规格(17 × 12 × 2.7 mm,0.6W)',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
code: '1712',
|
||||||
|
size: '12 × 17 mm',
|
||||||
|
confidence: 'derived',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
code: '1318',
|
||||||
|
size: '13 × 18 mm',
|
||||||
|
confidence: 'media',
|
||||||
|
source: '电商 1318 / 1813 规格',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
code: '1813',
|
||||||
|
size: '13 × 18 mm',
|
||||||
|
confidence: 'derived',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
code: '1014',
|
||||||
|
size: '10 × 14 mm',
|
||||||
|
confidence: 'media',
|
||||||
|
source: '瑞声 AAC 1014 电商型号资料',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
code: '1012',
|
||||||
|
size: '10 × 12 mm',
|
||||||
|
confidence: 'derived',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
code: '1015',
|
||||||
|
size: '10 × 15 mm',
|
||||||
|
confidence: 'derived',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
code: '1016',
|
||||||
|
size: '10 × 16 mm',
|
||||||
|
confidence: 'derived',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
code: '1116',
|
||||||
|
size: '11 × 16 mm',
|
||||||
|
confidence: 'derived',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
code: '1226',
|
||||||
|
size: '12 × 26 mm',
|
||||||
|
confidence: 'derived',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
code: '1510',
|
||||||
|
size: '15 × 10 mm',
|
||||||
|
confidence: 'derived',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
code: '1620',
|
||||||
|
size: '16 × 20 mm',
|
||||||
|
confidence: 'derived',
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const MOTOR_MAP = new Map(MOTOR_CATALOG.map((entry) => [entry.code, entry]));
|
||||||
|
const SPEAKER_MAP = new Map(SPEAKER_CATALOG.map((entry) => [entry.code, entry]));
|
||||||
|
|
||||||
|
/** 同一尺寸单元的两种常见写法(1511 与 1115 等)合并统计 */
|
||||||
|
const SPEAKER_CODE_ALIASES: Record<string, string> = {
|
||||||
|
'1511': '1115',
|
||||||
|
'1612': '1216',
|
||||||
|
'1712': '1217',
|
||||||
|
'1813': '1318',
|
||||||
|
'1611': '1116',
|
||||||
|
'1015': '1510',
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 型号里带厂商前后缀时,取第一个 4 位数字代号与紧邻的字母后缀;091640 / 751440 这类带厚度后缀的取前 4 位 */
|
||||||
|
const MODEL_CODE = /(\d{4})([A-Za-z])?/;
|
||||||
|
|
||||||
|
export function normalizeMotorModel(raw?: string): string | undefined {
|
||||||
|
const text = String(raw ?? '').trim();
|
||||||
|
if (!text) return undefined;
|
||||||
|
const match = text.match(MODEL_CODE);
|
||||||
|
if (!match) return undefined;
|
||||||
|
const base = match[1];
|
||||||
|
const suffix = (match[2] ?? '').toUpperCase();
|
||||||
|
let code = suffix ? `${base}${suffix}` : base;
|
||||||
|
if (base === '0916' && /turbo/i.test(text)) code = '0916T';
|
||||||
|
if (!MOTOR_MAP.has(code)) code = base;
|
||||||
|
return MOTOR_MAP.has(code) ? code : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function normalizeSpeakerModel(raw?: string): string | undefined {
|
||||||
|
const text = String(raw ?? '').trim();
|
||||||
|
if (!text) return undefined;
|
||||||
|
const rawCode = text.match(MODEL_CODE)?.[1];
|
||||||
|
if (!rawCode) return undefined;
|
||||||
|
const code = SPEAKER_CODE_ALIASES[rawCode] ?? rawCode;
|
||||||
|
return SPEAKER_MAP.has(code) ? code : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function lookupMotorModel(raw?: string): MotorCatalogEntry | undefined {
|
||||||
|
const code = normalizeMotorModel(raw);
|
||||||
|
return code ? MOTOR_MAP.get(code) : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function lookupSpeakerModel(raw?: string): SpeakerCatalogEntry | undefined {
|
||||||
|
const code = normalizeSpeakerModel(raw);
|
||||||
|
return code ? SPEAKER_MAP.get(code) : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 写入设备的体积文本;估算值追加说明,避免与官方数据混淆 */
|
||||||
|
function catalogVolumeText(entry?: MotorCatalogEntry): string | undefined {
|
||||||
|
if (!entry?.volume) return undefined;
|
||||||
|
if (entry.estimated && !/估算|计算/.test(entry.volume)) return `${entry.volume}(估算)`;
|
||||||
|
return entry.volume;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据已知型号补齐缺失的尺寸 / 体积 / 功率。
|
||||||
|
* 不覆盖已有字段;没有变化时返回原对象,便于调用方判断是否需要写库。
|
||||||
|
*/
|
||||||
|
export function enrichHardwareSpecs(specs: PhoneSpecs): PhoneSpecs {
|
||||||
|
let next = specs;
|
||||||
|
let changed = false;
|
||||||
|
|
||||||
|
const vibration = specs.vibration;
|
||||||
|
if (vibration) {
|
||||||
|
// 旧数据 / AI 曾把体积写进尺寸字段(如「约 1.0 cm³」),这里纠正为体积
|
||||||
|
let normalized = vibration;
|
||||||
|
if (vibration.size && /(cm³|mm³)/i.test(vibration.size)) {
|
||||||
|
const volumeText = vibration.size;
|
||||||
|
normalized = {
|
||||||
|
...vibration,
|
||||||
|
size: undefined,
|
||||||
|
volume: vibration.volume ?? volumeText,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
// 尺寸字段只有型号(如「0809」)时清掉,交给目录补真实尺寸
|
||||||
|
const sizeText = normalized.size?.trim();
|
||||||
|
const modelText = normalized.model?.trim();
|
||||||
|
if (
|
||||||
|
sizeText &&
|
||||||
|
(/^\d{3,6}[A-Za-z]?$/.test(sizeText) ||
|
||||||
|
(modelText && (modelText.includes(sizeText) || sizeText.includes(modelText))))
|
||||||
|
) {
|
||||||
|
normalized = { ...normalized, size: undefined };
|
||||||
|
}
|
||||||
|
// 少数本地机型的型号直接写在类型里(如「0815超线性马达」)
|
||||||
|
if (!normalized.model && normalized.type) {
|
||||||
|
const code = normalizeMotorModel(normalized.type);
|
||||||
|
if (code) normalized = { ...normalized, model: code };
|
||||||
|
}
|
||||||
|
const entry = normalized.model ? lookupMotorModel(normalized.model) : undefined;
|
||||||
|
// 0809E 这类同系列变体厚度不同,需要覆盖旧尺寸
|
||||||
|
if (entry?.overrideSize && normalized.size && normalized.size !== entry.size) {
|
||||||
|
normalized = { ...normalized, size: entry.size };
|
||||||
|
}
|
||||||
|
// 已有体积与厂商参数不一致时(如 0809 被写成 1.0 cm³、0916 写成 601),以目录数据为准
|
||||||
|
const existingVolume = motorVolume(normalized.volume);
|
||||||
|
const officialVolume = motorVolume(entry?.volume);
|
||||||
|
if (existingVolume && officialVolume) {
|
||||||
|
const ratio = existingVolume / officialVolume;
|
||||||
|
const exactSource = entry!.confidence === 'official' || entry!.confidence === 'brand';
|
||||||
|
if (
|
||||||
|
ratio < 0.8 ||
|
||||||
|
ratio > 1.25 ||
|
||||||
|
entry!.overrideSize ||
|
||||||
|
(exactSource && Math.abs(existingVolume - officialVolume) > 0.5)
|
||||||
|
) {
|
||||||
|
normalized = { ...normalized, volume: catalogVolumeText(entry) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const nextVibration = {
|
||||||
|
...normalized,
|
||||||
|
...(normalized.size || !entry?.size ? {} : { size: entry.size }),
|
||||||
|
...(normalized.volume || !entry?.volume ? {} : { volume: catalogVolumeText(entry) }),
|
||||||
|
...(normalized.resonance || !entry?.resonance ? {} : { resonance: entry.resonance }),
|
||||||
|
...(normalized.grms || !entry?.grms ? {} : { grms: entry.grms }),
|
||||||
|
...(normalized.transient || !entry?.transient ? {} : { transient: entry.transient }),
|
||||||
|
};
|
||||||
|
if (JSON.stringify(nextVibration) !== JSON.stringify(vibration)) {
|
||||||
|
next = { ...next, vibration: nextVibration };
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const units = specs.speakers?.units ?? [];
|
||||||
|
let unitsChanged = false;
|
||||||
|
const nextUnits = units.map((unit) => {
|
||||||
|
if (!unit.model) return unit;
|
||||||
|
const entry = lookupSpeakerModel(unit.model);
|
||||||
|
if (!entry) return unit;
|
||||||
|
const enriched = {
|
||||||
|
...unit,
|
||||||
|
...(unit.size || !entry.size ? {} : { size: entry.size }),
|
||||||
|
...(unit.power || !entry.power ? {} : { power: entry.power }),
|
||||||
|
};
|
||||||
|
if (enriched.size === unit.size && enriched.power === unit.power) return unit;
|
||||||
|
unitsChanged = true;
|
||||||
|
return enriched;
|
||||||
|
});
|
||||||
|
if (unitsChanged) {
|
||||||
|
next = { ...next, speakers: { ...specs.speakers!, units: nextUnits } };
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return changed ? next : specs;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 从尺寸文本里取面积(长 × 宽),用于扬声器排行;无法解析返回 undefined */
|
||||||
|
export function speakerArea(size?: string): number | undefined {
|
||||||
|
if (!size) return undefined;
|
||||||
|
const numbers = size.match(/\d+(?:\.\d+)?/g)?.map(Number) ?? [];
|
||||||
|
if (numbers.length < 2) return undefined;
|
||||||
|
return numbers[0] * numbers[1];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 从体积文本里取数值,用于马达排行 */
|
||||||
|
export function motorVolume(volume?: string): number | undefined {
|
||||||
|
if (!volume) return undefined;
|
||||||
|
const value = volume.match(/\d+(?:\.\d+)?/)?.[0];
|
||||||
|
return value ? Number(value) : undefined;
|
||||||
|
}
|
||||||
+132
@@ -0,0 +1,132 @@
|
|||||||
|
import sharp from 'sharp';
|
||||||
|
import type { PhoneDevice } from './schema';
|
||||||
|
|
||||||
|
const WIDTH = 1200;
|
||||||
|
const HEIGHT = 630;
|
||||||
|
|
||||||
|
function escapeXml(value: string): string {
|
||||||
|
return value
|
||||||
|
.replace(/&/g, '&')
|
||||||
|
.replace(/</g, '<')
|
||||||
|
.replace(/>/g, '>')
|
||||||
|
.replace(/"/g, '"')
|
||||||
|
.replace(/'/g, ''');
|
||||||
|
}
|
||||||
|
|
||||||
|
function cut(value: string, max: number): string {
|
||||||
|
const text = value.trim() || '—';
|
||||||
|
return text.length > max ? `${text.slice(0, max - 1)}…` : text;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** OG 图只使用 Latin 字符,避免 Linux 容器缺中文字体时出现方框 */
|
||||||
|
function isAscii(value: string): boolean {
|
||||||
|
return /^[\x20-\x7e]*$/.test(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function asciiOr(value: string, fallback: string): string {
|
||||||
|
return isAscii(value) ? value : fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "4610 mAh" / "4610 毫安时" -> "4610 mAh" */
|
||||||
|
function numericWithUnit(value: string | undefined, unit: string): string {
|
||||||
|
const match = (value ?? '').match(/\d+(?:\.\d+)?/);
|
||||||
|
return match ? `${match[0]}${unit}` : '—';
|
||||||
|
}
|
||||||
|
|
||||||
|
interface OgCard {
|
||||||
|
kicker: string;
|
||||||
|
title: string;
|
||||||
|
subtitle: string;
|
||||||
|
boxes: { label: string; value: string }[];
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildCard(device: PhoneDevice | null, counts: { phones: number; chips: number }): OgCard {
|
||||||
|
if (!device) {
|
||||||
|
return {
|
||||||
|
kicker: 'PUBLIC HARDWARE SPECS',
|
||||||
|
title: 'LFSpecs',
|
||||||
|
subtitle: 'Phones + SoCs + Peripherals',
|
||||||
|
boxes: [
|
||||||
|
{ label: 'PHONES', value: String(counts.phones) },
|
||||||
|
{ label: 'SOCS', value: String(counts.chips) },
|
||||||
|
{ label: 'COVERAGE', value: 'Phone + SoC' },
|
||||||
|
{ label: 'SITE', value: 'specs.atie.fun' },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const specs = device.specs;
|
||||||
|
const model = device.model.trim();
|
||||||
|
const brand = device.brand.trim();
|
||||||
|
const rawTitle = model.toLowerCase().startsWith(brand.toLowerCase()) ? model : `${brand} ${model}`;
|
||||||
|
const title = asciiOr(rawTitle, device.slug.replace(/-/g, ' '));
|
||||||
|
const soc = asciiOr(specs.platform?.chipset ?? '', device.chipRefs.soc ?? '—');
|
||||||
|
return {
|
||||||
|
kicker: 'PHONE SPECIFICATIONS',
|
||||||
|
title,
|
||||||
|
subtitle: `${device.lifecycle === 'discontinued' ? 'Discontinued' : device.lifecycle === 'announced' ? 'Announced' : 'Released'} - Hardware specifications`,
|
||||||
|
boxes: [
|
||||||
|
{ label: 'SOC', value: cut(soc, 20) },
|
||||||
|
{ label: 'DISPLAY', value: numericWithUnit(specs.display?.size, ' in') },
|
||||||
|
{ label: 'BATTERY', value: numericWithUnit(specs.battery?.capacity, ' mAh') },
|
||||||
|
{ label: 'WEIGHT', value: numericWithUnit(specs.body?.weight, ' g') },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildSvg(card: OgCard): string {
|
||||||
|
const boxWidth = 240;
|
||||||
|
const boxGap = 24;
|
||||||
|
const boxX = 72;
|
||||||
|
const boxY = 372;
|
||||||
|
|
||||||
|
const boxes = card.boxes
|
||||||
|
.map((box, index) => {
|
||||||
|
const x = boxX + index * (boxWidth + boxGap);
|
||||||
|
return `
|
||||||
|
<g transform="translate(${x} ${boxY})">
|
||||||
|
<rect width="${boxWidth}" height="112" rx="14" fill="#121518" stroke="#242a30" />
|
||||||
|
<text x="20" y="34" font-family="Inter, 'Segoe UI', 'DejaVu Sans', Arial, sans-serif" font-size="15" fill="#9aa3ad" letter-spacing="1.4">${escapeXml(box.label)}</text>
|
||||||
|
<text x="20" y="78" font-family="Inter, 'Segoe UI', 'DejaVu Sans', Arial, sans-serif" font-size="22" font-weight="600" fill="#e8eaed">${escapeXml(box.value)}</text>
|
||||||
|
</g>`;
|
||||||
|
})
|
||||||
|
.join('');
|
||||||
|
|
||||||
|
return `<svg xmlns="http://www.w3.org/2000/svg" width="${WIDTH}" height="${HEIGHT}" viewBox="0 0 ${WIDTH} ${HEIGHT}">
|
||||||
|
<defs>
|
||||||
|
<linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
|
||||||
|
<stop offset="0" stop-color="#0b0d0f" />
|
||||||
|
<stop offset="1" stop-color="#0f1616" />
|
||||||
|
</linearGradient>
|
||||||
|
<radialGradient id="glow" cx="0.82" cy="0.12" r="0.7">
|
||||||
|
<stop offset="0" stop-color="#2dd4bf" stop-opacity="0.22" />
|
||||||
|
<stop offset="1" stop-color="#2dd4bf" stop-opacity="0" />
|
||||||
|
</radialGradient>
|
||||||
|
</defs>
|
||||||
|
<rect width="${WIDTH}" height="${HEIGHT}" fill="url(#bg)" />
|
||||||
|
<rect width="${WIDTH}" height="${HEIGHT}" fill="url(#glow)" />
|
||||||
|
<circle cx="1040" cy="120" r="210" fill="none" stroke="#2dd4bf" stroke-opacity="0.18" />
|
||||||
|
<circle cx="1040" cy="120" r="150" fill="none" stroke="#2dd4bf" stroke-opacity="0.12" />
|
||||||
|
<circle cx="1040" cy="120" r="90" fill="none" stroke="#2dd4bf" stroke-opacity="0.1" />
|
||||||
|
<rect x="0" y="0" width="8" height="${HEIGHT}" fill="#2dd4bf" />
|
||||||
|
<text x="72" y="78" font-family="Inter, 'Segoe UI', 'DejaVu Sans', Arial, sans-serif" font-size="26" font-weight="600" fill="#e8eaed">LFSpecs</text>
|
||||||
|
<text x="72" y="150" font-family="Inter, 'Segoe UI', 'DejaVu Sans', Arial, sans-serif" font-size="20" fill="#2dd4bf" letter-spacing="2">${escapeXml(card.kicker)}</text>
|
||||||
|
<text x="72" y="240" font-family="Inter, 'Segoe UI', 'DejaVu Sans', Arial, sans-serif" font-size="64" font-weight="700" fill="#e8eaed">${escapeXml(cut(card.title, 22))}</text>
|
||||||
|
<text x="72" y="302" font-family="Inter, 'Segoe UI', 'DejaVu Sans', Arial, sans-serif" font-size="24" fill="#9aa3ad">${escapeXml(cut(card.subtitle, 48))}</text>
|
||||||
|
${boxes}
|
||||||
|
<line x1="72" y1="548" x2="1128" y2="548" stroke="#242a30" />
|
||||||
|
<text x="72" y="586" font-family="Inter, 'Segoe UI', 'DejaVu Sans', Arial, sans-serif" font-size="20" fill="#9aa3ad">Compiled by humans + AI | For reference only</text>
|
||||||
|
<text x="1128" y="586" text-anchor="end" font-family="Inter, 'Segoe UI', 'DejaVu Sans', Arial, sans-serif" font-size="20" fill="#2dd4bf">specs.atie.fun</text>
|
||||||
|
</svg>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function renderOgPng(
|
||||||
|
device: PhoneDevice | null,
|
||||||
|
counts: { phones: number; chips: number },
|
||||||
|
): Promise<Buffer> {
|
||||||
|
const svg = buildSvg(buildCard(device, counts));
|
||||||
|
// density 72 保证按 SVG 的 width/height 原尺寸输出(1200x630)
|
||||||
|
return sharp(Buffer.from(svg), { density: 72 })
|
||||||
|
.png({ compressionLevel: 9 })
|
||||||
|
.toBuffer();
|
||||||
|
}
|
||||||
@@ -0,0 +1,184 @@
|
|||||||
|
import {
|
||||||
|
lookupMotorModel,
|
||||||
|
lookupSpeakerModel,
|
||||||
|
motorVolume,
|
||||||
|
normalizeMotorModel,
|
||||||
|
normalizeSpeakerModel,
|
||||||
|
speakerArea,
|
||||||
|
} from './hardware-catalog';
|
||||||
|
import { listChips, listDevices } from './repo';
|
||||||
|
import type { Device, SocDetail } from './schema';
|
||||||
|
|
||||||
|
export type SocMetric = 'single' | 'multi' | 'antutu';
|
||||||
|
|
||||||
|
export interface SocRankRow {
|
||||||
|
slug: string;
|
||||||
|
brand: string;
|
||||||
|
model: string;
|
||||||
|
single?: number;
|
||||||
|
multi?: number;
|
||||||
|
antutu?: number;
|
||||||
|
year?: number;
|
||||||
|
phoneCount?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface HardwareRankRow {
|
||||||
|
code: string;
|
||||||
|
size?: string;
|
||||||
|
volume?: string;
|
||||||
|
/** 体积是否为估算值 */
|
||||||
|
estimated?: boolean;
|
||||||
|
resonance?: string;
|
||||||
|
grms?: string;
|
||||||
|
power?: string;
|
||||||
|
/** 单元面积 mm²(扬声器)或体积 mm³(马达) */
|
||||||
|
metric?: number;
|
||||||
|
/** 使用该型号的设备数 */
|
||||||
|
count: number;
|
||||||
|
/** 单元数量(仅扬声器,按出现次数) */
|
||||||
|
units?: number;
|
||||||
|
/** 原始型号写法,便于排查 */
|
||||||
|
variants: string[];
|
||||||
|
devices: { slug: string; brand: string; model: string }[];
|
||||||
|
}
|
||||||
|
|
||||||
|
function scoreFrom(benchmarks: SocDetail['benchmarks'], patterns: RegExp[]): number | undefined {
|
||||||
|
for (const pattern of patterns) {
|
||||||
|
const found = benchmarks.find((item) => pattern.test(item.name));
|
||||||
|
if (!found) continue;
|
||||||
|
const value = Number(String(found.score).replace(/[^0-9.]/g, ''));
|
||||||
|
if (Number.isFinite(value) && value > 0) return value;
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** SoC 榜:单核 / 多核优先取 Geekbench 6,缺失时回退 Geekbench 7 / 通用条目 */
|
||||||
|
export function listSocRanking(metric: SocMetric = 'single'): SocRankRow[] {
|
||||||
|
const rows: SocRankRow[] = [];
|
||||||
|
for (const chip of listChips({ type: 'soc' })) {
|
||||||
|
const detail = chip.detail;
|
||||||
|
const benchmarks = detail.benchmarks ?? [];
|
||||||
|
const single = scoreFrom(benchmarks, [/Geekbench 6 单核/i, /Geekbench 7 单核/i, /Geekbench.*单核/i]);
|
||||||
|
const multi = scoreFrom(benchmarks, [/Geekbench 6 多核/i, /Geekbench 7 多核/i, /Geekbench.*多核/i]);
|
||||||
|
const antutu = scoreFrom(benchmarks, [/安兔兔 v11/i, /安兔兔/i]);
|
||||||
|
if (!single && !multi && !antutu) continue;
|
||||||
|
rows.push({
|
||||||
|
slug: chip.slug,
|
||||||
|
brand: chip.brand,
|
||||||
|
model: chip.model,
|
||||||
|
single,
|
||||||
|
multi,
|
||||||
|
antutu,
|
||||||
|
year: detail.overview?.releaseYear,
|
||||||
|
phoneCount: detail.overview?.phoneCount,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const value = (row: SocRankRow) =>
|
||||||
|
(metric === 'single' ? row.single : metric === 'multi' ? row.multi : row.antutu) ?? -1;
|
||||||
|
rows.sort(
|
||||||
|
(a, b) =>
|
||||||
|
value(b) - value(a) ||
|
||||||
|
(b.multi ?? 0) - (a.multi ?? 0) ||
|
||||||
|
(b.antutu ?? 0) - (a.antutu ?? 0) ||
|
||||||
|
a.model.localeCompare(b.model),
|
||||||
|
);
|
||||||
|
return rows;
|
||||||
|
}
|
||||||
|
|
||||||
|
function pushDevice(row: HardwareRankRow, device: HardwareRankRow['devices'][number]): void {
|
||||||
|
row.devices.push(device);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 马达榜:按厂商体积从大到小;无体积的型号按搭载机型数排在后面 */
|
||||||
|
export function listMotorRanking(devices: Device[] = listDevices()): HardwareRankRow[] {
|
||||||
|
const map = new Map<string, HardwareRankRow>();
|
||||||
|
for (const device of devices) {
|
||||||
|
const vibration = device.specs.vibration;
|
||||||
|
const code = normalizeMotorModel(vibration?.model);
|
||||||
|
if (!code) continue;
|
||||||
|
const entry = lookupMotorModel(code);
|
||||||
|
if (!entry) continue;
|
||||||
|
|
||||||
|
let row = map.get(code);
|
||||||
|
if (!row) {
|
||||||
|
row = {
|
||||||
|
code,
|
||||||
|
size: entry.size,
|
||||||
|
volume: entry.volume,
|
||||||
|
estimated: entry.estimated,
|
||||||
|
resonance: entry.resonance,
|
||||||
|
grms: entry.grms,
|
||||||
|
metric: motorVolume(entry.volume),
|
||||||
|
count: 0,
|
||||||
|
variants: [],
|
||||||
|
devices: [],
|
||||||
|
};
|
||||||
|
map.set(code, row);
|
||||||
|
}
|
||||||
|
const raw = String(vibration?.model ?? code).trim();
|
||||||
|
if (raw && !row.variants.includes(raw)) row.variants.push(raw);
|
||||||
|
pushDevice(row, { slug: device.slug, brand: device.brand, model: device.model });
|
||||||
|
}
|
||||||
|
// 同一设备可能被重复扫描,统一按 slug 去重后再计算数量
|
||||||
|
for (const row of map.values()) {
|
||||||
|
const unique = new Map(row.devices.map((device) => [device.slug, device]));
|
||||||
|
row.devices = [...unique.values()];
|
||||||
|
row.count = row.devices.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
return [...map.values()].sort(
|
||||||
|
(a, b) =>
|
||||||
|
(b.metric ?? -1) - (a.metric ?? -1) ||
|
||||||
|
b.count - a.count ||
|
||||||
|
a.code.localeCompare(b.code),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 扬声器榜:按单元振膜面积(长 × 宽)排序 */
|
||||||
|
export function listSpeakerRanking(devices: Device[] = listDevices()): HardwareRankRow[] {
|
||||||
|
const map = new Map<string, HardwareRankRow>();
|
||||||
|
const seen = new Map<string, Set<string>>();
|
||||||
|
|
||||||
|
for (const device of devices) {
|
||||||
|
for (const unit of device.specs.speakers?.units ?? []) {
|
||||||
|
const code = normalizeSpeakerModel(unit.model);
|
||||||
|
if (!code) continue;
|
||||||
|
const entry = lookupSpeakerModel(code);
|
||||||
|
if (!entry) continue;
|
||||||
|
|
||||||
|
let row = map.get(code);
|
||||||
|
if (!row) {
|
||||||
|
row = {
|
||||||
|
code,
|
||||||
|
size: entry.size,
|
||||||
|
power: entry.power,
|
||||||
|
metric: speakerArea(entry.size),
|
||||||
|
count: 0,
|
||||||
|
units: 0,
|
||||||
|
variants: [],
|
||||||
|
devices: [],
|
||||||
|
};
|
||||||
|
map.set(code, row);
|
||||||
|
seen.set(code, new Set());
|
||||||
|
}
|
||||||
|
row.units = (row.units ?? 0) + 1;
|
||||||
|
const raw = String(unit.model ?? code).trim();
|
||||||
|
if (raw && !row.variants.includes(raw)) row.variants.push(raw);
|
||||||
|
|
||||||
|
const seenDevices = seen.get(code)!;
|
||||||
|
if (!seenDevices.has(device.slug)) {
|
||||||
|
seenDevices.add(device.slug);
|
||||||
|
row.devices.push({ slug: device.slug, brand: device.brand, model: device.model });
|
||||||
|
row.count = row.devices.length;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return [...map.values()].sort(
|
||||||
|
(a, b) =>
|
||||||
|
(b.metric ?? -1) - (a.metric ?? -1) ||
|
||||||
|
b.count - a.count ||
|
||||||
|
a.code.localeCompare(b.code),
|
||||||
|
);
|
||||||
|
}
|
||||||
+417
-38
@@ -1,5 +1,6 @@
|
|||||||
import { getDb } from './db';
|
import { getDb } from './db';
|
||||||
import { chipSchema, deviceSchema, type Chip, type Device, type DeviceCategory } from './schema';
|
import { chipSchema, deviceSchema, type Chip, type Device, type DeviceCategory } from './schema';
|
||||||
|
import { enrichHardwareSpecs } from './hardware-catalog';
|
||||||
|
|
||||||
type Row = Record<string, unknown>;
|
type Row = Record<string, unknown>;
|
||||||
|
|
||||||
@@ -16,6 +17,27 @@ function toNullable(value: string | undefined | null): string | null {
|
|||||||
return value ?? null;
|
return value ?? null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function transaction<T>(fn: () => T): T {
|
||||||
|
const db = getDb();
|
||||||
|
db.exec('BEGIN');
|
||||||
|
try {
|
||||||
|
const result = fn();
|
||||||
|
db.exec('COMMIT');
|
||||||
|
return result;
|
||||||
|
} catch (error) {
|
||||||
|
db.exec('ROLLBACK');
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function insertRevision(entity: 'device' | 'chip', entityId: number, snapshot: unknown, now: string): void {
|
||||||
|
getDb()
|
||||||
|
.prepare(
|
||||||
|
'INSERT INTO revisions (entity, entity_id, snapshot_json, diff_json, created_at) VALUES (?,?,?,?,?)',
|
||||||
|
)
|
||||||
|
.run(entity, entityId, JSON.stringify(snapshot), null, now);
|
||||||
|
}
|
||||||
|
|
||||||
function rowToDevice(row: Row): Device {
|
function rowToDevice(row: Row): Device {
|
||||||
return deviceSchema.parse({
|
return deviceSchema.parse({
|
||||||
slug: row.slug,
|
slug: row.slug,
|
||||||
@@ -53,61 +75,175 @@ function rowToChip(row: Row): Chip {
|
|||||||
|
|
||||||
/* ------------------------------- devices ------------------------------- */
|
/* ------------------------------- devices ------------------------------- */
|
||||||
|
|
||||||
export type DeviceSort = 'latest' | 'name' | 'brand';
|
export type DeviceSort = 'latest' | 'name' | 'brand' | 'updated';
|
||||||
|
|
||||||
export interface DeviceQuery {
|
export interface DeviceQuery {
|
||||||
category?: DeviceCategory;
|
category?: DeviceCategory;
|
||||||
brand?: string;
|
brand?: string;
|
||||||
q?: string;
|
q?: string;
|
||||||
sort?: DeviceSort;
|
sort?: DeviceSort;
|
||||||
|
/** 只看存在 low 置信度且未核实字段的设备(后台核验用) */
|
||||||
|
needsReview?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 列表查询:分类 / 品牌 / 关键词 / 排序,全部走参数化 SQL */
|
export interface DevicePageQuery extends DeviceQuery {
|
||||||
export function listDevices(query: DeviceQuery = {}): Device[] {
|
page?: number;
|
||||||
const db = getDb();
|
pageSize?: number;
|
||||||
const where: string[] = [];
|
}
|
||||||
|
|
||||||
|
export interface DevicePageResult {
|
||||||
|
items: Device[];
|
||||||
|
total: number;
|
||||||
|
page: number;
|
||||||
|
pageSize: number;
|
||||||
|
pages: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 过滤条件交给参数化 SQL,排序字段走白名单,避免拼接外部输入 */
|
||||||
|
function deviceFilter(query: DeviceQuery): { where: string; params: string[] } {
|
||||||
|
const conditions: string[] = [];
|
||||||
const params: string[] = [];
|
const params: string[] = [];
|
||||||
|
|
||||||
if (query.category) {
|
if (query.category) {
|
||||||
where.push('category = ?');
|
conditions.push('category = ?');
|
||||||
params.push(query.category);
|
params.push(query.category);
|
||||||
}
|
}
|
||||||
if (query.brand) {
|
if (query.brand) {
|
||||||
where.push('brand = ?');
|
conditions.push('brand = ?');
|
||||||
params.push(query.brand);
|
params.push(query.brand);
|
||||||
}
|
}
|
||||||
if (query.q) {
|
if (query.q) {
|
||||||
where.push('(brand LIKE ? OR model LIKE ? OR aliases_json LIKE ? OR summary LIKE ?)');
|
conditions.push(
|
||||||
|
'(brand LIKE ? OR model LIKE ? OR slug LIKE ? OR aliases_json LIKE ? OR summary LIKE ?)',
|
||||||
|
);
|
||||||
const like = `%${query.q}%`;
|
const like = `%${query.q}%`;
|
||||||
params.push(like, like, like, like);
|
params.push(like, like, like, like, like);
|
||||||
|
}
|
||||||
|
if (query.needsReview) {
|
||||||
|
conditions.push(
|
||||||
|
`EXISTS (
|
||||||
|
SELECT 1 FROM json_each(devices.meta_json) AS m
|
||||||
|
WHERE json_extract(m.value, '$.confidence') = 'low'
|
||||||
|
AND COALESCE(json_extract(m.value, '$.verified'), 0) = 0
|
||||||
|
)`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 排序字段白名单,避免拼接外部输入
|
return {
|
||||||
const orderBy =
|
where: conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '',
|
||||||
query.sort === 'name'
|
params,
|
||||||
? 'model ASC'
|
};
|
||||||
: query.sort === 'brand'
|
}
|
||||||
? 'brand ASC, model ASC'
|
|
||||||
: "COALESCE(release_date, announce_date, '') DESC, brand, model";
|
|
||||||
|
|
||||||
const sql = `SELECT * FROM devices ${
|
/**
|
||||||
where.length > 0 ? `WHERE ${where.join(' AND ')}` : ''
|
* 同一发布时间的档位排序:顶配在前,标准版在后。
|
||||||
} ORDER BY ${orderBy}`;
|
* 覆盖常见命名:非凡大师 / 典藏版 / Pro Max / Ultra / Pro+ / Pro / Max / 至尊版 / Plus / 青春版。
|
||||||
|
*/
|
||||||
|
const MODEL_TIER_SQL = `CASE
|
||||||
|
WHEN lower(model) LIKE '%非凡大师%' THEN 120
|
||||||
|
WHEN lower(model) LIKE '%典藏版%' THEN 110
|
||||||
|
WHEN lower(model) LIKE '%pro max%' THEN 100
|
||||||
|
WHEN lower(model) LIKE '%ultra%' THEN 95
|
||||||
|
WHEN lower(model) LIKE '%pro+%' THEN 92
|
||||||
|
WHEN lower(model) LIKE '%pro plus%' THEN 92
|
||||||
|
WHEN lower(model) LIKE '%pro%' THEN 90
|
||||||
|
WHEN lower(model) LIKE '%max%' THEN 85
|
||||||
|
WHEN lower(model) LIKE '%至尊版%' THEN 80
|
||||||
|
WHEN lower(model) LIKE '%plus%' THEN 75
|
||||||
|
WHEN lower(model) LIKE '%+%' THEN 75
|
||||||
|
WHEN lower(model) LIKE '%青春版%' THEN 50
|
||||||
|
WHEN lower(model) LIKE '%活力版%' THEN 50
|
||||||
|
WHEN lower(model) LIKE '%竞速版%' THEN 50
|
||||||
|
WHEN lower(model) LIKE '%lite%' THEN 50
|
||||||
|
ELSE 60
|
||||||
|
END`;
|
||||||
|
|
||||||
const rows = db.prepare(sql).all(...params);
|
function deviceOrderBy(sort: DeviceSort = 'latest'): string {
|
||||||
|
if (sort === 'name') return 'model ASC';
|
||||||
|
if (sort === 'brand') return 'brand ASC, model ASC';
|
||||||
|
if (sort === 'updated') return 'updated_at DESC, brand ASC, model ASC';
|
||||||
|
return `COALESCE(release_date, announce_date, '') DESC, ${MODEL_TIER_SQL} DESC, brand ASC, model ASC`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 列表查询:分类 / 品牌 / 关键词 / 排序 */
|
||||||
|
export function listDevices(query: DeviceQuery = {}): Device[] {
|
||||||
|
const db = getDb();
|
||||||
|
const { where, params } = deviceFilter(query);
|
||||||
|
const rows = db.prepare(`SELECT * FROM devices ${where} ORDER BY ${deviceOrderBy(query.sort)}`).all(...params);
|
||||||
return (rows as Row[]).map(rowToDevice);
|
return (rows as Row[]).map(rowToDevice);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 分页列表:避免一次渲染几百张卡片,只取当前页并返回总数 / 页码 */
|
||||||
|
export function listDevicesPaged(query: DevicePageQuery = {}): DevicePageResult {
|
||||||
|
const db = getDb();
|
||||||
|
const { where, params } = deviceFilter(query);
|
||||||
|
const pageSize = Math.max(1, Math.min(100, Math.floor(query.pageSize ?? 24)));
|
||||||
|
|
||||||
|
const countRow = db.prepare(`SELECT COUNT(*) AS n FROM devices ${where}`).get(...params) as {
|
||||||
|
n: number;
|
||||||
|
};
|
||||||
|
const total = countRow.n;
|
||||||
|
const pages = Math.max(1, Math.ceil(total / pageSize));
|
||||||
|
const requested = Number.isFinite(query.page) ? Math.floor(query.page!) : 1;
|
||||||
|
const page = Math.min(pages, Math.max(1, requested));
|
||||||
|
|
||||||
|
const rows = db
|
||||||
|
.prepare(`SELECT * FROM devices ${where} ORDER BY ${deviceOrderBy(query.sort)} LIMIT ? OFFSET ?`)
|
||||||
|
.all(...params, pageSize, (page - 1) * pageSize);
|
||||||
|
|
||||||
|
return { items: (rows as Row[]).map(rowToDevice), total, page, pageSize, pages };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 品牌默认排序:按大众认知的品牌量级分档,同档内最新机型发布越晚越靠前,
|
||||||
|
* 再按收录量、品牌名排序。未列出的品牌统一排在最后。
|
||||||
|
*/
|
||||||
|
const BRAND_TIERS: readonly (readonly string[])[] = [
|
||||||
|
['Apple', 'Huawei'],
|
||||||
|
['Xiaomi', 'Samsung', 'Honor', 'OPPO', 'vivo'],
|
||||||
|
['OnePlus', 'Redmi', 'realme', 'iQOO'],
|
||||||
|
['Motorola', 'Meizu', 'nubia', 'ZTE', 'ROG'],
|
||||||
|
[
|
||||||
|
'Sony',
|
||||||
|
'Nokia',
|
||||||
|
'Lenovo',
|
||||||
|
'Google',
|
||||||
|
'Nothing',
|
||||||
|
'POCO',
|
||||||
|
'ASUS',
|
||||||
|
'Hisense',
|
||||||
|
'TCL',
|
||||||
|
'BlackBerry',
|
||||||
|
'Sharp',
|
||||||
|
],
|
||||||
|
['NIO Phone', 'Lenovo Legion', 'Gionee', 'Coolpad', 'Maimang'],
|
||||||
|
['WIKO', 'Moondrop MIAD', 'Philips'],
|
||||||
|
];
|
||||||
|
|
||||||
|
function brandTier(brand: string): number {
|
||||||
|
const index = BRAND_TIERS.findIndex((tier) => (tier as readonly string[]).includes(brand));
|
||||||
|
return index === -1 ? BRAND_TIERS.length : index;
|
||||||
|
}
|
||||||
|
|
||||||
export function listBrands(category?: DeviceCategory): { brand: string; count: number }[] {
|
export function listBrands(category?: DeviceCategory): { brand: string; count: number }[] {
|
||||||
const db = getDb();
|
const db = getDb();
|
||||||
const rows = category
|
const sql = `SELECT brand, COUNT(*) AS count, MAX(COALESCE(release_date, announce_date, '')) AS latest
|
||||||
? db
|
FROM devices ${category ? 'WHERE category = ?' : ''}
|
||||||
.prepare(
|
GROUP BY brand`;
|
||||||
'SELECT brand, COUNT(*) AS count FROM devices WHERE category = ? GROUP BY brand ORDER BY brand',
|
const rows = (category ? db.prepare(sql).all(category) : db.prepare(sql).all()) as {
|
||||||
)
|
brand: string;
|
||||||
.all(category)
|
count: number;
|
||||||
: db.prepare('SELECT brand, COUNT(*) AS count FROM devices GROUP BY brand ORDER BY brand').all();
|
latest: string;
|
||||||
return rows as { brand: string; count: number }[];
|
}[];
|
||||||
|
|
||||||
|
rows.sort(
|
||||||
|
(a, b) =>
|
||||||
|
brandTier(a.brand) - brandTier(b.brand) ||
|
||||||
|
b.latest.localeCompare(a.latest) ||
|
||||||
|
b.count - a.count ||
|
||||||
|
a.brand.localeCompare(b.brand),
|
||||||
|
);
|
||||||
|
return rows.map(({ brand, count }) => ({ brand, count }));
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getDevice(slug: string): Device | undefined {
|
export function getDevice(slug: string): Device | undefined {
|
||||||
@@ -139,9 +275,14 @@ export function devicesUsingChip(chipSlug: string): Device[] {
|
|||||||
return (rows as Row[]).map(rowToDevice);
|
return (rows as Row[]).map(rowToDevice);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function saveDevice(input: Device): Device {
|
export function getDeviceId(slug: string): number | undefined {
|
||||||
const device = deviceSchema.parse(input);
|
const row = getDb().prepare('SELECT id FROM devices WHERE slug = ?').get(slug) as
|
||||||
const now = new Date().toISOString();
|
| { id: number }
|
||||||
|
| undefined;
|
||||||
|
return row?.id;
|
||||||
|
}
|
||||||
|
|
||||||
|
function upsertDevice(device: Device, now: string): void {
|
||||||
getDb()
|
getDb()
|
||||||
.prepare(
|
.prepare(
|
||||||
`INSERT INTO devices (
|
`INSERT INTO devices (
|
||||||
@@ -188,19 +329,112 @@ export function saveDevice(input: Device): Device {
|
|||||||
now,
|
now,
|
||||||
now,
|
now,
|
||||||
);
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function saveDevice(input: Device): Device {
|
||||||
|
const parsed = deviceSchema.parse(input);
|
||||||
|
const device = { ...parsed, specs: enrichHardwareSpecs(parsed.specs) };
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
transaction(() => {
|
||||||
|
upsertDevice(device, now);
|
||||||
|
insertRevision('device', getDeviceId(device.slug)!, device, now);
|
||||||
|
});
|
||||||
return getDevice(device.slug)!;
|
return getDevice(device.slug)!;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* -------------------------------- chips -------------------------------- */
|
/* -------------------------------- chips -------------------------------- */
|
||||||
|
|
||||||
export function listChips(options: { type?: Chip['type'] } = {}): Chip[] {
|
export type ChipSort = 'tier' | 'year' | 'name' | 'brand';
|
||||||
|
|
||||||
|
export interface ChipQuery {
|
||||||
|
type?: Chip['type'];
|
||||||
|
brand?: string;
|
||||||
|
q?: string;
|
||||||
|
sort?: ChipSort;
|
||||||
|
page?: number;
|
||||||
|
pageSize?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ChipPageResult {
|
||||||
|
items: Chip[];
|
||||||
|
total: number;
|
||||||
|
page: number;
|
||||||
|
pageSize: number;
|
||||||
|
pages: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
function chipFilter(query: ChipQuery): { where: string; params: string[] } {
|
||||||
|
const conditions: string[] = [];
|
||||||
|
const params: string[] = [];
|
||||||
|
|
||||||
|
if (query.type) {
|
||||||
|
conditions.push('type = ?');
|
||||||
|
params.push(query.type);
|
||||||
|
}
|
||||||
|
if (query.brand) {
|
||||||
|
conditions.push('brand = ?');
|
||||||
|
params.push(query.brand);
|
||||||
|
}
|
||||||
|
if (query.q) {
|
||||||
|
conditions.push('(brand LIKE ? OR model LIKE ? OR aliases_json LIKE ? OR codename LIKE ?)');
|
||||||
|
const like = `%${query.q}%`;
|
||||||
|
params.push(like, like, like, like);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
where: conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '',
|
||||||
|
params,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function chipOrderBy(sort: ChipSort = 'tier'): string {
|
||||||
|
const tier = "CAST(json_extract(detail_json, '$.overview.tierScore') AS REAL)";
|
||||||
|
const year = "CAST(json_extract(detail_json, '$.overview.releaseYear') AS INTEGER)";
|
||||||
|
if (sort === 'name') return 'model ASC';
|
||||||
|
if (sort === 'brand') return `brand ASC, ${tier} DESC, model ASC`;
|
||||||
|
if (sort === 'year') return `${year} DESC, ${tier} DESC, model ASC`;
|
||||||
|
return `${tier} DESC, ${year} DESC, model ASC`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 芯片列表:默认按档位分 / 发布年份 / 名称排序 */
|
||||||
|
export function listChips(query: ChipQuery = {}): Chip[] {
|
||||||
const db = getDb();
|
const db = getDb();
|
||||||
const rows = options.type
|
const { where, params } = chipFilter(query);
|
||||||
? db.prepare('SELECT * FROM chips WHERE type = ? ORDER BY brand, model').all(options.type)
|
const rows = db.prepare(`SELECT * FROM chips ${where} ORDER BY ${chipOrderBy(query.sort)}`).all(...params);
|
||||||
: db.prepare('SELECT * FROM chips ORDER BY brand, model').all();
|
|
||||||
return (rows as Row[]).map(rowToChip);
|
return (rows as Row[]).map(rowToChip);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 分页芯片列表,避免一次渲染数百张卡片 */
|
||||||
|
export function listChipsPaged(query: ChipQuery = {}): ChipPageResult {
|
||||||
|
const db = getDb();
|
||||||
|
const { where, params } = chipFilter(query);
|
||||||
|
const pageSize = Math.max(1, Math.min(100, Math.floor(query.pageSize ?? 24)));
|
||||||
|
|
||||||
|
const countRow = db.prepare(`SELECT COUNT(*) AS n FROM chips ${where}`).get(...params) as {
|
||||||
|
n: number;
|
||||||
|
};
|
||||||
|
const total = countRow.n;
|
||||||
|
const pages = Math.max(1, Math.ceil(total / pageSize));
|
||||||
|
const requested = Number.isFinite(query.page) ? Math.floor(query.page!) : 1;
|
||||||
|
const page = Math.min(pages, Math.max(1, requested));
|
||||||
|
|
||||||
|
const rows = db
|
||||||
|
.prepare(`SELECT * FROM chips ${where} ORDER BY ${chipOrderBy(query.sort)} LIMIT ? OFFSET ?`)
|
||||||
|
.all(...params, pageSize, (page - 1) * pageSize);
|
||||||
|
|
||||||
|
return { items: (rows as Row[]).map(rowToChip), total, page, pageSize, pages };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listChipBrands(type?: Chip['type']): { brand: string; count: number }[] {
|
||||||
|
const db = getDb();
|
||||||
|
const rows = type
|
||||||
|
? db
|
||||||
|
.prepare('SELECT brand, COUNT(*) AS count FROM chips WHERE type = ? GROUP BY brand ORDER BY count DESC, brand')
|
||||||
|
.all(type)
|
||||||
|
: db.prepare('SELECT brand, COUNT(*) AS count FROM chips GROUP BY brand ORDER BY count DESC, brand').all();
|
||||||
|
return rows as { brand: string; count: number }[];
|
||||||
|
}
|
||||||
|
|
||||||
export function getChip(slug: string): Chip | undefined {
|
export function getChip(slug: string): Chip | undefined {
|
||||||
const row = getDb().prepare('SELECT * FROM chips WHERE slug = ?').get(slug) as Row | undefined;
|
const row = getDb().prepare('SELECT * FROM chips WHERE slug = ?').get(slug) as Row | undefined;
|
||||||
return row ? rowToChip(row) : undefined;
|
return row ? rowToChip(row) : undefined;
|
||||||
@@ -214,9 +448,14 @@ export function countChips(type?: Chip['type']): number {
|
|||||||
return row.n;
|
return row.n;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function saveChip(input: Chip): Chip {
|
export function getChipId(slug: string): number | undefined {
|
||||||
const chip = chipSchema.parse(input);
|
const row = getDb().prepare('SELECT id FROM chips WHERE slug = ?').get(slug) as
|
||||||
const now = new Date().toISOString();
|
| { id: number }
|
||||||
|
| undefined;
|
||||||
|
return row?.id;
|
||||||
|
}
|
||||||
|
|
||||||
|
function upsertChip(chip: Chip, now: string): void {
|
||||||
getDb()
|
getDb()
|
||||||
.prepare(
|
.prepare(
|
||||||
`INSERT INTO chips (
|
`INSERT INTO chips (
|
||||||
@@ -249,5 +488,145 @@ export function saveChip(input: Chip): Chip {
|
|||||||
now,
|
now,
|
||||||
now,
|
now,
|
||||||
);
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function saveChip(input: Chip): Chip {
|
||||||
|
const chip = chipSchema.parse(input);
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
transaction(() => {
|
||||||
|
upsertChip(chip, now);
|
||||||
|
insertRevision('chip', getChipId(chip.slug)!, chip, now);
|
||||||
|
});
|
||||||
return getChip(chip.slug)!;
|
return getChip(chip.slug)!;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface ImportCounts {
|
||||||
|
devices: number;
|
||||||
|
chips: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 批量导入:整批在同一事务内 upsert,任一失败全部回滚 */
|
||||||
|
export function importEntities(deviceInputs: Device[], chipInputs: Chip[]): ImportCounts {
|
||||||
|
const devices = deviceInputs.map((item) => {
|
||||||
|
const parsed = deviceSchema.parse(item);
|
||||||
|
return { ...parsed, specs: enrichHardwareSpecs(parsed.specs) };
|
||||||
|
});
|
||||||
|
const chips = chipInputs.map((item) => chipSchema.parse(item));
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
|
||||||
|
transaction(() => {
|
||||||
|
for (const device of devices) {
|
||||||
|
upsertDevice(device, now);
|
||||||
|
insertRevision('device', getDeviceId(device.slug)!, device, now);
|
||||||
|
}
|
||||||
|
for (const chip of chips) {
|
||||||
|
upsertChip(chip, now);
|
||||||
|
insertRevision('chip', getChipId(chip.slug)!, chip, now);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return { devices: devices.length, chips: chips.length };
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------- revisions ------------------------------- */
|
||||||
|
|
||||||
|
export interface RevisionRecord {
|
||||||
|
id: number;
|
||||||
|
entity: 'device' | 'chip';
|
||||||
|
entityId: number;
|
||||||
|
createdAt: string;
|
||||||
|
snapshot: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listRevisions(
|
||||||
|
entity: 'device' | 'chip',
|
||||||
|
entityId: number,
|
||||||
|
limit = 10,
|
||||||
|
): RevisionRecord[] {
|
||||||
|
const rows = getDb()
|
||||||
|
.prepare(
|
||||||
|
`SELECT id, entity, entity_id, snapshot_json, created_at
|
||||||
|
FROM revisions WHERE entity = ? AND entity_id = ?
|
||||||
|
ORDER BY id DESC LIMIT ?`,
|
||||||
|
)
|
||||||
|
.all(entity, entityId, limit) as Row[];
|
||||||
|
return rows.map((row) => ({
|
||||||
|
id: Number(row.id),
|
||||||
|
entity: row.entity as 'device' | 'chip',
|
||||||
|
entityId: Number(row.entity_id),
|
||||||
|
createdAt: String(row.created_at),
|
||||||
|
snapshot: parseJson(row.snapshot_json, null),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------- settings ------------------------------- */
|
||||||
|
|
||||||
|
/** 运行时配置读写(如 B 站登录态),后台界面写入后立即生效,无需重启 */
|
||||||
|
export function getSetting(key: string): string | undefined {
|
||||||
|
const row = getDb()
|
||||||
|
.prepare('SELECT value FROM settings WHERE key = ?')
|
||||||
|
.get(key) as { value: string } | undefined;
|
||||||
|
return row?.value;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function saveSetting(key: string, value: string): void {
|
||||||
|
getDb()
|
||||||
|
.prepare(
|
||||||
|
`INSERT INTO settings (key, value, updated_at) VALUES (?,?,?)
|
||||||
|
ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at`,
|
||||||
|
)
|
||||||
|
.run(key, value, new Date().toISOString());
|
||||||
|
}
|
||||||
|
|
||||||
|
export function deleteSetting(key: string): void {
|
||||||
|
getDb().prepare('DELETE FROM settings WHERE key = ?').run(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------- ai_cache ------------------------------- */
|
||||||
|
|
||||||
|
export interface AiCacheRecord {
|
||||||
|
result: unknown;
|
||||||
|
sources: string[];
|
||||||
|
createdAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getAiCache(key: string): AiCacheRecord | undefined {
|
||||||
|
const row = getDb()
|
||||||
|
.prepare('SELECT result_json, sources_json, created_at FROM ai_cache WHERE key = ?')
|
||||||
|
.get(key) as Row | undefined;
|
||||||
|
if (!row) return undefined;
|
||||||
|
return {
|
||||||
|
result: parseJson(row.result_json, null),
|
||||||
|
sources: parseJson(row.sources_json, []),
|
||||||
|
createdAt: String(row.created_at),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function saveAiCache(key: string, result: unknown, sources: string[]): void {
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
getDb()
|
||||||
|
.prepare(
|
||||||
|
`INSERT INTO ai_cache (key, result_json, sources_json, created_at) VALUES (?,?,?,?)
|
||||||
|
ON CONFLICT(key) DO UPDATE SET
|
||||||
|
result_json = excluded.result_json,
|
||||||
|
sources_json = excluded.sources_json,
|
||||||
|
created_at = excluded.created_at`,
|
||||||
|
)
|
||||||
|
.run(key, JSON.stringify(result), JSON.stringify(sources), now);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listRecentRevisions(limit = 10): RevisionRecord[] {
|
||||||
|
const rows = getDb()
|
||||||
|
.prepare(
|
||||||
|
`SELECT id, entity, entity_id, snapshot_json, created_at
|
||||||
|
FROM revisions ORDER BY id DESC LIMIT ?`,
|
||||||
|
)
|
||||||
|
.all(limit) as Row[];
|
||||||
|
return rows.map((row) => ({
|
||||||
|
id: Number(row.id),
|
||||||
|
entity: row.entity as 'device' | 'chip',
|
||||||
|
entityId: Number(row.entity_id),
|
||||||
|
createdAt: String(row.created_at),
|
||||||
|
snapshot: parseJson(row.snapshot_json, null),
|
||||||
|
}));
|
||||||
|
}
|
||||||
+102
-17
@@ -10,6 +10,7 @@ export const cameraPositionSchema = z.enum([
|
|||||||
'macro',
|
'macro',
|
||||||
'depth',
|
'depth',
|
||||||
'mono',
|
'mono',
|
||||||
|
'color',
|
||||||
'front',
|
'front',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
@@ -17,14 +18,20 @@ export const cameraPositionSchema = z.enum([
|
|||||||
export const cameraModuleSchema = z.object({
|
export const cameraModuleSchema = z.object({
|
||||||
position: cameraPositionSchema,
|
position: cameraPositionSchema,
|
||||||
sensorModel: z.string().optional(), // "Sony IMX890"
|
sensorModel: z.string().optional(), // "Sony IMX890"
|
||||||
|
sensorAlias: z.string().optional(), // 营销名,如 "光影猎人 900"
|
||||||
resolution: z.string().optional(), // "50MP"
|
resolution: z.string().optional(), // "50MP"
|
||||||
aperture: z.string().optional(), // "f/1.8"
|
aperture: z.string().optional(), // "f/1.8"
|
||||||
focalLength: z.string().optional(), // "24mm"
|
focalLength: z.string().optional(), // "24mm"
|
||||||
sensorSize: z.string().optional(), // "1/1.56\""
|
sensorSize: z.string().optional(), // "1/1.56\""
|
||||||
pixelSize: z.string().optional(), // "1.0µm"
|
pixelSize: z.string().optional(), // "1.0µm"
|
||||||
lensElements: z.string().optional(), // "7P"
|
lensElements: z.string().optional(), // "7P"
|
||||||
|
fov: z.string().optional(), // 视场角,如 "115°"
|
||||||
ois: z.boolean().optional(),
|
ois: z.boolean().optional(),
|
||||||
eis: z.boolean().optional(),
|
eis: z.boolean().optional(),
|
||||||
|
cipa: z.string().optional(), // CIPA 防抖等级,如 "CIPA 7.0"
|
||||||
|
telephotoStructure: z.string().optional(), // 长焦结构,如 "潜望式"
|
||||||
|
telephotoMacro: z.boolean().optional(), // 长焦微距
|
||||||
|
telephotoMacroDistance: z.string().optional(), // 长焦微距最近距离,如 "12cm"
|
||||||
zoom: z.string().optional(), // "3x 光学 / 30x 数码"
|
zoom: z.string().optional(), // "3x 光学 / 30x 数码"
|
||||||
autofocusType: z.string().optional(), // "双像素 PDAF"
|
autofocusType: z.string().optional(), // "双像素 PDAF"
|
||||||
video: z
|
video: z
|
||||||
@@ -39,11 +46,50 @@ export const cameraModuleSchema = z.object({
|
|||||||
});
|
});
|
||||||
export type CameraModule = z.infer<typeof cameraModuleSchema>;
|
export type CameraModule = z.infer<typeof cameraModuleSchema>;
|
||||||
|
|
||||||
|
const displayBaseSchema = z.object({
|
||||||
|
size: z.string().optional(), // "6.79 英寸"
|
||||||
|
resolution: z.string().optional(), // "2712 x 1220"
|
||||||
|
cutout: z.string().optional(), // 挖孔形态,如 "中孔" / "无孔"
|
||||||
|
aspectRatio: z.string().optional(),
|
||||||
|
panel: z.string().optional(), // "LTPO AMOLED"
|
||||||
|
vendor: z.string().optional(), // 面板厂商,如 "京东方" / "TCL 华星"
|
||||||
|
technology: z.string().optional(), // 面板技术代号,如 "X1" / "M11"
|
||||||
|
refreshRate: z.string().optional(), // "120Hz"
|
||||||
|
refreshRange: z.string().optional(), // "1-120Hz"
|
||||||
|
refreshNote: z.string().optional(), // 附加说明,如 "最高 185Hz 仅部分游戏场景生效"
|
||||||
|
touchSampling: z.string().optional(),
|
||||||
|
touchSamplingInstant: z.string().optional(), // 瞬时触控采样率
|
||||||
|
colorDepth: z.string().optional(), // "12bit / 687 亿色"
|
||||||
|
colorGamut: z.string().optional(), // "DCI-P3"
|
||||||
|
pixelDensity: z.string().optional(), // "460 PPI"
|
||||||
|
equivalentPpi: z.string().optional(), // OLED 等效 PPI,如 "375 PPI"
|
||||||
|
screenBodyRatio: z.string().optional(), // "89.3%"
|
||||||
|
bezel: z.string().optional(), // 边框宽度
|
||||||
|
width16x9: z.string().optional(), // 16:9 等效宽度,如 "5.34 英寸"
|
||||||
|
brightnessTypical: z.string().optional(),
|
||||||
|
brightnessPeak: z.string().optional(),
|
||||||
|
brightnessGlobalPeak: z.string().optional(),
|
||||||
|
hdr: z.string().optional(),
|
||||||
|
protection: z.string().optional(), // "康宁大猩猩 Victus 2"
|
||||||
|
pwmDimming: z.string().optional(),
|
||||||
|
alwaysOn: z.boolean().optional(),
|
||||||
|
features: z.array(z.string()).default([]), // 屏幕特性
|
||||||
|
note: z.string().optional(), // 其它附加说明
|
||||||
|
});
|
||||||
|
|
||||||
|
/** 主屏 / 副屏共用同一套字段;副屏通过 display.secondary 引用 */
|
||||||
|
export const displaySchema = displayBaseSchema.extend({
|
||||||
|
secondary: displayBaseSchema.optional(),
|
||||||
|
});
|
||||||
|
|
||||||
export const phoneSpecsSchema = z.object({
|
export const phoneSpecsSchema = z.object({
|
||||||
body: z
|
body: z
|
||||||
.object({
|
.object({
|
||||||
dimensions: z.string().optional(), // "161.4 x 74.6 x 8.2 mm"
|
dimensions: z.string().optional(), // "161.4 x 74.6 x 8.2 mm"
|
||||||
weight: z.string().optional(), // "193 g"
|
weight: z.string().optional(), // "193 g"
|
||||||
|
// 不同配色 / 折叠形态下的厚度、重量差异,第一行仍写入 dimensions / weight
|
||||||
|
thicknessVariants: z.array(z.string()).default([]), // "8.47mm(玻璃蓝/透明)"
|
||||||
|
weightVariants: z.array(z.string()).default([]), // "240g(玻璃蓝/透明)"
|
||||||
build: z
|
build: z
|
||||||
.object({
|
.object({
|
||||||
front: z.string().optional(),
|
front: z.string().optional(),
|
||||||
@@ -54,31 +100,21 @@ export const phoneSpecsSchema = z.object({
|
|||||||
sim: z.string().optional(),
|
sim: z.string().optional(),
|
||||||
ipRating: z.string().optional(), // "IP68"
|
ipRating: z.string().optional(), // "IP68"
|
||||||
colors: z.array(z.string()).default([]),
|
colors: z.array(z.string()).default([]),
|
||||||
|
// 与 colors 顺序一致的近似色值,AI / 人工维护,展示页优先使用
|
||||||
|
colorHexes: z.array(z.string()).default([]),
|
||||||
buttons: z.string().optional(),
|
buttons: z.string().optional(),
|
||||||
|
cooling: z.string().optional(), // 散热系统,如 "环形冷泵散热系统"
|
||||||
})
|
})
|
||||||
.optional(),
|
.optional(),
|
||||||
display: z
|
display: displaySchema.optional(),
|
||||||
.object({
|
|
||||||
size: z.string().optional(), // "6.79 英寸"
|
|
||||||
resolution: z.string().optional(), // "2712 x 1220"
|
|
||||||
aspectRatio: z.string().optional(),
|
|
||||||
panel: z.string().optional(), // "LTPO AMOLED"
|
|
||||||
refreshRate: z.string().optional(), // "120Hz"
|
|
||||||
refreshRange: z.string().optional(), // "1-120Hz"
|
|
||||||
touchSampling: z.string().optional(),
|
|
||||||
brightnessTypical: z.string().optional(),
|
|
||||||
brightnessPeak: z.string().optional(),
|
|
||||||
hdr: z.string().optional(),
|
|
||||||
protection: z.string().optional(), // "康宁大猩猩 Victus 2"
|
|
||||||
pwmDimming: z.string().optional(),
|
|
||||||
alwaysOn: z.boolean().optional(),
|
|
||||||
})
|
|
||||||
.optional(),
|
|
||||||
platform: z
|
platform: z
|
||||||
.object({
|
.object({
|
||||||
os: z.string().optional(),
|
os: z.string().optional(),
|
||||||
skin: z.string().optional(),
|
skin: z.string().optional(),
|
||||||
chipset: z.string().optional(), // 冗余展示用,权威值在 chipRefs.soc
|
chipset: z.string().optional(), // 冗余展示用,权威值在 chipRefs.soc
|
||||||
|
socBrand: z.string().optional(), // 高通 / 联发科 / 苹果
|
||||||
|
gpu: z.string().optional(), // "Adreno 850"
|
||||||
|
coprocessor: z.string().optional(), // 协处理器 / 独显芯片 / 影像芯片
|
||||||
})
|
})
|
||||||
.optional(),
|
.optional(),
|
||||||
memory: z
|
memory: z
|
||||||
@@ -87,6 +123,7 @@ export const phoneSpecsSchema = z.object({
|
|||||||
ramType: z.string().optional(), // "LPDDR5X"
|
ramType: z.string().optional(), // "LPDDR5X"
|
||||||
storage: z.string().optional(),
|
storage: z.string().optional(),
|
||||||
storageType: z.string().optional(), // "UFS 4.0"
|
storageType: z.string().optional(), // "UFS 4.0"
|
||||||
|
storageSpeed: z.string().optional(), // 顺序读写速度,如 "约 4.2 GB/s 读取"
|
||||||
cardSlot: z.string().optional(),
|
cardSlot: z.string().optional(),
|
||||||
})
|
})
|
||||||
.optional(),
|
.optional(),
|
||||||
@@ -98,6 +135,10 @@ export const phoneSpecsSchema = z.object({
|
|||||||
type: z.string().optional(),
|
type: z.string().optional(),
|
||||||
model: z.string().optional(),
|
model: z.string().optional(),
|
||||||
size: z.string().optional(),
|
size: z.string().optional(),
|
||||||
|
volume: z.string().optional(), // 实际体积,如 "约 1.0 cm³"
|
||||||
|
resonance: z.string().optional(), // 谐振频率,如 "170 Hz"
|
||||||
|
grms: z.string().optional(), // 稳态振动量 @100g,如 "0.66 Grms"
|
||||||
|
transient: z.string().optional(), // 瞬态振动量 @10ms,如 "1.21 Gpp"
|
||||||
})
|
})
|
||||||
.optional(),
|
.optional(),
|
||||||
speakers: z
|
speakers: z
|
||||||
@@ -107,6 +148,8 @@ export const phoneSpecsSchema = z.object({
|
|||||||
units: z
|
units: z
|
||||||
.array(
|
.array(
|
||||||
z.object({
|
z.object({
|
||||||
|
position: z.enum(['top', 'bottom', 'left', 'right']).optional(),
|
||||||
|
label: z.string().optional(), // 自定义标识,如 "上" / "中置" / "第三单元"
|
||||||
model: z.string().optional(),
|
model: z.string().optional(),
|
||||||
size: z.string().optional(),
|
size: z.string().optional(),
|
||||||
power: z.string().optional(),
|
power: z.string().optional(),
|
||||||
@@ -122,11 +165,17 @@ export const phoneSpecsSchema = z.object({
|
|||||||
connectivity: z
|
connectivity: z
|
||||||
.object({
|
.object({
|
||||||
cellular: z.string().optional(),
|
cellular: z.string().optional(),
|
||||||
|
bands: z.array(z.string()).default([]), // 5G / LTE 频段
|
||||||
|
satellite: z.boolean().optional(),
|
||||||
|
satelliteProvider: z.string().optional(), // 天通 / 北斗 / 其他
|
||||||
|
satelliteBands: z.array(z.string()).default([]),
|
||||||
wifi: z.string().optional(),
|
wifi: z.string().optional(),
|
||||||
bluetooth: z.string().optional(),
|
bluetooth: z.string().optional(),
|
||||||
nfc: z.boolean().optional(),
|
nfc: z.boolean().optional(),
|
||||||
gps: z.string().optional(),
|
gps: z.string().optional(),
|
||||||
usb: z.string().optional(),
|
usb: z.string().optional(),
|
||||||
|
usbSpeed: z.string().optional(), // 实际速率,如 "5 Gbps"
|
||||||
|
usbVideoOut: z.boolean().optional(),
|
||||||
ir: z.boolean().optional(),
|
ir: z.boolean().optional(),
|
||||||
uwb: z.boolean().optional(),
|
uwb: z.boolean().optional(),
|
||||||
})
|
})
|
||||||
@@ -150,6 +199,7 @@ export const phoneSpecsSchema = z.object({
|
|||||||
barometer: z.boolean().optional(),
|
barometer: z.boolean().optional(),
|
||||||
colorSensor: z.boolean().optional(),
|
colorSensor: z.boolean().optional(),
|
||||||
flickerSensor: z.boolean().optional(),
|
flickerSensor: z.boolean().optional(),
|
||||||
|
list: z.array(z.string()).default([]), // 完整传感器清单
|
||||||
})
|
})
|
||||||
.optional(),
|
.optional(),
|
||||||
software: z
|
software: z
|
||||||
@@ -157,6 +207,41 @@ export const phoneSpecsSchema = z.object({
|
|||||||
launchVersion: z.string().optional(),
|
launchVersion: z.string().optional(),
|
||||||
currentVersion: z.string().optional(),
|
currentVersion: z.string().optional(),
|
||||||
updatePolicy: z.string().optional(),
|
updatePolicy: z.string().optional(),
|
||||||
|
updateTimeline: z.array(z.string()).default([]), // "2025-01-15 HyperOS 2.0(Android 15)"
|
||||||
|
})
|
||||||
|
.optional(),
|
||||||
|
/** 手机特点 / 卖点,面向列表摘要展示 */
|
||||||
|
features: z.array(z.string()).default([]),
|
||||||
|
/** 影像功能(跨镜头),如 "徕卡影像" / "4K@60fps HDR10+ 录像" */
|
||||||
|
cameraFeatures: z.array(z.string()).default([]),
|
||||||
|
/** 设备实测跑分,格式自由,如 "Geekbench 6 单核 2300" */
|
||||||
|
benchmarks: z.array(z.string()).default([]),
|
||||||
|
/** 初始售价,格式自由,如 "8GB+256GB 3999 元" */
|
||||||
|
pricing: z.array(z.string()).default([]),
|
||||||
|
officialUrl: z.string().optional(),
|
||||||
|
regulatoryModel: z.string().optional(), // 入网型号,如 "M154FF"
|
||||||
|
boxContents: z.array(z.string()).default([]), // 包装清单
|
||||||
|
service: z.string().optional(), // 售后服务政策
|
||||||
|
/** 酷安产品库的评分与同步信息(原始参数已映射进各规格字段) */
|
||||||
|
coolapk: z
|
||||||
|
.object({
|
||||||
|
productId: z.string(),
|
||||||
|
configId: z.string(),
|
||||||
|
name: z.string(),
|
||||||
|
price: z.string().optional(),
|
||||||
|
syncedAt: z.string().optional(),
|
||||||
|
rating: z
|
||||||
|
.object({
|
||||||
|
overall: z.number().optional(), // 所有人评分
|
||||||
|
owner: z.number().optional(), // 机主评分
|
||||||
|
battery: z.number().optional(), // 续航
|
||||||
|
camera: z.number().optional(), // 影像
|
||||||
|
performance: z.number().optional(), // 性能
|
||||||
|
display: z.number().optional(), // 屏幕
|
||||||
|
design: z.number().optional(), // 外观质感
|
||||||
|
value: z.number().optional(), // 性价比
|
||||||
|
})
|
||||||
|
.optional(),
|
||||||
})
|
})
|
||||||
.optional(),
|
.optional(),
|
||||||
extra: extraSchema,
|
extra: extraSchema,
|
||||||
|
|||||||
@@ -4,6 +4,19 @@ import { z } from 'zod';
|
|||||||
* SoC 详情。与设备 specs 分开维护,供多机型引用。
|
* SoC 详情。与设备 specs 分开维护,供多机型引用。
|
||||||
*/
|
*/
|
||||||
export const socDetailSchema = z.object({
|
export const socDetailSchema = z.object({
|
||||||
|
/** 概览:来自处理器档案的定位、年份、系列与热度 */
|
||||||
|
overview: z
|
||||||
|
.object({
|
||||||
|
nameEn: z.string().optional(),
|
||||||
|
nameZh: z.string().optional(),
|
||||||
|
series: z.string().optional(),
|
||||||
|
tier: z.string().optional(), // 旗舰 / 高端 / 中高端 / 中端 / 入门
|
||||||
|
tierScore: z.number().optional(),
|
||||||
|
releaseYear: z.number().optional(),
|
||||||
|
phoneCount: z.number().optional(),
|
||||||
|
source: z.string().optional(),
|
||||||
|
})
|
||||||
|
.optional(),
|
||||||
cpuClusters: z
|
cpuClusters: z
|
||||||
.array(
|
.array(
|
||||||
z.object({
|
z.object({
|
||||||
@@ -23,6 +36,18 @@ export const socDetailSchema = z.object({
|
|||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
.default([]),
|
.default([]),
|
||||||
|
cpuBlock: z
|
||||||
|
.object({
|
||||||
|
config: z.string().optional(),
|
||||||
|
arch: z.string().optional(),
|
||||||
|
archType: z.string().optional(), // 厂商自研 / 公版 ARM
|
||||||
|
maxFreq: z.string().optional(),
|
||||||
|
cores: z.number().optional(),
|
||||||
|
cacheL3: z.string().optional(),
|
||||||
|
systemCache: z.string().optional(),
|
||||||
|
note: z.string().optional(),
|
||||||
|
})
|
||||||
|
.optional(),
|
||||||
gpuBlock: z
|
gpuBlock: z
|
||||||
.object({
|
.object({
|
||||||
name: z.string().optional(), // "Adreno 750"
|
name: z.string().optional(), // "Adreno 750"
|
||||||
@@ -30,14 +55,18 @@ export const socDetailSchema = z.object({
|
|||||||
cores: z.number().optional(),
|
cores: z.number().optional(),
|
||||||
clockMax: z.string().optional(),
|
clockMax: z.string().optional(),
|
||||||
apis: z.array(z.string()).default([]),
|
apis: z.array(z.string()).default([]),
|
||||||
|
features: z.array(z.string()).default([]),
|
||||||
})
|
})
|
||||||
.optional(),
|
.optional(),
|
||||||
npuBlock: z
|
npuBlock: z
|
||||||
.object({
|
.object({
|
||||||
name: z.string().optional(),
|
name: z.string().optional(),
|
||||||
tops: z.string().optional(),
|
tops: z.string().optional(),
|
||||||
|
features: z.array(z.string()).default([]),
|
||||||
})
|
})
|
||||||
.optional(),
|
.optional(),
|
||||||
|
/** 系统缓存,如 "6 MB" */
|
||||||
|
systemCache: z.string().optional(),
|
||||||
ispBlock: z.string().optional(),
|
ispBlock: z.string().optional(),
|
||||||
dspBlock: z.string().optional(),
|
dspBlock: z.string().optional(),
|
||||||
modemBlock: z.string().optional(),
|
modemBlock: z.string().optional(),
|
||||||
@@ -50,12 +79,55 @@ export const socDetailSchema = z.object({
|
|||||||
.optional(),
|
.optional(),
|
||||||
storageSupport: z.string().optional(), // "UFS 4.0"
|
storageSupport: z.string().optional(), // "UFS 4.0"
|
||||||
displaySupport: z.string().optional(), // 最高分辨率/刷新率
|
displaySupport: z.string().optional(), // 最高分辨率/刷新率
|
||||||
|
displayBlock: z
|
||||||
|
.object({
|
||||||
|
maxResolution: z.string().optional(),
|
||||||
|
maxRefresh: z.string().optional(),
|
||||||
|
externalMax: z.string().optional(),
|
||||||
|
hdr: z.string().optional(),
|
||||||
|
colorDepth: z.string().optional(),
|
||||||
|
colorGamut: z.string().optional(),
|
||||||
|
})
|
||||||
|
.optional(),
|
||||||
|
cameraBlock: z
|
||||||
|
.object({
|
||||||
|
isp: z.string().optional(),
|
||||||
|
maxSensor: z.string().optional(),
|
||||||
|
videoCapture: z.string().optional(),
|
||||||
|
slowMotion: z.string().optional(),
|
||||||
|
features: z.array(z.string()).default([]),
|
||||||
|
})
|
||||||
|
.optional(),
|
||||||
|
connectivityBlock: z
|
||||||
|
.object({
|
||||||
|
wifi: z.string().optional(),
|
||||||
|
wifiStandard: z.string().optional(),
|
||||||
|
bluetooth: z.string().optional(),
|
||||||
|
peakSpeed: z.string().optional(),
|
||||||
|
})
|
||||||
|
.optional(),
|
||||||
videoCodec: z
|
videoCodec: z
|
||||||
.object({
|
.object({
|
||||||
encode: z.array(z.string()).default([]),
|
encode: z.array(z.string()).default([]),
|
||||||
decode: z.array(z.string()).default([]),
|
decode: z.array(z.string()).default([]),
|
||||||
})
|
})
|
||||||
.optional(),
|
.optional(),
|
||||||
|
benchmarkInfo: z
|
||||||
|
.object({
|
||||||
|
version: z.string().optional(),
|
||||||
|
cpuIndex: z.number().optional(),
|
||||||
|
cpuIndexNote: z.string().optional(),
|
||||||
|
note: z.string().optional(),
|
||||||
|
antutu: z
|
||||||
|
.object({
|
||||||
|
cpu: z.number().optional(),
|
||||||
|
gpu: z.number().optional(),
|
||||||
|
memory: z.number().optional(),
|
||||||
|
ux: z.number().optional(),
|
||||||
|
})
|
||||||
|
.optional(),
|
||||||
|
})
|
||||||
|
.optional(),
|
||||||
benchmarks: z
|
benchmarks: z
|
||||||
.array(
|
.array(
|
||||||
z.object({
|
z.object({
|
||||||
@@ -65,6 +137,11 @@ export const socDetailSchema = z.object({
|
|||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
.default([]),
|
.default([]),
|
||||||
|
traits: z.array(z.string()).default([]),
|
||||||
|
caveats: z.array(z.string()).default([]),
|
||||||
|
sourceUrls: z.array(z.string()).default([]),
|
||||||
|
/** 源站官方规格表(中文分组 -> 字段 -> 值),用于详情页完整参数折叠表 */
|
||||||
|
specGroups: z.record(z.string(), z.record(z.string(), z.string())).default({}),
|
||||||
extra: z.record(z.string(), z.string()).default({}),
|
extra: z.record(z.string(), z.string()).default({}),
|
||||||
});
|
});
|
||||||
export type SocDetail = z.infer<typeof socDetailSchema>;
|
export type SocDetail = z.infer<typeof socDetailSchema>;
|
||||||
@@ -0,0 +1,394 @@
|
|||||||
|
/**
|
||||||
|
* 手机字段注册表:表单渲染、AI 路径校验、字段标签都以此为单一事实来源。
|
||||||
|
* path 采用扁平写法,如 specs.display.size、specs.rearCamera[0].sensorModel。
|
||||||
|
*/
|
||||||
|
|
||||||
|
export type FieldKind = 'text' | 'bool' | 'number' | 'list';
|
||||||
|
|
||||||
|
export interface PhoneFieldDef {
|
||||||
|
key: string;
|
||||||
|
label: string;
|
||||||
|
kind?: FieldKind;
|
||||||
|
hint?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PhoneSpecSection {
|
||||||
|
section: string;
|
||||||
|
title: string;
|
||||||
|
fields: PhoneFieldDef[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export const PHONE_SPEC_SECTIONS: PhoneSpecSection[] = [
|
||||||
|
{
|
||||||
|
section: 'body',
|
||||||
|
title: '外观',
|
||||||
|
fields: [
|
||||||
|
{ key: 'dimensions', label: '尺寸', hint: '如 152.8 x 71.5 x 8.2 mm' },
|
||||||
|
{ key: 'weight', label: '重量', hint: '如 188 g' },
|
||||||
|
{ key: 'thicknessVariants', label: '厚度版本', kind: 'list', hint: '与首行不同的配色 / 形态厚度' },
|
||||||
|
{ key: 'weightVariants', label: '重量版本', kind: 'list', hint: '与首行不同的配色 / 形态重量' },
|
||||||
|
{ key: 'build.front', label: '正面材质' },
|
||||||
|
{ key: 'build.back', label: '背面材质' },
|
||||||
|
{ key: 'build.frame', label: '边框材质' },
|
||||||
|
{ key: 'sim', label: 'SIM' },
|
||||||
|
{ key: 'ipRating', label: '防护等级' },
|
||||||
|
{ key: 'colors', label: '配色', kind: 'list', hint: '英文逗号分隔' },
|
||||||
|
{ key: 'colorHexes', label: '配色色值', kind: 'list', hint: '与配色顺序一致,如 #1b1c1f,#d8dce2' },
|
||||||
|
{ key: 'buttons', label: '按键' },
|
||||||
|
{ key: 'cooling', label: '散热系统' },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
section: 'display',
|
||||||
|
title: '屏幕',
|
||||||
|
fields: [
|
||||||
|
{ key: 'size', label: '尺寸' },
|
||||||
|
{ key: 'resolution', label: '分辨率' },
|
||||||
|
{ key: 'cutout', label: '挖孔形态' },
|
||||||
|
{ key: 'aspectRatio', label: '比例' },
|
||||||
|
{ key: 'panel', label: '面板' },
|
||||||
|
{ key: 'vendor', label: '面板厂商' },
|
||||||
|
{ key: 'technology', label: '面板技术 / 代号' },
|
||||||
|
{ key: 'refreshRate', label: '刷新率' },
|
||||||
|
{ key: 'refreshRange', label: '刷新范围' },
|
||||||
|
{ key: 'refreshNote', label: '刷新附加说明', hint: '如 1-165Hz 自适应,185Hz 仅部分游戏生效' },
|
||||||
|
{ key: 'touchSampling', label: '触控采样率' },
|
||||||
|
{ key: 'touchSamplingInstant', label: '瞬时触控采样率' },
|
||||||
|
{ key: 'colorDepth', label: '色深' },
|
||||||
|
{ key: 'colorGamut', label: '色域' },
|
||||||
|
{ key: 'pixelDensity', label: '像素密度' },
|
||||||
|
{ key: 'equivalentPpi', label: '等效 PPI' },
|
||||||
|
{ key: 'screenBodyRatio', label: '屏占比' },
|
||||||
|
{ key: 'bezel', label: '边框宽度' },
|
||||||
|
{ key: 'width16x9', label: '16:9 等效尺寸' },
|
||||||
|
{ key: 'brightnessTypical', label: '典型亮度' },
|
||||||
|
{ key: 'brightnessPeak', label: '局部峰值亮度' },
|
||||||
|
{ key: 'brightnessGlobalPeak', label: '全局峰值亮度' },
|
||||||
|
{ key: 'hdr', label: 'HDR' },
|
||||||
|
{ key: 'protection', label: '保护玻璃' },
|
||||||
|
{ key: 'pwmDimming', label: '调光' },
|
||||||
|
{ key: 'alwaysOn', label: '息屏显示', kind: 'bool' },
|
||||||
|
{ key: 'features', label: '屏幕特性', kind: 'list' },
|
||||||
|
{ key: 'note', label: '其它附加说明' },
|
||||||
|
{ key: 'secondary.size', label: '副屏尺寸' },
|
||||||
|
{ key: 'secondary.resolution', label: '副屏分辨率' },
|
||||||
|
{ key: 'secondary.pixelDensity', label: '副屏像素密度' },
|
||||||
|
{ key: 'secondary.cutout', label: '副屏形态' },
|
||||||
|
{ key: 'secondary.panel', label: '副屏面板' },
|
||||||
|
{ key: 'secondary.vendor', label: '副屏厂商' },
|
||||||
|
{ key: 'secondary.technology', label: '副屏技术 / 代号' },
|
||||||
|
{ key: 'secondary.refreshRate', label: '副屏刷新率' },
|
||||||
|
{ key: 'secondary.refreshNote', label: '副屏刷新备注' },
|
||||||
|
{ key: 'secondary.touchSamplingInstant', label: '副屏瞬时触控' },
|
||||||
|
{ key: 'secondary.colorDepth', label: '副屏色深' },
|
||||||
|
{ key: 'secondary.colorGamut', label: '副屏色域' },
|
||||||
|
{ key: 'secondary.hdr', label: '副屏 HDR' },
|
||||||
|
{ key: 'secondary.protection', label: '副屏盖板' },
|
||||||
|
{ key: 'secondary.brightnessTypical', label: '副屏典型亮度' },
|
||||||
|
{ key: 'secondary.brightnessPeak', label: '副屏峰值亮度' },
|
||||||
|
{ key: 'secondary.brightnessGlobalPeak', label: '副屏全局峰值亮度' },
|
||||||
|
{ key: 'secondary.pwmDimming', label: '副屏调光' },
|
||||||
|
{ key: 'secondary.features', label: '副屏特性', kind: 'list' },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
section: 'platform',
|
||||||
|
title: '平台',
|
||||||
|
fields: [
|
||||||
|
{ key: 'os', label: '系统' },
|
||||||
|
{ key: 'skin', label: '定制 UI' },
|
||||||
|
{ key: 'chipset', label: '芯片展示名', hint: '权威引用在基本信息里的 SoC' },
|
||||||
|
{ key: 'socBrand', label: 'SoC 品牌', hint: '高通 / 联发科 / 苹果' },
|
||||||
|
{ key: 'gpu', label: 'GPU' },
|
||||||
|
{ key: 'coprocessor', label: '协处理器', hint: '独显芯片 / 影像芯片等' },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
section: 'memory',
|
||||||
|
title: '内存与存储',
|
||||||
|
fields: [
|
||||||
|
{ key: 'ram', label: '内存' },
|
||||||
|
{ key: 'ramType', label: '内存类型' },
|
||||||
|
{ key: 'storage', label: '存储' },
|
||||||
|
{ key: 'storageType', label: '存储类型' },
|
||||||
|
{ key: 'storageSpeed', label: '存储速度' },
|
||||||
|
{ key: 'cardSlot', label: '存储卡' },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
section: 'vibration',
|
||||||
|
title: '振动',
|
||||||
|
fields: [
|
||||||
|
{ key: 'type', label: '马达类型' },
|
||||||
|
{ key: 'model', label: '马达型号' },
|
||||||
|
{ key: 'size', label: '马达尺寸' },
|
||||||
|
{ key: 'volume', label: '马达体积' },
|
||||||
|
{ key: 'resonance', label: '谐振频率' },
|
||||||
|
{ key: 'grms', label: '稳态振动量' },
|
||||||
|
{ key: 'transient', label: '瞬态振动量' },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
section: 'connectivity',
|
||||||
|
title: '连接',
|
||||||
|
fields: [
|
||||||
|
{ key: 'cellular', label: '蜂窝' },
|
||||||
|
{ key: 'bands', label: '移动网络频段', kind: 'list' },
|
||||||
|
{ key: 'satellite', label: '卫星通信', kind: 'bool' },
|
||||||
|
{ key: 'satelliteProvider', label: '卫星服务商' },
|
||||||
|
{ key: 'satelliteBands', label: '卫星频段', kind: 'list' },
|
||||||
|
{ key: 'wifi', label: 'Wi-Fi' },
|
||||||
|
{ key: 'bluetooth', label: '蓝牙' },
|
||||||
|
{ key: 'nfc', label: 'NFC', kind: 'bool' },
|
||||||
|
{ key: 'gps', label: '定位' },
|
||||||
|
{ key: 'usb', label: 'USB' },
|
||||||
|
{ key: 'usbSpeed', label: 'USB 实际速率' },
|
||||||
|
{ key: 'usbVideoOut', label: 'USB 视频输出', kind: 'bool' },
|
||||||
|
{ key: 'ir', label: '红外', kind: 'bool' },
|
||||||
|
{ key: 'uwb', label: 'UWB', kind: 'bool' },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
section: 'battery',
|
||||||
|
title: '电池与充电',
|
||||||
|
fields: [
|
||||||
|
{ key: 'capacity', label: '容量' },
|
||||||
|
{ key: 'type', label: '电池类型' },
|
||||||
|
{ key: 'wired', label: '有线充电' },
|
||||||
|
{ key: 'wireless', label: '无线充电' },
|
||||||
|
{ key: 'reverse', label: '反向充电' },
|
||||||
|
{ key: 'chargingProtocol', label: '充电协议' },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
section: 'sensors',
|
||||||
|
title: '传感器',
|
||||||
|
fields: [
|
||||||
|
{ key: 'fingerprint', label: '指纹' },
|
||||||
|
{ key: 'fingerprintType', label: '指纹类型' },
|
||||||
|
{ key: 'fingerprintPosition', label: '指纹位置' },
|
||||||
|
{ key: 'gyro', label: '陀螺仪', kind: 'bool' },
|
||||||
|
{ key: 'barometer', label: '气压计', kind: 'bool' },
|
||||||
|
{ key: 'colorSensor', label: '色温传感器', kind: 'bool' },
|
||||||
|
{ key: 'flickerSensor', label: '闪烁传感器', kind: 'bool' },
|
||||||
|
{ key: 'list', label: '传感器清单', kind: 'list' },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
section: 'software',
|
||||||
|
title: '系统与更新',
|
||||||
|
fields: [
|
||||||
|
{ key: 'launchVersion', label: '出厂版本' },
|
||||||
|
{ key: 'currentVersion', label: '当前版本' },
|
||||||
|
{ key: 'updatePolicy', label: '更新策略' },
|
||||||
|
{ key: 'updateTimeline', label: '更新记录', kind: 'list' },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
export const CAMERA_POSITIONS = [
|
||||||
|
'wide',
|
||||||
|
'ultrawide',
|
||||||
|
'tele',
|
||||||
|
'periscope',
|
||||||
|
'macro',
|
||||||
|
'depth',
|
||||||
|
'mono',
|
||||||
|
'color',
|
||||||
|
'front',
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
export const CAMERA_FIELDS: PhoneFieldDef[] = [
|
||||||
|
{ key: 'sensorModel', label: '传感器型号' },
|
||||||
|
{ key: 'sensorAlias', label: '传感器营销名' },
|
||||||
|
{ key: 'resolution', label: '像素' },
|
||||||
|
{ key: 'aperture', label: '光圈' },
|
||||||
|
{ key: 'focalLength', label: '等效焦距' },
|
||||||
|
{ key: 'sensorSize', label: '传感器尺寸' },
|
||||||
|
{ key: 'pixelSize', label: '单像素尺寸' },
|
||||||
|
{ key: 'lensElements', label: '镜片' },
|
||||||
|
{ key: 'fov', label: '视场角' },
|
||||||
|
{ key: 'ois', label: 'OIS', kind: 'bool' },
|
||||||
|
{ key: 'eis', label: 'EIS', kind: 'bool' },
|
||||||
|
{ key: 'cipa', label: 'CIPA 防抖等级', hint: '如 CIPA 7.0' },
|
||||||
|
{ key: 'telephotoStructure', label: '长焦结构', hint: '潜望式 / 直立式' },
|
||||||
|
{ key: 'telephotoMacro', label: '长焦微距', kind: 'bool' },
|
||||||
|
{ key: 'telephotoMacroDistance', label: '长焦微距距离', hint: '如 12cm' },
|
||||||
|
{ key: 'zoom', label: '变焦' },
|
||||||
|
{ key: 'autofocusType', label: '对焦方式' },
|
||||||
|
{ key: 'video.max', label: '最高视频' },
|
||||||
|
{ key: 'video.stabilization', label: '视频防抖' },
|
||||||
|
{ key: 'flash', label: '闪光灯' },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const SPEAKERS_FIELDS: PhoneFieldDef[] = [
|
||||||
|
{ key: 'count', label: '数量', kind: 'number' },
|
||||||
|
{ key: 'stereo', label: '立体声', kind: 'bool' },
|
||||||
|
{ key: 'dolbyAtmos', label: '杜比全景声', kind: 'bool' },
|
||||||
|
{ key: 'hiRes', label: 'Hi-Res', kind: 'bool' },
|
||||||
|
{ key: 'headphoneJack', label: '耳机孔', kind: 'bool' },
|
||||||
|
{ key: 'loudnessDba', label: '响度' },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const SPEAKER_UNIT_FIELDS: PhoneFieldDef[] = [
|
||||||
|
{ key: 'label', label: '单元标识', hint: '如 上 / 下 / 中置' },
|
||||||
|
{ key: 'model', label: '单元型号' },
|
||||||
|
{ key: 'size', label: '尺寸' },
|
||||||
|
{ key: 'power', label: '功率' },
|
||||||
|
];
|
||||||
|
|
||||||
|
/** 不属于某个 specs 子对象、直接挂在 specs 下的补充字段 */
|
||||||
|
export const PHONE_TOP_LEVEL_FIELDS: PhoneFieldDef[] = [
|
||||||
|
{ key: 'features', label: '手机特点', kind: 'list' },
|
||||||
|
{ key: 'cameraFeatures', label: '影像功能', kind: 'list' },
|
||||||
|
{ key: 'benchmarks', label: '设备跑分', kind: 'list' },
|
||||||
|
{ key: 'pricing', label: '初始售价', kind: 'list' },
|
||||||
|
{ key: 'officialUrl', label: '官网' },
|
||||||
|
{ key: 'regulatoryModel', label: '入网型号' },
|
||||||
|
{ key: 'boxContents', label: '包装清单', kind: 'list' },
|
||||||
|
{ key: 'service', label: '售后服务' },
|
||||||
|
];
|
||||||
|
|
||||||
|
/* ------------------------------- 路径工具 ------------------------------- */
|
||||||
|
|
||||||
|
/** `specs.rearCamera[2].ois` -> ['specs','rearCamera',2,'ois'] */
|
||||||
|
export function pathSegments(path: string): (string | number)[] {
|
||||||
|
return path
|
||||||
|
.replace(/\[(\d+)\]/g, '.$1')
|
||||||
|
.split('.')
|
||||||
|
.filter(Boolean)
|
||||||
|
.map((segment) => (/^\d+$/.test(segment) ? Number(segment) : segment));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getValueAtPath(source: unknown, path: string): unknown {
|
||||||
|
let cursor: unknown = source;
|
||||||
|
for (const key of pathSegments(path)) {
|
||||||
|
if (cursor === null || cursor === undefined || typeof cursor !== 'object') return undefined;
|
||||||
|
cursor = (cursor as Record<string | number, unknown>)[key];
|
||||||
|
}
|
||||||
|
return cursor;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 不可变写入;空字符串/undefined 视为删除。数组下标会自动补空对象。 */
|
||||||
|
export function setValueAtPath<T>(source: T, path: string, value: unknown): T {
|
||||||
|
const keys = pathSegments(path);
|
||||||
|
if (keys.length === 0) return source;
|
||||||
|
|
||||||
|
const clone = structuredClone(source);
|
||||||
|
let cursor = clone as unknown as Record<string | number, unknown>;
|
||||||
|
|
||||||
|
for (let index = 0; index < keys.length - 1; index += 1) {
|
||||||
|
const key = keys[index];
|
||||||
|
const nextKey = keys[index + 1];
|
||||||
|
let next = cursor[key];
|
||||||
|
if (next === null || next === undefined || typeof next !== 'object') {
|
||||||
|
next = typeof nextKey === 'number' ? [] : {};
|
||||||
|
cursor[key] = next;
|
||||||
|
}
|
||||||
|
if (Array.isArray(next) && typeof nextKey === 'number') {
|
||||||
|
for (let slot = 0; slot <= nextKey; slot += 1) {
|
||||||
|
if (next[slot] === null || next[slot] === undefined || typeof next[slot] !== 'object') {
|
||||||
|
next[slot] = {};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cursor = next as Record<string | number, unknown>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const last = keys[keys.length - 1];
|
||||||
|
if (value === undefined || value === '') {
|
||||||
|
if (Array.isArray(cursor) && typeof last === 'number') cursor.splice(last, 1);
|
||||||
|
else delete cursor[last];
|
||||||
|
} else {
|
||||||
|
cursor[last] = value;
|
||||||
|
}
|
||||||
|
return clone;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function hasValueAtPath(source: unknown, path: string): boolean {
|
||||||
|
const value = getValueAtPath(source, path);
|
||||||
|
if (value === undefined || value === null || value === '') return false;
|
||||||
|
if (Array.isArray(value) && value.length === 0) return false;
|
||||||
|
if (typeof value === 'object' && !Array.isArray(value) && Object.keys(value).length === 0) return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ----------------------------- 路径 -> 字段信息 ----------------------------- */
|
||||||
|
|
||||||
|
export interface ResolvedFieldSpec {
|
||||||
|
kind: FieldKind | 'position';
|
||||||
|
label: string;
|
||||||
|
allowedValues?: readonly string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
const scalarSpecs = new Map<string, ResolvedFieldSpec>();
|
||||||
|
|
||||||
|
for (const section of PHONE_SPEC_SECTIONS) {
|
||||||
|
for (const field of section.fields) {
|
||||||
|
scalarSpecs.set(`specs.${section.section}.${field.key}`, {
|
||||||
|
kind: field.kind ?? 'text',
|
||||||
|
label: `${section.title} · ${field.label}`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const field of SPEAKERS_FIELDS) {
|
||||||
|
scalarSpecs.set(`specs.speakers.${field.key}`, {
|
||||||
|
kind: field.kind ?? 'text',
|
||||||
|
label: `扬声器 · ${field.label}`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const field of PHONE_TOP_LEVEL_FIELDS) {
|
||||||
|
scalarSpecs.set(`specs.${field.key}`, {
|
||||||
|
kind: field.kind ?? 'text',
|
||||||
|
label: `设备 · ${field.label}`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
for (let index = 0; index < 5; index += 1) {
|
||||||
|
for (const field of SPEAKER_UNIT_FIELDS) {
|
||||||
|
scalarSpecs.set(`specs.speakers.units[${index}].${field.key}`, {
|
||||||
|
kind: 'text',
|
||||||
|
label: `扬声器单元 ${index + 1} · ${field.label}`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const cameraFieldMap = new Map<string, PhoneFieldDef>(CAMERA_FIELDS.map((field) => [field.key, field]));
|
||||||
|
|
||||||
|
export function resolveFieldPath(path: string): ResolvedFieldSpec | null {
|
||||||
|
const scalar = scalarSpecs.get(path);
|
||||||
|
if (scalar) return scalar;
|
||||||
|
|
||||||
|
const cameraMatch = /^specs\.(rearCamera|frontCamera)\[(\d+)\]\.(.+)$/.exec(path);
|
||||||
|
if (cameraMatch) {
|
||||||
|
const [, kind, indexText, key] = cameraMatch;
|
||||||
|
const index = Number(indexText);
|
||||||
|
if (kind === 'rearCamera' && index > 3) return null;
|
||||||
|
if (kind === 'frontCamera' && index > 1) return null;
|
||||||
|
|
||||||
|
if (key === 'position') {
|
||||||
|
return {
|
||||||
|
kind: 'position',
|
||||||
|
label: `${kind === 'rearCamera' ? '后置' : '前置'}影像 ${index + 1} · 位置`,
|
||||||
|
allowedValues: CAMERA_POSITIONS,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (key === 'video.modes') {
|
||||||
|
return { kind: 'list', label: `${kind === 'rearCamera' ? '后置' : '前置'}影像 ${index + 1} · 视频模式` };
|
||||||
|
}
|
||||||
|
const field = cameraFieldMap.get(key);
|
||||||
|
if (!field) return null;
|
||||||
|
return {
|
||||||
|
kind: field.kind ?? 'text',
|
||||||
|
label: `${kind === 'rearCamera' ? '后置' : '前置'}影像 ${index + 1} · ${field.label}`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function fieldLabelForPath(path: string): string {
|
||||||
|
return resolveFieldPath(path)?.label ?? path;
|
||||||
|
}
|
||||||
@@ -1,5 +1,8 @@
|
|||||||
import { mkdir, rm, writeFile } from 'node:fs/promises';
|
import { mkdir, rm, writeFile } from 'node:fs/promises';
|
||||||
import { join } from 'node:path';
|
import { join } from 'node:path';
|
||||||
|
import { loadEnv } from './env';
|
||||||
|
|
||||||
|
loadEnv();
|
||||||
|
|
||||||
export interface StorageDriver {
|
export interface StorageDriver {
|
||||||
put(key: string, buf: Uint8Array, contentType: string): Promise<void>;
|
put(key: string, buf: Uint8Array, contentType: string): Promise<void>;
|
||||||
|
|||||||
@@ -4,3 +4,92 @@ import { twMerge } from 'tailwind-merge';
|
|||||||
export function cn(...inputs: ClassValue[]) {
|
export function cn(...inputs: ClassValue[]) {
|
||||||
return twMerge(clsx(inputs));
|
return twMerge(clsx(inputs));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 品牌中文名:只收录有通用中文叫法的品牌,展示为「中文 English」 */
|
||||||
|
const BRAND_ZH: Record<string, string> = {
|
||||||
|
Huawei: '华为',
|
||||||
|
Honor: '荣耀',
|
||||||
|
realme: '真我',
|
||||||
|
Redmi: '红米',
|
||||||
|
nubia: '努比亚',
|
||||||
|
Xiaomi: '小米',
|
||||||
|
Motorola: '摩托罗拉',
|
||||||
|
OnePlus: '一加',
|
||||||
|
Apple: '苹果',
|
||||||
|
Samsung: '三星',
|
||||||
|
Meizu: '魅族',
|
||||||
|
ROG: '玩家国度',
|
||||||
|
ZTE: '中兴',
|
||||||
|
Gionee: '金立',
|
||||||
|
Coolpad: '酷派',
|
||||||
|
Maimang: '麦芒',
|
||||||
|
'NIO Phone': '蔚来',
|
||||||
|
'Lenovo Legion': '联想拯救者',
|
||||||
|
'Moondrop MIAD': '水月雨',
|
||||||
|
Philips: '飞利浦',
|
||||||
|
Sony: '索尼',
|
||||||
|
Qin: '多亲',
|
||||||
|
BlackShark: '黑鲨',
|
||||||
|
Smartisan: '坚果',
|
||||||
|
Nokia: '诺基亚',
|
||||||
|
Meitu: '美图',
|
||||||
|
Hisense: '海信',
|
||||||
|
RayNeo: '雷鸟',
|
||||||
|
Royole: '柔宇',
|
||||||
|
ASUS: '华硕',
|
||||||
|
Tianyi: '天翼',
|
||||||
|
BlueFox: '蓝狐',
|
||||||
|
Lenovo: '联想',
|
||||||
|
BlackBerry: '黑莓',
|
||||||
|
Sharp: '夏普',
|
||||||
|
// 芯片品牌
|
||||||
|
Qualcomm: '高通',
|
||||||
|
MediaTek: '联发科',
|
||||||
|
HiSilicon: '海思',
|
||||||
|
Google: '谷歌',
|
||||||
|
UNISOC: '紫光展锐',
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 品牌展示名,如「一加 OnePlus」;无中文名的品牌原样返回 */
|
||||||
|
export function brandLabel(brand: string): string {
|
||||||
|
const name = brand.trim();
|
||||||
|
const zh = BRAND_ZH[name];
|
||||||
|
return zh ? `${zh} ${name}` : name;
|
||||||
|
}
|
||||||
|
|
||||||
|
function escapeRegExp(value: string): string {
|
||||||
|
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||||
|
}
|
||||||
|
|
||||||
|
function startsWithName(value: string, prefix: string): boolean {
|
||||||
|
return new RegExp(`^${escapeRegExp(prefix)}(\\s+|$)`, 'i').test(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 机型名称拆分:型号本身已带品牌(如「Xiaomi 14」)时去掉前缀,
|
||||||
|
* 避免组合后出现「小米 Xiaomi Xiaomi 14」;品牌统一用中英文展示名。
|
||||||
|
*/
|
||||||
|
export function deviceNameParts(brand: string, model: string): { brand: string; model: string } {
|
||||||
|
const brandName = brand.trim();
|
||||||
|
const modelName = model.trim();
|
||||||
|
if (!brandName) return { brand: '', model: modelName };
|
||||||
|
|
||||||
|
const label = brandLabel(brandName);
|
||||||
|
const zh = BRAND_ZH[brandName];
|
||||||
|
const prefix = [brandName, zh].find((item) => item && startsWithName(modelName, item));
|
||||||
|
if (!prefix) return { brand: label, model: modelName };
|
||||||
|
|
||||||
|
const rest = modelName.slice(prefix.length).trim();
|
||||||
|
return rest ? { brand: label, model: rest } : { brand: '', model: modelName };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 完整机型名,如「一加 OnePlus 16」 */
|
||||||
|
export function deviceTitle(brand: string, model: string): string {
|
||||||
|
const parts = deviceNameParts(brand, model);
|
||||||
|
return parts.brand ? `${parts.brand} ${parts.model}` : parts.model;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 芯片名,如「高通 Qualcomm 骁龙8 Elite」 */
|
||||||
|
export function chipTitle(brand: string, model: string): string {
|
||||||
|
return deviceTitle(brand, model);
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import { defineMiddleware } from 'astro:middleware';
|
||||||
|
import { isAuthed } from '@/lib/auth';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* /admin 本身同时是登录页与仪表盘,由页面自行判断;
|
||||||
|
* /admin/** 的其余页面在中间件层拦截,未登录直接跳回登录入口。
|
||||||
|
*/
|
||||||
|
export const onRequest = defineMiddleware(async (context, next) => {
|
||||||
|
const { pathname } = context.url;
|
||||||
|
if (pathname.startsWith('/admin/') && !(await isAuthed(context.cookies))) {
|
||||||
|
const next = pathname + context.url.search;
|
||||||
|
return context.redirect(`/admin?next=${encodeURIComponent(next)}`);
|
||||||
|
}
|
||||||
|
return next();
|
||||||
|
});
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
---
|
||||||
|
import BaseLayout from '@/layouts/BaseLayout.astro';
|
||||||
|
import BilibiliSetup from '@/components/admin/BilibiliSetup';
|
||||||
|
import { BILIBILI_SESSDATA_KEY, getBilibiliSessdata } from '@/lib/bilibili';
|
||||||
|
import { getSetting } from '@/lib/repo';
|
||||||
|
|
||||||
|
// 中间件已保证 /admin/** 需登录
|
||||||
|
const envConfigured = Boolean(process.env.BILIBILI_SESSDATA?.trim());
|
||||||
|
const savedAt = getSetting(`${BILIBILI_SESSDATA_KEY}_saved_at`) ?? undefined;
|
||||||
|
const bound = Boolean(getBilibiliSessdata());
|
||||||
|
---
|
||||||
|
|
||||||
|
<BaseLayout title="B 站绑定 · LFSpecs">
|
||||||
|
<div class="mx-auto mt-8 max-w-2xl">
|
||||||
|
<header class="flex flex-wrap items-center justify-between gap-3">
|
||||||
|
<div>
|
||||||
|
<h1 class="text-2xl font-semibold tracking-tight">B 站绑定</h1>
|
||||||
|
<p class="mt-1 text-xs text-muted-foreground">
|
||||||
|
用于 AI 补全拉取拆机视频字幕(马达 / 扬声器单元等内部参数的主要来源)
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<a
|
||||||
|
href="/admin"
|
||||||
|
class="text-sm text-muted-foreground transition-colors hover:text-foreground"
|
||||||
|
>
|
||||||
|
返回后台
|
||||||
|
</a>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<section class="mt-6 rounded-lg border border-border bg-card p-5">
|
||||||
|
<BilibiliSetup
|
||||||
|
client:load
|
||||||
|
bound={bound && !envConfigured}
|
||||||
|
envConfigured={envConfigured}
|
||||||
|
savedAt={savedAt}
|
||||||
|
/>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</BaseLayout>
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
---
|
||||||
|
import BaseLayout from '@/layouts/BaseLayout.astro';
|
||||||
|
import ChipEditor from '@/components/admin/ChipEditor.tsx';
|
||||||
|
import { getChip, getChipId, listRevisions } from '@/lib/repo';
|
||||||
|
|
||||||
|
const slug = Astro.params.slug ?? '';
|
||||||
|
const isNew = slug === 'new';
|
||||||
|
const chip = isNew ? undefined : getChip(slug);
|
||||||
|
if (!isNew && !chip) {
|
||||||
|
return new Response('未找到该芯片', { status: 404 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const id = chip ? getChipId(chip.slug) : undefined;
|
||||||
|
const revisions = id ? listRevisions('chip', id, 10) : [];
|
||||||
|
const saved = Astro.url.searchParams.get('saved') === '1';
|
||||||
|
|
||||||
|
function formatTime(iso: string): string {
|
||||||
|
return new Intl.DateTimeFormat('zh-CN', {
|
||||||
|
dateStyle: 'medium',
|
||||||
|
timeStyle: 'short',
|
||||||
|
timeZone: 'Asia/Shanghai',
|
||||||
|
}).format(new Date(iso));
|
||||||
|
}
|
||||||
|
---
|
||||||
|
|
||||||
|
<BaseLayout title={isNew ? '新增芯片 · LFSpecs' : `${chip?.model ?? ''} 编辑 · LFSpecs`}>
|
||||||
|
<nav class="text-xs text-muted-foreground">
|
||||||
|
<a href="/admin" class="hover:text-foreground">编辑后台</a>
|
||||||
|
<span class="mx-1.5">/</span>
|
||||||
|
<span class="text-foreground">{isNew ? '新增芯片' : chip?.model}</span>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<header class="mt-3 flex flex-wrap items-baseline justify-between gap-3">
|
||||||
|
<h1 class="text-2xl font-semibold tracking-tight">{isNew ? '新增芯片' : '编辑芯片'}</h1>
|
||||||
|
{!isNew && chip && <span class="font-mono text-xs text-muted-foreground">{chip.slug}</span>}
|
||||||
|
</header>
|
||||||
|
|
||||||
|
{
|
||||||
|
saved && (
|
||||||
|
<p class="mt-4 rounded-md border border-primary/40 bg-primary/10 px-3 py-2 text-sm text-primary">
|
||||||
|
{isNew ? '创建成功。' : '已保存,修订记录已写入。'}
|
||||||
|
</p>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
<ChipEditor client:load initial={chip ?? null} isNew={isNew} />
|
||||||
|
|
||||||
|
{
|
||||||
|
!isNew && (
|
||||||
|
<section class="mt-10">
|
||||||
|
<h2 class="text-sm font-semibold">修订记录</h2>
|
||||||
|
<ul class="mt-3 divide-y divide-border/60 rounded-lg border border-border bg-card">
|
||||||
|
{revisions.map((revision) => (
|
||||||
|
<li class="flex flex-wrap items-center justify-between gap-2 px-4 py-2.5 text-xs">
|
||||||
|
<span class="font-mono text-[10px] text-muted-foreground">#{revision.id}</span>
|
||||||
|
<span class="tabular text-muted-foreground">{formatTime(revision.createdAt)}</span>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
{revisions.length === 0 && (
|
||||||
|
<li class="px-4 py-6 text-center text-sm text-muted-foreground">暂无修订记录。</li>
|
||||||
|
)}
|
||||||
|
</ul>
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
</BaseLayout>
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
---
|
||||||
|
import BaseLayout from '@/layouts/BaseLayout.astro';
|
||||||
|
import DeviceEditor from '@/components/admin/DeviceEditor.tsx';
|
||||||
|
import DeviceQuickCreate from '@/components/admin/DeviceQuickCreate.tsx';
|
||||||
|
import { getDevice, getDeviceId, listChips, listRevisions } from '@/lib/repo';
|
||||||
|
|
||||||
|
const slug = Astro.params.slug ?? '';
|
||||||
|
const isNew = slug === 'new';
|
||||||
|
const device = isNew ? undefined : getDevice(slug);
|
||||||
|
if (!isNew && !device) {
|
||||||
|
return new Response('未找到该设备', { status: 404 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const socOptions = listChips({ type: 'soc' }).map((chip) => ({
|
||||||
|
slug: chip.slug,
|
||||||
|
label: `${chip.brand} ${chip.model}`,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const id = device ? getDeviceId(device.slug) : undefined;
|
||||||
|
const revisions = id ? listRevisions('device', id, 10) : [];
|
||||||
|
const saved = Astro.url.searchParams.get('saved') === '1';
|
||||||
|
const created = Astro.url.searchParams.get('created') === '1';
|
||||||
|
|
||||||
|
function formatTime(iso: string): string {
|
||||||
|
return new Intl.DateTimeFormat('zh-CN', {
|
||||||
|
dateStyle: 'medium',
|
||||||
|
timeStyle: 'short',
|
||||||
|
timeZone: 'Asia/Shanghai',
|
||||||
|
}).format(new Date(iso));
|
||||||
|
}
|
||||||
|
---
|
||||||
|
|
||||||
|
<BaseLayout title={isNew ? '新增设备 · LFSpecs' : `${device?.model ?? ''} 编辑 · LFSpecs`}>
|
||||||
|
<nav class="text-xs text-muted-foreground">
|
||||||
|
<a href="/admin" class="hover:text-foreground">编辑后台</a>
|
||||||
|
<span class="mx-1.5">/</span>
|
||||||
|
<span class="text-foreground">{isNew ? '新增设备' : device?.model}</span>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<header class="mt-3 flex flex-wrap items-baseline justify-between gap-3">
|
||||||
|
<h1 class="text-2xl font-semibold tracking-tight">{isNew ? '新增设备' : '编辑设备'}</h1>
|
||||||
|
{!isNew && device && (
|
||||||
|
<span class="font-mono text-xs text-muted-foreground">{device.slug}</span>
|
||||||
|
)}
|
||||||
|
</header>
|
||||||
|
|
||||||
|
{
|
||||||
|
(saved || created) && (
|
||||||
|
<p class="mt-4 rounded-md border border-primary/40 bg-primary/10 px-3 py-2 text-sm text-primary">
|
||||||
|
{created ? 'AI 初稿已创建,请逐项核对后保存。' : isNew ? '创建成功。' : '已保存,修订记录已写入。'}
|
||||||
|
</p>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
isNew ? (
|
||||||
|
<DeviceQuickCreate client:load />
|
||||||
|
) : (
|
||||||
|
<DeviceEditor
|
||||||
|
client:load
|
||||||
|
initial={device ?? null}
|
||||||
|
socOptions={socOptions}
|
||||||
|
isNew={false}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
!isNew && (
|
||||||
|
<section class="mt-10">
|
||||||
|
<h2 class="text-sm font-semibold">修订记录</h2>
|
||||||
|
<ul class="mt-3 divide-y divide-border/60 rounded-lg border border-border bg-card">
|
||||||
|
{revisions.map((revision) => (
|
||||||
|
<li class="flex flex-wrap items-center justify-between gap-2 px-4 py-2.5 text-xs">
|
||||||
|
<span class="font-mono text-[10px] text-muted-foreground">#{revision.id}</span>
|
||||||
|
<span class="tabular text-muted-foreground">{formatTime(revision.createdAt)}</span>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
{revisions.length === 0 && (
|
||||||
|
<li class="px-4 py-6 text-center text-sm text-muted-foreground">暂无修订记录。</li>
|
||||||
|
)}
|
||||||
|
</ul>
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
</BaseLayout>
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
---
|
||||||
|
import BaseLayout from '@/layouts/BaseLayout.astro';
|
||||||
|
import ImportPanel from '@/components/admin/ImportPanel.tsx';
|
||||||
|
---
|
||||||
|
|
||||||
|
<BaseLayout title="导入数据 · LFSpecs">
|
||||||
|
<nav class="text-xs text-muted-foreground">
|
||||||
|
<a href="/admin" class="hover:text-foreground">编辑后台</a>
|
||||||
|
<span class="mx-1.5">/</span>
|
||||||
|
<span class="text-foreground">导入</span>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<header class="mt-3 flex flex-wrap items-baseline justify-between gap-3">
|
||||||
|
<h1 class="text-2xl font-semibold tracking-tight">导入数据</h1>
|
||||||
|
<a href="/api/export" class="text-xs text-primary hover:underline">
|
||||||
|
导出当前数据
|
||||||
|
</a>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<p class="mt-2 max-w-3xl text-sm text-muted-foreground">
|
||||||
|
接受 <code class="font-mono text-foreground/80">formatVersion: 1</code> 的完整导出文件。
|
||||||
|
导入按 slug upsert:已存在的 slug 会被覆盖,未出现在文件里的设备不会被删除。
|
||||||
|
图片不包含在 JSON 中,请随 <code class="font-mono text-foreground/80">data/uploads</code> 一起迁移。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<ImportPanel client:load />
|
||||||
|
|
||||||
|
<section class="mt-8 rounded-lg border border-border bg-card p-5 text-xs text-muted-foreground">
|
||||||
|
<h2 class="text-sm font-semibold text-foreground">导入文件结构</h2>
|
||||||
|
<pre class="mt-3 overflow-x-auto rounded-md border border-border bg-background p-3 font-mono text-[11px] text-foreground/80">{`{
|
||||||
|
"formatVersion": 1,
|
||||||
|
"devices": [ { "slug": "xiaomi-14", "category": "phone", ... } ],
|
||||||
|
"chips": [ { "slug": "snapdragon-8-gen-3", "type": "soc", ... } ]
|
||||||
|
}`}</pre>
|
||||||
|
<p class="mt-3">
|
||||||
|
整批数据会先经过 zod 校验;只要有一条不合法就整批拒绝,不会写入半份数据。
|
||||||
|
</p>
|
||||||
|
</section>
|
||||||
|
</BaseLayout>
|
||||||
@@ -0,0 +1,415 @@
|
|||||||
|
---
|
||||||
|
import Pagination from '@/components/Pagination.astro';
|
||||||
|
import BaseLayout from '@/layouts/BaseLayout.astro';
|
||||||
|
import { authConfigured, isAuthed } from '@/lib/auth';
|
||||||
|
import {
|
||||||
|
countDevices,
|
||||||
|
listBrands,
|
||||||
|
listChips,
|
||||||
|
listDevicesPaged,
|
||||||
|
listRecentRevisions,
|
||||||
|
type DeviceSort,
|
||||||
|
} from '@/lib/repo';
|
||||||
|
import { brandLabel } from '@/lib/utils';
|
||||||
|
|
||||||
|
const authed = await isAuthed(Astro.cookies);
|
||||||
|
const errorKey = Astro.url.searchParams.get('error');
|
||||||
|
const next = Astro.url.searchParams.get('next') ?? '/admin';
|
||||||
|
|
||||||
|
const errorMessages: Record<string, string> = {
|
||||||
|
config: '尚未配置 ADMIN_PASSWORD / SESSION_SECRET,请在 .env 中填写后重启服务。',
|
||||||
|
rate: '尝试过于频繁,请等待一分钟后再试。',
|
||||||
|
invalid: '密码错误。',
|
||||||
|
};
|
||||||
|
|
||||||
|
const PAGE_SIZE = 30;
|
||||||
|
|
||||||
|
const params = Astro.url.searchParams;
|
||||||
|
const q = (params.get('q') ?? '').trim();
|
||||||
|
const brand = params.get('brand') ?? undefined;
|
||||||
|
const review = params.get('review') === 'low';
|
||||||
|
const sortParam = params.get('sort') ?? 'updated';
|
||||||
|
const sort: DeviceSort = ['latest', 'name', 'brand', 'updated'].includes(sortParam)
|
||||||
|
? (sortParam as DeviceSort)
|
||||||
|
: 'updated';
|
||||||
|
const pageParam = Number.parseInt(params.get('page') ?? '1', 10);
|
||||||
|
|
||||||
|
const reviewCount = authed ? listDevicesPaged({ needsReview: true, pageSize: 1 }).total : 0;
|
||||||
|
const deviceTotal = authed ? countDevices() : 0;
|
||||||
|
const deviceResult = authed
|
||||||
|
? listDevicesPaged({
|
||||||
|
q: q || undefined,
|
||||||
|
brand,
|
||||||
|
sort,
|
||||||
|
needsReview: review || undefined,
|
||||||
|
page: Number.isFinite(pageParam) ? pageParam : 1,
|
||||||
|
pageSize: PAGE_SIZE,
|
||||||
|
})
|
||||||
|
: { items: [], total: 0, page: 1, pageSize: PAGE_SIZE, pages: 1 };
|
||||||
|
const brands = authed ? listBrands() : [];
|
||||||
|
const chips = authed ? listChips({}) : [];
|
||||||
|
const revisions = authed ? listRecentRevisions(8) : [];
|
||||||
|
|
||||||
|
/** 保留其他筛选条件,只覆盖指定项 */
|
||||||
|
function urlWith(overrides: Record<string, string | undefined>): string {
|
||||||
|
const search = new URLSearchParams();
|
||||||
|
const merged: Record<string, string | undefined> = {
|
||||||
|
q: q || undefined,
|
||||||
|
brand,
|
||||||
|
sort: sort === 'updated' ? undefined : sort,
|
||||||
|
review: review ? 'low' : undefined,
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
for (const [key, value] of Object.entries(merged)) {
|
||||||
|
if (value) search.set(key, value);
|
||||||
|
}
|
||||||
|
const query = search.toString();
|
||||||
|
return query ? `/admin?${query}` : '/admin';
|
||||||
|
}
|
||||||
|
|
||||||
|
const pageHref = (target: number) =>
|
||||||
|
`${urlWith({ page: target === 1 ? undefined : String(target) })}#devices`;
|
||||||
|
|
||||||
|
const sortOptions: { key: DeviceSort; label: string }[] = [
|
||||||
|
{ key: 'updated', label: '最近编辑' },
|
||||||
|
{ key: 'latest', label: '最新发布' },
|
||||||
|
{ key: 'brand', label: '按品牌' },
|
||||||
|
{ key: 'name', label: '按型号' },
|
||||||
|
];
|
||||||
|
|
||||||
|
function formatTime(iso: string): string {
|
||||||
|
return new Intl.DateTimeFormat('zh-CN', {
|
||||||
|
dateStyle: 'medium',
|
||||||
|
timeStyle: 'short',
|
||||||
|
timeZone: 'Asia/Shanghai',
|
||||||
|
}).format(new Date(iso));
|
||||||
|
}
|
||||||
|
|
||||||
|
function snapshotLabel(snapshot: unknown): string {
|
||||||
|
if (snapshot && typeof snapshot === 'object') {
|
||||||
|
const item = snapshot as { brand?: string; model?: string; slug?: string };
|
||||||
|
return [item.brand, item.model].filter(Boolean).join(' ') || item.slug || '—';
|
||||||
|
}
|
||||||
|
return '—';
|
||||||
|
}
|
||||||
|
|
||||||
|
function snapshotSlug(snapshot: unknown): string | undefined {
|
||||||
|
if (snapshot && typeof snapshot === 'object') {
|
||||||
|
const item = snapshot as { slug?: string };
|
||||||
|
return item.slug;
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function pendingCount(meta: { confidence: string; verified: boolean }[]): number {
|
||||||
|
return meta.filter((item) => item.confidence === 'low' && !item.verified).length;
|
||||||
|
}
|
||||||
|
---
|
||||||
|
|
||||||
|
<BaseLayout title={authed ? '编辑后台 · LFSpecs' : '登录 · LFSpecs'}>
|
||||||
|
{
|
||||||
|
!authed ? (
|
||||||
|
<div class="mx-auto mt-10 max-w-sm">
|
||||||
|
<h1 class="text-2xl font-semibold tracking-tight">编辑登录</h1>
|
||||||
|
<p class="mt-2 text-sm text-muted-foreground">
|
||||||
|
本站只读展示,编辑需要站主密码。登录状态保持 7 天。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{errorKey && errorMessages[errorKey] && (
|
||||||
|
<p class="mt-4 rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive">
|
||||||
|
{errorMessages[errorKey]}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<form method="post" action="/api/auth/login" class="mt-5 space-y-3">
|
||||||
|
<input type="hidden" name="next" value={next} />
|
||||||
|
<label class="flex flex-col gap-1.5">
|
||||||
|
<span class="text-xs text-muted-foreground">密码</span>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
name="password"
|
||||||
|
required
|
||||||
|
autofocus
|
||||||
|
autocomplete="current-password"
|
||||||
|
disabled={!authConfigured()}
|
||||||
|
class="h-9 w-full rounded-md border border-border bg-card px-3 text-sm placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={!authConfigured()}
|
||||||
|
class="h-9 w-full rounded-md bg-primary text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90 disabled:pointer-events-none disabled:opacity-50"
|
||||||
|
>
|
||||||
|
进入后台
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<p class="mt-4 text-xs text-muted-foreground">
|
||||||
|
需要配置 <code class="font-mono text-foreground/80">ADMIN_PASSWORD</code> 与
|
||||||
|
<code class="ml-1 font-mono text-foreground/80">SESSION_SECRET</code>。
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div>
|
||||||
|
<header class="flex flex-wrap items-center justify-between gap-3">
|
||||||
|
<div>
|
||||||
|
<h1 class="text-2xl font-semibold tracking-tight">编辑后台</h1>
|
||||||
|
<p class="mt-1 text-xs text-muted-foreground">
|
||||||
|
{deviceResult.total} / {deviceTotal} 款设备 · {chips.length} 颗芯片
|
||||||
|
<span class="ml-2">待核验 {reviewCount} 款</span>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<a
|
||||||
|
href="/api/export"
|
||||||
|
class="rounded-md border border-border px-3 py-1.5 text-xs text-muted-foreground transition-colors hover:text-foreground"
|
||||||
|
>
|
||||||
|
导出 JSON
|
||||||
|
</a>
|
||||||
|
<a
|
||||||
|
href="/admin/import"
|
||||||
|
class="rounded-md border border-border px-3 py-1.5 text-xs text-muted-foreground transition-colors hover:text-foreground"
|
||||||
|
>
|
||||||
|
导入 JSON
|
||||||
|
</a>
|
||||||
|
<a
|
||||||
|
href="/admin/bilibili"
|
||||||
|
class="rounded-md border border-border px-3 py-1.5 text-xs text-muted-foreground transition-colors hover:text-foreground"
|
||||||
|
>
|
||||||
|
B 站绑定
|
||||||
|
</a>
|
||||||
|
<a
|
||||||
|
href="/"
|
||||||
|
class="rounded-md border border-border px-3 py-1.5 text-xs text-muted-foreground transition-colors hover:text-foreground"
|
||||||
|
>
|
||||||
|
前台首页
|
||||||
|
</a>
|
||||||
|
<form method="post" action="/api/auth/logout">
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
class="rounded-md border border-border px-3 py-1.5 text-xs text-muted-foreground transition-colors hover:text-foreground"
|
||||||
|
>
|
||||||
|
退出登录
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<section id="devices" class="mt-8">
|
||||||
|
<div class="flex flex-wrap items-center justify-between gap-2">
|
||||||
|
<h2 class="text-sm font-semibold">设备</h2>
|
||||||
|
<a href="/admin/devices/new" class="text-xs text-primary hover:underline">
|
||||||
|
+ 新增设备
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form action="/admin" method="get" class="mt-3 flex flex-wrap gap-2">
|
||||||
|
<input
|
||||||
|
type="search"
|
||||||
|
name="q"
|
||||||
|
value={q}
|
||||||
|
placeholder="搜索品牌、型号、slug、别名"
|
||||||
|
class="h-9 min-w-0 flex-1 rounded-md border border-border bg-card px-3 text-sm placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring"
|
||||||
|
/>
|
||||||
|
{brand && <input type="hidden" name="brand" value={brand} />}
|
||||||
|
{sort !== 'updated' && <input type="hidden" name="sort" value={sort} />}
|
||||||
|
{review && <input type="hidden" name="review" value="low" />}
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
class="h-9 rounded-md bg-primary px-4 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90"
|
||||||
|
>
|
||||||
|
搜索
|
||||||
|
</button>
|
||||||
|
{(q || brand || review) && (
|
||||||
|
<a
|
||||||
|
href="/admin"
|
||||||
|
class="inline-flex h-9 items-center rounded-md border border-border px-3 text-sm text-muted-foreground transition-colors hover:text-foreground"
|
||||||
|
>
|
||||||
|
清除
|
||||||
|
</a>
|
||||||
|
)}
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<div class="mt-3 flex flex-wrap items-center gap-1 text-xs text-muted-foreground">
|
||||||
|
<span class="mr-1">排序</span>
|
||||||
|
{
|
||||||
|
sortOptions.map((option) => (
|
||||||
|
<a
|
||||||
|
href={urlWith({
|
||||||
|
sort: option.key === 'updated' ? undefined : option.key,
|
||||||
|
page: undefined,
|
||||||
|
})}
|
||||||
|
class:list={[
|
||||||
|
'rounded-md px-2 py-1 transition-colors',
|
||||||
|
sort === option.key ? 'bg-accent text-foreground' : 'hover:text-foreground',
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
{option.label}
|
||||||
|
</a>
|
||||||
|
))
|
||||||
|
}
|
||||||
|
<a
|
||||||
|
href={urlWith({
|
||||||
|
review: review ? undefined : 'low',
|
||||||
|
page: undefined,
|
||||||
|
})}
|
||||||
|
class:list={[
|
||||||
|
'ml-2 rounded-full border px-2.5 py-1 transition-colors',
|
||||||
|
review
|
||||||
|
? 'border-destructive/50 bg-destructive/10 text-destructive'
|
||||||
|
: 'border-border hover:text-foreground',
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
只看待核验 <span class="tabular">{reviewCount}</span>
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<details class="mt-3 rounded-md border border-border/70 bg-card px-3 py-2" open={Boolean(brand)}>
|
||||||
|
<summary class="cursor-pointer text-xs text-muted-foreground">
|
||||||
|
品牌筛选{brand ? `:${brandLabel(brand)}` : `(${brands.length} 个)`}
|
||||||
|
</summary>
|
||||||
|
<div class="mt-2 flex flex-wrap gap-1.5">
|
||||||
|
<a
|
||||||
|
href={urlWith({ brand: undefined, page: undefined })}
|
||||||
|
class:list={[
|
||||||
|
'rounded-full border px-2.5 py-1 text-xs transition-colors',
|
||||||
|
brand
|
||||||
|
? 'border-border text-muted-foreground hover:text-foreground'
|
||||||
|
: 'border-primary/50 bg-primary/10 text-primary',
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
全部
|
||||||
|
</a>
|
||||||
|
{
|
||||||
|
brands.map((item) => (
|
||||||
|
<a
|
||||||
|
href={urlWith({ brand: item.brand, page: undefined })}
|
||||||
|
class:list={[
|
||||||
|
'rounded-full border px-2.5 py-1 text-xs transition-colors',
|
||||||
|
brand === item.brand
|
||||||
|
? 'border-primary/50 bg-primary/10 text-primary'
|
||||||
|
: 'border-border text-muted-foreground hover:text-foreground',
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
{brandLabel(item.brand)} <span class="tabular opacity-60">{item.count}</span>
|
||||||
|
</a>
|
||||||
|
))
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
|
||||||
|
<ul class="mt-3 divide-y divide-border/60 rounded-lg border border-border bg-card">
|
||||||
|
{
|
||||||
|
deviceResult.items.map((device) => {
|
||||||
|
const pending = pendingCount(device.meta);
|
||||||
|
return (
|
||||||
|
<li class="flex flex-wrap items-center justify-between gap-3 px-4 py-3">
|
||||||
|
<div class="min-w-0">
|
||||||
|
<div class="flex flex-wrap items-center gap-2">
|
||||||
|
<span class="text-sm font-medium">{device.brand} {device.model}</span>
|
||||||
|
{pending > 0 && (
|
||||||
|
<span class="rounded-full border border-destructive/40 bg-destructive/10 px-1.5 py-0.5 text-[10px] text-destructive">
|
||||||
|
待核 {pending}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div class="font-mono text-[11px] text-muted-foreground">{device.slug}</div>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center gap-3 text-xs">
|
||||||
|
<a
|
||||||
|
href={`/devices/${device.slug}`}
|
||||||
|
target="_blank"
|
||||||
|
rel="noreferrer"
|
||||||
|
class="text-muted-foreground hover:text-foreground"
|
||||||
|
>
|
||||||
|
前台
|
||||||
|
</a>
|
||||||
|
<a href={`/admin/devices/${device.slug}`} class="text-primary hover:underline">
|
||||||
|
编辑
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
})
|
||||||
|
}
|
||||||
|
{deviceResult.items.length === 0 && (
|
||||||
|
<li class="px-4 py-8 text-center text-sm text-muted-foreground">
|
||||||
|
没有匹配的设备。试试更换关键词、品牌,或清除筛选。
|
||||||
|
</li>
|
||||||
|
)}
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
{deviceResult.pages > 1 && (
|
||||||
|
<div class="flex items-center justify-between text-xs text-muted-foreground">
|
||||||
|
<span class="tabular">第 {deviceResult.page} / {deviceResult.pages} 页 · 共 {deviceResult.total} 款</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<Pagination page={deviceResult.page} pages={deviceResult.pages} buildHref={pageHref} />
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<details class="mt-8">
|
||||||
|
<summary class="cursor-pointer text-sm font-semibold">
|
||||||
|
芯片 <span class="ml-1 text-xs font-normal text-muted-foreground">{chips.length} 颗</span>
|
||||||
|
</summary>
|
||||||
|
<div class="mt-2 flex justify-end">
|
||||||
|
<a href="/admin/chips/new" class="text-xs text-primary hover:underline">
|
||||||
|
+ 新增芯片
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
<ul class="mt-2 divide-y divide-border/60 rounded-lg border border-border bg-card">
|
||||||
|
{chips.map((chip) => (
|
||||||
|
<li class="flex flex-wrap items-center justify-between gap-3 px-4 py-3">
|
||||||
|
<div class="min-w-0">
|
||||||
|
<div class="text-sm font-medium">{chip.brand} {chip.model}</div>
|
||||||
|
<div class="font-mono text-[11px] text-muted-foreground">{chip.slug}</div>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center gap-3 text-xs">
|
||||||
|
<a href={`/chips/${chip.slug}`} target="_blank" rel="noreferrer" class="text-muted-foreground hover:text-foreground">
|
||||||
|
前台
|
||||||
|
</a>
|
||||||
|
<a href={`/admin/chips/${chip.slug}`} class="text-primary hover:underline">
|
||||||
|
编辑
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
{chips.length === 0 && (
|
||||||
|
<li class="px-4 py-6 text-center text-sm text-muted-foreground">暂无芯片。</li>
|
||||||
|
)}
|
||||||
|
</ul>
|
||||||
|
</details>
|
||||||
|
|
||||||
|
<section class="mt-8">
|
||||||
|
<h2 class="text-sm font-semibold">最近修订</h2>
|
||||||
|
<ul class="mt-3 divide-y divide-border/60 rounded-lg border border-border bg-card">
|
||||||
|
{revisions.map((revision) => (
|
||||||
|
<li class="flex flex-wrap items-center justify-between gap-2 px-4 py-2.5 text-xs">
|
||||||
|
<div class="flex flex-wrap items-center gap-2">
|
||||||
|
<span class="rounded-full border border-border px-1.5 py-0.5 text-[10px] text-muted-foreground">
|
||||||
|
{revision.entity === 'device' ? '设备' : '芯片'}
|
||||||
|
</span>
|
||||||
|
<span class="text-foreground">{snapshotLabel(revision.snapshot)}</span>
|
||||||
|
<span class="font-mono text-[10px] text-muted-foreground">#{revision.id}</span>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center gap-3 text-muted-foreground">
|
||||||
|
<span class="tabular">{formatTime(revision.createdAt)}</span>
|
||||||
|
{snapshotSlug(revision.snapshot) && (
|
||||||
|
<a
|
||||||
|
href={`/admin/${revision.entity === 'device' ? 'devices' : 'chips'}/${snapshotSlug(revision.snapshot)}`}
|
||||||
|
class="text-primary hover:underline"
|
||||||
|
>
|
||||||
|
编辑
|
||||||
|
</a>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
{revisions.length === 0 && (
|
||||||
|
<li class="px-4 py-6 text-center text-sm text-muted-foreground">暂无修订记录。</li>
|
||||||
|
)}
|
||||||
|
</ul>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
</BaseLayout>
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
import type { APIRoute } from 'astro';
|
||||||
|
import { z } from 'zod';
|
||||||
|
import { guardWrite } from '@/lib/auth';
|
||||||
|
import { AiLookupError, AiNotConfiguredError, lookupPhoneField } from '@/lib/ai/lookup';
|
||||||
|
|
||||||
|
const payloadSchema = z.object({
|
||||||
|
brand: z.string().trim().min(1).max(100),
|
||||||
|
model: z.string().trim().min(1).max(200),
|
||||||
|
path: z.string().trim().min(1).max(200),
|
||||||
|
currentValue: z.unknown().optional(),
|
||||||
|
force: z.boolean().optional(),
|
||||||
|
sourceText: z.string().trim().max(30_000).optional(),
|
||||||
|
sourceUrls: z.array(z.string().trim().max(500)).max(5).optional(),
|
||||||
|
// 检索范围:默认(全网+拆机)/ 仅源网站 / 全网 / 仅拆机视频
|
||||||
|
searchScope: z.enum(['default', 'whitelist', 'web', 'teardown']).optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const POST: APIRoute = async ({ request, cookies }) => {
|
||||||
|
const denied = await guardWrite(request, cookies);
|
||||||
|
if (denied) return denied;
|
||||||
|
|
||||||
|
let body: unknown;
|
||||||
|
try {
|
||||||
|
body = await request.json();
|
||||||
|
} catch {
|
||||||
|
return Response.json({ error: '请求体不是合法 JSON' }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const parsed = payloadSchema.safeParse(body);
|
||||||
|
if (!parsed.success) {
|
||||||
|
return Response.json(
|
||||||
|
{
|
||||||
|
error: '参数校验失败',
|
||||||
|
issues: parsed.error.issues.map((issue) => ({
|
||||||
|
path: issue.path.join('.'),
|
||||||
|
message: issue.message,
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
{ status: 400 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await lookupPhoneField({
|
||||||
|
brand: parsed.data.brand,
|
||||||
|
model: parsed.data.model,
|
||||||
|
path: parsed.data.path,
|
||||||
|
currentValue: parsed.data.currentValue,
|
||||||
|
force: parsed.data.force,
|
||||||
|
sourceText: parsed.data.sourceText,
|
||||||
|
sourceUrls: parsed.data.sourceUrls,
|
||||||
|
searchScope: parsed.data.searchScope,
|
||||||
|
});
|
||||||
|
return Response.json(result);
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof AiNotConfiguredError) {
|
||||||
|
return Response.json({ error: error.message }, { status: 503 });
|
||||||
|
}
|
||||||
|
if (error instanceof AiLookupError) {
|
||||||
|
return Response.json({ error: error.message }, { status: error.status });
|
||||||
|
}
|
||||||
|
return Response.json(
|
||||||
|
{ error: `AI 补全失败:${error instanceof Error ? error.message : '未知错误'}` },
|
||||||
|
{ status: 500 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
import type { APIRoute } from 'astro';
|
||||||
|
import { z } from 'zod';
|
||||||
|
import { guardWrite } from '@/lib/auth';
|
||||||
|
import { AiLookupError, AiNotConfiguredError, lookupPhoneSpecs } from '@/lib/ai/lookup';
|
||||||
|
|
||||||
|
const payloadSchema = z.object({
|
||||||
|
category: z.literal('phone').default('phone'),
|
||||||
|
brand: z.string().trim().min(1).max(100),
|
||||||
|
model: z.string().trim().min(1).max(200),
|
||||||
|
force: z.boolean().optional(),
|
||||||
|
/** 官网参数文本;用于无搜索 key 或最新机型 */
|
||||||
|
sourceText: z.string().trim().max(30_000).optional(),
|
||||||
|
sourceUrl: z.string().trim().max(500).optional(),
|
||||||
|
sourceUrls: z.array(z.string().trim().max(500)).max(5).optional(),
|
||||||
|
// 检索范围:默认(源网站+拆机)/ 仅源网站 / 全网 / 仅拆机视频
|
||||||
|
searchScope: z.enum(['default', 'whitelist', 'web', 'teardown']).optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const POST: APIRoute = async ({ request, cookies }) => {
|
||||||
|
const denied = await guardWrite(request, cookies);
|
||||||
|
if (denied) return denied;
|
||||||
|
|
||||||
|
let body: unknown;
|
||||||
|
try {
|
||||||
|
body = await request.json();
|
||||||
|
} catch {
|
||||||
|
return Response.json({ error: '请求体不是合法 JSON' }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const parsed = payloadSchema.safeParse(body);
|
||||||
|
if (!parsed.success) {
|
||||||
|
return Response.json(
|
||||||
|
{
|
||||||
|
error: '参数校验失败',
|
||||||
|
issues: parsed.error.issues.map((issue) => ({
|
||||||
|
path: issue.path.join('.'),
|
||||||
|
message: issue.message,
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
{ status: 400 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await lookupPhoneSpecs({
|
||||||
|
brand: parsed.data.brand,
|
||||||
|
model: parsed.data.model,
|
||||||
|
force: parsed.data.force,
|
||||||
|
sourceText: parsed.data.sourceText,
|
||||||
|
sourceUrl: parsed.data.sourceUrl,
|
||||||
|
sourceUrls: parsed.data.sourceUrls,
|
||||||
|
searchScope: parsed.data.searchScope,
|
||||||
|
});
|
||||||
|
return Response.json(result);
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof AiNotConfiguredError) {
|
||||||
|
return Response.json({ error: error.message }, { status: 503 });
|
||||||
|
}
|
||||||
|
if (error instanceof AiLookupError) {
|
||||||
|
return Response.json({ error: error.message }, { status: error.status });
|
||||||
|
}
|
||||||
|
return Response.json(
|
||||||
|
{ error: `AI 补全失败:${error instanceof Error ? error.message : '未知错误'}` },
|
||||||
|
{ status: 500 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,166 @@
|
|||||||
|
import type { APIRoute } from 'astro';
|
||||||
|
import { z } from 'zod';
|
||||||
|
import { guardWrite } from '@/lib/auth';
|
||||||
|
import { applyAiFields } from '@/lib/ai/apply';
|
||||||
|
import { AiLookupError, AiNotConfiguredError, lookupPhoneSpecs } from '@/lib/ai/lookup';
|
||||||
|
import { getDevice, saveDevice } from '@/lib/repo';
|
||||||
|
import { slugSchema, type PhoneDevice } from '@/lib/schema';
|
||||||
|
|
||||||
|
const payloadSchema = z.object({
|
||||||
|
slug: slugSchema.max(100),
|
||||||
|
});
|
||||||
|
|
||||||
|
const BRAND_PREFIXES: [prefix: string, brand: string][] = [
|
||||||
|
['redmi', 'Redmi'],
|
||||||
|
['xiaomi', 'Xiaomi'],
|
||||||
|
['poco', 'POCO'],
|
||||||
|
['oppo', 'OPPO'],
|
||||||
|
['oneplus', 'OnePlus'],
|
||||||
|
['vivo', 'vivo'],
|
||||||
|
['iqoo', 'iQOO'],
|
||||||
|
['honor', 'HONOR'],
|
||||||
|
['huawei', 'HUAWEI'],
|
||||||
|
['samsung', 'Samsung'],
|
||||||
|
['apple', 'Apple'],
|
||||||
|
['iphone', 'Apple'],
|
||||||
|
['realme', 'realme'],
|
||||||
|
['meizu', 'Meizu'],
|
||||||
|
['nubia', 'nubia'],
|
||||||
|
['zte', 'ZTE'],
|
||||||
|
['lenovo', 'Lenovo'],
|
||||||
|
['motorola', 'Motorola'],
|
||||||
|
['sony', 'Sony'],
|
||||||
|
['asus', 'ASUS'],
|
||||||
|
];
|
||||||
|
|
||||||
|
const TOKEN_CASE: Record<string, string> = {
|
||||||
|
pro: 'Pro',
|
||||||
|
max: 'Max',
|
||||||
|
ultra: 'Ultra',
|
||||||
|
plus: 'Plus',
|
||||||
|
mini: 'Mini',
|
||||||
|
gt: 'GT',
|
||||||
|
ace: 'Ace',
|
||||||
|
find: 'Find',
|
||||||
|
x: 'X',
|
||||||
|
k: 'K',
|
||||||
|
note: 'Note',
|
||||||
|
fold: 'Fold',
|
||||||
|
flip: 'Flip',
|
||||||
|
se: 'SE',
|
||||||
|
fe: 'FE',
|
||||||
|
edge: 'Edge',
|
||||||
|
neo: 'Neo',
|
||||||
|
turbo: 'Turbo',
|
||||||
|
power: 'Power',
|
||||||
|
lite: 'Lite',
|
||||||
|
};
|
||||||
|
|
||||||
|
function titleToken(token: string): string {
|
||||||
|
if (/^\d/.test(token)) return token;
|
||||||
|
const lower = token.toLowerCase();
|
||||||
|
if (TOKEN_CASE[lower]) return TOKEN_CASE[lower];
|
||||||
|
return token.charAt(0).toUpperCase() + token.slice(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
function inferIdentity(slug: string): { brand: string; model: string } {
|
||||||
|
const parts = slug.split('-');
|
||||||
|
const lower = parts[0];
|
||||||
|
const prefix = BRAND_PREFIXES.find(([key]) => key === lower);
|
||||||
|
const rest = prefix ? parts.slice(1) : parts;
|
||||||
|
if (!prefix) {
|
||||||
|
return {
|
||||||
|
brand: titleToken(parts[0] ?? slug),
|
||||||
|
model: rest.map(titleToken).join(' ') || slug,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const model = rest.map(titleToken).join(' ') || prefix[1];
|
||||||
|
return {
|
||||||
|
brand: prefix[1],
|
||||||
|
model: prefix[0] === 'iphone' ? `iPhone ${model}` : model,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function blankPhone(input: { slug: string; brand: string; model: string }): PhoneDevice {
|
||||||
|
return {
|
||||||
|
slug: input.slug,
|
||||||
|
category: 'phone',
|
||||||
|
brand: input.brand,
|
||||||
|
model: input.model,
|
||||||
|
aliases: [],
|
||||||
|
gallery: [],
|
||||||
|
tags: [],
|
||||||
|
lifecycle: 'announced',
|
||||||
|
chipRefs: {},
|
||||||
|
meta: [],
|
||||||
|
specs: {
|
||||||
|
rearCamera: [],
|
||||||
|
frontCamera: [],
|
||||||
|
features: [],
|
||||||
|
cameraFeatures: [],
|
||||||
|
benchmarks: [],
|
||||||
|
pricing: [],
|
||||||
|
boxContents: [],
|
||||||
|
extra: {},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export const POST: APIRoute = async ({ request, cookies }) => {
|
||||||
|
const denied = await guardWrite(request, cookies);
|
||||||
|
if (denied) return denied;
|
||||||
|
|
||||||
|
let body: unknown;
|
||||||
|
try {
|
||||||
|
body = await request.json();
|
||||||
|
} catch {
|
||||||
|
return Response.json({ error: '请求体不是合法 JSON' }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const parsed = payloadSchema.safeParse(body);
|
||||||
|
if (!parsed.success) {
|
||||||
|
return Response.json(
|
||||||
|
{
|
||||||
|
error: 'slug 校验失败',
|
||||||
|
issues: parsed.error.issues.map((issue) => ({
|
||||||
|
path: issue.path.join('.'),
|
||||||
|
message: issue.message,
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
{ status: 400 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const slug = parsed.data.slug;
|
||||||
|
if (getDevice(slug)) {
|
||||||
|
return Response.json({ error: `slug「${slug}」已存在` }, { status: 409 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const identity = inferIdentity(slug);
|
||||||
|
const base = blankPhone({ slug, ...identity });
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await lookupPhoneSpecs({
|
||||||
|
brand: identity.brand,
|
||||||
|
model: identity.model,
|
||||||
|
force: true,
|
||||||
|
});
|
||||||
|
if (result.fields.length === 0) {
|
||||||
|
return Response.json({ error: 'AI 没有返回可用字段,请稍后重试或手动创建。' }, { status: 422 });
|
||||||
|
}
|
||||||
|
const device = applyAiFields(base, result.fields);
|
||||||
|
const saved = saveDevice(device);
|
||||||
|
return Response.json({ device: saved, fields: result.fields.length, sources: result.sources });
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof AiNotConfiguredError) {
|
||||||
|
return Response.json({ error: error.message }, { status: 503 });
|
||||||
|
}
|
||||||
|
if (error instanceof AiLookupError) {
|
||||||
|
return Response.json({ error: error.message }, { status: error.status });
|
||||||
|
}
|
||||||
|
return Response.json(
|
||||||
|
{ error: `AI 创建失败:${error instanceof Error ? error.message : '未知错误'}` },
|
||||||
|
{ status: 500 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
import type { APIRoute } from 'astro';
|
||||||
|
import { z } from 'zod';
|
||||||
|
import { guardWrite } from '@/lib/auth';
|
||||||
|
import { AiLookupError, AiNotConfiguredError, lookupPhoneSection } from '@/lib/ai/lookup';
|
||||||
|
|
||||||
|
const payloadSchema = z.object({
|
||||||
|
brand: z.string().trim().min(1).max(100),
|
||||||
|
model: z.string().trim().min(1).max(200),
|
||||||
|
section: z.string().trim().min(1).max(50),
|
||||||
|
force: z.boolean().optional(),
|
||||||
|
sourceText: z.string().trim().max(30_000).optional(),
|
||||||
|
sourceUrls: z.array(z.string().trim().max(500)).max(5).optional(),
|
||||||
|
// 检索范围:默认(全网+拆机)/ 仅源网站 / 全网 / 仅拆机视频
|
||||||
|
searchScope: z.enum(['default', 'whitelist', 'web', 'teardown']).optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const POST: APIRoute = async ({ request, cookies }) => {
|
||||||
|
const denied = await guardWrite(request, cookies);
|
||||||
|
if (denied) return denied;
|
||||||
|
|
||||||
|
let body: unknown;
|
||||||
|
try {
|
||||||
|
body = await request.json();
|
||||||
|
} catch {
|
||||||
|
return Response.json({ error: '请求体不是合法 JSON' }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const parsed = payloadSchema.safeParse(body);
|
||||||
|
if (!parsed.success) {
|
||||||
|
return Response.json(
|
||||||
|
{
|
||||||
|
error: '参数校验失败',
|
||||||
|
issues: parsed.error.issues.map((issue) => ({
|
||||||
|
path: issue.path.join('.'),
|
||||||
|
message: issue.message,
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
{ status: 400 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await lookupPhoneSection({
|
||||||
|
brand: parsed.data.brand,
|
||||||
|
model: parsed.data.model,
|
||||||
|
section: parsed.data.section,
|
||||||
|
force: parsed.data.force,
|
||||||
|
sourceText: parsed.data.sourceText,
|
||||||
|
sourceUrls: parsed.data.sourceUrls,
|
||||||
|
searchScope: parsed.data.searchScope,
|
||||||
|
});
|
||||||
|
return Response.json(result);
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof AiNotConfiguredError) {
|
||||||
|
return Response.json({ error: error.message }, { status: 503 });
|
||||||
|
}
|
||||||
|
if (error instanceof AiLookupError) {
|
||||||
|
return Response.json({ error: error.message }, { status: error.status });
|
||||||
|
}
|
||||||
|
return Response.json(
|
||||||
|
{ error: `AI 补全失败:${error instanceof Error ? error.message : '未知错误'}` },
|
||||||
|
{ status: 500 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import type { APIRoute } from 'astro';
|
||||||
|
import {
|
||||||
|
authConfigured,
|
||||||
|
clientIp,
|
||||||
|
clearLoginFailures,
|
||||||
|
loginRateLimited,
|
||||||
|
passwordMatches,
|
||||||
|
recordLoginFailure,
|
||||||
|
sameOrigin,
|
||||||
|
setSessionCookie,
|
||||||
|
} from '@/lib/auth';
|
||||||
|
|
||||||
|
function safeNext(value: string | null): string {
|
||||||
|
if (!value || !value.startsWith('/admin') || value.startsWith('//')) return '/admin';
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
function redirectTo(location: string): Response {
|
||||||
|
return new Response(null, { status: 303, headers: { location } });
|
||||||
|
}
|
||||||
|
|
||||||
|
export const POST: APIRoute = async ({ request, cookies, clientAddress }) => {
|
||||||
|
if (!sameOrigin(request)) {
|
||||||
|
return new Response('Origin 校验失败', { status: 403 });
|
||||||
|
}
|
||||||
|
if (!authConfigured()) return redirectTo('/admin?error=config');
|
||||||
|
|
||||||
|
const ip = clientIp(request, clientAddress);
|
||||||
|
if (loginRateLimited(ip)) return redirectTo('/admin?error=rate');
|
||||||
|
|
||||||
|
const form = await request.formData();
|
||||||
|
const password = String(form.get('password') ?? '');
|
||||||
|
const next = safeNext(String(form.get('next') ?? ''));
|
||||||
|
|
||||||
|
if (!passwordMatches(password)) {
|
||||||
|
recordLoginFailure(ip);
|
||||||
|
return redirectTo('/admin?error=invalid');
|
||||||
|
}
|
||||||
|
|
||||||
|
clearLoginFailures(ip);
|
||||||
|
await setSessionCookie(cookies);
|
||||||
|
return redirectTo(next);
|
||||||
|
};
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import type { APIRoute } from 'astro';
|
||||||
|
import { clearSessionCookie, sameOrigin } from '@/lib/auth';
|
||||||
|
|
||||||
|
export const POST: APIRoute = async ({ request, cookies }) => {
|
||||||
|
if (!sameOrigin(request)) {
|
||||||
|
return new Response('Origin 校验失败', { status: 403 });
|
||||||
|
}
|
||||||
|
clearSessionCookie(cookies);
|
||||||
|
return new Response(null, { status: 303, headers: { location: '/admin' } });
|
||||||
|
};
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import type { APIRoute } from 'astro';
|
||||||
|
import { guardWrite } from '@/lib/auth';
|
||||||
|
import { createLoginQRCode } from '@/lib/bilibili';
|
||||||
|
|
||||||
|
/** 生成 B 站扫码登录二维码(data URL),前端展示后轮询 poll 接口 */
|
||||||
|
export const POST: APIRoute = async ({ request, cookies }) => {
|
||||||
|
const denied = await guardWrite(request, cookies);
|
||||||
|
if (denied) return denied;
|
||||||
|
try {
|
||||||
|
const { key, imageDataUrl } = await createLoginQRCode();
|
||||||
|
return Response.json({ key, imageDataUrl });
|
||||||
|
} catch (error) {
|
||||||
|
return Response.json(
|
||||||
|
{ error: `生成二维码失败:${error instanceof Error ? error.message : '未知错误'}` },
|
||||||
|
{ status: 502 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import type { APIRoute } from 'astro';
|
||||||
|
import { z } from 'zod';
|
||||||
|
import { guardWrite } from '@/lib/auth';
|
||||||
|
import { pollLoginQRCode } from '@/lib/bilibili';
|
||||||
|
|
||||||
|
const payloadSchema = z.object({
|
||||||
|
key: z.string().trim().min(10).max(100),
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 轮询扫码结果:waiting(未扫)/ scanned(已扫待确认)/ confirmed(已登录,
|
||||||
|
* SESSDATA 已保存)/ expired(过期需重新生成)。
|
||||||
|
*/
|
||||||
|
export const POST: APIRoute = async ({ request, cookies }) => {
|
||||||
|
const denied = await guardWrite(request, cookies);
|
||||||
|
if (denied) return denied;
|
||||||
|
|
||||||
|
let body: unknown;
|
||||||
|
try {
|
||||||
|
body = await request.json();
|
||||||
|
} catch {
|
||||||
|
return Response.json({ error: '请求体不是合法 JSON' }, { status: 400 });
|
||||||
|
}
|
||||||
|
const parsed = payloadSchema.safeParse(body);
|
||||||
|
if (!parsed.success) {
|
||||||
|
return Response.json({ error: '缺少 key 参数' }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await pollLoginQRCode(parsed.data.key);
|
||||||
|
return Response.json(result);
|
||||||
|
} catch (error) {
|
||||||
|
return Response.json(
|
||||||
|
{ error: `轮询失败:${error instanceof Error ? error.message : '未知错误'}` },
|
||||||
|
{ status: 502 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
import type { APIRoute } from 'astro';
|
||||||
|
import { guardWrite } from '@/lib/auth';
|
||||||
|
import { unbindBilibili } from '@/lib/bilibili';
|
||||||
|
|
||||||
|
/** 解除 B 站绑定:删除后台保存的 SESSDATA(.env 配置不受影响) */
|
||||||
|
export const POST: APIRoute = async ({ request, cookies }) => {
|
||||||
|
const denied = await guardWrite(request, cookies);
|
||||||
|
if (denied) return denied;
|
||||||
|
unbindBilibili();
|
||||||
|
return Response.json({ ok: true });
|
||||||
|
};
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
import type { APIRoute } from 'astro';
|
||||||
|
import { guardWrite } from '@/lib/auth';
|
||||||
|
import { unverifiedLowFields } from '@/lib/ai/rules';
|
||||||
|
import { getChip, saveChip } from '@/lib/repo';
|
||||||
|
import { chipSchema } from '@/lib/schema';
|
||||||
|
|
||||||
|
export const POST: APIRoute = async ({ request, cookies, url }) => {
|
||||||
|
const denied = await guardWrite(request, cookies);
|
||||||
|
if (denied) return denied;
|
||||||
|
|
||||||
|
let body: unknown;
|
||||||
|
try {
|
||||||
|
body = await request.json();
|
||||||
|
} catch {
|
||||||
|
return Response.json({ error: '请求体不是合法 JSON' }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const parsed = chipSchema.safeParse(body);
|
||||||
|
if (!parsed.success) {
|
||||||
|
return Response.json(
|
||||||
|
{
|
||||||
|
error: '数据校验失败',
|
||||||
|
issues: parsed.error.issues.map((issue) => ({
|
||||||
|
path: issue.path.join('.'),
|
||||||
|
message: issue.message,
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
{ status: 400 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (url.searchParams.get('create') === '1' && getChip(parsed.data.slug)) {
|
||||||
|
return Response.json({ error: `slug「${parsed.data.slug}」已存在` }, { status: 409 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const blocking = unverifiedLowFields(parsed.data);
|
||||||
|
if (blocking.length > 0) {
|
||||||
|
return Response.json(
|
||||||
|
{
|
||||||
|
error: `有 ${blocking.length} 项 low 置信度字段未确认`,
|
||||||
|
issues: blocking.map((item) => ({
|
||||||
|
path: item.path,
|
||||||
|
message: 'low 置信度字段需要人工确认或清空后才能保存',
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
{ status: 400 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const chip = saveChip(parsed.data);
|
||||||
|
return Response.json({ chip });
|
||||||
|
};
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
import type { APIRoute } from 'astro';
|
||||||
|
import { guardWrite } from '@/lib/auth';
|
||||||
|
import { unverifiedLowFields } from '@/lib/ai/rules';
|
||||||
|
import { getDevice, saveDevice } from '@/lib/repo';
|
||||||
|
import { deviceSchema } from '@/lib/schema';
|
||||||
|
|
||||||
|
export const POST: APIRoute = async ({ request, cookies, url }) => {
|
||||||
|
const denied = await guardWrite(request, cookies);
|
||||||
|
if (denied) return denied;
|
||||||
|
|
||||||
|
let body: unknown;
|
||||||
|
try {
|
||||||
|
body = await request.json();
|
||||||
|
} catch {
|
||||||
|
return Response.json({ error: '请求体不是合法 JSON' }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const parsed = deviceSchema.safeParse(body);
|
||||||
|
if (!parsed.success) {
|
||||||
|
return Response.json(
|
||||||
|
{
|
||||||
|
error: '数据校验失败',
|
||||||
|
issues: parsed.error.issues.map((issue) => ({
|
||||||
|
path: issue.path.join('.'),
|
||||||
|
message: issue.message,
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
{ status: 400 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (url.searchParams.get('create') === '1' && getDevice(parsed.data.slug)) {
|
||||||
|
return Response.json({ error: `slug「${parsed.data.slug}」已存在` }, { status: 409 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const blocking = unverifiedLowFields(parsed.data);
|
||||||
|
if (blocking.length > 0) {
|
||||||
|
return Response.json(
|
||||||
|
{
|
||||||
|
error: `有 ${blocking.length} 项 low 置信度字段未确认`,
|
||||||
|
issues: blocking.map((item) => ({
|
||||||
|
path: item.path,
|
||||||
|
message: 'low 置信度字段需要人工确认或清空后才能保存',
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
{ status: 400 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const device = saveDevice(parsed.data);
|
||||||
|
return Response.json({ device });
|
||||||
|
};
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import type { APIRoute } from 'astro';
|
||||||
|
import { listChips, listDevices } from '@/lib/repo';
|
||||||
|
|
||||||
|
export const FORMAT_VERSION = 1;
|
||||||
|
|
||||||
|
export const GET: APIRoute = () => {
|
||||||
|
const devices = listDevices();
|
||||||
|
const chips = listChips();
|
||||||
|
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
|
||||||
|
|
||||||
|
const payload = {
|
||||||
|
formatVersion: FORMAT_VERSION,
|
||||||
|
generator: 'LFSpecs',
|
||||||
|
exportedAt: new Date().toISOString(),
|
||||||
|
devices,
|
||||||
|
chips,
|
||||||
|
};
|
||||||
|
|
||||||
|
return new Response(JSON.stringify(payload, null, 2), {
|
||||||
|
headers: {
|
||||||
|
'content-type': 'application/json; charset=utf-8',
|
||||||
|
'content-disposition': `attachment; filename="lfspecs-export-${stamp}.json"`,
|
||||||
|
'cache-control': 'no-store',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
};
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
import type { APIRoute } from 'astro';
|
||||||
|
import { z } from 'zod';
|
||||||
|
import { guardWrite } from '@/lib/auth';
|
||||||
|
import { importEntities } from '@/lib/repo';
|
||||||
|
import { chipSchema, deviceSchema } from '@/lib/schema';
|
||||||
|
|
||||||
|
const MAX_BYTES = 20 * 1024 * 1024;
|
||||||
|
const MAX_ITEMS = 5000;
|
||||||
|
|
||||||
|
const envelopeSchema = z.object({
|
||||||
|
formatVersion: z.literal(1),
|
||||||
|
devices: z.array(z.unknown()).default([]),
|
||||||
|
chips: z.array(z.unknown()).default([]),
|
||||||
|
});
|
||||||
|
|
||||||
|
async function readPayload(request: Request): Promise<unknown> {
|
||||||
|
const contentType = request.headers.get('content-type') ?? '';
|
||||||
|
|
||||||
|
if (contentType.includes('multipart/form-data')) {
|
||||||
|
const form = await request.formData();
|
||||||
|
const file = form.get('file');
|
||||||
|
if (file instanceof File) {
|
||||||
|
if (file.size > MAX_BYTES) throw new Error('文件不能超过 20MB');
|
||||||
|
return JSON.parse(await file.text()) as unknown;
|
||||||
|
}
|
||||||
|
const text = String(form.get('json') ?? '');
|
||||||
|
if (!text.trim()) throw new Error('请上传文件或粘贴 JSON');
|
||||||
|
return JSON.parse(text) as unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
const text = await request.text();
|
||||||
|
if (text.length > MAX_BYTES) throw new Error('请求体不能超过 20MB');
|
||||||
|
if (!text.trim()) throw new Error('请求体为空');
|
||||||
|
return JSON.parse(text) as unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const POST: APIRoute = async ({ request, cookies }) => {
|
||||||
|
const denied = await guardWrite(request, cookies);
|
||||||
|
if (denied) return denied;
|
||||||
|
|
||||||
|
let payload: unknown;
|
||||||
|
try {
|
||||||
|
payload = await readPayload(request);
|
||||||
|
} catch (error) {
|
||||||
|
return Response.json(
|
||||||
|
{ error: `无法读取导入内容:${error instanceof Error ? error.message : '解析失败'}` },
|
||||||
|
{ status: 400 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const envelope = envelopeSchema.safeParse(payload);
|
||||||
|
if (!envelope.success) {
|
||||||
|
return Response.json(
|
||||||
|
{
|
||||||
|
error: '导入文件格式不正确,需要 { formatVersion: 1, devices: [...], chips: [...] }',
|
||||||
|
issues: envelope.error.issues.map((issue) => ({
|
||||||
|
path: issue.path.join('.'),
|
||||||
|
message: issue.message,
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
{ status: 400 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const { devices: rawDevices, chips: rawChips } = envelope.data;
|
||||||
|
if (rawDevices.length === 0 && rawChips.length === 0) {
|
||||||
|
return Response.json({ error: '没有可导入的设备或芯片' }, { status: 400 });
|
||||||
|
}
|
||||||
|
if (rawDevices.length > MAX_ITEMS || rawChips.length > MAX_ITEMS) {
|
||||||
|
return Response.json({ error: `单次最多导入 ${MAX_ITEMS} 条` }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const issues: { path: string; message: string }[] = [];
|
||||||
|
const devices = [];
|
||||||
|
for (const [index, item] of rawDevices.entries()) {
|
||||||
|
const parsed = deviceSchema.safeParse(item);
|
||||||
|
if (parsed.success) {
|
||||||
|
devices.push(parsed.data);
|
||||||
|
} else {
|
||||||
|
for (const issue of parsed.error.issues) {
|
||||||
|
issues.push({
|
||||||
|
path: `devices[${index}].${issue.path.join('.')}`,
|
||||||
|
message: issue.message,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const chips = [];
|
||||||
|
for (const [index, item] of rawChips.entries()) {
|
||||||
|
const parsed = chipSchema.safeParse(item);
|
||||||
|
if (parsed.success) {
|
||||||
|
chips.push(parsed.data);
|
||||||
|
} else {
|
||||||
|
for (const issue of parsed.error.issues) {
|
||||||
|
issues.push({
|
||||||
|
path: `chips[${index}].${issue.path.join('.')}`,
|
||||||
|
message: issue.message,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (issues.length > 0) {
|
||||||
|
return Response.json(
|
||||||
|
{ error: `导入数据校验失败(${issues.length} 处)`, issues: issues.slice(0, 200) },
|
||||||
|
{ status: 400 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const counts = importEntities(devices, chips);
|
||||||
|
return Response.json({ ok: true, counts });
|
||||||
|
};
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import type { APIRoute } from 'astro';
|
||||||
|
import { randomUUID } from 'node:crypto';
|
||||||
|
import { guardWrite } from '@/lib/auth';
|
||||||
|
import { getStorage } from '@/lib/storage';
|
||||||
|
|
||||||
|
const MAX_BYTES = 10 * 1024 * 1024;
|
||||||
|
|
||||||
|
const EXTENSIONS: Record<string, string> = {
|
||||||
|
'image/jpeg': '.jpg',
|
||||||
|
'image/png': '.png',
|
||||||
|
'image/webp': '.webp',
|
||||||
|
'image/avif': '.avif',
|
||||||
|
};
|
||||||
|
|
||||||
|
export const POST: APIRoute = async ({ request, cookies }) => {
|
||||||
|
const denied = await guardWrite(request, cookies);
|
||||||
|
if (denied) return denied;
|
||||||
|
|
||||||
|
const form = await request.formData();
|
||||||
|
const file = form.get('file');
|
||||||
|
if (!(file instanceof File)) {
|
||||||
|
return Response.json({ error: '缺少 file 字段' }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const extension = EXTENSIONS[file.type];
|
||||||
|
if (!extension) {
|
||||||
|
return Response.json({ error: '仅支持 jpg / png / webp / avif' }, { status: 400 });
|
||||||
|
}
|
||||||
|
if (file.size > MAX_BYTES) {
|
||||||
|
return Response.json({ error: '图片不能超过 10MB' }, { status: 413 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const slug = String(form.get('slug') ?? '');
|
||||||
|
const folder = /^[a-z0-9][a-z0-9-]*$/.test(slug) ? slug : 'misc';
|
||||||
|
const key = `devices/${folder}/${Date.now()}-${randomUUID().slice(0, 8)}${extension}`;
|
||||||
|
|
||||||
|
await getStorage().put(key, new Uint8Array(await file.arrayBuffer()), file.type);
|
||||||
|
return Response.json({ key, url: getStorage().publicUrl(key) });
|
||||||
|
};
|
||||||
@@ -1,49 +1,70 @@
|
|||||||
---
|
---
|
||||||
|
import DeviceCard from '@/components/DeviceCard.astro';
|
||||||
|
import Pagination from '@/components/Pagination.astro';
|
||||||
import BaseLayout from '@/layouts/BaseLayout.astro';
|
import BaseLayout from '@/layouts/BaseLayout.astro';
|
||||||
import { listBrands, listDevices } from '@/lib/repo';
|
import { listBrands, listDevicesPaged } from '@/lib/repo';
|
||||||
|
import { brandLabel } from '@/lib/utils';
|
||||||
|
|
||||||
|
const PAGE_SIZE = 24;
|
||||||
|
|
||||||
const brand = decodeURIComponent(Astro.params.brand ?? '');
|
const brand = decodeURIComponent(Astro.params.brand ?? '');
|
||||||
const devices = listDevices({ brand });
|
const pageParam = Number.parseInt(Astro.url.searchParams.get('page') ?? '1', 10);
|
||||||
|
const result = listDevicesPaged({
|
||||||
|
brand,
|
||||||
|
page: Number.isFinite(pageParam) ? pageParam : 1,
|
||||||
|
pageSize: PAGE_SIZE,
|
||||||
|
});
|
||||||
const brands = listBrands();
|
const brands = listBrands();
|
||||||
const totalOfBrand = brands.find((item) => item.brand === brand)?.count ?? devices.length;
|
const totalOfBrand = brands.find((item) => item.brand === brand)?.count ?? result.total;
|
||||||
|
const label = brandLabel(brand);
|
||||||
|
|
||||||
if (devices.length === 0) {
|
if (result.total === 0) {
|
||||||
return new Response('未找到该品牌', { status: 404 });
|
return new Response('未找到该品牌', { status: 404 });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const brandHref = (target: number) => {
|
||||||
|
const path = `/brands/${encodeURIComponent(brand)}`;
|
||||||
|
return target === 1 ? `${path}#list` : `${path}?page=${target}#list`;
|
||||||
|
};
|
||||||
---
|
---
|
||||||
|
|
||||||
<BaseLayout title={`${brand} 设备 · LFSpecs`} description={`${brand} 收录的 ${devices.length} 款设备详细规格。`}>
|
<BaseLayout title={`${label} 设备 · LFSpecs`} description={`${label} 收录的 ${totalOfBrand} 款设备详细规格。`}>
|
||||||
<nav class="text-xs text-muted-foreground">
|
<nav class="text-xs text-muted-foreground">
|
||||||
<a href="/brands" class="hover:text-foreground">品牌</a>
|
<a href="/brands" class="hover:text-foreground">品牌</a>
|
||||||
<span class="mx-1.5">/</span>
|
<span class="mx-1.5">/</span>
|
||||||
<span class="text-foreground">{brand}</span>
|
<span class="text-foreground">{label}</span>
|
||||||
</nav>
|
</nav>
|
||||||
|
|
||||||
<header class="mt-3 flex flex-wrap items-baseline justify-between gap-3">
|
<header class="mt-3 flex flex-wrap items-baseline justify-between gap-3">
|
||||||
<h1 class="text-2xl font-semibold tracking-tight">{brand}</h1>
|
<h1 class="text-2xl font-semibold tracking-tight">{label}</h1>
|
||||||
<span class="tabular text-sm text-muted-foreground">{totalOfBrand} 款</span>
|
<span class="tabular text-sm text-muted-foreground">{totalOfBrand} 款</span>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<div class="mt-6 grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
<div class="mt-4 flex flex-wrap items-center gap-2 text-xs">
|
||||||
{
|
{
|
||||||
devices.map((device) => (
|
brands.map((item) => (
|
||||||
<a
|
<a
|
||||||
href={`/devices/${device.slug}`}
|
href={`/brands/${encodeURIComponent(item.brand)}`}
|
||||||
class="rounded-lg border border-border bg-card p-5 transition-colors hover:border-primary/40"
|
class:list={[
|
||||||
|
'rounded-full border px-3 py-1 transition-colors',
|
||||||
|
item.brand === brand
|
||||||
|
? 'border-primary/50 bg-primary/10 text-primary'
|
||||||
|
: 'border-border text-muted-foreground hover:text-foreground',
|
||||||
|
]}
|
||||||
>
|
>
|
||||||
<div class="text-base font-semibold">{device.model}</div>
|
{brandLabel(item.brand)} <span class="tabular opacity-60">{item.count}</span>
|
||||||
<dl class="tabular mt-4 grid grid-cols-2 gap-x-4 gap-y-1 text-xs">
|
|
||||||
<dt class="text-muted-foreground">SoC</dt>
|
|
||||||
<dd class="truncate text-right">{device.specs.platform?.chipset ?? '—'}</dd>
|
|
||||||
<dt class="text-muted-foreground">发布日期</dt>
|
|
||||||
<dd class="text-right">{device.releaseDate ?? device.announceDate ?? '—'}</dd>
|
|
||||||
<dt class="text-muted-foreground">屏幕</dt>
|
|
||||||
<dd class="truncate text-right">{device.specs.display?.size ?? '—'}</dd>
|
|
||||||
<dt class="text-muted-foreground">电池</dt>
|
|
||||||
<dd class="truncate text-right">{device.specs.battery?.capacity ?? '—'}</dd>
|
|
||||||
</dl>
|
|
||||||
</a>
|
</a>
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div id="list" class="reveal-grid mt-6 grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||||
|
{
|
||||||
|
result.items.map((device) => (
|
||||||
|
<DeviceCard device={device} />
|
||||||
|
))
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Pagination page={result.page} pages={result.pages} buildHref={brandHref} />
|
||||||
</BaseLayout>
|
</BaseLayout>
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
---
|
---
|
||||||
import BaseLayout from '@/layouts/BaseLayout.astro';
|
import BaseLayout from '@/layouts/BaseLayout.astro';
|
||||||
import { listBrands } from '@/lib/repo';
|
import { listBrands } from '@/lib/repo';
|
||||||
|
import { brandLabel } from '@/lib/utils';
|
||||||
|
|
||||||
const brands = listBrands();
|
const brands = listBrands();
|
||||||
const total = brands.reduce((sum, item) => sum + item.count, 0);
|
const total = brands.reduce((sum, item) => sum + item.count, 0);
|
||||||
@@ -12,14 +13,14 @@ const total = brands.reduce((sum, item) => sum + item.count, 0);
|
|||||||
<span class="tabular text-sm text-muted-foreground">{brands.length} 个品牌 · {total} 款设备</span>
|
<span class="tabular text-sm text-muted-foreground">{brands.length} 个品牌 · {total} 款设备</span>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<div class="mt-6 grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
<div class="reveal-grid mt-6 grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||||
{
|
{
|
||||||
brands.map((item) => (
|
brands.map((item) => (
|
||||||
<a
|
<a
|
||||||
href={`/brands/${encodeURIComponent(item.brand)}`}
|
href={`/brands/${encodeURIComponent(item.brand)}`}
|
||||||
class="flex items-center justify-between rounded-lg border border-border bg-card px-5 py-4 transition-colors hover:border-primary/40"
|
class="flex items-center justify-between rounded-lg border border-border bg-card px-5 py-4 transition-colors hover:border-primary/40"
|
||||||
>
|
>
|
||||||
<span class="text-sm font-medium">{item.brand}</span>
|
<span class="min-w-0 truncate text-sm font-medium">{brandLabel(item.brand)}</span>
|
||||||
<span class="tabular text-xs text-muted-foreground">{item.count} 款</span>
|
<span class="tabular text-xs text-muted-foreground">{item.count} 款</span>
|
||||||
</a>
|
</a>
|
||||||
))
|
))
|
||||||
|
|||||||
+277
-55
@@ -1,6 +1,7 @@
|
|||||||
---
|
---
|
||||||
import BaseLayout from '@/layouts/BaseLayout.astro';
|
import BaseLayout from '@/layouts/BaseLayout.astro';
|
||||||
import { devicesUsingChip, getChip } from '@/lib/repo';
|
import { devicesUsingChip, getChip } from '@/lib/repo';
|
||||||
|
import { chipTitle, deviceTitle } from '@/lib/utils';
|
||||||
|
|
||||||
const slug = Astro.params.slug ?? '';
|
const slug = Astro.params.slug ?? '';
|
||||||
const chip = getChip(slug);
|
const chip = getChip(slug);
|
||||||
@@ -9,14 +10,41 @@ if (!chip) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const detail = chip.detail;
|
const detail = chip.detail;
|
||||||
|
const overview = detail.overview;
|
||||||
|
const cpu = detail.cpuBlock;
|
||||||
const devices = devicesUsingChip(chip.slug);
|
const devices = devicesUsingChip(chip.slug);
|
||||||
const coreTotal = detail.cpuClusters.reduce(
|
const coreTotal =
|
||||||
(sum, c) => sum + (c.cores ?? []).reduce((n, x) => n + (x.count ?? 0), 0),
|
cpu?.cores ??
|
||||||
|
detail.cpuClusters.reduce(
|
||||||
|
(sum, cluster) => sum + cluster.cores.reduce((n, core) => n + (core.count ?? 0), 0),
|
||||||
0,
|
0,
|
||||||
);
|
);
|
||||||
|
const headlineBenchmark =
|
||||||
|
detail.benchmarks.find((item) => /多核/.test(item.name)) ?? detail.benchmarks[0];
|
||||||
|
const antutu = detail.benchmarkInfo?.antutu;
|
||||||
|
const hasAntutuBreakdown =
|
||||||
|
antutu && [antutu.cpu, antutu.gpu, antutu.memory, antutu.ux].some((value) => value !== undefined);
|
||||||
|
const specGroups = Object.entries(detail.specGroups);
|
||||||
|
const aliases = chip.aliases.filter((alias) => alias !== chip.model).slice(0, 16);
|
||||||
|
|
||||||
|
const keyCards: { label: string; value?: string; sub?: string }[] = [
|
||||||
|
{ label: '制程', value: chip.process },
|
||||||
|
{ label: 'CPU', value: coreTotal > 0 ? `${coreTotal} 核${cpu?.maxFreq ? ` · ${cpu.maxFreq}` : ''}` : undefined },
|
||||||
|
{ label: 'GPU', value: detail.gpuBlock?.name },
|
||||||
|
{ label: 'NPU', value: detail.npuBlock?.name },
|
||||||
|
{ label: '基带', value: detail.modemBlock },
|
||||||
|
{
|
||||||
|
label: '跑分',
|
||||||
|
value: headlineBenchmark ? headlineBenchmark.score : undefined,
|
||||||
|
sub: headlineBenchmark?.name,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const lifecycleText = (value: string) =>
|
||||||
|
value === 'discontinued' ? '已停产' : value === 'announced' ? '已发布' : '在售';
|
||||||
---
|
---
|
||||||
|
|
||||||
<BaseLayout title={`${chip.brand} ${chip.model} 规格 · LFSpecs`}>
|
<BaseLayout title={`${chipTitle(chip.brand, chip.model)} 规格 · LFSpecs`}>
|
||||||
<nav class="text-xs text-muted-foreground">
|
<nav class="text-xs text-muted-foreground">
|
||||||
<a href="/chips" class="hover:text-foreground">芯片</a>
|
<a href="/chips" class="hover:text-foreground">芯片</a>
|
||||||
<span class="mx-1.5">/</span>
|
<span class="mx-1.5">/</span>
|
||||||
@@ -24,33 +52,86 @@ const coreTotal = detail.cpuClusters.reduce(
|
|||||||
</nav>
|
</nav>
|
||||||
|
|
||||||
<header class="mt-3">
|
<header class="mt-3">
|
||||||
<p class="text-sm text-muted-foreground">{chip.brand}</p>
|
<h1 class="text-4xl font-semibold tracking-[-0.03em] sm:text-[2.75rem]">
|
||||||
<h1 class="mt-1 text-3xl font-semibold tracking-tight">{chip.model}</h1>
|
{chipTitle(chip.brand, chip.model)}
|
||||||
<p class="tabular mt-1.5 text-xs text-muted-foreground">
|
</h1>
|
||||||
{chip.codename ?? ''} {chip.aliases.length > 0 && `· 别名:${chip.aliases.join('、')}`}
|
<p class="tabular mt-2 text-xs text-muted-foreground">
|
||||||
|
{chip.codename ?? ''}
|
||||||
|
{chip.codename && aliases.length > 0 ? ' · ' : ''}
|
||||||
|
{aliases.length > 0 ? `别名:${aliases.join('、')}` : ''}
|
||||||
</p>
|
</p>
|
||||||
|
<div class="mt-3 flex flex-wrap items-center gap-1.5 text-[11px]">
|
||||||
|
{
|
||||||
|
overview?.tier && (
|
||||||
|
<span class="rounded-full border border-primary/50 bg-primary/10 px-2.5 py-0.5 text-primary">
|
||||||
|
{overview.tier}
|
||||||
|
</span>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
{overview?.series && (
|
||||||
|
<span class="rounded-full border border-border px-2.5 py-0.5 text-muted-foreground">{overview.series}</span>
|
||||||
|
)}
|
||||||
|
{overview?.releaseYear && (
|
||||||
|
<span class="tabular rounded-full border border-border px-2.5 py-0.5 text-muted-foreground">
|
||||||
|
{overview.releaseYear} 年
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{chip.process && (
|
||||||
|
<span class="rounded-full border border-border px-2.5 py-0.5 text-muted-foreground">{chip.process}</span>
|
||||||
|
)}
|
||||||
|
{devices.length > 0 && (
|
||||||
|
<span class="tabular rounded-full border border-border px-2.5 py-0.5 text-muted-foreground">
|
||||||
|
{devices.length} 台机型
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<dl class="tabular mt-6 grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-6">
|
<dl class="tabular mt-6 grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-6">
|
||||||
{
|
{
|
||||||
[
|
keyCards.map((card) => (
|
||||||
['制程', chip.process],
|
<div class="flex min-h-[102px] flex-col justify-between rounded-lg border border-border bg-card p-3.5">
|
||||||
['架构', chip.arch],
|
<dt class="text-[11px] text-muted-foreground">{card.label}</dt>
|
||||||
['CPU 核心', coreTotal ? `${coreTotal} 核` : undefined],
|
<dd class="mt-1 line-clamp-2 text-[15px] font-semibold leading-snug">{card.value ?? '—'}</dd>
|
||||||
['GPU', detail.gpuBlock?.name],
|
{card.sub && <span class="mt-1 block truncate text-[11px] text-muted-foreground">{card.sub}</span>}
|
||||||
['NPU', detail.npuBlock?.name],
|
|
||||||
['基带', detail.modemBlock],
|
|
||||||
].map(([label, value]) => (
|
|
||||||
<div class="rounded-lg border border-border bg-card p-3">
|
|
||||||
<dt class="text-[11px] text-muted-foreground">{label}</dt>
|
|
||||||
<dd class="mt-1 truncate text-sm font-medium">{value ?? '—'}</dd>
|
|
||||||
</div>
|
</div>
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
</dl>
|
</dl>
|
||||||
|
|
||||||
|
{
|
||||||
|
detail.traits.length > 0 && (
|
||||||
|
<div class="mt-3 flex flex-wrap gap-1.5">
|
||||||
|
{detail.traits.map((trait) => (
|
||||||
|
<span class="rounded border border-border bg-secondary/40 px-2 py-0.5 text-[11px] text-foreground/80">
|
||||||
|
{trait}
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
<section class="mt-10">
|
<section class="mt-10">
|
||||||
<h2 class="text-lg font-semibold">CPU 核心簇</h2>
|
<h2 class="text-lg font-semibold">CPU 与缓存</h2>
|
||||||
|
<div class="tabular mt-3 grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
|
||||||
|
{
|
||||||
|
[
|
||||||
|
['核心总数', coreTotal > 0 ? `${coreTotal} 核` : undefined],
|
||||||
|
['最高频率', cpu?.maxFreq],
|
||||||
|
['微架构', cpu?.arch],
|
||||||
|
['架构类型', cpu?.archType],
|
||||||
|
['L3 缓存', cpu?.cacheL3],
|
||||||
|
['系统缓存', cpu?.systemCache ?? detail.systemCache],
|
||||||
|
].map(([label, value]) => (
|
||||||
|
<div class="rounded-lg border border-border bg-card px-4 py-3">
|
||||||
|
<div class="text-[11px] text-muted-foreground">{label}</div>
|
||||||
|
<div class="mt-1 truncate text-sm font-medium">{value ?? '—'}</div>
|
||||||
|
</div>
|
||||||
|
))
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{detail.cpuClusters.length > 0 ? (
|
||||||
<div class="mt-3 overflow-hidden rounded-lg border border-border">
|
<div class="mt-3 overflow-hidden rounded-lg border border-border">
|
||||||
<table class="w-full border-collapse text-sm">
|
<table class="w-full border-collapse text-sm">
|
||||||
<thead class="bg-secondary/60 text-xs text-muted-foreground">
|
<thead class="bg-secondary/60 text-xs text-muted-foreground">
|
||||||
@@ -59,51 +140,55 @@ const coreTotal = detail.cpuClusters.reduce(
|
|||||||
<th class="px-4 py-2 text-left font-normal">微架构</th>
|
<th class="px-4 py-2 text-left font-normal">微架构</th>
|
||||||
<th class="px-4 py-2 text-right font-normal">数量</th>
|
<th class="px-4 py-2 text-right font-normal">数量</th>
|
||||||
<th class="px-4 py-2 text-right font-normal">最高频率</th>
|
<th class="px-4 py-2 text-right font-normal">最高频率</th>
|
||||||
|
<th class="px-4 py-2 text-right font-normal">L2</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{
|
{detail.cpuClusters.map((cluster) =>
|
||||||
detail.cpuClusters.map((cluster) =>
|
|
||||||
cluster.cores.map((core) => (
|
cluster.cores.map((core) => (
|
||||||
<tr class="border-t border-border/60">
|
<tr class="border-t border-border/60">
|
||||||
<td class="px-4 py-2">{cluster.name ?? '—'}</td>
|
<td class="px-4 py-2">{cluster.name ?? '—'}</td>
|
||||||
<td class="px-4 py-2">{core.microArch ?? '—'}</td>
|
<td class="px-4 py-2">{core.microArch ?? '—'}</td>
|
||||||
<td class="tabular px-4 py-2 text-right">{core.count ?? '—'}</td>
|
<td class="tabular px-4 py-2 text-right">{core.count ?? '—'}</td>
|
||||||
<td class="tabular px-4 py-2 text-right">{core.clockMax ?? '—'}</td>
|
<td class="tabular px-4 py-2 text-right">{core.clockMax ?? '—'}</td>
|
||||||
|
<td class="tabular px-4 py-2 text-right">{core.l2 ?? '—'}</td>
|
||||||
</tr>
|
</tr>
|
||||||
)),
|
)),
|
||||||
)
|
)}
|
||||||
}
|
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
|
) : (
|
||||||
|
<p class="mt-3 text-sm text-muted-foreground">暂无 CPU 核心簇数据。</p>
|
||||||
|
)}
|
||||||
|
{cpu?.config && <p class="mt-2 text-xs text-muted-foreground">配置:{cpu.config}</p>}
|
||||||
|
{cpu?.note && <p class="mt-1 text-xs text-muted-foreground">缓存说明:{cpu.note}</p>}
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section class="mt-10 grid gap-3 sm:grid-cols-2">
|
<section class="mt-10 grid gap-3 lg:grid-cols-2">
|
||||||
<div class="rounded-lg border border-border bg-card p-5">
|
<div class="rounded-lg border border-border bg-card p-5">
|
||||||
<h3 class="text-sm font-semibold">GPU</h3>
|
<h3 class="text-sm font-semibold">GPU</h3>
|
||||||
<dl class="tabular mt-3 grid grid-cols-2 gap-x-3 gap-y-1 text-xs">
|
<div class="mt-2 text-base font-medium">{detail.gpuBlock?.name ?? '—'}</div>
|
||||||
<dt class="text-muted-foreground">型号</dt>
|
{detail.gpuBlock?.apis && detail.gpuBlock.apis.length > 0 && (
|
||||||
<dd class="text-right">{detail.gpuBlock?.name ?? '—'}</dd>
|
<p class="mt-3 text-xs text-muted-foreground">API:{detail.gpuBlock.apis.join(' / ')}</p>
|
||||||
<dt class="text-muted-foreground">最高频率</dt>
|
)}
|
||||||
<dd class="text-right">{detail.gpuBlock?.clockMax ?? '—'}</dd>
|
{detail.gpuBlock?.features && detail.gpuBlock.features.length > 0 && (
|
||||||
<dt class="text-muted-foreground">API</dt>
|
<p class="mt-2 text-xs leading-relaxed text-muted-foreground">
|
||||||
<dd class="text-right">{detail.gpuBlock?.apis.join(' / ') || '—'}</dd>
|
{detail.gpuBlock.features.join(';')}
|
||||||
</dl>
|
</p>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="rounded-lg border border-border bg-card p-5">
|
<div class="rounded-lg border border-border bg-card p-5">
|
||||||
<h3 class="text-sm font-semibold">内存与存储支持</h3>
|
<h3 class="text-sm font-semibold">NPU / AI</h3>
|
||||||
<dl class="tabular mt-3 grid grid-cols-2 gap-x-3 gap-y-1 text-xs">
|
<div class="mt-2 text-base font-medium">{detail.npuBlock?.name ?? '—'}</div>
|
||||||
<dt class="text-muted-foreground">内存类型</dt>
|
{detail.npuBlock?.tops && (
|
||||||
<dd class="text-right">{detail.memorySupport?.type ?? '—'}</dd>
|
<p class="mt-2 text-xs text-muted-foreground">算力:{detail.npuBlock.tops}</p>
|
||||||
<dt class="text-muted-foreground">带宽</dt>
|
)}
|
||||||
<dd class="text-right">{detail.memorySupport?.bandwidth ?? '—'}</dd>
|
{detail.npuBlock?.features && detail.npuBlock.features.length > 0 && (
|
||||||
<dt class="text-muted-foreground">存储</dt>
|
<p class="mt-2 text-xs leading-relaxed text-muted-foreground">
|
||||||
<dd class="text-right">{detail.storageSupport ?? '—'}</dd>
|
{detail.npuBlock.features.join(';')}
|
||||||
<dt class="text-muted-foreground">显示支持</dt>
|
</p>
|
||||||
<dd class="text-right">{detail.displaySupport ?? '—'}</dd>
|
)}
|
||||||
</dl>
|
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
@@ -111,17 +196,151 @@ const coreTotal = detail.cpuClusters.reduce(
|
|||||||
detail.benchmarks.length > 0 && (
|
detail.benchmarks.length > 0 && (
|
||||||
<section class="mt-10">
|
<section class="mt-10">
|
||||||
<h2 class="text-lg font-semibold">跑分</h2>
|
<h2 class="text-lg font-semibold">跑分</h2>
|
||||||
<div class="mt-3 grid gap-3 sm:grid-cols-3">
|
<div class="mt-3 grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
|
||||||
{detail.benchmarks.map((b) => (
|
{detail.benchmarks.map((benchmark) => (
|
||||||
<div class="rounded-lg border border-border bg-card p-4">
|
<div class="rounded-lg border border-border bg-card p-4">
|
||||||
<div class="text-xs text-muted-foreground">{b.name}</div>
|
<div class="text-xs text-muted-foreground">{benchmark.name}</div>
|
||||||
<div class="tabular mt-1 text-xl font-semibold">
|
<div class="tabular mt-1 text-2xl font-semibold tracking-tight">
|
||||||
{b.score}
|
{benchmark.score}
|
||||||
<span class="ml-1 text-xs font-normal text-muted-foreground">{b.unit ?? ''}</span>
|
{benchmark.unit && (
|
||||||
|
<span class="ml-1 text-[11px] font-normal text-muted-foreground">{benchmark.unit}</span>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
{hasAntutuBreakdown && (
|
||||||
|
<div class="tabular mt-3 grid grid-cols-2 gap-2 text-xs sm:grid-cols-4">
|
||||||
|
{[
|
||||||
|
['CPU', antutu?.cpu],
|
||||||
|
['GPU', antutu?.gpu],
|
||||||
|
['内存', antutu?.memory],
|
||||||
|
['UX', antutu?.ux],
|
||||||
|
].map(([label, value]) => (
|
||||||
|
<div class="rounded-md border border-border/70 bg-card/60 px-3 py-2">
|
||||||
|
<span class="text-muted-foreground">安兔兔 {label}</span>
|
||||||
|
<span class="float-right font-medium">{value ?? '—'}</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{(detail.benchmarkInfo?.note || detail.benchmarkInfo?.cpuIndexNote) && (
|
||||||
|
<div class="mt-2 space-y-1 text-[11px] text-muted-foreground">
|
||||||
|
{detail.benchmarkInfo.note && <p>{detail.benchmarkInfo.note}</p>}
|
||||||
|
{detail.benchmarkInfo.cpuIndexNote && <p>{detail.benchmarkInfo.cpuIndexNote}</p>}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
<section class="mt-10 grid gap-3 lg:grid-cols-2">
|
||||||
|
<div class="rounded-lg border border-border bg-card p-5">
|
||||||
|
<h3 class="text-sm font-semibold">内存与存储支持</h3>
|
||||||
|
<dl class="tabular mt-3 grid grid-cols-[auto_1fr] gap-x-4 gap-y-2 text-xs">
|
||||||
|
<dt class="text-muted-foreground">内存类型</dt>
|
||||||
|
<dd class="text-right">{detail.memorySupport?.type ?? '—'}</dd>
|
||||||
|
<dt class="text-muted-foreground">内存频率</dt>
|
||||||
|
<dd class="text-right">{detail.memorySupport?.maxClock ?? '—'}</dd>
|
||||||
|
<dt class="text-muted-foreground">内存带宽</dt>
|
||||||
|
<dd class="text-right">{detail.memorySupport?.bandwidth ?? '—'}</dd>
|
||||||
|
<dt class="text-muted-foreground">存储支持</dt>
|
||||||
|
<dd class="text-right">{detail.storageSupport ?? '—'}</dd>
|
||||||
|
<dt class="text-muted-foreground">显示支持</dt>
|
||||||
|
<dd class="text-right">{detail.displayBlock?.maxResolution ?? detail.displaySupport ?? '—'}</dd>
|
||||||
|
<dt class="text-muted-foreground">最高刷新</dt>
|
||||||
|
<dd class="text-right">{detail.displayBlock?.maxRefresh ?? '—'}</dd>
|
||||||
|
{detail.displayBlock?.externalMax && (
|
||||||
|
<>
|
||||||
|
<dt class="text-muted-foreground">外接显示</dt>
|
||||||
|
<dd class="text-right">{detail.displayBlock.externalMax}</dd>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</dl>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="rounded-lg border border-border bg-card p-5">
|
||||||
|
<h3 class="text-sm font-semibold">影像与连接</h3>
|
||||||
|
<dl class="tabular mt-3 grid grid-cols-[auto_1fr] gap-x-4 gap-y-2 text-xs">
|
||||||
|
<dt class="text-muted-foreground">ISP</dt>
|
||||||
|
<dd class="text-right">{detail.cameraBlock?.isp ?? '—'}</dd>
|
||||||
|
<dt class="text-muted-foreground">单摄最高</dt>
|
||||||
|
<dd class="text-right">{detail.cameraBlock?.maxSensor ?? '—'}</dd>
|
||||||
|
<dt class="text-muted-foreground">视频录制</dt>
|
||||||
|
<dd class="text-right">{detail.cameraBlock?.videoCapture ?? '—'}</dd>
|
||||||
|
<dt class="text-muted-foreground">Wi-Fi</dt>
|
||||||
|
<dd class="text-right">{detail.connectivityBlock?.wifi ?? '—'}</dd>
|
||||||
|
<dt class="text-muted-foreground">蓝牙</dt>
|
||||||
|
<dd class="text-right">{detail.connectivityBlock?.bluetooth ?? '—'}</dd>
|
||||||
|
<dt class="text-muted-foreground">峰值速率</dt>
|
||||||
|
<dd class="text-right">{detail.connectivityBlock?.peakSpeed ?? '—'}</dd>
|
||||||
|
</dl>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{
|
||||||
|
detail.caveats.length > 0 && (
|
||||||
|
<section class="mt-10">
|
||||||
|
<h2 class="text-lg font-semibold">注意事项</h2>
|
||||||
|
<ul class="mt-3 list-disc space-y-1 pl-5 text-sm text-muted-foreground">
|
||||||
|
{detail.caveats.map((item) => (
|
||||||
|
<li>{item}</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
specGroups.length > 0 && (
|
||||||
|
<section class="mt-10">
|
||||||
|
<h2 class="text-lg font-semibold">完整规格</h2>
|
||||||
|
<div class="mt-3 space-y-2">
|
||||||
|
{specGroups.map(([group, rows]) => (
|
||||||
|
<details class="rounded-lg border border-border bg-card">
|
||||||
|
<summary class="cursor-pointer select-none px-4 py-3 text-sm font-medium">
|
||||||
|
{group}
|
||||||
|
<span class="ml-2 text-xs font-normal text-muted-foreground">{Object.keys(rows).length} 项</span>
|
||||||
|
</summary>
|
||||||
|
<div class="overflow-x-auto border-t border-border/60">
|
||||||
|
<table class="w-full border-collapse text-sm">
|
||||||
|
<tbody>
|
||||||
|
{Object.entries(rows).map(([key, value]) => (
|
||||||
|
<tr class="border-b border-border/50 last:border-b-0">
|
||||||
|
<th class="w-44 px-4 py-2 text-left align-top text-xs font-normal text-muted-foreground">
|
||||||
|
{key}
|
||||||
|
</th>
|
||||||
|
<td class="px-4 py-2 align-top leading-relaxed">{value}</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
detail.sourceUrls.length > 0 && (
|
||||||
|
<section class="mt-10">
|
||||||
|
<h2 class="text-lg font-semibold">资料来源</h2>
|
||||||
|
<ul class="mt-3 space-y-1 text-xs">
|
||||||
|
{detail.sourceUrls.map((url) => (
|
||||||
|
<li>
|
||||||
|
<a
|
||||||
|
href={url}
|
||||||
|
target="_blank"
|
||||||
|
rel="nofollow noopener noreferrer"
|
||||||
|
class="break-all text-primary hover:underline"
|
||||||
|
>
|
||||||
|
{url}
|
||||||
|
</a>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
</section>
|
</section>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -129,15 +348,18 @@ const coreTotal = detail.cpuClusters.reduce(
|
|||||||
<section class="mt-10">
|
<section class="mt-10">
|
||||||
<h2 class="text-lg font-semibold">搭载该芯片的设备</h2>
|
<h2 class="text-lg font-semibold">搭载该芯片的设备</h2>
|
||||||
{devices.length > 0 ? (
|
{devices.length > 0 ? (
|
||||||
<ul class="mt-3 grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
<ul class="reveal-grid mt-3 grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||||
{devices.map((d) => (
|
{devices.map((device) => (
|
||||||
<li>
|
<li>
|
||||||
<a
|
<a
|
||||||
href={`/devices/${d.slug}`}
|
href={`/devices/${device.slug}`}
|
||||||
class="block rounded-lg border border-border bg-card p-4 transition-colors hover:border-primary/40"
|
class="block rounded-lg border border-border bg-card p-4 transition-colors hover:border-primary/40"
|
||||||
>
|
>
|
||||||
<div class="text-xs text-muted-foreground">{d.brand}</div>
|
<div class="truncate text-sm font-medium">{deviceTitle(device.brand, device.model)}</div>
|
||||||
<div class="text-sm font-medium">{d.model}</div>
|
<div class="tabular mt-1 text-[11px] text-muted-foreground">
|
||||||
|
{device.releaseDate ?? device.announceDate ?? lifecycleText(device.lifecycle)} ·{' '}
|
||||||
|
{device.specs.display?.size ?? '—'}
|
||||||
|
</div>
|
||||||
</a>
|
</a>
|
||||||
</li>
|
</li>
|
||||||
))}
|
))}
|
||||||
|
|||||||
+183
-20
@@ -1,41 +1,202 @@
|
|||||||
---
|
---
|
||||||
|
import Pagination from '@/components/Pagination.astro';
|
||||||
import BaseLayout from '@/layouts/BaseLayout.astro';
|
import BaseLayout from '@/layouts/BaseLayout.astro';
|
||||||
import { listChips } from '@/lib/repo';
|
import { listChipBrands, listChipsPaged, type ChipSort } from '@/lib/repo';
|
||||||
|
import { brandLabel, chipTitle } from '@/lib/utils';
|
||||||
|
|
||||||
const chips = listChips({ type: 'soc' });
|
const PAGE_SIZE = 24;
|
||||||
|
const params = Astro.url.searchParams;
|
||||||
|
const q = (params.get('q') ?? '').trim();
|
||||||
|
const brand = params.get('brand') ?? undefined;
|
||||||
|
const sortParam = params.get('sort') ?? 'tier';
|
||||||
|
const sort: ChipSort = ['tier', 'year', 'name', 'brand'].includes(sortParam)
|
||||||
|
? (sortParam as ChipSort)
|
||||||
|
: 'tier';
|
||||||
|
const pageParam = Number.parseInt(params.get('page') ?? '1', 10);
|
||||||
|
|
||||||
|
const result = listChipsPaged({
|
||||||
|
type: 'soc',
|
||||||
|
q: q || undefined,
|
||||||
|
brand,
|
||||||
|
sort,
|
||||||
|
page: Number.isFinite(pageParam) ? pageParam : 1,
|
||||||
|
pageSize: PAGE_SIZE,
|
||||||
|
});
|
||||||
|
const brands = listChipBrands('soc');
|
||||||
|
|
||||||
|
function urlWith(overrides: Record<string, string | undefined>): string {
|
||||||
|
const next = new URLSearchParams();
|
||||||
|
const merged: Record<string, string | undefined> = {
|
||||||
|
q: q || undefined,
|
||||||
|
brand,
|
||||||
|
sort: sort === 'tier' ? undefined : sort,
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
for (const [key, value] of Object.entries(merged)) {
|
||||||
|
if (value) next.set(key, value);
|
||||||
|
}
|
||||||
|
const query = next.toString();
|
||||||
|
return query ? `/chips?${query}` : '/chips';
|
||||||
|
}
|
||||||
|
|
||||||
|
const pageHref = (target: number) =>
|
||||||
|
`${urlWith({ page: target === 1 ? undefined : String(target) })}#list`;
|
||||||
|
|
||||||
|
const sortOptions: { key: ChipSort; label: string }[] = [
|
||||||
|
{ key: 'tier', label: '性能优先' },
|
||||||
|
{ key: 'year', label: '最新年份' },
|
||||||
|
{ key: 'name', label: '按名称' },
|
||||||
|
{ key: 'brand', label: '按品牌' },
|
||||||
|
];
|
||||||
|
|
||||||
|
const tierClass = (tier?: string) =>
|
||||||
|
tier === '旗舰'
|
||||||
|
? 'border-primary/50 bg-primary/10 text-primary'
|
||||||
|
: tier === '高端'
|
||||||
|
? 'border-border bg-secondary/50 text-foreground'
|
||||||
|
: 'border-border text-muted-foreground';
|
||||||
---
|
---
|
||||||
|
|
||||||
<BaseLayout title="芯片库 · LFSpecs">
|
<BaseLayout title="SoC 芯片库 · LFSpecs">
|
||||||
<div class="flex items-baseline justify-between">
|
<header class="flex flex-wrap items-baseline justify-between gap-3">
|
||||||
<h1 class="text-2xl font-semibold tracking-tight">SoC</h1>
|
<h1 class="text-2xl font-semibold tracking-tight">SoC</h1>
|
||||||
<span class="tabular text-sm text-muted-foreground">{chips.length} 颗</span>
|
<span class="tabular text-sm text-muted-foreground">{result.total} 颗</span>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<form action="/chips" method="get" class="mt-5 flex flex-wrap gap-2">
|
||||||
|
<input
|
||||||
|
type="search"
|
||||||
|
name="q"
|
||||||
|
value={q}
|
||||||
|
placeholder="搜索型号、代号、别名"
|
||||||
|
class="h-9 min-w-0 flex-1 rounded-md border border-border bg-card px-3 text-sm placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring"
|
||||||
|
/>
|
||||||
|
{brand && <input type="hidden" name="brand" value={brand} />}
|
||||||
|
{sort !== 'tier' && <input type="hidden" name="sort" value={sort} />}
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
class="h-9 rounded-md bg-primary px-4 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90"
|
||||||
|
>
|
||||||
|
搜索
|
||||||
|
</button>
|
||||||
|
{q && (
|
||||||
|
<a
|
||||||
|
href={urlWith({ q: undefined })}
|
||||||
|
class="inline-flex h-9 items-center rounded-md border border-border px-3 text-sm text-muted-foreground transition-colors hover:text-foreground"
|
||||||
|
>
|
||||||
|
清除
|
||||||
|
</a>
|
||||||
|
)}
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<div class="mt-4 flex flex-wrap items-center gap-2">
|
||||||
|
<a
|
||||||
|
href={urlWith({ brand: undefined })}
|
||||||
|
class:list={[
|
||||||
|
'rounded-full border px-3 py-1 text-xs transition-colors',
|
||||||
|
brand ? 'border-border text-muted-foreground hover:text-foreground' : 'border-primary/50 bg-primary/10 text-primary',
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
全部品牌
|
||||||
|
</a>
|
||||||
|
{
|
||||||
|
brands.map((item) => (
|
||||||
|
<a
|
||||||
|
href={urlWith({ brand: item.brand })}
|
||||||
|
class:list={[
|
||||||
|
'rounded-full border px-3 py-1 text-xs transition-colors',
|
||||||
|
brand === item.brand
|
||||||
|
? 'border-primary/50 bg-primary/10 text-primary'
|
||||||
|
: 'border-border text-muted-foreground hover:text-foreground',
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
{brandLabel(item.brand)} <span class="tabular opacity-60">{item.count}</span>
|
||||||
|
</a>
|
||||||
|
))
|
||||||
|
}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="mt-6 grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
<div class="mt-4 flex flex-wrap items-center gap-1 text-xs text-muted-foreground">
|
||||||
|
<span class="mr-1">排序</span>
|
||||||
{
|
{
|
||||||
chips.map((chip) => {
|
sortOptions.map((option) => (
|
||||||
const clusters = chip.detail.cpuClusters ?? [];
|
<a
|
||||||
const coreCount = clusters.reduce(
|
href={urlWith({ sort: option.key === 'tier' ? undefined : option.key })}
|
||||||
(sum, c) => sum + (c.cores ?? []).reduce((n, x) => n + (x.count ?? 0), 0),
|
class:list={[
|
||||||
|
'rounded-md px-2 py-1 transition-colors',
|
||||||
|
sort === option.key ? 'bg-accent text-foreground' : 'hover:text-foreground',
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
{option.label}
|
||||||
|
</a>
|
||||||
|
))
|
||||||
|
}
|
||||||
|
{result.pages > 1 && (
|
||||||
|
<span class="tabular ml-auto text-muted-foreground">
|
||||||
|
第 {result.page} / {result.pages} 页
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="list" class="reveal-grid mt-6 grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||||
|
{
|
||||||
|
result.items.map((chip) => {
|
||||||
|
const detail = chip.detail;
|
||||||
|
const coreCount =
|
||||||
|
detail.cpuBlock?.cores ??
|
||||||
|
detail.cpuClusters.reduce(
|
||||||
|
(sum, cluster) => sum + cluster.cores.reduce((n, core) => n + (core.count ?? 0), 0),
|
||||||
0,
|
0,
|
||||||
);
|
);
|
||||||
|
const tier = detail.overview?.tier;
|
||||||
|
const year = detail.overview?.releaseYear;
|
||||||
|
const series = detail.overview?.series;
|
||||||
|
const phoneCount = detail.overview?.phoneCount ?? 0;
|
||||||
return (
|
return (
|
||||||
<a
|
<a
|
||||||
href={`/chips/${chip.slug}`}
|
href={`/chips/${chip.slug}`}
|
||||||
class="group rounded-lg border border-border bg-card p-5 transition-colors hover:border-primary/40"
|
class="group flex flex-col rounded-lg border border-border bg-card p-5 transition-colors hover:border-primary/40 hover:bg-accent/20"
|
||||||
>
|
>
|
||||||
<div class="text-xs text-muted-foreground">{chip.brand}</div>
|
<div class="flex items-start justify-between gap-2">
|
||||||
<div class="mt-0.5 text-base font-semibold">{chip.model}</div>
|
<div class="min-w-0">
|
||||||
|
<div class="truncate text-base font-semibold leading-tight group-hover:text-primary">
|
||||||
|
{chipTitle(chip.brand, chip.model)}
|
||||||
|
</div>
|
||||||
|
<div class="mt-1 truncate text-[11px] text-muted-foreground">
|
||||||
|
{chip.codename ?? detail.overview?.nameEn ?? ''}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{tier && (
|
||||||
|
<span
|
||||||
|
class:list={[
|
||||||
|
'shrink-0 rounded-full border px-2 py-0.5 text-[11px]',
|
||||||
|
tierClass(tier),
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
{tier}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
<dl class="tabular mt-4 grid grid-cols-2 gap-x-4 gap-y-1 text-xs">
|
<dl class="tabular mt-4 grid grid-cols-2 gap-x-4 gap-y-1 text-xs">
|
||||||
<dt class="text-muted-foreground">制程</dt>
|
<dt class="text-muted-foreground">制程</dt>
|
||||||
<dd class="truncate text-right">{chip.process ?? '—'}</dd>
|
<dd class="truncate text-right">{chip.process ?? '—'}</dd>
|
||||||
<dt class="text-muted-foreground">核心</dt>
|
<dt class="text-muted-foreground">CPU</dt>
|
||||||
<dd class="text-right">{coreCount || '—'} 核</dd>
|
<dd class="truncate text-right">
|
||||||
|
{coreCount > 0 ? `${coreCount} 核` : '—'}
|
||||||
|
{detail.cpuBlock?.maxFreq ? ` · ${detail.cpuBlock.maxFreq}` : ''}
|
||||||
|
</dd>
|
||||||
<dt class="text-muted-foreground">GPU</dt>
|
<dt class="text-muted-foreground">GPU</dt>
|
||||||
<dd class="truncate text-right">{chip.detail.gpuBlock?.name ?? '—'}</dd>
|
<dd class="truncate text-right">{detail.gpuBlock?.name ?? '—'}</dd>
|
||||||
<dt class="text-muted-foreground">架构</dt>
|
<dt class="text-muted-foreground">NPU</dt>
|
||||||
<dd class="truncate text-right">{chip.arch ?? '—'}</dd>
|
<dd class="truncate text-right">{detail.npuBlock?.name ?? '—'}</dd>
|
||||||
</dl>
|
</dl>
|
||||||
|
|
||||||
|
<div class="mt-auto flex flex-wrap items-center gap-x-2 gap-y-1 pt-4 text-[11px] text-muted-foreground">
|
||||||
|
{year && <span class="tabular">{year} 年</span>}
|
||||||
|
{series && <span>{series}</span>}
|
||||||
|
{phoneCount > 0 && <span class="tabular">{phoneCount} 台机型</span>}
|
||||||
|
</div>
|
||||||
</a>
|
</a>
|
||||||
);
|
);
|
||||||
})
|
})
|
||||||
@@ -43,10 +204,12 @@ const chips = listChips({ type: 'soc' });
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{
|
{
|
||||||
chips.length === 0 && (
|
result.total === 0 && (
|
||||||
<p class="mt-6 rounded-lg border border-dashed border-border p-8 text-center text-sm text-muted-foreground">
|
<p class="mt-6 rounded-lg border border-dashed border-border p-8 text-center text-sm text-muted-foreground">
|
||||||
暂无芯片数据,运行 <code class="font-mono text-foreground">pnpm db:seed</code> 写入种子数据。
|
没有匹配的芯片。试试清除关键词或换一个品牌。
|
||||||
</p>
|
</p>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
<Pagination page={result.page} pages={result.pages} buildHref={pageHref} />
|
||||||
</BaseLayout>
|
</BaseLayout>
|
||||||
@@ -0,0 +1,418 @@
|
|||||||
|
---
|
||||||
|
import Pagination from '@/components/Pagination.astro';
|
||||||
|
import BaseLayout from '@/layouts/BaseLayout.astro';
|
||||||
|
import { buildComparison } from '@/lib/compare';
|
||||||
|
import { getDevice, listBrands, listDevicesPaged } from '@/lib/repo';
|
||||||
|
import type { PhoneDevice } from '@/lib/schema';
|
||||||
|
import { brandLabel, deviceTitle } from '@/lib/utils';
|
||||||
|
|
||||||
|
const PAGE_SIZE = 24;
|
||||||
|
|
||||||
|
const params = Astro.url.searchParams;
|
||||||
|
const ids = [
|
||||||
|
...new Set(
|
||||||
|
params
|
||||||
|
.getAll('ids')
|
||||||
|
.flatMap((value) => value.split(','))
|
||||||
|
.map((value) => value.trim())
|
||||||
|
.filter(Boolean),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
const onlyDiff = params.get('diff') === '1';
|
||||||
|
const pick = params.get('pick') === '1';
|
||||||
|
const q = (params.get('q') ?? '').trim();
|
||||||
|
const brand = params.get('brand') ?? undefined;
|
||||||
|
const pageParam = Number.parseInt(params.get('page') ?? '1', 10);
|
||||||
|
|
||||||
|
const found = ids
|
||||||
|
.map((id) => ({ id, device: getDevice(id) }))
|
||||||
|
.filter((entry): entry is { id: string; device: PhoneDevice } => Boolean(entry.device));
|
||||||
|
const devices = found.map((entry) => entry.device);
|
||||||
|
const missing = ids.filter((id) => !found.some((entry) => entry.id === id));
|
||||||
|
|
||||||
|
const sameCategory = new Set(devices.map((device) => device.category)).size <= 1;
|
||||||
|
const canCompare =
|
||||||
|
devices.length >= 2 && devices.length <= 4 && missing.length === 0 && sameCategory;
|
||||||
|
const showPicker = pick || !canCompare;
|
||||||
|
|
||||||
|
const comparison = canCompare ? buildComparison(devices) : null;
|
||||||
|
const visibleGroups =
|
||||||
|
comparison && onlyDiff
|
||||||
|
? comparison.groups
|
||||||
|
.map((group) => ({ ...group, rows: group.rows.filter((row) => row.different) }))
|
||||||
|
.filter((group) => group.rows.length > 0)
|
||||||
|
: comparison?.groups ?? [];
|
||||||
|
const visibleRowCount = visibleGroups.reduce((sum, group) => sum + group.rows.length, 0);
|
||||||
|
const canonicalIds = ids.join(',');
|
||||||
|
|
||||||
|
const picker = listDevicesPaged({
|
||||||
|
category: 'phone',
|
||||||
|
q: q || undefined,
|
||||||
|
brand,
|
||||||
|
sort: 'latest',
|
||||||
|
page: Number.isFinite(pageParam) ? pageParam : 1,
|
||||||
|
pageSize: PAGE_SIZE,
|
||||||
|
});
|
||||||
|
const brands = listBrands('phone');
|
||||||
|
|
||||||
|
let error = '';
|
||||||
|
if (missing.length > 0) error = `未找到:${missing.join('、')}`;
|
||||||
|
else if (ids.length > 4) error = '最多同时对比 4 款设备。';
|
||||||
|
else if (!sameCategory) error = '只能对比同一类别的设备。';
|
||||||
|
|
||||||
|
function compareUrl(
|
||||||
|
nextIds: string[],
|
||||||
|
options: { pick?: boolean; q?: string; brand?: string; page?: number; diff?: boolean } = {},
|
||||||
|
): string {
|
||||||
|
const search = new URLSearchParams();
|
||||||
|
if (nextIds.length > 0) search.set('ids', nextIds.join(','));
|
||||||
|
if (options.pick) search.set('pick', '1');
|
||||||
|
if (options.q) search.set('q', options.q);
|
||||||
|
if (options.brand) search.set('brand', options.brand);
|
||||||
|
if (options.page && options.page > 1) search.set('page', String(options.page));
|
||||||
|
if (options.diff) search.set('diff', '1');
|
||||||
|
const value = search.toString();
|
||||||
|
return value ? `/compare?${value}` : '/compare';
|
||||||
|
}
|
||||||
|
|
||||||
|
const pickerHref = (target: number) =>
|
||||||
|
`${compareUrl(ids, { pick: true, q: q || undefined, brand, page: target })}#picker`;
|
||||||
|
const viewHref = compareUrl(ids, { diff: onlyDiff });
|
||||||
|
const editHref = compareUrl(ids, { pick: true, diff: onlyDiff });
|
||||||
|
|
||||||
|
const lifecycleText = (value: string) =>
|
||||||
|
value === 'discontinued' ? '已停产' : value === 'announced' ? '已发布' : '在售';
|
||||||
|
---
|
||||||
|
|
||||||
|
<BaseLayout title={showPicker ? '选择对比设备 · LFSpecs' : '设备对比 · LFSpecs'}>
|
||||||
|
<nav class="print-hidden text-xs text-muted-foreground">
|
||||||
|
<a href="/devices" class="hover:text-foreground">手机</a>
|
||||||
|
<span class="mx-1.5">/</span>
|
||||||
|
<span class="text-foreground">对比</span>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
{devices.length > 0 && (
|
||||||
|
<div
|
||||||
|
data-compare-selection
|
||||||
|
data-items={JSON.stringify(
|
||||||
|
devices.map((device) => ({
|
||||||
|
slug: device.slug,
|
||||||
|
name: deviceTitle(device.brand, device.model),
|
||||||
|
})),
|
||||||
|
)}
|
||||||
|
hidden
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{
|
||||||
|
showPicker ? (
|
||||||
|
<div id="picker">
|
||||||
|
<header class="mt-3 flex flex-wrap items-baseline justify-between gap-3">
|
||||||
|
<div>
|
||||||
|
<h1 class="text-2xl font-semibold tracking-tight">选择对比设备</h1>
|
||||||
|
<p class="tabular mt-1 text-xs text-muted-foreground">
|
||||||
|
已选 {ids.length} / 4 款 · 至少 2 款、最多 4 款
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div class="flex flex-wrap items-center gap-2">
|
||||||
|
{canCompare && (
|
||||||
|
<a
|
||||||
|
href={viewHref}
|
||||||
|
class="rounded-md bg-primary px-3.5 py-1.5 text-xs font-medium text-primary-foreground transition-colors hover:bg-primary/90"
|
||||||
|
>
|
||||||
|
查看对比({devices.length})
|
||||||
|
</a>
|
||||||
|
)}
|
||||||
|
{ids.length > 0 && (
|
||||||
|
<a
|
||||||
|
href="/compare?pick=1#picker"
|
||||||
|
class="rounded-md border border-border px-3 py-1.5 text-xs text-muted-foreground transition-colors hover:text-foreground"
|
||||||
|
>
|
||||||
|
清空
|
||||||
|
</a>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<p class="mt-4 rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive">
|
||||||
|
{error}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{devices.length > 0 && (
|
||||||
|
<div class="mt-4 flex flex-wrap items-center gap-1.5">
|
||||||
|
{devices.map((device) => (
|
||||||
|
<span class="inline-flex items-center gap-1 rounded-full border border-primary/40 bg-primary/10 px-2.5 py-1 text-xs text-primary">
|
||||||
|
{deviceTitle(device.brand, device.model)}
|
||||||
|
<a
|
||||||
|
href={`${compareUrl(
|
||||||
|
ids.filter((id) => id !== device.slug),
|
||||||
|
{ pick: true, q: q || undefined, brand },
|
||||||
|
)}#picker`}
|
||||||
|
class="text-primary/70 hover:text-primary"
|
||||||
|
aria-label={`移除 ${deviceTitle(device.brand, device.model)}`}
|
||||||
|
>
|
||||||
|
×
|
||||||
|
</a>
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<form action="/compare" method="get" class="mt-4 flex flex-wrap gap-2">
|
||||||
|
{ids.length > 0 && <input type="hidden" name="ids" value={canonicalIds} />}
|
||||||
|
<input type="hidden" name="pick" value="1" />
|
||||||
|
{brand && <input type="hidden" name="brand" value={brand} />}
|
||||||
|
<input
|
||||||
|
type="search"
|
||||||
|
name="q"
|
||||||
|
value={q}
|
||||||
|
placeholder="搜索型号、别名、简介"
|
||||||
|
class="h-9 min-w-0 flex-1 rounded-md border border-border bg-card px-3 text-sm placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
class="h-9 rounded-md bg-primary px-4 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90"
|
||||||
|
>
|
||||||
|
搜索
|
||||||
|
</button>
|
||||||
|
{q && (
|
||||||
|
<a
|
||||||
|
href={compareUrl(ids, { pick: true, brand })}
|
||||||
|
class="inline-flex h-9 items-center rounded-md border border-border px-3 text-sm text-muted-foreground transition-colors hover:text-foreground"
|
||||||
|
>
|
||||||
|
清除
|
||||||
|
</a>
|
||||||
|
)}
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<div class="mt-3 flex flex-wrap items-center gap-2">
|
||||||
|
<a
|
||||||
|
href={compareUrl(ids, { pick: true, q: q || undefined })}
|
||||||
|
class:list={[
|
||||||
|
'rounded-full border px-3 py-1 text-xs transition-colors',
|
||||||
|
brand ? 'border-border text-muted-foreground hover:text-foreground' : 'border-primary/50 bg-primary/10 text-primary',
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
全部品牌
|
||||||
|
</a>
|
||||||
|
{
|
||||||
|
brands.map((item) => (
|
||||||
|
<a
|
||||||
|
href={compareUrl(ids, { pick: true, q: q || undefined, brand: item.brand })}
|
||||||
|
class:list={[
|
||||||
|
'rounded-full border px-3 py-1 text-xs transition-colors',
|
||||||
|
brand === item.brand
|
||||||
|
? 'border-primary/50 bg-primary/10 text-primary'
|
||||||
|
: 'border-border text-muted-foreground hover:text-foreground',
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
{brandLabel(item.brand)} <span class="tabular opacity-60">{item.count}</span>
|
||||||
|
</a>
|
||||||
|
))
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="mt-4 flex flex-wrap items-baseline justify-between gap-2">
|
||||||
|
<h2 class="text-sm font-semibold">搜索结果</h2>
|
||||||
|
<span class="tabular text-xs text-muted-foreground">{picker.total} 款</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="reveal-grid mt-3 grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
|
||||||
|
{
|
||||||
|
picker.items.map((device) => {
|
||||||
|
const selected = ids.includes(device.slug);
|
||||||
|
const full = ids.length >= 4;
|
||||||
|
return (
|
||||||
|
<div class="relative">
|
||||||
|
<a
|
||||||
|
href={`/devices/${device.slug}`}
|
||||||
|
class="block rounded-lg border border-border bg-card p-4 pr-16 transition-colors hover:border-primary/40"
|
||||||
|
>
|
||||||
|
<div class="truncate text-sm font-semibold">{deviceTitle(device.brand, device.model)}</div>
|
||||||
|
<div class="tabular mt-1 truncate text-[11px] text-muted-foreground">
|
||||||
|
{device.specs.platform?.chipset ?? '未填写 SoC'} · {device.specs.display?.size ?? '—'}
|
||||||
|
</div>
|
||||||
|
<div class="mt-2 text-[11px] text-muted-foreground">{lifecycleText(device.lifecycle)}</div>
|
||||||
|
</a>
|
||||||
|
{selected ? (
|
||||||
|
<a
|
||||||
|
href={`${compareUrl(
|
||||||
|
ids.filter((id) => id !== device.slug),
|
||||||
|
{ pick: true, q: q || undefined, brand },
|
||||||
|
)}#picker`}
|
||||||
|
class="absolute right-3 top-3 rounded-md border border-primary/50 bg-primary/10 px-2 py-1 text-[11px] text-primary"
|
||||||
|
>
|
||||||
|
已选 ×
|
||||||
|
</a>
|
||||||
|
) : full ? (
|
||||||
|
<span class="absolute right-3 top-3 rounded-md border border-border px-2 py-1 text-[11px] text-muted-foreground/60">
|
||||||
|
上限
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<a
|
||||||
|
href={`${compareUrl([...ids, device.slug], {
|
||||||
|
pick: true,
|
||||||
|
q: q || undefined,
|
||||||
|
brand,
|
||||||
|
})}#picker`}
|
||||||
|
class="absolute right-3 top-3 rounded-md border border-border px-2 py-1 text-[11px] text-muted-foreground transition-colors hover:border-primary/50 hover:text-primary"
|
||||||
|
>
|
||||||
|
+ 加入
|
||||||
|
</a>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{picker.items.length === 0 && (
|
||||||
|
<p class="mt-4 rounded-lg border border-dashed border-border p-8 text-center text-sm text-muted-foreground">
|
||||||
|
没有匹配的设备,换个关键词或品牌试试。
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Pagination page={picker.page} pages={picker.pages} buildHref={pickerHref} />
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div>
|
||||||
|
<header class="mt-3 flex flex-wrap items-start justify-between gap-3">
|
||||||
|
<div>
|
||||||
|
<h1 class="text-2xl font-semibold tracking-tight">设备对比</h1>
|
||||||
|
<p class="tabular mt-1 text-xs text-muted-foreground">
|
||||||
|
{devices.length} 款 · {comparison?.diffCount ?? 0} 项差异
|
||||||
|
{onlyDiff && ` · 当前仅显示差异(${visibleRowCount} 项)`}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div class="print-hidden flex flex-wrap items-center gap-2">
|
||||||
|
<a
|
||||||
|
href={compareUrl(ids, { diff: !onlyDiff })}
|
||||||
|
class:list={[
|
||||||
|
'rounded-md border px-3 py-1.5 text-xs transition-colors',
|
||||||
|
onlyDiff
|
||||||
|
? 'border-primary/50 bg-primary/10 text-primary'
|
||||||
|
: 'border-border text-muted-foreground hover:text-foreground',
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
{onlyDiff ? '显示全部' : '只看差异'}
|
||||||
|
</a>
|
||||||
|
<a
|
||||||
|
href={editHref}
|
||||||
|
class="rounded-md border border-border px-3 py-1.5 text-xs text-muted-foreground transition-colors hover:text-foreground"
|
||||||
|
>
|
||||||
|
更改选择
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<div
|
||||||
|
class={`reveal-grid tabular mt-5 grid gap-3 ${devices.length === 2 ? 'sm:grid-cols-2' : devices.length === 3 ? 'sm:grid-cols-3' : 'sm:grid-cols-2 lg:grid-cols-4'}`}
|
||||||
|
>
|
||||||
|
{devices.map((device) => (
|
||||||
|
<a
|
||||||
|
href={`/devices/${device.slug}`}
|
||||||
|
class="group flex items-start gap-3 rounded-lg border border-border bg-card p-4 transition-colors hover:border-primary/40"
|
||||||
|
>
|
||||||
|
{device.cover ? (
|
||||||
|
<img
|
||||||
|
src={`/uploads/${device.cover}`}
|
||||||
|
alt={device.model}
|
||||||
|
class="h-14 w-14 shrink-0 rounded-md border border-border object-cover"
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<div class="flex h-14 w-14 shrink-0 items-center justify-center rounded-md border border-dashed border-border text-xs text-muted-foreground">
|
||||||
|
{device.brand.slice(0, 2)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div class="min-w-0">
|
||||||
|
<div class="truncate text-sm font-semibold group-hover:text-primary">
|
||||||
|
{deviceTitle(device.brand, device.model)}
|
||||||
|
</div>
|
||||||
|
<div class="mt-1 flex flex-wrap items-center gap-1.5 text-[11px] text-muted-foreground">
|
||||||
|
<span>{lifecycleText(device.lifecycle)}</span>
|
||||||
|
{device.specs.platform?.chipset && <span>· {device.specs.platform.chipset}</span>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</a>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{visibleGroups.length === 0 ? (
|
||||||
|
<p class="mt-6 rounded-lg border border-dashed border-border p-8 text-center text-sm text-muted-foreground">
|
||||||
|
当前对比下没有差异项。
|
||||||
|
</p>
|
||||||
|
) : (
|
||||||
|
visibleGroups.map((group) => (
|
||||||
|
<details open class="mt-4 rounded-lg border border-border bg-card">
|
||||||
|
<summary class="cursor-pointer select-none px-4 py-3 text-sm font-semibold">
|
||||||
|
{group.title}
|
||||||
|
<span class="ml-2 text-xs font-normal text-muted-foreground">{group.rows.length} 项</span>
|
||||||
|
</summary>
|
||||||
|
<div class="overflow-x-auto border-t border-border/60">
|
||||||
|
<table class="w-full min-w-[640px] table-fixed border-collapse text-sm">
|
||||||
|
<thead>
|
||||||
|
<tr class="bg-secondary/40 text-xs text-muted-foreground">
|
||||||
|
<th class="sticky left-0 z-10 w-44 bg-card px-4 py-2 text-left font-normal">
|
||||||
|
字段
|
||||||
|
</th>
|
||||||
|
{devices.map((device) => (
|
||||||
|
<th class="px-4 py-2 text-left font-normal">
|
||||||
|
<a href={`/devices/${device.slug}`} class="hover:text-foreground">
|
||||||
|
{deviceTitle(device.brand, device.model)}
|
||||||
|
</a>
|
||||||
|
</th>
|
||||||
|
))}
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{group.rows.map((row) => (
|
||||||
|
<tr class={`border-t border-border/60 ${row.different ? 'bg-primary/[0.03]' : ''}`}>
|
||||||
|
<th class="sticky left-0 z-10 bg-card px-4 py-2 text-left align-top text-xs font-normal text-muted-foreground">
|
||||||
|
<span class="flex items-center gap-1.5">
|
||||||
|
{row.different && <span class="h-1.5 w-1.5 shrink-0 rounded-full bg-primary" />}
|
||||||
|
{row.label}
|
||||||
|
</span>
|
||||||
|
</th>
|
||||||
|
{row.formatted.map((value, index) => {
|
||||||
|
const numeric = row.numeric?.[index] ?? null;
|
||||||
|
const width =
|
||||||
|
row.numericMax > 0 && numeric !== null
|
||||||
|
? Math.max(6, Math.round((numeric / row.numericMax) * 100))
|
||||||
|
: 0;
|
||||||
|
return (
|
||||||
|
<td class="px-4 py-2 align-top">
|
||||||
|
{row.different && width > 0 ? (
|
||||||
|
<div class="relative">
|
||||||
|
<div
|
||||||
|
class="absolute inset-y-0 left-0 rounded bg-primary/15"
|
||||||
|
style={`width: ${width}%`}
|
||||||
|
/>
|
||||||
|
<span class="tabular relative z-10">{value}</span>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<span
|
||||||
|
class:list={[
|
||||||
|
'tabular',
|
||||||
|
value === '—' ? 'text-muted-foreground' : 'text-foreground',
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
{value}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
</BaseLayout>
|
||||||
+1355
-179
File diff suppressed because it is too large.
Load diff
@@ -1,17 +1,30 @@
|
|||||||
---
|
---
|
||||||
|
import DeviceCard from '@/components/DeviceCard.astro';
|
||||||
|
import Pagination from '@/components/Pagination.astro';
|
||||||
import BaseLayout from '@/layouts/BaseLayout.astro';
|
import BaseLayout from '@/layouts/BaseLayout.astro';
|
||||||
import { listBrands, listDevices, type DeviceSort } from '@/lib/repo';
|
import { listBrands, listDevicesPaged, type DeviceSort } from '@/lib/repo';
|
||||||
|
import { brandLabel } from '@/lib/utils';
|
||||||
|
|
||||||
|
const PAGE_SIZE = 24;
|
||||||
|
|
||||||
const params = Astro.url.searchParams;
|
const params = Astro.url.searchParams;
|
||||||
const q = (params.get('q') ?? '').trim();
|
const q = (params.get('q') ?? '').trim();
|
||||||
const brand = params.get('brand') ?? undefined;
|
const brand = params.get('brand') ?? undefined;
|
||||||
const sortParam = params.get('sort') ?? 'latest';
|
const sortParam = params.get('sort') ?? 'latest';
|
||||||
const sort: DeviceSort = sortParam === 'name' || sortParam === 'brand' ? sortParam : 'latest';
|
const sort: DeviceSort = sortParam === 'name' || sortParam === 'brand' ? sortParam : 'latest';
|
||||||
|
const pageParam = Number.parseInt(params.get('page') ?? '1', 10);
|
||||||
|
|
||||||
const devices = listDevices({ category: 'phone', q: q || undefined, brand, sort });
|
const result = listDevicesPaged({
|
||||||
|
category: 'phone',
|
||||||
|
q: q || undefined,
|
||||||
|
brand,
|
||||||
|
sort,
|
||||||
|
page: Number.isFinite(pageParam) ? pageParam : 1,
|
||||||
|
pageSize: PAGE_SIZE,
|
||||||
|
});
|
||||||
const brands = listBrands('phone');
|
const brands = listBrands('phone');
|
||||||
|
|
||||||
/** 保留其他筛选条件,只覆盖指定项 */
|
/** 保留其他筛选条件,只覆盖指定项;换品牌 / 排序 / 搜索时会重置到第一页 */
|
||||||
function urlWith(overrides: Record<string, string | undefined>): string {
|
function urlWith(overrides: Record<string, string | undefined>): string {
|
||||||
const next = new URLSearchParams();
|
const next = new URLSearchParams();
|
||||||
const merged: Record<string, string | undefined> = {
|
const merged: Record<string, string | undefined> = {
|
||||||
@@ -27,6 +40,9 @@ function urlWith(overrides: Record<string, string | undefined>): string {
|
|||||||
return query ? `/devices?${query}` : '/devices';
|
return query ? `/devices?${query}` : '/devices';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const pageHref = (target: number) =>
|
||||||
|
`${urlWith({ page: target === 1 ? undefined : String(target) })}#list`;
|
||||||
|
|
||||||
const sortOptions: { key: DeviceSort; label: string }[] = [
|
const sortOptions: { key: DeviceSort; label: string }[] = [
|
||||||
{ key: 'latest', label: '最新发布' },
|
{ key: 'latest', label: '最新发布' },
|
||||||
{ key: 'name', label: '按型号' },
|
{ key: 'name', label: '按型号' },
|
||||||
@@ -37,7 +53,7 @@ const sortOptions: { key: DeviceSort; label: string }[] = [
|
|||||||
<BaseLayout title="手机规格库 · LFSpecs">
|
<BaseLayout title="手机规格库 · LFSpecs">
|
||||||
<header class="flex flex-wrap items-baseline justify-between gap-3">
|
<header class="flex flex-wrap items-baseline justify-between gap-3">
|
||||||
<h1 class="text-2xl font-semibold tracking-tight">手机</h1>
|
<h1 class="text-2xl font-semibold tracking-tight">手机</h1>
|
||||||
<span class="tabular text-sm text-muted-foreground">{devices.length} 款</span>
|
<span class="tabular text-sm text-muted-foreground">{result.total} 款</span>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<form action="/devices" method="get" class="mt-5 flex flex-wrap gap-2">
|
<form action="/devices" method="get" class="mt-5 flex flex-wrap gap-2">
|
||||||
@@ -87,10 +103,13 @@ const sortOptions: { key: DeviceSort; label: string }[] = [
|
|||||||
: 'border-border text-muted-foreground hover:text-foreground',
|
: 'border-border text-muted-foreground hover:text-foreground',
|
||||||
]}
|
]}
|
||||||
>
|
>
|
||||||
{item.brand} <span class="tabular opacity-60">{item.count}</span>
|
{brandLabel(item.brand)} <span class="tabular opacity-60">{item.count}</span>
|
||||||
</a>
|
</a>
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
<a href="/brands" class="ml-auto text-xs text-muted-foreground transition-colors hover:text-foreground">
|
||||||
|
品牌集合 →
|
||||||
|
</a>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="mt-4 flex flex-wrap items-center gap-1 text-xs text-muted-foreground">
|
<div class="mt-4 flex flex-wrap items-center gap-1 text-xs text-muted-foreground">
|
||||||
@@ -108,55 +127,28 @@ const sortOptions: { key: DeviceSort; label: string }[] = [
|
|||||||
</a>
|
</a>
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
</div>
|
{result.pages > 1 && (
|
||||||
|
<span class="tabular ml-auto text-muted-foreground">
|
||||||
<div class="mt-6 grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
第 {result.page} / {result.pages} 页
|
||||||
{
|
|
||||||
devices.map((device) => (
|
|
||||||
<a
|
|
||||||
href={`/devices/${device.slug}`}
|
|
||||||
class="group rounded-lg border border-border bg-card p-5 transition-colors hover:border-primary/40"
|
|
||||||
>
|
|
||||||
<div class="flex items-start justify-between gap-2">
|
|
||||||
<div>
|
|
||||||
<div class="text-xs text-muted-foreground">
|
|
||||||
<a href={`/brands/${encodeURIComponent(device.brand)}`} class="hover:text-foreground">
|
|
||||||
{device.brand}
|
|
||||||
</a>
|
|
||||||
</div>
|
|
||||||
<div class="mt-0.5 text-base font-semibold">{device.model}</div>
|
|
||||||
</div>
|
|
||||||
<span class="rounded-full border border-border px-2 py-0.5 text-[11px] text-muted-foreground">
|
|
||||||
{device.lifecycle === 'discontinued'
|
|
||||||
? '已停产'
|
|
||||||
: device.lifecycle === 'announced'
|
|
||||||
? '已发布'
|
|
||||||
: '在售'}
|
|
||||||
</span>
|
</span>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<dl class="tabular mt-4 grid grid-cols-2 gap-x-4 gap-y-1 text-xs">
|
<div id="list" class="reveal-grid mt-6 grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||||
<dt class="text-muted-foreground">SoC</dt>
|
{
|
||||||
<dd class="truncate text-right">{device.specs.platform?.chipset ?? '—'}</dd>
|
result.items.map((device) => (
|
||||||
<dt class="text-muted-foreground">屏幕</dt>
|
<DeviceCard device={device} />
|
||||||
<dd class="truncate text-right">{device.specs.display?.size ?? '—'}</dd>
|
|
||||||
<dt class="text-muted-foreground">电池</dt>
|
|
||||||
<dd class="truncate text-right">{device.specs.battery?.capacity ?? '—'}</dd>
|
|
||||||
<dt class="text-muted-foreground">重量</dt>
|
|
||||||
<dd class="truncate text-right">{device.specs.body?.weight ?? '—'}</dd>
|
|
||||||
</dl>
|
|
||||||
|
|
||||||
{device.summary && <p class="mt-4 line-clamp-2 text-xs text-muted-foreground">{device.summary}</p>}
|
|
||||||
</a>
|
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{
|
{
|
||||||
devices.length === 0 && (
|
result.total === 0 && (
|
||||||
<p class="mt-6 rounded-lg border border-dashed border-border p-8 text-center text-sm text-muted-foreground">
|
<p class="mt-6 rounded-lg border border-dashed border-border p-8 text-center text-sm text-muted-foreground">
|
||||||
没有匹配的设备。试试清除关键词或换一个品牌。
|
没有匹配的设备。试试清除关键词或换一个品牌。
|
||||||
</p>
|
</p>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
<Pagination page={result.page} pages={result.pages} buildHref={pageHref} />
|
||||||
</BaseLayout>
|
</BaseLayout>
|
||||||
+33
-22
@@ -1,10 +1,13 @@
|
|||||||
---
|
---
|
||||||
|
import DeviceCard from '@/components/DeviceCard.astro';
|
||||||
import BaseLayout from '@/layouts/BaseLayout.astro';
|
import BaseLayout from '@/layouts/BaseLayout.astro';
|
||||||
import { countChips, countDevices, listDevices } from '@/lib/repo';
|
import { countChips, countDevices, listBrands, listDevicesPaged } from '@/lib/repo';
|
||||||
|
import { brandLabel } from '@/lib/utils';
|
||||||
|
|
||||||
const phoneCount = countDevices('phone');
|
const phoneCount = countDevices('phone');
|
||||||
const socCount = countChips('soc');
|
const socCount = countChips('soc');
|
||||||
const latest = listDevices({ category: 'phone' }).slice(0, 6);
|
const brands = listBrands('phone');
|
||||||
|
const latest = listDevicesPaged({ category: 'phone', sort: 'latest', page: 1, pageSize: 6 }).items;
|
||||||
---
|
---
|
||||||
|
|
||||||
<BaseLayout>
|
<BaseLayout>
|
||||||
@@ -15,42 +18,50 @@ const latest = listDevices({ category: 'phone' }).slice(0, 6);
|
|||||||
</p>
|
</p>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section class="mt-8 grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
|
<section class="mt-8 grid gap-3 sm:grid-cols-3">
|
||||||
<a href="/devices" class="rounded-lg border border-border bg-card p-5 transition-colors hover:border-primary/40">
|
<a href="/devices" class="rounded-lg border border-border bg-card p-5 transition-colors hover:border-primary/40">
|
||||||
<div class="text-xs text-muted-foreground">手机收录</div>
|
<div class="text-xs text-muted-foreground">手机收录</div>
|
||||||
<div class="tabular mt-1 text-2xl font-semibold">{phoneCount}</div>
|
<div class="tabular mt-1 text-2xl font-semibold">{phoneCount}</div>
|
||||||
</a>
|
</a>
|
||||||
|
<a href="/brands" class="rounded-lg border border-border bg-card p-5 transition-colors hover:border-primary/40">
|
||||||
|
<div class="text-xs text-muted-foreground">收录品牌</div>
|
||||||
|
<div class="tabular mt-1 text-2xl font-semibold">{brands.length}</div>
|
||||||
|
</a>
|
||||||
<a href="/chips" class="rounded-lg border border-border bg-card p-5 transition-colors hover:border-primary/40">
|
<a href="/chips" class="rounded-lg border border-border bg-card p-5 transition-colors hover:border-primary/40">
|
||||||
<div class="text-xs text-muted-foreground">SoC 收录</div>
|
<div class="text-xs text-muted-foreground">SoC 收录</div>
|
||||||
<div class="tabular mt-1 text-2xl font-semibold">{socCount}</div>
|
<div class="tabular mt-1 text-2xl font-semibold">{socCount}</div>
|
||||||
</a>
|
</a>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<section class="mt-12">
|
||||||
|
<div class="flex items-baseline justify-between">
|
||||||
|
<h2 class="text-lg font-semibold">品牌</h2>
|
||||||
|
<a href="/brands" class="text-sm text-muted-foreground hover:text-foreground">全部品牌 →</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="reveal-grid mt-4 grid gap-2 sm:grid-cols-2 lg:grid-cols-4">
|
||||||
|
{
|
||||||
|
brands.map((item) => (
|
||||||
|
<a
|
||||||
|
href={`/brands/${encodeURIComponent(item.brand)}`}
|
||||||
|
class="flex items-center justify-between rounded-lg border border-border bg-card px-4 py-3 transition-colors hover:border-primary/40 hover:bg-accent/20"
|
||||||
|
>
|
||||||
|
<span class="min-w-0 truncate text-sm font-medium">{brandLabel(item.brand)}</span>
|
||||||
|
<span class="tabular ml-2 shrink-0 text-xs text-muted-foreground">{item.count} 款</span>
|
||||||
|
</a>
|
||||||
|
))
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
<section class="mt-12">
|
<section class="mt-12">
|
||||||
<div class="flex items-baseline justify-between">
|
<div class="flex items-baseline justify-between">
|
||||||
<h2 class="text-lg font-semibold">最新收录</h2>
|
<h2 class="text-lg font-semibold">最新收录</h2>
|
||||||
<a href="/devices" class="text-sm text-muted-foreground hover:text-foreground">全部手机 →</a>
|
<a href="/devices" class="text-sm text-muted-foreground hover:text-foreground">全部手机 →</a>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="mt-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
<div class="reveal-grid mt-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||||
{
|
{latest.map((device) => <DeviceCard device={device} compact />)}
|
||||||
latest.map((device) => (
|
|
||||||
<a
|
|
||||||
href={`/devices/${device.slug}`}
|
|
||||||
class="group rounded-lg border border-border bg-card p-5 transition-colors hover:border-primary/40"
|
|
||||||
>
|
|
||||||
<div class="text-xs text-muted-foreground">{device.brand}</div>
|
|
||||||
<div class="mt-0.5 text-base font-semibold">{device.model}</div>
|
|
||||||
<div class="tabular mt-3 text-xs text-muted-foreground">
|
|
||||||
{device.specs.platform?.chipset ?? '未填写 SoC'}
|
|
||||||
{' · '}
|
|
||||||
{device.specs.display?.size ?? '—'}
|
|
||||||
{' · '}
|
|
||||||
{device.specs.battery?.capacity ?? '—'}
|
|
||||||
</div>
|
|
||||||
</a>
|
|
||||||
))
|
|
||||||
}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import type { APIRoute } from 'astro';
|
||||||
|
import { renderOgPng } from '@/lib/og';
|
||||||
|
import { countChips, countDevices, getDevice } from '@/lib/repo';
|
||||||
|
|
||||||
|
const CACHE_TTL = 5 * 60 * 1000;
|
||||||
|
const cache = new Map<string, { buffer: Buffer; expires: number }>();
|
||||||
|
|
||||||
|
function pngResponse(buffer: Buffer): Response {
|
||||||
|
return new Response(new Uint8Array(buffer), {
|
||||||
|
headers: {
|
||||||
|
'content-type': 'image/png',
|
||||||
|
'cache-control': 'public, max-age=300',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export const GET: APIRoute = async ({ params }) => {
|
||||||
|
const slug = params.slug ?? 'site';
|
||||||
|
const now = Date.now();
|
||||||
|
const cached = cache.get(slug);
|
||||||
|
if (cached && cached.expires > now) return pngResponse(cached.buffer);
|
||||||
|
|
||||||
|
let device = null;
|
||||||
|
if (slug !== 'site') {
|
||||||
|
const found = getDevice(slug);
|
||||||
|
if (!found) return new Response('未找到该设备', { status: 404 });
|
||||||
|
device = found;
|
||||||
|
}
|
||||||
|
|
||||||
|
const buffer = await renderOgPng(device, {
|
||||||
|
phones: countDevices('phone'),
|
||||||
|
chips: countChips('soc'),
|
||||||
|
});
|
||||||
|
cache.set(slug, { buffer, expires: now + CACHE_TTL });
|
||||||
|
return pngResponse(buffer);
|
||||||
|
};
|
||||||
@@ -0,0 +1,284 @@
|
|||||||
|
---
|
||||||
|
import BaseLayout from '@/layouts/BaseLayout.astro';
|
||||||
|
import { listDevices } from '@/lib/repo';
|
||||||
|
import {
|
||||||
|
listMotorRanking,
|
||||||
|
listSocRanking,
|
||||||
|
listSpeakerRanking,
|
||||||
|
type SocMetric,
|
||||||
|
} from '@/lib/rankings';
|
||||||
|
import { chipTitle, deviceTitle } from '@/lib/utils';
|
||||||
|
|
||||||
|
const params = Astro.url.searchParams;
|
||||||
|
const typeParam = params.get('type') ?? 'soc';
|
||||||
|
const type = (['soc', 'motor', 'speaker'].includes(typeParam) ? typeParam : 'soc') as
|
||||||
|
| 'soc'
|
||||||
|
| 'motor'
|
||||||
|
| 'speaker';
|
||||||
|
const metricParam = params.get('metric') ?? 'single';
|
||||||
|
const metric = (['single', 'multi', 'antutu'].includes(metricParam) ? metricParam : 'single') as SocMetric;
|
||||||
|
|
||||||
|
const socRows = type === 'soc' ? listSocRanking(metric) : [];
|
||||||
|
const devices = type === 'soc' ? [] : listDevices();
|
||||||
|
const motorRows = type === 'motor' ? listMotorRanking(devices) : [];
|
||||||
|
const speakerRows = type === 'speaker' ? listSpeakerRanking(devices) : [];
|
||||||
|
|
||||||
|
const tabs = [
|
||||||
|
{ key: 'soc', label: 'SoC 性能' },
|
||||||
|
{ key: 'motor', label: '振动马达' },
|
||||||
|
{ key: 'speaker', label: '扬声器单元' },
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
const socMetrics: { key: SocMetric; label: string }[] = [
|
||||||
|
{ key: 'single', label: '单核' },
|
||||||
|
{ key: 'multi', label: '多核' },
|
||||||
|
{ key: 'antutu', label: '安兔兔' },
|
||||||
|
];
|
||||||
|
|
||||||
|
const tabHref = (key: string) => (key === 'soc' ? '/rankings' : `/rankings?type=${key}`);
|
||||||
|
const metricHref = (key: SocMetric) =>
|
||||||
|
key === 'single' ? '/rankings' : `/rankings?type=soc&metric=${key}`;
|
||||||
|
|
||||||
|
const number = (value?: number) =>
|
||||||
|
value === undefined ? '—' : value.toLocaleString('zh-CN');
|
||||||
|
|
||||||
|
const rankClass = (index: number) =>
|
||||||
|
index === 0
|
||||||
|
? 'bg-primary/15 text-primary'
|
||||||
|
: index === 1
|
||||||
|
? 'bg-secondary text-foreground'
|
||||||
|
: index === 2
|
||||||
|
? 'bg-accent text-foreground'
|
||||||
|
: 'text-muted-foreground';
|
||||||
|
|
||||||
|
const labelForType = type === 'soc' ? 'SoC' : type === 'motor' ? '马达' : '扬声器';
|
||||||
|
---
|
||||||
|
|
||||||
|
<BaseLayout title="排行榜 · LFSpecs" description="已收录 SoC、振动马达与扬声器单元的规格排行,只对比公开跑分与硬件尺寸。">
|
||||||
|
<header class="flex flex-wrap items-baseline justify-between gap-3">
|
||||||
|
<h1 class="text-2xl font-semibold tracking-tight">排行榜</h1>
|
||||||
|
<span class="text-sm text-muted-foreground">当前:{labelForType}</span>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<nav class="mt-5 flex flex-wrap gap-2">
|
||||||
|
{
|
||||||
|
tabs.map((tab) => (
|
||||||
|
<a
|
||||||
|
href={tabHref(tab.key)}
|
||||||
|
class:list={[
|
||||||
|
'rounded-full border px-3 py-1 text-xs transition-colors',
|
||||||
|
type === tab.key
|
||||||
|
? 'border-primary/50 bg-primary/10 text-primary'
|
||||||
|
: 'border-border text-muted-foreground hover:text-foreground',
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
{tab.label}
|
||||||
|
</a>
|
||||||
|
))
|
||||||
|
}
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
{
|
||||||
|
type === 'soc' && (
|
||||||
|
<>
|
||||||
|
<div class="mt-4 flex flex-wrap items-center gap-1 text-xs text-muted-foreground">
|
||||||
|
<span class="mr-1">排序</span>
|
||||||
|
{socMetrics.map((item) => (
|
||||||
|
<a
|
||||||
|
href={metricHref(item.key)}
|
||||||
|
class:list={[
|
||||||
|
'rounded-md px-2 py-1 transition-colors',
|
||||||
|
metric === item.key ? 'bg-accent text-foreground' : 'hover:text-foreground',
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
{item.label}
|
||||||
|
</a>
|
||||||
|
))}
|
||||||
|
<span class="ml-auto tabular">{socRows.length} 颗</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="mt-5 overflow-x-auto rounded-lg border border-border">
|
||||||
|
<table class="w-full min-w-[640px] border-collapse text-sm">
|
||||||
|
<thead>
|
||||||
|
<tr class="border-b border-border text-xs text-muted-foreground">
|
||||||
|
<th class="w-12 px-4 py-3 text-left font-medium">#</th>
|
||||||
|
<th class="px-4 py-3 text-left font-medium">芯片</th>
|
||||||
|
<th class="px-4 py-3 text-right font-medium">单核</th>
|
||||||
|
<th class="px-4 py-3 text-right font-medium">多核</th>
|
||||||
|
<th class="px-4 py-3 text-right font-medium">安兔兔</th>
|
||||||
|
<th class="px-4 py-3 text-right font-medium">年份</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{socRows.map((row, index) => (
|
||||||
|
<tr class="border-b border-border/60 last:border-0 hover:bg-accent/20">
|
||||||
|
<td class="px-4 py-2.5">
|
||||||
|
<span class:list={['inline-flex h-6 min-w-6 items-center justify-center rounded px-1.5 text-xs tabular', rankClass(index)]}>
|
||||||
|
{index + 1}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td class="px-4 py-2.5">
|
||||||
|
<a href={`/chips/${row.slug}`} class="font-medium hover:text-primary">
|
||||||
|
{chipTitle(row.brand, row.model)}
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td class="px-4 py-2.5 text-right tabular">{number(row.single)}</td>
|
||||||
|
<td class="px-4 py-2.5 text-right tabular">{number(row.multi)}</td>
|
||||||
|
<td class="px-4 py-2.5 text-right tabular">{number(row.antutu)}</td>
|
||||||
|
<td class="px-4 py-2.5 text-right tabular text-muted-foreground">
|
||||||
|
{row.year ?? '—'}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p class="mt-4 rounded-lg border border-dashed border-border p-4 text-xs leading-relaxed text-muted-foreground">
|
||||||
|
本排行只看跑分,实际表现需结合能效。参考:<a
|
||||||
|
href="https://socpk.com/category/mobile-soc"
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
class="text-primary hover:underline"
|
||||||
|
>极客湾 SoC 排行榜</a>。
|
||||||
|
跑分取 Geekbench 6(缺失时回退 Geekbench 7 / 通用条目)与安兔兔 v11。
|
||||||
|
</p>
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
type === 'motor' && (
|
||||||
|
<>
|
||||||
|
<div class="mt-4 flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
|
||||||
|
<span>{motorRows.length} 款型号 · 按体积排序</span>
|
||||||
|
<span class="ml-auto tabular">{devices.length} 台机型参与统计</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="mt-5 overflow-x-auto rounded-lg border border-border">
|
||||||
|
<table class="w-full min-w-[860px] border-collapse text-sm">
|
||||||
|
<thead>
|
||||||
|
<tr class="border-b border-border text-xs text-muted-foreground">
|
||||||
|
<th class="w-12 px-4 py-3 text-left font-medium">#</th>
|
||||||
|
<th class="px-4 py-3 text-left font-medium">型号</th>
|
||||||
|
<th class="px-4 py-3 text-left font-medium">尺寸</th>
|
||||||
|
<th class="px-4 py-3 text-right font-medium">体积</th>
|
||||||
|
<th class="px-4 py-3 text-right font-medium">稳态振动量</th>
|
||||||
|
<th class="px-4 py-3 text-right font-medium">机型数</th>
|
||||||
|
<th class="px-4 py-3 text-left font-medium">代表机型</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{motorRows.map((row, index) => (
|
||||||
|
<tr class="border-b border-border/60 last:border-0 hover:bg-accent/20">
|
||||||
|
<td class="px-4 py-2.5">
|
||||||
|
<span class:list={['inline-flex h-6 min-w-6 items-center justify-center rounded px-1.5 text-xs tabular', rankClass(index)]}>
|
||||||
|
{index + 1}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td class="px-4 py-2.5">
|
||||||
|
<div class="font-medium">{row.code}</div>
|
||||||
|
{row.variants.length > 0 && (
|
||||||
|
<div class="mt-0.5 text-[11px] text-muted-foreground">
|
||||||
|
{row.variants.slice(0, 3).join(' / ')}
|
||||||
|
{row.variants.length > 3 ? ` 等 ${row.variants.length} 种写法` : ''}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
<td class="px-4 py-2.5 tabular text-muted-foreground">{row.size ?? '—'}</td>
|
||||||
|
<td class="px-4 py-2.5 text-right tabular">
|
||||||
|
{row.volume ?? '—'}
|
||||||
|
{row.estimated && (
|
||||||
|
<span class="ml-1 rounded border border-border bg-secondary/60 px-1 text-[10px] text-muted-foreground">
|
||||||
|
估算
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
<td class="px-4 py-2.5 text-right tabular text-muted-foreground">{row.grms ?? '—'}</td>
|
||||||
|
<td class="px-4 py-2.5 text-right tabular">{row.count}</td>
|
||||||
|
<td class="px-4 py-2.5 text-xs text-muted-foreground">
|
||||||
|
{row.devices.slice(0, 2).map((device) => (
|
||||||
|
<a href={`/devices/${device.slug}`} class="mr-2 hover:text-foreground">
|
||||||
|
{deviceTitle(device.brand, device.model)}
|
||||||
|
</a>
|
||||||
|
))}
|
||||||
|
{row.count > 2 && <span>等 {row.count} 款</span>}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p class="mt-4 rounded-lg border border-dashed border-border p-4 text-xs leading-relaxed text-muted-foreground">
|
||||||
|
尺寸、谐振频率与振动量来自厂商公开规格(瑞声 RichTap)与《主流手机马达型号参数表》。7514、8282、9593 厂商未公开体积,按型号尺寸 × 常见厚度估算(标注「估算」),仍按预估值参与排序。
|
||||||
|
</p>
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
type === 'speaker' && (
|
||||||
|
<>
|
||||||
|
<div class="mt-4 flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
|
||||||
|
<span>{speakerRows.length} 款型号 · 按振膜面积排序</span>
|
||||||
|
<span class="ml-auto tabular">{devices.length} 台机型参与统计</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="mt-5 overflow-x-auto rounded-lg border border-border">
|
||||||
|
<table class="w-full min-w-[720px] border-collapse text-sm">
|
||||||
|
<thead>
|
||||||
|
<tr class="border-b border-border text-xs text-muted-foreground">
|
||||||
|
<th class="w-12 px-4 py-3 text-left font-medium">#</th>
|
||||||
|
<th class="px-4 py-3 text-left font-medium">型号</th>
|
||||||
|
<th class="px-4 py-3 text-left font-medium">尺寸</th>
|
||||||
|
<th class="px-4 py-3 text-right font-medium">面积</th>
|
||||||
|
<th class="px-4 py-3 text-right font-medium">机型 / 单元</th>
|
||||||
|
<th class="px-4 py-3 text-left font-medium">代表机型</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{speakerRows.map((row, index) => (
|
||||||
|
<tr class="border-b border-border/60 last:border-0 hover:bg-accent/20">
|
||||||
|
<td class="px-4 py-2.5">
|
||||||
|
<span class:list={['inline-flex h-6 min-w-6 items-center justify-center rounded px-1.5 text-xs tabular', rankClass(index)]}>
|
||||||
|
{index + 1}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td class="px-4 py-2.5">
|
||||||
|
<div class="font-medium">{row.code}</div>
|
||||||
|
{row.variants.length > 0 && (
|
||||||
|
<div class="mt-0.5 text-[11px] text-muted-foreground">
|
||||||
|
{row.variants.slice(0, 3).join(' / ')}
|
||||||
|
{row.variants.length > 3 ? ` 等 ${row.variants.length} 种写法` : ''}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
<td class="px-4 py-2.5 tabular text-muted-foreground">{row.size ?? '—'}</td>
|
||||||
|
<td class="px-4 py-2.5 text-right tabular">
|
||||||
|
{row.metric ? `${row.metric} mm²` : '—'}
|
||||||
|
</td>
|
||||||
|
<td class="px-4 py-2.5 text-right tabular">
|
||||||
|
{row.count} / {row.units ?? 0}
|
||||||
|
</td>
|
||||||
|
<td class="px-4 py-2.5 text-xs text-muted-foreground">
|
||||||
|
{row.devices.slice(0, 2).map((device) => (
|
||||||
|
<a href={`/devices/${device.slug}`} class="mr-2 hover:text-foreground">
|
||||||
|
{deviceTitle(device.brand, device.model)}
|
||||||
|
</a>
|
||||||
|
))}
|
||||||
|
{row.count > 2 && <span>等 {row.count} 款</span>}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p class="mt-4 rounded-lg border border-dashed border-border p-4 text-xs leading-relaxed text-muted-foreground">
|
||||||
|
手机扬声器型号通常以「长 × 宽」命名(如 1115 = 15 × 11 mm、1216 = 12 × 16 mm),面积按型号尺寸计算,仅供横向参考;厚度与功率厂商未统一公开。
|
||||||
|
</p>
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
</BaseLayout>
|
||||||
@@ -4,7 +4,7 @@ import { listBrands, listChips, listDevices } from '@/lib/repo';
|
|||||||
const SITE = 'https://specs.atie.fun';
|
const SITE = 'https://specs.atie.fun';
|
||||||
|
|
||||||
export const GET: APIRoute = () => {
|
export const GET: APIRoute = () => {
|
||||||
const paths: string[] = ['', '/devices', '/chips', '/brands'];
|
const paths: string[] = ['', '/devices', '/chips', '/rankings', '/brands'];
|
||||||
for (const device of listDevices()) paths.push(`/devices/${device.slug}`);
|
for (const device of listDevices()) paths.push(`/devices/${device.slug}`);
|
||||||
for (const chip of listChips()) paths.push(`/chips/${chip.slug}`);
|
for (const chip of listChips()) paths.push(`/chips/${chip.slug}`);
|
||||||
for (const item of listBrands()) paths.push(`/brands/${encodeURIComponent(item.brand)}`);
|
for (const item of listBrands()) paths.push(`/brands/${encodeURIComponent(item.brand)}`);
|
||||||
|
|||||||
@@ -23,6 +23,28 @@
|
|||||||
--radius: 0.625rem;
|
--radius: 0.625rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* 白色主题:同一套语义变量,组件不需要写两套样式 */
|
||||||
|
html[data-theme="light"] {
|
||||||
|
--background: #f7f9f8;
|
||||||
|
--foreground: #111827;
|
||||||
|
--card: #ffffff;
|
||||||
|
--card-foreground: #111827;
|
||||||
|
--popover: #ffffff;
|
||||||
|
--popover-foreground: #111827;
|
||||||
|
--primary: #0f766e;
|
||||||
|
--primary-foreground: #ffffff;
|
||||||
|
--secondary: #f0f4f3;
|
||||||
|
--secondary-foreground: #111827;
|
||||||
|
--muted: #eef2f1;
|
||||||
|
--muted-foreground: #5b6770;
|
||||||
|
--accent: #e8f0ee;
|
||||||
|
--accent-foreground: #111827;
|
||||||
|
--destructive: #dc2626;
|
||||||
|
--border: #dfe7e4;
|
||||||
|
--input: #d6e0dd;
|
||||||
|
--ring: #0f766e;
|
||||||
|
}
|
||||||
|
|
||||||
@theme inline {
|
@theme inline {
|
||||||
--color-background: var(--background);
|
--color-background: var(--background);
|
||||||
--color-foreground: var(--foreground);
|
--color-foreground: var(--foreground);
|
||||||
@@ -59,6 +81,11 @@
|
|||||||
|
|
||||||
html {
|
html {
|
||||||
color-scheme: dark;
|
color-scheme: dark;
|
||||||
|
scroll-behavior: smooth;
|
||||||
|
}
|
||||||
|
|
||||||
|
html[data-theme="light"] {
|
||||||
|
color-scheme: light;
|
||||||
}
|
}
|
||||||
|
|
||||||
body {
|
body {
|
||||||
@@ -72,4 +99,461 @@
|
|||||||
.tabular {
|
.tabular {
|
||||||
font-variant-numeric: tabular-nums;
|
font-variant-numeric: tabular-nums;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* 主题切换的轻微过渡 */
|
||||||
|
body,
|
||||||
|
header,
|
||||||
|
footer,
|
||||||
|
.bg-card {
|
||||||
|
transition:
|
||||||
|
background-color 0.2s ease,
|
||||||
|
border-color 0.2s ease,
|
||||||
|
color 0.2s ease;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* low 置信度徽章与悬停说明 */
|
||||||
|
.low-badge {
|
||||||
|
position: relative;
|
||||||
|
display: inline-flex;
|
||||||
|
margin-left: 0.375rem;
|
||||||
|
vertical-align: middle;
|
||||||
|
cursor: help;
|
||||||
|
}
|
||||||
|
|
||||||
|
.low-badge-pill {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
border: 1px solid var(--destructive);
|
||||||
|
border-radius: 999px;
|
||||||
|
padding: 1px 5px;
|
||||||
|
color: var(--destructive);
|
||||||
|
font-size: 9px;
|
||||||
|
font-weight: 500;
|
||||||
|
line-height: 1.2;
|
||||||
|
letter-spacing: 0.02em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.low-badge-panel {
|
||||||
|
display: none;
|
||||||
|
position: absolute;
|
||||||
|
top: calc(100% + 4px);
|
||||||
|
left: 0;
|
||||||
|
z-index: 50;
|
||||||
|
width: 18rem;
|
||||||
|
max-width: 75vw;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
background: var(--card);
|
||||||
|
padding: 0.5rem 0.625rem;
|
||||||
|
color: var(--foreground);
|
||||||
|
font-size: 11px;
|
||||||
|
font-weight: 400;
|
||||||
|
line-height: 1.5;
|
||||||
|
box-shadow: 0 8px 24px rgb(0 0 0 / 0.18);
|
||||||
|
pointer-events: none;
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
|
|
||||||
|
.low-badge-right .low-badge-panel {
|
||||||
|
left: auto;
|
||||||
|
right: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.low-badge:hover .low-badge-panel,
|
||||||
|
.low-badge:focus-within .low-badge-panel {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media print {
|
||||||
|
.low-badge-panel {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 频段 / 卫星等附加信息的悬停面板 */
|
||||||
|
.hover-info {
|
||||||
|
position: relative;
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
cursor: help;
|
||||||
|
}
|
||||||
|
|
||||||
|
.hover-info-trigger {
|
||||||
|
border-bottom: 1px dashed var(--muted-foreground);
|
||||||
|
color: var(--primary);
|
||||||
|
font-size: 12px;
|
||||||
|
line-height: 1.4;
|
||||||
|
}
|
||||||
|
|
||||||
|
.hover-info-panel {
|
||||||
|
display: none;
|
||||||
|
position: absolute;
|
||||||
|
top: calc(100% + 6px);
|
||||||
|
left: 0;
|
||||||
|
z-index: 50;
|
||||||
|
width: 22rem;
|
||||||
|
max-width: 80vw;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
background: var(--card);
|
||||||
|
padding: 0.625rem;
|
||||||
|
color: var(--foreground);
|
||||||
|
font-size: 11px;
|
||||||
|
font-weight: 400;
|
||||||
|
line-height: 1.5;
|
||||||
|
box-shadow: 0 8px 24px rgb(0 0 0 / 0.18);
|
||||||
|
pointer-events: none;
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
|
|
||||||
|
.hover-info:hover .hover-info-panel,
|
||||||
|
.hover-info:focus-within .hover-info-panel {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media print {
|
||||||
|
.hover-info-panel {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------ 对比选择 ------------------------------ */
|
||||||
|
|
||||||
|
.compare-tray {
|
||||||
|
position: fixed;
|
||||||
|
inset-inline: 0;
|
||||||
|
bottom: 0;
|
||||||
|
z-index: 60;
|
||||||
|
border-top: 1px solid var(--border);
|
||||||
|
background: color-mix(in srgb, var(--card) 92%, transparent);
|
||||||
|
box-shadow: 0 -8px 30px rgb(0 0 0 / 0.18);
|
||||||
|
backdrop-filter: blur(10px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.compare-tray > div {
|
||||||
|
max-height: 40vh;
|
||||||
|
overflow-y: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
html.compare-tray-open body {
|
||||||
|
padding-bottom: 4.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.compare-chip {
|
||||||
|
display: inline-flex;
|
||||||
|
max-width: 13rem;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.35rem;
|
||||||
|
overflow: hidden;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 999px;
|
||||||
|
background: var(--background);
|
||||||
|
padding: 2px 8px;
|
||||||
|
color: var(--foreground);
|
||||||
|
font-size: 11px;
|
||||||
|
white-space: nowrap;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.compare-chip:hover {
|
||||||
|
border-color: color-mix(in srgb, var(--primary) 50%, var(--border));
|
||||||
|
}
|
||||||
|
|
||||||
|
.compare-chip span {
|
||||||
|
color: var(--muted-foreground);
|
||||||
|
}
|
||||||
|
|
||||||
|
.compare-toggle[data-active="1"] {
|
||||||
|
border-color: color-mix(in srgb, var(--primary) 55%, var(--border));
|
||||||
|
background: color-mix(in srgb, var(--primary) 12%, transparent);
|
||||||
|
color: var(--primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.compare-go[aria-disabled="true"] {
|
||||||
|
cursor: not-allowed;
|
||||||
|
opacity: 0.45;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media print {
|
||||||
|
.compare-tray {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ----------------------------- 图片放大查看 ----------------------------- */
|
||||||
|
|
||||||
|
.image-lightbox {
|
||||||
|
margin: auto;
|
||||||
|
padding: 0;
|
||||||
|
border: 0;
|
||||||
|
background: transparent;
|
||||||
|
max-width: 92vw;
|
||||||
|
max-height: 90vh;
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-lightbox::backdrop {
|
||||||
|
background: rgb(0 0 0 / 0.78);
|
||||||
|
backdrop-filter: blur(3px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-lightbox img {
|
||||||
|
display: block;
|
||||||
|
width: auto;
|
||||||
|
height: auto;
|
||||||
|
max-width: 92vw;
|
||||||
|
max-height: 86vh;
|
||||||
|
border-radius: 0.75rem;
|
||||||
|
background: #fff;
|
||||||
|
box-shadow: 0 24px 80px rgb(0 0 0 / 0.45);
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-lightbox-close {
|
||||||
|
position: fixed;
|
||||||
|
top: max(1rem, env(safe-area-inset-top));
|
||||||
|
right: max(1rem, env(safe-area-inset-right));
|
||||||
|
z-index: 10;
|
||||||
|
display: inline-flex;
|
||||||
|
height: 2.25rem;
|
||||||
|
width: 2.25rem;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
border: 1px solid rgb(255 255 255 / 0.25);
|
||||||
|
border-radius: 999px;
|
||||||
|
background: rgb(0 0 0 / 0.55);
|
||||||
|
color: #fff;
|
||||||
|
font-size: 1.25rem;
|
||||||
|
line-height: 1;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-lightbox-close:hover {
|
||||||
|
background: rgb(0 0 0 / 0.75);
|
||||||
|
}
|
||||||
|
|
||||||
|
.lightbox-open {
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media print {
|
||||||
|
.image-lightbox {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 图标按当前主题显示:深色时给“太阳”(切换到浅色),浅色时给“月亮” */
|
||||||
|
.theme-icon-sun {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
html[data-theme="dark"] .theme-icon-sun {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
|
html[data-theme="dark"] .theme-icon-moon {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
body,
|
||||||
|
header,
|
||||||
|
footer,
|
||||||
|
.bg-card {
|
||||||
|
transition: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --------------------------- 克制的列表渐入动效 --------------------------- */
|
||||||
|
|
||||||
|
@keyframes reveal-up {
|
||||||
|
from {
|
||||||
|
opacity: 0;
|
||||||
|
transform: translateY(6px);
|
||||||
|
}
|
||||||
|
to {
|
||||||
|
opacity: 1;
|
||||||
|
transform: translateY(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.reveal-grid > * {
|
||||||
|
animation: reveal-up 0.35s cubic-bezier(0.22, 1, 0.36, 1) both;
|
||||||
|
}
|
||||||
|
|
||||||
|
.reveal-grid > *:nth-child(2) { animation-delay: 40ms; }
|
||||||
|
.reveal-grid > *:nth-child(3) { animation-delay: 80ms; }
|
||||||
|
.reveal-grid > *:nth-child(4) { animation-delay: 120ms; }
|
||||||
|
.reveal-grid > *:nth-child(5) { animation-delay: 160ms; }
|
||||||
|
.reveal-grid > *:nth-child(6) { animation-delay: 200ms; }
|
||||||
|
.reveal-grid > *:nth-child(7) { animation-delay: 240ms; }
|
||||||
|
.reveal-grid > *:nth-child(8) { animation-delay: 280ms; }
|
||||||
|
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
html {
|
||||||
|
scroll-behavior: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.reveal-grid > * {
|
||||||
|
animation: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
::view-transition-group(*),
|
||||||
|
::view-transition-old(*),
|
||||||
|
::view-transition-new(*) {
|
||||||
|
animation: none !important;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------- 设备页顶部:配色 / 售价 ------------------------- */
|
||||||
|
.device-hero {
|
||||||
|
position: relative;
|
||||||
|
overflow: hidden;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 1rem;
|
||||||
|
background: var(--card);
|
||||||
|
}
|
||||||
|
|
||||||
|
.device-hero::before {
|
||||||
|
content: "";
|
||||||
|
position: absolute;
|
||||||
|
inset: 0;
|
||||||
|
pointer-events: none;
|
||||||
|
background:
|
||||||
|
radial-gradient(
|
||||||
|
120% 150% at 0% 0%,
|
||||||
|
color-mix(in srgb, var(--device-accent, var(--primary)) 26%, transparent),
|
||||||
|
transparent 58%
|
||||||
|
),
|
||||||
|
radial-gradient(
|
||||||
|
80% 120% at 100% 10%,
|
||||||
|
color-mix(in srgb, var(--device-accent, var(--primary)) 10%, transparent),
|
||||||
|
transparent 70%
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
.device-hero::after {
|
||||||
|
content: "";
|
||||||
|
position: absolute;
|
||||||
|
inset: 0;
|
||||||
|
pointer-events: none;
|
||||||
|
opacity: 0.16;
|
||||||
|
background-image:
|
||||||
|
linear-gradient(color-mix(in srgb, var(--foreground) 12%, transparent) 1px, transparent 1px),
|
||||||
|
linear-gradient(90deg, color-mix(in srgb, var(--foreground) 12%, transparent) 1px, transparent 1px);
|
||||||
|
background-size: 26px 26px;
|
||||||
|
-webkit-mask-image: linear-gradient(120deg, #000 0%, transparent 65%);
|
||||||
|
mask-image: linear-gradient(120deg, #000 0%, transparent 65%);
|
||||||
|
}
|
||||||
|
|
||||||
|
.device-hero > * {
|
||||||
|
position: relative;
|
||||||
|
z-index: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
html[data-theme="light"] .device-hero::before {
|
||||||
|
opacity: 0.6;
|
||||||
|
}
|
||||||
|
|
||||||
|
.device-kicker {
|
||||||
|
font-size: 11px;
|
||||||
|
font-weight: 600;
|
||||||
|
letter-spacing: 0.14em;
|
||||||
|
color: var(--muted-foreground);
|
||||||
|
}
|
||||||
|
|
||||||
|
.device-price {
|
||||||
|
font-size: clamp(1.5rem, 3.6vw, 2rem);
|
||||||
|
font-weight: 700;
|
||||||
|
line-height: 1;
|
||||||
|
letter-spacing: -0.03em;
|
||||||
|
color: var(--foreground);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media print {
|
||||||
|
.device-hero::before,
|
||||||
|
.device-hero::after {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------- 打印样式 ------------------------------- */
|
||||||
|
|
||||||
|
@media print {
|
||||||
|
:root,
|
||||||
|
html[data-theme] {
|
||||||
|
--background: #ffffff;
|
||||||
|
--foreground: #111827;
|
||||||
|
--card: #ffffff;
|
||||||
|
--card-foreground: #111827;
|
||||||
|
--popover: #ffffff;
|
||||||
|
--popover-foreground: #111827;
|
||||||
|
--primary: #0f766e;
|
||||||
|
--primary-foreground: #ffffff;
|
||||||
|
--secondary: #f3f4f6;
|
||||||
|
--secondary-foreground: #111827;
|
||||||
|
--muted: #f3f4f6;
|
||||||
|
--muted-foreground: #4b5563;
|
||||||
|
--accent: #f3f4f6;
|
||||||
|
--accent-foreground: #111827;
|
||||||
|
--destructive: #b91c1c;
|
||||||
|
--border: #d1d5db;
|
||||||
|
--input: #d1d5db;
|
||||||
|
--ring: #0f766e;
|
||||||
|
}
|
||||||
|
|
||||||
|
html {
|
||||||
|
color-scheme: light;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
background: #ffffff !important;
|
||||||
|
color: #111827 !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.print-hidden {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.reveal-grid > * {
|
||||||
|
animation: none !important;
|
||||||
|
opacity: 1 !important;
|
||||||
|
transform: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
main {
|
||||||
|
max-width: none !important;
|
||||||
|
padding: 0 !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
a {
|
||||||
|
color: inherit !important;
|
||||||
|
text-decoration: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.shadow-sm,
|
||||||
|
.shadow-lg,
|
||||||
|
.shadow-2xl {
|
||||||
|
box-shadow: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sticky {
|
||||||
|
position: static !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.overflow-x-auto {
|
||||||
|
overflow: visible !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
section,
|
||||||
|
table,
|
||||||
|
tr,
|
||||||
|
dl,
|
||||||
|
details {
|
||||||
|
break-inside: avoid;
|
||||||
|
}
|
||||||
|
|
||||||
|
details > summary {
|
||||||
|
list-style: none;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+1
-2
@@ -1,10 +1,9 @@
|
|||||||
{
|
{
|
||||||
"extends": "astro/tsconfigs/strict",
|
"extends": "astro/tsconfigs/strict",
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"baseUrl": ".",
|
|
||||||
"jsx": "react-jsx",
|
"jsx": "react-jsx",
|
||||||
"paths": {
|
"paths": {
|
||||||
"@/*": ["src/*"]
|
"@/*": ["./src/*"]
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"include": [".astro/types.d.ts", "**/*"],
|
"include": [".astro/types.d.ts", "**/*"],
|
||||||
|
|||||||
Reference in new issue
Block a user