This commit is contained in:
zhongluofeng committed 2026-11-06 15:07:02 +08:00
1 parent 787544eec1
commit 4ff9146910
81 files changed
+18417 -545

No files matched your search

+69
View File
@@ -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));
}
+2
View File
@@ -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';
+611
View File
@@ -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"
}
]
}
]
+173 -56
View File
@@ -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();
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+532
View File
@@ -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);
});