@salty-css/vite 0.0.1-alpha.10 → 0.0.1-alpha.101

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (5) hide show
  1. package/README.md +83 -8
  2. package/index.cjs +14 -14
  3. package/index.d.ts +1 -0
  4. package/index.js +259 -211
  5. package/package.json +11 -2
package/README.md CHANGED
@@ -1,15 +1,90 @@
1
- # Salty Css
1
+ # Salty CSS - Kinda sweet but yet spicy CSS-in-JS library
2
2
 
3
- ## Basic usage example with Button
3
+ In the world of frontend dev is there anything saltier than CSS? Salty CSS is built to provide better developer experience for developers looking for performant and feature rich CSS-in-JS solutions.
4
4
 
5
- ### Initial requirements
5
+ ## Features
6
6
 
7
- 1. Add `saltyPlugin` to vite or webpack config from `@salty-css/vite` or `@salty-css/webpack`
8
- 2. Create `salty-config.ts` to the root of your project
9
- 3. Import global styles to any regular .css file from `saltygen/index.css` (does not exist during first run, cli command coming later)
10
- 4. Create salty components with styled only inside files that end with `.css.ts`, `.salty.ts` `.styled.ts` or `.styles.ts`
7
+ - Build time compilation to achieve awesome runtime performance and minimal size
8
+ - Next.js, React Server Components, Vite and Webpack support
9
+ - Type safety with out of the box TypeScript and ESLint plugin
10
+ - Advanced CSS variables configuration to allow smooth token usage
11
+ - Style templates to create reusable styles easily
11
12
 
12
- ### Code examples
13
+ ## Get started
14
+
15
+ - Initialize: `npx salty-css init [directory]`
16
+ - Create component: `npx salty-css generate [filePath]`
17
+ - Build: `npx salty-css build [directory]`
18
+
19
+ ### Packages
20
+
21
+ Note: Fastest way to get started with any framework is [npx salty-css init [directory]](#initialize-salty-css-for-a-project) command
22
+
23
+ - [Next.js](#nextjs) → `npm install @salty-css/next` + [Next.js install guide](#nextjs) + [Next.js example app](https://github.com/margarita-form/salty-css-website)
24
+ - [React](#react) → `npm install @salty-css/react` + [React install guide](#react) + [React example code](#code-examples)
25
+ - [Vite](#vite) → `npm install @salty-css/vite` + [(Vite install guide)](#vite)
26
+ - [Webpack](https://www.npmjs.com/package/@salty-css/webpack) → `npm install @salty-css/webpack` + Guide coming soon
27
+ - [ESLint](https://www.npmjs.com/package/@salty-css/eslint-plugin-core) → `npm install @salty-css/eslint-plugin-core` + Guide coming soon
28
+ - [Core](https://www.npmjs.com/package/@salty-css/react) → `npm install @salty-css/core` (This package contains code for internal use)
29
+
30
+ ### Add Salty CSS to your project with `salty-css` CLI
31
+
32
+ #### Initialize Salty CSS for a project
33
+
34
+ In your existing repository run `npx salty-css init [directory]` which installs required salty-css packages to the current directory, detects framework in use (current support for vite and next.js) and creates project files to the provided directory. Directory can be left blank if you want files to be created to the current directory. Init will also create `.saltyrc.json` which contains some metadata for future CLI commands.
35
+
36
+ #### Create components
37
+
38
+ Components can be created with `npx salty-css generate [filePath]` which then creates a new Salty CSS component file to the specified path. Additional options like `--dir, --tag, --name and --className` are also supported. Read more about them with `npx salty-css generate --help`
39
+
40
+ #### Build / Compile Salty CSS
41
+
42
+ If you want to manually build your project that can be done by running `npx salty-css build [directory]`. Directory is not required as CLI can use default directory defined in `.saltyrc.json`. Note that build generates css files but Vite / Webpack plugin is still required for full support.
43
+
44
+ #### Update Salty CSS packages
45
+
46
+ To ease the pain of package updates all Salty CSS packages can be updated with `npx salty-css update`
47
+
48
+ ### Manual work
49
+
50
+ #### Next.js
51
+
52
+ 1. For Next.js support install `npm i @salty-css/next @salty-css/core @salty-css/react`
53
+ 2. Create `salty.config.ts` to your app directory
54
+ 3. Add Salty CSS plugin to next.js config
55
+
56
+ - **Next.js 15:** In `next.config.ts` add import for salty plugin `import { withSaltyCss } from '@salty-css/next';` and then add `withSaltyCss` to wrap your nextConfig export like so `export default withSaltyCss(nextConfig);`
57
+ - **Next.js 14 and older:** In `next.config.js` add import for salty plugin `const { withSaltyCss } = require('@salty-css/next');` and then add `withSaltyCss` to wrap your nextConfig export like so `module.exports = withSaltyCss(nextConfig);`
58
+
59
+ 4. Make sure that `salty.config.ts` and `next.config.ts` are in the same folder!
60
+ 5. Build `saltygen` directory by running your app once or with cli `npx salty-css build [directory]`
61
+ 6. Import global styles from `saltygen/index.css` to some global css file with `@import 'insert_path_to_index_css';`.
62
+
63
+ [Check out Next.js demo project](https://github.com/margarita-form/salty-css-website) or [react example code](#code-examples)
64
+
65
+ #### React
66
+
67
+ 1. Install related dependencies: `npm i @salty-css/core @salty-css/react`
68
+ 2. Create `salty.config.ts` to your app directory
69
+ 3. Configure your build tool to support Salty CSS ([Vite](#vite) or Webpack)
70
+
71
+ [Check out react example code](#code-examples)
72
+
73
+ #### Vite
74
+
75
+ 1. For Vite support install `npm i @salty-css/vite @salty-css/core`
76
+ 2. In `vite.config` add import for salty plugin `import { saltyPlugin } from '@salty-css/vite';` and then add `saltyPlugin(__dirname)` to your vite configuration plugins
77
+ 3. Make sure that `salty.config.ts` and `vite.config.ts` are in the same folder!
78
+ 4. Build `saltygen` directory by running your app once or with cli `npx salty-css build [directory]`
79
+ 5. Import global styles from `saltygen/index.css` to some global css file with `@import 'insert_path_to_index_css';`.
80
+
81
+ ### Create components
82
+
83
+ 1. Create salty components with styled only inside files that end with `.css.ts`, `.salty.ts` `.styled.ts` or `.styles.ts`
84
+
85
+ ## Code examples
86
+
87
+ ### Basic usage example with Button
13
88
 
14
89
  **Salty config**
15
90
 
package/index.cjs CHANGED
@@ -1,18 +1,18 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const K=require("esbuild"),W=require("winston"),L=require("child_process"),y=require("path"),d=require("fs"),G=require("fs/promises");function R(t){const s=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const e in t)if(e!=="default"){const n=Object.getOwnPropertyDescriptor(t,e);Object.defineProperty(s,e,n.get?n:{enumerable:!0,get:()=>t[e]})}}return s.default=t,Object.freeze(s)}const Z=R(K),x=R(W),q=t=>String.fromCharCode(t+(t>25?39:97)),U=(t,s)=>{let e="",n;for(n=Math.abs(t);n>52;n=n/52|0)e=q(n%52)+e;return e=q(n%52)+e,e.length<s?e=e.padStart(s,"a"):e.length>s&&(e=e.slice(-s)),e},X=(t,s)=>{let e=s.length;for(;e;)t=t*33^s.charCodeAt(--e);return t},_=(t,s=3)=>{const e=X(5381,JSON.stringify(t))>>>0;return U(e,s)};function V(t){return t?typeof t!="string"?String(t):t.replace(/\s/g,"-").replace(/[A-Z](?:(?=[^A-Z])|[A-Z]*(?=[A-Z][^A-Z]|$))/g,(s,e)=>(e>0?"-":"")+s.toLowerCase()):""}const Y=(t,s)=>{if(typeof t!="string")return{result:t};if(!s)return{result:t};const e=[];return Object.values(s).forEach(n=>{const{pattern:o,transform:g}=n;t=t.replace(o,$=>{const{value:a,css:f}=g($);return f&&e.push(f),a})}),{result:t,additionalCss:e}},I=t=>typeof t!="string"?{result:t}:/\{[^{}]+\}/g.test(t)?{result:t.replace(/\{([^{}]+)\}/g,(...n)=>`var(--${V(n[1].replaceAll(".","-"))})`)}:{result:t},N=(t,s,e,n)=>{const o=[],g=Object.entries(t).reduce((a,[f,r])=>{const i=f.trim();if(typeof r=="function"&&(r=r()),typeof r=="object"){if(!r)return a;if(i==="variants")return Object.entries(r).forEach(([u,c])=>{c&&Object.entries(c).forEach(([m,l])=>{if(!l)return;const O=`${s}.${u}-${m}`,P=N(l,O);o.push(P)})}),a;if(i==="defaultVariants")return a;if(i==="compoundVariants")return r.forEach(u=>{const{css:c,...m}=u,l=Object.entries(m).reduce((P,[D,k])=>`${P}.${D}-${k}`,s),O=N(c,l);o.push(O)}),a;if(i.startsWith("@")){const u=N(r,s),c=`${i} {
2
- ${u.replace(`
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const ot=require("esbuild"),rt=require("child_process"),u=require("path"),d=require("fs"),L=require("fs/promises"),V=require("winston");var R=typeof document<"u"?document.currentScript:null;function it(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const s in t)if(s!=="default"){const n=Object.getOwnPropertyDescriptor(t,s);Object.defineProperty(e,s,n.get?n:{enumerable:!0,get:()=>t[s]})}}return e.default=t,Object.freeze(e)}const U=it(ot),B=t=>String.fromCharCode(t+(t>25?39:97)),ct=(t,e)=>{let s="",n;for(n=Math.abs(t);n>52;n=n/52|0)s=B(n%52)+s;return s=B(n%52)+s,s.length<e?s=s.padStart(e,"a"):s.length>e&&(s=s.slice(-e)),s},at=(t,e)=>{let s=e.length;for(;s;)t=t*33^e.charCodeAt(--s);return t},q=(t,e=3)=>{const s=at(5381,JSON.stringify(t))>>>0;return ct(s,e)};function E(t){return t?typeof t!="string"?E(String(t)):t.replace(/\s/g,"-").replace(/[A-Z](?:(?=[^A-Z])|[A-Z]*(?=[A-Z][^A-Z]|$))/g,(e,s)=>(s>0?"-":"")+e.toLowerCase()):""}const lt=(t,e)=>{if(typeof t!="string")return{result:t};if(!e)return{result:t};const s=[];return Object.values(e).forEach(n=>{const{pattern:r,transform:c}=n;t=t.replace(r,m=>{const{value:a,css:j}=c(m);return j&&s.push(j),a})}),{result:t,additionalCss:s}},G=t=>typeof t!="string"?{result:t}:/\{[^{}]+\}/g.test(t)?{result:t.replace(/\{([^{}]+)\}/g,(...n)=>`var(--${E(n[1].replaceAll(".","-"))})`)}:{result:t},T=(t,e,s,n)=>{if(!t)return"";const r=[],c=Object.entries(t).reduce((a,[j,o])=>{const y=j.trim();if(typeof o=="function"&&(o=o()),typeof o=="object"){if(!o)return a;if(y==="variants")return Object.entries(o).forEach(([f,i])=>{i&&Object.entries(i).forEach(([h,p])=>{if(!p)return;const P=`${e}.${f}-${h}`,C=T(p,P);r.push(C)})}),a;if(y==="defaultVariants")return a;if(y==="compoundVariants")return o.forEach(f=>{const{css:i,...h}=f,p=Object.entries(h).reduce((C,[S,x])=>`${C}.${S}-${x}`,e),P=T(i,p);r.push(P)}),a;if(y.startsWith("@")){const f=T(o,e),i=`${y} {
2
+ ${f.replace(`
3
3
  `,`
4
4
  `)}
5
- }`;return o.push(c),a}const h=f.includes("&")?i.replace("&",s):i.startsWith(":")?`${s}${i}`:`${s} ${i}`,F=N(r,h);return o.push(F),a}const p=i.startsWith("-")?i:V(i),b=(h,F=";")=>a=`${a}${h}${F}`,j=h=>b(`${p}:${h}`);if(typeof r=="number")return j(r);if(typeof r!="string")if("toString"in r)r=r.toString();else return a;const{modifiers:S}={},C=function*(){yield I(r),yield Y(r,S)}();for(const{result:h,additionalCss:F=[]}of C)r=h,F.forEach(u=>{const c=N(u,"");b(c,"")});return j(r)},"");if(!g)return o.join(`
6
- `);if(!s)return g;let $="";return $=`${s} { ${g} }`,[$,...o].join(`
7
- `)},z=(t,s=[])=>{const e=[],n={};if(Object.entries(t).forEach(([o,g])=>{if(typeof g=="object"){if(!g)return;const $=o.trim(),a=z(g,[...s,$]);e.push(a)}else n[o]=g}),Object.keys(n).length){const o=s.map(V).join("-"),g=N(n,`.${o}`);e.push(g)}return e.join(`
8
- `)};x.createLogger({level:"info",format:x.format.combine(x.format.colorize(),x.format.cli()),transports:[new x.transports.Console({})]});const E=t=>y.join(t,"./saltygen"),Q=["salty","css","styles","styled"],T=t=>new RegExp(`\\.(${Q.join("|")})\\.`).test(t),v=async t=>{const s=E(t),e=y.join(t,"salty-config.ts"),n=y.join(s,"salty-config.js");await Z.build({entryPoints:[e],minify:!0,treeShaking:!0,bundle:!0,outfile:n,format:"esm",external:["react"]});const o=Date.now(),{config:g}=await import(`${n}?t=${o}`);return g},B=async t=>{const s=await v(t),e=new Set,n=(u,c=[])=>u?Object.entries(u).flatMap(([m,l])=>{if(!l)return;if(typeof l=="object")return n(l,[...c,m]);const O=[...c,m].join(".");e.add(`"${O}"`);const P=[...c.map(V),V(m)].join("-"),{result:D}=I(l);return`--${P}: ${D};`}):[],o=u=>u?Object.entries(u).flatMap(([c,m])=>{const l=n(m);return c==="base"?l.join(""):`${c} { ${l.join("")} }`}):[],g=u=>u?Object.entries(u).flatMap(([c,m])=>Object.entries(m).flatMap(([l,O])=>{const P=n(O,[c]),D=`.${c}-${l}, [data-${c}="${l}"]`,k=P.join("");return`${D} { ${k} }`})):[],$=n(s.variables),a=o(s.responsiveVariables),f=g(s.conditionalVariables),r=E(t),i=y.join(r,"css/variables.css"),p=`:root { ${$.join("")} ${a.join("")} } ${f.join("")}`;d.writeFileSync(i,p);const b=y.join(r,"types/css-tokens.d.ts"),S=`type VariableTokens = ${[...e].join("|")}; type PropertyValueToken = \`{\${VariableTokens}}\``;d.writeFileSync(b,S);const w=y.join(r,"css/global.css"),C=N(s.global,"");d.writeFileSync(w,C);const h=y.join(r,"css/templates.css"),F=z(s.templates);d.writeFileSync(h,F)},A=async(t,s)=>{const e=_(t),n=y.join(s,"js",e+".js");await Z.build({entryPoints:[t],minify:!0,treeShaking:!0,bundle:!0,outfile:n,format:"esm",target:["es2022"],keepNames:!0,external:["react"]});const o=Date.now();return await import(`${n}?t=${o}`)},M=async t=>{const s=E(t),e=y.join(s,"salty-config.js"),{config:n}=await import(e);return n},tt=async t=>{try{const s=[],e=[],n=E(t),o=y.join(n,"index.css");(()=>{d.existsSync(n)&&L.execSync("rm -rf "+n),d.mkdirSync(n),d.mkdirSync(y.join(n,"css")),d.mkdirSync(y.join(n,"types"))})(),await B(t);const $=await M(t);async function a(p,b){const j=d.statSync(p);if(j.isDirectory()){const S=d.readdirSync(p);await Promise.all(S.map(w=>a(y.join(p,w),y.join(b,w))))}else if(j.isFile()&&T(p)){const w=await A(p,n),C=[];Object.entries(w).forEach(([c,m])=>{if(m.isKeyframes&&m.css){const k=`${m.animationName}.css`,H=`css/${k}`,J=y.join(n,H);s.push(k),d.writeFileSync(J,m.css);return}if(!m.generator)return;const l=m.generator._withBuildContext({name:c,config:$}),O=`${l.hash}-${l.priority}.css`;e[l.priority]||(e[l.priority]=[]),e[l.priority].push(O),C.push(O);const P=`css/${O}`,D=y.join(n,P);d.writeFileSync(D,l.css)});const h=C.map(c=>`@import url('./${c}');`).join(`
9
- `),F=_(p,6),u=y.join(n,`css/${F}.css`);d.writeFileSync(u,h)}}await a(t,n);const f=s.map(p=>`@import url('./css/${p}');`).join(`
10
- `);let i=`@layer l0, l1, l2, l3, l4, l5, l6, l7, l8;
5
+ }`;return r.push(i),a}const g=j.includes("&")?y.replace("&",e):y.startsWith(":")?`${e}${y}`:`${e} ${y}`,b=T(o,g);return r.push(b),a}const $=y.startsWith("-")?y:E(y),w=(g,b=";")=>a=`${a}${g}${b}`,k=g=>w(`${$}:${g}`);if(typeof o=="number")return k(o);if(typeof o!="string")if("toString"in o)o=o.toString();else return a;const{modifiers:l}={},O=function*(){yield G(o),yield lt(o,l)}();for(const{result:g,additionalCss:b=[]}of O)o=g,b.forEach(f=>{const i=T(f,"");w(i,"")});return k(o)},"");if(!c)return r.join(`
6
+ `);if(!e)return c;let m="";return m=`${e} { ${c} }`,[m,...r].join(`
7
+ `)},H=(t,e=[])=>{if(!t)return"";const s=[],n={};if(Object.entries(t).forEach(([r,c])=>{if(typeof c=="object"){if(!c)return;const m=r.trim(),a=H(c,[...e,m]);s.push(a)}else n[r]=c}),Object.keys(n).length){const r=e.map(E).join("-"),c=T(n,`.${r}`);s.push(c)}return s.join(`
8
+ `)},K=t=>{if(!t||t==="/")throw new Error("Could not find package.json file");const e=u.join(t,"package.json");return d.existsSync(e)?e:K(u.join(t,".."))},ut=async t=>{const e=K(t);return await L.readFile(e,"utf-8").then(JSON.parse).catch(()=>{})},ft=async t=>{const e=await ut(t);if(e)return e.type};let D;const X=async t=>{if(D)return D;const e=await ft(t);return e==="module"?D="esm":(e==="commonjs"||(typeof document>"u"?require("url").pathToFileURL(__filename).href:R&&R.tagName.toUpperCase()==="SCRIPT"&&R.src||new URL("index.cjs",document.baseURI).href).endsWith(".cjs"))&&(D="cjs"),D||"esm"},Z=V.createLogger({level:"debug",format:V.format.combine(V.format.colorize(),V.format.cli()),transports:[new V.transports.Console({})]}),A={externalModules:[]},Y=t=>{if(A.externalModules.length>0)return A.externalModules;const e=u.join(t,"salty.config.ts"),n=d.readFileSync(e,"utf8").match(/externalModules:\s?\[(.*)\]/);if(!n)return[];const r=n[1].split(",").map(c=>c.replace(/['"`]/g,"").trim());return A.externalModules=r,r},J=t=>u.join(t,"./saltygen"),pt=["salty","css","styles","styled"],dt=(t=[])=>new RegExp(`\\.(${[...pt,...t].join("|")})\\.`),_=(t,e=[])=>dt(e).test(t),yt=async t=>{const e=J(t),s=u.join(t,"salty.config.ts"),n=u.join(e,"salty.config.js"),r=await X(t),c=Y(t);await U.build({entryPoints:[s],minify:!0,treeShaking:!0,bundle:!0,outfile:n,format:r,external:c});const m=Date.now(),{config:a}=await import(`${n}?t=${m}`);return a},Q=async t=>{const e=await yt(t),s=new Set,n=(f,i=[])=>f?Object.entries(f).flatMap(([h,p])=>{if(!p)return;if(typeof p=="object")return n(p,[...i,h]);const P=[...i,h].join(".");s.add(`"${P}"`);const C=[...i.map(E),E(h)].join("-"),{result:S}=G(p);return`--${C}: ${S};`}):[],r=f=>f?Object.entries(f).flatMap(([i,h])=>{const p=n(h);return i==="base"?p.join(""):`${i} { ${p.join("")} }`}):[],c=f=>f?Object.entries(f).flatMap(([i,h])=>Object.entries(h).flatMap(([p,P])=>{const C=n(P,[i]),S=`.${i}-${p}, [data-${i}="${p}"]`,x=C.join("");return`${S} { ${x} }`})):[],m=n(e.variables),a=r(e.responsiveVariables),j=c(e.conditionalVariables),o=J(t),y=u.join(o,"css/variables.css"),$=`:root { ${m.join("")} ${a.join("")} } ${j.join("")}`;d.writeFileSync(y,$);const w=u.join(o,"types/css-tokens.d.ts"),l=`type VariableTokens = ${[...s].join("|")||'""'}; type PropertyValueToken = \`{\${VariableTokens}}\``;d.writeFileSync(w,l);const F=u.join(o,"css/global.css"),O=T(e.global,"");d.writeFileSync(F,O);const g=u.join(o,"css/templates.css"),b=H(e.templates);d.writeFileSync(g,b)},I=async(t,e,s)=>{const n=q(e),r=u.join(s,"js",n+".js"),c=await X(t),m=Y(t);await U.build({entryPoints:[e],minify:!0,treeShaking:!0,bundle:!0,outfile:r,format:c,target:["es2022"],keepNames:!0,external:m});const a=Date.now();return await import(`${r}?t=${a}`)},W=async t=>{const e=J(t),s=u.join(e,"salty.config.js"),{config:n}=await import(s);return n},v=()=>{try{return process.env.NODE_ENV==="production"}catch{return!1}},gt=async(t,e=v())=>{try{e?Z.info("Generating CSS in production mode! 🔥"):Z.info("Generating CSS in development mode! 🚀");const s=[],n=[],r=J(t),c=u.join(r,"index.css");(()=>{d.existsSync(r)&&rt.execSync("rm -rf "+r),d.mkdirSync(r),d.mkdirSync(u.join(r,"css")),d.mkdirSync(u.join(r,"types"))})(),await Q(t);const a=await W(t);async function j(l,F){const O=["node_modules","saltygen"],g=d.statSync(l);if(g.isDirectory()){const b=d.readdirSync(l);if(O.some(i=>l.includes(i)))return;await Promise.all(b.map(i=>j(u.join(l,i),u.join(F,i))))}else if(g.isFile()&&_(l)){const f=await I(t,l,r),i=[];Object.entries(f).forEach(([C,S])=>{if(S.isKeyframes&&S.css){const z=`${S.animationName}.css`,st=`css/${z}`,nt=u.join(r,st);s.push(z),d.writeFileSync(nt,S.css);return}if(!S.generator)return;const x=S.generator._withBuildContext({name:C,config:a,prod:e}),M=`${x.hash}-${x.priority}.css`;n[x.priority]||(n[x.priority]=[]),n[x.priority].push(M),i.push(M);const N=`css/${M}`,et=u.join(r,N);d.writeFileSync(et,x.css)});const h=i.map(C=>`@import url('./${C}');`).join(`
9
+ `),p=q(l,6),P=u.join(r,`css/${p}.css`);d.writeFileSync(P,h)}}await j(t,r);const o=s.map(l=>`@import url('./css/${l}');`).join(`
10
+ `);let k=`@layer l0, l1, l2, l3, l4, l5, l6, l7, l8;
11
11
 
12
- ${["@import url('./css/variables.css');","@import url('./css/global.css');","@import url('./css/templates.css');"].join(`
12
+ ${["variables.css","global.css","templates.css"].filter(l=>{try{return d.readFileSync(u.join(r,"css",l),"utf8").length>0}catch{return!1}}).map(l=>`@import url('./css/${l}');`).join(`
13
13
  `)}
14
- ${f}`;if($.importStrategy!=="component"){const p=e.flat().map(b=>`@import url('./css/${b}');`).join(`
15
- `);i+=p}d.writeFileSync(o,i)}catch(s){console.error(s)}},st=async(t,s)=>{try{const e=[],n=y.join(t,"./saltygen"),o=y.join(n,"index.css");if(T(s)){const $=await M(t),a=await A(s,n);Object.entries(a).forEach(([b,j])=>{if(!j.generator)return;const S=j.generator._withBuildContext({name:b,config:$}),w=`${S.hash}-${S.priority}.css`,C=`css/${w}`,h=y.join(n,C);e.push(w),d.writeFileSync(h,S.css)});const f=d.readFileSync(o,"utf8").split(`
16
- `),r=e.map(b=>`@import url('../saltygen/css/${b}');`),p=[...new Set([...f,...r])].join(`
17
- `);d.writeFileSync(o,p)}}catch(e){console.error(e)}},et=async(t,s)=>{try{const e=y.join(t,"./saltygen");if(T(s)){let o=d.readFileSync(s,"utf8");o.replace(/^(?!export\s)const\s.*/gm,i=>`export ${i}`)!==o&&await G.writeFile(s,o);const $=await M(t),a=await A(s,e);let f=o;Object.entries(a).forEach(([i,p])=>{var u;if(p.isKeyframes){console.log("value",p);return}if(!p.generator)return;const b=p.generator._withBuildContext({name:i,config:$}),j=new RegExp(`${i}[=\\s]+[^()]+styled\\(([^,]+),`,"g").exec(o);if(!j)return console.error("Could not find the original declaration");const S=(u=j.at(1))==null?void 0:u.trim(),{element:w,variantKeys:C}=b.props,h=`${i} = styled(${S}, "${b.classNames}", "${b._callerName}", ${JSON.stringify(w)}, ${JSON.stringify(C)});`,F=new RegExp(`${i}[=\\s]+[^()]+styled\\(([^,]+),[^;]+;`,"g");f=f.replace(F,h)});const r=_(s,6);return $.importStrategy==="component"&&(f=`import '../../saltygen/css/${r}.css';
18
- ${f}`),f=f.replace("{ styled }","{ styledClient as styled }"),f=f.replace("@salty-css/react/styled","@salty-css/react/styled-client"),f}}catch(e){console.error(e)}},nt=t=>({name:"stylegen",buildStart:()=>tt(t),load:async s=>{if(T(s))return await et(t,s)},watchChange:{handler:async s=>{T(s)&&await st(t,s),s.includes("salty-config")&&await B(t)}}});exports.saltyPlugin=nt;
14
+ ${o}`;if(a.importStrategy!=="component"){const l=n.flat().map(F=>`@import url('./css/${F}');`).join(`
15
+ `);k+=l}d.writeFileSync(c,k)}catch(s){console.error(s)}},mt=async(t,e)=>{try{const s=[],n=u.join(t,"./saltygen"),r=u.join(n,"index.css");if(_(e)){const m=await W(t),a=await I(t,e,n);Object.entries(a).forEach(([w,k])=>{if(!k.generator)return;const l=k.generator._withBuildContext({name:w,config:m}),F=`${l.hash}-${l.priority}.css`,O=`css/${F}`,g=u.join(n,O);s.push(F),d.writeFileSync(g,l.css)});const j=d.readFileSync(r,"utf8").split(`
16
+ `),o=s.map(w=>`@import url('../saltygen/css/${w}');`),$=[...new Set([...j,...o])].join(`
17
+ `);d.writeFileSync(r,$)}}catch(s){console.error(s)}},ht=async(t,e,s=v())=>{try{const n=u.join(t,"./saltygen");if(_(e)){const c=d.readFileSync(e,"utf8");c.replace(/^(?!export\s)const\s.*/gm,$=>`export ${$}`)!==c&&await L.writeFile(e,c);const a=await W(t),j=await I(t,e,n);let o=c;Object.entries(j).forEach(([$,w])=>{var M;if(w.isKeyframes||!w.generator)return;const k=w.generator._withBuildContext({name:$,config:a,prod:s}),l=new RegExp(`\\s${$}[=\\s]+[^()]+styled\\(([^,]+),`,"g").exec(c);if(!l)return console.error("Could not find the original declaration");const F=(M=l.at(1))==null?void 0:M.trim(),O=new RegExp(`\\s${$}[=\\s]+styled\\(`,"g").exec(o);if(!O)return console.error("Could not find the original declaration");const{index:g}=O;let b=!1;const f=setTimeout(()=>b=!0,5e3);let i=0,h=!1,p=0;for(;!h&&!b;){const N=o[g+i];N==="("&&p++,N===")"&&p--,p===0&&N===")"&&(h=!0),i>o.length&&(b=!0),i++}if(!b)clearTimeout(f);else throw new Error("Failed to find the end of the styled call and timed out");const P=g+i,C=o.slice(g,P),S=o,x=` ${$} = styled(${F}, "${k.classNames}", ${JSON.stringify(k.props)});`;o=o.replace(C,x),S===o&&console.error("Minimize file failed to change content",{name:$,tagName:F})});const y=q(e,6);return a.importStrategy==="component"&&(o=`import '../../saltygen/css/${y}.css';
18
+ ${o}`),o=o.replace("{ styled }","{ styledClient as styled }"),o=o.replace("@salty-css/react/styled","@salty-css/react/styled-client"),o}}catch(n){console.error("Error in minimizeFile:",n)}},tt=t=>({name:"stylegen",buildStart:()=>gt(t),load:async e=>{if(_(e))return await ht(t,e)},watchChange:{handler:async e=>{_(e)&&await mt(t,e),e.includes("salty.config")&&await Q(t)}}});exports.default=tt;exports.saltyPlugin=tt;
package/index.d.ts CHANGED
@@ -6,3 +6,4 @@ export declare const saltyPlugin: (dir: string) => {
6
6
  handler: (filePath: string) => Promise<void>;
7
7
  };
8
8
  };
9
+ export default saltyPlugin;
package/index.js CHANGED
@@ -1,279 +1,327 @@
1
- import * as I from "esbuild";
2
- import * as P from "winston";
3
- import { execSync as L } from "child_process";
4
- import { join as u } from "path";
5
- import { writeFileSync as x, existsSync as q, mkdirSync as A, statSync as G, readdirSync as U, readFileSync as B } from "fs";
6
- import { writeFile as X } from "fs/promises";
7
- const Z = (t) => String.fromCharCode(t + (t > 25 ? 39 : 97)), Y = (t, s) => {
8
- let e = "", n;
9
- for (n = Math.abs(t); n > 52; n = n / 52 | 0) e = Z(n % 52) + e;
10
- return e = Z(n % 52) + e, e.length < s ? e = e.padStart(s, "a") : e.length > s && (e = e.slice(-s)), e;
11
- }, Q = (t, s) => {
12
- let e = s.length;
13
- for (; e; ) t = t * 33 ^ s.charCodeAt(--e);
1
+ import * as K from "esbuild";
2
+ import { execSync as ot } from "child_process";
3
+ import { join as f } from "path";
4
+ import { existsSync as L, writeFileSync as E, mkdirSync as R, statSync as rt, readdirSync as ct, readFileSync as J } from "fs";
5
+ import { readFile as it, writeFile as at } from "fs/promises";
6
+ import { createLogger as lt, format as _, transports as ft } from "winston";
7
+ const G = (t) => String.fromCharCode(t + (t > 25 ? 39 : 97)), ut = (t, e) => {
8
+ let s = "", o;
9
+ for (o = Math.abs(t); o > 52; o = o / 52 | 0) s = G(o % 52) + s;
10
+ return s = G(o % 52) + s, s.length < e ? s = s.padStart(e, "a") : s.length > e && (s = s.slice(-e)), s;
11
+ }, pt = (t, e) => {
12
+ let s = e.length;
13
+ for (; s; ) t = t * 33 ^ e.charCodeAt(--s);
14
14
  return t;
15
- }, M = (t, s = 3) => {
16
- const e = Q(5381, JSON.stringify(t)) >>> 0;
17
- return Y(e, s);
15
+ }, B = (t, e = 3) => {
16
+ const s = pt(5381, JSON.stringify(t)) >>> 0;
17
+ return ut(s, e);
18
18
  };
19
- function k(t) {
20
- return t ? typeof t != "string" ? String(t) : t.replace(/\s/g, "-").replace(/[A-Z](?:(?=[^A-Z])|[A-Z]*(?=[A-Z][^A-Z]|$))/g, (s, e) => (e > 0 ? "-" : "") + s.toLowerCase()) : "";
19
+ function N(t) {
20
+ return t ? typeof t != "string" ? N(String(t)) : t.replace(/\s/g, "-").replace(/[A-Z](?:(?=[^A-Z])|[A-Z]*(?=[A-Z][^A-Z]|$))/g, (e, s) => (s > 0 ? "-" : "") + e.toLowerCase()) : "";
21
21
  }
22
- const v = (t, s) => {
22
+ const gt = (t, e) => {
23
23
  if (typeof t != "string") return { result: t };
24
- if (!s) return { result: t };
25
- const e = [];
26
- return Object.values(s).forEach((n) => {
27
- const { pattern: r, transform: g } = n;
28
- t = t.replace(r, ($) => {
29
- const { value: a, css: f } = g($);
30
- return f && e.push(f), a;
24
+ if (!e) return { result: t };
25
+ const s = [];
26
+ return Object.values(e).forEach((o) => {
27
+ const { pattern: r, transform: i } = o;
28
+ t = t.replace(r, (d) => {
29
+ const { value: a, css: h } = i(d);
30
+ return h && s.push(h), a;
31
31
  });
32
- }), { result: t, additionalCss: e };
33
- }, H = (t) => typeof t != "string" ? { result: t } : /\{[^{}]+\}/g.test(t) ? { result: t.replace(/\{([^{}]+)\}/g, (...n) => `var(--${k(n[1].replaceAll(".", "-"))})`) } : { result: t }, O = (t, s, e, n) => {
34
- const r = [], g = Object.entries(t).reduce((a, [f, o]) => {
35
- const i = f.trim();
36
- if (typeof o == "function" && (o = o()), typeof o == "object") {
37
- if (!o) return a;
38
- if (i === "variants")
39
- return Object.entries(o).forEach(([y, c]) => {
40
- c && Object.entries(c).forEach(([m, l]) => {
41
- if (!l) return;
42
- const F = `${s}.${y}-${m}`, N = O(l, F);
43
- r.push(N);
32
+ }), { result: t, additionalCss: s };
33
+ }, q = (t) => typeof t != "string" ? { result: t } : /\{[^{}]+\}/g.test(t) ? { result: t.replace(/\{([^{}]+)\}/g, (...o) => `var(--${N(o[1].replaceAll(".", "-"))})`) } : { result: t }, D = (t, e, s, o) => {
34
+ if (!t) return "";
35
+ const r = [], i = Object.entries(t).reduce((a, [h, n]) => {
36
+ const g = h.trim();
37
+ if (typeof n == "function" && (n = n()), typeof n == "object") {
38
+ if (!n) return a;
39
+ if (g === "variants")
40
+ return Object.entries(n).forEach(([u, c]) => {
41
+ c && Object.entries(c).forEach(([m, p]) => {
42
+ if (!p) return;
43
+ const x = `${e}.${u}-${m}`, F = D(p, x);
44
+ r.push(F);
44
45
  });
45
46
  }), a;
46
- if (i === "defaultVariants")
47
+ if (g === "defaultVariants")
47
48
  return a;
48
- if (i === "compoundVariants")
49
- return o.forEach((y) => {
50
- const { css: c, ...m } = y, l = Object.entries(m).reduce((N, [D, V]) => `${N}.${D}-${V}`, s), F = O(c, l);
51
- r.push(F);
49
+ if (g === "compoundVariants")
50
+ return n.forEach((u) => {
51
+ const { css: c, ...m } = u, p = Object.entries(m).reduce((F, [w, k]) => `${F}.${w}-${k}`, e), x = D(c, p);
52
+ r.push(x);
52
53
  }), a;
53
- if (i.startsWith("@")) {
54
- const y = O(o, s), c = `${i} {
55
- ${y.replace(`
54
+ if (g.startsWith("@")) {
55
+ const u = D(n, e), c = `${g} {
56
+ ${u.replace(`
56
57
  `, `
57
58
  `)}
58
59
  }`;
59
60
  return r.push(c), a;
60
61
  }
61
- const d = f.includes("&") ? i.replace("&", s) : i.startsWith(":") ? `${s}${i}` : `${s} ${i}`, S = O(o, d);
62
- return r.push(S), a;
62
+ const y = h.includes("&") ? g.replace("&", e) : g.startsWith(":") ? `${e}${g}` : `${e} ${g}`, $ = D(n, y);
63
+ return r.push($), a;
63
64
  }
64
- const p = i.startsWith("-") ? i : k(i), h = (d, S = ";") => a = `${a}${d}${S}`, b = (d) => h(`${p}:${d}`);
65
- if (typeof o == "number") return b(o);
66
- if (typeof o != "string")
67
- if ("toString" in o) o = o.toString();
65
+ const b = g.startsWith("-") ? g : N(g), S = (y, $ = ";") => a = `${a}${y}${$}`, C = (y) => S(`${b}:${y}`);
66
+ if (typeof n == "number") return C(n);
67
+ if (typeof n != "string")
68
+ if ("toString" in n) n = n.toString();
68
69
  else return a;
69
- const { modifiers: j } = {}, C = function* () {
70
- yield H(o), yield v(o, j);
70
+ const { modifiers: l } = {}, P = function* () {
71
+ yield q(n), yield gt(n, l);
71
72
  }();
72
- for (const { result: d, additionalCss: S = [] } of C)
73
- o = d, S.forEach((y) => {
74
- const c = O(y, "");
75
- h(c, "");
73
+ for (const { result: y, additionalCss: $ = [] } of P)
74
+ n = y, $.forEach((u) => {
75
+ const c = D(u, "");
76
+ S(c, "");
76
77
  });
77
- return b(o);
78
+ return C(n);
78
79
  }, "");
79
- if (!g) return r.join(`
80
+ if (!i) return r.join(`
80
81
  `);
81
- if (!s) return g;
82
- let $ = "";
83
- return $ = `${s} { ${g} }`, [$, ...r].join(`
82
+ if (!e) return i;
83
+ let d = "";
84
+ return d = `${e} { ${i} }`, [d, ...r].join(`
84
85
  `);
85
- }, J = (t, s = []) => {
86
- const e = [], n = {};
87
- if (Object.entries(t).forEach(([r, g]) => {
88
- if (typeof g == "object") {
89
- if (!g) return;
90
- const $ = r.trim(), a = J(g, [...s, $]);
91
- e.push(a);
86
+ }, U = (t, e = []) => {
87
+ if (!t) return "";
88
+ const s = [], o = {};
89
+ if (Object.entries(t).forEach(([r, i]) => {
90
+ if (typeof i == "object") {
91
+ if (!i) return;
92
+ const d = r.trim(), a = U(i, [...e, d]);
93
+ s.push(a);
92
94
  } else
93
- n[r] = g;
94
- }), Object.keys(n).length) {
95
- const r = s.map(k).join("-"), g = O(n, `.${r}`);
96
- e.push(g);
95
+ o[r] = i;
96
+ }), Object.keys(o).length) {
97
+ const r = e.map(N).join("-"), i = D(o, `.${r}`);
98
+ s.push(i);
97
99
  }
98
- return e.join(`
100
+ return s.join(`
99
101
  `);
102
+ }, X = (t) => {
103
+ if (!t || t === "/") throw new Error("Could not find package.json file");
104
+ const e = f(t, "package.json");
105
+ return L(e) ? e : X(f(t, ".."));
106
+ }, yt = async (t) => {
107
+ const e = X(t);
108
+ return await it(e, "utf-8").then(JSON.parse).catch(() => {
109
+ });
110
+ }, dt = async (t) => {
111
+ const e = await yt(t);
112
+ if (e)
113
+ return e.type;
100
114
  };
101
- P.createLogger({
102
- level: "info",
103
- format: P.format.combine(P.format.colorize(), P.format.cli()),
104
- transports: [new P.transports.Console({})]
105
- });
106
- const T = (t) => u(t, "./saltygen"), tt = ["salty", "css", "styles", "styled"], E = (t) => new RegExp(`\\.(${tt.join("|")})\\.`).test(t), st = async (t) => {
107
- const s = T(t), e = u(t, "salty-config.ts"), n = u(s, "salty-config.js");
108
- await I.build({
109
- entryPoints: [e],
115
+ let T;
116
+ const Y = async (t) => {
117
+ if (T) return T;
118
+ const e = await dt(t);
119
+ return e === "module" ? T = "esm" : (e === "commonjs" || import.meta.url.endsWith(".cjs")) && (T = "cjs"), T || "esm";
120
+ }, H = lt({
121
+ level: "debug",
122
+ format: _.combine(_.colorize(), _.cli()),
123
+ transports: [new ft.Console({})]
124
+ }), W = {
125
+ externalModules: []
126
+ }, Q = (t) => {
127
+ if (W.externalModules.length > 0) return W.externalModules;
128
+ const e = f(t, "salty.config.ts"), o = J(e, "utf8").match(/externalModules:\s?\[(.*)\]/);
129
+ if (!o) return [];
130
+ const r = o[1].split(",").map((i) => i.replace(/['"`]/g, "").trim());
131
+ return W.externalModules = r, r;
132
+ }, A = (t) => f(t, "./saltygen"), mt = ["salty", "css", "styles", "styled"], ht = (t = []) => new RegExp(`\\.(${[...mt, ...t].join("|")})\\.`), V = (t, e = []) => ht(e).test(t), $t = async (t) => {
133
+ const e = A(t), s = f(t, "salty.config.ts"), o = f(e, "salty.config.js"), r = await Y(t), i = Q(t);
134
+ await K.build({
135
+ entryPoints: [s],
110
136
  minify: !0,
111
137
  treeShaking: !0,
112
138
  bundle: !0,
113
- outfile: n,
114
- format: "esm",
115
- external: ["react"]
139
+ outfile: o,
140
+ format: r,
141
+ external: i
116
142
  });
117
- const r = Date.now(), { config: g } = await import(`${n}?t=${r}`);
118
- return g;
119
- }, K = async (t) => {
120
- const s = await st(t), e = /* @__PURE__ */ new Set(), n = (y, c = []) => y ? Object.entries(y).flatMap(([m, l]) => {
121
- if (!l) return;
122
- if (typeof l == "object") return n(l, [...c, m]);
123
- const F = [...c, m].join(".");
124
- e.add(`"${F}"`);
125
- const N = [...c.map(k), k(m)].join("-"), { result: D } = H(l);
126
- return `--${N}: ${D};`;
127
- }) : [], r = (y) => y ? Object.entries(y).flatMap(([c, m]) => {
128
- const l = n(m);
129
- return c === "base" ? l.join("") : `${c} { ${l.join("")} }`;
130
- }) : [], g = (y) => y ? Object.entries(y).flatMap(([c, m]) => Object.entries(m).flatMap(([l, F]) => {
131
- const N = n(F, [c]), D = `.${c}-${l}, [data-${c}="${l}"]`, V = N.join("");
132
- return `${D} { ${V} }`;
133
- })) : [], $ = n(s.variables), a = r(s.responsiveVariables), f = g(s.conditionalVariables), o = T(t), i = u(o, "css/variables.css"), p = `:root { ${$.join("")} ${a.join("")} } ${f.join("")}`;
134
- x(i, p);
135
- const h = u(o, "types/css-tokens.d.ts"), j = `type VariableTokens = ${[...e].join("|")}; type PropertyValueToken = \`{\${VariableTokens}}\``;
136
- x(h, j);
137
- const w = u(o, "css/global.css"), C = O(s.global, "");
138
- x(w, C);
139
- const d = u(o, "css/templates.css"), S = J(s.templates);
140
- x(d, S);
141
- }, R = async (t, s) => {
142
- const e = M(t), n = u(s, "js", e + ".js");
143
- await I.build({
144
- entryPoints: [t],
143
+ const d = Date.now(), { config: a } = await import(`${o}?t=${d}`);
144
+ return a;
145
+ }, v = async (t) => {
146
+ const e = await $t(t), s = /* @__PURE__ */ new Set(), o = (u, c = []) => u ? Object.entries(u).flatMap(([m, p]) => {
147
+ if (!p) return;
148
+ if (typeof p == "object") return o(p, [...c, m]);
149
+ const x = [...c, m].join(".");
150
+ s.add(`"${x}"`);
151
+ const F = [...c.map(N), N(m)].join("-"), { result: w } = q(p);
152
+ return `--${F}: ${w};`;
153
+ }) : [], r = (u) => u ? Object.entries(u).flatMap(([c, m]) => {
154
+ const p = o(m);
155
+ return c === "base" ? p.join("") : `${c} { ${p.join("")} }`;
156
+ }) : [], i = (u) => u ? Object.entries(u).flatMap(([c, m]) => Object.entries(m).flatMap(([p, x]) => {
157
+ const F = o(x, [c]), w = `.${c}-${p}, [data-${c}="${p}"]`, k = F.join("");
158
+ return `${w} { ${k} }`;
159
+ })) : [], d = o(e.variables), a = r(e.responsiveVariables), h = i(e.conditionalVariables), n = A(t), g = f(n, "css/variables.css"), b = `:root { ${d.join("")} ${a.join("")} } ${h.join("")}`;
160
+ E(g, b);
161
+ const S = f(n, "types/css-tokens.d.ts"), l = `type VariableTokens = ${[...s].join("|") || '""'}; type PropertyValueToken = \`{\${VariableTokens}}\``;
162
+ E(S, l);
163
+ const j = f(n, "css/global.css"), P = D(e.global, "");
164
+ E(j, P);
165
+ const y = f(n, "css/templates.css"), $ = U(e.templates);
166
+ E(y, $);
167
+ }, I = async (t, e, s) => {
168
+ const o = B(e), r = f(s, "js", o + ".js"), i = await Y(t), d = Q(t);
169
+ await K.build({
170
+ entryPoints: [e],
145
171
  minify: !0,
146
172
  treeShaking: !0,
147
173
  bundle: !0,
148
- outfile: n,
149
- format: "esm",
174
+ outfile: r,
175
+ format: i,
150
176
  target: ["es2022"],
151
177
  keepNames: !0,
152
- external: ["react"]
178
+ external: d
153
179
  });
154
- const r = Date.now();
155
- return await import(`${n}?t=${r}`);
156
- }, _ = async (t) => {
157
- const s = T(t), e = u(s, "salty-config.js"), { config: n } = await import(e);
158
- return n;
159
- }, et = async (t) => {
180
+ const a = Date.now();
181
+ return await import(`${r}?t=${a}`);
182
+ }, Z = async (t) => {
183
+ const e = A(t), s = f(e, "salty.config.js"), { config: o } = await import(s);
184
+ return o;
185
+ }, tt = () => {
160
186
  try {
161
- const s = [], e = [], n = T(t), r = u(n, "index.css");
187
+ return process.env.NODE_ENV === "production";
188
+ } catch {
189
+ return !1;
190
+ }
191
+ }, bt = async (t, e = tt()) => {
192
+ try {
193
+ e ? H.info("Generating CSS in production mode! 🔥") : H.info("Generating CSS in development mode! 🚀");
194
+ const s = [], o = [], r = A(t), i = f(r, "index.css");
162
195
  (() => {
163
- q(n) && L("rm -rf " + n), A(n), A(u(n, "css")), A(u(n, "types"));
164
- })(), await K(t);
165
- const $ = await _(t);
166
- async function a(p, h) {
167
- const b = G(p);
168
- if (b.isDirectory()) {
169
- const j = U(p);
170
- await Promise.all(j.map((w) => a(u(p, w), u(h, w))));
171
- } else if (b.isFile() && E(p)) {
172
- const w = await R(p, n), C = [];
173
- Object.entries(w).forEach(([c, m]) => {
174
- if (m.isKeyframes && m.css) {
175
- const V = `${m.animationName}.css`, W = `css/${V}`, z = u(n, W);
176
- s.push(V), x(z, m.css);
196
+ L(r) && ot("rm -rf " + r), R(r), R(f(r, "css")), R(f(r, "types"));
197
+ })(), await v(t);
198
+ const a = await Z(t);
199
+ async function h(l, j) {
200
+ const P = ["node_modules", "saltygen"], y = rt(l);
201
+ if (y.isDirectory()) {
202
+ const $ = ct(l);
203
+ if (P.some((c) => l.includes(c))) return;
204
+ await Promise.all($.map((c) => h(f(l, c), f(j, c))));
205
+ } else if (y.isFile() && V(l)) {
206
+ const u = await I(t, l, r), c = [];
207
+ Object.entries(u).forEach(([F, w]) => {
208
+ if (w.isKeyframes && w.css) {
209
+ const z = `${w.animationName}.css`, st = `css/${z}`, nt = f(r, st);
210
+ s.push(z), E(nt, w.css);
177
211
  return;
178
212
  }
179
- if (!m.generator) return;
180
- const l = m.generator._withBuildContext({
181
- name: c,
182
- config: $
183
- }), F = `${l.hash}-${l.priority}.css`;
184
- e[l.priority] || (e[l.priority] = []), e[l.priority].push(F), C.push(F);
185
- const N = `css/${F}`, D = u(n, N);
186
- x(D, l.css);
213
+ if (!w.generator) return;
214
+ const k = w.generator._withBuildContext({
215
+ name: F,
216
+ config: a,
217
+ prod: e
218
+ }), M = `${k.hash}-${k.priority}.css`;
219
+ o[k.priority] || (o[k.priority] = []), o[k.priority].push(M), c.push(M);
220
+ const O = `css/${M}`, et = f(r, O);
221
+ E(et, k.css);
187
222
  });
188
- const d = C.map((c) => `@import url('./${c}');`).join(`
189
- `), S = M(p, 6), y = u(n, `css/${S}.css`);
190
- x(y, d);
223
+ const m = c.map((F) => `@import url('./${F}');`).join(`
224
+ `), p = B(l, 6), x = f(r, `css/${p}.css`);
225
+ E(x, m);
191
226
  }
192
227
  }
193
- await a(t, n);
194
- const f = s.map((p) => `@import url('./css/${p}');`).join(`
228
+ await h(t, r);
229
+ const n = s.map((l) => `@import url('./css/${l}');`).join(`
195
230
  `);
196
- let i = `@layer l0, l1, l2, l3, l4, l5, l6, l7, l8;
231
+ let C = `@layer l0, l1, l2, l3, l4, l5, l6, l7, l8;
197
232
 
198
- ${["@import url('./css/variables.css');", "@import url('./css/global.css');", "@import url('./css/templates.css');"].join(`
233
+ ${["variables.css", "global.css", "templates.css"].filter((l) => {
234
+ try {
235
+ return J(f(r, "css", l), "utf8").length > 0;
236
+ } catch {
237
+ return !1;
238
+ }
239
+ }).map((l) => `@import url('./css/${l}');`).join(`
199
240
  `)}
200
- ${f}`;
201
- if ($.importStrategy !== "component") {
202
- const p = e.flat().map((h) => `@import url('./css/${h}');`).join(`
241
+ ${n}`;
242
+ if (a.importStrategy !== "component") {
243
+ const l = o.flat().map((j) => `@import url('./css/${j}');`).join(`
203
244
  `);
204
- i += p;
245
+ C += l;
205
246
  }
206
- x(r, i);
247
+ E(i, C);
207
248
  } catch (s) {
208
249
  console.error(s);
209
250
  }
210
- }, nt = async (t, s) => {
251
+ }, wt = async (t, e) => {
211
252
  try {
212
- const e = [], n = u(t, "./saltygen"), r = u(n, "index.css");
213
- if (E(s)) {
214
- const $ = await _(t), a = await R(s, n);
215
- Object.entries(a).forEach(([h, b]) => {
216
- if (!b.generator) return;
217
- const j = b.generator._withBuildContext({
218
- name: h,
219
- config: $
220
- }), w = `${j.hash}-${j.priority}.css`, C = `css/${w}`, d = u(n, C);
221
- e.push(w), x(d, j.css);
253
+ const s = [], o = f(t, "./saltygen"), r = f(o, "index.css");
254
+ if (V(e)) {
255
+ const d = await Z(t), a = await I(t, e, o);
256
+ Object.entries(a).forEach(([S, C]) => {
257
+ if (!C.generator) return;
258
+ const l = C.generator._withBuildContext({
259
+ name: S,
260
+ config: d
261
+ }), j = `${l.hash}-${l.priority}.css`, P = `css/${j}`, y = f(o, P);
262
+ s.push(j), E(y, l.css);
222
263
  });
223
- const f = B(r, "utf8").split(`
224
- `), o = e.map((h) => `@import url('../saltygen/css/${h}');`), p = [.../* @__PURE__ */ new Set([...f, ...o])].join(`
264
+ const h = J(r, "utf8").split(`
265
+ `), n = s.map((S) => `@import url('../saltygen/css/${S}');`), b = [.../* @__PURE__ */ new Set([...h, ...n])].join(`
225
266
  `);
226
- x(r, p);
267
+ E(r, b);
227
268
  }
228
- } catch (e) {
229
- console.error(e);
269
+ } catch (s) {
270
+ console.error(s);
230
271
  }
231
- }, rt = async (t, s) => {
272
+ }, St = async (t, e, s = tt()) => {
232
273
  try {
233
- const e = u(t, "./saltygen");
234
- if (E(s)) {
235
- let r = B(s, "utf8");
236
- r.replace(/^(?!export\s)const\s.*/gm, (i) => `export ${i}`) !== r && await X(s, r);
237
- const $ = await _(t), a = await R(s, e);
238
- let f = r;
239
- Object.entries(a).forEach(([i, p]) => {
240
- var y;
241
- if (p.isKeyframes) {
242
- console.log("value", p);
243
- return;
274
+ const o = f(t, "./saltygen");
275
+ if (V(e)) {
276
+ const i = J(e, "utf8");
277
+ i.replace(/^(?!export\s)const\s.*/gm, (b) => `export ${b}`) !== i && await at(e, i);
278
+ const a = await Z(t), h = await I(t, e, o);
279
+ let n = i;
280
+ Object.entries(h).forEach(([b, S]) => {
281
+ var M;
282
+ if (S.isKeyframes || !S.generator) return;
283
+ const C = S.generator._withBuildContext({
284
+ name: b,
285
+ config: a,
286
+ prod: s
287
+ }), l = new RegExp(`\\s${b}[=\\s]+[^()]+styled\\(([^,]+),`, "g").exec(i);
288
+ if (!l) return console.error("Could not find the original declaration");
289
+ const j = (M = l.at(1)) == null ? void 0 : M.trim(), P = new RegExp(`\\s${b}[=\\s]+styled\\(`, "g").exec(n);
290
+ if (!P) return console.error("Could not find the original declaration");
291
+ const { index: y } = P;
292
+ let $ = !1;
293
+ const u = setTimeout(() => $ = !0, 5e3);
294
+ let c = 0, m = !1, p = 0;
295
+ for (; !m && !$; ) {
296
+ const O = n[y + c];
297
+ O === "(" && p++, O === ")" && p--, p === 0 && O === ")" && (m = !0), c > n.length && ($ = !0), c++;
244
298
  }
245
- if (!p.generator) return;
246
- const h = p.generator._withBuildContext({
247
- name: i,
248
- config: $
249
- }), b = new RegExp(`${i}[=\\s]+[^()]+styled\\(([^,]+),`, "g").exec(r);
250
- if (!b)
251
- return console.error("Could not find the original declaration");
252
- const j = (y = b.at(1)) == null ? void 0 : y.trim(), { element: w, variantKeys: C } = h.props, d = `${i} = styled(${j}, "${h.classNames}", "${h._callerName}", ${JSON.stringify(w)}, ${JSON.stringify(
253
- C
254
- )});`, S = new RegExp(`${i}[=\\s]+[^()]+styled\\(([^,]+),[^;]+;`, "g");
255
- f = f.replace(S, d);
299
+ if (!$) clearTimeout(u);
300
+ else throw new Error("Failed to find the end of the styled call and timed out");
301
+ const x = y + c, F = n.slice(y, x), w = n, k = ` ${b} = styled(${j}, "${C.classNames}", ${JSON.stringify(C.props)});`;
302
+ n = n.replace(F, k), w === n && console.error("Minimize file failed to change content", { name: b, tagName: j });
256
303
  });
257
- const o = M(s, 6);
258
- return $.importStrategy === "component" && (f = `import '../../saltygen/css/${o}.css';
259
- ${f}`), f = f.replace("{ styled }", "{ styledClient as styled }"), f = f.replace("@salty-css/react/styled", "@salty-css/react/styled-client"), f;
304
+ const g = B(e, 6);
305
+ return a.importStrategy === "component" && (n = `import '../../saltygen/css/${g}.css';
306
+ ${n}`), n = n.replace("{ styled }", "{ styledClient as styled }"), n = n.replace("@salty-css/react/styled", "@salty-css/react/styled-client"), n;
260
307
  }
261
- } catch (e) {
262
- console.error(e);
308
+ } catch (o) {
309
+ console.error("Error in minimizeFile:", o);
263
310
  }
264
- }, lt = (t) => ({
311
+ }, Pt = (t) => ({
265
312
  name: "stylegen",
266
- buildStart: () => et(t),
267
- load: async (s) => {
268
- if (E(s))
269
- return await rt(t, s);
313
+ buildStart: () => bt(t),
314
+ load: async (e) => {
315
+ if (V(e))
316
+ return await St(t, e);
270
317
  },
271
318
  watchChange: {
272
- handler: async (s) => {
273
- E(s) && await nt(t, s), s.includes("salty-config") && await K(t);
319
+ handler: async (e) => {
320
+ V(e) && await wt(t, e), e.includes("salty.config") && await v(t);
274
321
  }
275
322
  }
276
323
  });
277
324
  export {
278
- lt as saltyPlugin
325
+ Pt as default,
326
+ Pt as saltyPlugin
279
327
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@salty-css/vite",
3
- "version": "0.0.1-alpha.10",
3
+ "version": "0.0.1-alpha.101",
4
4
  "main": "./dist/index.js",
5
5
  "module": "./dist/index.mjs",
6
6
  "typings": "./dist/index.d.ts",
@@ -10,7 +10,12 @@
10
10
  "publishConfig": {
11
11
  "access": "public"
12
12
  },
13
- "homepage": "https://github.com/margarita-form/salty-css",
13
+ "description": "Vite plugin for Salty CSS",
14
+ "homepage": "https://salty-css.dev/",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/margarita-form/salty-css.git"
18
+ },
14
19
  "bugs": {
15
20
  "url": "https://github.com/margarita-form/salty-css/issues"
16
21
  },
@@ -19,6 +24,7 @@
19
24
  "!**/*.tsbuildinfo"
20
25
  ],
21
26
  "nx": {
27
+ "sourceRoot": "libs/vite/src",
22
28
  "name": "vite"
23
29
  },
24
30
  "exports": {
@@ -26,5 +32,8 @@
26
32
  "import": "./index.js",
27
33
  "require": "./index.cjs"
28
34
  }
35
+ },
36
+ "dependencies": {
37
+ "@salty-css/core": "^0.0.1-alpha.101"
29
38
  }
30
39
  }