exifreader 4.45.2 → 4.47.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/exif-reader.d.ts CHANGED
@@ -234,9 +234,9 @@ export interface ExpandedTags {
234
234
  iptc?: ExifTags,
235
235
  xmp?: {
236
236
  /**
237
- * The raw, unsanitized XMP packet exactly as it appears in the image.
238
- * Treat it as untrusted: escape or sanitize it before inserting it into
239
- * a page as HTML to avoid cross-site scripting.
237
+ * The raw, unsanitized XMP packet as it appears in the image, decoded
238
+ * as text. Treat it as untrusted: escape or sanitize it before
239
+ * inserting it into a page as HTML to avoid cross-site scripting.
240
240
  */
241
241
  _raw: string
242
242
  } & XmpTags,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "exifreader",
3
- "version": "4.45.2",
3
+ "version": "4.47.0",
4
4
  "description": "Library that parses Exif metadata in images.",
5
5
  "author": "Mattias Wallander <mattias@wallander.eu>",
6
6
  "repository": {
@@ -32,24 +32,24 @@
32
32
  "@babel/preset-env": "^7.29.7",
33
33
  "@cypress/webpack-preprocessor": "^8.0.0",
34
34
  "@eslint/js": "^9.39.5",
35
- "@types/node": "^26.5.1",
35
+ "@types/node": "^26.6.3",
36
36
  "babel-loader": "^10.0.0",
37
37
  "c8": "^12.0.0",
38
38
  "chai": "^6.2.2",
39
39
  "cross-env": "^10.0.0",
40
- "cypress": "^16.0.0",
40
+ "cypress": "^16.1.0",
41
41
  "eslint": "^9.39.4",
42
42
  "eslint-plugin-cypress": "^6.4.4",
43
43
  "globals": "^17.12.0",
44
44
  "husky": "^9.0.11",
45
45
  "linkedom": "^0.18.13",
46
- "mocha": "^12.0.1",
46
+ "mocha": "^12.0.2",
47
47
  "npm-run-all2": "^9.0.3",
48
48
  "rimraf": "^5.0.5",
49
49
  "string-replace-loader": "^3.1.0",
50
50
  "terser-webpack-plugin": "^5.6.1",
51
51
  "typescript": "^7.0.2",
52
- "webpack": "5.111.0",
52
+ "webpack": "5.111.1",
53
53
  "webpack-cli": "^7.2.3",
54
54
  "webpack-dev-server": "^5.2.6"
55
55
  },
package/src/canon-tags.js CHANGED
@@ -29,7 +29,8 @@ function read(
29
29
  byteOrder,
30
30
  includeUnknown,
31
31
  computed = false,
32
- tagFilter = undefined
32
+ tagFilter = undefined,
33
+ valueBudget = undefined
33
34
  ) {
34
35
  let tags = readIfd(
35
36
  dataView,
@@ -40,7 +41,8 @@ function read(
40
41
  includeUnknown,
41
42
  computed,
42
43
  tagFilter,
43
- 'makerNotes'
44
+ 'makerNotes',
45
+ valueBudget
44
46
  );
45
47
 
46
48
  if (tags['ShotInfo']) {
@@ -8,7 +8,7 @@
8
8
  */
9
9
  /* global Buffer */
10
10
 
11
- import {objectAssign, decompress, COMPRESSION_METHOD_BROTLI, getDataView, getStringValueFromArray, assertPromiseSupport} from './utils.js';
11
+ import {objectAssign, decompress, withDecompressBudget, COMPRESSION_METHOD_BROTLI, getDataView, getStringValueFromArray, assertPromiseSupport, setProperty} from './utils.js';
12
12
  import {isFilePathOrURL, isBrowserFileObject, loadFile, loadFileObject} from './file-loaders.js';
13
13
  import {makeLoadAuto, validateAutoOptions} from './load-auto.js';
14
14
  import Constants from './constants.js';
@@ -17,6 +17,7 @@ import ByteOrder from './byte-order.js';
17
17
  import {getTiffHeaderOffset} from './image-header-iso-bmff.js';
18
18
  import ImageHeader from './image-header.js';
19
19
  import Tags from './tags.js';
20
+ import {getValueBudget} from './tags-helpers.js';
20
21
  import MpfTags from './mpf-tags.js';
21
22
  import FileTags from './file-tags.js';
22
23
  import JxlFileTags from './jxl-file-tags.js';
@@ -93,6 +94,7 @@ export function loadView(
93
94
  } = {}
94
95
  ) {
95
96
  dataView = getSelfContainedDataView(dataView);
97
+ decompressConfig = withDecompressBudget(decompressConfig);
96
98
 
97
99
  const tagFilter = createTagFilter({includeTags, excludeTags});
98
100
  const parsedGroups = Object.create(null);
@@ -101,6 +103,7 @@ export function loadView(
101
103
  const deferredPromises = [];
102
104
  let pngTextIsAsync = false;
103
105
  let thumbnailIfdTags = undefined;
106
+ let valueBudget = undefined;
104
107
  let embeddedXmpStepForFlat = undefined;
105
108
 
106
109
  const {
@@ -187,13 +190,14 @@ export function loadView(
187
190
  && tiffHeaderOffset !== undefined
188
191
  && tagFilter.shouldParseGroup('exif')
189
192
  ) {
190
- const {tags: readTags, byteOrder} = readExifTagsSafely(
193
+ const {tags: readTags, byteOrder, valueBudget: exifValueBudget} = readExifTagsSafely(
191
194
  exifDataView || dataView,
192
195
  tiffHeaderOffset,
193
196
  includeUnknown,
194
197
  computed,
195
198
  tagFilter
196
199
  );
200
+ valueBudget = exifValueBudget;
197
201
  if (readTags.Thumbnail) {
198
202
  thumbnailIfdTags = readTags.Thumbnail;
199
203
  delete readTags.Thumbnail;
@@ -321,7 +325,8 @@ export function loadView(
321
325
  byteOrder,
322
326
  includeUnknown,
323
327
  computed,
324
- tagFilter
328
+ tagFilter,
329
+ valueBudget
325
330
  );
326
331
  parsedGroups.makerNotes = readCanonTags;
327
332
  if (tagFilter.shouldReturnGroup('makerNotes')) {
@@ -338,7 +343,8 @@ export function loadView(
338
343
  parsedExifTags['MakerNote'].__offset,
339
344
  includeUnknown,
340
345
  computed,
341
- tagFilter
346
+ tagFilter,
347
+ valueBudget
342
348
  );
343
349
  parsedGroups.makerNotes = readPentaxTags;
344
350
  if (tagFilter.shouldReturnGroup('makerNotes')) {
@@ -369,6 +375,10 @@ export function loadView(
369
375
  }
370
376
  }
371
377
 
378
+ if (valueBudget === undefined && dataView !== undefined) {
379
+ valueBudget = getValueBudget(dataView);
380
+ }
381
+
372
382
  if (
373
383
  Constants.USE_JPEG
374
384
  && Constants.USE_IPTC
@@ -423,7 +433,8 @@ export function loadView(
423
433
  brobTiffHeaderOffset,
424
434
  includeUnknown,
425
435
  computed,
426
- tagFilter
436
+ tagFilter,
437
+ valueBudget
427
438
  );
428
439
  if (readTags.Thumbnail) {
429
440
  delete readTags.Thumbnail;
@@ -509,7 +520,8 @@ export function loadView(
509
520
  mpfDataOffset,
510
521
  includeUnknown,
511
522
  computed,
512
- tagFilter
523
+ tagFilter,
524
+ valueBudget
513
525
  );
514
526
  const parsedMpfTags = filterTagsForParse('mpf', readMpfTags, tagFilter);
515
527
  parsedGroups.mpf = parsedMpfTags;
@@ -557,7 +569,8 @@ export function loadView(
557
569
  includeUnknown,
558
570
  computed,
559
571
  tagFilter,
560
- decompressConfig
572
+ decompressConfig,
573
+ valueBudget
561
574
  );
562
575
  pngTextIsAsync = !!readTagsPromise;
563
576
 
@@ -770,14 +783,20 @@ function getBrobDataView(dataView, brobChunk) {
770
783
  }
771
784
 
772
785
  function readExifTagsSafely(dataView, tiffHeaderOffset, includeUnknown, computed, tagFilter) {
786
+ // Created outside the try so values decoded before a throw still count
787
+ // against the budget that the maker note and MPF reads draw from. The data
788
+ // view is only missing in unit tests that fake the tag readers.
789
+ const valueBudget = dataView === undefined ? undefined : getValueBudget(dataView);
773
790
  try {
774
- return Tags.read(dataView, tiffHeaderOffset, includeUnknown, computed, tagFilter);
791
+ const {tags, byteOrder} = Tags.read(dataView, tiffHeaderOffset, includeUnknown, computed, tagFilter, valueBudget);
792
+ return {tags, byteOrder, valueBudget};
775
793
  } catch (error) {
776
794
  // A malformed TIFF header (an out-of-bounds offset or an invalid byte
777
795
  // order marker, e.g. from a HEIC/AVIF iloc that does not point at real
778
796
  // Exif) must not abort the whole parse. Skip Exif instead, but keep the
779
- // same {tags, byteOrder} shape so callers can destructure safely.
780
- return {tags: {}, byteOrder: ByteOrder.BIG_ENDIAN};
797
+ // same {tags, byteOrder, valueBudget} shape so callers can destructure
798
+ // safely.
799
+ return {tags: {}, byteOrder: ByteOrder.BIG_ENDIAN, valueBudget};
781
800
  }
782
801
  }
783
802
 
@@ -809,7 +828,7 @@ function filterTags(groupKey, readTags, matchesTag) {
809
828
  const tagId = getTagId(tagValue);
810
829
 
811
830
  if (matchesTag(groupKey, tagName, tagId)) {
812
- filteredTags[tagName] = tagValue;
831
+ setProperty(filteredTags, tagName, tagValue);
813
832
  }
814
833
  }
815
834
 
@@ -65,7 +65,7 @@ export function loadFileObject(file, options) {
65
65
 
66
66
  function legacyRange(options) {
67
67
  if (options && Number.isInteger(options.length) && options.length >= 0) {
68
- return {start: 0, end: options.length};
68
+ return {start: 0, end: options.length, maxBytes: options.length};
69
69
  }
70
70
  return {start: 0};
71
71
  }
@@ -75,13 +75,16 @@ function legacyRange(options) {
75
75
  * requested range is not the whole file.
76
76
  *
77
77
  * @param {string} url
78
- * @param {{start?: number, end?: number}} [range] `end` is exclusive. Omit (or pass `Infinity`) to read to EOF.
78
+ * @param {{start?: number, end?: number, maxBytes?: number}} [range] `end` is exclusive. Omit (or pass `Infinity`)
79
+ * to read to EOF. With `maxBytes` (a non-negative integer) at most that many body bytes are kept, for a 2xx
80
+ * status and for 416; where the response body is a `ReadableStream` the transfer is stopped once they have
81
+ * arrived, otherwise the whole body is read and cut.
79
82
  * @returns {Promise<{buffer: ArrayBuffer, totalSize: number|undefined, status: number|undefined}>}
80
83
  * `totalSize` is taken from the `Content-Range` or `Content-Length` response header when present.
81
84
  * Rejects with `Could not fetch file: <status>` on non-2xx responses, except 416 which the
82
85
  * `length: 'auto'` loop consumes as a fall-back signal. Mirrors `nodeGetRange`.
83
86
  */
84
- export function fetchRange(url, {start = 0, end} = {}) {
87
+ export function fetchRange(url, {start = 0, end, maxBytes} = {}) {
85
88
  const options = {method: 'GET'};
86
89
  if (start > 0 || (end !== undefined && end !== Infinity)) {
87
90
  options.headers = {range: buildRangeHeader(start, end)};
@@ -93,10 +96,99 @@ export function fetchRange(url, {start = 0, end} = {}) {
93
96
  return Promise.reject(new Error(`Could not fetch file: ${status} ${statusText}`.trim()));
94
97
  }
95
98
  const totalSize = totalSizeFromFetchResponse(response);
96
- return Promise.resolve(response.arrayBuffer()).then((buffer) => ({buffer, totalSize, status}));
99
+ return readFetchBody(response, maxBytes).then((buffer) => ({buffer, totalSize, status}));
97
100
  });
98
101
  }
99
102
 
103
+ function readFetchBody(response, maxBytes) {
104
+ if (!isByteLimit(maxBytes)) {
105
+ return Promise.resolve(response.arrayBuffer());
106
+ }
107
+ if (response.body && typeof response.body.getReader === 'function') {
108
+ return readStreamUpTo(response.body.getReader(), maxBytes);
109
+ }
110
+ return Promise.resolve(response.arrayBuffer()).then((buffer) => buffer.slice(0, maxBytes));
111
+ }
112
+
113
+ function isByteLimit(maxBytes) {
114
+ return Number.isInteger(maxBytes) && maxBytes >= 0;
115
+ }
116
+
117
+ function readStreamUpTo(reader, maxBytes) {
118
+ return new Promise((resolve, reject) => {
119
+ const collector = createByteCollector(maxBytes);
120
+ readNextChunk();
121
+
122
+ // Not returning the inner promise keeps memory constant per chunk;
123
+ // a returned chain would retain every link until the stream ends.
124
+ function readNextChunk() {
125
+ if (collector.isFull()) {
126
+ resolve(collector.toArrayBuffer());
127
+ cancelQuietly(reader);
128
+ return;
129
+ }
130
+ reader.read().then(onChunk).then(undefined, onFailure);
131
+ }
132
+
133
+ function onChunk(result) {
134
+ if (result.done) {
135
+ resolve(collector.toArrayBuffer());
136
+ return;
137
+ }
138
+ collector.add(result.value);
139
+ readNextChunk();
140
+ }
141
+
142
+ function onFailure(error) {
143
+ reject(error);
144
+ cancelQuietly(reader);
145
+ }
146
+ });
147
+ }
148
+
149
+ function cancelQuietly(reader) {
150
+ Promise.resolve().then(() => reader.cancel()).then(undefined, () => undefined);
151
+ }
152
+
153
+ /**
154
+ * Collects the first `maxBytes` bytes of a sequence of chunks into one
155
+ * growable array, so memory stays O(maxBytes) however the body is chunked.
156
+ * Capacity grows with the data rather than being preallocated, since a
157
+ * caller may pass a large `length` for a small file.
158
+ */
159
+ function createByteCollector(maxBytes) {
160
+ let bytes = new Uint8Array(0);
161
+ let count = 0;
162
+
163
+ return {
164
+ add(chunk) {
165
+ const size = Math.min(chunk.byteLength, maxBytes - count);
166
+ if (count + size > bytes.length) {
167
+ grow(count + size);
168
+ }
169
+ bytes.set(chunk.subarray(0, size), count);
170
+ count += size;
171
+ },
172
+ isFull() {
173
+ return count >= maxBytes;
174
+ },
175
+ toArrayBuffer() {
176
+ if (bytes.length === count) {
177
+ return bytes.buffer;
178
+ }
179
+ const exact = new Uint8Array(count);
180
+ exact.set(bytes.subarray(0, count));
181
+ return exact.buffer;
182
+ },
183
+ };
184
+
185
+ function grow(needed) {
186
+ const larger = new Uint8Array(Math.min(maxBytes, Math.max(needed, 2 * bytes.length)));
187
+ larger.set(bytes.subarray(0, count));
188
+ bytes = larger;
189
+ }
190
+ }
191
+
100
192
  function buildRangeHeader(start, end) {
101
193
  if (end === undefined || end === Infinity) {
102
194
  return `bytes=${start}-`;
@@ -125,10 +217,12 @@ function isAcceptableFetchStatus(status) {
125
217
  * on non-2xx responses with the status line in the error message.
126
218
  *
127
219
  * @param {string} url
128
- * @param {{start?: number, end?: number}} [range] `end` is exclusive. Omit (or pass `Infinity`) to read to EOF.
220
+ * @param {{start?: number, end?: number, maxBytes?: number}} [range] `end` is exclusive. Omit (or pass `Infinity`)
221
+ * to read to EOF. With `maxBytes` (a non-negative integer) at most that many body bytes are read on a 2xx
222
+ * response, 200 or 206, and the transfer is stopped once they have arrived.
129
223
  * @returns {Promise<{buffer: Buffer, totalSize: number|undefined, status: number|undefined}>}
130
224
  */
131
- export function nodeGetRange(url, {start = 0, end} = {}) {
225
+ export function nodeGetRange(url, {start = 0, end, maxBytes} = {}) {
132
226
  return new Promise((resolve, reject) => {
133
227
  const options = {};
134
228
  if (start > 0 || (end !== undefined && end !== Infinity)) {
@@ -139,14 +233,22 @@ export function nodeGetRange(url, {start = 0, end} = {}) {
139
233
  get(url, options, (response) => {
140
234
  if ((response.statusCode >= HTTP_STATUS_OK) && (response.statusCode <= HTTP_STATUS_SUCCESS_MAX)) {
141
235
  const totalSize = totalSizeFromNodeResponse(response);
142
- const data = [];
143
- response.on('data', (chunk) => data.push(Buffer.from(chunk)));
144
- response.on('error', (error) => reject(error));
145
- response.on('end', () => resolve({
146
- buffer: Buffer.concat(data),
147
- totalSize,
148
- status: response.statusCode,
149
- }));
236
+ if (isByteLimit(maxBytes)) {
237
+ readNodeResponseUpTo(response, maxBytes, (buffer) => resolve({
238
+ buffer,
239
+ totalSize,
240
+ status: response.statusCode,
241
+ }), reject);
242
+ } else {
243
+ const data = [];
244
+ response.on('data', (chunk) => data.push(Buffer.from(chunk)));
245
+ response.on('error', (error) => reject(error));
246
+ response.on('end', () => resolve({
247
+ buffer: Buffer.concat(data),
248
+ totalSize,
249
+ status: response.statusCode,
250
+ }));
251
+ }
150
252
  } else if (response.statusCode === HTTP_STATUS_RANGE_NOT_SATISFIABLE) {
151
253
  // Resolve (rather than reject) so the adaptive `length: 'auto'`
152
254
  // loop can fall back to a full read, mirroring the fetch path.
@@ -160,6 +262,36 @@ export function nodeGetRange(url, {start = 0, end} = {}) {
160
262
  });
161
263
  }
162
264
 
265
+ function readNodeResponseUpTo(response, maxBytes, onBuffer, onError) {
266
+ const collector = createByteCollector(maxBytes);
267
+ let finished = false;
268
+
269
+ response.on('error', onError);
270
+ if (collector.isFull()) {
271
+ finish();
272
+ response.destroy();
273
+ } else {
274
+ response.on('data', onData);
275
+ response.on('end', finish);
276
+ }
277
+
278
+ function onData(chunk) {
279
+ if (finished) {
280
+ return;
281
+ }
282
+ collector.add(chunk);
283
+ if (collector.isFull()) {
284
+ finish();
285
+ response.destroy();
286
+ }
287
+ }
288
+
289
+ function finish() {
290
+ finished = true;
291
+ onBuffer(Buffer.from(collector.toArrayBuffer()));
292
+ }
293
+ }
294
+
163
295
  function totalSizeFromNodeResponse(response) {
164
296
  if (!response || !response.headers) {
165
297
  return undefined;
@@ -41,6 +41,7 @@ export function parseItemLocationBox(dataView, startOffset, version, contentOffs
41
41
  return {
42
42
  type: 'iloc',
43
43
  items: getItems(dataView, boxEnd, version, offsets, sizes, offsetSize, lengthSize, indexSize, itemCount),
44
+ uses64BitFields: hasAny64BitField(offsetSize, lengthSize, baseOffsetSize, indexSize),
44
45
  length: boxLength
45
46
  };
46
47
  }
@@ -190,9 +191,11 @@ function getVariableSizedValue(dataView, offset, size) {
190
191
  return dataView.getUint32(offset);
191
192
  }
192
193
  if (size === 8) {
193
- // eslint-disable-next-line no-console
194
- console.warn('This file uses an 8-bit offset which is currently not supported by ExifReader. Contact the maintainer to get it fixed.');
195
194
  return get64BitValue(dataView, offset);
196
195
  }
197
196
  return 0;
198
197
  }
198
+
199
+ function hasAny64BitField(offsetSize, lengthSize, baseOffsetSize, indexSize) {
200
+ return offsetSize === 8 || lengthSize === 8 || baseOffsetSize === 8 || indexSize === 8;
201
+ }
@@ -228,6 +228,8 @@ export function findOffsets(dataView, metadataBlocks) {
228
228
  return {hasAppMarkers: false};
229
229
  }
230
230
 
231
+ warnIfUnsupportedFieldSize(metaBox);
232
+
231
233
  if (Constants.USE_EXIF) {
232
234
  const exif = findExifOffset(dataView, metaBox, metadataBlocks);
233
235
  if (exif !== undefined) {
@@ -279,6 +281,14 @@ function findMetaBox(dataView) {
279
281
  return undefined;
280
282
  }
281
283
 
284
+ function warnIfUnsupportedFieldSize(metaBox) {
285
+ const ilocBox = metaBox.subBoxes.find((box) => box.type === 'iloc');
286
+ if (ilocBox && ilocBox.uses64BitFields) {
287
+ // eslint-disable-next-line no-console
288
+ console.warn('This file uses 8-byte iloc offset, length or index fields which are currently not fully supported by ExifReader. Contact the maintainer to get it fixed.');
289
+ }
290
+ }
291
+
282
292
  function findExifOffset(dataView, metaBox, metadataBlocks) {
283
293
  try {
284
294
  const exifItemId = findIinfExifItemId(metaBox).itemId;
@@ -207,15 +207,20 @@ export function applyMergeStep({
207
207
 
208
208
  if (Constants.USE_PNG && step.type === 'processPngTextReadTagsDeferredList') {
209
209
  const tagList = deferredResults[step.deferredKey] || [];
210
+ const merge = createInPlaceMerge(deps);
210
211
 
211
212
  for (let i = 0; i < tagList.length; i++) {
213
+ const entry = tagList[i];
212
214
  tags = addPngTextReadTagsToTagsAndGroups({
213
- readTags: tagList[i],
215
+ readTags: entry.readTags || {},
216
+ embeddedExifTags: entry.embeddedExifTags,
217
+ embeddedIptcTags: entry.embeddedIptcTags,
214
218
  parsedGroups,
215
219
  expanded,
216
220
  tagFilter,
217
221
  tags,
218
222
  deps,
223
+ merge,
219
224
  });
220
225
  }
221
226
 
@@ -377,25 +382,19 @@ export function mergeMergeGroup(tags, groupKey, returnedTags, expanded, deps) {
377
382
 
378
383
  export function addPngTextReadTagsToTagsAndGroups({
379
384
  readTags,
385
+ embeddedExifTags,
386
+ embeddedIptcTags,
380
387
  parsedGroups,
381
388
  expanded,
382
389
  tagFilter,
383
390
  tags,
384
391
  deps,
392
+ merge = createCopyingMerge(deps),
385
393
  }) {
386
- const embeddedExifTags = readTags.__exif;
387
- const embeddedIptcTags = readTags.__iptc;
388
- delete readTags.__exif;
389
- delete readTags.__iptc;
390
-
391
394
  if (embeddedExifTags) {
392
395
  const parsedEmbeddedExifTags =
393
396
  deps.filterTagsForParse('exif', embeddedExifTags, tagFilter);
394
- parsedGroups.exif = !parsedGroups.exif ? parsedEmbeddedExifTags : deps.objectAssign(
395
- {},
396
- parsedGroups.exif,
397
- parsedEmbeddedExifTags
398
- );
397
+ merge.group(parsedGroups, 'exif', parsedEmbeddedExifTags);
399
398
 
400
399
  if (tagFilter.shouldReturnGroup('exif')) {
401
400
  const returnedEmbeddedExifTags = deps.filterTagsForReturn(
@@ -404,11 +403,7 @@ export function addPngTextReadTagsToTagsAndGroups({
404
403
  tagFilter
405
404
  );
406
405
  if (expanded) {
407
- tags.exif = !tags.exif ? returnedEmbeddedExifTags : deps.objectAssign(
408
- {},
409
- tags.exif,
410
- returnedEmbeddedExifTags
411
- );
406
+ merge.group(tags, 'exif', returnedEmbeddedExifTags);
412
407
  } else {
413
408
  // The thumbnail image is never read from a text chunk, so the
414
409
  // thumbnail IFD would land at the top level with no image.
@@ -416,7 +411,7 @@ export function addPngTextReadTagsToTagsAndGroups({
416
411
  deps.objectAssign({}, returnedEmbeddedExifTags);
417
412
  delete returnedEmbeddedExifTagsForFlat.Thumbnail;
418
413
 
419
- tags = deps.objectAssign({}, tags, returnedEmbeddedExifTagsForFlat);
414
+ tags = merge.topLevel(tags, returnedEmbeddedExifTagsForFlat);
420
415
  }
421
416
  }
422
417
  }
@@ -424,11 +419,7 @@ export function addPngTextReadTagsToTagsAndGroups({
424
419
  if (embeddedIptcTags) {
425
420
  const parsedEmbeddedIptcTags =
426
421
  deps.filterTagsForParse('iptc', embeddedIptcTags, tagFilter);
427
- parsedGroups.iptc = !parsedGroups.iptc ? parsedEmbeddedIptcTags : deps.objectAssign(
428
- {},
429
- parsedGroups.iptc,
430
- parsedEmbeddedIptcTags
431
- );
422
+ merge.group(parsedGroups, 'iptc', parsedEmbeddedIptcTags);
432
423
 
433
424
  if (tagFilter.shouldReturnGroup('iptc')) {
434
425
  const returnedEmbeddedIptcTags = deps.filterTagsForReturn(
@@ -437,13 +428,9 @@ export function addPngTextReadTagsToTagsAndGroups({
437
428
  tagFilter
438
429
  );
439
430
  if (expanded) {
440
- tags.iptc = !tags.iptc ? returnedEmbeddedIptcTags : deps.objectAssign(
441
- {},
442
- tags.iptc,
443
- returnedEmbeddedIptcTags
444
- );
431
+ merge.group(tags, 'iptc', returnedEmbeddedIptcTags);
445
432
  } else {
446
- tags = deps.objectAssign({}, tags, returnedEmbeddedIptcTags);
433
+ tags = merge.topLevel(tags, returnedEmbeddedIptcTags);
447
434
  }
448
435
  }
449
436
  }
@@ -455,30 +442,58 @@ export function addPngTextReadTagsToTagsAndGroups({
455
442
  parsedGroups.pngText = parsedPngTextTags;
456
443
 
457
444
  if (expanded) {
458
- tags.png = !tags.png ? returnedPngTextTags : deps.objectAssign(
459
- {},
460
- tags.png,
461
- returnedPngTextTags
462
- );
445
+ merge.group(tags, 'png', returnedPngTextTags);
463
446
  // Historical behavior in build fixtures:
464
447
  // - if PNG text chunks yield actual "png" tags, `pngText` should contain only those
465
448
  // - otherwise (e.g. only embedded Exif/IPTC), `pngText` should represent the full `png` group
466
449
  // and will be filled in later as a fallback from `tags.png`
467
450
  if (returnedPngTextTags && Object.keys(returnedPngTextTags).length > 0) {
468
- tags.pngText = !tags.pngText ? returnedPngTextTags : deps.objectAssign(
469
- {},
470
- tags.pngText,
471
- returnedPngTextTags
472
- );
451
+ merge.group(tags, 'pngText', returnedPngTextTags);
473
452
  }
474
453
  } else {
475
- tags = deps.objectAssign({}, tags, returnedPngTextTags);
454
+ tags = merge.topLevel(tags, returnedPngTextTags);
476
455
  }
477
456
  }
478
457
 
479
458
  return tags;
480
459
  }
481
460
 
461
+ function createCopyingMerge(deps) {
462
+ return {
463
+ group(holder, key, source) {
464
+ holder[key] = !holder[key] ? source : deps.objectAssign({}, holder[key], source);
465
+ },
466
+ topLevel(tags, source) {
467
+ return deps.objectAssign({}, tags, source);
468
+ },
469
+ };
470
+ }
471
+
472
+ function createInPlaceMerge(deps) {
473
+ const ownedContainers = [];
474
+
475
+ return {
476
+ group(holder, key, source) {
477
+ holder[key] = own(holder[key]);
478
+ deps.objectAssign(holder[key], source);
479
+ },
480
+ topLevel(tags, source) {
481
+ return deps.objectAssign(own(tags), source);
482
+ },
483
+ };
484
+
485
+ // Earlier steps can share these containers (tags.png can be tags.pngFile or the
486
+ // synchronous text chunks' tags), so each is copied once before merging in place.
487
+ function own(container) {
488
+ if (ownedContainers.indexOf(container) !== -1) {
489
+ return container;
490
+ }
491
+ const copy = deps.objectAssign({}, container);
492
+ ownedContainers.push(copy);
493
+ return copy;
494
+ }
495
+ }
496
+
482
497
  export function isThenable(value) {
483
498
  return !!value && typeof value.then === 'function';
484
499
  }
package/src/mpf-tags.js CHANGED
@@ -25,7 +25,8 @@ function read(
25
25
  dataOffset,
26
26
  includeUnknown,
27
27
  computed = false,
28
- tagFilter = undefined
28
+ tagFilter = undefined,
29
+ valueBudget = undefined
29
30
  ) {
30
31
  try {
31
32
  const byteOrder = ByteOrder.getByteOrder(dataView, dataOffset);
@@ -42,7 +43,8 @@ function read(
42
43
  includeUnknown,
43
44
  computed,
44
45
  tagFilter,
45
- 'mpf'
46
+ 'mpf',
47
+ valueBudget
46
48
  );
47
49
  return addMpfImages(dataView, dataOffset, tags, byteOrder);
48
50
  } catch (error) {
@@ -37,7 +37,8 @@ function read(
37
37
  offset,
38
38
  includeUnknown,
39
39
  computed = false,
40
- tagFilter = undefined
40
+ tagFilter = undefined,
41
+ valueBudget = undefined
41
42
  ) {
42
43
  try {
43
44
  // Pentax does not use the standard TIFF header offset as base for tag
@@ -54,7 +55,8 @@ function read(
54
55
  includeUnknown,
55
56
  computed,
56
57
  tagFilter,
57
- 'makerNotes'
58
+ 'makerNotes',
59
+ valueBudget
58
60
  );
59
61
 
60
62
  if (hasLevelInfoK3III(tags)) {