@salty-css/vite 0.0.1-alpha.12 → 0.0.1-alpha.121

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 +102 -26
  2. package/index.cjs +24 -14
  3. package/index.d.ts +1 -0
  4. package/index.js +333 -212
  5. package/package.json +10 -2
package/README.md CHANGED
@@ -1,15 +1,91 @@
1
- # Salty Css
1
+ # Salty CSS - Kinda sweet but yet spicy CSS-in-JS library
2
2
 
3
- ## Basic usage example with Button
3
+ In the world of frontend dev is there anything saltier than CSS? Salty CSS is built to provide better developer experience for developers looking for performant and feature rich CSS-in-JS solutions.
4
4
 
5
- ### Initial requirements
5
+ ## Features
6
6
 
7
- 1. Add `saltyPlugin` to vite or webpack config from `@salty-css/vite` or `@salty-css/webpack`
8
- 2. Create `salty-config.ts` to the root of your project
9
- 3. Import global styles to any regular .css file from `saltygen/index.css` (does not exist during first run, cli command coming later)
10
- 4. Create salty components with styled only inside files that end with `.css.ts`, `.salty.ts` `.styled.ts` or `.styles.ts`
7
+ - Build time compilation to achieve awesome runtime performance and minimal size
8
+ - Next.js, React Server Components, Vite and Webpack support
9
+ - Type safety with out of the box TypeScript and ESLint plugin
10
+ - Advanced CSS variables configuration to allow smooth token usage
11
+ - Style templates to create reusable styles easily
11
12
 
12
- ### Code examples
13
+ ## Get started
14
+
15
+ - Initialize: `npx salty-css init [directory]`
16
+ - Create component: `npx salty-css generate [filePath]`
17
+ - Build: `npx salty-css build [directory]`
18
+
19
+ ### Initialize
20
+
21
+ Fastest way to get started with any framework is [npx salty-css init [directory]](#initialize-salty-css-for-a-project) command
22
+
23
+ - Next.js → [Next.js guide](#nextjs) + [Next.js example app](https://github.com/margarita-form/salty-css-website)
24
+ - React → [React guide](#react) + [React example code](#code-examples)
25
+ - Vite → [Vite guide](#vite)
26
+ - Webpack → Guide coming soon
27
+ - ESLint → Guide coming soon
28
+
29
+ ### Salty CSS CLI
30
+
31
+ In your existing repository you can use `npx salty-css [command]` to initialize a project, generate components, update related packages and build required files.
32
+
33
+ - 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.
34
+ - 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.
35
+ - 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
36
+
37
+ ### Guides
38
+
39
+ #### Next.js
40
+
41
+ In your existing Next.js repository you can run `npx salty-css init` to automatically configure Salty CSS.
42
+
43
+ ##### Manual configuration
44
+
45
+ 1. For Next.js support install `npm i @salty-css/next @salty-css/core @salty-css/react`
46
+ 2. Create `salty.config.ts` to your app directory
47
+ 3. Add Salty CSS plugin to next.js config
48
+
49
+ - **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);`
50
+ - **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);`
51
+
52
+ 4. Make sure that `salty.config.ts` and `next.config.ts` are in the same folder!
53
+ 5. Build `saltygen` directory by running your app once or with cli `npx salty-css build [directory]`
54
+ 6. Import global styles from `saltygen/index.css` to some global css file with `@import 'insert_path_to_index_css';`.
55
+
56
+ [Check out Next.js demo project](https://github.com/margarita-form/salty-css-website) or [react example code](#code-examples)
57
+
58
+ #### Vite
59
+
60
+ In your existing Vite repository you can run `npx salty-css init` to automatically configure Salty CSS.
61
+
62
+ ##### Manual configuration
63
+
64
+ 1. For Vite support install `npm i @salty-css/vite @salty-css/core`
65
+ 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
66
+ 3. Make sure that `salty.config.ts` and `vite.config.ts` are in the same folder!
67
+ 4. Build `saltygen` directory by running your app once or with cli `npx salty-css build [directory]`
68
+ 5. Import global styles from `saltygen/index.css` to some global css file with `@import 'insert_path_to_index_css';`.
69
+
70
+ #### React
71
+
72
+ In your existing React repository you can run `npx salty-css init` to automatically configure Salty CSS.
73
+
74
+ ##### Manual configuration
75
+
76
+ 1. Install related dependencies: `npm i @salty-css/core @salty-css/react`
77
+ 2. Create `salty.config.ts` to your app directory
78
+ 3. Configure your build tool to support Salty CSS ([Vite](#vite) or Webpack) or after changes run `npx salty-css build`
79
+
80
+ [Check out react example code](#code-examples)
81
+
82
+ ### Create components
83
+
84
+ 1. Create salty components with styled only inside files that end with `.css.ts`, `.salty.ts` `.styled.ts` or `.styles.ts`
85
+
86
+ ## Code examples
87
+
88
+ ### Basic usage example with Button
13
89
 
14
90
  **Salty config**
15
91
 
@@ -31,23 +107,6 @@ export const config = defineConfig({
31
107
  });
32
108
  ```
33
109
 
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
110
  **Wrapper** (`components/wrapper/wrapper.css.ts`)
52
111
 
53
112
  ```tsx
@@ -72,7 +131,7 @@ export const Button = styled('button', {
72
131
  padding: `0.6em 1.2em`,
73
132
  border: '1px solid currentColor',
74
133
  background: 'transparent',
75
- color: 'currentColor/40',
134
+ color: 'currentColor',
76
135
  cursor: 'pointer',
77
136
  transition: '200ms',
78
137
  textDecoration: 'none',
@@ -108,4 +167,21 @@ export const Button = styled('button', {
108
167
  });
109
168
  ```
110
169
 
170
+ **Your React component file**
171
+
172
+ ```tsx
173
+ import { Wrapper } from '../components/wrapper/wrapper.css';
174
+ import { Button } from '../components/button/button.css';
175
+
176
+ export const IndexPage = () => {
177
+ return (
178
+ <Wrapper>
179
+ <Button variant="solid" onClick={() => alert('It is a button.')}>
180
+ Outlined
181
+ </Button>
182
+ </Wrapper>
183
+ );
184
+ };
185
+ ```
186
+
111
187
  More examples coming soon
package/index.cjs CHANGED
@@ -1,18 +1,28 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const K=require("esbuild"),W=require("winston"),L=require("child_process"),y=require("path"),d=require("fs"),G=require("fs/promises");function R(t){const s=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const e in t)if(e!=="default"){const n=Object.getOwnPropertyDescriptor(t,e);Object.defineProperty(s,e,n.get?n:{enumerable:!0,get:()=>t[e]})}}return s.default=t,Object.freeze(s)}const Z=R(K),k=R(W),q=t=>String.fromCharCode(t+(t>25?39:97)),U=(t,s)=>{let e="",n;for(n=Math.abs(t);n>52;n=n/52|0)e=q(n%52)+e;return e=q(n%52)+e,e.length<s?e=e.padStart(s,"a"):e.length>s&&(e=e.slice(-s)),e},X=(t,s)=>{let e=s.length;for(;e;)t=t*33^s.charCodeAt(--e);return t},_=(t,s=3)=>{const e=X(5381,JSON.stringify(t))>>>0;return U(e,s)};function V(t){return t?typeof t!="string"?String(t):t.replace(/\s/g,"-").replace(/[A-Z](?:(?=[^A-Z])|[A-Z]*(?=[A-Z][^A-Z]|$))/g,(s,e)=>(e>0?"-":"")+s.toLowerCase()):""}const Y=(t,s)=>{if(typeof t!="string")return{result:t};if(!s)return{result:t};const e=[];return Object.values(s).forEach(n=>{const{pattern:o,transform:g}=n;t=t.replace(o,$=>{const{value:a,css:f}=g($);return f&&e.push(f),a})}),{result:t,additionalCss:e}},I=t=>typeof t!="string"?{result:t}:/\{[^{}]+\}/g.test(t)?{result:t.replace(/\{([^{}]+)\}/g,(...n)=>`var(--${V(n[1].replaceAll(".","-"))})`)}:{result:t},D=(t,s,e,n)=>{const o=[],g=Object.entries(t).reduce((a,[f,r])=>{const i=f.trim();if(typeof r=="function"&&(r=r()),typeof r=="object"){if(!r)return a;if(i==="variants")return Object.entries(r).forEach(([u,c])=>{c&&Object.entries(c).forEach(([m,l])=>{if(!l)return;const O=`${s}.${u}-${m}`,P=D(l,O);o.push(P)})}),a;if(i==="defaultVariants")return a;if(i==="compoundVariants")return r.forEach(u=>{const{css:c,...m}=u,l=Object.entries(m).reduce((P,[x,N])=>`${P}.${x}-${N}`,s),O=D(c,l);o.push(O)}),a;if(i.startsWith("@")){const u=D(r,s),c=`${i} {
2
- ${u.replace(`
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const ce=require("esbuild"),ae=require("child_process"),c=require("path"),f=require("fs"),U=require("fs/promises"),R=require("winston");var Z=typeof document<"u"?document.currentScript:null;function le(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 G=le(ce),L=e=>String.fromCharCode(e+(e>25?39:97)),ue=(e,t)=>{let s="",n;for(n=Math.abs(e);n>52;n=n/52|0)s=L(n%52)+s;return s=L(n%52)+s,s.length<t?s=s.padStart(t,"a"):s.length>t&&(s=s.slice(-t)),s},fe=(e,t)=>{let s=t.length;for(;s;)e=e*33^t.charCodeAt(--s);return e},I=(e,t=5)=>{const s=fe(5381,JSON.stringify(e))>>>0;return ue(s,t)};function D(e){return e?typeof e!="string"?D(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 pe=(e,t)=>{if(typeof e!="string")return{result:e};if(!t)return{result:e};const s=[];return Object.values(t).forEach(n=>{const{pattern:r,transform:i}=n;e=e.replace(r,y=>{const{value:a,css:j}=i(y);return j&&s.push(j),a})}),{result:e,additionalCss:s}},X=e=>typeof e!="string"?{result:e}:/\{[^{}]+\}/g.test(e)?{result:e.replace(/\{([^{}]+)\}/g,(...n)=>`var(--${D(n[1].replaceAll(".","-"))})`)}:{result:e},N=(e,t,s,n)=>{if(!e)return"";const r=[],i=Object.entries(e).reduce((a,[j,o])=>{const l=j.trim();if(typeof o=="function"&&(o=o()),typeof o=="object"){if(!o)return a;if(l==="variants")return Object.entries(o).forEach(([b,p])=>{p&&Object.entries(p).forEach(([T,O])=>{if(!O)return;const _=`${t}.${b}-${T}`,g=N(O,_);r.push(g)})}),a;if(l==="defaultVariants")return a;if(l==="compoundVariants")return o.forEach(b=>{const{css:p,...T}=b,O=Object.entries(T).reduce((g,[m,S])=>`${g}.${m}-${S}`,t),_=N(p,O);r.push(_)}),a;if(l.startsWith("@")){const b=N(o,t),p=`${l} {
2
+ ${b.replace(`
3
3
  `,`
4
4
  `)}
5
- }`;return o.push(c),a}const h=f.includes("&")?i.replace("&",s):i.startsWith(":")?`${s}${i}`:`${s} ${i}`,F=D(r,h);return o.push(F),a}const p=i.startsWith("-")?i:V(i),b=(h,F=";")=>a=`${a}${h}${F}`,j=h=>b(`${p}:${h}`);if(typeof r=="number")return j(r);if(typeof r!="string")if("toString"in r)r=r.toString();else return a;const{modifiers:S}={},C=function*(){yield I(r),yield Y(r,S)}();for(const{result:h,additionalCss:F=[]}of C)r=h,F.forEach(u=>{const c=D(u,"");b(c,"")});return j(r)},"");if(!g)return o.join(`
6
- `);if(!s)return g;let $="";return $=`${s} { ${g} }`,[$,...o].join(`
7
- `)},z=(t,s=[])=>{const e=[],n={};if(Object.entries(t).forEach(([o,g])=>{if(typeof g=="object"){if(!g)return;const $=o.trim(),a=z(g,[...s,$]);e.push(a)}else n[o]=g}),Object.keys(n).length){const o=s.map(V).join("-"),g=D(n,`.${o}`);e.push(g)}return e.join(`
8
- `)};k.createLogger({level:"info",format:k.format.combine(k.format.colorize(),k.format.cli()),transports:[new k.transports.Console({})]});const E=t=>y.join(t,"./saltygen"),Q=["salty","css","styles","styled"],v=(t=[])=>new RegExp(`\\.(${[...Q,...t].join("|")})\\.`),T=(t,s=[])=>v(s).test(t),tt=async t=>{const s=E(t),e=y.join(t,"salty-config.ts"),n=y.join(s,"salty-config.js");await Z.build({entryPoints:[e],minify:!0,treeShaking:!0,bundle:!0,outfile:n,format:"esm",external:["react"]});const o=Date.now(),{config:g}=await import(`${n}?t=${o}`);return g},B=async t=>{const s=await tt(t),e=new Set,n=(u,c=[])=>u?Object.entries(u).flatMap(([m,l])=>{if(!l)return;if(typeof l=="object")return n(l,[...c,m]);const O=[...c,m].join(".");e.add(`"${O}"`);const P=[...c.map(V),V(m)].join("-"),{result:x}=I(l);return`--${P}: ${x};`}):[],o=u=>u?Object.entries(u).flatMap(([c,m])=>{const l=n(m);return c==="base"?l.join(""):`${c} { ${l.join("")} }`}):[],g=u=>u?Object.entries(u).flatMap(([c,m])=>Object.entries(m).flatMap(([l,O])=>{const P=n(O,[c]),x=`.${c}-${l}, [data-${c}="${l}"]`,N=P.join("");return`${x} { ${N} }`})):[],$=n(s.variables),a=o(s.responsiveVariables),f=g(s.conditionalVariables),r=E(t),i=y.join(r,"css/variables.css"),p=`:root { ${$.join("")} ${a.join("")} } ${f.join("")}`;d.writeFileSync(i,p);const b=y.join(r,"types/css-tokens.d.ts"),S=`type VariableTokens = ${[...e].join("|")}; type PropertyValueToken = \`{\${VariableTokens}}\``;d.writeFileSync(b,S);const w=y.join(r,"css/global.css"),C=D(s.global,"");d.writeFileSync(w,C);const h=y.join(r,"css/templates.css"),F=z(s.templates);d.writeFileSync(h,F)},A=async(t,s)=>{const e=_(t),n=y.join(s,"js",e+".js");await Z.build({entryPoints:[t],minify:!0,treeShaking:!0,bundle:!0,outfile:n,format:"esm",target:["es2022"],keepNames:!0,external:["react"]});const o=Date.now();return await import(`${n}?t=${o}`)},M=async t=>{const s=E(t),e=y.join(s,"salty-config.js"),{config:n}=await import(e);return n},st=async t=>{try{const s=[],e=[],n=E(t),o=y.join(n,"index.css");(()=>{d.existsSync(n)&&L.execSync("rm -rf "+n),d.mkdirSync(n),d.mkdirSync(y.join(n,"css")),d.mkdirSync(y.join(n,"types"))})(),await B(t);const $=await M(t);async function a(p,b){const j=d.statSync(p);if(j.isDirectory()){const S=d.readdirSync(p);await Promise.all(S.map(w=>a(y.join(p,w),y.join(b,w))))}else if(j.isFile()&&T(p)){const w=await A(p,n),C=[];Object.entries(w).forEach(([c,m])=>{if(m.isKeyframes&&m.css){const N=`${m.animationName}.css`,H=`css/${N}`,J=y.join(n,H);s.push(N),d.writeFileSync(J,m.css);return}if(!m.generator)return;const l=m.generator._withBuildContext({name:c,config:$}),O=`${l.hash}-${l.priority}.css`;e[l.priority]||(e[l.priority]=[]),e[l.priority].push(O),C.push(O);const P=`css/${O}`,x=y.join(n,P);d.writeFileSync(x,l.css)});const h=C.map(c=>`@import url('./${c}');`).join(`
9
- `),F=_(p,6),u=y.join(n,`css/${F}.css`);d.writeFileSync(u,h)}}await a(t,n);const f=s.map(p=>`@import url('./css/${p}');`).join(`
10
- `);let i=`@layer l0, l1, l2, l3, l4, l5, l6, l7, l8;
5
+ }`;return r.push(p),a}const h=j.includes("&")?l.replace("&",t):l.startsWith(":")?`${t}${l}`:`${t} ${l}`,x=N(o,h);return r.push(x),a}const w=l.startsWith("-")?l:D(l),F=(h,x=";")=>a=`${a}${h}${x}`,$=h=>F(`${w}:${h}`);if(typeof o=="number")return $(o);if(typeof o!="string")if("toString"in o)o=o.toString();else return a;const{modifiers:u}={},C=function*(){yield X(o),yield pe(o,u)}();for(const{result:h,additionalCss:x=[]}of C)o=h,x.forEach(b=>{const p=N(b,"");F(p,"")});return $(o)},"");if(!i)return r.join(`
6
+ `);if(!t)return i;let y="";return y=`${t} { ${i} }`,[y,...r].join(`
7
+ `)},Y=(e,t=[])=>{if(!e)return"";const s=[],n={};if(Object.entries(e).forEach(([r,i])=>{if(typeof i=="object"){if(!i)return;const y=r.trim(),a=Y(i,[...t,y]);s.push(a)}else n[r]=i}),Object.keys(n).length){const r=t.map(D).join("-"),i=N(n,`.${r}`);s.push(i)}return s.join(`
8
+ `)},de=e=>Object.entries(e).reduce((t,[s,n])=>(typeof n=="object"&&(t[s]=Q(n).map(r=>`"${r}"`).join(" | ")),t),{}),Q=(e,t="",s=new Set)=>e?(Object.entries(e).forEach(([n,r])=>{const i=t?`${t}.${n}`:n;return typeof r=="object"?Q(r,i,s):s.add(t)}),[...s]):[],v=e=>{if(!e||e==="/")throw new Error("Could not find package.json file");const t=c.join(e,"package.json");return f.existsSync(t)?t:v(c.join(e,".."))},ye=async e=>{const t=v(e);return await U.readFile(t,"utf-8").then(JSON.parse).catch(()=>{})},ge=async e=>{const t=await ye(e);if(t)return t.type};let E;const ee=async e=>{if(E)return E;const t=await ge(e);return t==="module"?E="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"))&&(E="cjs"),E||"esm"},K=R.createLogger({level:"debug",format:R.format.combine(R.format.colorize(),R.format.cli()),transports:[new R.transports.Console({})]});function te(e){return e?typeof e!="string"?te(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 me={"*, *::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"},button:{lineHeight:"1em"},"input, optgroup, select, textarea":{fontFamily:"inherit",fontSize:"100%",lineHeight:"1.15em"}},q={externalModules:[]},se=e=>{if(q.externalModules.length>0)return q.externalModules;const t=c.join(e,"salty.config.ts"),n=f.readFileSync(t,"utf8").match(/externalModules:\s?\[(.*)\]/);if(!n)return[];const r=n[1].split(",").map(i=>i.replace(/['"`]/g,"").trim());return q.externalModules=r,r},z=e=>c.join(e,"./saltygen"),he=["salty","css","styles","styled"],be=(e=[])=>new RegExp(`\\.(${[...he,...e].join("|")})\\.`),J=(e,t=[])=>be(t).test(e),je=async e=>{const t=z(e),s=c.join(e,"salty.config.ts"),n=c.join(t,"salty.config.js"),r=await ee(e),i=se(e);await G.build({entryPoints:[s],minify:!0,treeShaking:!0,bundle:!0,outfile:n,format:r,external:i});const y=Date.now(),{config:a}=await import(`${n}?t=${y}`);return a},ne=async e=>{const t=await je(e),s=new Set,n=(g,m=[])=>g?Object.entries(g).flatMap(([S,d])=>{if(!d)return;if(typeof d=="object")return n(d,[...m,S]);const P=te(S),V=D(S),A=[...m,P].join(".");s.add(`"${A}"`);const M=[...m.map(D),V].join("-"),{result:W}=X(d);return`--${M}: ${W};`}):[],r=g=>g?Object.entries(g).flatMap(([m,S])=>{const d=n(S);return m==="base"?d.join(""):`${m} { ${d.join("")} }`}):[],i=g=>g?Object.entries(g).flatMap(([m,S])=>Object.entries(S).flatMap(([d,P])=>{const V=n(P,[m]),A=`.${m}-${d}, [data-${m}="${d}"]`,M=V.join("");return`${A} { ${M} }`})):[],y=n(t.variables),a=r(t.responsiveVariables),j=i(t.conditionalVariables),o=z(e),l=c.join(o,"css/_variables.css"),w=`:root { ${y.join("")} ${a.join("")} } ${j.join("")}`;f.writeFileSync(l,w);const F=c.join(o,"css/_global.css"),$=N(t.global,"");f.writeFileSync(F,`@layer global { ${$} }`);const u=c.join(o,"css/_reset.css"),C=t.reset==="none"?{}:typeof t.reset=="object"?t.reset:me,h=N(C,"");f.writeFileSync(u,`@layer reset { ${h} }`);const x=c.join(o,"css/_templates.css"),b=Y(t.templates),p=de(t.templates);f.writeFileSync(x,b);const T=c.join(o,"types/css-tokens.d.ts"),_=`
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(p).map(([g,m])=>`${g}?: ${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=y.join(t,"./saltygen"),o=y.join(n,"index.css");if(T(s)){const $=await M(t),a=await A(s,n);Object.entries(a).forEach(([b,j])=>{if(!j.generator)return;const S=j.generator._withBuildContext({name:b,config:$}),w=`${S.hash}-${S.priority}.css`,C=`css/${w}`,h=y.join(n,C);e.push(w),d.writeFileSync(h,S.css)});const f=d.readFileSync(o,"utf8").split(`
16
- `),r=e.map(b=>`@import url('../saltygen/css/${b}');`),p=[...new Set([...f,...r])].join(`
17
- `);d.writeFileSync(o,p)}}catch(e){console.error(e)}},nt=async(t,s)=>{try{const e=y.join(t,"./saltygen");if(T(s)){let o=d.readFileSync(s,"utf8");o.replace(/^(?!export\s)const\s.*/gm,i=>`export ${i}`)!==o&&await G.writeFile(s,o);const $=await M(t),a=await A(s,e);let f=o;Object.entries(a).forEach(([i,p])=>{var u;if(p.isKeyframes){console.log("value",p);return}if(!p.generator)return;const b=p.generator._withBuildContext({name:i,config:$}),j=new RegExp(`${i}[=\\s]+[^()]+styled\\(([^,]+),`,"g").exec(o);if(!j)return console.error("Could not find the original declaration");const S=(u=j.at(1))==null?void 0:u.trim(),{element:w,variantKeys:C}=b.props,h=`${i} = styled(${S}, "${b.classNames}", "${b._callerName}", ${JSON.stringify(w)}, ${JSON.stringify(C)});`,F=new RegExp(`${i}[=\\s]+[^()]+styled\\(([^,]+),[^;]+;`,"g");f=f.replace(F,h)});const r=_(s,6);return $.importStrategy==="component"&&(f=`import '../../saltygen/css/${r}.css';
18
- ${f}`),f=f.replace("{ styled }","{ styledClient as styled }"),f=f.replace("@salty-css/react/styled","@salty-css/react/styled-client"),f}}catch(e){console.error(e)}},ot=t=>({name:"stylegen",buildStart:()=>st(t),load:async s=>{if(T(s))return await nt(t,s)},watchChange:{handler:async s=>{T(s)&&await et(t,s),s.includes("salty-config")&&await B(t)}}});exports.saltyPlugin=ot;
17
+ }
18
+ `;f.writeFileSync(T,_)},H=async(e,t,s)=>{const n=I(t),r=c.join(s,"./temp");f.existsSync(r)||f.mkdirSync(r);const i=c.parse(t);let y=f.readFileSync(t,"utf8");y=y.replace(/styled\([^"'`{,]+,/g,"styled('div',");const a=c.join(s,"js",n+".js"),j=se(e),o=await ee(e);await G.build({stdin:{contents:y,sourcefile:i.base,resolveDir:i.dir,loader:"tsx"},minify:!1,treeShaking:!0,bundle:!0,outfile:a,format:o,target:["node20"],keepNames:!0,external:j,packages:"external"});const l=Date.now();return await import(`${a}?t=${l}`)},B=async e=>{const t=z(e),s=c.join(t,"salty.config.js"),{config:n}=await import(s);return n},oe=()=>{try{return process.env.NODE_ENV==="production"}catch{return!1}},Se=async(e,t=oe())=>{try{t?K.info("Generating CSS in production mode! 🔥"):K.info("Generating CSS in development mode! 🚀");const s=[],n=[],r=z(e),i=c.join(r,"index.css");(()=>{f.existsSync(r)&&ae.execSync("rm -rf "+r),f.mkdirSync(r),f.mkdirSync(c.join(r,"css")),f.mkdirSync(c.join(r,"types"))})(),await ne(e);const a=await B(e);async function j(u,k){const C=["node_modules","saltygen"],h=f.statSync(u);if(h.isDirectory()){const x=f.readdirSync(u);if(C.some(p=>u.includes(p)))return;await Promise.all(x.map(p=>j(c.join(u,p),c.join(k,p))))}else if(h.isFile()&&J(u)){const b=await H(e,u,r),p=[];Object.entries(b).forEach(([S,d])=>{if(d.isKeyframes&&d.css){const M=`a_${d.animationName}.css`,W=`css/${M}`,ie=c.join(r,W);s.push(M),f.writeFileSync(ie,d.css);return}if(!d.generator)return;const P=d.generator._withBuildContext({name:S,config:a,prod:t});n[P.priority]||(n[P.priority]=[]),n[P.priority].push(P.cssFileName),p.push(P.cssFileName);const V=`css/${P.cssFileName}`,A=c.join(r,V);f.writeFileSync(A,P.css)});const T=p.map(S=>`@import url('./${S}');`).join(`
19
+ `),O=I(u,6),_=c.parse(u),g=D(_.name),m=c.join(r,`css/f_${g}-${O}.css`);f.writeFileSync(m,T)}}await j(e,r);const o=s.map(u=>`@import url('./css/${u}');`).join(`
20
+ `);let $=`@layer reset, global, l0, l1, l2, l3, l4, l5, l6, l7, l8;
21
+
22
+ ${["_variables.css","_reset.css","_global.css","_templates.css"].filter(u=>{try{return f.readFileSync(c.join(r,"css",u),"utf8").length>0}catch{return!1}}).map(u=>`@import url('./css/${u}');`).join(`
23
+ `)}
24
+ ${o}`;if(a.importStrategy!=="component"){const u=n.flat().map(k=>`@import url('./css/${k}');`).join(`
25
+ `);$+=u}f.writeFileSync(i,$)}catch(s){console.error(s)}},$e=async(e,t)=>{try{const s=[],n=c.join(e,"./saltygen"),r=c.join(n,"index.css");if(J(t)){const y=await B(e),a=await H(e,t,n);Object.entries(a).forEach(([F,$])=>{if(!$.generator)return;const u=$.generator._withBuildContext({name:F,config:y}),k=`css/${u.cssFileName}`,C=c.join(n,k);s.push(u.cssFileName),f.writeFileSync(C,u.css)});const j=f.readFileSync(r,"utf8").split(`
26
+ `),o=s.map(F=>`@import url('../saltygen/css/${F}');`),w=[...new Set([...j,...o])].join(`
27
+ `);f.writeFileSync(r,w)}}catch(s){console.error(s)}},we=async(e,t,s=oe())=>{try{const n=c.join(e,"./saltygen");if(J(t)){const i=f.readFileSync(t,"utf8");i.replace(/^(?!export\s)const\s.*/gm,l=>`export ${l}`)!==i&&await U.writeFile(t,i);const a=await B(e),j=await H(e,t,n);let o=i;if(Object.entries(j).forEach(([l,w])=>{var S;if(w.isKeyframes||!w.generator)return;const F=w.generator._withBuildContext({name:l,config:a,prod:s}),$=new RegExp(`\\s${l}[=\\s]+[^()]+styled\\(([^,]+),`,"g").exec(i);if(!$)return console.error("Could not find the original declaration");const u=(S=$.at(1))==null?void 0:S.trim(),k=new RegExp(`\\s${l}[=\\s]+styled\\(`,"g").exec(o);if(!k)return console.error("Could not find the original declaration");const{index:C}=k;let h=!1;const x=setTimeout(()=>h=!0,5e3);let b=0,p=!1,T=0;for(;!p&&!h;){const d=o[C+b];d==="("&&T++,d===")"&&T--,T===0&&d===")"&&(p=!0),b>o.length&&(h=!0),b++}if(!h)clearTimeout(x);else throw new Error("Failed to find the end of the styled call and timed out");const O=C+b,_=o.slice(C,O),g=o,m=` ${l} = styled(${u}, "${F.classNames}", ${JSON.stringify(F.props)});`;o=o.replace(_,m),g===o&&console.error("Minimize file failed to change content",{name:l,tagName:u})}),a.importStrategy==="component"){const l=I(t,6),w=c.parse(t);o=`import '../../saltygen/css/${`f_${D(w.name)}-${l}.css`}';
28
+ ${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)}},re=e=>({name:"stylegen",buildStart:()=>Se(e),load:async t=>{if(J(t))return await we(e,t)},watchChange:{handler:async t=>{J(t)&&await $e(e,t),t.includes("salty.config")&&await ne(e)}}});exports.default=re;exports.saltyPlugin=re;
package/index.d.ts CHANGED
@@ -6,3 +6,4 @@ export declare const saltyPlugin: (dir: string) => {
6
6
  handler: (filePath: string) => Promise<void>;
7
7
  };
8
8
  };
9
+ export default saltyPlugin;
package/index.js CHANGED
@@ -1,279 +1,400 @@
1
- import * as I from "esbuild";
2
- import * as P from "winston";
3
- import { execSync as L } from "child_process";
4
- import { join as u } from "path";
5
- import { writeFileSync as x, existsSync as q, mkdirSync as A, statSync as G, readdirSync as U, readFileSync as B } from "fs";
6
- import { writeFile as X } from "fs/promises";
7
- const Z = (t) => String.fromCharCode(t + (t > 25 ? 39 : 97)), Y = (t, s) => {
8
- let e = "", n;
9
- for (n = Math.abs(t); n > 52; n = n / 52 | 0) e = Z(n % 52) + e;
10
- return e = Z(n % 52) + e, e.length < s ? e = e.padStart(s, "a") : e.length > s && (e = e.slice(-s)), e;
11
- }, Q = (t, s) => {
12
- let e = s.length;
13
- for (; e; ) t = t * 33 ^ s.charCodeAt(--e);
1
+ import * as Y from "esbuild";
2
+ import { execSync as at } from "child_process";
3
+ import { join as f, parse as I } from "path";
4
+ import { existsSync as K, writeFileSync as N, mkdirSync as z, statSync as lt, readdirSync as ft, readFileSync as W } from "fs";
5
+ import { readFile as pt, writeFile as ut } from "fs/promises";
6
+ import { createLogger as dt, format as H, transports as gt } from "winston";
7
+ const U = (t) => String.fromCharCode(t + (t > 25 ? 39 : 97)), yt = (t, e) => {
8
+ let s = "", n;
9
+ for (n = Math.abs(t); n > 52; n = n / 52 | 0) s = U(n % 52) + s;
10
+ return s = U(n % 52) + s, s.length < e ? s = s.padStart(e, "a") : s.length > e && (s = s.slice(-e)), s;
11
+ }, mt = (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 = mt(5381, JSON.stringify(t)) >>> 0;
17
+ return yt(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 O(t) {
20
+ return t ? typeof t != "string" ? O(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 ht = (t, e) => {
23
23
  if (typeof t != "string") return { result: t };
24
- if (!s) return { result: t };
25
- const e = [];
26
- return Object.values(s).forEach((n) => {
27
- const { pattern: r, transform: g } = n;
28
- t = t.replace(r, ($) => {
29
- const { value: a, css: f } = g($);
30
- return f && e.push(f), a;
24
+ if (!e) return { result: t };
25
+ const s = [];
26
+ return Object.values(e).forEach((n) => {
27
+ const { pattern: r, transform: i } = n;
28
+ t = t.replace(r, (d) => {
29
+ const { value: c, css: b } = i(d);
30
+ return b && s.push(b), c;
31
31
  });
32
- }), { result: t, additionalCss: e };
33
- }, H = (t) => typeof t != "string" ? { result: t } : /\{[^{}]+\}/g.test(t) ? { result: t.replace(/\{([^{}]+)\}/g, (...n) => `var(--${k(n[1].replaceAll(".", "-"))})`) } : { result: t }, O = (t, s, e, n) => {
34
- const r = [], g = Object.entries(t).reduce((a, [f, o]) => {
35
- const i = f.trim();
32
+ }), { result: t, additionalCss: s };
33
+ }, Q = (t) => typeof t != "string" ? { result: t } : /\{[^{}]+\}/g.test(t) ? { result: t.replace(/\{([^{}]+)\}/g, (...n) => `var(--${O(n[1].replaceAll(".", "-"))})`) } : { result: t }, D = (t, e, s, n) => {
34
+ if (!t) return "";
35
+ const r = [], i = Object.entries(t).reduce((c, [b, o]) => {
36
+ const a = b.trim();
36
37
  if (typeof o == "function" && (o = o()), typeof o == "object") {
37
- if (!o) return a;
38
- if (i === "variants")
39
- return Object.entries(o).forEach(([y, c]) => {
40
- c && Object.entries(c).forEach(([m, l]) => {
41
- if (!l) return;
42
- const F = `${s}.${y}-${m}`, N = O(l, F);
43
- r.push(N);
38
+ if (!o) return c;
39
+ if (a === "variants")
40
+ return Object.entries(o).forEach(([h, p]) => {
41
+ p && Object.entries(p).forEach(([C, P]) => {
42
+ if (!P) return;
43
+ const E = `${e}.${h}-${C}`, g = D(P, E);
44
+ r.push(g);
44
45
  });
45
- }), a;
46
- if (i === "defaultVariants")
47
- return a;
48
- if (i === "compoundVariants")
49
- return o.forEach((y) => {
50
- const { css: c, ...m } = y, l = Object.entries(m).reduce((N, [D, V]) => `${N}.${D}-${V}`, s), F = O(c, l);
51
- r.push(F);
52
- }), a;
53
- if (i.startsWith("@")) {
54
- const y = O(o, s), c = `${i} {
55
- ${y.replace(`
46
+ }), c;
47
+ if (a === "defaultVariants")
48
+ return c;
49
+ if (a === "compoundVariants")
50
+ return o.forEach((h) => {
51
+ const { css: p, ...C } = h, P = Object.entries(C).reduce((g, [y, $]) => `${g}.${y}-${$}`, e), E = D(p, P);
52
+ r.push(E);
53
+ }), c;
54
+ if (a.startsWith("@")) {
55
+ const h = D(o, e), p = `${a} {
56
+ ${h.replace(`
56
57
  `, `
57
58
  `)}
58
59
  }`;
59
- return r.push(c), a;
60
+ return r.push(p), c;
60
61
  }
61
- const d = f.includes("&") ? i.replace("&", s) : i.startsWith(":") ? `${s}${i}` : `${s} ${i}`, S = O(o, d);
62
- return r.push(S), a;
62
+ const m = b.includes("&") ? a.replace("&", e) : a.startsWith(":") ? `${e}${a}` : `${e} ${a}`, F = D(o, m);
63
+ return r.push(F), c;
63
64
  }
64
- const p = i.startsWith("-") ? i : k(i), h = (d, S = ";") => a = `${a}${d}${S}`, b = (d) => h(`${p}:${d}`);
65
- if (typeof o == "number") return b(o);
65
+ const j = a.startsWith("-") ? a : O(a), w = (m, F = ";") => c = `${c}${m}${F}`, S = (m) => w(`${j}:${m}`);
66
+ if (typeof o == "number") return S(o);
66
67
  if (typeof o != "string")
67
68
  if ("toString" in o) o = o.toString();
68
- else return a;
69
- const { modifiers: j } = {}, C = function* () {
70
- yield H(o), yield v(o, j);
69
+ else return c;
70
+ const { modifiers: l } = {}, k = function* () {
71
+ yield Q(o), yield ht(o, l);
71
72
  }();
72
- for (const { result: d, additionalCss: S = [] } of C)
73
- o = d, S.forEach((y) => {
74
- const c = O(y, "");
75
- h(c, "");
73
+ for (const { result: m, additionalCss: F = [] } of k)
74
+ o = m, F.forEach((h) => {
75
+ const p = D(h, "");
76
+ w(p, "");
76
77
  });
77
- return b(o);
78
+ return S(o);
78
79
  }, "");
79
- if (!g) return r.join(`
80
+ if (!i) return r.join(`
80
81
  `);
81
- if (!s) return g;
82
- let $ = "";
83
- return $ = `${s} { ${g} }`, [$, ...r].join(`
82
+ if (!e) return i;
83
+ let d = "";
84
+ return d = `${e} { ${i} }`, [d, ...r].join(`
84
85
  `);
85
- }, J = (t, s = []) => {
86
- const e = [], n = {};
87
- if (Object.entries(t).forEach(([r, g]) => {
88
- if (typeof g == "object") {
89
- if (!g) return;
90
- const $ = r.trim(), a = J(g, [...s, $]);
91
- e.push(a);
86
+ }, v = (t, e = []) => {
87
+ if (!t) return "";
88
+ const s = [], n = {};
89
+ if (Object.entries(t).forEach(([r, i]) => {
90
+ if (typeof i == "object") {
91
+ if (!i) return;
92
+ const d = r.trim(), c = v(i, [...e, d]);
93
+ s.push(c);
92
94
  } else
93
- n[r] = g;
95
+ n[r] = i;
94
96
  }), Object.keys(n).length) {
95
- const r = s.map(k).join("-"), g = O(n, `.${r}`);
96
- e.push(g);
97
+ const r = e.map(O).join("-"), i = D(n, `.${r}`);
98
+ s.push(i);
97
99
  }
98
- return e.join(`
100
+ return s.join(`
99
101
  `);
102
+ }, bt = (t) => Object.entries(t).reduce((e, [s, n]) => (typeof n == "object" && (e[s] = tt(n).map((r) => `"${r}"`).join(" | ")), e), {}), tt = (t, e = "", s = /* @__PURE__ */ new Set()) => t ? (Object.entries(t).forEach(([n, r]) => {
103
+ const i = e ? `${e}.${n}` : n;
104
+ return typeof r == "object" ? tt(r, i, s) : s.add(e);
105
+ }), [...s]) : [], et = (t) => {
106
+ if (!t || t === "/") throw new Error("Could not find package.json file");
107
+ const e = f(t, "package.json");
108
+ return K(e) ? e : et(f(t, ".."));
109
+ }, $t = async (t) => {
110
+ const e = et(t);
111
+ return await pt(e, "utf-8").then(JSON.parse).catch(() => {
112
+ });
113
+ }, St = async (t) => {
114
+ const e = await $t(t);
115
+ if (e)
116
+ return e.type;
100
117
  };
101
- P.createLogger({
102
- level: "info",
103
- format: P.format.combine(P.format.colorize(), P.format.cli()),
104
- transports: [new P.transports.Console({})]
118
+ let M;
119
+ const st = async (t) => {
120
+ if (M) return M;
121
+ const e = await St(t);
122
+ return e === "module" ? M = "esm" : (e === "commonjs" || import.meta.url.endsWith(".cjs")) && (M = "cjs"), M || "esm";
123
+ }, X = dt({
124
+ level: "debug",
125
+ format: H.combine(H.colorize(), H.cli()),
126
+ transports: [new gt.Console({})]
105
127
  });
106
- const T = (t) => u(t, "./saltygen"), tt = ["salty", "css", "styles", "styled"], st = (t = []) => new RegExp(`\\.(${[...tt, ...t].join("|")})\\.`), E = (t, s = []) => st(s).test(t), et = async (t) => {
107
- const s = T(t), e = u(t, "salty-config.ts"), n = u(s, "salty-config.js");
108
- await I.build({
109
- entryPoints: [e],
128
+ function nt(t) {
129
+ return t ? typeof t != "string" ? nt(String(t)) : t.replace(/[\s-]/g, ".").replace(/[A-Z](?:(?=[^A-Z])|[A-Z]*(?=[A-Z][^A-Z]|$))/g, (e, s) => (s > 0 ? "." : "") + e.toLowerCase()) : "";
130
+ }
131
+ const jt = {
132
+ /** Set box model to border-box */
133
+ "*, *::before, *::after": {
134
+ boxSizing: "border-box"
135
+ },
136
+ /** Remove default margin and padding */
137
+ "*": {
138
+ margin: 0
139
+ },
140
+ /** Remove adjust font properties */
141
+ html: {
142
+ lineHeight: 1.15,
143
+ textSizeAdjust: "100%",
144
+ WebkitFontSmoothing: "antialiased"
145
+ },
146
+ /** Make media elements responsive */
147
+ "img, picture, video, canvas, svg": {
148
+ display: "block",
149
+ maxWidth: "100%"
150
+ },
151
+ /** Avoid overflow of text */
152
+ "p, h1, h2, h3, h4, h5, h6": {
153
+ overflowWrap: "break-word"
154
+ },
155
+ /** Improve text wrapping */
156
+ p: {
157
+ textWrap: "pretty"
158
+ },
159
+ "h1, h2, h3, h4, h5, h6": {
160
+ textWrap: "balance"
161
+ },
162
+ /** Improve button line height */
163
+ button: {
164
+ lineHeight: "1em"
165
+ },
166
+ /** Improve form elements */
167
+ "input, optgroup, select, textarea": {
168
+ fontFamily: "inherit",
169
+ fontSize: "100%",
170
+ lineHeight: "1.15em"
171
+ }
172
+ }, B = {
173
+ externalModules: []
174
+ }, ot = (t) => {
175
+ if (B.externalModules.length > 0) return B.externalModules;
176
+ const e = f(t, "salty.config.ts"), n = W(e, "utf8").match(/externalModules:\s?\[(.*)\]/);
177
+ if (!n) return [];
178
+ const r = n[1].split(",").map((i) => i.replace(/['"`]/g, "").trim());
179
+ return B.externalModules = r, r;
180
+ }, R = (t) => f(t, "./saltygen"), wt = ["salty", "css", "styles", "styled"], Ft = (t = []) => new RegExp(`\\.(${[...wt, ...t].join("|")})\\.`), J = (t, e = []) => Ft(e).test(t), xt = async (t) => {
181
+ const e = R(t), s = f(t, "salty.config.ts"), n = f(e, "salty.config.js"), r = await st(t), i = ot(t);
182
+ await Y.build({
183
+ entryPoints: [s],
110
184
  minify: !0,
111
185
  treeShaking: !0,
112
186
  bundle: !0,
113
187
  outfile: n,
114
- format: "esm",
115
- external: ["react"]
188
+ format: r,
189
+ external: i
116
190
  });
117
- const r = Date.now(), { config: g } = await import(`${n}?t=${r}`);
118
- return g;
119
- }, K = async (t) => {
120
- const s = await et(t), e = /* @__PURE__ */ new Set(), n = (y, c = []) => y ? Object.entries(y).flatMap(([m, l]) => {
121
- if (!l) return;
122
- if (typeof l == "object") return n(l, [...c, m]);
123
- const F = [...c, m].join(".");
124
- e.add(`"${F}"`);
125
- const N = [...c.map(k), k(m)].join("-"), { result: D } = H(l);
126
- return `--${N}: ${D};`;
127
- }) : [], r = (y) => y ? Object.entries(y).flatMap(([c, m]) => {
128
- const l = n(m);
129
- return c === "base" ? l.join("") : `${c} { ${l.join("")} }`;
130
- }) : [], g = (y) => y ? Object.entries(y).flatMap(([c, m]) => Object.entries(m).flatMap(([l, F]) => {
131
- const N = n(F, [c]), D = `.${c}-${l}, [data-${c}="${l}"]`, V = N.join("");
132
- return `${D} { ${V} }`;
133
- })) : [], $ = n(s.variables), a = r(s.responsiveVariables), f = g(s.conditionalVariables), o = T(t), i = u(o, "css/variables.css"), p = `:root { ${$.join("")} ${a.join("")} } ${f.join("")}`;
134
- x(i, p);
135
- const h = u(o, "types/css-tokens.d.ts"), j = `type VariableTokens = ${[...e].join("|")}; type PropertyValueToken = \`{\${VariableTokens}}\``;
136
- x(h, j);
137
- const w = u(o, "css/global.css"), C = O(s.global, "");
138
- x(w, C);
139
- const d = u(o, "css/templates.css"), S = J(s.templates);
140
- x(d, S);
141
- }, M = async (t, s) => {
142
- const e = R(t), n = u(s, "js", e + ".js");
143
- await I.build({
144
- entryPoints: [t],
145
- minify: !0,
191
+ const d = Date.now(), { config: c } = await import(`${n}?t=${d}`);
192
+ return c;
193
+ }, rt = async (t) => {
194
+ const e = await xt(t), s = /* @__PURE__ */ new Set(), n = (g, y = []) => g ? Object.entries(g).flatMap(([$, u]) => {
195
+ if (!u) return;
196
+ if (typeof u == "object") return n(u, [...y, $]);
197
+ const T = nt($), _ = O($), A = [...y, T].join(".");
198
+ s.add(`"${A}"`);
199
+ const V = [...y.map(O), _].join("-"), { result: Z } = Q(u);
200
+ return `--${V}: ${Z};`;
201
+ }) : [], r = (g) => g ? Object.entries(g).flatMap(([y, $]) => {
202
+ const u = n($);
203
+ return y === "base" ? u.join("") : `${y} { ${u.join("")} }`;
204
+ }) : [], i = (g) => g ? Object.entries(g).flatMap(([y, $]) => Object.entries($).flatMap(([u, T]) => {
205
+ const _ = n(T, [y]), A = `.${y}-${u}, [data-${y}="${u}"]`, V = _.join("");
206
+ return `${A} { ${V} }`;
207
+ })) : [], d = n(e.variables), c = r(e.responsiveVariables), b = i(e.conditionalVariables), o = R(t), a = f(o, "css/_variables.css"), j = `:root { ${d.join("")} ${c.join("")} } ${b.join("")}`;
208
+ N(a, j);
209
+ const w = f(o, "css/_global.css"), S = D(e.global, "");
210
+ N(w, `@layer global { ${S} }`);
211
+ const l = f(o, "css/_reset.css"), k = e.reset === "none" ? {} : typeof e.reset == "object" ? e.reset : jt, m = D(k, "");
212
+ N(l, `@layer reset { ${m} }`);
213
+ const F = f(o, "css/_templates.css"), h = v(e.templates), p = bt(e.templates);
214
+ N(F, h);
215
+ const C = f(o, "types/css-tokens.d.ts"), E = `
216
+ // Variable types
217
+ type VariableTokens = ${[...s].join("|")};
218
+ type PropertyValueToken = \`{\${VariableTokens}}\`;
219
+
220
+ // Template types
221
+ type TemplateTokens = {
222
+ ${Object.entries(p).map(([g, y]) => `${g}?: ${y}`).join(`
223
+ `)}
224
+ }
225
+ `;
226
+ N(C, E);
227
+ }, L = async (t, e, s) => {
228
+ const n = G(e), r = f(s, "./temp");
229
+ K(r) || z(r);
230
+ const i = I(e);
231
+ let d = W(e, "utf8");
232
+ d = d.replace(/styled\([^"'`{,]+,/g, "styled('div',");
233
+ const c = f(s, "js", n + ".js"), b = ot(t), o = await st(t);
234
+ await Y.build({
235
+ stdin: {
236
+ contents: d,
237
+ sourcefile: i.base,
238
+ resolveDir: i.dir,
239
+ loader: "tsx"
240
+ },
241
+ minify: !1,
146
242
  treeShaking: !0,
147
243
  bundle: !0,
148
- outfile: n,
149
- format: "esm",
150
- target: ["es2022"],
244
+ outfile: c,
245
+ format: o,
246
+ target: ["node20"],
151
247
  keepNames: !0,
152
- external: ["react"]
248
+ external: b,
249
+ packages: "external"
153
250
  });
154
- const r = Date.now();
155
- return await import(`${n}?t=${r}`);
156
- }, _ = async (t) => {
157
- const s = T(t), e = u(s, "salty-config.js"), { config: n } = await import(e);
251
+ const a = Date.now();
252
+ return await import(`${c}?t=${a}`);
253
+ }, q = async (t) => {
254
+ const e = R(t), s = f(e, "salty.config.js"), { config: n } = await import(s);
158
255
  return n;
159
- }, nt = async (t) => {
256
+ }, it = () => {
257
+ try {
258
+ return process.env.NODE_ENV === "production";
259
+ } catch {
260
+ return !1;
261
+ }
262
+ }, kt = async (t, e = it()) => {
160
263
  try {
161
- const s = [], e = [], n = T(t), r = u(n, "index.css");
264
+ e ? X.info("Generating CSS in production mode! 🔥") : X.info("Generating CSS in development mode! 🚀");
265
+ const s = [], n = [], r = R(t), i = f(r, "index.css");
162
266
  (() => {
163
- q(n) && L("rm -rf " + n), A(n), A(u(n, "css")), A(u(n, "types"));
164
- })(), await K(t);
165
- const $ = await _(t);
166
- async function a(p, h) {
167
- const b = G(p);
168
- if (b.isDirectory()) {
169
- const j = U(p);
170
- await Promise.all(j.map((w) => a(u(p, w), u(h, w))));
171
- } else if (b.isFile() && E(p)) {
172
- const w = await M(p, n), C = [];
173
- Object.entries(w).forEach(([c, m]) => {
174
- if (m.isKeyframes && m.css) {
175
- const V = `${m.animationName}.css`, W = `css/${V}`, z = u(n, W);
176
- s.push(V), x(z, m.css);
267
+ K(r) && at("rm -rf " + r), z(r), z(f(r, "css")), z(f(r, "types"));
268
+ })(), await rt(t);
269
+ const c = await q(t);
270
+ async function b(l, x) {
271
+ const k = ["node_modules", "saltygen"], m = lt(l);
272
+ if (m.isDirectory()) {
273
+ const F = ft(l);
274
+ if (k.some((p) => l.includes(p))) return;
275
+ await Promise.all(F.map((p) => b(f(l, p), f(x, p))));
276
+ } else if (m.isFile() && J(l)) {
277
+ const h = await L(t, l, r), p = [];
278
+ Object.entries(h).forEach(([$, u]) => {
279
+ if (u.isKeyframes && u.css) {
280
+ const V = `a_${u.animationName}.css`, Z = `css/${V}`, ct = f(r, Z);
281
+ s.push(V), N(ct, u.css);
177
282
  return;
178
283
  }
179
- if (!m.generator) return;
180
- const l = m.generator._withBuildContext({
181
- name: c,
182
- config: $
183
- }), F = `${l.hash}-${l.priority}.css`;
184
- e[l.priority] || (e[l.priority] = []), e[l.priority].push(F), C.push(F);
185
- const N = `css/${F}`, D = u(n, N);
186
- x(D, l.css);
284
+ if (!u.generator) return;
285
+ const T = u.generator._withBuildContext({
286
+ name: $,
287
+ config: c,
288
+ prod: e
289
+ });
290
+ n[T.priority] || (n[T.priority] = []), n[T.priority].push(T.cssFileName), p.push(T.cssFileName);
291
+ const _ = `css/${T.cssFileName}`, A = f(r, _);
292
+ N(A, T.css);
187
293
  });
188
- const d = C.map((c) => `@import url('./${c}');`).join(`
189
- `), S = R(p, 6), y = u(n, `css/${S}.css`);
190
- x(y, d);
294
+ const C = p.map(($) => `@import url('./${$}');`).join(`
295
+ `), P = G(l, 6), E = I(l), g = O(E.name), y = f(r, `css/f_${g}-${P}.css`);
296
+ N(y, C);
191
297
  }
192
298
  }
193
- await a(t, n);
194
- const f = s.map((p) => `@import url('./css/${p}');`).join(`
299
+ await b(t, r);
300
+ const o = s.map((l) => `@import url('./css/${l}');`).join(`
195
301
  `);
196
- let i = `@layer l0, l1, l2, l3, l4, l5, l6, l7, l8;
302
+ let S = `@layer reset, global, l0, l1, l2, l3, l4, l5, l6, l7, l8;
197
303
 
198
- ${["@import url('./css/variables.css');", "@import url('./css/global.css');", "@import url('./css/templates.css');"].join(`
304
+ ${["_variables.css", "_reset.css", "_global.css", "_templates.css"].filter((l) => {
305
+ try {
306
+ return W(f(r, "css", l), "utf8").length > 0;
307
+ } catch {
308
+ return !1;
309
+ }
310
+ }).map((l) => `@import url('./css/${l}');`).join(`
199
311
  `)}
200
- ${f}`;
201
- if ($.importStrategy !== "component") {
202
- const p = e.flat().map((h) => `@import url('./css/${h}');`).join(`
312
+ ${o}`;
313
+ if (c.importStrategy !== "component") {
314
+ const l = n.flat().map((x) => `@import url('./css/${x}');`).join(`
203
315
  `);
204
- i += p;
316
+ S += l;
205
317
  }
206
- x(r, i);
318
+ N(i, S);
207
319
  } catch (s) {
208
320
  console.error(s);
209
321
  }
210
- }, rt = async (t, s) => {
322
+ }, Ct = async (t, e) => {
211
323
  try {
212
- const e = [], n = u(t, "./saltygen"), r = u(n, "index.css");
213
- if (E(s)) {
214
- const $ = await _(t), a = await M(s, n);
215
- Object.entries(a).forEach(([h, b]) => {
216
- if (!b.generator) return;
217
- const j = b.generator._withBuildContext({
218
- name: h,
219
- config: $
220
- }), w = `${j.hash}-${j.priority}.css`, C = `css/${w}`, d = u(n, C);
221
- e.push(w), x(d, j.css);
324
+ const s = [], n = f(t, "./saltygen"), r = f(n, "index.css");
325
+ if (J(e)) {
326
+ const d = await q(t), c = await L(t, e, n);
327
+ Object.entries(c).forEach(([w, S]) => {
328
+ if (!S.generator) return;
329
+ const l = S.generator._withBuildContext({
330
+ name: w,
331
+ config: d
332
+ }), x = `css/${l.cssFileName}`, k = f(n, x);
333
+ s.push(l.cssFileName), N(k, l.css);
222
334
  });
223
- const f = B(r, "utf8").split(`
224
- `), o = e.map((h) => `@import url('../saltygen/css/${h}');`), p = [.../* @__PURE__ */ new Set([...f, ...o])].join(`
335
+ const b = W(r, "utf8").split(`
336
+ `), o = s.map((w) => `@import url('../saltygen/css/${w}');`), j = [.../* @__PURE__ */ new Set([...b, ...o])].join(`
225
337
  `);
226
- x(r, p);
338
+ N(r, j);
227
339
  }
228
- } catch (e) {
229
- console.error(e);
340
+ } catch (s) {
341
+ console.error(s);
230
342
  }
231
- }, ot = async (t, s) => {
343
+ }, Tt = async (t, e, s = it()) => {
232
344
  try {
233
- const e = u(t, "./saltygen");
234
- if (E(s)) {
235
- let r = B(s, "utf8");
236
- r.replace(/^(?!export\s)const\s.*/gm, (i) => `export ${i}`) !== r && await X(s, r);
237
- const $ = await _(t), a = await M(s, e);
238
- let f = r;
239
- Object.entries(a).forEach(([i, p]) => {
240
- var y;
241
- if (p.isKeyframes) {
242
- console.log("value", p);
243
- return;
345
+ const n = f(t, "./saltygen");
346
+ if (J(e)) {
347
+ const i = W(e, "utf8");
348
+ i.replace(/^(?!export\s)const\s.*/gm, (a) => `export ${a}`) !== i && await ut(e, i);
349
+ const c = await q(t), b = await L(t, e, n);
350
+ let o = i;
351
+ if (Object.entries(b).forEach(([a, j]) => {
352
+ var $;
353
+ if (j.isKeyframes || !j.generator) return;
354
+ const w = j.generator._withBuildContext({
355
+ name: a,
356
+ config: c,
357
+ prod: s
358
+ }), S = new RegExp(`\\s${a}[=\\s]+[^()]+styled\\(([^,]+),`, "g").exec(i);
359
+ if (!S) return console.error("Could not find the original declaration");
360
+ const l = ($ = S.at(1)) == null ? void 0 : $.trim(), x = new RegExp(`\\s${a}[=\\s]+styled\\(`, "g").exec(o);
361
+ if (!x) return console.error("Could not find the original declaration");
362
+ const { index: k } = x;
363
+ let m = !1;
364
+ const F = setTimeout(() => m = !0, 5e3);
365
+ let h = 0, p = !1, C = 0;
366
+ for (; !p && !m; ) {
367
+ const u = o[k + h];
368
+ u === "(" && C++, u === ")" && C--, C === 0 && u === ")" && (p = !0), h > o.length && (m = !0), h++;
244
369
  }
245
- if (!p.generator) return;
246
- const h = p.generator._withBuildContext({
247
- name: i,
248
- config: $
249
- }), b = new RegExp(`${i}[=\\s]+[^()]+styled\\(([^,]+),`, "g").exec(r);
250
- if (!b)
251
- return console.error("Could not find the original declaration");
252
- const j = (y = b.at(1)) == null ? void 0 : y.trim(), { element: w, variantKeys: C } = h.props, d = `${i} = styled(${j}, "${h.classNames}", "${h._callerName}", ${JSON.stringify(w)}, ${JSON.stringify(
253
- C
254
- )});`, S = new RegExp(`${i}[=\\s]+[^()]+styled\\(([^,]+),[^;]+;`, "g");
255
- f = f.replace(S, d);
256
- });
257
- const o = R(s, 6);
258
- return $.importStrategy === "component" && (f = `import '../../saltygen/css/${o}.css';
259
- ${f}`), f = f.replace("{ styled }", "{ styledClient as styled }"), f = f.replace("@salty-css/react/styled", "@salty-css/react/styled-client"), f;
370
+ if (!m) clearTimeout(F);
371
+ else throw new Error("Failed to find the end of the styled call and timed out");
372
+ const P = k + h, E = o.slice(k, P), g = o, y = ` ${a} = styled(${l}, "${w.classNames}", ${JSON.stringify(w.props)});`;
373
+ o = o.replace(E, y), g === o && console.error("Minimize file failed to change content", { name: a, tagName: l });
374
+ }), c.importStrategy === "component") {
375
+ const a = G(e, 6), j = I(e);
376
+ o = `import '../../saltygen/css/${`f_${O(j.name)}-${a}.css`}';
377
+ ${o}`;
378
+ }
379
+ return o = o.replace("{ styled }", "{ styledClient as styled }"), o = o.replace("@salty-css/react/styled", "@salty-css/react/styled-client"), o;
260
380
  }
261
- } catch (e) {
262
- console.error(e);
381
+ } catch (n) {
382
+ console.error("Error in minimizeFile:", n);
263
383
  }
264
- }, ft = (t) => ({
384
+ }, Vt = (t) => ({
265
385
  name: "stylegen",
266
- buildStart: () => nt(t),
267
- load: async (s) => {
268
- if (E(s))
269
- return await ot(t, s);
386
+ buildStart: () => kt(t),
387
+ load: async (e) => {
388
+ if (J(e))
389
+ return await Tt(t, e);
270
390
  },
271
391
  watchChange: {
272
- handler: async (s) => {
273
- E(s) && await rt(t, s), s.includes("salty-config") && await K(t);
392
+ handler: async (e) => {
393
+ J(e) && await Ct(t, e), e.includes("salty.config") && await rt(t);
274
394
  }
275
395
  }
276
396
  });
277
397
  export {
278
- ft as saltyPlugin
398
+ Vt as default,
399
+ Vt as saltyPlugin
279
400
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@salty-css/vite",
3
- "version": "0.0.1-alpha.12",
3
+ "version": "0.0.1-alpha.121",
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.121"
30
38
  }
31
39
  }