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.
@@ -25,6 +25,7 @@ export function decode(data, { transform, maxPixels = MAX_PIXELS } = {}) {
25
25
  let orientation = 1;
26
26
  const profile = [];
27
27
  let restartInterval = 0;
28
+ let scans = 0;
28
29
  let pos = 2;
29
30
  const u16 = (offset) => data[offset] << 8 | data[offset + 1];
30
31
  while (pos < data.length) {
@@ -86,6 +87,8 @@ export function decode(data, { transform, maxPixels = MAX_PIXELS } = {}) {
86
87
  case 0xc2: {
87
88
  if (frame)
88
89
  throw new Error('JPEG: multiple frames are not supported');
90
+ if (end - start < 6)
91
+ throw new Error('JPEG: truncated frame header');
89
92
  if (data[start] !== 8)
90
93
  throw new Error(`JPEG: ${data[start]}-bit precision is not supported`);
91
94
  checkPixels(u16(start + 3), u16(start + 1), maxPixels);
@@ -148,6 +151,7 @@ export function decode(data, { transform, maxPixels = MAX_PIXELS } = {}) {
148
151
  const spectralEnd = data[p + 1];
149
152
  const successiveHigh = data[p + 2] >> 4;
150
153
  const successiveLow = data[p + 2] & 15;
154
+ scans++;
151
155
  pos = decodeScan(data, end, frame, components, restartInterval, spectralStart, spectralEnd, successiveHigh, successiveLow);
152
156
  continue;
153
157
  }
@@ -156,6 +160,8 @@ export function decode(data, { transform, maxPixels = MAX_PIXELS } = {}) {
156
160
  }
157
161
  if (!frame)
158
162
  throw new Error('JPEG: missing frame header');
163
+ if (!scans)
164
+ throw new Error('JPEG: no image data (the file is truncated)');
159
165
  const icc = profile.length && Array.from(profile).every(Boolean) ? concat(profile) : undefined;
160
166
  return { width: frame.width, height: frame.height, pixels: output(frame, adobe, jfif, transform), orientation, icc };
161
167
  }
@@ -220,9 +226,10 @@ function buildHuffmanTable(counts, symbols) {
220
226
  function decodeScan(data, offset, frame, components, restartInterval, ss, se, ah, al) {
221
227
  let pos = offset;
222
228
  let buffer = 0, bits = 0;
229
+ let padding = 0;
223
230
  const fill = () => {
224
231
  while (bits <= 24) {
225
- let byte = 0;
232
+ let byte = 0, fed = false;
226
233
  if (pos < data.length) {
227
234
  byte = data[pos];
228
235
  if (byte === 0xff) {
@@ -230,11 +237,17 @@ function decodeScan(data, offset, frame, components, restartInterval, ss, se, ah
230
237
  if (next === 0x00)
231
238
  pos += 2;
232
239
  else
233
- byte = 0;
240
+ fed = true;
234
241
  }
235
242
  else
236
243
  pos++;
237
244
  }
245
+ else
246
+ fed = true;
247
+ if (fed) {
248
+ byte = 0;
249
+ padding++;
250
+ }
238
251
  buffer = buffer << 8 | byte;
239
252
  bits += 8;
240
253
  }
@@ -250,6 +263,7 @@ function decodeScan(data, offset, frame, components, restartInterval, ss, se, ah
250
263
  fill();
251
264
  return buffer >>> --bits & 1;
252
265
  };
266
+ let broken = false;
253
267
  const huffman = (table) => {
254
268
  if (!table)
255
269
  throw new Error('JPEG: missing huffman table');
@@ -263,8 +277,12 @@ function decodeScan(data, offset, frame, components, restartInterval, ss, se, ah
263
277
  let length = 10;
264
278
  let code = buffer >>> bits - 10 & 1023;
265
279
  while (code > table.maxCode[length]) {
266
- if (++length > 16)
267
- throw new Error('JPEG: invalid huffman code');
280
+ if (++length > 16) {
281
+ if (!restartInterval)
282
+ throw new Error('JPEG: invalid huffman code');
283
+ broken = true;
284
+ return 0;
285
+ }
268
286
  code = buffer >>> bits - length & (1 << length) - 1;
269
287
  }
270
288
  bits -= length;
@@ -272,6 +290,10 @@ function decodeScan(data, offset, frame, components, restartInterval, ss, se, ah
272
290
  };
273
291
  const extend = (value, size) => value < 1 << size - 1 ? value + (-1 << size) + 1 : value;
274
292
  const receiveExtend = (size) => size ? extend(getBits(size), size) : 0;
293
+ const checkComplete = () => {
294
+ if (padding * 8 > bits)
295
+ throw new Error('JPEG: the scan data is truncated');
296
+ };
275
297
  let eobrun = 0;
276
298
  const decodeBaseline = (component, offset) => {
277
299
  const coefficients = component.coefficients;
@@ -395,11 +417,12 @@ function decodeScan(data, offset, frame, components, restartInterval, ss, se, ah
395
417
  const column = unit % component.blocksPerLine;
396
418
  if (sequential) {
397
419
  pending = row;
398
- decodeBlock(component, column * 64);
420
+ if (!broken)
421
+ decodeBlock(component, column * 64);
399
422
  if (column === component.blocksPerLine - 1)
400
423
  finish();
401
424
  }
402
- else
425
+ else if (!broken)
403
426
  decodeBlock(component, (row * component.blocksPerLineForMcu + column) * 64);
404
427
  }
405
428
  else {
@@ -412,7 +435,8 @@ function decodeScan(data, offset, frame, components, restartInterval, ss, se, ah
412
435
  for (let h = 0; h < component.h; h++) {
413
436
  const row = sequential ? v : mcuRow * component.v + v;
414
437
  const column = mcuColumn * component.h + h;
415
- decodeBlock(component, (row * component.blocksPerLineForMcu + column) * 64);
438
+ if (!broken)
439
+ decodeBlock(component, (row * component.blocksPerLineForMcu + column) * 64);
416
440
  }
417
441
  if (sequential && mcuColumn === frame.mcusPerLine - 1)
418
442
  finish();
@@ -420,16 +444,23 @@ function decodeScan(data, offset, frame, components, restartInterval, ss, se, ah
420
444
  }
421
445
  if (unit >= total)
422
446
  break;
447
+ const short = !broken && padding * 8 > bits;
448
+ broken = false;
423
449
  bits = 0;
424
450
  buffer = 0;
451
+ padding = 0;
425
452
  while (pos + 1 < data.length && !(data[pos] === 0xff && data[pos + 1] >= 0xd0 && data[pos + 1] <= 0xd7)) {
426
453
  if (data[pos] === 0xff && data[pos + 1] !== 0x00 && data[pos + 1] !== 0xff) {
454
+ if (short)
455
+ throw new Error('JPEG: the scan data is truncated');
427
456
  finish();
428
457
  return pos;
429
458
  }
430
459
  pos++;
431
460
  }
432
461
  if (pos + 1 >= data.length) {
462
+ if (short)
463
+ throw new Error('JPEG: the scan data is truncated');
433
464
  finish();
434
465
  return pos;
435
466
  }
@@ -438,6 +469,8 @@ function decodeScan(data, offset, frame, components, restartInterval, ss, se, ah
438
469
  for (const component of components)
439
470
  component.pred = 0;
440
471
  }
472
+ if (!broken)
473
+ checkComplete();
441
474
  finish();
442
475
  return pos;
443
476
  }
@@ -18,8 +18,11 @@ class Sections {
18
18
  constructor(d, t) {
19
19
  this.d = d;
20
20
  this.t = t;
21
- if (t.offsets.length === 1)
21
+ if (t.offsets.length === 1) {
22
+ if (t.offsets[0] + t.sizes[0] > d.length)
23
+ throw new Error('JPEG XL: truncated data');
22
24
  this.single = new BitReader(d, t.offsets[0], t.offsets[0] + t.sizes[0]);
25
+ }
23
26
  }
24
27
  get(i) {
25
28
  if (this.single)
@@ -227,7 +227,8 @@ export async function encodeVarDCT(rgba, width, height, options) {
227
227
  if (width < 1 || height < 1)
228
228
  throw new RangeError('JPEG XL: dimensions must be at least 1');
229
229
  const n = Math.min(options.threads, Math.ceil(height / 64), Math.max(4, Math.floor(width * height / PIXELS_PER_THREAD[options.effort])));
230
- const pool = { threads: n > 1 && width * height >= MIN_THREADED_PIXELS[options.effort] ? startThreads(n) : null };
230
+ const minimum = n < 4 ? Math.max(MIN_THREADED_PIXELS[options.effort], MIN_THREADED_PIXELS[0]) : MIN_THREADED_PIXELS[options.effort];
231
+ const pool = { threads: n > 1 && width * height >= minimum ? startThreads(n) : null };
231
232
  try {
232
233
  return await encode(rgba, width, height, options, pool);
233
234
  }
@@ -355,6 +355,7 @@ function parse(array) {
355
355
  let current = null;
356
356
  let sequence = 0;
357
357
  let animationError = false;
358
+ let ended = false, truncated = false;
358
359
  let offset = 8;
359
360
  while (offset + 8 <= array.length) {
360
361
  const length = view.getUint32(offset);
@@ -367,8 +368,12 @@ function parse(array) {
367
368
  break;
368
369
  }
369
370
  const chunk = array.subarray(start, end);
370
- if (end + 4 <= array.length && crc32(array.subarray(offset + 4, end)) !== view.getUint32(end))
371
- throw new Error('PNG: chunk checksum mismatch');
371
+ if (end + 4 <= array.length && crc32(array.subarray(offset + 4, end)) !== view.getUint32(end)) {
372
+ if (!(type & 0x20000000) || type === acTL || type === fcTL || type === fdAT)
373
+ throw new Error('PNG: chunk checksum mismatch');
374
+ offset = end + 4;
375
+ continue;
376
+ }
372
377
  if (type === IHDR) {
373
378
  if (length < 13)
374
379
  throw new Error('PNG: invalid IHDR');
@@ -438,8 +443,10 @@ function parse(array) {
438
443
  srgb = true;
439
444
  else if (type === tEXt || type === zTXt || type === iTXt)
440
445
  text.push({ type, chunk });
441
- else if (type === IEND)
446
+ else if (type === IEND) {
447
+ ended = true;
442
448
  break;
449
+ }
443
450
  offset = end + 4;
444
451
  }
445
452
  if (!header)
@@ -459,10 +466,15 @@ function parse(array) {
459
466
  if (animation) {
460
467
  if (frames.length > animation.frames)
461
468
  frames.length = animation.frames;
462
- if (!frames.length || frames.length < animation.frames || frames.some(f => !f.data.length))
469
+ if (!ended) {
470
+ truncated = true;
471
+ while (frames.length && !frames[frames.length - 1].data.length)
472
+ frames.pop();
473
+ }
474
+ if (!frames.length || (frames.length < animation.frames && !truncated) || frames.some(f => !f.data.length))
463
475
  animationError = true;
464
476
  }
465
- return { header, palette, transparency, idat, exif, iccp: srgb ? null : iccp, text, animation, frames, animationError };
477
+ return { header, palette, transparency, idat, exif, iccp: srgb ? null : iccp, text, animation, frames, animationError, truncated };
466
478
  }
467
479
  function passesOf(p, width, height) {
468
480
  const bitsPerPixel = COLOR_TYPE_CHANNELS[p.header.colorType] * p.header.depth;
@@ -547,27 +559,45 @@ export async function decodeAnimation(array, firstFrameOnly = false, maxPixels =
547
559
  checkPixels(width, height, maxPixels, !p.animation || p.animationError || firstFrameOnly ? 1 : Math.max(1, p.frames.length));
548
560
  if (!p.animation || p.animationError) {
549
561
  const pixels = await decodeImageData(p, p.idat, width, height);
550
- return { width, height, plays: 0, frames: [{ x: 0, y: 0, width, height, duration: 0, dispose: 0, blend: 0, pixels }], icc: await profile(p.iccp), orientation };
562
+ const still = async function* () {
563
+ yield { x: 0, y: 0, width, height, duration: 0, dispose: 0, blend: 0, pixels };
564
+ };
565
+ return { width, height, plays: 0, frames: still(), icc: await profile(p.iccp), orientation };
551
566
  }
552
- const frames = [];
553
- for (const { control: c, data } of p.frames) {
567
+ for (const { control: c } of p.frames)
554
568
  if (!c.width || !c.height || c.x + c.width > width || c.y + c.height > height)
555
569
  throw new Error('PNG: invalid APNG frame region');
556
- frames.push({
557
- x: c.x, y: c.y, width: c.width, height: c.height, duration: c.delay,
558
- dispose: !frames.length && c.dispose === 2 ? 1 : c.dispose,
559
- blend: c.blend,
560
- pixels: await decodeImageData(p, data, c.width, c.height)
561
- });
562
- if (firstFrameOnly)
563
- break;
570
+ async function* frames() {
571
+ let count = 0;
572
+ for (const { control: c, data } of p.frames) {
573
+ let pixels;
574
+ try {
575
+ pixels = await decodeImageData(p, data, c.width, c.height);
576
+ }
577
+ catch (error) {
578
+ if (p.truncated && count)
579
+ return;
580
+ throw error;
581
+ }
582
+ yield {
583
+ x: c.x, y: c.y, width: c.width, height: c.height, duration: c.delay,
584
+ dispose: !count++ && c.dispose === 2 ? 1 : c.dispose,
585
+ blend: c.blend,
586
+ pixels
587
+ };
588
+ if (firstFrameOnly)
589
+ return;
590
+ }
564
591
  }
565
- return { width, height, plays: p.animation.plays, frames, icc: await profile(p.iccp), orientation };
592
+ return { width, height, plays: p.animation.plays, frames: frames(), icc: await profile(p.iccp), orientation };
566
593
  }
567
594
  export function compositeAnimation({ width, height, frames }) {
595
+ const step = compositor(width, height);
596
+ return frames.map(f => ({ pixels: step(f), duration: f.duration }));
597
+ }
598
+ export function compositor(width, height) {
568
599
  const canvas = new Uint8Array(width * height * 4);
569
- const output = [];
570
- for (const f of frames) {
600
+ return f => {
571
601
  const previous = f.dispose === 2 ? canvas.slice() : null;
572
602
  for (let y = 0; y < f.height; y++) {
573
603
  if (f.blend === 0) {
@@ -593,14 +623,14 @@ export function compositeAnimation({ width, height, frames }) {
593
623
  }
594
624
  }
595
625
  }
596
- output.push({ pixels: canvas.slice(), duration: f.duration });
626
+ const shown = canvas.slice();
597
627
  if (f.dispose === 1)
598
628
  for (let y = 0; y < f.height; y++)
599
629
  canvas.fill(0, ((f.y + y) * width + f.x) * 4, ((f.y + y) * width + f.x + f.width) * 4);
600
630
  else if (previous)
601
631
  canvas.set(previous);
602
- }
603
- return output;
632
+ return shown;
633
+ };
604
634
  }
605
635
  const RAW_EXIF = /^Raw profile type (exif|APP1)$/;
606
636
  const XMP = 'XML:com.adobe.xmp';
@@ -1,18 +1,16 @@
1
- import { oneOf } from "../util/options.js";
1
+ import { oneOf, finite } from "../util/options.js";
2
2
  const WR = 3, WG = 4, WB = 2;
3
3
  const DITHER = { 'none': true, 'floyd-steinberg': true, 'atkinson': true, 'ordered': true };
4
4
  export const DITHER_METHODS = Object.keys(DITHER);
5
5
  export function paletteOptions(colors, dither, ditherStrength) {
6
6
  let count;
7
7
  if (colors !== undefined) {
8
- count = Number(colors);
8
+ count = finite(colors, 'colors');
9
9
  if (!Number.isInteger(count) || count < 2 || count > 256)
10
10
  throw new RangeError(`colors must be an integer from 2 to 256, not ${colors}`);
11
11
  }
12
12
  oneOf(dither, DITHER_METHODS, 'dither');
13
- const strength = Number(ditherStrength);
14
- if (!Number.isFinite(strength))
15
- throw new RangeError(`Invalid ditherStrength: ${ditherStrength}`);
13
+ const strength = finite(ditherStrength, 'ditherStrength');
16
14
  if (strength < 0 || strength > 1)
17
15
  throw new RangeError(`ditherStrength must be 0-1, not ${ditherStrength}`);
18
16
  return { colors: count, dither: dither, strength };
@@ -118,6 +118,8 @@ export async function decode(data, maxPixels = MAX_PIXELS) {
118
118
  const samplesPerPixel = value(TAGS.SamplesPerPixel, 1);
119
119
  const bitsPerSample = values(TAGS.BitsPerSample, [1]);
120
120
  const bps = bitsPerSample[0];
121
+ if (typeof bps !== 'number')
122
+ throw new Error('TIFF: invalid BitsPerSample');
121
123
  if (bitsPerSample.some(b => b !== bps))
122
124
  throw new Error('TIFF: mixed bit depths are not supported');
123
125
  const compression = value(TAGS.Compression, 1);
@@ -134,7 +136,7 @@ export async function decode(data, maxPixels = MAX_PIXELS) {
134
136
  if (![0, 1, 2, 3, 5, 6].includes(photometric))
135
137
  throw new Error(`TIFF: photometric interpretation ${photometric} is not supported`);
136
138
  if (sampleFormat === 3 ? bps !== 32 && bps !== 64 : bps < 1 || bps > 32)
137
- throw new Error(`TIFF: ${bps}-bit samples are not supported`);
139
+ throw new Error(`TIFF: ${bps}-bit ${sampleFormat === 3 ? 'floating-point ' : ''}samples are not supported`);
138
140
  const colorChannels = { 0: 1, 1: 1, 2: 3, 3: 1, 5: 4, 6: 3 }[photometric];
139
141
  if (samplesPerPixel < colorChannels)
140
142
  throw new Error('TIFF: not enough samples per pixel');
@@ -160,6 +162,8 @@ export async function decode(data, maxPixels = MAX_PIXELS) {
160
162
  checkPixels(width, height, maxPixels);
161
163
  checkPixels(segmentWidth, segmentHeight, Math.max(4 * width * height, 1 << 20));
162
164
  checkBytes(Math.ceil(width * samplesPerPixel * bps / 8) * height, maxPixels);
165
+ if (samplesPerPixel > 32)
166
+ throw new Error('TIFF: unsupported number of samples per pixel');
163
167
  const pixels = new Uint8Array(width * height * 4);
164
168
  if (compression === 7) {
165
169
  const jpegTables = tags.get(TAGS.JPEGTables);
@@ -186,8 +190,11 @@ export async function decode(data, maxPixels = MAX_PIXELS) {
186
190
  if (tiled || planar || bps !== 8)
187
191
  throw new Error('TIFF: subsampled YCbCr is only supported for 8-bit strips');
188
192
  const [h, v] = subsampling;
193
+ if (![1, 2, 4].includes(h) || ![1, 2, 4].includes(v))
194
+ throw new Error('TIFF: unsupported YCbCr subsampling');
189
195
  const unitsPerRow = Math.ceil(width / h);
190
196
  const unitRowBytes = unitsPerRow * (h * v + 2);
197
+ checkBytes(Math.ceil(height / v) * unitRowBytes, maxPixels);
191
198
  const units = new Uint8Array(Math.ceil(height / v) * unitRowBytes);
192
199
  let written = 0;
193
200
  for (let s = 0; s < segmentsPerPlane && written < units.length; s++) {
@@ -294,7 +294,7 @@ export function decode(data, maxPixels = MAX_PIXELS) {
294
294
  inverseDCT(coeffs, b * 16, plane, cBase + (i >> 1) * 4 * cs + (i & 1) * 4, cs, ac >> b & 1);
295
295
  }
296
296
  }
297
- if (tokens.exhausted && d.exhausted)
297
+ if (tokens.exhausted || d.exhausted)
298
298
  throw new Error('VP8: unexpected end of data');
299
299
  }
300
300
  if (h.filterLevel)
@@ -8,7 +8,7 @@ import { encodeVP8, encodeAlpha } from "./vp8-enc.js";
8
8
  import { rgbaToYUV } from "./vp8-enc-dsp.js";
9
9
  import { orientation as exifOrientation } from "./exif.js";
10
10
  import { MAX_PIXELS, checkPixels } from "../util/limits.js";
11
- import { effort as checkEffort, quality as checkQuality } from "../util/options.js";
11
+ import { effort as checkEffort, quality as checkQuality, boolean as checkBoolean } from "../util/options.js";
12
12
  import { startThreads } from "../util/threads.js";
13
13
  const fourCC = (s) => s.charCodeAt(0) | s.charCodeAt(1) << 8 | s.charCodeAt(2) << 16 | s.charCodeAt(3) << 24;
14
14
  const RIFF = fourCC('RIFF'), WEBP = fourCC('WEBP');
@@ -22,7 +22,7 @@ function chunks(data, start, end) {
22
22
  const type = view.getUint32(offset, true);
23
23
  const size = view.getUint32(offset + 4, true);
24
24
  const dataStart = offset + 8;
25
- out.push({ type, data: data.subarray(dataStart, Math.min(end, dataStart + size)) });
25
+ out.push({ type, data: data.subarray(dataStart, Math.min(end, dataStart + size)), cut: dataStart + size > end });
26
26
  offset = dataStart + size + (size & 1);
27
27
  }
28
28
  return out;
@@ -40,6 +40,8 @@ const u24 = (d, o) => d[o] | d[o + 1] << 8 | d[o + 2] << 16;
40
40
  function decodeBitstream(list, maxPixels) {
41
41
  let alpha = null;
42
42
  for (const chunk of list) {
43
+ if ((chunk.type === ALPH || chunk.type === VP8L || chunk.type === VP8) && chunk.cut)
44
+ throw new Error('WebP: the image data is truncated');
43
45
  if (chunk.type === ALPH)
44
46
  alpha ??= chunk;
45
47
  else if (chunk.type === VP8L) {
@@ -148,19 +150,22 @@ export function decodeAnimation(data, firstFrameOnly = false, maxPixels = MAX_PI
148
150
  const width = u24(header.data, 4) + 1, height = u24(header.data, 7) + 1;
149
151
  checkPixels(width, height, maxPixels, firstFrameOnly ? 1 : list.filter(c => c.type === ANMF).length);
150
152
  let loopCount = 0, background = 0;
151
- const frames = [];
152
- for (const chunk of list) {
153
- if (chunk.type === ANIM && chunk.data.length >= 6) {
154
- const d = chunk.data;
155
- background = (d[3] << 24 | d[2] << 16 | d[1] << 8 | d[0]) >>> 0;
156
- loopCount = d[4] | d[5] << 8;
157
- }
158
- else if (chunk.type === ANMF) {
159
- const d = chunk.data;
160
- if (d.length < 16)
161
- throw new Error('WebP: invalid ANMF chunk');
153
+ const anim = list.find(c => c.type === ANIM && c.data.length >= 6);
154
+ if (anim) {
155
+ const d = anim.data;
156
+ background = (d[3] << 24 | d[2] << 16 | d[1] << 8 | d[0]) >>> 0;
157
+ loopCount = d[4] | d[5] << 8;
158
+ }
159
+ const anmf = list.filter(c => c.type === ANMF && !c.cut);
160
+ if (!anmf.length && list.some(c => c.type === ANMF))
161
+ throw new Error('WebP: unexpected end of data');
162
+ for (const { data } of anmf)
163
+ if (data.length < 16)
164
+ throw new Error('WebP: invalid ANMF chunk');
165
+ function* frames() {
166
+ for (const { data: d } of anmf) {
162
167
  const frame = decodeBitstream(chunks(d, 16, d.length), maxPixels);
163
- frames.push({
168
+ yield {
164
169
  x: u24(d, 0) * 2,
165
170
  y: u24(d, 3) * 2,
166
171
  width: frame.width,
@@ -169,14 +174,12 @@ export function decodeAnimation(data, firstFrameOnly = false, maxPixels = MAX_PI
169
174
  blend: (d[15] & 2) === 0,
170
175
  dispose: (d[15] & 1) === 1,
171
176
  pixels: frame.pixels
172
- });
177
+ };
173
178
  if (firstFrameOnly)
174
- break;
179
+ return;
175
180
  }
176
181
  }
177
- if (!frames.length)
178
- throw new Error('WebP: animation without frames');
179
- return { width, height, loopCount, background, frames, icc: list.find(c => c.type === ICCP)?.data, orientation: orientationOf(list) };
182
+ return { width, height, loopCount, background, frames: frames(), icc: list.find(c => c.type === ICCP)?.data, orientation: orientationOf(list) };
180
183
  }
181
184
  function orientationOf(list) {
182
185
  const exif = list.find(c => c.type === EXIF);
@@ -294,10 +297,11 @@ export async function encode(rgba, width, height, exif, threads = 1, effort = 2)
294
297
  }
295
298
  export function lossyOptions(quality, effort, sharp, alphaQuality) {
296
299
  checkEffort(effort, 6);
300
+ const a = checkQuality(alphaQuality, 'alphaQuality');
301
+ checkBoolean(sharp, 'sharpYuv');
297
302
  if (quality === undefined)
298
303
  return undefined;
299
- const q = checkQuality(quality), a = checkQuality(alphaQuality, 'alphaQuality');
300
- return { quality: q, method: effort, sharp, alphaQuality: Math.round(a) };
304
+ return { quality: checkQuality(quality), method: effort, sharp, alphaQuality: Math.round(a) };
301
305
  }
302
306
  export async function encodeLossy(rgba, width, height, lossy, exif) {
303
307
  const { alpha, chunks } = await lossyChunks(rgba, width, height, lossy);
package/dist/colors.d.ts CHANGED
@@ -74,6 +74,9 @@ export declare class Colors {
74
74
  * Creates a multi-point gradient generator
75
75
  * @param stops The colors along the gradient: their positions (0..1) and colors (`{ 0: 0xff0000ff, 1: 0x00ff00ff }`),
76
76
  * or just the colors, evenly spaced (`[0xff0000ff, 0x00ff00ff]`), like {@link GradientOptions.stops}
77
+ * @remarks A stop may lie outside 0..1 (`{ 0: red, 2: blue }`): it is where it says, so the part between 0 and 1
78
+ * shows only part of the way between its colors. Before the first stop and after the last one, the gradient has
79
+ * their colors
77
80
  * @return The gradient generator. The function argument is the position in the gradient (0..1).
78
81
  */
79
82
  static gradient(stops: Record<number, Color> | Color[]): (position: number) => Color;
package/dist/colors.js CHANGED
@@ -1,4 +1,4 @@
1
- import { finite, color as checkColor } from "./util/options.js";
1
+ import { finite, checkNumber, color as checkColor } from "./util/options.js";
2
2
  export function channel(value) {
3
3
  return value > 255 ? 255 : value > 0 ? Math.round(value) : 0;
4
4
  }
@@ -48,25 +48,34 @@ export function rgbaToHSLA(r, g, b, a) {
48
48
  }
49
49
  return [h, s, l, a / 255];
50
50
  }
51
+ function checkPosition(position) {
52
+ checkNumber(position, 'gradient position');
53
+ if (Number.isNaN(position))
54
+ throw new RangeError(`Invalid gradient position: ${position}`);
55
+ }
51
56
  function gradientBetween(startColor, endColor) {
52
- const sr = startColor >>> 24;
53
- const sg = startColor >> 16 & 0xff;
54
- const sb = startColor >> 8 & 0xff;
55
- const sa = startColor & 0xff;
56
- const er = (endColor >>> 24) - sr;
57
- const eg = (endColor >> 16 & 0xff) - sg;
58
- const eb = (endColor >> 8 & 0xff) - sb;
59
- const ea = (endColor & 0xff) - sa;
57
+ const sr = startColor >>> 24, sg = startColor >> 16 & 0xff, sb = startColor >> 8 & 0xff, sa = startColor & 0xff;
58
+ const er = (endColor >>> 24) - sr, eg = (endColor >> 16 & 0xff) - sg, eb = (endColor >> 8 & 0xff) - sb, ea = (endColor & 0xff) - sa;
59
+ if (sa === 255 && ea === 0)
60
+ return position => {
61
+ const r = sr + position * er, g = sg + position * eg, b = sb + position * eb;
62
+ return (((r & 0xff) << 24) | ((g & 0xff) << 16) | ((b & 0xff) << 8) | 0xff) >>> 0;
63
+ };
64
+ const pr = sr * sa / 255, pg = sg * sa / 255, pb = sb * sa / 255;
65
+ const dr = (er + sr) * (ea + sa) / 255 - pr, dg = (eg + sg) * (ea + sa) / 255 - pg, db = (eb + sb) * (ea + sa) / 255 - pb;
60
66
  return position => {
61
- const r = sr + position * er;
62
- const g = sg + position * eg;
63
- const b = sb + position * eb;
64
67
  const a = sa + position * ea;
68
+ if (a <= 0)
69
+ return 0;
70
+ const k = 255 / a;
71
+ const r = Math.min(255, (pr + position * dr) * k + 1e-9), g = Math.min(255, (pg + position * dg) * k + 1e-9), b = Math.min(255, (pb + position * db) * k + 1e-9);
65
72
  return (((r & 0xff) << 24) | ((g & 0xff) << 16) | ((b & 0xff) << 8) | (a & 0xff)) >>> 0;
66
73
  };
67
74
  }
68
75
  export class Colors {
69
- constructor() { }
76
+ constructor() {
77
+ throw new TypeError('Colors only has static methods, like Colors.fromRGBA()');
78
+ }
70
79
  static fromRGBA(r, g, b, a) {
71
80
  r = finite(r, 'red');
72
81
  g = finite(g, 'green');
@@ -115,6 +124,8 @@ export class Colors {
115
124
  return [h * 360, s, l, alpha];
116
125
  }
117
126
  static gradient(stops) {
127
+ if (typeof stops !== 'object' || stops === null)
128
+ throw new TypeError(`gradient() takes an array of colors or an object of positions and colors, not ${stops === null ? 'null' : typeof stops}`);
118
129
  let colors;
119
130
  if (Array.isArray(stops)) {
120
131
  if (!stops.length)
@@ -130,13 +141,15 @@ export class Colors {
130
141
  if (positions.length === 0)
131
142
  throw new RangeError('Invalid gradient point count');
132
143
  else if (positions.length === 1) {
133
- return () => values[0];
144
+ return position => {
145
+ checkPosition(position);
146
+ return values[0];
147
+ };
134
148
  }
135
149
  else if (positions.length === 2) {
136
150
  const gradient = gradientBetween(values[0], values[1]);
137
151
  return position => {
138
- if (Number.isNaN(position))
139
- throw new RangeError(`Invalid gradient position: ${position}`);
152
+ checkPosition(position);
140
153
  if (position <= positions[0])
141
154
  return values[0];
142
155
  if (position >= positions[1])
@@ -163,8 +176,7 @@ export class Colors {
163
176
  }
164
177
  if (!gradients.length)
165
178
  return position => {
166
- if (Number.isNaN(position))
167
- throw new RangeError(`Invalid gradient position: ${position}`);
179
+ checkPosition(position);
168
180
  return position <= minDef ? values[0] : values[values.length - 1];
169
181
  };
170
182
  return position => {
package/dist/frame.d.ts CHANGED
@@ -9,17 +9,30 @@ import { Image, ResizeOptions, ResizeToOptions, TrimOptions, RotateOptions, Tran
9
9
  export type FrameDisposalMode = 'any' | 'keep' | 'previous' | 'background';
10
10
  /** Options of {@link Frame} */
11
11
  export interface FrameOptions {
12
- /** The frame's duration in milliseconds. Default: `100` */
12
+ /**
13
+ * The frame's duration in milliseconds
14
+ * @defaultValue `100`
15
+ */
13
16
  duration?: number;
14
- /** The frame's offset on the x-axis. Default: `0` */
17
+ /**
18
+ * The frame's offset on the x-axis
19
+ * @defaultValue `0`
20
+ */
15
21
  xOffset?: number;
16
- /** The frame's offset on the y-axis. Default: `0` */
22
+ /**
23
+ * The frame's offset on the y-axis
24
+ * @defaultValue `0`
25
+ */
17
26
  yOffset?: number;
18
- /** The frame's disposal mode, see {@link Frame.disposalMode}. Default: `'keep'` */
27
+ /**
28
+ * The frame's disposal mode, see {@link Frame.disposalMode}
29
+ * @defaultValue `'keep'`
30
+ */
19
31
  disposalMode?: FrameDisposalMode;
20
32
  }
21
33
  /**
22
- * A frame of an {@link Animation}: an {@link Image} ({@link Frame.image}) with a duration, offsets and a disposal mode.
34
+ * A frame of an {@link Animation}: an {@link Image} ({@link Frame.image}) with a duration, offsets and a disposal mode
35
+ * @remarks
23
36
  * The frame has the methods that change the image's size (`resize()` including its `'contain'` and `'cover'` fit
24
37
  * modes, `scale()`, `crop()`, `trim()`, `rotate()`, `transform()`, `dropShadow()` and `outline()`), which move the
25
38
  * offsets along so the frame stays in place in the animation; every other change goes to the image
package/dist/frame.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { Image } from "./image.js";
2
2
  import { checkOptions, finite, oneOf } from "./util/options.js";
3
+ import { describe } from "./util/inspect.js";
3
4
  const DISPOSAL_MODES = ['any', 'keep', 'previous', 'background'];
4
5
  export class Frame {
5
6
  __image__;
@@ -112,3 +113,4 @@ export class Frame {
112
113
  return this.__tracked__(image => image.outline(options));
113
114
  }
114
115
  }
116
+ describe(Frame, frame => ({ width: frame.width, height: frame.height, duration: frame.duration }));