@d0paminedriven/fs 7.2.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 (44) hide show
  1. package/README.md +104 -51
  2. package/dist/chunk-2IRCHZCF.js +75 -0
  3. package/dist/{chunk-KUGIFRTF.js → chunk-2XQ44ZWR.js} +339 -3
  4. package/dist/{chunk-O2P3L3CJ.js → chunk-6HHKXBIM.js} +5 -2
  5. package/dist/chunk-HPM4IQQR.js +69 -0
  6. package/dist/{chunk-GH6MFTV5.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-MRKO3PAA.js → chunk-R63XI7FS.js} +1 -1
  13. package/dist/{chunk-6FJJLFJL.js → chunk-UW52DMHT.js} +2 -2
  14. package/dist/chunk-Z2WZLZC4.js +75 -0
  15. package/dist/fs/index.d.ts +18 -329
  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 +11 -4
  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 +5 -4
  36. package/dist/mime/index.js +4 -3
  37. package/dist/types/index.d.ts +13 -13
  38. package/dist/types/index.js +1 -1
  39. package/dist/url/index.d.ts +1 -0
  40. package/dist/url/index.js +3 -2
  41. package/dist/utils/index.d.ts +2 -1
  42. package/dist/utils/index.js +2 -1
  43. package/package.json +31 -3
  44. package/dist/chunk-SYISQ57E.js +0 -895
@@ -0,0 +1,367 @@
1
+ import {
2
+ FsCore
3
+ } from "./chunk-KOKPGEU4.js";
4
+ import {
5
+ __name
6
+ } from "./chunk-7QVYU63E.js";
7
+
8
+ // src/fs-tmp/index.ts
9
+ import fsSync from "fs";
10
+ import fsAsync from "fs/promises";
11
+ import { resolve } from "path";
12
+ var FsTmp = class extends FsCore {
13
+ constructor(cwd) {
14
+ super(cwd ??= process.cwd());
15
+ this.cwd = cwd;
16
+ }
17
+ static {
18
+ __name(this, "FsTmp");
19
+ }
20
+ /**
21
+ * Write data to a file in the system's tmp directory
22
+ * @param filename The filename (can include subdirectories like "img-probe/file.txt")
23
+ * @param data The data to write
24
+ * @param options Optional write stream options
25
+ * @returns The full path to the written file
26
+ * @example
27
+ * ```ts
28
+ * const fs = new Fs(process.cwd());
29
+ * const tmpPath = fs.writeTmp("session-data.json", JSON.stringify(data));
30
+ * // Or with a subdirectory:
31
+ * fs.writeTmp("img-probe/output.png", imageBuffer);
32
+ * ```
33
+ */
34
+ writeTmp(filename, data, options) {
35
+ const fullPath = resolve(this.tmpDir, filename);
36
+ Promise.resolve(this.withWs(fullPath, data, options));
37
+ }
38
+ async writeTmpAsync(filename, data, options = {}) {
39
+ const fullPath = resolve(this.tmpDir, filename);
40
+ return await this.writeFileAsync(
41
+ fullPath,
42
+ data,
43
+ typeof options === "object" ? { ...options, mode: 511 } : options
44
+ );
45
+ }
46
+ async readTmpAsync(filename) {
47
+ const fullPath = resolve(this.tmpDir, filename);
48
+ if (!this.existsTmp(filename)) {
49
+ throw new Error(`Tmp file not found: ${filename}`);
50
+ }
51
+ return await this.fileToBufferAsync(fullPath);
52
+ }
53
+ /**
54
+ * Read a file from the tmp directory
55
+ * @param filename The filename to read (can include subdirectories)
56
+ * @returns Buffer containing the file data
57
+ * @example
58
+ * ```ts
59
+ * const fs = new Fs(process.cwd());
60
+ * const data = fs.readTmp("session-data.json");
61
+ * const parsed = JSON.parse(data.toString("utf-8"));
62
+ * ```
63
+ */
64
+ readTmp(filename) {
65
+ const fullPath = resolve(this.tmpDir, filename);
66
+ if (!this.exists(fullPath)) {
67
+ throw new Error(`Tmp file not found: ${filename}`);
68
+ }
69
+ return this.fileToBuffer(fullPath);
70
+ }
71
+ /**
72
+ * Scan the tmp directory for files matching a pattern
73
+ * @param pattern Optional pattern to filter files (e.g., "img-probe")
74
+ * @param options Options for directory reading (defaults to non-recursive to avoid permission issues)
75
+ * @returns Array of matching file paths relative to tmp directory
76
+ * @example
77
+ * ```ts
78
+ * const fs = new Fs(process.cwd());
79
+ * // Get all img-probe files
80
+ * const imgFiles = fs.scanTmp("img-probe");
81
+ * // Get all files in tmp (non-recursive)
82
+ * const allFiles = fs.scanTmp();
83
+ * ```
84
+ */
85
+ scanTmp(pattern, options = {
86
+ recursive: false,
87
+ withFileTypes: false,
88
+ encoding: "utf-8"
89
+ }) {
90
+ const dirs = resolve(this.tmpDir);
91
+ const tmpContents = this.readDir(dirs, options);
92
+ if (!pattern) {
93
+ return tmpContents;
94
+ }
95
+ if (typeof pattern === "string") {
96
+ return tmpContents.filter((t) => t.includes(pattern));
97
+ }
98
+ return tmpContents.filter((path) => {
99
+ return pattern.test(path);
100
+ });
101
+ }
102
+ /**
103
+ * Extract specific files from tmp directory to a target location
104
+ * @param pattern Pattern to match files (e.g., "img-probe")
105
+ * @param targetDir Target directory to extract files to
106
+ * @param options Options for extraction behavior
107
+ * @returns Array of extracted file paths
108
+ * @example
109
+ * ```ts
110
+ * const fs = new Fs(process.cwd());
111
+ * // Extract all img-probe files to ./output
112
+ * const extracted = fs.extractFromTmp("img-probe", "./output");
113
+ * // Extract with custom behavior
114
+ * fs.extractFromTmp("session-", "./sessions", {
115
+ * preserveStructure: true,
116
+ * cleanupAfter: true
117
+ * });
118
+ * ```
119
+ */
120
+ extractFromTmp(pattern, targetDir, options) {
121
+ const {
122
+ preserveStructure = false,
123
+ cleanupAfter = false,
124
+ overwrite = true
125
+ } = options ?? {};
126
+ const matchingFiles = this.scanTmp(pattern);
127
+ const extracted = [];
128
+ for (const file of matchingFiles) {
129
+ const sourcePath = resolve(this.tmpDir, file);
130
+ const lastSegment = file.includes("/") ? file.split("/").pop() : file;
131
+ if (!lastSegment) continue;
132
+ const targetPath = preserveStructure ? resolve(targetDir, file) : resolve(targetDir, lastSegment);
133
+ if (this.exists(targetPath) && !overwrite) {
134
+ console.warn(`Skipping existing file: ${targetPath}`);
135
+ continue;
136
+ }
137
+ const data = this.fileToBuffer(sourcePath);
138
+ this.withWs(targetPath, data);
139
+ extracted.push(targetPath);
140
+ if (cleanupAfter) {
141
+ this.rmFile(sourcePath);
142
+ }
143
+ }
144
+ return extracted;
145
+ }
146
+ /**
147
+ * Clean up tmp files matching a pattern
148
+ * @param pattern Pattern to match files for deletion
149
+ * @param maxAge Optional max age in milliseconds (only delete files older than this)
150
+ * @returns Number of files removed
151
+ * @example
152
+ * ```ts
153
+ * const fs = new Fs(process.cwd());
154
+ * // Remove all img-probe files
155
+ * fs.cleanupTmp("img-probe");
156
+ * // Remove session files older than 1 hour
157
+ * fs.cleanupTmp("session-", 60 * 60 * 1000);
158
+ * ```
159
+ */
160
+ cleanupTmp(pattern, maxAge) {
161
+ const matchingFiles = this.scanTmp(pattern);
162
+ let removed = 0;
163
+ for (const file of matchingFiles) {
164
+ const fullPath = resolve(this.tmpDir, file);
165
+ try {
166
+ const stats = fsSync.statSync(fullPath);
167
+ if (maxAge) {
168
+ const age = Date.now() - stats.mtimeMs;
169
+ if (age < maxAge) {
170
+ continue;
171
+ }
172
+ }
173
+ if (stats.isDirectory()) {
174
+ this.rmDirSync(fullPath);
175
+ } else {
176
+ this.rmFile(fullPath);
177
+ }
178
+ removed++;
179
+ } catch (err) {
180
+ console.warn(`Failed to remove tmp file ${file}:`, err);
181
+ }
182
+ }
183
+ return removed;
184
+ }
185
+ /**
186
+ * Generate a unique tmp filename with optional prefix
187
+ * @param prefix Optional prefix for the filename
188
+ * @param extension Optional file extension (without dot)
189
+ * @returns Unique filename
190
+ * @example
191
+ * ```ts
192
+ * const fs = new Fs(process.cwd());
193
+ * const filename = fs.uniqueTmpName("img-probe", "png");
194
+ * // Returns: "img-probe-1701234567890-a3b2c1.png"
195
+ * ```
196
+ */
197
+ uniqueTmpName(prefix, extension) {
198
+ const timestamp = Date.now();
199
+ const random = Math.random().toString(36).substring(2, 8);
200
+ const parts = [prefix ?? "tmp", timestamp, random].join("-");
201
+ return extension ? `${parts}.${extension}` : parts;
202
+ }
203
+ /**
204
+ * Async generator for cleaning tmp files with batched removal
205
+ * @param pattern Pattern to match files for deletion
206
+ * @param batchSize Number of files to remove per batch (default 10)
207
+ * @yields Progress information during cleanup
208
+ * @returns Final cleanup summary
209
+ * @example
210
+ * ```ts
211
+ * const fs = new Fs(process.cwd());
212
+ * // Clean up with progress tracking
213
+ * for await (const progress of fs.cleanTmpGenerator("session-", 25)) {
214
+ * console.log(progress);
215
+ * }
216
+ * ```
217
+ */
218
+ async *cleanTmpGenerator(pattern, batchSize = 10) {
219
+ const files = this.scanTmp(pattern);
220
+ const batches = await this.arrToArrOfArrs({
221
+ arrToFragment: files,
222
+ arrOfArrsAggregator: [],
223
+ interval: batchSize
224
+ });
225
+ let totalRemoved = 0;
226
+ for (const [index, batch] of batches.entries()) {
227
+ yield {
228
+ action: "removing",
229
+ batch: [...batch],
230
+ batchNumber: index + 1,
231
+ totalBatches: batches.length,
232
+ totalFound: files.length,
233
+ removed: totalRemoved
234
+ };
235
+ for (const file of batch) {
236
+ this.rmTmpFile(file);
237
+ totalRemoved++;
238
+ }
239
+ yield {
240
+ action: "batch-complete",
241
+ batchNumber: index + 1,
242
+ batchSize: batch.length,
243
+ totalRemoved,
244
+ remaining: files.length - totalRemoved
245
+ };
246
+ }
247
+ return {
248
+ action: "complete",
249
+ totalRemoved,
250
+ totalBatches: batches.length,
251
+ pattern: pattern.toString()
252
+ };
253
+ }
254
+ /**
255
+ * Async version of withWs with atomic write support and progress tracking
256
+ * @param path Target file path
257
+ * @param data Streamable data to write
258
+ * @param options Optional atomic write and abort signal
259
+ * @returns Promise with path and bytes written
260
+ * @example
261
+ * ```ts
262
+ * const fs = new Fs(process.cwd());
263
+ * // Simple async write
264
+ * const result = await fs.asyncWithWs("output.txt", "Hello World");
265
+ * console.log(`Wrote ${result.bytes} bytes to ${result.path}`);
266
+ *
267
+ * // Atomic write with temp file
268
+ * const { path, bytes } = await fs.asyncWithWs(
269
+ * "critical-data.json",
270
+ * JSON.stringify(data),
271
+ * { atomic: true }
272
+ * );
273
+ * ```
274
+ */
275
+ async asyncWithWs(path, data, options) {
276
+ const { atomic = false, signal: _signal = AbortSignal } = options ?? {};
277
+ let bytes = 0;
278
+ if (!atomic) {
279
+ try {
280
+ if (/\//g.test(path)) {
281
+ return this.generateDirIfDNETmp(this.pathHandler(path), {
282
+ recursive: true
283
+ });
284
+ } else return path;
285
+ } catch (error) {
286
+ console.error(
287
+ `[asyncWithWs non-atomic error]: `.concat(
288
+ error instanceof Error ? error.message : typeof error === "string" ? error : JSON.stringify(error, null, 2)
289
+ )
290
+ );
291
+ } finally {
292
+ const readable = this.toReadable(data);
293
+ const chunks = [];
294
+ for await (const chunk of readable) {
295
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
296
+ }
297
+ const buffer = Buffer.concat(chunks);
298
+ try {
299
+ this.withWs(path, buffer);
300
+ } catch (err) {
301
+ console.error(err);
302
+ } finally {
303
+ return { path, bytes: buffer.length };
304
+ }
305
+ }
306
+ }
307
+ let tmpName;
308
+ try {
309
+ if (/\//g.test(path)) {
310
+ this.generateDirIfDNETmp(this.pathHandler(path), {
311
+ recursive: true
312
+ });
313
+ }
314
+ tmpName = this.uniqueTmpName("atomic", "tmp");
315
+ } catch (error) {
316
+ console.error(
317
+ `[asyncWithWs atomic setup error]: `.concat(
318
+ error instanceof Error ? error.message : typeof error === "string" ? error : JSON.stringify(error, null, 2)
319
+ )
320
+ );
321
+ if (tmpName) {
322
+ try {
323
+ this.rmTmpFile(tmpName);
324
+ } catch (err) {
325
+ console.error(err);
326
+ }
327
+ }
328
+ } finally {
329
+ if (tmpName) {
330
+ let newPath = null;
331
+ let newBytes = 0;
332
+ const readable = this.toReadable(data);
333
+ const chunks = [];
334
+ for await (const chunk of readable) {
335
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
336
+ }
337
+ const buffer = Buffer.concat(chunks);
338
+ bytes = buffer.length;
339
+ try {
340
+ await this.writeTmpAsync(tmpName, buffer.toString());
341
+ const tmpPath = resolve(this.tmpDir, tmpName);
342
+ const finalPath = resolve(this.cwd, path);
343
+ await fsAsync.rename(tmpPath, finalPath);
344
+ newPath = path;
345
+ newBytes = bytes;
346
+ } catch (err) {
347
+ console.error(`[asyncWithWs atomic rename error]:`, err);
348
+ if (this.existsTmp(tmpName)) {
349
+ try {
350
+ this.rmTmpFile(tmpName);
351
+ } catch (err2) {
352
+ console.error(err2);
353
+ }
354
+ }
355
+ throw err;
356
+ }
357
+ return { path, bytes, newPath, newBytes };
358
+ }
359
+ }
360
+ return { path, bytes: 0 };
361
+ }
362
+ };
363
+
364
+ export {
365
+ FsTmp
366
+ };
367
+ //# sourceMappingURL=chunk-PTXZQBLV.js.map
@@ -11,4 +11,4 @@ var unitsObj = {
11
11
  export {
12
12
  unitsObj
13
13
  };
14
- //# sourceMappingURL=chunk-MRKO3PAA.js.map
14
+ //# sourceMappingURL=chunk-R63XI7FS.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  UtilsService
3
- } from "./chunk-O2P3L3CJ.js";
3
+ } from "./chunk-6HHKXBIM.js";
4
4
  import {
5
5
  __name
6
6
  } from "./chunk-7QVYU63E.js";
@@ -30,4 +30,4 @@ var UrlService = class extends UtilsService {
30
30
  export {
31
31
  UrlService
32
32
  };
33
- //# sourceMappingURL=chunk-6FJJLFJL.js.map
33
+ //# sourceMappingURL=chunk-UW52DMHT.js.map
@@ -0,0 +1,75 @@
1
+ import {
2
+ __name
3
+ } from "./chunk-7QVYU63E.js";
4
+
5
+ // src/ld/index.ts
6
+ var LevenshteinDistance = class {
7
+ static {
8
+ __name(this, "LevenshteinDistance");
9
+ }
10
+ createMatrix(rows, cols, initialValue) {
11
+ const matrix = Array.of();
12
+ for (let r = 0; r < rows; r++) {
13
+ const row = new Array(cols).fill(initialValue);
14
+ matrix.push(row);
15
+ }
16
+ return matrix;
17
+ }
18
+ inBounds(matrix, row, col) {
19
+ if (!matrix[row]) return false;
20
+ return row >= 0 && row < matrix.length && col >= 0 && col < matrix[row].length;
21
+ }
22
+ getCell(matrix, row, col) {
23
+ if (!matrix[row]) {
24
+ throw new Error(`getRow: row does not exist`);
25
+ }
26
+ if (!this.inBounds(matrix, row, col) || !matrix[row][col]) return 0;
27
+ return matrix[row][col];
28
+ }
29
+ setCell(matrix, row, col, value) {
30
+ if (!matrix[row]) return false;
31
+ if (!this.inBounds(matrix, row, col)) {
32
+ return false;
33
+ }
34
+ matrix[row][col] = value;
35
+ return true;
36
+ }
37
+ /**
38
+ * Computes the Levenshtein distance between two strings, i.e.,
39
+ * the minimum number of single-character edits (insertions,
40
+ * deletions, or substitutions) needed to transform `a` into `b`.
41
+ */
42
+ calculate(a, b) {
43
+ const strA = a ?? "";
44
+ const strB = b ?? "";
45
+ const dp = this.createMatrix(strA.length + 1, strB.length + 1, 0);
46
+ for (let i = 0; i < dp.length; i++) {
47
+ for (let j = 0; j < (dp[i] ?? []).length; j++) {
48
+ if (i === 0) {
49
+ this.setCell(dp, i, j, j);
50
+ } else if (j === 0) {
51
+ this.setCell(dp, i, j, i);
52
+ } else {
53
+ const charA = strA[i - 1];
54
+ const charB = strB[j - 1];
55
+ if (charA === charB) {
56
+ const diag = this.getCell(dp, i - 1, j - 1);
57
+ this.setCell(dp, i, j, diag);
58
+ } else {
59
+ const top = this.getCell(dp, i - 1, j);
60
+ const left = this.getCell(dp, i, j - 1);
61
+ const diag = this.getCell(dp, i - 1, j - 1);
62
+ const val = 1 + Math.min(top, left, diag);
63
+ this.setCell(dp, i, j, val);
64
+ }
65
+ }
66
+ }
67
+ }
68
+ return this.getCell(dp, strA.length, strB.length);
69
+ }
70
+ };
71
+
72
+ export {
73
+ LevenshteinDistance
74
+ };
75
+ //# sourceMappingURL=chunk-Z2WZLZC4.js.map