exifreader 4.52.0 → 4.54.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "exifreader",
3
- "version": "4.52.0",
3
+ "version": "4.54.0",
4
4
  "description": "Library that parses Exif metadata in images.",
5
5
  "author": "Mattias Wallander <mattias@wallander.eu>",
6
6
  "repository": {
@@ -59,14 +59,14 @@
59
59
  "eslint-plugin-cypress": "^6.4.4",
60
60
  "globals": "^17.13.0",
61
61
  "husky": "^9.0.11",
62
- "linkedom": "^0.18.13",
62
+ "linkedom": "^0.18.14",
63
63
  "mocha": "^12.0.3",
64
- "npm-run-all2": "^9.0.3",
64
+ "npm-run-all2": "^9.0.4",
65
65
  "rimraf": "^5.0.5",
66
66
  "string-replace-loader": "^3.1.0",
67
67
  "terser-webpack-plugin": "^5.6.1",
68
68
  "typescript": "^7.0.2",
69
- "webpack": "5.112.0",
69
+ "webpack": "5.112.2",
70
70
  "webpack-cli": "^7.2.3",
71
71
  "webpack-dev-server": "^6.1.0"
72
72
  },
@@ -0,0 +1,27 @@
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
+ import {getByteString} from './utils.js';
6
+
7
+ export function getBase64Image(image) {
8
+ if (typeof image === 'string' && typeof btoa !== 'undefined') {
9
+ // Only tests pass a string. btoa reads it as Latin-1, Buffer.from would use UTF-8.
10
+ return btoa(image);
11
+ }
12
+ if (hasBufferFrom()) {
13
+ return Buffer.from(image).toString('base64'); // eslint-disable-line no-undef
14
+ }
15
+ if (typeof btoa !== 'undefined') {
16
+ return btoa(getByteString(new Uint8Array(image)));
17
+ }
18
+ if (typeof Buffer === 'undefined') {
19
+ return undefined;
20
+ }
21
+ return (new Buffer(image)).toString('base64'); // eslint-disable-line no-undef
22
+ }
23
+
24
+ function hasBufferFrom() {
25
+ // Buffer polyfills before buffer@4.6.0 inherit Uint8Array.from, which returns an empty array for an ArrayBuffer.
26
+ return typeof Buffer !== 'undefined' && typeof Buffer.from !== 'undefined' && Buffer.from !== Uint8Array.from; // eslint-disable-line no-undef
27
+ }
package/src/dom-parser.js CHANGED
@@ -4,22 +4,71 @@
4
4
 
5
5
  import NodeRequire from './node-require.js';
6
6
 
7
+ // The XMP depth and markup node limits are checked the way @xmldom/xmldom 0.9.12 reads markup.
8
+ const MIN_XMLDOM_VERSION = [0, 9, 12];
9
+ const NO_PARSER_WARNING = 'Warning: DOMParser is not available. It is needed to be able to parse XMP tags.';
10
+ const XMLDOM_REMEDY = 'ExifReader needs 0.9.12 or later, or a parser passed in the domParser option.';
11
+ const UNREADABLE_VERSION_WARNING = 'Warning: XMP tags are skipped because the version of the @xmldom/xmldom that was found could not be read. ' + XMLDOM_REMEDY;
12
+
7
13
  export default {
8
14
  get
9
15
  };
10
16
 
17
+ /**
18
+ * Finds the DOM parser to read XMP with: the one passed in, a global DOMParser,
19
+ * or an @xmldom/xmldom of version 0.9.12 or later.
20
+ *
21
+ * @param {Object} [domParser] A parser passed in by the caller.
22
+ * @returns {{parser: (Object|undefined), warning: (string|undefined)}} The
23
+ * parser, or no parser and the warning that says why.
24
+ */
11
25
  function get(domParser) {
12
26
  if (domParser) {
13
- return domParser;
27
+ return {parser: domParser};
14
28
  }
15
29
 
16
30
  if (typeof DOMParser !== 'undefined') {
17
- return new DOMParser();
31
+ return {parser: new DOMParser()};
18
32
  }
33
+
34
+ return getXmldomParser();
35
+ }
36
+
37
+ function getXmldomParser() {
19
38
  try {
20
39
  const {DOMParser, onErrorStopParsing} = NodeRequire.optionalPackage('@xmldom/xmldom');
21
- return new DOMParser({onError: onErrorStopParsing});
40
+ const warning = getXmldomVersionWarning(readXmldomVersion());
41
+ if (warning) {
42
+ return {parser: undefined, warning};
43
+ }
44
+ return {parser: new DOMParser({onError: onErrorStopParsing})};
22
45
  } catch (error) {
23
- return undefined;
46
+ return {parser: undefined, warning: NO_PARSER_WARNING};
47
+ }
48
+ }
49
+
50
+ function readXmldomVersion() {
51
+ const packageJson = NodeRequire.optionalPackage('@xmldom/xmldom/package.json');
52
+ return packageJson ? packageJson.version : undefined;
53
+ }
54
+
55
+ function getXmldomVersionWarning(version) {
56
+ const match = typeof version === 'string' ? /^(\d+)\.(\d+)\.(\d+)(-?)/.exec(version) : null;
57
+ if (!match) {
58
+ return UNREADABLE_VERSION_WARNING;
59
+ }
60
+ if (isOlderThanMinimum(match.slice(1, 4).map(Number), match[4] === '-')) {
61
+ return `Warning: XMP tags are skipped because the @xmldom/xmldom that was found is version ${version}. ${XMLDOM_REMEDY}`;
62
+ }
63
+ return undefined;
64
+ }
65
+
66
+ // A prerelease of the minimum version (0.9.12-beta.1) comes before it.
67
+ function isOlderThanMinimum(parts, isPrerelease) {
68
+ for (let i = 0; i < MIN_XMLDOM_VERSION.length; i++) {
69
+ if (parts[i] !== MIN_XMLDOM_VERSION[i]) {
70
+ return parts[i] < MIN_XMLDOM_VERSION[i];
71
+ }
24
72
  }
73
+ return isPrerelease;
25
74
  }
package/src/engine.js ADDED
@@ -0,0 +1,388 @@
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
+ import {decompress, isThenable, objectAssign} from './utils.js';
6
+ import {getValueBudget} from './tags-helpers.js';
7
+
8
+ // A finder block, a block it emits and a block emitted by that one.
9
+ export const MAX_BLOCK_DEPTH = 3;
10
+ export const MAX_DECOMPRESSIONS_IN_FLIGHT = 4;
11
+
12
+ // Brob XMP is bounded by the file size, as brob Exif is, plus room for one JPEG
13
+ // standard XMP segment so that a small file can still carry a typical packet.
14
+ const BROB_XMP_SIZE_PER_INPUT_SIZE = 4;
15
+ const BROB_XMP_SIZE_ALLOWANCE = 64 * 1024;
16
+ // An embedded thumbnail is sliced from a decoded or decompressed view that can be
17
+ // far larger than the file. A real JPEG thumbnail shrinks only a little when
18
+ // compressed, so bound the embedded thumbnails of a file by twice its size in
19
+ // total, plus room for a typical thumbnail.
20
+ const EMBEDDED_THUMBNAIL_SIZE_PER_INPUT_SIZE = 2;
21
+ const EMBEDDED_THUMBNAIL_SIZE_ALLOWANCE = 64 * 1024;
22
+
23
+ /**
24
+ * Runs the composition's groups over the finder's blocks and the blocks the
25
+ * groups emit, and collects their merge blocks in dispatch order.
26
+ *
27
+ * @param {{groups: Array<object>, dispatchKind: function, rank: function, suppressions: Array<object>}} composition
28
+ * `groups` in dispatch order of the kinds they consume, each
29
+ * `{key, consumes, emits, read(block, context), merge(block)}`;
30
+ * `dispatchKind(block)` the kind a block dispatches under; `rank(block)` an
31
+ * integer, of which only the top one per `block.kind` dispatches among the
32
+ * finder blocks; `suppressions` rules `{kind, isSuppressed(block,
33
+ * finderBlocks, context)}` that drop an emitted block.
34
+ * @param {Array<object>} blocks The finder's blocks.
35
+ * @param {object} context From createContext.
36
+ * @returns {{mergeBlocks: Array<object>}|Promise<{mergeBlocks: Array<object>}>}
37
+ * A promise when `context.options.async` is set.
38
+ */
39
+ export function run(composition, blocks, context) {
40
+ const plan = createDispatchPlan(composition, blocks, context);
41
+ const roots = [];
42
+ const deferred = [];
43
+
44
+ for (let i = 0; i < plan.finderBlocks.length; i++) {
45
+ dispatchBlock(plan.finderBlocks[i], 1, roots, deferred, plan);
46
+ }
47
+
48
+ if (!context.options.async) {
49
+ return {mergeBlocks: getMergeBlocks(roots)};
50
+ }
51
+
52
+ return runDeferredRounds(deferred, plan).then(() => ({mergeBlocks: getMergeBlocks(roots)}));
53
+ }
54
+
55
+ function createDispatchPlan(composition, blocks, context) {
56
+ const consumedKinds = Object.create(null);
57
+ const groups = composition.groups;
58
+ for (let i = 0; i < groups.length; i++) {
59
+ for (let j = 0; j < groups[i].consumes.length; j++) {
60
+ consumedKinds[groups[i].consumes[j]] = true;
61
+ }
62
+ }
63
+
64
+ const plan = {
65
+ composition,
66
+ context,
67
+ consumedKinds,
68
+ consumersOf,
69
+ shouldDispatch: createShouldDispatch(groups, consumersOf, context.tagFilter),
70
+ finderBlocks: undefined,
71
+ };
72
+ plan.finderBlocks = getFinderBlocksToDispatch(composition.rank, getFinderCandidates(composition, blocks, plan));
73
+
74
+ return plan;
75
+
76
+ function consumersOf(kind) {
77
+ return groups.filter((group) => group.consumes.indexOf(kind) !== -1);
78
+ }
79
+ }
80
+
81
+ // A group dispatches when the filter parses its key, or a group that consumes
82
+ // a kind it emits does. A cycle counts as false; validateComposition rejects
83
+ // one anyway.
84
+ function createShouldDispatch(groups, consumersOf, tagFilter) {
85
+ const verdicts = [];
86
+
87
+ return shouldDispatch;
88
+
89
+ function shouldDispatch(group) {
90
+ const index = groups.indexOf(group);
91
+ if (verdicts[index] === undefined) {
92
+ verdicts[index] = 'visiting';
93
+ verdicts[index] = tagFilter.shouldParseGroup(group.key)
94
+ || group.emits.some((kind) => consumersOf(kind).some(shouldDispatch));
95
+ }
96
+ return verdicts[index] === true;
97
+ }
98
+ }
99
+
100
+ function getFinderCandidates(composition, blocks, plan) {
101
+ const candidates = [];
102
+ for (let i = 0; i < blocks.length; i++) {
103
+ const position = getDispatchPosition(composition.groups, composition.dispatchKind(blocks[i]));
104
+ if (position === -1 || isCompressedInSyncMode(blocks[i], plan.context)) {
105
+ continue;
106
+ }
107
+ candidates.push({block: blocks[i], index: i, position});
108
+ }
109
+ return candidates;
110
+ }
111
+
112
+ function getDispatchPosition(groups, kind) {
113
+ for (let i = 0; i < groups.length; i++) {
114
+ if (groups[i].consumes.indexOf(kind) !== -1) {
115
+ return i;
116
+ }
117
+ }
118
+ return -1;
119
+ }
120
+
121
+ // Of each block.kind only the top rank dispatches. The explicit comparator keeps
122
+ // block-list order within a kind, since sort is not stable on every target.
123
+ function getFinderBlocksToDispatch(rank, candidates) {
124
+ const topRanks = Object.create(null);
125
+ for (let i = 0; i < candidates.length; i++) {
126
+ const kind = candidates[i].block.kind;
127
+ candidates[i].rank = rank(candidates[i].block);
128
+ if (topRanks[kind] === undefined || candidates[i].rank > topRanks[kind]) {
129
+ topRanks[kind] = candidates[i].rank;
130
+ }
131
+ }
132
+
133
+ return candidates
134
+ .filter((candidate) => candidate.rank === topRanks[candidate.block.kind])
135
+ .sort((a, b) => (a.position - b.position) || (a.index - b.index))
136
+ .map((candidate) => candidate.block);
137
+ }
138
+
139
+ function isCompressedInSyncMode(block, context) {
140
+ return !context.options.async && block.compression !== undefined;
141
+ }
142
+
143
+ // Every group consuming the block's kind reads it, in table order. A read that
144
+ // throws drops the block for that group alone.
145
+ function dispatchBlock(block, depth, siblings, deferred, plan) {
146
+ const groups = plan.consumersOf(plan.composition.dispatchKind(block));
147
+
148
+ for (let i = 0; i < groups.length; i++) {
149
+ const group = groups[i];
150
+ if (!plan.shouldDispatch(group)) {
151
+ continue;
152
+ }
153
+ const node = {group, block, tags: undefined, children: []};
154
+ let result;
155
+ try {
156
+ result = group.read(block, plan.context);
157
+ } catch (error) {
158
+ continue;
159
+ }
160
+ if (isThenable(result)) {
161
+ if (!plan.context.options.async) {
162
+ throw new Error('Promise is required when async mode is enabled.');
163
+ }
164
+ siblings.push(node);
165
+ deferred.push({node, depth, promise: Promise.resolve(result).then(keepResult, dropResult)});
166
+ continue;
167
+ }
168
+ if (result === undefined) {
169
+ continue;
170
+ }
171
+ siblings.push(node);
172
+ node.tags = result.tags;
173
+ dispatchEmittedBlocks(result.blocks, depth + 1, node.children, deferred, plan);
174
+ }
175
+ }
176
+
177
+ function keepResult(result) {
178
+ return result;
179
+ }
180
+
181
+ // A rejected read (a decompression failure, a bad header) drops its block alone.
182
+ function dropResult() {
183
+ return undefined;
184
+ }
185
+
186
+ function dispatchEmittedBlocks(blocks, depth, children, deferred, plan) {
187
+ if (!blocks) {
188
+ return;
189
+ }
190
+ for (let i = 0; i < blocks.length; i++) {
191
+ const block = blocks[i];
192
+ if (
193
+ depth > MAX_BLOCK_DEPTH
194
+ || !plan.consumedKinds[plan.composition.dispatchKind(block)]
195
+ || isCompressedInSyncMode(block, plan.context)
196
+ || isSuppressed(block, plan)
197
+ ) {
198
+ continue;
199
+ }
200
+ dispatchBlock(block, depth, children, deferred, plan);
201
+ }
202
+ }
203
+
204
+ function isSuppressed(block, plan) {
205
+ const rules = plan.composition.suppressions;
206
+ for (let i = 0; i < rules.length; i++) {
207
+ if (rules[i].kind === block.kind && rules[i].isSuppressed(block, plan.finderBlocks, plan.context)) {
208
+ return true;
209
+ }
210
+ }
211
+ return false;
212
+ }
213
+
214
+ // The deferred blocks of a round settle together, then their emitted blocks
215
+ // dispatch in block-list order, whatever order the decompressions finished in.
216
+ // A dropped block's node keeps undefined tags and no children, so it merges
217
+ // nothing.
218
+ function runDeferredRounds(deferred, plan) {
219
+ if (deferred.length === 0) {
220
+ return Promise.resolve();
221
+ }
222
+ return Promise.all(deferred.map((entry) => entry.promise)).then((results) => {
223
+ const nextRound = [];
224
+ for (let i = 0; i < deferred.length; i++) {
225
+ const {node, depth} = deferred[i];
226
+ if (results[i] === undefined) {
227
+ continue;
228
+ }
229
+ node.tags = results[i].tags;
230
+ dispatchEmittedBlocks(results[i].blocks, depth + 1, node.children, nextRound, plan);
231
+ }
232
+ return runDeferredRounds(nextRound, plan);
233
+ });
234
+ }
235
+
236
+ // A node with children, or one whose merge descriptor names an outer slot,
237
+ // gives a nested container at that slot holding its own block first; a node
238
+ // whose tags are undefined contributes no block of its own.
239
+ function getMergeBlocks(nodes) {
240
+ const mergeBlocks = [];
241
+ for (let i = 0; i < nodes.length; i++) {
242
+ mergeBlocks.push.apply(mergeBlocks, getNodeMergeBlocks(nodes[i]));
243
+ }
244
+ return mergeBlocks;
245
+ }
246
+
247
+ function getNodeMergeBlocks(node) {
248
+ const merge = node.group.merge(node.block);
249
+ const own = node.tags === undefined ? [] : [objectAssign({group: node.group.key, tags: node.tags}, merge)];
250
+ const children = getMergeBlocks(node.children);
251
+ if (children.length === 0 && merge.outerSlot === undefined) {
252
+ return own;
253
+ }
254
+ return [{slot: merge.outerSlot || merge.slot, mode: 'nested', blocks: own.concat(children)}];
255
+ }
256
+
257
+ /**
258
+ * Builds the per-load state the groups share: the input, the options, the
259
+ * budgets and the entry's helpers.
260
+ *
261
+ * @param {{dataView: DataView, options: object, tagFilter: object, decompressConfig: object, getBase64Image: function, getDomParser: function}} parts
262
+ * @returns {object} The context, with `decompress` running through a pool of at
263
+ * most MAX_DECOMPRESSIONS_IN_FLIGHT tasks and `getValueBudget(view)`
264
+ * creating one budget on its first call.
265
+ */
266
+ export function createContext({dataView, options, tagFilter, decompressConfig, getBase64Image, getDomParser}) {
267
+ const pool = createPool(MAX_DECOMPRESSIONS_IN_FLIGHT);
268
+ const inputByteLength = getInputByteLength(dataView);
269
+ const context = {
270
+ dataView,
271
+ options,
272
+ tagFilter,
273
+ decompressConfig,
274
+ getBase64Image,
275
+ getDomParser,
276
+ valueBudget: undefined,
277
+ decompressedApplicationNotesSize: 0,
278
+ copiedThumbnailSize: 0,
279
+ hasEmbeddedThumbnailImage: false,
280
+ compressedPngTextChunks: 0,
281
+ hasRawIptcProfile: undefined,
282
+ embeddedThumbnailSizeBound: EMBEDDED_THUMBNAIL_SIZE_PER_INPUT_SIZE * inputByteLength + EMBEDDED_THUMBNAIL_SIZE_ALLOWANCE,
283
+ decompress(view, compressionMethod, encoding, returnType) {
284
+ return pool.run(() => decompress(view, compressionMethod, encoding, returnType, decompressConfig));
285
+ },
286
+ // The main Exif block creates the budget from its view; later callers
287
+ // get the same object, whatever view they pass. The view is only
288
+ // missing in unit tests that fake the readers.
289
+ getValueBudget(view) {
290
+ if (context.valueBudget === undefined) {
291
+ const budgetView = view || dataView;
292
+ if (budgetView !== undefined) {
293
+ context.valueBudget = getValueBudget(budgetView);
294
+ }
295
+ }
296
+ return context.valueBudget;
297
+ },
298
+ // The brob XMP bound covers the decompressed Exif blocks of a file
299
+ // together, so that several cannot each pass it.
300
+ takeDecompressedApplicationNotesAllowance(byteLength) {
301
+ if (context.exceedsBrobXmpSizeBound(context.decompressedApplicationNotesSize + byteLength)) {
302
+ return false;
303
+ }
304
+ context.decompressedApplicationNotesSize += byteLength;
305
+ return true;
306
+ },
307
+ exceedsBrobXmpSizeBound(byteLength) {
308
+ return byteLength > BROB_XMP_SIZE_PER_INPUT_SIZE * inputByteLength + BROB_XMP_SIZE_ALLOWANCE;
309
+ },
310
+ };
311
+
312
+ return context;
313
+ }
314
+
315
+ function getInputByteLength(dataView) {
316
+ return dataView !== undefined && typeof dataView.byteLength === 'number' ? dataView.byteLength : 0;
317
+ }
318
+
319
+ // Starts a task when fewer than `limit` are running, else queues it until one
320
+ // settles. Promise is only referenced once a task is given, in async mode.
321
+ function createPool(limit) {
322
+ const queue = [];
323
+ let running = 0;
324
+
325
+ return {
326
+ run(task) {
327
+ return new Promise((resolve, reject) => {
328
+ queue.push({task, resolve, reject});
329
+ startNext();
330
+ });
331
+ },
332
+ };
333
+
334
+ function startNext() {
335
+ if (running >= limit || queue.length === 0) {
336
+ return;
337
+ }
338
+ const {task, resolve, reject} = queue.shift();
339
+ running++;
340
+ // The wrapper turns a synchronous throw from a task into a rejection.
341
+ new Promise((start) => start(task())).then((result) => {
342
+ running--;
343
+ startNext();
344
+ resolve(result);
345
+ }, (error) => {
346
+ running--;
347
+ startNext();
348
+ reject(error);
349
+ });
350
+ }
351
+ }
352
+
353
+ /**
354
+ * Throws when the groups' static emission graph has a cycle: a kind that,
355
+ * through the groups consuming it and what they emit, leads back to itself.
356
+ *
357
+ * @param {{groups: Array<object>}} composition
358
+ */
359
+ export function validateComposition(composition) {
360
+ const edges = Object.create(null);
361
+ const groups = composition.groups;
362
+ for (let i = 0; i < groups.length; i++) {
363
+ for (let j = 0; j < groups[i].consumes.length; j++) {
364
+ const kind = groups[i].consumes[j];
365
+ edges[kind] = (edges[kind] || []).concat(groups[i].emits);
366
+ }
367
+ }
368
+
369
+ const states = Object.create(null);
370
+ for (const kind in edges) {
371
+ visit(kind);
372
+ }
373
+
374
+ function visit(kind) {
375
+ if (states[kind] === 'done') {
376
+ return;
377
+ }
378
+ if (states[kind] === 'visiting') {
379
+ throw new Error('The group emission graph has a cycle through ' + kind);
380
+ }
381
+ states[kind] = 'visiting';
382
+ const emitted = edges[kind] || [];
383
+ for (let i = 0; i < emitted.length; i++) {
384
+ visit(emitted[i]);
385
+ }
386
+ states[kind] = 'done';
387
+ }
388
+ }