@salty-css/vite 0.0.1-alpha.14 → 0.0.1-alpha.140

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 +25 -14
  3. package/index.d.ts +3 -8
  4. package/index.js +380 -210
  5. package/package.json +10 -2
package/README.md CHANGED
@@ -1,15 +1,132 @@
1
- # Salty Css
1
+ ![Salty CSS Banner](https://raw.githubusercontent.com/gist/tremppu/ef2b867907cbf262ab7373f41558a403/raw/a2137de136ee2296e386682beb4487bba0f58a2f/salty-logo-svg-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,29 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const J=require("esbuild"),K=require("winston"),L=require("child_process"),u=require("path"),d=require("fs"),G=require("fs/promises");function R(t){const s=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const e in t)if(e!=="default"){const n=Object.getOwnPropertyDescriptor(t,e);Object.defineProperty(s,e,n.get?n:{enumerable:!0,get:()=>t[e]})}}return s.default=t,Object.freeze(s)}const Z=R(J),N=R(K),q=t=>String.fromCharCode(t+(t>25?39:97)),U=(t,s)=>{let e="",n;for(n=Math.abs(t);n>52;n=n/52|0)e=q(n%52)+e;return e=q(n%52)+e,e.length<s?e=e.padStart(s,"a"):e.length>s&&(e=e.slice(-s)),e},X=(t,s)=>{let e=s.length;for(;e;)t=t*33^s.charCodeAt(--e);return t},_=(t,s=3)=>{const e=X(5381,JSON.stringify(t))>>>0;return U(e,s)};function V(t){return t?typeof t!="string"?String(t):t.replace(/\s/g,"-").replace(/[A-Z](?:(?=[^A-Z])|[A-Z]*(?=[A-Z][^A-Z]|$))/g,(s,e)=>(e>0?"-":"")+s.toLowerCase()):""}const Y=(t,s)=>{if(typeof t!="string")return{result:t};if(!s)return{result:t};const e=[];return Object.values(s).forEach(n=>{const{pattern:o,transform:y}=n;t=t.replace(o,$=>{const{value:a,css:f}=y($);return f&&e.push(f),a})}),{result:t,additionalCss:e}},I=t=>typeof t!="string"?{result:t}:/\{[^{}]+\}/g.test(t)?{result:t.replace(/\{([^{}]+)\}/g,(...n)=>`var(--${V(n[1].replaceAll(".","-"))})`)}:{result:t},D=(t,s,e,n)=>{const o=[],y=Object.entries(t).reduce((a,[f,r])=>{const i=f.trim();if(typeof r=="function"&&(r=r()),typeof r=="object"){if(!r)return a;if(i==="variants")return Object.entries(r).forEach(([g,c])=>{c&&Object.entries(c).forEach(([m,l])=>{if(!l)return;const F=`${s}.${g}-${m}`,P=D(l,F);o.push(P)})}),a;if(i==="defaultVariants")return a;if(i==="compoundVariants")return r.forEach(g=>{const{css:c,...m}=g,l=Object.entries(m).reduce((P,[x,k])=>`${P}.${x}-${k}`,s),F=D(c,l);o.push(F)}),a;if(i.startsWith("@")){const g=D(r,s),c=`${i} {
2
- ${g.replace(`
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const pe=require("esbuild"),de=require("child_process"),a=require("path"),u=require("fs"),X=require("fs/promises"),J=require("winston");var Z=typeof document<"u"?document.currentScript:null;function ye(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 Y=ye(pe),U=e=>String.fromCharCode(e+(e>25?39:97)),ge=(e,t)=>{let s="",n;for(n=Math.abs(e);n>52;n=n/52|0)s=U(n%52)+s;return s=U(n%52)+s,s.length<t?s=s.padStart(t,"a"):s.length>t&&(s=s.slice(-t)),s},me=(e,t)=>{let s=t.length;for(;s;)e=e*33^t.charCodeAt(--s);return e},L=(e,t=5)=>{const s=me(5381,JSON.stringify(e))>>>0;return ge(s,t)};function E(e){return e?typeof e!="string"?E(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 he=(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:o}=n;e=e.replace(i,l=>{const{value:d,css:c}=o(l);return c&&s.push(c),d})}),{result:e,additionalCss:s}},Q=e=>typeof e!="string"?{result:e}:/\{[^{}]+\}/g.test(e)?{result:e.replace(/\{([^{}]+)\}/g,(...n)=>`var(--${E(n[1].replaceAll(".","-"))})`)}:{result:e},D=(e,t,s)=>{if(!e)return"";const n=[],i=Object.entries(e).reduce((l,[d,c])=>{const r=d.trim();if(typeof c=="function"&&(c=c()),typeof c=="object"){if(!c)return l;if(r==="variants")return Object.entries(c).forEach(([f,g])=>{g&&Object.entries(g).forEach(([N,b])=>{if(!b)return;const T=`${t}.${f}-${N}`,k=D(b,T);n.push(k)})}),l;if(r==="defaultVariants")return l;if(r==="compoundVariants")return c.forEach(f=>{const{css:g,...N}=f,b=Object.entries(N).reduce((k,[p,m])=>`${k}.${p}-${m}`,t),T=D(g,b);n.push(T)}),l;if(r.startsWith("@")){const f=D(c,t),g=`${r} {
2
+ ${f.replace(`
3
3
  `,`
4
4
  `)}
5
- }`;return o.push(c),a}const h=f.includes("&")?i.replace("&",s):i.startsWith(":")?`${s}${i}`:`${s} ${i}`,C=D(r,h);return o.push(C),a}const p=i.startsWith("-")?i:V(i),b=(h,C=";")=>a=`${a}${h}${C}`,j=h=>b(`${p}:${h}`);if(typeof r=="number")return j(r);if(typeof r!="string")if("toString"in r)r=r.toString();else return a;const{modifiers:w}={},O=function*(){yield I(r),yield Y(r,w)}();for(const{result:h,additionalCss:C=[]}of O)r=h,C.forEach(g=>{const c=D(g,"");b(c,"")});return j(r)},"");if(!y)return o.join(`
6
- `);if(!s)return y;let $="";return $=`${s} { ${y} }`,[$,...o].join(`
7
- `)},z=(t,s=[])=>{const e=[],n={};if(Object.entries(t).forEach(([o,y])=>{if(typeof y=="object"){if(!y)return;const $=o.trim(),a=z(y,[...s,$]);e.push(a)}else n[o]=y}),Object.keys(n).length){const o=s.map(V).join("-"),y=D(n,`.${o}`);e.push(y)}return e.join(`
8
- `)};N.createLogger({level:"info",format:N.format.combine(N.format.colorize(),N.format.cli()),transports:[new N.transports.Console({})]});const E=t=>u.join(t,"./saltygen"),Q=["salty","css","styles","styled"],v=(t=[])=>new RegExp(`\\.(${[...Q,...t].join("|")})\\.`),T=(t,s=[])=>v(s).test(t),tt=async t=>{const s=E(t),e=u.join(t,"salty-config.ts"),n=u.join(s,"salty-config.js");await Z.build({entryPoints:[e],minify:!0,treeShaking:!0,bundle:!0,outfile:n,format:"esm",external:["react"]});const o=Date.now(),{config:y}=await import(`${n}?t=${o}`);return y},B=async t=>{const s=await tt(t),e=new Set,n=(g,c=[])=>g?Object.entries(g).flatMap(([m,l])=>{if(!l)return;if(typeof l=="object")return n(l,[...c,m]);const F=[...c,m].join(".");e.add(`"${F}"`);const P=[...c.map(V),V(m)].join("-"),{result:x}=I(l);return`--${P}: ${x};`}):[],o=g=>g?Object.entries(g).flatMap(([c,m])=>{const l=n(m);return c==="base"?l.join(""):`${c} { ${l.join("")} }`}):[],y=g=>g?Object.entries(g).flatMap(([c,m])=>Object.entries(m).flatMap(([l,F])=>{const P=n(F,[c]),x=`.${c}-${l}, [data-${c}="${l}"]`,k=P.join("");return`${x} { ${k} }`})):[],$=n(s.variables),a=o(s.responsiveVariables),f=y(s.conditionalVariables),r=E(t),i=u.join(r,"css/variables.css"),p=`:root { ${$.join("")} ${a.join("")} } ${f.join("")}`;d.writeFileSync(i,p);const b=u.join(r,"types/css-tokens.d.ts"),w=`type VariableTokens = ${[...e].join("|")}; type PropertyValueToken = \`{\${VariableTokens}}\``;d.writeFileSync(b,w);const S=u.join(r,"css/global.css"),O=D(s.global,"");d.writeFileSync(S,O);const h=u.join(r,"css/templates.css"),C=z(s.templates);d.writeFileSync(h,C)},A=async(t,s)=>{const e=_(t),n=u.join(s,"js",e+".js");await Z.build({entryPoints:[t],minify:!0,treeShaking:!0,bundle:!0,outfile:n,format:"esm",target:["es2022"],keepNames:!0,external:["react"]});const o=Date.now();return await import(`${n}?t=${o}`)},M=async t=>{const s=E(t),e=u.join(s,"salty-config.js"),{config:n}=await import(e);return n},st=async t=>{try{const s=[],e=[],n=E(t),o=u.join(n,"index.css");(()=>{d.existsSync(n)&&L.execSync("rm -rf "+n),d.mkdirSync(n),d.mkdirSync(u.join(n,"css")),d.mkdirSync(u.join(n,"types"))})(),await B(t);const $=await M(t);async function a(p,b){const j=d.statSync(p);if(j.isDirectory()){const w=d.readdirSync(p);await Promise.all(w.map(S=>a(u.join(p,S),u.join(b,S))))}else if(j.isFile()&&T(p)){const S=await A(p,n),O=[];Object.entries(S).forEach(([c,m])=>{if(m.isKeyframes&&m.css){const k=`${m.animationName}.css`,H=`css/${k}`,W=u.join(n,H);s.push(k),d.writeFileSync(W,m.css);return}if(!m.generator)return;const l=m.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);d.writeFileSync(x,l.css)});const h=O.map(c=>`@import url('./${c}');`).join(`
9
- `),C=_(p,6),g=u.join(n,`css/${C}.css`);d.writeFileSync(g,h)}}await a(t,n);const f=s.map(p=>`@import url('./css/${p}');`).join(`
10
- `);let i=`@layer l0, l1, l2, l3, l4, l5, l6, l7, l8;
5
+ }`;return n.push(g),l}const y=d.includes("&")?r.replace("&",t):r.startsWith(":")?`${t}${r}`:`${t} ${r}`,w=D(c,y);return n.push(w),l}const h=r.startsWith("-")?r:E(r),F=(y,w=";")=>l=`${l}${y}${w}`,j=y=>F(`${h}:${y}`);if(typeof c=="number")return j(c);if(typeof c!="string")if("toString"in c)c=c.toString();else return l;const{modifiers:S}={},_=function*(){yield Q(c),yield he(c,S)}();for(const{result:y,additionalCss:w=[]}of _)c=y,w.forEach(f=>{const g=D(f,"");F(g,"")});return j(c)},"");return i?t?[`${t} { ${i} }`,...n].join(`
6
+ `):i:n.join(`
7
+ `)},v=(e,t=[])=>{if(!e)return"";const s=[],n={};if(Object.entries(e).forEach(([i,o])=>{if(typeof o=="object"){if(!o)return;const l=i.trim(),d=v(o,[...t,l]);s.push(d)}else n[i]=o}),Object.keys(n).length){const i=t.map(E).join("-"),o=D(n,`.${i}`);s.push(o)}return s.join(`
8
+ `)},Se=e=>Object.entries(e).reduce((t,[s,n])=>(typeof n=="object"&&(t[s]=ee(n).map(i=>`"${i}"`).join(" | ")),t),{}),ee=(e,t="",s=new Set)=>e?(Object.entries(e).forEach(([n,i])=>{const o=t?`${t}.${n}`:n;return typeof i=="object"?ee(i,o,s):s.add(t)}),[...s]):[],te=e=>{if(!e||e==="/")throw new Error("Could not find package.json file");const t=a.join(e,"package.json");return u.existsSync(t)?t:te(a.join(e,".."))},$e=async e=>{const t=te(e);return await X.readFile(t,"utf-8").then(JSON.parse).catch(()=>{})},be=async e=>{const t=await $e(e);if(t)return t.type};let R;const se=async e=>{if(R)return R;const t=await be(e);return t==="module"?R="esm":(t==="commonjs"||(typeof document>"u"?require("url").pathToFileURL(__filename).href:Z&&Z.tagName.toUpperCase()==="SCRIPT"&&Z.src||new URL("index.cjs",document.baseURI).href).endsWith(".cjs"))&&(R="cjs"),R||"esm"},I=J.createLogger({level:"debug",format:J.format.combine(J.format.colorize(),J.format.cli()),transports:[new J.transports.Console({})]});function ne(e){return e?typeof e!="string"?ne(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 je={"*, *::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"}},q={externalModules:[]},oe=e=>{if(q.externalModules.length>0)return q.externalModules;const t=a.join(e,"salty.config.ts"),n=u.readFileSync(t,"utf8").match(/externalModules:\s?\[(.*)\]/);if(!n)return[];const i=n[1].split(",").map(o=>o.replace(/['"`]/g,"").trim());return q.externalModules=i,i},z=e=>a.join(e,"./saltygen"),re=["salty","css","styles","styled"],we=(e=[])=>new RegExp(`\\.(${[...re,...e].join("|")})\\.`),W=(e,t=[])=>we(t).test(e),Fe=async e=>{const t=z(e),s=a.join(e,"salty.config.ts"),n=a.join(t,"salty.config.js"),i=await se(e),o=oe(e);await Y.build({entryPoints:[s],minify:!0,treeShaking:!0,bundle:!0,outfile:n,format:i,external:o});const l=Date.now(),{config:d}=await import(`${n}?t=${l}`);return d},xe=async e=>{const t=await Fe(e),s=new Set,n=(p,m=[])=>p?Object.entries(p).flatMap(([C,$])=>{if(!$)return;if(typeof $=="object")return n($,[...m,C]);const M=ne(C),A=E(C),V=[...m,M].join(".");s.add(`"${V}"`);const P=[...m.map(E),A].join("-"),{result:O}=Q($);return`--${P}: ${O};`}):[],i=p=>p?Object.entries(p).flatMap(([m,C])=>{const $=n(C);return m==="base"?$.join(""):`${m} { ${$.join("")} }`}):[],o=p=>p?Object.entries(p).flatMap(([m,C])=>Object.entries(C).flatMap(([$,M])=>{const A=n(M,[m]),V=`.${m}-${$}, [data-${m}="${$}"]`,P=A.join("");return`${V} { ${P} }`})):[],l=n(t.variables),d=i(t.responsiveVariables),c=o(t.conditionalVariables),r=z(e),h=a.join(r,"css/_variables.css"),F=`:root { ${l.join("")} ${d.join("")} } ${c.join("")}`;u.writeFileSync(h,F);const j=a.join(r,"css/_global.css"),S=D(t.global,"");u.writeFileSync(j,`@layer global { ${S} }`);const x=a.join(r,"css/_reset.css"),y=t.reset==="none"?{}:typeof t.reset=="object"?t.reset:je,w=D(y,"");u.writeFileSync(x,`@layer reset { ${w} }`);const f=a.join(r,"css/_templates.css"),g=v(t.templates),N=Se(t.templates);u.writeFileSync(f,g);const b=a.join(r,"types/css-tokens.d.ts"),k=`
9
+ // Variable types
10
+ type VariableTokens = ${[...s].join("|")};
11
+ type PropertyValueToken = \`{\${VariableTokens}}\`;
11
12
 
12
- ${["@import url('./css/variables.css');","@import url('./css/global.css');","@import url('./css/templates.css');"].join(`
13
+ // Template types
14
+ type TemplateTokens = {
15
+ ${Object.entries(N).map(([p,m])=>`${p}?: ${m}`).join(`
13
16
  `)}
14
- ${f}`;if($.importStrategy!=="component"){const p=e.flat().map(b=>`@import url('./css/${b}');`).join(`
15
- `);i+=p}d.writeFileSync(o,i)}catch(s){console.error(s)}},et=async(t,s)=>{try{const e=[],n=u.join(t,"./saltygen"),o=u.join(n,"index.css");if(T(s)){const $=await M(t),a=await A(s,n);Object.entries(a).forEach(([b,j])=>{if(!j.generator)return;const w=j.generator._withBuildContext({name:b,config:$}),S=`${w.hash}-${w.priority}.css`,O=`css/${S}`,h=u.join(n,O);e.push(S),d.writeFileSync(h,w.css)});const f=d.readFileSync(o,"utf8").split(`
16
- `),r=e.map(b=>`@import url('../saltygen/css/${b}');`),p=[...new Set([...f,...r])].join(`
17
- `);d.writeFileSync(o,p)}}catch(e){console.error(e)}},nt=async(t,s)=>{try{const e=u.join(t,"./saltygen");if(T(s)){const o=d.readFileSync(s,"utf8");o.replace(/^(?!export\s)const\s.*/gm,i=>`export ${i}`)!==o&&await G.writeFile(s,o);const $=await M(t),a=await A(s,e);let f=o;Object.entries(a).forEach(([i,p])=>{var h;if(p.isKeyframes){console.log("value",p);return}if(!p.generator)return;const b=p.generator._withBuildContext({name:i,config:$}),j=new RegExp(`${i}[=\\s]+[^()]+styled\\(([^,]+),`,"g").exec(o);if(!j)return console.error("Could not find the original declaration");const w=(h=j.at(1))==null?void 0:h.trim(),S=`${i} = styled(${w}, "${b.classNames}", "${b._callerName}", ${JSON.stringify(b.props)});`,O=new RegExp(`${i}[=\\s]+[^()]+styled\\(([^,]+),[^;]+;`,"g");f=f.replace(O,S)});const r=_(s,6);return $.importStrategy==="component"&&(f=`import '../../saltygen/css/${r}.css';
18
- ${f}`),f=f.replace("{ styled }","{ styledClient as styled }"),f=f.replace("@salty-css/react/styled","@salty-css/react/styled-client"),f}}catch(e){console.error(e)}},ot=t=>({name:"stylegen",buildStart:()=>st(t),load:async s=>{if(T(s))return await nt(t,s)},watchChange:{handler:async s=>{T(s)&&await et(t,s),s.includes("salty-config")&&await B(t)}}});exports.saltyPlugin=ot;
17
+ }
18
+ `;u.writeFileSync(b,k)},G=e=>e.replace(/styled\(([^"'`{,]+),/g,(t,s)=>{const n=/^['"`]/.test(s);if(n&&console.log("String tag",s),n)return t;const i=new RegExp(`import[^;]*${s}[,\\s{][^;]*from\\s?([^{};]+);`),o=i.test(e);if(o||console.log("Not imported",s),!o)return t;const l=i.exec(e);if(l){const d=l.at(1),c=re.some(r=>d==null?void 0:d.includes(r));if(c&&console.log("Salty import for",s,`"${l.at(0)}"`),c)return t}return console.log("Replacing",s),"styled('div',"}),H=async(e,t,s)=>{console.log({sourceFilePath:t});const n=L(t),i=a.join(s,"./temp");u.existsSync(i)||u.mkdirSync(i);const o=a.parse(t);let l=u.readFileSync(t,"utf8");l=G(l);const d=a.join(s,"js",n+".js"),c=oe(e),r=await se(e);await Y.build({stdin:{contents:l,sourcefile:o.base,resolveDir:o.dir,loader:"tsx"},minify:!1,treeShaking:!0,bundle:!0,outfile:d,format:r,target:["node20"],keepNames:!0,external:c,packages:"external",plugins:[{name:"test",setup:j=>{j.onLoad({filter:/.*.css.ts/},S=>{console.log("Loading",{sourceFilePath:t,args:S});const x=u.readFileSync(S.path,"utf8");return{contents:G(x)}})}}]});const h=Date.now();return await import(`${d}?t=${h}`)},B=async e=>{const t=z(e),s=a.join(t,"salty.config.js"),n=Date.now(),{config:i}=await import(`${s}?t=${n}`);return i},ie=()=>{try{return process.env.NODE_ENV==="production"}catch{return!1}},Ce=async(e,t=ie())=>{try{const s=Date.now();t?I.info("Generating CSS in production mode! 🔥"):I.info("Generating CSS in development mode! 🚀");const n=[],i=[],o=z(e),l=a.join(o,"index.css");(()=>{u.existsSync(o)&&de.execSync("rm -rf "+o),u.mkdirSync(o),u.mkdirSync(a.join(o,"css")),u.mkdirSync(a.join(o,"types"))})(),await xe(e);const c=await B(e);async function r(f,g){const N=["node_modules","saltygen"],b=u.statSync(f);if(b.isDirectory()){const T=u.readdirSync(f);if(N.some(p=>f.includes(p)))return;await Promise.all(T.map(p=>r(a.join(f,p),a.join(g,p))))}else if(b.isFile()&&W(f)){const k=await H(e,f,o),p=[];Object.entries(k).forEach(([V,P])=>{if(P.isKeyframes&&P.css){const K=`a_${P.animationName}.css`,fe=`css/${K}`,ue=a.join(o,fe);n.push(K),u.writeFileSync(ue,P.css);return}if(!P.generator)return;const O=P.generator._withBuildContext({name:V,config:c,prod:t});i[O.priority]||(i[O.priority]=[]),i[O.priority].push(O.cssFileName),p.push(O.cssFileName);const ae=`css/${O.cssFileName}`,le=a.join(o,ae);u.writeFileSync(le,O.css)});const m=p.map(V=>`@import url('./${V}');`).join(`
19
+ `),C=L(f,6),$=a.parse(f),M=E($.name),A=a.join(o,`css/f_${M}-${C}.css`);u.writeFileSync(A,m)}}await r(e,o);const h=n.map(f=>`@import url('./css/${f}');`).join(`
20
+ `);let x=`@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(a.join(o,"css",f),"utf8").length>0}catch{return!1}}).map(f=>`@import url('./css/${f}');`).join(`
23
+ `)}
24
+ ${h}`;if(c.importStrategy!=="component"){const f=i.reduce((g,N,b)=>{const T=N.reduce((C,$)=>{const M=u.readFileSync(a.join(o,"css",$),"utf8");return`${C}
25
+ ${M}`},""),k=`l_${b}.css`,p=a.join(o,"css",k),m=`@layer l${b} { ${T} }`;return u.writeFileSync(p,m),`${g}
26
+ @import url('./css/${k}');`},"");x+=f}u.writeFileSync(l,x);const y=Date.now()-s,w=y<200?"🔥":y<500?"🚀":y<1e3?"🎉":y<2e3?"🚗":y<5e3?"🤔":"🥴";I.info(`Generated CSS in ${y}ms! ${w}`)}catch(s){console.error(s)}},ke=async(e,t)=>{try{const s=[],n=a.join(e,"./saltygen"),i=a.join(n,"index.css");if(W(t)){const l=await B(e),d=await H(e,t,n);Object.entries(d).forEach(([j,S])=>{if(S.isKeyframes&&S.css){const f=`css/${`a_${S.animationName}.css`}`,g=a.join(n,f);u.writeFileSync(g,S.css);return}if(!S.generator)return;const x=S.generator._withBuildContext({name:j,config:l}),_=`css/${x.cssFileName}`,y=a.join(n,_);s.push(x.cssFileName),u.writeFileSync(y,x.css)});const c=u.readFileSync(i,"utf8").split(`
27
+ `),r=s.map(j=>`@import url('../saltygen/css/${j}');`),F=[...new Set([...c,...r])].join(`
28
+ `);u.writeFileSync(i,F)}}catch(s){console.error(s)}},Ne=async(e,t,s=ie())=>{try{const n=a.join(e,"./saltygen");if(W(t)){const o=u.readFileSync(t,"utf8");o.replace(/^(?!export\s)const\s.*/gm,h=>`export ${h}`)!==o&&await X.writeFile(t,o);const d=await B(e),c=await H(e,t,n);let r=o;if(Object.entries(c).forEach(([h,F])=>{var C;if(F.isKeyframes||!F.generator)return;const j=F.generator._withBuildContext({name:h,config:d,prod:s}),S=new RegExp(`\\s${h}[=\\s]+[^()]+styled\\(([^,]+),`,"g").exec(o);if(!S)return console.error("Could not find the original declaration");const x=(C=S.at(1))==null?void 0:C.trim(),_=new RegExp(`\\s${h}[=\\s]+styled\\(`,"g").exec(r);if(!_)return console.error("Could not find the original declaration");const{index:y}=_;let w=!1;const f=setTimeout(()=>w=!0,5e3);let g=0,N=!1,b=0;for(;!N&&!w;){const $=r[y+g];$==="("&&b++,$===")"&&b--,b===0&&$===")"&&(N=!0),g>r.length&&(w=!0),g++}if(!w)clearTimeout(f);else throw new Error("Failed to find the end of the styled call and timed out");const T=y+g,k=r.slice(y,T),p=r,m=` ${h} = styled(${x}, "${j.classNames}", ${JSON.stringify(j.props)});`;r=r.replace(k,m),p===r&&console.error("Minimize file failed to change content",{name:h,tagName:x})}),d.importStrategy==="component"){const h=L(t,6),F=a.parse(t);r=`import '../../saltygen/css/${`f_${E(F.name)}-${h}.css`}';
29
+ ${r}`}return r=r.replace("{ styled }","{ styledClient as styled }"),r=r.replace("@salty-css/react/styled","@salty-css/react/styled-client"),r}}catch(n){console.error("Error in minimizeFile:",n)}},ce=e=>({name:"stylegen",buildStart:()=>Ce(e),load:async t=>{if(W(t))return await Ne(e,t)},handleHotUpdate:async({file:t,server:s})=>{t.includes("salty.config")&&await s.restart()},watchChange:{handler:async t=>{W(t)&&await ke(e,t)}}});exports.default=ce;exports.saltyPlugin=ce;
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,277 +1,447 @@
1
- import * as I from "esbuild";
2
- import * as P from "winston";
3
- import { execSync as L } from "child_process";
4
- import { join as y } from "path";
5
- import { writeFileSync as C, existsSync as q, mkdirSync as A, statSync as G, readdirSync as U, readFileSync as B } from "fs";
6
- import { writeFile as X } from "fs/promises";
7
- const Z = (t) => String.fromCharCode(t + (t > 25 ? 39 : 97)), Y = (t, s) => {
8
- let e = "", n;
9
- for (n = Math.abs(t); n > 52; n = n / 52 | 0) e = Z(n % 52) + e;
10
- return e = Z(n % 52) + e, e.length < s ? e = e.padStart(s, "a") : e.length > s && (e = e.slice(-s)), e;
11
- }, Q = (t, s) => {
12
- let e = s.length;
13
- for (; e; ) t = t * 33 ^ s.charCodeAt(--e);
1
+ import * as v from "esbuild";
2
+ import { execSync as dt } from "child_process";
3
+ import { join as f, parse as B } from "path";
4
+ import { existsSync as K, mkdirSync as z, statSync as gt, readdirSync as yt, writeFileSync as k, readFileSync as A } from "fs";
5
+ import { readFile as mt, writeFile as ht } from "fs/promises";
6
+ import { createLogger as $t, format as H, transports as bt } from "winston";
7
+ const Y = (t) => String.fromCharCode(t + (t > 25 ? 39 : 97)), St = (t, e) => {
8
+ let s = "", n;
9
+ for (n = Math.abs(t); n > 52; n = n / 52 | 0) s = Y(n % 52) + s;
10
+ return s = Y(n % 52) + s, s.length < e ? s = s.padStart(e, "a") : s.length > e && (s = s.slice(-e)), s;
11
+ }, wt = (t, e) => {
12
+ let s = e.length;
13
+ for (; s; ) t = t * 33 ^ e.charCodeAt(--s);
14
14
  return t;
15
- }, R = (t, s = 3) => {
16
- const e = Q(5381, JSON.stringify(t)) >>> 0;
17
- return Y(e, s);
15
+ }, G = (t, e = 5) => {
16
+ const s = wt(5381, JSON.stringify(t)) >>> 0;
17
+ return St(s, e);
18
18
  };
19
- function k(t) {
20
- return t ? typeof t != "string" ? String(t) : t.replace(/\s/g, "-").replace(/[A-Z](?:(?=[^A-Z])|[A-Z]*(?=[A-Z][^A-Z]|$))/g, (s, e) => (e > 0 ? "-" : "") + s.toLowerCase()) : "";
19
+ function V(t) {
20
+ return t ? typeof t != "string" ? V(String(t)) : t.replace(/[\s.]/g, "-").replace(/[A-Z](?:(?=[^A-Z])|[A-Z]*(?=[A-Z][^A-Z]|$))/g, (e, s) => (s > 0 ? "-" : "") + e.toLowerCase()) : "";
21
21
  }
22
- const v = (t, s) => {
22
+ const jt = (t, e) => {
23
23
  if (typeof t != "string") return { result: t };
24
- if (!s) return { result: t };
25
- const e = [];
26
- return Object.values(s).forEach((n) => {
27
- const { pattern: o, transform: u } = n;
28
- t = t.replace(o, ($) => {
29
- const { value: a, css: f } = u($);
30
- return f && e.push(f), a;
24
+ if (!e) return { result: t };
25
+ const s = [];
26
+ return Object.values(e).forEach((n) => {
27
+ const { pattern: i, transform: o } = n;
28
+ t = t.replace(i, (a) => {
29
+ const { value: u, css: c } = o(a);
30
+ return c && s.push(c), u;
31
31
  });
32
- }), { result: t, additionalCss: e };
33
- }, H = (t) => typeof t != "string" ? { result: t } : /\{[^{}]+\}/g.test(t) ? { result: t.replace(/\{([^{}]+)\}/g, (...n) => `var(--${k(n[1].replaceAll(".", "-"))})`) } : { result: t }, V = (t, s, e, n) => {
34
- const o = [], u = Object.entries(t).reduce((a, [f, r]) => {
35
- const i = f.trim();
36
- if (typeof r == "function" && (r = r()), typeof r == "object") {
37
- if (!r) return a;
38
- if (i === "variants")
39
- return Object.entries(r).forEach(([g, c]) => {
40
- c && Object.entries(c).forEach(([m, l]) => {
41
- if (!l) return;
42
- const S = `${s}.${g}-${m}`, D = V(l, S);
43
- o.push(D);
32
+ }), { result: t, additionalCss: s };
33
+ }, tt = (t) => typeof t != "string" ? { result: t } : /\{[^{}]+\}/g.test(t) ? { result: t.replace(/\{([^{}]+)\}/g, (...n) => `var(--${V(n[1].replaceAll(".", "-"))})`) } : { result: t }, O = (t, e, s) => {
34
+ if (!t) return "";
35
+ const n = [], i = Object.entries(t).reduce((a, [u, c]) => {
36
+ const r = u.trim();
37
+ if (typeof c == "function" && (c = c()), typeof c == "object") {
38
+ if (!c) return a;
39
+ if (r === "variants")
40
+ return Object.entries(c).forEach(([l, g]) => {
41
+ g && Object.entries(g).forEach(([N, b]) => {
42
+ if (!b) return;
43
+ const T = `${e}.${l}-${N}`, F = O(b, T);
44
+ n.push(F);
44
45
  });
45
46
  }), a;
46
- if (i === "defaultVariants")
47
+ if (r === "defaultVariants")
47
48
  return a;
48
- if (i === "compoundVariants")
49
- return r.forEach((g) => {
50
- const { css: c, ...m } = g, l = Object.entries(m).reduce((D, [N, O]) => `${D}.${N}-${O}`, s), S = V(c, l);
51
- o.push(S);
49
+ if (r === "compoundVariants")
50
+ return c.forEach((l) => {
51
+ const { css: g, ...N } = l, b = Object.entries(N).reduce((F, [p, y]) => `${F}.${p}-${y}`, e), T = O(g, b);
52
+ n.push(T);
52
53
  }), a;
53
- if (i.startsWith("@")) {
54
- const g = V(r, s), c = `${i} {
55
- ${g.replace(`
54
+ if (r.startsWith("@")) {
55
+ const l = O(c, e), g = `${r} {
56
+ ${l.replace(`
56
57
  `, `
57
58
  `)}
58
59
  }`;
59
- return o.push(c), a;
60
+ return n.push(g), a;
60
61
  }
61
- const d = f.includes("&") ? i.replace("&", s) : i.startsWith(":") ? `${s}${i}` : `${s} ${i}`, x = V(r, d);
62
- return o.push(x), a;
62
+ const d = u.includes("&") ? r.replace("&", e) : r.startsWith(":") ? `${e}${r}` : `${e} ${r}`, w = O(c, d);
63
+ return n.push(w), a;
63
64
  }
64
- const p = i.startsWith("-") ? i : k(i), h = (d, x = ";") => a = `${a}${d}${x}`, b = (d) => h(`${p}:${d}`);
65
- if (typeof r == "number") return b(r);
66
- if (typeof r != "string")
67
- if ("toString" in r) r = r.toString();
65
+ const m = r.startsWith("-") ? r : V(r), j = (d, w = ";") => a = `${a}${d}${w}`, S = (d) => j(`${m}:${d}`);
66
+ if (typeof c == "number") return S(c);
67
+ if (typeof c != "string")
68
+ if ("toString" in c) c = c.toString();
68
69
  else return a;
69
- const { modifiers: j } = {}, F = function* () {
70
- yield H(r), yield v(r, j);
70
+ const { modifiers: h } = {}, D = function* () {
71
+ yield tt(c), yield jt(c, h);
71
72
  }();
72
- for (const { result: d, additionalCss: x = [] } of F)
73
- r = d, x.forEach((g) => {
74
- const c = V(g, "");
75
- h(c, "");
73
+ for (const { result: d, additionalCss: w = [] } of D)
74
+ c = d, w.forEach((l) => {
75
+ const g = O(l, "");
76
+ j(g, "");
76
77
  });
77
- return b(r);
78
+ return S(c);
78
79
  }, "");
79
- if (!u) return o.join(`
80
+ return i ? e ? [`${e} { ${i} }`, ...n].join(`
81
+ `) : i : n.join(`
80
82
  `);
81
- if (!s) return u;
82
- let $ = "";
83
- return $ = `${s} { ${u} }`, [$, ...o].join(`
84
- `);
85
- }, W = (t, s = []) => {
86
- const e = [], n = {};
87
- if (Object.entries(t).forEach(([o, u]) => {
88
- if (typeof u == "object") {
89
- if (!u) return;
90
- const $ = o.trim(), a = W(u, [...s, $]);
91
- e.push(a);
83
+ }, et = (t, e = []) => {
84
+ if (!t) return "";
85
+ const s = [], n = {};
86
+ if (Object.entries(t).forEach(([i, o]) => {
87
+ if (typeof o == "object") {
88
+ if (!o) return;
89
+ const a = i.trim(), u = et(o, [...e, a]);
90
+ s.push(u);
92
91
  } else
93
- n[o] = u;
92
+ n[i] = o;
94
93
  }), Object.keys(n).length) {
95
- const o = s.map(k).join("-"), u = V(n, `.${o}`);
96
- e.push(u);
94
+ const i = e.map(V).join("-"), o = O(n, `.${i}`);
95
+ s.push(o);
97
96
  }
98
- return e.join(`
97
+ return s.join(`
99
98
  `);
99
+ }, xt = (t) => Object.entries(t).reduce((e, [s, n]) => (typeof n == "object" && (e[s] = st(n).map((i) => `"${i}"`).join(" | ")), e), {}), st = (t, e = "", s = /* @__PURE__ */ new Set()) => t ? (Object.entries(t).forEach(([n, i]) => {
100
+ const o = e ? `${e}.${n}` : n;
101
+ return typeof i == "object" ? st(i, o, s) : s.add(e);
102
+ }), [...s]) : [], nt = (t) => {
103
+ if (!t || t === "/") throw new Error("Could not find package.json file");
104
+ const e = f(t, "package.json");
105
+ return K(e) ? e : nt(f(t, ".."));
106
+ }, Ct = async (t) => {
107
+ const e = nt(t);
108
+ return await mt(e, "utf-8").then(JSON.parse).catch(() => {
109
+ });
110
+ }, Ft = async (t) => {
111
+ const e = await Ct(t);
112
+ if (e)
113
+ return e.type;
100
114
  };
101
- P.createLogger({
102
- level: "info",
103
- format: P.format.combine(P.format.colorize(), P.format.cli()),
104
- transports: [new P.transports.Console({})]
115
+ let R;
116
+ const ot = async (t) => {
117
+ if (R) return R;
118
+ const e = await Ft(t);
119
+ return e === "module" ? R = "esm" : (e === "commonjs" || import.meta.url.endsWith(".cjs")) && (R = "cjs"), R || "esm";
120
+ }, I = $t({
121
+ level: "debug",
122
+ format: H.combine(H.colorize(), H.cli()),
123
+ transports: [new bt.Console({})]
105
124
  });
106
- const T = (t) => y(t, "./saltygen"), tt = ["salty", "css", "styles", "styled"], st = (t = []) => new RegExp(`\\.(${[...tt, ...t].join("|")})\\.`), E = (t, s = []) => st(s).test(t), et = async (t) => {
107
- const s = T(t), e = y(t, "salty-config.ts"), n = y(s, "salty-config.js");
108
- await I.build({
109
- entryPoints: [e],
125
+ function rt(t) {
126
+ return t ? typeof t != "string" ? rt(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 kt = {
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
+ }, L = {
175
+ externalModules: []
176
+ }, it = (t) => {
177
+ if (L.externalModules.length > 0) return L.externalModules;
178
+ const e = f(t, "salty.config.ts"), n = A(e, "utf8").match(/externalModules:\s?\[(.*)\]/);
179
+ if (!n) return [];
180
+ const i = n[1].split(",").map((o) => o.replace(/['"`]/g, "").trim());
181
+ return L.externalModules = i, i;
182
+ }, Z = (t) => f(t, "./saltygen"), ct = ["salty", "css", "styles", "styled"], Nt = (t = []) => new RegExp(`\\.(${[...ct, ...t].join("|")})\\.`), W = (t, e = []) => Nt(e).test(t), Tt = async (t) => {
183
+ const e = Z(t), s = f(t, "salty.config.ts"), n = f(e, "salty.config.js"), i = await ot(t), o = it(t);
184
+ await v.build({
185
+ entryPoints: [s],
110
186
  minify: !0,
111
187
  treeShaking: !0,
112
188
  bundle: !0,
113
189
  outfile: n,
114
- format: "esm",
115
- external: ["react"]
190
+ format: i,
191
+ external: o
116
192
  });
117
- const o = Date.now(), { config: u } = await import(`${n}?t=${o}`);
193
+ const a = Date.now(), { config: u } = await import(`${n}?t=${a}`);
118
194
  return u;
119
- }, z = async (t) => {
120
- const s = await et(t), e = /* @__PURE__ */ new Set(), n = (g, c = []) => g ? Object.entries(g).flatMap(([m, l]) => {
121
- if (!l) return;
122
- if (typeof l == "object") return n(l, [...c, m]);
123
- const S = [...c, m].join(".");
124
- e.add(`"${S}"`);
125
- const D = [...c.map(k), k(m)].join("-"), { result: N } = H(l);
126
- return `--${D}: ${N};`;
127
- }) : [], o = (g) => g ? Object.entries(g).flatMap(([c, m]) => {
128
- const l = n(m);
129
- return c === "base" ? l.join("") : `${c} { ${l.join("")} }`;
130
- }) : [], u = (g) => g ? Object.entries(g).flatMap(([c, m]) => Object.entries(m).flatMap(([l, S]) => {
131
- const D = n(S, [c]), N = `.${c}-${l}, [data-${c}="${l}"]`, O = D.join("");
132
- return `${N} { ${O} }`;
133
- })) : [], $ = n(s.variables), a = o(s.responsiveVariables), f = u(s.conditionalVariables), r = T(t), i = y(r, "css/variables.css"), p = `:root { ${$.join("")} ${a.join("")} } ${f.join("")}`;
134
- C(i, p);
135
- const h = y(r, "types/css-tokens.d.ts"), j = `type VariableTokens = ${[...e].join("|")}; type PropertyValueToken = \`{\${VariableTokens}}\``;
136
- C(h, j);
137
- const w = y(r, "css/global.css"), F = V(s.global, "");
138
- C(w, F);
139
- const d = y(r, "css/templates.css"), x = W(s.templates);
140
- C(d, x);
141
- }, M = async (t, s) => {
142
- const e = R(t), n = y(s, "js", e + ".js");
143
- await I.build({
144
- entryPoints: [t],
145
- minify: !0,
195
+ }, Pt = async (t) => {
196
+ const e = await Tt(t), s = /* @__PURE__ */ new Set(), n = (p, y = []) => p ? Object.entries(p).flatMap(([C, $]) => {
197
+ if (!$) return;
198
+ if (typeof $ == "object") return n($, [...y, C]);
199
+ const M = rt(C), J = V(C), _ = [...y, M].join(".");
200
+ s.add(`"${_}"`);
201
+ const P = [...y.map(V), J].join("-"), { result: E } = tt($);
202
+ return `--${P}: ${E};`;
203
+ }) : [], i = (p) => p ? Object.entries(p).flatMap(([y, C]) => {
204
+ const $ = n(C);
205
+ return y === "base" ? $.join("") : `${y} { ${$.join("")} }`;
206
+ }) : [], o = (p) => p ? Object.entries(p).flatMap(([y, C]) => Object.entries(C).flatMap(([$, M]) => {
207
+ const J = n(M, [y]), _ = `.${y}-${$}, [data-${y}="${$}"]`, P = J.join("");
208
+ return `${_} { ${P} }`;
209
+ })) : [], a = n(e.variables), u = i(e.responsiveVariables), c = o(e.conditionalVariables), r = Z(t), m = f(r, "css/_variables.css"), j = `:root { ${a.join("")} ${u.join("")} } ${c.join("")}`;
210
+ k(m, j);
211
+ const S = f(r, "css/_global.css"), h = O(e.global, "");
212
+ k(S, `@layer global { ${h} }`);
213
+ const x = f(r, "css/_reset.css"), d = e.reset === "none" ? {} : typeof e.reset == "object" ? e.reset : kt, w = O(d, "");
214
+ k(x, `@layer reset { ${w} }`);
215
+ const l = f(r, "css/_templates.css"), g = et(e.templates), N = xt(e.templates);
216
+ k(l, g);
217
+ const b = f(r, "types/css-tokens.d.ts"), F = `
218
+ // Variable types
219
+ type VariableTokens = ${[...s].join("|")};
220
+ type PropertyValueToken = \`{\${VariableTokens}}\`;
221
+
222
+ // Template types
223
+ type TemplateTokens = {
224
+ ${Object.entries(N).map(([p, y]) => `${p}?: ${y}`).join(`
225
+ `)}
226
+ }
227
+ `;
228
+ k(b, F);
229
+ }, Q = (t) => t.replace(/styled\(([^"'`{,]+),/g, (e, s) => {
230
+ const n = /^['"`]/.test(s);
231
+ if (n && console.log("String tag", s), n) return e;
232
+ const i = new RegExp(`import[^;]*${s}[,\\s{][^;]*from\\s?([^{};]+);`), o = i.test(t);
233
+ if (o || console.log("Not imported", s), !o) return e;
234
+ const a = i.exec(t);
235
+ if (a) {
236
+ const u = a.at(1), c = ct.some((r) => u == null ? void 0 : u.includes(r));
237
+ if (c && console.log("Salty import for", s, `"${a.at(0)}"`), c) return e;
238
+ }
239
+ return console.log("Replacing", s), "styled('div',";
240
+ }), q = async (t, e, s) => {
241
+ console.log({ sourceFilePath: e });
242
+ const n = G(e), i = f(s, "./temp");
243
+ K(i) || z(i);
244
+ const o = B(e);
245
+ let a = A(e, "utf8");
246
+ a = Q(a);
247
+ const u = f(s, "js", n + ".js"), c = it(t), r = await ot(t);
248
+ await v.build({
249
+ stdin: {
250
+ contents: a,
251
+ sourcefile: o.base,
252
+ resolveDir: o.dir,
253
+ loader: "tsx"
254
+ },
255
+ minify: !1,
146
256
  treeShaking: !0,
147
257
  bundle: !0,
148
- outfile: n,
149
- format: "esm",
150
- target: ["es2022"],
258
+ outfile: u,
259
+ format: r,
260
+ target: ["node20"],
151
261
  keepNames: !0,
152
- external: ["react"]
262
+ external: c,
263
+ packages: "external",
264
+ plugins: [
265
+ {
266
+ name: "test",
267
+ setup: (S) => {
268
+ S.onLoad({ filter: /.*.css.ts/ }, (h) => {
269
+ console.log("Loading", {
270
+ sourceFilePath: e,
271
+ args: h
272
+ });
273
+ const x = A(h.path, "utf8");
274
+ return { contents: Q(x) };
275
+ });
276
+ }
277
+ }
278
+ ]
153
279
  });
154
- const o = Date.now();
155
- return await import(`${n}?t=${o}`);
156
- }, _ = async (t) => {
157
- const s = T(t), e = y(s, "salty-config.js"), { config: n } = await import(e);
158
- return n;
159
- }, nt = async (t) => {
280
+ const m = Date.now();
281
+ return await import(`${u}?t=${m}`);
282
+ }, U = async (t) => {
283
+ const e = Z(t), s = f(e, "salty.config.js"), n = Date.now(), { config: i } = await import(`${s}?t=${n}`);
284
+ return i;
285
+ }, at = () => {
160
286
  try {
161
- const s = [], e = [], n = T(t), o = y(n, "index.css");
287
+ return process.env.NODE_ENV === "production";
288
+ } catch {
289
+ return !1;
290
+ }
291
+ }, Dt = async (t, e = at()) => {
292
+ try {
293
+ const s = Date.now();
294
+ e ? I.info("Generating CSS in production mode! 🔥") : I.info("Generating CSS in development mode! 🚀");
295
+ const n = [], i = [], o = Z(t), a = f(o, "index.css");
162
296
  (() => {
163
- q(n) && L("rm -rf " + n), A(n), A(y(n, "css")), A(y(n, "types"));
164
- })(), await z(t);
165
- const $ = await _(t);
166
- async function a(p, h) {
167
- const b = G(p);
297
+ K(o) && dt("rm -rf " + o), z(o), z(f(o, "css")), z(f(o, "types"));
298
+ })(), await Pt(t);
299
+ const c = await U(t);
300
+ async function r(l, g) {
301
+ const N = ["node_modules", "saltygen"], b = gt(l);
168
302
  if (b.isDirectory()) {
169
- const j = U(p);
170
- await Promise.all(j.map((w) => a(y(p, w), y(h, w))));
171
- } else if (b.isFile() && E(p)) {
172
- const w = await M(p, n), F = [];
173
- Object.entries(w).forEach(([c, m]) => {
174
- if (m.isKeyframes && m.css) {
175
- const O = `${m.animationName}.css`, J = `css/${O}`, K = y(n, J);
176
- s.push(O), C(K, m.css);
303
+ const T = yt(l);
304
+ if (N.some((p) => l.includes(p))) return;
305
+ await Promise.all(T.map((p) => r(f(l, p), f(g, p))));
306
+ } else if (b.isFile() && W(l)) {
307
+ const F = await q(t, l, o), p = [];
308
+ Object.entries(F).forEach(([_, P]) => {
309
+ if (P.isKeyframes && P.css) {
310
+ const X = `a_${P.animationName}.css`, pt = `css/${X}`, ut = f(o, pt);
311
+ n.push(X), k(ut, P.css);
177
312
  return;
178
313
  }
179
- if (!m.generator) return;
180
- const l = m.generator._withBuildContext({
181
- name: c,
182
- config: $
183
- }), S = `${l.hash}-${l.priority}.css`;
184
- e[l.priority] || (e[l.priority] = []), e[l.priority].push(S), F.push(S);
185
- const D = `css/${S}`, N = y(n, D);
186
- C(N, l.css);
314
+ if (!P.generator) return;
315
+ const E = P.generator._withBuildContext({
316
+ name: _,
317
+ config: c,
318
+ prod: e
319
+ });
320
+ i[E.priority] || (i[E.priority] = []), i[E.priority].push(E.cssFileName), p.push(E.cssFileName);
321
+ const lt = `css/${E.cssFileName}`, ft = f(o, lt);
322
+ k(ft, E.css);
187
323
  });
188
- const d = F.map((c) => `@import url('./${c}');`).join(`
189
- `), x = R(p, 6), g = y(n, `css/${x}.css`);
190
- C(g, d);
324
+ const y = p.map((_) => `@import url('./${_}');`).join(`
325
+ `), C = G(l, 6), $ = B(l), M = V($.name), J = f(o, `css/f_${M}-${C}.css`);
326
+ k(J, y);
191
327
  }
192
328
  }
193
- await a(t, n);
194
- const f = s.map((p) => `@import url('./css/${p}');`).join(`
329
+ await r(t, o);
330
+ const m = n.map((l) => `@import url('./css/${l}');`).join(`
195
331
  `);
196
- let i = `@layer l0, l1, l2, l3, l4, l5, l6, l7, l8;
332
+ let x = `@layer reset, global, l0, l1, l2, l3, l4, l5, l6, l7, l8;
197
333
 
198
- ${["@import url('./css/variables.css');", "@import url('./css/global.css');", "@import url('./css/templates.css');"].join(`
334
+ ${["_variables.css", "_reset.css", "_global.css", "_templates.css"].filter((l) => {
335
+ try {
336
+ return A(f(o, "css", l), "utf8").length > 0;
337
+ } catch {
338
+ return !1;
339
+ }
340
+ }).map((l) => `@import url('./css/${l}');`).join(`
199
341
  `)}
200
- ${f}`;
201
- if ($.importStrategy !== "component") {
202
- const p = e.flat().map((h) => `@import url('./css/${h}');`).join(`
203
- `);
204
- i += p;
342
+ ${m}`;
343
+ if (c.importStrategy !== "component") {
344
+ const l = i.reduce((g, N, b) => {
345
+ const T = N.reduce((C, $) => {
346
+ const M = A(f(o, "css", $), "utf8");
347
+ return `${C}
348
+ ${M}`;
349
+ }, ""), F = `l_${b}.css`, p = f(o, "css", F), y = `@layer l${b} { ${T} }`;
350
+ return k(p, y), `${g}
351
+ @import url('./css/${F}');`;
352
+ }, "");
353
+ x += l;
205
354
  }
206
- C(o, i);
355
+ k(a, x);
356
+ const d = Date.now() - s, w = d < 200 ? "🔥" : d < 500 ? "🚀" : d < 1e3 ? "🎉" : d < 2e3 ? "🚗" : d < 5e3 ? "🤔" : "🥴";
357
+ I.info(`Generated CSS in ${d}ms! ${w}`);
207
358
  } catch (s) {
208
359
  console.error(s);
209
360
  }
210
- }, ot = async (t, s) => {
361
+ }, Et = async (t, e) => {
211
362
  try {
212
- const e = [], n = y(t, "./saltygen"), o = y(n, "index.css");
213
- if (E(s)) {
214
- const $ = await _(t), a = await M(s, n);
215
- Object.entries(a).forEach(([h, b]) => {
216
- if (!b.generator) return;
217
- const j = b.generator._withBuildContext({
218
- name: h,
219
- config: $
220
- }), w = `${j.hash}-${j.priority}.css`, F = `css/${w}`, d = y(n, F);
221
- e.push(w), C(d, j.css);
363
+ const s = [], n = f(t, "./saltygen"), i = f(n, "index.css");
364
+ if (W(e)) {
365
+ const a = await U(t), u = await q(t, e, n);
366
+ Object.entries(u).forEach(([S, h]) => {
367
+ if (h.isKeyframes && h.css) {
368
+ const l = `css/${`a_${h.animationName}.css`}`, g = f(n, l);
369
+ k(g, h.css);
370
+ return;
371
+ }
372
+ if (!h.generator) return;
373
+ const x = h.generator._withBuildContext({
374
+ name: S,
375
+ config: a
376
+ }), D = `css/${x.cssFileName}`, d = f(n, D);
377
+ s.push(x.cssFileName), k(d, x.css);
222
378
  });
223
- const f = B(o, "utf8").split(`
224
- `), r = e.map((h) => `@import url('../saltygen/css/${h}');`), p = [.../* @__PURE__ */ new Set([...f, ...r])].join(`
379
+ const c = A(i, "utf8").split(`
380
+ `), r = s.map((S) => `@import url('../saltygen/css/${S}');`), j = [.../* @__PURE__ */ new Set([...c, ...r])].join(`
225
381
  `);
226
- C(o, p);
382
+ k(i, j);
227
383
  }
228
- } catch (e) {
229
- console.error(e);
384
+ } catch (s) {
385
+ console.error(s);
230
386
  }
231
- }, rt = async (t, s) => {
387
+ }, Ot = async (t, e, s = at()) => {
232
388
  try {
233
- const e = y(t, "./saltygen");
234
- if (E(s)) {
235
- const o = B(s, "utf8");
236
- o.replace(/^(?!export\s)const\s.*/gm, (i) => `export ${i}`) !== o && await X(s, o);
237
- const $ = await _(t), a = await M(s, e);
238
- let f = o;
239
- Object.entries(a).forEach(([i, p]) => {
240
- var d;
241
- if (p.isKeyframes) {
242
- console.log("value", p);
243
- return;
389
+ const n = f(t, "./saltygen");
390
+ if (W(e)) {
391
+ const o = A(e, "utf8");
392
+ o.replace(/^(?!export\s)const\s.*/gm, (m) => `export ${m}`) !== o && await ht(e, o);
393
+ const u = await U(t), c = await q(t, e, n);
394
+ let r = o;
395
+ if (Object.entries(c).forEach(([m, j]) => {
396
+ var C;
397
+ if (j.isKeyframes || !j.generator) return;
398
+ const S = j.generator._withBuildContext({
399
+ name: m,
400
+ config: u,
401
+ prod: s
402
+ }), h = new RegExp(`\\s${m}[=\\s]+[^()]+styled\\(([^,]+),`, "g").exec(o);
403
+ if (!h) return console.error("Could not find the original declaration");
404
+ const x = (C = h.at(1)) == null ? void 0 : C.trim(), D = new RegExp(`\\s${m}[=\\s]+styled\\(`, "g").exec(r);
405
+ if (!D) return console.error("Could not find the original declaration");
406
+ const { index: d } = D;
407
+ let w = !1;
408
+ const l = setTimeout(() => w = !0, 5e3);
409
+ let g = 0, N = !1, b = 0;
410
+ for (; !N && !w; ) {
411
+ const $ = r[d + g];
412
+ $ === "(" && b++, $ === ")" && b--, b === 0 && $ === ")" && (N = !0), g > r.length && (w = !0), g++;
244
413
  }
245
- if (!p.generator) return;
246
- const h = p.generator._withBuildContext({
247
- name: i,
248
- config: $
249
- }), b = new RegExp(`${i}[=\\s]+[^()]+styled\\(([^,]+),`, "g").exec(o);
250
- if (!b)
251
- return console.error("Could not find the original declaration");
252
- 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");
253
- f = f.replace(F, w);
254
- });
255
- const r = R(s, 6);
256
- return $.importStrategy === "component" && (f = `import '../../saltygen/css/${r}.css';
257
- ${f}`), f = f.replace("{ styled }", "{ styledClient as styled }"), f = f.replace("@salty-css/react/styled", "@salty-css/react/styled-client"), f;
414
+ if (!w) clearTimeout(l);
415
+ else throw new Error("Failed to find the end of the styled call and timed out");
416
+ const T = d + g, F = r.slice(d, T), p = r, y = ` ${m} = styled(${x}, "${S.classNames}", ${JSON.stringify(S.props)});`;
417
+ r = r.replace(F, y), p === r && console.error("Minimize file failed to change content", { name: m, tagName: x });
418
+ }), u.importStrategy === "component") {
419
+ const m = G(e, 6), j = B(e);
420
+ r = `import '../../saltygen/css/${`f_${V(j.name)}-${m}.css`}';
421
+ ${r}`;
422
+ }
423
+ return r = r.replace("{ styled }", "{ styledClient as styled }"), r = r.replace("@salty-css/react/styled", "@salty-css/react/styled-client"), r;
258
424
  }
259
- } catch (e) {
260
- console.error(e);
425
+ } catch (n) {
426
+ console.error("Error in minimizeFile:", n);
261
427
  }
262
- }, ft = (t) => ({
428
+ }, Jt = (t) => ({
263
429
  name: "stylegen",
264
- buildStart: () => nt(t),
265
- load: async (s) => {
266
- if (E(s))
267
- return await rt(t, s);
430
+ buildStart: () => Dt(t),
431
+ load: async (e) => {
432
+ if (W(e))
433
+ return await Ot(t, e);
434
+ },
435
+ handleHotUpdate: async ({ file: e, server: s }) => {
436
+ e.includes("salty.config") && await s.restart();
268
437
  },
269
438
  watchChange: {
270
- handler: async (s) => {
271
- E(s) && await ot(t, s), s.includes("salty-config") && await z(t);
439
+ handler: async (e) => {
440
+ W(e) && await Et(t, e);
272
441
  }
273
442
  }
274
443
  });
275
444
  export {
276
- ft as saltyPlugin
445
+ Jt as default,
446
+ Jt as saltyPlugin
277
447
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@salty-css/vite",
3
- "version": "0.0.1-alpha.14",
3
+ "version": "0.0.1-alpha.140",
4
4
  "main": "./dist/index.js",
5
5
  "module": "./dist/index.mjs",
6
6
  "typings": "./dist/index.d.ts",
@@ -10,7 +10,12 @@
10
10
  "publishConfig": {
11
11
  "access": "public"
12
12
  },
13
- "homepage": "https://github.com/margarita-form/salty-css",
13
+ "description": "Vite plugin for Salty CSS",
14
+ "homepage": "https://salty-css.dev/",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/margarita-form/salty-css.git"
18
+ },
14
19
  "bugs": {
15
20
  "url": "https://github.com/margarita-form/salty-css/issues"
16
21
  },
@@ -27,5 +32,8 @@
27
32
  "import": "./index.js",
28
33
  "require": "./index.cjs"
29
34
  }
35
+ },
36
+ "dependencies": {
37
+ "@salty-css/core": "^0.0.1-alpha.140"
30
38
  }
31
39
  }