@reliverse/pathkit 1.2.4 → 1.2.6

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 (2) hide show
  1. package/bin/mod.js +106 -36
  2. package/package.json +1 -1
package/bin/mod.js CHANGED
@@ -2,19 +2,14 @@ import fs from "node:fs/promises";
2
2
  import {
3
3
  getFileImportsExports
4
4
  } from "./impl/getFileImportsExports.js";
5
- const logger = (msg, debugOnly = false) => {
6
- if (!debugOnly || DEBUG_MODE) {
7
- const message = typeof msg === "function" ? msg() : msg;
8
- console.log(`\x1B[2m${message}\x1B[0m`);
9
- }
5
+ const logger = (msg) => {
6
+ const message = typeof msg === "function" ? msg() : msg;
7
+ console.log(`\x1B[2m${message}\x1B[0m`);
10
8
  };
11
- const logInternal = (msg) => {
12
- if (DEBUG_MODE) {
13
- const message = typeof msg === "function" ? msg() : msg;
14
- console.log(`\x1B[36;2m${message}\x1B[0m`);
15
- }
9
+ const logger2 = (msg) => {
10
+ const message = typeof msg === "function" ? msg() : msg;
11
+ console.log(`\x1B[36;2m${message}\x1B[0m`);
16
12
  };
17
- const DEBUG_MODE = true;
18
13
  const EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".d.ts"];
19
14
  const SLASH = "/";
20
15
  const BACK_SLASH = "\\";
@@ -355,13 +350,20 @@ function reverseResolveAlias(path2, aliases) {
355
350
  return matches.sort((a, b) => b.length - a.length);
356
351
  }
357
352
  const findAliasMatch = (importPath, paths) => {
353
+ logger2(`[findAliasMatch] Processing import: ${importPath}`);
354
+ logger2(` - paths: ${JSON.stringify(paths)}`);
358
355
  const firstPathKey = Object.keys(paths)[0];
359
- if (!firstPathKey) return null;
356
+ if (!firstPathKey) {
357
+ logger2(` - no paths defined`);
358
+ return null;
359
+ }
360
360
  const baseAlias = firstPathKey.replace("/*", "");
361
361
  if (importPath.startsWith("@") && !importPath.startsWith(baseAlias)) {
362
+ logger2(` - skipping: npm package import`);
362
363
  return null;
363
364
  }
364
365
  if (paths[importPath]?.[0]) {
366
+ logger2(` - found exact match`);
365
367
  return {
366
368
  key: importPath,
367
369
  root: importPath,
@@ -372,11 +374,15 @@ const findAliasMatch = (importPath, paths) => {
372
374
  for (const aliasKey in paths) {
373
375
  if (aliasKey.endsWith("/*")) {
374
376
  const aliasRoot = aliasKey.slice(0, -2);
377
+ logger2(` - checking wildcard match for: ${aliasRoot}`);
375
378
  if (importPath === aliasRoot || importPath.startsWith(`${aliasRoot}/`)) {
376
379
  const suffix = importPath === aliasRoot ? "" : importPath.slice(aliasRoot.length + 1);
377
380
  const targetPaths = paths[aliasKey];
378
381
  if (targetPaths?.[0]) {
379
382
  const resolvedPathPattern = targetPaths[0].slice(0, -2);
383
+ logger2(` - found wildcard match`);
384
+ logger2(` - suffix: ${suffix}`);
385
+ logger2(` - resolvedPathPattern: ${resolvedPathPattern}`);
380
386
  return {
381
387
  key: aliasKey,
382
388
  root: aliasRoot,
@@ -387,6 +393,7 @@ const findAliasMatch = (importPath, paths) => {
387
393
  }
388
394
  }
389
395
  }
396
+ logger2(` - no match found`);
390
397
  return null;
391
398
  };
392
399
  const toRelativeImport = (absPath, fromDir) => {
@@ -428,19 +435,33 @@ async function convertStringAliasRelative({
428
435
  pathPattern,
429
436
  targetDir
430
437
  }) {
438
+ logger2(`[convertStringAliasRelative] Processing import: ${importPath}`);
439
+ logger2(` - importerFile: ${importerFile}`);
440
+ logger2(` - pathPattern: ${pathPattern}`);
441
+ logger2(` - targetDir: ${targetDir}`);
431
442
  const baseAlias = pathPattern.replace("/*", "");
432
443
  if (importPath.startsWith("@") && !importPath.startsWith(baseAlias)) {
444
+ logger2(` - skipping: npm package import`);
433
445
  return importPath;
434
446
  }
435
447
  const paths = { [pathPattern]: ["./*"] };
436
448
  const importerDir = dirname(importerFile);
437
449
  const match = findAliasMatch(importPath, paths);
438
- if (!match) return importPath;
450
+ if (!match) {
451
+ logger2(` - no alias match found`);
452
+ return importPath;
453
+ }
454
+ logger2(` - found alias match: ${JSON.stringify(match)}`);
439
455
  const absPath = resolve(targetDir, match.resolvedPath, match.suffix);
456
+ logger2(` - resolved absolute path: ${absPath}`);
440
457
  const resolvedFile = await resolveFileWithExtensions(absPath);
458
+ logger2(` - resolved file with extensions: ${resolvedFile || "not found"}`);
441
459
  const relPath = toRelativeImport(resolvedFile || absPath, importerDir);
460
+ logger2(` - relative path: ${relPath}`);
442
461
  const originalExt = extname(importPath);
443
- return getTargetExtension(relPath, originalExt);
462
+ const result = getTargetExtension(relPath, originalExt);
463
+ logger2(` - final result: ${result}`);
464
+ return result;
444
465
  }
445
466
  function replaceAllInString(original, searchValue, replaceValue) {
446
467
  let currentPosition = 0;
@@ -464,32 +485,50 @@ async function processFile(filePath, aliasToReplace, targetDir, pathExtFilter) {
464
485
  const matches = Array.from(content.matchAll(IMPORT_REGEX));
465
486
  const normalizedAlias = aliasToReplace.endsWith("/*") ? aliasToReplace : `${aliasToReplace}/*`;
466
487
  const baseAlias = aliasToReplace.replace("/*", "");
488
+ logger2(`[processFile] Processing file: ${filePath}`);
489
+ logger2(` - normalizedAlias: ${normalizedAlias}`);
490
+ logger2(` - baseAlias: ${baseAlias}`);
491
+ logger2(` - found ${matches.length} import statements`);
467
492
  for (const match of matches) {
468
493
  const originalQuote = match[1];
469
494
  const importPath = match[2];
470
495
  if (!importPath) continue;
496
+ logger2(` Processing import: ${importPath}`);
471
497
  if (!importPath.startsWith(baseAlias)) {
498
+ logger2(` - skipping: import doesn't start with ${baseAlias}`);
472
499
  continue;
473
500
  }
474
501
  const importExt = extname(importPath);
475
502
  const shouldProcess = pathExtFilter === "js" && importExt === ".js" || pathExtFilter === "ts" && importExt === ".ts" || pathExtFilter === "none" && importExt === "" || pathExtFilter === "js-ts-none";
476
- if (!shouldProcess) continue;
503
+ if (!shouldProcess) {
504
+ logger2(` - skipping: doesn't match pathExtFilter ${pathExtFilter}`);
505
+ continue;
506
+ }
507
+ logger2(` - converting alias to relative path...`);
477
508
  const relPath = await convertStringAliasRelative({
478
509
  importPath,
479
510
  importerFile: filePath,
480
511
  pathPattern: normalizedAlias,
481
512
  targetDir
482
513
  });
514
+ logger2(` - original path: ${importPath}`);
515
+ logger2(` - converted to: ${relPath}`);
483
516
  const finalPath = pathExtFilter === "none" ? relPath.replace(/\.(ts|js|tsx|jsx|mjs|cjs)$/, "") : relPath;
484
517
  if (importPath !== finalPath) {
485
518
  changes.push({ from: importPath, to: finalPath });
486
519
  const searchString = `${originalQuote}${importPath}${originalQuote}`;
487
520
  const replacementString = `${originalQuote}${finalPath}${originalQuote}`;
488
521
  updated = replaceAllInString(updated, searchString, replacementString);
522
+ logger2(` - applied change: ${importPath} \u2192 ${finalPath}`);
523
+ } else {
524
+ logger2(` - no change needed`);
489
525
  }
490
526
  }
491
527
  if (content !== updated) {
492
528
  await fs.writeFile(filePath, updated);
529
+ logger2(`\u2713 processed: ${filePath}`);
530
+ } else {
531
+ logger2(` - no changes made to file`);
493
532
  }
494
533
  return changes;
495
534
  }
@@ -527,6 +566,7 @@ async function processAllFiles({
527
566
  results.push({ file: fullPath, changes });
528
567
  }
529
568
  } else {
569
+ logger2(` - skipping non-matching file: ${entry.name}`);
530
570
  }
531
571
  })
532
572
  );
@@ -550,6 +590,7 @@ async function convertImportsAliasToRelative({
550
590
  logger(
551
591
  ` (Assuming "${normalizedAlias}" resolves relative to "${targetDir}")`
552
592
  );
593
+ logger2(` (Using extension mode: ${pathExtFilter})`);
553
594
  const results = await processAllFiles({
554
595
  srcDir: targetDir,
555
596
  aliasToReplace: normalizedAlias,
@@ -558,12 +599,12 @@ async function convertImportsAliasToRelative({
558
599
  pathExtFilter
559
600
  });
560
601
  if (results.length > 0) {
561
- logger("\n[convertImportsAliasToRelative] Summary of changes:", true);
602
+ logger("\n[convertImportsAliasToRelative] Summary of changes:");
562
603
  for (const { file, changes } of results) {
563
604
  const displayPath = relative(targetDir, file) || basename(file);
564
- logger(() => ` in ${displayPath}:`, true);
605
+ logger(() => ` in ${displayPath}:`);
565
606
  for (const { from, to } of changes) {
566
- logger(() => ` - ${from} \u2192 ${to}`, true);
607
+ logger(() => ` - ${from} \u2192 ${to}`);
567
608
  }
568
609
  }
569
610
  } else {
@@ -577,6 +618,9 @@ async function convertImportsExt({
577
618
  extTo,
578
619
  alias
579
620
  }) {
621
+ logger2(
622
+ `Converting import extensions from '${extFrom}' to '${extTo}' in "${targetDir}"...`
623
+ );
580
624
  const fromExtStr = extFrom === "none" ? "" : `.${extFrom}`;
581
625
  const toExtStr = extTo === "none" ? "" : `.${extTo}`;
582
626
  const normalizedAlias = alias ? alias.endsWith("/*") ? alias : `${alias}/*` : void 0;
@@ -649,24 +693,27 @@ async function convertImportsExt({
649
693
  }
650
694
  if (content !== updated) {
651
695
  await fs.writeFile(fullPath, updated);
696
+ logger2(`\u2713 processed: ${fullPath}`);
652
697
  if (changes.length > 0) {
653
698
  results.push({ file: fullPath, changes });
654
699
  }
655
700
  }
656
701
  } else {
702
+ logger2(` - skipping non-matching file: ${entry.name}`);
657
703
  }
658
704
  })
659
705
  );
660
706
  if (results.length > 0) {
661
- logger("\n[convertImportsExt] Summary of changes:", true);
707
+ logger("\n[convertImportsExt] Summary of changes:");
662
708
  for (const { file, changes } of results) {
663
709
  const displayPath = relative(targetDir, file) || basename(file);
664
- logger(() => ` in ${displayPath}:`, true);
710
+ logger(() => ` in ${displayPath}:`);
665
711
  for (const { from, to } of changes) {
666
- logger(() => ` - ${from} \u2192 ${to}`, true);
712
+ logger(() => ` - ${from} \u2192 ${to}`);
667
713
  }
668
714
  }
669
715
  }
716
+ logger2("Extension conversion complete.");
670
717
  return results;
671
718
  } catch (error) {
672
719
  logger(
@@ -678,8 +725,12 @@ async function convertImportsExt({
678
725
  function stripPathSegments(path2, count = 1, alias = "") {
679
726
  if (typeof path2 !== "string" || path2.length === 0) return path2;
680
727
  if (count <= 0) return path2;
728
+ logger2(`[stripPathSegments] Processing path: ${path2}`);
729
+ logger2(` - count: ${count}, alias: ${alias}`);
681
730
  const normalizedPath = normalizeWindowsPath(path2);
731
+ logger2(` - normalized: ${normalizedPath}`);
682
732
  const parsed = parse(normalizedPath);
733
+ logger2(` - parsed: ${JSON.stringify(parsed)}`);
683
734
  let pathSegments = [];
684
735
  if (parsed.dir && parsed.dir !== parsed.root) {
685
736
  let dirRelativeToRoot = parsed.dir;
@@ -692,26 +743,36 @@ function stripPathSegments(path2, count = 1, alias = "") {
692
743
  pathSegments.push(parsed.base);
693
744
  }
694
745
  pathSegments = pathSegments.filter(Boolean);
746
+ logger2(` - initial segments: ${JSON.stringify(pathSegments)}`);
695
747
  const leadingPreservedSegments = [];
696
748
  if (alias && pathSegments.length > 0 && pathSegments[0]?.startsWith(alias)) {
697
749
  const preserved = pathSegments.shift();
698
750
  if (preserved) {
699
751
  leadingPreservedSegments.push(preserved);
752
+ logger2(` - preserved alias segment: ${preserved}`);
700
753
  }
701
754
  }
702
755
  while (pathSegments.length > 0 && (pathSegments[0] === DOT || pathSegments[0] === DOUBLE_DOT)) {
703
756
  const preserved = pathSegments.shift();
704
757
  if (preserved) {
705
758
  leadingPreservedSegments.push(preserved);
759
+ logger2(` - preserved relative segment: ${preserved}`);
706
760
  }
707
761
  }
708
762
  const numToStrip = Math.min(count, pathSegments.length);
709
763
  const remainingBodySegments = pathSegments.slice(numToStrip);
764
+ logger2(
765
+ ` - stripping ${numToStrip} segments from: ${JSON.stringify(pathSegments)}`
766
+ );
767
+ logger2(
768
+ ` - remaining body segments: ${JSON.stringify(remainingBodySegments)}`
769
+ );
710
770
  const pathRoot = parsed.root;
711
771
  const effectiveSegments = [
712
772
  ...leadingPreservedSegments,
713
773
  ...remainingBodySegments
714
774
  ];
775
+ logger2(` - effective segments: ${JSON.stringify(effectiveSegments)}`);
715
776
  let result;
716
777
  if (effectiveSegments.length === 0) {
717
778
  result = normalize(pathRoot || DOT);
@@ -720,6 +781,7 @@ function stripPathSegments(path2, count = 1, alias = "") {
720
781
  } else {
721
782
  result = join(...effectiveSegments);
722
783
  }
784
+ logger2(` - final result: ${result}`);
723
785
  return result;
724
786
  }
725
787
  async function stripPathSegmentsInDirectory({
@@ -729,13 +791,10 @@ async function stripPathSegmentsInDirectory({
729
791
  extensionsToProcess = EXTENSIONS
730
792
  }) {
731
793
  logger(
732
- () => `[stripPathSegmentsInDirectory] Processing directory: ${targetDir}`,
733
- true
734
- );
735
- logger(
736
- () => ` - segmentsToStrip: ${segmentsToStrip}, alias: ${alias}`,
737
- true
794
+ () => `[stripPathSegmentsInDirectory] Processing directory: ${targetDir}`
738
795
  );
796
+ logger(() => ` - segmentsToStrip: ${segmentsToStrip}, alias: ${alias}`);
797
+ logger2(` - extensions: ${JSON.stringify(extensionsToProcess)}`);
739
798
  try {
740
799
  const entries = await fs.readdir(targetDir, { withFileTypes: true });
741
800
  const results = [];
@@ -744,6 +803,7 @@ async function stripPathSegmentsInDirectory({
744
803
  const fullPath = join(targetDir, entry.name);
745
804
  if (entry.isDirectory()) {
746
805
  if (entry.name === "node_modules") return;
806
+ logger2(` - recursing into directory: ${entry.name}`);
747
807
  const subdirResults = await stripPathSegmentsInDirectory({
748
808
  targetDir: fullPath,
749
809
  segmentsToStrip,
@@ -752,54 +812,65 @@ async function stripPathSegmentsInDirectory({
752
812
  });
753
813
  results.push(...subdirResults);
754
814
  } else if (extensionsToProcess.includes(extname(entry.name))) {
815
+ logger2(` Processing file: ${entry.name}`);
755
816
  const content = await fs.readFile(fullPath, "utf-8");
756
817
  let updated = content;
757
818
  const changes = [];
758
819
  const matches = Array.from(content.matchAll(IMPORT_REGEX));
820
+ logger2(` - found ${matches.length} import statements`);
759
821
  for (const match of matches) {
760
822
  const originalQuote = match[1];
761
823
  const importPath = match[2];
762
824
  if (!importPath) continue;
763
825
  if (!importPath.includes(SLASH)) {
826
+ logger2(` - skipping non-path import: ${importPath}`);
764
827
  continue;
765
828
  }
766
829
  if (alias && !importPath.startsWith(alias.replace("/*", ""))) {
830
+ logger2(` - skipping non-alias import: ${importPath}`);
767
831
  continue;
768
832
  }
833
+ logger2(` Processing import: ${importPath}`);
769
834
  const strippedPath = stripPathSegments(
770
835
  importPath,
771
836
  segmentsToStrip,
772
837
  alias
773
838
  );
774
839
  if (importPath === strippedPath) {
840
+ logger2(" - no changes needed");
775
841
  continue;
776
842
  }
777
843
  changes.push({ from: importPath, to: strippedPath });
844
+ logger2(` - transformed: ${importPath} \u2192 ${strippedPath}`);
778
845
  const searchStr = `${originalQuote}${importPath}${originalQuote}`;
779
846
  const replaceStr = `${originalQuote}${strippedPath}${originalQuote}`;
780
847
  updated = replaceAllInString(updated, searchStr, replaceStr);
781
848
  }
782
849
  if (content !== updated) {
783
850
  await fs.writeFile(fullPath, updated);
851
+ logger2(" \u2713 wrote changes to file");
784
852
  if (changes.length > 0) {
785
853
  results.push({ file: fullPath, changes });
786
854
  }
787
855
  } else {
856
+ logger2(" - no changes made to file");
788
857
  }
789
858
  } else {
859
+ logger2(` - skipping non-matching file: ${entry.name}`);
790
860
  }
791
861
  })
792
862
  );
793
863
  if (results.length > 0) {
794
- logger(() => "[stripPathSegmentsInDirectory] Summary of changes:", true);
864
+ logger(() => "[stripPathSegmentsInDirectory] Summary of changes:");
795
865
  for (const { file, changes } of results) {
796
866
  const displayPath = relative(targetDir, file) || basename(file);
797
- logger(() => ` in ${displayPath}:`, true);
867
+ logger(() => ` in ${displayPath}:`);
798
868
  for (const { from, to } of changes) {
799
- logger(() => ` - ${from} \u2192 ${to}`, true);
869
+ logger(() => ` - ${from} \u2192 ${to}`);
800
870
  }
801
871
  }
802
872
  } else {
873
+ logger2(" No changes were made in any files");
803
874
  }
804
875
  return results;
805
876
  } catch (error) {
@@ -889,24 +960,23 @@ async function attachPathSegmentsInDirectory({
889
960
  }
890
961
  if (content !== updated) {
891
962
  await fs.writeFile(fullPath, updated);
963
+ logger2(`\u2713 processed: ${fullPath}`);
892
964
  if (changes.length > 0) {
893
965
  results.push({ file: fullPath, changes });
894
966
  }
895
967
  }
896
968
  } else {
969
+ logger2(` - skipping non-matching file: ${entry.name}`);
897
970
  }
898
971
  })
899
972
  );
900
973
  if (results.length > 0) {
901
- logger(
902
- () => "\n[attachPathSegmentsInDirectory] Summary of changes:",
903
- true
904
- );
974
+ logger(() => "\n[attachPathSegmentsInDirectory] Summary of changes:");
905
975
  for (const { file, changes } of results) {
906
976
  const displayPath = relative(targetDir, file) || basename(file);
907
- logger(() => ` in ${displayPath}:`, true);
977
+ logger(() => ` in ${displayPath}:`);
908
978
  for (const { from, to } of changes) {
909
- logger(() => ` - ${from} \u2192 ${to}`, true);
979
+ logger(() => ` - ${from} \u2192 ${to}`);
910
980
  }
911
981
  }
912
982
  }
package/package.json CHANGED
@@ -5,7 +5,7 @@
5
5
  "license": "MIT",
6
6
  "name": "@reliverse/pathkit",
7
7
  "type": "module",
8
- "version": "1.2.4",
8
+ "version": "1.2.6",
9
9
  "devDependencies": {},
10
10
  "exports": {
11
11
  ".": "./bin/mod.js"