New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@korautils/alias-fixer

Package Overview
Dependencies
Maintainers
1
Versions
7
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@korautils/alias-fixer - npm Package Compare versions

Comparing version 1.0.6 to 1.0.7

181

dist/index.js

@@ -1,181 +0,2 @@

// src/index.ts
import fs from "fs";
import path from "path";
import figlet from "figlet";
import * as jsonc from "jsonc-parser";
var init = (header) => {
console.log("-------------------------------------------------------");
console.log(header);
console.log("-------------------------------------------------------");
console.log("Finding tsconfig file...");
console.log("-------------------------------------------------------");
const tsconfig = getTsConfig();
if (!checkPaths(tsconfig)) {
console.log(
"ERROR: No se encontr\xF3 el archivo tsconfig.json o no se encontr\xF3 una configuraci\xF3n v\xE1lida"
);
console.log("Se finaliza la operaci\xF3n.");
return;
}
const dir = path.resolve(process.cwd(), getArgument("--dir", "./"));
const types = getArgument("--types", "ts,tsx,jsx,js").split(",");
const exclude = getProp(tsconfig, "exclude", ["node_modules"]);
console.log("dir:", dir);
console.log("types:", types);
console.log("exclude:", exclude);
const files = listFilesByTypes(dir, types, exclude);
replaceImportsWithAliases(files, tsconfig);
};
function replaceImportsWithAliases(files, tsconfig) {
const paths = tsconfig.compilerOptions?.paths || {};
const dir = path.resolve(
process.cwd(),
tsconfig.compilerOptions?.baseUrl || "./"
);
const computedPaths = [];
for (const alias in paths) {
if (Object.prototype.hasOwnProperty.call(paths, alias)) {
const folderPaths = paths[alias];
computedPaths.push({
alias: alias.replace(/\/\*{1,2}(\*)?$/, ""),
folders: folderPaths.map((folder) => path.join(process.cwd(), folder.replace(/\/\*{1,2}(\*)?$/, "")))
});
}
}
files.forEach((file) => {
const content = fs.readFileSync(file, "utf-8");
const updatedContent = content.replace(
/(import\s+.*?['"])(\.{1,2}\/.*?)(['"])/g,
(fullMatch, prefix, relativePath, suffix) => {
const importedFilePath = path.resolve(path.dirname(file), relativePath);
const backFoldersTo = countRelativePaths(relativePath);
let currentDir = path.dirname(file);
for (let i = 0; i < backFoldersTo; i++) {
currentDir = path.dirname(currentDir);
}
if (!currentDir.startsWith(dir)) {
return fullMatch;
}
const isOutsideAllPaths = computedPaths.every(
(aliasPath) => !aliasPath.folders.some(
(folderPath) => importedFilePath.startsWith(folderPath)
)
);
if (isOutsideAllPaths) {
return fullMatch;
}
let bestMatch = null;
computedPaths.forEach((aliasPath) => {
aliasPath.folders.forEach((folderPath) => {
if (importedFilePath.startsWith(folderPath)) {
const relativeImportPath = path.relative(folderPath, importedFilePath);
const newPathCandidate = path.join(
aliasPath.alias,
relativeImportPath
);
if (!bestMatch || newPathCandidate.length > bestMatch.relativeImportPath.length) {
bestMatch = {
alias: aliasPath.alias,
relativeImportPath: newPathCandidate
};
}
}
});
});
return bestMatch ? `${prefix}${getProp(bestMatch, "relativeImportPath")}${suffix}` : fullMatch;
}
);
if (content !== updatedContent) {
console.log("Updated import in:", file);
fs.writeFileSync(file, updatedContent, "utf-8");
}
});
}
function countRelativePaths(path2) {
const regex = /\.\.\//g;
const matches = path2.match(regex);
return matches ? matches.length : 0;
}
function listFilesByTypes(dir, types, exclude = []) {
const matchedFiles = [];
function recursiveRead(currentDir) {
const entries = fs.readdirSync(currentDir, { withFileTypes: true });
const excludedFiles = exclude.map((item) => {
const file = path.join(currentDir, item.trim());
if (fs.existsSync(file)) {
return file;
}
return item.trim();
});
for (const entry of entries) {
const fullPath = path.join(currentDir, entry.name);
if (excludedFiles.some((excluded) => fullPath.includes(excluded))) {
continue;
}
if (entry.isDirectory()) {
recursiveRead(fullPath);
} else if (entry.isFile()) {
const ext = path.extname(entry.name).slice(1);
if (types.includes(ext)) {
matchedFiles.push(fullPath);
}
}
}
}
recursiveRead(dir);
return matchedFiles;
}
function getArgument(key, defaultValue = "./") {
const args = process.argv.slice(2);
const prefix = `${key}=`;
const arg = args.find((arg2) => arg2.startsWith(prefix));
if (arg) {
return arg.slice(prefix.length);
} else {
return defaultValue;
}
}
var checkPaths = (tsconfig) => {
const baseUrl = getProp(tsconfig, "compilerOptions.baseUrl");
const paths = getProp(tsconfig, "compilerOptions.paths");
if (!tsconfig || !baseUrl || !paths) {
return false;
}
const aliasList = Object.keys(paths).filter((alias) => alias.startsWith("@/"));
if (aliasList.length == 0) {
return false;
}
return true;
};
var getTsConfig = () => {
const tsconfigPath = path.resolve(process.cwd(), "tsconfig.json");
if (!fs.existsSync(tsconfigPath)) {
return;
}
const tsconfigContent = fs.readFileSync(tsconfigPath, "utf-8");
const parsedTsconfig = jsonc.parse(tsconfigContent);
return parsedTsconfig;
};
figlet("fix-imports", (err, data) => {
if (err) {
console.log("Algo sali\xF3 mal...", err);
return;
}
init(data);
});
function getProp(obj, path2, defaultValue) {
if (!obj || typeof path2 !== "string") {
return defaultValue;
}
const keys = path2.split(".");
let current = obj;
for (const key of keys) {
if (current && typeof current === "object" && key in current) {
current = current[key];
} else {
return defaultValue;
}
}
return current;
}
import u from"fs";import i from"path";import w from"figlet";import*as j from"jsonc-parser";var b=t=>{console.log("-------------------------------------------------------"),console.log(t),console.log("-------------------------------------------------------"),console.log("Finding tsconfig file..."),console.log("-------------------------------------------------------");let s=$();if(!W(s)){console.log("ERROR: No se encontr\xF3 el archivo tsconfig.json o no se encontr\xF3 una configuraci\xF3n v\xE1lida"),console.log("Se finaliza la operaci\xF3n.");return}let n=i.resolve(process.cwd(),P("--dir","./")),r=P("--types","ts,tsx,jsx,js").split(","),e=h(s,"exclude",["node_modules"]);console.log("dir:",n),console.log("types:",r),console.log("exclude:",e);let o=R(n,r,e);S(o,s)};function S(t,s){let n=s.compilerOptions?.paths||{},r=i.resolve(process.cwd(),s.compilerOptions?.baseUrl||"./"),e=[];for(let o in n)if(Object.prototype.hasOwnProperty.call(n,o)){let f=n[o];e.push({alias:o.replace(/\/\*{1,2}(\*)?$/,""),folders:f.map(p=>i.join(process.cwd(),p.replace(/\/\*{1,2}(\*)?$/,"")))})}t.forEach(o=>{let f=u.readFileSync(o,"utf-8"),p=f.replace(/(import\s+.*?['"])(\.{1,2}\/.*?)(['"])/g,(c,l,g,F)=>{let y=i.resolve(i.dirname(o),g),O=I(g),v=i.dirname(o);for(let a=0;a<O;a++)v=i.dirname(v);if(!v.startsWith(r)||e.every(a=>!a.folders.some(m=>y.startsWith(m))))return c;let d=null;return e.forEach(a=>{a.folders.forEach(m=>{if(y.startsWith(m)){let T=i.relative(m,y),x=i.join(a.alias,T);(!d||x.length>d.relativeImportPath.length)&&(d={alias:a.alias,relativeImportPath:x})}})}),d?`${l}${h(d,"relativeImportPath")}${F}`:c});f!==p&&(console.log("Updated import in:",o),u.writeFileSync(o,p,"utf-8"))})}function I(t){let s=/\.\.\//g,n=t.match(s);return n?n.length:0}function R(t,s,n=[]){let r=[];function e(o){let f=u.readdirSync(o,{withFileTypes:!0}),p=n.map(c=>{let l=i.join(o,c.trim());return u.existsSync(l)?l:c.trim()});for(let c of f){let l=i.join(o,c.name);if(!p.some(g=>l.includes(g))){if(c.isDirectory())e(l);else if(c.isFile()){let g=i.extname(c.name).slice(1);s.includes(g)&&r.push(l)}}}}return e(t),r}function P(t,s="./"){let n=process.argv.slice(2),r=`${t}=`,e=n.find(o=>o.startsWith(r));return e?e.slice(r.length):s}var W=t=>{let s=h(t,"compilerOptions.baseUrl"),n=h(t,"compilerOptions.paths");return!(!t||!s||!n||Object.keys(n).filter(e=>e.startsWith("@/")).length==0)},$=()=>{let t=i.resolve(process.cwd(),"tsconfig.json");if(!u.existsSync(t))return;let s=u.readFileSync(t,"utf-8");return j.parse(s)};w("fix-imports",(t,s)=>{if(t){console.log("Algo sali\xF3 mal...",t);return}b(s)});function h(t,s,n){if(!t||typeof s!="string")return n;let r=s.split("."),e=t;for(let o of r)if(e&&typeof e=="object"&&o in e)e=e[o];else return n;return e}
//# sourceMappingURL=index.js.map

2

package.json
{
"name": "@korautils/alias-fixer",
"version": "1.0.6",
"version": "1.0.7",
"description": "A development utility to automatically fix relative imports by replacing them with path aliases defined in your tsconfig.json. Ideal for streamlining large codebases with consistent import paths.",

@@ -5,0 +5,0 @@ "type": "module",

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc