@graphein/node 0.17.0 → 0.19.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 +33 -2
- package/dist/index.d.ts +30 -6
- package/dist/index.js +82 -17
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
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,7 @@ 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. |
|
|
72
98
|
|
|
73
99
|
### Fonts
|
|
74
100
|
|
|
@@ -77,11 +103,16 @@ Convenience wrapper that returns only the PNG bytes.
|
|
|
77
103
|
|
|
78
104
|
```ts
|
|
79
105
|
renderChart(spec, {
|
|
80
|
-
fonts: [{ path: '
|
|
106
|
+
fonts: [{ path: 'C:\\fonts\\Inter-Variable.ttf', family: 'Inter' }],
|
|
81
107
|
});
|
|
82
108
|
```
|
|
83
109
|
|
|
84
110
|
`GlobalFonts` is re-exported if you prefer to register fonts once at startup.
|
|
111
|
+
Unreadable/unregisterable files do not crash an otherwise valid render:
|
|
112
|
+
`fontRegistrations` contains `{path,family,registered,message?}` for each request,
|
|
113
|
+
and failures add a `font-fallback` warning to the report and quality history.
|
|
114
|
+
Successful registration establishes that the file loaded, not that every glyph or
|
|
115
|
+
requested font style is available.
|
|
85
116
|
|
|
86
117
|
## Supported charts
|
|
87
118
|
|
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,11 +64,24 @@ 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:
|
|
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);
|
|
63
85
|
}
|
|
64
86
|
/**
|
|
65
87
|
* Render `spec` to a PNG buffer and its {@link RenderReport}, entirely in Node.
|
|
@@ -68,12 +90,14 @@ interface NodeRenderResult {
|
|
|
68
90
|
* sankey, choropleth, combo, histogram, funnel, and the formerly DOM-only kpi,
|
|
69
91
|
* table, matrix, slicers and dashboard (painted as a static canvas snapshot).
|
|
70
92
|
*/
|
|
93
|
+
declare function renderChart(spec: DashboardSpec, options?: RenderImageOptions): NodeRenderResult<DashboardRenderReport>;
|
|
71
94
|
declare function renderChart(spec: ChartSpec, options?: RenderImageOptions): NodeRenderResult;
|
|
95
|
+
declare function renderChart(spec: AnySpec, options?: RenderImageOptions): NodeRenderResult<AnyRenderReport>;
|
|
72
96
|
/**
|
|
73
97
|
* Convenience wrapper around {@link renderChart} that returns only the PNG bytes.
|
|
74
98
|
*/
|
|
75
|
-
declare function renderToPNG(spec:
|
|
99
|
+
declare function renderToPNG(spec: AnySpec, options?: RenderImageOptions): Buffer;
|
|
76
100
|
|
|
77
101
|
declare const VERSION = "0.7.0";
|
|
78
102
|
|
|
79
|
-
export { type FontFace, type NodeRenderResult, type RenderImageOptions, VERSION, renderChart, renderToPNG };
|
|
103
|
+
export { type FontFace, type FontRegistration, NodeRenderError, type NodeRenderResult, type RenderImageOptions, VERSION, renderChart, renderToPNG };
|
package/dist/index.js
CHANGED
|
@@ -1,23 +1,59 @@
|
|
|
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 {
|
|
7
|
+
import {
|
|
8
|
+
draft,
|
|
9
|
+
renderDashboardToContext,
|
|
10
|
+
renderToContext,
|
|
11
|
+
setMeasureContext
|
|
12
|
+
} from "graphein";
|
|
13
|
+
var NodeRenderError = class extends Error {
|
|
14
|
+
constructor(result) {
|
|
15
|
+
super((result.renderError ?? result.errors.map((e) => `${e.path}: ${e.message}`).join("; ")) || "Graphein: no final render report is available.");
|
|
16
|
+
__publicField(this, "result", result);
|
|
17
|
+
this.name = "NodeRenderError";
|
|
18
|
+
}
|
|
19
|
+
};
|
|
4
20
|
var DEFAULT_WIDTH = 800;
|
|
5
21
|
var DEFAULT_HEIGHT = 500;
|
|
6
22
|
var DEFAULT_DPR = 2;
|
|
7
23
|
function registerFonts(fonts) {
|
|
8
|
-
|
|
9
|
-
for (const f of fonts) {
|
|
24
|
+
return (fonts ?? []).map((f) => {
|
|
10
25
|
try {
|
|
11
|
-
GlobalFonts.registerFromPath(f.path, f.family);
|
|
12
|
-
|
|
26
|
+
const registered = !!GlobalFonts.registerFromPath(f.path, f.family);
|
|
27
|
+
return { ...f, registered, ...registered ? {} : { message: "Font registration returned no font." } };
|
|
28
|
+
} catch (error) {
|
|
29
|
+
return { ...f, registered: false, message: error instanceof Error ? error.message : String(error) };
|
|
13
30
|
}
|
|
14
|
-
}
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
function withFontFindings(report, fonts) {
|
|
34
|
+
const failed = fonts.filter((f) => !f.registered);
|
|
35
|
+
if (!failed.length) return report;
|
|
36
|
+
return {
|
|
37
|
+
...report,
|
|
38
|
+
ok: false,
|
|
39
|
+
diagnostics: [
|
|
40
|
+
...report.diagnostics.filter((d) => d.severity === "error"),
|
|
41
|
+
...failed.map((f) => ({
|
|
42
|
+
code: "font-fallback",
|
|
43
|
+
severity: "warning",
|
|
44
|
+
message: `Could not register "${f.family}"; text may use an available fallback font.`,
|
|
45
|
+
details: { family: f.family, path: f.path, reason: f.message },
|
|
46
|
+
hint: "Supply a readable font file and register it under the family used by the theme."
|
|
47
|
+
})),
|
|
48
|
+
...report.diagnostics.filter((d) => d.severity !== "error")
|
|
49
|
+
]
|
|
50
|
+
};
|
|
15
51
|
}
|
|
16
52
|
function renderChart(spec, options = {}) {
|
|
17
53
|
const width = options.width ?? DEFAULT_WIDTH;
|
|
18
54
|
const height = options.height ?? DEFAULT_HEIGHT;
|
|
19
55
|
const dpr = options.dpr ?? DEFAULT_DPR;
|
|
20
|
-
registerFonts(options.fonts);
|
|
56
|
+
const fontRegistrations = registerFonts(options.fonts);
|
|
21
57
|
const pxW = Math.max(1, Math.round(width * dpr));
|
|
22
58
|
const pxH = Math.max(1, Math.round(height * dpr));
|
|
23
59
|
const canvas = createCanvas(pxW, pxH);
|
|
@@ -28,20 +64,48 @@ function renderChart(spec, options = {}) {
|
|
|
28
64
|
interactionCtx.scale(dpr, dpr);
|
|
29
65
|
setMeasureContext(measureCtx);
|
|
30
66
|
let report;
|
|
67
|
+
let effectiveSpec = spec;
|
|
68
|
+
let quality;
|
|
69
|
+
let warnings;
|
|
31
70
|
try {
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
spec
|
|
40
|
-
|
|
71
|
+
const target = {
|
|
72
|
+
marks: ctx,
|
|
73
|
+
interaction: interactionCtx,
|
|
74
|
+
width,
|
|
75
|
+
height
|
|
76
|
+
};
|
|
77
|
+
if (options.quality) {
|
|
78
|
+
const selected = draft(spec, { target, repair: false, quality: options.quality });
|
|
79
|
+
if (!selected.report) throw new NodeRenderError(selected);
|
|
80
|
+
report = selected.report;
|
|
81
|
+
effectiveSpec = selected.spec;
|
|
82
|
+
quality = selected.quality;
|
|
83
|
+
warnings = selected.warnings;
|
|
84
|
+
} else {
|
|
85
|
+
report = spec.type === "dashboard" ? renderDashboardToContext(target, spec) : renderToContext(target, spec);
|
|
86
|
+
}
|
|
41
87
|
} finally {
|
|
42
88
|
setMeasureContext(null);
|
|
43
89
|
}
|
|
44
|
-
|
|
90
|
+
if (quality) {
|
|
91
|
+
for (const iteration of quality.iterations) {
|
|
92
|
+
if (iteration.report) iteration.report = withFontFindings(iteration.report, fontRegistrations);
|
|
93
|
+
}
|
|
94
|
+
report = quality.iterations.find((i) => i.pass === quality.selectedPass)?.report ?? report;
|
|
95
|
+
if (!report.ok && quality.stopReason === "satisfied") quality.stopReason = "no-actions";
|
|
96
|
+
} else {
|
|
97
|
+
report = withFontFindings(report, fontRegistrations);
|
|
98
|
+
}
|
|
99
|
+
return {
|
|
100
|
+
png: canvas.toBuffer("image/png"),
|
|
101
|
+
report,
|
|
102
|
+
spec: effectiveSpec,
|
|
103
|
+
quality,
|
|
104
|
+
...warnings ? { warnings } : {},
|
|
105
|
+
fontRegistrations,
|
|
106
|
+
width: pxW,
|
|
107
|
+
height: pxH
|
|
108
|
+
};
|
|
45
109
|
}
|
|
46
110
|
function renderToPNG(spec, options) {
|
|
47
111
|
return renderChart(spec, options).png;
|
|
@@ -49,6 +113,7 @@ function renderToPNG(spec, options) {
|
|
|
49
113
|
var VERSION = "0.7.0";
|
|
50
114
|
export {
|
|
51
115
|
GlobalFonts,
|
|
116
|
+
NodeRenderError,
|
|
52
117
|
VERSION,
|
|
53
118
|
renderChart,
|
|
54
119
|
renderToPNG
|
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,gBAAgB;AACtB,IAAM,iBAAiB;AACvB,IAAM,cAAc;AAEpB,SAAS,cAAc,OAAqC;AAC1D,MAAI,CAAC,MAAO;AACZ,aAAW,KAAK,OAAO;AACrB,QAAI;AACF,kBAAY,iBAAiB,EAAE,MAAM,EAAE,MAAM;AAAA,IAC/C,QAAQ;AAAA,IAER;AAAA,EACF;AACF;AASO,SAAS,YAAY,MAAiB,UAA8B,CAAC,GAAqB;AAC/F,QAAM,QAAQ,QAAQ,SAAS;AAC/B,QAAM,SAAS,QAAQ,UAAU;AACjC,QAAM,MAAM,QAAQ,OAAO;AAE3B,gBAAc,QAAQ,KAAK;AAE3B,QAAM,MAAM,KAAK,IAAI,GAAG,KAAK,MAAM,QAAQ,GAAG,CAAC;AAC/C,QAAM,MAAM,KAAK,IAAI,GAAG,KAAK,MAAM,SAAS,GAAG,CAAC;AAEhD,QAAM,SAAS,aAAa,KAAK,GAAG;AACpC,QAAM,MAAM,OAAO,WAAW,IAAI;AAClC,MAAI,MAAM,KAAK,GAAG;AAIlB,QAAM,aAAa,aAAa,GAAG,CAAC,EAAE,WAAW,IAAI;AAIrD,QAAM,iBAAiB,aAAa,KAAK,GAAG,EAAE,WAAW,IAAI;AAC7D,iBAAe,MAAM,KAAK,GAAG;AAE7B,oBAAkB,UAAiD;AACnE,MAAI;AACJ,MAAI;AACF,aAAS;AAAA,MACP;AAAA,QACE,OAAO;AAAA,QACP,aAAa;AAAA,QACb;AAAA,QACA;AAAA,MACF;AAAA,MACA;AAAA,IACF;AAAA,EACF,UAAE;AACA,sBAAkB,IAAI;AAAA,EACxB;AAEA,SAAO,EAAE,KAAK,OAAO,SAAS,WAAW,GAAG,QAAQ,OAAO,KAAK,QAAQ,IAAI;AAC9E;AAKO,SAAS,YAAY,MAAiB,SAAsC;AACjF,SAAO,YAAY,MAAM,OAAO,EAAE;AACpC;AAMO,IAAM,UAAU;","names":[]}
|
|
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 {\n draft, renderDashboardToContext, renderToContext, setMeasureContext,\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';\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\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 = options.width ?? DEFAULT_WIDTH;\n const height = options.height ?? DEFAULT_HEIGHT;\n const dpr = options.dpr ?? DEFAULT_DPR;\n\n const fontRegistrations = 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: 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 };\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 setMeasureContext(null);\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.7.0';\n"],"mappings":"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","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@graphein/node",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.19.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",
|
|
@@ -56,6 +56,6 @@
|
|
|
56
56
|
},
|
|
57
57
|
"dependencies": {
|
|
58
58
|
"@napi-rs/canvas": "^1.0.1",
|
|
59
|
-
"graphein": "^0.
|
|
59
|
+
"graphein": "^0.19.0"
|
|
60
60
|
}
|
|
61
61
|
}
|