@x12i/reportic-core 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,6 +1,6 @@
1
1
  // packages/reportic-core/src/types.ts
2
2
  var FORMAT_VERSION = "0.2";
3
- var VERSION = "0.2.3";
3
+ var VERSION = "0.2.5";
4
4
 
5
5
  // packages/reportic-core/src/safety.ts
6
6
  import { createHash } from "crypto";
@@ -81,10 +81,15 @@ function formatValue(value, format, locale = "en-US", timezone = "UTC") {
81
81
  if (kind !== "currency" && digits !== void 0 && (!Number.isInteger(digits) || digits < 0 || digits > 20)) fail("INVALID_FORMAT", "Decimal precision must be between 0 and 20.");
82
82
  return new Intl.NumberFormat(locale, kind === "currency" ? { style: "currency", currency: precision } : { style: kind === "percent" ? "percent" : "decimal", minimumFractionDigits: digits, maximumFractionDigits: digits }).format(value);
83
83
  }
84
- if (kind === "date" || kind === "datetime") {
85
- if (typeof value !== "string" || (kind === "date" ? !/^\d{4}-\d{2}-\d{2}$/.test(value) : !/T.*(?:Z|[+-]\d{2}:\d{2})$/.test(value))) fail("INVALID_FORMAT_VALUE", `${kind} requires ${kind === "date" ? "an ISO calendar date" : "an ISO timestamp with an explicit offset"}.`);
86
- const d = new Date(kind === "date" ? `${value}T00:00:00Z` : value);
87
- if (Number.isNaN(d.getTime()) || kind === "date" && d.toISOString().slice(0, 10) !== value) fail("INVALID_FORMAT_VALUE", "Invalid calendar date.");
84
+ if (kind === "date" || kind === "datetime" || kind === "shortdate") {
85
+ const calendar = kind !== "datetime";
86
+ if (typeof value !== "string" || (calendar ? !/^\d{4}-\d{2}-\d{2}$/.test(value) : !/T.*(?:Z|[+-]\d{2}:\d{2})$/.test(value))) fail("INVALID_FORMAT_VALUE", `${kind} requires ${calendar ? "an ISO calendar date" : "an ISO timestamp with an explicit offset"}.`);
87
+ const d = new Date(calendar ? `${value}T00:00:00Z` : value);
88
+ if (Number.isNaN(d.getTime()) || calendar && d.toISOString().slice(0, 10) !== value) fail("INVALID_FORMAT_VALUE", "Invalid calendar date.");
89
+ if (kind === "shortdate") {
90
+ const out = new Intl.DateTimeFormat(locale, { day: "numeric", month: "short", year: "numeric", timeZone: "UTC" }).format(d);
91
+ return /^en(?:-|$)/i.test(locale) ? out.replace(/\bSept\b/, "Sep") : out;
92
+ }
88
93
  return new Intl.DateTimeFormat(locale, { dateStyle: "medium", ...kind === "datetime" ? { timeStyle: "short" } : {}, timeZone: kind === "date" ? "UTC" : timezone }).format(d);
89
94
  }
90
95
  fail("INVALID_FORMAT", `Unknown format "${format}".`);
@@ -102,6 +107,26 @@ function themeTokens(theme = {}) {
102
107
  };
103
108
  return { ...baseTokens, ...presets[theme.name ?? "editorial"], ...theme.tokens };
104
109
  }
110
+ var hexColor = /^#(?:[\da-f]{3}|[\da-f]{4}|[\da-f]{6}|[\da-f]{8})$/i;
111
+ function relativeLuminance(hex) {
112
+ const s = hex.replace("#", "");
113
+ const full = s.length <= 4 ? s.slice(0, 3).split("").map((c) => c + c).join("") : s.slice(0, 6);
114
+ const [r, g, b] = [0, 2, 4].map((i) => parseInt(full.slice(i, i + 2), 16) / 255);
115
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b;
116
+ }
117
+ function semanticColors(tokens) {
118
+ const dark = relativeLuminance(tokens.background) < 0.4;
119
+ const base = dark ? { ok: "#6bc28f", warn: "#e2bc7b", bad: "#e08a80", na: tokens.muted, ink: tokens.text, grey: "#5b6778", grid: tokens.border, axis: "#6b7686", okSoft: "#6bc28f26", warnSoft: "#e2bc7b26", badSoft: "#e08a8026", accentSoft: `${tokens.accent}26`, zebra: `${tokens.accent}0d`, head: `${tokens.accent}1a`, page: tokens.background } : { ok: "#2f7d4f", warn: "#b07a1a", bad: "#bb4f46", na: tokens.muted, ink: tokens.text, grey: "#b9bec9", grid: tokens.border, axis: "#9aa0ad", okSoft: "#2f7d4f1a", warnSoft: "#b07a1a1f", badSoft: "#bb4f461a", accentSoft: `${tokens.accent}14`, zebra: `${tokens.accent}08`, head: `${tokens.accent}0d`, page: tokens.background };
120
+ return { ...base, ...tokens.semantic };
121
+ }
122
+ var tones = ["ok", "warn", "bad", "na"];
123
+ function statusTone(label) {
124
+ const k = String(label ?? "").trim().toLowerCase();
125
+ if (["done", "closed", "complete", "completed", "met"].includes(k)) return "done";
126
+ if (["late", "overdue", "off target", "not met"].includes(k)) return "late";
127
+ if (["in progress", "started", "at risk"].includes(k)) return "progress";
128
+ return "";
129
+ }
105
130
  function validateStyles(o, format) {
106
131
  if (o.css && /@import|url\s*\(|expression\s*\(|<\/?style|behavior\s*:/i.test(o.css)) fail("UNSAFE_CSS", "External CSS resources and executable CSS are not allowed.");
107
132
  const tokens = themeTokens(o.theme);
@@ -109,6 +134,8 @@ function validateStyles(o, format) {
109
134
  if (typeof tokens.fontFamily !== "string" || typeof tokens.headingFont !== "string" || /[;{}<>@]/.test(tokens.fontFamily + tokens.headingFont)) fail("INVALID_THEME", "Invalid font family.");
110
135
  for (const key of ["bodySize", "headingSize", "contentWidth", "spacing", "logoWidth"]) if (!Number.isFinite(tokens[key]) || tokens[key] < 1 || tokens[key] > 5e3) fail("INVALID_THEME", `Invalid theme token ${key}.`);
111
136
  if (!Array.isArray(tokens.chartPalette) || tokens.chartPalette.length === 0 || tokens.chartPalette.some((c) => !/^#(?:[\da-f]{3}|[\da-f]{4}|[\da-f]{6}|[\da-f]{8})$/i.test(c))) fail("INVALID_THEME", "Chart palette must contain hex colors.");
137
+ if (tokens.semantic !== void 0 && (!isRecord(tokens.semantic) || Object.values(tokens.semantic).some((c) => typeof c !== "string" || !hexColor.test(c)))) fail("INVALID_THEME", "Semantic colors must be hex colors.");
138
+ if (tokens.layout !== void 0 && tokens.layout !== "page" && tokens.layout !== "card") fail("INVALID_THEME", 'Theme layout must be "page" or "card".');
112
139
  for (const [selector, rule] of Object.entries(o.theme?.rules ?? {})) {
113
140
  if (!/^[a-zA-Z0-9_.-]+$/.test(selector)) fail("INVALID_THEME", "Style rule selectors must be semantic types or element IDs.");
114
141
  for (const [property, value] of Object.entries(rule)) if (!["color", "backgroundColor", "fontSize", "fontFamily", "fontWeight", "textAlign", "marginTop", "marginBottom", "padding", "borderColor", "borderWidth"].includes(property) || /[;{}<>@]|url\s*\(/i.test(String(value))) fail("INVALID_THEME", `Unsupported or unsafe semantic style property ${property}.`);
@@ -156,7 +183,14 @@ function parseTemplate(source) {
156
183
  if (!Array.isArray(e.props.children)) fail("INVALID_ELEMENT", `${e.type} children must be authored element mappings.`, { phase: "parse", line, elementId: e.id });
157
184
  e.props.children = e.props.children.map((child) => validateElement(child, line, depth + 1));
158
185
  }
159
- return { id: e.id, type: e.type, props: e.props, fallback: e.fallback, line };
186
+ if (e.type === "reportic.columns.v1") {
187
+ if (!Array.isArray(e.props.columns) || e.props.columns.length < 2 || e.props.columns.length > 4) fail("INVALID_ELEMENT", "Columns need two, three, or four stacks.", { phase: "parse", line, elementId: e.id });
188
+ e.props.columns = e.props.columns.map((col) => {
189
+ if (!Array.isArray(col)) fail("INVALID_ELEMENT", "Each column is a list of elements.", { phase: "parse", line, elementId: e.id });
190
+ return col.map((child) => validateElement(child, line, depth + 1));
191
+ });
192
+ }
193
+ return { id: e.id, type: e.type, props: e.props, fallback: e.fallback, ...e.when !== void 0 ? { when: e.when } : {}, line };
160
194
  };
161
195
  let offset = metadataMatch?.[0].length ?? 0;
162
196
  let body = "";
@@ -186,6 +220,169 @@ import Ajv from "ajv";
186
220
  import Ajv2020 from "ajv/dist/2020.js";
187
221
  import addFormats from "ajv-formats";
188
222
  import { lexer as lexer2, marked } from "marked";
223
+
224
+ // packages/reportic-core/src/figure.ts
225
+ var figureKinds = ["hbar", "bar", "grouped", "stacked", "line", "matrix", "dots", "flow"];
226
+ var figureTones = ["accent", "grey", "muted", "ok", "warn", "bad"];
227
+ var MAX_ITEMS = 300;
228
+ var MAX_SERIES = 12;
229
+ var MAX_NODES = 120;
230
+ var MAX_EDGES = 400;
231
+ var bad = (message) => fail("INVALID_ELEMENT_PROPS", `Figure: ${message}`);
232
+ var text = (v, name, max = 400) => {
233
+ if (typeof v !== "string" || v.length > max) bad(`${name} must be text of at most ${max} characters.`);
234
+ return v;
235
+ };
236
+ var optText = (v, name, max = 400) => v === void 0 || v === null ? void 0 : text(v, name, max);
237
+ var num = (v, name) => {
238
+ if (typeof v !== "number" || !Number.isFinite(v)) bad(`${name} must be a finite number.`);
239
+ return v;
240
+ };
241
+ var bounded = (v, name, lo, hi) => {
242
+ if (v === void 0 || v === null) return void 0;
243
+ const n = num(v, name);
244
+ if (n < lo || n > hi) bad(`${name} must be between ${lo} and ${hi}.`);
245
+ return n;
246
+ };
247
+ var list = (v, name, max = MAX_ITEMS) => {
248
+ if (!Array.isArray(v) || v.length > max) bad(`${name} must be a list of at most ${max} items.`);
249
+ return v;
250
+ };
251
+ var tone = (v, name) => {
252
+ if (v === void 0 || v === null || v === "") return void 0;
253
+ if (!figureTones.includes(v)) bad(`${name} must be one of ${figureTones.join(", ")}.`);
254
+ return v;
255
+ };
256
+ var strings = (v, name, max = MAX_ITEMS) => list(v, name, max).map((s, i) => text(s, `${name}[${i}]`));
257
+ var reference = (v) => {
258
+ if (v === void 0 || v === null) return void 0;
259
+ if (!isRecord(v)) bad("reference must be {value, label}.");
260
+ const r = v;
261
+ return { value: num(r.value, "reference.value"), ...r.label !== void 0 ? { label: text(r.label, "reference.label") } : {} };
262
+ };
263
+ var numbers = (v, name, length, allowNull = false) => {
264
+ const items = list(v, name);
265
+ if (items.length !== length) bad(`${name} needs ${length} values, one per category.`);
266
+ return items.map((n, i) => allowNull && (n === null || n === void 0) ? null : num(n, `${name}[${i}]`));
267
+ };
268
+ var tones2 = (v, name, length) => v === void 0 || v === null ? void 0 : list(v, name).slice(0, length).map((t, i) => tone(t, `${name}[${i}]`) ?? null);
269
+ function parseFigure(raw) {
270
+ if (!isRecord(raw)) return bad("spec must be an object.");
271
+ const s = raw;
272
+ if (!figureKinds.includes(s.type)) bad(`spec.type must be one of ${figureKinds.join(", ")}.`);
273
+ const kind = s.type;
274
+ const figure = { kind, title: text(s.title, "title"), subtitle: optText(s.subtitle, "subtitle"), note: optText(s.note, "note", 600) };
275
+ if (s.unit !== void 0 && s.unit !== null) figure.unit = text(s.unit, "unit", 8);
276
+ figure.reference = reference(s.reference);
277
+ figure.labelWidth = bounded(s.labelWidth, "labelWidth", 40, 600);
278
+ figure.rowHeight = bounded(s.rowHeight, "rowHeight", 12, 80);
279
+ figure.height = bounded(s.height, "height", 120, 900);
280
+ figure.min = s.min === void 0 || s.min === null ? void 0 : num(s.min, "min");
281
+ figure.max = s.max === void 0 || s.max === null ? void 0 : num(s.max, "max");
282
+ if (figure.min !== void 0 && figure.max !== void 0 && figure.max <= figure.min) bad("max must be greater than min.");
283
+ figure.nodeHeight = bounded(s.nodeHeight, "nodeHeight", 24, 200);
284
+ if (kind === "hbar" || kind === "dots") {
285
+ figure.categories = strings(s.categories, "categories");
286
+ figure.values = numbers(s.values, "values", figure.categories.length);
287
+ if (s.highlight !== void 0) figure.highlight = list(s.highlight, "highlight").map((i, k) => {
288
+ if (!Number.isInteger(i) || i < 0 || i >= figure.categories.length) bad(`highlight[${k}] must be a valid category index.`);
289
+ return i;
290
+ });
291
+ figure.tones = tones2(s.tones, "tones", figure.categories.length);
292
+ } else if (kind === "bar" || kind === "grouped" || kind === "stacked" || kind === "line") {
293
+ figure.categories = strings(s.categories, "categories");
294
+ figure.series = list(s.series, "series", MAX_SERIES).map((x, i) => {
295
+ if (!isRecord(x)) bad(`series[${i}] must be an object.`);
296
+ return { name: text(x.name, `series[${i}].name`, 120), values: numbers(x.values, `series[${i}].values`, figure.categories.length, true), tone: tone(x.tone, `series[${i}].tone`) };
297
+ });
298
+ if (!figure.series.length) bad("series needs at least one entry.");
299
+ } else if (kind === "matrix") {
300
+ figure.rows = strings(s.rows, "rows");
301
+ figure.cols = strings(s.cols, "cols", 60);
302
+ const grid = list(s.values, "values");
303
+ if (grid.length !== figure.rows.length) bad("values needs one row per entry in rows.");
304
+ figure.matrix = grid.map((r, i) => numbers(r, `values[${i}]`, figure.cols.length, true));
305
+ if (s.cellTones !== void 0 && s.cellTones !== null) figure.cellTones = list(s.cellTones, "cellTones").slice(0, figure.rows.length).map((r, i) => list(r ?? [], `cellTones[${i}]`, 60).map((t, j) => tone(t, `cellTones[${i}][${j}]`) ?? null));
306
+ figure.rowTones = tones2(s.rowTones, "rowTones", figure.rows.length);
307
+ figure.colTones = tones2(s.colTones, "colTones", figure.cols.length);
308
+ } else {
309
+ const ids = /* @__PURE__ */ new Set();
310
+ let total = 0;
311
+ figure.columns = list(s.columns, "columns", 12).map((c, i) => {
312
+ if (!isRecord(c)) bad(`columns[${i}] must be an object.`);
313
+ const nodes = list(c.nodes, `columns[${i}].nodes`, MAX_NODES).map((n, j) => {
314
+ if (!isRecord(n)) bad(`columns[${i}].nodes[${j}] must be an object.`);
315
+ const id = text(n.id, `columns[${i}].nodes[${j}].id`, 80);
316
+ if (ids.has(id)) bad(`node id "${id}" is used more than once.`);
317
+ ids.add(id);
318
+ total++;
319
+ const sub = n.sub === void 0 || n.sub === null ? void 0 : Array.isArray(n.sub) ? strings(n.sub, `columns[${i}].nodes[${j}].sub`, 8) : [text(n.sub, `columns[${i}].nodes[${j}].sub`)];
320
+ return { id, label: text(n.label, `columns[${i}].nodes[${j}].label`, 160), sub, tone: tone(n.tone, `columns[${i}].nodes[${j}].tone`), dashed: n.dashed === true };
321
+ });
322
+ return { title: optText(c.title, `columns[${i}].title`, 80), nodes };
323
+ });
324
+ if (!figure.columns.length || total === 0) bad("flow needs at least one column with a node.");
325
+ if (total > MAX_NODES) bad(`flow supports at most ${MAX_NODES} nodes.`);
326
+ figure.edges = list(s.edges ?? [], "edges", MAX_EDGES).map((e, i) => {
327
+ if (!isRecord(e)) bad(`edges[${i}] must be an object.`);
328
+ const from = text(e.from, `edges[${i}].from`, 80), to = text(e.to, `edges[${i}].to`, 80);
329
+ if (!ids.has(from) || !ids.has(to)) bad(`edges[${i}] refers to a node that does not exist.`);
330
+ return { from, to, tone: tone(e.tone, `edges[${i}].tone`), dashed: e.dashed === true, label: optText(e.label, `edges[${i}].label`, 120) };
331
+ });
332
+ }
333
+ return figure;
334
+ }
335
+ function figureTable(figure, locale = "en-US") {
336
+ const n = (v) => v === null || v === void 0 ? "" : figure.unit === "%" ? `${new Intl.NumberFormat(locale, { maximumFractionDigits: 1 }).format(v)}%` : new Intl.NumberFormat(locale, { maximumFractionDigits: 1 }).format(v);
337
+ const target = figure.reference ? figure.reference.label || "Reference" : "";
338
+ if (figure.kind === "hbar" || figure.kind === "dots") return { columns: [{ label: "Item" }, { label: "Value", align: "right" }], cells: [...figure.categories.map((c, i) => [c, n(figure.values[i])]), ...figure.reference ? [[target, n(figure.reference.value)]] : []] };
339
+ if (figure.series) return { columns: [{ label: "Item" }, ...figure.series.map((s) => ({ label: s.name, align: "right" }))], cells: [...figure.categories.map((c, i) => [c, ...figure.series.map((s) => n(s.values[i]))]), ...figure.reference ? [[target, ...figure.series.map((_, j) => figure.kind === "stacked" && j > 0 ? "" : n(figure.reference.value))]] : []] };
340
+ if (figure.kind === "matrix") return { columns: [{ label: "" }, ...figure.cols.map((c) => ({ label: c, align: "right" }))], cells: figure.rows.map((r, i) => [r, ...figure.matrix[i].map(n)]) };
341
+ const nodes = figure.columns.flatMap((c) => c.nodes), label = new Map(nodes.map((x) => [x.id, x.label]));
342
+ const linked = new Set(figure.edges.flatMap((e) => [e.from, e.to]));
343
+ const described = nodes.filter((x) => x.sub?.length || !linked.has(x.id)).map((x) => [x.label, "", (x.sub ?? []).join(" \xB7 ")]);
344
+ return { columns: [{ label: "From" }, { label: "To" }, { label: "Note" }], cells: [...figure.edges.map((e) => [label.get(e.from), label.get(e.to), e.label ?? ""]), ...described] };
345
+ }
346
+ function figureSpec(figure) {
347
+ const spec = { type: figure.kind, title: figure.title };
348
+ const put = (key, value) => {
349
+ if (value !== void 0 && value !== null) spec[key] = value;
350
+ };
351
+ put("subtitle", figure.subtitle);
352
+ put("note", figure.note);
353
+ put("unit", figure.unit);
354
+ put("reference", figure.reference);
355
+ put("labelWidth", figure.labelWidth);
356
+ put("rowHeight", figure.rowHeight);
357
+ put("height", figure.height);
358
+ put("min", figure.min);
359
+ put("max", figure.max);
360
+ put("nodeHeight", figure.nodeHeight);
361
+ const pruned = (tones3) => tones3 && tones3.some(Boolean) ? tones3 : void 0;
362
+ if (figure.kind === "hbar" || figure.kind === "dots") {
363
+ put("categories", figure.categories);
364
+ put("values", figure.values);
365
+ put("highlight", figure.highlight?.length ? figure.highlight : void 0);
366
+ put("tones", pruned(figure.tones));
367
+ } else if (figure.series) {
368
+ put("categories", figure.categories);
369
+ put("series", figure.series.map((s) => ({ name: s.name, values: s.values, ...s.tone ? { tone: s.tone } : {} })));
370
+ } else if (figure.kind === "matrix") {
371
+ put("rows", figure.rows);
372
+ put("cols", figure.cols);
373
+ put("values", figure.matrix);
374
+ put("cellTones", figure.cellTones?.some((r) => r.some(Boolean)) ? figure.cellTones : void 0);
375
+ put("rowTones", pruned(figure.rowTones));
376
+ put("colTones", pruned(figure.colTones));
377
+ } else {
378
+ put("columns", figure.columns.map((c) => ({ ...c.title ? { title: c.title } : {}, nodes: c.nodes.map((x) => ({ id: x.id, label: x.label, ...x.sub?.length ? { sub: x.sub } : {}, ...x.tone ? { tone: x.tone } : {}, ...x.dashed ? { dashed: true } : {} })) })));
379
+ put("edges", figure.edges?.length ? figure.edges.map((e) => ({ from: e.from, to: e.to, ...e.tone ? { tone: e.tone } : {}, ...e.dashed ? { dashed: true } : {}, ...e.label ? { label: e.label } : {} })) : void 0);
380
+ }
381
+ return spec;
382
+ }
383
+ var figureAlt = (figure) => `${figure.title}${figure.subtitle ? ` \u2014 ${figure.subtitle}` : ""}`;
384
+
385
+ // packages/reportic-core/src/prepare.ts
189
386
  var ajv = new Ajv({ allErrors: true, strict: false });
190
387
  var MISSING = /* @__PURE__ */ Symbol("missing");
191
388
  function resolvePath(path, context) {
@@ -201,9 +398,12 @@ function resolvePath(path, context) {
201
398
  }
202
399
  function bind(value, context, skip = /* @__PURE__ */ new Set()) {
203
400
  if (isRecord(value) && own(value, "$bind")) {
204
- if (Object.keys(value).length !== 1) fail("INVALID_BINDING", "A binding may contain only $bind.");
401
+ if (Object.keys(value).some((k) => k !== "$bind" && k !== "default")) fail("INVALID_BINDING", "A binding may contain only $bind and an optional default.");
205
402
  const result = resolvePath(value.$bind, context);
206
- if (result === MISSING) fail("MISSING_REQUIRED_INPUT", `Missing value at ${value.$bind}.`, { bindingPath: value.$bind });
403
+ if (result === MISSING) {
404
+ if (own(value, "default")) return structuredClone(value.default);
405
+ fail("MISSING_REQUIRED_INPUT", `Missing value at ${value.$bind}.`, { bindingPath: value.$bind });
406
+ }
207
407
  return structuredClone(result);
208
408
  }
209
409
  if (Array.isArray(value)) return value.map((v) => bind(v, context));
@@ -248,28 +448,37 @@ function validateInput(dataSets, variables, options, declarations) {
248
448
  return indexed;
249
449
  }
250
450
  function validateSvg(bytes) {
251
- const text = Buffer.from(bytes).toString("utf8");
252
- if (!/^\s*(?:<\?xml[^>]*>\s*)?<svg[\s>]/i.test(text) || /<\s*[\w-]+:|<\s*(script|foreignObject|iframe|object|embed|image|use|a|style|animate\w*|set)\b|\bon\w+\s*=|(?:href|src)\s*=|url\s*\(|<!DOCTYPE|<!ENTITY|javascript:|data:/i.test(text)) fail("UNSAFE_SVG", "SVG must contain only static, self-contained vector content.");
451
+ const text2 = Buffer.from(bytes).toString("utf8");
452
+ if (!/^\s*(?:<\?xml[^>]*>\s*)?<svg[\s>]/i.test(text2) || /<\s*[\w-]+:|<\s*(script|foreignObject|iframe|object|embed|image|use|a|style|animate\w*|set)\b|\bon\w+\s*=|(?:href|src)\s*=|url\s*\(|<!DOCTYPE|<!ENTITY|javascript:|data:/i.test(text2)) fail("UNSAFE_SVG", "SVG must contain only static, self-contained vector content.");
253
453
  }
254
454
  function assetReference(ref, alt, options, assets) {
255
455
  if (typeof alt !== "string" || !alt.trim()) fail("INVALID_ELEMENT_PROPS", "Managed images require nonempty alt text.");
256
- if (!isRecord(ref) || Object.keys(ref).length !== 1) fail("INVALID_ASSET_REFERENCE", "Image src must be { asset: key } or { url: httpsURL }.");
456
+ if (!isRecord(ref) || Object.keys(ref).length !== 1) fail("INVALID_ASSET_REFERENCE", "Image src must be { asset: key }, { org: kind }, or { url: httpsURL }.");
257
457
  if (typeof ref.url === "string") {
258
458
  safeUrl(ref.url, true);
259
459
  if (!options.allowRemoteImages) fail("REMOTE_ASSET_DENIED", "Remote images require allowRemoteImages: true.");
260
460
  return { src: ref.url, alt, remote: true };
261
461
  }
462
+ if (typeof ref.org === "string") {
463
+ if (!/^[a-z][a-z0-9-]{0,31}$/.test(ref.org)) fail("INVALID_ASSET_REFERENCE", "Use an organization file name such as logo.");
464
+ const input2 = options.orgResources?.[ref.org];
465
+ if (!input2) fail("ORG_RESOURCE_MISSING", `Organization file "${ref.org}" was not supplied.`);
466
+ return embedAsset(`org-${ref.org}`, input2, alt, options, assets, `Organization file "${ref.org}"`, false);
467
+ }
262
468
  if (typeof ref.asset !== "string") fail("INVALID_ASSET_REFERENCE", "Missing asset key.");
263
469
  const key = ref.asset;
264
470
  if (!/^[a-zA-Z0-9_-]+$/.test(key)) fail("UNSAFE_PATH", "Asset keys must contain only letters, numbers, underscores, and hyphens.");
265
471
  const input = options.assets?.[key];
266
472
  if (!input) fail("ASSET_MISSING", `Asset "${key}" was not supplied.`);
267
- const extensions = { "image/png": "png", "image/jpeg": "jpg", "image/webp": "webp", "image/svg+xml": "svg" };
268
- if (!extensions[input.mediaType]) fail("ASSET_UNSUPPORTED", `Unsupported image media type for "${key}".`);
269
- if (!(input.bytes instanceof Uint8Array) || input.bytes.length > limitsFor(options).assetBytes) fail("LIMIT_EXCEEDED", `Asset "${key}" is invalid or too large.`);
473
+ return embedAsset(key, input, alt, options, assets, `Asset "${key}"`, true);
474
+ }
475
+ function embedAsset(key, input, alt, options, assets, label, allowSvg) {
476
+ const extensions = { "image/png": "png", "image/jpeg": "jpg", "image/webp": "webp", ...allowSvg ? { "image/svg+xml": "svg" } : {} };
477
+ if (!extensions[input.mediaType]) fail("ASSET_UNSUPPORTED", allowSvg ? `${label} must be a PNG, JPEG, WebP, or SVG image.` : `${label} must be a PNG, JPEG, or WebP image.`);
478
+ if (!(input.bytes instanceof Uint8Array) || input.bytes.length > limitsFor(options).assetBytes) fail("LIMIT_EXCEEDED", `${label} is invalid or too large.`);
270
479
  if (input.mediaType === "image/svg+xml") validateSvg(input.bytes);
271
480
  const bytes = input.bytes;
272
- if (input.mediaType === "image/png" && Buffer.from(bytes.subarray(0, 8)).toString("hex") !== "89504e470d0a1a0a" || input.mediaType === "image/jpeg" && !(bytes[0] === 255 && bytes[1] === 216) || input.mediaType === "image/webp" && Buffer.from(bytes.subarray(8, 12)).toString() !== "WEBP") fail("ASSET_INVALID", `Asset "${key}" does not match its declared media type.`);
481
+ if (input.mediaType === "image/png" && Buffer.from(bytes.subarray(0, 8)).toString("hex") !== "89504e470d0a1a0a" || input.mediaType === "image/jpeg" && !(bytes[0] === 255 && bytes[1] === 216) || input.mediaType === "image/webp" && Buffer.from(bytes.subarray(8, 12)).toString() !== "WEBP") fail("ASSET_INVALID", `${label} does not match its declared media type.`);
273
482
  const path = safeRelative(`assets/${key}.${extensions[input.mediaType]}`);
274
483
  if (!assets.some((a) => a.path === path)) assets.push({ path, mediaType: input.mediaType, bytes: new Uint8Array(bytes) });
275
484
  return { src: path, alt, assetPath: path };
@@ -345,20 +554,111 @@ async function prepareReportModel(template, dataSets, variables, options, regist
345
554
  let nodeCount = 0;
346
555
  const context = { dataSets: map, variables };
347
556
  const display = (v, format) => formatValue(v, format, locale, timezone);
557
+ const optionalBind = (value, scope, element) => {
558
+ try {
559
+ return bind(value, scope);
560
+ } catch (e) {
561
+ if (e instanceof ReporticError && e.diagnostics.every((d) => d.code === "MISSING_REQUIRED_INPUT")) {
562
+ if (element) diagnostics.push({ code: "OPTIONAL_VALUE_OMITTED", severity: "info", phase: "prepare", message: `An optional value is missing and was left out: ${e.diagnostics[0]?.bindingPath ?? "binding"}.`, elementId: element.id, bindingPath: e.diagnostics[0]?.bindingPath });
563
+ return void 0;
564
+ }
565
+ throw e;
566
+ }
567
+ };
568
+ const kindCell = (column, raw, tone2) => {
569
+ const kind = column.kind, format = column.format;
570
+ if (!kind) return { raw, text: display(raw, format) };
571
+ if (kind === "rating") {
572
+ if (raw === null || raw === void 0 || raw === "") return { raw, text: "", kind };
573
+ if (tone2 !== void 0 && tone2 !== null && tone2 !== "" && !isRecord(raw)) {
574
+ if (!tones.includes(tone2) || !["string", "number"].includes(typeof raw)) fail("INVALID_ELEMENT_PROPS", "A rating column tone must be ok, warn, bad, or na, and its value text or a number.");
575
+ return { raw, text: display(raw, format), kind, tone: tone2 };
576
+ }
577
+ if (!isRecord(raw) || !tones.includes(raw.tone) || typeof raw.label !== "string") fail("INVALID_ELEMENT_PROPS", "A rating cell needs { tone: ok | warn | bad | na, label }.");
578
+ return { raw, text: raw.label, kind, tone: raw.tone };
579
+ }
580
+ if (kind === "list") {
581
+ if (raw === null || raw === void 0 || raw === "") return { raw, text: "", kind };
582
+ if (!Array.isArray(raw) || raw.length > 200 || raw.some((x) => !["string", "number", "boolean"].includes(typeof x))) fail("INVALID_ELEMENT_PROPS", "A list cell needs a list of text or numbers.");
583
+ return { raw, text: raw.map((x) => display(x, format)).join(", "), kind };
584
+ }
585
+ if (kind === "date") return { raw, text: raw === null || raw === void 0 || raw === "" ? "" : display(raw, format ?? "date"), kind };
586
+ const text2 = display(raw, format);
587
+ return { raw, text: text2, kind, ...kind === "status" ? { status: statusTone(text2) } : {} };
588
+ };
589
+ const partKeys = /* @__PURE__ */ new Set(["value", "format", "kind", "prefix", "suffix", "optional", "join"]);
590
+ const composeCell = (column, scope) => {
591
+ if (column.value.length > 12) fail("INVALID_ELEMENT_PROPS", "A composed cell supports at most 12 parts.");
592
+ const runs = [];
593
+ const push = (text3, style = {}) => {
594
+ if (text3) runs.push({ text: text3, ...style });
595
+ };
596
+ for (const part of column.value) {
597
+ if (["string", "number", "boolean"].includes(typeof part)) {
598
+ push(String(part));
599
+ continue;
600
+ }
601
+ const spec = isRecord(part) && own(part, "$bind") ? { value: part } : part;
602
+ if (!isRecord(spec) || !own(spec, "value") || Object.keys(spec).some((k) => !partKeys.has(k))) fail("INVALID_ELEMENT_PROPS", "A composed cell part must be text, a binding, or { value, format?, kind?, prefix?, suffix?, join?, optional? }.");
603
+ let v = spec.value;
604
+ if (isRecord(v) && own(v, "$bind")) {
605
+ if (Object.keys(v).some((k) => k !== "$bind" && k !== "default")) fail("INVALID_BINDING", "A binding may contain only $bind and an optional default.");
606
+ const found = resolvePath(v.$bind, scope);
607
+ if (found === MISSING) {
608
+ if (own(v, "default")) v = v.default;
609
+ else if (spec.optional === true) continue;
610
+ else fail("MISSING_REQUIRED_INPUT", `Missing value at ${v.$bind}.`, { bindingPath: v.$bind });
611
+ } else v = found;
612
+ }
613
+ if (spec.join !== void 0) {
614
+ if (typeof spec.join !== "string") fail("INVALID_ELEMENT_PROPS", "A part join must be text.");
615
+ if (v !== null && v !== void 0 && v !== "" && !Array.isArray(v)) fail("INVALID_ELEMENT_PROPS", "A part with join needs a list.");
616
+ if (Array.isArray(v)) {
617
+ if (v.length > 200 || v.some((x) => !["string", "number", "boolean"].includes(typeof x))) fail("INVALID_ELEMENT_PROPS", "A joined part needs a list of at most 200 text or number items.");
618
+ v = v.map((x) => display(x, spec.format)).join(spec.join);
619
+ }
620
+ }
621
+ if (v === null || v === void 0 || v === "") continue;
622
+ let text3, style = {};
623
+ if (isRecord(v) && spec.kind === "rating") {
624
+ if (!tones.includes(v.tone) || typeof v.label !== "string") fail("INVALID_ELEMENT_PROPS", "A rating needs { tone: ok | warn | bad | na, label }.");
625
+ text3 = v.label;
626
+ style = { tone: v.tone };
627
+ } else {
628
+ text3 = spec.join !== void 0 ? String(v) : display(v, spec.format);
629
+ if (spec.kind === "code") style = { code: true };
630
+ else if (spec.kind === "strong") style = { strong: true };
631
+ }
632
+ const suffix = Array.isArray(spec.suffix) ? v === 1 ? spec.suffix[0] : spec.suffix[1] : spec.suffix;
633
+ if (spec.prefix !== void 0) push(String(spec.prefix));
634
+ push(text3, style);
635
+ if (suffix !== void 0) push(String(suffix));
636
+ }
637
+ const text2 = runs.map((r) => r.text).join("");
638
+ return { raw: text2, text: text2, runs };
639
+ };
640
+ const textOf = (spec, scope, what) => {
641
+ if (Array.isArray(spec)) return composeCell({ value: spec }, scope).text;
642
+ const text2 = bind(spec, scope);
643
+ if (typeof text2 !== "string") fail("INVALID_ELEMENT_PROPS", `${what} must be text.`);
644
+ return text2;
645
+ };
646
+ const truthy = (v) => v === void 0 || v === null || v === false || v === 0 || v === "" ? false : Array.isArray(v) ? v.length > 0 : isRecord(v) ? Object.keys(v).length > 0 : true;
348
647
  const normalize = (element, row) => {
349
648
  checkAbort(options);
649
+ const local = { ...context, ...row !== void 0 ? { row } : {} };
650
+ if (element.when !== void 0 && !truthy(optionalBind(element.when, local))) return void 0;
350
651
  if (++nodeCount > limit.nodes) fail("LIMIT_EXCEEDED", `Report exceeds ${limit.nodes} semantic nodes.`);
351
652
  const occurrence = (occurrences.get(element.id) ?? 0) + 1;
352
653
  occurrences.set(element.id, occurrence);
353
654
  const node = { id: element.id, occurrenceId: `${element.id}-${occurrence}`, type: element.type, componentType: element.type, props: {}, line: element.line };
354
- const local = { ...context, ...row !== void 0 ? { row } : {} };
355
655
  const definition = registry.get(element.type);
356
656
  if (!definition) {
357
657
  if (element.fallback !== void 0) {
358
- const text = bind(element.fallback, local);
359
- if (typeof text !== "string") fail("INVALID_ELEMENT_PROPS", "Fallback must resolve to text.");
658
+ const text2 = bind(element.fallback, local);
659
+ if (typeof text2 !== "string") fail("INVALID_ELEMENT_PROPS", "Fallback must resolve to text.");
360
660
  diagnostics.push({ code: "ELEMENT_FALLBACK", severity: "warning", phase: "prepare", message: `Using authored fallback for ${element.type}.`, elementId: element.id });
361
- return { ...node, type: "narrative", fallbackUsed: true, props: { text } };
661
+ return { ...node, type: "narrative", fallbackUsed: true, props: { text: text2 } };
362
662
  }
363
663
  fail("UNKNOWN_COMPONENT", `Component "${element.type}" is not registered.`, { elementId: element.id });
364
664
  }
@@ -366,20 +666,87 @@ async function prepareReportModel(template, dataSets, variables, options, regist
366
666
  let p;
367
667
  try {
368
668
  const skip = /* @__PURE__ */ new Set(["children"]);
369
- if (element.type === "table") skip.add("columns");
669
+ if (element.type === "table") {
670
+ skip.add("columns");
671
+ skip.add("dataColumns");
672
+ }
673
+ if (element.type === "reportic.grid.v1") {
674
+ skip.add("columns");
675
+ skip.add("rows");
676
+ }
370
677
  if (element.type === "chart") {
371
678
  skip.add("x");
372
679
  skip.add("series");
373
680
  }
374
- if (element.type === "list") skip.add("text");
681
+ if (element.type === "list") {
682
+ skip.add("text");
683
+ skip.add("lead");
684
+ }
685
+ if (element.type === "reportic.masthead.v1") {
686
+ skip.add("marking");
687
+ skip.add("kicker");
688
+ skip.add("lead");
689
+ }
690
+ if (element.type === "reportic.heading.v1" || element.type === "reportic.footer.v1" || element.type === "narrative" && Array.isArray(element.props.text)) skip.add("text");
691
+ if (element.type === "reportic.figure.v1") skip.add("source");
692
+ if (element.type === "reportic.columns.v1") skip.add("columns");
375
693
  p = bind(element.props, local, skip);
694
+ const resolveColumn = (c) => {
695
+ const column = bind(c, local, /* @__PURE__ */ new Set(["value", "tone"]));
696
+ if (Array.isArray(column.label)) column.label = column.label.map((x) => String(x ?? "")).join("");
697
+ return column;
698
+ };
699
+ const primitives = (a) => a.every((x) => ["string", "number", "boolean"].includes(typeof x));
700
+ const cellFor = (column, scope) => Array.isArray(column.value) && !(column.kind === "list" && primitives(column.value)) ? composeCell(column, scope) : kindCell(column, bind(column.value, scope), column.tone === void 0 ? void 0 : bind(column.tone, scope));
701
+ if (element.type === "narrative" && Array.isArray(element.props.text)) p.text = textOf(element.props.text, local, "Narrative text");
702
+ if (element.type === "reportic.heading.v1") {
703
+ p.text = textOf(element.props.text, local, "A heading");
704
+ if (!p.text.trim()) fail("INVALID_ELEMENT_PROPS", "A heading needs text.");
705
+ }
706
+ if (element.type === "reportic.footer.v1") p.text = textOf(element.props.text, local, "A footer");
707
+ if (element.type === "reportic.figure.v1" && element.props.source !== void 0) {
708
+ const source = optionalBind(element.props.source, local, element);
709
+ if (source === void 0 || source === null || source === "") delete p.source;
710
+ else p.source = source;
711
+ }
712
+ if (element.type === "reportic.grid.v1") {
713
+ if (!Array.isArray(p.columns) || !p.columns.length || p.columns.length > 50 || !Array.isArray(p.rows) || p.rows.length > 500) fail("INVALID_ELEMENT_PROPS", "A grid needs at least one column and a list of rows.");
714
+ p.columns = p.columns.map(resolveColumn);
715
+ p.cells = p.rows.map((r) => {
716
+ if (!Array.isArray(r) || r.length !== p.columns.length) fail("INVALID_ELEMENT_PROPS", "A grid row needs exactly one cell for each column.");
717
+ return r.map((spec, i) => cellFor({ ...p.columns[i], ...isRecord(spec) && own(spec, "value") && !own(spec, "$bind") ? spec : { value: spec } }, local));
718
+ });
719
+ p.rows = p.cells;
720
+ }
376
721
  if (element.type === "table") {
377
722
  if (!Array.isArray(p.rows) || !Array.isArray(p.columns) || !p.columns.length || p.rows.some((r) => !isRecord(r))) fail("INVALID_ELEMENT_PROPS", "A table requires record rows and at least one column.");
378
- p.columns = p.columns.map((c) => ({ ...bind(c, local, /* @__PURE__ */ new Set(["value"])) }));
379
- p.cells = p.rows.map((r) => p.columns.map((c) => {
380
- const raw = bind(c.value, { ...local, row: r });
381
- return { raw, text: display(raw, c.format) };
382
- }));
723
+ p.columns = p.columns.map(resolveColumn);
724
+ let extra = [];
725
+ if (p.dataColumns !== void 0) {
726
+ const dc = p.dataColumns;
727
+ if (!isRecord(dc) || dc.labels === void 0 || dc.values === void 0) fail("INVALID_ELEMENT_PROPS", "dataColumns needs labels and values.");
728
+ const labels = bind(dc.labels, local);
729
+ if (!Array.isArray(labels) || labels.length > 100 || labels.some((l) => !["string", "number"].includes(typeof l))) fail("INVALID_ELEMENT_PROPS", "dataColumns.labels must be a list of at most 100 labels.");
730
+ extra = labels.map((l) => ({ label: String(l), value: null, ...dc.align ? { align: dc.align } : {}, ...dc.format ? { format: dc.format } : {}, ...dc.kind ? { kind: dc.kind } : {} }));
731
+ }
732
+ const fixed = p.columns;
733
+ const cellsFor = (r, total) => {
734
+ const scope = { ...local, row: r };
735
+ const cells = fixed.map((c) => cellFor(c, scope));
736
+ if (extra.length) {
737
+ const values = bind(p.dataColumns.values, scope);
738
+ if (!Array.isArray(values)) fail("INVALID_ELEMENT_PROPS", "dataColumns.values must resolve to a list for every row.");
739
+ extra.forEach((c, i) => cells.push(kindCell(c, values[i] ?? null)));
740
+ }
741
+ return total ? cells.map((cell) => ({ ...cell, total: true })) : cells;
742
+ };
743
+ p.cells = p.rows.map((r) => cellsFor(r, false));
744
+ if (p.total !== void 0 && p.total !== null) {
745
+ if (!isRecord(p.total)) fail("INVALID_ELEMENT_PROPS", "A table total must be a record.");
746
+ if (p.rows.length) p.cells.push(cellsFor(p.total, true));
747
+ }
748
+ if (p.total === null) delete p.total;
749
+ p.columns = [...fixed, ...extra];
383
750
  } else if (element.type === "chart") {
384
751
  if (!Array.isArray(p.rows) || p.rows.some((r) => !isRecord(r)) || !isRecord(p.x) || !Array.isArray(p.series) || !p.series.length) fail("INVALID_ELEMENT_PROPS", "A chart requires record rows, an x axis, and numeric series.");
385
752
  p.x = bind(p.x, local, /* @__PURE__ */ new Set(["value"]));
@@ -399,16 +766,41 @@ async function prepareReportModel(template, dataSets, variables, options, regist
399
766
  });
400
767
  } else if (element.type === "list") {
401
768
  if (!Array.isArray(p.rows)) fail("INVALID_ELEMENT_PROPS", "List rows must be an array.");
402
- p.items = p.rows.map((r) => {
403
- const text = bind(p.text, { ...local, row: r });
404
- if (typeof text !== "string") fail("INVALID_ELEMENT_PROPS", "List item text must be a string.");
405
- return text;
769
+ p.items = p.rows.map((r) => textOf(p.text, { ...local, row: r }, "List item text"));
770
+ if (p.lead !== void 0) p.leads = p.rows.map((r) => {
771
+ const scope = { ...local, row: r };
772
+ if (Array.isArray(p.lead)) return composeCell({ value: p.lead }, scope).text;
773
+ const lead = optionalBind(p.lead, scope);
774
+ return lead === void 0 || lead === null ? "" : String(display(lead));
406
775
  });
407
776
  } else if (element.type === "metrics") {
408
- if (Array.isArray(p.items)) p.items = p.items.map((item) => ({ ...item, display: display(item.value, item.format) }));
777
+ const key = p.comparisonKey;
778
+ if (key !== void 0 && (typeof key !== "string" || !/^[A-Za-z0-9_-]+$/.test(key) || badKeys.has(key))) fail("INVALID_ELEMENT_PROPS", "comparisonKey must name a field of each item.");
779
+ if (Array.isArray(p.items)) p.items = p.items.map((item) => {
780
+ if (!isRecord(item)) return item;
781
+ const tile = { ...item, display: display(item.value, item.format) };
782
+ if (key !== void 0 && tile.comparison === void 0 && own(item, key) && typeof item[key] === "string" && item[key]) tile.comparison = item[key];
783
+ if (key !== void 0 && (tile.tone === "" || tile.tone === null)) delete tile.tone;
784
+ return tile;
785
+ });
786
+ } else if (element.type === "reportic.masthead.v1") {
787
+ for (const key of ["marking", "kicker", "lead"]) if (p[key] !== void 0) {
788
+ const v = optionalBind(p[key], local, element);
789
+ if (v === void 0 || v === null || v === "") delete p[key];
790
+ else p[key] = String(display(v));
791
+ }
792
+ if (Array.isArray(p.byline)) p.byline = p.byline.map((item) => ({ ...item, display: item.value === null || item.value === void 0 || item.value === "" ? "" : display(item.value, item.format ?? (item.kind === "date" ? "date" : void 0)) })).filter((item) => item.display !== "");
409
793
  }
410
794
  const errors = definition.validate(p);
411
795
  if (errors.length) fail("INVALID_ELEMENT_PROPS", `${definition.title}: ${errors.join("; ")}`);
796
+ if (element.type === "reportic.footer.v1" && p.logo !== void 0) {
797
+ const ref = assetReference(p.logo, p.logoAlt ?? "Logo", options, assets);
798
+ p = { ...p, logoImage: { src: ref.src, alt: ref.alt }, ...ref.remote ? { remote: true } : {} };
799
+ }
800
+ if (element.type === "reportic.figure.v1") {
801
+ const figure = parseFigure(p.spec);
802
+ p = { ...p, figure, alt: p.alt ?? figureAlt(figure), table: figureTable(figure, locale) };
803
+ }
412
804
  if (element.type === "image") p = { ...p, ...assetReference(p.src, p.alt, options, assets) };
413
805
  if (element.type === "diagram") {
414
806
  if (p.source !== void 0 && (p.model !== void 0 || p.adapter !== void 0)) fail("INVALID_DIAGRAM", "Use source or model and adapter, not both.");
@@ -430,13 +822,30 @@ async function prepareReportModel(template, dataSets, variables, options, regist
430
822
  if (element.type === "sources") {
431
823
  for (const source of Object.values(p.records)) if (source.url) safeUrl(source.url);
432
824
  }
433
- if (element.type === "group") node.children = p.children.map((e) => normalize(e, row));
434
- if (element.type === "repeat") node.children = p.rows.flatMap((r) => p.children.map((e) => normalize(e, r)));
825
+ if (element.type === "reportic.columns.v1") {
826
+ const count = p.count;
827
+ if (![2, 3, 4].includes(count) || !Array.isArray(p.columns) || p.columns.length !== count || p.columns.some((col) => !Array.isArray(col))) fail("INVALID_ELEMENT_PROPS", "Columns need two, three, or four stacks.");
828
+ const spans = [];
829
+ node.children = p.columns.flatMap((col) => {
830
+ const kids = col.map((e) => normalize(e, row)).filter(Boolean);
831
+ spans.push(kids.length);
832
+ return kids;
833
+ });
834
+ p.spans = spans;
835
+ }
836
+ if (element.type === "group") node.children = p.children.map((e) => normalize(e, row)).filter(Boolean);
837
+ if (element.type === "repeat") node.children = p.rows.flatMap((r) => p.children.map((e) => normalize(e, r))).filter(Boolean);
435
838
  if (definition.normalize) {
436
839
  const normalized = definition.normalize(p);
437
840
  node.type = normalized.type;
438
841
  p = normalized.props;
439
842
  }
843
+ if (node.type === "kit-chart" && p.empty && element.fallback !== void 0) {
844
+ const text2 = bind(element.fallback, local);
845
+ if (typeof text2 !== "string") fail("INVALID_ELEMENT_PROPS", "Fallback must resolve to text.");
846
+ diagnostics.push({ code: "ELEMENT_FALLBACK", severity: "warning", phase: "prepare", message: `Using authored fallback for ${element.type}.`, elementId: element.id });
847
+ return { ...node, type: "narrative", fallbackUsed: true, props: { text: text2 } };
848
+ }
440
849
  node.props = p;
441
850
  delete node.props.children;
442
851
  return node;
@@ -444,10 +853,10 @@ async function prepareReportModel(template, dataSets, variables, options, regist
444
853
  if (e instanceof ReporticError) {
445
854
  const missing = e.diagnostics.every((d) => d.code === "MISSING_REQUIRED_INPUT");
446
855
  if (missing && element.fallback !== void 0) {
447
- const text = bind(element.fallback, local);
448
- if (typeof text !== "string") throw e;
856
+ const text2 = bind(element.fallback, local);
857
+ if (typeof text2 !== "string") throw e;
449
858
  diagnostics.push({ code: "OPTIONAL_VALUE_FALLBACK", severity: "warning", phase: "prepare", message: "Using authored fallback for a missing value.", elementId: element.id });
450
- return { ...node, type: "narrative", fallbackUsed: true, props: { text } };
859
+ return { ...node, type: "narrative", fallbackUsed: true, props: { text: text2 } };
451
860
  }
452
861
  throw new ReporticError(e.diagnostics.map((d) => ({ ...d, elementId: element.id, line: element.line, occurrenceId: node.occurrenceId })));
453
862
  }
@@ -509,7 +918,8 @@ async function prepareReportModel(template, dataSets, variables, options, regist
509
918
  const element = parsed.elements.get(match[1]);
510
919
  if (element) {
511
920
  try {
512
- nodes.push(normalize(element));
921
+ const node = normalize(element);
922
+ if (node) nodes.push(node);
513
923
  } catch (e) {
514
924
  if (e instanceof ReporticError) diagnostics.push(...e.diagnostics);
515
925
  else throw e;
@@ -518,7 +928,7 @@ async function prepareReportModel(template, dataSets, variables, options, regist
518
928
  end = pattern.lastIndex;
519
929
  }
520
930
  addMarkdown(output.slice(end));
521
- const flat = (list) => list.flatMap((n) => [n, ...flat(n.children ?? [])]);
931
+ const flat = (list2) => list2.flatMap((n) => [n, ...flat(n.children ?? [])]);
522
932
  const visible = flat(nodes);
523
933
  const sources = visible.filter((n) => n.type === "sources");
524
934
  const citations = /* @__PURE__ */ new Map();
@@ -535,11 +945,26 @@ async function prepareReportModel(template, dataSets, variables, options, regist
535
945
  });
536
946
  }
537
947
  if (sources[0]) sources[0].props.citations = [...citations].map(([id, number]) => ({ id, number, ...records[id] }));
948
+ const headings = [];
949
+ for (const n of visible) {
950
+ if (n.type === "markdown" && n.props.token?.type === "heading" && n.props.token.text) headings.push({ text: String(n.props.token.text), level: Number(n.props.token.depth) || 1, anchor: n.occurrenceId });
951
+ else if ((n.type === "masthead" || n.type === "cover") && n.props.title) headings.push({ text: String(n.props.title), level: 1, anchor: n.occurrenceId });
952
+ else if (n.type === "group" && typeof n.props.heading === "string" && n.props.heading) headings.push({ text: n.props.heading, level: 2, anchor: n.occurrenceId });
953
+ }
954
+ for (const n of visible) if (n.type === "toc") n.props.items = headings.filter((h) => h.anchor !== n.occurrenceId);
538
955
  if (assets.reduce((n, a) => n + a.bytes.length, 0) > limit.totalAssetBytes) fail("LIMIT_EXCEEDED", "Combined assets exceed the configured limit.");
539
956
  if (diagnostics.some((d) => d.severity === "error")) throw new ReporticError(diagnostics);
540
957
  let title = parsed.metadata.id ?? "Untitled report";
541
958
  const heading = visible.find((n) => n.type === "markdown" && n.props.token.type === "heading" && n.props.token.depth === 1);
542
959
  if (heading) title = heading.props.token.text;
960
+ else {
961
+ const masthead = visible.find((n) => n.type === "masthead");
962
+ if (masthead) title = masthead.props.title;
963
+ else {
964
+ const cover = visible.find((n) => n.type === "cover");
965
+ if (cover) title = cover.props.title;
966
+ }
967
+ }
543
968
  for (const asset of assets) {
544
969
  const snapshot = new Uint8Array(asset.bytes);
545
970
  Object.defineProperty(asset, "bytes", { enumerable: true, get: () => new Uint8Array(snapshot) });
@@ -573,13 +998,13 @@ function preflightReport(report, options) {
573
998
  import { lexer as lexer3 } from "marked";
574
999
  import { parseDocument as parseDocument2, isMap as isMap2, isAlias as isAlias2, visit as visit2, stringify } from "yaml";
575
1000
  var unsafe = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
576
- var sourceFingerprint = (text) => {
1001
+ var sourceFingerprint = (text2) => {
577
1002
  let hash = 2166136261;
578
- for (let i = 0; i < text.length; i++) {
579
- hash ^= text.charCodeAt(i);
1003
+ for (let i = 0; i < text2.length; i++) {
1004
+ hash ^= text2.charCodeAt(i);
580
1005
  hash = Math.imul(hash, 16777619);
581
1006
  }
582
- return `${text.length.toString(36)}-${(hash >>> 0).toString(16)}`;
1007
+ return `${text2.length.toString(36)}-${(hash >>> 0).toString(16)}`;
583
1008
  };
584
1009
  function sourceRange(source, from, to) {
585
1010
  const before = source.slice(0, from);
@@ -589,8 +1014,8 @@ function sourceRange(source, from, to) {
589
1014
  function validBindingPath(path) {
590
1015
  return /^(dataSets|variables|row)(?:\.[A-Za-z0-9_-]+)*$/.test(path) && !path.split(".").some((p) => unsafe.has(p));
591
1016
  }
592
- function parseAuthoringYaml(text) {
593
- const doc = parseDocument2(text, { uniqueKeys: true, keepSourceTokens: true });
1017
+ function parseAuthoringYaml(text2) {
1018
+ const doc = parseDocument2(text2, { uniqueKeys: true, keepSourceTokens: true });
594
1019
  if (doc.errors.length) throw new Error(doc.errors[0].message.split("\n")[0]);
595
1020
  visit2(doc, (_key, node) => {
596
1021
  if (isAlias2(node) || node && typeof node === "object" && ("anchor" in node && node.anchor || "tag" in node && node.tag)) throw new Error("Aliases, anchors, and custom tags are not permitted.");
@@ -651,9 +1076,9 @@ function indexSource(source) {
651
1076
  if (Object.hasOwn(v, "$bind")) {
652
1077
  const n = doc.getIn([...path, ...keys, "$bind"], true);
653
1078
  const r = n?.range ? sourceRange(source, contentStart + n.range[0], contentStart + n.range[1]) : entryRange;
654
- const binding = { path: v.$bind, slot, range: r, elementId: entry.id };
1079
+ const binding = { path: v.$bind, slot, range: r, elementId: entry.id, ...slot === "when" || Object.hasOwn(v, "default") ? { guarded: true } : {} };
655
1080
  entry.bindings.push(binding);
656
- if (typeof v.$bind !== "string" || !validBindingPath(v.$bind) || Object.keys(v).length !== 1) index.diagnostics.push({ code: "INVALID_BINDING_PATH", severity: "error", message: "Use an exact dataSets, variables, or row path without prototype keys.", elementId: entry.id, slot, range: r });
1081
+ if (typeof v.$bind !== "string" || !validBindingPath(v.$bind) || Object.keys(v).some((k) => k !== "$bind" && k !== "default")) index.diagnostics.push({ code: "INVALID_BINDING_PATH", severity: "error", message: "Use an exact dataSets, variables, or row path without prototype keys.", elementId: entry.id, slot, range: r });
657
1082
  return;
658
1083
  }
659
1084
  if (Array.isArray(v)) v.forEach((child, i) => bindings(child, [...keys, i], slot + "[" + i + "]"));
@@ -663,6 +1088,7 @@ function indexSource(source) {
663
1088
  }
664
1089
  };
665
1090
  bindings(element.props, ["props"], "props");
1091
+ if (element.when && typeof element.when === "object") bindings(element.when, ["when"], "when");
666
1092
  if (Array.isArray(element.props?.children)) element.props.children.forEach((child, i) => walk(child, [...path, "props", "children", i], entry.id));
667
1093
  };
668
1094
  walk(value, []);
@@ -681,15 +1107,15 @@ function indexSource(source) {
681
1107
  return index;
682
1108
  }
683
1109
  var serialize = (value) => JSON.stringify(value);
684
- function patchYaml(text, path, value) {
685
- const doc = parseAuthoringYaml(text), existing = doc.getIn(path, true);
1110
+ function patchYaml(text2, path, value) {
1111
+ const doc = parseAuthoringYaml(text2), existing = doc.getIn(path, true);
686
1112
  if (!doc.contents) {
687
1113
  let result = value;
688
1114
  for (let i = path.length - 1; i >= 0; i--) result = { [path[i]]: result };
689
1115
  return stringify(result);
690
1116
  }
691
1117
  if (existing?.range) {
692
- return text.slice(0, existing.range[0]) + serialize(value) + text.slice(existing.range[1]);
1118
+ return text2.slice(0, existing.range[0]) + serialize(value) + text2.slice(existing.range[1]);
693
1119
  }
694
1120
  const parent = doc.getIn(path.slice(0, -1), true);
695
1121
  const key = path[path.length - 1];
@@ -697,23 +1123,23 @@ function patchYaml(text, path, value) {
697
1123
  const pairs = parent.items;
698
1124
  const last = pairs[pairs.length - 1];
699
1125
  const firstKey = pairs[0]?.key;
700
- const indent = firstKey?.range ? firstKey.range[0] - (text.lastIndexOf("\n", firstKey.range[0] - 1) + 1) : Math.max(0, (path.length - 1) * 2);
1126
+ const indent = firstKey?.range ? firstKey.range[0] - (text2.lastIndexOf("\n", firstKey.range[0] - 1) + 1) : Math.max(0, (path.length - 1) * 2);
701
1127
  if (parent.flow) {
702
1128
  const at = parent.range[1] - 1;
703
- return text.slice(0, at) + (pairs.length ? ", " : "") + JSON.stringify(key) + ": " + serialize(value) + text.slice(at);
1129
+ return text2.slice(0, at) + (pairs.length ? ", " : "") + JSON.stringify(key) + ": " + serialize(value) + text2.slice(at);
704
1130
  }
705
1131
  const lastValue = last?.value;
706
1132
  const lastKey = last?.key;
707
- const end = lastValue?.range?.[2] ?? lastValue?.range?.[1] ?? lastKey?.range?.[2] ?? parent.range?.[1] ?? text.length;
708
- const prefix = text.slice(0, end);
709
- const suffix = text.slice(end);
1133
+ const end = lastValue?.range?.[2] ?? lastValue?.range?.[1] ?? lastKey?.range?.[2] ?? parent.range?.[1] ?? text2.length;
1134
+ const prefix = text2.slice(0, end);
1135
+ const suffix = text2.slice(end);
710
1136
  return prefix + (prefix.endsWith("\n") ? "" : "\n") + " ".repeat(indent) + key + ": " + serialize(value) + "\n" + suffix;
711
1137
  }
712
1138
  let ancestor = path.length - 1;
713
1139
  while (ancestor > 0 && !doc.getIn(path.slice(0, ancestor), true)) ancestor--;
714
1140
  let nested = value;
715
1141
  for (let i = path.length - 1; i > ancestor; i--) nested = { [path[i]]: nested };
716
- return patchYaml(text, path.slice(0, ancestor + 1), nested);
1142
+ return patchYaml(text2, path.slice(0, ancestor + 1), nested);
717
1143
  }
718
1144
  function editElementProperty(source, elementId, path, value, expectedFingerprint = sourceFingerprint(source)) {
719
1145
  if (sourceFingerprint(source) !== expectedFingerprint) throw new Error("STALE_SOURCE: The source changed. Reload this form before applying it.");
@@ -728,14 +1154,14 @@ function declareDataset(source, alias, schemaRef, required) {
728
1154
  if (!/^[A-Za-z_][\w]*$/.test(alias) || unsafe.has(alias)) throw new Error("Use an identifier-style local dataset name.");
729
1155
  const index = indexSource(source);
730
1156
  if (index.metadataRange) {
731
- let text = source.slice(index.metadataRange.from, index.metadataRange.to);
732
- if (!index.metadata.reportic) text = patchYaml(text, ["reportic"], "0.2");
1157
+ let text2 = source.slice(index.metadataRange.from, index.metadataRange.to);
1158
+ if (!index.metadata.reportic) text2 = patchYaml(text2, ["reportic"], "0.2");
733
1159
  const existing = index.metadata.dataSets?.[alias];
734
1160
  if (existing && typeof existing === "object") {
735
- text = patchYaml(text, ["dataSets", alias, "schema"], schemaRef);
736
- if (required !== void 0) text = patchYaml(text, ["dataSets", alias, "required"], required);
737
- } else text = patchYaml(text, ["dataSets", alias], { schema: schemaRef, ...required === false ? { required: false } : {} });
738
- return source.slice(0, index.metadataRange.from) + text + source.slice(index.metadataRange.to);
1161
+ text2 = patchYaml(text2, ["dataSets", alias, "schema"], schemaRef);
1162
+ if (required !== void 0) text2 = patchYaml(text2, ["dataSets", alias, "required"], required);
1163
+ } else text2 = patchYaml(text2, ["dataSets", alias], { schema: schemaRef, ...required === false ? { required: false } : {} });
1164
+ return source.slice(0, index.metadataRange.from) + text2 + source.slice(index.metadataRange.to);
739
1165
  }
740
1166
  return "---\n" + stringify({ reportic: "0.2", dataSets: { [alias]: { schema: schemaRef, ...required === false ? { required: false } : {} } } }) + "---\n\n" + source;
741
1167
  }
@@ -759,8 +1185,8 @@ function replaceElement(source, elementId, value, expectedFingerprint = sourceFi
759
1185
  const content = patchYaml(source.slice(block.contentRange.from, block.contentRange.to), entry.yamlPath, value);
760
1186
  return source.slice(0, block.contentRange.from) + content + source.slice(block.contentRange.to);
761
1187
  }
762
- const text = stringify(value, { lineWidth: 100 }).trimEnd();
763
- return source.slice(0, entry.contentRange.from) + text + source.slice(entry.contentRange.to);
1188
+ const text2 = stringify(value, { lineWidth: 100 }).trimEnd();
1189
+ return source.slice(0, entry.contentRange.from) + text2 + source.slice(entry.contentRange.to);
764
1190
  }
765
1191
  function insertElement(source, value, at = source.length) {
766
1192
  const originalLength = source.length;
@@ -821,7 +1247,9 @@ function inferBindingSlots(schema, rowScopes = []) {
821
1247
  function getBindingSlot(definition, path, props) {
822
1248
  const slot = (definition.bindingSlots ?? inferBindingSlots(definition.schema, definition.rowScopes)).find((s) => s.path === path.replace(/\[\d+\]/g, "[]"));
823
1249
  if (slot?.expectedBy && props) {
824
- const key = slot.expectedBy.property.replace(/^props\./, "").split(".").reduce((value, key2) => value?.[key2], props);
1250
+ const indexes = [...path.matchAll(/\[(\d+)\]/g)].map((m) => m[1]);
1251
+ let next = 0;
1252
+ const key = slot.expectedBy.property.replace(/^props\./, "").replace(/\[\]/g, () => "." + (indexes[next++] ?? "0")).split(".").filter(Boolean).reduce((value, key2) => value?.[key2], props);
825
1253
  return { ...slot, expected: slot.expectedBy.values[String(key)] ?? slot.expected };
826
1254
  }
827
1255
  return slot;
@@ -845,6 +1273,11 @@ export {
845
1273
  escapeHtml,
846
1274
  escapeMd,
847
1275
  fail,
1276
+ figureAlt,
1277
+ figureKinds,
1278
+ figureSpec,
1279
+ figureTable,
1280
+ figureTones,
848
1281
  flowchartSource,
849
1282
  formatValue,
850
1283
  getBindingSlot,
@@ -857,6 +1290,7 @@ export {
857
1290
  officeColor,
858
1291
  own,
859
1292
  parseAuthoringYaml,
1293
+ parseFigure,
860
1294
  parseTemplate,
861
1295
  preflightReport,
862
1296
  prepareReportModel,
@@ -866,10 +1300,13 @@ export {
866
1300
  safeRelative,
867
1301
  safeUrl,
868
1302
  safeYaml,
1303
+ semanticColors,
869
1304
  semanticRule,
870
1305
  sourceFingerprint,
871
1306
  sourceRange,
1307
+ statusTone,
872
1308
  themeTokens,
1309
+ tones,
873
1310
  validBindingPath,
874
1311
  validateStyles,
875
1312
  walkNodes