imagescript 4.0.0-rc.5 → 4.0.0

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/index.d.ts CHANGED
@@ -1,5 +1,10 @@
1
1
  /**
2
2
  * @packageDocumentation
3
+ * @document ../guides/Choosing ImageScript.md
4
+ * @document ../guides/Coming from Jimp.md
5
+ * @document ../guides/Generate favicons.md
6
+ * @document ../guides/Shrink images before upload.md
7
+ * @document ../guides/Social cards for static sites.md
3
8
  * @document ../guides/Migrating to 4.0.md
4
9
  */
5
10
  import { BinaryData } from './util/mem.js';
@@ -12,6 +12,13 @@
12
12
  * The Exif and TGA text fields are ASCII in the file format; other characters are written as UTF-8, which readers
13
13
  * that follow the format show wrongly. PNG text chunks take any text.
14
14
  *
15
+ * Decoding doesn't read metadata: it applies the orientation and the ICC profile to the pixels and drops the rest
16
+ * (Exif, XMP, text), so a decoded image is written with only the metadata given to the encoder.
17
+ *
18
+ * Some formats limit the length: in JPEG the comment and the Exif fields together hold up to 65533 bytes each, and
19
+ * longer ones throw a `RangeError` before encoding. TGA cuts the author and the software to 40 bytes and the comment to
20
+ * 4 lines of 80 bytes.
21
+ *
15
22
  * Empty fields (and `null` ones) are left out. Without metadata, the files only say which software made them (`software`), so the same
16
23
  * image always encodes to the same bytes
17
24
  */
@@ -25,7 +32,8 @@ export interface Metadata {
25
32
  /** The image's copyright info */
26
33
  copyright?: string;
27
34
  /**
28
- * The image's creation time
35
+ * The image's creation time (a date, a timestamp or a date string, in the years 1000 to 9999: the formats write
36
+ * the year with 4 digits)
29
37
  * @defaultValue None (`null` leaves it out, too)
30
38
  */
31
39
  creationTime?: string | number | Date | null;
package/dist/metadata.js CHANGED
@@ -1,15 +1,33 @@
1
1
  import { encode as utf8 } from "./util/utf8.js";
2
+ import { shown } from "./util/options.js";
2
3
  import * as exif from "./codecs/exif.js";
4
+ function isDate(value) {
5
+ if (typeof value !== 'object' || value === null)
6
+ return false;
7
+ try {
8
+ Date.prototype.getTime.call(value);
9
+ return true;
10
+ }
11
+ catch {
12
+ return false;
13
+ }
14
+ }
3
15
  const TEXT_FIELDS = ['title', 'author', 'description', 'copyright', 'software', 'disclaimer', 'warning', 'source', 'comment'];
4
16
  export function resolveMetadata(metadata = {}) {
5
17
  if (metadata === null || typeof metadata !== 'object' || Array.isArray(metadata))
6
- throw new TypeError(`metadata takes an object, like { title: 'Sunset' }, not ${metadata === null ? 'null' : Array.isArray(metadata) ? 'an array' : typeof metadata}`);
18
+ throw new TypeError(`metadata takes an object, like { title: 'Sunset' }, not ${shown(metadata)}`);
7
19
  const { creationTime, software } = metadata;
8
20
  const resolved = {};
9
21
  if (creationTime !== undefined && creationTime !== null) {
22
+ if (!isDate(creationTime) && typeof creationTime !== 'number' && typeof creationTime !== 'string') {
23
+ throw new TypeError(`creationTime must be a Date, a number or a string, not ${typeof creationTime === 'object' ? shown(creationTime) : typeof creationTime}`);
24
+ }
10
25
  const time = new Date(creationTime);
11
26
  if (isNaN(time.getTime()))
12
- throw new RangeError('Invalid creation time');
27
+ throw new RangeError(`creationTime must be a date, a timestamp or a date string, not ${shown(creationTime)}`);
28
+ const year = time.getUTCFullYear();
29
+ if (year < 1000 || year > 9999)
30
+ throw new RangeError(`creationTime's year must be from 1000 to 9999, not ${year}`);
13
31
  resolved.creationTime = time;
14
32
  }
15
33
  for (const key of TEXT_FIELDS) {
@@ -17,7 +35,7 @@ export function resolveMetadata(metadata = {}) {
17
35
  if (value === undefined || value === null || value === '')
18
36
  continue;
19
37
  if (typeof value !== 'string')
20
- throw new TypeError(`metadata ${key} must be a string, not ${typeof value}`);
38
+ throw new TypeError(`metadata ${key} must be a string, not ${shown(value)}`);
21
39
  resolved[key] = value;
22
40
  }
23
41
  return resolved;
@@ -1,3 +1,10 @@
1
+ export const MAX_BITMAP_GLYPH_PIXELS = 2048 * 2048;
2
+ export function bitmapPixels(png) {
3
+ if (png.length < 24 || png[12] !== 0x49 || png[13] !== 0x48 || png[14] !== 0x44 || png[15] !== 0x52)
4
+ return NaN;
5
+ const view = new DataView(png.buffer, png.byteOffset, png.length);
6
+ return view.getUint32(16) * view.getUint32(20);
7
+ }
1
8
  export function parsePalette(font, cpal) {
2
9
  const entries = font.u16(cpal + 2), records = cpal + font.u32(cpal + 8), first = font.u16(cpal + 12);
3
10
  return index => {
@@ -22,7 +29,7 @@ export function parseColorLayers(font) {
22
29
  return result;
23
30
  result = null;
24
31
  for (let lo = 0, hi = baseCount - 1; lo <= hi;) {
25
- const mid = lo + hi >> 1, record = bases + mid * 6, id = font.u16(record);
32
+ const mid = lo + hi >>> 1, record = bases + mid * 6, id = font.u16(record);
26
33
  if (id < glyph)
27
34
  lo = mid + 1;
28
35
  else if (id > glyph)
@@ -58,7 +65,10 @@ function parseSbix(font, size) {
58
65
  if (sbix === undefined)
59
66
  return null;
60
67
  const strikes = Array.from({ length: font.u32(sbix + 4) }, (_, i) => sbix + font.u32(sbix + 8 + i * 4));
61
- const index = closestStrike(strikes.map(strike => font.u16(strike)), size);
68
+ const ppems = strikes.map(strike => font.u16(strike));
69
+ if (ppems.includes(0))
70
+ throw new Error('Font: damaged sbix table (a strike of 0 pixels per em)');
71
+ const index = closestStrike(ppems, size);
62
72
  if (index < 0)
63
73
  return null;
64
74
  const strike = strikes[index], ppem = font.u16(strike);
@@ -91,7 +101,10 @@ function parseCBDT(font, size) {
91
101
  const cblc = font.tables.CBLC?.offset, cbdt = font.tables.CBDT?.offset;
92
102
  if (cblc === undefined || cbdt === undefined)
93
103
  return null;
94
- const ppems = Array.from({ length: font.u32(cblc + 4) }, (_, i) => font.u8(cblc + 8 + i * 48 + 45));
104
+ const strikes = font.count(font.u32(cblc + 4), cblc + 8, 48, 'CBLC table');
105
+ const ppems = Array.from({ length: strikes }, (_, i) => font.u8(cblc + 8 + i * 48 + 45));
106
+ if (ppems.includes(0))
107
+ throw new Error('Font: damaged CBLC table (a strike of 0 pixels per em)');
95
108
  const index = closestStrike(ppems, size);
96
109
  if (index < 0)
97
110
  return null;
@@ -12,11 +12,11 @@ export function parsePaintGlyphs(font) {
12
12
  if (!baseList)
13
13
  return null;
14
14
  const clipList = font.u32(colr + 22) ? colr + font.u32(colr + 22) : 0;
15
- const count = font.u32(baseList), clips = clipList ? font.u32(clipList + 1) : 0;
15
+ const count = font.count(font.u32(baseList), baseList + 4, 6, 'COLR table'), clips = clipList ? font.count(font.u32(clipList + 1), clipList + 5, 7, 'COLR table') : 0;
16
16
  return {
17
17
  paint: glyph => {
18
18
  for (let lo = 0, hi = count - 1; lo <= hi;) {
19
- const mid = lo + hi >> 1, record = baseList + 4 + mid * 6, id = font.u16(record);
19
+ const mid = lo + hi >>> 1, record = baseList + 4 + mid * 6, id = font.u16(record);
20
20
  if (id < glyph)
21
21
  lo = mid + 1;
22
22
  else if (id > glyph)
@@ -28,7 +28,7 @@ export function parsePaintGlyphs(font) {
28
28
  },
29
29
  clip: glyph => {
30
30
  for (let lo = 0, hi = clips - 1; lo <= hi;) {
31
- const mid = lo + hi >> 1, record = clipList + 5 + mid * 7;
31
+ const mid = lo + hi >>> 1, record = clipList + 5 + mid * 7;
32
32
  if (font.u16(record + 2) < glyph)
33
33
  lo = mid + 1;
34
34
  else if (font.u16(record) > glyph)
@@ -135,15 +135,16 @@ function intRect(r, m) {
135
135
  }
136
136
  const sameRect = (a, b) => a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;
137
137
  const scaleOf = (m) => [Math.hypot(m[0], m[1]), Math.hypot(m[2], m[3])];
138
- export function applyFilter(filter, ts, source) {
139
- const result = filterResult(filter, ts, source);
138
+ export function applyFilter(filter, ts, source, budget = UNBOUNDED) {
139
+ const result = filterResult(filter, ts, source, budget);
140
140
  source.data.fill(0);
141
141
  if (!result)
142
142
  return;
143
143
  const { image, region } = result;
144
144
  draw(source, inColorSpace(image, false).pixmap, region.x, region.y);
145
145
  }
146
- function filterResult(filter, ts, full) {
146
+ const UNBOUNDED = { work() { }, keep() { }, free() { } };
147
+ function filterResult(filter, ts, full, budget) {
147
148
  const r = intRect(filter.rect, ts);
148
149
  const x0 = Math.max(r.x, 0), y0 = Math.max(r.y, 0), x1 = Math.min(r.x + r.width, full.width), y1 = Math.min(r.y + r.height, full.height);
149
150
  if (x1 <= x0 || y1 <= y0)
@@ -171,8 +172,30 @@ function filterResult(filter, ts, full) {
171
172
  return results[i].image;
172
173
  return input('SourceGraphic');
173
174
  };
175
+ let kept = 0;
176
+ try {
177
+ return runPrimitives(filter, matrix, region, outputRegion, input, results, pixels => {
178
+ budget.keep(pixels);
179
+ kept += pixels;
180
+ }, budget);
181
+ }
182
+ finally {
183
+ budget.free(kept);
184
+ }
185
+ }
186
+ function cost(kind) {
187
+ if (kind.type === 'convolve')
188
+ return Math.max(1, kind.columns * kind.rows / 9);
189
+ if (kind.type === 'turbulence')
190
+ return Math.max(1, kind.octaves);
191
+ if (kind.type === 'merge')
192
+ return Math.max(1, kind.inputs.length);
193
+ return 1;
194
+ }
195
+ function runPrimitives(filter, matrix, region, outputRegion, input, results, keep, budget) {
174
196
  for (const primitive of filter.primitives) {
175
197
  const { kind } = primitive;
198
+ budget.work(region.width * region.height * cost(kind));
176
199
  let subregion = intRect(primitive.rect, matrix);
177
200
  if (kind.type === 'offset' && typeof kind.input === 'object') {
178
201
  const name = kind.input.result;
@@ -189,6 +212,7 @@ function filterResult(filter, ts, full) {
189
212
  clearOutside(pixmap, subregion);
190
213
  result = { pixmap, region: subregion, linear: result.linear };
191
214
  }
215
+ keep(result.pixmap.width * result.pixmap.height);
192
216
  results.push({ name: primitive.result, image: result });
193
217
  }
194
218
  const last = results.pop();
@@ -49,6 +49,8 @@ export class Font {
49
49
  throw new Error(`Font: missing ${tag} table`);
50
50
  const head = this.tables.head.offset;
51
51
  this.unitsPerEm = this.u16(head + 18);
52
+ if (!this.unitsPerEm)
53
+ throw new Error('Font: damaged head table (0 units per em)');
52
54
  this.indexToLocFormat = this.i16(head + 50);
53
55
  const hhea = this.tables.hhea.offset;
54
56
  this.ascender = this.i16(hhea + 4);
@@ -108,10 +110,16 @@ export class Font {
108
110
  const base = Object.getPrototypeOf(this) instanceof Font ? Object.getPrototypeOf(this) : this;
109
111
  const key = coords.join(',');
110
112
  const cached = base.instances?.get(key);
111
- if (cached)
113
+ if (cached) {
114
+ base.instances.delete(key);
115
+ base.instances.set(key, cached);
112
116
  return cached;
117
+ }
113
118
  const instance = Object.create(base);
114
- (base.instances ??= new Map()).set(key, instance);
119
+ const instances = base.instances ??= new Map();
120
+ if (instances.size >= 64)
121
+ instances.delete(instances.keys().next().value);
122
+ instances.set(key, instance);
115
123
  instance.coords = coords;
116
124
  instance.outlineCache = new Map();
117
125
  const metric = (tag, value) => {
@@ -135,6 +143,11 @@ export class Font {
135
143
  i16(o) { return this.view.getInt16(o); }
136
144
  u32(o) { return this.view.getUint32(o); }
137
145
  i32(o) { return this.view.getInt32(o); }
146
+ count(count, start, size, what) {
147
+ if (start + count * size > this.data.length)
148
+ throw new Error(`Font: damaged ${what}`);
149
+ return count;
150
+ }
138
151
  glyphIndex(codepoint) {
139
152
  return this.cmap(codepoint) || 0;
140
153
  }
@@ -481,7 +494,7 @@ function parseCmap(font, offset) {
481
494
  return 0;
482
495
  let lo = 0, hi = segments - 1;
483
496
  while (lo < hi) {
484
- const mid = lo + hi >> 1;
497
+ const mid = lo + hi >>> 1;
485
498
  if (font.u16(ends + mid * 2) < c)
486
499
  lo = mid + 1;
487
500
  else
@@ -499,11 +512,11 @@ function parseCmap(font, offset) {
499
512
  };
500
513
  }
501
514
  else {
502
- const groups = font.u32(table + 12);
515
+ const groups = font.count(font.u32(table + 12), table + 16, 12, 'cmap table');
503
516
  lookup = (c) => {
504
517
  let lo = 0, hi = groups - 1;
505
518
  while (lo <= hi) {
506
- const mid = lo + hi >> 1;
519
+ const mid = lo + hi >>> 1;
507
520
  const group = table + 16 + mid * 12;
508
521
  if (c < font.u32(group))
509
522
  hi = mid - 1;
@@ -530,11 +543,11 @@ function parseVariations(font, offset) {
530
543
  if (table < 0)
531
544
  return null;
532
545
  const u24 = (o) => font.u8(o) << 16 | font.u16(o + 1);
533
- const records = font.u32(table + 6);
546
+ const records = font.count(font.u32(table + 6), table + 10, 11, 'cmap table');
534
547
  return (codepoint, selector) => {
535
548
  let lo = 0, hi = records - 1;
536
549
  while (lo <= hi) {
537
- const mid = lo + hi >> 1, record = table + 10 + mid * 11, vs = u24(record);
550
+ const mid = lo + hi >>> 1, record = table + 10 + mid * 11, vs = u24(record);
538
551
  if (vs < selector)
539
552
  lo = mid + 1;
540
553
  else if (vs > selector)
@@ -543,9 +556,9 @@ function parseVariations(font, offset) {
543
556
  const defaults = font.u32(record + 3), others = font.u32(record + 7);
544
557
  if (others) {
545
558
  const o = table + others;
546
- let l = 0, h = font.u32(o) - 1;
559
+ let l = 0, h = font.count(font.u32(o), o + 4, 5, 'cmap table') - 1;
547
560
  while (l <= h) {
548
- const m = l + h >> 1, u = u24(o + 4 + m * 5);
561
+ const m = l + h >>> 1, u = u24(o + 4 + m * 5);
549
562
  if (u < codepoint)
550
563
  l = m + 1;
551
564
  else if (u > codepoint)
@@ -556,9 +569,9 @@ function parseVariations(font, offset) {
556
569
  }
557
570
  if (defaults) {
558
571
  const o = table + defaults;
559
- let l = 0, h = font.u32(o) - 1;
572
+ let l = 0, h = font.count(font.u32(o), o + 4, 4, 'cmap table') - 1;
560
573
  while (l <= h) {
561
- const m = l + h >> 1, start = u24(o + 4 + m * 4);
574
+ const m = l + h >>> 1, start = u24(o + 4 + m * 4);
562
575
  if (codepoint < start)
563
576
  h = m - 1;
564
577
  else if (codepoint > start + font.u8(o + 4 + m * 4 + 3))
@@ -578,7 +591,7 @@ export function parseCoverage(font, table) {
578
591
  return glyph => {
579
592
  let lo = 0, hi = count - 1;
580
593
  while (lo <= hi) {
581
- const mid = lo + hi >> 1;
594
+ const mid = lo + hi >>> 1;
582
595
  if (format === 1) {
583
596
  const value = font.u16(table + 4 + mid * 2);
584
597
  if (value < glyph)
@@ -611,7 +624,7 @@ export function parseClassDef(font, table) {
611
624
  return glyph => {
612
625
  let lo = 0, hi = count - 1;
613
626
  while (lo <= hi) {
614
- const mid = lo + hi >> 1;
627
+ const mid = lo + hi >>> 1;
615
628
  const range = table + 4 + mid * 6;
616
629
  if (font.u16(range + 2) < glyph)
617
630
  lo = mid + 1;
@@ -643,7 +656,7 @@ function parseKern(font, kern) {
643
656
  for (const { pairs, start } of tables) {
644
657
  let lo = 0, hi = pairs - 1;
645
658
  while (lo <= hi) {
646
- const mid = lo + hi >> 1;
659
+ const mid = lo + hi >>> 1;
647
660
  const pair = start + mid * 6;
648
661
  const value = font.u32(pair);
649
662
  if (value < key)
@@ -686,6 +699,8 @@ function parseCFF(font, base) {
686
699
  const topDicts = readIndex(names.end);
687
700
  const strings = readIndex(topDicts.end);
688
701
  const globalSubrs = readIndex(strings.end).items;
702
+ if (!topDicts.items.length)
703
+ throw new Error('Font: CFF font has no Top DICT');
689
704
  const top = parseDict(topDicts.items[0]);
690
705
  if (!top[17])
691
706
  throw new Error('Font: CFF font has no charstrings');
@@ -700,20 +715,28 @@ function parseCFF(font, base) {
700
715
  };
701
716
  let privateFor;
702
717
  if (top[1236]) {
718
+ if (!top[1237])
719
+ throw new Error('Font: CID-keyed CFF font has no FDSelect');
703
720
  const fdArray = readIndex(base + top[1236][0]).items.map(dict => readPrivate(parseDict(dict)[18]));
704
721
  const fdSelect = base + top[1237][0];
705
722
  const format = data[fdSelect];
723
+ const fd = (index) => {
724
+ const dict = fdArray[index];
725
+ if (!dict)
726
+ throw new Error(`Font: damaged CFF font (glyph selects private dict ${index} of ${fdArray.length})`);
727
+ return dict;
728
+ };
706
729
  privateFor = glyph => {
707
730
  if (format === 0)
708
- return fdArray[data[fdSelect + 1 + glyph]];
731
+ return fd(data[fdSelect + 1 + glyph]);
709
732
  const ranges = font.u16(fdSelect + 1);
710
733
  for (let i = 0; i < ranges; i++) {
711
734
  const r = fdSelect + 3 + i * 3;
712
735
  const next = font.u16(r + 3);
713
736
  if (glyph >= font.u16(r) && glyph < next)
714
- return fdArray[data[r + 2]];
737
+ return fd(data[r + 2]);
715
738
  }
716
- return fdArray[0];
739
+ return fd(0);
717
740
  };
718
741
  }
719
742
  else {
@@ -742,6 +765,8 @@ function parseDict(bytes) {
742
765
  else if (b0 === 30) {
743
766
  let s = '';
744
767
  for (let done = false; !done;) {
768
+ if (i >= bytes.length)
769
+ throw new Error('Font: damaged CFF dict (a real number without its end)');
745
770
  const byte = bytes[i++];
746
771
  for (const nibble of [byte >> 4, byte & 15]) {
747
772
  if (nibble === 15) {
@@ -999,8 +1024,19 @@ function fromWOFF(data) {
999
1024
  const tables = [];
1000
1025
  for (let i = 0; i < count; i++) {
1001
1026
  const e = 44 + i * 20, offset = view.getUint32(e + 4), compressed = view.getUint32(e + 8), length = view.getUint32(e + 12);
1027
+ if (offset + compressed > data.length)
1028
+ throw new Error('Font: damaged or truncated font data');
1002
1029
  const raw = data.subarray(offset, offset + compressed);
1003
- tables.push({ tag: view.getUint32(e), checksum: view.getUint32(e + 16), data: compressed < length ? decompress(raw, length).subarray(0, length) : raw });
1030
+ let table = raw;
1031
+ if (compressed < length) {
1032
+ try {
1033
+ table = decompress(raw, length).subarray(0, length);
1034
+ }
1035
+ catch (err) {
1036
+ throw new Error('Font: damaged WOFF table', { cause: err });
1037
+ }
1038
+ }
1039
+ tables.push({ tag: view.getUint32(e), checksum: view.getUint32(e + 16), data: table });
1004
1040
  }
1005
1041
  const header = 12 + count * 16;
1006
1042
  let size = header;
@@ -486,7 +486,7 @@ export class LayoutTable {
486
486
  }
487
487
  featureVariations(table) {
488
488
  const f = this.font;
489
- for (let i = 0, count = f.u32(table + 4); i < count; i++) {
489
+ for (let i = 0, count = f.count(f.u32(table + 4), table + 8, 8, 'GSUB table'); i < count; i++) {
490
490
  const record = table + 8 + i * 8;
491
491
  const conditions = f.u32(record), substitution = f.u32(record + 4);
492
492
  let matches = true;
@@ -923,7 +923,7 @@ export class LayoutTable {
923
923
  const second = buffer.info[pos].codepoint;
924
924
  let lo = 0, hi = count - 1, record = -1;
925
925
  while (lo <= hi) {
926
- const mid = lo + hi >> 1, g = f.u16(set + 2 + mid * recordSize);
926
+ const mid = lo + hi >>> 1, g = f.u16(set + 2 + mid * recordSize);
927
927
  if (g < second)
928
928
  lo = mid + 1;
929
929
  else if (g > second)
@@ -42,18 +42,15 @@ export function lineBreaks(codepoints) {
42
42
  pictographicCn[i] = 0;
43
43
  }
44
44
  }
45
- const before = (i) => {
46
- let j = i - 1;
47
- while (j >= 0 && attached[j])
48
- j--;
49
- return j;
50
- };
51
- const after = (i) => {
52
- let j = i;
53
- while (j < n && attached[j])
54
- j++;
55
- return j;
56
- };
45
+ const previous = new Int32Array(n + 1), next = new Int32Array(n + 1);
46
+ previous[0] = -1;
47
+ for (let i = 1; i <= n; i++)
48
+ previous[i] = attached[i - 1] ? previous[i - 1] : i - 1;
49
+ next[n] = n;
50
+ for (let i = n - 1; i >= 0; i--)
51
+ next[i] = attached[i] ? next[i + 1] : i;
52
+ const before = (i) => i <= 0 ? -1 : previous[Math.min(i, n)];
53
+ const after = (i) => i >= n ? n : next[Math.max(i, 0)];
57
54
  const beforeSpaces = (i) => {
58
55
  let j = before(i);
59
56
  while (j >= 0 && cls[j] === 'SP')