@salty-css/vite 0.0.1-alpha.21 → 0.0.1-alpha.211

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 +143 -26
  2. package/index.cjs +40 -16
  3. package/index.d.ts +3 -8
  4. package/index.js +631 -233
  5. package/package.json +9 -4
package/README.md CHANGED
@@ -1,15 +1,132 @@
1
- # Salty Css
1
+ ![Salty CSS Banner](https://salty-css.dev/assets/banners/dvd.svg)
2
2
 
3
- ## Basic usage example with Button
3
+ # Salty CSS - CSS-in-JS library that is kinda sweet
4
4
 
5
- ### Initial requirements
5
+ Is there anything saltier than CSS in frontend web development? Salty CSS is built to provide better developer experience for developers looking for performant and feature rich CSS-in-JS solutions.
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
+ ## Features
11
8
 
12
- ### Code examples
9
+ - Build time compilation to achieve awesome runtime performance and minimal size
10
+ - Next.js, React Server Components, Vite and Webpack support
11
+ - Type safety with out of the box TypeScript and ESLint plugin
12
+ - Advanced CSS variables configuration to allow smooth token usage
13
+ - Style templates to create reusable styles easily
14
+
15
+ ## Get started
16
+
17
+ Fastest way to get started with any framework is `npx salty-css init [directory]` command
18
+
19
+ - Next.js → [Next.js guide](#nextjs) + [Next.js example app](https://github.com/margarita-form/salty-css-website)
20
+ - React + Vite → [React + Vite guide](#react--vite) + [React example code](#code-examples)
21
+ - React + Webpack → Guide coming soon
22
+
23
+ ## Useful commands
24
+
25
+ - Create component: `npx salty-css generate [filePath]`
26
+ - Build: `npx salty-css build [directory]`
27
+ - Update Salty CSS packages: `npx salty-css up`
28
+
29
+ ## Salty CSS styled function
30
+
31
+ ```ts
32
+ // components/wrapper.css.ts
33
+ import { styled } from '@salty-css/react/styled';
34
+
35
+ // Define a component with styled function. First argument is the component name or existing component to extend and second argument is the object containing the styles and other options
36
+ export const Component = styled('div', {
37
+ className: 'wrapper', // Define custom class name that will be included for this component
38
+ element: 'section', // Define the html element that will be rendered for this component, overrides the first 'div' argument
39
+ base: {
40
+ // 👉 Add your CSS-in-JS base styles here! 👈
41
+ },
42
+ variants: {
43
+ // Define conditional styles that will be applied to the component based on the variant prop values
44
+ },
45
+ compoundVariants: [
46
+ // Define conditional styles that will be applied to the component based on the combination of variant prop values
47
+ ],
48
+ defaultVariants: {
49
+ // Set default variant prop values
50
+ },
51
+ defaultProps: {
52
+ // Add additional default props for the component (eg, id and other html element attributes)
53
+ },
54
+ passProps: true, // Pass variant props to the rendered element / parent component (default: false)
55
+ });
56
+ ```
57
+
58
+ ## Salty CSS CLI
59
+
60
+ In your existing repository you can use `npx salty-css [command]` to initialize a project, generate components, update related packages and build required files.
61
+
62
+ - Initialize project → `npx salty-css init [directory]` - Installs required packages, detects framework in use and creates project files to the provided directory. Directory can be left blank if you want files to be created to the current directory.
63
+ - Generate component → `npx salty-css update [version]` - Update @salty-css packages in your repository. Default version is "latest". Additional options like `--dir`, `--tag`, `--name` and `--className` are also supported.
64
+ - Build files → `npx salty-css build [directory]` - Compile Salty CSS related files in your project. This should not be needed if you are using tools like Next.js or Vite
65
+
66
+ ## Usage
67
+
68
+ ### Next.js
69
+
70
+ ![salty-next](https://github.com/user-attachments/assets/2cf6a93f-cdd5-4f5f-ab2e-3bc8bcfb83e8)
71
+
72
+ Salty CSS provides Next.js App & Pages router support with full React Server Components support.
73
+
74
+ ### Add Salty CSS to Next.js
75
+
76
+ 1. In your existing Next.js repository you can run `npx salty-css init` to automatically configure Salty CSS.
77
+ 2. Create your first Salty CSS component with `npx salty-css generate [filePath]` (e.g. src/custom-wrapper)
78
+ 3. Import your component for example to `page.tsx` and see it working!
79
+
80
+ And note: steps 2 & 3 are just to show how get new components up and running, step 1 does all of the important stuff 🤯
81
+
82
+ #### Manual configuration
83
+
84
+ 1. For Next.js support install `npm i @salty-css/next @salty-css/core @salty-css/react`
85
+ 2. Create `salty.config.ts` to your app directory
86
+ 3. Add Salty CSS plugin to next.js config
87
+
88
+ - **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);`
89
+ - **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);`
90
+
91
+ 4. Make sure that `salty.config.ts` and `next.config.ts` are in the same folder!
92
+ 5. Build `saltygen` directory by running your app once or with cli `npx salty-css build [directory]`
93
+ 6. Import global styles from `saltygen/index.css` to some global css file with `@import 'insert_path_to_index_css';`.
94
+
95
+ [Check out Next.js demo project](https://github.com/margarita-form/salty-css-website) or [react example code](#code-examples)
96
+
97
+ ---
98
+
99
+ ### React + Vite
100
+
101
+ ![salty-vite-react](https://github.com/user-attachments/assets/12ec5b6a-0dcc-48fa-afc1-d337fc8f800c)
102
+
103
+ ### Add Salty CSS to your React + Vite app
104
+
105
+ 1. In your existing Vite repository you can run `npx salty-css init` to automatically configure Salty CSS.
106
+ 2. Create your first Salty CSS component with `npx salty-css generate [filePath]` (e.g. src/custom-wrapper)
107
+ 3. Import your component for example to `main.tsx` and see it working!
108
+
109
+ And note: steps 2 & 3 are just to show how get new components up and running, step 1 does all of the important stuff 🤯
110
+
111
+ #### Manual configuration
112
+
113
+ 1. For Vite support install `npm i @salty-css/vite @salty-css/core`
114
+ 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
115
+ 3. Make sure that `salty.config.ts` and `vite.config.ts` are in the same folder!
116
+ 4. Build `saltygen` directory by running your app once or with cli `npx salty-css build [directory]`
117
+ 5. Import global styles from `saltygen/index.css` to some global css file with `@import 'insert_path_to_index_css';`.
118
+
119
+ [Check out react example code](#code-examples)
120
+
121
+ ---
122
+
123
+ ### Create components
124
+
125
+ 1. Create salty components with styled only inside files that end with `.css.ts`, `.salty.ts` `.styled.ts` or `.styles.ts`
126
+
127
+ ## Code examples
128
+
129
+ ### Basic usage example with Button
13
130
 
14
131
  **Salty config**
15
132
 
@@ -31,23 +148,6 @@ export const config = defineConfig({
31
148
  });
32
149
  ```
33
150
 
34
- **Your React component file**
35
-
36
- ```tsx
37
- import { Wrapper } from '../components/wrapper/wrapper.css';
38
- import { Button } from '../components/button/button.css';
39
-
40
- export const IndexPage = () => {
41
- return (
42
- <Wrapper>
43
- <Button variant="solid" onClick={() => alert('It is a button.')}>
44
- Outlined
45
- </Button>
46
- </Wrapper>
47
- );
48
- };
49
- ```
50
-
51
151
  **Wrapper** (`components/wrapper/wrapper.css.ts`)
52
152
 
53
153
  ```tsx
@@ -72,7 +172,7 @@ export const Button = styled('button', {
72
172
  padding: `0.6em 1.2em`,
73
173
  border: '1px solid currentColor',
74
174
  background: 'transparent',
75
- color: 'currentColor/40',
175
+ color: 'currentColor',
76
176
  cursor: 'pointer',
77
177
  transition: '200ms',
78
178
  textDecoration: 'none',
@@ -108,4 +208,21 @@ export const Button = styled('button', {
108
208
  });
109
209
  ```
110
210
 
211
+ **Your React component file**
212
+
213
+ ```tsx
214
+ import { Wrapper } from '../components/wrapper/wrapper.css';
215
+ import { Button } from '../components/button/button.css';
216
+
217
+ export const IndexPage = () => {
218
+ return (
219
+ <Wrapper>
220
+ <Button variant="solid" onClick={() => alert('It is a button.')}>
221
+ Outlined
222
+ </Button>
223
+ </Wrapper>
224
+ );
225
+ };
226
+ ```
227
+
111
228
  More examples coming soon
package/index.cjs CHANGED
@@ -1,18 +1,42 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const W=require("esbuild"),z=require("child_process"),u=require("path"),m=require("fs"),J=require("fs/promises");function K(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 R=K(W),M=t=>String.fromCharCode(t+(t>25?39:97)),G=(t,s)=>{let e="",n;for(n=Math.abs(t);n>52;n=n/52|0)e=M(n%52)+e;return e=M(n%52)+e,e.length<s?e=e.padStart(s,"a"):e.length>s&&(e=e.slice(-s)),e},L=(t,s)=>{let e=s.length;for(;e;)t=t*33^s.charCodeAt(--e);return t},E=(t,s=3)=>{const e=L(5381,JSON.stringify(t))>>>0;return G(e,s)};function N(t){return t?typeof t!="string"?N(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 U=(t,s)=>{if(typeof t!="string")return{result:t};if(!s)return{result:t};const e=[];return Object.values(s).forEach(n=>{const{pattern:r,transform:y}=n;t=t.replace(r,$=>{const{value:a,css:f}=y($);return f&&e.push(f),a})}),{result:t,additionalCss:e}},q=t=>typeof t!="string"?{result:t}:/\{[^{}]+\}/g.test(t)?{result:t.replace(/\{([^{}]+)\}/g,(...n)=>`var(--${N(n[1].replaceAll(".","-"))})`)}:{result:t},D=(t,s,e,n)=>{if(!t)return"";const r=[],y=Object.entries(t).reduce((a,[f,o])=>{const i=f.trim();if(typeof o=="function"&&(o=o()),typeof o=="object"){if(!o)return a;if(i==="variants")return Object.entries(o).forEach(([g,c])=>{c&&Object.entries(c).forEach(([d,l])=>{if(!l)return;const F=`${s}.${g}-${d}`,P=D(l,F);r.push(P)})}),a;if(i==="defaultVariants")return a;if(i==="compoundVariants")return o.forEach(g=>{const{css:c,...d}=g,l=Object.entries(d).reduce((P,[x,k])=>`${P}.${x}-${k}`,s),F=D(c,l);r.push(F)}),a;if(i.startsWith("@")){const g=D(o,s),c=`${i} {
2
- ${g.replace(`
3
- `,`
4
- `)}
5
- }`;return r.push(c),a}const b=f.includes("&")?i.replace("&",s):i.startsWith(":")?`${s}${i}`:`${s} ${i}`,C=D(o,b);return r.push(C),a}const p=i.startsWith("-")?i:N(i),h=(b,C=";")=>a=`${a}${b}${C}`,j=b=>h(`${p}:${b}`);if(typeof o=="number")return j(o);if(typeof o!="string")if("toString"in o)o=o.toString();else return a;const{modifiers:S}={},O=function*(){yield q(o),yield U(o,S)}();for(const{result:b,additionalCss:C=[]}of O)o=b,C.forEach(g=>{const c=D(g,"");h(c,"")});return j(o)},"");if(!y)return r.join(`
6
- `);if(!s)return y;let $="";return $=`${s} { ${y} }`,[$,...r].join(`
7
- `)},Z=(t,s=[])=>{if(!t)return"";const e=[],n={};if(Object.entries(t).forEach(([r,y])=>{if(typeof y=="object"){if(!y)return;const $=r.trim(),a=Z(y,[...s,$]);e.push(a)}else n[r]=y}),Object.keys(n).length){const r=s.map(N).join("-"),y=D(n,`.${r}`);e.push(y)}return e.join(`
8
- `)},T=t=>u.join(t,"./saltygen"),X=["salty","css","styles","styled"],Y=(t=[])=>new RegExp(`\\.(${[...X,...t].join("|")})\\.`),V=(t,s=[])=>Y(s).test(t),Q=async t=>{const s=T(t),e=u.join(t,"salty.config.ts"),n=u.join(s,"salty.config.js");await R.build({entryPoints:[e],minify:!0,treeShaking:!0,bundle:!0,outfile:n,format:"esm",external:["react"]});const r=Date.now(),{config:y}=await import(`${n}?t=${r}`);return y},I=async t=>{const s=await Q(t),e=new Set,n=(g,c=[])=>g?Object.entries(g).flatMap(([d,l])=>{if(!l)return;if(typeof l=="object")return n(l,[...c,d]);const F=[...c,d].join(".");e.add(`"${F}"`);const P=[...c.map(N),N(d)].join("-"),{result:x}=q(l);return`--${P}: ${x};`}):[],r=g=>g?Object.entries(g).flatMap(([c,d])=>{const l=n(d);return c==="base"?l.join(""):`${c} { ${l.join("")} }`}):[],y=g=>g?Object.entries(g).flatMap(([c,d])=>Object.entries(d).flatMap(([l,F])=>{const P=n(F,[c]),x=`.${c}-${l}, [data-${c}="${l}"]`,k=P.join("");return`${x} { ${k} }`})):[],$=n(s.variables),a=r(s.responsiveVariables),f=y(s.conditionalVariables),o=T(t),i=u.join(o,"css/variables.css"),p=`:root { ${$.join("")} ${a.join("")} } ${f.join("")}`;m.writeFileSync(i,p);const h=u.join(o,"types/css-tokens.d.ts"),S=`type VariableTokens = ${[...e].join("|")}; type PropertyValueToken = \`{\${VariableTokens}}\``;m.writeFileSync(h,S);const w=u.join(o,"css/global.css"),O=D(s.global,"");m.writeFileSync(w,O);const b=u.join(o,"css/templates.css"),C=Z(s.templates);m.writeFileSync(b,C)},_=async(t,s)=>{const e=E(t),n=u.join(s,"js",e+".js");await R.build({entryPoints:[t],minify:!0,treeShaking:!0,bundle:!0,outfile:n,format:"esm",target:["es2022"],keepNames:!0,external:["react"]});const r=Date.now();return await import(`${n}?t=${r}`)},A=async t=>{const s=T(t),e=u.join(s,"salty.config.js"),{config:n}=await import(e);return n},v=async t=>{try{const s=[],e=[],n=T(t),r=u.join(n,"index.css");(()=>{m.existsSync(n)&&z.execSync("rm -rf "+n),m.mkdirSync(n),m.mkdirSync(u.join(n,"css")),m.mkdirSync(u.join(n,"types"))})(),await I(t);const $=await A(t);async function a(p,h){const j=m.statSync(p);if(j.isDirectory()){const S=m.readdirSync(p);await Promise.all(S.map(w=>a(u.join(p,w),u.join(h,w))))}else if(j.isFile()&&V(p)){const w=await _(p,n),O=[];Object.entries(w).forEach(([c,d])=>{if(d.isKeyframes&&d.css){const k=`${d.animationName}.css`,B=`css/${k}`,H=u.join(n,B);s.push(k),m.writeFileSync(H,d.css);return}if(!d.generator)return;const l=d.generator._withBuildContext({name:c,config:$}),F=`${l.hash}-${l.priority}.css`;e[l.priority]||(e[l.priority]=[]),e[l.priority].push(F),O.push(F);const P=`css/${F}`,x=u.join(n,P);m.writeFileSync(x,l.css)});const b=O.map(c=>`@import url('./${c}');`).join(`
9
- `),C=E(p,6),g=u.join(n,`css/${C}.css`);m.writeFileSync(g,b)}}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;
1
+ "use strict";var Tt=Object.defineProperty;var Dt=(e,t,s)=>t in e?Tt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var tt=(e,t,s)=>Dt(e,typeof t!="symbol"?t+"":t,s);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const Et=require("esbuild"),Ot=require("child_process"),l=require("path"),d=require("fs"),st=require("fs/promises"),G=require("winston");var it=typeof document<"u"?document.currentScript:null;function Mt(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const s in e)if(s!=="default"){const n=Object.getOwnPropertyDescriptor(e,s);Object.defineProperty(t,s,n.get?n:{enumerable:!0,get:()=>e[s]})}}return t.default=e,Object.freeze(t)}const gt=Mt(Et),mt=e=>String.fromCharCode(e+(e>25?39:97)),Rt=(e,t)=>{let s="",n;for(n=Math.abs(e);n>52;n=n/52|0)s=mt(n%52)+s;return s=mt(n%52)+s,s.length<t?s=s.padStart(t,"a"):s.length>t&&(s=s.slice(-t)),s},Vt=(e,t)=>{let s=t.length;for(;s;)e=e*33^t.charCodeAt(--s);return e},v=(e,t=5)=>{const s=Vt(5381,JSON.stringify(e))>>>0;return Rt(s,t)};function V(e){return e?typeof e!="string"?V(String(e)):e.replace(/[\s.]/g,"-").replace(/[A-Z](?:(?=[^A-Z])|[A-Z]*(?=[A-Z][^A-Z]|$))/g,(t,s)=>(s>0?"-":"")+t.toLowerCase()):""}const At=e=>t=>{if(typeof t!="string"||!e)return;let s=t;const n=[];return Object.values(e).forEach(o=>{const{pattern:r,transform:i}=o;s=s.replace(r,w=>{const{value:$,css:f}=i(w);return f&&n.push(f),$})}),{transformed:s,additionalCss:n}},wt=e=>t=>typeof t!="string"||!/\{[^{}]+\}/g.test(t)?void 0:{transformed:t.replace(/\{([^{}]+)\}/g,(...o)=>`var(--${V(o[1].replaceAll(".","-"))})`)},Jt=wt(),vt=["top","right","bottom","left","min-width",/.*width.*/,/^[^line]*height.*/,/padding.*/,/margin.*/,/border.*/,/inset.*/,/.*radius.*/,/.*spacing.*/,/.*gap.*/,/.*indent.*/,/.*offset.*/,/.*size.*/,/.*thickness.*/,/.*font-size.*/],zt=(e,t,s)=>vt.some(o=>typeof o=="string"?o===e:o.test(e))?`${t}px`:`${t}`,Wt=["Webkit","Moz","ms","O"],It=e=>e.startsWith("-")?e:Wt.some(t=>e.startsWith(t))?`-${V(e)}`:V(e),et=async(e,t="",s,n=!1)=>{if(!e)throw new Error("No styles provided to parseStyles function!");const o=new Set,i=Object.entries(e).map(async([y,a])=>{const m=y.trim(),x=It(m),P=(N,M=";")=>`${x}:${N}${M}`;if(typeof a=="function"&&(a=a({scope:t,config:s})),a instanceof Promise&&(a=await a),typeof a=="object"){if(!a)return;if(a.isColor)return P(a.toString());if(m==="defaultVariants")return;if(m==="variants"){const j=Object.entries(a);for(const[D,c]of j){if(!c)return;const h=Object.entries(c);for(const[F,u]of h){if(!u)return;const S=`${t}.${D}-${F}`;(await et(u,S,s)).forEach(E=>o.add(E))}}return}if(m==="compoundVariants"){for(const j of a){const{css:D,...c}=j,h=Object.entries(c).reduce((u,[S,k])=>`${u}.${S}-${k}`,t);(await et(D,h,s)).forEach(u=>o.add(u))}return}if(m.startsWith("@")){const j=m,D=await K(a,t,s),c=`${j} { ${D} }`;o.add(c);return}const N=y.includes("&")?m.replace("&",t):m.startsWith(":")?`${t}${m}`:`${t} ${m}`;(await et(a,N,s)).forEach(j=>o.add(j));return}if(typeof a=="number"){const N=zt(x,a);return P(N)}if(typeof a!="string")if("toString"in a)a=a.toString();else throw new Error(`Invalid value type for property ${x}`);return P(a)}),{modifiers:w}={},$=[wt(),At(w)],p=(await Promise.all(i).then(y=>Promise.all(y.map(a=>$.reduce(async(m,x)=>{const P=await m;if(!P)return P;const R=await x(P);if(!R)return P;const{transformed:N,additionalCss:M}=R;let j="";if(M)for(const D of M)j+=await K(D,"");return`${j}${N}`},Promise.resolve(a)))))).filter(y=>y!==void 0).join(`
2
+ `);if(!p.trim())return Array.from(o);const b=t?`${t} {
3
+ ${p}
4
+ }`:p;return o.has(b)?Array.from(o):[b,...o]},K=async(e,t,s,n=!1)=>(await et(e,t,s,n)).join(`
5
+ `),$t=async(e,t=[])=>{if(!e)return"";const s=[],n={};for(const[o,r]of Object.entries(e))if(typeof r!="function")if(r&&typeof r=="object"){const i=o.trim(),w=await $t(r,[...t,i]);s.push(w)}else n[o]=r;if(Object.keys(n).length){const o=t.map(V).join("-"),r="t_"+v(o,4),i=await K(n,`.${o}, .${r}`);s.push(i)}return s.join(`
6
+ `)},Zt=e=>e?Object.entries(e).reduce((t,[s,n])=>(typeof n=="function"?t[s]="any":typeof n=="object"&&(t[s]=bt(n).map(o=>`"${o}"`).join(" | ")),t),{}):{},bt=(e,t="",s=new Set)=>e?(Object.entries(e).forEach(([n,o])=>{const r=t?`${t}.${n}`:n;return typeof o=="object"?bt(o,r,s):s.add(t)}),[...s]):[],St=e=>{if(!e||e==="/")throw new Error("Could not find package.json file");const t=l.join(e,"package.json");return d.existsSync(t)?t:St(l.join(e,".."))},qt=async e=>{const t=St(e);return await st.readFile(t,"utf-8").then(JSON.parse).catch(()=>{})},Ht=async e=>{const t=await qt(e);if(t)return t.type};let W;const jt=async e=>{if(W)return W;const t=await Ht(e);return t==="module"?W="esm":(t==="commonjs"||(typeof document>"u"?require("url").pathToFileURL(__filename).href:it&&it.tagName.toUpperCase()==="SCRIPT"&&it.src||new URL("index.cjs",document.baseURI).href).endsWith(".cjs"))&&(W="cjs"),W||"esm"},at=G.createLogger({level:"debug",format:G.format.combine(G.format.colorize(),G.format.cli()),transports:[new G.transports.Console({})]});function Ft(e){return e?typeof e!="string"?Ft(String(e)):e.replace(/[\s-]/g,".").replace(/[A-Z](?:(?=[^A-Z])|[A-Z]*(?=[A-Z][^A-Z]|$))/g,(t,s)=>(s>0?".":"")+t.toLowerCase()):""}const Lt={"*, *::before, *::after":{boxSizing:"border-box"},"*":{margin:0},html:{lineHeight:1.15,textSizeAdjust:"100%",WebkitFontSmoothing:"antialiased"},"img, picture, video, canvas, svg":{display:"block",maxWidth:"100%"},"p, h1, h2, h3, h4, h5, h6":{overflowWrap:"break-word"},p:{textWrap:"pretty"},"h1, h2, h3, h4, h5, h6":{textWrap:"balance"},a:{color:"currentColor"},button:{lineHeight:"1em",color:"currentColor"},"input, optgroup, select, textarea":{fontFamily:"inherit",fontSize:"100%",lineHeight:"1.15em"}},I=(...e)=>e.flat().reduce((t,s)=>s!=null&&s._current?{...t,...s._current}:{...t,...s},{}),Bt=(...e)=>e.flat().reduce((t,s)=>({...t,...s._children}),{});class Gt{constructor(t){tt(this,"_path");this.params=t}get _current(){return this.params.template}get isDefineTemplate(){return!0}_setPath(t){return this._path=t,this}}class Kt{constructor(t){tt(this,"_path");tt(this,"templates",[]);this.params=t,Object.entries(t).forEach(([s,n])=>{this.templates.push(new Gt({name:s,template:n}))})}get _current(){return this.params}get _children(){return Object.fromEntries(this.templates.map(t=>[t.params.name,t]))}get isDefineTemplates(){return!0}_setPath(t){return this._path=t,this.templates.forEach(s=>s._setPath(t)),this}}const Ut=e=>new Kt(e),J={externalModules:[],rcFile:void 0,destDir:void 0},Ct=e=>{if(J.externalModules.length>0)return J.externalModules;const s=d.readFileSync(e,"utf8").match(/externalModules:\s?\[(.*)\]/);if(!s)return[];const n=s[1].split(",").map(o=>o.replace(/['"`]/g,"").trim());return J.externalModules=n,n},z=async e=>{if(J.destDir)return J.destDir;const t=await ct(e),s=l.join(e,(t==null?void 0:t.saltygenDir)||"saltygen");return J.destDir=s,s},Pt=["salty","css","styles","styled"],Qt=(e=[])=>new RegExp(`\\.(${[...Pt,...e].join("|")})\\.`),Z=(e,t=[])=>Qt(t).test(e),_t=async e=>{if(J.rcFile)return J.rcFile;if(e==="/")throw new Error("Could not find .saltyrc.json file");const t=l.join(e,".saltyrc.json"),s=await st.readFile(t,"utf-8").then(JSON.parse).catch(()=>{});return s?(J.rcFile=s,s):_t(l.join(e,".."))},ct=async e=>{var n,o;const t=await _t(e),s=(n=t.projects)==null?void 0:n.find(r=>e.endsWith(r.dir||""));return s||((o=t.projects)==null?void 0:o.find(r=>r.dir===t.defaultProject))},Xt=async e=>{const t=await ct(e),s=await z(e),n=l.join(e,(t==null?void 0:t.configDir)||"","salty.config.ts"),o=l.join(s,"salty.config.js"),r=await jt(e),i=Ct(n);await gt.build({entryPoints:[n],minify:!0,treeShaking:!0,bundle:!0,outfile:o,format:r,external:i});const w=Date.now(),{config:$}=await import(`${o}?t=${w}`);return{config:$,path:o}},Yt=async(e,t)=>{var ut,dt;const s=await z(e),n={mediaQueries:[],globalStyles:[],variables:[],templates:[]};await Promise.all([...t].map(async C=>{const{contents:_,outputFilePath:A}=await nt(e,C,s);Object.entries(_).forEach(([T,O])=>{O.isMedia?n.mediaQueries.push([T,O]):O.isGlobalDefine?n.globalStyles.push(O):O.isDefineVariables?n.variables.push(O):O.isDefineTemplates&&n.templates.push(O._setPath(`${T};;${A}`))})}));const{config:o,path:r}=await Xt(e),i={...o},w=new Set,$=(C,_=[])=>C?Object.entries(C).flatMap(([A,T])=>{if(!T)return;if(typeof T=="object")return $(T,[..._,A]);const O=Ft(A),ot=V(A),rt=[..._,O].join(".");w.add(`"${rt}"`);const Y=[..._.map(V),ot].join("-"),pt=Jt(T);return pt?`--${Y}: ${pt.transformed};`:`--${Y}: ${T};`}):[],f=C=>C?Object.entries(C).flatMap(([_,A])=>{const T=$(A);return _==="base"?T.join(""):`${_} { ${T.join("")} }`}):[],p=C=>C?Object.entries(C).flatMap(([_,A])=>Object.entries(A).flatMap(([T,O])=>{const ot=$(O,[_]),rt=`.${_}-${T}, [data-${_}="${T}"]`,Y=ot.join("");return`${rt} { ${Y} }`})):[],b=C=>({...C,responsive:void 0,conditional:void 0}),g=C=>n.variables.map(_=>C==="static"?b(_._current):_._current[C]),y=I(b(o.variables),g("static")),a=$(y),m=I((ut=o.variables)==null?void 0:ut.responsive,g("responsive")),x=f(m),P=I((dt=o.variables)==null?void 0:dt.conditional,g("conditional")),R=p(P),N=l.join(s,"css/_variables.css"),M=`:root { ${a.join("")} ${x.join("")} } ${R.join("")}`;d.writeFileSync(N,M),i.staticVariables=y;const j=l.join(s,"css/_global.css"),D=I(o.global,n.globalStyles),c=await K(D,"");d.writeFileSync(j,`@layer global { ${c} }`);const h=l.join(s,"css/_reset.css"),u=o.reset==="none"?{}:typeof o.reset=="object"?o.reset:Lt,S=await K(u,"");d.writeFileSync(h,`@layer reset { ${S} }`);const k=l.join(s,"css/_templates.css"),E=I(o.templates,n.templates),q=await $t(E),H=Zt(E);d.writeFileSync(k,`@layer templates { ${q} }`),i.templates=E;const L=o.templates?[Ut(o.templates)._setPath(`config;;${r}`)]:[],U=Bt(n.templates,L);i.templatePaths=Object.fromEntries(Object.entries(U).map(([C,_])=>[C,_._path]));const{mediaQueries:Q}=n;i.mediaQueries=Object.fromEntries(Q.map(([C,_])=>[`@${C}`,_]));const B=Q.map(([C])=>`'@${C}'`).join(" | "),X=l.join(s,"types/css-tokens.d.ts"),Nt=`
7
+ // Variable types
8
+ type VariableTokens = ${[...w].join("|")};
9
+ type PropertyValueToken = \`{\${VariableTokens}}\`;
11
10
 
12
- ${["@import url('./css/variables.css');","@import url('./css/global.css');","@import url('./css/templates.css');"].join(`
11
+ // Template types
12
+ type TemplateTokens = {
13
+ ${Object.entries(H).map(([C,_])=>`${C}?: ${_}`).join(`
13
14
  `)}
14
- ${f}`;if($.importStrategy!=="component"){const p=e.flat().map(h=>`@import url('./css/${h}');`).join(`
15
- `);i+=p}m.writeFileSync(r,i)}catch(s){console.error(s)}},tt=async(t,s)=>{try{const e=[],n=u.join(t,"./saltygen"),r=u.join(n,"index.css");if(V(s)){const $=await A(t),a=await _(s,n);Object.entries(a).forEach(([h,j])=>{if(!j.generator)return;const S=j.generator._withBuildContext({name:h,config:$}),w=`${S.hash}-${S.priority}.css`,O=`css/${w}`,b=u.join(n,O);e.push(w),m.writeFileSync(b,S.css)});const f=m.readFileSync(r,"utf8").split(`
16
- `),o=e.map(h=>`@import url('../saltygen/css/${h}');`),p=[...new Set([...f,...o])].join(`
17
- `);m.writeFileSync(r,p)}}catch(e){console.error(e)}},st=async(t,s)=>{try{const e=u.join(t,"./saltygen");if(V(s)){const r=m.readFileSync(s,"utf8");r.replace(/^(?!export\s)const\s.*/gm,i=>`export ${i}`)!==r&&await J.writeFile(s,r);const $=await A(t),a=await _(s,e);let f=r;Object.entries(a).forEach(([i,p])=>{var b;if(p.isKeyframes){console.log("value",p);return}if(!p.generator)return;const h=p.generator._withBuildContext({name:i,config:$}),j=new RegExp(`${i}[=\\s]+[^()]+styled\\(([^,]+),`,"g").exec(r);if(!j)return console.error("Could not find the original declaration");const S=(b=j.at(1))==null?void 0:b.trim(),w=`${i} = styled(${S}, "${h.classNames}", "${h._callerName}", ${JSON.stringify(h.props)});`,O=new RegExp(`${i}[=\\s]+[^()]+styled\\(([^,]+),[^;]+;`,"g");f=f.replace(O,w)});const o=E(s,6);return $.importStrategy==="component"&&(f=`import '../../saltygen/css/${o}.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)}},et=t=>({name:"stylegen",buildStart:()=>v(t),load:async s=>{if(V(s))return await st(t,s)},watchChange:{handler:async s=>{V(s)&&await tt(t,s),s.includes("salty.config")&&await I(t)}}});exports.saltyPlugin=et;
15
+ }
16
+
17
+ // Media query types
18
+ type MediaQueryKeys = ${B||"''"};
19
+ `;d.writeFileSync(X,Nt);const kt=l.join(s,"cache/config-cache.json");d.writeFileSync(kt,JSON.stringify(i,null,2))},yt=e=>e.replace(/styled\(([^"'`{,]+),/g,(t,s)=>{if(/^['"`]/.test(s))return t;const o=new RegExp(`import[^;]*${s}[,\\s{][^;]*from\\s?([^{};]+);`);if(!o.test(e))return t;const i=o.exec(e);if(i){const w=i.at(1);if(Pt.some(f=>w==null?void 0:w.includes(f)))return t}return"styled('div',"}),te=(e,t)=>{try{const s=d.readFileSync(l.join(t,"saltygen/cache/config-cache.json"),"utf8");return s?`globalThis.saltyConfig = ${s};
20
+
21
+ ${e}`:`globalThis.saltyConfig = {};
22
+
23
+ ${e}`}catch{return e}},nt=async(e,t,s)=>{const n=v(t),o=l.join(s,"./temp");d.existsSync(o)||d.mkdirSync(o);const r=l.parse(t);let i=d.readFileSync(t,"utf8");i=yt(i),i=te(i,e);const w=l.join(s,"js",n+".js"),$=await ct(e),f=l.join(e,($==null?void 0:$.configDir)||"","salty.config.ts"),p=Ct(f),b=await jt(e);await gt.build({stdin:{contents:i,sourcefile:r.base,resolveDir:r.dir,loader:"tsx"},minify:!1,treeShaking:!0,bundle:!0,outfile:w,format:b,target:["node20"],keepNames:!0,external:p,packages:"external",plugins:[{name:"test",setup:a=>{a.onLoad({filter:/.*\.css|salty|styles|styled\.ts/},m=>{const x=d.readFileSync(m.path,"utf8");return{contents:yt(x),loader:"ts"}})}}]});const g=Date.now();return{contents:await import(`${w}?t=${g}`),outputFilePath:w}},ee=async e=>{const t=await z(e),s=l.join(t,"cache/config-cache.json"),n=d.readFileSync(s,"utf8");if(!n)throw new Error("Could not find config cache file");return JSON.parse(n)},lt=async e=>{const t=await ee(e),s=await z(e),n=l.join(s,"salty.config.js"),o=Date.now(),{config:r}=await import(`${n}?t=${o}`);return I(r,t)},ft=()=>{try{return process.env.NODE_ENV==="production"}catch{return!1}},se=async(e,t=ft(),s=!0)=>{try{const n=Date.now();t?at.info("Generating CSS in production mode! 🔥"):at.info("Generating CSS in development mode! 🚀");const o=[],r=[],i=await z(e),w=l.join(i,"index.css");s&&(()=>{d.existsSync(i)&&Ot.execSync("rm -rf "+i),d.mkdirSync(i,{recursive:!0}),d.mkdirSync(l.join(i,"css")),d.mkdirSync(l.join(i,"types")),d.mkdirSync(l.join(i,"js")),d.mkdirSync(l.join(i,"cache"))})();const f=new Set,p=new Set;async function b(c){const h=["node_modules","saltygen"],F=d.statSync(c);if(F.isDirectory()){const u=d.readdirSync(c);if(h.some(k=>c.includes(k)))return;await Promise.all(u.map(k=>b(l.join(c,k))))}else if(F.isFile()&&Z(c)){f.add(c);const S=d.readFileSync(c,"utf8");/define[\w\d]+\(/.test(S)&&p.add(c)}}await b(e),await Yt(e,p);const g={keyframes:[],components:[],classNames:[]};await Promise.all([...f].map(async c=>{const{contents:h}=await nt(e,c,i);Object.entries(h).forEach(([F,u])=>{u.isKeyframes?g.keyframes.push({value:u,src:c,name:F}):u.isClassName?g.classNames.push({...u,src:c,name:F}):u.generator&&g.components.push({...u,src:c,name:F})})}));const y=await lt(e);for(const c of g.keyframes){const{value:h}=c,F=`a_${h.animationName}.css`,u=`css/${F}`,S=l.join(i,u);o.push(F),d.writeFileSync(S,h.css)}const a={};for(const c of g.components){const{src:h,name:F}=c;a[h]||(a[h]=[]);const u=c.generator._withBuildContext({callerName:F,isProduction:t,config:y});r[u.priority]||(r[u.priority]=[]);const S=await u.css;if(!S)continue;r[u.priority].push(u.cssFileName);const k=`css/${u.cssFileName}`,E=l.join(i,k);d.writeFileSync(E,S),y.importStrategy==="component"&&a[h].push(u.cssFileName)}for(const c of g.classNames){const{src:h,name:F}=c;a[h]||(a[h]=[]);const u=c.generator._withBuildContext({callerName:F,isProduction:t,config:y}),S=await u.css;if(!S)continue;r[0].push(u.cssFileName);const k=`css/${u.cssFileName}`,E=l.join(i,k);d.writeFileSync(E,S),y.importStrategy==="component"&&a[h].push(u.cssFileName)}y.importStrategy==="component"&&Object.entries(a).forEach(([c,h])=>{const F=h.map(q=>`@import url('./${q}');`).join(`
24
+ `),u=v(c,6),S=l.parse(c),k=V(S.name),E=l.join(i,`css/f_${k}-${u}.css`);d.writeFileSync(E,F||"/* Empty file */")});const m=o.map(c=>`@import url('./css/${c}');`).join(`
25
+ `);let N=`@layer reset, global, templates, l0, l1, l2, l3, l4, l5, l6, l7, l8;
26
+
27
+ ${["_variables.css","_reset.css","_global.css","_templates.css"].filter(c=>{try{return d.readFileSync(l.join(i,"css",c),"utf8").length>0}catch{return!1}}).map(c=>`@import url('./css/${c}');`).join(`
28
+ `)}
29
+ ${m}`;if(y.importStrategy!=="component"){const c=r.reduce((h,F,u)=>{const S=F.reduce((H,L)=>{var X;const U=l.join(i,"css",L),Q=d.readFileSync(U,"utf8"),B=((X=/.*-([^-]+)-\d+.css/.exec(L))==null?void 0:X.at(1))||v(U,6);return H.includes(B)?H:`${H}
30
+ /*start:${B}-${L}*/
31
+ ${Q}
32
+ /*end:${B}*/
33
+ `},""),k=`l_${u}.css`,E=l.join(i,"css",k),q=`@layer l${u} { ${S}
34
+ }`;return d.writeFileSync(E,q),`${h}
35
+ @import url('./css/${k}');`},"");N+=c}d.writeFileSync(w,N);const j=Date.now()-n,D=j<200?"🔥":j<500?"🚀":j<1e3?"🎉":j<2e3?"🚗":j<5e3?"🤔":"🥴";at.info(`Generated CSS in ${j}ms! ${D}`)}catch(n){console.error(n)}},ne=async(e,t,s=ft())=>{try{const n=await z(e);if(Z(t)){const r=[],i=await lt(e),{contents:w}=await nt(e,t,n);for(const[$,f]of Object.entries(w)){if(f.isKeyframes&&f.css){const m=`css/${`a_${f.animationName}.css`}`,x=l.join(n,m);d.writeFileSync(x,await f.css);return}if(f.isClassName){const a=f.generator._withBuildContext({callerName:$,isProduction:s,config:i}),m=await a.css;if(!m)continue;r[0].push(a.cssFileName);const x=`css/${a.cssFileName}`,P=l.join(n,x);d.writeFileSync(P,m)}if(!f.generator)return;const p=f.generator._withBuildContext({callerName:$,isProduction:s,config:i}),b=await p.css;if(!b)continue;const g=`css/${p.cssFileName}`,y=l.join(n,g);d.writeFileSync(y,b),r[p.priority]||(r[p.priority]=[]),r[p.priority].push(p.cssFileName)}if(i.importStrategy!=="component")r.forEach(($,f)=>{const p=`l_${f}.css`,b=l.join(n,"css",p);let g=d.readFileSync(b,"utf8");$.forEach(y=>{var P;const a=l.join(n,"css",y),m=((P=/.*-([^-]+)-\d+.css/.exec(y))==null?void 0:P.at(1))||v(a,6);if(!g.includes(m)){const R=d.readFileSync(a,"utf8"),N=`/*start:${m}-${y}*/
36
+ ${R}
37
+ /*end:${m}*/
38
+ `;g=`${g.replace(/\}$/,"")}
39
+ ${N}
40
+ }`}}),d.writeFileSync(b,g)});else{const $=r.flat().map(y=>`@import url('./${y}');`).join(`
41
+ `),f=v(t,6),p=l.parse(t),b=V(p.name),g=l.join(n,`css/f_${b}-${f}.css`);d.writeFileSync(g,$||"/* Empty file */")}}}catch(n){console.error(n)}},oe=async(e,t,s=ft())=>{try{const n=await z(e);if(Z(t)){const r=d.readFileSync(t,"utf8");r.replace(/^(?!export\s)const\s.*/gm,p=>`export ${p}`)!==r&&await st.writeFile(t,r);const w=await lt(e),{contents:$}=await nt(e,t,n);let f=r;if(Object.entries($).forEach(([p,b])=>{var u;if(b.isKeyframes||!b.generator)return;const g=b.generator._withBuildContext({callerName:p,isProduction:s,config:w}),y=new RegExp(`\\s${p}[=\\s]+[^()]+styled\\(([^,]+),`,"g").exec(r);if(!y)return console.error("Could not find the original declaration");const a=(u=y.at(1))==null?void 0:u.trim(),m=new RegExp(`\\s${p}[=\\s]+styled\\(`,"g").exec(f);if(!m)return console.error("Could not find the original declaration");const{index:x}=m;let P=!1;const R=setTimeout(()=>P=!0,5e3);let N=0,M=!1,j=0;for(;!M&&!P;){const S=f[x+N];S==="("&&j++,S===")"&&j--,j===0&&S===")"&&(M=!0),N>f.length&&(P=!0),N++}if(!P)clearTimeout(R);else throw new Error("Failed to find the end of the styled call and timed out");const D=x+N,c=f.slice(x,D),h=f,F=` ${p} = styled(${a}, "${g.classNames}", ${JSON.stringify(g.clientProps)});`;f=f.replace(c,F),h===f&&console.error("Minimize file failed to change content",{name:p,tagName:a})}),w.importStrategy==="component"){const p=v(t,6),b=l.parse(t);f=`import '../../saltygen/css/${`f_${V(b.name)}-${p}.css`}';
42
+ ${f}`}return f=f.replace("{ styled }","{ styledClient as styled }"),f=f.replace("@salty-css/react/styled","@salty-css/react/styled-client"),f}}catch(n){console.error("Error in minimizeFile:",n)}},ht=async e=>{if(!e||e.includes("node_modules")||e.includes("saltygen"))return!1;if(e.includes("salty.config"))return!0;if(!Z(e))return!1;const n=await st.readFile(e,"utf-8");return!!/.+define[A-Z]\w+/.test(n)},xt=e=>({name:"stylegen",buildStart:()=>se(e),load:async t=>{if(Z(t))return await oe(e,t)},handleHotUpdate:async({file:t,server:s})=>{await ht(t)&&await s.restart()},watchChange:{handler:async t=>{Z(t)&&(await ht(t)||await ne(e,t))}}});exports.default=xt;exports.saltyPlugin=xt;
package/index.d.ts CHANGED
@@ -1,8 +1,3 @@
1
- export declare const saltyPlugin: (dir: string) => {
2
- name: string;
3
- buildStart: () => Promise<void>;
4
- load: (filePath: string) => Promise<string | undefined>;
5
- watchChange: {
6
- handler: (filePath: string) => Promise<void>;
7
- };
8
- };
1
+ import { PluginOption } from 'vite';
2
+ export declare const saltyPlugin: (dir: string) => PluginOption;
3
+ export default saltyPlugin;
package/index.js CHANGED
@@ -1,272 +1,670 @@
1
- import * as Z from "esbuild";
2
- import { execSync as q } from "child_process";
3
- import { join as u } from "path";
4
- import { writeFileSync as C, existsSync as z, mkdirSync as T, statSync as G, readdirSync as L, readFileSync as I } from "fs";
5
- import { writeFile as U } from "fs/promises";
6
- const _ = (t) => String.fromCharCode(t + (t > 25 ? 39 : 97)), X = (t, s) => {
7
- let e = "", n;
8
- for (n = Math.abs(t); n > 52; n = n / 52 | 0) e = _(n % 52) + e;
9
- return e = _(n % 52) + e, e.length < s ? e = e.padStart(s, "a") : e.length > s && (e = e.slice(-s)), e;
10
- }, Y = (t, s) => {
11
- let e = s.length;
12
- for (; e; ) t = t * 33 ^ s.charCodeAt(--e);
13
- return t;
14
- }, A = (t, s = 3) => {
15
- const e = Y(5381, JSON.stringify(t)) >>> 0;
16
- return X(e, s);
1
+ var Tt = Object.defineProperty;
2
+ var Ot = (e, t, s) => t in e ? Tt(e, t, { enumerable: !0, configurable: !0, writable: !0, value: s }) : e[t] = s;
3
+ var et = (e, t, s) => Ot(e, typeof t != "symbol" ? t + "" : t, s);
4
+ import * as bt from "esbuild";
5
+ import { execSync as Vt } from "child_process";
6
+ import { join as u, parse as nt } from "path";
7
+ import { existsSync as lt, mkdirSync as H, statSync as Mt, readdirSync as Rt, readFileSync as M, writeFileSync as k } from "fs";
8
+ import { readFile as ft, writeFile as At } from "fs/promises";
9
+ import { createLogger as Jt, format as at, transports as Wt } from "winston";
10
+ const yt = (e) => String.fromCharCode(e + (e > 25 ? 39 : 97)), zt = (e, t) => {
11
+ let s = "", n;
12
+ for (n = Math.abs(e); n > 52; n = n / 52 | 0) s = yt(n % 52) + s;
13
+ return s = yt(n % 52) + s, s.length < t ? s = s.padStart(t, "a") : s.length > t && (s = s.slice(-t)), s;
14
+ }, vt = (e, t) => {
15
+ let s = t.length;
16
+ for (; s; ) e = e * 33 ^ t.charCodeAt(--s);
17
+ return e;
18
+ }, z = (e, t = 5) => {
19
+ const s = vt(5381, JSON.stringify(e)) >>> 0;
20
+ return zt(s, t);
17
21
  };
18
- function V(t) {
19
- return t ? typeof t != "string" ? V(String(t)) : t.replace(/\s/g, "-").replace(/[A-Z](?:(?=[^A-Z])|[A-Z]*(?=[A-Z][^A-Z]|$))/g, (s, e) => (e > 0 ? "-" : "") + s.toLowerCase()) : "";
22
+ function A(e) {
23
+ return e ? typeof e != "string" ? A(String(e)) : e.replace(/[\s.]/g, "-").replace(/[A-Z](?:(?=[^A-Z])|[A-Z]*(?=[A-Z][^A-Z]|$))/g, (t, s) => (s > 0 ? "-" : "") + t.toLowerCase()) : "";
20
24
  }
21
- const Q = (t, s) => {
22
- if (typeof t != "string") return { result: t };
23
- if (!s) return { result: t };
24
- const e = [];
25
- return Object.values(s).forEach((n) => {
26
- const { pattern: r, transform: y } = n;
27
- t = t.replace(r, ($) => {
28
- const { value: a, css: f } = y($);
29
- return f && e.push(f), a;
25
+ const Zt = (e) => (t) => {
26
+ if (typeof t != "string" || !e) return;
27
+ let s = t;
28
+ const n = [];
29
+ return Object.values(e).forEach((o) => {
30
+ const { pattern: r, transform: i } = o;
31
+ s = s.replace(r, (y) => {
32
+ const { value: $, css: l } = i(y);
33
+ return l && n.push(l), $;
30
34
  });
31
- }), { result: t, additionalCss: e };
32
- }, B = (t) => typeof t != "string" ? { result: t } : /\{[^{}]+\}/g.test(t) ? { result: t.replace(/\{([^{}]+)\}/g, (...n) => `var(--${V(n[1].replaceAll(".", "-"))})`) } : { result: t }, O = (t, s, e, n) => {
33
- if (!t) return "";
34
- const r = [], y = 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(([g, c]) => {
40
- c && Object.entries(c).forEach(([m, l]) => {
41
- if (!l) return;
42
- const S = `${s}.${g}-${m}`, D = O(l, S);
43
- r.push(D);
44
- });
45
- }), a;
46
- if (i === "defaultVariants")
47
- return a;
48
- if (i === "compoundVariants")
49
- return o.forEach((g) => {
50
- const { css: c, ...m } = g, l = Object.entries(m).reduce((D, [N, P]) => `${D}.${N}-${P}`, s), S = O(c, l);
51
- r.push(S);
52
- }), a;
53
- if (i.startsWith("@")) {
54
- const g = O(o, s), c = `${i} {
55
- ${g.replace(`
56
- `, `
57
- `)}
58
- }`;
59
- return r.push(c), a;
35
+ }), { transformed: s, additionalCss: n };
36
+ }, Ct = (e) => (t) => typeof t != "string" || !/\{[^{}]+\}/g.test(t) ? void 0 : { transformed: t.replace(/\{([^{}]+)\}/g, (...o) => `var(--${A(o[1].replaceAll(".", "-"))})`) }, Ht = Ct(), It = [
37
+ "top",
38
+ "right",
39
+ "bottom",
40
+ "left",
41
+ "min-width",
42
+ /.*width.*/,
43
+ /^[^line]*height.*/,
44
+ // Exclude line-height
45
+ /padding.*/,
46
+ /margin.*/,
47
+ /border.*/,
48
+ /inset.*/,
49
+ /.*radius.*/,
50
+ /.*spacing.*/,
51
+ /.*gap.*/,
52
+ /.*indent.*/,
53
+ /.*offset.*/,
54
+ /.*size.*/,
55
+ /.*thickness.*/,
56
+ /.*font-size.*/
57
+ ], Bt = (e, t, s) => It.some((o) => typeof o == "string" ? o === e : o.test(e)) ? `${t}px` : `${t}`, Gt = ["Webkit", "Moz", "ms", "O"], Kt = (e) => e.startsWith("-") ? e : Gt.some((t) => e.startsWith(t)) ? `-${A(e)}` : A(e), st = async (e, t = "", s, n = !1) => {
58
+ if (!e) throw new Error("No styles provided to parseStyles function!");
59
+ const o = /* @__PURE__ */ new Set(), i = Object.entries(e).map(async ([m, a]) => {
60
+ const p = m.trim(), x = Kt(p), F = (N, V = ";") => `${x}:${N}${V}`;
61
+ if (typeof a == "function" && (a = a({ scope: t, config: s })), a instanceof Promise && (a = await a), typeof a == "object") {
62
+ if (!a) return;
63
+ if (a.isColor) return F(a.toString());
64
+ if (p === "defaultVariants") return;
65
+ if (p === "variants") {
66
+ const C = Object.entries(a);
67
+ for (const [E, c] of C) {
68
+ if (!c) return;
69
+ const h = Object.entries(c);
70
+ for (const [S, f] of h) {
71
+ if (!f) return;
72
+ const b = `${t}.${E}-${S}`;
73
+ (await st(f, b, s)).forEach((T) => o.add(T));
74
+ }
75
+ }
76
+ return;
77
+ }
78
+ if (p === "compoundVariants") {
79
+ for (const C of a) {
80
+ const { css: E, ...c } = C, h = Object.entries(c).reduce((f, [b, _]) => `${f}.${b}-${_}`, t);
81
+ (await st(E, h, s)).forEach((f) => o.add(f));
82
+ }
83
+ return;
84
+ }
85
+ if (p.startsWith("@")) {
86
+ const C = p, E = await U(a, t, s), c = `${C} { ${E} }`;
87
+ o.add(c);
88
+ return;
60
89
  }
61
- const d = f.includes("&") ? i.replace("&", s) : i.startsWith(":") ? `${s}${i}` : `${s} ${i}`, x = O(o, d);
62
- return r.push(x), a;
90
+ const N = m.includes("&") ? p.replace("&", t) : p.startsWith(":") ? `${t}${p}` : `${t} ${p}`;
91
+ (await st(a, N, s)).forEach((C) => o.add(C));
92
+ return;
63
93
  }
64
- const p = i.startsWith("-") ? i : V(i), h = (d, x = ";") => a = `${a}${d}${x}`, 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();
68
- else return a;
69
- const { modifiers: j } = {}, F = function* () {
70
- yield B(o), yield Q(o, j);
71
- }();
72
- for (const { result: d, additionalCss: x = [] } of F)
73
- o = d, x.forEach((g) => {
74
- const c = O(g, "");
75
- h(c, "");
76
- });
77
- return b(o);
78
- }, "");
79
- if (!y) return r.join(`
80
- `);
81
- if (!s) return y;
82
- let $ = "";
83
- return $ = `${s} { ${y} }`, [$, ...r].join(`
84
- `);
85
- }, H = (t, s = []) => {
86
- if (!t) return "";
87
- const e = [], n = {};
88
- if (Object.entries(t).forEach(([r, y]) => {
89
- if (typeof y == "object") {
90
- if (!y) return;
91
- const $ = r.trim(), a = H(y, [...s, $]);
92
- e.push(a);
94
+ if (typeof a == "number") {
95
+ const N = Bt(x, a);
96
+ return F(N);
97
+ }
98
+ if (typeof a != "string")
99
+ if ("toString" in a) a = a.toString();
100
+ else throw new Error(`Invalid value type for property ${x}`);
101
+ return F(a);
102
+ }), { modifiers: y } = {}, $ = [Ct(), Zt(y)], d = (await Promise.all(i).then((m) => Promise.all(
103
+ m.map((a) => $.reduce(async (p, x) => {
104
+ const F = await p;
105
+ if (!F) return F;
106
+ const R = await x(F);
107
+ if (!R) return F;
108
+ const { transformed: N, additionalCss: V } = R;
109
+ let C = "";
110
+ if (V)
111
+ for (const E of V)
112
+ C += await U(E, "");
113
+ return `${C}${N}`;
114
+ }, Promise.resolve(a)))
115
+ ))).filter((m) => m !== void 0).join(`
116
+ `);
117
+ if (!d.trim()) return Array.from(o);
118
+ const w = t ? `${t} {
119
+ ${d}
120
+ }` : d;
121
+ return o.has(w) ? Array.from(o) : [w, ...o];
122
+ }, U = async (e, t, s, n = !1) => (await st(e, t, s, n)).join(`
123
+ `), St = async (e, t = []) => {
124
+ if (!e) return "";
125
+ const s = [], n = {};
126
+ for (const [o, r] of Object.entries(e))
127
+ if (typeof r != "function") if (r && typeof r == "object") {
128
+ const i = o.trim(), y = await St(r, [...t, i]);
129
+ s.push(y);
93
130
  } else
94
- n[r] = y;
95
- }), Object.keys(n).length) {
96
- const r = s.map(V).join("-"), y = O(n, `.${r}`);
97
- e.push(y);
131
+ n[o] = r;
132
+ if (Object.keys(n).length) {
133
+ const o = t.map(A).join("-"), r = "t_" + z(o, 4), i = await U(n, `.${o}, .${r}`);
134
+ s.push(i);
98
135
  }
99
- return e.join(`
136
+ return s.join(`
100
137
  `);
101
- }, E = (t) => u(t, "./saltygen"), v = ["salty", "css", "styles", "styled"], tt = (t = []) => new RegExp(`\\.(${[...v, ...t].join("|")})\\.`), k = (t, s = []) => tt(s).test(t), st = async (t) => {
102
- const s = E(t), e = u(t, "salty.config.ts"), n = u(s, "salty.config.js");
103
- await Z.build({
104
- entryPoints: [e],
138
+ }, Lt = (e) => e ? Object.entries(e).reduce((t, [s, n]) => (typeof n == "function" ? t[s] = "any" : typeof n == "object" && (t[s] = jt(n).map((o) => `"${o}"`).join(" | ")), t), {}) : {}, jt = (e, t = "", s = /* @__PURE__ */ new Set()) => e ? (Object.entries(e).forEach(([n, o]) => {
139
+ const r = t ? `${t}.${n}` : n;
140
+ return typeof o == "object" ? jt(o, r, s) : s.add(t);
141
+ }), [...s]) : [], Ft = (e) => {
142
+ if (!e || e === "/") throw new Error("Could not find package.json file");
143
+ const t = u(e, "package.json");
144
+ return lt(t) ? t : Ft(u(e, ".."));
145
+ }, Qt = async (e) => {
146
+ const t = Ft(e);
147
+ return await ft(t, "utf-8").then(JSON.parse).catch(() => {
148
+ });
149
+ }, Ut = async (e) => {
150
+ const t = await Qt(e);
151
+ if (t)
152
+ return t.type;
153
+ };
154
+ let Z;
155
+ const Pt = async (e) => {
156
+ if (Z) return Z;
157
+ const t = await Ut(e);
158
+ return t === "module" ? Z = "esm" : (t === "commonjs" || import.meta.url.endsWith(".cjs")) && (Z = "cjs"), Z || "esm";
159
+ }, ct = Jt({
160
+ level: "debug",
161
+ format: at.combine(at.colorize(), at.cli()),
162
+ transports: [new Wt.Console({})]
163
+ });
164
+ function xt(e) {
165
+ return e ? typeof e != "string" ? xt(String(e)) : e.replace(/[\s-]/g, ".").replace(/[A-Z](?:(?=[^A-Z])|[A-Z]*(?=[A-Z][^A-Z]|$))/g, (t, s) => (s > 0 ? "." : "") + t.toLowerCase()) : "";
166
+ }
167
+ const qt = {
168
+ /** Set box model to border-box */
169
+ "*, *::before, *::after": {
170
+ boxSizing: "border-box"
171
+ },
172
+ /** Remove default margin and padding */
173
+ "*": {
174
+ margin: 0
175
+ },
176
+ /** Remove adjust font properties */
177
+ html: {
178
+ lineHeight: 1.15,
179
+ textSizeAdjust: "100%",
180
+ WebkitFontSmoothing: "antialiased"
181
+ },
182
+ /** Make media elements responsive */
183
+ "img, picture, video, canvas, svg": {
184
+ display: "block",
185
+ maxWidth: "100%"
186
+ },
187
+ /** Avoid overflow of text */
188
+ "p, h1, h2, h3, h4, h5, h6": {
189
+ overflowWrap: "break-word"
190
+ },
191
+ /** Improve text wrapping */
192
+ p: {
193
+ textWrap: "pretty"
194
+ },
195
+ "h1, h2, h3, h4, h5, h6": {
196
+ textWrap: "balance"
197
+ },
198
+ /** Improve link color */
199
+ a: {
200
+ color: "currentColor"
201
+ },
202
+ /** Improve button line height */
203
+ button: {
204
+ lineHeight: "1em",
205
+ color: "currentColor"
206
+ },
207
+ /** Improve form elements */
208
+ "input, optgroup, select, textarea": {
209
+ fontFamily: "inherit",
210
+ fontSize: "100%",
211
+ lineHeight: "1.15em"
212
+ }
213
+ }, I = (...e) => e.flat().reduce((t, s) => s != null && s._current ? { ...t, ...s._current } : { ...t, ...s }, {}), Xt = (...e) => e.flat().reduce((t, s) => ({ ...t, ...s._children }), {});
214
+ class Yt {
215
+ constructor(t) {
216
+ et(this, "_path");
217
+ this.params = t;
218
+ }
219
+ get _current() {
220
+ return this.params.template;
221
+ }
222
+ get isDefineTemplate() {
223
+ return !0;
224
+ }
225
+ _setPath(t) {
226
+ return this._path = t, this;
227
+ }
228
+ }
229
+ class te {
230
+ constructor(t) {
231
+ et(this, "_path");
232
+ et(this, "templates", []);
233
+ this.params = t, Object.entries(t).forEach(([s, n]) => {
234
+ this.templates.push(
235
+ new Yt({
236
+ name: s,
237
+ template: n
238
+ })
239
+ );
240
+ });
241
+ }
242
+ get _current() {
243
+ return this.params;
244
+ }
245
+ get _children() {
246
+ return Object.fromEntries(
247
+ this.templates.map((t) => [t.params.name, t])
248
+ );
249
+ }
250
+ get isDefineTemplates() {
251
+ return !0;
252
+ }
253
+ _setPath(t) {
254
+ return this._path = t, this.templates.forEach((s) => s._setPath(t)), this;
255
+ }
256
+ }
257
+ const ee = (e) => new te(e), W = {
258
+ externalModules: [],
259
+ rcFile: void 0,
260
+ destDir: void 0
261
+ }, Nt = (e) => {
262
+ if (W.externalModules.length > 0) return W.externalModules;
263
+ const s = M(e, "utf8").match(/externalModules:\s?\[(.*)\]/);
264
+ if (!s) return [];
265
+ const n = s[1].split(",").map((o) => o.replace(/['"`]/g, "").trim());
266
+ return W.externalModules = n, n;
267
+ }, v = async (e) => {
268
+ if (W.destDir) return W.destDir;
269
+ const t = await ut(e), s = u(e, (t == null ? void 0 : t.saltygenDir) || "saltygen");
270
+ return W.destDir = s, s;
271
+ }, _t = ["salty", "css", "styles", "styled"], se = (e = []) => new RegExp(`\\.(${[..._t, ...e].join("|")})\\.`), B = (e, t = []) => se(t).test(e), kt = async (e) => {
272
+ if (W.rcFile) return W.rcFile;
273
+ if (e === "/") throw new Error("Could not find .saltyrc.json file");
274
+ const t = u(e, ".saltyrc.json"), s = await ft(t, "utf-8").then(JSON.parse).catch(() => {
275
+ });
276
+ return s ? (W.rcFile = s, s) : kt(u(e, ".."));
277
+ }, ut = async (e) => {
278
+ var n, o;
279
+ const t = await kt(e), s = (n = t.projects) == null ? void 0 : n.find((r) => e.endsWith(r.dir || ""));
280
+ return s || ((o = t.projects) == null ? void 0 : o.find((r) => r.dir === t.defaultProject));
281
+ }, ne = async (e) => {
282
+ const t = await ut(e), s = await v(e), n = u(e, (t == null ? void 0 : t.configDir) || "", "salty.config.ts"), o = u(s, "salty.config.js"), r = await Pt(e), i = Nt(n);
283
+ await bt.build({
284
+ entryPoints: [n],
105
285
  minify: !0,
106
286
  treeShaking: !0,
107
287
  bundle: !0,
108
- outfile: n,
109
- format: "esm",
110
- external: ["react"]
288
+ outfile: o,
289
+ format: r,
290
+ external: i
111
291
  });
112
- const r = Date.now(), { config: y } = await import(`${n}?t=${r}`);
113
- return y;
114
- }, W = async (t) => {
115
- const s = await st(t), e = /* @__PURE__ */ new Set(), n = (g, c = []) => g ? Object.entries(g).flatMap(([m, l]) => {
116
- if (!l) return;
117
- if (typeof l == "object") return n(l, [...c, m]);
118
- const S = [...c, m].join(".");
119
- e.add(`"${S}"`);
120
- const D = [...c.map(V), V(m)].join("-"), { result: N } = B(l);
121
- return `--${D}: ${N};`;
122
- }) : [], r = (g) => g ? Object.entries(g).flatMap(([c, m]) => {
123
- const l = n(m);
124
- return c === "base" ? l.join("") : `${c} { ${l.join("")} }`;
125
- }) : [], y = (g) => g ? Object.entries(g).flatMap(([c, m]) => Object.entries(m).flatMap(([l, S]) => {
126
- const D = n(S, [c]), N = `.${c}-${l}, [data-${c}="${l}"]`, P = D.join("");
127
- return `${N} { ${P} }`;
128
- })) : [], $ = n(s.variables), a = r(s.responsiveVariables), f = y(s.conditionalVariables), o = E(t), i = u(o, "css/variables.css"), p = `:root { ${$.join("")} ${a.join("")} } ${f.join("")}`;
129
- C(i, p);
130
- const h = u(o, "types/css-tokens.d.ts"), j = `type VariableTokens = ${[...e].join("|")}; type PropertyValueToken = \`{\${VariableTokens}}\``;
131
- C(h, j);
132
- const w = u(o, "css/global.css"), F = O(s.global, "");
133
- C(w, F);
134
- const d = u(o, "css/templates.css"), x = H(s.templates);
135
- C(d, x);
136
- }, R = async (t, s) => {
137
- const e = A(t), n = u(s, "js", e + ".js");
138
- await Z.build({
139
- entryPoints: [t],
140
- minify: !0,
292
+ const y = Date.now(), { config: $ } = await import(`${o}?t=${y}`);
293
+ return { config: $, path: o };
294
+ }, oe = async (e, t) => {
295
+ var mt, ht;
296
+ const s = await v(e), n = {
297
+ mediaQueries: [],
298
+ globalStyles: [],
299
+ variables: [],
300
+ templates: []
301
+ };
302
+ await Promise.all(
303
+ [...t].map(async (j) => {
304
+ const { contents: P, outputFilePath: J } = await ot(e, j, s);
305
+ Object.entries(P).forEach(([D, O]) => {
306
+ O.isMedia ? n.mediaQueries.push([D, O]) : O.isGlobalDefine ? n.globalStyles.push(O) : O.isDefineVariables ? n.variables.push(O) : O.isDefineTemplates && n.templates.push(O._setPath(`${D};;${J}`));
307
+ });
308
+ })
309
+ );
310
+ const { config: o, path: r } = await ne(e), i = { ...o }, y = /* @__PURE__ */ new Set(), $ = (j, P = []) => j ? Object.entries(j).flatMap(([J, D]) => {
311
+ if (!D) return;
312
+ if (typeof D == "object") return $(D, [...P, J]);
313
+ const O = xt(J), rt = A(J), it = [...P, O].join(".");
314
+ y.add(`"${it}"`);
315
+ const tt = [...P.map(A), rt].join("-"), gt = Ht(D);
316
+ return gt ? `--${tt}: ${gt.transformed};` : `--${tt}: ${D};`;
317
+ }) : [], l = (j) => j ? Object.entries(j).flatMap(([P, J]) => {
318
+ const D = $(J);
319
+ return P === "base" ? D.join("") : `${P} { ${D.join("")} }`;
320
+ }) : [], d = (j) => j ? Object.entries(j).flatMap(([P, J]) => Object.entries(J).flatMap(([D, O]) => {
321
+ const rt = $(O, [P]), it = `.${P}-${D}, [data-${P}="${D}"]`, tt = rt.join("");
322
+ return `${it} { ${tt} }`;
323
+ })) : [], w = (j) => ({ ...j, responsive: void 0, conditional: void 0 }), g = (j) => n.variables.map((P) => j === "static" ? w(P._current) : P._current[j]), m = I(w(o.variables), g("static")), a = $(m), p = I((mt = o.variables) == null ? void 0 : mt.responsive, g("responsive")), x = l(p), F = I((ht = o.variables) == null ? void 0 : ht.conditional, g("conditional")), R = d(F), N = u(s, "css/_variables.css"), V = `:root { ${a.join("")} ${x.join("")} } ${R.join("")}`;
324
+ k(N, V), i.staticVariables = m;
325
+ const C = u(s, "css/_global.css"), E = I(o.global, n.globalStyles), c = await U(E, "");
326
+ k(C, `@layer global { ${c} }`);
327
+ const h = u(s, "css/_reset.css"), f = o.reset === "none" ? {} : typeof o.reset == "object" ? o.reset : qt, b = await U(f, "");
328
+ k(h, `@layer reset { ${b} }`);
329
+ const _ = u(s, "css/_templates.css"), T = I(o.templates, n.templates), G = await St(T), K = Lt(T);
330
+ k(_, `@layer templates { ${G} }`), i.templates = T;
331
+ const L = o.templates ? [ee(o.templates)._setPath(`config;;${r}`)] : [], q = Xt(n.templates, L);
332
+ i.templatePaths = Object.fromEntries(Object.entries(q).map(([j, P]) => [j, P._path]));
333
+ const { mediaQueries: X } = n;
334
+ i.mediaQueries = Object.fromEntries(X.map(([j, P]) => [`@${j}`, P]));
335
+ const Q = X.map(([j]) => `'@${j}'`).join(" | "), Y = u(s, "types/css-tokens.d.ts"), Dt = `
336
+ // Variable types
337
+ type VariableTokens = ${[...y].join("|")};
338
+ type PropertyValueToken = \`{\${VariableTokens}}\`;
339
+
340
+ // Template types
341
+ type TemplateTokens = {
342
+ ${Object.entries(K).map(([j, P]) => `${j}?: ${P}`).join(`
343
+ `)}
344
+ }
345
+
346
+ // Media query types
347
+ type MediaQueryKeys = ${Q || "''"};
348
+ `;
349
+ k(Y, Dt);
350
+ const Et = u(s, "cache/config-cache.json");
351
+ k(Et, JSON.stringify(i, null, 2));
352
+ }, $t = (e) => e.replace(/styled\(([^"'`{,]+),/g, (t, s) => {
353
+ if (/^['"`]/.test(s)) return t;
354
+ const o = new RegExp(`import[^;]*${s}[,\\s{][^;]*from\\s?([^{};]+);`);
355
+ if (!o.test(e)) return t;
356
+ const i = o.exec(e);
357
+ if (i) {
358
+ const y = i.at(1);
359
+ if (_t.some((l) => y == null ? void 0 : y.includes(l))) return t;
360
+ }
361
+ return "styled('div',";
362
+ }), re = (e, t) => {
363
+ try {
364
+ const s = M(u(t, "saltygen/cache/config-cache.json"), "utf8");
365
+ return s ? `globalThis.saltyConfig = ${s};
366
+
367
+ ${e}` : `globalThis.saltyConfig = {};
368
+
369
+ ${e}`;
370
+ } catch {
371
+ return e;
372
+ }
373
+ }, ot = async (e, t, s) => {
374
+ const n = z(t), o = u(s, "./temp");
375
+ lt(o) || H(o);
376
+ const r = nt(t);
377
+ let i = M(t, "utf8");
378
+ i = $t(i), i = re(i, e);
379
+ const y = u(s, "js", n + ".js"), $ = await ut(e), l = u(e, ($ == null ? void 0 : $.configDir) || "", "salty.config.ts"), d = Nt(l), w = await Pt(e);
380
+ await bt.build({
381
+ stdin: {
382
+ contents: i,
383
+ sourcefile: r.base,
384
+ resolveDir: r.dir,
385
+ loader: "tsx"
386
+ },
387
+ minify: !1,
141
388
  treeShaking: !0,
142
389
  bundle: !0,
143
- outfile: n,
144
- format: "esm",
145
- target: ["es2022"],
390
+ outfile: y,
391
+ format: w,
392
+ target: ["node20"],
146
393
  keepNames: !0,
147
- external: ["react"]
394
+ external: d,
395
+ packages: "external",
396
+ plugins: [
397
+ {
398
+ name: "test",
399
+ setup: (a) => {
400
+ a.onLoad({ filter: /.*\.css|salty|styles|styled\.ts/ }, (p) => {
401
+ const x = M(p.path, "utf8");
402
+ return { contents: $t(x), loader: "ts" };
403
+ });
404
+ }
405
+ }
406
+ ]
148
407
  });
149
- const r = Date.now();
150
- return await import(`${n}?t=${r}`);
151
- }, M = async (t) => {
152
- const s = E(t), e = u(s, "salty.config.js"), { config: n } = await import(e);
153
- return n;
154
- }, et = async (t) => {
408
+ const g = Date.now();
409
+ return { contents: await import(`${y}?t=${g}`), outputFilePath: y };
410
+ }, ie = async (e) => {
411
+ const t = await v(e), s = u(t, "cache/config-cache.json"), n = M(s, "utf8");
412
+ if (!n) throw new Error("Could not find config cache file");
413
+ return JSON.parse(n);
414
+ }, dt = async (e) => {
415
+ const t = await ie(e), s = await v(e), n = u(s, "salty.config.js"), o = Date.now(), { config: r } = await import(`${n}?t=${o}`);
416
+ return I(r, t);
417
+ }, pt = () => {
155
418
  try {
156
- const s = [], e = [], n = E(t), r = u(n, "index.css");
157
- (() => {
158
- z(n) && q("rm -rf " + n), T(n), T(u(n, "css")), T(u(n, "types"));
159
- })(), await W(t);
160
- const $ = await M(t);
161
- async function a(p, h) {
162
- const b = G(p);
163
- if (b.isDirectory()) {
164
- const j = L(p);
165
- await Promise.all(j.map((w) => a(u(p, w), u(h, w))));
166
- } else if (b.isFile() && k(p)) {
167
- const w = await R(p, n), F = [];
168
- Object.entries(w).forEach(([c, m]) => {
169
- if (m.isKeyframes && m.css) {
170
- const P = `${m.animationName}.css`, J = `css/${P}`, K = u(n, J);
171
- s.push(P), C(K, m.css);
172
- return;
173
- }
174
- if (!m.generator) return;
175
- const l = m.generator._withBuildContext({
176
- name: c,
177
- config: $
178
- }), S = `${l.hash}-${l.priority}.css`;
179
- e[l.priority] || (e[l.priority] = []), e[l.priority].push(S), F.push(S);
180
- const D = `css/${S}`, N = u(n, D);
181
- C(N, l.css);
182
- });
183
- const d = F.map((c) => `@import url('./${c}');`).join(`
184
- `), x = A(p, 6), g = u(n, `css/${x}.css`);
185
- C(g, d);
419
+ return process.env.NODE_ENV === "production";
420
+ } catch {
421
+ return !1;
422
+ }
423
+ }, ae = async (e, t = pt(), s = !0) => {
424
+ try {
425
+ const n = Date.now();
426
+ t ? ct.info("Generating CSS in production mode! 🔥") : ct.info("Generating CSS in development mode! 🚀");
427
+ const o = [], r = [], i = await v(e), y = u(i, "index.css");
428
+ s && (() => {
429
+ lt(i) && Vt("rm -rf " + i), H(i, { recursive: !0 }), H(u(i, "css")), H(u(i, "types")), H(u(i, "js")), H(u(i, "cache"));
430
+ })();
431
+ const l = /* @__PURE__ */ new Set(), d = /* @__PURE__ */ new Set();
432
+ async function w(c) {
433
+ const h = ["node_modules", "saltygen"], S = Mt(c);
434
+ if (S.isDirectory()) {
435
+ const f = Rt(c);
436
+ if (h.some((_) => c.includes(_))) return;
437
+ await Promise.all(f.map((_) => w(u(c, _))));
438
+ } else if (S.isFile() && B(c)) {
439
+ l.add(c);
440
+ const b = M(c, "utf8");
441
+ /define[\w\d]+\(/.test(b) && d.add(c);
186
442
  }
187
443
  }
188
- await a(t, n);
189
- const f = s.map((p) => `@import url('./css/${p}');`).join(`
444
+ await w(e), await oe(e, d);
445
+ const g = {
446
+ keyframes: [],
447
+ components: [],
448
+ classNames: []
449
+ };
450
+ await Promise.all(
451
+ [...l].map(async (c) => {
452
+ const { contents: h } = await ot(e, c, i);
453
+ Object.entries(h).forEach(([S, f]) => {
454
+ f.isKeyframes ? g.keyframes.push({
455
+ value: f,
456
+ src: c,
457
+ name: S
458
+ }) : f.isClassName ? g.classNames.push({
459
+ ...f,
460
+ src: c,
461
+ name: S
462
+ }) : f.generator && g.components.push({
463
+ ...f,
464
+ src: c,
465
+ name: S
466
+ });
467
+ });
468
+ })
469
+ );
470
+ const m = await dt(e);
471
+ for (const c of g.keyframes) {
472
+ const { value: h } = c, S = `a_${h.animationName}.css`, f = `css/${S}`, b = u(i, f);
473
+ o.push(S), k(b, h.css);
474
+ }
475
+ const a = {};
476
+ for (const c of g.components) {
477
+ const { src: h, name: S } = c;
478
+ a[h] || (a[h] = []);
479
+ const f = c.generator._withBuildContext({
480
+ callerName: S,
481
+ isProduction: t,
482
+ config: m
483
+ });
484
+ r[f.priority] || (r[f.priority] = []);
485
+ const b = await f.css;
486
+ if (!b) continue;
487
+ r[f.priority].push(f.cssFileName);
488
+ const _ = `css/${f.cssFileName}`, T = u(i, _);
489
+ k(T, b), m.importStrategy === "component" && a[h].push(f.cssFileName);
490
+ }
491
+ for (const c of g.classNames) {
492
+ const { src: h, name: S } = c;
493
+ a[h] || (a[h] = []);
494
+ const f = c.generator._withBuildContext({
495
+ callerName: S,
496
+ isProduction: t,
497
+ config: m
498
+ }), b = await f.css;
499
+ if (!b) continue;
500
+ r[0].push(f.cssFileName);
501
+ const _ = `css/${f.cssFileName}`, T = u(i, _);
502
+ k(T, b), m.importStrategy === "component" && a[h].push(f.cssFileName);
503
+ }
504
+ m.importStrategy === "component" && Object.entries(a).forEach(([c, h]) => {
505
+ const S = h.map((G) => `@import url('./${G}');`).join(`
506
+ `), f = z(c, 6), b = nt(c), _ = A(b.name), T = u(i, `css/f_${_}-${f}.css`);
507
+ k(T, S || "/* Empty file */");
508
+ });
509
+ const p = o.map((c) => `@import url('./css/${c}');`).join(`
190
510
  `);
191
- let i = `@layer l0, l1, l2, l3, l4, l5, l6, l7, l8;
511
+ let N = `@layer reset, global, templates, l0, l1, l2, l3, l4, l5, l6, l7, l8;
192
512
 
193
- ${["@import url('./css/variables.css');", "@import url('./css/global.css');", "@import url('./css/templates.css');"].join(`
513
+ ${["_variables.css", "_reset.css", "_global.css", "_templates.css"].filter((c) => {
514
+ try {
515
+ return M(u(i, "css", c), "utf8").length > 0;
516
+ } catch {
517
+ return !1;
518
+ }
519
+ }).map((c) => `@import url('./css/${c}');`).join(`
194
520
  `)}
195
- ${f}`;
196
- if ($.importStrategy !== "component") {
197
- const p = e.flat().map((h) => `@import url('./css/${h}');`).join(`
198
- `);
199
- i += p;
521
+ ${p}`;
522
+ if (m.importStrategy !== "component") {
523
+ const c = r.reduce((h, S, f) => {
524
+ const b = S.reduce((K, L) => {
525
+ var Y;
526
+ const q = u(i, "css", L), X = M(q, "utf8"), Q = ((Y = /.*-([^-]+)-\d+.css/.exec(L)) == null ? void 0 : Y.at(1)) || z(q, 6);
527
+ return K.includes(Q) ? K : `${K}
528
+ /*start:${Q}-${L}*/
529
+ ${X}
530
+ /*end:${Q}*/
531
+ `;
532
+ }, ""), _ = `l_${f}.css`, T = u(i, "css", _), G = `@layer l${f} { ${b}
533
+ }`;
534
+ return k(T, G), `${h}
535
+ @import url('./css/${_}');`;
536
+ }, "");
537
+ N += c;
200
538
  }
201
- C(r, i);
202
- } catch (s) {
203
- console.error(s);
539
+ k(y, N);
540
+ const C = Date.now() - n, E = C < 200 ? "🔥" : C < 500 ? "🚀" : C < 1e3 ? "🎉" : C < 2e3 ? "🚗" : C < 5e3 ? "🤔" : "🥴";
541
+ ct.info(`Generated CSS in ${C}ms! ${E}`);
542
+ } catch (n) {
543
+ console.error(n);
204
544
  }
205
- }, nt = async (t, s) => {
545
+ }, ce = async (e, t, s = pt()) => {
206
546
  try {
207
- const e = [], n = u(t, "./saltygen"), r = u(n, "index.css");
208
- if (k(s)) {
209
- const $ = await M(t), a = await R(s, n);
210
- Object.entries(a).forEach(([h, b]) => {
211
- if (!b.generator) return;
212
- const j = b.generator._withBuildContext({
213
- name: h,
214
- config: $
215
- }), w = `${j.hash}-${j.priority}.css`, F = `css/${w}`, d = u(n, F);
216
- e.push(w), C(d, j.css);
217
- });
218
- const f = I(r, "utf8").split(`
219
- `), o = e.map((h) => `@import url('../saltygen/css/${h}');`), p = [.../* @__PURE__ */ new Set([...f, ...o])].join(`
220
- `);
221
- C(r, p);
547
+ const n = await v(e);
548
+ if (B(t)) {
549
+ const r = [], i = await dt(e), { contents: y } = await ot(e, t, n);
550
+ for (const [$, l] of Object.entries(y)) {
551
+ if (l.isKeyframes && l.css) {
552
+ const p = `css/${`a_${l.animationName}.css`}`, x = u(n, p);
553
+ k(x, await l.css);
554
+ return;
555
+ }
556
+ if (l.isClassName) {
557
+ const a = l.generator._withBuildContext({
558
+ callerName: $,
559
+ isProduction: s,
560
+ config: i
561
+ }), p = await a.css;
562
+ if (!p) continue;
563
+ r[0].push(a.cssFileName);
564
+ const x = `css/${a.cssFileName}`, F = u(n, x);
565
+ k(F, p);
566
+ }
567
+ if (!l.generator) return;
568
+ const d = l.generator._withBuildContext({
569
+ callerName: $,
570
+ isProduction: s,
571
+ config: i
572
+ }), w = await d.css;
573
+ if (!w) continue;
574
+ const g = `css/${d.cssFileName}`, m = u(n, g);
575
+ k(m, w), r[d.priority] || (r[d.priority] = []), r[d.priority].push(d.cssFileName);
576
+ }
577
+ if (i.importStrategy !== "component")
578
+ r.forEach(($, l) => {
579
+ const d = `l_${l}.css`, w = u(n, "css", d);
580
+ let g = M(w, "utf8");
581
+ $.forEach((m) => {
582
+ var F;
583
+ const a = u(n, "css", m), p = ((F = /.*-([^-]+)-\d+.css/.exec(m)) == null ? void 0 : F.at(1)) || z(a, 6);
584
+ if (!g.includes(p)) {
585
+ const R = M(a, "utf8"), N = `/*start:${p}-${m}*/
586
+ ${R}
587
+ /*end:${p}*/
588
+ `;
589
+ g = `${g.replace(/\}$/, "")}
590
+ ${N}
591
+ }`;
592
+ }
593
+ }), k(w, g);
594
+ });
595
+ else {
596
+ const $ = r.flat().map((m) => `@import url('./${m}');`).join(`
597
+ `), l = z(t, 6), d = nt(t), w = A(d.name), g = u(n, `css/f_${w}-${l}.css`);
598
+ k(g, $ || "/* Empty file */");
599
+ }
222
600
  }
223
- } catch (e) {
224
- console.error(e);
601
+ } catch (n) {
602
+ console.error(n);
225
603
  }
226
- }, rt = async (t, s) => {
604
+ }, le = async (e, t, s = pt()) => {
227
605
  try {
228
- const e = u(t, "./saltygen");
229
- if (k(s)) {
230
- const r = I(s, "utf8");
231
- r.replace(/^(?!export\s)const\s.*/gm, (i) => `export ${i}`) !== r && await U(s, r);
232
- const $ = await M(t), a = await R(s, e);
233
- let f = r;
234
- Object.entries(a).forEach(([i, p]) => {
235
- var d;
236
- if (p.isKeyframes) {
237
- console.log("value", p);
238
- return;
606
+ const n = await v(e);
607
+ if (B(t)) {
608
+ const r = M(t, "utf8");
609
+ r.replace(/^(?!export\s)const\s.*/gm, (d) => `export ${d}`) !== r && await At(t, r);
610
+ const y = await dt(e), { contents: $ } = await ot(e, t, n);
611
+ let l = r;
612
+ if (Object.entries($).forEach(([d, w]) => {
613
+ var f;
614
+ if (w.isKeyframes || !w.generator) return;
615
+ const g = w.generator._withBuildContext({
616
+ callerName: d,
617
+ isProduction: s,
618
+ config: y
619
+ }), m = new RegExp(`\\s${d}[=\\s]+[^()]+styled\\(([^,]+),`, "g").exec(r);
620
+ if (!m) return console.error("Could not find the original declaration");
621
+ const a = (f = m.at(1)) == null ? void 0 : f.trim(), p = new RegExp(`\\s${d}[=\\s]+styled\\(`, "g").exec(l);
622
+ if (!p) return console.error("Could not find the original declaration");
623
+ const { index: x } = p;
624
+ let F = !1;
625
+ const R = setTimeout(() => F = !0, 5e3);
626
+ let N = 0, V = !1, C = 0;
627
+ for (; !V && !F; ) {
628
+ const b = l[x + N];
629
+ b === "(" && C++, b === ")" && C--, C === 0 && b === ")" && (V = !0), N > l.length && (F = !0), N++;
239
630
  }
240
- if (!p.generator) return;
241
- const h = p.generator._withBuildContext({
242
- name: i,
243
- config: $
244
- }), b = new RegExp(`${i}[=\\s]+[^()]+styled\\(([^,]+),`, "g").exec(r);
245
- if (!b)
246
- return console.error("Could not find the original declaration");
247
- const j = (d = b.at(1)) == null ? void 0 : d.trim(), w = `${i} = styled(${j}, "${h.classNames}", "${h._callerName}", ${JSON.stringify(h.props)});`, F = new RegExp(`${i}[=\\s]+[^()]+styled\\(([^,]+),[^;]+;`, "g");
248
- f = f.replace(F, w);
249
- });
250
- const o = A(s, 6);
251
- return $.importStrategy === "component" && (f = `import '../../saltygen/css/${o}.css';
252
- ${f}`), f = f.replace("{ styled }", "{ styledClient as styled }"), f = f.replace("@salty-css/react/styled", "@salty-css/react/styled-client"), f;
631
+ if (!F) clearTimeout(R);
632
+ else throw new Error("Failed to find the end of the styled call and timed out");
633
+ const E = x + N, c = l.slice(x, E), h = l, S = ` ${d} = styled(${a}, "${g.classNames}", ${JSON.stringify(g.clientProps)});`;
634
+ l = l.replace(c, S), h === l && console.error("Minimize file failed to change content", { name: d, tagName: a });
635
+ }), y.importStrategy === "component") {
636
+ const d = z(t, 6), w = nt(t);
637
+ l = `import '../../saltygen/css/${`f_${A(w.name)}-${d}.css`}';
638
+ ${l}`;
639
+ }
640
+ return l = l.replace("{ styled }", "{ styledClient as styled }"), l = l.replace("@salty-css/react/styled", "@salty-css/react/styled-client"), l;
253
641
  }
254
- } catch (e) {
255
- console.error(e);
642
+ } catch (n) {
643
+ console.error("Error in minimizeFile:", n);
256
644
  }
257
- }, lt = (t) => ({
645
+ }, wt = async (e) => {
646
+ if (!e || e.includes("node_modules") || e.includes("saltygen")) return !1;
647
+ if (e.includes("salty.config")) return !0;
648
+ if (!B(e)) return !1;
649
+ const n = await ft(e, "utf-8");
650
+ return !!/.+define[A-Z]\w+/.test(n);
651
+ }, ye = (e) => ({
258
652
  name: "stylegen",
259
- buildStart: () => et(t),
260
- load: async (s) => {
261
- if (k(s))
262
- return await rt(t, s);
653
+ buildStart: () => ae(e),
654
+ load: async (t) => {
655
+ if (B(t))
656
+ return await le(e, t);
657
+ },
658
+ handleHotUpdate: async ({ file: t, server: s }) => {
659
+ await wt(t) && await s.restart();
263
660
  },
264
661
  watchChange: {
265
- handler: async (s) => {
266
- k(s) && await nt(t, s), s.includes("salty.config") && await W(t);
662
+ handler: async (t) => {
663
+ B(t) && (await wt(t) || await ce(e, t));
267
664
  }
268
665
  }
269
666
  });
270
667
  export {
271
- lt as saltyPlugin
668
+ ye as default,
669
+ ye as saltyPlugin
272
670
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@salty-css/vite",
3
- "version": "0.0.1-alpha.21",
3
+ "version": "0.0.1-alpha.211",
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
  },
@@ -28,7 +33,7 @@
28
33
  "require": "./index.cjs"
29
34
  }
30
35
  },
31
- "peerDependencies": {
32
- "@salty-css/core": "^0.0.1-alpha.15"
36
+ "dependencies": {
37
+ "@salty-css/core": "^0.0.1-alpha.211"
33
38
  }
34
39
  }