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