Add multi-board selector and scalable firmware catalog UI.

Board chips reserve future models; firmware uses searchable cards with detail pane and optional meta.json media/docs.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-10-19 19:45:24 +08:00
parent ae63378fdb
commit a59aaf1c8d
11 changed files with 788 additions and 226 deletions

62
lib/boards.ts Normal file
View File

@@ -0,0 +1,62 @@
/** Supported / planned hardware families for the flasher UI. */
export type BoardDefinition = {
id: string;
/** Match VERSION.txt / meta board strings (case-insensitive substring). */
match: string[];
/** Translation key under boards.items.<key> */
labelKey: string;
displayName: string;
/** Short chip line shown on the chip */
chip: string;
available: boolean;
};
export const BOARDS: BoardDefinition[] = [
{
id: "esp32-2432s028",
match: ["2432s028", "esp32-2432s028"],
labelKey: "cyd28",
displayName: "CYD ESP32-2432S028",
chip: "ESP32 · 2.8\"",
available: true,
},
{
id: "esp32-2432s024",
match: ["2432s024"],
labelKey: "cyd24",
displayName: "CYD ESP32-2432S024",
chip: "ESP32 · 2.4\"",
available: false,
},
{
id: "esp32-3248s035",
match: ["3248s035"],
labelKey: "cyd35",
displayName: "CYD ESP32-3248S035",
chip: "ESP32 · 3.5\"",
available: false,
},
{
id: "esp32-s3-touch",
match: ["esp32-s3", "s3-touch"],
labelKey: "s3touch",
displayName: "ESP32-S3 Touch",
chip: "ESP32-S3",
available: false,
},
];
export const DEFAULT_BOARD_ID = "esp32-2432s028";
export function resolveBoardId(boardField: string | null | undefined): string {
const raw = (boardField || "").toLowerCase();
if (!raw) return DEFAULT_BOARD_ID;
for (const b of BOARDS) {
if (b.match.some((m) => raw.includes(m.toLowerCase()))) return b.id;
}
return DEFAULT_BOARD_ID;
}
export function getBoard(id: string): BoardDefinition | undefined {
return BOARDS.find((b) => b.id === id);
}

View File

@@ -1,5 +1,6 @@
import fs from "fs";
import path from "path";
import { DEFAULT_BOARD_ID, resolveBoardId } from "@/lib/boards";
export const REQUIRED_BINS = [
"bootloader.bin",
@@ -15,20 +16,51 @@ export const FLASH_PARTS = [
{ file: "firmware.bin", offset: 0x10000 },
] as const;
/** Optional rich metadata: place meta.json next to the .bin files. */
export type FirmwareMedia = {
cover: string | null;
animation: string | null;
video: string | null;
docs: string | null;
};
export type FirmwareInfo = {
id: string;
project: string;
variant: string;
name: string;
summary: string | null;
description: string | null;
tags: string[];
git: string | null;
date: string | null;
board: string;
boardId: string;
flash_size: string;
size: number;
extras: Record<string, string>;
media: FirmwareMedia;
manifestUrl: string;
};
type MetaJson = {
boardId?: string;
name?: string;
summary?: string;
description?: string;
tags?: string[];
git?: string;
date?: string;
board?: string;
flash_size?: string;
media?: {
cover?: string;
animation?: string;
video?: string;
docs?: string;
};
};
function parseVersionTxt(text: string): Record<string, string> {
const meta: Record<string, string> = {};
for (const raw of text.split(/\r?\n/)) {
@@ -44,6 +76,108 @@ function parseVersionTxt(text: string): Record<string, string> {
return meta;
}
function readMetaJson(dir: string): MetaJson | null {
const p = path.join(dir, "meta.json");
if (!fs.existsSync(p)) return null;
try {
return JSON.parse(fs.readFileSync(p, "utf8")) as MetaJson;
} catch {
return null;
}
}
function mediaUrl(
project: string,
variant: string,
dir: string,
rel: string | undefined
): string | null {
if (!rel) return null;
if (/^https?:\/\//i.test(rel)) return rel;
const clean = rel.replace(/^[/\\]+/, "").replace(/\\/g, "/");
const abs = path.join(dir, ...clean.split("/"));
if (!fs.existsSync(abs) || !fs.statSync(abs).isFile()) return null;
return `/api/firmware/${encodeURIComponent(project)}/${encodeURIComponent(variant)}/media/${clean
.split("/")
.map(encodeURIComponent)
.join("/")}`;
}
function buildFirmwareInfo(
project: string,
variant: string,
dir: string
): FirmwareInfo {
const versionMeta = (() => {
const verPath = path.join(dir, "VERSION.txt");
if (!fs.existsSync(verPath)) return {} as Record<string, string>;
try {
return parseVersionTxt(fs.readFileSync(verPath, "utf8"));
} catch {
return {};
}
})();
const json = readMetaJson(dir);
const boardField = json?.board || versionMeta.board || "ESP32-2432S028R";
const boardId =
json?.boardId || resolveBoardId(boardField) || DEFAULT_BOARD_ID;
const tags =
json?.tags?.filter(Boolean) ||
Object.keys(versionMeta)
.filter(
(k) =>
!["name", "git", "date", "board", "flash_size"].includes(k) &&
versionMeta[k]
)
.slice(0, 4);
const features = versionMeta.features;
const summary =
json?.summary ||
features ||
Object.entries(versionMeta)
.filter(([k]) => !["name", "git", "date", "board", "flash_size"].includes(k))
.map(([k, v]) => `${k}: ${v}`)
.slice(0, 2)
.join(" · ") ||
null;
const reserved = new Set(["name", "git", "date", "board", "flash_size", "features"]);
const firmwareStat = fs.statSync(path.join(dir, "firmware.bin"));
return {
id: `${project}/${variant}`,
project,
variant,
name: json?.name || versionMeta.name || `${project} (${variant})`,
summary,
description: json?.description || null,
tags,
git: json?.git || versionMeta.git || null,
date: json?.date || versionMeta.date || null,
board: boardField,
boardId,
flash_size: json?.flash_size || versionMeta.flash_size || "4MB",
size: firmwareStat.size,
extras: Object.fromEntries(
Object.entries(versionMeta).filter(([k]) => !reserved.has(k))
),
media: {
cover: mediaUrl(project, variant, dir, json?.media?.cover),
animation: mediaUrl(project, variant, dir, json?.media?.animation),
video: mediaUrl(project, variant, dir, json?.media?.video),
docs: json?.media?.docs
? /^https?:\/\//i.test(json.media.docs)
? json.media.docs
: mediaUrl(project, variant, dir, json.media.docs)
: null,
},
manifestUrl: `/api/firmware/${encodeURIComponent(project)}/${encodeURIComponent(variant)}/manifest.json`,
};
}
/** Search roots: env override, bundled ./firmware, sibling projects (..). */
export function getFirmwareSearchRoots(): string[] {
const roots: string[] = [];
@@ -80,40 +214,11 @@ function scanProjectFirmware(
for (const v of variants) {
if (!v.isDirectory()) continue;
const dir = path.join(fwRoot, v.name);
const missing = REQUIRED_BINS.filter((f) => !fs.existsSync(path.join(dir, f)));
if (missing.length) continue;
if (REQUIRED_BINS.some((f) => !fs.existsSync(path.join(dir, f)))) continue;
const id = `${projectName}/${v.name}`;
if (seen.has(id)) continue;
seen.add(id);
let meta: Record<string, string> = {};
const verPath = path.join(dir, "VERSION.txt");
if (fs.existsSync(verPath)) {
try {
meta = parseVersionTxt(fs.readFileSync(verPath, "utf8"));
} catch {
/* ignore */
}
}
const firmwareStat = fs.statSync(path.join(dir, "firmware.bin"));
const reserved = new Set(["name", "git", "date", "board", "flash_size"]);
items.push({
id,
project: projectName,
variant: v.name,
name: meta.name || `${projectName} (${v.name})`,
git: meta.git || null,
date: meta.date || null,
board: meta.board || "ESP32-2432S028R",
flash_size: meta.flash_size || "4MB",
size: firmwareStat.size,
extras: Object.fromEntries(
Object.entries(meta).filter(([k]) => !reserved.has(k))
),
manifestUrl: `/api/firmware/${encodeURIComponent(projectName)}/${encodeURIComponent(v.name)}/manifest.json`,
});
items.push(buildFirmwareInfo(projectName, v.name, dir));
}
return items;
}
@@ -130,8 +235,6 @@ export function discoverFirmware(): FirmwareInfo[] {
for (const root of getFirmwareSearchRoots()) {
if (!fs.existsSync(root)) continue;
// Bundled: root itself is the firmware mirror (contains project folders)
// or root is cyd parent with project folders that contain firmware/
let entries: fs.Dirent[];
try {
entries = fs.readdirSync(root, { withFileTypes: true });
@@ -141,29 +244,19 @@ export function discoverFirmware(): FirmwareInfo[] {
for (const ent of entries) {
if (!ent.isDirectory()) continue;
if (ent.name === "cydweb" || ent.name === "node_modules" || ent.name.startsWith(".")) {
if (
ent.name === "cydweb" ||
ent.name === "node_modules" ||
ent.name.startsWith(".")
) {
continue;
}
const projectPath = path.join(root, ent.name);
// Sibling project: ../temperature/firmware/...
items.push(...scanProjectFirmware(projectPath, ent.name, seen));
// Bundled mirror: firmware/temperature/cyd_28r/...
// Here `root` is ./firmware and `ent` is project name; variants are direct children.
const maybeVariantBins = REQUIRED_BINS.every((f) =>
fs.existsSync(path.join(projectPath, f))
);
if (maybeVariantBins) {
// Unusual: project folder IS the variant — treat parent name
continue;
}
// If root is ./firmware, children are projects whose children are variants
const nestedFw = path.join(projectPath, "firmware");
if (!fs.existsSync(nestedFw)) {
// Direct: firmware/<project>/<variant>
let variants: fs.Dirent[];
try {
variants = fs.readdirSync(projectPath, { withFileTypes: true });
@@ -173,37 +266,13 @@ export function discoverFirmware(): FirmwareInfo[] {
for (const v of variants) {
if (!v.isDirectory()) continue;
const dir = path.join(projectPath, v.name);
if (REQUIRED_BINS.some((f) => !fs.existsSync(path.join(dir, f)))) continue;
if (REQUIRED_BINS.some((f) => !fs.existsSync(path.join(dir, f)))) {
continue;
}
const id = `${ent.name}/${v.name}`;
if (seen.has(id)) continue;
seen.add(id);
let meta: Record<string, string> = {};
const verPath = path.join(dir, "VERSION.txt");
if (fs.existsSync(verPath)) {
try {
meta = parseVersionTxt(fs.readFileSync(verPath, "utf8"));
} catch {
/* ignore */
}
}
const firmwareStat = fs.statSync(path.join(dir, "firmware.bin"));
const reserved = new Set(["name", "git", "date", "board", "flash_size"]);
items.push({
id,
project: ent.name,
variant: v.name,
name: meta.name || `${ent.name} (${v.name})`,
git: meta.git || null,
date: meta.date || null,
board: meta.board || "ESP32-2432S028R",
flash_size: meta.flash_size || "4MB",
size: firmwareStat.size,
extras: Object.fromEntries(
Object.entries(meta).filter(([k]) => !reserved.has(k))
),
manifestUrl: `/api/firmware/${encodeURIComponent(ent.name)}/${encodeURIComponent(v.name)}/manifest.json`,
});
items.push(buildFirmwareInfo(ent.name, v.name, dir));
}
}
}
@@ -244,3 +313,19 @@ export function readFirmwareMeta(dir: string): Record<string, string> {
return {};
}
}
/** Resolve a media file under a firmware dir (path traversal safe). */
export function resolveMediaFile(
project: string,
variant: string,
relPath: string
): string | null {
const dir = resolveFirmwareDir(project, variant);
if (!dir) return null;
const normalized = path.normalize(relPath).replace(/^([/\\])+/, "");
if (normalized.startsWith("..") || path.isAbsolute(normalized)) return null;
const abs = path.join(dir, normalized);
if (!abs.startsWith(dir + path.sep) && abs !== dir) return null;
if (!fs.existsSync(abs) || !fs.statSync(abs).isFile()) return null;
return abs;
}