imagescript 4.0.0-rc.4 → 4.0.0-rc.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +9 -5
  2. package/dist/animation-encoder.d.ts +2 -1
  3. package/dist/animation-encoder.js +23 -19
  4. package/dist/animation.d.ts +26 -20
  5. package/dist/animation.js +58 -55
  6. package/dist/codecs/avif-enc.js +3 -3
  7. package/dist/codecs/avif.js +7 -2
  8. package/dist/codecs/bmp.js +1 -1
  9. package/dist/codecs/gif.js +2 -2
  10. package/dist/codecs/jpeg.js +55 -14
  11. package/dist/codecs/jxl/vardct-enc.js +2 -1
  12. package/dist/codecs/png.js +7 -3
  13. package/dist/codecs/tga.js +4 -3
  14. package/dist/codecs/tiff.js +1 -1
  15. package/dist/codecs/vp8.js +1 -1
  16. package/dist/codecs/vp8l.js +4 -3
  17. package/dist/codecs/webp.js +11 -9
  18. package/dist/colors.d.ts +10 -8
  19. package/dist/colors.js +28 -31
  20. package/dist/frame.d.ts +4 -3
  21. package/dist/frame.js +6 -8
  22. package/dist/gainmap.d.ts +6 -6
  23. package/dist/gainmap.js +32 -24
  24. package/dist/image.d.ts +75 -37
  25. package/dist/image.js +189 -163
  26. package/dist/metadata.d.ts +12 -1
  27. package/dist/metadata.js +30 -5
  28. package/dist/render/color.js +16 -3
  29. package/dist/render/colr.js +3 -3
  30. package/dist/render/filter.js +27 -3
  31. package/dist/render/font.js +54 -18
  32. package/dist/render/layout.js +2 -2
  33. package/dist/render/linebreak.js +9 -12
  34. package/dist/render/svg-text.js +112 -28
  35. package/dist/render/svg.js +183 -34
  36. package/dist/render/text.js +93 -23
  37. package/dist/text-layout.d.ts +2 -1
  38. package/dist/text-layout.js +3 -8
  39. package/dist/util/alpha.js +1 -1
  40. package/dist/util/inspect.js +16 -0
  41. package/dist/util/limits.d.ts +16 -3
  42. package/dist/util/limits.js +20 -5
  43. package/dist/util/mem.d.ts +2 -0
  44. package/dist/util/mem.js +24 -4
  45. package/dist/util/optimize.js +4 -3
  46. package/dist/util/options.js +104 -7
  47. package/package.json +1 -1
@@ -5,7 +5,7 @@
5
5
  * (Copyright 2014 Mozilla Foundation, Apache License 2.0). See THIRD_PARTY_NOTICES.md
6
6
  */
7
7
  import { ByteWriter } from "../util/bytes.js";
8
- import { MAX_PIXELS, checkPixels } from "../util/limits.js";
8
+ import { MAX_PIXELS, checkPixels, checkFormatSize } from "../util/limits.js";
9
9
  import { orientation as exifOrientation } from "./exif.js";
10
10
  import { concat } from "../util/mem.js";
11
11
  import { littleEndian } from "../util/alpha.js";
@@ -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) {
@@ -91,7 +92,7 @@ export function decode(data, { transform, maxPixels = MAX_PIXELS } = {}) {
91
92
  if (data[start] !== 8)
92
93
  throw new Error(`JPEG: ${data[start]}-bit precision is not supported`);
93
94
  checkPixels(u16(start + 3), u16(start + 1), maxPixels);
94
- frame = createFrame(marker === 0xc2, u16(start + 1), u16(start + 3), data.subarray(start + 5, end));
95
+ frame = createFrame(marker === 0xc2, u16(start + 1), u16(start + 3), data.subarray(start + 5, end), data.length - end);
95
96
  break;
96
97
  }
97
98
  case 0xc3:
@@ -150,6 +151,7 @@ export function decode(data, { transform, maxPixels = MAX_PIXELS } = {}) {
150
151
  const spectralEnd = data[p + 1];
151
152
  const successiveHigh = data[p + 2] >> 4;
152
153
  const successiveLow = data[p + 2] & 15;
154
+ scans++;
153
155
  pos = decodeScan(data, end, frame, components, restartInterval, spectralStart, spectralEnd, successiveHigh, successiveLow);
154
156
  continue;
155
157
  }
@@ -158,10 +160,12 @@ export function decode(data, { transform, maxPixels = MAX_PIXELS } = {}) {
158
160
  }
159
161
  if (!frame)
160
162
  throw new Error('JPEG: missing frame header');
163
+ if (!scans)
164
+ throw new Error('JPEG: no image data (the file is truncated)');
161
165
  const icc = profile.length && Array.from(profile).every(Boolean) ? concat(profile) : undefined;
162
166
  return { width: frame.width, height: frame.height, pixels: output(frame, adobe, jfif, transform), orientation, icc };
163
167
  }
164
- function createFrame(progressive, height, width, componentData) {
168
+ function createFrame(progressive, height, width, componentData, available) {
165
169
  const count = componentData[0];
166
170
  const sampling = [];
167
171
  for (let i = 0; i < count; i++) {
@@ -176,6 +180,13 @@ function createFrame(progressive, height, width, componentData) {
176
180
  const vmax = Math.max(...sampling.map(c => c.v));
177
181
  const mcusPerLine = Math.ceil(width / (8 * hmax));
178
182
  const mcusPerColumn = Math.ceil(height / (8 * vmax));
183
+ if (!progressive) {
184
+ let blocks = 0;
185
+ for (const c of sampling)
186
+ blocks += Math.ceil(Math.ceil(width * c.h / hmax) / 8) * Math.ceil(Math.ceil(height * c.v / vmax) / 8);
187
+ if (blocks * 2 > available * 8)
188
+ throw new Error('JPEG: the scan data is truncated');
189
+ }
179
190
  const components = sampling.map((c) => {
180
191
  const componentWidth = Math.ceil(width * c.h / hmax);
181
192
  const componentHeight = Math.ceil(height * c.v / vmax);
@@ -222,9 +233,10 @@ function buildHuffmanTable(counts, symbols) {
222
233
  function decodeScan(data, offset, frame, components, restartInterval, ss, se, ah, al) {
223
234
  let pos = offset;
224
235
  let buffer = 0, bits = 0;
236
+ let padding = 0;
225
237
  const fill = () => {
226
238
  while (bits <= 24) {
227
- let byte = 0;
239
+ let byte = 0, fed = false;
228
240
  if (pos < data.length) {
229
241
  byte = data[pos];
230
242
  if (byte === 0xff) {
@@ -232,11 +244,17 @@ function decodeScan(data, offset, frame, components, restartInterval, ss, se, ah
232
244
  if (next === 0x00)
233
245
  pos += 2;
234
246
  else
235
- byte = 0;
247
+ fed = true;
236
248
  }
237
249
  else
238
250
  pos++;
239
251
  }
252
+ else
253
+ fed = true;
254
+ if (fed) {
255
+ byte = 0;
256
+ padding++;
257
+ }
240
258
  buffer = buffer << 8 | byte;
241
259
  bits += 8;
242
260
  }
@@ -252,6 +270,7 @@ function decodeScan(data, offset, frame, components, restartInterval, ss, se, ah
252
270
  fill();
253
271
  return buffer >>> --bits & 1;
254
272
  };
273
+ let broken = false;
255
274
  const huffman = (table) => {
256
275
  if (!table)
257
276
  throw new Error('JPEG: missing huffman table');
@@ -265,8 +284,12 @@ function decodeScan(data, offset, frame, components, restartInterval, ss, se, ah
265
284
  let length = 10;
266
285
  let code = buffer >>> bits - 10 & 1023;
267
286
  while (code > table.maxCode[length]) {
268
- if (++length > 16)
269
- throw new Error('JPEG: invalid huffman code');
287
+ if (++length > 16) {
288
+ if (!restartInterval)
289
+ throw new Error('JPEG: invalid huffman code');
290
+ broken = true;
291
+ return 0;
292
+ }
270
293
  code = buffer >>> bits - length & (1 << length) - 1;
271
294
  }
272
295
  bits -= length;
@@ -274,6 +297,10 @@ function decodeScan(data, offset, frame, components, restartInterval, ss, se, ah
274
297
  };
275
298
  const extend = (value, size) => value < 1 << size - 1 ? value + (-1 << size) + 1 : value;
276
299
  const receiveExtend = (size) => size ? extend(getBits(size), size) : 0;
300
+ const checkComplete = () => {
301
+ if (padding * 8 > bits)
302
+ throw new Error('JPEG: the scan data is truncated');
303
+ };
277
304
  let eobrun = 0;
278
305
  const decodeBaseline = (component, offset) => {
279
306
  const coefficients = component.coefficients;
@@ -397,11 +424,12 @@ function decodeScan(data, offset, frame, components, restartInterval, ss, se, ah
397
424
  const column = unit % component.blocksPerLine;
398
425
  if (sequential) {
399
426
  pending = row;
400
- decodeBlock(component, column * 64);
427
+ if (!broken)
428
+ decodeBlock(component, column * 64);
401
429
  if (column === component.blocksPerLine - 1)
402
430
  finish();
403
431
  }
404
- else
432
+ else if (!broken)
405
433
  decodeBlock(component, (row * component.blocksPerLineForMcu + column) * 64);
406
434
  }
407
435
  else {
@@ -414,7 +442,8 @@ function decodeScan(data, offset, frame, components, restartInterval, ss, se, ah
414
442
  for (let h = 0; h < component.h; h++) {
415
443
  const row = sequential ? v : mcuRow * component.v + v;
416
444
  const column = mcuColumn * component.h + h;
417
- decodeBlock(component, (row * component.blocksPerLineForMcu + column) * 64);
445
+ if (!broken)
446
+ decodeBlock(component, (row * component.blocksPerLineForMcu + column) * 64);
418
447
  }
419
448
  if (sequential && mcuColumn === frame.mcusPerLine - 1)
420
449
  finish();
@@ -422,16 +451,23 @@ function decodeScan(data, offset, frame, components, restartInterval, ss, se, ah
422
451
  }
423
452
  if (unit >= total)
424
453
  break;
454
+ const short = !broken && padding * 8 > bits;
455
+ broken = false;
425
456
  bits = 0;
426
457
  buffer = 0;
458
+ padding = 0;
427
459
  while (pos + 1 < data.length && !(data[pos] === 0xff && data[pos + 1] >= 0xd0 && data[pos + 1] <= 0xd7)) {
428
460
  if (data[pos] === 0xff && data[pos + 1] !== 0x00 && data[pos + 1] !== 0xff) {
461
+ if (short)
462
+ throw new Error('JPEG: the scan data is truncated');
429
463
  finish();
430
464
  return pos;
431
465
  }
432
466
  pos++;
433
467
  }
434
468
  if (pos + 1 >= data.length) {
469
+ if (short)
470
+ throw new Error('JPEG: the scan data is truncated');
435
471
  finish();
436
472
  return pos;
437
473
  }
@@ -440,6 +476,8 @@ function decodeScan(data, offset, frame, components, restartInterval, ss, se, ah
440
476
  for (const component of components)
441
477
  component.pred = 0;
442
478
  }
479
+ if (!broken)
480
+ checkComplete();
443
481
  finish();
444
482
  return pos;
445
483
  }
@@ -809,9 +847,10 @@ function reciprocals(table) {
809
847
  }
810
848
  return r;
811
849
  }
812
- export function encode(pixels, width, height, quality = 90, { exif, comment, segments, gray = false, fullChroma = false, subsampling } = {}) {
813
- if (!width || !height || width > 0xffff || height > 0xffff)
850
+ export function encode(pixels, width, height, quality = 90, { exif, comment, segments, gray = false, fullChroma = false, subsampling, rows } = {}) {
851
+ if (!width || !height)
814
852
  throw new RangeError('JPEG: invalid dimensions');
853
+ checkFormatSize('JPEG', width, height, 0xffff);
815
854
  quality = Math.min(100, Math.max(1, Math.round(quality)));
816
855
  const scale = quality < 50 ? Math.floor(5000 / quality) : 200 - quality * 2;
817
856
  const scaleTable = (base) => base.map(v => Math.min(255, Math.max(1, Math.floor((v * scale + 50) / 100))));
@@ -829,10 +868,12 @@ export function encode(pixels, width, height, quality = 90, { exif, comment, seg
829
868
  const Y = new Uint8Array(W * lumaBlocksY * 8), Cb = new Uint8Array(CW * chromaBlocksY * 8), Cr = new Uint8Array(CW * chromaBlocksY * 8);
830
869
  const rowWidth = CW * hmax;
831
870
  const cbRows = subsample ? new Uint8Array(2 * rowWidth) : Cb, crRows = subsample ? new Uint8Array(2 * rowWidth) : Cr;
832
- const words = littleEndian && pixels.byteOffset % 4 === 0 ? new Uint32Array(pixels.buffer, pixels.byteOffset, width * height) : null;
871
+ const words = littleEndian && pixels.byteOffset % 4 === 0 ? new Uint32Array(pixels.buffer, pixels.byteOffset, (rows ? width : width * height)) : null;
833
872
  for (let y = 0; y < height; y++) {
873
+ if (rows)
874
+ rows(y);
834
875
  const row = subsample ? (y & 1) * rowWidth : y * CW;
835
- let i = y * width * 4, o = y * W, c = row;
876
+ let i = rows ? 0 : y * width * 4, o = y * W, c = row;
836
877
  if (words)
837
878
  for (let x = 0, w = i >> 2; x < width; x++, w++, o++, c++) {
838
879
  const p = words[w], r = p & 255, g = p >> 8 & 255, b = p >> 16 & 255;
@@ -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
  }
@@ -258,7 +258,7 @@ export async function encodeRGBA(rgba, width, height, level, text) {
258
258
  }
259
259
  export async function encodeAnimation(frames, width, height, plays, level, text) {
260
260
  if (!frames.length)
261
- throw new Error('PNG: an animation needs at least one frame');
261
+ throw new RangeError('PNG: an animation needs at least one frame, not 0');
262
262
  frames = [coverCanvas(frames[0], width, height), ...frames.slice(1)];
263
263
  for (const f of frames)
264
264
  checkFrame(f, width, height);
@@ -368,8 +368,12 @@ function parse(array) {
368
368
  break;
369
369
  }
370
370
  const chunk = array.subarray(start, end);
371
- if (end + 4 <= array.length && crc32(array.subarray(offset + 4, end)) !== view.getUint32(end))
372
- 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
+ }
373
377
  if (type === IHDR) {
374
378
  if (length < 13)
375
379
  throw new Error('PNG: invalid IHDR');
@@ -1,5 +1,5 @@
1
1
  import { encode as utf8 } from "../util/utf8.js";
2
- import { MAX_PIXELS, checkPixels } from "../util/limits.js";
2
+ import { MAX_PIXELS, checkPixels, checkFormatSize } from "../util/limits.js";
3
3
  const SIGNATURE = 'TRUEVISION-XFILE.\0';
4
4
  function readHeader(d) {
5
5
  if (d.length < 18)
@@ -182,8 +182,9 @@ function extensionArea({ author, comment, time, software }, alpha) {
182
182
  return area;
183
183
  }
184
184
  export function encode(rgba, width, height, extension) {
185
- if (width < 1 || height < 1 || width > 65535 || height > 65535)
186
- throw new RangeError('TGA: dimensions must be 1-65535');
185
+ if (width < 1 || height < 1)
186
+ throw new RangeError('TGA: dimensions must be at least 1');
187
+ checkFormatSize('TGA', width, height, 65535);
187
188
  let opaque = true;
188
189
  for (let i = 3; i < rgba.length; i += 4)
189
190
  if (rgba[i] !== 255) {
@@ -136,7 +136,7 @@ export async function decode(data, maxPixels = MAX_PIXELS) {
136
136
  if (![0, 1, 2, 3, 5, 6].includes(photometric))
137
137
  throw new Error(`TIFF: photometric interpretation ${photometric} is not supported`);
138
138
  if (sampleFormat === 3 ? bps !== 32 && bps !== 64 : bps < 1 || bps > 32)
139
- 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`);
140
140
  const colorChannels = { 0: 1, 1: 1, 2: 3, 3: 1, 5: 4, 6: 3 }[photometric];
141
141
  if (samplesPerPixel < colorChannels)
142
142
  throw new Error('TIFF: not enough samples per pixel');
@@ -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)
@@ -6,7 +6,7 @@
6
6
  * Copyright (c) 2012 Google Inc., BSD-3-Clause License
7
7
  */
8
8
  import { ByteWriter } from "../util/bytes.js";
9
- import { MAX_PIXELS, checkPixels } from "../util/limits.js";
9
+ import { MAX_PIXELS, checkPixels, checkFormatSize } from "../util/limits.js";
10
10
  import { runChunks, shared } from "../util/threads.js";
11
11
  const SIGNATURE = 0x2f;
12
12
  const CODE_LENGTH_ORDER = [17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
@@ -1462,8 +1462,9 @@ export function predictorChunks({ p, src, modes, width, height, bits, candidates
1462
1462
  };
1463
1463
  }
1464
1464
  export async function encode(argb, width, height, threads = null, effort = 2) {
1465
- if (width < 1 || height < 1 || width > 16384 || height > 16384)
1466
- throw new RangeError('VP8L: dimensions must be 1-16384');
1465
+ if (width < 1 || height < 1)
1466
+ throw new RangeError('WebP: dimensions must be at least 1');
1467
+ checkFormatSize('WebP', width, height, 16384);
1467
1468
  const tuning = TUNING[Math.min(2, effort)];
1468
1469
  const colors = new Map();
1469
1470
  for (let i = 0; i < argb.length && colors.size <= 256; i++)
@@ -7,8 +7,8 @@ import * as vp8 from "./vp8.js";
7
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
- import { MAX_PIXELS, checkPixels } from "../util/limits.js";
11
- import { effort as checkEffort, quality as checkQuality } from "../util/options.js";
10
+ import { MAX_PIXELS, checkPixels, checkFormatSize } from "../util/limits.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');
@@ -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) {
@@ -295,10 +297,12 @@ export async function encode(rgba, width, height, exif, threads = 1, effort = 2)
295
297
  }
296
298
  export function lossyOptions(quality, effort, sharp, alphaQuality) {
297
299
  checkEffort(effort, 6);
300
+ const a = checkQuality(alphaQuality, 'alphaQuality');
301
+ checkBoolean(sharp, 'sharpYuv');
298
302
  if (quality === undefined)
299
303
  return undefined;
300
- const q = checkQuality(quality), a = checkQuality(alphaQuality, 'alphaQuality');
301
- return { quality: q, method: effort, sharp, alphaQuality: Math.round(a) };
304
+ const q = checkQuality(quality);
305
+ return q === 100 ? undefined : { quality: q, method: effort, sharp, alphaQuality: Math.round(a) };
302
306
  }
303
307
  export async function encodeLossy(rgba, width, height, lossy, exif) {
304
308
  const { alpha, chunks } = await lossyChunks(rgba, width, height, lossy);
@@ -311,8 +315,7 @@ export async function encodeLossy(rgba, width, height, lossy, exif) {
311
315
  return riff([riffChunk('VP8X', vp8x), ...chunks, ...exif ? [riffChunk('EXIF', exif)] : []]);
312
316
  }
313
317
  async function lossyChunks(rgba, width, height, { quality, method, sharp, alphaQuality }) {
314
- if (width > 16383 || height > 16383)
315
- throw new RangeError('WebP: lossy images can be at most 16383 pixels wide and high');
318
+ checkFormatSize('WebP', width, height, 16383);
316
319
  const picture = rgbaToYUV(rgba, width, height, sharp);
317
320
  const frame = encodeVP8(picture, quality, method);
318
321
  const padded = new Uint8Array(frame.length + (frame.length & 1));
@@ -328,9 +331,8 @@ export function lossyTolerance(quality) {
328
331
  }
329
332
  export async function encodeAnimation(frames, width, height, plays, exif, lossy, effort = 2) {
330
333
  if (!frames.length)
331
- throw new Error('WebP: an animation needs at least one frame');
332
- if (width > 1 << 24 || height > 1 << 24)
333
- throw new RangeError('WebP: canvas too large');
334
+ throw new RangeError('WebP: an animation needs at least one frame, not 0');
335
+ checkFormatSize('WebP', width, height, 1 << 24);
334
336
  let alpha = false;
335
337
  for (const [i, f] of frames.entries())
336
338
  alpha ||= needsAlpha(f, i === 0, width, height);
package/dist/colors.d.ts CHANGED
@@ -1,6 +1,4 @@
1
1
  import type { Color } from './image.js';
2
- /** Clamps and rounds a channel value to 0..255 */
3
- export declare function channel(value: number): number;
4
2
  export declare function wrapHue(h: number): number;
5
3
  export declare function hue2rgb(p: number, q: number, t: number): number;
6
4
  /**
@@ -19,7 +17,7 @@ export declare function rgbaToHSLA(r: number, g: number, b: number, a: number):
19
17
  export declare class Colors {
20
18
  private constructor();
21
19
  /**
22
- * Converts RGBA components to an RGBA value, values are rounded and clamped to 0..255
20
+ * Converts RGBA components to an RGBA value. Fractions are rounded, values outside of 0..255 throw a `RangeError`
23
21
  * @param r red (0..255)
24
22
  * @param g green (0..255)
25
23
  * @param b blue (0..255)
@@ -38,17 +36,17 @@ export declare class Colors {
38
36
  /**
39
37
  * Converts HSLA colors to RGBA colors
40
38
  * @param h hue in degrees (0..360, like CSS' `hsl()`: 0 red, 120 green, 240 blue; other values wrap around)
41
- * @param s saturation (0..1)
42
- * @param l lightness (0..1)
43
- * @param a opacity (0..1)
39
+ * @param s saturation (0..1, else a `RangeError`)
40
+ * @param l lightness (0..1, else a `RangeError`)
41
+ * @param a opacity (0..1, else a `RangeError`)
44
42
  * @returns color
45
43
  */
46
44
  static fromHSLA(h: number, s: number, l: number, a: number): Color;
47
45
  /**
48
46
  * Converts HSL colors to RGBA colors (fully opaque)
49
47
  * @param h hue in degrees (0..360, like CSS' `hsl()`; other values wrap around)
50
- * @param s saturation (0..1)
51
- * @param l lightness (0..1)
48
+ * @param s saturation (0..1, else a `RangeError`)
49
+ * @param l lightness (0..1, else a `RangeError`)
52
50
  * @returns color
53
51
  */
54
52
  static fromHSL(h: number, s: number, l: number): Color;
@@ -74,6 +72,10 @@ export declare class Colors {
74
72
  * Creates a multi-point gradient generator
75
73
  * @param stops The colors along the gradient: their positions (0..1) and colors (`{ 0: 0xff0000ff, 1: 0x00ff00ff }`),
76
74
  * or just the colors, evenly spaced (`[0xff0000ff, 0x00ff00ff]`), like {@link GradientOptions.stops}
75
+ * @remarks A stop may lie outside 0..1 (`{ 0: red, 2: blue }`): it is where it says, so the part between 0 and 1
76
+ * shows only part of the way between its colors. Before the first stop and after the last one, the gradient has
77
+ * their colors, and at a stop its color. Stops at the same position make a hard edge: the gradient jumps from
78
+ * the earlier stop's color to the later one's, which is the color at that position (like CSS)
77
79
  * @return The gradient generator. The function argument is the position in the gradient (0..1).
78
80
  */
79
81
  static gradient(stops: Record<number, Color> | Color[]): (position: number) => Color;
package/dist/colors.js CHANGED
@@ -1,7 +1,4 @@
1
- import { finite, checkNumber, color as checkColor } from "./util/options.js";
2
- export function channel(value) {
3
- return value > 255 ? 255 : value > 0 ? Math.round(value) : 0;
4
- }
1
+ import { shown, finite, notNaN, byte, unitInterval, color as checkColor } from "./util/options.js";
5
2
  export function wrapHue(h) {
6
3
  const t = h - Math.trunc(h) + 1;
7
4
  return t < 1 ? t : t < 2 ? t - 1 : 0;
@@ -49,9 +46,7 @@ export function rgbaToHSLA(r, g, b, a) {
49
46
  return [h, s, l, a / 255];
50
47
  }
51
48
  function checkPosition(position) {
52
- checkNumber(position, 'gradient position');
53
- if (Number.isNaN(position))
54
- throw new RangeError(`Invalid gradient position: ${position}`);
49
+ notNaN(position, 'gradient position');
55
50
  }
56
51
  function gradientBetween(startColor, endColor) {
57
52
  const sr = startColor >>> 24, sg = startColor >> 16 & 0xff, sb = startColor >> 8 & 0xff, sa = startColor & 0xff;
@@ -73,25 +68,20 @@ function gradientBetween(startColor, endColor) {
73
68
  };
74
69
  }
75
70
  export class Colors {
76
- constructor() { }
71
+ constructor() {
72
+ throw new TypeError('Colors only has static methods, like Colors.fromRGBA()');
73
+ }
77
74
  static fromRGBA(r, g, b, a) {
78
- r = finite(r, 'red');
79
- g = finite(g, 'green');
80
- b = finite(b, 'blue');
81
- a = finite(a, 'alpha');
82
- return (channel(r) << 24 | channel(g) << 16 | channel(b) << 8 | channel(a)) >>> 0;
75
+ return (byte(r, 'red') << 24 | byte(g, 'green') << 16 | byte(b, 'blue') << 8 | byte(a, 'alpha')) >>> 0;
83
76
  }
84
77
  static fromRGB(r, g, b) {
85
78
  return Colors.fromRGBA(r, g, b, 0xff);
86
79
  }
87
80
  static fromHSLA(h, s, l, a) {
88
81
  h = wrapHue(finite(h, 'hue') / 360);
89
- s = finite(s, 'saturation');
90
- l = finite(l, 'lightness');
91
- a = finite(a, 'alpha');
92
- s = Math.min(1, Math.max(0, s));
93
- l = Math.min(1, Math.max(0, l));
94
- a = Math.min(1, Math.max(0, a));
82
+ s = unitInterval(s, 'saturation');
83
+ l = unitInterval(l, 'lightness');
84
+ a = unitInterval(a, 'alpha');
95
85
  let r, g, b;
96
86
  if (s === 0) {
97
87
  r = g = b = l;
@@ -122,10 +112,12 @@ export class Colors {
122
112
  return [h * 360, s, l, alpha];
123
113
  }
124
114
  static gradient(stops) {
115
+ if (typeof stops !== 'object' || stops === null)
116
+ throw new TypeError(`Colors.gradient() takes an array of colors or an object of positions and colors, not ${shown(stops)}`);
125
117
  let colors;
126
118
  if (Array.isArray(stops)) {
127
119
  if (!stops.length)
128
- throw new RangeError('Invalid gradient point count');
120
+ throw new RangeError('Colors.gradient() takes at least one color, not 0');
129
121
  const list = stops.length === 1 ? [stops[0], stops[0]] : stops;
130
122
  colors = Object.fromEntries(list.map((color, i) => [i / (list.length - 1), color]));
131
123
  }
@@ -135,7 +127,7 @@ export class Colors {
135
127
  const positions = entries.map(e => finite(parseFloat(e[0]), 'gradient position'));
136
128
  const values = entries.map(e => checkColor(e[1]));
137
129
  if (positions.length === 0)
138
- throw new RangeError('Invalid gradient point count');
130
+ throw new RangeError('Colors.gradient() takes at least one color, not 0');
139
131
  else if (positions.length === 1) {
140
132
  return position => {
141
133
  checkPosition(position);
@@ -146,15 +138,15 @@ export class Colors {
146
138
  const gradient = gradientBetween(values[0], values[1]);
147
139
  return position => {
148
140
  checkPosition(position);
149
- if (position <= positions[0])
150
- return values[0];
151
141
  if (position >= positions[1])
152
142
  return values[1];
143
+ if (position <= positions[0])
144
+ return values[0];
153
145
  return gradient((position - positions[0]) / (positions[1] - positions[0]));
154
146
  };
155
147
  }
156
- const minDef = Math.min(...positions);
157
- const maxDef = Math.max(...positions);
148
+ const minDef = positions[0];
149
+ const maxDef = positions[positions.length - 1];
158
150
  const gradients = [];
159
151
  for (let i = 0; i < positions.length; i++) {
160
152
  const minPos = positions[i - 1];
@@ -173,17 +165,22 @@ export class Colors {
173
165
  if (!gradients.length)
174
166
  return position => {
175
167
  checkPosition(position);
176
- return position <= minDef ? values[0] : values[values.length - 1];
168
+ return position < minDef ? values[0] : values[values.length - 1];
177
169
  };
170
+ const atStop = new Map(positions.map((p, i) => [p, values[i]]));
178
171
  return position => {
179
- if (position <= minDef)
180
- return gradients[0].gradient(0);
172
+ checkPosition(position);
173
+ if (position < minDef)
174
+ return values[0];
181
175
  if (position >= maxDef)
182
- return gradients[gradients.length - 1].gradient(1);
176
+ return values[values.length - 1];
177
+ const stop = atStop.get(position);
178
+ if (stop !== undefined)
179
+ return stop;
183
180
  for (const gradient of gradients)
184
- if (position >= gradient.min && position <= gradient.max)
181
+ if (position > gradient.min && position < gradient.max)
185
182
  return gradient.gradient((position - gradient.min) / (gradient.max - gradient.min));
186
- throw new RangeError(`Invalid gradient position: ${position}`);
183
+ throw new RangeError(`The gradient has no color at position ${position}`);
187
184
  };
188
185
  }
189
186
  }
package/dist/frame.d.ts CHANGED
@@ -58,9 +58,10 @@ export declare class Frame {
58
58
  /** The frame's height (its image's) */
59
59
  get height(): number;
60
60
  /**
61
- * The frame's duration in milliseconds (a finite number from 0, else it throws a RangeError). GIFs store
62
- * hundredths of a second, so this is rounded to 10 ms when encoding a GIF; note that browsers play frames shorter
63
- * than 20 ms with 100 ms
61
+ * The frame's duration in milliseconds (a finite number from 0, else it throws a RangeError). It doesn't have to
62
+ * be a whole number: encoding rounds it, to whole milliseconds for APNG and WebP and, as GIFs store hundredths of
63
+ * a second, to 10 ms for GIF (1.5 ms becomes 0, 5 ms becomes 10). Browsers play GIF frames shorter than 20 ms with
64
+ * 100 ms
64
65
  */
65
66
  get duration(): number;
66
67
  /**
package/dist/frame.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { Image } from "./image.js";
2
- import { checkOptions, finite, oneOf } from "./util/options.js";
2
+ import { instance, checkOptions, finite, nonNegative, 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__;
@@ -13,7 +14,7 @@ export class Frame {
13
14
  constructor(image, options = {}) {
14
15
  if (!(image instanceof Image))
15
16
  throw new TypeError('A frame takes an Image, like new Frame(image, { duration: 100 })');
16
- checkOptions(options, 'Frame(image, { duration: 100 })');
17
+ checkOptions(options, 'new Frame(image, { duration: 100 })');
17
18
  const { duration = 100, xOffset: x = 0, yOffset: y = 0, disposalMode: disposal = 'keep' } = options;
18
19
  this.__image__ = image;
19
20
  this.duration = duration;
@@ -25,8 +26,7 @@ export class Frame {
25
26
  return this.__image__;
26
27
  }
27
28
  set image(image) {
28
- if (!(image instanceof Image))
29
- throw new TypeError('A frame\'s image has to be an Image');
29
+ instance(image, [Image], 'frame.image');
30
30
  this.__image__ = image;
31
31
  }
32
32
  get width() {
@@ -39,10 +39,7 @@ export class Frame {
39
39
  return this.__duration__;
40
40
  }
41
41
  set duration(duration) {
42
- const value = finite(duration, 'frame duration');
43
- if (value < 0)
44
- throw new RangeError('Invalid frame duration');
45
- this.__duration__ = value;
42
+ this.__duration__ = nonNegative(duration, 'frame duration');
46
43
  }
47
44
  get xOffset() {
48
45
  return this.__x__;
@@ -112,3 +109,4 @@ export class Frame {
112
109
  return this.__tracked__(image => image.outline(options));
113
110
  }
114
111
  }
112
+ describe(Frame, frame => ({ width: frame.width, height: frame.height, duration: frame.duration }));
package/dist/gainmap.d.ts CHANGED
@@ -4,7 +4,7 @@ import { BinaryData } from './util/mem.js';
4
4
  /** Options of {@link GainMap.encodeJPEG} */
5
5
  export interface GainMapEncodeOptions {
6
6
  /**
7
- * The JPEG quality (1-100)
7
+ * The JPEG quality (0-100, like {@link Image.encodeJPEG}'s: 0 is 1)
8
8
  * @defaultValue `90`
9
9
  */
10
10
  quality?: number;
@@ -64,8 +64,8 @@ export interface GainMapOptions {
64
64
  * location. For developers who need the exact calculation, the boost is
65
65
  * `2^(min + (max - min) * (v / 255)^(1 / gamma))`, per color channel.
66
66
  *
67
- * The parameters are checked when they are set: a value that isn't finite (or an array of other than 1 or 3 of them)
68
- * throws, and the map keeps its value
67
+ * The parameters are checked when they are set: a value that isn't finite or lies beyond ±(2^31 - 1) (what the
68
+ * formats store), a gamma below 2^-31, or an array of other than 1 or 3 of them throws, and the map keeps its value
69
69
  */
70
70
  export declare class GainMap {
71
71
  /** log2 of the boost of the map's value 0, per channel (red, green, blue; a copy: assign to change it) */
@@ -86,7 +86,7 @@ export declare class GainMap {
86
86
  get gamma(): readonly [red: number, green: number, blue: number];
87
87
  /**
88
88
  * Replaces the value (checked: an invalid one throws and the old one stays)
89
- * @param value One number above 0 for all channels or [r, g, b]
89
+ * @param value One number from 2^-31 for all channels or [r, g, b]
90
90
  */
91
91
  set gamma(value: GainMapChannelValues);
92
92
  /** Added to the SDR image's linear values before the boost, per channel (a copy: assign to change it) */
@@ -107,14 +107,14 @@ export declare class GainMap {
107
107
  get hdrCapacityMin(): number;
108
108
  /**
109
109
  * Replaces the value (checked: an invalid one throws and the old one stays)
110
- * @param value A finite number from 0
110
+ * @param value A finite number from 0, below `hdrCapacityMax`
111
111
  */
112
112
  set hdrCapacityMin(value: number);
113
113
  /** log2 of the display headroom at which it applies fully (above `hdrCapacityMin`) */
114
114
  get hdrCapacityMax(): number;
115
115
  /**
116
116
  * Replaces the value (checked: an invalid one throws and the old one stays)
117
- * @param value A finite number
117
+ * @param value A finite number above `hdrCapacityMin`
118
118
  */
119
119
  set hdrCapacityMax(value: number);
120
120
  /** Whether the boost applies in the SDR image's color space (else in the HDR image's) */