@graphein/node 0.18.0 → 0.20.0

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/README.md CHANGED
@@ -49,7 +49,7 @@ native bits live only in this package.
49
49
 
50
50
  ## API
51
51
 
52
- ### `renderChart(spec, options?) → { png, report, width, height }`
52
+ ### `renderChart(spec, options?) → { png, report, spec, quality?, warnings?, fontRegistrations, width, height }`
53
53
 
54
54
  Renders `spec` and returns the PNG bytes **and** the [`RenderReport`](https://github.com/spatney/graphein/blob/main/docs/spec-reference.md#render-report)
55
55
  — `ok`, mark/series/color counts, and any clipping / overlap / contrast diagnostics. The
@@ -57,6 +57,31 @@ report is computed from the resolved model (no pixel read-back), so it's identic
57
57
  `instance.report()` in the browser. This is what lets an agent verify a chart **without a
58
58
  vision model**.
59
59
 
60
+ Accepts `ChartSpec` **or** `DashboardSpec` (`AnySpec`), with no dashboard casts.
61
+ The default remains one direct render, with no authoring/data repairs.
62
+ Overloads preserve chart-only `RenderReport` typing and return
63
+ `DashboardRenderReport` for a dashboard. Use `NodeRenderResult<AnyRenderReport>`
64
+ when storing results from either kind; plain `NodeRenderResult` retains its
65
+ chart-only default type.
66
+
67
+ Opt in with `{ quality:true }` to reuse core `draft()`'s presentation controller:
68
+ at most **three total whole-visual render attempts**, including the initial draw
69
+ and any restoration. Only eligible unspecified presentation defaults can change;
70
+ explicit palettes/domains/themes and input data stay unchanged. `spec`, `report`,
71
+ and `png` correspond to the selected final frame, and PNG encoding happens once,
72
+ after selection. `quality` contains `renderPasses`, `selectedPass`, `iterations`,
73
+ retained `applied` actions, `rejected` actions with reasons, and `stopReason`.
74
+ Unresolved warnings remain in `report`; a quality loop is not a guarantee of perfect
75
+ output. `NodeRenderError.result` exposes core validation/failure history if no final
76
+ frame is available; no partial or mismatched PNG is returned.
77
+ Candidate and rollback paints replay from the original canvas pixels, so transparent
78
+ or translucent backgrounds never accumulate discarded attempts. This restoration
79
+ does not add chart-render passes.
80
+ Opted-in results also retain validation `warnings`, including exact data evidence
81
+ and `requiresDecision`. These advisories are separate from the render report:
82
+ presentation improvements do not resolve data/meaning choices or explicit theme
83
+ fallback decisions. The direct default path does not validate and omits `warnings`.
84
+
60
85
  ### `renderToPNG(spec, options?) → Buffer`
61
86
 
62
87
  Convenience wrapper that returns only the PNG bytes.
@@ -69,6 +94,16 @@ Convenience wrapper that returns only the PNG bytes.
69
94
  | `height` | `500` | Logical height in CSS pixels. |
70
95
  | `dpr` | `2` | Device pixel ratio — the PNG is rasterized at `width*dpr × height*dpr`. |
71
96
  | `fonts` | — | `{ path, family }[]` font files to register before rendering. |
97
+ | `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. |
98
+
99
+ `width` and `height` must be finite numbers from 1 to 8192 CSS pixels. `dpr`
100
+ must be finite from 0.25 to 4, and the final rasterized canvas
101
+ (`round(width*dpr) × round(height*dpr)`) is capped at 67,108,864 pixels.
102
+ Invalid or unsafe sizes throw a `RangeError` before any canvas is allocated.
103
+ Core still records backing-store evidence on reports; if a composing target has
104
+ to lower the effective DPR for safety, `report.evidence.backingStore` contains the
105
+ requested/effective DPR and raster size and the report includes a
106
+ `backing-store-clamped` info diagnostic.
72
107
 
73
108
  ### Fonts
74
109
 
@@ -77,11 +112,16 @@ Convenience wrapper that returns only the PNG bytes.
77
112
 
78
113
  ```ts
79
114
  renderChart(spec, {
80
- fonts: [{ path: '/fonts/Inter-Variable.ttf', family: 'Inter' }],
115
+ fonts: [{ path: 'C:\\fonts\\Inter-Variable.ttf', family: 'Inter' }],
81
116
  });
82
117
  ```
83
118
 
84
119
  `GlobalFonts` is re-exported if you prefer to register fonts once at startup.
120
+ Unreadable/unregisterable files do not crash an otherwise valid render:
121
+ `fontRegistrations` contains `{path,family,registered,message?}` for each request,
122
+ and failures add a `font-fallback` warning to the report and quality history.
123
+ Successful registration establishes that the file loaded, not that every glyph or
124
+ requested font style is available.
85
125
 
86
126
  ## Supported charts
87
127
 
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  export { GlobalFonts } from '@napi-rs/canvas';
2
- import { RenderReport, ChartSpec } from 'graphein';
3
- export { ChartSpec, RenderReport } from 'graphein';
2
+ import { DraftResult, AnyRenderReport, RenderReport, AnySpec, QualityResult, ValidationError, QualityOptions, DashboardSpec, DashboardRenderReport, ChartSpec } from 'graphein';
3
+ export { AnyRenderReport, AnySpec, ChartSpec, DashboardRenderReport, DashboardSpec, QualityOptions, QualityResult, RenderReport, ValidationError } from 'graphein';
4
4
 
5
5
  /**
6
6
  * `@graphein/node` — headless Graphein rendering for Node.
@@ -45,9 +45,18 @@ interface RenderImageOptions {
45
45
  dpr?: number;
46
46
  /** Extra fonts to register before rendering. */
47
47
  fonts?: FontFace[];
48
+ /** Opt in to core's presentation-default loop (at most three whole-visual render attempts). */
49
+ quality?: boolean | QualityOptions;
50
+ }
51
+ /** Registration evidence for a caller-supplied font; failure is non-fatal. */
52
+ interface FontRegistration {
53
+ path: string;
54
+ family: string;
55
+ registered: boolean;
56
+ message?: string;
48
57
  }
49
58
  /** The result of a headless render: the PNG bytes plus the render report. */
50
- interface NodeRenderResult {
59
+ interface NodeRenderResult<R extends AnyRenderReport = RenderReport> {
51
60
  /** PNG-encoded image bytes. */
52
61
  png: Buffer;
53
62
  /**
@@ -55,12 +64,49 @@ interface NodeRenderResult {
55
64
  * browser — `ok`, mark/series/color counts, and any clipping / overlap /
56
65
  * contrast warnings. Lets an agent critique the chart with no vision model.
57
66
  */
58
- report: RenderReport;
67
+ report: R;
59
68
  /** Pixel width of the PNG (`width * dpr`, rounded). */
60
69
  width: number;
61
70
  /** Pixel height of the PNG (`height * dpr`, rounded). */
62
71
  height: number;
72
+ /** Effective spec corresponding to the final PNG and report. Input data is never transformed by quality mode. */
73
+ spec: AnySpec;
74
+ /** Core quality-loop evidence, present only when opted in. */
75
+ quality?: QualityResult;
76
+ /** Validation advisories retained when quality mode validates the spec; absent on the direct default path. */
77
+ warnings?: ValidationError[];
78
+ /** Outcome of each explicitly requested font registration. */
79
+ fontRegistrations: FontRegistration[];
80
+ }
81
+ /** Opt-in validation/rendering failed, so no potentially mismatched PNG was encoded. */
82
+ declare class NodeRenderError extends Error {
83
+ readonly result: DraftResult;
84
+ constructor(result: DraftResult);
85
+ }
86
+ /** Hard bounds that keep headless renders from creating invalid or enormous canvases. */
87
+ declare const RENDER_LIMITS: Readonly<{
88
+ minWidth: 1;
89
+ maxWidth: 8192;
90
+ minHeight: 1;
91
+ maxHeight: 8192;
92
+ minDpr: 0.25;
93
+ maxDpr: 4;
94
+ maxPixels: 67108864;
95
+ }>;
96
+ interface ResolvedRenderImageOptions {
97
+ /** Logical width in CSS pixels. */
98
+ width: number;
99
+ /** Logical height in CSS pixels. */
100
+ height: number;
101
+ /** Device pixel ratio. */
102
+ dpr: number;
103
+ /** Rounded raster width in physical pixels. */
104
+ pixelWidth: number;
105
+ /** Rounded raster height in physical pixels. */
106
+ pixelHeight: number;
63
107
  }
108
+ /** Validate and resolve render sizing options before allocating a canvas. */
109
+ declare function validateRenderImageOptions(options?: RenderImageOptions): ResolvedRenderImageOptions;
64
110
  /**
65
111
  * Render `spec` to a PNG buffer and its {@link RenderReport}, entirely in Node.
66
112
  *
@@ -68,12 +114,14 @@ interface NodeRenderResult {
68
114
  * sankey, choropleth, combo, histogram, funnel, and the formerly DOM-only kpi,
69
115
  * table, matrix, slicers and dashboard (painted as a static canvas snapshot).
70
116
  */
117
+ declare function renderChart(spec: DashboardSpec, options?: RenderImageOptions): NodeRenderResult<DashboardRenderReport>;
71
118
  declare function renderChart(spec: ChartSpec, options?: RenderImageOptions): NodeRenderResult;
119
+ declare function renderChart(spec: AnySpec, options?: RenderImageOptions): NodeRenderResult<AnyRenderReport>;
72
120
  /**
73
121
  * Convenience wrapper around {@link renderChart} that returns only the PNG bytes.
74
122
  */
75
- declare function renderToPNG(spec: ChartSpec, options?: RenderImageOptions): Buffer;
123
+ declare function renderToPNG(spec: AnySpec, options?: RenderImageOptions): Buffer;
76
124
 
77
- declare const VERSION = "0.7.0";
125
+ declare const VERSION = "0.20.0";
78
126
 
79
- export { type FontFace, type NodeRenderResult, type RenderImageOptions, VERSION, renderChart, renderToPNG };
127
+ export { type FontFace, type FontRegistration, NodeRenderError, type NodeRenderResult, RENDER_LIMITS, type RenderImageOptions, type ResolvedRenderImageOptions, VERSION, renderChart, renderToPNG, validateRenderImageOptions };
package/dist/index.js CHANGED
@@ -1,56 +1,163 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
+
1
5
  // src/index.ts
2
6
  import { createCanvas, GlobalFonts } from "@napi-rs/canvas";
3
- import { renderToContext, setMeasureContext } from "graphein";
7
+ import {
8
+ draft
9
+ } from "graphein";
10
+ import {
11
+ computeBackingSize,
12
+ renderDashboardToContext,
13
+ renderToContext,
14
+ setMeasureContext
15
+ } from "graphein/internal";
16
+ var NodeRenderError = class extends Error {
17
+ constructor(result) {
18
+ super((result.renderError ?? result.errors.map((e) => `${e.path}: ${e.message}`).join("; ")) || "Graphein: no final render report is available.");
19
+ __publicField(this, "result", result);
20
+ this.name = "NodeRenderError";
21
+ }
22
+ };
4
23
  var DEFAULT_WIDTH = 800;
5
24
  var DEFAULT_HEIGHT = 500;
6
25
  var DEFAULT_DPR = 2;
7
- function registerFonts(fonts) {
8
- if (!fonts) return;
9
- for (const f of fonts) {
10
- try {
11
- GlobalFonts.registerFromPath(f.path, f.family);
12
- } catch {
13
- }
26
+ var RENDER_LIMITS = Object.freeze({
27
+ minWidth: 1,
28
+ maxWidth: 8192,
29
+ minHeight: 1,
30
+ maxHeight: 8192,
31
+ minDpr: 0.25,
32
+ maxDpr: 4,
33
+ maxPixels: 67108864
34
+ });
35
+ function assertFiniteInRange(name, value, min, max, unit) {
36
+ if (!Number.isFinite(value) || value < min || value > max) {
37
+ throw new RangeError(`Graphein render option "${name}" must be a finite number between ${min} and ${max}${unit ? ` ${unit}` : ""}.`);
14
38
  }
15
39
  }
16
- function renderChart(spec, options = {}) {
40
+ function validateRenderImageOptions(options = {}) {
17
41
  const width = options.width ?? DEFAULT_WIDTH;
18
42
  const height = options.height ?? DEFAULT_HEIGHT;
19
43
  const dpr = options.dpr ?? DEFAULT_DPR;
20
- registerFonts(options.fonts);
21
- const pxW = Math.max(1, Math.round(width * dpr));
22
- const pxH = Math.max(1, Math.round(height * dpr));
44
+ assertFiniteInRange("width", width, RENDER_LIMITS.minWidth, RENDER_LIMITS.maxWidth, "CSS pixels");
45
+ assertFiniteInRange("height", height, RENDER_LIMITS.minHeight, RENDER_LIMITS.maxHeight, "CSS pixels");
46
+ assertFiniteInRange("dpr", dpr, RENDER_LIMITS.minDpr, RENDER_LIMITS.maxDpr, "");
47
+ const pixelWidth = Math.round(width * dpr);
48
+ const pixelHeight = Math.round(height * dpr);
49
+ const pixels = pixelWidth * pixelHeight;
50
+ if (!Number.isSafeInteger(pixels) || pixels > RENDER_LIMITS.maxPixels) {
51
+ throw new RangeError(
52
+ `Graphein render size ${pixelWidth}\xD7${pixelHeight} (${pixels.toLocaleString("en-US")} pixels) exceeds the ${RENDER_LIMITS.maxPixels.toLocaleString("en-US")}-pixel cap. Reduce width, height, or dpr.`
53
+ );
54
+ }
55
+ return { width, height, dpr, pixelWidth, pixelHeight };
56
+ }
57
+ function registerFonts(fonts) {
58
+ return (fonts ?? []).map((f) => {
59
+ try {
60
+ const registered = !!GlobalFonts.registerFromPath(f.path, f.family);
61
+ return { ...f, registered, ...registered ? {} : { message: "Font registration returned no font." } };
62
+ } catch (error) {
63
+ return { ...f, registered: false, message: error instanceof Error ? error.message : String(error) };
64
+ }
65
+ });
66
+ }
67
+ function withFontFindings(report, fonts) {
68
+ const failed = fonts.filter((f) => !f.registered);
69
+ if (!failed.length) return report;
70
+ return {
71
+ ...report,
72
+ ok: false,
73
+ diagnostics: [
74
+ ...report.diagnostics.filter((d) => d.severity === "error"),
75
+ ...failed.map((f) => ({
76
+ code: "font-fallback",
77
+ severity: "warning",
78
+ message: `Could not register "${f.family}"; text may use an available fallback font.`,
79
+ details: { family: f.family, path: f.path, reason: f.message },
80
+ hint: "Supply a readable font file and register it under the family used by the theme."
81
+ })),
82
+ ...report.diagnostics.filter((d) => d.severity !== "error")
83
+ ]
84
+ };
85
+ }
86
+ function renderChart(spec, options = {}) {
87
+ const { width, height, dpr } = validateRenderImageOptions(options);
88
+ const fontRegistrations = registerFonts(options.fonts);
89
+ const backing = computeBackingSize(width, height, dpr);
90
+ const pxW = backing.pixelWidth;
91
+ const pxH = backing.pixelHeight;
23
92
  const canvas = createCanvas(pxW, pxH);
24
93
  const ctx = canvas.getContext("2d");
25
- ctx.scale(dpr, dpr);
94
+ ctx.scale(backing.dpr, backing.dpr);
26
95
  const measureCtx = createCanvas(1, 1).getContext("2d");
27
96
  const interactionCtx = createCanvas(pxW, pxH).getContext("2d");
28
- interactionCtx.scale(dpr, dpr);
29
- setMeasureContext(measureCtx);
97
+ interactionCtx.scale(backing.dpr, backing.dpr);
98
+ const restoreMeasureContext = setMeasureContext(measureCtx);
30
99
  let report;
100
+ let effectiveSpec = spec;
101
+ let quality;
102
+ let warnings;
31
103
  try {
32
- report = renderToContext(
33
- {
34
- marks: ctx,
35
- interaction: interactionCtx,
36
- width,
37
- height
38
- },
39
- spec
40
- );
104
+ const target = {
105
+ marks: ctx,
106
+ interaction: interactionCtx,
107
+ width,
108
+ height,
109
+ backingStore: {
110
+ requestedDpr: backing.requestedDpr,
111
+ effectiveDpr: backing.dpr,
112
+ pixelWidth: backing.pixelWidth,
113
+ pixelHeight: backing.pixelHeight,
114
+ clamped: backing.clamped
115
+ }
116
+ };
117
+ if (options.quality) {
118
+ const selected = draft(spec, { target, repair: false, quality: options.quality });
119
+ if (!selected.report) throw new NodeRenderError(selected);
120
+ report = selected.report;
121
+ effectiveSpec = selected.spec;
122
+ quality = selected.quality;
123
+ warnings = selected.warnings;
124
+ } else {
125
+ report = spec.type === "dashboard" ? renderDashboardToContext(target, spec) : renderToContext(target, spec);
126
+ }
41
127
  } finally {
42
- setMeasureContext(null);
128
+ restoreMeasureContext();
129
+ }
130
+ if (quality) {
131
+ for (const iteration of quality.iterations) {
132
+ if (iteration.report) iteration.report = withFontFindings(iteration.report, fontRegistrations);
133
+ }
134
+ report = quality.iterations.find((i) => i.pass === quality.selectedPass)?.report ?? report;
135
+ if (!report.ok && quality.stopReason === "satisfied") quality.stopReason = "no-actions";
136
+ } else {
137
+ report = withFontFindings(report, fontRegistrations);
43
138
  }
44
- return { png: canvas.toBuffer("image/png"), report, width: pxW, height: pxH };
139
+ return {
140
+ png: canvas.toBuffer("image/png"),
141
+ report,
142
+ spec: effectiveSpec,
143
+ quality,
144
+ ...warnings ? { warnings } : {},
145
+ fontRegistrations,
146
+ width: pxW,
147
+ height: pxH
148
+ };
45
149
  }
46
150
  function renderToPNG(spec, options) {
47
151
  return renderChart(spec, options).png;
48
152
  }
49
- var VERSION = "0.7.0";
153
+ var VERSION = "0.20.0";
50
154
  export {
51
155
  GlobalFonts,
156
+ NodeRenderError,
157
+ RENDER_LIMITS,
52
158
  VERSION,
53
159
  renderChart,
54
- renderToPNG
160
+ renderToPNG,
161
+ validateRenderImageOptions
55
162
  };
56
163
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * `@graphein/node` — headless Graphein rendering for Node.\n *\n * Render any canvas-backed {@link ChartSpec} to a PNG buffer **and** its\n * {@link RenderReport} with no browser and no JSDOM, so the whole\n * generate → validate → render → critique loop can run server-side (CI, agents,\n * email/PDF report assets). It wires `graphein`'s dependency-free\n * `renderToContext` to `@napi-rs/canvas`; the core engine stays zero-dependency.\n *\n * ```ts\n * import { renderChart } from '@graphein/node';\n * const { png, report } = renderChart(spec, { width: 900, height: 480, dpr: 2 });\n * if (!report.ok) console.warn(report.diagnostics);\n * await fs.writeFile('chart.png', png);\n * ```\n *\n * Every chart type rasterizes — kpi/table/matrix/slicers/dashboard render a\n * static canvas snapshot, so the whole catalog can be validated server-side.\n */\n\nimport { createCanvas, GlobalFonts } from '@napi-rs/canvas';\nimport { renderToContext, setMeasureContext, type ChartSpec, type RenderReport } from 'graphein';\n\n/** A font file to register before rendering, improving text fidelity. */\nexport interface FontFace {\n /** Absolute path to a `.ttf` / `.otf` / `.woff` file. */\n path: string;\n /**\n * The family name to register the font under. Match this to the family your\n * theme uses (Graphein's default is `Inter`) so text renders in that face.\n */\n family: string;\n}\n\n/** Options for {@link renderChart} / {@link renderToPNG}. */\nexport interface RenderImageOptions {\n /** Logical width in CSS pixels. Default `800`. */\n width?: number;\n /** Logical height in CSS pixels. Default `500`. */\n height?: number;\n /**\n * Device pixel ratio. The PNG is rasterized at `width * dpr × height * dpr`\n * for crisp output. Default `2`.\n */\n dpr?: number;\n /** Extra fonts to register before rendering. */\n fonts?: FontFace[];\n}\n\n/** The result of a headless render: the PNG bytes plus the render report. */\nexport interface NodeRenderResult {\n /** PNG-encoded image bytes. */\n png: Buffer;\n /**\n * The same machine-readable diagnostics as `instance.report()` in the\n * browser — `ok`, mark/series/color counts, and any clipping / overlap /\n * contrast warnings. Lets an agent critique the chart with no vision model.\n */\n report: RenderReport;\n /** Pixel width of the PNG (`width * dpr`, rounded). */\n width: number;\n /** Pixel height of the PNG (`height * dpr`, rounded). */\n height: number;\n}\n\nconst DEFAULT_WIDTH = 800;\nconst DEFAULT_HEIGHT = 500;\nconst DEFAULT_DPR = 2;\n\nfunction registerFonts(fonts: FontFace[] | undefined): void {\n if (!fonts) return;\n for (const f of fonts) {\n try {\n GlobalFonts.registerFromPath(f.path, f.family);\n } catch {\n // An unreadable font path is non-fatal — napi falls back to a system sans.\n }\n }\n}\n\n/**\n * Render `spec` to a PNG buffer and its {@link RenderReport}, entirely in Node.\n *\n * Supports the entire catalog: line, area, bar, scatter, box, pie, heatmap,\n * sankey, choropleth, combo, histogram, funnel, and the formerly DOM-only kpi,\n * table, matrix, slicers and dashboard (painted as a static canvas snapshot).\n */\nexport function renderChart(spec: ChartSpec, options: RenderImageOptions = {}): NodeRenderResult {\n const width = options.width ?? DEFAULT_WIDTH;\n const height = options.height ?? DEFAULT_HEIGHT;\n const dpr = options.dpr ?? DEFAULT_DPR;\n\n registerFonts(options.fonts);\n\n const pxW = Math.max(1, Math.round(width * dpr));\n const pxH = Math.max(1, Math.round(height * dpr));\n\n const canvas = createCanvas(pxW, pxH);\n const ctx = canvas.getContext('2d');\n ctx.scale(dpr, dpr);\n\n // A dedicated 1×1 context for text measurement so layout uses real font\n // metrics (not the SSR heuristic) without mutating the drawing context.\n const measureCtx = createCanvas(1, 1).getContext('2d');\n\n // The interaction layer is unused on the static path; give it its own canvas\n // so a stray hover-layer paint can never land on the marks canvas.\n const interactionCtx = createCanvas(pxW, pxH).getContext('2d');\n interactionCtx.scale(dpr, dpr);\n\n setMeasureContext(measureCtx as unknown as CanvasRenderingContext2D);\n let report: RenderReport;\n try {\n report = renderToContext(\n {\n marks: ctx as unknown as CanvasRenderingContext2D,\n interaction: interactionCtx as unknown as CanvasRenderingContext2D,\n width,\n height,\n },\n spec,\n );\n } finally {\n setMeasureContext(null);\n }\n\n return { png: canvas.toBuffer('image/png'), report, width: pxW, height: pxH };\n}\n\n/**\n * Convenience wrapper around {@link renderChart} that returns only the PNG bytes.\n */\nexport function renderToPNG(spec: ChartSpec, options?: RenderImageOptions): Buffer {\n return renderChart(spec, options).png;\n}\n\n/** Re-exported so callers can register fonts globally without a second dep. */\nexport { GlobalFonts };\nexport type { ChartSpec, RenderReport } from 'graphein';\n\nexport const VERSION = '0.7.0';\n"],"mappings":";AAoBA,SAAS,cAAc,mBAAmB;AAC1C,SAAS,iBAAiB,yBAA4D;AA4CtF,IAAM,gBAAg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rendering for Node.\n *\n * Render any canvas-backed {@link ChartSpec} to a PNG buffer **and** its\n * {@link RenderReport} with no browser and no JSDOM, so the whole\n * generate → validate → render → critique loop can run server-side (CI, agents,\n * email/PDF report assets). It wires `graphein`'s dependency-free\n * `renderToContext` to `@napi-rs/canvas`; the core engine stays zero-dependency.\n *\n * ```ts\n * import { renderChart } from '@graphein/node';\n * const { png, report } = renderChart(spec, { width: 900, height: 480, dpr: 2 });\n * if (!report.ok) console.warn(report.diagnostics);\n * await fs.writeFile('chart.png', png);\n * ```\n *\n * Every chart type rasterizes — kpi/table/matrix/slicers/dashboard render a\n * static canvas snapshot, so the whole catalog can be validated server-side.\n */\n\nimport { createCanvas, GlobalFonts } from '@napi-rs/canvas';\nimport {\n draft,\n type AnySpec, type ChartSpec, type DashboardSpec, type DraftResult,\n type AnyRenderReport, type DashboardRenderReport, type QualityOptions, type QualityResult, type RenderReport,\n type ValidationError,\n} from 'graphein';\nimport {\n computeBackingSize,\n renderDashboardToContext,\n renderToContext,\n setMeasureContext,\n} from 'graphein/internal';\n\n/** A font file to register before rendering, improving text fidelity. */\nexport interface FontFace {\n /** Absolute path to a `.ttf` / `.otf` / `.woff` file. */\n path: string;\n /**\n * The family name to register the font under. Match this to the family your\n * theme uses (Graphein's default is `Inter`) so text renders in that face.\n */\n family: string;\n}\n\n/** Options for {@link renderChart} / {@link renderToPNG}. */\nexport interface RenderImageOptions {\n /** Logical width in CSS pixels. Default `800`. */\n width?: number;\n /** Logical height in CSS pixels. Default `500`. */\n height?: number;\n /**\n * Device pixel ratio. The PNG is rasterized at `width * dpr × height * dpr`\n * for crisp output. Default `2`.\n */\n dpr?: number;\n /** Extra fonts to register before rendering. */\n fonts?: FontFace[];\n /** Opt in to core's presentation-default loop (at most three whole-visual render attempts). */\n quality?: boolean | QualityOptions;\n}\n\n/** Registration evidence for a caller-supplied font; failure is non-fatal. */\nexport interface FontRegistration {\n path: string;\n family: string;\n registered: boolean;\n message?: string;\n}\n\n/** The result of a headless render: the PNG bytes plus the render report. */\nexport interface NodeRenderResult<R extends AnyRenderReport = RenderReport> {\n /** PNG-encoded image bytes. */\n png: Buffer;\n /**\n * The same machine-readable diagnostics as `instance.report()` in the\n * browser — `ok`, mark/series/color counts, and any clipping / overlap /\n * contrast warnings. Lets an agent critique the chart with no vision model.\n */\n report: R;\n /** Pixel width of the PNG (`width * dpr`, rounded). */\n width: number;\n /** Pixel height of the PNG (`height * dpr`, rounded). */\n height: number;\n /** Effective spec corresponding to the final PNG and report. Input data is never transformed by quality mode. */\n spec: AnySpec;\n /** Core quality-loop evidence, present only when opted in. */\n quality?: QualityResult;\n /** Validation advisories retained when quality mode validates the spec; absent on the direct default path. */\n warnings?: ValidationError[];\n /** Outcome of each explicitly requested font registration. */\n fontRegistrations: FontRegistration[];\n}\n\n/** Opt-in validation/rendering failed, so no potentially mismatched PNG was encoded. */\nexport class NodeRenderError extends Error {\n constructor(readonly result: DraftResult) {\n super((result.renderError ?? result.errors.map((e) => `${e.path}: ${e.message}`).join('; ')) ||\n 'Graphein: no final render report is available.');\n this.name = 'NodeRenderError';\n }\n}\n\nconst DEFAULT_WIDTH = 800;\nconst DEFAULT_HEIGHT = 500;\nconst DEFAULT_DPR = 2;\n\n/** Hard bounds that keep headless renders from creating invalid or enormous canvases. */\nexport const RENDER_LIMITS = Object.freeze({\n minWidth: 1,\n maxWidth: 8192,\n minHeight: 1,\n maxHeight: 8192,\n minDpr: 0.25,\n maxDpr: 4,\n maxPixels: 67_108_864,\n});\n\nexport interface ResolvedRenderImageOptions {\n /** Logical width in CSS pixels. */\n width: number;\n /** Logical height in CSS pixels. */\n height: number;\n /** Device pixel ratio. */\n dpr: number;\n /** Rounded raster width in physical pixels. */\n pixelWidth: number;\n /** Rounded raster height in physical pixels. */\n pixelHeight: number;\n}\n\nfunction assertFiniteInRange(name: string, value: number, min: number, max: number, unit: string): void {\n if (!Number.isFinite(value) || value < min || value > max) {\n throw new RangeError(`Graphein render option \"${name}\" must be a finite number between ${min} and ${max}${unit ? ` ${unit}` : ''}.`);\n }\n}\n\n/** Validate and resolve render sizing options before allocating a canvas. */\nexport function validateRenderImageOptions(options: RenderImageOptions = {}): ResolvedRenderImageOptions {\n const width = options.width ?? DEFAULT_WIDTH;\n const height = options.height ?? DEFAULT_HEIGHT;\n const dpr = options.dpr ?? DEFAULT_DPR;\n assertFiniteInRange('width', width, RENDER_LIMITS.minWidth, RENDER_LIMITS.maxWidth, 'CSS pixels');\n assertFiniteInRange('height', height, RENDER_LIMITS.minHeight, RENDER_LIMITS.maxHeight, 'CSS pixels');\n assertFiniteInRange('dpr', dpr, RENDER_LIMITS.minDpr, RENDER_LIMITS.maxDpr, '');\n const pixelWidth = Math.round(width * dpr);\n const pixelHeight = Math.round(height * dpr);\n const pixels = pixelWidth * pixelHeight;\n if (!Number.isSafeInteger(pixels) || pixels > RENDER_LIMITS.maxPixels) {\n throw new RangeError(\n `Graphein render size ${pixelWidth}×${pixelHeight} (${pixels.toLocaleString('en-US')} pixels) exceeds the ${RENDER_LIMITS.maxPixels.toLocaleString('en-US')}-pixel cap. Reduce width, height, or dpr.`,\n );\n }\n return { width, height, dpr, pixelWidth, pixelHeight };\n}\n\nfunction registerFonts(fonts: FontFace[] | undefined): FontRegistration[] {\n return (fonts ?? []).map((f) => {\n try {\n const registered = !!GlobalFonts.registerFromPath(f.path, f.family);\n return { ...f, registered, ...(registered ? {} : { message: 'Font registration returned no font.' }) };\n } catch (error) {\n return { ...f, registered: false, message: error instanceof Error ? error.message : String(error) };\n }\n });\n}\n\nfunction withFontFindings<R extends AnyRenderReport>(report: R, fonts: FontRegistration[]): R {\n const failed = fonts.filter((f) => !f.registered);\n if (!failed.length) return report;\n return {\n ...report,\n ok: false,\n diagnostics: [\n ...report.diagnostics.filter((d) => d.severity === 'error'),\n ...failed.map((f) => ({\n code: 'font-fallback', severity: 'warning' as const,\n message: `Could not register \"${f.family}\"; text may use an available fallback font.`,\n details: { family: f.family, path: f.path, reason: f.message },\n hint: 'Supply a readable font file and register it under the family used by the theme.',\n })),\n ...report.diagnostics.filter((d) => d.severity !== 'error'),\n ],\n };\n}\n\n/**\n * Render `spec` to a PNG buffer and its {@link RenderReport}, entirely in Node.\n *\n * Supports the entire catalog: line, area, bar, scatter, box, pie, heatmap,\n * sankey, choropleth, combo, histogram, funnel, and the formerly DOM-only kpi,\n * table, matrix, slicers and dashboard (painted as a static canvas snapshot).\n */\nexport function renderChart(spec: DashboardSpec, options?: RenderImageOptions): NodeRenderResult<DashboardRenderReport>;\nexport function renderChart(spec: ChartSpec, options?: RenderImageOptions): NodeRenderResult;\nexport function renderChart(spec: AnySpec, options?: RenderImageOptions): NodeRenderResult<AnyRenderReport>;\nexport function renderChart(spec: AnySpec, options: RenderImageOptions = {}): NodeRenderResult<AnyRenderReport> {\n const { width, height, dpr } = validateRenderImageOptions(options);\n\n const fontRegistrations = registerFonts(options.fonts);\n\n const backing = computeBackingSize(width, height, dpr);\n const pxW = backing.pixelWidth;\n const pxH = backing.pixelHeight;\n\n const canvas = createCanvas(pxW, pxH);\n const ctx = canvas.getContext('2d');\n ctx.scale(backing.dpr, backing.dpr);\n\n // A dedicated 1×1 context for text measurement so layout uses real font\n // metrics (not the SSR heuristic) without mutating the drawing context.\n const measureCtx = createCanvas(1, 1).getContext('2d');\n\n // The interaction layer is unused on the static path; give it its own canvas\n // so a stray hover-layer paint can never land on the marks canvas.\n const interactionCtx = createCanvas(pxW, pxH).getContext('2d');\n interactionCtx.scale(backing.dpr, backing.dpr);\n\n const restoreMeasureContext = setMeasureContext(measureCtx as unknown as CanvasRenderingContext2D);\n let report: AnyRenderReport;\n let effectiveSpec = spec;\n let quality: QualityResult | undefined;\n let warnings: ValidationError[] | undefined;\n try {\n const target = {\n marks: ctx as unknown as CanvasRenderingContext2D,\n interaction: interactionCtx as unknown as CanvasRenderingContext2D,\n width,\n height,\n backingStore: {\n requestedDpr: backing.requestedDpr,\n effectiveDpr: backing.dpr,\n pixelWidth: backing.pixelWidth,\n pixelHeight: backing.pixelHeight,\n clamped: backing.clamped,\n },\n };\n if (options.quality) {\n const selected = draft(spec, { target, repair: false, quality: options.quality });\n if (!selected.report) throw new NodeRenderError(selected);\n report = selected.report;\n effectiveSpec = selected.spec as AnySpec;\n quality = selected.quality;\n warnings = selected.warnings;\n } else {\n report = spec.type === 'dashboard'\n ? renderDashboardToContext(target, spec)\n : renderToContext(target, spec);\n }\n } finally {\n restoreMeasureContext();\n }\n\n if (quality) {\n for (const iteration of quality.iterations) {\n if (iteration.report) iteration.report = withFontFindings(iteration.report, fontRegistrations);\n }\n report = quality.iterations.find((i) => i.pass === quality.selectedPass)?.report ?? report;\n if (!report.ok && quality.stopReason === 'satisfied') quality.stopReason = 'no-actions';\n } else {\n report = withFontFindings(report, fontRegistrations);\n }\n return {\n png: canvas.toBuffer('image/png'), report, spec: effectiveSpec, quality,\n ...(warnings ? { warnings } : {}),\n fontRegistrations, width: pxW, height: pxH,\n };\n}\n\n/**\n * Convenience wrapper around {@link renderChart} that returns only the PNG bytes.\n */\nexport function renderToPNG(spec: AnySpec, options?: RenderImageOptions): Buffer {\n return renderChart(spec, options).png;\n}\n\n/** Re-exported so callers can register fonts globally without a second dep. */\nexport { GlobalFonts };\nexport type {\n AnySpec, ChartSpec, DashboardSpec, QualityOptions, QualityResult,\n AnyRenderReport, DashboardRenderReport, RenderReport,\n ValidationError,\n} from 'graphein';\n\nexport const VERSION = '0.20.0';\n"],"mappings":";;;;;AAoBA,SAAS,cAAc,mBAAmB;AAC1C;AAAA,EACE;AAAA,OAIK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AA+DA,IAAM,kBAAN,cAA8B,MAAM;AAAA,EACzC,YAAqB,QAAqB;AACxC,WAAO,OAAO,eAAe,OAAO,OAAO,IAAI,CAAC,MAAM,GAAG,EAAE,IAAI,KAAK,EAAE,OAAO,EAAE,EAAE,KAAK,IAAI,MACxF,gDAAgD;AAF/B;AAGnB,SAAK,OAAO;AAAA,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AO;AACL,aAAS,iBAAiB,QAAQ,iBAAiB;AAAA,EACrD;AACA,SAAO;AAAA,IACL,KAAK,OAAO,SAAS,WAAW;AAAA,IAAG;AAAA,IAAQ,MAAM;AAAA,IAAe;AAAA,IAChE,GAAI,WAAW,EAAE,SAAS,IAAI,CAAC;AAAA,IAC/B;AAAA,IAAmB,OAAO;AAAA,IAAK,QAAQ;AAAA,EACzC;AACF;AAKO,SAAS,YAAY,MAAe,SAAsC;AAC/E,SAAO,YAAY,MAAM,OAAO,EAAE;AACpC;AAUO,IAAM,UAAU;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@graphein/node",
3
- "version": "0.18.0",
3
+ "version": "0.20.0",
4
4
  "type": "module",
5
5
  "description": "Headless Graphein rendering for Node — render any ChartSpec to a PNG buffer with a RenderReport, no browser required.",
6
6
  "license": "MIT",
@@ -48,14 +48,15 @@
48
48
  "access": "public"
49
49
  },
50
50
  "scripts": {
51
- "build": "tsup",
51
+ "sync:version": "node ../core/scripts/sync-version.mjs .",
52
+ "build": "npm run sync:version && tsup",
52
53
  "dev": "tsup --watch",
53
54
  "test": "vitest run",
54
55
  "typecheck": "tsc --noEmit",
55
- "prepack": "tsup"
56
+ "prepack": "npm run sync:version && tsup"
56
57
  },
57
58
  "dependencies": {
58
59
  "@napi-rs/canvas": "^1.0.1",
59
- "graphein": "^0.18.0"
60
+ "graphein": "^0.20.0"
60
61
  }
61
62
  }