@graphein/node
v0.21.0
Published
Headless Graphein rendering for Node — render any ChartSpec to a PNG buffer with a RenderReport, no browser required.
Maintainers
Readme
@graphein/node
Headless Graphein rendering for Node — turn any
ChartSpecinto a PNG buffer plus a machine-readable render report, with no browser and no JSDOM.
This is the server-side half of Graphein's agent feedback loop. The same model build and mark renderers that run in the browser run here, so an agent (or a CI job, or a report emailer) can generate → validate → render → critique a chart entirely on the server.
npm install @graphein/node grapheinimport { renderChart } from '@graphein/node';
import { writeFileSync } from 'node:fs';
const { png, report } = renderChart(
{
type: 'combo',
title: 'Revenue vs. conversion',
data: [
{ month: 'Jan', revenue: 120, conversion: 0.041 },
{ month: 'Feb', revenue: 145, conversion: 0.046 },
{ month: 'Mar', revenue: 138, conversion: 0.044 },
],
encoding: { x: { field: 'month' } },
layers: [
{ mark: 'bar', encoding: { y: { field: 'revenue', title: 'Revenue ($k)' } } },
{ mark: 'line', axis: 'right', encoding: { y: { field: 'conversion', format: '.1%' } } },
],
},
{ width: 900, height: 480, dpr: 2 },
);
if (!report.ok) console.warn('chart has issues:', report.diagnostics);
writeFileSync('chart.png', png);Why it exists
Text in Graphein (axis labels, titles, legends, annotations) is normally laid out as a
crisp HTML overlay. Headless rendering can't use the DOM, so @graphein/node drives
core's dependency-free renderToContext — which paints that same text onto the canvas
at the exact computed positions — and wires it to @napi-rs/canvas
for fast, native PNG output. The core graphein engine stays zero-dependency; the
native bits live only in this package.
API
renderChart(spec, options?) → { png, report, spec, quality?, warnings?, fontRegistrations, width, height }
Renders spec and returns the PNG bytes and the RenderReport
— ok, mark/series/color counts, and any clipping / overlap / contrast diagnostics. The
report is computed from the resolved model (no pixel read-back), so it's identical to
instance.report() in the browser. This is what lets an agent verify a chart without a
vision model.
Accepts ChartSpec or DashboardSpec (AnySpec), with no dashboard casts.
The default remains one direct render, with no authoring/data repairs.
Overloads preserve chart-only RenderReport typing and return
DashboardRenderReport for a dashboard. Use NodeRenderResult<AnyRenderReport>
when storing results from either kind; plain NodeRenderResult retains its
chart-only default type.
Opt in with { quality:true } to reuse core draft()'s presentation controller:
at most three total whole-visual render attempts, including the initial draw
and any restoration. Only eligible unspecified presentation defaults can change;
explicit palettes/domains/themes and input data stay unchanged. spec, report,
and png correspond to the selected final frame, and PNG encoding happens once,
after selection. quality contains renderPasses, selectedPass, iterations,
retained applied actions, rejected actions with reasons, and stopReason.
Unresolved warnings remain in report; a quality loop is not a guarantee of perfect
output. NodeRenderError.result exposes core validation/failure history if no final
frame is available; no partial or mismatched PNG is returned.
Candidate and rollback paints replay from the original canvas pixels, so transparent
or translucent backgrounds never accumulate discarded attempts. This restoration
does not add chart-render passes.
Opted-in results also retain validation warnings, including exact data evidence
and requiresDecision. These advisories are separate from the render report:
presentation improvements do not resolve data/meaning choices or explicit theme
fallback decisions. The direct default path does not validate and omits warnings.
renderToPNG(spec, options?) → Buffer
Convenience wrapper that returns only the PNG bytes.
Options
| Option | Default | Description |
| -------- | ------- | --------------------------------------------------------------------- |
| width | 800 | Logical width in CSS pixels. |
| height | 500 | Logical height in CSS pixels. |
| dpr | 2 | Device pixel ratio — the PNG is rasterized at width*dpr × height*dpr. |
| fonts | — | { path, family }[] font files to register before rendering. |
| quality | false | true or {maxPasses?:1\|2\|3}. Initial/candidate/restoration share one budget. Budgets below 3 only evaluate the initial render because rollback capacity is reserved. |
width and height must be finite numbers from 1 to 8192 CSS pixels. dpr
must be finite from 0.25 to 4, and the final rasterized canvas
(round(width*dpr) × round(height*dpr)) is capped at 67,108,864 pixels.
Invalid or unsafe sizes throw a RangeError before any canvas is allocated.
Core still records backing-store evidence on reports; if a composing target has
to lower the effective DPR for safety, report.evidence.backingStore contains the
requested/effective DPR and raster size and the report includes a
backing-store-clamped info diagnostic.
Fonts
@napi-rs/canvas uses system fonts by default. For pixel-perfect parity with the browser
(Graphein's default family is Inter), register a font file:
renderChart(spec, {
fonts: [{ path: 'C:\\fonts\\Inter-Variable.ttf', family: 'Inter' }],
});GlobalFonts is re-exported if you prefer to register fonts once at startup.
Unreadable/unregisterable files do not crash an otherwise valid render:
fontRegistrations contains {path,family,registered,message?} for each request,
and failures add a font-fallback warning to the report and quality history.
Successful registration establishes that the file loaded, not that every glyph or
requested font style is available.
Supported charts
Every type. Cartesian + custom canvas charts: line, area, bar, scatter, box, pie, heatmap, sankey, choropleth, combo, histogram, funnel, treemap, gauge, bullet, calendarHeatmap, waterfall, slope, dumbbell — plus the formerly DOM-only kpi, table, matrix, slicers (dropdown/list/search/range/dateRange) and dashboard, which render a static canvas snapshot. So the whole catalog rasterizes + validates headlessly.
License
MIT
