aem-eds-kit 0.4.26 → 0.4.30

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/bin/eds.js CHANGED
@@ -1,16 +1,16 @@
1
1
  #!/usr/bin/env node
2
- var _a=Object.defineProperty;var w=(e,t)=>()=>(e&&(t=e(e=0)),t);var N=(e,t)=>{for(var n in t)_a(e,n,{get:t[n],enumerable:!0})};import np from"path";import{fileURLToPath as ip}from"url";var m=w(()=>{"use strict"});import F from"chalk";function vt(e){return J[e]}function Io(e){return e.replace(Ua,"").length}function Xe(e,t){let n=t-Io(e);return n>0?e+" ".repeat(n):e}function Ba(){return F.bgHex("#ff5a36").hex("#0d0d0c").bold(" >_ ")}function Mo(){return`${Ba()} ${F.bold("aem-eds-kit")}`}function Ga(){return Array.from({length:Ha},()=>_.accent("\u25CF")).join(" ")}function za(e,t=""){return t?`${Mo()} ${e} ${F.dim(t)}`:`${Mo()} ${e}`}function No(e){let t=e.replace("#","");return[Number.parseInt(t.slice(0,2),16),Number.parseInt(t.slice(2,4),16),Number.parseInt(t.slice(4,6),16)]}function Ja(e,t,n){let[o,r,a]=No(e),[s,d,l]=No(t),c=Math.round(o+(s-o)*n),u=Math.round(r+(d-r)*n),p=Math.round(a+(l-a)*n);return`#${[c,u,p].map(f=>f.toString(16).padStart(2,"0")).join("")}`}function Wa(e,t,n){let o=[...e],r=Math.max(n-1,1);return o.map((a,s)=>{if(a===" ")return a;let d=s/r*(t.length-1),l=Math.min(Math.floor(d),t.length-2);return F.hex(Ja(t[l],t[l+1],d-l))(a)}).join("")}function Ka(){let e=O(_o);return _o.map(t=>` ${Wa(t,qa,e)}`).join(`
3
- `)}function P(e="AEM Edge Delivery Services"){return`
4
- ${Ka()}
5
-
6
- ${za(Ga(),e)}
7
- `}function j(e,t){let n=_.red("\u258A"),o=t?` ${F.dim(t)}`:"";return`
8
- ${n} ${F.bold(e)}${o}
9
- `}function D(e,t,n,o=0){let r=o?Xe(t,o):t,a=n?` ${F.dim(n)}`:"";return` ${J[e]} ${r}${a}`}function $(e,t,n=0){let o=n?Xe(e,n):e,r=t?` ${F.dim(t)}`:"";return` ${_.accent("\u2714")} ${o}${r}`}function O(e){return e.reduce((t,n)=>Math.max(t,Io(n)),0)}function L(e,t=_.red){let n=O(e),o=t(`\u256D${"\u2500".repeat(n+2)}\u256E`),r=t(`\u2570${"\u2500".repeat(n+2)}\u256F`),a=e.map(s=>`${t("\u2502")} ${Xe(s,n)} ${t("\u2502")}`).join(`
2
+ var hs=Object.defineProperty;var v=(e,t)=>()=>(e&&(t=e(e=0)),t);var L=(e,t)=>{for(var n in t)hs(e,n,{get:t[n],enumerable:!0})};import Wp from"path";import{fileURLToPath as qp}from"url";var f=v(()=>{"use strict"});import D from"chalk";function Tt(e){return q[e]}function ei(e){return e.replace(bs,"").length}function ot(e,t){let n=t-ei(e);return n>0?e+" ".repeat(n):e}function ys(){return D.bgHex("#ff5a36").hex("#0d0d0c").bold(" >_ ")}function Yo(){return`${ys()} ${D.bold("aem-eds-kit")}`}function ks(){return Array.from({length:vs},()=>_.accent("\u25CF")).join(" ")}function xs(e,t=""){return t?`${Yo()} ${e} ${D.dim(t)}`:`${Yo()} ${e}`}function Qo(e){let t=e.replace("#","");return[Number.parseInt(t.slice(0,2),16),Number.parseInt(t.slice(2,4),16),Number.parseInt(t.slice(4,6),16)]}function $s(e,t,n){let[o,i,a]=Qo(e),[s,d,l]=Qo(t),c=Math.round(o+(s-o)*n),p=Math.round(i+(d-i)*n),m=Math.round(a+(l-a)*n);return`#${[c,p,m].map(u=>u.toString(16).padStart(2,"0")).join("")}`}function Ss(e,t,n){let o=[...e],i=Math.max(n-1,1);return o.map((a,s)=>{if(a===" ")return a;let d=s/i*(t.length-1),l=Math.min(Math.floor(d),t.length-2);return D.hex($s(t[l],t[l+1],d-l))(a)}).join("")}function Ps(){let e=M(Zo);return Zo.map(t=>` ${Ss(t,js,e)}`).join(`
3
+ `)}function E(e="AEM Edge Delivery Services"){return`
4
+ ${Ps()}
5
+
6
+ ${xs(ks(),e)}
7
+ `}function S(e,t){let n=_.red("\u258A"),o=t?` ${D.dim(t)}`:"";return`
8
+ ${n} ${D.bold(e)}${o}
9
+ `}function A(e,t,n,o=0){let i=o?ot(t,o):t,a=n?` ${D.dim(n)}`:"";return` ${q[e]} ${i}${a}`}function j(e,t,n=0){let o=n?ot(e,n):e,i=t?` ${D.dim(t)}`:"";return` ${_.accent("\u2714")} ${o}${i}`}function M(e){return e.reduce((t,n)=>Math.max(t,ei(n)),0)}function O(e,t=_.red){let n=M(e),o=t(`\u256D${"\u2500".repeat(n+2)}\u256E`),i=t(`\u2570${"\u2500".repeat(n+2)}\u256F`),a=e.map(s=>`${t("\u2502")} ${ot(s,n)} ${t("\u2502")}`).join(`
10
10
  `);return`${o}
11
11
  ${a}
12
- ${r}`}function de(e){let t=[];return e.pass&&t.push(`${J.pass} ${e.pass} passed`),e.warn&&t.push(`${J.warn} ${e.warn} ${Xa(e.warn,"warning")}`),e.fail&&t.push(`${J.fail} ${e.fail} failed`),e.info&&t.push(`${J.info} ${e.info} info`),t.join(F.dim(" "))}function Xa(e,t){return e===1?t:`${t}s`}var _,J,Ua,Ha,Uo,_o,qa,I=w(()=>{"use strict";m();_={red:F.hex("#FA0F00"),ember:F.hex("#FF4B1F"),orange:F.hex("#FF7B00"),blue:F.hex("#2680EB"),accent:F.hex("#ff5a36"),dotOrange:F.hex("#F24E1E"),dotPurple:F.hex("#A259FF"),dotBlue:F.hex("#1ABCFE"),dotGreen:F.hex("#0ACF83"),dotPink:F.hex("#FF7262"),ok:F.hex("#2D9D78"),warn:F.hex("#E68619"),err:F.hex("#D7373F"),info:F.hex("#2680EB")},J={pass:_.ok("\u2713"),warn:_.warn("\u26A0"),fail:_.err("\u2717"),info:_.info("\u2139"),bullet:F.dim("\u2022"),arrow:F.dim("\u21B3"),figma:_.dotPurple("\u25C6")};Ua=/\[[0-9;]*m/g;Ha=5;Uo={prefix:"",style:{highlight:e=>F.hex("#ff5a36").bold(e)}};_o=["\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588","\u2588 \u2588 \u2588 \u2588 ","\u2588\u2588\u2588\u2588 \u2588 \u2588 \u2588\u2588\u2588\u2588\u2588","\u2588 \u2588 \u2588 \u2588","\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588"],qa=["#ff3b1e","#ff5a36","#ff7d52"]});import kt from"chalk";function Va(){let e=process.env.EDS_LOG_LEVEL?.toLowerCase();return e&&e in nn?e:"info"}function we(e){return Ho?e==="error":nn[e]>=nn[Bo]}var nn,Bo,Ho,xt,i,R=w(()=>{"use strict";m();I();nn={debug:0,info:1,warn:2,error:3,silent:4};Bo=Va(),Ho=!1,xt=!1;i={setLevel(e){Bo=e},setQuiet(e){Ho=e},debug(...e){we("debug")&&console.error(kt.gray("[debug]"),...e)},info(...e){we("info")&&console.error(...e)},logoOnce(e){xt||(xt=!0,we("info")&&console.error(e))},async logoOnceAnimated(e){xt||(xt=!0,we("info")&&console.error(P(e)))},success(...e){we("info")&&console.error(kt.green("\u2713"),...e)},warn(...e){we("warn")&&console.error(kt.yellow("\u26A0"),...e)},error(...e){we("error")&&console.error(kt.red("\u2717"),...e)}}});function Le(e){return{Authorization:`Bearer ${e}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"aem-eds-kit","Content-Type":"application/json"}}function Ya(e){return`${Fe}/repos/${e}/generate`}async function $t(e){let t=await fetch(`${Fe}/user`,{headers:Le(e)});if(!t.ok)throw new Error(`GitHub auth failed: ${t.status}`);return(await t.json()).login}async function Go(e,t,n){let o=await fetch(`${Fe}/repos/${t}/${n}`,{headers:Le(e)});if(o.status===404)return!1;if(o.ok)return!0;throw new Error(`existence check failed: ${o.status} ${await o.text()}`)}async function zo(e,t,n){let o=await fetch(Ya(t),{method:"POST",headers:Le(e),body:JSON.stringify({owner:n.owner,name:n.name,private:!!n.private,include_all_branches:!1})});if(!o.ok)throw new Error(`create failed: ${o.status} ${await o.text()}`);let r=await o.json();return{fullName:r.full_name,htmlUrl:r.html_url,cloneUrl:r.clone_url}}async function Jo(e,t,n,o){await fetch(`${Fe}/repos/${t}/${n}/topics`,{method:"PUT",headers:Le(e),body:JSON.stringify({names:o})})}async function Wo(e,t,n){let o=await fetch(`${Fe}/repos/${t}/${n}`,{method:"DELETE",headers:Le(e)});if(!o.ok&&o.status!==204)throw new Error(`delete failed: ${o.status} ${await o.text()}`)}async function qo(e,t,n){let o=encodeURIComponent(`user:${t} topic:${n} fork:true`),r=await fetch(`${Fe}/search/repositories?q=${o}&per_page=100`,{headers:Le(e)});if(!r.ok)throw new Error(`search failed: ${r.status}`);return(await r.json()).items.map(s=>s.full_name)}var Fe,Ko=w(()=>{"use strict";m();Fe="https://api.github.com"});import{existsSync as Xo}from"fs";import{mkdir as Qa,readFile as Za,rm as es,writeFile as ts}from"fs/promises";import ns from"os";import Vo from"path";async function Qo(){let e=process.env.GITHUB_TOKEN||process.env.GH_TOKEN;if(e)return e;if(Xo(Ve))try{return JSON.parse(await Za(Ve,"utf-8")).token??null}catch{return null}return null}async function on(e){await Qa(Yo,{recursive:!0,mode:448}),await ts(Ve,`${JSON.stringify({token:e},null,2)}
13
- `,{mode:384})}async function Zo(){Xo(Ve)&&await es(Ve)}async function ei(e){let t=await fetch("https://github.com/login/device/code",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({client_id:St,scope:e.join(" ")})});if(!t.ok)throw new Error(`device code request failed: ${t.status}`);return await t.json()}async function ti(e,t,n){let o=Math.max(t,1),r=Date.now()+n*1e3;for(;Date.now()<r;){await new Promise(d=>setTimeout(d,o*1e3));let s=await(await fetch("https://github.com/login/oauth/access_token",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({client_id:St,device_code:e,grant_type:"urn:ietf:params:oauth:grant-type:device_code"})})).json();if(s.access_token)return s.access_token;if(s.error==="slow_down")o+=5;else if(s.error!=="authorization_pending")throw new Error(s.error??"device flow failed")}throw new Error("device flow timed out")}var Yo,Ve,St,ni=w(()=>{"use strict";m();Yo=Vo.join(ns.homedir(),".eds"),Ve=Vo.join(Yo,"github.json"),St=process.env.EDS_GITHUB_CLIENT_ID??""});function rn(e,t,n="main"){return`https://${n}--${t}--${e}.aem.page/`}function an(){return"https://github.com/apps/aem-code-sync/installations/new"}function oi(e,t){return["repo","create",e,"--template",t.template,t.private?"--private":"--public",...t.clone?["--clone"]:[]]}var Oe,Ye,ii=w(()=>{"use strict";m();Oe="eds-sandbox",Ye={document:"adobe/aem-boilerplate",ue:"adobe/aem-boilerplate-xwalk"}});var U={};N(U,{checkbox:()=>ds,confirm:()=>ls,input:()=>cs,select:()=>ss});import{checkbox as os,confirm as is,input as rs,select as as}from"@inquirer/prompts";function jt(e){let t={...Uo,...e.theme??{}};return{...e,theme:t}}var ss,cs,ls,ds,B=w(()=>{"use strict";m();I();ss=(e,t)=>as(jt(e),t),cs=(e,t)=>rs(jt(e),t),ls=(e,t)=>is(jt(e),t),ds=(e,t)=>os(jt(e),t)});import{z as A}from"zod";var Ep,sn,ri,Pp,ye,Me=w(()=>{"use strict";m();Ep=A.object({fileKey:A.string().min(1),nodeId:A.string().optional(),fileName:A.string().optional()}),sn=A.object({agent:A.enum(["claude","cursor","codex"]).optional(),model:A.string().optional(),figma:A.object({mcpEndpoint:A.string().url().optional(),token:A.string().optional()}).optional(),admin:A.object({org:A.string().optional(),site:A.string().optional(),ref:A.string().default("main")}).optional()}),ri=A.object({root:A.string(),hasFstab:A.boolean(),hasBlocks:A.boolean(),hasHeadHtml:A.boolean()}),Pp=A.object({figmaFileKey:A.string(),figmaNodeId:A.string().optional(),lastSyncedAt:A.string().datetime(),promptVersion:A.string(),agentUsed:A.string().optional(),breakpoints:A.array(A.object({width:A.number(),label:A.string().optional(),source:A.enum(["figma","default"]).optional()})).optional()}),ye=/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/});import{existsSync as Qe}from"fs";import pe from"path";function E(e=process.cwd()){let t=pe.resolve(e),{root:n}=pe.parse(t);for(;t!==n;){if(ai.some(o=>Qe(pe.join(t,o))))return t;t=pe.dirname(t)}if(ai.some(o=>Qe(pe.join(n,o))))return n}function si(e){return ri.parse({root:e,hasFstab:Qe(pe.join(e,"fstab.yaml")),hasBlocks:Qe(pe.join(e,"blocks")),hasHeadHtml:Qe(pe.join(e,"head.html"))})}var ai,z=w(()=>{"use strict";m();Me();ai=["fstab.yaml","head.html","helix-query.yaml","component-definition.json","paths.json","scripts/scripts.js","scripts/aem.js"]});import{existsSync as ps}from"fs";import{mkdir as ms,writeFile as us}from"fs/promises";import ci from"path";async function Et(e){let t=ci.join(e,".github","workflows","eds.yml");return ps(t)?{path:li,created:!1}:(await ms(ci.dirname(t),{recursive:!0}),await us(t,fs),{path:li,created:!0})}var li,fs,cn=w(()=>{"use strict";m();li=".github/workflows/eds.yml",fs=`name: EDS checks
12
+ ${i}`}function fe(e){let t=[];return e.pass&&t.push(`${q.pass} ${e.pass} passed`),e.warn&&t.push(`${q.warn} ${e.warn} ${Es(e.warn,"warning")}`),e.fail&&t.push(`${q.fail} ${e.fail} failed`),e.info&&t.push(`${q.info} ${e.info} info`),t.join(D.dim(" "))}function Es(e,t){return e===1?t:`${t}s`}var _,q,bs,vs,ti,Zo,js,N=v(()=>{"use strict";f();_={red:D.hex("#FA0F00"),ember:D.hex("#FF4B1F"),orange:D.hex("#FF7B00"),blue:D.hex("#2680EB"),accent:D.hex("#ff5a36"),dotOrange:D.hex("#F24E1E"),dotPurple:D.hex("#A259FF"),dotBlue:D.hex("#1ABCFE"),dotGreen:D.hex("#0ACF83"),dotPink:D.hex("#FF7262"),ok:D.hex("#2D9D78"),warn:D.hex("#E68619"),err:D.hex("#D7373F"),info:D.hex("#2680EB")},q={pass:_.ok("\u2713"),warn:_.warn("\u26A0"),fail:_.err("\u2717"),info:_.info("\u2139"),bullet:D.dim("\u2022"),arrow:D.dim("\u21B3"),figma:_.dotPurple("\u25C6")};bs=/\[[0-9;]*m/g;vs=5;ti={prefix:"",style:{highlight:e=>D.hex("#ff5a36").bold(e)}};Zo=["\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588","\u2588 \u2588 \u2588 \u2588 ","\u2588\u2588\u2588\u2588 \u2588 \u2588 \u2588\u2588\u2588\u2588\u2588","\u2588 \u2588 \u2588 \u2588","\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588"],js=["#ff3b1e","#ff5a36","#ff7d52"]});import Rt from"chalk";function Cs(){let e=process.env.EDS_LOG_LEVEL?.toLowerCase();return e&&e in fn?e:"info"}function $e(e){return oi?e==="error":fn[e]>=fn[ni]}var fn,ni,oi,Ft,r,R=v(()=>{"use strict";f();N();fn={debug:0,info:1,warn:2,error:3,silent:4};ni=Cs(),oi=!1,Ft=!1;r={setLevel(e){ni=e},setQuiet(e){oi=e},debug(...e){$e("debug")&&console.error(Rt.gray("[debug]"),...e)},info(...e){$e("info")&&console.error(...e)},logoOnce(e){Ft||(Ft=!0,$e("info")&&console.error(e))},async logoOnceAnimated(e){Ft||(Ft=!0,$e("info")&&console.error(E(e)))},success(...e){$e("info")&&console.error(Rt.green("\u2713"),...e)},warn(...e){$e("warn")&&console.error(Rt.yellow("\u26A0"),...e)},error(...e){$e("error")&&console.error(Rt.red("\u2717"),...e)}}});function _e(e){return{Authorization:`Bearer ${e}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"aem-eds-kit","Content-Type":"application/json"}}function As(e){return`${Ie}/repos/${e}/generate`}async function Dt(e){let t=await fetch(`${Ie}/user`,{headers:_e(e)});if(!t.ok)throw new Error(`GitHub auth failed: ${t.status}`);return(await t.json()).login}async function ii(e,t,n){let o=await fetch(`${Ie}/repos/${t}/${n}`,{headers:_e(e)});if(o.status===404)return!1;if(o.ok)return!0;throw new Error(`existence check failed: ${o.status} ${await o.text()}`)}async function ri(e,t,n){let o=await fetch(As(t),{method:"POST",headers:_e(e),body:JSON.stringify({owner:n.owner,name:n.name,private:!!n.private,include_all_branches:!1})});if(!o.ok)throw new Error(`create failed: ${o.status} ${await o.text()}`);let i=await o.json();return{fullName:i.full_name,htmlUrl:i.html_url,cloneUrl:i.clone_url}}async function ai(e,t,n,o){await fetch(`${Ie}/repos/${t}/${n}/topics`,{method:"PUT",headers:_e(e),body:JSON.stringify({names:o})})}async function si(e,t,n){let o=await fetch(`${Ie}/repos/${t}/${n}`,{method:"DELETE",headers:_e(e)});if(!o.ok&&o.status!==204)throw new Error(`delete failed: ${o.status} ${await o.text()}`)}async function ci(e,t,n){let o=encodeURIComponent(`user:${t} topic:${n} fork:true`),i=await fetch(`${Ie}/search/repositories?q=${o}&per_page=100`,{headers:_e(e)});if(!i.ok)throw new Error(`search failed: ${i.status}`);return(await i.json()).items.map(s=>s.full_name)}var Ie,li=v(()=>{"use strict";f();Ie="https://api.github.com"});import{existsSync as di}from"fs";import{mkdir as Ts,readFile as Rs,rm as Fs,writeFile as Ds}from"fs/promises";import Ls from"os";import pi from"path";async function ui(){let e=process.env.GITHUB_TOKEN||process.env.GH_TOKEN;if(e)return e;if(di(it))try{return JSON.parse(await Rs(it,"utf-8")).token??null}catch{return null}return null}async function gn(e){await Ts(mi,{recursive:!0,mode:448}),await Ds(it,`${JSON.stringify({token:e},null,2)}
13
+ `,{mode:384})}async function fi(){di(it)&&await Fs(it)}async function gi(e){let t=await fetch("https://github.com/login/device/code",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({client_id:Lt,scope:e.join(" ")})});if(!t.ok)throw new Error(`device code request failed: ${t.status}`);return await t.json()}async function hi(e,t,n){let o=Math.max(t,1),i=Date.now()+n*1e3;for(;Date.now()<i;){await new Promise(d=>setTimeout(d,o*1e3));let s=await(await fetch("https://github.com/login/oauth/access_token",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({client_id:Lt,device_code:e,grant_type:"urn:ietf:params:oauth:grant-type:device_code"})})).json();if(s.access_token)return s.access_token;if(s.error==="slow_down")o+=5;else if(s.error!=="authorization_pending")throw new Error(s.error??"device flow failed")}throw new Error("device flow timed out")}var mi,it,Lt,wi=v(()=>{"use strict";f();mi=pi.join(Ls.homedir(),".eds"),it=pi.join(mi,"github.json"),Lt=process.env.EDS_GITHUB_CLIENT_ID??""});function hn(e,t,n="main"){return`https://${n}--${t}--${e}.aem.page/`}function wn(){return"https://github.com/apps/aem-code-sync/installations/new"}function bi(e,t){return["repo","create",e,"--template",t.template,t.private?"--private":"--public",...t.clone?["--clone"]:[]]}var Ue,rt,yi=v(()=>{"use strict";f();Ue="eds-sandbox",rt={document:"adobe/aem-boilerplate",ue:"adobe/aem-boilerplate-xwalk"}});var H={};L(H,{checkbox:()=>Hs,confirm:()=>Bs,input:()=>Us,select:()=>_s});import{checkbox as Os,confirm as Ns,input as Ms,select as Is}from"@inquirer/prompts";function Ot(e){let t={...ti,...e.theme??{}};return{...e,theme:t}}var _s,Us,Bs,Hs,G=v(()=>{"use strict";f();N();_s=(e,t)=>Is(Ot(e),t),Us=(e,t)=>Ms(Ot(e),t),Bs=(e,t)=>Ns(Ot(e),t),Hs=(e,t)=>Os(Ot(e),t)});import{z as F}from"zod";var gm,bn,vi,hm,Se,Be=v(()=>{"use strict";f();gm=F.object({fileKey:F.string().min(1),nodeId:F.string().optional(),fileName:F.string().optional()}),bn=F.object({agent:F.enum(["claude","cursor","codex"]).optional(),model:F.string().optional(),figma:F.object({mcpEndpoint:F.string().url().optional(),token:F.string().optional()}).optional(),admin:F.object({org:F.string().optional(),site:F.string().optional(),ref:F.string().default("main")}).optional()}),vi=F.object({root:F.string(),hasFstab:F.boolean(),hasBlocks:F.boolean(),hasHeadHtml:F.boolean()}),hm=F.object({figmaFileKey:F.string(),figmaNodeId:F.string().optional(),lastSyncedAt:F.string().datetime(),promptVersion:F.string(),agentUsed:F.string().optional(),breakpoints:F.array(F.object({width:F.number(),label:F.string().optional(),source:F.enum(["figma","default"]).optional()})).optional()}),Se=/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/});import{existsSync as at}from"fs";import ge from"path";function P(e=process.cwd()){let t=ge.resolve(e),{root:n}=ge.parse(t);for(;t!==n;){if(ki.some(o=>at(ge.join(t,o))))return t;t=ge.dirname(t)}if(ki.some(o=>at(ge.join(n,o))))return n}function xi(e){return vi.parse({root:e,hasFstab:at(ge.join(e,"fstab.yaml")),hasBlocks:at(ge.join(e,"blocks")),hasHeadHtml:at(ge.join(e,"head.html"))})}var ki,B=v(()=>{"use strict";f();Be();ki=["fstab.yaml","head.html","helix-query.yaml","component-definition.json","paths.json","scripts/scripts.js","scripts/aem.js"]});import{existsSync as Gs}from"fs";import{mkdir as zs,writeFile as Ws}from"fs/promises";import $i from"path";async function Nt(e){let t=$i.join(e,".github","workflows","eds.yml");return Gs(t)?{path:Si,created:!1}:(await zs($i.dirname(t),{recursive:!0}),await Ws(t,Js),{path:Si,created:!0})}var Si,Js,yn=v(()=>{"use strict";f();Si=".github/workflows/eds.yml",Js=`name: EDS checks
14
14
 
15
15
  # Generated by aem-eds-kit (\`eds scaffold ci\`). Runs the project's own
16
16
  # lint/build plus the eds audits as a gatekeeper on every PR and push to main.
@@ -53,18 +53,18 @@ jobs:
53
53
  run: npx --yes aem-eds-kit@latest audit loading
54
54
  - name: Security & exploit scan
55
55
  run: npx --yes aem-eds-kit@latest audit security
56
- `});import{existsSync as di}from"fs";import{readFile as gs,writeFile as pi}from"fs/promises";import mi from"path";function hs(e={}){let t=e.open??"/",n=e.port??3007,o=e.pagesUrl??"";return`AEM_OPEN=${t}
56
+ `});import{existsSync as ji}from"fs";import{readFile as qs,writeFile as Pi}from"fs/promises";import Ei from"path";function Ks(e={}){let t=e.open??"/",n=e.port??3007,o=e.pagesUrl??"";return`AEM_OPEN=${t}
57
57
  AEM_PORT=${n}
58
58
  AEM_PAGES_URL=${o}
59
- `}async function bs(e){let t=mi.join(e,".gitignore"),n="";if(di(t)&&(n=await gs(t,"utf-8")),n.split(/\r?\n/).some(r=>r.trim()===".env"))return!1;let o=n&&!n.endsWith(`
59
+ `}async function Xs(e){let t=Ei.join(e,".gitignore"),n="";if(ji(t)&&(n=await qs(t,"utf-8")),n.split(/\r?\n/).some(i=>i.trim()===".env"))return!1;let o=n&&!n.endsWith(`
60
60
  `)?`
61
- `:"";return await pi(t,`${n}${o}.env
62
- `),!0}async function Pt(e,t={}){let n=mi.join(e,".env"),o=!di(n);o&&await pi(n,hs(t));let r=await bs(e);return{path:".env",created:o,gitignoreUpdated:r}}var ln=w(()=>{"use strict";m()});import{writeFile as ui}from"fs/promises";import fi from"path";function Ct(e){return e!=="ue"}function gi(e,t){return`https://content.da.live/${e}/${t}/`}function ws(e){return`mountpoints:
61
+ `:"";return await Pi(t,`${n}${o}.env
62
+ `),!0}async function Mt(e,t={}){let n=Ei.join(e,".env"),o=!ji(n);o&&await Pi(n,Ks(t));let i=await Xs(e);return{path:".env",created:o,gitignoreUpdated:i}}var vn=v(()=>{"use strict";f()});import{writeFile as Ci}from"fs/promises";import Ai from"path";function It(e){return e!=="ue"}function Ti(e,t){return`https://content.da.live/${e}/${t}/`}function Vs(e){return`mountpoints:
63
63
  /: ${e}
64
- `}async function hi(e,t){return await ui(fi.join(e,"fstab.yaml"),ws(t)),"fstab.yaml"}function ys(e){return`${JSON.stringify({mappings:[`/content/${e}/:/`],includes:[`/content/${e}/`]},null,2)}
65
- `}async function bi(e,t){return await ui(fi.join(e,"paths.json"),ys(t)),"paths.json"}var ve,wi=w(()=>{"use strict";m();ve={ue:"Universal Editor (crosswalk)",da:"Document Authoring (da.live)",gdrive:"Document Authoring (Google Drive)",sharepoint:"Document Authoring (SharePoint)"}});import{existsSync as vs}from"fs";import{writeFile as ks}from"fs/promises";import xs from"path";function Ss(){return`${JSON.stringify($s,null,2)}
66
- `}async function At(e){let t=xs.join(e,"xwalk.json");return vs(t)?{path:"xwalk.json",created:!1}:(await ks(t,Ss()),{path:"xwalk.json",created:!0})}var $s,dn=w(()=>{"use strict";m();$s={public:{xwalk:{"multi-field":{enabled:!0}}}}});function Ne(e){let t=e.trim().match(/github\.com[:/]([^/]+)\/(.+?)(?:\.git)?\/?$/i);return t?{owner:t[1],repo:t[2]}:null}function _e(e,t,n="main"){return`${n}--${t}--${e}.aem.page`}function yi({host:e,path:t="/",org:n}){let o=e.replace(/^https?:\/\//,"").replace(/\/+$/,""),r=t.startsWith("/")?t:`/${t}`;return`https://experience.adobe.com/#/${n?`@${n}/`:""}aem/editor/canvas/${o}${r}`}var Tt=w(()=>{"use strict";m()});function Ze(e){return`${JSON.stringify(e,null,2)}
67
- `}function mn(e){return ke.find(t=>t.id===e)}var pn,vi,ki,ke,un=w(()=>{"use strict";m();pn=(e,t,n)=>({title:e,id:t,plugins:{xwalk:{page:{resourceType:"core/franklin/components/block/v1/block",template:{name:e,model:n}}}}}),vi=(e,t,n)=>({title:e,id:t,plugins:{xwalk:{page:{resourceType:"core/franklin/components/block/v1/block",template:{name:e,filter:n}}}}}),ki=(e,t,n)=>({title:e,id:t,plugins:{xwalk:{page:{resourceType:"core/franklin/components/block/v1/block/item",template:{name:e,model:n}}}}}),ke=[{id:"hero",title:"Hero",js:`// Block: hero
64
+ `}async function Ri(e,t){return await Ci(Ai.join(e,"fstab.yaml"),Vs(t)),"fstab.yaml"}function Ys(e){return`${JSON.stringify({mappings:[`/content/${e}/:/`],includes:[`/content/${e}/`]},null,2)}
65
+ `}async function Fi(e,t){return await Ci(Ai.join(e,"paths.json"),Ys(t)),"paths.json"}var je,Di=v(()=>{"use strict";f();je={ue:"Universal Editor (crosswalk)",da:"Document Authoring (da.live)",gdrive:"Document Authoring (Google Drive)",sharepoint:"Document Authoring (SharePoint)"}});import{existsSync as Qs}from"fs";import{writeFile as Zs}from"fs/promises";import ec from"path";function nc(){return`${JSON.stringify(tc,null,2)}
66
+ `}async function _t(e){let t=ec.join(e,"xwalk.json");return Qs(t)?{path:"xwalk.json",created:!1}:(await Zs(t,nc()),{path:"xwalk.json",created:!0})}var tc,kn=v(()=>{"use strict";f();tc={public:{xwalk:{"multi-field":{enabled:!0}}}}});function He(e){let t=e.trim().match(/github\.com[:/]([^/]+)\/(.+?)(?:\.git)?\/?$/i);return t?{owner:t[1],repo:t[2]}:null}function Ge(e,t,n="main"){return`${n}--${t}--${e}.aem.page`}function Li({host:e,path:t="/",org:n}){let o=e.replace(/^https?:\/\//,"").replace(/\/+$/,""),i=t.startsWith("/")?t:`/${t}`;return`https://experience.adobe.com/#/${n?`@${n}/`:""}aem/editor/canvas/${o}${i}`}var Ut=v(()=>{"use strict";f()});function st(e){return`${JSON.stringify(e,null,2)}
67
+ `}function $n(e){return Pe.find(t=>t.id===e)}var xn,Oi,Ni,Pe,Sn=v(()=>{"use strict";f();xn=(e,t,n)=>({title:e,id:t,plugins:{xwalk:{page:{resourceType:"core/franklin/components/block/v1/block",template:{name:e,model:n}}}}}),Oi=(e,t,n)=>({title:e,id:t,plugins:{xwalk:{page:{resourceType:"core/franklin/components/block/v1/block",template:{name:e,filter:n}}}}}),Ni=(e,t,n)=>({title:e,id:t,plugins:{xwalk:{page:{resourceType:"core/franklin/components/block/v1/block/item",template:{name:e,model:n}}}}}),Pe=[{id:"hero",title:"Hero",js:`// Block: hero
68
68
  export default function decorate(block) {
69
69
  block.classList.add('hero');
70
70
  const picture = block.querySelector('picture');
@@ -93,7 +93,7 @@ export default function decorate(block) {
93
93
  margin: 0 auto;
94
94
  padding: 0 var(--spacing-m, 16px);
95
95
  }
96
- `,model:Ze({definitions:[pn("Hero","hero","hero")],models:[{id:"hero",fields:[{component:"reference",valueType:"string",name:"image",label:"Image"},{component:"text",valueType:"string",name:"imageAlt",label:"Alt"},{component:"text",valueType:"string",name:"title",label:"Title"},{component:"richtext",valueType:"string",name:"text",value:"",label:"Text"}]}],filters:[]})},{id:"cards",title:"Cards",js:`// Block: cards
96
+ `,model:st({definitions:[xn("Hero","hero","hero")],models:[{id:"hero",fields:[{component:"reference",valueType:"string",name:"image",label:"Image"},{component:"text",valueType:"string",name:"imageAlt",label:"Alt"},{component:"text",valueType:"string",name:"title",label:"Title"},{component:"richtext",valueType:"string",name:"text",value:"",label:"Text"}]}],filters:[]})},{id:"cards",title:"Cards",js:`// Block: cards
97
97
  export default function decorate(block) {
98
98
  const ul = document.createElement('ul');
99
99
  [...block.children].forEach((row) => {
@@ -132,7 +132,7 @@ export default function decorate(block) {
132
132
  .cards .cards-card-body {
133
133
  padding: var(--spacing-m, 16px);
134
134
  }
135
- `,model:Ze({definitions:[vi("Cards","cards","cards"),ki("Card","card","card")],models:[{id:"card",fields:[{component:"reference",valueType:"string",name:"image",label:"Image"},{component:"text",valueType:"string",name:"imageAlt",label:"Alt"},{component:"text",valueType:"string",name:"title",label:"Title"},{component:"richtext",valueType:"string",name:"text",value:"",label:"Text"},{component:"aem-content",name:"link",label:"Link"}]}],filters:[{id:"cards",components:["card"]}]})},{id:"columns",title:"Columns",js:`// Block: columns
135
+ `,model:st({definitions:[Oi("Cards","cards","cards"),Ni("Card","card","card")],models:[{id:"card",fields:[{component:"reference",valueType:"string",name:"image",label:"Image"},{component:"text",valueType:"string",name:"imageAlt",label:"Alt"},{component:"text",valueType:"string",name:"title",label:"Title"},{component:"richtext",valueType:"string",name:"text",value:"",label:"Text"},{component:"aem-content",name:"link",label:"Link"}]}],filters:[{id:"cards",components:["card"]}]})},{id:"columns",title:"Columns",js:`// Block: columns
136
136
  export default function decorate(block) {
137
137
  const cols = [...block.firstElementChild.children];
138
138
  block.classList.add(\`columns-\${cols.length}-cols\`);
@@ -159,7 +159,7 @@ export default function decorate(block) {
159
159
  }
160
160
 
161
161
  .columns img { width: 100%; height: auto; }
162
- `,model:Ze({definitions:[pn("Columns","columns","columns")],models:[{id:"columns",fields:[{component:"richtext",valueType:"string",name:"content",value:"",label:"Content"}]}],filters:[]})},{id:"accordion",title:"Accordion",js:`// Block: accordion
162
+ `,model:st({definitions:[xn("Columns","columns","columns")],models:[{id:"columns",fields:[{component:"richtext",valueType:"string",name:"content",value:"",label:"Content"}]}],filters:[]})},{id:"accordion",title:"Accordion",js:`// Block: accordion
163
163
  export default function decorate(block) {
164
164
  [...block.children].forEach((row) => {
165
165
  const [label, body] = row.children;
@@ -192,7 +192,7 @@ export default function decorate(block) {
192
192
  .accordion .accordion-item-body {
193
193
  padding-bottom: var(--spacing-m, 16px);
194
194
  }
195
- `,model:Ze({definitions:[vi("Accordion","accordion","accordion"),ki("Accordion Item","accordion-item","accordion-item")],models:[{id:"accordion-item",fields:[{component:"text",valueType:"string",name:"label",label:"Label"},{component:"richtext",valueType:"string",name:"body",value:"",label:"Body"}]}],filters:[{id:"accordion",components:["accordion-item"]}]})},{id:"embed",title:"Embed",js:`// Block: embed
195
+ `,model:st({definitions:[Oi("Accordion","accordion","accordion"),Ni("Accordion Item","accordion-item","accordion-item")],models:[{id:"accordion-item",fields:[{component:"text",valueType:"string",name:"label",label:"Label"},{component:"richtext",valueType:"string",name:"body",value:"",label:"Body"}]}],filters:[{id:"accordion",components:["accordion-item"]}]})},{id:"embed",title:"Embed",js:`// Block: embed
196
196
  export default function decorate(block) {
197
197
  const link = block.querySelector('a');
198
198
  const url = link?.href;
@@ -221,12 +221,12 @@ export default function decorate(block) {
221
221
  height: 100%;
222
222
  border: 0;
223
223
  }
224
- `,model:Ze({definitions:[pn("Embed","embed","embed")],models:[{id:"embed",fields:[{component:"aem-content",name:"link",label:"Embed URL"}]}],filters:[]})}]});import{existsSync as js}from"fs";import{mkdir as Es,writeFile as Ps}from"fs/promises";import xi from"path";function Si(e){return et.find(t=>t.id===e)}function ji(e){let t=new Set,n=o=>{if(t.has(o))return;let r=Si(o);if(r){for(let a of r.deps??[])n(a);t.add(o)}};for(let o of e)n(o);return et.filter(o=>t.has(o.id)).map(o=>o.id)}function Cs(e){return`// scripts/utils.js - common EDS helpers (generated by \`eds scaffold helpers\`).
224
+ `,model:st({definitions:[xn("Embed","embed","embed")],models:[{id:"embed",fields:[{component:"aem-content",name:"link",label:"Embed URL"}]}],filters:[]})}]});import{existsSync as oc}from"fs";import{mkdir as ic,writeFile as rc}from"fs/promises";import Mi from"path";function _i(e){return ct.find(t=>t.id===e)}function Ui(e){let t=new Set,n=o=>{if(t.has(o))return;let i=_i(o);if(i){for(let a of i.deps??[])n(a);t.add(o)}};for(let o of e)n(o);return ct.filter(o=>t.has(o.id)).map(o=>o.id)}function ac(e){return`// scripts/utils.js - common EDS helpers (generated by \`eds scaffold helpers\`).
225
225
 
226
- ${ji(e).map(o=>Si(o)).filter(o=>!!o).map(o=>o.code).join(`
226
+ ${Ui(e).map(o=>_i(o)).filter(o=>!!o).map(o=>o.code).join(`
227
227
 
228
228
  `)}
229
- `}async function Ei(e,t=fn){let n=ji(t),o=xi.join(e,"scripts","utils.js");return js(o)?{path:$i,created:!1,helpers:n}:(await Es(xi.dirname(o),{recursive:!0}),await Ps(o,Cs(t)),{path:$i,created:!0,helpers:n})}var $i,et,fn,Pi=w(()=>{"use strict";m();$i="scripts/utils.js",et=[{id:"getMetadata",label:"getMetadata (read a page meta value)",code:`/**
229
+ `}async function Bi(e,t=jn){let n=Ui(t),o=Mi.join(e,"scripts","utils.js");return oc(o)?{path:Ii,created:!1,helpers:n}:(await ic(Mi.dirname(o),{recursive:!0}),await rc(o,ac(t)),{path:Ii,created:!0,helpers:n})}var Ii,ct,jn,Hi=v(()=>{"use strict";f();Ii="scripts/utils.js",ct=[{id:"getMetadata",label:"getMetadata (read a page meta value)",code:`/**
230
230
  * Reads a page metadata value by name (meta[name] or meta[property]).
231
231
  * @param {string} name The metadata name.
232
232
  * @returns {string} The value, or an empty string.
@@ -323,8 +323,8 @@ export function isUEPreview() {
323
323
  */
324
324
  export function isUE() {
325
325
  return isUEEdit() || isUEPreview();
326
- }`}],fn=et.map(e=>e.id)});function As(){return[{component:"tab",name:"basics",label:"Basics"},{component:"text",valueType:"string",name:"text",label:"Text (single line)"},{component:"textarea",valueType:"string",name:"textarea",label:"Textarea (multi-line)"},{component:"richtext",valueType:"string",name:"richtext",value:"",label:"Rich text"},{component:"number",valueType:"number",name:"number",label:"Number"},{component:"boolean",valueType:"boolean",name:"boolean",value:!1,label:"Boolean"},{component:"date-time",valueType:"date",name:"date",label:"Date / time"},{component:"tab",name:"selection",label:"Selection"},{component:"select",valueType:"string",name:"select",label:"Select",value:"a",options:[{name:"Option A",value:"a"},{name:"Option B",value:"b"}]},{component:"radio-group",valueType:"string",name:"radio",label:"Radio group",value:"x",options:[{name:"X",value:"x"},{name:"Y",value:"y"}]},{component:"multiselect",valueType:"string",name:"classes",label:"Multiselect (CSS classes)",options:[{name:"Highlight",value:"highlight"},{name:"Dark",value:"dark"}]},{component:"checkbox-group",valueType:"string[]",name:"toggles",label:"Checkbox group",options:[{name:"Show title",value:"show-title"},{name:"Show image",value:"show-image"}]},{component:"tab",name:"media",label:"Media & content"},{component:"reference",valueType:"string",name:"image",label:"Image (DAM asset)"},{component:"text",valueType:"string",name:"imageAlt",label:"Image alt"},{component:"aem-content",name:"link",label:"Link (page / URL)"},{component:"aem-content-fragment",name:"contentFragment",label:"Content Fragment"},{component:"aem-experience-fragment",name:"experienceFragment",label:"Experience Fragment"},{component:"aem-tag",valueType:"string",name:"tags",label:"Tags"},{component:"tab",name:"repeatable",label:"Multifield"},{component:"container",name:"items",label:"Items (repeatable)",multi:!0,collapsible:!0,fields:[{component:"text",valueType:"string",name:"itemTitle",label:"Title"},{component:"richtext",valueType:"string",name:"itemText",value:"",label:"Text"},{component:"aem-content",name:"itemLink",label:"Link"}]}]}function gn(){let e={definitions:[{title:"Field Reference",id:"field-reference",plugins:{xwalk:{page:{resourceType:"core/franklin/components/block/v1/block",template:{name:"Field Reference",model:"field-reference"}}}}}],models:[{id:"field-reference",fields:As()}],filters:[]};return`${JSON.stringify(e,null,2)}
327
- `}function hn(e,t){let n=new Set(e.map(o=>o.id));return[...e,...t.filter(o=>!n.has(o.id))]}function Di(e,t,n){let o=e?.groups?[...e.groups]:[],r=(a,s,d)=>{let l=o.find(c=>c.id===a);l||(l={id:a,title:s,components:[]},o.push(l)),l.components=hn(l.components,d)};return r("default","Default Content",t),r("blocks","Blocks",n),{groups:o}}function tt(e,t){let n=e?[...e]:[],o=n.find(r=>r.id==="section");return o||(o={id:"section",components:["text","image","button","title"]},n.push(o)),o.components=[...new Set([...o.components,...t])],n}var Ci,Ai,Ti,Ri,bn=w(()=>{"use strict";m();Ci=[{title:"Text",id:"text",plugins:{xwalk:{page:{resourceType:"core/franklin/components/text/v1/text",template:{text:"<p>Text</p>"}}}}},{title:"Image",id:"image",plugins:{xwalk:{page:{resourceType:"core/franklin/components/image/v1/image",template:{image:"",imageAlt:""}}}}},{title:"Button",id:"button",plugins:{xwalk:{page:{resourceType:"core/franklin/components/button/v1/button",template:{text:"Button",href:"",type:""}}}}},{title:"Title",id:"title",plugins:{xwalk:{page:{resourceType:"core/franklin/components/title/v1/title",template:{title:"Title",type:"h2"}}}}}],Ai=[{id:"title",fields:[{component:"text",valueType:"string",name:"title",label:"Title"},{component:"select",valueType:"string",name:"type",label:"Type",value:"h2",options:[{name:"H1",value:"h1"},{name:"H2",value:"h2"},{name:"H3",value:"h3"},{name:"H4",value:"h4"},{name:"H5",value:"h5"},{name:"H6",value:"h6"}]}]},{id:"image",fields:[{component:"reference",valueType:"string",name:"image",label:"Image",multi:!1},{component:"text",valueType:"string",name:"imageAlt",label:"Alt Text"}]},{id:"button",fields:[{component:"text",valueType:"string",name:"text",label:"Text"},{component:"aem-content",name:"href",label:"Link"},{component:"select",valueType:"string",name:"type",label:"Type",options:[{name:"Default",value:""},{name:"Primary",value:"primary"},{name:"Secondary",value:"secondary"}]}]}];Ti=`// Block: field-reference
326
+ }`}],jn=ct.map(e=>e.id)});function sc(){return[{component:"tab",name:"basics",label:"Basics"},{component:"text",valueType:"string",name:"text",label:"Text (single line)"},{component:"textarea",valueType:"string",name:"textarea",label:"Textarea (multi-line)"},{component:"richtext",valueType:"string",name:"richtext",value:"",label:"Rich text"},{component:"number",valueType:"number",name:"number",label:"Number"},{component:"boolean",valueType:"boolean",name:"boolean",value:!1,label:"Boolean"},{component:"date-time",valueType:"date",name:"date",label:"Date / time"},{component:"tab",name:"selection",label:"Selection"},{component:"select",valueType:"string",name:"select",label:"Select",value:"a",options:[{name:"Option A",value:"a"},{name:"Option B",value:"b"}]},{component:"radio-group",valueType:"string",name:"radio",label:"Radio group",value:"x",options:[{name:"X",value:"x"},{name:"Y",value:"y"}]},{component:"multiselect",valueType:"string",name:"classes",label:"Multiselect (CSS classes)",options:[{name:"Highlight",value:"highlight"},{name:"Dark",value:"dark"}]},{component:"checkbox-group",valueType:"string[]",name:"toggles",label:"Checkbox group",options:[{name:"Show title",value:"show-title"},{name:"Show image",value:"show-image"}]},{component:"tab",name:"media",label:"Media & content"},{component:"reference",valueType:"string",name:"image",label:"Image (DAM asset)"},{component:"text",valueType:"string",name:"imageAlt",label:"Image alt"},{component:"aem-content",name:"link",label:"Link (page / URL)"},{component:"aem-content-fragment",name:"contentFragment",label:"Content Fragment"},{component:"aem-experience-fragment",name:"experienceFragment",label:"Experience Fragment"},{component:"aem-tag",valueType:"string",name:"tags",label:"Tags"},{component:"tab",name:"repeatable",label:"Multifield"},{component:"container",name:"items",label:"Items (repeatable)",multi:!0,collapsible:!0,fields:[{component:"text",valueType:"string",name:"itemTitle",label:"Title"},{component:"richtext",valueType:"string",name:"itemText",value:"",label:"Text"},{component:"aem-content",name:"itemLink",label:"Link"}]}]}function Pn(){let e={definitions:[{title:"Field Reference",id:"field-reference",plugins:{xwalk:{page:{resourceType:"core/franklin/components/block/v1/block",template:{name:"Field Reference",model:"field-reference"}}}}}],models:[{id:"field-reference",fields:sc()}],filters:[]};return`${JSON.stringify(e,null,2)}
327
+ `}function En(e,t){let n=new Set(e.map(o=>o.id));return[...e,...t.filter(o=>!n.has(o.id))]}function qi(e,t,n){let o=e?.groups?[...e.groups]:[],i=(a,s,d)=>{let l=o.find(c=>c.id===a);l||(l={id:a,title:s,components:[]},o.push(l)),l.components=En(l.components,d)};return i("default","Default Content",t),i("blocks","Blocks",n),{groups:o}}function lt(e,t){let n=e?[...e]:[],o=n.find(i=>i.id==="section");return o||(o={id:"section",components:["text","image","button","title"]},n.push(o)),o.components=[...new Set([...o.components,...t])],n}var Gi,zi,Wi,Ji,Cn=v(()=>{"use strict";f();Gi=[{title:"Text",id:"text",plugins:{xwalk:{page:{resourceType:"core/franklin/components/text/v1/text",template:{text:"<p>Text</p>"}}}}},{title:"Image",id:"image",plugins:{xwalk:{page:{resourceType:"core/franklin/components/image/v1/image",template:{image:"",imageAlt:""}}}}},{title:"Button",id:"button",plugins:{xwalk:{page:{resourceType:"core/franklin/components/button/v1/button",template:{text:"Button",href:"",type:""}}}}},{title:"Title",id:"title",plugins:{xwalk:{page:{resourceType:"core/franklin/components/title/v1/title",template:{title:"Title",type:"h2"}}}}}],zi=[{id:"title",fields:[{component:"text",valueType:"string",name:"title",label:"Title"},{component:"select",valueType:"string",name:"type",label:"Type",value:"h2",options:[{name:"H1",value:"h1"},{name:"H2",value:"h2"},{name:"H3",value:"h3"},{name:"H4",value:"h4"},{name:"H5",value:"h5"},{name:"H6",value:"h6"}]}]},{id:"image",fields:[{component:"reference",valueType:"string",name:"image",label:"Image",multi:!1},{component:"text",valueType:"string",name:"imageAlt",label:"Alt Text"}]},{id:"button",fields:[{component:"text",valueType:"string",name:"text",label:"Text"},{component:"aem-content",name:"href",label:"Link"},{component:"select",valueType:"string",name:"type",label:"Type",options:[{name:"Default",value:""},{name:"Primary",value:"primary"},{name:"Secondary",value:"secondary"}]}]}];Wi=`// Block: field-reference
328
328
  // A living reference of every Universal Editor field type (see _field-reference.json).
329
329
  // Authors use it to see what's available; delete it before launch.
330
330
  export default function decorate(block) {
@@ -333,44 +333,44 @@ export default function decorate(block) {
333
333
  // are what you drop and edit.
334
334
  block.classList.add('field-reference');
335
335
  }
336
- `,Ri=`/* Block: field-reference */
336
+ `,Ji=`/* Block: field-reference */
337
337
  .field-reference {
338
338
  display: grid;
339
339
  gap: var(--spacing-m, 16px);
340
340
  padding: var(--spacing-l, 32px) 0;
341
341
  }
342
- `});var ce={};N(ce,{scaffoldBlocks:()=>Oi,scaffoldCi:()=>Mi,scaffoldEnv:()=>_i,scaffoldHelpers:()=>Ni,scaffoldInteractive:()=>Rs,scaffoldUe:()=>Ft,scaffoldXwalk:()=>Ii});import{existsSync as Fi}from"fs";import{mkdir as Li,readFile as Ts,writeFile as xe}from"fs/promises";import te from"path";async function Rt(e){if(!Fi(e))return null;try{return JSON.parse(await Ts(e,"utf-8"))}catch{return null}}async function Dt(e,t){await xe(e,`${JSON.stringify(t,null,2)}
343
- `)}async function Ft(){let e=E();if(!e){i.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}i.logoOnce(P("Scaffold - Universal Editor"));let t=[],n=te.join(e,"blocks","field-reference");await Li(n,{recursive:!0}),await xe(te.join(n,"field-reference.js"),Ti),await xe(te.join(n,"field-reference.css"),Ri),await xe(te.join(n,"_field-reference.json"),gn()),t.push("blocks/field-reference/ (all 17 fields + multifield)");let o=te.join(e,"component-definition.json"),r=te.join(e,"component-models.json"),a=te.join(e,"component-filters.json"),s=[{title:"Field Reference",id:"field-reference",plugins:{xwalk:{page:{resourceType:"core/franklin/components/block/v1/block",template:{name:"Field Reference",model:"field-reference"}}}}}],d=Di(await Rt(o),Ci,s);await Dt(o,d),t.push("component-definition.json (default content + field-reference)");let l=await Rt(r)??[],c=JSON.parse(gn()).models[0],u=hn(l,[...Ai,c]);await Dt(r,u),t.push("component-models.json (title / image / button / field-reference)");let p=tt(await Rt(a),["field-reference"]);await Dt(a,p),t.push("component-filters.json (section filter)"),i.info(j("Created / merged"));let f=t.map(y=>y.split(" ")[0]),g=O(f);for(let y of t){let[h,...b]=y.split(" ");i.info($(h,b.join(" ").replace(/^\((.*)\)$/,"$1"),g))}i.info(""),i.info(L(["Universal Editor scaffold ready"]))}async function Oi(e){let t=E();if(!t){i.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}i.logoOnce(P("Scaffold \u2014 standard blocks"));let n;if(e?.length){n=e.map(c=>mn(c.trim())).filter(c=>!!c);let l=e.filter(c=>!mn(c.trim()));l.length&&i.warn(`Unknown block(s): ${l.join(", ")}. Available: ${ke.map(c=>c.id).join(", ")}`)}else n=ke;let o=[],r=[];for(let l of n){let c=te.join(t,"blocks",l.id);if(Fi(c)){r.push(l.id);continue}await Li(c,{recursive:!0}),await xe(te.join(c,`${l.id}.js`),l.js),await xe(te.join(c,`${l.id}.css`),l.css),await xe(te.join(c,`_${l.id}.json`),l.model),o.push(l.id)}let a=te.join(t,"component-filters.json"),s=tt(await Rt(a),n.map(l=>l.id));await Dt(a,s),i.info(j("Blocks"));let d=O([...o,...r,"component-filters"]);for(let l of o)i.info($(l,"created",d));for(let l of r)i.info(D("warn",l,"already exists \u2014 skipped",d));i.info(""),i.info(L([`${o.length} block(s) scaffolded + registered`]))}async function Mi(){let e=E();if(!e){i.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}i.logoOnce(P("Scaffold - CI workflow"));let t=await Et(e);i.info(j("GitHub Actions")),t.created?i.info($(t.path,"doctor + audit loading + audit security + lint/build")):i.info(D("warn",t.path,"already exists - skipped")),i.info(""),i.info(L([t.created?"CI workflow scaffolded - commit it and it runs on every PR":"CI workflow left untouched"]))}async function Ni(e){let t=E();if(!t){i.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}i.logoOnce(P("Scaffold - helpers"));let n=e?.length?e:void 0;if(!n)if(process.stdout.isTTY){let{checkbox:r}=await Promise.resolve().then(()=>(B(),U));n=await r({message:"Which helpers?",choices:et.map(a=>({name:a.label,value:a.id,checked:!0}))})}else n=fn;if(!n.length){i.info("Nothing selected.");return}let o=await Ei(t,n);i.info(j("Helpers")),o.created?i.info($(o.path,o.helpers.join(", "))):i.info(D("warn",o.path,"already exists - skipped")),i.info(""),i.info(L([o.created?`${o.helpers.length} helper(s) -> scripts/utils.js`:"Helpers left untouched"]))}async function _i(e={}){let t=E();if(!t){i.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}i.logoOnce(P("Scaffold - .env"));let n=e.pagesUrl;if(n===void 0)try{let{execa:s}=await import("execa"),d=await s("git",["remote","get-url","origin"],{cwd:t}),l=Ne(d.stdout.trim());n=l?`https://${_e(l.owner,l.repo)}`:""}catch{n=""}let o=e.open??"/",r=e.port??"3007";if(!e.yes&&process.stdout.isTTY){let{input:s}=await Promise.resolve().then(()=>(B(),U));o=await s({message:"AEM_OPEN (path opened on start)",default:o}),r=await s({message:"AEM_PORT",default:String(r)}),n=await s({message:"AEM_PAGES_URL (content origin)",default:n})}let a=await Pt(t,{open:o,port:r,pagesUrl:n});i.info(j(".env")),a.created?i.info($(a.path,`AEM_OPEN=${o} AEM_PORT=${r}`)):i.info(D("warn",a.path,"already exists - left untouched")),a.gitignoreUpdated&&i.info($(".gitignore","added .env")),i.info(""),i.info(L([a.created?".env ready for `aem up`":".env left untouched"]))}async function Ii(){let e=E();if(!e){i.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}i.logoOnce(P("Scaffold - xwalk.json"));let t=await At(e);i.info(j("xwalk.json")),t.created?i.info($(t.path,"multi-field enabled")):i.info(D("warn",t.path,"already exists - left untouched")),i.info(""),i.info(L([t.created?"xwalk.json ready (UE multi-field)":"xwalk.json left untouched"]))}async function Rs(){let{select:e,checkbox:t}=await Promise.resolve().then(()=>(B(),U));i.logoOnce(P("Scaffold"));let n=await e({message:"What do you want to scaffold?",choices:[{name:"Universal Editor config + field-reference (all 17 field types)",value:"ue"},{name:"Standard blocks (hero, cards, columns, accordion, embed)",value:"blocks"},{name:"GitHub Actions CI (doctor + audits + lint/build)",value:"ci"},{name:"Helper functions (scripts/utils.js)",value:"helpers"},{name:"Local-dev .env (aem up: port / open / pages URL)",value:"env"},{name:"xwalk.json (enable Universal Editor multi-field)",value:"xwalk"},{name:"UE config + standard blocks",value:"both"}]});if(n==="env")return _i();if(n==="xwalk")return Ii();if((n==="ue"||n==="both")&&await Ft(),n==="blocks"||n==="both"){let o=await t({message:"Which blocks?",choices:ke.map(r=>({name:r.title,value:r.id,checked:!0}))});await Oi(o)}n==="ci"&&await Mi(),n==="helpers"&&await Ni()}var re=w(()=>{"use strict";m();R();z();un();cn();ln();Pi();bn();dn();Tt();I()});var Ot={};N(Ot,{initProject:()=>Ms});import{existsSync as yn}from"fs";import{readFile as vn,writeFile as Ui}from"fs/promises";import Lt from"path";import wn from"chalk";async function Ds(e){try{let{execa:t}=await import("execa"),n=await t("git",["remote","get-url","origin"],{cwd:e}),o=Ne(n.stdout.trim());return o?`https://${_e(o.owner,o.repo)}`:""}catch{return""}}async function Fs(e,t){let n=Lt.join(e,"package.json");if(!yn(n))return!1;try{let o=JSON.parse(await vn(n,"utf-8"));return o.name=t,await Ui(n,`${JSON.stringify(o,null,2)}
344
- `),!0}catch{return!1}}async function Ls(e,t){let n=[];for(let o of["README.md","index.html","head.html"]){let r=Lt.join(e,o);if(yn(r))try{let a=await vn(r,"utf-8"),s=a.replace(/aem-boilerplate/gi,t);s!==a&&(await Ui(r,s),n.push(o))}catch{}}return n}async function Os(e){let{confirm:t}=await Promise.resolve().then(()=>(B(),U)),n=[{title:"Install the AEM Code Sync GitHub app",url:"https://github.com/apps/aem-code-sync/installations/new",note:"Connects your repo to the Edge Delivery pipeline (preview/publish)."}];e==="gdrive"&&n.push({title:"Share your content folder",note:"Share the Google Drive folder with the AEM service and set it as the mountpoint."}),e==="sharepoint"&&n.push({title:"Share your content folder",note:"Grant the SharePoint/OneDrive folder to the AEM service account."}),e==="da"&&n.push({title:"Author in DA",url:"https://da.live",note:"Create documents at da.live."}),e==="ue"&&n.push({title:"Open the Universal Editor",url:"https://experience.adobe.com",note:"Author in-context once the repo is connected to AEM."}),n.push({title:"Install the AEM Sidekick extension",url:"https://chromewebstore.google.com/detail/aem-sidekick/igkmdomcgoebiipaifhmpfjhbjccggml",note:"Preview and publish from the browser."}),n.push({title:"Run the local dev server",note:"npm install, then `aem up` (from @adobe/aem-cli)."}),i.info(j("Next steps (outside the repo)"));for(let o=0;o<n.length;o++){let r=n[o];i.info(` ${_.accent(String(o+1))} ${wn.bold(r.title)}`),r.url&&i.info(` ${wn.cyan(r.url)}`),i.info(` ${wn.dim(r.note)}`),await t({message:" Done / skip?",default:!0})}}async function Ms(e={}){let t=E();if(!t){i.error("Not inside an EDS project (no EDS project markers found). Clone an EDS boilerplate first, then run this from its root."),process.exitCode=1;return}await i.logoOnceAnimated("Project setup");let{input:n,select:o,confirm:r}=await Promise.resolve().then(()=>(B(),U)),a=!e.yes,s=Lt.basename(t),d=Lt.join(t,"package.json");if(yn(d))try{s=JSON.parse(await vn(d,"utf-8")).name||s}catch{}let l=e.name&&nt(e.name)||nt(await n({message:"1/4 Project name",default:nt(s),validate:h=>!!nt(h)||"Use letters, numbers and dashes"})),c=e.authoring??await o({message:"2/4 Authoring model",choices:[{name:ve.ue,value:"ue"},{name:ve.da,value:"da"},{name:ve.gdrive,value:"gdrive"},{name:ve.sharepoint,value:"sharepoint"}]}),u=e.mountpoint;if(Ct(c)&&!u)if(c==="da"&&(e.org||a)){let h=e.org??await n({message:" DA org",validate:S=>!!S.trim()||"Required"}),b=e.site??(a?await n({message:" DA site",default:l}):l);u=gi(h.trim(),nt(b))}else c!=="da"&&a&&(u=(await n({message:` ${c==="gdrive"?"Google Drive folder URL":"SharePoint folder URL"}`,validate:b=>/^https?:\/\//.test(b.trim())||"Paste the folder URL"})).trim());let p=e.ci??(a?await r({message:"4/4 Add GitHub Actions CI (audits gatekeeper)?",default:!0}):!0);i.info(j("Summary"));let f=O(["name","authoring","mountpoint","ci"]);if(i.info($("name",l,f)),i.info($("authoring",ve[c],f)),u?i.info($("mountpoint",u,f)):Ct(c)&&i.info($("mountpoint","(skipped - set it in fstab.yaml later)",f)),i.info($("ci",p?"yes":"no",f)),i.info(""),a&&!await r({message:"Apply this setup?",default:!0})){i.info("Cancelled.");return}let g=[];await Fs(t,l)&&g.push("package.json (name)");for(let h of await Ls(t,l))g.push(`${h} (renamed)`);if(Ct(c)&&u&&g.push(await hi(t,u)),c==="ue"&&(await Ft(),g.push(await bi(t,l))),p){let h=await Et(t);g.push(h.created?h.path:`${h.path} (exists, skipped)`)}if(e.env!==!1){let h=await Pt(t,{pagesUrl:await Ds(t)});g.push(h.created?".env (aem up config)":".env (exists, skipped)")}if(e.xwalk!==!1&&c==="ue"){let h=await At(t);g.push(h.created?`${h.path} (UE multi-field)`:`${h.path} (exists, skipped)`)}i.info(j("Configured"));let y=O(g.map(h=>h.split(" ")[0]));for(let h of g){let[b,...S]=h.split(" ");i.info($(b,S.join(" ").replace(/^\((.*)\)$/,"$1"),y))}i.info(""),a&&await Os(c),i.info(L([`"${l}" set up for ${ve[c]}`]))}var nt,Mt=w(()=>{"use strict";m();R();z();cn();ln();wi();dn();Tt();I();re();nt=e=>e.trim().toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"")});var $e={};N($e,{sandboxList:()=>Gs,sandboxLogin:()=>Us,sandboxLogout:()=>Bs,sandboxNew:()=>Hs,sandboxRm:()=>zs});import Ns from"path";import Z from"chalk";async function le(e,t,n={}){let{execa:o}=await import("execa");return((await o(e,t,n)).stdout??"").toString().trim()}async function kn(e){let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{await le(t,[e],{stdio:"ignore"})}catch{}}async function _s(){try{return await le("gh",["auth","status"]),await le("gh",["api","user","-q",".login"])}catch{return null}}async function xn(){let e=await Qo();if(e)try{return{mode:"api",token:e,login:await $t(e)}}catch{}let t=await _s();return t?{mode:"gh",login:t}:null}async function Is(e,t,n){if(e.mode==="api")return Go(e.token,t,n);try{return await le("gh",["repo","view",`${t}/${n}`,"--json","name"]),!0}catch{return!1}}function $n(){i.error("Not authenticated with GitHub."),i.info(" Run `eds sandbox login` to authorize GitHub, or install + `gh auth login`."),process.exitCode=1}async function Us(){await i.logoOnceAnimated("Sandbox - GitHub login");let{input:e}=await Promise.resolve().then(()=>(B(),U));if(St){let n=await ei(["repo","delete_repo"]);i.info(j("Authorize GitHub")),i.info($("code",n.user_code)),i.info($("open",n.verification_uri)),i.info(""),await kn(n.verification_uri),i.info(Z.dim(" Waiting for you to authorize in the browser..."));try{let o=await ti(n.device_code,n.interval,n.expires_in);await on(o),i.success(`Authorized as ${await $t(o)}.`)}catch(o){i.error(`Device flow failed: ${o.message}`),process.exitCode=1}return}i.info(j("Authorize GitHub (least-privilege token)")),i.info(" Create a fine-grained token limited to your sandboxes only:"),i.info(` ${Z.cyan("https://github.com/settings/personal-access-tokens/new")}`),i.info(Z.dim(" - Resource owner: a dedicated sandbox org (recommended) or your account")),i.info(Z.dim(" - Repository access: All repositories in that org (to create new sandboxes),")),i.info(Z.dim(" or Only select repositories to manage existing ones")),i.info(Z.dim(" - Permissions: Administration = Read and write, Contents = Read and write,")),i.info(Z.dim(" Metadata = Read. Set a short expiry.")),i.info(Z.dim(" Tip: `eds sandbox new --org <sandbox-org>` so nothing in your personal account is touched.")),i.info(""),await(await Promise.resolve().then(()=>(B(),U))).confirm({message:"Open the token page?",default:!0})&&await kn("https://github.com/settings/personal-access-tokens/new");let t=(await e({message:"Paste the token",validate:n=>!!n.trim()||"Required"})).trim();try{let n=await $t(t);await on(t),i.success(`Authorized as ${n}.`)}catch{i.error("That token didn't work (check the scopes)."),process.exitCode=1}}async function Bs(){await Zo(),i.success("Signed out (stored GitHub token removed).")}async function Hs(e,t={}){let n=await xn();if(!n)return $n();await i.logoOnceAnimated("Sandbox");let o=!t.yes,{select:r,confirm:a}=await Promise.resolve().then(()=>(B(),U)),s=t.boilerplate;s||(t.ue?s=Ye.ue:o?s=await r({message:"Which boilerplate?",choices:[{name:"Document Authoring (adobe/aem-boilerplate)",value:Ye.document},{name:"Universal Editor / crosswalk (adobe/aem-boilerplate-xwalk)",value:Ye.ue}]}):s=Ye.document);let d=t.private??!1;t.private===void 0&&o&&(d=await r({message:"Visibility?",choices:[{name:"Public",value:!1},{name:"Private",value:!0}],default:!1}));let l=t.org??n.login;if(await Is(n,l,e)){i.error(`A repository ${l}/${e} already exists - refusing to touch it.`),i.info(Z.dim(" Pick another name, or remove it first (e.g. `eds sandbox rm` for a sandbox).")),process.exitCode=1;return}i.info(j("Creating sandbox",`${l}/${e} \xB7 ${s}`));try{if(n.mode==="api"){let c=await zo(n.token,s,{owner:l,name:e,private:d});await Jo(n.token,l,e,[Oe]),i.info(Z.dim(" Cloning...")),await le("git",["clone",c.cloneUrl,e],{stdio:"inherit"})}else{let c=t.org?`${t.org}/${e}`:e;await le("gh",oi(c,{template:s,private:d,clone:!0}),{stdio:"inherit"});try{await le("gh",["repo","edit",`${l}/${e}`,"--add-topic",Oe])}catch{}}}catch(c){i.error(`Create failed: ${c.message}`),process.exitCode=1;return}if(i.info(""),i.info(j("Sandbox ready")),i.info($("repo",`https://github.com/${l}/${e}`)),i.info($("preview",rn(l,e))),i.info(""),o){if(await a({message:"Open the AEM Code Sync install page now?",default:!0})&&await kn(an()),await a({message:`Configure authoring now (eds init in ./${e})?`,default:!0})){let c=process.cwd();try{process.chdir(Ns.join(c,e));let{initProject:u}=await Promise.resolve().then(()=>(Mt(),Ot));await u({})}finally{process.chdir(c)}}}else i.info(Z.dim(` Install AEM Code Sync: ${an()}`)),i.info(Z.dim(` Configure authoring: cd ${e} && eds init`));i.info(""),i.info(L([`Sandbox "${e}" ready - tear down with \`eds sandbox rm ${e}\``]))}async function Gs(){let e=await xn();if(!e)return $n();let t=[];try{if(e.mode==="api")t=await qo(e.token,e.login,Oe);else{let o=await le("gh",["repo","list","--topic",Oe,"--limit","100","--json","nameWithOwner","-q",".[].nameWithOwner"]);t=o?o.split(`
345
- `).filter(Boolean):[]}}catch(o){i.error(`List failed: ${o.message}`),process.exitCode=1;return}if(i.info(j("Sandboxes",`${t.length} tagged ${Oe}`)),t.length===0){i.info(Z.dim(" None yet. Create one with `eds sandbox new <name>`."));return}let n=O(t);for(let o of t){let[r,a]=o.split("/");i.info($(o,rn(r,a),n))}}async function zs(e,t={}){let n=await xn();if(!n)return $n();let o=t.org??n.login,r=`${o}/${e}`;if(!t.yes){let{confirm:a}=await Promise.resolve().then(()=>(B(),U));if(!await a({message:`Permanently delete ${r}? This cannot be undone.`,default:!1})){i.info("Cancelled.");return}}try{n.mode==="api"?await Wo(n.token,o,e):await le("gh",["repo","delete",r,"--yes"])}catch(a){i.error(`Delete failed: ${a.message}`),i.info(Z.dim(" Deleting needs the delete_repo scope (re-run `eds sandbox login`, or `gh auth refresh -s delete_repo`).")),process.exitCode=1;return}i.info(j("Deleted")),i.info($(r,"removed"))}var Se=w(()=>{"use strict";m();R();Ko();ni();ii();I()});import{existsSync as Js}from"fs";import{readFile as Ws}from"fs/promises";import qs from"path";import{parse as Ks}from"yaml";async function Bi(e){let t=qs.join(e,"fstab.yaml");if(Js(t))try{let o=(Ks(await Ws(t,"utf-8"))??{}).mountpoints?.["/"],r=typeof o=="string"?o:o?.url??"",a=r.match(/content\.da\.live\/([^/]+)\/([^/]+)/);return a?{model:"da",org:a[1],site:a[2],mountpoint:r}:/drive\.google\.com/.test(r)?{model:"gdrive",mountpoint:r}:/sharepoint\.com|-my\.sharepoint/.test(r)?{model:"sharepoint",mountpoint:r}:{model:"document",mountpoint:r}}catch{}return{model:"ue"}}var Hi=w(()=>{"use strict";m()});function Xs(e,t,n){let o=n.replace(/^\/+/,"").replace(/\.html$/i,"");return`https://admin.da.live/source/${e}/${t}/${o}.html`}function Gi(e,t,n){let o=n.replace(/^\/+/,"").replace(/\.html$/i,"");return`https://da.live/edit#/${e}/${t}/${o}`}async function zi(e,t,n,o,r){let a=Xs(e,t,n),s=new FormData;s.append("data",new Blob([o],{type:"text/html"}),"content.html");let d={};r&&(d.Authorization=`Bearer ${r}`);let l=await fetch(a,{method:"POST",body:s,headers:d});if(!l.ok)throw new Error(`DA push failed: ${l.status} ${l.statusText}`);return a}var Ji=w(()=>{"use strict";m()});function Vs(e){return` <div class="${e}">
342
+ `});var le={};L(le,{scaffoldBlocks:()=>Vi,scaffoldCi:()=>Yi,scaffoldEnv:()=>Zi,scaffoldHelpers:()=>Qi,scaffoldInteractive:()=>lc,scaffoldUe:()=>Gt,scaffoldXwalk:()=>er});import{existsSync as Ki}from"fs";import{mkdir as Xi,readFile as cc,writeFile as Ee}from"fs/promises";import ne from"path";async function Bt(e){if(!Ki(e))return null;try{return JSON.parse(await cc(e,"utf-8"))}catch{return null}}async function Ht(e,t){await Ee(e,`${JSON.stringify(t,null,2)}
343
+ `)}async function Gt(){let e=P();if(!e){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(E("Scaffold - Universal Editor"));let t=[],n=ne.join(e,"blocks","field-reference");await Xi(n,{recursive:!0}),await Ee(ne.join(n,"field-reference.js"),Wi),await Ee(ne.join(n,"field-reference.css"),Ji),await Ee(ne.join(n,"_field-reference.json"),Pn()),t.push("blocks/field-reference/ (all 17 fields + multifield)");let o=ne.join(e,"component-definition.json"),i=ne.join(e,"component-models.json"),a=ne.join(e,"component-filters.json"),s=[{title:"Field Reference",id:"field-reference",plugins:{xwalk:{page:{resourceType:"core/franklin/components/block/v1/block",template:{name:"Field Reference",model:"field-reference"}}}}}],d=qi(await Bt(o),Gi,s);await Ht(o,d),t.push("component-definition.json (default content + field-reference)");let l=await Bt(i)??[],c=JSON.parse(Pn()).models[0],p=En(l,[...zi,c]);await Ht(i,p),t.push("component-models.json (title / image / button / field-reference)");let m=lt(await Bt(a),["field-reference"]);await Ht(a,m),t.push("component-filters.json (section filter)"),r.info(S("Created / merged"));let u=t.map(w=>w.split(" ")[0]),g=M(u);for(let w of t){let[y,...h]=w.split(" ");r.info(j(y,h.join(" ").replace(/^\((.*)\)$/,"$1"),g))}r.info(""),r.info(O(["Universal Editor scaffold ready"]))}async function Vi(e){let t=P();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(E("Scaffold \u2014 standard blocks"));let n;if(e?.length){n=e.map(c=>$n(c.trim())).filter(c=>!!c);let l=e.filter(c=>!$n(c.trim()));l.length&&r.warn(`Unknown block(s): ${l.join(", ")}. Available: ${Pe.map(c=>c.id).join(", ")}`)}else n=Pe;let o=[],i=[];for(let l of n){let c=ne.join(t,"blocks",l.id);if(Ki(c)){i.push(l.id);continue}await Xi(c,{recursive:!0}),await Ee(ne.join(c,`${l.id}.js`),l.js),await Ee(ne.join(c,`${l.id}.css`),l.css),await Ee(ne.join(c,`_${l.id}.json`),l.model),o.push(l.id)}let a=ne.join(t,"component-filters.json"),s=lt(await Bt(a),n.map(l=>l.id));await Ht(a,s),r.info(S("Blocks"));let d=M([...o,...i,"component-filters"]);for(let l of o)r.info(j(l,"created",d));for(let l of i)r.info(A("warn",l,"already exists \u2014 skipped",d));r.info(""),r.info(O([`${o.length} block(s) scaffolded + registered`]))}async function Yi(){let e=P();if(!e){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(E("Scaffold - CI workflow"));let t=await Nt(e);r.info(S("GitHub Actions")),t.created?r.info(j(t.path,"doctor + audit loading + audit security + lint/build")):r.info(A("warn",t.path,"already exists - skipped")),r.info(""),r.info(O([t.created?"CI workflow scaffolded - commit it and it runs on every PR":"CI workflow left untouched"]))}async function Qi(e){let t=P();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(E("Scaffold - helpers"));let n=e?.length?e:void 0;if(!n)if(process.stdout.isTTY){let{checkbox:i}=await Promise.resolve().then(()=>(G(),H));n=await i({message:"Which helpers?",choices:ct.map(a=>({name:a.label,value:a.id,checked:!0}))})}else n=jn;if(!n.length){r.info("Nothing selected.");return}let o=await Bi(t,n);r.info(S("Helpers")),o.created?r.info(j(o.path,o.helpers.join(", "))):r.info(A("warn",o.path,"already exists - skipped")),r.info(""),r.info(O([o.created?`${o.helpers.length} helper(s) -> scripts/utils.js`:"Helpers left untouched"]))}async function Zi(e={}){let t=P();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(E("Scaffold - .env"));let n=e.pagesUrl;if(n===void 0)try{let{execa:s}=await import("execa"),d=await s("git",["remote","get-url","origin"],{cwd:t}),l=He(d.stdout.trim());n=l?`https://${Ge(l.owner,l.repo)}`:""}catch{n=""}let o=e.open??"/",i=e.port??"3007";if(!e.yes&&process.stdout.isTTY){let{input:s}=await Promise.resolve().then(()=>(G(),H));o=await s({message:"AEM_OPEN (path opened on start)",default:o}),i=await s({message:"AEM_PORT",default:String(i)}),n=await s({message:"AEM_PAGES_URL (content origin)",default:n})}let a=await Mt(t,{open:o,port:i,pagesUrl:n});r.info(S(".env")),a.created?r.info(j(a.path,`AEM_OPEN=${o} AEM_PORT=${i}`)):r.info(A("warn",a.path,"already exists - left untouched")),a.gitignoreUpdated&&r.info(j(".gitignore","added .env")),r.info(""),r.info(O([a.created?".env ready for `aem up`":".env left untouched"]))}async function er(){let e=P();if(!e){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(E("Scaffold - xwalk.json"));let t=await _t(e);r.info(S("xwalk.json")),t.created?r.info(j(t.path,"multi-field enabled")):r.info(A("warn",t.path,"already exists - left untouched")),r.info(""),r.info(O([t.created?"xwalk.json ready (UE multi-field)":"xwalk.json left untouched"]))}async function lc(){let{select:e,checkbox:t}=await Promise.resolve().then(()=>(G(),H));r.logoOnce(E("Scaffold"));let n=await e({message:"What do you want to scaffold?",choices:[{name:"Universal Editor config + field-reference (all 17 field types)",value:"ue"},{name:"Standard blocks (hero, cards, columns, accordion, embed)",value:"blocks"},{name:"GitHub Actions CI (doctor + audits + lint/build)",value:"ci"},{name:"Helper functions (scripts/utils.js)",value:"helpers"},{name:"Local-dev .env (aem up: port / open / pages URL)",value:"env"},{name:"xwalk.json (enable Universal Editor multi-field)",value:"xwalk"},{name:"UE config + standard blocks",value:"both"}]});if(n==="env")return Zi();if(n==="xwalk")return er();if((n==="ue"||n==="both")&&await Gt(),n==="blocks"||n==="both"){let o=await t({message:"Which blocks?",choices:Pe.map(i=>({name:i.title,value:i.id,checked:!0}))});await Vi(o)}n==="ci"&&await Yi(),n==="helpers"&&await Qi()}var ae=v(()=>{"use strict";f();R();B();Sn();yn();vn();Hi();Cn();kn();Ut();N()});var Wt={};L(Wt,{initProject:()=>fc});import{existsSync as Tn}from"fs";import{readFile as Rn,writeFile as tr}from"fs/promises";import zt from"path";import An from"chalk";async function dc(e){try{let{execa:t}=await import("execa"),n=await t("git",["remote","get-url","origin"],{cwd:e}),o=He(n.stdout.trim());return o?`https://${Ge(o.owner,o.repo)}`:""}catch{return""}}async function pc(e,t){let n=zt.join(e,"package.json");if(!Tn(n))return!1;try{let o=JSON.parse(await Rn(n,"utf-8"));return o.name=t,await tr(n,`${JSON.stringify(o,null,2)}
344
+ `),!0}catch{return!1}}async function mc(e,t){let n=[];for(let o of["README.md","index.html","head.html"]){let i=zt.join(e,o);if(Tn(i))try{let a=await Rn(i,"utf-8"),s=a.replace(/aem-boilerplate/gi,t);s!==a&&(await tr(i,s),n.push(o))}catch{}}return n}async function uc(e){let{confirm:t}=await Promise.resolve().then(()=>(G(),H)),n=[{title:"Install the AEM Code Sync GitHub app",url:"https://github.com/apps/aem-code-sync/installations/new",note:"Connects your repo to the Edge Delivery pipeline (preview/publish)."}];e==="gdrive"&&n.push({title:"Share your content folder",note:"Share the Google Drive folder with the AEM service and set it as the mountpoint."}),e==="sharepoint"&&n.push({title:"Share your content folder",note:"Grant the SharePoint/OneDrive folder to the AEM service account."}),e==="da"&&n.push({title:"Author in DA",url:"https://da.live",note:"Create documents at da.live."}),e==="ue"&&n.push({title:"Open the Universal Editor",url:"https://experience.adobe.com",note:"Author in-context once the repo is connected to AEM."}),n.push({title:"Install the AEM Sidekick extension",url:"https://chromewebstore.google.com/detail/aem-sidekick/igkmdomcgoebiipaifhmpfjhbjccggml",note:"Preview and publish from the browser."}),n.push({title:"Run the local dev server",note:"npm install, then `aem up` (from @adobe/aem-cli)."}),r.info(S("Next steps (outside the repo)"));for(let o=0;o<n.length;o++){let i=n[o];r.info(` ${_.accent(String(o+1))} ${An.bold(i.title)}`),i.url&&r.info(` ${An.cyan(i.url)}`),r.info(` ${An.dim(i.note)}`),await t({message:" Done / skip?",default:!0})}}async function fc(e={}){let t=P();if(!t){r.error("Not inside an EDS project (no EDS project markers found). Clone an EDS boilerplate first, then run this from its root."),process.exitCode=1;return}await r.logoOnceAnimated("Project setup");let{input:n,select:o,confirm:i}=await Promise.resolve().then(()=>(G(),H)),a=!e.yes,s=zt.basename(t),d=zt.join(t,"package.json");if(Tn(d))try{s=JSON.parse(await Rn(d,"utf-8")).name||s}catch{}let l=e.name&&dt(e.name)||dt(await n({message:"1/4 Project name",default:dt(s),validate:y=>!!dt(y)||"Use letters, numbers and dashes"})),c=e.authoring??await o({message:"2/4 Authoring model",choices:[{name:je.ue,value:"ue"},{name:je.da,value:"da"},{name:je.gdrive,value:"gdrive"},{name:je.sharepoint,value:"sharepoint"}]}),p=e.mountpoint;if(It(c)&&!p)if(c==="da"&&(e.org||a)){let y=e.org??await n({message:" DA org",validate:$=>!!$.trim()||"Required"}),h=e.site??(a?await n({message:" DA site",default:l}):l);p=Ti(y.trim(),dt(h))}else c!=="da"&&a&&(p=(await n({message:` ${c==="gdrive"?"Google Drive folder URL":"SharePoint folder URL"}`,validate:h=>/^https?:\/\//.test(h.trim())||"Paste the folder URL"})).trim());let m=e.ci??(a?await i({message:"4/4 Add GitHub Actions CI (audits gatekeeper)?",default:!0}):!0);r.info(S("Summary"));let u=M(["name","authoring","mountpoint","ci"]);if(r.info(j("name",l,u)),r.info(j("authoring",je[c],u)),p?r.info(j("mountpoint",p,u)):It(c)&&r.info(j("mountpoint","(skipped - set it in fstab.yaml later)",u)),r.info(j("ci",m?"yes":"no",u)),r.info(""),a&&!await i({message:"Apply this setup?",default:!0})){r.info("Cancelled.");return}let g=[];await pc(t,l)&&g.push("package.json (name)");for(let y of await mc(t,l))g.push(`${y} (renamed)`);if(It(c)&&p&&g.push(await Ri(t,p)),c==="ue"&&(await Gt(),g.push(await Fi(t,l))),m){let y=await Nt(t);g.push(y.created?y.path:`${y.path} (exists, skipped)`)}if(e.env!==!1){let y=await Mt(t,{pagesUrl:await dc(t)});g.push(y.created?".env (aem up config)":".env (exists, skipped)")}if(e.xwalk!==!1&&c==="ue"){let y=await _t(t);g.push(y.created?`${y.path} (UE multi-field)`:`${y.path} (exists, skipped)`)}r.info(S("Configured"));let w=M(g.map(y=>y.split(" ")[0]));for(let y of g){let[h,...$]=y.split(" ");r.info(j(h,$.join(" ").replace(/^\((.*)\)$/,"$1"),w))}r.info(""),a&&await uc(c),r.info(O([`"${l}" set up for ${je[c]}`]))}var dt,Jt=v(()=>{"use strict";f();R();B();yn();vn();Di();kn();Ut();N();ae();dt=e=>e.trim().toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"")});var Ce={};L(Ce,{sandboxList:()=>kc,sandboxLogin:()=>bc,sandboxLogout:()=>yc,sandboxNew:()=>vc,sandboxRm:()=>xc});import gc from"path";import Z from"chalk";async function de(e,t,n={}){let{execa:o}=await import("execa");return((await o(e,t,n)).stdout??"").toString().trim()}async function Fn(e){let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{await de(t,[e],{stdio:"ignore"})}catch{}}async function hc(){try{return await de("gh",["auth","status"]),await de("gh",["api","user","-q",".login"])}catch{return null}}async function Dn(){let e=await ui();if(e)try{return{mode:"api",token:e,login:await Dt(e)}}catch{}let t=await hc();return t?{mode:"gh",login:t}:null}async function wc(e,t,n){if(e.mode==="api")return ii(e.token,t,n);try{return await de("gh",["repo","view",`${t}/${n}`,"--json","name"]),!0}catch{return!1}}function Ln(){r.error("Not authenticated with GitHub."),r.info(" Run `eds sandbox login` to authorize GitHub, or install + `gh auth login`."),process.exitCode=1}async function bc(){await r.logoOnceAnimated("Sandbox - GitHub login");let{input:e}=await Promise.resolve().then(()=>(G(),H));if(Lt){let n=await gi(["repo","delete_repo"]);r.info(S("Authorize GitHub")),r.info(j("code",n.user_code)),r.info(j("open",n.verification_uri)),r.info(""),await Fn(n.verification_uri),r.info(Z.dim(" Waiting for you to authorize in the browser..."));try{let o=await hi(n.device_code,n.interval,n.expires_in);await gn(o),r.success(`Authorized as ${await Dt(o)}.`)}catch(o){r.error(`Device flow failed: ${o.message}`),process.exitCode=1}return}r.info(S("Authorize GitHub (least-privilege token)")),r.info(" Create a fine-grained token limited to your sandboxes only:"),r.info(` ${Z.cyan("https://github.com/settings/personal-access-tokens/new")}`),r.info(Z.dim(" - Resource owner: a dedicated sandbox org (recommended) or your account")),r.info(Z.dim(" - Repository access: All repositories in that org (to create new sandboxes),")),r.info(Z.dim(" or Only select repositories to manage existing ones")),r.info(Z.dim(" - Permissions: Administration = Read and write, Contents = Read and write,")),r.info(Z.dim(" Metadata = Read. Set a short expiry.")),r.info(Z.dim(" Tip: `eds sandbox new --org <sandbox-org>` so nothing in your personal account is touched.")),r.info(""),await(await Promise.resolve().then(()=>(G(),H))).confirm({message:"Open the token page?",default:!0})&&await Fn("https://github.com/settings/personal-access-tokens/new");let t=(await e({message:"Paste the token",validate:n=>!!n.trim()||"Required"})).trim();try{let n=await Dt(t);await gn(t),r.success(`Authorized as ${n}.`)}catch{r.error("That token didn't work (check the scopes)."),process.exitCode=1}}async function yc(){await fi(),r.success("Signed out (stored GitHub token removed).")}async function vc(e,t={}){let n=await Dn();if(!n)return Ln();await r.logoOnceAnimated("Sandbox");let o=!t.yes,{select:i,confirm:a}=await Promise.resolve().then(()=>(G(),H)),s=t.boilerplate;s||(t.ue?s=rt.ue:o?s=await i({message:"Which boilerplate?",choices:[{name:"Document Authoring (adobe/aem-boilerplate)",value:rt.document},{name:"Universal Editor / crosswalk (adobe/aem-boilerplate-xwalk)",value:rt.ue}]}):s=rt.document);let d=t.private??!1;t.private===void 0&&o&&(d=await i({message:"Visibility?",choices:[{name:"Public",value:!1},{name:"Private",value:!0}],default:!1}));let l=t.org??n.login;if(await wc(n,l,e)){r.error(`A repository ${l}/${e} already exists - refusing to touch it.`),r.info(Z.dim(" Pick another name, or remove it first (e.g. `eds sandbox rm` for a sandbox).")),process.exitCode=1;return}r.info(S("Creating sandbox",`${l}/${e} \xB7 ${s}`));try{if(n.mode==="api"){let c=await ri(n.token,s,{owner:l,name:e,private:d});await ai(n.token,l,e,[Ue]),r.info(Z.dim(" Cloning...")),await de("git",["clone",c.cloneUrl,e],{stdio:"inherit"})}else{let c=t.org?`${t.org}/${e}`:e;await de("gh",bi(c,{template:s,private:d,clone:!0}),{stdio:"inherit"});try{await de("gh",["repo","edit",`${l}/${e}`,"--add-topic",Ue])}catch{}}}catch(c){r.error(`Create failed: ${c.message}`),process.exitCode=1;return}if(r.info(""),r.info(S("Sandbox ready")),r.info(j("repo",`https://github.com/${l}/${e}`)),r.info(j("preview",hn(l,e))),r.info(""),o){if(await a({message:"Open the AEM Code Sync install page now?",default:!0})&&await Fn(wn()),await a({message:`Configure authoring now (eds init in ./${e})?`,default:!0})){let c=process.cwd();try{process.chdir(gc.join(c,e));let{initProject:p}=await Promise.resolve().then(()=>(Jt(),Wt));await p({})}finally{process.chdir(c)}}}else r.info(Z.dim(` Install AEM Code Sync: ${wn()}`)),r.info(Z.dim(` Configure authoring: cd ${e} && eds init`));r.info(""),r.info(O([`Sandbox "${e}" ready - tear down with \`eds sandbox rm ${e}\``]))}async function kc(){let e=await Dn();if(!e)return Ln();let t=[];try{if(e.mode==="api")t=await ci(e.token,e.login,Ue);else{let o=await de("gh",["repo","list","--topic",Ue,"--limit","100","--json","nameWithOwner","-q",".[].nameWithOwner"]);t=o?o.split(`
345
+ `).filter(Boolean):[]}}catch(o){r.error(`List failed: ${o.message}`),process.exitCode=1;return}if(r.info(S("Sandboxes",`${t.length} tagged ${Ue}`)),t.length===0){r.info(Z.dim(" None yet. Create one with `eds sandbox new <name>`."));return}let n=M(t);for(let o of t){let[i,a]=o.split("/");r.info(j(o,hn(i,a),n))}}async function xc(e,t={}){let n=await Dn();if(!n)return Ln();let o=t.org??n.login,i=`${o}/${e}`;if(!t.yes){let{confirm:a}=await Promise.resolve().then(()=>(G(),H));if(!await a({message:`Permanently delete ${i}? This cannot be undone.`,default:!1})){r.info("Cancelled.");return}}try{n.mode==="api"?await si(n.token,o,e):await de("gh",["repo","delete",i,"--yes"])}catch(a){r.error(`Delete failed: ${a.message}`),r.info(Z.dim(" Deleting needs the delete_repo scope (re-run `eds sandbox login`, or `gh auth refresh -s delete_repo`).")),process.exitCode=1;return}r.info(S("Deleted")),r.info(j(i,"removed"))}var Ae=v(()=>{"use strict";f();R();li();wi();yi();N()});import{existsSync as $c}from"fs";import{readFile as Sc}from"fs/promises";import jc from"path";import{parse as Pc}from"yaml";async function nr(e){let t=jc.join(e,"fstab.yaml");if($c(t))try{let o=(Pc(await Sc(t,"utf-8"))??{}).mountpoints?.["/"],i=typeof o=="string"?o:o?.url??"",a=i.match(/content\.da\.live\/([^/]+)\/([^/]+)/);return a?{model:"da",org:a[1],site:a[2],mountpoint:i}:/drive\.google\.com/.test(i)?{model:"gdrive",mountpoint:i}:/sharepoint\.com|-my\.sharepoint/.test(i)?{model:"sharepoint",mountpoint:i}:{model:"document",mountpoint:i}}catch{}return{model:"ue"}}var or=v(()=>{"use strict";f()});function Ec(e,t,n){let o=n.replace(/^\/+/,"").replace(/\.html$/i,"");return`https://admin.da.live/source/${e}/${t}/${o}.html`}function ir(e,t,n){let o=n.replace(/^\/+/,"").replace(/\.html$/i,"");return`https://da.live/edit#/${e}/${t}/${o}`}async function rr(e,t,n,o,i){let a=Ec(e,t,n),s=new FormData;s.append("data",new Blob([o],{type:"text/html"}),"content.html");let d={};i&&(d.Authorization=`Bearer ${i}`);let l=await fetch(a,{method:"POST",body:s,headers:d});if(!l.ok)throw new Error(`DA push failed: ${l.status} ${l.statusText}`);return a}var ar=v(()=>{"use strict";f()});function Cc(e){return` <div class="${e}">
346
346
  <div>
347
347
  <div>${e} content</div>
348
348
  </div>
349
- </div>`}function Ys(e){let t=[` <div><div>Title</div><div>${e.title}</div></div>`,` <div><div>Description</div><div>${e.description??""}</div></div>`];return e.area&&t.push(` <div><div>Template</div><div>${e.area}</div></div>`),` <div class="metadata">
349
+ </div>`}function Ac(e){let t=[` <div><div>Title</div><div>${e.title}</div></div>`,` <div><div>Description</div><div>${e.description??""}</div></div>`];return e.area&&t.push(` <div><div>Template</div><div>${e.area}</div></div>`),` <div class="metadata">
350
350
  ${t.join(`
351
351
  `)}
352
- </div>`}function Wi(e){let t=e.blocks??[],n=` <div>
352
+ </div>`}function sr(e){let t=e.blocks??[],n=` <div>
353
353
  <h1>${e.title}</h1>
354
354
  <p>${e.description??"Intro copy goes here."}</p>
355
355
  </div>`,o=t.map(a=>` <div>
356
- ${Vs(a)}
357
- </div>`),r=` <div>
358
- ${Ys(e)}
356
+ ${Cc(a)}
357
+ </div>`),i=` <div>
358
+ ${Ac(e)}
359
359
  </div>`;return`<body>
360
360
  <header></header>
361
361
  <main>
362
- ${[n,...o,r].join(`
362
+ ${[n,...o,i].join(`
363
363
  `)}
364
364
  </main>
365
365
  <footer></footer>
366
366
  </body>
367
- `}var qi=w(()=>{"use strict";m()});import{existsSync as Qs}from"fs";import{readFile as Zs}from"fs/promises";import ec from"path";function tc(e){if(e.value!==void 0)return e.value;switch(e.valueType){case"boolean":return!1;case"number":return 0;case"string[]":return[];default:return""}}async function nc(e,t){let n=ec.join(e,"blocks",t,`_${t}.json`);if(!Qs(n))return{};try{let o=JSON.parse(await Zs(n,"utf-8")),r=Array.isArray(o.models)?o.models:[],s=(r.find(l=>l.id===t)??r[0])?.fields??[],d={};for(let l of s)l.component!=="tab"&&(d[l.name]=l.component==="container"?[]:tc(l));return d}catch{return{}}}async function Ki(e,t){let n=[];for(let r of t.blocks)n.push({name:r,model:r,fields:await nc(e,r)});let o={title:t.title,template:t.name,components:n};return`${JSON.stringify(o,null,2)}
368
- `}var Xi=w(()=>{"use strict";m()});var En={};N(En,{templateNew:()=>lc});import{existsSync as jn}from"fs";import{mkdir as oc,readFile as Vi,readdir as ic,writeFile as Sn}from"fs/promises";import me from"path";import ot from"chalk";async function ac(e){let t=me.join(e,"blocks");return jn(t)?(await ic(t,{withFileTypes:!0})).filter(n=>n.isDirectory()).map(n=>n.name):[]}async function sc(e){let t=me.join(e,".edsrc.json");if(!jn(t))return{};try{return JSON.parse(await Vi(t,"utf-8")).admin??{}}catch{return{}}}async function cc(e,t){if(!t.length)return!1;let n=me.join(e,"component-filters.json"),o=null;if(jn(n))try{o=JSON.parse(await Vi(n,"utf-8"))}catch{o=null}let r=tt(o,t);return await Sn(n,`${JSON.stringify(r,null,2)}
369
- `),!0}async function lc(e,t={}){let n=E();if(!n){i.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}await i.logoOnceAnimated("Page template");let{input:o,select:r,confirm:a}=await Promise.resolve().then(()=>(B(),U)),s=!t.yes,d=await Bi(n),l=t.authoring??d.model,c=rc(e),u=t.title??(s?await o({message:"Page title",default:e}):e),p=t.description??(s?await o({message:"Description (optional)"}):""),f=t.path??`/templates/${c}`,g=t.blocks;if(!g&&s){let S=await ac(n),x=S.length?S:ke.map(H=>H.id),T=[],oe=!0;for(;oe;){let H=await r({message:`Add a block in order (${T.length} so far)`,choices:[...x.map(q=>({name:q,value:q})),{name:T.length?"- done -":"- done (empty page) -",value:"__done"}]});H==="__done"?oe=!1:T.push(H)}g=T}let y=g??[],h=Wi({title:u,description:p||void 0,blocks:y,area:t.area}),b=me.join("templates",`${c}.html`);if(await oc(me.join(n,"templates"),{recursive:!0}),await Sn(me.join(n,b),h),i.info(j("Page template",`${f} \xB7 ${l}`)),i.info($(b,`${y.length} block(s) + metadata`)),l==="da"){let S=await sc(n),x=t.org??S.org??d.org,T=t.site??S.site??d.site;if(t.push??(s?await a({message:"Push to DA (da.live)?",default:!0}):!0))if(!x||!T)i.warn("No DA org/site. Pass --org/--site or set admin in .edsrc.json.");else try{await zi(x,T,f,h,process.env.DA_TOKEN),i.info($("pushed to DA",Gi(x,T,f)))}catch(H){i.error(`DA push failed: ${H.message}`),i.info(ot.dim(" Open projects allow anonymous writes; others need DA_TOKEN."))}}else if(l==="gdrive"||l==="sharepoint"){let S=l==="gdrive"?"a Google Doc":"a Word doc";i.info(""),i.info(ot.dim(` Document model: import ${b} into ${S} in your mounted folder,`)),i.info(ot.dim(" then preview/publish. (Share the folder + install aem-code-sync first.)"))}else if(l==="ue"){let S=me.join("templates",`${c}.json`);await Sn(me.join(n,S),await Ki(n,{title:u,name:c,blocks:y})),i.info($(S,`initial content (${y.length} component(s), in order)`)),await cc(n,y)&&i.info($("component-filters.json","seeded blocks allowed in Universal Editor")),i.info(""),i.info(ot.dim(" Universal Editor: use the template JSON as the page's initial content, then")),i.info(ot.dim(" author it in the Universal Editor (wire the repo to AEM)."))}i.info(""),i.info(L([`"${c}" template (${l}) - preview with \`eds preview ${f}\``]))}var rc,Pn=w(()=>{"use strict";m();R();z();un();bn();Hi();Ji();qi();Xi();I();rc=e=>e.trim().toLowerCase().replace(/[^a-z0-9-/]+/g,"-").replace(/^-+|-+$/g,"")});import{existsSync as Nt}from"fs";import{readFile as Yi,readdir as Qi}from"fs/promises";import je from"path";async function dc(e){let t=[],n=async o=>{for(let r of await Qi(o,{withFileTypes:!0})){let a=je.join(o,r.name);r.isDirectory()?await n(a):t.push(a)}};return Nt(e)&&await n(e),t}async function Zi(e){if(!Nt(e))return null;let t=await Qi(e,{withFileTypes:!0}),n=t.find(r=>r.isDirectory()&&/clientlib/i.test(r.name));return n?je.join(e,n.name):t.some(r=>r.isFile()&&r.name.endsWith(".css"))?e:null}async function er(e){let t=await dc(e),n=t.filter(s=>/\.(less|scss|sass)$/i.test(s)).map(s=>je.relative(e,s)),o,r=je.join(e,"css.txt");if(Nt(r)){let s=(await Yi(r,"utf-8")).split(`
370
- `).map(c=>c.trim()),d=e,l=[];for(let c of s){if(!c)continue;let u=c.match(/^#base\s*=\s*(.+)$/);u?d=je.join(e,u[1].trim()):c.startsWith("#")||l.push(c)}o=l.map(c=>je.join(d,c)).filter(c=>Nt(c)&&c.endsWith(".css"))}else o=t.filter(s=>s.endsWith(".css"));let a=[];for(let s of o)a.push(await Yi(s,"utf-8"));return{css:a.join(`
367
+ `}var cr=v(()=>{"use strict";f()});import{existsSync as Tc}from"fs";import{readFile as Rc}from"fs/promises";import Fc from"path";function Dc(e){if(e.value!==void 0)return e.value;switch(e.valueType){case"boolean":return!1;case"number":return 0;case"string[]":return[];default:return""}}async function Lc(e,t){let n=Fc.join(e,"blocks",t,`_${t}.json`);if(!Tc(n))return{};try{let o=JSON.parse(await Rc(n,"utf-8")),i=Array.isArray(o.models)?o.models:[],s=(i.find(l=>l.id===t)??i[0])?.fields??[],d={};for(let l of s)l.component!=="tab"&&(d[l.name]=l.component==="container"?[]:Dc(l));return d}catch{return{}}}async function lr(e,t){let n=[];for(let i of t.blocks)n.push({name:i,model:i,fields:await Lc(e,i)});let o={title:t.title,template:t.name,components:n};return`${JSON.stringify(o,null,2)}
368
+ `}var dr=v(()=>{"use strict";f()});var Mn={};L(Mn,{templateNew:()=>Bc});import{existsSync as Nn}from"fs";import{mkdir as Oc,readFile as pr,readdir as Nc,writeFile as On}from"fs/promises";import he from"path";import pt from"chalk";async function Ic(e){let t=he.join(e,"blocks");return Nn(t)?(await Nc(t,{withFileTypes:!0})).filter(n=>n.isDirectory()).map(n=>n.name):[]}async function _c(e){let t=he.join(e,".edsrc.json");if(!Nn(t))return{};try{return JSON.parse(await pr(t,"utf-8")).admin??{}}catch{return{}}}async function Uc(e,t){if(!t.length)return!1;let n=he.join(e,"component-filters.json"),o=null;if(Nn(n))try{o=JSON.parse(await pr(n,"utf-8"))}catch{o=null}let i=lt(o,t);return await On(n,`${JSON.stringify(i,null,2)}
369
+ `),!0}async function Bc(e,t={}){let n=P();if(!n){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}await r.logoOnceAnimated("Page template");let{input:o,select:i,confirm:a}=await Promise.resolve().then(()=>(G(),H)),s=!t.yes,d=await nr(n),l=t.authoring??d.model,c=Mc(e),p=t.title??(s?await o({message:"Page title",default:e}):e),m=t.description??(s?await o({message:"Description (optional)"}):""),u=t.path??`/templates/${c}`,g=t.blocks;if(!g&&s){let $=await Ic(n),b=$.length?$:Pe.map(z=>z.id),T=[],Q=!0;for(;Q;){let z=await i({message:`Add a block in order (${T.length} so far)`,choices:[...b.map(ue=>({name:ue,value:ue})),{name:T.length?"- done -":"- done (empty page) -",value:"__done"}]});z==="__done"?Q=!1:T.push(z)}g=T}let w=g??[],y=sr({title:p,description:m||void 0,blocks:w,area:t.area}),h=he.join("templates",`${c}.html`);if(await Oc(he.join(n,"templates"),{recursive:!0}),await On(he.join(n,h),y),r.info(S("Page template",`${u} \xB7 ${l}`)),r.info(j(h,`${w.length} block(s) + metadata`)),l==="da"){let $=await _c(n),b=t.org??$.org??d.org,T=t.site??$.site??d.site;if(t.push??(s?await a({message:"Push to DA (da.live)?",default:!0}):!0))if(!b||!T)r.warn("No DA org/site. Pass --org/--site or set admin in .edsrc.json.");else try{await rr(b,T,u,y,process.env.DA_TOKEN),r.info(j("pushed to DA",ir(b,T,u)))}catch(z){r.error(`DA push failed: ${z.message}`),r.info(pt.dim(" Open projects allow anonymous writes; others need DA_TOKEN."))}}else if(l==="gdrive"||l==="sharepoint"){let $=l==="gdrive"?"a Google Doc":"a Word doc";r.info(""),r.info(pt.dim(` Document model: import ${h} into ${$} in your mounted folder,`)),r.info(pt.dim(" then preview/publish. (Share the folder + install aem-code-sync first.)"))}else if(l==="ue"){let $=he.join("templates",`${c}.json`);await On(he.join(n,$),await lr(n,{title:p,name:c,blocks:w})),r.info(j($,`initial content (${w.length} component(s), in order)`)),await Uc(n,w)&&r.info(j("component-filters.json","seeded blocks allowed in Universal Editor")),r.info(""),r.info(pt.dim(" Universal Editor: use the template JSON as the page's initial content, then")),r.info(pt.dim(" author it in the Universal Editor (wire the repo to AEM)."))}r.info(""),r.info(O([`"${c}" template (${l}) - preview with \`eds preview ${u}\``]))}var Mc,In=v(()=>{"use strict";f();R();B();Sn();Cn();or();ar();cr();dr();N();Mc=e=>e.trim().toLowerCase().replace(/[^a-z0-9-/]+/g,"-").replace(/^-+|-+$/g,"")});import{existsSync as qt}from"fs";import{readFile as mr,readdir as ur}from"fs/promises";import Te from"path";async function Hc(e){let t=[],n=async o=>{for(let i of await ur(o,{withFileTypes:!0})){let a=Te.join(o,i.name);i.isDirectory()?await n(a):t.push(a)}};return qt(e)&&await n(e),t}async function fr(e){if(!qt(e))return null;let t=await ur(e,{withFileTypes:!0}),n=t.find(i=>i.isDirectory()&&/clientlib/i.test(i.name));return n?Te.join(e,n.name):t.some(i=>i.isFile()&&i.name.endsWith(".css"))?e:null}async function gr(e){let t=await Hc(e),n=t.filter(s=>/\.(less|scss|sass)$/i.test(s)).map(s=>Te.relative(e,s)),o,i=Te.join(e,"css.txt");if(qt(i)){let s=(await mr(i,"utf-8")).split(`
370
+ `).map(c=>c.trim()),d=e,l=[];for(let c of s){if(!c)continue;let p=c.match(/^#base\s*=\s*(.+)$/);p?d=Te.join(e,p[1].trim()):c.startsWith("#")||l.push(c)}o=l.map(c=>Te.join(d,c)).filter(c=>qt(c)&&c.endsWith(".css"))}else o=t.filter(s=>s.endsWith(".css"));let a=[];for(let s of o)a.push(await mr(s,"utf-8"));return{css:a.join(`
371
371
 
372
- `),files:o.map(s=>je.relative(e,s)),preprocessed:n}}var tr=w(()=>{"use strict";m()});import{XMLParser as pc}from"fast-xml-parser";function it(e){return Object.keys(e).find(t=>t!==":@")??""}function ue(e){let t=it(e),n=e[t];return Array.isArray(n)?n:[]}function mc(e){return e[":@"]??{}}function uc(e){return typeof e=="string"?e.replace(/^\{[^}]+\}/,""):e}function Y(e,t){return uc(mc(e)[`@_${t}`])}function fc(e,t){let n=Y(t,"multiple")==="true"||Y(t,"multiple")==="{Boolean}true";return e.endsWith("/form/textfield")?"text":e.endsWith("/form/textarea")?"textarea":e.includes("/richtext")?"richtext":e.endsWith("/form/numberfield")?"number":e.endsWith("/form/checkbox")?"boolean":e.endsWith("/form/radiogroup")?"radio-group":e.endsWith("/form/select")?n?"multiselect":"select":e.endsWith("/form/datepicker")?"date-time":e.endsWith("/form/pathfield")||e.endsWith("/form/pathbrowser")?"aem-content":e.includes("/fileupload")||e.endsWith("/form/fileupload")?"reference":e.includes("tagfield")||e.includes("tagpicker")||e.includes("tagbrowser")?"aem-tag":e.includes("contentfragment")?"aem-content-fragment":e.includes("experiencefragment")?"aem-experience-fragment":null}function gc(e){return e.includes("/foundation/container")||e.includes("/foundation/fixedcolumns")||e.includes("/foundation/well")||e.includes("/foundation/tabs")||e.includes("/foundation/form/fieldset")||e.includes("/foundation/accordion")}function hc(e){switch(e){case"number":return"number";case"boolean":return"boolean";case"date-time":return"date";case"checkbox-group":return"string[]";case"aem-content":case"aem-content-fragment":case"aem-experience-fragment":return;default:return"string"}}function Cn(e,t){return(e??"").replace(/^\.\//,"").trim()||t}function bc(e){let t=ue(e).find(n=>it(n)==="items");return t?ue(t).map(n=>{let o=Y(n,"value")??"";return{name:Y(n,"text")??Y(n,"jcr:title")??o,value:o}}):[]}function _t(e,t,n,o){for(let r of e){let a=Y(r,"sling:resourceType")??"";if(a.endsWith("/foundation/tabs")){let d=ue(r).find(l=>it(l)==="items");for(let l of d?ue(d):[]){let c=Y(l,"jcr:title");t.push({component:"tab",name:Cn(void 0,it(l)),label:c}),_t(ue(l),t,n,o)}continue}if(a.endsWith("/form/multifield")){let d=[];_t(ue(r),d,n,o);let l=Cn(Y(r,"name"),`items${o.i++}`);t.push({component:"container",name:l,label:Y(r,"fieldLabel")??"Items",multi:!0,collapsible:!0,fields:d});continue}let s=a?fc(a,r):null;if(s){let d=Cn(Y(r,"name"),`field${o.i++}`),l={component:s,name:d},c=hc(s);c&&(l.valueType=c);let u=Y(r,"fieldLabel")??Y(r,"text");if(u&&(l.label=u),s==="select"||s==="radio-group"||s==="multiselect"){let f=bc(r);f.length&&(l.options=f)}let p=Y(r,"value")??(s==="boolean"?Y(r,"checked"):void 0);p!==void 0&&p!==""&&(l.value=s==="boolean"?p==="true":p),t.push(l);continue}a&&Y(r,"name")&&!gc(a)&&n.add(a),_t(ue(r),t,n,o)}}function nr(e){let o=new pc({ignoreAttributes:!1,attributeNamePrefix:"@_",preserveOrder:!0,removeNSPrefix:!1,trimValues:!0}).parse(e).find(s=>it(s)==="jcr:root"),r=[],a=new Set;return o&&_t(ue(o),r,a,{i:1}),{fields:r,unmapped:[...a]}}var or=w(()=>{"use strict";m()});import{existsSync as ir}from"fs";import{readFile as rr}from"fs/promises";import It from"path";import{XMLParser as wc}from"fast-xml-parser";function An(e){return[It.join(e,"_cq_dialog",".content.xml"),It.join(e,"_cq_dialog.xml"),It.join(e,"cq:dialog",".content.xml")].find(n=>ir(n))??null}async function ar(e){let t=It.join(e,".content.xml");if(ir(t))try{let a=(new wc({ignoreAttributes:!1,attributeNamePrefix:"@_"}).parse(await rr(t,"utf-8"))["jcr:root"]??{})["@_jcr:title"];return typeof a=="string"?a.replace(/^\{[^}]+\}/,""):void 0}catch{return}}async function sr(e){let t=An(e);return t?nr(await rr(t,"utf-8")):null}function cr(e,t,n){return`${JSON.stringify({definitions:[{title:t,id:e,plugins:{xwalk:{page:{resourceType:"core/franklin/components/block/v1/block",template:{name:t,model:e}}}}}],models:[{id:e,fields:n}],filters:[]},null,2)}
373
- `}function lr(e,t){let o=t.some(r=>r.component==="container"&&r.multi)?` // This block was migrated from a classic AEM component with a multifield.
372
+ `),files:o.map(s=>Te.relative(e,s)),preprocessed:n}}var hr=v(()=>{"use strict";f()});import{XMLParser as Gc}from"fast-xml-parser";function mt(e){return Object.keys(e).find(t=>t!==":@")??""}function we(e){let t=mt(e),n=e[t];return Array.isArray(n)?n:[]}function zc(e){return e[":@"]??{}}function Wc(e){return typeof e=="string"?e.replace(/^\{[^}]+\}/,""):e}function V(e,t){return Wc(zc(e)[`@_${t}`])}function Jc(e,t){let n=V(t,"multiple")==="true"||V(t,"multiple")==="{Boolean}true";return e.endsWith("/form/textfield")?"text":e.endsWith("/form/textarea")?"textarea":e.includes("/richtext")?"richtext":e.endsWith("/form/numberfield")?"number":e.endsWith("/form/checkbox")?"boolean":e.endsWith("/form/radiogroup")?"radio-group":e.endsWith("/form/select")?n?"multiselect":"select":e.endsWith("/form/datepicker")?"date-time":e.endsWith("/form/pathfield")||e.endsWith("/form/pathbrowser")?"aem-content":e.includes("/fileupload")||e.endsWith("/form/fileupload")?"reference":e.includes("tagfield")||e.includes("tagpicker")||e.includes("tagbrowser")?"aem-tag":e.includes("contentfragment")?"aem-content-fragment":e.includes("experiencefragment")?"aem-experience-fragment":null}function qc(e){return e.includes("/foundation/container")||e.includes("/foundation/fixedcolumns")||e.includes("/foundation/well")||e.includes("/foundation/tabs")||e.includes("/foundation/form/fieldset")||e.includes("/foundation/accordion")}function Kc(e){switch(e){case"number":return"number";case"boolean":return"boolean";case"date-time":return"date";case"checkbox-group":return"string[]";case"aem-content":case"aem-content-fragment":case"aem-experience-fragment":return;default:return"string"}}function _n(e,t){return(e??"").replace(/^\.\//,"").trim()||t}function Xc(e){let t=we(e).find(n=>mt(n)==="items");return t?we(t).map(n=>{let o=V(n,"value")??"";return{name:V(n,"text")??V(n,"jcr:title")??o,value:o}}):[]}function Kt(e,t,n,o){for(let i of e){let a=V(i,"sling:resourceType")??"";if(a.endsWith("/foundation/tabs")){let d=we(i).find(l=>mt(l)==="items");for(let l of d?we(d):[]){let c=V(l,"jcr:title");t.push({component:"tab",name:_n(void 0,mt(l)),label:c}),Kt(we(l),t,n,o)}continue}if(a.endsWith("/form/multifield")){let d=[];Kt(we(i),d,n,o);let l=_n(V(i,"name"),`items${o.i++}`);t.push({component:"container",name:l,label:V(i,"fieldLabel")??"Items",multi:!0,collapsible:!0,fields:d});continue}let s=a?Jc(a,i):null;if(s){let d=_n(V(i,"name"),`field${o.i++}`),l={component:s,name:d},c=Kc(s);c&&(l.valueType=c);let p=V(i,"fieldLabel")??V(i,"text");if(p&&(l.label=p),s==="select"||s==="radio-group"||s==="multiselect"){let u=Xc(i);u.length&&(l.options=u)}let m=V(i,"value")??(s==="boolean"?V(i,"checked"):void 0);m!==void 0&&m!==""&&(l.value=s==="boolean"?m==="true":m),t.push(l);continue}a&&V(i,"name")&&!qc(a)&&n.add(a),Kt(we(i),t,n,o)}}function wr(e){let o=new Gc({ignoreAttributes:!1,attributeNamePrefix:"@_",preserveOrder:!0,removeNSPrefix:!1,trimValues:!0}).parse(e).find(s=>mt(s)==="jcr:root"),i=[],a=new Set;return o&&Kt(we(o),i,a,{i:1}),{fields:i,unmapped:[...a]}}var br=v(()=>{"use strict";f()});import{existsSync as yr}from"fs";import{readFile as vr}from"fs/promises";import Xt from"path";import{XMLParser as Vc}from"fast-xml-parser";function Un(e){return[Xt.join(e,"_cq_dialog",".content.xml"),Xt.join(e,"_cq_dialog.xml"),Xt.join(e,"cq:dialog",".content.xml")].find(n=>yr(n))??null}async function kr(e){let t=Xt.join(e,".content.xml");if(yr(t))try{let a=(new Vc({ignoreAttributes:!1,attributeNamePrefix:"@_"}).parse(await vr(t,"utf-8"))["jcr:root"]??{})["@_jcr:title"];return typeof a=="string"?a.replace(/^\{[^}]+\}/,""):void 0}catch{return}}async function xr(e){let t=Un(e);return t?wr(await vr(t,"utf-8")):null}function $r(e,t,n){return`${JSON.stringify({definitions:[{title:t,id:e,plugins:{xwalk:{page:{resourceType:"core/franklin/components/block/v1/block",template:{name:t,model:e}}}}}],models:[{id:e,fields:n}],filters:[]},null,2)}
373
+ `}function Sr(e,t){let o=t.some(i=>i.component==="container"&&i.multi)?` // This block was migrated from a classic AEM component with a multifield.
374
374
  // Each child row is one repeated item - enhance them here.
375
375
  [...block.children].forEach((row) => {
376
376
  row.classList.add('${e}-item');
@@ -382,25 +382,25 @@ export default function decorate(block) {
382
382
  block.classList.add('${e}');
383
383
  ${o}
384
384
  }
385
- `}function dr(e){return`/* Block: ${e} */
385
+ `}function jr(e){return`/* Block: ${e} */
386
386
  /* Migrated from a classic AEM component. Bring the component's styles here */
387
387
  /* (from its clientlib or the rendered page) and keep them scoped to the block. */
388
388
  .${e} {
389
389
  }
390
- `}var pr=w(()=>{"use strict";m();or()});function yc(e,t,n){let o=[` // --- ${ur} ---`];return n.click&&o.push(` ${t}.addEventListener('click', (ev) => {`," const el = ev.target.closest('a, button');"," if (!el) return;",` trackEvent({ event: 'block_click', block: '${e}', label: el.dataset.track || el.textContent.trim() });`," });"),n.submit&&o.push(` ${t}.addEventListener('submit', () => {`,` trackEvent({ event: 'form_submit', block: '${e}' });`," });"),o.join(`
391
- `)}function fr(e,t,n){if(e.includes(ur))return{js:e,changed:!1,reason:"already instrumented"};if(!n.click&&!n.submit)return{js:e,changed:!1,reason:"no events selected"};let o=e.match(/export default (?:async )?function decorate\s*\(\s*([A-Za-z_$][\w$]*)?[^)]*\)\s*\{/);if(!o||o.index===void 0)return{js:e,changed:!1,reason:"no `export default function decorate(...)` found"};let r=o[1]||"block",a=e;if(!a.includes("scripts/analytics.js")){let c=[...a.matchAll(/^import .*$/gm)];if(c.length){let u=c[c.length-1],p=(u.index??0)+u[0].length;a=`${a.slice(0,p)}
392
- ${mr}${a.slice(p)}`}else a=`${mr}
390
+ `}var Pr=v(()=>{"use strict";f();br()});function Yc(e,t,n){let o=[` // --- ${Cr} ---`];return n.click&&o.push(` ${t}.addEventListener('click', (ev) => {`," const el = ev.target.closest('a, button');"," if (!el) return;",` trackEvent({ event: 'block_click', block: '${e}', label: el.dataset.track || el.textContent.trim() });`," });"),n.submit&&o.push(` ${t}.addEventListener('submit', () => {`,` trackEvent({ event: 'form_submit', block: '${e}' });`," });"),o.join(`
391
+ `)}function Ar(e,t,n){if(e.includes(Cr))return{js:e,changed:!1,reason:"already instrumented"};if(!n.click&&!n.submit)return{js:e,changed:!1,reason:"no events selected"};let o=e.match(/export default (?:async )?function decorate\s*\(\s*([A-Za-z_$][\w$]*)?[^)]*\)\s*\{/);if(!o||o.index===void 0)return{js:e,changed:!1,reason:"no `export default function decorate(...)` found"};let i=o[1]||"block",a=e;if(!a.includes("scripts/analytics.js")){let c=[...a.matchAll(/^import .*$/gm)];if(c.length){let p=c[c.length-1],m=(p.index??0)+p[0].length;a=`${a.slice(0,m)}
392
+ ${Er}${a.slice(m)}`}else a=`${Er}
393
393
 
394
- ${a}`}let s=a.match(/export default (?:async )?function decorate\s*\(\s*([A-Za-z_$][\w$]*)?[^)]*\)\s*\{/);if(!s||s.index===void 0)return{js:a,changed:!1,reason:"decorate not found"};let d=s.index+s[0].length,l=yc(t,r,n);return a=`${a.slice(0,d)}
394
+ ${a}`}let s=a.match(/export default (?:async )?function decorate\s*\(\s*([A-Za-z_$][\w$]*)?[^)]*\)\s*\{/);if(!s||s.index===void 0)return{js:a,changed:!1,reason:"decorate not found"};let d=s.index+s[0].length,l=Yc(t,i,n);return a=`${a.slice(0,d)}
395
395
  ${l}
396
- ${a.slice(d)}`,{js:a,changed:!0}}var ur,mr,gr=w(()=>{"use strict";m();ur="analytics (eds track)",mr="import { trackEvent } from '../../scripts/analytics.js';"});var rt={};N(rt,{trackBlock:()=>$c});import{existsSync as hr}from"fs";import{readFile as vc,writeFile as kc}from"fs/promises";import br from"path";import xc from"chalk";async function $c(e,t={}){let n=E();if(!n){i.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}i.logoOnce(P("Track block"));let o=br.join(n,"blocks",e,`${e}.js`);if(!hr(o)){i.error(`Block "${e}" not found (no blocks/${e}/${e}.js).`),process.exitCode=1;return}let r={click:t.click!==!1,submit:t.submit!==!1},a=fr(await vc(o,"utf-8"),e,r);if(!a.changed){i.warn(`Not instrumented: ${a.reason}.`);return}await kc(o,a.js),i.info(j("Instrumented"));let s=[r.click?"block_click":null,r.submit?"form_submit":null].filter(Boolean);i.info($(`blocks/${e}/${e}.js`,s.join(" + "))),hr(br.join(n,"scripts","analytics.js"))||(i.info(""),i.warn("scripts/analytics.js is missing - run `eds integrate gtm` to create it.")),i.info(""),i.info(xc.dim(" Events push to window.dataLayer via trackEvent - GTM picks them up."))}var at=w(()=>{"use strict";m();R();z();gr();I()});var Dn={};N(Dn,{migrateComponent:()=>Ec});import{existsSync as Tn}from"fs";import{mkdir as Sc,writeFile as Rn}from"fs/promises";import Ee from"path";function jc(e,t,n){return`/* Block: ${e} */
396
+ ${a.slice(d)}`,{js:a,changed:!0}}var Cr,Er,Tr=v(()=>{"use strict";f();Cr="analytics (eds track)",Er="import { trackEvent } from '../../scripts/analytics.js';"});var ut={};L(ut,{trackBlock:()=>tl});import{existsSync as Rr}from"fs";import{readFile as Qc,writeFile as Zc}from"fs/promises";import Fr from"path";import el from"chalk";async function tl(e,t={}){let n=P();if(!n){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(E("Track block"));let o=Fr.join(n,"blocks",e,`${e}.js`);if(!Rr(o)){r.error(`Block "${e}" not found (no blocks/${e}/${e}.js).`),process.exitCode=1;return}let i={click:t.click!==!1,submit:t.submit!==!1},a=Ar(await Qc(o,"utf-8"),e,i);if(!a.changed){r.warn(`Not instrumented: ${a.reason}.`);return}await Zc(o,a.js),r.info(S("Instrumented"));let s=[i.click?"block_click":null,i.submit?"form_submit":null].filter(Boolean);r.info(j(`blocks/${e}/${e}.js`,s.join(" + "))),Rr(Fr.join(n,"scripts","analytics.js"))||(r.info(""),r.warn("scripts/analytics.js is missing - run `eds integrate gtm` to create it.")),r.info(""),r.info(el.dim(" Events push to window.dataLayer via trackEvent - GTM picks them up."))}var ft=v(()=>{"use strict";f();R();B();Tr();N()});var Gn={};L(Gn,{migrateComponent:()=>il});import{existsSync as Bn}from"fs";import{mkdir as nl,writeFile as Hn}from"fs/promises";import Re from"path";function ol(e,t,n){return`/* Block: ${e} */
397
397
  /* Migrated from the component clientlib: ${n.join(", ")}. */
398
398
  /* TODO: review selectors and scope them under .${e} (and port any LESS/SCSS). */
399
399
 
400
400
  ${t.trim()}
401
- `}function wr(e,t=0){let n=[];for(let o of e){let r=" ".repeat(t);if(o.component==="tab")n.push(`${r}${_.blue("\u25B8")} ${o.label??o.name}`);else{let a=o.options?.length?` (${o.options.length} options)`:"",s=o.multi?" \xB7multi":"",d=o.label?`- ${o.label}`:"";n.push(`${r}${_.accent(o.component)}${s} ${o.name}${a} ${d}`),o.fields?.length&&n.push(...wr(o.fields,t+1))}}return n}function yr(e){let t=0;for(let n of e)n.component!=="tab"&&(t+=1,n.fields&&(t+=yr(n.fields)));return t}async function Ec(e,t={}){let n=E();if(!n){i.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}await i.logoOnceAnimated("Migrate component");let{input:o,confirm:r}=await Promise.resolve().then(()=>(B(),U)),a=!t.yes,s=e;if(!s&&a&&(s=await o({message:"Path to the classic component folder",validate:S=>Tn(S.trim())||"Folder not found"})),!s){i.error("Provide the path to the classic component folder."),process.exitCode=1;return}if(s=Ee.resolve(s.trim()),!An(s)){i.error(`No Touch UI dialog (_cq_dialog/.content.xml) found in ${s}.`),process.exitCode=1;return}let d=await sr(s);if(!d||d.fields.length===0){i.warn("Dialog found but no mappable fields were detected."),d?.unmapped.length&&i.info(`Unmapped resourceTypes: ${d.unmapped.join(", ")}`),process.exitCode=1;return}let l=await ar(s)??Ee.basename(s),c=t.name&&Ut(t.name)||Ut(a?await o({message:"Block name",default:Ut(l)}):l);i.info(j("Mapped fields",`${yr(d.fields)} from dialog`));for(let S of wr(d.fields))i.info(` ${S}`);if(d.unmapped.length&&(i.info(""),i.warn(`Skipped (unrecognised): ${d.unmapped.join(", ")}`)),i.info(""),a&&!await r({message:`Generate block "${c}"?`,default:!0})){i.info("Cancelled.");return}let u=Ee.join(n,"blocks",c);if(Tn(u)){i.error(`Block "${c}" already exists at blocks/${c}. Use --name to pick another.`),process.exitCode=1;return}let p=t.clientlib?Ee.resolve(t.clientlib.trim()):await Zi(s),f=dr(c),g="empty - add styles from clientlib / rendered CSS",y=[];if(p&&Tn(p)){let S=await er(p);S.css.trim()&&(f=jc(c,S.css,S.files),g=`from clientlib (${S.files.length} file(s)) - review & scope`),y=S.preprocessed}await Sc(u,{recursive:!0}),await Rn(Ee.join(u,`${c}.js`),lr(c,d.fields)),await Rn(Ee.join(u,`${c}.css`),f),await Rn(Ee.join(u,`_${c}.json`),cr(c,l,d.fields)),i.info(j("Created"));let h=[`${c}.js`,`${c}.css`,`_${c}.json`],b=O(h);if(i.info($(`${c}.js`,"decorator stub (port HTL logic)",b)),i.info($(`${c}.css`,g,b)),i.info($(`_${c}.json`,"Universal Editor model",b)),y.length&&(i.info(""),i.warn(`LESS/SCSS found (needs a build, not copied): ${y.join(", ")}`)),i.info(""),a&&await r({message:"Instrument this block for analytics (dataLayer)?",default:!1})){let{trackBlock:x}=await Promise.resolve().then(()=>(at(),rt));await x(c,{})}i.info(L([`"${c}" migrated. Next: add CSS, then \`eds block preview ${c}\``]))}var Ut,Fn=w(()=>{"use strict";m();R();tr();pr();z();I();Ut=e=>e.trim().toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"")});function V(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):t}var X,vr=w(()=>{"use strict";m();X={text:(e,t)=>({component:"text",valueType:"string",name:e,label:t}),textarea:(e,t)=>({component:"textarea",valueType:"string",name:e,label:t}),richtext:(e,t)=>({component:"richtext",valueType:"string",name:e,value:"",label:t}),number:(e,t)=>({component:"number",valueType:"number",name:e,label:t}),boolean:(e,t,n=!1)=>({component:"boolean",valueType:"boolean",name:e,value:n,label:t}),dateTime:(e,t)=>({component:"date-time",valueType:"date",name:e,label:t}),select:(e,t,n,o)=>({component:"select",valueType:"string",name:e,label:t,options:n,...o!==void 0?{value:o}:{}}),multiselect:(e,t,n)=>({component:"multiselect",valueType:"string",name:e,label:t,options:n}),radioGroup:(e,t,n,o)=>({component:"radio-group",valueType:"string",name:e,label:t,options:n,...o!==void 0?{value:o}:{}}),checkboxGroup:(e,t,n)=>({component:"checkbox-group",valueType:"string[]",name:e,label:t,options:n}),reference:(e,t)=>({component:"reference",valueType:"string",name:e,label:t}),aemContent:(e,t)=>({component:"aem-content",name:e,label:t}),aemContentFragment:(e,t)=>({component:"aem-content-fragment",name:e,label:t}),aemExperienceFragment:(e,t)=>({component:"aem-experience-fragment",name:e,label:t}),aemTag:(e,t)=>({component:"aem-tag",valueType:"string",name:e,label:t}),tab:(e,t)=>({component:"tab",name:e,label:t}),container:(e,t,n,o=!0)=>({component:"container",name:e,label:t,multi:!0,collapsible:o,fields:n})}});function Nn(e){return Ie.find(t=>t.id===e)}var Pc,Cc,Ac,Tc,kr,xr,Ln,$r,On,Mn,Rc,Dc,Fc,Lc,Oc,Ie,_n=w(()=>{"use strict";m();vr();Pc=[{name:"H1",value:"h1"},{name:"H2",value:"h2"},{name:"H3",value:"h3"},{name:"H4",value:"h4"},{name:"H5",value:"h5"},{name:"H6",value:"h6"}],Cc=[{name:"Same tab",value:"_self"},{name:"New tab",value:"_blank"}],Ac=[{name:"Default",value:""},{name:"Primary",value:"primary"},{name:"Secondary",value:"secondary"}],Tc=[{name:"Highlight",value:"highlight"},{name:"Dark",value:"dark"},{name:"Centered",value:"centered"},{name:"Full width",value:"full-width"}],kr=(e="")=>[X.text(V(e,"title"),"Title"),X.select(V(e,"titleType"),"Heading level",Pc,"h2")],xr=(e="")=>[X.text(V(e,"eyebrow"),"Eyebrow")],Ln=(e="")=>[X.reference(V(e,"image"),"Image"),X.text(V(e,"imageAlt"),"Alt text")],$r=(e="")=>[X.richtext(V(e,"text"),"Text")],On=(e="")=>[X.text(V(e,"linkText"),"Link text"),X.aemContent(V(e,"link"),"Link"),X.select(V(e,"linkTarget"),"Open in",Cc,"_self")],Mn=(e="")=>[...On(e),X.select(V(e,"ctaStyle"),"Style",Ac,"")],Rc=(e="")=>[X.container(V(e,"ctas")||"ctas","Buttons",Mn())],Dc=(e="")=>[X.multiselect(V(e,"classes"),"Styles",Tc)],Fc=(e="")=>[X.aemContent(V(e,"url"),"URL (video / embed)")],Lc=(e="")=>[...Ln(e),...xr(e),...kr(e),...$r(e),...Mn(e)],Oc=(e="")=>[...Ln(e),X.text(V(e,"title"),"Title"),X.richtext(V(e,"description"),"Description"),...On(e)],Ie=[{id:"heading",label:"Heading (title + level)",build:kr},{id:"eyebrow",label:"Eyebrow (kicker line)",build:xr},{id:"image",label:"Image (reference + alt)",build:Ln},{id:"richtext",label:"Rich text body",build:$r},{id:"link",label:"Link (text + url + target)",build:On},{id:"cta",label:"CTA (link + style)",build:Mn},{id:"cta-group",label:"CTA group (repeatable buttons)",build:Rc},{id:"classes",label:"Section styles (CSS modifiers)",build:Dc},{id:"embed",label:"Embed / video (URL)",build:Fc},{id:"teaser",label:"Teaser (image + eyebrow + title + text + CTA)",build:Lc},{id:"card",label:"Card (image + title + description + link)",build:Oc}]});var Bn={};N(Bn,{modelAdd:()=>_c});import{existsSync as In}from"fs";import{readFile as Mc,writeFile as Nc}from"fs/promises";import Un from"path";async function _c(e,t,n={}){let o=E();if(!o){i.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}i.logoOnce(P("Model - add partials"));let{select:r,checkbox:a}=await Promise.resolve().then(()=>(B(),U)),s=!n.yes,d=e;if(!d&&s){let{readdir:x}=await import("fs/promises"),T=Un.join(o,"blocks"),oe=In(T)?(await x(T,{withFileTypes:!0})).filter(H=>H.isDirectory()&&In(Un.join(T,H.name,`_${H.name}.json`))).map(H=>H.name):[];if(oe.length===0){i.error("No block with a _<name>.json model found. Create one with `eds block create`."),process.exitCode=1;return}d=await r({message:"Which block's model?",choices:oe.map(H=>({name:H,value:H}))})}if(!d){i.error("Provide a block name."),process.exitCode=1;return}let l=Un.join(o,"blocks",d,`_${d}.json`);if(!In(l)){i.error(`No model at blocks/${d}/_${d}.json. Create the block first.`),process.exitCode=1;return}let c=t;c.length===0&&s&&(c=await a({message:"Which partials to add?",choices:Ie.map(x=>({name:x.label,value:x.id}))}));let u=c.map(x=>Nn(x.trim())).filter(x=>!!x),p=c.filter(x=>!Nn(x.trim()));if(p.length&&i.warn(`Unknown partial(s): ${p.join(", ")}. Available: ${Ie.map(x=>x.id).join(", ")}`),u.length===0){i.info("Nothing to add.");return}let f;try{f=JSON.parse(await Mc(l,"utf-8"))}catch{i.error(`Could not parse ${l}.`),process.exitCode=1;return}let g=Array.isArray(f.models)?f.models:[],y=g.find(x=>x.id===d)??g[0];if(!y){i.error("Model has no `models[]` entry to add fields to."),process.exitCode=1;return}y.fields=Array.isArray(y.fields)?y.fields:[];let h=new Set(y.fields.map(x=>x.name)),b=[],S=[];for(let x of u)for(let T of x.build()){if(h.has(T.name)){S.push(T.name);continue}h.add(T.name),y.fields.push(T),b.push(T.name)}await Nc(l,`${JSON.stringify(f,null,2)}
402
- `),i.info(j("Model updated",`blocks/${d}/_${d}.json`)),i.info($("partials",u.map(x=>x.id).join(", "))),i.info($("fields added",b.length?b.join(", "):"(none)")),S.length&&i.info(D("warn","skipped (exists)",S.join(", "))),i.info(""),i.info(L([`${b.length} field(s) added to "${d}"`]))}var Hn=w(()=>{"use strict";m();R();_n();z();I()});function jr(e){return Bt.find(t=>t.id.toLowerCase()===e.toLowerCase())}function Er(e,t){if(e.includes(Sr))return{js:e,changed:!1,reason:"already has JSON-LD"};let n=e.match(/export default (?:async )?function decorate\s*\(\s*([A-Za-z_$][\w$]*)?[^)]*\)\s*\{/);if(!n||n.index===void 0)return{js:e,changed:!1,reason:"no `export default function decorate(...)` found"};let o=n[1]||"block",r=n.index+n[0].length,a=`
403
- // --- ${Sr}: ${t.id}) ---
401
+ `}function Dr(e,t=0){let n=[];for(let o of e){let i=" ".repeat(t);if(o.component==="tab")n.push(`${i}${_.blue("\u25B8")} ${o.label??o.name}`);else{let a=o.options?.length?` (${o.options.length} options)`:"",s=o.multi?" \xB7multi":"",d=o.label?`- ${o.label}`:"";n.push(`${i}${_.accent(o.component)}${s} ${o.name}${a} ${d}`),o.fields?.length&&n.push(...Dr(o.fields,t+1))}}return n}function Lr(e){let t=0;for(let n of e)n.component!=="tab"&&(t+=1,n.fields&&(t+=Lr(n.fields)));return t}async function il(e,t={}){let n=P();if(!n){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}await r.logoOnceAnimated("Migrate component");let{input:o,confirm:i}=await Promise.resolve().then(()=>(G(),H)),a=!t.yes,s=e;if(!s&&a&&(s=await o({message:"Path to the classic component folder",validate:$=>Bn($.trim())||"Folder not found"})),!s){r.error("Provide the path to the classic component folder."),process.exitCode=1;return}if(s=Re.resolve(s.trim()),!Un(s)){r.error(`No Touch UI dialog (_cq_dialog/.content.xml) found in ${s}.`),process.exitCode=1;return}let d=await xr(s);if(!d||d.fields.length===0){r.warn("Dialog found but no mappable fields were detected."),d?.unmapped.length&&r.info(`Unmapped resourceTypes: ${d.unmapped.join(", ")}`),process.exitCode=1;return}let l=await kr(s)??Re.basename(s),c=t.name&&Vt(t.name)||Vt(a?await o({message:"Block name",default:Vt(l)}):l);r.info(S("Mapped fields",`${Lr(d.fields)} from dialog`));for(let $ of Dr(d.fields))r.info(` ${$}`);if(d.unmapped.length&&(r.info(""),r.warn(`Skipped (unrecognised): ${d.unmapped.join(", ")}`)),r.info(""),a&&!await i({message:`Generate block "${c}"?`,default:!0})){r.info("Cancelled.");return}let p=Re.join(n,"blocks",c);if(Bn(p)){r.error(`Block "${c}" already exists at blocks/${c}. Use --name to pick another.`),process.exitCode=1;return}let m=t.clientlib?Re.resolve(t.clientlib.trim()):await fr(s),u=jr(c),g="empty - add styles from clientlib / rendered CSS",w=[];if(m&&Bn(m)){let $=await gr(m);$.css.trim()&&(u=ol(c,$.css,$.files),g=`from clientlib (${$.files.length} file(s)) - review & scope`),w=$.preprocessed}await nl(p,{recursive:!0}),await Hn(Re.join(p,`${c}.js`),Sr(c,d.fields)),await Hn(Re.join(p,`${c}.css`),u),await Hn(Re.join(p,`_${c}.json`),$r(c,l,d.fields)),r.info(S("Created"));let y=[`${c}.js`,`${c}.css`,`_${c}.json`],h=M(y);if(r.info(j(`${c}.js`,"decorator stub (port HTL logic)",h)),r.info(j(`${c}.css`,g,h)),r.info(j(`_${c}.json`,"Universal Editor model",h)),w.length&&(r.info(""),r.warn(`LESS/SCSS found (needs a build, not copied): ${w.join(", ")}`)),r.info(""),a&&await i({message:"Instrument this block for analytics (dataLayer)?",default:!1})){let{trackBlock:b}=await Promise.resolve().then(()=>(ft(),ut));await b(c,{})}r.info(O([`"${c}" migrated. Next: add CSS, then \`eds block preview ${c}\``]))}var Vt,zn=v(()=>{"use strict";f();R();hr();Pr();B();N();Vt=e=>e.trim().toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"")});function X(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):t}var K,Or=v(()=>{"use strict";f();K={text:(e,t)=>({component:"text",valueType:"string",name:e,label:t}),textarea:(e,t)=>({component:"textarea",valueType:"string",name:e,label:t}),richtext:(e,t)=>({component:"richtext",valueType:"string",name:e,value:"",label:t}),number:(e,t)=>({component:"number",valueType:"number",name:e,label:t}),boolean:(e,t,n=!1)=>({component:"boolean",valueType:"boolean",name:e,value:n,label:t}),dateTime:(e,t)=>({component:"date-time",valueType:"date",name:e,label:t}),select:(e,t,n,o)=>({component:"select",valueType:"string",name:e,label:t,options:n,...o!==void 0?{value:o}:{}}),multiselect:(e,t,n)=>({component:"multiselect",valueType:"string",name:e,label:t,options:n}),radioGroup:(e,t,n,o)=>({component:"radio-group",valueType:"string",name:e,label:t,options:n,...o!==void 0?{value:o}:{}}),checkboxGroup:(e,t,n)=>({component:"checkbox-group",valueType:"string[]",name:e,label:t,options:n}),reference:(e,t)=>({component:"reference",valueType:"string",name:e,label:t}),aemContent:(e,t)=>({component:"aem-content",name:e,label:t}),aemContentFragment:(e,t)=>({component:"aem-content-fragment",name:e,label:t}),aemExperienceFragment:(e,t)=>({component:"aem-experience-fragment",name:e,label:t}),aemTag:(e,t)=>({component:"aem-tag",valueType:"string",name:e,label:t}),tab:(e,t)=>({component:"tab",name:e,label:t}),container:(e,t,n,o=!0)=>({component:"container",name:e,label:t,multi:!0,collapsible:o,fields:n})}});function Kn(e){return ze.find(t=>t.id===e)}var rl,al,sl,cl,Nr,Mr,Wn,Ir,Jn,qn,ll,dl,pl,ml,ul,ze,Xn=v(()=>{"use strict";f();Or();rl=[{name:"H1",value:"h1"},{name:"H2",value:"h2"},{name:"H3",value:"h3"},{name:"H4",value:"h4"},{name:"H5",value:"h5"},{name:"H6",value:"h6"}],al=[{name:"Same tab",value:"_self"},{name:"New tab",value:"_blank"}],sl=[{name:"Default",value:""},{name:"Primary",value:"primary"},{name:"Secondary",value:"secondary"}],cl=[{name:"Highlight",value:"highlight"},{name:"Dark",value:"dark"},{name:"Centered",value:"centered"},{name:"Full width",value:"full-width"}],Nr=(e="")=>[K.text(X(e,"title"),"Title"),K.select(X(e,"titleType"),"Heading level",rl,"h2")],Mr=(e="")=>[K.text(X(e,"eyebrow"),"Eyebrow")],Wn=(e="")=>[K.reference(X(e,"image"),"Image"),K.text(X(e,"imageAlt"),"Alt text")],Ir=(e="")=>[K.richtext(X(e,"text"),"Text")],Jn=(e="")=>[K.text(X(e,"linkText"),"Link text"),K.aemContent(X(e,"link"),"Link"),K.select(X(e,"linkTarget"),"Open in",al,"_self")],qn=(e="")=>[...Jn(e),K.select(X(e,"ctaStyle"),"Style",sl,"")],ll=(e="")=>[K.container(X(e,"ctas")||"ctas","Buttons",qn())],dl=(e="")=>[K.multiselect(X(e,"classes"),"Styles",cl)],pl=(e="")=>[K.aemContent(X(e,"url"),"URL (video / embed)")],ml=(e="")=>[...Wn(e),...Mr(e),...Nr(e),...Ir(e),...qn(e)],ul=(e="")=>[...Wn(e),K.text(X(e,"title"),"Title"),K.richtext(X(e,"description"),"Description"),...Jn(e)],ze=[{id:"heading",label:"Heading (title + level)",build:Nr},{id:"eyebrow",label:"Eyebrow (kicker line)",build:Mr},{id:"image",label:"Image (reference + alt)",build:Wn},{id:"richtext",label:"Rich text body",build:Ir},{id:"link",label:"Link (text + url + target)",build:Jn},{id:"cta",label:"CTA (link + style)",build:qn},{id:"cta-group",label:"CTA group (repeatable buttons)",build:ll},{id:"classes",label:"Section styles (CSS modifiers)",build:dl},{id:"embed",label:"Embed / video (URL)",build:pl},{id:"teaser",label:"Teaser (image + eyebrow + title + text + CTA)",build:ml},{id:"card",label:"Card (image + title + description + link)",build:ul}]});var Qn={};L(Qn,{modelAdd:()=>hl});import{existsSync as Vn}from"fs";import{readFile as fl,writeFile as gl}from"fs/promises";import Yn from"path";async function hl(e,t,n={}){let o=P();if(!o){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(E("Model - add partials"));let{select:i,checkbox:a}=await Promise.resolve().then(()=>(G(),H)),s=!n.yes,d=e;if(!d&&s){let{readdir:b}=await import("fs/promises"),T=Yn.join(o,"blocks"),Q=Vn(T)?(await b(T,{withFileTypes:!0})).filter(z=>z.isDirectory()&&Vn(Yn.join(T,z.name,`_${z.name}.json`))).map(z=>z.name):[];if(Q.length===0){r.error("No block with a _<name>.json model found. Create one with `eds block create`."),process.exitCode=1;return}d=await i({message:"Which block's model?",choices:Q.map(z=>({name:z,value:z}))})}if(!d){r.error("Provide a block name."),process.exitCode=1;return}let l=Yn.join(o,"blocks",d,`_${d}.json`);if(!Vn(l)){r.error(`No model at blocks/${d}/_${d}.json. Create the block first.`),process.exitCode=1;return}let c=t;c.length===0&&s&&(c=await a({message:"Which partials to add?",choices:ze.map(b=>({name:b.label,value:b.id}))}));let p=c.map(b=>Kn(b.trim())).filter(b=>!!b),m=c.filter(b=>!Kn(b.trim()));if(m.length&&r.warn(`Unknown partial(s): ${m.join(", ")}. Available: ${ze.map(b=>b.id).join(", ")}`),p.length===0){r.info("Nothing to add.");return}let u;try{u=JSON.parse(await fl(l,"utf-8"))}catch{r.error(`Could not parse ${l}.`),process.exitCode=1;return}let g=Array.isArray(u.models)?u.models:[],w=g.find(b=>b.id===d)??g[0];if(!w){r.error("Model has no `models[]` entry to add fields to."),process.exitCode=1;return}w.fields=Array.isArray(w.fields)?w.fields:[];let y=new Set(w.fields.map(b=>b.name)),h=[],$=[];for(let b of p)for(let T of b.build()){if(y.has(T.name)){$.push(T.name);continue}y.add(T.name),w.fields.push(T),h.push(T.name)}await gl(l,`${JSON.stringify(u,null,2)}
402
+ `),r.info(S("Model updated",`blocks/${d}/_${d}.json`)),r.info(j("partials",p.map(b=>b.id).join(", "))),r.info(j("fields added",h.length?h.join(", "):"(none)")),$.length&&r.info(A("warn","skipped (exists)",$.join(", "))),r.info(""),r.info(O([`${h.length} field(s) added to "${d}"`]))}var Zn=v(()=>{"use strict";f();R();Xn();B();N()});function Ur(e){return Yt.find(t=>t.id.toLowerCase()===e.toLowerCase())}function Br(e,t){if(e.includes(_r))return{js:e,changed:!1,reason:"already has JSON-LD"};let n=e.match(/export default (?:async )?function decorate\s*\(\s*([A-Za-z_$][\w$]*)?[^)]*\)\s*\{/);if(!n||n.index===void 0)return{js:e,changed:!1,reason:"no `export default function decorate(...)` found"};let o=n[1]||"block",i=n.index+n[0].length,a=`
403
+ // --- ${_r}: ${t.id}) ---
404
404
  {
405
405
  const root = ${o};
406
406
  const ld = ${t.object};
@@ -409,7 +409,7 @@ ${t.trim()}
409
409
  ldScript.textContent = JSON.stringify(ld);
410
410
  document.head.append(ldScript);
411
411
  }
412
- `;return{js:`${e.slice(0,r)}${a}${e.slice(r)}`,changed:!0}}var Sr,Bt,Pr=w(()=>{"use strict";m();Sr="json-ld (eds schema",Bt=[{id:"Article",label:"Article / BlogPosting",object:`{
412
+ `;return{js:`${e.slice(0,i)}${a}${e.slice(i)}`,changed:!0}}var _r,Yt,Hr=v(()=>{"use strict";f();_r="json-ld (eds schema",Yt=[{id:"Article",label:"Article / BlogPosting",object:`{
413
413
  '@context': 'https://schema.org',
414
414
  '@type': 'Article',
415
415
  headline: root.querySelector('h1, h2, h3')?.textContent?.trim() || document.title,
@@ -488,52 +488,58 @@ ${t.trim()}
488
488
  position: i + 1,
489
489
  text: li.textContent?.trim(),
490
490
  })),
491
- }`}]});var Gn={};N(Gn,{schemaBlock:()=>zc});import{existsSync as Ic}from"fs";import{readFile as Uc,writeFile as Bc}from"fs/promises";import Hc from"path";import Gc from"chalk";async function zc(e,t={}){let n=E();if(!n){i.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}i.logoOnce(P("Schema - JSON-LD"));let o=Hc.join(n,"blocks",e,`${e}.js`);if(!Ic(o)){i.error(`Block "${e}" not found (no blocks/${e}/${e}.js).`),process.exitCode=1;return}let r=t.type;if(!r&&!t.yes){let{select:d}=await Promise.resolve().then(()=>(B(),U));r=await d({message:"Which schema.org type?",choices:Bt.map(l=>({name:`${l.id} - ${l.label}`,value:l.id}))})}let a=r?jr(r):void 0;if(!a){i.error(`Unknown schema type "${r}". Options: ${Bt.map(d=>d.id).join(", ")}`),process.exitCode=1;return}let s=Er(await Uc(o,"utf-8"),a);if(!s.changed){i.warn(`Not added: ${s.reason}.`);return}await Bc(o,s.js),i.info(j("JSON-LD added")),i.info($(`blocks/${e}/${e}.js`,`${a.id} (${a.label})`)),i.info(""),i.info(Gc.dim(" Review the generated object - some fields are heuristic or TODO. Validate at search.google.com/test/rich-results."))}var zn=w(()=>{"use strict";m();R();z();Pr();I()});function Wc(e,t){for(let n of e.match(/<meta\b[^>]*>/gi)??[])if(n.match(/\bname=["']([^"']+)["']/i)?.[1]===t)return n.match(/\bcontent=["']([^"']*)["']/i)?.[1]??"";return null}function Cr(e){return Wc(e,Jc)!==null}function Ar(e){return Array.isArray(e)?e.map(t=>t&&typeof t=="object"?t.id:void 0).filter(t=>typeof t=="string"):[]}function Tr(e){let t=!!e.configPresent["component-definition.json"]&&!!e.configPresent["component-models.json"],n=new Set(e.modelIds),o=e.blocks.map(r=>{let a=r.hasModelFile||n.has(r.name);return{name:r.name,editable:a,reason:a?void 0:"no UE model (_<name>.json or component-models entry)"}});return{isUeProject:t,blocks:o}}var Jn,Jc,Rr=w(()=>{"use strict";m();Jn=["component-definition.json","component-models.json","component-filters.json"],Jc="urn:adobe:aue:system:aemconnection"});var lt={};N(lt,{ueCheck:()=>Qc,ueOpen:()=>Zc});import{existsSync as ct}from"fs";import{readFile as Dr,readdir as qc}from"fs/promises";import st from"path";import Ht from"chalk";async function Kc(e){if(!ct(e))return null;try{return JSON.parse(await Dr(e,"utf-8"))}catch{return null}}async function Xc(e){let t=st.join(e,"blocks");return ct(t)?(await qc(t,{withFileTypes:!0})).filter(o=>o.isDirectory()).map(o=>({name:o.name,hasModelFile:ct(st.join(t,o.name,`_${o.name}.json`))})):[]}async function Vc(e){let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{let{execa:n}=await import("execa");await n(t,[e],{stdio:"ignore"})}catch{}}async function Yc(e){try{let{execa:t}=await import("execa");return(await t("git",["remote","get-url","origin"],{cwd:e})).stdout.trim()||null}catch{return null}}async function Qc(){let e=E();if(!e){i.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}i.logoOnce(P("Universal Editor - readiness"));let t={};for(let p of Jn)t[p]=ct(st.join(e,p));let n=await Kc(st.join(e,"component-models.json")),o=await Xc(e),{isUeProject:r,blocks:a}=Tr({configPresent:t,blocks:o,modelIds:Ar(n)});i.info(j("Universal Editor config"));let s=[...Jn],d=O(s);for(let p of s)i.info(D(t[p]?"pass":"fail",p,void 0,d));if(!r){i.info(""),i.warn("This doesn't look like a Universal Editor (crosswalk) project - run `eds scaffold ue` first."),process.exitCode=1;return}let l=st.join(e,"head.html");if(ct(l)){let p=Cr(await Dr(l,"utf-8"));i.info(D(p?"pass":"info","head.html",p?"aemconnection present":"no aemconnection (fine for cloud author)"))}if(i.info(j("Blocks",`${a.length} found`)),a.length===0)i.info(Ht.dim(" No blocks yet."));else{let p=O(a.map(f=>f.name));for(let f of a)i.info(D(f.editable?"pass":"warn",f.name,f.reason,p))}let c=a.filter(p=>p.editable).length,u=a.length-c;i.info(""),i.info(de({pass:c,warn:u})),i.info(Ht.dim(" Open a page in the editor with `eds ue open <path>`."))}async function Zc(e,t={}){let n=E()??process.cwd(),o=e??t.path??"/",r=t.url;if(!r){let s=await Yc(n),d=s?Ne(s):null;if(!d){i.error("Couldn't determine the preview host from git."),i.info(Ht.dim(" Pass it explicitly: `eds ue open <path> --url main--<repo>--<owner>.aem.page`")),process.exitCode=1;return}r=_e(d.owner,d.repo,t.ref??"main")}let a=yi({host:r,path:o,org:t.org});i.info(j("Universal Editor")),i.info($("page",`${r}${o.startsWith("/")?"":"/"}${o}`)),i.info($("open",a)),t.open!==!1?await Vc(a):i.info(Ht.dim(" (use without --no-open to launch the browser)"))}var dt=w(()=>{"use strict";m();R();z();Rr();Tt();I()});var qn={};N(qn,{createBlock:()=>ol,ueModelFor:()=>Lr});import{existsSync as el}from"fs";import{mkdir as tl,writeFile as Wn}from"fs/promises";import pt from"path";import Fr from"chalk";function nl(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Lr(e){let t=nl(e);return`${JSON.stringify({definitions:[{title:t,id:e,plugins:{xwalk:{page:{resourceType:"core/franklin/components/block/v1/block",template:{name:t,model:e}}}}}],models:[{id:e,fields:[{component:"text",name:"title",label:"Title",valueType:"string"},{component:"select",name:"titleType",label:"Title Type",valueType:"string",value:"h2",options:[{name:"H1",value:"h1"},{name:"H2",value:"h2"},{name:"H3",value:"h3"},{name:"H4",value:"h4"}]},{component:"richtext",name:"text",value:"",label:"Text",valueType:"string"}]}],filters:[]},null,2)}
492
- `}async function ol(e,t={}){if(!ye.test(e)){i.error(`Invalid block name "${e}". Use kebab-case (e.g., "hero-banner", "card-list").`),process.exitCode=1;return}let n=E();if(!n){i.error("Not inside an EDS project (no EDS project markers found). Run this from your project root."),process.exitCode=1;return}let o=pt.join(n,"blocks",e);if(el(o)){i.error(`Block "${e}" already exists at ${o}`),process.exitCode=1;return}await tl(o,{recursive:!0});let r=`export default function decorate(block) {
491
+ }`}]});var eo={};L(eo,{schemaBlock:()=>xl});import{existsSync as wl}from"fs";import{readFile as bl,writeFile as yl}from"fs/promises";import vl from"path";import kl from"chalk";async function xl(e,t={}){let n=P();if(!n){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(E("Schema - JSON-LD"));let o=vl.join(n,"blocks",e,`${e}.js`);if(!wl(o)){r.error(`Block "${e}" not found (no blocks/${e}/${e}.js).`),process.exitCode=1;return}let i=t.type;if(!i&&!t.yes){let{select:d}=await Promise.resolve().then(()=>(G(),H));i=await d({message:"Which schema.org type?",choices:Yt.map(l=>({name:`${l.id} - ${l.label}`,value:l.id}))})}let a=i?Ur(i):void 0;if(!a){r.error(`Unknown schema type "${i}". Options: ${Yt.map(d=>d.id).join(", ")}`),process.exitCode=1;return}let s=Br(await bl(o,"utf-8"),a);if(!s.changed){r.warn(`Not added: ${s.reason}.`);return}await yl(o,s.js),r.info(S("JSON-LD added")),r.info(j(`blocks/${e}/${e}.js`,`${a.id} (${a.label})`)),r.info(""),r.info(kl.dim(" Review the generated object - some fields are heuristic or TODO. Validate at search.google.com/test/rich-results."))}var to=v(()=>{"use strict";f();R();B();Hr();N()});function Sl(e,t){for(let n of e.match(/<meta\b[^>]*>/gi)??[])if(n.match(/\bname=["']([^"']+)["']/i)?.[1]===t)return n.match(/\bcontent=["']([^"']*)["']/i)?.[1]??"";return null}function Gr(e){return Sl(e,$l)!==null}function zr(e){return Array.isArray(e)?e.map(t=>t&&typeof t=="object"?t.id:void 0).filter(t=>typeof t=="string"):[]}function Wr(e){let t=!!e.configPresent["component-definition.json"]&&!!e.configPresent["component-models.json"],n=new Set(e.modelIds),o=e.blocks.map(i=>{let a=i.hasModelFile||n.has(i.name);return{name:i.name,editable:a,reason:a?void 0:"no UE model (_<name>.json or component-models entry)"}});return{isUeProject:t,blocks:o}}var no,$l,Jr=v(()=>{"use strict";f();no=["component-definition.json","component-models.json","component-filters.json"],$l="urn:adobe:aue:system:aemconnection"});var wt={};L(wt,{ueCheck:()=>Tl,ueOpen:()=>Rl});import{existsSync as ht}from"fs";import{readFile as qr,readdir as jl}from"fs/promises";import gt from"path";import Qt from"chalk";async function Pl(e){if(!ht(e))return null;try{return JSON.parse(await qr(e,"utf-8"))}catch{return null}}async function El(e){let t=gt.join(e,"blocks");return ht(t)?(await jl(t,{withFileTypes:!0})).filter(o=>o.isDirectory()).map(o=>({name:o.name,hasModelFile:ht(gt.join(t,o.name,`_${o.name}.json`))})):[]}async function Cl(e){let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{let{execa:n}=await import("execa");await n(t,[e],{stdio:"ignore"})}catch{}}async function Al(e){try{let{execa:t}=await import("execa");return(await t("git",["remote","get-url","origin"],{cwd:e})).stdout.trim()||null}catch{return null}}async function Tl(){let e=P();if(!e){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(E("Universal Editor - readiness"));let t={};for(let m of no)t[m]=ht(gt.join(e,m));let n=await Pl(gt.join(e,"component-models.json")),o=await El(e),{isUeProject:i,blocks:a}=Wr({configPresent:t,blocks:o,modelIds:zr(n)});r.info(S("Universal Editor config"));let s=[...no],d=M(s);for(let m of s)r.info(A(t[m]?"pass":"fail",m,void 0,d));if(!i){r.info(""),r.warn("This doesn't look like a Universal Editor (crosswalk) project - run `eds scaffold ue` first."),process.exitCode=1;return}let l=gt.join(e,"head.html");if(ht(l)){let m=Gr(await qr(l,"utf-8"));r.info(A(m?"pass":"info","head.html",m?"aemconnection present":"no aemconnection (fine for cloud author)"))}if(r.info(S("Blocks",`${a.length} found`)),a.length===0)r.info(Qt.dim(" No blocks yet."));else{let m=M(a.map(u=>u.name));for(let u of a)r.info(A(u.editable?"pass":"warn",u.name,u.reason,m))}let c=a.filter(m=>m.editable).length,p=a.length-c;r.info(""),r.info(fe({pass:c,warn:p})),r.info(Qt.dim(" Open a page in the editor with `eds ue open <path>`."))}async function Rl(e,t={}){let n=P()??process.cwd(),o=e??t.path??"/",i=t.url;if(!i){let s=await Al(n),d=s?He(s):null;if(!d){r.error("Couldn't determine the preview host from git."),r.info(Qt.dim(" Pass it explicitly: `eds ue open <path> --url main--<repo>--<owner>.aem.page`")),process.exitCode=1;return}i=Ge(d.owner,d.repo,t.ref??"main")}let a=Li({host:i,path:o,org:t.org});r.info(S("Universal Editor")),r.info(j("page",`${i}${o.startsWith("/")?"":"/"}${o}`)),r.info(j("open",a)),t.open!==!1?await Cl(a):r.info(Qt.dim(" (use without --no-open to launch the browser)"))}var bt=v(()=>{"use strict";f();R();B();Jr();Ut();N()});var io={};L(io,{createBlock:()=>Ol,ueModelFor:()=>Xr});import{existsSync as Fl}from"fs";import{mkdir as Dl,writeFile as oo}from"fs/promises";import yt from"path";import Kr from"chalk";function Ll(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Xr(e){let t=Ll(e);return`${JSON.stringify({definitions:[{title:t,id:e,plugins:{xwalk:{page:{resourceType:"core/franklin/components/block/v1/block",template:{name:t,model:e}}}}}],models:[{id:e,fields:[{component:"text",name:"title",label:"Title",valueType:"string"},{component:"select",name:"titleType",label:"Title Type",valueType:"string",value:"h2",options:[{name:"H1",value:"h1"},{name:"H2",value:"h2"},{name:"H3",value:"h3"},{name:"H4",value:"h4"}]},{component:"richtext",name:"text",value:"",label:"Text",valueType:"string"}]}],filters:[]},null,2)}
492
+ `}async function Ol(e,t={}){if(!Se.test(e)){r.error(`Invalid block name "${e}". Use kebab-case (e.g., "hero-banner", "card-list").`),process.exitCode=1;return}let n=P();if(!n){r.error("Not inside an EDS project (no EDS project markers found). Run this from your project root."),process.exitCode=1;return}let o=yt.join(n,"blocks",e);if(Fl(o)){r.error(`Block "${e}" already exists at ${o}`),process.exitCode=1;return}await Dl(o,{recursive:!0});let i=`export default function decorate(block) {
493
493
  // TODO: implement ${e} block
494
494
  }
495
495
  `,a=`.${e} {
496
496
  /* TODO: style ${e} block */
497
497
  }
498
- `;await Wn(pt.join(o,`${e}.js`),r),await Wn(pt.join(o,`${e}.css`),a);let s=t.ueModel!==!1;s&&await Wn(pt.join(o,`_${e}.json`),Lr(e)),i.success(`Block "${e}" created at ${Fr.cyan(pt.relative(n,o))}${s?Fr.dim(" (+ Universal Editor model)"):""}`)}var Kn=w(()=>{"use strict";m();R();z();Me()});import{existsSync as Gt}from"fs";import{readFile as il}from"fs/promises";import{homedir as Ue}from"os";import Be from"path";async function Vn(e){let{execaCommand:t}=await import("execa");try{return(await t(`which ${e}`)).stdout.trim()||void 0}catch{return}}function Or(e){if(!e||typeof e!="object")return;let t=e,n=t.mcpServers;if(n&&typeof n=="object"){for(let o of Object.keys(n))if(o.toLowerCase().includes("figma"))return o}for(let o of Object.values(t)){let r=Or(o);if(r)return r}}async function Yn(e){for(let t of e)try{if(!Gt(t))continue;let n=await il(t,"utf-8");try{let o=Or(JSON.parse(n));if(o)return o}catch{}if(n.toLowerCase().includes("figma"))return"figma"}catch{}}async function Mr(e){if(e){let t=Xn.find(n=>n.type===e);if(t){let n=await Vn(t.binary);if(n){let o=await Yn(t.mcpConfigPaths);return{type:t.type,path:n,configDir:Gt(t.configDir)?t.configDir:void 0,hasFigmaMcp:!!o,figmaMcpServerName:o}}i.warn(`Preferred agent "${e}" not found in PATH`)}}for(let t of Xn){let n=await Vn(t.binary);if(n){let o=await Yn(t.mcpConfigPaths);return{type:t.type,path:n,configDir:Gt(t.configDir)?t.configDir:void 0,hasFigmaMcp:!!o,figmaMcpServerName:o}}}}async function zt(){let e=[];for(let t of Xn){let n=await Vn(t.binary);if(n){let o=await Yn(t.mcpConfigPaths);e.push({type:t.type,path:n,configDir:Gt(t.configDir)?t.configDir:void 0,hasFigmaMcp:!!o,figmaMcpServerName:o})}}return e}var Xn,Qn=w(()=>{"use strict";m();R();Xn=[{type:"claude",binary:"claude",configDir:Be.join(Ue(),".claude"),mcpConfigPaths:[Be.join(Ue(),".claude","plugins.json"),Be.join(Ue(),".claude.json")]},{type:"cursor",binary:"cursor",configDir:Be.join(Ue(),".cursor"),mcpConfigPaths:[Be.join(Ue(),".cursor","mcp.json")]},{type:"codex",binary:"codex",configDir:Be.join(Ue(),".codex"),mcpConfigPaths:[]}]});import{mkdir as rl,readFile as al,writeFile as sl}from"fs/promises";import{tmpdir as cl}from"os";import mt from"path";import ll from"readline";import ee from"chalk";async function Zn(e,t){let n=t?mt.join(t,"tmp"):cl(),o=mt.join(n,"eds-cli");await rl(o,{recursive:!0});let r=`from-design-${Date.now()}.md`,a=mt.join(o,r);return await sl(a,e,"utf-8"),a}async function eo(e,t,n,o){let{execa:r}=await import("execa"),a=await al(t,"utf-8");try{switch(e.type){case"claude":{i.info(`Running Claude Code ${ee.dim("- live log:")}`);let s=[...e.figmaMcpServerName?[e.figmaMcpServerName]:[],"figma-sse","figma-desktop","figma","Figma","plugin_figma_figma"],d=[...new Set(s.map(u=>`mcp__${u}`)),"Edit","Write","Read"].join(","),c=r("claude",["-p",a,"--model",o??"haiku","--output-format","stream-json","--verbose","--allowedTools",d],{cwd:n,buffer:!1,stdio:["ignore","pipe","inherit"]});await pl(c,n);break}case"cursor":{i.info("Running Cursor agent..."),await r("cursor",["--prompt",a],{cwd:n,stdio:"inherit"});break}case"codex":{i.info("Running Codex..."),await r("codex",[a],{cwd:n,stdio:"inherit"});break}}return!0}catch(s){let d=s instanceof Error?s.message:String(s);return i.error(`Agent ${e.type} failed: ${d}`),!1}}function dl(e){return e.includes("figma")?e.split("__").pop()??e:e.toLowerCase()}async function pl(e,t){let n=(await import("ora")).default,o=Date.now(),r=()=>`${Math.round((Date.now()-o)/1e3)}s`,a=n({text:`thinking ${ee.dim(r())}`,color:"yellow"}).start(),s="thinking",d=setInterval(()=>{a.text=`${s} ${ee.dim(r())}`},300),l=new Map,c=p=>{a.stop(),i.info(` ${p}`),a.start()},u;try{if(e.stdout){let p=ll.createInterface({input:e.stdout});for await(let f of p){let g=f.trim();if(!g)continue;let y;try{y=JSON.parse(g)}catch{continue}let h=Array.isArray(y.message?.content)?y.message.content:[];if(y.type==="assistant"){for(let b of h)if(b.type==="text"&&"text"in b){let S=b.text.trim().split(`
499
- `)[0].slice(0,100);S&&c(ee.dim(S))}else if(b.type==="tool_use"&&"name"in b){let S="id"in b&&b.id?b.id:`${Math.random()}`;l.set(S,{label:ml(b.name,b.input,t),start:Date.now()}),s=dl(b.name)}}else if(y.type==="user"){for(let b of h)if(b.type==="tool_result"&&"tool_use_id"in b&&b.tool_use_id){let S=l.get(b.tool_use_id);if(S){let x=`${((Date.now()-S.start)/1e3).toFixed(1)}s`,T="is_error"in b&&b.is_error?` ${ee.red("failed")}`:"";c(`${S.label} ${ee.dim(x)}${T}`),l.delete(b.tool_use_id)}}}else if(y.type==="result"){let b=typeof y.duration_ms=="number"?`${(y.duration_ms/1e3).toFixed(1)}s`:"",S=typeof y.total_cost_usd=="number"?`$${y.total_cost_usd.toFixed(3)}`:"";u=[b,S].filter(Boolean).join(" \xB7 ")||"done"}}}for(let p of l.values())c(`${p.label} ${ee.dim("\u2026")}`);clearInterval(d),u?a.succeed(`${_.accent("agent finished")} ${ee.dim(u)}`):a.stop()}catch(p){throw clearInterval(d),a.stop(),p}await e}function ml(e,t,n){let o=r=>{let a=t?.[r];return typeof a!="string"?"":a.startsWith(n)?mt.relative(n,a):mt.basename(a)};if(e.includes("figma")){let r=e.split("__").pop()??e;return`${J.figma} ${ee.bold(r)} ${ee.dim("Figma MCP")}`}switch(e){case"Write":case"Edit":case"NotebookEdit":return`${_.accent("\u270E")} ${ee.cyan(o("file_path"))}`;case"Read":return ee.dim(`\xB7 read ${o("file_path")}`);case"Bash":{let r=typeof t?.command=="string"?t.command.split(`
500
- `)[0].slice(0,70):"";return ee.dim(`$ ${r}`)}default:return`${_.blue("\u2192")} ${e}`}}var Nr=w(()=>{"use strict";m();R();I()});import{existsSync as ul}from"fs";import{readFile as fl}from"fs/promises";import{homedir as gl}from"os";import to from"path";async function _r(e){try{let t=await fl(e,"utf-8");return JSON.parse(t)}catch{return}}async function fe(e){let t=await _r(no),n=e?await _r(to.join(e,hl)):void 0,o={...typeof t=="object"&&t!==null?t:{},...typeof n=="object"&&n!==null?n:{}},r=sn.safeParse(o);return r.success?r.data:(i.debug("Config validation issues:",r.error.flatten()),sn.parse({}))}function Ur(){return Ir}function oo(){return no}function io(){return ul(no)}var Ir,no,hl,Pe=w(()=>{"use strict";m();R();Me();Ir=to.join(gl(),".eds"),no=to.join(Ir,"config.json"),hl=".edsrc.json"});function Br(e){return e<=480?`${e} mobile`:e<=1024?`${e} tablet`:`${e} desktop`}function bl(e,t="figma"){return e?e.split(",").map(n=>Number.parseInt(n.trim(),10)).filter(n=>Number.isFinite(n)&&n>0).map(n=>({width:n,label:Br(n),source:t})):[]}function Hr(e,t){let n=bl(e,"figma");return n.length?n:wl(t)}function wl(e){if(!Array.isArray(e))return[];let t=new Set,n=[];for(let o of e){let r=Number(o?.width);if(!Number.isFinite(r)||r<=0||t.has(r))continue;t.add(r);let a=o.source;n.push({width:r,label:Br(r),source:a==="figma"?"figma":"default"})}return n}var Gr=w(()=>{"use strict";m()});async function qr(e){let{fileKey:t,nodeId:n,token:o}=e,r=n?`${zr}/files/${t}/nodes?ids=${encodeURIComponent(n)}`:`${zr}/files/${t}`,a=await fetch(r,{headers:{"X-Figma-Token":o}});if(!a.ok){let s=await a.text().catch(()=>""),d=a.status===403?" (check the token scope: it needs file_content:read, and access to this file)":a.status===404?" (file or node not found \u2014 check the URL)":"";throw new Error(`Figma REST ${a.status} ${a.statusText}${d}${s?` \u2014 ${s.slice(0,200)}`:""}`)}return a.json()}function ro(e){if(!e)return;let t=o=>Math.round(Math.max(0,Math.min(1,o))*255).toString(16).padStart(2,"0"),n=`#${t(e.r)}${t(e.g)}${t(e.b)}`;return e.a!==void 0&&e.a<1?`${n}${t(e.a)}`:n}function Wr(e){let t=e?.find(n=>n.visible!==!1);if(t){if(t.type==="SOLID")return ro(t.color);if(t.type?.startsWith("GRADIENT")){let n=(t.gradientStops??[]).map(o=>ro(o.color)).filter(Boolean);return n.length?`gradient(${n.join(" \u2192 ")})`:"gradient"}return t.type==="IMAGE"?"image(placeholder)":t.type?.toLowerCase()}}function Kr(e,t){if(!e||typeof e!="object")return null;let n={name:e.name,type:e.type};if(e.absoluteBoundingBox){let{width:s,height:d}=e.absoluteBoundingBox;s!=null&&d!=null&&(n.size={w:Math.round(s),h:Math.round(d)})}e.layoutMode&&e.layoutMode!=="NONE"&&(n.layout={direction:e.layoutMode==="HORIZONTAL"?"row":"column",gap:e.itemSpacing,padding:[e.paddingTop,e.paddingRight,e.paddingBottom,e.paddingLeft],align:[e.primaryAxisAlignItems,e.counterAxisAlignItems].filter(Boolean).join("/")});let o=Wr(e.fills);o&&(n.fill=o);let r=Wr(e.strokes);r&&(n.stroke={color:r,weight:e.strokeWeight}),e.cornerRadius&&(n.radius=e.cornerRadius);let a=(e.effects??[]).filter(s=>s.visible!==!1&&(s.type==="DROP_SHADOW"||s.type==="INNER_SHADOW")).map(s=>`${s.type==="INNER_SHADOW"?"inset ":""}${s.offset?.x??0} ${s.offset?.y??0} ${s.radius??0} ${ro(s.color)??""}`.trim());if(a.length&&(n.shadows=a),e.type==="TEXT"&&e.characters!==void 0){n.text=e.characters;let s=e.style??{};n.font={family:s.fontFamily,size:s.fontSize,weight:s.fontWeight,lineHeight:s.lineHeightPx,letterSpacing:s.letterSpacing,align:s.textAlignHorizontal}}if(e.children?.length&&t<yl){let s=e.children.slice(0,Jr).map(d=>Kr(d,t+1)).filter(Boolean);s.length&&(n.children=s),e.children.length>Jr&&(n.childrenTruncated=e.children.length)}return n}function Xr(e,t){let n=e,o;if(t&&n.nodes){let a=Object.keys(n.nodes)[0];o=a?n.nodes[a]?.document:void 0}if(o??=n.document,!o)throw new Error("Figma REST response had no document node to serialize.");let r={source:"figma-rest",file:n.name,root:Kr(o,0)};return JSON.stringify(r,null,2)}var zr,yl,Jr,Vr=w(()=>{"use strict";m();zr="https://api.figma.com/v1";yl=12,Jr=60});import{existsSync as vl}from"fs";import{mkdir as kl,readFile as xl,writeFile as $l}from"fs/promises";import ao from"path";function Sl(e,t,n){let o=a=>a.replace(/[^a-z0-9._-]/gi,"-"),r=`${o(t)}__${o(n??"file")}.json`;return ao.join(e,"tmp","eds-cli","design-cache",r)}async function jl(e){if(!vl(e))return null;try{return await xl(e,"utf-8")}catch{return null}}async function El(e,t){await kl(ao.dirname(e),{recursive:!0}),await $l(e,t,"utf-8")}async function Yr(e){if(e.localFile)return{design:{mode:"file",filePath:e.localFile},summary:`local file ${e.localFile}`};let{figma:t,projectRoot:n}=e;if(!t?.fileKey)return{summary:"provider MCP"};let o=Sl(n,t.fileKey,t.nodeId),r=ao.relative(n,o);if(!e.refresh){let a=await jl(o);if(a)return{design:{mode:"spec",spec:a,cachePath:r},summary:`cache ${r}`}}if(e.token&&!e.preferMcp)try{let a=await qr({fileKey:t.fileKey,nodeId:t.nodeId,token:e.token}),s=Xr(a,t.nodeId);return await El(o,s),{design:{mode:"spec",spec:s,cachePath:r},summary:`REST \u2192 ${r}`}}catch(a){return{design:{mode:"mcp",cachePath:r},summary:"MCP (REST failed \u2014 1 call)",restError:a instanceof Error?a.message:String(a)}}return{design:{mode:"mcp",cachePath:r},summary:"MCP (1 call, cached)"}}var Qr=w(()=>{"use strict";m();Vr()});function Jt(e){if(/^\d+[-:]\d+$/.test(e.trim()))throw new Error(`Input "${e}" looks like a node-id but not a full URL. Provide a Figma URL or use --file-key.`);let t;try{t=new URL(e.trim())}catch{throw new Error(`Invalid Figma URL: "${e}"`)}if(!t.hostname.endsWith("figma.com"))throw new Error(`Not a Figma URL: "${e}"`);let n=t.pathname.split("/").filter(Boolean);if(n.length<2)throw new Error(`Cannot extract fileKey from URL: "${e}"`);let o=n[0],r,a;n[2]==="branch"&&n[3]?(r=n[3],a=n[4]?decodeURIComponent(n[4]):void 0):(r=n[1],a=n[2]?decodeURIComponent(n[2]):void 0);let s=t.searchParams.get("node-id"),d=s?Pl(s):void 0;return{fileKey:r,nodeId:d,fileName:a}}function Pl(e){return decodeURIComponent(e).replace(/-/g,":")}var Zr=w(()=>{"use strict";m()});import{existsSync as Cl}from"fs";import{readFile as Al}from"fs/promises";import Tl from"path";function Rl(e,t,n){if(!e||e==="document"||e==="ue")return"";let o=t?` (model / persisted query: \`${t}\`)`:"",r="`${window.location.origin}/graphql/execute.json/<project>/<query>;path=<cfPath>`";return e==="cf"?`
498
+ `;await oo(yt.join(o,`${e}.js`),i),await oo(yt.join(o,`${e}.css`),a);let s=t.ueModel!==!1;s&&await oo(yt.join(o,`_${e}.json`),Xr(e)),r.success(`Block "${e}" created at ${Kr.cyan(yt.relative(n,o))}${s?Kr.dim(" (+ Universal Editor model)"):""}`)}var ro=v(()=>{"use strict";f();R();B();Be()});import{existsSync as Zt}from"fs";import{readFile as Nl}from"fs/promises";import{homedir as We}from"os";import Je from"path";async function so(e){let{execaCommand:t}=await import("execa");try{return(await t(`which ${e}`)).stdout.trim()||void 0}catch{return}}function Vr(e){if(!e||typeof e!="object")return;let t=e,n=t.mcpServers;if(n&&typeof n=="object"){for(let o of Object.keys(n))if(o.toLowerCase().includes("figma"))return o}for(let o of Object.values(t)){let i=Vr(o);if(i)return i}}async function co(e){for(let t of e)try{if(!Zt(t))continue;let n=await Nl(t,"utf-8");try{let o=Vr(JSON.parse(n));if(o)return o}catch{}if(n.toLowerCase().includes("figma"))return"figma"}catch{}}async function Yr(e){if(e){let t=ao.find(n=>n.type===e);if(t){let n=await so(t.binary);if(n){let o=await co(t.mcpConfigPaths);return{type:t.type,path:n,configDir:Zt(t.configDir)?t.configDir:void 0,hasFigmaMcp:!!o,figmaMcpServerName:o}}r.warn(`Preferred agent "${e}" not found in PATH`)}}for(let t of ao){let n=await so(t.binary);if(n){let o=await co(t.mcpConfigPaths);return{type:t.type,path:n,configDir:Zt(t.configDir)?t.configDir:void 0,hasFigmaMcp:!!o,figmaMcpServerName:o}}}}async function en(){let e=[];for(let t of ao){let n=await so(t.binary);if(n){let o=await co(t.mcpConfigPaths);e.push({type:t.type,path:n,configDir:Zt(t.configDir)?t.configDir:void 0,hasFigmaMcp:!!o,figmaMcpServerName:o})}}return e}var ao,lo=v(()=>{"use strict";f();R();ao=[{type:"claude",binary:"claude",configDir:Je.join(We(),".claude"),mcpConfigPaths:[Je.join(We(),".claude","plugins.json"),Je.join(We(),".claude.json")]},{type:"cursor",binary:"cursor",configDir:Je.join(We(),".cursor"),mcpConfigPaths:[Je.join(We(),".cursor","mcp.json")]},{type:"codex",binary:"codex",configDir:Je.join(We(),".codex"),mcpConfigPaths:[]}]});import{mkdir as Ml,readFile as Il,writeFile as _l}from"fs/promises";import{tmpdir as Ul}from"os";import vt from"path";import Bl from"readline";import ee from"chalk";async function po(e,t){let n=t?vt.join(t,"tmp"):Ul(),o=vt.join(n,"eds-cli");await Ml(o,{recursive:!0});let i=`from-design-${Date.now()}.md`,a=vt.join(o,i);return await _l(a,e,"utf-8"),a}async function mo(e,t,n,o){let{execa:i}=await import("execa"),a=await Il(t,"utf-8");try{switch(e.type){case"claude":{r.info(`Running Claude Code ${ee.dim("- live log:")}`);let s=[...e.figmaMcpServerName?[e.figmaMcpServerName]:[],"figma-sse","figma-desktop","figma","Figma","plugin_figma_figma"],d=[...new Set(s.map(p=>`mcp__${p}`)),"Edit","Write","Read"].join(","),c=i("claude",["-p",a,"--model",o??"haiku","--output-format","stream-json","--verbose","--allowedTools",d],{cwd:n,buffer:!1,stdio:["ignore","pipe","inherit"]});await Gl(c,n);break}case"cursor":{r.info("Running Cursor agent..."),await i("cursor",["--prompt",a],{cwd:n,stdio:"inherit"});break}case"codex":{r.info("Running Codex..."),await i("codex",[a],{cwd:n,stdio:"inherit"});break}}return!0}catch(s){let d=s instanceof Error?s.message:String(s);return r.error(`Agent ${e.type} failed: ${d}`),!1}}function Hl(e){return e.includes("figma")?e.split("__").pop()??e:e.toLowerCase()}async function Gl(e,t){let n=(await import("ora")).default,o=Date.now(),i=()=>`${Math.round((Date.now()-o)/1e3)}s`,a=n({text:`thinking ${ee.dim(i())}`,color:"yellow"}).start(),s="thinking",d=setInterval(()=>{a.text=`${s} ${ee.dim(i())}`},300),l=new Map,c=m=>{a.stop(),r.info(` ${m}`),a.start()},p;try{if(e.stdout){let m=Bl.createInterface({input:e.stdout});for await(let u of m){let g=u.trim();if(!g)continue;let w;try{w=JSON.parse(g)}catch{continue}let y=Array.isArray(w.message?.content)?w.message.content:[];if(w.type==="assistant"){for(let h of y)if(h.type==="text"&&"text"in h){let $=h.text.trim().split(`
499
+ `)[0].slice(0,100);$&&c(ee.dim($))}else if(h.type==="tool_use"&&"name"in h){let $="id"in h&&h.id?h.id:`${Math.random()}`;l.set($,{label:zl(h.name,h.input,t),start:Date.now()}),s=Hl(h.name)}}else if(w.type==="user"){for(let h of y)if(h.type==="tool_result"&&"tool_use_id"in h&&h.tool_use_id){let $=l.get(h.tool_use_id);if($){let b=`${((Date.now()-$.start)/1e3).toFixed(1)}s`,T="is_error"in h&&h.is_error?` ${ee.red("failed")}`:"";c(`${$.label} ${ee.dim(b)}${T}`),l.delete(h.tool_use_id)}}}else if(w.type==="result"){let h=typeof w.duration_ms=="number"?`${(w.duration_ms/1e3).toFixed(1)}s`:"",$=typeof w.total_cost_usd=="number"?`$${w.total_cost_usd.toFixed(3)}`:"";p=[h,$].filter(Boolean).join(" \xB7 ")||"done"}}}for(let m of l.values())c(`${m.label} ${ee.dim("\u2026")}`);clearInterval(d),p?a.succeed(`${_.accent("agent finished")} ${ee.dim(p)}`):a.stop()}catch(m){throw clearInterval(d),a.stop(),m}await e}function zl(e,t,n){let o=i=>{let a=t?.[i];return typeof a!="string"?"":a.startsWith(n)?vt.relative(n,a):vt.basename(a)};if(e.includes("figma")){let i=e.split("__").pop()??e;return`${q.figma} ${ee.bold(i)} ${ee.dim("Figma MCP")}`}switch(e){case"Write":case"Edit":case"NotebookEdit":return`${_.accent("\u270E")} ${ee.cyan(o("file_path"))}`;case"Read":return ee.dim(`\xB7 read ${o("file_path")}`);case"Bash":{let i=typeof t?.command=="string"?t.command.split(`
500
+ `)[0].slice(0,70):"";return ee.dim(`$ ${i}`)}default:return`${_.blue("\u2192")} ${e}`}}var Qr=v(()=>{"use strict";f();R();N()});import{existsSync as Wl}from"fs";import{readFile as Jl}from"fs/promises";import{homedir as ql}from"os";import uo from"path";async function Zr(e){try{let t=await Jl(e,"utf-8");return JSON.parse(t)}catch{return}}async function se(e){let t=await Zr(fo),n=e?await Zr(uo.join(e,Kl)):void 0,o={...typeof t=="object"&&t!==null?t:{},...typeof n=="object"&&n!==null?n:{}},i=bn.safeParse(o);return i.success?i.data:(r.debug("Config validation issues:",i.error.flatten()),bn.parse({}))}function ta(){return ea}function go(){return fo}function ho(){return Wl(fo)}var ea,fo,Kl,be=v(()=>{"use strict";f();R();Be();ea=uo.join(ql(),".eds"),fo=uo.join(ea,"config.json"),Kl=".edsrc.json"});function na(e){return e<=480?`${e} mobile`:e<=1024?`${e} tablet`:`${e} desktop`}function Xl(e,t="figma"){return e?e.split(",").map(n=>Number.parseInt(n.trim(),10)).filter(n=>Number.isFinite(n)&&n>0).map(n=>({width:n,label:na(n),source:t})):[]}function oa(e,t){let n=Xl(e,"figma");return n.length?n:Vl(t)}function Vl(e){if(!Array.isArray(e))return[];let t=new Set,n=[];for(let o of e){let i=Number(o?.width);if(!Number.isFinite(i)||i<=0||t.has(i))continue;t.add(i);let a=o.source;n.push({width:i,label:na(i),source:a==="figma"?"figma":"default"})}return n}var ia=v(()=>{"use strict";f()});async function Yl(){try{return(await import("playwright")).chromium}catch{throw new Error("Scraping needs Playwright. Install it with `npm i -D playwright` (it ships as an optional dependency), then `npx playwright install chromium`.")}}async function ra(e){let t=e.width??1440,n=await Yl(),o;try{o=await n.launch({headless:!0})}catch(i){let a=i instanceof Error?i.message:String(i);throw/Executable doesn't exist|install/i.test(a)?new Error("Chromium isn't installed for Playwright. Run `npx playwright install chromium`."):i}try{let i=await o.newPage({viewport:{width:t,height:900},deviceScaleFactor:1});await i.goto(e.url,{waitUntil:"networkidle",timeout:45e3}),await i.waitForTimeout(700);let a=await i.evaluate(Ql,{maxNodes:320,maxDepth:14,textCap:200}),s={source:`scrape:${e.provider}`,url:e.url,viewport:t,title:a.title,root:a.root,nodeCount:a.nodeCount,truncated:a.truncated};return JSON.stringify(s,null,2)}finally{await o.close()}}function Ql(e){let t=new Set(["SCRIPT","STYLE","NOSCRIPT","LINK","META","HEAD","BR","TEMPLATE"]),n=0,o=!1,i=c=>!c||c==="none"||c==="normal"||c==="auto"||c==="0px"||c==="rgba(0, 0, 0, 0)"||c==="transparent";function a(c){let p="";for(let m of Array.from(c.childNodes))m.nodeType===3&&(p+=m.textContent??"");return p=p.replace(/\s+/g," ").trim(),p.length>e.textCap?`${p.slice(0,e.textCap)}\u2026`:p}function s(c){let p=getComputedStyle(c),m={},u=(g,w)=>{i(w)||(m[g]=w)};return u("display",p.display),(p.display.includes("flex")||p.display.includes("grid"))&&(u("flexDirection",p.flexDirection),u("justifyContent",p.justifyContent),u("alignItems",p.alignItems),u("gap",p.gap)),u("padding",p.padding),u("margin",p.margin),u("color",p.color),u("background",p.backgroundColor),p.backgroundImage&&p.backgroundImage!=="none"&&(m.backgroundImage=p.backgroundImage.slice(0,160)),u("fontFamily",p.fontFamily),u("fontSize",p.fontSize),u("fontWeight",p.fontWeight),u("lineHeight",p.lineHeight),u("letterSpacing",p.letterSpacing),u("textAlign",p.textAlign),u("border",p.border),u("borderRadius",p.borderRadius),u("boxShadow",p.boxShadow),p.opacity&&p.opacity!=="1"&&(m.opacity=p.opacity),p.position&&p.position!=="static"&&(m.position=p.position),m}function d(c,p){if(n>=e.maxNodes)return o=!0,null;if(t.has(c.tagName))return null;let m=c.getBoundingClientRect(),u=getComputedStyle(c);if(u.display==="none"||u.visibility==="hidden"||u.opacity==="0"||m.width<1||m.height<1)return null;n++;let w={tag:c.tagName.toLowerCase(),rect:{x:Math.round(m.x),y:Math.round(m.y),w:Math.round(m.width),h:Math.round(m.height)}},y=(c.getAttribute("class")||"").trim().split(/\s+/).filter(Boolean).slice(0,3);y.length&&(w.class=y.join(" "));let h=s(c);if(Object.keys(h).length&&(w.style=h),c.tagName==="IMG"){let b=c;w.img={src:(b.currentSrc||b.src||"").slice(0,200),alt:b.alt||"",w:b.naturalWidth,h:b.naturalHeight}}let $=a(c);if($&&(w.text=$),p<e.maxDepth){let b=[];for(let T of Array.from(c.children)){let Q=d(T,p+1);Q&&b.push(Q)}b.length&&(w.children=b)}return w}let l=d(document.body,0);return{title:document.title,root:l,nodeCount:n,truncated:o}}var aa=v(()=>{"use strict";f()});async function la(e){let{fileKey:t,nodeId:n,token:o}=e,i=n?`${wo}/files/${t}/nodes?ids=${encodeURIComponent(n)}`:`${wo}/files/${t}`,a=await fetch(i,{headers:{"X-Figma-Token":o}});if(!a.ok){let s=await a.text().catch(()=>""),d=a.status===403?" (check the token scope: it needs file_content:read, and access to this file)":a.status===404?" (file or node not found \u2014 check the URL)":"";throw new Error(`Figma REST ${a.status} ${a.statusText}${d}${s?` \u2014 ${s.slice(0,200)}`:""}`)}return a.json()}async function da(e){let{fileKey:t,nodeId:n,token:o,scale:i=1}=e;if(!n)throw new Error("A node id is required to render a Figma image.");let a=`${wo}/images/${t}?ids=${encodeURIComponent(n)}&format=png&scale=${i}`,s=await fetch(a,{headers:{"X-Figma-Token":o}});if(!s.ok){let p=await s.text().catch(()=>"");throw new Error(`Figma images ${s.status} ${s.statusText}${p?` \u2014 ${p.slice(0,200)}`:""}`)}let d=await s.json();if(d.err)throw new Error(`Figma images: ${d.err}`);let l=d.images?.[n]??Object.values(d.images??{}).find(Boolean);if(!l)throw new Error("Figma returned no image URL for that node.");let c=await fetch(l);if(!c.ok)throw new Error(`Fetching the rendered image failed: ${c.status} ${c.statusText}`);return Buffer.from(await c.arrayBuffer())}function bo(e){if(!e)return;let t=o=>Math.round(Math.max(0,Math.min(1,o))*255).toString(16).padStart(2,"0"),n=`#${t(e.r)}${t(e.g)}${t(e.b)}`;return e.a!==void 0&&e.a<1?`${n}${t(e.a)}`:n}function ca(e){let t=e?.find(n=>n.visible!==!1);if(t){if(t.type==="SOLID")return bo(t.color);if(t.type?.startsWith("GRADIENT")){let n=(t.gradientStops??[]).map(o=>bo(o.color)).filter(Boolean);return n.length?`gradient(${n.join(" \u2192 ")})`:"gradient"}return t.type==="IMAGE"?"image(placeholder)":t.type?.toLowerCase()}}function pa(e,t){if(!e||typeof e!="object")return null;let n={name:e.name,type:e.type};if(e.absoluteBoundingBox){let{width:s,height:d}=e.absoluteBoundingBox;s!=null&&d!=null&&(n.size={w:Math.round(s),h:Math.round(d)})}e.layoutMode&&e.layoutMode!=="NONE"&&(n.layout={direction:e.layoutMode==="HORIZONTAL"?"row":"column",gap:e.itemSpacing,padding:[e.paddingTop,e.paddingRight,e.paddingBottom,e.paddingLeft],align:[e.primaryAxisAlignItems,e.counterAxisAlignItems].filter(Boolean).join("/")});let o=ca(e.fills);o&&(n.fill=o);let i=ca(e.strokes);i&&(n.stroke={color:i,weight:e.strokeWeight}),e.cornerRadius&&(n.radius=e.cornerRadius);let a=(e.effects??[]).filter(s=>s.visible!==!1&&(s.type==="DROP_SHADOW"||s.type==="INNER_SHADOW")).map(s=>`${s.type==="INNER_SHADOW"?"inset ":""}${s.offset?.x??0} ${s.offset?.y??0} ${s.radius??0} ${bo(s.color)??""}`.trim());if(a.length&&(n.shadows=a),e.type==="TEXT"&&e.characters!==void 0){n.text=e.characters;let s=e.style??{};n.font={family:s.fontFamily,size:s.fontSize,weight:s.fontWeight,lineHeight:s.lineHeightPx,letterSpacing:s.letterSpacing,align:s.textAlignHorizontal}}if(e.children?.length&&t<Zl){let s=e.children.slice(0,sa).map(d=>pa(d,t+1)).filter(Boolean);s.length&&(n.children=s),e.children.length>sa&&(n.childrenTruncated=e.children.length)}return n}function ma(e,t){let n=e,o;if(t&&n.nodes){let a=Object.keys(n.nodes)[0];o=a?n.nodes[a]?.document:void 0}if(o??=n.document,!o)throw new Error("Figma REST response had no document node to serialize.");let i={source:"figma-rest",file:n.name,root:pa(o,0)};return JSON.stringify(i,null,2)}var wo,Zl,sa,yo=v(()=>{"use strict";f();wo="https://api.figma.com/v1";Zl=12,sa=60});import{existsSync as ed}from"fs";import{mkdir as td,readFile as nd,writeFile as od}from"fs/promises";import kt from"path";function id(e,t,n){let o=a=>a.replace(/[^a-z0-9._-]/gi,"-"),i=`${o(t)}__${o(n??"file")}.json`;return kt.join(e,"tmp","eds-cli","design-cache",i)}function rd(e,t){let n=`scrape__${t.replace(/[^a-z0-9._-]/gi,"-").slice(0,120)}.json`;return kt.join(e,"tmp","eds-cli","design-cache",n)}function ad(e){return e==="framer"||e==="stitch"}async function ua(e){if(!ed(e))return null;try{return await nd(e,"utf-8")}catch{return null}}async function fa(e,t){await td(kt.dirname(e),{recursive:!0}),await od(e,t,"utf-8")}async function ga(e){let{figma:t,projectRoot:n}=e;if(e.localFile)return{design:{mode:"file",filePath:e.localFile},summary:`local file ${e.localFile}`};if(ad(e.provider)&&e.designUrl){let a=rd(n,e.designUrl),s=kt.relative(n,a);if(e.dryRun)return{design:{mode:"scrape",spec:`{ "note": "dry run \u2014 the live ${e.provider} page is scraped at generate time", "url": "${e.designUrl}" }`,cachePath:s},summary:`scrape (dry run) ${e.designUrl}`};if(!e.refresh){let d=await ua(a);if(d)return{design:{mode:"scrape",spec:d,cachePath:s},summary:`cache ${s}`}}try{let d=await ra({url:e.designUrl,provider:e.provider});return await fa(a,d),{design:{mode:"scrape",spec:d,cachePath:s},summary:`scrape \u2192 ${s}`}}catch(d){return{summary:"scrape failed",scrapeError:d instanceof Error?d.message:String(d)}}}if(!t?.fileKey)return{summary:"no design source"};let o=id(n,t.fileKey,t.nodeId),i=kt.relative(n,o);if(!e.refresh){let a=await ua(o);if(a)return{design:{mode:"spec",spec:a,cachePath:i},summary:`cache ${i}`}}if(e.token&&!e.preferMcp)try{let a=await la({fileKey:t.fileKey,nodeId:t.nodeId,token:e.token}),s=ma(a,t.nodeId);return await fa(o,s),{design:{mode:"spec",spec:s,cachePath:i},summary:`REST \u2192 ${i}`}}catch(a){return{design:{mode:"mcp",cachePath:i},summary:"MCP (REST failed \u2014 1 call)",restError:a instanceof Error?a.message:String(a)}}return{design:{mode:"mcp",cachePath:i},summary:"MCP (1 call, cached)"}}var ha=v(()=>{"use strict";f();aa();yo()});function tn(e){if(/^\d+[-:]\d+$/.test(e.trim()))throw new Error(`Input "${e}" looks like a node-id but not a full URL. Provide a Figma URL or use --file-key.`);let t;try{t=new URL(e.trim())}catch{throw new Error(`Invalid Figma URL: "${e}"`)}if(!t.hostname.endsWith("figma.com"))throw new Error(`Not a Figma URL: "${e}"`);let n=t.pathname.split("/").filter(Boolean);if(n.length<2)throw new Error(`Cannot extract fileKey from URL: "${e}"`);let o=n[0],i,a;n[2]==="branch"&&n[3]?(i=n[3],a=n[4]?decodeURIComponent(n[4]):void 0):(i=n[1],a=n[2]?decodeURIComponent(n[2]):void 0);let s=t.searchParams.get("node-id"),d=s?sd(s):void 0;return{fileKey:i,nodeId:d,fileName:a}}function sd(e){return decodeURIComponent(e).replace(/-/g,":")}var wa=v(()=>{"use strict";f()});import{existsSync as cd}from"fs";import{readFile as ld}from"fs/promises";import dd from"path";function pd(e,t,n){if(!e||e==="document"||e==="ue")return"";let o=t?` (model / persisted query: \`${t}\`)`:"",i="`${window.location.origin}/graphql/execute.json/<project>/<query>;path=<cfPath>`";return e==="cf"?`
501
501
  ## Content source: Content Fragment
502
502
  This block renders an AEM **Content Fragment**${o} - not inline-authored copy.
503
503
  - UE model: use an \`aem-content-fragment\` field (e.g. \`name: "fragment"\`) for the CF reference.
504
- - \`decorate(block)\` must be **async**: read the CF reference from the authored DOM (a link to \`/content/dam/...\`), fetch its fields through an AEM GraphQL **persisted query** (${r}), then build the DOM from the returned fields.
504
+ - \`decorate(block)\` must be **async**: read the CF reference from the authored DOM (a link to \`/content/dam/...\`), fetch its fields through an AEM GraphQL **persisted query** (${i}), then build the DOM from the returned fields.
505
505
  - Handle loading / empty / error states. Do not hardcode copy that the CF owns.
506
506
  - \`.${n}\` styling still follows the EDS conventions below.
507
507
  `:`
508
508
  ## Content source: Mixed (Universal Editor + Content Fragment)
509
509
  This block mixes **two sources in one model and one \`decorate(block)\`**:
510
510
  - **Inline (UE-authored)** parts \u2192 normal fields (text / richtext / image / select) read straight from the authored DOM cells, with semantic collapsing.
511
- - **Content Fragment** part${o} \u2192 an \`aem-content-fragment\` field; \`decorate()\` is **async** and also fetches that CF via a GraphQL persisted query (${r}) and renders its fields.
511
+ - **Content Fragment** part${o} \u2192 an \`aem-content-fragment\` field; \`decorate()\` is **async** and also fetches that CF via a GraphQL persisted query (${i}) and renders its fields.
512
512
  - Field order in the model = cell order in the authored DOM. Read the inline cells by position; detect the CF reference by its \`/content/dam/\` link. Merge both into the final markup, and handle the CF loading/empty/error states.
513
- `}async function ea(e){let t=await Dl(e.projectRoot),n=Rl(e.contentSource,e.cfHint,e.blockName),o=e.screenshot===!0,r=e.provider??"figma",a=He[r],s=e.design,d=s?.mode==="file"?/\.(png|jpe?g|webp)$/i.test(s.filePath):!1,c=`## Step 5 \u2014 One Verification Pass (single pass, then stop)
513
+ `}async function ba(e){let t=await md(e.projectRoot),n=pd(e.contentSource,e.cfHint,e.blockName),o=e.screenshot===!0,i=e.provider??"figma",a=qe[i],s=e.design,d=s?.mode==="file"?/\.(png|jpe?g|webp)$/i.test(s.filePath):!1,c=`## Step 5 \u2014 One Verification Pass (single pass, then stop)
514
514
  Do **exactly one** self-check \u2014 do **not** loop:
515
- 1. Compare your implementation to ${s?.mode==="spec"?"the exact values in the embedded design data from Step 1":s?.mode==="file"?d?"the local design image":"the exact values in the local SVG":s?.mode==="mcp"?"the exact values from the `get_design_context` you cached":o?"the `get_screenshot` image":"the exact values from `get_design_context`"} once, across: spacing, fonts, colors, radius, shadows, alignment and proportions.
515
+ 1. Compare your implementation to ${s?.mode==="spec"?"the exact values in the embedded design data from Step 1":s?.mode==="scrape"?"the exact values in the scraped design data from Step 1":s?.mode==="file"?d?"the local design image":"the exact values in the local SVG":s?.mode==="mcp"?"the exact values from the `get_design_context` you cached":o?"the `get_screenshot` image":"the exact values from `get_design_context`"} once, across: spacing, fonts, colors, radius, shadows, alignment and proportions.
516
516
  2. Apply **one** round of corrections, then **stop** \u2014 don't iterate to "pixel perfect". The author reviews the result in the live preview (\`eds block preview\`) and will request another pass with specific feedback if needed.
517
- 3. Briefly state what you checked and any value you had to infer.`,u=`Target: fileKey \`${e.figma?.fileKey}\`${e.figma?.nodeId?`, node \`${e.figma.nodeId}\``:" (no node selected \u2014 use the full page)"}.`,p;s?.mode==="spec"?p=`## Step 1 \u2014 Use the Provided Design Data (no MCP)
517
+ 3. Briefly state what you checked and any value you had to infer.`,p=`Target: fileKey \`${e.figma?.fileKey}\`${e.figma?.nodeId?`, node \`${e.figma.nodeId}\``:" (no node selected \u2014 use the full page)"}.`,m;s?.mode==="spec"?m=`## Step 1 \u2014 Use the Provided Design Data (no MCP)
518
518
  The design was already fetched for you and is embedded below \u2014 **do not call any Figma MCP tool** (\`get_design_context\`, \`get_variable_defs\`, \`get_screenshot\`). Parse it for the exact structure, layout, spacing, colors, typography, radius and effects.
519
519
 
520
520
  \`\`\`json
521
521
  ${s.spec}
522
522
  \`\`\`
523
523
 
524
- Image fills are placeholders (the data references assets, not pixels) \u2014 render a placeholder at the right aspect-ratio per the Placeholders section; authors supply the real image.`:s?.mode==="file"?p=`## Step 1 \u2014 Read the Local Design Export (no MCP)
524
+ Image fills are placeholders (the data references assets, not pixels) \u2014 render a placeholder at the right aspect-ratio per the Placeholders section; authors supply the real image.`:s?.mode==="scrape"?m=`## Step 1 \u2014 Use the Scraped Design Data (no MCP)
525
+ The design was scraped from the live **${a}** page (${e.designRef??"the URL"}) with headless Chromium and is embedded below \u2014 **do not call any MCP tool** and **do not fetch the URL yourself**. The tree holds **computed** values: geometry (\`rect\` x/y/w/h, px), layout (\`display\`/\`flexDirection\`/\`gap\`/\`padding\`), colours, typography, radius and shadows. Use them verbatim (convert px\u2192rem where appropriate) and regroup the flattened DOM into semantic structure yourself (Step 3).
526
+
527
+ \`\`\`json
528
+ ${s.spec}
529
+ \`\`\`
530
+
531
+ The scraped **text and images are reference content**, not authored copy \u2014 reproduce the layout/styling exactly, but read real content from the authored DOM at runtime and fall back to placeholders (see the Placeholders section). Do **not** hardcode the scraped copy or ship the scraped image URLs.`:s?.mode==="file"?m=`## Step 1 \u2014 Read the Local Design Export (no MCP)
525
532
  Read \`${s.filePath}\` with your **Read** tool. Do **not** call any Figma MCP tool.
526
533
 
527
- ${d?"It's a raster image (PNG/JPG) \u2014 open it and reproduce it visually: infer spacing, colors, typography, radius, shadows and layout as precisely as you can from the pixels.":"It's an **SVG** \u2014 read it as text and parse the **exact** values: geometry and positions (x/y/width/height, `viewBox`), text and typography (font-family / font-size / font-weight on `<text>`/`<tspan>`), fills and gradients, strokes, and effects. Use the numbers verbatim, converting px\u2192rem where appropriate. The SVG is flattened \u2014 regroup into semantic structure yourself (Step 3), don't mirror raw `<g>`/`<path>` nesting."}`:s?.mode==="mcp"?p=`## Step 1 \u2014 Fetch the Design Once, Then Cache It (single MCP call)
534
+ ${d?"It's a raster image (PNG/JPG) \u2014 open it and reproduce it visually: infer spacing, colors, typography, radius, shadows and layout as precisely as you can from the pixels.":"It's an **SVG** \u2014 read it as text and parse the **exact** values: geometry and positions (x/y/width/height, `viewBox`), text and typography (font-family / font-size / font-weight on `<text>`/`<tspan>`), fills and gradients, strokes, and effects. Use the numbers verbatim, converting px\u2192rem where appropriate. The SVG is flattened \u2014 regroup into semantic structure yourself (Step 3), don't mirror raw `<g>`/`<path>` nesting."}`:s?.mode==="mcp"?m=`## Step 1 \u2014 Fetch the Design Once, Then Cache It (single MCP call)
528
535
  Call **\`get_design_context\` exactly once** for the target node. Do **not** call \`get_variable_defs\` or \`get_screenshot\` \u2014 each extra MCP call burns the Figma plan's scarce tool-call budget; derive colors and tokens from the context you already got.
529
536
  **Immediately after**, \`Write\` the raw design data you received to \`${s.cachePath}\` (pretty JSON) so re-runs and refine passes reuse it without another MCP call. Then generate from it.
530
537
 
531
- ${u}`:r==="figma"?p=`## Step 1 \u2014 Fetch the Design (single MCP call)
538
+ ${p}`:i==="figma"?m=`## Step 1 \u2014 Fetch the Design (single MCP call)
532
539
  Call **\`get_design_context\` exactly once** for the target node \u2014 it returns structure, layout, measurements, text and the colors/tokens you need. Do **not** call \`get_variable_defs\`${o?"":" or `get_screenshot`"} \u2014 each extra MCP call burns the Figma plan's scarce budget.${o?" You may call `get_screenshot` once (`maxDimension: 1024`) for the Step 5 check.":""}
533
540
 
534
- ${u}`:p=`## Step 1 \u2014 Fetch the Design
535
- Read the design from **${a}** through your ${a} MCP connection (design-context / inspect tools). Design reference: \`${e.designRef??"(the selected design)"}\`.
536
- Extract the **exact** structure, layout, colours, typography, spacing, radius and effects \u2014 do not approximate. Fetch once for the target only.`;let f=e.withUeModel?`
541
+ ${p}`:m=`## Step 1 \u2014 Read the Design
542
+ Open the live **${a}** page at \`${e.designRef??"(the design URL)"}\` and read its rendered layout, typography, colours, spacing, radius and effects. Extract the **exact** values \u2014 do not approximate.`;let u=e.withUeModel?`
537
543
  ## Step 4b \u2014 Universal Editor Authoring (REQUIRED, not optional)
538
544
  Authors must be able to drop and edit this block in the Universal Editor, so generate its UE configuration **in the same pass** as the code.
539
545
 
@@ -608,14 +614,14 @@ Rules:
608
614
  If the project uses a **single aggregated model file** (\`component-definition.json\` + \`component-models.json\` + \`component-filters.json\`) instead of per-block \`_${e.blockName}.json\`, detect that convention and add the block's definition/model/filter to those files instead (and register the block in the \`section\` filter). Prefer the per-block \`_${e.blockName}.json\` when neither exists. Full field reference and a repeatable-cards round-trip example: \`docs/universal-editor-fields.md\`.
609
615
 
610
616
  **Reusable field groups (partials):** when the design shows one of these common shapes, reuse the standard group instead of inventing fields \u2014 same groups \`eds model add\` uses, so the model stays consistent across the project:
611
- ${Ie.map(h=>`- \`${h.id}\` \u2014 ${h.label}`).join(`
617
+ ${ze.map(y=>`- \`${y.id}\` \u2014 ${y.label}`).join(`
612
618
  `)}
613
- `:"",g=s?.mode==="file"?"a design export":a,y=s?.mode==="file"?"design":`${a} design`;return`# Pixel-Perfect EDS Block from ${g}
619
+ `:"",g=s?.mode==="file"?"a design export":a,w=s?.mode==="file"?"design":`${a} design`;return`# Pixel-Perfect EDS Block from ${g}
614
620
 
615
621
  ## Task
616
- Generate an AEM Edge Delivery Services block named **\`${e.blockName}\`** that reproduces the ${y} **1:1 \u2014 pixel perfect**. Exact spacing, colors, typography, and layout. Not "close enough" \u2014 identical.
622
+ Generate an AEM Edge Delivery Services block named **\`${e.blockName}\`** that reproduces the ${w} **1:1 \u2014 pixel perfect**. Exact spacing, colors, typography, and layout. Not "close enough" \u2014 identical.
617
623
 
618
- ${p}
624
+ ${m}
619
625
 
620
626
  ## Step 2 \u2014 Extract Exact Values
621
627
  From the design data you fetched, record the **precise** values \u2014 do not approximate:
@@ -656,9 +662,9 @@ export default function decorate(block) {
656
662
  /* Map Figma design tokens to CSS custom properties; reuse project tokens below where they match */
657
663
  /* Mobile-first; exact values from Step 2 */
658
664
  \`\`\`
659
- ${f}${n}
665
+ ${u}${n}
660
666
  ## Placeholders & assets \u2014 be visible before Universal Editor takes over
661
- Content images and copy come from **authoring** (the document / DAM via UE), not the repo. Do **not** ship design-tool CDN URLs (Figma / Google Stitch links are short-lived) and do **not** bundle content photos into the repo.
667
+ Content images and copy come from **authoring** (the document / DAM via UE), not the repo. Do **not** ship design-tool / scraped CDN URLs (Figma, Framer and Stitch asset links are short-lived) and do **not** bundle content photos into the repo.
662
668
  - In \`decorate()\`, read the image/text from the authored DOM. When none is present yet, render a lightweight **placeholder** so the block is visible *before* an author sets the real content: an inline SVG data-URI grey box (or a CSS placeholder) at the correct \`aspect-ratio\`, and sensible placeholder copy.
663
669
  - Provide the mock for the preview in \`blocks/${e.blockName}/_${e.blockName}.preview.html\` (used by \`eds block preview\`). Keep placeholder copy there, not hardcoded in the block. **This file must be a bare block fragment only** \u2014 just the authored \`<div class="${e.blockName} block">\u2026</div>\` markup that \`decorate()\` consumes. Do **not** wrap it in \`<!DOCTYPE>\`, \`<html>\`, \`<head>\`, \`<body>\`, \`<link>\`, \`<style>\` or \`<script>\`; the preview harness supplies the page, the block CSS and the \`decorate()\` call itself. A full HTML document here renders as a blank preview.
664
670
  - Only bundle genuinely **static, decorative** assets (e.g. a small icon) as an optimized inline/\`icons/\` **SVG**, referenced by project-relative path. Never bundle authorable content images.
@@ -689,11 +695,11 @@ ${t}
689
695
  5. Mobile-first CSS with breakpoints at 600px and 900px
690
696
  6. Prefer existing project tokens over new hardcoded values${e.withUeModel?"\n7. UE model field `name`s must match what `decorate()` reads, and every Figma variant must appear as a select option wired to a CSS modifier":""}
691
697
 
692
- Finally, record the design's frame width(s) you read in Step 1 into \`blocks/${e.blockName}/.eds-meta.json\` as \`{ "breakpoints": [{ "width": <px>, "source": "figma" }] }\` (one entry per distinct frame width). The CLI merges this so \`eds block preview\` shows the block at the **real design widths**, not a fixed device set.
698
+ Finally, record the design's frame width(s) you read in Step 1 into \`blocks/${e.blockName}/.eds-meta.json\` as \`{ "breakpoints": [{ "width": <px>, "source": "${s?.mode==="scrape"?"scrape":i}" }] }\` (one entry per distinct frame width). The CLI merges this so \`eds block preview\` shows the block at the **real design widths**, not a fixed device set.
693
699
 
694
700
  ---
695
- *Prompt version: ${ut}*
696
- `}function ta(e){let t=e.provider??"figma",n=t==="figma"&&e.figma?.fileKey?`If the change needs design values, re-read **only what you need** from Figma (fileKey \`${e.figma.fileKey}\`${e.figma.nodeId?`, node \`${e.figma.nodeId}\``:""}) \u2014 don't re-fetch the whole design.`:e.designRef?`If the change needs design values, re-read only what you need from the ${He[t]} design: \`${e.designRef}\`.`:"";return`# Refine the \`${e.blockName}\` EDS block
701
+ *Prompt version: ${xt}*
702
+ `}function ya(e){let t=e.provider??"figma",n=t==="figma"&&e.figma?.fileKey?`If the change needs design values, re-read **only what you need** from Figma (fileKey \`${e.figma.fileKey}\`${e.figma.nodeId?`, node \`${e.figma.nodeId}\``:""}) \u2014 don't re-fetch the whole design.`:"Use the values already in the files (and the cached design snapshot under `tmp/eds-cli/design-cache/` if present); infer sensibly if the request is purely stylistic.";return`# Refine the \`${e.blockName}\` EDS block
697
703
 
698
704
  The block already exists in \`blocks/${e.blockName}/\` and the author reviewed it in the live preview. Apply **this change** and nothing else:
699
705
 
@@ -712,20 +718,20 @@ The block already exists in \`blocks/${e.blockName}/\` and the author reviewed i
712
718
  - **No shell access:** only read/write files${t==="figma"?" and call the Figma MCP":""}. Do **not** run \`eslint\`, \`stylelint\`, \`npm\`, \`npx\`, \`tsc\`, a build, or any Bash command \u2014 they aren't granted and just fail.
713
719
  - **Minimise chat output:** edit files directly, don't paste code back. End with a **\u22642-line** summary of what changed.
714
720
 
715
- *Prompt version: ${ut}*
716
- `}async function Dl(e){let t=Tl.join(e,"styles","styles.css");if(!Cl(t))return"";try{let o=(await Al(t,"utf-8")).match(/:root\s*\{([^}]+)\}/);if(!o)return"";let r=o[1].split(`
721
+ *Prompt version: ${xt}*
722
+ `}async function md(e){let t=dd.join(e,"styles","styles.css");if(!cd(t))return"";try{let o=(await ld(t,"utf-8")).match(/:root\s*\{([^}]+)\}/);if(!o)return"";let i=o[1].split(`
717
723
  `).filter(a=>a.trim().startsWith("--")).map(a=>a.trim()).join(`
718
- `);return r?`
724
+ `);return i?`
719
725
  ## Existing Project Tokens
720
726
  The project already defines these CSS custom properties in \`styles/styles.css\`.
721
727
  Reuse them instead of hardcoding values:
722
728
 
723
729
  \`\`\`css
724
730
  :root {
725
- ${r}
731
+ ${i}
726
732
  }
727
733
  \`\`\`
728
- `:""}catch{return""}}var ut,He,na=w(()=>{"use strict";m();_n();ut="0.7.0",He={figma:"Figma",stitch:"Google Stitch",canva:"Canva",sketch:"Sketch",framer:"Framer"}});function ae(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Fl(e){let t=e,n=t.match(/<body[^>]*>([\s\S]*?)<\/body>/i);return n&&(t=n[1]),t.replace(/<!DOCTYPE[^>]*>/gi,"").replace(/<\/?(?:html|head|body)[^>]*>/gi,"").replace(/<link\b[^>]*>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<!--[\s\S]*?-->/g,"").trim()}function so(e){let{blockName:t}=e,n=Fl(e.sampleContent);return`<!DOCTYPE html>
734
+ `:""}catch{return""}}var xt,qe,va=v(()=>{"use strict";f();Xn();xt="0.7.0",qe={figma:"Figma",framer:"Framer",stitch:"Google Stitch"}});function ce(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function ud(e){let t=e,n=t.match(/<body[^>]*>([\s\S]*?)<\/body>/i);return n&&(t=n[1]),t.replace(/<!DOCTYPE[^>]*>/gi,"").replace(/<\/?(?:html|head|body)[^>]*>/gi,"").replace(/<link\b[^>]*>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<!--[\s\S]*?-->/g,"").trim()}function nn(e){let{blockName:t}=e,n=ud(e.sampleContent);return`<!DOCTYPE html>
729
735
  <html lang="en">
730
736
  <head>
731
737
  <meta charset="utf-8" />
@@ -755,10 +761,10 @@ ${n}
755
761
  try { new EventSource('/__eds_events').onmessage = () => location.reload(); } catch (e) { /* no SSE */ }
756
762
  </script>
757
763
  </body>
758
- </html>`}function Ll(e){let t=e.filter(n=>n.figma);return(t.length?t:e).reduce((n,o)=>o.width>n.width?o:n,e[0])}function oa(e){let t=e.map((o,r)=>{let a=Ll(o.breakpoints),s=o.breakpoints.map(c=>`<option value="${c.width}"${c.width===a.width?" selected":""}>${ae(c.label)}</option>`).join(""),d=o.figmaUrl?`<a class="figma-link" href="${ae(o.figmaUrl)}" target="_blank" rel="noopener">Figma \u2197</a>`:"",l=o.placeholder?'<span class="hint">placeholder content</span>':"";return`<section class="card">
764
+ </html>`}function fd(e){let t=e.filter(n=>n.figma);return(t.length?t:e).reduce((n,o)=>o.width>n.width?o:n,e[0])}function ka(e){let t=e.map((o,i)=>{let a=fd(o.breakpoints),s=o.breakpoints.map(c=>`<option value="${c.width}"${c.width===a.width?" selected":""}>${ce(c.label)}</option>`).join(""),d=o.figmaUrl?`<a class="figma-link" href="${ce(o.figmaUrl)}" target="_blank" rel="noopener">Figma \u2197</a>`:"",l=o.placeholder?'<span class="hint">placeholder content</span>':"";return`<section class="card">
759
765
  <div class="cardbar">
760
- <span class="block">${ae(o.blockName)}</span>
761
- <select class="bp" data-i="${r}">
766
+ <span class="block">${ce(o.blockName)}</span>
767
+ <select class="bp" data-i="${i}">
762
768
  ${s}
763
769
  <option value="full">Full</option>
764
770
  </select>
@@ -766,8 +772,8 @@ ${n}
766
772
  ${d}
767
773
  </div>
768
774
  <div class="stage">
769
- <div class="device" data-i="${r}" data-w="${a.width}" style="width:${a.width}px">
770
- <iframe src="${ae(o.frameRoute)}" title="${ae(o.blockName)} preview" loading="lazy"></iframe>
775
+ <div class="device" data-i="${i}" data-w="${a.width}" style="width:${a.width}px">
776
+ <iframe src="${ce(o.frameRoute)}" title="${ce(o.blockName)} preview" loading="lazy"></iframe>
771
777
  </div>
772
778
  </div>
773
779
  </section>`}).join(`
@@ -816,16 +822,16 @@ ${n}
816
822
  try { new EventSource('/__eds_events').onmessage = () => location.reload(); } catch (e) { /* no SSE */ }
817
823
  </script>
818
824
  </body>
819
- </html>`}function ia(e){let{blockName:t,breakpoints:n,figmaUrl:o,frameRoute:r,placeholder:a}=e,s=n.filter(p=>p.figma),d=(s.length?s:n).reduce((p,f)=>f.width>p.width?f:p,n[0]),l=n.map(p=>`<option value="${p.width}"${p.width===d.width?" selected":""}>${ae(p.label)}</option>`).join(`
820
- `),c=o?`<a class="figma-link" href="${ae(o)}" target="_blank" rel="noopener">
825
+ </html>`}function xa(e){let{blockName:t,breakpoints:n,figmaUrl:o,frameRoute:i,placeholder:a}=e,s=n.filter(m=>m.figma),d=(s.length?s:n).reduce((m,u)=>u.width>m.width?u:m,n[0]),l=n.map(m=>`<option value="${m.width}"${m.width===d.width?" selected":""}>${ce(m.label)}</option>`).join(`
826
+ `),c=o?`<a class="figma-link" href="${ce(o)}" target="_blank" rel="noopener">
821
827
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M15 3h6v6"/><path d="M10 14 21 3"/><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/></svg>
822
828
  Open in Figma
823
- </a>`:"",u=a?`<span class="hint">placeholder content \u2014 add <code>blocks/${t}/_${t}.preview.html</code></span>`:"";return`<!DOCTYPE html>
829
+ </a>`:"",p=a?`<span class="hint">placeholder content \u2014 add <code>blocks/${t}/_${t}.preview.html</code></span>`:"";return`<!DOCTYPE html>
824
830
  <html lang="en">
825
831
  <head>
826
832
  <meta charset="utf-8" />
827
833
  <meta name="viewport" content="width=device-width, initial-scale=1" />
828
- <title>eds preview \u2014 ${ae(t)}</title>
834
+ <title>eds preview \u2014 ${ce(t)}</title>
829
835
  <style>
830
836
  *{box-sizing:border-box}
831
837
  html,body{margin:0;padding:0;background:#1f1f1f;color:#eaeaea;font-family:ui-sans-serif,-apple-system,"Segoe UI",sans-serif}
@@ -847,18 +853,18 @@ ${n}
847
853
  </head>
848
854
  <body>
849
855
  <div class="bar">
850
- <span class="label">Block</span><span class="block">${ae(t)}</span>
856
+ <span class="label">Block</span><span class="block">${ce(t)}</span>
851
857
  <label class="label" for="bp" style="margin-left:8px">Breakpoint</label>
852
858
  <select id="bp">
853
859
  ${l}
854
860
  <option value="full">Full ca\u0142a szeroko\u015B\u0107</option>
855
861
  </select>
856
- ${u}
862
+ ${p}
857
863
  ${c}
858
864
  </div>
859
865
  <div class="stage">
860
866
  <div class="device" id="device" data-w="${d.width}" style="width:${d.width}px">
861
- <iframe id="frame" src="${r}" title="${ae(t)} preview"></iframe>
867
+ <iframe id="frame" src="${i}" title="${ce(t)} preview"></iframe>
862
868
  </div>
863
869
  </div>
864
870
  <script>
@@ -872,29 +878,65 @@ ${n}
872
878
  setWidth(Number(bp.value));
873
879
  </script>
874
880
  </body>
875
- </html>`}var ra=w(()=>{"use strict";m()});import{createReadStream as Ol,existsSync as Ml,statSync as Nl}from"fs";import _l from"http";import co from"path";function lo(e,t,n,o="127.0.0.1",r){let a=co.resolve(e),s=new Set,d=_l.createServer(async(l,c)=>{let u=decodeURIComponent((l.url??"/").split("?")[0]);if(u===Ul){c.writeHead(200,{"content-type":"application/json"}),c.end(JSON.stringify({eds:!0}));return}if(u===Bl){c.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),c.write(`: connected
881
+ </html>`}var $a=v(()=>{"use strict";f()});import{createReadStream as gd,existsSync as hd,statSync as wd}from"fs";import bd from"http";import vo from"path";function on(e,t,n,o="127.0.0.1",i){let a=vo.resolve(e),s=new Set,d=bd.createServer(async(l,c)=>{let p=decodeURIComponent((l.url??"/").split("?")[0]);if(p===vd){c.writeHead(200,{"content-type":"application/json"}),c.end(JSON.stringify({eds:!0}));return}if(p===kd){c.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),c.write(`: connected
876
882
 
877
- `),s.add(c),l.on("close",()=>s.delete(c));return}let p=t[u];if(p){c.writeHead(200,{"content-type":p.type}),c.end(p.body);return}if(r)try{let g=await r(u);if(g){c.writeHead(200,{"content-type":g.type}),c.end(g.body);return}}catch(g){c.writeHead(500,{"content-type":"text/plain"}),c.end(`Preview error: ${g instanceof Error?g.message:String(g)}`);return}let f=co.join(a,u);if(!f.startsWith(a)){c.writeHead(403),c.end("Forbidden");return}if(!Ml(f)||!Nl(f).isFile()){c.writeHead(404,{"content-type":"text/plain"}),c.end(`Not found: ${u}`);return}c.writeHead(200,{"content-type":Il[co.extname(f).toLowerCase()]??"application/octet-stream"}),Ol(f).pipe(c)});return new Promise((l,c)=>{let u=0,p=f=>{d.once("error",g=>{g.code==="EADDRINUSE"&&u<10?(u++,p(f+1)):c(g)}),d.listen(f,o,()=>{l({url:`http://${o}:${f}/`,port:f,reload:()=>{for(let g of s)g.write(`data: reload
883
+ `),s.add(c),l.on("close",()=>s.delete(c));return}let m=t[p];if(m){c.writeHead(200,{"content-type":m.type}),c.end(m.body);return}if(i)try{let g=await i(p);if(g){c.writeHead(200,{"content-type":g.type}),c.end(g.body);return}}catch(g){c.writeHead(500,{"content-type":"text/plain"}),c.end(`Preview error: ${g instanceof Error?g.message:String(g)}`);return}let u=vo.join(a,p);if(!u.startsWith(a)){c.writeHead(403),c.end("Forbidden");return}if(!hd(u)||!wd(u).isFile()){c.writeHead(404,{"content-type":"text/plain"}),c.end(`Not found: ${p}`);return}c.writeHead(200,{"content-type":yd[vo.extname(u).toLowerCase()]??"application/octet-stream"}),gd(u).pipe(c)});return new Promise((l,c)=>{let p=0,m=u=>{d.once("error",g=>{g.code==="EADDRINUSE"&&p<10?(p++,m(u+1)):c(g)}),d.listen(u,o,()=>{l({url:`http://${o}:${u}/`,port:u,reload:()=>{for(let g of s)g.write(`data: reload
878
884
 
879
- `)},close:()=>new Promise(g=>{for(let y of s)y.end();d.close(()=>g())})})})};p(n)})}var Il,Ul,Bl,aa=w(()=>{"use strict";m();Il={".html":"text/html; charset=utf-8",".js":"text/javascript; charset=utf-8",".mjs":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".json":"application/json; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".avif":"image/avif",".woff":"font/woff",".woff2":"font/woff2",".ico":"image/x-icon"},Ul="/__eds_ping",Bl="/__eds_events"});var ft={};N(ft,{galleryPreview:()=>Wl,previewBlock:()=>Jl,startPreview:()=>fa});import{existsSync as ne,watch as la}from"fs";import{readFile as Wt,readdir as Hl}from"fs/promises";import Q from"path";import ge from"chalk";function po(e){return e<=480?`${e} mobile`:e<=1024?`${e} tablet`:`${e} desktop`}function da(e,t){if(e){let o=e.split(",").map(r=>Number.parseInt(r.trim(),10)).filter(r=>Number.isFinite(r)&&r>0);if(o.length)return o.map(r=>({width:r,label:po(r),figma:!1}))}let n=t?.breakpoints;return Array.isArray(n)&&n.length?n.map(o=>({width:Number(o.width),label:typeof o.label=="string"?o.label:po(Number(o.width)),figma:o.source==="figma"})).filter(o=>Number.isFinite(o.width)&&o.width>0):zl.map(o=>({width:o,label:po(o),figma:!1}))}function pa(e){if(!e?.figmaFileKey||typeof e.figmaFileKey!="string")return;let t=typeof e.figmaNodeId=="string"?e.figmaNodeId.replace(":","-"):void 0,n=`https://www.figma.com/design/${e.figmaFileKey}/preview`;return t?`${n}?node-id=${t}`:n}function ma(e){return`<div class="${e} block">
885
+ `)},close:()=>new Promise(g=>{for(let w of s)w.end();d.close(()=>g())})})})};m(n)})}var yd,vd,kd,Sa=v(()=>{"use strict";f();yd={".html":"text/html; charset=utf-8",".js":"text/javascript; charset=utf-8",".mjs":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".json":"application/json; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".avif":"image/avif",".woff":"font/woff",".woff2":"font/woff2",".ico":"image/x-icon"},vd="/__eds_ping",kd="/__eds_events"});var $t={};L($t,{FRAME_PREFIX:()=>ve,galleryPreview:()=>Pd,listPreviewableBlocks:()=>Fe,loadBlockForPreview:()=>pe,previewBlock:()=>jd,startFrameServer:()=>Ke,startPreview:()=>Ta});import{existsSync as oe,watch as ja}from"fs";import{readFile as rn,readdir as xd}from"fs/promises";import Y from"path";import ye from"chalk";function ko(e){return e<=480?`${e} mobile`:e<=1024?`${e} tablet`:`${e} desktop`}function Pa(e,t){if(e){let o=e.split(",").map(i=>Number.parseInt(i.trim(),10)).filter(i=>Number.isFinite(i)&&i>0);if(o.length)return o.map(i=>({width:i,label:ko(i),figma:!1}))}let n=t?.breakpoints;return Array.isArray(n)&&n.length?n.map(o=>({width:Number(o.width),label:typeof o.label=="string"?o.label:ko(Number(o.width)),figma:o.source==="figma"})).filter(o=>Number.isFinite(o.width)&&o.width>0):Sd.map(o=>({width:o,label:ko(o),figma:!1}))}function Ea(e){if(!e?.figmaFileKey||typeof e.figmaFileKey!="string")return;let t=typeof e.figmaNodeId=="string"?e.figmaNodeId.replace(":","-"):void 0,n=`https://www.figma.com/design/${e.figmaFileKey}/preview`;return t?`${n}?node-id=${t}`:n}function Ca(e){return`<div class="${e} block">
880
886
  <div><div>
881
887
  <h2>${e} heading</h2>
882
888
  <p>Sample body copy for the preview. Replace with real authored content.</p>
883
889
  <p><a href="#">Primary action</a></p>
884
890
  <p><a href="#">Secondary action</a></p>
885
891
  </div></div>
886
- </div>`}async function sa(e,t,n){let o=Q.join(e,"blocks",t);if(!ne(Q.join(o,`${t}.css`))&&!ne(Q.join(o,`${t}.js`)))return null;let r=null,a=Q.join(o,".eds-meta.json");if(ne(a))try{r=JSON.parse(await Wt(a,"utf-8"))}catch{}let s=Q.join(o,`_${t}.preview.html`),d,l=!1;return ne(s)?d=await Wt(s,"utf-8"):(d=ma(t),l=!0),{name:t,sampleContent:d,breakpoints:da(n,r),figmaUrl:pa(r),placeholder:l}}async function ca(e){let t=Q.join(e,"blocks");if(!ne(t))return[];let n=await Hl(t,{withFileTypes:!0}),o=[];for(let r of n){if(!r.isDirectory()||Gl.has(r.name))continue;let a=Q.join(t,r.name);(ne(Q.join(a,`${r.name}.css`))||ne(Q.join(a,`${r.name}.js`)))&&o.push(r.name)}return o.sort()}async function ua(e){let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{let{execa:n}=await import("execa");await n(t,[e],{stdio:"ignore",shell:process.platform==="win32"})}catch{}}async function fa(e,t={}){let n=E();if(!n)return i.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1,null;let o=Q.join(n,"blocks",e);if(!ne(o))return i.error(`Block "${e}" not found at blocks/${e}/.`),process.exitCode=1,null;if(!ne(Q.join(o,`${e}.css`))&&!ne(Q.join(o,`${e}.js`)))return i.error(`Block "${e}" has no ${e}.css / ${e}.js to preview.`),process.exitCode=1,null;(e==="header"||e==="footer")&&(i.warn(`"${e}" is page chrome, not a content block \u2014 it won't render standalone here.`),i.info(ge.dim(` It fetches the ${e==="header"?"nav":"footer"} fragment and needs the full page runtime.`)),i.info(ge.dim(" Preview a content block instead (e.g. a block generated from a design).")));let r=null,a=Q.join(o,".eds-meta.json");if(ne(a))try{r=JSON.parse(await Wt(a,"utf-8"))}catch{}let s=Q.join(o,`_${e}.preview.html`),d,l=!1;ne(s)?d=await Wt(s,"utf-8"):(d=ma(e),l=!0);let c=da(t.widths,r),u=pa(r),p="/__eds_preview_frame",f=so({blockName:e,breakpoints:c,sampleContent:d,frameRoute:p}),g=ia({blockName:e,breakpoints:c,sampleContent:d,figmaUrl:u,frameRoute:p,placeholder:l}),y=Number.parseInt(t.port??"8777",10),h=await lo(n,{"/":{body:g,type:"text/html; charset=utf-8"},[p]:{body:f,type:"text/html; charset=utf-8"}},Number.isFinite(y)?y:8777);i.logoOnce(P(`Preview \u2014 ${e}`)),i.info(j("Live preview",h.url)),i.info(D("pass","breakpoints",`${c.map(x=>`${x.width}${x.figma?"\u2713":""}`).join(", ")}, Full`)),l&&i.info(D("warn","content",`placeholder \u2014 add blocks/${e}/_${e}.preview.html for real content`));let b,S=la(o,{recursive:!0},()=>{clearTimeout(b),b=setTimeout(()=>h.reload(),150)});return i.info(""),i.info(` ${ge.bold("\u279C")} ${ge.cyan(h.url)}`),i.info(D("pass","live reload","edits to the block refresh the browser")),t.open!==!1&&await ua(h.url),{url:h.url,close:async()=>{S.close(),await h.close()}}}async function Jl(e,t={}){let n=await fa(e,t);n&&(i.info(ge.dim(` Press Ctrl+C to stop.
887
- `)),await new Promise(o=>{let r=async()=>{await n.close(),o(),process.exit(0)};process.on("SIGINT",r),process.on("SIGTERM",r)}))}async function Wl(e={}){let t=E();if(!t){i.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}let n="/__eds_frame/",o=async c=>{if(c==="/"){let u=await ca(t),p=[];for(let f of u){let g=await sa(t,f,e.widths);g&&p.push({blockName:f,breakpoints:g.breakpoints,frameRoute:n+f,figmaUrl:g.figmaUrl,placeholder:g.placeholder})}return{body:oa(p),type:"text/html; charset=utf-8"}}if(c.startsWith(n)){let u=c.slice(n.length);if(!/^[a-z0-9-]+$/i.test(u))return;let p=await sa(t,u,e.widths);return p?{body:so({blockName:u,breakpoints:p.breakpoints,sampleContent:p.sampleContent,frameRoute:n+u}),type:"text/html; charset=utf-8"}:void 0}},r=Number.parseInt(e.port??"8777",10),a=await lo(t,{},Number.isFinite(r)?r:8777,"127.0.0.1",o),s=await ca(t);i.logoOnce(P("Preview \u2014 gallery")),i.info(j("Live gallery",a.url)),i.info(D(s.length?"pass":"warn","blocks",s.length?s.join(", "):"none yet \u2014 generate one with eds block from-design"));let d,l=la(Q.join(t,"blocks"),{recursive:!0},()=>{clearTimeout(d),d=setTimeout(()=>a.reload(),150)});i.info(""),i.info(` ${ge.bold("\u279C")} ${ge.cyan(a.url)}`),i.info(D("pass","live reload","new & edited blocks refresh the browser")),i.info(ge.dim(` Press Ctrl+C to stop.
888
- `)),e.open!==!1&&await ua(a.url),await new Promise(c=>{let u=async()=>{l.close(),await a.close(),c(),process.exit(0)};process.on("SIGINT",u),process.on("SIGTERM",u)})}var Gl,zl,gt=w(()=>{"use strict";m();R();ra();aa();z();I();Gl=new Set(["header","footer"]),zl=[375,768,1280]});var mo={};N(mo,{blockFromDesign:()=>Ql});import{existsSync as se}from"fs";import{readFile as Ge,writeFile as ql}from"fs/promises";import W from"path";import C from"chalk";import qt from"ora";async function Kl(e=8777){try{let t=new AbortController,n=setTimeout(()=>t.abort(),400),o=await fetch(`http://127.0.0.1:${e}/__eds_ping`,{signal:t.signal});return clearTimeout(n),o.ok?(await o.json())?.eds===!0:!1}catch{return!1}}async function Xl(e){let{input:t,select:n,confirm:o}=await Promise.resolve().then(()=>(B(),U)),r=await n({message:"1/7 Design source",choices:[{name:"Figma",value:"figma"},{name:"Google Stitch",value:"stitch"},{name:"Canva",value:"canva"},{name:"Sketch",value:"sketch"},{name:"Framer",value:"framer"}],default:"figma"}),a=await t({message:"2/7 Component name",validate:x=>ye.test(x.trim())||"Use kebab-case, e.g. hero-banner"}),s=e??await t({message:`3/7 ${He[r]} link`,validate:x=>{if(!x.trim())return"Paste the design link";if(r!=="figma")return!0;try{return Jt(x.trim()),!0}catch(T){return T.message}}}),d=await n({message:"4/7 Where does the content come from?",choices:[{name:"Document authoring (default EDS)",value:"document"},{name:"Universal Editor",value:"ue"},{name:"Content Fragment",value:"cf"},{name:"Mixed - Universal Editor + Content Fragment",value:"mixed"}],default:"document"}),l;(d==="cf"||d==="mixed")&&(l=(await t({message:" CF model / GraphQL persisted-query name (optional)"})).trim()||void 0);let c=await o({message:"5/7 Generate the Universal Editor model?",default:!0}),u=await o({message:"6/7 Add a screenshot MCP call for a pixel check? (off = one fewer MCP call)",default:!1}),p=await zt(),f=await n({message:"7/7 Run with",choices:[...p.map(x=>({name:`${x.type}${r==="figma"&&!x.hasFigmaMcp?" (Figma MCP not detected)":""}`,value:`agent:${x.type}`})),{name:"Preview the prompt only (--dry-run)",value:"dry-run"},{name:"Save the prompt, run it later (--agent none)",value:"none"}],default:p[0]?`agent:${p[0].type}`:"dry-run"}),g=He[r].toLowerCase();i.info(j("Summary"));let y=O(["component",g,"content","ue model","screenshot","run"]);i.info($("component",a,y));let h=r==="figma"?(()=>{let x=Jt(s.trim());return x.nodeId?`node ${x.nodeId}`:x.fileKey})():s.trim();if(i.info($(g,h,y)),i.info($("content",d+(l?` (${l})`:""),y)),i.info($("ue model",c?"yes":"no",y)),i.info($("screenshot",u?"yes":"no (token-lean)",y)),i.info($("run",f.replace("agent:",""),y)),i.info(""),!await o({message:"Generate this block?",default:!0}))return null;let S={figmaUrl:s.trim(),name:a,provider:r,source:d,cfHint:l,ueModel:c,screenshot:u};return f==="dry-run"?S.dryRun=!0:f==="none"?S.agent="none":(S.agent=f.replace("agent:",""),S.yes=!0),S}function ga(e){return e&&e.replace(/[-_\s]+/g,"-").replace(/[^a-z0-9-]/gi,"").toLowerCase().replace(/^-+|-+$/g,"")||"design-block"}function Yl(e){if(/^[a-z][a-z0-9+.-]*:\/\//i.test(e))return null;let t=W.isAbsolute(e)?e:W.resolve(process.cwd(),e);return!se(t)||!Vl.has(W.extname(t).toLowerCase())?null:t}async function Ql(e,t){let n=E();if(!n){i.error("Not inside an EDS project (no EDS project markers found). Run this from your project root."),process.exitCode=1;return}await i.logoOnceAnimated("Design \u2192 EDS block");let o=e,r=t;if(!o){let K=await Xl(o);if(!K){i.info("Cancelled.");return}o=K.figmaUrl,r={...r,...K}}let a=r.provider??"figma",s=He[a],d=Yl(o),l=d?d.startsWith(n+W.sep)?W.relative(n,d):d:void 0,c=null,u=l??o;if(d)i.info(` ${J.pass} Local design file ${C.dim(l)} ${C.dim("(no Figma MCP)")}`);else if(a==="figma"){let K=qt("Parsing Figma URL...").start();try{c=Jt(o),K.succeed(`Parsed Figma URL ${C.dim(c.nodeId?`node ${c.nodeId}`:`file ${c.fileKey}`)}`)}catch(Re){K.fail(Re.message),process.exitCode=1;return}}else i.info(` ${J.pass} ${s} design ${C.dim(u)}`);let p=r.name||(d?ga(W.basename(d,W.extname(d))):c?ga(c.fileName):"");if(!ye.test(p)){i.error(`Invalid block name "${p}". Use --name with a kebab-case name (e.g., --name hero-banner).`),process.exitCode=1;return}!r.name&&c?.nodeId&&(i.warn(`Block name "${p}" came from the Figma file name, not the selected frame.`),i.info(C.dim(` Pass ${C.cyan("--name <kebab-case>")} for a cleaner block name.`)));let f=await fe(n),g=f.figma?.token??process.env.FIGMA_TOKEN??process.env.FIGMA_PAT,y=qt("Resolving design source...").start(),h=await Yr({figma:c,localFile:l,token:g,projectRoot:n,preferMcp:r.mcp,refresh:r.refresh});y.succeed(`Design source ${C.dim(h.summary)}`),h.restError&&i.warn(`Figma REST fetch failed, using MCP fallback: ${h.restError}`);let b=qt("Reading design tokens & building prompt...").start(),S=await ea({provider:a,figma:c,designRef:u,blockName:p,projectRoot:n,withUeModel:r.ueModel!==!1,contentSource:r.source??"document",cfHint:r.cfHint,screenshot:r.screenshot===!0,design:h.design}),x=await Zn(S,n),T=se(W.join(n,"styles","styles.css"));if(b.succeed(T?`Loaded design tokens ${C.dim("styles/styles.css")}`:`Built prompt ${C.dim("no project tokens found")}`),i.info(C.dim(` prompt \u2192 ${x}`)),r.dryRun){i.info(""),i.info(C.yellow("Dry run mode \u2014 prompt generated but agent not invoked.")),i.info(`Prompt file: ${C.cyan(x)}`),i.info(`Block name: ${C.cyan(p)}`),i.info(`Prompt version: ${ut}`),i.info(""),i.info("Preview:"),i.info(C.dim("\u2500".repeat(60))),console.log(S);return}let oe=r.agent||f.agent;if(r.agent==="none"){i.info("Agent skipped (--agent none). Use the prompt file manually:"),i.info(` ${C.cyan(x)}`);return}let H=qt("Detecting AI agent...").start(),q=await Mr(oe);if(!q){H.fail("No AI agent found (claude, cursor, or codex)."),i.info(`Install Claude Code: ${C.cyan("npm install -g @anthropic-ai/claude-code")}`),i.info(`Or use the prompt file manually: ${C.cyan(x)}`),process.exitCode=1;return}if(H.succeed(`Agent ready ${C.cyan(q.type)} ${C.dim(q.path)}`),(h.design?.mode==="mcp"||!h.design&&a==="figma")&&a==="figma"&&!q.hasFigmaMcp&&(i.warn(`Figma MCP may not be configured for ${q.type}.`),i.info(`Run ${C.cyan("eds figma setup")} to configure it, or set a Figma token for REST.`)),!r.yes){let{confirm:K}=await Promise.resolve().then(()=>(B(),U));if(!await K({message:`Run ${q.type} with the generated prompt?`,default:!0})){i.info(`Prompt saved to: ${C.cyan(x)}`);return}}let Te=h.design?.mode==="spec"?"embedded design (no MCP)":h.design?.mode==="file"?`reading ${l}`:h.design?.mode==="mcp"?`via ${s} MCP (1 call, cached)`:`via ${s} MCP`;if(i.info(` ${C.dim("\u2192")} Handing off to ${C.cyan(q.type)} ${C.dim(Te)}`),h.design?.mode==="mcp"&&i.info(C.dim(" get_design_context \xD71 \u2192 cache")),!await eo(q,x,n,f.model)){process.exitCode=1;return}let Ke=W.join(n,"blocks",p);if(!(se(W.join(Ke,`${p}.js`))||se(W.join(Ke,`${p}.css`)))){i.warn(`No block files were written to blocks/${p}/ \u2014 nothing to preview.`),i.info(C.dim(" The agent couldn't read the design, so it generated nothing. Common cause: the")),i.info(C.dim(` ${s} MCP tool-call limit (e.g. Figma Starter plan). See the log above.`)),i.info(C.dim(" Wait for the limit to reset or upgrade the plan, then re-run the same command.")),process.exitCode=1;return}let Oa=await ed(Ke,p,r.ueModel!==!1);if(se(Ke)){let K=W.join(Ke,".eds-meta.json"),Re;if(se(K))try{Re=JSON.parse(await Ge(K,"utf-8")).breakpoints}catch{}let De=Hr(r.widths,Re),Ma={provider:a,designRef:u,figmaFileKey:c?.fileKey??null,figmaNodeId:c?.nodeId??null,lastSyncedAt:new Date().toISOString(),promptVersion:ut,agentUsed:q.type,...De.length?{breakpoints:De}:{}};await ql(K,`${JSON.stringify(Ma,null,2)}
889
- `),De.length&&i.info(C.dim(` Preview breakpoints: ${De.map(Na=>Na.width).join(" \xB7 ")}`))}if(!Oa){i.warn(`Block "${p}" generated with issues \u2014 review the output above before publishing.`),process.exitCode=1;return}if(i.success(`Block "${p}" generation complete.`),!r.yes){let{confirm:K}=await Promise.resolve().then(()=>(B(),U));if(await K({message:"Instrument this block for analytics (dataLayer)?",default:!1})){let{trackBlock:De}=await Promise.resolve().then(()=>(at(),rt));await De(p,{})}}if(!r.yes)await Zl({blockName:p,projectRoot:n,agent:q,model:f.model,provider:a,figma:c,designRef:u});else if(r.serve){let{previewBlock:K}=await Promise.resolve().then(()=>(gt(),ft));await K(p,{})}else i.info(` ${C.dim("\u2192")} Next: ${C.cyan(`eds block preview ${p}`)}`)}async function Zl(e){let{select:t,input:n}=await Promise.resolve().then(()=>(B(),U)),{startPreview:o}=await Promise.resolve().then(()=>(gt(),ft)),r=null;for(i.info("");;){let a=await t({message:"Block ready \u2014 what next?",choices:[{name:"Refine \u2014 describe a change",value:"refine"},{name:r?`Preview open at ${r.url} (reloads on change)`:"Open live preview",value:"preview",disabled:r?"running":!1},{name:"Finish",value:"done"}],default:"refine"});if(a==="done")break;if(a==="preview"){await Kl()?i.info(C.dim(" A preview server is already running at http://127.0.0.1:8777.")):r=await o(e.blockName,{});continue}let s=(await n({message:"Describe the change:"})).trim();if(!s)continue;let d=ta({blockName:e.blockName,feedback:s,provider:e.provider,figma:e.figma,designRef:e.designRef}),l=await Zn(d,e.projectRoot);i.info(` ${C.dim("\u2192")} Applying your change with ${C.cyan(e.agent.type)}\u2026`),await eo(e.agent,l,e.projectRoot,e.model)}r&&(i.info(C.dim(` Preview still live at ${r.url} \u2014 press Ctrl+C to stop.
890
- `)),await new Promise(a=>{let s=async()=>{r&&await r.close(),a(),process.exit(0)};process.on("SIGINT",s),process.on("SIGTERM",s)}))}async function ed(e,t,n){let o=[],r=W.join(e,`${t}.js`),a=W.join(e,`${t}.css`),s=se(r),d=se(a);if(o.push({status:s?"pass":"fail",name:`${t}.js`,message:s?"created":"missing \u2014 agent did not write the JS file"}),o.push({status:d?"pass":"fail",name:`${t}.css`,message:d?"created":"missing \u2014 agent did not write the CSS file"}),s){let c=await Ge(r,"utf-8");o.push({status:/export\s+default/.test(c)?"pass":"fail",name:"decorate export",message:/export\s+default/.test(c)?"found":"no default export \u2014 block won't load"}),c.includes("console.log")&&o.push({status:"warn",name:"no console.log",message:"found console.log \u2014 remove before production"})}if(d){let c=await Ge(a,"utf-8");o.push({status:c.includes(`.${t}`)?"pass":"warn",name:"scoped CSS",message:c.includes(`.${t}`)?`scoped to .${t}`:`no .${t} selector \u2014 styles may leak`})}if(n){let c=se(W.join(e,`_${t}.json`)),u=W.join(e,"..","..","component-models.json"),p=!1;if(!c&&se(u))try{p=(await Ge(u,"utf-8")).includes(`"${t}"`)}catch{}let f=c||p;if(o.push({status:f?"pass":"warn",name:"Universal Editor model",message:f?c?`_${t}.json created`:"added to component-models.json":`missing \u2014 no _${t}.json (run with default UE generation, or --no-ue-model to skip)`}),c&&s)try{let g=await Ge(W.join(e,`_${t}.json`),"utf-8"),y=await Ge(r,"utf-8"),h=/"resourceType"\s*:\s*"[^"]*\/item"/.test(g)||/"filter"\s*:/.test(g)||/"multi"\s*:\s*true/.test(g),b=/\.children/.test(y)||/\bfor\s*\(/.test(y)||/\.forEach\s*\(/.test(y);h&&o.push({status:b?"pass":"warn",name:"multifield wired",message:b?"decorate() iterates items":"repeatable model but decorate() never iterates block.children \u2014 only one item will render"})}catch{}}i.info(j("Verification"));let l=O(o.map(c=>c.name));for(let c of o)i.info(D(c.status,c.name,c.message,l));return i.info(""),!o.some(c=>c.status==="fail")}var Vl,uo=w(()=>{"use strict";m();Qn();Nr();Pe();Gr();Qr();Zr();na();R();z();Me();I();Vl=new Set([".svg",".png",".jpg",".jpeg",".webp"])});var ha={};N(ha,{listBlocks:()=>od});import{existsSync as ht}from"fs";import{readFile as td,readdir as nd}from"fs/promises";import ze from"path";import Je from"chalk";async function od(e={}){let t=E();if(!t){i.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}let n=ze.join(t,"blocks");if(!ht(n)){i.info("No blocks/ directory found.");return}let o=await nd(n,{withFileTypes:!0}),r=[];for(let s of o){if(!s.isDirectory())continue;let d=s.name,l=ze.join(n,d),c={name:d,hasJs:ht(ze.join(l,`${d}.js`)),hasCss:ht(ze.join(l,`${d}.css`)),hasUeModel:ht(ze.join(l,`_${d}.json`))},u=ze.join(l,".eds-meta.json");if(ht(u))try{let p=JSON.parse(await td(u,"utf-8"));c.figmaSource={fileKey:p.figmaFileKey,nodeId:p.figmaNodeId,lastSyncedAt:p.lastSyncedAt}}catch{}r.push(c)}if(e.json){console.log(JSON.stringify(r,null,2));return}if(r.length===0){i.info("No blocks found.");return}i.info(j("Blocks",`${r.length} in project`));let a=O(r.map(s=>s.name));for(let s of r){let d=[s.hasJs?_.ok("js"):Je.dim.strikethrough("js"),s.hasCss?_.ok("css"):Je.dim.strikethrough("css")];s.hasUeModel&&d.push(_.blue("ue-model")),s.figmaSource&&d.push(`${J.figma} ${_.dotPurple("figma")}`);let l=Xe(Je.bold(s.name),a);if(i.info(` ${l} ${Je.dim("[")}${d.join(" ")}${Je.dim("]")}`),s.figmaSource){let c=new Date(s.figmaSource.lastSyncedAt).toLocaleDateString();i.info(` ${" ".repeat(a)} ${J.arrow} ${Je.dim(`figma:${s.figmaSource.fileKey} \xB7 synced ${c}`)}`)}}i.info("")}var ba=w(()=>{"use strict";m();R();z();I()});function wa(e){return Kt.find(t=>t.id===e)}function ya(e,t){return`
892
+ </div>`}async function pe(e,t,n){let o=Y.join(e,"blocks",t);if(!oe(Y.join(o,`${t}.css`))&&!oe(Y.join(o,`${t}.js`)))return null;let i=null,a=Y.join(o,".eds-meta.json");if(oe(a))try{i=JSON.parse(await rn(a,"utf-8"))}catch{}let s=Y.join(o,`_${t}.preview.html`),d,l=!1;return oe(s)?d=await rn(s,"utf-8"):(d=Ca(t),l=!0),{name:t,sampleContent:d,breakpoints:Pa(n,i),figmaUrl:Ea(i),placeholder:l}}async function Ke(e,t,n){return on(e,{},n,"127.0.0.1",async i=>{if(!i.startsWith(ve))return;let a=i.slice(ve.length);if(!/^[a-z0-9-]+$/i.test(a))return;let s=await pe(e,a,t);if(s)return{body:nn({blockName:a,breakpoints:s.breakpoints,sampleContent:s.sampleContent,frameRoute:ve+a}),type:"text/html; charset=utf-8"}})}async function Fe(e){let t=Y.join(e,"blocks");if(!oe(t))return[];let n=await xd(t,{withFileTypes:!0}),o=[];for(let i of n){if(!i.isDirectory()||$d.has(i.name))continue;let a=Y.join(t,i.name);(oe(Y.join(a,`${i.name}.css`))||oe(Y.join(a,`${i.name}.js`)))&&o.push(i.name)}return o.sort()}async function Aa(e){let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{let{execa:n}=await import("execa");await n(t,[e],{stdio:"ignore",shell:process.platform==="win32"})}catch{}}async function Ta(e,t={}){let n=P();if(!n)return r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1,null;let o=Y.join(n,"blocks",e);if(!oe(o))return r.error(`Block "${e}" not found at blocks/${e}/.`),process.exitCode=1,null;if(!oe(Y.join(o,`${e}.css`))&&!oe(Y.join(o,`${e}.js`)))return r.error(`Block "${e}" has no ${e}.css / ${e}.js to preview.`),process.exitCode=1,null;(e==="header"||e==="footer")&&(r.warn(`"${e}" is page chrome, not a content block \u2014 it won't render standalone here.`),r.info(ye.dim(` It fetches the ${e==="header"?"nav":"footer"} fragment and needs the full page runtime.`)),r.info(ye.dim(" Preview a content block instead (e.g. a block generated from a design).")));let i=null,a=Y.join(o,".eds-meta.json");if(oe(a))try{i=JSON.parse(await rn(a,"utf-8"))}catch{}let s=Y.join(o,`_${e}.preview.html`),d,l=!1;oe(s)?d=await rn(s,"utf-8"):(d=Ca(e),l=!0);let c=Pa(t.widths,i),p=Ea(i),m="/__eds_preview_frame",u=nn({blockName:e,breakpoints:c,sampleContent:d,frameRoute:m}),g=xa({blockName:e,breakpoints:c,sampleContent:d,figmaUrl:p,frameRoute:m,placeholder:l}),w=Number.parseInt(t.port??"8777",10),y=await on(n,{"/":{body:g,type:"text/html; charset=utf-8"},[m]:{body:u,type:"text/html; charset=utf-8"}},Number.isFinite(w)?w:8777);r.logoOnce(E(`Preview \u2014 ${e}`)),r.info(S("Live preview",y.url)),r.info(A("pass","breakpoints",`${c.map(b=>`${b.width}${b.figma?"\u2713":""}`).join(", ")}, Full`)),l&&r.info(A("warn","content",`placeholder \u2014 add blocks/${e}/_${e}.preview.html for real content`));let h,$=ja(o,{recursive:!0},()=>{clearTimeout(h),h=setTimeout(()=>y.reload(),150)});return r.info(""),r.info(` ${ye.bold("\u279C")} ${ye.cyan(y.url)}`),r.info(A("pass","live reload","edits to the block refresh the browser")),t.open!==!1&&await Aa(y.url),{url:y.url,close:async()=>{$.close(),await y.close()}}}async function jd(e,t={}){let n=await Ta(e,t);n&&(r.info(ye.dim(` Press Ctrl+C to stop.
893
+ `)),await new Promise(o=>{let i=async()=>{await n.close(),o(),process.exit(0)};process.on("SIGINT",i),process.on("SIGTERM",i)}))}async function Pd(e={}){let t=P();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}let n="/__eds_frame/",o=async c=>{if(c==="/"){let p=await Fe(t),m=[];for(let u of p){let g=await pe(t,u,e.widths);g&&m.push({blockName:u,breakpoints:g.breakpoints,frameRoute:n+u,figmaUrl:g.figmaUrl,placeholder:g.placeholder})}return{body:ka(m),type:"text/html; charset=utf-8"}}if(c.startsWith(n)){let p=c.slice(n.length);if(!/^[a-z0-9-]+$/i.test(p))return;let m=await pe(t,p,e.widths);return m?{body:nn({blockName:p,breakpoints:m.breakpoints,sampleContent:m.sampleContent,frameRoute:n+p}),type:"text/html; charset=utf-8"}:void 0}},i=Number.parseInt(e.port??"8777",10),a=await on(t,{},Number.isFinite(i)?i:8777,"127.0.0.1",o),s=await Fe(t);r.logoOnce(E("Preview \u2014 gallery")),r.info(S("Live gallery",a.url)),r.info(A(s.length?"pass":"warn","blocks",s.length?s.join(", "):"none yet \u2014 generate one with eds block from-design"));let d,l=ja(Y.join(t,"blocks"),{recursive:!0},()=>{clearTimeout(d),d=setTimeout(()=>a.reload(),150)});r.info(""),r.info(` ${ye.bold("\u279C")} ${ye.cyan(a.url)}`),r.info(A("pass","live reload","new & edited blocks refresh the browser")),r.info(ye.dim(` Press Ctrl+C to stop.
894
+ `)),e.open!==!1&&await Aa(a.url),await new Promise(c=>{let p=async()=>{l.close(),await a.close(),c(),process.exit(0)};process.on("SIGINT",p),process.on("SIGTERM",p)})}var $d,Sd,ve,De=v(()=>{"use strict";f();R();$a();Sa();B();N();$d=new Set(["header","footer"]),Sd=[375,768,1280];ve="/__eds_frame/"});var $o={};L($o,{blockFromDesign:()=>Nd});import{existsSync as ie}from"fs";import{readFile as Xe,writeFile as Ed}from"fs/promises";import W from"path";import{fileURLToPath as Cd}from"url";import C from"chalk";import an from"ora";function Ad(){let e=W.dirname(Cd(import.meta.url));return[W.resolve(e,"../../samples/hero.svg"),W.resolve(e,"../../../samples/hero.svg")].find(n=>ie(n))??null}async function Td(e=8777){try{let t=new AbortController,n=setTimeout(()=>t.abort(),400),o=await fetch(`http://127.0.0.1:${e}/__eds_ping`,{signal:t.signal});return clearTimeout(n),o.ok?(await o.json())?.eds===!0:!1}catch{return!1}}async function Rd(e){let{input:t,select:n,confirm:o}=await Promise.resolve().then(()=>(G(),H)),i=await n({message:"1/7 Design source",choices:[{name:"Figma (REST / MCP / local)",value:"figma"},{name:"Framer (scraped, headless Chromium)",value:"framer"},{name:"Google Stitch (scraped, headless Chromium)",value:"stitch"}],default:"figma"}),a=await t({message:"2/7 Component name",validate:b=>Se.test(b.trim())||"Use kebab-case, e.g. hero-banner"}),s=e??await t({message:`3/7 ${qe[i]} link`,validate:b=>{if(!b.trim())return"Paste the design link";if(i!=="figma")return/^https?:\/\//i.test(b.trim())||"Paste a public http(s) URL to the page";try{return tn(b.trim()),!0}catch(T){return T.message}}}),d=await n({message:"4/7 Where does the content come from?",choices:[{name:"Document authoring (default EDS)",value:"document"},{name:"Universal Editor",value:"ue"},{name:"Content Fragment",value:"cf"},{name:"Mixed - Universal Editor + Content Fragment",value:"mixed"}],default:"document"}),l;(d==="cf"||d==="mixed")&&(l=(await t({message:" CF model / GraphQL persisted-query name (optional)"})).trim()||void 0);let c=await o({message:"5/7 Generate the Universal Editor model?",default:!0}),p=await o({message:"6/7 Add a screenshot MCP call for a pixel check? (off = one fewer MCP call)",default:!1}),m=await en(),u=await n({message:"7/7 Run with",choices:[...m.map(b=>({name:`${b.type}${i==="figma"&&!b.hasFigmaMcp?" (Figma MCP not detected)":""}`,value:`agent:${b.type}`})),{name:"Preview the prompt only (--dry-run)",value:"dry-run"},{name:"Save the prompt, run it later (--agent none)",value:"none"}],default:m[0]?`agent:${m[0].type}`:"dry-run"}),g=qe[i].toLowerCase();r.info(S("Summary"));let w=M(["component",g,"content","ue model","screenshot","run"]);r.info(j("component",a,w));let y=i==="figma"?(()=>{let b=tn(s.trim());return b.nodeId?`node ${b.nodeId}`:b.fileKey})():s.trim();if(r.info(j(g,y,w)),r.info(j("content",d+(l?` (${l})`:""),w)),r.info(j("ue model",c?"yes":"no",w)),r.info(j("screenshot",p?"yes":"no (token-lean)",w)),r.info(j("run",u.replace("agent:",""),w)),r.info(""),!await o({message:"Generate this block?",default:!0}))return null;let $={figmaUrl:s.trim(),name:a,provider:i,source:d,cfHint:l,ueModel:c,screenshot:p};return u==="dry-run"?$.dryRun=!0:u==="none"?$.agent="none":($.agent=u.replace("agent:",""),$.yes=!0),$}function xo(e){return e&&e.replace(/[-_\s]+/g,"-").replace(/[^a-z0-9-]/gi,"").toLowerCase().replace(/^-+|-+$/g,"")||"design-block"}function Fd(e){try{let t=new URL(e);return t.pathname.split("/").filter(Boolean).pop()||t.hostname.split(".")[0]}catch{return""}}function Dd(e){if(e)try{let t=new URL(e).hostname.toLowerCase();if(t.includes("figma.com"))return"figma";if(t.includes("framer"))return"framer";if(t.includes("stitch"))return"stitch"}catch{}}function Od(e){if(/^[a-z][a-z0-9+.-]*:\/\//i.test(e))return null;let t=W.isAbsolute(e)?e:W.resolve(process.cwd(),e);return!ie(t)||!Ld.has(W.extname(t).toLowerCase())?null:t}async function Nd(e,t){let n=P();if(!n){r.error("Not inside an EDS project (no EDS project markers found). Run this from your project root."),process.exitCode=1;return}await r.logoOnceAnimated("Design \u2192 EDS block");let o=e,i=t;if(!o&&i.sample){let J=Ad();if(!J){r.error("Bundled sample design not found (samples/hero.svg)."),process.exitCode=1;return}o=J,i={name:"hero",provider:"figma",...i},r.info(` ${q.pass} Sample design ${C.dim("Kiri Bloom hero")} ${C.dim("(bundled \xB7 no token \xB7 no MCP)")}`)}if(!o){let J=await Rd(o);if(!J){r.info("Cancelled.");return}o=J.figmaUrl,i={...i,...J}}let a=i.provider;if(a&&!(a in qe)){r.error(`Unknown --provider "${a}". Use: figma, framer or stitch.`),process.exitCode=1;return}let s=a??Dd(o)??"figma",d=qe[s],l=Od(o),c=l?l.startsWith(n+W.sep)?W.relative(n,l):l:void 0,p=null,m=c??o;if(l)r.info(` ${q.pass} Local design file ${C.dim(c)} ${C.dim("(no Figma MCP)")}`);else if(s==="figma"){let J=an("Parsing Figma URL...").start();try{p=tn(o),J.succeed(`Parsed Figma URL ${C.dim(p.nodeId?`node ${p.nodeId}`:`file ${p.fileKey}`)}`)}catch(Ne){J.fail(Ne.message),process.exitCode=1;return}}else r.info(` ${q.pass} ${d} design ${C.dim(m)}`);let u=i.name||(l?xo(W.basename(l,W.extname(l))):p?xo(p.fileName):o?xo(Fd(o)):"");if(!Se.test(u)){r.error(`Invalid block name "${u}". Use --name with a kebab-case name (e.g., --name hero-banner).`),process.exitCode=1;return}!i.name&&p?.nodeId&&(r.warn(`Block name "${u}" came from the Figma file name, not the selected frame.`),r.info(C.dim(` Pass ${C.cyan("--name <kebab-case>")} for a cleaner block name.`)));let g=await se(n),w=g.figma?.token??process.env.FIGMA_TOKEN??process.env.FIGMA_PAT,y=an("Resolving design source...").start(),h=await ga({figma:p,localFile:c,token:w,projectRoot:n,preferMcp:i.mcp,refresh:i.refresh,provider:s,designUrl:l?void 0:o,dryRun:i.dryRun});if(h.scrapeError){y.fail(`Scrape failed: ${h.scrapeError}`),r.info(C.dim(` Check the URL is a public ${d} page, and that Chromium is installed (${C.cyan("npx playwright install chromium")}).`)),process.exitCode=1;return}y.succeed(`Design source ${C.dim(h.summary)}`),h.restError&&r.warn(`Figma REST fetch failed, using MCP fallback: ${h.restError}`);let $=an("Reading design tokens & building prompt...").start(),b=await ba({provider:s,figma:p,designRef:m,blockName:u,projectRoot:n,withUeModel:i.ueModel!==!1,contentSource:i.source??"document",cfHint:i.cfHint,screenshot:i.screenshot===!0,design:h.design}),T=await po(b,n),Q=ie(W.join(n,"styles","styles.css"));if($.succeed(Q?`Loaded design tokens ${C.dim("styles/styles.css")}`:`Built prompt ${C.dim("no project tokens found")}`),r.info(C.dim(` prompt \u2192 ${T}`)),i.dryRun){r.info(""),r.info(C.yellow("Dry run mode \u2014 prompt generated but agent not invoked.")),r.info(`Prompt file: ${C.cyan(T)}`),r.info(`Block name: ${C.cyan(u)}`),r.info(`Prompt version: ${xt}`),r.info(""),r.info("Preview:"),r.info(C.dim("\u2500".repeat(60))),console.log(b);return}let z=i.agent||g.agent;if(i.agent==="none"){r.info("Agent skipped (--agent none). Use the prompt file manually:"),r.info(` ${C.cyan(T)}`);return}let ue=an("Detecting AI agent...").start(),te=await Yr(z);if(!te){ue.fail("No AI agent found (claude, cursor, or codex)."),r.info(`Install Claude Code: ${C.cyan("npm install -g @anthropic-ai/claude-code")}`),r.info(`Or use the prompt file manually: ${C.cyan(T)}`),process.exitCode=1;return}if(ue.succeed(`Agent ready ${C.cyan(te.type)} ${C.dim(te.path)}`),(h.design?.mode==="mcp"||!h.design&&s==="figma")&&s==="figma"&&!te.hasFigmaMcp&&(r.warn(`Figma MCP may not be configured for ${te.type}.`),r.info(`Run ${C.cyan("eds figma setup")} to configure it, or set a Figma token for REST.`)),!i.yes){let{confirm:J}=await Promise.resolve().then(()=>(G(),H));if(!await J({message:`Run ${te.type} with the generated prompt?`,default:!0})){r.info(`Prompt saved to: ${C.cyan(T)}`);return}}let ms=h.design?.mode==="spec"?"embedded design (no MCP)":h.design?.mode==="scrape"?`scraped ${d} page (no MCP)`:h.design?.mode==="file"?`reading ${c}`:h.design?.mode==="mcp"?`via ${d} MCP (1 call, cached)`:`via ${d} MCP`;if(r.info(` ${C.dim("\u2192")} Handing off to ${C.cyan(te.type)} ${C.dim(ms)}`),h.design?.mode==="mcp"&&r.info(C.dim(" get_design_context \xD71 \u2192 cache")),!await mo(te,T,n,g.model)){process.exitCode=1;return}let nt=W.join(n,"blocks",u);if(!(ie(W.join(nt,`${u}.js`))||ie(W.join(nt,`${u}.css`)))){r.warn(`No block files were written to blocks/${u}/ \u2014 nothing to preview.`),h.design?.mode==="mcp"?(r.info(C.dim(" The agent couldn't read the design, so it generated nothing. Common cause: the")),r.info(C.dim(` ${d} MCP tool-call limit (e.g. Figma Starter plan). See the log above.`)),r.info(C.dim(" Wait for the limit to reset or upgrade the plan, then re-run the same command."))):r.info(C.dim(" The agent generated nothing \u2014 see the log above for why.")),process.exitCode=1;return}let us=await Id(nt,u,i.ueModel!==!1);if(ie(nt)){let J=W.join(nt,".eds-meta.json"),Ne;if(ie(J))try{Ne=JSON.parse(await Xe(J,"utf-8")).breakpoints}catch{}let Me=oa(i.widths,Ne),fs={provider:s,designRef:m,figmaFileKey:p?.fileKey??null,figmaNodeId:p?.nodeId??null,lastSyncedAt:new Date().toISOString(),promptVersion:xt,agentUsed:te.type,...Me.length?{breakpoints:Me}:{}};await Ed(J,`${JSON.stringify(fs,null,2)}
895
+ `),Me.length&&r.info(C.dim(` Preview breakpoints: ${Me.map(gs=>gs.width).join(" \xB7 ")}`))}if(!us){r.warn(`Block "${u}" generated with issues \u2014 review the output above before publishing.`),process.exitCode=1;return}if(r.success(`Block "${u}" generation complete.`),!i.yes){let{confirm:J}=await Promise.resolve().then(()=>(G(),H));if(await J({message:"Instrument this block for analytics (dataLayer)?",default:!1})){let{trackBlock:Me}=await Promise.resolve().then(()=>(ft(),ut));await Me(u,{})}}if(!i.yes)await Md({blockName:u,projectRoot:n,agent:te,model:g.model,provider:s,figma:p,designRef:m});else if(i.serve){let{previewBlock:J}=await Promise.resolve().then(()=>(De(),$t));await J(u,{})}else r.info(` ${C.dim("\u2192")} Next: ${C.cyan(`eds block preview ${u}`)}`)}async function Md(e){let{select:t,input:n}=await Promise.resolve().then(()=>(G(),H)),{startPreview:o}=await Promise.resolve().then(()=>(De(),$t)),i=null;for(r.info("");;){let a=await t({message:"Block ready \u2014 what next?",choices:[{name:"Refine \u2014 describe a change",value:"refine"},{name:i?`Preview open at ${i.url} (reloads on change)`:"Open live preview",value:"preview",disabled:i?"running":!1},{name:"Finish",value:"done"}],default:"refine"});if(a==="done")break;if(a==="preview"){await Td()?r.info(C.dim(" A preview server is already running at http://127.0.0.1:8777.")):i=await o(e.blockName,{});continue}let s=(await n({message:"Describe the change:"})).trim();if(!s)continue;let d=ya({blockName:e.blockName,feedback:s,provider:e.provider,figma:e.figma,designRef:e.designRef}),l=await po(d,e.projectRoot);r.info(` ${C.dim("\u2192")} Applying your change with ${C.cyan(e.agent.type)}\u2026`),await mo(e.agent,l,e.projectRoot,e.model)}i&&(r.info(C.dim(` Preview still live at ${i.url} \u2014 press Ctrl+C to stop.
896
+ `)),await new Promise(a=>{let s=async()=>{i&&await i.close(),a(),process.exit(0)};process.on("SIGINT",s),process.on("SIGTERM",s)}))}async function Id(e,t,n){let o=[],i=W.join(e,`${t}.js`),a=W.join(e,`${t}.css`),s=ie(i),d=ie(a);if(o.push({status:s?"pass":"fail",name:`${t}.js`,message:s?"created":"missing \u2014 agent did not write the JS file"}),o.push({status:d?"pass":"fail",name:`${t}.css`,message:d?"created":"missing \u2014 agent did not write the CSS file"}),s){let c=await Xe(i,"utf-8");o.push({status:/export\s+default/.test(c)?"pass":"fail",name:"decorate export",message:/export\s+default/.test(c)?"found":"no default export \u2014 block won't load"}),c.includes("console.log")&&o.push({status:"warn",name:"no console.log",message:"found console.log \u2014 remove before production"})}if(d){let c=await Xe(a,"utf-8");o.push({status:c.includes(`.${t}`)?"pass":"warn",name:"scoped CSS",message:c.includes(`.${t}`)?`scoped to .${t}`:`no .${t} selector \u2014 styles may leak`})}if(n){let c=ie(W.join(e,`_${t}.json`)),p=W.join(e,"..","..","component-models.json"),m=!1;if(!c&&ie(p))try{m=(await Xe(p,"utf-8")).includes(`"${t}"`)}catch{}let u=c||m;if(o.push({status:u?"pass":"warn",name:"Universal Editor model",message:u?c?`_${t}.json created`:"added to component-models.json":`missing \u2014 no _${t}.json (run with default UE generation, or --no-ue-model to skip)`}),c&&s)try{let g=await Xe(W.join(e,`_${t}.json`),"utf-8"),w=await Xe(i,"utf-8"),y=/"resourceType"\s*:\s*"[^"]*\/item"/.test(g)||/"filter"\s*:/.test(g)||/"multi"\s*:\s*true/.test(g),h=/\.children/.test(w)||/\bfor\s*\(/.test(w)||/\.forEach\s*\(/.test(w);y&&o.push({status:h?"pass":"warn",name:"multifield wired",message:h?"decorate() iterates items":"repeatable model but decorate() never iterates block.children \u2014 only one item will render"})}catch{}}r.info(S("Verification"));let l=M(o.map(c=>c.name));for(let c of o)r.info(A(c.status,c.name,c.message,l));return r.info(""),!o.some(c=>c.status==="fail")}var Ld,So=v(()=>{"use strict";f();lo();Qr();be();ia();ha();wa();va();R();B();Be();N();Ld=new Set([".svg",".png",".jpg",".jpeg",".webp"])});var Ra={};L(Ra,{listBlocks:()=>Bd});import{existsSync as St}from"fs";import{readFile as _d,readdir as Ud}from"fs/promises";import Ve from"path";import Ye from"chalk";async function Bd(e={}){let t=P();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}let n=Ve.join(t,"blocks");if(!St(n)){r.info("No blocks/ directory found.");return}let o=await Ud(n,{withFileTypes:!0}),i=[];for(let s of o){if(!s.isDirectory())continue;let d=s.name,l=Ve.join(n,d),c={name:d,hasJs:St(Ve.join(l,`${d}.js`)),hasCss:St(Ve.join(l,`${d}.css`)),hasUeModel:St(Ve.join(l,`_${d}.json`))},p=Ve.join(l,".eds-meta.json");if(St(p))try{let m=JSON.parse(await _d(p,"utf-8"));c.figmaSource={fileKey:m.figmaFileKey,nodeId:m.figmaNodeId,lastSyncedAt:m.lastSyncedAt}}catch{}i.push(c)}if(e.json){console.log(JSON.stringify(i,null,2));return}if(i.length===0){r.info("No blocks found.");return}r.info(S("Blocks",`${i.length} in project`));let a=M(i.map(s=>s.name));for(let s of i){let d=[s.hasJs?_.ok("js"):Ye.dim.strikethrough("js"),s.hasCss?_.ok("css"):Ye.dim.strikethrough("css")];s.hasUeModel&&d.push(_.blue("ue-model")),s.figmaSource&&d.push(`${q.figma} ${_.dotPurple("figma")}`);let l=ot(Ye.bold(s.name),a);if(r.info(` ${l} ${Ye.dim("[")}${d.join(" ")}${Ye.dim("]")}`),s.figmaSource){let c=new Date(s.figmaSource.lastSyncedAt).toLocaleDateString();r.info(` ${" ".repeat(a)} ${q.arrow} ${Ye.dim(`figma:${s.figmaSource.fileKey} \xB7 synced ${c}`)}`)}}r.info("")}var Fa=v(()=>{"use strict";f();R();B();N()});import Da from"path";function jo(e,t){return Da.join(e,"blocks",t,"__snapshots__")}function Oa(e,t,n){return Da.join(jo(e,t),`${t}-${n}.png`)}function jt(e){return`${(e*100).toFixed(2)}%`}async function Po(e,t,n=900){let o;try{({chromium:o}=await import("playwright"))}catch{throw new Error(La)}let i=await o.launch();try{let a=await i.newPage({viewport:{width:t,height:n}});return await a.goto(e,{waitUntil:"networkidle"}),await a.waitForTimeout(300),await a.screenshot({fullPage:!0})}finally{await i.close()}}async function Na(){try{let e="pngjs",t="pixelmatch",{PNG:n}=await import(e),o=(await import(t)).default;return{PNG:n,pixelmatch:o}}catch{throw new Error(La)}}async function Ma(e,t){let{PNG:n,pixelmatch:o}=await Na(),i=n.sync.read(e),a=n.sync.read(t);if(i.width!==a.width||i.height!==a.height)return{diffPixels:-1,totalPixels:0,ratio:1,sizeMismatch:!0,width:i.width,height:i.height};let{width:s,height:d}=i,l=new n({width:s,height:d}),c=o(i.data,a.data,l.data,s,d,{threshold:.1}),p=s*d;return{diffPixels:c,totalPixels:p,ratio:p?c/p:0,width:s,height:d,diffPng:n.sync.write(l)}}async function Ia(e,t){let{PNG:n,pixelmatch:o}=await Na(),i=n.sync.read(e),a=n.sync.read(t),s=Math.min(i.width,a.width),d=Math.min(i.height,a.height),l=new n({width:s,height:d}),c=new n({width:s,height:d});i.bitblt(l,0,0,s,d,0,0),a.bitblt(c,0,0,s,d,0,0);let p=new n({width:s,height:d}),m=o(l.data,c.data,p.data,s,d,{threshold:.1}),u=s*d;return{diffPixels:m,totalPixels:u,ratio:u?m/u:0,width:s,height:d,diffPng:n.sync.write(p)}}var La,_a=v(()=>{"use strict";f();La=`Visual testing needs extra tools. Install them with:
897
+ npm i -D playwright pixelmatch pngjs && npx playwright install chromium`});var Ga={};L(Ga,{visualTest:()=>Hd});import{existsSync as Ua}from"fs";import{mkdir as Eo,readFile as Ba,writeFile as Pt}from"fs/promises";import me from"path";import Co from"chalk";async function Hd(e,t={}){let n=P();if(!n){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}if(t.design){await Gd(n,e,t);return}let o=e?[e]:await Fe(n);if(!o.length){r.warn("No previewable blocks to test.");return}let i=Number.parseInt(t.port??"8788",10),a=await Ke(n,t.widths,Number.isFinite(i)?i:8788),s=Number.parseFloat(t.threshold??"0.01"),d=me.join(n,"tmp","eds-cli","visual-diff");r.logoOnce(E("Visual test"));let l=0,c=0,p=0,m=0;try{for(let u of o){let g=await pe(n,u,t.widths);if(g){r.info(S(u));for(let w of g.breakpoints){let y=await Po(Ha(a.url,u),w.width),h=Oa(n,u,w.width),$=Ua(h);if(t.update||!$){await Eo(jo(n,u),{recursive:!0}),await Pt(h,y),$?(m++,r.info(A("pass",`${w.width}px`,"baseline updated"))):(p++,r.info(A("pass",`${w.width}px`,"baseline created")));continue}let b=await Ma(await Ba(h),y);if(b.sizeMismatch){c++,r.info(A("fail",`${w.width}px`,`size changed \u2192 ${b.width}\xD7${b.height}`));continue}if(b.ratio>s){c++,await Eo(d,{recursive:!0});let T=me.join(d,`${u}-${w.width}.diff.png`);b.diffPng&&await Pt(T,b.diffPng),r.info(A("fail",`${w.width}px`,`${jt(b.ratio)} changed \u2192 ${me.relative(n,T)}`))}else l++,r.info(A("pass",`${w.width}px`,b.ratio>0?`${jt(b.ratio)} (within ${jt(s)})`:"identical"))}}}}catch(u){r.error(u instanceof Error?u.message:String(u)),process.exitCode=1;return}finally{await a.close()}r.info(""),r.info(`${Co.green(`${l} passed`)} \xB7 ${Co.yellow(`${c} changed`)} \xB7 ${p} new \xB7 ${m} updated`),c>0&&(r.warn(`${c} visual change(s). Review the diff PNGs in tmp/eds-cli/visual-diff/, then re-run with --update to accept.`),process.exitCode=1)}async function Gd(e,t,n){if(!t){r.error("Design diff needs a block name: eds block test <name> --design"),process.exitCode=1;return}let o=await pe(e,t,n.widths);if(!o){r.error(`Block "${t}" has no css/js to render.`),process.exitCode=1;return}let i,a,s=me.join(e,"blocks",t,".eds-meta.json");if(Ua(s))try{let g=JSON.parse(await Ba(s,"utf-8"));i=g.figmaFileKey??void 0,a=g.figmaNodeId??void 0}catch{}if(!i||!a){r.error(`"${t}" has no Figma source in .eds-meta.json \u2014 can't fetch the design image.`),process.exitCode=1;return}let l=(await se(e)).figma?.token??process.env.FIGMA_TOKEN??process.env.FIGMA_PAT;if(!l){r.error("Design diff needs a Figma token (FIGMA_TOKEN or figma.token) to render the node."),process.exitCode=1;return}let c=o.breakpoints.filter(g=>g.figma),p=(c.length?c:o.breakpoints).reduce((g,w)=>w.width>g.width?w:g,o.breakpoints[0]).width,m=Number.parseInt(n.port??"8788",10),u=await Ke(e,n.widths,Number.isFinite(m)?m:8788);r.logoOnce(E("Design \u2194 render")),r.info(S(t,`${p}px`));try{let g=await Po(Ha(u.url,t),p);r.info(A("pass","render","block screenshot captured"));let w=await da({fileKey:i,nodeId:a,token:l,scale:1});r.info(A("pass","design","Figma image fetched (REST)"));let y=await Ia(w,g),h=me.join(e,"tmp","eds-cli","visual-diff");await Eo(h,{recursive:!0}),await Pt(me.join(h,`${t}-design.png`),w),await Pt(me.join(h,`${t}-render.png`),g),y.diffPng&&await Pt(me.join(h,`${t}-design-diff.png`),y.diffPng),r.info(A("warn","diff",`~${jt(y.ratio)} different over ${y.width}\xD7${y.height} (approximate)`)),r.info(""),r.info(Co.dim(` Saved design / render / diff to ${me.relative(e,h)}/${t}-*.png \u2014 compare side by side.`))}catch(g){r.error(g instanceof Error?g.message:String(g)),process.exitCode=1}finally{await u.close()}}var Ha,za=v(()=>{"use strict";f();be();yo();R();_a();B();N();De();Ha=(e,t)=>`${e}${ve.slice(1)}${t}`});async function Wa(e,t){let n;try{({chromium:n}=await import("playwright"))}catch{throw new Error(zd)}let o=await n.launch();try{let i=await o.newPage({viewport:{width:t,height:900}});return await i.goto(e,{waitUntil:"networkidle"}),await i.waitForTimeout(200),await i.evaluate(Wd)}finally{await o.close()}}var zd,Wd,Ja=v(()=>{"use strict";f();zd=`Content checks need Playwright. Install it with:
898
+ npm i -D playwright && npx playwright install chromium`,Wd=`(() => {
899
+ const out = [];
900
+ const root = document.querySelector('[class$="block"]') || document.body;
901
+ const trunc = (s) => (s || '').slice(0, 60);
902
+ const accName = (el) => {
903
+ const t = (el.getAttribute('aria-label') || el.textContent || '').trim();
904
+ if (t) return t;
905
+ const img = el.querySelector('img');
906
+ if (img && (img.getAttribute('alt') || '').trim()) return img.getAttribute('alt').trim();
907
+ return (el.getAttribute('title') || '').trim();
908
+ };
909
+ for (const img of root.querySelectorAll('img')) {
910
+ const src = trunc(img.getAttribute('src'));
911
+ if (!img.hasAttribute('alt')) out.push({ level: 'warn', rule: 'img-alt', detail: '<img> without alt (use alt="" if decorative): ' + src });
912
+ const cs = getComputedStyle(img);
913
+ const hasDims = (img.hasAttribute('width') && img.hasAttribute('height'))
914
+ || (cs.aspectRatio && cs.aspectRatio !== 'auto')
915
+ || (cs.height && cs.height !== 'auto' && cs.height !== '0px');
916
+ if (!hasDims) out.push({ level: 'warn', rule: 'img-cls', detail: '<img> without width/height or aspect-ratio (CLS risk): ' + src });
917
+ }
918
+ for (const a of root.querySelectorAll('a')) {
919
+ if (!accName(a)) out.push({ level: 'error', rule: 'link-name', detail: '<a> with no accessible name, href=' + trunc(a.getAttribute('href')) });
920
+ const href = a.getAttribute('href');
921
+ if (href === null || href === '') out.push({ level: 'warn', rule: 'link-href', detail: '<a> with empty or missing href' });
922
+ }
923
+ for (const b of root.querySelectorAll('button')) {
924
+ if (!accName(b)) out.push({ level: 'error', rule: 'button-name', detail: '<button> with no accessible name' });
925
+ }
926
+ for (const el of root.querySelectorAll('*')) {
927
+ for (const attr of el.getAttributeNames()) {
928
+ if (attr.startsWith('on')) { out.push({ level: 'warn', rule: 'inline-handler', detail: '<' + el.tagName.toLowerCase() + '> has inline ' + attr }); break; }
929
+ }
930
+ }
931
+ return out;
932
+ })()`});var qa={};L(qa,{blockCheck:()=>Jd});import Ao from"chalk";async function Jd(e,t={}){let n=P();if(!n){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}let o=e?[e]:await Fe(n);if(!o.length){r.warn("No previewable blocks to check.");return}let i=Number.parseInt(t.port??"8789",10),a=await Ke(n,t.widths,Number.isFinite(i)?i:8789);r.logoOnce(E("Content check"));let s=0,d=0,l=0;try{for(let c of o){let p=await pe(n,c,t.widths);if(!p)continue;let m=p.breakpoints.reduce((g,w)=>w.width>g.width?w:g,p.breakpoints[0]).width,u=await Wa(`${a.url}${ve.slice(1)}${c}`,m);if(r.info(S(c,`${m}px`)),!u.length){l++,r.info(A("pass","clean","no issues"));continue}for(let g of u)g.level==="error"?s++:d++,r.info(A(g.level==="error"?"fail":"warn",g.rule,g.detail))}}catch(c){r.error(c instanceof Error?c.message:String(c)),process.exitCode=1;return}finally{await a.close()}r.info(""),r.info(`${Ao.green(`${l} clean`)} \xB7 ${Ao.red(`${s} error(s)`)} \xB7 ${Ao.yellow(`${d} warning(s)`)}`),(s>0||t.strict&&d>0)&&(process.exitCode=1)}var Ka=v(()=>{"use strict";f();R();Ja();B();N();De()});function Xa(e){return sn.find(t=>t.id===e)}function Va(e,t){return`
891
933
  // \u2500\u2500 ${e} (eds integrate) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
892
934
  {
893
935
  ${t.split(`
894
936
  `).map(n=>n&&` ${n}`).join(`
895
937
  `)}
896
938
  }
897
- `}var Kt,va=w(()=>{"use strict";m();Kt=[{id:"gtm",name:"Google Tag Manager",fields:[{name:"id",message:"GTM container ID",placeholder:"GTM-XXXXXXX"}],code:()=>`// Google Tag Manager - loaded from ./analytics.js (delayed phase, after LCP).
939
+ `}var sn,Ya=v(()=>{"use strict";f();sn=[{id:"gtm",name:"Google Tag Manager",fields:[{name:"id",message:"GTM container ID",placeholder:"GTM-XXXXXXX"}],code:()=>`// Google Tag Manager - loaded from ./analytics.js (delayed phase, after LCP).
898
940
  import { loadGTM } from './analytics.js';
899
941
  import pageMetaPush from './page-meta.js';
900
942
 
@@ -985,19 +1027,19 @@ document.head.appendChild(cb);`},{id:"custom",name:"Custom third-party script",f
985
1027
  const s = document.createElement('script');
986
1028
  s.async = true;
987
1029
  s.src = ${JSON.stringify(e.url||"")};
988
- document.head.appendChild(s);`}]});var go={};N(go,{integrate:()=>sd});import{existsSync as id}from"fs";import{mkdir as ka,readFile as rd,writeFile as xa}from"fs/promises";import Xt from"path";import fo from"chalk";async function sd(e){let t=E();if(!t){i.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}i.logoOnce(P("Integrate - third-party service"));let{select:n,input:o}=await Promise.resolve().then(()=>(B(),U)),r=e||await n({message:"Which service do you want to add?",choices:Kt.map(p=>({name:p.name,value:p.id}))}),a=wa(r);if(!a){i.error(`Unknown integration "${r}". Options: ${Kt.map(p=>p.id).join(", ")}`),process.exitCode=1;return}let s={};for(let p of a.fields){let f=await o({message:` ${p.message}`,default:p.placeholder});s[p.name]=f.trim()}let d=[];if(a.module)for(let p of a.module(s)){let f=Xt.join(t,p.file);await ka(Xt.dirname(f),{recursive:!0}),await xa(f,p.content),d.push(p.file)}let l=a.module?`
1030
+ document.head.appendChild(s);`}]});var Ro={};L(Ro,{integrate:()=>Vd});import{existsSync as qd}from"fs";import{mkdir as Qa,readFile as Kd,writeFile as Za}from"fs/promises";import cn from"path";import To from"chalk";async function Vd(e){let t=P();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(E("Integrate - third-party service"));let{select:n,input:o}=await Promise.resolve().then(()=>(G(),H)),i=e||await n({message:"Which service do you want to add?",choices:sn.map(m=>({name:m.name,value:m.id}))}),a=Xa(i);if(!a){r.error(`Unknown integration "${i}". Options: ${sn.map(m=>m.id).join(", ")}`),process.exitCode=1;return}let s={};for(let m of a.fields){let u=await o({message:` ${m.message}`,default:m.placeholder});s[m.name]=u.trim()}let d=[];if(a.module)for(let m of a.module(s)){let u=cn.join(t,m.file);await Qa(cn.dirname(u),{recursive:!0}),await Za(u,m.content),d.push(m.file)}let l=a.module?`
989
1031
  // ${a.name} (eds integrate)
990
1032
  ${a.code(s)}
991
- `:ya(a.name,a.code(s)),c=Xt.join(t,"scripts","delayed.js");await ka(Xt.dirname(c),{recursive:!0});let u=id(c)?await rd(c,"utf-8"):ad;await xa(c,`${u.replace(/\s*$/,"")}
992
- ${l}`),i.info(j("Added"));for(let p of d)i.info($(a.name,`wrote ${p}`));i.info($(a.name,"wired into scripts/delayed.js")),i.info(""),i.info(fo.dim(" Loads after LCP (delayed phase) - zero impact on your Core Web Vitals.")),(a.id==="gtm"||a.id==="ga4")&&i.info(fo.dim(" Tip: gate analytics behind user consent (add the Cookiebot integration).")),a.id==="chat"&&i.info(fo.dim(" The widget loads only when the visitor clicks the button (facade pattern).")),i.info(""),i.info(L(["Integration added"]))}var ad,ho=w(()=>{"use strict";m();va();R();z();I();ad=`// delayed.js - third-party / non-critical scripts.
1033
+ `:Va(a.name,a.code(s)),c=cn.join(t,"scripts","delayed.js");await Qa(cn.dirname(c),{recursive:!0});let p=qd(c)?await Kd(c,"utf-8"):Xd;await Za(c,`${p.replace(/\s*$/,"")}
1034
+ ${l}`),r.info(S("Added"));for(let m of d)r.info(j(a.name,`wrote ${m}`));r.info(j(a.name,"wired into scripts/delayed.js")),r.info(""),r.info(To.dim(" Loads after LCP (delayed phase) - zero impact on your Core Web Vitals.")),(a.id==="gtm"||a.id==="ga4")&&r.info(To.dim(" Tip: gate analytics behind user consent (add the Cookiebot integration).")),a.id==="chat"&&r.info(To.dim(" The widget loads only when the visitor clicks the button (facade pattern).")),r.info(""),r.info(O(["Integration added"]))}var Xd,Fo=v(()=>{"use strict";f();Ya();R();B();N();Xd=`// delayed.js - third-party / non-critical scripts.
993
1035
  // Loaded in the EDS delayed phase (after LCP), so nothing here blocks the page.
994
- `});var bo={};N(bo,{figmaSetup:()=>pd});import{existsSync as cd}from"fs";import{mkdir as ld,writeFile as dd}from"fs/promises";import ie from"chalk";async function pd(){let{select:e,confirm:t}=await Promise.resolve().then(()=>(B(),U));i.logoOnce(P()),i.info(j("Figma MCP Setup Wizard")),i.info("Detecting installed AI agents...");let n=await zt(),o;if(n.length===0?(i.warn("No AI agents found (claude, cursor, codex)."),i.info(`Install Claude Code: ${ie.cyan("npm install -g @anthropic-ai/claude-code")}`),o="none"):(i.success(`Found: ${n.map(a=>ie.cyan(a.type)).join(", ")}`),o=await e({message:"Which agent do you want to use with eds-cli?",choices:[...n.map(a=>({name:`${a.type}${a.hasFigmaMcp?ie.green(" (Figma MCP detected)"):""}`,value:a.type})),{name:"None (manual mode)",value:"none"}]})),o!=="none"){let a=n.find(s=>s.type===o);if(a&&!a.hasFigmaMcp){switch(i.warn(`Figma MCP is not configured for ${o}.
995
- `),i.info(`Install it with one of these methods:
996
- `),o){case"claude":i.info(` ${ie.cyan("claude mcp add --transport sse figma-sse https://mcp.figma.com/sse")}`),i.info(" or for Figma Desktop app:"),i.info(` ${ie.cyan("claude mcp add --transport http figma-desktop http://127.0.0.1:3845/mcp")}`);break;case"cursor":i.info(` Add to ${ie.cyan("~/.cursor/mcp.json")}:`),i.info(ie.dim(JSON.stringify({mcpServers:{figma:{url:"https://mcp.figma.com/sse"}}},null,2)));break;case"codex":i.info(" See Figma MCP docs: https://help.figma.com/hc/en-us/articles/32132100833559");break}i.info("")}else a?.hasFigmaMcp&&i.success(`Figma MCP is already configured for ${o}!`)}if(i.info(ie.dim(`
997
- Note: Figma MCP requires a Figma seat (Dev or Full on paid plans for desktop server).`)),await t({message:"Save preferences to ~/.eds/config.json?",default:!0})){let a=Ur();cd(a)||await ld(a,{recursive:!0});let s={};o!=="none"&&(s.agent=o),await dd(oo(),`${JSON.stringify(s,null,2)}
998
- `,{mode:384}),i.success(`Config saved to ${ie.cyan(oo())}`)}i.info(ie.bold(`
999
- Setup complete!`)),o!=="none"&&i.info(`Try: ${ie.cyan('eds block from-design "<figma-url>" --dry-run')}`)}var wo=w(()=>{"use strict";m();Qn();Pe();R();I()});var yo={};N(yo,{doctor:()=>ud});import{existsSync as bt}from"fs";import{readFile as wt,readdir as md}from"fs/promises";import Ce from"path";import{parse as $a}from"yaml";async function ud(e={}){let t=E();if(!t){i.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}let n=si(t);e.json||(i.logoOnce(P("Doctor")),i.info(j("Doctor",t)));let o=[];if(o.push({name:"fstab.yaml exists",status:n.hasFstab?"pass":"warn",message:n.hasFstab?"Found":"Missing - fine for Universal Editor / DA; required for document-mounted setups"}),n.hasFstab)try{let p=await wt(Ce.join(t,"fstab.yaml"),"utf-8");$a(p),o.push({name:"fstab.yaml valid YAML",status:"pass",message:"Valid"})}catch{o.push({name:"fstab.yaml valid YAML",status:"fail",message:"Invalid YAML syntax"})}if(o.push({name:"head.html exists",status:n.hasHeadHtml?"pass":"warn",message:n.hasHeadHtml?"Found":"Missing - recommended for metadata/scripts"}),o.push({name:"blocks/ directory",status:n.hasBlocks?"pass":"warn",message:n.hasBlocks?"Found":"Missing - no blocks yet"}),n.hasBlocks){let p=Ce.join(t,"blocks"),f=await md(p,{withFileTypes:!0}),g="",y=Ce.join(t,"component-models.json");if(bt(y))try{g=await wt(y,"utf-8")}catch{}for(let h of f){if(!h.isDirectory())continue;let b=h.name,S=Ce.join(p,b,`${b}.js`),x=bt(S);o.push({name:`blocks/${b} has JS`,status:x?"pass":"warn",message:x?"Found":`Missing ${b}.js`}),x&&(await wt(S,"utf-8")).includes("console.log")&&o.push({name:`blocks/${b} no console.log`,status:"warn",message:"Found console.log - remove before production"});let T=bt(Ce.join(p,b,`_${b}.json`)),oe=g.includes(`"${b}"`);o.push({name:`blocks/${b} UE model`,status:T||oe?"pass":"warn",message:T||oe?T?`_${b}.json`:"in component-models.json":"no Universal Editor model - authors can't edit this block in UE"});let H=Ce.join(p,b,".eds-meta.json");if(bt(H))try{let q=JSON.parse(await wt(H,"utf-8")),Lo=new Date(q.lastSyncedAt),Te=Math.floor((Date.now()-Lo.getTime())/(1e3*60*60*24));o.push({name:`blocks/${b} Figma sync`,status:Te>30?"warn":"pass",message:Te>30?`Last synced ${Te} days ago - design may have changed`:`Synced ${Te} days ago`})}catch{o.push({name:`blocks/${b} .eds-meta.json`,status:"warn",message:"Invalid metadata file"})}}}let r=Ce.join(t,"helix-query.yaml");if(bt(r))try{let p=await wt(r,"utf-8");$a(p),o.push({name:"helix-query.yaml valid",status:"pass",message:"Valid YAML"})}catch{o.push({name:"helix-query.yaml valid",status:"fail",message:"Invalid YAML syntax"})}o.push({name:"~/.eds/config.json",status:io()?"pass":"warn",message:io()?"Found":'Missing - run "eds figma setup" to configure'});let a=o.filter(p=>p.status==="fail"),s=o.filter(p=>p.status==="warn");if(e.json){let p={pass:o.filter(f=>f.status==="pass").length,warn:s.length,fail:a.length};console.log(JSON.stringify({projectRoot:t,results:o,summary:p},null,2)),a.length>0&&(process.exitCode=1);return}let d=O(o.map(p=>p.name));for(let p of o)i.info(D(p.status,p.name,p.message,d));let l=o.filter(p=>p.status==="fail"),c=o.filter(p=>p.status==="warn"),u=o.filter(p=>p.status==="pass");i.info(""),i.info(L([de({pass:u.length,warn:c.length,fail:l.length})])),l.length>0&&(process.exitCode=1)}var vo=w(()=>{"use strict";m();Pe();R();z();I()});var xo={};N(xo,{auditLoading:()=>gd});import{existsSync as he}from"fs";import{readFile as We,readdir as fd,stat as Sa}from"fs/promises";import be from"path";import ko from"chalk";async function gd(e={}){let t=E();if(!t){i.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}e.json||(i.logoOnce(P("Loading Audit")),i.info(j("Loading Order Audit",t)));let n=[];if(await hd(t,n),await bd(t,n),await wd(t,n),await yd(t,n),await vd(t,n),await kd(t,n),e.json){let o={pass:n.filter(r=>r.status==="pass").length,warn:n.filter(r=>r.status==="warn").length,fail:n.filter(r=>r.status==="fail").length,info:n.filter(r=>r.status==="info").length};console.log(JSON.stringify({projectRoot:t,results:n,summary:o},null,2)),o.fail>0&&(process.exitCode=1);return}$d(n)}async function hd(e,t){let n=be.join(e,"head.html");if(!he(n)){t.push({rule:"head.html exists",status:"warn",message:"Missing head.html"});return}let o=await We(n,"utf-8"),r=o.split(`
1000
- `);for(let l=0;l<r.length;l++){let c=r[l];/<script\b/i.test(c)&&!/type\s*=\s*["']module["']/i.test(c)&&!/<\/script>/.test(c)&&t.push({rule:"No render-blocking scripts in head.html",status:"fail",message:'Script without type="module" blocks rendering',file:"head.html",line:l+1})}let s=(o.match(/<link[^>]+rel=["']stylesheet["'][^>]*>/gi)||[]).filter(l=>!l.includes("styles/styles.css")&&!l.includes("styles.css"));s.length>0&&t.push({rule:"No extra stylesheets in head.html",status:"warn",message:`${s.length} extra stylesheet(s) \u2014 each competes with LCP budget`,file:"head.html"}),/<link[^>]+rel=["'](preload|preconnect)["']/i.test(o)&&t.push({rule:"No preload/preconnect in head.html",status:"warn",message:"preload/preconnect can hurt EDS LCP \u2014 resources compete with the 100KB budget",file:"head.html"}),/<script\b[^>]*>[\s\S]*?[^\s<][\s\S]*?<\/script>/i.test(o)&&t.push({rule:"No inline scripts in head.html",status:"warn",message:"Inline scripts block rendering \u2014 move to delayed.js",file:"head.html"});let d=/(?:src|href)=["'](https?:\/\/(?!(?:localhost|127\.0\.0\.1))[^"']+)["']/gi;for(let l of o.matchAll(d)){let c=l[1];c.includes("fonts.googleapis.com")||t.push({rule:"No third-party resources in head.html",status:"warn",message:`Third-party resource: ${c} \u2014 move to delayed.js`,file:"head.html"})}/<link[^>]+as=["']font["']/i.test(o)&&t.push({rule:"No font preloads in head.html",status:"warn",message:"Font preloads consume LCP bandwidth budget \u2014 let loadFonts() handle them",file:"head.html"}),t.some(l=>l.file==="head.html")||t.push({rule:"head.html is clean",status:"pass",message:"No render-blocking issues found",file:"head.html"})}async function bd(e,t){let n=be.join(e,"scripts","scripts.js");if(!he(n)){t.push({rule:"scripts/scripts.js exists",status:"warn",message:"Missing scripts.js \u2014 cannot audit loading phases"});return}let o=await We(n,"utf-8"),r=o.split(`
1001
- `),a=/function\s+loadEager|loadEager\s*=/i.test(o),s=/function\s+loadLazy|loadLazy\s*=/i.test(o),d=/function\s+loadDelayed|loadDelayed\s*=/i.test(o);t.push({rule:"loadEager phase exists",status:a?"pass":"fail",message:a?"Found":"Missing loadEager \u2014 LCP optimization depends on it",file:"scripts/scripts.js"}),t.push({rule:"loadLazy phase exists",status:s?"pass":"fail",message:s?"Found":"Missing loadLazy \u2014 below-fold content won't load properly",file:"scripts/scripts.js"}),t.push({rule:"loadDelayed phase exists",status:d?"pass":"warn",message:d?"Found":"Missing loadDelayed \u2014 third-party scripts may block LCP",file:"scripts/scripts.js"});let l=o.match(/setTimeout\s*\([^,]+,\s*(\d+)\s*\)/);if(d&&l){let c=Number.parseInt(l[1],10);c<3e3?t.push({rule:"Delayed phase waits >= 3s",status:"warn",message:`delayed.js loads after ${c}ms \u2014 should be >= 3000ms for LCP safety`,file:"scripts/scripts.js"}):t.push({rule:"Delayed phase waits >= 3s",status:"pass",message:`${c}ms delay before loading delayed.js`,file:"scripts/scripts.js"})}if(a){let c=o.match(/loadEager[\s\S]*?(?=function\s|const\s+load|$)/)?.[0]||"";/loadSections\s*\(/.test(c)&&t.push({rule:"loadEager loads only first section",status:"fail",message:"loadEager calls loadSections() \u2014 should only load first section for fast LCP",file:"scripts/scripts.js"})}for(let c=0;c<r.length;c++){let u=r[c];/import\s.*from\s+['"]https?:\/\//i.test(u)&&t.push({rule:"No third-party imports at top level",status:"warn",message:`Third-party import at line ${c+1} \u2014 move to delayed.js if not critical`,file:"scripts/scripts.js",line:c+1})}if(a){let c=xd(o,"loadEager");c&&/loadHeader|loadFooter/.test(c)&&t.push({rule:"Header/footer not in loadEager",status:"warn",message:"Header/footer in loadEager delays LCP \u2014 move to loadLazy",file:"scripts/scripts.js"})}}async function wd(e,t){let n=be.join(e,"styles","styles.css");if(!he(n))return;let r=(await Sa(n)).size/1024;t.push({rule:"styles.css size within LCP budget",status:r>40?"warn":"pass",message:`${r.toFixed(1)} KB${r>40?" \u2014 large CSS competes with 100KB LCP budget":""}`,file:"styles/styles.css"});let a=await We(n,"utf-8");/@import\s/.test(a)&&t.push({rule:"No @import in styles.css",status:"warn",message:"@import creates a request chain \u2014 inline the CSS or use lazy-styles.css",file:"styles/styles.css"})}async function yd(e,t){let n=be.join(e,"scripts","delayed.js");if(!he(n)){t.push({rule:"scripts/delayed.js exists",status:"info",message:"No delayed.js \u2014 third-party scripts should go here"});return}(await We(n,"utf-8")).replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"").trim()||t.push({rule:"delayed.js has content",status:"info",message:"delayed.js is empty \u2014 add analytics/martech here",file:"scripts/delayed.js"})}async function vd(e,t){let n=be.join(e,"blocks");if(!he(n))return;let o=await fd(n,{withFileTypes:!0});for(let r of o){if(!r.isDirectory())continue;let a=r.name,s=be.join(n,a,`${a}.js`);if(!he(s))continue;let d=await We(s,"utf-8"),l=d.split(`
1002
- `),c=["jquery","lodash","moment","rxjs","d3","three","gsap","anime","chart.js","swiper"];for(let f=0;f<l.length;f++){let g=l[f].toLowerCase();for(let y of c)g.includes("from")&&g.includes(y)&&/import\s/.test(g)&&t.push({rule:"No heavy imports in blocks",status:"warn",message:`Imports "${y}" \u2014 heavy library delays section loading`,file:`blocks/${a}/${a}.js`,line:f+1})}/document\.write/i.test(d)&&t.push({rule:"No document.write in blocks",status:"fail",message:"document.write blocks parsing and can break the page",file:`blocks/${a}/${a}.js`});let p=(await Sa(s)).size/1024;p>20&&t.push({rule:"Block JS size reasonable",status:"warn",message:`${p.toFixed(1)} KB \u2014 consider splitting or lazy-loading parts`,file:`blocks/${a}/${a}.js`})}for(let r of o){if(!r.isDirectory())continue;let a=r.name,s=be.join(n,a,`${a}.css`);if(!he(s))continue;let d=await We(s,"utf-8"),l=/^([a-z][a-z0-9-]*)\s*\{/gm;for(let c of d.matchAll(l)){let u=c[1];["body","html","main"].includes(u)||t.push({rule:"Block CSS is scoped",status:"warn",message:`Bare element selector "${u}" \u2014 may leak styles and cause CLS. Use .${a} prefix`,file:`blocks/${a}/${a}.css`})}}}async function kd(e,t){let n=be.join(e,"scripts","aem.js");if(!he(n)){t.push({rule:"scripts/aem.js exists",status:"warn",message:"Missing aem.js (or lib-franklin.js) \u2014 the EDS framework library"});return}t.push({rule:"aem.js present",status:"pass",message:"Found \u2014 remember: never modify this file",file:"scripts/aem.js"})}function xd(e,t){let o=new RegExp(`(?:async\\s+)?function\\s+${t}\\s*\\([^)]*\\)\\s*\\{`).exec(e);if(!o)return null;let r=1,a=o.index+o[0].length,s=a;for(;a<e.length&&r>0;)e[a]==="{"?r++:e[a]==="}"&&r--,a++;return e.slice(s,a-1)}function $d(e){let t=new Map;for(let o of e){let r=o.file||"general",a=t.get(r)??[];a.push(o),t.set(r,a)}for(let[o,r]of t){i.info(` ${J.bullet} ${ko.underline(o)}`);for(let a of r){let s=a.line?ko.dim(`:${a.line}`):"";i.info(` ${vt(a.status)} ${a.rule}${s}`),a.status!=="pass"&&i.info(ko.dim(` ${a.message}`))}i.info("")}let n={pass:e.filter(o=>o.status==="pass").length,warn:e.filter(o=>o.status==="warn").length,fail:e.filter(o=>o.status==="fail").length,info:e.filter(o=>o.status==="info").length};i.info(L([de(n)])),n.fail>0&&(process.exitCode=1)}var $o=w(()=>{"use strict";m();R();z();I()});var jo={};N(jo,{auditSecurity:()=>Dd});import{existsSync as Vt}from"fs";import{readFile as Sd,readdir as jd}from"fs/promises";import Ae from"path";import So from"chalk";async function*Ea(e){let t=await jd(e,{withFileTypes:!0});for(let n of t){let o=Ae.join(e,n.name);if(n.isDirectory()){if(Cd.has(n.name))continue;yield*Ea(o)}else n.isFile()&&(yield o)}}function Td(e,t,n){let o=[],r=e.split(`
1003
- `);for(let a=0;a<r.length;a++){let s=r[a],d=!1;for(let l of Ed)l.ext.includes(n)&&(l.id==="innerhtml-static"&&d||l.re.test(s)&&(l.extra&&!l.extra(s)||(l.id==="innerhtml-dynamic"&&(d=!0),o.push({severity:l.severity,rule:l.id,message:l.message,file:t,line:a+1,snippet:s.trim().slice(0,100)}))))}return o}async function Rd(e){if(!Vt(Ae.join(e,"package.json")))return{status:"skipped",note:"no package.json"};if(!(Vt(Ae.join(e,"package-lock.json"))||Vt(Ae.join(e,"npm-shrinkwrap.json")))&&!Vt(Ae.join(e,"node_modules")))return{status:"skipped",note:"no package-lock.json / node_modules \u2014 run npm install"};try{let{execa:n}=await import("execa"),{stdout:o}=await n("npm",["audit","--json"],{cwd:e,reject:!1}),a=JSON.parse(o)?.metadata?.vulnerabilities??{},s={critical:a.critical??0,high:a.high??0,moderate:a.moderate??0,low:a.low??0};return{status:s.critical+s.high+s.moderate+s.low>0?"vulnerable":"ok",counts:s}}catch(n){return{status:"skipped",note:`npm audit failed: ${n.message}`}}}async function Dd(e={}){let t=E();if(!t){i.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}let n=[];for await(let l of Ea(t)){let c=Ae.extname(l).slice(1).toLowerCase();if(!Ad.has(c))continue;let u=Ae.relative(t,l);if(u.endsWith("aem.js")||u.endsWith("lib-franklin.js"))continue;let p=await Sd(l,"utf-8");n.push(...Td(p,u,c))}let o=await Rd(t),r=l=>n.filter(c=>c.severity===l),a={critical:r("critical").length,high:r("high").length,moderate:r("moderate").length,low:r("low").length},s=a.critical>0||a.high>0||(o.counts?.critical??0)>0||(o.counts?.high??0)>0;if(e.json){console.log(JSON.stringify({projectRoot:t,dependencies:o,findings:n,summary:{code:a}},null,2)),s&&(process.exitCode=1);return}if(i.logoOnce(P("Security Audit")),i.info(j("Dependencies","npm audit")),o.status==="skipped")i.info(D("info","npm audit",o.note??"skipped"));else if(o.status==="ok")i.info(D("pass","npm audit","no known vulnerabilities"));else{let l=o.counts??{critical:0,high:0,moderate:0,low:0};i.info(D(l.critical+l.high>0?"fail":"warn","npm audit",`${l.critical} critical, ${l.high} high, ${l.moderate} moderate, ${l.low} low \u2014 run \`npm audit fix\``))}if(i.info(j("Exploit scan","XSS \xB7 secrets \xB7 injection \xB7 tabnabbing")),n.length===0)i.info(D("pass","code","no risky patterns found"));else{let l=[...n].sort((c,u)=>ja.indexOf(c.severity)-ja.indexOf(u.severity));for(let c of l){let u=Pd[c.severity],p=So.dim(`${c.file}:${c.line}`);i.info(` ${vt(u.status)} ${So.bold(u.label)} ${c.message} ${p}`),i.info(So.dim(` ${c.snippet}`))}}let d=de({fail:a.critical+a.high+(o.counts?.critical??0)+(o.counts?.high??0),warn:a.moderate+(o.counts?.moderate??0),info:a.low+(o.counts?.low??0)});i.info(""),i.info(L([d||`${J.pass} no vulnerabilities or risky patterns found`])),s&&(process.exitCode=1)}var Ed,ja,Pd,Cd,Ad,Eo=w(()=>{"use strict";m();R();z();I();Ed=[{id:"eval",severity:"critical",re:/\beval\s*\(/,message:"eval() executes arbitrary code \u2014 prime XSS / RCE vector",ext:["js","mjs","html"]},{id:"aws-key",severity:"critical",re:/\bAKIA[0-9A-Z]{16}\b/,message:"Hardcoded AWS access key id",ext:["js","mjs","html","json"]},{id:"private-key",severity:"critical",re:/-----BEGIN (?:RSA |EC |OPENSSH |DSA |PGP )?PRIVATE KEY-----/,message:"Embedded private key material",ext:["js","mjs","html","json","pem","txt"]},{id:"new-function",severity:"high",re:/\bnew\s+Function\s*\(/,message:"new Function() runs strings as code",ext:["js","mjs","html"]},{id:"document-write",severity:"high",re:/document\.write(?:ln)?\s*\(/,message:"document.write() enables XSS and blocks parsing",ext:["js","mjs","html"]},{id:"innerhtml-dynamic",severity:"high",re:/\.(?:inner|outer)HTML\s*=\s*[^;\n]*(?:\$\{|\+|concat)/,message:"Dynamic innerHTML assignment \u2014 sanitize or use textContent / DOM APIs",ext:["js","mjs"]},{id:"insert-adjacent-html",severity:"high",re:/insertAdjacentHTML\s*\(/,message:"insertAdjacentHTML with untrusted data is an XSS vector",ext:["js","mjs"]},{id:"js-url",severity:"high",re:/(?:href|src)\s*=\s*["']?\s*javascript:/i,message:"javascript: URL \u2014 XSS vector",ext:["js","mjs","html"]},{id:"secret",severity:"high",re:/(?:api[_-]?key|secret|access[_-]?token|auth[_-]?token|client[_-]?secret|passwd|password)\s*[:=]\s*["'][^"']{8,}["']/i,message:"Possible hardcoded secret / credential",ext:["js","mjs","html","json"],extra:e=>!/(example|placeholder|your[-_]|changeme|xxxx|<[^>]+>|\$\{)/i.test(e)},{id:"bearer-token",severity:"high",re:/Bearer\s+[A-Za-z0-9\-._~+/]{20,}/,message:"Hardcoded bearer token",ext:["js","mjs","html","json"]},{id:"innerhtml-static",severity:"moderate",re:/\.(?:inner|outer)HTML\s*=/,message:"innerHTML assignment \u2014 confirm the content is trusted / sanitized",ext:["js","mjs"]},{id:"insecure-url",severity:"moderate",re:/(?:href|src)\s*=\s*["']http:\/\/(?!localhost|127\.0\.0\.1)/i,message:"Insecure http:// resource \u2014 mixed content, use https://",ext:["html","js","mjs"]},{id:"target-blank",severity:"moderate",re:/target\s*=\s*["']_blank["']/,message:'target="_blank" without rel="noopener" \u2014 reverse tabnabbing',ext:["html","js","mjs"],extra:e=>!/rel\s*=\s*["'][^"']*noopener/i.test(e)},{id:"postmessage-wildcard",severity:"moderate",re:/postMessage\s*\([^,]+,\s*["']\*["']\s*\)/,message:"postMessage to '*' origin \u2014 restrict the target origin",ext:["js","mjs"]},{id:"inline-handler",severity:"low",re:/\son[a-z]+\s*=\s*["']/i,message:"Inline event handler \u2014 move to addEventListener (CSP-unfriendly)",ext:["html"]},{id:"console-log",severity:"low",re:/console\.(?:log|debug)\s*\(/,message:"console.log / debug left in code \u2014 potential info leak",ext:["js","mjs"]}],ja=["critical","high","moderate","low"],Pd={critical:{status:"fail",label:"CRIT"},high:{status:"fail",label:"HIGH"},moderate:{status:"warn",label:"MOD "},low:{status:"info",label:"LOW "}},Cd=new Set(["node_modules",".git","dist","build",".vscode","coverage"]),Ad=new Set(["js","mjs","html","json","pem","txt"])});async function Pa(e,t,n){let o=t.ref||"main",r=n.startsWith("/")?n:`/${n}`,a=`${Fd}/${e}/${t.org}/${t.site}/${o}${r}`;i.debug(`POST ${a}`);let s=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json"}}),d=await s.json().catch(()=>({})),l=d;return s.ok?{ok:!0,status:s.status,path:r,previewUrl:l.preview?.url,liveUrl:l.live?.url}:{ok:!1,status:s.status,path:r,message:d.message||`HTTP ${s.status}`}}async function Po(e,t){return Pa("preview",e,t)}async function Co(e,t){return Pa("live",e,t)}async function Ca(e,t){return Promise.all(t.map(n=>Po(e,n)))}async function Aa(e,t){return Promise.all(t.map(n=>Co(e,n)))}var Fd,Ao=w(()=>{"use strict";m();R();Fd="https://admin.hlx.page"});var To={};N(To,{preview:()=>Od,resolveAdminConfig:()=>Yt});import Ta from"chalk";import Ld from"ora";async function Od(e,t){let n=E(),o=await fe(n),r=Yt(o,t);if(!r)return;let a=Ld(`Previewing ${e.length} path(s)...`).start(),s=e.length===1?[await Po(r,e[0])]:await Ca(r,e);a.stop();let d=!1;for(let l of s)l.ok?i.success(`${l.path} \u2192 ${Ta.cyan(l.previewUrl||"preview updated")}`):(i.error(`${l.path} \u2014 ${l.message}`),d=!0);d&&(process.exitCode=1)}function Yt(e,t){let n=t.org||e.admin?.org,o=t.site||e.admin?.site,r=t.ref||e.admin?.ref||"main";if(!n||!o){i.error("Missing --org and --site. Set them via flags or in .edsrc.json:"),i.info(Ta.dim(' { "admin": { "org": "my-org", "site": "my-site" } }')),process.exitCode=1;return}return{org:n,site:o,ref:r}}var Qt=w(()=>{"use strict";m();Ao();Pe();R();z()});var Ro={};N(Ro,{publish:()=>_d});import Md from"chalk";import Nd from"ora";async function _d(e,t){let n=E(),o=await fe(n),r=Yt(o,t);if(!r)return;let a=Nd(`Publishing ${e.length} path(s)...`).start(),s=e.length===1?[await Co(r,e[0])]:await Aa(r,e);a.stop();let d=!1;for(let l of s)l.ok?i.success(`${l.path} \u2192 ${Md.cyan(l.liveUrl||"published")}`):(i.error(`${l.path} \u2014 ${l.message}`),d=!0);d&&(process.exitCode=1)}var Do=w(()=>{"use strict";m();Ao();Pe();R();z();Qt()});var Zt={};N(Zt,{adminWizard:()=>Id});async function Id(e){let t=E();if(!t){i.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}i.logoOnce(P("Admin API \u2014 preview / publish"));let{select:n,input:o,confirm:r}=await Promise.resolve().then(()=>(B(),U)),s=(await fe(t)).admin??{},d=e??await n({message:"What do you want to do?",choices:[{name:"Preview pages (staging)",value:"preview"},{name:"Publish pages (go live)",value:"publish"}]}),l=(await o({message:"GitHub org / owner",default:s.org})).trim(),c=(await o({message:"Repository / site",default:s.site})).trim(),u=(await o({message:"Git ref",default:s.ref||"main"})).trim(),f=(await o({message:"Paths (space- or comma-separated)",default:"/"})).split(/[\s,]+/).filter(Boolean);if(!l||!c||f.length===0){i.error("org, site and at least one path are required."),process.exitCode=1;return}i.info(j("Summary"));let g=O(["operation","org","site","ref","paths"]);if(i.info($("operation",d,g)),i.info($("org",l,g)),i.info($("site",c,g)),i.info($("ref",u,g)),i.info($("paths",f.join(", "),g)),i.info(""),d==="publish"&&!await r({message:`Publish ${f.length} path(s) to LIVE?`,default:!1})){i.info("Cancelled.");return}let y={org:l,site:c,ref:u};if(d==="preview"){let{preview:h}=await Promise.resolve().then(()=>(Qt(),To));await h(f,y)}else{let{publish:h}=await Promise.resolve().then(()=>(Do(),Ro));await h(f,y)}}var en=w(()=>{"use strict";m();Pe();R();z();I()});var Ra={};N(Ra,{mainMenu:()=>Gd});import{existsSync as Ud}from"fs";import{readdir as Bd}from"fs/promises";import Hd from"path";async function Fo(e){let t=Hd.join(e,"blocks");return Ud(t)?(await Bd(t,{withFileTypes:!0})).filter(o=>o.isDirectory()).map(o=>o.name):[]}async function Gd(){let{select:e,input:t}=await Promise.resolve().then(()=>(B(),U));switch(await i.logoOnceAnimated(""),await e({message:"Choose an action",choices:[{name:"Set up project",value:"init",description:"Authoring model, CI, naming"},{name:"Page template",value:"template",description:"Generate initial content"},{name:"Sandbox repo",value:"sandbox",description:"Disposable GitHub repo"},{name:"Block from design",value:"from-design",description:"Figma / Stitch / Canva / Sketch / Framer"},{name:"Migrate component",value:"migrate",description:"Classic AEM component \u2192 EDS"},{name:"Scaffold UE",value:"scaffold",description:"Universal Editor components"},{name:"Empty block",value:"create",description:"Create a bare block"},{name:"Integration",value:"integrate",description:"GTM, chat, consent\u2026"},{name:"Model fields",value:"model",description:"Add fields to a block model (partials)"},{name:"Analytics",value:"track",description:"Instrument a block (dataLayer)"},{name:"Structured data",value:"schema",description:"Add JSON-LD to a block"},{name:"Universal Editor",value:"ue",description:"Check readiness / open the editor"},{name:"Preview block",value:"preview-block",description:"Live preview in the browser"},{name:"Pages",value:"admin",description:"Preview / publish (Admin API)"},{name:"Audit",value:"audit",description:"Doctor / loading / security"},{name:"Figma MCP",value:"figma-setup",description:"Configure the connection"}]})){case"init":{let{initProject:o}=await Promise.resolve().then(()=>(Mt(),Ot));await o({});return}case"template":{let o=await t({message:"Template name",validate:a=>!!a.trim()||"Required"}),{templateNew:r}=await Promise.resolve().then(()=>(Pn(),En));await r(o.trim(),{});return}case"sandbox":{let o=await t({message:"Sandbox repo name",validate:a=>/^[a-z0-9][a-z0-9._-]*$/i.test(a.trim())||"Use a valid repo name"}),{sandboxNew:r}=await Promise.resolve().then(()=>(Se(),$e));await r(o.trim(),{});return}case"from-design":{let{blockFromDesign:o}=await Promise.resolve().then(()=>(uo(),mo));await o(void 0,{});return}case"migrate":{let{migrateComponent:o}=await Promise.resolve().then(()=>(Fn(),Dn));await o(void 0,{});return}case"scaffold":{let{scaffoldInteractive:o}=await Promise.resolve().then(()=>(re(),ce));await o();return}case"create":{let o=await t({message:"Block name",validate:a=>ye.test(a.trim())||"Use kebab-case, e.g. hero-banner"}),{createBlock:r}=await Promise.resolve().then(()=>(Kn(),qn));await r(o.trim(),{});return}case"integrate":{let{integrate:o}=await Promise.resolve().then(()=>(ho(),go));await o(void 0);return}case"preview-block":{let o=E();if(!o){i.error("Not inside an EDS project (no EDS project markers found).");return}let r=await Fo(o);if(r.length===0){i.warn("No blocks found in blocks/.");return}let a=await e({message:"Which block?",choices:r.map(d=>({name:d,value:d}))}),{previewBlock:s}=await Promise.resolve().then(()=>(gt(),ft));await s(a,{});return}case"model":{let{modelAdd:o}=await Promise.resolve().then(()=>(Hn(),Bn));await o(void 0,[],{});return}case"track":{let o=E();if(!o){i.error("Not inside an EDS project (no EDS project markers found).");return}let r=await Fo(o);if(r.length===0){i.warn("No blocks found in blocks/.");return}let a=await e({message:"Which block to instrument?",choices:r.map(d=>({name:d,value:d}))}),{trackBlock:s}=await Promise.resolve().then(()=>(at(),rt));await s(a,{});return}case"schema":{let o=E();if(!o){i.error("Not inside an EDS project (no EDS project markers found).");return}let r=await Fo(o);if(r.length===0){i.warn("No blocks found in blocks/.");return}let a=await e({message:"Which block?",choices:r.map(d=>({name:d,value:d}))}),{schemaBlock:s}=await Promise.resolve().then(()=>(zn(),Gn));await s(a,{});return}case"ue":{if(await e({message:"Universal Editor:",choices:[{name:"Check readiness (which blocks are editable)",value:"check"},{name:"Open a page in the editor",value:"open"}]})==="check"){let{ueCheck:r}=await Promise.resolve().then(()=>(dt(),lt));await r()}else{let r=await t({message:"Page path",default:"/"}),{ueOpen:a}=await Promise.resolve().then(()=>(dt(),lt));await a(r.trim()||"/",{})}return}case"admin":{let{adminWizard:o}=await Promise.resolve().then(()=>(en(),Zt));await o();return}case"audit":{let o=await e({message:"Which audit?",choices:[{name:"Doctor \u2014 overall project health",value:"doctor"},{name:"Loading \u2014 three-phase / LCP budget",value:"loading"},{name:"Security \u2014 vulnerabilities & exploit patterns",value:"security"}]});if(o==="doctor"){let{doctor:r}=await Promise.resolve().then(()=>(vo(),yo));await r({})}else if(o==="loading"){let{auditLoading:r}=await Promise.resolve().then(()=>($o(),xo));await r({})}else{let{auditSecurity:r}=await Promise.resolve().then(()=>(Eo(),jo));await r({})}return}case"figma-setup":{let{figmaSetup:o}=await Promise.resolve().then(()=>(wo(),bo));await o();return}}}var Da=w(()=>{"use strict";m();R();z();Me()});m();import zd from"chalk";import{Command as Jd}from"commander";var Oo={name:"aem-eds-kit",version:"0.4.26",description:"CLI for AEM Edge Delivery Services with Figma MCP integration",type:"module",engines:{node:">=20"},bin:{eds:"dist/bin/eds.js"},files:["dist","CHANGELOG.md"],scripts:{dev:"tsx src/bin/eds.ts",build:"tsup",test:"vitest run","test:watch":"vitest",lint:"biome check src/ tests/","lint:fix":"biome check --write src/ tests/",typecheck:"tsc --noEmit",prepare:"git config core.hooksPath .githooks || true",prepublishOnly:"npm run build"},keywords:["aem","edge-delivery-services","helix","figma","mcp","cli","adobe"],author:"Piotr Godycki <piotrgodycki@yahoo.com>",license:"MIT",repository:{type:"git",url:"git+https://github.com/piotrgodycki/aem-eds-kit.git"},homepage:"https://piotrgodycki.github.io/aem-eds-kit/",bugs:{url:"https://github.com/piotrgodycki/aem-eds-kit/issues"},dependencies:{"@inquirer/prompts":"^7.0.0",chalk:"^5.4.0",commander:"^13.0.0",execa:"^9.5.0","fast-xml-parser":"^5.11.2",ora:"^8.1.0",yaml:"^2.6.0",zod:"^3.24.0"},devDependencies:{"@biomejs/biome":"^1.9.0","@types/node":"^22.0.0",tsup:"^8.3.0",tsx:"^4.19.0",typescript:"^5.7.0",vitest:"^2.1.0"},optionalDependencies:{"@modelcontextprotocol/sdk":"^1.29.0"}};R();I();var M=new Jd;M.name("eds").description("CLI for AEM Edge Delivery Services with Figma integration").version(Oo.version).option("--verbose","Enable verbose output").option("--quiet","Suppress non-error output").option("--json","Output in JSON format").option("--no-color","Disable color output").showHelpAfterError("(add --help for usage)").hook("preAction",e=>{let t=e.opts();t.verbose&&i.setLevel("debug"),t.quiet&&i.setQuiet(!0),t.color===!1&&(zd.level=0)});M.addHelpText("beforeAll",()=>P());var yt=M.command("sandbox").description("Disposable EDS sandbox repos on GitHub");yt.command("new <name>").description("Create a disposable EDS repo from a boilerplate (GitHub auth, no gh required)").option("--org <org>","Create under a GitHub org (else your account)").option("--boilerplate <repo>","Template repo (default adobe/aem-boilerplate)").option("--ue","Use the crosswalk / Universal Editor boilerplate").option("--private","Create a private repo").option("--yes","Skip the guided prompts (use flags/defaults)").action(async(e,t)=>{let{sandboxNew:n}=await Promise.resolve().then(()=>(Se(),$e));await n(e,t)});yt.command("login").description("Authorize GitHub (OAuth device flow or a token) - no gh needed").action(async()=>{let{sandboxLogin:e}=await Promise.resolve().then(()=>(Se(),$e));await e()});yt.command("logout").description("Remove the stored GitHub token").action(async()=>{let{sandboxLogout:e}=await Promise.resolve().then(()=>(Se(),$e));await e()});yt.command("list").description("List your EDS sandboxes (repos tagged eds-sandbox)").action(async()=>{let{sandboxList:e}=await Promise.resolve().then(()=>(Se(),$e));await e()});yt.command("rm <name>").description("Delete a sandbox repo (destructive)").option("--org <org>","Owner org (else your account)").option("--yes","Skip the confirmation").action(async(e,t)=>{let{sandboxRm:n}=await Promise.resolve().then(()=>(Se(),$e));await n(e,t)});var Wd=M.command("template").description("Generate page templates / initial content");Wd.command("new <name>").description("Generate EDS page initial content (sections + blocks + metadata), DA push optional").option("--path <path>","Content path (default: /templates/<name>)").option("--title <title>","Page title").option("--description <text>","Page description").option("--blocks <list>","Comma-separated block ids to seed",e=>e.split(",").map(t=>t.trim())).option("--area <area>","Site area / template label (stored in metadata)").option("--authoring <model>","Force authoring model: da | gdrive | sharepoint | ue").option("--push","Push the page to DA (da.live)").option("--org <org>","DA org (else from .edsrc.json)").option("--site <site>","DA site (else from .edsrc.json)").option("--yes","Skip prompts").action(async(e,t)=>{let{templateNew:n}=await Promise.resolve().then(()=>(Pn(),En));await n(e,t)});M.command("init").description("Set up a freshly cloned EDS boilerplate for your authoring model (interactive)").option("--name <name>","Project name (kebab-case)").option("--authoring <model>","Authoring model: ue | da | gdrive | sharepoint").option("--mountpoint <url>","Content source URL (document models)").option("--org <org>","DA org (authoring=da)").option("--site <site>","DA site (authoring=da)").option("--no-ci","Skip the GitHub Actions CI workflow").option("--no-env","Skip the local-dev .env (aem up config)").option("--no-xwalk","Skip xwalk.json (UE multi-field)").option("--yes","Skip prompts; apply with flags/defaults").action(async e=>{let{initProject:t}=await Promise.resolve().then(()=>(Mt(),Ot));await t(e)});var qd=M.command("migrate").description("Migrate from classic AEM to EDS");qd.command("component [dir]").description("Migrate a classic AEM component's dialog into an EDS block + UE model").option("--name <name>","Block name (otherwise inferred from the component)").option("--clientlib <dir>","Path to the component's clientlib (otherwise auto-detected)").option("--yes","Skip confirmation prompts").action(async(e,t)=>{let{migrateComponent:n}=await Promise.resolve().then(()=>(Fn(),Dn));await n(e,t)});var Kd=M.command("model").description("Compose Universal Editor models");Kd.command("add <block> [partials...]").description("Add reusable field groups (partials) to a block's UE model").option("--yes","Skip prompts").action(async(e,t,n)=>{let{modelAdd:o}=await Promise.resolve().then(()=>(Hn(),Bn));await o(e,t,n)});var Xd=M.command("schema").description("Structured data (JSON-LD) for blocks");Xd.command("block <name>").description("Inject a JSON-LD (schema.org) builder into a block's decorate()").option("--type <type>","schema.org type (Article, FAQPage, Product, ...)").option("--yes","Skip prompts").action(async(e,t)=>{let{schemaBlock:n}=await Promise.resolve().then(()=>(zn(),Gn));await n(e,t)});var Vd=M.command("track").description("Instrument blocks for analytics");Vd.command("block <name>").description("Add dataLayer tracking (click + form submit) to a block's decorate()").option("--no-click","Skip click tracking").option("--no-submit","Skip form-submit tracking").action(async(e,t)=>{let{trackBlock:n}=await Promise.resolve().then(()=>(at(),rt));await n(e,t)});var Fa=M.command("ue").description("Universal Editor - readiness check + editor deep link");Fa.command("check").description("Check whether blocks are Universal-Editor-ready (offline)").action(async()=>{let{ueCheck:e}=await Promise.resolve().then(()=>(dt(),lt));await e()});Fa.command("open [path]").description("Open a page in the hosted Universal Editor (preview host from git)").option("--org <slug>","IMS org slug (skips the org picker)").option("--ref <branch>","Branch/ref for the preview host (default: main)").option("--url <host>","Override the delivery host (e.g. main--repo--owner.aem.page)").option("--no-open","Print the link without opening the browser").action(async(e,t)=>{let{ueOpen:n}=await Promise.resolve().then(()=>(dt(),lt));await n(e,t)});var tn=M.command("block").description("Manage EDS blocks");tn.command("create <name>").description("Scaffold a new EDS block (with Universal Editor model by default)").option("--no-ue-model","Skip the Universal Editor model (generated by default)").action(async(e,t)=>{let{createBlock:n}=await Promise.resolve().then(()=>(Kn(),qn));await n(e,t)});tn.command("from-design [design]").description("Generate an EDS block from a design: a Figma/Stitch/Canva URL, or a local SVG/PNG export (quota-free, no MCP). Interactive wizard when run with no argument.").option("--name <name>","Override the inferred block name").option("--agent <type>","Force agent type (claude|cursor|codex|none)").option("--dry-run","Generate prompt only, do not invoke agent").option("--source <type>","Content source: document|ue|cf|mixed (default: document)").option("--widths <list>","Design frame widths for preview breakpoints (e.g. 390,768,1440)").option("--no-ue-model","Skip the Universal Editor model (generated by default)").option("--screenshot","Add a screenshot MCP call for pixel verification (opt-in; costs a call)").option("--mcp","Force the Figma MCP adapter even when a REST token is set").option("--refresh","Ignore the cached design snapshot and re-fetch").option("--serve","Auto-start the live preview after generating (non-interactive runs only)").option("--yes","Skip confirmation prompts").action(async(e,t)=>{let{blockFromDesign:n}=await Promise.resolve().then(()=>(uo(),mo));await n(e,t)});tn.command("list").description("List all blocks in the project").action(async e=>{let{listBlocks:t}=await Promise.resolve().then(()=>(ba(),ha));await t({...e,json:M.opts().json})});tn.command("preview [name]").description("Serve a live, breakpoint-switchable preview of a block \u2014 or a gallery of all blocks when no name is given").option("--port <port>","Port to serve on (default: 8777, falls back if taken)").option("--widths <list>","Comma-separated breakpoint widths (e.g. 375,768,1280)").option("--no-open","Do not open the browser automatically").action(async(e,t)=>{let n=await Promise.resolve().then(()=>(gt(),ft));e?await n.previewBlock(e,t):await n.galleryPreview(t)});var qe=M.command("scaffold").description("Scaffold standard UE components and blocks").action(async()=>{let{scaffoldInteractive:e}=await Promise.resolve().then(()=>(re(),ce));await e()});qe.command("ue").description("Scaffold default-content UE components + a field-reference block (all 17 fields)").action(async()=>{let{scaffoldUe:e}=await Promise.resolve().then(()=>(re(),ce));await e()});qe.command("blocks [names...]").description("Scaffold standard blocks (hero, cards, columns, accordion, embed) with UE models").action(async e=>{let{scaffoldBlocks:t}=await Promise.resolve().then(()=>(re(),ce));await t(e)});qe.command("ci").description("Scaffold a GitHub Actions workflow (doctor + audits + project lint/build)").action(async()=>{let{scaffoldCi:e}=await Promise.resolve().then(()=>(re(),ce));await e()});qe.command("helpers [names...]").description("Scaffold scripts/utils.js with chosen EDS helpers (interactive picker)").action(async e=>{let{scaffoldHelpers:t}=await Promise.resolve().then(()=>(re(),ce));await t(e)});qe.command("env").description("Write a local-dev .env for `aem up` (AEM_OPEN / AEM_PORT / AEM_PAGES_URL)").option("--open <path>","AEM_OPEN - path opened on start (default: /)").option("--port <port>","AEM_PORT - proxy port (default: 3007)").option("--pages-url <url>","AEM_PAGES_URL - content origin (default: from git remote)").option("--yes","Skip prompts; use flags/defaults").action(async e=>{let{scaffoldEnv:t}=await Promise.resolve().then(()=>(re(),ce));await t(e)});qe.command("xwalk").description("Write xwalk.json enabling Universal Editor multi-field support").action(async()=>{let{scaffoldXwalk:e}=await Promise.resolve().then(()=>(re(),ce));await e()});M.command("integrate [type]").description("Add a third-party service (GTM, GA4, chat, consent) to scripts/delayed.js").action(async e=>{let{integrate:t}=await Promise.resolve().then(()=>(ho(),go));await t(e)});var Yd=M.command("figma").description("Figma MCP integration");Yd.command("setup").description("Configure Figma MCP for your AI agent").action(async()=>{let{figmaSetup:e}=await Promise.resolve().then(()=>(wo(),bo));await e()});M.command("doctor").description("Audit your EDS project for common issues").action(async()=>{let{doctor:e}=await Promise.resolve().then(()=>(vo(),yo));await e({json:M.opts().json})});var La=M.command("audit").description("Run project audits");La.command("loading").description("Check loading order (eager/lazy/delayed phases, LCP budget)").action(async()=>{let{auditLoading:e}=await Promise.resolve().then(()=>($o(),xo));await e({json:M.opts().json})});La.command("security").description("Scan for vulnerabilities (npm audit) and exploit patterns (XSS, secrets, tabnabbing)").action(async()=>{let{auditSecurity:e}=await Promise.resolve().then(()=>(Eo(),jo));await e({json:M.opts().json})});M.command("preview [paths...]").description("Preview pages via Admin API (interactive wizard when run with no paths)").option("--org <org>","GitHub org/owner").option("--site <site>","Repository name").option("--ref <ref>","Git ref (default: main)").action(async(e,t)=>{if(!e||e.length===0){let{adminWizard:o}=await Promise.resolve().then(()=>(en(),Zt));await o("preview");return}let{preview:n}=await Promise.resolve().then(()=>(Qt(),To));await n(e,t)});M.command("publish [paths...]").description("Publish pages to live via Admin API (interactive wizard when run with no paths)").option("--org <org>","GitHub org/owner").option("--site <site>","Repository name").option("--ref <ref>","Git ref (default: main)").action(async(e,t)=>{if(!e||e.length===0){let{adminWizard:o}=await Promise.resolve().then(()=>(en(),Zt));await o("publish");return}let{publish:n}=await Promise.resolve().then(()=>(Do(),Ro));await n(e,t)});(async()=>{try{if(process.argv.slice(2).length===0)if(process.stdout.isTTY){let{mainMenu:e}=await Promise.resolve().then(()=>(Da(),Ra));await e()}else M.outputHelp();else await M.parseAsync()}catch(e){i.error(e instanceof Error?e.message:String(e)),process.exitCode=1}})();
1036
+ `});var Do={};L(Do,{figmaSetup:()=>ep});import{existsSync as Yd}from"fs";import{mkdir as Qd,writeFile as Zd}from"fs/promises";import re from"chalk";async function ep(){let{select:e,confirm:t}=await Promise.resolve().then(()=>(G(),H));r.logoOnce(E()),r.info(S("Figma MCP Setup Wizard")),r.info("Detecting installed AI agents...");let n=await en(),o;if(n.length===0?(r.warn("No AI agents found (claude, cursor, codex)."),r.info(`Install Claude Code: ${re.cyan("npm install -g @anthropic-ai/claude-code")}`),o="none"):(r.success(`Found: ${n.map(a=>re.cyan(a.type)).join(", ")}`),o=await e({message:"Which agent do you want to use with eds-cli?",choices:[...n.map(a=>({name:`${a.type}${a.hasFigmaMcp?re.green(" (Figma MCP detected)"):""}`,value:a.type})),{name:"None (manual mode)",value:"none"}]})),o!=="none"){let a=n.find(s=>s.type===o);if(a&&!a.hasFigmaMcp){switch(r.warn(`Figma MCP is not configured for ${o}.
1037
+ `),r.info(`Install it with one of these methods:
1038
+ `),o){case"claude":r.info(` ${re.cyan("claude mcp add --transport sse figma-sse https://mcp.figma.com/sse")}`),r.info(" or for Figma Desktop app:"),r.info(` ${re.cyan("claude mcp add --transport http figma-desktop http://127.0.0.1:3845/mcp")}`);break;case"cursor":r.info(` Add to ${re.cyan("~/.cursor/mcp.json")}:`),r.info(re.dim(JSON.stringify({mcpServers:{figma:{url:"https://mcp.figma.com/sse"}}},null,2)));break;case"codex":r.info(" See Figma MCP docs: https://help.figma.com/hc/en-us/articles/32132100833559");break}r.info("")}else a?.hasFigmaMcp&&r.success(`Figma MCP is already configured for ${o}!`)}if(r.info(re.dim(`
1039
+ Note: Figma MCP requires a Figma seat (Dev or Full on paid plans for desktop server).`)),await t({message:"Save preferences to ~/.eds/config.json?",default:!0})){let a=ta();Yd(a)||await Qd(a,{recursive:!0});let s={};o!=="none"&&(s.agent=o),await Zd(go(),`${JSON.stringify(s,null,2)}
1040
+ `,{mode:384}),r.success(`Config saved to ${re.cyan(go())}`)}r.info(re.bold(`
1041
+ Setup complete!`)),o!=="none"&&r.info(`Try: ${re.cyan('eds block from-design "<figma-url>" --dry-run')}`)}var Lo=v(()=>{"use strict";f();lo();be();R();N()});var Oo={};L(Oo,{doctor:()=>np});import{existsSync as Et}from"fs";import{readFile as Ct,readdir as tp}from"fs/promises";import Le from"path";import{parse as es}from"yaml";async function np(e={}){let t=P();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}let n=xi(t);e.json||(r.logoOnce(E("Doctor")),r.info(S("Doctor",t)));let o=[];if(o.push({name:"fstab.yaml exists",status:n.hasFstab?"pass":"warn",message:n.hasFstab?"Found":"Missing - fine for Universal Editor / DA; required for document-mounted setups"}),n.hasFstab)try{let m=await Ct(Le.join(t,"fstab.yaml"),"utf-8");es(m),o.push({name:"fstab.yaml valid YAML",status:"pass",message:"Valid"})}catch{o.push({name:"fstab.yaml valid YAML",status:"fail",message:"Invalid YAML syntax"})}if(o.push({name:"head.html exists",status:n.hasHeadHtml?"pass":"warn",message:n.hasHeadHtml?"Found":"Missing - recommended for metadata/scripts"}),o.push({name:"blocks/ directory",status:n.hasBlocks?"pass":"warn",message:n.hasBlocks?"Found":"Missing - no blocks yet"}),n.hasBlocks){let m=Le.join(t,"blocks"),u=await tp(m,{withFileTypes:!0}),g="",w=Le.join(t,"component-models.json");if(Et(w))try{g=await Ct(w,"utf-8")}catch{}for(let y of u){if(!y.isDirectory())continue;let h=y.name,$=Le.join(m,h,`${h}.js`),b=Et($);o.push({name:`blocks/${h} has JS`,status:b?"pass":"warn",message:b?"Found":`Missing ${h}.js`}),b&&(await Ct($,"utf-8")).includes("console.log")&&o.push({name:`blocks/${h} no console.log`,status:"warn",message:"Found console.log - remove before production"});let T=Et(Le.join(m,h,`_${h}.json`)),Q=g.includes(`"${h}"`);o.push({name:`blocks/${h} UE model`,status:T||Q?"pass":"warn",message:T||Q?T?`_${h}.json`:"in component-models.json":"no Universal Editor model - authors can't edit this block in UE"});let z=Le.join(m,h,".eds-meta.json");if(Et(z))try{let ue=JSON.parse(await Ct(z,"utf-8")),te=new Date(ue.lastSyncedAt),tt=Math.floor((Date.now()-te.getTime())/(1e3*60*60*24));o.push({name:`blocks/${h} Figma sync`,status:tt>30?"warn":"pass",message:tt>30?`Last synced ${tt} days ago - design may have changed`:`Synced ${tt} days ago`})}catch{o.push({name:`blocks/${h} .eds-meta.json`,status:"warn",message:"Invalid metadata file"})}}}let i=Le.join(t,"helix-query.yaml");if(Et(i))try{let m=await Ct(i,"utf-8");es(m),o.push({name:"helix-query.yaml valid",status:"pass",message:"Valid YAML"})}catch{o.push({name:"helix-query.yaml valid",status:"fail",message:"Invalid YAML syntax"})}o.push({name:"~/.eds/config.json",status:ho()?"pass":"warn",message:ho()?"Found":'Missing - run "eds figma setup" to configure'});let a=o.filter(m=>m.status==="fail"),s=o.filter(m=>m.status==="warn");if(e.json){let m={pass:o.filter(u=>u.status==="pass").length,warn:s.length,fail:a.length};console.log(JSON.stringify({projectRoot:t,results:o,summary:m},null,2)),a.length>0&&(process.exitCode=1);return}let d=M(o.map(m=>m.name));for(let m of o)r.info(A(m.status,m.name,m.message,d));let l=o.filter(m=>m.status==="fail"),c=o.filter(m=>m.status==="warn"),p=o.filter(m=>m.status==="pass");r.info(""),r.info(O([fe({pass:p.length,warn:c.length,fail:l.length})])),l.length>0&&(process.exitCode=1)}var No=v(()=>{"use strict";f();be();R();B();N()});var Io={};L(Io,{auditLoading:()=>ip});import{existsSync as ke}from"fs";import{readFile as Qe,readdir as op,stat as ts}from"fs/promises";import xe from"path";import Mo from"chalk";async function ip(e={}){let t=P();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}e.json||(r.logoOnce(E("Loading Audit")),r.info(S("Loading Order Audit",t)));let n=[];if(await rp(t,n),await ap(t,n),await sp(t,n),await cp(t,n),await lp(t,n),await dp(t,n),e.json){let o={pass:n.filter(i=>i.status==="pass").length,warn:n.filter(i=>i.status==="warn").length,fail:n.filter(i=>i.status==="fail").length,info:n.filter(i=>i.status==="info").length};console.log(JSON.stringify({projectRoot:t,results:n,summary:o},null,2)),o.fail>0&&(process.exitCode=1);return}mp(n)}async function rp(e,t){let n=xe.join(e,"head.html");if(!ke(n)){t.push({rule:"head.html exists",status:"warn",message:"Missing head.html"});return}let o=await Qe(n,"utf-8"),i=o.split(`
1042
+ `);for(let l=0;l<i.length;l++){let c=i[l];/<script\b/i.test(c)&&!/type\s*=\s*["']module["']/i.test(c)&&!/<\/script>/.test(c)&&t.push({rule:"No render-blocking scripts in head.html",status:"fail",message:'Script without type="module" blocks rendering',file:"head.html",line:l+1})}let s=(o.match(/<link[^>]+rel=["']stylesheet["'][^>]*>/gi)||[]).filter(l=>!l.includes("styles/styles.css")&&!l.includes("styles.css"));s.length>0&&t.push({rule:"No extra stylesheets in head.html",status:"warn",message:`${s.length} extra stylesheet(s) \u2014 each competes with LCP budget`,file:"head.html"}),/<link[^>]+rel=["'](preload|preconnect)["']/i.test(o)&&t.push({rule:"No preload/preconnect in head.html",status:"warn",message:"preload/preconnect can hurt EDS LCP \u2014 resources compete with the 100KB budget",file:"head.html"}),/<script\b[^>]*>[\s\S]*?[^\s<][\s\S]*?<\/script>/i.test(o)&&t.push({rule:"No inline scripts in head.html",status:"warn",message:"Inline scripts block rendering \u2014 move to delayed.js",file:"head.html"});let d=/(?:src|href)=["'](https?:\/\/(?!(?:localhost|127\.0\.0\.1))[^"']+)["']/gi;for(let l of o.matchAll(d)){let c=l[1];c.includes("fonts.googleapis.com")||t.push({rule:"No third-party resources in head.html",status:"warn",message:`Third-party resource: ${c} \u2014 move to delayed.js`,file:"head.html"})}/<link[^>]+as=["']font["']/i.test(o)&&t.push({rule:"No font preloads in head.html",status:"warn",message:"Font preloads consume LCP bandwidth budget \u2014 let loadFonts() handle them",file:"head.html"}),t.some(l=>l.file==="head.html")||t.push({rule:"head.html is clean",status:"pass",message:"No render-blocking issues found",file:"head.html"})}async function ap(e,t){let n=xe.join(e,"scripts","scripts.js");if(!ke(n)){t.push({rule:"scripts/scripts.js exists",status:"warn",message:"Missing scripts.js \u2014 cannot audit loading phases"});return}let o=await Qe(n,"utf-8"),i=o.split(`
1043
+ `),a=/function\s+loadEager|loadEager\s*=/i.test(o),s=/function\s+loadLazy|loadLazy\s*=/i.test(o),d=/function\s+loadDelayed|loadDelayed\s*=/i.test(o);t.push({rule:"loadEager phase exists",status:a?"pass":"fail",message:a?"Found":"Missing loadEager \u2014 LCP optimization depends on it",file:"scripts/scripts.js"}),t.push({rule:"loadLazy phase exists",status:s?"pass":"fail",message:s?"Found":"Missing loadLazy \u2014 below-fold content won't load properly",file:"scripts/scripts.js"}),t.push({rule:"loadDelayed phase exists",status:d?"pass":"warn",message:d?"Found":"Missing loadDelayed \u2014 third-party scripts may block LCP",file:"scripts/scripts.js"});let l=o.match(/setTimeout\s*\([^,]+,\s*(\d+)\s*\)/);if(d&&l){let c=Number.parseInt(l[1],10);c<3e3?t.push({rule:"Delayed phase waits >= 3s",status:"warn",message:`delayed.js loads after ${c}ms \u2014 should be >= 3000ms for LCP safety`,file:"scripts/scripts.js"}):t.push({rule:"Delayed phase waits >= 3s",status:"pass",message:`${c}ms delay before loading delayed.js`,file:"scripts/scripts.js"})}if(a){let c=o.match(/loadEager[\s\S]*?(?=function\s|const\s+load|$)/)?.[0]||"";/loadSections\s*\(/.test(c)&&t.push({rule:"loadEager loads only first section",status:"fail",message:"loadEager calls loadSections() \u2014 should only load first section for fast LCP",file:"scripts/scripts.js"})}for(let c=0;c<i.length;c++){let p=i[c];/import\s.*from\s+['"]https?:\/\//i.test(p)&&t.push({rule:"No third-party imports at top level",status:"warn",message:`Third-party import at line ${c+1} \u2014 move to delayed.js if not critical`,file:"scripts/scripts.js",line:c+1})}if(a){let c=pp(o,"loadEager");c&&/loadHeader|loadFooter/.test(c)&&t.push({rule:"Header/footer not in loadEager",status:"warn",message:"Header/footer in loadEager delays LCP \u2014 move to loadLazy",file:"scripts/scripts.js"})}}async function sp(e,t){let n=xe.join(e,"styles","styles.css");if(!ke(n))return;let i=(await ts(n)).size/1024;t.push({rule:"styles.css size within LCP budget",status:i>40?"warn":"pass",message:`${i.toFixed(1)} KB${i>40?" \u2014 large CSS competes with 100KB LCP budget":""}`,file:"styles/styles.css"});let a=await Qe(n,"utf-8");/@import\s/.test(a)&&t.push({rule:"No @import in styles.css",status:"warn",message:"@import creates a request chain \u2014 inline the CSS or use lazy-styles.css",file:"styles/styles.css"})}async function cp(e,t){let n=xe.join(e,"scripts","delayed.js");if(!ke(n)){t.push({rule:"scripts/delayed.js exists",status:"info",message:"No delayed.js \u2014 third-party scripts should go here"});return}(await Qe(n,"utf-8")).replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"").trim()||t.push({rule:"delayed.js has content",status:"info",message:"delayed.js is empty \u2014 add analytics/martech here",file:"scripts/delayed.js"})}async function lp(e,t){let n=xe.join(e,"blocks");if(!ke(n))return;let o=await op(n,{withFileTypes:!0});for(let i of o){if(!i.isDirectory())continue;let a=i.name,s=xe.join(n,a,`${a}.js`);if(!ke(s))continue;let d=await Qe(s,"utf-8"),l=d.split(`
1044
+ `),c=["jquery","lodash","moment","rxjs","d3","three","gsap","anime","chart.js","swiper"];for(let u=0;u<l.length;u++){let g=l[u].toLowerCase();for(let w of c)g.includes("from")&&g.includes(w)&&/import\s/.test(g)&&t.push({rule:"No heavy imports in blocks",status:"warn",message:`Imports "${w}" \u2014 heavy library delays section loading`,file:`blocks/${a}/${a}.js`,line:u+1})}/document\.write/i.test(d)&&t.push({rule:"No document.write in blocks",status:"fail",message:"document.write blocks parsing and can break the page",file:`blocks/${a}/${a}.js`});let m=(await ts(s)).size/1024;m>20&&t.push({rule:"Block JS size reasonable",status:"warn",message:`${m.toFixed(1)} KB \u2014 consider splitting or lazy-loading parts`,file:`blocks/${a}/${a}.js`})}for(let i of o){if(!i.isDirectory())continue;let a=i.name,s=xe.join(n,a,`${a}.css`);if(!ke(s))continue;let d=await Qe(s,"utf-8"),l=/^([a-z][a-z0-9-]*)\s*\{/gm;for(let c of d.matchAll(l)){let p=c[1];["body","html","main"].includes(p)||t.push({rule:"Block CSS is scoped",status:"warn",message:`Bare element selector "${p}" \u2014 may leak styles and cause CLS. Use .${a} prefix`,file:`blocks/${a}/${a}.css`})}}}async function dp(e,t){let n=xe.join(e,"scripts","aem.js");if(!ke(n)){t.push({rule:"scripts/aem.js exists",status:"warn",message:"Missing aem.js (or lib-franklin.js) \u2014 the EDS framework library"});return}t.push({rule:"aem.js present",status:"pass",message:"Found \u2014 remember: never modify this file",file:"scripts/aem.js"})}function pp(e,t){let o=new RegExp(`(?:async\\s+)?function\\s+${t}\\s*\\([^)]*\\)\\s*\\{`).exec(e);if(!o)return null;let i=1,a=o.index+o[0].length,s=a;for(;a<e.length&&i>0;)e[a]==="{"?i++:e[a]==="}"&&i--,a++;return e.slice(s,a-1)}function mp(e){let t=new Map;for(let o of e){let i=o.file||"general",a=t.get(i)??[];a.push(o),t.set(i,a)}for(let[o,i]of t){r.info(` ${q.bullet} ${Mo.underline(o)}`);for(let a of i){let s=a.line?Mo.dim(`:${a.line}`):"";r.info(` ${Tt(a.status)} ${a.rule}${s}`),a.status!=="pass"&&r.info(Mo.dim(` ${a.message}`))}r.info("")}let n={pass:e.filter(o=>o.status==="pass").length,warn:e.filter(o=>o.status==="warn").length,fail:e.filter(o=>o.status==="fail").length,info:e.filter(o=>o.status==="info").length};r.info(O([fe(n)])),n.fail>0&&(process.exitCode=1)}var _o=v(()=>{"use strict";f();R();B();N()});var Bo={};L(Bo,{auditSecurity:()=>kp});import{existsSync as ln}from"fs";import{readFile as up,readdir as fp}from"fs/promises";import Oe from"path";import Uo from"chalk";async function*os(e){let t=await fp(e,{withFileTypes:!0});for(let n of t){let o=Oe.join(e,n.name);if(n.isDirectory()){if(wp.has(n.name))continue;yield*os(o)}else n.isFile()&&(yield o)}}function yp(e,t,n){let o=[],i=e.split(`
1045
+ `);for(let a=0;a<i.length;a++){let s=i[a],d=!1;for(let l of gp)l.ext.includes(n)&&(l.id==="innerhtml-static"&&d||l.re.test(s)&&(l.extra&&!l.extra(s)||(l.id==="innerhtml-dynamic"&&(d=!0),o.push({severity:l.severity,rule:l.id,message:l.message,file:t,line:a+1,snippet:s.trim().slice(0,100)}))))}return o}async function vp(e){if(!ln(Oe.join(e,"package.json")))return{status:"skipped",note:"no package.json"};if(!(ln(Oe.join(e,"package-lock.json"))||ln(Oe.join(e,"npm-shrinkwrap.json")))&&!ln(Oe.join(e,"node_modules")))return{status:"skipped",note:"no package-lock.json / node_modules \u2014 run npm install"};try{let{execa:n}=await import("execa"),{stdout:o}=await n("npm",["audit","--json"],{cwd:e,reject:!1}),a=JSON.parse(o)?.metadata?.vulnerabilities??{},s={critical:a.critical??0,high:a.high??0,moderate:a.moderate??0,low:a.low??0};return{status:s.critical+s.high+s.moderate+s.low>0?"vulnerable":"ok",counts:s}}catch(n){return{status:"skipped",note:`npm audit failed: ${n.message}`}}}async function kp(e={}){let t=P();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}let n=[];for await(let l of os(t)){let c=Oe.extname(l).slice(1).toLowerCase();if(!bp.has(c))continue;let p=Oe.relative(t,l);if(p.endsWith("aem.js")||p.endsWith("lib-franklin.js"))continue;let m=await up(l,"utf-8");n.push(...yp(m,p,c))}let o=await vp(t),i=l=>n.filter(c=>c.severity===l),a={critical:i("critical").length,high:i("high").length,moderate:i("moderate").length,low:i("low").length},s=a.critical>0||a.high>0||(o.counts?.critical??0)>0||(o.counts?.high??0)>0;if(e.json){console.log(JSON.stringify({projectRoot:t,dependencies:o,findings:n,summary:{code:a}},null,2)),s&&(process.exitCode=1);return}if(r.logoOnce(E("Security Audit")),r.info(S("Dependencies","npm audit")),o.status==="skipped")r.info(A("info","npm audit",o.note??"skipped"));else if(o.status==="ok")r.info(A("pass","npm audit","no known vulnerabilities"));else{let l=o.counts??{critical:0,high:0,moderate:0,low:0};r.info(A(l.critical+l.high>0?"fail":"warn","npm audit",`${l.critical} critical, ${l.high} high, ${l.moderate} moderate, ${l.low} low \u2014 run \`npm audit fix\``))}if(r.info(S("Exploit scan","XSS \xB7 secrets \xB7 injection \xB7 tabnabbing")),n.length===0)r.info(A("pass","code","no risky patterns found"));else{let l=[...n].sort((c,p)=>ns.indexOf(c.severity)-ns.indexOf(p.severity));for(let c of l){let p=hp[c.severity],m=Uo.dim(`${c.file}:${c.line}`);r.info(` ${Tt(p.status)} ${Uo.bold(p.label)} ${c.message} ${m}`),r.info(Uo.dim(` ${c.snippet}`))}}let d=fe({fail:a.critical+a.high+(o.counts?.critical??0)+(o.counts?.high??0),warn:a.moderate+(o.counts?.moderate??0),info:a.low+(o.counts?.low??0)});r.info(""),r.info(O([d||`${q.pass} no vulnerabilities or risky patterns found`])),s&&(process.exitCode=1)}var gp,ns,hp,wp,bp,Ho=v(()=>{"use strict";f();R();B();N();gp=[{id:"eval",severity:"critical",re:/\beval\s*\(/,message:"eval() executes arbitrary code \u2014 prime XSS / RCE vector",ext:["js","mjs","html"]},{id:"aws-key",severity:"critical",re:/\bAKIA[0-9A-Z]{16}\b/,message:"Hardcoded AWS access key id",ext:["js","mjs","html","json"]},{id:"private-key",severity:"critical",re:/-----BEGIN (?:RSA |EC |OPENSSH |DSA |PGP )?PRIVATE KEY-----/,message:"Embedded private key material",ext:["js","mjs","html","json","pem","txt"]},{id:"new-function",severity:"high",re:/\bnew\s+Function\s*\(/,message:"new Function() runs strings as code",ext:["js","mjs","html"]},{id:"document-write",severity:"high",re:/document\.write(?:ln)?\s*\(/,message:"document.write() enables XSS and blocks parsing",ext:["js","mjs","html"]},{id:"innerhtml-dynamic",severity:"high",re:/\.(?:inner|outer)HTML\s*=\s*[^;\n]*(?:\$\{|\+|concat)/,message:"Dynamic innerHTML assignment \u2014 sanitize or use textContent / DOM APIs",ext:["js","mjs"]},{id:"insert-adjacent-html",severity:"high",re:/insertAdjacentHTML\s*\(/,message:"insertAdjacentHTML with untrusted data is an XSS vector",ext:["js","mjs"]},{id:"js-url",severity:"high",re:/(?:href|src)\s*=\s*["']?\s*javascript:/i,message:"javascript: URL \u2014 XSS vector",ext:["js","mjs","html"]},{id:"secret",severity:"high",re:/(?:api[_-]?key|secret|access[_-]?token|auth[_-]?token|client[_-]?secret|passwd|password)\s*[:=]\s*["'][^"']{8,}["']/i,message:"Possible hardcoded secret / credential",ext:["js","mjs","html","json"],extra:e=>!/(example|placeholder|your[-_]|changeme|xxxx|<[^>]+>|\$\{)/i.test(e)},{id:"bearer-token",severity:"high",re:/Bearer\s+[A-Za-z0-9\-._~+/]{20,}/,message:"Hardcoded bearer token",ext:["js","mjs","html","json"]},{id:"innerhtml-static",severity:"moderate",re:/\.(?:inner|outer)HTML\s*=/,message:"innerHTML assignment \u2014 confirm the content is trusted / sanitized",ext:["js","mjs"]},{id:"insecure-url",severity:"moderate",re:/(?:href|src)\s*=\s*["']http:\/\/(?!localhost|127\.0\.0\.1)/i,message:"Insecure http:// resource \u2014 mixed content, use https://",ext:["html","js","mjs"]},{id:"target-blank",severity:"moderate",re:/target\s*=\s*["']_blank["']/,message:'target="_blank" without rel="noopener" \u2014 reverse tabnabbing',ext:["html","js","mjs"],extra:e=>!/rel\s*=\s*["'][^"']*noopener/i.test(e)},{id:"postmessage-wildcard",severity:"moderate",re:/postMessage\s*\([^,]+,\s*["']\*["']\s*\)/,message:"postMessage to '*' origin \u2014 restrict the target origin",ext:["js","mjs"]},{id:"inline-handler",severity:"low",re:/\son[a-z]+\s*=\s*["']/i,message:"Inline event handler \u2014 move to addEventListener (CSP-unfriendly)",ext:["html"]},{id:"console-log",severity:"low",re:/console\.(?:log|debug)\s*\(/,message:"console.log / debug left in code \u2014 potential info leak",ext:["js","mjs"]}],ns=["critical","high","moderate","low"],hp={critical:{status:"fail",label:"CRIT"},high:{status:"fail",label:"HIGH"},moderate:{status:"warn",label:"MOD "},low:{status:"info",label:"LOW "}},wp=new Set(["node_modules",".git","dist","build",".vscode","coverage"]),bp=new Set(["js","mjs","html","json","pem","txt"])});async function is(e,t,n){let o=t.ref||"main",i=n.startsWith("/")?n:`/${n}`,a=`${xp}/${e}/${t.org}/${t.site}/${o}${i}`;r.debug(`POST ${a}`);let s=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json"}}),d=await s.json().catch(()=>({})),l=d;return s.ok?{ok:!0,status:s.status,path:i,previewUrl:l.preview?.url,liveUrl:l.live?.url}:{ok:!1,status:s.status,path:i,message:d.message||`HTTP ${s.status}`}}async function Go(e,t){return is("preview",e,t)}async function zo(e,t){return is("live",e,t)}async function rs(e,t){return Promise.all(t.map(n=>Go(e,n)))}async function as(e,t){return Promise.all(t.map(n=>zo(e,n)))}var xp,Wo=v(()=>{"use strict";f();R();xp="https://admin.hlx.page"});var Jo={};L(Jo,{preview:()=>Sp,resolveAdminConfig:()=>dn});import ss from"chalk";import $p from"ora";async function Sp(e,t){let n=P(),o=await se(n),i=dn(o,t);if(!i)return;let a=$p(`Previewing ${e.length} path(s)...`).start(),s=e.length===1?[await Go(i,e[0])]:await rs(i,e);a.stop();let d=!1;for(let l of s)l.ok?r.success(`${l.path} \u2192 ${ss.cyan(l.previewUrl||"preview updated")}`):(r.error(`${l.path} \u2014 ${l.message}`),d=!0);d&&(process.exitCode=1)}function dn(e,t){let n=t.org||e.admin?.org,o=t.site||e.admin?.site,i=t.ref||e.admin?.ref||"main";if(!n||!o){r.error("Missing --org and --site. Set them via flags or in .edsrc.json:"),r.info(ss.dim(' { "admin": { "org": "my-org", "site": "my-site" } }')),process.exitCode=1;return}return{org:n,site:o,ref:i}}var pn=v(()=>{"use strict";f();Wo();be();R();B()});var qo={};L(qo,{publish:()=>Ep});import jp from"chalk";import Pp from"ora";async function Ep(e,t){let n=P(),o=await se(n),i=dn(o,t);if(!i)return;let a=Pp(`Publishing ${e.length} path(s)...`).start(),s=e.length===1?[await zo(i,e[0])]:await as(i,e);a.stop();let d=!1;for(let l of s)l.ok?r.success(`${l.path} \u2192 ${jp.cyan(l.liveUrl||"published")}`):(r.error(`${l.path} \u2014 ${l.message}`),d=!0);d&&(process.exitCode=1)}var Ko=v(()=>{"use strict";f();Wo();be();R();B();pn()});var mn={};L(mn,{adminWizard:()=>Cp});async function Cp(e){let t=P();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(E("Admin API \u2014 preview / publish"));let{select:n,input:o,confirm:i}=await Promise.resolve().then(()=>(G(),H)),s=(await se(t)).admin??{},d=e??await n({message:"What do you want to do?",choices:[{name:"Preview pages (staging)",value:"preview"},{name:"Publish pages (go live)",value:"publish"}]}),l=(await o({message:"GitHub org / owner",default:s.org})).trim(),c=(await o({message:"Repository / site",default:s.site})).trim(),p=(await o({message:"Git ref",default:s.ref||"main"})).trim(),u=(await o({message:"Paths (space- or comma-separated)",default:"/"})).split(/[\s,]+/).filter(Boolean);if(!l||!c||u.length===0){r.error("org, site and at least one path are required."),process.exitCode=1;return}r.info(S("Summary"));let g=M(["operation","org","site","ref","paths"]);if(r.info(j("operation",d,g)),r.info(j("org",l,g)),r.info(j("site",c,g)),r.info(j("ref",p,g)),r.info(j("paths",u.join(", "),g)),r.info(""),d==="publish"&&!await i({message:`Publish ${u.length} path(s) to LIVE?`,default:!1})){r.info("Cancelled.");return}let w={org:l,site:c,ref:p};if(d==="preview"){let{preview:y}=await Promise.resolve().then(()=>(pn(),Jo));await y(u,w)}else{let{publish:y}=await Promise.resolve().then(()=>(Ko(),qo));await y(u,w)}}var un=v(()=>{"use strict";f();be();R();B();N()});var cs={};L(cs,{mainMenu:()=>Fp});import{existsSync as Ap}from"fs";import{readdir as Tp}from"fs/promises";import Rp from"path";async function Xo(e){let t=Rp.join(e,"blocks");return Ap(t)?(await Tp(t,{withFileTypes:!0})).filter(o=>o.isDirectory()).map(o=>o.name):[]}async function Fp(){let{select:e,input:t}=await Promise.resolve().then(()=>(G(),H));switch(await r.logoOnceAnimated(""),await e({message:"Choose an action",choices:[{name:"Set up project",value:"init",description:"Authoring model, CI, naming"},{name:"Page template",value:"template",description:"Generate initial content"},{name:"Sandbox repo",value:"sandbox",description:"Disposable GitHub repo"},{name:"Block from design",value:"from-design",description:"Figma, Framer or Google Stitch"},{name:"Migrate component",value:"migrate",description:"Classic AEM component \u2192 EDS"},{name:"Scaffold UE",value:"scaffold",description:"Universal Editor components"},{name:"Empty block",value:"create",description:"Create a bare block"},{name:"Integration",value:"integrate",description:"GTM, chat, consent\u2026"},{name:"Model fields",value:"model",description:"Add fields to a block model (partials)"},{name:"Analytics",value:"track",description:"Instrument a block (dataLayer)"},{name:"Structured data",value:"schema",description:"Add JSON-LD to a block"},{name:"Universal Editor",value:"ue",description:"Check readiness / open the editor"},{name:"Preview block",value:"preview-block",description:"Live preview in the browser"},{name:"Pages",value:"admin",description:"Preview / publish (Admin API)"},{name:"Audit",value:"audit",description:"Doctor / loading / security"},{name:"Figma MCP",value:"figma-setup",description:"Configure the connection"}]})){case"init":{let{initProject:o}=await Promise.resolve().then(()=>(Jt(),Wt));await o({});return}case"template":{let o=await t({message:"Template name",validate:a=>!!a.trim()||"Required"}),{templateNew:i}=await Promise.resolve().then(()=>(In(),Mn));await i(o.trim(),{});return}case"sandbox":{let o=await t({message:"Sandbox repo name",validate:a=>/^[a-z0-9][a-z0-9._-]*$/i.test(a.trim())||"Use a valid repo name"}),{sandboxNew:i}=await Promise.resolve().then(()=>(Ae(),Ce));await i(o.trim(),{});return}case"from-design":{let{blockFromDesign:o}=await Promise.resolve().then(()=>(So(),$o));await o(void 0,{});return}case"migrate":{let{migrateComponent:o}=await Promise.resolve().then(()=>(zn(),Gn));await o(void 0,{});return}case"scaffold":{let{scaffoldInteractive:o}=await Promise.resolve().then(()=>(ae(),le));await o();return}case"create":{let o=await t({message:"Block name",validate:a=>Se.test(a.trim())||"Use kebab-case, e.g. hero-banner"}),{createBlock:i}=await Promise.resolve().then(()=>(ro(),io));await i(o.trim(),{});return}case"integrate":{let{integrate:o}=await Promise.resolve().then(()=>(Fo(),Ro));await o(void 0);return}case"preview-block":{let o=P();if(!o){r.error("Not inside an EDS project (no EDS project markers found).");return}let i=await Xo(o);if(i.length===0){r.warn("No blocks found in blocks/.");return}let a=await e({message:"Which block?",choices:i.map(d=>({name:d,value:d}))}),{previewBlock:s}=await Promise.resolve().then(()=>(De(),$t));await s(a,{});return}case"model":{let{modelAdd:o}=await Promise.resolve().then(()=>(Zn(),Qn));await o(void 0,[],{});return}case"track":{let o=P();if(!o){r.error("Not inside an EDS project (no EDS project markers found).");return}let i=await Xo(o);if(i.length===0){r.warn("No blocks found in blocks/.");return}let a=await e({message:"Which block to instrument?",choices:i.map(d=>({name:d,value:d}))}),{trackBlock:s}=await Promise.resolve().then(()=>(ft(),ut));await s(a,{});return}case"schema":{let o=P();if(!o){r.error("Not inside an EDS project (no EDS project markers found).");return}let i=await Xo(o);if(i.length===0){r.warn("No blocks found in blocks/.");return}let a=await e({message:"Which block?",choices:i.map(d=>({name:d,value:d}))}),{schemaBlock:s}=await Promise.resolve().then(()=>(to(),eo));await s(a,{});return}case"ue":{if(await e({message:"Universal Editor:",choices:[{name:"Check readiness (which blocks are editable)",value:"check"},{name:"Open a page in the editor",value:"open"}]})==="check"){let{ueCheck:i}=await Promise.resolve().then(()=>(bt(),wt));await i()}else{let i=await t({message:"Page path",default:"/"}),{ueOpen:a}=await Promise.resolve().then(()=>(bt(),wt));await a(i.trim()||"/",{})}return}case"admin":{let{adminWizard:o}=await Promise.resolve().then(()=>(un(),mn));await o();return}case"audit":{let o=await e({message:"Which audit?",choices:[{name:"Doctor \u2014 overall project health",value:"doctor"},{name:"Loading \u2014 three-phase / LCP budget",value:"loading"},{name:"Security \u2014 vulnerabilities & exploit patterns",value:"security"}]});if(o==="doctor"){let{doctor:i}=await Promise.resolve().then(()=>(No(),Oo));await i({})}else if(o==="loading"){let{auditLoading:i}=await Promise.resolve().then(()=>(_o(),Io));await i({})}else{let{auditSecurity:i}=await Promise.resolve().then(()=>(Ho(),Bo));await i({})}return}case"figma-setup":{let{figmaSetup:o}=await Promise.resolve().then(()=>(Lo(),Do));await o();return}}}var ls=v(()=>{"use strict";f();R();B();Be()});f();import Dp from"chalk";import{Command as Lp}from"commander";var Vo={name:"aem-eds-kit",version:"0.4.30",description:"CLI for AEM Edge Delivery Services with Figma MCP integration",type:"module",engines:{node:">=20"},bin:{eds:"dist/bin/eds.js"},files:["dist","samples","CHANGELOG.md"],scripts:{dev:"tsx src/bin/eds.ts",build:"tsup",test:"vitest run","test:watch":"vitest",lint:"biome check src/ tests/","lint:fix":"biome check --write src/ tests/",typecheck:"tsc --noEmit",prepare:"git config core.hooksPath .githooks || true",prepublishOnly:"npm run build"},keywords:["aem","edge-delivery-services","helix","figma","mcp","cli","adobe"],author:"Piotr Godycki <piotrgodycki@yahoo.com>",license:"MIT",repository:{type:"git",url:"git+https://github.com/piotrgodycki/aem-eds-kit.git"},homepage:"https://piotrgodycki.github.io/aem-eds-kit/",bugs:{url:"https://github.com/piotrgodycki/aem-eds-kit/issues"},dependencies:{"@inquirer/prompts":"^7.0.0",chalk:"^5.4.0",commander:"^13.0.0",execa:"^9.5.0","fast-xml-parser":"^5.11.2",ora:"^8.1.0",yaml:"^2.6.0",zod:"^3.24.0"},devDependencies:{"@biomejs/biome":"^1.9.0","@types/node":"^22.0.0",tsup:"^8.3.0",tsx:"^4.19.0",typescript:"^5.7.0",vitest:"^2.1.0"},optionalDependencies:{"@modelcontextprotocol/sdk":"^1.29.0",pixelmatch:"^6.0.0",playwright:"^1.48.0",pngjs:"^7.0.0"}};R();N();var I=new Lp;I.name("eds").description("CLI for AEM Edge Delivery Services with Figma integration").version(Vo.version).option("--verbose","Enable verbose output").option("--quiet","Suppress non-error output").option("--json","Output in JSON format").option("--no-color","Disable color output").showHelpAfterError("(add --help for usage)").hook("preAction",e=>{let t=e.opts();t.verbose&&r.setLevel("debug"),t.quiet&&r.setQuiet(!0),t.color===!1&&(Dp.level=0)});I.addHelpText("beforeAll",()=>E());var At=I.command("sandbox").description("Disposable EDS sandbox repos on GitHub");At.command("new <name>").description("Create a disposable EDS repo from a boilerplate (GitHub auth, no gh required)").option("--org <org>","Create under a GitHub org (else your account)").option("--boilerplate <repo>","Template repo (default adobe/aem-boilerplate)").option("--ue","Use the crosswalk / Universal Editor boilerplate").option("--private","Create a private repo").option("--yes","Skip the guided prompts (use flags/defaults)").action(async(e,t)=>{let{sandboxNew:n}=await Promise.resolve().then(()=>(Ae(),Ce));await n(e,t)});At.command("login").description("Authorize GitHub (OAuth device flow or a token) - no gh needed").action(async()=>{let{sandboxLogin:e}=await Promise.resolve().then(()=>(Ae(),Ce));await e()});At.command("logout").description("Remove the stored GitHub token").action(async()=>{let{sandboxLogout:e}=await Promise.resolve().then(()=>(Ae(),Ce));await e()});At.command("list").description("List your EDS sandboxes (repos tagged eds-sandbox)").action(async()=>{let{sandboxList:e}=await Promise.resolve().then(()=>(Ae(),Ce));await e()});At.command("rm <name>").description("Delete a sandbox repo (destructive)").option("--org <org>","Owner org (else your account)").option("--yes","Skip the confirmation").action(async(e,t)=>{let{sandboxRm:n}=await Promise.resolve().then(()=>(Ae(),Ce));await n(e,t)});var Op=I.command("template").description("Generate page templates / initial content");Op.command("new <name>").description("Generate EDS page initial content (sections + blocks + metadata), DA push optional").option("--path <path>","Content path (default: /templates/<name>)").option("--title <title>","Page title").option("--description <text>","Page description").option("--blocks <list>","Comma-separated block ids to seed",e=>e.split(",").map(t=>t.trim())).option("--area <area>","Site area / template label (stored in metadata)").option("--authoring <model>","Force authoring model: da | gdrive | sharepoint | ue").option("--push","Push the page to DA (da.live)").option("--org <org>","DA org (else from .edsrc.json)").option("--site <site>","DA site (else from .edsrc.json)").option("--yes","Skip prompts").action(async(e,t)=>{let{templateNew:n}=await Promise.resolve().then(()=>(In(),Mn));await n(e,t)});I.command("init").description("Set up a freshly cloned EDS boilerplate for your authoring model (interactive)").option("--name <name>","Project name (kebab-case)").option("--authoring <model>","Authoring model: ue | da | gdrive | sharepoint").option("--mountpoint <url>","Content source URL (document models)").option("--org <org>","DA org (authoring=da)").option("--site <site>","DA site (authoring=da)").option("--no-ci","Skip the GitHub Actions CI workflow").option("--no-env","Skip the local-dev .env (aem up config)").option("--no-xwalk","Skip xwalk.json (UE multi-field)").option("--yes","Skip prompts; apply with flags/defaults").action(async e=>{let{initProject:t}=await Promise.resolve().then(()=>(Jt(),Wt));await t(e)});var Np=I.command("migrate").description("Migrate from classic AEM to EDS");Np.command("component [dir]").description("Migrate a classic AEM component's dialog into an EDS block + UE model").option("--name <name>","Block name (otherwise inferred from the component)").option("--clientlib <dir>","Path to the component's clientlib (otherwise auto-detected)").option("--yes","Skip confirmation prompts").action(async(e,t)=>{let{migrateComponent:n}=await Promise.resolve().then(()=>(zn(),Gn));await n(e,t)});var Mp=I.command("model").description("Compose Universal Editor models");Mp.command("add <block> [partials...]").description("Add reusable field groups (partials) to a block's UE model").option("--yes","Skip prompts").action(async(e,t,n)=>{let{modelAdd:o}=await Promise.resolve().then(()=>(Zn(),Qn));await o(e,t,n)});var Ip=I.command("schema").description("Structured data (JSON-LD) for blocks");Ip.command("block <name>").description("Inject a JSON-LD (schema.org) builder into a block's decorate()").option("--type <type>","schema.org type (Article, FAQPage, Product, ...)").option("--yes","Skip prompts").action(async(e,t)=>{let{schemaBlock:n}=await Promise.resolve().then(()=>(to(),eo));await n(e,t)});var _p=I.command("track").description("Instrument blocks for analytics");_p.command("block <name>").description("Add dataLayer tracking (click + form submit) to a block's decorate()").option("--no-click","Skip click tracking").option("--no-submit","Skip form-submit tracking").action(async(e,t)=>{let{trackBlock:n}=await Promise.resolve().then(()=>(ft(),ut));await n(e,t)});var ds=I.command("ue").description("Universal Editor - readiness check + editor deep link");ds.command("check").description("Check whether blocks are Universal-Editor-ready (offline)").action(async()=>{let{ueCheck:e}=await Promise.resolve().then(()=>(bt(),wt));await e()});ds.command("open [path]").description("Open a page in the hosted Universal Editor (preview host from git)").option("--org <slug>","IMS org slug (skips the org picker)").option("--ref <branch>","Branch/ref for the preview host (default: main)").option("--url <host>","Override the delivery host (e.g. main--repo--owner.aem.page)").option("--no-open","Print the link without opening the browser").action(async(e,t)=>{let{ueOpen:n}=await Promise.resolve().then(()=>(bt(),wt));await n(e,t)});var Ze=I.command("block").description("Manage EDS blocks");Ze.command("create <name>").description("Scaffold a new EDS block (with Universal Editor model by default)").option("--no-ue-model","Skip the Universal Editor model (generated by default)").action(async(e,t)=>{let{createBlock:n}=await Promise.resolve().then(()=>(ro(),io));await n(e,t)});Ze.command("from-design [design]").description("Generate an EDS block from a design: a Figma URL, a Framer/Stitch page (scraped with headless Chromium), or a local SVG/PNG export (quota-free, no MCP). Interactive wizard when run with no argument.").option("--name <name>","Override the inferred block name").option("--provider <type>","Design source: figma | framer | stitch (else detected from the URL)").option("--agent <type>","Force agent type (claude|cursor|codex|none)").option("--dry-run","Generate prompt only, do not invoke agent").option("--source <type>","Content source: document|ue|cf|mixed (default: document)").option("--widths <list>","Design frame widths for preview breakpoints (e.g. 390,768,1440)").option("--no-ue-model","Skip the Universal Editor model (generated by default)").option("--screenshot","Add a screenshot MCP call for pixel verification (opt-in; costs a call)").option("--mcp","Force the Figma MCP adapter even when a REST token is set").option("--refresh","Ignore the cached design snapshot and re-fetch").option("--sample","Use the bundled sample design (Kiri Bloom hero) \u2014 no URL, no token, no MCP").option("--serve","Auto-start the live preview after generating (non-interactive runs only)").option("--yes","Skip confirmation prompts").action(async(e,t)=>{let{blockFromDesign:n}=await Promise.resolve().then(()=>(So(),$o));await n(e,t)});Ze.command("list").description("List all blocks in the project").action(async e=>{let{listBlocks:t}=await Promise.resolve().then(()=>(Fa(),Ra));await t({...e,json:I.opts().json})});Ze.command("preview [name]").description("Serve a live, breakpoint-switchable preview of a block \u2014 or a gallery of all blocks when no name is given").option("--port <port>","Port to serve on (default: 8777, falls back if taken)").option("--widths <list>","Comma-separated breakpoint widths (e.g. 375,768,1280)").option("--no-open","Do not open the browser automatically").action(async(e,t)=>{let n=await Promise.resolve().then(()=>(De(),$t));e?await n.previewBlock(e,t):await n.galleryPreview(t)});Ze.command("test [name]").description("Visual-regression test a block (or all blocks) against committed baselines").option("--update","(Re)write the baseline screenshots instead of comparing").option("--threshold <ratio>","Max changed-pixel ratio before failing (default 0.01 = 1%)").option("--design","Compare the rendered block against its Figma design image (needs a token)").option("--widths <list>","Comma-separated breakpoint widths (e.g. 375,768,1280)").option("--port <port>","Port for the internal preview server (default: 8788)").action(async(e,t)=>{let{visualTest:n}=await Promise.resolve().then(()=>(za(),Ga));await n(e,t)});Ze.command("check [name]").description("Content, link and a11y check on a block's rendered DOM (or all blocks)").option("--strict","Fail on warnings too, not just errors").option("--widths <list>","Comma-separated breakpoint widths (uses the widest)").option("--port <port>","Port for the internal preview server (default: 8789)").action(async(e,t)=>{let{blockCheck:n}=await Promise.resolve().then(()=>(Ka(),qa));await n(e,t)});var et=I.command("scaffold").description("Scaffold standard UE components and blocks").action(async()=>{let{scaffoldInteractive:e}=await Promise.resolve().then(()=>(ae(),le));await e()});et.command("ue").description("Scaffold default-content UE components + a field-reference block (all 17 fields)").action(async()=>{let{scaffoldUe:e}=await Promise.resolve().then(()=>(ae(),le));await e()});et.command("blocks [names...]").description("Scaffold standard blocks (hero, cards, columns, accordion, embed) with UE models").action(async e=>{let{scaffoldBlocks:t}=await Promise.resolve().then(()=>(ae(),le));await t(e)});et.command("ci").description("Scaffold a GitHub Actions workflow (doctor + audits + project lint/build)").action(async()=>{let{scaffoldCi:e}=await Promise.resolve().then(()=>(ae(),le));await e()});et.command("helpers [names...]").description("Scaffold scripts/utils.js with chosen EDS helpers (interactive picker)").action(async e=>{let{scaffoldHelpers:t}=await Promise.resolve().then(()=>(ae(),le));await t(e)});et.command("env").description("Write a local-dev .env for `aem up` (AEM_OPEN / AEM_PORT / AEM_PAGES_URL)").option("--open <path>","AEM_OPEN - path opened on start (default: /)").option("--port <port>","AEM_PORT - proxy port (default: 3007)").option("--pages-url <url>","AEM_PAGES_URL - content origin (default: from git remote)").option("--yes","Skip prompts; use flags/defaults").action(async e=>{let{scaffoldEnv:t}=await Promise.resolve().then(()=>(ae(),le));await t(e)});et.command("xwalk").description("Write xwalk.json enabling Universal Editor multi-field support").action(async()=>{let{scaffoldXwalk:e}=await Promise.resolve().then(()=>(ae(),le));await e()});I.command("integrate [type]").description("Add a third-party service (GTM, GA4, chat, consent) to scripts/delayed.js").action(async e=>{let{integrate:t}=await Promise.resolve().then(()=>(Fo(),Ro));await t(e)});var Up=I.command("figma").description("Figma MCP integration");Up.command("setup").description("Configure Figma MCP for your AI agent").action(async()=>{let{figmaSetup:e}=await Promise.resolve().then(()=>(Lo(),Do));await e()});I.command("doctor").description("Audit your EDS project for common issues").action(async()=>{let{doctor:e}=await Promise.resolve().then(()=>(No(),Oo));await e({json:I.opts().json})});var ps=I.command("audit").description("Run project audits");ps.command("loading").description("Check loading order (eager/lazy/delayed phases, LCP budget)").action(async()=>{let{auditLoading:e}=await Promise.resolve().then(()=>(_o(),Io));await e({json:I.opts().json})});ps.command("security").description("Scan for vulnerabilities (npm audit) and exploit patterns (XSS, secrets, tabnabbing)").action(async()=>{let{auditSecurity:e}=await Promise.resolve().then(()=>(Ho(),Bo));await e({json:I.opts().json})});I.command("preview [paths...]").description("Preview pages via Admin API (interactive wizard when run with no paths)").option("--org <org>","GitHub org/owner").option("--site <site>","Repository name").option("--ref <ref>","Git ref (default: main)").action(async(e,t)=>{if(!e||e.length===0){let{adminWizard:o}=await Promise.resolve().then(()=>(un(),mn));await o("preview");return}let{preview:n}=await Promise.resolve().then(()=>(pn(),Jo));await n(e,t)});I.command("publish [paths...]").description("Publish pages to live via Admin API (interactive wizard when run with no paths)").option("--org <org>","GitHub org/owner").option("--site <site>","Repository name").option("--ref <ref>","Git ref (default: main)").action(async(e,t)=>{if(!e||e.length===0){let{adminWizard:o}=await Promise.resolve().then(()=>(un(),mn));await o("publish");return}let{publish:n}=await Promise.resolve().then(()=>(Ko(),qo));await n(e,t)});(async()=>{try{if(process.argv.slice(2).length===0)if(process.stdout.isTTY){let{mainMenu:e}=await Promise.resolve().then(()=>(ls(),cs));await e()}else I.outputHelp();else await I.parseAsync()}catch(e){r.error(e instanceof Error?e.message:String(e)),process.exitCode=1}})();