@d0paminedriven/fs 10.1.0 → 12.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/dist/docs/index.d.ts +151 -0
  2. package/dist/docs/index.js +1163 -0
  3. package/dist/extract/client.d.ts +56 -0
  4. package/dist/extract/client.js +116 -0
  5. package/dist/extract/index.d.ts +66 -0
  6. package/dist/extract/index.js +620 -0
  7. package/dist/fs/index.d.ts +18 -58
  8. package/dist/fs/index.js +89 -19
  9. package/dist/fs-atomic/index.d.ts +25 -39
  10. package/dist/fs-atomic/index.js +94 -13
  11. package/dist/fs-base/index.d.ts +105 -113
  12. package/dist/fs-base/index.js +197 -12
  13. package/dist/fs-core/index.d.ts +18 -26
  14. package/dist/fs-core/index.js +43 -16
  15. package/dist/fs-fetch/index.d.ts +48 -65
  16. package/dist/fs-fetch/index.js +183 -18
  17. package/dist/fs-size/index.d.ts +15 -31
  18. package/dist/fs-size/index.js +63 -15
  19. package/dist/fs-tmp/index.d.ts +178 -195
  20. package/dist/fs-tmp/index.js +320 -17
  21. package/dist/images/index.d.ts +443 -0
  22. package/dist/images/index.js +893 -0
  23. package/dist/images/workup.d.ts +26 -0
  24. package/dist/images/workup.js +316 -0
  25. package/dist/index.d.ts +48 -22
  26. package/dist/index.js +19 -64
  27. package/dist/ld/index.d.ts +14 -16
  28. package/dist/ld/index.js +54 -6
  29. package/dist/mime/index.d.ts +301 -296
  30. package/dist/mime/index.js +348 -13
  31. package/dist/mixins/index.d.ts +30 -0
  32. package/dist/mixins/index.js +54 -0
  33. package/dist/types/index.d.ts +339 -260
  34. package/dist/types/index.js +10 -6
  35. package/dist/types/stream.d.ts +7 -9
  36. package/dist/types/stream.js +1 -1
  37. package/dist/url/index.d.ts +18 -25
  38. package/dist/url/index.js +19 -8
  39. package/dist/utils/index.d.ts +18 -26
  40. package/dist/utils/index.js +80 -7
  41. package/package.json +42 -22
  42. package/dist/chunk-4D2YBCI6.js +0 -163
  43. package/dist/chunk-5CACVZVF.js +0 -386
  44. package/dist/chunk-5H6GE5AO.js +0 -14
  45. package/dist/chunk-7QVYU63E.js +0 -7
  46. package/dist/chunk-DNR5ZI2T.js +0 -75
  47. package/dist/chunk-JZ6JNZZ6.js +0 -77
  48. package/dist/chunk-L2QMQOEJ.js +0 -366
  49. package/dist/chunk-NJHN5OE3.js +0 -33
  50. package/dist/chunk-OHKRQJZH.js +0 -82
  51. package/dist/chunk-OT5JEQKW.js +0 -139
  52. package/dist/chunk-PATMSIQK.js +0 -367
  53. package/dist/chunk-PB5A7ZFD.js +0 -79
  54. package/dist/chunk-VDKUXJE7.js +0 -240
  55. package/dist/chunk-Y5QWE4EG.js +0 -1335
  56. package/dist/chunk-YRCJWFZD.js +0 -107
  57. package/dist/image/index.d.ts +0 -182
  58. package/dist/image/index.js +0 -13
  59. package/dist/image/workup.d.ts +0 -40
  60. package/dist/image/workup.js +0 -12
@@ -1,1335 +0,0 @@
1
- import {
2
- ImageServiceWorkup
3
- } from "./chunk-5CACVZVF.js";
4
- import {
5
- __name
6
- } from "./chunk-7QVYU63E.js";
7
-
8
- // src/image/index.ts
9
- import { createReadStream } from "fs";
10
- import { relative } from "path";
11
- import { inflateSync } from "fflate";
12
- var ImageService = class extends ImageServiceWorkup {
13
- constructor(cwd) {
14
- super(cwd ??= process.cwd());
15
- this.cwd = cwd;
16
- }
17
- static {
18
- __name(this, "ImageService");
19
- }
20
- /**
21
- * Extract image metadata from a stream, reading only ~4KB for most formats
22
- * Automatically handles PNG, JPEG, GIF, BMP, WebP, and AVIF
23
- */
24
- async extractFromStream(stream, size = 4096) {
25
- const headerSize = size;
26
- const header = await this.readBytes(stream, headerSize);
27
- if (this.isPNG(header)) {
28
- return this.extractPNGFromBuffer(header);
29
- }
30
- if (this.isJPEG(header)) {
31
- return this.extractJPEGFromBuffer(header);
32
- }
33
- if (this.isGIF(header)) {
34
- return this.extractGIFFromBuffer(header);
35
- }
36
- if (this.isBMP(header)) {
37
- return this.extractBMPFromBuffer(header);
38
- }
39
- if (this.isWebP(header)) {
40
- return this.extractWebPFromBuffer(header);
41
- }
42
- if (this.isAVIF(header)) {
43
- return this.extractAVIFFromBuffer(header);
44
- }
45
- throw new Error("Unsupported image format or invalid file");
46
- }
47
- /**
48
- * Extract metadata from file path using streaming (memory efficient)
49
- */
50
- async extractFromPath(filePath, size = 4096) {
51
- const stream = createReadStream(relative(this.cwd, filePath), {
52
- highWaterMark: size
53
- });
54
- return this.extractFromStream(stream, size);
55
- }
56
- // Format detection helpers
57
- isPNG(buffer) {
58
- return buffer?.length >= 8 && buffer[0] === 137 && buffer[1] === 80 && buffer[2] === 78 && buffer[3] === 71 && buffer[4] === 13 && buffer[5] === 10 && buffer[6] === 26 && buffer[7] === 10;
59
- }
60
- isJPEG(buffer) {
61
- return buffer.length >= 2 && buffer[0] === 255 && buffer[1] === 216;
62
- }
63
- isGIF(buffer) {
64
- const header = buffer.toString("ascii", 0, 6);
65
- return buffer.length >= 6 && (header === "GIF87a" || header === "GIF89a");
66
- }
67
- isBMP(buffer) {
68
- return buffer.length >= 2 && buffer[0] === 66 && buffer[1] === 77;
69
- }
70
- isWebP(buffer) {
71
- return buffer.length >= 12 && buffer.toString("ascii", 0, 4) === "RIFF" && buffer.toString("ascii", 8, 12) === "WEBP";
72
- }
73
- isAVIF(buffer) {
74
- if (buffer.length < 32) return false;
75
- const ftyp = buffer.toString("ascii", 4, 8);
76
- if (ftyp !== "ftyp") return false;
77
- const brands = buffer.toString("ascii", 8, 32);
78
- return brands.includes("avif") || brands.includes("avis");
79
- }
80
- // Extract methods for each format (refactored from getImageSpecsWorkup)
81
- extractPNGFromBuffer(buffer) {
82
- if (!this.isPNG(buffer) || buffer.length < 24) {
83
- throw new Error("Invalid PNG header");
84
- }
85
- const width = buffer.readUInt32BE(16);
86
- const height = buffer.readUInt32BE(20);
87
- const colorType = buffer[25];
88
- let colorModel;
89
- let hasAlpha = false;
90
- switch (colorType) {
91
- case 0:
92
- colorModel = "grayscale";
93
- break;
94
- case 2:
95
- colorModel = "rgb";
96
- break;
97
- case 3:
98
- colorModel = "indexed";
99
- break;
100
- case 4:
101
- colorModel = "grayscale-alpha";
102
- hasAlpha = true;
103
- break;
104
- case 6:
105
- colorModel = "rgba";
106
- hasAlpha = true;
107
- break;
108
- default:
109
- colorModel = "unknown";
110
- }
111
- return {
112
- width,
113
- height,
114
- format: "png",
115
- frames: 1,
116
- animated: false,
117
- hasAlpha,
118
- orientation: null,
119
- aspectRatio: width / height,
120
- colorSpace: "unknown",
121
- colorModel,
122
- iccProfile: null,
123
- exifDateTimeOriginal: null
124
- };
125
- }
126
- extractJPEGFromBuffer(buffer) {
127
- if (!this.isJPEG(buffer)) {
128
- throw new Error("Invalid JPEG header");
129
- }
130
- let pos = 2;
131
- let width = 0;
132
- let height = 0;
133
- let colorModel = "unknown";
134
- while (pos < buffer.length - 10) {
135
- if (buffer[pos] !== 255) break;
136
- const marker = buffer[pos + 1];
137
- if (!marker || marker === 218) break;
138
- const segmentSize = buffer.readUInt16BE(pos + 2);
139
- if (marker && marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204) {
140
- const numComponents = buffer[pos + 4];
141
- switch (numComponents) {
142
- case 1:
143
- colorModel = "grayscale";
144
- break;
145
- case 3:
146
- colorModel = "ycbcr";
147
- break;
148
- case 4:
149
- colorModel = "ycck";
150
- break;
151
- default:
152
- colorModel = "unknown";
153
- }
154
- height = buffer.readUInt16BE(pos + 5);
155
- width = buffer.readUInt16BE(pos + 7);
156
- break;
157
- }
158
- pos += segmentSize + 2;
159
- if (pos >= buffer.length) break;
160
- }
161
- if (width === 0) {
162
- throw new Error("Could not find JPEG dimensions in available data");
163
- }
164
- return {
165
- width,
166
- height,
167
- format: "jpeg",
168
- frames: 1,
169
- animated: false,
170
- hasAlpha: false,
171
- orientation: null,
172
- aspectRatio: width / height,
173
- colorSpace: "unknown",
174
- colorModel,
175
- iccProfile: null,
176
- exifDateTimeOriginal: null
177
- };
178
- }
179
- extractGIFFromBuffer(buffer) {
180
- if (!this.isGIF(buffer) || buffer.length < 10) {
181
- throw new Error("Invalid GIF header");
182
- }
183
- const width = buffer.readUInt16LE(6);
184
- const height = buffer.readUInt16LE(8);
185
- let potentiallyAnimated = false;
186
- if (buffer.length > 13) {
187
- for (let i = 13; i < Math.min(buffer.length - 2, 100); i++) {
188
- if (buffer[i] === 33 && buffer[i + 1] === 249) {
189
- potentiallyAnimated = true;
190
- break;
191
- }
192
- }
193
- }
194
- return {
195
- width,
196
- height,
197
- colorModel: "unknown",
198
- format: "gif",
199
- frames: potentiallyAnimated ? 2 : 1,
200
- // Estimate
201
- animated: potentiallyAnimated,
202
- hasAlpha: null,
203
- orientation: null,
204
- aspectRatio: width / height,
205
- colorSpace: "unknown",
206
- iccProfile: null,
207
- exifDateTimeOriginal: null
208
- };
209
- }
210
- extractBMPFromBuffer(buffer) {
211
- if (!this.isBMP(buffer) || buffer.length < 26) {
212
- throw new Error("Invalid BMP header");
213
- }
214
- const width = buffer.readInt32LE(18);
215
- const height = Math.abs(buffer.readInt32LE(22));
216
- const bitDepth = buffer.readUInt16LE(28);
217
- const colorModel = bitDepth <= 8 ? "indexed" : "rgb";
218
- return {
219
- width,
220
- height,
221
- format: "bmp",
222
- frames: 1,
223
- animated: false,
224
- hasAlpha: null,
225
- orientation: buffer.readInt32LE(22) < 0 ? 1 : 6,
226
- aspectRatio: width / height,
227
- colorSpace: "unknown",
228
- colorModel,
229
- iccProfile: null,
230
- exifDateTimeOriginal: null
231
- };
232
- }
233
- extractWebPFromBuffer(buffer) {
234
- if (!this.isWebP(buffer) || buffer.length < 30) {
235
- throw new Error("Invalid WebP header");
236
- }
237
- const chunkType = buffer.toString("ascii", 12, 16);
238
- let width = 0;
239
- let height = 0;
240
- let hasAlpha = false;
241
- let animated = false;
242
- let colorModel = "rgb";
243
- if (chunkType === "VP8X") {
244
- const flags = buffer[20];
245
- if (flags !== void 0) {
246
- hasAlpha = !!(flags & 2);
247
- animated = !!(flags & 1);
248
- colorModel = hasAlpha ? "rgba" : "rgb";
249
- }
250
- const b24 = buffer[24], b25 = buffer[25], b26 = buffer[26];
251
- const b27 = buffer[27], b28 = buffer[28], b29 = buffer[29];
252
- if (b24 !== void 0 && b25 !== void 0 && b26 !== void 0 && b27 !== void 0 && b28 !== void 0 && b29 !== void 0) {
253
- const widthMinus1 = b24 | b25 << 8 | b26 << 16;
254
- const heightMinus1 = b27 | b28 << 8 | b29 << 16;
255
- width = widthMinus1 + 1;
256
- height = heightMinus1 + 1;
257
- }
258
- } else if (chunkType === "VP8") {
259
- if (buffer.length < 30) throw new Error("VP8 data too short");
260
- width = buffer.readUInt16LE(26) & 16383;
261
- height = buffer.readUInt16LE(28) & 16383;
262
- } else if (chunkType === "VP8L") {
263
- if (buffer.length < 25) throw new Error("VP8L data too short");
264
- const bits = buffer.readUInt32LE(21);
265
- hasAlpha = !!(bits & 1 << 8);
266
- colorModel = hasAlpha ? "rgba" : "rgb";
267
- width = 1 + (bits & 16383);
268
- height = 1 + (bits >> 14 & 16383);
269
- }
270
- return {
271
- width,
272
- colorModel,
273
- height,
274
- format: "webp",
275
- frames: animated ? 2 : 1,
276
- // Estimate
277
- animated,
278
- hasAlpha,
279
- orientation: null,
280
- aspectRatio: width / height,
281
- colorSpace: "unknown",
282
- iccProfile: null,
283
- exifDateTimeOriginal: null
284
- };
285
- }
286
- extractAVIFFromBuffer(buffer) {
287
- if (!this.isAVIF(buffer)) {
288
- throw new Error("Invalid AVIF header");
289
- }
290
- let width = 0;
291
- let height = 0;
292
- for (let i = 0; i < buffer.length - 16; i++) {
293
- if (buffer.toString("ascii", i, i + 4) === "ispe") {
294
- if (i + 12 < buffer.length) {
295
- width = buffer.readUInt32BE(i + 8);
296
- height = buffer.readUInt32BE(i + 12);
297
- break;
298
- }
299
- }
300
- }
301
- if (width === 0 || height === 0) {
302
- throw new Error("Could not find AVIF dimensions in available data");
303
- }
304
- return {
305
- width,
306
- height,
307
- format: "avif",
308
- frames: 1,
309
- animated: false,
310
- hasAlpha: null,
311
- orientation: null,
312
- aspectRatio: width / height,
313
- colorModel: "rgb",
314
- colorSpace: "unknown",
315
- iccProfile: null,
316
- exifDateTimeOriginal: null
317
- };
318
- }
319
- async extractViaStream(stream, size = 4096) {
320
- const headerSize = size;
321
- const header = await this.readBytes(stream, headerSize);
322
- return this.getImageSpecsWorkup(header, size);
323
- }
324
- async extractViaPath(filePath, size = 4096) {
325
- const stream = createReadStream(relative(this.cwd, filePath), {
326
- highWaterMark: size
327
- });
328
- return await this.extractViaStream(stream, size);
329
- }
330
- /**
331
- * Probe image from various sources
332
- * Handles local Buffer, remote URL, or S3 object
333
- */
334
- async extractRemoteFs(source, size = 16384, timeout = 5e3) {
335
- let buffer;
336
- if (Buffer.isBuffer(source)) {
337
- buffer = source;
338
- return this.getImageSpecsWorkup(buffer, size);
339
- } else {
340
- buffer = await this.fetchMinimalBufferFs(source, size, timeout);
341
- return this.getImageSpecsWorkup(buffer, size);
342
- }
343
- }
344
- /**
345
- * Fetch minimal bytes from remote URL using Range header
346
- * This is the KEY optimization - only fetch what we need!
347
- */
348
- knownToBlock(inputUrl) {
349
- if (inputUrl.startsWith("https://github.com")) {
350
- return "GET";
351
- } else if (inputUrl.startsWith("https://raw.githubusercontent.com")) {
352
- return "GET";
353
- } else {
354
- return "HEAD";
355
- }
356
- }
357
- async fetchMinimalBufferFs(url, size = 16384, timeout = 5e3) {
358
- const controller = new AbortController();
359
- const timeoutId = setTimeout(() => controller.abort(), timeout);
360
- try {
361
- const headResponse = await fetch(url, {
362
- method: this.knownToBlock(url),
363
- signal: controller.signal
364
- });
365
- const acceptsRange = headResponse.headers.get("accept-ranges") === "bytes";
366
- const contentLength = parseInt(
367
- headResponse.headers.get("content-length") ?? "0"
368
- );
369
- clearTimeout(timeoutId);
370
- if (acceptsRange) {
371
- const rangeResponse = await fetch(url, {
372
- headers: {
373
- Range: `bytes=0-${size}`
374
- // First 16KB
375
- },
376
- signal: AbortSignal.timeout(timeout)
377
- });
378
- if (rangeResponse.status === 206) {
379
- const arrayBuffer = await rangeResponse.arrayBuffer();
380
- return Buffer.from(arrayBuffer);
381
- }
382
- }
383
- if (contentLength && contentLength < 1024 * 1024) {
384
- const response2 = await fetch(url, {
385
- signal: AbortSignal.timeout(timeout)
386
- });
387
- const arrayBuffer = await response2.arrayBuffer();
388
- return Buffer.from(arrayBuffer);
389
- }
390
- const response = await fetch(url, {
391
- signal: AbortSignal.timeout(timeout)
392
- });
393
- if (!response.body) {
394
- throw new Error("No response body");
395
- }
396
- const reader = response.body.getReader();
397
- const chunks = [];
398
- let totalBytes = 0;
399
- const maxBytes = size;
400
- while (totalBytes < maxBytes) {
401
- const { done, value } = await reader.read();
402
- if (done) break;
403
- const bytesToAdd = Math.min(value.length, maxBytes - totalBytes);
404
- chunks.push(value.slice(0, bytesToAdd));
405
- totalBytes += bytesToAdd;
406
- if (totalBytes >= maxBytes) {
407
- reader.cancel();
408
- break;
409
- }
410
- }
411
- return Buffer.concat(chunks);
412
- } finally {
413
- clearTimeout(timeoutId);
414
- }
415
- }
416
- getImageSpecsWorkupFs(rawbuffer, size = 4096 * 6) {
417
- const MAX_HEADER_SIZE = size;
418
- const buffer = rawbuffer.subarray(
419
- 0,
420
- Math.min(rawbuffer.length, MAX_HEADER_SIZE)
421
- );
422
- if (buffer?.length >= 24 && buffer?.[0] === 137 && buffer?.[1] === 80 && buffer?.[2] === 78 && buffer?.[3] === 71 && buffer?.[4] === 13 && buffer?.[5] === 10 && buffer?.[6] === 26 && buffer?.[7] === 10) {
423
- if (buffer.readUInt32BE(8) !== 13 || buffer?.[12] !== 73 || buffer?.[13] !== 72 || buffer?.[14] !== 68 || buffer?.[15] !== 82) {
424
- throw new Error("IHDR Chunk of png not found or incorrect.");
425
- }
426
- const colorType = buffer[25];
427
- let colorModel = "unknown", colorSpace = "unknown", hasAlpha = false;
428
- switch (colorType) {
429
- case 0:
430
- colorModel = "grayscale";
431
- colorSpace = "gray";
432
- break;
433
- case 2:
434
- colorModel = "rgb";
435
- colorSpace = "srgb";
436
- break;
437
- case 3:
438
- colorModel = "indexed";
439
- colorSpace = "srgb";
440
- break;
441
- case 4:
442
- colorModel = "grayscale-alpha";
443
- colorSpace = "gray";
444
- hasAlpha = true;
445
- break;
446
- case 6:
447
- colorModel = "rgba";
448
- colorSpace = "srgb";
449
- hasAlpha = true;
450
- break;
451
- default:
452
- colorModel = "unknown";
453
- }
454
- const width = buffer.readUInt32BE(16);
455
- const height = buffer.readUInt32BE(20);
456
- let frames = 1;
457
- let animated = false;
458
- let iccProfile = null;
459
- let exifDateTimeOriginal = null;
460
- const orientation = null;
461
- let pos = 33;
462
- while (pos < buffer.length - 12) {
463
- const chunkLen = buffer.readUInt32BE(pos);
464
- const chunkType = buffer.toString("ascii", pos + 4, pos + 8);
465
- const chunkData = pos + 8;
466
- if (chunkType === "acTL") {
467
- animated = true;
468
- frames = buffer.readUInt32BE(chunkData);
469
- } else if (chunkType === "iCCP") {
470
- const nameEnd = buffer.indexOf(0, chunkData);
471
- const profileName = buffer.toString("ascii", chunkData, nameEnd);
472
- iccProfile = profileName || "embedded";
473
- colorSpace = this.mapProfileToColorSpace(profileName, colorSpace);
474
- } else if (chunkType === "sRGB") {
475
- if (iccProfile === null) {
476
- iccProfile = "sRGB";
477
- colorSpace = "srgb";
478
- }
479
- } else if (chunkType === "cHRM") {
480
- if (iccProfile === null && colorModel !== "grayscale" && colorModel !== "grayscale-alpha") {
481
- const white_x = buffer.readUInt32BE(chunkData), white_y = buffer.readUInt32BE(chunkData + 4), red_x = buffer.readUInt32BE(chunkData + 8), red_y = buffer.readUInt32BE(chunkData + 12), green_x = buffer.readUInt32BE(chunkData + 16), green_y = buffer.readUInt32BE(chunkData + 20), blue_x = buffer.readUInt32BE(chunkData + 24), blue_y = buffer.readUInt32BE(chunkData + 28);
482
- colorSpace = this.mapChrmToColorSpace(
483
- {
484
- white_x,
485
- white_y,
486
- red_x,
487
- red_y,
488
- green_x,
489
- green_y,
490
- blue_x,
491
- blue_y
492
- },
493
- colorSpace
494
- );
495
- }
496
- } else if (chunkType === "iTXt") {
497
- let offset = chunkData;
498
- const keywordEnd = buffer.indexOf(0, offset);
499
- const keyword = buffer.toString("ascii", offset, keywordEnd);
500
- offset = keywordEnd + 1;
501
- const compressionFlag = buffer[offset];
502
- const _compressionMethod = buffer[offset + 1];
503
- offset += 2;
504
- const langEnd = buffer.indexOf(0, offset);
505
- offset = langEnd + 1;
506
- const transEnd = buffer.indexOf(0, offset);
507
- offset = transEnd + 1;
508
- let textBuffer = buffer.subarray(offset, chunkData + chunkLen - 8);
509
- if (compressionFlag === 1) {
510
- try {
511
- textBuffer = Buffer.from(inflateSync(textBuffer));
512
- } catch (e) {
513
- console.error("Failed to decompress iTXt:", e);
514
- }
515
- }
516
- const text = textBuffer.toString("utf8");
517
- if (keyword === "XML:com.adobe.xmp" && !iccProfile) {
518
- colorSpace = this.mapXmpToColorSpace(text, colorSpace);
519
- }
520
- } else if (chunkType === "tIME") {
521
- const month = buffer?.[chunkData + 2], day = buffer?.[chunkData + 3], hour = buffer?.[chunkData + 4], minute = buffer?.[chunkData + 5], second = buffer?.[chunkData + 6];
522
- if (typeof month !== "undefined" && typeof day !== "undefined" && typeof hour !== "undefined" && typeof minute !== "undefined" && typeof second !== "undefined") {
523
- const year = buffer.readUInt16BE(chunkData);
524
- exifDateTimeOriginal = `${year}:${month.toString().padStart(2, "0")}:${day.toString().padStart(2, "0")} ${hour.toString().padStart(2, "0")}:${minute.toString().padStart(2, "0")}:${second.toString().padStart(2, "0")}`;
525
- }
526
- } else if (chunkType === "IDAT") {
527
- break;
528
- }
529
- pos += 12 + chunkLen;
530
- }
531
- return {
532
- width,
533
- height,
534
- format: animated === true ? "apng" : "png",
535
- frames,
536
- animated,
537
- hasAlpha,
538
- colorModel,
539
- orientation,
540
- aspectRatio: width / height,
541
- colorSpace,
542
- iccProfile,
543
- exifDateTimeOriginal
544
- };
545
- }
546
- if (buffer.length >= 10 && buffer[0] === 255 && buffer[1] === 216) {
547
- const colorSpace = "unknown", hasAlpha = false;
548
- let pos = 2, colorModel = "unknown", width = 0, height = 0, iccProfile = null, orientation = null, exifDateTimeOriginal = null;
549
- while (pos < buffer.length - 10) {
550
- if (buffer[pos] !== 255) {
551
- const nextFF = buffer.indexOf(255, pos + 1);
552
- if (nextFF === -1 || nextFF >= buffer.length - 4) break;
553
- pos = nextFF;
554
- continue;
555
- }
556
- const marker = buffer[pos + 1];
557
- if (marker === 218) break;
558
- if (pos + 4 > buffer.length) break;
559
- const segmentSize = buffer.readUInt16BE(pos + 2);
560
- if (segmentSize < 2) {
561
- pos += 2;
562
- continue;
563
- }
564
- const segmentEnd = pos + 2 + segmentSize;
565
- if (segmentEnd > buffer.length) {
566
- if (marker && marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204) {
567
- if (pos + 9 <= buffer.length) {
568
- const numComponents = buffer[pos + 4];
569
- switch (numComponents) {
570
- case 1:
571
- colorModel = "grayscale";
572
- break;
573
- case 3:
574
- colorModel = "ycbcr";
575
- break;
576
- case 4:
577
- colorModel = "ycck";
578
- break;
579
- default:
580
- colorModel = "unknown";
581
- }
582
- if (pos + 7 <= buffer.length - 2) {
583
- width = buffer.readUInt16BE(pos + 7);
584
- }
585
- if (pos + 5 <= buffer.length - 2) {
586
- height = buffer.readUInt16BE(pos + 5);
587
- }
588
- }
589
- }
590
- break;
591
- }
592
- if (marker && marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204) {
593
- const numComponents = buffer[pos + 4];
594
- switch (numComponents) {
595
- case 1:
596
- colorModel = "grayscale";
597
- break;
598
- case 3:
599
- colorModel = "ycbcr";
600
- break;
601
- // Most common for RGB JPEGs (stored as YCbCr)
602
- case 4:
603
- colorModel = "ycck";
604
- break;
605
- // YCCK for CMYK with alpha-like, but no true alpha
606
- default:
607
- colorModel = "unknown";
608
- }
609
- width = buffer.readUInt16BE(pos + 7);
610
- height = buffer.readUInt16BE(pos + 5);
611
- } else if (marker === 225) {
612
- const { orientation: ori, dateTimeOriginal } = this.parseExif(
613
- buffer,
614
- pos,
615
- segmentSize
616
- );
617
- orientation = ori;
618
- exifDateTimeOriginal = dateTimeOriginal;
619
- } else if (marker === 226) {
620
- if (pos + 18 <= buffer.length) {
621
- const iccHeader = buffer.toString("ascii", pos + 4, pos + 18);
622
- if (iccHeader.startsWith("ICC_PROFILE")) {
623
- iccProfile = "embedded";
624
- }
625
- }
626
- } else if (marker === 255) {
627
- pos++;
628
- continue;
629
- }
630
- pos = segmentEnd;
631
- while (pos < buffer.length && buffer[pos] === 0) {
632
- pos++;
633
- }
634
- while (pos < buffer.length - 1 && buffer[pos] === 255 && buffer[pos + 1] === 255) {
635
- pos++;
636
- }
637
- }
638
- if (width === 0) throw new Error("No dimensions found in JPEG file");
639
- return {
640
- width,
641
- height,
642
- format: "jpeg",
643
- frames: 1,
644
- animated: false,
645
- // JPEG not animated
646
- hasAlpha,
647
- orientation,
648
- aspectRatio: width / height,
649
- colorSpace,
650
- colorModel,
651
- iccProfile,
652
- exifDateTimeOriginal
653
- };
654
- }
655
- const gifHeader = buffer.toString("ascii", 0, 6);
656
- if (buffer.length >= 10 && (gifHeader === "GIF87a" || gifHeader === "GIF89a")) {
657
- const width = buffer.readUInt16LE(6), height = buffer.readUInt16LE(8);
658
- let frames = 0;
659
- let pos = 13;
660
- const bufTen = buffer?.[10];
661
- if (typeof bufTen === "undefined") {
662
- pos = 13;
663
- frames = 0;
664
- } else if (bufTen & 128) pos += 3 << (bufTen & 7) + 1;
665
- while (pos < buffer.length) {
666
- if (buffer[pos] === 33) {
667
- pos += 2;
668
- let subSize = buffer?.[pos];
669
- while (subSize && subSize > 0) {
670
- pos += subSize + 1;
671
- subSize = buffer?.[pos];
672
- }
673
- pos++;
674
- } else if (buffer?.[pos] && buffer?.[pos] === 44) {
675
- frames++;
676
- pos += 10;
677
- const b = buffer?.[pos - 1];
678
- if (typeof b !== "undefined" && b & 128)
679
- pos += 3 << (b & 7) + 1;
680
- pos++;
681
- let dataSize = buffer?.[pos];
682
- while (dataSize && dataSize > 0) {
683
- pos += dataSize + 1;
684
- dataSize = buffer[pos];
685
- }
686
- pos++;
687
- } else if (buffer[pos] === 59) {
688
- break;
689
- } else {
690
- pos++;
691
- }
692
- }
693
- return {
694
- width,
695
- height,
696
- format: "gif",
697
- frames,
698
- animated: frames > 1,
699
- hasAlpha: null,
700
- // GIF transparency is per-pixel binary, not full alpha; set null or true if transparent color exists, but complex
701
- orientation: null,
702
- // No orientation in GIF
703
- aspectRatio: width / height,
704
- colorModel: "indexed",
705
- colorSpace: "unknown",
706
- iccProfile: null,
707
- // No ICC in GIF
708
- exifDateTimeOriginal: null
709
- // No EXIF in GIF
710
- };
711
- }
712
- if (buffer.length >= 26 && buffer?.[0] === 66 && buffer?.[1] === 77) {
713
- const width = buffer.readInt32LE(18);
714
- const height = Math.abs(buffer.readInt32LE(22));
715
- const bitDepth = buffer.readUInt16LE(28);
716
- const colorModel = bitDepth <= 8 ? "indexed" : "rgb";
717
- return {
718
- width,
719
- height,
720
- format: "bmp",
721
- frames: 1,
722
- animated: false,
723
- hasAlpha: null,
724
- // Some BMP have alpha in 32bpp, check if bitDepth===32 && compression===3 (bitfields with alpha)
725
- orientation: buffer.readInt32LE(22) < 0 ? 1 : 6,
726
- // Negative height means top-down (orientation 1), positive bottom-up (like 6, but simplified)
727
- aspectRatio: width / height,
728
- colorModel,
729
- colorSpace: "unknown",
730
- iccProfile: null,
731
- // Rare in BMP
732
- exifDateTimeOriginal: null
733
- };
734
- }
735
- if (buffer.length >= 30 && buffer.toString("ascii", 0, 4) === "RIFF" && buffer.toString("ascii", 8, 12) === "WEBP") {
736
- const chunkType = buffer.toString("ascii", 12, 16);
737
- const colorSpace = "unknown";
738
- let colorModel = "unknown", hasAlpha = false, width = 0, height = 0, frames = 1, animated = false, iccProfile = null;
739
- if (chunkType === "VP8X") {
740
- const flags = buffer?.[20];
741
- colorModel = flags ? flags & 2 ? "rgba" : "rgb" : "unknown";
742
- hasAlpha = flags ? !!(flags & 2) : false;
743
- animated = flags ? !!(flags & 1) : false;
744
- let widthSubtractOne = 0;
745
- let heightSubtractOne = 0;
746
- if (buffer?.[24] && buffer?.[25] && buffer?.[26]) {
747
- widthSubtractOne = buffer[24] | buffer[25] << 8 | buffer[26] << 16;
748
- }
749
- if (buffer?.[27] && buffer?.[28] && buffer?.[29]) {
750
- heightSubtractOne = buffer[27] | buffer[28] << 8 | buffer[29] << 16;
751
- }
752
- width = widthSubtractOne + 1;
753
- height = heightSubtractOne + 1;
754
- if (animated) {
755
- let pos = 30;
756
- frames = 0;
757
- while (pos < buffer.length - 8) {
758
- const subChunkType = buffer.toString("ascii", pos, pos + 4);
759
- const subChunkSize = buffer.readUInt32LE(pos + 4);
760
- if (subChunkType === "ICCP") {
761
- iccProfile = "embedded";
762
- } else if (subChunkType === "ANMF") {
763
- frames++;
764
- }
765
- pos += 8 + subChunkSize + subChunkSize % 2;
766
- }
767
- }
768
- } else if (chunkType === "VP8 ") {
769
- colorModel = "rgb";
770
- hasAlpha = false;
771
- const dataStart = 20;
772
- if (buffer?.[dataStart + 3] !== 157 || buffer?.[dataStart + 4] !== 1 || buffer?.[dataStart + 5] !== 42) {
773
- throw new Error("Invalid VP8 keyframe");
774
- }
775
- width = buffer.readUInt16LE(dataStart + 6) & 16383;
776
- height = buffer.readUInt16LE(dataStart + 8) & 16383;
777
- } else if (chunkType === "VP8L") {
778
- const dataStart = 20;
779
- if (buffer?.[dataStart] !== 47) {
780
- throw new Error("Invalid VP8L signature");
781
- }
782
- const bits = buffer.readUInt32LE(dataStart + 1);
783
- if (bits >>> 29 !== 0) {
784
- throw new Error("Invalid VP8L version");
785
- }
786
- colorModel = bits & 1 << 8 ? "rgba" : "rgb";
787
- hasAlpha = !!(bits & 1 << 8);
788
- width = 1 + (bits & 16383);
789
- height = 1 + (bits >> 14 & 16383);
790
- } else {
791
- throw new Error("Unsupported WebP chunk");
792
- }
793
- return {
794
- width,
795
- height,
796
- format: "webp",
797
- frames,
798
- animated,
799
- hasAlpha,
800
- colorModel,
801
- orientation: null,
802
- // No standard orientation in WebP
803
- aspectRatio: width / height,
804
- colorSpace,
805
- iccProfile,
806
- exifDateTimeOriginal: null
807
- // Can have EXIF chunk, but rare; add if needed
808
- };
809
- }
810
- if (buffer.length >= 32 && buffer.toString("ascii", 4, 8) === "ftyp") {
811
- const ftyp = this.findBox(buffer, "ftyp");
812
- if (!ftyp) throw new Error("Invalid AVIF: No ftyp");
813
- const brands = buffer.toString("ascii", ftyp.pos, ftyp.pos + ftyp.size);
814
- const isAvif = brands.includes("avif");
815
- const isAvis = brands.includes("avis");
816
- if (!isAvif && !isAvis) throw new Error("Not an AVIF file");
817
- const meta = this.findBox(buffer, "meta");
818
- if (!meta) throw new Error("Invalid AVIF: No meta");
819
- const metaSubStart = meta.pos + 4;
820
- const metaSubEnd = meta.pos + meta.size;
821
- const iprp = this.findBox(buffer, "iprp", metaSubStart, metaSubEnd);
822
- if (!iprp) throw new Error("Invalid AVIF: No iprp");
823
- const ipco = this.findBox(buffer, "ipco", iprp.pos, iprp.pos + iprp.size);
824
- if (!ipco) throw new Error("Invalid AVIF: No ipco");
825
- const ispe = this.findBox(buffer, "ispe", ipco.pos, ipco.pos + ipco.size);
826
- if (!ispe) throw new Error("Invalid AVIF: No ispe");
827
- if (buffer[ispe.pos] !== 0) throw new Error("Invalid ispe version");
828
- const width = buffer.readUInt32BE(ispe.pos + 4);
829
- const height = buffer.readUInt32BE(ispe.pos + 8);
830
- let colorSpace = "rgb", colorModel = "rgb", hasAlpha = false, iccProfile = null;
831
- const colr = this.findBox(buffer, "colr", ipco.pos, ipco.pos + ipco.size);
832
- if (colr) {
833
- const colrType = buffer.toString("ascii", colr.pos, colr.pos + 4);
834
- if (colrType === "nclx") {
835
- const matrix = buffer.readUInt16BE(colr.pos + 6);
836
- colorModel = matrix === 2 ? "rgb" : "ycbcr";
837
- } else if (colrType === "rICC" || colrType === "prof") {
838
- colorSpace = "unknown";
839
- iccProfile = "embedded";
840
- }
841
- }
842
- const auxC = this.findBox(buffer, "auxC", ipco.pos, ipco.pos + ipco.size);
843
- if (auxC && buffer.toString("ascii", auxC.pos, auxC.pos + auxC.size).includes("alpha")) {
844
- hasAlpha = true;
845
- if (colorModel === "rgb") {
846
- colorModel = "rgba";
847
- } else if (colorModel === "ycbcr") {
848
- colorModel = "ycck";
849
- } else if (colorModel === "grayscale" || colorModel === "unknown") {
850
- colorModel = "grayscale-alpha";
851
- }
852
- }
853
- const xmpXml = this.parseXmpFromAvif(buffer, meta, ipco);
854
- let exifDateTimeOriginal = null;
855
- if (xmpXml) {
856
- let dateStart = xmpXml.indexOf('xmp:CreateDate="');
857
- if (dateStart === -1)
858
- dateStart = xmpXml.indexOf('photoshop:DateCreated="');
859
- if (dateStart !== -1) {
860
- dateStart += 16;
861
- const dateEnd = xmpXml.indexOf('"', dateStart);
862
- if (dateEnd !== -1) {
863
- exifDateTimeOriginal = xmpXml.substring(dateStart, dateEnd);
864
- }
865
- }
866
- }
867
- let frames = 1;
868
- const animated = isAvis;
869
- if (animated) {
870
- const iloc = this.findBox(buffer, "iloc", metaSubStart, metaSubEnd);
871
- if (iloc) {
872
- const version = buffer?.[iloc.pos] ?? 0;
873
- const itemCountPos = iloc.pos + (version < 2 ? 4 : 6);
874
- let itemCount = buffer?.readUInt16BE(itemCountPos) ?? 0;
875
- if (version >= 2) itemCount = buffer?.readUInt32BE(itemCountPos) ?? 0;
876
- frames = Math.max(1, Math.floor(itemCount / (hasAlpha ? 2 : 1)));
877
- }
878
- }
879
- return {
880
- width,
881
- height,
882
- format: "avif",
883
- frames,
884
- animated,
885
- colorModel,
886
- hasAlpha: hasAlpha ? true : null,
887
- orientation: null,
888
- // Can have 'irot' or 'imir' transforms, but rare
889
- aspectRatio: width / height,
890
- colorSpace,
891
- iccProfile,
892
- exifDateTimeOriginal
893
- // Can have 'XMP' box, but parse XMP for date if needed
894
- };
895
- }
896
- if (buffer.length >= 32 && buffer.toString("ascii", 4, 8) === "ftyp") {
897
- const ftyp = this.findBox(buffer, "ftyp");
898
- if (!ftyp) throw new Error("Invalid HEIC: No ftyp");
899
- const brands = buffer.toString("ascii", ftyp.pos, ftyp.pos + ftyp.size).toLowerCase();
900
- const isHeic = brands.includes("heic") || brands.includes("heix") || brands.includes("heim") || brands.includes("heis") || brands.includes("hevc") || brands.includes("hevx") || brands.includes("mif1");
901
- if (!isHeic) throw new Error("Not a HEIC file");
902
- const meta = this.findBox(buffer, "meta");
903
- if (!meta) throw new Error("Invalid HEIC: No meta");
904
- const metaSubStart = meta.pos + 4;
905
- const metaSubEnd = meta.pos + meta.size;
906
- const iprp = this.findBox(buffer, "iprp", metaSubStart, metaSubEnd);
907
- if (!iprp) throw new Error("Invalid HEIC: No iprp");
908
- const ipco = this.findBox(buffer, "ipco", iprp.pos, iprp.pos + iprp.size);
909
- if (!ipco) throw new Error("Invalid HEIC: No ipco");
910
- const ispe = this.findBox(buffer, "ispe", ipco.pos, ipco.pos + ipco.size);
911
- if (!ispe) throw new Error("Invalid HEIC: No ispe");
912
- if (buffer[ispe.pos] !== 0) throw new Error("Invalid ispe version");
913
- const width = buffer.readUInt32BE(ispe.pos + 4);
914
- const height = buffer.readUInt32BE(ispe.pos + 8);
915
- let colorSpace = "rgb", colorModel = "rgb", hasAlpha = false, iccProfile = null;
916
- const colr = this.findBox(buffer, "colr", ipco.pos, ipco.pos + ipco.size);
917
- if (colr) {
918
- const colrType = buffer.toString("ascii", colr.pos, colr.pos + 4);
919
- if (colrType === "nclx") {
920
- const matrix = buffer.readUInt16BE(colr.pos + 6);
921
- colorModel = matrix === 2 ? "rgb" : "ycbcr";
922
- } else if (colrType === "rICC" || colrType === "prof") {
923
- colorSpace = "unknown";
924
- iccProfile = "embedded";
925
- }
926
- }
927
- const auxC = this.findBox(buffer, "auxC", ipco.pos, ipco.pos + ipco.size);
928
- if (auxC && buffer.toString("ascii", auxC.pos, auxC.pos + auxC.size).includes("alpha")) {
929
- hasAlpha = true;
930
- if (colorModel === "rgb") {
931
- colorModel = "rgba";
932
- } else if (colorModel === "ycbcr") {
933
- colorModel = "ycck";
934
- } else if (colorModel === "grayscale" || colorModel === "unknown") {
935
- colorModel = "grayscale-alpha";
936
- }
937
- }
938
- const xmpXml = this.parseXmpFromAvif(buffer, meta, ipco);
939
- let exifDateTimeOriginal = null;
940
- if (xmpXml) {
941
- let dateStart = xmpXml.indexOf('xmp:CreateDate="');
942
- if (dateStart === -1)
943
- dateStart = xmpXml.indexOf('photoshop:DateCreated="');
944
- if (dateStart !== -1) {
945
- dateStart += 16;
946
- const dateEnd = xmpXml.indexOf('"', dateStart);
947
- if (dateEnd !== -1) {
948
- exifDateTimeOriginal = xmpXml.substring(dateStart, dateEnd);
949
- }
950
- }
951
- }
952
- let frames = 1;
953
- const animated = brands.includes("heim") || brands.includes("heis");
954
- if (animated) {
955
- const iloc = this.findBox(buffer, "iloc", metaSubStart, metaSubEnd);
956
- if (iloc) {
957
- const version = buffer?.[iloc.pos] ?? 0;
958
- const itemCountPos = iloc.pos + (version < 2 ? 4 : 6);
959
- let itemCount = buffer?.readUInt16BE(itemCountPos) ?? 0;
960
- if (version >= 2) itemCount = buffer?.readUInt32BE(itemCountPos) ?? 0;
961
- frames = Math.max(1, Math.floor(itemCount / (hasAlpha ? 2 : 1)));
962
- }
963
- }
964
- return {
965
- width,
966
- height,
967
- format: "heic",
968
- frames,
969
- animated,
970
- colorModel,
971
- hasAlpha: hasAlpha ? true : null,
972
- orientation: null,
973
- // Can have 'irot' or 'imir' transforms, or EXIF; add parsing if needed
974
- aspectRatio: width / height,
975
- colorSpace,
976
- iccProfile,
977
- exifDateTimeOriginal
978
- // Can have dedicated 'Exif' item; add parser similar to XMP if required
979
- };
980
- }
981
- const headerText = buffer.toString("utf-8", 0, Math.min(1024, buffer.length)).trim();
982
- if (headerText.startsWith("<svg") || headerText.startsWith("<?xml") && headerText.includes("<svg")) {
983
- const widthMatch = headerText.match(
984
- /width\s*=\s*["']?(\d+(?:\.\d+)?)(?:px)?["']?/i
985
- );
986
- const heightMatch = headerText.match(
987
- /height\s*=\s*["']?(\d+(?:\.\d+)?)(?:px)?["']?/i
988
- );
989
- const viewBoxMatch = headerText.match(
990
- /viewBox\s*=\s*["']?(\d+(?:\.\d+)?\s+\d+(?:\.\d+)?\s+\d+(?:\.\d+)?\s+\d+(?:\.\d+)?)["']?/i
991
- );
992
- let width = 0;
993
- let height = 0;
994
- if (widthMatch?.[1] && heightMatch?.[1]) {
995
- width = parseFloat(widthMatch[1]);
996
- height = parseFloat(heightMatch[1]);
997
- } else if (viewBoxMatch) {
998
- const [_x0, _y0, vbWidth, vbHeight] = viewBoxMatch?.[1]?.split(/\s+/).map((t) => Number.parseFloat(t));
999
- width = vbWidth;
1000
- height = vbHeight;
1001
- } else {
1002
- width = 0;
1003
- height = 0;
1004
- throw new Error("SVG has no defined width/height or viewBox");
1005
- }
1006
- const animated = headerText.includes("<animate") || headerText.includes("<animation") || headerText.includes("<motion.");
1007
- const frames = 1;
1008
- return {
1009
- width,
1010
- height,
1011
- format: "svg",
1012
- frames,
1013
- animated,
1014
- hasAlpha: true,
1015
- // SVG supports transparency
1016
- orientation: null,
1017
- aspectRatio: width / height || 1,
1018
- // Fallback if 0
1019
- colorModel: "vector",
1020
- colorSpace: "srgb",
1021
- // Typically sRGB for web SVGs
1022
- iccProfile: null,
1023
- // Rare, but can embed ICC in <color-profile>
1024
- exifDateTimeOriginal: null
1025
- // No standard EXIF
1026
- };
1027
- }
1028
- if (buffer.length >= 6 && buffer[0] === 0 && buffer[1] === 0 && buffer[2] === 1 && buffer[3] === 0) {
1029
- const frames = buffer.readUInt16LE(4);
1030
- if (frames === 0) throw new Error("Invalid ICO: No images");
1031
- let maxWidth = 0;
1032
- let maxHeight = 0;
1033
- let hasAlpha = null;
1034
- let colorModel = "unknown";
1035
- for (let i = 0; i < frames; i++) {
1036
- const entryPos = 6 + i * 16;
1037
- if (entryPos + 16 > buffer.length) break;
1038
- let entryWidth = buffer[entryPos];
1039
- let entryHeight = buffer[entryPos + 1];
1040
- entryWidth = entryWidth === 0 ? 256 : entryWidth;
1041
- entryHeight = entryHeight === 0 ? 256 : entryHeight;
1042
- const bpp = buffer.readUInt16LE(entryPos + 6);
1043
- const _size = buffer.readUInt32LE(entryPos + 8);
1044
- const offset = buffer.readUInt32LE(entryPos + 12);
1045
- if (bpp <= 8) colorModel = "indexed";
1046
- else if (bpp === 24) colorModel = "rgb";
1047
- else if (bpp === 32) {
1048
- colorModel = "rgba";
1049
- hasAlpha = true;
1050
- }
1051
- if (offset + 8 <= rawbuffer.length && // Use full buffer for data
1052
- rawbuffer[offset] === 137 && rawbuffer[offset + 1] === 80 && rawbuffer[offset + 2] === 78 && rawbuffer[offset + 3] === 71 && rawbuffer[offset + 4] === 13 && rawbuffer[offset + 5] === 10 && rawbuffer[offset + 6] === 26 && rawbuffer[offset + 7] === 10) {
1053
- hasAlpha = true;
1054
- colorModel = "rgba";
1055
- }
1056
- if (entryWidth && entryWidth > maxWidth) maxWidth = entryWidth;
1057
- if (entryHeight && entryHeight > maxHeight) maxHeight = entryHeight;
1058
- }
1059
- return {
1060
- width: maxWidth,
1061
- height: maxHeight,
1062
- format: "ico",
1063
- frames,
1064
- animated: false,
1065
- // ICO not animated
1066
- hasAlpha,
1067
- orientation: null,
1068
- aspectRatio: maxWidth / maxHeight,
1069
- colorModel,
1070
- colorSpace: "srgb",
1071
- // Typically
1072
- iccProfile: null,
1073
- exifDateTimeOriginal: null
1074
- };
1075
- }
1076
- if (buffer.length >= 8 && // "II*\0" (little-endian classic TIFF)
1077
- (buffer[0] === 73 && buffer[1] === 73 && buffer[2] === 42 && buffer[3] === 0 || // "MM\0*" (big-endian classic TIFF)
1078
- buffer[0] === 77 && buffer[1] === 77 && buffer[2] === 0 && buffer[3] === 42 || // BigTIFF magic "II+\0" or "MM\0+"
1079
- buffer[0] === 73 && buffer[1] === 73 && buffer[2] === 43 && buffer[3] === 0 || buffer[0] === 77 && buffer[1] === 77 && buffer[2] === 0 && buffer[3] === 43)) {
1080
- let readIFDValue2 = function(entryOff, type, count) {
1081
- const valueOrOff = readU32(entryOff + 8);
1082
- const valueFitsInline = (type === TYPE.BYTE || type === TYPE.SBYTE || type === TYPE.UNDEFINED || type === TYPE.ASCII) && count <= 4 || type === TYPE.SHORT && count <= 2 || type === TYPE.LONG && count <= 1;
1083
- let dataOff = valueOrOff;
1084
- if (valueFitsInline) {
1085
- dataOff = entryOff + 8;
1086
- } else {
1087
- dataOff = TIFF_START + valueOrOff;
1088
- }
1089
- if (dataOff < 0 || dataOff >= src.length) return null;
1090
- const readShortN = /* @__PURE__ */ __name((o) => readU16(o), "readShortN");
1091
- const readLongN = /* @__PURE__ */ __name((o) => readU32(o), "readLongN");
1092
- switch (type) {
1093
- case TYPE.ASCII: {
1094
- const end = Math.min(
1095
- src.indexOf(0, dataOff) === -1 ? dataOff + count : src.indexOf(0, dataOff),
1096
- src.length
1097
- );
1098
- try {
1099
- return src.toString("ascii", dataOff, end);
1100
- } catch {
1101
- return null;
1102
- }
1103
- }
1104
- case TYPE.BYTE:
1105
- case TYPE.SBYTE:
1106
- case TYPE.UNDEFINED: {
1107
- const out = [];
1108
- for (let i = 0; i < count; i++) {
1109
- const off = dataOff + i;
1110
- if (off >= src.length || !src[off]) break;
1111
- out.push(src[off]);
1112
- }
1113
- return count === 1 ? out[0] ?? null : out;
1114
- }
1115
- case TYPE.SHORT: {
1116
- const out = [];
1117
- for (let i = 0; i < count; i++) {
1118
- const off = dataOff + i * 2;
1119
- if (off + 2 > src.length) break;
1120
- out.push(readShortN(off));
1121
- }
1122
- return count === 1 ? out[0] ?? null : out;
1123
- }
1124
- case TYPE.LONG: {
1125
- const out = [];
1126
- for (let i = 0; i < count; i++) {
1127
- const off = dataOff + i * 4;
1128
- if (off + 4 > src.length) break;
1129
- out.push(readLongN(off));
1130
- }
1131
- return count === 1 ? out[0] ?? null : out;
1132
- }
1133
- case TYPE.RATIONAL: {
1134
- const out = [];
1135
- for (let i = 0; i < count; i++) {
1136
- const off = dataOff + i * 8;
1137
- if (off + 8 > src.length) break;
1138
- const num = readLongN(off);
1139
- const den = readLongN(off + 4);
1140
- out.push(den ? num / den : 0);
1141
- }
1142
- return count === 1 ? out[0] ?? null : out;
1143
- }
1144
- default:
1145
- return null;
1146
- }
1147
- };
1148
- var readIFDValue = readIFDValue2;
1149
- __name(readIFDValue2, "readIFDValue");
1150
- const little = buffer[0] === 73;
1151
- const isBigTiff = buffer[2] === 43 || buffer[3] === 43;
1152
- if (isBigTiff) {
1153
- throw new Error(
1154
- "BigTIFF (0x2B) detected \u2014 not supported in lightweight header parser."
1155
- );
1156
- }
1157
- const src = rawbuffer;
1158
- const readU16 = /* @__PURE__ */ __name((off) => little ? src.readUInt16LE(off) : src.readUInt16BE(off), "readU16");
1159
- const readU32 = /* @__PURE__ */ __name((off) => little ? src.readUInt32LE(off) : src.readUInt32BE(off), "readU32");
1160
- const TIFF_START = 0;
1161
- const firstIFDOff = readU32(4);
1162
- let ifdOff = TIFF_START + firstIFDOff;
1163
- let frames = 0;
1164
- let width = null;
1165
- let height = null;
1166
- let samplesPerPixel = null;
1167
- let extraSamples = [];
1168
- let photometric = null;
1169
- let orientation = null;
1170
- let iccPresent = false;
1171
- let exifIFDOffset = null;
1172
- const TAG = {
1173
- ImageWidth: 256,
1174
- ImageLength: 257,
1175
- BitsPerSample: 258,
1176
- // not strictly needed here
1177
- Compression: 259,
1178
- // not strictly needed here
1179
- PhotometricInterpretation: 262,
1180
- StripOffsets: 273,
1181
- // not needed for metadata
1182
- Orientation: 274,
1183
- SamplesPerPixel: 277,
1184
- RowsPerStrip: 278,
1185
- // not needed for metadata
1186
- PlanarConfiguration: 284,
1187
- // not needed for metadata
1188
- ExtraSamples: 338,
1189
- ICCProfile: 34675,
1190
- ExifIFDPointer: 34665,
1191
- // EXIF IFD:
1192
- DateTimeOriginal: 36867
1193
- };
1194
- const TYPE = {
1195
- BYTE: 1,
1196
- ASCII: 2,
1197
- SHORT: 3,
1198
- LONG: 4,
1199
- RATIONAL: 5,
1200
- SBYTE: 6,
1201
- UNDEFINED: 7,
1202
- SSHORT: 8,
1203
- SLONG: 9,
1204
- SRATIONAL: 10,
1205
- FLOAT: 11,
1206
- DOUBLE: 12
1207
- };
1208
- const MAX_IFDS = 32;
1209
- while (ifdOff > 0 && ifdOff + 2 <= src.length && frames < MAX_IFDS) {
1210
- const numEntries = readU16(ifdOff);
1211
- const entriesBase = ifdOff + 2;
1212
- for (let i = 0; i < numEntries; i++) {
1213
- const entry = entriesBase + i * 12;
1214
- if (entry + 12 > src.length) break;
1215
- const tag = readU16(entry);
1216
- const type = readU16(entry + 2);
1217
- const count = readU32(entry + 4);
1218
- if (tag === TAG.ImageWidth && width == null) {
1219
- const v = readIFDValue2(entry, type, count);
1220
- if (typeof v === "number") width = v;
1221
- if (Array.isArray(v) && typeof v[0] === "number") width = v[0];
1222
- } else if (tag === TAG.ImageLength && height == null) {
1223
- const v = readIFDValue2(entry, type, count);
1224
- if (typeof v === "number") height = v;
1225
- if (Array.isArray(v) && typeof v[0] === "number") height = v[0];
1226
- } else if (tag === TAG.SamplesPerPixel && samplesPerPixel == null) {
1227
- const v = readIFDValue2(entry, type, count);
1228
- if (typeof v === "number") samplesPerPixel = v;
1229
- } else if (tag === TAG.ExtraSamples) {
1230
- const v = readIFDValue2(entry, type, count);
1231
- if (typeof v === "number") extraSamples = [v];
1232
- else if (Array.isArray(v))
1233
- extraSamples = v.filter((n) => typeof n === "number");
1234
- } else if (tag === TAG.PhotometricInterpretation && photometric == null) {
1235
- const v = readIFDValue2(entry, type, count);
1236
- if (typeof v === "number") photometric = v;
1237
- } else if (tag === TAG.Orientation && orientation == null) {
1238
- const v = readIFDValue2(entry, type, count);
1239
- if (typeof v === "number") orientation = v;
1240
- } else if (tag === TAG.ICCProfile) {
1241
- iccPresent = true;
1242
- } else if (tag === TAG.ExifIFDPointer && exifIFDOffset == null) {
1243
- const v = readIFDValue2(entry, type, count);
1244
- if (typeof v === "number") exifIFDOffset = TIFF_START + v;
1245
- }
1246
- }
1247
- frames++;
1248
- const nextPtrOff = entriesBase + numEntries * 12;
1249
- if (nextPtrOff + 4 > src.length) break;
1250
- const nextRel = readU32(nextPtrOff);
1251
- ifdOff = nextRel ? TIFF_START + nextRel : 0;
1252
- }
1253
- let exifDateTimeOriginal = null;
1254
- if (exifIFDOffset && exifIFDOffset + 2 <= src.length) {
1255
- try {
1256
- const num = readU16(exifIFDOffset);
1257
- const base = exifIFDOffset + 2;
1258
- for (let i = 0; i < num; i++) {
1259
- const entry = base + i * 12;
1260
- if (entry + 12 > src.length) break;
1261
- const tag = readU16(entry);
1262
- if (tag === TAG.DateTimeOriginal) {
1263
- const type = readU16(entry + 2);
1264
- const count = readU32(entry + 4);
1265
- const val = readIFDValue2(entry, type, count);
1266
- if (typeof val === "string" && /^\d{4}:\d{2}:\d{2} \d{2}:\d{2}:\d{2}/.test(val)) {
1267
- exifDateTimeOriginal = val;
1268
- }
1269
- break;
1270
- }
1271
- }
1272
- } catch {
1273
- }
1274
- }
1275
- if (!width || !height) {
1276
- throw new Error(
1277
- "Invalid TIFF: missing ImageWidth/ImageLength in first IFD (consider reading more than header)."
1278
- );
1279
- }
1280
- let colorModel = "unknown";
1281
- let colorSpace = "unknown";
1282
- switch (photometric) {
1283
- case 0:
1284
- case 1:
1285
- colorModel = samplesPerPixel === 2 || extraSamples.length ? "grayscale-alpha" : "grayscale";
1286
- colorSpace = "gray";
1287
- break;
1288
- case 2:
1289
- colorModel = samplesPerPixel === 4 || extraSamples.length ? "rgba" : "rgb";
1290
- colorSpace = "srgb";
1291
- break;
1292
- case 3:
1293
- colorModel = "indexed";
1294
- colorSpace = "srgb";
1295
- break;
1296
- case 5:
1297
- colorModel = "cmyk";
1298
- colorSpace = "cmyk";
1299
- break;
1300
- case 6:
1301
- colorModel = "ycbcr";
1302
- colorSpace = "srgb";
1303
- break;
1304
- case 8:
1305
- colorModel = "lab";
1306
- colorSpace = "lab";
1307
- break;
1308
- default:
1309
- break;
1310
- }
1311
- const hasAlpha = extraSamples.some((v) => v === 1 || v === 2) || // 1: associated alpha, 2: unassociated
1312
- photometric === 2 && samplesPerPixel === 4 || (photometric === 0 || photometric === 1) && samplesPerPixel === 2;
1313
- return {
1314
- width,
1315
- height,
1316
- format: "tiff",
1317
- frames,
1318
- animated: false,
1319
- hasAlpha,
1320
- orientation: orientation ?? null,
1321
- aspectRatio: width / height,
1322
- colorModel,
1323
- colorSpace,
1324
- iccProfile: iccPresent ? "embedded" : null,
1325
- exifDateTimeOriginal
1326
- };
1327
- }
1328
- throw new Error("Unsupported image format or invalid file");
1329
- }
1330
- };
1331
-
1332
- export {
1333
- ImageService
1334
- };
1335
- //# sourceMappingURL=chunk-Y5QWE4EG.js.map