imagescript 4.0.0-rc.3 → 4.0.0-rc.5

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.
@@ -21,7 +21,7 @@ import { fontFace, layOutText, parseFontFamilies, parseVariationSettings, pathLe
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 { MAX_PIXELS, LimitError, checkPixels } from "../util/limits.js";
24
+ import { MAX_PIXELS, LimitError } from "../util/limits.js";
25
25
  const UNSUPPORTED = new Set(['filter', 'pattern', 'marker', 'foreignObject', 'script', 'style', 'title', 'desc', 'metadata',
26
26
  'defs', 'clipPath', 'mask', 'linearGradient', 'radialGradient', 'stop', 'symbol', 'font', 'font-face', 'animate', 'animateTransform', 'animateMotion', 'set']);
27
27
  const INHERITED = new Set(['fill', 'fill-opacity', 'fill-rule', 'stroke', 'stroke-width', 'stroke-opacity', 'stroke-linecap', 'stroke-linejoin',
@@ -82,9 +82,11 @@ export function render(source, mode, size, images = new Map(), fonts = [], maxPi
82
82
  outHeight = Math.max(1, outHeight);
83
83
  if (!Number.isSafeInteger(outWidth) || !Number.isSafeInteger(outHeight))
84
84
  throw new RangeError(`SVG output dimensions are too large: ${outWidth}x${outHeight}`);
85
- checkPixels(outWidth, outHeight, maxPixels);
86
- const previous = layerBudget;
85
+ if (!(outWidth * outHeight <= maxPixels))
86
+ 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;
87
88
  layerBudget = { left: maxLayerPixels, limit: maxLayerPixels };
89
+ crossingsLeft = MAX_CROSSINGS;
88
90
  try {
89
91
  const canvas = new Layer(outWidth, outHeight);
90
92
  doc.renderRoot([outWidth / width, 0, 0, outHeight / height, 0, 0], canvas, 0);
@@ -92,6 +94,7 @@ export function render(source, mode, size, images = new Map(), fonts = [], maxPi
92
94
  }
93
95
  finally {
94
96
  layerBudget = previous;
97
+ crossingsLeft = previousCrossings;
95
98
  }
96
99
  }
97
100
  let layerBudget = null;
@@ -104,7 +107,11 @@ function documentSize(root) {
104
107
  return fallback * parseFloat(value) / 100;
105
108
  return parseLength(value, null, 16);
106
109
  };
107
- return { width: lengthOf(root.attrs.width, viewBox ? viewBox[2] : 100), height: lengthOf(root.attrs.height, viewBox ? viewBox[3] : 100) };
110
+ const width = lengthOf(root.attrs.width, viewBox ? viewBox[2] : 100), height = lengthOf(root.attrs.height, viewBox ? viewBox[3] : 100);
111
+ const given = (value) => value !== undefined && value !== 'auto';
112
+ if (viewBox && viewBox[2] > 0 && viewBox[3] > 0 && given(root.attrs.width) !== given(root.attrs.height))
113
+ return given(root.attrs.width) ? { width, height: width * viewBox[3] / viewBox[2] } : { width: height * viewBox[2] / viewBox[3], height };
114
+ return { width, height };
108
115
  }
109
116
  const glyphDocuments = new WeakMap();
110
117
  function drawRaster(layer, image, matrix, filter) {
@@ -557,8 +564,21 @@ function validProperty(name, value) {
557
564
  }
558
565
  const MAX_INSTANCES = 100000;
559
566
  const MAX_OCTAVES = 24;
567
+ const DASH_BATCH = 20000;
568
+ function take(iterator, n) {
569
+ const items = [];
570
+ while (items.length < n) {
571
+ const next = iterator.next();
572
+ if (next.done)
573
+ break;
574
+ items.push(next.value);
575
+ }
576
+ return items;
577
+ }
560
578
  const MAX_NESTED = 2 ** 26, MIN_NESTED = 2 ** 16;
561
579
  const MAX_DASHES = 1000000;
580
+ const MAX_CROSSINGS = 2 ** 27;
581
+ let crossingsLeft = Infinity;
562
582
  const MAX_TILE = 4096 * 1024;
563
583
  class Document {
564
584
  budget = { instances: 0, nested: 0, nesting: 0 };
@@ -1380,16 +1400,51 @@ class Document {
1380
1400
  const strokeWidth = parseLength(style['stroke-width'], ctx.viewport, 16, 'diagonal');
1381
1401
  if (!stroke || !(strokeWidth > 0))
1382
1402
  return;
1383
- let lines = subpaths;
1403
+ const lines = subpaths;
1384
1404
  const fontSize = parseNumber(style['font-size'], 16);
1385
1405
  const dashes = parseDashArray(style['stroke-dasharray'], ctx.viewport, fontSize);
1386
- if (dashes)
1387
- lines = dash(subpaths, dashes, parseLength(style['stroke-dashoffset'], ctx.viewport, fontSize, 'diagonal'));
1388
- const polygons = strokePolygons(lines, strokeWidth / 2, style['stroke-linecap'], style['stroke-linejoin'], Math.max(1, parseNumber(style['stroke-miterlimit'], 4)), tolerance).map(points => transformPoints(points, matrix));
1389
- const coverage = rasterize(polygons, false, layer.width, layer.height);
1406
+ const miterLimit = Math.max(1, parseNumber(style['stroke-miterlimit'], 4));
1407
+ if (dashes) {
1408
+ const reach = strokeWidth / 2 * Math.max(miterLimit, Math.SQRT2) * Math.hypot(matrix[0], matrix[1], matrix[2], matrix[3]) + 1;
1409
+ const visible = (points) => {
1410
+ let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
1411
+ for (let i = 0; i < points.length; i += 2) {
1412
+ const x = matrix[0] * points[i] + matrix[2] * points[i + 1] + matrix[4], y = matrix[1] * points[i] + matrix[3] * points[i + 1] + matrix[5];
1413
+ x0 = Math.min(x0, x);
1414
+ x1 = Math.max(x1, x);
1415
+ y0 = Math.min(y0, y);
1416
+ y1 = Math.max(y1, y);
1417
+ }
1418
+ return !(x1 + reach <= 0 || x0 - reach >= layer.width || y1 + reach <= 0 || y0 - reach >= layer.height);
1419
+ };
1420
+ const generated = dash(subpaths, dashes, parseLength(style['stroke-dashoffset'], ctx.viewport, fontSize, 'diagonal'), visible);
1421
+ let total = null;
1422
+ for (let batch = take(generated, DASH_BATCH); batch.length; batch = take(generated, DASH_BATCH)) {
1423
+ const coverage = this.strokeCoverage(batch, strokeWidth, miterLimit, tolerance, ctx);
1424
+ if (!coverage)
1425
+ continue;
1426
+ if (batch.length < DASH_BATCH && !total) {
1427
+ total = coverage;
1428
+ break;
1429
+ }
1430
+ total ??= { x0: 0, y0: 0, w: layer.width, h: layer.height, data: new Float32Array(layer.width * layer.height) };
1431
+ for (let y = 0; y < coverage.h; y++)
1432
+ for (let x = 0, o = y * coverage.w, t = (coverage.y0 + y) * total.w + coverage.x0; x < coverage.w; x++)
1433
+ total.data[t + x] = Math.min(1, total.data[t + x] + coverage.data[o + x]);
1434
+ }
1435
+ if (total)
1436
+ layer.fill(crisp(total, style), stroke);
1437
+ return;
1438
+ }
1439
+ const coverage = this.strokeCoverage(lines, strokeWidth, miterLimit, tolerance, ctx);
1390
1440
  if (coverage)
1391
1441
  layer.fill(crisp(coverage, style), stroke);
1392
1442
  }
1443
+ strokeCoverage(lines, strokeWidth, miterLimit, tolerance, ctx) {
1444
+ const style = ctx.style;
1445
+ const polygons = strokePolygons(lines, strokeWidth / 2, style['stroke-linecap'], style['stroke-linejoin'], miterLimit, tolerance).map(points => transformPoints(points, ctx.matrix));
1446
+ return rasterize(polygons, false, ctx.layer.width, ctx.layer.height);
1447
+ }
1393
1448
  renderMarkers(path, bbox, node, ctx) {
1394
1449
  const style = ctx.style;
1395
1450
  for (let p = node.parent; p; p = p.parent)
@@ -2772,6 +2827,20 @@ function rasterize(polygons, evenOdd, width, height) {
2772
2827
  const n = points.length >> 1;
2773
2828
  if (n < 2)
2774
2829
  continue;
2830
+ let px0 = Infinity, py0 = Infinity, px1 = -Infinity, py1 = -Infinity;
2831
+ for (let i = 0; i < n; i++) {
2832
+ const x = points[i * 2], y = points[i * 2 + 1];
2833
+ if (x < px0)
2834
+ px0 = x;
2835
+ if (x > px1)
2836
+ px1 = x;
2837
+ if (y < py0)
2838
+ py0 = y;
2839
+ if (y > py1)
2840
+ py1 = y;
2841
+ }
2842
+ if (px1 <= 0 || px0 >= width || py1 <= 0 || py0 >= height)
2843
+ continue;
2775
2844
  for (let i = 0; i < n; i++) {
2776
2845
  const ax = points[i * 2], ay = points[i * 2 + 1];
2777
2846
  const j = (i + 1) % n;
@@ -2816,7 +2885,6 @@ function rasterize(polygons, evenOdd, width, height) {
2816
2885
  order[placed[startRow(e)]++] = e;
2817
2886
  let numActive = 0;
2818
2887
  const active = scratch.i32(4, numEdges), keys = scratch.f64(4, numEdges), firsts = scratch.i32(5, numEdges), lasts = scratch.i32(6, numEdges);
2819
- const counts = new Int32Array(SAMPLES), starts = new Int32Array(SAMPLES), ends = new Int32Array(SAMPLES);
2820
2888
  const span = (a, b) => {
2821
2889
  a = Math.max(a, x0) - x0;
2822
2890
  b = Math.min(b, x1) - x0;
@@ -2840,11 +2908,10 @@ function rasterize(polygons, evenOdd, width, height) {
2840
2908
  if (bottoms[active[k]] > py)
2841
2909
  active[kept++] = active[k];
2842
2910
  numActive = kept;
2843
- for (let k = rowStarts[py - y0]; k < rowStarts[py - y0 + 1]; k++)
2844
- active[numActive++] = order[k];
2845
2911
  const mid = py + 0.5;
2846
- for (let k = 0; k < numActive; k++) {
2847
- const e = active[k], key = xs[e] + (Math.min(Math.max(mid, tops[e]), bottoms[e]) - tops[e]) * slopes[e];
2912
+ const keyOf = (e) => xs[e] + (Math.min(Math.max(mid, tops[e]), bottoms[e]) - tops[e]) * slopes[e];
2913
+ for (let k = 0; k < kept; k++) {
2914
+ const e = active[k], key = keyOf(e);
2848
2915
  let j = k - 1;
2849
2916
  for (; j >= 0 && keys[j] > key; j--) {
2850
2917
  keys[j + 1] = keys[j];
@@ -2853,8 +2920,28 @@ function rasterize(polygons, evenOdd, width, height) {
2853
2920
  keys[j + 1] = key;
2854
2921
  active[j + 1] = e;
2855
2922
  }
2856
- counts.fill(0);
2857
- let total = 0;
2923
+ const added = rowStarts[py - y0 + 1] - rowStarts[py - y0];
2924
+ if (added) {
2925
+ const first = rowStarts[py - y0];
2926
+ const newKeys = scratch.f64(6, added), ranks = scratch.i32(7, added).subarray(0, added);
2927
+ for (let n = 0; n < added; n++) {
2928
+ newKeys[n] = keyOf(order[first + n]);
2929
+ ranks[n] = n;
2930
+ }
2931
+ ranks.sort((a, b) => newKeys[a] - newKeys[b]);
2932
+ let i = kept - 1, n = added - 1, out = kept + added - 1;
2933
+ while (n >= 0) {
2934
+ if (i >= 0 && keys[i] > newKeys[ranks[n]]) {
2935
+ keys[out] = keys[i];
2936
+ active[out--] = active[i--];
2937
+ }
2938
+ else {
2939
+ keys[out] = newKeys[ranks[n]];
2940
+ active[out--] = order[first + ranks[n--]];
2941
+ }
2942
+ }
2943
+ numActive += added;
2944
+ }
2858
2945
  for (let k = 0; k < numActive; k++) {
2859
2946
  const e = active[k], top = tops[e], bottom = bottoms[e];
2860
2947
  let s0 = Math.max(0, Math.ceil((top - py) * SAMPLES - 0.5)), s1 = Math.min(SAMPLES - 1, Math.ceil((bottom - py) * SAMPLES - 0.5) - 1);
@@ -2868,34 +2955,26 @@ function rasterize(polygons, evenOdd, width, height) {
2868
2955
  s1--;
2869
2956
  firsts[k] = s0;
2870
2957
  lasts[k] = Math.max(-1, s1);
2871
- for (let s = s0; s <= s1; s++)
2872
- counts[s]++;
2873
- if (s1 >= s0)
2874
- total += s1 - s0 + 1;
2875
- }
2876
- const crossings = scratch.f64(5, 2 * total);
2877
- for (let s = 0, at = 0; s < SAMPLES; s++) {
2878
- starts[s] = at;
2879
- at += 2 * counts[s];
2880
- }
2881
- for (let s = 0; s < SAMPLES; s++)
2882
- ends[s] = starts[s];
2883
- for (let k = 0; k < numActive; k++) {
2884
- const e = active[k];
2885
- for (let s = firsts[k]; s <= lasts[k]; s++) {
2886
- const sy = py + OFFSETS[s];
2887
- crossings[ends[s]++] = xs[e] + (sy - tops[e]) * slopes[e];
2888
- crossings[ends[s]++] = dirs[e];
2889
- }
2890
2958
  }
2959
+ const crossings = scratch.f64(5, 2 * numActive);
2891
2960
  for (let s = 0; s < SAMPLES; s++) {
2892
- const base = starts[s], end = ends[s];
2893
- if (end - base < 4)
2961
+ const sy = py + OFFSETS[s];
2962
+ let end = 0;
2963
+ for (let k = 0; k < numActive; k++) {
2964
+ if (s < firsts[k] || s > lasts[k])
2965
+ continue;
2966
+ const e = active[k];
2967
+ crossings[end++] = xs[e] + (sy - tops[e]) * slopes[e];
2968
+ crossings[end++] = dirs[e];
2969
+ }
2970
+ if (end < 4)
2894
2971
  continue;
2895
- for (let i = base + 2; i < end; i += 2) {
2972
+ if ((crossingsLeft -= end >> 1) < 0)
2973
+ throw new LimitError(`SVG too complex: its shapes' edges cross the rows of the image more than ${MAX_CROSSINGS} times (many large overlapping strokes or shapes)`);
2974
+ for (let i = 2; i < end; i += 2) {
2896
2975
  const x = crossings[i], dir = crossings[i + 1];
2897
2976
  let j = i - 2;
2898
- for (; j >= base && crossings[j] > x; j -= 2) {
2977
+ for (; j >= 0 && crossings[j] > x; j -= 2) {
2899
2978
  crossings[j + 2] = crossings[j];
2900
2979
  crossings[j + 3] = crossings[j + 1];
2901
2980
  }
@@ -2903,7 +2982,7 @@ function rasterize(polygons, evenOdd, width, height) {
2903
2982
  crossings[j + 3] = dir;
2904
2983
  }
2905
2984
  let winding = 0;
2906
- for (let i = base; i < end - 2; i += 2) {
2985
+ for (let i = 0; i < end - 2; i += 2) {
2907
2986
  winding += crossings[i + 1];
2908
2987
  if (evenOdd ? winding & 1 : winding !== 0)
2909
2988
  span(crossings[i], crossings[i + 2]);
@@ -3261,17 +3340,18 @@ function transformPoints(points, m) {
3261
3340
  }
3262
3341
  return out;
3263
3342
  }
3264
- function dash(subpaths, pattern, offset) {
3343
+ function* dash(subpaths, pattern, offset, visible = () => true) {
3265
3344
  const total = pattern.reduce((a, b) => a + b, 0);
3266
- const result = [];
3267
3345
  let length = 0;
3268
3346
  for (const { points, closed } of subpaths) {
3269
3347
  const pts = closed ? [...points, points[0], points[1]] : points;
3270
3348
  for (let i = 0; i + 3 < pts.length; i += 2)
3271
3349
  length += Math.hypot(pts[i + 2] - pts[i], pts[i + 3] - pts[i + 1]);
3272
3350
  }
3273
- if (!(length / total * pattern.length <= MAX_DASHES))
3274
- return subpaths;
3351
+ if (!(length / total * pattern.length <= MAX_DASHES)) {
3352
+ yield* subpaths;
3353
+ return;
3354
+ }
3275
3355
  for (const { points, closed } of subpaths) {
3276
3356
  const pts = closed ? [...points, points[0], points[1]] : points;
3277
3357
  let index = 0;
@@ -3300,7 +3380,8 @@ function dash(subpaths, pattern, offset) {
3300
3380
  if (on) {
3301
3381
  if (current) {
3302
3382
  current.push(mx, my);
3303
- result.push({ points: current, closed: false, direction: [(bx - ax) / length, (by - ay) / length] });
3383
+ if (visible(current))
3384
+ yield { points: current, closed: false, direction: [(bx - ax) / length, (by - ay) / length] };
3304
3385
  }
3305
3386
  current = null;
3306
3387
  }
@@ -3315,10 +3396,9 @@ function dash(subpaths, pattern, offset) {
3315
3396
  }
3316
3397
  }
3317
3398
  }
3318
- if (on && current && current.length >= 4)
3319
- result.push({ points: current, closed: false });
3399
+ if (on && current && current.length >= 4 && visible(current))
3400
+ yield { points: current, closed: false };
3320
3401
  }
3321
- return result;
3322
3402
  }
3323
3403
  function strokePolygons(subpaths, halfWidth, cap, join, miterLimit, tolerance) {
3324
3404
  const polygons = [];
@@ -3381,11 +3461,19 @@ function strokePolygons(subpaths, halfWidth, cap, join, miterLimit, tolerance) {
3381
3461
  const dot = prev[0] * next[0] + prev[1] * next[1];
3382
3462
  if (Math.abs(cross) < 1e-9 && dot > 0)
3383
3463
  continue;
3464
+ const side = cross > 0 ? -1 : 1;
3384
3465
  if (join === 'round') {
3385
- circle(vx, vy);
3466
+ const turn = Math.acos(Math.max(-1, Math.min(1, dot)));
3467
+ const steps = Math.max(1, Math.ceil(turn / (2 * Math.PI / circleSegments)));
3468
+ const start = Math.atan2(side * prev[0], side * -prev[1]), sweep = side === -1 ? turn : -turn;
3469
+ const wedge = [vx, vy];
3470
+ for (let k = 0; k <= steps; k++) {
3471
+ const a = start + sweep * k / steps;
3472
+ wedge.push(vx + Math.cos(a) * halfWidth, vy + Math.sin(a) * halfWidth);
3473
+ }
3474
+ add(wedge);
3386
3475
  continue;
3387
3476
  }
3388
- const side = cross > 0 ? -1 : 1;
3389
3477
  const ax = vx + side * -prev[1] * halfWidth, ay = vy + side * prev[0] * halfWidth;
3390
3478
  const bx = vx + side * -next[1] * halfWidth, by = vy + side * next[0] * halfWidth;
3391
3479
  const theta = Math.acos(Math.max(-1, Math.min(1, dot)));
@@ -39,7 +39,9 @@ export function axisValues(variations) {
39
39
  if (!tag)
40
40
  throw new RangeError(`Unknown font variation ${key}: use weight, width, slant, italic, opticalSize or an axis tag`);
41
41
  const v = typeof value === 'boolean' ? +value : value;
42
- if (typeof v !== 'number' || !Number.isFinite(v))
42
+ 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
+ if (!Number.isFinite(v))
43
45
  throw new RangeError(`Invalid font variation ${key}: ${String(value)}`);
44
46
  values[tag] = v;
45
47
  }
@@ -143,8 +145,8 @@ async function layOut(fonts, size, text, layout, hinting, foreground, features,
143
145
  const coverage = new Uint8Array(width * height);
144
146
  let color = null;
145
147
  for (const [n, line] of visible.entries()) {
146
- let offset = layout.horizontalAlign === 'right' ? width - line.extent
147
- : layout.horizontalAlign === 'center' ? (width - line.extent) / 2 : 0;
148
+ const align = layout.horizontalAlign ?? (line.rtl ? 'right' : 'left');
149
+ let offset = align === 'right' ? width - line.extent : align === 'center' ? (width - line.extent - line.start) / 2 : -line.start;
148
150
  if (primary.hinter)
149
151
  offset = Math.round(offset);
150
152
  const baseline = top + ascent + n * lineHeight;
@@ -287,8 +289,9 @@ function shapeRange(p, start, end, levels, font, size, features) {
287
289
  const isSpace = (codepoint) => codepoint === 0x20 || codepoint === 0x09 || codepoint === 0x3000 || codepoint >= 0x2000 && codepoint <= 0x200a;
288
290
  function layOutParagraph(p, layout, font, size, features) {
289
291
  const n = p.codepoints.length;
292
+ const rtl = (p.bidi.level & 1) === 1;
290
293
  if (!n)
291
- return [{ glyphs: [], extent: 0 }];
294
+ return [{ glyphs: [], extent: 0, start: 0, rtl }];
292
295
  const whole = shapeRange(p, 0, n, p.bidi.levels, font, size, features);
293
296
  const width = new Float64Array(n), starts = new Uint8Array(n + 1);
294
297
  starts[n] = 1;
@@ -336,11 +339,13 @@ function layOutParagraph(p, layout, font, size, features) {
336
339
  const shifted = new Int8Array(n);
337
340
  shifted.set(levels, start);
338
341
  const { glyphs } = ranges.length === 1 ? whole : shapeRange(p, start, end, shifted, font, size, features);
339
- let extent = 0;
342
+ let extent = 0, left = Infinity;
340
343
  for (const { x, dx, glyph } of glyphs)
341
- if (glyph.ink)
344
+ if (glyph.ink) {
342
345
  extent = Math.max(extent, x + dx + glyph.ink.right);
343
- return { glyphs, extent };
346
+ left = Math.min(left, x + dx + glyph.ink.left);
347
+ }
348
+ return { glyphs, extent, start: rtl && left < Infinity ? Math.max(0, left) : 0, rtl };
344
349
  });
345
350
  }
346
351
  async function scaledBitmap(glyph, scale) {
@@ -8,24 +8,31 @@ export type VerticalAlign = 'top' | 'middle' | 'bottom';
8
8
  export interface TextLayoutOptions {
9
9
  /**
10
10
  * The image's width in pixels: lines are wrapped to fit into it (inside the outline, see
11
- * {@link TextStyleOptions.strokeWidth}) and placed in it by `horizontalAlign`. Default: the widest line's width
11
+ * {@link TextStyleOptions.strokeWidth}) and placed in it by `horizontalAlign`
12
+ * @defaultValue The widest line's width
12
13
  */
13
14
  width?: number;
14
15
  /**
15
16
  * The image's height in pixels: lines that don't fit are left out, and the text is placed in it by `verticalAlign`.
16
- * Default: the height of the lines
17
+ * @defaultValue The height of the lines
17
18
  */
18
19
  height?: number;
19
- /** Whether to wrap between words or at any character. Default: `'word'` */
20
+ /**
21
+ * Whether to wrap between words or at any character
22
+ * @defaultValue `'word'`
23
+ */
20
24
  wrapStyle?: WrapStyle;
21
25
  /**
22
26
  * Where the lines are placed horizontally: `'left'`, `'center'` or `'right'` in the `width`, or (without one)
23
- * relative to the widest line. Default: `'left'`
27
+ * relative to the widest line
28
+ * @defaultValue The paragraph's direction: `'left'` for left-to-right text, `'right'` for right-to-left text
29
+ * (Arabic, Hebrew, ...), like the `start` of CSS' `text-align`
24
30
  */
25
31
  horizontalAlign?: HorizontalAlign;
26
32
  /**
27
33
  * Where the text is placed vertically in the `height`: `'top'`, `'middle'` or `'bottom'`. When not all lines fit,
28
- * these keep the first, the middle or the last lines. Without a `height`, it has no effect. Default: `'top'`
34
+ * these keep the first, the middle or the last lines. Without a `height`, it has no effect
35
+ * @defaultValue `'top'`
29
36
  */
30
37
  verticalAlign?: VerticalAlign;
31
38
  }
@@ -1,12 +1,13 @@
1
- import { oneOf } from "./util/options.js";
1
+ import { oneOf, checkNumber } from "./util/options.js";
2
2
  const HORIZONTAL = ['left', 'center', 'right'];
3
3
  const VERTICAL = ['top', 'middle', 'bottom'];
4
4
  function boxSide(value, name) {
5
5
  if (value === undefined)
6
6
  return undefined;
7
- const side = Math.floor(Number(value));
8
- if (typeof value !== 'number' || !(side >= 1) || !Number.isFinite(side))
9
- throw new RangeError(`${name} must be a finite number from 1, not ${String(value)}`);
7
+ checkNumber(value, name);
8
+ const side = Math.floor(value);
9
+ if (!(side >= 1) || !Number.isFinite(side))
10
+ throw new RangeError(`${name} must be a finite number from 1, not ${value}`);
10
11
  return side;
11
12
  }
12
13
  export function textLayout(options) {
@@ -15,7 +16,7 @@ export function textLayout(options) {
15
16
  width: boxSide(width, 'width'),
16
17
  height: boxSide(height, 'height'),
17
18
  wrapStyle: wrapStyle === undefined ? 'word' : oneOf(wrapStyle, ['word', 'char'], 'wrapStyle'),
18
- horizontalAlign: horizontalAlign === undefined ? 'left' : oneOf(horizontalAlign, HORIZONTAL, 'horizontalAlign'),
19
+ horizontalAlign: horizontalAlign === undefined ? undefined : oneOf(horizontalAlign, HORIZONTAL, 'horizontalAlign'),
19
20
  verticalAlign: verticalAlign === undefined ? 'top' : oneOf(verticalAlign, VERTICAL, 'verticalAlign')
20
21
  };
21
22
  }
@@ -0,0 +1,16 @@
1
+ export function describe(type, json) {
2
+ Object.defineProperty(type.prototype, Symbol.for('nodejs.util.inspect.custom'), {
3
+ value() {
4
+ return this.toString();
5
+ },
6
+ writable: true,
7
+ configurable: true
8
+ });
9
+ Object.defineProperty(type.prototype, 'toJSON', {
10
+ value() {
11
+ return json(this);
12
+ },
13
+ writable: true,
14
+ configurable: true
15
+ });
16
+ }
@@ -13,6 +13,11 @@ export declare const MAX_PIXELS: number;
13
13
  * @param count the number of such images (frames)
14
14
  */
15
15
  export declare function checkPixels(width: number, height: number, limit: number, count?: number): void;
16
+ /**
17
+ * Throws a {@link LimitError} naming the operation if an image it makes would have more pixels than an image can
18
+ * (the default `maxPixels` of the decoders): a shadow or outline of a huge size or offset would only fail allocating
19
+ */
20
+ export declare function checkGrowth(width: number, height: number, what: string): void;
16
21
  /** The most bytes of raw samples per pixel of the limit (4 samples of 16 bits) */
17
22
  export declare const MAX_BYTES_PER_PIXEL = 8;
18
23
  /**
@@ -6,6 +6,10 @@ export function checkPixels(width, height, limit, count = 1) {
6
6
  if (!(width * height * count <= limit))
7
7
  throw new LimitError(`Image too large: ${count > 1 ? `${count} frames of ` : ''}${width}x${height} pixels exceed the limit of ${limit} (the decode options' maxPixels)`);
8
8
  }
9
+ export function checkGrowth(width, height, what) {
10
+ if (!(width * height <= MAX_PIXELS))
11
+ throw new LimitError(`${what} would make the image ${width}x${height} pixels, more than the limit of ${MAX_PIXELS}`);
12
+ }
9
13
  export const MAX_BYTES_PER_PIXEL = 8;
10
14
  export function checkBytes(bytes, limit) {
11
15
  if (!(bytes <= limit * MAX_BYTES_PER_PIXEL))
package/dist/util/mem.js CHANGED
@@ -7,7 +7,7 @@ export function view(buffer) {
7
7
  return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
8
8
  if (typeof SharedArrayBuffer !== 'undefined' && buffer instanceof SharedArrayBuffer)
9
9
  return new Uint8Array(buffer);
10
- throw new TypeError('The provided value is not of type \'(ArrayBuffer or ArrayBufferView)\'');
10
+ throw new TypeError(`Binary data has to be an ArrayBuffer or a typed array like Uint8Array, not ${buffer === null ? 'null' : typeof buffer}`);
11
11
  }
12
12
  export function concat(parts) {
13
13
  let length = 0;
@@ -1,27 +1,49 @@
1
+ export function shown(value) {
2
+ if (value === null)
3
+ return 'null';
4
+ if (Array.isArray(value))
5
+ return 'an array';
6
+ if (typeof value === 'string')
7
+ return `'${value}'`;
8
+ if (typeof value === 'number')
9
+ return String(value);
10
+ if (typeof value === 'object')
11
+ return 'an object';
12
+ return typeof value;
13
+ }
1
14
  export function isOptions(value) {
2
- return typeof value === 'object' && value !== null && !ArrayBuffer.isView(value);
15
+ return typeof value === 'object' && value !== null && !Array.isArray(value) && !ArrayBuffer.isView(value);
3
16
  }
4
17
  export function checkOptions(value, usage) {
5
18
  if (value !== undefined && !isOptions(value))
6
- throw new TypeError(`${usage.split('(')[0]}() takes an options object, like ${usage}, not ${value === null ? 'null' : typeof value}`);
19
+ throw new TypeError(`${usage.split('(')[0]}() takes an options object, like ${usage}, not ${shown(value)}`);
7
20
  }
8
21
  export function oneOf(value, allowed, name) {
9
22
  if (typeof value !== 'string' || !allowed.includes(value)) {
10
23
  const list = allowed.map(a => `'${a}'`);
11
24
  const expected = list.length > 1 ? `${list.slice(0, -1).join(', ')} or ${list[list.length - 1]}` : list[0];
12
- throw new TypeError(`${name} must be ${expected}, not ${typeof value === 'string' ? `'${value}'` : String(value)}`);
25
+ throw new TypeError(`${name} must be ${expected}, not ${shown(value)}`);
13
26
  }
14
27
  return value;
15
28
  }
29
+ export function boolean(value, name) {
30
+ if (typeof value !== 'boolean')
31
+ throw new TypeError(`${name} must be true or false, not ${shown(value)}`);
32
+ return value;
33
+ }
34
+ export function checkNumber(value, name) {
35
+ if (typeof value !== 'number')
36
+ throw new TypeError(`${name} must be a number, not ${shown(value)}`);
37
+ }
16
38
  export function finite(value, name) {
17
- const number = Number(value);
18
- if (!Number.isFinite(number))
39
+ checkNumber(value, name);
40
+ if (!Number.isFinite(value))
19
41
  throw new RangeError(`Invalid ${name}: ${value}`);
20
- return number;
42
+ return value;
21
43
  }
22
44
  export function loopCount(value, name = 'loop count') {
23
45
  if (typeof value !== 'number')
24
- throw new TypeError(`${name} must be a number (Infinity or an integer from 0), not ${value === null ? 'null' : typeof value}`);
46
+ throw new TypeError(`${name} must be a number (Infinity or an integer from 0), not ${shown(value)}`);
25
47
  if (value !== Infinity && (!Number.isInteger(value) || value < 0))
26
48
  throw new RangeError(`${name} must be Infinity or an integer from 0, not ${value}`);
27
49
  return value;
@@ -43,6 +65,24 @@ export function fitDuration(duration, format) {
43
65
  throw new RangeError(`refuse frame durations that don't fit the format: ${format} frames last up to ${max} ms, not ${duration}`);
44
66
  return duration;
45
67
  }
68
+ export function nonNegative(value, name) {
69
+ finite(value, name);
70
+ if (value < 0)
71
+ throw new RangeError(`${name} must be 0 or more, not ${value}`);
72
+ return value;
73
+ }
74
+ export function unitInterval(value, name) {
75
+ finite(value, name);
76
+ if (value < 0 || value > 1)
77
+ throw new RangeError(`${name} must be 0-1, not ${value}`);
78
+ return value;
79
+ }
80
+ export function positive(value, name) {
81
+ finite(value, name);
82
+ if (!(value > 0))
83
+ throw new RangeError(`${name} must be above 0, not ${value}`);
84
+ return value;
85
+ }
46
86
  export function quality(value, name = 'quality') {
47
87
  const q = finite(value, name);
48
88
  if (q < 0 || q > 100)
@@ -50,9 +90,28 @@ export function quality(value, name = 'quality') {
50
90
  return q;
51
91
  }
52
92
  export function pixelLimit(value, name = 'maxPixels') {
53
- if (!(Number(value) > 0))
93
+ checkNumber(value, name);
94
+ if (!(value > 0))
54
95
  throw new RangeError(`${name} must be a positive number, not ${value}`);
55
- return Number(value);
96
+ return value;
97
+ }
98
+ export function gainMapEmbed(value) {
99
+ if (value === false)
100
+ return null;
101
+ if (value === true)
102
+ return {};
103
+ if (typeof value !== 'object' || value === null)
104
+ throw new TypeError(`gainMap must be true, false or an options object like { quality: 90, scale: 0.5 }, not ${shown(value)}`);
105
+ const { quality: q, scale } = value;
106
+ const options = {};
107
+ if (q !== undefined) {
108
+ options.quality = quality(q, 'gain map quality');
109
+ if (options.quality < 1)
110
+ throw new RangeError(`gain map quality must be 1-100, not ${options.quality}`);
111
+ }
112
+ if (scale !== undefined)
113
+ options.scale = gainMapScale(scale);
114
+ return options;
56
115
  }
57
116
  export function gainMapScale(value) {
58
117
  const scale = finite(value, 'gain map scale');
@@ -61,15 +120,18 @@ export function gainMapScale(value) {
61
120
  return scale;
62
121
  }
63
122
  export function checkThreads(threads) {
123
+ checkNumber(threads, 'threads');
64
124
  if (!Number.isInteger(threads) || threads < 1)
65
125
  throw new RangeError(`threads must be a positive integer, not ${threads}`);
66
126
  }
67
127
  export function effort(value, max) {
128
+ checkNumber(value, 'effort');
68
129
  if (!Number.isInteger(value) || value < 0 || value > max)
69
130
  throw new RangeError(`effort must be an integer 0-${max}, not ${value}`);
70
131
  return value;
71
132
  }
72
133
  export function compressionLevel(value) {
134
+ checkNumber(value, 'compression level');
73
135
  if (!Number.isInteger(value) || value < 0 || value > 9)
74
136
  throw new RangeError(`compression level must be an integer 0-9, not ${value}`);
75
137
  return value;