@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/fs/index.cjs CHANGED
@@ -37,6 +37,7 @@ module.exports = __toCommonJS(fs_exports);
37
37
  var import_child_process = require("child_process");
38
38
  var import_fs = __toESM(require("fs"), 1);
39
39
  var import_promises = __toESM(require("fs/promises"), 1);
40
+ var import_node_os = require("os");
40
41
  var import_path = require("path");
41
42
  var dotenv = __toESM(require("dotenv"), 1);
42
43
  var import_dotenv_expand = __toESM(require("dotenv-expand"), 1);
@@ -75,7 +76,7 @@ var extMimeMap = {
75
76
  avif: ["image/avif"],
76
77
  avi: ["video/x-msvideo"],
77
78
  azw: ["application/vnd.amazon.ebook"],
78
- bin: ["application/octet-stream"],
79
+ bin: ["application/octet-stream", "multipart/voice-message"],
79
80
  bmp: ["image/bmp"],
80
81
  bz: ["application/x-bzip"],
81
82
  bz2: ["application/x-bzip2"],
@@ -95,7 +96,7 @@ var extMimeMap = {
95
96
  gif: ["image/gif"],
96
97
  glb: ["model/gltf-binary"],
97
98
  gltf: ["model/gltf+json"],
98
- gz: ["application/x-gzip", "application/gzip"],
99
+ gz: ["application/gzip", "application/x-gzip"],
99
100
  hjif: ["haptics/hjif"],
100
101
  hmpg: ["haptics/hmpg"],
101
102
  htm: ["text/html"],
@@ -103,6 +104,7 @@ var extMimeMap = {
103
104
  ico: ["image/vnd.microsoft.icon"],
104
105
  ics: ["text/calendar"],
105
106
  ivs: ["haptics/ivs"],
107
+ ivt: ["haptics/ivs"],
106
108
  jar: ["application/java-archive"],
107
109
  jpeg: ["image/jpeg"],
108
110
  jpg: ["image/jpeg"],
@@ -124,7 +126,8 @@ var extMimeMap = {
124
126
  mpeg: ["video/mpeg"],
125
127
  mpkg: ["application/vnd.apple.installer+xml"],
126
128
  ndjson: ["application/x-ndjson"],
127
- obj: ["application/octet-stream", "text/plain", "model/obj"],
129
+ node: ["application/node", "text/javascript"],
130
+ obj: ["model/obj", "application/octet-stream", "text/plain"],
128
131
  odp: ["application/vnd.oasis.opendocument.presentation"],
129
132
  ods: ["application/vnd.oasis.opendocument.spreadsheet"],
130
133
  odt: ["application/vnd.oasis.opendocument.text"],
@@ -145,9 +148,11 @@ var extMimeMap = {
145
148
  py: ["text/x-python"],
146
149
  pyc: ["application/x-python-code"],
147
150
  rar: ["application/vnd.rar"],
151
+ rs: ["text/rust"],
148
152
  rtf: ["application/rtf"],
149
153
  sh: ["application/x-sh"],
150
154
  sql: ["application/sql"],
155
+ sse: ["text/event-stream"],
151
156
  svg: ["image/svg+xml"],
152
157
  tar: ["application/x-tar"],
153
158
  tif: ["image/tiff"],
@@ -177,6 +182,118 @@ var extMimeMap = {
177
182
  "3g2": ["video/3gpp2"],
178
183
  "7z": ["application/x-7z-compressed"]
179
184
  };
185
+ var mimeToExt = {
186
+ "application/epub+zip": ["epub"],
187
+ "application/font-sfnt": ["ttf"],
188
+ "application/gzip": ["gz"],
189
+ "application/java-archive": ["jar"],
190
+ "application/json": ["json"],
191
+ "application/ld+json": ["jsonld"],
192
+ "application/msword": ["doc"],
193
+ "application/node": ["node", "js"],
194
+ "application/octet-stream": ["bin", "obj"],
195
+ "application/ogg": ["ogx"],
196
+ "application/pdf": ["pdf"],
197
+ "application/rtf": ["rtf"],
198
+ "application/sql": ["sql"],
199
+ "application/toml": ["toml"],
200
+ "application/vnd.amazon.ebook": ["azw"],
201
+ "application/vnd.apple.installer+xml": ["mpkg"],
202
+ "application/vnd.apple.mpegurl": ["m3u8"],
203
+ "application/vnd.apple.pkpass": ["pkpass"],
204
+ "application/vnd.mozilla.xul+xml": ["xul"],
205
+ "application/vnd.ms-excel": ["xls"],
206
+ "application/vnd.ms-fontobject": ["eot"],
207
+ "application/vnd.ms-powerpoint": ["ppt"],
208
+ "application/vnd.oasis.opendocument.presentation": ["odp"],
209
+ "application/vnd.oasis.opendocument.spreadsheet": ["ods"],
210
+ "application/vnd.oasis.opendocument.text": ["odt"],
211
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation": [
212
+ "pptx"
213
+ ],
214
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": ["xlsx"],
215
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document": [
216
+ "docx"
217
+ ],
218
+ "application/vnd.rar": ["rar"],
219
+ "application/vnd.visio": ["vsd"],
220
+ "application/wasm": ["wasm"],
221
+ "application/x-7z-compressed": ["7z"],
222
+ "application/x-abiword": ["abw"],
223
+ "application/x-bzip": ["bz"],
224
+ "application/x-bzip2": ["bz2"],
225
+ "application/x-cdf": ["cda"],
226
+ "application/x-csh": ["csh"],
227
+ "application/x-freearc": ["arc"],
228
+ "application/x-gzip": ["gz"],
229
+ "application/x-httpd-php": ["php"],
230
+ "application/x-mdx": ["mdx"],
231
+ "application/x-ndjson": ["ndjson"],
232
+ "application/x-python-code": ["pyc"],
233
+ "application/x-sh": ["sh"],
234
+ "application/x-tar": ["tar"],
235
+ "application/x-zip-compressed": ["zip"],
236
+ "application/xhtml+xml": ["xhtml"],
237
+ "application/xml": ["xml"],
238
+ "application/yaml": ["yml", "yaml"],
239
+ "application/zip": ["zip"],
240
+ "audio/aac": ["aac"],
241
+ "audio/midi": ["mid"],
242
+ "audio/mp4": ["m4a"],
243
+ "audio/mpeg": ["mp3"],
244
+ "audio/ogg": ["opus", "ogg", "oga"],
245
+ "audio/wav": ["wav"],
246
+ "audio/x-midi": ["midi"],
247
+ "font/otf": ["otf"],
248
+ "font/ttf": ["ttf"],
249
+ "font/woff": ["woff"],
250
+ "font/woff2": ["woff2"],
251
+ "haptics/hjif": ["hjif"],
252
+ "haptics/hmpg": ["hmpg"],
253
+ "haptics/ivs": ["ivs", "ivt"],
254
+ "image/aces": ["aces"],
255
+ "image/apng": ["apng"],
256
+ "image/avci": ["avci"],
257
+ "image/avif": ["avif"],
258
+ "image/bmp": ["bmp"],
259
+ "image/dpx": ["dpx"],
260
+ "image/emf": ["emf"],
261
+ "image/gif": ["gif"],
262
+ "image/jpeg": ["jpg", "jpeg"],
263
+ "image/ktx": ["ktx"],
264
+ "image/ktx2": ["ktx2"],
265
+ "image/png": ["png"],
266
+ "image/svg+xml": ["svg"],
267
+ "image/tiff": ["tiff", "tif"],
268
+ "image/vnd.microsoft.icon": ["ico"],
269
+ "image/webp": ["webp"],
270
+ "model/gltf-binary": ["glb"],
271
+ "model/gltf+json": ["gltf"],
272
+ "model/obj": ["obj"],
273
+ "model/vnd.usdz+zip": ["usdz"],
274
+ "multipart/voice-message": ["bin"],
275
+ "text/calendar": ["ics"],
276
+ "text/css": ["css"],
277
+ "text/csv": ["csv"],
278
+ "text/event-stream": ["sse", "ts", "rs", "py", "txt"],
279
+ "text/html": ["html", "htm"],
280
+ "text/javascript": ["cjs", "js", "mjs"],
281
+ "text/markdown": ["md"],
282
+ "text/plain": ["txt"],
283
+ "text/rust": ["rs"],
284
+ "text/typescript": ["ts"],
285
+ "text/vtt": ["vtt"],
286
+ "text/x-python": ["py"],
287
+ "video/3gpp": ["3gp"],
288
+ "video/3gpp2": ["3g2"],
289
+ "video/mp2t": ["ts"],
290
+ "video/mp4": ["mp4", "m4v"],
291
+ "video/mpeg": ["mpeg"],
292
+ "video/ogg": ["ogv"],
293
+ "video/vnd.dlna.mpeg-tts": ["ts"],
294
+ "video/webm": ["weba"],
295
+ "video/x-msvideo": ["avi"]
296
+ };
180
297
  var MimeService = class extends UrlService {
181
298
  static {
182
299
  __name(this, "MimeService");
@@ -185,6 +302,35 @@ var MimeService = class extends UrlService {
185
302
  super();
186
303
  }
187
304
  mimeTypeObj = extMimeMap;
305
+ toExtObj = mimeToExt;
306
+ compareMimeToExt(p = "mime") {
307
+ let a = {};
308
+ if (p === "mime") {
309
+ for (const [_key, vals] of Object.entries(extMimeMap)) {
310
+ for (const val of vals) {
311
+ a[val] = (a[val] ?? 0) + 1;
312
+ }
313
+ }
314
+ for (const [key, _val] of Object.entries(mimeToExt)) {
315
+ a[key] = (a[key] ?? 0) + 1;
316
+ }
317
+ return Object.fromEntries(
318
+ Object.entries(a).sort(([_a, aa], [_b, bb]) => bb - aa)
319
+ );
320
+ } else {
321
+ for (const [_key, vals] of Object.entries(mimeToExt)) {
322
+ for (const val of vals) {
323
+ a[val] = (a[val] ?? 0) + 1;
324
+ }
325
+ }
326
+ for (const [key, _val] of Object.entries(extMimeMap)) {
327
+ a[key] = (a[key] ?? 0) + 1;
328
+ }
329
+ return Object.fromEntries(
330
+ Object.entries(a).sort(([_a, aa], [_b, bb]) => bb - aa)
331
+ );
332
+ }
333
+ }
188
334
  assetType(url) {
189
335
  const parsed = this.parseUrl(url);
190
336
  if (!parsed) return void 0;
@@ -229,6 +375,7 @@ var Fs = class extends MimeService {
229
375
  constructor(cwd) {
230
376
  super();
231
377
  this.cwd = cwd;
378
+ cwd ??= process.cwd();
232
379
  }
233
380
  static {
234
381
  __name(this, "Fs");
@@ -236,6 +383,12 @@ var Fs = class extends MimeService {
236
383
  get myEnv() {
237
384
  return dotenv.config({ processEnv: {} });
238
385
  }
386
+ get tmpDir() {
387
+ return (0, import_node_os.tmpdir)();
388
+ }
389
+ get tmpDirRelative() {
390
+ return (0, import_path.relative)(this.cwd, (0, import_node_os.tmpdir)());
391
+ }
239
392
  parseDotEnv() {
240
393
  return import_dotenv_expand.default.expand(this.myEnv);
241
394
  }
@@ -349,7 +502,11 @@ var Fs = class extends MimeService {
349
502
  *
350
503
  * @returns an array of strings representing the contents of the directory
351
504
  */
352
- readDir(path, options = { recursive: true }) {
505
+ readDir(path, options = {
506
+ recursive: true,
507
+ withFileTypes: false,
508
+ encoding: "utf-8"
509
+ }) {
353
510
  if (this.isRootPathTargeted(path)) {
354
511
  return this.handleBuffStrArrUnion(
355
512
  import_fs.default.readdirSync((0, import_path.resolve)((0, import_path.join)(this.cwd, "./")), { ...options })
@@ -510,6 +667,9 @@ var Fs = class extends MimeService {
510
667
  fileToBuffer = /* @__PURE__ */ __name((path) => Buffer.from(
511
668
  import_fs.default.readFileSync((0, import_path.relative)(this.cwd ?? process.cwd(), path)).toJSON().data
512
669
  ), "fileToBuffer");
670
+ fileToBufferAsync = /* @__PURE__ */ __name(async (path) => {
671
+ return await import_promises.default.readFile((0, import_path.relative)(this.cwd, path));
672
+ }, "fileToBufferAsync");
513
673
  dirContainsDir(readDir, targetDir, options) {
514
674
  return this.readDir(readDir, options).filter((t) => t.split(".").length === 1).includes(targetDir);
515
675
  }
@@ -526,10 +686,11 @@ var Fs = class extends MimeService {
526
686
  };
527
687
  }
528
688
  async assetToBufferView(path) {
529
- const response = await fetch(path);
689
+ const response = await fetch(path, { method: "GET" });
530
690
  if (!response.ok) {
531
691
  throw new Error(`Failed to fetch asset: ${response.statusText}`);
532
692
  }
693
+ console.log(Object.fromEntries(Array.from(response.headers.entries())));
533
694
  const reader = response.body?.getReader();
534
695
  if (reader) {
535
696
  const chunks = Array.of();
@@ -596,13 +757,37 @@ var Fs = class extends MimeService {
596
757
  return console.error(err);
597
758
  }
598
759
  }
599
- async fetchRemoteWriteLocalLargeFiles(inputUrl, outputPath, useDetectedExtension = true) {
760
+ /**
761
+ *
762
+ * @param inputUrl remote url to fetch data from
763
+ * @param outputPath desired output path relative to the cwd
764
+ * @param useDetectedExtension optional, defaults to true
765
+ *
766
+ * if `useDetectedExtension` is false you must include the file extension in your output path →
767
+ *
768
+ * 🚫 'public/assets/image-1'
769
+ *
770
+ * ✅ 'public/assets/image-1.png'
771
+ *
772
+ * @description
773
+ * This method is designed for large files that may not fit into memory.
774
+ * It streams the data directly to disk instead of loading it all into memory.
775
+ */
776
+ async fetchRemoteWriteLocalLargeFiles(inputUrl, outputPathI, useDetectedExtension = true) {
600
777
  const MAX_SAFE_IN_MEMORY_MB = 100;
601
778
  try {
602
- const head = await fetch(inputUrl, { method: "HEAD" });
779
+ const isGithubRaw = inputUrl.startsWith(
780
+ "https://raw.githubusercontent.com"
781
+ );
782
+ const head = await fetch(inputUrl, {
783
+ method: isGithubRaw ? "GET" : "HEAD"
784
+ });
603
785
  const contentLength = head.headers.get("content-length");
604
786
  const fileSizeMb = contentLength ? parseInt(contentLength, 10) / (1024 * 1024) : null;
605
- const formattedPath = useDetectedExtension ? `${outputPath}.${this.assetType(inputUrl)}` : outputPath;
787
+ let outputPath = outputPathI;
788
+ const assetTypeViaUrl = this.assetType(inputUrl);
789
+ const contentType = head.headers.get("content-type") ?? "application/octet-stream";
790
+ const formattedPath = useDetectedExtension ? `${outputPath}.${typeof assetTypeViaUrl === "undefined" ? this.toExtObj[contentType][0] : assetTypeViaUrl}` : outputPath;
606
791
  this.generateDirIfDNE(this.pathHandler(formattedPath), {
607
792
  recursive: true
608
793
  });
@@ -633,6 +818,149 @@ var Fs = class extends MimeService {
633
818
  console.error(`[fetchRemoteWriteLocalLargeFiles error]:`, err);
634
819
  }
635
820
  }
821
+ findBox(buffer, type, start = 0, end = buffer.length) {
822
+ let pos = start;
823
+ while (pos < end) {
824
+ let boxSize = buffer.readUInt32BE(pos);
825
+ let boxType = buffer.toString("ascii", pos + 4, pos + 8);
826
+ let hdrSize = 8;
827
+ if (boxSize === 1) {
828
+ boxSize = Number(buffer.readBigUInt64BE(pos + 8));
829
+ hdrSize = 16;
830
+ } else if (boxSize === 0) {
831
+ boxSize = end - pos;
832
+ }
833
+ if (boxType === type) {
834
+ return { pos: pos + hdrSize, size: boxSize - hdrSize };
835
+ }
836
+ pos += boxSize;
837
+ }
838
+ return null;
839
+ }
840
+ async getImageSize(filePath) {
841
+ const buffer = await this.fileToBufferAsync(filePath);
842
+ 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) {
843
+ if (buffer.readUint32BE(8) !== 13 || buffer?.[12] !== 73 || buffer?.[13] !== 72 || buffer?.[14] !== 68 || buffer?.[15] !== 82) {
844
+ throw new Error("IHDR Chunk of png not found or incorrect.");
845
+ }
846
+ return {
847
+ width: buffer.readUInt32BE(16),
848
+ height: buffer.readUInt32BE(20),
849
+ type: "png"
850
+ };
851
+ }
852
+ if (buffer.length >= 10 && buffer[0] === 255 && buffer[1] === 216) {
853
+ let pos = 2;
854
+ while (pos < buffer.length - 10) {
855
+ if (buffer[pos] !== 255) {
856
+ throw new Error("Invalid JPEG file");
857
+ }
858
+ const marker = buffer[pos + 1];
859
+ if (marker === 218) break;
860
+ const segmentSize = buffer.readUInt16BE(pos + 2);
861
+ if (!marker) {
862
+ throw new Error("no marker for jpeg");
863
+ }
864
+ if (marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204) {
865
+ return {
866
+ width: buffer.readUInt16BE(pos + 7),
867
+ height: buffer.readUInt16BE(pos + 5),
868
+ type: "jpeg"
869
+ };
870
+ }
871
+ pos += segmentSize + 2;
872
+ }
873
+ throw new Error("No dimensions found in JPEG file");
874
+ }
875
+ const gifHeader = buffer.toString("ascii", 0, 6);
876
+ if (buffer.length >= 10 && (gifHeader === "GIF87a" || gifHeader === "GIF89a")) {
877
+ return {
878
+ width: buffer.readUInt16LE(6),
879
+ height: buffer.readUInt16LE(8),
880
+ type: "gif"
881
+ };
882
+ }
883
+ if (buffer.length >= 26 && buffer[0] === 66 && buffer[1] === 77) {
884
+ return {
885
+ width: buffer.readInt32LE(18),
886
+ height: Math.abs(buffer.readInt32LE(22)),
887
+ type: "bmp"
888
+ };
889
+ }
890
+ if (buffer.length >= 30 && buffer.toString("ascii", 0, 4) === "RIFF" && buffer.toString("ascii", 8, 12) === "WEBP") {
891
+ const chunkType = buffer.toString("ascii", 12, 16);
892
+ if (chunkType === "VP8X") {
893
+ let widthSubtractOne = 0;
894
+ let heightSubtractOne = 0;
895
+ if (buffer?.[24] && buffer?.[25] && buffer?.[26]) {
896
+ widthSubtractOne = buffer[24] | buffer[25] << 8 | buffer[26] << 16;
897
+ }
898
+ if (buffer?.[27] && buffer?.[28] && buffer?.[29]) {
899
+ heightSubtractOne = buffer[27] | buffer[28] << 8 | buffer[29] << 16;
900
+ }
901
+ return {
902
+ width: widthSubtractOne + 1,
903
+ height: heightSubtractOne + 1,
904
+ type: "webp"
905
+ };
906
+ } else if (chunkType === "VP8 ") {
907
+ const dataStart = 20;
908
+ if (buffer[dataStart + 3] !== 157 || buffer[dataStart + 4] !== 1 || buffer[dataStart + 5] !== 42) {
909
+ throw new Error("Invalid VP8 keyframe");
910
+ }
911
+ const width = buffer.readUInt16LE(dataStart + 6) & 16383;
912
+ const height = buffer.readUInt16LE(dataStart + 8) & 16383;
913
+ return {
914
+ width,
915
+ height,
916
+ type: "webp"
917
+ };
918
+ } else if (chunkType === "VP8L") {
919
+ const dataStart = 20;
920
+ if (buffer[dataStart] !== 47) {
921
+ throw new Error("Invalid VP8L signature");
922
+ }
923
+ const bits = buffer.readUInt32LE(dataStart + 1);
924
+ if (bits >>> 29 !== 0) {
925
+ throw new Error("Invalid VP8L version");
926
+ }
927
+ const width = 1 + (bits & 16383);
928
+ const height = 1 + (bits >> 14 & 16383);
929
+ return {
930
+ width,
931
+ height,
932
+ type: "webp"
933
+ };
934
+ }
935
+ throw new Error("Unsupported WebP chunk");
936
+ }
937
+ if (buffer.length >= 32 && buffer.toString("ascii", 4, 8) === "ftyp") {
938
+ const ftyp = this.findBox(buffer, "ftyp");
939
+ if (!ftyp) throw new Error("Invalid AVIF: No ftyp");
940
+ const brands = buffer.toString("ascii", ftyp.pos, ftyp.pos + ftyp.size);
941
+ if (!brands.includes("avif") && !brands.includes("avis"))
942
+ throw new Error("Not an AVIF file");
943
+ const meta = this.findBox(buffer, "meta");
944
+ if (!meta) throw new Error("Invalid AVIF: No meta");
945
+ const metaSubStart = meta.pos + 4;
946
+ const metaSubEnd = meta.pos + meta.size;
947
+ const iprp = this.findBox(buffer, "iprp", metaSubStart, metaSubEnd);
948
+ if (!iprp) throw new Error("Invalid AVIF: No iprp");
949
+ const ipco = this.findBox(buffer, "ipco", iprp.pos, iprp.pos + iprp.size);
950
+ if (!ipco) throw new Error("Invalid AVIF: No ipco");
951
+ const ispe = this.findBox(buffer, "ispe", ipco.pos, ipco.pos + ipco.size);
952
+ if (!ispe) throw new Error("Invalid AVIF: No ispe");
953
+ if (buffer[ispe.pos] !== 0) throw new Error("Invalid ispe version");
954
+ const width = buffer.readUInt32BE(ispe.pos + 4);
955
+ const height = buffer.readUInt32BE(ispe.pos + 8);
956
+ return {
957
+ width,
958
+ height,
959
+ type: "avif"
960
+ };
961
+ }
962
+ throw new Error("Unsupported image format or invalid file");
963
+ }
636
964
  /**
637
965
  *
638
966
  * @access package-private
@@ -659,5 +987,172 @@ var Fs = class extends MimeService {
659
987
  return await (0, import_sharp.default)(target).toFormat(format, { quality }).toBuffer();
660
988
  }
661
989
  }
990
+ /**
991
+ * Write data to a file in the system's tmp directory
992
+ * @param filename The filename (can include subdirectories like "img-probe/file.txt")
993
+ * @param data The data to write
994
+ * @param options Optional write stream options
995
+ * @returns The full path to the written file
996
+ * @example
997
+ * ```ts
998
+ * const fs = new Fs(process.cwd());
999
+ * const tmpPath = fs.writeTmp("session-data.json", JSON.stringify(data));
1000
+ * // Or with a subdirectory:
1001
+ * fs.writeTmp("img-probe/output.png", imageBuffer);
1002
+ * ```
1003
+ */
1004
+ writeTmp(filename, data, options) {
1005
+ const fullPath = (0, import_path.resolve)(this.tmpDir, filename);
1006
+ Promise.resolve(this.withWs(fullPath, data, options));
1007
+ return fullPath;
1008
+ }
1009
+ /**
1010
+ * Read a file from the tmp directory
1011
+ * @param filename The filename to read (can include subdirectories)
1012
+ * @returns Buffer containing the file data
1013
+ * @example
1014
+ * ```ts
1015
+ * const fs = new Fs(process.cwd());
1016
+ * const data = fs.readTmp("session-data.json");
1017
+ * const parsed = JSON.parse(data.toString("utf-8"));
1018
+ * ```
1019
+ */
1020
+ readTmp(filename) {
1021
+ const fullPath = (0, import_path.resolve)(this.tmpDir, filename);
1022
+ if (!this.exists(fullPath)) {
1023
+ throw new Error(`Tmp file not found: ${filename}`);
1024
+ }
1025
+ return this.fileToBuffer(fullPath);
1026
+ }
1027
+ /**
1028
+ * Scan the tmp directory for files matching a pattern
1029
+ * @param pattern Optional pattern to filter files (e.g., "img-probe")
1030
+ * @param options Options for directory reading (defaults to non-recursive to avoid permission issues)
1031
+ * @returns Array of matching file paths relative to tmp directory
1032
+ * @example
1033
+ * ```ts
1034
+ * const fs = new Fs(process.cwd());
1035
+ * // Get all img-probe files
1036
+ * const imgFiles = fs.scanTmp("img-probe");
1037
+ * // Get all files in tmp (non-recursive)
1038
+ * const allFiles = fs.scanTmp();
1039
+ * ```
1040
+ */
1041
+ scanTmp(pattern, options = {
1042
+ recursive: false,
1043
+ withFileTypes: false,
1044
+ encoding: "utf-8"
1045
+ }) {
1046
+ const dirs = (0, import_path.resolve)(this.tmpDir);
1047
+ const tmpContents = this.readDir(dirs, options);
1048
+ if (!pattern) {
1049
+ return tmpContents;
1050
+ }
1051
+ return tmpContents.filter((path) => {
1052
+ const filename = path.includes("/") ? path.split("/").pop() ?? path : path;
1053
+ return filename.includes(pattern) || path.startsWith(pattern);
1054
+ });
1055
+ }
1056
+ /**
1057
+ * Extract specific files from tmp directory to a target location
1058
+ * @param pattern Pattern to match files (e.g., "img-probe")
1059
+ * @param targetDir Target directory to extract files to
1060
+ * @param options Options for extraction behavior
1061
+ * @returns Array of extracted file paths
1062
+ * @example
1063
+ * ```ts
1064
+ * const fs = new Fs(process.cwd());
1065
+ * // Extract all img-probe files to ./output
1066
+ * const extracted = fs.extractFromTmp("img-probe", "./output");
1067
+ * // Extract with custom behavior
1068
+ * fs.extractFromTmp("session-", "./sessions", {
1069
+ * preserveStructure: true,
1070
+ * cleanupAfter: true
1071
+ * });
1072
+ * ```
1073
+ */
1074
+ extractFromTmp(pattern, targetDir, options) {
1075
+ const {
1076
+ preserveStructure = false,
1077
+ cleanupAfter = false,
1078
+ overwrite = true
1079
+ } = options ?? {};
1080
+ const matchingFiles = this.scanTmp(pattern);
1081
+ const extracted = [];
1082
+ for (const file of matchingFiles) {
1083
+ const sourcePath = (0, import_path.resolve)(this.tmpDir, file);
1084
+ const lastSegment = file.includes("/") ? file.split("/").pop() : file;
1085
+ if (!lastSegment) continue;
1086
+ const targetPath = preserveStructure ? (0, import_path.resolve)(targetDir, file) : (0, import_path.resolve)(targetDir, lastSegment);
1087
+ if (this.exists(targetPath) && !overwrite) {
1088
+ console.warn(`Skipping existing file: ${targetPath}`);
1089
+ continue;
1090
+ }
1091
+ const data = this.fileToBuffer(sourcePath);
1092
+ this.withWs(targetPath, data);
1093
+ extracted.push(targetPath);
1094
+ if (cleanupAfter) {
1095
+ this.rmFile(sourcePath);
1096
+ }
1097
+ }
1098
+ return extracted;
1099
+ }
1100
+ /**
1101
+ * Clean up tmp files matching a pattern
1102
+ * @param pattern Pattern to match files for deletion
1103
+ * @param maxAge Optional max age in milliseconds (only delete files older than this)
1104
+ * @returns Number of files removed
1105
+ * @example
1106
+ * ```ts
1107
+ * const fs = new Fs(process.cwd());
1108
+ * // Remove all img-probe files
1109
+ * fs.cleanupTmp("img-probe");
1110
+ * // Remove session files older than 1 hour
1111
+ * fs.cleanupTmp("session-", 60 * 60 * 1000);
1112
+ * ```
1113
+ */
1114
+ cleanupTmp(pattern, maxAge) {
1115
+ const matchingFiles = this.scanTmp(pattern);
1116
+ let removed = 0;
1117
+ for (const file of matchingFiles) {
1118
+ const fullPath = (0, import_path.resolve)(this.tmpDir, file);
1119
+ try {
1120
+ const stats = import_fs.default.statSync(fullPath);
1121
+ if (maxAge) {
1122
+ const age = Date.now() - stats.mtimeMs;
1123
+ if (age < maxAge) {
1124
+ continue;
1125
+ }
1126
+ }
1127
+ if (stats.isDirectory()) {
1128
+ this.rmDirSync(fullPath);
1129
+ } else {
1130
+ this.rmFile(fullPath);
1131
+ }
1132
+ removed++;
1133
+ } catch (err) {
1134
+ console.warn(`Failed to remove tmp file ${file}:`, err);
1135
+ }
1136
+ }
1137
+ return removed;
1138
+ }
1139
+ /**
1140
+ * Generate a unique tmp filename with optional prefix
1141
+ * @param prefix Optional prefix for the filename
1142
+ * @param extension Optional file extension (without dot)
1143
+ * @returns Unique filename
1144
+ * @example
1145
+ * ```ts
1146
+ * const fs = new Fs(process.cwd());
1147
+ * const filename = fs.uniqueTmpName("img-probe", "png");
1148
+ * // Returns: "img-probe-1701234567890-a3b2c1.png"
1149
+ * ```
1150
+ */
1151
+ uniqueTmpName(prefix, extension) {
1152
+ const timestamp = Date.now();
1153
+ const random = Math.random().toString(36).substring(2, 8);
1154
+ const parts = [prefix ?? "tmp", timestamp, random].join("-");
1155
+ return extension ? `${parts}.${extension}` : parts;
1156
+ }
662
1157
  };
663
1158
  //# sourceMappingURL=index.cjs.map