pkg-entry-points
Version:
Get all entry-points for an npm package. Supports the `exports` field in `package.json`.
2 lines (1 loc) • 2.75 kB
JavaScript
import O from"fs";import u from"path";const b=async(e,t,r)=>{const i=await e.readdir(t);return(await Promise.all(i.map(async o=>{const s=u.join(t,o);if((await e.stat(s)).isDirectory()){const a=await b(e,s,!0);return r?a:a.map(l=>`./${u.relative(t,l)}`)}return r?s:`./${u.relative(t,s)}`}))).flat()},w=(e,t,r)=>e.readdirSync(t).filter(o=>o!=="node_modules").map(o=>{const s=u.join(t,o);if(e.statSync(s).isDirectory()){const a=w(e,s,!0);return r?a:a.map(l=>`./${u.relative(t,l)}`)}return r?s:`./${u.relative(t,s)}`}).flat(),p="*",S=e=>{const t=e.split(p),r=t[0],i=t.length-1,n=t[i],o=t.slice(1,i);return{prefix:r,middle:o,suffix:n}},v=({prefix:e,suffix:t,middle:r},i)=>{if(!i.startsWith(e)||!i.endsWith(t))return;const n=i.slice(e.length,-t.length||void 0);if(r.length===0)return n;let o=0,s="";for(const c of r){const a=n.indexOf(c,o);if(a===-1)return;const l=n.slice(o,a);if(!s)s=l;else if(s!==l)return;o=a+c.length}return s},j=(e,t,r=[],i={})=>{if(t===null||typeof t=="string"){r.length===0&&r.push("default");const n=JSON.stringify(r);if(!Object.hasOwn(i,n))if(t===null)i[n]=t;else if(t.includes(p)){const o=S(t);i[n]=e.map(s=>{const c=v(o,s);return c&&[s,c]}).filter(s=>s!==void 0)}else e.includes(t)&&(i[n]=[t])}else if(Array.isArray(t))for(const n of t)j(e,n,r,i);else if(typeof t=="object"&&t)for(const n in t){if(!Object.hasOwn(t,n))continue;const o=r.slice();o.includes(n)||o.push(n),j(e,t[n],o.sort(),i)}return i},A=(e,t)=>{if(e===null)return{};let r=Object.keys(e);r[0][0]==="."||(e={".":e},r=["."]);const n={},o=[];for(const c of r){const a=j(t,e[c]),l=c.includes(p);for(const f in a){if(!Object.hasOwn(a,f))continue;const y=a[f];if(y)for(let g of y){let d=c;if(l){const h=Array.isArray(g);d=c.split(p).join(h?g[1]:"_"),h&&([g]=g)}n[d]||(n[d]={}),n[d][f]=Array.isArray(g)?g[0]:g}else o.push([l?S(c):c,f])}}const s={};for(const c in n){if(!Object.hasOwn(n,c))continue;const a=Object.entries(n[c]).filter(([l])=>!o.some(([f,y])=>(typeof f=="string"?f===c:v(f,c))&&l===y)).map(([l,f])=>[JSON.parse(l),f]).sort(([l],[f])=>l.length-f.length);a.length>0&&(s[c]=a)}return s},m=e=>[[["default"],e]],E=(e,t)=>{var r;const i=/\.(?:json|[cm]?js|d\.ts)$/,n=Object.fromEntries(t.filter(s=>i.test(s)).map(s=>[s,m(s)]));let o=(r=e.main)!=null?r:"./index.js";o[0]!=="."&&(o=`./${o}`);for(const s of["",".js",".json"]){const c=o+s;if(t.includes(c)){n["."]=m(c),n[c]=m(c);break}}return n},k=async(e,t=O.promises)=>{const r=await t.readFile(u.join(e,"package.json"),"utf8"),i=JSON.parse(r),n=await b(t,e);return i.exports!==void 0?A(i.exports,n):E(i,n)},J=(e,t=O)=>{const r=t.readFileSync(u.join(e,"package.json"),"utf8"),i=JSON.parse(r),n=w(t,e);return i.exports!==void 0?A(i.exports,n):E(i,n)};export{k as getPackageEntryPoints,J as getPackageEntryPointsSync};