@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.
@@ -87,8 +87,9 @@ var import_dotenv_expand = __toESM(require_main(), 1);
87
87
  import { execSync } from "child_process";
88
88
  import fsSync from "fs";
89
89
  import fsAsync from "fs/promises";
90
- import { relative } from "path";
90
+ import { join, relative, resolve } from "path";
91
91
  import * as dotenv from "dotenv";
92
+ import sharp from "sharp";
92
93
  dotenv.config();
93
94
  var Fs = class {
94
95
  constructor(cwd) {
@@ -108,20 +109,20 @@ var Fs = class {
108
109
  );
109
110
  }
110
111
  excludeTargeted = /* @__PURE__ */ __name((obj, props, sort) => {
111
- const resolve = Object.fromEntries(
112
+ const resolve2 = Object.fromEntries(
112
113
  Object.entries(obj).map(([key, val]) => {
113
114
  if (props.includes(key)) {
114
115
  return ["omit", "omit"];
115
116
  } else return [key, val];
116
117
  }).filter(([t, _v]) => /omit/.test(t) === false)
117
118
  );
118
- return typeof sort !== "undefined" ? this.sort(resolve, sort) : resolve;
119
+ return typeof sort !== "undefined" ? this.sort(resolve2, sort) : resolve2;
119
120
  }, "excludeTargeted");
120
121
  includeTargeted = /* @__PURE__ */ __name((obj, props, sort) => {
121
- const resolve = Object.fromEntries(
122
+ const resolve2 = Object.fromEntries(
122
123
  props.map((val) => this.extractTuple(obj, val))
123
124
  );
124
- return typeof sort !== "undefined" ? this.sort(resolve, sort) : resolve;
125
+ return typeof sort !== "undefined" ? this.sort(resolve2, sort) : resolve2;
125
126
  }, "includeTargeted");
126
127
  get myEnv() {
127
128
  return dotenv.config({ processEnv: {} });
@@ -145,6 +146,7 @@ var Fs = class {
145
146
  return { ...this.omitFields(targ, keys) };
146
147
  }
147
148
  exists(target) {
149
+ if (!/\//gm.test(target)) return fsSync.existsSync(resolve(join(this.cwd, target)));
148
150
  return fsSync.existsSync(relative(this.cwd ?? process.cwd(), target));
149
151
  }
150
152
  arrToArrOfArrs = /* @__PURE__ */ __name(({
@@ -152,7 +154,7 @@ var Fs = class {
152
154
  arrOfArrsAggregator = Array.of(),
153
155
  interval
154
156
  }) => new Promise(
155
- (resolve, _reject) => resolve(
157
+ (resolve2, _reject) => resolve2(
156
158
  ((interval2) => {
157
159
  for (let i = 0; i <= arrToFragment.length; i++) {
158
160
  if ((i % interval2 === 0 || i === 0) && i <= arrToFragment.length) {
@@ -164,7 +166,7 @@ var Fs = class {
164
166
  )
165
167
  ).then((_) => arrOfArrsAggregator), "arrToArrOfArrs");
166
168
  wait(ms) {
167
- return new Promise((resolve) => setTimeout(resolve, ms));
169
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
168
170
  }
169
171
  countsSorter = /* @__PURE__ */ __name(({
170
172
  counter,
@@ -182,8 +184,15 @@ var Fs = class {
182
184
  (v) => Buffer.isBuffer(v) ? Buffer.from(v).toString("utf-8") : v
183
185
  );
184
186
  }
187
+ isRootPathTargeted(path) {
188
+ if (/^(?:\.\/|\.|\/|root|\.\.\/|~\/\.?|cwd|\.\/\.)$/g.test(path)) {
189
+ return true;
190
+ } else return false;
191
+ }
185
192
  readDir(path, options) {
186
- return this.handleBuffStrArrUnion(
193
+ if (this.isRootPathTargeted(path)) {
194
+ return this.handleBuffStrArrUnion(fsSync.readdirSync(resolve(join(this.cwd, "./")), options));
195
+ } else return this.handleBuffStrArrUnion(
187
196
  fsSync.readdirSync(
188
197
  relative(this.cwd ??= process.cwd(), path),
189
198
  options
@@ -193,9 +202,7 @@ var Fs = class {
193
202
  executeCommand = /* @__PURE__ */ __name(({
194
203
  command,
195
204
  ...options
196
- }) => Buffer.from(
197
- Buffer.from(execSync(command, { ...options }).toJSON().data)
198
- ).toString("utf-8"), "executeCommand");
205
+ }) => Buffer.from(execSync(command, { ...options }).toJSON().data).toString("utf-8"), "executeCommand");
199
206
  fileGenTimestamp(d) {
200
207
  const date = d.toISOString();
201
208
  return `/* file-autogenerated by @d0paminedriven/fs on ${date.split(/([T])/gm)?.[0]} at ${date.split(/([T])/gm)[2]?.split(/([Z])/gm)?.[0]} UTC */`;
@@ -207,6 +214,7 @@ var Fs = class {
207
214
  return this.fileGenTimestamp(d).replace("/*", "<!--").replace("*/", "-->");
208
215
  }
209
216
  existsSync(path) {
217
+ if (!/\//gm.test(path)) return fsSync.existsSync(resolve(join(this.cwd, path)));
210
218
  return fsSync.existsSync(relative(this.cwd ?? process.cwd(), path));
211
219
  }
212
220
  pathHandler(path) {
@@ -269,18 +277,11 @@ var Fs = class {
269
277
  }
270
278
  }, "writeFileAsync");
271
279
  fileToBuffer = /* @__PURE__ */ __name((path) => Buffer.from(
272
- Buffer.from(
273
- fsSync.readFileSync(relative(this.cwd ?? process.cwd(), path)).toJSON().data
274
- )
280
+ fsSync.readFileSync(relative(this.cwd ?? process.cwd(), path)).toJSON().data
275
281
  ), "fileToBuffer");
276
282
  dirContainsDir(readDir, targetDir, options) {
277
283
  return this.readDir(readDir, options).filter((t) => t.split(".").length === 1).includes(targetDir);
278
284
  }
279
- parseJsonBuffer(p) {
280
- return JSON.parse(
281
- Buffer.from(Buffer.from(p).toJSON().data).toString("utf-8")
282
- );
283
- }
284
285
  /* begin url */
285
286
  isServerSide() {
286
287
  return typeof window === "undefined";
@@ -317,20 +318,43 @@ var Fs = class {
317
318
  };
318
319
  }
319
320
  /* end url */
321
+ get cjsVal() {
322
+ return ["application/node", "text/javascript"].reduce(
323
+ (union) => union
324
+ );
325
+ }
320
326
  get gzVal() {
321
327
  return ["application/x-gzip", "application/gzip"].reduce(
322
- (vals) => vals
328
+ (union) => union
329
+ );
330
+ }
331
+ get jsVal() {
332
+ return ["application/node", "text/javascript"].reduce(
333
+ (union) => union
334
+ );
335
+ }
336
+ get objVal() {
337
+ return ["application/octet-stream", "text/plain", "model/obj"].reduce((union) => union);
338
+ }
339
+ get tsVal() {
340
+ return ["text/typescript", "video/mp2t", "video/vnd.dlna.mpeg-tts"].reduce((union) => union);
341
+ }
342
+ get ttfVal() {
343
+ return ["application/font-sfnt", "font/ttf"].reduce(
344
+ (union) => union
323
345
  );
324
346
  }
325
347
  get zipVal() {
326
- return ["application/zip", "application/x-zip-compressed"].reduce((vals) => vals);
348
+ return ["application/zip", "application/x-zip-compressed"].reduce((union) => union);
327
349
  }
328
350
  get mimeTypeObj() {
329
351
  return {
330
352
  aac: "audio/aac",
331
353
  abw: "application/x-abiword",
354
+ aces: "image/aces",
332
355
  apng: "image/apng",
333
356
  arc: "application/x-freearc",
357
+ avci: "image/avci",
334
358
  avif: "image/avif",
335
359
  avi: "video/x-msvideo",
336
360
  azw: "application/vnd.amazon.ebook",
@@ -339,27 +363,36 @@ var Fs = class {
339
363
  bz: "application/x-bzip",
340
364
  bz2: "application/x-bzip2",
341
365
  cda: "application/x-cdf",
342
- cjs: "application/javascript",
366
+ cjs: this.cjsVal,
343
367
  csh: "application/x-csh",
344
368
  css: "text/css",
345
369
  csv: "text/csv",
346
370
  doc: "application/msword",
347
371
  docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
372
+ dpx: "image/dpx",
373
+ emf: "image/emf",
348
374
  eot: "application/vnd.ms-fontobject",
349
375
  epub: "application/epub+zip",
350
376
  gif: "image/gif",
377
+ glb: "model/gltf-binary",
378
+ gltf: "model/gltf+json",
351
379
  gz: this.gzVal,
380
+ hjif: "haptics/hjif",
381
+ hmpg: "haptics/hmpg",
352
382
  htm: "text/html",
353
383
  html: "text/html",
354
384
  ico: "image/vnd.microsoft.icon",
355
385
  ics: "text/calendar",
386
+ ivs: "haptics/ivs",
356
387
  jar: "application/java-archive",
357
388
  jpeg: "image/jpeg",
358
389
  jpg: "image/jpeg",
359
- js: "text/javascript",
390
+ js: this.jsVal,
360
391
  json: "application/json",
361
392
  jsonld: "application/ld+json",
362
393
  m3u8: "application/vnd.apple.mpegurl",
394
+ m4a: "audio/mp4",
395
+ m4v: "video/mp4",
363
396
  md: "text/markdown",
364
397
  mdx: "application/x-mdx",
365
398
  mid: "audio/midi",
@@ -370,10 +403,12 @@ var Fs = class {
370
403
  mpeg: "video/mpeg",
371
404
  mpkg: "application/vnd.apple.installer+xml",
372
405
  ndjson: "application/x-ndjson",
406
+ obj: this.objVal,
373
407
  odp: "application/vnd.oasis.opendocument.presentation",
374
408
  ods: "application/vnd.oasis.opendocument.spreadsheet",
375
409
  odt: "application/vnd.oasis.opendocument.text",
376
410
  oga: "audio/ogg",
411
+ ogg: "audio/ogg",
377
412
  ogv: "video/ogg",
378
413
  ogx: "application/ogg",
379
414
  opus: "audio/ogg",
@@ -384,17 +419,24 @@ var Fs = class {
384
419
  pkpass: "application/vnd.apple.pkpass",
385
420
  ppt: "application/vnd.ms-powerpoint",
386
421
  pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
422
+ py: "text/x-python",
423
+ pyc: "application/x-python-code",
387
424
  rar: "application/vnd.rar",
388
425
  rtf: "application/rtf",
389
426
  sh: "application/x-sh",
427
+ sql: "application/sql",
390
428
  svg: "image/svg+xml",
391
429
  tar: "application/x-tar",
392
430
  tif: "image/tiff",
393
431
  tiff: "image/tiff",
394
- ts: "video/mp2t",
395
- ttf: "font/ttf",
432
+ toml: "application/toml",
433
+ ts: this.tsVal,
434
+ ttf: this.ttfVal,
396
435
  txt: "text/plain",
436
+ usdz: "model/vnd.usdz+zip",
397
437
  vsd: "application/vnd.visio",
438
+ vtt: "text/vtt",
439
+ wasm: "application/wasm",
398
440
  wav: "audio/wav",
399
441
  weba: "video/webm",
400
442
  webp: "image/webp",
@@ -405,6 +447,8 @@ var Fs = class {
405
447
  xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
406
448
  xml: "application/xml",
407
449
  xul: "application/vnd.mozilla.xul+xml",
450
+ yaml: "application/yaml",
451
+ yml: "application/yaml",
408
452
  zip: this.zipVal,
409
453
  "3gp": "video/3gpp",
410
454
  "3g2": "video/3gpp2",
@@ -412,18 +456,20 @@ var Fs = class {
412
456
  };
413
457
  }
414
458
  assetType(url) {
415
- return this.parseUrl(url).pathname?.split(/([.])/gim)?.reverse()?.[0];
459
+ const u = this.parseUrl(url);
460
+ return u.pathname?.split(/([.])/gim)?.reverse()?.[0];
416
461
  }
417
462
  getMime(input) {
418
463
  return this.mimeTypeObj[input];
419
464
  }
465
+ hmm = /* @__PURE__ */ __name((input) => {
466
+ return this.mimeTypeObj[input];
467
+ }, "hmm");
420
468
  async assetToBuffer(path) {
421
469
  const [fetcher] = await Promise.all([
422
470
  fetch(path).then((t) => t.arrayBuffer())
423
471
  ]);
424
- const b64encodedData = `data:${this.getMime(this.assetType(path))};base64, ${Buffer.from(
425
- Buffer.from(fetcher).toJSON().data
426
- ).toString("base64")}`;
472
+ const b64encodedData = `data:${this.getMime(this.assetType(path))};base64, ${Buffer.from(fetcher).toString("base64")}`;
427
473
  const extension = this.assetType(path);
428
474
  return {
429
475
  b64encodedData,
@@ -431,27 +477,40 @@ var Fs = class {
431
477
  };
432
478
  }
433
479
  async assetToBufferView(path) {
434
- const [fetcher] = await Promise.all([
435
- fetch(path).then((t) => t.arrayBuffer())
436
- ]);
437
- const reader = new ReadableStream({
438
- type: "bytes",
439
- async pull(controller) {
440
- const byobRequest = controller.byobRequest;
441
- byobRequest?.respond(byobRequest?.view?.byteLength ?? 0);
480
+ const p = this.parseUrl(path);
481
+ const doesUrlPathContainFileExtension = /\./g.test(
482
+ p.pathname.split(/\//g).reverse()[0] ?? ""
483
+ );
484
+ if (doesUrlPathContainFileExtension === false)
485
+ console.warn(`no file extension detected in input url ${path}, attempting fetch`);
486
+ const response = await fetch(path);
487
+ if (!response.ok) {
488
+ throw new Error(`Failed to fetch asset: ${response.statusText}`);
489
+ }
490
+ const reader = response.body?.getReader();
491
+ if (reader) {
492
+ const chunks = [];
493
+ while (true) {
494
+ const { done, value } = await reader.read();
495
+ if (done) break;
496
+ if (value) chunks.push(value);
442
497
  }
443
- });
444
- const readerByob = new ReadableStreamBYOBReader(reader);
445
- const readableByteStream = fetcher;
446
- const data = await readerByob.read(Buffer.from(readableByteStream));
447
- const b64encodedData = `data:${this.getMime(this.assetType(path))};base64, ${Buffer.from(
448
- Buffer.from(data.value ?? Buffer.alloc(0)).toJSON().data
449
- ).toString("base64")}`;
450
- const extension = this.assetType(path);
451
- return {
452
- b64encodedData,
453
- extension
454
- };
498
+ const totalLength = chunks.reduce((acc, chunk) => acc + chunk.length, 0);
499
+ const completeBuffer = new Uint8Array(totalLength);
500
+ let offset = 0;
501
+ for (const chunk of chunks) {
502
+ completeBuffer.set(chunk, offset);
503
+ offset += chunk.length;
504
+ }
505
+ const b64encodedData = `data:${this.getMime(this.assetType(path))};base64, ${Buffer.from(completeBuffer).toString("base64")}`;
506
+ const extension = this.assetType(path);
507
+ return { b64encodedData, extension };
508
+ } else {
509
+ const arrayBuffer = await response.arrayBuffer();
510
+ const b64encodedData = `data:${this.getMime(this.assetType(path))};base64, ${Buffer.from(arrayBuffer).toString("base64")}`;
511
+ const extension = this.assetType(path);
512
+ return { b64encodedData, extension };
513
+ }
455
514
  }
456
515
  formatHelper(f) {
457
516
  if (/([A-Za-z]+-[A-Za-z]+)/g.test(f) === true) {
@@ -460,7 +519,7 @@ var Fs = class {
460
519
  } else return f.substring(0, 1).toUpperCase().concat(f.substring(1));
461
520
  }
462
521
  range(from, to) {
463
- const values = [];
522
+ const values = Array.of();
464
523
  for (let i = from; i < to; i++) {
465
524
  values.push(i);
466
525
  }
@@ -500,10 +559,9 @@ var Fs = class {
500
559
  {
501
560
  const sliceSize = 512;
502
561
  const typeMatch = b64Data.match(
503
- /^data:(image|application|video|text|font)\/[A-Za-z0-9+-.]+;base64,/
562
+ /^data:(?:image|application|haptics|video|text|font|model|audio|multipart)\/[A-Za-z0-9+-.]+(?:;[^,]+)*;base64,/i
504
563
  );
505
564
  const type = typeMatch?.[1];
506
- console.log(type ?? "");
507
565
  if (!typeMatch) {
508
566
  throw new Error(`${b64Data} is not a valid data Url`);
509
567
  }
@@ -523,9 +581,111 @@ var Fs = class {
523
581
  return blob;
524
582
  }
525
583
  }
584
+ cleanDataUrl(props) {
585
+ return props.replace(
586
+ /^data:(?:image|application|haptics|video|text|font|model|audio|multipart)\/[A-Za-z0-9+-.]+(?:;[^,]+)*;base64,/i,
587
+ ""
588
+ );
589
+ }
590
+ /**
591
+ * public cleanDataUrl<const C extends string>(props: C) {
592
+ return props.replace(
593
+ /^data:(?:image|application|video|text|font|model|audio|haptics|multipart)\/[A-Za-z0-9+-.]+(?:;[^,]+)*;base64,/i,
594
+ ""
595
+ );
596
+ }
597
+
598
+ */
599
+ /**
600
+ *
601
+ * @param inputUrl remote url to fetch data from
602
+ * @param outputPath desired output path relative to the cwd
603
+ * @param useDetectedExtension optional, defaults to true
604
+ *
605
+ * if `useDetectedExtension` is false you must include the file extension in your output path &rarr;
606
+ *
607
+ * 🚫 'public/assets/image-1'
608
+ *
609
+ * ✅ 'public/assets/image-1.png'
610
+ */
611
+ async fetchRemoteWriteLocal(inputUrl, outputPath, useDetectedExtension = true) {
612
+ try {
613
+ const result = await this.assetToBufferView(inputUrl);
614
+ const cleanData = this.cleanDataUrl(result.b64encodedData);
615
+ const formattedPath = useDetectedExtension ? `${outputPath}.${result.extension}` : outputPath;
616
+ if (/\./g.test(formattedPath) === false) {
617
+ throw new Error(
618
+ "either add false as the third argument in `fetchRemoteWriteLocal` (input, output, use-detected-file-extension) or provide an output path without a file extension"
619
+ );
620
+ }
621
+ this.withWs(formattedPath, Buffer.from(cleanData, "base64"));
622
+ } catch (err) {
623
+ return console.error(err);
624
+ }
625
+ }
626
+ // USE fluent-ffmpeg for video/animated image transforms (apng, etc)
627
+ // https://www.npmjs.com/package/fluent-ffmpeg
628
+ // https://www.npmjs.com/package/@types/fluent-ffmpeg
629
+ async imageTransform({
630
+ format,
631
+ target,
632
+ quality = 80,
633
+ tint,
634
+ resize
635
+ }) {
636
+ if (tint && !resize) {
637
+ return await sharp(target).toFormat(format, { quality }).tint(tint).toBuffer();
638
+ } else if (!tint && resize) {
639
+ return await sharp(target).toFormat(format, { quality }).resize(resize.widthOrOptions, resize.height, resize.options).toBuffer();
640
+ } else if (tint && resize) {
641
+ return await sharp(target).toFormat(format, { quality }).tint(tint).resize(resize.widthOrOptions, resize.height, resize.options).toBuffer();
642
+ } else return await sharp(target).toFormat(format, { quality }).toBuffer();
643
+ }
644
+ // public async convertImage<
645
+ // const L extends "local" | "remote",
646
+ // const F extends "webp" | "avif" | "jpg" | "png",
647
+ // const I extends string,
648
+ // const O extends string
649
+ // >(isLocal: L, inputUrl: I, outputPath: O, useDetectedExtension = true) {
650
+ // if (isLocal === "remote") {
651
+ // try {
652
+ // const result = await this.assetToBufferView(inputUrl);
653
+ // const cleanData = this.cleanDataUrl(result.b64encodedData);
654
+ // const imageBuffer = Buffer.from(cleanData, "base64");
655
+ // const s = this.imageTransform({format: "webp", target: imageBuffer, quality: 100, resize: {options: {width: 1.2, height: 1.2}}} )
656
+ // const formattedPath = useDetectedExtension
657
+ // ? `${outputPath}.${result.extension}`
658
+ // : outputPath;
659
+ // if (/\./g.test(formattedPath) === false) {
660
+ // throw new Error(
661
+ // "either add false as the third argument in `fetchRemoteWriteLocal` (input, output, use-detected-file-extension)"
662
+ // );
663
+ // }
664
+ // this.withWs(formattedPath, Buffer.from(cleanData, "base64"));
665
+ // } catch (err) {
666
+ // return console.error(err);
667
+ // }
668
+ // } else {
669
+ // try {
670
+ // const result = await this.assetToBufferView(inputUrl);
671
+ // const cleanData = this.cleanDataUrl(result.b64encodedData);
672
+ // const formattedPath = useDetectedExtension
673
+ // ? `${outputPath}.${result.extension}`
674
+ // : outputPath;
675
+ // if (/\./g.test(formattedPath) === false) {
676
+ // throw new Error(
677
+ // "either add false as the third argument in `fetchRemoteWriteLocal` (input, output, use-detected-file-extension)"
678
+ // );
679
+ // }
680
+ // this.withWs(formattedPath, Buffer.from(cleanData, "base64"));
681
+ // } catch (err) {
682
+ // return console.error(err);
683
+ // }
684
+ // }
685
+ // }
526
686
  };
527
687
 
528
688
  export {
529
689
  Fs
530
690
  };
531
- //# sourceMappingURL=chunk-MZZJMVSV.js.map
691
+ //# sourceMappingURL=chunk-J3NUWUIN.js.map