@salty-css/vite 0.0.1-alpha.19 → 0.0.1-alpha.191

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 +33 -14
  3. package/index.d.ts +3 -8
  4. package/index.js +482 -218
  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,37 @@
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(`
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const $e=require("esbuild"),be=require("child_process"),l=require("path"),u=require("fs"),K=require("fs/promises"),q=require("winston");var v=typeof document<"u"?document.currentScript:null;function we(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 ce=we($e),oe=e=>String.fromCharCode(e+(e>25?39:97)),Fe=(e,t)=>{let s="",n;for(n=Math.abs(e);n>52;n=n/52|0)s=oe(n%52)+s;return s=oe(n%52)+s,s.length<t?s=s.padStart(t,"a"):s.length>t&&(s=s.slice(-t)),s},Ce=(e,t)=>{let s=t.length;for(;s;)e=e*33^t.charCodeAt(--s);return e},z=(e,t=5)=>{const s=Ce(5381,JSON.stringify(e))>>>0;return Fe(s,t)};function M(e){return e?typeof e!="string"?M(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 Ne=(e,t)=>{if(typeof e!="string")return{result:e};if(!t)return{result:e};const s=[];return Object.values(t).forEach(n=>{const{pattern:i,transform:a}=n;e=e.replace(i,c=>{const{value:p,css:r}=a(c);return r&&s.push(r),p})}),{result:e,additionalCss:s}},ae=e=>typeof e!="string"?{result:e}:/\{[^{}]+\}/g.test(e)?{result:e.replace(/\{([^{}]+)\}/g,(...n)=>`var(--${M(n[1].replaceAll(".","-"))})`)}:{result:e},R=(e,t,s)=>{if(!e)return"";const n=[],i=Object.entries(e).reduce((c,[p,r])=>{const o=p.trim();if(typeof r=="function"&&(r=r()),typeof r=="object"){if(!r)return c;if(o==="variants")return Object.entries(r).forEach(([_,$])=>{$&&Object.entries($).forEach(([O,f])=>{if(!f)return;const m=`${t}.${_}-${O}`,b=R(f,m);n.push(b)})}),c;if(o==="defaultVariants")return c;if(o==="compoundVariants")return r.forEach(_=>{const{css:$,...O}=_,f=Object.entries(O).reduce((b,[d,x])=>`${b}.${d}-${x}`,t),m=R($,f);n.push(m)}),c;if(o.startsWith("@")){const _=R(r,t),$=`${o} {
2
+ ${_.replace(`
3
3
  `,`
4
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;
5
+ }`;return n.push($),c}const F=p.includes("&")?o.replace("&",t):o.startsWith(":")?`${t}${o}`:`${t} ${o}`,N=R(r,F);return n.push(N),c}const h=o.startsWith("-")?o:M(o),y=(F,N=";")=>c=`${c}${F}${N}`,g=F=>y(`${h}:${F}`);if(typeof r=="number")return g(r);if(typeof r!="string")if("toString"in r)r=r.toString();else return c;const{modifiers:j}={},D=function*(){yield ae(r),yield Ne(r,j)}();for(const{result:F,additionalCss:N=[]}of D)r=F,N.forEach(_=>{const $=R(_,"");y($,"")});return g(r)},"");return i?t?[`${t} { ${i} }`,...n].join(`
6
+ `):i:n.join(`
7
+ `)},le=(e,t=[])=>{if(!e)return"";const s=[],n={};if(Object.entries(e).forEach(([i,a])=>{if(typeof a=="object"){if(!a)return;const c=i.trim(),p=le(a,[...t,c]);s.push(p)}else n[i]=a}),Object.keys(n).length){const i=t.map(M).join("-"),a=R(n,`.${i}`);s.push(a)}return s.join(`
8
+ `)},xe=e=>e?Object.entries(e).reduce((t,[s,n])=>(typeof n=="object"&&(t[s]=fe(n).map(i=>`"${i}"`).join(" | ")),t),{}):{},fe=(e,t="",s=new Set)=>e?(Object.entries(e).forEach(([n,i])=>{const a=t?`${t}.${n}`:n;return typeof i=="object"?fe(i,a,s):s.add(t)}),[...s]):[],ue=e=>{if(!e||e==="/")throw new Error("Could not find package.json file");const t=l.join(e,"package.json");return u.existsSync(t)?t:ue(l.join(e,".."))},ke=async e=>{const t=ue(e);return await K.readFile(t,"utf-8").then(JSON.parse).catch(()=>{})},Pe=async e=>{const t=await ke(e);if(t)return t.type};let A;const de=async e=>{if(A)return A;const t=await Pe(e);return t==="module"?A="esm":(t==="commonjs"||(typeof document>"u"?require("url").pathToFileURL(__filename).href:v&&v.tagName.toUpperCase()==="SCRIPT"&&v.src||new URL("index.cjs",document.baseURI).href).endsWith(".cjs"))&&(A="cjs"),A||"esm"},ee=q.createLogger({level:"debug",format:q.format.combine(q.format.colorize(),q.format.cli()),transports:[new q.transports.Console({})]});function pe(e){return e?typeof e!="string"?pe(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 _e={"*, *::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"}},W=(...e)=>e.flat().reduce((t,s)=>s!=null&&s._current?{...t,...s._current}:{...t,...s},{}),E={externalModules:[],rcFile:void 0,destDir:void 0},ye=e=>{if(E.externalModules.length>0)return E.externalModules;const s=u.readFileSync(e,"utf8").match(/externalModules:\s?\[(.*)\]/);if(!s)return[];const n=s[1].split(",").map(i=>i.replace(/['"`]/g,"").trim());return E.externalModules=n,n},J=async e=>{if(E.destDir)return E.destDir;const t=await te(e),s=l.join(e,(t==null?void 0:t.saltygenDir)||"saltygen");return E.destDir=s,s},ge=["salty","css","styles","styled"],De=(e=[])=>new RegExp(`\\.(${[...ge,...e].join("|")})\\.`),Z=(e,t=[])=>De(t).test(e),he=async e=>{if(E.rcFile)return E.rcFile;if(e==="/")throw new Error("Could not find .saltyrc.json file");const t=l.join(e,".saltyrc.json"),s=await K.readFile(t,"utf-8").then(JSON.parse).catch(()=>{});return s?(E.rcFile=s,s):he(l.join(e,".."))},te=async e=>{var n,i;const t=await he(e),s=(n=t.projects)==null?void 0:n.find(a=>e.endsWith(a.dir||""));return s||((i=t.projects)==null?void 0:i.find(a=>a.dir===t.defaultProject))},Te=async e=>{const t=await te(e),s=await J(e),n=l.join(e,(t==null?void 0:t.configDir)||"","salty.config.ts"),i=l.join(s,"salty.config.js"),a=await de(e),c=ye(n);await ce.build({entryPoints:[n],minify:!0,treeShaking:!0,bundle:!0,outfile:i,format:a,external:c});const p=Date.now(),{config:r}=await import(`${i}?t=${p}`);return r},Oe=async(e,t)=>{var H,G;const s=await Te(e),n={...s},i=new Set,a=(C,k=[])=>C?Object.entries(C).flatMap(([V,T])=>{if(!T)return;if(typeof T=="object")return a(T,[...k,V]);const U=pe(V),Q=M(V),X=[...k,U].join(".");i.add(`"${X}"`);const Y=[...k.map(M),Q].join("-"),{result:je}=ae(T);return`--${Y}: ${je};`}):[],c=C=>C?Object.entries(C).flatMap(([k,V])=>{const T=a(V);return k==="base"?T.join(""):`${k} { ${T.join("")} }`}):[],p=C=>C?Object.entries(C).flatMap(([k,V])=>Object.entries(V).flatMap(([T,U])=>{const Q=a(U,[k]),X=`.${k}-${T}, [data-${k}="${T}"]`,Y=Q.join("");return`${X} { ${Y} }`})):[],r=C=>({...C,responsive:void 0,conditional:void 0}),o=C=>t.variables.map(k=>C==="static"?r(k._current):k._current[C]),h=a(W(r(s.variables),o("static"))),y=c(W((H=s.variables)==null?void 0:H.responsive,o("responsive"))),g=p(W((G=s.variables)==null?void 0:G.conditional,o("conditional"))),j=await J(e),P=l.join(j,"css/_variables.css"),D=`:root { ${h.join("")} ${y.join("")} } ${g.join("")}`;u.writeFileSync(P,D);const F=l.join(j,"css/_global.css"),N=W(s.global,t.globalStyles),_=R(N,"");u.writeFileSync(F,`@layer global { ${_} }`);const $=l.join(j,"css/_reset.css"),f=s.reset==="none"?{}:typeof s.reset=="object"?s.reset:_e,m=R(f,"");u.writeFileSync($,`@layer reset { ${m} }`);const b=l.join(j,"css/_templates.css"),d=W(s.templates,t.templates),x=le(d),w=xe(d);u.writeFileSync(b,x),n.templates=d;const S=l.join(j,"types/css-tokens.d.ts"),I=`
9
+ // Variable types
10
+ type VariableTokens = ${[...i].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(w).map(([C,k])=>`${C}?: ${k}`).join(`
13
16
  `)}
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;
17
+ }
18
+ `;u.writeFileSync(S,I);const B=l.join(j,"cache/config-cache.json");u.writeFileSync(B,JSON.stringify(n,null,2))},re=e=>e.replace(/styled\(([^"'`{,]+),/g,(t,s)=>{if(/^['"`]/.test(s))return t;const i=new RegExp(`import[^;]*${s}[,\\s{][^;]*from\\s?([^{};]+);`);if(!i.test(e))return t;const c=i.exec(e);if(c){const p=c.at(1);if(ge.some(o=>p==null?void 0:p.includes(o)))return t}return"styled('div',"}),se=async(e,t,s)=>{const n=z(t),i=l.join(s,"./temp");u.existsSync(i)||u.mkdirSync(i);const a=l.parse(t);let c=u.readFileSync(t,"utf8");c=re(c);const p=l.join(s,"js",n+".js"),r=await te(e),o=l.join(e,(r==null?void 0:r.configDir)||"","salty.config.ts"),h=ye(o),y=await de(e);await ce.build({stdin:{contents:c,sourcefile:a.base,resolveDir:a.dir,loader:"tsx"},minify:!1,treeShaking:!0,bundle:!0,outfile:p,format:y,target:["node20"],keepNames:!0,external:h,packages:"external",plugins:[{name:"test",setup:P=>{P.onLoad({filter:/.*\.css|salty|styles|styled\.ts/},D=>{const F=u.readFileSync(D.path,"utf8");return{contents:re(F),loader:"ts"}})}}]});const g=Date.now();return await import(`${p}?t=${g}`)},Ee=async e=>{const t=await J(e),s=l.join(t,"cache/config-cache.json"),n=u.readFileSync(s,"utf8");if(!n)throw new Error("Could not find config cache file");return JSON.parse(n)},ne=async e=>{const t=await Ee(e),s=await J(e),n=l.join(s,"salty.config.js"),i=Date.now(),{config:a}=await import(`${n}?t=${i}`);return W(a,t)},me=()=>{try{return process.env.NODE_ENV==="production"}catch{return!1}},Me=async(e,t=me(),s=!0)=>{try{const n=Date.now();t?ee.info("Generating CSS in production mode! 🔥"):ee.info("Generating CSS in development mode! 🚀");const i=[],a=[],c=await J(e),p=l.join(c,"index.css");s&&(()=>{u.existsSync(c)&&be.execSync("rm -rf "+c),u.mkdirSync(c,{recursive:!0}),u.mkdirSync(l.join(c,"css")),u.mkdirSync(l.join(c,"types")),u.mkdirSync(l.join(c,"js")),u.mkdirSync(l.join(c,"cache"))})();const o={keyframes:[],mediaQueries:[],globalStyles:[],variables:[],templates:[],components:[],classNames:[]};async function h(f){const m=["node_modules","saltygen"],b=u.statSync(f);if(b.isDirectory()){const d=u.readdirSync(f);if(m.some(w=>f.includes(w)))return;await Promise.all(d.map(w=>h(l.join(f,w))))}else if(b.isFile()&&Z(f)){const x=await se(e,f,c);Object.entries(x).forEach(([w,S])=>{S.isKeyframes?o.keyframes.push({value:S,src:f,name:w}):S.isMedia?o.mediaQueries.push(S):S.isGlobalDefine?o.globalStyles.push(S):S.isDefineVariables?o.variables.push(S):S.isDefineTemplates?o.templates.push(S):S.isClassName?o.classNames.push({...S,src:f,name:w}):S.generator&&o.components.push({...S,src:f,name:w})})}}await h(e),await Oe(e,o);const y=await ne(e);for(const f of o.keyframes){const{value:m}=f,b=`a_${m.animationName}.css`,d=`css/${b}`,x=l.join(c,d);i.push(b),u.writeFileSync(x,m.css)}const g={};for(const f of o.components){const{src:m,name:b}=f,d=f.generator._withBuildContext({callerName:b,isProduction:t,config:y});a[d.priority]||(a[d.priority]=[]),a[d.priority].push(d.cssFileName);const x=`css/${d.cssFileName}`,w=l.join(c,x);u.writeFileSync(w,d.css),y.importStrategy==="component"&&(g[m]?g[m].push(d.cssFileName):g[m]=[d.cssFileName])}for(const f of o.classNames){const{src:m,name:b}=f,d=f.generator._withBuildContext({callerName:b,isProduction:t,config:y});a[0].push(d.cssFileName);const x=`css/${d.cssFileName}`,w=l.join(c,x);u.writeFileSync(w,d.css),y.importStrategy==="component"&&(g[m]?g[m].push(d.cssFileName):g[m]=[d.cssFileName])}y.importStrategy==="component"&&Object.entries(g).forEach(([f,m])=>{const b=m.map(L=>`@import url('./${L}');`).join(`
19
+ `),d=z(f,6),x=l.parse(f),w=M(x.name),S=l.join(c,`css/f_${w}-${d}.css`);u.writeFileSync(S,b)});const j=i.map(f=>`@import url('./css/${f}');`).join(`
20
+ `);let N=`@layer reset, global, l0, l1, l2, l3, l4, l5, l6, l7, l8;
21
+
22
+ ${["_variables.css","_reset.css","_global.css","_templates.css"].filter(f=>{try{return u.readFileSync(l.join(c,"css",f),"utf8").length>0}catch{return!1}}).map(f=>`@import url('./css/${f}');`).join(`
23
+ `)}
24
+ ${j}`;if(y.importStrategy!=="component"){const f=a.reduce((m,b,d)=>{const x=b.reduce((I,B)=>{var k;const H=l.join(c,"css",B),G=u.readFileSync(H,"utf8"),C=((k=/.*-([^-]+)-\d+.css/.exec(B))==null?void 0:k.at(1))||z(H,6);return I.includes(C)?I:`${I}
25
+ /*start:${C}*/
26
+ ${G}
27
+ /*end:${C}*/
28
+ `},""),w=`l_${d}.css`,S=l.join(c,"css",w),L=`@layer l${d} { ${x}
29
+ }`;return u.writeFileSync(S,L),`${m}
30
+ @import url('./css/${w}');`},"");N+=f}u.writeFileSync(p,N);const $=Date.now()-n,O=$<200?"🔥":$<500?"🚀":$<1e3?"🎉":$<2e3?"🚗":$<5e3?"🤔":"🥴";ee.info(`Generated CSS in ${$}ms! ${O}`)}catch(n){console.error(n)}},Re=async(e,t)=>{try{const s=await J(e);if(Z(t)){const i=[],a=await ne(e),c=await se(e,t,s);if(Object.entries(c).forEach(([p,r])=>{if(r.isKeyframes&&r.css){const j=`css/${`a_${r.animationName}.css`}`,P=l.join(s,j);u.writeFileSync(P,r.css);return}if(r.isClassName){const g=r.factory._withBuildContext({name:p});i[0].push(g.cssFileName);const j=`css/${g.cssFileName}`,P=l.join(s,j);u.writeFileSync(P,g.css)}if(!r.generator)return;const o=r.generator._withBuildContext({name:p,config:a}),h=`css/${o.cssFileName}`,y=l.join(s,h);u.writeFileSync(y,o.css),i[o.priority]||(i[o.priority]=[]),i[o.priority].push(o.cssFileName)}),a.importStrategy!=="component")i.forEach((p,r)=>{const o=`l_${r}.css`,h=l.join(s,"css",o);let y=u.readFileSync(h,"utf8");p.forEach(g=>{var F;const j=l.join(s,"css",g),P=((F=/.*-([^-]+)-\d+.css/.exec(g))==null?void 0:F.at(1))||z(j,6);if(!y.includes(P)){const N=u.readFileSync(j,"utf8"),_=`/*start:${P}*/
31
+ ${N}
32
+ /*end:${P}*/
33
+ `;y=`${y.replace(/\}$/,"")}
34
+ ${_}
35
+ }`}}),u.writeFileSync(h,y)});else{const p=i.flat().map(g=>`@import url('./${g}');`).join(`
36
+ `),r=z(t,6),o=l.parse(t),h=M(o.name),y=l.join(s,`css/f_${h}-${r}.css`);u.writeFileSync(y,p)}}}catch(s){console.error(s)}},Ve=async(e,t,s=me())=>{try{const n=await J(e);if(Z(t)){const a=u.readFileSync(t,"utf8");a.replace(/^(?!export\s)const\s.*/gm,h=>`export ${h}`)!==a&&await K.writeFile(t,a);const p=await ne(e),r=await se(e,t,n);let o=a;if(Object.entries(r).forEach(([h,y])=>{var w;if(y.isKeyframes||!y.generator)return;const g=y.generator._withBuildContext({name:h,config:p,prod:s}),j=new RegExp(`\\s${h}[=\\s]+[^()]+styled\\(([^,]+),`,"g").exec(a);if(!j)return console.error("Could not find the original declaration");const P=(w=j.at(1))==null?void 0:w.trim(),D=new RegExp(`\\s${h}[=\\s]+styled\\(`,"g").exec(o);if(!D)return console.error("Could not find the original declaration");const{index:F}=D;let N=!1;const _=setTimeout(()=>N=!0,5e3);let $=0,O=!1,f=0;for(;!O&&!N;){const S=o[F+$];S==="("&&f++,S===")"&&f--,f===0&&S===")"&&(O=!0),$>o.length&&(N=!0),$++}if(!N)clearTimeout(_);else throw new Error("Failed to find the end of the styled call and timed out");const m=F+$,b=o.slice(F,m),d=o,x=` ${h} = styled(${P}, "${g.classNames}", ${JSON.stringify(g.clientProps)});`;o=o.replace(b,x),d===o&&console.error("Minimize file failed to change content",{name:h,tagName:P})}),p.importStrategy==="component"){const h=z(t,6),y=l.parse(t);o=`import '../../saltygen/css/${`f_${M(y.name)}-${h}.css`}';
37
+ ${o}`}return o=o.replace("{ styled }","{ styledClient as styled }"),o=o.replace("@salty-css/react/styled","@salty-css/react/styled-client"),o}}catch(n){console.error("Error in minimizeFile:",n)}},ie=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 K.readFile(e,"utf-8");return!!/.+define[A-Z]\w+/.test(n)},Se=e=>({name:"stylegen",buildStart:()=>Me(e),load:async t=>{if(Z(t))return await Ve(e,t)},handleHotUpdate:async({file:t,server:s})=>{await ie(t)&&await s.restart()},watchChange:{handler:async t=>{Z(t)&&(await ie(t)||await Re(e,t))}}});exports.default=Se;exports.saltyPlugin=Se;
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,536 @@
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);
1
+ import * as ft from "esbuild";
2
+ import { execSync as Ct } from "child_process";
3
+ import { join as f, parse as Q } from "path";
4
+ import { existsSync as st, mkdirSync as z, statSync as jt, readdirSync as Ft, writeFileSync as k, readFileSync as V } from "fs";
5
+ import { readFile as nt, writeFile as Nt } from "fs/promises";
6
+ import { createLogger as xt, format as tt, transports as kt } from "winston";
7
+ const ct = (t) => String.fromCharCode(t + (t > 25 ? 39 : 97)), Pt = (t, e) => {
8
+ let s = "", n;
9
+ for (n = Math.abs(t); n > 52; n = n / 52 | 0) s = ct(n % 52) + s;
10
+ return s = ct(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);
13
14
  return t;
14
- }, A = (t, s = 3) => {
15
- const e = Y(5381, JSON.stringify(t)) >>> 0;
16
- return X(e, s);
15
+ }, H = (t, e = 5) => {
16
+ const s = Dt(5381, JSON.stringify(t)) >>> 0;
17
+ return Pt(s, e);
17
18
  };
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()) : "";
19
+ function M(t) {
20
+ return t ? typeof t != "string" ? M(String(t)) : t.replace(/[\s.]/g, "-").replace(/[A-Z](?:(?=[^A-Z])|[A-Z]*(?=[A-Z][^A-Z]|$))/g, (e, s) => (s > 0 ? "-" : "") + e.toLowerCase()) : "";
20
21
  }
21
- const Q = (t, s) => {
22
+ const Et = (t, e) => {
22
23
  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;
24
+ if (!e) return { result: t };
25
+ const s = [];
26
+ return Object.values(e).forEach((n) => {
27
+ const { pattern: i, transform: a } = n;
28
+ t = t.replace(i, (c) => {
29
+ const { value: p, css: r } = a(c);
30
+ return r && s.push(r), p;
30
31
  });
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) => {
32
+ }), { result: t, additionalCss: s };
33
+ }, ut = (t) => typeof t != "string" ? { result: t } : /\{[^{}]+\}/g.test(t) ? { result: t.replace(/\{([^{}]+)\}/g, (...n) => `var(--${M(n[1].replaceAll(".", "-"))})`) } : { result: t }, R = (t, e, s) => {
33
34
  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]) => {
35
+ const n = [], i = Object.entries(t).reduce((c, [p, r]) => {
36
+ const o = p.trim();
37
+ if (typeof r == "function" && (r = r()), typeof r == "object") {
38
+ if (!r) return c;
39
+ if (o === "variants")
40
+ return Object.entries(r).forEach(([D, b]) => {
41
+ b && Object.entries(b).forEach(([T, l]) => {
41
42
  if (!l) return;
42
- const S = `${s}.${g}-${m}`, D = O(l, S);
43
- r.push(D);
43
+ const m = `${e}.${D}-${T}`, w = R(l, m);
44
+ n.push(w);
44
45
  });
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(`
46
+ }), c;
47
+ if (o === "defaultVariants")
48
+ return c;
49
+ if (o === "compoundVariants")
50
+ return r.forEach((D) => {
51
+ const { css: b, ...T } = D, l = Object.entries(T).reduce((w, [u, N]) => `${w}.${u}-${N}`, e), m = R(b, l);
52
+ n.push(m);
53
+ }), c;
54
+ if (o.startsWith("@")) {
55
+ const D = R(r, e), b = `${o} {
56
+ ${D.replace(`
56
57
  `, `
57
58
  `)}
58
59
  }`;
59
- return r.push(c), a;
60
+ return n.push(b), c;
60
61
  }
61
- const d = f.includes("&") ? i.replace("&", s) : i.startsWith(":") ? `${s}${i}` : `${s} ${i}`, x = O(o, d);
62
- return r.push(x), a;
62
+ const C = p.includes("&") ? o.replace("&", e) : o.startsWith(":") ? `${e}${o}` : `${e} ${o}`, F = R(r, C);
63
+ return n.push(F), c;
63
64
  }
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);
65
+ const h = o.startsWith("-") ? o : M(o), d = (C, F = ";") => c = `${c}${C}${F}`, g = (C) => d(`${h}:${C}`);
66
+ if (typeof r == "number") return g(r);
67
+ if (typeof r != "string")
68
+ if ("toString" in r) r = r.toString();
69
+ else return c;
70
+ const { modifiers: $ } = {}, E = function* () {
71
+ yield ut(r), yield Et(r, $);
71
72
  }();
72
- for (const { result: d, additionalCss: x = [] } of F)
73
- o = d, x.forEach((g) => {
74
- const c = O(g, "");
75
- h(c, "");
73
+ for (const { result: C, additionalCss: F = [] } of E)
74
+ r = C, F.forEach((D) => {
75
+ const b = R(D, "");
76
+ d(b, "");
76
77
  });
77
- return b(o);
78
+ return g(r);
78
79
  }, "");
79
- if (!y) return r.join(`
80
+ return i ? e ? [`${e} { ${i} }`, ...n].join(`
81
+ `) : i : n.join(`
80
82
  `);
81
- if (!s) return y;
82
- let $ = "";
83
- return $ = `${s} { ${y} }`, [$, ...r].join(`
84
- `);
85
- }, H = (t, s = []) => {
83
+ }, pt = (t, e = []) => {
86
84
  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);
85
+ const s = [], n = {};
86
+ if (Object.entries(t).forEach(([i, a]) => {
87
+ if (typeof a == "object") {
88
+ if (!a) return;
89
+ const c = i.trim(), p = pt(a, [...e, c]);
90
+ s.push(p);
93
91
  } else
94
- n[r] = y;
92
+ n[i] = a;
95
93
  }), Object.keys(n).length) {
96
- const r = s.map(V).join("-"), y = O(n, `.${r}`);
97
- e.push(y);
94
+ const i = e.map(M).join("-"), a = R(n, `.${i}`);
95
+ s.push(a);
98
96
  }
99
- return e.join(`
97
+ return s.join(`
100
98
  `);
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],
99
+ }, _t = (t) => t ? Object.entries(t).reduce((e, [s, n]) => (typeof n == "object" && (e[s] = dt(n).map((i) => `"${i}"`).join(" | ")), e), {}) : {}, dt = (t, e = "", s = /* @__PURE__ */ new Set()) => t ? (Object.entries(t).forEach(([n, i]) => {
100
+ const a = e ? `${e}.${n}` : n;
101
+ return typeof i == "object" ? dt(i, a, s) : s.add(e);
102
+ }), [...s]) : [], gt = (t) => {
103
+ if (!t || t === "/") throw new Error("Could not find package.json file");
104
+ const e = f(t, "package.json");
105
+ return st(e) ? e : gt(f(t, ".."));
106
+ }, Tt = async (t) => {
107
+ const e = gt(t);
108
+ return await nt(e, "utf-8").then(JSON.parse).catch(() => {
109
+ });
110
+ }, Ot = async (t) => {
111
+ const e = await Tt(t);
112
+ if (e)
113
+ return e.type;
114
+ };
115
+ let W;
116
+ const ht = async (t) => {
117
+ if (W) return W;
118
+ const e = await Ot(t);
119
+ return e === "module" ? W = "esm" : (e === "commonjs" || import.meta.url.endsWith(".cjs")) && (W = "cjs"), W || "esm";
120
+ }, et = xt({
121
+ level: "debug",
122
+ format: tt.combine(tt.colorize(), tt.cli()),
123
+ transports: [new kt.Console({})]
124
+ });
125
+ function mt(t) {
126
+ return t ? typeof t != "string" ? mt(String(t)) : t.replace(/[\s-]/g, ".").replace(/[A-Z](?:(?=[^A-Z])|[A-Z]*(?=[A-Z][^A-Z]|$))/g, (e, s) => (s > 0 ? "." : "") + e.toLowerCase()) : "";
127
+ }
128
+ const Vt = {
129
+ /** Set box model to border-box */
130
+ "*, *::before, *::after": {
131
+ boxSizing: "border-box"
132
+ },
133
+ /** Remove default margin and padding */
134
+ "*": {
135
+ margin: 0
136
+ },
137
+ /** Remove adjust font properties */
138
+ html: {
139
+ lineHeight: 1.15,
140
+ textSizeAdjust: "100%",
141
+ WebkitFontSmoothing: "antialiased"
142
+ },
143
+ /** Make media elements responsive */
144
+ "img, picture, video, canvas, svg": {
145
+ display: "block",
146
+ maxWidth: "100%"
147
+ },
148
+ /** Avoid overflow of text */
149
+ "p, h1, h2, h3, h4, h5, h6": {
150
+ overflowWrap: "break-word"
151
+ },
152
+ /** Improve text wrapping */
153
+ p: {
154
+ textWrap: "pretty"
155
+ },
156
+ "h1, h2, h3, h4, h5, h6": {
157
+ textWrap: "balance"
158
+ },
159
+ /** Improve link color */
160
+ a: {
161
+ color: "currentColor"
162
+ },
163
+ /** Improve button line height */
164
+ button: {
165
+ lineHeight: "1em",
166
+ color: "currentColor"
167
+ },
168
+ /** Improve form elements */
169
+ "input, optgroup, select, textarea": {
170
+ fontFamily: "inherit",
171
+ fontSize: "100%",
172
+ lineHeight: "1.15em"
173
+ }
174
+ }, Z = (...t) => t.flat().reduce((e, s) => s != null && s._current ? { ...e, ...s._current } : { ...e, ...s }, {}), O = {
175
+ externalModules: [],
176
+ rcFile: void 0,
177
+ destDir: void 0
178
+ }, yt = (t) => {
179
+ if (O.externalModules.length > 0) return O.externalModules;
180
+ const s = V(t, "utf8").match(/externalModules:\s?\[(.*)\]/);
181
+ if (!s) return [];
182
+ const n = s[1].split(",").map((i) => i.replace(/['"`]/g, "").trim());
183
+ return O.externalModules = n, n;
184
+ }, A = async (t) => {
185
+ if (O.destDir) return O.destDir;
186
+ const e = await ot(t), s = f(t, (e == null ? void 0 : e.saltygenDir) || "saltygen");
187
+ return O.destDir = s, s;
188
+ }, $t = ["salty", "css", "styles", "styled"], Mt = (t = []) => new RegExp(`\\.(${[...$t, ...t].join("|")})\\.`), I = (t, e = []) => Mt(e).test(t), bt = async (t) => {
189
+ if (O.rcFile) return O.rcFile;
190
+ if (t === "/") throw new Error("Could not find .saltyrc.json file");
191
+ const e = f(t, ".saltyrc.json"), s = await nt(e, "utf-8").then(JSON.parse).catch(() => {
192
+ });
193
+ return s ? (O.rcFile = s, s) : bt(f(t, ".."));
194
+ }, ot = async (t) => {
195
+ var n, i;
196
+ const e = await bt(t), s = (n = e.projects) == null ? void 0 : n.find((a) => t.endsWith(a.dir || ""));
197
+ return s || ((i = e.projects) == null ? void 0 : i.find((a) => a.dir === e.defaultProject));
198
+ }, Rt = async (t) => {
199
+ const e = await ot(t), s = await A(t), n = f(t, (e == null ? void 0 : e.configDir) || "", "salty.config.ts"), i = f(s, "salty.config.js"), a = await ht(t), c = yt(n);
200
+ await ft.build({
201
+ entryPoints: [n],
105
202
  minify: !0,
106
203
  treeShaking: !0,
107
204
  bundle: !0,
108
- outfile: n,
109
- format: "esm",
110
- external: ["react"]
205
+ outfile: i,
206
+ format: a,
207
+ external: c
111
208
  });
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,
209
+ const p = Date.now(), { config: r } = await import(`${i}?t=${p}`);
210
+ return r;
211
+ }, Jt = async (t, e) => {
212
+ var G, q;
213
+ const s = await Rt(t), n = { ...s }, i = /* @__PURE__ */ new Set(), a = (j, x = []) => j ? Object.entries(j).flatMap(([J, _]) => {
214
+ if (!_) return;
215
+ if (typeof _ == "object") return a(_, [...x, J]);
216
+ const U = mt(J), X = M(J), Y = [...x, U].join(".");
217
+ i.add(`"${Y}"`);
218
+ const v = [...x.map(M), X].join("-"), { result: St } = ut(_);
219
+ return `--${v}: ${St};`;
220
+ }) : [], c = (j) => j ? Object.entries(j).flatMap(([x, J]) => {
221
+ const _ = a(J);
222
+ return x === "base" ? _.join("") : `${x} { ${_.join("")} }`;
223
+ }) : [], p = (j) => j ? Object.entries(j).flatMap(([x, J]) => Object.entries(J).flatMap(([_, U]) => {
224
+ const X = a(U, [x]), Y = `.${x}-${_}, [data-${x}="${_}"]`, v = X.join("");
225
+ return `${Y} { ${v} }`;
226
+ })) : [], r = (j) => ({ ...j, responsive: void 0, conditional: void 0 }), o = (j) => e.variables.map((x) => j === "static" ? r(x._current) : x._current[j]), h = a(Z(r(s.variables), o("static"))), d = c(Z((G = s.variables) == null ? void 0 : G.responsive, o("responsive"))), g = p(Z((q = s.variables) == null ? void 0 : q.conditional, o("conditional"))), $ = await A(t), P = f($, "css/_variables.css"), E = `:root { ${h.join("")} ${d.join("")} } ${g.join("")}`;
227
+ k(P, E);
228
+ const C = f($, "css/_global.css"), F = Z(s.global, e.globalStyles), D = R(F, "");
229
+ k(C, `@layer global { ${D} }`);
230
+ const b = f($, "css/_reset.css"), l = s.reset === "none" ? {} : typeof s.reset == "object" ? s.reset : Vt, m = R(l, "");
231
+ k(b, `@layer reset { ${m} }`);
232
+ const w = f($, "css/_templates.css"), u = Z(s.templates, e.templates), N = pt(u), S = _t(u);
233
+ k(w, N), n.templates = u;
234
+ const y = f($, "types/css-tokens.d.ts"), B = `
235
+ // Variable types
236
+ type VariableTokens = ${[...i].join("|")};
237
+ type PropertyValueToken = \`{\${VariableTokens}}\`;
238
+
239
+ // Template types
240
+ type TemplateTokens = {
241
+ ${Object.entries(S).map(([j, x]) => `${j}?: ${x}`).join(`
242
+ `)}
243
+ }
244
+ `;
245
+ k(y, B);
246
+ const K = f($, "cache/config-cache.json");
247
+ k(K, JSON.stringify(n, null, 2));
248
+ }, at = (t) => t.replace(/styled\(([^"'`{,]+),/g, (e, s) => {
249
+ if (/^['"`]/.test(s)) return e;
250
+ const i = new RegExp(`import[^;]*${s}[,\\s{][^;]*from\\s?([^{};]+);`);
251
+ if (!i.test(t)) return e;
252
+ const c = i.exec(t);
253
+ if (c) {
254
+ const p = c.at(1);
255
+ if ($t.some((o) => p == null ? void 0 : p.includes(o))) return e;
256
+ }
257
+ return "styled('div',";
258
+ }), rt = async (t, e, s) => {
259
+ const n = H(e), i = f(s, "./temp");
260
+ st(i) || z(i);
261
+ const a = Q(e);
262
+ let c = V(e, "utf8");
263
+ c = at(c);
264
+ const p = f(s, "js", n + ".js"), r = await ot(t), o = f(t, (r == null ? void 0 : r.configDir) || "", "salty.config.ts"), h = yt(o), d = await ht(t);
265
+ await ft.build({
266
+ stdin: {
267
+ contents: c,
268
+ sourcefile: a.base,
269
+ resolveDir: a.dir,
270
+ loader: "tsx"
271
+ },
272
+ minify: !1,
141
273
  treeShaking: !0,
142
274
  bundle: !0,
143
- outfile: n,
144
- format: "esm",
145
- target: ["es2022"],
275
+ outfile: p,
276
+ format: d,
277
+ target: ["node20"],
146
278
  keepNames: !0,
147
- external: ["react"]
279
+ external: h,
280
+ packages: "external",
281
+ plugins: [
282
+ {
283
+ name: "test",
284
+ setup: (P) => {
285
+ P.onLoad({ filter: /.*\.css|salty|styles|styled\.ts/ }, (E) => {
286
+ const C = V(E.path, "utf8");
287
+ return { contents: at(C), loader: "ts" };
288
+ });
289
+ }
290
+ }
291
+ ]
148
292
  });
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) => {
293
+ const g = Date.now();
294
+ return await import(`${p}?t=${g}`);
295
+ }, At = async (t) => {
296
+ const e = await A(t), s = f(e, "cache/config-cache.json"), n = V(s, "utf8");
297
+ if (!n) throw new Error("Could not find config cache file");
298
+ return JSON.parse(n);
299
+ }, it = async (t) => {
300
+ const e = await At(t), s = await A(t), n = f(s, "salty.config.js"), i = Date.now(), { config: a } = await import(`${n}?t=${i}`);
301
+ return Z(a, e);
302
+ }, wt = () => {
155
303
  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);
304
+ return process.env.NODE_ENV === "production";
305
+ } catch {
306
+ return !1;
307
+ }
308
+ }, Wt = async (t, e = wt(), s = !0) => {
309
+ try {
310
+ const n = Date.now();
311
+ e ? et.info("Generating CSS in production mode! 🔥") : et.info("Generating CSS in development mode! 🚀");
312
+ const i = [], a = [], c = await A(t), p = f(c, "index.css");
313
+ s && (() => {
314
+ st(c) && Ct("rm -rf " + c), z(c, { recursive: !0 }), z(f(c, "css")), z(f(c, "types")), z(f(c, "js")), z(f(c, "cache"));
315
+ })();
316
+ const o = {
317
+ keyframes: [],
318
+ mediaQueries: [],
319
+ globalStyles: [],
320
+ variables: [],
321
+ templates: [],
322
+ components: [],
323
+ classNames: []
324
+ };
325
+ async function h(l) {
326
+ const m = ["node_modules", "saltygen"], w = jt(l);
327
+ if (w.isDirectory()) {
328
+ const u = Ft(l);
329
+ if (m.some((S) => l.includes(S))) return;
330
+ await Promise.all(u.map((S) => h(f(l, S))));
331
+ } else if (w.isFile() && I(l)) {
332
+ const N = await rt(t, l, c);
333
+ Object.entries(N).forEach(([S, y]) => {
334
+ y.isKeyframes ? o.keyframes.push({
335
+ value: y,
336
+ src: l,
337
+ name: S
338
+ }) : y.isMedia ? o.mediaQueries.push(y) : y.isGlobalDefine ? o.globalStyles.push(y) : y.isDefineVariables ? o.variables.push(y) : y.isDefineTemplates ? o.templates.push(y) : y.isClassName ? o.classNames.push({
339
+ ...y,
340
+ src: l,
341
+ name: S
342
+ }) : y.generator && o.components.push({
343
+ ...y,
344
+ src: l,
345
+ name: S
346
+ });
182
347
  });
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);
186
348
  }
187
349
  }
188
- await a(t, n);
189
- const f = s.map((p) => `@import url('./css/${p}');`).join(`
350
+ await h(t), await Jt(t, o);
351
+ const d = await it(t);
352
+ for (const l of o.keyframes) {
353
+ const { value: m } = l, w = `a_${m.animationName}.css`, u = `css/${w}`, N = f(c, u);
354
+ i.push(w), k(N, m.css);
355
+ }
356
+ const g = {};
357
+ for (const l of o.components) {
358
+ const { src: m, name: w } = l, u = l.generator._withBuildContext({
359
+ callerName: w,
360
+ isProduction: e,
361
+ config: d
362
+ });
363
+ a[u.priority] || (a[u.priority] = []), a[u.priority].push(u.cssFileName);
364
+ const N = `css/${u.cssFileName}`, S = f(c, N);
365
+ k(S, u.css), d.importStrategy === "component" && (g[m] ? g[m].push(u.cssFileName) : g[m] = [u.cssFileName]);
366
+ }
367
+ for (const l of o.classNames) {
368
+ const { src: m, name: w } = l, u = l.generator._withBuildContext({
369
+ callerName: w,
370
+ isProduction: e,
371
+ config: d
372
+ });
373
+ a[0].push(u.cssFileName);
374
+ const N = `css/${u.cssFileName}`, S = f(c, N);
375
+ k(S, u.css), d.importStrategy === "component" && (g[m] ? g[m].push(u.cssFileName) : g[m] = [u.cssFileName]);
376
+ }
377
+ d.importStrategy === "component" && Object.entries(g).forEach(([l, m]) => {
378
+ const w = m.map((L) => `@import url('./${L}');`).join(`
379
+ `), u = H(l, 6), N = Q(l), S = M(N.name), y = f(c, `css/f_${S}-${u}.css`);
380
+ k(y, w);
381
+ });
382
+ const $ = i.map((l) => `@import url('./css/${l}');`).join(`
190
383
  `);
191
- let i = `@layer l0, l1, l2, l3, l4, l5, l6, l7, l8;
384
+ let F = `@layer reset, global, l0, l1, l2, l3, l4, l5, l6, l7, l8;
192
385
 
193
- ${["@import url('./css/variables.css');", "@import url('./css/global.css');", "@import url('./css/templates.css');"].join(`
386
+ ${["_variables.css", "_reset.css", "_global.css", "_templates.css"].filter((l) => {
387
+ try {
388
+ return V(f(c, "css", l), "utf8").length > 0;
389
+ } catch {
390
+ return !1;
391
+ }
392
+ }).map((l) => `@import url('./css/${l}');`).join(`
194
393
  `)}
195
- ${f}`;
196
- if ($.importStrategy !== "component") {
197
- const p = e.flat().map((h) => `@import url('./css/${h}');`).join(`
198
- `);
199
- i += p;
394
+ ${$}`;
395
+ if (d.importStrategy !== "component") {
396
+ const l = a.reduce((m, w, u) => {
397
+ const N = w.reduce((B, K) => {
398
+ var x;
399
+ const G = f(c, "css", K), q = V(G, "utf8"), j = ((x = /.*-([^-]+)-\d+.css/.exec(K)) == null ? void 0 : x.at(1)) || H(G, 6);
400
+ return B.includes(j) ? B : `${B}
401
+ /*start:${j}*/
402
+ ${q}
403
+ /*end:${j}*/
404
+ `;
405
+ }, ""), S = `l_${u}.css`, y = f(c, "css", S), L = `@layer l${u} { ${N}
406
+ }`;
407
+ return k(y, L), `${m}
408
+ @import url('./css/${S}');`;
409
+ }, "");
410
+ F += l;
200
411
  }
201
- C(r, i);
202
- } catch (s) {
203
- console.error(s);
412
+ k(p, F);
413
+ const b = Date.now() - n, T = b < 200 ? "🔥" : b < 500 ? "🚀" : b < 1e3 ? "🎉" : b < 2e3 ? "🚗" : b < 5e3 ? "🤔" : "🥴";
414
+ et.info(`Generated CSS in ${b}ms! ${T}`);
415
+ } catch (n) {
416
+ console.error(n);
204
417
  }
205
- }, nt = async (t, s) => {
418
+ }, zt = async (t, e) => {
206
419
  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);
420
+ const s = await A(t);
421
+ if (I(e)) {
422
+ const i = [], a = await it(t), c = await rt(t, e, s);
423
+ if (Object.entries(c).forEach(([p, r]) => {
424
+ if (r.isKeyframes && r.css) {
425
+ const $ = `css/${`a_${r.animationName}.css`}`, P = f(s, $);
426
+ k(P, r.css);
427
+ return;
428
+ }
429
+ if (r.isClassName) {
430
+ const g = r.factory._withBuildContext({
431
+ name: p
432
+ });
433
+ i[0].push(g.cssFileName);
434
+ const $ = `css/${g.cssFileName}`, P = f(s, $);
435
+ k(P, g.css);
436
+ }
437
+ if (!r.generator) return;
438
+ const o = r.generator._withBuildContext({
439
+ name: p,
440
+ config: a
441
+ }), h = `css/${o.cssFileName}`, d = f(s, h);
442
+ k(d, o.css), i[o.priority] || (i[o.priority] = []), i[o.priority].push(o.cssFileName);
443
+ }), a.importStrategy !== "component")
444
+ i.forEach((p, r) => {
445
+ const o = `l_${r}.css`, h = f(s, "css", o);
446
+ let d = V(h, "utf8");
447
+ p.forEach((g) => {
448
+ var C;
449
+ const $ = f(s, "css", g), P = ((C = /.*-([^-]+)-\d+.css/.exec(g)) == null ? void 0 : C.at(1)) || H($, 6);
450
+ if (!d.includes(P)) {
451
+ const F = V($, "utf8"), D = `/*start:${P}*/
452
+ ${F}
453
+ /*end:${P}*/
454
+ `;
455
+ d = `${d.replace(/\}$/, "")}
456
+ ${D}
457
+ }`;
458
+ }
459
+ }), k(h, d);
460
+ });
461
+ else {
462
+ const p = i.flat().map((g) => `@import url('./${g}');`).join(`
463
+ `), r = H(e, 6), o = Q(e), h = M(o.name), d = f(s, `css/f_${h}-${r}.css`);
464
+ k(d, p);
465
+ }
222
466
  }
223
- } catch (e) {
224
- console.error(e);
467
+ } catch (s) {
468
+ console.error(s);
225
469
  }
226
- }, rt = async (t, s) => {
470
+ }, Zt = async (t, e, s = wt()) => {
227
471
  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;
472
+ const n = await A(t);
473
+ if (I(e)) {
474
+ const a = V(e, "utf8");
475
+ a.replace(/^(?!export\s)const\s.*/gm, (h) => `export ${h}`) !== a && await Nt(e, a);
476
+ const p = await it(t), r = await rt(t, e, n);
477
+ let o = a;
478
+ if (Object.entries(r).forEach(([h, d]) => {
479
+ var S;
480
+ if (d.isKeyframes || !d.generator) return;
481
+ const g = d.generator._withBuildContext({
482
+ name: h,
483
+ config: p,
484
+ prod: s
485
+ }), $ = new RegExp(`\\s${h}[=\\s]+[^()]+styled\\(([^,]+),`, "g").exec(a);
486
+ if (!$) return console.error("Could not find the original declaration");
487
+ const P = (S = $.at(1)) == null ? void 0 : S.trim(), E = new RegExp(`\\s${h}[=\\s]+styled\\(`, "g").exec(o);
488
+ if (!E) return console.error("Could not find the original declaration");
489
+ const { index: C } = E;
490
+ let F = !1;
491
+ const D = setTimeout(() => F = !0, 5e3);
492
+ let b = 0, T = !1, l = 0;
493
+ for (; !T && !F; ) {
494
+ const y = o[C + b];
495
+ y === "(" && l++, y === ")" && l--, l === 0 && y === ")" && (T = !0), b > o.length && (F = !0), b++;
239
496
  }
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;
497
+ if (!F) clearTimeout(D);
498
+ else throw new Error("Failed to find the end of the styled call and timed out");
499
+ const m = C + b, w = o.slice(C, m), u = o, N = ` ${h} = styled(${P}, "${g.classNames}", ${JSON.stringify(g.clientProps)});`;
500
+ o = o.replace(w, N), u === o && console.error("Minimize file failed to change content", { name: h, tagName: P });
501
+ }), p.importStrategy === "component") {
502
+ const h = H(e, 6), d = Q(e);
503
+ o = `import '../../saltygen/css/${`f_${M(d.name)}-${h}.css`}';
504
+ ${o}`;
505
+ }
506
+ return o = o.replace("{ styled }", "{ styledClient as styled }"), o = o.replace("@salty-css/react/styled", "@salty-css/react/styled-client"), o;
253
507
  }
254
- } catch (e) {
255
- console.error(e);
508
+ } catch (n) {
509
+ console.error("Error in minimizeFile:", n);
256
510
  }
257
- }, lt = (t) => ({
511
+ }, lt = async (t) => {
512
+ if (!t || t.includes("node_modules") || t.includes("saltygen")) return !1;
513
+ if (t.includes("salty.config")) return !0;
514
+ if (!I(t)) return !1;
515
+ const n = await nt(t, "utf-8");
516
+ return !!/.+define[A-Z]\w+/.test(n);
517
+ }, Kt = (t) => ({
258
518
  name: "stylegen",
259
- buildStart: () => et(t),
260
- load: async (s) => {
261
- if (k(s))
262
- return await rt(t, s);
519
+ buildStart: () => Wt(t),
520
+ load: async (e) => {
521
+ if (I(e))
522
+ return await Zt(t, e);
523
+ },
524
+ handleHotUpdate: async ({ file: e, server: s }) => {
525
+ await lt(e) && await s.restart();
263
526
  },
264
527
  watchChange: {
265
- handler: async (s) => {
266
- k(s) && await nt(t, s), s.includes("salty.config") && await W(t);
528
+ handler: async (e) => {
529
+ I(e) && (await lt(e) || await zt(t, e));
267
530
  }
268
531
  }
269
532
  });
270
533
  export {
271
- lt as saltyPlugin
534
+ Kt as default,
535
+ Kt as saltyPlugin
272
536
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@salty-css/vite",
3
- "version": "0.0.1-alpha.19",
3
+ "version": "0.0.1-alpha.191",
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.191"
33
38
  }
34
39
  }