diff --git a/README.md b/README.md index fc02d31..1692372 100644 --- a/README.md +++ b/README.md @@ -1,26 +1,41 @@ # Reportist -Reportist validates and renders structured YAML or JSON reports with Typst. -It has no dependency on the Beffroi integration repository or any specific plugin. +Reportist validates and renders structured YAML or JSON reports with Typst. It +also accepts a Typst plugin that maps another JSON document into the same +Reportist v1 report dictionary. Every PDF uses `templates/report.typ`. ## Render a report ```bash ./render.sh examples/example-report.yaml --output report.pdf +./render.sh examples/diagnostic-style.yaml --output custom-diagnostic.pdf ``` -## Render through a plugin +The second example uses the same sections, finding lists, progress bar, and +tables available to plugins. Existing output requires `--force`. + +## Render JSON through a plugin ```bash -./render-plugin.sh /path/to/plugin /path/to/input output.pdf [plugin options] +./render.sh input.json --plugin /path/to/plugin \ + --plugin-input author='Reviewer Name' --output output.pdf \ + --emit-ir output.report.json ``` -A plugin directory contains `plugin.json` (name, version, input, output) and -an executable `prepare.sh`. Reportist invokes `prepare.sh INPUT STAGE -REPORTIST_ROOT [plugin options]`. The plugin writes a validated Reportist v1 -`report.json` and any relative assets into `STAGE`. Reportist then uses its -normal renderer and schema validation. Plugins own domain interpretation; -Reportist owns document presentation. Plugins can be kept in any repository. +The plugin directory contains `plugin.json`, `transform.typ`, and optionally a +`runtime/` directory. `plugin.json` declares `interface_version: 1`, `name`, +`input`, `output`, and `transform: "transform.typ"`. Typst imports +`transform.typ` and calls `transform(data)` with the parsed input JSON. The +function returns a Reportist v1 dictionary. `--plugin-input KEY=VALUE` is +available to the transform as `sys.inputs.at("plugin-KEY")`. + +Reportist writes the returned dictionary as validated JSON in a private stage, +then uses its normal renderer. `--emit-ir` keeps a copy of this intermediate +report JSON and a referenced branding logo, if any, so the JSON can be +rendered again. A plugin can include Typst-readable resources and images in +`runtime/`; its returned report can reference images there with a path beginning +`plugin/runtime/`. The same report validation applies to authored and plugin +outputs. Reportist has no dependency on any specific plugin. ## Batch and validation @@ -30,5 +45,4 @@ bash tools/validate.sh examples/example-report.yaml bash tools/validate-all.sh /path/to/reports ``` -See [`docs/report-contract.md`](docs/report-contract.md) and -[`docs/development.md`](docs/development.md). +See [`docs/report-contract.md`](docs/report-contract.md) for all report fields. diff --git a/docs/development.md b/docs/development.md index ca1e50c..3a2d25e 100644 --- a/docs/development.md +++ b/docs/development.md @@ -18,7 +18,8 @@ text checks. Those checks are skipped when Poppler is unavailable. The suite covers JSON and YAML input, contract failures, optional fields, replaceable branding, asset safety, overwrite behavior, pagination, extracted -content, and rendering from a standalone component copy. +content, generic diagnostic-style blocks, Typst plugin conversion, emitted report +JSON, and rendering from a standalone component copy. ## Contract maintenance diff --git a/docs/report-contract.md b/docs/report-contract.md index 8dbcb3f..5fb9ff0 100644 --- a/docs/report-contract.md +++ b/docs/report-contract.md @@ -83,6 +83,12 @@ are rejected, including legacy `diagnostics`, top-level `organization` and named | `code` | `text` | — | | `subsection` | `title`, nonempty nested `content` | — | | `card` | `title`, nonempty nested `content` | `tone` (severity token) | +| `table` | 2–5 `columns`, nonempty `rows` of matching string cells | `note` | +| `progress` | `label`, numeric `value` from 0 to 100 | `tone`, `note` | +| `finding_list` | `items` of finding objects | `compact` boolean | +| `references` | nonempty `items` with `label` and HTTPS `url` | — | + +`sections` and `appendices` also accept `page_break_before: true`. A `finding_list` renders the same generic finding cards used by top-level `findings`; if a section has a finding list, the automatic top-level findings section is omitted. Unknown or misspelled blocks fail validation. Text and commands are data, not code for the validator to execute. The renderer must preserve that boundary. @@ -116,7 +122,7 @@ blue-green palette. No organisation, author, logo, or incident name is hard-code Logo and artifact paths use relative forward-slash paths without parent/dot segments, backslashes, drive letters, or control characters. The renderer resolves -assets relative to the input report directory; missing branding means neutral +assets relative to the input report directory. For a Typst plugin, files under its `runtime/` directory are staged at `plugin/runtime/` and can be referenced there; missing branding means neutral defaults with no logo, and a missing specified asset is an error. It accepts one report and one explicit output path. @@ -146,3 +152,12 @@ See [JSON Schema validation](https://json-schema.org/draft/2020-12/json-schema-v and [jsonschema format checking](https://python-jsonschema.readthedocs.io/en/stable/validate/) for the underlying validation rules. Local semantic checks additionally reject repeated finding IDs. + +## Plugin intermediate report + +`render.sh INPUT --plugin DIR` requires a JSON input. Typst imports +`DIR/transform.typ` and calls `transform(data)` with the parsed JSON. The +returned dictionary is the same Reportist v1 contract as an authored report. +Reportist validates and renders it with the normal template; `--emit-ir PATH` +writes the intermediate JSON for inspection. The plugin manifest and runtime +layout are described in [`../README.md`](../README.md). diff --git a/examples/diagnostic-style.yaml b/examples/diagnostic-style.yaml new file mode 100644 index 0000000..accbf4c --- /dev/null +++ b/examples/diagnostic-style.yaml @@ -0,0 +1,55 @@ +schema_version: 1 +title: Example system assessment +subtitle: Example device · Full collection +report_type: technical +status: draft +metadata: + Date: '2026-09-16' + Author: Example Author + Device: EXAMPLE-PC +summary: A custom authored report using the same blocks as the diagnostic plugin. +metrics: + - {label: Critical, value: 1, tone: critical} + - {label: Warnings, value: 2, tone: warning} + - {label: RAM maximum, value: 32 GB} + - {label: Confidence, value: 85%, tone: success} +sections: + - title: Executive overview + content: + - {type: callout, title: Overall assessment, kind: warning, text: Review the observed warnings.} + - {type: progress, label: Observed signal score, value: 74, tone: warning, note: This score summarizes observed signals only.} + - type: finding_list + compact: true + items: + - {title: Example storage warning, severity: warning, confidence: 85, assessment: Review the storage evidence.} + - title: Findings requiring attention + page_break_before: true + content: + - type: finding_list + items: + - title: Example storage warning + severity: warning + confidence: 85 + evidence: The sample event records an I/O error. + assessment: Review storage and controller logs. + resolution_steps: + - Preserve the logs. + - Check the disk and controller path. + - title: Technical evidence + page_break_before: true + content: + - type: table + columns: [System property, Observed value] + rows: + - [Computer, EXAMPLE-PC] + - [Operating system, Example OS] + - [Memory, 32 GB] + - type: table + columns: [Collector section, Status, Records] + rows: + - [Storage, Complete, '2'] + - [Event log, Partial, '12'] + note: Counts reflect the captured data. + - type: references + items: + - {label: Example source guidance, url: 'https://example.com/guidance'} diff --git a/render-plugin.sh b/render-plugin.sh deleted file mode 100755 index c2eece5..0000000 --- a/render-plugin.sh +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env bash -# A plugin converts its input to a validated Reportist v1 report in a private stage. -set -euo pipefail -root=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P) -usage(){ echo "Usage: $0 PLUGIN_DIR INPUT OUTPUT.pdf [plugin options]" >&2; exit 2; } -[[ $# -ge 3 ]] || usage -plugin=$(realpath "$1"); input=$(realpath "$2"); output=$3; shift 3 -[[ -d "$plugin" && -x "$plugin/prepare.sh" && -f "$plugin/plugin.json" ]] || { echo "Invalid Reportist plugin: $plugin" >&2; exit 1; } -[[ -f "$input" ]] || { echo "Input does not exist: $input" >&2; exit 1; } -[[ ! -e "$output" ]] || { echo "Output exists: $output" >&2; exit 1; } -stage=$(mktemp -d "${TMPDIR:-/tmp}/reportist-plugin.XXXXXXXX") -trap 'rm -rf "$stage"' EXIT -"$plugin/prepare.sh" "$input" "$stage" "$root" "$@" -[[ -f "$stage/report.json" ]] || { echo "Plugin did not produce report.json" >&2; exit 1; } -"$root/render.sh" "$stage/report.json" --output "$output" diff --git a/render.sh b/render.sh index 05fd02b..a72141d 100755 --- a/render.sh +++ b/render.sh @@ -1,59 +1,102 @@ #!/usr/bin/env bash -# Render a Reportist v1 YAML/JSON document without a Python runtime. +# Validate and render a Reportist report or a Typst-transformed plugin input. set -euo pipefail - root=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P) -usage() { echo "Usage: $0 INPUT [--output PDF] [--typst COMMAND] [--force]" >&2; exit 2; } +usage() { echo "Usage: $0 INPUT [--plugin DIR] [--plugin-input KEY=VALUE] [--output PDF] [--emit-ir JSON] [--typst COMMAND] [--force]" >&2; exit 2; } fail() { echo "error: $*" >&2; exit 1; } - input=${1:-}; [[ -n "$input" ]] || usage; shift -output= typst_command=typst force=false +output= ir_output= typst_command=typst force=false plugin= plugin_inputs=() while (($#)); do case $1 in - --output) (($# >= 2)) || usage; output=$2; shift 2 ;; - --typst) (($# >= 2)) || usage; typst_command=$2; shift 2 ;; - --force) force=true; shift ;; - *) usage ;; + --output|--emit-ir|--typst|--plugin) (($# >= 2)) || usage + case $1 in --output) output=$2;; --emit-ir) ir_output=$2;; --typst) typst_command=$2;; --plugin) plugin=$2;; esac; shift 2;; + --plugin-input) (($# >= 2)) || usage + [[ $2 =~ ^[a-z][a-z0-9-]*= ]] || fail "plugin input must be KEY=VALUE with a lowercase key" + plugin_inputs+=(--input "plugin-$2"); shift 2;; + --force) force=true; shift;; + *) usage;; esac done -case $input in *.json) format=json;; *.yaml|*.yml) format=yaml;; *) fail "expected a .yaml, .yml, or .json report";; esac +case $input in *.json) format=json;; *.yaml|*.yml) format=yaml;; *) fail "expected a .yaml, .yml, or .json input";; esac +[[ -z "$plugin" || "$format" == json ]] || fail "plugin input must be JSON" +[[ -n "$plugin" || ${#plugin_inputs[@]} -eq 0 ]] || fail "--plugin-input requires --plugin" command -v "$typst_command" >/dev/null 2>&1 || fail "Typst executable not found: $typst_command" -input=$(realpath "$input") -[[ -f "$input" ]] || fail "$input: report does not exist" -"$root/tools/validate.sh" "$input" >/dev/null || fail "invalid report" +input=$(realpath "$input"); [[ -f "$input" ]] || fail "$input: input does not exist" if [[ -z "$output" ]]; then output=${input%.*}.pdf; fi output_parent=$(dirname "$output"); mkdir -p "$output_parent"; output=$(cd "$output_parent" && pwd -P)/$(basename "$output") [[ "$input" != "$output" ]] || fail "input and output paths must differ" -if [[ -e "$output" && "$force" == false ]]; then fail "$output: output exists; use --force to replace it"; fi - +[[ ! -e "$output" || "$force" == true ]] || fail "$output: output exists; use --force to replace it" +if [[ -n "$ir_output" ]]; then + ir_parent=$(dirname "$ir_output"); mkdir -p "$ir_parent"; ir_output=$(cd "$ir_parent" && pwd -P)/$(basename "$ir_output") + [[ "$ir_output" != "$input" && "$ir_output" != "$output" ]] || fail "IR output must differ from input and PDF" + [[ ! -e "$ir_output" || "$force" == true ]] || fail "$ir_output: output exists; use --force to replace it" +fi stage=$(mktemp -d "${TMPDIR:-/tmp}/reportist.XXXXXXXX") trap 'rm -rf "$stage"' EXIT -cp -- "$input" "$stage/report.$format" cp -- "$root/templates/report.typ" "$stage/report.typ" cp -- "$root/tools/report-value.typ" "$stage/report-value.typ" - +if [[ -n "$plugin" ]]; then + plugin=$(realpath "$plugin") + [[ -f "$plugin/plugin.json" && -f "$plugin/transform.typ" ]] || fail "invalid plugin directory: $plugin" + mkdir -p "$stage/plugin" + cp -- "$plugin/transform.typ" "$stage/plugin/transform.typ" + cp -- "$plugin/plugin.json" "$stage/plugin/plugin.json" + cp -- "$root/tools/plugin-manifest.typ" "$stage/plugin-manifest.typ" + "$typst_command" eval --root "$stage" --in "$stage/plugin-manifest.typ" 'query().first().value' >/dev/null || fail "invalid plugin manifest" + if [[ -d "$plugin/runtime" ]]; then + [[ -z $(find "$plugin/runtime" -type l -print -quit) ]] || fail "plugin runtime contains a symlink" + cp -R -- "$plugin/runtime" "$stage/plugin/runtime" + fi + cp -- "$root/tools/resolve-plugin.typ" "$stage/resolve-plugin.typ" + cp -- "$input" "$stage/source.json" + "$typst_command" eval --root "$stage" --input source=source.json "${plugin_inputs[@]}" \ + --in "$stage/resolve-plugin.typ" 'query().first().value' >"$stage/report.json" || fail "plugin transform failed" + "$root/tools/validate.sh" "$stage/report.json" >/dev/null || fail "plugin returned an invalid report" + format=json +else + "$root/tools/validate.sh" "$input" >/dev/null || fail "invalid report" + cp -- "$input" "$stage/report.$format" +fi +logo_path= logo=$( - "$typst_command" query --root "$stage" --input "report=report.$format" --input "format=$format" \ - "$stage/report-value.typ" '' --field value --one 2>/dev/null + "$typst_command" eval --root "$stage" --input "report=report.$format" --input "format=$format" \ + --in "$stage/report-value.typ" 'query().first().value' 2>/dev/null ) || fail "unable to read report input" if [[ "$logo" != null ]]; then logo=${logo#\"}; logo=${logo%\"} + logo_path=$logo [[ -n "$logo" && "$logo" != /* && "$logo" != *\\* && "$logo" != *$'\n'* ]] || fail "/branding/logo: invalid relative asset path" IFS=/ read -r -a parts <<<"$logo" - source_dir=$(dirname "$input"); cursor=$source_dir + source_dir=$(dirname "$input"); cursor=$source_dir; stage_cursor=$stage for part in "${parts[@]}"; do [[ -n "$part" && "$part" != . && "$part" != .. ]] || fail "/branding/logo: invalid relative asset path" - cursor=$cursor/$part - [[ ! -L "$cursor" ]] || fail "/branding/logo: symlinks are not accepted: $logo" + cursor=$cursor/$part; stage_cursor=$stage_cursor/$part + [[ ! -L "$cursor" && ! -L "$stage_cursor" ]] || fail "/branding/logo: symlinks are not accepted: $logo" done - [[ -f "$cursor" ]] || fail "/branding/logo: asset does not exist: $logo" - mkdir -p "$stage/$(dirname "$logo")" - cp -- "$cursor" "$stage/$logo" + if [[ ! -f "$stage_cursor" ]]; then + [[ -f "$cursor" ]] || fail "/branding/logo: asset does not exist: $logo" + mkdir -p "$stage/$(dirname "$logo")"; cp -- "$cursor" "$stage/$logo" + fi fi - if ! "$typst_command" compile --root "$stage" --input "report=report.$format" --input "format=$format" \ - "$stage/report.typ" "$stage/report.pdf"; then - fail "invalid report or Typst rendering failed" + "$stage/report.typ" "$stage/report.pdf"; then fail "invalid report or Typst rendering failed"; fi +if [[ -n "$ir_output" ]]; then + if [[ -n "$logo_path" ]]; then + ir_asset="$ir_parent/$logo_path" + if [[ -e "$ir_asset" ]]; then + if ! cmp -s -- "$stage/$logo_path" "$ir_asset"; then + [[ "$force" == true ]] || fail "$ir_asset: IR asset differs; use --force to replace it" + cp -- "$stage/$logo_path" "$ir_asset" + fi + else + mkdir -p "$(dirname "$ir_asset")" + cp -- "$stage/$logo_path" "$ir_asset" + fi + fi + if [[ "$format" == json ]]; then cp -- "$stage/report.json" "$ir_output"; else + "$typst_command" eval --root "$stage" --input "report=report.$format" --input "format=$format" \ + --in "$stage/report-value.typ" 'query().first().value' >"$ir_output" + fi fi -if [[ "$force" == true ]]; then mv -f -- "$stage/report.pdf" "$output"; else mv -- "$stage/report.pdf" "$output"; fi +mv -f -- "$stage/report.pdf" "$output" echo "Rendered PDF: $output" diff --git a/schema/report.schema.json b/schema/report.schema.json index e9fa5d5..2da6415 100644 --- a/schema/report.schema.json +++ b/schema/report.schema.json @@ -411,6 +411,9 @@ "$ref": "#/$defs/block" }, "minItems": 1 + }, + "page_break_before": { + "type": "boolean" } }, "required": [ @@ -583,6 +586,56 @@ "content" ], "additionalProperties": false + }, + { + "type": "object", + "properties": { + "type": {"const": "table"}, + "columns": {"type": "array", "items": {"type": "string", "pattern": "\\S"}, "minItems": 2, "maxItems": 5}, + "rows": {"type": "array", "items": {"type": "array", "items": {"type": "string"}, "minItems": 2, "maxItems": 5}, "minItems": 1}, + "note": {"type": "string", "pattern": "\\S"} + }, + "required": ["type", "columns", "rows"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "type": {"const": "progress"}, + "label": {"type": "string", "pattern": "\\S"}, + "value": {"type": "number", "minimum": 0, "maximum": 100}, + "tone": {"enum": ["info", "low", "medium", "high", "critical", "warning", "ok", "success", "unanalysed"]}, + "note": {"type": "string", "pattern": "\\S"} + }, + "required": ["type", "label", "value"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "type": {"const": "finding_list"}, + "items": {"type": "array", "items": {"$ref": "#/properties/findings/items"}}, + "compact": {"type": "boolean"} + }, + "required": ["type", "items"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "type": {"const": "references"}, + "items": {"type": "array", "minItems": 1, "items": { + "type": "object", + "properties": { + "label": {"type": "string", "pattern": "\\S"}, + "url": {"type": "string", "pattern": "^https://"} + }, + "required": ["label", "url"], + "additionalProperties": false + }} + }, + "required": ["type", "items"], + "additionalProperties": false } ] } diff --git a/templates/report.typ b/templates/report.typ index 377ed2f..329e376 100644 --- a/templates/report.typ +++ b/templates/report.typ @@ -51,6 +51,24 @@ #if title != none { text(weight: "bold", fill: severity-color(kind))[#as-text(title)]; parbreak() } #body ] +#let render-finding(finding, compact: false) = block(width: 100%, inset: 8pt, below: 6pt, breakable: true, + stroke: (left: 2pt + severity-color(get(finding, "severity", default: "info")), + top: 0.5pt + line-color, right: 0.5pt + line-color, bottom: 0.5pt + line-color), radius: 2pt)[ + #grid(columns: (1fr, auto, auto, auto), gutter: 5pt, align: (left, center, center, center), + text(weight: "bold")[#as-text(finding.title)], + if "severity" in finding { badge(finding.severity) } else { [] }, + if "status" in finding { badge(finding.status) } else { [] }, + if "confidence" in finding { badge(str(finding.confidence) + "% confidence") } else { [] }) + #if not compact and "evidence" in finding { parbreak(); text(size: 8pt, weight: "bold", fill: muted)[EVIDENCE]; parbreak(); as-text(finding.evidence) } + #if "assessment" in finding { parbreak(); text(size: 8pt, weight: "bold", fill: muted)[ASSESSMENT]; parbreak(); as-text(finding.assessment) } + #if not compact and "resolution_steps" in finding and finding.resolution_steps.len() > 0 { + parbreak(); text(size: 8pt, weight: "bold", fill: muted)[RESOLUTION PATH] + parbreak(); enum(..finding.resolution_steps.map(step => [#as-text(step)])) + } + #if not compact and "reference_url" in finding { + parbreak(); link(finding.reference_url)[#as-text(get(finding, "reference_label", default: "Reference guidance")) ↗] + } +] #let render-block(item) = { let kind = get(item, "type", default: "text") if kind == "text" { inline-code(get(item, "text", default: "")) } @@ -78,6 +96,33 @@ #for child in item.content { render-block(child); v(3pt) } ] } + else if kind == "table" { + table(columns: (1fr,) * item.columns.len(), inset: 4pt, stroke: 0.4pt + line-color, + fill: (x, y) => if y == 0 or calc.rem(y, 2) == 0 { soft } else { none }, + table.header(..item.columns.map(value => [#text(weight: "bold")[#as-text(value)]])), + ..item.rows.map(row => row.map(value => [#as-text(value)])).flatten()) + if "note" in item { v(2pt); text(size: 7.5pt, fill: muted)[#as-text(item.note)] } + } + else if kind == "progress" { + let tone = severity-color(get(item, "tone", default: "info")) + block(width: 100%, inset: 8pt, fill: soft, stroke: 0.5pt + line-color)[ + #grid(columns: (1fr, auto), text(weight: "bold")[#as-text(item.label)], + text(weight: "bold", fill: tone)[#as-text(item.value)%]) + #v(4pt) + #block(width: 100%, height: 6pt, radius: 3pt, fill: line-color)[ + #block(width: item.value * 1%, height: 100%, radius: 3pt, fill: tone) + ] + #if "note" in item { v(3pt); text(size: 7.5pt, fill: muted)[#as-text(item.note)] } + ] + } + else if kind == "finding_list" { + for finding in item.items { render-finding(finding, compact: get(item, "compact", default: false)) } + } + else if kind == "references" { + for reference in item.items { + block(below: 3pt)[#link(reference.url)[#as-text(reference.label) ↗]] + } + } } #let logo = get(branding, "logo", default: none) #let organization = get(branding, "organization", default: "Report") @@ -136,27 +181,17 @@ [#as-text(get(entry, "notes", default: ""))], )).flatten()) } -#if "findings" in report and report.findings.len() > 0 { +#let has-finding-list(item) = { + let direct = get(item, "type", default: "") == "finding_list" + direct or get(item, "content", default: ()).any(child => has-finding-list(child)) +} +#let sections-own-findings = get(report, "sections", default: ()).any(section => section.content.any(has-finding-list)) +#if not sections-own-findings and "findings" in report and report.findings.len() > 0 { heading("Findings") - for finding in report.findings { block(width: 100%, inset: 8pt, below: 6pt, breakable: false, - stroke: 0.5pt + line-color, radius: 2pt)[ - #grid(columns: (1fr, auto, auto, auto), gutter: 5pt, align: (left, center, center, center), - text(weight: "bold")[#as-text(finding.title)], - if "severity" in finding { badge(finding.severity) } else { [] }, - if "status" in finding { badge(finding.status) } else { [] }, - if "confidence" in finding { badge(str(finding.confidence) + "% confidence") } else { [] }) - #if "evidence" in finding { parbreak(); text(size: 8pt, weight: "bold", fill: muted)[EVIDENCE]; parbreak(); as-text(finding.evidence) } - #if "assessment" in finding { parbreak(); text(size: 8pt, weight: "bold", fill: muted)[ASSESSMENT]; parbreak(); as-text(finding.assessment) } - #if "resolution_steps" in finding and finding.resolution_steps.len() > 0 { - parbreak(); text(size: 8pt, weight: "bold", fill: muted)[RESOLUTION PATH] - parbreak(); enum(..finding.resolution_steps.map(step => [#as-text(step)])) - } - #if "reference_url" in finding { - parbreak(); link(finding.reference_url)[#as-text(get(finding, "reference_label", default: "Reference guidance")) ↗] - } - ] } + for finding in report.findings { render-finding(finding) } } #for section in get(report, "sections", default: ()) { + if get(section, "page_break_before", default: false) { pagebreak(weak: true) } heading(section.title) for item in section.content { render-block(item); v(4pt) } } diff --git a/tests/test_contract.py b/tests/test_contract.py index 8c42259..764cc8b 100644 --- a/tests/test_contract.py +++ b/tests/test_contract.py @@ -89,6 +89,22 @@ class ReportContractTests(unittest.TestCase): card["content"] = [] self.assertTrue(validation.validate_document(self.document)) + def test_diagnostic_layout_blocks_share_the_report_contract(self): + self.document["sections"] = [{"title": "Overview", "page_break_before": True, + "content": [ + {"type": "progress", "label": "Signal score", "value": 73, + "tone": "warning"}, + {"type": "table", "columns": ["Property", "Value"], + "rows": [["Memory", "32 GB"]]}, + {"type": "finding_list", "compact": True, + "items": [{"title": "Example finding", "severity": "warning"}]}, + {"type": "references", "items": [ + {"label": "Source", "url": "https://example.com/source"}]}, + ]}] + self.assertEqual(validation.validate_document(self.document), []) + self.document["sections"][0]["content"][1]["rows"] = [["Memory"]] + self.assertTrue(validation.validate_document(self.document)) + def test_bad_branding_and_references(self): for path in ("../secret.svg", "/logo.svg", "C:\\logo.svg", "assets/../logo.svg", "logo.svg\n"): with self.subTest(path=path): diff --git a/tests/test_render.py b/tests/test_render.py index 31869ff..3a01e24 100644 --- a/tests/test_render.py +++ b/tests/test_render.py @@ -41,6 +41,45 @@ class RenderTests(unittest.TestCase): renderer.render(ROOT / "examples" / "minimal-report.json", output, TYPST) self.assert_pdf(output) + def test_typst_plugin_produces_valid_report_ir(self): + plugin = self.work / "plugin" + plugin.mkdir() + (plugin / "plugin.json").write_text(json.dumps({ + "name": "example", "interface_version": 1, "input": "example-v1", + "output": "reportist-v1", "transform": "transform.typ", + }), encoding="utf-8") + (plugin / "transform.typ").write_text( + '#let transform(data) = (schema_version: 1, title: data.title, ' + 'metadata: (Date: "2026-09-16", Author: sys.inputs.at("plugin-author")), ' + 'sections: ((title: "Plugin section", content: ' + '((type: "text", text: data.message),)),))\n', encoding="utf-8") + source = self.work / "source.json" + source.write_text(json.dumps({"title": "Converted input", "message": "Mapped by Typst"}), encoding="utf-8") + output = self.work / "plugin.pdf" + ir = self.work / "plugin.ir.json" + result = subprocess.run([ + "bash", str(ROOT / "render.sh"), str(source), "--plugin", str(plugin), + "--plugin-input", "author=Plugin Test", "--output", str(output), + "--emit-ir", str(ir), + ], text=True, capture_output=True) + self.assertEqual(result.returncode, 0, result.stderr) + self.assert_pdf(output) + document = json.loads(ir.read_text(encoding="utf-8")) + self.assertEqual(document["title"], "Converted input") + self.assertEqual(document["metadata"]["Author"], "Plugin Test") + self.assertEqual(document["sections"][0]["content"][0]["text"], "Mapped by Typst") + + def test_authored_report_uses_diagnostic_layout_blocks(self): + output = self.work / "diagnostic-style.pdf" + renderer.render(ROOT / "examples" / "diagnostic-style.yaml", output, TYPST) + self.assert_pdf(output) + if PDFTOTEXT: + extracted = subprocess.run([PDFTOTEXT, str(output), "-"], + text=True, capture_output=True, check=True).stdout + for phrase in ("Executive overview", "Observed signal score", + "Findings requiring attention", "Technical evidence"): + self.assertIn(phrase, extracted) + def test_invalid_input_leaves_no_pdf(self): report = self.work / "invalid.json" report.write_text(json.dumps({"schema_version": 2}), encoding="utf-8") diff --git a/tools/plugin-manifest.typ b/tools/plugin-manifest.typ new file mode 100644 index 0000000..97690ee --- /dev/null +++ b/tools/plugin-manifest.typ @@ -0,0 +1,7 @@ +#let manifest = json("plugin/plugin.json") +#assert(type(manifest) == dictionary, message: "plugin manifest must be an object") +#assert(manifest.at("interface_version", default: none) == 1, message: "unsupported plugin interface") +#assert(type(manifest.at("name", default: none)) == str and manifest.name.match(regex("^[a-z][a-z0-9-]*$")) != none, message: "invalid plugin name") +#assert(manifest.at("transform", default: none) == "transform.typ", message: "unsupported plugin transform") +#assert(type(manifest.at("input", default: none)) == str and type(manifest.at("output", default: none)) == str, message: "plugin input/output must be named") +#metadata(true) diff --git a/tools/resolve-plugin.typ b/tools/resolve-plugin.typ new file mode 100644 index 0000000..0865614 --- /dev/null +++ b/tools/resolve-plugin.typ @@ -0,0 +1,5 @@ +#import "plugin/transform.typ": transform +#let input = json(sys.inputs.at("source")) +#let report = transform(input) +#assert(type(report) == dictionary, message: "plugin must return a Reportist report dictionary") +#metadata(report) diff --git a/tools/validate.typ b/tools/validate.typ index 1125c1d..ca82e99 100644 --- a/tools/validate.typ +++ b/tools/validate.typ @@ -12,6 +12,13 @@ value.split("/").all(part => part not in ("", ".", "..")) ) #let values = ("info", "low", "medium", "high", "critical", "warning", "ok", "success", "unanalysed") +#let validate-finding(finding) = { + assert(keys-allowed(finding, ("id", "title", "severity", "status", "evidence", "assessment", "evidence_refs", "confidence", "resolution_steps", "reference_url", "reference_label")) and nonempty(finding.at("title", default: none)), message: "invalid finding") + if "confidence" in finding { assert(type(finding.confidence) in (int, float) and finding.confidence >= 0 and finding.confidence <= 100, message: "invalid finding confidence") } + if "resolution_steps" in finding { assert(type(finding.resolution_steps) == array and finding.resolution_steps.all(nonempty), message: "invalid resolution steps") } + if "reference_url" in finding { assert(type(finding.reference_url) == str and finding.reference_url.starts-with("https://"), message: "invalid reference URL") } + if "reference_label" in finding { assert(nonempty(finding.reference_label), message: "invalid reference label") } +} #let validate-block(item) = { assert(type(item) == dictionary, message: "content block must be an object") @@ -31,10 +38,30 @@ type(content) == array and content.len() > 0, message: "invalid card/subsection block") if kind == "card" { assert(item.at("tone", default: "info") in values, message: "invalid card tone") } for child in content { validate-block(child) } + } else if kind == "table" { + let columns = item.at("columns", default: none) + let rows = item.at("rows", default: none) + assert(keys-allowed(item, ("type", "columns", "rows", "note")) and type(columns) == array and columns.len() >= 2 and columns.len() <= 5 and columns.all(nonempty), message: "invalid table columns") + assert(type(rows) == array and rows.len() > 0 and rows.all(row => type(row) == array and row.len() == columns.len() and row.all(value => type(value) == str)), message: "invalid table rows") + if "note" in item { assert(nonempty(item.note), message: "invalid table note") } + } else if kind == "progress" { + assert(keys-allowed(item, ("type", "label", "value", "tone", "note")) and nonempty(item.at("label", default: none)) and type(item.at("value", default: none)) in (int, float) and item.value >= 0 and item.value <= 100 and item.at("tone", default: "info") in values, message: "invalid progress block") + if "note" in item { assert(nonempty(item.note), message: "invalid progress note") } + } else if kind == "finding_list" { + let items = item.at("items", default: none) + assert(keys-allowed(item, ("type", "items", "compact")) and type(items) == array and type(item.at("compact", default: false)) == bool, message: "invalid finding list") + for finding in items { validate-finding(finding) } + } else if kind == "references" { + let items = item.at("items", default: none) + assert(keys-allowed(item, ("type", "items")) and type(items) == array and items.len() > 0, message: "invalid references block") + for reference in items { + assert(keys-allowed(reference, ("label", "url")) and nonempty(reference.at("label", default: none)) and + type(reference.at("url", default: none)) == str and reference.url.starts-with("https://"), message: "invalid reference") + } } else { assert(false, message: "unsupported content block") } } #let validate-section(section) = { - assert(keys-allowed(section, ("title", "content")) and nonempty(section.at("title", default: none)), message: "invalid section") + assert(keys-allowed(section, ("title", "content", "page_break_before")) and nonempty(section.at("title", default: none)) and type(section.at("page_break_before", default: false)) == bool, message: "invalid section") let content = section.at("content", default: none) assert(type(content) == array and content.len() > 0, message: "section content must not be empty") for item in content { validate-block(item) } @@ -76,12 +103,6 @@ #let findings = report.at("findings", default: ()) #let finding-ids = findings.filter(item => "id" in item).map(item => item.id) #assert(finding-ids.dedup().len() == finding-ids.len(), message: "duplicate finding ID") -#for finding in findings { - assert(keys-allowed(finding, ("id", "title", "severity", "status", "evidence", "assessment", "evidence_refs", "confidence", "resolution_steps", "reference_url", "reference_label")) and nonempty(finding.at("title", default: none)), message: "invalid finding") - if "confidence" in finding { assert(type(finding.confidence) in (int, float) and finding.confidence >= 0 and finding.confidence <= 100, message: "invalid finding confidence") } - if "resolution_steps" in finding { assert(type(finding.resolution_steps) == array and finding.resolution_steps.all(nonempty), message: "invalid resolution steps") } - if "reference_url" in finding { assert(type(finding.reference_url) == str and finding.reference_url.starts-with("https://"), message: "invalid reference URL") } - if "reference_label" in finding { assert(nonempty(finding.reference_label), message: "invalid reference label") } -} +#for finding in findings { validate-finding(finding) } #metadata(true)