@d0paminedriven/fs 6.1.0 → 6.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.
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,6 +45,7 @@ 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);
@@ -82,7 +84,7 @@ var extMimeMap = {
82
84
  avif: ["image/avif"],
83
85
  avi: ["video/x-msvideo"],
84
86
  azw: ["application/vnd.amazon.ebook"],
85
- bin: ["application/octet-stream"],
87
+ bin: ["application/octet-stream", "multipart/voice-message"],
86
88
  bmp: ["image/bmp"],
87
89
  bz: ["application/x-bzip"],
88
90
  bz2: ["application/x-bzip2"],
@@ -102,7 +104,7 @@ var extMimeMap = {
102
104
  gif: ["image/gif"],
103
105
  glb: ["model/gltf-binary"],
104
106
  gltf: ["model/gltf+json"],
105
- gz: ["application/x-gzip", "application/gzip"],
107
+ gz: ["application/gzip", "application/x-gzip"],
106
108
  hjif: ["haptics/hjif"],
107
109
  hmpg: ["haptics/hmpg"],
108
110
  htm: ["text/html"],
@@ -110,6 +112,7 @@ var extMimeMap = {
110
112
  ico: ["image/vnd.microsoft.icon"],
111
113
  ics: ["text/calendar"],
112
114
  ivs: ["haptics/ivs"],
115
+ ivt: ["haptics/ivs"],
113
116
  jar: ["application/java-archive"],
114
117
  jpeg: ["image/jpeg"],
115
118
  jpg: ["image/jpeg"],
@@ -131,7 +134,8 @@ var extMimeMap = {
131
134
  mpeg: ["video/mpeg"],
132
135
  mpkg: ["application/vnd.apple.installer+xml"],
133
136
  ndjson: ["application/x-ndjson"],
134
- obj: ["application/octet-stream", "text/plain", "model/obj"],
137
+ node: ["application/node", "text/javascript"],
138
+ obj: ["model/obj", "application/octet-stream", "text/plain"],
135
139
  odp: ["application/vnd.oasis.opendocument.presentation"],
136
140
  ods: ["application/vnd.oasis.opendocument.spreadsheet"],
137
141
  odt: ["application/vnd.oasis.opendocument.text"],
@@ -152,9 +156,11 @@ var extMimeMap = {
152
156
  py: ["text/x-python"],
153
157
  pyc: ["application/x-python-code"],
154
158
  rar: ["application/vnd.rar"],
159
+ rs: ["text/rust"],
155
160
  rtf: ["application/rtf"],
156
161
  sh: ["application/x-sh"],
157
162
  sql: ["application/sql"],
163
+ sse: ["text/event-stream"],
158
164
  svg: ["image/svg+xml"],
159
165
  tar: ["application/x-tar"],
160
166
  tif: ["image/tiff"],
@@ -184,6 +190,118 @@ var extMimeMap = {
184
190
  "3g2": ["video/3gpp2"],
185
191
  "7z": ["application/x-7z-compressed"]
186
192
  };
193
+ var mimeToExt = {
194
+ "application/epub+zip": ["epub"],
195
+ "application/font-sfnt": ["ttf"],
196
+ "application/gzip": ["gz"],
197
+ "application/java-archive": ["jar"],
198
+ "application/json": ["json"],
199
+ "application/ld+json": ["jsonld"],
200
+ "application/msword": ["doc"],
201
+ "application/node": ["node", "js"],
202
+ "application/octet-stream": ["bin", "obj"],
203
+ "application/ogg": ["ogx"],
204
+ "application/pdf": ["pdf"],
205
+ "application/rtf": ["rtf"],
206
+ "application/sql": ["sql"],
207
+ "application/toml": ["toml"],
208
+ "application/vnd.amazon.ebook": ["azw"],
209
+ "application/vnd.apple.installer+xml": ["mpkg"],
210
+ "application/vnd.apple.mpegurl": ["m3u8"],
211
+ "application/vnd.apple.pkpass": ["pkpass"],
212
+ "application/vnd.mozilla.xul+xml": ["xul"],
213
+ "application/vnd.ms-excel": ["xls"],
214
+ "application/vnd.ms-fontobject": ["eot"],
215
+ "application/vnd.ms-powerpoint": ["ppt"],
216
+ "application/vnd.oasis.opendocument.presentation": ["odp"],
217
+ "application/vnd.oasis.opendocument.spreadsheet": ["ods"],
218
+ "application/vnd.oasis.opendocument.text": ["odt"],
219
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation": [
220
+ "pptx"
221
+ ],
222
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": ["xlsx"],
223
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document": [
224
+ "docx"
225
+ ],
226
+ "application/vnd.rar": ["rar"],
227
+ "application/vnd.visio": ["vsd"],
228
+ "application/wasm": ["wasm"],
229
+ "application/x-7z-compressed": ["7z"],
230
+ "application/x-abiword": ["abw"],
231
+ "application/x-bzip": ["bz"],
232
+ "application/x-bzip2": ["bz2"],
233
+ "application/x-cdf": ["cda"],
234
+ "application/x-csh": ["csh"],
235
+ "application/x-freearc": ["arc"],
236
+ "application/x-gzip": ["gz"],
237
+ "application/x-httpd-php": ["php"],
238
+ "application/x-mdx": ["mdx"],
239
+ "application/x-ndjson": ["ndjson"],
240
+ "application/x-python-code": ["pyc"],
241
+ "application/x-sh": ["sh"],
242
+ "application/x-tar": ["tar"],
243
+ "application/x-zip-compressed": ["zip"],
244
+ "application/xhtml+xml": ["xhtml"],
245
+ "application/xml": ["xml"],
246
+ "application/yaml": ["yml", "yaml"],
247
+ "application/zip": ["zip"],
248
+ "audio/aac": ["aac"],
249
+ "audio/midi": ["mid"],
250
+ "audio/mp4": ["m4a"],
251
+ "audio/mpeg": ["mp3"],
252
+ "audio/ogg": ["opus", "ogg", "oga"],
253
+ "audio/wav": ["wav"],
254
+ "audio/x-midi": ["midi"],
255
+ "font/otf": ["otf"],
256
+ "font/ttf": ["ttf"],
257
+ "font/woff": ["woff"],
258
+ "font/woff2": ["woff2"],
259
+ "haptics/hjif": ["hjif"],
260
+ "haptics/hmpg": ["hmpg"],
261
+ "haptics/ivs": ["ivs", "ivt"],
262
+ "image/aces": ["aces"],
263
+ "image/apng": ["apng"],
264
+ "image/avci": ["avci"],
265
+ "image/avif": ["avif"],
266
+ "image/bmp": ["bmp"],
267
+ "image/dpx": ["dpx"],
268
+ "image/emf": ["emf"],
269
+ "image/gif": ["gif"],
270
+ "image/jpeg": ["jpg", "jpeg"],
271
+ "image/ktx": ["ktx"],
272
+ "image/ktx2": ["ktx2"],
273
+ "image/png": ["png"],
274
+ "image/svg+xml": ["svg"],
275
+ "image/tiff": ["tiff", "tif"],
276
+ "image/vnd.microsoft.icon": ["ico"],
277
+ "image/webp": ["webp"],
278
+ "model/gltf-binary": ["glb"],
279
+ "model/gltf+json": ["gltf"],
280
+ "model/obj": ["obj"],
281
+ "model/vnd.usdz+zip": ["usdz"],
282
+ "multipart/voice-message": ["bin"],
283
+ "text/calendar": ["ics"],
284
+ "text/css": ["css"],
285
+ "text/csv": ["csv"],
286
+ "text/event-stream": ["sse", "ts", "rs", "py", "txt"],
287
+ "text/html": ["html", "htm"],
288
+ "text/javascript": ["cjs", "js", "mjs"],
289
+ "text/markdown": ["md"],
290
+ "text/plain": ["txt"],
291
+ "text/rust": ["rs"],
292
+ "text/typescript": ["ts"],
293
+ "text/vtt": ["vtt"],
294
+ "text/x-python": ["py"],
295
+ "video/3gpp": ["3gp"],
296
+ "video/3gpp2": ["3g2"],
297
+ "video/mp2t": ["ts"],
298
+ "video/mp4": ["mp4", "m4v"],
299
+ "video/mpeg": ["mpeg"],
300
+ "video/ogg": ["ogv"],
301
+ "video/vnd.dlna.mpeg-tts": ["ts"],
302
+ "video/webm": ["weba"],
303
+ "video/x-msvideo": ["avi"]
304
+ };
187
305
  var MimeService = class extends UrlService {
188
306
  static {
189
307
  __name(this, "MimeService");
@@ -192,6 +310,35 @@ var MimeService = class extends UrlService {
192
310
  super();
193
311
  }
194
312
  mimeTypeObj = extMimeMap;
313
+ toExtObj = mimeToExt;
314
+ compareMimeToExt(p = "mime") {
315
+ let a = {};
316
+ if (p === "mime") {
317
+ for (const [_key, vals] of Object.entries(extMimeMap)) {
318
+ for (const val of vals) {
319
+ a[val] = (a[val] ?? 0) + 1;
320
+ }
321
+ }
322
+ for (const [key, _val] of Object.entries(mimeToExt)) {
323
+ a[key] = (a[key] ?? 0) + 1;
324
+ }
325
+ return Object.fromEntries(
326
+ Object.entries(a).sort(([_a, aa], [_b, bb]) => bb - aa)
327
+ );
328
+ } else {
329
+ for (const [_key, vals] of Object.entries(mimeToExt)) {
330
+ for (const val of vals) {
331
+ a[val] = (a[val] ?? 0) + 1;
332
+ }
333
+ }
334
+ for (const [key, _val] of Object.entries(extMimeMap)) {
335
+ a[key] = (a[key] ?? 0) + 1;
336
+ }
337
+ return Object.fromEntries(
338
+ Object.entries(a).sort(([_a, aa], [_b, bb]) => bb - aa)
339
+ );
340
+ }
341
+ }
195
342
  assetType(url) {
196
343
  const parsed = this.parseUrl(url);
197
344
  if (!parsed) return void 0;
@@ -236,6 +383,7 @@ var Fs = class extends MimeService {
236
383
  constructor(cwd) {
237
384
  super();
238
385
  this.cwd = cwd;
386
+ cwd ??= process.cwd();
239
387
  }
240
388
  static {
241
389
  __name(this, "Fs");
@@ -243,6 +391,12 @@ var Fs = class extends MimeService {
243
391
  get myEnv() {
244
392
  return dotenv.config({ processEnv: {} });
245
393
  }
394
+ get tmpDir() {
395
+ return (0, import_node_os.tmpdir)();
396
+ }
397
+ get tmpDirRelative() {
398
+ return (0, import_path.relative)(this.cwd, (0, import_node_os.tmpdir)());
399
+ }
246
400
  parseDotEnv() {
247
401
  return import_dotenv_expand.default.expand(this.myEnv);
248
402
  }
@@ -356,7 +510,11 @@ var Fs = class extends MimeService {
356
510
  *
357
511
  * @returns an array of strings representing the contents of the directory
358
512
  */
359
- readDir(path, options = { recursive: true }) {
513
+ readDir(path, options = {
514
+ recursive: true,
515
+ withFileTypes: false,
516
+ encoding: "utf-8"
517
+ }) {
360
518
  if (this.isRootPathTargeted(path)) {
361
519
  return this.handleBuffStrArrUnion(
362
520
  import_fs.default.readdirSync((0, import_path.resolve)((0, import_path.join)(this.cwd, "./")), { ...options })
@@ -517,6 +675,9 @@ var Fs = class extends MimeService {
517
675
  fileToBuffer = /* @__PURE__ */ __name((path) => Buffer.from(
518
676
  import_fs.default.readFileSync((0, import_path.relative)(this.cwd ?? process.cwd(), path)).toJSON().data
519
677
  ), "fileToBuffer");
678
+ fileToBufferAsync = /* @__PURE__ */ __name(async (path) => {
679
+ return await import_promises.default.readFile((0, import_path.relative)(this.cwd, path));
680
+ }, "fileToBufferAsync");
520
681
  dirContainsDir(readDir, targetDir, options) {
521
682
  return this.readDir(readDir, options).filter((t) => t.split(".").length === 1).includes(targetDir);
522
683
  }
@@ -533,10 +694,11 @@ var Fs = class extends MimeService {
533
694
  };
534
695
  }
535
696
  async assetToBufferView(path) {
536
- const response = await fetch(path);
697
+ const response = await fetch(path, { method: "GET" });
537
698
  if (!response.ok) {
538
699
  throw new Error(`Failed to fetch asset: ${response.statusText}`);
539
700
  }
701
+ console.log(Object.fromEntries(Array.from(response.headers.entries())));
540
702
  const reader = response.body?.getReader();
541
703
  if (reader) {
542
704
  const chunks = Array.of();
@@ -603,13 +765,37 @@ var Fs = class extends MimeService {
603
765
  return console.error(err);
604
766
  }
605
767
  }
606
- async fetchRemoteWriteLocalLargeFiles(inputUrl, outputPath, useDetectedExtension = true) {
768
+ /**
769
+ *
770
+ * @param inputUrl remote url to fetch data from
771
+ * @param outputPath desired output path relative to the cwd
772
+ * @param useDetectedExtension optional, defaults to true
773
+ *
774
+ * if `useDetectedExtension` is false you must include the file extension in your output path →
775
+ *
776
+ * 🚫 'public/assets/image-1'
777
+ *
778
+ * ✅ 'public/assets/image-1.png'
779
+ *
780
+ * @description
781
+ * This method is designed for large files that may not fit into memory.
782
+ * It streams the data directly to disk instead of loading it all into memory.
783
+ */
784
+ async fetchRemoteWriteLocalLargeFiles(inputUrl, outputPathI, useDetectedExtension = true) {
607
785
  const MAX_SAFE_IN_MEMORY_MB = 100;
608
786
  try {
609
- const head = await fetch(inputUrl, { method: "HEAD" });
787
+ const isGithubRaw = inputUrl.startsWith(
788
+ "https://raw.githubusercontent.com"
789
+ );
790
+ const head = await fetch(inputUrl, {
791
+ method: isGithubRaw ? "GET" : "HEAD"
792
+ });
610
793
  const contentLength = head.headers.get("content-length");
611
794
  const fileSizeMb = contentLength ? parseInt(contentLength, 10) / (1024 * 1024) : null;
612
- const formattedPath = useDetectedExtension ? `${outputPath}.${this.assetType(inputUrl)}` : outputPath;
795
+ let outputPath = outputPathI;
796
+ const assetTypeViaUrl = this.assetType(inputUrl);
797
+ const contentType = head.headers.get("content-type") ?? "application/octet-stream";
798
+ const formattedPath = useDetectedExtension ? `${outputPath}.${typeof assetTypeViaUrl === "undefined" ? this.toExtObj[contentType][0] : assetTypeViaUrl}` : outputPath;
613
799
  this.generateDirIfDNE(this.pathHandler(formattedPath), {
614
800
  recursive: true
615
801
  });
@@ -640,6 +826,149 @@ var Fs = class extends MimeService {
640
826
  console.error(`[fetchRemoteWriteLocalLargeFiles error]:`, err);
641
827
  }
642
828
  }
829
+ findBox(buffer, type, start = 0, end = buffer.length) {
830
+ let pos = start;
831
+ while (pos < end) {
832
+ let boxSize = buffer.readUInt32BE(pos);
833
+ let boxType = buffer.toString("ascii", pos + 4, pos + 8);
834
+ let hdrSize = 8;
835
+ if (boxSize === 1) {
836
+ boxSize = Number(buffer.readBigUInt64BE(pos + 8));
837
+ hdrSize = 16;
838
+ } else if (boxSize === 0) {
839
+ boxSize = end - pos;
840
+ }
841
+ if (boxType === type) {
842
+ return { pos: pos + hdrSize, size: boxSize - hdrSize };
843
+ }
844
+ pos += boxSize;
845
+ }
846
+ return null;
847
+ }
848
+ async getImageSize(filePath) {
849
+ const buffer = await this.fileToBufferAsync(filePath);
850
+ 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) {
851
+ if (buffer.readUint32BE(8) !== 13 || buffer?.[12] !== 73 || buffer?.[13] !== 72 || buffer?.[14] !== 68 || buffer?.[15] !== 82) {
852
+ throw new Error("IHDR Chunk of png not found or incorrect.");
853
+ }
854
+ return {
855
+ width: buffer.readUInt32BE(16),
856
+ height: buffer.readUInt32BE(20),
857
+ type: "png"
858
+ };
859
+ }
860
+ if (buffer.length >= 10 && buffer[0] === 255 && buffer[1] === 216) {
861
+ let pos = 2;
862
+ while (pos < buffer.length - 10) {
863
+ if (buffer[pos] !== 255) {
864
+ throw new Error("Invalid JPEG file");
865
+ }
866
+ const marker = buffer[pos + 1];
867
+ if (marker === 218) break;
868
+ const segmentSize = buffer.readUInt16BE(pos + 2);
869
+ if (!marker) {
870
+ throw new Error("no marker for jpeg");
871
+ }
872
+ if (marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204) {
873
+ return {
874
+ width: buffer.readUInt16BE(pos + 7),
875
+ height: buffer.readUInt16BE(pos + 5),
876
+ type: "jpeg"
877
+ };
878
+ }
879
+ pos += segmentSize + 2;
880
+ }
881
+ throw new Error("No dimensions found in JPEG file");
882
+ }
883
+ const gifHeader = buffer.toString("ascii", 0, 6);
884
+ if (buffer.length >= 10 && (gifHeader === "GIF87a" || gifHeader === "GIF89a")) {
885
+ return {
886
+ width: buffer.readUInt16LE(6),
887
+ height: buffer.readUInt16LE(8),
888
+ type: "gif"
889
+ };
890
+ }
891
+ if (buffer.length >= 26 && buffer[0] === 66 && buffer[1] === 77) {
892
+ return {
893
+ width: buffer.readInt32LE(18),
894
+ height: Math.abs(buffer.readInt32LE(22)),
895
+ type: "bmp"
896
+ };
897
+ }
898
+ if (buffer.length >= 30 && buffer.toString("ascii", 0, 4) === "RIFF" && buffer.toString("ascii", 8, 12) === "WEBP") {
899
+ const chunkType = buffer.toString("ascii", 12, 16);
900
+ if (chunkType === "VP8X") {
901
+ let widthSubtractOne = 0;
902
+ let heightSubtractOne = 0;
903
+ if (buffer?.[24] && buffer?.[25] && buffer?.[26]) {
904
+ widthSubtractOne = buffer[24] | buffer[25] << 8 | buffer[26] << 16;
905
+ }
906
+ if (buffer?.[27] && buffer?.[28] && buffer?.[29]) {
907
+ heightSubtractOne = buffer[27] | buffer[28] << 8 | buffer[29] << 16;
908
+ }
909
+ return {
910
+ width: widthSubtractOne + 1,
911
+ height: heightSubtractOne + 1,
912
+ type: "webp"
913
+ };
914
+ } else if (chunkType === "VP8 ") {
915
+ const dataStart = 20;
916
+ if (buffer[dataStart + 3] !== 157 || buffer[dataStart + 4] !== 1 || buffer[dataStart + 5] !== 42) {
917
+ throw new Error("Invalid VP8 keyframe");
918
+ }
919
+ const width = buffer.readUInt16LE(dataStart + 6) & 16383;
920
+ const height = buffer.readUInt16LE(dataStart + 8) & 16383;
921
+ return {
922
+ width,
923
+ height,
924
+ type: "webp"
925
+ };
926
+ } else if (chunkType === "VP8L") {
927
+ const dataStart = 20;
928
+ if (buffer[dataStart] !== 47) {
929
+ throw new Error("Invalid VP8L signature");
930
+ }
931
+ const bits = buffer.readUInt32LE(dataStart + 1);
932
+ if (bits >>> 29 !== 0) {
933
+ throw new Error("Invalid VP8L version");
934
+ }
935
+ const width = 1 + (bits & 16383);
936
+ const height = 1 + (bits >> 14 & 16383);
937
+ return {
938
+ width,
939
+ height,
940
+ type: "webp"
941
+ };
942
+ }
943
+ throw new Error("Unsupported WebP chunk");
944
+ }
945
+ if (buffer.length >= 32 && buffer.toString("ascii", 4, 8) === "ftyp") {
946
+ const ftyp = this.findBox(buffer, "ftyp");
947
+ if (!ftyp) throw new Error("Invalid AVIF: No ftyp");
948
+ const brands = buffer.toString("ascii", ftyp.pos, ftyp.pos + ftyp.size);
949
+ if (!brands.includes("avif") && !brands.includes("avis"))
950
+ throw new Error("Not an AVIF file");
951
+ const meta = this.findBox(buffer, "meta");
952
+ if (!meta) throw new Error("Invalid AVIF: No meta");
953
+ const metaSubStart = meta.pos + 4;
954
+ const metaSubEnd = meta.pos + meta.size;
955
+ const iprp = this.findBox(buffer, "iprp", metaSubStart, metaSubEnd);
956
+ if (!iprp) throw new Error("Invalid AVIF: No iprp");
957
+ const ipco = this.findBox(buffer, "ipco", iprp.pos, iprp.pos + iprp.size);
958
+ if (!ipco) throw new Error("Invalid AVIF: No ipco");
959
+ const ispe = this.findBox(buffer, "ispe", ipco.pos, ipco.pos + ipco.size);
960
+ if (!ispe) throw new Error("Invalid AVIF: No ispe");
961
+ if (buffer[ispe.pos] !== 0) throw new Error("Invalid ispe version");
962
+ const width = buffer.readUInt32BE(ispe.pos + 4);
963
+ const height = buffer.readUInt32BE(ispe.pos + 8);
964
+ return {
965
+ width,
966
+ height,
967
+ type: "avif"
968
+ };
969
+ }
970
+ throw new Error("Unsupported image format or invalid file");
971
+ }
643
972
  /**
644
973
  *
645
974
  * @access package-private
@@ -666,6 +995,173 @@ var Fs = class extends MimeService {
666
995
  return await (0, import_sharp.default)(target).toFormat(format, { quality }).toBuffer();
667
996
  }
668
997
  }
998
+ /**
999
+ * Write data to a file in the system's tmp directory
1000
+ * @param filename The filename (can include subdirectories like "img-probe/file.txt")
1001
+ * @param data The data to write
1002
+ * @param options Optional write stream options
1003
+ * @returns The full path to the written file
1004
+ * @example
1005
+ * ```ts
1006
+ * const fs = new Fs(process.cwd());
1007
+ * const tmpPath = fs.writeTmp("session-data.json", JSON.stringify(data));
1008
+ * // Or with a subdirectory:
1009
+ * fs.writeTmp("img-probe/output.png", imageBuffer);
1010
+ * ```
1011
+ */
1012
+ writeTmp(filename, data, options) {
1013
+ const fullPath = (0, import_path.resolve)(this.tmpDir, filename);
1014
+ Promise.resolve(this.withWs(fullPath, data, options));
1015
+ return fullPath;
1016
+ }
1017
+ /**
1018
+ * Read a file from the tmp directory
1019
+ * @param filename The filename to read (can include subdirectories)
1020
+ * @returns Buffer containing the file data
1021
+ * @example
1022
+ * ```ts
1023
+ * const fs = new Fs(process.cwd());
1024
+ * const data = fs.readTmp("session-data.json");
1025
+ * const parsed = JSON.parse(data.toString("utf-8"));
1026
+ * ```
1027
+ */
1028
+ readTmp(filename) {
1029
+ const fullPath = (0, import_path.resolve)(this.tmpDir, filename);
1030
+ if (!this.exists(fullPath)) {
1031
+ throw new Error(`Tmp file not found: ${filename}`);
1032
+ }
1033
+ return this.fileToBuffer(fullPath);
1034
+ }
1035
+ /**
1036
+ * Scan the tmp directory for files matching a pattern
1037
+ * @param pattern Optional pattern to filter files (e.g., "img-probe")
1038
+ * @param options Options for directory reading (defaults to non-recursive to avoid permission issues)
1039
+ * @returns Array of matching file paths relative to tmp directory
1040
+ * @example
1041
+ * ```ts
1042
+ * const fs = new Fs(process.cwd());
1043
+ * // Get all img-probe files
1044
+ * const imgFiles = fs.scanTmp("img-probe");
1045
+ * // Get all files in tmp (non-recursive)
1046
+ * const allFiles = fs.scanTmp();
1047
+ * ```
1048
+ */
1049
+ scanTmp(pattern, options = {
1050
+ recursive: false,
1051
+ withFileTypes: false,
1052
+ encoding: "utf-8"
1053
+ }) {
1054
+ const dirs = (0, import_path.resolve)(this.tmpDir);
1055
+ const tmpContents = this.readDir(dirs, options);
1056
+ if (!pattern) {
1057
+ return tmpContents;
1058
+ }
1059
+ return tmpContents.filter((path) => {
1060
+ const filename = path.includes("/") ? path.split("/").pop() ?? path : path;
1061
+ return filename.includes(pattern) || path.startsWith(pattern);
1062
+ });
1063
+ }
1064
+ /**
1065
+ * Extract specific files from tmp directory to a target location
1066
+ * @param pattern Pattern to match files (e.g., "img-probe")
1067
+ * @param targetDir Target directory to extract files to
1068
+ * @param options Options for extraction behavior
1069
+ * @returns Array of extracted file paths
1070
+ * @example
1071
+ * ```ts
1072
+ * const fs = new Fs(process.cwd());
1073
+ * // Extract all img-probe files to ./output
1074
+ * const extracted = fs.extractFromTmp("img-probe", "./output");
1075
+ * // Extract with custom behavior
1076
+ * fs.extractFromTmp("session-", "./sessions", {
1077
+ * preserveStructure: true,
1078
+ * cleanupAfter: true
1079
+ * });
1080
+ * ```
1081
+ */
1082
+ extractFromTmp(pattern, targetDir, options) {
1083
+ const {
1084
+ preserveStructure = false,
1085
+ cleanupAfter = false,
1086
+ overwrite = true
1087
+ } = options ?? {};
1088
+ const matchingFiles = this.scanTmp(pattern);
1089
+ const extracted = [];
1090
+ for (const file of matchingFiles) {
1091
+ const sourcePath = (0, import_path.resolve)(this.tmpDir, file);
1092
+ const lastSegment = file.includes("/") ? file.split("/").pop() : file;
1093
+ if (!lastSegment) continue;
1094
+ const targetPath = preserveStructure ? (0, import_path.resolve)(targetDir, file) : (0, import_path.resolve)(targetDir, lastSegment);
1095
+ if (this.exists(targetPath) && !overwrite) {
1096
+ console.warn(`Skipping existing file: ${targetPath}`);
1097
+ continue;
1098
+ }
1099
+ const data = this.fileToBuffer(sourcePath);
1100
+ this.withWs(targetPath, data);
1101
+ extracted.push(targetPath);
1102
+ if (cleanupAfter) {
1103
+ this.rmFile(sourcePath);
1104
+ }
1105
+ }
1106
+ return extracted;
1107
+ }
1108
+ /**
1109
+ * Clean up tmp files matching a pattern
1110
+ * @param pattern Pattern to match files for deletion
1111
+ * @param maxAge Optional max age in milliseconds (only delete files older than this)
1112
+ * @returns Number of files removed
1113
+ * @example
1114
+ * ```ts
1115
+ * const fs = new Fs(process.cwd());
1116
+ * // Remove all img-probe files
1117
+ * fs.cleanupTmp("img-probe");
1118
+ * // Remove session files older than 1 hour
1119
+ * fs.cleanupTmp("session-", 60 * 60 * 1000);
1120
+ * ```
1121
+ */
1122
+ cleanupTmp(pattern, maxAge) {
1123
+ const matchingFiles = this.scanTmp(pattern);
1124
+ let removed = 0;
1125
+ for (const file of matchingFiles) {
1126
+ const fullPath = (0, import_path.resolve)(this.tmpDir, file);
1127
+ try {
1128
+ const stats = import_fs.default.statSync(fullPath);
1129
+ if (maxAge) {
1130
+ const age = Date.now() - stats.mtimeMs;
1131
+ if (age < maxAge) {
1132
+ continue;
1133
+ }
1134
+ }
1135
+ if (stats.isDirectory()) {
1136
+ this.rmDirSync(fullPath);
1137
+ } else {
1138
+ this.rmFile(fullPath);
1139
+ }
1140
+ removed++;
1141
+ } catch (err) {
1142
+ console.warn(`Failed to remove tmp file ${file}:`, err);
1143
+ }
1144
+ }
1145
+ return removed;
1146
+ }
1147
+ /**
1148
+ * Generate a unique tmp filename with optional prefix
1149
+ * @param prefix Optional prefix for the filename
1150
+ * @param extension Optional file extension (without dot)
1151
+ * @returns Unique filename
1152
+ * @example
1153
+ * ```ts
1154
+ * const fs = new Fs(process.cwd());
1155
+ * const filename = fs.uniqueTmpName("img-probe", "png");
1156
+ * // Returns: "img-probe-1701234567890-a3b2c1.png"
1157
+ * ```
1158
+ */
1159
+ uniqueTmpName(prefix, extension) {
1160
+ const timestamp = Date.now();
1161
+ const random = Math.random().toString(36).substring(2, 8);
1162
+ const parts = [prefix ?? "tmp", timestamp, random].join("-");
1163
+ return extension ? `${parts}.${extension}` : parts;
1164
+ }
669
1165
  };
670
1166
 
671
1167
  // src/utils/index.ts
@@ -697,19 +1193,21 @@ var UtilsService = class {
697
1193
  b64ToBlob(b64Data) {
698
1194
  {
699
1195
  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
1196
+ const typeMatch = /^data:((?:image|application|haptics|video|text|font|model|audio|multipart)\/[A-Za-z0-9+-.]+(?:;[^,]+)*);base64,(.+)$/i.exec(
1197
+ b64Data
702
1198
  );
703
- const type = typeMatch?.[1];
704
1199
  if (!typeMatch) {
705
1200
  throw new Error(`${b64Data} is not a valid data Url`);
706
1201
  }
707
- const byteCharacters = Buffer.from(b64Data, "base64").toString("utf-8");
1202
+ const type = typeMatch[1];
1203
+ const base64Data = typeMatch?.[2] ?? "";
1204
+ const byteCharacters = Buffer.from(base64Data, "base64").toString(
1205
+ "binary"
1206
+ );
708
1207
  const byteArrays = Array.of();
709
1208
  for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
710
1209
  const slice = byteCharacters.slice(offset, offset + sliceSize);
711
- const byteNumbers = Array.of();
712
- byteNumbers.push(slice.length);
1210
+ const byteNumbers = new Array(slice.length);
713
1211
  for (let i = 0; i < slice.length; i++) {
714
1212
  byteNumbers[i] = slice.charCodeAt(i);
715
1213
  }
@@ -762,16 +1260,19 @@ var UtilsService = class {
762
1260
  );
763
1261
  return typeof sort !== "undefined" ? this.sort(resolve2, sort) : resolve2;
764
1262
  }, "includeTargeted");
765
- countsSorter = /* @__PURE__ */ __name(({
766
- counter,
767
- keySort,
768
- valSort
769
- }) => Object.fromEntries(
770
- Object.entries(counter).sort(
1263
+ countsSorter = /* @__PURE__ */ __name((counter, keySort = "ASC", valSort = "DESC") => Object.fromEntries(
1264
+ Array.from(Object.entries(counter)).sort(
771
1265
  ([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
- )
1266
+ ).sort(([aStr, aNum], [bStr, bNum]) => {
1267
+ if (typeof (aNum && bNum) === "number") {
1268
+ return valSort === "ASC" ? aNum - bNum : bNum - aNum;
1269
+ } else if (typeof (aNum && bNum) === "string") {
1270
+ return valSort === "ASC" ? aStr.localeCompare(bStr) - bStr.localeCompare(aStr) : bStr.localeCompare(aStr) - aStr.localeCompare(bStr);
1271
+ } else
1272
+ throw new Error(
1273
+ "only Record<string, string> and Record<string,number> types supported"
1274
+ );
1275
+ })
775
1276
  ), "countsSorter");
776
1277
  range(from, to) {
777
1278
  const values = Array.of();
@@ -797,6 +1298,7 @@ var UtilsService = class {
797
1298
  UrlService,
798
1299
  UtilsService,
799
1300
  extMimeMap,
1301
+ mimeToExt,
800
1302
  unitsObj
801
1303
  });
802
1304
  //# sourceMappingURL=index.cjs.map