@d0paminedriven/fs 6.1.0 → 6.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -36,6 +36,7 @@ __export(index_exports, {
36
36
  UrlService: () => UrlService,
37
37
  UtilsService: () => UtilsService,
38
38
  extMimeMap: () => extMimeMap,
39
+ mimeToExt: () => mimeToExt,
39
40
  unitsObj: () => unitsObj
40
41
  });
41
42
  module.exports = __toCommonJS(index_exports);
@@ -44,13 +45,142 @@ module.exports = __toCommonJS(index_exports);
44
45
  var import_child_process = require("child_process");
45
46
  var import_fs = __toESM(require("fs"), 1);
46
47
  var import_promises = __toESM(require("fs/promises"), 1);
48
+ var import_node_os = require("os");
47
49
  var import_path = require("path");
48
50
  var dotenv = __toESM(require("dotenv"), 1);
49
51
  var import_dotenv_expand = __toESM(require("dotenv-expand"), 1);
50
52
  var import_sharp = __toESM(require("sharp"), 1);
51
53
 
54
+ // src/utils/index.ts
55
+ var UtilsService = class {
56
+ static {
57
+ __name(this, "UtilsService");
58
+ }
59
+ chunkArray(arr, maxChunkLength) {
60
+ const chunks = Array.of();
61
+ let currentChunkLength = 0;
62
+ let currentChunk = Array.of();
63
+ for (const [index, val] of arr.entries()) {
64
+ if (val.length + currentChunkLength >= maxChunkLength) {
65
+ if (currentChunk.length) {
66
+ chunks.push(currentChunk);
67
+ }
68
+ currentChunkLength = val.length;
69
+ currentChunk = [val];
70
+ } else {
71
+ currentChunk.push(val);
72
+ currentChunkLength += val.length + 1;
73
+ }
74
+ if (arr.length === index + 1) {
75
+ chunks.push(currentChunk);
76
+ }
77
+ }
78
+ return chunks.length ? chunks : [arr];
79
+ }
80
+ b64ToBlob(b64Data) {
81
+ {
82
+ const sliceSize = 512;
83
+ const typeMatch = /^data:((?:image|application|haptics|video|text|font|model|audio|multipart)\/[A-Za-z0-9+-.]+(?:;[^,]+)*);base64,(.+)$/i.exec(
84
+ b64Data
85
+ );
86
+ if (!typeMatch) {
87
+ throw new Error(`${b64Data} is not a valid data Url`);
88
+ }
89
+ const type = typeMatch[1];
90
+ const base64Data = typeMatch?.[2] ?? "";
91
+ const byteCharacters = Buffer.from(base64Data, "base64").toString(
92
+ "binary"
93
+ );
94
+ const byteArrays = Array.of();
95
+ for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
96
+ const slice = byteCharacters.slice(offset, offset + sliceSize);
97
+ const byteNumbers = new Array(slice.length);
98
+ for (let i = 0; i < slice.length; i++) {
99
+ byteNumbers[i] = slice.charCodeAt(i);
100
+ }
101
+ const byteArray = new Uint8Array(byteNumbers);
102
+ byteArrays.push(byteArray);
103
+ }
104
+ const blob = new Blob(byteArrays, { type });
105
+ return blob;
106
+ }
107
+ }
108
+ arrToArrOfArrs = /* @__PURE__ */ __name(({
109
+ arrToFragment = Array.of(),
110
+ arrOfArrsAggregator = Array.of(),
111
+ interval
112
+ }) => new Promise(
113
+ (resolve2, _reject) => resolve2(
114
+ ((interval2) => {
115
+ for (let i = 0; i <= arrToFragment.length; i++) {
116
+ if ((i % interval2 === 0 || i === 0) && i <= arrToFragment.length) {
117
+ let segment = arrToFragment.slice(i, i + interval2);
118
+ arrOfArrsAggregator.push(segment);
119
+ }
120
+ }
121
+ })(interval)
122
+ )
123
+ ).then((_) => arrOfArrsAggregator), "arrToArrOfArrs");
124
+ extractTuple(obj, props) {
125
+ return [props, obj[props]];
126
+ }
127
+ sort(obj, order) {
128
+ return Object.fromEntries(
129
+ Object.entries(obj).sort(
130
+ ([a, _aa], [b, _bb]) => order === "DESC" ? b.localeCompare(a) - a.localeCompare(b) : a.localeCompare(b) - b.localeCompare(a)
131
+ )
132
+ );
133
+ }
134
+ excludeTargeted = /* @__PURE__ */ __name((obj, props, sort) => {
135
+ const resolve2 = Object.fromEntries(
136
+ Object.entries(obj).map(([key, val]) => {
137
+ if (props.includes(key)) {
138
+ return ["omit", "omit"];
139
+ } else return [key, val];
140
+ }).filter(([t, _v]) => /omit/.test(t) === false)
141
+ );
142
+ return typeof sort !== "undefined" ? this.sort(resolve2, sort) : resolve2;
143
+ }, "excludeTargeted");
144
+ includeTargeted = /* @__PURE__ */ __name((obj, props, sort) => {
145
+ const resolve2 = Object.fromEntries(
146
+ props.map((val) => this.extractTuple(obj, val))
147
+ );
148
+ return typeof sort !== "undefined" ? this.sort(resolve2, sort) : resolve2;
149
+ }, "includeTargeted");
150
+ countsSorter = /* @__PURE__ */ __name((counter, keySort = "ASC", valSort = "DESC") => Object.fromEntries(
151
+ Array.from(Object.entries(counter)).sort(
152
+ ([aStr, _aNum], [bStr, _bNum]) => keySort === "DESC" ? bStr.localeCompare(aStr) - aStr.localeCompare(bStr) : aStr.localeCompare(bStr) - bStr.localeCompare(aStr)
153
+ ).sort(([aStr, aNum], [bStr, bNum]) => {
154
+ if (typeof (aNum && bNum) === "number") {
155
+ return valSort === "ASC" ? aNum - bNum : bNum - aNum;
156
+ } else if (typeof (aNum && bNum) === "string") {
157
+ return valSort === "ASC" ? aStr.localeCompare(bStr) - bStr.localeCompare(aStr) : bStr.localeCompare(aStr) - aStr.localeCompare(bStr);
158
+ } else
159
+ throw new Error(
160
+ "only Record<string, string> and Record<string,number> types supported"
161
+ );
162
+ })
163
+ ), "countsSorter");
164
+ range(from, to) {
165
+ const values = Array.of();
166
+ for (let i = from; i < to; i++) {
167
+ values.push(i);
168
+ }
169
+ return values;
170
+ }
171
+ isPrimeNumber = /* @__PURE__ */ __name((n) => {
172
+ for (let i = 2; n > i; i++) {
173
+ if (n % i === 0) {
174
+ return false;
175
+ }
176
+ }
177
+ return n > 1;
178
+ }, "isPrimeNumber");
179
+ acceptor = /* @__PURE__ */ __name((num) => [...Array(num !== 0 ? num : this.range(num = -101, num = 101)).keys()].reverse().filter(this.isPrimeNumber), "acceptor");
180
+ };
181
+
52
182
  // src/url/index.ts
53
- var UrlService = class {
183
+ var UrlService = class extends UtilsService {
54
184
  static {
55
185
  __name(this, "UrlService");
56
186
  }
@@ -82,7 +212,7 @@ var extMimeMap = {
82
212
  avif: ["image/avif"],
83
213
  avi: ["video/x-msvideo"],
84
214
  azw: ["application/vnd.amazon.ebook"],
85
- bin: ["application/octet-stream"],
215
+ bin: ["application/octet-stream", "multipart/voice-message"],
86
216
  bmp: ["image/bmp"],
87
217
  bz: ["application/x-bzip"],
88
218
  bz2: ["application/x-bzip2"],
@@ -102,7 +232,7 @@ var extMimeMap = {
102
232
  gif: ["image/gif"],
103
233
  glb: ["model/gltf-binary"],
104
234
  gltf: ["model/gltf+json"],
105
- gz: ["application/x-gzip", "application/gzip"],
235
+ gz: ["application/gzip", "application/x-gzip"],
106
236
  hjif: ["haptics/hjif"],
107
237
  hmpg: ["haptics/hmpg"],
108
238
  htm: ["text/html"],
@@ -110,6 +240,7 @@ var extMimeMap = {
110
240
  ico: ["image/vnd.microsoft.icon"],
111
241
  ics: ["text/calendar"],
112
242
  ivs: ["haptics/ivs"],
243
+ ivt: ["haptics/ivs"],
113
244
  jar: ["application/java-archive"],
114
245
  jpeg: ["image/jpeg"],
115
246
  jpg: ["image/jpeg"],
@@ -131,7 +262,8 @@ var extMimeMap = {
131
262
  mpeg: ["video/mpeg"],
132
263
  mpkg: ["application/vnd.apple.installer+xml"],
133
264
  ndjson: ["application/x-ndjson"],
134
- obj: ["application/octet-stream", "text/plain", "model/obj"],
265
+ node: ["application/node", "text/javascript"],
266
+ obj: ["model/obj", "application/octet-stream", "text/plain"],
135
267
  odp: ["application/vnd.oasis.opendocument.presentation"],
136
268
  ods: ["application/vnd.oasis.opendocument.spreadsheet"],
137
269
  odt: ["application/vnd.oasis.opendocument.text"],
@@ -152,9 +284,11 @@ var extMimeMap = {
152
284
  py: ["text/x-python"],
153
285
  pyc: ["application/x-python-code"],
154
286
  rar: ["application/vnd.rar"],
287
+ rs: ["text/rust"],
155
288
  rtf: ["application/rtf"],
156
289
  sh: ["application/x-sh"],
157
290
  sql: ["application/sql"],
291
+ sse: ["text/event-stream"],
158
292
  svg: ["image/svg+xml"],
159
293
  tar: ["application/x-tar"],
160
294
  tif: ["image/tiff"],
@@ -184,6 +318,118 @@ var extMimeMap = {
184
318
  "3g2": ["video/3gpp2"],
185
319
  "7z": ["application/x-7z-compressed"]
186
320
  };
321
+ var mimeToExt = {
322
+ "application/epub+zip": ["epub"],
323
+ "application/font-sfnt": ["ttf"],
324
+ "application/gzip": ["gz"],
325
+ "application/java-archive": ["jar"],
326
+ "application/json": ["json"],
327
+ "application/ld+json": ["jsonld"],
328
+ "application/msword": ["doc"],
329
+ "application/node": ["node", "js"],
330
+ "application/octet-stream": ["bin", "obj"],
331
+ "application/ogg": ["ogx"],
332
+ "application/pdf": ["pdf"],
333
+ "application/rtf": ["rtf"],
334
+ "application/sql": ["sql"],
335
+ "application/toml": ["toml"],
336
+ "application/vnd.amazon.ebook": ["azw"],
337
+ "application/vnd.apple.installer+xml": ["mpkg"],
338
+ "application/vnd.apple.mpegurl": ["m3u8"],
339
+ "application/vnd.apple.pkpass": ["pkpass"],
340
+ "application/vnd.mozilla.xul+xml": ["xul"],
341
+ "application/vnd.ms-excel": ["xls"],
342
+ "application/vnd.ms-fontobject": ["eot"],
343
+ "application/vnd.ms-powerpoint": ["ppt"],
344
+ "application/vnd.oasis.opendocument.presentation": ["odp"],
345
+ "application/vnd.oasis.opendocument.spreadsheet": ["ods"],
346
+ "application/vnd.oasis.opendocument.text": ["odt"],
347
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation": [
348
+ "pptx"
349
+ ],
350
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": ["xlsx"],
351
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document": [
352
+ "docx"
353
+ ],
354
+ "application/vnd.rar": ["rar"],
355
+ "application/vnd.visio": ["vsd"],
356
+ "application/wasm": ["wasm"],
357
+ "application/x-7z-compressed": ["7z"],
358
+ "application/x-abiword": ["abw"],
359
+ "application/x-bzip": ["bz"],
360
+ "application/x-bzip2": ["bz2"],
361
+ "application/x-cdf": ["cda"],
362
+ "application/x-csh": ["csh"],
363
+ "application/x-freearc": ["arc"],
364
+ "application/x-gzip": ["gz"],
365
+ "application/x-httpd-php": ["php"],
366
+ "application/x-mdx": ["mdx"],
367
+ "application/x-ndjson": ["ndjson"],
368
+ "application/x-python-code": ["pyc"],
369
+ "application/x-sh": ["sh"],
370
+ "application/x-tar": ["tar"],
371
+ "application/x-zip-compressed": ["zip"],
372
+ "application/xhtml+xml": ["xhtml"],
373
+ "application/xml": ["xml"],
374
+ "application/yaml": ["yml", "yaml"],
375
+ "application/zip": ["zip"],
376
+ "audio/aac": ["aac"],
377
+ "audio/midi": ["mid"],
378
+ "audio/mp4": ["m4a"],
379
+ "audio/mpeg": ["mp3"],
380
+ "audio/ogg": ["opus", "ogg", "oga"],
381
+ "audio/wav": ["wav"],
382
+ "audio/x-midi": ["midi"],
383
+ "font/otf": ["otf"],
384
+ "font/ttf": ["ttf"],
385
+ "font/woff": ["woff"],
386
+ "font/woff2": ["woff2"],
387
+ "haptics/hjif": ["hjif"],
388
+ "haptics/hmpg": ["hmpg"],
389
+ "haptics/ivs": ["ivs", "ivt"],
390
+ "image/aces": ["aces"],
391
+ "image/apng": ["apng"],
392
+ "image/avci": ["avci"],
393
+ "image/avif": ["avif"],
394
+ "image/bmp": ["bmp"],
395
+ "image/dpx": ["dpx"],
396
+ "image/emf": ["emf"],
397
+ "image/gif": ["gif"],
398
+ "image/jpeg": ["jpg", "jpeg"],
399
+ "image/ktx": ["ktx"],
400
+ "image/ktx2": ["ktx2"],
401
+ "image/png": ["png"],
402
+ "image/svg+xml": ["svg"],
403
+ "image/tiff": ["tiff", "tif"],
404
+ "image/vnd.microsoft.icon": ["ico"],
405
+ "image/webp": ["webp"],
406
+ "model/gltf-binary": ["glb"],
407
+ "model/gltf+json": ["gltf"],
408
+ "model/obj": ["obj"],
409
+ "model/vnd.usdz+zip": ["usdz"],
410
+ "multipart/voice-message": ["bin"],
411
+ "text/calendar": ["ics"],
412
+ "text/css": ["css"],
413
+ "text/csv": ["csv"],
414
+ "text/event-stream": ["sse", "ts", "rs", "py", "txt"],
415
+ "text/html": ["html", "htm"],
416
+ "text/javascript": ["cjs", "js", "mjs"],
417
+ "text/markdown": ["md"],
418
+ "text/plain": ["txt"],
419
+ "text/rust": ["rs"],
420
+ "text/typescript": ["ts"],
421
+ "text/vtt": ["vtt"],
422
+ "text/x-python": ["py"],
423
+ "video/3gpp": ["3gp"],
424
+ "video/3gpp2": ["3g2"],
425
+ "video/mp2t": ["ts"],
426
+ "video/mp4": ["mp4", "m4v"],
427
+ "video/mpeg": ["mpeg"],
428
+ "video/ogg": ["ogv"],
429
+ "video/vnd.dlna.mpeg-tts": ["ts"],
430
+ "video/webm": ["weba"],
431
+ "video/x-msvideo": ["avi"]
432
+ };
187
433
  var MimeService = class extends UrlService {
188
434
  static {
189
435
  __name(this, "MimeService");
@@ -192,6 +438,35 @@ var MimeService = class extends UrlService {
192
438
  super();
193
439
  }
194
440
  mimeTypeObj = extMimeMap;
441
+ toExtObj = mimeToExt;
442
+ compareMimeToExt(p = "mime") {
443
+ let a = {};
444
+ if (p === "mime") {
445
+ for (const [_key, vals] of Object.entries(extMimeMap)) {
446
+ for (const val of vals) {
447
+ a[val] = (a[val] ?? 0) + 1;
448
+ }
449
+ }
450
+ for (const [key, _val] of Object.entries(mimeToExt)) {
451
+ a[key] = (a[key] ?? 0) + 1;
452
+ }
453
+ return Object.fromEntries(
454
+ Object.entries(a).sort(([_a, aa], [_b, bb]) => bb - aa)
455
+ );
456
+ } else {
457
+ for (const [_key, vals] of Object.entries(mimeToExt)) {
458
+ for (const val of vals) {
459
+ a[val] = (a[val] ?? 0) + 1;
460
+ }
461
+ }
462
+ for (const [key, _val] of Object.entries(extMimeMap)) {
463
+ a[key] = (a[key] ?? 0) + 1;
464
+ }
465
+ return Object.fromEntries(
466
+ Object.entries(a).sort(([_a, aa], [_b, bb]) => bb - aa)
467
+ );
468
+ }
469
+ }
195
470
  assetType(url) {
196
471
  const parsed = this.parseUrl(url);
197
472
  if (!parsed) return void 0;
@@ -236,6 +511,7 @@ var Fs = class extends MimeService {
236
511
  constructor(cwd) {
237
512
  super();
238
513
  this.cwd = cwd;
514
+ cwd ??= process.cwd();
239
515
  }
240
516
  static {
241
517
  __name(this, "Fs");
@@ -243,6 +519,12 @@ var Fs = class extends MimeService {
243
519
  get myEnv() {
244
520
  return dotenv.config({ processEnv: {} });
245
521
  }
522
+ get tmpDir() {
523
+ return (0, import_node_os.tmpdir)();
524
+ }
525
+ get tmpDirRelative() {
526
+ return (0, import_path.relative)(this.cwd, (0, import_node_os.tmpdir)());
527
+ }
246
528
  parseDotEnv() {
247
529
  return import_dotenv_expand.default.expand(this.myEnv);
248
530
  }
@@ -356,7 +638,11 @@ var Fs = class extends MimeService {
356
638
  *
357
639
  * @returns an array of strings representing the contents of the directory
358
640
  */
359
- readDir(path, options = { recursive: true }) {
641
+ readDir(path, options = {
642
+ recursive: true,
643
+ withFileTypes: false,
644
+ encoding: "utf-8"
645
+ }) {
360
646
  if (this.isRootPathTargeted(path)) {
361
647
  return this.handleBuffStrArrUnion(
362
648
  import_fs.default.readdirSync((0, import_path.resolve)((0, import_path.join)(this.cwd, "./")), { ...options })
@@ -517,6 +803,9 @@ var Fs = class extends MimeService {
517
803
  fileToBuffer = /* @__PURE__ */ __name((path) => Buffer.from(
518
804
  import_fs.default.readFileSync((0, import_path.relative)(this.cwd ?? process.cwd(), path)).toJSON().data
519
805
  ), "fileToBuffer");
806
+ fileToBufferAsync = /* @__PURE__ */ __name(async (path) => {
807
+ return await import_promises.default.readFile((0, import_path.relative)(this.cwd, path));
808
+ }, "fileToBufferAsync");
520
809
  dirContainsDir(readDir, targetDir, options) {
521
810
  return this.readDir(readDir, options).filter((t) => t.split(".").length === 1).includes(targetDir);
522
811
  }
@@ -533,10 +822,11 @@ var Fs = class extends MimeService {
533
822
  };
534
823
  }
535
824
  async assetToBufferView(path) {
536
- const response = await fetch(path);
825
+ const response = await fetch(path, { method: "GET" });
537
826
  if (!response.ok) {
538
827
  throw new Error(`Failed to fetch asset: ${response.statusText}`);
539
828
  }
829
+ console.log(Object.fromEntries(Array.from(response.headers.entries())));
540
830
  const reader = response.body?.getReader();
541
831
  if (reader) {
542
832
  const chunks = Array.of();
@@ -603,13 +893,37 @@ var Fs = class extends MimeService {
603
893
  return console.error(err);
604
894
  }
605
895
  }
606
- async fetchRemoteWriteLocalLargeFiles(inputUrl, outputPath, useDetectedExtension = true) {
896
+ /**
897
+ *
898
+ * @param inputUrl remote url to fetch data from
899
+ * @param outputPath desired output path relative to the cwd
900
+ * @param useDetectedExtension optional, defaults to true
901
+ *
902
+ * if `useDetectedExtension` is false you must include the file extension in your output path &rarr;
903
+ *
904
+ * 🚫 'public/assets/image-1'
905
+ *
906
+ * ✅ 'public/assets/image-1.png'
907
+ *
908
+ * @description
909
+ * This method is designed for large files that may not fit into memory.
910
+ * It streams the data directly to disk instead of loading it all into memory.
911
+ */
912
+ async fetchRemoteWriteLocalLargeFiles(inputUrl, outputPathI, useDetectedExtension = true) {
607
913
  const MAX_SAFE_IN_MEMORY_MB = 100;
608
914
  try {
609
- const head = await fetch(inputUrl, { method: "HEAD" });
915
+ const isGithubRaw = inputUrl.startsWith(
916
+ "https://raw.githubusercontent.com"
917
+ );
918
+ const head = await fetch(inputUrl, {
919
+ method: isGithubRaw ? "GET" : "HEAD"
920
+ });
610
921
  const contentLength = head.headers.get("content-length");
611
922
  const fileSizeMb = contentLength ? parseInt(contentLength, 10) / (1024 * 1024) : null;
612
- const formattedPath = useDetectedExtension ? `${outputPath}.${this.assetType(inputUrl)}` : outputPath;
923
+ let outputPath = outputPathI;
924
+ const assetTypeViaUrl = this.assetType(inputUrl);
925
+ const contentType = head.headers.get("content-type") ?? "application/octet-stream";
926
+ const formattedPath = useDetectedExtension ? `${outputPath}.${typeof assetTypeViaUrl === "undefined" ? this.toExtObj[contentType][0] : assetTypeViaUrl}` : outputPath;
613
927
  this.generateDirIfDNE(this.pathHandler(formattedPath), {
614
928
  recursive: true
615
929
  });
@@ -640,6 +954,149 @@ var Fs = class extends MimeService {
640
954
  console.error(`[fetchRemoteWriteLocalLargeFiles error]:`, err);
641
955
  }
642
956
  }
957
+ findBox(buffer, type, start = 0, end = buffer.length) {
958
+ let pos = start;
959
+ while (pos < end) {
960
+ let boxSize = buffer.readUInt32BE(pos);
961
+ let boxType = buffer.toString("ascii", pos + 4, pos + 8);
962
+ let hdrSize = 8;
963
+ if (boxSize === 1) {
964
+ boxSize = Number(buffer.readBigUInt64BE(pos + 8));
965
+ hdrSize = 16;
966
+ } else if (boxSize === 0) {
967
+ boxSize = end - pos;
968
+ }
969
+ if (boxType === type) {
970
+ return { pos: pos + hdrSize, size: boxSize - hdrSize };
971
+ }
972
+ pos += boxSize;
973
+ }
974
+ return null;
975
+ }
976
+ async getImageSize(filePath) {
977
+ const buffer = await this.fileToBufferAsync(filePath);
978
+ 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) {
979
+ if (buffer.readUint32BE(8) !== 13 || buffer?.[12] !== 73 || buffer?.[13] !== 72 || buffer?.[14] !== 68 || buffer?.[15] !== 82) {
980
+ throw new Error("IHDR Chunk of png not found or incorrect.");
981
+ }
982
+ return {
983
+ width: buffer.readUInt32BE(16),
984
+ height: buffer.readUInt32BE(20),
985
+ type: "png"
986
+ };
987
+ }
988
+ if (buffer.length >= 10 && buffer[0] === 255 && buffer[1] === 216) {
989
+ let pos = 2;
990
+ while (pos < buffer.length - 10) {
991
+ if (buffer[pos] !== 255) {
992
+ throw new Error("Invalid JPEG file");
993
+ }
994
+ const marker = buffer[pos + 1];
995
+ if (marker === 218) break;
996
+ const segmentSize = buffer.readUInt16BE(pos + 2);
997
+ if (!marker) {
998
+ throw new Error("no marker for jpeg");
999
+ }
1000
+ if (marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204) {
1001
+ return {
1002
+ width: buffer.readUInt16BE(pos + 7),
1003
+ height: buffer.readUInt16BE(pos + 5),
1004
+ type: "jpeg"
1005
+ };
1006
+ }
1007
+ pos += segmentSize + 2;
1008
+ }
1009
+ throw new Error("No dimensions found in JPEG file");
1010
+ }
1011
+ const gifHeader = buffer.toString("ascii", 0, 6);
1012
+ if (buffer.length >= 10 && (gifHeader === "GIF87a" || gifHeader === "GIF89a")) {
1013
+ return {
1014
+ width: buffer.readUInt16LE(6),
1015
+ height: buffer.readUInt16LE(8),
1016
+ type: "gif"
1017
+ };
1018
+ }
1019
+ if (buffer.length >= 26 && buffer[0] === 66 && buffer[1] === 77) {
1020
+ return {
1021
+ width: buffer.readInt32LE(18),
1022
+ height: Math.abs(buffer.readInt32LE(22)),
1023
+ type: "bmp"
1024
+ };
1025
+ }
1026
+ if (buffer.length >= 30 && buffer.toString("ascii", 0, 4) === "RIFF" && buffer.toString("ascii", 8, 12) === "WEBP") {
1027
+ const chunkType = buffer.toString("ascii", 12, 16);
1028
+ if (chunkType === "VP8X") {
1029
+ let widthSubtractOne = 0;
1030
+ let heightSubtractOne = 0;
1031
+ if (buffer?.[24] && buffer?.[25] && buffer?.[26]) {
1032
+ widthSubtractOne = buffer[24] | buffer[25] << 8 | buffer[26] << 16;
1033
+ }
1034
+ if (buffer?.[27] && buffer?.[28] && buffer?.[29]) {
1035
+ heightSubtractOne = buffer[27] | buffer[28] << 8 | buffer[29] << 16;
1036
+ }
1037
+ return {
1038
+ width: widthSubtractOne + 1,
1039
+ height: heightSubtractOne + 1,
1040
+ type: "webp"
1041
+ };
1042
+ } else if (chunkType === "VP8 ") {
1043
+ const dataStart = 20;
1044
+ if (buffer[dataStart + 3] !== 157 || buffer[dataStart + 4] !== 1 || buffer[dataStart + 5] !== 42) {
1045
+ throw new Error("Invalid VP8 keyframe");
1046
+ }
1047
+ const width = buffer.readUInt16LE(dataStart + 6) & 16383;
1048
+ const height = buffer.readUInt16LE(dataStart + 8) & 16383;
1049
+ return {
1050
+ width,
1051
+ height,
1052
+ type: "webp"
1053
+ };
1054
+ } else if (chunkType === "VP8L") {
1055
+ const dataStart = 20;
1056
+ if (buffer[dataStart] !== 47) {
1057
+ throw new Error("Invalid VP8L signature");
1058
+ }
1059
+ const bits = buffer.readUInt32LE(dataStart + 1);
1060
+ if (bits >>> 29 !== 0) {
1061
+ throw new Error("Invalid VP8L version");
1062
+ }
1063
+ const width = 1 + (bits & 16383);
1064
+ const height = 1 + (bits >> 14 & 16383);
1065
+ return {
1066
+ width,
1067
+ height,
1068
+ type: "webp"
1069
+ };
1070
+ }
1071
+ throw new Error("Unsupported WebP chunk");
1072
+ }
1073
+ if (buffer.length >= 32 && buffer.toString("ascii", 4, 8) === "ftyp") {
1074
+ const ftyp = this.findBox(buffer, "ftyp");
1075
+ if (!ftyp) throw new Error("Invalid AVIF: No ftyp");
1076
+ const brands = buffer.toString("ascii", ftyp.pos, ftyp.pos + ftyp.size);
1077
+ if (!brands.includes("avif") && !brands.includes("avis"))
1078
+ throw new Error("Not an AVIF file");
1079
+ const meta = this.findBox(buffer, "meta");
1080
+ if (!meta) throw new Error("Invalid AVIF: No meta");
1081
+ const metaSubStart = meta.pos + 4;
1082
+ const metaSubEnd = meta.pos + meta.size;
1083
+ const iprp = this.findBox(buffer, "iprp", metaSubStart, metaSubEnd);
1084
+ if (!iprp) throw new Error("Invalid AVIF: No iprp");
1085
+ const ipco = this.findBox(buffer, "ipco", iprp.pos, iprp.pos + iprp.size);
1086
+ if (!ipco) throw new Error("Invalid AVIF: No ipco");
1087
+ const ispe = this.findBox(buffer, "ispe", ipco.pos, ipco.pos + ipco.size);
1088
+ if (!ispe) throw new Error("Invalid AVIF: No ispe");
1089
+ if (buffer[ispe.pos] !== 0) throw new Error("Invalid ispe version");
1090
+ const width = buffer.readUInt32BE(ispe.pos + 4);
1091
+ const height = buffer.readUInt32BE(ispe.pos + 8);
1092
+ return {
1093
+ width,
1094
+ height,
1095
+ type: "avif"
1096
+ };
1097
+ }
1098
+ throw new Error("Unsupported image format or invalid file");
1099
+ }
643
1100
  /**
644
1101
  *
645
1102
  * @access package-private
@@ -666,129 +1123,229 @@ var Fs = class extends MimeService {
666
1123
  return await (0, import_sharp.default)(target).toFormat(format, { quality }).toBuffer();
667
1124
  }
668
1125
  }
669
- };
670
-
671
- // src/utils/index.ts
672
- var UtilsService = class {
673
- static {
674
- __name(this, "UtilsService");
1126
+ /**
1127
+ * Write data to a file in the system's tmp directory
1128
+ * @param filename The filename (can include subdirectories like "img-probe/file.txt")
1129
+ * @param data The data to write
1130
+ * @param options Optional write stream options
1131
+ * @returns The full path to the written file
1132
+ * @example
1133
+ * ```ts
1134
+ * const fs = new Fs(process.cwd());
1135
+ * const tmpPath = fs.writeTmp("session-data.json", JSON.stringify(data));
1136
+ * // Or with a subdirectory:
1137
+ * fs.writeTmp("img-probe/output.png", imageBuffer);
1138
+ * ```
1139
+ */
1140
+ writeTmp(filename, data, options) {
1141
+ const fullPath = (0, import_path.resolve)(this.tmpDir, filename);
1142
+ Promise.resolve(this.withWs(fullPath, data, options));
675
1143
  }
676
- chunkArray(arr, maxChunkLength) {
677
- const chunks = Array.of();
678
- let currentChunkLength = 0;
679
- let currentChunk = Array.of();
680
- for (const [index, val] of arr.entries()) {
681
- if (val.length + currentChunkLength >= maxChunkLength) {
682
- if (currentChunk.length) {
683
- chunks.push(currentChunk);
684
- }
685
- currentChunkLength = val.length;
686
- currentChunk = [val];
687
- } else {
688
- currentChunk.push(val);
689
- currentChunkLength += val.length + 1;
690
- }
691
- if (arr.length === index + 1) {
692
- chunks.push(currentChunk);
693
- }
1144
+ /**
1145
+ * Read a file from the tmp directory
1146
+ * @param filename The filename to read (can include subdirectories)
1147
+ * @returns Buffer containing the file data
1148
+ * @example
1149
+ * ```ts
1150
+ * const fs = new Fs(process.cwd());
1151
+ * const data = fs.readTmp("session-data.json");
1152
+ * const parsed = JSON.parse(data.toString("utf-8"));
1153
+ * ```
1154
+ */
1155
+ readTmp(filename) {
1156
+ const fullPath = (0, import_path.resolve)(this.tmpDir, filename);
1157
+ if (!this.exists(fullPath)) {
1158
+ throw new Error(`Tmp file not found: ${filename}`);
694
1159
  }
695
- return chunks.length ? chunks : [arr];
1160
+ return this.fileToBuffer(fullPath);
696
1161
  }
697
- b64ToBlob(b64Data) {
698
- {
699
- const sliceSize = 512;
700
- const typeMatch = b64Data.match(
701
- /^data:(?:image|application|haptics|video|text|font|model|audio|multipart)\/[A-Za-z0-9+-.]+(?:;[^,]+)*;base64,/i
702
- );
703
- const type = typeMatch?.[1];
704
- if (!typeMatch) {
705
- throw new Error(`${b64Data} is not a valid data Url`);
1162
+ /**
1163
+ * Scan the tmp directory for files matching a pattern
1164
+ * @param pattern Optional pattern to filter files (e.g., "img-probe")
1165
+ * @param options Options for directory reading (defaults to non-recursive to avoid permission issues)
1166
+ * @returns Array of matching file paths relative to tmp directory
1167
+ * @example
1168
+ * ```ts
1169
+ * const fs = new Fs(process.cwd());
1170
+ * // Get all img-probe files
1171
+ * const imgFiles = fs.scanTmp("img-probe");
1172
+ * // Get all files in tmp (non-recursive)
1173
+ * const allFiles = fs.scanTmp();
1174
+ * ```
1175
+ */
1176
+ scanTmp(pattern, options = {
1177
+ recursive: false,
1178
+ withFileTypes: false,
1179
+ encoding: "utf-8"
1180
+ }) {
1181
+ const dirs = (0, import_path.resolve)(this.tmpDir);
1182
+ const tmpContents = this.readDir(dirs, options);
1183
+ if (!pattern) {
1184
+ return tmpContents;
1185
+ }
1186
+ if (typeof pattern === "string") {
1187
+ return tmpContents.filter((t) => t.includes(pattern));
1188
+ }
1189
+ return tmpContents.filter((path) => {
1190
+ return pattern.test(path);
1191
+ });
1192
+ }
1193
+ /**
1194
+ * Extract specific files from tmp directory to a target location
1195
+ * @param pattern Pattern to match files (e.g., "img-probe")
1196
+ * @param targetDir Target directory to extract files to
1197
+ * @param options Options for extraction behavior
1198
+ * @returns Array of extracted file paths
1199
+ * @example
1200
+ * ```ts
1201
+ * const fs = new Fs(process.cwd());
1202
+ * // Extract all img-probe files to ./output
1203
+ * const extracted = fs.extractFromTmp("img-probe", "./output");
1204
+ * // Extract with custom behavior
1205
+ * fs.extractFromTmp("session-", "./sessions", {
1206
+ * preserveStructure: true,
1207
+ * cleanupAfter: true
1208
+ * });
1209
+ * ```
1210
+ */
1211
+ extractFromTmp(pattern, targetDir, options) {
1212
+ const {
1213
+ preserveStructure = false,
1214
+ cleanupAfter = false,
1215
+ overwrite = true
1216
+ } = options ?? {};
1217
+ const matchingFiles = this.scanTmp(pattern);
1218
+ const extracted = [];
1219
+ for (const file of matchingFiles) {
1220
+ const sourcePath = (0, import_path.resolve)(this.tmpDir, file);
1221
+ const lastSegment = file.includes("/") ? file.split("/").pop() : file;
1222
+ if (!lastSegment) continue;
1223
+ const targetPath = preserveStructure ? (0, import_path.resolve)(targetDir, file) : (0, import_path.resolve)(targetDir, lastSegment);
1224
+ if (this.exists(targetPath) && !overwrite) {
1225
+ console.warn(`Skipping existing file: ${targetPath}`);
1226
+ continue;
706
1227
  }
707
- const byteCharacters = Buffer.from(b64Data, "base64").toString("utf-8");
708
- const byteArrays = Array.of();
709
- for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
710
- const slice = byteCharacters.slice(offset, offset + sliceSize);
711
- const byteNumbers = Array.of();
712
- byteNumbers.push(slice.length);
713
- for (let i = 0; i < slice.length; i++) {
714
- byteNumbers[i] = slice.charCodeAt(i);
715
- }
716
- const byteArray = new Uint8Array(byteNumbers);
717
- byteArrays.push(byteArray);
1228
+ const data = this.fileToBuffer(sourcePath);
1229
+ this.withWs(targetPath, data);
1230
+ extracted.push(targetPath);
1231
+ if (cleanupAfter) {
1232
+ this.rmFile(sourcePath);
718
1233
  }
719
- const blob = new Blob(byteArrays, { type });
720
- return blob;
721
1234
  }
1235
+ return extracted;
722
1236
  }
723
- arrToArrOfArrs = /* @__PURE__ */ __name(({
724
- arrToFragment = Array.of(),
725
- arrOfArrsAggregator = Array.of(),
726
- interval
727
- }) => new Promise(
728
- (resolve2, _reject) => resolve2(
729
- ((interval2) => {
730
- for (let i = 0; i <= arrToFragment.length; i++) {
731
- if ((i % interval2 === 0 || i === 0) && i <= arrToFragment.length) {
732
- let segment = arrToFragment.slice(i, i + interval2);
733
- arrOfArrsAggregator.push(segment);
1237
+ /**
1238
+ * Clean up tmp files matching a pattern
1239
+ * @param pattern Pattern to match files for deletion
1240
+ * @param maxAge Optional max age in milliseconds (only delete files older than this)
1241
+ * @returns Number of files removed
1242
+ * @example
1243
+ * ```ts
1244
+ * const fs = new Fs(process.cwd());
1245
+ * // Remove all img-probe files
1246
+ * fs.cleanupTmp("img-probe");
1247
+ * // Remove session files older than 1 hour
1248
+ * fs.cleanupTmp("session-", 60 * 60 * 1000);
1249
+ * ```
1250
+ */
1251
+ cleanupTmp(pattern, maxAge) {
1252
+ const matchingFiles = this.scanTmp(pattern);
1253
+ let removed = 0;
1254
+ for (const file of matchingFiles) {
1255
+ const fullPath = (0, import_path.resolve)(this.tmpDir, file);
1256
+ try {
1257
+ const stats = import_fs.default.statSync(fullPath);
1258
+ if (maxAge) {
1259
+ const age = Date.now() - stats.mtimeMs;
1260
+ if (age < maxAge) {
1261
+ continue;
734
1262
  }
735
1263
  }
736
- })(interval)
737
- )
738
- ).then((_) => arrOfArrsAggregator), "arrToArrOfArrs");
739
- extractTuple(obj, props) {
740
- return [props, obj[props]];
1264
+ if (stats.isDirectory()) {
1265
+ this.rmDirSync(fullPath);
1266
+ } else {
1267
+ this.rmFile(fullPath);
1268
+ }
1269
+ removed++;
1270
+ } catch (err) {
1271
+ console.warn(`Failed to remove tmp file ${file}:`, err);
1272
+ }
1273
+ }
1274
+ return removed;
741
1275
  }
742
- sort(obj, order) {
743
- return Object.fromEntries(
744
- Object.entries(obj).sort(
745
- ([a, _aa], [b, _bb]) => order === "DESC" ? b.localeCompare(a) - a.localeCompare(b) : a.localeCompare(b) - b.localeCompare(a)
746
- )
747
- );
1276
+ rmTmpFile(filename) {
1277
+ const tmpPath = (0, import_path.resolve)(this.tmpDir, filename);
1278
+ this.rmFile(tmpPath);
748
1279
  }
749
- excludeTargeted = /* @__PURE__ */ __name((obj, props, sort) => {
750
- const resolve2 = Object.fromEntries(
751
- Object.entries(obj).map(([key, val]) => {
752
- if (props.includes(key)) {
753
- return ["omit", "omit"];
754
- } else return [key, val];
755
- }).filter(([t, _v]) => /omit/.test(t) === false)
756
- );
757
- return typeof sort !== "undefined" ? this.sort(resolve2, sort) : resolve2;
758
- }, "excludeTargeted");
759
- includeTargeted = /* @__PURE__ */ __name((obj, props, sort) => {
760
- const resolve2 = Object.fromEntries(
761
- props.map((val) => this.extractTuple(obj, val))
762
- );
763
- return typeof sort !== "undefined" ? this.sort(resolve2, sort) : resolve2;
764
- }, "includeTargeted");
765
- countsSorter = /* @__PURE__ */ __name(({
766
- counter,
767
- keySort,
768
- valSort
769
- }) => Object.fromEntries(
770
- Object.entries(counter).sort(
771
- ([aStr, _aNum], [bStr, _bNum]) => keySort === "DESC" ? bStr.localeCompare(aStr) - aStr.localeCompare(bStr) : aStr.localeCompare(bStr) - bStr.localeCompare(aStr)
772
- ).sort(
773
- ([_aStr, aNum], [_bStr, bNum]) => valSort === "ASC" ? aNum - bNum : bNum - aNum
774
- )
775
- ), "countsSorter");
776
- range(from, to) {
777
- const values = Array.of();
778
- for (let i = from; i < to; i++) {
779
- values.push(i);
780
- }
781
- return values;
1280
+ /**
1281
+ * Generate a unique tmp filename with optional prefix
1282
+ * @param prefix Optional prefix for the filename
1283
+ * @param extension Optional file extension (without dot)
1284
+ * @returns Unique filename
1285
+ * @example
1286
+ * ```ts
1287
+ * const fs = new Fs(process.cwd());
1288
+ * const filename = fs.uniqueTmpName("img-probe", "png");
1289
+ * // Returns: "img-probe-1701234567890-a3b2c1.png"
1290
+ * ```
1291
+ */
1292
+ uniqueTmpName(prefix, extension) {
1293
+ const timestamp = Date.now();
1294
+ const random = Math.random().toString(36).substring(2, 8);
1295
+ const parts = [prefix ?? "tmp", timestamp, random].join("-");
1296
+ return extension ? `${parts}.${extension}` : parts;
782
1297
  }
783
- isPrimeNumber = /* @__PURE__ */ __name((n) => {
784
- for (let i = 2; n > i; i++) {
785
- if (n % i === 0) {
786
- return false;
1298
+ /**
1299
+ * Async generator for cleaning tmp files with batched removal
1300
+ * @param pattern Pattern to match files for deletion
1301
+ * @param batchSize Number of files to remove per batch (default 10)
1302
+ * @yields Progress information during cleanup
1303
+ * @returns Final cleanup summary
1304
+ * @example
1305
+ * ```ts
1306
+ * const fs = new Fs(process.cwd());
1307
+ * // Clean up with progress tracking
1308
+ * for await (const progress of fs.cleanTmpGenerator("session-", 25)) {
1309
+ * console.log(progress);
1310
+ * }
1311
+ * ```
1312
+ */
1313
+ async *cleanTmpGenerator(pattern, batchSize = 10) {
1314
+ const files = this.scanTmp(pattern);
1315
+ const batches = await this.arrToArrOfArrs({
1316
+ arrToFragment: files,
1317
+ arrOfArrsAggregator: [],
1318
+ interval: batchSize
1319
+ });
1320
+ let totalRemoved = 0;
1321
+ for (const [index, batch] of batches.entries()) {
1322
+ yield {
1323
+ action: "removing",
1324
+ batch: [...batch],
1325
+ batchNumber: index + 1,
1326
+ totalBatches: batches.length,
1327
+ totalFound: files.length,
1328
+ removed: totalRemoved
1329
+ };
1330
+ for (const file of batch) {
1331
+ this.rmTmpFile(file);
1332
+ totalRemoved++;
787
1333
  }
1334
+ yield {
1335
+ action: "batch-complete",
1336
+ batchNumber: index + 1,
1337
+ batchSize: batch.length,
1338
+ totalRemoved,
1339
+ remaining: files.length - totalRemoved
1340
+ };
788
1341
  }
789
- return n > 1;
790
- }, "isPrimeNumber");
791
- acceptor = /* @__PURE__ */ __name((num) => [...Array(num !== 0 ? num : this.range(num = -101, num = 101)).keys()].reverse().filter(this.isPrimeNumber), "acceptor");
1342
+ return {
1343
+ action: "complete",
1344
+ totalRemoved,
1345
+ totalBatches: batches.length,
1346
+ pattern: pattern.toString()
1347
+ };
1348
+ }
792
1349
  };
793
1350
  // Annotate the CommonJS export names for ESM import in node:
794
1351
  0 && (module.exports = {
@@ -797,6 +1354,7 @@ var UtilsService = class {
797
1354
  UrlService,
798
1355
  UtilsService,
799
1356
  extMimeMap,
1357
+ mimeToExt,
800
1358
  unitsObj
801
1359
  });
802
1360
  //# sourceMappingURL=index.cjs.map