imagescript 4.0.0-rc.1 → 4.0.0-rc.2

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/dist/image.js CHANGED
@@ -30,8 +30,8 @@ import { encode as utf8 } from "./util/utf8.js";
30
30
  import { resample, BOX, TRIANGLE, CUBIC } from "./util/resample.js";
31
31
  import { gaussianBlur, boxBlurRGBA, premultiply, unpremultiply } from "./util/blur.js";
32
32
  import { Colors, wrapHue, hue2rgb } from "./colors.js";
33
- import { isOptions, checkOptions, finite, color as checkColor, quality as checkQuality, effort as checkEffort, compressionLevel } from "./util/options.js";
34
- import { MAX_PIXELS, decoding } from "./util/limits.js";
33
+ import { isOptions, checkOptions, finite, oneOf, color as checkColor, quality as checkQuality, effort as checkEffort, compressionLevel } from "./util/options.js";
34
+ import { MAX_PIXELS, LimitError, decoding } from "./util/limits.js";
35
35
  import { GainMap } from "./gainmap.js";
36
36
  import * as gain from "./util/gain.js";
37
37
  import { multiply, invert } from "./util/matrix.js";
@@ -89,6 +89,8 @@ export class Image {
89
89
  throw new TypeError('The bitmap has to be a Uint8ClampedArray or Uint8Array');
90
90
  if (bitmap.length !== this.width * this.height * 4)
91
91
  throw new RangeError(`The bitmap has to have ${this.width * this.height * 4} bytes (width * height * 4), got ${bitmap.length}`);
92
+ if (bitmap.byteOffset % 4)
93
+ throw new TypeError(`The bitmap has to start at a byte offset divisible by 4 to be used without copying, not ${bitmap.byteOffset} (pass bitmap.slice() for a copy)`);
92
94
  this.__set_bitmap__(bitmap instanceof Uint8ClampedArray ? bitmap : new Uint8ClampedArray(bitmap.buffer, bitmap.byteOffset, bitmap.length));
93
95
  }
94
96
  __set_bitmap__(bitmap) {
@@ -150,14 +152,14 @@ export class Image {
150
152
  return image;
151
153
  }
152
154
  getPixelAt(x, y) {
153
- x = ~~finite(x, 'x');
154
- y = ~~finite(y, 'y');
155
+ x = Math.trunc(finite(x, 'x'));
156
+ y = Math.trunc(finite(y, 'y'));
155
157
  this.__check_boundaries__(x, y);
156
158
  return this.__view__.getUint32((y * this.width + x) * 4, false);
157
159
  }
158
160
  setPixelAt(x, y, color) {
159
- x = ~~finite(x, 'x');
160
- y = ~~finite(y, 'y');
161
+ x = Math.trunc(finite(x, 'x'));
162
+ y = Math.trunc(finite(y, 'y'));
161
163
  this.__check_boundaries__(x, y);
162
164
  this.__set_pixel__(x, y, checkColor(color));
163
165
  return this;
@@ -186,21 +188,19 @@ export class Image {
186
188
  const view = new DataView(this.bitmap.buffer, this.bitmap.byteOffset, this.bitmap.byteLength);
187
189
  if (typeof color !== 'function')
188
190
  color = checkColor(color);
189
- if (this.__gain_map__)
190
- this.__gain_map__ = gain.neutralMap(this.__gain_map__, this.width, this.width, this.height);
191
191
  if (typeof color === 'function') {
192
192
  let offset = 0;
193
193
  for (let y = 0; y < this.height; y++)
194
194
  for (let x = 0; x < this.width; x++, offset += 4)
195
- view.setUint32(offset, color(x, y), false);
195
+ view.setUint32(offset, checkColor(color(x, y)), false);
196
196
  }
197
197
  else {
198
- if (!this.bitmap.length)
199
- return this;
200
198
  view.setUint32(0, color, false);
201
199
  const u32 = new Uint32Array(this.bitmap.buffer, this.bitmap.byteOffset, this.bitmap.byteLength / 4);
202
200
  u32.fill(u32[0]);
203
201
  }
202
+ if (this.__gain_map__)
203
+ this.__gain_map__ = gain.neutralMap(this.__gain_map__, this.width, this.width, this.height);
204
204
  return this;
205
205
  }
206
206
  clone() {
@@ -295,11 +295,10 @@ export class Image {
295
295
  throw new RangeError('Image has to be at least 1 pixel wide');
296
296
  if (height < 1)
297
297
  throw new RangeError('Image has to be at least 1 pixel high');
298
+ oneOf(mode, RESIZE_MODES, 'resize mode');
298
299
  if (mode === 'nearest-neighbor')
299
300
  return this.__resize_nearest_neighbor__(width, height);
300
- const filter = mode === 'bilinear' ? TRIANGLE : mode === 'bicubic' ? CUBIC : mode === 'area' ? BOX : null;
301
- if (!filter)
302
- throw new Error('Invalid resize mode');
301
+ const filter = mode === 'bilinear' ? TRIANGLE : mode === 'bicubic' ? CUBIC : BOX;
303
302
  const image = new Image(region?.width ?? width, region?.height ?? height);
304
303
  resample(this.bitmap, this.width, this.height, width, height, filter, image.bitmap, fast, region);
305
304
  return image;
@@ -336,10 +335,10 @@ export class Image {
336
335
  return image;
337
336
  }
338
337
  __crop_bounds__(x, y, width, height) {
339
- x = ~~finite(x, 'x');
340
- y = ~~finite(y, 'y');
341
- width = ~~finite(width, 'width');
342
- height = ~~finite(height, 'height');
338
+ x = Math.trunc(finite(x, 'x'));
339
+ y = Math.trunc(finite(y, 'y'));
340
+ width = Math.trunc(finite(width, 'width'));
341
+ height = Math.trunc(finite(height, 'height'));
343
342
  const left = Math.max(0, x), top = Math.max(0, y);
344
343
  const right = Math.min(this.width, x + width), bottom = Math.min(this.height, y + height);
345
344
  if (right <= left || bottom <= top)
@@ -517,13 +516,11 @@ export class Image {
517
516
  checkOptions(options, 'composite(source, { x: 10, y: 20 })');
518
517
  const { opacity = 1, mode = 'normal' } = options;
519
518
  let x = options.x ?? 0, y = options.y ?? 0;
520
- x = finite(x, 'x') | 0;
521
- y = finite(y, 'y') | 0;
519
+ x = Math.trunc(finite(x, 'x'));
520
+ y = Math.trunc(finite(y, 'y'));
522
521
  if (isNaN(opacity) || opacity < 0 || opacity > 1)
523
522
  throw new RangeError('Invalid composite opacity');
524
- const blend = BLEND_MODES[mode];
525
- if (!blend || !Object.prototype.hasOwnProperty.call(BLEND_MODES, mode))
526
- throw new RangeError(`Invalid blend mode: ${mode}`);
523
+ const blend = BLEND_MODES[oneOf(mode, Object.keys(BLEND_MODES), 'blend mode')];
527
524
  if (opacity === 0)
528
525
  return this;
529
526
  if (this.__gain_map__ || source.__gain_map__)
@@ -1117,21 +1114,20 @@ export class Image {
1117
1114
  return this.__apply__(out);
1118
1115
  }
1119
1116
  flip(direction) {
1117
+ oneOf(direction, ['horizontal', 'vertical'], 'flip direction');
1120
1118
  const u32 = this.__u32__;
1121
1119
  const { width, height } = this;
1122
1120
  if (direction === 'horizontal') {
1123
1121
  for (let y = 0; y < height; y++)
1124
1122
  u32.subarray(y * width, (y + 1) * width).reverse();
1125
1123
  }
1126
- else if (direction === 'vertical') {
1124
+ else {
1127
1125
  for (let y = 0; y < height >> 1; y++) {
1128
1126
  const top = u32.slice(y * width, (y + 1) * width);
1129
1127
  u32.copyWithin(y * width, (height - 1 - y) * width, (height - y) * width);
1130
1128
  u32.set(top, (height - 1 - y) * width);
1131
1129
  }
1132
1130
  }
1133
- else
1134
- throw new RangeError('Invalid flip direction');
1135
1131
  this.__gain_map__?.__transform__(width, height, width, height, direction === 'horizontal' ? (X, Y) => [width - X, Y] : (X, Y) => [X, height - Y]);
1136
1132
  return this;
1137
1133
  }
@@ -1403,7 +1399,7 @@ export class Image {
1403
1399
  (icc ? profileTransform(icc) : cicp ? cicpTransform(...cicp) : colorSpace ? colorSpaceTransform(colorSpace.xy, colorSpace.curve) : null)?.(decoded.pixels);
1404
1400
  }
1405
1401
  const image = new Image(decoded.width, decoded.height);
1406
- image.bitmap = decoded.pixels;
1402
+ image.bitmap = alignedPixels(decoded.pixels);
1407
1403
  if (gainMap && ImageType.isJPEG(dataView)) {
1408
1404
  try {
1409
1405
  const found = gainMapCodec.find(data);
@@ -1418,7 +1414,7 @@ export class Image {
1418
1414
  if (decoded.gainMap) {
1419
1415
  const { width, height, pixels, params } = decoded.gainMap;
1420
1416
  const map = new Image(width, height);
1421
- map.bitmap = pixels;
1417
+ map.bitmap = alignedPixels(pixels);
1422
1418
  image.__gain_map__ = GainMap.__from_pixels__(map, params);
1423
1419
  }
1424
1420
  if (applyOrientation && decoded.orientation && decoded.orientation > 1) {
@@ -1486,6 +1482,11 @@ export class Image {
1486
1482
  const { width: givenWidth, height: givenHeight, scale, maxPixels = MAX_PIXELS, fonts = [], images: givenImages = {} } = options;
1487
1483
  if (!(Number(maxPixels) > 0))
1488
1484
  throw new RangeError(`maxPixels must be a positive number, not ${maxPixels}`);
1485
+ const { maxLayerPixels = 4 * Number(maxPixels), maxImagePixels = Number(maxPixels) } = options;
1486
+ if (!(Number(maxLayerPixels) > 0))
1487
+ throw new RangeError(`maxLayerPixels must be a positive number, not ${maxLayerPixels}`);
1488
+ if (!(Number(maxImagePixels) > 0))
1489
+ throw new RangeError(`maxImagePixels must be a positive number, not ${maxImagePixels}`);
1489
1490
  const sizes = [givenWidth, givenHeight, scale].filter(value => value !== undefined).length;
1490
1491
  if (sizes > 1)
1491
1492
  throw new TypeError('renderSVG() takes one of width, height and scale');
@@ -1506,27 +1507,39 @@ export class Image {
1506
1507
  }
1507
1508
  const source = typeof svg === 'string' ? svg : view(svg);
1508
1509
  const images = new Map();
1510
+ const shown = (href) => JSON.stringify(href.length > 100 ? `${href.slice(0, 100)}...` : href);
1511
+ let imagePixels = Number(maxImagePixels);
1509
1512
  for (const { href, data } of svgRenderer.imageReferences(source)) {
1510
1513
  const value = given.get(href) ?? data;
1511
1514
  if (!value)
1512
1515
  continue;
1516
+ if (value instanceof Image) {
1517
+ images.set(href, { width: value.width, height: value.height, pixels: value.bitmap });
1518
+ continue;
1519
+ }
1520
+ const tooLarge = (cause) => new LimitError(`SVG: the image ${shown(href)} exceeds what's left of the ${maxImagePixels} pixels the SVG's images may decode to (the render options' maxImagePixels)`, { cause });
1521
+ if (!(imagePixels >= 1)) {
1522
+ images.set(href, { error: tooLarge() });
1523
+ continue;
1524
+ }
1513
1525
  try {
1514
- if (value instanceof Image) {
1515
- images.set(href, { width: value.width, height: value.height, pixels: value.bitmap });
1516
- }
1517
- else if (ImageType.getType(value) === 'gif') {
1518
- const decoded = gif.decode(view(value), true, maxPixels);
1519
- images.set(href, { width: decoded.width, height: decoded.height, pixels: gif.composite(decoded)[0].pixels });
1526
+ let decoded;
1527
+ if (ImageType.getType(value) === 'gif') {
1528
+ const gifData = await decoding(() => gif.decode(view(value), true, imagePixels));
1529
+ decoded = { width: gifData.width, height: gifData.height, pixels: gif.composite(gifData)[0].pixels };
1520
1530
  }
1521
1531
  else {
1522
- const image = await Image.decode(value, { maxPixels });
1523
- images.set(href, { width: image.width, height: image.height, pixels: image.bitmap });
1532
+ const image = await Image.decode(value, { maxPixels: imagePixels });
1533
+ decoded = { width: image.width, height: image.height, pixels: image.bitmap };
1524
1534
  }
1535
+ imagePixels -= decoded.width * decoded.height;
1536
+ images.set(href, decoded);
1525
1537
  }
1526
- catch {
1538
+ catch (err) {
1539
+ images.set(href, { error: err instanceof LimitError ? tooLarge(err) : new Error(`SVG: the image ${shown(href)} can't be decoded`, { cause: err }) });
1527
1540
  }
1528
1541
  }
1529
- const { width, height, pixels } = svgRenderer.render(source, mode, size, images, (Array.isArray(fonts) ? fonts : [fonts]).map(font => view(font)), maxPixels);
1542
+ const { width, height, pixels } = svgRenderer.render(source, mode, size, images, (Array.isArray(fonts) ? fonts : [fonts]).map(font => view(font)), Number(maxPixels), Number(maxLayerPixels));
1530
1543
  const image = new Image(width, height);
1531
1544
  image.bitmap.set(pixels);
1532
1545
  return image;
@@ -1536,7 +1549,9 @@ export class Image {
1536
1549
  throw new TypeError('renderText() takes the text and an options object, like renderText(\'Hello\', { font, size: 32 })');
1537
1550
  if (options.font === undefined)
1538
1551
  throw new TypeError('renderText(text, options) needs the font in the options');
1539
- const { font, color = 0xffffffff, strokeWidth = 0, strokeColor = 0x000000ff, hinting = true, features = {}, variations = {} } = options;
1552
+ const { font, color = 0xffffffff, strokeWidth = 0, strokeColor = 0x000000ff, hinting = true, features = {}, variations = {}, maxPixels = MAX_PIXELS } = options;
1553
+ if (!(Number(maxPixels) > 0))
1554
+ throw new RangeError(`maxPixels must be a positive number, not ${maxPixels}`);
1540
1555
  const { maxWidth, maxHeight, wrapStyle, horizontalAlign, verticalAlign, wrapHardBreaks } = options;
1541
1556
  const layout = new TextLayout({ maxWidth, maxHeight, wrapStyle, horizontalAlign, verticalAlign, wrapHardBreaks });
1542
1557
  const axes = textRenderer.axisValues(variations);
@@ -1549,8 +1564,8 @@ export class Image {
1549
1564
  if (!fonts.length)
1550
1565
  throw new RangeError('No font given');
1551
1566
  const [r, g, b, a] = Colors.toRGBA(color);
1552
- const rendered = await textRenderer.render(fonts.map(view), size, text, layout, hinting, (r << 24 | g << 16 | b << 8 | 255) >>> 0, featureList(features), axes);
1553
1567
  const pad = Math.ceil(strokeWidth);
1568
+ const rendered = await textRenderer.render(fonts.map(view), size, text, layout, hinting, (r << 24 | g << 16 | b << 8 | 255) >>> 0, featureList(features), axes, Number(maxPixels), pad);
1554
1569
  const width = rendered.width + 2 * pad, height = rendered.height + 2 * pad;
1555
1570
  const coverage = new Uint8Array(width * height);
1556
1571
  for (let y = 0; y < rendered.height; y++)
@@ -1624,6 +1639,9 @@ function circleCoverage(px, py, cx, cy, radius) {
1624
1639
  return 0;
1625
1640
  return pixelCoverage(px, py, (x, y) => (x - cx) ** 2 + (y - cy) ** 2 <= radius * radius);
1626
1641
  }
1642
+ export function alignedPixels(pixels) {
1643
+ return pixels.byteOffset % 4 ? pixels.slice() : pixels;
1644
+ }
1627
1645
  export function resizeArguments(widthOrOptions, height, options) {
1628
1646
  if (!isOptions(widthOrOptions)) {
1629
1647
  checkOptions(options, 'resize(width, height, { mode: \'area\' })');
@@ -1642,8 +1660,9 @@ export function insideSize(width, height, boxWidth, boxHeight) {
1642
1660
  const scale = Math.min(boxWidth / width, boxHeight / height);
1643
1661
  return [Math.max(1, Math.min(boxWidth, Math.round(width * scale))), Math.max(1, Math.min(boxHeight, Math.round(height * scale)))];
1644
1662
  }
1663
+ const RESIZE_MODES = ['nearest-neighbor', 'bilinear', 'bicubic', 'area'];
1645
1664
  function resizeOptions(options) {
1646
- return { mode: options?.mode ?? 'bilinear', fast: options?.fast ?? true };
1665
+ return { mode: options?.mode === undefined ? 'bilinear' : oneOf(options.mode, RESIZE_MODES, 'resize mode'), fast: options?.fast ?? true };
1647
1666
  }
1648
1667
  const hardLight = (b, s) => s <= 0.5 ? b * 2 * s : 1 - (1 - b) * (1 - (2 * s - 1));
1649
1668
  const BLEND_MODES = {
package/dist/index.d.ts CHANGED
@@ -1,3 +1,7 @@
1
+ /**
2
+ * @packageDocumentation
3
+ * @document ../guides/Migrating to 4.0.md
4
+ */
1
5
  import { BinaryData } from './util/mem.js';
2
6
  import { Image, DecodeOptions } from './image.js';
3
7
  import { Animation } from './animation.js';
@@ -9,7 +9,8 @@
9
9
  * | GIF | software, comment (comment extensions) |
10
10
  * | TGA | author, comment, creation time, software (extension area) |
11
11
  *
12
- * Empty fields are left out
12
+ * Empty fields are left out. Without metadata, the files only say which software made them (`software`), so the same
13
+ * image always encodes to the same bytes
13
14
  */
14
15
  export interface Metadata {
15
16
  /** The image's title */
@@ -20,9 +21,9 @@ export interface Metadata {
20
21
  description?: string;
21
22
  /** The image's copyright info */
22
23
  copyright?: string;
23
- /** The image's creation time. Default: now */
24
+ /** The image's creation time. Default: none (left out) */
24
25
  creationTime?: string | number | Date;
25
- /** The software used to create the image. Default: `'ImageScript vX.X.X'`, `''` leaves it out */
26
+ /** The software used to create the image. Default: `'ImageScript'` (without a version), `''` leaves it out */
26
27
  software?: string;
27
28
  /** A disclaimer for the image */
28
29
  disclaimer?: string;
package/dist/metadata.js CHANGED
@@ -1,15 +1,17 @@
1
- import { VERSION } from "./version.js";
2
1
  import { encode as utf8 } from "./util/utf8.js";
3
2
  import * as exif from "./codecs/exif.js";
4
3
  const TEXT_FIELDS = ['title', 'author', 'description', 'copyright', 'software', 'disclaimer', 'warning', 'source', 'comment'];
5
4
  export function resolveMetadata(metadata = {}) {
6
5
  const { creationTime, software } = metadata || {};
7
- const time = new Date(creationTime === undefined ? Date.now() : creationTime);
8
- if (isNaN(time.getTime()))
9
- throw new RangeError('Invalid creation time');
10
- const resolved = { creationTime: time };
6
+ const resolved = {};
7
+ if (creationTime !== undefined) {
8
+ const time = new Date(creationTime);
9
+ if (isNaN(time.getTime()))
10
+ throw new RangeError('Invalid creation time');
11
+ resolved.creationTime = time;
12
+ }
11
13
  for (const key of TEXT_FIELDS) {
12
- const value = key === 'software' && software === undefined ? `ImageScript v${VERSION}` : metadata?.[key];
14
+ const value = key === 'software' && software === undefined ? 'ImageScript' : metadata?.[key];
13
15
  if (value)
14
16
  resolved[key] = String(value);
15
17
  }
@@ -21,7 +23,7 @@ export function pngText(m) {
21
23
  Author: m.author,
22
24
  Description: m.description,
23
25
  Copyright: m.copyright,
24
- 'Creation Time': m.creationTime.toUTCString(),
26
+ 'Creation Time': m.creationTime?.toUTCString(),
25
27
  Software: m.software,
26
28
  Disclaimer: m.disclaimer,
27
29
  Warning: m.warning,
@@ -442,7 +442,7 @@ function composite(mode, source, backdrop) {
442
442
  else
443
443
  src.fill(0);
444
444
  const as = src[3], ab = d[o + 3];
445
- let fa = 0, fb = 0;
445
+ let fa, fb;
446
446
  switch (mode) {
447
447
  case 0:
448
448
  fa = 0;
@@ -281,7 +281,7 @@ export class Font {
281
281
  components(offset) {
282
282
  const components = [];
283
283
  const f2dot14 = (o) => this.i16(o) / 16384;
284
- let p = offset + 10, flags = 0;
284
+ let p = offset + 10, flags;
285
285
  do {
286
286
  flags = this.u16(p);
287
287
  const glyph = this.u16(p + 2);
@@ -1096,7 +1096,7 @@ export class LayoutTable {
1096
1096
  return false;
1097
1097
  const j = it.idx;
1098
1098
  const id1 = ligId(buffer.cur()), id2 = ligId(info[j]), comp1 = ligComp(buffer.cur()), comp2 = ligComp(info[j]);
1099
- let good = false;
1099
+ let good;
1100
1100
  if (id1 === id2)
1101
1101
  good = id1 === 0 || comp1 === comp2;
1102
1102
  else
@@ -11,7 +11,7 @@ export function graphemeBoundaries(codepoints) {
11
11
  incb[i] = value(conjunctBreak, codepoints[i]);
12
12
  pictographic[i] = valueIndex(extendedPictographic, codepoints[i]) ? 1 : 0;
13
13
  }
14
- let emoji = false, emojiZWJ = false, ri = 0;
14
+ let emoji = false, emojiZWJ, ri = 0;
15
15
  let linker = false;
16
16
  for (let i = 1; i < n; i++) {
17
17
  const a = gcb[i - 1], b = gcb[i];
@@ -107,7 +107,7 @@ function preprocessText(_plan, buffer, font) {
107
107
  info[i++].category = 1;
108
108
  info[i++].category = 2;
109
109
  if (i < end)
110
- info[i++].category = 3;
110
+ info[i].category = 3;
111
111
  buffer.mergeOutClusters(start, end);
112
112
  continue;
113
113
  }
@@ -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, checkPixels } from "../util/limits.js";
24
+ import { MAX_PIXELS, LimitError, checkPixels } 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',
@@ -53,7 +53,7 @@ const DEFAULTS = {
53
53
  };
54
54
  const SAMPLES = 16;
55
55
  const OFFSETS = Float64Array.from({ length: SAMPLES }, (_, s) => (s + 0.5) / SAMPLES);
56
- export function render(source, mode, size, images = new Map(), fonts = [], maxPixels = MAX_PIXELS) {
56
+ export function render(source, mode, size, images = new Map(), fonts = [], maxPixels = MAX_PIXELS, maxLayerPixels = 4 * maxPixels) {
57
57
  if (typeof source !== 'string')
58
58
  source = decodeUTF8(source);
59
59
  const root = parseXML(source).children.find(node => node.name === 'svg' && node.svg);
@@ -83,10 +83,18 @@ export function render(source, mode, size, images = new Map(), fonts = [], maxPi
83
83
  if (!Number.isSafeInteger(outWidth) || !Number.isSafeInteger(outHeight))
84
84
  throw new RangeError(`SVG output dimensions are too large: ${outWidth}x${outHeight}`);
85
85
  checkPixels(outWidth, outHeight, maxPixels);
86
- const canvas = new Layer(outWidth, outHeight);
87
- doc.renderRoot([outWidth / width, 0, 0, outHeight / height, 0, 0], canvas, 0);
88
- return { width: outWidth, height: outHeight, pixels: canvas.toRGBA() };
86
+ const previous = layerBudget;
87
+ layerBudget = { left: maxLayerPixels, limit: maxLayerPixels };
88
+ try {
89
+ const canvas = new Layer(outWidth, outHeight);
90
+ doc.renderRoot([outWidth / width, 0, 0, outHeight / height, 0, 0], canvas, 0);
91
+ return { width: outWidth, height: outHeight, pixels: canvas.toRGBA() };
92
+ }
93
+ finally {
94
+ layerBudget = previous;
95
+ }
89
96
  }
97
+ let layerBudget = null;
90
98
  function documentSize(root) {
91
99
  const viewBox = parseViewBox(root.attrs.viewBox);
92
100
  const lengthOf = (value, fallback) => {
@@ -145,17 +153,20 @@ function isRaster(data) {
145
153
  }
146
154
  function nestedSvg(href) {
147
155
  const uri = dataURI(href);
148
- if (!uri || (uri.type !== 'image/svg+xml' && (uri.type !== 'text/plain' || isRaster(uri.data))))
149
- return null;
156
+ const shown = href.length > 100 ? `${href.slice(0, 100)}...` : href;
157
+ if (!uri)
158
+ return { error: new Error(/^\s*data:/i.test(href) ? 'SVG: an image\'s data URI is invalid' : `SVG: the image ${JSON.stringify(shown)} isn't a data URI or one of the images given to render it`) };
159
+ if (uri.type !== 'image/svg+xml' && (uri.type !== 'text/plain' || isRaster(uri.data)))
160
+ return { error: new Error(`SVG: images of type ${uri.type} aren't supported`) };
150
161
  try {
151
162
  const root = parseXML(svgText(uri.data)).children.find(node => node.name === 'svg' && node.svg);
152
163
  if (!root)
153
- return null;
164
+ return { error: new Error('SVG: an embedded SVG image has no <svg> element') };
154
165
  const { width, height } = documentSize(root);
155
166
  return width > 0 && height > 0 ? { width, height, document: new Document(root) } : null;
156
167
  }
157
- catch {
158
- return null;
168
+ catch (cause) {
169
+ return { error: new Error('SVG: an embedded SVG image can\'t be read', { cause }) };
159
170
  }
160
171
  }
161
172
  export function imageReferences(source) {
@@ -781,6 +792,7 @@ class Document {
781
792
  alpha = values;
782
793
  }
783
794
  context.layer.composite(layer, opacity, alpha, blend);
795
+ layer.release();
784
796
  }
785
797
  clipped(ctx, x, y, width, height, draw) {
786
798
  const layer = new Layer(ctx.layer.width, ctx.layer.height);
@@ -793,6 +805,7 @@ class Document {
793
805
  for (let column = 0; column < coverage.w; column++)
794
806
  alpha[(coverage.y0 + row) * w + coverage.x0 + column] = coverage.data[row * coverage.w + column];
795
807
  ctx.layer.composite(layer, 1, alpha);
808
+ layer.release();
796
809
  }
797
810
  renderNestedSvg(node, ctx) {
798
811
  const { viewport } = ctx;
@@ -851,6 +864,7 @@ class Document {
851
864
  const layer = new Layer(ctx.layer.width, ctx.layer.height);
852
865
  draw(layer);
853
866
  ctx.layer.composite(layer, opacity, null);
867
+ layer.release();
854
868
  return;
855
869
  }
856
870
  const computed = target.computed, computedParent = target.computedParent;
@@ -1250,8 +1264,10 @@ class Document {
1250
1264
  }
1251
1265
  renderImage(node, ctx) {
1252
1266
  const style = ctx.style;
1267
+ if (style.visibility !== 'visible')
1268
+ return;
1253
1269
  const image = this.imageOf(node, ctx.viewport);
1254
- if (!image || style.visibility !== 'visible')
1270
+ if (!image)
1255
1271
  return;
1256
1272
  const { raster, nested, intrinsic, x, y, width, height } = image;
1257
1273
  const aspect = node.attrs.preserveAspectRatio || 'xMidYMid meet';
@@ -1272,17 +1288,24 @@ class Document {
1272
1288
  else
1273
1289
  draw(ctx.layer);
1274
1290
  }
1275
- imageOf(node, viewport) {
1291
+ imageOf(node, viewport, draws = true) {
1276
1292
  const href = this.href(node)?.trim();
1277
1293
  if (!href)
1278
1294
  return null;
1279
- const raster = this.images.get(href);
1280
- let nested = null;
1281
- if (!raster) {
1295
+ const decoded = this.images.get(href);
1296
+ let embedded = null;
1297
+ if (!decoded) {
1282
1298
  if (!this.nested.has(href))
1283
1299
  this.nested.set(href, nestedSvg(href));
1284
- nested = this.nested.get(href);
1300
+ embedded = this.nested.get(href);
1301
+ }
1302
+ const broken = decoded && 'error' in decoded ? decoded : embedded && 'error' in embedded ? embedded : null;
1303
+ if (broken) {
1304
+ if (draws)
1305
+ throw broken.error;
1306
+ return null;
1285
1307
  }
1308
+ const raster = decoded, nested = embedded;
1286
1309
  if (!raster && !nested)
1287
1310
  return null;
1288
1311
  const intrinsic = raster || nested;
@@ -1656,6 +1679,7 @@ class Document {
1656
1679
  this.renderChildren(content, { ...ctx, matrix: contentMatrix, style: this.styleOf(content), layer: tile, depth: ctx.depth + 1,
1657
1680
  viewport: viewBox ? { width: viewBox[2], height: viewBox[3] } : ctx.viewport });
1658
1681
  this.active.delete(node);
1682
+ tile.release();
1659
1683
  if (tile.x1 <= tile.x0)
1660
1684
  return null;
1661
1685
  const translated = !rotated && patternMatrix[0] > 0 && patternMatrix[3] > 0;
@@ -1696,20 +1720,22 @@ class Document {
1696
1720
  const layer = new Layer(lw, lh);
1697
1721
  draw(layer, shifted);
1698
1722
  const pixmap = layer.toPixmap();
1723
+ layer.release();
1699
1724
  for (const filter of filters)
1700
1725
  applyFilter(filter, shifted, pixmap);
1701
1726
  const result = Layer.fromPixmap(pixmap);
1702
1727
  if (result.x1 <= result.x0)
1703
- return;
1728
+ return result.release();
1704
1729
  if (rest[0] === 1 && rest[1] === 0 && rest[2] === 0 && rest[3] === 1) {
1705
1730
  target.blit(result, lx, ly);
1706
- return;
1731
+ return result.release();
1707
1732
  }
1708
1733
  const place = multiply(rest, [1, 0, 0, 1, lx, ly]);
1709
1734
  const inverse = invert(place);
1710
1735
  const coverage = inverse && rasterize([transformPoints([0, 0, lw, 0, lw, lh, 0, lh], place)], false, target.width, target.height);
1711
1736
  if (coverage)
1712
1737
  target.fill(coverage, sampler(result.data, lw, lh, inverse, false, 1, 1));
1738
+ result.release();
1713
1739
  }
1714
1740
  filtersOf(node, style, viewport) {
1715
1741
  const value = (style.filter || '').trim();
@@ -1980,7 +2006,9 @@ class Document {
1980
2006
  else
1981
2007
  this.renderImage(image, { ...ctx, style: this.computeStyle(image, this.styleOf(node)) });
1982
2008
  this.active.delete(node);
1983
- return layer.toPixmap();
2009
+ const pixmap = layer.toPixmap();
2010
+ layer.release();
2011
+ return pixmap;
1984
2012
  }
1985
2013
  };
1986
2014
  }
@@ -2164,7 +2192,7 @@ class Document {
2164
2192
  groupBoundingBox(node, viewport, matrix = [1, 0, 0, 1, 0, 0]) {
2165
2193
  let box = null;
2166
2194
  const visit = (n, matrix) => {
2167
- const image = n.name === 'image' ? this.imageOf(n, viewport) : null;
2195
+ const image = n.name === 'image' ? this.imageOf(n, viewport, false) : null;
2168
2196
  const path = image ? [['M', image.x, image.y], ['L', image.x + image.width, image.y], ['L', image.x + image.width, image.y + image.height],
2169
2197
  ['L', image.x, image.y + image.height], ['Z']] : n.name === 'text' ? this.textBox(n, viewport) : shapePath(n, viewport, 16);
2170
2198
  if (path) {
@@ -2222,6 +2250,7 @@ class Document {
2222
2250
  const regionCoverage = rasterize([transformPoints([rx, ry, rx + rw, ry, rx + rw, ry + rh, rx, ry + rh], matrix)], false, width, height);
2223
2251
  if (!regionCoverage) {
2224
2252
  this.active.delete(mask);
2253
+ layer.release();
2225
2254
  return values;
2226
2255
  }
2227
2256
  const { x0, y0, w, h, data } = regionCoverage;
@@ -2231,6 +2260,7 @@ class Document {
2231
2260
  const i = (y0 + y) * width + x0 + x;
2232
2261
  values[i] = data[y * w + x] * (alphaMask ? d[i * 4 + 3] : 0.2125 * d[i * 4] + 0.7154 * d[i * 4 + 1] + 0.0721 * d[i * 4 + 2]);
2233
2262
  }
2263
+ layer.release();
2234
2264
  const nested = this.reference(maskStyle.mask);
2235
2265
  if (nested && nested.name === 'mask' && !this.active.has(nested)) {
2236
2266
  const outer = this.maskValues(nested, node, matrix, context);
@@ -2536,11 +2566,24 @@ class Layer {
2536
2566
  y0 = Infinity;
2537
2567
  x1 = -Infinity;
2538
2568
  y1 = -Infinity;
2569
+ budgeted = 0;
2539
2570
  constructor(width, height) {
2540
2571
  this.width = width;
2541
2572
  this.height = height;
2573
+ const budget = layerBudget;
2574
+ if (budget) {
2575
+ if (!(width * height <= budget.left))
2576
+ throw new LimitError(`SVG too complex: its layers (for opacity, masks, filters, ...) exceed ${budget.limit} pixels at once (the render options' maxLayerPixels)`);
2577
+ budget.left -= width * height;
2578
+ this.budgeted = width * height;
2579
+ }
2542
2580
  this.data = new Float32Array(width * height * 4);
2543
2581
  }
2582
+ release() {
2583
+ if (layerBudget)
2584
+ layerBudget.left += this.budgeted;
2585
+ this.budgeted = 0;
2586
+ }
2544
2587
  extend(x0, y0, x1, y1) {
2545
2588
  this.x0 = Math.min(this.x0, x0);
2546
2589
  this.y0 = Math.min(this.y0, y0);
@@ -13,6 +13,7 @@ import { graphemeBoundaries, scripts } from "./segment.js";
13
13
  import { parsePaintGlyphs, paintExtent, renderPaintGlyph } from "./colr.js";
14
14
  import { decode as decodePNG } from "../codecs/png.js";
15
15
  import { resample, TRIANGLE } from "../util/resample.js";
16
+ import { MAX_PIXELS, LimitError } from "../util/limits.js";
16
17
  const SUBPIXELS = 4;
17
18
  const MAX_GLYPH_PIXELS = 1 << 26;
18
19
  const fonts = new WeakMap();
@@ -104,20 +105,17 @@ function glyphOf(f, index, size) {
104
105
  f.glyphs.set(index, g);
105
106
  return g;
106
107
  }
107
- export async function render(fonts, size, text, layout, hinting = false, foreground = 0xffffffff, features = [], variations = {}) {
108
+ export async function render(fonts, size, text, layout, hinting = false, foreground = 0xffffffff, features = [], variations = {}, maxPixels = MAX_PIXELS, pad = 0) {
108
109
  try {
109
- return await layOut(fonts, size, text, layout, hinting, foreground, features, variations);
110
+ return await layOut(fonts, size, text, layout, hinting, foreground, features, variations, maxPixels, pad);
110
111
  }
111
112
  catch (err) {
112
- if (err instanceof RangeError && !(err instanceof TooLarge))
113
+ if (err instanceof RangeError && !(err instanceof LimitError))
113
114
  throw new Error('Font: damaged or truncated font data', { cause: err });
114
115
  throw err;
115
116
  }
116
117
  }
117
- const MAX_PIXELS = 1 << 28;
118
- class TooLarge extends RangeError {
119
- }
120
- async function layOut(fonts, size, text, layout, hinting, foreground, features, variations) {
118
+ async function layOut(fonts, size, text, layout, hinting, foreground, features, variations, maxPixels, pad) {
121
119
  const sized = [];
122
120
  const font = (i) => sized[i] ??= sizedFont(fonts[i], size, hinting, variations);
123
121
  const primary = font(0);
@@ -138,8 +136,8 @@ async function layOut(fonts, size, text, layout, hinting, foreground, features,
138
136
  }
139
137
  const width = Math.max(1, Math.ceil(Math.max(0, ...visible.map(line => line.extent))));
140
138
  const height = visible.length * lineHeight;
141
- if (!(width * height <= MAX_PIXELS))
142
- throw new TooLarge(`Text too large to render (${width}x${height} pixels)`);
139
+ if (!((width + 2 * pad) * (height + 2 * pad) <= maxPixels))
140
+ 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)`);
143
141
  const coverage = new Uint8Array(width * height);
144
142
  let color = null;
145
143
  for (const [n, line] of visible.entries()) {
@@ -1,3 +1,4 @@
1
+ import { oneOf } from "./util/options.js";
1
2
  const HORIZONTAL = ['left', 'center', 'right'];
2
3
  const VERTICAL = ['top', 'middle', 'bottom'];
3
4
  export class TextLayout {
@@ -15,9 +16,7 @@ export class TextLayout {
15
16
  this.maxHeight = maxHeight === undefined || maxHeight === 0 ? Infinity : Number(maxHeight);
16
17
  if (isNaN(this.maxHeight) || this.maxHeight < 1)
17
18
  throw new RangeError('Invalid maxHeight');
18
- this.wrapStyle = wrapStyle || 'word';
19
- if (!['word', 'char'].includes(this.wrapStyle))
20
- throw new RangeError('Invalid wrapStyle');
19
+ this.wrapStyle = wrapStyle === undefined ? 'word' : oneOf(wrapStyle, ['word', 'char'], 'wrapStyle');
21
20
  if (horizontalAlign !== undefined) {
22
21
  if (!HORIZONTAL.includes(horizontalAlign))
23
22
  throw new TypeError(`horizontalAlign must be 'left', 'center' or 'right', not '${horizontalAlign}'`);