@chartpng/render 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +165 -2
- package/SECURITY.md +34 -0
- package/THIRD_PARTY_NOTICES.md +253 -0
- package/bin/chartpng-render.js +2 -0
- package/dist/packages/render/cli.d.ts +1 -0
- package/dist/packages/render/cli.js +88 -0
- package/dist/packages/render/index.d.ts +61 -0
- package/dist/packages/render/index.js +79 -0
- package/dist/src/fonts/plex.d.ts +2 -0
- package/dist/src/fonts/plex.js +9 -0
- package/dist/src/lib/errors.d.ts +4 -0
- package/dist/src/lib/errors.js +9 -0
- package/dist/src/lib/maker.d.ts +90 -0
- package/dist/src/lib/maker.js +297 -0
- package/dist/src/lib/presets.d.ts +61 -0
- package/dist/src/lib/presets.js +576 -0
- package/dist/src/lib/render.d.ts +38 -0
- package/dist/src/lib/render.js +738 -0
- package/dist/src/lib/repair.d.ts +8 -0
- package/dist/src/lib/repair.js +598 -0
- package/dist/src/lib/style.d.ts +23 -0
- package/dist/src/lib/style.js +110 -0
- package/dist/src/lib/table-chart.d.ts +133 -0
- package/dist/src/lib/table-chart.js +624 -0
- package/dist/src/lib/theme.d.ts +37 -0
- package/dist/src/lib/theme.js +288 -0
- package/package.json +51 -3
|
@@ -0,0 +1,738 @@
|
|
|
1
|
+
// Renders a Chart.js config (plain JSON, never code) to a PNG buffer.
|
|
2
|
+
import { RenderError } from './errors.js';
|
|
3
|
+
import { createCanvas, GlobalFonts } from '@napi-rs/canvas';
|
|
4
|
+
import { Chart, registerables } from 'chart.js';
|
|
5
|
+
import { addRoundedRectPath } from 'chart.js/helpers';
|
|
6
|
+
import { repairConfig } from './repair.js';
|
|
7
|
+
import { chipFor, FONT_EXT, FONT_FAMILY, FONT_STACK, inkFor, valuesPlugin } from './theme.js';
|
|
8
|
+
import { applyPreset, presetPlugin } from './presets.js';
|
|
9
|
+
import { checkStyle, floorFonts, isOpaque, OUTPUT_DEFAULTS, OUTPUT_MIN_FONT, outputPreset, styleFields, withStyle } from './style.js';
|
|
10
|
+
import { PLEX_EXT_WOFF2_BASE64, PLEX_LATIN_WOFF2_BASE64 } from '../fonts/plex.js';
|
|
11
|
+
Chart.register(...registerables);
|
|
12
|
+
// Serverless hosts ship no system fonts, so the font travels in the bundle.
|
|
13
|
+
for (const font of PLEX_LATIN_WOFF2_BASE64)
|
|
14
|
+
GlobalFonts.register(Buffer.from(font, 'base64'), FONT_FAMILY);
|
|
15
|
+
for (const font of PLEX_EXT_WOFF2_BASE64)
|
|
16
|
+
GlobalFonts.register(Buffer.from(font, 'base64'), FONT_EXT);
|
|
17
|
+
Chart.defaults.font.family = FONT_STACK;
|
|
18
|
+
export const LIMITS = {
|
|
19
|
+
maxConfigBytes: 16 * 1024,
|
|
20
|
+
maxSide: 2000,
|
|
21
|
+
minSide: 50,
|
|
22
|
+
defaultWidth: 600,
|
|
23
|
+
defaultHeight: 360,
|
|
24
|
+
// Chart.js caps ticks from stepSize at 1000 but not ticks.count: a million
|
|
25
|
+
// ticks takes 25 s and 800 MB, a hundred million kills the process.
|
|
26
|
+
maxTicks: 100,
|
|
27
|
+
// Chart.js merges options recursively; very deep objects overflow the stack.
|
|
28
|
+
maxDepth: 16,
|
|
29
|
+
// The free plan's ceiling for w × h × dpr²: 2000 × 2000 at dpr 1. Paid keys get the full 16 MP.
|
|
30
|
+
freeMaxPixels: 4_000_000,
|
|
31
|
+
// A POST body: a 16 KB config plus room for the other fields.
|
|
32
|
+
maxBodyBytes: 20 * 1024,
|
|
33
|
+
};
|
|
34
|
+
const QUERY_FIELDS = new Set(['c', 'w', 'h', 'bkg', 'dpr', 'k', 's', 'theme', 'palette', 'preset']);
|
|
35
|
+
// QuickChart's names for the same fields, so moving from QuickChart is a domain change.
|
|
36
|
+
const QUICKCHART_NAMES = {
|
|
37
|
+
chart: 'c',
|
|
38
|
+
width: 'w',
|
|
39
|
+
height: 'h',
|
|
40
|
+
backgroundColor: 'bkg',
|
|
41
|
+
devicePixelRatio: 'dpr',
|
|
42
|
+
};
|
|
43
|
+
// Every URL that differs is a new render, so a query with an unknown or
|
|
44
|
+
// repeated parameter is refused before any drawing: junk can't bust the cache.
|
|
45
|
+
export function queryFields(params) {
|
|
46
|
+
const fields = {};
|
|
47
|
+
for (const [raw, value] of params) {
|
|
48
|
+
const name = QUICKCHART_NAMES[raw] ?? raw;
|
|
49
|
+
if (!QUERY_FIELDS.has(name))
|
|
50
|
+
throw new RenderError(`unknown parameter: ${raw.slice(0, 40)}`, 'unknown_param');
|
|
51
|
+
if (name in fields)
|
|
52
|
+
throw new RenderError(`parameter given twice: ${name}`, 'repeated_param');
|
|
53
|
+
fields[name] = value;
|
|
54
|
+
}
|
|
55
|
+
return fields;
|
|
56
|
+
}
|
|
57
|
+
export function checkFreeSize({ width, height, dpr }) {
|
|
58
|
+
if (width * height * dpr * dpr > LIMITS.freeMaxPixels) {
|
|
59
|
+
throw new RenderError('the free plan renders up to 4 megapixels (w × h × dpr²); a Pro key lifts it', 'free_size');
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
const CHART_TYPES = new Set(['bar', 'line', 'pie', 'doughnut', 'radar', 'polarArea', 'scatter', 'bubble']);
|
|
63
|
+
export { RenderError };
|
|
64
|
+
function toSide(value, fallback) {
|
|
65
|
+
if (value == null || value === '')
|
|
66
|
+
return fallback;
|
|
67
|
+
const n = Number(value);
|
|
68
|
+
if (!Number.isInteger(n) || n < LIMITS.minSide || n > LIMITS.maxSide) {
|
|
69
|
+
throw new RenderError(`width and height must be integers between ${LIMITS.minSide} and ${LIMITS.maxSide}`, 'bad_size');
|
|
70
|
+
}
|
|
71
|
+
return n;
|
|
72
|
+
}
|
|
73
|
+
// Walks the parsed config once: rejects nesting deeper than maxDepth and any
|
|
74
|
+
// ticks object asking for more than maxTicks ticks.
|
|
75
|
+
function checkConfig(value, depth = 0) {
|
|
76
|
+
if (!value || typeof value !== 'object')
|
|
77
|
+
return;
|
|
78
|
+
if (depth > LIMITS.maxDepth)
|
|
79
|
+
throw new RenderError(`chart config is nested deeper than ${LIMITS.maxDepth} levels`, 'too_deep');
|
|
80
|
+
for (const [key, child] of Object.entries(value)) {
|
|
81
|
+
if (key === 'ticks' && child && typeof child === 'object') {
|
|
82
|
+
for (const limit of ['count', 'maxTicksLimit']) {
|
|
83
|
+
const n = child[limit];
|
|
84
|
+
if (n != null && !(Number(n) <= LIMITS.maxTicks))
|
|
85
|
+
throw new RenderError(`ticks.${limit} must be at most ${LIMITS.maxTicks}`, 'ticks');
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
checkConfig(child, depth + 1);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
92
|
+
// Chart.js crashes while reading these options when they are not objects, which
|
|
93
|
+
// would only surface as a generic draw_failed. This names the path instead.
|
|
94
|
+
// It runs only after Chart.js has failed, never before: whether a shape crashes
|
|
95
|
+
// depends on the scale (a hidden axis or the radial r never reads its grid), so
|
|
96
|
+
// a check up front would refuse charts that draw. For the same reason it runs last of
|
|
97
|
+
// the post-failure checks: a shape may draw fine, a type Chart.js cannot resolve never does.
|
|
98
|
+
// (An empty dataset type is not one: Chart.js falls back to the chart type.)
|
|
99
|
+
// Run on the user's options.
|
|
100
|
+
function checkOptionShapes(options) {
|
|
101
|
+
if (!isObject(options))
|
|
102
|
+
return;
|
|
103
|
+
const refuse = (path) => {
|
|
104
|
+
throw new RenderError(`options.${path} must be an object`, 'bad_option');
|
|
105
|
+
};
|
|
106
|
+
if (isObject(options.plugins) && Array.isArray(options.plugins.legend))
|
|
107
|
+
refuse('plugins.legend');
|
|
108
|
+
if (!isObject(options.scales))
|
|
109
|
+
return;
|
|
110
|
+
for (const [name, scale] of Object.entries(options.scales)) {
|
|
111
|
+
if (!isObject(scale))
|
|
112
|
+
continue;
|
|
113
|
+
const at = (key) => `scales.${name.slice(0, 40)}.${key}`;
|
|
114
|
+
for (const key of ['ticks', 'grid', 'border']) {
|
|
115
|
+
if (scale[key] !== undefined && !isObject(scale[key]))
|
|
116
|
+
refuse(at(key));
|
|
117
|
+
}
|
|
118
|
+
// An array, a string or a number as the title is ignored; only null crashes.
|
|
119
|
+
if (scale.title === null)
|
|
120
|
+
refuse(at('title'));
|
|
121
|
+
// Same for the radial axis: only null crashes pointLabels (reading 'callback') and
|
|
122
|
+
// angleLines (reading 'display'); arrays, strings, numbers and booleans are ignored.
|
|
123
|
+
// Only a radial axis reads them, so a null on any other axis is not named as the cause.
|
|
124
|
+
if (name === 'r' || scale.type === 'radialLinear') {
|
|
125
|
+
for (const key of ['pointLabels', 'angleLines'])
|
|
126
|
+
if (scale[key] === null)
|
|
127
|
+
refuse(at(key));
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
// Chart.js 4 builds a time or timeseries axis only with a date adapter, which ChartPNG
|
|
132
|
+
// does not have, so the draw fails with a message the caller cannot act on. It runs
|
|
133
|
+
// only after a failed draw, never up front, so it can only name a cause and never
|
|
134
|
+
// refuses a chart that draws. It is checked first: a time axis fails the draw on its own.
|
|
135
|
+
function checkTimeAxes(options) {
|
|
136
|
+
if (!isObject(options) || !isObject(options.scales))
|
|
137
|
+
return;
|
|
138
|
+
for (const [name, scale] of Object.entries(options.scales)) {
|
|
139
|
+
if (!isObject(scale) || (scale.type !== 'time' && scale.type !== 'timeseries'))
|
|
140
|
+
continue;
|
|
141
|
+
throw new RenderError(`options.scales.${name.slice(0, 40)}.type '${scale.type}' needs a date adapter, which ChartPNG does not have: send the dates as labels with a category axis`, 'bad_option');
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
// The ids Chart.js has registered for a kind of component. TypedRegistry keeps them in
|
|
145
|
+
// an items map the typings do not expose.
|
|
146
|
+
const registered = (kind) => Object.keys(Chart.registry[kind].items);
|
|
147
|
+
// The ids the message suggests: time and timeseries are registered but checkTimeAxes refuses them
|
|
148
|
+
// (no date adapter), so they are not offered. What is accepted is still decided by registered().
|
|
149
|
+
const suggested = (kind) => registered(kind).filter((id) => kind !== 'scales' || (id !== 'time' && id !== 'timeseries'));
|
|
150
|
+
// An axis type or a dataset type Chart.js does not know ("foo", or "area" from a caller who
|
|
151
|
+
// meant a filled line) fails with a log line only, so the caller gets a draw_failed.
|
|
152
|
+
// Like checkTimeAxes this runs only after a failed draw, so it only names a cause, and
|
|
153
|
+
// before checkOptionShapes: a type Chart.js does not know fails on its own. The lists come from Chart.js's registry. Run on the user's options and data.
|
|
154
|
+
function checkTypes(options, data) {
|
|
155
|
+
const refuse = (path, shown, kind) => {
|
|
156
|
+
throw new RenderError(`${path} ${shown} is not a registered type; use one of: ${suggested(kind).join(', ')}`, 'bad_option');
|
|
157
|
+
};
|
|
158
|
+
// Chart.js looks a type up as a key of its registry, so a non-string type is read as its string form
|
|
159
|
+
// (["linear"] is 'linear', 5 is '5', {} is '[object Object]'). A form that cannot be built (an object
|
|
160
|
+
// with its own toString) throws inside Chart.js too, so it counts as not registered.
|
|
161
|
+
const asKey = (type) => {
|
|
162
|
+
try {
|
|
163
|
+
return String(type);
|
|
164
|
+
}
|
|
165
|
+
catch {
|
|
166
|
+
return undefined;
|
|
167
|
+
}
|
|
168
|
+
};
|
|
169
|
+
// A string is quoted as before; anything else is shown as JSON, cut to 40 characters.
|
|
170
|
+
const show = (type) => (typeof type === 'string' ? `'${type.slice(0, 40)}'` : (JSON.stringify(type) ?? String(type)).slice(0, 40));
|
|
171
|
+
const known = (type, kind) => {
|
|
172
|
+
const key = asKey(type);
|
|
173
|
+
return key !== undefined && registered(kind).includes(key);
|
|
174
|
+
};
|
|
175
|
+
if (isObject(options) && isObject(options.scales)) {
|
|
176
|
+
for (const [name, scale] of Object.entries(options.scales)) {
|
|
177
|
+
// Every present axis type is read: null, false and 0 fail Chart.js too.
|
|
178
|
+
if (isObject(scale) && scale.type !== undefined && !known(scale.type, 'scales')) {
|
|
179
|
+
refuse(`options.scales.${name.slice(0, 40)}.type`, show(scale.type), 'scales');
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
if (isObject(data) && Array.isArray(data.datasets)) {
|
|
184
|
+
data.datasets.forEach((dataset, i) => {
|
|
185
|
+
// A falsy dataset type (null, false, 0, '') falls back to the chart type and draws, so it is no cause.
|
|
186
|
+
if (isObject(dataset) && dataset.type && !known(dataset.type, 'controllers')) {
|
|
187
|
+
refuse(`data.datasets[${i}].type`, show(dataset.type), 'controllers');
|
|
188
|
+
}
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
// Accepts the raw query/body values and returns a validated render request.
|
|
193
|
+
export function parseRequest({ c, w, h, bkg, dpr, theme, palette, preset }) {
|
|
194
|
+
// POST bodies may send the config as an object; it gets the same cap as a string.
|
|
195
|
+
const size = Buffer.byteLength(typeof c === 'string' ? c : (JSON.stringify(c) ?? ''));
|
|
196
|
+
if (size > LIMITS.maxConfigBytes)
|
|
197
|
+
throw new RenderError('chart config is larger than 16 KB', 'config_size');
|
|
198
|
+
// Repairs run only on what strict JSON would reject or what has a known fix; the checks below see the result.
|
|
199
|
+
const repaired = repairConfig(c, LIMITS.maxDepth);
|
|
200
|
+
if (!repaired)
|
|
201
|
+
throw new RenderError('chart config must be valid JSON', 'bad_json');
|
|
202
|
+
c = repaired.config;
|
|
203
|
+
if (!c || typeof c !== 'object' || Array.isArray(c))
|
|
204
|
+
throw new RenderError('missing chart config (c)', 'no_config');
|
|
205
|
+
// The v2 translation only renames keys (moving legend under a new plugins adds
|
|
206
|
+
// 12 bytes), so it never turns a config under the cap into one over it.
|
|
207
|
+
if (repaired.fixes.some((code) => !code.startsWith('v2_')) && Buffer.byteLength(JSON.stringify(c)) > LIMITS.maxConfigBytes) {
|
|
208
|
+
throw new RenderError('chart config is larger than 16 KB', 'config_size');
|
|
209
|
+
}
|
|
210
|
+
const config = c;
|
|
211
|
+
if (!CHART_TYPES.has(config.type))
|
|
212
|
+
throw new RenderError(`type must be one of: ${[...CHART_TYPES].join(', ')}`, 'bad_type');
|
|
213
|
+
if (!config.data || typeof config.data !== 'object')
|
|
214
|
+
throw new RenderError('chart config needs a data object', 'no_data');
|
|
215
|
+
checkConfig(config);
|
|
216
|
+
// An output preset (email, slack) fills in what the request left out; what it sent wins.
|
|
217
|
+
const style = styleFields({ theme, palette, preset });
|
|
218
|
+
checkStyle(style);
|
|
219
|
+
const output = outputPreset(config, style);
|
|
220
|
+
const given = output ? OUTPUT_DEFAULTS[output] : undefined;
|
|
221
|
+
const ratio = dpr == null || dpr === '' ? (given?.dpr ?? 1) : Number(dpr);
|
|
222
|
+
if (ratio !== 1 && ratio !== 2)
|
|
223
|
+
throw new RenderError('dpr must be 1 or 2', 'bad_dpr');
|
|
224
|
+
const background = typeof bkg === 'string' && bkg.length <= 32 ? bkg : '#ffffff';
|
|
225
|
+
return {
|
|
226
|
+
config: config,
|
|
227
|
+
width: toSide(w, given?.width ?? LIMITS.defaultWidth),
|
|
228
|
+
height: toSide(h, given?.height ?? LIMITS.defaultHeight),
|
|
229
|
+
// An inbox or a chat shows the image over its own colour: no transparency.
|
|
230
|
+
background: output && !isOpaque(background) ? '#ffffff' : background,
|
|
231
|
+
dpr: ratio,
|
|
232
|
+
fixes: repaired.fixes,
|
|
233
|
+
style,
|
|
234
|
+
output,
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
// Chart.js keeps a resolver for every distinct parsing key string for the life of the
|
|
238
|
+
// process (keyResolvers is never evicted), and it reads parsing from every option scope a
|
|
239
|
+
// dataset has (dataset.datasets.<type>, options.datasets.<type>, options.parsing). So no
|
|
240
|
+
// string from a request may reach it: the keys a request names are read here with a plain
|
|
241
|
+
// property access and copied onto three fixed names, and the request's own parsing keys are
|
|
242
|
+
// removed everywhere. Only short plain keys are honoured; a dotted path or a long key reads as
|
|
243
|
+
// unset. The other ways a request string reaches keyResolvers are closed too: _fallback and the
|
|
244
|
+
// other resolver descriptors are dropped in repair.ts, and scale ids are renamed (renameScales).
|
|
245
|
+
// keyResolvers then gains only fixed names, however many keys are sent.
|
|
246
|
+
const PARSING_KEY = /^[A-Za-z0-9_]{1,32}$/;
|
|
247
|
+
const PARSING_ALIASES = { xAxisKey: 'chartpngParseX', yAxisKey: 'chartpngParseY', key: 'chartpngParseKey' };
|
|
248
|
+
// The keys a dataset asks for: the first scope that sets parsing decides false or an object;
|
|
249
|
+
// objects are merged field by field, nearest scope first, as Chart.js merges them.
|
|
250
|
+
function effectiveParsing(scopes) {
|
|
251
|
+
const keys = {};
|
|
252
|
+
for (const scope of scopes) {
|
|
253
|
+
if (scope === false)
|
|
254
|
+
return Object.keys(keys).length ? keys : false;
|
|
255
|
+
if (!isObject(scope))
|
|
256
|
+
continue;
|
|
257
|
+
for (const field of Object.keys(PARSING_ALIASES)) {
|
|
258
|
+
const value = scope[field];
|
|
259
|
+
if (!(field in keys) && typeof value === 'string' && PARSING_KEY.test(value))
|
|
260
|
+
keys[field] = value;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
return Object.keys(keys).length ? keys : undefined;
|
|
264
|
+
}
|
|
265
|
+
// Options that set how big Chart.js draws an element, under any prefix (lineBorderWidth,
|
|
266
|
+
// pointHoverRadius, ...) and in any scope it reads them from (dataset, dataset.elements,
|
|
267
|
+
// dataset.datasets.<type>, options.elements, options.datasets...). The work of a fill grows
|
|
268
|
+
// with its area, and with layout.autoPadding off a point is not pushed out of view.
|
|
269
|
+
// barThickness and maxBarThickness too: with the theme off nothing else caps how wide a bar is.
|
|
270
|
+
const SIZE_KEY = /(radius|borderwidth|thickness)$/i;
|
|
271
|
+
// Clamps a size option (a number, a numeric string, or an array of them) to the bound.
|
|
272
|
+
function clampSize(value, bound) {
|
|
273
|
+
if (Array.isArray(value))
|
|
274
|
+
return value.map((item) => clampSize(item, bound));
|
|
275
|
+
const n = typeof value === 'number' ? value : typeof value === 'string' && value.trim() !== '' ? Number(value) : NaN;
|
|
276
|
+
return Number.isNaN(n) || n <= bound ? value : bound;
|
|
277
|
+
}
|
|
278
|
+
// A copy of an options tree with every size option clamped and every parsing option removed.
|
|
279
|
+
// Keys in `skip` are copied as they are at the top level (a dataset's data, options.plugins).
|
|
280
|
+
function limitTree(tree, bound, skip = [], depth = 0) {
|
|
281
|
+
if (!isObject(tree) || depth > LIMITS.maxDepth)
|
|
282
|
+
return tree;
|
|
283
|
+
const copy = {};
|
|
284
|
+
for (const [key, value] of Object.entries(tree)) {
|
|
285
|
+
if (key === 'parsing')
|
|
286
|
+
continue;
|
|
287
|
+
if (skip.includes(key))
|
|
288
|
+
copy[key] = value;
|
|
289
|
+
else if (SIZE_KEY.test(key))
|
|
290
|
+
copy[key] = clampSize(value, bound);
|
|
291
|
+
else
|
|
292
|
+
copy[key] = limitTree(value, bound, [], depth + 1);
|
|
293
|
+
}
|
|
294
|
+
return copy;
|
|
295
|
+
}
|
|
296
|
+
// A dataset with its parsing rewritten onto the fixed names and its sizes clamped.
|
|
297
|
+
function limitDataset(dataset, options, chartType, bound) {
|
|
298
|
+
if (!isObject(dataset))
|
|
299
|
+
return dataset;
|
|
300
|
+
const type = typeof dataset.type === 'string' ? dataset.type : chartType;
|
|
301
|
+
const parsing = effectiveParsing([dataset.parsing, isObject(options.datasets) ? options.datasets[type]?.parsing : undefined, options.parsing]);
|
|
302
|
+
const limited = limitTree(dataset, bound, ['data']);
|
|
303
|
+
if (parsing === false)
|
|
304
|
+
limited.parsing = false;
|
|
305
|
+
else if (parsing && Array.isArray(dataset.data)) {
|
|
306
|
+
limited.parsing = Object.fromEntries(Object.keys(parsing).map((field) => [field, PARSING_ALIASES[field]]));
|
|
307
|
+
limited.data = dataset.data.map((item) => {
|
|
308
|
+
if (!isObject(item))
|
|
309
|
+
return item;
|
|
310
|
+
const row = { ...item };
|
|
311
|
+
for (const [field, key] of Object.entries(parsing))
|
|
312
|
+
if (Object.hasOwn(item, key))
|
|
313
|
+
row[PARSING_ALIASES[field]] = item[key];
|
|
314
|
+
return row;
|
|
315
|
+
});
|
|
316
|
+
}
|
|
317
|
+
return limited;
|
|
318
|
+
}
|
|
319
|
+
// The bound is the canvas diagonal: a circle that big around any point already covers the
|
|
320
|
+
// canvas, so a larger radius draws the same pixels at a higher cost and no ordinary chart has
|
|
321
|
+
// one. It only trims the per-element cost; the total is bounded by the draw budget below.
|
|
322
|
+
function limitOptions(options, datasets, chartType, width, height) {
|
|
323
|
+
const bound = Math.hypot(width, height);
|
|
324
|
+
const limited = {
|
|
325
|
+
options: limitTree(options, bound, ['plugins']),
|
|
326
|
+
datasets: Array.isArray(datasets) ? datasets.map((dataset) => limitDataset(dataset, options, chartType, bound)) : undefined,
|
|
327
|
+
};
|
|
328
|
+
renameScales(limited.options, limited.datasets);
|
|
329
|
+
limitNumberFormats(limited.options);
|
|
330
|
+
return limited;
|
|
331
|
+
}
|
|
332
|
+
// Chart.js keeps one Intl.NumberFormat per locale + JSON of its options for the life of the
|
|
333
|
+
// process (intlCache is never evicted), and merges a scale's ticks.format into those options, so a
|
|
334
|
+
// request could add a formatter with every chart. So ticks.format never reaches Chart.js: a scale
|
|
335
|
+
// that sets one gets its tick labels from here, worked out as Chart.js's numeric formatter does,
|
|
336
|
+
// with formatters kept for this render only. The locale is cut to what Intl resolves it to, which
|
|
337
|
+
// is one of a finite set; a tag Intl cannot read is dropped, as if none were sent.
|
|
338
|
+
function resolvedLocale(value) {
|
|
339
|
+
if (typeof value !== 'string' || value.length > 64)
|
|
340
|
+
return undefined;
|
|
341
|
+
try {
|
|
342
|
+
return new Intl.NumberFormat(value).resolvedOptions().locale;
|
|
343
|
+
}
|
|
344
|
+
catch {
|
|
345
|
+
return undefined;
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
function limitNumberFormats(options) {
|
|
349
|
+
if ('locale' in options) {
|
|
350
|
+
const locale = resolvedLocale(options.locale);
|
|
351
|
+
if (locale)
|
|
352
|
+
options.locale = locale;
|
|
353
|
+
else
|
|
354
|
+
delete options.locale;
|
|
355
|
+
}
|
|
356
|
+
if (!isObject(options.scales))
|
|
357
|
+
return;
|
|
358
|
+
for (const scale of Object.values(options.scales)) {
|
|
359
|
+
if (!isObject(scale) || !isObject(scale.ticks) || !('format' in scale.ticks))
|
|
360
|
+
continue;
|
|
361
|
+
const { format, ...ticks } = scale.ticks;
|
|
362
|
+
if (ticks.callback === undefined && isObject(format))
|
|
363
|
+
ticks.callback = tickLabels(options.locale, format);
|
|
364
|
+
scale.ticks = ticks;
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
// Chart.js 4's formatters.numeric and formatters.logarithmic, with the caller's format applied
|
|
368
|
+
// last as Chart.js applies it, and the Intl.NumberFormat objects held by this render.
|
|
369
|
+
function tickLabels(locale, format) {
|
|
370
|
+
const formatters = new Map();
|
|
371
|
+
const number = (value, options) => {
|
|
372
|
+
const key = JSON.stringify(options);
|
|
373
|
+
let formatter = formatters.get(key);
|
|
374
|
+
if (!formatter)
|
|
375
|
+
formatters.set(key, (formatter = new Intl.NumberFormat(locale, options)));
|
|
376
|
+
return formatter.format(value);
|
|
377
|
+
};
|
|
378
|
+
const numeric = (value, ticks) => {
|
|
379
|
+
if (value === 0)
|
|
380
|
+
return '0';
|
|
381
|
+
let notation;
|
|
382
|
+
let delta = value;
|
|
383
|
+
if (ticks.length > 1) {
|
|
384
|
+
const maxTick = Math.max(Math.abs(ticks[0].value), Math.abs(ticks[ticks.length - 1].value));
|
|
385
|
+
if (maxTick < 1e-4 || maxTick > 1e15)
|
|
386
|
+
notation = 'scientific';
|
|
387
|
+
delta = ticks.length > 3 ? ticks[2].value - ticks[1].value : ticks[1].value - ticks[0].value;
|
|
388
|
+
if (Math.abs(delta) >= 1 && value !== Math.floor(value))
|
|
389
|
+
delta = value - Math.floor(value);
|
|
390
|
+
}
|
|
391
|
+
const logDelta = Math.log10(Math.abs(delta));
|
|
392
|
+
const digits = Number.isNaN(logDelta) ? 1 : Math.max(Math.min(-1 * Math.floor(logDelta), 20), 0);
|
|
393
|
+
return number(value, { notation, minimumFractionDigits: digits, maximumFractionDigits: digits, ...format });
|
|
394
|
+
};
|
|
395
|
+
return function (value, index, ticks) {
|
|
396
|
+
if (this.type === 'linear' || this.type === 'radialLinear')
|
|
397
|
+
return numeric(value, ticks);
|
|
398
|
+
if (this.type === 'logarithmic') {
|
|
399
|
+
if (value === 0)
|
|
400
|
+
return '0';
|
|
401
|
+
const remain = ticks[index].significand || value / Math.pow(10, Math.floor(Math.log10(value)));
|
|
402
|
+
return [1, 2, 3, 5, 10, 15].includes(remain) || index > 0.8 * ticks.length ? numeric(value, ticks) : '';
|
|
403
|
+
}
|
|
404
|
+
// Other scales never read ticks.format: they keep their own default labels.
|
|
405
|
+
const fallback = Chart.registry.getScale(this.type)?.defaults?.ticks?.callback;
|
|
406
|
+
return typeof fallback === 'function' ? fallback.call(this, value, index, ticks) : value;
|
|
407
|
+
};
|
|
408
|
+
}
|
|
409
|
+
// A scale id is a key Chart.js resolves through keyResolvers too (one entry per id, kept for the
|
|
410
|
+
// life of the process), so, like parsing keys, the ids a request names are not handed over. The
|
|
411
|
+
// default ids keep their names; every other id becomes one of a fixed set, and the datasets that
|
|
412
|
+
// point at it follow. keyResolvers then gains at most these names, whatever ids are sent.
|
|
413
|
+
const KEPT_SCALE_IDS = new Set(['x', 'y', 'r']);
|
|
414
|
+
export const MAX_SCALES = 16;
|
|
415
|
+
const SCALE_NAMES = Array.from({ length: MAX_SCALES }, (_, i) => `chartpngScale${i}`);
|
|
416
|
+
const AXIS_IDS = new Set(['x', 'y', 'r']);
|
|
417
|
+
// Chart.js's own rule (determineAxis): the axis option, else the position, else the first letter
|
|
418
|
+
// of a longer id. A renamed scale loses its id, so the axis it implied is written out.
|
|
419
|
+
function axisOf(id, scale) {
|
|
420
|
+
if (typeof scale.axis === 'string')
|
|
421
|
+
return scale.axis;
|
|
422
|
+
if (scale.position === 'top' || scale.position === 'bottom')
|
|
423
|
+
return 'x';
|
|
424
|
+
if (scale.position === 'left' || scale.position === 'right')
|
|
425
|
+
return 'y';
|
|
426
|
+
const first = id.charAt(0).toLowerCase();
|
|
427
|
+
return id.length > 1 && AXIS_IDS.has(first) ? first : undefined;
|
|
428
|
+
}
|
|
429
|
+
// Works on the copies limitOptions made, so the request itself is not changed.
|
|
430
|
+
const AXIS_FIELDS = ['xAxisID', 'yAxisID', 'rAxisID'];
|
|
431
|
+
function renameScales(options, datasets) {
|
|
432
|
+
const declared = isObject(options.scales) ? Object.keys(options.scales) : [];
|
|
433
|
+
// A dataset can name a scale the options never declare; Chart.js then makes it, under that id.
|
|
434
|
+
const referenced = (datasets ?? []).flatMap((dataset) => (isObject(dataset) ? AXIS_FIELDS.map((field) => dataset[field]) : [])).filter((id) => typeof id === 'string');
|
|
435
|
+
const ids = [...new Set([...declared, ...referenced])];
|
|
436
|
+
if (ids.every((id) => KEPT_SCALE_IDS.has(id)))
|
|
437
|
+
return;
|
|
438
|
+
if (ids.length > MAX_SCALES)
|
|
439
|
+
throw new RenderError(`a chart takes at most ${MAX_SCALES} scales`, 'bad_option');
|
|
440
|
+
const names = new Map();
|
|
441
|
+
let next = 0;
|
|
442
|
+
for (const id of ids)
|
|
443
|
+
names.set(id, KEPT_SCALE_IDS.has(id) ? id : SCALE_NAMES[next++]);
|
|
444
|
+
if (isObject(options.scales)) {
|
|
445
|
+
const scales = {};
|
|
446
|
+
for (const id of declared) {
|
|
447
|
+
const scale = options.scales[id];
|
|
448
|
+
const name = names.get(id);
|
|
449
|
+
const axis = name !== id && isObject(scale) ? axisOf(id, scale) : undefined;
|
|
450
|
+
scales[name] = axis ? { ...scale, axis } : scale;
|
|
451
|
+
}
|
|
452
|
+
options.scales = scales;
|
|
453
|
+
}
|
|
454
|
+
for (const dataset of datasets ?? []) {
|
|
455
|
+
if (!isObject(dataset))
|
|
456
|
+
continue;
|
|
457
|
+
for (const field of AXIS_FIELDS) {
|
|
458
|
+
const id = dataset[field];
|
|
459
|
+
if (typeof id === 'string')
|
|
460
|
+
dataset[field] = names.get(id);
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
const backgroundPlugin = {
|
|
465
|
+
id: 'background',
|
|
466
|
+
beforeDraw(chart, _args, { color }) {
|
|
467
|
+
const { ctx, width, height } = chart;
|
|
468
|
+
ctx.save();
|
|
469
|
+
ctx.fillStyle = color;
|
|
470
|
+
ctx.fillRect(0, 0, width, height);
|
|
471
|
+
ctx.restore();
|
|
472
|
+
},
|
|
473
|
+
};
|
|
474
|
+
const FOOTER = { margin: 8, height: 14, gap: 8, radius: 3.5 };
|
|
475
|
+
// options.plugins.chartpng.source as a single short line, or undefined.
|
|
476
|
+
function sourceLine(config) {
|
|
477
|
+
const source = config.options?.plugins?.chartpng?.source;
|
|
478
|
+
const line = typeof source === 'string' ? source.replace(/\s+/g, ' ').trim().slice(0, 300) : '';
|
|
479
|
+
return line || undefined;
|
|
480
|
+
}
|
|
481
|
+
// The strip a footer needs under the chart, measured from the image's bottom edge.
|
|
482
|
+
const FOOTER_STRIP = 24;
|
|
483
|
+
// Chart.js layout padding (a number or per-side) as four sides whose bottom is at
|
|
484
|
+
// least the footer strip, so the footer wins over any padding the config set.
|
|
485
|
+
function reserveFooter(padding) {
|
|
486
|
+
const all = typeof padding === 'number' ? padding : 8;
|
|
487
|
+
const sides = (padding && typeof padding === 'object' ? padding : {});
|
|
488
|
+
const side = (value) => (value != null && Number.isFinite(Number(value)) ? Number(value) : all);
|
|
489
|
+
return {
|
|
490
|
+
top: side(sides.top ?? sides.y),
|
|
491
|
+
right: side(sides.right ?? sides.x),
|
|
492
|
+
bottom: Math.max(side(sides.bottom ?? sides.y), FOOTER_STRIP),
|
|
493
|
+
left: side(sides.left ?? sides.x),
|
|
494
|
+
};
|
|
495
|
+
}
|
|
496
|
+
// Cuts text to fit maxWidth, ending in an ellipsis. The context's font must be set.
|
|
497
|
+
function ellipsize(ctx, text, maxWidth) {
|
|
498
|
+
if (ctx.measureText(text).width <= maxWidth)
|
|
499
|
+
return text;
|
|
500
|
+
let end = text.length;
|
|
501
|
+
while (end > 0 && ctx.measureText(`${text.slice(0, end).trimEnd()}…`).width > maxWidth)
|
|
502
|
+
end--;
|
|
503
|
+
return end > 0 ? `${text.slice(0, end).trimEnd()}…` : '';
|
|
504
|
+
}
|
|
505
|
+
const footerPlugin = {
|
|
506
|
+
id: 'chartpngFooter',
|
|
507
|
+
afterDraw(chart, _args, { background, watermark, source, chipSize = 10.5 }) {
|
|
508
|
+
if (!watermark && !source)
|
|
509
|
+
return;
|
|
510
|
+
const { ctx, width, height } = chart;
|
|
511
|
+
const { margin, gap, radius } = FOOTER;
|
|
512
|
+
const middle = height - margin - FOOTER.height / 2;
|
|
513
|
+
ctx.save();
|
|
514
|
+
let right = width - margin;
|
|
515
|
+
if (watermark) {
|
|
516
|
+
// On its own opaque chip, so no background colour can hide it.
|
|
517
|
+
const chip = chipFor(background);
|
|
518
|
+
ctx.font = `600 ${chipSize}px ${FONT_STACK}`;
|
|
519
|
+
const padding = 12;
|
|
520
|
+
const textWidth = ctx.measureText(watermark).width;
|
|
521
|
+
// On a very narrow image the chip would run off the left edge: shrink the type to fit between the margins.
|
|
522
|
+
const room = Math.max(width - 2 * margin - padding, 1);
|
|
523
|
+
if (textWidth > room)
|
|
524
|
+
ctx.font = `600 ${(chipSize * room) / textWidth}px ${FONT_STACK}`;
|
|
525
|
+
const chipWidth = Math.ceil(Math.min(textWidth, room)) + padding;
|
|
526
|
+
const x = width - margin - chipWidth;
|
|
527
|
+
ctx.beginPath();
|
|
528
|
+
addRoundedRectPath(ctx, { x, y: height - margin - FOOTER.height, w: chipWidth, h: FOOTER.height, radius: { topLeft: radius, topRight: radius, bottomLeft: radius, bottomRight: radius } });
|
|
529
|
+
ctx.fillStyle = chip.fill;
|
|
530
|
+
ctx.fill();
|
|
531
|
+
ctx.strokeStyle = chip.stroke;
|
|
532
|
+
ctx.lineWidth = 1;
|
|
533
|
+
ctx.stroke();
|
|
534
|
+
ctx.fillStyle = chip.text;
|
|
535
|
+
ctx.textAlign = 'center';
|
|
536
|
+
ctx.textBaseline = 'middle';
|
|
537
|
+
ctx.fillText(watermark, x + chipWidth / 2, middle + 0.5);
|
|
538
|
+
right = x - gap;
|
|
539
|
+
}
|
|
540
|
+
if (source) {
|
|
541
|
+
ctx.font = `11px ${FONT_STACK}`;
|
|
542
|
+
ctx.fillStyle = inkFor(background).muted;
|
|
543
|
+
ctx.textAlign = 'left';
|
|
544
|
+
ctx.textBaseline = 'middle';
|
|
545
|
+
ctx.fillText(ellipsize(ctx, source, right - margin), margin, middle + 0.5);
|
|
546
|
+
}
|
|
547
|
+
ctx.restore();
|
|
548
|
+
},
|
|
549
|
+
};
|
|
550
|
+
// Chart.js 4 rounds the axis end up to a step; near the largest double that
|
|
551
|
+
// overflows to Infinity and its tick loop never ends, eating all memory. Data,
|
|
552
|
+
// grace and min/max all feed the range, so it is checked once it is final.
|
|
553
|
+
const MAX_AXIS_VALUE = 1e300;
|
|
554
|
+
// A pie or doughnut has no scale to check, and a slice near the largest double
|
|
555
|
+
// makes Chart.js loop forever drawing its arc: the data itself is checked too.
|
|
556
|
+
const tooLarge = (value) => {
|
|
557
|
+
// A point is an object or an array, and a pie reads its slice from any key (parsing.key),
|
|
558
|
+
// so every value one level down is checked, not only x, y and r.
|
|
559
|
+
if (value !== null && typeof value === 'object')
|
|
560
|
+
return Object.values(value).some((v) => (v === null || typeof v !== 'object') && tooLarge(v));
|
|
561
|
+
const n = typeof value === 'number' ? value : typeof value === 'string' ? Number(value) : NaN;
|
|
562
|
+
return Number.isFinite(n) && Math.abs(n) > MAX_AXIS_VALUE;
|
|
563
|
+
};
|
|
564
|
+
// Fill work the chart may ask for, in canvases. An ordinary chart fills well under one canvas
|
|
565
|
+
// (a few hundred points of radius 3 are a few thousand pixels); this is a ceiling that leaves
|
|
566
|
+
// room for large markers and thick lines, while a request that covers the canvas hundreds of
|
|
567
|
+
// times is refused. It is read from the options Chart.js resolved, so it holds for every scope
|
|
568
|
+
// and for bubble radii that come from the data.
|
|
569
|
+
const DRAW_BUDGET_CANVASES = 32;
|
|
570
|
+
const num = (value) => (typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0);
|
|
571
|
+
const ARC_TYPES = new Set(['pie', 'doughnut', 'polarArea']);
|
|
572
|
+
// The final geometry Chart.js laid out (animation is off, so it is already in place).
|
|
573
|
+
function barArea(element) {
|
|
574
|
+
if (typeof element?.getProps !== 'function')
|
|
575
|
+
return 0;
|
|
576
|
+
const { x, y, base, width, height, horizontal } = element.getProps(['x', 'y', 'base', 'width', 'height', 'horizontal'], true);
|
|
577
|
+
return horizontal ? num(Math.abs(height)) * num(Math.abs(x - base)) : num(Math.abs(width)) * num(Math.abs(y - base));
|
|
578
|
+
}
|
|
579
|
+
function arcArea(element) {
|
|
580
|
+
if (typeof element?.getProps !== 'function')
|
|
581
|
+
return 0;
|
|
582
|
+
const { innerRadius, outerRadius, circumference } = element.getProps(['innerRadius', 'outerRadius', 'circumference'], true);
|
|
583
|
+
const sweep = Math.min(num(Math.abs(circumference)), 2 * Math.PI);
|
|
584
|
+
return (sweep / 2) * Math.max(num(outerRadius) ** 2 - num(innerRadius) ** 2, 0);
|
|
585
|
+
}
|
|
586
|
+
function drawCost(chart) {
|
|
587
|
+
const area = chart.width * chart.height;
|
|
588
|
+
const diagonal = Math.hypot(chart.width, chart.height);
|
|
589
|
+
let cost = 0;
|
|
590
|
+
chart.data.datasets.forEach((_dataset, index) => {
|
|
591
|
+
if (!chart.isDatasetVisible(index))
|
|
592
|
+
return;
|
|
593
|
+
const meta = chart.getDatasetMeta(index);
|
|
594
|
+
let previous;
|
|
595
|
+
let length = 0;
|
|
596
|
+
for (const element of meta.data) {
|
|
597
|
+
// A bar fills its rectangle and an arc its ring sector: bars stacked on one another, or as
|
|
598
|
+
// wide as the canvas, cost as much as the points and lines below.
|
|
599
|
+
if (meta.type === 'bar')
|
|
600
|
+
cost += Math.min(barArea(element), area);
|
|
601
|
+
else if (ARC_TYPES.has(meta.type))
|
|
602
|
+
cost += Math.min(arcArea(element), area);
|
|
603
|
+
const radius = num(element?.options?.radius);
|
|
604
|
+
if (radius > 0)
|
|
605
|
+
cost += Math.min(Math.PI * (radius + num(element.options.borderWidth) / 2) ** 2, area);
|
|
606
|
+
if (Number.isFinite(element?.x) && Number.isFinite(element?.y)) {
|
|
607
|
+
if (previous)
|
|
608
|
+
length += Math.min(Math.hypot(element.x - previous.x, element.y - previous.y), diagonal);
|
|
609
|
+
previous = element;
|
|
610
|
+
}
|
|
611
|
+
else
|
|
612
|
+
previous = undefined;
|
|
613
|
+
}
|
|
614
|
+
// A stroked line covers its length times its width.
|
|
615
|
+
if (meta.type === 'line' || meta.type === 'radar')
|
|
616
|
+
cost += Math.min(length * num(meta.dataset?.options?.borderWidth), area);
|
|
617
|
+
});
|
|
618
|
+
return cost;
|
|
619
|
+
}
|
|
620
|
+
const rangeGuardPlugin = {
|
|
621
|
+
id: 'chartpngRangeGuard',
|
|
622
|
+
beforeUpdate(chart) {
|
|
623
|
+
for (const dataset of chart.data.datasets) {
|
|
624
|
+
if (Array.isArray(dataset?.data) && dataset.data.some(tooLarge)) {
|
|
625
|
+
throw new RenderError('numbers in the chart are too large to draw', 'number_range');
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
},
|
|
629
|
+
beforeDatasetsDraw(chart) {
|
|
630
|
+
// Parsed values past the guard's limit loop in drawArc whatever key they came from.
|
|
631
|
+
for (let i = 0; i < chart.data.datasets.length; i++) {
|
|
632
|
+
for (const parsed of chart.getDatasetMeta(i)._parsed) {
|
|
633
|
+
if (tooLarge(parsed))
|
|
634
|
+
throw new RenderError('numbers in the chart are too large to draw', 'number_range');
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
if (drawCost(chart) > DRAW_BUDGET_CANVASES * chart.width * chart.height)
|
|
638
|
+
throw new RenderError('the chart draws too much for this image size', 'draw_budget');
|
|
639
|
+
return undefined;
|
|
640
|
+
},
|
|
641
|
+
beforeBuildTicks(_chart, { scale }) {
|
|
642
|
+
const range = scale._range ?? scale;
|
|
643
|
+
for (const value of [range.min, range.max, scale.min, scale.max]) {
|
|
644
|
+
if (Number.isFinite(value) && Math.abs(value) > MAX_AXIS_VALUE) {
|
|
645
|
+
throw new RenderError('numbers in the chart are too large to draw', 'number_range');
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
},
|
|
649
|
+
};
|
|
650
|
+
// Destroys the chart a failed constructor left registered for this canvas.
|
|
651
|
+
function releaseChart(canvas) {
|
|
652
|
+
const stale = Chart.getChart(canvas);
|
|
653
|
+
if (!stale)
|
|
654
|
+
return;
|
|
655
|
+
try {
|
|
656
|
+
stale.destroy();
|
|
657
|
+
}
|
|
658
|
+
catch {
|
|
659
|
+
// destroy() can trip over the half-built chart that made the draw fail.
|
|
660
|
+
}
|
|
661
|
+
// Still registered: drop the reference ourselves.
|
|
662
|
+
for (const [id, chart] of Object.entries(Chart.instances))
|
|
663
|
+
if (chart === stale)
|
|
664
|
+
delete Chart.instances[id];
|
|
665
|
+
}
|
|
666
|
+
// Chart.js draws inside its constructor (animation is off), so any option it
|
|
667
|
+
// cannot handle throws there. That is the config's fault: a 400 with a generic
|
|
668
|
+
// message, and the stack in the logs in case it is ours. When an option has the
|
|
669
|
+
// wrong shape, the 400 is a bad_option naming its path in the user's options.
|
|
670
|
+
function drawChart(ctx, config, userOptions, userData) {
|
|
671
|
+
try {
|
|
672
|
+
return new Chart(ctx, config);
|
|
673
|
+
}
|
|
674
|
+
catch (error) {
|
|
675
|
+
// The constructor registers the chart in Chart.instances before it draws, so a throw
|
|
676
|
+
// would leave it and its full-size canvas referenced for the life of the instance.
|
|
677
|
+
releaseChart(ctx.canvas);
|
|
678
|
+
if (error instanceof RenderError)
|
|
679
|
+
throw error;
|
|
680
|
+
// The request's fault, so a warning and not an error; the stack stays in case it is ours.
|
|
681
|
+
console.warn(JSON.stringify({
|
|
682
|
+
event: 'draw_failed',
|
|
683
|
+
message: error instanceof Error ? error.message : String(error),
|
|
684
|
+
stack: error instanceof Error ? error.stack : undefined,
|
|
685
|
+
}));
|
|
686
|
+
// Most certain first: an unknown non-empty or time type breaks the draw on its own, while a
|
|
687
|
+
// mis-shaped option may be harmless (a hidden axis never reads its grid), so a shape
|
|
688
|
+
// is named only when no type is to blame.
|
|
689
|
+
checkTimeAxes(userOptions);
|
|
690
|
+
checkTypes(userOptions, userData);
|
|
691
|
+
checkOptionShapes(userOptions);
|
|
692
|
+
throw new RenderError('could not draw this chart with these options', 'draw_failed');
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
export function renderPng({ config: sent, width, height, background, dpr, style, output }, { watermark } = {}) {
|
|
696
|
+
// Logical size; Chart.js multiplies it by devicePixelRatio itself.
|
|
697
|
+
const canvas = createCanvas(width, height);
|
|
698
|
+
// theme=, palette= and preset= fill in what the config did not set.
|
|
699
|
+
const config = style ? withStyle(sent, style) : sent;
|
|
700
|
+
const drawn = applyPreset(config, background);
|
|
701
|
+
const limited = limitOptions(drawn.options, drawn.data.datasets, config.type, width, height);
|
|
702
|
+
const data = limited.datasets ? { ...drawn.data, datasets: limited.datasets } : drawn.data;
|
|
703
|
+
// An output preset keeps all type at 11 px or more, unless the config turned the theme off.
|
|
704
|
+
const options = output && config.options?.plugins?.chartpng?.theme !== false ? floorFonts(limited.options) : limited.options;
|
|
705
|
+
const source = sourceLine(config);
|
|
706
|
+
const layout = { padding: 8, ...options.layout };
|
|
707
|
+
// Reserve a strip under the chart so the watermark and the source never cover axis labels.
|
|
708
|
+
if (watermark || source)
|
|
709
|
+
layout.padding = reserveFooter(layout.padding);
|
|
710
|
+
// @napi-rs/canvas implements the 2D context Chart.js expects, under its own type.
|
|
711
|
+
const ctx = canvas.getContext('2d');
|
|
712
|
+
const chart = drawChart(ctx, {
|
|
713
|
+
type: config.type,
|
|
714
|
+
data,
|
|
715
|
+
options: {
|
|
716
|
+
...options,
|
|
717
|
+
layout,
|
|
718
|
+
responsive: false,
|
|
719
|
+
animation: false,
|
|
720
|
+
devicePixelRatio: dpr,
|
|
721
|
+
plugins: {
|
|
722
|
+
...(isObject(options.plugins) ? options.plugins : {}),
|
|
723
|
+
// Pinned after the spread: Chart.js skips a plugin whose option is false, so a
|
|
724
|
+
// request must not be able to name any of these. The guard has no options of its own.
|
|
725
|
+
background: { color: background },
|
|
726
|
+
chartpngFooter: { background, watermark, source, chipSize: output ? OUTPUT_MIN_FONT : undefined },
|
|
727
|
+
chartpngRangeGuard: {},
|
|
728
|
+
},
|
|
729
|
+
},
|
|
730
|
+
plugins: [rangeGuardPlugin, backgroundPlugin, valuesPlugin, presetPlugin, footerPlugin],
|
|
731
|
+
}, config.options, config.data);
|
|
732
|
+
try {
|
|
733
|
+
return canvas.toBuffer('image/png');
|
|
734
|
+
}
|
|
735
|
+
finally {
|
|
736
|
+
chart.destroy();
|
|
737
|
+
}
|
|
738
|
+
}
|