aem-eds-kit 0.4.30 → 0.4.48

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 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(`
2
+ var ac=Object.defineProperty;var k=(e,t)=>()=>(e&&(t=e(e=0)),t);var O=(e,t)=>{for(var n in t)ac(e,n,{get:t[n],enumerable:!0})};import gu from"path";import{fileURLToPath as wu}from"url";var f=k(()=>{"use strict"});import N from"chalk";function Gt(e){return J[e]}function Ci(e){return e.replace(lc,"").length}function ct(e,t){let n=t-Ci(e);return n>0?e+" ".repeat(n):e}function dc(){return N.bgHex("#ff5a36").hex("#0d0d0c").bold(" >_ ")}function ji(){return`${dc()} ${N.bold("aem-eds-kit")}`}function pc(){return Array.from({length:mc},()=>M.accent("\u25CF")).join(" ")}function uc(e,t=""){return t?`${ji()} ${e} ${N.dim(t)}`:`${ji()} ${e}`}function Pi(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 fc(e,t,n){let[o,i,s]=Pi(e),[a,l,c]=Pi(t),d=Math.round(o+(a-o)*n),m=Math.round(i+(l-i)*n),p=Math.round(s+(c-s)*n);return`#${[d,m,p].map(u=>u.toString(16).padStart(2,"0")).join("")}`}function gc(e,t,n){let o=[...e],i=Math.max(n-1,1);return o.map((s,a)=>{if(s===" ")return s;let l=a/i*(t.length-1),c=Math.min(Math.floor(l),t.length-2);return N.hex(fc(t[c],t[c+1],l-c))(s)}).join("")}function wc(){let e=U(Ei);return Ei.map(t=>` ${gc(t,hc,e)}`).join(`
3
+ `)}function T(e="AEM Edge Delivery Services"){return`
4
+ ${wc()}
5
+
6
+ ${uc(pc(),e)}
7
+ `}function S(e,t){let n=M.red("\u258A"),o=t?` ${N.dim(t)}`:"";return`
8
+ ${n} ${N.bold(e)}${o}
9
+ `}function R(e,t,n,o=0){let i=o?ct(t,o):t,s=n?` ${N.dim(n)}`:"";return` ${J[e]} ${i}${s}`}function j(e,t,n=0){let o=n?ct(e,n):e,i=t?` ${N.dim(t)}`:"";return` ${M.accent("\u2714")} ${o}${i}`}function U(e){return e.reduce((t,n)=>Math.max(t,Ci(n)),0)}function I(e,t=M.red){let n=U(e),o=t(`\u256D${"\u2500".repeat(n+2)}\u256E`),i=t(`\u2570${"\u2500".repeat(n+2)}\u256F`),s=e.map(a=>`${t("\u2502")} ${ct(a,n)} ${t("\u2502")}`).join(`
10
10
  `);return`${o}
11
- ${a}
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
11
+ ${s}
12
+ ${i}`}function be(e){let t=[];return e.pass&&t.push(`${J.pass} ${e.pass} passed`),e.warn&&t.push(`${J.warn} ${e.warn} ${bc(e.warn,"warning")}`),e.fail&&t.push(`${J.fail} ${e.fail} failed`),e.info&&t.push(`${J.info} ${e.info} info`),t.join(N.dim(" "))}function bc(e,t){return e===1?t:`${t}s`}var M,J,lc,mc,Ti,Ei,hc,_=k(()=>{"use strict";f();M={red:N.hex("#FA0F00"),ember:N.hex("#FF4B1F"),orange:N.hex("#FF7B00"),blue:N.hex("#2680EB"),accent:N.hex("#ff5a36"),dotOrange:N.hex("#F24E1E"),dotPurple:N.hex("#A259FF"),dotBlue:N.hex("#1ABCFE"),dotGreen:N.hex("#0ACF83"),dotPink:N.hex("#FF7262"),ok:N.hex("#2D9D78"),warn:N.hex("#E68619"),err:N.hex("#D7373F"),info:N.hex("#2680EB")},J={pass:M.ok("\u2713"),warn:M.warn("\u26A0"),fail:M.err("\u2717"),info:M.info("\u2139"),bullet:N.dim("\u2022"),arrow:N.dim("\u21B3"),figma:M.dotPurple("\u25C6")};lc=/\[[0-9;]*m/g;mc=5;Ti={prefix:"",style:{highlight:e=>N.hex("#ff5a36").bold(e)}};Ei=["\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"],hc=["#ff3b1e","#ff5a36","#ff7d52"]});import Wt from"chalk";function yc(){let e=process.env.EDS_LOG_LEVEL?.toLowerCase();return e&&e in Ln?e:"info"}function Te(e){return Ai?e==="error":Ln[e]>=Ln[Ri]}var Ln,Ri,Ai,zt,r,D=k(()=>{"use strict";f();_();Ln={debug:0,info:1,warn:2,error:3,silent:4};Ri=yc(),Ai=!1,zt=!1;r={setLevel(e){Ri=e},setQuiet(e){Ai=e},debug(...e){Te("debug")&&console.error(Wt.gray("[debug]"),...e)},info(...e){Te("info")&&console.error(...e)},logoOnce(e){zt||(zt=!0,Te("info")&&console.error(e))},async logoOnceAnimated(e){zt||(zt=!0,Te("info")&&console.error(T(e)))},success(...e){Te("info")&&console.error(Wt.green("\u2713"),...e)},warn(...e){Te("warn")&&console.error(Wt.yellow("\u26A0"),...e)},error(...e){Te("error")&&console.error(Wt.red("\u2717"),...e)}}});function We(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 vc(e){return`${Ge}/repos/${e}/generate`}async function Jt(e){let t=await fetch(`${Ge}/user`,{headers:We(e)});if(!t.ok)throw new Error(`GitHub auth failed: ${t.status}`);return(await t.json()).login}async function Fi(e,t,n){let o=await fetch(`${Ge}/repos/${t}/${n}`,{headers:We(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 Di(e,t,n){let o=await fetch(vc(t),{method:"POST",headers:We(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 Li(e,t,n,o){await fetch(`${Ge}/repos/${t}/${n}/topics`,{method:"PUT",headers:We(e),body:JSON.stringify({names:o})})}async function Ni(e,t,n){let o=await fetch(`${Ge}/repos/${t}/${n}`,{method:"DELETE",headers:We(e)});if(!o.ok&&o.status!==204)throw new Error(`delete failed: ${o.status} ${await o.text()}`)}async function Oi(e,t,n){let o=encodeURIComponent(`user:${t} topic:${n} fork:true`),i=await fetch(`${Ge}/search/repositories?q=${o}&per_page=100`,{headers:We(e)});if(!i.ok)throw new Error(`search failed: ${i.status}`);return(await i.json()).items.map(a=>a.full_name)}var Ge,Mi=k(()=>{"use strict";f();Ge="https://api.github.com"});import{existsSync as Ii}from"fs";import{mkdir as kc,readFile as xc,rm as $c,writeFile as Sc}from"fs/promises";import jc from"os";import _i from"path";async function Bi(){let e=process.env.GITHUB_TOKEN||process.env.GH_TOKEN;if(e)return e;if(Ii(lt))try{return JSON.parse(await xc(lt,"utf-8")).token??null}catch{return null}return null}async function Nn(e){await kc(Ui,{recursive:!0,mode:448}),await Sc(lt,`${JSON.stringify({token:e},null,2)}
13
+ `,{mode:384})}async function Hi(){Ii(lt)&&await $c(lt)}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:qt,scope:e.join(" ")})});if(!t.ok)throw new Error(`device code request failed: ${t.status}`);return await t.json()}async function Wi(e,t,n){let o=Math.max(t,1),i=Date.now()+n*1e3;for(;Date.now()<i;){await new Promise(l=>setTimeout(l,o*1e3));let a=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:qt,device_code:e,grant_type:"urn:ietf:params:oauth:grant-type:device_code"})})).json();if(a.access_token)return a.access_token;if(a.error==="slow_down")o+=5;else if(a.error!=="authorization_pending")throw new Error(a.error??"device flow failed")}throw new Error("device flow timed out")}var Ui,lt,qt,zi=k(()=>{"use strict";f();Ui=_i.join(jc.homedir(),".eds"),lt=_i.join(Ui,"github.json"),qt=process.env.EDS_GITHUB_CLIENT_ID??""});function On(e,t,n="main"){return`https://${n}--${t}--${e}.aem.page/`}function Mn(){return"https://github.com/apps/aem-code-sync/installations/new"}function Ji(e,t){return["repo","create",e,"--template",t.template,t.private?"--private":"--public",...t.clone?["--clone"]:[]]}var ze,dt,qi=k(()=>{"use strict";f();ze="eds-sandbox",dt={document:"adobe/aem-boilerplate",ue:"adobe/aem-boilerplate-xwalk"}});var B={};O(B,{checkbox:()=>Oc,confirm:()=>Nc,input:()=>Lc,isEscape:()=>Ac,isExit:()=>Fc,select:()=>Dc});import{emitKeypressEvents as Pc}from"readline";import{checkbox as Ec,confirm as Cc,input as Tc,select as Rc}from"@inquirer/prompts";function Kt(e){let t={...Ti,...e.theme??{}};return{...e,theme:t}}function Vt(e,t){let n=process.stdin;if(!n.isTTY)return e(t??{});let o=new AbortController;t?.signal?.addEventListener("abort",()=>o.abort(),{once:!0}),Pc(n);let i=(a,l)=>{l?.name==="escape"&&o.abort()};n.on("keypress",i);let s=e({...t,signal:o.signal});return Promise.resolve(s).catch(()=>{}).finally(()=>n.off("keypress",i)),s}function Ac(e){return e instanceof Error&&e.name==="AbortPromptError"}function Fc(e){return e instanceof Error&&e.name==="ExitPromptError"}var Dc,Lc,Nc,Oc,H=k(()=>{"use strict";f();_();Dc=(e,t)=>Vt(n=>Rc(Kt(e),n),t),Lc=(e,t)=>Vt(n=>Tc(Kt(e),n),t),Nc=(e,t)=>Vt(n=>Cc(Kt(e),n),t),Oc=(e,t)=>Vt(n=>Ec(Kt(e),n),t)});import{z as F}from"zod";var Uu,In,Ki,Bu,Re,Je=k(()=>{"use strict";f();Uu=F.object({fileKey:F.string().min(1),nodeId:F.string().optional(),fileName:F.string().optional()}),In=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(),restPerMinute:F.number().int().positive().optional()}).optional(),admin:F.object({org:F.string().optional(),site:F.string().optional(),ref:F.string().default("main")}).optional()}),Ki=F.object({root:F.string(),hasFstab:F.boolean(),hasBlocks:F.boolean(),hasHeadHtml:F.boolean()}),Bu=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","scrape","default"]).optional()})).optional()}),Re=/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/});import{existsSync as mt}from"fs";import ye from"path";function E(e=process.cwd()){let t=ye.resolve(e),{root:n}=ye.parse(t);for(;t!==n;){if(Vi.some(o=>mt(ye.join(t,o))))return t;t=ye.dirname(t)}if(Vi.some(o=>mt(ye.join(n,o))))return n}function Xi(e){return Ki.parse({root:e,hasFstab:mt(ye.join(e,"fstab.yaml")),hasBlocks:mt(ye.join(e,"blocks")),hasHeadHtml:mt(ye.join(e,"head.html"))})}var Vi,z=k(()=>{"use strict";f();Je();Vi=["fstab.yaml","head.html","helix-query.yaml","component-definition.json","paths.json","scripts/scripts.js","scripts/aem.js"]});import{existsSync as Mc}from"fs";import{mkdir as Ic,writeFile as _c}from"fs/promises";import Yi from"path";async function Xt(e){let t=Yi.join(e,".github","workflows","eds.yml");return Mc(t)?{path:Qi,created:!1}:(await Ic(Yi.dirname(t),{recursive:!0}),await _c(t,Uc),{path:Qi,created:!0})}var Qi,Uc,_n=k(()=>{"use strict";f();Qi=".github/workflows/eds.yml",Uc=`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 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}
56
+ `});import{existsSync as Zi}from"fs";import{readFile as Bc,writeFile as er}from"fs/promises";import tr from"path";function Hc(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 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(`
59
+ `}async function Gc(e){let t=tr.join(e,".gitignore"),n="";if(Zi(t)&&(n=await Bc(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 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:
61
+ `:"";return await er(t,`${n}${o}.env
62
+ `),!0}async function Yt(e,t={}){let n=tr.join(e,".env"),o=!Zi(n);o&&await er(n,Hc(t));let i=await Gc(e);return{path:".env",created:o,gitignoreUpdated:i}}var Un=k(()=>{"use strict";f()});import{writeFile as nr}from"fs/promises";import or from"path";function Qt(e){return e!=="ue"}function ir(e,t){return`https://content.da.live/${e}/${t}/`}function Wc(e){return`mountpoints:
63
63
  /: ${e}
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
64
+ `}async function rr(e,t){return await nr(or.join(e,"fstab.yaml"),Wc(t)),"fstab.yaml"}function zc(e){return`${JSON.stringify({mappings:[`/content/${e}/:/`],includes:[`/content/${e}/`]},null,2)}
65
+ `}async function sr(e,t){return await nr(or.join(e,"paths.json"),zc(t)),"paths.json"}var Ae,ar=k(()=>{"use strict";f();Ae={ue:"Universal Editor (crosswalk)",da:"Document Authoring (da.live)",gdrive:"Document Authoring (Google Drive)",sharepoint:"Document Authoring (SharePoint)"}});import{existsSync as Jc}from"fs";import{writeFile as qc}from"fs/promises";import Kc from"path";function Xc(){return`${JSON.stringify(Vc,null,2)}
66
+ `}async function Zt(e){let t=Kc.join(e,"xwalk.json");return Jc(t)?{path:"xwalk.json",created:!1}:(await qc(t,Xc()),{path:"xwalk.json",created:!0})}var Vc,Bn=k(()=>{"use strict";f();Vc={public:{xwalk:{"multi-field":{enabled:!0}}}}});function qe(e){let t=e.trim().match(/github\.com[:/]([^/]+)\/(.+?)(?:\.git)?\/?$/i);return t?{owner:t[1],repo:t[2]}:null}function Ke(e,t,n="main"){return`${n}--${t}--${e}.aem.page`}function cr({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 en=k(()=>{"use strict";f()});function pt(e){return`${JSON.stringify(e,null,2)}
67
+ `}function Gn(e){return Fe.find(t=>t.id===e)}var Hn,lr,dr,Fe,Wn=k(()=>{"use strict";f();Hn=(e,t,n)=>({title:e,id:t,plugins:{xwalk:{page:{resourceType:"core/franklin/components/block/v1/block",template:{name:e,model:n}}}}}),lr=(e,t,n)=>({title:e,id:t,plugins:{xwalk:{page:{resourceType:"core/franklin/components/block/v1/block",template:{name:e,filter:n}}}}}),dr=(e,t,n)=>({title:e,id:t,plugins:{xwalk:{page:{resourceType:"core/franklin/components/block/v1/block/item",template:{name:e,model:n}}}}}),Fe=[{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: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
96
+ `,model:pt({definitions:[Hn("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: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
135
+ `,model:pt({definitions:[lr("Cards","cards","cards"),dr("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: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
162
+ `,model:pt({definitions:[Hn("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: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
195
+ `,model:pt({definitions:[lr("Accordion","accordion","accordion"),dr("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: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\`).
224
+ `,model:pt({definitions:[Hn("Embed","embed","embed")],models:[{id:"embed",fields:[{component:"aem-content",name:"link",label:"Embed URL"}]}],filters:[]})}]});import{existsSync as Yc}from"fs";import{mkdir as Qc,writeFile as Zc}from"fs/promises";import mr from"path";function ur(e){return ut.find(t=>t.id===e)}function fr(e){let t=new Set,n=o=>{if(t.has(o))return;let i=ur(o);if(i){for(let s of i.deps??[])n(s);t.add(o)}};for(let o of e)n(o);return ut.filter(o=>t.has(o.id)).map(o=>o.id)}function el(e){return`// scripts/utils.js - common EDS helpers (generated by \`eds scaffold helpers\`).
225
225
 
226
- ${Ui(e).map(o=>_i(o)).filter(o=>!!o).map(o=>o.code).join(`
226
+ ${fr(e).map(o=>ur(o)).filter(o=>!!o).map(o=>o.code).join(`
227
227
 
228
228
  `)}
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:`/**
229
+ `}async function gr(e,t=zn){let n=fr(t),o=mr.join(e,"scripts","utils.js");return Yc(o)?{path:pr,created:!1,helpers:n}:(await Qc(mr.dirname(o),{recursive:!0}),await Zc(o,el(t)),{path:pr,created:!0,helpers:n})}var pr,ut,zn,hr=k(()=>{"use strict";f();pr="scripts/utils.js",ut=[{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
- }`}],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
326
+ }`}],zn=ut.map(e=>e.id)});function tl(){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 Jn(){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:tl()}],filters:[]};return`${JSON.stringify(e,null,2)}
327
+ `}function qn(e,t){let n=new Set(e.map(o=>o.id));return[...e,...t.filter(o=>!n.has(o.id))]}function kr(e,t,n){let o=e?.groups?[...e.groups]:[],i=(s,a,l)=>{let c=o.find(d=>d.id===s);c||(c={id:s,title:a,components:[]},o.push(c)),c.components=qn(c.components,l)};return i("default","Default Content",t),i("blocks","Blocks",n),{groups:o}}function ft(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 wr,br,yr,vr,Kn=k(()=>{"use strict";f();wr=[{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"}}}}}],br=[{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"}]}]}];yr=`// 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,29 +333,29 @@ export default function decorate(block) {
333
333
  // are what you drop and edit.
334
334
  block.classList.add('field-reference');
335
335
  }
336
- `,Ji=`/* Block: field-reference */
336
+ `,vr=`/* 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 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}">
342
+ `});var fe={};O(fe,{scaffoldBlocks:()=>Sr,scaffoldCi:()=>jr,scaffoldEnv:()=>Er,scaffoldHelpers:()=>Pr,scaffoldInteractive:()=>ol,scaffoldUe:()=>on,scaffoldXwalk:()=>Cr});import{existsSync as xr}from"fs";import{mkdir as $r,readFile as nl,writeFile as De}from"fs/promises";import se from"path";async function tn(e){if(!xr(e))return null;try{return JSON.parse(await nl(e,"utf-8"))}catch{return null}}async function nn(e,t){await De(e,`${JSON.stringify(t,null,2)}
343
+ `)}async function on(){let e=E();if(!e){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(T("Scaffold - Universal Editor"));let t=[],n=se.join(e,"blocks","field-reference");await $r(n,{recursive:!0}),await De(se.join(n,"field-reference.js"),yr),await De(se.join(n,"field-reference.css"),vr),await De(se.join(n,"_field-reference.json"),Jn()),t.push("blocks/field-reference/ (all 17 fields + multifield)");let o=se.join(e,"component-definition.json"),i=se.join(e,"component-models.json"),s=se.join(e,"component-filters.json"),a=[{title:"Field Reference",id:"field-reference",plugins:{xwalk:{page:{resourceType:"core/franklin/components/block/v1/block",template:{name:"Field Reference",model:"field-reference"}}}}}],l=kr(await tn(o),wr,a);await nn(o,l),t.push("component-definition.json (default content + field-reference)");let c=await tn(i)??[],d=JSON.parse(Jn()).models[0],m=qn(c,[...br,d]);await nn(i,m),t.push("component-models.json (title / image / button / field-reference)");let p=ft(await tn(s),["field-reference"]);await nn(s,p),t.push("component-filters.json (section filter)"),r.info(S("Created / merged"));let u=t.map(h=>h.split(" ")[0]),g=U(u);for(let h of t){let[b,...y]=h.split(" ");r.info(j(b,y.join(" ").replace(/^\((.*)\)$/,"$1"),g))}r.info(""),r.info(I(["Universal Editor scaffold ready"]))}async function Sr(e){let t=E();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(T("Scaffold \u2014 standard blocks"));let n;if(e?.length){n=e.map(d=>Gn(d.trim())).filter(d=>!!d);let c=e.filter(d=>!Gn(d.trim()));c.length&&r.warn(`Unknown block(s): ${c.join(", ")}. Available: ${Fe.map(d=>d.id).join(", ")}`)}else n=Fe;let o=[],i=[];for(let c of n){let d=se.join(t,"blocks",c.id);if(xr(d)){i.push(c.id);continue}await $r(d,{recursive:!0}),await De(se.join(d,`${c.id}.js`),c.js),await De(se.join(d,`${c.id}.css`),c.css),await De(se.join(d,`_${c.id}.json`),c.model),o.push(c.id)}let s=se.join(t,"component-filters.json"),a=ft(await tn(s),n.map(c=>c.id));await nn(s,a),r.info(S("Blocks"));let l=U([...o,...i,"component-filters"]);for(let c of o)r.info(j(c,"created",l));for(let c of i)r.info(R("warn",c,"already exists \u2014 skipped",l));r.info(""),r.info(I([`${o.length} block(s) scaffolded + registered`]))}async function jr(){let e=E();if(!e){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(T("Scaffold - CI workflow"));let t=await Xt(e);r.info(S("GitHub Actions")),t.created?r.info(j(t.path,"doctor + audit loading + audit security + lint/build")):r.info(R("warn",t.path,"already exists - skipped")),r.info(""),r.info(I([t.created?"CI workflow scaffolded - commit it and it runs on every PR":"CI workflow left untouched"]))}async function Pr(e){let t=E();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(T("Scaffold - helpers"));let n=e?.length?e:void 0;if(!n)if(process.stdout.isTTY){let{checkbox:i}=await Promise.resolve().then(()=>(H(),B));n=await i({message:"Which helpers?",choices:ut.map(s=>({name:s.label,value:s.id,checked:!0}))})}else n=zn;if(!n.length){r.info("Nothing selected.");return}let o=await gr(t,n);r.info(S("Helpers")),o.created?r.info(j(o.path,o.helpers.join(", "))):r.info(R("warn",o.path,"already exists - skipped")),r.info(""),r.info(I([o.created?`${o.helpers.length} helper(s) -> scripts/utils.js`:"Helpers left untouched"]))}async function Er(e={}){let t=E();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(T("Scaffold - .env"));let n=e.pagesUrl;if(n===void 0)try{let{execa:a}=await import("execa"),l=await a("git",["remote","get-url","origin"],{cwd:t}),c=qe(l.stdout.trim());n=c?`https://${Ke(c.owner,c.repo)}`:""}catch{n=""}let o=e.open??"/",i=e.port??"3007";if(!e.yes&&process.stdout.isTTY){let{input:a}=await Promise.resolve().then(()=>(H(),B));o=await a({message:"AEM_OPEN (path opened on start)",default:o}),i=await a({message:"AEM_PORT",default:String(i)}),n=await a({message:"AEM_PAGES_URL (content origin)",default:n})}let s=await Yt(t,{open:o,port:i,pagesUrl:n});r.info(S(".env")),s.created?r.info(j(s.path,`AEM_OPEN=${o} AEM_PORT=${i}`)):r.info(R("warn",s.path,"already exists - left untouched")),s.gitignoreUpdated&&r.info(j(".gitignore","added .env")),r.info(""),r.info(I([s.created?".env ready for `aem up`":".env left untouched"]))}async function Cr(){let e=E();if(!e){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(T("Scaffold - xwalk.json"));let t=await Zt(e);r.info(S("xwalk.json")),t.created?r.info(j(t.path,"multi-field enabled")):r.info(R("warn",t.path,"already exists - left untouched")),r.info(""),r.info(I([t.created?"xwalk.json ready (UE multi-field)":"xwalk.json left untouched"]))}async function ol(){let{select:e,checkbox:t}=await Promise.resolve().then(()=>(H(),B));r.logoOnce(T("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 Er();if(n==="xwalk")return Cr();if((n==="ue"||n==="both")&&await on(),n==="blocks"||n==="both"){let o=await t({message:"Which blocks?",choices:Fe.map(i=>({name:i.title,value:i.id,checked:!0}))});await Sr(o)}n==="ci"&&await jr(),n==="helpers"&&await Pr()}var me=k(()=>{"use strict";f();D();z();Wn();_n();Un();hr();Kn();Bn();en();_()});var sn={};O(sn,{initProject:()=>cl});import{existsSync as Xn}from"fs";import{readFile as Yn,writeFile as Tr}from"fs/promises";import rn from"path";import Vn from"chalk";async function il(e){try{let{execa:t}=await import("execa"),n=await t("git",["remote","get-url","origin"],{cwd:e}),o=qe(n.stdout.trim());return o?`https://${Ke(o.owner,o.repo)}`:""}catch{return""}}async function rl(e,t){let n=rn.join(e,"package.json");if(!Xn(n))return!1;try{let o=JSON.parse(await Yn(n,"utf-8"));return o.name=t,await Tr(n,`${JSON.stringify(o,null,2)}
344
+ `),!0}catch{return!1}}async function sl(e,t){let n=[];for(let o of["README.md","index.html","head.html"]){let i=rn.join(e,o);if(Xn(i))try{let s=await Yn(i,"utf-8"),a=s.replace(/aem-boilerplate/gi,t);a!==s&&(await Tr(i,a),n.push(o))}catch{}}return n}async function al(e){let{confirm:t}=await Promise.resolve().then(()=>(H(),B)),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(` ${M.accent(String(o+1))} ${Vn.bold(i.title)}`),i.url&&r.info(` ${Vn.cyan(i.url)}`),r.info(` ${Vn.dim(i.note)}`),await t({message:" Done / skip?",default:!0})}}async function cl(e={}){let t=E();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(()=>(H(),B)),s=!e.yes,a=rn.basename(t),l=rn.join(t,"package.json");if(Xn(l))try{a=JSON.parse(await Yn(l,"utf-8")).name||a}catch{}let c=e.name&&gt(e.name)||gt(await n({message:"1/4 Project name",default:gt(a),validate:b=>!!gt(b)||"Use letters, numbers and dashes"})),d=e.authoring??await o({message:"2/4 Authoring model",choices:[{name:Ae.ue,value:"ue"},{name:Ae.da,value:"da"},{name:Ae.gdrive,value:"gdrive"},{name:Ae.sharepoint,value:"sharepoint"}]}),m=e.mountpoint;if(Qt(d)&&!m)if(d==="da"&&(e.org||s)){let b=e.org??await n({message:" DA org",validate:v=>!!v.trim()||"Required"}),y=e.site??(s?await n({message:" DA site",default:c}):c);m=ir(b.trim(),gt(y))}else d!=="da"&&s&&(m=(await n({message:` ${d==="gdrive"?"Google Drive folder URL":"SharePoint folder URL"}`,validate:y=>/^https?:\/\//.test(y.trim())||"Paste the folder URL"})).trim());let p=e.ci??(s?await i({message:"4/4 Add GitHub Actions CI (audits gatekeeper)?",default:!0}):!0);r.info(S("Summary"));let u=U(["name","authoring","mountpoint","ci"]);if(r.info(j("name",c,u)),r.info(j("authoring",Ae[d],u)),m?r.info(j("mountpoint",m,u)):Qt(d)&&r.info(j("mountpoint","(skipped - set it in fstab.yaml later)",u)),r.info(j("ci",p?"yes":"no",u)),r.info(""),s&&!await i({message:"Apply this setup?",default:!0})){r.info("Cancelled.");return}let g=[];await rl(t,c)&&g.push("package.json (name)");for(let b of await sl(t,c))g.push(`${b} (renamed)`);if(Qt(d)&&m&&g.push(await rr(t,m)),d==="ue"&&(await on(),g.push(await sr(t,c))),p){let b=await Xt(t);g.push(b.created?b.path:`${b.path} (exists, skipped)`)}if(e.env!==!1){let b=await Yt(t,{pagesUrl:await il(t)});g.push(b.created?".env (aem up config)":".env (exists, skipped)")}if(e.xwalk!==!1&&d==="ue"){let b=await Zt(t);g.push(b.created?`${b.path} (UE multi-field)`:`${b.path} (exists, skipped)`)}r.info(S("Configured"));let h=U(g.map(b=>b.split(" ")[0]));for(let b of g){let[y,...v]=b.split(" ");r.info(j(y,v.join(" ").replace(/^\((.*)\)$/,"$1"),h))}r.info(""),s&&await al(d),r.info(I([`"${c}" set up for ${Ae[d]}`]))}var gt,an=k(()=>{"use strict";f();D();z();_n();Un();ar();Bn();en();_();me();gt=e=>e.trim().toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"")});var Le={};O(Le,{sandboxList:()=>gl,sandboxLogin:()=>pl,sandboxLogout:()=>ul,sandboxNew:()=>fl,sandboxRm:()=>hl});import ll from"path";import oe from"chalk";async function ge(e,t,n={}){let{execa:o}=await import("execa");return((await o(e,t,n)).stdout??"").toString().trim()}async function Qn(e){let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{await ge(t,[e],{stdio:"ignore"})}catch{}}async function dl(){try{return await ge("gh",["auth","status"]),await ge("gh",["api","user","-q",".login"])}catch{return null}}async function Zn(){let e=await Bi();if(e)try{return{mode:"api",token:e,login:await Jt(e)}}catch{}let t=await dl();return t?{mode:"gh",login:t}:null}async function ml(e,t,n){if(e.mode==="api")return Fi(e.token,t,n);try{return await ge("gh",["repo","view",`${t}/${n}`,"--json","name"]),!0}catch{return!1}}function eo(){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 pl(){await r.logoOnceAnimated("Sandbox - GitHub login");let{input:e}=await Promise.resolve().then(()=>(H(),B));if(qt){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 Qn(n.verification_uri),r.info(oe.dim(" Waiting for you to authorize in the browser..."));try{let o=await Wi(n.device_code,n.interval,n.expires_in);await Nn(o),r.success(`Authorized as ${await Jt(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(` ${oe.cyan("https://github.com/settings/personal-access-tokens/new")}`),r.info(oe.dim(" - Resource owner: a dedicated sandbox org (recommended) or your account")),r.info(oe.dim(" - Repository access: All repositories in that org (to create new sandboxes),")),r.info(oe.dim(" or Only select repositories to manage existing ones")),r.info(oe.dim(" - Permissions: Administration = Read and write, Contents = Read and write,")),r.info(oe.dim(" Metadata = Read. Set a short expiry.")),r.info(oe.dim(" Tip: `eds sandbox new --org <sandbox-org>` so nothing in your personal account is touched.")),r.info(""),await(await Promise.resolve().then(()=>(H(),B))).confirm({message:"Open the token page?",default:!0})&&await Qn("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 Jt(t);await Nn(t),r.success(`Authorized as ${n}.`)}catch{r.error("That token didn't work (check the scopes)."),process.exitCode=1}}async function ul(){await Hi(),r.success("Signed out (stored GitHub token removed).")}async function fl(e,t={}){let n=await Zn();if(!n)return eo();await r.logoOnceAnimated("Sandbox");let o=!t.yes,{select:i,confirm:s}=await Promise.resolve().then(()=>(H(),B)),a=t.boilerplate;a||(t.ue?a=dt.ue:o?a=await i({message:"Which boilerplate?",choices:[{name:"Document Authoring (adobe/aem-boilerplate)",value:dt.document},{name:"Universal Editor / crosswalk (adobe/aem-boilerplate-xwalk)",value:dt.ue}]}):a=dt.document);let l=t.private??!1;t.private===void 0&&o&&(l=await i({message:"Visibility?",choices:[{name:"Public",value:!1},{name:"Private",value:!0}],default:!1}));let c=t.org??n.login;if(await ml(n,c,e)){r.error(`A repository ${c}/${e} already exists - refusing to touch it.`),r.info(oe.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",`${c}/${e} \xB7 ${a}`));try{if(n.mode==="api"){let d=await Di(n.token,a,{owner:c,name:e,private:l});await Li(n.token,c,e,[ze]),r.info(oe.dim(" Cloning...")),await ge("git",["clone",d.cloneUrl,e],{stdio:"inherit"})}else{let d=t.org?`${t.org}/${e}`:e;await ge("gh",Ji(d,{template:a,private:l,clone:!0}),{stdio:"inherit"});try{await ge("gh",["repo","edit",`${c}/${e}`,"--add-topic",ze])}catch{}}}catch(d){r.error(`Create failed: ${d.message}`),process.exitCode=1;return}if(r.info(""),r.info(S("Sandbox ready")),r.info(j("repo",`https://github.com/${c}/${e}`)),r.info(j("preview",On(c,e))),r.info(""),o){if(await s({message:"Open the AEM Code Sync install page now?",default:!0})&&await Qn(Mn()),await s({message:`Configure authoring now (eds init in ./${e})?`,default:!0})){let d=process.cwd();try{process.chdir(ll.join(d,e));let{initProject:m}=await Promise.resolve().then(()=>(an(),sn));await m({})}finally{process.chdir(d)}}}else r.info(oe.dim(` Install AEM Code Sync: ${Mn()}`)),r.info(oe.dim(` Configure authoring: cd ${e} && eds init`));r.info(""),r.info(I([`Sandbox "${e}" ready - tear down with \`eds sandbox rm ${e}\``]))}async function gl(){let e=await Zn();if(!e)return eo();let t=[];try{if(e.mode==="api")t=await Oi(e.token,e.login,ze);else{let o=await ge("gh",["repo","list","--topic",ze,"--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 ${ze}`)),t.length===0){r.info(oe.dim(" None yet. Create one with `eds sandbox new <name>`."));return}let n=U(t);for(let o of t){let[i,s]=o.split("/");r.info(j(o,On(i,s),n))}}async function hl(e,t={}){let n=await Zn();if(!n)return eo();let o=t.org??n.login,i=`${o}/${e}`;if(!t.yes){let{confirm:s}=await Promise.resolve().then(()=>(H(),B));if(!await s({message:`Permanently delete ${i}? This cannot be undone.`,default:!1})){r.info("Cancelled.");return}}try{n.mode==="api"?await Ni(n.token,o,e):await ge("gh",["repo","delete",i,"--yes"])}catch(s){r.error(`Delete failed: ${s.message}`),r.info(oe.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 Ne=k(()=>{"use strict";f();D();Mi();zi();qi();_()});import{existsSync as wl}from"fs";import{readFile as bl}from"fs/promises";import yl from"path";import{parse as vl}from"yaml";async function Rr(e){let t=yl.join(e,"fstab.yaml");if(wl(t))try{let o=(vl(await bl(t,"utf-8"))??{}).mountpoints?.["/"],i=typeof o=="string"?o:o?.url??"",s=i.match(/content\.da\.live\/([^/]+)\/([^/]+)/);return s?{model:"da",org:s[1],site:s[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 Ar=k(()=>{"use strict";f()});function kl(e,t,n){let o=n.replace(/^\/+/,"").replace(/\.html$/i,"");return`https://admin.da.live/source/${e}/${t}/${o}.html`}function Fr(e,t,n){let o=n.replace(/^\/+/,"").replace(/\.html$/i,"");return`https://da.live/edit#/${e}/${t}/${o}`}async function Dr(e,t,n,o,i){let s=kl(e,t,n),a=new FormData;a.append("data",new Blob([o],{type:"text/html"}),"content.html");let l={};i&&(l.Authorization=`Bearer ${i}`);let c=await fetch(s,{method:"POST",body:a,headers:l});if(!c.ok)throw new Error(`DA push failed: ${c.status} ${c.statusText}`);return s}var Lr=k(()=>{"use strict";f()});function xl(e){return` <div class="${e}">
346
346
  <div>
347
347
  <div>${e} content</div>
348
348
  </div>
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">
349
+ </div>`}function $l(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 sr(e){let t=e.blocks??[],n=` <div>
352
+ </div>`}function Nr(e){let t=e.blocks??[],n=` <div>
353
353
  <h1>${e.title}</h1>
354
354
  <p>${e.description??"Intro copy goes here."}</p>
355
- </div>`,o=t.map(a=>` <div>
356
- ${Cc(a)}
355
+ </div>`,o=t.map(s=>` <div>
356
+ ${xl(s)}
357
357
  </div>`),i=` <div>
358
- ${Ac(e)}
358
+ ${$l(e)}
359
359
  </div>`;return`<body>
360
360
  <header></header>
361
361
  <main>
@@ -364,13 +364,13 @@ ${[n,...o,i].join(`
364
364
  </main>
365
365
  <footer></footer>
366
366
  </body>
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(`
367
+ `}var Or=k(()=>{"use strict";f()});import{existsSync as Sl}from"fs";import{readFile as jl}from"fs/promises";import Pl from"path";function El(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 Cl(e,t){let n=Pl.join(e,"blocks",t,`_${t}.json`);if(!Sl(n))return{};try{let o=JSON.parse(await jl(n,"utf-8")),i=Array.isArray(o.models)?o.models:[],a=(i.find(c=>c.id===t)??i[0])?.fields??[],l={};for(let c of a)c.component!=="tab"&&(l[c.name]=c.component==="container"?[]:El(c));return l}catch{return{}}}async function Mr(e,t){let n=[];for(let i of t.blocks)n.push({name:i,model:i,fields:await Cl(e,i)});let o={title:t.title,template:t.name,components:n};return`${JSON.stringify(o,null,2)}
368
+ `}var Ir=k(()=>{"use strict";f()});var oo={};O(oo,{templateNew:()=>Nl});import{existsSync as no}from"fs";import{mkdir as Tl,readFile as _r,readdir as Rl,writeFile as to}from"fs/promises";import ve from"path";import ht from"chalk";async function Fl(e){let t=ve.join(e,"blocks");return no(t)?(await Rl(t,{withFileTypes:!0})).filter(n=>n.isDirectory()).map(n=>n.name):[]}async function Dl(e){let t=ve.join(e,".edsrc.json");if(!no(t))return{};try{return JSON.parse(await _r(t,"utf-8")).admin??{}}catch{return{}}}async function Ll(e,t){if(!t.length)return!1;let n=ve.join(e,"component-filters.json"),o=null;if(no(n))try{o=JSON.parse(await _r(n,"utf-8"))}catch{o=null}let i=ft(o,t);return await to(n,`${JSON.stringify(i,null,2)}
369
+ `),!0}async function Nl(e,t={}){let n=E();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:s}=await Promise.resolve().then(()=>(H(),B)),a=!t.yes,l=await Rr(n),c=t.authoring??l.model,d=Al(e),m=t.title??(a?await o({message:"Page title",default:e}):e),p=t.description??(a?await o({message:"Description (optional)"}):""),u=t.path??`/templates/${d}`,g=t.blocks;if(!g&&a){let v=await Fl(n),w=v.length?v:Fe.map(K=>K.id),A=[],X=!0;for(;X;){let K=await i({message:`Add a block in order (${A.length} so far)`,choices:[...w.map(Ce=>({name:Ce,value:Ce})),{name:A.length?"- done -":"- done (empty page) -",value:"__done"}]});K==="__done"?X=!1:A.push(K)}g=A}let h=g??[],b=Nr({title:m,description:p||void 0,blocks:h,area:t.area}),y=ve.join("templates",`${d}.html`);if(await Tl(ve.join(n,"templates"),{recursive:!0}),await to(ve.join(n,y),b),r.info(S("Page template",`${u} \xB7 ${c}`)),r.info(j(y,`${h.length} block(s) + metadata`)),c==="da"){let v=await Dl(n),w=t.org??v.org??l.org,A=t.site??v.site??l.site;if(t.push??(a?await s({message:"Push to DA (da.live)?",default:!0}):!0))if(!w||!A)r.warn("No DA org/site. Pass --org/--site or set admin in .edsrc.json.");else try{await Dr(w,A,u,b,process.env.DA_TOKEN),r.info(j("pushed to DA",Fr(w,A,u)))}catch(K){r.error(`DA push failed: ${K.message}`),r.info(ht.dim(" Open projects allow anonymous writes; others need DA_TOKEN."))}}else if(c==="gdrive"||c==="sharepoint"){let v=c==="gdrive"?"a Google Doc":"a Word doc";r.info(""),r.info(ht.dim(` Document model: import ${y} into ${v} in your mounted folder,`)),r.info(ht.dim(" then preview/publish. (Share the folder + install aem-code-sync first.)"))}else if(c==="ue"){let v=ve.join("templates",`${d}.json`);await to(ve.join(n,v),await Mr(n,{title:m,name:d,blocks:h})),r.info(j(v,`initial content (${h.length} component(s), in order)`)),await Ll(n,h)&&r.info(j("component-filters.json","seeded blocks allowed in Universal Editor")),r.info(""),r.info(ht.dim(" Universal Editor: use the template JSON as the page's initial content, then")),r.info(ht.dim(" author it in the Universal Editor (wire the repo to AEM)."))}r.info(""),r.info(I([`"${d}" template (${c}) - preview with \`eds preview ${u}\``]))}var Al,io=k(()=>{"use strict";f();D();z();Wn();Kn();Ar();Lr();Or();Ir();_();Al=e=>e.trim().toLowerCase().replace(/[^a-z0-9-/]+/g,"-").replace(/^-+|-+$/g,"")});import{existsSync as cn}from"fs";import{readFile as Ur,readdir as Br}from"fs/promises";import Oe from"path";async function Ol(e){let t=[],n=async o=>{for(let i of await Br(o,{withFileTypes:!0})){let s=Oe.join(o,i.name);i.isDirectory()?await n(s):t.push(s)}};return cn(e)&&await n(e),t}async function Hr(e){if(!cn(e))return null;let t=await Br(e,{withFileTypes:!0}),n=t.find(i=>i.isDirectory()&&/clientlib/i.test(i.name));return n?Oe.join(e,n.name):t.some(i=>i.isFile()&&i.name.endsWith(".css"))?e:null}async function Gr(e){let t=await Ol(e),n=t.filter(a=>/\.(less|scss|sass)$/i.test(a)).map(a=>Oe.relative(e,a)),o,i=Oe.join(e,"css.txt");if(cn(i)){let a=(await Ur(i,"utf-8")).split(`
370
+ `).map(d=>d.trim()),l=e,c=[];for(let d of a){if(!d)continue;let m=d.match(/^#base\s*=\s*(.+)$/);m?l=Oe.join(e,m[1].trim()):d.startsWith("#")||c.push(d)}o=c.map(d=>Oe.join(l,d)).filter(d=>cn(d)&&d.endsWith(".css"))}else o=t.filter(a=>a.endsWith(".css"));let s=[];for(let a of o)s.push(await Ur(a,"utf-8"));return{css:s.join(`
371
371
 
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.
372
+ `),files:o.map(a=>Oe.relative(e,a)),preprocessed:n}}var Wr=k(()=>{"use strict";f()});import{XMLParser as Ml}from"fast-xml-parser";function Q(e){return Object.keys(e).find(t=>t!==":@")??""}function V(e){let t=Q(e),n=e[t];return Array.isArray(n)?n:[]}function Il(e){return e[":@"]??{}}function _l(e){return typeof e=="string"?e.replace(/^\{[^}]+\}/,""):e}function C(e,t){return _l(Il(e)[`@_${t}`])}function Ul(e,t){let n=C(t,"multiple")==="true"||C(t,"multiple")==="{Boolean}true";return e.endsWith("/form/pagefield")?"aem-content":e.includes("experience-fragment")||e.endsWith("/xffield")?"aem-experience-fragment":e.endsWith("/cfpicker")?"aem-content-fragment":e.endsWith("/form/textfield")||e.endsWith("/form/colorfield")||e.includes("/autocomplete")?"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 Bl(e){return e.endsWith("/form/hidden")||e.endsWith("/foundation/heading")||e.endsWith("/foundation/text")}function Hl(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 ro(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 Me(e,t){return(e??"").replace(/^\.\//,"").trim()||t}function Wl(e){let t=V(e).find(n=>Q(n)==="items");return t?V(t).map(n=>{let o=C(n,"value")??"";return{name:C(n,"text")??C(n,"jcr:title")??o,value:o}}):[]}function wt(e,t,n){let{unmapped:o,counter:i}=n;for(let s of e){let a=C(s,"sling:resourceType")??"";if(a.endsWith("/foundation/include")){let c=n.includeDepth<8?n.resolveInclude?.(C(s,"path")??""):null;c&&wt(c,t,{...n,includeDepth:n.includeDepth+1});continue}if(Bl(a))continue;if(a.endsWith("/foundation/tabs")){let c=V(s).find(d=>Q(d)==="items");for(let d of c?V(c):[]){let m=C(d,"jcr:title");t.push({component:"tab",name:Me(void 0,Q(d)),label:m}),wt(V(d),t,n)}continue}if(a.endsWith("/form/multifield")){let c=[];wt(V(s),c,n);let d=V(s).find(p=>Q(p)==="field"),m=Me(C(s,"name")??(d?C(d,"name"):void 0),`items${i.i++}`);t.push({component:"container",name:m,label:C(s,"fieldLabel")??"Items",multi:!0,collapsible:!0,fields:c});continue}let l=a?Ul(a,s):null;if(l){let c=Me(C(s,"name"),`field${i.i++}`),d={component:l,name:c},m=ro(l);m&&(d.valueType=m);let p=C(s,"fieldLabel")??C(s,"text");if(p&&(d.label=p),l==="select"||l==="radio-group"||l==="multiselect"){let g=Wl(s),h=V(s).find(y=>Q(y)==="datasource"),b=h?C(h,"sling:resourceType")??"":"";g.length?d.options=g:/heading|allowedtypes/i.test(b)?d.options=Gl:(d.component="text",d.valueType="string",n.datasourced.add(c))}let u=l==="boolean"?C(s,"checked"):C(s,"value");u!==void 0&&u!==""&&(d.value=l==="boolean"?u==="true":u),t.push(d);continue}a&&C(s,"name")&&!Hl(a)&&o.add(a),wt(V(s),t,n)}}function so(e){return e.filter((t,n)=>t.component!=="tab"||e[n+1]&&e[n+1].component!=="tab")}function ln(e){let t=new Set,n=[];for(let o of e){if(o.component!=="tab"){if(t.has(o.name))continue;t.add(o.name)}n.push(o.fields?{...o,fields:ln(o.fields)}:o)}return n}function bt(e){return new Ml({ignoreAttributes:!1,attributeNamePrefix:"@_",preserveOrder:!0,removeNSPrefix:!1,trimValues:!0}).parse(e)}function zr(e,t={}){let n=bt(e).find(a=>Q(a)==="jcr:root"),o=[],i=new Set,s=new Set;return n&&wt(V(n),o,{unmapped:i,datasourced:s,counter:{i:1},resolveInclude:t.resolveInclude,includeDepth:0}),{fields:so(ln(o)),unmapped:[...i],datasourced:[...s]}}function Ve(e){let t=0;for(let n of e)n.component!=="tab"&&(t+=1,n.fields&&(t+=Ve(n.fields)));return t}var Gl,dn=k(()=>{"use strict";f();Gl=["h1","h2","h3","h4","h5","h6"].map(e=>({name:e.toUpperCase(),value:e}))});function yt(e){return(C(e,"xtype")??"").toLowerCase()}function vt(e){let t=V(e).find(n=>Q(n)==="items");return t?C(t,"jcr:primaryType")==="cq:WidgetCollection"||!C(t,"xtype")?V(t):[t]:V(e).filter(n=>/^cq:/.test(C(n,"jcr:primaryType")??""))}function Jl(e){let t=V(e).find(n=>Q(n)==="options");return t?V(t).map(n=>{let o=C(n,"value")??"";return{name:C(n,"text")??o,value:o}}):[]}function Jr(e,t,n){let o=C(e,"name")??C(e,"key"),i=null,s,a=Me(o,`field${n.counter.i++}`);switch(t){case"textfield":case"colorfield":case"":i="text";break;case"textarea":i="textarea";break;case"richtext":i="richtext";break;case"numberfield":i="number";break;case"checkbox":i="boolean";break;case"datetime":case"datefield":i="date-time";break;case"pathfield":case"browsefield":i="aem-content";break;case"tags":case"tagsinputfield":i="aem-tag";break;case"smartimage":case"html5smartimage":case"smartfile":case"html5smartfile":case"fileupload":i="reference",a=Me(C(e,"fileReferenceParameter")??o,a);break;case"selection":{let p=(C(e,"type")??"select").toLowerCase();s=Jl(e),p==="checkbox"?i=s.length?"checkbox-group":"boolean":p==="radio"?i="radio-group":i="select",i!=="boolean"&&!s.length&&(i="text",n.datasourced.add(a));break}default:return null}let l={component:i,name:a},c=ro(i);c&&(l.valueType=c);let d=C(e,"fieldLabel")??C(e,"boxLabel")??C(e,"title");d&&(l.label=d),s?.length&&i!=="text"&&(l.options=s);let m=i==="boolean"?C(e,"checked")??C(e,"defaultValue"):C(e,"defaultValue")??C(e,"value");return m!==void 0&&m!==""&&(l.value=i==="boolean"?m==="true":m),l}function Ie(e,t,n){for(let o of e){let i=yt(o);if(zl.has(i))continue;if(Q(o)==="items"||C(o,"jcr:primaryType")==="cq:WidgetCollection"){Ie(V(o),t,n);continue}if(i==="slingscriptinclude"){/^rte\./.test(C(o,"script")??"")?t.push({component:"richtext",name:"text",valueType:"string",label:"Text"}):n.unmapped.add("xtype:slingscriptinclude");continue}if(i==="cqinclude"){let a=(C(o,"path")??"").replace(/\.(infinity|\d+)?\.?json$/,""),l=n.depth<8?n.resolveInclude?.(a):null;l&&Ie(l,t,{...n,depth:n.depth+1});continue}if(i==="tabpanel"){for(let a of vt(o)){if(yt(a)==="cqinclude"){Ie([a],t,n);continue}t.push({component:"tab",name:Q(a),label:C(a,"title")}),Ie(vt(a),t,n)}continue}if(i==="multifield"){let a=V(o).find(d=>Q(d)==="fieldConfig"),l=Me(C(o,"name"),`items${n.counter.i++}`);if(a&&!ao.has(yt(a))&&!C(a,"name")&&!C(a,"key")){let d=Jr(a,yt(a),n);if(d){t.push({...d,name:l,label:C(o,"fieldLabel")??d.label,multi:!0});continue}}let c=[];a&&Ie(ao.has(yt(a))?vt(a):[a],c,n),t.push({component:"container",name:l,label:C(o,"fieldLabel")??"Items",multi:!0,collapsible:!0,fields:c});continue}if(ao.has(i)||C(o,"jcr:primaryType")==="cq:Panel"||!i&&!C(o,"name")&&vt(o).length){Ie(vt(o),t,n);continue}let s=C(o,"name")||C(o,"key")?Jr(o,i,n):null;s?t.push(s):i&&n.unmapped.add(`xtype:${i}`)}}function qr(e){return/jcr:primaryType="cq:(Dialog|TabPanel|Panel|Widget)"/.test(e)||/\sxtype="/.test(e)}function Kr(e,t={}){let n=bt(e).find(s=>Q(s)==="jcr:root"),o=[],i={unmapped:new Set,datasourced:new Set,counter:{i:1},resolveInclude:t.resolveInclude,depth:0};return n&&Ie([n],o,i),{fields:so(ln(o)),unmapped:[...i.unmapped],datasourced:[...i.datasourced]}}var ao,zl,Vr=k(()=>{"use strict";f();dn();ao=new Set(["dialog","panel","dialogfieldset","multifieldpanel","fieldset"]),zl=new Set(["hidden","static","displayfield","label","box","componentstyles"])});import{existsSync as Xe,readFileSync as Xr}from"fs";import{readFile as ql}from"fs/promises";import Z from"path";import{XMLParser as Kl}from"fast-xml-parser";function Vl(e){return[Z.join(e,"_cq_dialog",".content.xml"),Z.join(e,"_cq_dialog.xml"),Z.join(e,"cq:dialog",".content.xml")].find(n=>Xe(n))??null}function Xl(e){return[Z.join(e,"dialog.xml"),Z.join(e,"dialog",".content.xml")].find(n=>Xe(n))??null}function Yr(e,t){let n=Z.join(e,".content.xml");if(Xe(n))try{let s=(new Kl({ignoreAttributes:!1,attributeNamePrefix:"@_"}).parse(Xr(n,"utf-8"))["jcr:root"]??{})[`@_${t}`];return typeof s=="string"?s.replace(/^\{[^}]+\}/,""):void 0}catch{return}}async function Qr(e){return Yr(e,"jcr:title")}function co(e){return Yr(e,"sling:resourceSuperType")}function Yl(e){let t=Z.resolve(e);for(;t!==Z.dirname(t);){if(Z.basename(t)==="jcr_root")return t;t=Z.dirname(t)}return null}function Zr(e,t){let n=e.replace(/^\/mnt\/overlay\//,"/").replace(/^\/(apps|libs)\//,"").replace(/^\//,"").split("/").map(i=>i.replace(/^([a-z]+):/,"_$1_")).join("/"),o=[];for(let i of t)o.push(Z.join(i,"apps",n),Z.join(i,"libs",n),Z.join(i,n));return o}function Ql(e){let t=new Map,n=o=>{if(!t.has(o))try{let i=bt(Xr(o,"utf-8")).find(s=>Q(s)==="jcr:root");t.set(o,i?V(i):null)}catch{t.set(o,null)}return t.get(o)??null};return o=>{if(!o||o.includes("${"))return null;for(let i of Zr(o,e)){let s=i.split(Z.sep);for(let a=s.length;a>1;a--){let l=s.slice(0,a).join(Z.sep),c=Xe(Z.join(l,".content.xml"))?Z.join(l,".content.xml"):Xe(`${l}.xml`)?`${l}.xml`:null;if(!c)continue;let d=n(c);for(let m of s.slice(a)){let p=d?.find(u=>Q(u)===m);d=p?[p]:null}if(d)return d;break}}return null}}async function es(e,t=[]){let n=Yl(e),o=[...n?[n]:[],...t],i=Ql(o),s=e,a,l=null;for(let c=0;c<8;c++){let d=Vl(s),m=d?null:Xl(s),p=d??m;if(p){let h=await ql(p,"utf-8"),b=m&&qr(h)?"classic":"touch",y=b==="classic"?Kr(h,{resolveInclude:i}):zr(h,{resolveInclude:i});if(Ve(y.fields)>0)return{...y,inheritedFrom:a,dialogKind:b};l??={...y,dialogKind:b}}let u=co(s),g=u?Zr(u,o).find(h=>Xe(h)):void 0;if(!u||!g)break;s=g,a=u}return l}function ts(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 ns(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 jr(e){return`/* Block: ${e} */
385
+ `}function os(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=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}
390
+ `}var is=k(()=>{"use strict";f();Vr();dn()});function Zl(e,t,n){let o=[` // --- ${ss} ---`];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 as(e,t,n){if(e.includes(ss))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",s=e;if(!s.includes("scripts/analytics.js")){let d=[...s.matchAll(/^import .*$/gm)];if(d.length){let m=d[d.length-1],p=(m.index??0)+m[0].length;s=`${s.slice(0,p)}
392
+ ${rs}${s.slice(p)}`}else s=`${rs}
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,i,n);return a=`${a.slice(0,d)}
395
- ${l}
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} */
394
+ ${s}`}let a=s.match(/export default (?:async )?function decorate\s*\(\s*([A-Za-z_$][\w$]*)?[^)]*\)\s*\{/);if(!a||a.index===void 0)return{js:s,changed:!1,reason:"decorate not found"};let l=a.index+a[0].length,c=Zl(t,i,n);return s=`${s.slice(0,l)}
395
+ ${c}
396
+ ${s.slice(l)}`,{js:s,changed:!0}}var ss,rs,cs=k(()=>{"use strict";f();ss="analytics (eds track)",rs="import { trackEvent } from '../../scripts/analytics.js';"});var kt={};O(kt,{trackBlock:()=>od});import{existsSync as ls}from"fs";import{readFile as ed,writeFile as td}from"fs/promises";import ds from"path";import nd from"chalk";async function od(e,t={}){let n=E();if(!n){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(T("Track block"));let o=ds.join(n,"blocks",e,`${e}.js`);if(!ls(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},s=as(await ed(o,"utf-8"),e,i);if(!s.changed){r.warn(`Not instrumented: ${s.reason}.`);return}await td(o,s.js),r.info(S("Instrumented"));let a=[i.click?"block_click":null,i.submit?"form_submit":null].filter(Boolean);r.info(j(`blocks/${e}/${e}.js`,a.join(" + "))),ls(ds.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(nd.dim(" Events push to window.dataLayer via trackEvent - GTM picks them up."))}var xt=k(()=>{"use strict";f();D();z();cs();_()});var po={};O(po,{migrateComponent:()=>sd});import{existsSync as lo}from"fs";import{mkdir as id,writeFile as mo}from"fs/promises";import ke from"path";function rd(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 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}) ---
401
+ `}function ms(e,t=0){let n=[];for(let o of e){let i=" ".repeat(t);if(o.component==="tab")n.push(`${i}${M.blue("\u25B8")} ${o.label??o.name}`);else{let s=o.options?.length?` (${o.options.length} options)`:"",a=o.multi?" \xB7multi":"",l=o.label?`- ${o.label}`:"";n.push(`${i}${M.accent(o.component)}${a} ${o.name}${s} ${l}`),o.fields?.length&&n.push(...ms(o.fields,t+1))}}return n}async function sd(e,t={}){let n=E();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(()=>(H(),B)),s=!t.yes,a=e;if(!a&&s&&(a=await o({message:"Path to the classic component folder",validate:w=>lo(w.trim())||"Folder not found"})),!a){r.error("Provide the path to the classic component folder."),process.exitCode=1;return}a=ke.resolve(a.trim());let l=(t.superRoot??"").split(",").map(w=>w.trim()).filter(Boolean).map(w=>ke.resolve(w)),c=await es(a,l);if(!c){let w=co(a);w?(r.error(`No dialog here: this is a proxy of ${w}, and that component isn't under ${l.length?"the given --super-root":"this jcr_root"}.`),r.info(" Pass --super-root <jcr_root that contains it>, e.g. a checkout of adobe/aem-core-wcm-components (content/src/content/jcr_root).")):r.error(`No Touch UI dialog (_cq_dialog/.content.xml) found in ${a}.`),process.exitCode=1;return}if(Ve(c.fields)===0){r.warn("Dialog found but no mappable fields were detected."),c.unmapped.length&&r.info(`Unmapped resourceTypes: ${c.unmapped.join(", ")}`),process.exitCode=1;return}let d=await Qr(a)??ke.basename(a),m=t.name&&mn(t.name)||mn(s?await o({message:"Block name",default:mn(d)}):d);c.dialogKind==="classic"&&r.info(` ${M.blue("\u21B3")} Classic UI dialog (dialog.xml) - mapped from its xtypes`),c.inheritedFrom&&r.info(` ${M.blue("\u21B3")} Dialog inherited from ${c.inheritedFrom} (proxy component; overlay changes not applied)`),r.info(S("Mapped fields",`${Ve(c.fields)} from dialog`));for(let w of ms(c.fields))r.info(` ${w}`);if(c.unmapped.length&&(r.info(""),r.warn(`Skipped (unrecognised): ${c.unmapped.join(", ")}`)),c.datasourced.length&&r.warn(`Options come from a datasource, migrated as text (add static options if needed): ${c.datasourced.join(", ")}`),r.info(""),s&&!await i({message:`Generate block "${m}"?`,default:!0})){r.info("Cancelled.");return}let p=ke.join(n,"blocks",m);if(lo(p)){r.error(`Block "${m}" already exists at blocks/${m}. Use --name to pick another.`),process.exitCode=1;return}let u=t.clientlib?ke.resolve(t.clientlib.trim()):await Hr(a),g=os(m),h="empty - add styles from clientlib / rendered CSS",b=[];if(u&&lo(u)){let w=await Gr(u);w.css.trim()&&(g=rd(m,w.css,w.files),h=`from clientlib (${w.files.length} file(s)) - review & scope`),b=w.preprocessed}await id(p,{recursive:!0}),await mo(ke.join(p,`${m}.js`),ns(m,c.fields)),await mo(ke.join(p,`${m}.css`),g),await mo(ke.join(p,`_${m}.json`),ts(m,d,c.fields)),r.info(S("Created"));let y=[`${m}.js`,`${m}.css`,`_${m}.json`],v=U(y);if(r.info(j(`${m}.js`,"decorator stub (port HTL logic)",v)),r.info(j(`${m}.css`,h,v)),r.info(j(`_${m}.json`,"Universal Editor model",v)),b.length&&(r.info(""),r.warn(`LESS/SCSS found (needs a build, not copied): ${b.join(", ")}`)),r.info(""),s&&await i({message:"Instrument this block for analytics (dataLayer)?",default:!1})){let{trackBlock:A}=await Promise.resolve().then(()=>(xt(),kt));await A(m,{})}r.info(I([`"${m}" migrated. Next: add CSS, then \`eds block preview ${m}\``]))}var mn,uo=k(()=>{"use strict";f();D();Wr();is();dn();z();_();mn=e=>e.trim().toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"")});function te(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):t}var ee,ps=k(()=>{"use strict";f();ee={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 wo(e){return Ye.find(t=>t.id===e)}var ad,cd,ld,dd,us,fs,fo,gs,go,ho,md,pd,ud,fd,gd,Ye,bo=k(()=>{"use strict";f();ps();ad=[{name:"H1",value:"h1"},{name:"H2",value:"h2"},{name:"H3",value:"h3"},{name:"H4",value:"h4"},{name:"H5",value:"h5"},{name:"H6",value:"h6"}],cd=[{name:"Same tab",value:"_self"},{name:"New tab",value:"_blank"}],ld=[{name:"Default",value:""},{name:"Primary",value:"primary"},{name:"Secondary",value:"secondary"}],dd=[{name:"Highlight",value:"highlight"},{name:"Dark",value:"dark"},{name:"Centered",value:"centered"},{name:"Full width",value:"full-width"}],us=(e="")=>[ee.text(te(e,"title"),"Title"),ee.select(te(e,"titleType"),"Heading level",ad,"h2")],fs=(e="")=>[ee.text(te(e,"eyebrow"),"Eyebrow")],fo=(e="")=>[ee.reference(te(e,"image"),"Image"),ee.text(te(e,"imageAlt"),"Alt text")],gs=(e="")=>[ee.richtext(te(e,"text"),"Text")],go=(e="")=>[ee.text(te(e,"linkText"),"Link text"),ee.aemContent(te(e,"link"),"Link"),ee.select(te(e,"linkTarget"),"Open in",cd,"_self")],ho=(e="")=>[...go(e),ee.select(te(e,"ctaStyle"),"Style",ld,"")],md=(e="")=>[ee.container(te(e,"ctas")||"ctas","Buttons",ho())],pd=(e="")=>[ee.multiselect(te(e,"classes"),"Styles",dd)],ud=(e="")=>[ee.aemContent(te(e,"url"),"URL (video / embed)")],fd=(e="")=>[...fo(e),...fs(e),...us(e),...gs(e),...ho(e)],gd=(e="")=>[...fo(e),ee.text(te(e,"title"),"Title"),ee.richtext(te(e,"description"),"Description"),...go(e)],Ye=[{id:"heading",label:"Heading (title + level)",build:us},{id:"eyebrow",label:"Eyebrow (kicker line)",build:fs},{id:"image",label:"Image (reference + alt)",build:fo},{id:"richtext",label:"Rich text body",build:gs},{id:"link",label:"Link (text + url + target)",build:go},{id:"cta",label:"CTA (link + style)",build:ho},{id:"cta-group",label:"CTA group (repeatable buttons)",build:md},{id:"classes",label:"Section styles (CSS modifiers)",build:pd},{id:"embed",label:"Embed / video (URL)",build:ud},{id:"teaser",label:"Teaser (image + eyebrow + title + text + CTA)",build:fd},{id:"card",label:"Card (image + title + description + link)",build:gd}]});var ko={};O(ko,{modelAdd:()=>bd});import{existsSync as yo}from"fs";import{readFile as hd,writeFile as wd}from"fs/promises";import vo from"path";async function bd(e,t,n={}){let o=E();if(!o){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(T("Model - add partials"));let{select:i,checkbox:s}=await Promise.resolve().then(()=>(H(),B)),a=!n.yes,l=e;if(!l&&a){let{readdir:w}=await import("fs/promises"),A=vo.join(o,"blocks"),X=yo(A)?(await w(A,{withFileTypes:!0})).filter(K=>K.isDirectory()&&yo(vo.join(A,K.name,`_${K.name}.json`))).map(K=>K.name):[];if(X.length===0){r.error("No block with a _<name>.json model found. Create one with `eds block create`."),process.exitCode=1;return}l=await i({message:"Which block's model?",choices:X.map(K=>({name:K,value:K}))})}if(!l){r.error("Provide a block name."),process.exitCode=1;return}let c=vo.join(o,"blocks",l,`_${l}.json`);if(!yo(c)){r.error(`No model at blocks/${l}/_${l}.json. Create the block first.`),process.exitCode=1;return}let d=t;d.length===0&&a&&(d=await s({message:"Which partials to add?",choices:Ye.map(w=>({name:w.label,value:w.id}))}));let m=d.map(w=>wo(w.trim())).filter(w=>!!w),p=d.filter(w=>!wo(w.trim()));if(p.length&&r.warn(`Unknown partial(s): ${p.join(", ")}. Available: ${Ye.map(w=>w.id).join(", ")}`),m.length===0){r.info("Nothing to add.");return}let u;try{u=JSON.parse(await hd(c,"utf-8"))}catch{r.error(`Could not parse ${c}.`),process.exitCode=1;return}let g=Array.isArray(u.models)?u.models:[],h=g.find(w=>w.id===l)??g[0];if(!h){r.error("Model has no `models[]` entry to add fields to."),process.exitCode=1;return}h.fields=Array.isArray(h.fields)?h.fields:[];let b=new Set(h.fields.map(w=>w.name)),y=[],v=[];for(let w of m)for(let A of w.build()){if(b.has(A.name)){v.push(A.name);continue}b.add(A.name),h.fields.push(A),y.push(A.name)}await wd(c,`${JSON.stringify(u,null,2)}
402
+ `),r.info(S("Model updated",`blocks/${l}/_${l}.json`)),r.info(j("partials",m.map(w=>w.id).join(", "))),r.info(j("fields added",y.length?y.join(", "):"(none)")),v.length&&r.info(R("warn","skipped (exists)",v.join(", "))),r.info(""),r.info(I([`${y.length} field(s) added to "${l}"`]))}var xo=k(()=>{"use strict";f();D();bo();z();_()});function ws(e){return pn.find(t=>t.id.toLowerCase()===e.toLowerCase())}function bs(e,t){if(e.includes(hs))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,s=`
403
+ // --- ${hs}: ${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,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:`{
412
+ `;return{js:`${e.slice(0,i)}${s}${e.slice(i)}`,changed:!0}}var hs,pn,ys=k(()=>{"use strict";f();hs="json-ld (eds schema",pn=[{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,16 +488,17 @@ ${t.trim()}
488
488
  position: i + 1,
489
489
  text: li.textContent?.trim(),
490
490
  })),
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) {
491
+ }`}]});var $o={};O($o,{schemaBlock:()=>Sd});import{existsSync as yd}from"fs";import{readFile as vd,writeFile as kd}from"fs/promises";import xd from"path";import $d from"chalk";async function Sd(e,t={}){let n=E();if(!n){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(T("Schema - JSON-LD"));let o=xd.join(n,"blocks",e,`${e}.js`);if(!yd(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:l}=await Promise.resolve().then(()=>(H(),B));i=await l({message:"Which schema.org type?",choices:pn.map(c=>({name:`${c.id} - ${c.label}`,value:c.id}))})}let s=i?ws(i):void 0;if(!s){r.error(`Unknown schema type "${i}". Options: ${pn.map(l=>l.id).join(", ")}`),process.exitCode=1;return}let a=bs(await vd(o,"utf-8"),s);if(!a.changed){r.warn(`Not added: ${a.reason}.`);return}await kd(o,a.js),r.info(S("JSON-LD added")),r.info(j(`blocks/${e}/${e}.js`,`${s.id} (${s.label})`)),r.info(""),r.info($d.dim(" Review the generated object - some fields are heuristic or TODO. Validate at search.google.com/test/rich-results."))}var So=k(()=>{"use strict";f();D();z();ys();_()});function Pd(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 vs(e){return Pd(e,jd)!==null}function ks(e){return Array.isArray(e)?e.map(t=>t&&typeof t=="object"?t.id:void 0).filter(t=>typeof t=="string"):[]}function xs(e){let t=!!e.configPresent["component-definition.json"]&&!!e.configPresent["component-models.json"],n=new Set(e.modelIds),o=e.blocks.map(i=>{let s=i.hasModelFile||n.has(i.name);return{name:i.name,editable:s,reason:s?void 0:"no UE model (_<name>.json or component-models entry)"}});return{isUeProject:t,blocks:o}}var jo,jd,$s=k(()=>{"use strict";f();jo=["component-definition.json","component-models.json","component-filters.json"],jd="urn:adobe:aue:system:aemconnection"});var jt={};O(jt,{ueCheck:()=>Fd,ueOpen:()=>Dd});import{existsSync as St}from"fs";import{readFile as Ss,readdir as Ed}from"fs/promises";import $t from"path";import un from"chalk";async function Cd(e){if(!St(e))return null;try{return JSON.parse(await Ss(e,"utf-8"))}catch{return null}}async function Td(e){let t=$t.join(e,"blocks");return St(t)?(await Ed(t,{withFileTypes:!0})).filter(o=>o.isDirectory()).map(o=>({name:o.name,hasModelFile:St($t.join(t,o.name,`_${o.name}.json`))})):[]}async function Rd(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 Ad(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 Fd(){let e=E();if(!e){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(T("Universal Editor - readiness"));let t={};for(let p of jo)t[p]=St($t.join(e,p));let n=await Cd($t.join(e,"component-models.json")),o=await Td(e),{isUeProject:i,blocks:s}=xs({configPresent:t,blocks:o,modelIds:ks(n)});r.info(S("Universal Editor config"));let a=[...jo],l=U(a);for(let p of a)r.info(R(t[p]?"pass":"fail",p,void 0,l));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 c=$t.join(e,"head.html");if(St(c)){let p=vs(await Ss(c,"utf-8"));r.info(R(p?"pass":"info","head.html",p?"aemconnection present":"no aemconnection (fine for cloud author)"))}if(r.info(S("Blocks",`${s.length} found`)),s.length===0)r.info(un.dim(" No blocks yet."));else{let p=U(s.map(u=>u.name));for(let u of s)r.info(R(u.editable?"pass":"warn",u.name,u.reason,p))}let d=s.filter(p=>p.editable).length,m=s.length-d;r.info(""),r.info(be({pass:d,warn:m})),r.info(un.dim(" Open a page in the editor with `eds ue open <path>`."))}async function Dd(e,t={}){let n=E()??process.cwd(),o=e??t.path??"/",i=t.url;if(!i){let a=await Ad(n),l=a?qe(a):null;if(!l){r.error("Couldn't determine the preview host from git."),r.info(un.dim(" Pass it explicitly: `eds ue open <path> --url main--<repo>--<owner>.aem.page`")),process.exitCode=1;return}i=Ke(l.owner,l.repo,t.ref??"main")}let s=cr({host:i,path:o,org:t.org});r.info(S("Universal Editor")),r.info(j("page",`${i}${o.startsWith("/")?"":"/"}${o}`)),r.info(j("open",s)),t.open!==!1?await Rd(s):r.info(un.dim(" (use without --no-open to launch the browser)"))}var Pt=k(()=>{"use strict";f();D();z();$s();en();_()});var Eo={};O(Eo,{createBlock:()=>Md,ueModelFor:()=>Ps});import{existsSync as Ld}from"fs";import{mkdir as Nd,writeFile as Po}from"fs/promises";import Et from"path";import js from"chalk";function Od(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Ps(e){let t=Od(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 Md(e,t={}){if(!Re.test(e)){r.error(`Invalid block name "${e}". Use kebab-case (e.g., "hero-banner", "card-list").`),process.exitCode=1;return}let n=E();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=Et.join(n,"blocks",e);if(Ld(o)){r.error(`Block "${e}" already exists at ${o}`),process.exitCode=1;return}await Nd(o,{recursive:!0});let i=`export default function decorate(block) {
493
493
  // TODO: implement ${e} block
494
494
  }
495
- `,a=`.${e} {
495
+ `,s=`.${e} {
496
496
  /* TODO: style ${e} block */
497
497
  }
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"?`
498
+ `;await Po(Et.join(o,`${e}.js`),i),await Po(Et.join(o,`${e}.css`),s);let a=t.ueModel!==!1;a&&await Po(Et.join(o,`_${e}.json`),Ps(e)),r.success(`Block "${e}" created at ${js.cyan(Et.relative(n,o))}${a?js.dim(" (+ Universal Editor model)"):""}`)}var Co=k(()=>{"use strict";f();D();z();Je()});import{existsSync as fn}from"fs";import{readFile as Id}from"fs/promises";import{homedir as Qe}from"os";import Ze from"path";async function Ro(e){let{execaCommand:t}=await import("execa");try{return(await t(`which ${e}`)).stdout.trim()||void 0}catch{return}}function Es(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=Es(o);if(i)return i}}async function Ao(e){for(let t of e)try{if(!fn(t))continue;let n=await Id(t,"utf-8");try{let o=Es(JSON.parse(n));if(o)return o}catch{}if(n.toLowerCase().includes("figma"))return"figma"}catch{}}async function Cs(e){if(e){let t=To.find(n=>n.type===e);if(t){let n=await Ro(t.binary);if(n){let o=await Ao(t.mcpConfigPaths);return{type:t.type,path:n,configDir:fn(t.configDir)?t.configDir:void 0,hasFigmaMcp:!!o,figmaMcpServerName:o}}r.warn(`Preferred agent "${e}" not found in PATH`)}}for(let t of To){let n=await Ro(t.binary);if(n){let o=await Ao(t.mcpConfigPaths);return{type:t.type,path:n,configDir:fn(t.configDir)?t.configDir:void 0,hasFigmaMcp:!!o,figmaMcpServerName:o}}}}async function gn(){let e=[];for(let t of To){let n=await Ro(t.binary);if(n){let o=await Ao(t.mcpConfigPaths);e.push({type:t.type,path:n,configDir:fn(t.configDir)?t.configDir:void 0,hasFigmaMcp:!!o,figmaMcpServerName:o})}}return e}var To,Fo=k(()=>{"use strict";f();D();To=[{type:"claude",binary:"claude",configDir:Ze.join(Qe(),".claude"),mcpConfigPaths:[Ze.join(Qe(),".claude","plugins.json"),Ze.join(Qe(),".claude.json")]},{type:"cursor",binary:"cursor",configDir:Ze.join(Qe(),".cursor"),mcpConfigPaths:[Ze.join(Qe(),".cursor","mcp.json")]},{type:"codex",binary:"codex",configDir:Ze.join(Qe(),".codex"),mcpConfigPaths:[]}]});import{mkdir as _d,readFile as Ud,writeFile as Bd}from"fs/promises";import{tmpdir as Hd}from"os";import Ct from"path";import Gd from"readline";import ie from"chalk";async function Do(e,t){let n=t?Ct.join(t,"tmp"):Hd(),o=Ct.join(n,"eds-cli");await _d(o,{recursive:!0});let i=`from-design-${Date.now()}.md`,s=Ct.join(o,i);return await Bd(s,e,"utf-8"),s}function Ts(e,t){return Buffer.byteLength(e,"utf-8")<=Wd?e:`Your full task is in the file ${t}. Read that whole file first and follow its instructions exactly - it replaces this message.`}async function Lo(e,t,n,o){let{execa:i}=await import("execa"),s=await Ud(t,"utf-8");try{switch(e.type){case"claude":{r.info(`Running Claude Code ${ie.dim("- live log:")}`);let a=[...e.figmaMcpServerName?[e.figmaMcpServerName]:[],"figma-sse","figma-desktop","figma","Figma","plugin_figma_figma"],l=[...new Set(a.map(m=>`mcp__${m}`)),"Edit","Write","Read"].join(","),d=i("claude",["-p","--model",o??"haiku","--output-format","stream-json","--verbose","--allowedTools",l],{cwd:n,buffer:!1,input:s,stdio:["pipe","pipe","inherit"]});await Jd(d,n);break}case"cursor":{r.info("Running Cursor agent..."),await i("cursor",["--prompt",Ts(s,t)],{cwd:n,stdio:"inherit"});break}case"codex":{r.info("Running Codex..."),await i("codex",[Ts(s,t)],{cwd:n,stdio:"inherit"});break}}return!0}catch(a){let l=(a instanceof Error?a.message:String(a)).split(`
499
+ `)[0].slice(0,300);return r.error(`Agent ${e.type} failed: ${l}`),!1}}function zd(e){return e.includes("figma")?e.split("__").pop()??e:e.toLowerCase()}async function Jd(e,t){let n=(await import("ora")).default,o=Date.now(),i=()=>`${Math.round((Date.now()-o)/1e3)}s`,s=n({text:`thinking ${ie.dim(i())}`,color:"yellow"}).start(),a="thinking",l=setInterval(()=>{s.text=`${a} ${ie.dim(i())}`},300),c=new Map,d=p=>{s.stop(),r.info(` ${p}`),s.start()},m;try{if(e.stdout){let p=Gd.createInterface({input:e.stdout});for await(let u of p){let g=u.trim();if(!g)continue;let h;try{h=JSON.parse(g)}catch{continue}let b=Array.isArray(h.message?.content)?h.message.content:[];if(h.type==="assistant"){for(let y of b)if(y.type==="text"&&"text"in y){let v=y.text.trim().split(`
500
+ `)[0].slice(0,100);v&&d(ie.dim(v))}else if(y.type==="tool_use"&&"name"in y){let v="id"in y&&y.id?y.id:`${Math.random()}`;c.set(v,{label:qd(y.name,y.input,t),start:Date.now()}),a=zd(y.name)}}else if(h.type==="user"){for(let y of b)if(y.type==="tool_result"&&"tool_use_id"in y&&y.tool_use_id){let v=c.get(y.tool_use_id);if(v){let w=`${((Date.now()-v.start)/1e3).toFixed(1)}s`,A="is_error"in y&&y.is_error?` ${ie.red("failed")}`:"";d(`${v.label} ${ie.dim(w)}${A}`),c.delete(y.tool_use_id)}}}else if(h.type==="result"){let y=typeof h.duration_ms=="number"?`${(h.duration_ms/1e3).toFixed(1)}s`:"",v=typeof h.total_cost_usd=="number"?`$${h.total_cost_usd.toFixed(3)}`:"";m=[y,v].filter(Boolean).join(" \xB7 ")||"done"}}}for(let p of c.values())d(`${p.label} ${ie.dim("\u2026")}`);clearInterval(l),m?s.succeed(`${M.accent("agent finished")} ${ie.dim(m)}`):s.stop()}catch(p){throw clearInterval(l),s.stop(),p}await e}function qd(e,t,n){let o=i=>{let s=t?.[i];return typeof s!="string"?"":s.startsWith(n)?Ct.relative(n,s):Ct.basename(s)};if(e.includes("figma")){let i=e.split("__").pop()??e;return`${J.figma} ${ie.bold(i)} ${ie.dim("Figma MCP")}`}switch(e){case"Write":case"Edit":case"NotebookEdit":return`${M.accent("\u270E")} ${ie.cyan(o("file_path"))}`;case"Read":return ie.dim(`\xB7 read ${o("file_path")}`);case"Bash":{let i=typeof t?.command=="string"?t.command.split(`
501
+ `)[0].slice(0,70):"";return ie.dim(`$ ${i}`)}default:return`${M.blue("\u2192")} ${e}`}}var Wd,Rs=k(()=>{"use strict";f();D();_();Wd=96*1024});import{existsSync as Kd}from"fs";import{readFile as Vd}from"fs/promises";import{homedir as Xd}from"os";import No from"path";async function As(e){try{let t=await Vd(e,"utf-8");return JSON.parse(t)}catch{return}}async function pe(e){let t=await As(Oo),n=e?await As(No.join(e,Yd)):void 0,o={...typeof t=="object"&&t!==null?t:{},...typeof n=="object"&&n!==null?n:{}},i=In.safeParse(o);return i.success?i.data:(r.debug("Config validation issues:",i.error.flatten()),In.parse({}))}function Ds(){return Fs}function Mo(){return Oo}function Io(){return Kd(Oo)}var Fs,Oo,Yd,xe=k(()=>{"use strict";f();D();Je();Fs=No.join(Xd(),".eds"),Oo=No.join(Fs,"config.json"),Yd=".edsrc.json"});function Ls(e){return e<=480?`${e} mobile`:e<=1024?`${e} tablet`:`${e} desktop`}function Qd(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:Ls(n),source:t})):[]}function Ns(e,t){let n=Qd(e,"figma");return n.length?n:Zd(t)}function Zd(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 s=o.source,a=s==="figma"||s==="scrape"?s:"default";n.push({width:i,label:Ls(i),source:a})}return n}var Os=k(()=>{"use strict";f()});import{existsSync as em}from"fs";import{createRequire as tm}from"module";import nm from"path";import{pathToFileURL as Ms}from"url";async function Is(e){try{return(await import("playwright")).chromium}catch{}let t=[e,process.cwd()].filter(n=>!!n);if(t.length)try{let o=tm(Ms(nm.join(t[0],"package.json")).href).resolve("playwright",{paths:t});return(await import(Ms(o).href)).chromium}catch{}throw new Error("Scraping needs Playwright. Install it in your project (`npm i -D playwright`) or globally (`npm i -g playwright`), then `npx playwright install chromium`.")}async function _s(e){let t=e.width??1440,n=await Is(e.projectRoot),o;try{o=await n.launch({headless:!0})}catch(i){let s=i instanceof Error?i.message:String(i);throw/Executable doesn't exist|install/i.test(s)?new Error("Chromium isn't installed for Playwright. Run `npx playwright install chromium`."):i}try{let i=e.storageStatePath&&em(e.storageStatePath),a=await(await o.newContext({viewport:{width:t,height:900},deviceScaleFactor:1,...i?{storageState:e.storageStatePath}:{}})).newPage();await a.goto(e.url,{waitUntil:"networkidle",timeout:45e3}),await a.waitForTimeout(700);let l=await a.evaluate(om,{maxNodes:320,maxDepth:14,textCap:200}),c={source:`scrape:${e.provider}`,url:e.url,viewport:t,authenticated:!!i,title:l.title,root:l.root,nodeCount:l.nodeCount,truncated:l.truncated};return JSON.stringify(c,null,2)}finally{await o.close()}}async function Us(e){let n=await(await Is(e.projectRoot)).launch({headless:!1});try{let o=await n.newContext();await(await o.newPage()).goto(e.loginUrl,{waitUntil:"domcontentloaded",timeout:6e4}),await e.waitForUser(),await o.storageState({path:e.statePath})}finally{await n.close()}}function om(e){let t=new Set(["SCRIPT","STYLE","NOSCRIPT","LINK","META","HEAD","BR","TEMPLATE"]),n=0,o=!1,i=d=>!d||d==="none"||d==="normal"||d==="auto"||d==="0px"||d==="rgba(0, 0, 0, 0)"||d==="transparent";function s(d){let m="";for(let p of Array.from(d.childNodes))p.nodeType===3&&(m+=p.textContent??"");return m=m.replace(/\s+/g," ").trim(),m.length>e.textCap?`${m.slice(0,e.textCap)}\u2026`:m}function a(d){let m=getComputedStyle(d),p={},u=(g,h)=>{i(h)||(p[g]=h)};return u("display",m.display),(m.display.includes("flex")||m.display.includes("grid"))&&(u("flexDirection",m.flexDirection),u("justifyContent",m.justifyContent),u("alignItems",m.alignItems),u("gap",m.gap)),u("padding",m.padding),u("margin",m.margin),u("color",m.color),u("background",m.backgroundColor),m.backgroundImage&&m.backgroundImage!=="none"&&(p.backgroundImage=m.backgroundImage.slice(0,160)),u("fontFamily",m.fontFamily),u("fontSize",m.fontSize),u("fontWeight",m.fontWeight),u("lineHeight",m.lineHeight),u("letterSpacing",m.letterSpacing),u("textAlign",m.textAlign),u("border",m.border),u("borderRadius",m.borderRadius),u("boxShadow",m.boxShadow),m.opacity&&m.opacity!=="1"&&(p.opacity=m.opacity),m.position&&m.position!=="static"&&(p.position=m.position),p}function l(d,m){if(n>=e.maxNodes)return o=!0,null;if(t.has(d.tagName))return null;let p=d.getBoundingClientRect(),u=getComputedStyle(d);if(u.display==="none"||u.visibility==="hidden"||u.opacity==="0"||p.width<1||p.height<1)return null;n++;let h={tag:d.tagName.toLowerCase(),rect:{x:Math.round(p.x),y:Math.round(p.y),w:Math.round(p.width),h:Math.round(p.height)}},b=(d.getAttribute("class")||"").trim().split(/\s+/).filter(Boolean).slice(0,3);b.length&&(h.class=b.join(" "));let y=a(d);if(Object.keys(y).length&&(h.style=y),d.tagName==="IMG"){let w=d;h.img={src:(w.currentSrc||w.src||"").slice(0,200),alt:w.alt||"",w:w.naturalWidth,h:w.naturalHeight}}let v=s(d);if(v&&(h.text=v),m<e.maxDepth){let w=[];for(let A of Array.from(d.children)){let X=l(A,m+1);X&&w.push(X)}w.length&&(h.children=w)}return h}let c=l(document.body,0);return{title:document.title,root:c,nodeCount:n,truncated:o}}var _o=k(()=>{"use strict";f()});import{mkdir as Bs,readFile as im,rm as Hs,stat as rm,writeFile as sm}from"fs/promises";import Ws from"path";function hn(e){return Ws.join(e,"tmp","eds-cli","figma-rest-calls.json")}async function cm(e,t,n){let o=`${e}.lock`;for(await Bs(Ws.dirname(e),{recursive:!0});;)try{await Bs(o);break}catch{await rm(o).then(s=>t()-s.mtimeMs,()=>0)>am?await Hs(o,{recursive:!0,force:!0}):await new Promise(s=>setTimeout(s,25))}try{return await n()}finally{await Hs(o,{recursive:!0,force:!0})}}async function lm(e){try{let t=JSON.parse(await im(e,"utf-8"));return Array.isArray(t)?t.filter(n=>typeof n=="number"):[]}catch{return[]}}async function wn(e){let t=Math.max(1,e.perMinute??Uo),n=e.now??Date.now,o=e.sleep??(i=>new Promise(s=>setTimeout(s,i)));for(;;){let i=await cm(e.logPath,n,async()=>{let s=n(),a=(await lm(e.logPath)).filter(l=>s-l<Gs);return a.length<t?(a.push(s),await sm(e.logPath,JSON.stringify(a)),0):Math.min(...a)+Gs-s+50});if(i<=0)return;e.onWait?.(i),await o(i)}}var Uo,Gs,am,bn=k(()=>{"use strict";f();Uo=10,Gs=6e4,am=1e4});function dm(e){let t=Math.max(0,Math.round(e));if(t<60)return`${t} s`;if(t<3600)return`${Math.round(t/60)} min`;if(t<86400){let o=Math.round(t%3600/60);return`${Math.floor(t/3600)} h${o?` ${o} min`:""}`}let n=Math.round(t%86400/3600);return`${Math.floor(t/86400)} d${n?` ${n} h`:""}`}async function Go(e,t,n,o=!1){await n?.();let i=await fetch(e,{headers:{"X-Figma-Token":t}});if(i.status!==429)return i;let s=c=>i.headers.get(c)??void 0,a=s("retry-after"),l=a!==void 0&&/^\d+$/.test(a)?Number(a):void 0;if(!o&&l!==void 0&&l<=60)return await mm.sleep(l*1e3),Go(e,t,n,!0);throw new Tt(l,s("x-figma-plan-tier"),s("x-figma-rate-limit-type"),s("x-figma-upgrade-link"))}async function qs(e){let{fileKey:t,nodeId:n,token:o}=e,i=n?`${Bo}/files/${t}/nodes?ids=${encodeURIComponent(n)}`:`${Bo}/files/${t}`,s=await Go(i,o,e.pace);if(!s.ok){let a=await s.text().catch(()=>""),l=s.status===403?" (check the token scope: it needs file_content:read, and access to this file)":s.status===404?" (file or node not found \u2014 check the URL)":"";throw new Error(`Figma REST ${s.status} ${s.statusText}${l}${a?` \u2014 ${a.slice(0,200)}`:""}`)}return s.json()}async function Ks(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 s=`${Bo}/images/${t}?ids=${encodeURIComponent(n)}&format=png&scale=${i}`,a=await Go(s,o,e.pace);if(!a.ok){let m=await a.text().catch(()=>"");throw new Error(`Figma images ${a.status} ${a.statusText}${m?` \u2014 ${m.slice(0,200)}`:""}`)}let l=await a.json();if(l.err)throw new Error(`Figma images: ${l.err}`);let c=l.images?.[n]??Object.values(l.images??{}).find(Boolean);if(!c)throw new Error("Figma returned no image URL for that node.");let d=await fetch(c);if(!d.ok)throw new Error(`Fetching the rendered image failed: ${d.status} ${d.statusText}`);return Buffer.from(await d.arrayBuffer())}function Ho(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 Js(e){let t=e?.find(n=>n.visible!==!1);if(t){if(t.type==="SOLID")return Ho(t.color);if(t.type?.startsWith("GRADIENT")){let n=(t.gradientStops??[]).map(o=>Ho(o.color)).filter(Boolean);return n.length?`gradient(${n.join(" \u2192 ")})`:"gradient"}return t.type==="IMAGE"?"image(placeholder)":t.type?.toLowerCase()}}function Vs(e,t){if(!e||typeof e!="object")return null;let n={name:e.name,type:e.type};if(e.absoluteBoundingBox){let{width:a,height:l}=e.absoluteBoundingBox;a!=null&&l!=null&&(n.size={w:Math.round(a),h:Math.round(l)})}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=Js(e.fills);o&&(n.fill=o);let i=Js(e.strokes);i&&(n.stroke={color:i,weight:e.strokeWeight}),e.cornerRadius&&(n.radius=e.cornerRadius);let s=(e.effects??[]).filter(a=>a.visible!==!1&&(a.type==="DROP_SHADOW"||a.type==="INNER_SHADOW")).map(a=>`${a.type==="INNER_SHADOW"?"inset ":""}${a.offset?.x??0} ${a.offset?.y??0} ${a.radius??0} ${Ho(a.color)??""}`.trim());if(s.length&&(n.shadows=s),e.type==="TEXT"&&e.characters!==void 0){n.text=e.characters;let a=e.style??{};n.font={family:a.fontFamily,size:a.fontSize,weight:a.fontWeight,lineHeight:a.lineHeightPx,letterSpacing:a.letterSpacing,align:a.textAlignHorizontal}}if(e.children?.length&&t<pm){let a=e.children.slice(0,zs).map(l=>Vs(l,t+1)).filter(Boolean);a.length&&(n.children=a),e.children.length>zs&&(n.childrenTruncated=e.children.length)}return n}function Xs(e,t){let n=e,o;if(t&&n.nodes){let s=Object.keys(n.nodes)[0];o=s?n.nodes[s]?.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:Vs(o,0)};return JSON.stringify(i,null,2)}var Bo,Tt,mm,pm,zs,Wo=k(()=>{"use strict";f();Bo="https://api.figma.com/v1",Tt=class extends Error{constructor(n,o,i,s){let a=[o&&`plan tier: ${o}`,i&&`limit type: ${i}`].filter(Boolean).join(", ");super(`Figma REST rate limit reached${a?` (${a})`:""}${n!==void 0?`; resets in ${dm(n)}`:""}`);this.retryAfterSeconds=n;this.planTier=o;this.limitType=i;this.upgradeLink=s;this.name="FigmaRateLimitError"}retryAfterSeconds;planTier;limitType;upgradeLink};mm={sleep:e=>new Promise(t=>setTimeout(t,e))};pm=12,zs=60});import{existsSync as um}from"fs";import{mkdir as fm,readFile as gm,writeFile as hm}from"fs/promises";import Rt from"path";function wm(e,t,n){let o=s=>s.replace(/[^a-z0-9._-]/gi,"-"),i=`${o(t)}__${o(n??"file")}.json`;return Rt.join(e,"tmp","eds-cli","design-cache",i)}function bm(e,t){let n=`scrape__${t.replace(/[^a-z0-9._-]/gi,"-").slice(0,120)}.json`;return Rt.join(e,"tmp","eds-cli","design-cache",n)}function zo(e){return e==="framer"||e==="stitch"}async function Ys(e){if(!um(e))return null;try{return await gm(e,"utf-8")}catch{return null}}async function Qs(e,t){await fm(Rt.dirname(e),{recursive:!0}),await hm(e,t,"utf-8")}async function Zs(e){let{figma:t,projectRoot:n}=e;if(e.localFile)return{design:{mode:"file",filePath:e.localFile},summary:`local file ${e.localFile}`};if(zo(e.provider)&&e.designUrl){let s=bm(n,e.designUrl),a=Rt.relative(n,s);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:a},summary:`scrape (dry run) ${e.designUrl}`};if(!e.refresh){let l=await Ys(s);if(l)return{design:{mode:"scrape",spec:l,cachePath:a},summary:`cache ${a}`}}try{let l=await _s({url:e.designUrl,provider:e.provider,projectRoot:n,storageStatePath:e.storageStatePath});return await Qs(s,l),{design:{mode:"scrape",spec:l,cachePath:a},summary:`scrape \u2192 ${a}`}}catch(l){return{summary:"scrape failed",scrapeError:l instanceof Error?l.message:String(l)}}}if(!t?.fileKey)return{summary:"no design source"};let o=wm(n,t.fileKey,t.nodeId),i=Rt.relative(n,o);if(!e.refresh){let s=await Ys(o);if(s)return{design:{mode:"spec",spec:s,cachePath:i},summary:`cache ${i}`}}if(e.token&&!e.preferMcp)try{let s=await qs({fileKey:t.fileKey,nodeId:t.nodeId,token:e.token,pace:()=>wn({logPath:hn(n),perMinute:e.restPerMinute,onWait:e.onRestWait})}),a=Xs(s,t.nodeId);return await Qs(o,a),{design:{mode:"spec",spec:a,cachePath:i},summary:`REST \u2192 ${i}`}}catch(s){return s instanceof Tt?{summary:"REST rate-limited",restError:s.message,rateLimit:s}:{design:{mode:"mcp",cachePath:i},summary:"MCP (REST failed \u2014 1 call)",restError:s instanceof Error?s.message:String(s)}}return{design:{mode:"mcp",cachePath:i},summary:"MCP (1 call, cached)"}}var ea=k(()=>{"use strict";f();_o();bn();Wo()});function yn(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];if(!ym.has(o))throw new Error(`Not a Figma file URL: "${e}". Use a design link (figma.com/design/<file>/\u2026?node-id=\u2026).`);let i,s;n[2]==="branch"&&n[3]?(i=n[3],s=n[4]?decodeURIComponent(n[4]):void 0):(i=n[1],s=n[2]?decodeURIComponent(n[2]):void 0);let a=t.searchParams.get("node-id"),l=a?vm(a):void 0;return{fileKey:i,nodeId:l,fileName:s}}function vm(e){return decodeURIComponent(e).replace(/-/g,":")}var ym,ta=k(()=>{"use strict";f();ym=new Set(["design","file","board","make","slides","proto"])});import{existsSync as km}from"fs";import{readFile as xm}from"fs/promises";import $m from"path";function na(e){try{return JSON.stringify(JSON.parse(e))}catch{return e}}function Sm(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
502
  ## Content source: Content Fragment
502
503
  This block renders an AEM **Content Fragment**${o} - not inline-authored copy.
503
504
  - UE model: use an \`aem-content-fragment\` field (e.g. \`name: "fragment"\`) for the CF reference.
@@ -510,36 +511,38 @@ This block mixes **two sources in one model and one \`decorate(block)\`**:
510
511
  - **Inline (UE-authored)** parts \u2192 normal fields (text / richtext / image / select) read straight from the authored DOM cells, with semantic collapsing.
511
512
  - **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
513
  - 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 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
+ `}async function oa(e){let t=await jm(e.projectRoot),n=Sm(e.contentSource,e.cfHint,e.blockName),o=e.screenshot===!0,i=e.provider??"figma",s=et[i],a=e.design,l=a?.mode==="file"?/\.(png|jpe?g|webp)$/i.test(a.filePath):!1,d=`## Step 5 \u2014 One Verification Pass (single pass, then stop)
514
515
  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==="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
+ 1. Compare your implementation to ${a?.mode==="spec"?"the exact values in the embedded design data from Step 1":a?.mode==="scrape"?"the exact values in the scraped design data from Step 1":a?.mode==="file"?l?"the local design image":"the exact values in the local SVG":a?.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
517
  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.`,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
+ 3. Briefly state what you checked and any value you had to infer.`,m=`Target: fileKey \`${e.figma?.fileKey}\`${e.figma?.nodeId?`, node \`${e.figma.nodeId}\``:" (no node selected \u2014 use the full page)"}.`,p;a?.mode==="spec"?p=`## Step 1 \u2014 Use the Provided Design Data (no MCP)
518
519
  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
520
 
520
521
  \`\`\`json
521
- ${s.spec}
522
+ ${na(a.spec)}
522
523
  \`\`\`
523
524
 
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).
525
+ 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.`:a?.mode==="scrape"?p=`## Step 1 \u2014 Use the Scraped Design Data (no MCP)
526
+ The design was scraped from the live **${s}** 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
 
527
528
  \`\`\`json
528
- ${s.spec}
529
+ ${na(a.spec)}
529
530
  \`\`\`
530
531
 
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)
532
- Read \`${s.filePath}\` with your **Read** tool. Do **not** call any Figma MCP tool.
532
+ If the page holds several sections, build **only** the one for \`${e.blockName}\` (the element whose class or \`data-block\` matches the block name) and read the rest only for shared tokens.
533
+
534
+ 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.`:a?.mode==="file"?p=`## Step 1 \u2014 Read the Local Design Export (no MCP)
535
+ Read \`${a.filePath}\` with your **Read** tool. Do **not** call any Figma MCP tool.
533
536
 
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)
537
+ ${l?"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."}`:a?.mode==="mcp"?p=`## Step 1 \u2014 Fetch the Design Once, Then Cache It (single MCP call)
535
538
  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.
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.
539
+ **Immediately after**, \`Write\` the raw design data you received to \`${a.cachePath}\` (pretty JSON) so re-runs and refine passes reuse it without another MCP call. Then generate from it.
537
540
 
538
- ${p}`:i==="figma"?m=`## Step 1 \u2014 Fetch the Design (single MCP call)
541
+ ${m}`:i==="figma"?p=`## Step 1 \u2014 Fetch the Design (single MCP call)
539
542
  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.":""}
540
543
 
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?`
544
+ ${m}`:p=`## Step 1 \u2014 Read the Design
545
+ Open the live **${s}** 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?`
543
546
  ## Step 4b \u2014 Universal Editor Authoring (REQUIRED, not optional)
544
547
  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.
545
548
 
@@ -614,14 +617,14 @@ Rules:
614
617
  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\`.
615
618
 
616
619
  **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:
617
- ${ze.map(y=>`- \`${y.id}\` \u2014 ${y.label}`).join(`
620
+ ${Ye.map(b=>`- \`${b.id}\` \u2014 ${b.label}`).join(`
618
621
  `)}
619
- `:"",g=s?.mode==="file"?"a design export":a,w=s?.mode==="file"?"design":`${a} design`;return`# Pixel-Perfect EDS Block from ${g}
622
+ `:"",g=a?.mode==="file"?"a design export":s,h=a?.mode==="file"?"design":`${s} design`;return`# Pixel-Perfect EDS Block from ${g}
620
623
 
621
624
  ## Task
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.
625
+ Generate an AEM Edge Delivery Services block named **\`${e.blockName}\`** that reproduces the ${h} **1:1 \u2014 pixel perfect**. Exact spacing, colors, typography, and layout. Not "close enough" \u2014 identical.
623
626
 
624
- ${m}
627
+ ${p}
625
628
 
626
629
  ## Step 2 \u2014 Extract Exact Values
627
630
  From the design data you fetched, record the **precise** values \u2014 do not approximate:
@@ -670,7 +673,7 @@ Content images and copy come from **authoring** (the document / DAM via UE), not
670
673
  - 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.
671
674
  - Always set \`width\`/\`height\` or \`aspect-ratio\` to avoid CLS.
672
675
 
673
- ${c}
676
+ ${d}
674
677
 
675
678
  ## EDS Block Conventions
676
679
  - **Full-width by default**: the block/section spans the **full viewport width** (full-bleed) \u2014 never a fixed or centered fixed-width box. Constrain only the *inner content* to a sensible \`max-width\` (centered) for line-length/readability, with fluid horizontal padding. The design frame's width (e.g. 1280px) is the content cap, not the section width.
@@ -693,13 +696,13 @@ ${t}
693
696
  4. **Minimise chat output (save tokens):** write the files directly with your editing tools \u2014 do **not** paste the generated code back into the chat, and skip step-by-step narration. End with a **\u22643-line** summary: files created + any value you had to infer.
694
697
  - **No shell access:** you can only read/write files and call the design MCP. Do **not** run \`eslint\`, \`stylelint\`, \`npm\`, \`npx\`, \`tsc\`, a build, or any shell/Bash command \u2014 those tools aren't granted and the attempts just fail and waste time. Write valid, clean, correctly-formatted files directly; linting/formatting is the project's job, not yours.
695
698
  5. Mobile-first CSS with breakpoints at 600px and 900px
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":""}
699
+ 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":""}${e.contentSource==="cf"||e.contentSource==="mixed"?"\n8. **Content Fragment (hard requirement - the CLI checks it):** the model has an `aem-content-fragment` field, and `decorate(block)` is `async` and `fetch()`es that fragment's data (GraphQL persisted query) before building the DOM. A block that only reads inline cells fails verification.":""}
697
700
 
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.
701
+ 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": "${a?.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.
699
702
 
700
703
  ---
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
704
+ *Prompt version: ${At}*
705
+ `}function ia(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
703
706
 
704
707
  The block already exists in \`blocks/${e.blockName}/\` and the author reviewed it in the live preview. Apply **this change** and nothing else:
705
708
 
@@ -718,9 +721,9 @@ The block already exists in \`blocks/${e.blockName}/\` and the author reviewed i
718
721
  - **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.
719
722
  - **Minimise chat output:** edit files directly, don't paste code back. End with a **\u22642-line** summary of what changed.
720
723
 
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(`
723
- `).filter(a=>a.trim().startsWith("--")).map(a=>a.trim()).join(`
724
+ *Prompt version: ${At}*
725
+ `}async function jm(e){let t=$m.join(e,"styles","styles.css");if(!km(t))return"";try{let o=(await xm(t,"utf-8")).match(/:root\s*\{([^}]+)\}/);if(!o)return"";let i=o[1].split(`
726
+ `).filter(s=>s.trim().startsWith("--")).map(s=>s.trim()).join(`
724
727
  `);return i?`
725
728
  ## Existing Project Tokens
726
729
  The project already defines these CSS custom properties in \`styles/styles.css\`.
@@ -731,7 +734,7 @@ Reuse them instead of hardcoding values:
731
734
  ${i}
732
735
  }
733
736
  \`\`\`
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>
737
+ `:""}catch{return""}}var At,et,ra=k(()=>{"use strict";f();bo();At="0.7.1",et={figma:"Figma",framer:"Framer",stitch:"Google Stitch"}});import{existsSync as Pm}from"fs";import{chmod as Em,mkdir as Cm}from"fs/promises";import{homedir as Tm}from"os";import sa from"path";function Jo(e){return sa.join(Tm(),".eds","auth",`${e}.json`)}function aa(e){return Pm(Jo(e))}async function ca(e){await Cm(sa.dirname(e),{recursive:!0,mode:448})}async function la(e){try{await Em(e,384)}catch{}}var da=k(()=>{"use strict";f()});import{emitKeypressEvents as Rm}from"readline";async function Ft(e){let t=process.stdin,n=vn.menu&&t.isTTY;await new Promise(o=>{let i=!1,s=async c=>{i||(i=!0,process.off("SIGINT",a),process.off("SIGTERM",a),n&&(t.off("keypress",l),t.setRawMode(!1),t.pause()),await e(),c&&process.exit(0),o())},a=()=>{s(!0)},l=(c,d)=>{d?.ctrl&&d.name==="c"?s(!0):(d?.name==="escape"||d?.name==="return")&&s(!1)};process.on("SIGINT",a),process.on("SIGTERM",a),n&&(Rm(t),t.setRawMode(!0),t.resume(),t.on("keypress",l))})}function Dt(){return vn.menu&&process.stdin.isTTY?"Press Esc or Enter to stop and go back to the menu (Ctrl+C quits).":"Press Ctrl+C to stop."}var vn,kn=k(()=>{"use strict";f();vn={menu:!1}});function ue(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Am(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 xn(e){let{blockName:t}=e,n=Am(e.sampleContent);return`<!DOCTYPE html>
735
738
  <html lang="en">
736
739
  <head>
737
740
  <meta charset="utf-8" />
@@ -761,19 +764,19 @@ ${n}
761
764
  try { new EventSource('/__eds_events').onmessage = () => location.reload(); } catch (e) { /* no SSE */ }
762
765
  </script>
763
766
  </body>
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">
767
+ </html>`}function Fm(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 ma(e){let t=e.map((o,i)=>{let s=Fm(o.breakpoints),a=o.breakpoints.map(d=>`<option value="${d.width}"${d.width===s.width?" selected":""}>${ue(d.label)}</option>`).join(""),l=o.figmaUrl?`<a class="figma-link" href="${ue(o.figmaUrl)}" target="_blank" rel="noopener">Figma \u2197</a>`:"",c=o.placeholder?'<span class="hint">placeholder content</span>':"";return`<section class="card">
765
768
  <div class="cardbar">
766
- <span class="block">${ce(o.blockName)}</span>
769
+ <span class="block">${ue(o.blockName)}</span>
767
770
  <select class="bp" data-i="${i}">
768
- ${s}
771
+ ${a}
769
772
  <option value="full">Full</option>
770
773
  </select>
774
+ ${c}
771
775
  ${l}
772
- ${d}
773
776
  </div>
774
777
  <div class="stage">
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>
778
+ <div class="device" data-i="${i}" data-w="${s.width}" style="width:${s.width}px">
779
+ <iframe src="${ue(o.frameRoute)}" title="${ue(o.blockName)} preview" loading="lazy"></iframe>
777
780
  </div>
778
781
  </div>
779
782
  </section>`}).join(`
@@ -822,16 +825,16 @@ ${n}
822
825
  try { new EventSource('/__eds_events').onmessage = () => location.reload(); } catch (e) { /* no SSE */ }
823
826
  </script>
824
827
  </body>
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">
828
+ </html>`}function pa(e){let{blockName:t,breakpoints:n,figmaUrl:o,frameRoute:i,placeholder:s}=e,a=n.filter(p=>p.figma),l=(a.length?a:n).reduce((p,u)=>u.width>p.width?u:p,n[0]),c=n.map(p=>`<option value="${p.width}"${p.width===l.width?" selected":""}>${ue(p.label)}</option>`).join(`
829
+ `),d=o?`<a class="figma-link" href="${ue(o)}" target="_blank" rel="noopener">
827
830
  <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>
828
831
  Open in Figma
829
- </a>`:"",p=a?`<span class="hint">placeholder content \u2014 add <code>blocks/${t}/_${t}.preview.html</code></span>`:"";return`<!DOCTYPE html>
832
+ </a>`:"",m=s?`<span class="hint">placeholder content \u2014 add <code>blocks/${t}/_${t}.preview.html</code></span>`:"";return`<!DOCTYPE html>
830
833
  <html lang="en">
831
834
  <head>
832
835
  <meta charset="utf-8" />
833
836
  <meta name="viewport" content="width=device-width, initial-scale=1" />
834
- <title>eds preview \u2014 ${ce(t)}</title>
837
+ <title>eds preview \u2014 ${ue(t)}</title>
835
838
  <style>
836
839
  *{box-sizing:border-box}
837
840
  html,body{margin:0;padding:0;background:#1f1f1f;color:#eaeaea;font-family:ui-sans-serif,-apple-system,"Segoe UI",sans-serif}
@@ -853,18 +856,18 @@ ${n}
853
856
  </head>
854
857
  <body>
855
858
  <div class="bar">
856
- <span class="label">Block</span><span class="block">${ce(t)}</span>
859
+ <span class="label">Block</span><span class="block">${ue(t)}</span>
857
860
  <label class="label" for="bp" style="margin-left:8px">Breakpoint</label>
858
861
  <select id="bp">
859
- ${l}
862
+ ${c}
860
863
  <option value="full">Full ca\u0142a szeroko\u015B\u0107</option>
861
864
  </select>
862
- ${p}
863
- ${c}
865
+ ${m}
866
+ ${d}
864
867
  </div>
865
868
  <div class="stage">
866
- <div class="device" id="device" data-w="${d.width}" style="width:${d.width}px">
867
- <iframe id="frame" src="${i}" title="${ce(t)} preview"></iframe>
869
+ <div class="device" id="device" data-w="${l.width}" style="width:${l.width}px">
870
+ <iframe id="frame" src="${i}" title="${ue(t)} preview"></iframe>
868
871
  </div>
869
872
  </div>
870
873
  <script>
@@ -878,24 +881,24 @@ ${n}
878
881
  setWidth(Number(bp.value));
879
882
  </script>
880
883
  </body>
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
884
+ </html>`}var ua=k(()=>{"use strict";f()});import{createReadStream as Dm,existsSync as Lm,statSync as Nm}from"fs";import Om from"http";import qo from"path";function $n(e,t,n,o="127.0.0.1",i){let s=qo.resolve(e),a=new Set,l=Om.createServer(async(c,d)=>{let m=decodeURIComponent((c.url??"/").split("?")[0]);if(m===Im){d.writeHead(200,{"content-type":"application/json"}),d.end(JSON.stringify({eds:!0}));return}if(m===_m){d.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),d.write(`: connected
882
885
 
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
886
+ `),a.add(d),c.on("close",()=>a.delete(d));return}let p=t[m];if(p){d.writeHead(200,{"content-type":p.type}),d.end(p.body);return}if(i)try{let g=await i(m);if(g){d.writeHead(200,{"content-type":g.type}),d.end(g.body);return}}catch(g){d.writeHead(500,{"content-type":"text/plain"}),d.end(`Preview error: ${g instanceof Error?g.message:String(g)}`);return}let u=qo.join(s,m);if(!u.startsWith(s)){d.writeHead(403),d.end("Forbidden");return}if(!Lm(u)||!Nm(u).isFile()){d.writeHead(404,{"content-type":"text/plain"}),d.end(`Not found: ${m}`);return}d.writeHead(200,{"content-type":Mm[qo.extname(u).toLowerCase()]??"application/octet-stream"}),Dm(u).pipe(d)});return new Promise((c,d)=>{let m=0,p=u=>{l.once("error",g=>{g.code==="EADDRINUSE"&&m<10?(m++,p(u+1)):d(g)}),l.listen(u,o,()=>{c({url:`http://${o}:${u}/`,port:u,reload:()=>{for(let g of a)g.write(`data: reload
884
887
 
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">
888
+ `)},close:()=>new Promise(g=>{for(let h of a)h.end();l.close(()=>g())})})})};p(n)})}var Mm,Im,_m,fa=k(()=>{"use strict";f();Mm={".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"},Im="/__eds_ping",_m="/__eds_events"});var Lt={};O(Lt,{FRAME_PREFIX:()=>Se,galleryPreview:()=>Wm,listPreviewableBlocks:()=>_e,loadBlockForPreview:()=>he,previewBlock:()=>Gm,startFrameServer:()=>tt,startPreview:()=>va});import{existsSync as ae,watch as ga}from"fs";import{readFile as Sn,readdir as Um}from"fs/promises";import ne from"path";import $e from"chalk";function Ko(e){return e<=480?`${e} mobile`:e<=1024?`${e} tablet`:`${e} desktop`}function ha(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"||o.source==="scrape"})).filter(o=>Number.isFinite(o.width)&&o.width>0):Hm.map(o=>({width:o,label:Ko(o),figma:!1}))}function wa(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 ba(e){return`<div class="${e} block">
886
889
  <div><div>
887
890
  <h2>${e} heading</h2>
888
891
  <p>Sample body copy for the preview. Replace with real authored content.</p>
889
892
  <p><a href="#">Primary action</a></p>
890
893
  <p><a href="#">Secondary action</a></p>
891
894
  </div></div>
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=`(() => {
895
+ </div>`}async function he(e,t,n){let o=ne.join(e,"blocks",t);if(!ae(ne.join(o,`${t}.css`))&&!ae(ne.join(o,`${t}.js`)))return null;let i=null,s=ne.join(o,".eds-meta.json");if(ae(s))try{i=JSON.parse(await Sn(s,"utf-8"))}catch{}let a=ne.join(o,`_${t}.preview.html`),l,c=!1;return ae(a)?l=await Sn(a,"utf-8"):(l=ba(t),c=!0),{name:t,sampleContent:l,breakpoints:ha(n,i),figmaUrl:wa(i),placeholder:c}}async function tt(e,t,n){return $n(e,{},n,"127.0.0.1",async i=>{if(!i.startsWith(Se))return;let s=i.slice(Se.length);if(!/^[a-z0-9-]+$/i.test(s))return;let a=await he(e,s,t);if(a)return{body:xn({blockName:s,breakpoints:a.breakpoints,sampleContent:a.sampleContent,frameRoute:Se+s}),type:"text/html; charset=utf-8"}})}async function _e(e){let t=ne.join(e,"blocks");if(!ae(t))return[];let n=await Um(t,{withFileTypes:!0}),o=[];for(let i of n){if(!i.isDirectory()||Bm.has(i.name))continue;let s=ne.join(t,i.name);(ae(ne.join(s,`${i.name}.css`))||ae(ne.join(s,`${i.name}.js`)))&&o.push(i.name)}return o.sort()}async function ya(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 va(e,t={}){let n=E();if(!n)return r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1,null;let o=ne.join(n,"blocks",e);if(!ae(o))return r.error(`Block "${e}" not found at blocks/${e}/.`),process.exitCode=1,null;if(!ae(ne.join(o,`${e}.css`))&&!ae(ne.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($e.dim(` It fetches the ${e==="header"?"nav":"footer"} fragment and needs the full page runtime.`)),r.info($e.dim(" Preview a content block instead (e.g. a block generated from a design).")));let i=null,s=ne.join(o,".eds-meta.json");if(ae(s))try{i=JSON.parse(await Sn(s,"utf-8"))}catch{}let a=ne.join(o,`_${e}.preview.html`),l,c=!1;ae(a)?l=await Sn(a,"utf-8"):(l=ba(e),c=!0);let d=ha(t.widths,i),m=wa(i),p="/__eds_preview_frame",u=xn({blockName:e,breakpoints:d,sampleContent:l,frameRoute:p}),g=pa({blockName:e,breakpoints:d,sampleContent:l,figmaUrl:m,frameRoute:p,placeholder:c}),h=Number.parseInt(t.port??"8777",10),b=await $n(n,{"/":{body:g,type:"text/html; charset=utf-8"},[p]:{body:u,type:"text/html; charset=utf-8"}},Number.isFinite(h)?h:8777);r.logoOnce(T(`Preview \u2014 ${e}`)),r.info(S("Live preview",b.url)),r.info(R("pass","breakpoints",`${d.map(w=>`${w.width}${w.figma?"\u2713":""}`).join(", ")}, Full`)),c&&r.info(R("warn","content",`placeholder \u2014 add blocks/${e}/_${e}.preview.html for real content`));let y,v=ga(o,{recursive:!0},()=>{clearTimeout(y),y=setTimeout(()=>b.reload(),150)});return r.info(""),r.info(` ${$e.bold("\u279C")} ${$e.cyan(b.url)}`),r.info(R("pass","live reload","edits to the block refresh the browser")),t.open!==!1&&await ya(b.url),{url:b.url,close:async()=>{v.close(),await b.close()}}}async function Gm(e,t={}){let n=await va(e,t);n&&(r.info($e.dim(` ${Dt()}
896
+ `)),await Ft(n.close))}async function Wm(e={}){let t=E();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}let n="/__eds_frame/",o=async d=>{if(d==="/"){let m=await _e(t),p=[];for(let u of m){let g=await he(t,u,e.widths);g&&p.push({blockName:u,breakpoints:g.breakpoints,frameRoute:n+u,figmaUrl:g.figmaUrl,placeholder:g.placeholder})}return{body:ma(p),type:"text/html; charset=utf-8"}}if(d.startsWith(n)){let m=d.slice(n.length);if(!/^[a-z0-9-]+$/i.test(m))return;let p=await he(t,m,e.widths);return p?{body:xn({blockName:m,breakpoints:p.breakpoints,sampleContent:p.sampleContent,frameRoute:n+m}),type:"text/html; charset=utf-8"}:void 0}},i=Number.parseInt(e.port??"8777",10),s=await $n(t,{},Number.isFinite(i)?i:8777,"127.0.0.1",o),a=await _e(t);r.logoOnce(T("Preview \u2014 gallery")),r.info(S("Live gallery",s.url)),r.info(R(a.length?"pass":"warn","blocks",a.length?a.join(", "):"none yet \u2014 generate one with eds block from-design"));let l,c=ga(ne.join(t,"blocks"),{recursive:!0},()=>{clearTimeout(l),l=setTimeout(()=>s.reload(),150)});r.info(""),r.info(` ${$e.bold("\u279C")} ${$e.cyan(s.url)}`),r.info(R("pass","live reload","new & edited blocks refresh the browser")),r.info($e.dim(` ${Dt()}
897
+ `)),e.open!==!1&&await ya(s.url),await Ft(async()=>{c.close(),await s.close()})}var Bm,Hm,Se,Ue=k(()=>{"use strict";f();D();ua();fa();z();kn();_();Bm=new Set(["header","footer"]),Hm=[375,768,1280];Se="/__eds_frame/"});var Xo={};O(Xo,{blockFromDesign:()=>ep});import{existsSync as ce}from"fs";import{readFile as je,writeFile as zm}from"fs/promises";import q from"path";import{fileURLToPath as Jm}from"url";import P from"chalk";import jn from"ora";function qm(){let e=q.dirname(Jm(import.meta.url));return[q.resolve(e,"../../samples/hero.svg"),q.resolve(e,"../../../samples/hero.svg")].find(n=>ce(n))??null}async function Km(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 Vm(e){let{input:t,select:n,confirm:o}=await Promise.resolve().then(()=>(H(),B)),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"}),s=await t({message:"2/7 Component name",validate:w=>Re.test(w.trim())||"Use kebab-case, e.g. hero-banner"}),a=e??await t({message:`3/7 ${et[i]} link`,validate:w=>{if(!w.trim())return"Paste the design link";if(i!=="figma")return/^https?:\/\//i.test(w.trim())||"Paste a public http(s) URL to the page";try{return yn(w.trim()),!0}catch(A){return A.message}}}),l=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"}),c;(l==="cf"||l==="mixed")&&(c=(await t({message:" CF model / GraphQL persisted-query name (optional)"})).trim()||void 0);let d=await o({message:"5/7 Generate the Universal Editor model?",default:!0}),m=await o({message:"6/7 Add a screenshot MCP call for a pixel check? (off = one fewer MCP call)",default:!1}),p=await gn(),u=await n({message:"7/7 Run with",choices:[...p.map(w=>({name:`${w.type}${i==="figma"&&!w.hasFigmaMcp?" (Figma MCP not detected)":""}`,value:`agent:${w.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=et[i].toLowerCase();r.info(S("Summary"));let h=U(["component",g,"content","ue model","screenshot","run"]);r.info(j("component",s,h));let b=i==="figma"?(()=>{let w=yn(a.trim());return w.nodeId?`node ${w.nodeId}`:w.fileKey})():a.trim();if(r.info(j(g,b,h)),r.info(j("content",l+(c?` (${c})`:""),h)),r.info(j("ue model",d?"yes":"no",h)),r.info(j("screenshot",m?"yes":"no (token-lean)",h)),r.info(j("run",u.replace("agent:",""),h)),r.info(""),!await o({message:"Generate this block?",default:!0}))return null;let v={figmaUrl:a.trim(),name:s,provider:i,source:l,cfHint:c,ueModel:d,screenshot:m};return u==="dry-run"?v.dryRun=!0:u==="none"?v.agent="none":(v.agent=u.replace("agent:",""),v.yes=!0),v}function Vo(e){return e&&e.replace(/[-_\s]+/g,"-").replace(/[^a-z0-9-]/gi,"").toLowerCase().replace(/^-+|-+$/g,"")||"design-block"}function Xm(e){try{let t=new URL(e);return t.pathname.split("/").filter(Boolean).pop()||t.hostname.split(".")[0]}catch{return""}}function Ym(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 Zm(e){if(/^[a-z][a-z0-9+.-]*:\/\//i.test(e))return null;let t=q.isAbsolute(e)?e:q.resolve(process.cwd(),e);return!ce(t)||!Qm.has(q.extname(t).toLowerCase())?null:t}async function ep(e,t){let n=E();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 L=qm();if(!L){r.error("Bundled sample design not found (samples/hero.svg)."),process.exitCode=1;return}o=L,i={name:"hero",provider:"figma",...i},r.info(` ${J.pass} Sample design ${P.dim("Kiri Bloom hero")} ${P.dim("(bundled \xB7 no token \xB7 no MCP)")}`)}if(!o){let L=await Vm(o);if(!L){r.info("Cancelled.");return}o=L.figmaUrl,i={...i,...L}}let s=i.provider;if(s&&!(s in et)){r.error(`Unknown --provider "${s}". Use: figma, framer or stitch.`),process.exitCode=1;return}if(i.source&&!ka.includes(i.source)){r.error(`Unknown --source "${i.source}". Use: ${ka.join(", ")}.`),process.exitCode=1;return}let a=s??Ym(o)??"figma",l=et[a],c=Zm(o),d=c?c.startsWith(n+q.sep)?q.relative(n,c):c:void 0,m=null,p=d??o;if(c)r.info(` ${J.pass} Local design file ${P.dim(d)} ${P.dim("(no Figma MCP)")}`);else if(a==="figma"){let L=jn("Parsing Figma URL...").start();try{m=yn(o),L.succeed(`Parsed Figma URL ${P.dim(m.nodeId?`node ${m.nodeId}`:`file ${m.fileKey}`)}`)}catch(le){L.fail(le.message),process.exitCode=1;return}}else r.info(` ${J.pass} ${l} design ${P.dim(p)}`);let u=i.name||(c?Vo(q.basename(c,q.extname(c))):m?Vo(m.fileName):o?Vo(Xm(o)):"");if(!Re.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&&m?.nodeId&&(r.warn(`Block name "${u}" came from the Figma file name, not the selected frame.`),r.info(P.dim(` Pass ${P.cyan("--name <kebab-case>")} for a cleaner block name.`)));let g=await pe(n),h=g.figma?.token??process.env.FIGMA_TOKEN??process.env.FIGMA_PAT,b;if(zo(a)&&!c&&!i.dryRun&&(i.auth||i.authRefresh))if(b=Jo(a),i.authRefresh||!aa(a)){let L=(()=>{try{return new URL(o).origin}catch{return o}})();r.info(` ${P.dim("\u2192")} Opening ${P.cyan(l)} \u2014 click ${P.cyan("Sign In")} and log in, then come back here.`);let{input:le}=await Promise.resolve().then(()=>(H(),B));try{await ca(b),await Us({loginUrl:L,statePath:b,projectRoot:n,waitForUser:async()=>{await le({message:"Press Enter once you're signed in (you don't need to open the design)"})}}),await la(b),r.info(` ${J.pass} Session saved ${P.dim(b)}`)}catch(re){r.error(`Could not capture the ${l} session: ${re instanceof Error?re.message:String(re)}`),process.exitCode=1;return}}else r.info(` ${J.pass} Using saved ${l} session ${P.dim(b)} ${P.dim("(--auth-refresh to re-login)")}`);let y=jn("Resolving design source...").start(),v=await Zs({figma:m,localFile:d,token:h,projectRoot:n,preferMcp:i.mcp,refresh:i.refresh,provider:a,designUrl:c?void 0:o,storageStatePath:b,dryRun:i.dryRun,restPerMinute:g.figma?.restPerMinute,onRestWait:L=>{y.text=`Resolving design source... waiting ${Math.ceil(L/1e3)} s for a Figma REST slot (${g.figma?.restPerMinute??Uo}/min)`}});if(v.scrapeError){y.fail(`Scrape failed: ${v.scrapeError}`),r.info(P.dim(` Check the URL is a public ${l} page, and that Chromium is installed (${P.cyan("npx playwright install chromium")}).`)),process.exitCode=1;return}if(v.rateLimit){y.fail(v.rateLimit.message),r.info(P.dim(" The limit follows the plan that owns the file: 20 calls/month on Starter or with a View/Collab seat, 10-20/min with a Dev/Full seat on a paid plan.")),r.info(P.dim(` Not falling back to Figma MCP (its budget is the same or smaller). Re-run after the reset, pass ${P.cyan("--mcp")} to spend an MCP call instead, or export the frame as PNG/SVG (no quota).`)),v.rateLimit.upgradeLink&&r.info(P.dim(` Plan details: ${v.rateLimit.upgradeLink}`)),process.exitCode=1;return}if(y.succeed(`Design source ${P.dim(v.summary)}`),v.restError&&r.warn(`Figma REST fetch failed, using MCP fallback: ${v.restError}`),v.design?.mode==="scrape"&&!i.dryRun)try{let L=JSON.parse(v.design.spec),le=(L.title??"").toLowerCase(),re=v.design.spec.toLowerCase(),Ht=/isn'?t shared|doesn'?t exist|page not found|\b404\b/;(Ht.test(le)||Ht.test(re)||/\bsign[ -]?in\b|\blog[ -]?in\b/.test(le)||(L.nodeCount??0)<8)&&(r.warn(`The scraped page looks like a login / error shell${L.title?` ("${L.title}")`:""} \u2014 the design may be gated or the URL wrong.`),r.info(P.dim(` Use ${P.cyan("--auth")} to log in once (or ${P.cyan("--auth-refresh")} to re-login), and confirm the URL opens the design when you're signed in.`)))}catch{}let w=jn("Reading design tokens & building prompt...").start(),A=await oa({provider:a,figma:m,designRef:p,blockName:u,projectRoot:n,withUeModel:i.ueModel!==!1,contentSource:i.source??"document",cfHint:i.cfHint,screenshot:i.screenshot===!0,design:v.design}),X=await Do(A,n),K=ce(q.join(n,"styles","styles.css"));if(w.succeed(K?`Loaded design tokens ${P.dim("styles/styles.css")}`:`Built prompt ${P.dim("no project tokens found")}`),r.info(P.dim(` prompt \u2192 ${X}`)),i.dryRun){r.info(""),r.info(P.yellow("Dry run mode \u2014 prompt generated but agent not invoked.")),r.info(`Prompt file: ${P.cyan(X)}`),r.info(`Block name: ${P.cyan(u)}`),r.info(`Prompt version: ${At}`),r.info(""),r.info("Preview:"),r.info(P.dim("\u2500".repeat(60))),console.log(A);return}let Ce=i.agent||g.agent;if(i.agent==="none"){r.info("Agent skipped (--agent none). Use the prompt file manually:"),r.info(` ${P.cyan(X)}`);return}let Bt=jn("Detecting AI agent...").start(),Y=await Cs(Ce);if(!Y){Bt.fail("No AI agent found (claude, cursor, or codex)."),r.info(`Install Claude Code: ${P.cyan("npm install -g @anthropic-ai/claude-code")}`),r.info(`Or use the prompt file manually: ${P.cyan(X)}`),process.exitCode=1;return}if(Bt.succeed(`Agent ready ${P.cyan(Y.type)} ${P.dim(Y.path)}`),(v.design?.mode==="mcp"||!v.design&&a==="figma")&&a==="figma"&&!Y.hasFigmaMcp&&(r.warn(`Figma MCP may not be configured for ${Y.type}.`),r.info(`Run ${P.cyan("eds figma setup")} to configure it, or set a Figma token for REST.`)),!i.yes){let{confirm:L}=await Promise.resolve().then(()=>(H(),B));if(!await L({message:`Run ${Y.type} with the generated prompt?`,default:!0})){r.info(`Prompt saved to: ${P.cyan(X)}`);return}}let ic=v.design?.mode==="spec"?"embedded design (no MCP)":v.design?.mode==="scrape"?`scraped ${l} page (no MCP)`:v.design?.mode==="file"?`reading ${d}`:v.design?.mode==="mcp"?`via ${l} MCP (1 call, cached)`:`via ${l} MCP`;r.info(` ${P.dim("\u2192")} Handing off to ${P.cyan(Y.type)} ${P.dim(ic)}`),v.design?.mode==="mcp"&&r.info(P.dim(" get_design_context \xD71 \u2192 cache"));let rc=i.source==="cf"||i.source==="mixed",Dn=g.model??(rc&&Y.type==="claude"?"sonnet":void 0);if(Dn&&!g.model&&r.info(P.dim(` Model: ${Dn} (Content Fragment source)`)),!await Lo(Y,X,n,Dn)){process.exitCode=1;return}let at=q.join(n,"blocks",u);if(!(ce(q.join(at,`${u}.js`))||ce(q.join(at,`${u}.css`)))){r.warn(`No block files were written to blocks/${u}/ \u2014 nothing to preview.`),v.design?.mode==="mcp"&&!Y.hasFigmaMcp?(r.info(P.dim(` The agent couldn't read the design: no ${l} MCP is configured for ${Y.type}.`)),r.info(P.dim(` Run ${P.cyan("eds figma setup")}, or set a Figma token (FIGMA_TOKEN) to use REST, then re-run.`))):v.design?.mode==="mcp"?(r.info(P.dim(" The agent couldn't read the design, so it generated nothing. Common cause: the")),r.info(P.dim(` ${l} MCP tool-call limit (e.g. Figma Starter plan). See the log above.`)),r.info(P.dim(" Wait for the limit to reset or upgrade the plan, then re-run the same command."))):r.info(P.dim(" The agent generated nothing \u2014 see the log above for why.")),process.exitCode=1;return}let sc=await np(at,u,i.ueModel!==!1,i.source??"document");if(ce(at)){let L=q.join(at,".eds-meta.json"),le;if(ce(L))try{le=JSON.parse(await je(L,"utf-8")).breakpoints}catch{}let re=Ns(i.widths,le),Ht={provider:a,designRef:p,figmaFileKey:m?.fileKey??null,figmaNodeId:m?.nodeId??null,lastSyncedAt:new Date().toISOString(),promptVersion:At,agentUsed:Y.type,...re.length?{breakpoints:re}:{}};await zm(L,`${JSON.stringify(Ht,null,2)}
898
+ `),re.length&&r.info(P.dim(` Preview breakpoints: ${re.map($i=>$i.width).join(" \xB7 ")}`))}if(!sc){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:L}=await Promise.resolve().then(()=>(H(),B));if(await L({message:"Instrument this block for analytics (dataLayer)?",default:!1})){let{trackBlock:re}=await Promise.resolve().then(()=>(xt(),kt));await re(u,{})}}if(!i.yes)await tp({blockName:u,projectRoot:n,agent:Y,model:g.model,provider:a,figma:m,designRef:p});else if(i.serve){let{previewBlock:L}=await Promise.resolve().then(()=>(Ue(),Lt));await L(u,{})}else r.info(` ${P.dim("\u2192")} Next: ${P.cyan(`eds block preview ${u}`)}`)}async function tp(e){let{select:t,input:n}=await Promise.resolve().then(()=>(H(),B)),{startPreview:o}=await Promise.resolve().then(()=>(Ue(),Lt)),i=null;for(r.info("");;){let s=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(s==="done")break;if(s==="preview"){await Km()?r.info(P.dim(" A preview server is already running at http://127.0.0.1:8777.")):i=await o(e.blockName,{});continue}let a=(await n({message:"Describe the change:"})).trim();if(!a)continue;let l=ia({blockName:e.blockName,feedback:a,provider:e.provider,figma:e.figma,designRef:e.designRef}),c=await Do(l,e.projectRoot);r.info(` ${P.dim("\u2192")} Applying your change with ${P.cyan(e.agent.type)}\u2026`),await Lo(e.agent,c,e.projectRoot,e.model)}if(i){let s=i;r.info(P.dim(` Preview still live at ${s.url}. ${Dt()}
899
+ `)),await Ft(s.close)}}async function np(e,t,n,o="document"){let i=[],s=q.join(e,`${t}.js`),a=q.join(e,`${t}.css`),l=ce(s),c=ce(a);if(i.push({status:l?"pass":"fail",name:`${t}.js`,message:l?"created":"missing \u2014 agent did not write the JS file"}),i.push({status:c?"pass":"fail",name:`${t}.css`,message:c?"created":"missing \u2014 agent did not write the CSS file"}),l){let m=await je(s,"utf-8");i.push({status:/export\s+default/.test(m)?"pass":"fail",name:"decorate export",message:/export\s+default/.test(m)?"found":"no default export \u2014 block won't load"}),m.includes("console.log")&&i.push({status:"warn",name:"no console.log",message:"found console.log \u2014 remove before production"})}if(c){let m=await je(a,"utf-8");i.push({status:m.includes(`.${t}`)?"pass":"warn",name:"scoped CSS",message:m.includes(`.${t}`)?`scoped to .${t}`:`no .${t} selector \u2014 styles may leak`})}if(n){let m=ce(q.join(e,`_${t}.json`)),p=q.join(e,"..","..","component-models.json"),u=!1;if(!m&&ce(p))try{u=(await je(p,"utf-8")).includes(`"${t}"`)}catch{}let g=m||u;if(i.push({status:g?"pass":"warn",name:"Universal Editor model",message:g?m?`_${t}.json created`:"added to component-models.json":`missing \u2014 no _${t}.json (run with default UE generation, or --no-ue-model to skip)`}),m&&l)try{let h=await je(q.join(e,`_${t}.json`),"utf-8"),b=await je(s,"utf-8"),y=/"resourceType"\s*:\s*"[^"]*\/item"/.test(h)||/"filter"\s*:/.test(h)||/"multi"\s*:\s*true/.test(h),v=/\.children/.test(b)||/\bfor\s*\(/.test(b)||/\.forEach\s*\(/.test(b);y&&i.push({status:v?"pass":"warn",name:"multifield wired",message:v?"decorate() iterates items":"repeatable model but decorate() never iterates block.children \u2014 only one item will render"})}catch{}}if((o==="cf"||o==="mixed")&&l){let m=await je(s,"utf-8"),p=q.join(e,`_${t}.json`),g=(ce(p)?await je(p,"utf-8"):"").includes("aem-content-fragment"),h=/\bfetch\s*\(/.test(m);i.push({status:g&&h?"pass":"warn",name:"content fragment",message:g&&h?"CF field in the model, fetched in decorate()":[!g&&"no aem-content-fragment field in the model",!h&&"decorate() never fetches the fragment"].filter(Boolean).join("; ")})}r.info(S("Verification"));let d=U(i.map(m=>m.name));for(let m of i)r.info(R(m.status,m.name,m.message,d));return r.info(""),!i.some(m=>m.status==="fail")}var ka,Qm,Yo=k(()=>{"use strict";f();Fo();Rs();xe();Os();ea();ta();bn();ra();D();z();Je();da();_o();kn();_();ka=["document","ue","cf","mixed"],Qm=new Set([".svg",".png",".jpg",".jpeg",".webp"])});var xa={};O(xa,{listBlocks:()=>rp});import{existsSync as Nt}from"fs";import{readFile as op,readdir as ip}from"fs/promises";import nt from"path";import ot from"chalk";async function rp(e={}){let t=E();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}let n=nt.join(t,"blocks");if(!Nt(n)){r.info("No blocks/ directory found.");return}let o=await ip(n,{withFileTypes:!0}),i=[];for(let a of o){if(!a.isDirectory())continue;let l=a.name,c=nt.join(n,l),d={name:l,hasJs:Nt(nt.join(c,`${l}.js`)),hasCss:Nt(nt.join(c,`${l}.css`)),hasUeModel:Nt(nt.join(c,`_${l}.json`))},m=nt.join(c,".eds-meta.json");if(Nt(m))try{let p=JSON.parse(await op(m,"utf-8"));d.figmaSource={fileKey:p.figmaFileKey,nodeId:p.figmaNodeId,lastSyncedAt:p.lastSyncedAt}}catch{}i.push(d)}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 s=U(i.map(a=>a.name));for(let a of i){let l=[a.hasJs?M.ok("js"):ot.dim.strikethrough("js"),a.hasCss?M.ok("css"):ot.dim.strikethrough("css")];a.hasUeModel&&l.push(M.blue("ue-model")),a.figmaSource&&l.push(`${J.figma} ${M.dotPurple("figma")}`);let c=ct(ot.bold(a.name),s);if(r.info(` ${c} ${ot.dim("[")}${l.join(" ")}${ot.dim("]")}`),a.figmaSource){let d=new Date(a.figmaSource.lastSyncedAt).toLocaleDateString();r.info(` ${" ".repeat(s)} ${J.arrow} ${ot.dim(`figma:${a.figmaSource.fileKey} \xB7 synced ${d}`)}`)}}r.info("")}var $a=k(()=>{"use strict";f();D();z();_()});import Sa from"path";function Qo(e,t){return Sa.join(e,"blocks",t,"__snapshots__")}function Pa(e,t,n){return Sa.join(Qo(e,t),`${t}-${n}.png`)}function Ot(e){return`${(e*100).toFixed(2)}%`}async function Zo(e,t,n,o=900){let i;try{({chromium:i}=await import("playwright"))}catch{throw new Error(ja)}let s=await i.launch();try{let a=await s.newPage({viewport:{width:t,height:o}});await a.goto(e,{waitUntil:"networkidle"}),await a.waitForTimeout(300);let l=n?a.locator(n).first():null;return l&&await l.count()?await l.screenshot():await a.screenshot({fullPage:!0})}finally{await s.close()}}async function Ea(){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(ja)}}async function Ca(e,t){let{PNG:n,pixelmatch:o}=await Ea(),i=n.sync.read(e),s=n.sync.read(t);if(i.width!==s.width||i.height!==s.height)return{diffPixels:-1,totalPixels:0,ratio:1,sizeMismatch:!0,width:i.width,height:i.height,otherWidth:s.width,otherHeight:s.height};let{width:a,height:l}=i,c=new n({width:a,height:l}),d=o(i.data,s.data,c.data,a,l,{threshold:.1}),m=a*l;return{diffPixels:d,totalPixels:m,ratio:m?d/m:0,width:a,height:l,diffPng:n.sync.write(c)}}async function Ta(e,t){let{PNG:n,pixelmatch:o}=await Ea(),i=n.sync.read(e),s=n.sync.read(t),a=Math.min(i.width,s.width),l=Math.min(i.height,s.height),c=new n({width:a,height:l}),d=new n({width:a,height:l});n.bitblt(i,c,0,0,a,l,0,0),n.bitblt(s,d,0,0,a,l,0,0);let m=new n({width:a,height:l}),p=o(c.data,d.data,m.data,a,l,{threshold:.1}),u=a*l;return{diffPixels:p,totalPixels:u,ratio:u?p/u:0,width:a,height:l,diffPng:n.sync.write(m)}}var ja,Ra=k(()=>{"use strict";f();ja=`Visual testing needs extra tools. Install them with:
900
+ npm i -D playwright pixelmatch pngjs && npx playwright install chromium`});var Na={};O(Na,{visualTest:()=>ap});import{existsSync as Aa}from"fs";import{mkdir as ei,readFile as Fa,writeFile as Mt}from"fs/promises";import we from"path";import ti from"chalk";async function ap(e,t={}){let n=E();if(!n){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}if(t.design){await cp(n,e,t);return}let o=e?[e]:await _e(n);if(!o.length){r.warn("No previewable blocks to test.");return}let i=Number.parseInt(t.port??"8788",10),s=await tt(n,t.widths,Number.isFinite(i)?i:8788),a=Number.parseFloat(t.threshold??"0.01"),l=we.join(n,"tmp","eds-cli","visual-diff");r.logoOnce(T("Visual test"));let c=0,d=0,m=0,p=0;try{for(let u of o){let g=await he(n,u,t.widths);if(g){r.info(S(u));for(let h of g.breakpoints){let b=await Zo(Da(s.url,u),h.width,La(u)),y=Pa(n,u,h.width),v=Aa(y);if(t.update||!v){await ei(Qo(n,u),{recursive:!0}),await Mt(y,b),v?(p++,r.info(R("pass",`${h.width}px`,"baseline updated"))):(m++,r.info(R("pass",`${h.width}px`,"baseline created")));continue}let w=await Ca(await Fa(y),b);if(w.sizeMismatch){d++;let A=w.height===sp&&(w.otherHeight??0)<w.height;r.info(R("fail",`${h.width}px`,A?`baseline is an older full-page shot (${w.width}\xD7${w.height}) \u2014 re-run with --update`:`size changed ${w.width}\xD7${w.height} \u2192 ${w.otherWidth}\xD7${w.otherHeight}`));continue}if(w.ratio>a){d++,await ei(l,{recursive:!0});let A=we.join(l,`${u}-${h.width}.diff.png`);w.diffPng&&await Mt(A,w.diffPng),r.info(R("fail",`${h.width}px`,`${Ot(w.ratio)} changed \u2192 ${we.relative(n,A)}`))}else c++,r.info(R("pass",`${h.width}px`,w.ratio>0?`${Ot(w.ratio)} (within ${Ot(a)})`:"identical"))}}}}catch(u){r.error(u instanceof Error?u.message:String(u)),process.exitCode=1;return}finally{await s.close()}r.info(""),r.info(`${ti.green(`${c} passed`)} \xB7 ${ti.yellow(`${d} changed`)} \xB7 ${m} new \xB7 ${p} updated`),d>0&&(r.warn(`${d} 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 cp(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 he(e,t,n.widths);if(!o){r.error(`Block "${t}" has no css/js to render.`),process.exitCode=1;return}let i,s,a=we.join(e,"blocks",t,".eds-meta.json");if(Aa(a))try{let g=JSON.parse(await Fa(a,"utf-8"));i=g.figmaFileKey??void 0,s=g.figmaNodeId??void 0}catch{}if(!i||!s){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 pe(e),c=l.figma?.token??process.env.FIGMA_TOKEN??process.env.FIGMA_PAT;if(!c){r.error("Design diff needs a Figma token (FIGMA_TOKEN or figma.token) to render the node."),process.exitCode=1;return}let d=o.breakpoints.filter(g=>g.figma),m=(d.length?d:o.breakpoints).reduce((g,h)=>h.width>g.width?h:g,o.breakpoints[0]).width,p=Number.parseInt(n.port??"8788",10),u=await tt(e,n.widths,Number.isFinite(p)?p:8788);r.logoOnce(T("Design \u2194 render")),r.info(S(t,`${m}px`));try{let g=await Zo(Da(u.url,t),m,La(t));r.info(R("pass","render","block screenshot captured"));let h=await Ks({fileKey:i,nodeId:s,token:c,scale:1,pace:()=>wn({logPath:hn(e),perMinute:l.figma?.restPerMinute,onWait:v=>r.info(R("warn","design",`waiting ${Math.ceil(v/1e3)} s for a Figma REST slot`))})});r.info(R("pass","design","Figma image fetched (REST)"));let b=await Ta(h,g),y=we.join(e,"tmp","eds-cli","visual-diff");await ei(y,{recursive:!0}),await Mt(we.join(y,`${t}-design.png`),h),await Mt(we.join(y,`${t}-render.png`),g),b.diffPng&&await Mt(we.join(y,`${t}-design-diff.png`),b.diffPng),r.info(R("warn","diff",`~${Ot(b.ratio)} different over ${b.width}\xD7${b.height} (approximate)`)),r.info(""),r.info(ti.dim(` Saved design / render / diff to ${we.relative(e,y)}/${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 Da,La,sp,Oa=k(()=>{"use strict";f();xe();bn();Wo();D();Ra();z();_();Ue();Da=(e,t)=>`${e}${Se.slice(1)}${t}`,La=e=>`body > .${e}`,sp=900});async function Ma(e,t,n){let o;try{({chromium:o}=await import("playwright"))}catch{throw new Error(lp)}let i=await o.launch();try{let s=await i.newPage({viewport:{width:t,height:900}});await s.goto(e,{waitUntil:"networkidle"}),await s.waitForTimeout(200);let a=await s.evaluate(dp);return n&&a.push(...await s.evaluate(`(${mp})(${JSON.stringify(n)})`)),a}finally{await i.close()}}var lp,dp,mp,Ia=k(()=>{"use strict";f();lp=`Content checks need Playwright. Install it with:
901
+ npm i -D playwright && npx playwright install chromium`,dp=`(() => {
899
902
  const out = [];
900
903
  const root = document.querySelector('[class$="block"]') || document.body;
901
904
  const trunc = (s) => (s || '').slice(0, 60);
@@ -909,10 +912,22 @@ ${n}
909
912
  for (const img of root.querySelectorAll('img')) {
910
913
  const src = trunc(img.getAttribute('src'));
911
914
  if (!img.hasAttribute('alt')) out.push({ level: 'warn', rule: 'img-alt', detail: '<img> without alt (use alt="" if decorative): ' + src });
915
+ // A rendered <img> always has a computed px height, so look for what
916
+ // actually reserves its box: width/height attributes, an aspect-ratio, or a
917
+ // stylesheet height on the image.
912
918
  const cs = getComputedStyle(img);
919
+ const cssHeight = [...document.styleSheets].some((sheet) => {
920
+ let rules;
921
+ try { rules = sheet.cssRules; } catch { return false; }
922
+ return [...rules].some((r) => {
923
+ const h = r.style && r.style.height;
924
+ return h && h !== 'auto' && r.selectorText && img.matches(r.selectorText);
925
+ });
926
+ });
913
927
  const hasDims = (img.hasAttribute('width') && img.hasAttribute('height'))
914
928
  || (cs.aspectRatio && cs.aspectRatio !== 'auto')
915
- || (cs.height && cs.height !== 'auto' && cs.height !== '0px');
929
+ || (img.style.height && img.style.height !== 'auto')
930
+ || cssHeight;
916
931
  if (!hasDims) out.push({ level: 'warn', rule: 'img-cls', detail: '<img> without width/height or aspect-ratio (CLS risk): ' + src });
917
932
  }
918
933
  for (const a of root.querySelectorAll('a')) {
@@ -929,14 +944,28 @@ ${n}
929
944
  }
930
945
  }
931
946
  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`
947
+ })()`,mp=`(html) => {
948
+ const doc = new DOMParser().parseFromString(html, 'text/html');
949
+ const root = doc.querySelector('.block') || doc.body.firstElementChild;
950
+ if (!root) return [];
951
+ let wrapped = 0, cells = 0;
952
+ for (const row of root.children) {
953
+ for (const cell of row.children) {
954
+ cells++;
955
+ const only = cell.children.length === 1 ? cell.firstElementChild : null;
956
+ const ownText = [...cell.childNodes].some((n) => n.nodeType === 3 && n.textContent.trim());
957
+ if (only && only.tagName === 'DIV' && !ownText) wrapped++;
958
+ }
959
+ }
960
+ return wrapped ? [{ level: 'warn', rule: 'mock-nesting', detail: wrapped + ' of ' + cells + ' cells in the preview mock wrap their content in an extra <div>; EDS delivers row > cell > content' }] : [];
961
+ }`});var _a={};O(_a,{blockCheck:()=>pp});import ni from"chalk";async function pp(e,t={}){let n=E();if(!n){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}let o=e?[e]:await _e(n);if(!o.length){r.warn("No previewable blocks to check.");return}let i=Number.parseInt(t.port??"8789",10),s=await tt(n,t.widths,Number.isFinite(i)?i:8789);r.logoOnce(T("Content check"));let a=0,l=0,c=0;try{for(let d of o){let m=await he(n,d,t.widths);if(!m)continue;let p=m.breakpoints.reduce((g,h)=>h.width>g.width?h:g,m.breakpoints[0]).width,u=await Ma(`${s.url}${Se.slice(1)}${d}`,p,m.placeholder?void 0:m.sampleContent);if(r.info(S(d,`${p}px`)),!u.length){c++,r.info(R("pass","clean","no issues"));continue}for(let g of u)g.level==="error"?a++:l++,r.info(R(g.level==="error"?"fail":"warn",g.rule,g.detail))}}catch(d){r.error(d instanceof Error?d.message:String(d)),process.exitCode=1;return}finally{await s.close()}r.info(""),r.info(`${ni.green(`${c} clean`)} \xB7 ${ni.red(`${a} error(s)`)} \xB7 ${ni.yellow(`${l} warning(s)`)}`),(a>0||t.strict&&l>0)&&(process.exitCode=1)}var Ua=k(()=>{"use strict";f();D();Ia();z();_();Ue()});function Ba(e){return Pn.find(t=>t.id===e)}function Ha(e,t){return`
933
962
  // \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
934
963
  {
935
964
  ${t.split(`
936
965
  `).map(n=>n&&` ${n}`).join(`
937
966
  `)}
938
967
  }
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).
968
+ `}var Pn,Ga=k(()=>{"use strict";f();Pn=[{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).
940
969
  import { loadGTM } from './analytics.js';
941
970
  import pageMetaPush from './page-meta.js';
942
971
 
@@ -1027,19 +1056,19 @@ document.head.appendChild(cb);`},{id:"custom",name:"Custom third-party script",f
1027
1056
  const s = document.createElement('script');
1028
1057
  s.async = true;
1029
1058
  s.src = ${JSON.stringify(e.url||"")};
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?`
1031
- // ${a.name} (eds integrate)
1032
- ${a.code(s)}
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.
1059
+ document.head.appendChild(s);`}]});var ii={};O(ii,{integrate:()=>hp});import{existsSync as up}from"fs";import{mkdir as Wa,readFile as fp,writeFile as za}from"fs/promises";import En from"path";import oi from"chalk";async function hp(e){let t=E();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(T("Integrate - third-party service"));let{select:n,input:o}=await Promise.resolve().then(()=>(H(),B)),i=e||await n({message:"Which service do you want to add?",choices:Pn.map(p=>({name:p.name,value:p.id}))}),s=Ba(i);if(!s){r.error(`Unknown integration "${i}". Options: ${Pn.map(p=>p.id).join(", ")}`),process.exitCode=1;return}let a={};for(let p of s.fields){let u=await o({message:` ${p.message}`,default:p.placeholder});a[p.name]=u.trim()}let l=[];if(s.module)for(let p of s.module(a)){let u=En.join(t,p.file);await Wa(En.dirname(u),{recursive:!0}),await za(u,p.content),l.push(p.file)}let c=s.module?`
1060
+ // ${s.name} (eds integrate)
1061
+ ${s.code(a)}
1062
+ `:Ha(s.name,s.code(a)),d=En.join(t,"scripts","delayed.js");await Wa(En.dirname(d),{recursive:!0});let m=up(d)?await fp(d,"utf-8"):gp;await za(d,`${m.replace(/\s*$/,"")}
1063
+ ${c}`),r.info(S("Added"));for(let p of l)r.info(j(s.name,`wrote ${p}`));r.info(j(s.name,"wired into scripts/delayed.js")),r.info(""),r.info(oi.dim(" Loads after LCP (delayed phase) - zero impact on your Core Web Vitals.")),(s.id==="gtm"||s.id==="ga4")&&r.info(oi.dim(" Tip: gate analytics behind user consent (add the Cookiebot integration).")),s.id==="chat"&&r.info(oi.dim(" The widget loads only when the visitor clicks the button (facade pattern).")),r.info(""),r.info(I(["Integration added"]))}var gp,ri=k(()=>{"use strict";f();Ga();D();z();_();gp=`// delayed.js - third-party / non-critical scripts.
1035
1064
  // Loaded in the EDS delayed phase (after LCP), so nothing here blocks the page.
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}.
1065
+ `});var si={};O(si,{figmaSetup:()=>vp});import{existsSync as wp}from"fs";import{mkdir as bp,writeFile as yp}from"fs/promises";import de from"chalk";async function vp(){let{select:e,confirm:t}=await Promise.resolve().then(()=>(H(),B));r.logoOnce(T()),r.info(S("Figma MCP Setup Wizard")),r.info("Detecting installed AI agents...");let n=await gn(),o;if(n.length===0?(r.warn("No AI agents found (claude, cursor, codex)."),r.info(`Install Claude Code: ${de.cyan("npm install -g @anthropic-ai/claude-code")}`),o="none"):(r.success(`Found: ${n.map(s=>de.cyan(s.type)).join(", ")}`),o=await e({message:"Which agent do you want to use with eds-cli?",choices:[...n.map(s=>({name:`${s.type}${s.hasFigmaMcp?de.green(" (Figma MCP detected)"):""}`,value:s.type})),{name:"None (manual mode)",value:"none"}]})),o!=="none"){let s=n.find(a=>a.type===o);if(s&&!s.hasFigmaMcp){switch(r.warn(`Figma MCP is not configured for ${o}.
1037
1066
  `),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}})();
1067
+ `),o){case"claude":r.info(` ${de.cyan("claude mcp add --transport sse figma-sse https://mcp.figma.com/sse")}`),r.info(" or for Figma Desktop app:"),r.info(` ${de.cyan("claude mcp add --transport http figma-desktop http://127.0.0.1:3845/mcp")}`);break;case"cursor":r.info(` Add to ${de.cyan("~/.cursor/mcp.json")}:`),r.info(de.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 s?.hasFigmaMcp&&r.success(`Figma MCP is already configured for ${o}!`)}if(r.info(de.dim(`
1068
+ 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 s=Ds();wp(s)||await bp(s,{recursive:!0});let a={};o!=="none"&&(a.agent=o),await yp(Mo(),`${JSON.stringify(a,null,2)}
1069
+ `,{mode:384}),r.success(`Config saved to ${de.cyan(Mo())}`)}r.info(de.bold(`
1070
+ Setup complete!`)),o!=="none"&&r.info(`Try: ${de.cyan('eds block from-design "<figma-url>" --dry-run')}`)}var ai=k(()=>{"use strict";f();Fo();xe();D();_()});var ci={};O(ci,{doctor:()=>xp});import{existsSync as It}from"fs";import{readFile as _t,readdir as kp}from"fs/promises";import Be from"path";import{parse as Ja}from"yaml";async function xp(e={}){let t=E();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(T("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 p=await _t(Be.join(t,"fstab.yaml"),"utf-8");Ja(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=Be.join(t,"blocks"),u=await kp(p,{withFileTypes:!0}),g="",h=Be.join(t,"component-models.json");if(It(h))try{g=await _t(h,"utf-8")}catch{}for(let b of u){if(!b.isDirectory())continue;let y=b.name,v=Be.join(p,y,`${y}.js`),w=It(v);o.push({name:`blocks/${y} has JS`,status:w?"pass":"warn",message:w?"Found":`Missing ${y}.js`}),w&&(await _t(v,"utf-8")).includes("console.log")&&o.push({name:`blocks/${y} no console.log`,status:"warn",message:"Found console.log - remove before production"});let A=It(Be.join(p,y,`_${y}.json`)),X=g.includes(`"${y}"`);o.push({name:`blocks/${y} UE model`,status:A||X?"pass":"warn",message:A||X?A?`_${y}.json`:"in component-models.json":"no Universal Editor model - authors can't edit this block in UE"});let K=Be.join(p,y,".eds-meta.json");if(It(K))try{let Ce=JSON.parse(await _t(K,"utf-8")),Bt=new Date(Ce.lastSyncedAt),Y=Math.floor((Date.now()-Bt.getTime())/(1e3*60*60*24));o.push({name:`blocks/${y} Figma sync`,status:Y>30?"warn":"pass",message:Y>30?`Last synced ${Y} days ago - design may have changed`:`Synced ${Y} days ago`})}catch{o.push({name:`blocks/${y} .eds-meta.json`,status:"warn",message:"Invalid metadata file"})}}}let i=Be.join(t,"helix-query.yaml");if(It(i))try{let p=await _t(i,"utf-8");Ja(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 s=o.filter(p=>p.status==="fail"),a=o.filter(p=>p.status==="warn");if(e.json){let p={pass:o.filter(u=>u.status==="pass").length,warn:a.length,fail:s.length};console.log(JSON.stringify({projectRoot:t,results:o,summary:p},null,2)),s.length>0&&(process.exitCode=1);return}let l=U(o.map(p=>p.name));for(let p of o)r.info(R(p.status,p.name,p.message,l));let c=o.filter(p=>p.status==="fail"),d=o.filter(p=>p.status==="warn"),m=o.filter(p=>p.status==="pass");r.info(""),r.info(I([be({pass:m.length,warn:d.length,fail:c.length})])),c.length>0&&(process.exitCode=1)}var li=k(()=>{"use strict";f();xe();D();z();_()});var mi={};O(mi,{auditLoading:()=>Sp});import{existsSync as Pe}from"fs";import{readFile as it,readdir as $p,stat as qa}from"fs/promises";import Ee from"path";import di from"chalk";async function Sp(e={}){let t=E();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}e.json||(r.logoOnce(T("Loading Audit")),r.info(S("Loading Order Audit",t)));let n=[];if(await jp(t,n),await Pp(t,n),await Ep(t,n),await Cp(t,n),await Tp(t,n),await Rp(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}Fp(n)}async function jp(e,t){let n=Ee.join(e,"head.html");if(!Pe(n)){t.push({rule:"head.html exists",status:"warn",message:"Missing head.html"});return}let o=await it(n,"utf-8"),i=o.split(`
1071
+ `);for(let c=0;c<i.length;c++){let d=i[c];/<script\b/i.test(d)&&!/type\s*=\s*["']module["']/i.test(d)&&!/<\/script>/.test(d)&&t.push({rule:"No render-blocking scripts in head.html",status:"fail",message:'Script without type="module" blocks rendering',file:"head.html",line:c+1})}let a=(o.match(/<link[^>]+rel=["']stylesheet["'][^>]*>/gi)||[]).filter(c=>!c.includes("styles/styles.css")&&!c.includes("styles.css"));a.length>0&&t.push({rule:"No extra stylesheets in head.html",status:"warn",message:`${a.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 l=/(?:src|href)=["'](https?:\/\/(?!(?:localhost|127\.0\.0\.1))[^"']+)["']/gi;for(let c of o.matchAll(l)){let d=c[1];d.includes("fonts.googleapis.com")||t.push({rule:"No third-party resources in head.html",status:"warn",message:`Third-party resource: ${d} \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(c=>c.file==="head.html")||t.push({rule:"head.html is clean",status:"pass",message:"No render-blocking issues found",file:"head.html"})}async function Pp(e,t){let n=Ee.join(e,"scripts","scripts.js");if(!Pe(n)){t.push({rule:"scripts/scripts.js exists",status:"warn",message:"Missing scripts.js \u2014 cannot audit loading phases"});return}let o=await it(n,"utf-8"),i=o.split(`
1072
+ `),s=/function\s+loadEager|loadEager\s*=/i.test(o),a=/function\s+loadLazy|loadLazy\s*=/i.test(o),l=/function\s+loadDelayed|loadDelayed\s*=/i.test(o);t.push({rule:"loadEager phase exists",status:s?"pass":"fail",message:s?"Found":"Missing loadEager \u2014 LCP optimization depends on it",file:"scripts/scripts.js"}),t.push({rule:"loadLazy phase exists",status:a?"pass":"fail",message:a?"Found":"Missing loadLazy \u2014 below-fold content won't load properly",file:"scripts/scripts.js"}),t.push({rule:"loadDelayed phase exists",status:l?"pass":"warn",message:l?"Found":"Missing loadDelayed \u2014 third-party scripts may block LCP",file:"scripts/scripts.js"});let c=o.match(/setTimeout\s*\([^,]+,\s*(\d+)\s*\)/);if(l&&c){let d=Number.parseInt(c[1],10);d<3e3?t.push({rule:"Delayed phase waits >= 3s",status:"warn",message:`delayed.js loads after ${d}ms \u2014 should be >= 3000ms for LCP safety`,file:"scripts/scripts.js"}):t.push({rule:"Delayed phase waits >= 3s",status:"pass",message:`${d}ms delay before loading delayed.js`,file:"scripts/scripts.js"})}if(s){let d=o.match(/loadEager[\s\S]*?(?=function\s|const\s+load|$)/)?.[0]||"";/loadSections\s*\(/.test(d)&&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 d=0;d<i.length;d++){let m=i[d];/import\s.*from\s+['"]https?:\/\//i.test(m)&&t.push({rule:"No third-party imports at top level",status:"warn",message:`Third-party import at line ${d+1} \u2014 move to delayed.js if not critical`,file:"scripts/scripts.js",line:d+1})}if(s){let d=Ap(o,"loadEager");d&&/loadHeader|loadFooter/.test(d)&&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 Ep(e,t){let n=Ee.join(e,"styles","styles.css");if(!Pe(n))return;let i=(await qa(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 s=await it(n,"utf-8");/@import\s/.test(s)&&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=Ee.join(e,"scripts","delayed.js");if(!Pe(n)){t.push({rule:"scripts/delayed.js exists",status:"info",message:"No delayed.js \u2014 third-party scripts should go here"});return}(await it(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 Tp(e,t){let n=Ee.join(e,"blocks");if(!Pe(n))return;let o=await $p(n,{withFileTypes:!0});for(let i of o){if(!i.isDirectory())continue;let s=i.name,a=Ee.join(n,s,`${s}.js`);if(!Pe(a))continue;let l=await it(a,"utf-8"),c=l.split(`
1073
+ `),d=["jquery","lodash","moment","rxjs","d3","three","gsap","anime","chart.js","swiper"];for(let u=0;u<c.length;u++){let g=c[u].toLowerCase();for(let h of d)g.includes("from")&&g.includes(h)&&/import\s/.test(g)&&t.push({rule:"No heavy imports in blocks",status:"warn",message:`Imports "${h}" \u2014 heavy library delays section loading`,file:`blocks/${s}/${s}.js`,line:u+1})}/document\.write/i.test(l)&&t.push({rule:"No document.write in blocks",status:"fail",message:"document.write blocks parsing and can break the page",file:`blocks/${s}/${s}.js`});let p=(await qa(a)).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/${s}/${s}.js`})}for(let i of o){if(!i.isDirectory())continue;let s=i.name,a=Ee.join(n,s,`${s}.css`);if(!Pe(a))continue;let l=await it(a,"utf-8"),c=/^([a-z][a-z0-9-]*)\s*\{/gm;for(let d of l.matchAll(c)){let m=d[1];["body","html","main"].includes(m)||t.push({rule:"Block CSS is scoped",status:"warn",message:`Bare element selector "${m}" \u2014 may leak styles and cause CLS. Use .${s} prefix`,file:`blocks/${s}/${s}.css`})}}}async function Rp(e,t){let n=Ee.join(e,"scripts","aem.js");if(!Pe(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 Ap(e,t){let o=new RegExp(`(?:async\\s+)?function\\s+${t}\\s*\\([^)]*\\)\\s*\\{`).exec(e);if(!o)return null;let i=1,s=o.index+o[0].length,a=s;for(;s<e.length&&i>0;)e[s]==="{"?i++:e[s]==="}"&&i--,s++;return e.slice(a,s-1)}function Fp(e){let t=new Map;for(let o of e){let i=o.file||"general",s=t.get(i)??[];s.push(o),t.set(i,s)}for(let[o,i]of t){r.info(` ${J.bullet} ${di.underline(o)}`);for(let s of i){let a=s.line?di.dim(`:${s.line}`):"";r.info(` ${Gt(s.status)} ${s.rule}${a}`),s.status!=="pass"&&r.info(di.dim(` ${s.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(I([be(n)])),n.fail>0&&(process.exitCode=1)}var pi=k(()=>{"use strict";f();D();z();_()});var fi={};O(fi,{auditSecurity:()=>Bp});import{existsSync as Cn}from"fs";import{readFile as Dp,readdir as Lp}from"fs/promises";import He from"path";import ui from"chalk";async function*Va(e){let t=await Lp(e,{withFileTypes:!0});for(let n of t){let o=He.join(e,n.name);if(n.isDirectory()){if(Mp.has(n.name))continue;yield*Va(o)}else n.isFile()&&(yield o)}}function _p(e,t,n){let o=[],i=e.split(`
1074
+ `);for(let s=0;s<i.length;s++){let a=i[s],l=!1;for(let c of Np)c.ext.includes(n)&&(c.id==="innerhtml-static"&&l||c.re.test(a)&&(c.extra&&!c.extra(a)||(c.id==="innerhtml-dynamic"&&(l=!0),o.push({severity:c.severity,rule:c.id,message:c.message,file:t,line:s+1,snippet:a.trim().slice(0,100)}))))}return o}async function Up(e){if(!Cn(He.join(e,"package.json")))return{status:"skipped",note:"no package.json"};if(!(Cn(He.join(e,"package-lock.json"))||Cn(He.join(e,"npm-shrinkwrap.json")))&&!Cn(He.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}),s=JSON.parse(o)?.metadata?.vulnerabilities??{},a={critical:s.critical??0,high:s.high??0,moderate:s.moderate??0,low:s.low??0};return{status:a.critical+a.high+a.moderate+a.low>0?"vulnerable":"ok",counts:a}}catch(n){return{status:"skipped",note:`npm audit failed: ${n.message}`}}}async function Bp(e={}){let t=E();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}let n=[];for await(let c of Va(t)){let d=He.extname(c).slice(1).toLowerCase();if(!Ip.has(d))continue;let m=He.relative(t,c);if(m.endsWith("aem.js")||m.endsWith("lib-franklin.js"))continue;let p=await Dp(c,"utf-8");n.push(..._p(p,m,d))}let o=await Up(t),i=c=>n.filter(d=>d.severity===c),s={critical:i("critical").length,high:i("high").length,moderate:i("moderate").length,low:i("low").length},a=s.critical>0||s.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:s}},null,2)),a&&(process.exitCode=1);return}if(r.logoOnce(T("Security Audit")),r.info(S("Dependencies","npm audit")),o.status==="skipped")r.info(R("info","npm audit",o.note??"skipped"));else if(o.status==="ok")r.info(R("pass","npm audit","no known vulnerabilities"));else{let c=o.counts??{critical:0,high:0,moderate:0,low:0};r.info(R(c.critical+c.high>0?"fail":"warn","npm audit",`${c.critical} critical, ${c.high} high, ${c.moderate} moderate, ${c.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(R("pass","code","no risky patterns found"));else{let c=[...n].sort((d,m)=>Ka.indexOf(d.severity)-Ka.indexOf(m.severity));for(let d of c){let m=Op[d.severity],p=ui.dim(`${d.file}:${d.line}`);r.info(` ${Gt(m.status)} ${ui.bold(m.label)} ${d.message} ${p}`),r.info(ui.dim(` ${d.snippet}`))}}let l=be({fail:s.critical+s.high+(o.counts?.critical??0)+(o.counts?.high??0),warn:s.moderate+(o.counts?.moderate??0),info:s.low+(o.counts?.low??0)});r.info(""),r.info(I([l||`${J.pass} no vulnerabilities or risky patterns found`])),a&&(process.exitCode=1)}var Np,Ka,Op,Mp,Ip,gi=k(()=>{"use strict";f();D();z();_();Np=[{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"]}],Ka=["critical","high","moderate","low"],Op={critical:{status:"fail",label:"CRIT"},high:{status:"fail",label:"HIGH"},moderate:{status:"warn",label:"MOD "},low:{status:"info",label:"LOW "}},Mp=new Set(["node_modules",".git","dist","build",".vscode","coverage"]),Ip=new Set(["js","mjs","html","json","pem","txt"])});async function Xa(e,t,n){let o=t.ref||"main",i=n.startsWith("/")?n:`/${n}`,s=`${Hp}/${e}/${t.org}/${t.site}/${o}${i}`;r.debug(`POST ${s}`);let a=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"}}),l=await a.json().catch(()=>({})),c=l;return a.ok?{ok:!0,status:a.status,path:i,previewUrl:c.preview?.url,liveUrl:c.live?.url}:{ok:!1,status:a.status,path:i,message:l.message||`HTTP ${a.status}`}}async function hi(e,t){return Xa("preview",e,t)}async function wi(e,t){return Xa("live",e,t)}async function Ya(e,t){return Promise.all(t.map(n=>hi(e,n)))}async function Qa(e,t){return Promise.all(t.map(n=>wi(e,n)))}var Hp,bi=k(()=>{"use strict";f();D();Hp="https://admin.hlx.page"});var yi={};O(yi,{preview:()=>Wp,resolveAdminConfig:()=>Tn});import Za from"chalk";import Gp from"ora";async function Wp(e,t){let n=E(),o=await pe(n),i=Tn(o,t);if(!i)return;let s=Gp(`Previewing ${e.length} path(s)...`).start(),a=e.length===1?[await hi(i,e[0])]:await Ya(i,e);s.stop();let l=!1;for(let c of a)c.ok?r.success(`${c.path} \u2192 ${Za.cyan(c.previewUrl||"preview updated")}`):(r.error(`${c.path} \u2014 ${c.message}`),l=!0);l&&(process.exitCode=1)}function Tn(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(Za.dim(' { "admin": { "org": "my-org", "site": "my-site" } }')),process.exitCode=1;return}return{org:n,site:o,ref:i}}var Rn=k(()=>{"use strict";f();bi();xe();D();z()});var vi={};O(vi,{publish:()=>qp});import zp from"chalk";import Jp from"ora";async function qp(e,t){let n=E(),o=await pe(n),i=Tn(o,t);if(!i)return;let s=Jp(`Publishing ${e.length} path(s)...`).start(),a=e.length===1?[await wi(i,e[0])]:await Qa(i,e);s.stop();let l=!1;for(let c of a)c.ok?r.success(`${c.path} \u2192 ${zp.cyan(c.liveUrl||"published")}`):(r.error(`${c.path} \u2014 ${c.message}`),l=!0);l&&(process.exitCode=1)}var ki=k(()=>{"use strict";f();bi();xe();D();z();Rn()});var An={};O(An,{adminWizard:()=>Kp});async function Kp(e){let t=E();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(T("Admin API \u2014 preview / publish"));let{select:n,input:o,confirm:i}=await Promise.resolve().then(()=>(H(),B)),a=(await pe(t)).admin??{},l=e??await n({message:"What do you want to do?",choices:[{name:"Preview pages (staging)",value:"preview"},{name:"Publish pages (go live)",value:"publish"}]}),c=(await o({message:"GitHub org / owner",default:a.org})).trim(),d=(await o({message:"Repository / site",default:a.site})).trim(),m=(await o({message:"Git ref",default:a.ref||"main"})).trim(),u=(await o({message:"Paths (space- or comma-separated)",default:"/"})).split(/[\s,]+/).filter(Boolean);if(!c||!d||u.length===0){r.error("org, site and at least one path are required."),process.exitCode=1;return}r.info(S("Summary"));let g=U(["operation","org","site","ref","paths"]);if(r.info(j("operation",l,g)),r.info(j("org",c,g)),r.info(j("site",d,g)),r.info(j("ref",m,g)),r.info(j("paths",u.join(", "),g)),r.info(""),l==="publish"&&!await i({message:`Publish ${u.length} path(s) to LIVE?`,default:!1})){r.info("Cancelled.");return}let h={org:c,site:d,ref:m};if(l==="preview"){let{preview:b}=await Promise.resolve().then(()=>(Rn(),yi));await b(u,h)}else{let{publish:b}=await Promise.resolve().then(()=>(ki(),vi));await b(u,h)}}var Fn=k(()=>{"use strict";f();xe();D();z();_()});var ec={};O(ec,{mainMenu:()=>eu});import{existsSync as Vp}from"fs";import{readdir as Xp}from"fs/promises";import Yp from"path";import Qp from"chalk";async function xi(e){let t=Yp.join(e,"blocks");return Vp(t)?(await Xp(t,{withFileTypes:!0})).filter(o=>o.isDirectory()).map(o=>o.name):[]}async function eu(){let{select:e,isEscape:t,isExit:n}=await Promise.resolve().then(()=>(H(),B));vn.menu=!0,await r.logoOnceAnimated("");let o;for(;;){r.info(Qp.dim(" Esc quits here \xB7 goes back to this menu from any step"));let i;try{i=await e({message:"Choose an action",choices:Zp,default:o})}catch(s){if(t(s)||n(s))return;throw s}if(i==="exit")return;o=i;try{await tu(i)}catch(s){if(n(s))return;t(s)||r.error(s instanceof Error?s.message:String(s))}process.exitCode=void 0,r.info("")}}async function tu(e){let{select:t,input:n}=await Promise.resolve().then(()=>(H(),B));switch(e){case"init":{let{initProject:o}=await Promise.resolve().then(()=>(an(),sn));await o({});return}case"template":{let o=await n({message:"Template name",validate:s=>!!s.trim()||"Required"}),{templateNew:i}=await Promise.resolve().then(()=>(io(),oo));await i(o.trim(),{});return}case"sandbox":{let o=await n({message:"Sandbox repo name",validate:s=>/^[a-z0-9][a-z0-9._-]*$/i.test(s.trim())||"Use a valid repo name"}),{sandboxNew:i}=await Promise.resolve().then(()=>(Ne(),Le));await i(o.trim(),{});return}case"from-design":{let{blockFromDesign:o}=await Promise.resolve().then(()=>(Yo(),Xo));await o(void 0,{});return}case"migrate":{let{migrateComponent:o}=await Promise.resolve().then(()=>(uo(),po));await o(void 0,{});return}case"scaffold":{let{scaffoldInteractive:o}=await Promise.resolve().then(()=>(me(),fe));await o();return}case"create":{let o=await n({message:"Block name",validate:s=>Re.test(s.trim())||"Use kebab-case, e.g. hero-banner"}),{createBlock:i}=await Promise.resolve().then(()=>(Co(),Eo));await i(o.trim(),{});return}case"integrate":{let{integrate:o}=await Promise.resolve().then(()=>(ri(),ii));await o(void 0);return}case"preview-block":{let o=E();if(!o){r.error("Not inside an EDS project (no EDS project markers found).");return}let i=await xi(o);if(i.length===0){r.warn("No blocks found in blocks/.");return}let s=await t({message:"Which block?",choices:i.map(l=>({name:l,value:l}))}),{previewBlock:a}=await Promise.resolve().then(()=>(Ue(),Lt));await a(s,{});return}case"model":{let{modelAdd:o}=await Promise.resolve().then(()=>(xo(),ko));await o(void 0,[],{});return}case"track":{let o=E();if(!o){r.error("Not inside an EDS project (no EDS project markers found).");return}let i=await xi(o);if(i.length===0){r.warn("No blocks found in blocks/.");return}let s=await t({message:"Which block to instrument?",choices:i.map(l=>({name:l,value:l}))}),{trackBlock:a}=await Promise.resolve().then(()=>(xt(),kt));await a(s,{});return}case"schema":{let o=E();if(!o){r.error("Not inside an EDS project (no EDS project markers found).");return}let i=await xi(o);if(i.length===0){r.warn("No blocks found in blocks/.");return}let s=await t({message:"Which block?",choices:i.map(l=>({name:l,value:l}))}),{schemaBlock:a}=await Promise.resolve().then(()=>(So(),$o));await a(s,{});return}case"ue":{if(await t({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(()=>(Pt(),jt));await i()}else{let i=await n({message:"Page path",default:"/"}),{ueOpen:s}=await Promise.resolve().then(()=>(Pt(),jt));await s(i.trim()||"/",{})}return}case"admin":{let{adminWizard:o}=await Promise.resolve().then(()=>(Fn(),An));await o();return}case"audit":{let o=await t({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(()=>(li(),ci));await i({})}else if(o==="loading"){let{auditLoading:i}=await Promise.resolve().then(()=>(pi(),mi));await i({})}else{let{auditSecurity:i}=await Promise.resolve().then(()=>(gi(),fi));await i({})}return}case"figma-setup":{let{figmaSetup:o}=await Promise.resolve().then(()=>(ai(),si));await o();return}}}var Zp,tc=k(()=>{"use strict";f();D();z();Je();kn();Zp=[{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"},{name:"Exit",value:"exit",description:"Quit eds (or press Esc)"}]});f();import nu from"chalk";import{Command as ou}from"commander";var Si={name:"aem-eds-kit",version:"0.4.48",description:"CLI for AEM Edge Delivery Services: blocks from Figma, Framer or Google Stitch designs, AEM component migration (AEMaaCS and 6.5), Universal Editor models and QA",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","aem-edge-delivery","universal-editor","aemaacs","aem-migration","framer","google-stitch","design-to-code","claude-code"],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.64.0",pngjs:"^7.0.0"}};D();_();var G=new ou;G.name("eds").description("CLI for AEM Edge Delivery Services with Figma integration").version(Si.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&&(nu.level=0)});G.addHelpText("beforeAll",()=>T());var Ut=G.command("sandbox").description("Disposable EDS sandbox repos on GitHub");Ut.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(()=>(Ne(),Le));await n(e,t)});Ut.command("login").description("Authorize GitHub (OAuth device flow or a token) - no gh needed").action(async()=>{let{sandboxLogin:e}=await Promise.resolve().then(()=>(Ne(),Le));await e()});Ut.command("logout").description("Remove the stored GitHub token").action(async()=>{let{sandboxLogout:e}=await Promise.resolve().then(()=>(Ne(),Le));await e()});Ut.command("list").description("List your EDS sandboxes (repos tagged eds-sandbox)").action(async()=>{let{sandboxList:e}=await Promise.resolve().then(()=>(Ne(),Le));await e()});Ut.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(()=>(Ne(),Le));await n(e,t)});var iu=G.command("template").description("Generate page templates / initial content");iu.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(()=>(io(),oo));await n(e,t)});G.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(()=>(an(),sn));await t(e)});var ru=G.command("migrate").description("Migrate from classic AEM to EDS");ru.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("--super-root <dirs>","jcr_root folder(s), comma-separated, holding a proxy component's super type (e.g. a Core Components checkout)").option("--yes","Skip confirmation prompts").action(async(e,t)=>{let{migrateComponent:n}=await Promise.resolve().then(()=>(uo(),po));await n(e,t)});var su=G.command("model").description("Compose Universal Editor models");su.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(()=>(xo(),ko));await o(e,t,n)});var au=G.command("schema").description("Structured data (JSON-LD) for blocks");au.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(()=>(So(),$o));await n(e,t)});var cu=G.command("track").description("Instrument blocks for analytics");cu.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(()=>(xt(),kt));await n(e,t)});var nc=G.command("ue").description("Universal Editor - readiness check + editor deep link");nc.command("check").description("Check whether blocks are Universal-Editor-ready (offline)").action(async()=>{let{ueCheck:e}=await Promise.resolve().then(()=>(Pt(),jt));await e()});nc.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(()=>(Pt(),jt));await n(e,t)});var rt=G.command("block").description("Manage EDS blocks");rt.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(()=>(Co(),Eo));await n(e,t)});rt.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("--auth","Scrape with a logged-in session (Framer/Stitch) \u2014 login captured once, then reused").option("--auth-refresh","Force a fresh scrape login even if a session is saved").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(()=>(Yo(),Xo));await n(e,t)});rt.command("list").description("List all blocks in the project").action(async e=>{let{listBlocks:t}=await Promise.resolve().then(()=>($a(),xa));await t({...e,json:G.opts().json})});rt.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(()=>(Ue(),Lt));e?await n.previewBlock(e,t):await n.galleryPreview(t)});rt.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(()=>(Oa(),Na));await n(e,t)});rt.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(()=>(Ua(),_a));await n(e,t)});var st=G.command("scaffold").description("Scaffold standard UE components and blocks").action(async()=>{let{scaffoldInteractive:e}=await Promise.resolve().then(()=>(me(),fe));await e()});st.command("ue").description("Scaffold default-content UE components + a field-reference block (all 17 fields)").action(async()=>{let{scaffoldUe:e}=await Promise.resolve().then(()=>(me(),fe));await e()});st.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(()=>(me(),fe));await t(e)});st.command("ci").description("Scaffold a GitHub Actions workflow (doctor + audits + project lint/build)").action(async()=>{let{scaffoldCi:e}=await Promise.resolve().then(()=>(me(),fe));await e()});st.command("helpers [names...]").description("Scaffold scripts/utils.js with chosen EDS helpers (interactive picker)").action(async e=>{let{scaffoldHelpers:t}=await Promise.resolve().then(()=>(me(),fe));await t(e)});st.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(()=>(me(),fe));await t(e)});st.command("xwalk").description("Write xwalk.json enabling Universal Editor multi-field support").action(async()=>{let{scaffoldXwalk:e}=await Promise.resolve().then(()=>(me(),fe));await e()});G.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(()=>(ri(),ii));await t(e)});var lu=G.command("figma").description("Figma MCP integration");lu.command("setup").description("Configure Figma MCP for your AI agent").action(async()=>{let{figmaSetup:e}=await Promise.resolve().then(()=>(ai(),si));await e()});G.command("doctor").description("Audit your EDS project for common issues").action(async()=>{let{doctor:e}=await Promise.resolve().then(()=>(li(),ci));await e({json:G.opts().json})});var oc=G.command("audit").description("Run project audits");oc.command("loading").description("Check loading order (eager/lazy/delayed phases, LCP budget)").action(async()=>{let{auditLoading:e}=await Promise.resolve().then(()=>(pi(),mi));await e({json:G.opts().json})});oc.command("security").description("Scan for vulnerabilities (npm audit) and exploit patterns (XSS, secrets, tabnabbing)").action(async()=>{let{auditSecurity:e}=await Promise.resolve().then(()=>(gi(),fi));await e({json:G.opts().json})});G.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(()=>(Fn(),An));await o("preview");return}let{preview:n}=await Promise.resolve().then(()=>(Rn(),yi));await n(e,t)});G.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(()=>(Fn(),An));await o("publish");return}let{publish:n}=await Promise.resolve().then(()=>(ki(),vi));await n(e,t)});(async()=>{try{if(process.argv.slice(2).length===0)if(process.stdout.isTTY){let{mainMenu:e}=await Promise.resolve().then(()=>(tc(),ec));await e()}else G.outputHelp();else await G.parseAsync()}catch(e){r.error(e instanceof Error?e.message:String(e)),process.exitCode=1}})();