@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/README.md CHANGED
@@ -1,100 +1,419 @@
1
1
  # @d0paminedriven/fs
2
2
 
3
- > *“Don’t sweat the small stuff; just write your damn files.”*
3
+ > **The filesystem utilities that eliminate entire categories of bugs from your codebase.**
4
4
 
5
- Let's be real, you likely already have a project manager breathing down your neck for updates on the hour, JIRA ticket blues bringing you down, Teams/Slack notification pings plaguing your dreams, the "hey, got five minutes?" guy breaking your flow state on the daily, and nth other pressing issues on your mind mid-development.
5
+ ## 🎯 Why This Package Exists
6
6
 
7
- These situations are all annoying af, which is why this package seamlessly ensures that targeted output paths exist for you (if they don't exist yet, they will before your file is written). Whether you're using `writeFileAsync`, `fetchRemoteWriteLocalLargeFiles`, or `withWs`, this package has you covered no matter how deep your targeted output paths go. Unfortunately, this package *can't* help with that pesky PM or that flow-breaking co-worker (yet--PRs welcome).
7
+ **Stop checking if directories exist.** Stop worrying about MIME types. Stop blowing up your RAM with large files. Stop writing the same filesystem boilerplate over and over.
8
8
 
9
- Want to grab some remote files? Throw any file size its way — no problemo — just use the `fetchRemoteWriteLocalLargeFiles` method. (Proceed with caution in the >=gigabyte range. If your setup can handle it, then by all means.)
9
+ This package solves real problems that `fs-extra` and other utilities ignore:
10
+
11
+ - ✅ **Atomic directory creation with write operations** - One method, zero directory anxiety
12
+ - ✅ **Intelligent MIME type handling** - Bidirectional mapping with compile-time safety
13
+ - ✅ **Memory-safe remote asset fetching** - Stream gigabyte files without fear
14
+ - ✅ **Native image dimension extraction** - Get width, height, format without dependencies
15
+ - ✅ **Tmp directory management** - Complete utilities for temporary file operations
16
+ - ✅ **Type-safe throughout** - Full TypeScript with literal types and inference
17
+
18
+ ## 🚀 The Revolutionary `withWs` Method
19
+
20
+ **This single method has eliminated "directory doesn't exist" errors for 3+ years:**
21
+
22
+ ```typescript
23
+ // What everyone else does (including fs-extra):
24
+ await fs.mkdir('/deep/nested/path', { recursive: true });
25
+ const stream = fs.createWriteStream('/deep/nested/path/file.json');
26
+ stream.write(data);
27
+ // 3 operations, multiple points of failure, mental overhead
28
+
29
+ // What withWs does:
30
+ fs.withWs('/deep/nested/path/file.json', data);
31
+ // ONE operation. Directories created atomically with write stream.
32
+ // No await needed. No directory checks. Just works.
33
+ ```
10
34
 
11
35
  ---
12
36
 
13
- ## 🚀 Quickstart
37
+ ## 📦 Installation
14
38
 
15
- ```ts
16
- import { Fs } from "@d0paminedriven/fs";
39
+ ```bash
40
+ pnpm add @d0paminedriven/fs
41
+ # or
42
+ npm install @d0paminedriven/fs
43
+ ```
44
+
45
+ ## 🔥 Core Features
46
+
47
+ ### 1. Smart Remote Asset Fetching
17
48
 
18
- // Set your cwd (project root recommended)
49
+ **Handles URLs without extensions intelligently:**
50
+
51
+ ```typescript
19
52
  const fs = new Fs(process.cwd());
20
53
 
21
- /** Write to a nested file path (no mkdirp needed) */
22
- await fs.writeFileAsync("public/assets/images/foo/bar.jpg", myImageBuffer);
23
- // No error, no “does this folder exist?”, no drama
54
+ // URLs with no extension? No problem!
55
+ // Automatically detects MIME type from Content-Type header
56
+ await fs.fetchRemoteWriteLocalLargeFiles(
57
+ "https://api.example.com/asset/12345", // No extension in URL
58
+ "public/assets/downloaded-file" // Extension auto-detected
59
+ );
60
+ // Result: public/assets/downloaded-file.png (if Content-Type was image/png)
24
61
 
25
- /** Fetch and save a massive remote asset */
62
+ // Streams large files without memory explosion
26
63
  await fs.fetchRemoteWriteLocalLargeFiles(
27
- "https://cdn.example.com/big-model.glb",
28
- "public/models/my-big-model"
64
+ "https://cdn.example.com/huge-video.mp4", // 2GB file? No problem
65
+ "public/videos/my-video"
29
66
  );
30
- // Handles directories, streams file to disk, and never blows up your RAM
67
+ ```
68
+
69
+ ### 2. Native Image Dimension Extraction
70
+
71
+ **Get image dimensions without heavy dependencies:**
31
72
 
32
- /** Read every file in a directory */
33
- const files = fs.readDir("public/assets/images", { recursive: true });
73
+ ```typescript
74
+ // Extract width, height, and format from any image
75
+ const imageInfo = fs.getImageSize("public/images/hero.jpg");
76
+ console.log(imageInfo);
77
+ // { width: 1920, height: 1080, type: "jpeg" }
34
78
 
35
- /** Unlink a file (with existence check) */
36
- await fs.unlink("public/assets/old/unused.txt");
79
+ // Works with PNG, JPEG, GIF, BMP, WebP, AVIF
80
+ // No ImageMagick, no Sharp needed for basic dimension reading
81
+ ```
82
+
83
+ ### 3. Intelligent MIME Type System
37
84
 
38
- /** Need a wait utility for your script? */
39
- await fs.wait(2000); // waits 2 seconds
85
+ ```typescript
86
+ // Bidirectional MIME mapping with full type safety
87
+ const mimeType = fs.getMimeTypeForPath("file.tsx"); // "text/tsx"
88
+ const extension = fs.mimeToExt("application/pdf"); // "pdf"
40
89
 
41
- /** Get the MIME type for any file by extension */
42
- const mime = fs.getMimeTypeForPath("foo.png"); // "image/png"
90
+ // Handles edge cases elegantly
91
+ fs.getMimeTypeForPath("no-extension"); // "application/octet-stream"
92
+ fs.mimeToExt("image/jpeg"); // "jpg" (returns common extension)
93
+ ```
94
+
95
+ ### 4. Tmp Directory Management Suite
96
+
97
+ ```typescript
98
+ // Write to tmp with automatic cleanup
99
+ const tmpPath = fs.writeTmp("session-data.json", JSON.stringify(data));
100
+
101
+ // Generate unique tmp filenames
102
+ const uniqueName = fs.uniqueTmpName("upload", "bin");
103
+ // Result: "upload-1701234567890-x7y8z9.bin"
104
+
105
+ // Scan tmp directory (non-recursive by default to avoid permission issues)
106
+ const tmpFiles = fs.scanTmp("session-"); // Find all session files
107
+ const regexFiles = fs.scanTmp(/\.json$/); // Regex pattern support
108
+
109
+ // Remove individual tmp files with precision
110
+ fs.rmTmpFile("session-abc123.json"); // Targeted single file removal
111
+
112
+ // Extract files from tmp to permanent location
113
+ fs.extractFromTmp("processed-", "./output", {
114
+ cleanupAfter: true // Auto-remove from tmp after extraction
115
+ });
116
+
117
+ // Cleanup old tmp files
118
+ fs.cleanupTmp("cache-", 60 * 60 * 1000); // Remove files older than 1 hour
119
+
120
+ // Async generator for batch removal with progress tracking
121
+ for await (const progress of fs.cleanTmpGenerator("upload-", 20)) {
122
+ // Process files in batches of 20 with real-time progress
123
+ console.log(`Batch ${progress.batchNumber}/${progress.totalBatches}`);
124
+ }
125
+ ```
126
+
127
+ ### 5. The Legendary `withWs` Method
128
+
129
+ ```typescript
130
+ // Deep nested paths? Complex directory structures? Don't care.
131
+ fs.withWs(
132
+ "output/2024/reports/january/week-1/summary.json",
133
+ JSON.stringify(reportData)
134
+ );
135
+ // Creates all 5 directories if needed, writes file, done.
136
+
137
+ // Works with any data type
138
+ fs.withWs("public/images/avatar.png", imageBuffer);
139
+ fs.withWs("logs/error.log", "Error: " + errorMessage);
140
+ fs.withWs("data/binary.dat", binaryData);
43
141
  ```
44
142
 
45
143
  ---
46
144
 
47
- ## 🍳 Recipes / Real-World Scripts
48
-
49
- Need to audit or analyze files, generate a TypeScript object from your assets, or automate asset metadata?
50
- Here’s a dead-simple pattern to iterate off of:
51
-
52
- ```ts
53
-
54
- const files = fs.readDir("public/assets/images", { recursive: true });
55
-
56
- /** Map those files to a typescript object with file names as keys + corresponding file sizes as values */
57
- const arr = Array.of<[string, number]>();
58
-
59
- function generateTsObjOfFileSizes(withExtensions = true) {
60
- try {
61
- files.forEach(function (file) {
62
- const size = fs.fileSizeMb(`public/assets/images/${file}`);
63
- if (withExtensions === false) {
64
- arr.push([file.split(/\./g)[0] ?? file, size]);
65
- } else {
66
- arr.push([file, size]);
67
- }
68
- });
69
- } catch (err) {
70
- if (err instanceof Error) throw new Error(err.message);
71
- else console.error(`generateTsFileOfFileSizes`, err);
72
- } finally {
73
- const tupleArrToObj = Object.fromEntries(arr);
74
- fs.withWs(
75
- `src/utils/file-sizes.ts`,
76
- `export const publicAssetsImagesFileSizesMb = ${JSON.stringify(tupleArrToObj, null, 2)} as const;`
145
+ ## 🎨 Real-World Examples
146
+
147
+ ### Image Asset Pipeline
148
+
149
+ ```typescript
150
+ const fs = new Fs(process.cwd());
151
+
152
+ async function processImageAssets() {
153
+ // Fetch remote images with automatic extension detection
154
+ const imageUrls = [
155
+ "https://api.unsplash.com/photos/random", // No extension!
156
+ "https://cdn.example.com/hero-image", // No extension!
157
+ "https://example.com/logo.avif" // Has extension
158
+ ];
159
+
160
+ for (const url of imageUrls) {
161
+ // Extension auto-detected from Content-Type
162
+ await fs.fetchRemoteWriteLocalLargeFiles(
163
+ url,
164
+ `public/images/${Date.now()}`
77
165
  );
78
166
  }
167
+
168
+ // Get dimensions for all downloaded images
169
+ const images = fs.readDir("public/images");
170
+ const metadata = images.map(img => ({
171
+ file: img,
172
+ ...fs.getImageSize(`public/images/${img}`),
173
+ size: fs.getSize(`public/images/${img}`)
174
+ }));
175
+
176
+ // Generate TypeScript metadata file
177
+ fs.withWs(
178
+ "src/generated/image-metadata.ts",
179
+ `export const imageMetadata = ${JSON.stringify(metadata, null, 2)} as const;`
180
+ );
181
+ }
182
+ ```
183
+
184
+ ### Temporary File Processing
185
+
186
+ ```typescript
187
+ async function processUpload(fileBuffer: Buffer, userId: string) {
188
+ const fs = new Fs(process.cwd());
189
+
190
+ // Generate unique tmp filename
191
+ const tmpName = fs.uniqueTmpName(`upload-${userId}`, "dat");
192
+
193
+ // Write to tmp for processing
194
+ const tmpPath = fs.writeTmp(tmpName, fileBuffer);
195
+
196
+ // Process the file (resize, convert, etc.)
197
+ const processed = await processFile(tmpPath);
198
+
199
+ // Move to permanent storage
200
+ fs.withWs(`uploads/${userId}/${Date.now()}.jpg`, processed);
201
+
202
+ // Cleanup tmp (or let cleanupTmp handle it later)
203
+ fs.cleanupTmp(`upload-${userId}`);
204
+ }
205
+ ```
206
+
207
+ ### Advanced Tmp Management
208
+
209
+ #### Granular Single File Removal
210
+ ```typescript
211
+ const fs = new Fs(process.cwd());
212
+
213
+ // Create some tmp files
214
+ const tmpFile1 = fs.uniqueTmpName("session", "json");
215
+ const tmpFile2 = fs.uniqueTmpName("cache", "dat");
216
+ fs.writeTmp(tmpFile1, JSON.stringify({ user: "123" }));
217
+ fs.writeTmp(tmpFile2, Buffer.from("cached data"));
218
+
219
+ // Remove a specific tmp file
220
+ fs.rmTmpFile(tmpFile1); // Removes only session-*.json file
221
+
222
+ // Or find and remove specific files
223
+ const sessionFiles = fs.scanTmp("session");
224
+ sessionFiles.forEach(file => fs.rmTmpFile(file));
225
+ ```
226
+
227
+ #### Batch Removal with Progress Tracking
228
+ ```typescript
229
+ async function cleanupWithProgress() {
230
+ const fs = new Fs(process.cwd());
231
+
232
+ // Clean tmp files in batches with real-time progress
233
+ for await (const progress of fs.cleanTmpGenerator("upload-", 25)) {
234
+ if (progress.action === 'removing') {
235
+ console.log(`Processing batch ${progress.batchNumber}/${progress.totalBatches}`);
236
+ console.log(`Files in batch: ${progress.batch.length}`);
237
+ } else if (progress.action === 'batch-complete') {
238
+ console.log(`Batch complete! Removed: ${progress.totalRemoved}`);
239
+ console.log(`Remaining: ${progress.remaining}`);
240
+ }
241
+ }
79
242
  }
80
243
 
81
- generateTsObjOfFileSizes();
244
+ // Using regex patterns for more complex matching
245
+ async function cleanupPatterns() {
246
+ const fs = new Fs(process.cwd());
247
+
248
+ // Match multiple patterns with regex
249
+ const pattern = /(session|cache|upload)-.*/;
250
+
251
+ for await (const progress of fs.cleanTmpGenerator(pattern, 50)) {
252
+ // Process large batches of 50 files at a time
253
+ if (progress.action === 'batch-complete') {
254
+ console.log(`Batch ${progress.batchNumber}: Removed ${progress.batchSize} files`);
255
+ }
256
+ }
257
+ }
258
+ ```
82
259
 
260
+ ### Build-Time Asset Generation
261
+
262
+ ```typescript
263
+ // Generate a manifest of all assets with sizes and dimensions
264
+ function generateAssetManifest() {
265
+ const fs = new Fs(process.cwd());
266
+ const assets: Record<string, any> = {};
267
+
268
+ // Scan all asset directories
269
+ const images = fs.readDir("public/images", { recursive: true });
270
+ const videos = fs.readDir("public/videos", { recursive: true });
271
+
272
+ // Process images
273
+ images.forEach(img => {
274
+ const path = `public/images/${img}`;
275
+ assets[img] = {
276
+ type: "image",
277
+ mime: fs.getMimeTypeForPath(img),
278
+ size: fs.autoFileSizeRaw(path),
279
+ dimensions: fs.getImageSize(path)
280
+ };
281
+ });
282
+
283
+ // Process videos
284
+ videos.forEach(vid => {
285
+ const path = `public/videos/${vid}`;
286
+ assets[vid] = {
287
+ type: "video",
288
+ mime: fs.getMimeTypeForPath(vid),
289
+ size: fs.autoFileSizeRaw(path)
290
+ };
291
+ });
292
+
293
+ // Write manifest (directories auto-created)
294
+ fs.withWs(
295
+ "src/generated/assets/manifest.json",
296
+ JSON.stringify(assets, null, 2)
297
+ );
298
+ }
83
299
  ```
84
300
 
85
- *This outputs a TypeScript object you can use for dashboards, asset analytics, or CI/CD checks:*
301
+ ## 📊 Performance & Architecture
302
+
303
+ ### Why It's Fast
86
304
 
87
- ```ts
88
- export const fileSizesInMb = {
89
- "chess-atb.png": 1.1277456283569336,
90
- "elegant-stone-tiles-albedo.png": 53.93040370941162,
91
- "port-40.avif": 1.7613801956176758,
92
- "saeukkang.usdz": 3.6647157669067383
93
- } as const;
305
+ - **Stream-based file operations** - Never loads entire files into memory
306
+ - **Parallel directory creation** - Uses `finally` blocks for guaranteed execution
307
+ - **Zero unnecessary checks** - No redundant `fs.exists()` calls
308
+ - **Optimized MIME lookups** - O(1) bidirectional mapping with Map structures
309
+
310
+ ### Memory Safety
311
+
312
+ ```typescript
313
+ // This won't blow up your RAM, even with a 10GB file
314
+ await fs.fetchRemoteWriteLocalLargeFiles(
315
+ "https://example.com/massive-file.zip",
316
+ "downloads/massive-file"
317
+ );
318
+
319
+ // Internally uses streams:
320
+ // response.body.pipe(fs.createWriteStream(path))
321
+ // Instead of loading entire file into memory
94
322
  ```
95
- <small>ⓘ assets used were pooled from repos across github via the `fetchRemoteWriteLocalLargeFiles` method</small>
96
323
 
97
- <br>
324
+ ## 🛠️ Complete API Reference
325
+
326
+ ### Core Methods
327
+
328
+ | Method | Description | Returns |
329
+ |--------|-------------|---------|
330
+ | `withWs(path, data, options?)` | Write with automatic directory creation | `WriteStream` |
331
+ | `writeFileAsync(path, data)` | Async file write with directory creation | `Promise<void>` |
332
+ | `readDir(path, options?)` | Read directory contents | `string[]` |
333
+ | `fileToBuffer(path)` | Read file as Buffer | `Buffer` |
334
+ | `exists(path)` | Check if path exists | `boolean` |
335
+ | `rmFile(path)` | Remove file | `void` |
336
+ | `rmDirSync(path)` | Remove directory | `void` |
337
+
338
+ ### Remote Operations
339
+
340
+ | Method | Description | Returns |
341
+ |--------|-------------|---------|
342
+ | `fetchRemoteWriteLocalLargeFiles(url, outputPath)` | Stream remote file to disk | `Promise<void>` |
343
+ | `assetToBufferView(url)` | Fetch remote asset as buffer | `Promise<{buffer, b64, mime}>` |
344
+
345
+ ### Image Operations
346
+
347
+ | Method | Description | Returns |
348
+ |--------|-------------|---------|
349
+ | `getImageSize(path)` | Extract image dimensions | `{width, height, type}` |
350
+ | `imageTransform(target, options)` | Transform images with Sharp | `Promise<Buffer>` |
351
+ | `cleanDataUrl(dataUrl)` | Strip data URL prefix | `string` |
352
+ | `b64ToBlob(b64, mime?)` | Convert base64 to Blob | `Blob` |
353
+
354
+ ### MIME Operations
355
+
356
+ | Method | Description | Returns |
357
+ |--------|-------------|---------|
358
+ | `getMimeTypeForPath(path)` | Get MIME type from file path | `string` |
359
+ | `mimeToExt(mime)` | Convert MIME to extension | `string` |
360
+ | `getExtensionForMimeType(mime)` | Get extension from MIME | `string \| undefined` |
361
+
362
+ ### Tmp Directory Operations
363
+
364
+ | Method | Description | Returns |
365
+ |--------|-------------|---------|
366
+ | `writeTmp(filename, data)` | Write to tmp directory | `string` (path) |
367
+ | `readTmp(filename)` | Read from tmp directory | `Buffer` |
368
+ | `scanTmp(pattern?)` | List tmp directory contents | `string[]` |
369
+ | `extractFromTmp(pattern, target, options?)` | Extract files from tmp | `string[]` |
370
+ | `cleanupTmp(pattern, maxAge?)` | Remove tmp files | `number` (removed) |
371
+ | `uniqueTmpName(prefix?, ext?)` | Generate unique tmp filename | `string` |
372
+
373
+ ### Utility Methods
374
+
375
+ | Method | Description | Returns |
376
+ |--------|-------------|---------|
377
+ | `wait(ms)` | Async delay utility | `Promise<void>` |
378
+ | `getSize(path)` | Human-readable file size | `string` |
379
+ | `fileSizeMb(path)` | File size in MB | `number` |
380
+ | `autoFileSizeRaw(path)` | Auto-formatted size object | `{size, unit}` |
381
+ | `chunkArray(array, size)` | Split array into chunks | `T[][]` |
382
+
383
+ ## 🚦 Migration Guide
384
+
385
+ ### From fs-extra
386
+
387
+ ```typescript
388
+ // Before (fs-extra)
389
+ await fs.ensureDir('/path/to/dir');
390
+ await fs.writeFile('/path/to/dir/file.json', data);
391
+
392
+ // After (@d0paminedriven/fs)
393
+ fs.withWs('/path/to/dir/file.json', data);
394
+ ```
395
+
396
+ ### From Native fs
397
+
398
+ ```typescript
399
+ // Before (native fs)
400
+ import { mkdir, writeFile } from 'fs/promises';
401
+ await mkdir('/path/to/dir', { recursive: true });
402
+ await writeFile('/path/to/dir/file.json', data);
403
+
404
+ // After (@d0paminedriven/fs)
405
+ fs.withWs('/path/to/dir/file.json', data);
406
+ ```
407
+
408
+ ## 💡 Philosophy
409
+
410
+ This package embodies a simple philosophy: **filesystem operations should be atomic, safe, and obvious**.
411
+
412
+ - **Atomic**: Operations either fully succeed or fully fail
413
+ - **Safe**: No memory explosions, no race conditions
414
+ - **Obvious**: One method does one thing well
415
+
416
+ The `withWs` method is the crown jewel - it eliminates an entire category of bugs (missing directories) that plague every Node.js application. After using it for 3+ years, the creator literally forgot that "directory doesn't exist" errors were even a thing.
98
417
 
99
418
  ---
100
419
 
@@ -102,4 +421,10 @@ export const fileSizesInMb = {
102
421
  |:----:|:----:|:------:|
103
422
  | [![npm](https://img.shields.io/npm/v/@d0paminedriven/fs?color=blue)](https://www.npmjs.com/package/@d0paminedriven/fs) | [![npm](https://img.shields.io/npm/dm/@d0paminedriven/fs)](https://www.npmjs.com/package/@d0paminedriven/fs) | <a style="fill:white;" href="https://github.com/DopamineDriven/d0paminedriven/tree/master/packages/fs"><svg height="24" aria-hidden="true" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-mark-github"><path d="M12 1C5.9225 1 1 5.9225 1 12C1 16.8675 4.14875 20.9787 8.52125 22.4362C9.07125 22.5325 9.2775 22.2025 9.2775 21.9137C9.2775 21.6525 9.26375 20.7862 9.26375 19.865C6.5 20.3737 5.785 19.1912 5.565 18.5725C5.44125 18.2562 4.905 17.28 4.4375 17.0187C4.0525 16.8125 3.5025 16.3037 4.42375 16.29C5.29 16.2762 5.90875 17.0875 6.115 17.4175C7.105 19.0812 8.68625 18.6137 9.31875 18.325C9.415 17.61 9.70375 17.1287 10.02 16.8537C7.5725 16.5787 5.015 15.63 5.015 11.4225C5.015 10.2262 5.44125 9.23625 6.1425 8.46625C6.0325 8.19125 5.6475 7.06375 6.2525 5.55125C6.2525 5.55125 7.17375 5.2625 9.2775 6.67875C10.1575 6.43125 11.0925 6.3075 12.0275 6.3075C12.9625 6.3075 13.8975 6.43125 14.7775 6.67875C16.8813 5.24875 17.8025 5.55125 17.8025 5.55125C18.4075 7.06375 18.0225 8.19125 17.9125 8.46625C18.6138 9.23625 19.04 10.2125 19.04 11.4225C19.04 15.6437 16.4688 16.5787 14.0213 16.8537C14.42 17.1975 14.7638 17.8575 14.7638 18.8887C14.7638 20.36 14.75 21.5425 14.75 21.9137C14.75 22.2025 14.9563 22.5462 15.5063 22.4362C19.8513 20.9787 23 16.8537 23 12C23 5.9225 18.0775 1 12 1Z"></path></svg></a>
104
423
 
424
+ ## 📜 License
425
+
426
+ MIT © [DopamineDriven](https://github.com/DopamineDriven)
427
+
105
428
  ---
429
+
430
+ **Built with frustration, refined with experience, shared with love.** 🚀
@@ -31,19 +31,21 @@ var UtilsService = class {
31
31
  b64ToBlob(b64Data) {
32
32
  {
33
33
  const sliceSize = 512;
34
- const typeMatch = b64Data.match(
35
- /^data:(?:image|application|haptics|video|text|font|model|audio|multipart)\/[A-Za-z0-9+-.]+(?:;[^,]+)*;base64,/i
34
+ const typeMatch = /^data:((?:image|application|haptics|video|text|font|model|audio|multipart)\/[A-Za-z0-9+-.]+(?:;[^,]+)*);base64,(.+)$/i.exec(
35
+ b64Data
36
36
  );
37
- const type = typeMatch?.[1];
38
37
  if (!typeMatch) {
39
38
  throw new Error(`${b64Data} is not a valid data Url`);
40
39
  }
41
- const byteCharacters = Buffer.from(b64Data, "base64").toString("utf-8");
40
+ const type = typeMatch[1];
41
+ const base64Data = typeMatch?.[2] ?? "";
42
+ const byteCharacters = Buffer.from(base64Data, "base64").toString(
43
+ "binary"
44
+ );
42
45
  const byteArrays = Array.of();
43
46
  for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
44
47
  const slice = byteCharacters.slice(offset, offset + sliceSize);
45
- const byteNumbers = Array.of();
46
- byteNumbers.push(slice.length);
48
+ const byteNumbers = new Array(slice.length);
47
49
  for (let i = 0; i < slice.length; i++) {
48
50
  byteNumbers[i] = slice.charCodeAt(i);
49
51
  }
@@ -96,16 +98,19 @@ var UtilsService = class {
96
98
  );
97
99
  return typeof sort !== "undefined" ? this.sort(resolve, sort) : resolve;
98
100
  }, "includeTargeted");
99
- countsSorter = /* @__PURE__ */ __name(({
100
- counter,
101
- keySort,
102
- valSort
103
- }) => Object.fromEntries(
104
- Object.entries(counter).sort(
101
+ countsSorter = /* @__PURE__ */ __name((counter, keySort = "ASC", valSort = "DESC") => Object.fromEntries(
102
+ Array.from(Object.entries(counter)).sort(
105
103
  ([aStr, _aNum], [bStr, _bNum]) => keySort === "DESC" ? bStr.localeCompare(aStr) - aStr.localeCompare(bStr) : aStr.localeCompare(bStr) - bStr.localeCompare(aStr)
106
- ).sort(
107
- ([_aStr, aNum], [_bStr, bNum]) => valSort === "ASC" ? aNum - bNum : bNum - aNum
108
- )
104
+ ).sort(([aStr, aNum], [bStr, bNum]) => {
105
+ if (typeof (aNum && bNum) === "number") {
106
+ return valSort === "ASC" ? aNum - bNum : bNum - aNum;
107
+ } else if (typeof (aNum && bNum) === "string") {
108
+ return valSort === "ASC" ? aStr.localeCompare(bStr) - bStr.localeCompare(aStr) : bStr.localeCompare(aStr) - aStr.localeCompare(bStr);
109
+ } else
110
+ throw new Error(
111
+ "only Record<string, string> and Record<string,number> types supported"
112
+ );
113
+ })
109
114
  ), "countsSorter");
110
115
  range(from, to) {
111
116
  const values = Array.of();
@@ -128,4 +133,4 @@ var UtilsService = class {
128
133
  export {
129
134
  UtilsService
130
135
  };
131
- //# sourceMappingURL=chunk-QMN5ZCE4.js.map
136
+ //# sourceMappingURL=chunk-IUGBPDQJ.js.map
@@ -11,4 +11,4 @@ var unitsObj = {
11
11
  export {
12
12
  unitsObj
13
13
  };
14
- //# sourceMappingURL=chunk-4X5DVWVM.js.map
14
+ //# sourceMappingURL=chunk-MXEE2WS7.js.map