ag-psd 33.0.0 → 34.1.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.
Files changed (91) hide show
  1. package/.v8-cache/v24.7.0-x64-ef5a0af0/05135617 +0 -0
  2. package/.v8-cache/v24.7.0-x64-ef5a0af0/226e2801 +0 -0
  3. package/.v8-cache/v24.7.0-x64-ef5a0af0/4511bacf +0 -0
  4. package/.v8-cache/v24.7.0-x64-ef5a0af0/68416cb2 +0 -0
  5. package/.v8-cache/v24.7.0-x64-ef5a0af0/71df9cb3 +0 -0
  6. package/.v8-cache/v24.7.0-x64-ef5a0af0/7ea06cea +0 -0
  7. package/.v8-cache/v24.7.0-x64-ef5a0af0/87cf2209 +0 -0
  8. package/.v8-cache/v24.7.0-x64-ef5a0af0/932f0770 +0 -0
  9. package/.v8-cache/v24.7.0-x64-ef5a0af0/acc36e66 +0 -0
  10. package/.v8-cache/v24.7.0-x64-ef5a0af0/b3c2fab7 +0 -0
  11. package/.v8-cache/v24.7.0-x64-ef5a0af0/c0b789d2 +0 -0
  12. package/.v8-cache/v24.7.0-x64-ef5a0af0/c314aece +0 -0
  13. package/.v8-cache/v24.7.0-x64-ef5a0af0/cfc49f4f +0 -0
  14. package/.v8-cache/v24.7.0-x64-ef5a0af0/d13d7610 +0 -0
  15. package/.v8-cache/v24.7.0-x64-ef5a0af0/dc86f000 +0 -0
  16. package/.v8-cache/v24.7.0-x64-ef5a0af0/e03e2acd +0 -0
  17. package/.v8-cache/v24.7.0-x64-ef5a0af0/e6b99945 +0 -0
  18. package/CHANGELOG.md +28 -0
  19. package/README.md +12 -1
  20. package/README_PSD.md +26 -10
  21. package/TODO.md +9 -94
  22. package/dist/abr.js +12 -7
  23. package/dist/abr.js.map +1 -1
  24. package/dist/additionalInfo.d.ts +2 -0
  25. package/dist/additionalInfo.js +375 -78
  26. package/dist/additionalInfo.js.map +1 -1
  27. package/dist/bundle.js +1661 -407
  28. package/dist/descriptor.d.ts +14 -5
  29. package/dist/descriptor.js +102 -64
  30. package/dist/descriptor.js.map +1 -1
  31. package/dist/helpers.d.ts +6 -0
  32. package/dist/helpers.js +242 -2
  33. package/dist/helpers.js.map +1 -1
  34. package/dist/imageResources.d.ts +2 -0
  35. package/dist/imageResources.js +113 -7
  36. package/dist/imageResources.js.map +1 -1
  37. package/dist/index.d.ts +3 -2
  38. package/dist/index.js +6 -1
  39. package/dist/index.js.map +1 -1
  40. package/dist/psd.d.ts +171 -22
  41. package/dist/psd.js.map +1 -1
  42. package/dist/psdReader.d.ts +5 -1
  43. package/dist/psdReader.js +295 -120
  44. package/dist/psdReader.js.map +1 -1
  45. package/dist/psdWriter.d.ts +1 -0
  46. package/dist/psdWriter.js +336 -91
  47. package/dist/psdWriter.js.map +1 -1
  48. package/dist/text.d.ts +32 -1
  49. package/dist/text.js +58 -0
  50. package/dist/text.js.map +1 -1
  51. package/dist-es/abr.js +12 -7
  52. package/dist-es/abr.js.map +1 -1
  53. package/dist-es/additionalInfo.d.ts +2 -0
  54. package/dist-es/additionalInfo.js +375 -78
  55. package/dist-es/additionalInfo.js.map +1 -1
  56. package/dist-es/descriptor.d.ts +14 -5
  57. package/dist-es/descriptor.js +102 -64
  58. package/dist-es/descriptor.js.map +1 -1
  59. package/dist-es/helpers.d.ts +6 -0
  60. package/dist-es/helpers.js +242 -2
  61. package/dist-es/helpers.js.map +1 -1
  62. package/dist-es/imageResources.d.ts +2 -0
  63. package/dist-es/imageResources.js +113 -7
  64. package/dist-es/imageResources.js.map +1 -1
  65. package/dist-es/index.d.ts +3 -2
  66. package/dist-es/index.js +6 -1
  67. package/dist-es/index.js.map +1 -1
  68. package/dist-es/psd.d.ts +171 -22
  69. package/dist-es/psd.js.map +1 -1
  70. package/dist-es/psdReader.d.ts +5 -1
  71. package/dist-es/psdReader.js +295 -120
  72. package/dist-es/psdReader.js.map +1 -1
  73. package/dist-es/psdWriter.d.ts +1 -0
  74. package/dist-es/psdWriter.js +336 -91
  75. package/dist-es/psdWriter.js.map +1 -1
  76. package/dist-es/text.d.ts +32 -1
  77. package/dist-es/text.js +58 -0
  78. package/dist-es/text.js.map +1 -1
  79. package/fuzz.js +808 -0
  80. package/package.json +1 -1
  81. package/perf.js +312 -9
  82. package/src/abr.ts +14 -7
  83. package/src/additionalInfo.ts +448 -91
  84. package/src/descriptor.ts +103 -58
  85. package/src/helpers.ts +262 -2
  86. package/src/imageResources.ts +138 -7
  87. package/src/index.ts +3 -2
  88. package/src/psd.ts +145 -22
  89. package/src/psdReader.ts +315 -118
  90. package/src/psdWriter.ts +345 -90
  91. package/src/text.ts +76 -1
package/dist/psdReader.js CHANGED
@@ -50,6 +50,10 @@ exports.getLayerRealMaskImageData = getLayerRealMaskImageData;
50
50
  exports.getLayerCanvas = getLayerCanvas;
51
51
  exports.getLayerMaskCanvas = getLayerMaskCanvas;
52
52
  exports.getLayerRealMaskCanvas = getLayerRealMaskCanvas;
53
+ exports.getFilterEffectsMaskImageData = getFilterEffectsMaskImageData;
54
+ exports.getFilterEffectsMaskExtraImageData = getFilterEffectsMaskExtraImageData;
55
+ exports.getFilterEffectsMaskCanvas = getFilterEffectsMaskCanvas;
56
+ exports.getFilterEffectsMaskExtraCanvas = getFilterEffectsMaskExtraCanvas;
53
57
  exports.decodeLayerPixels = decodeLayerPixels;
54
58
  exports.readGlobalLayerMaskInfo = readGlobalLayerMaskInfo;
55
59
  exports.readAdditionalLayerInfo = readAdditionalLayerInfo;
@@ -165,6 +169,9 @@ function readFixedPointPath32(reader) {
165
169
  }
166
170
  // NOTE: returned array may alias the reader's underlying buffer, never write into it
167
171
  function readBytes(reader, length) {
172
+ // negative length comes from sizes computed from malformed data (e.g. section shorter than its header)
173
+ if (!(length >= 0))
174
+ throw new Error(`Invalid length: ${length}`);
168
175
  const start = reader.offset;
169
176
  const viewLength = reader.view.byteLength;
170
177
  reader.offset += length;
@@ -206,6 +213,8 @@ function readUnicodeString(reader) {
206
213
  return readUnicodeStringWithLength(reader, length);
207
214
  }
208
215
  const STRING_CHUNK_SIZE = 0x2000;
216
+ // shorter strings (most descriptor keys, OSTypes and names) are faster to build with simple loop than String.fromCharCode.apply
217
+ const SHORT_STRING_LENGTH = 64;
209
218
  function checkReadBounds(reader, size) {
210
219
  if (reader.offset < 0 || (reader.offset + size) > reader.view.byteLength) {
211
220
  throw new RangeError('Offset is outside the bounds of the DataView');
@@ -216,9 +225,18 @@ function readUtf16String(reader, length, littleEndian) {
216
225
  return '';
217
226
  checkReadBounds(reader, length * 2);
218
227
  const view = reader.view;
219
- const codes = new Uint16Array(Math.min(length, STRING_CHUNK_SIZE));
220
228
  let offset = reader.offset;
221
229
  let text = '';
230
+ if (length <= SHORT_STRING_LENGTH) {
231
+ for (let i = 0; i < length; i++, offset += 2) {
232
+ text += String.fromCharCode(view.getUint16(offset, littleEndian));
233
+ }
234
+ reader.offset = offset;
235
+ if (text.charCodeAt(text.length - 1) === 0)
236
+ text = text.substring(0, text.length - 1);
237
+ return text;
238
+ }
239
+ const codes = new Uint16Array(Math.min(length, STRING_CHUNK_SIZE));
222
240
  for (let i = 0; i < length; i += STRING_CHUNK_SIZE) {
223
241
  const count = Math.min(STRING_CHUNK_SIZE, length - i);
224
242
  for (let j = 0; j < count; j++, offset += 2) {
@@ -249,6 +267,15 @@ function readAsciiString(reader, length) {
249
267
  if (!(length > 0))
250
268
  return '';
251
269
  checkReadBounds(reader, length);
270
+ if (length <= SHORT_STRING_LENGTH) {
271
+ const view = reader.view;
272
+ let text = '';
273
+ for (let i = 0, offset = reader.offset; i < length; i++, offset++) {
274
+ text += String.fromCharCode(view.getUint8(offset));
275
+ }
276
+ reader.offset += length;
277
+ return text;
278
+ }
252
279
  const text = bytesToString(new Uint8Array(reader.view.buffer, reader.view.byteOffset + reader.offset, length));
253
280
  reader.offset += length;
254
281
  return text;
@@ -264,7 +291,14 @@ function checkSignature(reader, a, b) {
264
291
  }
265
292
  }
266
293
  function readShortString(reader, length) {
267
- return bytesToString(readBytes(reader, length));
294
+ const bytes = readBytes(reader, length);
295
+ if (length > SHORT_STRING_LENGTH)
296
+ return bytesToString(bytes);
297
+ let text = '';
298
+ for (let i = 0; i < bytes.length; i++) {
299
+ text += String.fromCharCode(bytes[i]);
300
+ }
301
+ return text;
268
302
  }
269
303
  function isValidSignature(sig) {
270
304
  return sig === '8BIM' || sig === 'MeSa' || sig === 'AgHg' || sig === 'PHUT' || sig === 'DCSR';
@@ -335,16 +369,21 @@ function readPsd(reader, readOptions = {}) {
335
369
  skipBytes(reader, (nameLength + 1) % 2); // pad to even size
336
370
  readSection(reader, 2, left => {
337
371
  const handler = imageResources_1.resourceHandlersMap[id];
338
- const skip = id === 1036 && !!reader.skipThumbnail;
339
- if (handler && !skip) {
340
- try {
341
- handler.read(reader, imageResources, left, { signature, id, name, width, height });
342
- }
343
- catch (e) {
344
- if (reader.throwForMissingFeatures)
345
- throw e;
372
+ if (handler) {
373
+ const skip = (id === 1036 && !!reader.skipThumbnail) || !(0, imageResources_1.shouldReadResource)(handler, reader.imageResourcesWhitelist);
374
+ if (skip) {
346
375
  skipBytes(reader, left());
347
376
  }
377
+ else {
378
+ try {
379
+ handler.read(reader, imageResources, left, { signature, id, name, width, height });
380
+ }
381
+ catch (e) {
382
+ if (reader.throwForMissingFeatures)
383
+ throw e;
384
+ skipBytes(reader, left());
385
+ }
386
+ }
348
387
  }
349
388
  else {
350
389
  reader.logMissingFeatures && reader.log(`Unhandled image resource: ${id} (${left()})`);
@@ -450,6 +489,9 @@ function readLayerInfo(reader, psd, imageResources) {
450
489
  if (type === 1 /* SectionDividerType.OpenFolder */ || type === 2 /* SectionDividerType.ClosedFolder */) {
451
490
  l.opened = type === 1 /* SectionDividerType.OpenFolder */;
452
491
  l.children = [];
492
+ // group layers can't have image data, some broken files have it, ignore it like Photoshop does
493
+ delete l.canvas;
494
+ delete l.imageData;
453
495
  if ((_a = l.sectionDivider) === null || _a === void 0 ? void 0 : _a.key) {
454
496
  l.blendMode = (_b = helpers_1.toBlendMode[l.sectionDivider.key]) !== null && _b !== void 0 ? _b : l.blendMode;
455
497
  }
@@ -648,9 +690,8 @@ function readLayerChannelImageData(reader, psd, layer, channels) {
648
690
  const start = reader.offset;
649
691
  let compression = 0 /* Compression.RawData */;
650
692
  let data = undefined;
651
- if (channel.length === 1)
652
- throw new Error('Invalid channel length');
653
- if (channel.length) {
693
+ // channel length of 1 is invalid (should be 0 or at least 2), skip the byte and treat channel as empty
694
+ if (channel.length >= 2) {
654
695
  compression = readUint16(reader);
655
696
  // try to fix broken files where there's 1 byte shift of channel
656
697
  if (compression > 3) {
@@ -672,7 +713,16 @@ function readLayerChannelImageData(reader, psd, layer, channels) {
672
713
  layer.rawData.channels.push({ id: channel.id, compression, data });
673
714
  }
674
715
  if (!reader.useRawData) {
675
- decodeLayerImageData(layer, reader);
716
+ try {
717
+ decodeLayerImageData(layer, reader);
718
+ }
719
+ catch (e) {
720
+ // corrupted image data of one layer shouldn't prevent reading rest of the file
721
+ if (reader.throwForMissingFeatures || e.message === 'Exceeded memory limit')
722
+ throw e;
723
+ reader.logMissingFeatures && reader.log(`Failed to decode layer image data: ${e.message}`);
724
+ delete layer.rawData;
725
+ }
676
726
  }
677
727
  }
678
728
  function resetAlpha({ data }, cmyk) {
@@ -718,6 +768,67 @@ function getLayerMaskCanvas(layer) {
718
768
  function getLayerRealMaskCanvas(layer) {
719
769
  return imageDataToCanvasSafe(getLayerRealMaskImageData(layer));
720
770
  }
771
+ function getFilterEffectsMaskImageData(mask) {
772
+ const { depth, channels, colorMode = 3 /* ColorMode.RGB */ } = mask;
773
+ const width = Math.max(0, mask.right - mask.left);
774
+ const height = Math.max(0, mask.bottom - mask.top);
775
+ if (!width || !height)
776
+ return undefined;
777
+ const cmyk = colorMode === 4 /* ColorMode.CMYK */;
778
+ if (cmyk && depth !== 8 && depth !== 16)
779
+ throw new Error('bitsPerChannel not supported');
780
+ const step = cmyk ? 5 : 4;
781
+ // channels are color channels, followed by user mask and transparency
782
+ const transparencyIndex = channels.length - 1;
783
+ const colorChannels = Math.min(cmyk ? 4 : (colorMode === 1 /* ColorMode.Grayscale */ ? 1 : 3), channels.length - 2);
784
+ let imageData = createImageDataBitDepth(width, height, depth, step, undefined);
785
+ for (let i = 0; i < channels.length; i++) {
786
+ const channel = channels[i];
787
+ if (!channel)
788
+ continue;
789
+ if (i < colorChannels) {
790
+ readFilterEffectsChannel(channel, imageData, width, height, depth, i, step);
791
+ }
792
+ else if (i === transparencyIndex) {
793
+ readFilterEffectsChannel(channel, imageData, width, height, depth, step - 1, step);
794
+ }
795
+ }
796
+ if (colorMode === 1 /* ColorMode.Grayscale */)
797
+ setupGrayscale(imageData);
798
+ if (!channels[transparencyIndex])
799
+ resetAlpha(imageData, cmyk);
800
+ if (cmyk) {
801
+ const cmykData = imageData;
802
+ imageData = createImageDataBitDepth(cmykData.width, cmykData.height, depth, 4, undefined);
803
+ cmykToRgb(cmykData, imageData, false);
804
+ }
805
+ return imageData;
806
+ }
807
+ function getFilterEffectsMaskExtraImageData(mask) {
808
+ const { extra, depth } = mask;
809
+ if (!extra)
810
+ return undefined;
811
+ const width = Math.max(0, extra.right - extra.left);
812
+ const height = Math.max(0, extra.bottom - extra.top);
813
+ if (!width || !height)
814
+ return undefined;
815
+ const maskData = createImageDataBitDepth(width, height, depth, 4, undefined);
816
+ readFilterEffectsChannel(extra, maskData, width, height, depth, 0, 4);
817
+ setupGrayscale(maskData);
818
+ resetAlpha(maskData, false);
819
+ return maskData;
820
+ }
821
+ function getFilterEffectsMaskCanvas(mask) {
822
+ return imageDataToCanvasSafe(getFilterEffectsMaskImageData(mask));
823
+ }
824
+ function getFilterEffectsMaskExtraCanvas(mask) {
825
+ return imageDataToCanvasSafe(getFilterEffectsMaskExtraImageData(mask));
826
+ }
827
+ function readFilterEffectsChannel({ compressionMode, data }, pixels, width, height, depth, offset, step) {
828
+ const reader = createReader(data.buffer, data.byteOffset, data.byteLength);
829
+ // RLE row lengths are always 4 bytes, same as in PSB files
830
+ readData(reader, data.byteLength, pixels, compressionMode, width, height, depth, offset, true, step);
831
+ }
721
832
  function imageDataToCanvasSafe(imageData) {
722
833
  return imageData && (0, helpers_1.imageDataToCanvas)(imageData);
723
834
  }
@@ -876,7 +987,7 @@ function readGlobalLayerMaskInfo(reader) {
876
987
  const colorSpace2 = readUint16(reader);
877
988
  const colorSpace3 = readUint16(reader);
878
989
  const colorSpace4 = readUint16(reader);
879
- const opacity = readUint16(reader) / 100; // 0 - 100
990
+ const opacity = Math.min(readUint16(reader), 100) / 100; // 0 - 100 (some files have values out of range)
880
991
  const kind = readUint8(reader);
881
992
  skipBytes(reader, left()); // 3 bytes of padding ?
882
993
  return { overlayColorSpace, colorSpace1, colorSpace2, colorSpace3, colorSpace4, opacity, kind };
@@ -1126,10 +1237,7 @@ function toRange(value, max) {
1126
1237
  value = Math.round(value * (max / 255));
1127
1238
  return value <= 0 ? 0 : (value >= max ? max : value);
1128
1239
  }
1129
- // Polynomial approximation of U.S. Web Coated (SWOP) v2 CMYK to RGB conversion (default CMYK profile of Photoshop).
1130
- // Coefficients are taken from pdf.js (DeviceCmykCS in src/core/colorspace.js, https://github.com/mozilla/pdf.js),
1131
- // Copyright 2012 Mozilla Foundation, licensed under the Apache License, Version 2.0
1132
- // (http://www.apache.org/licenses/LICENSE-2.0)
1240
+ // converts CMYK data to RGB using approximation of U.S. Web Coated (SWOP) v2 profile (see cmykToRgbValues)
1133
1241
  // cmyk - 8 or 16 bit data with 5 channels (cmyka), rgb - 8 or 16 bit data with 4 channels (rgba)
1134
1242
  // removeMatte - colors are blended with white (no ink), used for composite image of documents with global alpha
1135
1243
  function cmykToRgb(cmyk, rgb, removeMatte) {
@@ -1138,6 +1246,7 @@ function cmykToRgb(cmyk, rgb, removeMatte) {
1138
1246
  const dstData = rgb.data;
1139
1247
  const srcMax = srcData instanceof Uint16Array ? 0xffff : 0xff;
1140
1248
  const dstMax = dstData instanceof Uint16Array ? 0xffff : 0xff;
1249
+ const out = [0, 0, 0];
1141
1250
  for (let src = 0, dst = 0; dst < size; src += 5, dst += 4) {
1142
1251
  const a = srcData[src + 4];
1143
1252
  // image data stores inverted values (0 = 100% ink)
@@ -1152,21 +1261,10 @@ function cmykToRgb(cmyk, rgb, removeMatte) {
1152
1261
  y = Math.min(1, y * ra);
1153
1262
  k = Math.min(1, k * ra);
1154
1263
  }
1155
- dstData[dst] = toRange(255 +
1156
- c * (-4.387332384609988 * c + 54.48615194189176 * m + 18.82290502165302 * y + 212.25662451639585 * k - 285.2331026137004) +
1157
- m * (1.7149763477362134 * m - 5.6096736904047315 * y - 17.873870861415444 * k - 5.497006427196366) +
1158
- y * (-2.5217340131683033 * y - 21.248923337353073 * k + 17.5119270841813) +
1159
- k * (-21.86122147463605 * k - 189.48180835922747), dstMax);
1160
- dstData[dst + 1] = toRange(255 +
1161
- c * (8.841041422036149 * c + 60.118027045597366 * m + 6.871425592049007 * y + 31.159100130055922 * k - 79.2970844816548) +
1162
- m * (-15.310361306967817 * m + 17.575251261109482 * y + 131.35250912493976 * k - 190.9453302588951) +
1163
- y * (4.444339102852739 * y + 9.8632861493405 * k - 24.86741582555878) +
1164
- k * (-20.737325471181034 * k - 187.80453709719578), dstMax);
1165
- dstData[dst + 2] = toRange(255 +
1166
- c * (0.8842522430003296 * c + 8.078677503112928 * m + 30.89978309703729 * y - 0.23883238689178934 * k - 14.183576799673286) +
1167
- m * (10.49593273432072 * m + 63.02378494754052 * y + 50.606957656360734 * k - 112.23884253719248) +
1168
- y * (0.03296041114873217 * y + 115.60384449646641 * k - 193.58209356861505) +
1169
- k * (-22.33816807309886 * k - 180.12613974708367), dstMax);
1264
+ (0, helpers_1.cmykToRgbValues)(c, m, y, k, out);
1265
+ dstData[dst] = toRange(out[0], dstMax);
1266
+ dstData[dst + 1] = toRange(out[1], dstMax);
1267
+ dstData[dst + 2] = toRange(out[2], dstMax);
1170
1268
  dstData[dst + 3] = srcMax === dstMax ? a : Math.round(a * dstMax / srcMax);
1171
1269
  }
1172
1270
  }
@@ -1234,11 +1332,11 @@ function decodePredicted(data, width, height) {
1234
1332
  }
1235
1333
  const zipOverflow = new Error('Decompressed data exceeds expected size');
1236
1334
  // inflates data, stopping when output exceeds expected size (protects against zip bombs)
1237
- function inflateLimited(compressed, expectedSize, reader) {
1335
+ function inflateLimited(compressed, expectedSize, reader, raw = false) {
1238
1336
  const output = new Uint8Array(expectedSize);
1239
1337
  let position = 0;
1240
1338
  let overflow = false;
1241
- const inflator = new pako_1.Inflate({ chunkSize: Math.max(1024, Math.min(expectedSize, 0x10000)) });
1339
+ const inflator = new pako_1.Inflate({ chunkSize: Math.max(1024, Math.min(expectedSize, 0x10000)), raw });
1242
1340
  inflator.onData = (chunk) => {
1243
1341
  const data = chunk;
1244
1342
  const count = Math.min(data.length, expectedSize - position);
@@ -1267,6 +1365,12 @@ function inflateLimited(compressed, expectedSize, reader) {
1267
1365
  if (reader)
1268
1366
  warnOrThrow(reader, zipOverflow.message);
1269
1367
  }
1368
+ else if (inflator.err && inflator.msg === 'incorrect data check' && !raw) {
1369
+ // some files have zeroed checksum (filter effects masks written by Photoshop), inflate again skipping zlib header and checksum
1370
+ if (reader)
1371
+ warnOrThrow(reader, `Invalid zip data: ${inflator.msg}`);
1372
+ return inflateLimited(compressed.subarray(2), expectedSize, reader, true);
1373
+ }
1270
1374
  else if (inflator.err) {
1271
1375
  throw new Error(`Invalid zip data: ${inflator.msg}`);
1272
1376
  }
@@ -1333,8 +1437,8 @@ function readDataZip(compressed, pixelData, width, height, bitDepth, step, offse
1333
1437
  recoverMemory(reader, expectedSize);
1334
1438
  }
1335
1439
  }
1336
- // decodes single PackBits row, returns number of decoded values
1337
- function decodeRLERow(src, i, end, dst, p, step, count) {
1440
+ // decodes single PackBits row into byte buffer, returns number of decoded bytes
1441
+ function decodeRLERow(src, i, end, dst, count) {
1338
1442
  let x = 0;
1339
1443
  while (i < end && x < count) {
1340
1444
  const header = src[i++];
@@ -1345,10 +1449,8 @@ function decodeRLERow(src, i, end, dst, p, step, count) {
1345
1449
  let n = 257 - header;
1346
1450
  if (n > count - x)
1347
1451
  n = count - x;
1452
+ dst.fill(value, x, x + n);
1348
1453
  x += n;
1349
- for (; n > 0; n--, p += step) {
1350
- dst[p] = value;
1351
- }
1352
1454
  }
1353
1455
  else if (header < 128) {
1354
1456
  let n = header + 1;
@@ -1356,9 +1458,8 @@ function decodeRLERow(src, i, end, dst, p, step, count) {
1356
1458
  n = count - x;
1357
1459
  if (n > end - i)
1358
1460
  n = end - i;
1359
- x += n;
1360
- for (; n > 0; n--, p += step) {
1361
- dst[p] = src[i++];
1461
+ for (; n > 0; n--) {
1462
+ dst[x++] = src[i++];
1362
1463
  }
1363
1464
  }
1364
1465
  else {
@@ -1367,6 +1468,47 @@ function decodeRLERow(src, i, end, dst, p, step, count) {
1367
1468
  }
1368
1469
  return x;
1369
1470
  }
1471
+ // decodes RLE rows of single 8bit channel, writing values to `data` with `step`
1472
+ // (kept as single function with the loops, inlining row decoder into readDataRLE makes V8 generate much slower code)
1473
+ function decodeRLEChannel8(src, lengths, li, pos, width, height, data, offset, step) {
1474
+ const srcEnd = src.length | 0;
1475
+ for (let y = 0; y < height; y++, li++) {
1476
+ let i = (pos < srcEnd ? pos : srcEnd) | 0;
1477
+ pos += lengths[li];
1478
+ const end = (pos < srcEnd ? pos : srcEnd) | 0;
1479
+ let p = (offset + y * width * step) | 0;
1480
+ let x = 0;
1481
+ while (i < end && x < width) {
1482
+ const header = src[i++] | 0;
1483
+ if (header > 128) {
1484
+ if (i >= end)
1485
+ break;
1486
+ const value = src[i++] | 0;
1487
+ let n = (257 - header) | 0;
1488
+ if (n > width - x)
1489
+ n = (width - x) | 0;
1490
+ x = (x + n) | 0;
1491
+ for (const pe = (p + n * step) | 0; p < pe; p = (p + step) | 0) {
1492
+ data[p] = value;
1493
+ }
1494
+ }
1495
+ else if (header < 128) {
1496
+ let n = (header + 1) | 0;
1497
+ if (n > width - x)
1498
+ n = (width - x) | 0;
1499
+ if (n > end - i)
1500
+ n = (end - i) | 0;
1501
+ x = (x + n) | 0;
1502
+ for (const ie = (i + n) | 0; i < ie; i = (i + 1) | 0, p = (p + step) | 0) {
1503
+ data[p] = src[i];
1504
+ }
1505
+ }
1506
+ else {
1507
+ // ignore 128
1508
+ }
1509
+ }
1510
+ }
1511
+ }
1370
1512
  // converts big-endian 16/32-bit values from bytes and writes them to `data` starting at `p` with `step`
1371
1513
  function scatterValues(bytes, count, bpv, data, p, step) {
1372
1514
  if (bpv === 2) {
@@ -1381,8 +1523,8 @@ function scatterValues(bytes, count, bpv, data, p, step) {
1381
1523
  }
1382
1524
  }
1383
1525
  }
1384
- // decodes RLE rows of single channel, each row starts at the beginning of the image row
1385
- function decodeRLEChannel(src, lengths, li, pos, width, height, data, offset, step, bpv, row) {
1526
+ // decodes RLE rows of single 16bit or 32bit channel, each row is decoded into `row` buffer and then converted to values
1527
+ function decodeRLEChannelWide(src, lengths, li, pos, width, height, data, offset, step, bpv, row) {
1386
1528
  const srcEnd = src.length;
1387
1529
  const rowSize = width * bpv;
1388
1530
  for (let y = 0; y < height; y++, li++) {
@@ -1391,25 +1533,24 @@ function decodeRLEChannel(src, lengths, li, pos, width, height, data, offset, st
1391
1533
  const rowEnd = pos < srcEnd ? pos : srcEnd;
1392
1534
  if (rowStart >= rowEnd)
1393
1535
  continue;
1394
- if (bpv === 1) {
1395
- decodeRLERow(src, rowStart, rowEnd, data, offset + y * width * step, step, width);
1396
- }
1397
- else {
1398
- const decoded = decodeRLERow(src, rowStart, rowEnd, row, 0, 1, rowSize);
1399
- scatterValues(row, Math.floor(decoded / bpv), bpv, data, offset + y * width * step, step);
1400
- }
1536
+ const decoded = decodeRLERow(src, rowStart, rowEnd, row, rowSize);
1537
+ scatterValues(row, Math.floor(decoded / bpv), bpv, data, offset + y * width * step, step);
1401
1538
  }
1402
1539
  }
1403
1540
  function readDataRLE(reader, pixelData, width, height, bitDepth, step, offsets, large) {
1404
1541
  const data = pixelData && pixelData.data;
1405
1542
  const rows = offsets.length * height;
1406
1543
  const lengthSize = large ? 4 : 2;
1407
- consumeMemory(reader, rows * lengthSize);
1544
+ const lengthsMemory = rows * lengthSize;
1545
+ const srcEnd = reader.view.byteLength;
1546
+ const bpv = bytesPerValue(bitDepth); // throws before consuming memory
1547
+ let lengths;
1548
+ consumeMemory(reader, lengthsMemory);
1408
1549
  try {
1409
- if ((reader.offset + rows * lengthSize) > reader.view.byteLength) {
1550
+ if ((reader.offset + lengthsMemory) > srcEnd) {
1410
1551
  throw new Error('RLE row lengths exceed buffer length');
1411
1552
  }
1412
- const lengths = large ? new Uint32Array(rows) : new Uint16Array(rows);
1553
+ lengths = large ? new Uint32Array(rows) : new Uint16Array(rows);
1413
1554
  let total = 0;
1414
1555
  if (large) {
1415
1556
  for (let i = 0; i < rows; i++)
@@ -1419,32 +1560,37 @@ function readDataRLE(reader, pixelData, width, height, bitDepth, step, offsets,
1419
1560
  for (let i = 0; i < rows; i++)
1420
1561
  total += (lengths[i] = readUint16(reader));
1421
1562
  }
1422
- const start = reader.offset;
1423
- const srcEnd = reader.view.byteLength;
1424
- if (total > (srcEnd - start)) {
1563
+ if (total > (srcEnd - reader.offset)) {
1425
1564
  // broken or truncated file, decode only data that is available
1426
1565
  warnOrThrow(reader, 'RLE data exceeds buffer length');
1427
1566
  }
1428
- const bpv = bytesPerValue(bitDepth);
1429
1567
  if (data)
1430
1568
  verifyArrayType(data, bpv);
1431
- const src = new Uint8Array(reader.view.buffer, reader.view.byteOffset, srcEnd);
1432
- const row = (data && bpv > 1) ? new Uint8Array(width * bpv) : undefined;
1433
- let pos = start;
1434
- for (let c = 0, li = 0; c < offsets.length; c++, li += height) {
1435
- const offset = offsets[c] | 0;
1436
- const channelStart = pos;
1437
- for (let y = 0; y < height; y++)
1438
- pos += lengths[li + y];
1439
- if (data && offset >= 0 && offset < step) {
1440
- decodeRLEChannel(src, lengths, li, channelStart, width, height, data, offset, step, bpv, row);
1569
+ }
1570
+ catch (e) {
1571
+ recoverMemory(reader, lengthsMemory);
1572
+ throw e;
1573
+ }
1574
+ // decoding can't throw, it's kept outside of try block because V8 generates much slower code for loops inlined into try block
1575
+ const src = new Uint8Array(reader.view.buffer, reader.view.byteOffset, srcEnd);
1576
+ const row = (data && bpv > 1) ? new Uint8Array(width * bpv) : undefined;
1577
+ let pos = reader.offset;
1578
+ for (let c = 0, li = 0; c < offsets.length; c++, li += height) {
1579
+ const offset = offsets[c] | 0;
1580
+ const channelStart = pos;
1581
+ for (let y = 0; y < height; y++)
1582
+ pos += lengths[li + y];
1583
+ if (data && offset >= 0 && offset < step) {
1584
+ if (bpv === 1) {
1585
+ decodeRLEChannel8(src, lengths, li, channelStart, width, height, data, offset, step);
1586
+ }
1587
+ else {
1588
+ decodeRLEChannelWide(src, lengths, li, channelStart, width, height, data, offset, step, bpv, row);
1441
1589
  }
1442
1590
  }
1443
- reader.offset = pos;
1444
- }
1445
- finally {
1446
- recoverMemory(reader, rows * lengthSize);
1447
1591
  }
1592
+ reader.offset = pos;
1593
+ recoverMemory(reader, lengthsMemory);
1448
1594
  }
1449
1595
  function readSection(reader, round, func, skipEmpty = true, eightBytes = false) {
1450
1596
  let length = readUint32(reader);
@@ -1586,19 +1732,13 @@ function readPattern(reader) {
1586
1732
  // channels cover whole pattern, each 2 bytes of RLE data can produce at most 128 bytes
1587
1733
  if (width * height > (Math.min(end, reader.view.byteLength) - reader.offset) * 64)
1588
1734
  throw new Error('Pattern data out of bounds');
1589
- const size = width * height * 4;
1590
- consumeMemory(reader, size);
1591
- const data = new Uint8Array(size);
1592
- for (let i = 3; i < data.byteLength; i += 4) {
1593
- data[i] = 255;
1594
- }
1595
1735
  // first written arrays are color channels, next one is transparency (Photoshop stores it in the last, sheet mask, array)
1596
1736
  const colorChannels = colorMode === 3 /* ColorMode.RGB */ ? 3 : (colorMode === 4 /* ColorMode.CMYK */ ? 4 : 1);
1597
- // CMYK channels are decoded into separate buffer (5 values per pixel, inverted, 0 = 100% ink) and converted to RGB at the end
1598
- const cmyk = colorMode === 4 /* ColorMode.CMYK */ ? new Uint8Array(width * height * 5).fill(255) : undefined;
1599
- if (cmyk)
1600
- consumeMemory(reader, cmyk.byteLength);
1601
- const alphaTarget = cmyk ? 4 : 3;
1737
+ const isCmyk = colorMode === 4 /* ColorMode.CMYK */;
1738
+ const alphaTarget = isCmyk ? 4 : 3;
1739
+ const channels = [];
1740
+ let maxDecodeSize = 0;
1741
+ // validate all channels before allocating any image data
1602
1742
  for (let i = 0, ch = 0; i < (channelsCount + 2) && reader.offset + 4 <= end; i++) {
1603
1743
  const has = readUint32(reader);
1604
1744
  if (!has)
@@ -1630,72 +1770,107 @@ function readPattern(reader) {
1630
1770
  const h = cbottom - ctop;
1631
1771
  const rowBytes = w * (depth / 8);
1632
1772
  const channelSize = rowBytes * h;
1633
- let bytes;
1634
1773
  if (compressionMode === 0) {
1635
1774
  if (cdata.byteLength < channelSize)
1636
1775
  throw new Error('Pattern channel data out of bounds');
1637
- bytes = cdata;
1638
1776
  }
1639
1777
  else if (compressionMode === 1) {
1640
1778
  // each 2 bytes of RLE data can produce at most 128 bytes
1641
1779
  if (channelSize > cdata.byteLength * 64)
1642
1780
  throw new Error('Pattern channel data out of bounds');
1643
- consumeMemory(reader, channelSize);
1644
- bytes = new Uint8Array(channelSize);
1645
- const cdataReader = createReader(cdata.buffer, cdata.byteOffset, cdata.byteLength);
1646
- readDataRLE(cdataReader, { data: bytes, width: rowBytes, height: h }, rowBytes, h, 8, 1, [0], false);
1781
+ maxDecodeSize = Math.max(maxDecodeSize, channelSize);
1647
1782
  }
1648
1783
  else {
1649
1784
  throw new Error('Invalid pattern compression mode');
1650
1785
  }
1786
+ channels.push({ target, depth, compressionMode, cdata, ctop, cleft, w, h, rowBytes, channelSize });
1787
+ }
1788
+ // check peak memory up front (image data, CMYK buffer and largest RLE decode buffer),
1789
+ // image data is consumed only after successful decoding so failed patterns don't reduce the limit
1790
+ const size = width * height * 4;
1791
+ const cmykSize = isCmyk ? width * height * 5 : 0;
1792
+ consumeMemory(reader, size + cmykSize + maxDecodeSize);
1793
+ recoverMemory(reader, size + cmykSize + maxDecodeSize);
1794
+ const data = new Uint8Array(size);
1795
+ for (let i = 3; i < data.byteLength; i += 4) {
1796
+ data[i] = 255;
1797
+ }
1798
+ // CMYK channels are decoded into separate buffer (5 values per pixel, inverted, 0 = 100% ink) and converted to RGB at the end
1799
+ const cmyk = isCmyk ? new Uint8Array(cmykSize).fill(255) : undefined;
1800
+ for (const { target, depth, compressionMode, cdata, ctop, cleft, w, h, rowBytes, channelSize } of channels) {
1801
+ let bytes = cdata;
1802
+ if (compressionMode === 1) {
1803
+ bytes = new Uint8Array(channelSize);
1804
+ const cdataReader = createReader(cdata.buffer, cdata.byteOffset, cdata.byteLength);
1805
+ readDataRLE(cdataReader, { data: bytes, width: rowBytes, height: h }, rowBytes, h, 8, 1, [0], false);
1806
+ }
1807
+ if (depth !== 8)
1808
+ bytes = patternChannelTo8bit(bytes, w * h, depth);
1651
1809
  const ox = cleft - left;
1652
1810
  const oy = ctop - top;
1653
- for (let y = 0; y < h; y++) {
1654
- for (let x = 0; x < w; x++) {
1655
- const src = x + y * w;
1656
- const dst = (ox + x + (y + oy) * width) * 4;
1657
- const value = depth === 8 ? bytes[src] : patternValueTo8bit(bytes, src, depth);
1658
- if (cmyk) {
1659
- cmyk[(ox + x + (y + oy) * width) * 5 + target] = value;
1660
- }
1661
- else if (target === 3) {
1662
- data[dst + 3] = value;
1663
- }
1664
- else if (colorMode === 2 /* ColorMode.Indexed */) {
1665
- const color = palette[value];
1666
- data[dst + 0] = color.r;
1667
- data[dst + 1] = color.g;
1668
- data[dst + 2] = color.b;
1811
+ if (cmyk) {
1812
+ copyPatternChannel(bytes, cmyk, w, h, (ox + oy * width) * 5 + target, width * 5, 5);
1813
+ }
1814
+ else if (target === 3 || colorMode === 3 /* ColorMode.RGB */) {
1815
+ copyPatternChannel(bytes, data, w, h, (ox + oy * width) * 4 + target, width * 4, 4);
1816
+ }
1817
+ else if (colorMode === 2 /* ColorMode.Indexed */) {
1818
+ const colors = new Uint8Array(256 * 3);
1819
+ for (let i = 0; i < 256; i++) {
1820
+ colors[i * 3 + 0] = palette[i].r;
1821
+ colors[i * 3 + 1] = palette[i].g;
1822
+ colors[i * 3 + 2] = palette[i].b;
1823
+ }
1824
+ for (let y = 0; y < h; y++) {
1825
+ for (let x = 0, src = y * w, dst = (ox + (y + oy) * width) * 4; x < w; x++, src++, dst += 4) {
1826
+ const index = bytes[src] * 3;
1827
+ data[dst + 0] = colors[index + 0];
1828
+ data[dst + 1] = colors[index + 1];
1829
+ data[dst + 2] = colors[index + 2];
1669
1830
  }
1670
- else if (colorMode === 1 /* ColorMode.Grayscale */) {
1831
+ }
1832
+ }
1833
+ else { // grayscale
1834
+ for (let y = 0; y < h; y++) {
1835
+ for (let x = 0, src = y * w, dst = (ox + (y + oy) * width) * 4; x < w; x++, src++, dst += 4) {
1836
+ const value = bytes[src];
1671
1837
  data[dst + 0] = value;
1672
1838
  data[dst + 1] = value;
1673
1839
  data[dst + 2] = value;
1674
1840
  }
1675
- else {
1676
- data[dst + target] = value;
1677
- }
1678
1841
  }
1679
1842
  }
1680
- if (compressionMode === 1)
1681
- recoverMemory(reader, channelSize);
1682
1843
  }
1683
1844
  if (cmyk) {
1684
1845
  cmykToRgb({ width, height, data: cmyk }, { width, height, data }, false);
1685
- recoverMemory(reader, cmyk.byteLength);
1686
1846
  }
1847
+ consumeMemory(reader, size);
1687
1848
  reader.offset = end;
1688
1849
  return { id, name, x, y, bounds: { x: left, y: top, w: width, h: height }, data };
1689
1850
  }
1690
- // converts big-endian 16bit or 32bit (float) value at given index to 8bit value
1691
- function patternValueTo8bit(bytes, index, depth) {
1851
+ // converts big-endian 16bit or 32bit (float) values to 8bit values
1852
+ function patternChannelTo8bit(bytes, count, depth) {
1853
+ const result = new Uint8Array(count);
1692
1854
  if (depth === 16) {
1693
- return Math.round(((bytes[index * 2] << 8) | bytes[index * 2 + 1]) / 257);
1855
+ for (let i = 0; i < count; i++) {
1856
+ result[i] = Math.round(((bytes[i * 2] << 8) | bytes[i * 2 + 1]) / 257);
1857
+ }
1694
1858
  }
1695
1859
  else {
1696
- const view = new DataView(bytes.buffer, bytes.byteOffset + index * 4, 4);
1697
- const value = view.getFloat32(0, false);
1698
- return value > 0 ? (value < 1 ? Math.round(value * 255) : 255) : 0;
1860
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1861
+ for (let i = 0; i < count; i++) {
1862
+ const value = view.getFloat32(i * 4, false);
1863
+ result[i] = value > 0 ? (value < 1 ? Math.round(value * 255) : 255) : 0;
1864
+ }
1865
+ }
1866
+ return result;
1867
+ }
1868
+ // copies w x h channel values into interleaved data starting at `offset`
1869
+ function copyPatternChannel(bytes, data, w, h, offset, stride, step) {
1870
+ for (let y = 0, src = 0; y < h; y++) {
1871
+ for (let x = 0, dst = offset + y * stride; x < w; x++, src++, dst += step) {
1872
+ data[dst] = bytes[src];
1873
+ }
1699
1874
  }
1700
1875
  }
1701
1876
  function consumeMemory(reader, size) {