From 4ff914691036ab9cee646a1bee736a0610903dfa Mon Sep 17 00:00:00 2001 From: zhongluofeng Date: Fri, 6 Nov 2026 15:07:02 +0800 Subject: [PATCH] =?UTF-8?q?=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.example | 11 + DESIGN.md | 371 ++++- Dockerfile | 3 +- README.md | 169 +- astro.config.mjs | 5 + docker-compose.yml | 3 + migrations/002_settings.sql | 6 + package.json | 13 +- pnpm-lock.yaml | 710 +++++++- scripts/apply-hardware-catalog.mjs | 69 + scripts/backup.mjs | 2 + scripts/seed-devices.json | 611 +++++++ scripts/seed.mjs | 229 ++- scripts/sync-coolapk.mjs | 1687 +++++++++++++++++++ scripts/sync-phonerecommend.mjs | 1007 ++++++++++++ scripts/sync-processors.mjs | 532 ++++++ src/components/CompareTray.astro | 179 +++ src/components/DeviceCard.astro | 64 + src/components/HoverInfo.astro | 29 + src/components/LowBadge.astro | 60 + src/components/Pagination.astro | 63 + src/components/admin/BilibiliSetup.tsx | 176 ++ src/components/admin/ChipEditor.tsx | 350 ++++ src/components/admin/DeviceEditor.tsx | 1696 ++++++++++++++++++++ src/components/admin/DeviceQuickCreate.tsx | 150 ++ src/components/admin/ImportPanel.tsx | 131 ++ src/components/admin/controls.tsx | 215 +++ src/layouts/BaseLayout.astro | 183 ++- src/lib/ai/apply.ts | 99 ++ src/lib/ai/lookup.ts | 905 +++++++++++ src/lib/ai/prompt.ts | 284 ++++ src/lib/ai/rules.ts | 278 ++++ src/lib/ai/search.ts | 1259 +++++++++++++++ src/lib/ai/types.ts | 42 + src/lib/auth.ts | 155 ++ src/lib/bilibili.ts | 129 ++ src/lib/compare.ts | 198 +++ src/lib/db.ts | 3 + src/lib/env.ts | 19 + src/lib/hardware-catalog.ts | 422 +++++ src/lib/og.ts | 132 ++ src/lib/rankings.ts | 184 +++ src/lib/repo.ts | 455 +++++- src/lib/schema/phone.ts | 119 +- src/lib/schema/soc.ts | 77 + src/lib/spec-fields.ts | 394 +++++ src/lib/storage.ts | 3 + src/lib/utils.ts | 89 + src/middleware.ts | 15 + src/pages/admin/bilibili.astro | 39 + src/pages/admin/chips/[slug].astro | 66 + src/pages/admin/devices/[slug].astro | 86 + src/pages/admin/import.astro | 39 + src/pages/admin/index.astro | 415 +++++ src/pages/api/ai/field.ts | 67 + src/pages/api/ai/lookup.ts | 67 + src/pages/api/ai/prospect.ts | 166 ++ src/pages/api/ai/section.ts | 65 + src/pages/api/auth/login.ts | 43 + src/pages/api/auth/logout.ts | 10 + src/pages/api/bilibili/login.ts | 18 + src/pages/api/bilibili/poll.ts | 38 + src/pages/api/bilibili/unbind.ts | 11 + src/pages/api/chips.ts | 52 + src/pages/api/devices.ts | 52 + src/pages/api/export.ts | 26 + src/pages/api/import.ts | 113 ++ src/pages/api/upload.ts | 39 + src/pages/brands/[brand].astro | 65 +- src/pages/brands/index.astro | 5 +- src/pages/chips/[slug].astro | 364 ++++- src/pages/chips/index.astro | 207 ++- src/pages/compare.astro | 418 +++++ src/pages/devices/[slug].astro | 1564 +++++++++++++++--- src/pages/devices/index.astro | 78 +- src/pages/index.astro | 55 +- src/pages/og/[slug].png.ts | 36 + src/pages/rankings.astro | 284 ++++ src/pages/sitemap.xml.ts | 2 +- src/styles/global.css | 484 ++++++ tsconfig.json | 3 +- 81 files changed, 18417 insertions(+), 545 deletions(-) create mode 100644 migrations/002_settings.sql create mode 100644 scripts/apply-hardware-catalog.mjs create mode 100644 scripts/seed-devices.json create mode 100644 scripts/sync-coolapk.mjs create mode 100644 scripts/sync-phonerecommend.mjs create mode 100644 scripts/sync-processors.mjs create mode 100644 src/components/CompareTray.astro create mode 100644 src/components/DeviceCard.astro create mode 100644 src/components/HoverInfo.astro create mode 100644 src/components/LowBadge.astro create mode 100644 src/components/Pagination.astro create mode 100644 src/components/admin/BilibiliSetup.tsx create mode 100644 src/components/admin/ChipEditor.tsx create mode 100644 src/components/admin/DeviceEditor.tsx create mode 100644 src/components/admin/DeviceQuickCreate.tsx create mode 100644 src/components/admin/ImportPanel.tsx create mode 100644 src/components/admin/controls.tsx create mode 100644 src/lib/ai/apply.ts create mode 100644 src/lib/ai/lookup.ts create mode 100644 src/lib/ai/prompt.ts create mode 100644 src/lib/ai/rules.ts create mode 100644 src/lib/ai/search.ts create mode 100644 src/lib/ai/types.ts create mode 100644 src/lib/auth.ts create mode 100644 src/lib/bilibili.ts create mode 100644 src/lib/compare.ts create mode 100644 src/lib/env.ts create mode 100644 src/lib/hardware-catalog.ts create mode 100644 src/lib/og.ts create mode 100644 src/lib/rankings.ts create mode 100644 src/lib/spec-fields.ts create mode 100644 src/middleware.ts create mode 100644 src/pages/admin/bilibili.astro create mode 100644 src/pages/admin/chips/[slug].astro create mode 100644 src/pages/admin/devices/[slug].astro create mode 100644 src/pages/admin/import.astro create mode 100644 src/pages/admin/index.astro create mode 100644 src/pages/api/ai/field.ts create mode 100644 src/pages/api/ai/lookup.ts create mode 100644 src/pages/api/ai/prospect.ts create mode 100644 src/pages/api/ai/section.ts create mode 100644 src/pages/api/auth/login.ts create mode 100644 src/pages/api/auth/logout.ts create mode 100644 src/pages/api/bilibili/login.ts create mode 100644 src/pages/api/bilibili/poll.ts create mode 100644 src/pages/api/bilibili/unbind.ts create mode 100644 src/pages/api/chips.ts create mode 100644 src/pages/api/devices.ts create mode 100644 src/pages/api/export.ts create mode 100644 src/pages/api/import.ts create mode 100644 src/pages/api/upload.ts create mode 100644 src/pages/compare.astro create mode 100644 src/pages/og/[slug].png.ts create mode 100644 src/pages/rankings.astro diff --git a/.env.example b/.env.example index b52a08a..d96df00 100644 --- a/.env.example +++ b/.env.example @@ -3,12 +3,23 @@ # ---- 编辑验证(M2 使用)---- ADMIN_PASSWORD=change-me SESSION_SECRET=请替换为随机长字符串 +# 生产环境走 HTTPS 时设为 1;本地 http 调试保持 0 +COOKIE_SECURE=0 +# 站点在反向代理 / CDN 之后时设为 1:登录限速改按 X-Forwarded-For 首段计数, +# 避免所有访问者共享代理 IP 的同一个限速桶。仅在有可信代理时开启,否则该头可被伪造。 +TRUST_PROXY=0 # ---- AI(OpenAI 兼容协议)---- AI_BASE_URL=https://api.deepseek.com/v1 AI_API_KEY= AI_MODEL=deepseek-chat +# Tavily 兼容搜索;不填时使用 Bing / Baidu / DuckDuckGo 公开检索 + ZOL / GSMArena 站内直查 + 白名单站点抓取 SEARCH_API_KEY= +SEARCH_BASE_URL=https://api.tavily.com +# 可选:B 站登录态(浏览器 F12 → Application → Cookies → SESSDATA)。 +# 配置后拆机视频补全会拉取视频字幕全文(马达型号、扬声器单元等细节主要在口播里); +# 不配置时仅能拿到视频标题和简介。SESSDATA 有效期较长,失效后字幕拉不到但不报错。 +BILIBILI_SESSDATA= # ---- 存储 ---- # local | s3 diff --git a/DESIGN.md b/DESIGN.md index 48e641e..426f314 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -556,10 +556,10 @@ interface StorageDriver { |---|---|---| | M0 | 脚手架、Tailwind、shadcn PoC(3 个组件)、zod schema、storage 驱动、repo 层 | 能跑的空站 | | M1 | 只读:手机列表/详情、芯片库、搜索筛选 + sitemap、JSON-LD | 可看、可收录的站 | -| M2 | 编辑:登录、表单(含字段级徽章)、图片上传、修订记录 | 可维护 | -| M3 | AI 分级补全(high 自动 / medium 标黄 / low 阻塞)+ 差异预览 | 录入效率 | -| M4 | 对比页(差异高亮、只看差异、条形可视化)、导出导入、备份脚本 | 完整闭环 | -| M5 | 动效打磨、OG 图、打印样式、部署上线 | 成品 | +| M2 | 编辑:登录、表单(含字段级徽章)、图片上传、修订记录 | 可维护(✅ 已完成,本地验证) | +| M3 | AI 分级补全(high 自动 / medium 标黄 / low 阻塞)+ 差异预览 | 录入效率(✅ 已完成,mock + 浏览器验证) | +| M4 | 对比页(差异高亮、只看差异、条形可视化)、导出导入、备份脚本 | 完整闭环(✅ 已完成,本地验证) | +| M5 | 动效打磨、OG 图、打印样式、部署上线 | 成品(✅ 本地完成,线上部署待执行) | --- @@ -617,7 +617,7 @@ M0 完成标志:**本地 `docker compose up` 能打开首页,`/devices` 与 - 筛选与排序:品牌 chip 列表 + 最新发布 / 按型号 / 按品牌三种排序,全部是 GET 链接 - 品牌页:`/brands`、`/brands/[brand]`(品牌参数 URL 编码 + `decodeURIComponent`) - 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 内容正确 ### 11.5 运行环境与踩坑记录(供换机后参考) @@ -647,17 +647,366 @@ M0 完成标志:**本地 `docker compose up` 能打开首页,`/devices` 与 - `8430e53` M0 脚手架(已推送) - `0c30c79` M1 只读增强(已推送) - `22aa0ef` 部署方式改为宿主构建 + 挂载(**本地已提交,待 `git push`**) +- 当前工作区:M2 编辑后台、M3 AI 补全、M4 对比 / 导入导出(未提交) **线上** - `https://specs.atie.fun` 待用户配置反代(目标 `127.0.0.1:3010`) - 可直接访问 `http://:3010`(需安全组放行)或内网/Tailscale 地址 -**下一步(M2 起)** -1. M2 编辑后台:登录(`ADMIN_PASSWORD` + 签名 cookie)、设备/芯片表单、图片上传(`storage.ts`)、`revisions` 修订记录 -2. M3 AI 分级补全:`/api/ai/lookup` 返回扁平字段 + 置信度,表单按 high/medium/low 着色,low 阻塞保存 -3. M4 对比页(差异高亮、只看差异、数值条形化)、`/api/export` + `/admin/import` -4. M5 动效打磨、OG 图、打印样式 -5. 换机续作时先执行 `pnpm install`(注意 `.npmrc` 的 hoisted 配置),再 `pnpm db:seed` 起本地数据 +**下一步(收尾)** +1. 提交并推送 M2–M5,按 `scripts/deploy.sh` 部署到 ECS +2. 线上验收:OG 图、打印样式、对比页、导入导出、AI 真实供应商 +3. 可选增强:对比页增加“复制链接 / 分享”按钮、更多数值字段的归一化评分 +4. 换机续作时先执行 `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//<时间戳>-<随机>.` + +**修订记录** +- `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/` 返回 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` 只看差异 +- 每组 `
` 可折叠;首列 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 ``,`
` 做页面淡入 +- 列表网格加 `.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/.png` 与 canonical 路径;其他页面默认 `/og/site.png` + +**打印** +- 全局 `@media print`:浅色配色、隐藏 `.print-hidden`(导航、页脚、操作按钮)、取消 sticky / 横向滚动 / 阴影、`break-inside: avoid` +- 设备详情页加「打印 / 保存 PDF」按钮,调用 `window.print()` +- 对比页的切换按钮与面包屑打印时隐藏 + +**主题与交互细节(反馈修正)** +- 黑白主题通过 `html[data-theme]` + 同一套语义变量实现;右上角按钮切换,`localStorage` 记忆,首次访问跟随系统 +- 头部主题脚本在 `` 内联执行,避免首屏闪烁;切换按钮用事件委托,ClientRouter 导航后仍有效 +- ClientRouter 换页会带入服务端渲染的 ``,因此监听 `astro:before-swap` / `astro:after-swap` / `astro:page-load`,把 `localStorage` 中的选择重新写回,避免跨页后主题失效 +- 详情页关键参数卡、影像卡、规格表行增加 hover:行底色 + 字段名切强调色 +- 修复手机列表卡嵌套 `` 导致的布局错乱:卡片改为单一链接,品牌改为纯文本,卡片恢复紧凑网格布局 + +**部署** +- `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 卡展示版本 + 实际速率 +- 卡片改为 ``,点击平滑滚动到对应详细分组;分组与 `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`,黑暗森林色块显示为近黑 + --- diff --git a/Dockerfile b/Dockerfile index 4e11dd3..9d71bc9 100644 --- a/Dockerfile +++ b/Dockerfile @@ -28,7 +28,8 @@ COPY --from=build /app/package.json ./package.json COPY --from=build /app/migrations ./migrations 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 CMD ["node", "./dist/server/entry.mjs"] diff --git a/README.md b/README.md index ea5b388..a45e944 100644 --- a/README.md +++ b/README.md @@ -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 pnpm install 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 typecheck # tsc --noEmit ``` 组件自检页:`/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//`,页面通过 `/uploads/devices//...` 读取;下载后会清理本地不存在的图片引用。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 `` + 主内容淡入;列表网格用 CSS `reveal-grid` 做轻量渐入与 40ms 级联。`prefers-reduced-motion: reduce` 时全部关闭,未引入 GSAP / Lenis。 +- **黑白主题**:右上角按钮切换日间 / 夜间主题;首次访问跟随系统,之后用 `localStorage` 记住,跨页导航和刷新都保持。打印时强制浅色。 +- **详情页参数 hover**:关键参数卡、影像卡和规格表行在鼠标悬停时高亮背景并把字段名切为强调色,便于定位当前参数;顶部参数卡可点击跳转到对应详细分组。 +- **OG 图**:`GET /og/[slug].png` 动态生成 1200×630 PNG,设备页自动使用 `/og/.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 方案) @@ -40,15 +180,28 @@ bash scripts/deploy.sh ```bash pnpm backup # VACUUM INTO 快照 + 打包 uploads 到 backups/<时间戳>/ pnpm db:seed # 重跑种子数据(幂等,按 slug upsert) +pnpm typecheck # 类型检查 ``` ## 目录 ``` -src/lib/schema/ zod 数据模型(phone / soc / FieldMeta) -src/lib/db.ts SQLite 连接 + 迁移 -src/lib/repo.ts 唯一数据出入口 -src/lib/storage.ts 图片存储驱动(local / s3 接口) -migrations/ SQL 迁移,按文件名顺序执行 -scripts/ seed / backup +src/lib/schema/ zod 数据模型(phone / soc / FieldMeta) +src/lib/db.ts SQLite 连接 + 迁移 +src/lib/repo.ts 唯一数据出入口(含修订快照) +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 迁移,按文件名顺序执行 +scripts/ seed / backup / sync-phonerecommend / sync-processors / sync-coolapk ``` + +> 在受限沙箱里 `pnpm dev` 首次 SSR 模块加载可能极慢;可改用 `pnpm build && node dist/server/entry.mjs` 在本地验证生产路径(设置 `HOST` / `PORT` 即可)。 diff --git a/astro.config.mjs b/astro.config.mjs index bc6a0da..a73088b 100644 --- a/astro.config.mjs +++ b/astro.config.mjs @@ -11,6 +11,11 @@ export default defineConfig({ output: 'server', adapter: node({ mode: 'standalone' }), integrations: [react()], + security: { + // 反代后 request.url 的 origin 可能是 localhost,内置校验会误伤正常表单提交。 + // 所有写接口在 src/lib/auth.ts 的 guardWrite / sameOrigin 中自行做同源校验。 + checkOrigin: false, + }, vite: { plugins: [tailwindcss()], }, diff --git a/docker-compose.yml b/docker-compose.yml index 7560ad1..b979814 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -15,6 +15,9 @@ services: - ./node_modules:/app/node_modules # 唯一需要持久化的目录:SQLite 与上传图片 - ./data:/app/data + # node:24-slim 不带字体;OG 图渲染文字需要挂载宿主字体 + - /usr/share/fonts:/usr/share/fonts:ro + - /etc/fonts:/etc/fonts:ro env_file: - .env environment: diff --git a/migrations/002_settings.sql b/migrations/002_settings.sql new file mode 100644 index 0000000..50500b2 --- /dev/null +++ b/migrations/002_settings.sql @@ -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 +); diff --git a/package.json b/package.json index c5adb6c..a44d7d1 100644 --- a/package.json +++ b/package.json @@ -9,7 +9,11 @@ "dev": "astro dev", "build": "astro build", "preview": "astro preview", + "typecheck": "tsc --noEmit", "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", "astro": "astro" }, @@ -25,15 +29,22 @@ "jose": "^6.2.14", "lucide-react": "^1.64.0", "motion": "^14.8.0", + "qrcode": "^1.5.4", "react": "^19.3.1", "react-dom": "^19.3.1", + "sharp": "^0.35.5", "tailwind-merge": "^3.7.0", "tailwindcss": "^4.3.3", "zod": "^4.6.7" }, "devDependencies": { "@types/node": "^26.6.6", + "@types/qrcode": "^1.5.6", "@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" } } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 3389aae..85cc6f0 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -10,10 +10,10 @@ importers: dependencies: '@astrojs/node': specifier: ^11.1.9 - version: 11.1.9(astro@7.4.4(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.1)) + version: 11.1.9(astro@7.4.4(@types/node@26.6.6)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)) '@astrojs/react': specifier: ^7.1.2 - version: 7.1.2(@types/node@26.6.6)(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(jiti@2.7.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(yaml@2.9.1) + version: 7.1.2(@types/node@26.6.6)(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(esbuild@0.28.2)(jiti@2.7.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(tsx@4.23.15)(yaml@2.9.1) '@radix-ui/react-dialog': specifier: ^1.3.1 version: 1.3.1(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) @@ -22,10 +22,10 @@ importers: version: 1.5.0(@types/react@19.3.0)(react@19.3.1) '@tailwindcss/vite': specifier: ^4.3.3 - version: 4.3.3(vite@8.3.5(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.1)) + version: 4.3.3(vite@8.3.5(@types/node@26.6.6)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)) astro: specifier: ^7.4.4 - version: 7.4.4(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.1) + version: 7.4.4(@types/node@26.6.6)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1) class-variance-authority: specifier: ^0.7.1 version: 0.7.1 @@ -41,12 +41,18 @@ importers: motion: specifier: ^14.8.0 version: 14.8.0(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + qrcode: + specifier: ^1.5.4 + version: 1.5.4 react: specifier: ^19.3.1 version: 19.3.1 react-dom: specifier: ^19.3.1 version: 19.3.1(react@19.3.1) + sharp: + specifier: ^0.35.5 + version: 0.35.5(@types/node@26.6.6) tailwind-merge: specifier: ^3.7.0 version: 3.7.0 @@ -60,12 +66,27 @@ importers: '@types/node': specifier: ^26.6.6 version: 26.6.6 + '@types/qrcode': + specifier: ^1.5.6 + version: 1.5.6 '@types/react': specifier: ^19.3.0 version: 19.3.0 '@types/react-dom': specifier: ^19.3.0 version: 19.3.0(@types/react@19.3.0) + cheerio: + specifier: ^1.2.0 + version: 1.2.0 + pinyin-pro: + specifier: ^3.29.5 + version: 3.29.5 + tsx: + specifier: ^4.23.15 + version: 4.23.15 + typescript: + specifier: ^6.0.3 + version: 6.0.3 packages: @@ -268,6 +289,162 @@ packages: '@emnapi/wasi-threads@1.2.3': resolution: {integrity: sha512-ELEBe8PsLvvJ6QMr0zLt8ffvOHW/dc1m3CEzNMg7aJUv3bMaoDtw2TXyDAwkYBuroxxuHEwhRTLJSe5sya547g==} + '@esbuild/aix-ppc64@0.28.2': + resolution: {integrity: sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [aix] + + '@esbuild/android-arm64@0.28.2': + resolution: {integrity: sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==} + engines: {node: '>=18'} + cpu: [arm64] + os: [android] + + '@esbuild/android-arm@0.28.2': + resolution: {integrity: sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==} + engines: {node: '>=18'} + cpu: [arm] + os: [android] + + '@esbuild/android-x64@0.28.2': + resolution: {integrity: sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==} + engines: {node: '>=18'} + cpu: [x64] + os: [android] + + '@esbuild/darwin-arm64@0.28.2': + resolution: {integrity: sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [darwin] + + '@esbuild/darwin-x64@0.28.2': + resolution: {integrity: sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==} + engines: {node: '>=18'} + cpu: [x64] + os: [darwin] + + '@esbuild/freebsd-arm64@0.28.2': + resolution: {integrity: sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [freebsd] + + '@esbuild/freebsd-x64@0.28.2': + resolution: {integrity: sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==} + engines: {node: '>=18'} + cpu: [x64] + os: [freebsd] + + '@esbuild/linux-arm64@0.28.2': + resolution: {integrity: sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==} + engines: {node: '>=18'} + cpu: [arm64] + os: [linux] + + '@esbuild/linux-arm@0.28.2': + resolution: {integrity: sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==} + engines: {node: '>=18'} + cpu: [arm] + os: [linux] + + '@esbuild/linux-ia32@0.28.2': + resolution: {integrity: sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==} + engines: {node: '>=18'} + cpu: [ia32] + os: [linux] + + '@esbuild/linux-loong64@0.28.2': + resolution: {integrity: sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==} + engines: {node: '>=18'} + cpu: [loong64] + os: [linux] + + '@esbuild/linux-mips64el@0.28.2': + resolution: {integrity: sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==} + engines: {node: '>=18'} + cpu: [mips64el] + os: [linux] + + '@esbuild/linux-ppc64@0.28.2': + resolution: {integrity: sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [linux] + + '@esbuild/linux-riscv64@0.28.2': + resolution: {integrity: sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==} + engines: {node: '>=18'} + cpu: [riscv64] + os: [linux] + + '@esbuild/linux-s390x@0.28.2': + resolution: {integrity: sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==} + engines: {node: '>=18'} + cpu: [s390x] + os: [linux] + + '@esbuild/linux-x64@0.28.2': + resolution: {integrity: sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [linux] + + '@esbuild/netbsd-arm64@0.28.2': + resolution: {integrity: sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [netbsd] + + '@esbuild/netbsd-x64@0.28.2': + resolution: {integrity: sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==} + engines: {node: '>=18'} + cpu: [x64] + os: [netbsd] + + '@esbuild/openbsd-arm64@0.28.2': + resolution: {integrity: sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openbsd] + + '@esbuild/openbsd-x64@0.28.2': + resolution: {integrity: sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==} + engines: {node: '>=18'} + cpu: [x64] + os: [openbsd] + + '@esbuild/openharmony-arm64@0.28.2': + resolution: {integrity: sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openharmony] + + '@esbuild/sunos-x64@0.28.2': + resolution: {integrity: sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==} + engines: {node: '>=18'} + cpu: [x64] + os: [sunos] + + '@esbuild/win32-arm64@0.28.2': + resolution: {integrity: sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==} + engines: {node: '>=18'} + cpu: [arm64] + os: [win32] + + '@esbuild/win32-ia32@0.28.2': + resolution: {integrity: sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==} + engines: {node: '>=18'} + cpu: [ia32] + os: [win32] + + '@esbuild/win32-x64@0.28.2': + resolution: {integrity: sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==} + engines: {node: '>=18'} + cpu: [x64] + os: [win32] + '@img/colour@1.1.0': resolution: {integrity: sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==} engines: {node: '>=18'} @@ -866,6 +1043,9 @@ packages: '@types/node@26.6.6': resolution: {integrity: sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==} + '@types/qrcode@1.5.6': + resolution: {integrity: sha512-te7NQcV2BOvdj2b1hCAHzAoMNuj65kNBMz0KBaxM6c3VGBOhU0dURQKOtH8CFNI/dsKkwlv32p26qYQTWoB5bw==} + '@types/react-dom@19.3.0': resolution: {integrity: sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==} peerDependencies: @@ -900,6 +1080,14 @@ packages: resolution: {integrity: sha512-KLcsDhqf1XRrJmJr+9I/C0EX2K+sGrAGZFgkmd84c8TJO9zJBu+/kFInjazu1KfJWFhWDKdRWkpBzEs7s35DVA==} hasBin: true + ansi-regex@5.0.1: + resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==} + engines: {node: '>=8'} + + ansi-styles@4.3.0: + resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==} + engines: {node: '>=8'} + anymatch@3.1.3: resolution: {integrity: sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==} engines: {node: '>= 8'} @@ -932,6 +1120,10 @@ packages: boolbase@1.0.0: resolution: {integrity: sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==} + camelcase@5.3.1: + resolution: {integrity: sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==} + engines: {node: '>=6'} + ccount@2.0.1: resolution: {integrity: sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==} @@ -941,6 +1133,13 @@ packages: character-entities-legacy@3.0.0: resolution: {integrity: sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ==} + cheerio-select@2.1.0: + resolution: {integrity: sha512-9v9kG0LvzrlcungtnJtpGNxY+fzECQKhK4EGJX2vByejiMX84MFNQw4UxPJl3bFbTMw+Dfs37XaIkCwTZfLh4g==} + + cheerio@1.2.0: + resolution: {integrity: sha512-WDrybc/gKFpTYQutKIK6UvfcuxijIZfMfXaYm8NMsPQxSYvf+13fXUJ4rztGGbJcBQ/GF55gvrZ0Bc0bj/mqvg==} + engines: {node: '>=20.18.1'} + chokidar@5.0.0: resolution: {integrity: sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==} engines: {node: '>= 20.19.0'} @@ -952,10 +1151,20 @@ packages: class-variance-authority@0.7.1: resolution: {integrity: sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg==} + cliui@6.0.0: + resolution: {integrity: sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==} + clsx@2.1.1: resolution: {integrity: sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==} engines: {node: '>=6'} + color-convert@2.0.1: + resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==} + engines: {node: '>=7.0.0'} + + color-name@1.1.4: + resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==} + comma-separated-tokens@2.0.3: resolution: {integrity: sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==} @@ -977,6 +1186,9 @@ packages: crossws@0.3.5: resolution: {integrity: sha512-ojKiDvcmByhwa8YYqbQI/hg7MEU0NC03+pSdEq4ZUnZR9xXpwk7E43SMNGkn+JxJGPFtNvQ48+vV2p+P1ml5PA==} + css-select@5.2.2: + resolution: {integrity: sha512-TizTzUddG/xYLA3NXodFM0fSbNizXjOKhqiQQwvhlspadZokn1KDy0NZFS0wuEubIYAV5/c1/lAr0TaaFXEXzw==} + css-select@6.0.0: resolution: {integrity: sha512-rZZVSLle8v0+EY8QAkDWrKhpgt6SA5OtHsgBnsj6ZaLb5dmDVOWUDtQitd9ydxxvEjhewNudS6eTVU7uOyzvXw==} @@ -988,6 +1200,10 @@ packages: resolution: {integrity: sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==} engines: {node: ^10 || ^12.20.0 || ^14.13.0 || >=15.0.0} + css-what@6.2.2: + resolution: {integrity: sha512-u/O3vwbptzhMs3L1fQE82ZSLHQQfto5gyZzwteVIEyeaY5Fc7R4dapF/BvRoSYFeqfBk4m0V1Vafq5Pjv25wvA==} + engines: {node: '>= 6'} + css-what@7.0.0: resolution: {integrity: sha512-wD5oz5xibMOPHzy13CyGmogB3phdvcDaB5t0W/Nr5Z2O/agcB8YwOz6e2Lsp10pNDzBoDO9nVa3RGs/2BttpHQ==} engines: {node: '>= 6'} @@ -1008,6 +1224,10 @@ packages: supports-color: optional: true + decamelize@1.2.0: + resolution: {integrity: sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==} + engines: {node: '>=0.10.0'} + defu@6.1.7: resolution: {integrity: sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ==} @@ -1040,6 +1260,9 @@ packages: resolution: {integrity: sha512-svtcdpS8CgJyqAjEQIXdb3OjhFVVYjzGAPO8WGCmRbrml64SPw/jJD4GoE98aR7r25A0XcgrK3F02yw9R/vhQw==} engines: {node: '>=0.3.1'} + dijkstrajs@1.0.3: + resolution: {integrity: sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA==} + dom-serializer@2.0.0: resolution: {integrity: sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==} @@ -1060,10 +1283,16 @@ packages: ee-first@1.1.1: resolution: {integrity: sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==} + emoji-regex@8.0.0: + resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==} + encodeurl@2.0.1: resolution: {integrity: sha512-Ev/hIyePLZtpL98x562lvPtenrUfGr0lfaf44HFZ+hDEwso7ccV9QAZrEVLg0hxNAzygaAFxy2dYaAKKM0G06A==} engines: {node: '>= 0.8'} + encoding-sniffer@0.2.1: + resolution: {integrity: sha512-5gvq20T6vfpekVtqrYQsSCFZ1wEg5+wW0/QaZMWkFr6BqD3NfKs0rLCx4rrVlSWJeZb5NBJgVLswK/w2MWU+Gw==} + enhanced-resolve@5.26.0: resolution: {integrity: sha512-9vhedylFonb2YGogzUKX6+Ja72gOJbN1QHAqdrvqLwhdl/QWbKopzoUC9EbQNVsAns/bx/4uyqalrQAoy1IByw==} engines: {node: '>=10.13.0'} @@ -1072,9 +1301,22 @@ packages: resolution: {integrity: sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==} engines: {node: '>=0.12'} + entities@6.0.1: + resolution: {integrity: sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==} + engines: {node: '>=0.12'} + + entities@7.0.1: + resolution: {integrity: sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==} + engines: {node: '>=0.12'} + es-module-lexer@3.0.4: resolution: {integrity: sha512-BldNY5mwkVu+cQ5Ymn3e6hB9Sx8XHx4ZevWbiUyZbfKxJxYO27Hf0wfzkxIaD5CAJMaGl3YspKELj0ff/7nCMA==} + esbuild@0.28.2: + resolution: {integrity: sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==} + engines: {node: '>=18'} + hasBin: true + escape-html@1.0.3: resolution: {integrity: sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==} @@ -1106,6 +1348,10 @@ packages: picomatch: optional: true + find-up@4.1.0: + resolution: {integrity: sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==} + engines: {node: '>=8'} + flattie@1.1.1: resolution: {integrity: sha512-9UbaD6XdAL97+k/n+N7JwX46K/M6Zc6KcFYskrYL8wbBV/Uyk0CTAMY0VT+qiK5PM7AIc9aTWYtq65U7T+aCNQ==} engines: {node: '>=8'} @@ -1143,6 +1389,10 @@ packages: engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} os: [darwin] + get-caller-file@2.0.5: + resolution: {integrity: sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==} + engines: {node: 6.* || 8.* || >= 10.*} + get-nonce@1.0.1: resolution: {integrity: sha512-FJhYRoDaiatfEkUK8HKlicmu/3SGFD51q3itKDGoSTysQJBnfOcxU5GxnhE1E6soB76MbT0MBtnKJuXyAx+96Q==} engines: {node: '>=6'} @@ -1172,6 +1422,9 @@ packages: html-void-elements@3.0.0: resolution: {integrity: sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg==} + htmlparser2@10.1.0: + resolution: {integrity: sha512-VTZkM9GWRAtEpveh7MSF6SjjrpNVNNVJfFup7xTY3UpFtm67foy9HDVXneLtFVt4pMz5kZtgNcvCniNFb1hlEQ==} + http-cache-semantics@4.3.0: resolution: {integrity: sha512-M5t5LlJpS1UHMjvwRQVdFHvPISGeLAxNcrWuJkeGh0KxsqCHZ1O3NXZU/8x7cD0BDcGW8kapxMKTvwlqrNkHkA==} @@ -1179,6 +1432,10 @@ packages: resolution: {integrity: sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==} engines: {node: '>= 0.8'} + iconv-lite@0.6.3: + resolution: {integrity: sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==} + engines: {node: '>=0.10.0'} + inherits@2.0.4: resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==} @@ -1190,6 +1447,10 @@ packages: engines: {node: '>=20'} hasBin: true + is-fullwidth-code-point@3.0.0: + resolution: {integrity: sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==} + engines: {node: '>=8'} + is-plain-obj@4.1.0: resolution: {integrity: sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==} engines: {node: '>=12'} @@ -1352,6 +1613,10 @@ packages: resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==} engines: {node: '>= 12.0.0'} + locate-path@5.0.0: + resolution: {integrity: sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==} + engines: {node: '>=8'} + lru-cache@11.5.3: resolution: {integrity: sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==} engines: {node: 20 || >=22} @@ -1475,10 +1740,18 @@ packages: oniguruma-to-es@4.3.6: resolution: {integrity: sha512-csuQ9x3Yr0cEIs/Zgx/OEt9iBw9vqIunAPQkx19R/fiMq2oGVTgcMqO/V3Ybqefr1TBvosI6jU539ksaBULJyA==} + p-limit@2.3.0: + resolution: {integrity: sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==} + engines: {node: '>=6'} + p-limit@7.3.3: resolution: {integrity: sha512-SKgVvDU5TNIxQ4r30U75BNLC6a+6GOEjngrk/ysM5+Zu3oJuk1SC5ApzIzY/7PjCEjoVPMWJ0zho/4QUiEB7TQ==} engines: {node: '>=20'} + p-locate@4.1.0: + resolution: {integrity: sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==} + engines: {node: '>=8'} + p-queue@9.3.5: resolution: {integrity: sha512-Lki/zhXFVmDhesBUn/yHRLW9Bte7mE7xoFHzTR8sIomV7a2z+LxYAPkGvdfidNiu4fKSfjtawixxSHcZci5QcQ==} engines: {node: '>=20'} @@ -1487,9 +1760,26 @@ packages: resolution: {integrity: sha512-prbX4Z3YszrFNgH+MW5Zoeq3baXrMtP/MQnFeET90UB/GtGcGDQ5Usg9OCy6ETjTTntOw1SL2z9fMPUppN3Guw==} engines: {node: '>=20'} + p-try@2.2.0: + resolution: {integrity: sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==} + engines: {node: '>=6'} + package-manager-detector@1.9.0: resolution: {integrity: sha512-zAMfbta9nPA8AKkA4WdmNAT8R8s6Dk0/xwPsqNnRidMFcLo1YkLuPDTgs2f64XdzS8vbLNnoJ+uUIkgbz7oRHA==} + parse5-htmlparser2-tree-adapter@7.1.0: + resolution: {integrity: sha512-ruw5xyKs6lrpo9x9rCZqZZnIUntICjQAd0Wsmp396Ul9lN/h+ifgVV1x1gZHi8euej6wTfpqX8j+BFQxF0NS/g==} + + parse5-parser-stream@7.1.2: + resolution: {integrity: sha512-JyeQc9iwFLn5TbvvqACIF/VXG6abODeB3Fwmv/TGdLk2LfbWkaySGY72at4+Ty7EkPZj854u4CrICqNk2qIbow==} + + parse5@7.3.0: + resolution: {integrity: sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==} + + path-exists@4.0.0: + resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==} + engines: {node: '>=8'} + piccolore@0.1.3: resolution: {integrity: sha512-o8bTeDWjE086iwKrROaDf31K0qC/BENdm15/uH9usSC/uZjJOKb2YGiVHfLY4GhwsERiPI1jmwI2XrA7ACOxVw==} @@ -1504,6 +1794,13 @@ packages: resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} engines: {node: '>=12'} + pinyin-pro@3.29.5: + resolution: {integrity: sha512-Fk5YoRmtdHqJWqAuzYVG/NzvzeCbaG+ZEwbY6Nbps3QAIrvQQEtcm49frcyCM8i2b5najnzPDtYqrHRYTTiuwQ==} + + pngjs@5.0.0: + resolution: {integrity: sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw==} + engines: {node: '>=10.13.0'} + postcss@8.5.32: resolution: {integrity: sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==} engines: {node: ^10 || ^12 || >=14} @@ -1519,6 +1816,11 @@ packages: property-information@7.2.0: resolution: {integrity: sha512-IAtzIB6sUiWaJYrX9smp3V46pBGbBeLFRGdh25kg1334VcBlD8HzhPeNIWQH9zhGmo2itIe25EHt9dQP7G5hmg==} + qrcode@1.5.4: + resolution: {integrity: sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg==} + engines: {node: '>=10.13.0'} + hasBin: true + radix3@1.1.2: resolution: {integrity: sha512-b484I/7b8rDEdSDKckSSBA8knMpcdsXudlE/LNL639wFoHKwLbEkQFZHWEYwDC0wa0FKUcCY+GAF73Z7wxNVFA==} @@ -1578,6 +1880,13 @@ packages: regex@6.1.0: resolution: {integrity: sha512-6VwtthbV4o/7+OaAF9I5L5V3llLEsoPyq9P1JVXkedTP33c7MfCG0/5NOPcSJn0TzXcG9YUrR0gQSWioew3LDg==} + require-directory@2.1.1: + resolution: {integrity: sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==} + engines: {node: '>=0.10.0'} + + require-main-filename@2.0.0: + resolution: {integrity: sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==} + resolve-pkg-maps@1.0.0: resolution: {integrity: sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==} @@ -1589,6 +1898,9 @@ packages: engines: {node: ^20.19.0 || >=22.12.0} hasBin: true + safer-buffer@2.1.2: + resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==} + satteri@0.10.5: resolution: {integrity: sha512-Ao1LKpAEa9Wdg0otgbVKViZHEq9ebdXe4DMrp3s9vQAU0HNIuHnFEuMuOcm0ZIXyV0Yzxj91NvhLpvXZJO/5ZQ==} @@ -1611,6 +1923,9 @@ packages: server-destroy@1.0.1: resolution: {integrity: sha512-rb+9B5YBIEzYcD6x2VKidaa+cqYBJQKnU4oe4E3ANwRRN56yk/ua1YCJT1n21NTS8w6CcOclAKNP3PhdCXKYtQ==} + set-blocking@2.0.0: + resolution: {integrity: sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==} + setprototypeof@1.2.0: resolution: {integrity: sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==} @@ -1648,9 +1963,17 @@ packages: std-env@4.3.0: resolution: {integrity: sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==} + string-width@4.2.3: + resolution: {integrity: sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==} + engines: {node: '>=8'} + stringify-entities@4.0.4: resolution: {integrity: sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==} + strip-ansi@6.0.1: + resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==} + engines: {node: '>=8'} + svgo@4.1.0: resolution: {integrity: sha512-bkxnTg1kSU0guhIBmibA6UUhrQmPVA1XsQLN+ylCd+UWzbnLkySOcXpyk1mrl05f+pcaCx2eHb+sp6BgMZWX+Q==} engines: {node: '>=16'} @@ -1697,6 +2020,16 @@ packages: tslib@2.8.1: resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==} + tsx@4.23.15: + resolution: {integrity: sha512-Yiex1Ovn8z2xPpOWckIiysV1SSyRMY9BkLF++q0yKiDxCqRhosKfMg3janKkiLBwZ5c/YryloKwGZcrEmtwxKw==} + engines: {node: '>=18.0.0'} + hasBin: true + + typescript@6.0.3: + resolution: {integrity: sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==} + engines: {node: '>=14.17'} + hasBin: true + ufo@1.6.4: resolution: {integrity: sha512-JFNbkD1Svwe0KvGi8GOeLcP4kAWQ609twvCdcHxq1oSL8svv39ZuSvajcD8B+5D0eL4+s1Is2D/O6KN3qcTeRA==} @@ -1709,6 +2042,10 @@ packages: undici-types@8.9.0: resolution: {integrity: sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==} + undici@7.30.1: + resolution: {integrity: sha512-03KrMbjIFDWQR5RNPrSw3bd1r12JpyFQl9/yxjUbJtqkjmllqC5lFjZh6ujeuJCKr8EOQvRW872Oy/az+nLYxg==} + engines: {node: '>=20.18.1'} + undici@8.12.3: resolution: {integrity: sha512-+fdndUTwBP86cVjihTp21hZHo7d6oj1c/47XPA3lL8mM0XHs+C4EkcjmgRsFnFk2f/UONGDy9ItBItmXsLOQHw==} engines: {node: '>=22.19.0'} @@ -1877,18 +2214,45 @@ packages: vite: optional: true + whatwg-encoding@3.1.1: + resolution: {integrity: sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==} + engines: {node: '>=18'} + deprecated: Use @exodus/bytes instead for a more spec-conformant and faster implementation + + whatwg-mimetype@4.0.0: + resolution: {integrity: sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==} + engines: {node: '>=18'} + + which-module@2.0.1: + resolution: {integrity: sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==} + + wrap-ansi@6.2.0: + resolution: {integrity: sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==} + engines: {node: '>=8'} + xxhash-wasm@1.1.0: resolution: {integrity: sha512-147y/6YNh+tlp6nd/2pWq38i9h6mz/EuQ6njIrmW8D1BS5nCqs0P6DG+m6zTGnNz5I+uhZ0SHxBs9BsPrwcKDA==} + y18n@4.0.3: + resolution: {integrity: sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==} + yaml@2.9.1: resolution: {integrity: sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==} engines: {node: '>= 14.6'} hasBin: true + yargs-parser@18.1.3: + resolution: {integrity: sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==} + engines: {node: '>=6'} + yargs-parser@22.0.0: resolution: {integrity: sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw==} engines: {node: ^20.19.0 || ^22.12.0 || >=23} + yargs@15.4.1: + resolution: {integrity: sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==} + engines: {node: '>=8'} + yocto-queue@1.2.2: resolution: {integrity: sha512-4LCcse/U2MHZ63HAJVE+v71o7yOdIe4cZ70Wpf8D/IyjDKYQLV5GD46B+hSTjJsvV5PztjvHoU580EftxjDZFQ==} engines: {node: '>=12.20'} @@ -1970,10 +2334,10 @@ snapshots: github-slugger: 2.0.0 satteri: 0.10.5 - '@astrojs/node@11.1.9(astro@7.4.4(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.1))': + '@astrojs/node@11.1.9(astro@7.4.4(@types/node@26.6.6)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))': dependencies: '@astrojs/internal-helpers': 0.13.0 - astro: 7.4.4(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.1) + astro: 7.4.4(@types/node@26.6.6)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1) send: 1.2.1 server-destroy: 1.0.1 transitivePeerDependencies: @@ -1983,17 +2347,17 @@ snapshots: dependencies: prismjs: 1.30.0 - '@astrojs/react@7.1.2(@types/node@26.6.6)(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(jiti@2.7.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(yaml@2.9.1)': + '@astrojs/react@7.1.2(@types/node@26.6.6)(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(esbuild@0.28.2)(jiti@2.7.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(tsx@4.23.15)(yaml@2.9.1)': dependencies: '@astrojs/internal-helpers': 0.13.0 '@types/react': 19.3.0 '@types/react-dom': 19.3.0(@types/react@19.3.0) - '@vitejs/plugin-react': 6.1.2(vite@8.3.5(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.1)) + '@vitejs/plugin-react': 6.1.2(vite@8.3.5(@types/node@26.6.6)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)) devalue: 6.0.3 react: 19.3.1 react-dom: 19.3.1(react@19.3.1) ultrahtml: 1.7.0 - vite: 8.3.5(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.1) + vite: 8.3.5(@types/node@26.6.6)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1) transitivePeerDependencies: - '@rolldown/plugin-babel' - '@types/node' @@ -2109,9 +2473,86 @@ snapshots: tslib: 2.8.1 optional: true - '@img/colour@1.1.0': + '@esbuild/aix-ppc64@0.28.2': optional: true + '@esbuild/android-arm64@0.28.2': + optional: true + + '@esbuild/android-arm@0.28.2': + optional: true + + '@esbuild/android-x64@0.28.2': + optional: true + + '@esbuild/darwin-arm64@0.28.2': + optional: true + + '@esbuild/darwin-x64@0.28.2': + optional: true + + '@esbuild/freebsd-arm64@0.28.2': + optional: true + + '@esbuild/freebsd-x64@0.28.2': + optional: true + + '@esbuild/linux-arm64@0.28.2': + optional: true + + '@esbuild/linux-arm@0.28.2': + optional: true + + '@esbuild/linux-ia32@0.28.2': + optional: true + + '@esbuild/linux-loong64@0.28.2': + optional: true + + '@esbuild/linux-mips64el@0.28.2': + optional: true + + '@esbuild/linux-ppc64@0.28.2': + optional: true + + '@esbuild/linux-riscv64@0.28.2': + optional: true + + '@esbuild/linux-s390x@0.28.2': + optional: true + + '@esbuild/linux-x64@0.28.2': + optional: true + + '@esbuild/netbsd-arm64@0.28.2': + optional: true + + '@esbuild/netbsd-x64@0.28.2': + optional: true + + '@esbuild/openbsd-arm64@0.28.2': + optional: true + + '@esbuild/openbsd-x64@0.28.2': + optional: true + + '@esbuild/openharmony-arm64@0.28.2': + optional: true + + '@esbuild/sunos-x64@0.28.2': + optional: true + + '@esbuild/win32-arm64@0.28.2': + optional: true + + '@esbuild/win32-ia32@0.28.2': + optional: true + + '@esbuild/win32-x64@0.28.2': + optional: true + + '@img/colour@1.1.0': {} + '@img/sharp-darwin-arm64@0.35.5': optionalDependencies: '@img/sharp-libvips-darwin-arm64': 1.3.4 @@ -2539,12 +2980,12 @@ snapshots: '@tailwindcss/oxide-win32-arm64-msvc': 4.3.3 '@tailwindcss/oxide-win32-x64-msvc': 4.3.3 - '@tailwindcss/vite@4.3.3(vite@8.3.5(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.1))': + '@tailwindcss/vite@4.3.3(vite@8.3.5(@types/node@26.6.6)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))': dependencies: '@tailwindcss/node': 4.3.3 '@tailwindcss/oxide': 4.3.3 tailwindcss: 4.3.3 - vite: 8.3.5(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.1) + vite: 8.3.5(@types/node@26.6.6)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1) '@tybys/wasm-util@0.10.4': dependencies: @@ -2573,6 +3014,10 @@ snapshots: dependencies: undici-types: 8.9.0 + '@types/qrcode@1.5.6': + dependencies: + '@types/node': 26.6.6 + '@types/react-dom@19.3.0(@types/react@19.3.0)': dependencies: '@types/react': 19.3.0 @@ -2585,15 +3030,21 @@ snapshots: '@ungap/structured-clone@1.4.0': {} - '@vitejs/plugin-react@6.1.2(vite@8.3.5(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.1))': + '@vitejs/plugin-react@6.1.2(vite@8.3.5(@types/node@26.6.6)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))': dependencies: '@rolldown/pluginutils': 1.0.1 - vite: 8.3.5(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.1) + vite: 8.3.5(@types/node@26.6.6)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1) am-i-vibing@0.5.0: dependencies: process-ancestry: 0.1.0 + ansi-regex@5.0.1: {} + + ansi-styles@4.3.0: + dependencies: + color-convert: 2.0.1 + anymatch@3.1.3: dependencies: normalize-path: 3.0.0 @@ -2605,7 +3056,7 @@ snapshots: aria-query@5.3.2: {} - astro@7.4.4(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.1): + astro@7.4.4(@types/node@26.6.6)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1): dependencies: '@astrojs/compiler-rs': 0.5.2 '@astrojs/internal-helpers': 0.13.0 @@ -2654,8 +3105,8 @@ snapshots: unifont: 1.0.3 unstorage: 1.17.6 verkit: 0.5.0 - vite: 8.3.5(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.1) - vitefu: 1.1.3(vite@8.3.5(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.1)) + vite: 8.3.5(@types/node@26.6.6)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1) + vitefu: 1.1.3(vite@8.3.5(@types/node@26.6.6)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)) xxhash-wasm: 1.1.0 yargs-parser: 22.0.0 zod: 4.6.7 @@ -2700,12 +3151,37 @@ snapshots: boolbase@1.0.0: {} + camelcase@5.3.1: {} + ccount@2.0.1: {} character-entities-html4@2.1.0: {} character-entities-legacy@3.0.0: {} + cheerio-select@2.1.0: + dependencies: + boolbase: 1.0.0 + css-select: 5.2.2 + css-what: 6.2.2 + domelementtype: 2.3.0 + domhandler: 5.0.3 + domutils: 3.2.2 + + cheerio@1.2.0: + dependencies: + cheerio-select: 2.1.0 + dom-serializer: 2.0.0 + domhandler: 5.0.3 + domutils: 3.2.2 + encoding-sniffer: 0.2.1 + htmlparser2: 10.1.0 + parse5: 7.3.0 + parse5-htmlparser2-tree-adapter: 7.1.0 + parse5-parser-stream: 7.1.2 + undici: 7.30.1 + whatwg-mimetype: 4.0.0 + chokidar@5.0.0: dependencies: readdirp: 5.1.1 @@ -2716,8 +3192,20 @@ snapshots: dependencies: clsx: 2.1.1 + cliui@6.0.0: + dependencies: + string-width: 4.2.3 + strip-ansi: 6.0.1 + wrap-ansi: 6.2.0 + clsx@2.1.1: {} + color-convert@2.0.1: + dependencies: + color-name: 1.1.4 + + color-name@1.1.4: {} + comma-separated-tokens@2.0.3: {} commander@11.1.0: {} @@ -2732,6 +3220,14 @@ snapshots: dependencies: uncrypto: 0.1.3 + css-select@5.2.2: + dependencies: + boolbase: 1.0.0 + css-what: 6.2.2 + domhandler: 5.0.3 + domutils: 3.2.2 + nth-check: 2.1.1 + css-select@6.0.0: dependencies: boolbase: 1.0.0 @@ -2750,6 +3246,8 @@ snapshots: mdn-data: 2.27.1 source-map-js: 1.2.2 + css-what@6.2.2: {} + css-what@7.0.0: {} csso@5.0.5: @@ -2762,6 +3260,8 @@ snapshots: dependencies: ms: 2.1.3 + decamelize@1.2.0: {} + defu@6.1.7: {} depd@2.0.0: {} @@ -2782,6 +3282,8 @@ snapshots: diff@9.0.0: {} + dijkstrajs@1.0.3: {} + dom-serializer@2.0.0: dependencies: domelementtype: 2.3.0 @@ -2804,8 +3306,15 @@ snapshots: ee-first@1.1.1: {} + emoji-regex@8.0.0: {} + encodeurl@2.0.1: {} + encoding-sniffer@0.2.1: + dependencies: + iconv-lite: 0.6.3 + whatwg-encoding: 3.1.1 + enhanced-resolve@5.26.0: dependencies: graceful-fs: 4.2.11 @@ -2813,8 +3322,41 @@ snapshots: entities@4.5.0: {} + entities@6.0.1: {} + + entities@7.0.1: {} + es-module-lexer@3.0.4: {} + esbuild@0.28.2: + optionalDependencies: + '@esbuild/aix-ppc64': 0.28.2 + '@esbuild/android-arm': 0.28.2 + '@esbuild/android-arm64': 0.28.2 + '@esbuild/android-x64': 0.28.2 + '@esbuild/darwin-arm64': 0.28.2 + '@esbuild/darwin-x64': 0.28.2 + '@esbuild/freebsd-arm64': 0.28.2 + '@esbuild/freebsd-x64': 0.28.2 + '@esbuild/linux-arm': 0.28.2 + '@esbuild/linux-arm64': 0.28.2 + '@esbuild/linux-ia32': 0.28.2 + '@esbuild/linux-loong64': 0.28.2 + '@esbuild/linux-mips64el': 0.28.2 + '@esbuild/linux-ppc64': 0.28.2 + '@esbuild/linux-riscv64': 0.28.2 + '@esbuild/linux-s390x': 0.28.2 + '@esbuild/linux-x64': 0.28.2 + '@esbuild/netbsd-arm64': 0.28.2 + '@esbuild/netbsd-x64': 0.28.2 + '@esbuild/openbsd-arm64': 0.28.2 + '@esbuild/openbsd-x64': 0.28.2 + '@esbuild/openharmony-arm64': 0.28.2 + '@esbuild/sunos-x64': 0.28.2 + '@esbuild/win32-arm64': 0.28.2 + '@esbuild/win32-ia32': 0.28.2 + '@esbuild/win32-x64': 0.28.2 + escape-html@1.0.3: {} etag@1.8.1: {} @@ -2837,6 +3379,11 @@ snapshots: optionalDependencies: picomatch: 4.0.7 + find-up@4.1.0: + dependencies: + locate-path: 5.0.0 + path-exists: 4.0.0 + flattie@1.1.1: {} fnv1a-64@0.1.2: {} @@ -2863,6 +3410,8 @@ snapshots: fsevents@2.3.3: optional: true + get-caller-file@2.0.5: {} + get-nonce@1.0.1: {} get-tsconfig@5.0.0-beta.6: @@ -2907,6 +3456,13 @@ snapshots: html-void-elements@3.0.0: {} + htmlparser2@10.1.0: + dependencies: + domelementtype: 2.3.0 + domhandler: 5.0.3 + domutils: 3.2.2 + entities: 7.0.1 + http-cache-semantics@4.3.0: {} http-errors@2.0.1: @@ -2917,12 +3473,18 @@ snapshots: statuses: 2.0.2 toidentifier: 1.0.1 + iconv-lite@0.6.3: + dependencies: + safer-buffer: 2.1.2 + inherits@2.0.4: {} iron-webcrypto@1.2.1: {} is-docker@4.0.0: {} + is-fullwidth-code-point@3.0.0: {} + is-plain-obj@4.1.0: {} jiti@2.7.0: {} @@ -3029,6 +3591,10 @@ snapshots: lightningcss-win32-arm64-msvc: 1.33.0 lightningcss-win32-x64-msvc: 1.33.0 + locate-path@5.0.0: + dependencies: + p-locate: 4.1.0 + lru-cache@11.5.3: {} lucide-react@1.65.0(@types/react@19.3.0)(react@19.3.1): @@ -3146,10 +3712,18 @@ snapshots: regex: 6.1.0 regex-recursion: 6.0.2 + p-limit@2.3.0: + dependencies: + p-try: 2.2.0 + p-limit@7.3.3: dependencies: yocto-queue: 1.2.2 + p-locate@4.1.0: + dependencies: + p-limit: 2.3.0 + p-queue@9.3.5: dependencies: eventemitter3: 5.0.4 @@ -3157,8 +3731,25 @@ snapshots: p-timeout@7.0.2: {} + p-try@2.2.0: {} + package-manager-detector@1.9.0: {} + parse5-htmlparser2-tree-adapter@7.1.0: + dependencies: + domhandler: 5.0.3 + parse5: 7.3.0 + + parse5-parser-stream@7.1.2: + dependencies: + parse5: 7.3.0 + + parse5@7.3.0: + dependencies: + entities: 6.0.1 + + path-exists@4.0.0: {} + piccolore@0.1.3: {} picocolors@1.1.1: {} @@ -3167,6 +3758,10 @@ snapshots: picomatch@4.0.7: {} + pinyin-pro@3.29.5: {} + + pngjs@5.0.0: {} + postcss@8.5.32: dependencies: nanoid: 3.3.20 @@ -3179,6 +3774,12 @@ snapshots: property-information@7.2.0: {} + qrcode@1.5.4: + dependencies: + dijkstrajs: 1.0.3 + pngjs: 5.0.0 + yargs: 15.4.1 + radix3@1.1.2: {} range-parser@1.3.0: {} @@ -3229,6 +3830,10 @@ snapshots: dependencies: regex-utilities: 2.3.0 + require-directory@2.1.1: {} + + require-main-filename@2.0.0: {} + resolve-pkg-maps@1.0.0: {} retext-smartypants@6.2.0: @@ -3258,6 +3863,8 @@ snapshots: '@rolldown/binding-win32-arm64-msvc': 1.2.16 '@rolldown/binding-win32-x64-msvc': 1.2.16 + safer-buffer@2.1.2: {} + satteri@0.10.5: dependencies: '@types/estree-jsx': 1.0.5 @@ -3279,8 +3886,7 @@ snapshots: scheduler@0.28.0: {} - semver@7.8.5: - optional: true + semver@7.8.5: {} send@1.2.1: dependencies: @@ -3300,6 +3906,8 @@ snapshots: server-destroy@1.0.1: {} + set-blocking@2.0.0: {} + setprototypeof@1.2.0: {} sharp@0.35.5(@types/node@26.6.6): @@ -3334,7 +3942,6 @@ snapshots: '@img/sharp-win32-ia32': 0.35.5 '@img/sharp-win32-x64': 0.35.5 '@types/node': 26.6.6 - optional: true shiki@4.5.0: dependencies: @@ -3359,11 +3966,21 @@ snapshots: std-env@4.3.0: {} + string-width@4.2.3: + dependencies: + emoji-regex: 8.0.0 + is-fullwidth-code-point: 3.0.0 + strip-ansi: 6.0.1 + stringify-entities@4.0.4: dependencies: character-entities-html4: 2.1.0 character-entities-legacy: 3.0.0 + strip-ansi@6.0.1: + dependencies: + ansi-regex: 5.0.1 + svgo@4.1.0: dependencies: commander: 11.1.0 @@ -3401,6 +4018,14 @@ snapshots: tslib@2.8.1: {} + tsx@4.23.15: + dependencies: + esbuild: 0.28.2 + optionalDependencies: + fsevents: 2.3.3 + + typescript@6.0.3: {} + ufo@1.6.4: {} ultrahtml@1.7.0: {} @@ -3409,6 +4034,8 @@ snapshots: undici-types@8.9.0: {} + undici@7.30.1: {} + undici@8.12.3: {} unified@11.0.5: @@ -3489,7 +4116,7 @@ snapshots: '@types/unist': 3.0.3 vfile-message: 4.0.3 - vite@8.3.5(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.1): + vite@8.3.5(@types/node@26.6.6)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1): dependencies: lightningcss: 1.33.0 picomatch: 4.0.7 @@ -3498,20 +4125,57 @@ snapshots: tinyglobby: 0.2.17 optionalDependencies: '@types/node': 26.6.6 + esbuild: 0.28.2 fsevents: 2.3.3 jiti: 2.7.0 + tsx: 4.23.15 yaml: 2.9.1 - vitefu@1.1.3(vite@8.3.5(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.1)): + vitefu@1.1.3(vite@8.3.5(@types/node@26.6.6)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)): optionalDependencies: - vite: 8.3.5(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.1) + vite: 8.3.5(@types/node@26.6.6)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1) + + whatwg-encoding@3.1.1: + dependencies: + iconv-lite: 0.6.3 + + whatwg-mimetype@4.0.0: {} + + which-module@2.0.1: {} + + wrap-ansi@6.2.0: + dependencies: + ansi-styles: 4.3.0 + string-width: 4.2.3 + strip-ansi: 6.0.1 xxhash-wasm@1.1.0: {} + y18n@4.0.3: {} + yaml@2.9.1: {} + yargs-parser@18.1.3: + dependencies: + camelcase: 5.3.1 + decamelize: 1.2.0 + yargs-parser@22.0.0: {} + yargs@15.4.1: + dependencies: + cliui: 6.0.0 + decamelize: 1.2.0 + find-up: 4.1.0 + get-caller-file: 2.0.5 + require-directory: 2.1.1 + require-main-filename: 2.0.0 + set-blocking: 2.0.0 + string-width: 4.2.3 + which-module: 2.0.1 + y18n: 4.0.3 + yargs-parser: 18.1.3 + yocto-queue@1.2.2: {} zod@4.6.7: {} diff --git a/scripts/apply-hardware-catalog.mjs b/scripts/apply-hardware-catalog.mjs new file mode 100644 index 0000000..77d7eb9 --- /dev/null +++ b/scripts/apply-hardware-catalog.mjs @@ -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)); +} diff --git a/scripts/backup.mjs b/scripts/backup.mjs index 659778c..ad3db6e 100644 --- a/scripts/backup.mjs +++ b/scripts/backup.mjs @@ -1,6 +1,8 @@ import { DatabaseSync } from 'node:sqlite'; import { cpSync, existsSync, mkdirSync } from 'node:fs'; +if (existsSync('.env')) process.loadEnvFile('.env'); + const DB_PATH = process.env.DB_PATH ?? 'data/app.db'; const UPLOADS = process.env.UPLOADS_DIR ?? 'data/uploads'; diff --git a/scripts/seed-devices.json b/scripts/seed-devices.json new file mode 100644 index 0000000..836a765 --- /dev/null +++ b/scripts/seed-devices.json @@ -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" + } + ] + } +] diff --git a/scripts/seed.mjs b/scripts/seed.mjs index c668338..8a8f498 100644 --- a/scripts/seed.mjs +++ b/scripts/seed.mjs @@ -2,6 +2,8 @@ import { DatabaseSync } from 'node:sqlite'; import { existsSync, mkdirSync, readFileSync, readdirSync } from 'node:fs'; import { dirname, join } from 'node:path'; +if (existsSync('.env')) process.loadEnvFile('.env'); + const DB_PATH = process.env.DB_PATH ?? 'data/app.db'; const now = new Date().toISOString(); @@ -38,11 +40,14 @@ const soc = { }, { 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: '能效核', - 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: { @@ -52,6 +57,7 @@ const soc = { apis: ['Vulkan 1.3', 'OpenGL ES 3.2', 'OpenCL 2.0'], }, npuBlock: { name: 'Hexagon NPU', tops: '约 45 TOPS (INT8)' }, + systemCache: '6 MB', ispBlock: 'Spectra 18-bit', modemBlock: 'Snapdragon X75 5G', memorySupport: { type: 'LPDDR5X', maxClock: '4800 MHz', bandwidth: '76.8 GB/s' }, @@ -59,9 +65,12 @@ const soc = { displaySupport: '最高 4K@60Hz / QHD+@144Hz', videoCodec: { encode: ['H.264', 'H.265', 'AV1'], decode: ['H.264', 'H.265', 'AV1'] }, benchmarks: [ - { name: 'Geekbench 6 单核', score: '2200', unit: 'pts' }, - { name: 'Geekbench 6 多核', score: '6800', unit: 'pts' }, - { name: '安兔兔 V10', score: '2100000', unit: 'pts' }, + { name: 'Geekbench 5 单核', score: '1700', unit: 'pts' }, + { name: 'Geekbench 5 多核', score: '6600', 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: {}, }, @@ -90,51 +99,82 @@ const phone = { chipRefs: { soc: 'snapdragon-8-gen-3' }, specs: { body: { - dimensions: '152.8 x 71.5 x 8.2 mm', - weight: '188 g', - build: { front: '康宁大猩猩 Victus', back: '玻璃', frame: '铝合金' }, - sim: 'Nano-SIM + eSIM', + dimensions: '152.8 x 71.5 x 8.20 mm(玻璃)/ 8.28 mm(科技纳米皮)', + weight: '193 g(玻璃)/ 188 g(科技纳米皮)', + build: { front: '康宁大猩猩 Victus 2', back: '玻璃 / 科技纳米皮', frame: '铝合金边框' }, + sim: '2 × Nano-SIM', ipRating: 'IP68', colors: ['黑色', '白色', '岩石青', '雪山粉'], buttons: '右侧电源 + 音量', + cooling: '环形冷泵散热系统', }, display: { size: '6.36 英寸', resolution: '2670 x 1200', - aspectRatio: '20:9', - panel: 'LTPO AMOLED', - refreshRate: '120Hz', + cutout: '中孔', + aspectRatio: '20.0:9', + panel: 'OLED', + vendor: '华星光电(TCL 华星)', + technology: 'C8 发光材质', + refreshRate: '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', brightnessPeak: '3000 nit', - hdr: 'HDR10+ / Dolby Vision', - protection: '康宁大猩猩 Victus', + hdr: 'HDR10+ / HDR Vivid / Dolby Vision', + protection: '康宁大猩猩 Victus 2', pwmDimming: '1920Hz PWM', 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: { ram: '8 / 12 / 16 GB', - ramType: 'LPDDR5X', + ramType: 'LPDDR5X 8400 MT/s(4 × 16bit)', storage: '256 / 512 GB / 1TB', storageType: 'UFS 4.0', + storageSpeed: '约 4.2 GB/s 顺序读取', cardSlot: '无', }, rearCamera: [ { position: 'wide', sensorModel: 'OmniVision OV50H', - resolution: '50MP', + sensorAlias: '光影猎人 900', + resolution: '50MP(默认合 1 输出 1250 万像素)', aperture: 'f/1.6', focalLength: '23mm', sensorSize: '1/1.31"', pixelSize: '1.2µm', lensElements: '7P', ois: true, + eis: true, zoom: '1x', - autofocusType: '双像素 PDAF', - video: { max: '8K@24fps', modes: ['4K@60fps', '1080p@240fps 慢动作'], stabilization: 'OIS + EIS' }, + autofocusType: '全像素全向对焦 + 激光对焦', + video: { + max: '8K@24fps', + modes: ['4K@60fps HDR10+ 录像', '1080p@240fps 慢动作', '电影模式'], + stabilization: 'OIS + EIS', + }, + flash: '双色温 LED 闪光灯', extra: {}, }, { @@ -142,13 +182,13 @@ const phone = { sensorModel: 'Samsung S5KJN1', resolution: '50MP', aperture: 'f/2.0', - focalLength: '75mm', + focalLength: '75mm(60mm 裁切)', sensorSize: '1/2.76"', pixelSize: '0.64µm', lensElements: '6P', ois: true, - zoom: '3.2x 光学 / 60x 数码', - autofocusType: 'PDAF', + zoom: '2.6x 光学(60mm)/ 3.2x(75mm)', + autofocusType: 'PDAF + 10cm 以上自动对焦', extra: {}, }, { @@ -160,6 +200,7 @@ const phone = { sensorSize: '1/2.76"', pixelSize: '0.64µm', lensElements: '6P', + fov: '115°', ois: false, zoom: '0.6x', extra: {}, @@ -168,22 +209,23 @@ const phone = { frontCamera: [ { position: 'front', - sensorModel: 'OmniVision OV32C', + sensorModel: 'OmniVision OV32B', resolution: '32MP', aperture: 'f/2.0', focalLength: '22mm', sensorSize: '1/3.14"', - video: { max: '1080p@30fps', modes: [], stabilization: 'EIS' }, + pixelSize: '0.7µm', + video: { max: '4K@60fps', modes: [], stabilization: 'EIS' }, extra: {}, }, ], - vibration: { type: 'X 轴线性马达', model: 'AAC 0809', size: '0809' }, + vibration: { type: 'X 轴线性马达', model: '瑞声 0809B', size: '0809', volume: '约 1.0 cm³' }, speakers: { count: 2, stereo: true, units: [ - { model: 'AAC 1116', size: '11 x 16 mm' }, - { model: 'AAC 1012', size: '10 x 12 mm' }, + { position: 'top', label: '上', model: 'AAC 1115K', size: '11 × 15 mm' }, + { position: 'bottom', label: '下', model: 'AAC 1014', size: '10 × 14 mm' }, ], dolbyAtmos: true, hiRes: true, @@ -191,12 +233,17 @@ const phone = { headphoneJack: false, }, connectivity: { - cellular: '5G Sub-6 / mmWave', - wifi: 'Wi-Fi 7 (802.11be)', - bluetooth: '5.4, LDAC / LHDC 5.0', + cellular: '5G 双模双卡双通', + bands: ['n1', 'n3', 'n5', 'n8', 'n28a', 'n38', 'n41', 'n77', 'n78', 'B1', 'B3', 'B5', 'B8', 'B34', 'B38', 'B39', 'B40', 'B41'], + 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, - gps: 'L1 + L5 双频', - usb: 'USB 3.2 Gen 1 Type-C', + 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(双面椭圆口)', + usbSpeed: '5 Gbps', + usbVideoOut: true, ir: true, uwb: false, }, @@ -206,23 +253,76 @@ const phone = { wired: '90W', wireless: '50W', reverse: '10W', - chargingProtocol: '小米澎湃 P1 + G1', + chargingProtocol: 'QC4 / QC3+ / QC3.0 / QC2.0 / PD3.0 / PD2.0 / 小米 FC 2.0 快充', }, sensors: { - fingerprint: '屏下光学指纹', + fingerprint: '短焦屏下指纹识别', fingerprintType: '光学', fingerprintPosition: '屏下短焦', gyro: true, barometer: true, colorSensor: true, flickerSensor: true, + list: [ + '距离传感器', + '屏下环境光(色温)传感器', + '后置环境光(色温)传感器', + '加速度传感器', + '陀螺仪', + '电子罗盘', + '红外线遥控器', + 'flicker 传感器', + '激光对焦传感器', + '气压计', + 'NFC', + ], }, software: { - launchVersion: 'Android 14 / HyperOS 1.0', - currentVersion: 'Android 14 / HyperOS 1.0', + launchVersion: 'Xiaomi HyperOS', + currentVersion: 'Android 15 / HyperOS 2.0', 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: [ { @@ -238,6 +338,19 @@ const phone = { verified: false, 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,24 +363,28 @@ const deviceCols = [ 'created_at', 'updated_at', ]; -const deviceValues = [ - phone.slug, phone.category, null, phone.brand, phone.model, - JSON.stringify(phone.aliases), phone.announceDate ?? null, phone.releaseDate ?? null, - phone.lifecycle, null, JSON.stringify(phone.gallery ?? []), - JSON.stringify(phone.tags ?? []), phone.summary ?? null, JSON.stringify(phone.specs), - JSON.stringify(phone.chipRefs ?? {}), JSON.stringify(phone.meta ?? []), now, now, -]; +const seedDevices = [phone, ...JSON.parse(readFileSync('scripts/seed-devices.json', 'utf8'))]; -db.prepare( - `INSERT INTO devices (${deviceCols.join(', ')}) VALUES (${deviceCols.map(() => '?').join(', ')}) - ON CONFLICT(slug) DO UPDATE SET - category = excluded.category, brand = excluded.brand, model = excluded.model, - aliases_json = excluded.aliases_json, announce_date = excluded.announce_date, - release_date = excluded.release_date, lifecycle = excluded.lifecycle, - tags_json = excluded.tags_json, summary = excluded.summary, - specs_json = excluded.specs_json, chip_refs_json = excluded.chip_refs_json, - meta_json = excluded.meta_json, updated_at = excluded.updated_at`, -).run(...deviceValues); +for (const device of seedDevices) { + const deviceValues = [ + device.slug, device.category, device.subCategory ?? null, device.brand, device.model, + JSON.stringify(device.aliases ?? []), device.announceDate ?? null, device.releaseDate ?? null, + device.lifecycle, device.cover ?? null, JSON.stringify(device.gallery ?? []), + JSON.stringify(device.tags ?? []), device.summary ?? null, JSON.stringify(device.specs), + JSON.stringify(device.chipRefs ?? {}), JSON.stringify(device.meta ?? []), now, now, + ]; + + db.prepare( + `INSERT INTO devices (${deviceCols.join(', ')}) VALUES (${deviceCols.map(() => '?').join(', ')}) + ON CONFLICT(slug) DO UPDATE SET + category = excluded.category, brand = excluded.brand, model = excluded.model, + aliases_json = excluded.aliases_json, announce_date = excluded.announce_date, + release_date = excluded.release_date, lifecycle = excluded.lifecycle, + tags_json = excluded.tags_json, summary = excluded.summary, + specs_json = excluded.specs_json, chip_refs_json = excluded.chip_refs_json, + meta_json = excluded.meta_json, updated_at = excluded.updated_at`, + ).run(...deviceValues); +} const chipCols = [ 'slug', 'type', 'brand', 'model', 'codename', 'aliases_json', @@ -288,5 +405,5 @@ db.prepare( 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(); diff --git a/scripts/sync-coolapk.mjs b/scripts/sync-coolapk.mjs new file mode 100644 index 0000000..85431b9 --- /dev/null +++ b/scripts/sync-coolapk.mjs @@ -0,0 +1,1687 @@ +/** + * 用酷安产品库补充 / 覆盖本项目的手机参数。 + * + * 流程: + * 1. 拉取酷安机型目录并按品牌 + 型号匹配本地设备; + * 2. 查询每个产品的版本与配置 ID,取基础版本; + * 3. 每 4 个配置请求一次配置对比页,解析完整参数表; + * 4. 按信息度合并酷安参数覆盖本地数据,本地缺失的机型自动创建; + * 5. 只保留酷安评分与同步时间,原始参数表不再入库。 + * + * 示例: + * pnpm sync:coolapk + * pnpm sync:coolapk -- --write + * pnpm sync:coolapk -- --limit 10 --write + */ +import { existsSync } from 'node:fs'; +import { mkdir, readFile, writeFile } from 'node:fs/promises'; +import { dirname } from 'node:path'; +import * as cheerio from 'cheerio'; +import { pinyin } from 'pinyin-pro'; +import { deviceSchema } from '../src/lib/schema'; +import { importEntities, listDevices } from '../src/lib/repo'; + +const BASE = 'https://m.coolapk.com'; +const HEADERS = { + 'User-Agent': + 'Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Mobile Safari/537.36', + Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', + Referer: `${BASE}/mp/productSelector/configSearch?callFunction=addProduct&drawNav=1&isHidden=0`, +}; +const CATALOG_CACHE = 'data/cache/coolapk-products.json'; + +const BRAND_ALIASES = { + Xiaomi: ['小米', 'xiaomi'], + Redmi: ['redmi', '红米'], + Huawei: ['华为', 'huawei'], + Honor: ['荣耀', 'honor'], + OPPO: ['oppo'], + vivo: ['vivo'], + iQOO: ['iqoo'], + OnePlus: ['一加', 'oneplus'], + realme: ['真我', 'realme'], + nubia: ['努比亚', 'nubia', '红魔'], + ZTE: ['中兴', 'zte'], + Samsung: ['三星', 'samsung'], + Apple: ['apple', '苹果'], + Meizu: ['魅族', 'meizu', '魅蓝'], + Motorola: ['moto', 'motorola', '摩托罗拉'], + ROG: ['rog', '玩家国度'], + 'NIO Phone': ['蔚来', 'nio'], + 'Lenovo Legion': ['联想拯救者', '拯救者手机', '拯救者', 'lenovo'], + Maimang: ['麦芒'], + WIKO: ['wiko'], + 'Moondrop MIAD': ['水月雨', 'moondrop'], + Philips: ['飞利浦', 'philips'], + Gionee: ['金立', 'gionee'], + Coolpad: ['酷派', 'coolpad'], + Sony: ['索尼', 'sony'], + Nothing: ['nothing'], + POCO: ['poco'], + Google: ['谷歌', 'google', 'nexus'], + BlackShark: ['黑鲨', 'blackshark'], + Smartisan: ['坚果', 'smartisan', '锤子'], + Nokia: ['诺基亚', 'nokia'], + Lenovo: ['联想', 'lenovo'], + BlackBerry: ['黑莓', 'blackberry'], + Sharp: ['夏普', 'sharp'], + Meitu: ['美图', 'meitu'], + Hisense: ['海信', 'hisense'], + RayNeo: ['雷鸟', 'rayneo'], + Royole: ['柔宇', 'royole'], + ASUS: ['华硕', 'asus'], + TCL: ['tcl'], + Unihertz: ['unihertz'], + AGM: ['agm'], + CMF: ['cmf', 'nothing'], + Qin: ['多亲', 'qin'], + Tianyi: ['天翼', 'tianyi'], + BlueFox: ['蓝狐', 'bluefox'], + STEPX: ['stepx'], + Essential: ['essential'], + LG: ['lg'], + HTC: ['htc'], + ZUK: ['zuk'], + '360': ['360'], +}; + +/** 新机型:从酷安产品名推断品牌与型号 */ +const PRODUCT_PREFIXES = [ + ['腾讯红魔', 'nubia', false], + ['红魔', 'nubia', false], + ['努比亚', 'nubia', true], + ['联想拯救者', 'Lenovo Legion', true], + ['拯救者电竞手机', 'Lenovo Legion', true], + ['拯救者手机', 'Lenovo Legion', true], + ['Redmi', 'Redmi', true], + ['红米', 'Redmi', true], + ['小米', 'Xiaomi', true], + ['华为', 'Huawei', true], + ['荣耀', 'Honor', true], + ['OPPO', 'OPPO', true], + ['vivo', 'vivo', true], + ['iQOO', 'iQOO', true], + ['一加', 'OnePlus', true], + ['真我', 'realme', true], + ['realme', 'realme', true], + ['中兴', 'ZTE', true], + ['ZTE', 'ZTE', true], + ['三星', 'Samsung', true], + ['iPhone', 'Apple', false], + ['苹果', 'Apple', true], + ['魅族', 'Meizu', true], + ['魅蓝', 'Meizu', true], + ['moto', 'Motorola', true], + ['摩托罗拉', 'Motorola', true], + ['ROG', 'ROG', true], + ['蔚来', 'NIO Phone', true], + ['NIO', 'NIO Phone', true], + ['麦芒', 'Maimang', true], + ['WIKO', 'WIKO', true], + ['水月雨', 'Moondrop MIAD', true], + ['飞利浦', 'Philips', true], + ['金立', 'Gionee', true], + ['酷派', 'Coolpad', true], + ['索尼', 'Sony', true], + ['Nothing', 'Nothing', true], + ['多亲', 'Qin', true], + ['谷歌', 'Google', true], + ['Google', 'Google', true], + ['黑鲨', 'BlackShark', true], + ['坚果', 'Smartisan', true], + ['诺基亚', 'Nokia', true], + ['LG', 'LG', true], + ['HTC', 'HTC', true], + ['ZUK', 'ZUK', true], + ['360', '360', true], + ['POCO', 'POCO', true], + ['Unihertz', 'Unihertz', true], + ['AGM', 'AGM', true], + ['CMF', 'CMF', true], + ['美图', 'Meitu', true], + ['海信', 'Hisense', true], + ['雷鸟', 'RayNeo', true], + ['柔宇', 'Royole', true], + ['TCL', 'TCL', true], + ['华硕', 'ASUS', true], + ['蓝狐', 'BlueFox', true], + ['天翼', 'Tianyi', true], + ['STEPX', 'STEPX', true], + ['联想', 'Lenovo', true], + ['黑莓', 'BlackBerry', true], + ['夏普', 'Sharp', true], + ['Galaxy', 'Samsung', false], + ['Nexus', 'Google', false], + ['Nokia', 'Nokia', false], + ['畅享', 'Huawei', false], + ['Essential', 'Essential', false], +]; + +function inferIdentity(name) { + const text = clean(name); + for (const [prefix, brand, strip] of PRODUCT_PREFIXES) { + if (text.toLowerCase().startsWith(prefix.toLowerCase())) { + const model = strip ? text.slice(prefix.length).trim() : text; + if (model) return { brand, model }; + } + } + return { brand: 'Other', model: text }; +} + +function slugify(value) { + const syllables = pinyin(value, { toneType: 'none', type: 'array', nonZh: 'consecutive' }); + return syllables + .join('-') + .toLowerCase() + .replace(/\+/g, '-plus') + .replace(/&/g, '-and') + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, '') + .replace(/-{2,}/g, '-'); +} + +function makeBlankSpecs() { + return { + body: {}, + display: {}, + platform: {}, + memory: {}, + rearCamera: [], + frontCamera: [], + vibration: {}, + speakers: { units: [] }, + connectivity: { bands: [], satelliteBands: [] }, + battery: {}, + sensors: { list: [] }, + software: { updateTimeline: [] }, + features: [], + cameraFeatures: [], + benchmarks: [], + pricing: [], + extra: {}, + }; +} + +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + +function clean(value) { + if (typeof value === 'string') return value.replace(/\u00a0/g, ' ').replace(/\s+/g, ' ').trim(); + if (typeof value === 'number') return String(value); + return ''; +} + +function lines(value) { + return String(value ?? '') + .replace(/\u00a0/g, ' ') + .split(/\n+/) + .map((line) => line.replace(/\s+/g, ' ').trim()) + .filter((line) => line && line !== '-'); +} + +function firstLine(value) { + return lines(value)[0] ?? ''; +} + +/** 第一行有效文本;'-' / 空白返回 undefined,避免覆盖成空值 */ +function line(value) { + return firstLine(value) || undefined; +} + +/** 多行文本用分号连接 */ +function semicolon(value) { + const valueLines = lines(value); + return valueLines.length > 0 ? valueLines.join(';') : undefined; +} + +function unique(values) { + return [...new Set(values.map(clean).filter(Boolean))]; +} + +function normalize(value) { + return String(value ?? '') + .toLowerCase() + .replace(/[®™©]/g, '') + .replace(/+/g, '+') + .replace(/[\s\-_/·,,.。()()[\]【】::]/g, ''); +} + +function splitList(value) { + return unique(String(value ?? '').split(/[,,、;;||]/)).filter((item) => item !== '-'); +} + +function numericTokens(value) { + return String(value ?? '').match(/\d+(?:\.\d+)?/g) ?? []; +} + +function infoScore(value) { + const text = clean(value); + if (!text) return 0; + const numbers = numericTokens(text).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 numericConflict(a, b) { + const left = new Set(numericTokens(a)); + const right = new Set(numericTokens(b)); + if (left.size === 0 || right.size === 0) return false; + const leftInRight = [...left].every((value) => right.has(value)); + const rightInLeft = [...right].every((value) => left.has(value)); + return !(leftInRight || rightInLeft); +} + +/** + * 合并文本:酷安为准,但不让低信息度内容覆盖高信息度内容; + * 若两边数值明显冲突,则视为不一致,采用酷安值。 + */ +function pickText(existing, incoming) { + if (!incoming) return existing; + if (!existing) return incoming; + if (clean(existing).toLowerCase() === clean(incoming).toLowerCase()) return existing; + const oldScore = infoScore(existing); + const newScore = infoScore(incoming); + if (newScore >= oldScore) return incoming; + if (numericConflict(existing, incoming)) return incoming; + return existing; +} + +function pickList(existing, incoming, options = {}) { + const oldList = existing ?? []; + const newList = incoming ?? []; + if (newList.length === 0) return oldList; + if (oldList.length === 0) return newList; + if (newList.length >= oldList.length) return newList; + if (options.union) return unique([...newList, ...oldList]); + return oldList; +} + +function pickResolution(existing, incoming) { + if (!incoming) return existing; + if (!existing) return incoming; + const newHasPixels = /\d+\s*[x×*]\s*\d+/i.test(incoming); + const oldHasPixels = /\d+\s*[x×*]\s*\d+/i.test(existing); + if (newHasPixels && !oldHasPixels) return incoming; + if (!newHasPixels && oldHasPixels) return existing; + return pickText(existing, incoming); +} + +function resolutionMegapixels(value) { + const match = String(value ?? '').match(/(\d+(?:\.\d+)?)\s*(亿|万)?像素/); + if (!match) return undefined; + const number = Number(match[1]); + return match[2] === '亿' ? number * 10000 : number; +} + +function pickResolutionField(existing, incoming) { + if (!incoming) return existing; + if (!existing) return incoming; + const oldScore = resolutionMegapixels(existing); + const newScore = resolutionMegapixels(incoming); + if (oldScore !== undefined && newScore !== undefined) return newScore >= oldScore ? incoming : existing; + return pickText(existing, incoming); +} + +function pickFocal(existing, incoming) { + if (!incoming) return existing; + if (!existing) return incoming; + const oldNumber = Number(numericTokens(existing)[0]); + const newNumber = Number(numericTokens(incoming)[0]); + if (Number.isFinite(oldNumber) && Number.isFinite(newNumber)) { + return Math.abs(oldNumber - newNumber) <= 1 ? existing : incoming; + } + return pickText(existing, incoming); +} + +function pickSensor(existing, incoming) { + if (!incoming) return existing; + if (!existing) return incoming; + const trim = (value) => clean(value).replace(/[、,,;;\s]+$/g, ''); + if (trim(existing) === trim(incoming)) return trim(incoming); + const score = (value) => { + const text = clean(value); + let total = Math.min(text.length, 20) / 10; + if (/思特威|索尼|三星|豪威|格科微|SK|OV|IMX|SC\d|HP\d|JN\d|LYT|HPE|HPC/i.test(text)) total += 6; + if (/^(RYYB|传感器|未知|主摄|镜头|CMOS)/i.test(text)) total -= 4; + return total; + }; + return score(incoming) >= score(existing) ? incoming : existing; +} + +function pickVideo(existing, incoming) { + if (!incoming) return existing; + if (!existing) return incoming; + const score = (value) => { + const text = String(value ?? '').toUpperCase(); + const resolution = text.includes('8K') ? 3 : text.includes('4K') ? 2 : text.includes('1080') ? 1 : 0; + const fps = Number((text.match(/(\d+)\s*FPS/) ?? [])[1] ?? 0); + return resolution * 1000 + fps; + }; + return score(incoming) >= score(existing) ? incoming : existing; +} + +function toNit(value) { + const match = clean(value).match(/(\d+(?:\.\d+)?)\s*(?:nits?|尼特)/i); + return match ? `${match[1]} nit` : undefined; +} + +function measure(value) { + const match = clean(value).match(/(\d+(?:\.\d+)?)\s*(mm|毫米|g|克|寸|英寸)/i); + if (!match) return undefined; + const unit = match[2].toLowerCase(); + return `${match[1]}${unit === '毫米' ? 'mm' : unit === '克' ? 'g' : unit === '英寸' ? '英寸' : unit}`; +} + +/** 保留「(玻璃蓝/透明)」这类版本说明,同时补全省略的单位 */ +function measureVariant(value, fallbackUnit) { + const text = clean(value); + const match = text.match(/(\d+(?:\.\d+)?)\s*(mm|毫米|g|克)?(.*)$/i); + if (!match) return text; + const unit = match[2] + ? match[2].toLowerCase() === '毫米' + ? 'mm' + : match[2].toLowerCase() === '克' + ? 'g' + : match[2] + : fallbackUnit; + return `${match[1]}${unit}${match[3] ?? ''}`.trim(); +} + +async function request(url, attempt = 1, ajax = false) { + try { + await sleep(120); + const response = await fetch(url, { + headers: ajax ? { ...HEADERS, 'X-Requested-With': 'XMLHttpRequest' } : HEADERS, + signal: AbortSignal.timeout(25000), + }); + if (!response.ok) { + const error = new Error(`HTTP ${response.status}`); + error.status = response.status; + throw error; + } + return await response.text(); + } catch (error) { + if (attempt >= 5) throw error; + const limited = error?.status === 429 || error?.status === 403; + await sleep((limited ? 1500 : 500) * attempt); + return request(url, attempt + 1, ajax); + } +} + +function parseProductList(html) { + const $ = cheerio.load(html); + const items = []; + $('.phone-item[data-product-id]').each((_, element) => { + const $item = $(element); + const id = clean($item.attr('data-product-id')); + const name = clean($item.find('.phone-name').first().text()); + if (id && name) items.push({ id, name }); + }); + return items; +} + +async function fetchCatalog(refresh) { + if (!refresh && existsSync(CATALOG_CACHE)) { + try { + const cached = JSON.parse(await readFile(CATALOG_CACHE, 'utf8')); + if (Array.isArray(cached.items) && cached.items.length > 0) { + console.log(`使用机型目录缓存(${cached.items.length} 款)`); + return cached.items; + } + } catch {} + } + + const items = []; + const seen = new Set(); + for (let page = 1; page <= 120; page += 1) { + const html = await request( + `${BASE}/mp/productSelector/configSearch?callFunction=addProduct&drawNav=1&isHidden=0&page=${page}`, + ); + const pageItems = parseProductList(html); + if (pageItems.length === 0) break; + for (const item of pageItems) { + if (seen.has(item.id)) continue; + seen.add(item.id); + items.push(item); + } + if (page % 10 === 0) console.log(` 机型目录 ${page} 页,累计 ${items.length} 款`); + } + + await mkdir(dirname(CATALOG_CACHE), { recursive: true }); + await writeFile( + CATALOG_CACHE, + `${JSON.stringify({ fetchedAt: new Date().toISOString(), items }, null, 2)}\n`, + 'utf8', + ); + console.log(`机型目录已缓存:${items.length} 款`); + return items; +} + +function matchProducts(devices, products) { + const byName = new Map(); + for (const product of products) { + const key = normalize(product.name); + if (!byName.has(key)) byName.set(key, []); + byName.get(key).push(product); + } + + const matches = []; + const misses = []; + for (const device of devices) { + const aliases = BRAND_ALIASES[device.brand] ?? []; + const model = device.model.trim(); + const candidates = []; + for (const alias of aliases) { + if (model.toLowerCase().startsWith(alias.toLowerCase())) { + const rest = model.slice(alias.length).trim(); + if (rest) candidates.push(`${alias}${rest}`, rest); + } else { + candidates.push(`${alias}${model}`); + } + } + candidates.push(model); + + let product; + for (const candidate of candidates) { + const found = byName.get(normalize(candidate)); + if (!found) continue; + if (found.length > 1 && candidate === model) continue; + product = found[0]; + break; + } + if (product) matches.push({ device, product, name: product.name }); + else misses.push(device); + } + return { matches, misses }; +} + +/** 酷安目录偶尔有同名重复机型,保留较新的产品 ID,避免重复建页 */ +function dedupeProducts(products) { + const byName = new Map(); + for (const product of products) { + const key = normalize(product.name); + const current = byName.get(key); + if (!current || Number(product.id) > Number(current.id)) byName.set(key, product); + } + return [...byName.values()]; +} + +async function fetchVersions(product) { + const text = await request( + `${BASE}/mp/productSelector/getProductVersion?callFunction=addProduct&productId=${product.id}`, + 1, + true, + ); + let json; + try { + json = JSON.parse(text); + } catch { + return { product, versions: [] }; + } + if (!json.data) return { product, versions: [] }; + + const $ = cheerio.load(json.data); + const versions = []; + $('.version-item').each((_, element) => { + const info = clean($(element).find('.version-info').text()); + const configId = clean($(element).find('[data-config-id]').attr('data-config-id')); + if (!configId) return; + const match = info.match(/(.+?)\s*[¥¥]\s*(\d+)/); + versions.push({ + configId, + name: match ? match[1].trim() : info, + price: match ? match[2] : undefined, + }); + }); + return { product, versions }; +} + +function parseValue(element, $) { + const $value = $(element).clone(); + $value.find('br').replaceWith('\n'); + const text = $value.text().replace(/\u00a0/g, ' '); + return text + .split('\n') + .map((line) => line.replace(/\s+/g, ' ').trim()) + .filter(Boolean) + .join('\n'); +} + +function parseComparePage(html) { + const $ = cheerio.load(html); + const products = []; + $('.products-row .product-card[data-config_id]').each((_, element) => { + const $card = $(element); + const configId = clean($card.attr('data-config_id')); + if (!configId) return; + products.push({ + configId, + name: + clean($card.find('.product-name').attr('data-original_title')) || + clean($card.find('.product-name').text()), + price: clean($card.find('.price-value').text()), + }); + }); + + const groups = []; + $('.specs-section').each((_, section) => { + const $section = $(section); + const groupName = clean($section.children('.section-title').find('.col-text').text()); + if (!groupName) return; + const rows = []; + let subgroup = ''; + $section.children('.section-title-small, .specs-row').each((__, node) => { + const $node = $(node); + if ($node.hasClass('section-title-small')) { + subgroup = clean($node.find('.col-text').text()); + return; + } + const label = clean($node.find('.fixed-column .spec-label').first().text()); + if (!label) return; + const values = []; + $node.find('.column.flex-column').each((___, column) => { + values.push(parseValue($(column).find('.spec-value').first(), $)); + }); + rows.push({ subgroup: subgroup || undefined, label, values }); + }); + groups.push({ name: groupName, rows }); + }); + return { products, groups }; +} + +async function fetchCompare(configIds) { + const html = await request( + `${BASE}/mp/productSelector/configCompare?share_key=${configIds.join(',')}`, + ); + return parseComparePage(html); +} + +function rowsOf(groups, groupName) { + return groups + .filter((group) => group.name === groupName) + .flatMap((group) => group.rows.map((row) => ({ ...row, groupName }))); +} + +function makeLookup(groupRows) { + return (label, subgroup) => { + const found = groupRows.find( + (row) => + row.label === label && (subgroup === undefined || row.subgroup === subgroup), + ); + return found?.value; + }; +} + +function mergeCamera(list, module, used) { + const index = list.findIndex( + (item, itemIndex) => item.position === module.position && !used.has(itemIndex), + ); + if (index >= 0) { + const current = list[index]; + list[index] = { + ...current, + ...(module.sensorModel + ? { sensorModel: pickSensor(current.sensorModel, module.sensorModel) } + : {}), + ...(module.sensorSize ? { sensorSize: pickText(current.sensorSize, module.sensorSize) } : {}), + ...(module.resolution + ? { resolution: pickResolutionField(current.resolution, module.resolution) } + : {}), + ...(module.aperture ? { aperture: pickText(current.aperture, module.aperture) } : {}), + ...(module.lensElements ? { lensElements: pickText(current.lensElements, module.lensElements) } : {}), + ...(module.pixelSize ? { pixelSize: pickText(current.pixelSize, module.pixelSize) } : {}), + ...(module.zoom ? { zoom: pickText(current.zoom, module.zoom) } : {}), + ...(module.focalLength ? { focalLength: pickFocal(current.focalLength, module.focalLength) } : {}), + ...(module.fov ? { fov: pickText(current.fov, module.fov) } : {}), + ...(module.ois ? { ois: true } : {}), + ...(module.eis ? { eis: true } : {}), + ...(module.cipa ? { cipa: pickText(current.cipa, module.cipa) } : {}), + ...(module.telephotoStructure + ? { telephotoStructure: pickText(current.telephotoStructure, module.telephotoStructure) } + : {}), + ...(module.telephotoMacro !== undefined + ? { telephotoMacro: current.telephotoMacro ?? module.telephotoMacro } + : {}), + ...(module.telephotoMacroDistance + ? { telephotoMacroDistance: pickText(current.telephotoMacroDistance, module.telephotoMacroDistance) } + : {}), + ...(module.autofocusType + ? { autofocusType: pickText(current.autofocusType, module.autofocusType) } + : {}), + }; + used.add(index); + return list; + } + list.push(module); + used.add(list.length - 1); + return list; +} + +function applyCoolapk(device, payload) { + const specs = device.specs; + const { groups, product, configId, price } = payload; + + const body = (specs.body ??= {}); + const display = (specs.display ??= {}); + const platform = (specs.platform ??= {}); + const memory = (specs.memory ??= {}); + const battery = (specs.battery ??= {}); + const connectivity = (specs.connectivity ??= {}); + const sensors = (specs.sensors ??= {}); + const software = (specs.software ??= {}); + + const basic = rowsOf(groups, '基本信息'); + const appearance = rowsOf(groups, '外观'); + const screen = rowsOf(groups, '屏幕'); + const performance = rowsOf(groups, '性能'); + const network = rowsOf(groups, '网络与连接'); + const charging = rowsOf(groups, '充电与电池'); + const other = rowsOf(groups, '其他配置'); + const cameraRows = rowsOf(groups, '影像'); + const cameraSummary = rowsOf(groups, '重要参数'); + const accessories = rowsOf(groups, '手机附件'); + const secondary = rowsOf(groups, '副屏'); + const afterSales = rowsOf(groups, '售后信息'); + + const fromBasic = makeLookup(basic); + const fromAppearance = makeLookup(appearance); + const fromScreen = makeLookup(screen); + const fromPerformance = makeLookup(performance); + const fromNetwork = makeLookup(network); + const fromCharging = makeLookup(charging); + const fromOther = makeLookup(other); + const fromCamera = makeLookup(cameraRows); + const fromSummary = makeLookup(cameraSummary); + const fromAccessories = makeLookup(accessories); + const fromSecondary = makeLookup(secondary); + const fromAfterSales = makeLookup(afterSales); + + const length = measure(fromAppearance('长度')); + const width = measure(fromAppearance('宽度')); + const thicknessLines = lines(fromAppearance('厚度')); + const thickness = measure(thicknessLines[0]); + if (length && width && thickness) { + body.dimensions = pickText( + body.dimensions, + `${length.replace(/mm$/, '')} x ${width.replace(/mm$/, '')} x ${thickness.replace(/mm$/, '')} mm`, + ); + } + const thicknessVariants = thicknessLines.slice(1).map((item) => measureVariant(item, 'mm')); + if (thicknessVariants.length > 0) { + body.thicknessVariants = pickList(body.thicknessVariants, thicknessVariants, { union: true }); + } + const weightLines = lines(fromAppearance('重量')); + const weight = measure(weightLines[0]); + if (weight) body.weight = pickText(body.weight, weight); + const weightVariants = weightLines.slice(1).map((item) => measureVariant(item, 'g')); + if (weightVariants.length > 0) { + body.weightVariants = pickList(body.weightVariants, weightVariants, { union: true }); + } + const buttons = semicolon(fromAppearance('按键')); + if (buttons) body.buttons = pickText(body.buttons, buttons); + + const colors = lines(fromAppearance('机身颜色') ?? ''); + if (colors.length > 0) { + const nextColors = pickList(body.colors, colors); + if (nextColors === colors) { + body.colors = colors; + body.colorHexes = []; + } + } + const frontMaterial = semicolon(fromAppearance('正面材质') ?? fromAppearance('屏幕盖板')); + const frame = semicolon(fromAppearance('中框材质')); + const back = semicolon(fromAppearance('背壳材质')); + if (frontMaterial || frame || back) { + body.build = { + ...(body.build ?? {}), + ...(frontMaterial ? { front: pickText(body.build?.front, frontMaterial) } : {}), + ...(frame ? { frame: pickText(body.build?.frame, frame) } : {}), + ...(back ? { back: pickText(body.build?.back, back) } : {}), + }; + } + const ipRating = line(fromOther('三防功能') ?? fromSummary('三防功能')); + if (ipRating) body.ipRating = pickText(body.ipRating, ipRating); + + const sim = line(fromNetwork('SIM卡类型')); + if (sim) body.sim = pickText(body.sim, sim); + + const size = line(fromScreen('屏幕尺寸')); + if (size) display.size = pickText(display.size, size); + const resolutionLines = lines(fromScreen('屏幕分辨率')); + if (resolutionLines.length > 0) { + display.resolution = pickResolution(display.resolution, resolutionLines[0]); + // 酷安常把 PPI 放在分辨率第二行,例如「2772x1280px / 447 PPI」 + const ppi = resolutionLines.find((item) => /PPI/i.test(item)); + if (ppi) display.pixelDensity = pickText(display.pixelDensity, ppi); + } + const panelLines = lines(fromScreen('屏幕材质')); + if (panelLines.length > 0) { + display.panel = pickText(display.panel, panelLines[0]); + if (panelLines.length > 1) { + display.features = pickList(display.features, panelLines.slice(1), { union: true }); + } + } + const vendor = line(fromScreen('屏幕厂商')); + if (vendor) display.vendor = pickText(display.vendor, vendor); + const technology = line(fromScreen('屏幕发光材质')); + if (technology) display.technology = pickText(display.technology, technology); + const cutout = line(fromScreen('屏幕形态')); + if (cutout) display.cutout = pickText(display.cutout, cutout); + const refreshLines = lines(fromScreen('屏幕刷新率')); + if (refreshLines.length > 0) { + display.refreshRate = pickText(display.refreshRate, refreshLines[0]); + // 第二行常是 LTPO / LTPS 等背板说明 + const refreshNote = refreshLines.slice(1).join(';'); + if (refreshNote) display.refreshNote = pickText(display.refreshNote, refreshNote); + } + const pixelDensity = line(fromScreen('像素密度')); + if (pixelDensity) display.pixelDensity = pickText(display.pixelDensity, pixelDensity); + const touch = semicolon(fromScreen('触控采样率')); + if (touch) display.touchSampling = pickText(display.touchSampling, touch); + const instant = semicolon(fromScreen('瞬时触控采样率')); + if (instant) display.touchSamplingInstant = pickText(display.touchSamplingInstant, instant); + const colorDepth = line(fromScreen('屏幕色深')); + if (colorDepth) display.colorDepth = pickText(display.colorDepth, colorDepth); + const colorGamut = line(fromScreen('屏幕色域')); + if (colorGamut) display.colorGamut = pickText(display.colorGamut, colorGamut); + const hdr = semicolon(fromScreen('HDR支持')); + if (hdr) display.hdr = pickText(display.hdr, hdr); + const protection = line(fromScreen('盖板玻璃')); + if (protection) display.protection = pickText(display.protection, protection); + const dimming = line(fromScreen('屏幕调光')); + if (dimming) display.pwmDimming = pickText(display.pwmDimming, dimming); + const extraTech = fromScreen('其他技术'); + if (extraTech) { + const techValues = lines(extraTech); + if (techValues.length > 0) { + display.features = pickList(display.features, techValues, { union: true }); + } + } + const aspectRatio = line(fromScreen('屏幕比例') ?? fromScreen('宽高比')); + if (aspectRatio) display.aspectRatio = pickText(display.aspectRatio, aspectRatio); + const screenBodyRatio = line(fromScreen('屏占比')); + if (screenBodyRatio) display.screenBodyRatio = pickText(display.screenBodyRatio, screenBodyRatio); + const bezel = line(fromScreen('边框') ?? fromScreen('边框宽度')); + if (bezel) display.bezel = pickText(display.bezel, bezel); + const width16x9 = line(fromScreen('16:9等效宽度') ?? fromScreen('16:9等效尺寸')); + if (width16x9) display.width16x9 = pickText(display.width16x9, width16x9); + const equivalentPpi = line(fromScreen('等效PPI') ?? fromScreen('等效像素密度')); + if (equivalentPpi) display.equivalentPpi = pickText(display.equivalentPpi, equivalentPpi); + const refreshRange = line(fromScreen('刷新范围') ?? fromScreen('刷新率范围')); + if (refreshRange) display.refreshRange = pickText(display.refreshRange, refreshRange); + const refreshRangeFromRate = lines(fromScreen('屏幕刷新率')) + .join(';') + .match(/(\d+\s*-\s*\d+\s*Hz)/i)?.[1]; + if (refreshRangeFromRate) display.refreshRange = pickText(display.refreshRange, refreshRangeFromRate); + const alwaysOn = fromScreen('息屏显示'); + if (alwaysOn) { + if (/支持|是/.test(alwaysOn) && !/不支持/.test(alwaysOn)) display.alwaysOn = true; + else if (/不支持|否/.test(alwaysOn)) display.alwaysOn = false; + } + + for (const row of screen) { + if (!/亮度/.test(row.label)) continue; + // 同一行可能有多档亮度,例如「8000nits / 全屏峰值亮度2600nits、手动峰值亮度1000nit」 + for (const segment of lines(row.value).flatMap((item) => item.split(/[、,,;;]/))) { + const nit = toNit(segment); + if (!nit) continue; + const context = `${row.label} ${segment}`; + if (/全屏|全局/.test(context)) display.brightnessGlobalPeak = pickText(display.brightnessGlobalPeak, nit); + else if (/典型|默认|手动/.test(context)) display.brightnessTypical = pickText(display.brightnessTypical, nit); + else if (/HDR|峰值|最高|激发/.test(context)) display.brightnessPeak = pickText(display.brightnessPeak, nit); + } + } + + if (secondary.length > 0) { + const target = { ...(display.secondary ?? {}) }; + const secondarySize = line(fromSecondary('屏幕尺寸')); + if (secondarySize) target.size = pickText(target.size, secondarySize); + const secondaryResolutionLines = lines(fromSecondary('屏幕分辨率')); + if (secondaryResolutionLines.length > 0) { + target.resolution = pickResolution(target.resolution, secondaryResolutionLines[0]); + const ppi = secondaryResolutionLines.find((item) => /PPI/i.test(item)); + if (ppi) target.pixelDensity = pickText(target.pixelDensity, ppi); + } + const secondaryPanelLines = lines(fromSecondary('屏幕材质')); + if (secondaryPanelLines.length > 0) { + target.panel = pickText(target.panel, secondaryPanelLines[0]); + if (secondaryPanelLines.length > 1) { + target.features = pickList(target.features, secondaryPanelLines.slice(1), { union: true }); + } + } + const secondaryVendor = line(fromSecondary('屏幕厂商')); + if (secondaryVendor) target.vendor = pickText(target.vendor, secondaryVendor); + const secondaryTechnology = line(fromSecondary('屏幕发光材质')); + if (secondaryTechnology) target.technology = pickText(target.technology, secondaryTechnology); + const secondaryCutout = line(fromSecondary('屏幕形态')); + if (secondaryCutout) target.cutout = pickText(target.cutout, secondaryCutout); + const secondaryRefreshLines = lines(fromSecondary('屏幕刷新率')); + if (secondaryRefreshLines.length > 0) { + target.refreshRate = pickText(target.refreshRate, secondaryRefreshLines[0]); + const note = secondaryRefreshLines.slice(1).join(';'); + if (note) target.refreshNote = pickText(target.refreshNote, note); + } + const secondaryDimming = line(fromSecondary('屏幕调光')); + if (secondaryDimming) target.pwmDimming = pickText(target.pwmDimming, secondaryDimming); + const secondaryTouch = semicolon(fromSecondary('瞬时触控采样率')); + if (secondaryTouch) target.touchSamplingInstant = pickText(target.touchSamplingInstant, secondaryTouch); + const secondaryDepth = line(fromSecondary('屏幕色深')); + if (secondaryDepth) target.colorDepth = pickText(target.colorDepth, secondaryDepth); + const secondaryGamut = line(fromSecondary('屏幕色域')); + if (secondaryGamut) target.colorGamut = pickText(target.colorGamut, secondaryGamut); + const secondaryHdr = semicolon(fromSecondary('HDR支持')); + if (secondaryHdr) target.hdr = pickText(target.hdr, secondaryHdr); + const secondaryProtection = line(fromSecondary('盖板玻璃')); + if (secondaryProtection) target.protection = pickText(target.protection, secondaryProtection); + const secondaryTech = fromSecondary('其他技术'); + if (secondaryTech) { + const techValues = lines(secondaryTech); + if (techValues.length > 0) { + target.features = pickList(target.features, techValues, { union: true }); + } + } + for (const row of secondary) { + if (!/亮度/.test(row.label)) continue; + for (const segment of lines(row.value).flatMap((item) => item.split(/[、,,;;]/))) { + const nit = toNit(segment); + if (!nit) continue; + const context = `${row.label} ${segment}`; + if (/全屏|全局/.test(context)) target.brightnessGlobalPeak = pickText(target.brightnessGlobalPeak, nit); + else if (/典型|默认|手动/.test(context)) target.brightnessTypical = pickText(target.brightnessTypical, nit); + else if (/HDR|峰值|最高|激发/.test(context)) target.brightnessPeak = pickText(target.brightnessPeak, nit); + } + } + const hasSecondaryData = Object.entries(target).some(([key, value]) => + key === 'features' ? Array.isArray(value) && value.length > 0 : Boolean(value), + ); + if (hasSecondaryData) display.secondary = target; + else delete display.secondary; + } + + const chipset = firstLine(fromPerformance('SoC型号') ?? fromSummary('芯片') ?? ''); + if (chipset) platform.chipset = pickText(platform.chipset, chipset); + const socBrand = line(fromPerformance('SoC品牌')); + if (socBrand) platform.socBrand = pickText(platform.socBrand, socBrand); + const gpu = line(fromPerformance('GPU型号') ?? fromPerformance('GPU')); + if (gpu) platform.gpu = pickText(platform.gpu, gpu); + const coprocessor = ['协处理器', '辅助芯片', '独显芯片'] + .map((label) => semicolon(fromPerformance(label))) + .filter(Boolean) + .join(';'); + if (coprocessor) platform.coprocessor = pickText(platform.coprocessor, coprocessor); + const os = line(fromBasic('操作系统')); + if (os) platform.os = pickText(platform.os, os); + const skin = line(fromBasic('出厂系统版本')); + if (skin) { + platform.skin = pickText(platform.skin, skin); + software.launchVersion = pickText(software.launchVersion, skin); + } + const regulatory = line(fromBasic('入网型号')); + if (regulatory) specs.regulatoryModel = pickText(specs.regulatoryModel, regulatory); + const serviceLines = lines(fromAfterSales('售后服务')); + if (serviceLines.length > 0) { + const hotline = serviceLines.find((item) => /^\d{3,6}$/.test(item)); + const policy = serviceLines.filter((item) => !/^\d{3,6}$/.test(item)).join(';'); + const service = hotline + ? policy + ? `服务热线 ${hotline};${policy}` + : `服务热线 ${hotline}` + : policy; + if (service) specs.service = pickText(specs.service, service); + } + + const ram = line(fromPerformance('RAM容量')); + if (ram) memory.ram = pickText(memory.ram, ram); + const ramType = semicolon(fromPerformance('RAM存储类型')); + if (ramType) memory.ramType = pickText(memory.ramType, ramType); + const storage = line(fromPerformance('ROM容量')); + if (storage) memory.storage = pickText(memory.storage, storage); + const storageType = semicolon(fromPerformance('ROM存储类型')); + if (storageType) memory.storageType = pickText(memory.storageType, storageType); + const cardSlotLines = lines(fromPerformance('存储卡')); + if (cardSlotLines.length > 0) { + // 「支持 / NM卡(最大512GB)」这类第二行才是真正规格 + const detail = cardSlotLines.filter((item) => item !== '支持').join(';') || cardSlotLines[0]; + memory.cardSlot = pickText(memory.cardSlot, detail); + } + const cooling = semicolon(fromPerformance('主动散热')); + if (cooling) body.cooling = pickText(body.cooling, cooling); + + const capacity = line(fromCharging('电池容量')); + if (capacity) battery.capacity = pickText(battery.capacity, capacity); + const batteryType = line(fromCharging('电池类型')); + if (batteryType) battery.type = pickText(battery.type, batteryType); + const wiredLines = lines(fromCharging('有线充电')); + if (wiredLines.length > 0) { + const primary = wiredLines[0]; + const existing = battery.wired; + // 旧数据曾把「100W / 100W PPS」合并进 wired,这里拆回主功率与协议 + battery.wired = + existing && existing.includes(';') && clean(existing.split(';')[0]) === clean(primary) + ? primary + : pickText(existing, primary); + const protocol = wiredLines.slice(1).join(';'); + if (protocol) battery.chargingProtocol = pickText(battery.chargingProtocol, protocol); + } + const wireless = semicolon(fromCharging('无线充电')); + if (wireless) battery.wireless = pickText(battery.wireless, wireless); + const reverse = semicolon(fromCharging('反向充电')); + if (reverse) battery.reverse = pickText(battery.reverse, reverse); + + const networkType = line(fromNetwork('网络类型')); + if (networkType) connectivity.cellular = pickText(connectivity.cellular, networkType); + + const fiveG = String(fromNetwork('5G网络频段') ?? '').match(/(n\d+)/gi) ?? []; + const fourG = String(fromNetwork('4G网络频段') ?? '').match(/(B\d+)/gi) ?? []; + const bands = unique( + [...fiveG, ...fourG].map((band) => + band[0].toLowerCase() === 'n' ? `n${band.slice(1)}` : `B${band.slice(1).toUpperCase()}`, + ), + ); + if (bands.length > 0) connectivity.bands = pickList(connectivity.bands, bands, { union: true }); + + const wifi = fromNetwork('WLAN协议'); + const wifiText = lines(wifi).join(','); + if (wifiText) connectivity.wifi = pickText(connectivity.wifi, wifiText); + const bluetooth = semicolon(fromNetwork('蓝牙')); + const bluetoothAudio = semicolon(fromNetwork('蓝牙音频规格')); + if (bluetooth || bluetoothAudio) { + const bluetoothText = [bluetooth, bluetoothAudio].filter(Boolean).join(';'); + connectivity.bluetooth = pickText(connectivity.bluetooth, bluetoothText); + } + const satelliteLocation = semicolon(fromNetwork('卫星定位')); + const locationTech = semicolon(fromNetwork('定位技术')); + const gpsParts = [satelliteLocation, locationTech].filter(Boolean); + if (gpsParts.length > 0) { + connectivity.gps = pickText(connectivity.gps, gpsParts.join(';')); + } + if (/支持/.test(fromNetwork('NFC') ?? '')) connectivity.nfc = true; + if (/支持/.test(fromNetwork('红外功能') ?? '')) connectivity.ir = true; + if (/支持/.test(fromNetwork('UWB') ?? '')) connectivity.uwb = true; + const usb = semicolon(fromNetwork('机身接口')); + if (usb) { + connectivity.usb = pickText(connectivity.usb, usb); + const speed = usb.match(/(\d+(?:\.\d+)?\s*Gbps)/i); + if (speed) connectivity.usbSpeed = pickText(connectivity.usbSpeed, speed[1].replace(/\s+/g, '')); + if (/DP|DisplayPort|视频输出/i.test(usb)) connectivity.usbVideoOut = true; + } + const satelliteText = [ + fromNetwork('卫星通讯'), + fromNetwork('卫星通话'), + fromNetwork('卫星通信'), + ] + .filter(Boolean) + .join(';'); + if (/支持|天通|北斗/.test(satelliteText)) { + connectivity.satellite = true; + if (/天通/.test(satelliteText)) connectivity.satelliteProvider = '天通'; + else if (/北斗/.test(satelliteText)) connectivity.satelliteProvider = '北斗'; + } + + // 酷安详情把规格写在第二行,例如「X轴马达 / 0815规格」,不能只取首行 + const motorDetail = fromOther('震动马达'); + const motorRaw = lines(motorDetail).length > 0 ? motorDetail : fromSummary('震动马达'); + const motorLines = lines(motorRaw); + if (motorLines.length > 0) { + const vibration = (specs.vibration ??= {}); + vibration.type = pickText(vibration.type, motorLines[0]); + if (motorLines.length === 1) { + // 少数机型把型号直接写在类型里:「0815超线性马达」 + const typeCode = motorLines[0].match(/([A-Za-z]*\d{3,6}[A-Za-z]*)/)?.[1]; + if (typeCode) vibration.model = pickText(vibration.model, typeCode); + } + for (const item of motorLines.slice(1)) { + const detail = clean(item); + // 酷安第二行是马达型号:0815规格、东磁0809规格、瑞声科技ELA8282规格、0916C 等 + const codeMatch = detail.match(/^(.*?)([A-Za-z]*\d{3,6}[A-Za-z]*)(?:\s*规格)?(.*)$/); + if (codeMatch) { + const vendor = clean(codeMatch[1]); + const code = codeMatch[2]; + const model = `${vendor}${code}`.trim(); + if (model) vibration.model = pickText(vibration.model, model); + // 旧数据曾把型号写入 size,迁移时清理重复值(如 7514A / ESA7514A) + const sizeText = vibration.size ? clean(vibration.size) : ''; + if ( + sizeText && + (sizeText === code || model.includes(sizeText) || sizeText.includes(code)) + ) { + delete vibration.size; + } + continue; + } + const volume = detail.match(/([\d.]+\s*(?:cm³|mm³))/i)?.[1]; + if (volume) vibration.volume = pickText(vibration.volume, volume); + } + if (vibration.model && vibration.size) { + const modelText = clean(vibration.model); + const sizeText = clean(vibration.size); + if (modelText.includes(sizeText) || sizeText.includes(modelText)) delete vibration.size; + } + } + + const speakerDetail = fromOther('扬声器'); + const speakerRaw = lines(speakerDetail).length > 0 ? speakerDetail : fromSummary('扬声器'); + const speakerLines = lines(speakerRaw); + if (speakerLines.length > 0) { + const text = speakerLines[0]; + const countMatch = text.match(/(\d+)\s*扬声器/); + const chineseMatch = text.match(/(单|双|二|三|四|五)/); + const chineseCount = { 单: 1, 双: 2, 二: 2, 三: 3, 四: 4, 五: 5 }; + const count = countMatch + ? Number(countMatch[1]) + : chineseMatch + ? chineseCount[chineseMatch[1]] + : undefined; + const speakers = (specs.speakers ??= {}); + if (count) { + speakers.count = count; + speakers.stereo = count >= 2; + } + + // 第二行起是单元规格:如「双1115X规格」「2.1立体声、双1115F扬声器+1620低音单元」 + const detailUnits = []; + for (const part of speakerLines.slice(1).join(';').split(/[、,,;;++]/)) { + const trimmed = clean(part); + const model = trimmed.match(/(\d{3,4}[A-Za-z]*)/)?.[1]; + if (!model) continue; + const multiplier = /^双|^二/.test(trimmed) ? 2 : /^三/.test(trimmed) ? 3 : /^四/.test(trimmed) ? 4 : 1; + const label = /低音|重低音/.test(trimmed) ? '低音单元' : undefined; + for (let index = 0; index < multiplier; index += 1) detailUnits.push({ label, model }); + } + const audioText = ['扬声器认证', '音频认证', '音质认证'] + .map((label) => fromOther(label)) + .filter(Boolean) + .join(';'); + if (audioText) { + if (/杜比|Dolby/i.test(audioText)) speakers.dolbyAtmos = true; + if (/Hi-?Res|金标/i.test(audioText)) speakers.hiRes = true; + const loudness = audioText.match(/(\d+(?:\.\d+)?\s*dB(?:A)?)/i)?.[1]; + if (loudness) speakers.loudnessDba = pickText(speakers.loudnessDba, loudness); + } + const headphone = line(fromOther('耳机孔') ?? fromNetwork('耳机孔')); + if (headphone) { + if (/支持|有|3\.5/i.test(headphone) && !/不支持|无/.test(headphone)) speakers.headphoneJack = true; + else if (/不支持|无/.test(headphone)) speakers.headphoneJack = false; + } + + if (detailUnits.length > 0) { + const existingUnits = speakers.units ?? []; + if (existingUnits.length === 0) { + speakers.units = detailUnits.map((unit, index) => ({ + label: unit.label ?? `单元${index + 1}`, + model: unit.model, + })); + } else { + speakers.units = existingUnits.map((unit, index) => { + const incoming = detailUnits[index]; + return incoming + ? { ...unit, model: incoming.model, ...(incoming.label ? { label: unit.label ?? incoming.label } : {}) } + : unit; + }); + for (let index = existingUnits.length; index < detailUnits.length; index += 1) { + const unit = detailUnits[index]; + speakers.units.push({ label: unit.label ?? `单元${index + 1}`, model: unit.model }); + } + } + if (!count) { + speakers.count = detailUnits.length; + speakers.stereo = detailUnits.length >= 2; + } + } + } + + const unlock = fromOther('解锁方式') ?? fromSummary('解锁方式'); + const unlockText = line(unlock); + if (unlockText) { + sensors.fingerprint = pickText(sensors.fingerprint, unlockText); + const fingerprint = sensors.fingerprint ?? ''; + if (/超声波/.test(fingerprint)) sensors.fingerprintType = '超声波'; + else if (/光学|短焦|超薄/.test(fingerprint)) sensors.fingerprintType = '光学'; + else if (/侧边/.test(fingerprint)) sensors.fingerprintType = '侧面'; + else if (/屏幕/.test(fingerprint)) sensors.fingerprintType = '屏下'; + } + const fingerprintPosition = line(fromOther('指纹位置')); + if (fingerprintPosition) sensors.fingerprintPosition = pickText(sensors.fingerprintPosition, fingerprintPosition); + const sensorList = fromOther('传感器'); + if (sensorList) { + const list = splitList(sensorList); + if (list.length > 0) { + sensors.list = pickList(sensors.list, list, { union: true }); + const joined = list.join(','); + if (/陀螺仪/.test(joined)) sensors.gyro = true; + if (/气压/.test(joined)) sensors.barometer = true; + if (/色温/.test(joined)) sensors.colorSensor = true; + if (/flicker/i.test(joined)) sensors.flickerSensor = true; + } + } + + const cameraSubgroups = unique(cameraRows.map((row) => row.subgroup)); + const rearModules = []; + const frontModules = []; + const positionForSubgroup = (subgroup) => { + if (/前置/.test(subgroup)) return 'front'; + if (/超广角/.test(subgroup)) return 'ultrawide'; + if (/微距/.test(subgroup)) return 'macro'; + if (/景深/.test(subgroup)) return 'depth'; + if (/黑白/.test(subgroup)) return 'mono'; + if (/色彩/.test(subgroup)) return 'color'; + if (/长焦/.test(subgroup)) { + const structure = fromCamera('长焦结构', subgroup) ?? ''; + return /潜望/.test(structure) ? 'periscope' : 'tele'; + } + if (/主摄/.test(subgroup)) return 'wide'; + if (/其他摄像头/.test(subgroup)) { + const type = fromCamera('类型', subgroup) ?? ''; + if (/微距/.test(type)) return 'macro'; + if (/景深/.test(type)) return 'depth'; + if (/黑白|单色/.test(type)) return 'mono'; + if (/色彩/.test(type)) return 'color'; + } + return undefined; + }; + + for (const subgroup of cameraSubgroups) { + if (!/参数|其他摄像头/.test(subgroup)) continue; + const position = positionForSubgroup(subgroup); + if (!position) continue; + const get = (label) => line(fromCamera(label, subgroup)); + // 型号行常有两行:第一行传感器型号,第二行尺寸/镜片,例如「索尼LYT808 / 1/1.4英寸、七镜式镜头」 + const modelLines = lines(fromCamera('型号', subgroup)); + const modelRaw = modelLines.join(' '); + const sizeMatch = modelRaw.match(/(1\/\d+(?:\.\d+)?)\s*(?:英寸|")/); + const lensMatch = modelRaw.match(/(?:[一二三四五六七八九十\d]+镜式镜头|\d+G\d+P)/); + const pixelSize = modelRaw.match(/(\d+(?:\.\d+)?)\s*(?:μm|µm|um)/i)?.[0]?.replace(/\s+/g, ''); + const cleanedModel = clean( + modelLines + .map((item) => + item + .replace(/(1\/\d+(?:\.\d+)?)\s*(?:英寸|")/g, '') + .replace(/(?:[一二三四五六七八九十\d]+镜式镜头|\d+G\d+P)/g, '') + .replace(/(\d+(?:\.\d+)?)\s*(?:μm|µm|um)/gi, ''), + ) + .join(' '), + ).replace(/[、,,;;\s]+$/g, ''); + const sensorModel = /^(?:RYYB|RGGB|RCCB|未知)$/i.test(cleanedModel) ? '' : cleanedModel; + const resolution = get('像素'); + const focalLines = lines(fromCamera('等效焦距', subgroup)); + const focalLength = focalLines.find((item) => /(?:mm|毫米)/i.test(item)); + const zoom = focalLines.filter((item) => /变焦/.test(item)).join(';'); + // 防抖模式可能有两行:「光学防抖 / CIPA 7.0」 + const stabilizationText = lines(fromCamera('防抖模式', subgroup)).join(';'); + const cipa = stabilizationText.match(/CIPA\s*[\d.]+/i)?.[0]?.replace(/\s+/g, ' '); + const teleLines = lines(fromCamera('长焦微距', subgroup)); + const isTeleModule = position === 'tele' || position === 'periscope'; + const telephotoStructure = isTeleModule ? line(fromCamera('长焦结构', subgroup)) : undefined; + const telephotoMacro = isTeleModule && teleLines.length > 0 ? /支持|是/.test(teleLines[0]) : undefined; + const telephotoMacroDistance = isTeleModule + ? teleLines.join(';').match(/(\d+(?:\.\d+)?\s*(?:cm|厘米))/i)?.[1] + : undefined; + const module = { + position, + ...(sensorModel ? { sensorModel } : {}), + ...(sizeMatch ? { sensorSize: `${sizeMatch[1]}"` } : {}), + ...(lensMatch ? { lensElements: lensMatch[0] } : {}), + ...(pixelSize ? { pixelSize } : {}), + ...(resolution ? { resolution } : {}), + ...(get('光圈') ? { aperture: get('光圈') } : {}), + ...(focalLength ? { focalLength } : {}), + ...(zoom ? { zoom } : {}), + ...(get('视场') ? { fov: get('视场') } : {}), + ...(stabilizationText && /光学防抖|OIS/i.test(stabilizationText) ? { ois: true } : {}), + ...(stabilizationText && /电子防抖|EIS/i.test(stabilizationText) ? { eis: true } : {}), + ...(cipa ? { cipa } : {}), + ...(telephotoStructure ? { telephotoStructure } : {}), + ...(telephotoMacro !== undefined ? { telephotoMacro } : {}), + ...(telephotoMacroDistance ? { telephotoMacroDistance } : {}), + ...(get('自动对焦') ? { autofocusType: get('自动对焦') } : {}), + }; + const hasData = + module.sensorModel || + module.sensorSize || + module.lensElements || + module.pixelSize || + module.resolution || + module.aperture || + module.focalLength || + module.zoom || + module.fov || + module.ois || + module.cipa || + module.telephotoStructure || + module.telephotoMacro !== undefined; + if (!hasData) continue; + if (position === 'front') frontModules.push(module); + else rearModules.push(module); + } + + // 旧数据可能把同一颗潜望长焦记成 tele,酷安记成 periscope; + // 酷安偶尔也会把同一颗长焦拆成「长焦① / 长焦②」,用等效焦距去重 + const focalKey = (value) => String(value ?? '').match(/(\d+(?:\.\d+)?)/)?.[1]; + const uniqueRearModules = []; + for (const module of rearModules) { + if ( + (module.position === 'tele' || module.position === 'periscope') && + module.focalLength && + uniqueRearModules.some( + (existing) => + (existing.position === 'tele' || existing.position === 'periscope') && + focalKey(existing.focalLength) === focalKey(module.focalLength), + ) + ) { + continue; + } + uniqueRearModules.push(module); + } + const newTeleFocals = new Set( + uniqueRearModules + .filter((module) => module.position === 'tele' || module.position === 'periscope') + .map((module) => focalKey(module.focalLength)) + .filter(Boolean), + ); + if (newTeleFocals.size > 0) { + specs.rearCamera = specs.rearCamera.filter( + (camera) => + !( + (camera.position === 'tele' || camera.position === 'periscope') && + newTeleFocals.has(focalKey(camera.focalLength)) + ), + ); + } + + const usedRear = new Set(); + const usedFront = new Set(); + for (const module of uniqueRearModules) { + specs.rearCamera = mergeCamera(specs.rearCamera, module, usedRear); + } + for (const module of frontModules) { + specs.frontCamera = mergeCamera(specs.frontCamera, module, usedFront); + } + + const videoMax = (subgroup) => { + const rows = cameraRows.filter((row) => row.subgroup === subgroup); + const candidates = rows + .filter((row) => /视频拍摄/.test(row.label)) + .map((row) => { + const resolution = row.label.startsWith('8K') + ? '8K' + : row.label.startsWith('4K') + ? '4K' + : row.label.startsWith('1080') + ? '1080P' + : undefined; + const fps = [...String(row.value).matchAll(/(\d+)\s*FPS/gi)].map((match) => Number(match[1])); + return resolution ? { resolution, fps: fps.length ? Math.max(...fps) : 0 } : undefined; + }) + .filter(Boolean) + .sort((a, b) => (a.resolution === b.resolution ? b.fps - a.fps : ['8K', '4K', '1080P'].indexOf(a.resolution) - ['8K', '4K', '1080P'].indexOf(b.resolution))); + const best = candidates[0]; + if (!best) return undefined; + return best.fps > 0 ? `${best.resolution}@${best.fps}fps` : best.resolution; + }; + + const videoModes = (subgroup) => + cameraRows + .filter((row) => row.subgroup === subgroup && /视频拍摄/.test(row.label)) + .map((row) => { + const value = clean(row.value); + return /^支持$/.test(value) ? row.label : `${row.label}:${value}`; + }); + const rearVideo = videoMax('后置视频拍摄'); + const rearModes = videoModes('后置视频拍摄'); + if (rearVideo || rearModes.length > 0) { + const main = specs.rearCamera.find((camera) => camera.position === 'wide'); + if (main) { + main.video = { + ...(main.video ?? {}), + ...(rearVideo ? { max: pickVideo(main.video?.max, rearVideo) } : {}), + ...(rearModes.length > 0 + ? { modes: pickList(main.video?.modes, rearModes, { union: true }) } + : {}), + }; + } + } + const frontVideo = videoMax('前置视频拍摄'); + const frontModes = videoModes('前置视频拍摄'); + if (frontVideo || frontModes.length > 0) { + const front = specs.frontCamera.find((camera) => camera.position === 'front'); + if (front) { + front.video = { + ...(front.video ?? {}), + ...(frontVideo ? { max: pickVideo(front.video?.max, frontVideo) } : {}), + ...(frontModes.length > 0 + ? { modes: pickList(front.video?.modes, frontModes, { union: true }) } + : {}), + }; + } + } + + // 功能列表可能在页面里折行,先拼回一整段再按分隔符拆分 + const cameraFeatureRaw = lines(cameraRows.find((row) => row.label === '后置摄像头功能')?.value).join(''); + const cameraFeatureList = splitList(cameraFeatureRaw); + const coBrand = line(fromCamera('影像联名品牌') ?? fromSummary('影像联名')); + if (cameraFeatureList.length > 0 || coBrand) { + specs.cameraFeatures = pickList(specs.cameraFeatures, unique([coBrand, ...cameraFeatureList])); + } + + const ramValues = unique( + payload.versions.map((version) => version.name.match(/(\d+GB|\d+TB)\s*\+\s*/i)?.[1]), + ); + const storageValues = unique( + payload.versions.map((version) => version.name.match(/\+\s*(\d+GB|\d+TB)/i)?.[1]), + ); + if (ramValues.length > 0) { + const ramList = pickList( + memory.ram ? splitList(memory.ram.replace(/\s*\/\s*/g, ',')) : [], + ramValues, + ); + memory.ram = ramList.join(' / '); + } + if (storageValues.length > 0) { + const storageList = pickList( + memory.storage ? splitList(memory.storage.replace(/\s*\/\s*/g, ',')) : [], + storageValues, + ); + memory.storage = storageList.join(' / '); + } + const priced = payload.versions.filter((version) => version.price); + if (priced.length > 0) { + specs.pricing = pickList(specs.pricing, priced.map((version) => `${version.name} ${version.price} 元`)); + } + const boxRaw = semicolon(fromAccessories('包装清单')); + if (boxRaw) { + const boxList = splitList(boxRaw); + if (boxList.length > 0) specs.boxContents = pickList(specs.boxContents, boxList); + } + + const ratingRows = groups.find((group) => group.name === '酷安评分')?.rows ?? []; + const ratingNumber = (label) => { + const value = Number(ratingRows.find((row) => row.label === label)?.value); + return Number.isFinite(value) ? value : undefined; + }; + + specs.coolapk = { + productId: product.id, + configId, + name: product.name, + price: price || undefined, + syncedAt: new Date().toISOString(), + rating: { + overall: ratingNumber('所有人评分'), + owner: ratingNumber('机主评分'), + battery: ratingNumber('续航'), + camera: ratingNumber('影像'), + performance: ratingNumber('性能'), + display: ratingNumber('屏幕'), + design: ratingNumber('外观质感'), + value: ratingNumber('性价比'), + }, + }; +} + +function allocateSlug(identity, product, usedSlugs) { + const base = slugify(`${identity.brand} ${identity.model}`).slice(0, 80).replace(/-+$/g, ''); + let slug = base || `coolapk-${product.id}`; + if (usedSlugs.has(slug)) { + let suffix = 2; + slug = `${base || `coolapk-${product.id}`}-${suffix}`; + while (usedSlugs.has(slug)) { + suffix += 1; + slug = `${base || `coolapk-${product.id}`}-${suffix}`; + } + } + usedSlugs.add(slug); + return slug; +} + +function parseCoolapkDate(value) { + const match = String(value ?? '').match(/(\d{4})年(\d{1,2})月(\d{1,2})日/); + if (!match) return undefined; + return `${match[1]}-${String(match[2]).padStart(2, '0')}-${String(match[3]).padStart(2, '0')}`; +} + +function createDevice(target, payload) { + const specs = makeBlankSpecs(); + const detailRows = payload.groups.find((group) => group.name === '基本信息')?.rows ?? []; + const releasedAt = parseCoolapkDate( + detailRows.find((row) => row.label === '发布时间')?.value, + ); + const today = new Date().toISOString().slice(0, 10); + const device = { + slug: target.slug, + category: 'phone', + brand: target.identity.brand, + model: target.identity.model, + aliases: unique([payload.product.name, `${target.identity.brand} ${target.identity.model}`]), + announceDate: releasedAt, + releaseDate: releasedAt, + lifecycle: releasedAt && releasedAt > today ? 'announced' : 'released', + gallery: [], + tags: [], + chipRefs: {}, + specs, + meta: [], + }; + applyCoolapk(device, payload); + const summaryParts = [ + specs.display?.size, + specs.display?.panel, + specs.platform?.chipset, + specs.battery?.capacity, + ].filter(Boolean); + device.summary = summaryParts.join(',').slice(0, 120) || undefined; + return device; +} + +function parseArgs(argv) { + const options = { write: false, limit: 0, out: '', refreshCatalog: false, concurrency: 2, slugs: [] }; + 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 === '--slug') options.slugs.push(argv[(index += 1)] ?? ''); + else if (arg === '--refresh-catalog') options.refreshCatalog = true; + else if (arg === '--concurrency') options.concurrency = Number(argv[(index += 1)] ?? 2); + else throw new Error(`未知参数:${arg}`); + } + return options; +} + +async function main() { + const options = parseArgs(process.argv.slice(2)); + console.log('拉取酷安机型目录 ...'); + const products = dedupeProducts(await fetchCatalog(options.refreshCatalog)); + + const devices = listDevices({ category: 'phone' }); + const { matches, misses } = matchProducts(devices, products); + console.log(`本地 ${devices.length} 款,匹配酷安 ${matches.length} 款,未匹配 ${misses.length} 款`); + if (misses.length > 0) { + console.log('未匹配示例:', misses.slice(0, 12).map((device) => `${device.brand} ${device.model}`)); + } + + const matchedIds = new Set(matches.map((match) => match.product.id)); + const matchedSlugs = new Set(matches.map((match) => match.device.slug)); + const usedSlugs = new Set(devices.map((device) => device.slug)); + const targets = matches.map((match) => ({ + kind: 'merge', + device: match.device, + product: match.product, + })); + + // 名称拼接没对上时,再按「推断品牌 + 型号」精确匹配一次,避免给已有设备重复建页 + let extraMatches = 0; + for (const product of products) { + if (matchedIds.has(product.id)) continue; + const identity = inferIdentity(product.name); + const existing = devices.find( + (device) => + !matchedSlugs.has(device.slug) && + device.brand === identity.brand && + normalize(device.model) === normalize(identity.model), + ); + if (!existing) continue; + matchedIds.add(product.id); + matchedSlugs.add(existing.slug); + extraMatches += 1; + targets.push({ kind: 'merge', device: existing, product }); + } + + const newProducts = products.filter((product) => !matchedIds.has(product.id)); + for (const product of newProducts) { + const identity = inferIdentity(product.name); + const slug = allocateSlug(identity, product, usedSlugs); + targets.push({ kind: 'create', product, identity, slug }); + } + console.log( + `本地 ${devices.length} 款,匹配 ${matches.length + extraMatches} 款,将新建 ${newProducts.length} 款酷安机型`, + ); + + const selected = options.slugs.length + ? targets.filter((target) => + options.slugs.includes(target.kind === 'merge' ? target.device.slug : target.slug), + ) + : options.limit > 0 + ? targets.slice(0, options.limit) + : targets; + if (selected.length === 0) throw new Error('没有匹配到指定 slug 的机型'); + console.log(`开始获取 ${selected.length} 款机型的版本信息 ...`); + + const withVersions = []; + let cursor = 0; + let done = 0; + async function versionWorker() { + while (cursor < selected.length) { + const index = cursor; + cursor += 1; + const target = selected[index]; + try { + const result = await fetchVersions(target.product); + if (result.versions.length > 0) withVersions.push({ ...target, versions: result.versions }); + else console.log(` 无版本信息:${target.product.name}`); + } catch (error) { + console.warn(` 版本失败 ${target.product.name}:${error instanceof Error ? error.message : error}`); + } + done += 1; + if (done % 50 === 0) console.log(` 版本进度 ${done}/${selected.length}`); + } + } + await Promise.all( + Array.from({ length: Math.min(options.concurrency, selected.length) }, () => versionWorker()), + ); + + console.log(`拿到 ${withVersions.length} 款机型的版本列表,开始批量对比 ...`); + const chunks = []; + for (let index = 0; index < withVersions.length; index += 4) { + chunks.push(withVersions.slice(index, index + 4)); + } + + const results = []; + for (let index = 0; index < chunks.length; index += 1) { + const chunk = chunks[index]; + const configIds = chunk.map((item) => item.versions[0].configId); + try { + const parsed = await fetchCompare(configIds); + const productMap = new Map(parsed.products.map((product) => [product.configId, product])); + for (const item of chunk) { + const product = productMap.get(item.versions[0].configId); + if (!product) continue; + const column = parsed.products.findIndex((entry) => entry.configId === item.versions[0].configId); + if (column < 0) continue; + const groups = parsed.groups.map((group) => ({ + name: group.name, + rows: group.rows.map((row) => ({ + subgroup: row.subgroup, + label: row.label, + value: row.values[column] ?? '', + })), + })); + results.push({ + kind: item.kind, + device: item.device, + identity: item.identity, + slug: item.slug, + product: item.product, + versions: item.versions, + configId: item.versions[0].configId, + price: product.price, + groups, + }); + } + } catch (error) { + console.warn(` 对比失败(${configIds.join(',')}):${error instanceof Error ? error.message : error}`); + } + if ((index + 1) % 20 === 0 || index + 1 === chunks.length) { + console.log(` 对比进度 ${index + 1}/${chunks.length}`); + } + } + + const merged = []; + const issues = []; + const enriched = []; + let created = 0; + for (const item of results) { + try { + const device = + item.kind === 'create' + ? createDevice(item, item) + : (() => { + const next = structuredClone(item.device); + applyCoolapk(next, item); + return next; + })(); + const parsed = deviceSchema.safeParse(device); + if (!parsed.success) { + issues.push({ + name: device.slug, + issues: parsed.error.issues.slice(0, 8).map((issue) => `${issue.path.join('.')}: ${issue.message}`), + }); + continue; + } + if (item.kind === 'create') created += 1; + merged.push(parsed.data); + enriched.push({ slug: device.slug, coolapk: parsed.data.specs.coolapk?.name }); + } catch (error) { + issues.push({ name: item.slug ?? item.device?.slug ?? item.product?.name, 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(`成功合并 ${merged.length} 款(其中新建 ${created} 款)`); + + const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19); + const outPath = options.out || `data/import/coolapk-${stamp}.json`; + const payload = { + formatVersion: 1, + generator: 'LFSpecs / sync-coolapk', + exportedAt: new Date().toISOString(), + devices: merged, + chips: [], + }; + await mkdir(dirname(outPath), { recursive: true }); + await writeFile(outPath, `${JSON.stringify(payload, null, 2)}\n`, 'utf8'); + console.log(`JSON 已写入 ${outPath}(${merged.length} 款)`); + + if (!options.write) { + console.log('未指定 --write,本次只产出 JSON。'); + return; + } + console.log('写入数据库 ...'); + const counts = importEntities(merged, []); + console.log(`数据库写入完成:devices ${counts.devices} / chips ${counts.chips}`); +} + +main().catch((error) => { + console.error(error); + process.exit(1); +}); diff --git a/scripts/sync-phonerecommend.mjs b/scripts/sync-phonerecommend.mjs new file mode 100644 index 0000000..feb3e1f --- /dev/null +++ b/scripts/sync-phonerecommend.mjs @@ -0,0 +1,1007 @@ +/** + * 从 phonerecommend.top 同步手机数据到本项目的导入格式 / 数据库。 + * + * 默认只产出 formatVersion: 1 的 JSON(可上传到 /admin/import); + * --write 直接幂等写入 data/app.db,--images 下载封面与相册到 data/uploads。 + * + * 示例: + * pnpm sync:phonerecommend + * pnpm sync:phonerecommend -- --write + * pnpm sync:phonerecommend -- --write --images + * pnpm sync:phonerecommend -- --write --images --brand 华为 --brand 小米 + */ +import { existsSync } from 'node:fs'; +import { mkdir, writeFile } from 'node:fs/promises'; +import { dirname, join } from 'node:path'; +import { pinyin } from 'pinyin-pro'; +import sharp from 'sharp'; +import { deviceSchema } from '../src/lib/schema/device'; +import { importEntities } from '../src/lib/repo'; +import { getStorage, storageRoot } from '../src/lib/storage'; + +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}/`, + Origin: BASE, +}; + +/** 源站中文品牌 → 本地品牌规范名(与现有数据保持一致) */ +const BRAND_MAP = { + 华为: 'Huawei', + 荣耀: 'Honor', + 小米: 'Xiaomi', + 红米: 'Redmi', + OPPO: 'OPPO', + vivo: 'vivo', + 一加: 'OnePlus', + 真我: 'realme', + iQOO: 'iQOO', + 努比亚: 'nubia', + 中兴: 'ZTE', + 摩托罗拉: 'Motorola', + 三星: 'Samsung', + 苹果: 'Apple', + 魅族: 'Meizu', + WIKO: 'WIKO', + ROG: 'ROG', + 金立: 'Gionee', + 酷派: 'Coolpad', + 蔚来Phone: 'NIO Phone', + 麦芒: 'Maimang', + 飞利浦: 'Philips', + 水月雨MIAD: 'Moondrop MIAD', + 联想拯救者手机: 'Lenovo Legion', +}; + +const CAMERA_POSITION_FALLBACK = ['wide', 'ultrawide', 'tele', 'periscope']; + +/* ------------------------------- CLI ------------------------------- */ + +function parseArgs(argv) { + const options = { write: false, images: false, brands: [], limit: 0, pageSize: 100, concurrency: 6, out: '' }; + for (let i = 0; i < argv.length; i += 1) { + const arg = argv[i]; + if (arg === '--write') options.write = true; + else if (arg === '--images') options.images = true; + else if (arg === '--brand') options.brands.push(String(argv[++i] ?? '')); + else if (arg === '--limit') options.limit = Number(argv[++i] ?? 0); + else if (arg === '--page-size') options.pageSize = Math.min(100, Math.max(1, Number(argv[++i] ?? 100))); + else if (arg === '--concurrency') options.concurrency = Math.max(1, Number(argv[++i] ?? 6)); + else if (arg === '--out') options.out = String(argv[++i] ?? ''); + } + return options; +} + +/* ----------------------------- 基础工具 ----------------------------- */ + +const PLACEHOLDERS = new Set(['', '-', '—', '/', '暂无', '暂无数据', '无数据']); + +function clean(value) { + if (typeof value !== 'string') return ''; + const text = value + .replace(/<\/?br\s*\/?>/gi, '\n') + .replace(/<[^>]*>/g, ' ') + .replace(/ /gi, ' ') + .replace(/</gi, '<') + .replace(/>/gi, '>') + .replace(/&/gi, '&') + .replace(/[ \t\u3000]+/g, ' ') + .replace(/\n{2,}/g, '\n') + .trim(); + if (PLACEHOLDERS.has(text)) return ''; + return text; +} + +function splitList(value) { + return clean(value) + .split(/[,,、;;\n]+/) + .map((item) => item.trim()) + .filter((item) => item && !PLACEHOLDERS.has(item)); +} + +function firstNumber(value) { + const match = clean(value).match(/-?\d+(?:\.\d+)?/); + return match ? match[0] : ''; +} + +function normalizeMetric(value) { + return clean(value) + .replace(/(\d+(?:\.\d+)?)\s*毫米/g, '$1 mm') + .replace(/(\d+(?:\.\d+)?)\s*克/g, '$1 g') + .trim(); +} + +function toIsoDate(value) { + const text = clean(value); + if (!text) return undefined; + const match = text.match(/(\d{4})[年./-](\d{1,2})[月./-](\d{1,2})/); + if (match) { + return `${match[1]}-${match[2].padStart(2, '0')}-${match[3].padStart(2, '0')}`; + } + const parsed = new Date(text); + return Number.isNaN(parsed.getTime()) ? undefined : parsed.toISOString().slice(0, 10); +} + +function slugify(value) { + const syllables = pinyin(value, { toneType: 'none', type: 'array', nonZh: 'consecutive' }); + return syllables + .join('-') + .toLowerCase() + .replace(/\+/g, '-plus') + .replace(/&/g, '-and') + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, '') + .replace(/-{2,}/g, '-'); +} + +function unique(items) { + return [...new Set(items.filter(Boolean))]; +} + +/** 源站部分文本会把商城推荐、评价等内容拼进参数,按已知分隔词截断 */ +const SOURCE_JUNK_MARKERS = [ + '暂无用户评价', + '为你推荐', + '没有更多了', + '扫一扫', + '到手价', + '预售价', + '官方标配', + '¥', + '¥', +]; + +function sanitizeSourceText(value) { + let text = clean(value); + const cuts = SOURCE_JUNK_MARKERS.map((marker) => text.indexOf(marker)).filter((index) => index >= 0); + if (cuts.length > 0) text = text.slice(0, Math.min(...cuts)).trim(); + return text; +} + +/** + * 解析屏幕亮度:区分典型亮度、局部/HDR 峰值、全局峰值与最低亮度。 + * 源站文案顺序不固定且会把多个指标连写,这里按空格 / 标点切段后再判断, + * 避免一个数字的上下文串到相邻指标(如把「最低亮度」误判成峰值)。 + */ +function parseBrightness(raw) { + const text = clean(raw); + if (!text) return {}; + + const typical = []; + const peak = []; + const globalPeak = []; + const unlabeled = []; + + const segments = text.split(/[\s,,;;、/]+/).filter(Boolean); + for (const segment of segments) { + const matches = [...segment.matchAll(/(\d+(?:\.\d+)?)\s*(?:尼特|nits?|nit)/gi)]; + if (matches.length === 0) continue; + + if (/最低|min/i.test(segment)) continue; + const strongPeak = /峰值|激发|HDR|局部|peak/i.test(segment); + const strongTypical = /典型|默认|常规|typical/i.test(segment); + const global = /全局|global/i.test(segment); + + for (const match of matches) { + const value = Number(match[1]); + if (!Number.isFinite(value)) continue; + if (strongPeak) { + if (global) globalPeak.push(value); + else peak.push(value); + } else if (strongTypical) { + typical.push(value); + } else { + unlabeled.push(value); + } + } + } + + const result = {}; + const typicalValues = [...new Set(typical)].sort((a, b) => a - b); + let typicalValue = typicalValues[0]; + let peakValue = peak.length > 0 ? Math.max(...peak) : undefined; + + // 多个“典型”读数通常对应不同场景:最低值作典型,最高值作峰值 + if (typicalValues.length > 1) { + typicalValue = typicalValues[0]; + peakValue = Math.max(peakValue ?? 0, typicalValues[typicalValues.length - 1]); + } + // 峰值低于典型值属于源站文案自相矛盾,宁可不展示峰值 + if (typicalValue !== undefined && peakValue !== undefined && peakValue < typicalValue) { + peakValue = undefined; + } + + if (typicalValue !== undefined) result.brightnessTypical = `${typicalValue} nit`; + if (peakValue !== undefined) result.brightnessPeak = `${peakValue} nit`; + if (globalPeak.length > 0) result.brightnessGlobalPeak = `${Math.max(...globalPeak)} nit`; + + if (!result.brightnessTypical && !result.brightnessPeak && unlabeled.length > 0) { + const values = [...new Set(unlabeled)].sort((a, b) => a - b); + result.brightnessTypical = `${values[0]} nit`; + if (values.length > 1) result.brightnessPeak = `${values[values.length - 1]} nit`; + } + return result; +} + +function truncate(value, max) { + return value.length > max ? `${value.slice(0, max - 1)}…` : value; +} + +/* ------------------------------ 抓取 ------------------------------ */ + +async function requestJson(path, attempt = 1) { + try { + const response = await fetch(`${BASE}${path}`, { headers: HEADERS }); + if (!response.ok) throw new Error(`HTTP ${response.status}`); + const json = await response.json(); + if (!json?.success) throw new Error(json?.message ?? '接口返回失败'); + return json; + } catch (error) { + if (attempt >= 3) throw error; + await new Promise((resolve) => setTimeout(resolve, 300 * attempt)); + return requestJson(path, attempt + 1); + } +} + +async function fetchAllPhones(pageSize) { + const first = await requestJson(`/api/phones?limit=${pageSize}&page=1`); + const pages = Math.max(1, Number(first.pagination?.pages ?? 1)); + const phones = [...(first.data ?? [])]; + for (let page = 2; page <= pages; page += 1) { + const json = await requestJson(`/api/phones?limit=${pageSize}&page=${page}`); + phones.push(...(json.data ?? [])); + console.log(` 已拉取第 ${page}/${pages} 页,累计 ${phones.length} 款`); + } + return { phones, total: Number(first.pagination?.total ?? phones.length) }; +} + +/* ----------------------------- 字段映射 ----------------------------- */ + +function parseLabeled(raw, labels) { + const text = clean(raw); + const result = {}; + const matches = [...text.matchAll(new RegExp(`(${labels.join('|')})[::]`, 'g'))]; + matches.forEach((match, index) => { + const start = match.index + match[0].length; + const end = index + 1 < matches.length ? matches[index + 1].index : text.length; + result[match[1]] = text.slice(start, end).trim(); + }); + return result; +} + +function parseOs(raw) { + const text = clean(raw); + if (!text) return {}; + if (/android/i.test(text)) { + const skin = text.split(/[,,]/)[0].trim(); + const version = text.match(/android\s*([\d.]+)/i); + return { + os: version ? `Android ${version[1]}` : 'Android', + skin: skin && !/android/i.test(skin) ? skin : undefined, + }; + } + return { os: text }; +} + +function parseCameraSegments(raw) { + const text = clean(raw); + const map = new Map(); + const matches = [...text.matchAll(/(后置|前置)摄像头(\d+)[::]/g)]; + if (matches.length === 0) { + if (text) map.set('rear-1', text); + return map; + } + matches.forEach((match, index) => { + const start = match.index + match[0].length; + const end = index + 1 < matches.length ? matches[index + 1].index : text.length; + const side = match[1] === '后置' ? 'rear' : 'front'; + map.set(`${side}-${match[2]}`, text.slice(start, end).trim()); + }); + return map; +} + +function parseCameraNames(raw) { + if (typeof raw !== 'string' || !raw.trim()) return []; + try { + const parsed = JSON.parse(raw); + return Array.isArray(parsed) ? parsed : []; + } catch { + return []; + } +} + +function positionFromName(name, index, type) { + if (type === 'front') return 'front'; + if (/潜望/.test(name)) return 'periscope'; + if (/超广角/.test(name)) return 'ultrawide'; + if (/长焦/.test(name)) return 'tele'; + if (/微距/.test(name)) return 'macro'; + if (/景深|深感|3D|TOF/i.test(name)) return 'depth'; + if (/黑白|mono/i.test(name)) return 'mono'; + if (/红枫|原色/.test(name)) return 'color'; + if (/广角|主摄|超光变/.test(name)) return 'wide'; + return CAMERA_POSITION_FALLBACK[index] ?? 'wide'; +} + +function parseVideoMax(raw) { + const text = clean(raw); + const matches = [...text.matchAll(/(8K|4K|1080P|720P)/gi)].map((match) => { + const tail = text.slice(match.index + match[0].length, match.index + match[0].length + 32); + const fpsMatch = tail.match(/(\d+)\s*fps/i); + return { resolution: match[1].toUpperCase(), fps: fpsMatch ? Number(fpsMatch[1]) : 0 }; + }); + if (matches.length === 0) return ''; + const rank = { '8K': 4, '4K': 3, '1080P': 2, '720P': 1 }; + let best = matches[0]; + for (const match of matches) { + const currentRank = rank[match.resolution] ?? 0; + const bestRank = rank[best.resolution] ?? 0; + if (currentRank > bestRank || (currentRank === bestRank && match.fps > best.fps)) best = match; + } + return best.fps ? `${best.resolution}@${best.fps}fps` : best.resolution; +} + +function buildCameras(remote) { + const camera = remote.camera ?? {}; + const names = parseCameraNames(camera.camera_names); + const pixelMap = parseCameraSegments(camera.pixels); + const apertureMap = parseCameraSegments(camera.aperture); + const focalMap = parseCameraSegments(camera.focal_length); + const lensMap = parseCameraSegments(camera.lens_elements); + const sensorMap = parseCameraSegments(camera.sensor_model); + const focusMap = parseCameraSegments(camera.focus_method); + const stabilizationMap = parseCameraSegments(camera.image_stabilization); + + const rear = []; + const front = []; + + const add = (item, side, index) => { + const key = `${side}-${String(item.position ?? index + 1)}`; + const resolution = pixelMap.get(key) ?? ''; + const aperture = apertureMap.get(key) ?? ''; + const focalLength = focalMap.get(key) ?? ''; + const lensElements = lensMap.get(key) ?? ''; + const sensorModel = sensorMap.get(key) ?? ''; + const autofocusType = focusMap.get(key) ?? ''; + const stabilization = stabilizationMap.get(key) ?? ''; + if (!resolution && !aperture && !focalLength && !sensorModel) return; + + const zoomText = clean(camera.zoom); + const optical = zoomText.match(/(\d+(?:\.\d+)?)\s*倍光学变焦/); + const digital = zoomText.match(/(\d+(?:\.\d+)?)\s*倍数码变焦/); + const zoom = + side === 'rear' && (optical || digital) + ? [optical ? `${optical[1]}x 光学` : '', digital ? `${digital[1]}x 数码` : ''].filter(Boolean).join(' / ') + : ''; + + const videoMax = parseVideoMax(side === 'rear' ? camera.rear_video : camera.front_video); + const module = { + position: item.position_enum, + ...(resolution ? { resolution } : {}), + ...(aperture ? { aperture } : {}), + ...(focalLength ? { focalLength } : {}), + ...(lensElements ? { lensElements } : {}), + ...(sensorModel ? { sensorModel } : {}), + ...(autofocusType ? { autofocusType } : {}), + ...(stabilization + ? { ois: /OIS/i.test(stabilization), eis: /EIS/i.test(stabilization) } + : {}), + ...(zoom && ['tele', 'periscope'].includes(item.position_enum) ? { zoom } : {}), + ...(side === 'rear' && item.position_enum === 'ultrawide' && clean(camera.wide_angle) + ? { fov: clean(camera.wide_angle) } + : {}), + ...(side === 'rear' && index === 0 && clean(camera.flash) ? { flash: clean(camera.flash) } : {}), + ...(videoMax && index === 0 ? { video: { max: videoMax, modes: [] } } : {}), + extra: {}, + }; + if (side === 'rear') rear.push(module); + else front.push(module); + }; + + const rearNames = names.filter((item) => item.type === 'rear'); + const frontNames = names.filter((item) => item.type === 'front'); + + rearNames.forEach((item, index) => + add( + { ...item, position_enum: positionFromName(item.name, index, 'rear') }, + 'rear', + index, + ), + ); + frontNames.forEach((item, index) => + add({ ...item, position_enum: 'front' }, 'front', index), + ); + + if (rear.length === 0 && front.length === 0) { + const totalText = clean(camera.camera_total); + const rearCount = Number((totalText.match(/后(\d+)/) ?? [])[1] ?? 0) || 3; + const frontCount = Number((totalText.match(/前(\d+)/) ?? [])[1] ?? 0) || 1; + for (let index = 0; index < rearCount; index += 1) { + add( + { position: index + 1, position_enum: CAMERA_POSITION_FALLBACK[index] ?? 'wide' }, + 'rear', + index, + ); + } + for (let index = 0; index < frontCount; index += 1) { + add({ position: index + 1, position_enum: 'front' }, 'front', index); + } + } + + return { rear, front }; +} + +function buildSpeakers(remote) { + const hardware = remote.hardware ?? {}; + const text = clean(hardware.speaker || hardware.speaker_count); + if (!text) return undefined; + const countMatch = text.match(/(\d+)\s*个/); + const count = countMatch ? Number(countMatch[1]) : /双|立体/.test(text) ? 2 : 1; + const models = [...text.matchAll(/\b(\d{3,4}[A-Za-z]?)\b/g)] + .map((match) => match[1]) + .filter((model, index, list) => list.indexOf(model) === index) + .slice(0, 4); + const units = models.map((model, index) => ({ + label: count > 1 ? `单元${index + 1}` : '扬声器', + model, + })); + if (units.length === 1 && count > 1) { + for (let index = 2; index <= count; index += 1) { + units.push({ ...units[0], label: `单元${index}` }); + } + } + return { + count, + stereo: /立体|双/.test(text) || count >= 2, + units, + ...( /杜比/.test(text) ? { dolbyAtmos: true } : {}), + ...( /Hi-Res|金标/i.test(text) ? { hiRes: true } : {}), + }; +} + +function parseBands(raw) { + const text = clean(raw); + if (!text) return []; + const nrStart = text.search(/5G\s*NR[::]/); + const nrSection = nrStart >= 0 ? text.slice(nrStart) : ''; + const nrBands = [...nrSection.matchAll(/n\d{1,3}/g)].map((match) => match[0]); + const lteStart = text.search(/4G\s*LTE/); + const lteSection = + lteStart >= 0 ? text.slice(lteStart, nrStart > lteStart ? nrStart : undefined) : ''; + const lteBands = [...lteSection.matchAll(/\b(\d{1,3})\b/g)].map((match) => `B${match[1]}`); + return unique([...nrBands, ...lteBands]).slice(0, 80); +} + +function buildSensors(remote) { + const features = remote.features ?? {}; + const basic = remote.basic_info ?? {}; + const list = splitList(String(features.sensors ?? '').replace(/注:[\s\S]*$/m, '')); + const fingerprint = clean(basic.fingerprint) || clean(basic.fingerprint_tech); + const fingerprintTypeMatch = `${fingerprint} ${clean(basic.fingerprint_tech)}`.match( + /(超声波|超声|光学|侧面|侧边|屏下|短焦)/, + ); + return { + ...(fingerprint ? { fingerprint } : {}), + ...(fingerprintTypeMatch ? { fingerprintType: fingerprintTypeMatch[1] } : {}), + ...(fingerprint ? { fingerprintPosition: fingerprint } : {}), + ...(list.some((item) => /陀螺仪/.test(item)) ? { gyro: true } : {}), + ...(list.some((item) => /气压/.test(item)) ? { barometer: true } : {}), + ...(list.some((item) => /色温/.test(item)) ? { colorSensor: true } : {}), + ...(list.some((item) => /闪烁|flicker/i.test(item)) ? { flickerSensor: true } : {}), + ...(list.length > 0 ? { list } : {}), + }; +} + +/* ------------------------------ 单机映射 ------------------------------ */ + +function mapPhone(remote, index) { + const brandSource = clean(remote.brand); + const brand = BRAND_MAP[brandSource] ?? brandSource ?? 'Unknown'; + const basic = remote.basic_info ?? {}; + const rawModel = clean(remote.model); + const productModel = clean(basic.product_model); + const stripBrand = (value) => { + for (const prefix of [brandSource, brand]) { + if (prefix && value.toLowerCase().startsWith(prefix.toLowerCase())) { + return value.slice(prefix.length).trim(); + } + } + return value; + }; + // 源站个别机型 model 只写了品牌,退回 product_model 并去掉品牌前缀 + const model = + rawModel && rawModel.toLowerCase() !== brand.toLowerCase() + ? rawModel + : stripBrand(productModel) || rawModel || productModel || `Phone ${index + 1}`; + const dimensions = remote.dimensions ?? {}; + const hardware = remote.hardware ?? {}; + const screen = remote.screen ?? {}; + const camera = remote.camera ?? {}; + const network = remote.network ?? {}; + const battery = remote.battery ?? {}; + const features = remote.features ?? {}; + const perVersion = remote.per_version ?? {}; + const versions = Array.isArray(remote.versions) ? remote.versions : []; + + const releaseDate = + toIsoDate(basic.launch_date) ?? + toIsoDate(basic.domestic_release_date) ?? + (typeof basic.release_date_timestamp === 'number' + ? new Date(basic.release_date_timestamp).toISOString().slice(0, 10) + : undefined); + const announceDate = toIsoDate(basic.domestic_release_date) ?? releaseDate; + const lifecycle = releaseDate && releaseDate > new Date().toISOString().slice(0, 10) + ? 'announced' + : 'released'; + + const display = { + ...(clean(screen.screen_size) ? { size: clean(screen.screen_size) } : {}), + ...(clean(screen.resolution) + ? { resolution: clean(screen.resolution).replace(/\s*像素$/, '').trim() } + : {}), + ...(clean(screen.screen_material) ? { panel: clean(screen.screen_material) } : {}), + }; + const refreshText = clean(screen.refresh_rate); + const refreshRangeMatch = refreshText.match(/(\d+)\s*[-~至]\s*(\d+)\s*Hz/); + const refreshNumbers = [...refreshText.matchAll(/(\d+)\s*Hz/g)].map((match) => Number(match[1])); + if (refreshRangeMatch) { + display.refreshRate = `${refreshRangeMatch[2]}Hz`; + display.refreshRange = `${refreshRangeMatch[1]}-${refreshRangeMatch[2]}Hz`; + } else if (refreshNumbers.length > 0) { + display.refreshRate = `${Math.max(...refreshNumbers)}Hz`; + } + if (refreshText && unique(refreshNumbers).length > 1) display.refreshNote = refreshText; + const touchText = clean(screen.touch_sampling_rate); + const instantMatch = touchText.match(/瞬时(?:采样率)?[::]?\s*(\d+)\s*Hz/); + if (/最高\s*\d+\s*Hz/.test(touchText)) display.touchSampling = touchText.match(/最高\s*\d+\s*Hz/)[0]; + if (instantMatch) display.touchSamplingInstant = `${instantMatch[1]}Hz`; + if (clean(screen.screen_color)) display.colorDepth = clean(screen.screen_color).split(/[,,]/)[0].trim(); + if (clean(screen.pixel_density)) display.pixelDensity = clean(screen.pixel_density); + if (clean(screen.screen_to_body_ratio)) display.screenBodyRatio = clean(screen.screen_to_body_ratio); + const brightness = parseBrightness(screen.screen_brightness); + Object.assign(display, brightness); + if (clean(screen.glass)) display.protection = clean(screen.glass); + if (clean(screen.dimming_method)) display.pwmDimming = truncate(clean(screen.dimming_method), 180); + if (/^支持/.test(clean(screen.aod))) display.alwaysOn = true; + const screenPoints = splitList(screen.selling_points); + if (screenPoints.length > 0) display.features = screenPoints; + + const buildRaw = clean(basic.body_material); + const buildParts = parseLabeled(buildRaw, ['屏幕盖板材质', '中框材质', '电池盖材质', '后盖', '边框']); + const bodyBuild = { + ...(buildParts['屏幕盖板材质'] ? { front: buildParts['屏幕盖板材质'] } : {}), + ...(buildParts['中框材质'] || buildParts['边框'] + ? { frame: buildParts['中框材质'] || buildParts['边框'] } + : {}), + ...(buildParts['电池盖材质'] || buildParts['后盖'] + ? { back: buildParts['电池盖材质'] || buildParts['后盖'] } + : {}), + }; + if (Object.keys(bodyBuild).length === 0 && buildRaw) bodyBuild.back = buildRaw; + + const length = firstNumber(dimensions.length); + const width = firstNumber(dimensions.width); + const thickness = firstNumber(dimensions.thickness); + const ipMatches = clean(features.waterproof ?? '').match(/IP\d{2}(?:K)?/g); + + const body = { + ...(length && width && thickness ? { dimensions: `${length} x ${width} x ${thickness} mm` } : {}), + ...(clean(dimensions.weight) ? { weight: normalizeMetric(dimensions.weight) } : {}), + ...(Object.keys(bodyBuild).length > 0 ? { build: bodyBuild } : {}), + ...(clean(network.sim_type) ? { sim: clean(network.sim_type) } : {}), + ...(ipMatches ? { ipRating: unique(ipMatches).join(',') } : {}), + ...(clean(hardware.cooling) ? { cooling: truncate(clean(hardware.cooling), 300) } : {}), + ...(splitList(basic.body_color).length > 0 ? { colors: splitList(basic.body_color) } : {}), + }; + + const osParts = parseOs(hardware.os); + const ramValues = unique(versions.map((version) => clean(version.ram))); + if (ramValues.length === 0 && clean(perVersion.ram_capacity)) ramValues.push(clean(perVersion.ram_capacity)); + const storageValues = unique(versions.map((version) => clean(version.rom))); + if (storageValues.length === 0 && clean(perVersion.rom_capacity)) { + storageValues.push(clean(perVersion.rom_capacity).split(/\s/)[0]); + } + + const memory = { + ...(ramValues.length > 0 ? { ram: ramValues.join(' / ') } : {}), + ...(clean(perVersion.ram_type) || clean(features['运行内存']) + ? { ramType: clean(perVersion.ram_type) || clean(features['运行内存']) } + : {}), + ...(storageValues.length > 0 ? { storage: storageValues.join(' / ') } : {}), + ...(clean(perVersion.rom_type) || clean(features['机身存储']) + ? { storageType: clean(perVersion.rom_type) || clean(features['机身存储']) } + : {}), + ...(clean(hardware.storage_card) ? { cardSlot: clean(hardware.storage_card) } : {}), + }; + + const cameras = buildCameras(remote); + const speakerText = clean(hardware.speaker || hardware.speaker_count); + const speakerModel = speakerText.match(/\b\d{3,4}[A-Za-z]?\b/); + const vibrationText = clean(hardware.vibration_motor); + const vibrationModel = vibrationText.match(/\b(\d{3,4})\b/); + + const pricing = versions + .filter((version) => typeof version.price === 'number') + .sort((a, b) => a.price - b.price) + .map((version) => `${clean(version.version_name) || '版本'} ${version.price} 元`); + + const rawAll = JSON.stringify([remote.features, remote.network, remote.other_params]); + const satellite = /卫星通话|卫星通信|天通卫星/.test(rawAll); + const satelliteProvider = satellite + ? /天通/.test(rawAll) + ? '天通' + : /北斗/.test(rawAll) + ? '北斗' + : undefined + : undefined; + + const specs = { + body: Object.keys(body).length > 0 ? body : undefined, + display: Object.keys(display).length > 0 ? display : undefined, + platform: { + ...(osParts.os ? { os: osParts.os } : {}), + ...(osParts.skin ? { skin: osParts.skin } : {}), + ...(clean(hardware.cpu_model) ? { chipset: clean(hardware.cpu_model) } : {}), + }, + memory: Object.keys(memory).length > 0 ? memory : undefined, + rearCamera: cameras.rear, + frontCamera: cameras.front, + vibration: vibrationText + ? { + type: vibrationText, + ...(vibrationModel ? { size: vibrationModel[1] } : {}), + } + : undefined, + speakers: buildSpeakers(remote), + connectivity: { + ...(clean(network.network_type) ? { cellular: clean(network.network_type).replace(/\s*,\s*/g, ' / ') } : {}), + ...(parseBands(network.network_bands).length > 0 ? { bands: parseBands(network.network_bands) } : {}), + ...(satellite ? { satellite: true } : {}), + ...(satelliteProvider ? { satelliteProvider } : {}), + ...(clean(network.wlan) + ? { wifi: truncate(sanitizeSourceText(network.wlan), 300) } + : {}), + ...(clean(network.bluetooth) + ? { bluetooth: truncate(sanitizeSourceText(network.bluetooth), 200) } + : {}), + ...(/^支持/.test(clean(network.nfc)) ? { nfc: true } : {}), + ...(clean(network.navigation) ? { gps: sanitizeSourceText(network.navigation) } : {}), + ...([clean(network.body_interface), clean(hardware.usb_version)].filter(Boolean).length > 0 + ? { usb: [clean(network.body_interface), clean(hardware.usb_version)].filter(Boolean).join(',') } + : {}), + ...(/^支持/.test(clean(network.infrared)) ? { ir: true } : {}), + ...(/UWB/i.test(rawAll) ? { uwb: true } : {}), + }, + battery: { + ...(clean(battery.battery_capacity) ? { capacity: clean(battery.battery_capacity) } : {}), + ...(clean(battery.battery_type) ? { type: clean(battery.battery_type) } : {}), + ...(clean(battery.wired_charging) ? { wired: clean(battery.wired_charging) } : {}), + ...(clean(battery.wireless_charging) ? { wireless: clean(battery.wireless_charging) } : {}), + ...(clean(battery.reverse_charging) ? { reverse: clean(battery.reverse_charging) } : {}), + ...(clean(battery.charging) ? { chargingProtocol: truncate(clean(battery.charging), 300) } : {}), + }, + sensors: buildSensors(remote), + software: { + ...(clean(hardware.os) ? { launchVersion: clean(hardware.os) } : {}), + }, + features: splitList(basic.use_scenario), + cameraFeatures: splitList(camera.rear_camera_features).slice(0, 30), + benchmarks: [], + pricing, + ...(clean(remote.official_price_url) ? { officialUrl: clean(remote.official_price_url) } : {}), + extra: {}, + }; + + const extra = { + 源站机型ID: String(remote._id ?? ''), + 数据来源: `${BASE}/phone/${remote._id}`, + }; + if (clean(remote.other_params)) extra['其他参数'] = truncate(clean(remote.other_params), 400); + if (clean(dimensions.other_dimensions)) extra['尺寸/重量说明'] = truncate(clean(dimensions.other_dimensions), 300); + if (clean(camera.zoom)) extra['变焦说明'] = truncate(clean(camera.zoom), 200); + if (clean(camera.other_camera_params)) extra['影像补充'] = truncate(clean(camera.other_camera_params), 400); + if (clean(features.audio_effects)) extra['音效'] = clean(features.audio_effects); + if (clean(features.in_the_box)) extra['包装清单'] = truncate(clean(features.in_the_box), 300); + if (clean(basic.face_recognition)) extra['面部识别'] = clean(basic.face_recognition); + if (clean(hardware.microphone_count)) extra['麦克风'] = clean(hardware.microphone_count); + if (clean(perVersion.storage)) extra['存储版本'] = clean(perVersion.storage); + if (speakerModel) extra['扬声器单元原文'] = speakerText; + specs.extra = extra; + + const summaryParts = [ + display.size, + display.panel, + clean(hardware.cpu_model), + clean(battery.battery_capacity), + clean(battery.wired_charging) ? `${clean(battery.wired_charging)} 有线充电` : '', + ].filter(Boolean); + const summary = truncate(summaryParts.join(','), 120); + + const aliases = unique([ + `${brandSource} ${model}`.trim(), + clean(basic.product_model), + `${brand} ${model}`, + ]); + + const imageId = String(remote._id ?? ''); + const coverSource = clean(remote.images?.cover_image); + const gallerySources = unique( + (Array.isArray(remote.images?.gallery_images) ? remote.images.gallery_images : []) + .map(clean) + .filter((key) => key.startsWith(`phones/${imageId}/`) && key !== coverSource), + ); + + const brandSlug = slugify(brand); + const modelSlug = slugify(model); + let slug = modelSlug.startsWith(`${brandSlug}-`) ? modelSlug : `${brandSlug}-${modelSlug}`; + slug = slug.slice(0, 80).replace(/-+$/g, ''); + if (!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(slug)) slug = `${brandSlug}-${imageId}`; + + const device = { + slug, + category: 'phone', + brand, + model, + aliases, + announceDate, + releaseDate, + lifecycle, + tags: splitList(basic.use_scenario).slice(0, 12), + summary: summary || undefined, + chipRefs: {}, + specs, + meta: [], + }; + + // 图片 key 依赖最终 slug(可能因重名追加后缀),等 slug 确定后再写入 + deviceImageSources.set(device, { cover: coverSource, gallery: gallerySources }); + + device.meta = buildMeta(device, `${BASE}/phone/${imageId}`); + return device; +} + +function buildMeta(device, sourceUrl) { + const meta = []; + const capturedAt = new Date().toISOString(); + const add = (path) => { + if (meta.length >= 80) return; + meta.push({ path, confidence: 'medium', sourceUrl, verified: false, capturedAt }); + }; + const walk = (value, path) => { + if (meta.length >= 80) return; + if (Array.isArray(value)) { + if (value.length === 0) return; + if (value.every((item) => typeof item === 'string' || typeof item === 'number' || typeof item === 'boolean')) { + add(path); + return; + } + value.forEach((item, index) => walk(item, `${path}[${index}]`)); + return; + } + if (value && typeof value === 'object') { + for (const [key, item] of Object.entries(value)) walk(item, `${path}.${key}`); + return; + } + if (typeof value === 'string' && value.trim()) add(path); + else if (typeof value === 'number' || typeof value === 'boolean') add(path); + }; + for (const [group, value] of Object.entries(device.specs)) { + if (group === 'extra') continue; + walk(value, `specs.${group}`); + } + for (const key of ['slug', 'brand', 'model', 'summary']) { + if (typeof device[key] === 'string' && device[key]) add(key); + } + if (device.aliases.length > 0) add('aliases'); + if (device.tags.length > 0) add('tags'); + if (device.announceDate) add('announceDate'); + if (device.releaseDate) add('releaseDate'); + return meta; +} + +/* ------------------------------ 图片 ------------------------------ */ + +/** 图片落到 data/uploads/devices//...,页面统一用 slug 路径读取 */ +const imageSources = new Map(); +const deviceImageSources = new WeakMap(); +const localImageKey = (slug, name) => `devices/${slug}/${name}.webp`; + +/** slug / 重名后缀确定后,再生成封面与相册的本地 key */ +function applyImageKeys(device) { + const sources = deviceImageSources.get(device); + if (!sources) return; + const cover = sources.cover ? localImageKey(device.slug, 'cover') : undefined; + const gallery = sources.gallery.map((source, index) => { + const key = localImageKey(device.slug, `gallery-${index + 1}`); + imageSources.set(key, source); + return key; + }); + if (cover) imageSources.set(cover, sources.cover); + device.cover = cover; + device.gallery = gallery; +} + +async function downloadImage(key, attempt = 1) { + const source = imageSources.get(key); + if (!source) return 'missing'; + const target = join(storageRoot(), key); + if (existsSync(target)) return 'skip'; + try { + const response = await fetch(`${BASE}/images/${source}`, { + headers: { ...HEADERS, Accept: 'image/avif,image/webp,image/apng,image/*,*/*;q=0.8' }, + signal: AbortSignal.timeout(20000), + }); + if (!response.ok) { + if (response.status === 404) return 'missing'; + throw new Error(`HTTP ${response.status}`); + } + const contentType = response.headers.get('content-type') ?? ''; + if (!contentType.startsWith('image/')) return 'not-image'; + const buffer = Buffer.from(await response.arrayBuffer()); + // 源站存在 .png 实为 JPEG 的文件,统一转 WebP,避免扩展名与内容不一致 + const webp = await sharp(buffer).webp({ quality: 82 }).toBuffer(); + await getStorage().put(key, new Uint8Array(webp), 'image/webp'); + return 'ok'; + } catch (error) { + if (attempt >= 2) throw error; + await new Promise((resolve) => setTimeout(resolve, 200 * attempt)); + return downloadImage(key, attempt + 1); + } +} + +async function downloadImages(devices, concurrency) { + const jobs = []; + for (const device of devices) { + if (device.cover) jobs.push(device.cover); + for (const key of device.gallery) jobs.push(key); + } + const uniqueJobs = unique(jobs); + const stats = { ok: 0, skip: 0, missing: 0, notImage: 0, fail: 0 }; + let cursor = 0; + + async function worker() { + while (cursor < uniqueJobs.length) { + const key = uniqueJobs[cursor]; + cursor += 1; + try { + const result = await downloadImage(key); + stats[result] += 1; + } catch (error) { + stats.fail += 1; + console.warn(` 图片失败 ${key}: ${error instanceof Error ? error.message : error}`); + } + const done = stats.ok + stats.skip + stats.missing + stats.notImage + stats.fail; + if (done % 100 === 0) console.log(` 图片进度 ${done}/${uniqueJobs.length}`); + } + } + + await Promise.all(Array.from({ length: Math.min(concurrency, uniqueJobs.length) }, () => worker())); + return { total: uniqueJobs.length, ...stats }; +} + +/** 下载完成后去掉本地不存在的图片引用,避免页面上出现破图 */ +function pruneMissingImages(devices) { + let removed = 0; + for (const device of devices) { + if (device.cover && !existsSync(join(storageRoot(), device.cover))) { + device.cover = undefined; + removed += 1; + } + const kept = device.gallery.filter((key) => existsSync(join(storageRoot(), key))); + removed += device.gallery.length - kept.length; + device.gallery = kept; + } + return removed; +} + +/* ------------------------------- 主流程 ------------------------------- */ + +async function main() { + const options = parseArgs(process.argv.slice(2)); + console.log(`拉取 ${BASE}/api/phones ...`); + const { phones, total } = await fetchAllPhones(options.pageSize); + console.log(`源站共 ${total} 款,已获取 ${phones.length} 款`); + + let filtered = phones; + if (options.brands.length > 0) { + const wanted = new Set( + options.brands.flatMap((brand) => [brand, BRAND_MAP[brand]]).filter(Boolean), + ); + filtered = filtered.filter((phone) => wanted.has(clean(phone.brand))); + } + if (options.limit > 0) filtered = filtered.slice(0, options.limit); + console.log(`本次处理 ${filtered.length} 款`); + + const devices = []; + const issues = []; + const slugOwner = new Map(); + const duplicateOwner = new Map(); + + filtered.forEach((phone, index) => { + try { + const device = mapPhone(phone, index); + const duplicateKey = `${device.brand}|${device.model}|${device.releaseDate ?? device.announceDate ?? ''}`.toLowerCase(); + if (duplicateOwner.has(duplicateKey)) { + console.warn( + ` 跳过重复机型:${phone.brand} ${phone.model}(与 ${duplicateOwner.get(duplicateKey)} 重复)`, + ); + return; + } + const owner = slugOwner.get(device.slug); + if (owner) { + let suffix = 2; + let candidate = `${device.slug}-${suffix}`; + while (slugOwner.has(candidate)) { + suffix += 1; + candidate = `${device.slug}-${suffix}`; + } + console.warn(` slug 冲突:${device.slug}(${owner} 与 ${phone.brand} ${phone.model}),改用 ${candidate}`); + device.slug = candidate; + } + slugOwner.set(device.slug, `${phone.brand} ${phone.model}`); + applyImageKeys(device); + + const parsed = deviceSchema.safeParse(device); + if (!parsed.success) { + issues.push({ + name: `${phone.brand} ${phone.model}`, + issues: parsed.error.issues.slice(0, 8).map((issue) => `${issue.path.join('.')}: ${issue.message}`), + }); + return; + } + devices.push(parsed.data); + duplicateOwner.set(duplicateKey, `${phone.brand} ${phone.model}`); + } catch (error) { + issues.push({ name: `${phone?.brand ?? '?'} ${phone?.model ?? '?'}`, 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(`映射成功 ${devices.length} 款`); + + if (options.images) { + console.log('开始下载封面与相册 ...'); + const stats = await downloadImages(devices, options.concurrency); + console.log( + `图片完成:共 ${stats.total},新增 ${stats.ok},已存在 ${stats.skip},缺失 ${stats.missing},非图片 ${stats.notImage},失败 ${stats.fail}`, + ); + const removed = pruneMissingImages(devices); + if (removed > 0) console.log(`已清理 ${removed} 个本地缺失的图片引用`); + } + + const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19); + const outPath = options.out || `data/import/phonerecommend-${stamp}.json`; + const payload = { + formatVersion: 1, + generator: 'LFSpecs / sync-phonerecommend', + 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}(${devices.length} 款)`); + + if (options.write) { + console.log('写入数据库 ...'); + const counts = importEntities(devices, []); + console.log(`数据库写入完成:devices ${counts.devices} / chips ${counts.chips}`); + } else { + console.log('未指定 --write,本次只产出 JSON。'); + } +} + +main().catch((error) => { + console.error(error instanceof Error ? error.message : error); + process.exitCode = 1; +}); diff --git a/scripts/sync-processors.mjs b/scripts/sync-processors.mjs new file mode 100644 index 0000000..f46d9ad --- /dev/null +++ b/scripts/sync-processors.mjs @@ -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); +}); diff --git a/src/components/CompareTray.astro b/src/components/CompareTray.astro new file mode 100644 index 0000000..2476882 --- /dev/null +++ b/src/components/CompareTray.astro @@ -0,0 +1,179 @@ +--- +// 全局对比选择条:在列表 / 详情页把机型加入最多 4 个槽位,再进入对比页 +--- + + + + diff --git a/src/components/DeviceCard.astro b/src/components/DeviceCard.astro new file mode 100644 index 0000000..68dbd42 --- /dev/null +++ b/src/components/DeviceCard.astro @@ -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 ?? '—' }, +]; +--- + + diff --git a/src/components/HoverInfo.astro b/src/components/HoverInfo.astro new file mode 100644 index 0000000..d9bbe9a --- /dev/null +++ b/src/components/HoverInfo.astro @@ -0,0 +1,29 @@ +--- +interface Props { + trigger: string; + title: string; + items: string[]; + note?: string; +} + +const { trigger, title, items, note } = Astro.props; +--- + + + {trigger} + + {title} + {note && {note}} + {items.length > 0 ? ( + + {items.map((item) => ( + + {item} + + ))} + + ) : ( + 暂无频段数据 + )} + + diff --git a/src/components/LowBadge.astro b/src/components/LowBadge.astro new file mode 100644 index 0000000..7f82650 --- /dev/null +++ b/src/components/LowBadge.astro @@ -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 && ( + + `${fieldLabelForPath(item.path)}:low,${item.verified ? '已核实' : '待核实'}${ + item.sourceUrl ? `,来源 ${item.sourceUrl}` : '' + }`, + ) + .join('\n')} + > + low + + {summary} + 悬停或聚焦可查看记录: +
    + {lowItems.map((item) => ( +
  • + {fieldLabelForPath(item.path)} + {item.verified ? ( + 已核实 + ) : ( + 待核实 + )} + {item.sourceUrl && ( + + {item.sourceUrl} + + )} +
  • + ))} +
+
+
+ ) +} diff --git a/src/components/Pagination.astro b/src/components/Pagination.astro new file mode 100644 index 0000000..3a6a8d3 --- /dev/null +++ b/src/components/Pagination.astro @@ -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 && ( + + ) +} diff --git a/src/components/admin/BilibiliSetup.tsx b/src/components/admin/BilibiliSetup.tsx new file mode 100644 index 0000000..1f9f787 --- /dev/null +++ b/src/components/admin/BilibiliSetup.tsx @@ -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('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 ( +
+
+ 绑定 B 站账号后,AI 补全可以抓取拆机视频(微机分等拆解 UP 主)的字幕全文, + 提炼马达型号、扬声器单元等官网不公开的参数。登录凭证仅保存在本站数据库,不会上传第三方。 +
+ +
+ + {envConfigured + ? '已绑定(.env 配置)' + : bound + ? `已绑定(扫码保存于 ${savedAt ?? '—'})` + : '未绑定'} + + + {bound && !envConfigured && ( + + )} +
+ + {qrImage && status !== 'confirmed' && ( +
+ B 站扫码登录二维码 +

+ {hint(status)} +

+ {(status === 'expired' || status === 'error') && ( + + )} +
+ )} + + {status === 'confirmed' && ( +

+ {hint('confirmed')} +

+ )} + + {message && status === 'error' && ( +

+ {message} +

+ )} + +

+ 也可以在 .env 中配置 BILIBILI_SESSDATA,优先级高于扫码绑定。 +

+
+ ); +} diff --git a/src/components/admin/ChipEditor.tsx b/src/components/admin/ChipEditor.tsx new file mode 100644 index 0000000..38c790f --- /dev/null +++ b/src/components/admin/ChipEditor.tsx @@ -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(source: T, path: string, value: unknown): T { + const clone = structuredClone(source); + const keys = path.split('.'); + let cursor = clone as Record; + for (const key of keys.slice(0, -1)) { + if (cursor[key] === null || typeof cursor[key] !== 'object') cursor[key] = {}; + cursor = cursor[key] as Record; + } + 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(() => (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(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) { + 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, + }, + }; + + 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 ( +
+ {error && } + +
+
+ +
+ updateChip('slug', event.target.value)} + /> + {isNew && ( + + )} +
+
+ + updateChip('brand', event.target.value)} /> + + + updateChip('model', event.target.value)} /> + + + updateChip('codename', event.target.value)} + /> + + + setAliasesText(event.target.value)} /> + + + updateChip('process', event.target.value)} + /> + + + updateChip('arch', event.target.value)} /> + +
+
+ +
+
+ + updateDetail('gpuBlock.name', event.target.value)} + /> + + + updateDetail('gpuBlock.arch', event.target.value)} + /> + + + + updateDetail( + 'gpuBlock.cores', + event.target.value === '' ? undefined : Number(event.target.value), + ) + } + /> + + + updateDetail('gpuBlock.clockMax', event.target.value)} + /> + + + updateDetail('gpuBlock.apis', apis)} + /> + +
+
+ +
+
+ + updateDetail('npuBlock.name', event.target.value)} + /> + + + updateDetail('npuBlock.tops', event.target.value)} + /> + + + updateDetail('ispBlock', event.target.value)} + /> + + + updateDetail('dspBlock', event.target.value)} + /> + + + updateDetail('modemBlock', event.target.value)} + /> + +
+
+ +
+
+ + updateDetail('memorySupport.type', event.target.value)} + /> + + + updateDetail('memorySupport.maxClock', event.target.value)} + /> + + + updateDetail('memorySupport.bandwidth', event.target.value)} + /> + + + updateDetail('storageSupport', event.target.value)} + /> + + + updateDetail('displaySupport', event.target.value)} + /> + +
+
+ +
+
+ + updateDetail('videoCodec.encode', encode)} + /> + + + updateDetail('videoCodec.decode', decode)} + /> + +
+
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ {chip.meta.length > 0 ? ( +

共 {chip.meta.length} 条来源记录。

+ ) : ( +

暂无字段级来源记录。

+ )} +
+ +
+ + + 返回后台 + + {!isNew && ( + + 查看前台 + + )} +
+ + ); +} diff --git a/src/components/admin/DeviceEditor.tsx b/src/components/admin/DeviceEditor.tsx new file mode 100644 index 0000000..7163e71 --- /dev/null +++ b/src/components/admin/DeviceEditor.tsx @@ -0,0 +1,1696 @@ +import { useMemo, useState, type FormEvent } from 'react'; +import { Button } from '@/components/ui/button'; +import { cn } from '@/lib/utils'; +import type { CameraModule, FieldMeta, PhoneDevice } from '@/lib/schema'; +import { applyAiFields, clearFieldValue, formatFieldValue } from '@/lib/ai/apply'; +import { judgeAiField, prepareAiFields, unverifiedLowFields } from '@/lib/ai/rules'; +import type { AiLookupField, AiLookupResult } from '@/lib/ai/types'; +import { + CAMERA_FIELDS, + CAMERA_POSITIONS, + PHONE_SPEC_SECTIONS as SPEC_SECTIONS, + PHONE_TOP_LEVEL_FIELDS, + fieldLabelForPath, + getValueAtPath, + setValueAtPath, + type PhoneFieldDef, +} from '@/lib/spec-fields'; +import { + BoolSelect, + Field, + FormError, + JsonTextArea, + ListInput, + issueText, + MetaBadge, + Section, + SelectInput, + TextArea, + TextInput, +} from './controls'; + +interface SocOption { + slug: string; + label: string; +} + +interface Props { + initial: PhoneDevice | null; + socOptions: SocOption[]; + isNew: boolean; +} + +interface SectionAiState { + loading?: boolean; + result?: AiLookupResult; + selected?: Record; + ignored?: number; + message?: string; + error?: boolean; +} + +function blankDevice(): PhoneDevice { + return { + slug: '', + category: 'phone', + brand: '', + model: '', + aliases: [], + gallery: [], + tags: [], + lifecycle: 'released', + chipRefs: {}, + meta: [], + specs: { + rearCamera: [], + frontCamera: [], + features: [], + cameraFeatures: [], + benchmarks: [], + pricing: [], + boxContents: [], + extra: {}, + }, + }; +} + +function splitList(text: string): string[] { + return text + .split(',') + .map((item) => item.trim()) + .filter(Boolean); +} + +function makeSlug(brand: string, model: string): string { + return `${brand} ${model}` + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, ''); +} + +/** 基础字段没有注册到 spec-fields,单独给出可读名称 */ +const BASE_FIELD_LABELS: Record = { + slug: 'slug', + brand: '品牌', + model: '型号', + aliases: '别名', + gallery: '图库', + tags: '标签', + summary: '简介', + cover: '封面图', + lifecycle: '生命周期', + announceDate: '发布日期', + releaseDate: '上市日期', + 'chipRefs.soc': 'SoC 引用', +}; + +const CONFIDENCE_RANK = { high: 3, medium: 2, low: 1 } as const; + +function metaLabel(path: string): string { + return BASE_FIELD_LABELS[path] ?? fieldLabelForPath(path); +} + +/** 按字段标签前缀归组,如「屏幕 · 尺寸」→ 屏幕 */ +function metaGroup(path: string): string { + if (!path.startsWith('specs.')) return '基本信息'; + const label = fieldLabelForPath(path); + const separator = label.indexOf(' · '); + return separator > 0 ? label.slice(0, separator) : '其它'; +} + +function metaGroupRank(name: string): number { + const index = SPEC_SECTIONS.findIndex((section) => section.title === name); + if (index >= 0) return index + 1; + if (name.startsWith('后置影像')) return 100; + if (name.startsWith('前置影像')) return 101; + if (name === '设备') return 102; + return 199; +} + +interface MetaRow { + path: string; + label: string; + value: string; + meta: FieldMeta; +} + +export default function DeviceEditor({ initial, socOptions, isNew }: Props) { + const [device, setDevice] = useState(() => + initial ? structuredClone(initial) : blankDevice(), + ); + const [listTexts, setListTexts] = useState>(() => ({ + aliases: initial?.aliases.join(', ') ?? '', + tags: initial?.tags.join(', ') ?? '', + })); + const [extraText, setExtraText] = useState(() => + JSON.stringify(initial?.specs.extra ?? {}, null, 2), + ); + const [error, setError] = useState(''); + const [saving, setSaving] = useState(false); + const [uploading, setUploading] = useState(false); + const [aiLoading, setAiLoading] = useState(false); + const [aiError, setAiError] = useState(''); + const [aiMessage, setAiMessage] = useState(''); + const [aiSourceText, setAiSourceText] = useState(''); + const [aiSourceUrl, setAiSourceUrl] = useState(''); + const [aiResult, setAiResult] = useState(null); + const [aiSelected, setAiSelected] = useState>({}); + const [aiIgnored, setAiIgnored] = useState(0); + const [aiForce, setAiForce] = useState(false); + // 检索范围:默认(整机源网站 / 单项+区块全网)/ 仅源网站 / 全网 / 仅拆机视频 + const [aiScope, setAiScope] = useState<'default' | 'whitelist' | 'web' | 'teardown'>('default'); + const [fieldAi, setFieldAi] = useState< + Record< + string, + { loading?: boolean; ok?: boolean; error?: boolean; empty?: boolean; message?: string } + > + >({}); + const [sectionAi, setSectionAi] = useState>({}); + // 核验清单默认只看待核验项,避免一次铺开几十条已确认记录 + const [metaFilter, setMetaFilter] = useState<'pending' | 'all' | 'low'>('pending'); + + const metaMap = useMemo(() => new Map(device.meta.map((item) => [item.path, item])), [device.meta]); + const lowFields = useMemo(() => unverifiedLowFields(device), [device]); + + const metaGroups = useMemo(() => { + const groups = new Map(); + for (const item of device.meta) { + const groupName = metaGroup(item.path); + const rows = groups.get(groupName) ?? []; + rows.push({ + path: item.path, + label: metaLabel(item.path), + value: formatFieldValue(getValueAtPath(device, item.path)), + meta: item, + }); + groups.set(groupName, rows); + } + return [...groups.entries()] + .map(([name, rows]) => ({ + name, + rows: rows.sort( + (left, right) => + Number(left.meta.verified) - Number(right.meta.verified) || + CONFIDENCE_RANK[left.meta.confidence] - CONFIDENCE_RANK[right.meta.confidence] || + left.label.localeCompare(right.label, 'zh-CN'), + ), + total: rows.length, + pending: rows.filter((row) => !row.meta.verified).length, + low: rows.filter((row) => row.meta.confidence === 'low' && !row.meta.verified).length, + })) + .sort( + (left, right) => + metaGroupRank(left.name) - metaGroupRank(right.name) || + left.name.localeCompare(right.name, 'zh-CN'), + ); + }, [device]); + + const pendingMetaCount = metaGroups.reduce((total, group) => total + group.pending, 0); + const visibleMetaGroups = metaGroups + .map((group) => ({ + ...group, + rows: group.rows.filter((row) => + metaFilter === 'all' + ? true + : metaFilter === 'low' + ? row.meta.confidence === 'low' && !row.meta.verified + : !row.meta.verified, + ), + })) + .filter((group) => group.rows.length > 0); + const sourceUrlList = aiSourceUrl + .split(/[\n,,]/) + .map((url) => url.trim()) + .filter(Boolean); + + function updateBase(key: K, value: PhoneDevice[K]) { + setDevice((prev) => ({ ...prev, [key]: value })); + } + + function updateSpec(path: string, value: unknown) { + setDevice((prev) => ({ ...prev, specs: setValueAtPath(prev.specs, path, value) })); + } + + function updateCameraList(kind: 'rearCamera' | 'frontCamera', list: CameraModule[]) { + setDevice((prev) => ({ ...prev, specs: { ...prev.specs, [kind]: list } })); + } + + function updateCameraField( + kind: 'rearCamera' | 'frontCamera', + index: number, + path: string, + value: unknown, + ) { + setDevice((prev) => { + const list = prev.specs[kind].map((camera, i) => + i === index ? setValueAtPath(camera, path, value) : camera, + ); + return { ...prev, specs: { ...prev.specs, [kind]: list } }; + }); + } + + function updateSpeakerUnit(index: number, path: string, value: unknown) { + setDevice((prev) => { + const speakers = prev.specs.speakers; + const units = (speakers?.units ?? []).map((unit, i) => + i === index ? setValueAtPath(unit, path, value) : unit, + ); + return { ...prev, specs: { ...prev.specs, speakers: { ...speakers, units } } }; + }); + } + + async function runFieldAi(path: string) { + if (fieldAi[path]?.loading) return; + if (!device.brand.trim() || !device.model.trim()) { + setFieldAi((prev) => ({ ...prev, [path]: { error: true, message: '请先填写品牌和型号' } })); + return; + } + + const current = getValueAtPath(device, path); + setFieldAi((prev) => ({ ...prev, [path]: { loading: true } })); + try { + const response = await fetch('/api/ai/field', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + brand: device.brand, + model: device.model, + path, + currentValue: current, + force: true, + sourceText: aiSourceText.trim() || undefined, + sourceUrls: sourceUrlList.length > 0 ? sourceUrlList : undefined, + searchScope: aiScope, + }), + }); + const data = await response.json(); + if (!response.ok) throw new Error(issueText(data)); + if (!data.field) { + setFieldAi((prev) => ({ + ...prev, + [path]: { + empty: true, + message: typeof data.notice === 'string' ? data.notice : '未找到可靠来源', + }, + })); + return; + } + + const judgement = judgeAiField(device, data.field); + if (!judgement) { + setFieldAi((prev) => ({ + ...prev, + [path]: { + ok: true, + message: `与当前值一致或已被现有信息覆盖,已忽略:${formatFieldValue(data.field.value)}`, + }, + })); + return; + } + if ( + !judgement.defaultSelected && + !window.confirm( + `当前:${formatFieldValue(current)}\nAI 建议:${formatFieldValue(data.field.value)}(${data.field.confidence})\n${judgement.reason}\n\n仍要覆盖吗?`, + ) + ) { + setFieldAi((prev) => ({ ...prev, [path]: { ok: true, message: '已保留当前值。' } })); + return; + } + + setDevice((prev) => applyAiFields(prev, [data.field])); + const note = data.field.note ? ` · ${data.field.note}` : ''; + setFieldAi((prev) => ({ + ...prev, + [path]: { + ok: true, + message: `已补全:${formatFieldValue(data.field.value)}(${data.field.confidence})${note}`, + }, + })); + } catch (caught) { + setFieldAi((prev) => ({ + ...prev, + [path]: { + error: true, + message: caught instanceof Error ? caught.message : 'AI 补全失败', + }, + })); + } + } + + function renderAiButton(path: string) { + const state = fieldAi[path]; + const tone = state?.error + ? 'border-destructive/50 text-destructive' + : state?.ok + ? 'border-primary/50 text-primary' + : state?.empty + ? 'border-yellow-500/50 text-yellow-500' + : 'border-border text-muted-foreground hover:border-primary/40 hover:text-foreground'; + const label = state?.loading + ? '…' + : state?.ok + ? '✓' + : state?.error + ? '!' + : state?.empty + ? '无' + : 'AI'; + return ( + + ); + } + + /** 字段旁的核验按钮:一次点击直接把该参数标记为已核实 */ + function renderVerifyButton(path: string) { + const meta = metaMap.get(path); + if (!meta || meta.verified) return null; + const isLow = meta.confidence === 'low'; + return ( + + ); + } + + function renderFieldActions(path: string) { + const state = fieldAi[path]; + return ( + <> + {renderAiButton(path)} + {renderVerifyButton(path)} + {state?.message && (state.empty || state.error) && ( + + {state.empty ? '无公开数据' : '检索失败'} + + )} + + ); + } + + async function runSectionAi(section: string) { + if (sectionAi[section]?.loading) return; + if (!device.brand.trim() || !device.model.trim()) { + setSectionAi((prev) => ({ + ...prev, + [section]: { error: true, message: '请先填写品牌和型号' }, + })); + return; + } + + setSectionAi((prev) => ({ ...prev, [section]: { loading: true } })); + try { + const response = await fetch('/api/ai/section', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + brand: device.brand, + model: device.model, + section, + force: true, + sourceText: aiSourceText.trim() || undefined, + sourceUrls: sourceUrlList.length > 0 ? sourceUrlList : undefined, + searchScope: aiScope, + }), + }); + const data = await response.json(); + if (!response.ok) throw new Error(issueText(data)); + const result = data as AiLookupResult; + const prepared = prepareAiFields(device, result.fields); + setSectionAi((prev) => ({ + ...prev, + [section]: { + result: { ...result, fields: prepared.fields }, + selected: prepared.selected, + ignored: prepared.ignored, + message: result.notice, + }, + })); + } catch (caught) { + setSectionAi((prev) => ({ + ...prev, + [section]: { + error: true, + message: caught instanceof Error ? caught.message : '区块 AI 补全失败', + }, + })); + } + } + + function toggleSectionField(section: string, path: string) { + setSectionAi((prev) => { + const state = prev[section]; + if (!state?.selected) return prev; + return { + ...prev, + [section]: { + ...state, + selected: { ...state.selected, [path]: !state.selected[path] }, + }, + }; + }); + } + + function applySectionAi(section: string) { + const state = sectionAi[section]; + if (!state?.result) return; + const selected = state.result.fields.filter((field) => state.selected?.[field.path]); + if (selected.length === 0) { + setSectionAi((prev) => ({ + ...prev, + [section]: { ...state, error: true, message: '请至少选择一个字段。' }, + })); + return; + } + setDevice((prev) => applyAiFields(prev, selected)); + const lowCount = selected.filter((field) => field.confidence === 'low').length; + setSectionAi((prev) => ({ + ...prev, + [section]: { + message: `已应用 ${selected.length} 个字段${ + lowCount > 0 ? `,其中 ${lowCount} 项 low 置信度需确认` : '' + }。`, + }, + })); + } + + function closeSectionAi(section: string) { + setSectionAi((prev) => { + const next = { ...prev }; + delete next[section]; + return next; + }); + } + + function renderSectionAi(section: string) { + const state = sectionAi[section]; + const tone = state?.error + ? 'border-destructive/50 text-destructive' + : state?.message && !state?.result + ? 'border-primary/50 text-primary' + : 'border-border text-muted-foreground hover:border-primary/40 hover:text-foreground'; + return ( + + ); + } + + function renderSectionPreview(section: string) { + const state = sectionAi[section]; + if (!state?.result) { + return state?.message ? ( +

+ {state.message} +

+ ) : null; + } + + const result = state.result; + const selectedCount = result.fields.filter((field) => state.selected?.[field.path]).length; + return ( +
+
+ + {result.fields.length} 个待处理字段 · 已选 {selectedCount} + {state.ignored ? ( + 已忽略 {state.ignored} 项一致/无效 + ) : null} + {result.notice && {result.notice}} + +
+ + +
+
+
+ {renderAiFieldList(result.fields, state.selected, (path) => toggleSectionField(section, path))} +
+
+ ); + } + + function setVerified(paths: string[], verified: boolean) { + const target = new Set(paths); + setDevice((prev) => ({ + ...prev, + meta: prev.meta.map((item) => (target.has(item.path) ? { ...item, verified } : item)), + })); + } + + async function runAiLookup() { + if (!device.brand.trim() || !device.model.trim()) { + setAiError('请先填写品牌和型号。'); + return; + } + setAiLoading(true); + setAiError(''); + setAiMessage(''); + try { + const response = await fetch('/api/ai/lookup', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + category: 'phone', + brand: device.brand, + model: device.model, + force: aiForce, + sourceText: aiSourceText.trim() || undefined, + sourceUrls: sourceUrlList.length > 0 ? sourceUrlList : undefined, + searchScope: aiScope, + }), + }); + const data = await response.json(); + if (!response.ok) throw new Error(issueText(data)); + const result = data as AiLookupResult; + const prepared = prepareAiFields(device, result.fields); + setAiResult({ ...result, fields: prepared.fields }); + setAiSelected(prepared.selected); + setAiIgnored(prepared.ignored); + if (prepared.fields.length === 0) { + setAiMessage(`没有需要补全或替换的字段${prepared.ignored > 0 ? `,已忽略 ${prepared.ignored} 项` : ''}。`); + } + } catch (caught) { + setAiError(caught instanceof Error ? caught.message : 'AI 补全失败'); + } finally { + setAiLoading(false); + } + } + + function toggleAiField(path: string) { + setAiSelected((prev) => ({ ...prev, [path]: !prev[path] })); + } + + function applyAiResult() { + if (!aiResult) return; + const selected = aiResult.fields.filter((field) => aiSelected[field.path]); + if (selected.length === 0) { + setAiError('请至少选择一个字段。'); + return; + } + + setDevice((prev) => applyAiFields(prev, selected)); + const lowCount = selected.filter((field) => field.confidence === 'low').length; + setAiMessage( + `已应用 ${selected.length} 个字段${ + lowCount > 0 ? `,其中 ${lowCount} 项 low 置信度需确认或清空后才能保存。` : '。' + }`, + ); + setAiError(''); + setAiResult(null); + setAiSelected({}); + setAiIgnored(0); + } + + function confirmAllLow() { + setDevice((prev) => ({ + ...prev, + meta: prev.meta.map((item) => + item.confidence === 'low' && !item.verified ? { ...item, verified: true } : item, + ), + })); + setAiMessage('已将全部 low 置信度字段标记为已核实。'); + } + + function clearAllLow() { + setDevice((prev) => + lowFields.reduce((current, item) => clearFieldValue(current, item.path), prev), + ); + setAiMessage(`已清空 ${lowFields.length} 项 low 置信度字段。`); + } + + function acceptAllHigh() { + setDevice((prev) => ({ + ...prev, + meta: prev.meta.map((item) => + item.confidence === 'high' && !item.verified ? { ...item, verified: true } : item, + ), + })); + } + + async function uploadCover(file: File) { + setUploading(true); + setError(''); + try { + const form = new FormData(); + form.append('file', file); + form.append('slug', device.slug || 'misc'); + const response = await fetch('/api/upload', { method: 'POST', body: form }); + const data = await response.json(); + if (!response.ok) throw new Error(issueText(data)); + updateBase('cover', data.key); + } catch (caught) { + setError(caught instanceof Error ? caught.message : '上传失败'); + } finally { + setUploading(false); + } + } + + async function handleSubmit(event: FormEvent) { + event.preventDefault(); + setSaving(true); + setError(''); + + let extra: Record; + try { + const parsed = JSON.parse(extraText || '{}') as unknown; + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + throw new Error('扩展字段必须是 JSON 对象'); + } + extra = parsed as Record; + } catch (caught) { + setError(caught instanceof Error ? `扩展字段 JSON 无效:${caught.message}` : '扩展字段 JSON 无效'); + setSaving(false); + return; + } + + if (lowFields.length > 0) { + setError( + `有 ${lowFields.length} 项 low 置信度字段未确认,请先在页面底部确认或清空后再保存。`, + ); + setSaving(false); + return; + } + + const payload: PhoneDevice = { + ...device, + aliases: splitList(listTexts.aliases ?? ''), + tags: splitList(listTexts.tags ?? ''), + specs: { + ...device.specs, + rearCamera: device.specs.rearCamera, + frontCamera: device.specs.frontCamera, + extra, + }, + }; + + try { + const response = await fetch(`/api/devices${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/devices/${data.device.slug}?saved=1`; + } catch (caught) { + setError(caught instanceof Error ? caught.message : '保存失败'); + setSaving(false); + } + } + + function renderScalar(section: string, field: PhoneFieldDef) { + const path = `specs.${section}.${field.key}`; + const raw = getValueAtPath((device.specs as Record)[section], field.key); + const meta = metaMap.get(path); + + if (field.kind === 'bool') { + return ( + + updateSpec(`${section}.${field.key}`, next)} + /> + + ); + } + + if (field.kind === 'number') { + return ( + + + updateSpec( + `${section}.${field.key}`, + event.target.value === '' ? undefined : Number(event.target.value), + ) + } + /> + + ); + } + + if (field.kind === 'list') { + const listValue = Array.isArray(raw) ? raw.map(String) : []; + return ( + + updateSpec(`${section}.${field.key}`, next)} + /> + + ); + } + + return ( + + updateSpec(`${section}.${field.key}`, event.target.value)} + /> + + ); + } + + function renderTopLevel(field: PhoneFieldDef) { + const path = `specs.${field.key}`; + const raw = getValueAtPath(device.specs, field.key); + const meta = metaMap.get(path); + if (field.kind === 'list') { + return ( + + updateSpec(field.key, next)} + /> + + ); + } + return ( + + updateSpec(field.key, event.target.value)} + /> + + ); + } + + function renderCameras(kind: 'rearCamera' | 'frontCamera', title: string) { + const cameras = device.specs[kind]; + return ( +
+
+ {cameras.map((camera, index) => ( +
+
+ 第 {index + 1} 颗 + +
+
+ + + updateCameraField(kind, index, 'position', event.target.value) + } + > + {CAMERA_POSITIONS.map((position) => ( + + ))} + + + {CAMERA_FIELDS.map((field) => { + const path = `specs.${kind}[${index}].${field.key}`; + const raw = getValueAtPath(camera, field.key); + const meta = metaMap.get(path); + if (field.kind === 'bool') { + return ( + + updateCameraField(kind, index, field.key, next)} + /> + + ); + } + return ( + + + updateCameraField(kind, index, field.key, event.target.value) + } + /> + + ); + })} + + + updateCameraField(kind, index, 'video.modes', modes.length ? modes : undefined) + } + /> + +
+
+ ))} + + +
+
+ ); + } + + const speakers = device.specs.speakers; + const aiCounts = aiResult + ? { + high: aiResult.fields.filter((field) => field.confidence === 'high').length, + medium: aiResult.fields.filter((field) => field.confidence === 'medium').length, + low: aiResult.fields.filter((field) => field.confidence === 'low').length, + } + : null; + const aiSelectedCount = aiResult + ? aiResult.fields.filter((field) => aiSelected[field.path]).length + : 0; + + function renderAiFieldList( + fields: AiLookupField[], + selected: Record | undefined, + toggle: (path: string) => void, + ) { + if (fields.length === 0) { + return ( +

+ 与当前数据一致或没有有效值,无需处理。 +

+ ); + } + + const badgeLabel = { + fill: '可补全', + replace: '可替换', + 'lower-info': '信息较少', + review: '需确认', + } as const; + const cardTone = { + fill: 'border-primary/35 bg-primary/5', + replace: 'border-yellow-500/35 bg-yellow-500/5', + 'lower-info': 'border-border bg-secondary/25', + review: 'border-border bg-secondary/25', + } as const; + const badgeTone = { + fill: 'border-primary/40 bg-primary/10 text-primary', + replace: 'border-yellow-500/40 bg-yellow-500/10 text-yellow-500', + 'lower-info': 'border-border text-muted-foreground', + review: 'border-border text-muted-foreground', + } as const; + const valueTone = { + fill: 'text-primary', + replace: 'text-yellow-500', + 'lower-info': 'text-muted-foreground', + review: 'text-muted-foreground', + } as const; + + return ( +
+ {fields.map((field) => { + const current = getValueAtPath(device, field.path); + const judgement = judgeAiField(device, field); + const action = judgement?.action ?? 'review'; + const checked = Boolean(selected?.[field.path]); + return ( + + ); + })} +
+ ); + } + + return ( +
+ {error && } + +
+
+ +
+ updateBase('slug', event.target.value)} + /> + {isNew && ( + + )} +
+
+ + updateBase('brand', event.target.value)} + /> + + + updateBase('model', event.target.value)} + /> + + + setListTexts((prev) => ({ ...prev, aliases: event.target.value }))} + /> + + + setListTexts((prev) => ({ ...prev, tags: event.target.value }))} + /> + + + + updateBase('lifecycle', event.target.value as PhoneDevice['lifecycle']) + } + > + + + + + + + + updateBase('announceDate', event.target.value || undefined) + } + /> + + + updateBase('releaseDate', event.target.value || undefined)} + /> + + + + updateBase('chipRefs', { ...device.chipRefs, soc: event.target.value || undefined }) + } + > + + {socOptions.map((option) => ( + + ))} + + +
+ +
+ +