import DOMPurify from 'dompurify';
import { svgPathProperties } from 'svg-path-properties';
import { num, text, color, choice, canvas, png, plain, json } from './common.js';
const tags = ['svg', 'g', 'path', 'rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon', 'defs', 'linearGradient', 'radialGradient', 'stop', 'clipPath', 'title', 'desc'];
const attrs = ['xmlns', 'viewBox', 'width', 'height', 'x', 'y', 'x1', 'y1', 'x2', 'y2', 'cx', 'cy', 'r', 'rx', 'ry', 'd', 'points', 'fill', 'fill-opacity', 'stroke', 'stroke-width', 'stroke-linecap', 'stroke-linejoin', 'stroke-opacity', 'opacity', 'transform', 'id', 'offset', 'stop-color', 'stop-opacity', 'gradientUnits', 'gradientTransform', 'spreadMethod', 'clip-path', 'fill-rule', 'clip-rule'];
export function cleanSVG(value, prefix = '') {
if (value.length > 1_048_576 || /<!DOCTYPE|<!ENTITY/i.test(value)) throw new Error('SVG 过大或包含不支持的声明。');
const parser = new DOMParser(), initial = parser.parseFromString(value, 'image/svg+xml');
if (initial.querySelector('parsererror') || initial.documentElement.localName !== 'svg') throw new Error('SVG 文档损坏。');
const safe = DOMPurify.sanitize(value, { ALLOWED_TAGS: tags, ALLOWED_ATTR: attrs, FORBID_TAGS: ['style', 'script', 'foreignObject', 'image', 'use', 'a', 'animate', 'set'], ALLOW_DATA_ATTR: false });
const doc = parser.parseFromString(safe, 'image/svg+xml'); if (doc.querySelector('parsererror') || doc.documentElement.localName !== 'svg') throw new Error('SVG 无法清理。');
const root = doc.documentElement; if (root.querySelectorAll('*').length > 5000) throw new Error('SVG 元素超过 5000 个。');
const ids = new Map(); const nodes = [root, ...root.querySelectorAll('*')];
for (const node of nodes) {
for (const attr of [...node.attributes]) {
const name = attr.name, value = attr.value;
if (name === 'id') { if (!/^[a-zA-Z_][\w.-]{0,80}$/.test(value) || ids.has(value)) node.removeAttribute(name); else { ids.set(value, `${prefix}${value}`); node.setAttribute(name, `${prefix}${value}`); } }
else if (/href|^on|style/i.test(name) || /(?:https?:|data:|javascript:|\/\/)/i.test(value) || (/url\s*\(/i.test(value) && !/^url\(#[a-zA-Z_][\w.-]{0,80}\)$/.test(value))) node.removeAttribute(name);
}
}
for (const node of nodes) for (const attr of [...node.attributes]) if (/^url\(#/.test(attr.value)) { const old = attr.value.slice(5, -1); if (ids.has(old)) node.setAttribute(attr.name, `url(#${ids.get(old)})`); else node.removeAttribute(attr.name); }
let box = root.getAttribute('viewBox')?.trim().split(/[\s,]+/).map(Number);
if (!box || box.length !== 4 || box.some((n) => !Number.isFinite(n)) || box[2] <= 0 || box[3] <= 0) {
const w = Number(root.getAttribute('width')), h = Number(root.getAttribute('height')); if (!(w > 0 && h > 0 && w <= 16000 && h <= 16000)) throw new Error('SVG 需要有效 viewBox 或数字宽高。'); box = [0, 0, w, h]; root.setAttribute('viewBox', box.join(' '));
}
if (box.some((n) => Math.abs(n) > 1e7)) throw new Error('SVG 坐标范围过大。');
root.setAttribute('xmlns', 'http://www.w3.org/2000/svg'); root.setAttribute('width', String(Math.min(2048, box[2]))); root.setAttribute('height', String(Math.min(2048, box[3])));
return { root, value: new XMLSerializer().serializeToString(root), box };
}
const fields = {
'svg-shape': [choice('shape', '形状', [['polygon', '正多边形'], ['star', '星形']]), num('sides', '边数 / 角数', 5, 3, 32), num('inner', '星形内径比', 0.45, 0.1, 0.95, 0.05), num('size', '尺寸(px)', 512, 32, 2048), num('stroke', '描边(px)', 4, 0, 40), color('fill', '填充色', '#167d68'), color('line', '描边色', '#203f51')],
'svg-path': [text('path', 'SVG 路径 d', 'M 20 180 C 80 20 180 20 240 180', true), num('samples', '采样点数', 24, 2, 500)],
'svg-sprite': [], 'svg-raster': [num('width', '输出宽度(px)', 512, 16, 2048), num('height', '输出高度(px)', 512, 16, 2048)], 'svg-clean': [],
};
export function getImplementation(id) {
return { fields: fields[id], async run({ values: v, files }) {
if (id === 'svg-shape') {
const count = v.sides * (v.shape === 'star' ? 2 : 1), center = v.size / 2, radius = (v.size - v.stroke * 2) / 2; if (radius <= 0) throw new Error('描边过宽。');
const points = Array.from({ length: count }, (_, i) => { const a = i / count * Math.PI * 2 - Math.PI / 2, r = radius * (v.shape === 'star' && i % 2 ? v.inner : 1); return `${center + Math.cos(a) * r},${center + Math.sin(a) * r}`; }).join(' ');
return [plain(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${v.size} ${v.size}" width="${v.size}" height="${v.size}"><polygon points="${points}" fill="${v.fill}" stroke="${v.line}" stroke-width="${v.stroke}"/></svg>`, 'shape.svg', 'image/svg+xml')];
}
if (id === 'svg-path') {
if (v.path.length > 8000 || !/^[MmZzLlHhVvCcSsQqTtAa\s\d.,eE+-]+$/.test(v.path)) throw new Error('路径字符无效或长度超过 8000。');
let properties; try { properties = new svgPathProperties(v.path); } catch { throw new Error('SVG 路径语法无效。'); } const length = properties.getTotalLength(); if (!(length > 0) || !Number.isFinite(length) || length > 1e7) throw new Error('路径长度无效或过大。');
const points = Array.from({ length: v.samples }, (_, i) => ({ distance: length * i / (v.samples - 1), ...properties.getPointAtLength(length * i / (v.samples - 1)) })); return [json({ length, points }, 'path.json')];
}
const docs = []; for (let i = 0; i < files.length; i++) docs.push(cleanSVG(await files[i].text(), id === 'svg-sprite' ? `icon${i + 1}-` : ''));
if (id === 'svg-sprite') {
const symbols = docs.map(({ root }, i) => `<symbol id="icon-${i + 1}" viewBox="${root.getAttribute('viewBox')}">${root.innerHTML}</symbol>`).join('');
return [plain(`<svg xmlns="http://www.w3.org/2000/svg"><defs>${symbols}</defs></svg>`, 'sprite.svg', 'image/svg+xml'), json(files.map((file, i) => ({ source: file.name, id: `icon-${i + 1}`, viewBox: docs[i].box })), 'symbols.json')];
}
if (id === 'svg-clean') return [plain(docs[0].value, 'clean.svg', 'image/svg+xml')];
const image = new Image(), url = URL.createObjectURL(new Blob([docs[0].value], { type: 'image/svg+xml' }));
try { image.src = url; await image.decode(); const out = canvas(v.width, v.height); const scale = Math.min(v.width / image.naturalWidth, v.height / image.naturalHeight); out.getContext('2d').drawImage(image, (v.width - image.naturalWidth * scale) / 2, (v.height - image.naturalHeight * scale) / 2, image.naturalWidth * scale, image.naturalHeight * scale); return [await png(out)]; } finally { URL.revokeObjectURL(url); }
} };
}