@salty-css/vite 0.0.1-alpha.11 → 0.0.1-alpha.111

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 +24 -14
  3. package/index.d.ts +1 -0
  4. package/index.js +283 -211
  5. package/package.json +10 -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,28 @@
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),k=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},D=(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=D(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,[x,N])=>`${P}.${x}-${N}`,s),O=D(c,l);o.push(O)}),a;if(i.startsWith("@")){const u=D(r,s),c=`${i} {
2
- ${u.replace(`
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const rt=require("esbuild"),it=require("child_process"),l=require("path"),f=require("fs"),L=require("fs/promises"),V=require("winston");var R=typeof document<"u"?document.currentScript:null;function ct(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=ct(rt),B=t=>String.fromCharCode(t+(t>25?39:97)),at=(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},lt=(t,e)=>{let s=e.length;for(;s;)t=t*33^e.charCodeAt(--s);return t},q=(t,e=3)=>{const s=lt(5381,JSON.stringify(t))>>>0;return at(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 ut=(t,e)=>{if(typeof t!="string")return{result:t};if(!e)return{result:t};const s=[];return Object.values(e).forEach(n=>{const{pattern:o,transform:i}=n;t=t.replace(o,y=>{const{value:a,css:j}=i(y);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},D=(t,e,s,n)=>{if(!t)return"";const o=[],i=Object.entries(t).reduce((a,[j,r])=>{const d=j.trim();if(typeof r=="function"&&(r=r()),typeof r=="object"){if(!r)return a;if(d==="variants")return Object.entries(r).forEach(([S,c])=>{c&&Object.entries(c).forEach(([p,m])=>{if(!m)return;const h=`${e}.${S}-${p}`,T=D(m,h);o.push(T)})}),a;if(d==="defaultVariants")return a;if(d==="compoundVariants")return r.forEach(S=>{const{css:c,...p}=S,m=Object.entries(p).reduce((T,[w,F])=>`${T}.${w}-${F}`,e),h=D(c,m);o.push(h)}),a;if(d.startsWith("@")){const S=D(r,e),c=`${d} {
2
+ ${S.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=D(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=D(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=D(n,`.${o}`);e.push(g)}return e.join(`
8
- `)};k.createLogger({level:"info",format:k.format.combine(k.format.colorize(),k.format.cli()),transports:[new k.transports.Console({})]});const E=t=>y.join(t,"./saltygen"),Q=["salty","css","styles","styled"],v=(t=[])=>new RegExp(`\\.(${[...Q,...t].join("|")})\\.`),T=(t,s=[])=>v(s).test(t),tt=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 tt(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:x}=I(l);return`--${P}: ${x};`}):[],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]),x=`.${c}-${l}, [data-${c}="${l}"]`,N=P.join("");return`${x} { ${N} }`})):[],$=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=D(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},st=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 N=`${m.animationName}.css`,H=`css/${N}`,J=y.join(n,H);s.push(N),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}`,x=y.join(n,P);d.writeFileSync(x,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 o.push(c),a}const g=j.includes("&")?d.replace("&",e):d.startsWith(":")?`${e}${d}`:`${e} ${d}`,$=D(r,g);return o.push($),a}const b=d.startsWith("-")?d:E(d),k=(g,$=";")=>a=`${a}${g}${$}`,C=g=>k(`${b}:${g}`);if(typeof r=="number")return C(r);if(typeof r!="string")if("toString"in r)r=r.toString();else return a;const{modifiers:u}={},O=function*(){yield G(r),yield ut(r,u)}();for(const{result:g,additionalCss:$=[]}of O)r=g,$.forEach(S=>{const c=D(S,"");k(c,"")});return C(r)},"");if(!i)return o.join(`
6
+ `);if(!e)return i;let y="";return y=`${e} { ${i} }`,[y,...o].join(`
7
+ `)},H=(t,e=[])=>{if(!t)return"";const s=[],n={};if(Object.entries(t).forEach(([o,i])=>{if(typeof i=="object"){if(!i)return;const y=o.trim(),a=H(i,[...e,y]);s.push(a)}else n[o]=i}),Object.keys(n).length){const o=e.map(E).join("-"),i=D(n,`.${o}`);s.push(i)}return s.join(`
8
+ `)},ft=t=>Object.entries(t).reduce((e,[s,n])=>(typeof n=="object"&&(e[s]=K(n).map(o=>`"${o}"`).join(" | ")),e),{}),K=(t,e="",s=new Set)=>t?(Object.entries(t).forEach(([n,o])=>{const i=e?`${e}.${n}`:n;return typeof o=="object"?K(o,i,s):s.add(e)}),[...s]):[],X=t=>{if(!t||t==="/")throw new Error("Could not find package.json file");const e=l.join(t,"package.json");return f.existsSync(e)?e:X(l.join(t,".."))},pt=async t=>{const e=X(t);return await L.readFile(e,"utf-8").then(JSON.parse).catch(()=>{})},dt=async t=>{const e=await pt(t);if(e)return e.type};let M;const Y=async t=>{if(M)return M;const e=await dt(t);return e==="module"?M="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"))&&(M="cjs"),M||"esm"},Z=V.createLogger({level:"debug",format:V.format.combine(V.format.colorize(),V.format.cli()),transports:[new V.transports.Console({})]}),A={externalModules:[]},Q=t=>{if(A.externalModules.length>0)return A.externalModules;const e=l.join(t,"salty.config.ts"),n=f.readFileSync(e,"utf8").match(/externalModules:\s?\[(.*)\]/);if(!n)return[];const o=n[1].split(",").map(i=>i.replace(/['"`]/g,"").trim());return A.externalModules=o,o},J=t=>l.join(t,"./saltygen"),yt=["salty","css","styles","styled"],gt=(t=[])=>new RegExp(`\\.(${[...yt,...t].join("|")})\\.`),_=(t,e=[])=>gt(e).test(t),mt=async t=>{const e=J(t),s=l.join(t,"salty.config.ts"),n=l.join(e,"salty.config.js"),o=await Y(t),i=Q(t);await U.build({entryPoints:[s],minify:!0,treeShaking:!0,bundle:!0,outfile:n,format:o,external:i});const y=Date.now(),{config:a}=await import(`${n}?t=${y}`);return a},v=async t=>{const e=await mt(t),s=new Set,n=(c,p=[])=>c?Object.entries(c).flatMap(([m,h])=>{if(!h)return;if(typeof h=="object")return n(h,[...p,m]);const T=[...p,m].join(".");s.add(`"${T}"`);const w=[...p.map(E),E(m)].join("-"),{result:F}=G(h);return`--${w}: ${F};`}):[],o=c=>c?Object.entries(c).flatMap(([p,m])=>{const h=n(m);return p==="base"?h.join(""):`${p} { ${h.join("")} }`}):[],i=c=>c?Object.entries(c).flatMap(([p,m])=>Object.entries(m).flatMap(([h,T])=>{const w=n(T,[p]),F=`.${p}-${h}, [data-${p}="${h}"]`,P=w.join("");return`${F} { ${P} }`})):[],y=n(e.variables),a=o(e.responsiveVariables),j=i(e.conditionalVariables),r=J(t),d=l.join(r,"css/variables.css"),b=`:root { ${y.join("")} ${a.join("")} } ${j.join("")}`;f.writeFileSync(d,b);const k=l.join(r,"css/global.css"),C=D(e.global,"");f.writeFileSync(k,C);const u=l.join(r,"css/templates.css"),x=H(e.templates),O=ft(e.templates);f.writeFileSync(u,x);const g=l.join(r,"types/css-tokens.d.ts"),S=`
9
+ // Variable types
10
+ type VariableTokens = ${[...s].join("|")};
11
+ type PropertyValueToken = \`{\${VariableTokens}}\`;
11
12
 
12
- ${["@import url('./css/variables.css');","@import url('./css/global.css');","@import url('./css/templates.css');"].join(`
13
+ // Template types
14
+ type TemplateTokens = {
15
+ ${Object.entries(O).map(([c,p])=>`${c}?: ${p}`).join(`
13
16
  `)}
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)}},et=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)}},nt=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)}},ot=t=>({name:"stylegen",buildStart:()=>st(t),load:async s=>{if(T(s))return await nt(t,s)},watchChange:{handler:async s=>{T(s)&&await et(t,s),s.includes("salty-config")&&await B(t)}}});exports.saltyPlugin=ot;
17
+ }
18
+ `;f.writeFileSync(g,S)},I=async(t,e,s)=>{const n=q(e),o=l.join(s,"./temp");f.existsSync(o)||f.mkdirSync(o);const i=l.parse(e);let y=f.readFileSync(e,"utf8");y=y.replace(/styled\([^"'`{,]+,/g,"styled('div',");const a=l.join(s,"js",n+".js"),j=Q(t),r=await Y(t);await U.build({stdin:{contents:y,sourcefile:i.base,resolveDir:i.dir,loader:"ts"},minify:!1,treeShaking:!0,bundle:!0,outfile:a,format:r,target:["node20"],keepNames:!0,external:j,packages:"external"});const d=Date.now();return await import(`${a}?t=${d}`)},W=async t=>{const e=J(t),s=l.join(e,"salty.config.js"),{config:n}=await import(s);return n},tt=()=>{try{return process.env.NODE_ENV==="production"}catch{return!1}},ht=async(t,e=tt())=>{try{e?Z.info("Generating CSS in production mode! 🔥"):Z.info("Generating CSS in development mode! 🚀");const s=[],n=[],o=J(t),i=l.join(o,"index.css");(()=>{f.existsSync(o)&&it.execSync("rm -rf "+o),f.mkdirSync(o),f.mkdirSync(l.join(o,"css")),f.mkdirSync(l.join(o,"types"))})(),await v(t);const a=await W(t);async function j(u,x){const O=["node_modules","saltygen"],g=f.statSync(u);if(g.isDirectory()){const $=f.readdirSync(u);if(O.some(c=>u.includes(c)))return;await Promise.all($.map(c=>j(l.join(u,c),l.join(x,c))))}else if(g.isFile()&&_(u)){const S=await I(t,u,o),c=[];Object.entries(S).forEach(([T,w])=>{if(w.isKeyframes&&w.css){const z=`${w.animationName}.css`,nt=`css/${z}`,ot=l.join(o,nt);s.push(z),f.writeFileSync(ot,w.css);return}if(!w.generator)return;const F=w.generator._withBuildContext({name:T,config:a,prod:e}),P=`${F.hash}-${F.priority}.css`;n[F.priority]||(n[F.priority]=[]),n[F.priority].push(P),c.push(P);const N=`css/${P}`,st=l.join(o,N);f.writeFileSync(st,F.css)});const p=c.map(T=>`@import url('./${T}');`).join(`
19
+ `),m=q(u,6),h=l.join(o,`css/${m}.css`);f.writeFileSync(h,p)}}await j(t,o);const r=s.map(u=>`@import url('./css/${u}');`).join(`
20
+ `);let C=`@layer l0, l1, l2, l3, l4, l5, l6, l7, l8;
21
+
22
+ ${["variables.css","global.css","templates.css"].filter(u=>{try{return f.readFileSync(l.join(o,"css",u),"utf8").length>0}catch{return!1}}).map(u=>`@import url('./css/${u}');`).join(`
23
+ `)}
24
+ ${r}`;if(a.importStrategy!=="component"){const u=n.flat().map(x=>`@import url('./css/${x}');`).join(`
25
+ `);C+=u}f.writeFileSync(i,C)}catch(s){console.error(s)}},jt=async(t,e)=>{try{const s=[],n=l.join(t,"./saltygen"),o=l.join(n,"index.css");if(_(e)){const y=await W(t),a=await I(t,e,n);Object.entries(a).forEach(([k,C])=>{if(!C.generator)return;const u=C.generator._withBuildContext({name:k,config:y}),x=`${u.hash}-${u.priority}.css`,O=`css/${x}`,g=l.join(n,O);s.push(x),f.writeFileSync(g,u.css)});const j=f.readFileSync(o,"utf8").split(`
26
+ `),r=s.map(k=>`@import url('../saltygen/css/${k}');`),b=[...new Set([...j,...r])].join(`
27
+ `);f.writeFileSync(o,b)}}catch(s){console.error(s)}},bt=async(t,e,s=tt())=>{try{const n=l.join(t,"./saltygen");if(_(e)){const i=f.readFileSync(e,"utf8");i.replace(/^(?!export\s)const\s.*/gm,b=>`export ${b}`)!==i&&await L.writeFile(e,i);const a=await W(t),j=await I(t,e,n);let r=i;Object.entries(j).forEach(([b,k])=>{var P;if(k.isKeyframes||!k.generator)return;const C=k.generator._withBuildContext({name:b,config:a,prod:s}),u=new RegExp(`\\s${b}[=\\s]+[^()]+styled\\(([^,]+),`,"g").exec(i);if(!u)return console.error("Could not find the original declaration");const x=(P=u.at(1))==null?void 0:P.trim(),O=new RegExp(`\\s${b}[=\\s]+styled\\(`,"g").exec(r);if(!O)return console.error("Could not find the original declaration");const{index:g}=O;let $=!1;const S=setTimeout(()=>$=!0,5e3);let c=0,p=!1,m=0;for(;!p&&!$;){const N=r[g+c];N==="("&&m++,N===")"&&m--,m===0&&N===")"&&(p=!0),c>r.length&&($=!0),c++}if(!$)clearTimeout(S);else throw new Error("Failed to find the end of the styled call and timed out");const h=g+c,T=r.slice(g,h),w=r,F=` ${b} = styled(${x}, "${C.classNames}", ${JSON.stringify(C.props)});`;r=r.replace(T,F),w===r&&console.error("Minimize file failed to change content",{name:b,tagName:x})});const d=q(e,6);return a.importStrategy==="component"&&(r=`import '../../saltygen/css/${d}.css';
28
+ ${r}`),r=r.replace("{ styled }","{ styledClient as styled }"),r=r.replace("@salty-css/react/styled","@salty-css/react/styled-client"),r}}catch(n){console.error("Error in minimizeFile:",n)}},et=t=>({name:"stylegen",buildStart:()=>ht(t),load:async e=>{if(_(e))return await bt(t,e)},watchChange:{handler:async e=>{_(e)&&await jt(t,e),e.includes("salty.config")&&await v(t)}}});exports.default=et;exports.saltyPlugin=et;
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,351 @@
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 L from "esbuild";
2
+ import { execSync as rt } from "child_process";
3
+ import { join as f, parse as it } from "path";
4
+ import { existsSync as B, writeFileSync as E, mkdirSync as A, statSync as ct, readdirSync as at, readFileSync as J } from "fs";
5
+ import { readFile as lt, writeFile as ft } from "fs/promises";
6
+ import { createLogger as pt, format as _, transports as ut } from "winston";
7
+ const H = (t) => String.fromCharCode(t + (t > 25 ? 39 : 97)), gt = (t, e) => {
8
+ let s = "", n;
9
+ for (n = Math.abs(t); n > 52; n = n / 52 | 0) s = H(n % 52) + s;
10
+ return s = H(n % 52) + s, s.length < e ? s = s.padStart(e, "a") : s.length > e && (s = s.slice(-e)), s;
11
+ }, dt = (t, e) => {
12
+ let s = e.length;
13
+ for (; s; ) t = t * 33 ^ e.charCodeAt(--s);
14
14
  return t;
15
- }, R = (t, s = 3) => {
16
- const e = Q(5381, JSON.stringify(t)) >>> 0;
17
- return Y(e, s);
15
+ }, I = (t, e = 3) => {
16
+ const s = dt(5381, JSON.stringify(t)) >>> 0;
17
+ return gt(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 V(t) {
20
+ return t ? typeof t != "string" ? V(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 yt = (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((n) => {
27
+ const { pattern: o, transform: i } = n;
28
+ t = t.replace(o, (g) => {
29
+ const { value: a, css: h } = i(g);
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, (...n) => `var(--${V(n[1].replaceAll(".", "-"))})`) } : { result: t }, D = (t, e, s, n) => {
34
+ if (!t) return "";
35
+ const o = [], i = Object.entries(t).reduce((a, [h, r]) => {
36
+ const u = h.trim();
37
+ if (typeof r == "function" && (r = r()), typeof r == "object") {
38
+ if (!r) return a;
39
+ if (u === "variants")
40
+ return Object.entries(r).forEach(([j, c]) => {
41
+ c && Object.entries(c).forEach(([p, y]) => {
42
+ if (!y) return;
43
+ const m = `${e}.${j}-${p}`, x = D(y, m);
44
+ o.push(x);
44
45
  });
45
46
  }), a;
46
- if (i === "defaultVariants")
47
+ if (u === "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 (u === "compoundVariants")
50
+ return r.forEach((j) => {
51
+ const { css: c, ...p } = j, y = Object.entries(p).reduce((x, [w, S]) => `${x}.${w}-${S}`, e), m = D(c, y);
52
+ o.push(m);
52
53
  }), a;
53
- if (i.startsWith("@")) {
54
- const y = O(o, s), c = `${i} {
55
- ${y.replace(`
54
+ if (u.startsWith("@")) {
55
+ const j = D(r, e), c = `${u} {
56
+ ${j.replace(`
56
57
  `, `
57
58
  `)}
58
59
  }`;
59
- return r.push(c), a;
60
+ return o.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 d = h.includes("&") ? u.replace("&", e) : u.startsWith(":") ? `${e}${u}` : `${e} ${u}`, b = D(r, d);
63
+ return o.push(b), 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 $ = u.startsWith("-") ? u : V(u), F = (d, b = ";") => a = `${a}${d}${b}`, C = (d) => F(`${$}:${d}`);
66
+ if (typeof r == "number") return C(r);
67
+ if (typeof r != "string")
68
+ if ("toString" in r) r = r.toString();
68
69
  else return a;
69
- const { modifiers: j } = {}, C = function* () {
70
- yield H(o), yield v(o, j);
70
+ const { modifiers: l } = {}, T = function* () {
71
+ yield q(r), yield yt(r, 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: d, additionalCss: b = [] } of T)
74
+ r = d, b.forEach((j) => {
75
+ const c = D(j, "");
76
+ F(c, "");
76
77
  });
77
- return b(o);
78
+ return C(r);
78
79
  }, "");
79
- if (!g) return r.join(`
80
+ if (!i) return o.join(`
80
81
  `);
81
- if (!s) return g;
82
- let $ = "";
83
- return $ = `${s} { ${g} }`, [$, ...r].join(`
82
+ if (!e) return i;
83
+ let g = "";
84
+ return g = `${e} { ${i} }`, [g, ...o].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 = [], n = {};
89
+ if (Object.entries(t).forEach(([o, i]) => {
90
+ if (typeof i == "object") {
91
+ if (!i) return;
92
+ const g = o.trim(), a = U(i, [...e, g]);
93
+ s.push(a);
92
94
  } else
93
- n[r] = g;
95
+ n[o] = i;
94
96
  }), Object.keys(n).length) {
95
- const r = s.map(k).join("-"), g = O(n, `.${r}`);
96
- e.push(g);
97
+ const o = e.map(V).join("-"), i = D(n, `.${o}`);
98
+ s.push(i);
97
99
  }
98
- return e.join(`
100
+ return s.join(`
99
101
  `);
102
+ }, mt = (t) => Object.entries(t).reduce((e, [s, n]) => (typeof n == "object" && (e[s] = X(n).map((o) => `"${o}"`).join(" | ")), e), {}), X = (t, e = "", s = /* @__PURE__ */ new Set()) => t ? (Object.entries(t).forEach(([n, o]) => {
103
+ const i = e ? `${e}.${n}` : n;
104
+ return typeof o == "object" ? X(o, i, s) : s.add(e);
105
+ }), [...s]) : [], Y = (t) => {
106
+ if (!t || t === "/") throw new Error("Could not find package.json file");
107
+ const e = f(t, "package.json");
108
+ return B(e) ? e : Y(f(t, ".."));
109
+ }, ht = async (t) => {
110
+ const e = Y(t);
111
+ return await lt(e, "utf-8").then(JSON.parse).catch(() => {
112
+ });
113
+ }, $t = async (t) => {
114
+ const e = await ht(t);
115
+ if (e)
116
+ return e.type;
100
117
  };
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"], st = (t = []) => new RegExp(`\\.(${[...tt, ...t].join("|")})\\.`), E = (t, s = []) => st(s).test(t), et = 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],
118
+ let O;
119
+ const Q = async (t) => {
120
+ if (O) return O;
121
+ const e = await $t(t);
122
+ return e === "module" ? O = "esm" : (e === "commonjs" || import.meta.url.endsWith(".cjs")) && (O = "cjs"), O || "esm";
123
+ }, K = pt({
124
+ level: "debug",
125
+ format: _.combine(_.colorize(), _.cli()),
126
+ transports: [new ut.Console({})]
127
+ }), W = {
128
+ externalModules: []
129
+ }, v = (t) => {
130
+ if (W.externalModules.length > 0) return W.externalModules;
131
+ const e = f(t, "salty.config.ts"), n = J(e, "utf8").match(/externalModules:\s?\[(.*)\]/);
132
+ if (!n) return [];
133
+ const o = n[1].split(",").map((i) => i.replace(/['"`]/g, "").trim());
134
+ return W.externalModules = o, o;
135
+ }, R = (t) => f(t, "./saltygen"), bt = ["salty", "css", "styles", "styled"], jt = (t = []) => new RegExp(`\\.(${[...bt, ...t].join("|")})\\.`), N = (t, e = []) => jt(e).test(t), wt = async (t) => {
136
+ const e = R(t), s = f(t, "salty.config.ts"), n = f(e, "salty.config.js"), o = await Q(t), i = v(t);
137
+ await L.build({
138
+ entryPoints: [s],
110
139
  minify: !0,
111
140
  treeShaking: !0,
112
141
  bundle: !0,
113
142
  outfile: n,
114
- format: "esm",
115
- external: ["react"]
143
+ format: o,
144
+ external: i
116
145
  });
117
- const r = Date.now(), { config: g } = await import(`${n}?t=${r}`);
118
- return g;
119
- }, K = async (t) => {
120
- const s = await et(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
- }, M = async (t, s) => {
142
- const e = R(t), n = u(s, "js", e + ".js");
143
- await I.build({
144
- entryPoints: [t],
145
- minify: !0,
146
+ const g = Date.now(), { config: a } = await import(`${n}?t=${g}`);
147
+ return a;
148
+ }, tt = async (t) => {
149
+ const e = await wt(t), s = /* @__PURE__ */ new Set(), n = (c, p = []) => c ? Object.entries(c).flatMap(([y, m]) => {
150
+ if (!m) return;
151
+ if (typeof m == "object") return n(m, [...p, y]);
152
+ const x = [...p, y].join(".");
153
+ s.add(`"${x}"`);
154
+ const w = [...p.map(V), V(y)].join("-"), { result: S } = q(m);
155
+ return `--${w}: ${S};`;
156
+ }) : [], o = (c) => c ? Object.entries(c).flatMap(([p, y]) => {
157
+ const m = n(y);
158
+ return p === "base" ? m.join("") : `${p} { ${m.join("")} }`;
159
+ }) : [], i = (c) => c ? Object.entries(c).flatMap(([p, y]) => Object.entries(y).flatMap(([m, x]) => {
160
+ const w = n(x, [p]), S = `.${p}-${m}, [data-${p}="${m}"]`, P = w.join("");
161
+ return `${S} { ${P} }`;
162
+ })) : [], g = n(e.variables), a = o(e.responsiveVariables), h = i(e.conditionalVariables), r = R(t), u = f(r, "css/variables.css"), $ = `:root { ${g.join("")} ${a.join("")} } ${h.join("")}`;
163
+ E(u, $);
164
+ const F = f(r, "css/global.css"), C = D(e.global, "");
165
+ E(F, C);
166
+ const l = f(r, "css/templates.css"), k = U(e.templates), T = mt(e.templates);
167
+ E(l, k);
168
+ const d = f(r, "types/css-tokens.d.ts"), j = `
169
+ // Variable types
170
+ type VariableTokens = ${[...s].join("|")};
171
+ type PropertyValueToken = \`{\${VariableTokens}}\`;
172
+
173
+ // Template types
174
+ type TemplateTokens = {
175
+ ${Object.entries(T).map(([c, p]) => `${c}?: ${p}`).join(`
176
+ `)}
177
+ }
178
+ `;
179
+ E(d, j);
180
+ }, Z = async (t, e, s) => {
181
+ const n = I(e), o = f(s, "./temp");
182
+ B(o) || A(o);
183
+ const i = it(e);
184
+ let g = J(e, "utf8");
185
+ g = g.replace(/styled\([^"'`{,]+,/g, "styled('div',");
186
+ const a = f(s, "js", n + ".js"), h = v(t), r = await Q(t);
187
+ await L.build({
188
+ stdin: {
189
+ contents: g,
190
+ sourcefile: i.base,
191
+ resolveDir: i.dir,
192
+ loader: "ts"
193
+ },
194
+ minify: !1,
146
195
  treeShaking: !0,
147
196
  bundle: !0,
148
- outfile: n,
149
- format: "esm",
150
- target: ["es2022"],
197
+ outfile: a,
198
+ format: r,
199
+ target: ["node20"],
151
200
  keepNames: !0,
152
- external: ["react"]
201
+ external: h,
202
+ packages: "external"
153
203
  });
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);
204
+ const u = Date.now();
205
+ return await import(`${a}?t=${u}`);
206
+ }, z = async (t) => {
207
+ const e = R(t), s = f(e, "salty.config.js"), { config: n } = await import(s);
158
208
  return n;
159
- }, nt = async (t) => {
209
+ }, et = () => {
210
+ try {
211
+ return process.env.NODE_ENV === "production";
212
+ } catch {
213
+ return !1;
214
+ }
215
+ }, St = async (t, e = et()) => {
160
216
  try {
161
- const s = [], e = [], n = T(t), r = u(n, "index.css");
217
+ e ? K.info("Generating CSS in production mode! 🔥") : K.info("Generating CSS in development mode! 🚀");
218
+ const s = [], n = [], o = R(t), i = f(o, "index.css");
162
219
  (() => {
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 M(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);
220
+ B(o) && rt("rm -rf " + o), A(o), A(f(o, "css")), A(f(o, "types"));
221
+ })(), await tt(t);
222
+ const a = await z(t);
223
+ async function h(l, k) {
224
+ const T = ["node_modules", "saltygen"], d = ct(l);
225
+ if (d.isDirectory()) {
226
+ const b = at(l);
227
+ if (T.some((c) => l.includes(c))) return;
228
+ await Promise.all(b.map((c) => h(f(l, c), f(k, c))));
229
+ } else if (d.isFile() && N(l)) {
230
+ const j = await Z(t, l, o), c = [];
231
+ Object.entries(j).forEach(([x, w]) => {
232
+ if (w.isKeyframes && w.css) {
233
+ const G = `${w.animationName}.css`, nt = `css/${G}`, ot = f(o, nt);
234
+ s.push(G), E(ot, w.css);
177
235
  return;
178
236
  }
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);
237
+ if (!w.generator) return;
238
+ const S = w.generator._withBuildContext({
239
+ name: x,
240
+ config: a,
241
+ prod: e
242
+ }), P = `${S.hash}-${S.priority}.css`;
243
+ n[S.priority] || (n[S.priority] = []), n[S.priority].push(P), c.push(P);
244
+ const M = `css/${P}`, st = f(o, M);
245
+ E(st, S.css);
187
246
  });
188
- const d = C.map((c) => `@import url('./${c}');`).join(`
189
- `), S = R(p, 6), y = u(n, `css/${S}.css`);
190
- x(y, d);
247
+ const p = c.map((x) => `@import url('./${x}');`).join(`
248
+ `), y = I(l, 6), m = f(o, `css/${y}.css`);
249
+ E(m, p);
191
250
  }
192
251
  }
193
- await a(t, n);
194
- const f = s.map((p) => `@import url('./css/${p}');`).join(`
252
+ await h(t, o);
253
+ const r = s.map((l) => `@import url('./css/${l}');`).join(`
195
254
  `);
196
- let i = `@layer l0, l1, l2, l3, l4, l5, l6, l7, l8;
255
+ let C = `@layer l0, l1, l2, l3, l4, l5, l6, l7, l8;
197
256
 
198
- ${["@import url('./css/variables.css');", "@import url('./css/global.css');", "@import url('./css/templates.css');"].join(`
257
+ ${["variables.css", "global.css", "templates.css"].filter((l) => {
258
+ try {
259
+ return J(f(o, "css", l), "utf8").length > 0;
260
+ } catch {
261
+ return !1;
262
+ }
263
+ }).map((l) => `@import url('./css/${l}');`).join(`
199
264
  `)}
200
- ${f}`;
201
- if ($.importStrategy !== "component") {
202
- const p = e.flat().map((h) => `@import url('./css/${h}');`).join(`
265
+ ${r}`;
266
+ if (a.importStrategy !== "component") {
267
+ const l = n.flat().map((k) => `@import url('./css/${k}');`).join(`
203
268
  `);
204
- i += p;
269
+ C += l;
205
270
  }
206
- x(r, i);
271
+ E(i, C);
207
272
  } catch (s) {
208
273
  console.error(s);
209
274
  }
210
- }, rt = async (t, s) => {
275
+ }, Ft = async (t, e) => {
211
276
  try {
212
- const e = [], n = u(t, "./saltygen"), r = u(n, "index.css");
213
- if (E(s)) {
214
- const $ = await _(t), a = await M(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);
277
+ const s = [], n = f(t, "./saltygen"), o = f(n, "index.css");
278
+ if (N(e)) {
279
+ const g = await z(t), a = await Z(t, e, n);
280
+ Object.entries(a).forEach(([F, C]) => {
281
+ if (!C.generator) return;
282
+ const l = C.generator._withBuildContext({
283
+ name: F,
284
+ config: g
285
+ }), k = `${l.hash}-${l.priority}.css`, T = `css/${k}`, d = f(n, T);
286
+ s.push(k), E(d, l.css);
222
287
  });
223
- const f = B(r, "utf8").split(`
224
- `), o = e.map((h) => `@import url('../saltygen/css/${h}');`), p = [.../* @__PURE__ */ new Set([...f, ...o])].join(`
288
+ const h = J(o, "utf8").split(`
289
+ `), r = s.map((F) => `@import url('../saltygen/css/${F}');`), $ = [.../* @__PURE__ */ new Set([...h, ...r])].join(`
225
290
  `);
226
- x(r, p);
291
+ E(o, $);
227
292
  }
228
- } catch (e) {
229
- console.error(e);
293
+ } catch (s) {
294
+ console.error(s);
230
295
  }
231
- }, ot = async (t, s) => {
296
+ }, Ct = async (t, e, s = et()) => {
232
297
  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 M(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;
298
+ const n = f(t, "./saltygen");
299
+ if (N(e)) {
300
+ const i = J(e, "utf8");
301
+ i.replace(/^(?!export\s)const\s.*/gm, ($) => `export ${$}`) !== i && await ft(e, i);
302
+ const a = await z(t), h = await Z(t, e, n);
303
+ let r = i;
304
+ Object.entries(h).forEach(([$, F]) => {
305
+ var P;
306
+ if (F.isKeyframes || !F.generator) return;
307
+ const C = F.generator._withBuildContext({
308
+ name: $,
309
+ config: a,
310
+ prod: s
311
+ }), l = new RegExp(`\\s${$}[=\\s]+[^()]+styled\\(([^,]+),`, "g").exec(i);
312
+ if (!l) return console.error("Could not find the original declaration");
313
+ const k = (P = l.at(1)) == null ? void 0 : P.trim(), T = new RegExp(`\\s${$}[=\\s]+styled\\(`, "g").exec(r);
314
+ if (!T) return console.error("Could not find the original declaration");
315
+ const { index: d } = T;
316
+ let b = !1;
317
+ const j = setTimeout(() => b = !0, 5e3);
318
+ let c = 0, p = !1, y = 0;
319
+ for (; !p && !b; ) {
320
+ const M = r[d + c];
321
+ M === "(" && y++, M === ")" && y--, y === 0 && M === ")" && (p = !0), c > r.length && (b = !0), c++;
244
322
  }
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);
323
+ if (!b) clearTimeout(j);
324
+ else throw new Error("Failed to find the end of the styled call and timed out");
325
+ const m = d + c, x = r.slice(d, m), w = r, S = ` ${$} = styled(${k}, "${C.classNames}", ${JSON.stringify(C.props)});`;
326
+ r = r.replace(x, S), w === r && console.error("Minimize file failed to change content", { name: $, tagName: k });
256
327
  });
257
- const o = R(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;
328
+ const u = I(e, 6);
329
+ return a.importStrategy === "component" && (r = `import '../../saltygen/css/${u}.css';
330
+ ${r}`), r = r.replace("{ styled }", "{ styledClient as styled }"), r = r.replace("@salty-css/react/styled", "@salty-css/react/styled-client"), r;
260
331
  }
261
- } catch (e) {
262
- console.error(e);
332
+ } catch (n) {
333
+ console.error("Error in minimizeFile:", n);
263
334
  }
264
- }, ft = (t) => ({
335
+ }, Dt = (t) => ({
265
336
  name: "stylegen",
266
- buildStart: () => nt(t),
267
- load: async (s) => {
268
- if (E(s))
269
- return await ot(t, s);
337
+ buildStart: () => St(t),
338
+ load: async (e) => {
339
+ if (N(e))
340
+ return await Ct(t, e);
270
341
  },
271
342
  watchChange: {
272
- handler: async (s) => {
273
- E(s) && await rt(t, s), s.includes("salty-config") && await K(t);
343
+ handler: async (e) => {
344
+ N(e) && await Ft(t, e), e.includes("salty.config") && await tt(t);
274
345
  }
275
346
  }
276
347
  });
277
348
  export {
278
- ft as saltyPlugin
349
+ Dt as default,
350
+ Dt as saltyPlugin
279
351
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@salty-css/vite",
3
- "version": "0.0.1-alpha.11",
3
+ "version": "0.0.1-alpha.111",
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
  },
@@ -27,5 +32,8 @@
27
32
  "import": "./index.js",
28
33
  "require": "./index.cjs"
29
34
  }
35
+ },
36
+ "dependencies": {
37
+ "@salty-css/core": "^0.0.1-alpha.111"
30
38
  }
31
39
  }