@d0paminedriven/fs 7.1.0 → 7.3.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/README.md +104 -51
  2. package/dist/chunk-2IRCHZCF.js +75 -0
  3. package/dist/{chunk-LFHV4PPA.js → chunk-2XQ44ZWR.js} +339 -3
  4. package/dist/{chunk-IUGBPDQJ.js → chunk-6HHKXBIM.js} +5 -2
  5. package/dist/chunk-HPM4IQQR.js +69 -0
  6. package/dist/{chunk-3WB2TSBO.js → chunk-KNLXF622.js} +2 -2
  7. package/dist/chunk-KOKPGEU4.js +69 -0
  8. package/dist/chunk-LQP2FYMK.js +237 -0
  9. package/dist/chunk-NHYRCNMW.js +107 -0
  10. package/dist/chunk-NOOFSAF4.js +165 -0
  11. package/dist/chunk-PTXZQBLV.js +367 -0
  12. package/dist/{chunk-RJ2YQE3C.js → chunk-R63XI7FS.js} +1 -1
  13. package/dist/{chunk-QBG7TFHM.js → chunk-UW52DMHT.js} +2 -2
  14. package/dist/chunk-Z2WZLZC4.js +75 -0
  15. package/dist/fs/index.d.ts +18 -282
  16. package/dist/fs/index.js +13 -6
  17. package/dist/fs-atomic/index.d.ts +38 -0
  18. package/dist/fs-atomic/index.js +14 -0
  19. package/dist/fs-base/index.d.ts +112 -0
  20. package/dist/fs-base/index.js +13 -0
  21. package/dist/fs-core/index.d.ts +24 -0
  22. package/dist/fs-core/index.js +17 -0
  23. package/dist/fs-fetch/index.d.ts +64 -0
  24. package/dist/fs-fetch/index.js +19 -0
  25. package/dist/fs-size/index.d.ts +30 -0
  26. package/dist/fs-size/index.js +16 -0
  27. package/dist/fs-tmp/index.d.ts +194 -0
  28. package/dist/fs-tmp/index.js +18 -0
  29. package/dist/image/index.d.ts +35 -1
  30. package/dist/image/index.js +5 -4
  31. package/dist/index.d.ts +12 -2
  32. package/dist/index.js +36 -8
  33. package/dist/ld/index.d.ts +14 -0
  34. package/dist/ld/index.js +8 -0
  35. package/dist/mime/index.d.ts +1 -0
  36. package/dist/mime/index.js +4 -3
  37. package/dist/types/index.d.ts +12 -12
  38. package/dist/types/index.js +1 -1
  39. package/dist/types/stream.d.ts +9 -0
  40. package/dist/types/stream.js +1 -0
  41. package/dist/url/index.d.ts +1 -0
  42. package/dist/url/index.js +3 -2
  43. package/dist/utils/index.d.ts +2 -1
  44. package/dist/utils/index.js +2 -1
  45. package/package.json +37 -5
  46. package/dist/chunk-3REIEDSC.js +0 -745
  47. package/dist/fs/index.cjs +0 -1818
  48. package/dist/fs/index.d.cts +0 -464
  49. package/dist/image/index.cjs +0 -1071
  50. package/dist/image/index.d.cts +0 -88
  51. package/dist/index.cjs +0 -1838
  52. package/dist/index.d.cts +0 -10
  53. package/dist/mime/index.cjs +0 -509
  54. package/dist/mime/index.d.cts +0 -502
  55. package/dist/types/index.cjs +0 -38
  56. package/dist/types/index.d.cts +0 -333
  57. package/dist/url/index.cjs +0 -181
  58. package/dist/url/index.d.cts +0 -33
  59. package/dist/utils/index.cjs +0 -157
  60. package/dist/utils/index.d.cts +0 -25
package/dist/index.cjs DELETED
@@ -1,1838 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
9
- var __export = (target, all) => {
10
- for (var name in all)
11
- __defProp(target, name, { get: all[name], enumerable: true });
12
- };
13
- var __copyProps = (to, from, except, desc) => {
14
- if (from && typeof from === "object" || typeof from === "function") {
15
- for (let key of __getOwnPropNames(from))
16
- if (!__hasOwnProp.call(to, key) && key !== except)
17
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
- }
19
- return to;
20
- };
21
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
- // If the importer is in node compatibility mode or this is not an ESM
23
- // file that has been converted to a CommonJS file using a Babel-
24
- // compatible transform (i.e. "__esModule" has not been set), then set
25
- // "default" to the CommonJS "module.exports" for node compatibility.
26
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
- mod
28
- ));
29
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
-
31
- // src/index.ts
32
- var index_exports = {};
33
- __export(index_exports, {
34
- Fs: () => Fs,
35
- ImageService: () => ImageService,
36
- MimeService: () => MimeService,
37
- UrlService: () => UrlService,
38
- UtilsService: () => UtilsService,
39
- extMimeMap: () => extMimeMap,
40
- mimeToExt: () => mimeToExt,
41
- unitsObj: () => unitsObj
42
- });
43
- module.exports = __toCommonJS(index_exports);
44
-
45
- // src/fs/index.ts
46
- var import_child_process = require("child_process");
47
- var import_fs = __toESM(require("fs"), 1);
48
- var import_promises = __toESM(require("fs/promises"), 1);
49
- var import_node_os = require("os");
50
- var import_path = require("path");
51
- var dotenv = __toESM(require("dotenv"), 1);
52
- var import_dotenv_expand = __toESM(require("dotenv-expand"), 1);
53
- var import_sharp = __toESM(require("sharp"), 1);
54
-
55
- // src/utils/index.ts
56
- var UtilsService = class {
57
- static {
58
- __name(this, "UtilsService");
59
- }
60
- chunkArray(arr, maxChunkLength) {
61
- const chunks = Array.of();
62
- let currentChunkLength = 0;
63
- let currentChunk = Array.of();
64
- for (const [index, val] of arr.entries()) {
65
- if (val.length + currentChunkLength >= maxChunkLength) {
66
- if (currentChunk.length) {
67
- chunks.push(currentChunk);
68
- }
69
- currentChunkLength = val.length;
70
- currentChunk = [val];
71
- } else {
72
- currentChunk.push(val);
73
- currentChunkLength += val.length + 1;
74
- }
75
- if (arr.length === index + 1) {
76
- chunks.push(currentChunk);
77
- }
78
- }
79
- return chunks.length ? chunks : [arr];
80
- }
81
- b64ToBlob(b64Data) {
82
- {
83
- const sliceSize = 512;
84
- const typeMatch = /^data:((?:image|application|haptics|video|text|font|model|audio|multipart)\/[A-Za-z0-9+-.]+(?:;[^,]+)*);base64,(.+)$/i.exec(
85
- b64Data
86
- );
87
- if (!typeMatch) {
88
- throw new Error(`${b64Data} is not a valid data Url`);
89
- }
90
- const type = typeMatch[1];
91
- const base64Data = typeMatch?.[2] ?? "";
92
- const byteCharacters = Buffer.from(base64Data, "base64").toString(
93
- "binary"
94
- );
95
- const byteArrays = Array.of();
96
- for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
97
- const slice = byteCharacters.slice(offset, offset + sliceSize);
98
- const byteNumbers = new Array(slice.length);
99
- for (let i = 0; i < slice.length; i++) {
100
- byteNumbers[i] = slice.charCodeAt(i);
101
- }
102
- const byteArray = new Uint8Array(byteNumbers);
103
- byteArrays.push(byteArray);
104
- }
105
- const blob = new Blob(byteArrays, { type });
106
- return blob;
107
- }
108
- }
109
- arrToArrOfArrs = /* @__PURE__ */ __name(({
110
- arrToFragment = Array.of(),
111
- arrOfArrsAggregator = Array.of(),
112
- interval
113
- }) => new Promise(
114
- (resolve2, _reject) => resolve2(
115
- ((interval2) => {
116
- for (let i = 0; i <= arrToFragment.length; i++) {
117
- if ((i % interval2 === 0 || i === 0) && i <= arrToFragment.length) {
118
- let segment = arrToFragment.slice(i, i + interval2);
119
- arrOfArrsAggregator.push(segment);
120
- }
121
- }
122
- })(interval)
123
- )
124
- ).then((_) => arrOfArrsAggregator), "arrToArrOfArrs");
125
- extractTuple(obj, props) {
126
- return [props, obj[props]];
127
- }
128
- sort(obj, order) {
129
- return Object.fromEntries(
130
- Object.entries(obj).sort(
131
- ([a, _aa], [b, _bb]) => order === "DESC" ? b.localeCompare(a) - a.localeCompare(b) : a.localeCompare(b) - b.localeCompare(a)
132
- )
133
- );
134
- }
135
- excludeTargeted = /* @__PURE__ */ __name((obj, props, sort) => {
136
- const resolve2 = Object.fromEntries(
137
- Object.entries(obj).map(([key, val]) => {
138
- if (props.includes(key)) {
139
- return ["omit", "omit"];
140
- } else return [key, val];
141
- }).filter(([t, _v]) => /omit/.test(t) === false)
142
- );
143
- return typeof sort !== "undefined" ? this.sort(resolve2, sort) : resolve2;
144
- }, "excludeTargeted");
145
- includeTargeted = /* @__PURE__ */ __name((obj, props, sort) => {
146
- const resolve2 = Object.fromEntries(
147
- props.map((val) => this.extractTuple(obj, val))
148
- );
149
- return typeof sort !== "undefined" ? this.sort(resolve2, sort) : resolve2;
150
- }, "includeTargeted");
151
- countsSorter = /* @__PURE__ */ __name((counter, keySort = "ASC", valSort = "DESC") => Object.fromEntries(
152
- Array.from(Object.entries(counter)).sort(
153
- ([aStr, _aNum], [bStr, _bNum]) => keySort === "DESC" ? bStr.localeCompare(aStr) - aStr.localeCompare(bStr) : aStr.localeCompare(bStr) - bStr.localeCompare(aStr)
154
- ).sort(([aStr, aNum], [bStr, bNum]) => {
155
- if (typeof (aNum && bNum) === "number") {
156
- return valSort === "ASC" ? aNum - bNum : bNum - aNum;
157
- } else if (typeof (aNum && bNum) === "string") {
158
- return valSort === "ASC" ? aStr.localeCompare(bStr) - bStr.localeCompare(aStr) : bStr.localeCompare(aStr) - aStr.localeCompare(bStr);
159
- } else
160
- throw new Error(
161
- "only Record<string, string> and Record<string,number> types supported"
162
- );
163
- })
164
- ), "countsSorter");
165
- range(from, to) {
166
- const values = Array.of();
167
- for (let i = from; i < to; i++) {
168
- values.push(i);
169
- }
170
- return values;
171
- }
172
- isPrimeNumber = /* @__PURE__ */ __name((n) => {
173
- for (let i = 2; n > i; i++) {
174
- if (n % i === 0) {
175
- return false;
176
- }
177
- }
178
- return n > 1;
179
- }, "isPrimeNumber");
180
- acceptor = /* @__PURE__ */ __name((num) => [...Array(num !== 0 ? num : this.range(num = -101, num = 101)).keys()].reverse().filter(this.isPrimeNumber), "acceptor");
181
- };
182
-
183
- // src/url/index.ts
184
- var UrlService = class extends UtilsService {
185
- static {
186
- __name(this, "UrlService");
187
- }
188
- URL_REGEX = /^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
189
- parseUrl(url) {
190
- const parsed = this.URL_REGEX.exec(url);
191
- if (parsed) {
192
- return {
193
- href: parsed[0],
194
- protocol: parsed[1] ?? "",
195
- baseUrl: `${parsed[1]}${parsed[3]}`,
196
- host: parsed[4] ?? "",
197
- pathname: parsed[5] ?? "",
198
- search: parsed[6] ?? "",
199
- hash: parsed[8] ?? ""
200
- };
201
- } else return null;
202
- }
203
- };
204
-
205
- // src/mime/index.ts
206
- var extMimeMap = {
207
- aac: ["audio/aac"],
208
- abw: ["application/x-abiword"],
209
- aces: ["image/aces"],
210
- apng: ["image/apng"],
211
- arc: ["application/x-freearc"],
212
- avci: ["image/avci"],
213
- avif: ["image/avif"],
214
- avi: ["video/x-msvideo"],
215
- azw: ["application/vnd.amazon.ebook"],
216
- bin: ["application/octet-stream", "multipart/voice-message"],
217
- bmp: ["image/bmp"],
218
- bz: ["application/x-bzip"],
219
- bz2: ["application/x-bzip2"],
220
- cda: ["application/x-cdf"],
221
- cjs: ["application/node", "text/javascript"],
222
- csh: ["application/x-csh"],
223
- css: ["text/css"],
224
- csv: ["text/csv"],
225
- cur: ["image/x-icon"],
226
- doc: ["application/msword"],
227
- docx: [
228
- "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
229
- ],
230
- dpx: ["image/dpx"],
231
- emf: ["image/emf"],
232
- eot: ["application/vnd.ms-fontobject"],
233
- epub: ["application/epub+zip"],
234
- gif: ["image/gif"],
235
- glb: ["model/gltf-binary"],
236
- gltf: ["model/gltf+json"],
237
- gz: ["application/gzip", "application/x-gzip"],
238
- hjif: ["haptics/hjif"],
239
- hmpg: ["haptics/hmpg"],
240
- htm: ["text/html"],
241
- html: ["text/html"],
242
- ico: ["image/vnd.microsoft.icon", "image/x-icon"],
243
- ics: ["text/calendar"],
244
- ivs: ["haptics/ivs"],
245
- ivt: ["haptics/ivs"],
246
- jar: ["application/java-archive"],
247
- jfif: ["image/jpeg"],
248
- jif: ["image/jpeg"],
249
- jpe: ["image/jpeg"],
250
- jpeg: ["image/jpeg"],
251
- jpg: ["image/jpeg"],
252
- js: ["application/node", "text/javascript"],
253
- json: ["application/json"],
254
- jsonld: ["application/ld+json"],
255
- ktx: ["image/ktx"],
256
- ktx2: ["image/ktx2"],
257
- m3u8: ["application/vnd.apple.mpegurl"],
258
- m4a: ["audio/mp4"],
259
- m4v: ["video/mp4"],
260
- md: ["text/markdown"],
261
- mdx: ["application/x-mdx"],
262
- mid: ["audio/midi"],
263
- midi: ["audio/x-midi"],
264
- mjs: ["text/javascript"],
265
- mp3: ["audio/mpeg"],
266
- mp4: ["video/mp4"],
267
- mpd: ["application/dash+xml"],
268
- mpeg: ["video/mpeg"],
269
- mpkg: ["application/vnd.apple.installer+xml"],
270
- mtlx: ["application/xml"],
271
- ndjson: ["application/x-ndjson"],
272
- node: ["application/node", "text/javascript"],
273
- obj: ["model/obj", "application/octet-stream", "text/plain"],
274
- odp: ["application/vnd.oasis.opendocument.presentation"],
275
- ods: ["application/vnd.oasis.opendocument.spreadsheet"],
276
- odt: ["application/vnd.oasis.opendocument.text"],
277
- oga: ["audio/ogg"],
278
- ogg: ["audio/ogg"],
279
- ogv: ["video/ogg"],
280
- ogx: ["application/ogg"],
281
- opus: ["audio/ogg"],
282
- otf: ["font/otf"],
283
- png: ["image/png"],
284
- pdf: ["application/pdf"],
285
- php: ["application/x-httpd-php"],
286
- pjp: ["image/jpeg"],
287
- pjpeg: ["image/jpeg"],
288
- pkpass: ["application/vnd.apple.pkpass"],
289
- ppt: ["application/vnd.ms-powerpoint"],
290
- pptx: [
291
- "application/vnd.openxmlformats-officedocument.presentationml.presentation"
292
- ],
293
- py: ["text/x-python"],
294
- pyc: ["application/x-python-code"],
295
- rar: ["application/vnd.rar"],
296
- rs: ["text/rust"],
297
- rtf: ["application/rtf"],
298
- sh: ["application/x-sh"],
299
- sql: ["application/sql"],
300
- sse: ["text/event-stream"],
301
- svg: ["image/svg+xml"],
302
- tar: ["application/x-tar"],
303
- tif: ["image/tiff"],
304
- tiff: ["image/tiff"],
305
- toml: ["application/toml"],
306
- ts: ["text/typescript", "video/mp2t", "video/vnd.dlna.mpeg-tts"],
307
- ttf: ["application/font-sfnt", "font/ttf"],
308
- txt: ["text/plain"],
309
- usdz: ["model/vnd.usdz+zip"],
310
- vsd: ["application/vnd.visio"],
311
- vtt: ["text/vtt"],
312
- wasm: ["application/wasm"],
313
- wav: ["audio/wav"],
314
- weba: ["audio/webm"],
315
- webm: ["video/webm"],
316
- webmanifest: ["application/manifest+json"],
317
- webp: ["image/webp"],
318
- woff: ["font/woff"],
319
- woff2: ["font/woff2"],
320
- xhtml: ["application/xhtml+xml"],
321
- xls: ["application/vnd.ms-excel"],
322
- xlsx: ["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],
323
- xml: ["application/xml", "text/xml"],
324
- xul: ["application/vnd.mozilla.xul+xml"],
325
- yaml: ["application/yaml"],
326
- yml: ["application/yaml"],
327
- zip: ["application/zip", "application/x-zip-compressed"],
328
- "3gp": ["video/3gpp"],
329
- "3g2": ["video/3gpp2"],
330
- "7z": ["application/x-7z-compressed"]
331
- };
332
- var mimeToExt = {
333
- "application/dash+xml": ["mpd"],
334
- "application/epub+zip": ["epub"],
335
- "application/font-sfnt": ["ttf"],
336
- "application/gzip": ["gz"],
337
- "application/java-archive": ["jar"],
338
- "application/json": ["json"],
339
- "application/ld+json": ["jsonld"],
340
- "application/manifest+json": ["webmanifest"],
341
- "application/msword": ["doc"],
342
- "application/node": ["node", "js"],
343
- "application/octet-stream": ["bin", "obj"],
344
- "application/ogg": ["ogx"],
345
- "application/pdf": ["pdf"],
346
- "application/rtf": ["rtf"],
347
- "application/sql": ["sql"],
348
- "application/toml": ["toml"],
349
- "application/vnd.amazon.ebook": ["azw"],
350
- "application/vnd.apple.installer+xml": ["mpkg"],
351
- "application/vnd.apple.mpegurl": ["m3u8"],
352
- "application/vnd.apple.pkpass": ["pkpass"],
353
- "application/vnd.mozilla.xul+xml": ["xul"],
354
- "application/vnd.ms-excel": ["xls"],
355
- "application/vnd.ms-fontobject": ["eot"],
356
- "application/vnd.ms-powerpoint": ["ppt"],
357
- "application/vnd.oasis.opendocument.presentation": ["odp"],
358
- "application/vnd.oasis.opendocument.spreadsheet": ["ods"],
359
- "application/vnd.oasis.opendocument.text": ["odt"],
360
- "application/vnd.openxmlformats-officedocument.presentationml.presentation": [
361
- "pptx"
362
- ],
363
- "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": ["xlsx"],
364
- "application/vnd.openxmlformats-officedocument.wordprocessingml.document": [
365
- "docx"
366
- ],
367
- "application/vnd.rar": ["rar"],
368
- "application/vnd.visio": ["vsd"],
369
- "application/wasm": ["wasm"],
370
- "application/x-7z-compressed": ["7z"],
371
- "application/x-abiword": ["abw"],
372
- "application/x-bzip": ["bz"],
373
- "application/x-bzip2": ["bz2"],
374
- "application/x-cdf": ["cda"],
375
- "application/x-csh": ["csh"],
376
- "application/x-freearc": ["arc"],
377
- "application/x-gzip": ["gz"],
378
- "application/x-httpd-php": ["php"],
379
- "application/x-mdx": ["mdx"],
380
- "application/x-ndjson": ["ndjson"],
381
- "application/x-python-code": ["pyc"],
382
- "application/x-sh": ["sh"],
383
- "application/x-tar": ["tar"],
384
- "application/x-zip-compressed": ["zip"],
385
- "application/xhtml+xml": ["xhtml"],
386
- "application/xml": ["xml", "mtlx"],
387
- "application/yaml": ["yml", "yaml"],
388
- "application/zip": ["zip"],
389
- "audio/aac": ["aac"],
390
- "audio/midi": ["mid"],
391
- "audio/mp4": ["m4a"],
392
- "audio/mpeg": ["mp3"],
393
- "audio/ogg": ["opus", "ogg", "oga"],
394
- "audio/wav": ["wav"],
395
- "audio/webm": ["weba"],
396
- "audio/x-midi": ["midi"],
397
- "font/otf": ["otf"],
398
- "font/ttf": ["ttf"],
399
- "font/woff": ["woff"],
400
- "font/woff2": ["woff2"],
401
- "haptics/hjif": ["hjif"],
402
- "haptics/hmpg": ["hmpg"],
403
- "haptics/ivs": ["ivs", "ivt"],
404
- "image/aces": ["aces"],
405
- "image/apng": ["apng"],
406
- "image/avci": ["avci"],
407
- "image/avif": ["avif"],
408
- "image/bmp": ["bmp"],
409
- "image/dpx": ["dpx"],
410
- "image/emf": ["emf"],
411
- "image/gif": ["gif"],
412
- "image/jpeg": ["jpg", "jpeg", "jpe", "jif", "jfif", "pjp", "pjpeg"],
413
- "image/ktx": ["ktx"],
414
- "image/ktx2": ["ktx2"],
415
- "image/png": ["png"],
416
- "image/svg+xml": ["svg"],
417
- "image/tiff": ["tiff", "tif"],
418
- "image/vnd.microsoft.icon": ["ico"],
419
- "image/webp": ["webp"],
420
- "image/x-icon": ["cur", "ico"],
421
- "model/gltf-binary": ["glb"],
422
- "model/gltf+json": ["gltf"],
423
- "model/obj": ["obj"],
424
- "model/vnd.usdz+zip": ["usdz"],
425
- "multipart/voice-message": ["bin"],
426
- "text/calendar": ["ics"],
427
- "text/css": ["css"],
428
- "text/csv": ["csv"],
429
- "text/event-stream": ["sse"],
430
- "text/html": ["html", "htm"],
431
- "text/javascript": ["js", "mjs", "cjs"],
432
- "text/markdown": ["md"],
433
- "text/plain": ["txt"],
434
- "text/rust": ["rs"],
435
- "text/typescript": ["ts"],
436
- "text/vtt": ["vtt"],
437
- "text/xml": ["xml"],
438
- "text/x-python": ["py"],
439
- "video/3gpp": ["3gp"],
440
- "video/3gpp2": ["3g2"],
441
- "video/mp2t": ["ts"],
442
- "video/mp4": ["mp4", "m4v"],
443
- "video/mpeg": ["mpeg"],
444
- "video/ogg": ["ogv"],
445
- "video/vnd.dlna.mpeg-tts": ["ts"],
446
- "video/webm": ["webm"],
447
- "video/x-msvideo": ["avi"]
448
- };
449
- var MimeService = class extends UrlService {
450
- static {
451
- __name(this, "MimeService");
452
- }
453
- constructor() {
454
- super();
455
- }
456
- mimeTypeObj = extMimeMap;
457
- toExtObj = mimeToExt;
458
- compareMimeToExt(p = "mime") {
459
- let a = {};
460
- if (p === "mime") {
461
- for (const [_key, vals] of Object.entries(extMimeMap)) {
462
- for (const val of vals) {
463
- a[val] = (a[val] ?? 0) + 1;
464
- }
465
- }
466
- for (const [key, _val] of Object.entries(mimeToExt)) {
467
- a[key] = (a[key] ?? 0) + 1;
468
- }
469
- return Object.fromEntries(
470
- Object.entries(a).sort(([_a, aa], [_b, bb]) => bb - aa)
471
- );
472
- } else {
473
- for (const [_key, vals] of Object.entries(mimeToExt)) {
474
- for (const val of vals) {
475
- a[val] = (a[val] ?? 0) + 1;
476
- }
477
- }
478
- for (const [key, _val] of Object.entries(extMimeMap)) {
479
- a[key] = (a[key] ?? 0) + 1;
480
- }
481
- return Object.fromEntries(
482
- Object.entries(a).sort(([_a, aa], [_b, bb]) => bb - aa)
483
- );
484
- }
485
- }
486
- mimeToExt(mime) {
487
- const extensions = this.toExtObj[mime];
488
- if (extensions.length === 1) return extensions[0];
489
- if (extensions.length === 2) {
490
- return extensions[0];
491
- }
492
- if (extensions.length === 3) {
493
- if (mime === "audio/ogg") return "ogg";
494
- return extensions[0];
495
- }
496
- if (extensions.length === 7) {
497
- return extensions[0];
498
- }
499
- return extensions[0];
500
- }
501
- assetType(url) {
502
- const parsed = this.parseUrl(url);
503
- if (!parsed) return void 0;
504
- const ext = parsed.pathname.split(/([.])/g)?.reverse()?.[0]?.toLowerCase();
505
- return ext && ext in this.mimeTypeObj ? ext : void 0;
506
- }
507
- getMimes(ext) {
508
- return this.mimeTypeObj[ext];
509
- }
510
- getMimeFor(ext, opts) {
511
- const mimes = this.getMimes(ext);
512
- if (mimes.length === 1) return mimes[0];
513
- if (opts?.type) {
514
- const found = mimes.find((mime) => mime.startsWith(opts.type + "/"));
515
- return found ?? mimes[0];
516
- }
517
- return mimes[0];
518
- }
519
- isMimeFor(ext, mime) {
520
- return this.getMimes(ext).find((s) => s === mime);
521
- }
522
- getMimeTypeForPath(path, opts) {
523
- const ext = this.assetType(path);
524
- if (!ext) return "application/octet-stream";
525
- return this.getMimeFor(ext, opts);
526
- }
527
- };
528
-
529
- // src/image/index.ts
530
- var ImageService = class extends MimeService {
531
- static {
532
- __name(this, "ImageService");
533
- }
534
- parseExif(buffer, app1Pos, app1Size) {
535
- const exifHeader = buffer.toString("ascii", app1Pos + 2, app1Pos + 8);
536
- if (exifHeader !== "Exif\0\0")
537
- return { orientation: null, dateTimeOriginal: null };
538
- let tiffPos = app1Pos + 8;
539
- const app1End = app1Pos + app1Size;
540
- if (tiffPos + 10 > app1End)
541
- return { orientation: null, dateTimeOriginal: null };
542
- const byteOrder = buffer.toString("ascii", tiffPos, tiffPos + 2);
543
- const littleEndian = byteOrder === "II";
544
- const readUInt16 = littleEndian ? buffer.readUInt16LE.bind(buffer) : buffer.readUInt16BE.bind(buffer);
545
- const readUInt32 = littleEndian ? buffer.readUInt32LE.bind(buffer) : buffer.readUInt32BE.bind(buffer);
546
- if (readUInt16(tiffPos + 2) !== 42)
547
- return { orientation: null, dateTimeOriginal: null };
548
- let ifdOffset = readUInt32(tiffPos + 4);
549
- tiffPos += ifdOffset;
550
- const numEntries = readUInt16(tiffPos);
551
- tiffPos += 2;
552
- let orientation = null;
553
- let dateTimeOriginal = null;
554
- for (let i = 0; i < numEntries; i++) {
555
- const tag = readUInt16(tiffPos), type = readUInt16(tiffPos + 2), count = readUInt32(tiffPos + 4), valueOffset = tiffPos + 8;
556
- if (tag === 274 && type === 3 && count === 1) {
557
- orientation = readUInt16(valueOffset);
558
- } else if (tag === 36867 && type === 2 && count === 20) {
559
- const offset = readUInt32(valueOffset);
560
- if (app1Pos + 2 + offset + 19 > app1End) {
561
- dateTimeOriginal = null;
562
- } else {
563
- dateTimeOriginal = buffer.toString("ascii", app1Pos + 2 + offset, app1Pos + 2 + offset + 19).trim();
564
- }
565
- }
566
- tiffPos += 12;
567
- }
568
- return { orientation, dateTimeOriginal };
569
- }
570
- parseXmpFromAvif(buffer, meta, _ipco) {
571
- const iinf = this.findBox(
572
- buffer,
573
- "iinf",
574
- meta.pos + 4,
575
- meta.pos + meta.size
576
- );
577
- if (!iinf) return null;
578
- let pos = iinf.pos;
579
- const version = buffer[pos++];
580
- const itemCount = version === 0 ? buffer.readUInt16BE(pos) : buffer.readUInt32BE(pos);
581
- pos += version === 0 ? 2 : 4;
582
- let xmpItemId;
583
- for (let i = 0; i < itemCount; i++) {
584
- const infeStart = pos;
585
- const infeSize = buffer.readUInt32BE(pos);
586
- if (buffer.toString("ascii", pos + 4, pos + 8) !== "infe") break;
587
- pos += 8;
588
- const infeVersion = buffer?.[pos++];
589
- if (!infeVersion) return null;
590
- const itemId = infeVersion < 2 ? buffer.readUInt16BE(pos) : buffer.readUInt32BE(pos);
591
- pos += infeVersion < 2 ? 2 : 4;
592
- pos += 2;
593
- const itemType = buffer.toString("ascii", pos, pos + 4);
594
- pos += 4;
595
- let nameEnd = pos;
596
- while (buffer[nameEnd] !== 0 && nameEnd < infeStart + infeSize) nameEnd++;
597
- const _itemName = buffer.toString("ascii", pos, nameEnd);
598
- pos = nameEnd + 1;
599
- if (itemType === "mime") {
600
- let ctEnd = pos;
601
- while (buffer[ctEnd] !== 0 && ctEnd < infeStart + infeSize) ctEnd++;
602
- const contentType = buffer.toString("ascii", pos, ctEnd);
603
- if (contentType === "application/rdf+xml") {
604
- xmpItemId = itemId;
605
- break;
606
- }
607
- pos = ctEnd + 1;
608
- }
609
- pos = infeStart + infeSize;
610
- }
611
- if (!xmpItemId) return null;
612
- const iloc = this.findBox(
613
- buffer,
614
- "iloc",
615
- meta.pos + 4,
616
- meta.pos + meta.size
617
- );
618
- if (!iloc) return null;
619
- pos = iloc.pos;
620
- const ilocVersion = buffer[pos++];
621
- const sizes = buffer?.[pos++];
622
- if (!sizes) return null;
623
- const offsetSize = sizes >> 4 & 15;
624
- const lengthSize = sizes & 15;
625
- let indexSize = 0;
626
- if (ilocVersion === 1 || ilocVersion === 2) {
627
- const indexSizes = buffer?.[pos++];
628
- if (!indexSizes) return null;
629
- indexSize = indexSizes >> 4 & 15;
630
- }
631
- if (!ilocVersion) return null;
632
- let buffpos = buffer?.[pos++];
633
- if (!buffpos) return null;
634
- const baseOffsetSize = ilocVersion < 2 ? 0 : buffpos >> 4 & 15;
635
- const itemCountIloc = ilocVersion < 2 ? buffer.readUInt16BE(pos) : buffer.readUInt32BE(pos);
636
- pos += ilocVersion < 2 ? 2 : 4;
637
- let xmpOffset = 0;
638
- let xmpLength = 0;
639
- for (let i = 0; i < itemCountIloc; i++) {
640
- const curItemId = ilocVersion < 2 ? buffer.readUInt16BE(pos) : buffer.readUInt32BE(pos);
641
- pos += ilocVersion < 2 ? 2 : 4;
642
- if (curItemId !== xmpItemId) {
643
- if (ilocVersion === 1 || ilocVersion === 2) pos += 2;
644
- pos += 2;
645
- pos += baseOffsetSize;
646
- const extentCount2 = buffer.readUInt16BE(pos);
647
- pos += 2;
648
- for (let e = 0; e < extentCount2; e++) {
649
- if (indexSize > 0) pos += indexSize;
650
- pos += offsetSize + lengthSize;
651
- }
652
- continue;
653
- }
654
- if (ilocVersion === 1 || ilocVersion === 2) {
655
- const constructionMethod = buffer.readUInt16BE(pos);
656
- pos += 2;
657
- if (constructionMethod !== 0) return null;
658
- }
659
- pos += 2;
660
- const baseOffset = this.readVarSize(buffer, pos, baseOffsetSize);
661
- pos += baseOffsetSize;
662
- const extentCount = buffer.readUInt16BE(pos);
663
- pos += 2;
664
- if (extentCount !== 1) return null;
665
- if (indexSize > 0) pos += indexSize;
666
- const extentOffset = this.readVarSize(buffer, pos, offsetSize);
667
- pos += offsetSize;
668
- const extentLength = this.readVarSize(buffer, pos, lengthSize);
669
- xmpOffset = baseOffset + extentOffset;
670
- xmpLength = extentLength;
671
- break;
672
- }
673
- if (xmpOffset === 0 || xmpLength === 0 || xmpOffset + xmpLength > buffer.length)
674
- return null;
675
- return buffer.toString("utf8", xmpOffset, xmpOffset + xmpLength);
676
- }
677
- readVarSize(buffer, pos, size) {
678
- if (size === 0) return 0;
679
- if (size === 1 && buffer?.[pos]) return buffer?.[pos];
680
- if (size === 2) return buffer.readUInt16BE(pos);
681
- if (size === 3) {
682
- let pos1 = buffer?.[pos + 1], pos2 = buffer?.[pos + 2];
683
- if (buffer?.[pos] && pos1 && pos2) {
684
- return buffer[pos] << 16 | pos1 << 8 | pos2;
685
- }
686
- throw new Error("Invalid var size");
687
- }
688
- if (size === 4) return buffer.readUInt32BE(pos);
689
- if (size === 8) return Number(buffer.readBigUInt64BE(pos));
690
- throw new Error("Invalid var size");
691
- }
692
- findBox(buffer, type, start = 0, end = buffer.length) {
693
- let pos = start;
694
- while (pos < end) {
695
- let boxSize = buffer.readUInt32BE(pos);
696
- let boxType = buffer.toString("ascii", pos + 4, pos + 8);
697
- let hdrSize = 8;
698
- if (boxSize === 1) {
699
- boxSize = Number(buffer.readBigUInt64BE(pos + 8));
700
- hdrSize = 16;
701
- } else if (boxSize === 0) {
702
- boxSize = end - pos;
703
- }
704
- if (boxType === type) {
705
- return { pos: pos + hdrSize, size: boxSize - hdrSize };
706
- }
707
- pos += boxSize;
708
- }
709
- return null;
710
- }
711
- getImageSpecsWorkup(buffer) {
712
- 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) {
713
- if (buffer.readUint32BE(8) !== 13 || buffer?.[12] !== 73 || buffer?.[13] !== 72 || buffer?.[14] !== 68 || buffer?.[15] !== 82) {
714
- throw new Error("IHDR Chunk of png not found or incorrect.");
715
- }
716
- const colorType = buffer[25];
717
- let colorSpace;
718
- let hasAlpha = false;
719
- switch (colorType) {
720
- case 0:
721
- colorSpace = "grayscale";
722
- break;
723
- case 2:
724
- colorSpace = "rgb";
725
- break;
726
- case 3:
727
- colorSpace = "indexed";
728
- break;
729
- case 4:
730
- colorSpace = "grayscale-alpha";
731
- hasAlpha = true;
732
- break;
733
- case 6:
734
- colorSpace = "rgba";
735
- hasAlpha = true;
736
- break;
737
- default:
738
- colorSpace = "unknown";
739
- }
740
- const width = buffer.readUInt32BE(16);
741
- const height = buffer.readUInt32BE(20);
742
- let frames = 1;
743
- let animated = false;
744
- let iccProfile = null;
745
- let exifDateTimeOriginal = null;
746
- let orientation = null;
747
- let pos = 33;
748
- while (pos < buffer.length - 12) {
749
- const chunkLen = buffer.readUInt32BE(pos);
750
- const chunkType = buffer.toString("ascii", pos + 4, pos + 8);
751
- const chunkData = pos + 8;
752
- if (chunkType === "acTL") {
753
- animated = true;
754
- frames = buffer.readUInt32BE(chunkData);
755
- } else if (chunkType === "iCCP") {
756
- const nameEnd = buffer.indexOf(0, chunkData);
757
- const profileName = buffer.toString("ascii", chunkData, nameEnd);
758
- iccProfile = profileName || "embedded";
759
- } else if (chunkType === "tIME") {
760
- const month = buffer?.[chunkData + 2], day = buffer?.[chunkData + 3], hour = buffer?.[chunkData + 4], minute = buffer?.[chunkData + 5], second = buffer?.[chunkData + 6];
761
- if (typeof month !== "undefined" && typeof day !== "undefined" && typeof hour !== "undefined" && typeof minute !== "undefined" && typeof second !== "undefined") {
762
- const year = buffer.readUInt16BE(chunkData);
763
- 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")}`;
764
- }
765
- } else if (chunkType === "IDAT") {
766
- break;
767
- }
768
- pos += 12 + chunkLen;
769
- }
770
- return {
771
- width,
772
- height,
773
- format: "png",
774
- frames,
775
- animated,
776
- hasAlpha,
777
- orientation,
778
- aspectRatio: width / height,
779
- colorSpace,
780
- iccProfile,
781
- exifDateTimeOriginal
782
- };
783
- }
784
- if (buffer.length >= 10 && buffer[0] === 255 && buffer[1] === 216) {
785
- let pos = 2, colorSpace = "unknown", hasAlpha = false, width = 0, height = 0, iccProfile = null, orientation = null, exifDateTimeOriginal = null;
786
- while (pos < buffer.length - 10) {
787
- if (buffer[pos] !== 255) {
788
- throw new Error("Invalid JPEG file");
789
- }
790
- const marker = buffer[pos + 1];
791
- if (marker === 218) break;
792
- const segmentSize = buffer.readUInt16BE(pos + 2);
793
- if (!marker) {
794
- throw new Error("no marker for jpeg");
795
- }
796
- if (marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204) {
797
- const numComponents = buffer[pos + 4];
798
- switch (numComponents) {
799
- case 1:
800
- colorSpace = "grayscale";
801
- break;
802
- case 3:
803
- colorSpace = "ycbcr";
804
- break;
805
- // Most common for RGB JPEGs (stored as YCbCr)
806
- case 4:
807
- colorSpace = "ycck";
808
- break;
809
- // YCCK for CMYK with alpha-like, but no true alpha
810
- default:
811
- colorSpace = "unknown";
812
- }
813
- width = buffer.readUInt16BE(pos + 7);
814
- height = buffer.readUInt16BE(pos + 5);
815
- } else if (marker === 225) {
816
- const { orientation: ori, dateTimeOriginal } = this.parseExif(
817
- buffer,
818
- pos,
819
- segmentSize
820
- );
821
- orientation = ori;
822
- exifDateTimeOriginal = dateTimeOriginal;
823
- } else if (marker === 226) {
824
- const iccHeader = buffer.toString("ascii", pos + 4, pos + 18);
825
- if (iccHeader.startsWith("ICC_PROFILE")) {
826
- iccProfile = "embedded";
827
- }
828
- }
829
- pos += segmentSize + 2;
830
- }
831
- if (width === 0) throw new Error("No dimensions found in JPEG file");
832
- return {
833
- width,
834
- height,
835
- format: "jpeg",
836
- frames: 1,
837
- animated: false,
838
- // JPEG not animated
839
- hasAlpha,
840
- orientation,
841
- aspectRatio: width / height,
842
- colorSpace,
843
- iccProfile,
844
- exifDateTimeOriginal
845
- };
846
- }
847
- const gifHeader = buffer.toString("ascii", 0, 6);
848
- if (buffer.length >= 10 && (gifHeader === "GIF87a" || gifHeader === "GIF89a")) {
849
- const width = buffer.readUInt16LE(6), height = buffer.readUInt16LE(8);
850
- let frames = 0;
851
- let pos = 13;
852
- let bufTen = buffer?.[10];
853
- if (typeof bufTen === "undefined") {
854
- pos = 13;
855
- frames = 0;
856
- } else if (bufTen & 128) pos += 3 << (bufTen & 7) + 1;
857
- while (pos < buffer.length) {
858
- if (buffer[pos] === 33) {
859
- pos += 2;
860
- let subSize = buffer?.[pos];
861
- while (subSize && subSize > 0) {
862
- pos += subSize + 1;
863
- subSize = buffer?.[pos];
864
- }
865
- pos++;
866
- } else if (buffer?.[pos] && buffer?.[pos] === 44) {
867
- frames++;
868
- pos += 10;
869
- let b = buffer?.[pos - 1];
870
- if (typeof b !== "undefined" && b & 128)
871
- pos += 3 << (b & 7) + 1;
872
- pos++;
873
- let dataSize = buffer?.[pos];
874
- while (dataSize && dataSize > 0) {
875
- pos += dataSize + 1;
876
- dataSize = buffer[pos];
877
- }
878
- pos++;
879
- } else if (buffer[pos] === 59) {
880
- break;
881
- } else {
882
- pos++;
883
- }
884
- }
885
- return {
886
- width,
887
- height,
888
- format: "gif",
889
- frames,
890
- animated: frames > 1,
891
- hasAlpha: null,
892
- // GIF transparency is per-pixel binary, not full alpha; set null or true if transparent color exists, but complex
893
- orientation: null,
894
- // No orientation in GIF
895
- aspectRatio: width / height,
896
- colorSpace: "indexed",
897
- iccProfile: null,
898
- // No ICC in GIF
899
- exifDateTimeOriginal: null
900
- // No EXIF in GIF
901
- };
902
- }
903
- if (buffer.length >= 26 && buffer?.[0] === 66 && buffer?.[1] === 77) {
904
- const width = buffer.readInt32LE(18);
905
- const height = Math.abs(buffer.readInt32LE(22));
906
- const bitDepth = buffer.readUInt16LE(28);
907
- let colorSpace = bitDepth <= 8 ? "indexed" : "rgb";
908
- return {
909
- width,
910
- height,
911
- format: "bmp",
912
- frames: 1,
913
- animated: false,
914
- hasAlpha: null,
915
- // Some BMP have alpha in 32bpp, check if bitDepth===32 && compression===3 (bitfields with alpha)
916
- orientation: buffer.readInt32LE(22) < 0 ? 1 : 6,
917
- // Negative height means top-down (orientation 1), positive bottom-up (like 6, but simplified)
918
- aspectRatio: width / height,
919
- colorSpace,
920
- iccProfile: null,
921
- // Rare in BMP
922
- exifDateTimeOriginal: null
923
- };
924
- }
925
- if (buffer.length >= 30 && buffer.toString("ascii", 0, 4) === "RIFF" && buffer.toString("ascii", 8, 12) === "WEBP") {
926
- const chunkType = buffer.toString("ascii", 12, 16);
927
- let colorSpace = "unknown";
928
- let hasAlpha = false;
929
- let width = 0;
930
- let height = 0;
931
- let frames = 1;
932
- let animated = false;
933
- let iccProfile = null;
934
- if (chunkType === "VP8X") {
935
- const flags = buffer?.[20];
936
- colorSpace = flags ? flags & 2 ? "rgba" : "rgb" : "unknown";
937
- hasAlpha = flags ? !!(flags & 2) : false;
938
- animated = flags ? !!(flags & 1) : false;
939
- let widthSubtractOne = 0;
940
- let heightSubtractOne = 0;
941
- if (buffer?.[24] && buffer?.[25] && buffer?.[26]) {
942
- widthSubtractOne = buffer[24] | buffer[25] << 8 | buffer[26] << 16;
943
- }
944
- if (buffer?.[27] && buffer?.[28] && buffer?.[29]) {
945
- heightSubtractOne = buffer[27] | buffer[28] << 8 | buffer[29] << 16;
946
- }
947
- width = widthSubtractOne + 1;
948
- height = heightSubtractOne + 1;
949
- if (animated) {
950
- let pos = 30;
951
- frames = 0;
952
- while (pos < buffer.length - 8) {
953
- const subChunkType = buffer.toString("ascii", pos, pos + 4);
954
- const subChunkSize = buffer.readUInt32LE(pos + 4);
955
- if (subChunkType === "ICCP") {
956
- iccProfile = "embedded";
957
- } else if (subChunkType === "ANMF") {
958
- frames++;
959
- }
960
- pos += 8 + subChunkSize + subChunkSize % 2;
961
- }
962
- }
963
- } else if (chunkType === "VP8 ") {
964
- colorSpace = "rgb";
965
- hasAlpha = false;
966
- const dataStart = 20;
967
- if (buffer?.[dataStart + 3] !== 157 || buffer?.[dataStart + 4] !== 1 || buffer?.[dataStart + 5] !== 42) {
968
- throw new Error("Invalid VP8 keyframe");
969
- }
970
- width = buffer.readUInt16LE(dataStart + 6) & 16383;
971
- height = buffer.readUInt16LE(dataStart + 8) & 16383;
972
- } else if (chunkType === "VP8L") {
973
- const dataStart = 20;
974
- if (buffer?.[dataStart] !== 47) {
975
- throw new Error("Invalid VP8L signature");
976
- }
977
- const bits = buffer.readUInt32LE(dataStart + 1);
978
- if (bits >>> 29 !== 0) {
979
- throw new Error("Invalid VP8L version");
980
- }
981
- colorSpace = bits & 1 << 8 ? "rgba" : "rgb";
982
- hasAlpha = !!(bits & 1 << 8);
983
- width = 1 + (bits & 16383);
984
- height = 1 + (bits >> 14 & 16383);
985
- } else {
986
- throw new Error("Unsupported WebP chunk");
987
- }
988
- return {
989
- width,
990
- height,
991
- format: "webp",
992
- frames,
993
- animated,
994
- hasAlpha,
995
- orientation: null,
996
- // No standard orientation in WebP
997
- aspectRatio: width / height,
998
- colorSpace,
999
- iccProfile,
1000
- exifDateTimeOriginal: null
1001
- // Can have EXIF chunk, but rare; add if needed
1002
- };
1003
- }
1004
- if (buffer.length >= 32 && buffer.toString("ascii", 4, 8) === "ftyp") {
1005
- const ftyp = this.findBox(buffer, "ftyp");
1006
- if (!ftyp) throw new Error("Invalid AVIF: No ftyp");
1007
- const brands = buffer.toString("ascii", ftyp.pos, ftyp.pos + ftyp.size);
1008
- const isAvif = brands.includes("avif");
1009
- const isAvis = brands.includes("avis");
1010
- if (!isAvif && !isAvis) throw new Error("Not an AVIF file");
1011
- const meta = this.findBox(buffer, "meta");
1012
- if (!meta) throw new Error("Invalid AVIF: No meta");
1013
- const metaSubStart = meta.pos + 4;
1014
- const metaSubEnd = meta.pos + meta.size;
1015
- const iprp = this.findBox(buffer, "iprp", metaSubStart, metaSubEnd);
1016
- if (!iprp) throw new Error("Invalid AVIF: No iprp");
1017
- const ipco = this.findBox(buffer, "ipco", iprp.pos, iprp.pos + iprp.size);
1018
- if (!ipco) throw new Error("Invalid AVIF: No ipco");
1019
- const ispe = this.findBox(buffer, "ispe", ipco.pos, ipco.pos + ipco.size);
1020
- if (!ispe) throw new Error("Invalid AVIF: No ispe");
1021
- if (buffer[ispe.pos] !== 0) throw new Error("Invalid ispe version");
1022
- const width = buffer.readUInt32BE(ispe.pos + 4);
1023
- const height = buffer.readUInt32BE(ispe.pos + 8);
1024
- let colorSpace = "rgb";
1025
- let hasAlpha = false;
1026
- let iccProfile = null;
1027
- const colr = this.findBox(buffer, "colr", ipco.pos, ipco.pos + ipco.size);
1028
- if (colr) {
1029
- const colrType = buffer.toString("ascii", colr.pos, colr.pos + 4);
1030
- if (colrType === "nclx") {
1031
- const matrix = buffer.readUInt16BE(colr.pos + 6);
1032
- colorSpace = matrix === 2 ? "rgb" : "ycbcr";
1033
- } else if (colrType === "rICC" || colrType === "prof") {
1034
- colorSpace = "unknown";
1035
- iccProfile = "embedded";
1036
- }
1037
- }
1038
- const auxC = this.findBox(buffer, "auxC", ipco.pos, ipco.pos + ipco.size);
1039
- if (auxC && buffer.toString("ascii", auxC.pos, auxC.pos + auxC.size).includes("alpha")) {
1040
- hasAlpha = true;
1041
- if (colorSpace === "rgb") {
1042
- colorSpace = "rgba";
1043
- } else if (colorSpace === "ycbcr") {
1044
- colorSpace = "ycck";
1045
- } else if (colorSpace === "grayscale" || colorSpace === "unknown") {
1046
- colorSpace = "grayscale-alpha";
1047
- }
1048
- }
1049
- const xmpXml = this.parseXmpFromAvif(buffer, meta, ipco);
1050
- let exifDateTimeOriginal = null;
1051
- if (xmpXml) {
1052
- let dateStart = xmpXml.indexOf('xmp:CreateDate="');
1053
- if (dateStart === -1)
1054
- dateStart = xmpXml.indexOf('photoshop:DateCreated="');
1055
- if (dateStart !== -1) {
1056
- dateStart += 16;
1057
- const dateEnd = xmpXml.indexOf('"', dateStart);
1058
- if (dateEnd !== -1) {
1059
- exifDateTimeOriginal = xmpXml.substring(dateStart, dateEnd);
1060
- }
1061
- }
1062
- }
1063
- let frames = 1;
1064
- let animated = isAvis;
1065
- if (animated) {
1066
- const iloc = this.findBox(buffer, "iloc", metaSubStart, metaSubEnd);
1067
- if (iloc) {
1068
- const version = buffer?.[iloc.pos] ?? 0;
1069
- const itemCountPos = iloc.pos + (version < 2 ? 4 : 6);
1070
- let itemCount = buffer?.readUInt16BE(itemCountPos) ?? 0;
1071
- if (version >= 2) itemCount = buffer?.readUInt32BE(itemCountPos) ?? 0;
1072
- frames = Math.max(1, Math.floor(itemCount / (hasAlpha ? 2 : 1)));
1073
- }
1074
- }
1075
- return {
1076
- width,
1077
- height,
1078
- format: "avif",
1079
- frames,
1080
- animated,
1081
- hasAlpha: hasAlpha ? true : null,
1082
- orientation: null,
1083
- // Can have 'irot' or 'imir' transforms, but rare
1084
- aspectRatio: width / height,
1085
- colorSpace,
1086
- iccProfile,
1087
- exifDateTimeOriginal
1088
- // Can have 'XMP' box, but parse XMP for date if needed
1089
- };
1090
- }
1091
- throw new Error("Unsupported image format or invalid file");
1092
- }
1093
- };
1094
-
1095
- // src/types/index.ts
1096
- var unitsObj = {
1097
- PB: 5,
1098
- TB: 4,
1099
- GB: 3,
1100
- MB: 2,
1101
- KB: 1,
1102
- B: 0
1103
- };
1104
-
1105
- // src/fs/index.ts
1106
- dotenv.config({ quiet: true });
1107
- var Fs = class extends ImageService {
1108
- constructor(cwd) {
1109
- super();
1110
- this.cwd = cwd;
1111
- cwd ??= process.cwd();
1112
- }
1113
- static {
1114
- __name(this, "Fs");
1115
- }
1116
- async getImageSpecs(filePath) {
1117
- const buffer = await this.fileToBufferAsync(filePath);
1118
- return this.getImageSpecsWorkup(buffer);
1119
- }
1120
- async getImageSpecsTmp(target) {
1121
- const buffer = await this.readTmpAsync(target);
1122
- return this.getImageSpecsWorkup(buffer);
1123
- }
1124
- get myEnv() {
1125
- return dotenv.config({ processEnv: {} });
1126
- }
1127
- get tmpDir() {
1128
- return (0, import_node_os.tmpdir)();
1129
- }
1130
- get tmpDirRelative() {
1131
- return (0, import_path.relative)(this.cwd, (0, import_node_os.tmpdir)());
1132
- }
1133
- parseDotEnv() {
1134
- return import_dotenv_expand.default.expand(this.myEnv);
1135
- }
1136
- /**
1137
- *
1138
- * @param target path to the file or directory to check for existence
1139
- * @returns true if the file or directory exists, false otherwise
1140
- * @example
1141
- * ```ts
1142
- * const fs = new Fs(process.cwd());
1143
- * const exists = fs.exists("my-file.txt");
1144
- * console.log(exists); // true if the file exists, false otherwise
1145
- * ```
1146
- * @description
1147
- * This method checks if a file or directory exists at the specified path input
1148
- *
1149
- * Additional Note:
1150
- *
1151
- * say you have a directory that begins with a dot, such as `.turbo`;
1152
- *
1153
- * in this scenario, both `./.turbo` and `.turbo` will return true if the directory exists
1154
- *
1155
- */
1156
- exists(target) {
1157
- if (!/\//gm.test(target)) {
1158
- if (/\./g.test(target)) {
1159
- return import_fs.default.existsSync((0, import_path.resolve)((0, import_path.join)(this.cwd, target)));
1160
- } else {
1161
- const statsSync = import_fs.default.statSync((0, import_path.resolve)((0, import_path.join)(this.cwd, target)), {
1162
- throwIfNoEntry: false
1163
- });
1164
- const isDir = statsSync?.isDirectory();
1165
- if (isDir) {
1166
- return isDir;
1167
- } else return false;
1168
- }
1169
- } else {
1170
- if (/\./g.test(target)) {
1171
- return import_fs.default.existsSync((0, import_path.relative)(this.cwd ?? process.cwd(), target));
1172
- } else {
1173
- const statsSync = import_fs.default.statSync((0, import_path.relative)(this.cwd, target), {
1174
- throwIfNoEntry: false
1175
- });
1176
- const isDir = statsSync?.isDirectory();
1177
- if (isDir) {
1178
- return isDir;
1179
- } else return false;
1180
- }
1181
- }
1182
- }
1183
- /**
1184
- *
1185
- * @param ms milliseconds to wait
1186
- * @returns a promise that resolves after the specified number of milliseconds
1187
- * @example
1188
- * ```ts
1189
- * const fs = new Fs(process.cwd());
1190
- * await fs.wait(1000); // waits for 1 second
1191
- * console.log("Done waiting!");
1192
- * ```
1193
- *
1194
- * Alternatively, you can use it like this:
1195
- * ```ts
1196
- * const fs = new Fs(process.cwd());
1197
- * fs.wait(1000).then(() => { // waits for 1 second
1198
- * console.log("Done waiting!");
1199
- * // do something after waiting
1200
- * });
1201
- * ```
1202
- *
1203
- * @description
1204
- * This method is useful for delaying execution in asynchronous code, such as when you need to wait for a file operation to complete or when you want to introduce a delay in a loop.
1205
- */
1206
- wait(ms) {
1207
- return new Promise((resolve2) => setTimeout(resolve2, ms));
1208
- }
1209
- /**
1210
- * Handles an array or readonly array of strings and/or Buffers, converting Buffers to strings
1211
- * @param arr An array or readonly array of strings and/or Buffers
1212
- * @returns An array of strings with Buffers converted to UTF-8 strings.
1213
- */
1214
- handleBuffStrArrUnion(arr) {
1215
- return arr.map(
1216
- (v) => Buffer.isBuffer(v) ? Buffer.from(v).toString("utf-8") : v
1217
- );
1218
- }
1219
- isRootPathTargeted(path) {
1220
- if (/^(?:\.\/|\.|\/|root|\.\.\/|~\/\.?|cwd|\.\/\.)$/g.test(path)) {
1221
- return true;
1222
- } else return false;
1223
- }
1224
- /**
1225
- *
1226
- * @param path path to the directory relative to the cwd
1227
- * @param options options for reading the directory, defaults to recursive
1228
- *
1229
- * The following two examples are equivalent:
1230
- *
1231
- * @example
1232
- * ```ts
1233
- * const fs = new Fs(process.cwd());
1234
- * const files = fs.readDir("./my-directory", { recursive: true });
1235
- * console.log(files);
1236
- * ```
1237
- * @example
1238
- * ```ts
1239
- * const fs = new Fs(process.cwd());
1240
- * const files = fs.readDir("my-directory", { recursive: true });
1241
- * console.log(files);
1242
- * ```
1243
- *
1244
- * @returns an array of strings representing the contents of the directory
1245
- */
1246
- readDir(path, options = {
1247
- recursive: true,
1248
- withFileTypes: false,
1249
- encoding: "utf-8"
1250
- }) {
1251
- if (this.isRootPathTargeted(path)) {
1252
- return this.handleBuffStrArrUnion(
1253
- import_fs.default.readdirSync((0, import_path.resolve)((0, import_path.join)(this.cwd, "./")), { ...options })
1254
- );
1255
- } else {
1256
- return this.handleBuffStrArrUnion(
1257
- import_fs.default.readdirSync(
1258
- (0, import_path.relative)(this.cwd ??= process.cwd(), path),
1259
- options
1260
- )
1261
- );
1262
- }
1263
- }
1264
- executeCommand = /* @__PURE__ */ __name(({
1265
- command,
1266
- ...options
1267
- }) => Buffer.from((0, import_child_process.execSync)(command, { ...options }).toJSON().data).toString(
1268
- "utf-8"
1269
- ), "executeCommand");
1270
- existsSync(path) {
1271
- return this.exists(path);
1272
- }
1273
- pathHandler(path) {
1274
- return /\//g.test(path) === true ? path.split(/([/])/gim).reverse().slice(2).reverse().join("") : path;
1275
- }
1276
- mkdirSync(path, options) {
1277
- return import_fs.default.mkdirSync((0, import_path.relative)(this.cwd, path), options);
1278
- }
1279
- units = unitsObj;
1280
- u = ["B", "KB", "MB", "GB", "TB", "PB"];
1281
- autoFileSizeRaw(size) {
1282
- let s = typeof size === "bigint" ? Number(size) : size;
1283
- let i = 0;
1284
- while (s >= 1024 && i < this.u.length - 1) {
1285
- s /= 1024;
1286
- i++;
1287
- }
1288
- return { value: s, unit: this.u[i] };
1289
- }
1290
- getSize(size, target, opts = { decimals: 4, includeUnits: true }) {
1291
- const { decimals, includeUnits } = opts;
1292
- if (target === "auto") {
1293
- const { value, unit } = this.autoFileSizeRaw(size);
1294
- const rounded2 = value.toFixed(decimals);
1295
- return includeUnits ? `${rounded2} ${unit}` : Number.parseFloat(rounded2);
1296
- }
1297
- const key = target.toUpperCase();
1298
- const exp = this.units[key];
1299
- const divisor = typeof size === "bigint" ? 1024n ** BigInt(exp) : 1024 ** exp;
1300
- let v = 0;
1301
- if (typeof size === "bigint" || typeof divisor === "bigint") {
1302
- if (typeof size === "bigint" && typeof divisor === "bigint")
1303
- v = Number(size / divisor);
1304
- else if (typeof size !== "bigint" && typeof divisor === "bigint")
1305
- v = size / Number(divisor);
1306
- else if (typeof size === "bigint" && typeof divisor !== "bigint")
1307
- v = Number(size) / divisor;
1308
- } else if (typeof size === "number" && typeof divisor === "number") {
1309
- v = size / divisor;
1310
- }
1311
- const rounded = v.toFixed(decimals);
1312
- return includeUnits ? `${rounded} ${key}` : Number.parseFloat(rounded);
1313
- }
1314
- fileSizeMb(path) {
1315
- return import_fs.default.statSync((0, import_path.relative)(this.cwd, path)).size / (1024 * 1024);
1316
- }
1317
- fileSize(path, target, opts) {
1318
- if (!this.exists(path)) throw new Error(`path ${path} does not exist`);
1319
- else {
1320
- return this.getSize(
1321
- import_fs.default.statSync((0, import_path.relative)(this.cwd, path)).size,
1322
- target,
1323
- opts
1324
- );
1325
- }
1326
- }
1327
- generateDirIfDNE(path, options) {
1328
- if (this.existsSync(path)) return;
1329
- else {
1330
- return this.mkdirSync(path, options);
1331
- }
1332
- }
1333
- withWs(path, data, options) {
1334
- try {
1335
- if (/\//g.test(path) === true) {
1336
- return this.generateDirIfDNE(this.pathHandler(path), {
1337
- recursive: true
1338
- });
1339
- } else return path;
1340
- } catch (error) {
1341
- console.error(
1342
- `[withWs error]: `.concat(
1343
- typeof error === "string" ? error : JSON.stringify(error, null, 2)
1344
- )
1345
- );
1346
- } finally {
1347
- return import_fs.default.createWriteStream(
1348
- (0, import_path.relative)(this.cwd ?? process.cwd(), path),
1349
- typeof options !== "undefined" ? typeof options === "object" ? options : options : { autoClose: true }
1350
- ).write(Buffer.from(Buffer.from(data).toJSON().data));
1351
- }
1352
- }
1353
- writeFileAsync = /* @__PURE__ */ __name(async (path, data, options) => {
1354
- try {
1355
- if (/\//g.test(path) === true)
1356
- return this.generateDirIfDNE(this.pathHandler(path), {
1357
- recursive: true
1358
- });
1359
- else return path;
1360
- } catch (error) {
1361
- console.error(
1362
- `[writeFileAsync error]: `.concat(
1363
- error instanceof Error ? error.message : typeof error === "string" ? error : JSON.stringify(error, null, 2)
1364
- )
1365
- );
1366
- } finally {
1367
- return await import_promises.default.writeFile(
1368
- (0, import_path.relative)(this.cwd ?? process.cwd(), path),
1369
- Buffer.from(Buffer.from(data).toJSON().data),
1370
- options
1371
- );
1372
- }
1373
- }, "writeFileAsync");
1374
- async unlink(path) {
1375
- if (this.existsSync(path)) {
1376
- return await import_promises.default.unlink((0, import_path.relative)(this.cwd, path));
1377
- } else {
1378
- throw new Error(`input path ${path} does not exist`);
1379
- }
1380
- }
1381
- rmFile(filePath) {
1382
- if (this.exists(filePath)) {
1383
- if (this.isRootPathTargeted(filePath)) {
1384
- import_fs.default.rmSync((0, import_path.resolve)((0, import_path.join)(this.cwd, filePath)));
1385
- } else import_fs.default.rmSync((0, import_path.resolve)(this.cwd, filePath));
1386
- } else return;
1387
- }
1388
- async rmdir(dir, options) {
1389
- const resolved = (0, import_path.relative)(this.cwd, dir);
1390
- if (this.exists(dir)) {
1391
- return import_promises.default.rmdir((0, import_path.relative)(this.cwd, dir), options);
1392
- } else {
1393
- throw new Error(`directory ${resolved} does not exist`);
1394
- }
1395
- }
1396
- rmDirSync(dir) {
1397
- const resolved = (0, import_path.resolve)(this.cwd, dir);
1398
- if (this.exists(dir)) {
1399
- return import_fs.default.rm(resolved, { force: true, recursive: true }, (err) => {
1400
- if (err?.message) {
1401
- console.error(err?.message);
1402
- }
1403
- });
1404
- } else {
1405
- throw new Error(`directory ${resolved} does not exist`);
1406
- }
1407
- }
1408
- fileToBuffer = /* @__PURE__ */ __name((path) => Buffer.from(
1409
- import_fs.default.readFileSync((0, import_path.relative)(this.cwd ?? process.cwd(), path)).toJSON().data
1410
- ), "fileToBuffer");
1411
- fileToBufferAsync = /* @__PURE__ */ __name(async (path) => {
1412
- return await import_promises.default.readFile((0, import_path.relative)(this.cwd, path));
1413
- }, "fileToBufferAsync");
1414
- dirContainsDir(readDir, targetDir, options) {
1415
- return this.readDir(readDir, options).filter((t) => t.split(".").length === 1).includes(targetDir);
1416
- }
1417
- async assetToBuffer(path) {
1418
- const [fetcher] = await Promise.all([
1419
- fetch(path).then((t) => t.arrayBuffer())
1420
- ]);
1421
- const mime = this.getMimeTypeForPath(path);
1422
- const b64encodedData = `data:${mime};base64, ${Buffer.from(fetcher).toString("base64")}`;
1423
- const extension = this.assetType(path) ?? "txt";
1424
- return {
1425
- b64encodedData,
1426
- extension
1427
- };
1428
- }
1429
- async assetToBufferView(path) {
1430
- const response = await fetch(path, { method: "GET" });
1431
- if (!response.ok) {
1432
- throw new Error(`Failed to fetch asset: ${response.statusText}`);
1433
- }
1434
- const reader = response.body?.getReader();
1435
- if (reader) {
1436
- const chunks = Array.of();
1437
- while (true) {
1438
- const { done, value } = await reader.read();
1439
- if (done) break;
1440
- if (value) chunks.push(value);
1441
- }
1442
- const totalLength = chunks.reduce((acc, chunk) => acc + chunk.length, 0);
1443
- const completeBuffer = new Uint8Array(totalLength);
1444
- let offset = 0;
1445
- for (const chunk of chunks) {
1446
- completeBuffer.set(chunk, offset);
1447
- offset += chunk.length;
1448
- }
1449
- const mime = this.getMimeTypeForPath(path);
1450
- const b64encodedData = `data:${mime};base64, ${Buffer.from(completeBuffer).toString("base64")}`;
1451
- const extension = this.assetType(path);
1452
- return { b64encodedData, extension };
1453
- } else {
1454
- const arrayBuffer = await response.arrayBuffer();
1455
- const mime = this.getMimeTypeForPath(path);
1456
- const b64encodedData = `data:${mime};base64, ${Buffer.from(arrayBuffer).toString("base64")}`;
1457
- const extension = this.assetType(path);
1458
- return { b64encodedData, extension };
1459
- }
1460
- }
1461
- formatHelper(f) {
1462
- if (/([A-Za-z]+-[A-Za-z]+)/g.test(f) === true) {
1463
- const formatting = f.split(/-/g).map((v) => v.substring(0, 1).toUpperCase().concat(v.substring(1))).join(" ");
1464
- return formatting;
1465
- } else return f.substring(0, 1).toUpperCase().concat(f.substring(1));
1466
- }
1467
- cleanDataUrl(props) {
1468
- return props.replace(
1469
- /^data:(?:image|application|haptics|video|text|font|model|audio|multipart)\/[A-Za-z0-9+-.]+(?:;[^,]+)*;base64,/i,
1470
- ""
1471
- );
1472
- }
1473
- /**
1474
- *
1475
- * @param inputUrl remote url to fetch data from
1476
- * @param outputPath desired output path relative to the cwd
1477
- * @param useDetectedExtension optional, defaults to true
1478
- *
1479
- * if `useDetectedExtension` is false you must include the file extension in your output path &rarr;
1480
- *
1481
- * 🚫 'public/assets/image-1'
1482
- *
1483
- * ✅ 'public/assets/image-1.png'
1484
- */
1485
- async fetchRemoteWriteLocal(inputUrl, outputPath, useDetectedExtension = true) {
1486
- try {
1487
- const result = await this.assetToBufferView(inputUrl);
1488
- const cleanData = this.cleanDataUrl(result.b64encodedData);
1489
- const formattedPath = useDetectedExtension ? `${outputPath}.${result.extension}` : outputPath;
1490
- if (/\./g.test(formattedPath) === false) {
1491
- throw new Error(
1492
- "either add false as the third argument in `fetchRemoteWriteLocal` (input, output, use-detected-file-extension) or provide an output path without a file extension"
1493
- );
1494
- }
1495
- this.withWs(formattedPath, Buffer.from(cleanData, "base64"));
1496
- } catch (err) {
1497
- return console.error(err);
1498
- }
1499
- }
1500
- knownToBlockHead(inputUrl) {
1501
- if (inputUrl.startsWith("https://github.com")) {
1502
- return "GET";
1503
- } else if (inputUrl.startsWith("https://raw.githubusercontent.com")) {
1504
- return "GET";
1505
- } else {
1506
- return "HEAD";
1507
- }
1508
- }
1509
- /**
1510
- *
1511
- * @param inputUrl remote url to fetch data from
1512
- * @param outputPath desired output path relative to the cwd
1513
- * @param useDetectedExtension optional, defaults to true
1514
- *
1515
- * if `useDetectedExtension` is false you must include the file extension in your output path &rarr;
1516
- *
1517
- * 🚫 'public/assets/image-1'
1518
- *
1519
- * ✅ 'public/assets/image-1.png'
1520
- *
1521
- * @description
1522
- * This method is designed for all files regardless of size, but especially for
1523
- * larger files that may not fit into memory (it intelligently determines the best approach on the fly)
1524
- * For files > 100 MB, it streams the data directly to disk instead of loading it all into memory
1525
- */
1526
- async fetchRemoteWriteLocalLargeFiles(inputUrl, outputPathI, useDetectedExtension = true) {
1527
- if (!URL.canParse(inputUrl))
1528
- throw new Error(`invalid URL ${inputUrl} is unable to be parsed`);
1529
- const MAX_SAFE_IN_MEMORY_MB = 100;
1530
- try {
1531
- const head = await fetch(inputUrl, {
1532
- method: this.knownToBlockHead(inputUrl)
1533
- });
1534
- const contentLength = head.headers.get("content-length");
1535
- const fileSizeMb = contentLength ? parseInt(contentLength, 10) / (1024 * 1024) : null;
1536
- let outputPath = outputPathI;
1537
- const assetTypeViaUrl = this.assetType(inputUrl);
1538
- const contentType = head.headers.get("content-type") ?? "application/octet-stream";
1539
- const formattedPath = useDetectedExtension ? `${outputPath}.${typeof assetTypeViaUrl === "undefined" ? this.toExtObj[contentType][0] : assetTypeViaUrl}` : outputPath;
1540
- this.generateDirIfDNE(this.pathHandler(formattedPath), {
1541
- recursive: true
1542
- });
1543
- if (fileSizeMb !== null && fileSizeMb > MAX_SAFE_IN_MEMORY_MB) {
1544
- const res = await fetch(inputUrl);
1545
- if (!res.ok || !res.body) {
1546
- throw new Error(`Failed to fetch asset: ${res.statusText}`);
1547
- }
1548
- const writeStream = import_fs.default.createWriteStream(
1549
- (0, import_path.relative)(this.cwd ?? process.cwd(), formattedPath)
1550
- );
1551
- const reader = res.body.getReader();
1552
- const pump = /* @__PURE__ */ __name(async () => {
1553
- while (true) {
1554
- const { done, value } = await reader.read();
1555
- if (done) break;
1556
- writeStream.write(value);
1557
- }
1558
- writeStream.end();
1559
- }, "pump");
1560
- await pump();
1561
- return;
1562
- }
1563
- const result = await this.assetToBufferView(inputUrl);
1564
- const cleanedData = this.cleanDataUrl(result.b64encodedData);
1565
- this.withWs(formattedPath, Buffer.from(cleanedData, "base64"));
1566
- } catch (err) {
1567
- console.error(`[fetchRemoteWriteLocalLargeFiles error]:`, err);
1568
- }
1569
- }
1570
- /**
1571
- *
1572
- * @access package-private
1573
- *
1574
- * work in progress, for internal package maintainer use only
1575
- */
1576
- // USE fluent-ffmpeg for video/animated image transforms (apng, etc)
1577
- // https://www.npmjs.com/package/fluent-ffmpeg
1578
- // https://www.npmjs.com/package/@types/fluent-ffmpeg
1579
- async imageTransform({
1580
- format,
1581
- target,
1582
- quality = 80,
1583
- tint,
1584
- resize
1585
- }) {
1586
- if (tint && !resize) {
1587
- return await (0, import_sharp.default)(target).toFormat(format, { quality }).tint(tint).toBuffer();
1588
- } else if (!tint && resize) {
1589
- return await (0, import_sharp.default)(target).toFormat(format, { quality }).resize(resize.widthOrOptions, resize.height, resize.options).toBuffer();
1590
- } else if (tint && resize) {
1591
- return await (0, import_sharp.default)(target).toFormat(format, { quality }).tint(tint).resize(resize.widthOrOptions, resize.height, resize.options).toBuffer();
1592
- } else {
1593
- return await (0, import_sharp.default)(target).toFormat(format, { quality }).toBuffer();
1594
- }
1595
- }
1596
- /**
1597
- * Write data to a file in the system's tmp directory
1598
- * @param filename The filename (can include subdirectories like "img-probe/file.txt")
1599
- * @param data The data to write
1600
- * @param options Optional write stream options
1601
- * @returns The full path to the written file
1602
- * @example
1603
- * ```ts
1604
- * const fs = new Fs(process.cwd());
1605
- * const tmpPath = fs.writeTmp("session-data.json", JSON.stringify(data));
1606
- * // Or with a subdirectory:
1607
- * fs.writeTmp("img-probe/output.png", imageBuffer);
1608
- * ```
1609
- */
1610
- writeTmp(filename, data, options) {
1611
- const fullPath = (0, import_path.resolve)(this.tmpDir, filename);
1612
- Promise.resolve(this.withWs(fullPath, data, options));
1613
- }
1614
- async readTmpAsync(filename) {
1615
- const fullPath = (0, import_path.resolve)(this.tmpDir, filename);
1616
- if (!this.exists(fullPath)) {
1617
- throw new Error(`Tmp file not found: ${filename}`);
1618
- }
1619
- return await this.fileToBufferAsync(fullPath);
1620
- }
1621
- /**
1622
- * Read a file from the tmp directory
1623
- * @param filename The filename to read (can include subdirectories)
1624
- * @returns Buffer containing the file data
1625
- * @example
1626
- * ```ts
1627
- * const fs = new Fs(process.cwd());
1628
- * const data = fs.readTmp("session-data.json");
1629
- * const parsed = JSON.parse(data.toString("utf-8"));
1630
- * ```
1631
- */
1632
- readTmp(filename) {
1633
- const fullPath = (0, import_path.resolve)(this.tmpDir, filename);
1634
- if (!this.exists(fullPath)) {
1635
- throw new Error(`Tmp file not found: ${filename}`);
1636
- }
1637
- return this.fileToBuffer(fullPath);
1638
- }
1639
- /**
1640
- * Scan the tmp directory for files matching a pattern
1641
- * @param pattern Optional pattern to filter files (e.g., "img-probe")
1642
- * @param options Options for directory reading (defaults to non-recursive to avoid permission issues)
1643
- * @returns Array of matching file paths relative to tmp directory
1644
- * @example
1645
- * ```ts
1646
- * const fs = new Fs(process.cwd());
1647
- * // Get all img-probe files
1648
- * const imgFiles = fs.scanTmp("img-probe");
1649
- * // Get all files in tmp (non-recursive)
1650
- * const allFiles = fs.scanTmp();
1651
- * ```
1652
- */
1653
- scanTmp(pattern, options = {
1654
- recursive: false,
1655
- withFileTypes: false,
1656
- encoding: "utf-8"
1657
- }) {
1658
- const dirs = (0, import_path.resolve)(this.tmpDir);
1659
- const tmpContents = this.readDir(dirs, options);
1660
- if (!pattern) {
1661
- return tmpContents;
1662
- }
1663
- if (typeof pattern === "string") {
1664
- return tmpContents.filter((t) => t.includes(pattern));
1665
- }
1666
- return tmpContents.filter((path) => {
1667
- return pattern.test(path);
1668
- });
1669
- }
1670
- /**
1671
- * Extract specific files from tmp directory to a target location
1672
- * @param pattern Pattern to match files (e.g., "img-probe")
1673
- * @param targetDir Target directory to extract files to
1674
- * @param options Options for extraction behavior
1675
- * @returns Array of extracted file paths
1676
- * @example
1677
- * ```ts
1678
- * const fs = new Fs(process.cwd());
1679
- * // Extract all img-probe files to ./output
1680
- * const extracted = fs.extractFromTmp("img-probe", "./output");
1681
- * // Extract with custom behavior
1682
- * fs.extractFromTmp("session-", "./sessions", {
1683
- * preserveStructure: true,
1684
- * cleanupAfter: true
1685
- * });
1686
- * ```
1687
- */
1688
- extractFromTmp(pattern, targetDir, options) {
1689
- const {
1690
- preserveStructure = false,
1691
- cleanupAfter = false,
1692
- overwrite = true
1693
- } = options ?? {};
1694
- const matchingFiles = this.scanTmp(pattern);
1695
- const extracted = [];
1696
- for (const file of matchingFiles) {
1697
- const sourcePath = (0, import_path.resolve)(this.tmpDir, file);
1698
- const lastSegment = file.includes("/") ? file.split("/").pop() : file;
1699
- if (!lastSegment) continue;
1700
- const targetPath = preserveStructure ? (0, import_path.resolve)(targetDir, file) : (0, import_path.resolve)(targetDir, lastSegment);
1701
- if (this.exists(targetPath) && !overwrite) {
1702
- console.warn(`Skipping existing file: ${targetPath}`);
1703
- continue;
1704
- }
1705
- const data = this.fileToBuffer(sourcePath);
1706
- this.withWs(targetPath, data);
1707
- extracted.push(targetPath);
1708
- if (cleanupAfter) {
1709
- this.rmFile(sourcePath);
1710
- }
1711
- }
1712
- return extracted;
1713
- }
1714
- /**
1715
- * Clean up tmp files matching a pattern
1716
- * @param pattern Pattern to match files for deletion
1717
- * @param maxAge Optional max age in milliseconds (only delete files older than this)
1718
- * @returns Number of files removed
1719
- * @example
1720
- * ```ts
1721
- * const fs = new Fs(process.cwd());
1722
- * // Remove all img-probe files
1723
- * fs.cleanupTmp("img-probe");
1724
- * // Remove session files older than 1 hour
1725
- * fs.cleanupTmp("session-", 60 * 60 * 1000);
1726
- * ```
1727
- */
1728
- cleanupTmp(pattern, maxAge) {
1729
- const matchingFiles = this.scanTmp(pattern);
1730
- let removed = 0;
1731
- for (const file of matchingFiles) {
1732
- const fullPath = (0, import_path.resolve)(this.tmpDir, file);
1733
- try {
1734
- const stats = import_fs.default.statSync(fullPath);
1735
- if (maxAge) {
1736
- const age = Date.now() - stats.mtimeMs;
1737
- if (age < maxAge) {
1738
- continue;
1739
- }
1740
- }
1741
- if (stats.isDirectory()) {
1742
- this.rmDirSync(fullPath);
1743
- } else {
1744
- this.rmFile(fullPath);
1745
- }
1746
- removed++;
1747
- } catch (err) {
1748
- console.warn(`Failed to remove tmp file ${file}:`, err);
1749
- }
1750
- }
1751
- return removed;
1752
- }
1753
- rmTmpFile(filename) {
1754
- const tmpPath = (0, import_path.resolve)(this.tmpDir, filename);
1755
- this.rmFile(tmpPath);
1756
- }
1757
- /**
1758
- * Generate a unique tmp filename with optional prefix
1759
- * @param prefix Optional prefix for the filename
1760
- * @param extension Optional file extension (without dot)
1761
- * @returns Unique filename
1762
- * @example
1763
- * ```ts
1764
- * const fs = new Fs(process.cwd());
1765
- * const filename = fs.uniqueTmpName("img-probe", "png");
1766
- * // Returns: "img-probe-1701234567890-a3b2c1.png"
1767
- * ```
1768
- */
1769
- uniqueTmpName(prefix, extension) {
1770
- const timestamp = Date.now();
1771
- const random = Math.random().toString(36).substring(2, 8);
1772
- const parts = [prefix ?? "tmp", timestamp, random].join("-");
1773
- return extension ? `${parts}.${extension}` : parts;
1774
- }
1775
- /**
1776
- * Async generator for cleaning tmp files with batched removal
1777
- * @param pattern Pattern to match files for deletion
1778
- * @param batchSize Number of files to remove per batch (default 10)
1779
- * @yields Progress information during cleanup
1780
- * @returns Final cleanup summary
1781
- * @example
1782
- * ```ts
1783
- * const fs = new Fs(process.cwd());
1784
- * // Clean up with progress tracking
1785
- * for await (const progress of fs.cleanTmpGenerator("session-", 25)) {
1786
- * console.log(progress);
1787
- * }
1788
- * ```
1789
- */
1790
- async *cleanTmpGenerator(pattern, batchSize = 10) {
1791
- const files = this.scanTmp(pattern);
1792
- const batches = await this.arrToArrOfArrs({
1793
- arrToFragment: files,
1794
- arrOfArrsAggregator: [],
1795
- interval: batchSize
1796
- });
1797
- let totalRemoved = 0;
1798
- for (const [index, batch] of batches.entries()) {
1799
- yield {
1800
- action: "removing",
1801
- batch: [...batch],
1802
- batchNumber: index + 1,
1803
- totalBatches: batches.length,
1804
- totalFound: files.length,
1805
- removed: totalRemoved
1806
- };
1807
- for (const file of batch) {
1808
- this.rmTmpFile(file);
1809
- totalRemoved++;
1810
- }
1811
- yield {
1812
- action: "batch-complete",
1813
- batchNumber: index + 1,
1814
- batchSize: batch.length,
1815
- totalRemoved,
1816
- remaining: files.length - totalRemoved
1817
- };
1818
- }
1819
- return {
1820
- action: "complete",
1821
- totalRemoved,
1822
- totalBatches: batches.length,
1823
- pattern: pattern.toString()
1824
- };
1825
- }
1826
- };
1827
- // Annotate the CommonJS export names for ESM import in node:
1828
- 0 && (module.exports = {
1829
- Fs,
1830
- ImageService,
1831
- MimeService,
1832
- UrlService,
1833
- UtilsService,
1834
- extMimeMap,
1835
- mimeToExt,
1836
- unitsObj
1837
- });
1838
- //# sourceMappingURL=index.cjs.map