UNPKG

1.74 kBJavaScriptView Raw
1"use strict";import{existsSync as j,promises as S}from"fs";import{fileURLToPath as d,URL as h}from"url";import*as y from"./utils.js";let u,m,c=y.$defaults("esm"),T=c.file&&import("file:///"+c.file);async function x(){let t=await T;return t=t&&t.default||t,y.$finalize(c,t)}const w=/\.\w+(?=\?|$)/,b=/\.[mc]?tsx?(?=\?|$)/;async function p(t){u=u||await x();let[r]=w.exec(t)||[];return u[r]}function g(t){let r=d(t);if(j(r))return t}const C={".js":[".ts",".tsx",".jsx"],".jsx":[".tsx"],".mjs":[".mts"],".cjs":[".cts"]},R=new h("file:///"+process.cwd()+"/");export const resolve=async function(t,r,o){if(/^\w+\:?/.test(t))return o(t,r,o);let e=new h(t,r.parentURL||R),s,n,l,i,a=0,f;if(i=w.exec(e.href)){if(s=i[0],!r.parentURL||b.test(s))return{url:e.href,shortCircuit:!0};if(n=g(e.href))return{url:n,shortCircuit:!0};if(l=C[s]){for(f=e.href.substring(0,i.index);a<l.length;a++)if(n=g(f+l[a]))return a=i.index+s.length,{shortCircuit:!0,url:a>e.href.length?f+e.href.substring(a):n}}return o(t,r,o)}u=u||await x();for(s in u)if(n=g(e.href+s),n)return{url:n,shortCircuit:!0};return o(t,r,o)},load=async function(t,r,o){let e=await p(t);if(e==null)return o(t,r,o);let s=e.format==="cjs"?"commonjs":"module",n=d(t),l=await S.readFile(n);m=m||await import("esbuild");let i=await m.transform(l.toString(),{...e,sourcefile:n,format:s==="module"?"esm":"cjs"});return{format:s,source:i.code,shortCircuit:!0}},getFormat=async function(t,r,o){let e=await p(t);return e==null?o(t,r,o):{format:e.format==="cjs"?"commonjs":"module"}},transformSource=async function(t,r,o){let e=await p(r.url);return e==null?o(t,r,o):(m=m||await import("esbuild"),{source:(await m.transform(t.toString(),{...e,sourcefile:r.url,format:r.format==="module"?"esm":"cjs"})).code})};