exifreader 4.39.0 → 4.40.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.
@@ -0,0 +1,310 @@
1
+ /* This Source Code Form is subject to the terms of the Mozilla Public
2
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
3
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
+
5
+ /* global Buffer, SharedArrayBuffer */
6
+
7
+ import {
8
+ fetchRange, nodeGetRange, readLocalFileRange, readFileObjectRange,
9
+ concatBuffers, isFilePathOrURL, isBrowserFileObject, isDataUri,
10
+ HTTP_STATUS_OK, HTTP_STATUS_RANGE_NOT_SATISFIABLE,
11
+ } from './file-loaders.js';
12
+ import {objectAssign, dataUriToBuffer} from './utils.js';
13
+
14
+ const AUTO_INITIAL_LENGTH = 128 * 1024;
15
+ const AUTO_MAX_ITERATIONS = 4;
16
+ const AUTO_UNSUPPORTED_ERROR =
17
+ 'length: "auto" could not locate metadata in this file '
18
+ + '(no metadata blocks found after reading the file — e.g. plain TIFF, '
19
+ + 'bare JPEG XL codestream, or a file with no recognizable metadata).';
20
+ const AUTO_MEMORY_UNSUPPORTED_ERROR =
21
+ 'length: "auto" is not supported for this file type '
22
+ + '(no leading metadata container — e.g. plain TIFF or bare JPEG XL codestream).';
23
+
24
+ /**
25
+ * Throws synchronously if `length: 'auto'` is missing `expanded: true`
26
+ * and/or `includeOffsets: true`.
27
+ *
28
+ * @param {object} options
29
+ */
30
+ export function validateAutoOptions(options) {
31
+ if (options.expanded !== true || options.includeOffsets !== true) {
32
+ throw new Error('length: "auto" requires both expanded: true and includeOffsets: true.');
33
+ }
34
+ }
35
+
36
+ /**
37
+ * Builds a `loadAuto(data, options)` bound to `loadFromData`. Factory
38
+ * to avoid a circular import with `exif-reader.js`.
39
+ *
40
+ * @param {(data: any, options: object) => any} loadFromData
41
+ * @returns {(data: any, options: object) => Promise<object>}
42
+ */
43
+ export function makeLoadAuto(loadFromData) {
44
+ return function loadAuto(data, options) {
45
+ if (typeof Promise === 'undefined') {
46
+ throw new Error('Promise is required when async mode is enabled.');
47
+ }
48
+ const asyncOptions = objectAssign({}, options, {async: true});
49
+ if (isFilePathOrURL(data)) {
50
+ return loadAdaptiveFromFilenameOrUrl(data, asyncOptions);
51
+ }
52
+ if (isBrowserFileObject(data)) {
53
+ return loadAdaptiveFromFileObject(data, asyncOptions);
54
+ }
55
+ return loadAdaptiveFromMemory(data, asyncOptions);
56
+ };
57
+
58
+ function loadAdaptiveFromFilenameOrUrl(filename, options) {
59
+ if (/^\w+:\/\//.test(filename)) {
60
+ if (typeof fetch !== 'undefined') {
61
+ return adaptiveLoop({
62
+ readRange: (start, end) => fetchRange(filename, {start, end}),
63
+ options,
64
+ });
65
+ }
66
+ return adaptiveLoop({
67
+ readRange: (start, end) => nodeGetRange(filename, {start, end}),
68
+ options,
69
+ });
70
+ }
71
+ if (isDataUri(filename)) {
72
+ return loadAdaptiveFromMemory(dataUriToBuffer(filename), options);
73
+ }
74
+ return adaptiveLoop({
75
+ readRange: (start, end, ctx) => readLocalFileRange(filename, {
76
+ start, end, totalSize: ctx ? ctx.totalSize : undefined
77
+ }),
78
+ options,
79
+ });
80
+ }
81
+
82
+ function loadAdaptiveFromFileObject(file, options) {
83
+ return adaptiveLoop({
84
+ readRange: (start, end) => readFileObjectRange(file, {start, end}),
85
+ options,
86
+ });
87
+ }
88
+
89
+ function loadAdaptiveFromMemory(data, options) {
90
+ return Promise.resolve()
91
+ .then(() => loadFromData(data, options))
92
+ .then((tags) => {
93
+ if (!tags || !tags.metadataRange) {
94
+ throw new Error(AUTO_MEMORY_UNSUPPORTED_ERROR);
95
+ }
96
+ const end = tags.metadataRange.end;
97
+ tags.metadataRange.buffer = sliceInputBuffer(data, end);
98
+ tags.metadataRange.fetched = bufferByteLength(tags.metadataRange.buffer);
99
+ tags.metadataRange.requests = 0;
100
+ return tags;
101
+ });
102
+ }
103
+
104
+ function adaptiveLoop({readRange, options}) {
105
+ return runAdaptiveIteration({
106
+ readRange,
107
+ options,
108
+ buffer: null,
109
+ fetched: 0,
110
+ requests: 0,
111
+ totalSize: undefined,
112
+ need: AUTO_INITIAL_LENGTH,
113
+ iter: 0,
114
+ });
115
+ }
116
+
117
+ function runAdaptiveIteration(state) {
118
+ if (state.iter >= AUTO_MAX_ITERATIONS) {
119
+ return runAdaptiveFallback(state);
120
+ }
121
+ if (state.totalSize !== undefined) {
122
+ state.need = Math.min(state.need, state.totalSize);
123
+ }
124
+ if (state.need <= state.fetched) {
125
+ return runAdaptiveFallback(state);
126
+ }
127
+ return state.readRange(state.fetched, state.need, {totalSize: state.totalSize})
128
+ .then((chunk) => {
129
+ state.requests++;
130
+ // Fall back to a full GET when the server cannot satisfy
131
+ // the requested range.
132
+ if (chunk.status === HTTP_STATUS_RANGE_NOT_SATISFIABLE) {
133
+ return handleAdaptive416(state);
134
+ }
135
+ mergeAdaptiveChunk(state, chunk);
136
+ return Promise.resolve(loadFromData(state.buffer, state.options))
137
+ .then((tags) => decideAdaptiveNext(state, tags));
138
+ });
139
+ }
140
+
141
+ function decideAdaptiveNext(state, tags) {
142
+ const range = tags && tags.metadataRange;
143
+ if (range && range.complete) {
144
+ return attachAdaptiveFields(tags, state.buffer, state.fetched, state.requests);
145
+ }
146
+
147
+ // No metadataRange yet does not mean unsupported. The `meta` box
148
+ // may be past the current buffer in ISO-BMFF. Only reject after
149
+ // a full-file read.
150
+ const reachedEnd = state.totalSize !== undefined && state.fetched >= state.totalSize;
151
+ if (!range && reachedEnd) {
152
+ throw new Error(AUTO_UNSUPPORTED_ERROR);
153
+ }
154
+
155
+ const nextNeed = pickNextNeed({range, totalSize: state.totalSize, fetched: state.fetched});
156
+ if (nextNeed <= state.fetched) {
157
+ if (range) {
158
+ return attachAdaptiveFields(tags, state.buffer, state.fetched, state.requests);
159
+ }
160
+ throw new Error(AUTO_UNSUPPORTED_ERROR);
161
+ }
162
+ state.need = nextNeed;
163
+ state.iter++;
164
+ return runAdaptiveIteration(state);
165
+ }
166
+
167
+ function handleAdaptive416(state) {
168
+ return state.readRange(0, Infinity, {totalSize: undefined})
169
+ .then((full) => {
170
+ state.requests++;
171
+ state.buffer = full.buffer;
172
+ state.fetched = bufferByteLength(state.buffer);
173
+ if (full.totalSize !== undefined) {
174
+ state.totalSize = full.totalSize;
175
+ }
176
+ return Promise.resolve(loadFromData(state.buffer, state.options));
177
+ })
178
+ .then((tags) => {
179
+ if (!tags || !tags.metadataRange) {
180
+ throw new Error(AUTO_UNSUPPORTED_ERROR);
181
+ }
182
+ return attachAdaptiveFields(tags, state.buffer, state.fetched, state.requests);
183
+ });
184
+ }
185
+
186
+ function runAdaptiveFallback(state) {
187
+ // Iteration cap reached. Fall back to full read for correctness.
188
+ console.warn( // eslint-disable-line no-console
189
+ `ExifReader: length:"auto" did not converge in ${AUTO_MAX_ITERATIONS} iterations; falling back to full read.`
190
+ );
191
+ let chunkPromise;
192
+ if (state.totalSize !== undefined && state.fetched < state.totalSize) {
193
+ chunkPromise = state.readRange(state.fetched, state.totalSize, {totalSize: state.totalSize})
194
+ .then((chunk) => {
195
+ state.requests++;
196
+ state.buffer = concatBuffers(state.buffer, chunk.buffer);
197
+ state.fetched = bufferByteLength(state.buffer);
198
+ });
199
+ } else if (state.totalSize === undefined) {
200
+ chunkPromise = state.readRange(state.fetched, Infinity, {totalSize: state.totalSize})
201
+ .then((chunk) => {
202
+ state.requests++;
203
+ if (chunk.totalSize !== undefined) {
204
+ state.totalSize = chunk.totalSize;
205
+ }
206
+ state.buffer = concatBuffers(state.buffer, chunk.buffer);
207
+ state.fetched = bufferByteLength(state.buffer);
208
+ });
209
+ } else {
210
+ chunkPromise = Promise.resolve();
211
+ }
212
+ return chunkPromise
213
+ .then(() => Promise.resolve(loadFromData(state.buffer, state.options)))
214
+ .then((tags) => {
215
+ if (!tags || !tags.metadataRange) {
216
+ throw new Error(AUTO_UNSUPPORTED_ERROR);
217
+ }
218
+ return attachAdaptiveFields(tags, state.buffer, state.fetched, state.requests);
219
+ });
220
+ }
221
+ }
222
+
223
+ function mergeAdaptiveChunk(state, chunk) {
224
+ // HTTP 200 on a Range request means the server ignored Range and
225
+ // sent the full body. Replace the buffer instead of concatenating to
226
+ // avoid corrupting offsets.
227
+ if (chunk.status === HTTP_STATUS_OK && state.fetched > 0) {
228
+ state.buffer = chunk.buffer;
229
+ state.fetched = bufferByteLength(state.buffer);
230
+ if (chunk.totalSize !== undefined) {
231
+ state.totalSize = chunk.totalSize;
232
+ }
233
+ return;
234
+ }
235
+ if (chunk.totalSize !== undefined && state.totalSize === undefined) {
236
+ state.totalSize = chunk.totalSize;
237
+ }
238
+ state.buffer = concatBuffers(state.buffer, chunk.buffer);
239
+ state.fetched = bufferByteLength(state.buffer);
240
+ }
241
+
242
+ function attachAdaptiveFields(tags, buffer, fetched, requests) {
243
+ const end = tags.metadataRange.end;
244
+ // `buffer` = minimal slice for re-extraction. `fetched` = bytes
245
+ // actually read (may exceed `end` due to fixed-size chunks).
246
+ tags.metadataRange.buffer = sliceBufferToEnd(buffer, end);
247
+ tags.metadataRange.fetched = fetched;
248
+ tags.metadataRange.requests = requests;
249
+ return tags;
250
+ }
251
+
252
+ function pickNextNeed({range, totalSize, fetched}) {
253
+ if (range) {
254
+ return Math.min(
255
+ Math.max(range.end, fetched * 2),
256
+ totalSize !== undefined ? totalSize : Infinity
257
+ );
258
+ }
259
+ // No blocks yet. Jump straight to EOF if known. Avoids burning the
260
+ // iteration cap on ISO-BMFF where `meta` sits near EOF.
261
+ if (totalSize !== undefined) {
262
+ return totalSize;
263
+ }
264
+ return fetched * 2;
265
+ }
266
+
267
+ function sliceBufferToEnd(buffer, end) {
268
+ if (!buffer || typeof end !== 'number' || end < 0) {
269
+ return buffer;
270
+ }
271
+ if (typeof Buffer !== 'undefined' && Buffer.isBuffer(buffer)) {
272
+ return Buffer.from(buffer.subarray(0, Math.min(end, buffer.length)));
273
+ }
274
+ if (buffer instanceof ArrayBuffer) {
275
+ return buffer.slice(0, Math.min(end, buffer.byteLength));
276
+ }
277
+ if (typeof SharedArrayBuffer !== 'undefined' && buffer instanceof SharedArrayBuffer) {
278
+ return buffer.slice(0, Math.min(end, buffer.byteLength));
279
+ }
280
+ return buffer;
281
+ }
282
+
283
+ function sliceInputBuffer(data, end) {
284
+ if (typeof Buffer !== 'undefined' && Buffer.isBuffer(data)) {
285
+ return Buffer.from(data.subarray(0, end));
286
+ }
287
+ if (data instanceof ArrayBuffer) {
288
+ return data.slice(0, end);
289
+ }
290
+ if (typeof SharedArrayBuffer !== 'undefined' && data instanceof SharedArrayBuffer) {
291
+ return data.slice(0, end);
292
+ }
293
+ if (ArrayBuffer.isView(data)) {
294
+ return data.buffer.slice(data.byteOffset, data.byteOffset + end);
295
+ }
296
+ return data;
297
+ }
298
+
299
+ function bufferByteLength(buffer) {
300
+ if (!buffer) {
301
+ return 0;
302
+ }
303
+ if (typeof buffer.byteLength === 'number') {
304
+ return buffer.byteLength;
305
+ }
306
+ if (typeof buffer.length === 'number') {
307
+ return buffer.length;
308
+ }
309
+ return 0;
310
+ }
@@ -10,6 +10,7 @@ export function buildTagsFromMergeSteps({
10
10
  tagFilter,
11
11
  dataView,
12
12
  tiffHeaderOffset,
13
+ exifDataView,
13
14
  fileType,
14
15
  pngTextChunks,
15
16
  pngTextIsAsync,
@@ -27,6 +28,7 @@ export function buildTagsFromMergeSteps({
27
28
  tagFilter,
28
29
  dataView,
29
30
  tiffHeaderOffset,
31
+ exifDataView,
30
32
  fileType,
31
33
  thumbnailIfdTags,
32
34
  tags,
@@ -64,6 +66,7 @@ export function applyMergeStep({
64
66
  tagFilter,
65
67
  dataView,
66
68
  tiffHeaderOffset,
69
+ exifDataView,
67
70
  fileType,
68
71
  thumbnailIfdTags,
69
72
  tags,
@@ -304,7 +307,7 @@ export function applyMergeStep({
304
307
  const thumbnail = (deps.Constants.USE_JPEG || deps.Constants.USE_WEBP)
305
308
  && deps.Constants.USE_EXIF
306
309
  && deps.Constants.USE_THUMBNAIL
307
- && deps.Thumbnail.get(dataView, parsedThumbnailIfdTags, tiffHeaderOffset);
310
+ && deps.Thumbnail.get(exifDataView || dataView, parsedThumbnailIfdTags, tiffHeaderOffset);
308
311
  if (thumbnail) {
309
312
  tags.Thumbnail = thumbnail;
310
313
  } else {
@@ -314,6 +317,22 @@ export function applyMergeStep({
314
317
  return tags;
315
318
  }
316
319
 
320
+ if (step.type === 'metadataRange') {
321
+ if (!expanded) {
322
+ return tags;
323
+ }
324
+ const metadataRange = buildMetadataRange(
325
+ step.metadataBlocks,
326
+ step.metadataTruncated,
327
+ dataView,
328
+ parsedGroups
329
+ );
330
+ if (metadataRange) {
331
+ tags.metadataRange = metadataRange;
332
+ }
333
+ return tags;
334
+ }
335
+
317
336
  if (step.type === 'fileType') {
318
337
  if (
319
338
  fileType
@@ -461,3 +480,49 @@ export function addPngTextReadTagsToTagsAndGroups({
461
480
  export function isThenable(value) {
462
481
  return !!value && typeof value.then === 'function';
463
482
  }
483
+
484
+ function buildMetadataRange(metadataBlocks, metadataTruncated, dataView, parsedGroups) {
485
+ const blocks = (metadataBlocks || []).slice();
486
+ const finderTruncated = !!metadataTruncated;
487
+
488
+ if (parsedGroups && parsedGroups.mpf && Array.isArray(parsedGroups.mpf.Images)) {
489
+ for (let i = 0; i < parsedGroups.mpf.Images.length; i++) {
490
+ const image = parsedGroups.mpf.Images[i];
491
+ if (!image || !image.ImageOffset || !image.ImageSize) {
492
+ continue;
493
+ }
494
+ const offset = image.ImageOffset.value;
495
+ const size = image.ImageSize.value;
496
+ // Skip the primary self-reference (offset 0), malformed entries,
497
+ // and zero-length entries.
498
+ if (typeof offset !== 'number' || offset <= 0
499
+ || typeof size !== 'number' || size <= 0) {
500
+ continue;
501
+ }
502
+ blocks.push({
503
+ type: 'mpfImage',
504
+ start: offset,
505
+ end: offset + size,
506
+ });
507
+ }
508
+ }
509
+
510
+ if (blocks.length === 0) {
511
+ return undefined;
512
+ }
513
+
514
+ blocks.sort((a, b) => a.start - b.start);
515
+
516
+ const start = blocks[0].start;
517
+ let end = blocks[0].end;
518
+ for (let i = 1; i < blocks.length; i++) {
519
+ if (blocks[i].end > end) {
520
+ end = blocks[i].end;
521
+ }
522
+ }
523
+
524
+ const byteLength = dataView && typeof dataView.byteLength === 'number' ? dataView.byteLength : 0;
525
+ const complete = !finderTruncated && end <= byteLength;
526
+
527
+ return {start, end, complete, blocks};
528
+ }
@@ -6,6 +6,23 @@ import TextDecoder from './text-decoder.js';
6
6
 
7
7
  const TAG_HEADER_SIZE = 5;
8
8
 
9
+ // Windows-1252 (CP1252) mapping for the 0x80–0x9F range, which is where it
10
+ // differs from ISO-8859-1. Bytes outside this range map identically in the
11
+ // two encodings. Five positions (0x81, 0x8D, 0x8F, 0x90, 0x9D) are unassigned
12
+ // in CP1252; we keep their raw byte value so the data is still
13
+ // representable. We do not delegate to TextDecoder('windows-1252') because
14
+ // Node.js's built-in implementation regressed in 20.18.3 / 22.13.0 / 23.4.0
15
+ // and returns the raw bytes for 0x80–0x9F instead of the WHATWG-specified
16
+ // codepoints (nodejs/node#60888, still tracked under nodejs/node#61041).
17
+ const WINDOWS_1252_C1_MAP = {
18
+ 0x80: 0x20ac, 0x82: 0x201a, 0x83: 0x0192, 0x84: 0x201e, 0x85: 0x2026,
19
+ 0x86: 0x2020, 0x87: 0x2021, 0x88: 0x02c6, 0x89: 0x2030, 0x8a: 0x0160,
20
+ 0x8b: 0x2039, 0x8c: 0x0152, 0x8e: 0x017d,
21
+ 0x91: 0x2018, 0x92: 0x2019, 0x93: 0x201c, 0x94: 0x201d, 0x95: 0x2022,
22
+ 0x96: 0x2013, 0x97: 0x2014, 0x98: 0x02dc, 0x99: 0x2122, 0x9a: 0x0161,
23
+ 0x9b: 0x203a, 0x9c: 0x0153, 0x9e: 0x017e, 0x9f: 0x0178,
24
+ };
25
+
9
26
  export default {
10
27
  decode,
11
28
  TAG_HEADER_SIZE
@@ -25,7 +42,29 @@ function decode(encoding, tagValue) {
25
42
  }
26
43
 
27
44
  const stringValue = tagValue.map((charCode) => String.fromCharCode(charCode)).join('');
28
- return decodeAsciiValue(stringValue);
45
+ try {
46
+ return decodeURIComponent(escape(stringValue));
47
+ } catch (error) {
48
+ // The bytes are not valid UTF-8. Many real-world IPTC blocks have no
49
+ // Coded Character Set tag but use Windows-1252 (en/em dashes,
50
+ // ellipsis, smart quotes, etc.). Remap the bytes through CP1252 so
51
+ // those characters render correctly instead of staying as C1 control
52
+ // characters.
53
+ return decodeWindows1252(tagValue);
54
+ }
55
+ }
56
+
57
+ function decodeWindows1252(tagValue) {
58
+ const isDataView = tagValue instanceof DataView;
59
+ const length = isDataView ? tagValue.byteLength : tagValue.length;
60
+ const getByte = isDataView ? (i) => tagValue.getUint8(i) : (i) => tagValue[i];
61
+ const codePoints = new Array(length);
62
+ for (let i = 0; i < length; i++) {
63
+ const byte = getByte(i);
64
+ const mapped = WINDOWS_1252_C1_MAP[byte];
65
+ codePoints[i] = mapped !== undefined ? mapped : byte;
66
+ }
67
+ return String.fromCharCode.apply(null, codePoints);
29
68
  }
30
69
 
31
70
  function decodeAsciiValue(asciiValue) {
package/src/xml.js CHANGED
@@ -12,14 +12,52 @@ export default {
12
12
  const XML_MARKER_OFFSET = 0;
13
13
  const XML_MARKER = '<?xpacket begin';
14
14
 
15
+ // Closing markers for an XMP packet. `</x:xmpmeta>` covers XMP without an
16
+ // xpacket wrapper.
17
+ const XMP_END_PATTERNS = [
18
+ '<?xpacket end=',
19
+ '</x:xmpmeta>',
20
+ ];
21
+
22
+ /**
23
+ * Checks if the provided data view represents a standalone XMP file.
24
+ *
25
+ * @param {DataView} dataView The data view to check.
26
+ * @returns {boolean} True if the data view starts with the XMP packet marker.
27
+ */
15
28
  function isXMLFile(dataView) {
16
29
  return !!dataView && getStringFromDataView(dataView, XML_MARKER_OFFSET, XML_MARKER.length) === XML_MARKER;
17
30
  }
18
31
 
19
- function findOffsets(dataView) {
32
+ /**
33
+ * Finds the XMP chunk offset for a standalone XMP file.
34
+ *
35
+ * @param {DataView} dataView The data view to find offsets in.
36
+ * @param {Array<Object>=} metadataBlocks Optional out-array. When provided,
37
+ * receives one `xmp` block covering the whole buffer and gets a
38
+ * `truncated` property set to true if no XMP closing marker is found.
39
+ * @returns {{xmpChunks: Array<{dataOffset: number, length: number}>}}
40
+ */
41
+ function findOffsets(dataView, metadataBlocks) {
20
42
  const xmpChunks = [];
21
43
  xmpChunks.push({dataOffset: XML_MARKER_OFFSET, length: dataView.byteLength});
44
+ if (metadataBlocks) {
45
+ metadataBlocks.push({type: 'xmp', start: 0, end: dataView.byteLength});
46
+ metadataBlocks.truncated = !hasXmpClosingMarker(dataView);
47
+ }
22
48
  return {
23
49
  xmpChunks,
24
50
  };
25
51
  }
52
+
53
+ function hasXmpClosingMarker(dataView) {
54
+ // XMP packets can have arbitrary trailing whitespace padding, so scan
55
+ // the entire buffer rather than a fixed tail window.
56
+ const text = getStringFromDataView(dataView, 0, dataView.byteLength);
57
+ for (let i = 0; i < XMP_END_PATTERNS.length; i++) {
58
+ if (text.indexOf(XMP_END_PATTERNS[i]) !== -1) {
59
+ return true;
60
+ }
61
+ }
62
+ return false;
63
+ }