import { csvParseRows, csvFormatRows } from 'd3';
import { escapeHTML } from '../src/io.js';
import { plain, png, canvas } from '../expansion/common.js';
export * from '../expansion/common.js';
export const esc = escapeHTML;
export const colors = ['#167d68', '#477ec4', '#d27b39', '#a75eb8', '#c75368', '#76943b', '#457e84', '#747474'];
export const assert = (value, message) => { if (!value) throw new Error(message); };
export function parseJSON(value, maxNodes = 3000) {
let result; try { result = JSON.parse(value); } catch { throw new Error('JSON语法无效。'); }
const queue = [[result, 0]]; let nodes = 0;
while (queue.length) { const [item, depth] = queue.pop(); assert(++nodes <= maxNodes && depth <= 24, 'JSON层级或条目过多。'); if (item && typeof item === 'object') queue.push(...Object.values(item).map((child) => [child, depth + 1])); }
return result;
}
export function csvRows(value, maxRows = 200) {
assert(value.length <= 100000, 'CSV文本过长。');
const rows = csvParseRows(value.trim());
assert(rows.length && rows.length <= maxRows && rows[0].length <= 30 && rows.every((r) => r.length === rows[0].length), 'CSV需为矩形表格,最多200行、30列。');
assert(rows.flat().every((v) => v.length <= 300), '单元格文字超过300字符。'); return rows;
}
export const csv = (rows, name = 'result.csv') => plain('\ufeff' + csvFormatRows(rows), name, 'text/csv');
export function table(value, minColumns = 2) {
const [header, ...rows] = csvRows(value); assert(rows.length && header.length >= minColumns, '需要列名和至少一行数据。');
assert(header.every((h) => h.trim()) && new Set(header).size === header.length, '列名不能为空或重复。');
return { header, rows };
}
export function numeric(value, label = '数值') { const n = Number(value); assert(String(value).trim() && Number.isFinite(n) && Math.abs(n) <= 1e9, `${label}必须是有限数值,绝对值不超过10亿。`); return n; }
export function points(value, min = 2, max = 500) {
const result = parseJSON(value); assert(Array.isArray(result) && result.length >= min && result.length <= max, `坐标需为${min}–${max}个[x,y]数组。`);
return result.map((point) => { assert(Array.isArray(point) && point.length === 2, '坐标需为[x,y]。'); return point.map((v) => numeric(v, '坐标')); });
}
export function svgDoc(body, width = 640, height = 420, title = '') {
assert(Number.isFinite(width) && Number.isFinite(height) && width > 0 && height > 0 && width <= 4096 && height <= 4096, 'SVG尺寸无效。');
return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" role="img"><title>${esc(title)}</title><rect width="100%" height="100%" fill="#ffffff"/>${body}</svg>`;
}
export const label = (text, x, y, options = '') => `<text x="${x}" y="${y}" ${/\bfont-family=/.test(options) ? '' : 'font-family="sans-serif"'} ${/\bfont-size=/.test(options) ? '' : 'font-size="13"'} ${/\bfill=/.test(options) ? '' : 'fill="#283c35"'} ${options}>${esc(text)}</text>`;
export async function svgResults(value, stem = 'result', includePNG = true) {
const results = [plain(value, `${stem}.svg`, 'image/svg+xml')]; if (!includePNG) return results;
const url = URL.createObjectURL(results[0].blob), image = new Image();
try { image.src = url; await image.decode(); assert(image.naturalWidth * image.naturalHeight <= 16_000_000, 'SVG栅格结果过大。'); const node = canvas(image.naturalWidth, image.naturalHeight); node.getContext('2d').drawImage(image, 0, 0); results.push(await png(node, `${stem}.png`)); }
finally { URL.revokeObjectURL(url); }
return results;
}
export function seeded(seed) { let s = seed >>> 0; return () => { let t = s += 0x6d2b79f5; t = Math.imul(t ^ t >>> 15, t | 1); t ^= t + Math.imul(t ^ t >>> 7, t | 61); return ((t ^ t >>> 14) >>> 0) / 4294967296; }; }
export function date(value) { assert(/^\d{4}-\d{2}-\d{2}$/.test(value), '日期格式应为YYYY-MM-DD。'); const n = Date.parse(value + 'T00:00:00Z'); assert(Number.isFinite(n) && new Date(n).toISOString().slice(0, 10) === value, '日期无效。'); return n; }
export function safeName(value) { return String(value).replace(/[\\/:*?"<>|\x00-\x1f]/g, '_').slice(0, 80) || 'item'; }