imagescript 4.0.0-rc.5 → 4.0.0-rc.6

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.
@@ -17,10 +17,11 @@ import { gunzip } from "../codecs/zlib.js";
17
17
  import { applyFilter } from "./filter.js";
18
18
  import { multiply, invert } from "../util/matrix.js";
19
19
  import { BLEND_MODES, blendPixel } from "./blend.js";
20
- import { fontFace, layOutText, parseFontFamilies, parseVariationSettings, pathLength, placeOutline, colorTablesOf } from "./svg-text.js";
20
+ import { fontFace, givenFontFace, damaged, layOutText, parseFontFamilies, parseVariationSettings, pathLength, placeOutline, colorTablesOf } from "./svg-text.js";
21
21
  import { rasterizeGlyph } from "./text.js";
22
22
  import { renderPaintGlyph } from "./colr.js";
23
23
  import { decodeSync as decodePNG } from "../codecs/png.js";
24
+ import { bitmapPixels, MAX_BITMAP_GLYPH_PIXELS } from "./color.js";
24
25
  import { MAX_PIXELS, LimitError } from "../util/limits.js";
25
26
  const UNSUPPORTED = new Set(['filter', 'pattern', 'marker', 'foreignObject', 'script', 'style', 'title', 'desc', 'metadata',
26
27
  'defs', 'clipPath', 'mask', 'linearGradient', 'radialGradient', 'stop', 'symbol', 'font', 'font-face', 'animate', 'animateTransform', 'animateMotion', 'set']);
@@ -61,7 +62,7 @@ export function render(source, mode, size, images = new Map(), fonts = [], maxPi
61
62
  throw new Error('SVG: no <svg> element');
62
63
  const doc = new Document(root);
63
64
  doc.images = images;
64
- doc.given = fonts.map(data => fontFace(data)).filter(face => face !== null);
65
+ doc.given = fonts.map(givenFontFace);
65
66
  const { width, height } = documentSize(root);
66
67
  if (!(width > 0) || !(height > 0))
67
68
  throw new Error('SVG: invalid dimensions');
@@ -81,12 +82,25 @@ export function render(source, mode, size, images = new Map(), fonts = [], maxPi
81
82
  outWidth = Math.max(1, outWidth);
82
83
  outHeight = Math.max(1, outHeight);
83
84
  if (!Number.isSafeInteger(outWidth) || !Number.isSafeInteger(outHeight))
84
- throw new RangeError(`SVG output dimensions are too large: ${outWidth}x${outHeight}`);
85
+ throw new LimitError(`SVG too large to render: ${outWidth}x${outHeight} pixels`);
85
86
  if (!(outWidth * outHeight <= maxPixels))
86
87
  throw new LimitError(`SVG too large to render: ${outWidth}x${outHeight} pixels exceed the limit of ${maxPixels} (the render options' maxPixels)`);
87
- const previous = layerBudget, previousCrossings = crossingsLeft;
88
+ const previous = layerBudget, previousCrossings = crossingsLeft, previousFilterWork = filterWorkLeft, previousPaint = paintLeft, previousPoints = pointsLeft;
88
89
  layerBudget = { left: maxLayerPixels, limit: maxLayerPixels };
89
90
  crossingsLeft = MAX_CROSSINGS;
91
+ filterWorkLeft = MAX_FILTER_WORK + FILTER_WORK_PER_PIXEL * outWidth * outHeight;
92
+ paintLeft = MAX_PAINT + PAINT_PER_PIXEL * outWidth * outHeight;
93
+ const previousPaths = parsedPaths, previousCached = cachedCommands;
94
+ if (!previousPaths)
95
+ pointsLeft = MAX_POINTS + POINTS_PER_PIXEL * outWidth * outHeight;
96
+ parsedPaths = new Map();
97
+ const previousBitmaps = decodedBitmaps, previousBitmapPixels = decodedBitmapPixels;
98
+ if (!decodedBitmaps) {
99
+ decodedBitmaps = new WeakMap();
100
+ decodedBitmapPixels = 0;
101
+ }
102
+ if (!previousPaths)
103
+ cachedCommands = 0;
90
104
  try {
91
105
  const canvas = new Layer(outWidth, outHeight);
92
106
  doc.renderRoot([outWidth / width, 0, 0, outHeight / height, 0, 0], canvas, 0);
@@ -95,6 +109,15 @@ export function render(source, mode, size, images = new Map(), fonts = [], maxPi
95
109
  finally {
96
110
  layerBudget = previous;
97
111
  crossingsLeft = previousCrossings;
112
+ filterWorkLeft = previousFilterWork;
113
+ paintLeft = previousPaint;
114
+ if (!previousPaths)
115
+ pointsLeft = previousPoints;
116
+ parsedPaths = previousPaths;
117
+ decodedBitmaps = previousBitmaps;
118
+ if (!previousBitmaps)
119
+ decodedBitmapPixels = previousBitmapPixels;
120
+ cachedCommands = previousCached;
98
121
  }
99
122
  }
100
123
  let layerBudget = null;
@@ -189,7 +212,8 @@ export function imageReferences(source) {
189
212
  const stack = [root];
190
213
  while (stack.length) {
191
214
  const node = stack.pop();
192
- stack.push(...node.children);
215
+ for (const child of node.children)
216
+ stack.push(child);
193
217
  if ((node.name !== 'image' && node.name !== 'feImage') || !node.svg)
194
218
  continue;
195
219
  const href = (node.attrs.href || node.attrs['xlink:href'] || '').trim();
@@ -234,7 +258,7 @@ function parseXML(text) {
234
258
  return match;
235
259
  size += custom[name].length - match.length;
236
260
  if (size > limit)
237
- throw new Error('SVG: entity expansion exceeds the size limit');
261
+ throw new LimitError('SVG too complex: entity expansion exceeds the size limit');
238
262
  return custom[name];
239
263
  });
240
264
  }
@@ -563,6 +587,7 @@ function validProperty(name, value) {
563
587
  }
564
588
  }
565
589
  const MAX_INSTANCES = 100000;
590
+ const MAX_MARKERS = 10000;
566
591
  const MAX_OCTAVES = 24;
567
592
  const DASH_BATCH = 20000;
568
593
  function take(iterator, n) {
@@ -579,9 +604,35 @@ const MAX_NESTED = 2 ** 26, MIN_NESTED = 2 ** 16;
579
604
  const MAX_DASHES = 1000000;
580
605
  const MAX_CROSSINGS = 2 ** 27;
581
606
  let crossingsLeft = Infinity;
607
+ const MAX_FILTER_WORK = 2 ** 25, FILTER_WORK_PER_PIXEL = 16;
608
+ let filterWorkLeft = Infinity;
609
+ const MAX_PAINT = 2 ** 28, PAINT_PER_PIXEL = 64;
610
+ let paintLeft = Infinity;
611
+ function charge(pixels) {
612
+ if ((paintLeft -= pixels) < 0)
613
+ throw new LimitError(`SVG too complex: its shapes and layers paint more pixels than a render of this size allows (${MAX_PAINT} and ${PAINT_PER_PIXEL} per output pixel)`);
614
+ }
615
+ const filterBudget = {
616
+ work(pixels) {
617
+ if ((filterWorkLeft -= pixels) < 0)
618
+ throw new LimitError(`SVG too complex: its filters' primitives work on more pixels than a render of this size allows (${MAX_FILTER_WORK} and ${FILTER_WORK_PER_PIXEL} per output pixel)`);
619
+ },
620
+ keep(pixels) {
621
+ const budget = layerBudget;
622
+ if (!budget)
623
+ return;
624
+ if (!(pixels <= budget.left))
625
+ throw new LimitError(`SVG too complex: its layers (for opacity, masks, filters, ...) exceed ${budget.limit} pixels at once (the render options' maxLayerPixels)`);
626
+ budget.left -= pixels;
627
+ },
628
+ free(pixels) {
629
+ if (layerBudget)
630
+ layerBudget.left += pixels;
631
+ }
632
+ };
582
633
  const MAX_TILE = 4096 * 1024;
583
634
  class Document {
584
- budget = { instances: 0, nested: 0, nesting: 0 };
635
+ budget = { instances: 0, markers: 0, nested: 0, nesting: 0 };
585
636
  ids;
586
637
  active;
587
638
  root;
@@ -619,7 +670,8 @@ class Document {
619
670
  const stack = [this.root];
620
671
  while (stack.length) {
621
672
  const node = stack.pop();
622
- stack.push(...node.children);
673
+ for (const child of node.children)
674
+ stack.push(child);
623
675
  if (node.name !== 'feImage' || !node.parent || !node.parent.attrs.id)
624
676
  continue;
625
677
  const href = this.href(node)?.trim(), target = href?.startsWith('#') ? this.reference(href) : null;
@@ -637,11 +689,12 @@ class Document {
637
689
  return inline?.important[name] ?? inline?.normal[name] ?? node.attrs[name];
638
690
  };
639
691
  const descendants = (node) => {
640
- const list = [], stack = [...node.children];
692
+ const list = [], stack = [...node.children].reverse();
641
693
  while (stack.length) {
642
- const n = stack.shift();
694
+ const n = stack.pop();
643
695
  list.push(n);
644
- stack.unshift(...n.children);
696
+ for (let i = n.children.length - 1; i >= 0; i--)
697
+ stack.push(n.children[i]);
645
698
  }
646
699
  return list;
647
700
  };
@@ -754,7 +807,7 @@ class Document {
754
807
  if (!node.svg || UNSUPPORTED.has(node.name) || context.depth > 32 || !this.passesConditions(node))
755
808
  return;
756
809
  if (context.instanced && ++this.budget.instances > MAX_INSTANCES)
757
- throw new Error(`SVG: more than ${MAX_INSTANCES} elements rendered through <use> references or embedded SVGs`);
810
+ throw new LimitError(`SVG too complex: more than ${MAX_INSTANCES} elements rendered through <use> references, markers or embedded SVGs`);
758
811
  const style = this.computeStyle(node, context.style);
759
812
  if (style.display === 'none')
760
813
  return;
@@ -906,16 +959,32 @@ class Document {
906
959
  const fonts = this.fonts;
907
960
  if (fonts.length) {
908
961
  try {
909
- layout = layOutText(this.textInput(node, style, viewport, scale), fonts);
962
+ layout = layOutText(this.textInput(node, style, viewport, scale), fonts, this.given[0] ?? fonts[0]);
910
963
  }
911
964
  catch (err) {
912
- if (!(err instanceof RangeError))
965
+ if (!(err instanceof RangeError) || err instanceof LimitError)
913
966
  throw err;
967
+ if (this.given.length && this.givenFontsFail(node, style, viewport, scale))
968
+ throw damaged(err);
914
969
  }
915
970
  }
971
+ if (layout)
972
+ for (const span of layout.spans)
973
+ glyphPaths.add(span.glyphs);
916
974
  this.texts.set(node, { style, width: viewport.width, height: viewport.height, scale, layout });
917
975
  return layout;
918
976
  }
977
+ givenFontsFail(node, style, viewport, scale) {
978
+ if (!this.embedded.length)
979
+ return true;
980
+ try {
981
+ layOutText(this.textInput(node, style, viewport, scale), this.given);
982
+ return false;
983
+ }
984
+ catch (err) {
985
+ return err instanceof RangeError && !(err instanceof LimitError);
986
+ }
987
+ }
919
988
  textInput(text, textStyle, viewport, scale) {
920
989
  const leaves = [];
921
990
  const preserveOf = (node, inherited) => node.attrs['xml:space'] === undefined ? inherited : node.attrs['xml:space'] === 'preserve';
@@ -1142,13 +1211,14 @@ class Document {
1142
1211
  };
1143
1212
  collect(root);
1144
1213
  const mode = textStyle['writing-mode'];
1145
- return { chunks, dx, dy, rotate: rotations, vertical: mode === 'tb' || mode === 'tb-rl' || mode === 'vertical-rl' || mode === 'vertical-lr', scale };
1214
+ return { chunks, dx, dy, rotate: rotations, vertical: mode === 'tb' || mode === 'tb-rl' || mode === 'vertical-rl' || mode === 'vertical-lr', scale, charge: commands => chargePoints(GLYPH_COMMAND_POINTS * commands) };
1146
1215
  }
1147
1216
  textPathOf(node, viewport, fontSize) {
1148
1217
  const target = this.reference(this.href(node));
1149
1218
  const raw = target ? shapePath(target, viewport, fontSize) : null;
1150
1219
  if (!target || !raw || !raw.length)
1151
1220
  return null;
1221
+ chargePoints(16 * raw.length);
1152
1222
  const m = target.attrs.transform ? originTransform(target.attrs.transform, target.attrs['transform-origin'], viewport) : null;
1153
1223
  const path = m ? raw.map(c => [c[0], ...transformPoints(c.slice(1), m)]) : raw;
1154
1224
  const offset = (node.attrs.startOffset ?? '').trim();
@@ -1171,8 +1241,17 @@ class Document {
1171
1241
  paint(d.path, d.paint, 'normal');
1172
1242
  if (span.glyphs.length)
1173
1243
  paint(span.glyphs, span.paint, span.paint['paint-order']);
1174
- for (const glyph of span.colors)
1175
- this.renderColorGlyph(glyph, span.paint, node, ctx, paint);
1244
+ for (const glyph of span.colors) {
1245
+ try {
1246
+ this.renderColorGlyph(glyph, span.paint, node, ctx, paint);
1247
+ }
1248
+ catch (err) {
1249
+ if (!(err instanceof RangeError) || err instanceof LimitError)
1250
+ throw err;
1251
+ if (this.given.includes(glyph.face))
1252
+ throw damaged(err);
1253
+ }
1254
+ }
1176
1255
  for (const d of span.after)
1177
1256
  paint(d.path, d.paint, 'normal');
1178
1257
  }
@@ -1208,13 +1287,9 @@ class Document {
1208
1287
  const bitmap = tables.bitmaps(Math.round(s * font.unitsPerEm))?.(g.glyph) ?? tables.bitmaps(g.fontSize)?.(g.glyph);
1209
1288
  if (!bitmap)
1210
1289
  return;
1211
- let decoded;
1212
- try {
1213
- decoded = decodePNG(bitmap.png);
1214
- }
1215
- catch {
1290
+ const decoded = decodedBitmap(bitmap.png);
1291
+ if (!decoded)
1216
1292
  return;
1217
- }
1218
1293
  const k = font.unitsPerEm / bitmap.ppem;
1219
1294
  let left = bitmap.left * k, top = bitmap.top * k;
1220
1295
  if (font.tables.sbix && !font.tables.CBDT) {
@@ -1281,7 +1356,9 @@ class Document {
1281
1356
  for (const span of layout.spans)
1282
1357
  if (span.visible)
1283
1358
  for (const part of [...span.before, { path: span.glyphs }, ...span.after])
1284
- path.push(...part.path);
1359
+ for (const command of part.path)
1360
+ path.push(command);
1361
+ glyphPaths.add(path);
1285
1362
  return path.length ? path : null;
1286
1363
  }
1287
1364
  renderImage(node, ctx) {
@@ -1490,7 +1567,9 @@ class Document {
1490
1567
  matrix = multiply(matrix, [cos, sin, -sin, cos, 0, 0]);
1491
1568
  }
1492
1569
  matrix = multiply(matrix, [sx * units, 0, 0, sy * units, -refX * sx * units, -refY * sy * units]);
1493
- const inner = { ...ctx, matrix, style: markerStyle, depth: ctx.depth + 1, viewport: viewBox ? { width: viewBox[2], height: viewBox[3] } : ctx.viewport, contextElement };
1570
+ if (++this.budget.markers > MAX_MARKERS)
1571
+ throw new LimitError(`SVG too complex: more than ${MAX_MARKERS} markers`);
1572
+ const inner = { ...ctx, matrix, style: markerStyle, depth: ctx.depth + 1, viewport: viewBox ? { width: viewBox[2], height: viewBox[3] } : ctx.viewport, contextElement, instanced: true };
1494
1573
  this.active.add(marker);
1495
1574
  this.indirect(0, () => {
1496
1575
  if (!clip)
@@ -1773,7 +1852,7 @@ class Document {
1773
1852
  lh = Math.min(ly + lh, Math.ceil(cy1)) - top;
1774
1853
  lx = left;
1775
1854
  ly = top;
1776
- if (lw <= 0 || lh <= 0 || lw * lh > 1 << 26)
1855
+ if (lw <= 0 || lh <= 0)
1777
1856
  return;
1778
1857
  const shifted = multiply([1, 0, 0, 1, -lx, -ly], scaled);
1779
1858
  const layer = new Layer(lw, lh);
@@ -1781,7 +1860,7 @@ class Document {
1781
1860
  const pixmap = layer.toPixmap();
1782
1861
  layer.release();
1783
1862
  for (const filter of filters)
1784
- applyFilter(filter, shifted, pixmap);
1863
+ applyFilter(filter, shifted, pixmap, filterBudget);
1785
1864
  const result = Layer.fromPixmap(pixmap);
1786
1865
  if (result.x1 <= result.x0)
1787
1866
  return result.release();
@@ -2181,7 +2260,7 @@ class Document {
2181
2260
  indirect(pixels, render) {
2182
2261
  const budget = this.budget;
2183
2262
  if (budget.nesting > 0 && (budget.nested += Math.max(pixels, MIN_NESTED)) > MAX_NESTED)
2184
- throw new Error('SVG: too many masks, clip paths, patterns, markers or filter images inside each other');
2263
+ throw new LimitError('SVG too complex: too many masks, clip paths, patterns, markers or filter images inside each other');
2185
2264
  budget.nesting++;
2186
2265
  try {
2187
2266
  return render();
@@ -2671,6 +2750,7 @@ class Layer {
2671
2750
  }
2672
2751
  fill({ x0, y0, w, h, data }, paint) {
2673
2752
  const d = this.data;
2753
+ let painted = 0;
2674
2754
  const solid = paint.solid;
2675
2755
  this.extend(x0, y0, x0 + w, y0 + h);
2676
2756
  for (let y = 0; y < h; y++) {
@@ -2679,6 +2759,7 @@ class Layer {
2679
2759
  const c = data[o];
2680
2760
  if (c <= 0)
2681
2761
  continue;
2762
+ painted++;
2682
2763
  const color = solid || paint(x0 + x + 0.5, y0 + y + 0.5);
2683
2764
  const a = color[3] * c;
2684
2765
  if (a <= 0)
@@ -2693,6 +2774,7 @@ class Layer {
2693
2774
  while (x + run < w && data[o + run] >= 1)
2694
2775
  run++;
2695
2776
  if (run > 1) {
2777
+ painted += run - 1;
2696
2778
  for (let filled = 1; filled < run; filled *= 2)
2697
2779
  d.copyWithin(i + filled * 4, i, i + Math.min(filled, run - filled) * 4);
2698
2780
  x += run - 1;
@@ -2709,6 +2791,7 @@ class Layer {
2709
2791
  d[i + 3] = a + d[i + 3] * inv;
2710
2792
  }
2711
2793
  }
2794
+ charge(painted + (w * h >> 4));
2712
2795
  }
2713
2796
  toPixmap() {
2714
2797
  const d = this.data, out = new Uint8Array(d.length);
@@ -2750,6 +2833,7 @@ class Layer {
2750
2833
  composite(layer, opacity, mask, blend = 'normal') {
2751
2834
  if (layer.x1 <= layer.x0)
2752
2835
  return;
2836
+ charge((layer.x1 - layer.x0) * (layer.y1 - layer.y0));
2753
2837
  this.extend(layer.x0, layer.y0, layer.x1, layer.y1);
2754
2838
  const s = layer.data, d = this.data;
2755
2839
  if (blend !== 'normal') {
@@ -3001,8 +3085,16 @@ function rasterize(polygons, evenOdd, width, height) {
3001
3085
  function shapePath(node, viewport, fontSize) {
3002
3086
  const length = (name, axis, fallback = 0) => node.attrs[name] === undefined ? fallback : parseLength(node.attrs[name], viewport, fontSize, axis);
3003
3087
  switch (node.name) {
3004
- case 'path':
3005
- return parsePath(node.attrs.d || '');
3088
+ case 'path': {
3089
+ const d = node.attrs.d || '';
3090
+ const cached = parsedPaths?.get(d);
3091
+ if (cached)
3092
+ return cached;
3093
+ const path = parsePath(d);
3094
+ if (parsedPaths && (cachedCommands += path.length) <= MAX_CACHED_COMMANDS)
3095
+ parsedPaths.set(d, path);
3096
+ return path;
3097
+ }
3006
3098
  case 'rect': {
3007
3099
  const x = length('x', 'x'), y = length('y', 'y');
3008
3100
  const w = length('width', 'x'), h = length('height', 'y');
@@ -3074,8 +3166,55 @@ function shapePath(node, viewport, fontSize) {
3074
3166
  }
3075
3167
  return null;
3076
3168
  }
3169
+ const MAX_POINTS = 2 ** 25, POINTS_PER_PIXEL = 4, MAX_PATH_POINTS = 2 ** 21;
3170
+ let pointsLeft = Infinity;
3171
+ let parsedPaths = null, cachedCommands = 0;
3172
+ const glyphPaths = new WeakSet();
3173
+ let decodedBitmaps = null, decodedBitmapPixels = 0;
3174
+ const MAX_KEPT_BITMAP_PIXELS = 2 ** 22;
3175
+ function decodedBitmap(png) {
3176
+ let kept = decodedBitmaps?.get(png.buffer);
3177
+ const key = png.byteOffset * 2 ** 21 + Math.min(png.length, 2 ** 21 - 1);
3178
+ const cached = kept?.get(key);
3179
+ if (cached !== undefined)
3180
+ return cached;
3181
+ let decoded = null;
3182
+ const declared = bitmapPixels(png);
3183
+ if (declared <= MAX_BITMAP_GLYPH_PIXELS) {
3184
+ charge(4 * Math.max(declared, 1));
3185
+ try {
3186
+ decoded = decodePNG(png, MAX_BITMAP_GLYPH_PIXELS);
3187
+ }
3188
+ catch {
3189
+ decoded = null;
3190
+ }
3191
+ }
3192
+ const pixels = decoded ? decoded.width * decoded.height : 0;
3193
+ if (decodedBitmaps && decodedBitmapPixels + pixels <= MAX_KEPT_BITMAP_PIXELS) {
3194
+ decodedBitmapPixels += pixels;
3195
+ if (!kept)
3196
+ decodedBitmaps.set(png.buffer, kept = new Map());
3197
+ kept.set(key, decoded);
3198
+ }
3199
+ return decoded;
3200
+ }
3201
+ const MAX_CACHED_COMMANDS = 2 ** 20;
3202
+ function pointCounter() {
3203
+ let pathPoints = 0;
3204
+ return points => {
3205
+ pathPoints += points;
3206
+ if ((pointsLeft -= points) < 0 || pathPoints > MAX_PATH_POINTS)
3207
+ throw new LimitError(`SVG too complex: its paths are made of more points than a render of this size allows (${MAX_PATH_POINTS} in a path, ${MAX_POINTS} and ${POINTS_PER_PIXEL} per output pixel in all)`);
3208
+ };
3209
+ }
3210
+ const GLYPH_COMMAND_POINTS = 16;
3211
+ function chargePoints(points) {
3212
+ if ((pointsLeft -= points) < 0)
3213
+ pointCounter()(0);
3214
+ }
3077
3215
  function parsePath(d) {
3078
3216
  const path = [];
3217
+ const count = pointCounter();
3079
3218
  const items = [];
3080
3219
  let end = 0;
3081
3220
  for (const m of d.matchAll(PATH_TOKENS)) {
@@ -3084,6 +3223,7 @@ function parsePath(d) {
3084
3223
  end = m.index + m[0].length;
3085
3224
  items.push(m[1] ? { command: m[1] } : m[2]);
3086
3225
  }
3226
+ chargePoints(2 * items.length);
3087
3227
  let i = 0;
3088
3228
  let command = null;
3089
3229
  let x = 0, y = 0, sx = 0, sy = 0;
@@ -3199,7 +3339,7 @@ function parsePath(d) {
3199
3339
  const nx = number() + ox, ny = number() + oy;
3200
3340
  if ([rx, ry, rotation, large, sweep, nx, ny].some(isNaN))
3201
3341
  return path;
3202
- arcToCubics(path, x, y, rx, ry, rotation, large, sweep, nx, ny);
3342
+ arcToCubics(path, x, y, rx, ry, rotation, large, sweep, nx, ny, count);
3203
3343
  x = nx;
3204
3344
  y = ny;
3205
3345
  }
@@ -3209,7 +3349,7 @@ function parsePath(d) {
3209
3349
  }
3210
3350
  return path;
3211
3351
  }
3212
- function arcToCubics(path, x1, y1, rx, ry, rotation, large, sweep, x2, y2) {
3352
+ function arcToCubics(path, x1, y1, rx, ry, rotation, large, sweep, x2, y2, count = () => { }) {
3213
3353
  if (x1 === x2 && y1 === y2)
3214
3354
  return;
3215
3355
  rx = Math.abs(rx);
@@ -3245,8 +3385,9 @@ function arcToCubics(path, x1, y1, rx, ry, rotation, large, sweep, x2, y2) {
3245
3385
  delta -= 2 * Math.PI;
3246
3386
  else if (sweep && delta < 0)
3247
3387
  delta += 2 * Math.PI;
3248
- const perTurn = Math.max(Math.pow(1.1163 * Math.max(rx, ry) / 0.1, 1 / 6), 3.999999);
3388
+ const perTurn = Math.min(Math.max(Math.pow(1.1163 * Math.max(rx, ry) / 0.1, 1 / 6), 3.999999), 64);
3249
3389
  const segments = Math.max(1, Math.ceil(perTurn * Math.abs(delta) / (2 * Math.PI)));
3390
+ count(4 * segments);
3250
3391
  const step = delta / segments;
3251
3392
  const k = 4 / 3 * Math.tan(step / 4);
3252
3393
  const point = (t) => [cx + rx * Math.cos(t) * cos - ry * Math.sin(t) * sin, cy + rx * Math.cos(t) * sin + ry * Math.sin(t) * cos];
@@ -3261,6 +3402,7 @@ function arcToCubics(path, x1, y1, rx, ry, rotation, large, sweep, x2, y2) {
3261
3402
  }
3262
3403
  }
3263
3404
  function flatten(path, tolerance) {
3405
+ const count = glyphPaths.has(path) ? chargePoints : pointCounter();
3264
3406
  const subpaths = [];
3265
3407
  let current = null;
3266
3408
  let x = 0, y = 0, sx = 0, sy = 0;
@@ -3274,9 +3416,11 @@ function flatten(path, tolerance) {
3274
3416
  case 'M':
3275
3417
  x = sx = command[1];
3276
3418
  y = sy = command[2];
3419
+ count(1);
3277
3420
  current = start(x, y);
3278
3421
  break;
3279
3422
  case 'L':
3423
+ count(1);
3280
3424
  if (!current)
3281
3425
  current = start(x, y);
3282
3426
  x = command[1];
@@ -3290,6 +3434,7 @@ function flatten(path, tolerance) {
3290
3434
  const ddx = Math.max(Math.abs(x - 2 * c1x + c2x), Math.abs(c1x - 2 * c2x + ex));
3291
3435
  const ddy = Math.max(Math.abs(y - 2 * c1y + c2y), Math.abs(c1y - 2 * c2y + ey));
3292
3436
  const n = Math.min(512, Math.max(1, Math.ceil(Math.sqrt(0.75 * Math.hypot(ddx, ddy) / tolerance))));
3437
+ count(n);
3293
3438
  for (let i = 1; i <= n; i++) {
3294
3439
  const t = i / n, mt = 1 - t;
3295
3440
  current.points.push(mt * mt * mt * x + 3 * mt * mt * t * c1x + 3 * mt * t * t * c2x + t * t * t * ex, mt * mt * mt * y + 3 * mt * mt * t * c1y + 3 * mt * t * t * c2y + t * t * t * ey);
@@ -4,8 +4,9 @@
4
4
  */
5
5
  import { Font } from "./font.js";
6
6
  import { Hinter } from "./hinting.js";
7
- import { parseColorLayers, parseBitmaps } from "./color.js";
7
+ import { parseColorLayers, parseBitmaps, bitmapPixels, MAX_BITMAP_GLYPH_PIXELS } from "./color.js";
8
8
  import { shapeFont, shapeRun, isDefaultIgnorableCodepoint } from "./shape.js";
9
+ import { shown } from "../util/options.js";
9
10
  import "./shapers/index.js";
10
11
  import { classOf, resolve, lineLevels } from "./bidi.js";
11
12
  import { lineBreaks } from "./linebreak.js";
@@ -40,7 +41,7 @@ export function axisValues(variations) {
40
41
  throw new RangeError(`Unknown font variation ${key}: use weight, width, slant, italic, opticalSize or an axis tag`);
41
42
  const v = typeof value === 'boolean' ? +value : value;
42
43
  if (typeof v !== 'number')
43
- throw new TypeError(`The font variation ${key} must be a number or a boolean, not ${v === null ? 'null' : typeof v}`);
44
+ throw new TypeError(`The font variation ${key} must be a number or a boolean, not ${shown(v)}`);
44
45
  if (!Number.isFinite(v))
45
46
  throw new RangeError(`Invalid font variation ${key}: ${String(value)}`);
46
47
  values[tag] = v;
@@ -67,8 +68,10 @@ function sizedFont(data, size, hinting, variations) {
67
68
  let shared = colorTables.get(font);
68
69
  if (!shared)
69
70
  colorTables.set(font, shared = { layers: parseColorLayers(font), paints: parsePaintGlyphs(font) });
70
- if (bySize.size >= SIZES)
71
+ if (bySize.size >= SIZES) {
71
72
  bySize.clear();
73
+ keptBytes.delete(font);
74
+ }
72
75
  bySize.set(key, sized = { font, scale: size / font.unitsPerEm, hinter, layers: shared.layers, bitmaps: parseBitmaps(font, size), paints: shared.paints, shaping: shapeFont(font), glyphs: new Map() });
73
76
  return sized;
74
77
  }
@@ -126,7 +129,8 @@ async function layOut(fonts, size, text, layout, hinting, foreground, features,
126
129
  const paragraphs = text.split(/\r\n|[\r\n\u0085\u2028\u2029]/);
127
130
  const lines = [];
128
131
  for (const paragraph of paragraphs)
129
- lines.push(...layOutParagraph(analyze(paragraph, fonts.length, font), layout, font, size, features));
132
+ for (const line of layOutParagraph(analyze(paragraph, fonts.length, font), layout, font, size, features))
133
+ lines.push(line);
130
134
  let visible = lines;
131
135
  if (layout.height !== undefined) {
132
136
  const count = Math.max(1, Math.floor(layout.height / lineHeight));
@@ -136,7 +140,10 @@ async function layOut(fonts, size, text, layout, hinting, foreground, features,
136
140
  visible = lines.slice(start, start + count);
137
141
  }
138
142
  }
139
- const width = layout.width ?? Math.max(1, Math.ceil(Math.max(0, ...visible.map(line => line.extent))));
143
+ let extent = 0;
144
+ for (const line of visible)
145
+ extent = Math.max(extent, line.extent);
146
+ const width = layout.width ?? Math.max(1, Math.ceil(extent));
140
147
  const height = layout.height ?? visible.length * lineHeight;
141
148
  const free = height - visible.length * lineHeight;
142
149
  const top = layout.verticalAlign === 'bottom' ? free : layout.verticalAlign === 'middle' ? Math.floor(free / 2) : 0;
@@ -144,6 +151,24 @@ async function layOut(fonts, size, text, layout, hinting, foreground, features,
144
151
  throw new LimitError(`Text too large to render: ${width + 2 * pad}x${height + 2 * pad} pixels exceed the limit of ${maxPixels} (the render options' maxPixels)`);
145
152
  const coverage = new Uint8Array(width * height);
146
153
  let color = null;
154
+ const budget = { left: 2 ** 28 + 64 * width * height, image: width * height };
155
+ const scaled = new Map();
156
+ let scaledPixels = 0;
157
+ const local = new Map();
158
+ let localBytes = 0;
159
+ const keep = (g, key, raster, withFont) => {
160
+ const bytes = raster ? raster.data.length : 0;
161
+ if (keptWithFont(g, bytes))
162
+ withFont();
163
+ else if (localBytes + bytes <= 2 ** 26) {
164
+ localBytes += bytes;
165
+ let rasters = local.get(g);
166
+ if (!rasters)
167
+ local.set(g, rasters = new Map());
168
+ rasters.set(key, raster);
169
+ }
170
+ return raster;
171
+ };
147
172
  for (const [n, line] of visible.entries()) {
148
173
  const align = layout.horizontalAlign ?? (line.rtl ? 'right' : 'left');
149
174
  let offset = align === 'right' ? width - line.extent : align === 'center' ? (width - line.extent - line.start) / 2 : -line.start;
@@ -162,24 +187,53 @@ async function layOut(fonts, size, text, layout, hinting, foreground, features,
162
187
  subpixel = 0;
163
188
  const key = 'bitmap' in g.color ? '0' : `${subpixel}:${foreground}`;
164
189
  let bitmap = g.colors.get(key);
165
- if (bitmap === undefined)
166
- g.colors.set(key, bitmap = 'bitmap' in g.color
167
- ? await scaledBitmap(g.color.bitmap, size / g.color.bitmap.ppem)
168
- : 'layers' in g.color ? layeredGlyph(g, g.color.layers, subpixel / SUBPIXELS, foreground)
169
- : paintedGlyph(g, subpixel / SUBPIXELS, foreground));
190
+ if ('bitmap' in g.color) {
191
+ bitmap = scaled.get(g);
192
+ if (bitmap === undefined) {
193
+ bitmap = await scaledBitmap(g.color.bitmap, size / g.color.bitmap.ppem, budget);
194
+ const pixels = bitmap ? bitmap.width * bitmap.height : 0;
195
+ if (scaledPixels + pixels <= 2 ** 22) {
196
+ scaledPixels += pixels;
197
+ scaled.set(g, bitmap);
198
+ }
199
+ }
200
+ }
201
+ else if (bitmap === undefined) {
202
+ bitmap = local.get(g)?.get(key);
203
+ if (bitmap === undefined) {
204
+ const made = 'layers' in g.color ? layeredGlyph(g, g.color.layers, subpixel / SUBPIXELS, foreground) : paintedGlyph(g, subpixel / SUBPIXELS, foreground);
205
+ spend(budget, made ? made.width * made.height : 0);
206
+ bitmap = g.colors.size < 8 ? keep(g, key, made, () => g.colors.set(key, made)) : keep(g, key, made, () => { });
207
+ }
208
+ }
170
209
  if (bitmap)
171
210
  blitColor(color ??= new Uint8ClampedArray(width * height * 4), width, height, bitmap, pixel + bitmap.left, y - bitmap.top);
172
211
  continue;
173
212
  }
174
- if (g.bitmaps[subpixel] === undefined)
175
- g.bitmaps[subpixel] = rasterizeGlyph(g.path, g.scale, subpixel / SUBPIXELS);
176
- const bitmap = g.bitmaps[subpixel];
213
+ let bitmap = g.bitmaps[subpixel];
214
+ if (bitmap === undefined)
215
+ bitmap = local.get(g)?.get(`${subpixel}`);
216
+ if (bitmap === undefined) {
217
+ const made = rasterizeGlyph(g.path, g.scale, subpixel / SUBPIXELS);
218
+ spend(budget, made ? made.width * made.height : 0);
219
+ bitmap = keep(g, `${subpixel}`, made, () => g.bitmaps[subpixel] = made);
220
+ }
177
221
  if (bitmap)
178
222
  blit(coverage, width, height, bitmap, pixel + bitmap.left, y - bitmap.top);
179
223
  }
180
224
  }
181
225
  return { width, height, coverage, color };
182
226
  }
227
+ const keptBytes = new WeakMap();
228
+ function keptWithFont(g, bytes) {
229
+ if (bytes > 2 ** 18)
230
+ return false;
231
+ const kept = (keptBytes.get(g.font.font) ?? 0) + bytes;
232
+ if (kept > 2 ** 22)
233
+ return false;
234
+ keptBytes.set(g.font.font, kept);
235
+ return true;
236
+ }
183
237
  function analyze(text, count, font) {
184
238
  const codepoints = Array.from(text, char => char.codePointAt(0));
185
239
  const n = codepoints.length;
@@ -203,7 +257,7 @@ function analyze(text, count, font) {
203
257
  }
204
258
  return first;
205
259
  };
206
- const normalized = (grapheme, form) => Array.from(String.fromCodePoint(...grapheme).normalize(form), char => char.codePointAt(0));
260
+ const normalized = (grapheme, form) => Array.from(grapheme.map(c => String.fromCodePoint(c)).join('').normalize(form), char => char.codePointAt(0));
207
261
  const graphemes = graphemeBoundaries(codepoints), fontOf = new Int32Array(n);
208
262
  for (let start = 0; start < n;) {
209
263
  let end = start + 1;
@@ -334,9 +388,9 @@ function layOutParagraph(p, layout, font, size, features) {
334
388
  ranges.push([lineStart, fit]);
335
389
  lineStart = fit;
336
390
  }
391
+ const shifted = new Int8Array(n);
337
392
  return ranges.map(([start, end]) => {
338
393
  const levels = lineLevels(p.bidi, start, end);
339
- const shifted = new Int8Array(n);
340
394
  shifted.set(levels, start);
341
395
  const { glyphs } = ranges.length === 1 ? whole : shapeRange(p, start, end, shifted, font, size, features);
342
396
  let extent = 0, left = Infinity;
@@ -348,15 +402,26 @@ function layOutParagraph(p, layout, font, size, features) {
348
402
  return { glyphs, extent, start: rtl && left < Infinity ? Math.max(0, left) : 0, rtl };
349
403
  });
350
404
  }
351
- async function scaledBitmap(glyph, scale) {
405
+ function spend(budget, pixels) {
406
+ if ((budget.left -= pixels) < 0)
407
+ throw new LimitError('Text too complex: its glyphs take more work to decode, scale and rasterize than an image of this size allows (2^28 pixels and 64 per pixel of the image)');
408
+ }
409
+ async function scaledBitmap(glyph, scale, budget) {
410
+ const declared = bitmapPixels(glyph.png);
411
+ if (!(declared <= MAX_BITMAP_GLYPH_PIXELS))
412
+ return null;
413
+ spend(budget, 4 * Math.max(declared, 1));
352
414
  let decoded;
353
415
  try {
354
- decoded = await decodePNG(glyph.png);
416
+ decoded = await decodePNG(glyph.png, MAX_BITMAP_GLYPH_PIXELS);
355
417
  }
356
418
  catch {
357
419
  return null;
358
420
  }
359
421
  const width = Math.max(1, Math.round(decoded.width * scale)), height = Math.max(1, Math.round(decoded.height * scale));
422
+ if (width * height > Math.max(MAX_BITMAP_GLYPH_PIXELS, 4 * budget.image))
423
+ return null;
424
+ spend(budget, width * height);
360
425
  const data = new Uint8ClampedArray(width * height * 4);
361
426
  resample(new Uint8ClampedArray(decoded.pixels.buffer, decoded.pixels.byteOffset, decoded.pixels.length), decoded.width, decoded.height, width, height, TRIANGLE, data, true);
362
427
  premultiply(data);