UNPKG

vite-plugin-svg-symbols

Version:
22 lines (20 loc) 7.09 kB
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const c=require("node:path"),x=require("node:fs/promises"),J=require("node:crypto"),Z=(e=[],r)=>{const l=new Map,f=async s=>{const u=await x.stat(s);if(l.has(s)){const[g,I]=l.get(s)||[0,[]];if(g===u.mtimeMs){const[i]=I;return i}}const p=await x.readFile(s,{encoding:"utf8"}),y=await(typeof r=="function"?r(p,s):Promise.resolve(p));return l.set(s,[u.mtimeMs,[y]]),y},o=async s=>{const u=await x.stat(s);if(l.has(s)){const[g,I]=l.get(s)||[0,[]];if(g===u.mtimeMs)return I}const p=[],y=await x.readdir(s,{withFileTypes:!0});for(const g of y){if(g.isDirectory()){const I=await o(c.join(s,g.name));p.push(...I)}(e.length===0||e.includes(c.extname(g.name)))&&p.push(c.join(s,g.name))}return l.set(s,[u.mtimeMs,p]),p};return{store:l,getDirContent:o,getFileContent:f}},K=()=>{const e={isDevMode:!1,isTestMode:!1,root:"",base:"",assets:"",aliases:{}},r=o=>o.reduce((s,u)=>(typeof u.find=="string"&&(s[u.find]=u.replacement),s),{});return{config:e,updateConfig:o=>{e.isDevMode=o.command==="serve",e.isTestMode=o.mode==="plugintest",e.root=o.root,e.base=o.base,e.assets=o.build.assetsDir,e.aliases={"@icons":c.join(e.root,"src","icons"),...r(o.resolve.alias)}},findAliasName:o=>{const[s=[]]=Object.entries(e.aliases).filter(([p,y])=>o.startsWith(y)).sort(([,p],[,y])=>y.length-p.length),[u=""]=s;return u.replace("@","")}}},Q="\0virtual:",R="\0virtual:symbol:",U="\0virtual:svg:symbols",H=".svg?symbol",tt="svg:symbols@",C="/@id/__vite-plugin-svg-symbols__.svg",et={"aria-hidden":"true",style:["position:absolute;","top:0;","left:0;","width:1px;","height:1px;","visibility:hidden;","opacity:0;"].join("")},st=["fill","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width"],ot=`declare module 'svg:symbols@[alias]' { [content] const symbols: Record<string, string>; export default symbols; }`,nt=`/** * @see [see] */`,V=`/** * Vite plugin for creating SVG symbol sprite * @see [Documentation on Github](https://github.com/werty1001/vite-plugin-svg-symbols) */`,rt=`declare module '*.svg?symbol' { const src: string export default src }`,at=(e,r)=>c.relative(e,r).split(c.sep).join("_").replace(/[-_]([a-z0-9])/gi,(f,o)=>o.toUpperCase()).replace(".svg","").concat("Icon"),Y=(e,r=8)=>J.createHash("sha256").update(e).digest("hex").slice(0,r),it=(e,r=".svg")=>e.replace(r,"").trim().concat(r),q=e=>`<svg xmlns="http://www.w3.org/2000/svg">${e}</svg>`,z=e=>{const[,r=""]=e.split("#");return r},ct=(e,r)=>c.relative(r,e).replace(".svg","").replace("node_modules".concat(c.sep),"").replace("src".concat(c.sep),"").split(c.sep).join("-"),lt=(e,r,l,f)=>{const o=/<svg([^>]*)>([\s\S]*?)<\/svg>/,s=/([a-zA-Z-]+)\s*=\s*["']([^"']*)["']/g,[,u="",p=""]=e.match(o)||[],y=p.trim().replace(/>((\r\n|\n|\r)(\s+)?)</g,"><"),g={viewBox:"0 0 24 24"},I=u.matchAll(s);if(I)for(const _ of I){const[,A,j]=_;g[A.trim()]=j.trim()}const i=f.reduce((_,A)=>{const j=g[A];return j&&_.push([A,`"${j}"`].join("=")),_},[]).join(" "),N=i?`<g ${i}>${y}</g>`:y,B=g.viewBox;return[`<symbol viewBox="${B}" id="${l}">${N}</symbol>`,{symbolId:l,symbolBody:N,symbolViewBox:B,svgBody:y,svgPath:r,svgAttrs:g}]},dt=(e,r)=>{const l=new RegExp(r.concat("#([^'\"`]*)"),"gi"),f=Object.keys(e).reduce((o,s)=>{if(s.endsWith(".js")||s.endsWith(".mjs")){const p=e[s].code.match(l)||[];o.push(...p)}return o},[]);return new Set(f)},mt=(e,r,l)=>{Object.keys(e).forEach(f=>{if(!f.endsWith(".js")&&!f.endsWith(".mjs"))return;const o=e[f];o.code&&(o.code=o.code.replace(r,l))})},G=et,X=st,ut=e=>{const{fileName:r="sprite-[hash]",shouldInheritAttrs:l=X,shouldInjectToHtml:f=!1,injectAttrs:o=G,transformIcon:s=t=>t,transformIconId:u=t=>t,transformSymbol:p=t=>t,transformSprite:y=t=>t,transformImportName:g=t=>t,transformImportComment:I=t=>t}=e||{},{config:i,updateConfig:N,findAliasName:B}=K(),{getDirContent:_,getFileContent:A}=Z([".svg"],s),j=new Map,O=async t=>{const n=i.isDevMode?`?v=${Date.now()}`:"",a=await u(ct(t,i.root),t);return[C.concat(n),a].join("#")},D=async t=>{const[n,a]=await Promise.all([A(t),O(t)]),[m,d]=lt(n,t,z(a),l),v=await p(m,d);return j.set(t,v),a},L=async t=>{const n=Array.from(j.keys()).sort((m,d)=>{const v=c.relative(i.root,m),w=c.relative(i.root,d);return v>w?1:-1});let a="";for(const m of n){const d=j.get(m)||"";if(!t){a+=d;continue}const v=await O(m);t.has(v)&&(a+=d)}return y(a)},k=new Map,F=async t=>{const n=i.aliases[`@${t}`]||"";if(!n)throw new Error([`The alias @${t} is not defined.`,"Please add it to your vite.config.ts"].join(" "));const a=await _(n),m=[],d=new Map;let v="",w="";for(const b of a){const[h,M]=await Promise.all([g(at(n,b),b),D(b)]),T=d.get(h)||0,S=h.concat(T>0?String(T+1):"");v+=`export const ${S} = '${M}'; `,w+=`${S}, `,m.push([b,S,M]),d.set(h,T+1)}return k.set(t,m),v.concat(`export default { ${w}};`)},P=async()=>{let t="";for(const[a,m]of k.entries()){let d="";for(const[w,b,h]of m){const M=c.relative(i.root,w),T=nt.replace("[see]",`[${M}](file://${w})`),S=await I(T,w),$=`export const ${b}: '#${z(h)}'`;d+=[S,$,` `].join(` `)}const v=ot.replace("[alias]",a).replace("[content]",d);t+=[V,v,` `].join(` `)}t+=[[V,rt].join(` `)].join(` `);const n=i.isTestMode?c.join(i.root,"app","client.d.ts"):c.join(i.root,"node_modules","vite-plugin-svg-symbols","client.d.ts");return x.writeFile(n,t)};let E,W="";return{name:"vite-plugin-svg-symbols",enforce:"pre",closeWatcher(){clearTimeout(E)},configResolved(t){N(t)},configureServer({watcher:t,middlewares:n,ws:a,moduleGraph:m}){const d=new Set,v=()=>{for(const b of d){const h=U.concat("@",b),M=m.getModuleById(h);M&&m.invalidateModule(M)}d.clear(),a.send({type:"full-reload",path:"*"})},w=()=>{clearTimeout(E),E=setTimeout(v,50)};t.on("all",(b,h)=>{if(!h.endsWith(".svg"))return;const M=B(h);M&&(d.add(M),w())}),n.use(C,async(b,h)=>{const M=await L(),T=q(M),S=Y(T,32),$=b.headers["if-none-match"];if(S===$){h.writeHead(304,{"Content-Length":0}).end("");return}h.writeHead(200,{"Content-Length":Buffer.byteLength(T),"Content-Type":"image/svg+xml","Cache-Control":"no-cache",Etag:S}).end(T)})},resolveId(t,n=""){if(t.endsWith(H)){const a=c.isAbsolute(t)?t:c.resolve(c.dirname(n),t);return R.concat(a.replace(H,".svg"))}return t.startsWith(tt)?Q.concat(t):null},async load(t){if(t.startsWith(R)){const n=t.replace(R,"");return`export default '${await D(n)}';`}if(t.startsWith(U)){const[,n="icons"]=t.split("@"),a=await F(n);return await P(),a}return null},transformIndexHtml(){if(!(i.isDevMode||!f))return[{tag:"svg",attrs:o,children:W,injectTo:"body-prepend"}]},async generateBundle(t,n){if(i.isDevMode)return;const a=dt(n,C),m=await L(a),d=q(m),v=Y(d),w=it(r.replace("[hash]",v)),b=f?"":c.join(i.base,i.assets,w),h=new RegExp(C,"g");mt(n,h,b),f?W=m:this.emitFile({type:"asset",fileName:c.join(i.assets,w),source:d})},api:{async generateSymbolsTypes(){const t=Object.keys(i.aliases).map(n=>n.replace("@","")).filter(Boolean);return await Promise.all(t.map(F)),P()}}}};exports.default=ut;exports.defaultInheritAttrs=X;exports.defaultInjectAttrs=G;