feat(expand): P0-P3 素材扩库批次(发现器 + Google Fonts + Poly Haven + Noto Emoji 3D)

- P0: scripts/discover-sources.js 四通道候选发现,产出 candidates.json / registry.json

- P1: build-posters 新增 fontsource 适配器,接入 Google Fonts 2766 个 woff2

- P2: 新增 polyhaven 适配器,接入 Poly Haven CC0 纹理 238 张

- P3: build-icons 新增 gh-raster listPath(Git Tree 逐级下钻),接入 Noto Emoji 3D 3797 个 PNG

- 修复: GitHub Contents API 不支持目录分页导致重复/截断,改为 Git Tree 下钻并按路径去重;audit-files.json 同步重建

- 判定 noto-emoji-2d / twemoji-png 与既有 Iconify 源同图重复,不予收录

- 基线: 图标 264 源/448,551;海报 69 源/5,366;版本联动 20261108a
This commit is contained in:
sgp
2026-11-08 01:46:52 +08:00
parent 5bcd5ab0f2
commit b10184bf94
6829 changed files with 30261 additions and 452 deletions
+181 -10
View File
@@ -682,32 +682,190 @@ async function downloadGhFiles(src) {
* 产物:PNG 落盘 js/data/sources/{id}/files/,图标 svg 为 <image href="..."> 引用
* (渲染时相对页面路径可直接显示;导出时由 HGB_IconLib.inlineRasters 内联为 data URI)
*/
async function fetchTreeWithRetry(url, tries) {
let last;
for (let i = 0; i < (tries || 3); i++) {
try {
return JSON.parse(await fetch(url, 0, {
'User-Agent': 'drawlogo-build',
Accept: 'application/vnd.github+json'
}));
} catch (e) {
last = e;
await new Promise(r => setTimeout(r, 1500 * (i + 1)));
}
}
throw last;
}
/**
* emoji 名称映射(emoji-datasource 的 unified → short_name)
* 用于把 Twemoji / Noto 的纯码点文件名(1f600 / emoji_u1f600)还原为可搜索的英文名(grinning)
*/
async function loadNameMap(url) {
const arr = JSON.parse(await fetch(url, 0, { 'User-Agent': 'drawlogo-build', Accept: 'application/json' }));
const map = new Map();
for (const e of arr) {
// short_names 里常混有 "+1" 这类符号名,优先取可读的字母名(如 thumbsup)
const names = (e.short_names && e.short_names.length ? e.short_names : [e.short_name]).filter(Boolean);
const name = names.find(n => /^[a-z][a-z0-9-]*$/i.test(n) && n.length >= 2) || names[0];
if (!name) continue;
for (const k of [e.unified, e.non_qualified]) {
if (k) map.set(String(k).toLowerCase().replace(/_/g, '-'), name);
}
}
return map;
}
const GITHUB_TOKEN = process.env.GITHUB_TOKEN || process.env.GH_TOKEN || '';
/**
* GitHub API 专用 fetch(返回 {status, headers, body},timeout 60s,和项目内 fetch 兼容)
* 解决原 fetch 遇到 403 直接 reject 拿不到 status/headers 的问题
*/
function fetchGithubRaw(url, extraHeaders) {
return new Promise((resolve, reject) => {
const headers = {
'User-Agent': 'drawlogo-build',
Accept: 'application/vnd.github+json',
...(GITHUB_TOKEN ? { Authorization: 'Bearer ' + GITHUB_TOKEN } : {}),
...(extraHeaders || {})
};
const req = https.get(url, { timeout: 120000, headers }, (res) => {
// 非 2xx 也要读完 body 才能 resolve(否则连接被占用)
const chunks = [];
res.on('data', c => chunks.push(c));
res.on('end', () => resolve({
status: res.statusCode,
headers: res.headers,
body: Buffer.concat(chunks).toString('utf8')
}));
});
req.on('error', reject);
req.on('timeout', () => { req.destroy(new Error('timeout ' + url)); });
});
}
async function githubWaitForReset() {
try {
const rl = await fetchGithubRaw('https://api.github.com/rate_limit');
const data = JSON.parse(rl.body);
const reset = data?.resources?.core?.reset || (Date.now() / 1000 + 60);
const remaining = data?.resources?.core?.remaining ?? '?';
const waitMs = Math.max(2000, Math.round((reset - Date.now() / 1000) * 1000) + 3000);
console.warn(` ⏳ GitHub 限流(remaining=${remaining}),等 ${(waitMs/1000).toFixed(0)}s 恢复…`);
await new Promise(r => setTimeout(r, waitMs));
} catch (e) {
console.warn(` ⏳ GitHub rate_limit 查询失败,等 60s…`);
await new Promise(r => setTimeout(r, 60000));
}
}
/**
* 目录列举(Git Tree API 逐级定位子目录)
* —— 为什么不用 Contents API 分页:GitHub Contents 对目录**不支持 page 参数**,
* 每次返回同一页 1000 条(noto-emoji 3D 目录 5700+ 文件会被截断 + 重复写入)。
* —— 为什么不用 git/trees?recursive=1:noto-emoji 整树 9MB / 60s+ 易超时。
* 方案:从分支逐级下钻 git/trees/{sha}(每层一次请求,返回全部条目、无 base64),
* 5 次小请求即可拿全子目录(支持上万文件);带 403 自动等 reset + token 支持。
*/
async function listGithubDir(src) {
const gh = src.gh;
const branch = src.ghBranch || 'main';
const segs = String(src.listPath).split('/').filter(Boolean);
async function api(url) {
let tries = 0;
while (true) {
tries++;
let resp;
try { resp = await fetchGithubRaw(url); }
catch (e) {
if (tries >= 5) throw e;
console.warn(` ⚠️ ${src.id}: 网络错误 ${e.message},等 ${1500 * tries}ms 重试 (${tries}/5)`);
await new Promise(r => setTimeout(r, 1500 * tries));
continue;
}
if (resp.status === 403) {
await githubWaitForReset();
if (tries >= 5) throw new Error(`${src.id}: rate limit keep hitting after 5 retries`);
continue;
}
if (resp.status === 404) return null;
if (resp.status !== 200) throw new Error(`GitHub ${resp.status} (${src.id}): ${resp.body.substring(0, 200)}`);
return JSON.parse(resp.body);
}
}
// 下钻到目标目录拿 sha(分支名本身可作为 tree sha)
let sha = encodeURIComponent(branch);
for (const seg of segs) {
const t = await api(`https://api.github.com/repos/${gh}/git/trees/${sha}`);
if (!t) return [];
const node = (t.tree || []).find(x => x.path === seg && x.type === 'tree');
if (!node) { console.warn(` ⚠️ ${src.id}: 路径不存在 ${segs.join('/')}`); return []; }
sha = node.sha;
}
const t = await api(`https://api.github.com/repos/${gh}/git/trees/${sha}`);
if (!t) return [];
const prefix = segs.join('/') + '/';
return (t.tree || [])
.filter(x => x.type === 'blob')
.map(x => ({ type: 'blob', path: prefix + x.path, size: x.size }));
}
async function downloadGhRaster(src) {
const branch = src.ghBranch || 'main';
const api = `https://api.github.com/repos/${src.gh}/git/trees/${branch}?recursive=1`;
const tree = JSON.parse(await fetch(api, 0, {
'User-Agent': 'drawlogo-build',
Accept: 'application/vnd.github+json'
}));
let entries;
if (src.listPath) {
entries = await listGithubDir(src);
} else {
const api = `https://api.github.com/repos/${src.gh}/git/trees/${branch}?recursive=1`;
const tree = await fetchTreeWithRetry(api);
if (tree.truncated) console.warn(` ⚠️ ${src.id}: GitHub 文件树被截断,可能漏掉部分素材`);
entries = tree.tree || [];
}
const re = new RegExp(src.pathRe);
let picked = (tree.tree || []).filter(e => e.type === 'blob' && re.test(e.path));
let picked = entries.filter(e => e.type === 'blob' && re.test(e.path));
if (src.exclude) {
const ex = new RegExp(src.exclude);
picked = picked.filter(e => !ex.test(e.path));
}
// 去重(按路径):防止列举接口重复返回导致同名图标被反复写入、数据文件膨胀
const seenPaths = new Set();
picked = picked.filter(e => (seenPaths.has(e.path) ? false : (seenPaths.add(e.path), true)));
const cap = Number(src.maxItems) > 0 ? Math.min(Number(src.maxItems), picked.length) : picked.length;
picked = picked.slice(0, cap);
const expected = picked.length;
const dir = path.join(process.cwd(), 'js/data/sources', src.id, 'files');
fs.mkdirSync(dir, { recursive: true });
const nameMap = src.nameMapUrl ? await loadNameMap(src.nameMapUrl) : null;
const usedNames = new Set();
const base = `https://cdn.jsdelivr.net/gh/${src.gh}@${branch}/`;
let fail = 0;
const results = await mapLimit(picked, 12, async (e) => {
// 文件名 slug → 图标名:去掉 _3d / _3d_default 后缀,下划线转连字符
const slug = path.basename(e.path, '.png')
.replace(/_3d(?:_default)?$/i, '')
.replace(/_/g, '-');
const raw = path.basename(e.path, '.png');
const code = raw.replace(/^emoji_u/i, '').replace(/_/g, '-').toLowerCase();
// 文件名 slug → 图标名:优先取 emoji 短名,其次去掉 _3d 后缀,最后退回码点
let slug;
if (nameMap) {
slug = nameMap.get(code);
if (!slug) {
// 肤色变体(1f44d-1f3fb)在名称表里没有独立条目 → 拆掉肤色修饰符后回退到基础名
const parts = code.split('-');
const tones = [];
while (parts.length && /^1f3f[b-f]$/.test(parts[parts.length - 1])) tones.unshift(parts.pop());
const baseName = tones.length ? nameMap.get(parts.join('-')) : null;
slug = baseName ? baseName + '-skin-tone-' + tones.join('-') : null;
}
if (!slug) slug = raw.replace(/_/g, '-');
} else {
slug = raw.replace(/_3d(?:_default)?$/i, '').replace(/_/g, '-');
}
slug = String(slug).toLowerCase().replace(/[^a-z0-9-]+/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '') || code;
if (usedNames.has(slug)) slug = slug + '-' + code; // 肤色/变体共用短名时保留码点后缀,避免覆盖
usedNames.add(slug);
try {
const buf = await fetchBuffer(base + e.path.split('/').map(encodeURIComponent).join('/'));
if (!buf || buf.length < 500) throw new Error('empty');
@@ -983,7 +1141,11 @@ async function main() {
const srcDir = path.join(process.cwd(), 'js/data/sources');
fs.mkdirSync(srcDir, { recursive: true });
// 环境变量 ONLY_IDS 可限定只跑特定源(逗号分隔),调试用
const onlyIds = process.env.ONLY_IDS ? new Set(process.env.ONLY_IDS.split(',').map(s => s.trim())) : null;
for (const src of SOURCES) {
if (onlyIds && !onlyIds.has(src.id)) continue;
let icons = null, fail = 0, usedUrl = '';
// 批次校验统计:expected=官方索引数(iconify 源);badViewBox=非法 viewBox 数
let expCount = null, badViewBox = 0;
@@ -1143,6 +1305,15 @@ async function main() {
console.log(`✅ ${src.name}: ${icons.length} 个图标(${type},失败 ${fail})`);
}
// ONLY_IDS 调试模式:只写按源数据文件,绝不覆盖 builtin-icons.js / manifest(否则索引被裁成 2 源)
if (onlyIds) {
console.log(`\n🧪 ONLY_IDS 调试模式:只处理 ${Object.keys(out.sources).length} 个源,共 ${grand} 个图标`);
console.log(' → 已写入 js/data/sources/*.js,跳过索引与 manifest 重建(请稍后跑全量构建收口)');
const passN = verifyReport.length - verifyFailCount;
console.log(`🔍 批次校验:${passN}/${verifyReport.length} 源通过`);
return;
}
out.meta.total = grand;
out.meta.sources = Object.keys(out.sources).length;