@x12i/reportic-render-html 0.2.3 → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // packages/reportic-render-html/src/index.ts
2
2
  import { marked } from "marked";
3
3
  import sanitizeHtml from "sanitize-html";
4
- import { escapeHtml as h2, escapeMd as md, themeTokens as themeTokens2, formatValue as formatValue2, safeUrl, safeRelative, fail as fail3 } from "@x12i/reportic-core";
4
+ import { escapeHtml as h4, escapeMd as md, themeTokens as themeTokens5, semanticColors as semanticColors3, walkNodes as walkNodes2, formatValue as formatValue3, safeUrl, safeRelative, fail as fail4, figureSpec as figureSpec2 } from "@x12i/reportic-core";
5
5
 
6
6
  // packages/reportic-render-html/src/visuals.ts
7
7
  import { readFile } from "fs/promises";
@@ -173,14 +173,2728 @@ function chartSvg(node, report, options = {}) {
173
173
  return svg + "</svg>";
174
174
  }
175
175
 
176
+ // packages/reportic-render-html/src/figures.ts
177
+ import { escapeHtml as h2, themeTokens as themeTokens2, semanticColors } from "@x12i/reportic-core";
178
+ var W = 760;
179
+ var attrs = (a) => Object.entries(a).filter(([, v]) => v !== void 0 && v !== null).map(([k, v]) => ` ${k}="${h2(typeof v === "number" ? Math.round(v * 100) / 100 : v)}"`).join("");
180
+ var el = (tag2, a, text2) => text2 === void 0 ? `<${tag2}${attrs(a)}/>` : `<${tag2}${attrs(a)}>${h2(text2)}</${tag2}>`;
181
+ var glyph = (ch) => ch === " " ? 0.28 : "il.,:;'|!".includes(ch) ? 0.26 : "()[]/\\\xB7-\u2013tfIjr".includes(ch) ? 0.36 : "mwMW@%".includes(ch) ? 0.84 : ch >= "A" && ch <= "Z" ? 0.62 : ch >= "0" && ch <= "9" ? 0.56 : 0.52;
182
+ var textWidth = (s, size) => [...s].reduce((w, ch) => w + glyph(ch), 0) * size;
183
+ var fit = (s, room, size) => {
184
+ if (textWidth(s, size) <= room) return s;
185
+ let out = "";
186
+ for (const ch of s) {
187
+ if (textWidth(out + ch + "\u2026", size) > room) break;
188
+ out += ch;
189
+ }
190
+ return (out || s.slice(0, 1)) + "\u2026";
191
+ };
192
+ var wrapPx = (s, room, size, weight = 1) => {
193
+ const lines = [];
194
+ let line = "";
195
+ for (const word2 of s.split(/\s+/).filter(Boolean)) {
196
+ if (line && textWidth(line + " " + word2, size) * weight > room) {
197
+ lines.push(line);
198
+ line = word2;
199
+ } else line = line ? line + " " + word2 : word2;
200
+ }
201
+ if (line) lines.push(line);
202
+ return lines.length ? lines : [""];
203
+ };
204
+ var nice = (max) => {
205
+ if (max <= 0) return 1;
206
+ const p = Math.pow(10, Math.floor(Math.log10(max))), f = max / p;
207
+ return (f <= 1 ? 1 : f <= 2 ? 2 : f <= 2.5 ? 2.5 : f <= 5 ? 5 : 10) * p;
208
+ };
209
+ function draw(f, c, locale) {
210
+ const tone2 = (t, fallback = c.accent) => !t ? fallback : t === "muted" || t === "grey" ? c.grey : c[t];
211
+ const nf = new Intl.NumberFormat(locale);
212
+ const fmt = (v) => v === null || v === void 0 ? "" : (Math.abs(v) >= 1e3 ? nf.format(v) : String(Math.round(v * 10) / 10)) + (f.unit === "%" ? "%" : "");
213
+ const titleLines = wrapPx(f.title, 728, 15, 1.07), subLines = f.subtitle ? wrapPx(f.subtitle, 728, 12) : [];
214
+ const headerHeight = 18 + titleLines.length * 19 + (subLines.length ? subLines.length * 16 + 2 : 0) + 4;
215
+ const header = () => titleLines.map((l, i) => el("text", { x: 16, y: 26 + i * 19, "font-size": 15, "font-weight": 600, fill: c.ink }, l)).join("") + subLines.map((l, i) => el("text", { x: 16, y: 26 + titleLines.length * 19 + 2 + i * 16, "font-size": 12, fill: c.muted }, l)).join("");
216
+ const noteLines = f.note ? wrapPx(f.note, 728, 11.5) : [];
217
+ const note = (y) => noteLines.map((l, i) => el("text", { x: 16, y: y + i * 15, "font-size": 11.5, fill: c.muted }, l)).join("");
218
+ const noteHeight = noteLines.length ? noteLines.length * 15 + 6 : 0;
219
+ const gridY = (x0, x1, yOf, min, max) => {
220
+ let out = "";
221
+ for (let i = 0; i <= 4; i++) {
222
+ const v = min + (max - min) * i / 4, y = yOf(v);
223
+ out += el("line", { x1: x0, x2: x1, y1: y, y2: y, stroke: i ? c.grid : c.axis, "stroke-width": 1 }) + el("text", { x: x0 - 8, y: y + 4, "font-size": 11, fill: c.muted, "text-anchor": "end" }, fmt(v));
224
+ }
225
+ return out;
226
+ };
227
+ const seriesFills = (series, stacked) => {
228
+ const seen = /* @__PURE__ */ new Map(), defs = [];
229
+ const fills = series.map((s, j) => {
230
+ const base = tone2(s.tone, j === 0 ? c.accent : c.grey), n = seen.get(base) ?? 0;
231
+ seen.set(base, n + 1);
232
+ if (!stacked || !n) return base;
233
+ const id = `hatch-${j}`, size = 5 + n;
234
+ defs.push(`<pattern id="${id}" width="${size}" height="${size}" patternUnits="userSpaceOnUse" patternTransform="rotate(${n % 2 ? 45 : 135})"><rect width="${size}" height="${size}" fill="${h2(c.bg ?? "#ffffff")}"/><rect width="${Math.ceil(size / 2)}" height="${size}" fill="${h2(base)}"/></pattern>`);
235
+ return `url(#${id})`;
236
+ });
237
+ return { fills, defs: defs.length ? `<defs>${defs.join("")}</defs>` : "" };
238
+ };
239
+ const legend2 = (series, x, y, fills) => {
240
+ let out = "";
241
+ series.forEach((s, j) => {
242
+ out += el("rect", { x, y: y - 9, width: 12, height: 12, rx: 2, fill: fills[j], stroke: fills[j].startsWith("url(") ? tone2(s.tone, j === 0 ? c.accent : c.grey) : null, "stroke-width": fills[j].startsWith("url(") ? 1 : null }) + el("text", { x: x + 17, y: y + 1, "font-size": 11.5, fill: c.body }, s.name);
243
+ x += 17 + textWidth(s.name, 11.5) + 18;
244
+ });
245
+ return out;
246
+ };
247
+ if (f.kind === "dots") {
248
+ const cats = f.categories, vals = f.values, rowH = f.rowHeight ?? 24, labelW = f.labelWidth ?? 220;
249
+ const y02 = headerHeight + 6, all2 = [...vals, ...f.reference ? [f.reference.value] : []];
250
+ const max = f.max ?? nice(Math.max(0, ...all2)), min = f.min ?? Math.min(0, ...all2);
251
+ const x0 = labelW + 16, x1 = W - 70, xOf = (v) => x0 + (x1 - x0) * (v - min) / (max - min || 1), r = Math.max(3.5, Math.min(7, rowH / 2 - 4));
252
+ let body2 = header();
253
+ body2 += el("line", { x1: x0, x2: x0, y1: y02, y2: y02 + cats.length * rowH, stroke: c.axis });
254
+ cats.forEach((cat, i) => {
255
+ const y = y02 + i * rowH, cy = y + rowH / 2, v = vals[i], cx = xOf(Math.min(max, Math.max(min, v))), t = f.tones?.[i] ?? (f.highlight?.includes(i) ? "accent" : "grey");
256
+ body2 += el("text", { x: x0 - 10, y: cy + 4, "font-size": 12.5, fill: c.body, "text-anchor": "end" }, fit(cat, labelW - 4, 12.5));
257
+ body2 += el("line", { x1: x0, x2: cx, y1: cy, y2: cy, stroke: c.grid, "stroke-width": 1.5 });
258
+ body2 += el("circle", { cx, cy, r: t === "grey" || t === "muted" ? r : r + 1.5, fill: tone2(t) });
259
+ body2 += el("text", { x: cx + r + 6, y: cy + 4, "font-size": 12, fill: c.ink, "font-weight": 600 }, fmt(v));
260
+ });
261
+ let H2 = y02 + cats.length * rowH + 8;
262
+ if (f.reference) {
263
+ const rx = xOf(f.reference.value);
264
+ body2 += el("line", { x1: rx, x2: rx, y1: y02, y2: H2 - 8, stroke: c.axis, "stroke-dasharray": "4 3" }) + el("text", { x: Math.max(16, Math.min(rx + 4, W - 16 - textWidth(f.reference.label ?? "", 11))), y: H2 + 6, "font-size": 11, fill: c.muted }, f.reference.label ?? "");
265
+ H2 += 14;
266
+ }
267
+ if (noteLines.length) {
268
+ body2 += note(H2 + 10);
269
+ H2 += 10 + noteHeight;
270
+ }
271
+ return { svg: body2, height: H2 + 8 };
272
+ }
273
+ if (f.kind === "hbar") {
274
+ const cats = f.categories, vals = f.values, rowH = f.rowHeight ?? 28, labelW = f.labelWidth ?? 220;
275
+ const y02 = headerHeight + 6, all2 = [...vals, ...f.reference ? [f.reference.value] : []];
276
+ const max = nice(Math.max(0, ...all2)), minv = Math.min(0, ...all2), min = minv < 0 ? -nice(-minv) : 0;
277
+ const x0 = labelW + 16, x1 = W - 70, xOf = (v) => x0 + (x1 - x0) * (v - min) / (max - min), xz = xOf(0);
278
+ let body2 = header();
279
+ cats.forEach((cat, i) => {
280
+ const y = y02 + i * rowH, v = vals[i], t = f.tones?.[i] ?? (f.highlight?.includes(i) ? "accent" : "grey");
281
+ const xa = Math.min(xz, xOf(v)), xb = Math.max(xz, xOf(v));
282
+ body2 += el("text", { x: x0 - 10, y: y + rowH / 2 + 4, "font-size": 12.5, fill: c.body, "text-anchor": "end" }, fit(cat, labelW - 4, 12.5));
283
+ body2 += el("rect", { x: xa, y: y + 6, width: Math.max(0, xb - xa), height: Math.max(1, rowH - 12), rx: 3, fill: tone2(t), "fill-opacity": t === "grey" ? 1 : 0.85 });
284
+ body2 += el("text", { x: v < 0 ? xa - 6 : xb + 6, y: y + rowH / 2 + 4, "font-size": 12, fill: c.ink, "font-weight": 600, "text-anchor": v < 0 ? "end" : "start" }, fmt(v));
285
+ });
286
+ let H2 = y02 + cats.length * rowH + 8;
287
+ if (min < 0) body2 += el("line", { x1: xz, x2: xz, y1: y02, y2: H2 - 8, stroke: c.axis });
288
+ if (f.reference) {
289
+ const rx = xOf(f.reference.value);
290
+ body2 += el("line", { x1: rx, x2: rx, y1: y02, y2: H2 - 8, stroke: c.axis, "stroke-dasharray": "4 3" }) + el("text", { x: rx + 4, y: H2 + 6, "font-size": 11, fill: c.muted }, f.reference.label ?? "");
291
+ H2 += 14;
292
+ }
293
+ if (noteLines.length) {
294
+ body2 += note(H2 + 10);
295
+ H2 += 10 + noteHeight;
296
+ }
297
+ return { svg: body2, height: H2 + 8 };
298
+ }
299
+ if (f.kind === "bar" || f.kind === "grouped" || f.kind === "stacked") {
300
+ const cats = f.categories, S = f.series, stacked = f.kind === "stacked", H2 = f.height ?? 300, top = headerHeight + (S.length > 1 ? 24 : 10);
301
+ const x0 = 56, x1 = W - 16, yb = H2 - 30;
302
+ const totals = cats.map((_, i) => stacked ? S.reduce((a, s) => a + (s.values[i] ?? 0), 0) : Math.max(0, ...S.map((s) => s.values[i] ?? 0)));
303
+ const max = nice(Math.max(0, ...totals, ...f.reference ? [f.reference.value] : []));
304
+ const yOf = (v) => yb - (yb - top) * v / max;
305
+ const { fills, defs } = seriesFills(S, stacked);
306
+ let body2 = defs + header() + gridY(x0, x1, yOf, 0, max);
307
+ const band = (x1 - x0) / cats.length, inner = band * 0.72, bw = stacked ? inner : inner / S.length;
308
+ cats.forEach((cat, i) => {
309
+ const bx = x0 + i * band + (band - inner) / 2;
310
+ let acc = 0;
311
+ S.forEach((s, j) => {
312
+ const v = s.values[i] ?? 0, t = fills[j];
313
+ const y = stacked ? yOf(acc + v) : yOf(v), hgt = stacked ? yOf(acc) - yOf(acc + v) : yb - yOf(v);
314
+ if (!stacked || v > 0) body2 += el("rect", { x: stacked ? bx : bx + j * bw, y, width: Math.max(1, stacked ? bw : bw - 3), height: Math.max(0, hgt), rx: stacked ? 0 : 2, fill: t, "fill-opacity": stacked ? null : 0.9, stroke: stacked ? c.bg ?? "#ffffff" : null, "stroke-width": stacked ? 0.75 : null });
315
+ if (!stacked && cats.length <= 12) body2 += el("text", { x: bx + j * bw + (bw - 3) / 2, y: y - 5, "font-size": 11, fill: c.ink, "text-anchor": "middle" }, fmt(v));
316
+ acc += v;
317
+ });
318
+ if (stacked) body2 += el("text", { x: bx + inner / 2, y: yOf(acc) - 5, "font-size": 11, fill: c.ink, "text-anchor": "middle" }, fmt(acc));
319
+ body2 += el("text", { x: bx + inner / 2, y: yb + 16, "font-size": 11.5, fill: c.muted, "text-anchor": "middle" }, fit(cat, band, 11.5));
320
+ });
321
+ if (f.reference) {
322
+ const ry = yOf(f.reference.value);
323
+ body2 += el("line", { x1: x0, x2: x1, y1: ry, y2: ry, stroke: c.bad, "stroke-dasharray": "5 4" }) + el("text", { x: x1, y: ry - 5, "font-size": 11, fill: c.bad, "text-anchor": "end" }, f.reference.label ?? "");
324
+ }
325
+ if (S.length > 1) body2 += legend2(S, 16, top - 10, fills);
326
+ body2 += note(H2 + 32);
327
+ return { svg: body2, height: H2 + 40 + noteHeight };
328
+ }
329
+ if (f.kind === "line") {
330
+ const cats = f.categories, S = f.series, H2 = f.height ?? 300, top = headerHeight + (S.length > 1 ? 24 : 10);
331
+ const x0 = 56, x1 = W - 90, yb = H2 - 30;
332
+ const all2 = S.flatMap((s) => s.values.filter((v) => v !== null));
333
+ if (f.reference) all2.push(f.reference.value);
334
+ const max = f.max ?? nice(Math.max(0, ...all2)), min = f.min ?? 0;
335
+ const yOf = (v) => yb - (yb - top) * (v - min) / (max - min), xOf = (i) => x0 + (x1 - x0) * (cats.length === 1 ? 0.5 : i / (cats.length - 1));
336
+ let body2 = header() + gridY(x0, x1, yOf, min, max);
337
+ const every = Math.ceil(cats.length / 12);
338
+ cats.forEach((cat, i) => {
339
+ if (cats.length <= 14 || i % every === 0) body2 += el("text", { x: xOf(i), y: yb + 16, "font-size": 11.5, fill: c.muted, "text-anchor": "middle" }, fit(cat, (x1 - x0) / Math.max(1, cats.length - 1) * (cats.length <= 14 ? 1 : every), 11.5));
340
+ });
341
+ if (f.reference) {
342
+ const ry = yOf(f.reference.value);
343
+ body2 += el("line", { x1: x0, x2: x1, y1: ry, y2: ry, stroke: c.axis, "stroke-dasharray": "5 4" }) + el("text", { x: x1 + 6, y: ry + 4, "font-size": 11, fill: c.muted }, f.reference.label ?? "");
344
+ }
345
+ S.forEach((s, j) => {
346
+ const t = tone2(s.tone, j === 0 ? c.accent : c.grey);
347
+ let d = "", last = null, pen = false;
348
+ s.values.forEach((v, i) => {
349
+ if (v === null) {
350
+ pen = false;
351
+ return;
352
+ }
353
+ d += `${pen ? " L " : d ? " M " : "M "}${Math.round(xOf(i) * 100) / 100} ${Math.round(yOf(v) * 100) / 100}`;
354
+ pen = true;
355
+ last = i;
356
+ });
357
+ if (d) body2 += el("path", { d, fill: "none", stroke: t, "stroke-width": 2.25, "stroke-linejoin": "round" });
358
+ s.values.forEach((v, i) => {
359
+ if (v !== null) body2 += el("circle", { cx: xOf(i), cy: yOf(v), r: 3.2, fill: t });
360
+ });
361
+ if (last !== null) body2 += el("text", { x: xOf(last) + 8, y: yOf(s.values[last]) + 4, "font-size": 11.5, fill: t, "font-weight": 600 }, fmt(s.values[last]) + (S.length > 1 ? " " + s.name : ""));
362
+ });
363
+ if (S.length > 1) body2 += legend2(S, 16, top - 10, seriesFills(S, false).fills);
364
+ body2 += note(H2 + 32);
365
+ return { svg: body2, height: H2 + 40 + noteHeight };
366
+ }
367
+ if (f.kind === "matrix") {
368
+ const rows = f.rows, cols = f.cols, grid = f.matrix, lw = f.labelWidth ?? 150, cw2 = (W - lw - 24) / cols.length, rh = f.rowHeight ?? 30;
369
+ const y02 = headerHeight + 8, maxv = Math.max(0, ...grid.flat().map((v) => v ?? 0));
370
+ let body2 = header();
371
+ cols.forEach((col, j) => {
372
+ body2 += el("text", { x: lw + 16 + j * cw2 + cw2 / 2, y: y02 + 14, "font-size": 11.5, fill: c.body, "text-anchor": "middle" }, fit(col, cw2 - 4, 11.5));
373
+ });
374
+ rows.forEach((r, i) => {
375
+ const y = y02 + 24 + i * rh;
376
+ body2 += el("text", { x: lw + 8, y: y + rh / 2 + 4, "font-size": 12.5, fill: c.body, "text-anchor": "end" }, fit(r, lw + 4, 12.5));
377
+ cols.forEach((_, j) => {
378
+ const v = grid[i][j], x = lw + 16 + j * cw2, op = v === null || v === 0 ? 0 : 0.15 + 0.75 * (v / (maxv || 1));
379
+ const ct = f.cellTones?.[i]?.[j] ?? f.rowTones?.[i] ?? f.colTones?.[j] ?? "accent";
380
+ body2 += el("rect", { x: x + 2, y: y + 2, width: cw2 - 4, height: rh - 4, rx: 3, fill: tone2(ct), "fill-opacity": op, stroke: c.grid });
381
+ if (v !== null && v !== void 0) body2 += el("text", { x: x + cw2 / 2, y: y + rh / 2 + 4, "font-size": 12, "font-weight": 600, fill: v === 0 ? c.muted : op > 0.55 ? "#ffffff" : c.ink, "text-anchor": "middle" }, fmt(v));
382
+ });
383
+ });
384
+ let H2 = y02 + 24 + rows.length * rh + 12;
385
+ if (noteLines.length) {
386
+ body2 += note(H2 + 6);
387
+ H2 += 6 + noteHeight;
388
+ }
389
+ return { svg: body2, height: H2 };
390
+ }
391
+ const columns = f.columns, nC = columns.length, gap = 40, cw = (W - 32 - gap * (nC - 1)) / nC, vg = 14;
392
+ const maxSub = Math.max(1, ...columns.flatMap((col) => col.nodes.map((n) => n.sub?.length ?? 0)));
393
+ const nh = f.nodeHeight ?? 28 + 13 * maxSub + 8, maxN = Math.max(...columns.map((col) => col.nodes.length));
394
+ const y0 = headerHeight + 8, pos = /* @__PURE__ */ new Map();
395
+ const used = /* @__PURE__ */ new Set([...(f.edges ?? []).map((e) => e.tone ?? "grey")]);
396
+ let body = header();
397
+ body += `<defs>${[...used].map((t) => `<marker id="arr-${h2(t)}" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse"><path d="M0 0L10 5L0 10z" fill="${h2(tone2(t, c.grey))}"/></marker>`).join("")}</defs>`;
398
+ columns.forEach((col, j) => {
399
+ const x = 16 + j * (cw + gap);
400
+ if (col.title) body += el("text", { x, y: y0 + 12, "font-size": 11, "font-weight": 600, fill: c.muted }, fit(col.title.toUpperCase(), cw, 11));
401
+ const colH = col.nodes.length * (nh + vg) - vg, yStart = y0 + 24 + (maxN * (nh + vg) - vg - colH) / 2;
402
+ col.nodes.forEach((n, i) => {
403
+ const y = yStart + i * (nh + vg), t = n.tone ? tone2(n.tone) : null;
404
+ body += el("rect", { x, y, width: cw, height: nh, rx: 8, fill: t ?? "none", "fill-opacity": t ? 0.1 : 1, stroke: t ?? c.axis, "stroke-width": t ? 2 : 1.25, "stroke-dasharray": n.dashed ? "6 4" : null });
405
+ body += el("text", { x: x + 12, y: y + 21, "font-size": 12.5, "font-weight": 600, fill: c.ink }, fit(n.label, cw - 24, 12.5));
406
+ (n.sub ?? []).forEach((s, k) => {
407
+ body += el("text", { x: x + 12, y: y + 37 + k * 13, "font-size": 10.5, fill: c.muted }, fit(s, cw - 24, 10.5));
408
+ });
409
+ pos.set(n.id, { l: x, r: x + cw, y: y + nh / 2 });
410
+ });
411
+ });
412
+ (f.edges ?? []).forEach((e) => {
413
+ const a = pos.get(e.from), b = pos.get(e.to), t = e.tone ?? "grey", mx = (a.r + b.l) / 2, color = tone2(t, c.grey);
414
+ body += el("path", { d: `M ${a.r} ${a.y} C ${mx} ${a.y}, ${mx} ${b.y}, ${b.l} ${b.y}`, fill: "none", stroke: color, "stroke-width": 1.75, "stroke-dasharray": e.dashed ? "6 4" : null, "marker-end": `url(#arr-${t})` });
415
+ if (e.label) body += el("text", { x: mx, y: (a.y + b.y) / 2 - 6, "font-size": 10.5, fill: color, "text-anchor": "middle" }, e.label);
416
+ });
417
+ let H = y0 + 24 + maxN * (nh + vg) - vg + 12;
418
+ if (noteLines.length) {
419
+ body += note(H + 6);
420
+ H += 6 + noteHeight;
421
+ }
422
+ return { svg: body, height: H };
423
+ }
424
+ function figureSvg(node, report, options = {}) {
425
+ const t = themeTokens2(options.theme ?? report.theme), s = semanticColors(t);
426
+ const colors = { ink: s.ink, body: t.text, muted: t.muted, accent: t.accent, grey: s.grey, grid: s.grid, axis: s.axis, ok: s.ok, warn: s.warn, bad: s.bad, bg: t.background };
427
+ const f = node.props.figure;
428
+ const { svg, height } = draw(f, colors, report.locale);
429
+ const h22 = Math.ceil(height);
430
+ return `<svg xmlns="http://www.w3.org/2000/svg" role="img" aria-label="${h2(node.props.alt)}" viewBox="0 0 ${W} ${h22}" width="${W}" height="${h22}" font-family="${h2(t.fontFamily)}">${svg}</svg>`;
431
+ }
432
+
433
+ // packages/reportic-render-html/src/kit-chart.ts
434
+ import { AXIS_FONT_SIZE, TICK_PADDING, TICK_SIZE, buildChartModel, describeChart, isOpenMarker, layoutChart, markerPath, modelToTable } from "@x12i/charts";
435
+ import { escapeHtml as h3, semanticColors as semanticColors2, themeTokens as themeTokens3 } from "@x12i/reportic-core";
436
+ var MIDDLE_OFFSET = 4;
437
+ var TALL = /* @__PURE__ */ new Set(["sankey", "timeline", "gantt", "architecture", "swimlane", "network-map", "screen-frame", "cell-table", "chain-cards", "treemap"]);
438
+ var ORDER = { area: 0, bar: 1, cell: 1, arc: 1, connector: 2, stem: 2, line: 3, point: 4 };
439
+ function chartHeight(mark) {
440
+ if (mark === "sparkline") return 48;
441
+ if (mark === "gauge" || mark === "progress-ring") return 220;
442
+ if (TALL.has(mark)) return 420;
443
+ return 320;
444
+ }
445
+ function hex(input) {
446
+ const s = input.replace("#", "");
447
+ const full = s.length <= 4 ? s.slice(0, 3).split("").map((c) => c + c).join("") : s.slice(0, 6);
448
+ return "#" + full;
449
+ }
450
+ function rgb(color) {
451
+ const h5 = hex(color).slice(1);
452
+ return [0, 2, 4].map((i) => parseInt(h5.slice(i, i + 2), 16));
453
+ }
454
+ function mix(from, to, t) {
455
+ const a = rgb(from), b = rgb(to), u = Math.min(1, Math.max(0, t));
456
+ return "#" + a.map((v, i) => Math.round(v + (b[i] - v) * u).toString(16).padStart(2, "0")).join("");
457
+ }
458
+ function toneColor(tone2, paint) {
459
+ switch (tone2) {
460
+ case "accent":
461
+ return paint.accent;
462
+ case "muted":
463
+ return paint.muted;
464
+ case "reference":
465
+ return paint.grey;
466
+ case "good":
467
+ return paint.ok;
468
+ case "warning":
469
+ return paint.warn;
470
+ case "critical":
471
+ return paint.bad;
472
+ default: {
473
+ const slot = Number(String(tone2).replace("categorical-", "")) - 1;
474
+ return paint.palette[(Number.isFinite(slot) && slot >= 0 ? slot : 0) % paint.palette.length] ?? paint.accent;
475
+ }
476
+ }
477
+ }
478
+ function rampColor(kind, t, paint) {
479
+ const u = Math.min(1, Math.max(0, t ?? 0));
480
+ if (kind === "diverging") return u < 0.5 ? mix(paint.bad, paint.grey, u * 2) : mix(paint.grey, paint.ok, (u - 0.5) * 2);
481
+ return mix(paint.muted, paint.accent, u);
482
+ }
483
+ var num = (v) => Number.isFinite(v) ? String(Math.round(v * 100) / 100) : "0";
484
+ var rtl = /[\u0590-\u08FF\uFB1D-\uFDFF\uFE70-\uFEFF]/;
485
+ function textDir(text2, numeric) {
486
+ const flip = !numeric && rtl.test(text2);
487
+ return { direction: flip ? "rtl" : "ltr", flip };
488
+ }
489
+ function anchorOf(anchor, flip) {
490
+ if (!flip) return anchor;
491
+ return anchor === "start" ? "end" : anchor === "end" ? "start" : anchor;
492
+ }
493
+ var PATTERN_BODY = {
494
+ 0: { size: 6, body: (c) => `<path d="M-1,1L1,-1M0,6L6,0M5,7L7,5" stroke="${c}" fill="none" stroke-width="1"/>` },
495
+ 1: { size: 6, body: (c) => `<path d="M-1,5L1,7M0,0L6,6M5,-1L7,1" stroke="${c}" fill="none" stroke-width="1"/>` },
496
+ 2: { size: 6, body: (c) => `<circle cx="3" cy="3" r="1" fill="${c}"/>` },
497
+ 3: { size: 6, body: (c) => `<path d="M0,3H6" stroke="${c}" fill="none" stroke-width="1"/>` },
498
+ 4: { size: 6, body: (c) => `<path d="M3,0V6" stroke="${c}" fill="none" stroke-width="1"/>` },
499
+ 5: { size: 6, body: (c) => `<path d="M0,3H6M3,0V6" stroke="${c}" fill="none" stroke-width="1"/>` },
500
+ 6: { size: 8, body: (c) => `<path d="M-1,1L1,-1M0,8L8,0M7,9L9,7" stroke="${c}" fill="none" stroke-width="1"/>` },
501
+ 7: { size: 6, body: (c) => `<rect x="0" y="0" width="3" height="3" fill="${c}"/><rect x="3" y="3" width="3" height="3" fill="${c}"/>` }
502
+ };
503
+ function patternDefs(indices, color, prefix) {
504
+ return indices.map((index) => {
505
+ const tile = PATTERN_BODY[index % 8] ?? PATTERN_BODY[0];
506
+ return `<pattern id="${prefix}-p${index}" patternUnits="userSpaceOnUse" width="${tile.size}" height="${tile.size}">${tile.body(color)}</pattern>`;
507
+ }).join("");
508
+ }
509
+ function axes(layout, paint) {
510
+ return layout.axes.map((axis) => {
511
+ const vertical = axis.orient === "left" || axis.orient === "right";
512
+ const sign = axis.orient === "left" || axis.orient === "top" ? -1 : 1;
513
+ const ticks = axis.ticks.filter((tick) => tick.visible).map((tick) => {
514
+ const tickLine = vertical ? { x1: axis.line.x1, y1: tick.position, x2: axis.line.x1 + sign * TICK_SIZE, y2: tick.position } : { x1: tick.position, y1: axis.line.y1, x2: tick.position, y2: axis.line.y1 + sign * TICK_SIZE };
515
+ const gap = TICK_SIZE + TICK_PADDING;
516
+ let x, y;
517
+ if (vertical) {
518
+ x = axis.line.x1 + sign * gap;
519
+ y = tick.position + MIDDLE_OFFSET;
520
+ } else {
521
+ x = tick.position;
522
+ y = axis.line.y1 + sign * gap + (sign > 0 ? axis.labelAngle === 0 ? AXIS_FONT_SIZE * 0.8 : AXIS_FONT_SIZE * 0.35 : 0);
523
+ }
524
+ const text2 = String(tick.label);
525
+ const dir = textDir(text2, axis.numeric);
526
+ const grid = axis.grid ? vertical ? `<line x1="${num(layout.plot.x)}" y1="${num(tick.position)}" x2="${num(layout.plot.x + layout.plot.width)}" y2="${num(tick.position)}" stroke="${paint.border}" stroke-width="1"/>` : `<line x1="${num(tick.position)}" y1="${num(layout.plot.y)}" x2="${num(tick.position)}" y2="${num(layout.plot.y + layout.plot.height)}" stroke="${paint.border}" stroke-width="1"/>` : "";
527
+ const rotate = axis.labelAngle !== 0 && !vertical ? ` transform="rotate(${axis.labelAngle} ${num(x)} ${num(y)})"` : "";
528
+ return `${grid}<line x1="${num(tickLine.x1)}" y1="${num(tickLine.y1)}" x2="${num(tickLine.x2)}" y2="${num(tickLine.y2)}" stroke="${paint.muted}" stroke-width="1"/><text x="${num(x)}" y="${num(y)}" text-anchor="${anchorOf(axis.labelAnchor, dir.flip)}" direction="${dir.direction}" fill="${paint.muted}" font-size="${AXIS_FONT_SIZE}"${rotate}>${h3(text2)}</text>`;
529
+ }).join("");
530
+ const spine = axis.id === "x" ? `<line x1="${num(axis.line.x1)}" y1="${num(axis.line.y1)}" x2="${num(axis.line.x2)}" y2="${num(axis.line.y2)}" stroke="${paint.muted}" stroke-width="1"/>` : "";
531
+ const title = axis.title && axis.titlePosition ? `<text x="${num(axis.titlePosition.x)}" y="${num(axis.titlePosition.y)}" text-anchor="middle" fill="${paint.text}" font-size="${AXIS_FONT_SIZE}"${axis.titlePosition.rotate ? ` transform="rotate(${axis.titlePosition.rotate} ${num(axis.titlePosition.x)} ${num(axis.titlePosition.y)})"` : ""}>${h3(axis.title)}</text>` : "";
532
+ return `${spine}${ticks}${title}`;
533
+ }).join("");
534
+ }
535
+ function marks(layout, paint, prefix) {
536
+ return [...layout.marks].sort((a, b) => ORDER[a.kind] - ORDER[b.kind]).map((mark) => {
537
+ const color = mark.kind === "cell" ? rampColor(mark.ramp, mark.t, paint) : mark.role === "track" ? paint.border : toneColor(mark.tone, paint);
538
+ const opacity = mark.muted ? ' opacity="0.4"' : "";
539
+ const overlay = mark.pattern >= 0 ? ` fill="url(#${prefix}-p${mark.pattern})"` : "";
540
+ if (mark.kind === "bar" || mark.kind === "cell") {
541
+ if (![mark.x, mark.y, mark.width, mark.height].every((v) => Number.isFinite(v))) return "";
542
+ const rect = `<rect x="${num(mark.x)}" y="${num(mark.y)}" width="${num(mark.width)}" height="${num(mark.height)}" fill="${color}"${opacity}/>`;
543
+ return overlay ? `${rect}<rect x="${num(mark.x)}" y="${num(mark.y)}" width="${num(mark.width)}" height="${num(mark.height)}"${overlay}/>` : rect;
544
+ }
545
+ if (mark.kind === "area" || mark.kind === "arc" || mark.kind === "line") {
546
+ if (!mark.d) return "";
547
+ const fill = mark.kind === "line" ? "none" : color;
548
+ const stroke = mark.kind === "line" ? color : "none";
549
+ const dash = mark.dash ? ` stroke-dasharray="${h3(mark.dash)}"` : "";
550
+ const path = `<path d="${h3(mark.d)}" fill="${fill}" stroke="${stroke}" stroke-width="${mark.kind === "line" ? 2 : 0}"${dash}${opacity}/>`;
551
+ return overlay && mark.kind !== "line" ? `${path}<path d="${h3(mark.d)}"${overlay}/>` : path;
552
+ }
553
+ if (mark.kind === "stem" || mark.kind === "connector") {
554
+ if (![mark.x1, mark.y1, mark.x2, mark.y2].every((v) => Number.isFinite(v))) return "";
555
+ return `<line x1="${num(mark.x1)}" y1="${num(mark.y1)}" x2="${num(mark.x2)}" y2="${num(mark.y2)}" stroke="${color}" stroke-width="1.5"${opacity}/>`;
556
+ }
557
+ const shape = mark.shape ?? "circle";
558
+ if (shape === "circle") return `<circle cx="${num(mark.cx)}" cy="${num(mark.cy)}" r="${num(mark.r)}" fill="${color}"${opacity}/>`;
559
+ const d = markerPath(shape, mark.cx ?? 0, mark.cy ?? 0, mark.r ?? 4);
560
+ return isOpenMarker(shape) ? `<path d="${h3(d)}" fill="none" stroke="${color}" stroke-width="1.5"${opacity}/>` : `<path d="${h3(d)}" fill="${color}"${opacity}/>`;
561
+ }).join("");
562
+ }
563
+ function annotations(layout, paint) {
564
+ return layout.annotations.map((note) => {
565
+ const color = toneColor(note.tone, paint);
566
+ if ((note.kind === "band" || note.kind === "forecast") && note.box) return `<rect x="${num(note.box.x)}" y="${num(note.box.y)}" width="${num(note.box.width)}" height="${num(note.box.height)}" fill="${color}" opacity="0.15"/>`;
567
+ if (note.kind === "line") return `<line x1="${num(note.x1)}" y1="${num(note.y1)}" x2="${num(note.x2)}" y2="${num(note.y2)}" stroke="${color}" stroke-width="1" stroke-dasharray="4 3"/>`;
568
+ if (note.kind === "point") return `<circle cx="${num(note.cx)}" cy="${num(note.cy)}" r="5" fill="${color}"/>`;
569
+ return "";
570
+ }).join("");
571
+ }
572
+ function labels(layout, paint) {
573
+ const all2 = [...layout.labels, ...layout.annotations.map((note) => note.label).filter((label) => !!label)];
574
+ return all2.map((label) => {
575
+ const dir = textDir(label.text, label.numeric);
576
+ const dy = label.baseline === "above" ? -3 : label.baseline === "below" ? 11 : 4;
577
+ const fill = label.tone ? toneColor(label.tone, paint) : paint.text;
578
+ return `<text x="${num(label.x)}" y="${num(label.y + dy)}" text-anchor="${anchorOf(label.anchor, dir.flip)}" direction="${dir.direction}" fill="${fill}" font-size="11">${h3(label.text)}</text>`;
579
+ }).join("");
580
+ }
581
+ function legend(layout, paint, y) {
582
+ const entries = layout.legend.filter((entry) => entry.visible);
583
+ if (!entries.length) return "";
584
+ const gap = layout.width / Math.max(entries.length, 1);
585
+ return entries.map((entry, index) => {
586
+ const color = toneColor(entry.tone, paint);
587
+ const x = 16 + index * Math.min(gap, 160);
588
+ const glyph2 = entry.glyph === "line" || entry.glyph === "area" ? `<line x1="${num(x)}" y1="${num(y)}" x2="${num(x + 16)}" y2="${num(y)}" stroke="${color}" stroke-width="2"/>` : `<rect x="${num(x)}" y="${num(y - 6)}" width="12" height="12" fill="${color}"/>`;
589
+ return `${glyph2}<text x="${num(x + 20)}" y="${num(y + 4)}" fill="${paint.text}" font-size="11">${h3(entry.label)}</text>`;
590
+ }).join("");
591
+ }
592
+ function colorScale(layout, paint, y) {
593
+ const scale = layout.colorScale;
594
+ if (!scale) return "";
595
+ const steps = 9;
596
+ const width = 140;
597
+ const bars = Array.from({ length: steps }, (_, i) => `<rect x="${num(16 + width / steps * i)}" y="${num(y)}" width="${num(width / steps + 0.5)}" height="8" fill="${rampColor(scale.kind, i / (steps - 1), paint)}"/>`).join("");
598
+ return `${bars}<text x="${num(16 + width + 8)}" y="${num(y + 8)}" fill="${paint.muted}" font-size="11">${h3(String(scale.min))} \u2013 ${h3(String(scale.max))}</text>`;
599
+ }
600
+ function paintChart(layout, paint, prefix) {
601
+ const showLegend = layout.legend.some((entry) => entry.visible);
602
+ const extra = (showLegend ? 28 : 0) + (layout.colorScale ? 24 : 0);
603
+ const height = layout.height + extra;
604
+ const font = "sans-serif";
605
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${layout.width}" height="${height}" viewBox="0 0 ${layout.width} ${height}" role="img" font-family="${font}"><rect width="100%" height="100%" fill="${paint.background}"/><defs>${patternDefs(layout.patterns, paint.text, prefix)}</defs>${axes(layout, paint)}${annotations(layout, paint)}${marks(layout, paint, prefix)}${labels(layout, paint)}${legend(layout, paint, layout.height + 16)}${colorScale(layout, paint, layout.height + (showLegend ? 28 : 8))}</svg>`;
606
+ }
607
+ function colorsOf(tokens) {
608
+ const semantic = semanticColors2(tokens);
609
+ return { accent: tokens.accent, text: tokens.text, muted: tokens.muted, border: tokens.border, background: tokens.background, ok: semantic.ok, warn: semantic.warn, bad: semantic.bad, grey: semantic.grey, palette: tokens.chartPalette };
610
+ }
611
+ function specOf(node) {
612
+ return node.props.spec ? structuredClone(node.props.spec) : void 0;
613
+ }
614
+ function layoutOf(node, report, options) {
615
+ const spec = specOf(node);
616
+ if (!spec || node.props.empty) return void 0;
617
+ const model = buildChartModel(spec);
618
+ if (model.status !== "ok") return void 0;
619
+ const patterns = spec.a11y?.patterns === true || spec.a11y?.patterns === "auto";
620
+ return layoutChart(model, { width: 640, height: chartHeight(spec.mark), patterns, locale: report.locale || options.locale });
621
+ }
622
+ function kitChartSvg(node, report, options = {}) {
623
+ const layout = layoutOf(node, report, options);
624
+ const tokens = themeTokens3(options.theme ?? report.theme);
625
+ if (!layout) {
626
+ const message = h3(node.props.message ?? "No data to display.");
627
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="640" height="80" viewBox="0 0 640 80" role="img"><rect width="100%" height="100%" fill="${tokens.background}"/><text x="24" y="46" fill="${tokens.muted}" font-size="14" font-family="sans-serif">${message}</text></svg>`;
628
+ }
629
+ const prefix = "k" + String(node.occurrenceId).replace(/[^A-Za-z0-9]/g, "");
630
+ return paintChart(layout, colorsOf(tokens), prefix);
631
+ }
632
+ function kitChartTable(node, report) {
633
+ const spec = specOf(node);
634
+ if (!spec || node.props.empty) return { columns: [], cells: [] };
635
+ const model = buildChartModel(spec);
636
+ if (model.status !== "ok") return { columns: [], cells: [] };
637
+ const table = modelToTable(model, { locale: report.locale });
638
+ return { columns: table.columns.map((column) => ({ label: column.label, ...column.numeric ? { align: "right" } : {} })), cells: table.rows.map((row) => row.map((cell) => cell.text)) };
639
+ }
640
+ function kitChartDescription(node, report) {
641
+ const spec = specOf(node);
642
+ if (!spec || node.props.empty) return String(node.props.message ?? "");
643
+ return describeChart(spec, { locale: report.locale }).text;
644
+ }
645
+
646
+ // packages/reportic-render-html/src/import/index.ts
647
+ import { fail as fail3 } from "@x12i/reportic-core";
648
+
649
+ // packages/reportic-render-html/src/import/dom.ts
650
+ import { parse } from "parse5";
651
+ var parseHtml = (html) => parse(html);
652
+ var isEl = (n) => !!n && "tagName" in n;
653
+ var isText = (n) => !!n && n.nodeName === "#text";
654
+ var kids = (n) => "childNodes" in n ? n.childNodes : [];
655
+ var elements = (n) => kids(n).filter(isEl);
656
+ var attr = (el2, name) => el2.attrs.find((a) => a.name === name)?.value;
657
+ var classes = (el2) => (attr(el2, "class") ?? "").split(/\s+/).filter(Boolean);
658
+ var hasClass = (el2, name) => classes(el2).includes(name);
659
+ function textOf(n, keepBreaks = false) {
660
+ const parts = [];
661
+ const visit = (x) => {
662
+ if (isText(x)) parts.push(x.value);
663
+ else if (isEl(x)) {
664
+ if (["script", "style", "template"].includes(x.tagName)) return;
665
+ if (x.tagName === "br") {
666
+ parts.push(keepBreaks ? "\n" : " ");
667
+ return;
668
+ }
669
+ kids(x).forEach(visit);
670
+ }
671
+ };
672
+ visit(n);
673
+ const text2 = parts.join("");
674
+ return keepBreaks ? text2.split("\n").map((l) => l.replace(/\s+/g, " ").trim()).join("\n").trim() : text2.replace(/\s+/g, " ").trim();
675
+ }
676
+ function findAll(n, test, into = []) {
677
+ for (const k of kids(n)) {
678
+ if (isEl(k)) {
679
+ if (test(k)) into.push(k);
680
+ findAll(k, test, into);
681
+ }
682
+ }
683
+ return into;
684
+ }
685
+ var find = (n, test) => {
686
+ for (const k of kids(n)) {
687
+ if (isEl(k)) {
688
+ if (test(k)) return k;
689
+ const inner = find(k, test);
690
+ if (inner) return inner;
691
+ }
692
+ }
693
+ return void 0;
694
+ };
695
+ var child = (n, test) => elements(n).find(test);
696
+ var style = (el2, property) => {
697
+ const match2 = new RegExp(`(?:^|;)\\s*${property}\\s*:\\s*([^;]+)`, "i").exec(attr(el2, "style") ?? "");
698
+ return match2?.[1].trim();
699
+ };
700
+ var json = (el2, name) => {
701
+ const value = attr(el2, name);
702
+ if (value === void 0) return void 0;
703
+ try {
704
+ return JSON.parse(value);
705
+ } catch {
706
+ return void 0;
707
+ }
708
+ };
709
+
710
+ // packages/reportic-render-html/src/import/ctx.ts
711
+ import { createHash } from "crypto";
712
+ var EXTENSION = { "image/png": "png", "image/jpeg": "jpg", "image/gif": "gif", "image/webp": "webp", "image/svg+xml": "svg" };
713
+ var Importer = class {
714
+ notes = [];
715
+ unbound = [];
716
+ assets = {};
717
+ ids = /* @__PURE__ */ new Map();
718
+ hashes = /* @__PURE__ */ new Map();
719
+ count = 0;
720
+ note(code, message, extra = {}, severity = "info") {
721
+ if (!this.notes.some((n) => n.code === code && n.message === message && n.elementId === extra.elementId)) this.notes.push({ code, severity, message, ...extra });
722
+ }
723
+ warn(code, message, extra = {}) {
724
+ this.note(code, message, extra, "warning");
725
+ }
726
+ /** An id that is valid in a template and not used yet. */
727
+ uid(base) {
728
+ let id = (base ?? "").replace(/[^\w.-]+/g, "-").replace(/^[^a-zA-Z]+/, "").replace(/-+$/, "") || "element";
729
+ const n = (this.ids.get(id) ?? 0) + 1;
730
+ this.ids.set(id, n);
731
+ if (n > 1) {
732
+ const next = `${id}-${n}`;
733
+ this.ids.set(next, 1);
734
+ return next;
735
+ }
736
+ return id;
737
+ }
738
+ /** Reads an inline image (a data: URI) and keeps its bytes as a managed asset. Returns its name. */
739
+ asset(src, preferred) {
740
+ const match2 = /^data:([\w.+/-]+)(;[^,]*)?,(.*)$/s.exec(src.trim());
741
+ if (!match2) return void 0;
742
+ const mediaType = match2[1].toLowerCase(), encoded = match2[3];
743
+ if (!EXTENSION[mediaType]) {
744
+ this.warn("IMAGE_TYPE_UNSUPPORTED", `An embedded ${mediaType} image was dropped; use PNG, JPEG, GIF, WebP, or SVG.`);
745
+ return void 0;
746
+ }
747
+ let bytes;
748
+ try {
749
+ bytes = /;base64/i.test(match2[2] ?? "") ? new Uint8Array(Buffer.from(encoded, "base64")) : new Uint8Array(Buffer.from(decodeURIComponent(encoded)));
750
+ } catch {
751
+ return void 0;
752
+ }
753
+ if (!bytes.length) return void 0;
754
+ const hash = createHash("sha1").update(bytes).digest("hex");
755
+ const known = this.hashes.get(hash);
756
+ if (known) return known;
757
+ let name = (preferred ?? `image-${++this.count}`).replace(/[^\w-]/g, "-");
758
+ if (this.assets[name]) name = `${name}-${++this.count}`;
759
+ this.assets[name] = { bytes, mediaType, name: `${name}.${EXTENSION[mediaType]}` };
760
+ this.hashes.set(hash, name);
761
+ return name;
762
+ }
763
+ /** Markdown images: a data URI becomes a managed asset under assets/<name>.<ext>; a link to https is kept; a page-relative file cannot be read. */
764
+ markdown() {
765
+ return {
766
+ note: (code, message) => this.note(code, message),
767
+ image: (src, alt) => {
768
+ if (src.startsWith("data:")) {
769
+ const name = this.asset(src);
770
+ return name ? `assets/${name}.${EXTENSION[this.assets[name].mediaType]}` : void 0;
771
+ }
772
+ if (/^https:\/\//i.test(src)) {
773
+ this.warn("REMOTE_IMAGE", `Image ${src.slice(0, 80)} is a remote link. Rendering it needs allowRemoteImages; embed it to keep the report portable.`);
774
+ return src;
775
+ }
776
+ this.warn("IMAGE_NOT_EMBEDDED", `Image "${src.slice(0, 80)}" is not embedded in the page, so its bytes cannot be imported.`);
777
+ return void 0;
778
+ }
779
+ };
780
+ }
781
+ };
782
+
783
+ // packages/reportic-render-html/src/import/markdown.ts
784
+ var BLOCKS = /* @__PURE__ */ new Set(["h1", "h2", "h3", "h4", "h5", "h6", "p", "ul", "ol", "blockquote", "pre", "hr", "table", "div", "section", "article", "aside", "header", "footer", "main", "nav", "figure", "figcaption", "details", "summary", "dl", "dt", "dd", "address", "fieldset", "form"]);
785
+ var SKIPPED = /* @__PURE__ */ new Set(["script", "style", "noscript", "template", "iframe", "object", "embed", "video", "audio", "canvas", "svg", "form", "button", "select", "textarea", "head", "link", "meta", "title"]);
786
+ var isBlock = (n) => isEl(n) && BLOCKS.has(n.tagName);
787
+ var isSkipped = (n) => isEl(n) && SKIPPED.has(n.tagName);
788
+ function escapeText(s, inTable = false) {
789
+ let out = s.replace(/[\\`*<>~[\]]|_|\|/g, (m, offset) => {
790
+ if (m === "|") return inTable ? "\\|" : m;
791
+ if (m === "_") {
792
+ const before = s[offset - 1] ?? "", after = s[offset + 1] ?? "";
793
+ return /\w/.test(before) && /\w/.test(after) ? m : "\\_";
794
+ }
795
+ return "\\" + m;
796
+ });
797
+ out = out.replace(/&(?=[#\w]+;)/g, "\\&").replace(/\{\{/g, "&#123;&#123;");
798
+ return out;
799
+ }
800
+ var protectLine = (s) => s.replace(/^(\s*)(#{1,6}(?=\s|$)|>|[-+](?=\s)|\d+[.)](?=\s)|={3,}|-{3,})/, "$1\\$2");
801
+ var fence = (text2, char, min = 3) => char.repeat(Math.max(min, ...[...text2.matchAll(new RegExp(`${char === "`" ? "`" : "~"}+`, "g"))].map((m) => m[0].length + 1)));
802
+ var safeHref = (href) => /^(https?:|mailto:|#|\/|\.{0,2}\/|[\w-]+(\/|$))/i.test(href) && !/^(javascript|data|vbscript):/i.test(href) ? href.replace(/ /g, "%20").replace(/\(/g, "%28").replace(/\)/g, "%29") : void 0;
803
+ function inline(nodes, ctx, inTable = false) {
804
+ let out = "";
805
+ for (const n of nodes) {
806
+ if (isText(n)) {
807
+ out += escapeText(n.value.replace(/\s+/g, " "), inTable);
808
+ continue;
809
+ }
810
+ if (!isEl(n) || SKIPPED.has(n.tagName)) continue;
811
+ const inner = () => inline(kids(n), ctx, inTable);
812
+ switch (n.tagName) {
813
+ case "br":
814
+ out += inTable ? " " : "\\\n";
815
+ break;
816
+ case "strong":
817
+ case "b": {
818
+ const t = inner().trim();
819
+ if (t) out += `**${t}**`;
820
+ break;
821
+ }
822
+ case "em":
823
+ case "i": {
824
+ const t = inner().trim();
825
+ if (t) out += `*${t}*`;
826
+ break;
827
+ }
828
+ case "del":
829
+ case "s":
830
+ case "strike": {
831
+ const t = inner().trim();
832
+ if (t) out += `~~${t}~~`;
833
+ break;
834
+ }
835
+ case "code":
836
+ case "kbd":
837
+ case "samp":
838
+ case "tt": {
839
+ const raw = textOf(n);
840
+ if (!raw) break;
841
+ const text2 = raw.replace(/\{\{/g, "{\u200B{");
842
+ if (text2 !== raw) ctx.note("BRACES_SEPARATED", "Two braces in inline code were separated with a zero-width space so a template does not read them as an expression.");
843
+ const ticks = fence(text2, "`", 1);
844
+ out += `${ticks}${/^`|`$/.test(text2) ? ` ${text2} ` : text2}${ticks}`;
845
+ break;
846
+ }
847
+ case "a": {
848
+ const href = attr(n, "href"), label = inner().trim(), safe = href === void 0 ? void 0 : safeHref(href.trim());
849
+ if (!label) break;
850
+ out += safe ? `[${label}](${safe})` : label;
851
+ break;
852
+ }
853
+ case "img": {
854
+ const src = attr(n, "src"), alt = attr(n, "alt") ?? "";
855
+ const path = src ? ctx.image(src, alt) : void 0;
856
+ if (path) out += `![${escapeText(alt)}](${path})`;
857
+ else if (alt) out += escapeText(alt);
858
+ break;
859
+ }
860
+ case "input":
861
+ break;
862
+ default:
863
+ out += inner();
864
+ }
865
+ }
866
+ return out;
867
+ }
868
+ var paragraph = (nodes, ctx) => protectLine(inline(nodes, ctx).replace(/^\s+|\s+$/g, "").replace(/ *\\\n */g, "\\\n"));
869
+ function listItem(li, ctx, marker, depth) {
870
+ const indent = " ".repeat(marker.length), inlineNodes = [], nested = [];
871
+ let task = "";
872
+ for (const k of kids(li)) {
873
+ if (isEl(k) && k.tagName === "input" && attr(k, "type") === "checkbox") {
874
+ task = attr(k, "checked") !== void 0 ? "[x] " : "[ ] ";
875
+ continue;
876
+ }
877
+ if (isEl(k) && (k.tagName === "ul" || k.tagName === "ol")) {
878
+ nested.push(list(k, ctx, depth + 1));
879
+ continue;
880
+ }
881
+ if (isEl(k) && k.tagName === "p") {
882
+ if (inlineNodes.length) inlineNodes.push(...kids(k).length ? [{ nodeName: "#text", value: " " }] : []);
883
+ inlineNodes.push(...kids(k));
884
+ continue;
885
+ }
886
+ inlineNodes.push(k);
887
+ }
888
+ const text2 = inline(inlineNodes, ctx).trim().replace(/\\\n/g, "\\\n" + indent);
889
+ const first = `${marker}${task}${text2}`;
890
+ return [first, ...nested.map((block2) => block2.split("\n").map((line) => indent + line).join("\n"))].join("\n");
891
+ }
892
+ function list(el2, ctx, depth = 0) {
893
+ const ordered = el2.tagName === "ol";
894
+ let n = Number(attr(el2, "start") ?? 1);
895
+ if (!Number.isFinite(n)) n = 1;
896
+ return elements(el2).filter((c) => c.tagName === "li").map((li) => listItem(li, ctx, ordered ? `${n++}. ` : "- ", depth)).join("\n");
897
+ }
898
+ function tableMarkdown(table, ctx) {
899
+ const rows = findAll(table, (e) => e.tagName === "tr");
900
+ if (!rows.length) return "";
901
+ const cellsOf2 = (tr) => elements(tr).filter((c) => c.tagName === "td" || c.tagName === "th");
902
+ const head = cellsOf2(rows[0]), width = Math.max(...rows.map((r) => cellsOf2(r).length));
903
+ const align = (c) => {
904
+ const a = (c && (attr(c, "align") ?? style(c, "text-align"))) ?? "";
905
+ return a === "right" ? "---:" : a === "center" ? ":---:" : a === "left" ? ":---" : "---";
906
+ };
907
+ const line = (cells) => `| ${cells.join(" | ")} |`;
908
+ const pad2 = (cells) => [...cells, ...Array(Math.max(0, width - cells.length)).fill("")];
909
+ const text2 = (c) => inline(kids(c), ctx, true).trim().replace(/\s+/g, " ");
910
+ return [line(pad2(head.map(text2))), line(Array.from({ length: width }, (_, i) => align(head[i]))), ...rows.slice(1).map((r) => line(pad2(cellsOf2(r).map(text2))))].join("\n");
911
+ }
912
+ function blocks(nodes, ctx) {
913
+ const out = [];
914
+ let run = [];
915
+ const flush = () => {
916
+ if (run.length) {
917
+ const p = paragraph(run, ctx);
918
+ if (p) out.push(p);
919
+ run = [];
920
+ }
921
+ };
922
+ for (const n of nodes) {
923
+ if (isText(n) || !isBlock(n)) {
924
+ if (isEl(n) && SKIPPED.has(n.tagName)) continue;
925
+ run.push(n);
926
+ continue;
927
+ }
928
+ flush();
929
+ const el2 = n, name = el2.tagName;
930
+ if (/^h[1-6]$/.test(name)) {
931
+ const t = inline(kids(el2), ctx).replace(/\\\n/g, " ").trim();
932
+ if (t) out.push(`${"#".repeat(Number(name[1]))} ${t}`);
933
+ } else if (name === "p") {
934
+ const p = paragraph(kids(el2), ctx);
935
+ if (p) out.push(p);
936
+ } else if (name === "ul" || name === "ol") {
937
+ const l = list(el2, ctx);
938
+ if (l) out.push(l);
939
+ } else if (name === "blockquote") {
940
+ const inner = blocks(kids(el2), ctx).join("\n\n");
941
+ if (inner) out.push(inner.split("\n").map((l) => l ? `> ${l}` : ">").join("\n"));
942
+ } else if (name === "pre") {
943
+ const code = elements(el2).find((c) => c.tagName === "code") ?? el2, raw = textOf(code, true).length ? kids(code).map((k) => isText(k) ? k.value : textOf(k, true)).join("") : "";
944
+ const text2 = raw.replace(/\n$/, "").replace(/\{\{/g, "{\u200B{");
945
+ if (text2 !== raw.replace(/\n$/, "")) ctx.note("BRACES_SEPARATED", "Two braces in a code block were separated with a zero-width space so a template does not read them as an expression.");
946
+ const language = classes(code).map((c) => /^(?:language|lang)-(.+)$/.exec(c)?.[1]).find(Boolean) ?? "";
947
+ const ticks = fence(text2, "`");
948
+ out.push(`${ticks}${language}
949
+ ${text2}
950
+ ${ticks}`);
951
+ } else if (name === "hr") out.push("---");
952
+ else if (name === "table") {
953
+ const t = tableMarkdown(el2, ctx);
954
+ if (t) out.push(t);
955
+ } else if (name === "dl") {
956
+ for (const d of elements(el2)) {
957
+ const p = paragraph(kids(d), ctx);
958
+ if (p) out.push(d.tagName === "dt" ? `**${p.replace(/^\*\*|\*\*$/g, "")}**` : p);
959
+ }
960
+ } else if (name === "figcaption" || name === "summary" || name === "dt" || name === "dd") {
961
+ const p = paragraph(kids(el2), ctx);
962
+ if (p) out.push(p);
963
+ } else out.push(...blocks(kids(el2), ctx));
964
+ }
965
+ flush();
966
+ return out;
967
+ }
968
+ var toMarkdown = (nodes, ctx) => blocks(nodes, ctx).join("\n\n");
969
+
970
+ // packages/reportic-render-html/src/import/tables.ts
971
+ var toneOf = (el2) => ["ok", "warn", "bad", "na"].find((t) => hasClass(el2, `rpt-${t}`));
972
+ var kinds = /* @__PURE__ */ new Set(["rating", "status", "date", "code", "list"]);
973
+ function readCell(td) {
974
+ const raw = attr(td, "data-reportic-raw"), text2 = textOf(td, true);
975
+ const nodes = kids(td).filter((n) => !(isText(n) && !n.value.trim()) && !(isEl(n) && n.tagName === "wbr"));
976
+ if (!nodes.length) return { text: "" };
977
+ if (raw !== void 0) {
978
+ const parsed = (() => {
979
+ try {
980
+ return JSON.parse(raw);
981
+ } catch {
982
+ return raw;
983
+ }
984
+ })();
985
+ if (Array.isArray(parsed)) return { text: text2, kind: "list", value: parsed.filter((x) => ["string", "number", "boolean"].includes(typeof x)) };
986
+ if (nodes.length === 1 && isEl(nodes[0]) && hasClass(nodes[0], "rpt-date")) return { text: text2, kind: "date", value: String(raw) };
987
+ }
988
+ if (nodes.length === 1 && isEl(nodes[0])) {
989
+ const only = nodes[0];
990
+ if (only.tagName === "span" && hasClass(only, "rpt-rating") && toneOf(only)) return { text: text2, kind: "rating", value: { tone: toneOf(only), label: textOf(only) } };
991
+ if (only.tagName === "span" && hasClass(only, "rpt-chip") && hasClass(only, "rpt-status")) return { text: text2, kind: "status", value: textOf(only) };
992
+ if (only.tagName === "code") return { text: text2, kind: "code", value: textOf(only) };
993
+ }
994
+ const mixed = nodes.some((n) => isEl(n) && (n.tagName === "span" && hasClass(n, "rpt-rating") || n.tagName === "code" || n.tagName === "strong" || n.tagName === "br"));
995
+ if (mixed) {
996
+ const parts = [];
997
+ const push = (s) => {
998
+ if (typeof parts[parts.length - 1] === "string") parts[parts.length - 1] += s;
999
+ else parts.push(s);
1000
+ };
1001
+ for (const n of kids(td)) {
1002
+ if (isText(n)) {
1003
+ push(n.value.replace(/\s+/g, " "));
1004
+ continue;
1005
+ }
1006
+ if (!isEl(n)) continue;
1007
+ if (n.tagName === "br") push("\n");
1008
+ else if (n.tagName === "span" && hasClass(n, "rpt-rating") && toneOf(n)) parts.push({ value: { tone: toneOf(n), label: textOf(n) }, kind: "rating" });
1009
+ else if (n.tagName === "code") parts.push({ value: textOf(n), kind: "code" });
1010
+ else if (n.tagName === "strong") parts.push({ value: textOf(n), kind: "strong" });
1011
+ else if (n.tagName !== "wbr") push(textOf(n));
1012
+ }
1013
+ return { text: text2, parts };
1014
+ }
1015
+ return { text: text2 };
1016
+ }
1017
+ var alignOf = (el2) => {
1018
+ const a = style(el2, "text-align");
1019
+ return a === "right" || a === "center" ? a : void 0;
1020
+ };
1021
+ function readTable(table) {
1022
+ const head = child(table, (e) => e.tagName === "thead");
1023
+ const bodyRows = [...elements(table).filter((e) => e.tagName === "tbody").flatMap((b) => elements(b).filter((r) => r.tagName === "tr")), ...elements(table).filter((e) => e.tagName === "tr")];
1024
+ const headRow = head ? elements(head).find((r) => r.tagName === "tr") : void 0;
1025
+ const cellsOf2 = (tr) => elements(tr).filter((c) => c.tagName === "td" || c.tagName === "th");
1026
+ let headers = !!headRow, header = headRow ? cellsOf2(headRow) : [];
1027
+ let rowsEl = bodyRows;
1028
+ if (!headRow && rowsEl.length && cellsOf2(rowsEl[0]).length && cellsOf2(rowsEl[0]).every((c) => c.tagName === "th" && attr(c, "scope") !== "row")) {
1029
+ headers = true;
1030
+ header = cellsOf2(rowsEl[0]);
1031
+ rowsEl = rowsEl.slice(1);
1032
+ }
1033
+ if (!rowsEl.length) return void 0;
1034
+ const width = Math.max(header.length, ...rowsEl.map((r) => cellsOf2(r).length));
1035
+ if (!width) return void 0;
1036
+ const rowHeader = rowsEl.some((r) => {
1037
+ const c = cellsOf2(r)[0];
1038
+ return !!c && c.tagName === "th" && (attr(c, "scope") === "row" || hasClass(c, "rpt-rowheader") || !headers);
1039
+ }) && rowsEl.every((r) => cellsOf2(r)[0]?.tagName === "th");
1040
+ const columns = Array.from({ length: width }, (_, i) => {
1041
+ const th = header[i];
1042
+ const kind = th ? attr(th, "data-reportic-kind") : void 0;
1043
+ const sample = rowsEl.map((r) => cellsOf2(r)[i]).filter(Boolean);
1044
+ return {
1045
+ label: th ? textOf(th) : headers ? "" : `Column ${i + 1}`,
1046
+ ...th && alignOf(th) ? { align: alignOf(th) } : sample.length && alignOf(sample[0]) ? { align: alignOf(sample[0]) } : {},
1047
+ ...kind && kinds.has(kind) ? { kind } : {},
1048
+ ...th && attr(th, "data-reportic-format") ? { format: attr(th, "data-reportic-format") } : {},
1049
+ ...sample.some((c) => /white-space:\s*nowrap/.test(attr(c, "style") ?? "")) ? { nowrap: true } : {}
1050
+ };
1051
+ });
1052
+ const rows = [];
1053
+ let total;
1054
+ for (const tr of rowsEl) {
1055
+ const cells = Array.from({ length: width }, (_, i) => {
1056
+ const c = cellsOf2(tr)[i];
1057
+ return c ? readCell(c) : { text: "" };
1058
+ });
1059
+ if (hasClass(tr, "rpt-total") && !total) total = cells;
1060
+ else rows.push(cells);
1061
+ }
1062
+ columns.forEach((c, i) => {
1063
+ if (c.kind) return;
1064
+ const filled = [...rows, ...total ? [total] : []].map((r) => r[i]).filter((x) => x.text !== "");
1065
+ const first = filled[0]?.kind;
1066
+ if (first && filled.every((x) => x.kind === first) && !filled.some((x) => x.parts)) c.kind = first;
1067
+ });
1068
+ return { columns, headers, rowHeader, rows, total };
1069
+ }
1070
+ function gridCell(cell, column) {
1071
+ if (cell.parts) return cell.parts;
1072
+ if (!cell.kind) return cell.text;
1073
+ const value = cell.value ?? cell.text;
1074
+ if (cell.kind === column.kind) return cell.kind === "list" ? { value } : value;
1075
+ return { value, kind: cell.kind, ...cell.kind === "date" ? { format: "date" } : {} };
1076
+ }
1077
+ var columnProps = (c, value) => ({ label: c.label, ...value !== void 0 ? { value } : {}, ...c.align ? { align: c.align } : {}, ...c.kind ? { kind: c.kind } : {}, ...c.format && c.kind === "date" ? { format: c.format } : {}, ...c.nowrap ? { nowrap: true } : {} });
1078
+ var formatsOf = (columns) => columns.map((c) => c.kind === "date" ? void 0 : c.format);
1079
+ function tableElement(model, id, ctx) {
1080
+ const { columns, rows, total } = model;
1081
+ const flags = { ...model.headers ? {} : { headers: false }, ...model.rowHeader ? { rowHeader: true } : {} };
1082
+ if (total) {
1083
+ const key2 = (i) => `c${i}`;
1084
+ const record = (r) => Object.fromEntries(r.map((cell, i) => [key2(i), cell.kind === "rating" || cell.kind === "list" || cell.kind === "date" || cell.kind === "status" || cell.kind === "code" ? cell.kind === columns[i].kind ? cell.value : cell.text : cell.text]));
1085
+ if ([...rows, total].some((r) => r.some((c) => c.parts))) ctx.note("COMPOSED_CELL_FLATTENED", "A table with a total row cannot keep cells made of several runs; those cells became plain text.", { elementId: id });
1086
+ return { id, type: "table", props: { rows: rows.map(record), total: record(total), columns: columns.map((c, i) => columnProps(c, { $bind: `row.${key2(i)}` })), ...flags }, meta: { formats: formatsOf(columns) } };
1087
+ }
1088
+ return { id, type: "reportic.grid.v1", props: { ...flags, columns: columns.map((c) => columnProps(c)), rows: rows.map((r) => r.map((cell, i) => gridCell(cell, columns[i]))) }, meta: { formats: formatsOf(columns) } };
1089
+ }
1090
+
1091
+ // packages/reportic-render-html/src/import/emit.ts
1092
+ var baseOf = /* @__PURE__ */ new WeakMap();
1093
+ var isMap = (v) => !!v && typeof v === "object" && !Array.isArray(v);
1094
+ var word = /^[A-Za-z][A-Za-z0-9 _.-]*$/;
1095
+ var reserved = /^(true|false|null|yes|no|on|off|y|n)$/i;
1096
+ var quote = (s) => JSON.stringify(s).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029").replace(/\u0085/g, "\\u0085").replace(/\{\{/g, "\\u007B\\u007B").replace(/\{%/g, "\\u007B%");
1097
+ var scalar = (v) => typeof v === "string" ? word.test(v) && v.trim() === v && !reserved.test(v) ? v : quote(v) : v === null ? "null" : String(v);
1098
+ var key = (k) => /^[A-Za-z$][A-Za-z0-9_$]*$/.test(k) ? k : quote(k);
1099
+ var flow = (v) => Array.isArray(v) ? `[${v.map(flow).join(", ")}]` : isMap(v) ? Object.keys(v).length ? `{ ${Object.entries(v).filter(([, x]) => x !== void 0).map(([k, x]) => `${key(k)}: ${flow(x)}`).join(", ")} }` : "{}" : scalar(v);
1100
+ var pad = (n) => " ".repeat(n);
1101
+ var collection = (v) => Array.isArray(v) || isMap(v);
1102
+ function block(v, ind) {
1103
+ if (Array.isArray(v)) {
1104
+ return v.flatMap((item) => {
1105
+ const f = flow(item);
1106
+ if (f.length + ind < 96 || !collection(item)) return [`${pad(ind)}- ${f}`];
1107
+ const sub = block(item, ind + 2);
1108
+ sub[0] = `${pad(ind)}- ${sub[0].trimStart()}`;
1109
+ return sub;
1110
+ });
1111
+ }
1112
+ return Object.entries(v).filter(([, x]) => x !== void 0).flatMap(([k, x]) => {
1113
+ const f = flow(x);
1114
+ if (!collection(x) || f.length + ind + k.length < 96) return [`${pad(ind)}${key(k)}: ${f}`];
1115
+ return [`${pad(ind)}${key(k)}:`, ...block(x, ind + 2)];
1116
+ });
1117
+ }
1118
+ var clean = (v) => Array.isArray(v) ? v.map(clean) : v && typeof v === "object" ? Object.fromEntries(Object.entries(v).filter(([k]) => !(k === "meta" && "props" in v && "type" in v)).map(([k, x]) => [k, clean(x)])) : v;
1119
+ var elementText = (e) => {
1120
+ const props = clean(e.props);
1121
+ return ["~~~reportic", `id: ${e.id}`, `type: ${e.type}`, ...e.when !== void 0 ? [`when: ${flow(e.when)}`] : [], ...Object.keys(props).length ? ["props:", ...block(props, 2)] : ["props: {}"], "~~~"].join("\n");
1122
+ };
1123
+ function writeTemplate(d) {
1124
+ const front = ["---", 'reportic: "0.2"', `id: ${scalar(d.id)}`, `locale: ${scalar(d.locale)}`, `timezone: ${scalar(d.timezone ?? "UTC")}`];
1125
+ if (d.logo) front.push("branding:", " logo:", ` src: { asset: ${scalar(d.logo.asset)} }`, ` alt: ${scalar(d.logo.alt)}`);
1126
+ if (d.dataSets?.length) front.push("dataSets:", ...d.dataSets.map((n) => ` ${key(n)}: {}`));
1127
+ front.push("---");
1128
+ const body = d.blocks.map((b) => "md" in b ? b.md.trim() : elementText(b.element)).filter(Boolean);
1129
+ return `${front.join("\n")}
1130
+
1131
+ ${body.join("\n\n")}
1132
+ `;
1133
+ }
1134
+
1135
+ // packages/reportic-render-html/src/import/exact.ts
1136
+ function isReporticHtml(doc) {
1137
+ const generator = find(doc, (e) => e.tagName === "meta" && attr(e, "name") === "generator");
1138
+ const main = find(doc, (e) => e.tagName === "main" && hasClass(e, "reportic-report"));
1139
+ return !!generator && /^Reportic\s+0\.2/i.test(attr(generator, "content") ?? "") && !!main && !!find(main, (e) => attr(e, "data-reportic-type") !== void 0);
1140
+ }
1141
+ var mainOf = (doc) => find(doc, (e) => e.tagName === "main" && hasClass(e, "reportic-report"));
1142
+ var tone = (el2) => ["ok", "warn", "bad", "na"].find((t) => hasClass(el2, `rpt-${t}`));
1143
+ var nonEmpty = (o) => Object.fromEntries(Object.entries(o).filter(([, v]) => v !== void 0 && v !== "" && v !== null));
1144
+ var Exact = class {
1145
+ constructor(ctx) {
1146
+ this.ctx = ctx;
1147
+ }
1148
+ ctx;
1149
+ logo;
1150
+ /** One section of Reportic HTML as an element. Several elements come back for a repeat, which has no element of its own on the page. */
1151
+ section(sec) {
1152
+ const base = attr(sec, "data-reportic-id"), out = this.build(sec);
1153
+ if (base) {
1154
+ for (const e of out) if (!baseOf.has(e)) baseOf.set(e, base);
1155
+ }
1156
+ return out;
1157
+ }
1158
+ build(sec) {
1159
+ const type = attr(sec, "data-reportic-type"), id = this.ctx.uid(attr(sec, "data-reportic-id"));
1160
+ const make = (elementType, props, extra = {}) => [{ id, type: elementType, props, ...extra }];
1161
+ switch (type) {
1162
+ case "logo":
1163
+ return this.image(sec, id, true);
1164
+ case "image":
1165
+ return this.image(sec, id, false);
1166
+ case "masthead":
1167
+ return make("reportic.masthead.v1", this.masthead(sec));
1168
+ case "footer":
1169
+ return make("reportic.footer.v1", this.footer(sec));
1170
+ case "metrics":
1171
+ return make("metrics", this.metrics(sec));
1172
+ case "table":
1173
+ return this.table(sec, id);
1174
+ case "chart":
1175
+ return this.chart(sec, id);
1176
+ case "diagram":
1177
+ return this.diagram(sec, id);
1178
+ case "figure":
1179
+ return this.figure(sec, id);
1180
+ case "narrative":
1181
+ return make("narrative", this.narrative(sec));
1182
+ case "list":
1183
+ return this.list(sec, id);
1184
+ case "sources":
1185
+ return make("sources", this.sources(sec));
1186
+ case "callout":
1187
+ return make("reportic.callout.v1", this.callout(sec));
1188
+ case "progress":
1189
+ return make("reportic.progress.v1", this.progress(sec));
1190
+ case "timeline":
1191
+ return make("reportic.timeline.v1", this.timeline(sec));
1192
+ case "comparison":
1193
+ return this.comparison(sec, id);
1194
+ case "checklist":
1195
+ return make("reportic.checklist.v1", this.checklist(sec));
1196
+ case "code":
1197
+ return make("reportic.code.v1", this.code(sec));
1198
+ case "kit-chart":
1199
+ return this.kitChart(sec, id);
1200
+ case "divider":
1201
+ return make("reportic.divider.v1", {});
1202
+ case "footnote":
1203
+ return make("reportic.footnote.v1", { text: textOf(find(sec, (e) => e.tagName === "p") ?? sec, true) });
1204
+ case "badge":
1205
+ return make("reportic.badge.v1", this.badges(sec));
1206
+ case "columns":
1207
+ return make("reportic.columns.v1", this.columnStacks(sec));
1208
+ case "page-break":
1209
+ return make("reportic.page-break.v1", {});
1210
+ case "toc":
1211
+ return make("reportic.toc.v1", this.toc(sec));
1212
+ case "cover":
1213
+ return make("reportic.cover.v1", this.cover(sec));
1214
+ case "group": {
1215
+ const h22 = this.members(sec)[0];
1216
+ const titled = h22?.tagName === "h2";
1217
+ return make("group", { ...titled ? { heading: textOf(h22) } : {}, children: this.children(sec, titled) });
1218
+ }
1219
+ case "repeat":
1220
+ return this.repeat(sec, id);
1221
+ default:
1222
+ this.ctx.warn("SECTION_UNKNOWN", `A section of type "${type}" has no element in the library, so its text was kept as a paragraph.`, { elementId: id });
1223
+ return textOf(sec) ? make("narrative", { text: textOf(sec, true) }) : [];
1224
+ }
1225
+ }
1226
+ /** What a group or repeat holds, in order: sections, and headings (a heading element is plain Markdown on the page, so it has no section). */
1227
+ members(sec) {
1228
+ return elements(sec).filter((e) => e.tagName === "section" && attr(e, "data-reportic-type") !== void 0 || /^h[1-6]$/.test(e.tagName));
1229
+ }
1230
+ member(e) {
1231
+ if (e.tagName === "section") return this.section(e);
1232
+ const text2 = textOf(e);
1233
+ if (!text2) return [];
1234
+ const heading = { id: this.ctx.uid("heading"), type: "reportic.heading.v1", props: { text: text2, level: Number(e.tagName[1]) } };
1235
+ baseOf.set(heading, e.tagName);
1236
+ return [heading];
1237
+ }
1238
+ children(sec, skipHeading = false) {
1239
+ const list2 = this.members(sec);
1240
+ return (skipHeading && list2[0]?.tagName === "h2" ? list2.slice(1) : list2).flatMap((e) => this.member(e));
1241
+ }
1242
+ image(sec, id, brand) {
1243
+ const img = find(sec, (e) => e.tagName === "img");
1244
+ if (!img) return [];
1245
+ const src = attr(img, "src") ?? "", alt = attr(img, "alt") ?? "";
1246
+ const name = this.ctx.asset(src, brand ? "logo" : void 0);
1247
+ if (!name) {
1248
+ this.ctx.warn("IMAGE_NOT_EMBEDDED", `An image${alt ? ` ("${alt}")` : ""} is not embedded in the page, so it was left out.`, { elementId: id });
1249
+ return [];
1250
+ }
1251
+ if (brand || attr(sec, "data-reportic-id") === "reportic-brand-logo") {
1252
+ this.logo = { asset: name, alt: alt || "Logo" };
1253
+ return [];
1254
+ }
1255
+ const figcaption = find(sec, (e) => e.tagName === "figcaption"), caption = figcaption ? textOf(figcaption) : "";
1256
+ return [{ id, type: "image", props: { src: { asset: name }, alt: alt || "Image", ...caption ? { caption } : {} } }];
1257
+ }
1258
+ masthead(sec) {
1259
+ const header = find(sec, (e) => e.tagName === "header") ?? sec;
1260
+ const byEl = (cls) => find(header, (e) => hasClass(e, cls));
1261
+ const model = json(sec, "data-reportic-model");
1262
+ let byline = model?.byline;
1263
+ const bylineEl = byEl("rpt-byline");
1264
+ if (!byline && bylineEl) {
1265
+ byline = kids(bylineEl).flatMap((n) => isEl(n) && hasClass(n, "rpt-chip") ? [{ value: textOf(n), kind: hasClass(n, "rpt-person") ? "person" : "date" }] : isText(n) ? n.value.split("\xB7").map((s) => s.trim()).filter(Boolean).map((value) => ({ value })) : []);
1266
+ this.ctx.note("BYLINE_APPROXIMATE", "The byline was read from the page text; dates are kept as written.");
1267
+ }
1268
+ return nonEmpty({ marking: byEl("rpt-marking") && textOf(byEl("rpt-marking")), kicker: byEl("rpt-kicker") && textOf(byEl("rpt-kicker")), title: textOf(find(header, (e) => e.tagName === "h1") ?? header), byline: byline?.length ? byline : void 0, lead: byEl("rpt-lead") && textOf(byEl("rpt-lead")) });
1269
+ }
1270
+ footer(sec) {
1271
+ const footer = find(sec, (e) => e.tagName === "footer") ?? sec, img = find(footer, (e) => e.tagName === "img");
1272
+ const text2 = kids(footer).filter((n) => !(isEl(n) && n.tagName === "img")).map((n) => textOf(n)).join(" ").replace(/\s+/g, " ").trim();
1273
+ const name = img ? this.ctx.asset(attr(img, "src") ?? "", "footer-logo") : void 0;
1274
+ return { text: text2, ...name ? { logo: { asset: name }, logoAlt: attr(img, "alt") ?? "Logo" } : {} };
1275
+ }
1276
+ metrics(sec) {
1277
+ const holder = find(sec, (e) => hasClass(e, "metrics"));
1278
+ const model = json(sec, "data-reportic-model");
1279
+ const items = (holder ? elements(holder) : []).map((div, i) => {
1280
+ const part = (cls) => {
1281
+ const e = find(div, (x) => hasClass(x, cls));
1282
+ return e ? textOf(e) : void 0;
1283
+ };
1284
+ const extra = model?.items?.[i];
1285
+ return nonEmpty({ label: part("metric-label"), value: part("metric-value"), comparison: part("metric-comparison"), tone: tone(div), trend: extra?.trend, intent: extra?.intent });
1286
+ });
1287
+ return { items };
1288
+ }
1289
+ table(sec, id) {
1290
+ const table = find(sec, (e) => e.tagName === "table");
1291
+ if (!table) {
1292
+ const empty = textOf(sec);
1293
+ this.ctx.note("TABLE_EMPTY", `A table with no rows shows "${empty}"; its columns are not on the page, so it was kept as a paragraph.`, { elementId: id });
1294
+ return empty ? [{ id, type: "narrative", props: { text: empty } }] : [];
1295
+ }
1296
+ const model = readTable(table);
1297
+ if (!model) return [];
1298
+ return [tableElement(model, id, this.ctx)];
1299
+ }
1300
+ chart(sec, id) {
1301
+ const m = json(sec, "data-reportic-model"), kind = attr(sec, "data-reportic-kind");
1302
+ if (!m || !Array.isArray(m.categories) || !Array.isArray(m.series)) {
1303
+ const empty = textOf(sec);
1304
+ this.ctx.note("CHART_EMPTY", "A chart with no data has nothing to import and was kept as a paragraph.", { elementId: id });
1305
+ return empty ? [{ id, type: "narrative", props: { text: empty } }] : [];
1306
+ }
1307
+ const rows = m.categories.map((c, i) => ({ x: c, ...Object.fromEntries(m.series.map((s, j) => [`s${j}`, s.values[i]])) }));
1308
+ return [{ id, type: "chart", props: { kind: kind === "bar" ? "bar" : "line", title: m.title, alt: m.alt, rows, x: { label: m.x?.label ?? "", value: { $bind: "row.x" } }, series: m.series.map((s, j) => ({ label: s.label, value: { $bind: `row.s${j}` }, ...s.format ? { format: s.format } : {} })) } }];
1309
+ }
1310
+ diagram(sec, id) {
1311
+ const m = json(sec, "data-reportic-model");
1312
+ if (!m) {
1313
+ this.ctx.warn("DIAGRAM_SOURCE_LOST", "A diagram has no source on the page. It was kept as an image.", { elementId: id });
1314
+ return this.image(sec, id, false);
1315
+ }
1316
+ return [{ id, type: "diagram", props: { engine: "mermaid", alt: m.alt, ...m.adapter ? { adapter: m.adapter, model: m.model } : { source: m.source }, ...m.caption && m.caption !== m.alt ? { caption: m.caption } : {} } }];
1317
+ }
1318
+ figure(sec, id) {
1319
+ const spec = json(sec, "data-reportic-spec");
1320
+ if (!spec) {
1321
+ this.ctx.warn("FIGURE_SPEC_LOST", "A figure has no spec on the page. It was kept as an image.", { elementId: id });
1322
+ return this.image(sec, id, false);
1323
+ }
1324
+ const caption = find(sec, (e) => e.tagName === "figcaption"), source = caption ? textOf(caption) : "";
1325
+ const alt = attr(find(sec, (e) => e.tagName === "img") ?? sec, "alt");
1326
+ return [{ id, type: "reportic.figure.v1", props: { spec, ...source ? { source } : {}, ...alt && alt !== spec.title && alt !== `${spec.title} \u2014 ${spec.subtitle}` ? { alt } : {} } }];
1327
+ }
1328
+ narrative(sec) {
1329
+ const heading = find(sec, (e) => e.tagName === "h3"), p = find(sec, (e) => e.tagName === "p");
1330
+ const evidence = p ? findAll(p, (e) => e.tagName === "a" && hasClass(e, "evidence")) : [];
1331
+ const text2 = p ? kids(p).filter((n) => !(isEl(n) && hasClass(n, "evidence"))).map((n) => isText(n) ? n.value : textOf(n, true)).join("").replace(/[ \t]+/g, " ").replace(/ *\n */g, "\n").trim() : "";
1332
+ const ids = evidence.map((a) => (attr(a, "href") ?? "").replace(/^#/, "")).filter(Boolean);
1333
+ return nonEmpty({ heading: heading && textOf(heading), text: text2, evidenceIds: ids.length ? ids : void 0 });
1334
+ }
1335
+ list(sec, id) {
1336
+ const aside = find(sec, (e) => e.tagName === "aside"), listEl = find(sec, (e) => e.tagName === "ul" || e.tagName === "ol");
1337
+ const empty = child(sec, (e) => hasClass(e, "empty"));
1338
+ const itemEls = aside ? elements(aside).filter((e) => e.tagName === "p") : listEl ? elements(listEl).filter((e) => e.tagName === "li") : elements(sec).filter((e) => e.tagName === "p" && !hasClass(e, "empty"));
1339
+ const variant = aside ? "callout" : listEl ? void 0 : "paragraphs";
1340
+ const items = itemEls.map((el2) => {
1341
+ const first = kids(el2).find((n) => isEl(n) || isText(n) && n.value.trim());
1342
+ const lead = isEl(first) && first.tagName === "strong" ? textOf(first) : "";
1343
+ const rest = kids(el2).filter((n) => n !== first || !lead).map((n) => isText(n) ? n.value : textOf(n)).join("").replace(/\s+/g, " ").trim();
1344
+ return { lead, text: lead ? rest : textOf(el2) };
1345
+ });
1346
+ if (!items.length) return [{ id, type: "list", props: { rows: [], text: { $bind: "row" }, ...empty ? { empty: textOf(empty) } : {} } }];
1347
+ const leads = items.some((i) => i.lead);
1348
+ return [{ id, type: "list", props: { rows: leads ? items.map((i) => nonEmpty(i)) : items.map((i) => i.text), ...leads ? { lead: { $bind: "row.lead" }, text: { $bind: "row.text" } } : { text: { $bind: "row" } }, ...variant ? { variant } : {}, ...listEl?.tagName === "ol" ? { ordered: true } : {} } }];
1349
+ }
1350
+ sources(sec) {
1351
+ const records = {};
1352
+ for (const li of findAll(sec, (e) => e.tagName === "li")) {
1353
+ const a = find(li, (e) => e.tagName === "a"), idAttr = attr(li, "id") ?? `source-${Object.keys(records).length + 1}`;
1354
+ records[idAttr] = { label: textOf(li), ...a && attr(a, "href") ? { url: attr(a, "href") } : {} };
1355
+ }
1356
+ return { records };
1357
+ }
1358
+ callout(sec) {
1359
+ const aside = find(sec, (e) => e.tagName === "aside") ?? sec, strong = child(aside, (e) => e.tagName === "strong"), paragraphs = elements(aside).filter((e) => e.tagName === "p");
1360
+ const model = json(sec, "data-reportic-model");
1361
+ const tones = ["info", "success", "warning", "danger", "neutral"];
1362
+ const t = tones.find((x) => hasClass(aside, `tone-${x}`));
1363
+ return { title: strong ? textOf(strong) : "", text: paragraphs[0] ? textOf(paragraphs[0], true) : "", ...model?.items?.length ? { items: model.items } : {}, ...t && t !== "info" ? { tone: t } : {} };
1364
+ }
1365
+ kitChart(sec, id) {
1366
+ const spec = json(sec, "data-reportic-spec");
1367
+ if (!spec) {
1368
+ this.ctx.warn("CHART_SPEC_LOST", "A chart has no spec on the page. It was kept as an image.", { elementId: id });
1369
+ return this.image(sec, id, false);
1370
+ }
1371
+ const alt = attr(find(sec, (e) => e.tagName === "img") ?? sec, "alt");
1372
+ return [{ id, type: "reportic.chart.v1", props: { spec, ...alt ? { alt } : {} } }];
1373
+ }
1374
+ badges(sec) {
1375
+ const tones = ["neutral", "accent", "success", "warning", "danger", "info"];
1376
+ return { items: findAll(sec, (e) => hasClass(e, "rpt-badge")).map((el2) => nonEmpty({ label: textOf(el2), tone: tones.find((t) => hasClass(el2, `rpt-${t}`)) })) };
1377
+ }
1378
+ columnStacks(sec) {
1379
+ const grid = find(sec, (e) => hasClass(e, "rpt-columns")) ?? sec;
1380
+ const columns = kids(grid).filter(isEl).map((col) => kids(col).filter(isEl).flatMap((e) => this.member(e)));
1381
+ return { count: columns.length, columns };
1382
+ }
1383
+ toc(sec) {
1384
+ const heading = find(sec, (e) => e.tagName === "h2");
1385
+ return nonEmpty({ title: heading ? textOf(heading) : void 0 });
1386
+ }
1387
+ cover(sec) {
1388
+ const header = find(sec, (e) => e.tagName === "header") ?? sec;
1389
+ const by = (cls) => {
1390
+ const e = find(header, (x) => hasClass(x, cls));
1391
+ return e ? textOf(e) : void 0;
1392
+ };
1393
+ return nonEmpty({ marking: by("rpt-marking"), kicker: by("rpt-kicker"), title: textOf(find(header, (e) => e.tagName === "h1") ?? header), subtitle: by("rpt-subtitle") });
1394
+ }
1395
+ progress(sec) {
1396
+ return { items: findAll(sec, (e) => hasClass(e, "progress-item")).map((item) => {
1397
+ const bar = find(item, (e) => attr(e, "role") === "progressbar"), now = Number(attr(bar ?? item, "aria-valuenow") ?? 0), small = find(item, (e) => e.tagName === "small");
1398
+ const row = find(item, (e) => hasClass(e, "progress-label")), span = row && child(row, (e) => e.tagName === "span");
1399
+ return nonEmpty({ label: textOf(span ?? item), value: Number((now / 100).toPrecision(10)), detail: small && textOf(small) });
1400
+ }) };
1401
+ }
1402
+ timeline(sec) {
1403
+ return { items: findAll(sec, (e) => hasClass(e, "timeline-item")).map((item) => nonEmpty({ date: textOf(find(item, (e) => hasClass(e, "timeline-date")) ?? item), title: textOf(find(item, (e) => e.tagName === "strong") ?? item), text: (() => {
1404
+ const p = find(item, (e) => e.tagName === "p");
1405
+ return p && textOf(p);
1406
+ })() })) };
1407
+ }
1408
+ comparison(sec, id) {
1409
+ const table = find(sec, (e) => e.tagName === "table"), model = table && readTable(table);
1410
+ if (!model || model.columns.length !== 3) return table ? [tableElement(model ?? readTable(table), id, this.ctx)] : [];
1411
+ return [{ id, type: "reportic.comparison.v1", props: { labels: [model.columns[1].label, model.columns[2].label], rows: model.rows.map((r) => ({ label: r[0].text, left: r[1].text, right: r[2].text })) } }];
1412
+ }
1413
+ checklist(sec) {
1414
+ return { items: findAll(sec, (e) => e.tagName === "li").map((li) => {
1415
+ const mark = find(li, (e) => hasClass(e, "checkmark")), owner = find(li, (e) => e.tagName === "small");
1416
+ const text2 = kids(li).filter((n) => n !== mark && !(isEl(n) && n.tagName === "small")).map((n) => textOf(n)).join("").replace(/\s+/g, " ").trim();
1417
+ return nonEmpty({ text: text2, done: mark ? textOf(mark).includes("\u2611") : false, owner: owner && textOf(owner).replace(/^·\s*/, "") });
1418
+ }) };
1419
+ }
1420
+ code(sec) {
1421
+ const pre = find(sec, (e) => e.tagName === "pre"), small = child(sec, (e) => e.tagName === "small"), caption = child(sec, (e) => e.tagName === "p");
1422
+ return nonEmpty({ code: pre ? kids(find(pre, (e) => e.tagName === "code") ?? pre).map((n) => isText(n) ? n.value : textOf(n, true)).join("") : "", language: small && textOf(small), caption: caption && textOf(caption) });
1423
+ }
1424
+ /** A repeat leaves no trace of its rows, only its children once per row. Each row becomes a group so every one keeps its own text. */
1425
+ repeat(sec, id) {
1426
+ const empty = child(sec, (e) => hasClass(e, "empty"));
1427
+ const secs = this.members(sec);
1428
+ if (!secs.length) {
1429
+ if (empty) this.ctx.note("REPEAT_EMPTY", "A repeat with no rows was dropped.", { elementId: id });
1430
+ return [];
1431
+ }
1432
+ const chunks = [];
1433
+ let seen = /* @__PURE__ */ new Set();
1434
+ for (const s of secs) {
1435
+ const key2 = attr(s, "data-reportic-id") ?? s.tagName;
1436
+ if (!chunks.length || seen.has(key2)) {
1437
+ chunks.push([]);
1438
+ seen = /* @__PURE__ */ new Set();
1439
+ }
1440
+ chunks[chunks.length - 1].push(s);
1441
+ seen.add(key2);
1442
+ }
1443
+ this.ctx.note("REPEAT_EXPANDED", `A repeat showed ${chunks.length} time${chunks.length === 1 ? "" : "s"} and became one group each. Import with a sample to turn them into a repeat again.`, { elementId: id });
1444
+ return chunks.map((chunk, i) => ({ id: this.ctx.uid(`${attr(sec, "data-reportic-id") ?? "repeat"}-row`), type: "group", props: { children: chunk.flatMap((s) => this.member(s)) }, meta: { repeat: attr(sec, "data-reportic-id") ?? id, index: i, count: chunks.length } }));
1445
+ }
1446
+ };
1447
+ function importReportic(doc, ctx) {
1448
+ const main = mainOf(doc), exact = new Exact(ctx), md2 = ctx.markdown();
1449
+ const blocks2 = [];
1450
+ let pending = [];
1451
+ const flush = () => {
1452
+ if (!pending.length) return;
1453
+ const text2 = toMarkdown(pending, md2);
1454
+ pending = [];
1455
+ if (text2) blocks2.push({ md: text2 });
1456
+ };
1457
+ for (const n of kids(main)) {
1458
+ if (isEl(n) && n.tagName === "section" && attr(n, "data-reportic-type") !== void 0) {
1459
+ flush();
1460
+ for (const element of exact.section(n)) blocks2.push({ element });
1461
+ } else pending.push(n);
1462
+ }
1463
+ flush();
1464
+ const html = find(doc, (e) => e.tagName === "html");
1465
+ const title = (() => {
1466
+ const mast = blocks2.find((b) => "element" in b && b.element.type === "reportic.masthead.v1");
1467
+ const h1 = find(main, (e) => e.tagName === "h1"), named = find(doc, (e) => e.tagName === "title");
1468
+ return mast?.element.props.title ?? (h1 ? textOf(h1) : named ? textOf(named) : "").slice(0, 60);
1469
+ })();
1470
+ return { id: `imported-${String(title || "report").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48) || "report"}`, locale: html && attr(html, "lang") || "en-US", blocks: blocks2, logo: exact.logo, assets: ctx.assets };
1471
+ }
1472
+
1473
+ // packages/reportic-render-html/src/import/effort.ts
1474
+ var DROPPED = { script: "scripts", iframe: "embedded frames", video: "video", audio: "audio", canvas: "canvas drawings", object: "embedded objects", embed: "embedded objects", form: "forms", button: "buttons", select: "form controls", textarea: "form controls", nav: "navigation", noscript: "fallback markup" };
1475
+ var CONTAINERS = /* @__PURE__ */ new Set(["div", "section", "article", "main", "header", "aside", "span", "center", "body", "html", "figure", "details", "address", "hgroup", "footer"]);
1476
+ var VALUE = /^[+\-−]?[\p{Sc}]?\s?\d[\d,.\s]*\s?(%|[kKmMbB]|pts?|ms|s|x|d|h|min|GB|MB|TB)?$/u;
1477
+ var DATE = /^(\d{4}-\d{2}-\d{2}|\d{1,2} [A-Z][a-z]{2,8}\.?(?: \d{4})?|[A-Z][a-z]{2,8}\.? \d{1,2}(?:,? \d{4})?|Q[1-4] \d{4}|[A-Z][a-z]{2,8} \d{4})(?=\s|$|[:\-–—·|])/;
1478
+ var TONES = [[/danger|error|critical|alert-danger|bad/i, "danger"], [/warn|caution|attention/i, "warning"], [/success|tip|ok|good|done/i, "success"]];
1479
+ var isValue = (s) => s.length <= 14 && s.split(/\s+/).length <= 2 && VALUE.test(s.trim());
1480
+ var text = (n) => textOf(n);
1481
+ var Effort = class {
1482
+ constructor(ctx) {
1483
+ this.ctx = ctx;
1484
+ }
1485
+ ctx;
1486
+ items = [];
1487
+ dropped = /* @__PURE__ */ new Map();
1488
+ sources;
1489
+ emit(element) {
1490
+ this.items.push({ element });
1491
+ }
1492
+ drop(el2, why) {
1493
+ const label = DROPPED[el2.tagName] ?? why ?? el2.tagName;
1494
+ this.dropped.set(label, (this.dropped.get(label) ?? 0) + 1);
1495
+ }
1496
+ walk(nodes) {
1497
+ for (let i = 0; i < nodes.length; i++) {
1498
+ const n = nodes[i];
1499
+ if (!isEl(n)) {
1500
+ if (isText(n) && n.value.trim()) this.items.push({ node: n });
1501
+ continue;
1502
+ }
1503
+ if (n.tagName in DROPPED) {
1504
+ this.drop(n);
1505
+ continue;
1506
+ }
1507
+ if (isSkipped(n)) {
1508
+ if (n.tagName === "svg") this.ctx.warn("SVG_DROPPED", "An inline SVG drawing was dropped. A picture of a chart is kept only when it is an image with a caption.");
1509
+ continue;
1510
+ }
1511
+ if (attr(n, "hidden") !== void 0 || /display\s*:\s*none/i.test(attr(n, "style") ?? "")) continue;
1512
+ if (this.special(n, nodes, i)) continue;
1513
+ if (CONTAINERS.has(n.tagName) || n.tagName === "li" || n.tagName === "dd") {
1514
+ this.walk(kids(n));
1515
+ continue;
1516
+ }
1517
+ this.items.push({ node: n });
1518
+ }
1519
+ }
1520
+ /** Tries each structural pattern. Returns true when the element was consumed. */
1521
+ special(n, siblings, index) {
1522
+ const id = (base) => this.ctx.uid(base);
1523
+ const tag2 = n.tagName;
1524
+ if (tag2 === "progress" || tag2 === "meter" || attr(n, "role") === "progressbar") {
1525
+ const item = this.progressItem(n, siblings, index);
1526
+ if (item) {
1527
+ const last = this.items[this.items.length - 1];
1528
+ if (last && "element" in last && last.element.type === "reportic.progress.v1" && last.element.meta?.open) last.element.props.items.push(item);
1529
+ else this.emit({ id: id("progress"), type: "reportic.progress.v1", props: { items: [item] }, meta: { open: true } });
1530
+ return true;
1531
+ }
1532
+ this.ctx.note("PROGRESS_WEAK", "A progress bar without a value between 0 and 1 was left out.");
1533
+ return true;
1534
+ }
1535
+ if (hasClass(n, "mermaid") || tag2 === "pre" && find(n, (e) => e.tagName === "code" && classes(e).includes("language-mermaid")) || tag2 === "code" && classes(n).includes("language-mermaid")) {
1536
+ const source = textOf(n, true).trim();
1537
+ if (source) {
1538
+ this.emit({ id: id("diagram"), type: "diagram", props: { engine: "mermaid", alt: "Diagram", source } });
1539
+ this.ctx.note("DIAGRAM_ALT", 'A Mermaid diagram was imported with the alt text "Diagram"; write a real description in the editor.');
1540
+ return true;
1541
+ }
1542
+ }
1543
+ if (tag2 === "pre") {
1544
+ const code = find(n, (e) => e.tagName === "code"), language = classes(code ?? n).map((c) => /^(?:language|lang)-(.+)$/.exec(c)?.[1]).find(Boolean);
1545
+ const body = code ?? n;
1546
+ const raw = kids(body).map((k) => isText(k) ? k.value : textOf(k, true)).join("").replace(/\n$/, "");
1547
+ if (raw.trim()) {
1548
+ this.emit({ id: id("code"), type: "reportic.code.v1", props: { code: raw, ...language ? { language } : {} } });
1549
+ return true;
1550
+ }
1551
+ return true;
1552
+ }
1553
+ if (tag2 === "img" || tag2 === "figure" && find(n, (e) => e.tagName === "img") && !find(n, (e) => e.tagName === "table")) {
1554
+ return this.image(n);
1555
+ }
1556
+ if (tag2 === "ul" || tag2 === "ol") {
1557
+ const lis = elements(n).filter((e) => e.tagName === "li");
1558
+ if (lis.length && lis.every((li) => {
1559
+ const first = kids(li).find((k) => isEl(k) || isText(k) && k.value.trim());
1560
+ return isEl(first) && first.tagName === "input" && attr(first, "type") === "checkbox";
1561
+ })) {
1562
+ this.emit({ id: id("checklist"), type: "reportic.checklist.v1", props: { items: lis.map((li) => ({ text: text(li), done: !!find(li, (e) => e.tagName === "input" && attr(e, "checked") !== void 0) })) } });
1563
+ return true;
1564
+ }
1565
+ const bar = (e) => e.tagName === "progress" || e.tagName === "meter" || attr(e, "role") === "progressbar";
1566
+ if (lis.length && lis.every((li) => find(li, bar))) {
1567
+ const items = lis.map((li) => this.progressItem(find(li, bar), kids(li), kids(li).indexOf(find(li, bar))));
1568
+ if (items.every(Boolean)) {
1569
+ this.emit({ id: id("progress"), type: "reportic.progress.v1", props: { items } });
1570
+ return true;
1571
+ }
1572
+ }
1573
+ if (tag2 === "ol" && lis.length && lis.every((li) => {
1574
+ const a = find(li, (e) => e.tagName === "a" && /^https?:/i.test(attr(e, "href") ?? ""));
1575
+ return !!a;
1576
+ }) && this.trailing(siblings, index)) {
1577
+ const records = {}, ids = [];
1578
+ lis.forEach((li, k) => {
1579
+ const a = find(li, (e) => e.tagName === "a"), key2 = `source-${k + 1}`;
1580
+ ids.push(key2);
1581
+ records[key2] = { label: text(li), url: attr(a, "href") };
1582
+ });
1583
+ this.sources = { ids };
1584
+ this.emit({ id: id("sources"), type: "sources", props: { records } });
1585
+ return true;
1586
+ }
1587
+ return false;
1588
+ }
1589
+ if (tag2 === "dl") {
1590
+ const rows = [];
1591
+ let term = "";
1592
+ for (const e of elements(n)) {
1593
+ if (e.tagName === "dt") term = text(e);
1594
+ else if (e.tagName === "dd") {
1595
+ rows.push([term, text(e)]);
1596
+ term = "";
1597
+ }
1598
+ }
1599
+ if (rows.length) {
1600
+ this.emit({ id: id("details"), type: "reportic.grid.v1", props: { headers: false, rowHeader: true, columns: [{ label: "Item" }, { label: "Value" }], rows } });
1601
+ return true;
1602
+ }
1603
+ return false;
1604
+ }
1605
+ if (tag2 === "table") return this.table(n);
1606
+ if (tag2 === "footer" && text(n).length < 400 && !find(n, (e) => ["ul", "ol", "table", "h1", "h2", "h3"].includes(e.tagName)) && text(n)) {
1607
+ this.emit({ id: id("footer"), type: "reportic.footer.v1", props: { text: text(n) } });
1608
+ return true;
1609
+ }
1610
+ if (tag2 === "p" && /\[\d{1,2}\]/.test(text(n)) && !n.attrs.some((a) => a.name === "class" && /footnote/.test(a.value))) {
1611
+ this.items.push({ cited: n });
1612
+ return true;
1613
+ }
1614
+ if (CONTAINERS.has(tag2) || tag2 === "li") {
1615
+ if (this.callout(n)) return true;
1616
+ if (this.metrics(n)) return true;
1617
+ if (this.flow(n)) return true;
1618
+ }
1619
+ if (/^h[3-5]$/.test(tag2) || tag2 === "li") {
1620
+ if (this.timeline(n, siblings, index)) return true;
1621
+ }
1622
+ return false;
1623
+ }
1624
+ trailing(siblings, index) {
1625
+ return siblings.slice(index + 1).every((s) => !isEl(s) || ["footer", "script", "style"].includes(s.tagName) || !text(s));
1626
+ }
1627
+ progressItem(n, siblings, index) {
1628
+ let value;
1629
+ if (n.tagName === "progress") {
1630
+ const max = Number(attr(n, "max") ?? 1), v = Number(attr(n, "value"));
1631
+ if (attr(n, "value") !== void 0 && max > 0) value = v / max;
1632
+ } else if (n.tagName === "meter") {
1633
+ const min = Number(attr(n, "min") ?? 0), max = Number(attr(n, "max") ?? 1), v = Number(attr(n, "value"));
1634
+ if (attr(n, "value") !== void 0 && max > min) value = (v - min) / (max - min);
1635
+ } else {
1636
+ const min = Number(attr(n, "aria-valuemin") ?? 0), max = Number(attr(n, "aria-valuemax") ?? 100), v = Number(attr(n, "aria-valuenow"));
1637
+ if (attr(n, "aria-valuenow") !== void 0 && max > min) value = (v - min) / (max - min);
1638
+ }
1639
+ if (value === void 0 || !Number.isFinite(value) || value < 0 || value > 1) return void 0;
1640
+ const prev = [...siblings.slice(0, index)].reverse().find((s) => isEl(s) && text(s) || isText(s) && s.value.trim());
1641
+ const parentLabel = (() => {
1642
+ const p = n.parentNode;
1643
+ return p && isEl(p) ? kids(p).filter((k) => k !== n && (isText(k) || isEl(k) && !["progress", "meter"].includes(k.tagName) && attr(k, "role") !== "progressbar")).map(text).join(" ").replace(/\s+/g, " ").trim() : "";
1644
+ })();
1645
+ const label = attr(n, "aria-label") ?? (parentLabel && parentLabel.length < 80 ? parentLabel : prev ? text(prev).slice(0, 80) : "") ?? "";
1646
+ return { label: label || "Progress", value: Number(value.toPrecision(6)) };
1647
+ }
1648
+ image(n) {
1649
+ const img = n.tagName === "img" ? n : find(n, (e) => e.tagName === "img"), src = attr(img, "src") ?? "", alt = attr(img, "alt") ?? "";
1650
+ const figcaption = n.tagName === "figure" ? find(n, (e) => e.tagName === "figcaption") : void 0, caption = figcaption ? text(figcaption) : "";
1651
+ const name = this.ctx.asset(src);
1652
+ if (!name) {
1653
+ this.ctx.warn(src.startsWith("data:") ? "IMAGE_TYPE_UNSUPPORTED" : "IMAGE_NOT_EMBEDDED", `An image${alt ? ` ("${alt.slice(0, 60)}")` : ""} is not embedded in the page, so its bytes cannot be imported.`);
1654
+ return true;
1655
+ }
1656
+ this.emit({ id: this.ctx.uid("image"), type: "image", props: { src: { asset: name }, alt: alt || caption || "Image", ...caption ? { caption } : {} } });
1657
+ if (!alt && !caption) this.ctx.note("IMAGE_ALT", 'An image had no alt text and was imported with "Image"; describe it in the editor.');
1658
+ return true;
1659
+ }
1660
+ table(n) {
1661
+ const nested = find(n, (e) => e.tagName === "table" && e !== n);
1662
+ const cells = findAll(n, (e) => e.tagName === "td"), blocky = cells.some((c) => elements(c).some((e) => ["div", "p", "ul", "ol", "table", "h1", "h2", "h3", "h4"].includes(e.tagName)));
1663
+ if (nested || blocky && !find(n, (e) => e.tagName === "th")) {
1664
+ this.ctx.note("LAYOUT_TABLE", "A table used for page layout was read as its contents.");
1665
+ for (const td of cells) this.walk(kids(td));
1666
+ return true;
1667
+ }
1668
+ const model = readTable(n);
1669
+ if (!model) return true;
1670
+ const caption = child(n, (e) => e.tagName === "caption");
1671
+ const hasTh = !!find(n, (e) => e.tagName === "th"), thead = !!child(n, (e) => e.tagName === "thead");
1672
+ if (!hasTh && !thead) {
1673
+ model.headers = false;
1674
+ }
1675
+ for (const [j, column] of model.columns.entries()) {
1676
+ if (!column.align && model.rows.length && model.rows.every((r) => r[j].text === "" || isValue(r[j].text))) column.align = "right";
1677
+ }
1678
+ if (caption && text(caption)) this.items.push({ md: `**${escapeText(text(caption))}**` });
1679
+ if (model.headers && model.columns.length === 3 && !model.total && model.columns.slice(1).every((c) => c.label) && (model.columns[0].label === "" || model.rows.every((r) => r[0].text) && !!find(n, (e) => e.tagName === "th" && attr(e, "scope") === "row"))) {
1680
+ this.emit({ id: this.ctx.uid("comparison"), type: "reportic.comparison.v1", props: { labels: [model.columns[1].label, model.columns[2].label], rows: model.rows.map((r) => ({ label: r[0].text, left: r[1].text, right: r[2].text })) } });
1681
+ return true;
1682
+ }
1683
+ this.emit(tableElement(model, this.ctx.uid("table"), this.ctx));
1684
+ return true;
1685
+ }
1686
+ callout(n) {
1687
+ const cls = classes(n).join(" "), role = attr(n, "role") ?? "";
1688
+ const looks = n.tagName === "aside" || /callout|alert|admonition|notice|note|warning|tip|banner/i.test(cls) || /note|alert/.test(role);
1689
+ if (!looks || text(n).length > 900 || text(n).length < 3) return false;
1690
+ if (find(n, (e) => ["ul", "ol", "table", "pre", "img", "h1", "h2"].includes(e.tagName))) return false;
1691
+ const title = child(n, (e) => /^h[1-6]$/.test(e.tagName) || e.tagName === "strong" || e.tagName === "b" || hasClass(e, "title") || hasClass(e, "callout-title"));
1692
+ const rest = kids(n).filter((k) => k !== title).map((k) => text(k)).filter(Boolean).join("\n").trim();
1693
+ if (!rest && !title) return false;
1694
+ const tone2 = TONES.find(([re]) => re.test(cls))?.[1];
1695
+ this.emit({ id: this.ctx.uid("callout"), type: "reportic.callout.v1", props: { title: rest ? title ? text(title) : "" : "", text: rest || (title ? text(title) : ""), ...tone2 ? { tone: tone2 } : {} } });
1696
+ return true;
1697
+ }
1698
+ /** Siblings that each show one short number and one label are summary tiles. */
1699
+ metrics(n) {
1700
+ const tiles = elements(n);
1701
+ if (tiles.length < 2 || tiles.length > 12) return false;
1702
+ const read = tiles.map((t) => this.tile(t));
1703
+ if (!read.every(Boolean)) return false;
1704
+ const hinted = classes(n).concat(...tiles.map(classes)).some((c) => /metric|kpi|stat|tile|figure|summary|number/i.test(c));
1705
+ if (!hinted && read.length < 3) return false;
1706
+ this.emit({ id: this.ctx.uid("metrics"), type: "metrics", props: { items: read.map((t) => t) } });
1707
+ return true;
1708
+ }
1709
+ tile(t) {
1710
+ const blocky = ["div", "p", "ul", "ol", "table", "section", "h1", "h2", "h3", "h4", "h5", "h6", "dl"];
1711
+ const blocks2 = (e) => kids(e).every((k) => isText(k) || isEl(k) && !blocky.includes(k.tagName)) ? elements(e).length > 1 || elements(e).length === 1 && kids(e).some((k) => isText(k) && k.value.trim()) ? kids(e).map((k) => text(k)).filter(Boolean) : text(e) ? [text(e)] : [] : elements(e).flatMap(blocks2);
1712
+ const parts = blocks2(t);
1713
+ if (parts.length < 2 || parts.length > 3) return void 0;
1714
+ const values = parts.filter(isValue);
1715
+ if (values.length < 1) return void 0;
1716
+ const value = values[0], others = parts.filter((p) => p !== value);
1717
+ if (others.some((o) => o.length > 80) || others.every(isValue)) return void 0;
1718
+ const label = others.find((o) => !/^[+\-−▲▼↑↓]/.test(o) && !isValue(o)) ?? others[0];
1719
+ const comparison = others.find((o) => o !== label);
1720
+ return { label, value, ...comparison ? { comparison } : {} };
1721
+ }
1722
+ /** Labeled boxes joined by arrows are a flowchart. */
1723
+ flow(n) {
1724
+ const parts = elements(n);
1725
+ if (parts.length < 3 || parts.length > 15) return false;
1726
+ const arrow = (e) => /^(→|->|➜|⟶|▶|➔|↓|⇒|»)$/.test(text(e)) || hasClass(e, "arrow");
1727
+ const boxes = parts.filter((e) => !arrow(e)), arrows = parts.filter(arrow);
1728
+ if (arrows.length < 1 || arrows.length !== boxes.length - 1 || !parts.every((e, i) => i % 2 === 0 ? !arrow(e) : arrow(e)) || boxes.some((b) => text(b).length > 40 || !text(b))) return false;
1729
+ const nodes = boxes.map((b, i) => ({ id: `n${i + 1}`, label: text(b) })), edges = nodes.slice(1).map((b, i) => ({ from: nodes[i].id, to: b.id }));
1730
+ this.emit({ id: this.ctx.uid("diagram"), type: "diagram", props: { engine: "mermaid", alt: `Flow: ${nodes.map((x) => x.label).join(" to ")}`, adapter: "reportic.flowchart.v1", model: { nodes, edges } } });
1731
+ return true;
1732
+ }
1733
+ /** Three or more headings that start with a date, each with a title after it, are a timeline. */
1734
+ timeline(n, siblings, index) {
1735
+ const dated = (e) => isEl(e) && e.tagName === n.tagName && DATE.test(text(e)) && text(e).replace(DATE, "").replace(/^\s*[:\-–—·|]\s*/, "").length > 2;
1736
+ if (!dated(n) || index > 0 && dated(siblings.slice(0, index).reverse().find(isEl))) return false;
1737
+ const run = [];
1738
+ for (const s of siblings.slice(index)) {
1739
+ if (!isEl(s)) continue;
1740
+ if (s.tagName === n.tagName) {
1741
+ if (!dated(s)) break;
1742
+ run.push(s);
1743
+ } else if (!["p", "ul"].includes(s.tagName)) break;
1744
+ }
1745
+ if (run.length < 3) return false;
1746
+ const items = run.map((h5) => {
1747
+ const full = text(h5), date = DATE.exec(full)[1], title = full.slice(date.length).replace(/^\s*[:\-–—·|]\s*/, "");
1748
+ const after = siblings.slice(siblings.indexOf(h5) + 1).find(isEl);
1749
+ const body = after && after.tagName === "p" ? text(after) : "";
1750
+ return { date, title, ...body ? { text: body } : {} };
1751
+ });
1752
+ const consumed = /* @__PURE__ */ new Set();
1753
+ for (const h5 of run) {
1754
+ consumed.add(h5);
1755
+ const after = siblings.slice(siblings.indexOf(h5) + 1).find(isEl);
1756
+ if (after && after.tagName === "p") consumed.add(after);
1757
+ }
1758
+ this.emit({ id: this.ctx.uid("timeline"), type: "reportic.timeline.v1", props: { items } });
1759
+ for (let k = index; k < siblings.length; k++) if (consumed.has(siblings[k])) siblings[k] = { nodeName: "#comment", data: "" };
1760
+ return true;
1761
+ }
1762
+ };
1763
+ function importBestEffort(doc, ctx) {
1764
+ const body = find(doc, (e) => e.tagName === "body") ?? doc, effort = new Effort(ctx);
1765
+ effort.walk(kids(body));
1766
+ const md2 = ctx.markdown(), blocks2 = [];
1767
+ let pending = [];
1768
+ const flush = () => {
1769
+ if (!pending.length) return;
1770
+ const t = toMarkdown(pending, md2);
1771
+ pending = [];
1772
+ if (t) blocks2.push({ md: t });
1773
+ };
1774
+ const hasSources = !!effort.sources;
1775
+ for (const item of effort.items) {
1776
+ if ("node" in item) pending.push(item.node);
1777
+ else if ("md" in item) {
1778
+ flush();
1779
+ blocks2.push({ md: item.md });
1780
+ } else if ("cited" in item) {
1781
+ if (hasSources && effort.sources.ids.length) {
1782
+ flush();
1783
+ const raw = text(item.cited), ids = [];
1784
+ for (const m of raw.matchAll(/\[(\d{1,2})\]/g)) {
1785
+ const id = effort.sources.ids[Number(m[1]) - 1];
1786
+ if (id && !ids.includes(id)) ids.push(id);
1787
+ }
1788
+ const clean2 = raw.replace(/\s*\[\d{1,2}\]/g, "").replace(/\s+/g, " ").trim();
1789
+ if (ids.length && clean2) blocks2.push({ element: { id: ctx.uid("narrative"), type: "narrative", props: { text: clean2, evidenceIds: ids } } });
1790
+ else pending.push(item.cited);
1791
+ } else pending.push(item.cited);
1792
+ } else if ("element" in item) {
1793
+ flush();
1794
+ const e = item.element;
1795
+ if (e.meta) {
1796
+ const { open, ...rest } = e.meta;
1797
+ void open;
1798
+ e.meta = rest;
1799
+ }
1800
+ blocks2.push({ element: e });
1801
+ }
1802
+ }
1803
+ flush();
1804
+ for (const [what, n] of effort.dropped) ctx.warn("DROPPED", `Dropped ${n} ${what}: they have no element in the library.`);
1805
+ const html = find(doc, (e) => e.tagName === "html"), title = find(doc, (e) => e.tagName === "h1") ?? find(doc, (e) => e.tagName === "title");
1806
+ return { id: `imported-${String(title ? text(title) : "page").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48) || "page"}`, locale: html && attr(html, "lang") || "en-US", blocks: blocks2, assets: ctx.assets };
1807
+ }
1808
+
1809
+ // packages/reportic-render-html/src/import/theme.ts
1810
+ import { themeTokens as themeTokens4 } from "@x12i/reportic-core";
1811
+ var PRESETS = ["editorial", "forest", "midnight", "minimal"];
1812
+ var hex2 = /^#(?:[\da-f]{3}|[\da-f]{4}|[\da-f]{6}|[\da-f]{8})$/i;
1813
+ var RULE_PROPS = { color: "color", "background-color": "backgroundColor", "font-size": "fontSize", "font-family": "fontFamily", "font-weight": "fontWeight", "text-align": "textAlign", "margin-top": "marginTop", "margin-bottom": "marginBottom", padding: "padding", "border-color": "borderColor", "border-width": "borderWidth" };
1814
+ var unsafe = /@import|url\s*\(|expression\s*\(|<\/?style|behavior\s*:|[<>]|\\/i;
1815
+ var strip = (css) => css.replace(/\/\*[\s\S]*?\*\//g, "");
1816
+ function readBlock(css, from) {
1817
+ let depth = 1, i = from;
1818
+ while (i < css.length && depth) {
1819
+ if (css[i] === "{") depth++;
1820
+ else if (css[i] === "}") depth--;
1821
+ i++;
1822
+ }
1823
+ return i;
1824
+ }
1825
+ function parseCss(source) {
1826
+ const css = strip(source), rules = [], pages = [];
1827
+ let order = 0;
1828
+ const decls = (body) => Object.fromEntries(body.split(";").map((d) => {
1829
+ const i = d.indexOf(":");
1830
+ return i < 0 ? ["", ""] : [d.slice(0, i).trim().toLowerCase(), d.slice(i + 1).replace(/!important/i, "").trim()];
1831
+ }).filter(([k, v]) => k && v));
1832
+ const walk = (text2, media) => {
1833
+ let i = 0;
1834
+ while (i < text2.length) {
1835
+ const open = text2.indexOf("{", i), semi = text2.indexOf(";", i);
1836
+ if (open < 0) break;
1837
+ if (semi >= 0 && semi < open && text2.slice(i, semi).trim().startsWith("@")) {
1838
+ i = semi + 1;
1839
+ continue;
1840
+ }
1841
+ const prelude = text2.slice(i, open).trim(), end = readBlock(text2, open + 1), body = text2.slice(open + 1, end - 1);
1842
+ i = end;
1843
+ if (/^@(media|supports)/i.test(prelude)) walk(body, prelude);
1844
+ else if (/^@page/i.test(prelude)) pages.push(decls(body));
1845
+ else if (prelude.startsWith("@")) continue;
1846
+ else for (const selector of prelude.split(/,(?![^(]*\))/).map((s) => s.trim()).filter(Boolean)) rules.push({ selector, decls: decls(body), media, order: order++ });
1847
+ }
1848
+ };
1849
+ walk(css);
1850
+ return { rules, pages };
1851
+ }
1852
+ function pageOf(css) {
1853
+ const { pages } = parseCss(css);
1854
+ let page;
1855
+ for (const p of pages) {
1856
+ const size = p.size;
1857
+ if (!size) continue;
1858
+ const words = size.toLowerCase().split(/\s+/), next = { ...page };
1859
+ if (words.includes("landscape")) next.landscape = true;
1860
+ if (words.includes("portrait")) next.landscape = false;
1861
+ if (words.includes("a4")) next.size = "A4";
1862
+ if (words.includes("letter")) next.size = "Letter";
1863
+ const dims = words.map((w) => /^([\d.]+)(mm|cm|in|px|pt)$/.exec(w)).filter(Boolean);
1864
+ if (dims.length === 2) {
1865
+ const mm = (m) => Number(m[1]) * { mm: 1, cm: 10, in: 25.4, px: 25.4 / 96, pt: 25.4 / 72 }[m[2]];
1866
+ next.landscape = mm(dims[0]) > mm(dims[1]);
1867
+ const longSide = Math.max(mm(dims[0]), mm(dims[1]));
1868
+ next.size = Math.abs(longSide - 279.4) < 3 ? "Letter" : "A4";
1869
+ }
1870
+ page = next;
1871
+ }
1872
+ return page;
1873
+ }
1874
+ var NAMED = { white: "#ffffff", black: "#000000", red: "#ff0000", green: "#008000", blue: "#0000ff", gray: "#808080", grey: "#808080", navy: "#000080", teal: "#008080", orange: "#ffa500", purple: "#800080", silver: "#c0c0c0", maroon: "#800000", darkgreen: "#006400", darkblue: "#00008b", darkgray: "#a9a9a9", lightgray: "#d3d3d3", lightgrey: "#d3d3d3", whitesmoke: "#f5f5f5", ghostwhite: "#f8f8ff", crimson: "#dc143c", steelblue: "#4682b4", slategray: "#708090", dimgray: "#696969" };
1875
+ function toHex(value) {
1876
+ if (!value) return void 0;
1877
+ const v = value.trim().toLowerCase();
1878
+ if (hex2.test(v)) return v.length === 4 ? "#" + [...v.slice(1)].map((c) => c + c).join("") : v;
1879
+ if (NAMED[v]) return NAMED[v];
1880
+ const m = /^rgba?\(\s*(\d+(?:\.\d+)?)[ ,]+(\d+(?:\.\d+)?)[ ,]+(\d+(?:\.\d+)?)(?:[ ,/]+([\d.]+%?))?\s*\)$/.exec(v);
1881
+ if (!m) return void 0;
1882
+ if (m[4] !== void 0 && Number.parseFloat(m[4]) / (m[4].endsWith("%") ? 100 : 1) < 0.5) return void 0;
1883
+ return "#" + [m[1], m[2], m[3]].map((x) => Math.max(0, Math.min(255, Math.round(Number(x)))).toString(16).padStart(2, "0")).join("");
1884
+ }
1885
+ var colorIn = (value) => {
1886
+ for (const part of (value ?? "").split(/\s+(?![^(]*\))/)) {
1887
+ const c = toHex(part);
1888
+ if (c) return c;
1889
+ }
1890
+ return void 0;
1891
+ };
1892
+ function px(value, base = 16) {
1893
+ const m = /^(-?[\d.]+)(px|pt|em|rem|%)?$/.exec((value ?? "").trim());
1894
+ if (!m) return void 0;
1895
+ const n = Number(m[1]);
1896
+ return Math.round({ px: n, pt: n * 4 / 3, em: n * base, rem: n * 16, "%": n / 100 * base }[m[2] ?? "px"] * 10) / 10;
1897
+ }
1898
+ var rgb2 = (h5) => [1, 3, 5].map((i) => parseInt(h5.slice(i, i + 2), 16));
1899
+ var distance = (a, b) => {
1900
+ const x = rgb2(a), y = rgb2(b);
1901
+ return Math.hypot(x[0] - y[0], x[1] - y[1], x[2] - y[2]);
1902
+ };
1903
+ var cleanFont = (f) => {
1904
+ const v = (f ?? "").replace(/[;{}<>@"]/g, "").replace(/\s+/g, " ").trim();
1905
+ return v && v.length < 200 ? v : void 0;
1906
+ };
1907
+ function match(found) {
1908
+ let best = "editorial", bestScore = Infinity;
1909
+ for (const name of PRESETS) {
1910
+ const base2 = themeTokens4({ name });
1911
+ let score = 0;
1912
+ for (const k of ["accent", "text", "background", "muted", "border"]) {
1913
+ const f = found[k];
1914
+ if (f && hex2.test(f) && hex2.test(base2[k])) score += distance(toHex(f), toHex(base2[k]));
1915
+ }
1916
+ for (const k of ["fontFamily", "headingFont"]) if (found[k] && found[k] !== base2[k]) score += 60;
1917
+ for (const k of ["bodySize", "headingSize", "contentWidth", "logoWidth"]) if (found[k] !== void 0 && found[k] !== base2[k]) score += 25;
1918
+ if (score < bestScore) {
1919
+ bestScore = score;
1920
+ best = name;
1921
+ }
1922
+ }
1923
+ const base = themeTokens4({ name: best }), tokens = {};
1924
+ for (const [k, v] of Object.entries(found)) if (v !== void 0 && JSON.stringify(v) !== JSON.stringify(base[k])) tokens[k] = v;
1925
+ return { name: best, tokens, exact: !Object.keys(tokens).length };
1926
+ }
1927
+ var SELECTORS = [
1928
+ [/^\.reportic-report$/, () => "document"],
1929
+ [/^\.reportic-report :is\(h1,h2,h3,h4\)$/, () => "heading"],
1930
+ [/^\.reportic-report p$/, () => "paragraph"],
1931
+ [/^\.reportic-report \[data-reportic-type="([\w-]+)"\]$/, (m) => m[1] === "metrics" ? "metric" : m[1]],
1932
+ [/^\.reportic-report \[data-reportic-id="([\w.-]+)"\]$/, (m) => m[1]]
1933
+ ];
1934
+ var kebabToCamel = Object.fromEntries(Object.entries(RULE_PROPS));
1935
+ function readReporticStyle(css, ctx) {
1936
+ const lines = css.replace(/^\s+/, "").split("\n"), generated = lines[0];
1937
+ if (!generated.startsWith(":root{color-scheme:light}")) return void 0;
1938
+ const grab = (re) => re.exec(generated);
1939
+ const found = {};
1940
+ const accent = grab(/--reportic-accent:(#[\da-fA-F]{3,8})/)?.[1], body = grab(/body\{margin:0;background:(#[\da-fA-F]{3,8});color:(#[\da-fA-F]{3,8})\}/), font = grab(/\.reportic-report\{--reportic-accent:[^;]+;font:([\d.]+)px\/1\.75 ([^;]+);max-width:(\d+)px/);
1941
+ if (accent) found.accent = accent;
1942
+ if (body) {
1943
+ found.background = body[1];
1944
+ found.text = body[2];
1945
+ }
1946
+ if (font) {
1947
+ found.bodySize = Number(font[1]);
1948
+ found.fontFamily = font[2];
1949
+ found.contentWidth = Number(font[3]);
1950
+ }
1951
+ const heading = grab(/\.reportic-report h3\{line-height:1\.2;font-family:([^;]+);font-weight:500/)?.[1];
1952
+ if (heading) found.headingFont = heading;
1953
+ const size = grab(/\.reportic-report h1\{font-size:([\d.]+)px;margin:20px 0 24px\}/)?.[1];
1954
+ if (size) found.headingSize = Number(size);
1955
+ const muted = grab(/\.reportic-report blockquote\{[^}]*?color:(#[\da-fA-F]{3,8});/)?.[1];
1956
+ if (muted) found.muted = muted;
1957
+ const border = grab(/\.reportic-report hr\{border:0;border-top:1px solid (#[\da-fA-F]{3,8})[;}]/)?.[1];
1958
+ if (border) found.border = border;
1959
+ const logo = grab(/\[data-reportic-type=logo\] img\{max-width:(\d+)px/)?.[1];
1960
+ if (logo) found.logoWidth = Number(logo);
1961
+ const layout = grab(/--reportic-layout:(page|card)[;}]/)?.[1];
1962
+ if (layout) found.layout = layout;
1963
+ const palette = grab(/--reportic-palette:((?:#[\da-fA-F]{3,8} ?)+)[;}]/)?.[1].trim().split(" ");
1964
+ if (palette) found.chartPalette = palette;
1965
+ const semantic = Object.fromEntries([...generated.matchAll(/--reportic-semantic-(\w+):(#[\da-fA-F]{3,8})(?=[;}])/g)].map((m) => [m[1], m[2]]));
1966
+ if (Object.keys(semantic).length) found.semantic = semantic;
1967
+ if (!accent || !body || !font) return void 0;
1968
+ const { name, tokens, exact } = match(found);
1969
+ if (!exact) ctx.note("THEME_TOKENS", `The page's colors and fonts are not exactly one of the presets. Imported as ${name} with ${Object.keys(tokens).length} token override${Object.keys(tokens).length === 1 ? "" : "s"}.`);
1970
+ const rules = {};
1971
+ let i = 1;
1972
+ for (; i < lines.length; i++) {
1973
+ const m = /^(.*)\{([^{}]*)\}$/.exec(lines[i]);
1974
+ if (!m) break;
1975
+ const matcher = SELECTORS.map(([re, name2]) => {
1976
+ const r = re.exec(m[1]);
1977
+ return r ? name2(r) : void 0;
1978
+ }).find(Boolean);
1979
+ if (!matcher) break;
1980
+ const rule = {};
1981
+ let ok = true;
1982
+ for (const d of m[2].split(";")) {
1983
+ const j = d.indexOf(":"), k = d.slice(0, j), v = d.slice(j + 1);
1984
+ const prop = kebabToCamel[k];
1985
+ if (!prop) {
1986
+ ok = false;
1987
+ break;
1988
+ }
1989
+ rule[prop] = /^-?[\d.]+px$/.test(v) ? Number(v.slice(0, -2)) : /^\d+$/.test(v) && prop === "fontWeight" ? Number(v) : v;
1990
+ }
1991
+ if (!ok) break;
1992
+ rules[matcher] = { ...rules[matcher], ...rule };
1993
+ }
1994
+ const custom = lines.slice(i).join("\n").trim();
1995
+ const theme = { name, ...Object.keys(tokens).length ? { tokens } : {}, ...Object.keys(rules).length ? { rules } : {} };
1996
+ return { theme, css: custom, page: pageOf(custom) };
1997
+ }
1998
+ function parseSelector(selector) {
1999
+ if (/[:+~]|::/.test(selector.replace(/\[[^\]]*\]/g, ""))) {
2000
+ if (/^(:root|html)$/.test(selector.trim())) return { parts: [{ compound: { tag: "html", classes: [], attrs: [] }, combinator: "" }], specificity: 1 };
2001
+ return void 0;
2002
+ }
2003
+ const tokens = selector.replace(/\s*>\s*/g, " > ").trim().split(/\s+/);
2004
+ const parts = [];
2005
+ let specificity = 0, combinator = "";
2006
+ for (const token of tokens) {
2007
+ if (token === ">") {
2008
+ combinator = ">";
2009
+ continue;
2010
+ }
2011
+ const compound = { classes: [], attrs: [] };
2012
+ for (const m of token.matchAll(/(^|[.#])([\w-]+)|\[([\w-]+)(?:=["']?([^\]"']*)["']?)?\]|(\*)/g)) {
2013
+ if (m[3]) {
2014
+ compound.attrs.push([m[3], m[4]]);
2015
+ specificity += 10;
2016
+ } else if (m[1] === ".") {
2017
+ compound.classes.push(m[2]);
2018
+ specificity += 10;
2019
+ } else if (m[1] === "#") {
2020
+ compound.id = m[2];
2021
+ specificity += 100;
2022
+ } else if (m[2]) {
2023
+ compound.tag = m[2].toLowerCase();
2024
+ specificity += 1;
2025
+ }
2026
+ }
2027
+ parts.push({ compound, combinator: parts.length ? combinator || " " : "" });
2028
+ combinator = "";
2029
+ }
2030
+ return parts.length ? { parts, specificity } : void 0;
2031
+ }
2032
+ var parentEl = (el2) => el2.parentNode && isEl(el2.parentNode) ? el2.parentNode : void 0;
2033
+ function matches(el2, parts, at = parts.length - 1) {
2034
+ const { compound } = parts[at];
2035
+ if (compound.tag && el2.tagName !== compound.tag) return false;
2036
+ if (compound.id && attr(el2, "id") !== compound.id) return false;
2037
+ if (compound.classes.some((c) => !classes(el2).includes(c))) return false;
2038
+ if (compound.attrs.some(([k, v]) => {
2039
+ const a = attr(el2, k);
2040
+ return a === void 0 || v !== void 0 && a !== v;
2041
+ })) return false;
2042
+ if (at === 0) return true;
2043
+ const link = parts[at].combinator;
2044
+ if (link === ">") {
2045
+ const p = parentEl(el2);
2046
+ return !!p && matches(p, parts, at - 1);
2047
+ }
2048
+ for (let p = parentEl(el2); p; p = parentEl(p)) if (matches(p, parts, at - 1)) return true;
2049
+ return false;
2050
+ }
2051
+ var INHERITED = /* @__PURE__ */ new Set(["color", "font-family", "font-size", "font-weight", "text-align", "line-height"]);
2052
+ var Cascade = class {
2053
+ rules = [];
2054
+ constructor(css) {
2055
+ for (const r of parseCss(css).rules) {
2056
+ if (r.media && !/screen|all/i.test(r.media)) continue;
2057
+ const s = parseSelector(r.selector);
2058
+ if (s) this.rules.push({ ...s, decls: r.decls, order: r.order });
2059
+ }
2060
+ this.rules.sort((a, b) => a.specificity - b.specificity || a.order - b.order);
2061
+ }
2062
+ get(el2, property) {
2063
+ let value;
2064
+ for (const r of this.rules) {
2065
+ const v = r.decls[property] ?? (property === "background-color" ? r.decls.background : void 0);
2066
+ if (v !== void 0 && matches(el2, r.parts)) value = v;
2067
+ }
2068
+ const inline2 = attr(el2, "style");
2069
+ if (inline2) {
2070
+ const m = new RegExp(`(?:^|;)\\s*${property.replace("-", "\\-")}\\s*:\\s*([^;]+)`, "i").exec(inline2) ?? (property === "background-color" ? /(?:^|;)\s*background\s*:\s*([^;]+)/i.exec(inline2) : null);
2071
+ if (m) value = m[1].trim();
2072
+ }
2073
+ if (value === void 0 && INHERITED.has(property)) {
2074
+ const p = parentEl(el2);
2075
+ if (p && p.tagName !== "html") return this.get(p, property);
2076
+ }
2077
+ return value;
2078
+ }
2079
+ };
2080
+ var all = (doc, test) => {
2081
+ const out = [];
2082
+ const visit = (n) => {
2083
+ for (const k of kids(n)) if (isEl(k)) {
2084
+ if (test(k)) out.push(k);
2085
+ visit(k);
2086
+ }
2087
+ };
2088
+ visit(doc);
2089
+ return out;
2090
+ };
2091
+ var same = (values) => values.length && values.every((v) => v !== void 0 && v === values[0]) ? values[0] : void 0;
2092
+ function readPageStyle(doc, css, ctx) {
2093
+ const cascade = new Cascade(css), body = all(doc, (e) => e.tagName === "body")[0], first = (name2) => all(doc, (e) => e.tagName === name2)[0];
2094
+ const found = {};
2095
+ if (body) {
2096
+ const bg = toHex(colorIn(cascade.get(body, "background-color")) ?? void 0), text2 = toHex(cascade.get(body, "color"));
2097
+ if (bg) found.background = bg;
2098
+ if (text2) found.text = text2;
2099
+ const family = cleanFont(cascade.get(body, "font-family"));
2100
+ if (family) found.fontFamily = family;
2101
+ const size = px(cascade.get(body, "font-size"));
2102
+ if (size && size >= 8 && size <= 40) found.bodySize = size;
2103
+ }
2104
+ const link = first("a"), h1 = first("h1") ?? first("h2"), th = first("th");
2105
+ const accent = [link && toHex(cascade.get(link, "color")), h1 && toHex(cascade.get(h1, "color")), th && colorIn(cascade.get(th, "background-color"))].find((c) => c && c !== found.text && c !== found.background);
2106
+ if (accent) found.accent = accent;
2107
+ const note = all(doc, (e) => ["figcaption", "small", "caption", "blockquote"].includes(e.tagName))[0] ?? all(doc, (e) => classes(e).some((c) => /muted|subtle|secondary/.test(c)))[0];
2108
+ const muted = note && toHex(cascade.get(note, "color"));
2109
+ if (muted && muted !== found.text) found.muted = muted;
2110
+ const cell = first("td") ?? th, border = cell && ["border-bottom", "border", "border-top", "border-color"].map((p) => colorIn(cascade.get(cell, p))).find(Boolean);
2111
+ if (border) found.border = border;
2112
+ if (h1) {
2113
+ const hf = cleanFont(cascade.get(h1, "font-family"));
2114
+ if (hf && hf !== found.fontFamily) found.headingFont = hf;
2115
+ const hs = px(cascade.get(h1, "font-size"), found.bodySize ?? 16);
2116
+ if (hs && hs >= 14 && hs <= 96 && hs !== found.bodySize) found.headingSize = hs;
2117
+ }
2118
+ const container = all(doc, (e) => ["main", "article"].includes(e.tagName) || classes(e).some((c) => /^(container|wrapper|page|content|report)$/.test(c)))[0] ?? body;
2119
+ const width = container && px(cascade.get(container, "max-width"));
2120
+ if (width && width >= 400 && width <= 2e3) found.contentWidth = width;
2121
+ const { name, tokens } = match(found);
2122
+ const dropped = ["accent", "text", "background"].filter((k) => !found[k]);
2123
+ ctx.note("THEME_REDUCED", `Reduced the page's design to the ${name} preset${Object.keys(tokens).length ? ` with overrides for ${Object.keys(tokens).join(", ")}` : ""}${dropped.length ? `; ${dropped.join(", ")} not found, so the preset's value is used` : ""}.`);
2124
+ const base = themeTokens4({ name, tokens }), rules = {};
2125
+ const rule = (key2, props) => {
2126
+ const clean2 = Object.fromEntries(Object.entries(props).filter(([, v]) => v !== void 0));
2127
+ if (Object.keys(clean2).length) rules[key2] = clean2;
2128
+ };
2129
+ const headings = all(doc, (e) => /^h[1-4]$/.test(e.tagName)), paragraphs = all(doc, (e) => e.tagName === "p"), tables = all(doc, (e) => e.tagName === "table");
2130
+ const diff = (v, expected) => v && v !== expected ? v : void 0;
2131
+ rule("heading", { color: diff(same(headings.map((h5) => toHex(cascade.get(h5, "color")))), base.text), textAlign: /* @__PURE__ */ ((a) => a && a !== "left" && a !== "start" ? a : void 0)(same(headings.map((h5) => cascade.get(h5, "text-align")))) });
2132
+ rule("paragraph", { color: diff(same(paragraphs.map((p) => toHex(cascade.get(p, "color")))), base.text), textAlign: ((a) => a && ["center", "right", "justify"].includes(a) ? a : void 0)(same(paragraphs.map((p) => cascade.get(p, "text-align")))), fontSize: ((s) => s && Math.abs(s - base.bodySize) > 0.5 ? s : void 0)(same(paragraphs.map((p) => px(cascade.get(p, "font-size"), base.bodySize)))) });
2133
+ rule("table", { backgroundColor: ((c) => c && c !== base.background ? c : void 0)(same(tables.map((t) => colorIn(cascade.get(t, "background-color"))))) });
2134
+ const rulesCount = Object.keys(rules).length;
2135
+ if (rulesCount) ctx.note("THEME_RULES", `Kept ${rulesCount} block style${rulesCount === 1 ? "" : "s"} that differ from the document: ${Object.keys(rules).join(", ")}.`);
2136
+ const SAFE = /* @__PURE__ */ new Set(["color", "background-color", "border", "border-top", "border-bottom", "border-left", "border-right", "border-radius", "padding", "margin", "font-size", "font-weight", "font-style", "line-height", "letter-spacing", "text-transform", "text-align", "text-decoration", "width", "max-width", "vertical-align"]);
2137
+ const TAGS = /^(h[1-6]|p|a|ul|ol|li|table|thead|tbody|tr|th|td|blockquote|code|pre|hr|img|figure|figcaption|strong|em)$/;
2138
+ const left = [];
2139
+ for (const r of parseCss(css).rules) {
2140
+ if (r.media && !/print|screen|all/i.test(r.media)) continue;
2141
+ const parts = r.selector.split(/\s+/);
2142
+ if (parts.length > 3 || !parts.every((p) => p === ">" || TAGS.test(p))) continue;
2143
+ const decls = Object.entries(r.decls).filter(([k, v]) => SAFE.has(k) && !unsafe.test(v) && !/^var\(/.test(v)).map(([k, v]) => `${k}:${v}`);
2144
+ if (!decls.length) continue;
2145
+ const text2 = `.reportic-report ${r.selector}{${decls.join(";")}}`;
2146
+ left.push(r.media ? `${r.media}{${text2}}` : text2);
2147
+ }
2148
+ const leftover = left.join("\n").slice(0, 16e3);
2149
+ if (leftover) ctx.note("CSS_LEFTOVERS", `${left.length} plain element rule${left.length === 1 ? "" : "s"} from the page were kept as report css. Word and PowerPoint do not use them.`);
2150
+ return { theme: { name, ...Object.keys(tokens).length ? { tokens } : {}, ...rulesCount ? { rules } : {} }, css: leftover, page: pageOf(css) };
2151
+ }
2152
+
2153
+ // packages/reportic-render-html/src/import/rebind.ts
2154
+ import { figureKinds, figureSpec, formatValue as formatValue2, parseFigure } from "@x12i/reportic-core";
2155
+ var isRec = (v) => !!v && typeof v === "object" && !Array.isArray(v);
2156
+ var norm = (s) => s.replace(/\s+/g, " ").trim();
2157
+ var GROUPED = new Intl.NumberFormat("en-US", { maximumFractionDigits: 20 });
2158
+ var SEGMENT = /^[A-Za-z0-9_-]+$/;
2159
+ var UNSAFE = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
2160
+ var NUMBERISH = /^[+\-\u2212]?[\p{Sc}]?[\d.,]+\s?%?$/u;
2161
+ var WORD = /[\p{L}\p{N}_]/u;
2162
+ var NUMBER_EDGE = /[\p{L}\p{N}_.,\-:/]/u;
2163
+ var KINDS = new Set(figureKinds);
2164
+ var goodKey = (k) => SEGMENT.test(k) && !UNSAFE.has(k);
2165
+ var shows = (v) => {
2166
+ if (typeof v === "string") {
2167
+ const s = norm(v);
2168
+ return s ? [s] : [];
2169
+ }
2170
+ if (typeof v === "number" && Number.isFinite(v)) return [.../* @__PURE__ */ new Set([String(v), GROUPED.format(v)])];
2171
+ return [];
2172
+ };
2173
+ var add = (map, key2, path) => {
2174
+ const set = map.get(key2);
2175
+ if (set) set.add(path);
2176
+ else map.set(key2, /* @__PURE__ */ new Set([path]));
2177
+ };
2178
+ var valueAt = (rec, field) => field.split(".").reduce((v, k) => isRec(v) ? v[k] : void 0, rec);
2179
+ var truthy = (v) => !(v === void 0 || v === null || v === false || v === 0 || v === "") && (Array.isArray(v) ? v.length > 0 : isRec(v) ? Object.keys(v).length > 0 : true);
2180
+ var canonical = (v) => JSON.stringify(v, (_k, x) => isRec(x) ? Object.fromEntries(Object.entries(x).sort(([a], [b]) => a < b ? -1 : 1)) : x);
2181
+ var Layer = class {
2182
+ scalars = /* @__PURE__ */ new Map();
2183
+ universe = /* @__PURE__ */ new Map();
2184
+ arrays = [];
2185
+ objects = [];
2186
+ joined = /* @__PURE__ */ new Map();
2187
+ nodes = 0;
2188
+ constructor(root, prefix) {
2189
+ this.walk(root, prefix, true, 0);
2190
+ }
2191
+ walk(v, path, bindable, depth) {
2192
+ if (++this.nodes > 6e4 || depth > 10) return;
2193
+ if (typeof v === "string" || typeof v === "number") {
2194
+ for (const s of shows(v)) {
2195
+ this.universe.set(s, (this.universe.get(s) ?? 0) + 1);
2196
+ if (bindable) add(this.scalars, s, path);
2197
+ }
2198
+ return;
2199
+ }
2200
+ if (Array.isArray(v)) {
2201
+ if (bindable) {
2202
+ this.arrays.push({ path, items: v });
2203
+ if (v.length >= 2 && v.every((x) => typeof x === "string" && norm(x))) for (const sep of [" \xB7 ", ", ", "; "]) add(this.joined, `${sep}\0${v.map((x) => norm(x)).join(sep)}`, path);
2204
+ }
2205
+ for (const x of v) this.walk(x, path, false, depth + 1);
2206
+ return;
2207
+ }
2208
+ if (isRec(v)) {
2209
+ if (bindable) this.objects.push({ path, value: v });
2210
+ for (const [k, x] of Object.entries(v)) this.walk(x, `${path}.${k}`, bindable && goodKey(k), depth + 1);
2211
+ }
2212
+ }
2213
+ };
2214
+ var View = class _View {
2215
+ constructor(layers) {
2216
+ this.layers = layers;
2217
+ }
2218
+ layers;
2219
+ withRow(row) {
2220
+ return new _View([...this.layers, new Layer(row, "row")]);
2221
+ }
2222
+ get arrays() {
2223
+ return this.layers.flatMap((l) => l.arrays);
2224
+ }
2225
+ get objects() {
2226
+ return this.layers.flatMap((l) => l.objects);
2227
+ }
2228
+ paths(text2) {
2229
+ const out = /* @__PURE__ */ new Set();
2230
+ for (const l of this.layers) for (const p of l.scalars.get(text2) ?? []) out.add(p);
2231
+ return out;
2232
+ }
2233
+ seen(text2) {
2234
+ return this.layers.reduce((n, l) => n + (l.universe.get(text2) ?? 0), 0);
2235
+ }
2236
+ shortOrNumber = (s) => s.length < 6 || NUMBERISH.test(s);
2237
+ /** A slot whose whole text is one field. A short or numeric text (Pending, 0, 1) is bound only when no other value in the sample shows the same. */
2238
+ lookup(text2) {
2239
+ const s = norm(text2);
2240
+ if (!s) return void 0;
2241
+ const paths = this.paths(s);
2242
+ if (!paths.size) return void 0;
2243
+ if (paths.size > 1) return { collision: [...paths].slice(0, 6) };
2244
+ if (this.shortOrNumber(s) && this.seen(s) > 1) return { collision: [[...paths][0]] };
2245
+ return { path: [...paths][0] };
2246
+ }
2247
+ /** A text made of several fields: each field found once, the rest written as it was. Anything unclear leaves the text alone. */
2248
+ segment(text2) {
2249
+ if (text2.length < 3) return void 0;
2250
+ const cuts = [];
2251
+ let ambiguous = false;
2252
+ const find2 = (display) => {
2253
+ const at2 = [];
2254
+ for (let i = text2.indexOf(display); i >= 0; i = text2.indexOf(display, i + 1)) {
2255
+ const before = text2[i - 1], after = text2[i + display.length];
2256
+ const edge = NUMBERISH.test(display) ? NUMBER_EDGE : WORD;
2257
+ if (WORD.test(display[0]) && before && edge.test(before)) continue;
2258
+ if (WORD.test(display[display.length - 1]) && after && edge.test(after)) continue;
2259
+ at2.push(i);
2260
+ }
2261
+ return at2;
2262
+ };
2263
+ const seenDisplays = /* @__PURE__ */ new Set();
2264
+ for (const layer of this.layers) for (const display of layer.scalars.keys()) {
2265
+ if (seenDisplays.has(display) || !text2.includes(display)) continue;
2266
+ seenDisplays.add(display);
2267
+ const paths = this.paths(display), at2 = find2(display);
2268
+ if (!at2.length) continue;
2269
+ if (paths.size > 1) {
2270
+ if (display.length >= 6) ambiguous = true;
2271
+ continue;
2272
+ }
2273
+ if (this.shortOrNumber(display) && this.seen(display) > 1) continue;
2274
+ if (at2.length > 1) {
2275
+ ambiguous = true;
2276
+ continue;
2277
+ }
2278
+ cuts.push({ start: at2[0], end: at2[0] + display.length, part: { $bind: [...paths][0] } });
2279
+ }
2280
+ for (const layer of this.layers) for (const [key2, paths] of layer.joined) {
2281
+ const [sep, display] = key2.split("\0");
2282
+ if (!text2.includes(display)) continue;
2283
+ const at2 = find2(display);
2284
+ if (!at2.length) continue;
2285
+ if (paths.size > 1 || at2.length > 1) {
2286
+ ambiguous = true;
2287
+ continue;
2288
+ }
2289
+ cuts.push({ start: at2[0], end: at2[0] + display.length, part: { value: { $bind: [...paths][0] }, join: sep } });
2290
+ }
2291
+ if (ambiguous) return "ambiguous";
2292
+ const chosen = [];
2293
+ for (const c of [...cuts].sort((a, b) => b.end - b.start - (a.end - a.start) || a.start - b.start)) if (!chosen.some((o) => c.start < o.end && o.start < c.end)) chosen.push(c);
2294
+ chosen.sort((a, b) => a.start - b.start);
2295
+ const covered = chosen.reduce((n, c) => n + c.end - c.start, 0);
2296
+ if (!chosen.length || covered < text2.trim().length / 2 && !chosen.some((c) => c.end - c.start >= 6)) return void 0;
2297
+ const parts = [];
2298
+ let at = 0;
2299
+ for (const c of chosen) {
2300
+ if (c.start > at) parts.push(text2.slice(at, c.start));
2301
+ parts.push(c.part);
2302
+ at = c.end;
2303
+ }
2304
+ if (at < text2.length) parts.push(text2.slice(at));
2305
+ return parts.length <= 12 ? parts : void 0;
2306
+ }
2307
+ };
2308
+ var slotOf = (st, el2, slot, text2, reason, candidates) => st.sink.push({ elementId: el2.id, slot, text: text2.length > 140 ? `${text2.slice(0, 137)}...` : text2, reason, ...candidates?.length ? { candidates } : {} });
2309
+ function bindText(el2, key2, view, st, holder = el2.props, slot = `props.${key2}`) {
2310
+ const v = holder[key2];
2311
+ if (typeof v !== "string" || !norm(v)) return;
2312
+ const hit = view.lookup(v);
2313
+ if (!hit) slotOf(st, el2, slot, v, "no-match");
2314
+ else if ("collision" in hit) slotOf(st, el2, slot, v, "collision", hit.collision);
2315
+ else {
2316
+ holder[key2] = { $bind: hit.path };
2317
+ st.bound.n++;
2318
+ }
2319
+ }
2320
+ function want(cell, column) {
2321
+ if (typeof cell === "string") return { kind: "text", text: norm(cell) };
2322
+ if (typeof cell === "number" || typeof cell === "boolean") return { kind: "text", text: String(cell) };
2323
+ if (cell === null) return { kind: "text", text: "" };
2324
+ if (Array.isArray(cell) || !isRec(cell)) return void 0;
2325
+ if (typeof cell.tone === "string" && typeof cell.label === "string" && Object.keys(cell).length === 2) return { kind: "rating", tone: cell.tone, label: norm(cell.label) };
2326
+ if ("value" in cell) {
2327
+ if (["kind", "format"].some((k) => k in cell && cell[k] !== column[k])) return void 0;
2328
+ const inner = cell.value;
2329
+ if (Array.isArray(inner)) return inner.every((x) => typeof x === "string") ? { kind: "list", items: inner.map((x) => norm(x)) } : void 0;
2330
+ return want(inner, column);
2331
+ }
2332
+ return void 0;
2333
+ }
2334
+ function has(w, value, column, st) {
2335
+ if (w.kind === "list") return Array.isArray(value) && value.length === w.items.length && value.every((x, i) => typeof x === "string" && norm(x) === w.items[i]);
2336
+ if (w.kind === "rating") return isRec(value) && value.tone === w.tone && typeof value.label === "string" && norm(value.label) === w.label;
2337
+ if (value === void 0 || value === null) return w.text === "";
2338
+ if (typeof value === "boolean") return w.text === String(value);
2339
+ if (shows(value).includes(w.text)) return true;
2340
+ if (w.text === "" && value === "") return true;
2341
+ if (column.format && typeof value === "number") {
2342
+ try {
2343
+ return norm(formatValue2(value, column.format, st.locale, st.tz)) === w.text;
2344
+ } catch {
2345
+ return false;
2346
+ }
2347
+ }
2348
+ return false;
2349
+ }
2350
+ function fieldsOf(items) {
2351
+ const out = /* @__PURE__ */ new Set();
2352
+ for (const r of items.slice(0, 50)) for (const [k, v] of Object.entries(r)) {
2353
+ if (!goodKey(k)) continue;
2354
+ out.add(k);
2355
+ if (isRec(v)) {
2356
+ for (const j of Object.keys(v)) if (goodKey(j)) out.add(`${k}.${j}`);
2357
+ }
2358
+ }
2359
+ return [...out];
2360
+ }
2361
+ var alias = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, "");
2362
+ function explain(cells, columns, items, st) {
2363
+ if (!columns.length || items.length !== cells.length) return void 0;
2364
+ const fields = fieldsOf(items), out = [];
2365
+ for (let c = 0; c < columns.length; c++) {
2366
+ const wants = cells.map((r) => want(r[c], columns[c]));
2367
+ if (wants.some((w) => !w)) return void 0;
2368
+ const found = fields.filter((f) => wants.every((w, i) => has(w, valueAt(items[i], f), columns[c], st)));
2369
+ if (found.length) {
2370
+ const named = found.find((f) => alias(f) === alias(String(columns[c].label ?? "")));
2371
+ const field = named ?? found[0];
2372
+ out.push({ field, others: found.filter((f) => f !== field) });
2373
+ } else if (items.length > 1 && wants.every((w) => canonical(w) === canonical(wants[0]))) out.push({ constant: cells[0][c] });
2374
+ else return void 0;
2375
+ }
2376
+ return out.some((x) => x && "field" in x) ? out : void 0;
2377
+ }
2378
+ var clone = (v) => structuredClone(v);
2379
+ function uniqueList(view, test) {
2380
+ const hits = view.arrays.map((a) => ({ ...a, result: test(a) })).filter((a) => a.result !== void 0);
2381
+ if (hits.length === 1) return { hit: hits[0] };
2382
+ if (hits.length > 1) return { collision: hits.map((h5) => h5.path).slice(0, 6) };
2383
+ return void 0;
2384
+ }
2385
+ var withFormats = (columns, el2) => columns.map((c, i) => ({ ...c, ...c.format === void 0 && el2.meta?.formats?.[i] ? { format: el2.meta.formats[i] } : {} }));
2386
+ function boundColumns(columns, explained) {
2387
+ return columns.map((c, i) => {
2388
+ const e = explained[i], { value: _drop, ...rest } = c;
2389
+ if ("field" in e) return { ...rest, value: { $bind: `row.${e.field}`, default: "" } };
2390
+ const { format: _format, ...plain } = rest;
2391
+ return { ...plain, value: clone(e.constant) };
2392
+ });
2393
+ }
2394
+ function bindGrid(el2, view, st) {
2395
+ const p = el2.props, rows = p.rows;
2396
+ if (!Array.isArray(rows) || !rows.length || !Array.isArray(p.columns)) return;
2397
+ const columns = withFormats(p.columns, el2);
2398
+ const found = uniqueList(view, (a) => a.items.every(isRec) ? explain(rows, columns, a.items, st) : void 0);
2399
+ if (found && "hit" in found) {
2400
+ const { path, result } = found.hit;
2401
+ el2.type = "table";
2402
+ delete el2.meta;
2403
+ el2.props = { rows: { $bind: path }, columns: boundColumns(columns, result), ...p.headers === false ? { headers: false } : {}, ...p.rowHeader ? { rowHeader: true } : {} };
2404
+ for (const e of result) if (e && "field" in e && e.others.length) st.ctx.note("BIND_AMBIGUOUS_COLUMN", `A column could be ${e.field} or ${e.others.join(", ")}; ${e.field} was used.`, { elementId: el2.id, candidates: [e.field, ...e.others].slice(0, 6) });
2405
+ st.bound.n++;
2406
+ return;
2407
+ }
2408
+ const detailed = p.rowHeader === true;
2409
+ if (found && "collision" in found) slotOf(st, el2, "props.rows", String(rows[0]?.[0] ?? ""), "collision", found.collision);
2410
+ else if (!detailed) slotOf(st, el2, "props.rows", rows.slice(0, 2).map((r) => r.map((x) => typeof x === "string" ? x : "").join(" | ")).join(" / "), "no-match");
2411
+ rows.forEach((row, r) => {
2412
+ row.forEach((cell, c) => {
2413
+ if (detailed && c === 0) return;
2414
+ const slot = `props.rows[${r}][${c}]`;
2415
+ const piece = (s) => {
2416
+ const whole = view.lookup(s);
2417
+ if (whole && "path" in whole) {
2418
+ st.bound.n++;
2419
+ return { $bind: whole.path };
2420
+ }
2421
+ const parts = view.segment(s);
2422
+ if (parts === "ambiguous") {
2423
+ if (s.length >= 8) slotOf(st, el2, slot, s, "composed-ambiguous");
2424
+ return s;
2425
+ }
2426
+ if (parts) {
2427
+ st.bound.n++;
2428
+ return parts;
2429
+ }
2430
+ if (detailed && s.length >= 3) slotOf(st, el2, slot, s, whole && "collision" in whole ? "collision" : "no-match", whole && "collision" in whole ? whole.collision : void 0);
2431
+ return s;
2432
+ };
2433
+ const flat = (v) => Array.isArray(v) ? v : [v];
2434
+ if (typeof cell === "string") row[c] = piece(cell);
2435
+ else if (Array.isArray(cell) && cell.some((x) => typeof x === "string")) row[c] = cell.flatMap((x) => typeof x === "string" && norm(x) ? flat(piece(x)) : [x]);
2436
+ });
2437
+ });
2438
+ }
2439
+ function unformat(text2, format, st) {
2440
+ const n = Number(text2.replace(/[^\d.\-]/g, "")) / (format.startsWith("percent") ? 100 : 1);
2441
+ if (!Number.isFinite(n) || !/\d/.test(text2)) return void 0;
2442
+ try {
2443
+ return norm(formatValue2(n, format, st.locale, st.tz)) === norm(text2) ? n : void 0;
2444
+ } catch {
2445
+ return void 0;
2446
+ }
2447
+ }
2448
+ function bindLiteralTable(el2, view, st) {
2449
+ const p = el2.props, rows = p.rows, literal = p.columns;
2450
+ if (!Array.isArray(rows) || !rows.length || !Array.isArray(literal) || rows.some((r) => !isRec(r))) return;
2451
+ const keys = literal.map((c) => isRec(c.value) && typeof c.value.$bind === "string" && c.value.$bind.startsWith("row.") ? c.value.$bind.slice(4) : void 0);
2452
+ if (keys.some((k) => !k)) return;
2453
+ const columns = withFormats(literal.map(({ value: _v, ...c }) => c), el2), cells = rows.map((r) => keys.map((k) => r[k]));
2454
+ const found = uniqueList(view, (a) => a.items.every(isRec) ? explain(cells, columns, a.items, st) : void 0);
2455
+ const first = String(cells[0]?.[0] ?? "");
2456
+ if (!found) {
2457
+ slotOf(st, el2, "props.rows", first, "no-match");
2458
+ return;
2459
+ }
2460
+ if ("collision" in found) {
2461
+ slotOf(st, el2, "props.rows", first, "collision", found.collision);
2462
+ return;
2463
+ }
2464
+ const { path, result } = found.hit;
2465
+ let total;
2466
+ if (isRec(p.total)) {
2467
+ total = {};
2468
+ for (const [i, e] of result.entries()) {
2469
+ if (!e || !("field" in e)) continue;
2470
+ const text2 = p.total[keys[i]], format = columns[i].format;
2471
+ if (format && typeof text2 === "string") {
2472
+ const n = unformat(text2, format, st);
2473
+ if (n === void 0) {
2474
+ slotOf(st, el2, "props.total", text2, "no-match");
2475
+ return;
2476
+ }
2477
+ total[e.field] = n;
2478
+ } else total[e.field] = text2;
2479
+ }
2480
+ }
2481
+ p.rows = { $bind: path };
2482
+ p.columns = boundColumns(columns, result);
2483
+ if (total) p.total = total;
2484
+ delete el2.meta;
2485
+ st.bound.n++;
2486
+ }
2487
+ function bindList(el2, view, st) {
2488
+ const p = el2.props, rows = p.rows;
2489
+ if (!Array.isArray(rows) || !rows.length) return;
2490
+ const keys = ["lead", "text"].filter((k) => p[k] !== void 0);
2491
+ if (rows.every((r) => typeof r === "string")) {
2492
+ const found2 = uniqueList(view, (a) => a.items.length === rows.length && a.items.every((x) => typeof x === "string") && a.items.every((x, i) => norm(x) === norm(rows[i])) ? true : void 0);
2493
+ if (found2 && "hit" in found2) {
2494
+ p.rows = { $bind: found2.hit.path };
2495
+ st.bound.n++;
2496
+ } else slotOf(st, el2, "props.rows", String(rows[0]), found2 ? "collision" : "no-match", found2 && "collision" in found2 ? found2.collision : void 0);
2497
+ return;
2498
+ }
2499
+ if (!rows.every(isRec)) return;
2500
+ const cells = rows.map((r) => keys.map((k) => typeof r[k] === "string" ? r[k] : "")), columns = keys.map((k) => ({ label: k }));
2501
+ const found = uniqueList(view, (a) => a.items.every(isRec) ? explain(cells, columns, a.items, st) : void 0);
2502
+ if (found && "hit" in found) {
2503
+ p.rows = { $bind: found.hit.path };
2504
+ keys.forEach((k, i) => {
2505
+ const e = found.hit.result[i];
2506
+ p[k] = "field" in e ? { $bind: `row.${e.field}` } : clone(e.constant);
2507
+ });
2508
+ st.bound.n++;
2509
+ } else slotOf(st, el2, "props.rows", String(rows[0].text ?? ""), found ? "collision" : "no-match", found && "collision" in found ? found.collision : void 0);
2510
+ }
2511
+ function bindRecords(el2, key2, known, view, st) {
2512
+ const lit = el2.props[key2];
2513
+ if (!Array.isArray(lit) || !lit.length || !lit.every(isRec)) return;
2514
+ const same2 = (a, b) => typeof a === "boolean" || typeof b === "boolean" ? a === b : typeof a === "number" && typeof b === "number" ? a === b : (shows(a)[0] ?? "") === (shows(b)[0] ?? "");
2515
+ const found = uniqueList(view, (a) => a.items.length === lit.length && a.items.every(isRec) && lit.every((r, i) => known.every((k) => same2(r[k], a.items[i][k]))) ? true : void 0);
2516
+ if (found && "hit" in found) {
2517
+ el2.props[key2] = { $bind: found.hit.path };
2518
+ st.bound.n++;
2519
+ return;
2520
+ }
2521
+ slotOf(st, el2, `props.${key2}`, String(lit[0][known[0]] ?? ""), found ? "collision" : "no-match", found && "collision" in found ? found.collision : void 0);
2522
+ }
2523
+ function bindMetrics(el2, view, st) {
2524
+ const lit = el2.props.items;
2525
+ if (!Array.isArray(lit) || !lit.length || !lit.every(isRec)) return;
2526
+ const shown = (r) => {
2527
+ try {
2528
+ return norm(String(formatValue2(r.value, r.format, st.locale, st.tz)));
2529
+ } catch {
2530
+ return "";
2531
+ }
2532
+ };
2533
+ const asText = (v) => typeof v === "string" ? norm(v) : "";
2534
+ const found = uniqueList(view, (a) => {
2535
+ if (a.items.length !== lit.length || !a.items.every(isRec)) return void 0;
2536
+ if (!lit.every((t, i) => asText(a.items[i].label) === asText(t.label) && shown(a.items[i]) === asText(t.value) && asText(a.items[i].tone) === asText(t.tone))) return void 0;
2537
+ const wants = lit.map((t) => asText(t.comparison));
2538
+ if (a.items.every((r, i) => asText(r.comparison) === wants[i])) return { key: void 0 };
2539
+ if (a.items.some((r) => asText(r.comparison))) return void 0;
2540
+ const keys = fieldsOf(a.items).filter((f) => !f.includes(".") && !["label", "value", "tone", "format", "comparison"].includes(f) && a.items.every((r, i) => typeof (r[f] ?? "") === "string" && asText(r[f]) === wants[i]));
2541
+ return keys.length ? { key: keys.find((k) => /delta|comparison|change|note/.test(k)) ?? keys[0] } : void 0;
2542
+ });
2543
+ if (found && "hit" in found) {
2544
+ el2.props.items = { $bind: found.hit.path };
2545
+ if (found.hit.result.key) el2.props.comparisonKey = found.hit.result.key;
2546
+ st.bound.n++;
2547
+ return;
2548
+ }
2549
+ if (found) slotOf(st, el2, "props.items", asText(lit[0].label), "collision", found.collision);
2550
+ else {
2551
+ let any = false;
2552
+ for (const t of lit) for (const k of ["label", "value", "comparison"]) {
2553
+ const before = t[k];
2554
+ bindText(el2, k, view, { ...st, sink: [] }, t);
2555
+ if (isRec(t[k]) && t[k] !== before) {
2556
+ any = true;
2557
+ st.bound.n++;
2558
+ }
2559
+ }
2560
+ if (!any) slotOf(st, el2, "props.items", asText(lit[0].label), "no-match");
2561
+ }
2562
+ }
2563
+ function bindSpec(el2, view, st) {
2564
+ const lit = el2.props.spec;
2565
+ if (!isRec(lit)) return;
2566
+ let key2;
2567
+ try {
2568
+ key2 = canonical(figureSpec(parseFigure(lit)));
2569
+ } catch {
2570
+ return;
2571
+ }
2572
+ const hits = view.objects.filter((o) => typeof o.value.type === "string" && KINDS.has(o.value.type)).filter((o) => {
2573
+ try {
2574
+ return canonical(figureSpec(parseFigure(o.value))) === key2;
2575
+ } catch {
2576
+ return false;
2577
+ }
2578
+ });
2579
+ const paths = [...new Set(hits.map((h5) => h5.path))];
2580
+ if (paths.length === 1) {
2581
+ el2.props.spec = { $bind: paths[0] };
2582
+ st.bound.n++;
2583
+ } else slotOf(st, el2, "props.spec", String(lit.title ?? lit.type), paths.length ? "collision" : "no-match", paths.slice(0, 6));
2584
+ }
2585
+ function bindElement(el2, view, st) {
2586
+ const p = el2.props;
2587
+ switch (el2.type) {
2588
+ case "reportic.masthead.v1":
2589
+ for (const k of ["marking", "kicker", "title", "lead"]) bindText(el2, k, view, st);
2590
+ if (Array.isArray(p.byline)) p.byline.forEach((item, i) => {
2591
+ if (isRec(item)) bindText(el2, "value", view, st, item, `props.byline[${i}].value`);
2592
+ else if (typeof item === "string") bindText(el2, String(i), view, st, p.byline, `props.byline[${i}]`);
2593
+ });
2594
+ break;
2595
+ case "reportic.footer.v1":
2596
+ bindText(el2, "text", view, st);
2597
+ break;
2598
+ case "narrative":
2599
+ bindText(el2, "text", view, st);
2600
+ bindText(el2, "heading", view, st);
2601
+ break;
2602
+ case "reportic.callout.v1":
2603
+ bindText(el2, "title", view, st);
2604
+ bindText(el2, "text", view, st);
2605
+ break;
2606
+ case "reportic.heading.v1":
2607
+ bindText(el2, "text", view, st);
2608
+ break;
2609
+ case "reportic.figure.v1":
2610
+ bindSpec(el2, view, st);
2611
+ bindText(el2, "source", view, st);
2612
+ break;
2613
+ case "reportic.grid.v1":
2614
+ bindGrid(el2, view, st);
2615
+ break;
2616
+ case "table":
2617
+ bindLiteralTable(el2, view, st);
2618
+ break;
2619
+ case "list":
2620
+ bindList(el2, view, st);
2621
+ break;
2622
+ case "metrics":
2623
+ bindMetrics(el2, view, st);
2624
+ break;
2625
+ case "reportic.timeline.v1":
2626
+ bindRecords(el2, "items", ["date", "title", "text"], view, st);
2627
+ break;
2628
+ case "reportic.checklist.v1":
2629
+ bindRecords(el2, "items", ["text", "done", "owner"], view, st);
2630
+ break;
2631
+ case "reportic.progress.v1":
2632
+ bindRecords(el2, "items", ["label", "value", "detail"], view, st);
2633
+ break;
2634
+ case "reportic.comparison.v1":
2635
+ bindRecords(el2, "rows", ["label", "left", "right"], view, st);
2636
+ break;
2637
+ case "group":
2638
+ bindText(el2, "heading", view, st);
2639
+ if (Array.isArray(p.children)) p.children = sequence(p.children, view, st);
2640
+ break;
2641
+ }
2642
+ }
2643
+ function cloneEl(e) {
2644
+ const props = Object.fromEntries(Object.entries(e.props).map(([k, v]) => [k, k === "children" && Array.isArray(v) ? v.map(cloneEl) : clone(v)]));
2645
+ const copy = { id: e.id, type: e.type, props, ...e.when !== void 0 ? { when: clone(e.when) } : {}, ...e.meta ? { meta: e.meta } : {} };
2646
+ const base = baseOf.get(e);
2647
+ if (base) baseOf.set(copy, base);
2648
+ return copy;
2649
+ }
2650
+ var binds = (props) => {
2651
+ const skip = Array.isArray(props.rows) || isRec(props.rows) && "$bind" in props.rows ? /* @__PURE__ */ new Set(["columns", "lead", "text"]) : /* @__PURE__ */ new Set();
2652
+ return Object.entries(props).filter(([k]) => !skip.has(k)).flatMap(([, v]) => isRec(v) && typeof v.$bind === "string" && v.$bind.startsWith("row.") ? [v.$bind] : []);
2653
+ };
2654
+ var sameElement = (a, b) => a.type === b.type && canonical(a.props) === canonical(b.props);
2655
+ function attempt(groups, list2, view, st) {
2656
+ const local = { ...st, sink: [], bound: { n: 0 } }, n = groups.length;
2657
+ const keyed = groups.map((g, k) => {
2658
+ const rowView = view.withRow(list2.items[k]), seen = /* @__PURE__ */ new Map();
2659
+ return sequence(g.props.children.map(cloneEl), rowView, local).map((e) => {
2660
+ const base = baseOf.get(e) ?? e.type, at = (seen.get(base) ?? 0) + 1;
2661
+ seen.set(base, at);
2662
+ return { key: `${base}#${at}`, e };
2663
+ });
2664
+ });
2665
+ const order = [];
2666
+ for (const occ of keyed) {
2667
+ let anchor = -1;
2668
+ for (const { key: key2 } of occ) {
2669
+ const at = order.indexOf(key2);
2670
+ if (at >= 0) anchor = at;
2671
+ else order.splice(++anchor, 0, key2);
2672
+ }
2673
+ }
2674
+ for (const occ of keyed) {
2675
+ let last = -1;
2676
+ for (const { key: key2 } of occ) {
2677
+ const at = order.indexOf(key2);
2678
+ if (at < 0 || at <= last) return void 0;
2679
+ last = at;
2680
+ }
2681
+ }
2682
+ const children = [], used = /* @__PURE__ */ new Set();
2683
+ for (const key2 of order) {
2684
+ const present = keyed.map((occ) => occ.find((x) => x.key === key2)?.e);
2685
+ const first = present.find(Boolean);
2686
+ if (present.some((e) => e && !sameElement(first, e))) return void 0;
2687
+ const merged = cloneEl(first);
2688
+ used.add(first.id);
2689
+ if (present.some((e) => !e)) {
2690
+ const flags = present.map(Boolean);
2691
+ const via = binds(merged.props).find((path) => list2.items.every((r, k) => truthy(valueAt(r, path.slice(4))) === flags[k]));
2692
+ if (!via) return void 0;
2693
+ merged.when = { $bind: via };
2694
+ }
2695
+ children.push(merged);
2696
+ }
2697
+ if (children.length === 0 || n === 0) return void 0;
2698
+ return { children, sink: local.sink.filter((s) => used.has(s.elementId)), bound: local.bound.n };
2699
+ }
2700
+ function tryRepeat(groups, view, st) {
2701
+ const id = String(groups[0].meta.repeat), n = groups.length;
2702
+ const ok = view.arrays.filter((a) => a.items.length === n && a.items.every(isRec)).flatMap((a) => {
2703
+ const r = attempt(groups, a, view, st);
2704
+ return r ? [{ path: a.path, ...r }] : [];
2705
+ });
2706
+ if (ok.length === 1) {
2707
+ st.sink.push(...ok[0].sink);
2708
+ st.bound.n += ok[0].bound + 1;
2709
+ st.ctx.note("REPEAT_FORMED", `${n} repeated group${n === 1 ? "" : "s"} became one repeat over ${ok[0].path}.`, { elementId: id });
2710
+ return { id, type: "repeat", props: { rows: { $bind: ok[0].path }, children: ok[0].children } };
2711
+ }
2712
+ slotOf(st, groups[0], "props.rows", `${id}: ${n} rows`, ok.length ? "collision" : "no-match", ok.map((o) => o.path).slice(0, 6));
2713
+ return void 0;
2714
+ }
2715
+ function sequence(items, view, st) {
2716
+ const out = [];
2717
+ for (let i = 0; i < items.length; ) {
2718
+ const e = items[i], rid = e.meta?.repeat;
2719
+ if (rid !== void 0) {
2720
+ let j = i;
2721
+ while (j < items.length && items[j].meta?.repeat === rid && items[j].meta?.index === j - i) j++;
2722
+ const run = items.slice(i, j), merged = tryRepeat(run, view, st);
2723
+ if (merged) out.push(merged);
2724
+ else for (const g of run) {
2725
+ bindElement(g, view, st);
2726
+ out.push(g);
2727
+ }
2728
+ i = j;
2729
+ continue;
2730
+ }
2731
+ bindElement(e, view, st);
2732
+ out.push(e);
2733
+ i++;
2734
+ }
2735
+ return out;
2736
+ }
2737
+ function rebind(draft, sample, ctx, dataSet) {
2738
+ if (!isRec(sample)) {
2739
+ ctx.warn("SAMPLE_INVALID", "The sample must be one JSON object, so nothing was bound.");
2740
+ return;
2741
+ }
2742
+ if (!goodKey(dataSet) || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(dataSet)) {
2743
+ ctx.warn("SAMPLE_INVALID", `"${dataSet}" is not a usable dataset name, so nothing was bound.`);
2744
+ return;
2745
+ }
2746
+ const st = { ctx, ds: dataSet, locale: draft.locale, tz: draft.timezone ?? "UTC", sink: [], bound: { n: 0 } };
2747
+ const view = new View([new Layer(sample, `dataSets.${dataSet}`)]);
2748
+ const out = [];
2749
+ let run = [];
2750
+ const flush = () => {
2751
+ if (run.length) {
2752
+ for (const e of sequence(run, view, st)) out.push({ element: e });
2753
+ run = [];
2754
+ }
2755
+ };
2756
+ for (const b of draft.blocks) {
2757
+ if ("element" in b) run.push(b.element);
2758
+ else {
2759
+ flush();
2760
+ out.push(b);
2761
+ }
2762
+ }
2763
+ flush();
2764
+ draft.blocks = out;
2765
+ if (JSON.stringify(out).includes(`"dataSets.${dataSet}`)) draft.dataSets = [dataSet];
2766
+ const seen = /* @__PURE__ */ new Set();
2767
+ for (const s of st.sink) {
2768
+ const key2 = `${s.elementId}|${s.slot}`;
2769
+ if (!seen.has(key2) && ctx.unbound.length < 300) {
2770
+ seen.add(key2);
2771
+ ctx.unbound.push(s);
2772
+ }
2773
+ }
2774
+ ctx.note("REBOUND", `Bound ${st.bound.n} slot${st.bound.n === 1 ? "" : "s"} to the sample; ${ctx.unbound.length} left as written (see the unbound list).`);
2775
+ }
2776
+
2777
+ // packages/reportic-render-html/src/import/guide.ts
2778
+ var IMPORT_GUIDE = `Reportic reads two kinds of HTML.
2779
+
2780
+ - Reportic HTML is a report Reportic exported: it has the generator tag "Reportic 0.2", a main.reportic-report element, and sections marked with data-reportic-type and data-reportic-id. It is imported exactly: every section comes back as the element that made it, with the same ids, and the colors and fonts are matched to a preset theme.
2781
+ - Any other HTML is imported best effort. A real HTML parser reads it, scripts, forms, frames and event handlers are dropped, and only structure that is clear becomes an element. Everything else stays Markdown, and what was left out is listed in the notes.
2782
+
2783
+ What a best-effort import maps
2784
+ - Headings, paragraphs, lists, quotes and links stay Markdown.
2785
+ - A data table becomes a table (a grid of written-out cells). A table with three columns and a blank first header becomes a comparison.
2786
+ - A definition list becomes a two-column table with row headers.
2787
+ - A group of two or more short number-and-label blocks becomes metrics.
2788
+ - A titled aside, or a block with a callout, alert, note, or warning class, becomes a callout.
2789
+ - A progress or meter element (or role="progressbar") with a value from 0 to 1 becomes a progress list.
2790
+ - A list of checkbox items becomes a checklist.
2791
+ - Three or more headings that start with a date become a timeline.
2792
+ - pre and code become a code block. A mermaid block becomes a diagram. Labeled boxes joined by arrows become a flowchart.
2793
+ - An image with a caption becomes an image. Images must be embedded (data: URIs); linked files cannot be read.
2794
+ - A trailing ordered list of links becomes sources, and earlier paragraphs with [1] style markers become narratives that cite them.
2795
+ - Colors, fonts and sizes are reduced to the nearest preset plus token overrides. A block style that differs from the document becomes a theme rule. Plain element rules are kept as report css. @page size and orientation are kept as the page setup.
2796
+
2797
+ What has no element
2798
+ - Video, audio, frames, forms, scripts and canvases are dropped. A picture of a chart with no table of numbers stays an image.
2799
+
2800
+ To get an exact import
2801
+ - Re-export the report from Reportic as HTML and import that file, or
2802
+ - Mark each block with data-reportic-type and data-reportic-id, using the type names from the component library (metrics, table, chart, diagram, image, list, narrative, sources, group, repeat, reportic.callout.v1 as "callout", progress, timeline, comparison, checklist, code, masthead, footer, figure), put it in a main.reportic-report element, add <meta name="generator" content="Reportic 0.2">, and import again.
2803
+
2804
+ Data
2805
+ - The template written from HTML holds the text of that one report. Import with a JSON sample (one object, used as the dataset "report") and every slot that one field explains completely is bound to it. Slots that several fields could explain, and cells that could be split in more than one way, stay as written and are listed so you can bind them in the editor.`;
2806
+ var guideFor = (mode) => `${mode === "reportic" ? "This page is Reportic HTML, so it was imported exactly." : "This page is not Reportic HTML, so it was imported best effort."}
2807
+
2808
+ ${IMPORT_GUIDE}`;
2809
+
2810
+ // packages/reportic-render-html/src/import/index.ts
2811
+ var unsafeCss = /@import|url\s*\(|expression\s*\(|<\/?style|behavior\s*:/i;
2812
+ function importHtml(html, options = {}) {
2813
+ if (typeof html !== "string" || !html.trim()) fail3("INVALID_INPUT", "HTML to import must be a non-empty string.", { phase: "input" });
2814
+ if (Buffer.byteLength(html) > 25e6) fail3("LIMIT_EXCEEDED", "The page is larger than 25 MB.", { phase: "input" });
2815
+ const doc = parseHtml(html), ctx = new Importer();
2816
+ const css = findAll(doc, (e) => e.tagName === "style").map((s) => kids(s).map((k) => isText(k) ? k.value : "").join("")).join("\n");
2817
+ const reportic = isReporticHtml(doc);
2818
+ const draft = reportic ? importReportic(doc, ctx) : importBestEffort(doc, ctx);
2819
+ const style2 = (reportic ? readReporticStyle(css, ctx) : void 0) ?? readPageStyle(doc, css, ctx);
2820
+ if (unsafeCss.test(css)) ctx.warn("CSS_DROPPED", "Style rules that fetch or run something (@import, url(), expression(), behavior) were dropped.");
2821
+ if (unsafeCss.test(style2.css)) style2.css = style2.css.split("\n").filter((line) => !unsafeCss.test(line)).join("\n");
2822
+ const dataSet = options.dataSet ?? "report";
2823
+ if (options.sample !== void 0) rebind(draft, options.sample, ctx, dataSet);
2824
+ const template = writeTemplate(draft);
2825
+ const named = find(doc, (e) => e.tagName === "h1") ?? find(doc, (e) => e.tagName === "title");
2826
+ const result = { mode: reportic ? "reportic" : "best-effort", title: named ? textOf(named).slice(0, 120) : "", template, theme: style2.theme, css: style2.css, assets: draft.assets, notes: ctx.notes, unbound: ctx.unbound, guide: guideFor(reportic ? "reportic" : "best-effort") };
2827
+ if (style2.page) result.page = style2.page;
2828
+ return result;
2829
+ }
2830
+
176
2831
  // packages/reportic-render-html/src/index.ts
2832
+ var darken = (hex3, amount) => {
2833
+ const s = hex3.replace("#", "");
2834
+ const full = s.length <= 4 ? s.slice(0, 3).split("").map((c) => c + c).join("") : s.slice(0, 6);
2835
+ return "#" + [0, 2, 4].map((i) => Math.round(parseInt(full.slice(i, i + 2), 16) * (1 - amount)).toString(16).padStart(2, "0")).join("");
2836
+ };
2837
+ var cellsOf = (node) => (node.props.cells ?? []).flat();
2838
+ function featureCss(report, t, c) {
2839
+ const nodes = walkNodes2(report.nodes);
2840
+ const uses = (f) => nodes.some(f);
2841
+ const scope = ".reportic-report";
2842
+ let css = "";
2843
+ const tone2 = (k) => c[k];
2844
+ if (uses((n) => n.type === "table" && cellsOf(n).some((x) => x.kind === "rating" || x.runs || x.kind === "status" || x.kind === "date" || x.kind === "code")) || uses((n) => n.type === "masthead")) {
2845
+ css += `${scope} td code{white-space:nowrap;overflow-wrap:normal}${scope} td code.rpt-long{white-space:normal;overflow-wrap:break-word}${scope} .rpt-rating{font-weight:600;white-space:nowrap;overflow-wrap:normal}${scope} .rpt-rating.rpt-ok{color:${tone2("ok")}}${scope} .rpt-rating.rpt-warn{color:${tone2("warn")}}${scope} .rpt-rating.rpt-bad{color:${tone2("bad")}}${scope} .rpt-rating.rpt-na{color:${tone2("na")};font-weight:400}`;
2846
+ css += `${scope} .rpt-chip{display:inline-block;padding:0 7px;border-radius:5px;font-size:.92em;line-height:1.5;white-space:nowrap}${scope} .rpt-chip.rpt-date{background:${c.head};color:${c.ink};border:1px solid ${t.border}}${scope} .rpt-chip.rpt-person{background:${c.accentSoft};color:${t.accent}}`;
2847
+ css += `${scope} .rpt-chip.rpt-status{background:${c.warnSoft};color:${darken(c.warn, 0.45)};border:1px solid ${c.warn}55}${scope} .rpt-chip.rpt-status.rpt-done{background:${c.okSoft};color:${c.ok};border-color:${c.ok}55}${scope} .rpt-chip.rpt-status.rpt-late{background:${c.badSoft};color:${c.bad};border-color:${c.bad}55}${scope} .rpt-chip.rpt-status.rpt-progress{background:${c.accentSoft};color:${t.accent};border-color:${t.accent}44}`;
2848
+ }
2849
+ if (uses((n) => n.type === "table" && (cellsOf(n).some((x) => x.total) || n.props.rowHeader))) {
2850
+ css += `${scope} tr.rpt-total td{border-top:1px solid ${t.muted}66;font-weight:600;color:${c.ink}}${scope} th.rpt-rowheader{background:${c.zebra};color:${c.ink};font-weight:600;width:28%;padding:11px 12px;border-bottom:1px solid ${t.border}}${scope} tbody tr:last-child th.rpt-rowheader{border-bottom:0}`;
2851
+ }
2852
+ if (uses((n) => n.type === "metrics" && n.props.items.some((i) => i.tone))) {
2853
+ css += `${scope} .rpt-metric.rpt-ok .metric-value{color:${tone2("ok")}}${scope} .rpt-metric.rpt-warn .metric-value{color:${tone2("warn")}}${scope} .rpt-metric.rpt-bad .metric-value{color:${tone2("bad")}}${scope} .rpt-metric.rpt-na .metric-value{color:${tone2("na")}}`;
2854
+ }
2855
+ if (uses((n) => n.type === "metrics" && n.props.items.some((i) => i.intent || i.trend))) {
2856
+ css += `${scope} .metric-trend{font-size:11px;margin-top:4px}${scope} .rpt-intent-positive .metric-trend{color:${tone2("ok")}}${scope} .rpt-intent-negative .metric-trend{color:${tone2("bad")}}${scope} .rpt-intent-neutral .metric-trend{color:${t.muted}}`;
2857
+ }
2858
+ if (uses((n) => n.type === "list" && n.props.variant === "callout")) {
2859
+ css += `${scope} .callout.rpt-clauses strong{font-size:inherit;letter-spacing:inherit;text-transform:none}${scope} .callout.rpt-clauses p{margin:6px 0}${scope} .callout.rpt-clauses p:first-child{margin-top:0}${scope} .callout.rpt-clauses p:last-child{margin-bottom:0}`;
2860
+ }
2861
+ if (uses((n) => n.type === "masthead" || n.type === "cover")) {
2862
+ css += `${scope} .rpt-masthead{margin:0 0 8px}${scope} .rpt-marking{display:inline-block;border:1.5px solid ${tone2("bad")};color:${tone2("bad")};font-weight:600;padding:2px 8px;border-radius:5px;font-size:12.5px;line-height:1.6;margin:0 0 14px}${scope} .rpt-kicker{font-size:12px;letter-spacing:.1em;text-transform:uppercase;color:${t.accent};font-weight:600;margin:0 0 10px}${scope} .rpt-masthead h1{margin-top:0}${scope} .rpt-byline{font-size:.93em;color:${t.muted};margin:0 0 18px}${scope} .rpt-byline .rpt-chip{margin-right:2px}${scope} .rpt-lead{font-size:1.13em;line-height:1.55;color:${c.ink};margin:0 0 18px}`;
2863
+ }
2864
+ if (uses((n) => n.type === "footer")) {
2865
+ css += `${scope} .rpt-footer{margin:28px 0 0;padding:16px 0 0;font-size:12.5px;line-height:1.5;color:${t.muted};border-top:1px solid ${t.border};break-inside:avoid}${scope} .rpt-footer img{height:18px;width:auto;max-width:none;vertical-align:middle;margin-right:8px}`;
2866
+ }
2867
+ if (uses((n) => n.type === "figure" || n.type === "kit-chart")) {
2868
+ css += `${scope} .rpt-figure{margin:18px 0 22px;break-inside:avoid}${scope} .rpt-figure-box{border:1px solid ${t.border};border-radius:8px;background:${t.background};padding:10px 8px 4px}${scope} .rpt-figure img{display:block;width:100%;height:auto;max-height:none}${scope} .rpt-figure figcaption{font-size:12.5px;color:${t.muted};margin:6px 0 0;padding-left:2px}${scope} .rpt-figure figcaption:before{content:"Source: ";font-weight:600;color:${t.text}}${scope} .rpt-sr-only{position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}`;
2869
+ }
2870
+ if (uses((n) => n.type === "badge")) {
2871
+ css += `${scope} .rpt-badges{margin:8px 0 12px}${scope} .rpt-badge{display:inline-block;padding:0 7px;border-radius:5px;font-size:.92em;line-height:1.5;white-space:nowrap;margin:0 6px 6px 0}${scope} .rpt-badge.rpt-neutral{background:${c.head};color:${t.muted};border:1px solid ${t.border}}${scope} .rpt-badge.rpt-accent,${scope} .rpt-badge.rpt-info{background:${c.accentSoft};color:${t.accent};border:1px solid ${t.accent}44}${scope} .rpt-badge.rpt-success{background:${c.okSoft};color:${c.ok};border:1px solid ${c.ok}55}${scope} .rpt-badge.rpt-warning{background:${c.warnSoft};color:${darken(c.warn, 0.45)};border:1px solid ${c.warn}55}${scope} .rpt-badge.rpt-danger{background:${c.badSoft};color:${c.bad};border:1px solid ${c.bad}55}`;
2872
+ }
2873
+ if (uses((n) => n.type === "columns")) css += `${scope} .rpt-columns{display:grid;grid-template-columns:repeat(var(--cols,2),minmax(0,1fr));gap:22px;margin:12px 0;align-items:start}${scope} .rpt-columns>div>:first-child{margin-top:0}`;
2874
+ if (uses((n) => n.type === "footnote")) css += `${scope} .rpt-footnote{margin:8px 0 16px;font-size:12.5px;line-height:1.45;color:${t.muted}}${scope} .rpt-footnote p{margin:0}`;
2875
+ if (uses((n) => n.type === "toc")) css += `${scope} .rpt-toc ol{list-style:none;padding:0;margin:8px 0 0}${scope} .rpt-toc li{margin:4px 0}${scope} .rpt-toc-l2{padding-left:16px}${scope} .rpt-toc-l3{padding-left:32px}${scope} .rpt-toc-l4,${scope} .rpt-toc-l5,${scope} .rpt-toc-l6{padding-left:48px}`;
2876
+ if (uses((n) => n.type === "page-break")) css += `${scope} [data-reportic-type=page-break]{margin:0}${scope} .rpt-break{break-before:page;page-break-before:always;height:0}`;
2877
+ if (uses((n) => n.type === "cover")) css += `${scope} [data-reportic-type=cover]{break-after:page;page-break-after:always}${scope} .rpt-subtitle{font-size:1.15em;color:${t.muted}}`;
2878
+ if (uses((n) => n.type === "callout" && n.props.tone === "neutral")) css += `${scope} .callout.tone-neutral{border-left-color:${t.border};background:${t.background}}`;
2879
+ if (t.layout === "card") css += cardCss(t, c);
2880
+ return css;
2881
+ }
2882
+ function tokenProperties(tokens = {}) {
2883
+ const props = [...tokens.layout ? [`--reportic-layout:${tokens.layout}`] : [], ...tokens.chartPalette ? [`--reportic-palette:${tokens.chartPalette.join(" ")}`] : [], ...Object.entries(tokens.semantic ?? {}).filter(([k]) => /^[a-zA-Z]\w*$/.test(k)).map(([k, v]) => `--reportic-semantic-${k}:${v}`)];
2884
+ return props.length ? `.reportic-report{${props.join(";")}}` : "";
2885
+ }
2886
+ function cardCss(t, c) {
2887
+ const s = ".reportic-report", rule = t.border, strong = `${t.muted}55`;
2888
+ return `@media screen{body{background:${c.page}}}${s}{background:${t.background};border:1px solid ${rule};border-top:5px solid ${t.accent};border-radius:12px;padding:36px 36px 28px;margin:32px auto 48px;line-height:1.6}${s} h1,${s} h2,${s} h3{color:${c.ink};font-weight:600;letter-spacing:0}${s} h1{line-height:1.15;margin:0 0 10px}${s} h2{font-size:22px;line-height:1.3;margin:34px 0 10px;padding-top:14px;border-top:1px solid ${rule}}${s} h3{font-family:${t.fontFamily};font-size:16.5px;margin:24px 0 8px}${s} h2:first-child{border-top:0;padding-top:0;margin-top:0}${s} p{margin:0 0 12px}${s} strong{color:${c.ink};font-weight:600}${s} code{background:${c.head};color:${c.ink};padding:1px 5px;border-radius:4px}${s} pre{background:${c.head};border-radius:8px;padding:12px 14px;font-size:13px}${s} li::marker{color:${t.muted}}${s} ul,${s} ol{margin:0 0 14px;padding-left:22px}${s} li{margin:4px 0}${s},${s} td,${s} th{overflow-wrap:break-word}${s} th{vertical-align:top}${s} th.rpt-rowheader{padding:8px 11px}${s} table{border-collapse:separate;border-spacing:0;border:1px solid ${rule};border-radius:8px;overflow:hidden;font-size:13.5px;line-height:1.45;font-variant-numeric:tabular-nums;margin:14px 0 20px}${s} th{background:${c.head};color:${c.ink};padding:8px 11px;border-bottom:1px solid ${strong}}${s} td{padding:8px 11px;border-bottom:1px solid ${rule}}${s} tbody tr:last-child td{border-bottom:0}${s} tr:nth-child(even) td{background:${c.zebra}}${s} blockquote{background:${c.accentSoft}}${s} .callout{margin:16px 0 18px;padding:14px 18px;background:${t.accent}0d;border:0;border-left:4px solid ${t.accent};border-radius:0 8px 8px 0}${s} .callout.tone-warning{background:${c.warnSoft};border-left-color:${c.warn}}${s} .callout.tone-danger{background:${c.badSoft};border-left-color:${c.bad}}${s} .callout.tone-success{background:${c.okSoft};border-left-color:${c.ok}}${s} .callout p{margin:0 0 8px}${s} .callout p:last-child{margin-bottom:0}${s} .metrics{border:0;padding:0;margin:14px 0 18px;gap:12px;grid-template-columns:repeat(auto-fit,minmax(150px,1fr))}${s} .metrics>div{display:flex;flex-direction:column;border:1px solid ${rule};border-radius:8px;padding:12px 14px;background:${c.zebra}}${s} .metric-value{order:1;font-family:${t.headingFont};font-size:var(--metric-size,28px);line-height:1.1;color:${c.ink};letter-spacing:0}${s} .metric-label{order:2;font-size:12.5px;letter-spacing:0;text-transform:none;color:${t.muted};margin:4px 0 0;line-height:1.35}${s} .metric-comparison{order:3;font-size:12.5px;color:${t.text};margin-top:4px}${s} .rpt-lead{font-size:17px}${s} .rpt-byline{font-size:14px}${s} [data-reportic-type=logo]{margin:0 0 16px}${s} [data-reportic-type=logo] figure{margin:0}${s} [data-reportic-type=logo] img{display:block;height:44px;width:auto;max-width:none;max-height:none}@media(max-width:600px){${s}{padding:22px 18px 18px;border-radius:10px;margin:14px auto 32px}${s} h1{font-size:26px}${s} h2{font-size:19.5px}${s} table{font-size:13px}${s} th,${s} td{padding:7px 9px}}@media print{body{background:#fff}${s}{border:0;border-top:4px solid ${t.accent};border-radius:0;padding:12px 0 0;margin:0;max-width:none;font-size:10.5pt}${s} table{font-size:9pt}${s} tr,${s} .callout{break-inside:avoid}${s} [data-reportic-type=logo] img{height:12mm}${s} .rpt-footer img{height:4mm}}`;
2889
+ }
177
2890
  function reportCss(report, options = {}) {
178
- const t = themeTokens2(options.theme ?? report.theme);
179
- const rules = Object.entries((options.theme ?? report.theme).rules ?? {}).sort(([a], [b]) => Number(!["document", "heading", "paragraph", "table", "metric", "chart", "diagram", "image", "logo"].includes(a)) - Number(!["document", "heading", "paragraph", "table", "metric", "chart", "diagram", "image", "logo"].includes(b))).map(([key, value]) => {
180
- const selector = key === "document" ? ".reportic-report" : key === "heading" ? ".reportic-report :is(h1,h2,h3,h4)" : key === "paragraph" ? ".reportic-report p" : ["table", "metric", "chart", "diagram", "image", "logo"].includes(key) ? `.reportic-report [data-reportic-type="${key === "metric" ? "metrics" : key}"]` : `.reportic-report [data-reportic-id="${key}"]`;
2891
+ const t = themeTokens5(options.theme ?? report.theme);
2892
+ const feature = tokenProperties((options.theme ?? report.theme).tokens) + featureCss(report, t, semanticColors3(t));
2893
+ const rules = Object.entries((options.theme ?? report.theme).rules ?? {}).sort(([a], [b]) => Number(!["document", "heading", "paragraph", "table", "metric", "chart", "diagram", "image", "logo"].includes(a)) - Number(!["document", "heading", "paragraph", "table", "metric", "chart", "diagram", "image", "logo"].includes(b))).map(([key2, value]) => {
2894
+ const selector = key2 === "document" ? ".reportic-report" : key2 === "heading" ? ".reportic-report :is(h1,h2,h3,h4)" : key2 === "paragraph" ? ".reportic-report p" : ["table", "metric", "chart", "diagram", "image", "logo"].includes(key2) ? `.reportic-report [data-reportic-type="${key2 === "metric" ? "metrics" : key2}"]` : `.reportic-report [data-reportic-id="${key2}"]`;
181
2895
  return `${selector}{${Object.entries(value).map(([k, v]) => `${k.replace(/[A-Z]/g, (m) => "-" + m.toLowerCase())}:${typeof v === "number" && !["fontWeight", "lineHeight"].includes(k) ? v + "px" : v}`).join(";")}}`;
182
2896
  }).join("\n");
183
- return `:root{color-scheme:light}*{box-sizing:border-box}body{margin:0;background:${t.background};color:${t.text}}.reportic-report{--reportic-accent:${t.accent};font:${t.bodySize}px/1.75 ${t.fontFamily};max-width:${t.contentWidth}px;margin:0 auto;padding:60px 58px;overflow-wrap:anywhere}.reportic-report h1,.reportic-report h2,.reportic-report h3{line-height:1.2;font-family:${t.headingFont};font-weight:500;letter-spacing:-.035em;color:${t.text};break-after:avoid}.reportic-report h1{font-size:${t.headingSize}px;margin:20px 0 24px}.reportic-report h2{font-size:27px;margin:44px 0 19px}.reportic-report h3{font-size:21px;margin:28px 0 14px}.reportic-report p{margin:12px 0}.reportic-report a{color:${t.accent};text-underline-offset:3px}.reportic-report blockquote{border-left:3px solid ${t.accent};padding:8px 20px;margin:24px 0;color:${t.muted};background:${t.accent}08}.reportic-report hr{border:0;border-top:1px solid ${t.border};margin:30px 0}.reportic-report code{font-family:Consolas,monospace;font-size:.87em;background:${t.accent}0b;padding:2px 5px;border-radius:4px}.reportic-report pre{white-space:pre-wrap;overflow-wrap:anywhere;padding:20px;background:${t.accent}08;border:1px solid ${t.border};border-radius:8px;break-inside:avoid}.reportic-report pre code{padding:0;background:none}.reportic-report table{width:100%;border-collapse:collapse;margin:16px 0 24px;font-size:.9em;table-layout:auto}.reportic-report thead{display:table-header-group}.reportic-report th{text-align:left;background:${t.accent}0d;font-weight:600;border-bottom:1px solid ${t.border};color:${t.accent};padding:12px}.reportic-report td{border-bottom:1px solid ${t.border};padding:11px 12px;vertical-align:top;overflow-wrap:anywhere}.reportic-report tr{break-inside:avoid}.reportic-report tr:nth-child(even) td{background:${t.accent}03}.reportic-report section{margin:20px 0}.reportic-report figure{margin:20px 0;break-inside:avoid}.reportic-report img{max-width:100%;height:auto}.reportic-report figcaption{font-size:12px;color:${t.muted};margin:10px 0}.reportic-report [data-reportic-type=logo]{margin:0 0 26px}.reportic-report [data-reportic-type=logo] img{max-width:${t.logoWidth}px;max-height:70px;object-fit:contain}.reportic-report .metrics{display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));border-top:1px solid ${t.border};border-bottom:1px solid ${t.border};padding:22px 0;gap:24px;margin:24px 0;break-inside:avoid}.reportic-report .metric-label{font-size:10px;letter-spacing:.09em;text-transform:uppercase;color:${t.muted};margin:0 0 8px}.reportic-report .metric-value{font-size:var(--metric-size,28px);white-space:nowrap;line-height:1.3;letter-spacing:-.04em;font-weight:600}.reportic-report .metric-comparison{font-size:11px;color:${t.accent};margin-top:7px}.reportic-report .callout{border:1px solid ${t.accent}25;border-left:3px solid ${t.accent};padding:16px 20px;border-radius:0 7px 7px 0;background:${t.accent}07;break-inside:avoid}.reportic-report .callout strong{font-size:14px}.reportic-report .callout p{margin:5px 0}.reportic-report .tone-warning{border-left-color:#bf8c3c;background:#c78a190a}.reportic-report .tone-danger{border-left-color:#bb5c53}.reportic-report .progress-item{margin:18px 0;break-inside:avoid}.reportic-report .progress-label{display:flex;justify-content:space-between;font-size:12px}.reportic-report .progress-track{height:7px;border-radius:5px;background:${t.border};margin:8px 0}.reportic-report .progress-track span{display:block;height:100%;background:${t.accent};border-radius:5px}.reportic-report .timeline-item{border-left:1px solid ${t.border};padding:0 0 22px 24px;position:relative;break-inside:avoid}.reportic-report .timeline-item:before{content:'';position:absolute;left:-5px;top:8px;width:9px;height:9px;border-radius:100%;background:${t.accent}}.reportic-report .timeline-date{font-size:11px;color:${t.muted}}.reportic-report .timeline-item p{margin:4px 0}.reportic-report .checklist{list-style:none;padding-left:0}.reportic-report .checklist li{margin:10px 0}.reportic-report .checkmark{color:${t.accent};margin-right:10px}.reportic-report .source-list{font-size:12px;color:${t.muted}}.reportic-report .diagram img{width:100%;max-height:400px;object-fit:contain}.reportic-report .chart img{width:100%}.reportic-report .chart-data{font-size:10px}.reportic-report .empty{color:${t.muted};font-style:italic}.reportic-report .evidence{font-size:10px;vertical-align:super;margin-left:4px}@media(max-width:600px){.reportic-report{padding:30px 22px}.reportic-report h1{font-size:34px}.reportic-report th,.reportic-report td{padding:7px;font-size:11px}}@page{size:A4;margin:17mm 15mm}@media print{.reportic-report{padding:0;max-width:none;font-size:10.5pt}.reportic-report h1{font-size:32pt}.reportic-report h2{font-size:20pt}.reportic-report .metrics{grid-template-columns:repeat(var(--metric-count,4),1fr)}a{text-decoration:none}.reportic-report figure img{max-height:90mm}.reportic-report .chart-data{font-size:8pt}}${rules}
2897
+ return `:root{color-scheme:light}*{box-sizing:border-box}body{margin:0;background:${t.background};color:${t.text}}.reportic-report{--reportic-accent:${t.accent};font:${t.bodySize}px/1.75 ${t.fontFamily};max-width:${t.contentWidth}px;margin:0 auto;padding:60px 58px;overflow-wrap:anywhere}.reportic-report h1,.reportic-report h2,.reportic-report h3{line-height:1.2;font-family:${t.headingFont};font-weight:500;letter-spacing:-.035em;color:${t.text};break-after:avoid}.reportic-report h1{font-size:${t.headingSize}px;margin:20px 0 24px}.reportic-report h2{font-size:27px;margin:44px 0 19px}.reportic-report h3{font-size:21px;margin:28px 0 14px}.reportic-report p{margin:12px 0}.reportic-report a{color:${t.accent};text-underline-offset:3px}.reportic-report blockquote{border-left:3px solid ${t.accent};padding:8px 20px;margin:24px 0;color:${t.muted};background:${t.accent}08}.reportic-report hr{border:0;border-top:1px solid ${t.border};margin:30px 0}.reportic-report code{font-family:Consolas,monospace;font-size:.87em;background:${t.accent}0b;padding:2px 5px;border-radius:4px}.reportic-report pre{white-space:pre-wrap;overflow-wrap:anywhere;padding:20px;background:${t.accent}08;border:1px solid ${t.border};border-radius:8px;break-inside:avoid}.reportic-report pre code{padding:0;background:none}.reportic-report table{width:100%;border-collapse:collapse;margin:16px 0 24px;font-size:.9em;table-layout:auto}.reportic-report thead{display:table-header-group}.reportic-report th{text-align:left;background:${t.accent}0d;font-weight:600;border-bottom:1px solid ${t.border};color:${t.accent};padding:12px}.reportic-report td{border-bottom:1px solid ${t.border};padding:11px 12px;vertical-align:top;overflow-wrap:anywhere}.reportic-report tr{break-inside:avoid}.reportic-report tr:nth-child(even) td{background:${t.accent}03}.reportic-report section{margin:20px 0}.reportic-report figure{margin:20px 0;break-inside:avoid}.reportic-report img{max-width:100%;height:auto}.reportic-report figcaption{font-size:12px;color:${t.muted};margin:10px 0}.reportic-report [data-reportic-type=logo]{margin:0 0 26px}.reportic-report [data-reportic-type=logo] img{max-width:${t.logoWidth}px;max-height:70px;object-fit:contain}.reportic-report .metrics{display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));border-top:1px solid ${t.border};border-bottom:1px solid ${t.border};padding:22px 0;gap:24px;margin:24px 0;break-inside:avoid}.reportic-report .metric-label{font-size:10px;letter-spacing:.09em;text-transform:uppercase;color:${t.muted};margin:0 0 8px}.reportic-report .metric-value{font-size:var(--metric-size,28px);white-space:nowrap;line-height:1.3;letter-spacing:-.04em;font-weight:600}.reportic-report .metric-comparison{font-size:11px;color:${t.accent};margin-top:7px}.reportic-report .callout{border:1px solid ${t.accent}25;border-left:3px solid ${t.accent};padding:16px 20px;border-radius:0 7px 7px 0;background:${t.accent}07;break-inside:avoid}.reportic-report .callout strong{font-size:14px}.reportic-report .callout p{margin:5px 0}.reportic-report .tone-warning{border-left-color:#bf8c3c;background:#c78a190a}.reportic-report .tone-danger{border-left-color:#bb5c53}.reportic-report .progress-item{margin:18px 0;break-inside:avoid}.reportic-report .progress-label{display:flex;justify-content:space-between;font-size:12px}.reportic-report .progress-track{height:7px;border-radius:5px;background:${t.border};margin:8px 0}.reportic-report .progress-track span{display:block;height:100%;background:${t.accent};border-radius:5px}.reportic-report .timeline-item{border-left:1px solid ${t.border};padding:0 0 22px 24px;position:relative;break-inside:avoid}.reportic-report .timeline-item:before{content:'';position:absolute;left:-5px;top:8px;width:9px;height:9px;border-radius:100%;background:${t.accent}}.reportic-report .timeline-date{font-size:11px;color:${t.muted}}.reportic-report .timeline-item p{margin:4px 0}.reportic-report .checklist{list-style:none;padding-left:0}.reportic-report .checklist li{margin:10px 0}.reportic-report .checkmark{color:${t.accent};margin-right:10px}.reportic-report .source-list{font-size:12px;color:${t.muted}}.reportic-report .diagram img{width:100%;max-height:400px;object-fit:contain}.reportic-report .chart img{width:100%}.reportic-report .chart-data{font-size:10px}.reportic-report .empty{color:${t.muted};font-style:italic}.reportic-report .evidence{font-size:10px;vertical-align:super;margin-left:4px}@media(max-width:600px){.reportic-report{padding:30px 22px}.reportic-report h1{font-size:34px}.reportic-report th,.reportic-report td{padding:7px;font-size:11px}}@page{size:A4;margin:17mm 15mm}@media print{.reportic-report{padding:0;max-width:none;font-size:10.5pt}.reportic-report h1{font-size:32pt}.reportic-report h2{font-size:20pt}.reportic-report .metrics{grid-template-columns:repeat(var(--metric-count,4),1fr)}a{text-decoration:none}.reportic-report figure img{max-height:90mm}.reportic-report .chart-data{font-size:8pt}}${feature}${rules}
184
2898
  ${options.css ?? report.css ?? ""}`;
185
2899
  }
186
2900
  function assetData(asset) {
@@ -188,26 +2902,45 @@ function assetData(asset) {
188
2902
  }
189
2903
  function cleanMarkdownHtml(markdown, report, options = {}) {
190
2904
  const renderer = new marked.Renderer();
191
- renderer.html = ({ text }) => h2(text);
192
- renderer.image = ({ href, text }) => {
2905
+ renderer.html = ({ text: text2 }) => h4(text2);
2906
+ renderer.image = ({ href, text: text2 }) => {
193
2907
  let src = href;
194
2908
  if (/^https:\/\//.test(src)) {
195
2909
  safeUrl(src, true);
196
- if (!options.allowRemoteImages) fail3("REMOTE_ASSET_DENIED", "Remote Markdown images require an explicit image policy.");
2910
+ if (!options.allowRemoteImages) fail4("REMOTE_ASSET_DENIED", "Remote Markdown images require an explicit image policy.");
197
2911
  } else {
198
2912
  safeRelative(src);
199
2913
  const asset = report.assets.find((a) => a.path === src);
200
2914
  if (asset) src = options.html?.assetMode === "bundled" ? asset.path : assetData(asset);
201
- else fail3("ASSET_MISSING", `Markdown image "${src}" needs a registered asset for portable export.`);
2915
+ else fail4("ASSET_MISSING", `Markdown image "${src}" needs a registered asset for portable export.`);
202
2916
  }
203
- return `<img src="${h2(src)}" alt="${h2(text)}">`;
2917
+ return `<img src="${h4(src)}" alt="${h4(text2)}">`;
204
2918
  };
205
2919
  return sanitizeHtml(marked.parse(markdown, { async: false, gfm: true, renderer }), { allowedTags: [...sanitizeHtml.defaults.allowedTags, "img", "del", "input"], allowedAttributes: { a: ["href", "title"], img: ["src", "alt"], th: ["align", "style"], td: ["align", "style"], input: ["type", "checked", "disabled"] }, allowedStyles: { "*": { "text-align": [/^left$/, /^right$/, /^center$/] } }, allowedSchemes: ["https", "http", "mailto"], allowedSchemesByTag: { img: ["data", "https"] }, allowProtocolRelative: false });
206
2920
  }
207
- var tableHtml = (columns, cells, className = "") => `<table class="${className}"><thead><tr>${columns.map((c) => `<th scope="col" style="text-align:${c.align ?? "left"}">${h2(c.label)}</th>`).join("")}</tr></thead><tbody>${cells.map((row) => `<tr>${row.map((cell, i) => `<td style="text-align:${columns[i].align ?? "left"}">${h2(cell.text ?? cell)}</td>`).join("")}</tr>`).join("")}</tbody></table>`;
2921
+ var codeHtml = (raw) => raw.length > 16 ? `<code class="rpt-long">${h4(raw).replace(/([_\-/.,])(?=\S)/g, "$1<wbr>")}</code>` : `<code>${h4(raw)}</code>`;
2922
+ var runHtml = (run) => {
2923
+ const text2 = h4(run.text).replace(/\n/g, "<br>");
2924
+ return run.tone ? `<span class="rpt-rating rpt-${h4(run.tone)}">${text2}</span>` : run.code ? codeHtml(String(run.text)) : run.strong ? `<strong>${text2}</strong>` : text2;
2925
+ };
2926
+ var cellInner = (cell) => {
2927
+ if (cell && typeof cell === "object") {
2928
+ if (cell.runs) return cell.runs.map(runHtml).join("");
2929
+ if (cell.kind === "rating" && cell.tone) return `<span class="rpt-rating rpt-${h4(cell.tone)}">${h4(cell.text)}</span>`;
2930
+ if (cell.kind === "status" && cell.text) return `<span class="rpt-chip rpt-status${cell.status ? ` rpt-${h4(cell.status)}` : ""}">${h4(cell.text)}</span>`;
2931
+ if (cell.kind === "date" && cell.text) return `<span class="rpt-chip rpt-date">${h4(cell.text)}</span>`;
2932
+ if (cell.kind === "code" && cell.text) return codeHtml(String(cell.text));
2933
+ }
2934
+ return h4(cell.text ?? cell);
2935
+ };
2936
+ var rawAttr = (cell) => cell && typeof cell === "object" && cell.text ? cell.kind === "date" && typeof cell.raw === "string" ? ` data-reportic-raw="${h4(cell.raw)}"` : cell.kind === "list" && Array.isArray(cell.raw) && cell.raw.length ? ` data-reportic-raw="${h4(JSON.stringify(cell.raw))}"` : "" : "";
2937
+ var kindAttr = (c) => `${c.kind ? ` data-reportic-kind="${h4(c.kind)}"` : ""}${c.format ? ` data-reportic-format="${h4(c.format)}"` : ""}`;
2938
+ var tableHtml = (columns, cells, className = "", options = {}) => `<table class="${className}">${options.headers === false ? "" : `<thead><tr>${columns.map((c) => `<th scope="col" style="text-align:${c.align ?? "left"}"${kindAttr(c)}>${h4(c.label)}</th>`).join("")}</tr></thead>`}<tbody>${cells.map((row) => `<tr${row[0]?.total ? ' class="rpt-total"' : ""}>${row.map((cell, i) => options.rowHeader && i === 0 ? `<th scope="row" class="rpt-rowheader" style="text-align:${columns[i].align ?? "left"}"${rawAttr(cell)}>${cellInner(cell)}</th>` : `<td style="text-align:${columns[i].align ?? "left"}${columns[i].nowrap ? ";white-space:nowrap" : ""}"${rawAttr(cell)}>${cellInner(cell)}</td>`).join("")}</tr>`).join("")}</tbody></table>`;
2939
+ var stamp = (name, value) => ` data-reportic-${name}="${h4(typeof value === "string" ? value : JSON.stringify(value))}"`;
2940
+ var trendWord = (trend) => trend === "up" ? "Up" : trend === "down" ? "Down" : trend === "flat" ? "Flat" : "";
208
2941
  function chartTable(node, report) {
209
2942
  const p = node.props;
210
- return { columns: [{ label: p.x.label }, ...p.series.map((s) => ({ label: s.label, align: "right" }))], cells: p.categories.map((c, i) => [c, ...p.series.map((s) => formatValue2(s.values[i], s.format, report.locale, report.timezone))]) };
2943
+ return { columns: [{ label: p.x.label }, ...p.series.map((s) => ({ label: s.label, align: "right" }))], cells: p.categories.map((c, i) => [c, ...p.series.map((s) => formatValue3(s.values[i], s.format, report.locale, report.timezone))]) };
211
2944
  }
212
2945
  async function renderHtml(report, options = {}) {
213
2946
  const diagrams = await diagramVisuals(report, options);
@@ -224,71 +2957,144 @@ async function renderHtml(report, options = {}) {
224
2957
  };
225
2958
  const render = (node) => {
226
2959
  const p = node.props;
227
- let content = "";
2960
+ let content = "", marks2 = "";
228
2961
  switch (node.type) {
229
- case "markdown":
230
- return cleanMarkdownHtml(p.markdown, report, options);
231
- case "metrics":
232
- content = `<div class="metrics" style="--metric-count:${Math.min(p.items.length, 4)}">${p.items.map((i) => `<div><p class="metric-label">${h2(i.label)}</p><div class="metric-value" style="--metric-size:${Math.min(28, Math.max(12, Math.floor(222 / Math.max(1, i.display.length))))}px">${h2(i.display)}</div>${i.comparison ? `<div class="metric-comparison">${h2(i.comparison)}</div>` : ""}</div>`).join("")}</div>`;
2962
+ case "markdown": {
2963
+ const html2 = cleanMarkdownHtml(p.markdown, report, options);
2964
+ return p.token?.type === "heading" ? html2.replace(/<h([1-6])(?![^>]*\sid=)/, `<h$1 id="${h4(node.occurrenceId)}"`) : html2;
2965
+ }
2966
+ case "metrics": {
2967
+ const extra = p.items.some((i) => i.trend || i.intent);
2968
+ if (extra) marks2 = stamp("model", { items: p.items.map((i) => ({ ...i.trend ? { trend: i.trend } : {}, ...i.intent ? { intent: i.intent } : {} })) });
2969
+ content = `<div class="metrics" style="--metric-count:${Math.min(p.items.length, 4)}">${p.items.map((i) => {
2970
+ const cls = [i.tone ? `rpt-metric rpt-${h4(i.tone)}` : "", i.intent ? `rpt-intent-${h4(i.intent)}` : ""].filter(Boolean).join(" ");
2971
+ return `<div${cls ? ` class="${cls}"` : ""}><p class="metric-label">${h4(i.label)}</p><div class="metric-value" style="--metric-size:${Math.min(28, Math.max(12, Math.floor(222 / Math.max(1, i.display.length))))}px">${h4(i.display)}</div>${i.comparison ? `<div class="metric-comparison">${h4(i.comparison)}</div>` : ""}${i.trend ? `<div class="metric-trend">${h4(trendWord(i.trend))}</div>` : ""}</div>`;
2972
+ }).join("")}</div>`;
233
2973
  break;
2974
+ }
234
2975
  case "table":
235
- content = p.rows.length ? tableHtml(p.columns, p.cells) : `<p class="empty">${h2(p.empty ?? "No rows to display.")}</p>`;
2976
+ content = p.rows.length ? tableHtml(p.columns, p.cells, "", { headers: p.headers, rowHeader: p.rowHeader }) : `<p class="empty">${h4(p.empty ?? "No rows to display.")}</p>`;
236
2977
  break;
237
2978
  case "chart": {
238
2979
  if (!p.categories.length) {
239
- content = `<p class="empty">${h2(p.empty ?? "No data to display.")}</p>`;
2980
+ content = `<p class="empty">${h4(p.empty ?? "No data to display.")}</p>`;
240
2981
  break;
241
2982
  }
242
2983
  const data = chartTable(node, report);
243
- content = `<figure class="chart"><h3>${h2(p.title)}</h3><img src="${image(node, chartSvg(node, report, options))}" alt="${h2(p.alt)}"/></figure>${tableHtml(data.columns, data.cells, "chart-data")}`;
2984
+ marks2 = stamp("kind", p.kind) + stamp("model", { title: p.title, alt: p.alt, x: { label: p.x.label }, categories: p.categories, series: p.series.map((s) => ({ label: s.label, ...s.format ? { format: s.format } : {}, values: s.values })) });
2985
+ content = `<figure class="chart"><h3>${h4(p.title)}</h3><img src="${image(node, chartSvg(node, report, options))}" alt="${h4(p.alt)}"/></figure>${tableHtml(data.columns, data.cells, "chart-data")}`;
244
2986
  break;
245
2987
  }
246
2988
  case "diagram":
247
- content = `<figure class="diagram"><img src="${image(node, diagrams.get(node.occurrenceId))}" alt="${h2(p.alt)}"/><figcaption>${h2(p.caption ?? p.alt)}</figcaption></figure>`;
2989
+ marks2 = stamp("model", { ...p.adapter ? { adapter: p.adapter, model: p.model } : { source: p.source }, alt: p.alt, ...p.caption ? { caption: p.caption } : {} });
2990
+ content = `<figure class="diagram"><img src="${image(node, diagrams.get(node.occurrenceId))}" alt="${h4(p.alt)}"/><figcaption>${h4(p.caption ?? p.alt)}</figcaption></figure>`;
248
2991
  break;
249
2992
  case "logo":
250
2993
  case "image":
251
- content = `<figure><img src="${h2(image(node))}" alt="${h2(p.alt)}"/>${p.caption ? `<figcaption>${h2(p.caption)}</figcaption>` : ""}</figure>`;
2994
+ content = `<figure><img src="${h4(image(node))}" alt="${h4(p.alt)}"/>${p.caption ? `<figcaption>${h4(p.caption)}</figcaption>` : ""}</figure>`;
252
2995
  break;
253
2996
  case "narrative":
254
- content = `${p.heading ? `<h3>${h2(p.heading)}</h3>` : ""}<p>${h2(p.text).replace(/\n/g, "<br>")}${(p.citations ?? []).map((n) => `<a class="evidence" href="#source-${n}">[${n}]</a>`).join("")}</p>`;
2997
+ content = `${p.heading ? `<h3>${h4(p.heading)}</h3>` : ""}<p>${h4(p.text).replace(/\n/g, "<br>")}${(p.citations ?? []).map((n) => `<a class="evidence" href="#source-${n}">[${n}]</a>`).join("")}</p>`;
255
2998
  break;
256
- case "list":
257
- content = p.items.length ? `<${p.ordered ? "ol" : "ul"}>${p.items.map((s) => `<li>${h2(s)}</li>`).join("")}</${p.ordered ? "ol" : "ul"}>` : `<p class="empty">${h2(p.empty ?? "No items to display.")}</p>`;
2999
+ case "list": {
3000
+ const lead = (i) => p.leads?.[i] ? `<strong>${h4(p.leads[i])}</strong> ` : "";
3001
+ content = !p.items.length ? `<p class="empty">${h4(p.empty ?? "No items to display.")}</p>` : p.variant === "callout" ? `<aside class="callout rpt-clauses">${p.items.map((s, i) => `<p>${lead(i)}${h4(s)}</p>`).join("")}</aside>` : p.variant === "paragraphs" ? p.items.map((s, i) => `<p>${lead(i)}${h4(s)}</p>`).join("") : `<${p.ordered ? "ol" : "ul"}>${p.items.map((s, i) => `<li>${lead(i)}${h4(s)}</li>`).join("")}</${p.ordered ? "ol" : "ul"}>`;
258
3002
  break;
3003
+ }
259
3004
  case "sources":
260
- content = `<ol class="source-list">${p.citations.map((s) => `<li id="source-${s.number}" value="${s.number}">${s.url ? `<a href="${h2(s.url)}">${h2(s.label)}</a>` : h2(s.label)}</li>`).join("")}</ol>`;
3005
+ content = `<ol class="source-list">${p.citations.map((s) => `<li id="source-${s.number}" value="${s.number}">${s.url ? `<a href="${h4(s.url)}">${h4(s.label)}</a>` : h4(s.label)}</li>`).join("")}</ol>`;
261
3006
  break;
262
3007
  case "group":
263
- content = `${p.heading ? `<h2>${h2(p.heading)}</h2>` : ""}${(node.children ?? []).map(render).join("")}`;
3008
+ content = `${p.heading ? `<h2>${h4(p.heading)}</h2>` : ""}${(node.children ?? []).map(render).join("")}`;
264
3009
  break;
265
3010
  case "repeat":
266
- content = node.children?.length ? node.children.map(render).join("") : `<p class="empty">${h2(p.empty ?? "No items to display.")}</p>`;
3011
+ content = node.children?.length ? node.children.map(render).join("") : `<p class="empty">${h4(p.empty ?? "No items to display.")}</p>`;
267
3012
  break;
268
- case "callout":
269
- content = `<aside class="callout tone-${h2(p.tone ?? "info")}"><strong>${h2(p.title)}</strong><p>${h2(p.text)}</p></aside>`;
3013
+ case "callout": {
3014
+ const items = Array.isArray(p.items) ? p.items : [];
3015
+ if (items.length) marks2 = stamp("model", { items, ...p.tone ? { tone: p.tone } : {} });
3016
+ content = `<aside class="callout tone-${h4(p.tone ?? "info")}">${p.title === "" ? "" : `<strong>${h4(p.title)}</strong>`}<p>${h4(p.text)}</p>${items.map((item) => `<p>${item.label ? `<strong>${h4(item.label)}</strong> ` : ""}${h4(item.text)}</p>`).join("")}</aside>`;
3017
+ break;
3018
+ }
3019
+ case "masthead":
3020
+ if (p.byline?.length) marks2 = stamp("model", { byline: p.byline.map((i) => ({ value: i.value, ...i.format ? { format: i.format } : {}, ...i.kind ? { kind: i.kind } : {} })) });
3021
+ content = `<header class="rpt-masthead">${p.marking ? `<div class="rpt-marking">${h4(p.marking)}</div>` : ""}${p.kicker ? `<p class="rpt-kicker">${h4(p.kicker)}</p>` : ""}<h1>${h4(p.title)}</h1>${p.byline?.length ? `<p class="rpt-byline">${p.byline.map((i) => i.kind === "date" || i.kind === "person" ? `<span class="rpt-chip rpt-${i.kind}">${h4(i.display)}</span>` : h4(i.display)).join(" \xB7 ")}</p>` : ""}${p.lead ? `<p class="rpt-lead">${h4(p.lead)}</p>` : ""}</header>`;
3022
+ break;
3023
+ case "footer": {
3024
+ const logo = p.logoImage;
3025
+ const src = logo ? report.assets.find((a) => a.path === logo.src) ? options.html?.assetMode === "bundled" ? logo.src : assetData(report.assets.find((a) => a.path === logo.src)) : logo.src : "";
3026
+ content = `<footer class="rpt-footer">${logo ? `<img src="${h4(src)}" alt="${h4(logo.alt)}"/>` : ""}${h4(p.text)}</footer>`;
3027
+ break;
3028
+ }
3029
+ case "figure": {
3030
+ const svg = figureSvg(node, report, options);
3031
+ marks2 = stamp("kind", p.figure.kind) + stamp("spec", figureSpec2(p.figure));
3032
+ content = `<figure class="rpt-figure"><div class="rpt-figure-box"><img src="${image(node, svg)}" alt="${h4(p.alt)}"/></div>${p.source ? `<figcaption>${h4(p.source)}</figcaption>` : ""}</figure><div class="rpt-sr-only">${tableHtml(p.table.columns, p.table.cells)}</div>`;
270
3033
  break;
3034
+ }
271
3035
  case "progress":
272
- content = p.items.map((i) => `<div class="progress-item"><div class="progress-label"><span>${h2(i.label)}</span><strong>${formatValue2(i.value, "percent:0", report.locale)}</strong></div><div class="progress-track" role="progressbar" aria-label="${h2(i.label)}" aria-valuenow="${i.value * 100}" aria-valuemin="0" aria-valuemax="100"><span style="width:${i.value * 100}%"></span></div>${i.detail ? `<small>${h2(i.detail)}</small>` : ""}</div>`).join("");
3036
+ content = p.items.map((i) => `<div class="progress-item"><div class="progress-label"><span>${h4(i.label)}</span><strong>${formatValue3(i.value, "percent:0", report.locale)}</strong></div><div class="progress-track" role="progressbar" aria-label="${h4(i.label)}" aria-valuenow="${i.value * 100}" aria-valuemin="0" aria-valuemax="100"><span style="width:${i.value * 100}%"></span></div>${i.detail ? `<small>${h4(i.detail)}</small>` : ""}</div>`).join("");
273
3037
  break;
274
3038
  case "timeline":
275
- content = p.items.map((i) => `<div class="timeline-item"><div class="timeline-date">${h2(i.date)}</div><strong>${h2(i.title)}</strong>${i.text ? `<p>${h2(i.text)}</p>` : ""}</div>`).join("");
3039
+ content = p.items.map((i) => `<div class="timeline-item"><div class="timeline-date">${h4(i.date)}</div><strong>${h4(i.title)}</strong>${i.text ? `<p>${h4(i.text)}</p>` : ""}</div>`).join("");
276
3040
  break;
277
3041
  case "comparison":
278
3042
  content = tableHtml([{ label: "", align: "left" }, ...p.labels.map((s) => ({ label: s }))], p.rows.map((r) => [r.label, r.left, r.right]));
279
3043
  break;
280
3044
  case "checklist":
281
- content = `<ul class="checklist">${p.items.map((i) => `<li><span class="checkmark">${i.done ? "\u2611" : "\u2610"}</span>${h2(i.text)}${i.owner ? ` <small>\xB7 ${h2(i.owner)}</small>` : ""}</li>`).join("")}</ul>`;
3045
+ content = `<ul class="checklist">${p.items.map((i) => `<li><span class="checkmark">${i.done ? "\u2611" : "\u2610"}</span>${h4(i.text)}${i.owner ? ` <small>\xB7 ${h4(i.owner)}</small>` : ""}</li>`).join("")}</ul>`;
282
3046
  break;
283
3047
  case "code":
284
- content = `${p.language ? `<small>${h2(p.language)}</small>` : ""}<pre><code>${h2(p.code)}</code></pre>${p.caption ? `<p>${h2(p.caption)}</p>` : ""}`;
3048
+ content = `${p.language ? `<small>${h4(p.language)}</small>` : ""}<pre><code>${h4(p.code)}</code></pre>${p.caption ? `<p>${h4(p.caption)}</p>` : ""}`;
3049
+ break;
3050
+ case "kit-chart": {
3051
+ if (p.empty) {
3052
+ content = `<p class="empty">${h4(p.message ?? "No data to display.")}</p>`;
3053
+ break;
3054
+ }
3055
+ const data = kitChartTable(node, report);
3056
+ marks2 = stamp("spec", p.spec);
3057
+ content = `<figure class="rpt-figure rpt-kit-chart"><div class="rpt-figure-box"><img src="${image(node, kitChartSvg(node, report, options))}" alt="${h4(p.alt)}"/></div>${p.source ? `<figcaption>${h4(p.source)}</figcaption>` : ""}<p class="rpt-sr-only">${h4(kitChartDescription(node, report))}</p></figure>${data.cells.length ? tableHtml(data.columns, data.cells, "chart-data") : ""}`;
3058
+ break;
3059
+ }
3060
+ case "divider":
3061
+ content = "<hr>";
3062
+ break;
3063
+ case "footnote":
3064
+ content = `<aside class="rpt-footnote"><p>${h4(p.text)}</p></aside>`;
3065
+ break;
3066
+ case "badge":
3067
+ content = `<p class="rpt-badges">${p.items.map((item) => `<span class="rpt-chip rpt-badge rpt-${h4(item.tone ?? "neutral")}">${h4(item.label)}</span>`).join("")}</p>`;
3068
+ break;
3069
+ case "columns": {
3070
+ const kids2 = node.children ?? [];
3071
+ const spans = Array.isArray(p.spans) && p.spans.length ? p.spans : [kids2.length];
3072
+ let i = 0;
3073
+ content = `<div class="rpt-columns" style="--cols:${spans.length}">${spans.map((span) => {
3074
+ const slice = kids2.slice(i, i + span);
3075
+ i += span;
3076
+ return `<div>${slice.map(render).join("")}</div>`;
3077
+ }).join("")}</div>`;
3078
+ break;
3079
+ }
3080
+ case "page-break":
3081
+ content = '<div class="rpt-break"></div>';
3082
+ break;
3083
+ case "toc": {
3084
+ const items = p.items ?? [];
3085
+ const title = p.title || "Contents";
3086
+ content = `<nav class="rpt-toc"><h2>${h4(title)}</h2>${items.length ? `<ol>${items.map((item) => `<li class="rpt-toc-l${h4(String(item.level))}"><a href="#${h4(item.anchor)}">${h4(item.text)}</a></li>`).join("")}</ol>` : `<p class="empty">No headings yet.</p>`}</nav>`;
3087
+ break;
3088
+ }
3089
+ case "cover":
3090
+ content = `<header class="rpt-cover">${p.marking ? `<div class="rpt-marking">${h4(p.marking)}</div>` : ""}${p.kicker ? `<p class="rpt-kicker">${h4(p.kicker)}</p>` : ""}<h1>${h4(p.title)}</h1>${p.subtitle ? `<p class="rpt-subtitle">${h4(p.subtitle)}</p>` : ""}</header>`;
285
3091
  break;
286
3092
  default:
287
- fail3("RENDERER_UNAVAILABLE", `No HTML representation for semantic type ${node.type}.`, { elementId: node.id, phase: "render" });
3093
+ fail4("RENDERER_UNAVAILABLE", `No HTML representation for semantic type ${node.type}.`, { elementId: node.id, phase: "render" });
288
3094
  }
289
- return `<section data-reportic-type="${h2(node.type)}" data-reportic-id="${h2(node.id)}" data-reportic-occurrence="${h2(node.occurrenceId)}">${content}</section>`;
3095
+ return `<section data-reportic-type="${h4(node.type)}" id="${h4(node.occurrenceId)}" data-reportic-id="${h4(node.id)}" data-reportic-occurrence="${h4(node.occurrenceId)}"${marks2}>${content}</section>`;
290
3096
  };
291
- const html = `<!doctype html><html lang="${h2(report.locale)}"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="generator" content="Reportic 0.2"><title>${h2(report.title)}</title><style>${reportCss(report, options)}</style></head><body><main class="reportic-report">${report.nodes.map(render).join("\n")}</main></body></html>`;
3097
+ const html = `<!doctype html><html lang="${h4(report.locale)}"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="generator" content="Reportic 0.2"><title>${h4(report.title)}</title><style>${reportCss(report, options)}</style></head><body><main class="reportic-report">${report.nodes.map(render).join("\n")}</main></body></html>`;
292
3098
  return { html, assets: [...report.assets, ...generated] };
293
3099
  }
294
3100
  async function renderMarkdown(report, options = {}) {
@@ -303,7 +3109,7 @@ ${cells.map((row) => `| ${row.map((v) => md(v.text ?? v)).join(" | ")} |`).join(
303
3109
  case "markdown":
304
3110
  return p.markdown;
305
3111
  case "metrics":
306
- return p.items.map((i) => `**${md(i.label)}:** ${md(i.display)}${i.comparison ? ` (${md(i.comparison)})` : ""}`).join("\n\n");
3112
+ return p.items.map((i) => `**${md(i.label)}:** ${md(i.display)}${i.comparison ? ` (${md(i.comparison)})` : ""}${i.trend ? ` (${trendWord(i.trend)})` : ""}`).join("\n\n");
307
3113
  case "table":
308
3114
  return p.rows.length ? table(p.columns, p.cells) : md(p.empty ?? "No rows to display.");
309
3115
  case "chart": {
@@ -344,20 +3150,38 @@ ${md(p.caption)}` : ""}`;
344
3150
  ` : ""}${md(p.text)}${(p.citations ?? []).map((n2) => ` [${n2}]`).join("")}`;
345
3151
  case "sources":
346
3152
  return p.citations.map((s) => `${s.number}. ${s.url ? `[${md(s.label)}](${s.url})` : md(s.label)}`).join("\n");
347
- case "list":
348
- return p.items.length ? p.items.map((s, i) => `${p.ordered ? i + 1 + "." : "-"} ${md(s)}`).join("\n") : md(p.empty ?? "No items to display.");
3153
+ case "list": {
3154
+ const lead = (i) => p.leads?.[i] ? `**${md(p.leads[i])}** ` : "";
3155
+ return p.items.length ? p.items.map((s, i) => p.variant === "callout" ? `> ${lead(i)}${md(s)}` : p.variant === "paragraphs" ? `${lead(i)}${md(s)}` : `${p.ordered ? i + 1 + "." : "-"} ${lead(i)}${md(s)}`).join(p.variant === "callout" ? "\n>\n" : p.variant === "paragraphs" ? "\n\n" : "\n") : md(p.empty ?? "No items to display.");
3156
+ }
3157
+ case "masthead":
3158
+ return [p.marking ? `**${md(p.marking)}**` : "", p.kicker ? md(p.kicker) : "", `# ${md(p.title)}`, p.byline?.length ? p.byline.map((i) => md(i.display)).join(" \xB7 ") : "", p.lead ? md(p.lead) : ""].filter(Boolean).join("\n\n");
3159
+ case "footer":
3160
+ return `---
3161
+
3162
+ ${md(p.text)}`;
3163
+ case "figure": {
3164
+ const path = `assets/${n.occurrenceId}.svg`;
3165
+ assets.push({ path, mediaType: "image/svg+xml", bytes: Buffer.from(figureSvg(n, report, options)) });
3166
+ return `![${md(p.alt)}](${path})${p.source ? `
3167
+
3168
+ Source: ${md(p.source)}` : ""}
3169
+
3170
+ ${table(p.table.columns, p.table.cells)}`;
3171
+ }
349
3172
  case "group":
350
3173
  return `${p.heading ? `## ${md(p.heading)}
351
3174
 
352
3175
  ` : ""}${(n.children ?? []).map(render).join("\n\n")}`;
353
3176
  case "repeat":
354
3177
  return n.children?.length ? n.children.map(render).join("\n\n") : md(p.empty ?? "No items to display.");
355
- case "callout":
356
- return `> **${md(p.title)}**
357
- >
358
- > ${md(p.text)}`;
3178
+ case "callout": {
3179
+ const lines = [`> **${md(p.title)}**`, `>`, `> ${md(p.text)}`];
3180
+ for (const item of p.items ?? []) lines.push(">", `> ${item.label ? `**${md(item.label)}** ` : ""}${md(item.text)}`);
3181
+ return lines.join("\n");
3182
+ }
359
3183
  case "progress":
360
- return p.items.map((i) => `- **${md(i.label)}:** ${formatValue2(i.value, "percent:0", report.locale)}${i.detail ? " \u2014 " + md(i.detail) : ""}`).join("\n");
3184
+ return p.items.map((i) => `- **${md(i.label)}:** ${formatValue3(i.value, "percent:0", report.locale)}${i.detail ? " \u2014 " + md(i.detail) : ""}`).join("\n");
361
3185
  case "timeline":
362
3186
  return p.items.map((i) => `- **${md(i.date)} \xB7 ${md(i.title)}**${i.text ? " \u2014 " + md(i.text) : ""}`).join("\n");
363
3187
  case "comparison":
@@ -370,8 +3194,45 @@ ${md(p.caption)}` : ""}`;
370
3194
  ${p.code}
371
3195
  ${ticks}`;
372
3196
  }
3197
+ case "kit-chart": {
3198
+ if (p.empty) return md(p.message ?? "No data to display.");
3199
+ const data = kitChartTable(n, report);
3200
+ const path = `assets/${n.occurrenceId}.svg`;
3201
+ assets.push({ path, mediaType: "image/svg+xml", bytes: Buffer.from(kitChartSvg(n, report, options)) });
3202
+ return `### ${md(p.title)}
3203
+
3204
+ ![${md(p.alt)}](${path})${p.source ? `
3205
+
3206
+ Source: ${md(p.source)}` : ""}
3207
+
3208
+ ${table(data.columns, data.cells)}`;
3209
+ }
3210
+ case "divider":
3211
+ return "---";
3212
+ case "footnote":
3213
+ return `*${md(p.text)}*`;
3214
+ case "badge":
3215
+ return p.items.map((item) => `**${md(item.label)}**`).join(" \xB7 ");
3216
+ case "columns": {
3217
+ const kids2 = n.children ?? [];
3218
+ const spans = Array.isArray(p.spans) && p.spans.length ? p.spans : [kids2.length];
3219
+ let i = 0;
3220
+ return spans.map((span) => {
3221
+ const slice = kids2.slice(i, i + span);
3222
+ i += span;
3223
+ return slice.map(render).join("\n\n");
3224
+ }).filter(Boolean).join("\n\n");
3225
+ }
3226
+ case "page-break":
3227
+ return "<!-- pagebreak -->";
3228
+ case "toc": {
3229
+ const items = p.items ?? [];
3230
+ return [`## ${md(p.title || "Contents")}`, ...items.map((item) => `${" ".repeat(Math.max(0, Number(item.level) - 1))}- [${md(item.text)}](#${item.anchor})`)].join("\n");
3231
+ }
3232
+ case "cover":
3233
+ return [p.marking ? `**${md(p.marking)}**` : "", p.kicker ? md(p.kicker) : "", `# ${md(p.title)}`, p.subtitle ? md(p.subtitle) : "", "<!-- pagebreak -->"].filter(Boolean).join("\n\n");
373
3234
  default:
374
- return fail3("RENDERER_UNAVAILABLE", `No Markdown representation for ${n.type}.`);
3235
+ return fail4("RENDERER_UNAVAILABLE", `No Markdown representation for ${n.type}.`);
375
3236
  }
376
3237
  };
377
3238
  let markdown = "";
@@ -386,12 +3247,19 @@ ${ticks}`;
386
3247
  return { markdown: markdown + (markdown.endsWith("\n") ? "" : "\n"), assets };
387
3248
  }
388
3249
  export {
3250
+ IMPORT_GUIDE,
389
3251
  assetData,
390
3252
  chartSvg,
391
3253
  chartTable,
392
3254
  cleanMarkdownHtml,
393
3255
  diagramVisuals,
3256
+ figureSvg,
394
3257
  findBrowser,
3258
+ guideFor,
3259
+ importHtml,
3260
+ kitChartDescription,
3261
+ kitChartSvg,
3262
+ kitChartTable,
395
3263
  renderHtml,
396
3264
  renderMarkdown,
397
3265
  reportCss,