@frontfriend/tailwind 4.0.10 → 4.0.11
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/cli.js +44 -36
- package/dist/lib/core/api-client.js +2 -2
- package/dist/lib/core/api-client.js.map +3 -3
- package/dist/lib/core/cache-manager.js +7 -0
- package/dist/lib/core/component-downloader.js +3 -3
- package/dist/lib/core/component-downloader.js.map +3 -3
- package/dist/lib/core/default-config.js +1 -1
- package/dist/lib/core/default-config.js.map +3 -3
- package/dist/next.js +1 -1
- package/dist/next.js.map +3 -3
- package/dist/vite.js +8 -8
- package/dist/vite.js.map +3 -3
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,82 +1,90 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
`,{mode:384});try{
|
|
2
|
+
var T=(e,o)=>()=>(o||e((o={exports:{}}).exports,o),o.exports);var X=T((Zn,Q)=>{var Oe="https://app.frontfriend.dev",Pe="https://registry-legacy.frontfriend.dev",Le=".cache/frontfriend",De={JS:["tokens.js","variables.js","semanticVariables.js","semanticDarkVariables.js","safelist.js","custom.js"],JSON:["fonts.json","icons.json","components-config.json","version.json","metadata.json"]},Ne={FF_ID:"FF_ID",FF_API_URL:"FF_API_URL",FF_USE_LOCAL:"FF_USE_LOCAL",FF_AUTH_TOKEN:"FF_AUTH_TOKEN"};Q.exports={DEFAULT_API_URL:Oe,LEGACY_API_URL:Pe,CACHE_DIR_NAME:Le,CACHE_TTL_DAYS:7,CACHE_TTL_MS:6048e5,CACHE_FILES:De,ENV_VARS:Ne}});var le=T((Qn,ae)=>{var k=require("fs"),ee=require("path"),Re=require("os"),Ue=require("https"),Me=require("http"),{URL:Ve}=require("url"),{DEFAULT_API_URL:ne}=X(),oe=ee.join(Re.homedir(),".frontfriend"),$=ee.join(oe,"credentials");function qe(){return $}function te(){try{return k.existsSync($)?JSON.parse(k.readFileSync($,"utf8")):null}catch{return null}}function se(e){k.mkdirSync(oe,{recursive:!0,mode:448}),k.writeFileSync($,`${JSON.stringify(e,null,2)}
|
|
3
|
+
`,{mode:384});try{k.chmodSync($,384)}catch{}}function Je(){return k.existsSync($)?(k.unlinkSync($),!0):!1}function re(e,o=60*1e3){return!(e!=null&&e.accessToken)||!e.expiresAt||Date.now()+o>=e.expiresAt}function L(e){let o=new Error(`${e}. Run \`frontfriend login\` to re-authenticate.`);return o.code="FF_AUTH_REFRESH_FAILED",o}function ie(e,o,n){return new Promise((t,s)=>{let r=new Ve(e),i=r.protocol==="https:"?Ue:Me,f=JSON.stringify(o||{}),a=i.request({hostname:r.hostname,port:r.port,path:`${r.pathname}${r.search}`,method:"POST",headers:{"content-type":"application/json","content-length":Buffer.byteLength(f),...n?{authorization:`Bearer ${n}`}:{}}},l=>{let g="";l.on("data",c=>{g+=c}),l.on("end",()=>{if(l.statusCode>=300&&l.statusCode<400){let u=l.headers.location?` to ${l.headers.location}`:"",h=new Error(`HTTP ${l.statusCode}: redirected${u}`);h.statusCode=l.statusCode,h.body=g,s(h);return}let c=null;try{c=g?JSON.parse(g):null}catch(u){if(l.statusCode>=400){let h=new Error(`HTTP ${l.statusCode}: ${l.statusMessage||"Non-JSON response"}`);h.statusCode=l.statusCode,h.body=g,s(h);return}s(u);return}if(l.statusCode>=400){let u=new Error((c==null?void 0:c.error_description)||(c==null?void 0:c.error)||`HTTP ${l.statusCode}`);u.statusCode=l.statusCode,u.body=c,s(u);return}t(c)})});a.on("error",s),a.write(f),a.end()})}async function ce(e,o=ne){if(!(e!=null&&e.refreshToken)||!(e!=null&&e.deviceId))throw L("FrontFriend session expired");let n;try{n=await ie(`${o}/api/plugin/token`,{grant_type:"refresh_token",refresh_token:e.refreshToken,device_id:e.deviceId})}catch(s){throw L((s==null?void 0:s.message)||"Could not refresh FrontFriend session")}if(!(n!=null&&n.access_token)||!(n!=null&&n.refresh_token))throw L("Could not refresh FrontFriend session");let t={accessToken:n.access_token,refreshToken:n.refresh_token,deviceId:n.device_id||e.deviceId,expiresAt:Date.now()+(n.expires_in||900)*1e3,refreshExpiresAt:Date.now()+(n.refresh_expires_in||604800)*1e3,ffApiUrl:o};return se(t),t}async function Be(e={}){if(!e.skipCredentials){let o=te();if(o!=null&&o.accessToken||o!=null&&o.refreshToken){let n=e.baseURL||o.ffApiUrl||ne;return o.accessToken&&!re(o)?o.accessToken:(await ce(o,n)).accessToken}}return e.envToken?e.envToken:e.legacyToken?(e.silent||console.warn("\u26A0\uFE0F auth-token in frontfriend.config.js is deprecated. Run `frontfriend login` to store credentials outside the repo."),e.legacyToken):null}ae.exports={getCredentialsPath:qe,readCredentials:te,writeCredentials:se,deleteCredentials:Je,isExpired:re,postJson:ie,refreshCredentials:ce,resolveAuthToken:Be,createAuthRefreshError:L}});var ge=T((Xn,ue)=>{var R={primary:"brand-mid","primary-foreground":"onbrand-mid",secondary:"neutral-subtle","secondary-foreground":"neutral-strong",destructive:"negative-mid","destructive-foreground":"onnegative-mid",background:"layer-below",foreground:"neutral-strong",card:"layer-raised","card-foreground":"neutral-strong",popover:"layer-popover","popover-foreground":"neutral-strong",muted:"neutral-subtle","muted-foreground":"neutral-mid",accent:"neutral-subtle","accent-foreground":"neutral-strong",border:"neutral-subtle",ring:"brand-mid","sidebar-foreground":"neutral-strong","sidebar-primary":"brand-mid","sidebar-primary-foreground":"onbrand-mid","sidebar-accent":"neutral-subtle","sidebar-accent-foreground":"neutral-strong","sidebar-border":"neutral-subtle","sidebar-ring":"brand-mid",success:"positive-mid","success-foreground":"onpositive-mid",info:"info-mid","info-foreground":"oninfo-mid",warning:"warning-mid","warning-foreground":"onwarning-mid",invert:"inverse-mid","invert-foreground":"neutral-low"},He=[...Object.keys(R),"input"].sort((e,o)=>o.length-e.length);function Ge(e){return e.split(/\s+/).filter(Boolean).map(fe).join(" ")}function ze(e){let o=0,n=-1;for(let t=0;t<e.length;t+=1){let s=e[t];s==="["&&(o+=1),s==="]"&&(o=Math.max(0,o-1)),s===":"&&o===0&&(n=t)}return n===-1?{prefix:"",base:e}:{prefix:e.slice(0,n+1),base:e.slice(n+1)}}function fe(e){if(!e)return e;let{prefix:o,base:n}=ze(e),t=n.match(/^(.*?)(\/\d{1,3})$/),s=t?t[1]:n,r=t?t[2]:"";if(s==="bg-black")return`${o}bg-overlay`;for(let i of He){if(!s.endsWith(i))continue;let f=s.slice(0,s.length-i.length);if(!f.endsWith("-"))continue;let a=f.slice(0,-1);if(a)return i==="input"?`${o}${a}-${a==="bg"?"layer-control":"neutral-subtle"}${r}`:`${o}${a}-${R[i]}${r}`}return e}var Ye=new Set(["chart-1","chart-2","chart-3","chart-4","chart-5","sidebar","radius"]),de=/--(?:chart-\d+|sidebar(?:-[a-z-]+)?|radius)\s*:[^;{}]+;/gi;function Ke(e){if(!e)return"";let o=new Set,n=[],t=e.match(de)||[];for(let s of t){let r=s.replace(/\s+/g," ").trim(),i=r.slice(0,r.indexOf(":")).trim();o.has(i)||(o.add(i),n.push(` ${r}`))}return n.length===0?"":`:root {
|
|
4
4
|
${n.join(`
|
|
5
5
|
`)}
|
|
6
6
|
}
|
|
7
|
-
`}
|
|
8
|
-
`)
|
|
7
|
+
`}function We(e){if(!e)return{scaffold:"",custom:""};let o=s=>/^\s*@import\s+["'](?:tailwindcss|tw-animate-css|@frontfriend\/)/.test(s),n=[],t=[];for(let s of e.split(`
|
|
8
|
+
`))(o(s)?n:t).push(s);return{scaffold:n.join(`
|
|
9
|
+
`).trim(),custom:t.join(`
|
|
10
|
+
`).replace(/\n{3,}/g,`
|
|
11
|
+
|
|
12
|
+
`).trim()}}ue.exports={SHADCN_FF_TOKEN_MAP:R,CSSVAR_TOKENS:Ye,SHADCN_CSSVAR_PATTERN:de,shadcnToFf:Ge,shadcnTokenToFf:fe,extractShadcnCssVars:Ke,liftHostCustomCss:We}});var he=T((eo,me)=>{var pe={lucide:["lucide-react"],tabler:["@tabler/icons-react"],hugeicons:["@hugeicons/react","@hugeicons/core-free-icons"],phosphor:["@phosphor-icons/react"],remixicon:["@remixicon/react"]};function Ze(e,o){let n=e&&e.iconLibrary||o||"lucide";return pe[n]?n:"lucide"}function Qe(e,o){return typeof e!="string"?e:e.replace(/(from\s+["']\.\/adapters\/)[a-z]+(["'])/,`$1${o}$2`)}me.exports={ICON_LIBRARY_DEPS:pe,resolveIconLibraryName:Ze,swapIconAdapterImport:Qe}});var ye=T((no,Xe)=>{Xe.exports={name:"@frontfriend/tailwind",version:"4.0.11",description:"Design token management for Tailwind CSS",main:"./dist/index.js",types:"./dist/types/index.d.ts",bin:{frontfriend:"dist/cli.js"},exports:{".":{types:"./dist/types/index.d.ts",browser:"./dist/browser.mjs",import:"./dist/index.mjs",require:"./dist/index.js",default:"./dist/index.js"},"./runtime":{types:"./dist/runtime.d.ts",default:"./dist/runtime.js"},"./next":{types:"./dist/next.d.ts",default:"./dist/next.js"},"./vite":{types:"./dist/vite.d.ts",default:"./dist/vite.mjs"},"./lib/react/utils":{types:"./dist/lib/react/utils.d.ts",default:"./dist/lib/react/utils.mjs"},"./lib/vue/utils":{types:"./dist/lib/vue/utils.d.ts",default:"./dist/lib/vue/utils.mjs"},"./ffdc":{types:"./dist/ffdc.d.ts",default:"./dist/ffdc.js"},"./theme":"./src/theme.css","./theme.css":"./src/theme.css","./components-config-schema":{types:"./dist/components-config-schema.d.ts",require:"./dist/components-config-schema.js",import:"./dist/components-config-schema.js",default:"./dist/components-config-schema.js"}},scripts:{test:"jest",build:"node scripts/build.js",prepublishOnly:"npm run build"},keywords:["tailwindcss","design-tokens","frontfriend"],author:"Donux",license:"SEE LICENSE IN LICENSE",files:["dist/","src/theme.css","scripts/","README.md","LICENSE"],dependencies:{commander:"^11.0.0",dotenv:"^16.0.0",color:"^4.2.3",clsx:"^2.0.0","tailwind-merge":"^2.0.0","tw-animate-css":"^1.3.4"},peerDependencies:{tailwindcss:"^3.0.0 || ^4.0.0","tw-animate-css":"^1.3.0",react:"^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",vue:">=3.0.0"},devDependencies:{jest:"^29.0.0",esbuild:"^0.19.0",glob:"^10.0.0"}}});var M=T((oo,U)=>{var x=require("fs"),E=require("path");function Ce(e={}){let o=e.projectRoot||process.cwd(),n=E.join(o,"node_modules",".cache","frontfriend","icons.json"),t=e.outputPath||E.join(o,"types","frontfriend.d.ts");x.existsSync(n)||(console.error('[FrontFriend] Error: icons.json not found. Please run "npx frontfriend init" first.'),process.exit(1));try{let a=function(y){for(let C of Object.values(y))typeof C=="string"?f.add(C):typeof C=="object"&&C!==null&&a(C)},l=function(y,C=" "){let v=[];for(let[P,b]of Object.entries(y))typeof b=="string"?v.push(`${C}${P}: '${b}';`):typeof b=="object"&&b!==null&&(v.push(`${C}${P}: {`),v.push(l(b,C+" ")),v.push(`${C}};`));return v.join(`
|
|
13
|
+
`)};var s=a,r=l;let i=JSON.parse(x.readFileSync(n,"utf-8")),f=new Set;a(i);let g=Array.from(f).map(y=>`'${y}'`).join(" | "),c=`// Generated by @frontfriend/tailwind
|
|
9
14
|
// DO NOT EDIT THIS FILE MANUALLY
|
|
10
15
|
|
|
11
16
|
import type { IconSetStructure } from '@frontfriend/tailwind';
|
|
12
17
|
|
|
13
18
|
declare module '@frontfriend/tailwind' {
|
|
14
19
|
// Icon names used in this project
|
|
15
|
-
export type ProjectIconName = ${
|
|
20
|
+
export type ProjectIconName = ${g||"string"};
|
|
16
21
|
|
|
17
22
|
// Typed iconSet structure with exact icon names
|
|
18
23
|
export interface TypedIconSet extends IconSetStructure {
|
|
19
|
-
${
|
|
24
|
+
${l(i)}
|
|
20
25
|
}
|
|
21
26
|
}
|
|
22
27
|
|
|
23
28
|
// Augment Vue component types with exact icon names
|
|
24
29
|
declare module '*/components/ui/icon/*.vue' {
|
|
25
|
-
export type IconName = ${
|
|
30
|
+
export type IconName = ${g||"string"};
|
|
26
31
|
}
|
|
27
32
|
|
|
28
33
|
declare module '@/components/ui/icon/*.vue' {
|
|
29
|
-
export type IconName = ${
|
|
34
|
+
export type IconName = ${g||"string"};
|
|
30
35
|
}
|
|
31
36
|
|
|
32
37
|
declare module '@/components/ui/icon' {
|
|
33
|
-
export type IconName = ${
|
|
38
|
+
export type IconName = ${g||"string"};
|
|
34
39
|
}
|
|
35
40
|
|
|
36
41
|
declare module '@/src/components/ui/icon' {
|
|
37
|
-
export type IconName = ${
|
|
42
|
+
export type IconName = ${g||"string"};
|
|
38
43
|
}
|
|
39
44
|
|
|
40
45
|
declare module '@/src/components/ui/icon/Icon.vue' {
|
|
41
|
-
export type IconName = ${
|
|
46
|
+
export type IconName = ${g||"string"};
|
|
42
47
|
}
|
|
43
|
-
`,
|
|
44
|
-
`)}var
|
|
48
|
+
`,u=E.dirname(t);x.existsSync(u)||x.mkdirSync(u,{recursive:!0}),x.writeFileSync(t,c),console.log("[FrontFriend] \u2713 Generated types at",E.relative(o,t));let h=E.join(o,"tsconfig.json");if(x.existsSync(h)){let y=JSON.parse(x.readFileSync(h,"utf-8"));y.include||(y.include=[]);let C="types/**/*.d.ts";y.include.includes(C)||(y.include.push(C),x.writeFileSync(h,JSON.stringify(y,null,2)),console.log("[FrontFriend] \u2713 Updated tsconfig.json to include generated types"))}}catch(i){console.error("[FrontFriend] Error generating icon types:",i.message),process.exit(1)}}require.main===U&&Ce();U.exports={generateIconTypes:Ce}});var{loadEnvLocal:en}=require("./lib/core/env-utils");en();var{Command:nn}=require("commander"),O=require("./lib/core/config-loader"),A=require("./lib/core/cache-manager"),{APIClient:Se}=require("./lib/core/api-client"),{getCredentialsPath:on,writeCredentials:tn,readCredentials:sn,deleteCredentials:rn,postJson:V}=le(),{ComponentDownloader:cn}=require("./lib/core/component-downloader"),an=require("./lib/core/token-processor"),{shadcnToFf:ln,liftHostCustomCss:fn}=ge(),{ICON_LIBRARY_DEPS:dn,resolveIconLibraryName:un,swapIconAdapterImport:gn}=he(),{ConfigError:j,APIError:pn,CacheError:z}=require("./lib/core/errors"),d=require("path"),p=require("fs"),{spawn:mn}=require("child_process"),S=new nn,{version:be}=ye(),hn="https://registry.frontfriend.dev/r/v4",we='@import "@frontfriend/tailwind/theme.css";',xe=["app/globals.css","src/app/globals.css","styles/globals.css","src/styles/globals.css","src/styles.css","src/index.css","src/style.css"];function yn(e){let o=(e||process.env.FF_REGISTRY_URL||hn).replace(/\/+$/,"");return/\/r\/(legacy|v4)$/i.test(o)?o:`${o}/r/v4`}function F(e){try{return JSON.parse(p.readFileSync(e,"utf8"))}catch{return null}}function N(e,o){p.mkdirSync(d.dirname(e),{recursive:!0}),p.writeFileSync(e,`${JSON.stringify(o,null,2)}
|
|
49
|
+
`)}var Cn=d.join("node_modules",".cache","frontfriend","migrated-components.json");function wn(e){let o=F(d.join(e,"package.json"))||{},n={...o.dependencies||{},...o.devDependencies||{}};return n.vue||n["@vitejs/plugin-vue"]?"vue":"react"}function vn(e){let o=F(d.join(e,"package.json"))||{},n={...o.dependencies||{},...o.devDependencies||{}};return n.next||p.existsSync(d.join(e,"next.config.js"))||p.existsSync(d.join(e,"next.config.mjs"))?"next":n.vite||p.existsSync(d.join(e,"vite.config.ts"))||p.existsSync(d.join(e,"vite.config.js"))?"vite":null}function Sn(e,o,n){let t=d.join(e,"components.json");if(!p.existsSync(t))return!1;let s=F(t)||{};s.registries=s.registries||{};let r=`${yn(n)}/${o}/{name}.json`;return s.registries["@frontfriend"]===r?!1:(s.registries["@frontfriend"]=r,N(t,s),!0)}function bn(e){let o=d.join(e,"package.json"),n=F(o);return n?(n.dependencies=n.dependencies||{},n.dependencies["@frontfriend/tailwind"]?!1:(n.dependencies["@frontfriend/tailwind"]="^4.0.0",N(o,n),!0)):!1}function xn(e){let o=["next.config.js","next.config.mjs","next.config.ts"].map(n=>d.join(e,n)).find(n=>p.existsSync(n));return o?p.readFileSync(o,"utf8").includes("@frontfriend/tailwind/next")?"present":"manual":(p.writeFileSync(d.join(e,"next.config.js"),`const frontfriend = require('@frontfriend/tailwind/next');
|
|
45
50
|
|
|
46
51
|
module.exports = frontfriend({});
|
|
47
|
-
`),"created")}function
|
|
52
|
+
`),"created")}function jn(e){let o=["vite.config.ts","vite.config.js","vite.config.mjs"].map(n=>d.join(e,n)).find(n=>p.existsSync(n));return o?p.readFileSync(o,"utf8").includes("@frontfriend/tailwind/vite")?"present":"manual":(p.writeFileSync(d.join(e,"vite.config.ts"),`import { defineConfig } from 'vite';
|
|
48
53
|
import frontfriend from '@frontfriend/tailwind/vite';
|
|
49
54
|
|
|
50
55
|
export default defineConfig({
|
|
51
56
|
plugins: [frontfriend()],
|
|
52
57
|
});
|
|
53
|
-
`),"created")}function
|
|
54
|
-
${t}`),{changed:!0,relativePath:n})}function
|
|
55
|
-
`))}function
|
|
58
|
+
`),"created")}function Fn(e){let o=xe.find(n=>p.existsSync(d.join(e,n)));return o?d.join(e,o):null}function kn(e){let n=xe.find(s=>p.existsSync(d.join(e,s)))||"app/globals.css",t=d.join(e,n);return p.mkdirSync(d.dirname(t),{recursive:!0}),p.existsSync(t)||p.writeFileSync(t,""),{fullPath:t,relativePath:n}}function $n(e){let{fullPath:o,relativePath:n}=kn(e),t=p.readFileSync(o,"utf8");return t.includes(we)?{changed:!1,relativePath:n}:(p.writeFileSync(o,`${we}
|
|
59
|
+
${t}`),{changed:!0,relativePath:n})}function _n(e,o={}){let n=d.join(e,"components.json");if(!p.existsSync(n))return{isShadcnProject:!1,changes:[]};let t=wn(e),s=vn(e),r=[],i=[];if(Sn(e,t,o.registryUrl)&&r.push(`registered @frontfriend registry for ${t}`),bn(e)&&r.push("added @frontfriend/tailwind dependency"),s==="next"){let a=xn(e);a==="created"&&r.push("created next.config.js with the FrontFriend plugin"),a==="manual"&&i.push('wrap your existing next.config with `require("@frontfriend/tailwind/next")(...)`')}if(s==="vite"){let a=jn(e);a==="created"&&r.push("created vite.config.ts with the FrontFriend plugin"),a==="manual"&&i.push("add `frontfriend()` from `@frontfriend/tailwind/vite` to your existing vite.config plugins array")}let f=$n(e);return f.changed&&r.push(`imported bundled theme in ${f.relativePath}`),{isShadcnProject:!0,changes:r,manualSteps:i,framework:t,buildTool:s}}function Tn(e){return new Promise(o=>setTimeout(o,e))}function An(e){let o=process.platform==="darwin"?"open":process.platform==="win32"?"cmd":"xdg-open",n=process.platform==="win32"?["/c","start","",e]:[e];try{return mn(o,n,{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}function In(e){e.isShadcnProject&&(console.log("\u{1F9E9} shadcn project wiring"),e.changes.length===0?console.log(" \u2713 Already configured"):e.changes.forEach(o=>console.log(` \u2713 ${o}`)),e.manualSteps&&e.manualSteps.length>0&&(console.log(" \u26A0 Manual steps required (existing config left untouched):"),e.manualSteps.forEach(o=>console.log(` \u2022 ${o}`))),console.log(` Next: npx shadcn add @frontfriend/button
|
|
60
|
+
`))}function En(e,o){let n=e.indexOf(`${o}:`);if(n===-1)return null;let t=e.indexOf("{",n);if(t===-1)return null;let s=0;for(let r=t;r<e.length;r+=1){let i=e[r];if(i==="{"&&(s+=1),i==="}"&&(s-=1),s===0)return e.slice(t+1,r)}return null}function On(e){let o={},n=/([A-Za-z0-9_-]+):\s*(['"`])([\s\S]*?)\2/g,t;for(;t=n.exec(e||"");)o[t[1]]=t[3].replace(/\s+/g," ").trim();return o}function Pn(e,o){let n=o;for(;/\s|,/.test(e[n]||"");)n+=1;let t=e[n];if(t==='"'||t==="'"||t==="`"){let r=e.indexOf(t,n+1);return r===-1?null:{name:e.slice(n+1,r),end:r+1}}let s=e.slice(n).match(/^([A-Za-z0-9_-]+)/);return s?{name:s[1],end:n+s[1].length}:null}function Ln(e){let o={},n=0;for(;n<(e||"").length;){let t=Pn(e,n);if(!t){n+=1;continue}for(n=t.end;/\s/.test(e[n]||"");)n+=1;if(e[n]!==":")continue;for(n+=1;/\s/.test(e[n]||"");)n+=1;if(e[n]!=="{")continue;let s=0,r=n;for(;n<e.length;n+=1)if(e[n]==="{"&&(s+=1),e[n]==="}"&&(s-=1),s===0){o[t.name]=On(e.slice(r+1,n)),n+=1;break}}return o}function D(e){return String(e||"").replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[_\s]+/g,"-").toLowerCase()}function Dn(e){return String(e||"").replace(/-([a-z0-9])/g,(o,n)=>n.toUpperCase())}function Nn(e){return String(e||"").replace(/(^|[-_\s]+)([a-z0-9])/g,(o,n,t)=>t.toUpperCase())}function q(e,o,n,t){let s=0,r=null,i=!1;for(let f=o;f<e.length;f+=1){let a=e[f];if(r){i?i=!1:a==="\\"?i=!0:a===r&&(r=null);continue}if(a==='"'||a==="'"||a==="`"){r=a;continue}if(a===n&&(s+=1),a===t&&(s-=1),s===0)return f}return-1}function Rn(e){let o=[],n=/(?:export\s+)?function\s+([A-Z][A-Za-z0-9_]*)\s*\(/g,t;for(;t=n.exec(e);){let r=t[1],i=e.indexOf("(",t.index),f=i===-1?-1:q(e,i,"(",")"),a=f===-1?-1:e.indexOf("{",f);if(a===-1)continue;let l=q(e,a,"{","}");l!==-1&&(o.push({name:r,body:e.slice(a,l+1)}),n.lastIndex=l+1)}let s=/(?:export\s+)?const\s+([A-Z][A-Za-z0-9_]*)\s*=/g;for(;t=s.exec(e);){let r=t[1],i=t.index,f=e.slice(i+1).search(/\n(?:export\s+)?(?:const|function)\s+[A-Z][A-Za-z0-9_]*\b|\nexport\s*\{/),a=f===-1?e.length:i+1+f;o.push({name:r,body:e.slice(i,a)})}return o}function je(e,o){let n=e[o],t="",s=!1;for(let r=o+1;r<e.length;r+=1){let i=e[r];if(s){t+=i,s=!1;continue}if(i==="\\"){s=!0;continue}if(i===n)return{value:t,end:r+1};t+=i}return null}function Un(e){let o=[];for(let n=0;n<e.length;n+=1){let t=e[n];if(t!=='"'&&t!=="'"&&t!=="`")continue;let s=je(e,n);s&&((t!=="`"||!s.value.includes("${"))&&o.push(s.value.replace(/\s+/g," ").trim()),n=s.end-1)}return o.filter(Boolean)}function Mn(e,o){let n=o;for(;/\s/.test(e[n]||"");)n+=1;if(e[n]!=="=")return null;for(n+=1;/\s/.test(e[n]||"");)n+=1;if(e[n]==='"'||e[n]==="'"){let t=je(e,n);return t?{value:t.value,end:t.end}:null}if(e[n]==="{"){let t=q(e,n,"{","}");return t===-1?null:{expression:e.slice(n+1,t),end:t+1}}return null}function Vn(e){let o=e.match(/\bdata-slot\s*=\s*(?:"([^"]+)"|'([^']+)'|\{\s*["'`]([^"'`]+)["'`]\s*\})/);return o?o[1]||o[2]||o[3]:null}function qn(e,o,n){let t=D(n),s=D(e||o);if(s===t)return"root";if(s.startsWith(`${t}-`))s=s.slice(t.length+1);else{let r=Nn(n);!e&&o.startsWith(r)&&(s=D(o.slice(r.length)))}return s?Dn(s):"root"}function Jn(e,o){let n={},t=[];for(let s of Rn(e)){let r=/\bclassName\s*=/g,i,f=!1;for(;i=r.exec(s.body);){let a=Mn(s.body,i.index+9);if(!a){t.push(`${s.name}: unreadable className`);continue}let g=(a.value!==void 0?[a.value]:Un(a.expression||"")).join(" ").replace(/\s+/g," ").trim();if(!g){t.push(`${s.name}: dynamic className without literal classes`);continue}let c=s.body.lastIndexOf("<",i.index),u=a.end?s.body.indexOf(">",a.end):-1,h=c===-1?"":s.body.slice(c,u===-1?Math.min(s.body.length,a.end+300):u+1),y=qn(Vn(h),s.name,o);n[y]=n[y]?`${n[y]} ${g}`.replace(/\s+/g," ").trim():g,f=!0}!f&&/\bclassName\b/.test(s.body)&&t.push(`${s.name}: className present but no literal classes captured`)}return{slots:n,missed:t}}function J(e,o){if(typeof e=="string")return o(e);if(Array.isArray(e))return e.map(n=>J(n,o));if(e&&typeof e=="object"){let n={};for(let[t,s]of Object.entries(e))n[t]=J(s,o);return n}return e}var Bn={button:{variant:{default:"main",outline:"tertiary"}},badge:{variant:{default:"main",outline:"tertiary"}}},Hn=new Set(["variant","size","sizes","iconPosition"]);function B(e,o){let n=e.includes("cva(")&&e.includes("variants:"),t=e.match(/cva\(\s*(['"`])([\s\S]*?)\1\s*,/),s=En(e,"variants"),r=Ln(s),i=Object.values(r).some(c=>Object.keys(c).length>0),f=Jn(e,o),a=Bn[o]||{},l={},g=c=>{c&&(l.root=l.root?`${l.root} ${c}`.replace(/\s+/g," ").trim():c)};if(t&&g(t[2].replace(/\s+/g," ").trim()),i)for(let[c,u]of Object.entries(r)){if(Object.keys(u).length===0)continue;let h;Hn.has(c)?(l[c]=l[c]||{},h=l[c]):(l.variants=l.variants||{},l.variants[c]=l.variants[c]||{},h=l.variants[c]);let y=a[c]||{};for(let[C,v]of Object.entries(u))h[y[C]||C]=v}for(let[c,u]of Object.entries(f.slots))c==="root"?g(u):(l.slots=l.slots||{},l.slots[c]=u);return!n&&Object.keys(f.slots).length===0?{skipped:!0,reason:f.missed.length>0?f.missed.join("; "):`${o} has no cva variants or literal className slots`}:n&&!i&&Object.keys(f.slots).length===0?{skipped:!0,reason:"cva component has no variant class maps or literal className slots"}:{skipped:!1,config:{[o]:l},warnings:f.missed}}function H(...e){let{deepMerge:o}=require("./lib/core/default-config");return e.reduce((n,t)=>o(n,t||{}),{})}function Gn(e){let o=require("./lib/core/token-processor"),{mergeComponentsConfig:n}=require("./lib/core/default-config"),t=new o,s=n(e),r=t.extractClassesFromComponentsConfig(s);return{componentsConfig:s,icons:{},safelist:r,classesContent:t.generateClassesContent(r),themeCSS:t.generateThemeCSS({}),metadata:{version:"local-components"}}}function Fe(e,o){let n=new A(e),t=n.exists()?n.load()||{}:{},s=H(t.componentsConfig,o),r=Gn(s);return n.save({...t,...r,icons:t.icons||{}}),r.componentsConfig}function G(e){return d.basename(e).replace(/\.(tsx|ts|jsx|js|vue)$/,"").replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[_\s]+/g,"-").toLowerCase()}var zn=["tsx","ts","jsx","js","vue"],ke=/\.(tsx|ts|jsx|js|vue)$/;function Yn(e){let o={};for(let n of["tsconfig.json","tsconfig.app.json","jsconfig.json"]){let t=F(d.join(e,n)),s=t&&t.compilerOptions&&t.compilerOptions.paths;s&&Object.assign(o,s)}return o}function Kn(e,o){if(!o)return null;let n=Yn(e);for(let[t,s]of Object.entries(n))if(!(!Array.isArray(s)||s.length===0)){if(t.endsWith("/*")){let r=t.slice(0,-1);if(o.startsWith(r)){let i=o.slice(r.length),f=s[0].replace(/\*+$/,"");return d.resolve(e,f,i)}}else if(t===o)return d.resolve(e,s[0])}return o.startsWith("@/")?d.resolve(e,"src",o.slice(2)):d.resolve(e,o)}function $e(e){let o=F(d.join(e,"components.json")),n=o&&o.aliases&&o.aliases.ui,t=[n?Kn(e,n):null,d.join(e,"src","components","ui"),d.join(e,"components","ui")].filter(Boolean);return[...new Set(t)].filter(s=>p.existsSync(s))}function _e(e,o){let n=F(d.join(e,"components.json")),t=un(n,o),s=$e(e).flatMap(g=>[d.join(g,"icon","index.tsx"),d.join(g,"icon","Icon.vue")]).find(g=>p.existsSync(g));if(!s)return{changed:!1,iconLibrary:t};let r=p.readFileSync(s,"utf8"),i=gn(r,t),f=i!==r;f&&p.writeFileSync(s,i);let a=d.join(e,"package.json"),l=F(a);if(l){l.dependencies=l.dependencies||{};let g=!1;for(let c of dn[t])l.dependencies[c]||(l.dependencies[c]="latest",g=!0);g&&N(a,l)}return{changed:f,iconLibrary:t}}function ve(e,o){for(let t of zn){let s=d.join(e,`${o}.${t}`);if(p.existsSync(s))return s}let n=d.join(e,o);if(p.existsSync(n)&&p.statSync(n).isDirectory()){let t=p.readdirSync(n).filter(i=>ke.test(i)),s=t.filter(i=>!/^index\./i.test(i)),r=s.find(i=>i.toLowerCase().startsWith(`${o.toLowerCase()}.`))||s[0]||t.find(i=>/^index\./i.test(i));if(r)return d.join(n,r)}return null}function Te(e,o){let n=$e(e);if(o&&o!=="all"){for(let r of n){let i=ve(r,o);if(i)return[{component:o,inputPath:i}]}return[]}let t=new Set,s=[];for(let r of n)for(let i of p.readdirSync(r,{withFileTypes:!0})){let f,a=null;if(i.isFile()&&ke.test(i.name)&&!/^index\./i.test(i.name)?(f=G(i.name),a=d.join(r,i.name)):i.isDirectory()&&(f=G(i.name),a=ve(r,i.name)),!a||!f)continue;let l=f.toLowerCase();t.has(l)||(t.add(l),s.push({component:f,inputPath:a}))}return s}function Ae(e){let o={},n=[],t=Te(e,"all");for(let{component:s,inputPath:r}of t){let i=B(p.readFileSync(r,"utf8"),s);if(i.skipped){n.push({component:s,reason:i.reason});continue}Object.assign(o,i.config)}return{config:o,skipped:n}}S.name("frontfriend").description("FrontFriend Tailwind CLI - Manage design tokens and cache").version(be);S.command("login").description("Authenticate FrontFriend CLI with an 8-digit device code").option("--api-url <url>","FrontFriend API URL",process.env.FF_API_URL||"https://app.frontfriend.dev").option("--no-open","Do not open the browser automatically").action(async e=>{try{let o=e.apiUrl.replace(/\/$/,""),n=await V(`${o}/api/auth/device/start`,{}),t=n.interval||5,s=Date.now()+(n.expires_in||600)*1e3;for(console.log("\u{1F510} FrontFriend Login"),console.log(`====================
|
|
56
61
|
`),console.log(`Go to ${n.verification_uri} and enter the code:`),console.log(`
|
|
57
62
|
${n.user_code}
|
|
58
|
-
`),e.open!==!1&&
|
|
59
|
-
`);Date.now()<s;){await
|
|
60
|
-
`);let t=await new
|
|
61
|
-
Please add "ff-id" to your frontfriend.config.js file`,"ff-id");let i=e.tag||t.tag,f=e.version||t.version;console.log("\u{1F4CB} Configuration loaded"),console.log(` FF_ID: ${t.ffId}`),console.log(` App Root: ${t.appRoot}`),i&&console.log(` Tag: ${i}`),f&&console.log(` Version: ${f}`),console.log("");let
|
|
62
|
-
`):
|
|
63
|
+
`),e.open!==!1&&An(n.verification_uri)&&console.log("Opened the browser for you."),console.log(`Waiting for approval...
|
|
64
|
+
`);Date.now()<s;){await Tn(t*1e3);let r=await V(`${o}/api/auth/device/poll`,{device_code:n.device_code});if(r.error!=="authorization_pending"){if(r.error==="slow_down"){t=r.interval||t+5;continue}if(r.error)throw new Error(`${r.error}: ${r.error_description||"Authentication failed"}`);if(!r.access_token||!r.refresh_token||!r.device_id)throw new Error("Invalid login response from FrontFriend. Run `frontfriend login` again.");tn({accessToken:r.access_token,refreshToken:r.refresh_token,deviceId:r.device_id,expiresAt:Date.now()+(r.expires_in||900)*1e3,refreshExpiresAt:Date.now()+(r.refresh_expires_in||604800)*1e3,ffApiUrl:o}),console.log("\u2705 Login complete!"),console.log(` Credentials saved to ${on()}`),process.exit(0)}}throw new Error("expired_token: the code has expired, run `frontfriend login` again.")}catch(o){console.error("\u274C Login failed:",o.message),process.exit(1)}});S.command("logout").description("Remove FrontFriend CLI credentials").option("--api-url <url>","FrontFriend API URL",process.env.FF_API_URL||"https://app.frontfriend.dev").action(async e=>{let o=sn(),n=(e.apiUrl||(o==null?void 0:o.ffApiUrl)||"https://app.frontfriend.dev").replace(/\/$/,"");if(o!=null&&o.accessToken&&(o!=null&&o.deviceId))try{await V(`${n}/api/plugin/logout`,{device_id:o.deviceId},o.accessToken)}catch{}let t=rn();console.log(t?"\u2705 Logged out. Credentials removed.":"\u2139\uFE0F No stored credentials found."),process.exit(0)});S.command("init").description("Initialize FrontFriend configuration and fetch from API").option("--force","Force refresh even if cache is valid").option("--verbose","Show detailed output including safelist size and token counts").option("--tag <tag>","Fetch specific tag (e.g., dev, next, latest)").option("--version <version>","Fetch specific version (e.g., v1.0.0)").option("--registry-url <url>","Registry base URL for components.json (overrides FF_REGISTRY_URL)").action(async e=>{var o;try{console.log("\u{1F527} FrontFriend Setup"),console.log(`==================
|
|
65
|
+
`);let t=await new O().load(),s=_n(t.appRoot,{registryUrl:e.registryUrl}),r=s.isShadcnProject?Ae(t.appRoot):{config:{},skipped:[]};if(In(s),!t.ffId)throw s.isShadcnProject&&(Fe(t.appRoot,r.config),console.log("\u2705 Local FrontFriend wiring complete!"),console.log(` Local component config cached (${Object.keys(r.config).length||"default"} component${Object.keys(r.config).length===1?"":"s"}).`),console.log(' Add frontfriend.config.js with "ff-id" later to fetch cloud design tokens.'),process.exit(0)),new j(`ff-id not found in frontfriend.config.js
|
|
66
|
+
Please add "ff-id" to your frontfriend.config.js file`,"ff-id");let i=e.tag||t.tag,f=e.version||t.version;console.log("\u{1F4CB} Configuration loaded"),console.log(` FF_ID: ${t.ffId}`),console.log(` App Root: ${t.appRoot}`),i&&console.log(` Tag: ${i}`),f&&console.log(` Version: ${f}`),console.log("");let a=new A(t.appRoot);!e.force&&a.exists()&&a.isValid()&&(console.log("\u2705 Cache is valid and up to date"),console.log(" Use --force to refresh anyway"),process.exit(0)),console.log("\u{1F50D} Checking cache..."),e.force?console.log(` Force refresh requested
|
|
67
|
+
`):a.exists()?console.log(` Cache expired
|
|
63
68
|
`):console.log(` No cache found
|
|
64
|
-
`),console.log("\u{1F310} Fetching configuration...");let
|
|
69
|
+
`),console.log("\u{1F310} Fetching configuration...");let l=new Se(t.ffId,{baseURL:t["api-url"]||t.apiUrl,authToken:t["auth-token"]||t.authToken});(t["api-url"]||t.apiUrl)&&console.log(` Using API URL: ${t["api-url"]||t.apiUrl}`);let g=new an,c=null;try{c=await l.fetchProcessedTokens({tag:i,version:f,tailwindV4:g.useTailwindV4})}catch(m){console.log(` \u26A0\uFE0F Failed to fetch pre-processed tokens: ${m.message}`)}if(c){if(console.log(" \u2713 Pre-processed tokens fetched from server"),console.log(" \u2713 Skipping local processing"),Object.keys(r.config).length>0&&(c.componentsConfig=H(c.componentsConfig,r.config),console.log(` \u2713 Preserved host component classes for ${Object.keys(r.config).join(", ")}`)),c.versionMetadata){let m=c.versionMetadata;console.log(" \u2139\uFE0F Version Information:"),m.version&&console.log(` Version: ${m.version}`),m.tag&&console.log(` Tag: ${m.tag}`),m.cached!==void 0&&console.log(` From Cache: ${m.cached?"Yes":"No"}`)}if(console.log(""),(!((o=c.tokens)!=null&&o.fontFamily)||Object.keys(c.tokens.fontFamily).length===0)&&(console.log("\u26A0\uFE0F Warning: No font family utilities found"),console.log(" Font classes like font-primary and font-secondary will not be available"),c.globalTokens?console.log(` Global tokens are present - font processor may need to be updated
|
|
65
70
|
`):console.log(` Consider adding font family tokens to your design system
|
|
66
|
-
`)),
|
|
71
|
+
`)),g.useTailwindV4){let m=g.extractClassesFromComponentsConfig(c.componentsConfig),I=[...c.safelist||[],...m||[]];c.safelist=[...new Set(I)].sort(),c.themeCSS||(c.themeCSS=g.generateThemeCSS({variables:c.variables||{},semanticVariables:c.semanticVariables||{},semanticDarkVariables:c.semanticDarkVariables||{},fontFaces:c.fonts||[],keyframes:c.keyframes||{},animations:c.animations||{},custom:c.custom||{}})),(!c.classesContent||Object.keys(r.config).length>0)&&(c.classesContent=g.generateClassesContent(c.safelist))}if(console.log("\u{1F4BE} Saving cache..."),(process.env.FF_VERBOSE==="true"||e.verbose)&&console.log(` Safelist has ${c.safelist?c.safelist.length:0} items`),a.save(c),console.log(` \u2713 Cache saved successfully
|
|
67
72
|
`),console.log("\u2705 Setup complete!"),console.log(" Your FrontFriend configuration has been cached."),console.log(" The Tailwind plugin will now use this cached data."),t.types){console.log(`
|
|
68
|
-
\u{1F524} Generating TypeScript types...`);try{let{generateIconTypes:m}=
|
|
69
|
-
`);let[
|
|
70
|
-
`),console.log("\u2699\uFE0F Processing tokens..."),console.log(" Processing raw token data...");let
|
|
71
|
-
`);let
|
|
72
|
-
`));let
|
|
73
|
+
\u{1F524} Generating TypeScript types...`);try{let{generateIconTypes:m}=M(),I=t.aliases&&t.aliases.types?d.join(t.appRoot,t.aliases.types,"frontfriend.d.ts"):void 0;m({projectRoot:t.appRoot,outputPath:I})}catch(m){console.log(" \u26A0\uFE0F Type generation failed:",m.message),console.log(' Enable type generation in frontfriend.config.js with "types": true')}}process.exit(0)}console.log(` \u2139\uFE0F Pre-processed tokens not available, falling back to local processing
|
|
74
|
+
`);let[u,h,y,C,v,P]=await Promise.all([l.fetchTokens(),l.fetchComponentsConfig(),l.fetchFonts(),l.fetchIcons(),l.fetchVersion(),l.fetchCustomCss()]),b=H(h,r.config);if(console.log(" \u2713 Tokens fetched"),u.global||u.colors||u.semantic||u.semanticDark){let m=[u.global?"global":null,u.colors?"colors":null,u.semantic?"semantic":null,u.semanticDark?"semanticDark":null].filter(Boolean).join(", ");console.log(` (Found: ${m})`)}console.log(" \u2713 Components config fetched"),Object.keys(r.config).length>0&&console.log(` \u2713 Preserved host component classes for ${Object.keys(r.config).join(", ")}`),console.log(" \u2713 Fonts fetched"),console.log(" \u2713 Icons fetched"),console.log(" \u2713 Version fetched"),console.log(` \u2713 Custom CSS fetched
|
|
75
|
+
`),console.log("\u2699\uFE0F Processing tokens..."),console.log(" Processing raw token data...");let w=await g.process({colors:u.colors||u.global,semantic:u.semantic,semanticDark:u.semanticDark,fonts:y,globalTokens:u.global,animations:u.animations,version:v==null?void 0:v.version,ffId:t.ffId,customCss:P});console.log(" \u2713 Colors processed"),console.log(" \u2713 Semantic tokens processed"),w.fontFaces.length>0&&console.log(` \u2713 ${w.fontFaces.length} font faces processed`),Object.keys(w.animations).length>0&&console.log(` \u2713 ${Object.keys(w.animations).length} animations processed`),console.log(`
|
|
76
|
+
`);let Ie=g.extractClassesFromComponentsConfig(b),Ee=[...w.safelist||[],...Ie||[]],Y=[...new Set(Ee)].sort(),K,W;g.useTailwindV4&&(console.log("\u{1F3A8} Generating Tailwind v4 CSS artifacts..."),K=g.generateThemeCSS(w),W=g.generateClassesContent(Y),console.log(" \u2713 theme.css generated"),console.log(` \u2713 classes.css generated for @source scanning
|
|
77
|
+
`));let _={tokens:w.utilities,variables:w.variables,semanticVariables:w.semanticVariables,semanticDarkVariables:w.semanticDarkVariables,fonts:w.fontFaces,icons:C,componentsConfig:b,keyframes:w.keyframes,animations:w.animations,safelist:Y,version:v,metadata:w.metadata,custom:w.custom,themeCSS:K,classesContent:W};console.log("\u{1F4BE} Saving cache..."),(process.env.FF_VERBOSE==="true"||e.verbose)&&(console.log(" Cache data summary:"),console.log(` - Tokens: ${Object.keys(_.tokens||{}).length} utilities`),console.log(` - Variables: ${Object.keys(_.variables||{}).length} CSS variables`),console.log(` - Semantic variables: ${Object.keys(_.semanticVariables||{}).length} semantic variables`),console.log(` - Font faces: ${(_.fonts||[]).length} fonts`),console.log(` - Safelist: ${(_.safelist||[]).length} safelist classes`)),a.save(_),console.log(` \u2713 Cache saved successfully
|
|
78
|
+
`);let Z=_e(t.appRoot,a.getIconLibrary());if(Z.changed&&console.log(` \u2713 Icon library: ${Z.iconLibrary} (adapter + dependency wired)
|
|
73
79
|
`),console.log("\u2705 Setup complete!"),console.log(" Your FrontFriend configuration has been cached."),console.log(" The Tailwind plugin will now use this cached data."),t.types){console.log(`
|
|
74
|
-
\u{1F524} Generating TypeScript types...`);try{let{generateIconTypes:m}=
|
|
75
|
-
`);let o=new
|
|
76
|
-
`),console.log("Package:"),console.log(` Version: ${
|
|
77
|
-
`)
|
|
78
|
-
|
|
79
|
-
`);let
|
|
80
|
-
|
|
80
|
+
\u{1F524} Generating TypeScript types...`);try{let{generateIconTypes:m}=M(),I=t.aliases&&t.aliases.types?d.join(t.appRoot,t.aliases.types,"frontfriend.d.ts"):void 0;m({projectRoot:t.appRoot,outputPath:I})}catch(m){console.log(" \u26A0\uFE0F Type generation failed:",m.message),console.log(' Enable type generation in frontfriend.config.js with "types": true')}}process.exit(0)}catch(n){n instanceof j?console.error("\u274C Configuration Error:",n.message):n instanceof pn?(console.error("\u274C API Error:",n.message),console.error(` Status: ${n.statusCode}`),console.error(` URL: ${n.url}`)):n instanceof z?(console.error("\u274C Cache Error:",n.message),console.error(` Operation: ${n.operation}`)):console.error("\u274C Setup failed:",n.message),process.exit(1)}});S.command("clean").description("Remove cached configuration").action(async()=>{try{console.log(`\u{1F9F9} Cleaning FrontFriend cache...
|
|
81
|
+
`);let o=new O().load(),n=new A(o.appRoot);n.exists()?(n.clear(),console.log("\u2705 Cache cleared successfully")):console.log("\u2139\uFE0F No cache found"),process.exit(0)}catch(e){e instanceof z?(console.error("\u274C Cache Error:",e.message),console.error(` Operation: ${e.operation}`)):console.error("\u274C Clean failed:",e.message),process.exit(1)}});S.command("status").description("Show cache status and configuration").action(async()=>{try{console.log("\u{1F4CA} FrontFriend Status"),console.log(`===================
|
|
82
|
+
`),console.log("Package:"),console.log(` Version: ${be}`),console.log("");let o=await new O().load();console.log("Configuration:"),console.log(` FF_ID: ${o.ffId||"Not set"}`),console.log(` App Root: ${o.appRoot}`),o.tag&&console.log(` Tag: ${o.tag}`),o.version&&console.log(` Version: ${o.version}`),console.log("");let n=new A(o.appRoot),t=n.getCacheDir();if(console.log("Cache:"),console.log(` Directory: ${d.relative(process.cwd(),t)}`),n.exists()){console.log(` Status: ${n.isValid()?"\u2705 Valid":"\u26A0\uFE0F Expired"}`);let s=n.load();if(s&&s.metadata){let r=new Date(s.metadata.timestamp);console.log(` Created: ${r.toLocaleString()}`),console.log(` Format Version: ${s.metadata.version||"Unknown"}`)}s&&s.versionMetadata&&(console.log(" Cached Version Info:"),s.versionMetadata.version&&console.log(` Version: ${s.versionMetadata.version}`),s.versionMetadata.tag&&console.log(` Tag: ${s.versionMetadata.tag}`))}else console.log(" Status: \u274C Not found");process.exit(0)}catch(e){e instanceof j?console.error("\u274C Configuration Error:",e.message):e instanceof z?(console.error("\u274C Cache Error:",e.message),console.error(` Operation: ${e.operation}`)):console.error("\u274C Status check failed:",e.message),process.exit(1)}});S.command("migrate").description("Migrate shadcn components (cva + non-cva) into FrontFriend config, rewriting classes to FF tokens by default").option("--component <name>",'Component to migrate, or "all" to scan the UI dir',"all").option("--input <path>","Path to the shadcn component source").option("--output <path>","Output JSON path for migrated config",Cn).option("--no-push","Do not push migrated config to the configured FrontFriend cloud").option("--keep-shadcn-classes","Keep raw shadcn classes instead of rewriting them to FrontFriend tokens (default: rewrite)").action(async e=>{try{let n=await new O().load(),t=n.appRoot,s=e.input&&e.component==="all"?G(e.input):e.component,r;if(e.input){let c=d.resolve(t,e.input);if(!p.existsSync(c))throw new j(`Component source not found: ${d.relative(t,c)}`);let u=p.readFileSync(c,"utf8");r=B(u,s)}else if(s==="all")r=Ae(t);else{let c=Te(t,s);if(c.length===0)throw new j(`Component source "${s}" not found under components/ui or src/components/ui`,"component");let u=p.readFileSync(c[0].inputPath,"utf8");r=B(u,s)}if(r.skipped===!0||Object.keys(r.config||{}).length===0){let c=r.reason||(Array.isArray(r.skipped)&&r.skipped.length>0?r.skipped.map(u=>`${u.component} (${u.reason})`).join(", "):"no cva-structured components or literal className slots found");console.log(`\u23ED\uFE0F Skipped ${s}: ${c}`),process.exit(0)}e.keepShadcnClasses||(r.config=J(r.config,ln));let i=Fn(t),f="",a="";if(i){let c=fn(p.readFileSync(i,"utf8"));if(f=c.custom,a=c.scaffold,f){let u=d.join(new A(t).getCacheDir(),"migrated-customcss.css");p.mkdirSync(d.dirname(u),{recursive:!0}),p.writeFileSync(u,`${f}
|
|
83
|
+
`)}}let l=d.resolve(t,e.output);N(l,r.config),Fe(t,r.config);let g=!1;e.push&&n.ffId&&(await new Se(n.ffId,{baseURL:n["api-url"]||n.apiUrl,authToken:n["auth-token"]||n.authToken}).pushComponentsConfig(r.config,f||void 0),g=!0,i&&f&&(p.writeFileSync(`${i}.bak`,p.readFileSync(i)),p.writeFileSync(i,a?`${a}
|
|
84
|
+
`:""),console.log(` Centralised host CSS \u2192 DS customCss (backup: ${d.relative(t,i)}.bak)`))),console.log("\u2705 Migration complete!"),console.log(` Component: ${s==="all"?Object.keys(r.config).join(", "):s}`),console.log(` Output: ${d.relative(t,l)}`),console.log(" Local config: cached for the FrontFriend plugin"),r.skipped&&r.skipped.length>0&&console.log(` Skipped: ${r.skipped.map(c=>`${c.component} (${c.reason})`).join(", ")}`),console.log(g?" Cloud config: pushed user override":" Cloud config: not pushed (missing ff-id or --no-push)"),process.exit(0)}catch(o){o instanceof j?console.error("\u274C Migration Error:",o.message):console.error("\u274C Migration failed:",o.message),process.exit(1)}});S.command("download").description("Download components from registry").argument("<components...>",'component names to download (or "all" to download all components)').option("-f, --framework <framework>","Framework to download components for (react/vue)").option("-o, --output <path>","Output directory for components").option("--registry <generation>","Registry generation to use (legacy/v4)").option("--overwrite","Overwrite existing files").action(async(e,o)=>{try{console.log(`\u{1F4E6} Downloading components...
|
|
85
|
+
`);let t=await new O().load();if(!t.ffId)throw new j(`ff-id not found in frontfriend.config.js
|
|
86
|
+
Please add "ff-id" to your frontfriend.config.js file`,"ff-id");let s=new cn({appRoot:t.appRoot,config:t,framework:o.framework,registryGeneration:o.registry,outputPath:o.output,overwrite:o.overwrite}),r=e;if(e.length===1&&e[0].toLowerCase()==="all"){let f=await s.getAllComponents(),a=await s.getCustomComponents();process.env.FF_DEBUG&&console.log(`Debug: Found ${a.length} custom components: ${a.join(", ")}`),f.length===0&&(console.error("\u274C Failed to fetch component list"),process.exit(1));let l=new Set(a),g=f.filter(c=>!l.has(c));r=[...a,...g],console.log("\u{1F4CB} Configuration"),console.log(` Framework: ${s.framework}`),console.log(` Registry: ${s.registryGeneration}`),console.log(` Output: ${s.outputPath}`),console.log(` Components: All ${r.length} components`),process.env.FF_DEBUG&&a.length>0&&console.log(` Debug: ${a.length} custom components will override standard ones`),console.log("")}else console.log("\u{1F4CB} Configuration"),console.log(` Framework: ${s.framework}`),console.log(` Registry: ${s.registryGeneration}`),console.log(` Output: ${s.outputPath}`),console.log(` Components: ${e.join(", ")}
|
|
87
|
+
`);let i=await s.downloadComponents(r);if(i.successful.length>0){console.log(`
|
|
88
|
+
\u2705 Download complete!`),console.log(` Downloaded: ${i.successful.length} components`);let f=new A(t.appRoot).getIconLibrary()||t.iconLibrary,a=_e(t.appRoot,f);a.changed&&console.log(` Icon library: ${a.iconLibrary} (adapter + dependency wired)`)}i.failed.length>0&&(console.log(""),i.failed.forEach(f=>{f.error.includes("not found")?console.log(`\u274C ${f.error}`):console.log(`\u274C Failed to download ${f.component}: ${f.error}`)})),i.successful.length>0&&i.dependencies.length>0&&(console.log(`
|
|
81
89
|
\u{1F4E6} Install dependencies:`),console.log(` npm install ${i.dependencies.join(" ")}`)),i.successful.length===0&&i.failed.length>0&&process.exit(1),process.exit(0)}catch(n){n instanceof j?(console.error("\u274C Configuration Error:",n.message),n.missingKey&&console.error(` Missing key: ${n.missingKey}`)):console.error("\u274C Download failed:",n.message),process.exit(1)}});S.parse(process.argv);process.argv.slice(2).length||(S.outputHelp(),process.exit(0));
|
|
82
90
|
//# sourceMappingURL=cli-temp.js.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var T=(
|
|
2
|
-
`,{mode:384});try{C.chmodSync(k,384)}catch{}}function Se(){return C.existsSync(k)?(C.unlinkSync(k),!0):!1}function te(s,e=60*1e3){return!(s!=null&&s.accessToken)||!s.expiresAt||Date.now()+e>=s.expiresAt}function j(s){let e=new Error(`${s}. Run \`frontfriend login\` to re-authenticate.`);return e.code="FF_AUTH_REFRESH_FAILED",e}function se(s,e,t){return new Promise((o,n)=>{let c=new Pe(s),r=c.protocol==="https:"?Ee:$e,a=JSON.stringify(e||{}),u=r.request({hostname:c.hostname,port:c.port,path:`${c.pathname}${c.search}`,method:"POST",headers:{"content-type":"application/json","content-length":Buffer.byteLength(a),...t?{authorization:`Bearer ${t}`}:{}}},i=>{let d="";i.on("data",l=>{d+=l}),i.on("end",()=>{if(i.statusCode>=300&&i.statusCode<400){let p=i.headers.location?` to ${i.headers.location}`:"",m=new Error(`HTTP ${i.statusCode}: redirected${p}`);m.statusCode=i.statusCode,m.body=d,n(m);return}let l=null;try{l=d?JSON.parse(d):null}catch(p){if(i.statusCode>=400){let m=new Error(`HTTP ${i.statusCode}: ${i.statusMessage||"Non-JSON response"}`);m.statusCode=i.statusCode,m.body=d,n(m);return}n(p);return}if(i.statusCode>=400){let p=new Error((l==null?void 0:l.error_description)||(l==null?void 0:l.error)||`HTTP ${i.statusCode}`);p.statusCode=i.statusCode,p.body=l,n(p);return}o(l)})});u.on("error",n),u.write(a),u.end()})}async function ne(s,e=Q){if(!(s!=null&&s.refreshToken)||!(s!=null&&s.deviceId))throw j("FrontFriend session expired");let t;try{t=await se(`${e}/api/plugin/token`,{grant_type:"refresh_token",refresh_token:s.refreshToken,device_id:s.deviceId})}catch(n){throw j((n==null?void 0:n.message)||"Could not refresh FrontFriend session")}if(!(t!=null&&t.access_token)||!(t!=null&&t.refresh_token))throw j("Could not refresh FrontFriend session");let o={accessToken:t.access_token,refreshToken:t.refresh_token,deviceId:t.device_id||s.deviceId,expiresAt:Date.now()+(t.expires_in||900)*1e3,refreshExpiresAt:Date.now()+(t.refresh_expires_in||604800)*1e3,ffApiUrl:e};return ee(o),o}async function Ae(s={}){if(!s.skipCredentials){let e=Z();if(e!=null&&e.accessToken||e!=null&&e.refreshToken){let t=s.baseURL||e.ffApiUrl||Q;return e.accessToken&&!te(e)?e.accessToken:(await ne(e,t)).accessToken}}return s.envToken?s.envToken:s.legacyToken?(s.silent||console.warn("\u26A0\uFE0F auth-token in frontfriend.config.js is deprecated. Run `frontfriend login` to store credentials outside the repo."),s.legacyToken):null}oe.exports={getCredentialsPath:Re,readCredentials:Z,writeCredentials:ee,deleteCredentials:Se,isExpired:te,postJson:se,refreshCredentials:ne,resolveAuthToken:Ae,createAuthRefreshError:j}});var b=require("https"),L=require("http"),{URL:I}=require("url"),{DEFAULT_API_URL:Ue,LEGACY_API_URL:F,ENV_VARS:N}=E(),{APIError:f}=q(),{LocalTokenReader:De}=z(),{resolveAuthToken:ve}=re(),_="Authentication required. Run `frontfriend login` to re-authenticate.";function ae(s,e,t,o){return t?s.get(new I(e),{headers:{authorization:`Bearer ${t}`}},o):s.get(e,o)}function x(s,e=""){var o;let t=((o=s.headers)==null?void 0:o.location)||"";return s.statusCode===401||s.statusCode===403||s.statusCode>=300&&s.statusCode<400&&t.includes("/sign-in")||String(e).trim().startsWith("/sign-in")}function ie(s,e,t=""){return x(s,t)?new f(_,s.statusCode,e):new f(`HTTP ${s.statusCode}: ${s.statusMessage}`,s.statusCode,e)}var J=class{constructor(e,t={}){this.ffId=e,this.baseURL=t.baseURL||process.env[N.FF_API_URL]||Ue,this.legacyAuthToken=t.authToken||null,this.authToken=null,this.skipCredentials=t.skipCredentials||!1,process.env[N.FF_USE_LOCAL]==="true"&&(console.log(" \u{1F3E0} Using local token reader"),this.localReader=new De(e,t))}async getAuthToken(){return this.authToken=await ve({baseURL:this.baseURL,envToken:process.env[N.FF_AUTH_TOKEN],legacyToken:this.legacyAuthToken,skipCredentials:this.skipCredentials}),this.authToken}async fetchJson(e,t={}){let o=await this.getAuthToken();return new Promise((n,c)=>{let r=e.startsWith("https")?b:L;ae(r,e,o,a=>{let u="";if(a.statusCode>=300){c(ie(a,e));return}a.on("data",i=>{u+=i}),a.on("end",()=>{try{let i=JSON.parse(u);t.returnHeaders?n({data:i,headers:a.headers}):n(i)}catch(i){if(x(a,u)){c(new f(_,a.statusCode,e));return}c(new f(`Invalid JSON response: ${i.message}`,a.statusCode,e))}}),a.on("error",i=>{c(new f(`Response error: ${i.message}`,a.statusCode,e))})}).on("error",a=>{c(new f(`Network error: ${a.message}`,0,e))})})}async fetchRaw(e){let t=await this.getAuthToken();return new Promise((o,n)=>{let c=e.startsWith("https")?b:L;ae(c,e,t,r=>{let a="";if(r.statusCode>=400){n(new f(`HTTP ${r.statusCode}: ${r.statusMessage}`,r.statusCode,e));return}r.on("data",u=>{a+=u}),r.on("end",()=>{o(a)}),r.on("error",u=>{n(new f(`Response error: ${u.message}`,r.statusCode,e))})}).on("error",r=>{n(new f(`Network error: ${r.message}`,0,e))})})}async fetchTokens(){if(this.localReader)return this.localReader.fetchTokens();try{let n=`${this.baseURL}/api/design-systems/${this.ffId}/tokens`,c=await this.fetchJson(n);if(c&&c.tokens){let r=c.tokens;return{global:r["Global Tokens/Default"]||r.global||null,colors:r["Global Colors/Default"]||r.colors||null,semantic:r["Semantic/Light"]||r["semantic/light"]||null,semanticDark:r["Semantic/Dark"]||r["semantic/dark"]||null}}}catch(n){if(n.statusCode===400)throw new f("Design system not synced with Figma. Please sync tokens from Figma before using this design system.",400,`${this.baseURL}/api/design-systems/${this.ffId}/tokens`)}let e=F,t={global:`${e}/${this.ffId}/global-tokens/default.json`,colors:`${e}/${this.ffId}/global-colors/default.json`,semantic:`${e}/${this.ffId}/semantic/light.json`,semanticDark:`${e}/${this.ffId}/semantic/dark.json`},o=await Promise.all([this.fetchJson(t.global).catch(n=>n.statusCode===404?null:Promise.reject(n)),this.fetchJson(t.colors).catch(n=>n.statusCode===404?null:Promise.reject(n)),this.fetchJson(t.semantic).catch(n=>n.statusCode===404?null:Promise.reject(n)),this.fetchJson(t.semanticDark).catch(n=>n.statusCode===404?null:Promise.reject(n))]);return{global:o[0],colors:o[1],semantic:o[2],semanticDark:o[3]}}async fetchProcessedTokens(e={}){if(this.localReader)return this.localReader.fetchProcessedTokens();let t=new I(`${this.baseURL}/api/design-systems/${this.ffId}/processed-tokens`);e.tag&&t.searchParams.append("tag",e.tag),e.version&&t.searchParams.append("version",e.version),e.tailwindV4&&t.searchParams.append("tailwind","v4");let o=t.toString();try{let n=await this.fetchJson(o,{returnHeaders:!0});return n.headers&&(n.data.versionMetadata={version:n.headers["x-frontfriend-version"],tag:n.headers["x-frontfriend-tag"],cached:n.headers["x-frontfriend-cached"]==="true"}),n.data}catch(n){if(n.statusCode===404)return null;throw n.statusCode===400?new f("Design system not synced with Figma. Please sync tokens from Figma before using this design system.",400,o):n}}async sendJson(e,t,o){let n=await this.getAuthToken();if(!n)throw new f(_,401,e);return new Promise((c,r)=>{let a=new I(e),u=e.startsWith("https")?b:L,i=JSON.stringify(o||{}),d=u.request({hostname:a.hostname,port:a.port,path:`${a.pathname}${a.search}`,method:t,headers:{"content-type":"application/json","content-length":Buffer.byteLength(i),...n?{authorization:`Bearer ${n}`}:{}}},l=>{let p="";if(l.statusCode>=300){r(ie(l,e));return}l.on("data",m=>{p+=m}),l.on("end",()=>{if(!p){c(null);return}try{c(JSON.parse(p))}catch(m){if(x(l,p)){r(new f(_,l.statusCode,e));return}r(new f(`Invalid JSON response: ${m.message}`,l.statusCode,e))}})});d.on("error",l=>{r(new f(`Network error: ${l.message}`,0,e))}),d.write(i),d.end()})}async pushComponentsConfig(e){let t=`${this.baseURL}/api/design-systems/${this.ffId}/components-config`;return this.sendJson(t,"PUT",{componentsConfig:e})}async fetchComponentsConfig(){if(this.localReader)return this.localReader.fetchComponentsConfig();let e=`${F}/${this.ffId}/components-config.json`;try{return await this.fetchJson(e)}catch(t){if(t.statusCode===404)return null;throw t}}async fetchFonts(){if(this.localReader)return this.localReader.fetchFonts();let e=`${F}/${this.ffId}/font.json`;try{return await this.fetchJson(e)}catch(t){if(t.statusCode===404)return null;throw t}}async fetchIcons(){if(this.localReader)return this.localReader.fetchIcons();let e=`${F}/${this.ffId}/icons.json`;try{return await this.fetchJson(e)}catch(t){if(t.statusCode===404)return null;throw t}}async fetchVersion(){if(this.localReader)return this.localReader.fetchVersion();let e=`${F}/${this.ffId}/version.json`;try{return await this.fetchJson(e)}catch(t){if(t.statusCode===404)return null;throw t}}async fetchCustomCss(){if(this.localReader)return this.localReader.fetchCustomCss();let e=`${F}/${this.ffId}/custom.css`;try{return await this.fetchRaw(e)}catch(t){if(t.statusCode===404)return null;throw t}}async fetchPlanMetadata(){if(this.localReader)return process.env.FF_DEBUG&&console.log(" \u2192 Using local reader for plan metadata"),this.localReader.fetchPlanMetadata();let e=`${this.baseURL}/api/design-systems/${this.ffId}/processed-tokens`;try{process.env.FF_DEBUG&&console.log(` \u2192 Fetching plan metadata from saas app: ${e}`);let t=await this.fetchJson(e);if(t&&t.metadata){let o={planType:t.metadata.planType||"full",allowedComponents:t.metadata.allowedComponents||null};return process.env.FF_DEBUG&&console.log(` \u2192 Found plan metadata in saas app: ${o.planType}, allowed: ${o.allowedComponents?o.allowedComponents.length+" components":"all"}`),o}}catch(t){if(t.statusCode===404){process.env.FF_DEBUG&&console.log(" \u2192 ff-id not found in saas app, trying legacy server");let o=`${F}/${this.ffId}/metadata`;try{process.env.FF_DEBUG&&console.log(` \u2192 Fetching from legacy server: ${o}`);let n=await this.fetchJson(o),c={planType:n.planType||"full",allowedComponents:n.allowedComponents||null};return process.env.FF_DEBUG&&console.log(` \u2192 Found in legacy server: ${c.planType}, allowed: ${c.allowedComponents?c.allowedComponents.length+" components":"all"}`),c}catch(n){if(n.statusCode===404)return process.env.FF_DEBUG&&console.log(" \u2192 ff-id not found in any server - access denied"),{planType:"denied",allowedComponents:[],error:"Design system not found. Please ensure your ff-id is valid."};throw n}}throw t}}};module.exports={APIClient:J};
|
|
1
|
+
var T=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var E=T((Le,O)=>{var ce="https://app.frontfriend.dev",le="https://registry-legacy.frontfriend.dev",he=".cache/frontfriend",ue={JS:["tokens.js","variables.js","semanticVariables.js","semanticDarkVariables.js","safelist.js","custom.js"],JSON:["fonts.json","icons.json","components-config.json","version.json","metadata.json"]},fe={FF_ID:"FF_ID",FF_API_URL:"FF_API_URL",FF_USE_LOCAL:"FF_USE_LOCAL",FF_AUTH_TOKEN:"FF_AUTH_TOKEN"};O.exports={DEFAULT_API_URL:ce,LEGACY_API_URL:le,CACHE_DIR_NAME:he,CACHE_TTL_DAYS:7,CACHE_TTL_MS:6048e5,CACHE_FILES:ue,ENV_VARS:fe}});var q=T((Ne,M)=>{var $=class extends Error{constructor(e,t,o){super(e),this.name="APIError",this.statusCode=t,this.url=o,this.code=`API_${t}`}},P=class extends Error{constructor(e,t){super(e),this.name="CacheError",this.operation=t,this.code=`CACHE_${t.toUpperCase()}`}},R=class extends Error{constructor(e,t){super(e),this.name="ConfigError",this.field=t,this.code=t?`CONFIG_${String(t).toUpperCase()}`:"CONFIG_ERROR"}},S=class extends Error{constructor(e,t){super(e),this.name="ProcessingError",this.token=t,this.code="PROCESSING_ERROR"}};M.exports={APIError:$,CacheError:P,ConfigError:R,ProcessingError:S}});var A=T((Ie,H)=>{var y=require("fs");function de(n){try{let e=y.readFileSync(n,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}function pe(n){try{return y.readFileSync(n,"utf8").replace(/^\uFEFF/,"")}catch(e){if(e.code==="ENOENT")return null;throw e}}function me(n,e,t=2){let o=JSON.stringify(e,null,t);y.writeFileSync(n,o,"utf8")}function ye(n,e){y.writeFileSync(n,e,"utf8")}function ge(n,e){if(e==null||typeof e=="object"&&Object.keys(e).length===0||Array.isArray(e)&&e.length===0){let o=`module.exports = ${Array.isArray(e)?"[]":"{}"};`;y.writeFileSync(n,o,"utf8")}else{let t=`module.exports = ${JSON.stringify(e,null,2)};`;y.writeFileSync(n,t,"utf8")}}function we(n){return y.existsSync(n)}function Ce(n){y.mkdirSync(n,{recursive:!0})}function ke(n){y.rmSync(n,{recursive:!0,force:!0})}H.exports={readJsonFileSafe:de,readFileSafe:pe,writeJsonFile:me,writeTextFile:ye,writeModuleExportsFile:ge,fileExists:we,ensureDirectoryExists:Ce,removeDirectory:ke}});var B=T((xe,G)=>{var g=require("path"),{fileExists:U}=A();function Fe(n,e=process.cwd()){let t=e;for(;t!==g.parse(t).root;){let o=g.join(t,n);if(U(o))return o;t=g.dirname(t)}return null}function Te(n,e=process.cwd(),t=null){let o=[],s=e,c=10;for(let r=0;r<c;r++){o.push(g.join(s,n)),r<3&&o.push(g.join(s,"../".repeat(r+1)+n));let a=g.dirname(s);if(a===s)break;s=a}o.push(g.join(__dirname,"../../../",n));for(let r of o)if(U(r)&&(!t||t(r)))return r;return null}function je(n,e=process.cwd()){let t=n.map(o=>g.isAbsolute(o)?o:g.join(e,o));for(let o of t)if(U(o))return o;return null}G.exports={findFileUpward:Fe,findDirectoryUpward:Te,findDirectoryWithPaths:je}});var z=T((Je,Y)=>{var h=require("path"),{findDirectoryUpward:V}=B(),{readJsonFileSafe:w,readFileSafe:W,fileExists:D}=A(),v=class{constructor(e,t={}){if(this.ffId=e,this.tokensBasePath=t.tokensBasePath||this.findTokensPath(),this.folderMap=this.loadFolderMap(),this.projectFolder=this.folderMap[e],!this.projectFolder)throw new Error(`No folder mapping found for ff-id: ${e}`);this.projectPath=h.join(this.tokensBasePath,this.projectFolder)}findTokensPath(){let e=V("apps/tokens",process.cwd(),t=>D(h.join(t,"folderMap.json")));if(e||(e=V("tokens",process.cwd(),t=>D(h.join(t,"folderMap.json")))),!e)throw new Error("Could not find tokens directory with folderMap.json");return e}loadFolderMap(){let e=h.join(this.tokensBasePath,"folderMap.json"),t=w(e);if(!t)throw new Error("Failed to load folderMap.json: File not found");return t}async fetchTokens(){let e=h.join(this.projectPath,"figma"),t={global:[h.join(e,"Global Tokens","Default.json"),h.join(e,"global.json")],colors:[h.join(e,"Global Colors","Default.json"),h.join(e,"Global Colors","Light.json")],semantic:[h.join(e,"Semantic","Light.json"),h.join(e,"Semantic","Default.json")],semanticDark:[h.join(e,"Semantic","Dark.json")]},o={};for(let[s,c]of Object.entries(t)){for(let r of c){let a=w(r);if(a!==null){o[s]=a;break}}o[s]||(o[s]=null)}return o}async fetchProcessedTokens(){let e=h.join(this.projectPath,"cache");if(!D(e))return null;let t=r=>{if(r===null)return null;let a={},u={exports:a};return new Function("module","exports",r)(u,a),u.exports},o={tokens:{fileName:"hashedTokens.js",type:"module"},variables:{fileName:"hashedVariables.js",type:"module"},semanticVariables:{fileName:"hashedSemanticVariables.js",type:"module"},semanticDarkVariables:{fileName:"hashedSemanticDarkVariables.js",type:"module"},safelist:{fileName:"safelist.js",type:"module"},custom:{fileName:"custom.js",type:"module"},fonts:{fileName:"fonts.json",type:"json"},icons:{fileName:"icons.json",type:"json"},componentsConfig:{fileName:"encoded-config.json",type:"json"},version:{fileName:"version.json",type:"json"}},s={};for(let[r,{fileName:a,type:u}]of Object.entries(o)){let i=h.join(e,a),d=u==="module"?t(W(i)):w(i);d!==null&&(s[r]=d)}return Object.values(s).some(r=>r!==null)?s:null}async fetchComponentsConfig(){return w(h.join(this.projectPath,"components-config.json"))}async fetchFonts(){return w(h.join(this.projectPath,"font.json"))}async fetchIcons(){return w(h.join(this.projectPath,"icons.json"))}async fetchVersion(){return w(h.join(this.projectPath,"version.json"))}async fetchCustomCss(){return W(h.join(this.projectPath,"custom.css"))}async fetchPlanMetadata(){return w(h.join(this.projectPath,"metadata.json"))||{planType:"full",allowedComponents:null}}fetchJson(){throw new Error("fetchJson is not implemented in LocalTokenReader. Use specific fetch methods.")}fetchRaw(){throw new Error("fetchRaw is not implemented in LocalTokenReader. Use specific fetch methods.")}};Y.exports={LocalTokenReader:v}});var re=T((Oe,oe)=>{var C=require("fs"),K=require("path"),_e=require("os"),Ee=require("https"),$e=require("http"),{URL:Pe}=require("url"),{DEFAULT_API_URL:Q}=E(),X=K.join(_e.homedir(),".frontfriend"),k=K.join(X,"credentials");function Re(){return k}function Z(){try{return C.existsSync(k)?JSON.parse(C.readFileSync(k,"utf8")):null}catch{return null}}function ee(n){C.mkdirSync(X,{recursive:!0,mode:448}),C.writeFileSync(k,`${JSON.stringify(n,null,2)}
|
|
2
|
+
`,{mode:384});try{C.chmodSync(k,384)}catch{}}function Se(){return C.existsSync(k)?(C.unlinkSync(k),!0):!1}function te(n,e=60*1e3){return!(n!=null&&n.accessToken)||!n.expiresAt||Date.now()+e>=n.expiresAt}function j(n){let e=new Error(`${n}. Run \`frontfriend login\` to re-authenticate.`);return e.code="FF_AUTH_REFRESH_FAILED",e}function ne(n,e,t){return new Promise((o,s)=>{let c=new Pe(n),r=c.protocol==="https:"?Ee:$e,a=JSON.stringify(e||{}),u=r.request({hostname:c.hostname,port:c.port,path:`${c.pathname}${c.search}`,method:"POST",headers:{"content-type":"application/json","content-length":Buffer.byteLength(a),...t?{authorization:`Bearer ${t}`}:{}}},i=>{let d="";i.on("data",l=>{d+=l}),i.on("end",()=>{if(i.statusCode>=300&&i.statusCode<400){let p=i.headers.location?` to ${i.headers.location}`:"",m=new Error(`HTTP ${i.statusCode}: redirected${p}`);m.statusCode=i.statusCode,m.body=d,s(m);return}let l=null;try{l=d?JSON.parse(d):null}catch(p){if(i.statusCode>=400){let m=new Error(`HTTP ${i.statusCode}: ${i.statusMessage||"Non-JSON response"}`);m.statusCode=i.statusCode,m.body=d,s(m);return}s(p);return}if(i.statusCode>=400){let p=new Error((l==null?void 0:l.error_description)||(l==null?void 0:l.error)||`HTTP ${i.statusCode}`);p.statusCode=i.statusCode,p.body=l,s(p);return}o(l)})});u.on("error",s),u.write(a),u.end()})}async function se(n,e=Q){if(!(n!=null&&n.refreshToken)||!(n!=null&&n.deviceId))throw j("FrontFriend session expired");let t;try{t=await ne(`${e}/api/plugin/token`,{grant_type:"refresh_token",refresh_token:n.refreshToken,device_id:n.deviceId})}catch(s){throw j((s==null?void 0:s.message)||"Could not refresh FrontFriend session")}if(!(t!=null&&t.access_token)||!(t!=null&&t.refresh_token))throw j("Could not refresh FrontFriend session");let o={accessToken:t.access_token,refreshToken:t.refresh_token,deviceId:t.device_id||n.deviceId,expiresAt:Date.now()+(t.expires_in||900)*1e3,refreshExpiresAt:Date.now()+(t.refresh_expires_in||604800)*1e3,ffApiUrl:e};return ee(o),o}async function Ae(n={}){if(!n.skipCredentials){let e=Z();if(e!=null&&e.accessToken||e!=null&&e.refreshToken){let t=n.baseURL||e.ffApiUrl||Q;return e.accessToken&&!te(e)?e.accessToken:(await se(e,t)).accessToken}}return n.envToken?n.envToken:n.legacyToken?(n.silent||console.warn("\u26A0\uFE0F auth-token in frontfriend.config.js is deprecated. Run `frontfriend login` to store credentials outside the repo."),n.legacyToken):null}oe.exports={getCredentialsPath:Re,readCredentials:Z,writeCredentials:ee,deleteCredentials:Se,isExpired:te,postJson:ne,refreshCredentials:se,resolveAuthToken:Ae,createAuthRefreshError:j}});var b=require("https"),L=require("http"),{URL:I}=require("url"),{DEFAULT_API_URL:Ue,LEGACY_API_URL:F,ENV_VARS:N}=E(),{APIError:f}=q(),{LocalTokenReader:De}=z(),{resolveAuthToken:ve}=re(),_="Authentication required. Run `frontfriend login` to re-authenticate.";function ae(n,e,t,o){return t?n.get(new I(e),{headers:{authorization:`Bearer ${t}`}},o):n.get(e,o)}function x(n,e=""){var o;let t=((o=n.headers)==null?void 0:o.location)||"";return n.statusCode===401||n.statusCode===403||n.statusCode>=300&&n.statusCode<400&&t.includes("/sign-in")||String(e).trim().startsWith("/sign-in")}function ie(n,e,t=""){return x(n,t)?new f(_,n.statusCode,e):new f(`HTTP ${n.statusCode}: ${n.statusMessage}`,n.statusCode,e)}var J=class{constructor(e,t={}){this.ffId=e,this.baseURL=t.baseURL||process.env[N.FF_API_URL]||Ue,this.legacyAuthToken=t.authToken||null,this.authToken=null,this.skipCredentials=t.skipCredentials||!1,process.env[N.FF_USE_LOCAL]==="true"&&(console.log(" \u{1F3E0} Using local token reader"),this.localReader=new De(e,t))}async getAuthToken(){return this.authToken=await ve({baseURL:this.baseURL,envToken:process.env[N.FF_AUTH_TOKEN],legacyToken:this.legacyAuthToken,skipCredentials:this.skipCredentials}),this.authToken}async fetchJson(e,t={}){let o=await this.getAuthToken();return new Promise((s,c)=>{let r=e.startsWith("https")?b:L;ae(r,e,o,a=>{let u="";if(a.statusCode>=300){c(ie(a,e));return}a.on("data",i=>{u+=i}),a.on("end",()=>{try{let i=JSON.parse(u);t.returnHeaders?s({data:i,headers:a.headers}):s(i)}catch(i){if(x(a,u)){c(new f(_,a.statusCode,e));return}c(new f(`Invalid JSON response: ${i.message}`,a.statusCode,e))}}),a.on("error",i=>{c(new f(`Response error: ${i.message}`,a.statusCode,e))})}).on("error",a=>{c(new f(`Network error: ${a.message}`,0,e))})})}async fetchRaw(e){let t=await this.getAuthToken();return new Promise((o,s)=>{let c=e.startsWith("https")?b:L;ae(c,e,t,r=>{let a="";if(r.statusCode>=400){s(new f(`HTTP ${r.statusCode}: ${r.statusMessage}`,r.statusCode,e));return}r.on("data",u=>{a+=u}),r.on("end",()=>{o(a)}),r.on("error",u=>{s(new f(`Response error: ${u.message}`,r.statusCode,e))})}).on("error",r=>{s(new f(`Network error: ${r.message}`,0,e))})})}async fetchTokens(){if(this.localReader)return this.localReader.fetchTokens();try{let s=`${this.baseURL}/api/design-systems/${this.ffId}/tokens`,c=await this.fetchJson(s);if(c&&c.tokens){let r=c.tokens;return{global:r["Global Tokens/Default"]||r.global||null,colors:r["Global Colors/Default"]||r.colors||null,semantic:r["Semantic/Light"]||r["semantic/light"]||null,semanticDark:r["Semantic/Dark"]||r["semantic/dark"]||null}}}catch(s){if(s.statusCode===400)throw new f("Design system not synced with Figma. Please sync tokens from Figma before using this design system.",400,`${this.baseURL}/api/design-systems/${this.ffId}/tokens`)}let e=F,t={global:`${e}/${this.ffId}/global-tokens/default.json`,colors:`${e}/${this.ffId}/global-colors/default.json`,semantic:`${e}/${this.ffId}/semantic/light.json`,semanticDark:`${e}/${this.ffId}/semantic/dark.json`},o=await Promise.all([this.fetchJson(t.global).catch(s=>s.statusCode===404?null:Promise.reject(s)),this.fetchJson(t.colors).catch(s=>s.statusCode===404?null:Promise.reject(s)),this.fetchJson(t.semantic).catch(s=>s.statusCode===404?null:Promise.reject(s)),this.fetchJson(t.semanticDark).catch(s=>s.statusCode===404?null:Promise.reject(s))]);return{global:o[0],colors:o[1],semantic:o[2],semanticDark:o[3]}}async fetchProcessedTokens(e={}){if(this.localReader)return this.localReader.fetchProcessedTokens();let t=new I(`${this.baseURL}/api/design-systems/${this.ffId}/processed-tokens`);e.tag&&t.searchParams.append("tag",e.tag),e.version&&t.searchParams.append("version",e.version),e.tailwindV4&&t.searchParams.append("tailwind","v4");let o=t.toString();try{let s=await this.fetchJson(o,{returnHeaders:!0});return s.headers&&(s.data.versionMetadata={version:s.headers["x-frontfriend-version"],tag:s.headers["x-frontfriend-tag"],cached:s.headers["x-frontfriend-cached"]==="true"}),s.data}catch(s){if(s.statusCode===404)return null;throw s.statusCode===400?new f("Design system not synced with Figma. Please sync tokens from Figma before using this design system.",400,o):s}}async sendJson(e,t,o){let s=await this.getAuthToken();if(!s)throw new f(_,401,e);return new Promise((c,r)=>{let a=new I(e),u=e.startsWith("https")?b:L,i=JSON.stringify(o||{}),d=u.request({hostname:a.hostname,port:a.port,path:`${a.pathname}${a.search}`,method:t,headers:{"content-type":"application/json","content-length":Buffer.byteLength(i),...s?{authorization:`Bearer ${s}`}:{}}},l=>{let p="";if(l.statusCode>=300){r(ie(l,e));return}l.on("data",m=>{p+=m}),l.on("end",()=>{if(!p){c(null);return}try{c(JSON.parse(p))}catch(m){if(x(l,p)){r(new f(_,l.statusCode,e));return}r(new f(`Invalid JSON response: ${m.message}`,l.statusCode,e))}})});d.on("error",l=>{r(new f(`Network error: ${l.message}`,0,e))}),d.write(i),d.end()})}async pushComponentsConfig(e,t){let o=`${this.baseURL}/api/design-systems/${this.ffId}/components-config`,s={componentsConfig:e};return typeof t=="string"&&t.length>0&&(s.customCss=t),this.sendJson(o,"PUT",s)}async fetchComponentsConfig(){if(this.localReader)return this.localReader.fetchComponentsConfig();let e=`${F}/${this.ffId}/components-config.json`;try{return await this.fetchJson(e)}catch(t){if(t.statusCode===404)return null;throw t}}async fetchFonts(){if(this.localReader)return this.localReader.fetchFonts();let e=`${F}/${this.ffId}/font.json`;try{return await this.fetchJson(e)}catch(t){if(t.statusCode===404)return null;throw t}}async fetchIcons(){if(this.localReader)return this.localReader.fetchIcons();let e=`${F}/${this.ffId}/icons.json`;try{return await this.fetchJson(e)}catch(t){if(t.statusCode===404)return null;throw t}}async fetchVersion(){if(this.localReader)return this.localReader.fetchVersion();let e=`${F}/${this.ffId}/version.json`;try{return await this.fetchJson(e)}catch(t){if(t.statusCode===404)return null;throw t}}async fetchCustomCss(){if(this.localReader)return this.localReader.fetchCustomCss();let e=`${F}/${this.ffId}/custom.css`;try{return await this.fetchRaw(e)}catch(t){if(t.statusCode===404)return null;throw t}}async fetchPlanMetadata(){if(this.localReader)return process.env.FF_DEBUG&&console.log(" \u2192 Using local reader for plan metadata"),this.localReader.fetchPlanMetadata();let e=`${this.baseURL}/api/design-systems/${this.ffId}/processed-tokens`;try{process.env.FF_DEBUG&&console.log(` \u2192 Fetching plan metadata from saas app: ${e}`);let t=await this.fetchJson(e);if(t&&t.metadata){let o={planType:t.metadata.planType||"full",allowedComponents:t.metadata.allowedComponents||null};return process.env.FF_DEBUG&&console.log(` \u2192 Found plan metadata in saas app: ${o.planType}, allowed: ${o.allowedComponents?o.allowedComponents.length+" components":"all"}`),o}}catch(t){if(t.statusCode===404){process.env.FF_DEBUG&&console.log(" \u2192 ff-id not found in saas app, trying legacy server");let o=`${F}/${this.ffId}/metadata`;try{process.env.FF_DEBUG&&console.log(` \u2192 Fetching from legacy server: ${o}`);let s=await this.fetchJson(o),c={planType:s.planType||"full",allowedComponents:s.allowedComponents||null};return process.env.FF_DEBUG&&console.log(` \u2192 Found in legacy server: ${c.planType}, allowed: ${c.allowedComponents?c.allowedComponents.length+" components":"all"}`),c}catch(s){if(s.statusCode===404)return process.env.FF_DEBUG&&console.log(" \u2192 ff-id not found in any server - access denied"),{planType:"denied",allowedComponents:[],error:"Design system not found. Please ensure your ff-id is valid."};throw s}}throw t}}};module.exports={APIClient:J};
|
|
3
3
|
//# sourceMappingURL=api-client.js.map
|