@mnrendra/alias-resolver
Version:
A utility for resolving alias paths.
3 lines (2 loc) • 1.77 kB
JavaScript
;var g=require("acorn"),v=require("acorn-walk"),E=require("escodegen"),n=require("node:path");const b=o=>!o.startsWith(".")&&!n.isAbsolute(o)?"./"+o:o,i=(o,t,e)=>{e.forEach(({alias:r,path:s})=>{const{value:a}=t;if(typeof a=="string"){const l=a.endsWith("/")?a:a+"/",p=r.endsWith("/")?r:r+"/";if(l.startsWith(p)){const u=n.normalize(n.resolve(o)),y="./"+n.join(s,a.replace(r,"./")),m=n.normalize(n.resolve(y)),f=n.dirname(u),d=n.relative(f,m),h=b(d);t.value=h}}})},w=(o,t)=>({source:e})=>{typeof e=="object"&&e!==null&&e.type==="Literal"&&typeof e.value=="string"&&i(o,e,t)},x=(o,t)=>({callee:e,arguments:r})=>{e.type==="Identifier"&&e.name==="require"&&r.length>0&&r.forEach(s=>{typeof s=="object"&&s!==null&&s.type==="Literal"&&typeof s.value=="string"&&i(o,s,t)})},j=(o,t)=>({argument:e})=>{if(e.type==="ImportExpression"){const{source:r}=e;typeof r=="object"&&r!==null&&r.type==="Literal"&&typeof r.value=="string"&&i(o,r,t)}},c=(o,t=[])=>{try{o.type=o.type??"script";const{path:e,type:r}=o,s=g.parse(o.code,{sourceType:r,ecmaVersion:"latest"});v.simple(s,{ImportDeclaration:w(e,t),CallExpression:x(e,t),AwaitExpression:j(e,t)}),o.code=E.generate(s)}catch(e){if(typeof e=="object"&&e!==null&&"message"in e&&typeof e.message=="string")if(`${e.message}`.includes("'import' and 'export' may appear only with 'sourceType: module'"))o.type=o.type==="script"?"module":"script",c(o,t);else throw`${e.message}`.includes("Unexpected token")?new Error("Your source code contains an 'Unexpected token' error or might be in `TypeScript` format, so it cannot be parsed. This module can only parse CommonJS or ESModule formats."):e instanceof Error?e:(console.error(e),new Error("Unknown error!"));else throw e}};exports.resolveAlias=c;
//# sourceMappingURL=index.js.map