@sugarcube-org/cli 0.0.0-alpha.21 → 0.0.0-alpha.23
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.
- package/dist/index.mjs +66 -50
- package/package.json +5 -4
package/dist/index.mjs
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var Xe=Object.defineProperty;var o=(e,t)=>Xe(e,"name",{value:t,configurable:!0});import{Command as U}from"commander";import{relative as R,join as C,basename as Te,resolve as L,dirname as et,normalize as tt}from"pathe";import c from"picocolors";import{existsSync as F,readFileSync as Se}from"node:fs";import nt from"node-fetch";import{z as w}from"zod";import oe,{mkdir as V,writeFile as Q,readFile as Ie}from"node:fs/promises";import{execa as st}from"execa";import X from"fast-glob";import{loadAndResolveTokens as ot,configFileExists as D,loadInternalConfig as ee,loadUserConfig as rt,processAndConvertTokens as re,generateCSSVariables as Ee,writeCSSVariablesToDisk as ke,writeCSSUtilitiesToDisk as _e,convertConfigToUnoRules as it,DEFAULT_STYLES_PATH as at,DEFAULT_CONFIG as te,fillDefaults as ct}from"@sugarcube-org/core";import ie,{resolve as lt}from"node:path";import{select as ut,isCancel as ae,log as ft,multiselect as pt,confirm as dt,cancel as $e}from"@clack/prompts";import{getColumns as gt}from"@clack/core";import{wrapAnsi as mt}from"fast-wrap-ansi";import ht from"is-unicode-supported";import*as Re from"node:readline";import Ce from"node:readline";import{createLogUpdate as be}from"log-update";import{detect as wt}from"@antfu/ni";import{getTsconfig as yt}from"get-tsconfig";import{createGenerator as Tt}from"@unocss/core";var St="0.0.0-alpha.23",It={version:St};const ce="fluid",Et="**/*.json",le="@sugarcube-org/vite",kt=["node_modules",".git",".next","dist","build"],_t=5,N={INIT:"make-sugarcube init",COMPONENTS:"make-sugarcube components",GENERATE:"make-sugarcube generate",CUBE:"make-sugarcube cube"},ve={INITIALIZATION:"https://sugarcube.sh/docs/setup",CONFIGURATION:"https://sugarcube.sh/docs/configuration"},m={PROJECT_REQUIRED:`No sugarcube project detected. Please run ${c.cyan(N.INIT)} first.
|
|
3
3
|
|
|
4
|
-
For more information, visit: ${c.cyan(
|
|
4
|
+
For more information, visit: ${c.cyan(ve.INITIALIZATION)}`,CONFIG_EXISTS:o(()=>`A sugarcube config file already exists in this projct.
|
|
5
5
|
|
|
6
|
-
To start over, remove it and run ${c.cyan(
|
|
6
|
+
To start over, remove it and run ${c.cyan(N.INIT)} again.`,"CONFIG_EXISTS"),PLUGIN_INSTALL_FAILED:o(e=>{const t=e.packageManager==="npm"?"install":"add";return`Failed to install ${e.pluginToInstall} plugin.
|
|
7
7
|
|
|
8
8
|
This is usually a temporary issue. Try these steps:
|
|
9
9
|
|
|
10
10
|
1. Run the command again
|
|
11
11
|
2. Check your internet connection
|
|
12
|
-
3. Install manually: ${e.packageManager}
|
|
12
|
+
3. Install manually: ${e.packageManager} ${t} ${e.pluginToInstall}
|
|
13
13
|
|
|
14
14
|
If the problem continues, please open an issue at:
|
|
15
|
-
https://github.com/sugarcube-org/sugarcube/issues
|
|
15
|
+
https://github.com/sugarcube-org/sugarcube/issues`},"PLUGIN_INSTALL_FAILED"),INITIALIZATION_INCOMPLETE:o(()=>`The initialization process was not completed properly.
|
|
16
16
|
This is an internal error that should not occur.
|
|
17
17
|
Try running the \`init\` command again.
|
|
18
18
|
|
|
@@ -35,7 +35,24 @@ URL: ${c.cyan(e)}`,"REGISTRY_INVALID_DATA"),REGISTRY_ITEM_NOT_FOUND:o((e,t,n)=>`
|
|
|
35
35
|
Available ${e==="tokens"?"starter kit":e}s: ${n.join(", ")}`,"REGISTRY_ITEM_NOT_FOUND"),REGISTRY_FILE_INVALID:o(e=>`Invalid file content received
|
|
36
36
|
File: ${c.cyan(e)}`,"REGISTRY_FILE_INVALID"),STARTER_KIT_UNAVAILABLE:o(e=>`Starter kit '${c.cyan(e)}' is currently unavailable.
|
|
37
37
|
|
|
38
|
-
Please try a different starter kit or run the command again in a few minutes.`,"STARTER_KIT_UNAVAILABLE"),
|
|
38
|
+
Please try a different starter kit or run the command again in a few minutes.`,"STARTER_KIT_UNAVAILABLE"),RESOLVER_NOT_CONFIGURED:o(()=>`No resolver path configured.
|
|
39
|
+
|
|
40
|
+
Add a resolver path to your sugarcube config:
|
|
41
|
+
|
|
42
|
+
${c.cyan(`export default {
|
|
43
|
+
resolver: "./tokens.resolver.json",
|
|
44
|
+
// ...
|
|
45
|
+
}`)}
|
|
46
|
+
|
|
47
|
+
See ${c.cyan("https://sugarcube.sh/docs/resolver")} for more information.`,"RESOLVER_NOT_CONFIGURED"),RESOLVER_NOT_FOUND:o(e=>`No resolver document found in ${c.cyan(e)}.
|
|
48
|
+
|
|
49
|
+
A resolver document (*.resolver.json) is required to define how your tokens are loaded.
|
|
50
|
+
|
|
51
|
+
See ${c.cyan("https://sugarcube.sh/docs/resolver")} to learn how to create one.`,"RESOLVER_NOT_FOUND"),RESOLVER_MULTIPLE_FOUND:o(e=>`Multiple resolver documents found:
|
|
52
|
+
${e.map(t=>` - ${c.cyan(t)}`).join(`
|
|
53
|
+
`)}
|
|
54
|
+
|
|
55
|
+
A project should have only one resolver document. Please remove the extras or consolidate them.`,"RESOLVER_MULTIPLE_FOUND"),TOKEN_LOAD_FAILED:o(e=>`Failed to load token files:
|
|
39
56
|
|
|
40
57
|
${e.join(`
|
|
41
58
|
`)}
|
|
@@ -60,8 +77,8 @@ The 'generate' command is for manual generation without plugins. Since you have
|
|
|
60
77
|
|
|
61
78
|
npm run dev # or your framework's dev command
|
|
62
79
|
|
|
63
|
-
The plugin will automatically generate CSS with hot module replacement.`,"PLUGIN_DETECTED")};class
|
|
64
|
-
Available components: ${
|
|
80
|
+
The plugin will automatically generate CSS with hot module replacement.`,"PLUGIN_DETECTED")};class d extends Error{static{o(this,"CLIError")}constructor(t,n){super(t),this.name="CLIError",this.cause=n}}const ue=w.enum(["react","web-components","css-only"]),De=w.object({path:w.string(),type:w.string()}),$t=De.extend({framework:ue}),Rt=w.object({name:w.string(),type:w.string(),description:w.string().optional(),frameworks:w.array(w.string()).optional(),files:w.array(w.union([$t,De])),tokens:w.record(w.object({type:w.string(),mapping:w.string()})).optional(),dependencies:w.record(ue,w.array(w.string())).optional(),registryDependencies:w.record(ue,w.array(w.string())).optional(),tokenDependencies:w.array(w.string()).optional()}),Ct=w.array(Rt),bt=w.object({content:w.string()}),Ne=process.env.REGISTRY_URL??"https://sugarcube.sh/r";async function Ae(e){try{const t=await nt(e);if(!t.ok){if(t.status===401)throw new d(m.REGISTRY_AUTH_REQUIRED(e));if(t.status===403)throw new d(m.REGISTRY_AUTH_INVALID(e));if(t.status===404)throw new d(m.REGISTRY_NOT_FOUND(e));const n=await t.json().catch(()=>null),s=n&&typeof n=="object"&&"error"in n?String(n.error):t.statusText;throw new d(m.REGISTRY_REQUEST_FAILED(s,e))}return t.json()}catch(t){throw t instanceof d?t:new d(m.REGISTRY_NETWORK_ERROR(e))}}o(Ae,"fetchRegistry");async function j(){const e=`${Ne}/index.json`,t=await Ae(e);try{return Ct.parse(t)}catch{throw new d(m.REGISTRY_INVALID_DATA(e))}}o(j,"getRegistryIndex");async function fe({type:e,name:t,framework:n}){const s=await j(),r=s.find(u=>u.type===e&&u.name===t);if(!r){const u=s.filter(p=>p.type===e).map(p=>p.name);throw new d(m.REGISTRY_ITEM_NOT_FOUND(e,t,u))}let a=r.files;e==="component"&&n&&(a=r.files.filter(u=>"framework"in u&&u.framework===n));const i=await Promise.all(a.map(async u=>{const p=`${Ne}/${u.path}.json`,f=await Ae(p);try{const l=bt.parse(f);return{path:u.path,type:u.type,framework:"framework"in u?u.framework:void 0,content:l.content}}catch{throw new d(m.REGISTRY_FILE_INVALID(u.path))}}));return{item:r,files:i}}o(fe,"getRegistryFiles");async function vt(e){const t=await fe({type:"tokens",name:e});if(!t.files[0])throw new d(m.STARTER_KIT_UNAVAILABLE(e));return t}o(vt,"fetchStarterKit");async function pe(e,t,n){const s=[],r=new Set;async function a(i){if(r.has(i))return;r.add(i);const u=e.find(f=>f.name===i);if(!u){const f=e.filter(l=>l.type==="component").map(l=>l.name).join(", ");throw new d(`Component '${i}' not found in registry
|
|
81
|
+
Available components: ${f}`)}const p=u.registryDependencies?.[n]||[];for(const f of p)await a(f);s.push(u)}o(a,"resolveComponent");for(const i of t)await a(i);return s}o(pe,"resolveTree");async function Dt({selectedComponents:e,componentType:t,componentsOutputDirectory:n}){const s={variableCSS:[],utilityCSS:[],componentFiles:[],componentCSS:[],cubeCSS:[],indexFiles:[]},r=await j(),i=(await pe(r,e,t)).map(l=>l.name),u=r.filter(l=>l.type==="component").filter(l=>i.includes(l.name)),p=u.flatMap(l=>l.files.filter(g=>(g.type==="tsx"||g.type==="astro"||g.type==="njk")&&"framework"in g&&g.framework===t).map(g=>R(process.cwd(),C(n,l.name,`${l.name}.${g.type}`))));s.componentFiles=p.filter(l=>F(C(process.cwd(),l)));const f=u.map(l=>{const g=l.name;return R(process.cwd(),C(n,l.name,`${g}.css`))});return s.componentCSS=f.filter(l=>F(C(process.cwd(),l))),s}o(Dt,"collectComponentOverwriteWarnings");async function Nt({cubeDirectory:e}){const t={variableCSS:[],utilityCSS:[],componentFiles:[],componentCSS:[],cubeCSS:[],indexFiles:[]},s=(await j()).filter(r=>r.type==="cube").flatMap(r=>r.files).map(r=>{const a=r.path.replace(/^styles\//,"");return R(process.cwd(),C(e,a))});return t.cubeCSS=s.filter(r=>F(C(process.cwd(),r))),t}o(Nt,"collectCubeOverwriteWarnings");function Fe(e){const t=[];if(e.variableCSS.length>0&&t.push(`CSS variables files:
|
|
65
82
|
${e.variableCSS.map(s=>` - ${s}`).join(`
|
|
66
83
|
`)}`),e.utilityCSS.length>0&&t.push(`CSS utility files:
|
|
67
84
|
${e.utilityCSS.map(s=>` - ${s}`).join(`
|
|
@@ -75,74 +92,73 @@ ${e.indexFiles.map(s=>` - ${s}`).join(`
|
|
|
75
92
|
|
|
76
93
|
${t.join(`
|
|
77
94
|
|
|
78
|
-
`)}`}o(Fe,"formatOverwriteWarnings");async function
|
|
79
|
-
|
|
80
|
-
${c.gray(
|
|
81
|
-
`)},"intro"),
|
|
82
|
-
${c.gray(
|
|
83
|
-
|
|
84
|
-
`)},"outro");function
|
|
85
|
-
`)
|
|
86
|
-
`);
|
|
87
|
-
`);const
|
|
88
|
-
`)
|
|
89
|
-
`)}
|
|
90
|
-
|
|
91
|
-
${e}`;
|
|
92
|
-
${e}`;
|
|
93
|
-
|
|
94
|
-
`)
|
|
95
|
-
`))}else
|
|
96
|
-
`))
|
|
97
|
-
`))
|
|
98
|
-
`)
|
|
99
|
-
`);if(l.length>0){const[a,...f]=l;a&&a.length>0?i.push(`${t} ${a}`):i.push(t);for(const u of f)u.length>0?i.push(`${n} ${u}`):i.push(n)}s.write(`${i.join(`
|
|
95
|
+
`)}`}o(Fe,"formatOverwriteWarnings");async function de(e,t,n){if(e.length===0)return;const s=n==="npm"?"install":"add";try{await st(n,[s,...e],{cwd:t})}catch{throw new d(m.DEPENDENCY_INSTALL_FAILED(n))}}o(de,"installDependencies");async function At(e,t,n){const s=C(n,t.name);if(await V(s,{recursive:!0}),e.path.endsWith(".css")){const a=C(s,`${t.name}.css`);return await Q(a,e.content),a}const r=C(s,Te(e.path));return await Q(r,e.content),r}o(At,"writeComponentFile");async function Ft({registryIndex:e,selectedComponents:t,componentType:n,componentsOutputDirectory:s,packageManager:r}){const a=[],i=new Set;await V(s,{recursive:!0});const u=await pe(e,t,n);for(const p of u){const f=await fe({type:"component",name:p.name,framework:n});for(const g of f.files)if(g)try{const h=await At(g,p,s);h&&a.push(h)}catch(h){const k=h instanceof Error?`: ${h.message}`:"";throw new d(`Failed to write component file for "${p.name}"${k}`)}const l=p.dependencies?.[n]||[];for(const g of l)i.add(g)}if(i.size>0)try{await de(Array.from(i),process.cwd(),r)}catch(p){const f=p instanceof Error?`: ${p.message}`:"";throw new d(`Failed to install component dependencies${f}`)}return{createdFiles:a,npmDependencies:i}}o(Ft,"installComponents");function Ot(e,t){const n=L(e),s=L(t);return n.startsWith(`${s}/`)||n===s}o(Ot,"isWithinDirectory");async function Pt(e){const t=[],n=L(process.cwd(),e);await V(n,{recursive:!0});const r=(await j()).filter(a=>a.type==="cube").map(a=>a.name);for(const a of r){const i=await fe({type:"cube",name:a});for(const u of i.files){if(!u)continue;const p=u.path.replace(/^styles\//,""),f=L(n,p);if(!Ot(f,n))throw new d(`Invalid file path detected in CUBE module "${a}": path escapes target directory`);const l=et(f);try{await V(l,{recursive:!0}),await Q(f,u.content),t.push(f)}catch(g){const h=g instanceof Error?`: ${g.message}`:"";throw new d(`Failed to write CUBE module "${a}"${h}`)}}}return t}o(Pt,"installCUBE");async function Oe(e){const t=C(e,"*.resolver.json"),n=await X(t,{onlyFiles:!0});if(n.length===0)return{found:"none"};const[s]=n;return n.length===1&&s?{found:"one",path:R(process.cwd(),s)}:{found:"multiple",paths:n.map(r=>R(process.cwd(),r))}}o(Oe,"findResolverDocument");async function Lt(e,t){await oe.mkdir(t,{recursive:!0});const n=[];for(const s of e)await oe.writeFile(s.path,s.content),n.push(s.path);return n}o(Lt,"writeTokenFiles");async function W(e,t){let n;if(t)n={type:"memory",data:t,config:e};else{if(!e.resolver)throw new d(m.RESOLVER_NOT_CONFIGURED());n={type:"resolver",resolverPath:e.resolver,config:e}}const{trees:s,resolved:r,modifiers:a,errors:i}=await ot(n);if(i.load.length>0){const u=i.load.map(p=>{const f=p.file.split("/").pop()||"unknown file";let l=`File ${f}: `;return p.message.includes("Unexpected token")?l=m.TOKEN_FILE_INVALID_JSON(f):p.message.includes("Unexpected end")?l=m.TOKEN_FILE_INCOMPLETE_JSON(f):l=m.TOKEN_FILE_GENERIC_ERROR(f,p.message),l});throw new d(m.TOKEN_LOAD_FAILED(u))}if(i.validation.length>0||i.flatten.length>0||i.resolution.length>0){const u=[...i.flatten,...i.validation,...i.resolution],p=new Map;for(const f of u)if(f.source?.sourcePath){const l=p.get(f.source.sourcePath)||[];l.push(f.message),p.set(f.source.sourcePath,l)}throw new d(m.TOKEN_VALIDATION_FAILED(p))}return{trees:s,resolved:r,modifiers:a}}o(W,"loadAndResolveTokensForCLI");const Mt=o(async(e,t,n)=>{const s=await vt(e),r=L(process.cwd(),t),a=s.files.map(i=>({path:C(r,Te(i.path)),content:i.content}));return{config:n,tokenFiles:a,tokensDir:r,createdTokenPaths:a.map(i=>R(process.cwd(),i.path))}},"prepareStarterKitForInstall");async function Ut(e){const t=await Mt(e.starterKit??"",e.tokensDir,e.config),n=await Lt(t.tokenFiles,e.tokensDir),s=await Oe(e.tokensDir);if(s.found==="none")throw new d(m.RESOLVER_NOT_FOUND(e.tokensDir));if(s.found==="multiple")throw new d(m.RESOLVER_MULTIPLE_FOUND(s.paths));const r={...e.config,resolver:s.path},{trees:a,resolved:i}=await W(r);e.setupResult={config:r,createdTokenPaths:t.createdTokenPaths,trees:a,resolved:i,tokenFiles:t.tokenFiles,tokensDir:t.tokensDir},e.createdFiles.push(...n),e.config=r,e.userConfig={...e.userConfig,resolver:s.path}}o(Ut,"installFromStarterKit");async function Pe(e=!0){const t=[{label:"React",value:"react",hint:".tsx"},{label:"CSS Only",value:"css-only",hint:".css"},{label:c.dim("Web components"),value:"web-components",hint:"Coming soon!"}];e&&t.push({label:"Skip",value:"skip",hint:"continue without components"});const n=await ut({message:"Build with",options:t});return ae(n)&&process.exit(0),n==="web-components"?(ft.info(c.blue("Web components are coming soon! Please choose React or CSS Only for now.")),Pe(e)):n}o(Pe,"promptComponentFramework");async function jt(e,t){const n=e.filter(r=>r.type==="component"&&r.frameworks?.includes(t)),s=await pt({message:"Select components to add",options:n.map(r=>({label:r.name,value:r.name,hint:r.description})),required:!0});return ae(s)&&process.exit(0),s}o(jt,"promptComponentSelectionFiltered");async function Le(e,t=!1){const n=await dt({message:e,initialValue:t});return(!n||ae(n))&&($e(),process.exit(0)),!0}o(Le,"confirmOverwrite");const{hidden:ds}=c,Gt=ht(),E=o((e,t)=>Gt?e:t,"unicodeOr"),xt=E("\u25C7","o"),Me=E("\u250C","T"),O=E("\u2502","|"),ge=E("\u2514","\u2014"),Bt=E("\u2510","T"),Vt=E("\u2518","\u2014"),ne=E("\u2500","-"),Wt=E("\u256E","+"),Yt=E("\u256F","+"),Kt=E("\u2570","+"),Ht=E("\u256D","+"),zt=E("\u25CF","\u2022"),qt=E("\u25C6","*"),Jt=E("\u25B2","!"),Zt=E("\u25A0","x"),Y=o((e,t=c.bgGreen,n=c.black)=>t(` ${n(e)} `),"label"),K=o(e=>{const t=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))"].join("|"),n=new RegExp(t,"g");return typeof e=="string"?e.replace(n,""):e},"strip"),H=o((e="",t)=>{process.stdout.write(`
|
|
96
|
+
|
|
97
|
+
${c.gray(Me)}${c.gray(ne)} ${e}
|
|
98
|
+
`)},"intro"),se=o((e="",t)=>{process.stdout.write(`${c.gray(O)}
|
|
99
|
+
${c.gray(ge)}${c.gray(ne)} ${e}
|
|
100
|
+
|
|
101
|
+
`)},"outro");function G(e){return new Promise(t=>setTimeout(t,e))}o(G,"sleep");const Qt=[Ht,Wt,Kt,Yt],Xt=[Me,Bt,ge,Vt];function Ue(e,t,n,s){let r=n,a=n;return s==="center"?r=Math.floor((t-e)/2):s==="right"&&(r=t-e-n),a=t-r-e,[r,a]}o(Ue,"getPaddingForLine");const en=o(e=>e,"defaultFormatBorder"),me=o((e="",t="",n)=>{const s=n?.output??process.stdout,r=gt(s),i=1*2,u=n?.titlePadding??1,p=n?.contentPadding??2,f=n?.width===void 0||n.width==="auto"?1:Math.min(1,n.width),l=n?.includePrefix?`${O} `:"",g=n?.formatBorder??en,h=(n?.rounded?Qt:Xt).map(g),k=g(ne),_=g(O),T=r-l.length;let $=Math.floor(r*f)-l.length;if(n?.width==="auto"){const J=e.split(`
|
|
102
|
+
`);let B=K(t).length+u*2;for(const Qe of J){const ye=K(Qe).length+p*2;ye>B&&(B=ye)}const Z=B+i;Z<$&&($=Z)}$%2!==0&&($<T?$++:$--);const I=$-i,A=I-u*2,y=K(t).length>A?`${t.slice(0,A-3)}...`:t,[b,v]=Ue(K(y).length,I,u,n?.titleAlign),P=mt(e,I-p*2,{hard:!0,trim:!1});s.write(`${l}${h[0]}${k.repeat(b)}${y}${k.repeat(v)}${h[1]}
|
|
103
|
+
`);const q=P.split(`
|
|
104
|
+
`);for(const J of q){const[B,Z]=Ue(K(J).length,I,p,n?.contentAlign);s.write(`${l}${_}${" ".repeat(B)}${J}${" ".repeat(Z)}${_}
|
|
105
|
+
`)}s.write(`${l}${h[2]}${k.repeat(I)}${h[3]}
|
|
106
|
+
`)},"box");function he(e,t={}){const n=`
|
|
107
|
+
${e}`;me(n,c.black(c.bgRed(" ERROR ")),{width:"auto",titlePadding:2,formatBorder:c.red,...t})}o(he,"errorBoxWithBadge");function je(e,t={}){const n=`
|
|
108
|
+
${e}`;me(n,c.black(c.bgYellow(" WARNING ")),{width:"auto",titlePadding:2,formatBorder:c.yellow,...t})}o(je,"warningBoxWithBadge");function tn(e,t={}){const n=`
|
|
109
|
+
${e}`;me(n,c.black(c.bgCyan(" INFO ")),{width:"auto",titlePadding:2,formatBorder:c.cyan,...t})}o(tn,"infoBoxWithBadge");const nn=o((e,t)=>{if(!(e.meta&&e.name!=="escape")){if(e.ctrl){if(e.name==="a")return"first";if(e.name==="c"||e.name==="d")return"abort";if(e.name==="e")return"last";if(e.name==="g")return"reset"}return e.name==="return"||e.name==="enter"?"submit":e.name==="backspace"?"delete":e.name==="delete"?"deleteForward":e.name==="abort"?"abort":e.name==="escape"?"exit":e.name==="tab"?"next":e.name==="pagedown"?"nextPage":e.name==="pageup"?"prevPage":e.name==="home"?"home":e.name==="end"?"end":e.name==="up"?"up":e.name==="down"?"down":e.name==="right"?"right":e.name==="left"?"left":!1}},"action"),sn=o(async(e,t={})=>{const{sidebarSymbol:n=c.gray("\u2502"),clear:s=!1,stdin:r=process.stdin,stdout:a=process.stdout}=t,i=Ce.createInterface({input:r,escapeCodeTimeout:50}),u=be(a,{showCursor:!1});Ce.emitKeypressEvents(r,i);let p=0,f=!1;const l=o(async()=>{r.off("keypress",g),r.isTTY&&r.setRawMode(!1),i.close(),f=!0,p<e.length-1||s?u.clear():u.done()},"done"),g=o((h,k)=>{r.isTTY&&r.setRawMode(!0);const _=nn(k);if(_==="abort")return l(),process.exit(0);["up","down","left","right"].includes(_)||l()},"handleKeyPress");r.isTTY&&r.setRawMode(!0),r.on("keypress",g);for(const h of e){const k=Array.isArray(h)?h:h.split(" "),_=[];for(const I of[""].concat(k)){I&&_.push(I);const A=_.join(" ").replace(/sugarcube/g,c.cyan("sugarcube")),y=`${n} ${A}`;u(y),f||await new Promise(b=>setTimeout(b,Math.floor(Math.random()*126)+75))}f||await new Promise(I=>setTimeout(I,100));const $=(await Promise.all(k).then(I=>I.join(" "))).replace(/sugarcube/g,c.cyan("sugarcube"));u(`${n} ${$}`),f||await new Promise(I=>setTimeout(I,Math.floor(Math.random()*201)+1200)),p++}r.off("keypress",g),await new Promise(h=>setTimeout(h,100)),l(),r.isTTY&&r.setRawMode(!1),r.removeAllListeners("keypress")},"sayAnimatedInSidebar");function on(){return Math.floor(Math.random()*551)+200}o(on,"getRandomTaskDuration");async function rn(e,{sidebarSymbol:t="\u2502",spacing:n=1,stdin:s=process.stdin,stdout:r=process.stdout,initialDelayMs:a=200,minDurationMs:i,successPauseMs:u=300,successMessage:p,successAsOutro:f=!1}={}){const l=o((y,b)=>{let v="";switch(b){case"start":v=`${c.cyan(`\u25B6 ${y.start}`)}`;break;case"pending":v=`${c.dim(`\u25A1 ${y.pending}`)}`;break;case"success":v=`${c.green(`\u2714 ${y.end}`)}`;break;case"end":v=`${c.dim(`\u25A0 ${y.end}`)}`;break}return`${t} ${v}`},"formatWithSidebar"),g=Array.from({length:e.length},()=>"");e.forEach((y,b)=>{g[b]=l(y,"pending")});const h=be(r),k=Re.createInterface({input:s,escapeCodeTimeout:50});Re.emitKeypressEvents(s,k);const _=o(y=>{y===""&&(h.clear(),k.close(),s.isTTY&&s.setRawMode(!1),process.exit(0)),s.isTTY&&s.setRawMode(!0)},"keypress");s.isTTY&&s.setRawMode(!0),s.on("keypress",_);const T=Array.from({length:Math.max(n,0)},()=>`${t}`),$=o(()=>[...T,...g].join(`
|
|
110
|
+
`),"renderContent");h($()),await G(a);let I=0;for(const y of e){g[I]=l(y,"start"),h($());const b=Date.now(),v=y.while();try{await v;const P=Date.now()-b,q=typeof i=="number"?i:on();P<q&&await G(q-P),g[I]=l(y,"success"),h($()),await G(u)}catch(P){throw g[I]=`${t} ${c.red(`\u2717 ${y.end} (failed)`)}`,h($()),y.onError?.(P),s.removeListener("keypress",_),k.close(),s.isTTY&&s.setRawMode(!1),P}I++}const A=e.map(y=>l(y,"end"));if(p)if(f){const y=`${c.gray(ge)}${c.gray(ne)} ${c.green(p)}`;h([...T,...A,`${t}`,y].join(`
|
|
111
|
+
`))}else{const y=`${t} ${c.green(p)}`;h([...T,...A,`${t}`,y].join(`
|
|
112
|
+
`))}else h([...T,...A].join(`
|
|
113
|
+
`));await G(1e3),s.removeListener("keypress",_),s.isTTY&&s.setRawMode(!1),k.close(),h.done()}o(rn,"executeTasksInSidebar");const an=o(e=>process.stdout.write(`${e}
|
|
114
|
+
`),"rawLog"),S={message:o((e=[],{symbol:t=c.gray(O),secondarySymbol:n=c.gray(O),output:s=process.stdout,spacing:r=1}={})=>{const a=[];for(let u=0;u<r;u++)a.push(`${n}`);const i=Array.isArray(e)?e:e.split(`
|
|
115
|
+
`);if(i.length>0){const[u,...p]=i;u&&u.length>0?a.push(`${t} ${u}`):a.push(t);for(const f of p)f.length>0?a.push(`${n} ${f}`):a.push(n)}s.write(`${a.join(`
|
|
100
116
|
`)}
|
|
101
|
-
`)},"message"),info:o((e,t)=>{S.message(e,{...t,symbol:c.blue(
|
|
117
|
+
`)},"message"),info:o((e,t)=>{S.message(e,{...t,symbol:c.blue(zt)})},"info"),success:o((e,t)=>{S.message(e,{...t,symbol:c.green(qt)})},"success"),step:o((e,t)=>{S.message(e,{...t,symbol:c.green(xt)})},"step"),warn:o((e,t)=>{S.message(e,{...t,symbol:c.yellow(Jt)})},"warn"),error:o((e,t)=>{S.message(e,{...t,symbol:c.red(Zt)})},"error"),animated:o(async(e,{secondarySymbol:t=c.gray(O),output:n=process.stdout,clear:s=!1,...r}={})=>sn(e,{sidebarSymbol:t,stdout:n,clear:s,...r}),"animated"),tasks:o(async(e,{spacing:t=1,secondarySymbol:n=c.gray(O),output:s=process.stdout,...r}={})=>rn(e,{sidebarSymbol:n,spacing:t,stdout:s,...r}),"tasks"),space:o((e=1)=>{for(let t=0;t<e;t++)process.stdout.write(`${c.gray(O)}
|
|
102
118
|
`)},"space"),break:o((e=1)=>{for(let t=0;t<e;t++)process.stdout.write(`
|
|
103
|
-
`)},"break")};function
|
|
119
|
+
`)},"break")};function z(e){if(e instanceof d)S.space(1),he(e.message,{});else{const t=`An unexpected error occurred: ${e instanceof Error?e.message:String(e)}
|
|
104
120
|
|
|
105
|
-
If this issue persists, please report it: ${c.cyan("https://github.com/sugarcube-org/sugarcube/issues")}`;S.space(1),
|
|
121
|
+
If this issue persists, please report it: ${c.cyan("https://github.com/sugarcube-org/sugarcube/issues")}`;S.space(1),he(t,{})}process.exit(0)}o(z,"handleError");function Ge(e){return{absolute:L(process.cwd(),e)}}o(Ge,"resolveDirectoryFromFlag");async function xe(e){if(D())try{const{config:t}=await ee(),n=cn(t,e);return typeof n=="string"?L(process.cwd(),n):void 0}catch{return}}o(xe,"resolveDirectoryFromConfig");function cn(e,t){const n=t.split(".");let s=e;for(const r of n){if(s==null||typeof s!="object")return;s=s[r]}return s}o(cn,"getNestedValue");async function ln(e){if(e){const{absolute:t}=Ge(e);return{directory:t,fromConfig:!1}}if(D())try{const t=await xe("output.css");if(t)return{directory:t,fromConfig:!0}}catch{}throw new d(`A sugarcube config file was not found.
|
|
106
122
|
|
|
107
123
|
Either a config file or --styles-dir is required to run this command.
|
|
108
124
|
|
|
109
125
|
To use the cube command without a config file:
|
|
110
|
-
e.g. ${c.cyan(`${
|
|
126
|
+
e.g. ${c.cyan(`${N.CUBE} --styles-dir src/styles`)}
|
|
111
127
|
|
|
112
128
|
To create a config file:
|
|
113
|
-
${c.cyan(
|
|
129
|
+
${c.cyan(N.INIT)}
|
|
114
130
|
|
|
115
|
-
Stuck? ${c.cyan("https://sugarcube.sh")}`)}o(
|
|
131
|
+
Stuck? ${c.cyan("https://sugarcube.sh")}`)}o(ln,"getCssDir");async function un(e){if(e){const{absolute:t}=Ge(e);return{directory:t,fromConfig:!1}}if(D())try{const t=await xe("output.components");if(t)return{directory:t,fromConfig:!0}}catch{}throw new d(`A sugarcube config file was not found.
|
|
116
132
|
|
|
117
133
|
Either a config file or --components-dir is required to run this command.
|
|
118
134
|
|
|
119
135
|
To use the components command without a config file:
|
|
120
|
-
e.g. ${c.cyan(`${
|
|
136
|
+
e.g. ${c.cyan(`${N.COMPONENTS} --components-dir src/components/ui`)}
|
|
121
137
|
|
|
122
138
|
To create a config file:
|
|
123
|
-
${c.cyan(
|
|
139
|
+
${c.cyan(N.INIT)}
|
|
124
140
|
|
|
125
|
-
Stuck? ${c.cyan("https://sugarcube.sh")}`)}o(
|
|
126
|
-
${e.map(r=>`${n} ${
|
|
141
|
+
Stuck? ${c.cyan("https://sugarcube.sh")}`)}o(un,"getComponentsDir");function x(e,t=process.cwd()){try{const n=lt(t,"package.json");if(!F(n))return!1;const s=Se(n,"utf-8"),r=JSON.parse(s),a={...r.dependencies,...r.devDependencies,...r.peerDependencies};return e in a}catch{return!1}}o(x,"isPackageInstalled");async function Be(e,{withFallback:t=!1}={}){const n=await wt({programmatic:!0,cwd:e});if(n?.includes("yarn"))return"yarn";if(n?.includes("pnpm"))return"pnpm";if(n?.includes("bun"))return"bun";if(n?.includes("npm"))return"npm";if(t){const s=process.env.npm_config_user_agent||"";if(s.includes("yarn"))return"yarn";if(s.includes("pnpm"))return"pnpm";if(s.includes("bun"))return"bun"}return"npm"}o(Be,"getPackageManager");function fn(e=process.cwd()){return yt(e)!==null}o(fn,"isTypeScriptProject");async function Ve(e=process.cwd()){return fn(e)?"sugarcube.config.ts":"sugarcube.config.js"}o(Ve,"getConfigFileName");function pn(e){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e)}o(pn,"isValidIdentifier");function we(e,t=0){const n=" ".repeat(t);if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="string")return JSON.stringify(e);if(typeof e=="number"||typeof e=="boolean")return String(e);if(Array.isArray(e))return e.length===0?"[]":`[
|
|
142
|
+
${e.map(r=>`${n} ${we(r,t+1)}`).join(`,
|
|
127
143
|
`)}
|
|
128
144
|
${n}]`;if(typeof e=="object"){const s=Object.entries(e);return s.length===0?"{}":`{
|
|
129
|
-
${s.map(([i
|
|
145
|
+
${s.map(([a,i])=>{const u=pn(a)?a:JSON.stringify(a);return`${n} ${u}: ${we(i,t+1)}`}).join(`,
|
|
130
146
|
`)}
|
|
131
|
-
${n}}`}return JSON.stringify(e)}o(
|
|
147
|
+
${n}}`}return JSON.stringify(e)}o(we,"formatValue");function dn(e,t,n){const s=we(e,0);let r;return n?r=t?`import type { UserConfig } from "@sugarcube-org/vite";
|
|
132
148
|
|
|
133
149
|
const config: UserConfig = `:`/**
|
|
134
150
|
* @type {import('@sugarcube-org/vite').UserConfig}
|
|
135
151
|
*/
|
|
136
|
-
const config = `:r=`// Configuration reference: ${
|
|
152
|
+
const config = `:r=`// Configuration reference: ${ve.CONFIGURATION}
|
|
137
153
|
const config = `,`${r}${s};
|
|
138
154
|
|
|
139
155
|
export default config;
|
|
140
|
-
`}o(
|
|
141
|
-
`),{css:f}=await s.generate(
|
|
156
|
+
`}o(dn,"formatConfigAsCode");async function We(e,t){try{const n=await Ve(),s=n.endsWith(".ts"),r=dn(e,s,t);await Q(n,r,"utf-8")}catch(n){const s=n instanceof Error?`: ${n.message}`:"";throw new d(`Failed to write config file${s}`)}}o(We,"writeUserConfig");function gn(e,t){return{...e,...t,output:{...e.output??{},...t.output??{}},transforms:{...e.transforms??{},...t.transforms??{}}}}o(gn,"mergeUserConfig");async function Ye(e){const{config:t}=await rt(),n=gn(t,e),s=x(le);await We(n,s)}o(Ye,"mergeConfigIntoFile");const mn=new U().name("components").description("Add components to your project").argument("[components...]","Components to add (e.g., button card)").option("-f, --framework <type>","Framework to use (react, css-only)").option("--components-dir <dir>","Components output directory (e.g., 'src/components')").option("-s, --silent","Suppress logs and prompts").option("-o, --overwrite","Overwrite existing files").action(async(e,t)=>{try{t.silent||H(Y(c.bgGreen(c.black("Components"))));const{directory:n,fromConfig:s}=await un(t.componentsDir);let r=[],a;if(e.length>0||t.framework){if(!t.framework)throw new d(m.COMPONENTS_FRAMEWORK_REQUIRED());if(!["react","css-only"].includes(t.framework))throw new d(m.COMPONENTS_INVALID_FRAMEWORK());a=t.framework,r=e}else{a=await Pe(!1);const T=await j();T||($e("Failed to fetch component list"),process.exit(1)),r=await jt(T,a)}const i=await Be(process.cwd(),{withFallback:!0}),u=await j(),p=await pe(u,r,a),f=await Dt({selectedComponents:r,componentType:a,componentsOutputDirectory:n}),l=Fe(f);if(l&&!t.force&&!t.silent){const T=je(l,{});S.space(1),await Le("Continue?",!1)}const g=[],h=[],k=new Set;for(const T of p){const $=T.dependencies?.[a]||[];for(const I of $)k.add(I)}const _=Array.from(k).filter(T=>!x(T,process.cwd()));_.length>0&&g.push({pending:`Install ${_.length} dependencies`,start:`Installing ${_.join(", ")}...`,end:`Installed ${_.join(", ")}`,while:o(async()=>{await de(_,process.cwd(),i)},"while")});for(const T of p)g.push({pending:`Write component files for ${T.name}`,start:`Writing component files for ${T.name}...`,end:`Wrote component files for ${T.name}`,while:o(async()=>{const $=await Ft({registryIndex:u,selectedComponents:[T.name],componentType:a,componentsOutputDirectory:n,overwrite:t.overwrite||!1,packageManager:i});h.push(...$.createdFiles)},"while")});if(await S.tasks(g,{successMessage:"Components added successfully! \u{1F389} ",minDurationMs:0,successAsOutro:!0}),an(""),!s&&D()){const T=R(process.cwd(),n);await Ye({output:{components:T}})}}catch(n){z(n)}}),hn=new U().name("cube").description("Add CUBE CSS to your project").option("-s, --silent","Suppress logs and prompts").option("-f, --force","Skip overwrite confirmation").option("--styles-dir <dir>","CSS output directory (e.g., 'src/styles')").action(async e=>{try{e.silent||H(Y("CUBE CSS"));const{directory:t,fromConfig:n}=await ln(e.stylesDir);try{await V(t,{recursive:!0})}catch(i){const u=i instanceof Error?`: ${i.message}`:"";throw new d(`Failed to create output directory${u}`)}const s=await Nt({cubeDirectory:t}),r=Fe(s);if(r&&!e.force&&!e.silent){S.space(1);const i=je(r,{});await Le("Continue?",!1)}const a=await Pt(t);if(!e.silent){S.space(1);const i=a,f=[...new Set(i)].map(l=>R(process.cwd(),l)).map(l=>({pending:`Write ${l}`,start:`Writing ${l}`,end:`Wrote ${l}`,while:o(async()=>{},"while")}));await S.tasks(f,{spacing:0,minDurationMs:0,successPauseMs:100,successMessage:"\u{1F389} Files written!"}),se(c.green("CUBE added successfully."))}if(!n&&D()){const i=R(process.cwd(),t);await Ye({output:{css:i}})}}catch(t){z(t)}}),wn="**/*.{html,htm,js,ts,jsx,tsx,vue,svelte,astro,php,njk,liquid,pug,hbs,handlebars,twig,erb,ejs}",yn=["**/node_modules/**","**/dist/**","**/build/**","**/.next/**","**/.nuxt/**","**/.astro/**","**/.git/**","**/coverage/**","**/.pnpm/**","**/.pnpm-store/**","**/.npm/**","**/.cache/**","**/.turbo/**","**/.vercel/**","**/.svelte-kit/**","**/out/**","**/__snapshots__/**","**/*.config.{js,ts,mjs}","**/*.min.js","**/*.bundle.js","**/*.d.ts"],Ke=1e4,He=100;async function ze(e,t){const n={name:"sugarcube",rules:it(t.utilities??{},e),preflights:[]},s=await Tt({presets:[n]}),r=await X(wn,{ignore:yn,dot:!1,onlyFiles:!0,absolute:!1});if(r.length===0)return[];if(r.length>Ke)throw new d(`Found ${r.length} files to scan (limit: ${Ke}). Are you running this from a monorepo root or a directory containing multiple projects? Run the command from within a single project directory instead.`);const a=[];let i=0;const u=He*1024*1024;for(const l of r){const g=await Ie(l,"utf8");if(i+=g.length,i>u)throw new d(`Total source size exceeds ${He}MB. Are you running this from a monorepo root or a directory containing multiple projects? Run the command from within a single project directory instead.`);a.push(g)}const p=a.join(`
|
|
157
|
+
`),{css:f}=await s.generate(p,{preflights:!1});return f?.trim()?[{path:`${t.output?.css||at}/utilities/utilities.gen.css`,css:f}]:[]}o(ze,"generateSugarcubeUtilities");async function Tn(e,t,n,s){const r=[],a=await re(e,t,n),i=await Ee(a,n,s);await ke(i),r.push(...i);const u=await ze(a,n);return await _e(u),r.push(...u),r}o(Tn,"generateAllCSS");const Sn=new U().name("generate").description("Generate CSS from your design tokens").option("--force","Skip overwrite confirmation").option("-s, --silent","Suppress logs and prompts").action(async e=>{try{if(e.silent||H(Y("Generate CSS")),x("@sugarcube-org/vite"))throw new d("Sugarcube vite plugin detected. When using the plugin, CSS is generated automatically during your build process. Remove the plugin to use CLI generation instead.");if(!D())throw new d(`A sugarcube config file was not found. This command requires one.
|
|
142
158
|
|
|
143
|
-
Please run ${c.cyan(
|
|
159
|
+
Please run ${c.cyan(N.INIT)} (or manually create a config file).
|
|
144
160
|
|
|
145
|
-
Stuck? ${c.cyan("https://sugarcube.sh")}`);const{config:t}=await ee(),{trees:n,resolved:s}=await
|
|
161
|
+
Stuck? ${c.cyan("https://sugarcube.sh")}`);const{config:t}=await ee(),{trees:n,resolved:s,modifiers:r}=await W(t),a=await Tn(n,s,t,r);if(!e.silent){const i=a.map(l=>l.path),f=[...new Set(i)].map(l=>R(process.cwd(),l)).map(l=>({pending:`Write ${l}`,start:`Writing ${l}`,end:`Wrote ${l}`,while:o(async()=>{},"while")}));await S.tasks(f,{spacing:1,minDurationMs:0,successPauseMs:100,successMessage:"\u{1F389} Files written!"}),S.space(1),se(c.green("CSS generated successfully."))}}catch(t){z(t)}});async function In(e){const t=R(process.cwd(),e.actualStylesDir),n=e.isSrcDir?te.output.components:te.output.components.replace(/^src\//,"");return{resolver:e.resolverPath,output:{css:t,components:n}}}o(In,"buildUserConfig");function qe(e,t=0){if(typeof e!="object"||e===null||t>_t)return!1;for(const[n,s]of Object.entries(e))if(!n.startsWith("$")&&typeof s=="object"&&s!==null&&("$value"in s||qe(s,t+1)))return!0;return!1}o(qe,"hasAnyToken");async function En(e){try{const t=await X(Et,{cwd:e,absolute:!0});for(const n of t)try{const s=await oe.readFile(n,"utf-8"),r=JSON.parse(s);if(qe(r))return!0}catch{}return!1}catch{return!1}}o(En,"detectExistingTokens");function Je(e){try{const t=ie.resolve(e,"package.json");if(!F(t))return null;const n=Se(t,"utf-8");return JSON.parse(n)}catch{return null}}o(Je,"getPackageJson");function M(e,t){if(!e)return!1;const n=e.dependencies,s=e.devDependencies;return!!(n?.[t]||s?.[t])}o(M,"hasDependency");function kn(e,t){if(!e)return!1;const n=e.dependencies,s=e.devDependencies,r={...n,...s};return Object.keys(r).some(a=>a.startsWith(t))}o(kn,"hasDependencyStartingWith");function _n(e){const t=F(ie.resolve(e,"src")),n=Je(e),s=t?"src/design-tokens":"design-tokens",r=t?"src/styles":"styles",a=t?"src/components":"components";let i="none";return M(n,"next")?i=F(ie.resolve(e,`${t?"src/":""}app`))?"next-app":"next-pages":M(n,"astro")?i="astro":M(n,"nuxt")?i="nuxt":M(n,"@sveltejs/kit")?i="sveltekit":kn(n,"@remix-run/")?i="remix":M(n,"@11ty/eleventy")?i="eleventy":M(n,"vite")&&(i="vite"),{framework:i,isSrcDir:t,tokensDir:s,stylesDir:r,componentDir:a}}o(_n,"getProjectInfo");function $n(e,t){if(["vite","astro","nuxt","sveltekit","remix"].includes(e))return!0;if(e==="eleventy"){const s=Je(t);return M(s,"vite")}return!1}o($n,"shouldInstallVitePlugin");const Rn=o(async e=>{S.space(2),await G(200);let t="Next steps";if(e.pluginToInstall===le)t+=`
|
|
146
162
|
|
|
147
163
|
`,t+=`1. Import the generated CSS
|
|
148
164
|
`,t+=` ${c.cyan("import 'virtual:sugarcube.css'")}`;else{const n=`${e.stylesDir}/global/tokens.variables.gen.css`;t+=`
|
|
@@ -151,9 +167,9 @@ Stuck? ${c.cyan("https://sugarcube.sh")}`);const{config:t}=await ee(),{trees:n,r
|
|
|
151
167
|
`,t+=` ${c.cyan(`import './${n}'`)}`}t+=`
|
|
152
168
|
|
|
153
169
|
`,t+=`2. (Optional) Add CUBE CSS
|
|
154
|
-
`,t+=` ${c.cyan(
|
|
170
|
+
`,t+=` ${c.cyan(N.CUBE)}`,t+=`
|
|
155
171
|
|
|
156
172
|
`,t+=`3. (Optional) Add components
|
|
157
|
-
`,t+=` ${c.cyan(
|
|
173
|
+
`,t+=` ${c.cyan(N.COMPONENTS)}`,t+=`
|
|
158
174
|
|
|
159
|
-
`,t+=`Docs: ${c.cyan("https://sugarcube.sh")}`,
|
|
175
|
+
`,t+=`Docs: ${c.cyan("https://sugarcube.sh")}`,tn(t,{width:.75}),await G(200),S.break(1)},"nextSteps");async function Cn(e){await Rn(e)}o(Cn,"next");const bn=o(async()=>{const e=["Welcome to sugarcube \u2014 the toolkit for seriously sweet frontends!"];S.space(1),await S.animated(e,{clear:!1})},"welcome");function Ze(e,t){if(!e||e.trim()==="")throw new d(m.DIRECTORY_PATH_EMPTY(t));const s=tt(e).split("/")[0];if(s&&kt.includes(s))throw new d(m.DIRECTORY_PATH_RESERVED(t,e))}o(Ze,"validateDirectoryPath");function vn(e){e.tokensDir&&Ze(e.tokensDir,"tokens-dir"),e.stylesDir&&Ze(e.stylesDir,"styles-dir")}o(vn,"validateOptions");async function Dn(){D()&&(he(m.CONFIG_EXISTS(),{}),process.exit(0))}o(Dn,"preflightInit");async function Nn(e){const t=_n(process.cwd()),n=e.tokensDir||t.tokensDir,s=e.stylesDir||t.stylesDir,r=await En(n);let a=null;if(r){const i=await Oe(n);if(i.found==="none")throw new d(m.RESOLVER_NOT_FOUND(n));if(i.found==="multiple")throw new d(m.RESOLVER_MULTIPLE_FOUND(i.paths));a=i.path}return{tokensDir:n,stylesDir:s,isSrcDir:t.isSrcDir,hasExistingTokens:r,resolverPath:a,framework:t.framework}}o(Nn,"initializeProjectContext");function An(e,t,n){const s=t?null:e.kit||ce;if((e.skip||[]).includes("plugin"))return{starterKit:s,pluginToInstall:null};const a=Fn(n,process.cwd());return{starterKit:s,pluginToInstall:a}}o(An,"determineInstallationTargets");function Fn(e,t){return $n(e,t)?le:null}o(Fn,"determinePlugin");async function On(e,t,n,s,r){const a=await Be(process.cwd(),{withFallback:!0});return{options:e,...t,isSrcDir:t.isSrcDir,config:n,userConfig:s,...r,packageManager:a,createdFiles:[],createdDirectories:[],installedDependencies:[],tasks:[]}}o(On,"buildInitContext");async function Pn(e){const{trees:t,resolved:n}=await W(e.config);e.setupResult={config:e.config,createdTokenPaths:[],trees:t,resolved:n,tokenFiles:[],tokensDir:e.tokensDir}}o(Pn,"processExistingTokens");async function Ln(e){!e.hasExistingTokens&&e.starterKit?await Ut(e):await Pn(e)}o(Ln,"setupDesignTokens");async function Mn(e){if(!e.setupResult)throw new d(m.INITIALIZATION_INCOMPLETE());const{trees:t,resolved:n}=e.setupResult,s=await re(t,n,e.config),r=await Ee(s,e.config);await ke(r)}o(Mn,"writeCSSVariables");async function Un(e){if(!e.setupResult)throw new d(m.INITIALIZATION_INCOMPLETE());const{trees:t,resolved:n}=e.setupResult,s=await re(t,n,e.config),r=await ze(s,e.config);r.length&&await _e(r)}o(Un,"writeCSSUtilities");async function jn(e){if(e.pluginToInstall&&!x(e.pluginToInstall))try{await de([e.pluginToInstall],process.cwd(),e.packageManager),e.installedDependencies.push(e.pluginToInstall)}catch{throw new d(m.PLUGIN_INSTALL_FAILED({pluginToInstall:e.pluginToInstall,packageManager:e.packageManager}))}}o(jn,"installPlugins");async function Gn(e){try{const t=!!e.pluginToInstall;await We(e.userConfig,t);const n=await Ve();e.createdFiles.push(n)}catch{throw new d(m.CONFIG_WRITE_FAILED())}}o(Gn,"finalize");function xn(e){const t=[];if(e.hasExistingTokens?t.push({pending:"Looking for existing tokens",start:"Looking for existing tokens...",end:`Existing tokens found at ${e.tokensDir} ${E("\u2192","->")} using them`,while:o(async()=>{},"while")}):e.starterKit&&t.push({pending:"Looking for existing tokens",start:"Looking for existing tokens...",end:`No existing tokens detected ${E("\u2192","->")} adding starter kit`,while:o(async()=>{},"while")}),e.pluginToInstall){const n="Vite";x(e.pluginToInstall)?t.push({pending:`Checking for ${n} compatibility`,start:`Checking for ${n} compatibility...`,end:`${n} plugin already installed ${E("\u2192","->")} skipping plugin installation`,while:o(async()=>{},"while")}):t.push({pending:"Checking for Vite compatibility",start:"Checking for Vite compatibility...",end:`Vite detected ${E("\u2192","->")} plugin will be installed`,while:o(async()=>{},"while")})}else{const n=e.options.skip?.includes("plugin");t.push({pending:"Checking for Vite compatibility",start:"Checking for Vite compatibility...",end:n?`Plugin skipped ${E("\u2192","->")} CSS will be generated as file(s)`:`No Vite detected ${E("\u2192","->")} CSS will be generated as file(s)`,while:o(async()=>{},"while")})}return t}o(xn,"buildDetectionTasks");async function Bn(e){if(e.tasks.push({pending:e.hasExistingTokens?"Process existing design tokens":"Add design tokens",start:e.hasExistingTokens?"Processing existing design tokens...":"Adding design tokens...",end:e.hasExistingTokens?"Design tokens processed":"Design tokens added",while:o(async()=>{await Ln(e)},"while")}),!e.pluginToInstall)e.tasks.push({pending:"Generate CSS variables",start:"Generating CSS variables...",end:"CSS variables generated",while:o(async()=>{await Mn(e)},"while")}),e.tasks.push({pending:"Generate CSS utilities",start:"Generating CSS utilities...",end:"CSS utilities generated",while:o(async()=>{await Un(e)},"while")});else if(e.pluginToInstall&&!x(e.pluginToInstall)){const t="Vite";e.tasks.push({pending:`Install ${t} plugin`,start:`Installing ${t} plugin...`,end:`${t} plugin installed`,while:o(async()=>{await jn(e)},"while")})}e.tasks.push({pending:"Write configuration file",start:"Writing configuration file...",end:"Configuration file written",while:o(async()=>{await Gn(e)},"while")})}o(Bn,"buildExecutionTasks");const Vn=new U().name("init").description("Initialize a new sugarcube project").option("--kit <kit>",`Starter kit to use (default: ${ce})`,ce).option("--tokens-dir <dir>","Design tokens directory (e.g., 'src/design-tokens')").option("--styles-dir <dir>","Styles output directory (e.g., 'src/styles')").option("--with <items...>","Install optional items").option("--skip <items...>","Skip installation of specific items (e.g., plugin)").action(async e=>{let t;try{vn(e),await Dn();const n=await Nn(e),s=n.resolverPath??"",r=await In({resolverPath:s,actualStylesDir:n.stylesDir,isSrcDir:n.isSrcDir}),a=ct(r),i=An(e,n.hasExistingTokens,n.framework);t=await On(e,n,a,r,i),H(Y("sugarcube")),await bn();const u=xn(t);u.length>0&&(S.message("Detecting project\u2026"),await S.tasks(u,{minDurationMs:1e3})),t.tasks=[],await Bn(t),t.tasks.length>0&&(S.message("Setting things up\u2026"),await S.tasks(t.tasks,{successMessage:"\u{1F389} Tasks completed successfully!"})),await Cn(t)}catch(n){z(n)}}),Wn=new U().name("validate").description("Validate design token files").argument("[paths...]","Token files or directories to validate (e.g., src/design-tokens)").action(async e=>{try{if(H(Y("Validate")),D()&&!e.length){const{config:r}=await ee();await W(r),se(c.greenBright("All tokens valid \u2728"));return}if(!e.length)throw new d(m.VALIDATE_NO_PATH_SPECIFIED());for(const r of e)if(!F(r))throw new d(m.VALIDATE_PATH_NOT_FOUND(r));const t=await X(e.map(r=>r.endsWith(".json")?r:C(r,"**/*.json")));if(t.length===0)throw new d(m.VALIDATE_NO_TOKEN_FILES());const n={};for(const r of t){const a=await Ie(r,"utf-8"),i=R(process.cwd(),r);n[i]={content:a}}const s=D()?(await ee()).config:{output:te.output,transforms:te.transforms};await W(s,n),se(c.greenBright("All tokens valid \u2728"))}catch(t){z(t)}});process.on("SIGINT",()=>process.exit(0)),process.on("SIGTERM",()=>process.exit(0));async function Yn(){const e=new U().name("sugarcube").description("CLI for scaffolding sugarcube projects").version(It.version,"-v, --version","display the version number");e.addCommand(Vn).addCommand(Sn).addCommand(Wn).addCommand(mn).addCommand(hn),e.parse()}o(Yn,"main"),Yn();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sugarcube-org/cli",
|
|
3
|
-
"version": "0.0.0-alpha.
|
|
3
|
+
"version": "0.0.0-alpha.23",
|
|
4
4
|
"publishConfig": {
|
|
5
5
|
"access": "public",
|
|
6
6
|
"provenance": false
|
|
@@ -40,7 +40,7 @@
|
|
|
40
40
|
"@antfu/ni": "23.3.0",
|
|
41
41
|
"@clack/core": "1.0.0-alpha.3",
|
|
42
42
|
"@clack/prompts": "1.0.0-alpha.3",
|
|
43
|
-
"@sugarcube-org/core": "0.0.1-alpha.
|
|
43
|
+
"@sugarcube-org/core": "0.0.1-alpha.10",
|
|
44
44
|
"@unocss/core": "66.5.2",
|
|
45
45
|
"commander": "12.1.0",
|
|
46
46
|
"execa": "9.5.2",
|
|
@@ -65,8 +65,9 @@
|
|
|
65
65
|
"scripts": {
|
|
66
66
|
"build": "tsc --noEmit && pkgroll --minify",
|
|
67
67
|
"dev": "cross-env REGISTRY_URL=http://localhost:4321/r tsx src/index.ts",
|
|
68
|
-
"test": "vitest run",
|
|
69
|
-
"test:
|
|
68
|
+
"test": "vitest run --exclude 'tests/e2e/**'",
|
|
69
|
+
"test:e2e": "vitest run tests/e2e",
|
|
70
|
+
"test:watch": "vitest --exclude 'tests/e2e/**'",
|
|
70
71
|
"type-check": "tsc --noEmit",
|
|
71
72
|
"start": "cross-env REGISTRY_URL=https://sugarcube.sh/r tsx src/index.ts"
|
|
72
73
|
}
|