/**
* DIL 图标占位符 → 内联 SVG(用户决策 B,2026-10-12)
*
* ─────────────────────────────────────────────────────────────────
* 为什么在后端做
* 客户端只输出 `` 占位符,不带图标集:
* · lucide 官方 ~2141 个图标,单个 SVG ≈ 408B,整包 ≈ 480KB(raw)/130KB(gzip)。
* 塞进 content script 等于给所有平台、所有会话无条件加这份体积。
* · 官方图标本身在**按需加载的 code-split chunk** 里(2026-10-12 抓取的
* 133 个 main bundle 中不存在图标定义),无法从主包提取子集。
* · 后端按需读取,单次 PDF 只付实际用到的那几个图标的代价(真机 15 次/10 个)。
*
* 渲染时机:`/api/generate_pdf` 在 setContent 之前替换 —— DIL 的 HTML 是随
* 主文档一起来的(不走 widget 截图管线),所以就地替换即可,不影响图表出图。
*
* 图标来源:lucide-static v1.55.0(与官方 bundle 内 `lucide-static` 版本号一致)。
*/
const fs = require('fs');
const path = require('path');
const ICON_DIR = path.join(__dirname, '..', 'node_modules', 'lucide-static', 'icons');
/** 名称白名单:lucide 文件名形如 `arrow-down.svg`,杜绝 `..` 与路径穿越 */
const SAFE_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
const cache = new Map();
const stats = { hits: 0, misses: 0, injected: 0, unknown: 0 };
/** 读取并清洗单个 SVG(去掉许可证注释、固定尺寸交由 CSS 控制) */
function loadSvg(name) {
if (!SAFE_NAME.test(name)) return null;
if (cache.has(name)) { stats.hits++; return cache.get(name); }
stats.misses++;
let svg = null;
try {
svg = fs.readFileSync(path.join(ICON_DIR, `${name}.svg`), 'utf8');
} catch {
svg = null;
}
if (svg) {
svg = svg.replace(//g, '').trim();
// lucide 原生带 `width="24" height="24"`。**不能直接删**——删掉后 SVG
// 只剩 viewBox,尺寸完全依赖调用方 CSS 给 `> svg{width;height}`;
// 一旦该规则缺失或被覆盖,SVG 就是 0×0,PDF 里图标位置**彻底空白**
// (2026-10-12 pdf-test 实测:后端日志报"注入 4 个",页面却一个图标都没有)。
// 改成 `1em`:既能随 `.xwx-dil-icon-*` 的字号缩放,又自带兜底尺寸。
svg = svg.replace(/\s(width|height)="24"/g, '');
svg = svg.replace(
'` 这一种形态(客户端唯一产出)。
* 找不到对应图标时**原样保留占位符**并计数 —— 宁可少一个图标,
* 也不能让整块内容消失或抛错中断整份 PDF。
*
* @param {string} html
* @returns {string}
*/
function resolveDilIcons(html) {
if (typeof html !== 'string' || !html.includes('data-dil-icon')) return html;
return html.replace(
/]*?)\bdata-dil-icon="([a-z0-9-]+)"([^>]*)><\/span>/g,
(whole, pre, name, post) => {
const svg = loadSvg(name);
if (!svg) { stats.unknown++; return whole; }
stats.injected++;
// 占位符上的 class 保留(字号/对齐仍由 CSS 控制),SVG 继承 currentColor
return `${svg}`;
},
);
}
/** 供排障使用 */
function dilIconStats() {
return { ...stats, cached: cache.size, iconDir: fs.existsSync(ICON_DIR) };
}
/** 清空缓存(长驻进程按需调用) */
function clearDilIconCache() {
cache.clear();
stats.hits = stats.misses = stats.injected = stats.unknown = 0;
}
module.exports = { resolveDilIcons, dilIconStats, clearDilIconCache };