@uicopilot/storybook-addon 0.19.0 → 0.20.0

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/preset.js CHANGED
@@ -1,3 +1,3 @@
1
- "use strict";var Ue=Object.create;var N=Object.defineProperty;var ze=Object.getOwnPropertyDescriptor;var We=Object.getOwnPropertyNames;var Ge=Object.getPrototypeOf,Xe=Object.prototype.hasOwnProperty;var Ke=(e,n)=>()=>(e&&(n=e(e=0)),n);var ae=(e,n)=>{for(var t in n)N(e,t,{get:n[t],enumerable:!0})},ce=(e,n,t,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of We(n))!Xe.call(e,o)&&o!==t&&N(e,o,{get:()=>n[o],enumerable:!(r=ze(n,o))||r.enumerable});return e};var le=(e,n,t)=>(t=e!=null?Ue(Ge(e)):{},ce(n||!e||!e.__esModule?N(t,"default",{value:e,enumerable:!0}):t,e)),qe=e=>ce(N({},"__esModule",{value:!0}),e);var Ie={};ae(Ie,{detectFileType:()=>Ee,formatValidationResult:()=>kt,isValidCode:()=>Ft,validateCode:()=>ve,validateCodeForFile:()=>Te});function Ot(e,n={}){let t=n.minLength??_t;return e.length<t?{code:"CODE_TOO_SHORT",message:`Code is too short (${e.length} chars). Minimum: ${t}. Likely incomplete or a snippet.`,severity:"error"}:null}function Rt(e){let n=[/^[+-]{3}\s+[ab]\//m,/^@@\s+-\d+,\d+\s+\+\d+,\d+\s+@@/m,/^diff --git/m,/^index [a-f0-9]+\.\.[a-f0-9]+/m];for(let t of n)if(t.test(e))return{code:"CODE_IS_DIFF",message:"Code appears to be a diff/patch format, not complete file content.",severity:"error"};return null}function Lt(e){let n=e.split(`
2
- `).filter(o=>o.trim()),t=n.filter(o=>o.trim().startsWith("//")||o.trim().startsWith("/*")||o.trim().startsWith("*")||o.trim().startsWith("#"));if(n.length>0&&t.length/n.length>.8)return{code:"CODE_IS_INSTRUCTIONS",message:"Code appears to be mostly comments/instructions, not actual implementation.",severity:"error"};let r=[/^\/\/\s*(Change|Replace|Update|Modify|Add|Remove|Delete)\s+(from|to|this|the)/im,/^\/\/\s*To:/m,/^\/\/\s*From:/m];for(let o of r)if(o.test(e))return{code:"CODE_IS_INSTRUCTIONS",message:'Code contains instruction comments (e.g., "// Change from:" / "// To:") instead of actual code.',severity:"error"};return null}function $t(e){let n={"{":"}","[":"]","(":")"},t=[],r=!1,o="",a=!1;for(let i=0;i<e.length;i++){let c=e[i],f=e[i-1];if((c==='"'||c==="'"||c==="`")&&f!=="\\"){r?c===o&&(r=!1,a=!1):(r=!0,o=c,c==="`"&&(a=!0));continue}if(!r){if(n[c])t.push(n[c]);else if(Object.values(n).includes(c)&&t.pop()!==c)return{code:"UNBALANCED_BRACES",message:`Unbalanced braces/brackets detected. Found unexpected '${c}'.`,severity:"warning"}}}return t.length>0?{code:"UNBALANCED_BRACES",message:`Unbalanced braces/brackets. Missing: ${t.reverse().join("")}`,severity:"warning"}:null}function Ce(e,n={}){let t=[],r=[];e.includes("import ")||t.push({code:"TSX_MISSING_IMPORTS",message:"Component file missing import statements. A complete file must have imports.",severity:"error"}),e.includes("export ")||t.push({code:"TSX_MISSING_EXPORTS",message:"Component file missing exports. A complete file must export something.",severity:"error"});let o=/import\s+(?:React|\{[^}]*\})\s+from\s+['"]react['"]/.test(e);/<[A-Z][a-zA-Z]*|<[a-z]+[\s/>]/.test(e)&&!o&&r.push({code:"TSX_NO_REACT_IMPORT",message:"JSX detected but no React import. OK for React 17+ with automatic runtime.",severity:"warning"}),/export\s+(default\s+)?function\s+\w+/.test(e)||/export\s+(const|let)\s+\w+\s*[:=]/.test(e)||/export\s+default\s+\w+/.test(e)||/export\s+\{[^}]+\}/.test(e)||r.push({code:"TSX_NO_COMPONENT_DEF",message:"No clear component definition found. Expected function or const export.",severity:"warning"});let c=[{pattern:/\.\.\.\s*$/,message:'Code ends with "..." - likely truncated'},{pattern:/\/\/\s*\.\.\./m,message:'Contains "// ..." - likely incomplete'},{pattern:/{\s*\/\*\s*\.\.\.\s*\*\/\s*}/m,message:'Contains "{/* ... */}" placeholder'}];for(let{pattern:f,message:l}of c)f.test(e)&&t.push({code:"TSX_INCOMPLETE",message:l,severity:"error"});return{errors:t,warnings:r}}function Mt(e,n={}){let t=[],r=[];(e.includes("import ")||e.includes("export "))&&t.push({code:"CSS_HAS_JS_CODE",message:"CSS file contains JavaScript import/export statements. Wrong file type.",severity:"error"}),/[.#\w\[\]]+\s*\{[\s\S]*?:\s*[^;]+;?[\s\S]*?\}/.test(e)||t.push({code:"CSS_INVALID_SYNTAX",message:"No valid CSS syntax found. Expected selector { property: value; } pattern.",severity:"error"});let a=(e.match(/\{[^}]+\}/g)||[]).length;return a===0&&t.push({code:"CSS_NO_RULES",message:"No CSS rules found. File appears empty or malformed.",severity:"error"}),(e.includes("/* ... */")||e.includes("// ..."))&&t.push({code:"CSS_INCOMPLETE",message:"CSS contains placeholder comments (/* ... */) - likely incomplete.",severity:"error"}),a>0&&a<3&&!n.allowPartial&&r.push({code:"CSS_FEW_RULES",message:`Only ${a} CSS rule(s) found. Might be incomplete.`,severity:"warning"}),{errors:t,warnings:r}}function Nt(e,n={}){let t=[],r=[];return e.includes("import ")||t.push({code:"STORIES_MISSING_IMPORTS",message:"Stories file missing import statements.",severity:"error"}),/@storybook\//.test(e)||t.push({code:"STORIES_NO_STORYBOOK_IMPORT",message:"Stories file must import from @storybook/* (e.g., @storybook/react).",severity:"error"}),e.includes("Meta")||e.includes("ComponentMeta")||r.push({code:"STORIES_NO_META_TYPE",message:"Stories file should have Meta type import for type safety.",severity:"warning"}),e.includes("StoryObj")||e.includes("ComponentStory")||e.includes("Story")||r.push({code:"STORIES_NO_STORY_TYPE",message:"Stories file should have StoryObj/Story type for type safety.",severity:"warning"}),e.includes("export default")||t.push({code:"STORIES_NO_DEFAULT_EXPORT",message:"Stories file must have a default export (meta configuration).",severity:"error"}),/export\s+const\s+\w+\s*[:=]/.test(e)||t.push({code:"STORIES_NO_STORY_EXPORTS",message:"Stories file must have at least one named export (story definition).",severity:"error"}),/import\s+\{?\s*\w+\s*\}?\s+from\s+['"]\.\//.test(e)||r.push({code:"STORIES_NO_COMPONENT_IMPORT",message:"Stories file should import the component being documented.",severity:"warning"}),(e.includes("// ... other")||e.includes("/* ... */"))&&t.push({code:"STORIES_INCOMPLETE",message:"Stories file contains placeholder comments - likely incomplete.",severity:"error"}),{errors:t,warnings:r}}function Ee(e){let n=e.toLowerCase();if(n.includes(".stories."))return"stories";switch(n.split(".").pop()){case"tsx":return"tsx";case"jsx":return"jsx";case"ts":return"ts";case"js":return"js";case"css":return"css";case"scss":return"scss";case"less":return"less";default:return"unknown"}}function ve(e,n,t={}){let r={valid:!0,fileType:n,errors:[],warnings:[]},o=Ot(e,t);o&&r.errors.push(o);let a=Rt(e);a&&r.errors.push(a);let i=Lt(e);i&&r.errors.push(i);let c=$t(e);switch(c&&(t.strict?r.errors.push({...c,severity:"error"}):r.warnings.push(c)),n){case"stories":{let{errors:f,warnings:l}=Nt(e,t);r.errors.push(...f),r.warnings.push(...l);break}case"tsx":case"jsx":{let{errors:f,warnings:l}=Ce(e,t);r.errors.push(...f),r.warnings.push(...l);break}case"css":case"scss":case"less":{let{errors:f,warnings:l}=Mt(e,t);r.errors.push(...f),r.warnings.push(...l);break}case"ts":case"js":{let{errors:f,warnings:l}=Ce(e,t);r.errors.push(...f),r.warnings.push(...l.filter(s=>!s.code.includes("JSX")));break}default:break}return r.valid=r.errors.length===0,r}function Te(e,n,t={}){let r=Ee(n);return ve(e,r,t)}function Ft(e,n,t={}){return Te(e,n,t).valid}function kt(e){if(e.valid&&e.warnings.length===0)return`\u2713 Valid ${e.fileType} code`;let n=[];if(e.valid)n.push(`\u26A0 Valid ${e.fileType} code with warnings`);else{n.push(`\u2717 Invalid ${e.fileType} code`),n.push(""),n.push("Errors:");for(let t of e.errors)n.push(` - [${t.code}] ${t.message}`)}if(e.warnings.length>0){n.push(""),n.push("Warnings:");for(let t of e.warnings)n.push(` - [${t.code}] ${t.message}`)}return n.join(`
3
- `)}var _t,Pe=Ke(()=>{"use strict";_t=50});var Zt={};ae(Zt,{experimental_serverChannel:()=>ke,managerEntries:()=>Yt,previewAnnotations:()=>Jt,viteFinal:()=>Ae});module.exports=qe(Zt);var O=require("path"),ie=require("url");var Fe=le(require("fs/promises")),V=le(require("path")),re=require("glob");var z=require("fs"),W=require("module");var U={NAME:"UI Parity",SHORT:"Parity",DOMAIN:"uiparity.com",MARKETING_URL:"https://uiparity.com",APP_URL:"https://app.uiparity.com",API_URL:"https://api.uiparity.com",SUPPORT_EMAIL:"feedback@uiparity.com",TAGLINE:"Pixel-perfect isn't a feeling. It's a score."};function Ye(){if(typeof process<"u"&&process.env)return process.env.UICOPILOT_DEBUG==="1";if(typeof globalThis<"u"&&"localStorage"in globalThis)try{return globalThis.localStorage.getItem("uicopilot_debug")==="1"}catch{return!1}return!1}var F=`[${U.NAME}]`,g={debug:(...e)=>{Ye()&&console.log(F,...e)},info:(...e)=>{console.log(F,...e)},warn:(...e)=>{console.warn(F,...e)},error:(...e)=>{console.error(F,...e)}};var dt=["flex","inline-flex"],pt=["grid","inline-grid"],Pn=[...dt,...pt];function k(e){let r=e.ownerDocument?.defaultView;if(!r)return e.firstElementChild??e;let o=e.getBoundingClientRect(),a=l=>{let s=r.getComputedStyle(l);if(s.position==="fixed"||s.display==="none"||s.visibility==="hidden")return!0;let d=l.getBoundingClientRect();return d.width===0||d.height===0||l.children.length===0&&!(l.textContent??"").trim()},i=l=>{if(o.width===0||o.height===0)return!1;let s=l.getBoundingClientRect();return s.width>=o.width*.9&&s.height>=o.height*.9},c=e;for(let l=0;l<6;l+=1){let s=Array.from(c.children).filter(d=>!a(d));if(s.length!==1||c!==e&&!i(c))break;c=s[0]}if(c!==e&&i(c)){let l=Array.from(c.children).filter(s=>!a(s));if(l.length>1&&f(l))return l[0].setAttribute("data-uicopilot-instances",String(l.length)),l[0]}if(c===e)return e.firstElementChild??e;return c;function f(l){let s=u=>{let m=u.className,w=typeof m=="string"?m:"";return`${u.tagName}.${w.split(" ")[0]??""}`},d=s(l[0]);return l.every(u=>s(u)===d)}}var yt={},ge=k.toString(),L=null,_=null,me=!1;async function X(){if(me)return!!L;if(me=!0,process.env.STORYBOOK_UICOPILOT_NO_PUPPETEER==="true")return g.debug("Puppeteer disabled via STORYBOOK_UICOPILOT_NO_PUPPETEER flag"),!1;let e=(0,W.createRequire)(process.cwd()+"/");try{return L=e("puppeteer"),g.debug("Puppeteer loaded \u2014 server-side screenshots enabled"),!0}catch{}try{return L=e("puppeteer-core"),g.debug("puppeteer-core loaded from the project \u2014 capture enabled"),!0}catch{}try{return L=(0,W.createRequire)(yt.url)("puppeteer-core"),g.debug("puppeteer-core loaded from the addon \u2014 capture enabled"),!0}catch{}return g.debug("No Puppeteer implementation available \u2014 server-side capture disabled"),!1}function gt(){let e=process.env.STORYBOOK_UICOPILOT_CHROME_PATH;if(e){if((0,z.existsSync)(e))return e;g.warn(`STORYBOOK_UICOPILOT_CHROME_PATH is set to "${e}" but no file exists there \u2014 falling back to discovery`)}let n=process.platform==="win32",t=process.env,r=n?[`${t.PROGRAMFILES??"C:\\Program Files"}\\Google\\Chrome\\Application\\chrome.exe`,`${t["PROGRAMFILES(X86)"]??"C:\\Program Files (x86)"}\\Google\\Chrome\\Application\\chrome.exe`,`${t.LOCALAPPDATA??""}\\Google\\Chrome\\Application\\chrome.exe`,`${t.PROGRAMFILES??"C:\\Program Files"}\\Microsoft\\Edge\\Application\\msedge.exe`].filter(o=>!o.startsWith("\\")):["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary","/Applications/Chromium.app/Contents/MacOS/Chromium","/usr/bin/google-chrome","/usr/bin/google-chrome-stable","/usr/bin/chromium-browser","/usr/bin/chromium","/snap/bin/chromium"];for(let o of r)if((0,z.existsSync)(o))return o}async function he(){return K()}var A=class extends Error{constructor(){super("No Chrome or Chromium found. Install Google Chrome, or set STORYBOOK_UICOPILOT_CHROME_PATH to an executable. (Capture needs a real browser to render your stories.)"),this.name="BrowserNotFoundError"}},G=class extends Error{constructor(n,t){super(`Found a browser at "${n}" but could not drive it: ${t instanceof Error?t.message:String(t)}. This usually means the installed browser and puppeteer-core versions are incompatible.`),this.name="BrowserIncompatibleError"}};async function K(){if(_&&_.connected)return _;let e=gt();if(!e&&!ht())throw new A;let n={headless:!0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-dev-shm-usage"],...e?{executablePath:e}:{}};try{_=await L.launch(n)}catch(t){throw e?new G(e,t):new A}return g.debug("Headless Chrome launched for screenshots"),_}function ht(){try{return typeof L?.executablePath=="function"}catch{return!1}}async function q(e,n){if(!await X())return null;let o=await(await K()).newPage();try{await o.setCacheEnabled(!1),await o.setViewport({width:n?.width||800,height:n?.height||600,deviceScaleFactor:1}),await o.goto(e,{waitUntil:"load",timeout:15e3}),await o.evaluate(()=>document.fonts.ready),await o.waitForSelector("#storybook-root > *",{timeout:1e4}),await o.waitForFunction(()=>new Promise(l=>{let s=document.querySelectorAll("style").length,d=0,u=()=>{let m=document.querySelectorAll("style").length;if(m===s){if(d++,d>=3){l(!0);return}}else d=0,s=m;setTimeout(u,100)};setTimeout(u,200)}),{timeout:5e3}).catch(()=>{}),await new Promise(l=>setTimeout(l,500));let a=await o.evaluate(l=>{let s=document.querySelector("#storybook-root");if(!s)return null;let d=window.innerHeight,u=window.innerWidth,m=v=>v.setAttribute("data-uic-drilled",""),w=()=>{let v=document.createElement("style");v.id="uic-drilled-bg-reset",v.textContent="[data-uic-drilled] { background: transparent !important; border-color: transparent !important; box-shadow: none !important; }",document.head.appendChild(v),document.body.offsetHeight};try{let T=new Function("return ("+l+")")()(s),y=T?.getBoundingClientRect(),E=!!y&&y.width>=u*.9&&y.height>=d*.9;if(T&&T!==s&&y&&y.width>0&&y.height>0&&!E){for(let P=T.parentElement;P&&P!==s;P=P.parentElement)m(P);return w(),{top:y.top,bottom:y.bottom,left:y.left,right:y.right}}}catch{}let p=1/0,h=0,S=1/0,C=0,b=!1;function x(v){for(let T of Array.from(v.children)){let y=window.getComputedStyle(T);if(y.display==="none"||y.visibility==="hidden"||y.position==="fixed"||y.position==="absolute")continue;let E=T.getBoundingClientRect();if(E.height<=0||E.width<=0)continue;if((E.width>=u*.9||E.height>=d*.9)&&T.children.length>0){T.setAttribute("data-uic-drilled",""),x(T);continue}if(T.children.length===1){let j=y.backgroundColor,De=j==="rgba(0, 0, 0, 0)"||j==="transparent"||j==="",Be=y.borderStyle!=="none"&&y.borderWidth!=="0px",He=y.boxShadow!=="none",Ve=!De||Be||He,se=T.children[0].getBoundingClientRect(),je=se.width>=E.width*.95&&se.height>=E.height*.95;if(!Ve||je){T.setAttribute("data-uic-drilled",""),x(T);continue}}p=Math.min(p,E.top),h=Math.max(h,E.bottom),S=Math.min(S,E.left),C=Math.max(C,E.right),b=!0}}return x(s),b?(w(),{top:p,bottom:h,left:S,right:C}):null},ge);await o.evaluate(()=>new Promise(l=>requestAnimationFrame(()=>l())));let i=4,c=a?{x:Math.max(0,a.left-i),y:Math.max(0,a.top-i),width:Math.min(a.right-a.left+i*2,800),height:Math.min(a.bottom-a.top+i*2,600)}:void 0,f=await o.screenshot({type:"png",omitBackground:!0,...c?{clip:c}:{fullPage:!1}});return Buffer.from(f)}finally{await o.close()}}async function ye(e,n,t,r){if(!await X())return null;let i=await(await K()).newPage();try{await i.setCacheEnabled(!1),await i.setViewport({width:r?.width||800,height:r?.height||600,deviceScaleFactor:1});let c=r?.storyId||"",f=`${t}/iframe.html?viewMode=story&id=${c}&globals=`;await i.goto(f,{waitUntil:"load",timeout:15e3}),await i.waitForSelector("#storybook-root > *",{timeout:1e4}),await i.evaluate(d=>{let u=document.getElementById("storybook-root");u&&(u.innerHTML=d)},e),await i.evaluate(()=>document.fonts.ready),await new Promise(d=>setTimeout(d,500));let l=await i.evaluate(d=>{let u=document.querySelector("#storybook-root");if(!u)return null;let m=window.innerWidth,w=window.innerHeight,p=8;try{let x=new Function("return ("+d+")")()(u),v=x?.getBoundingClientRect(),T=!!v&&v.width>=m*.9&&v.height>=w*.9;if(x&&x!==u&&v&&v.width>0&&v.height>0&&!T)return{x:Math.max(0,v.x-p),y:Math.max(0,v.y-p),width:v.width+p*2,height:v.height+p*2}}catch{}function h(b){let x=b.getBoundingClientRect();if(x.width===0||x.height===0)return null;if(x.width<m*.8&&x.height>0)return x;for(let v of Array.from(b.children)){let T=window.getComputedStyle(v);if(T.position==="fixed"||T.position==="absolute"||T.display==="none"||T.visibility==="hidden")continue;let y=h(v);if(y)return y}return null}let S=h(u);if(S)return{x:Math.max(0,S.x-p),y:Math.max(0,S.y-p),width:S.width+p*2,height:S.height+p*2};let C=u.firstElementChild;if(C){let b=C.getBoundingClientRect();return{x:b.x,y:b.y,width:b.width,height:b.height}}return null},ge);if(!l)throw new Error("Could not determine component bounds from snapshot");let s=await i.screenshot({type:"png",clip:l});return Buffer.from(s)}finally{await i.close()}}async function D(){return X()}async function Y(){_&&(await _.close(),_=null)}async function J(e,n){return await e.evaluate(r=>{let o=document.getElementById("storybook-root")||document.getElementById("root"),a=null;if(o)try{a=new Function("return ("+r+")")()(o)}catch{a=o.firstElementChild}let i={};if(a){let s=window.getComputedStyle(a);for(let d=0;d<s.length;d++)i[s[d]]=s.getPropertyValue(s[d])}let c={backgroundColor:["transparent","rgba(0, 0, 0, 0)"],border:["none","0px none","0px none rgb(0, 0, 0)"],borderRadius:["0px"],boxShadow:["none"],opacity:["1"]};function f(s){return s.replace(/-([a-z])/g,(d,u)=>u.toUpperCase())}function l(s,d){if(d>4)return null;let u=s.tagName.toLowerCase();if(["script","style","link","meta","br","hr","noscript"].includes(u))return null;let m=s.className,w=typeof m=="string"?m:m?.baseVal||"",p=s.id||void 0,h=s.getAttribute("role")||void 0,S;for(let y of Array.from(s.childNodes))if(y.nodeType===3){let E=y.textContent?.trim();if(E){S=E.length>50?E.substring(0,50)+"...":E;break}}let C=u;p?C=`${u}#${p}`:w&&(C=`${u}.${w.split(" ").filter(Boolean).join(".")}`);let b=window.getComputedStyle(s),x=["background-color","border","border-radius","box-shadow","opacity","fill","stroke","stroke-width","font-size","font-family","font-weight","line-height","letter-spacing","color","text-align","display","padding","margin","gap","flex-direction","justify-content","align-items","width","height"],v={};for(let y of x){let E=b.getPropertyValue(y),P=f(y);E&&!c[P]?.includes(E)&&(v[P]=E)}if(u==="svg"||s.closest("svg"))for(let y of["fill","stroke","stroke-width","viewBox","d","r","cx","cy"]){let E=s.getAttribute(y);E&&(v[f(y)]=E)}let T=[];for(let y of Array.from(s.children)){let E=window.getComputedStyle(y);if(E.display==="none"||E.visibility==="hidden")continue;let P=l(y,d+1);P&&T.push(P)}return{selector:C,tagName:u,className:w,id:p,role:h,textContent:S,styles:v,children:T}}return{computedStyles:i,domTree:a?l(a,0):null}},n)}async function B(e,n=5e3){await e.evaluate(t=>new Promise(r=>{let o=setTimeout(r,t);try{let a=window.__STORYBOOK_ADDONS_CHANNEL__;if(a){let i=()=>{clearTimeout(o),a.off("storyRendered",i),setTimeout(r,100)};a.on("storyRendered",i)}else clearTimeout(o),setTimeout(r,300)}catch{clearTimeout(o),r()}}),n)}async function we(e,n,t=15e3){return await e.evaluate((r,o)=>{let a=window,i=a.__STORYBOOK_PREVIEW__,c=a.__STORYBOOK_ADDONS_CHANNEL__;return!i||!c||typeof i.renderSelection!="function"||typeof i.selectionStore?.setSelection!="function"?Promise.resolve("no-preview"):new Promise(f=>{let l=!1,s=w=>{if(!l){l=!0,clearTimeout(m);try{c.off("storyRendered",d),c.off("storyErrored",u),c.off("storyMissing",u)}catch{}f(w)}},d=w=>{let p=typeof w=="string"?w:w?.storyId||w?.id;(!p||p===r)&&setTimeout(()=>s("ok"),100)},u=()=>s("errored"),m=setTimeout(()=>s("timeout"),o);c.on("storyRendered",d),c.on("storyErrored",u),c.on("storyMissing",u);try{i.selectionStore.setSelection({storyId:r,viewMode:"story"}),i.renderSelection()}catch{s("nav-failed")}})},n,t)}async function Se(e){try{return await e.evaluate(()=>window.__STORYBOOK_PREVIEW__?.selectionStore?.selection?.storyId||null)}catch{return null}}async function Z(e){try{return await e.evaluate(()=>{let n=r=>r?r.getAttributeNames().sort().map(o=>{let a=r.getAttribute(o)??"";return o!=="class"?`${o}=${a}`:`class=${a.split(/\s+/).filter(c=>c&&!c.startsWith("sb-")).sort().join(" ")}`}).join("|"):"<missing>",t=document.getElementById("storybook-root")||document.getElementById("root");return[`html[${n(document.documentElement)}]`,`body[${n(document.body)}]`,`root[${n(t)}]`].join(" ")})}catch{return null}}var wt=6,St=15,bt=9e4,xt=2e4;function Ct(){let e=Number(process.env.UICOPILOT_WARM_MAX_USES);return Number.isFinite(e)&&e>0?e:St}function Et(){return process.env.UICOPILOT_WARM_CAPTURE!=="0"}var I=[],ee=[];function vt(e,n){return`${e}/iframe.html?viewMode=story&id=${n}&globals=`}function te(){let e=ee.shift();e&&e()}function be(){let e=Date.now(),n=I.filter(t=>!t.busy&&t.page&&e-t.lastUsedAt>bt);if(n.length===0){I.length===0&&Q();return}I=I.filter(t=>!n.includes(t));for(let t of n)t.page?.close().catch(()=>{});I.length===0&&Q()}var $=null;function Tt(){$||($=setInterval(be,3e4),$.unref?.())}function Q(){$&&(clearInterval($),$=null)}async function It(e,n,t){let r=await e.newPage();try{return await r.setViewport({width:800,height:600,deviceScaleFactor:1}),await r.goto(vt(n,t),{waitUntil:"load",timeout:xt}),await r.evaluate(()=>document.fonts.ready),await r.waitForSelector("#storybook-root > *",{timeout:1e4}),await B(r),r}catch(o){throw await r.close().catch(()=>{}),o}}async function Pt(e,n,t){for(;;){be();let r=I.find(o=>o.baseUrl===n&&!o.busy&&o.page);if(r)return r.busy=!0,{entry:r,fresh:!1};if(I.length<wt){let o={page:null,baseUrl:n,uses:0,lastUsedAt:Date.now(),busy:!0,baseline:null};I.push(o),Tt();try{return o.page=await It(e,n,t),o.baseline=await Z(o.page),{entry:o,fresh:!0}}catch{return I=I.filter(a=>a!==o),te(),null}}await new Promise(o=>ee.push(o))}}function R(e,n){e.busy=!1,e.uses++,e.lastUsedAt=Date.now(),(n||e.uses>=Ct())&&(I=I.filter(t=>t!==e),e.page?.close().catch(()=>{})),te()}async function xe(e,n,t,r){if(!Et())return{ok:!1,reason:"disabled"};let o=await Pt(e,n,t);if(!o)return{ok:!1,reason:"boot-failed"};let{entry:a,fresh:i}=o,c=a.page;try{if(!i){let l=await we(c,t);if(l!=="ok")return R(a,!0),{ok:!1,reason:`switch-${l}`};let s=await Se(c);if(s&&s!==t)return R(a,!0),{ok:!1,reason:"selection-mismatch"};if(a.baseline===null)return R(a,!0),{ok:!1,reason:"baseline-unavailable"};let d=await Z(c);if(d===null)return R(a,!0),{ok:!1,reason:"document-unreadable"};if(d!==a.baseline)return R(a,!0),{ok:!1,reason:"document-drift"};await c.evaluate(()=>document.fonts.ready)}let f=await r(c);return R(a,!1),{ok:!0,value:f,booted:i}}catch(f){return R(a,!0),{ok:!1,reason:`error:${f.message}`}}}async function ne(){Q();let e=I;for(I=[];ee.length;)te();await Promise.all(e.map(n=>n.page?.close().catch(()=>{})))}var _e=k.toString(),oe=null,H=null,Oe=!1;async function At(){if(!Oe){Oe=!0;try{let e=await Promise.resolve().then(()=>(Pe(),Ie));oe=e.validateCodeForFile,H=e.formatValidationResult,g.debug("Code validator loaded - fix validation enabled")}catch{g.debug("Code validator not available - skipping fix validation")}}}var Dt="UICOPILOT/APPLY_FIXES",Bt="UICOPILOT/FIX_STARTED",Ht="UICOPILOT/FIX_COMPLETED",Vt="UICOPILOT/FIX_FAILED",Re="UICOPILOT/ALL_FIXES_APPLIED",jt="UICOPILOT/RELOAD_REQUIRED",Le="UICOPILOT/WORKSPACE_PATH",Ut="UICOPILOT/REQUEST_WORKSPACE_PATH",zt="UICOPILOT/DISCOVER_COMPONENT_FILES",$e="UICOPILOT/COMPONENT_FILES_DISCOVERED";async function Me(e,n){let t=e.toLowerCase(),r=e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),o=[`src/**/fui-${t}/fui-${t}.css`,`src/**/fui-${t}/*.css`,`src/**/${t}/${t}.css`,`src/**/${r}/${r}.css`,`src/**/*${t}*.css`,`src/**/*${r}*.css`,`styles/**/*${t}*.css`],a=[`src/**/fui-${t}/fui-${t}.tsx`,`src/**/fui-${t}/*.tsx`,`src/**/${t}/${t}.tsx`,`src/**/${r}/${r}.tsx`,`src/**/*${r}*.tsx`,`src/**/*${r}*.jsx`],i=[],c=[];for(let p of o)try{let h=await(0,re.glob)(p,{cwd:n,nodir:!0,ignore:["**/node_modules/**","**/dist/**","**/.storybook/**"]});h.length>0&&i.push(...h)}catch{}for(let p of a)try{let h=await(0,re.glob)(p,{cwd:n,nodir:!0,ignore:["**/node_modules/**","**/dist/**","**/.storybook/**","**/*.stories.*","**/*.test.*"]});h.length>0&&c.push(...h)}catch{}let f=[...new Set(i)],l=[...new Set(c)],s=p=>{if(p.length===0)return;let h=p.find(b=>b.includes(`/fui-${t}/`)&&b.endsWith(".css"));if(h)return h;let S=p.find(b=>b.toLowerCase().includes(`/${t}/${t}.css`)||b.includes(`/${r}/${r}.css`));if(S)return S;let C=p.find(b=>b.toLowerCase().endsWith(`/${t}.css`)||b.endsWith(`/${r}.css`));return C||p[0]},d=p=>{if(p.length===0)return;let h=p.filter(x=>!x.includes(".stories.")&&!x.includes(".test."));if(h.length===0)return p[0];let S=h.find(x=>x.includes(`/fui-${t}/`)&&(x.endsWith(".tsx")||x.endsWith(".jsx")));if(S)return S;let C=h.find(x=>x.toLowerCase().includes(`/${t}/${t}.tsx`)||x.includes(`/${r}/${r}.tsx`));if(C)return C;let b=h.find(x=>x.toLowerCase().endsWith(`/${t}.tsx`)||x.endsWith(`/${r}.tsx`));return b||h[0]},u=s(f),m=d(l),w=[...f,...l];return g.debug(`Discovered files for "${e}":`,{cssFile:u,componentFile:m,totalMatches:w.length}),{cssFile:u,componentFile:m,allMatches:[...new Set(w)]}}var Wt=100;function Gt(e){return new Promise(n=>setTimeout(n,e))}async function Xt(e,n){if(await At(),!oe||!H)return g.debug(`Skipping validation (validator not available) for ${n}`),{valid:!0};let t=oe(e,n);if(!t.valid){let r=t.errors.map(o=>o.message).join("; ");return g.warn(`Code validation failed for ${n}:`),console.warn(H(t)),{valid:!1,error:r}}return t.warnings.length>0&&(g.warn(`Code validation warnings for ${n}:`),console.warn(H(t))),g.debug(`Validation passed for ${n}`),{valid:!0}}var Ne=!1;function ke(e){if(Ne)return e;Ne=!0;let n=process.cwd();return g.debug("Apply fixes initialized"),g.debug("Workspace:",n),e.emit(Le,{path:n}),e.on(Ut,()=>{g.debug("Workspace path requested by browser"),g.debug("Emitting workspace path response:",n),e.emit(Le,{path:n})}),e.on(zt,async t=>{let{componentName:r,storyId:o}=t;g.debug(`Discovering files for component: ${r}`);try{let a=await Me(r,n);e.emit($e,{componentName:r,storyId:o,...a,workspacePath:n})}catch(a){g.error("File discovery error:",a),e.emit($e,{componentName:r,storyId:o,error:a.message,allMatches:[]})}}),e.on(Dt,t=>{setTimeout(async()=>{try{let{issues:r,storybookRoot:o}=t,a=o||n;o?g.debug(`Using storybookRoot from API: ${o}`):g.debug(`Using process.cwd(): ${n}`),g.debug(`Received APPLY_FIXES for ${r.length} issue(s)`);let i=new Map;async function c(s){let d=s.targetFileType||"css",u=s.targetFilePath||s.generatedFix?.filePath,m="",w=s.title?.match(/^(\w+)\s/);if(w&&(m=w[1]),!m&&u){let S=u.match(/\/(\w+)\.(?:css|tsx|jsx)$/i);S&&(m=S[1])}if(!m)return g.debug(`Could not extract component name, using provided path: ${u}`),u||null;if(!i.has(m)){let S=await Me(m,a);i.set(m,S)}let p=i.get(m),h=d==="css"?p.cssFile:p.componentFile;return h?(g.debug(`Discovered ${d} path: ${h} (was: ${u})`),h):(g.debug(`No ${d} file discovered, using provided: ${u}`),u||null)}let f=[];for(let s of r){let{generatedFix:d}=s,u=s.targetFilePath||d?.filePath,m=await c(s)||u;g.debug("Processing issue:",{id:s.id,type:s.type,targetFileType:s.targetFileType||"css",targetPath:m,providedPath:u!==m?u:"(same)",codeLength:d?.code?.length||0}),e.emit(Bt,{issueId:s.id});try{if(!d||!d.code||!m)throw new Error("Missing AI-generated fix data (code or filePath)");g.debug("Code to write (first 200 chars):",d.code.substring(0,200)),g.debug(`Code length: ${d.code.length} chars`);let w=await Xt(d.code,m);if(!w.valid)throw new Error(`Code validation failed: ${w.error}. Fix was not applied to prevent breaking the file.`);let p=V.isAbsolute(m)?m:V.join(a,m);g.debug(`Writing to absolute path: ${p}`),await Fe.writeFile(p,d.code,"utf-8"),await Gt(Wt);let h={success:!0,issueId:s.id,filePath:m,timestamp:new Date};e.emit(Ht,{issueId:s.id,result:h}),g.debug(`\u2713 Applied ${s.targetFileType||"css"} fix to: ${m}`),f.push(h)}catch(w){let p=w.message||"Unknown error";e.emit(Vt,{issueId:s.id,error:p}),g.error(`\u2717 Error: ${p}`),f.push({success:!1,issueId:s.id,error:p,timestamp:new Date})}}let l={total:f.length,succeeded:f.filter(s=>s.success).length,failed:f.filter(s=>!s.success).length};e.emit(Re,{results:f,summary:l}),g.debug(`Completed: ${l.succeeded}/${l.total} fixes applied`),l.succeeded>0&&e.emit(jt,{message:"Fixes applied. If Storybook crashes due to HMR, please restart it.",filesChanged:f.filter(s=>s.success).map(s=>s.filePath)})}catch(r){g.error("Fatal error during fix application:",r),e.emit(Re,{results:[],summary:{total:t.issues?.length||0,succeeded:0,failed:t.issues?.length||0}})}},0)}),e}function Ae(e){let n=process.cwd();return e.plugins=e.plugins||[],e.plugins.push({name:"uicopilot-server-api",configureServer(t){t.middlewares.use("/__uicopilot/health",(a,i)=>{i.writeHead(200,{"Content-Type":"application/json"}),i.end(JSON.stringify({ok:!0,workspacePath:n}))}),t.middlewares.use("/__uicopilot/screenshot",async(a,i)=>{try{if(!await D()){i.writeHead(501,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Puppeteer not installed. Run: npm install puppeteer"}));return}let l=new URL(a.url||"",`http://${a.headers.host}`).searchParams.get("storyId");if(!l){i.writeHead(400,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Missing storyId parameter"}));return}let d=`http://${a.headers.host||"localhost:6006"}/iframe.html?viewMode=story&id=${l}&globals=`;g.debug(`Taking screenshot: ${l}`);let u=await q(d,{selector:"#storybook-root > *"});if(!u){i.writeHead(500,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Screenshot capture failed"}));return}let m=u.toString("base64");i.writeHead(200,{"Content-Type":"application/json"}),i.end(JSON.stringify({screenshot:`data:image/png;base64,${m}`}))}catch(c){g.error("Screenshot error:",c.message),i.writeHead(500,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:c.message}))}}),t.middlewares.use("/__uicopilot/capture",async(a,i)=>{try{if(!await D()){i.writeHead(501,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Puppeteer not installed"}));return}let f=new URL(a.url||"",`http://${a.headers.host}`),l=f.searchParams.get("storyId");if(!l){i.writeHead(400,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Missing storyId parameter"}));return}let s=f.searchParams.get("domOnly")==="1",d=a.headers.host||"localhost:6006",u=`http://${d}/iframe.html?viewMode=story&id=${l}&globals=`;g.debug(`Full capture${s?" (domOnly)":""}: ${l}`);let m=null;if(!s&&(m=await q(u,{selector:"#storybook-root > *"}),!m)){i.writeHead(500,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Screenshot capture failed"}));return}let w=await he(),p=f.searchParams.get("warm")==="0",h=null,S="cold";if(!p){let C=`http://${d}`,b=await xe(w,C,l,x=>J(x,_e));b.ok?(h=b.value,S=b.booted?"warm-boot":"warm"):g.debug(`Warm capture unavailable (${b.reason}): ${l}`)}if(!h){let C=await w.newPage();try{await C.setCacheEnabled(!1),await C.setViewport({width:800,height:600}),await C.goto(u,{waitUntil:"load",timeout:15e3}),await C.evaluate(()=>document.fonts.ready),await C.waitForSelector("#storybook-root > *",{timeout:1e4}),await B(C),h=await J(C,_e)}finally{await C.close()}}g.debug(`Capture path for ${l}: ${S}`),i.writeHead(200,{"Content-Type":"application/json"}),i.end(JSON.stringify({screenshot:m?`data:image/png;base64,${m.toString("base64")}`:void 0,computedStyles:h.computedStyles,domTree:h.domTree}))}catch(c){g.error("Capture error:",c.message),i.writeHead(500,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:c.message}))}}),t.middlewares.use("/__uicopilot/screenshot-snapshot",async(a,i)=>{if(a.method!=="POST"){i.writeHead(405,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"POST required"}));return}try{if(!await D()){i.writeHead(501,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Puppeteer not installed"}));return}let f=[];for await(let S of a)f.push(typeof S=="string"?Buffer.from(S):S);let l=JSON.parse(Buffer.concat(f).toString()),{html:s,stylesheetUrls:d,storyId:u}=l;if(!s){i.writeHead(400,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Missing html in body"}));return}let w=`http://${a.headers.host||"localhost:6006"}`;g.debug(`Taking snapshot screenshot for ${u||"unknown"}`);let p=await ye(s,d||[],w,{storyId:u});if(!p){i.writeHead(500,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Snapshot screenshot failed"}));return}let h=p.toString("base64");i.writeHead(200,{"Content-Type":"application/json"}),i.end(JSON.stringify({screenshot:`data:image/png;base64,${h}`}))}catch(c){g.error("Snapshot screenshot error:",c.message),i.writeHead(500,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:c.message}))}}),t.httpServer?.on("close",()=>{ne().catch(()=>{}).finally(()=>Y().catch(()=>{}))});let r=a=>{ne().catch(()=>{}).then(()=>Y()).catch(()=>{}).finally(()=>{process.kill(process.pid,a)})},o=globalThis;o.__uicopilotShutdownRegistered||(o.__uicopilotShutdownRegistered=!0,process.once("SIGINT",()=>r("SIGINT")),process.once("SIGTERM",()=>r("SIGTERM")))}}),e}var M={},Kt=()=>{if(typeof M<"u"&&M.url){let e=(0,ie.fileURLToPath)(M.url),n=(0,O.dirname)(e);return(0,O.join)(n,"manager.mjs")}return(0,O.join)(__dirname,"manager.mjs")},qt=()=>{if(typeof M<"u"&&M.url){let e=(0,ie.fileURLToPath)(M.url),n=(0,O.dirname)(e);return(0,O.join)(n,"preview.mjs")}return(0,O.join)(__dirname,"preview.mjs")};function Yt(e=[]){return[...e,Kt()]}function Jt(e=[]){return[...e,qt()]}0&&(module.exports={experimental_serverChannel,managerEntries,previewAnnotations,viteFinal});
1
+ "use strict";var Ye=Object.create;var V=Object.defineProperty;var Je=Object.getOwnPropertyDescriptor;var Ze=Object.getOwnPropertyNames;var Qe=Object.getPrototypeOf,et=Object.prototype.hasOwnProperty;var tt=(e,n)=>()=>(e&&(n=e(e=0)),n);var fe=(e,n)=>{for(var t in n)V(e,t,{get:n[t],enumerable:!0})},pe=(e,n,t,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of Ze(n))!et.call(e,o)&&o!==t&&V(e,o,{get:()=>n[o],enumerable:!(r=Je(n,o))||r.enumerable});return e};var me=(e,n,t)=>(t=e!=null?Ye(Qe(e)):{},pe(n||!e||!e.__esModule?V(t,"default",{value:e,enumerable:!0}):t,e)),nt=e=>pe(V({},"__esModule",{value:!0}),e);var Ae={};fe(Ae,{detectFileType:()=>ke,formatValidationResult:()=>qt,isValidCode:()=>Kt,validateCode:()=>Fe,validateCodeForFile:()=>Le});function jt(e,n={}){let t=n.minLength??Vt;return e.length<t?{code:"CODE_TOO_SHORT",message:`Code is too short (${e.length} chars). Minimum: ${t}. Likely incomplete or a snippet.`,severity:"error"}:null}function zt(e){let n=[/^[+-]{3}\s+[ab]\//m,/^@@\s+-\d+,\d+\s+\+\d+,\d+\s+@@/m,/^diff --git/m,/^index [a-f0-9]+\.\.[a-f0-9]+/m];for(let t of n)if(t.test(e))return{code:"CODE_IS_DIFF",message:"Code appears to be a diff/patch format, not complete file content.",severity:"error"};return null}function Ut(e){let n=e.split(`
2
+ `).filter(o=>o.trim()),t=n.filter(o=>o.trim().startsWith("//")||o.trim().startsWith("/*")||o.trim().startsWith("*")||o.trim().startsWith("#"));if(n.length>0&&t.length/n.length>.8)return{code:"CODE_IS_INSTRUCTIONS",message:"Code appears to be mostly comments/instructions, not actual implementation.",severity:"error"};let r=[/^\/\/\s*(Change|Replace|Update|Modify|Add|Remove|Delete)\s+(from|to|this|the)/im,/^\/\/\s*To:/m,/^\/\/\s*From:/m];for(let o of r)if(o.test(e))return{code:"CODE_IS_INSTRUCTIONS",message:'Code contains instruction comments (e.g., "// Change from:" / "// To:") instead of actual code.',severity:"error"};return null}function Wt(e){let n={"{":"}","[":"]","(":")"},t=[],r=!1,o="",l=!1;for(let i=0;i<e.length;i++){let d=e[i],h=e[i-1];if((d==='"'||d==="'"||d==="`")&&h!=="\\"){r?d===o&&(r=!1,l=!1):(r=!0,o=d,d==="`"&&(l=!0));continue}if(!r){if(n[d])t.push(n[d]);else if(Object.values(n).includes(d)&&t.pop()!==d)return{code:"UNBALANCED_BRACES",message:`Unbalanced braces/brackets detected. Found unexpected '${d}'.`,severity:"warning"}}}return t.length>0?{code:"UNBALANCED_BRACES",message:`Unbalanced braces/brackets. Missing: ${t.reverse().join("")}`,severity:"warning"}:null}function Ne(e,n={}){let t=[],r=[];e.includes("import ")||t.push({code:"TSX_MISSING_IMPORTS",message:"Component file missing import statements. A complete file must have imports.",severity:"error"}),e.includes("export ")||t.push({code:"TSX_MISSING_EXPORTS",message:"Component file missing exports. A complete file must export something.",severity:"error"});let o=/import\s+(?:React|\{[^}]*\})\s+from\s+['"]react['"]/.test(e);/<[A-Z][a-zA-Z]*|<[a-z]+[\s/>]/.test(e)&&!o&&r.push({code:"TSX_NO_REACT_IMPORT",message:"JSX detected but no React import. OK for React 17+ with automatic runtime.",severity:"warning"}),/export\s+(default\s+)?function\s+\w+/.test(e)||/export\s+(const|let)\s+\w+\s*[:=]/.test(e)||/export\s+default\s+\w+/.test(e)||/export\s+\{[^}]+\}/.test(e)||r.push({code:"TSX_NO_COMPONENT_DEF",message:"No clear component definition found. Expected function or const export.",severity:"warning"});let d=[{pattern:/\.\.\.\s*$/,message:'Code ends with "..." - likely truncated'},{pattern:/\/\/\s*\.\.\./m,message:'Contains "// ..." - likely incomplete'},{pattern:/{\s*\/\*\s*\.\.\.\s*\*\/\s*}/m,message:'Contains "{/* ... */}" placeholder'}];for(let{pattern:h,message:s}of d)h.test(e)&&t.push({code:"TSX_INCOMPLETE",message:s,severity:"error"});return{errors:t,warnings:r}}function Xt(e,n={}){let t=[],r=[];(e.includes("import ")||e.includes("export "))&&t.push({code:"CSS_HAS_JS_CODE",message:"CSS file contains JavaScript import/export statements. Wrong file type.",severity:"error"}),/[.#\w\[\]]+\s*\{[\s\S]*?:\s*[^;]+;?[\s\S]*?\}/.test(e)||t.push({code:"CSS_INVALID_SYNTAX",message:"No valid CSS syntax found. Expected selector { property: value; } pattern.",severity:"error"});let l=(e.match(/\{[^}]+\}/g)||[]).length;return l===0&&t.push({code:"CSS_NO_RULES",message:"No CSS rules found. File appears empty or malformed.",severity:"error"}),(e.includes("/* ... */")||e.includes("// ..."))&&t.push({code:"CSS_INCOMPLETE",message:"CSS contains placeholder comments (/* ... */) - likely incomplete.",severity:"error"}),l>0&&l<3&&!n.allowPartial&&r.push({code:"CSS_FEW_RULES",message:`Only ${l} CSS rule(s) found. Might be incomplete.`,severity:"warning"}),{errors:t,warnings:r}}function Gt(e,n={}){let t=[],r=[];return e.includes("import ")||t.push({code:"STORIES_MISSING_IMPORTS",message:"Stories file missing import statements.",severity:"error"}),/@storybook\//.test(e)||t.push({code:"STORIES_NO_STORYBOOK_IMPORT",message:"Stories file must import from @storybook/* (e.g., @storybook/react).",severity:"error"}),e.includes("Meta")||e.includes("ComponentMeta")||r.push({code:"STORIES_NO_META_TYPE",message:"Stories file should have Meta type import for type safety.",severity:"warning"}),e.includes("StoryObj")||e.includes("ComponentStory")||e.includes("Story")||r.push({code:"STORIES_NO_STORY_TYPE",message:"Stories file should have StoryObj/Story type for type safety.",severity:"warning"}),e.includes("export default")||t.push({code:"STORIES_NO_DEFAULT_EXPORT",message:"Stories file must have a default export (meta configuration).",severity:"error"}),/export\s+const\s+\w+\s*[:=]/.test(e)||t.push({code:"STORIES_NO_STORY_EXPORTS",message:"Stories file must have at least one named export (story definition).",severity:"error"}),/import\s+\{?\s*\w+\s*\}?\s+from\s+['"]\.\//.test(e)||r.push({code:"STORIES_NO_COMPONENT_IMPORT",message:"Stories file should import the component being documented.",severity:"warning"}),(e.includes("// ... other")||e.includes("/* ... */"))&&t.push({code:"STORIES_INCOMPLETE",message:"Stories file contains placeholder comments - likely incomplete.",severity:"error"}),{errors:t,warnings:r}}function ke(e){let n=e.toLowerCase();if(n.includes(".stories."))return"stories";switch(n.split(".").pop()){case"tsx":return"tsx";case"jsx":return"jsx";case"ts":return"ts";case"js":return"js";case"css":return"css";case"scss":return"scss";case"less":return"less";default:return"unknown"}}function Fe(e,n,t={}){let r={valid:!0,fileType:n,errors:[],warnings:[]},o=jt(e,t);o&&r.errors.push(o);let l=zt(e);l&&r.errors.push(l);let i=Ut(e);i&&r.errors.push(i);let d=Wt(e);switch(d&&(t.strict?r.errors.push({...d,severity:"error"}):r.warnings.push(d)),n){case"stories":{let{errors:h,warnings:s}=Gt(e,t);r.errors.push(...h),r.warnings.push(...s);break}case"tsx":case"jsx":{let{errors:h,warnings:s}=Ne(e,t);r.errors.push(...h),r.warnings.push(...s);break}case"css":case"scss":case"less":{let{errors:h,warnings:s}=Xt(e,t);r.errors.push(...h),r.warnings.push(...s);break}case"ts":case"js":{let{errors:h,warnings:s}=Ne(e,t);r.errors.push(...h),r.warnings.push(...s.filter(c=>!c.code.includes("JSX")));break}default:break}return r.valid=r.errors.length===0,r}function Le(e,n,t={}){let r=ke(n);return Fe(e,r,t)}function Kt(e,n,t={}){return Le(e,n,t).valid}function qt(e){if(e.valid&&e.warnings.length===0)return`\u2713 Valid ${e.fileType} code`;let n=[];if(e.valid)n.push(`\u26A0 Valid ${e.fileType} code with warnings`);else{n.push(`\u2717 Invalid ${e.fileType} code`),n.push(""),n.push("Errors:");for(let t of e.errors)n.push(` - [${t.code}] ${t.message}`)}if(e.warnings.length>0){n.push(""),n.push("Warnings:");for(let t of e.warnings)n.push(` - [${t.code}] ${t.message}`)}return n.join(`
3
+ `)}var Vt,De=tt(()=>{"use strict";Vt=50});var fn={};fe(fn,{experimental_serverChannel:()=>Ge,managerEntries:()=>un,previewAnnotations:()=>dn,viteFinal:()=>Ke});module.exports=nt(fn);var N=require("path"),de=require("url");var Xe=me(require("fs/promises")),K=me(require("path")),le=require("glob");var Y=require("fs"),J=require("module");var q={NAME:"UI Parity",SHORT:"Parity",DOMAIN:"uiparity.com",MARKETING_URL:"https://uiparity.com",APP_URL:"https://app.uiparity.com",API_URL:"https://api.uiparity.com",SUPPORT_EMAIL:"feedback@uiparity.com",TAGLINE:"Pixel-perfect isn't a feeling. It's a score."};function rt(){if(typeof process<"u"&&process.env)return process.env.UICOPILOT_DEBUG==="1";if(typeof globalThis<"u"&&"localStorage"in globalThis)try{return globalThis.localStorage.getItem("uicopilot_debug")==="1"}catch{return!1}return!1}var j=`[${q.NAME}]`,y={debug:(...e)=>{rt()&&console.log(j,...e)},info:(...e)=>{console.log(j,...e)},warn:(...e)=>{console.warn(j,...e)},error:(...e)=>{console.error(j,...e)}};var wt=["flex","inline-flex"],bt=["grid","inline-grid"],Bn=[...wt,...bt];function z(e){let r=e.ownerDocument?.defaultView;if(!r)return e.firstElementChild??e;let o=e.getBoundingClientRect(),l=u=>{let a=r.getComputedStyle(u);if(a.position==="fixed"||a.display==="none"||a.visibility==="hidden")return!0;let p=u.getBoundingClientRect();return p.width===0||p.height===0||u.children.length===0&&!(u.textContent??"").trim()},i=u=>{if(o.width===0||o.height===0)return!1;let a=u.getBoundingClientRect();return a.width>=o.width*.9&&a.height>=o.height*.9},d=[],h=u=>{for(let a of Array.from(u.children))a.hasAttribute("data-uicopilot-instance")?d.push(a):h(a)};if(h(e),d.length>1){let u=g=>{let m=[];for(let f=g;f&&f!==e;f=f.parentElement)m.unshift(f);return m},a=d.map(u),p=e;for(let g=0;;g+=1){let m=a[0][g];if(!m||!a.every(f=>f[g]===m))break;p=m}if(p!==e)return p}let s=e;for(let u=0;u<6;u+=1){if(s!==e&&s.hasAttribute("data-uicopilot-instance"))return s;let a=Array.from(s.children).filter(p=>!l(p));if(a.length!==1||s!==e&&!i(s))break;s=a[0]}if(s!==e&&i(s)){let u=Array.from(s.children).filter(a=>!l(a));if(u.length>1&&c(u))return u[0].setAttribute("data-uicopilot-instances",String(u.length)),u[0]}if(s===e)return e.firstElementChild??e;return s;function c(u){let a=g=>{let m=g.className,f=typeof m=="string"?m:"";return`${g.tagName}.${f.split(" ")[0]??""}`},p=a(u[0]);return u.every(g=>a(g)===p)}}var vt={},Ce=z.toString(),F=null,$=null,Ee=!1;async function Q(){if(Ee)return!!F;if(Ee=!0,process.env.STORYBOOK_UICOPILOT_NO_PUPPETEER==="true")return y.debug("Puppeteer disabled via STORYBOOK_UICOPILOT_NO_PUPPETEER flag"),!1;let e=(0,J.createRequire)(process.cwd()+"/");try{return F=e("puppeteer"),y.debug("Puppeteer loaded \u2014 server-side screenshots enabled"),!0}catch{}try{return F=e("puppeteer-core"),y.debug("puppeteer-core loaded from the project \u2014 capture enabled"),!0}catch{}try{return F=(0,J.createRequire)(vt.url)("puppeteer-core"),y.debug("puppeteer-core loaded from the addon \u2014 capture enabled"),!0}catch{}return y.debug("No Puppeteer implementation available \u2014 server-side capture disabled"),!1}function Tt(){let e=process.env.STORYBOOK_UICOPILOT_CHROME_PATH;if(e){if((0,Y.existsSync)(e))return e;y.warn(`STORYBOOK_UICOPILOT_CHROME_PATH is set to "${e}" but no file exists there \u2014 falling back to discovery`)}let n=process.platform==="win32",t=process.env,r=n?[`${t.PROGRAMFILES??"C:\\Program Files"}\\Google\\Chrome\\Application\\chrome.exe`,`${t["PROGRAMFILES(X86)"]??"C:\\Program Files (x86)"}\\Google\\Chrome\\Application\\chrome.exe`,`${t.LOCALAPPDATA??""}\\Google\\Chrome\\Application\\chrome.exe`,`${t.PROGRAMFILES??"C:\\Program Files"}\\Microsoft\\Edge\\Application\\msedge.exe`].filter(o=>!o.startsWith("\\")):["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary","/Applications/Chromium.app/Contents/MacOS/Chromium","/usr/bin/google-chrome","/usr/bin/google-chrome-stable","/usr/bin/chromium-browser","/usr/bin/chromium","/snap/bin/chromium"];for(let o of r)if((0,Y.existsSync)(o))return o}async function Te(){return ee()}var U=class extends Error{constructor(){super("No Chrome or Chromium found. Install Google Chrome, or set STORYBOOK_UICOPILOT_CHROME_PATH to an executable. (Capture needs a real browser to render your stories.)"),this.name="BrowserNotFoundError"}},Z=class extends Error{constructor(n,t){super(`Found a browser at "${n}" but could not drive it: ${t instanceof Error?t.message:String(t)}. This usually means the installed browser and puppeteer-core versions are incompatible.`),this.name="BrowserIncompatibleError"}};async function ee(){if($&&$.connected)return $;let e=Tt();if(!e&&!It())throw new U;let n={headless:!0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-dev-shm-usage"],...e?{executablePath:e}:{}};try{$=await F.launch(n)}catch(t){throw e?new Z(e,t):new U}return y.debug("Headless Chrome launched for screenshots"),$}function It(){try{return typeof F?.executablePath=="function"}catch{return!1}}async function te(e,n){if(!await Q())return null;let o=await(await ee()).newPage();try{await o.setCacheEnabled(!1),await o.setViewport({width:n?.width||800,height:n?.height||600,deviceScaleFactor:1}),await o.goto(e,{waitUntil:"load",timeout:15e3}),await o.evaluate(()=>document.fonts.ready),await o.waitForSelector("#storybook-root > *",{timeout:1e4}),await o.waitForFunction(()=>new Promise(s=>{let c=document.querySelectorAll("style").length,u=0,a=()=>{let p=document.querySelectorAll("style").length;if(p===c){if(u++,u>=3){s(!0);return}}else u=0,c=p;setTimeout(a,100)};setTimeout(a,200)}),{timeout:5e3}).catch(()=>{}),await new Promise(s=>setTimeout(s,500));let l=await o.evaluate(s=>{let c=document.querySelector("#storybook-root");if(!c)return null;let u=window.innerHeight,a=window.innerWidth,p=E=>E.setAttribute("data-uic-drilled",""),g=()=>{let E=document.createElement("style");E.id="uic-drilled-bg-reset",E.textContent="[data-uic-drilled] { background: transparent !important; border-color: transparent !important; box-shadow: none !important; }",document.head.appendChild(E),document.body.offsetHeight};try{let T=new Function("return ("+s+")")()(c),C=T?.getBoundingClientRect(),_=!!C&&C.width>=a*.9&&C.height>=u*.9;if(T&&T!==c&&C&&C.width>0&&C.height>0&&!_){for(let P=T.parentElement;P&&P!==c;P=P.parentElement)p(P);return g(),{top:C.top,bottom:C.bottom,left:C.left,right:C.right}}}catch{}let m=1/0,f=0,w=1/0,b=0,x=!1;function S(E){for(let T of Array.from(E.children)){let C=window.getComputedStyle(T);if(C.display==="none"||C.visibility==="hidden"||C.position==="fixed"||C.position==="absolute")continue;let _=T.getBoundingClientRect();if(_.height<=0||_.width<=0)continue;if((_.width>=a*.9||_.height>=u*.9)&&T.children.length>0){T.setAttribute("data-uic-drilled",""),S(T);continue}if(T.children.length===1){let D=C.backgroundColor,R=D==="rgba(0, 0, 0, 0)"||D==="transparent"||D==="",H=C.borderStyle!=="none"&&C.borderWidth!=="0px",v=C.boxShadow!=="none",I=!R||H||v,B=T.children[0].getBoundingClientRect(),qe=B.width>=_.width*.95&&B.height>=_.height*.95;if(!I||qe){T.setAttribute("data-uic-drilled",""),S(T);continue}}m=Math.min(m,_.top),f=Math.max(f,_.bottom),w=Math.min(w,_.left),b=Math.max(b,_.right),x=!0}}return S(c),x?(g(),{top:m,bottom:f,left:w,right:b}):null},Ce);await o.evaluate(()=>new Promise(s=>requestAnimationFrame(()=>s())));let i=4,d=l?{x:Math.max(0,l.left-i),y:Math.max(0,l.top-i),width:Math.min(l.right-l.left+i*2,800),height:Math.min(l.bottom-l.top+i*2,600)}:void 0,h=await o.screenshot({type:"png",omitBackground:!0,...d?{clip:d}:{fullPage:!1}});return Buffer.from(h)}finally{await o.close()}}async function Ie(e,n,t,r){if(!await Q())return null;let i=await(await ee()).newPage();try{await i.setCacheEnabled(!1),await i.setViewport({width:r?.width||800,height:r?.height||600,deviceScaleFactor:1});let d=r?.storyId||"",h=`${t}/iframe.html?viewMode=story&id=${d}&globals=`;await i.goto(h,{waitUntil:"load",timeout:15e3}),await i.waitForSelector("#storybook-root > *",{timeout:1e4}),await i.evaluate(u=>{let a=document.getElementById("storybook-root");a&&(a.innerHTML=u)},e),await i.evaluate(()=>document.fonts.ready),await new Promise(u=>setTimeout(u,500));let s=await i.evaluate(u=>{let a=document.querySelector("#storybook-root");if(!a)return null;let p=window.innerWidth,g=window.innerHeight,m=8;try{let S=new Function("return ("+u+")")()(a),E=S?.getBoundingClientRect(),T=!!E&&E.width>=p*.9&&E.height>=g*.9;if(S&&S!==a&&E&&E.width>0&&E.height>0&&!T)return{x:Math.max(0,E.x-m),y:Math.max(0,E.y-m),width:E.width+m*2,height:E.height+m*2}}catch{}function f(x){let S=x.getBoundingClientRect();if(S.width===0||S.height===0)return null;if(S.width<p*.8&&S.height>0)return S;for(let E of Array.from(x.children)){let T=window.getComputedStyle(E);if(T.position==="fixed"||T.position==="absolute"||T.display==="none"||T.visibility==="hidden")continue;let C=f(E);if(C)return C}return null}let w=f(a);if(w)return{x:Math.max(0,w.x-m),y:Math.max(0,w.y-m),width:w.width+m*2,height:w.height+m*2};let b=a.firstElementChild;if(b){let x=b.getBoundingClientRect();return{x:x.x,y:x.y,width:x.width,height:x.height}}return null},Ce);if(!s)throw new Error("Could not determine component bounds from snapshot");let c=await i.screenshot({type:"png",clip:s});return Buffer.from(c)}finally{await i.close()}}async function W(){return Q()}async function ne(){$&&(await $.close(),$=null)}function ve(e,n){let t=e.getBoundingClientRect(),r=n.getBoundingClientRect();return{x:Math.round(t.left-r.left),y:Math.round(t.top-r.top),w:Math.round(t.width),h:Math.round(t.height)}}function _e(e,n){let t=s=>{let c=Object.keys(s).find(u=>u.startsWith("__reactFiber$"));return c?s[c]:void 0},r=s=>!!s&&s.nodeType===1&&typeof s.getBoundingClientRect=="function",o=s=>s.elementType===e||s.type===e,l=s=>{for(let c=s?.child??null;c;c=c.sibling){if(c.tag===5&&r(c.stateNode)){let a=c.stateNode.getBoundingClientRect();if(a.width>0&&a.height>0)return c.stateNode}let u=l(c);if(u)return u}},i=s=>{for(let c=s.return;c;c=c.return)if(o(c))return!0;return!1},d=new Set,h=[];for(let s of n)for(let c of[s,...Array.from(s.querySelectorAll("*"))])for(let u=t(c)??null;u;u=u.return){if(!o(u)||d.has(u)||(d.add(u),i(u)))continue;let a=l(u);a&&h.push(a)}return h}async function Pe(e,n,t,r){let o=e.document;o.querySelectorAll("[data-uicopilot-instance]").forEach(a=>a.removeAttribute("data-uicopilot-instance")),o.querySelectorAll("[data-uicopilot-instance-count]").forEach(a=>a.removeAttribute("data-uicopilot-instance-count"));let l=e.__STORYBOOK_PREVIEW__;if(!l?.storyStoreValue)return 0;let i;try{i=await l.storyStoreValue.loadStory({storyId:n})}catch{return 0}let d=r??o.getElementById("storybook-root")??o.getElementById("root");if(!d||!i.component)return 0;let h=r?[]:Array.from(o.body.children).filter(a=>a!==d&&!a.contains(d)&&a.tagName!=="SCRIPT"),s=[d,...h],c=t(i.component,s);if(c.length===0&&i.subcomponents){let a=Object.values(i.subcomponents).flatMap(p=>p?t(p,s):[]);c=Array.from(new Set(a)).filter(p=>!a.some(g=>g!==p&&g.contains(p))).sort((p,g)=>p.compareDocumentPosition(g)&4?-1:1)}return c.forEach((a,p)=>a.setAttribute("data-uicopilot-instance",String(p+1))),[d,...h].some(a=>[a,...Array.from(a.querySelectorAll("*"))].some(p=>Object.keys(p).some(g=>g.startsWith("__reactFiber$"))))&&d.setAttribute("data-uicopilot-instance-count",String(c.length)),c.length}var _t=ve.toString(),Pt=_e.toString(),Ot=Pe.toString(),Mt="data-uicopilot-instance";async function re(e,n,t){return t&&await e.evaluate(async(o,l,i)=>{let d=new Function("return ("+o+")")(),h=new Function("return ("+l+")")();return d(window,i,h)},Ot,Pt,t),await e.evaluate((o,l,i)=>{let d=new Function("return ("+l+")")(),h=document.getElementById("storybook-root")||document.getElementById("root"),s=null;if(h)try{s=new Function("return ("+o+")")()(h)}catch{s=h.firstElementChild}let c={};if(s){let f=window.getComputedStyle(s);for(let w=0;w<f.length;w++)c[f[w]]=f.getPropertyValue(f[w])}let u={backgroundColor:["transparent","rgba(0, 0, 0, 0)"],border:["none","0px none","0px none rgb(0, 0, 0)"],borderRadius:["0px"],boxShadow:["none"],opacity:["1"]};function a(f){return f.replace(/-([a-z])/g,(w,b)=>b.toUpperCase())}function p(f,w){if(w>4)return null;let b=f.tagName.toLowerCase();if(["script","style","link","meta","br","hr","noscript"].includes(b))return null;let x=f.className,S=typeof x=="string"?x:x?.baseVal||"",E=f.id||void 0,T=f.getAttribute("role")||void 0,C;for(let v of Array.from(f.childNodes))if(v.nodeType===3){let I=v.textContent?.trim();if(I){C=I.length>50?I.substring(0,50)+"...":I;break}}let _=b;E?_=`${b}#${E}`:S&&(_=`${b}.${S.split(" ").filter(Boolean).join(".")}`);let P=window.getComputedStyle(f),D=["background-color","border","border-radius","box-shadow","opacity","fill","stroke","stroke-width","font-size","font-family","font-weight","line-height","letter-spacing","color","text-align","display","padding","margin","gap","flex-direction","justify-content","align-items","width","height"],R={};for(let v of D){let I=P.getPropertyValue(v),M=a(v);I&&!u[M]?.includes(I)&&(R[M]=I)}if(!R.border){let v=["top","right","bottom","left"].filter(I=>parseFloat(P.getPropertyValue(`border-${I}-width`))>0&&P.getPropertyValue(`border-${I}-style`)!=="none");if(v.length>0){let I=v.reduce((M,B)=>parseFloat(P.getPropertyValue(`border-${B}-width`))>parseFloat(P.getPropertyValue(`border-${M}-width`))?B:M);R.border=`${P.getPropertyValue(`border-${I}-width`)} ${P.getPropertyValue(`border-${I}-style`)} ${P.getPropertyValue(`border-${I}-color`)}`,R.borderSides=v.join(" ")}}if(b==="svg"||f.closest("svg"))for(let v of["fill","stroke","stroke-width","viewBox","d","r","cx","cy"]){let I=f.getAttribute(v);I&&(R[a(v)]=I)}let H=[];for(let v of Array.from(f.children)){let I=window.getComputedStyle(v);if(I.display==="none"||I.visibility==="hidden")continue;let M=p(v,w+1);M&&H.push(M)}return{selector:_,tagName:b,className:S,id:E,role:T,textContent:C,rect:s?d(f,s):void 0,instance:Number(f.getAttribute(i))>0?Number(f.getAttribute(i)):void 0,styles:R,children:H}}let g=s?p(s,0):null,m=document.querySelector("["+i+"-count]");return g&&m&&(g.instanceCount=Number(m.getAttribute(i+"-count"))),{computedStyles:c,domTree:g}},n,_t,Mt)}async function X(e,n=5e3){await e.evaluate(t=>new Promise(r=>{let o=setTimeout(r,t);try{let l=window.__STORYBOOK_ADDONS_CHANNEL__;if(l){let i=()=>{clearTimeout(o),l.off("storyRendered",i),setTimeout(r,100)};l.on("storyRendered",i)}else clearTimeout(o),setTimeout(r,300)}catch{clearTimeout(o),r()}}),n)}async function Oe(e,n,t=15e3){return await e.evaluate((r,o)=>{let l=window,i=l.__STORYBOOK_PREVIEW__,d=l.__STORYBOOK_ADDONS_CHANNEL__;return!i||!d||typeof i.renderSelection!="function"||typeof i.selectionStore?.setSelection!="function"?Promise.resolve("no-preview"):new Promise(h=>{let s=!1,c=g=>{if(!s){s=!0,clearTimeout(p);try{d.off("storyRendered",u),d.off("storyErrored",a),d.off("storyMissing",a)}catch{}h(g)}},u=g=>{let m=typeof g=="string"?g:g?.storyId||g?.id;(!m||m===r)&&setTimeout(()=>c("ok"),100)},a=()=>c("errored"),p=setTimeout(()=>c("timeout"),o);d.on("storyRendered",u),d.on("storyErrored",a),d.on("storyMissing",a);try{i.selectionStore.setSelection({storyId:r,viewMode:"story"}),i.renderSelection()}catch{c("nav-failed")}})},n,t)}async function Me(e){try{return await e.evaluate(()=>window.__STORYBOOK_PREVIEW__?.selectionStore?.selection?.storyId||null)}catch{return null}}async function oe(e){try{return await e.evaluate(()=>{let n=r=>r?r.getAttributeNames().sort().map(o=>{let l=r.getAttribute(o)??"";return o!=="class"?`${o}=${l}`:`class=${l.split(/\s+/).filter(d=>d&&!d.startsWith("sb-")).sort().join(" ")}`}).join("|"):"<missing>",t=document.getElementById("storybook-root")||document.getElementById("root");return[`html[${n(document.documentElement)}]`,`body[${n(document.body)}]`,`root[${n(t)}]`].join(" ")})}catch{return null}}var Rt=6,$t=15,Nt=9e4,kt=2e4;function Ft(){let e=Number(process.env.UICOPILOT_WARM_MAX_USES);return Number.isFinite(e)&&e>0?e:$t}function Lt(){return process.env.UICOPILOT_WARM_CAPTURE!=="0"}var O=[],se=[];function At(e,n){return`${e}/iframe.html?viewMode=story&id=${n}&globals=`}function ae(){let e=se.shift();e&&e()}function Re(){let e=Date.now(),n=O.filter(t=>!t.busy&&t.page&&e-t.lastUsedAt>Nt);if(n.length===0){O.length===0&&ie();return}O=O.filter(t=>!n.includes(t));for(let t of n)t.page?.close().catch(()=>{});O.length===0&&ie()}var L=null;function Dt(){L||(L=setInterval(Re,3e4),L.unref?.())}function ie(){L&&(clearInterval(L),L=null)}async function Bt(e,n,t){let r=await e.newPage();try{return await r.setViewport({width:800,height:600,deviceScaleFactor:1}),await r.goto(At(n,t),{waitUntil:"load",timeout:kt}),await r.evaluate(()=>document.fonts.ready),await r.waitForSelector("#storybook-root > *",{timeout:1e4}),await X(r),r}catch(o){throw await r.close().catch(()=>{}),o}}async function Ht(e,n,t){for(;;){Re();let r=O.find(o=>o.baseUrl===n&&!o.busy&&o.page);if(r)return r.busy=!0,{entry:r,fresh:!1};if(O.length<Rt){let o={page:null,baseUrl:n,uses:0,lastUsedAt:Date.now(),busy:!0,baseline:null};O.push(o),Dt();try{return o.page=await Bt(e,n,t),o.baseline=await oe(o.page),{entry:o,fresh:!0}}catch{return O=O.filter(l=>l!==o),ae(),null}}await new Promise(o=>se.push(o))}}function k(e,n){e.busy=!1,e.uses++,e.lastUsedAt=Date.now(),(n||e.uses>=Ft())&&(O=O.filter(t=>t!==e),e.page?.close().catch(()=>{})),ae()}async function $e(e,n,t,r){if(!Lt())return{ok:!1,reason:"disabled"};let o=await Ht(e,n,t);if(!o)return{ok:!1,reason:"boot-failed"};let{entry:l,fresh:i}=o,d=l.page;try{if(!i){let s=await Oe(d,t);if(s!=="ok")return k(l,!0),{ok:!1,reason:`switch-${s}`};let c=await Me(d);if(c&&c!==t)return k(l,!0),{ok:!1,reason:"selection-mismatch"};if(l.baseline===null)return k(l,!0),{ok:!1,reason:"baseline-unavailable"};let u=await oe(d);if(u===null)return k(l,!0),{ok:!1,reason:"document-unreadable"};if(u!==l.baseline)return k(l,!0),{ok:!1,reason:"document-drift"};await d.evaluate(()=>document.fonts.ready)}let h=await r(d);return k(l,!1),{ok:!0,value:h,booted:i}}catch(h){return k(l,!0),{ok:!1,reason:`error:${h.message}`}}}async function ce(){ie();let e=O;for(O=[];se.length;)ae();await Promise.all(e.map(n=>n.page?.close().catch(()=>{})))}var Be=z.toString(),ue=null,G=null,He=!1;async function Yt(){if(!He){He=!0;try{let e=await Promise.resolve().then(()=>(De(),Ae));ue=e.validateCodeForFile,G=e.formatValidationResult,y.debug("Code validator loaded - fix validation enabled")}catch{y.debug("Code validator not available - skipping fix validation")}}}var Jt="UICOPILOT/APPLY_FIXES",Zt="UICOPILOT/FIX_STARTED",Qt="UICOPILOT/FIX_COMPLETED",en="UICOPILOT/FIX_FAILED",Ve="UICOPILOT/ALL_FIXES_APPLIED",tn="UICOPILOT/RELOAD_REQUIRED",je="UICOPILOT/WORKSPACE_PATH",nn="UICOPILOT/REQUEST_WORKSPACE_PATH",rn="UICOPILOT/DISCOVER_COMPONENT_FILES",ze="UICOPILOT/COMPONENT_FILES_DISCOVERED";async function Ue(e,n){let t=e.toLowerCase(),r=e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),o=[`src/**/fui-${t}/fui-${t}.css`,`src/**/fui-${t}/*.css`,`src/**/${t}/${t}.css`,`src/**/${r}/${r}.css`,`src/**/*${t}*.css`,`src/**/*${r}*.css`,`styles/**/*${t}*.css`],l=[`src/**/fui-${t}/fui-${t}.tsx`,`src/**/fui-${t}/*.tsx`,`src/**/${t}/${t}.tsx`,`src/**/${r}/${r}.tsx`,`src/**/*${r}*.tsx`,`src/**/*${r}*.jsx`],i=[],d=[];for(let m of o)try{let f=await(0,le.glob)(m,{cwd:n,nodir:!0,ignore:["**/node_modules/**","**/dist/**","**/.storybook/**"]});f.length>0&&i.push(...f)}catch{}for(let m of l)try{let f=await(0,le.glob)(m,{cwd:n,nodir:!0,ignore:["**/node_modules/**","**/dist/**","**/.storybook/**","**/*.stories.*","**/*.test.*"]});f.length>0&&d.push(...f)}catch{}let h=[...new Set(i)],s=[...new Set(d)],c=m=>{if(m.length===0)return;let f=m.find(x=>x.includes(`/fui-${t}/`)&&x.endsWith(".css"));if(f)return f;let w=m.find(x=>x.toLowerCase().includes(`/${t}/${t}.css`)||x.includes(`/${r}/${r}.css`));if(w)return w;let b=m.find(x=>x.toLowerCase().endsWith(`/${t}.css`)||x.endsWith(`/${r}.css`));return b||m[0]},u=m=>{if(m.length===0)return;let f=m.filter(S=>!S.includes(".stories.")&&!S.includes(".test."));if(f.length===0)return m[0];let w=f.find(S=>S.includes(`/fui-${t}/`)&&(S.endsWith(".tsx")||S.endsWith(".jsx")));if(w)return w;let b=f.find(S=>S.toLowerCase().includes(`/${t}/${t}.tsx`)||S.includes(`/${r}/${r}.tsx`));if(b)return b;let x=f.find(S=>S.toLowerCase().endsWith(`/${t}.tsx`)||S.endsWith(`/${r}.tsx`));return x||f[0]},a=c(h),p=u(s),g=[...h,...s];return y.debug(`Discovered files for "${e}":`,{cssFile:a,componentFile:p,totalMatches:g.length}),{cssFile:a,componentFile:p,allMatches:[...new Set(g)]}}var on=100;function sn(e){return new Promise(n=>setTimeout(n,e))}async function an(e,n){if(await Yt(),!ue||!G)return y.debug(`Skipping validation (validator not available) for ${n}`),{valid:!0};let t=ue(e,n);if(!t.valid){let r=t.errors.map(o=>o.message).join("; ");return y.warn(`Code validation failed for ${n}:`),console.warn(G(t)),{valid:!1,error:r}}return t.warnings.length>0&&(y.warn(`Code validation warnings for ${n}:`),console.warn(G(t))),y.debug(`Validation passed for ${n}`),{valid:!0}}var We=!1;function Ge(e){if(We)return e;We=!0;let n=process.cwd();return y.debug("Apply fixes initialized"),y.debug("Workspace:",n),e.emit(je,{path:n}),e.on(nn,()=>{y.debug("Workspace path requested by browser"),y.debug("Emitting workspace path response:",n),e.emit(je,{path:n})}),e.on(rn,async t=>{let{componentName:r,storyId:o}=t;y.debug(`Discovering files for component: ${r}`);try{let l=await Ue(r,n);e.emit(ze,{componentName:r,storyId:o,...l,workspacePath:n})}catch(l){y.error("File discovery error:",l),e.emit(ze,{componentName:r,storyId:o,error:l.message,allMatches:[]})}}),e.on(Jt,t=>{setTimeout(async()=>{try{let{issues:r,storybookRoot:o}=t,l=o||n;o?y.debug(`Using storybookRoot from API: ${o}`):y.debug(`Using process.cwd(): ${n}`),y.debug(`Received APPLY_FIXES for ${r.length} issue(s)`);let i=new Map;async function d(c){let u=c.targetFileType||"css",a=c.targetFilePath||c.generatedFix?.filePath,p="",g=c.title?.match(/^(\w+)\s/);if(g&&(p=g[1]),!p&&a){let w=a.match(/\/(\w+)\.(?:css|tsx|jsx)$/i);w&&(p=w[1])}if(!p)return y.debug(`Could not extract component name, using provided path: ${a}`),a||null;if(!i.has(p)){let w=await Ue(p,l);i.set(p,w)}let m=i.get(p),f=u==="css"?m.cssFile:m.componentFile;return f?(y.debug(`Discovered ${u} path: ${f} (was: ${a})`),f):(y.debug(`No ${u} file discovered, using provided: ${a}`),a||null)}let h=[];for(let c of r){let{generatedFix:u}=c,a=c.targetFilePath||u?.filePath,p=await d(c)||a;y.debug("Processing issue:",{id:c.id,type:c.type,targetFileType:c.targetFileType||"css",targetPath:p,providedPath:a!==p?a:"(same)",codeLength:u?.code?.length||0}),e.emit(Zt,{issueId:c.id});try{if(!u||!u.code||!p)throw new Error("Missing AI-generated fix data (code or filePath)");y.debug("Code to write (first 200 chars):",u.code.substring(0,200)),y.debug(`Code length: ${u.code.length} chars`);let g=await an(u.code,p);if(!g.valid)throw new Error(`Code validation failed: ${g.error}. Fix was not applied to prevent breaking the file.`);let m=K.isAbsolute(p)?p:K.join(l,p);y.debug(`Writing to absolute path: ${m}`),await Xe.writeFile(m,u.code,"utf-8"),await sn(on);let f={success:!0,issueId:c.id,filePath:p,timestamp:new Date};e.emit(Qt,{issueId:c.id,result:f}),y.debug(`\u2713 Applied ${c.targetFileType||"css"} fix to: ${p}`),h.push(f)}catch(g){let m=g.message||"Unknown error";e.emit(en,{issueId:c.id,error:m}),y.error(`\u2717 Error: ${m}`),h.push({success:!1,issueId:c.id,error:m,timestamp:new Date})}}let s={total:h.length,succeeded:h.filter(c=>c.success).length,failed:h.filter(c=>!c.success).length};e.emit(Ve,{results:h,summary:s}),y.debug(`Completed: ${s.succeeded}/${s.total} fixes applied`),s.succeeded>0&&e.emit(tn,{message:"Fixes applied. If Storybook crashes due to HMR, please restart it.",filesChanged:h.filter(c=>c.success).map(c=>c.filePath)})}catch(r){y.error("Fatal error during fix application:",r),e.emit(Ve,{results:[],summary:{total:t.issues?.length||0,succeeded:0,failed:t.issues?.length||0}})}},0)}),e}function Ke(e){let n=process.cwd();return e.plugins=e.plugins||[],e.plugins.push({name:"uicopilot-server-api",configureServer(t){t.middlewares.use("/__uicopilot/health",(l,i)=>{i.writeHead(200,{"Content-Type":"application/json"}),i.end(JSON.stringify({ok:!0,workspacePath:n}))}),t.middlewares.use("/__uicopilot/screenshot",async(l,i)=>{try{if(!await W()){i.writeHead(501,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Puppeteer not installed. Run: npm install puppeteer"}));return}let s=new URL(l.url||"",`http://${l.headers.host}`).searchParams.get("storyId");if(!s){i.writeHead(400,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Missing storyId parameter"}));return}let u=`http://${l.headers.host||"localhost:6006"}/iframe.html?viewMode=story&id=${s}&globals=`;y.debug(`Taking screenshot: ${s}`);let a=await te(u,{selector:"#storybook-root > *"});if(!a){i.writeHead(500,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Screenshot capture failed"}));return}let p=a.toString("base64");i.writeHead(200,{"Content-Type":"application/json"}),i.end(JSON.stringify({screenshot:`data:image/png;base64,${p}`}))}catch(d){y.error("Screenshot error:",d.message),i.writeHead(500,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:d.message}))}}),t.middlewares.use("/__uicopilot/capture",async(l,i)=>{try{if(!await W()){i.writeHead(501,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Puppeteer not installed"}));return}let h=new URL(l.url||"",`http://${l.headers.host}`),s=h.searchParams.get("storyId");if(!s){i.writeHead(400,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Missing storyId parameter"}));return}let c=h.searchParams.get("domOnly")==="1",u=l.headers.host||"localhost:6006",a=`http://${u}/iframe.html?viewMode=story&id=${s}&globals=`;y.debug(`Full capture${c?" (domOnly)":""}: ${s}`);let p=null;if(!c&&(p=await te(a,{selector:"#storybook-root > *"}),!p)){i.writeHead(500,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Screenshot capture failed"}));return}let g=await Te(),m=h.searchParams.get("warm")==="0",f=null,w="cold";if(!m){let b=`http://${u}`,x=await $e(g,b,s,S=>re(S,Be,s));x.ok?(f=x.value,w=x.booted?"warm-boot":"warm"):y.debug(`Warm capture unavailable (${x.reason}): ${s}`)}if(!f){let b=await g.newPage();try{await b.setCacheEnabled(!1),await b.setViewport({width:800,height:600}),await b.goto(a,{waitUntil:"load",timeout:15e3}),await b.evaluate(()=>document.fonts.ready),await b.waitForSelector("#storybook-root > *",{timeout:1e4}),await X(b),f=await re(b,Be,s)}finally{await b.close()}}y.debug(`Capture path for ${s}: ${w}`),i.writeHead(200,{"Content-Type":"application/json"}),i.end(JSON.stringify({screenshot:p?`data:image/png;base64,${p.toString("base64")}`:void 0,computedStyles:f.computedStyles,domTree:f.domTree}))}catch(d){y.error("Capture error:",d.message),i.writeHead(500,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:d.message}))}}),t.middlewares.use("/__uicopilot/screenshot-snapshot",async(l,i)=>{if(l.method!=="POST"){i.writeHead(405,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"POST required"}));return}try{if(!await W()){i.writeHead(501,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Puppeteer not installed"}));return}let h=[];for await(let w of l)h.push(typeof w=="string"?Buffer.from(w):w);let s=JSON.parse(Buffer.concat(h).toString()),{html:c,stylesheetUrls:u,storyId:a}=s;if(!c){i.writeHead(400,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Missing html in body"}));return}let g=`http://${l.headers.host||"localhost:6006"}`;y.debug(`Taking snapshot screenshot for ${a||"unknown"}`);let m=await Ie(c,u||[],g,{storyId:a});if(!m){i.writeHead(500,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Snapshot screenshot failed"}));return}let f=m.toString("base64");i.writeHead(200,{"Content-Type":"application/json"}),i.end(JSON.stringify({screenshot:`data:image/png;base64,${f}`}))}catch(d){y.error("Snapshot screenshot error:",d.message),i.writeHead(500,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:d.message}))}}),t.httpServer?.on("close",()=>{ce().catch(()=>{}).finally(()=>ne().catch(()=>{}))});let r=l=>{ce().catch(()=>{}).then(()=>ne()).catch(()=>{}).finally(()=>{process.kill(process.pid,l)})},o=globalThis;o.__uicopilotShutdownRegistered||(o.__uicopilotShutdownRegistered=!0,process.once("SIGINT",()=>r("SIGINT")),process.once("SIGTERM",()=>r("SIGTERM")))}}),e}var A={},cn=()=>{if(typeof A<"u"&&A.url){let e=(0,de.fileURLToPath)(A.url),n=(0,N.dirname)(e);return(0,N.join)(n,"manager.mjs")}return(0,N.join)(__dirname,"manager.mjs")},ln=()=>{if(typeof A<"u"&&A.url){let e=(0,de.fileURLToPath)(A.url),n=(0,N.dirname)(e);return(0,N.join)(n,"preview.mjs")}return(0,N.join)(__dirname,"preview.mjs")};function un(e=[]){return[...e,cn()]}function dn(e=[]){return[...e,ln()]}0&&(module.exports={experimental_serverChannel,managerEntries,previewAnnotations,viteFinal});
package/dist/preset.mjs CHANGED
@@ -1,3 +1,3 @@
1
- var Ae=Object.defineProperty;var De=(e,n)=>()=>(e&&(n=e(e=0)),n);var Be=(e,n)=>{for(var t in n)Ae(e,t,{get:n[t],enumerable:!0})};var Se={};Be(Se,{detectFileType:()=>he,formatValidationResult:()=>Tt,isValidCode:()=>vt,validateCode:()=>ye,validateCodeForFile:()=>we});function wt(e,n={}){let t=n.minLength??yt;return e.length<t?{code:"CODE_TOO_SHORT",message:`Code is too short (${e.length} chars). Minimum: ${t}. Likely incomplete or a snippet.`,severity:"error"}:null}function St(e){let n=[/^[+-]{3}\s+[ab]\//m,/^@@\s+-\d+,\d+\s+\+\d+,\d+\s+@@/m,/^diff --git/m,/^index [a-f0-9]+\.\.[a-f0-9]+/m];for(let t of n)if(t.test(e))return{code:"CODE_IS_DIFF",message:"Code appears to be a diff/patch format, not complete file content.",severity:"error"};return null}function bt(e){let n=e.split(`
2
- `).filter(s=>s.trim()),t=n.filter(s=>s.trim().startsWith("//")||s.trim().startsWith("/*")||s.trim().startsWith("*")||s.trim().startsWith("#"));if(n.length>0&&t.length/n.length>.8)return{code:"CODE_IS_INSTRUCTIONS",message:"Code appears to be mostly comments/instructions, not actual implementation.",severity:"error"};let r=[/^\/\/\s*(Change|Replace|Update|Modify|Add|Remove|Delete)\s+(from|to|this|the)/im,/^\/\/\s*To:/m,/^\/\/\s*From:/m];for(let s of r)if(s.test(e))return{code:"CODE_IS_INSTRUCTIONS",message:'Code contains instruction comments (e.g., "// Change from:" / "// To:") instead of actual code.',severity:"error"};return null}function xt(e){let n={"{":"}","[":"]","(":")"},t=[],r=!1,s="",a=!1;for(let o=0;o<e.length;o++){let c=e[o],f=e[o-1];if((c==='"'||c==="'"||c==="`")&&f!=="\\"){r?c===s&&(r=!1,a=!1):(r=!0,s=c,c==="`"&&(a=!0));continue}if(!r){if(n[c])t.push(n[c]);else if(Object.values(n).includes(c)&&t.pop()!==c)return{code:"UNBALANCED_BRACES",message:`Unbalanced braces/brackets detected. Found unexpected '${c}'.`,severity:"warning"}}}return t.length>0?{code:"UNBALANCED_BRACES",message:`Unbalanced braces/brackets. Missing: ${t.reverse().join("")}`,severity:"warning"}:null}function ge(e,n={}){let t=[],r=[];e.includes("import ")||t.push({code:"TSX_MISSING_IMPORTS",message:"Component file missing import statements. A complete file must have imports.",severity:"error"}),e.includes("export ")||t.push({code:"TSX_MISSING_EXPORTS",message:"Component file missing exports. A complete file must export something.",severity:"error"});let s=/import\s+(?:React|\{[^}]*\})\s+from\s+['"]react['"]/.test(e);/<[A-Z][a-zA-Z]*|<[a-z]+[\s/>]/.test(e)&&!s&&r.push({code:"TSX_NO_REACT_IMPORT",message:"JSX detected but no React import. OK for React 17+ with automatic runtime.",severity:"warning"}),/export\s+(default\s+)?function\s+\w+/.test(e)||/export\s+(const|let)\s+\w+\s*[:=]/.test(e)||/export\s+default\s+\w+/.test(e)||/export\s+\{[^}]+\}/.test(e)||r.push({code:"TSX_NO_COMPONENT_DEF",message:"No clear component definition found. Expected function or const export.",severity:"warning"});let c=[{pattern:/\.\.\.\s*$/,message:'Code ends with "..." - likely truncated'},{pattern:/\/\/\s*\.\.\./m,message:'Contains "// ..." - likely incomplete'},{pattern:/{\s*\/\*\s*\.\.\.\s*\*\/\s*}/m,message:'Contains "{/* ... */}" placeholder'}];for(let{pattern:f,message:l}of c)f.test(e)&&t.push({code:"TSX_INCOMPLETE",message:l,severity:"error"});return{errors:t,warnings:r}}function Ct(e,n={}){let t=[],r=[];(e.includes("import ")||e.includes("export "))&&t.push({code:"CSS_HAS_JS_CODE",message:"CSS file contains JavaScript import/export statements. Wrong file type.",severity:"error"}),/[.#\w\[\]]+\s*\{[\s\S]*?:\s*[^;]+;?[\s\S]*?\}/.test(e)||t.push({code:"CSS_INVALID_SYNTAX",message:"No valid CSS syntax found. Expected selector { property: value; } pattern.",severity:"error"});let a=(e.match(/\{[^}]+\}/g)||[]).length;return a===0&&t.push({code:"CSS_NO_RULES",message:"No CSS rules found. File appears empty or malformed.",severity:"error"}),(e.includes("/* ... */")||e.includes("// ..."))&&t.push({code:"CSS_INCOMPLETE",message:"CSS contains placeholder comments (/* ... */) - likely incomplete.",severity:"error"}),a>0&&a<3&&!n.allowPartial&&r.push({code:"CSS_FEW_RULES",message:`Only ${a} CSS rule(s) found. Might be incomplete.`,severity:"warning"}),{errors:t,warnings:r}}function Et(e,n={}){let t=[],r=[];return e.includes("import ")||t.push({code:"STORIES_MISSING_IMPORTS",message:"Stories file missing import statements.",severity:"error"}),/@storybook\//.test(e)||t.push({code:"STORIES_NO_STORYBOOK_IMPORT",message:"Stories file must import from @storybook/* (e.g., @storybook/react).",severity:"error"}),e.includes("Meta")||e.includes("ComponentMeta")||r.push({code:"STORIES_NO_META_TYPE",message:"Stories file should have Meta type import for type safety.",severity:"warning"}),e.includes("StoryObj")||e.includes("ComponentStory")||e.includes("Story")||r.push({code:"STORIES_NO_STORY_TYPE",message:"Stories file should have StoryObj/Story type for type safety.",severity:"warning"}),e.includes("export default")||t.push({code:"STORIES_NO_DEFAULT_EXPORT",message:"Stories file must have a default export (meta configuration).",severity:"error"}),/export\s+const\s+\w+\s*[:=]/.test(e)||t.push({code:"STORIES_NO_STORY_EXPORTS",message:"Stories file must have at least one named export (story definition).",severity:"error"}),/import\s+\{?\s*\w+\s*\}?\s+from\s+['"]\.\//.test(e)||r.push({code:"STORIES_NO_COMPONENT_IMPORT",message:"Stories file should import the component being documented.",severity:"warning"}),(e.includes("// ... other")||e.includes("/* ... */"))&&t.push({code:"STORIES_INCOMPLETE",message:"Stories file contains placeholder comments - likely incomplete.",severity:"error"}),{errors:t,warnings:r}}function he(e){let n=e.toLowerCase();if(n.includes(".stories."))return"stories";switch(n.split(".").pop()){case"tsx":return"tsx";case"jsx":return"jsx";case"ts":return"ts";case"js":return"js";case"css":return"css";case"scss":return"scss";case"less":return"less";default:return"unknown"}}function ye(e,n,t={}){let r={valid:!0,fileType:n,errors:[],warnings:[]},s=wt(e,t);s&&r.errors.push(s);let a=St(e);a&&r.errors.push(a);let o=bt(e);o&&r.errors.push(o);let c=xt(e);switch(c&&(t.strict?r.errors.push({...c,severity:"error"}):r.warnings.push(c)),n){case"stories":{let{errors:f,warnings:l}=Et(e,t);r.errors.push(...f),r.warnings.push(...l);break}case"tsx":case"jsx":{let{errors:f,warnings:l}=ge(e,t);r.errors.push(...f),r.warnings.push(...l);break}case"css":case"scss":case"less":{let{errors:f,warnings:l}=Ct(e,t);r.errors.push(...f),r.warnings.push(...l);break}case"ts":case"js":{let{errors:f,warnings:l}=ge(e,t);r.errors.push(...f),r.warnings.push(...l.filter(i=>!i.code.includes("JSX")));break}default:break}return r.valid=r.errors.length===0,r}function we(e,n,t={}){let r=he(n);return ye(e,r,t)}function vt(e,n,t={}){return we(e,n,t).valid}function Tt(e){if(e.valid&&e.warnings.length===0)return`\u2713 Valid ${e.fileType} code`;let n=[];if(e.valid)n.push(`\u26A0 Valid ${e.fileType} code with warnings`);else{n.push(`\u2717 Invalid ${e.fileType} code`),n.push(""),n.push("Errors:");for(let t of e.errors)n.push(` - [${t.code}] ${t.message}`)}if(e.warnings.length>0){n.push(""),n.push("Warnings:");for(let t of e.warnings)n.push(` - [${t.code}] ${t.message}`)}return n.join(`
3
- `)}var yt,be=De(()=>{"use strict";yt=50});import{dirname as Re,join as B}from"path";import{fileURLToPath as Le}from"url";import*as Oe from"fs/promises";import*as D from"path";import{glob as xe}from"glob";import{existsSync as ie}from"fs";import{createRequire as se}from"module";var V={NAME:"UI Parity",SHORT:"Parity",DOMAIN:"uiparity.com",MARKETING_URL:"https://uiparity.com",APP_URL:"https://app.uiparity.com",API_URL:"https://api.uiparity.com",SUPPORT_EMAIL:"feedback@uiparity.com",TAGLINE:"Pixel-perfect isn't a feeling. It's a score."};function He(){if(typeof process<"u"&&process.env)return process.env.UICOPILOT_DEBUG==="1";if(typeof globalThis<"u"&&"localStorage"in globalThis)try{return globalThis.localStorage.getItem("uicopilot_debug")==="1"}catch{return!1}return!1}var $=`[${V.NAME}]`,g={debug:(...e)=>{He()&&console.log($,...e)},info:(...e)=>{console.log($,...e)},warn:(...e)=>{console.warn($,...e)},error:(...e)=>{console.error($,...e)}};var tt=["flex","inline-flex"],nt=["grid","inline-grid"],gn=[...tt,...nt];function M(e){let r=e.ownerDocument?.defaultView;if(!r)return e.firstElementChild??e;let s=e.getBoundingClientRect(),a=l=>{let i=r.getComputedStyle(l);if(i.position==="fixed"||i.display==="none"||i.visibility==="hidden")return!0;let d=l.getBoundingClientRect();return d.width===0||d.height===0||l.children.length===0&&!(l.textContent??"").trim()},o=l=>{if(s.width===0||s.height===0)return!1;let i=l.getBoundingClientRect();return i.width>=s.width*.9&&i.height>=s.height*.9},c=e;for(let l=0;l<6;l+=1){let i=Array.from(c.children).filter(d=>!a(d));if(i.length!==1||c!==e&&!o(c))break;c=i[0]}if(c!==e&&o(c)){let l=Array.from(c.children).filter(i=>!a(i));if(l.length>1&&f(l))return l[0].setAttribute("data-uicopilot-instances",String(l.length)),l[0]}if(c===e)return e.firstElementChild??e;return c;function f(l){let i=u=>{let m=u.className,w=typeof m=="string"?m:"";return`${u.tagName}.${w.split(" ")[0]??""}`},d=i(l[0]);return l.every(u=>i(u)===d)}}var ce=M.toString(),R=null,_=null,ae=!1;async function U(){if(ae)return!!R;if(ae=!0,process.env.STORYBOOK_UICOPILOT_NO_PUPPETEER==="true")return g.debug("Puppeteer disabled via STORYBOOK_UICOPILOT_NO_PUPPETEER flag"),!1;let e=se(process.cwd()+"/");try{return R=e("puppeteer"),g.debug("Puppeteer loaded \u2014 server-side screenshots enabled"),!0}catch{}try{return R=e("puppeteer-core"),g.debug("puppeteer-core loaded from the project \u2014 capture enabled"),!0}catch{}try{return R=se(import.meta.url)("puppeteer-core"),g.debug("puppeteer-core loaded from the addon \u2014 capture enabled"),!0}catch{}return g.debug("No Puppeteer implementation available \u2014 server-side capture disabled"),!1}function it(){let e=process.env.STORYBOOK_UICOPILOT_CHROME_PATH;if(e){if(ie(e))return e;g.warn(`STORYBOOK_UICOPILOT_CHROME_PATH is set to "${e}" but no file exists there \u2014 falling back to discovery`)}let n=process.platform==="win32",t=process.env,r=n?[`${t.PROGRAMFILES??"C:\\Program Files"}\\Google\\Chrome\\Application\\chrome.exe`,`${t["PROGRAMFILES(X86)"]??"C:\\Program Files (x86)"}\\Google\\Chrome\\Application\\chrome.exe`,`${t.LOCALAPPDATA??""}\\Google\\Chrome\\Application\\chrome.exe`,`${t.PROGRAMFILES??"C:\\Program Files"}\\Microsoft\\Edge\\Application\\msedge.exe`].filter(s=>!s.startsWith("\\")):["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary","/Applications/Chromium.app/Contents/MacOS/Chromium","/usr/bin/google-chrome","/usr/bin/google-chrome-stable","/usr/bin/chromium-browser","/usr/bin/chromium","/snap/bin/chromium"];for(let s of r)if(ie(s))return s}async function le(){return z()}var N=class extends Error{constructor(){super("No Chrome or Chromium found. Install Google Chrome, or set STORYBOOK_UICOPILOT_CHROME_PATH to an executable. (Capture needs a real browser to render your stories.)"),this.name="BrowserNotFoundError"}},j=class extends Error{constructor(n,t){super(`Found a browser at "${n}" but could not drive it: ${t instanceof Error?t.message:String(t)}. This usually means the installed browser and puppeteer-core versions are incompatible.`),this.name="BrowserIncompatibleError"}};async function z(){if(_&&_.connected)return _;let e=it();if(!e&&!st())throw new N;let n={headless:!0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-dev-shm-usage"],...e?{executablePath:e}:{}};try{_=await R.launch(n)}catch(t){throw e?new j(e,t):new N}return g.debug("Headless Chrome launched for screenshots"),_}function st(){try{return typeof R?.executablePath=="function"}catch{return!1}}async function W(e,n){if(!await U())return null;let s=await(await z()).newPage();try{await s.setCacheEnabled(!1),await s.setViewport({width:n?.width||800,height:n?.height||600,deviceScaleFactor:1}),await s.goto(e,{waitUntil:"load",timeout:15e3}),await s.evaluate(()=>document.fonts.ready),await s.waitForSelector("#storybook-root > *",{timeout:1e4}),await s.waitForFunction(()=>new Promise(l=>{let i=document.querySelectorAll("style").length,d=0,u=()=>{let m=document.querySelectorAll("style").length;if(m===i){if(d++,d>=3){l(!0);return}}else d=0,i=m;setTimeout(u,100)};setTimeout(u,200)}),{timeout:5e3}).catch(()=>{}),await new Promise(l=>setTimeout(l,500));let a=await s.evaluate(l=>{let i=document.querySelector("#storybook-root");if(!i)return null;let d=window.innerHeight,u=window.innerWidth,m=v=>v.setAttribute("data-uic-drilled",""),w=()=>{let v=document.createElement("style");v.id="uic-drilled-bg-reset",v.textContent="[data-uic-drilled] { background: transparent !important; border-color: transparent !important; box-shadow: none !important; }",document.head.appendChild(v),document.body.offsetHeight};try{let T=new Function("return ("+l+")")()(i),y=T?.getBoundingClientRect(),E=!!y&&y.width>=u*.9&&y.height>=d*.9;if(T&&T!==i&&y&&y.width>0&&y.height>0&&!E){for(let P=T.parentElement;P&&P!==i;P=P.parentElement)m(P);return w(),{top:y.top,bottom:y.bottom,left:y.left,right:y.right}}}catch{}let p=1/0,h=0,S=1/0,C=0,b=!1;function x(v){for(let T of Array.from(v.children)){let y=window.getComputedStyle(T);if(y.display==="none"||y.visibility==="hidden"||y.position==="fixed"||y.position==="absolute")continue;let E=T.getBoundingClientRect();if(E.height<=0||E.width<=0)continue;if((E.width>=u*.9||E.height>=d*.9)&&T.children.length>0){T.setAttribute("data-uic-drilled",""),x(T);continue}if(T.children.length===1){let H=y.backgroundColor,$e=H==="rgba(0, 0, 0, 0)"||H==="transparent"||H==="",Me=y.borderStyle!=="none"&&y.borderWidth!=="0px",Ne=y.boxShadow!=="none",Fe=!$e||Me||Ne,ee=T.children[0].getBoundingClientRect(),ke=ee.width>=E.width*.95&&ee.height>=E.height*.95;if(!Fe||ke){T.setAttribute("data-uic-drilled",""),x(T);continue}}p=Math.min(p,E.top),h=Math.max(h,E.bottom),S=Math.min(S,E.left),C=Math.max(C,E.right),b=!0}}return x(i),b?(w(),{top:p,bottom:h,left:S,right:C}):null},ce);await s.evaluate(()=>new Promise(l=>requestAnimationFrame(()=>l())));let o=4,c=a?{x:Math.max(0,a.left-o),y:Math.max(0,a.top-o),width:Math.min(a.right-a.left+o*2,800),height:Math.min(a.bottom-a.top+o*2,600)}:void 0,f=await s.screenshot({type:"png",omitBackground:!0,...c?{clip:c}:{fullPage:!1}});return Buffer.from(f)}finally{await s.close()}}async function ue(e,n,t,r){if(!await U())return null;let o=await(await z()).newPage();try{await o.setCacheEnabled(!1),await o.setViewport({width:r?.width||800,height:r?.height||600,deviceScaleFactor:1});let c=r?.storyId||"",f=`${t}/iframe.html?viewMode=story&id=${c}&globals=`;await o.goto(f,{waitUntil:"load",timeout:15e3}),await o.waitForSelector("#storybook-root > *",{timeout:1e4}),await o.evaluate(d=>{let u=document.getElementById("storybook-root");u&&(u.innerHTML=d)},e),await o.evaluate(()=>document.fonts.ready),await new Promise(d=>setTimeout(d,500));let l=await o.evaluate(d=>{let u=document.querySelector("#storybook-root");if(!u)return null;let m=window.innerWidth,w=window.innerHeight,p=8;try{let x=new Function("return ("+d+")")()(u),v=x?.getBoundingClientRect(),T=!!v&&v.width>=m*.9&&v.height>=w*.9;if(x&&x!==u&&v&&v.width>0&&v.height>0&&!T)return{x:Math.max(0,v.x-p),y:Math.max(0,v.y-p),width:v.width+p*2,height:v.height+p*2}}catch{}function h(b){let x=b.getBoundingClientRect();if(x.width===0||x.height===0)return null;if(x.width<m*.8&&x.height>0)return x;for(let v of Array.from(b.children)){let T=window.getComputedStyle(v);if(T.position==="fixed"||T.position==="absolute"||T.display==="none"||T.visibility==="hidden")continue;let y=h(v);if(y)return y}return null}let S=h(u);if(S)return{x:Math.max(0,S.x-p),y:Math.max(0,S.y-p),width:S.width+p*2,height:S.height+p*2};let C=u.firstElementChild;if(C){let b=C.getBoundingClientRect();return{x:b.x,y:b.y,width:b.width,height:b.height}}return null},ce);if(!l)throw new Error("Could not determine component bounds from snapshot");let i=await o.screenshot({type:"png",clip:l});return Buffer.from(i)}finally{await o.close()}}async function F(){return U()}async function G(){_&&(await _.close(),_=null)}async function X(e,n){return await e.evaluate(r=>{let s=document.getElementById("storybook-root")||document.getElementById("root"),a=null;if(s)try{a=new Function("return ("+r+")")()(s)}catch{a=s.firstElementChild}let o={};if(a){let i=window.getComputedStyle(a);for(let d=0;d<i.length;d++)o[i[d]]=i.getPropertyValue(i[d])}let c={backgroundColor:["transparent","rgba(0, 0, 0, 0)"],border:["none","0px none","0px none rgb(0, 0, 0)"],borderRadius:["0px"],boxShadow:["none"],opacity:["1"]};function f(i){return i.replace(/-([a-z])/g,(d,u)=>u.toUpperCase())}function l(i,d){if(d>4)return null;let u=i.tagName.toLowerCase();if(["script","style","link","meta","br","hr","noscript"].includes(u))return null;let m=i.className,w=typeof m=="string"?m:m?.baseVal||"",p=i.id||void 0,h=i.getAttribute("role")||void 0,S;for(let y of Array.from(i.childNodes))if(y.nodeType===3){let E=y.textContent?.trim();if(E){S=E.length>50?E.substring(0,50)+"...":E;break}}let C=u;p?C=`${u}#${p}`:w&&(C=`${u}.${w.split(" ").filter(Boolean).join(".")}`);let b=window.getComputedStyle(i),x=["background-color","border","border-radius","box-shadow","opacity","fill","stroke","stroke-width","font-size","font-family","font-weight","line-height","letter-spacing","color","text-align","display","padding","margin","gap","flex-direction","justify-content","align-items","width","height"],v={};for(let y of x){let E=b.getPropertyValue(y),P=f(y);E&&!c[P]?.includes(E)&&(v[P]=E)}if(u==="svg"||i.closest("svg"))for(let y of["fill","stroke","stroke-width","viewBox","d","r","cx","cy"]){let E=i.getAttribute(y);E&&(v[f(y)]=E)}let T=[];for(let y of Array.from(i.children)){let E=window.getComputedStyle(y);if(E.display==="none"||E.visibility==="hidden")continue;let P=l(y,d+1);P&&T.push(P)}return{selector:C,tagName:u,className:w,id:p,role:h,textContent:S,styles:v,children:T}}return{computedStyles:o,domTree:a?l(a,0):null}},n)}async function k(e,n=5e3){await e.evaluate(t=>new Promise(r=>{let s=setTimeout(r,t);try{let a=window.__STORYBOOK_ADDONS_CHANNEL__;if(a){let o=()=>{clearTimeout(s),a.off("storyRendered",o),setTimeout(r,100)};a.on("storyRendered",o)}else clearTimeout(s),setTimeout(r,300)}catch{clearTimeout(s),r()}}),n)}async function de(e,n,t=15e3){return await e.evaluate((r,s)=>{let a=window,o=a.__STORYBOOK_PREVIEW__,c=a.__STORYBOOK_ADDONS_CHANNEL__;return!o||!c||typeof o.renderSelection!="function"||typeof o.selectionStore?.setSelection!="function"?Promise.resolve("no-preview"):new Promise(f=>{let l=!1,i=w=>{if(!l){l=!0,clearTimeout(m);try{c.off("storyRendered",d),c.off("storyErrored",u),c.off("storyMissing",u)}catch{}f(w)}},d=w=>{let p=typeof w=="string"?w:w?.storyId||w?.id;(!p||p===r)&&setTimeout(()=>i("ok"),100)},u=()=>i("errored"),m=setTimeout(()=>i("timeout"),s);c.on("storyRendered",d),c.on("storyErrored",u),c.on("storyMissing",u);try{o.selectionStore.setSelection({storyId:r,viewMode:"story"}),o.renderSelection()}catch{i("nav-failed")}})},n,t)}async function pe(e){try{return await e.evaluate(()=>window.__STORYBOOK_PREVIEW__?.selectionStore?.selection?.storyId||null)}catch{return null}}async function K(e){try{return await e.evaluate(()=>{let n=r=>r?r.getAttributeNames().sort().map(s=>{let a=r.getAttribute(s)??"";return s!=="class"?`${s}=${a}`:`class=${a.split(/\s+/).filter(c=>c&&!c.startsWith("sb-")).sort().join(" ")}`}).join("|"):"<missing>",t=document.getElementById("storybook-root")||document.getElementById("root");return[`html[${n(document.documentElement)}]`,`body[${n(document.body)}]`,`root[${n(t)}]`].join(" ")})}catch{return null}}var at=6,ct=15,lt=9e4,ut=2e4;function dt(){let e=Number(process.env.UICOPILOT_WARM_MAX_USES);return Number.isFinite(e)&&e>0?e:ct}function pt(){return process.env.UICOPILOT_WARM_CAPTURE!=="0"}var I=[],Y=[];function ft(e,n){return`${e}/iframe.html?viewMode=story&id=${n}&globals=`}function J(){let e=Y.shift();e&&e()}function fe(){let e=Date.now(),n=I.filter(t=>!t.busy&&t.page&&e-t.lastUsedAt>lt);if(n.length===0){I.length===0&&q();return}I=I.filter(t=>!n.includes(t));for(let t of n)t.page?.close().catch(()=>{});I.length===0&&q()}var L=null;function mt(){L||(L=setInterval(fe,3e4),L.unref?.())}function q(){L&&(clearInterval(L),L=null)}async function gt(e,n,t){let r=await e.newPage();try{return await r.setViewport({width:800,height:600,deviceScaleFactor:1}),await r.goto(ft(n,t),{waitUntil:"load",timeout:ut}),await r.evaluate(()=>document.fonts.ready),await r.waitForSelector("#storybook-root > *",{timeout:1e4}),await k(r),r}catch(s){throw await r.close().catch(()=>{}),s}}async function ht(e,n,t){for(;;){fe();let r=I.find(s=>s.baseUrl===n&&!s.busy&&s.page);if(r)return r.busy=!0,{entry:r,fresh:!1};if(I.length<at){let s={page:null,baseUrl:n,uses:0,lastUsedAt:Date.now(),busy:!0,baseline:null};I.push(s),mt();try{return s.page=await gt(e,n,t),s.baseline=await K(s.page),{entry:s,fresh:!0}}catch{return I=I.filter(a=>a!==s),J(),null}}await new Promise(s=>Y.push(s))}}function O(e,n){e.busy=!1,e.uses++,e.lastUsedAt=Date.now(),(n||e.uses>=dt())&&(I=I.filter(t=>t!==e),e.page?.close().catch(()=>{})),J()}async function me(e,n,t,r){if(!pt())return{ok:!1,reason:"disabled"};let s=await ht(e,n,t);if(!s)return{ok:!1,reason:"boot-failed"};let{entry:a,fresh:o}=s,c=a.page;try{if(!o){let l=await de(c,t);if(l!=="ok")return O(a,!0),{ok:!1,reason:`switch-${l}`};let i=await pe(c);if(i&&i!==t)return O(a,!0),{ok:!1,reason:"selection-mismatch"};if(a.baseline===null)return O(a,!0),{ok:!1,reason:"baseline-unavailable"};let d=await K(c);if(d===null)return O(a,!0),{ok:!1,reason:"document-unreadable"};if(d!==a.baseline)return O(a,!0),{ok:!1,reason:"document-drift"};await c.evaluate(()=>document.fonts.ready)}let f=await r(c);return O(a,!1),{ok:!0,value:f,booted:o}}catch(f){return O(a,!0),{ok:!1,reason:`error:${f.message}`}}}async function Z(){q();let e=I;for(I=[];Y.length;)J();await Promise.all(e.map(n=>n.page?.close().catch(()=>{})))}var Ce=M.toString(),Q=null,A=null,Ee=!1;async function It(){if(!Ee){Ee=!0;try{let e=await Promise.resolve().then(()=>(be(),Se));Q=e.validateCodeForFile,A=e.formatValidationResult,g.debug("Code validator loaded - fix validation enabled")}catch{g.debug("Code validator not available - skipping fix validation")}}}var Pt="UICOPILOT/APPLY_FIXES",_t="UICOPILOT/FIX_STARTED",Ot="UICOPILOT/FIX_COMPLETED",Rt="UICOPILOT/FIX_FAILED",ve="UICOPILOT/ALL_FIXES_APPLIED",Lt="UICOPILOT/RELOAD_REQUIRED",Te="UICOPILOT/WORKSPACE_PATH",$t="UICOPILOT/REQUEST_WORKSPACE_PATH",Mt="UICOPILOT/DISCOVER_COMPONENT_FILES",Ie="UICOPILOT/COMPONENT_FILES_DISCOVERED";async function Pe(e,n){let t=e.toLowerCase(),r=e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),s=[`src/**/fui-${t}/fui-${t}.css`,`src/**/fui-${t}/*.css`,`src/**/${t}/${t}.css`,`src/**/${r}/${r}.css`,`src/**/*${t}*.css`,`src/**/*${r}*.css`,`styles/**/*${t}*.css`],a=[`src/**/fui-${t}/fui-${t}.tsx`,`src/**/fui-${t}/*.tsx`,`src/**/${t}/${t}.tsx`,`src/**/${r}/${r}.tsx`,`src/**/*${r}*.tsx`,`src/**/*${r}*.jsx`],o=[],c=[];for(let p of s)try{let h=await xe(p,{cwd:n,nodir:!0,ignore:["**/node_modules/**","**/dist/**","**/.storybook/**"]});h.length>0&&o.push(...h)}catch{}for(let p of a)try{let h=await xe(p,{cwd:n,nodir:!0,ignore:["**/node_modules/**","**/dist/**","**/.storybook/**","**/*.stories.*","**/*.test.*"]});h.length>0&&c.push(...h)}catch{}let f=[...new Set(o)],l=[...new Set(c)],i=p=>{if(p.length===0)return;let h=p.find(b=>b.includes(`/fui-${t}/`)&&b.endsWith(".css"));if(h)return h;let S=p.find(b=>b.toLowerCase().includes(`/${t}/${t}.css`)||b.includes(`/${r}/${r}.css`));if(S)return S;let C=p.find(b=>b.toLowerCase().endsWith(`/${t}.css`)||b.endsWith(`/${r}.css`));return C||p[0]},d=p=>{if(p.length===0)return;let h=p.filter(x=>!x.includes(".stories.")&&!x.includes(".test."));if(h.length===0)return p[0];let S=h.find(x=>x.includes(`/fui-${t}/`)&&(x.endsWith(".tsx")||x.endsWith(".jsx")));if(S)return S;let C=h.find(x=>x.toLowerCase().includes(`/${t}/${t}.tsx`)||x.includes(`/${r}/${r}.tsx`));if(C)return C;let b=h.find(x=>x.toLowerCase().endsWith(`/${t}.tsx`)||x.endsWith(`/${r}.tsx`));return b||h[0]},u=i(f),m=d(l),w=[...f,...l];return g.debug(`Discovered files for "${e}":`,{cssFile:u,componentFile:m,totalMatches:w.length}),{cssFile:u,componentFile:m,allMatches:[...new Set(w)]}}var Nt=100;function Ft(e){return new Promise(n=>setTimeout(n,e))}async function kt(e,n){if(await It(),!Q||!A)return g.debug(`Skipping validation (validator not available) for ${n}`),{valid:!0};let t=Q(e,n);if(!t.valid){let r=t.errors.map(s=>s.message).join("; ");return g.warn(`Code validation failed for ${n}:`),console.warn(A(t)),{valid:!1,error:r}}return t.warnings.length>0&&(g.warn(`Code validation warnings for ${n}:`),console.warn(A(t))),g.debug(`Validation passed for ${n}`),{valid:!0}}var _e=!1;function At(e){if(_e)return e;_e=!0;let n=process.cwd();return g.debug("Apply fixes initialized"),g.debug("Workspace:",n),e.emit(Te,{path:n}),e.on($t,()=>{g.debug("Workspace path requested by browser"),g.debug("Emitting workspace path response:",n),e.emit(Te,{path:n})}),e.on(Mt,async t=>{let{componentName:r,storyId:s}=t;g.debug(`Discovering files for component: ${r}`);try{let a=await Pe(r,n);e.emit(Ie,{componentName:r,storyId:s,...a,workspacePath:n})}catch(a){g.error("File discovery error:",a),e.emit(Ie,{componentName:r,storyId:s,error:a.message,allMatches:[]})}}),e.on(Pt,t=>{setTimeout(async()=>{try{let{issues:r,storybookRoot:s}=t,a=s||n;s?g.debug(`Using storybookRoot from API: ${s}`):g.debug(`Using process.cwd(): ${n}`),g.debug(`Received APPLY_FIXES for ${r.length} issue(s)`);let o=new Map;async function c(i){let d=i.targetFileType||"css",u=i.targetFilePath||i.generatedFix?.filePath,m="",w=i.title?.match(/^(\w+)\s/);if(w&&(m=w[1]),!m&&u){let S=u.match(/\/(\w+)\.(?:css|tsx|jsx)$/i);S&&(m=S[1])}if(!m)return g.debug(`Could not extract component name, using provided path: ${u}`),u||null;if(!o.has(m)){let S=await Pe(m,a);o.set(m,S)}let p=o.get(m),h=d==="css"?p.cssFile:p.componentFile;return h?(g.debug(`Discovered ${d} path: ${h} (was: ${u})`),h):(g.debug(`No ${d} file discovered, using provided: ${u}`),u||null)}let f=[];for(let i of r){let{generatedFix:d}=i,u=i.targetFilePath||d?.filePath,m=await c(i)||u;g.debug("Processing issue:",{id:i.id,type:i.type,targetFileType:i.targetFileType||"css",targetPath:m,providedPath:u!==m?u:"(same)",codeLength:d?.code?.length||0}),e.emit(_t,{issueId:i.id});try{if(!d||!d.code||!m)throw new Error("Missing AI-generated fix data (code or filePath)");g.debug("Code to write (first 200 chars):",d.code.substring(0,200)),g.debug(`Code length: ${d.code.length} chars`);let w=await kt(d.code,m);if(!w.valid)throw new Error(`Code validation failed: ${w.error}. Fix was not applied to prevent breaking the file.`);let p=D.isAbsolute(m)?m:D.join(a,m);g.debug(`Writing to absolute path: ${p}`),await Oe.writeFile(p,d.code,"utf-8"),await Ft(Nt);let h={success:!0,issueId:i.id,filePath:m,timestamp:new Date};e.emit(Ot,{issueId:i.id,result:h}),g.debug(`\u2713 Applied ${i.targetFileType||"css"} fix to: ${m}`),f.push(h)}catch(w){let p=w.message||"Unknown error";e.emit(Rt,{issueId:i.id,error:p}),g.error(`\u2717 Error: ${p}`),f.push({success:!1,issueId:i.id,error:p,timestamp:new Date})}}let l={total:f.length,succeeded:f.filter(i=>i.success).length,failed:f.filter(i=>!i.success).length};e.emit(ve,{results:f,summary:l}),g.debug(`Completed: ${l.succeeded}/${l.total} fixes applied`),l.succeeded>0&&e.emit(Lt,{message:"Fixes applied. If Storybook crashes due to HMR, please restart it.",filesChanged:f.filter(i=>i.success).map(i=>i.filePath)})}catch(r){g.error("Fatal error during fix application:",r),e.emit(ve,{results:[],summary:{total:t.issues?.length||0,succeeded:0,failed:t.issues?.length||0}})}},0)}),e}function Dt(e){let n=process.cwd();return e.plugins=e.plugins||[],e.plugins.push({name:"uicopilot-server-api",configureServer(t){t.middlewares.use("/__uicopilot/health",(a,o)=>{o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({ok:!0,workspacePath:n}))}),t.middlewares.use("/__uicopilot/screenshot",async(a,o)=>{try{if(!await F()){o.writeHead(501,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Puppeteer not installed. Run: npm install puppeteer"}));return}let l=new URL(a.url||"",`http://${a.headers.host}`).searchParams.get("storyId");if(!l){o.writeHead(400,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Missing storyId parameter"}));return}let d=`http://${a.headers.host||"localhost:6006"}/iframe.html?viewMode=story&id=${l}&globals=`;g.debug(`Taking screenshot: ${l}`);let u=await W(d,{selector:"#storybook-root > *"});if(!u){o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Screenshot capture failed"}));return}let m=u.toString("base64");o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({screenshot:`data:image/png;base64,${m}`}))}catch(c){g.error("Screenshot error:",c.message),o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:c.message}))}}),t.middlewares.use("/__uicopilot/capture",async(a,o)=>{try{if(!await F()){o.writeHead(501,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Puppeteer not installed"}));return}let f=new URL(a.url||"",`http://${a.headers.host}`),l=f.searchParams.get("storyId");if(!l){o.writeHead(400,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Missing storyId parameter"}));return}let i=f.searchParams.get("domOnly")==="1",d=a.headers.host||"localhost:6006",u=`http://${d}/iframe.html?viewMode=story&id=${l}&globals=`;g.debug(`Full capture${i?" (domOnly)":""}: ${l}`);let m=null;if(!i&&(m=await W(u,{selector:"#storybook-root > *"}),!m)){o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Screenshot capture failed"}));return}let w=await le(),p=f.searchParams.get("warm")==="0",h=null,S="cold";if(!p){let C=`http://${d}`,b=await me(w,C,l,x=>X(x,Ce));b.ok?(h=b.value,S=b.booted?"warm-boot":"warm"):g.debug(`Warm capture unavailable (${b.reason}): ${l}`)}if(!h){let C=await w.newPage();try{await C.setCacheEnabled(!1),await C.setViewport({width:800,height:600}),await C.goto(u,{waitUntil:"load",timeout:15e3}),await C.evaluate(()=>document.fonts.ready),await C.waitForSelector("#storybook-root > *",{timeout:1e4}),await k(C),h=await X(C,Ce)}finally{await C.close()}}g.debug(`Capture path for ${l}: ${S}`),o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({screenshot:m?`data:image/png;base64,${m.toString("base64")}`:void 0,computedStyles:h.computedStyles,domTree:h.domTree}))}catch(c){g.error("Capture error:",c.message),o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:c.message}))}}),t.middlewares.use("/__uicopilot/screenshot-snapshot",async(a,o)=>{if(a.method!=="POST"){o.writeHead(405,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"POST required"}));return}try{if(!await F()){o.writeHead(501,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Puppeteer not installed"}));return}let f=[];for await(let S of a)f.push(typeof S=="string"?Buffer.from(S):S);let l=JSON.parse(Buffer.concat(f).toString()),{html:i,stylesheetUrls:d,storyId:u}=l;if(!i){o.writeHead(400,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Missing html in body"}));return}let w=`http://${a.headers.host||"localhost:6006"}`;g.debug(`Taking snapshot screenshot for ${u||"unknown"}`);let p=await ue(i,d||[],w,{storyId:u});if(!p){o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Snapshot screenshot failed"}));return}let h=p.toString("base64");o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({screenshot:`data:image/png;base64,${h}`}))}catch(c){g.error("Snapshot screenshot error:",c.message),o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:c.message}))}}),t.httpServer?.on("close",()=>{Z().catch(()=>{}).finally(()=>G().catch(()=>{}))});let r=a=>{Z().catch(()=>{}).then(()=>G()).catch(()=>{}).finally(()=>{process.kill(process.pid,a)})},s=globalThis;s.__uicopilotShutdownRegistered||(s.__uicopilotShutdownRegistered=!0,process.once("SIGINT",()=>r("SIGINT")),process.once("SIGTERM",()=>r("SIGTERM")))}}),e}var Bt=()=>{if(typeof import.meta<"u"&&import.meta.url){let e=Le(import.meta.url),n=Re(e);return B(n,"manager.mjs")}return B(__dirname,"manager.mjs")},Ht=()=>{if(typeof import.meta<"u"&&import.meta.url){let e=Le(import.meta.url),n=Re(e);return B(n,"preview.mjs")}return B(__dirname,"preview.mjs")};function ho(e=[]){return[...e,Bt()]}function yo(e=[]){return[...e,Ht()]}export{At as experimental_serverChannel,ho as managerEntries,yo as previewAnnotations,Dt as viteFinal};
1
+ var Ue=Object.defineProperty;var We=(e,n)=>()=>(e&&(n=e(e=0)),n);var Xe=(e,n)=>{for(var t in n)Ue(e,t,{get:n[t],enumerable:!0})};var Me={};Xe(Me,{detectFileType:()=>_e,formatValidationResult:()=>Dt,isValidCode:()=>At,validateCode:()=>Pe,validateCodeForFile:()=>Oe});function Rt(e,n={}){let t=n.minLength??Mt;return e.length<t?{code:"CODE_TOO_SHORT",message:`Code is too short (${e.length} chars). Minimum: ${t}. Likely incomplete or a snippet.`,severity:"error"}:null}function $t(e){let n=[/^[+-]{3}\s+[ab]\//m,/^@@\s+-\d+,\d+\s+\+\d+,\d+\s+@@/m,/^diff --git/m,/^index [a-f0-9]+\.\.[a-f0-9]+/m];for(let t of n)if(t.test(e))return{code:"CODE_IS_DIFF",message:"Code appears to be a diff/patch format, not complete file content.",severity:"error"};return null}function Nt(e){let n=e.split(`
2
+ `).filter(i=>i.trim()),t=n.filter(i=>i.trim().startsWith("//")||i.trim().startsWith("/*")||i.trim().startsWith("*")||i.trim().startsWith("#"));if(n.length>0&&t.length/n.length>.8)return{code:"CODE_IS_INSTRUCTIONS",message:"Code appears to be mostly comments/instructions, not actual implementation.",severity:"error"};let r=[/^\/\/\s*(Change|Replace|Update|Modify|Add|Remove|Delete)\s+(from|to|this|the)/im,/^\/\/\s*To:/m,/^\/\/\s*From:/m];for(let i of r)if(i.test(e))return{code:"CODE_IS_INSTRUCTIONS",message:'Code contains instruction comments (e.g., "// Change from:" / "// To:") instead of actual code.',severity:"error"};return null}function kt(e){let n={"{":"}","[":"]","(":")"},t=[],r=!1,i="",l=!1;for(let o=0;o<e.length;o++){let d=e[o],h=e[o-1];if((d==='"'||d==="'"||d==="`")&&h!=="\\"){r?d===i&&(r=!1,l=!1):(r=!0,i=d,d==="`"&&(l=!0));continue}if(!r){if(n[d])t.push(n[d]);else if(Object.values(n).includes(d)&&t.pop()!==d)return{code:"UNBALANCED_BRACES",message:`Unbalanced braces/brackets detected. Found unexpected '${d}'.`,severity:"warning"}}}return t.length>0?{code:"UNBALANCED_BRACES",message:`Unbalanced braces/brackets. Missing: ${t.reverse().join("")}`,severity:"warning"}:null}function ve(e,n={}){let t=[],r=[];e.includes("import ")||t.push({code:"TSX_MISSING_IMPORTS",message:"Component file missing import statements. A complete file must have imports.",severity:"error"}),e.includes("export ")||t.push({code:"TSX_MISSING_EXPORTS",message:"Component file missing exports. A complete file must export something.",severity:"error"});let i=/import\s+(?:React|\{[^}]*\})\s+from\s+['"]react['"]/.test(e);/<[A-Z][a-zA-Z]*|<[a-z]+[\s/>]/.test(e)&&!i&&r.push({code:"TSX_NO_REACT_IMPORT",message:"JSX detected but no React import. OK for React 17+ with automatic runtime.",severity:"warning"}),/export\s+(default\s+)?function\s+\w+/.test(e)||/export\s+(const|let)\s+\w+\s*[:=]/.test(e)||/export\s+default\s+\w+/.test(e)||/export\s+\{[^}]+\}/.test(e)||r.push({code:"TSX_NO_COMPONENT_DEF",message:"No clear component definition found. Expected function or const export.",severity:"warning"});let d=[{pattern:/\.\.\.\s*$/,message:'Code ends with "..." - likely truncated'},{pattern:/\/\/\s*\.\.\./m,message:'Contains "// ..." - likely incomplete'},{pattern:/{\s*\/\*\s*\.\.\.\s*\*\/\s*}/m,message:'Contains "{/* ... */}" placeholder'}];for(let{pattern:h,message:s}of d)h.test(e)&&t.push({code:"TSX_INCOMPLETE",message:s,severity:"error"});return{errors:t,warnings:r}}function Ft(e,n={}){let t=[],r=[];(e.includes("import ")||e.includes("export "))&&t.push({code:"CSS_HAS_JS_CODE",message:"CSS file contains JavaScript import/export statements. Wrong file type.",severity:"error"}),/[.#\w\[\]]+\s*\{[\s\S]*?:\s*[^;]+;?[\s\S]*?\}/.test(e)||t.push({code:"CSS_INVALID_SYNTAX",message:"No valid CSS syntax found. Expected selector { property: value; } pattern.",severity:"error"});let l=(e.match(/\{[^}]+\}/g)||[]).length;return l===0&&t.push({code:"CSS_NO_RULES",message:"No CSS rules found. File appears empty or malformed.",severity:"error"}),(e.includes("/* ... */")||e.includes("// ..."))&&t.push({code:"CSS_INCOMPLETE",message:"CSS contains placeholder comments (/* ... */) - likely incomplete.",severity:"error"}),l>0&&l<3&&!n.allowPartial&&r.push({code:"CSS_FEW_RULES",message:`Only ${l} CSS rule(s) found. Might be incomplete.`,severity:"warning"}),{errors:t,warnings:r}}function Lt(e,n={}){let t=[],r=[];return e.includes("import ")||t.push({code:"STORIES_MISSING_IMPORTS",message:"Stories file missing import statements.",severity:"error"}),/@storybook\//.test(e)||t.push({code:"STORIES_NO_STORYBOOK_IMPORT",message:"Stories file must import from @storybook/* (e.g., @storybook/react).",severity:"error"}),e.includes("Meta")||e.includes("ComponentMeta")||r.push({code:"STORIES_NO_META_TYPE",message:"Stories file should have Meta type import for type safety.",severity:"warning"}),e.includes("StoryObj")||e.includes("ComponentStory")||e.includes("Story")||r.push({code:"STORIES_NO_STORY_TYPE",message:"Stories file should have StoryObj/Story type for type safety.",severity:"warning"}),e.includes("export default")||t.push({code:"STORIES_NO_DEFAULT_EXPORT",message:"Stories file must have a default export (meta configuration).",severity:"error"}),/export\s+const\s+\w+\s*[:=]/.test(e)||t.push({code:"STORIES_NO_STORY_EXPORTS",message:"Stories file must have at least one named export (story definition).",severity:"error"}),/import\s+\{?\s*\w+\s*\}?\s+from\s+['"]\.\//.test(e)||r.push({code:"STORIES_NO_COMPONENT_IMPORT",message:"Stories file should import the component being documented.",severity:"warning"}),(e.includes("// ... other")||e.includes("/* ... */"))&&t.push({code:"STORIES_INCOMPLETE",message:"Stories file contains placeholder comments - likely incomplete.",severity:"error"}),{errors:t,warnings:r}}function _e(e){let n=e.toLowerCase();if(n.includes(".stories."))return"stories";switch(n.split(".").pop()){case"tsx":return"tsx";case"jsx":return"jsx";case"ts":return"ts";case"js":return"js";case"css":return"css";case"scss":return"scss";case"less":return"less";default:return"unknown"}}function Pe(e,n,t={}){let r={valid:!0,fileType:n,errors:[],warnings:[]},i=Rt(e,t);i&&r.errors.push(i);let l=$t(e);l&&r.errors.push(l);let o=Nt(e);o&&r.errors.push(o);let d=kt(e);switch(d&&(t.strict?r.errors.push({...d,severity:"error"}):r.warnings.push(d)),n){case"stories":{let{errors:h,warnings:s}=Lt(e,t);r.errors.push(...h),r.warnings.push(...s);break}case"tsx":case"jsx":{let{errors:h,warnings:s}=ve(e,t);r.errors.push(...h),r.warnings.push(...s);break}case"css":case"scss":case"less":{let{errors:h,warnings:s}=Ft(e,t);r.errors.push(...h),r.warnings.push(...s);break}case"ts":case"js":{let{errors:h,warnings:s}=ve(e,t);r.errors.push(...h),r.warnings.push(...s.filter(c=>!c.code.includes("JSX")));break}default:break}return r.valid=r.errors.length===0,r}function Oe(e,n,t={}){let r=_e(n);return Pe(e,r,t)}function At(e,n,t={}){return Oe(e,n,t).valid}function Dt(e){if(e.valid&&e.warnings.length===0)return`\u2713 Valid ${e.fileType} code`;let n=[];if(e.valid)n.push(`\u26A0 Valid ${e.fileType} code with warnings`);else{n.push(`\u2717 Invalid ${e.fileType} code`),n.push(""),n.push("Errors:");for(let t of e.errors)n.push(` - [${t.code}] ${t.message}`)}if(e.warnings.length>0){n.push(""),n.push("Warnings:");for(let t of e.warnings)n.push(` - [${t.code}] ${t.message}`)}return n.join(`
3
+ `)}var Mt,Re=We(()=>{"use strict";Mt=50});import{dirname as Ve,join as X}from"path";import{fileURLToPath as je}from"url";import*as He from"fs/promises";import*as W from"path";import{glob as $e}from"glob";import{existsSync as pe}from"fs";import{createRequire as me}from"module";var G={NAME:"UI Parity",SHORT:"Parity",DOMAIN:"uiparity.com",MARKETING_URL:"https://uiparity.com",APP_URL:"https://app.uiparity.com",API_URL:"https://api.uiparity.com",SUPPORT_EMAIL:"feedback@uiparity.com",TAGLINE:"Pixel-perfect isn't a feeling. It's a score."};function Ge(){if(typeof process<"u"&&process.env)return process.env.UICOPILOT_DEBUG==="1";if(typeof globalThis<"u"&&"localStorage"in globalThis)try{return globalThis.localStorage.getItem("uicopilot_debug")==="1"}catch{return!1}return!1}var B=`[${G.NAME}]`,y={debug:(...e)=>{Ge()&&console.log(B,...e)},info:(...e)=>{console.log(B,...e)},warn:(...e)=>{console.warn(B,...e)},error:(...e)=>{console.error(B,...e)}};var ct=["flex","inline-flex"],lt=["grid","inline-grid"],_n=[...ct,...lt];function H(e){let r=e.ownerDocument?.defaultView;if(!r)return e.firstElementChild??e;let i=e.getBoundingClientRect(),l=u=>{let a=r.getComputedStyle(u);if(a.position==="fixed"||a.display==="none"||a.visibility==="hidden")return!0;let p=u.getBoundingClientRect();return p.width===0||p.height===0||u.children.length===0&&!(u.textContent??"").trim()},o=u=>{if(i.width===0||i.height===0)return!1;let a=u.getBoundingClientRect();return a.width>=i.width*.9&&a.height>=i.height*.9},d=[],h=u=>{for(let a of Array.from(u.children))a.hasAttribute("data-uicopilot-instance")?d.push(a):h(a)};if(h(e),d.length>1){let u=g=>{let m=[];for(let f=g;f&&f!==e;f=f.parentElement)m.unshift(f);return m},a=d.map(u),p=e;for(let g=0;;g+=1){let m=a[0][g];if(!m||!a.every(f=>f[g]===m))break;p=m}if(p!==e)return p}let s=e;for(let u=0;u<6;u+=1){if(s!==e&&s.hasAttribute("data-uicopilot-instance"))return s;let a=Array.from(s.children).filter(p=>!l(p));if(a.length!==1||s!==e&&!o(s))break;s=a[0]}if(s!==e&&o(s)){let u=Array.from(s.children).filter(a=>!l(a));if(u.length>1&&c(u))return u[0].setAttribute("data-uicopilot-instances",String(u.length)),u[0]}if(s===e)return e.firstElementChild??e;return s;function c(u){let a=g=>{let m=g.className,f=typeof m=="string"?m:"";return`${g.tagName}.${f.split(" ")[0]??""}`},p=a(u[0]);return u.every(g=>a(g)===p)}}var ge=H.toString(),k=null,$=null,he=!1;async function q(){if(he)return!!k;if(he=!0,process.env.STORYBOOK_UICOPILOT_NO_PUPPETEER==="true")return y.debug("Puppeteer disabled via STORYBOOK_UICOPILOT_NO_PUPPETEER flag"),!1;let e=me(process.cwd()+"/");try{return k=e("puppeteer"),y.debug("Puppeteer loaded \u2014 server-side screenshots enabled"),!0}catch{}try{return k=e("puppeteer-core"),y.debug("puppeteer-core loaded from the project \u2014 capture enabled"),!0}catch{}try{return k=me(import.meta.url)("puppeteer-core"),y.debug("puppeteer-core loaded from the addon \u2014 capture enabled"),!0}catch{}return y.debug("No Puppeteer implementation available \u2014 server-side capture disabled"),!1}function mt(){let e=process.env.STORYBOOK_UICOPILOT_CHROME_PATH;if(e){if(pe(e))return e;y.warn(`STORYBOOK_UICOPILOT_CHROME_PATH is set to "${e}" but no file exists there \u2014 falling back to discovery`)}let n=process.platform==="win32",t=process.env,r=n?[`${t.PROGRAMFILES??"C:\\Program Files"}\\Google\\Chrome\\Application\\chrome.exe`,`${t["PROGRAMFILES(X86)"]??"C:\\Program Files (x86)"}\\Google\\Chrome\\Application\\chrome.exe`,`${t.LOCALAPPDATA??""}\\Google\\Chrome\\Application\\chrome.exe`,`${t.PROGRAMFILES??"C:\\Program Files"}\\Microsoft\\Edge\\Application\\msedge.exe`].filter(i=>!i.startsWith("\\")):["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary","/Applications/Chromium.app/Contents/MacOS/Chromium","/usr/bin/google-chrome","/usr/bin/google-chrome-stable","/usr/bin/chromium-browser","/usr/bin/chromium","/snap/bin/chromium"];for(let i of r)if(pe(i))return i}async function ye(){return Y()}var V=class extends Error{constructor(){super("No Chrome or Chromium found. Install Google Chrome, or set STORYBOOK_UICOPILOT_CHROME_PATH to an executable. (Capture needs a real browser to render your stories.)"),this.name="BrowserNotFoundError"}},K=class extends Error{constructor(n,t){super(`Found a browser at "${n}" but could not drive it: ${t instanceof Error?t.message:String(t)}. This usually means the installed browser and puppeteer-core versions are incompatible.`),this.name="BrowserIncompatibleError"}};async function Y(){if($&&$.connected)return $;let e=mt();if(!e&&!ht())throw new V;let n={headless:!0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-dev-shm-usage"],...e?{executablePath:e}:{}};try{$=await k.launch(n)}catch(t){throw e?new K(e,t):new V}return y.debug("Headless Chrome launched for screenshots"),$}function ht(){try{return typeof k?.executablePath=="function"}catch{return!1}}async function J(e,n){if(!await q())return null;let i=await(await Y()).newPage();try{await i.setCacheEnabled(!1),await i.setViewport({width:n?.width||800,height:n?.height||600,deviceScaleFactor:1}),await i.goto(e,{waitUntil:"load",timeout:15e3}),await i.evaluate(()=>document.fonts.ready),await i.waitForSelector("#storybook-root > *",{timeout:1e4}),await i.waitForFunction(()=>new Promise(s=>{let c=document.querySelectorAll("style").length,u=0,a=()=>{let p=document.querySelectorAll("style").length;if(p===c){if(u++,u>=3){s(!0);return}}else u=0,c=p;setTimeout(a,100)};setTimeout(a,200)}),{timeout:5e3}).catch(()=>{}),await new Promise(s=>setTimeout(s,500));let l=await i.evaluate(s=>{let c=document.querySelector("#storybook-root");if(!c)return null;let u=window.innerHeight,a=window.innerWidth,p=E=>E.setAttribute("data-uic-drilled",""),g=()=>{let E=document.createElement("style");E.id="uic-drilled-bg-reset",E.textContent="[data-uic-drilled] { background: transparent !important; border-color: transparent !important; box-shadow: none !important; }",document.head.appendChild(E),document.body.offsetHeight};try{let T=new Function("return ("+s+")")()(c),C=T?.getBoundingClientRect(),_=!!C&&C.width>=a*.9&&C.height>=u*.9;if(T&&T!==c&&C&&C.width>0&&C.height>0&&!_){for(let P=T.parentElement;P&&P!==c;P=P.parentElement)p(P);return g(),{top:C.top,bottom:C.bottom,left:C.left,right:C.right}}}catch{}let m=1/0,f=0,w=1/0,b=0,x=!1;function S(E){for(let T of Array.from(E.children)){let C=window.getComputedStyle(T);if(C.display==="none"||C.visibility==="hidden"||C.position==="fixed"||C.position==="absolute")continue;let _=T.getBoundingClientRect();if(_.height<=0||_.width<=0)continue;if((_.width>=a*.9||_.height>=u*.9)&&T.children.length>0){T.setAttribute("data-uic-drilled",""),S(T);continue}if(T.children.length===1){let L=C.backgroundColor,R=L==="rgba(0, 0, 0, 0)"||L==="transparent"||L==="",D=C.borderStyle!=="none"&&C.borderWidth!=="0px",v=C.boxShadow!=="none",I=!R||D||v,A=T.children[0].getBoundingClientRect(),ze=A.width>=_.width*.95&&A.height>=_.height*.95;if(!I||ze){T.setAttribute("data-uic-drilled",""),S(T);continue}}m=Math.min(m,_.top),f=Math.max(f,_.bottom),w=Math.min(w,_.left),b=Math.max(b,_.right),x=!0}}return S(c),x?(g(),{top:m,bottom:f,left:w,right:b}):null},ge);await i.evaluate(()=>new Promise(s=>requestAnimationFrame(()=>s())));let o=4,d=l?{x:Math.max(0,l.left-o),y:Math.max(0,l.top-o),width:Math.min(l.right-l.left+o*2,800),height:Math.min(l.bottom-l.top+o*2,600)}:void 0,h=await i.screenshot({type:"png",omitBackground:!0,...d?{clip:d}:{fullPage:!1}});return Buffer.from(h)}finally{await i.close()}}async function we(e,n,t,r){if(!await q())return null;let o=await(await Y()).newPage();try{await o.setCacheEnabled(!1),await o.setViewport({width:r?.width||800,height:r?.height||600,deviceScaleFactor:1});let d=r?.storyId||"",h=`${t}/iframe.html?viewMode=story&id=${d}&globals=`;await o.goto(h,{waitUntil:"load",timeout:15e3}),await o.waitForSelector("#storybook-root > *",{timeout:1e4}),await o.evaluate(u=>{let a=document.getElementById("storybook-root");a&&(a.innerHTML=u)},e),await o.evaluate(()=>document.fonts.ready),await new Promise(u=>setTimeout(u,500));let s=await o.evaluate(u=>{let a=document.querySelector("#storybook-root");if(!a)return null;let p=window.innerWidth,g=window.innerHeight,m=8;try{let S=new Function("return ("+u+")")()(a),E=S?.getBoundingClientRect(),T=!!E&&E.width>=p*.9&&E.height>=g*.9;if(S&&S!==a&&E&&E.width>0&&E.height>0&&!T)return{x:Math.max(0,E.x-m),y:Math.max(0,E.y-m),width:E.width+m*2,height:E.height+m*2}}catch{}function f(x){let S=x.getBoundingClientRect();if(S.width===0||S.height===0)return null;if(S.width<p*.8&&S.height>0)return S;for(let E of Array.from(x.children)){let T=window.getComputedStyle(E);if(T.position==="fixed"||T.position==="absolute"||T.display==="none"||T.visibility==="hidden")continue;let C=f(E);if(C)return C}return null}let w=f(a);if(w)return{x:Math.max(0,w.x-m),y:Math.max(0,w.y-m),width:w.width+m*2,height:w.height+m*2};let b=a.firstElementChild;if(b){let x=b.getBoundingClientRect();return{x:x.x,y:x.y,width:x.width,height:x.height}}return null},ge);if(!s)throw new Error("Could not determine component bounds from snapshot");let c=await o.screenshot({type:"png",clip:s});return Buffer.from(c)}finally{await o.close()}}async function j(){return q()}async function Z(){$&&(await $.close(),$=null)}function be(e,n){let t=e.getBoundingClientRect(),r=n.getBoundingClientRect();return{x:Math.round(t.left-r.left),y:Math.round(t.top-r.top),w:Math.round(t.width),h:Math.round(t.height)}}function xe(e,n){let t=s=>{let c=Object.keys(s).find(u=>u.startsWith("__reactFiber$"));return c?s[c]:void 0},r=s=>!!s&&s.nodeType===1&&typeof s.getBoundingClientRect=="function",i=s=>s.elementType===e||s.type===e,l=s=>{for(let c=s?.child??null;c;c=c.sibling){if(c.tag===5&&r(c.stateNode)){let a=c.stateNode.getBoundingClientRect();if(a.width>0&&a.height>0)return c.stateNode}let u=l(c);if(u)return u}},o=s=>{for(let c=s.return;c;c=c.return)if(i(c))return!0;return!1},d=new Set,h=[];for(let s of n)for(let c of[s,...Array.from(s.querySelectorAll("*"))])for(let u=t(c)??null;u;u=u.return){if(!i(u)||d.has(u)||(d.add(u),o(u)))continue;let a=l(u);a&&h.push(a)}return h}async function Se(e,n,t,r){let i=e.document;i.querySelectorAll("[data-uicopilot-instance]").forEach(a=>a.removeAttribute("data-uicopilot-instance")),i.querySelectorAll("[data-uicopilot-instance-count]").forEach(a=>a.removeAttribute("data-uicopilot-instance-count"));let l=e.__STORYBOOK_PREVIEW__;if(!l?.storyStoreValue)return 0;let o;try{o=await l.storyStoreValue.loadStory({storyId:n})}catch{return 0}let d=r??i.getElementById("storybook-root")??i.getElementById("root");if(!d||!o.component)return 0;let h=r?[]:Array.from(i.body.children).filter(a=>a!==d&&!a.contains(d)&&a.tagName!=="SCRIPT"),s=[d,...h],c=t(o.component,s);if(c.length===0&&o.subcomponents){let a=Object.values(o.subcomponents).flatMap(p=>p?t(p,s):[]);c=Array.from(new Set(a)).filter(p=>!a.some(g=>g!==p&&g.contains(p))).sort((p,g)=>p.compareDocumentPosition(g)&4?-1:1)}return c.forEach((a,p)=>a.setAttribute("data-uicopilot-instance",String(p+1))),[d,...h].some(a=>[a,...Array.from(a.querySelectorAll("*"))].some(p=>Object.keys(p).some(g=>g.startsWith("__reactFiber$"))))&&d.setAttribute("data-uicopilot-instance-count",String(c.length)),c.length}var gt=be.toString(),yt=xe.toString(),wt=Se.toString(),bt="data-uicopilot-instance";async function Q(e,n,t){return t&&await e.evaluate(async(i,l,o)=>{let d=new Function("return ("+i+")")(),h=new Function("return ("+l+")")();return d(window,o,h)},wt,yt,t),await e.evaluate((i,l,o)=>{let d=new Function("return ("+l+")")(),h=document.getElementById("storybook-root")||document.getElementById("root"),s=null;if(h)try{s=new Function("return ("+i+")")()(h)}catch{s=h.firstElementChild}let c={};if(s){let f=window.getComputedStyle(s);for(let w=0;w<f.length;w++)c[f[w]]=f.getPropertyValue(f[w])}let u={backgroundColor:["transparent","rgba(0, 0, 0, 0)"],border:["none","0px none","0px none rgb(0, 0, 0)"],borderRadius:["0px"],boxShadow:["none"],opacity:["1"]};function a(f){return f.replace(/-([a-z])/g,(w,b)=>b.toUpperCase())}function p(f,w){if(w>4)return null;let b=f.tagName.toLowerCase();if(["script","style","link","meta","br","hr","noscript"].includes(b))return null;let x=f.className,S=typeof x=="string"?x:x?.baseVal||"",E=f.id||void 0,T=f.getAttribute("role")||void 0,C;for(let v of Array.from(f.childNodes))if(v.nodeType===3){let I=v.textContent?.trim();if(I){C=I.length>50?I.substring(0,50)+"...":I;break}}let _=b;E?_=`${b}#${E}`:S&&(_=`${b}.${S.split(" ").filter(Boolean).join(".")}`);let P=window.getComputedStyle(f),L=["background-color","border","border-radius","box-shadow","opacity","fill","stroke","stroke-width","font-size","font-family","font-weight","line-height","letter-spacing","color","text-align","display","padding","margin","gap","flex-direction","justify-content","align-items","width","height"],R={};for(let v of L){let I=P.getPropertyValue(v),M=a(v);I&&!u[M]?.includes(I)&&(R[M]=I)}if(!R.border){let v=["top","right","bottom","left"].filter(I=>parseFloat(P.getPropertyValue(`border-${I}-width`))>0&&P.getPropertyValue(`border-${I}-style`)!=="none");if(v.length>0){let I=v.reduce((M,A)=>parseFloat(P.getPropertyValue(`border-${A}-width`))>parseFloat(P.getPropertyValue(`border-${M}-width`))?A:M);R.border=`${P.getPropertyValue(`border-${I}-width`)} ${P.getPropertyValue(`border-${I}-style`)} ${P.getPropertyValue(`border-${I}-color`)}`,R.borderSides=v.join(" ")}}if(b==="svg"||f.closest("svg"))for(let v of["fill","stroke","stroke-width","viewBox","d","r","cx","cy"]){let I=f.getAttribute(v);I&&(R[a(v)]=I)}let D=[];for(let v of Array.from(f.children)){let I=window.getComputedStyle(v);if(I.display==="none"||I.visibility==="hidden")continue;let M=p(v,w+1);M&&D.push(M)}return{selector:_,tagName:b,className:S,id:E,role:T,textContent:C,rect:s?d(f,s):void 0,instance:Number(f.getAttribute(o))>0?Number(f.getAttribute(o)):void 0,styles:R,children:D}}let g=s?p(s,0):null,m=document.querySelector("["+o+"-count]");return g&&m&&(g.instanceCount=Number(m.getAttribute(o+"-count"))),{computedStyles:c,domTree:g}},n,gt,bt)}async function z(e,n=5e3){await e.evaluate(t=>new Promise(r=>{let i=setTimeout(r,t);try{let l=window.__STORYBOOK_ADDONS_CHANNEL__;if(l){let o=()=>{clearTimeout(i),l.off("storyRendered",o),setTimeout(r,100)};l.on("storyRendered",o)}else clearTimeout(i),setTimeout(r,300)}catch{clearTimeout(i),r()}}),n)}async function Ee(e,n,t=15e3){return await e.evaluate((r,i)=>{let l=window,o=l.__STORYBOOK_PREVIEW__,d=l.__STORYBOOK_ADDONS_CHANNEL__;return!o||!d||typeof o.renderSelection!="function"||typeof o.selectionStore?.setSelection!="function"?Promise.resolve("no-preview"):new Promise(h=>{let s=!1,c=g=>{if(!s){s=!0,clearTimeout(p);try{d.off("storyRendered",u),d.off("storyErrored",a),d.off("storyMissing",a)}catch{}h(g)}},u=g=>{let m=typeof g=="string"?g:g?.storyId||g?.id;(!m||m===r)&&setTimeout(()=>c("ok"),100)},a=()=>c("errored"),p=setTimeout(()=>c("timeout"),i);d.on("storyRendered",u),d.on("storyErrored",a),d.on("storyMissing",a);try{o.selectionStore.setSelection({storyId:r,viewMode:"story"}),o.renderSelection()}catch{c("nav-failed")}})},n,t)}async function Ce(e){try{return await e.evaluate(()=>window.__STORYBOOK_PREVIEW__?.selectionStore?.selection?.storyId||null)}catch{return null}}async function ee(e){try{return await e.evaluate(()=>{let n=r=>r?r.getAttributeNames().sort().map(i=>{let l=r.getAttribute(i)??"";return i!=="class"?`${i}=${l}`:`class=${l.split(/\s+/).filter(d=>d&&!d.startsWith("sb-")).sort().join(" ")}`}).join("|"):"<missing>",t=document.getElementById("storybook-root")||document.getElementById("root");return[`html[${n(document.documentElement)}]`,`body[${n(document.body)}]`,`root[${n(t)}]`].join(" ")})}catch{return null}}var xt=6,St=15,Et=9e4,Ct=2e4;function Tt(){let e=Number(process.env.UICOPILOT_WARM_MAX_USES);return Number.isFinite(e)&&e>0?e:St}function It(){return process.env.UICOPILOT_WARM_CAPTURE!=="0"}var O=[],ne=[];function vt(e,n){return`${e}/iframe.html?viewMode=story&id=${n}&globals=`}function re(){let e=ne.shift();e&&e()}function Te(){let e=Date.now(),n=O.filter(t=>!t.busy&&t.page&&e-t.lastUsedAt>Et);if(n.length===0){O.length===0&&te();return}O=O.filter(t=>!n.includes(t));for(let t of n)t.page?.close().catch(()=>{});O.length===0&&te()}var F=null;function _t(){F||(F=setInterval(Te,3e4),F.unref?.())}function te(){F&&(clearInterval(F),F=null)}async function Pt(e,n,t){let r=await e.newPage();try{return await r.setViewport({width:800,height:600,deviceScaleFactor:1}),await r.goto(vt(n,t),{waitUntil:"load",timeout:Ct}),await r.evaluate(()=>document.fonts.ready),await r.waitForSelector("#storybook-root > *",{timeout:1e4}),await z(r),r}catch(i){throw await r.close().catch(()=>{}),i}}async function Ot(e,n,t){for(;;){Te();let r=O.find(i=>i.baseUrl===n&&!i.busy&&i.page);if(r)return r.busy=!0,{entry:r,fresh:!1};if(O.length<xt){let i={page:null,baseUrl:n,uses:0,lastUsedAt:Date.now(),busy:!0,baseline:null};O.push(i),_t();try{return i.page=await Pt(e,n,t),i.baseline=await ee(i.page),{entry:i,fresh:!0}}catch{return O=O.filter(l=>l!==i),re(),null}}await new Promise(i=>ne.push(i))}}function N(e,n){e.busy=!1,e.uses++,e.lastUsedAt=Date.now(),(n||e.uses>=Tt())&&(O=O.filter(t=>t!==e),e.page?.close().catch(()=>{})),re()}async function Ie(e,n,t,r){if(!It())return{ok:!1,reason:"disabled"};let i=await Ot(e,n,t);if(!i)return{ok:!1,reason:"boot-failed"};let{entry:l,fresh:o}=i,d=l.page;try{if(!o){let s=await Ee(d,t);if(s!=="ok")return N(l,!0),{ok:!1,reason:`switch-${s}`};let c=await Ce(d);if(c&&c!==t)return N(l,!0),{ok:!1,reason:"selection-mismatch"};if(l.baseline===null)return N(l,!0),{ok:!1,reason:"baseline-unavailable"};let u=await ee(d);if(u===null)return N(l,!0),{ok:!1,reason:"document-unreadable"};if(u!==l.baseline)return N(l,!0),{ok:!1,reason:"document-drift"};await d.evaluate(()=>document.fonts.ready)}let h=await r(d);return N(l,!1),{ok:!0,value:h,booted:o}}catch(h){return N(l,!0),{ok:!1,reason:`error:${h.message}`}}}async function oe(){te();let e=O;for(O=[];ne.length;)re();await Promise.all(e.map(n=>n.page?.close().catch(()=>{})))}var Ne=H.toString(),ie=null,U=null,ke=!1;async function Bt(){if(!ke){ke=!0;try{let e=await Promise.resolve().then(()=>(Re(),Me));ie=e.validateCodeForFile,U=e.formatValidationResult,y.debug("Code validator loaded - fix validation enabled")}catch{y.debug("Code validator not available - skipping fix validation")}}}var Ht="UICOPILOT/APPLY_FIXES",Vt="UICOPILOT/FIX_STARTED",jt="UICOPILOT/FIX_COMPLETED",zt="UICOPILOT/FIX_FAILED",Fe="UICOPILOT/ALL_FIXES_APPLIED",Ut="UICOPILOT/RELOAD_REQUIRED",Le="UICOPILOT/WORKSPACE_PATH",Wt="UICOPILOT/REQUEST_WORKSPACE_PATH",Xt="UICOPILOT/DISCOVER_COMPONENT_FILES",Ae="UICOPILOT/COMPONENT_FILES_DISCOVERED";async function De(e,n){let t=e.toLowerCase(),r=e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),i=[`src/**/fui-${t}/fui-${t}.css`,`src/**/fui-${t}/*.css`,`src/**/${t}/${t}.css`,`src/**/${r}/${r}.css`,`src/**/*${t}*.css`,`src/**/*${r}*.css`,`styles/**/*${t}*.css`],l=[`src/**/fui-${t}/fui-${t}.tsx`,`src/**/fui-${t}/*.tsx`,`src/**/${t}/${t}.tsx`,`src/**/${r}/${r}.tsx`,`src/**/*${r}*.tsx`,`src/**/*${r}*.jsx`],o=[],d=[];for(let m of i)try{let f=await $e(m,{cwd:n,nodir:!0,ignore:["**/node_modules/**","**/dist/**","**/.storybook/**"]});f.length>0&&o.push(...f)}catch{}for(let m of l)try{let f=await $e(m,{cwd:n,nodir:!0,ignore:["**/node_modules/**","**/dist/**","**/.storybook/**","**/*.stories.*","**/*.test.*"]});f.length>0&&d.push(...f)}catch{}let h=[...new Set(o)],s=[...new Set(d)],c=m=>{if(m.length===0)return;let f=m.find(x=>x.includes(`/fui-${t}/`)&&x.endsWith(".css"));if(f)return f;let w=m.find(x=>x.toLowerCase().includes(`/${t}/${t}.css`)||x.includes(`/${r}/${r}.css`));if(w)return w;let b=m.find(x=>x.toLowerCase().endsWith(`/${t}.css`)||x.endsWith(`/${r}.css`));return b||m[0]},u=m=>{if(m.length===0)return;let f=m.filter(S=>!S.includes(".stories.")&&!S.includes(".test."));if(f.length===0)return m[0];let w=f.find(S=>S.includes(`/fui-${t}/`)&&(S.endsWith(".tsx")||S.endsWith(".jsx")));if(w)return w;let b=f.find(S=>S.toLowerCase().includes(`/${t}/${t}.tsx`)||S.includes(`/${r}/${r}.tsx`));if(b)return b;let x=f.find(S=>S.toLowerCase().endsWith(`/${t}.tsx`)||S.endsWith(`/${r}.tsx`));return x||f[0]},a=c(h),p=u(s),g=[...h,...s];return y.debug(`Discovered files for "${e}":`,{cssFile:a,componentFile:p,totalMatches:g.length}),{cssFile:a,componentFile:p,allMatches:[...new Set(g)]}}var Gt=100;function Kt(e){return new Promise(n=>setTimeout(n,e))}async function qt(e,n){if(await Bt(),!ie||!U)return y.debug(`Skipping validation (validator not available) for ${n}`),{valid:!0};let t=ie(e,n);if(!t.valid){let r=t.errors.map(i=>i.message).join("; ");return y.warn(`Code validation failed for ${n}:`),console.warn(U(t)),{valid:!1,error:r}}return t.warnings.length>0&&(y.warn(`Code validation warnings for ${n}:`),console.warn(U(t))),y.debug(`Validation passed for ${n}`),{valid:!0}}var Be=!1;function Yt(e){if(Be)return e;Be=!0;let n=process.cwd();return y.debug("Apply fixes initialized"),y.debug("Workspace:",n),e.emit(Le,{path:n}),e.on(Wt,()=>{y.debug("Workspace path requested by browser"),y.debug("Emitting workspace path response:",n),e.emit(Le,{path:n})}),e.on(Xt,async t=>{let{componentName:r,storyId:i}=t;y.debug(`Discovering files for component: ${r}`);try{let l=await De(r,n);e.emit(Ae,{componentName:r,storyId:i,...l,workspacePath:n})}catch(l){y.error("File discovery error:",l),e.emit(Ae,{componentName:r,storyId:i,error:l.message,allMatches:[]})}}),e.on(Ht,t=>{setTimeout(async()=>{try{let{issues:r,storybookRoot:i}=t,l=i||n;i?y.debug(`Using storybookRoot from API: ${i}`):y.debug(`Using process.cwd(): ${n}`),y.debug(`Received APPLY_FIXES for ${r.length} issue(s)`);let o=new Map;async function d(c){let u=c.targetFileType||"css",a=c.targetFilePath||c.generatedFix?.filePath,p="",g=c.title?.match(/^(\w+)\s/);if(g&&(p=g[1]),!p&&a){let w=a.match(/\/(\w+)\.(?:css|tsx|jsx)$/i);w&&(p=w[1])}if(!p)return y.debug(`Could not extract component name, using provided path: ${a}`),a||null;if(!o.has(p)){let w=await De(p,l);o.set(p,w)}let m=o.get(p),f=u==="css"?m.cssFile:m.componentFile;return f?(y.debug(`Discovered ${u} path: ${f} (was: ${a})`),f):(y.debug(`No ${u} file discovered, using provided: ${a}`),a||null)}let h=[];for(let c of r){let{generatedFix:u}=c,a=c.targetFilePath||u?.filePath,p=await d(c)||a;y.debug("Processing issue:",{id:c.id,type:c.type,targetFileType:c.targetFileType||"css",targetPath:p,providedPath:a!==p?a:"(same)",codeLength:u?.code?.length||0}),e.emit(Vt,{issueId:c.id});try{if(!u||!u.code||!p)throw new Error("Missing AI-generated fix data (code or filePath)");y.debug("Code to write (first 200 chars):",u.code.substring(0,200)),y.debug(`Code length: ${u.code.length} chars`);let g=await qt(u.code,p);if(!g.valid)throw new Error(`Code validation failed: ${g.error}. Fix was not applied to prevent breaking the file.`);let m=W.isAbsolute(p)?p:W.join(l,p);y.debug(`Writing to absolute path: ${m}`),await He.writeFile(m,u.code,"utf-8"),await Kt(Gt);let f={success:!0,issueId:c.id,filePath:p,timestamp:new Date};e.emit(jt,{issueId:c.id,result:f}),y.debug(`\u2713 Applied ${c.targetFileType||"css"} fix to: ${p}`),h.push(f)}catch(g){let m=g.message||"Unknown error";e.emit(zt,{issueId:c.id,error:m}),y.error(`\u2717 Error: ${m}`),h.push({success:!1,issueId:c.id,error:m,timestamp:new Date})}}let s={total:h.length,succeeded:h.filter(c=>c.success).length,failed:h.filter(c=>!c.success).length};e.emit(Fe,{results:h,summary:s}),y.debug(`Completed: ${s.succeeded}/${s.total} fixes applied`),s.succeeded>0&&e.emit(Ut,{message:"Fixes applied. If Storybook crashes due to HMR, please restart it.",filesChanged:h.filter(c=>c.success).map(c=>c.filePath)})}catch(r){y.error("Fatal error during fix application:",r),e.emit(Fe,{results:[],summary:{total:t.issues?.length||0,succeeded:0,failed:t.issues?.length||0}})}},0)}),e}function Jt(e){let n=process.cwd();return e.plugins=e.plugins||[],e.plugins.push({name:"uicopilot-server-api",configureServer(t){t.middlewares.use("/__uicopilot/health",(l,o)=>{o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({ok:!0,workspacePath:n}))}),t.middlewares.use("/__uicopilot/screenshot",async(l,o)=>{try{if(!await j()){o.writeHead(501,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Puppeteer not installed. Run: npm install puppeteer"}));return}let s=new URL(l.url||"",`http://${l.headers.host}`).searchParams.get("storyId");if(!s){o.writeHead(400,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Missing storyId parameter"}));return}let u=`http://${l.headers.host||"localhost:6006"}/iframe.html?viewMode=story&id=${s}&globals=`;y.debug(`Taking screenshot: ${s}`);let a=await J(u,{selector:"#storybook-root > *"});if(!a){o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Screenshot capture failed"}));return}let p=a.toString("base64");o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({screenshot:`data:image/png;base64,${p}`}))}catch(d){y.error("Screenshot error:",d.message),o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:d.message}))}}),t.middlewares.use("/__uicopilot/capture",async(l,o)=>{try{if(!await j()){o.writeHead(501,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Puppeteer not installed"}));return}let h=new URL(l.url||"",`http://${l.headers.host}`),s=h.searchParams.get("storyId");if(!s){o.writeHead(400,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Missing storyId parameter"}));return}let c=h.searchParams.get("domOnly")==="1",u=l.headers.host||"localhost:6006",a=`http://${u}/iframe.html?viewMode=story&id=${s}&globals=`;y.debug(`Full capture${c?" (domOnly)":""}: ${s}`);let p=null;if(!c&&(p=await J(a,{selector:"#storybook-root > *"}),!p)){o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Screenshot capture failed"}));return}let g=await ye(),m=h.searchParams.get("warm")==="0",f=null,w="cold";if(!m){let b=`http://${u}`,x=await Ie(g,b,s,S=>Q(S,Ne,s));x.ok?(f=x.value,w=x.booted?"warm-boot":"warm"):y.debug(`Warm capture unavailable (${x.reason}): ${s}`)}if(!f){let b=await g.newPage();try{await b.setCacheEnabled(!1),await b.setViewport({width:800,height:600}),await b.goto(a,{waitUntil:"load",timeout:15e3}),await b.evaluate(()=>document.fonts.ready),await b.waitForSelector("#storybook-root > *",{timeout:1e4}),await z(b),f=await Q(b,Ne,s)}finally{await b.close()}}y.debug(`Capture path for ${s}: ${w}`),o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({screenshot:p?`data:image/png;base64,${p.toString("base64")}`:void 0,computedStyles:f.computedStyles,domTree:f.domTree}))}catch(d){y.error("Capture error:",d.message),o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:d.message}))}}),t.middlewares.use("/__uicopilot/screenshot-snapshot",async(l,o)=>{if(l.method!=="POST"){o.writeHead(405,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"POST required"}));return}try{if(!await j()){o.writeHead(501,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Puppeteer not installed"}));return}let h=[];for await(let w of l)h.push(typeof w=="string"?Buffer.from(w):w);let s=JSON.parse(Buffer.concat(h).toString()),{html:c,stylesheetUrls:u,storyId:a}=s;if(!c){o.writeHead(400,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Missing html in body"}));return}let g=`http://${l.headers.host||"localhost:6006"}`;y.debug(`Taking snapshot screenshot for ${a||"unknown"}`);let m=await we(c,u||[],g,{storyId:a});if(!m){o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Snapshot screenshot failed"}));return}let f=m.toString("base64");o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({screenshot:`data:image/png;base64,${f}`}))}catch(d){y.error("Snapshot screenshot error:",d.message),o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:d.message}))}}),t.httpServer?.on("close",()=>{oe().catch(()=>{}).finally(()=>Z().catch(()=>{}))});let r=l=>{oe().catch(()=>{}).then(()=>Z()).catch(()=>{}).finally(()=>{process.kill(process.pid,l)})},i=globalThis;i.__uicopilotShutdownRegistered||(i.__uicopilotShutdownRegistered=!0,process.once("SIGINT",()=>r("SIGINT")),process.once("SIGTERM",()=>r("SIGTERM")))}}),e}var Zt=()=>{if(typeof import.meta<"u"&&import.meta.url){let e=je(import.meta.url),n=Ve(e);return X(n,"manager.mjs")}return X(__dirname,"manager.mjs")},Qt=()=>{if(typeof import.meta<"u"&&import.meta.url){let e=je(import.meta.url),n=Ve(e);return X(n,"preview.mjs")}return X(__dirname,"preview.mjs")};function fi(e=[]){return[...e,Zt()]}function pi(e=[]){return[...e,Qt()]}export{Yt as experimental_serverChannel,fi as managerEntries,pi as previewAnnotations,Jt as viteFinal};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uicopilot/storybook-addon",
3
- "version": "0.19.0",
3
+ "version": "0.20.0",
4
4
  "description": "Catch design drift between Figma and Storybook before it ships.",
5
5
  "homepage": "https://uiparity.com",
6
6
  "keywords": [