@d0paminedriven/fs 0.2.0 → 2.0.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
@@ -130,6 +130,7 @@ var import_promises = __toESM(require("fs/promises"), 1);
130
130
  var import_path = require("path");
131
131
  var dotenv = __toESM(require("dotenv"), 1);
132
132
  var import_dotenv_expand = __toESM(require_main(), 1);
133
+ var import_sharp = __toESM(require("sharp"), 1);
133
134
  dotenv.config();
134
135
  var Fs = class {
135
136
  constructor(cwd) {
@@ -149,20 +150,20 @@ var Fs = class {
149
150
  );
150
151
  }
151
152
  excludeTargeted = /* @__PURE__ */ __name((obj, props, sort) => {
152
- const resolve = Object.fromEntries(
153
+ const resolve2 = Object.fromEntries(
153
154
  Object.entries(obj).map(([key, val]) => {
154
155
  if (props.includes(key)) {
155
156
  return ["omit", "omit"];
156
157
  } else return [key, val];
157
158
  }).filter(([t, _v]) => /omit/.test(t) === false)
158
159
  );
159
- return typeof sort !== "undefined" ? this.sort(resolve, sort) : resolve;
160
+ return typeof sort !== "undefined" ? this.sort(resolve2, sort) : resolve2;
160
161
  }, "excludeTargeted");
161
162
  includeTargeted = /* @__PURE__ */ __name((obj, props, sort) => {
162
- const resolve = Object.fromEntries(
163
+ const resolve2 = Object.fromEntries(
163
164
  props.map((val) => this.extractTuple(obj, val))
164
165
  );
165
- return typeof sort !== "undefined" ? this.sort(resolve, sort) : resolve;
166
+ return typeof sort !== "undefined" ? this.sort(resolve2, sort) : resolve2;
166
167
  }, "includeTargeted");
167
168
  get myEnv() {
168
169
  return dotenv.config({ processEnv: {} });
@@ -186,6 +187,7 @@ var Fs = class {
186
187
  return { ...this.omitFields(targ, keys) };
187
188
  }
188
189
  exists(target) {
190
+ if (!/\//gm.test(target)) return import_fs.default.existsSync((0, import_path.resolve)((0, import_path.join)(this.cwd, target)));
189
191
  return import_fs.default.existsSync((0, import_path.relative)(this.cwd ?? process.cwd(), target));
190
192
  }
191
193
  arrToArrOfArrs = /* @__PURE__ */ __name(({
@@ -193,7 +195,7 @@ var Fs = class {
193
195
  arrOfArrsAggregator = Array.of(),
194
196
  interval
195
197
  }) => new Promise(
196
- (resolve, _reject) => resolve(
198
+ (resolve2, _reject) => resolve2(
197
199
  ((interval2) => {
198
200
  for (let i = 0; i <= arrToFragment.length; i++) {
199
201
  if ((i % interval2 === 0 || i === 0) && i <= arrToFragment.length) {
@@ -205,7 +207,7 @@ var Fs = class {
205
207
  )
206
208
  ).then((_) => arrOfArrsAggregator), "arrToArrOfArrs");
207
209
  wait(ms) {
208
- return new Promise((resolve) => setTimeout(resolve, ms));
210
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
209
211
  }
210
212
  countsSorter = /* @__PURE__ */ __name(({
211
213
  counter,
@@ -223,8 +225,15 @@ var Fs = class {
223
225
  (v) => Buffer.isBuffer(v) ? Buffer.from(v).toString("utf-8") : v
224
226
  );
225
227
  }
228
+ isRootPathTargeted(path) {
229
+ if (/^(?:\.\/|\.|\/|root|\.\.\/|~\/\.?|cwd|\.\/\.)$/g.test(path)) {
230
+ return true;
231
+ } else return false;
232
+ }
226
233
  readDir(path, options) {
227
- return this.handleBuffStrArrUnion(
234
+ if (this.isRootPathTargeted(path)) {
235
+ return this.handleBuffStrArrUnion(import_fs.default.readdirSync((0, import_path.resolve)((0, import_path.join)(this.cwd, "./")), options));
236
+ } else return this.handleBuffStrArrUnion(
228
237
  import_fs.default.readdirSync(
229
238
  (0, import_path.relative)(this.cwd ??= process.cwd(), path),
230
239
  options
@@ -234,9 +243,7 @@ var Fs = class {
234
243
  executeCommand = /* @__PURE__ */ __name(({
235
244
  command,
236
245
  ...options
237
- }) => Buffer.from(
238
- Buffer.from((0, import_child_process.execSync)(command, { ...options }).toJSON().data)
239
- ).toString("utf-8"), "executeCommand");
246
+ }) => Buffer.from((0, import_child_process.execSync)(command, { ...options }).toJSON().data).toString("utf-8"), "executeCommand");
240
247
  fileGenTimestamp(d) {
241
248
  const date = d.toISOString();
242
249
  return `/* file-autogenerated by @d0paminedriven/fs on ${date.split(/([T])/gm)?.[0]} at ${date.split(/([T])/gm)[2]?.split(/([Z])/gm)?.[0]} UTC */`;
@@ -248,6 +255,7 @@ var Fs = class {
248
255
  return this.fileGenTimestamp(d).replace("/*", "<!--").replace("*/", "-->");
249
256
  }
250
257
  existsSync(path) {
258
+ if (!/\//gm.test(path)) return import_fs.default.existsSync((0, import_path.resolve)((0, import_path.join)(this.cwd, path)));
251
259
  return import_fs.default.existsSync((0, import_path.relative)(this.cwd ?? process.cwd(), path));
252
260
  }
253
261
  pathHandler(path) {
@@ -310,18 +318,11 @@ var Fs = class {
310
318
  }
311
319
  }, "writeFileAsync");
312
320
  fileToBuffer = /* @__PURE__ */ __name((path) => Buffer.from(
313
- Buffer.from(
314
- import_fs.default.readFileSync((0, import_path.relative)(this.cwd ?? process.cwd(), path)).toJSON().data
315
- )
321
+ import_fs.default.readFileSync((0, import_path.relative)(this.cwd ?? process.cwd(), path)).toJSON().data
316
322
  ), "fileToBuffer");
317
323
  dirContainsDir(readDir, targetDir, options) {
318
324
  return this.readDir(readDir, options).filter((t) => t.split(".").length === 1).includes(targetDir);
319
325
  }
320
- parseJsonBuffer(p) {
321
- return JSON.parse(
322
- Buffer.from(Buffer.from(p).toJSON().data).toString("utf-8")
323
- );
324
- }
325
326
  /* begin url */
326
327
  isServerSide() {
327
328
  return typeof window === "undefined";
@@ -358,20 +359,43 @@ var Fs = class {
358
359
  };
359
360
  }
360
361
  /* end url */
362
+ get cjsVal() {
363
+ return ["application/node", "text/javascript"].reduce(
364
+ (union) => union
365
+ );
366
+ }
361
367
  get gzVal() {
362
368
  return ["application/x-gzip", "application/gzip"].reduce(
363
- (vals) => vals
369
+ (union) => union
370
+ );
371
+ }
372
+ get jsVal() {
373
+ return ["application/node", "text/javascript"].reduce(
374
+ (union) => union
375
+ );
376
+ }
377
+ get objVal() {
378
+ return ["application/octet-stream", "text/plain", "model/obj"].reduce((union) => union);
379
+ }
380
+ get tsVal() {
381
+ return ["text/typescript", "video/mp2t", "video/vnd.dlna.mpeg-tts"].reduce((union) => union);
382
+ }
383
+ get ttfVal() {
384
+ return ["application/font-sfnt", "font/ttf"].reduce(
385
+ (union) => union
364
386
  );
365
387
  }
366
388
  get zipVal() {
367
- return ["application/zip", "application/x-zip-compressed"].reduce((vals) => vals);
389
+ return ["application/zip", "application/x-zip-compressed"].reduce((union) => union);
368
390
  }
369
391
  get mimeTypeObj() {
370
392
  return {
371
393
  aac: "audio/aac",
372
394
  abw: "application/x-abiword",
395
+ aces: "image/aces",
373
396
  apng: "image/apng",
374
397
  arc: "application/x-freearc",
398
+ avci: "image/avci",
375
399
  avif: "image/avif",
376
400
  avi: "video/x-msvideo",
377
401
  azw: "application/vnd.amazon.ebook",
@@ -380,27 +404,36 @@ var Fs = class {
380
404
  bz: "application/x-bzip",
381
405
  bz2: "application/x-bzip2",
382
406
  cda: "application/x-cdf",
383
- cjs: "application/javascript",
407
+ cjs: this.cjsVal,
384
408
  csh: "application/x-csh",
385
409
  css: "text/css",
386
410
  csv: "text/csv",
387
411
  doc: "application/msword",
388
412
  docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
413
+ dpx: "image/dpx",
414
+ emf: "image/emf",
389
415
  eot: "application/vnd.ms-fontobject",
390
416
  epub: "application/epub+zip",
391
417
  gif: "image/gif",
418
+ glb: "model/gltf-binary",
419
+ gltf: "model/gltf+json",
392
420
  gz: this.gzVal,
421
+ hjif: "haptics/hjif",
422
+ hmpg: "haptics/hmpg",
393
423
  htm: "text/html",
394
424
  html: "text/html",
395
425
  ico: "image/vnd.microsoft.icon",
396
426
  ics: "text/calendar",
427
+ ivs: "haptics/ivs",
397
428
  jar: "application/java-archive",
398
429
  jpeg: "image/jpeg",
399
430
  jpg: "image/jpeg",
400
- js: "text/javascript",
431
+ js: this.jsVal,
401
432
  json: "application/json",
402
433
  jsonld: "application/ld+json",
403
434
  m3u8: "application/vnd.apple.mpegurl",
435
+ m4a: "audio/mp4",
436
+ m4v: "video/mp4",
404
437
  md: "text/markdown",
405
438
  mdx: "application/x-mdx",
406
439
  mid: "audio/midi",
@@ -411,10 +444,12 @@ var Fs = class {
411
444
  mpeg: "video/mpeg",
412
445
  mpkg: "application/vnd.apple.installer+xml",
413
446
  ndjson: "application/x-ndjson",
447
+ obj: this.objVal,
414
448
  odp: "application/vnd.oasis.opendocument.presentation",
415
449
  ods: "application/vnd.oasis.opendocument.spreadsheet",
416
450
  odt: "application/vnd.oasis.opendocument.text",
417
451
  oga: "audio/ogg",
452
+ ogg: "audio/ogg",
418
453
  ogv: "video/ogg",
419
454
  ogx: "application/ogg",
420
455
  opus: "audio/ogg",
@@ -425,17 +460,24 @@ var Fs = class {
425
460
  pkpass: "application/vnd.apple.pkpass",
426
461
  ppt: "application/vnd.ms-powerpoint",
427
462
  pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
463
+ py: "text/x-python",
464
+ pyc: "application/x-python-code",
428
465
  rar: "application/vnd.rar",
429
466
  rtf: "application/rtf",
430
467
  sh: "application/x-sh",
468
+ sql: "application/sql",
431
469
  svg: "image/svg+xml",
432
470
  tar: "application/x-tar",
433
471
  tif: "image/tiff",
434
472
  tiff: "image/tiff",
435
- ts: "video/mp2t",
436
- ttf: "font/ttf",
473
+ toml: "application/toml",
474
+ ts: this.tsVal,
475
+ ttf: this.ttfVal,
437
476
  txt: "text/plain",
477
+ usdz: "model/vnd.usdz+zip",
438
478
  vsd: "application/vnd.visio",
479
+ vtt: "text/vtt",
480
+ wasm: "application/wasm",
439
481
  wav: "audio/wav",
440
482
  weba: "video/webm",
441
483
  webp: "image/webp",
@@ -446,6 +488,8 @@ var Fs = class {
446
488
  xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
447
489
  xml: "application/xml",
448
490
  xul: "application/vnd.mozilla.xul+xml",
491
+ yaml: "application/yaml",
492
+ yml: "application/yaml",
449
493
  zip: this.zipVal,
450
494
  "3gp": "video/3gpp",
451
495
  "3g2": "video/3gpp2",
@@ -453,18 +497,20 @@ var Fs = class {
453
497
  };
454
498
  }
455
499
  assetType(url) {
456
- return this.parseUrl(url).pathname?.split(/([.])/gim)?.reverse()?.[0];
500
+ const u = this.parseUrl(url);
501
+ return u.pathname?.split(/([.])/gim)?.reverse()?.[0];
457
502
  }
458
503
  getMime(input) {
459
504
  return this.mimeTypeObj[input];
460
505
  }
506
+ hmm = /* @__PURE__ */ __name((input) => {
507
+ return this.mimeTypeObj[input];
508
+ }, "hmm");
461
509
  async assetToBuffer(path) {
462
510
  const [fetcher] = await Promise.all([
463
511
  fetch(path).then((t) => t.arrayBuffer())
464
512
  ]);
465
- const b64encodedData = `data:${this.getMime(this.assetType(path))};base64, ${Buffer.from(
466
- Buffer.from(fetcher).toJSON().data
467
- ).toString("base64")}`;
513
+ const b64encodedData = `data:${this.getMime(this.assetType(path))};base64, ${Buffer.from(fetcher).toString("base64")}`;
468
514
  const extension = this.assetType(path);
469
515
  return {
470
516
  b64encodedData,
@@ -472,27 +518,40 @@ var Fs = class {
472
518
  };
473
519
  }
474
520
  async assetToBufferView(path) {
475
- const [fetcher] = await Promise.all([
476
- fetch(path).then((t) => t.arrayBuffer())
477
- ]);
478
- const reader = new ReadableStream({
479
- type: "bytes",
480
- async pull(controller) {
481
- const byobRequest = controller.byobRequest;
482
- byobRequest?.respond(byobRequest?.view?.byteLength ?? 0);
521
+ const p = this.parseUrl(path);
522
+ const doesUrlPathContainFileExtension = /\./g.test(
523
+ p.pathname.split(/\//g).reverse()[0] ?? ""
524
+ );
525
+ if (doesUrlPathContainFileExtension === false)
526
+ console.warn(`no file extension detected in input url ${path}, attempting fetch`);
527
+ const response = await fetch(path);
528
+ if (!response.ok) {
529
+ throw new Error(`Failed to fetch asset: ${response.statusText}`);
530
+ }
531
+ const reader = response.body?.getReader();
532
+ if (reader) {
533
+ const chunks = [];
534
+ while (true) {
535
+ const { done, value } = await reader.read();
536
+ if (done) break;
537
+ if (value) chunks.push(value);
483
538
  }
484
- });
485
- const readerByob = new ReadableStreamBYOBReader(reader);
486
- const readableByteStream = fetcher;
487
- const data = await readerByob.read(Buffer.from(readableByteStream));
488
- const b64encodedData = `data:${this.getMime(this.assetType(path))};base64, ${Buffer.from(
489
- Buffer.from(data.value ?? Buffer.alloc(0)).toJSON().data
490
- ).toString("base64")}`;
491
- const extension = this.assetType(path);
492
- return {
493
- b64encodedData,
494
- extension
495
- };
539
+ const totalLength = chunks.reduce((acc, chunk) => acc + chunk.length, 0);
540
+ const completeBuffer = new Uint8Array(totalLength);
541
+ let offset = 0;
542
+ for (const chunk of chunks) {
543
+ completeBuffer.set(chunk, offset);
544
+ offset += chunk.length;
545
+ }
546
+ const b64encodedData = `data:${this.getMime(this.assetType(path))};base64, ${Buffer.from(completeBuffer).toString("base64")}`;
547
+ const extension = this.assetType(path);
548
+ return { b64encodedData, extension };
549
+ } else {
550
+ const arrayBuffer = await response.arrayBuffer();
551
+ const b64encodedData = `data:${this.getMime(this.assetType(path))};base64, ${Buffer.from(arrayBuffer).toString("base64")}`;
552
+ const extension = this.assetType(path);
553
+ return { b64encodedData, extension };
554
+ }
496
555
  }
497
556
  formatHelper(f) {
498
557
  if (/([A-Za-z]+-[A-Za-z]+)/g.test(f) === true) {
@@ -501,7 +560,7 @@ var Fs = class {
501
560
  } else return f.substring(0, 1).toUpperCase().concat(f.substring(1));
502
561
  }
503
562
  range(from, to) {
504
- const values = [];
563
+ const values = Array.of();
505
564
  for (let i = from; i < to; i++) {
506
565
  values.push(i);
507
566
  }
@@ -541,10 +600,9 @@ var Fs = class {
541
600
  {
542
601
  const sliceSize = 512;
543
602
  const typeMatch = b64Data.match(
544
- /^data:(image|application|video|text|font)\/[A-Za-z0-9+-.]+;base64,/
603
+ /^data:(?:image|application|haptics|video|text|font|model|audio|multipart)\/[A-Za-z0-9+-.]+(?:;[^,]+)*;base64,/i
545
604
  );
546
605
  const type = typeMatch?.[1];
547
- console.log(type ?? "");
548
606
  if (!typeMatch) {
549
607
  throw new Error(`${b64Data} is not a valid data Url`);
550
608
  }
@@ -564,5 +622,107 @@ var Fs = class {
564
622
  return blob;
565
623
  }
566
624
  }
625
+ cleanDataUrl(props) {
626
+ return props.replace(
627
+ /^data:(?:image|application|haptics|video|text|font|model|audio|multipart)\/[A-Za-z0-9+-.]+(?:;[^,]+)*;base64,/i,
628
+ ""
629
+ );
630
+ }
631
+ /**
632
+ * public cleanDataUrl<const C extends string>(props: C) {
633
+ return props.replace(
634
+ /^data:(?:image|application|video|text|font|model|audio|haptics|multipart)\/[A-Za-z0-9+-.]+(?:;[^,]+)*;base64,/i,
635
+ ""
636
+ );
637
+ }
638
+
639
+ */
640
+ /**
641
+ *
642
+ * @param inputUrl remote url to fetch data from
643
+ * @param outputPath desired output path relative to the cwd
644
+ * @param useDetectedExtension optional, defaults to true
645
+ *
646
+ * if `useDetectedExtension` is false you must include the file extension in your output path &rarr;
647
+ *
648
+ * 🚫 'public/assets/image-1'
649
+ *
650
+ * ✅ 'public/assets/image-1.png'
651
+ */
652
+ async fetchRemoteWriteLocal(inputUrl, outputPath, useDetectedExtension = true) {
653
+ try {
654
+ const result = await this.assetToBufferView(inputUrl);
655
+ const cleanData = this.cleanDataUrl(result.b64encodedData);
656
+ const formattedPath = useDetectedExtension ? `${outputPath}.${result.extension}` : outputPath;
657
+ if (/\./g.test(formattedPath) === false) {
658
+ throw new Error(
659
+ "either add false as the third argument in `fetchRemoteWriteLocal` (input, output, use-detected-file-extension) or provide an output path without a file extension"
660
+ );
661
+ }
662
+ this.withWs(formattedPath, Buffer.from(cleanData, "base64"));
663
+ } catch (err) {
664
+ return console.error(err);
665
+ }
666
+ }
667
+ // USE fluent-ffmpeg for video/animated image transforms (apng, etc)
668
+ // https://www.npmjs.com/package/fluent-ffmpeg
669
+ // https://www.npmjs.com/package/@types/fluent-ffmpeg
670
+ async imageTransform({
671
+ format,
672
+ target,
673
+ quality = 80,
674
+ tint,
675
+ resize
676
+ }) {
677
+ if (tint && !resize) {
678
+ return await (0, import_sharp.default)(target).toFormat(format, { quality }).tint(tint).toBuffer();
679
+ } else if (!tint && resize) {
680
+ return await (0, import_sharp.default)(target).toFormat(format, { quality }).resize(resize.widthOrOptions, resize.height, resize.options).toBuffer();
681
+ } else if (tint && resize) {
682
+ return await (0, import_sharp.default)(target).toFormat(format, { quality }).tint(tint).resize(resize.widthOrOptions, resize.height, resize.options).toBuffer();
683
+ } else return await (0, import_sharp.default)(target).toFormat(format, { quality }).toBuffer();
684
+ }
685
+ // public async convertImage<
686
+ // const L extends "local" | "remote",
687
+ // const F extends "webp" | "avif" | "jpg" | "png",
688
+ // const I extends string,
689
+ // const O extends string
690
+ // >(isLocal: L, inputUrl: I, outputPath: O, useDetectedExtension = true) {
691
+ // if (isLocal === "remote") {
692
+ // try {
693
+ // const result = await this.assetToBufferView(inputUrl);
694
+ // const cleanData = this.cleanDataUrl(result.b64encodedData);
695
+ // const imageBuffer = Buffer.from(cleanData, "base64");
696
+ // const s = this.imageTransform({format: "webp", target: imageBuffer, quality: 100, resize: {options: {width: 1.2, height: 1.2}}} )
697
+ // const formattedPath = useDetectedExtension
698
+ // ? `${outputPath}.${result.extension}`
699
+ // : outputPath;
700
+ // if (/\./g.test(formattedPath) === false) {
701
+ // throw new Error(
702
+ // "either add false as the third argument in `fetchRemoteWriteLocal` (input, output, use-detected-file-extension)"
703
+ // );
704
+ // }
705
+ // this.withWs(formattedPath, Buffer.from(cleanData, "base64"));
706
+ // } catch (err) {
707
+ // return console.error(err);
708
+ // }
709
+ // } else {
710
+ // try {
711
+ // const result = await this.assetToBufferView(inputUrl);
712
+ // const cleanData = this.cleanDataUrl(result.b64encodedData);
713
+ // const formattedPath = useDetectedExtension
714
+ // ? `${outputPath}.${result.extension}`
715
+ // : outputPath;
716
+ // if (/\./g.test(formattedPath) === false) {
717
+ // throw new Error(
718
+ // "either add false as the third argument in `fetchRemoteWriteLocal` (input, output, use-detected-file-extension)"
719
+ // );
720
+ // }
721
+ // this.withWs(formattedPath, Buffer.from(cleanData, "base64"));
722
+ // } catch (err) {
723
+ // return console.error(err);
724
+ // }
725
+ // }
726
+ // }
567
727
  };
568
728
  //# sourceMappingURL=index.cjs.map