@uicopilot/storybook-addon 0.16.0 → 0.18.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/manager.mjs +121 -99
- package/dist/preset.js +3 -3
- package/dist/preset.mjs +3 -3
- package/package.json +1 -1
package/dist/preset.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";var
|
|
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
|
|
3
|
-
`)}var st,be=De(()=>{"use strict";st=50});var Nt={};re(Nt,{experimental_serverChannel:()=>_e,managerEntries:()=>_t,previewAnnotations:()=>$t,viteFinal:()=>$e});module.exports=Be(Nt);var R=require("path"),te=require("url");var Le=H(require("fs/promises")),X=H(require("path")),Q=require("glob");var de=require("fs"),pe=require("module");var K={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 Ve(){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=`[${K.NAME}]`,p={debug:(...e)=>{Ve()&&console.log(j,...e)},info:(...e)=>{console.log(j,...e)},warn:(...e)=>{console.warn(j,...e)},error:(...e)=>{console.error(j,...e)}};var tt=["flex","inline-flex"],nt=["grid","inline-grid"],rn=[...tt,...nt];function z(e){let o=e.ownerDocument?.defaultView;if(!o)return e.firstElementChild??e;let i=e.getBoundingClientRect(),a=d=>{let c=o.getComputedStyle(d);if(c.position==="fixed"||c.display==="none"||c.visibility==="hidden")return!0;let s=d.getBoundingClientRect();return s.width===0||s.height===0||d.children.length===0&&!(d.textContent??"").trim()},r=d=>{if(i.width===0||i.height===0)return!1;let c=d.getBoundingClientRect();return c.width>=i.width*.9&&c.height>=i.height*.9},u=e;for(let d=0;d<6;d+=1){let c=Array.from(u.children).filter(s=>!a(s));if(c.length!==1||u!==e&&!r(u))break;u=c[0]}return u===e?e.firstElementChild??e:u}var fe=z.toString(),U=null,N=null,ue=!1;async function Y(){if(ue)return!!U;if(ue=!0,process.env.STORYBOOK_UICOPILOT_NO_PUPPETEER==="true")return p.debug("Puppeteer disabled via STORYBOOK_UICOPILOT_NO_PUPPETEER flag"),!1;let e=(0,pe.createRequire)(process.cwd()+"/");try{return U=e("puppeteer"),p.debug("Puppeteer loaded \u2014 server-side screenshots enabled"),!0}catch{}try{return U=e("puppeteer-core"),p.debug("puppeteer-core loaded \u2014 server-side screenshots enabled"),!0}catch{}return p.debug("Puppeteer not found \u2014 install puppeteer for pixel-perfect screenshots"),!1}function it(){let e=["/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"];for(let n of e)if((0,de.existsSync)(n))return n}async function me(){if(N&&N.connected)return N;let e=it(),n={headless:!0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-dev-shm-usage"],...e?{executablePath:e}:{}};return N=await U.launch(n),p.debug("Headless Chrome launched for screenshots"),N}async function J(e,n){if(!await Y())return null;let i=await(await me()).newPage();try{await i.setCacheEnabled(!1),await i.setViewport({width:n?.width||800,height:n?.height||600,deviceScaleFactor:1}),await i.goto(e,{waitUntil:"networkidle2",timeout:15e3}),await i.evaluate(()=>document.fonts.ready),await i.waitForSelector("#storybook-root > *",{timeout:1e4}),await i.waitForFunction(()=>new Promise(c=>{let s=document.querySelectorAll("style").length,y=0,f=()=>{let g=document.querySelectorAll("style").length;if(g===s){if(y++,y>=3){c(!0);return}}else y=0,s=g;setTimeout(f,100)};setTimeout(f,200)}),{timeout:5e3}).catch(()=>{}),await new Promise(c=>setTimeout(c,500));let a=await i.evaluate(c=>{let s=document.querySelector("#storybook-root");if(!s)return null;let y=window.innerHeight,f=window.innerWidth,g=w=>w.setAttribute("data-uic-drilled",""),v=()=>{let w=document.createElement("style");w.id="uic-drilled-bg-reset",w.textContent="[data-uic-drilled] { background: transparent !important; border-color: transparent !important; box-shadow: none !important; }",document.head.appendChild(w),document.body.offsetHeight};try{let E=new Function("return ("+c+")")()(s),b=E?.getBoundingClientRect(),T=!!b&&b.width>=f*.9&&b.height>=y*.9;if(E&&E!==s&&b&&b.width>0&&b.height>0&&!T){for(let C=E.parentElement;C&&C!==s;C=C.parentElement)g(C);return v(),{top:b.top,bottom:b.bottom,left:b.left,right:b.right}}}catch{}let l=1/0,h=0,x=1/0,I=0,S=!1;function m(w){for(let E of Array.from(w.children)){let b=window.getComputedStyle(E);if(b.display==="none"||b.visibility==="hidden"||b.position==="fixed"||b.position==="absolute")continue;let T=E.getBoundingClientRect();if(T.height<=0||T.width<=0)continue;if((T.width>=f*.9||T.height>=y*.9)&&E.children.length>0){E.setAttribute("data-uic-drilled",""),m(E);continue}if(E.children.length===1){let L=b.backgroundColor,$=L==="rgba(0, 0, 0, 0)"||L==="transparent"||L==="",M=b.borderStyle!=="none"&&b.borderWidth!=="0px",F=b.boxShadow!=="none",k=!$||M||F,A=E.children[0].getBoundingClientRect(),D=A.width>=T.width*.95&&A.height>=T.height*.95;if(!k||D){E.setAttribute("data-uic-drilled",""),m(E);continue}}l=Math.min(l,T.top),h=Math.max(h,T.bottom),x=Math.min(x,T.left),I=Math.max(I,T.right),S=!0}}return m(s),S?(v(),{top:l,bottom:h,left:x,right:I}):null},fe);await i.evaluate(()=>new Promise(c=>requestAnimationFrame(()=>c())));let r=4,u=a?{x:Math.max(0,a.left-r),y:Math.max(0,a.top-r),width:Math.min(a.right-a.left+r*2,800),height:Math.min(a.bottom-a.top+r*2,600)}:void 0,d=await i.screenshot({type:"png",omitBackground:!0,...u?{clip:u}:{fullPage:!1}});return Buffer.from(d)}finally{await i.close()}}async function ge(e,n,t,o){if(!await Y())return null;let r=await(await me()).newPage();try{await r.setCacheEnabled(!1),await r.setViewport({width:o?.width||800,height:o?.height||600,deviceScaleFactor:1});let u=o?.storyId||"",d=`${t}/iframe.html?viewMode=story&id=${u}&globals=`;await r.goto(d,{waitUntil:"load",timeout:15e3}),await r.waitForSelector("#storybook-root > *",{timeout:1e4}),await r.evaluate(y=>{let f=document.getElementById("storybook-root");f&&(f.innerHTML=y)},e),await r.evaluate(()=>document.fonts.ready),await new Promise(y=>setTimeout(y,500));let c=await r.evaluate(y=>{let f=document.querySelector("#storybook-root");if(!f)return null;let g=window.innerWidth,v=window.innerHeight,l=8;try{let m=new Function("return ("+y+")")()(f),w=m?.getBoundingClientRect(),E=!!w&&w.width>=g*.9&&w.height>=v*.9;if(m&&m!==f&&w&&w.width>0&&w.height>0&&!E)return{x:Math.max(0,w.x-l),y:Math.max(0,w.y-l),width:w.width+l*2,height:w.height+l*2}}catch{}function h(S){let m=S.getBoundingClientRect();if(m.width===0||m.height===0)return null;if(m.width<g*.8&&m.height>0)return m;for(let w of Array.from(S.children)){let E=window.getComputedStyle(w);if(E.position==="fixed"||E.position==="absolute"||E.display==="none"||E.visibility==="hidden")continue;let b=h(w);if(b)return b}return null}let x=h(f);if(x)return{x:Math.max(0,x.x-l),y:Math.max(0,x.y-l),width:x.width+l*2,height:x.height+l*2};let I=f.firstElementChild;if(I){let S=I.getBoundingClientRect();return{x:S.x,y:S.y,width:S.width,height:S.height}}return null},fe);if(!c)throw new Error("Could not determine component bounds from snapshot");let s=await r.screenshot({type:"png",clip:c});return Buffer.from(s)}finally{await r.close()}}async function W(){return Y()}async function Z(){N&&(await N.close(),N=null)}var gt=z.toString(),ee=null,G=null,Ce=!1;async function ht(){if(!Ce){Ce=!0;try{let e=await Promise.resolve().then(()=>(be(),xe));ee=e.validateCodeForFile,G=e.formatValidationResult,p.debug("Code validator loaded - fix validation enabled")}catch{p.debug("Code validator not available - skipping fix validation")}}}var yt="UICOPILOT/APPLY_FIXES",St="UICOPILOT/FIX_STARTED",wt="UICOPILOT/FIX_COMPLETED",xt="UICOPILOT/FIX_FAILED",Ee="UICOPILOT/ALL_FIXES_APPLIED",bt="UICOPILOT/RELOAD_REQUIRED",ve="UICOPILOT/WORKSPACE_PATH",Ct="UICOPILOT/REQUEST_WORKSPACE_PATH",Et="UICOPILOT/DISCOVER_COMPONENT_FILES",Ie="UICOPILOT/COMPONENT_FILES_DISCOVERED";async function Te(e,n){let t=e.toLowerCase(),o=e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),i=[`src/**/fui-${t}/fui-${t}.css`,`src/**/fui-${t}/*.css`,`src/**/${t}/${t}.css`,`src/**/${o}/${o}.css`,`src/**/*${t}*.css`,`src/**/*${o}*.css`,`styles/**/*${t}*.css`],a=[`src/**/fui-${t}/fui-${t}.tsx`,`src/**/fui-${t}/*.tsx`,`src/**/${t}/${t}.tsx`,`src/**/${o}/${o}.tsx`,`src/**/*${o}*.tsx`,`src/**/*${o}*.jsx`],r=[],u=[];for(let l of i)try{let h=await(0,Q.glob)(l,{cwd:n,nodir:!0,ignore:["**/node_modules/**","**/dist/**","**/.storybook/**"]});h.length>0&&r.push(...h)}catch{}for(let l of a)try{let h=await(0,Q.glob)(l,{cwd:n,nodir:!0,ignore:["**/node_modules/**","**/dist/**","**/.storybook/**","**/*.stories.*","**/*.test.*"]});h.length>0&&u.push(...h)}catch{}let d=[...new Set(r)],c=[...new Set(u)],s=l=>{if(l.length===0)return;let h=l.find(S=>S.includes(`/fui-${t}/`)&&S.endsWith(".css"));if(h)return h;let x=l.find(S=>S.toLowerCase().includes(`/${t}/${t}.css`)||S.includes(`/${o}/${o}.css`));if(x)return x;let I=l.find(S=>S.toLowerCase().endsWith(`/${t}.css`)||S.endsWith(`/${o}.css`));return I||l[0]},y=l=>{if(l.length===0)return;let h=l.filter(m=>!m.includes(".stories.")&&!m.includes(".test."));if(h.length===0)return l[0];let x=h.find(m=>m.includes(`/fui-${t}/`)&&(m.endsWith(".tsx")||m.endsWith(".jsx")));if(x)return x;let I=h.find(m=>m.toLowerCase().includes(`/${t}/${t}.tsx`)||m.includes(`/${o}/${o}.tsx`));if(I)return I;let S=h.find(m=>m.toLowerCase().endsWith(`/${t}.tsx`)||m.endsWith(`/${o}.tsx`));return S||h[0]},f=s(d),g=y(c),v=[...d,...c];return p.debug(`Discovered files for "${e}":`,{cssFile:f,componentFile:g,totalMatches:v.length}),{cssFile:f,componentFile:g,allMatches:[...new Set(v)]}}var vt=100;function It(e){return new Promise(n=>setTimeout(n,e))}async function Tt(e,n){if(await ht(),!ee||!G)return p.debug(`Skipping validation (validator not available) for ${n}`),{valid:!0};let t=ee(e,n);if(!t.valid){let o=t.errors.map(i=>i.message).join("; ");return p.warn(`Code validation failed for ${n}:`),console.warn(G(t)),{valid:!1,error:o}}return t.warnings.length>0&&(p.warn(`Code validation warnings for ${n}:`),console.warn(G(t))),p.debug(`Validation passed for ${n}`),{valid:!0}}var Pe=!1;function _e(e){if(Pe)return e;Pe=!0;let n=process.cwd();return p.debug("Apply fixes initialized"),p.debug("Workspace:",n),e.emit(ve,{path:n}),e.on(Ct,()=>{p.debug("Workspace path requested by browser"),p.debug("Emitting workspace path response:",n),e.emit(ve,{path:n})}),e.on(Et,async t=>{let{componentName:o,storyId:i}=t;p.debug(`Discovering files for component: ${o}`);try{let a=await Te(o,n);e.emit(Ie,{componentName:o,storyId:i,...a,workspacePath:n})}catch(a){p.error("File discovery error:",a),e.emit(Ie,{componentName:o,storyId:i,error:a.message,allMatches:[]})}}),e.on(yt,t=>{setTimeout(async()=>{try{let{issues:o,storybookRoot:i}=t,a=i||n;i?p.debug(`Using storybookRoot from API: ${i}`):p.debug(`Using process.cwd(): ${n}`),p.debug(`Received APPLY_FIXES for ${o.length} issue(s)`);let r=new Map;async function u(s){let y=s.targetFileType||"css",f=s.targetFilePath||s.generatedFix?.filePath,g="",v=s.title?.match(/^(\w+)\s/);if(v&&(g=v[1]),!g&&f){let x=f.match(/\/(\w+)\.(?:css|tsx|jsx)$/i);x&&(g=x[1])}if(!g)return p.debug(`Could not extract component name, using provided path: ${f}`),f||null;if(!r.has(g)){let x=await Te(g,a);r.set(g,x)}let l=r.get(g),h=y==="css"?l.cssFile:l.componentFile;return h?(p.debug(`Discovered ${y} path: ${h} (was: ${f})`),h):(p.debug(`No ${y} file discovered, using provided: ${f}`),f||null)}let d=[];for(let s of o){let{generatedFix:y}=s,f=s.targetFilePath||y?.filePath,g=await u(s)||f;p.debug("Processing issue:",{id:s.id,type:s.type,targetFileType:s.targetFileType||"css",targetPath:g,providedPath:f!==g?f:"(same)",codeLength:y?.code?.length||0}),e.emit(St,{issueId:s.id});try{if(!y||!y.code||!g)throw new Error("Missing AI-generated fix data (code or filePath)");p.debug("Code to write (first 200 chars):",y.code.substring(0,200)),p.debug(`Code length: ${y.code.length} chars`);let v=await Tt(y.code,g);if(!v.valid)throw new Error(`Code validation failed: ${v.error}. Fix was not applied to prevent breaking the file.`);let l=X.isAbsolute(g)?g:X.join(a,g);p.debug(`Writing to absolute path: ${l}`),await Le.writeFile(l,y.code,"utf-8"),await It(vt);let h={success:!0,issueId:s.id,filePath:g,timestamp:new Date};e.emit(wt,{issueId:s.id,result:h}),p.debug(`\u2713 Applied ${s.targetFileType||"css"} fix to: ${g}`),d.push(h)}catch(v){let l=v.message||"Unknown error";e.emit(xt,{issueId:s.id,error:l}),p.error(`\u2717 Error: ${l}`),d.push({success:!1,issueId:s.id,error:l,timestamp:new Date})}}let c={total:d.length,succeeded:d.filter(s=>s.success).length,failed:d.filter(s=>!s.success).length};e.emit(Ee,{results:d,summary:c}),p.debug(`Completed: ${c.succeeded}/${c.total} fixes applied`),c.succeeded>0&&e.emit(bt,{message:"Fixes applied. If Storybook crashes due to HMR, please restart it.",filesChanged:d.filter(s=>s.success).map(s=>s.filePath)})}catch(o){p.error("Fatal error during fix application:",o),e.emit(Ee,{results:[],summary:{total:t.issues?.length||0,succeeded:0,failed:t.issues?.length||0}})}},0)}),e}function $e(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,r)=>{r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({ok:!0,workspacePath:n}))}),t.middlewares.use("/__uicopilot/screenshot",async(a,r)=>{try{if(!await W()){r.writeHead(501,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Puppeteer not installed. Run: npm install puppeteer"}));return}let c=new URL(a.url||"",`http://${a.headers.host}`).searchParams.get("storyId");if(!c){r.writeHead(400,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Missing storyId parameter"}));return}let y=`http://${a.headers.host||"localhost:6006"}/iframe.html?viewMode=story&id=${c}&globals=`;p.debug(`Taking screenshot: ${c}`);let f=await J(y,{selector:"#storybook-root > *"});if(!f){r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Screenshot capture failed"}));return}let g=f.toString("base64");r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({screenshot:`data:image/png;base64,${g}`}))}catch(u){p.error("Screenshot error:",u.message),r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:u.message}))}}),t.middlewares.use("/__uicopilot/capture",async(a,r)=>{try{if(!await W()){r.writeHead(501,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Puppeteer not installed"}));return}let c=new URL(a.url||"",`http://${a.headers.host}`).searchParams.get("storyId");if(!c){r.writeHead(400,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Missing storyId parameter"}));return}let y=`http://${a.headers.host||"localhost:6006"}/iframe.html?viewMode=story&id=${c}&globals=`;p.debug(`Full capture: ${c}`);let f=await J(y,{selector:"#storybook-root > *"});if(!f){r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Screenshot capture failed"}));return}let g;try{g=(await import("puppeteer")).default}catch{g=(await import("puppeteer-core")).default}let v=await g.launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox"]}),l=await v.newPage();try{await l.setCacheEnabled(!1),await l.setViewport({width:800,height:600}),await l.goto(y,{waitUntil:"networkidle2",timeout:15e3}),await l.evaluate(()=>document.fonts.ready),await l.waitForSelector("#storybook-root > *",{timeout:1e4}),await l.evaluate(()=>new Promise(I=>{let S=setTimeout(I,5e3);try{let m=window.__STORYBOOK_ADDONS_CHANNEL__;if(m){let w=()=>{clearTimeout(S),m.off("storyRendered",w),setTimeout(I,100)};m.on("storyRendered",w)}else clearTimeout(S),setTimeout(I,300)}catch{clearTimeout(S),I()}}));let h=await l.evaluate(I=>{let S=document.getElementById("storybook-root")||document.getElementById("root"),m=null;if(S)try{m=new Function("return ("+I+")")()(S)}catch{m=S.firstElementChild}let w={};if(m){let C=window.getComputedStyle(m);for(let L=0;L<C.length;L++)w[C[L]]=C.getPropertyValue(C[L])}let E={backgroundColor:["transparent","rgba(0, 0, 0, 0)"],border:["none","0px none","0px none rgb(0, 0, 0)"],borderRadius:["0px"],boxShadow:["none"],opacity:["1"]};function b(C){return C.replace(/-([a-z])/g,(L,$)=>$.toUpperCase())}function T(C,L){if(L>4)return null;let $=C.tagName.toLowerCase();if(["script","style","link","meta","br","hr","noscript"].includes($))return null;let M=C.className,F=typeof M=="string"?M:M?.baseVal||"",k=C.id||void 0,ne=C.getAttribute("role")||void 0,A;for(let _ of Array.from(C.childNodes))if(_.nodeType===3){let P=_.textContent?.trim();if(P){A=P.length>50?P.substring(0,50)+"...":P;break}}let D=$;k?D=`${$}#${k}`:F&&(D=`${$}.${F.split(" ").filter(Boolean).join(".")}`);let Ne=window.getComputedStyle(C),Re=["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"],q={};for(let _ of Re){let P=Ne.getPropertyValue(_),B=b(_);P&&!E[B]?.includes(P)&&(q[B]=P)}if($==="svg"||C.closest("svg"))for(let _ of["fill","stroke","stroke-width","viewBox","d","r","cx","cy"]){let P=C.getAttribute(_);P&&(q[b(_)]=P)}let oe=[];for(let _ of Array.from(C.children)){let P=window.getComputedStyle(_);if(P.display==="none"||P.visibility==="hidden")continue;let B=T(_,L+1);B&&oe.push(B)}return{selector:D,tagName:$,className:F,id:k,role:ne,textContent:A,styles:q,children:oe}}return{computedStyles:w,domTree:m?T(m,0):null}},gt),x=f.toString("base64");r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({screenshot:`data:image/png;base64,${x}`,computedStyles:h.computedStyles,domTree:h.domTree}))}finally{await l.close(),await v.close()}}catch(u){p.error("Capture error:",u.message),r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:u.message}))}}),t.middlewares.use("/__uicopilot/screenshot-snapshot",async(a,r)=>{if(a.method!=="POST"){r.writeHead(405,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"POST required"}));return}try{if(!await W()){r.writeHead(501,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Puppeteer not installed"}));return}let d=[];for await(let x of a)d.push(typeof x=="string"?Buffer.from(x):x);let c=JSON.parse(Buffer.concat(d).toString()),{html:s,stylesheetUrls:y,storyId:f}=c;if(!s){r.writeHead(400,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Missing html in body"}));return}let v=`http://${a.headers.host||"localhost:6006"}`;p.debug(`Taking snapshot screenshot for ${f||"unknown"}`);let l=await ge(s,y||[],v,{storyId:f});if(!l){r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Snapshot screenshot failed"}));return}let h=l.toString("base64");r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({screenshot:`data:image/png;base64,${h}`}))}catch(u){p.error("Snapshot screenshot error:",u.message),r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:u.message}))}}),t.httpServer?.on("close",()=>{Z().catch(()=>{})});let o=a=>{Z().catch(()=>{}).finally(()=>{process.kill(process.pid,a)})},i=globalThis;i.__uicopilotShutdownRegistered||(i.__uicopilotShutdownRegistered=!0,process.once("SIGINT",()=>o("SIGINT")),process.once("SIGTERM",()=>o("SIGTERM")))}}),e}var O={},Pt=()=>{if(typeof O<"u"&&O.url){let e=(0,te.fileURLToPath)(O.url),n=(0,R.dirname)(e);return(0,R.join)(n,"manager.mjs")}return(0,R.join)(__dirname,"manager.mjs")},Lt=()=>{if(typeof O<"u"&&O.url){let e=(0,te.fileURLToPath)(O.url),n=(0,R.dirname)(e);return(0,R.join)(n,"preview.mjs")}return(0,R.join)(__dirname,"preview.mjs")};function _t(e=[]){return[...e,Pt()]}function $t(e=[]){return[...e,Lt()]}0&&(module.exports={experimental_serverChannel,managerEntries,previewAnnotations,viteFinal});
|
|
1
|
+
"use strict";var Re=Object.create;var D=Object.defineProperty;var Me=Object.getOwnPropertyDescriptor;var Fe=Object.getOwnPropertyNames;var ke=Object.getPrototypeOf,Ae=Object.prototype.hasOwnProperty;var De=(e,n)=>()=>(e&&(n=e(e=0)),n);var oe=(e,n)=>{for(var t in n)D(e,t,{get:n[t],enumerable:!0})},ie=(e,n,t,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let i of Fe(n))!Ae.call(e,i)&&i!==t&&D(e,i,{get:()=>n[i],enumerable:!(r=Me(n,i))||r.enumerable});return e};var se=(e,n,t)=>(t=e!=null?Re(ke(e)):{},ie(n||!e||!e.__esModule?D(t,"default",{value:e,enumerable:!0}):t,e)),Be=e=>ie(D({},"__esModule",{value:!0}),e);var be={};oe(be,{detectFileType:()=>Se,formatValidationResult:()=>mt,isValidCode:()=>ft,validateCode:()=>we,validateCodeForFile:()=>xe});function at(e,n={}){let t=n.minLength??st;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 ct(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(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 ut(e){let n={"{":"}","[":"]","(":")"},t=[],r=!1,i="",a=!1;for(let o=0;o<e.length;o++){let u=e[o],d=e[o-1];if((u==='"'||u==="'"||u==="`")&&d!=="\\"){r?u===i&&(r=!1,a=!1):(r=!0,i=u,u==="`"&&(a=!0));continue}if(!r){if(n[u])t.push(n[u]);else if(Object.values(n).includes(u)&&t.pop()!==u)return{code:"UNBALANCED_BRACES",message:`Unbalanced braces/brackets detected. Found unexpected '${u}'.`,severity:"warning"}}}return t.length>0?{code:"UNBALANCED_BRACES",message:`Unbalanced braces/brackets. Missing: ${t.reverse().join("")}`,severity:"warning"}:null}function ye(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 u=[{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:d,message:c}of u)d.test(e)&&t.push({code:"TSX_INCOMPLETE",message:c,severity:"error"});return{errors:t,warnings:r}}function dt(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 pt(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 Se(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 we(e,n,t={}){let r={valid:!0,fileType:n,errors:[],warnings:[]},i=at(e,t);i&&r.errors.push(i);let a=ct(e);a&&r.errors.push(a);let o=lt(e);o&&r.errors.push(o);let u=ut(e);switch(u&&(t.strict?r.errors.push({...u,severity:"error"}):r.warnings.push(u)),n){case"stories":{let{errors:d,warnings:c}=pt(e,t);r.errors.push(...d),r.warnings.push(...c);break}case"tsx":case"jsx":{let{errors:d,warnings:c}=ye(e,t);r.errors.push(...d),r.warnings.push(...c);break}case"css":case"scss":case"less":{let{errors:d,warnings:c}=dt(e,t);r.errors.push(...d),r.warnings.push(...c);break}case"ts":case"js":{let{errors:d,warnings:c}=ye(e,t);r.errors.push(...d),r.warnings.push(...c.filter(s=>!s.code.includes("JSX")));break}default:break}return r.valid=r.errors.length===0,r}function xe(e,n,t={}){let r=Se(n);return we(e,r,t)}function ft(e,n,t={}){return xe(e,n,t).valid}function mt(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 st,Ce=De(()=>{"use strict";st=50});var Ot={};oe(Ot,{experimental_serverChannel:()=>$e,managerEntries:()=>_t,previewAnnotations:()=>$t,viteFinal:()=>Oe});module.exports=Be(Ot);var O=require("path"),ne=require("url");var _e=se(require("fs/promises")),U=se(require("path")),ee=require("glob");var pe=require("fs"),fe=require("module");var K={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 Ve(){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=`[${K.NAME}]`,p={debug:(...e)=>{Ve()&&console.log(B,...e)},info:(...e)=>{console.log(B,...e)},warn:(...e)=>{console.warn(B,...e)},error:(...e)=>{console.error(B,...e)}};var tt=["flex","inline-flex"],nt=["grid","inline-grid"],on=[...tt,...nt];function V(e){let r=e.ownerDocument?.defaultView;if(!r)return e.firstElementChild??e;let i=e.getBoundingClientRect(),a=d=>{let c=r.getComputedStyle(d);if(c.position==="fixed"||c.display==="none"||c.visibility==="hidden")return!0;let s=d.getBoundingClientRect();return s.width===0||s.height===0||d.children.length===0&&!(d.textContent??"").trim()},o=d=>{if(i.width===0||i.height===0)return!1;let c=d.getBoundingClientRect();return c.width>=i.width*.9&&c.height>=i.height*.9},u=e;for(let d=0;d<6;d+=1){let c=Array.from(u.children).filter(s=>!a(s));if(c.length!==1||u!==e&&!o(u))break;u=c[0]}return u===e?e.firstElementChild??e:u}var me=V.toString(),H=null,$=null,de=!1;async function Y(){if(de)return!!H;if(de=!0,process.env.STORYBOOK_UICOPILOT_NO_PUPPETEER==="true")return p.debug("Puppeteer disabled via STORYBOOK_UICOPILOT_NO_PUPPETEER flag"),!1;let e=(0,fe.createRequire)(process.cwd()+"/");try{return H=e("puppeteer"),p.debug("Puppeteer loaded \u2014 server-side screenshots enabled"),!0}catch{}try{return H=e("puppeteer-core"),p.debug("puppeteer-core loaded \u2014 server-side screenshots enabled"),!0}catch{}return p.debug("Puppeteer not found \u2014 install puppeteer for pixel-perfect screenshots"),!1}function it(){let e=["/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"];for(let n of e)if((0,pe.existsSync)(n))return n}async function ge(){return J()}async function J(){if($&&$.connected)return $;let e=it(),n={headless:!0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-dev-shm-usage"],...e?{executablePath:e}:{}};return $=await H.launch(n),p.debug("Headless Chrome launched for screenshots"),$}async function Z(e,n){if(!await Y())return null;let i=await(await J()).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(c=>{let s=document.querySelectorAll("style").length,y=0,f=()=>{let m=document.querySelectorAll("style").length;if(m===s){if(y++,y>=3){c(!0);return}}else y=0,s=m;setTimeout(f,100)};setTimeout(f,200)}),{timeout:5e3}).catch(()=>{}),await new Promise(c=>setTimeout(c,500));let a=await i.evaluate(c=>{let s=document.querySelector("#storybook-root");if(!s)return null;let y=window.innerHeight,f=window.innerWidth,m=C=>C.setAttribute("data-uic-drilled",""),I=()=>{let C=document.createElement("style");C.id="uic-drilled-bg-reset",C.textContent="[data-uic-drilled] { background: transparent !important; border-color: transparent !important; box-shadow: none !important; }",document.head.appendChild(C),document.body.offsetHeight};try{let E=new Function("return ("+c+")")()(s),b=E?.getBoundingClientRect(),x=!!b&&b.width>=f*.9&&b.height>=y*.9;if(E&&E!==s&&b&&b.width>0&&b.height>0&&!x){for(let T=E.parentElement;T&&T!==s;T=T.parentElement)m(T);return I(),{top:b.top,bottom:b.bottom,left:b.left,right:b.right}}}catch{}let l=1/0,g=0,w=1/0,v=0,h=!1;function S(C){for(let E of Array.from(C.children)){let b=window.getComputedStyle(E);if(b.display==="none"||b.visibility==="hidden"||b.position==="fixed"||b.position==="absolute")continue;let x=E.getBoundingClientRect();if(x.height<=0||x.width<=0)continue;if((x.width>=f*.9||x.height>=y*.9)&&E.children.length>0){E.setAttribute("data-uic-drilled",""),S(E);continue}if(E.children.length===1){let L=b.backgroundColor,M=L==="rgba(0, 0, 0, 0)"||L==="transparent"||L==="",F=b.borderStyle!=="none"&&b.borderWidth!=="0px",k=b.boxShadow!=="none",W=!M||F||k,N=E.children[0].getBoundingClientRect(),X=N.width>=x.width*.95&&N.height>=x.height*.95;if(!W||X){E.setAttribute("data-uic-drilled",""),S(E);continue}}l=Math.min(l,x.top),g=Math.max(g,x.bottom),w=Math.min(w,x.left),v=Math.max(v,x.right),h=!0}}return S(s),h?(I(),{top:l,bottom:g,left:w,right:v}):null},me);await i.evaluate(()=>new Promise(c=>requestAnimationFrame(()=>c())));let o=4,u=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,d=await i.screenshot({type:"png",omitBackground:!0,...u?{clip:u}:{fullPage:!1}});return Buffer.from(d)}finally{await i.close()}}async function he(e,n,t,r){if(!await Y())return null;let o=await(await J()).newPage();try{await o.setCacheEnabled(!1),await o.setViewport({width:r?.width||800,height:r?.height||600,deviceScaleFactor:1});let u=r?.storyId||"",d=`${t}/iframe.html?viewMode=story&id=${u}&globals=`;await o.goto(d,{waitUntil:"load",timeout:15e3}),await o.waitForSelector("#storybook-root > *",{timeout:1e4}),await o.evaluate(y=>{let f=document.getElementById("storybook-root");f&&(f.innerHTML=y)},e),await o.evaluate(()=>document.fonts.ready),await new Promise(y=>setTimeout(y,500));let c=await o.evaluate(y=>{let f=document.querySelector("#storybook-root");if(!f)return null;let m=window.innerWidth,I=window.innerHeight,l=8;try{let S=new Function("return ("+y+")")()(f),C=S?.getBoundingClientRect(),E=!!C&&C.width>=m*.9&&C.height>=I*.9;if(S&&S!==f&&C&&C.width>0&&C.height>0&&!E)return{x:Math.max(0,C.x-l),y:Math.max(0,C.y-l),width:C.width+l*2,height:C.height+l*2}}catch{}function g(h){let S=h.getBoundingClientRect();if(S.width===0||S.height===0)return null;if(S.width<m*.8&&S.height>0)return S;for(let C of Array.from(h.children)){let E=window.getComputedStyle(C);if(E.position==="fixed"||E.position==="absolute"||E.display==="none"||E.visibility==="hidden")continue;let b=g(C);if(b)return b}return null}let w=g(f);if(w)return{x:Math.max(0,w.x-l),y:Math.max(0,w.y-l),width:w.width+l*2,height:w.height+l*2};let v=f.firstElementChild;if(v){let h=v.getBoundingClientRect();return{x:h.x,y:h.y,width:h.width,height:h.height}}return null},me);if(!c)throw new Error("Could not determine component bounds from snapshot");let s=await o.screenshot({type:"png",clip:c});return Buffer.from(s)}finally{await o.close()}}async function j(){return Y()}async function Q(){$&&(await $.close(),$=null)}var gt=V.toString(),te=null,z=null,Ee=!1;async function ht(){if(!Ee){Ee=!0;try{let e=await Promise.resolve().then(()=>(Ce(),be));te=e.validateCodeForFile,z=e.formatValidationResult,p.debug("Code validator loaded - fix validation enabled")}catch{p.debug("Code validator not available - skipping fix validation")}}}var yt="UICOPILOT/APPLY_FIXES",St="UICOPILOT/FIX_STARTED",wt="UICOPILOT/FIX_COMPLETED",xt="UICOPILOT/FIX_FAILED",ve="UICOPILOT/ALL_FIXES_APPLIED",bt="UICOPILOT/RELOAD_REQUIRED",Ie="UICOPILOT/WORKSPACE_PATH",Ct="UICOPILOT/REQUEST_WORKSPACE_PATH",Et="UICOPILOT/DISCOVER_COMPONENT_FILES",Te="UICOPILOT/COMPONENT_FILES_DISCOVERED";async function Pe(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`],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=[],u=[];for(let l of i)try{let g=await(0,ee.glob)(l,{cwd:n,nodir:!0,ignore:["**/node_modules/**","**/dist/**","**/.storybook/**"]});g.length>0&&o.push(...g)}catch{}for(let l of a)try{let g=await(0,ee.glob)(l,{cwd:n,nodir:!0,ignore:["**/node_modules/**","**/dist/**","**/.storybook/**","**/*.stories.*","**/*.test.*"]});g.length>0&&u.push(...g)}catch{}let d=[...new Set(o)],c=[...new Set(u)],s=l=>{if(l.length===0)return;let g=l.find(h=>h.includes(`/fui-${t}/`)&&h.endsWith(".css"));if(g)return g;let w=l.find(h=>h.toLowerCase().includes(`/${t}/${t}.css`)||h.includes(`/${r}/${r}.css`));if(w)return w;let v=l.find(h=>h.toLowerCase().endsWith(`/${t}.css`)||h.endsWith(`/${r}.css`));return v||l[0]},y=l=>{if(l.length===0)return;let g=l.filter(S=>!S.includes(".stories.")&&!S.includes(".test."));if(g.length===0)return l[0];let w=g.find(S=>S.includes(`/fui-${t}/`)&&(S.endsWith(".tsx")||S.endsWith(".jsx")));if(w)return w;let v=g.find(S=>S.toLowerCase().includes(`/${t}/${t}.tsx`)||S.includes(`/${r}/${r}.tsx`));if(v)return v;let h=g.find(S=>S.toLowerCase().endsWith(`/${t}.tsx`)||S.endsWith(`/${r}.tsx`));return h||g[0]},f=s(d),m=y(c),I=[...d,...c];return p.debug(`Discovered files for "${e}":`,{cssFile:f,componentFile:m,totalMatches:I.length}),{cssFile:f,componentFile:m,allMatches:[...new Set(I)]}}var vt=100;function It(e){return new Promise(n=>setTimeout(n,e))}async function Tt(e,n){if(await ht(),!te||!z)return p.debug(`Skipping validation (validator not available) for ${n}`),{valid:!0};let t=te(e,n);if(!t.valid){let r=t.errors.map(i=>i.message).join("; ");return p.warn(`Code validation failed for ${n}:`),console.warn(z(t)),{valid:!1,error:r}}return t.warnings.length>0&&(p.warn(`Code validation warnings for ${n}:`),console.warn(z(t))),p.debug(`Validation passed for ${n}`),{valid:!0}}var Le=!1;function $e(e){if(Le)return e;Le=!0;let n=process.cwd();return p.debug("Apply fixes initialized"),p.debug("Workspace:",n),e.emit(Ie,{path:n}),e.on(Ct,()=>{p.debug("Workspace path requested by browser"),p.debug("Emitting workspace path response:",n),e.emit(Ie,{path:n})}),e.on(Et,async t=>{let{componentName:r,storyId:i}=t;p.debug(`Discovering files for component: ${r}`);try{let a=await Pe(r,n);e.emit(Te,{componentName:r,storyId:i,...a,workspacePath:n})}catch(a){p.error("File discovery error:",a),e.emit(Te,{componentName:r,storyId:i,error:a.message,allMatches:[]})}}),e.on(yt,t=>{setTimeout(async()=>{try{let{issues:r,storybookRoot:i}=t,a=i||n;i?p.debug(`Using storybookRoot from API: ${i}`):p.debug(`Using process.cwd(): ${n}`),p.debug(`Received APPLY_FIXES for ${r.length} issue(s)`);let o=new Map;async function u(s){let y=s.targetFileType||"css",f=s.targetFilePath||s.generatedFix?.filePath,m="",I=s.title?.match(/^(\w+)\s/);if(I&&(m=I[1]),!m&&f){let w=f.match(/\/(\w+)\.(?:css|tsx|jsx)$/i);w&&(m=w[1])}if(!m)return p.debug(`Could not extract component name, using provided path: ${f}`),f||null;if(!o.has(m)){let w=await Pe(m,a);o.set(m,w)}let l=o.get(m),g=y==="css"?l.cssFile:l.componentFile;return g?(p.debug(`Discovered ${y} path: ${g} (was: ${f})`),g):(p.debug(`No ${y} file discovered, using provided: ${f}`),f||null)}let d=[];for(let s of r){let{generatedFix:y}=s,f=s.targetFilePath||y?.filePath,m=await u(s)||f;p.debug("Processing issue:",{id:s.id,type:s.type,targetFileType:s.targetFileType||"css",targetPath:m,providedPath:f!==m?f:"(same)",codeLength:y?.code?.length||0}),e.emit(St,{issueId:s.id});try{if(!y||!y.code||!m)throw new Error("Missing AI-generated fix data (code or filePath)");p.debug("Code to write (first 200 chars):",y.code.substring(0,200)),p.debug(`Code length: ${y.code.length} chars`);let I=await Tt(y.code,m);if(!I.valid)throw new Error(`Code validation failed: ${I.error}. Fix was not applied to prevent breaking the file.`);let l=U.isAbsolute(m)?m:U.join(a,m);p.debug(`Writing to absolute path: ${l}`),await _e.writeFile(l,y.code,"utf-8"),await It(vt);let g={success:!0,issueId:s.id,filePath:m,timestamp:new Date};e.emit(wt,{issueId:s.id,result:g}),p.debug(`\u2713 Applied ${s.targetFileType||"css"} fix to: ${m}`),d.push(g)}catch(I){let l=I.message||"Unknown error";e.emit(xt,{issueId:s.id,error:l}),p.error(`\u2717 Error: ${l}`),d.push({success:!1,issueId:s.id,error:l,timestamp:new Date})}}let c={total:d.length,succeeded:d.filter(s=>s.success).length,failed:d.filter(s=>!s.success).length};e.emit(ve,{results:d,summary:c}),p.debug(`Completed: ${c.succeeded}/${c.total} fixes applied`),c.succeeded>0&&e.emit(bt,{message:"Fixes applied. If Storybook crashes due to HMR, please restart it.",filesChanged:d.filter(s=>s.success).map(s=>s.filePath)})}catch(r){p.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 Oe(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 j()){o.writeHead(501,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Puppeteer not installed. Run: npm install puppeteer"}));return}let c=new URL(a.url||"",`http://${a.headers.host}`).searchParams.get("storyId");if(!c){o.writeHead(400,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Missing storyId parameter"}));return}let y=`http://${a.headers.host||"localhost:6006"}/iframe.html?viewMode=story&id=${c}&globals=`;p.debug(`Taking screenshot: ${c}`);let f=await Z(y,{selector:"#storybook-root > *"});if(!f){o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Screenshot capture failed"}));return}let m=f.toString("base64");o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({screenshot:`data:image/png;base64,${m}`}))}catch(u){p.error("Screenshot error:",u.message),o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:u.message}))}}),t.middlewares.use("/__uicopilot/capture",async(a,o)=>{try{if(!await j()){o.writeHead(501,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Puppeteer not installed"}));return}let d=new URL(a.url||"",`http://${a.headers.host}`),c=d.searchParams.get("storyId");if(!c){o.writeHead(400,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Missing storyId parameter"}));return}let s=d.searchParams.get("domOnly")==="1",f=`http://${a.headers.host||"localhost:6006"}/iframe.html?viewMode=story&id=${c}&globals=`;p.debug(`Full capture${s?" (domOnly)":""}: ${c}`);let m=null;if(!s&&(m=await Z(f,{selector:"#storybook-root > *"}),!m)){o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Screenshot capture failed"}));return}let l=await(await ge()).newPage();try{await l.setCacheEnabled(!1),await l.setViewport({width:800,height:600}),await l.goto(f,{waitUntil:"load",timeout:15e3}),await l.evaluate(()=>document.fonts.ready),await l.waitForSelector("#storybook-root > *",{timeout:1e4}),await l.evaluate(()=>new Promise(w=>{let v=setTimeout(w,5e3);try{let h=window.__STORYBOOK_ADDONS_CHANNEL__;if(h){let S=()=>{clearTimeout(v),h.off("storyRendered",S),setTimeout(w,100)};h.on("storyRendered",S)}else clearTimeout(v),setTimeout(w,300)}catch{clearTimeout(v),w()}}));let g=await l.evaluate(w=>{let v=document.getElementById("storybook-root")||document.getElementById("root"),h=null;if(v)try{h=new Function("return ("+w+")")()(v)}catch{h=v.firstElementChild}let S={};if(h){let x=window.getComputedStyle(h);for(let T=0;T<x.length;T++)S[x[T]]=x.getPropertyValue(x[T])}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 E(x){return x.replace(/-([a-z])/g,(T,L)=>L.toUpperCase())}function b(x,T){if(T>4)return null;let L=x.tagName.toLowerCase();if(["script","style","link","meta","br","hr","noscript"].includes(L))return null;let M=x.className,F=typeof M=="string"?M:M?.baseVal||"",k=x.id||void 0,W=x.getAttribute("role")||void 0,G;for(let _ of Array.from(x.childNodes))if(_.nodeType===3){let P=_.textContent?.trim();if(P){G=P.length>50?P.substring(0,50)+"...":P;break}}let N=L;k?N=`${L}#${k}`:F&&(N=`${L}.${F.split(" ").filter(Boolean).join(".")}`);let X=window.getComputedStyle(x),Ne=["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"],q={};for(let _ of Ne){let P=X.getPropertyValue(_),A=E(_);P&&!C[A]?.includes(P)&&(q[A]=P)}if(L==="svg"||x.closest("svg"))for(let _ of["fill","stroke","stroke-width","viewBox","d","r","cx","cy"]){let P=x.getAttribute(_);P&&(q[E(_)]=P)}let re=[];for(let _ of Array.from(x.children)){let P=window.getComputedStyle(_);if(P.display==="none"||P.visibility==="hidden")continue;let A=b(_,T+1);A&&re.push(A)}return{selector:N,tagName:L,className:F,id:k,role:W,textContent:G,styles:q,children:re}}return{computedStyles:S,domTree:h?b(h,0):null}},gt);o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({screenshot:m?`data:image/png;base64,${m.toString("base64")}`:void 0,computedStyles:g.computedStyles,domTree:g.domTree}))}finally{await l.close()}}catch(u){p.error("Capture error:",u.message),o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:u.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 j()){o.writeHead(501,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Puppeteer not installed"}));return}let d=[];for await(let w of a)d.push(typeof w=="string"?Buffer.from(w):w);let c=JSON.parse(Buffer.concat(d).toString()),{html:s,stylesheetUrls:y,storyId:f}=c;if(!s){o.writeHead(400,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Missing html in body"}));return}let I=`http://${a.headers.host||"localhost:6006"}`;p.debug(`Taking snapshot screenshot for ${f||"unknown"}`);let l=await he(s,y||[],I,{storyId:f});if(!l){o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Snapshot screenshot failed"}));return}let g=l.toString("base64");o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({screenshot:`data:image/png;base64,${g}`}))}catch(u){p.error("Snapshot screenshot error:",u.message),o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:u.message}))}}),t.httpServer?.on("close",()=>{Q().catch(()=>{})});let r=a=>{Q().catch(()=>{}).finally(()=>{process.kill(process.pid,a)})},i=globalThis;i.__uicopilotShutdownRegistered||(i.__uicopilotShutdownRegistered=!0,process.once("SIGINT",()=>r("SIGINT")),process.once("SIGTERM",()=>r("SIGTERM")))}}),e}var R={},Pt=()=>{if(typeof R<"u"&&R.url){let e=(0,ne.fileURLToPath)(R.url),n=(0,O.dirname)(e);return(0,O.join)(n,"manager.mjs")}return(0,O.join)(__dirname,"manager.mjs")},Lt=()=>{if(typeof R<"u"&&R.url){let e=(0,ne.fileURLToPath)(R.url),n=(0,O.dirname)(e);return(0,O.join)(n,"preview.mjs")}return(0,O.join)(__dirname,"preview.mjs")};function _t(e=[]){return[...e,Pt()]}function $t(e=[]){return[...e,Lt()]}0&&(module.exports={experimental_serverChannel,managerEntries,previewAnnotations,viteFinal});
|
package/dist/preset.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var Ie=Object.defineProperty;var Te=(e,n)=>()=>(e&&(n=e(e=0)),n);var Pe=(e,n)=>{for(var t in n)Ie(e,t,{get:n[t],enumerable:!0})};var
|
|
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
|
|
3
|
-
`)}var Ye,pe=Te(()=>{"use strict";Ye=50});import{dirname as be,join as U}from"path";import{fileURLToPath as Ce}from"url";import*as xe from"fs/promises";import*as z from"path";import{glob as fe}from"glob";import{existsSync as Xe}from"fs";import{createRequire as qe}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 Le(){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 D=`[${G.NAME}]`,p={debug:(...e)=>{Le()&&console.log(D,...e)},info:(...e)=>{console.log(D,...e)},warn:(...e)=>{console.warn(D,...e)},error:(...e)=>{console.error(D,...e)}};var ze=["flex","inline-flex"],Ue=["grid","inline-grid"],Xt=[...ze,...Ue];function B(e){let o=e.ownerDocument?.defaultView;if(!o)return e.firstElementChild??e;let s=e.getBoundingClientRect(),a=d=>{let c=o.getComputedStyle(d);if(c.position==="fixed"||c.display==="none"||c.visibility==="hidden")return!0;let i=d.getBoundingClientRect();return i.width===0||i.height===0||d.children.length===0&&!(d.textContent??"").trim()},r=d=>{if(s.width===0||s.height===0)return!1;let c=d.getBoundingClientRect();return c.width>=s.width*.9&&c.height>=s.height*.9},u=e;for(let d=0;d<6;d+=1){let c=Array.from(u.children).filter(i=>!a(i));if(c.length!==1||u!==e&&!r(u))break;u=c[0]}return u===e?e.firstElementChild??e:u}var re=B.toString(),V=null,N=null,oe=!1;async function X(){if(oe)return!!V;if(oe=!0,process.env.STORYBOOK_UICOPILOT_NO_PUPPETEER==="true")return p.debug("Puppeteer disabled via STORYBOOK_UICOPILOT_NO_PUPPETEER flag"),!1;let e=qe(process.cwd()+"/");try{return V=e("puppeteer"),p.debug("Puppeteer loaded \u2014 server-side screenshots enabled"),!0}catch{}try{return V=e("puppeteer-core"),p.debug("puppeteer-core loaded \u2014 server-side screenshots enabled"),!0}catch{}return p.debug("Puppeteer not found \u2014 install puppeteer for pixel-perfect screenshots"),!1}function Ke(){let e=["/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"];for(let n of e)if(Xe(n))return n}async function ie(){if(N&&N.connected)return N;let e=Ke(),n={headless:!0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-dev-shm-usage"],...e?{executablePath:e}:{}};return N=await V.launch(n),p.debug("Headless Chrome launched for screenshots"),N}async function q(e,n){if(!await X())return null;let s=await(await ie()).newPage();try{await s.setCacheEnabled(!1),await s.setViewport({width:n?.width||800,height:n?.height||600,deviceScaleFactor:1}),await s.goto(e,{waitUntil:"networkidle2",timeout:15e3}),await s.evaluate(()=>document.fonts.ready),await s.waitForSelector("#storybook-root > *",{timeout:1e4}),await s.waitForFunction(()=>new Promise(c=>{let i=document.querySelectorAll("style").length,y=0,f=()=>{let g=document.querySelectorAll("style").length;if(g===i){if(y++,y>=3){c(!0);return}}else y=0,i=g;setTimeout(f,100)};setTimeout(f,200)}),{timeout:5e3}).catch(()=>{}),await new Promise(c=>setTimeout(c,500));let a=await s.evaluate(c=>{let i=document.querySelector("#storybook-root");if(!i)return null;let y=window.innerHeight,f=window.innerWidth,g=w=>w.setAttribute("data-uic-drilled",""),v=()=>{let w=document.createElement("style");w.id="uic-drilled-bg-reset",w.textContent="[data-uic-drilled] { background: transparent !important; border-color: transparent !important; box-shadow: none !important; }",document.head.appendChild(w),document.body.offsetHeight};try{let E=new Function("return ("+c+")")()(i),b=E?.getBoundingClientRect(),T=!!b&&b.width>=f*.9&&b.height>=y*.9;if(E&&E!==i&&b&&b.width>0&&b.height>0&&!T){for(let C=E.parentElement;C&&C!==i;C=C.parentElement)g(C);return v(),{top:b.top,bottom:b.bottom,left:b.left,right:b.right}}}catch{}let l=1/0,h=0,x=1/0,I=0,S=!1;function m(w){for(let E of Array.from(w.children)){let b=window.getComputedStyle(E);if(b.display==="none"||b.visibility==="hidden"||b.position==="fixed"||b.position==="absolute")continue;let T=E.getBoundingClientRect();if(T.height<=0||T.width<=0)continue;if((T.width>=f*.9||T.height>=y*.9)&&E.children.length>0){E.setAttribute("data-uic-drilled",""),m(E);continue}if(E.children.length===1){let L=b.backgroundColor,$=L==="rgba(0, 0, 0, 0)"||L==="transparent"||L==="",R=b.borderStyle!=="none"&&b.borderWidth!=="0px",O=b.boxShadow!=="none",M=!$||R||O,F=E.children[0].getBoundingClientRect(),k=F.width>=T.width*.95&&F.height>=T.height*.95;if(!M||k){E.setAttribute("data-uic-drilled",""),m(E);continue}}l=Math.min(l,T.top),h=Math.max(h,T.bottom),x=Math.min(x,T.left),I=Math.max(I,T.right),S=!0}}return m(i),S?(v(),{top:l,bottom:h,left:x,right:I}):null},re);await s.evaluate(()=>new Promise(c=>requestAnimationFrame(()=>c())));let r=4,u=a?{x:Math.max(0,a.left-r),y:Math.max(0,a.top-r),width:Math.min(a.right-a.left+r*2,800),height:Math.min(a.bottom-a.top+r*2,600)}:void 0,d=await s.screenshot({type:"png",omitBackground:!0,...u?{clip:u}:{fullPage:!1}});return Buffer.from(d)}finally{await s.close()}}async function se(e,n,t,o){if(!await X())return null;let r=await(await ie()).newPage();try{await r.setCacheEnabled(!1),await r.setViewport({width:o?.width||800,height:o?.height||600,deviceScaleFactor:1});let u=o?.storyId||"",d=`${t}/iframe.html?viewMode=story&id=${u}&globals=`;await r.goto(d,{waitUntil:"load",timeout:15e3}),await r.waitForSelector("#storybook-root > *",{timeout:1e4}),await r.evaluate(y=>{let f=document.getElementById("storybook-root");f&&(f.innerHTML=y)},e),await r.evaluate(()=>document.fonts.ready),await new Promise(y=>setTimeout(y,500));let c=await r.evaluate(y=>{let f=document.querySelector("#storybook-root");if(!f)return null;let g=window.innerWidth,v=window.innerHeight,l=8;try{let m=new Function("return ("+y+")")()(f),w=m?.getBoundingClientRect(),E=!!w&&w.width>=g*.9&&w.height>=v*.9;if(m&&m!==f&&w&&w.width>0&&w.height>0&&!E)return{x:Math.max(0,w.x-l),y:Math.max(0,w.y-l),width:w.width+l*2,height:w.height+l*2}}catch{}function h(S){let m=S.getBoundingClientRect();if(m.width===0||m.height===0)return null;if(m.width<g*.8&&m.height>0)return m;for(let w of Array.from(S.children)){let E=window.getComputedStyle(w);if(E.position==="fixed"||E.position==="absolute"||E.display==="none"||E.visibility==="hidden")continue;let b=h(w);if(b)return b}return null}let x=h(f);if(x)return{x:Math.max(0,x.x-l),y:Math.max(0,x.y-l),width:x.width+l*2,height:x.height+l*2};let I=f.firstElementChild;if(I){let S=I.getBoundingClientRect();return{x:S.x,y:S.y,width:S.width,height:S.height}}return null},re);if(!c)throw new Error("Could not determine component bounds from snapshot");let i=await r.screenshot({type:"png",clip:c});return Buffer.from(i)}finally{await r.close()}}async function H(){return X()}async function K(){N&&(await N.close(),N=null)}var it=B.toString(),Y=null,j=null,me=!1;async function st(){if(!me){me=!0;try{let e=await Promise.resolve().then(()=>(pe(),de));Y=e.validateCodeForFile,j=e.formatValidationResult,p.debug("Code validator loaded - fix validation enabled")}catch{p.debug("Code validator not available - skipping fix validation")}}}var at="UICOPILOT/APPLY_FIXES",ct="UICOPILOT/FIX_STARTED",lt="UICOPILOT/FIX_COMPLETED",ut="UICOPILOT/FIX_FAILED",ge="UICOPILOT/ALL_FIXES_APPLIED",dt="UICOPILOT/RELOAD_REQUIRED",he="UICOPILOT/WORKSPACE_PATH",pt="UICOPILOT/REQUEST_WORKSPACE_PATH",ft="UICOPILOT/DISCOVER_COMPONENT_FILES",ye="UICOPILOT/COMPONENT_FILES_DISCOVERED";async function Se(e,n){let t=e.toLowerCase(),o=e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),s=[`src/**/fui-${t}/fui-${t}.css`,`src/**/fui-${t}/*.css`,`src/**/${t}/${t}.css`,`src/**/${o}/${o}.css`,`src/**/*${t}*.css`,`src/**/*${o}*.css`,`styles/**/*${t}*.css`],a=[`src/**/fui-${t}/fui-${t}.tsx`,`src/**/fui-${t}/*.tsx`,`src/**/${t}/${t}.tsx`,`src/**/${o}/${o}.tsx`,`src/**/*${o}*.tsx`,`src/**/*${o}*.jsx`],r=[],u=[];for(let l of s)try{let h=await fe(l,{cwd:n,nodir:!0,ignore:["**/node_modules/**","**/dist/**","**/.storybook/**"]});h.length>0&&r.push(...h)}catch{}for(let l of a)try{let h=await fe(l,{cwd:n,nodir:!0,ignore:["**/node_modules/**","**/dist/**","**/.storybook/**","**/*.stories.*","**/*.test.*"]});h.length>0&&u.push(...h)}catch{}let d=[...new Set(r)],c=[...new Set(u)],i=l=>{if(l.length===0)return;let h=l.find(S=>S.includes(`/fui-${t}/`)&&S.endsWith(".css"));if(h)return h;let x=l.find(S=>S.toLowerCase().includes(`/${t}/${t}.css`)||S.includes(`/${o}/${o}.css`));if(x)return x;let I=l.find(S=>S.toLowerCase().endsWith(`/${t}.css`)||S.endsWith(`/${o}.css`));return I||l[0]},y=l=>{if(l.length===0)return;let h=l.filter(m=>!m.includes(".stories.")&&!m.includes(".test."));if(h.length===0)return l[0];let x=h.find(m=>m.includes(`/fui-${t}/`)&&(m.endsWith(".tsx")||m.endsWith(".jsx")));if(x)return x;let I=h.find(m=>m.toLowerCase().includes(`/${t}/${t}.tsx`)||m.includes(`/${o}/${o}.tsx`));if(I)return I;let S=h.find(m=>m.toLowerCase().endsWith(`/${t}.tsx`)||m.endsWith(`/${o}.tsx`));return S||h[0]},f=i(d),g=y(c),v=[...d,...c];return p.debug(`Discovered files for "${e}":`,{cssFile:f,componentFile:g,totalMatches:v.length}),{cssFile:f,componentFile:g,allMatches:[...new Set(v)]}}var mt=100;function gt(e){return new Promise(n=>setTimeout(n,e))}async function ht(e,n){if(await st(),!Y||!j)return p.debug(`Skipping validation (validator not available) for ${n}`),{valid:!0};let t=Y(e,n);if(!t.valid){let o=t.errors.map(s=>s.message).join("; ");return p.warn(`Code validation failed for ${n}:`),console.warn(j(t)),{valid:!1,error:o}}return t.warnings.length>0&&(p.warn(`Code validation warnings for ${n}:`),console.warn(j(t))),p.debug(`Validation passed for ${n}`),{valid:!0}}var we=!1;function yt(e){if(we)return e;we=!0;let n=process.cwd();return p.debug("Apply fixes initialized"),p.debug("Workspace:",n),e.emit(he,{path:n}),e.on(pt,()=>{p.debug("Workspace path requested by browser"),p.debug("Emitting workspace path response:",n),e.emit(he,{path:n})}),e.on(ft,async t=>{let{componentName:o,storyId:s}=t;p.debug(`Discovering files for component: ${o}`);try{let a=await Se(o,n);e.emit(ye,{componentName:o,storyId:s,...a,workspacePath:n})}catch(a){p.error("File discovery error:",a),e.emit(ye,{componentName:o,storyId:s,error:a.message,allMatches:[]})}}),e.on(at,t=>{setTimeout(async()=>{try{let{issues:o,storybookRoot:s}=t,a=s||n;s?p.debug(`Using storybookRoot from API: ${s}`):p.debug(`Using process.cwd(): ${n}`),p.debug(`Received APPLY_FIXES for ${o.length} issue(s)`);let r=new Map;async function u(i){let y=i.targetFileType||"css",f=i.targetFilePath||i.generatedFix?.filePath,g="",v=i.title?.match(/^(\w+)\s/);if(v&&(g=v[1]),!g&&f){let x=f.match(/\/(\w+)\.(?:css|tsx|jsx)$/i);x&&(g=x[1])}if(!g)return p.debug(`Could not extract component name, using provided path: ${f}`),f||null;if(!r.has(g)){let x=await Se(g,a);r.set(g,x)}let l=r.get(g),h=y==="css"?l.cssFile:l.componentFile;return h?(p.debug(`Discovered ${y} path: ${h} (was: ${f})`),h):(p.debug(`No ${y} file discovered, using provided: ${f}`),f||null)}let d=[];for(let i of o){let{generatedFix:y}=i,f=i.targetFilePath||y?.filePath,g=await u(i)||f;p.debug("Processing issue:",{id:i.id,type:i.type,targetFileType:i.targetFileType||"css",targetPath:g,providedPath:f!==g?f:"(same)",codeLength:y?.code?.length||0}),e.emit(ct,{issueId:i.id});try{if(!y||!y.code||!g)throw new Error("Missing AI-generated fix data (code or filePath)");p.debug("Code to write (first 200 chars):",y.code.substring(0,200)),p.debug(`Code length: ${y.code.length} chars`);let v=await ht(y.code,g);if(!v.valid)throw new Error(`Code validation failed: ${v.error}. Fix was not applied to prevent breaking the file.`);let l=z.isAbsolute(g)?g:z.join(a,g);p.debug(`Writing to absolute path: ${l}`),await xe.writeFile(l,y.code,"utf-8"),await gt(mt);let h={success:!0,issueId:i.id,filePath:g,timestamp:new Date};e.emit(lt,{issueId:i.id,result:h}),p.debug(`\u2713 Applied ${i.targetFileType||"css"} fix to: ${g}`),d.push(h)}catch(v){let l=v.message||"Unknown error";e.emit(ut,{issueId:i.id,error:l}),p.error(`\u2717 Error: ${l}`),d.push({success:!1,issueId:i.id,error:l,timestamp:new Date})}}let c={total:d.length,succeeded:d.filter(i=>i.success).length,failed:d.filter(i=>!i.success).length};e.emit(ge,{results:d,summary:c}),p.debug(`Completed: ${c.succeeded}/${c.total} fixes applied`),c.succeeded>0&&e.emit(dt,{message:"Fixes applied. If Storybook crashes due to HMR, please restart it.",filesChanged:d.filter(i=>i.success).map(i=>i.filePath)})}catch(o){p.error("Fatal error during fix application:",o),e.emit(ge,{results:[],summary:{total:t.issues?.length||0,succeeded:0,failed:t.issues?.length||0}})}},0)}),e}function St(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,r)=>{r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({ok:!0,workspacePath:n}))}),t.middlewares.use("/__uicopilot/screenshot",async(a,r)=>{try{if(!await H()){r.writeHead(501,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Puppeteer not installed. Run: npm install puppeteer"}));return}let c=new URL(a.url||"",`http://${a.headers.host}`).searchParams.get("storyId");if(!c){r.writeHead(400,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Missing storyId parameter"}));return}let y=`http://${a.headers.host||"localhost:6006"}/iframe.html?viewMode=story&id=${c}&globals=`;p.debug(`Taking screenshot: ${c}`);let f=await q(y,{selector:"#storybook-root > *"});if(!f){r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Screenshot capture failed"}));return}let g=f.toString("base64");r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({screenshot:`data:image/png;base64,${g}`}))}catch(u){p.error("Screenshot error:",u.message),r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:u.message}))}}),t.middlewares.use("/__uicopilot/capture",async(a,r)=>{try{if(!await H()){r.writeHead(501,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Puppeteer not installed"}));return}let c=new URL(a.url||"",`http://${a.headers.host}`).searchParams.get("storyId");if(!c){r.writeHead(400,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Missing storyId parameter"}));return}let y=`http://${a.headers.host||"localhost:6006"}/iframe.html?viewMode=story&id=${c}&globals=`;p.debug(`Full capture: ${c}`);let f=await q(y,{selector:"#storybook-root > *"});if(!f){r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Screenshot capture failed"}));return}let g;try{g=(await import("puppeteer")).default}catch{g=(await import("puppeteer-core")).default}let v=await g.launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox"]}),l=await v.newPage();try{await l.setCacheEnabled(!1),await l.setViewport({width:800,height:600}),await l.goto(y,{waitUntil:"networkidle2",timeout:15e3}),await l.evaluate(()=>document.fonts.ready),await l.waitForSelector("#storybook-root > *",{timeout:1e4}),await l.evaluate(()=>new Promise(I=>{let S=setTimeout(I,5e3);try{let m=window.__STORYBOOK_ADDONS_CHANNEL__;if(m){let w=()=>{clearTimeout(S),m.off("storyRendered",w),setTimeout(I,100)};m.on("storyRendered",w)}else clearTimeout(S),setTimeout(I,300)}catch{clearTimeout(S),I()}}));let h=await l.evaluate(I=>{let S=document.getElementById("storybook-root")||document.getElementById("root"),m=null;if(S)try{m=new Function("return ("+I+")")()(S)}catch{m=S.firstElementChild}let w={};if(m){let C=window.getComputedStyle(m);for(let L=0;L<C.length;L++)w[C[L]]=C.getPropertyValue(C[L])}let E={backgroundColor:["transparent","rgba(0, 0, 0, 0)"],border:["none","0px none","0px none rgb(0, 0, 0)"],borderRadius:["0px"],boxShadow:["none"],opacity:["1"]};function b(C){return C.replace(/-([a-z])/g,(L,$)=>$.toUpperCase())}function T(C,L){if(L>4)return null;let $=C.tagName.toLowerCase();if(["script","style","link","meta","br","hr","noscript"].includes($))return null;let R=C.className,O=typeof R=="string"?R:R?.baseVal||"",M=C.id||void 0,J=C.getAttribute("role")||void 0,F;for(let _ of Array.from(C.childNodes))if(_.nodeType===3){let P=_.textContent?.trim();if(P){F=P.length>50?P.substring(0,50)+"...":P;break}}let k=$;M?k=`${$}#${M}`:O&&(k=`${$}.${O.split(" ").filter(Boolean).join(".")}`);let Ee=window.getComputedStyle(C),ve=["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"],W={};for(let _ of ve){let P=Ee.getPropertyValue(_),A=b(_);P&&!E[A]?.includes(P)&&(W[A]=P)}if($==="svg"||C.closest("svg"))for(let _ of["fill","stroke","stroke-width","viewBox","d","r","cx","cy"]){let P=C.getAttribute(_);P&&(W[b(_)]=P)}let Z=[];for(let _ of Array.from(C.children)){let P=window.getComputedStyle(_);if(P.display==="none"||P.visibility==="hidden")continue;let A=T(_,L+1);A&&Z.push(A)}return{selector:k,tagName:$,className:O,id:M,role:J,textContent:F,styles:W,children:Z}}return{computedStyles:w,domTree:m?T(m,0):null}},it),x=f.toString("base64");r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({screenshot:`data:image/png;base64,${x}`,computedStyles:h.computedStyles,domTree:h.domTree}))}finally{await l.close(),await v.close()}}catch(u){p.error("Capture error:",u.message),r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:u.message}))}}),t.middlewares.use("/__uicopilot/screenshot-snapshot",async(a,r)=>{if(a.method!=="POST"){r.writeHead(405,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"POST required"}));return}try{if(!await H()){r.writeHead(501,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Puppeteer not installed"}));return}let d=[];for await(let x of a)d.push(typeof x=="string"?Buffer.from(x):x);let c=JSON.parse(Buffer.concat(d).toString()),{html:i,stylesheetUrls:y,storyId:f}=c;if(!i){r.writeHead(400,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Missing html in body"}));return}let v=`http://${a.headers.host||"localhost:6006"}`;p.debug(`Taking snapshot screenshot for ${f||"unknown"}`);let l=await se(i,y||[],v,{storyId:f});if(!l){r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Snapshot screenshot failed"}));return}let h=l.toString("base64");r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({screenshot:`data:image/png;base64,${h}`}))}catch(u){p.error("Snapshot screenshot error:",u.message),r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:u.message}))}}),t.httpServer?.on("close",()=>{K().catch(()=>{})});let o=a=>{K().catch(()=>{}).finally(()=>{process.kill(process.pid,a)})},s=globalThis;s.__uicopilotShutdownRegistered||(s.__uicopilotShutdownRegistered=!0,process.once("SIGINT",()=>o("SIGINT")),process.once("SIGTERM",()=>o("SIGTERM")))}}),e}var wt=()=>{if(typeof import.meta<"u"&&import.meta.url){let e=Ce(import.meta.url),n=be(e);return U(n,"manager.mjs")}return U(__dirname,"manager.mjs")},xt=()=>{if(typeof import.meta<"u"&&import.meta.url){let e=Ce(import.meta.url),n=be(e);return U(n,"preview.mjs")}return U(__dirname,"preview.mjs")};function Do(e=[]){return[...e,wt()]}function Bo(e=[]){return[...e,xt()]}export{yt as experimental_serverChannel,Do as managerEntries,Bo as previewAnnotations,St as viteFinal};
|
|
1
|
+
var Ie=Object.defineProperty;var Te=(e,n)=>()=>(e&&(n=e(e=0)),n);var Pe=(e,n)=>{for(var t in n)Ie(e,t,{get:n[t],enumerable:!0})};var pe={};Pe(pe,{detectFileType:()=>le,formatValidationResult:()=>ot,isValidCode:()=>rt,validateCode:()=>ue,validateCodeForFile:()=>de});function Je(e,n={}){let t=n.minLength??Ye;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 Ze(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 Qe(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 et(e){let n={"{":"}","[":"]","(":")"},t=[],r=!1,s="",a=!1;for(let o=0;o<e.length;o++){let u=e[o],d=e[o-1];if((u==='"'||u==="'"||u==="`")&&d!=="\\"){r?u===s&&(r=!1,a=!1):(r=!0,s=u,u==="`"&&(a=!0));continue}if(!r){if(n[u])t.push(n[u]);else if(Object.values(n).includes(u)&&t.pop()!==u)return{code:"UNBALANCED_BRACES",message:`Unbalanced braces/brackets detected. Found unexpected '${u}'.`,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 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 u=[{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:d,message:c}of u)d.test(e)&&t.push({code:"TSX_INCOMPLETE",message:c,severity:"error"});return{errors:t,warnings:r}}function tt(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 le(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 ue(e,n,t={}){let r={valid:!0,fileType:n,errors:[],warnings:[]},s=Je(e,t);s&&r.errors.push(s);let a=Ze(e);a&&r.errors.push(a);let o=Qe(e);o&&r.errors.push(o);let u=et(e);switch(u&&(t.strict?r.errors.push({...u,severity:"error"}):r.warnings.push(u)),n){case"stories":{let{errors:d,warnings:c}=nt(e,t);r.errors.push(...d),r.warnings.push(...c);break}case"tsx":case"jsx":{let{errors:d,warnings:c}=ce(e,t);r.errors.push(...d),r.warnings.push(...c);break}case"css":case"scss":case"less":{let{errors:d,warnings:c}=tt(e,t);r.errors.push(...d),r.warnings.push(...c);break}case"ts":case"js":{let{errors:d,warnings:c}=ce(e,t);r.errors.push(...d),r.warnings.push(...c.filter(i=>!i.code.includes("JSX")));break}default:break}return r.valid=r.errors.length===0,r}function de(e,n,t={}){let r=le(n);return ue(e,r,t)}function rt(e,n,t={}){return de(e,n,t).valid}function ot(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 Ye,fe=Te(()=>{"use strict";Ye=50});import{dirname as Ce,join as j}from"path";import{fileURLToPath as Ee}from"url";import*as be from"fs/promises";import*as H from"path";import{glob as me}from"glob";import{existsSync as Xe}from"fs";import{createRequire as qe}from"module";var X={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 Le(){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 k=`[${X.NAME}]`,p={debug:(...e)=>{Le()&&console.log(k,...e)},info:(...e)=>{console.log(k,...e)},warn:(...e)=>{console.warn(k,...e)},error:(...e)=>{console.error(k,...e)}};var ze=["flex","inline-flex"],Ue=["grid","inline-grid"],Xt=[...ze,...Ue];function A(e){let r=e.ownerDocument?.defaultView;if(!r)return e.firstElementChild??e;let s=e.getBoundingClientRect(),a=d=>{let c=r.getComputedStyle(d);if(c.position==="fixed"||c.display==="none"||c.visibility==="hidden")return!0;let i=d.getBoundingClientRect();return i.width===0||i.height===0||d.children.length===0&&!(d.textContent??"").trim()},o=d=>{if(s.width===0||s.height===0)return!1;let c=d.getBoundingClientRect();return c.width>=s.width*.9&&c.height>=s.height*.9},u=e;for(let d=0;d<6;d+=1){let c=Array.from(u.children).filter(i=>!a(i));if(c.length!==1||u!==e&&!o(u))break;u=c[0]}return u===e?e.firstElementChild??e:u}var ie=A.toString(),D=null,$=null,oe=!1;async function q(){if(oe)return!!D;if(oe=!0,process.env.STORYBOOK_UICOPILOT_NO_PUPPETEER==="true")return p.debug("Puppeteer disabled via STORYBOOK_UICOPILOT_NO_PUPPETEER flag"),!1;let e=qe(process.cwd()+"/");try{return D=e("puppeteer"),p.debug("Puppeteer loaded \u2014 server-side screenshots enabled"),!0}catch{}try{return D=e("puppeteer-core"),p.debug("puppeteer-core loaded \u2014 server-side screenshots enabled"),!0}catch{}return p.debug("Puppeteer not found \u2014 install puppeteer for pixel-perfect screenshots"),!1}function Ke(){let e=["/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"];for(let n of e)if(Xe(n))return n}async function se(){return K()}async function K(){if($&&$.connected)return $;let e=Ke(),n={headless:!0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-dev-shm-usage"],...e?{executablePath:e}:{}};return $=await D.launch(n),p.debug("Headless Chrome launched for screenshots"),$}async function Y(e,n){if(!await q())return null;let s=await(await K()).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(c=>{let i=document.querySelectorAll("style").length,y=0,f=()=>{let m=document.querySelectorAll("style").length;if(m===i){if(y++,y>=3){c(!0);return}}else y=0,i=m;setTimeout(f,100)};setTimeout(f,200)}),{timeout:5e3}).catch(()=>{}),await new Promise(c=>setTimeout(c,500));let a=await s.evaluate(c=>{let i=document.querySelector("#storybook-root");if(!i)return null;let y=window.innerHeight,f=window.innerWidth,m=C=>C.setAttribute("data-uic-drilled",""),I=()=>{let C=document.createElement("style");C.id="uic-drilled-bg-reset",C.textContent="[data-uic-drilled] { background: transparent !important; border-color: transparent !important; box-shadow: none !important; }",document.head.appendChild(C),document.body.offsetHeight};try{let E=new Function("return ("+c+")")()(i),b=E?.getBoundingClientRect(),x=!!b&&b.width>=f*.9&&b.height>=y*.9;if(E&&E!==i&&b&&b.width>0&&b.height>0&&!x){for(let T=E.parentElement;T&&T!==i;T=T.parentElement)m(T);return I(),{top:b.top,bottom:b.bottom,left:b.left,right:b.right}}}catch{}let l=1/0,g=0,w=1/0,v=0,h=!1;function S(C){for(let E of Array.from(C.children)){let b=window.getComputedStyle(E);if(b.display==="none"||b.visibility==="hidden"||b.position==="fixed"||b.position==="absolute")continue;let x=E.getBoundingClientRect();if(x.height<=0||x.width<=0)continue;if((x.width>=f*.9||x.height>=y*.9)&&E.children.length>0){E.setAttribute("data-uic-drilled",""),S(E);continue}if(E.children.length===1){let L=b.backgroundColor,N=L==="rgba(0, 0, 0, 0)"||L==="transparent"||L==="",R=b.borderStyle!=="none"&&b.borderWidth!=="0px",M=b.boxShadow!=="none",z=!N||R||M,O=E.children[0].getBoundingClientRect(),W=O.width>=x.width*.95&&O.height>=x.height*.95;if(!z||W){E.setAttribute("data-uic-drilled",""),S(E);continue}}l=Math.min(l,x.top),g=Math.max(g,x.bottom),w=Math.min(w,x.left),v=Math.max(v,x.right),h=!0}}return S(i),h?(I(),{top:l,bottom:g,left:w,right:v}):null},ie);await s.evaluate(()=>new Promise(c=>requestAnimationFrame(()=>c())));let o=4,u=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,d=await s.screenshot({type:"png",omitBackground:!0,...u?{clip:u}:{fullPage:!1}});return Buffer.from(d)}finally{await s.close()}}async function ae(e,n,t,r){if(!await q())return null;let o=await(await K()).newPage();try{await o.setCacheEnabled(!1),await o.setViewport({width:r?.width||800,height:r?.height||600,deviceScaleFactor:1});let u=r?.storyId||"",d=`${t}/iframe.html?viewMode=story&id=${u}&globals=`;await o.goto(d,{waitUntil:"load",timeout:15e3}),await o.waitForSelector("#storybook-root > *",{timeout:1e4}),await o.evaluate(y=>{let f=document.getElementById("storybook-root");f&&(f.innerHTML=y)},e),await o.evaluate(()=>document.fonts.ready),await new Promise(y=>setTimeout(y,500));let c=await o.evaluate(y=>{let f=document.querySelector("#storybook-root");if(!f)return null;let m=window.innerWidth,I=window.innerHeight,l=8;try{let S=new Function("return ("+y+")")()(f),C=S?.getBoundingClientRect(),E=!!C&&C.width>=m*.9&&C.height>=I*.9;if(S&&S!==f&&C&&C.width>0&&C.height>0&&!E)return{x:Math.max(0,C.x-l),y:Math.max(0,C.y-l),width:C.width+l*2,height:C.height+l*2}}catch{}function g(h){let S=h.getBoundingClientRect();if(S.width===0||S.height===0)return null;if(S.width<m*.8&&S.height>0)return S;for(let C of Array.from(h.children)){let E=window.getComputedStyle(C);if(E.position==="fixed"||E.position==="absolute"||E.display==="none"||E.visibility==="hidden")continue;let b=g(C);if(b)return b}return null}let w=g(f);if(w)return{x:Math.max(0,w.x-l),y:Math.max(0,w.y-l),width:w.width+l*2,height:w.height+l*2};let v=f.firstElementChild;if(v){let h=v.getBoundingClientRect();return{x:h.x,y:h.y,width:h.width,height:h.height}}return null},ie);if(!c)throw new Error("Could not determine component bounds from snapshot");let i=await o.screenshot({type:"png",clip:c});return Buffer.from(i)}finally{await o.close()}}async function B(){return q()}async function J(){$&&(await $.close(),$=null)}var it=A.toString(),Z=null,V=null,ge=!1;async function st(){if(!ge){ge=!0;try{let e=await Promise.resolve().then(()=>(fe(),pe));Z=e.validateCodeForFile,V=e.formatValidationResult,p.debug("Code validator loaded - fix validation enabled")}catch{p.debug("Code validator not available - skipping fix validation")}}}var at="UICOPILOT/APPLY_FIXES",ct="UICOPILOT/FIX_STARTED",lt="UICOPILOT/FIX_COMPLETED",ut="UICOPILOT/FIX_FAILED",he="UICOPILOT/ALL_FIXES_APPLIED",dt="UICOPILOT/RELOAD_REQUIRED",ye="UICOPILOT/WORKSPACE_PATH",pt="UICOPILOT/REQUEST_WORKSPACE_PATH",ft="UICOPILOT/DISCOVER_COMPONENT_FILES",Se="UICOPILOT/COMPONENT_FILES_DISCOVERED";async function we(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=[],u=[];for(let l of s)try{let g=await me(l,{cwd:n,nodir:!0,ignore:["**/node_modules/**","**/dist/**","**/.storybook/**"]});g.length>0&&o.push(...g)}catch{}for(let l of a)try{let g=await me(l,{cwd:n,nodir:!0,ignore:["**/node_modules/**","**/dist/**","**/.storybook/**","**/*.stories.*","**/*.test.*"]});g.length>0&&u.push(...g)}catch{}let d=[...new Set(o)],c=[...new Set(u)],i=l=>{if(l.length===0)return;let g=l.find(h=>h.includes(`/fui-${t}/`)&&h.endsWith(".css"));if(g)return g;let w=l.find(h=>h.toLowerCase().includes(`/${t}/${t}.css`)||h.includes(`/${r}/${r}.css`));if(w)return w;let v=l.find(h=>h.toLowerCase().endsWith(`/${t}.css`)||h.endsWith(`/${r}.css`));return v||l[0]},y=l=>{if(l.length===0)return;let g=l.filter(S=>!S.includes(".stories.")&&!S.includes(".test."));if(g.length===0)return l[0];let w=g.find(S=>S.includes(`/fui-${t}/`)&&(S.endsWith(".tsx")||S.endsWith(".jsx")));if(w)return w;let v=g.find(S=>S.toLowerCase().includes(`/${t}/${t}.tsx`)||S.includes(`/${r}/${r}.tsx`));if(v)return v;let h=g.find(S=>S.toLowerCase().endsWith(`/${t}.tsx`)||S.endsWith(`/${r}.tsx`));return h||g[0]},f=i(d),m=y(c),I=[...d,...c];return p.debug(`Discovered files for "${e}":`,{cssFile:f,componentFile:m,totalMatches:I.length}),{cssFile:f,componentFile:m,allMatches:[...new Set(I)]}}var mt=100;function gt(e){return new Promise(n=>setTimeout(n,e))}async function ht(e,n){if(await st(),!Z||!V)return p.debug(`Skipping validation (validator not available) for ${n}`),{valid:!0};let t=Z(e,n);if(!t.valid){let r=t.errors.map(s=>s.message).join("; ");return p.warn(`Code validation failed for ${n}:`),console.warn(V(t)),{valid:!1,error:r}}return t.warnings.length>0&&(p.warn(`Code validation warnings for ${n}:`),console.warn(V(t))),p.debug(`Validation passed for ${n}`),{valid:!0}}var xe=!1;function yt(e){if(xe)return e;xe=!0;let n=process.cwd();return p.debug("Apply fixes initialized"),p.debug("Workspace:",n),e.emit(ye,{path:n}),e.on(pt,()=>{p.debug("Workspace path requested by browser"),p.debug("Emitting workspace path response:",n),e.emit(ye,{path:n})}),e.on(ft,async t=>{let{componentName:r,storyId:s}=t;p.debug(`Discovering files for component: ${r}`);try{let a=await we(r,n);e.emit(Se,{componentName:r,storyId:s,...a,workspacePath:n})}catch(a){p.error("File discovery error:",a),e.emit(Se,{componentName:r,storyId:s,error:a.message,allMatches:[]})}}),e.on(at,t=>{setTimeout(async()=>{try{let{issues:r,storybookRoot:s}=t,a=s||n;s?p.debug(`Using storybookRoot from API: ${s}`):p.debug(`Using process.cwd(): ${n}`),p.debug(`Received APPLY_FIXES for ${r.length} issue(s)`);let o=new Map;async function u(i){let y=i.targetFileType||"css",f=i.targetFilePath||i.generatedFix?.filePath,m="",I=i.title?.match(/^(\w+)\s/);if(I&&(m=I[1]),!m&&f){let w=f.match(/\/(\w+)\.(?:css|tsx|jsx)$/i);w&&(m=w[1])}if(!m)return p.debug(`Could not extract component name, using provided path: ${f}`),f||null;if(!o.has(m)){let w=await we(m,a);o.set(m,w)}let l=o.get(m),g=y==="css"?l.cssFile:l.componentFile;return g?(p.debug(`Discovered ${y} path: ${g} (was: ${f})`),g):(p.debug(`No ${y} file discovered, using provided: ${f}`),f||null)}let d=[];for(let i of r){let{generatedFix:y}=i,f=i.targetFilePath||y?.filePath,m=await u(i)||f;p.debug("Processing issue:",{id:i.id,type:i.type,targetFileType:i.targetFileType||"css",targetPath:m,providedPath:f!==m?f:"(same)",codeLength:y?.code?.length||0}),e.emit(ct,{issueId:i.id});try{if(!y||!y.code||!m)throw new Error("Missing AI-generated fix data (code or filePath)");p.debug("Code to write (first 200 chars):",y.code.substring(0,200)),p.debug(`Code length: ${y.code.length} chars`);let I=await ht(y.code,m);if(!I.valid)throw new Error(`Code validation failed: ${I.error}. Fix was not applied to prevent breaking the file.`);let l=H.isAbsolute(m)?m:H.join(a,m);p.debug(`Writing to absolute path: ${l}`),await be.writeFile(l,y.code,"utf-8"),await gt(mt);let g={success:!0,issueId:i.id,filePath:m,timestamp:new Date};e.emit(lt,{issueId:i.id,result:g}),p.debug(`\u2713 Applied ${i.targetFileType||"css"} fix to: ${m}`),d.push(g)}catch(I){let l=I.message||"Unknown error";e.emit(ut,{issueId:i.id,error:l}),p.error(`\u2717 Error: ${l}`),d.push({success:!1,issueId:i.id,error:l,timestamp:new Date})}}let c={total:d.length,succeeded:d.filter(i=>i.success).length,failed:d.filter(i=>!i.success).length};e.emit(he,{results:d,summary:c}),p.debug(`Completed: ${c.succeeded}/${c.total} fixes applied`),c.succeeded>0&&e.emit(dt,{message:"Fixes applied. If Storybook crashes due to HMR, please restart it.",filesChanged:d.filter(i=>i.success).map(i=>i.filePath)})}catch(r){p.error("Fatal error during fix application:",r),e.emit(he,{results:[],summary:{total:t.issues?.length||0,succeeded:0,failed:t.issues?.length||0}})}},0)}),e}function St(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 B()){o.writeHead(501,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Puppeteer not installed. Run: npm install puppeteer"}));return}let c=new URL(a.url||"",`http://${a.headers.host}`).searchParams.get("storyId");if(!c){o.writeHead(400,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Missing storyId parameter"}));return}let y=`http://${a.headers.host||"localhost:6006"}/iframe.html?viewMode=story&id=${c}&globals=`;p.debug(`Taking screenshot: ${c}`);let f=await Y(y,{selector:"#storybook-root > *"});if(!f){o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Screenshot capture failed"}));return}let m=f.toString("base64");o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({screenshot:`data:image/png;base64,${m}`}))}catch(u){p.error("Screenshot error:",u.message),o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:u.message}))}}),t.middlewares.use("/__uicopilot/capture",async(a,o)=>{try{if(!await B()){o.writeHead(501,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Puppeteer not installed"}));return}let d=new URL(a.url||"",`http://${a.headers.host}`),c=d.searchParams.get("storyId");if(!c){o.writeHead(400,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Missing storyId parameter"}));return}let i=d.searchParams.get("domOnly")==="1",f=`http://${a.headers.host||"localhost:6006"}/iframe.html?viewMode=story&id=${c}&globals=`;p.debug(`Full capture${i?" (domOnly)":""}: ${c}`);let m=null;if(!i&&(m=await Y(f,{selector:"#storybook-root > *"}),!m)){o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Screenshot capture failed"}));return}let l=await(await se()).newPage();try{await l.setCacheEnabled(!1),await l.setViewport({width:800,height:600}),await l.goto(f,{waitUntil:"load",timeout:15e3}),await l.evaluate(()=>document.fonts.ready),await l.waitForSelector("#storybook-root > *",{timeout:1e4}),await l.evaluate(()=>new Promise(w=>{let v=setTimeout(w,5e3);try{let h=window.__STORYBOOK_ADDONS_CHANNEL__;if(h){let S=()=>{clearTimeout(v),h.off("storyRendered",S),setTimeout(w,100)};h.on("storyRendered",S)}else clearTimeout(v),setTimeout(w,300)}catch{clearTimeout(v),w()}}));let g=await l.evaluate(w=>{let v=document.getElementById("storybook-root")||document.getElementById("root"),h=null;if(v)try{h=new Function("return ("+w+")")()(v)}catch{h=v.firstElementChild}let S={};if(h){let x=window.getComputedStyle(h);for(let T=0;T<x.length;T++)S[x[T]]=x.getPropertyValue(x[T])}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 E(x){return x.replace(/-([a-z])/g,(T,L)=>L.toUpperCase())}function b(x,T){if(T>4)return null;let L=x.tagName.toLowerCase();if(["script","style","link","meta","br","hr","noscript"].includes(L))return null;let N=x.className,R=typeof N=="string"?N:N?.baseVal||"",M=x.id||void 0,z=x.getAttribute("role")||void 0,U;for(let _ of Array.from(x.childNodes))if(_.nodeType===3){let P=_.textContent?.trim();if(P){U=P.length>50?P.substring(0,50)+"...":P;break}}let O=L;M?O=`${L}#${M}`:R&&(O=`${L}.${R.split(" ").filter(Boolean).join(".")}`);let W=window.getComputedStyle(x),ve=["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"],G={};for(let _ of ve){let P=W.getPropertyValue(_),F=E(_);P&&!C[F]?.includes(P)&&(G[F]=P)}if(L==="svg"||x.closest("svg"))for(let _ of["fill","stroke","stroke-width","viewBox","d","r","cx","cy"]){let P=x.getAttribute(_);P&&(G[E(_)]=P)}let Q=[];for(let _ of Array.from(x.children)){let P=window.getComputedStyle(_);if(P.display==="none"||P.visibility==="hidden")continue;let F=b(_,T+1);F&&Q.push(F)}return{selector:O,tagName:L,className:R,id:M,role:z,textContent:U,styles:G,children:Q}}return{computedStyles:S,domTree:h?b(h,0):null}},it);o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({screenshot:m?`data:image/png;base64,${m.toString("base64")}`:void 0,computedStyles:g.computedStyles,domTree:g.domTree}))}finally{await l.close()}}catch(u){p.error("Capture error:",u.message),o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:u.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 B()){o.writeHead(501,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Puppeteer not installed"}));return}let d=[];for await(let w of a)d.push(typeof w=="string"?Buffer.from(w):w);let c=JSON.parse(Buffer.concat(d).toString()),{html:i,stylesheetUrls:y,storyId:f}=c;if(!i){o.writeHead(400,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Missing html in body"}));return}let I=`http://${a.headers.host||"localhost:6006"}`;p.debug(`Taking snapshot screenshot for ${f||"unknown"}`);let l=await ae(i,y||[],I,{storyId:f});if(!l){o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Snapshot screenshot failed"}));return}let g=l.toString("base64");o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({screenshot:`data:image/png;base64,${g}`}))}catch(u){p.error("Snapshot screenshot error:",u.message),o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:u.message}))}}),t.httpServer?.on("close",()=>{J().catch(()=>{})});let r=a=>{J().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 wt=()=>{if(typeof import.meta<"u"&&import.meta.url){let e=Ee(import.meta.url),n=Ce(e);return j(n,"manager.mjs")}return j(__dirname,"manager.mjs")},xt=()=>{if(typeof import.meta<"u"&&import.meta.url){let e=Ee(import.meta.url),n=Ce(e);return j(n,"preview.mjs")}return j(__dirname,"preview.mjs")};function Ar(e=[]){return[...e,wt()]}function Dr(e=[]){return[...e,xt()]}export{yt as experimental_serverChannel,Ar as managerEntries,Dr as previewAnnotations,St as viteFinal};
|