@uicopilot/storybook-addon 0.5.41 → 0.5.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/preset.js CHANGED
@@ -1,3 +1,3 @@
1
- "use strict";var _e=Object.create;var D=Object.defineProperty;var $e=Object.getOwnPropertyDescriptor;var Le=Object.getOwnPropertyNames;var Me=Object.getPrototypeOf,Oe=Object.prototype.hasOwnProperty;var Re=(e,i)=>()=>(e&&(i=e(e=0)),i);var te=(e,i)=>{for(var t in i)D(e,t,{get:i[t],enumerable:!0})},ie=(e,i,t,s)=>{if(i&&typeof i=="object"||typeof i=="function")for(let n of Le(i))!Oe.call(e,n)&&n!==t&&D(e,n,{get:()=>i[n],enumerable:!(s=$e(i,n))||s.enumerable});return e};var H=(e,i,t)=>(t=e!=null?_e(Me(e)):{},ie(i||!e||!e.__esModule?D(t,"default",{value:e,enumerable:!0}):t,e)),Ne=e=>ie(D({},"__esModule",{value:!0}),e);var he={};te(he,{detectFileType:()=>pe,formatValidationResult:()=>ot,isValidCode:()=>nt,validateCode:()=>fe,validateCodeForFile:()=>me});function Qe(e,i={}){let t=i.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 et(e){let i=[/^[+-]{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 i)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 tt(e){let i=e.split(`
2
- `).filter(n=>n.trim()),t=i.filter(n=>n.trim().startsWith("//")||n.trim().startsWith("/*")||n.trim().startsWith("*")||n.trim().startsWith("#"));if(i.length>0&&t.length/i.length>.8)return{code:"CODE_IS_INSTRUCTIONS",message:"Code appears to be mostly comments/instructions, not actual implementation.",severity:"error"};let s=[/^\/\/\s*(Change|Replace|Update|Modify|Add|Remove|Delete)\s+(from|to|this|the)/im,/^\/\/\s*To:/m,/^\/\/\s*From:/m];for(let n of s)if(n.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 it(e){let i={"{":"}","[":"]","(":")"},t=[],s=!1,n="",o=!1;for(let r=0;r<e.length;r++){let d=e[r],g=e[r-1];if((d==='"'||d==="'"||d==="`")&&g!=="\\"){s?d===n&&(s=!1,o=!1):(s=!0,n=d,d==="`"&&(o=!0));continue}if(!s){if(i[d])t.push(i[d]);else if(Object.values(i).includes(d)&&t.pop()!==d)return{code:"UNBALANCED_BRACES",message:`Unbalanced braces/brackets detected. Found unexpected '${d}'.`,severity:"warning"}}}return t.length>0?{code:"UNBALANCED_BRACES",message:`Unbalanced braces/brackets. Missing: ${t.reverse().join("")}`,severity:"warning"}:null}function ue(e,i={}){let t=[],s=[];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 n=/import\s+(?:React|\{[^}]*\})\s+from\s+['"]react['"]/.test(e);/<[A-Z][a-zA-Z]*|<[a-z]+[\s/>]/.test(e)&&!n&&s.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)||s.push({code:"TSX_NO_COMPONENT_DEF",message:"No clear component definition found. Expected function or const export.",severity:"warning"});let d=[{pattern:/\.\.\.\s*$/,message:'Code ends with "..." - likely truncated'},{pattern:/\/\/\s*\.\.\./m,message:'Contains "// ..." - likely incomplete'},{pattern:/{\s*\/\*\s*\.\.\.\s*\*\/\s*}/m,message:'Contains "{/* ... */}" placeholder'}];for(let{pattern:g,message:p}of d)g.test(e)&&t.push({code:"TSX_INCOMPLETE",message:p,severity:"error"});return{errors:t,warnings:s}}function st(e,i={}){let t=[],s=[];(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 o=(e.match(/\{[^}]+\}/g)||[]).length;return o===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"}),o>0&&o<3&&!i.allowPartial&&s.push({code:"CSS_FEW_RULES",message:`Only ${o} CSS rule(s) found. Might be incomplete.`,severity:"warning"}),{errors:t,warnings:s}}function rt(e,i={}){let t=[],s=[];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")||s.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")||s.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)||s.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:s}}function pe(e){let i=e.toLowerCase();if(i.includes(".stories."))return"stories";switch(i.split(".").pop()){case"tsx":return"tsx";case"jsx":return"jsx";case"ts":return"ts";case"js":return"js";case"css":return"css";case"scss":return"scss";case"less":return"less";default:return"unknown"}}function fe(e,i,t={}){let s={valid:!0,fileType:i,errors:[],warnings:[]},n=Qe(e,t);n&&s.errors.push(n);let o=et(e);o&&s.errors.push(o);let r=tt(e);r&&s.errors.push(r);let d=it(e);switch(d&&(t.strict?s.errors.push({...d,severity:"error"}):s.warnings.push(d)),i){case"stories":{let{errors:g,warnings:p}=rt(e,t);s.errors.push(...g),s.warnings.push(...p);break}case"tsx":case"jsx":{let{errors:g,warnings:p}=ue(e,t);s.errors.push(...g),s.warnings.push(...p);break}case"css":case"scss":case"less":{let{errors:g,warnings:p}=st(e,t);s.errors.push(...g),s.warnings.push(...p);break}case"ts":case"js":{let{errors:g,warnings:p}=ue(e,t);s.errors.push(...g),s.warnings.push(...p.filter(c=>!c.code.includes("JSX")));break}default:break}return s.valid=s.errors.length===0,s}function me(e,i,t={}){let s=pe(i);return fe(e,s,t)}function nt(e,i,t={}){return me(e,i,t).valid}function ot(e){if(e.valid&&e.warnings.length===0)return`\u2713 Valid ${e.fileType} code`;let i=[];if(e.valid)i.push(`\u26A0 Valid ${e.fileType} code with warnings`);else{i.push(`\u2717 Invalid ${e.fileType} code`),i.push(""),i.push("Errors:");for(let t of e.errors)i.push(` - [${t.code}] ${t.message}`)}if(e.warnings.length>0){i.push(""),i.push("Warnings:");for(let t of e.warnings)i.push(` - [${t.code}] ${t.message}`)}return i.join(`
3
- `)}var Ke,ge=Re(()=>{"use strict";Ke=50});var Ct={};te(Ct,{experimental_serverChannel:()=>Ie,managerEntries:()=>St,previewAnnotations:()=>bt,viteFinal:()=>Te});module.exports=Ne(Ct);var L=require("path"),K=require("url");var ve=H(require("fs/promises")),j=H(require("path")),Y=require("glob");var ae=require("fs"),ce=require("module");var W={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 Fe(){if(typeof process<"u"&&process.env)return process.env.UICOPILOT_DEBUG==="1";if(typeof globalThis<"u"&&"localStorage"in globalThis)try{return globalThis.localStorage.getItem("uicopilot_debug")==="1"}catch{return!1}return!1}var V=`[${W.NAME}]`,l={debug:(...e)=>{Fe()&&console.log(V,...e)},info:(...e)=>{console.log(V,...e)},warn:(...e)=>{console.warn(V,...e)},error:(...e)=>{console.error(V,...e)}};var qe=["flex","inline-flex"],Je=["grid","inline-grid"],jt=[...qe,...Je];var U=null,$=null,oe=!1;async function X(){if(oe)return!!U;if(oe=!0,process.env.STORYBOOK_UICOPILOT_NO_PUPPETEER==="true")return l.debug("Puppeteer disabled via STORYBOOK_UICOPILOT_NO_PUPPETEER flag"),!1;let e=(0,ce.createRequire)(process.cwd()+"/");try{return U=e("puppeteer"),l.debug("Puppeteer loaded \u2014 server-side screenshots enabled"),!0}catch{}try{return U=e("puppeteer-core"),l.debug("puppeteer-core loaded \u2014 server-side screenshots enabled"),!0}catch{}return l.debug("Puppeteer not found \u2014 install puppeteer for pixel-perfect screenshots"),!1}function Ze(){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 i of e)if((0,ae.existsSync)(i))return i}async function le(){if($&&$.connected)return $;let e=Ze(),i={headless:!0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-dev-shm-usage"],...e?{executablePath:e}:{}};return $=await U.launch(i),l.debug("Headless Chrome launched for screenshots"),$}async function q(e,i){if(!await X())return null;let n=await(await le()).newPage();try{await n.setCacheEnabled(!1),await n.setViewport({width:i?.width||800,height:i?.height||600,deviceScaleFactor:1}),await n.goto(e,{waitUntil:"networkidle2",timeout:15e3}),await n.evaluate(()=>document.fonts.ready),await n.waitForSelector("#storybook-root > *",{timeout:1e4}),await n.waitForFunction(()=>new Promise(p=>{let c=document.querySelectorAll("style").length,m=0,h=()=>{let f=document.querySelectorAll("style").length;if(f===c){if(m++,m>=3){p(!0);return}}else m=0,c=f;setTimeout(h,100)};setTimeout(h,200)}),{timeout:5e3}).catch(()=>{}),await new Promise(p=>setTimeout(p,500));let o=await n.evaluate(()=>{let p=document.querySelector("#storybook-root");if(!p)return null;let c=window.innerHeight,m=window.innerWidth,h=1/0,f=0,x=1/0,a=0,u=!1;function w(S){for(let y of Array.from(S.children)){let v=window.getComputedStyle(y);if(v.display==="none"||v.visibility==="hidden"||v.position==="fixed"||v.position==="absolute")continue;let T=y.getBoundingClientRect();if(T.height<=0||T.width<=0)continue;if((T.width>=m*.9||T.height>=c*.9)&&y.children.length>0){y.setAttribute("data-uic-drilled",""),w(y);continue}if(y.children.length===1){let E=v.backgroundColor,_=E==="rgba(0, 0, 0, 0)"||E==="transparent"||E==="",O=v.borderStyle!=="none"&&v.borderWidth!=="0px",R=v.boxShadow!=="none",N=!_||O||R,F=y.children[0].getBoundingClientRect(),k=F.width>=T.width*.95&&F.height>=T.height*.95;if(!N||k){y.setAttribute("data-uic-drilled",""),w(y);continue}}h=Math.min(h,T.top),f=Math.max(f,T.bottom),x=Math.min(x,T.left),a=Math.max(a,T.right),u=!0}}if(w(p),!u)return null;let b=document.createElement("style");return b.id="uic-drilled-bg-reset",b.textContent="[data-uic-drilled] { background: transparent !important; border-color: transparent !important; box-shadow: none !important; }",document.head.appendChild(b),document.body.offsetHeight,{top:h,bottom:f,left:x,right:a}});await n.evaluate(()=>new Promise(p=>requestAnimationFrame(()=>p())));let r=4,d=o?{x:Math.max(0,o.left-r),y:Math.max(0,o.top-r),width:Math.min(o.right-o.left+r*2,800),height:Math.min(o.bottom-o.top+r*2,600)}:void 0,g=await n.screenshot({type:"png",omitBackground:!0,...d?{clip:d}:{fullPage:!1}});return Buffer.from(g)}finally{await n.close()}}async function de(e,i,t,s){if(!await X())return null;let r=await(await le()).newPage();try{await r.setCacheEnabled(!1),await r.setViewport({width:s?.width||800,height:s?.height||600,deviceScaleFactor:1});let d=s?.storyId||"",g=`${t}/iframe.html?viewMode=story&id=${d}&globals=`;await r.goto(g,{waitUntil:"load",timeout:15e3}),await r.waitForSelector("#storybook-root > *",{timeout:1e4}),await r.evaluate(m=>{let h=document.getElementById("storybook-root");h&&(h.innerHTML=m)},e),await r.evaluate(()=>document.fonts.ready),await new Promise(m=>setTimeout(m,500));let p=await r.evaluate(()=>{let m=document.querySelector("#storybook-root");if(!m)return null;let h=window.innerWidth;function f(u){let w=u.getBoundingClientRect();if(w.width===0||w.height===0)return null;if(w.width<h*.8&&w.height>0)return w;for(let b of Array.from(u.children)){let S=window.getComputedStyle(b);if(S.position==="fixed"||S.position==="absolute"||S.display==="none"||S.visibility==="hidden")continue;let y=f(b);if(y)return y}return null}let x=f(m);if(x)return{x:Math.max(0,x.x-8),y:Math.max(0,x.y-8),width:x.width+16,height:x.height+16};let a=m.firstElementChild;if(a){let u=a.getBoundingClientRect();return{x:u.x,y:u.y,width:u.width,height:u.height}}return null});if(!p)throw new Error("Could not determine component bounds from snapshot");let c=await r.screenshot({type:"png",clip:p});return Buffer.from(c)}finally{await r.close()}}async function z(){return X()}async function J(){$&&(await $.close(),$=null)}var Z=null,B=null,ye=!1;async function at(){if(!ye){ye=!0;try{let e=await Promise.resolve().then(()=>(ge(),he));Z=e.validateCodeForFile,B=e.formatValidationResult,l.debug("Code validator loaded - fix validation enabled")}catch{l.debug("Code validator not available - skipping fix validation")}}}var ct="UICOPILOT/APPLY_FIXES",lt="UICOPILOT/FIX_STARTED",dt="UICOPILOT/FIX_COMPLETED",ut="UICOPILOT/FIX_FAILED",we="UICOPILOT/ALL_FIXES_APPLIED",pt="UICOPILOT/RELOAD_REQUIRED",xe="UICOPILOT/WORKSPACE_PATH",ft="UICOPILOT/REQUEST_WORKSPACE_PATH",mt="UICOPILOT/DISCOVER_COMPONENT_FILES",Se="UICOPILOT/COMPONENT_FILES_DISCOVERED";async function be(e,i){let t=e.toLowerCase(),s=e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),n=[`src/**/fui-${t}/fui-${t}.css`,`src/**/fui-${t}/*.css`,`src/**/${t}/${t}.css`,`src/**/${s}/${s}.css`,`src/**/*${t}*.css`,`src/**/*${s}*.css`,`styles/**/*${t}*.css`],o=[`src/**/fui-${t}/fui-${t}.tsx`,`src/**/fui-${t}/*.tsx`,`src/**/${t}/${t}.tsx`,`src/**/${s}/${s}.tsx`,`src/**/*${s}*.tsx`,`src/**/*${s}*.jsx`],r=[],d=[];for(let a of n)try{let u=await(0,Y.glob)(a,{cwd:i,nodir:!0,ignore:["**/node_modules/**","**/dist/**","**/.storybook/**"]});u.length>0&&r.push(...u)}catch{}for(let a of o)try{let u=await(0,Y.glob)(a,{cwd:i,nodir:!0,ignore:["**/node_modules/**","**/dist/**","**/.storybook/**","**/*.stories.*","**/*.test.*"]});u.length>0&&d.push(...u)}catch{}let g=[...new Set(r)],p=[...new Set(d)],c=a=>{if(a.length===0)return;let u=a.find(S=>S.includes(`/fui-${t}/`)&&S.endsWith(".css"));if(u)return u;let w=a.find(S=>S.toLowerCase().includes(`/${t}/${t}.css`)||S.includes(`/${s}/${s}.css`));if(w)return w;let b=a.find(S=>S.toLowerCase().endsWith(`/${t}.css`)||S.endsWith(`/${s}.css`));return b||a[0]},m=a=>{if(a.length===0)return;let u=a.filter(y=>!y.includes(".stories.")&&!y.includes(".test."));if(u.length===0)return a[0];let w=u.find(y=>y.includes(`/fui-${t}/`)&&(y.endsWith(".tsx")||y.endsWith(".jsx")));if(w)return w;let b=u.find(y=>y.toLowerCase().includes(`/${t}/${t}.tsx`)||y.includes(`/${s}/${s}.tsx`));if(b)return b;let S=u.find(y=>y.toLowerCase().endsWith(`/${t}.tsx`)||y.endsWith(`/${s}.tsx`));return S||u[0]},h=c(g),f=m(p),x=[...g,...p];return l.debug(`Discovered files for "${e}":`,{cssFile:h,componentFile:f,totalMatches:x.length}),{cssFile:h,componentFile:f,allMatches:[...new Set(x)]}}var ht=100;function gt(e){return new Promise(i=>setTimeout(i,e))}async function yt(e,i){if(await at(),!Z||!B)return l.debug(`Skipping validation (validator not available) for ${i}`),{valid:!0};let t=Z(e,i);if(!t.valid){let s=t.errors.map(n=>n.message).join("; ");return l.warn(`Code validation failed for ${i}:`),console.warn(B(t)),{valid:!1,error:s}}return t.warnings.length>0&&(l.warn(`Code validation warnings for ${i}:`),console.warn(B(t))),l.debug(`Validation passed for ${i}`),{valid:!0}}var Ce=!1;function Ie(e){if(Ce)return e;Ce=!0;let i=process.cwd();return l.debug("Apply fixes initialized"),l.debug("Workspace:",i),e.emit(xe,{path:i}),e.on(ft,()=>{l.debug("Workspace path requested by browser"),l.debug("Emitting workspace path response:",i),e.emit(xe,{path:i})}),e.on(mt,async t=>{let{componentName:s,storyId:n}=t;l.debug(`Discovering files for component: ${s}`);try{let o=await be(s,i);e.emit(Se,{componentName:s,storyId:n,...o,workspacePath:i})}catch(o){l.error("File discovery error:",o),e.emit(Se,{componentName:s,storyId:n,error:o.message,allMatches:[]})}}),e.on(ct,t=>{setTimeout(async()=>{try{let{issues:s,storybookRoot:n}=t,o=n||i;n?l.debug(`Using storybookRoot from API: ${n}`):l.debug(`Using process.cwd(): ${i}`),l.debug(`Received APPLY_FIXES for ${s.length} issue(s)`);let r=new Map;async function d(c){let m=c.targetFileType||"css",h=c.targetFilePath||c.generatedFix?.filePath,f="",x=c.title?.match(/^(\w+)\s/);if(x&&(f=x[1]),!f&&h){let w=h.match(/\/(\w+)\.(?:css|tsx|jsx)$/i);w&&(f=w[1])}if(!f)return l.debug(`Could not extract component name, using provided path: ${h}`),h||null;if(!r.has(f)){let w=await be(f,o);r.set(f,w)}let a=r.get(f),u=m==="css"?a.cssFile:a.componentFile;return u?(l.debug(`Discovered ${m} path: ${u} (was: ${h})`),u):(l.debug(`No ${m} file discovered, using provided: ${h}`),h||null)}let g=[];for(let c of s){let{generatedFix:m}=c,h=c.targetFilePath||m?.filePath,f=await d(c)||h;l.debug("Processing issue:",{id:c.id,type:c.type,targetFileType:c.targetFileType||"css",targetPath:f,providedPath:h!==f?h:"(same)",codeLength:m?.code?.length||0}),e.emit(lt,{issueId:c.id});try{if(!m||!m.code||!f)throw new Error("Missing AI-generated fix data (code or filePath)");l.debug("Code to write (first 200 chars):",m.code.substring(0,200)),l.debug(`Code length: ${m.code.length} chars`);let x=await yt(m.code,f);if(!x.valid)throw new Error(`Code validation failed: ${x.error}. Fix was not applied to prevent breaking the file.`);let a=j.isAbsolute(f)?f:j.join(o,f);l.debug(`Writing to absolute path: ${a}`),await ve.writeFile(a,m.code,"utf-8"),await gt(ht);let u={success:!0,issueId:c.id,filePath:f,timestamp:new Date};e.emit(dt,{issueId:c.id,result:u}),l.debug(`\u2713 Applied ${c.targetFileType||"css"} fix to: ${f}`),g.push(u)}catch(x){let a=x.message||"Unknown error";e.emit(ut,{issueId:c.id,error:a}),l.error(`\u2717 Error: ${a}`),g.push({success:!1,issueId:c.id,error:a,timestamp:new Date})}}let p={total:g.length,succeeded:g.filter(c=>c.success).length,failed:g.filter(c=>!c.success).length};e.emit(we,{results:g,summary:p}),l.debug(`Completed: ${p.succeeded}/${p.total} fixes applied`),p.succeeded>0&&e.emit(pt,{message:"Fixes applied. If Storybook crashes due to HMR, please restart it.",filesChanged:g.filter(c=>c.success).map(c=>c.filePath)})}catch(s){l.error("Fatal error during fix application:",s),e.emit(we,{results:[],summary:{total:t.issues?.length||0,succeeded:0,failed:t.issues?.length||0}})}},0)}),e}function Te(e){let i=process.cwd();return e.plugins=e.plugins||[],e.plugins.push({name:"uicopilot-server-api",configureServer(t){t.middlewares.use("/__uicopilot/health",(o,r)=>{r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({ok:!0,workspacePath:i}))}),t.middlewares.use("/__uicopilot/screenshot",async(o,r)=>{try{if(!await z()){r.writeHead(501,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Puppeteer not installed. Run: npm install puppeteer"}));return}let p=new URL(o.url||"",`http://${o.headers.host}`).searchParams.get("storyId");if(!p){r.writeHead(400,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Missing storyId parameter"}));return}let m=`http://${o.headers.host||"localhost:6006"}/iframe.html?viewMode=story&id=${p}&globals=`;l.debug(`Taking screenshot: ${p}`);let h=await q(m,{selector:"#storybook-root > *"});if(!h){r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Screenshot capture failed"}));return}let f=h.toString("base64");r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({screenshot:`data:image/png;base64,${f}`}))}catch(d){l.error("Screenshot error:",d.message),r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:d.message}))}}),t.middlewares.use("/__uicopilot/capture",async(o,r)=>{try{if(!await z()){r.writeHead(501,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Puppeteer not installed"}));return}let p=new URL(o.url||"",`http://${o.headers.host}`).searchParams.get("storyId");if(!p){r.writeHead(400,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Missing storyId parameter"}));return}let m=`http://${o.headers.host||"localhost:6006"}/iframe.html?viewMode=story&id=${p}&globals=`;l.debug(`Full capture: ${p}`);let h=await q(m,{selector:"#storybook-root > *"});if(!h){r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Screenshot capture failed"}));return}let f;try{f=(await import("puppeteer")).default}catch{f=(await import("puppeteer-core")).default}let x=await f.launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox"]}),a=await x.newPage();try{await a.setCacheEnabled(!1),await a.setViewport({width:800,height:600}),await a.goto(m,{waitUntil:"networkidle2",timeout:15e3}),await a.evaluate(()=>document.fonts.ready),await a.waitForSelector("#storybook-root > *",{timeout:1e4}),await a.evaluate(()=>new Promise(b=>{let S=setTimeout(b,5e3);try{let y=window.__STORYBOOK_ADDONS_CHANNEL__;if(y){let v=()=>{clearTimeout(S),y.off("storyRendered",v),setTimeout(b,100)};y.on("storyRendered",v)}else clearTimeout(S),setTimeout(b,300)}catch{clearTimeout(S),b()}}));let u=await a.evaluate(()=>{let b=document.querySelector("#storybook-root > *")||document.querySelector("#root > *"),S={};if(b){let C=window.getComputedStyle(b);for(let E=0;E<C.length;E++)S[C[E]]=C.getPropertyValue(C[E])}let y={backgroundColor:["transparent","rgba(0, 0, 0, 0)"],border:["none","0px none","0px none rgb(0, 0, 0)"],borderRadius:["0px"],boxShadow:["none"],opacity:["1"]};function v(C){return C.replace(/-([a-z])/g,(E,_)=>_.toUpperCase())}function T(C,E){if(E>4)return null;let _=C.tagName.toLowerCase();if(["script","style","link","meta","br","hr","noscript"].includes(_))return null;let O=C.className,R=typeof O=="string"?O:O?.baseVal||"",N=C.id||void 0,Q=C.getAttribute("role")||void 0,F;for(let P of Array.from(C.childNodes))if(P.nodeType===3){let I=P.textContent?.trim();if(I){F=I.length>50?I.substring(0,50)+"...":I;break}}let k=_;N?k=`${_}#${N}`:R&&(k=`${_}.${R.split(" ").filter(Boolean).join(".")}`);let Ee=window.getComputedStyle(C),Pe=["background-color","border","border-radius","box-shadow","opacity","fill","stroke","stroke-width","font-size","font-family","font-weight","line-height","letter-spacing","color","text-align","display","padding","margin","gap","flex-direction","justify-content","align-items","width","height"],G={};for(let P of Pe){let I=Ee.getPropertyValue(P),A=v(P);I&&!y[A]?.includes(I)&&(G[A]=I)}if(_==="svg"||C.closest("svg"))for(let P of["fill","stroke","stroke-width","viewBox","d","r","cx","cy"]){let I=C.getAttribute(P);I&&(G[v(P)]=I)}let ee=[];for(let P of Array.from(C.children)){let I=window.getComputedStyle(P);if(I.display==="none"||I.visibility==="hidden")continue;let A=T(P,E+1);A&&ee.push(A)}return{selector:k,tagName:_,className:R,id:N,role:Q,textContent:F,styles:G,children:ee}}return{computedStyles:S,domTree:b?T(b,0):null}}),w=h.toString("base64");r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({screenshot:`data:image/png;base64,${w}`,computedStyles:u.computedStyles,domTree:u.domTree}))}finally{await a.close(),await x.close()}}catch(d){l.error("Capture error:",d.message),r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:d.message}))}}),t.middlewares.use("/__uicopilot/screenshot-snapshot",async(o,r)=>{if(o.method!=="POST"){r.writeHead(405,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"POST required"}));return}try{if(!await z()){r.writeHead(501,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Puppeteer not installed"}));return}let g=[];for await(let w of o)g.push(typeof w=="string"?Buffer.from(w):w);let p=JSON.parse(Buffer.concat(g).toString()),{html:c,stylesheetUrls:m,storyId:h}=p;if(!c){r.writeHead(400,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Missing html in body"}));return}let x=`http://${o.headers.host||"localhost:6006"}`;l.debug(`Taking snapshot screenshot for ${h||"unknown"}`);let a=await de(c,m||[],x,{storyId:h});if(!a){r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Snapshot screenshot failed"}));return}let u=a.toString("base64");r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({screenshot:`data:image/png;base64,${u}`}))}catch(d){l.error("Snapshot screenshot error:",d.message),r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:d.message}))}}),t.httpServer?.on("close",()=>{J().catch(()=>{})});let s=o=>{J().catch(()=>{}).finally(()=>{process.kill(process.pid,o)})},n=globalThis;n.__uicopilotShutdownRegistered||(n.__uicopilotShutdownRegistered=!0,process.once("SIGINT",()=>s("SIGINT")),process.once("SIGTERM",()=>s("SIGTERM")))}}),e}var M={},wt=()=>{if(typeof M<"u"&&M.url){let e=(0,K.fileURLToPath)(M.url),i=(0,L.dirname)(e);return(0,L.join)(i,"manager.mjs")}return(0,L.join)(__dirname,"manager.mjs")},xt=()=>{if(typeof M<"u"&&M.url){let e=(0,K.fileURLToPath)(M.url),i=(0,L.dirname)(e);return(0,L.join)(i,"preview.mjs")}return(0,L.join)(__dirname,"preview.mjs")};function St(e=[]){return[...e,wt()]}function bt(e=[]){return[...e,xt()]}0&&(module.exports={experimental_serverChannel,managerEntries,previewAnnotations,viteFinal});
1
+ "use strict";var _e=Object.create;var D=Object.defineProperty;var Le=Object.getOwnPropertyDescriptor;var $e=Object.getOwnPropertyNames;var Me=Object.getPrototypeOf,Oe=Object.prototype.hasOwnProperty;var Re=(e,r)=>()=>(e&&(r=e(e=0)),r);var te=(e,r)=>{for(var t in r)D(e,t,{get:r[t],enumerable:!0})},re=(e,r,t,i)=>{if(r&&typeof r=="object"||typeof r=="function")for(let n of $e(r))!Oe.call(e,n)&&n!==t&&D(e,n,{get:()=>r[n],enumerable:!(i=Le(r,n))||i.enumerable});return e};var H=(e,r,t)=>(t=e!=null?_e(Me(e)):{},re(r||!e||!e.__esModule?D(t,"default",{value:e,enumerable:!0}):t,e)),Ne=e=>re(D({},"__esModule",{value:!0}),e);var he={};te(he,{detectFileType:()=>pe,formatValidationResult:()=>ot,isValidCode:()=>nt,validateCode:()=>fe,validateCodeForFile:()=>me});function Qe(e,r={}){let t=r.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 et(e){let r=[/^[+-]{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 r)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 tt(e){let r=e.split(`
2
+ `).filter(n=>n.trim()),t=r.filter(n=>n.trim().startsWith("//")||n.trim().startsWith("/*")||n.trim().startsWith("*")||n.trim().startsWith("#"));if(r.length>0&&t.length/r.length>.8)return{code:"CODE_IS_INSTRUCTIONS",message:"Code appears to be mostly comments/instructions, not actual implementation.",severity:"error"};let i=[/^\/\/\s*(Change|Replace|Update|Modify|Add|Remove|Delete)\s+(from|to|this|the)/im,/^\/\/\s*To:/m,/^\/\/\s*From:/m];for(let n of i)if(n.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 rt(e){let r={"{":"}","[":"]","(":")"},t=[],i=!1,n="",o=!1;for(let s=0;s<e.length;s++){let d=e[s],g=e[s-1];if((d==='"'||d==="'"||d==="`")&&g!=="\\"){i?d===n&&(i=!1,o=!1):(i=!0,n=d,d==="`"&&(o=!0));continue}if(!i){if(r[d])t.push(r[d]);else if(Object.values(r).includes(d)&&t.pop()!==d)return{code:"UNBALANCED_BRACES",message:`Unbalanced braces/brackets detected. Found unexpected '${d}'.`,severity:"warning"}}}return t.length>0?{code:"UNBALANCED_BRACES",message:`Unbalanced braces/brackets. Missing: ${t.reverse().join("")}`,severity:"warning"}:null}function ue(e,r={}){let t=[],i=[];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 n=/import\s+(?:React|\{[^}]*\})\s+from\s+['"]react['"]/.test(e);/<[A-Z][a-zA-Z]*|<[a-z]+[\s/>]/.test(e)&&!n&&i.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)||i.push({code:"TSX_NO_COMPONENT_DEF",message:"No clear component definition found. Expected function or const export.",severity:"warning"});let d=[{pattern:/\.\.\.\s*$/,message:'Code ends with "..." - likely truncated'},{pattern:/\/\/\s*\.\.\./m,message:'Contains "// ..." - likely incomplete'},{pattern:/{\s*\/\*\s*\.\.\.\s*\*\/\s*}/m,message:'Contains "{/* ... */}" placeholder'}];for(let{pattern:g,message:p}of d)g.test(e)&&t.push({code:"TSX_INCOMPLETE",message:p,severity:"error"});return{errors:t,warnings:i}}function it(e,r={}){let t=[],i=[];(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 o=(e.match(/\{[^}]+\}/g)||[]).length;return o===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"}),o>0&&o<3&&!r.allowPartial&&i.push({code:"CSS_FEW_RULES",message:`Only ${o} CSS rule(s) found. Might be incomplete.`,severity:"warning"}),{errors:t,warnings:i}}function st(e,r={}){let t=[],i=[];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")||i.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")||i.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)||i.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:i}}function pe(e){let r=e.toLowerCase();if(r.includes(".stories."))return"stories";switch(r.split(".").pop()){case"tsx":return"tsx";case"jsx":return"jsx";case"ts":return"ts";case"js":return"js";case"css":return"css";case"scss":return"scss";case"less":return"less";default:return"unknown"}}function fe(e,r,t={}){let i={valid:!0,fileType:r,errors:[],warnings:[]},n=Qe(e,t);n&&i.errors.push(n);let o=et(e);o&&i.errors.push(o);let s=tt(e);s&&i.errors.push(s);let d=rt(e);switch(d&&(t.strict?i.errors.push({...d,severity:"error"}):i.warnings.push(d)),r){case"stories":{let{errors:g,warnings:p}=st(e,t);i.errors.push(...g),i.warnings.push(...p);break}case"tsx":case"jsx":{let{errors:g,warnings:p}=ue(e,t);i.errors.push(...g),i.warnings.push(...p);break}case"css":case"scss":case"less":{let{errors:g,warnings:p}=it(e,t);i.errors.push(...g),i.warnings.push(...p);break}case"ts":case"js":{let{errors:g,warnings:p}=ue(e,t);i.errors.push(...g),i.warnings.push(...p.filter(c=>!c.code.includes("JSX")));break}default:break}return i.valid=i.errors.length===0,i}function me(e,r,t={}){let i=pe(r);return fe(e,i,t)}function nt(e,r,t={}){return me(e,r,t).valid}function ot(e){if(e.valid&&e.warnings.length===0)return`\u2713 Valid ${e.fileType} code`;let r=[];if(e.valid)r.push(`\u26A0 Valid ${e.fileType} code with warnings`);else{r.push(`\u2717 Invalid ${e.fileType} code`),r.push(""),r.push("Errors:");for(let t of e.errors)r.push(` - [${t.code}] ${t.message}`)}if(e.warnings.length>0){r.push(""),r.push("Warnings:");for(let t of e.warnings)r.push(` - [${t.code}] ${t.message}`)}return r.join(`
3
+ `)}var Ke,ge=Re(()=>{"use strict";Ke=50});var Ct={};te(Ct,{experimental_serverChannel:()=>Ee,managerEntries:()=>St,previewAnnotations:()=>bt,viteFinal:()=>Ie});module.exports=Ne(Ct);var $=require("path"),K=require("url");var ve=H(require("fs/promises")),j=H(require("path")),Y=require("glob");var ae=require("fs"),ce=require("module");var W={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 Fe(){if(typeof process<"u"&&process.env)return process.env.UICOPILOT_DEBUG==="1";if(typeof globalThis<"u"&&"localStorage"in globalThis)try{return globalThis.localStorage.getItem("uicopilot_debug")==="1"}catch{return!1}return!1}var V=`[${W.NAME}]`,l={debug:(...e)=>{Fe()&&console.log(V,...e)},info:(...e)=>{console.log(V,...e)},warn:(...e)=>{console.warn(V,...e)},error:(...e)=>{console.error(V,...e)}};var qe=["flex","inline-flex"],Je=["grid","inline-grid"],Gt=[...qe,...Je];var U=null,L=null,oe=!1;async function X(){if(oe)return!!U;if(oe=!0,process.env.STORYBOOK_UICOPILOT_NO_PUPPETEER==="true")return l.debug("Puppeteer disabled via STORYBOOK_UICOPILOT_NO_PUPPETEER flag"),!1;let e=(0,ce.createRequire)(process.cwd()+"/");try{return U=e("puppeteer"),l.debug("Puppeteer loaded \u2014 server-side screenshots enabled"),!0}catch{}try{return U=e("puppeteer-core"),l.debug("puppeteer-core loaded \u2014 server-side screenshots enabled"),!0}catch{}return l.debug("Puppeteer not found \u2014 install puppeteer for pixel-perfect screenshots"),!1}function Ze(){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 r of e)if((0,ae.existsSync)(r))return r}async function le(){if(L&&L.connected)return L;let e=Ze(),r={headless:!0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-dev-shm-usage"],...e?{executablePath:e}:{}};return L=await U.launch(r),l.debug("Headless Chrome launched for screenshots"),L}async function q(e,r){if(!await X())return null;let n=await(await le()).newPage();try{await n.setCacheEnabled(!1),await n.setViewport({width:r?.width||800,height:r?.height||600,deviceScaleFactor:1}),await n.goto(e,{waitUntil:"networkidle2",timeout:15e3}),await n.evaluate(()=>document.fonts.ready),await n.waitForSelector("#storybook-root > *",{timeout:1e4}),await n.waitForFunction(()=>new Promise(p=>{let c=document.querySelectorAll("style").length,m=0,h=()=>{let f=document.querySelectorAll("style").length;if(f===c){if(m++,m>=3){p(!0);return}}else m=0,c=f;setTimeout(h,100)};setTimeout(h,200)}),{timeout:5e3}).catch(()=>{}),await new Promise(p=>setTimeout(p,500));let o=await n.evaluate(()=>{let p=document.querySelector("#storybook-root");if(!p)return null;let c=window.innerHeight,m=window.innerWidth,h=1/0,f=0,x=1/0,a=0,u=!1;function w(S){for(let y of Array.from(S.children)){let v=window.getComputedStyle(y);if(v.display==="none"||v.visibility==="hidden"||v.position==="fixed"||v.position==="absolute")continue;let I=y.getBoundingClientRect();if(I.height<=0||I.width<=0)continue;if((I.width>=m*.9||I.height>=c*.9)&&y.children.length>0){y.setAttribute("data-uic-drilled",""),w(y);continue}if(y.children.length===1){let T=v.backgroundColor,_=T==="rgba(0, 0, 0, 0)"||T==="transparent"||T==="",O=v.borderStyle!=="none"&&v.borderWidth!=="0px",R=v.boxShadow!=="none",N=!_||O||R,F=y.children[0].getBoundingClientRect(),k=F.width>=I.width*.95&&F.height>=I.height*.95;if(!N||k){y.setAttribute("data-uic-drilled",""),w(y);continue}}h=Math.min(h,I.top),f=Math.max(f,I.bottom),x=Math.min(x,I.left),a=Math.max(a,I.right),u=!0}}if(w(p),!u)return null;let b=document.createElement("style");return b.id="uic-drilled-bg-reset",b.textContent="[data-uic-drilled] { background: transparent !important; border-color: transparent !important; box-shadow: none !important; }",document.head.appendChild(b),document.body.offsetHeight,{top:h,bottom:f,left:x,right:a}});await n.evaluate(()=>new Promise(p=>requestAnimationFrame(()=>p())));let s=4,d=o?{x:Math.max(0,o.left-s),y:Math.max(0,o.top-s),width:Math.min(o.right-o.left+s*2,800),height:Math.min(o.bottom-o.top+s*2,600)}:void 0,g=await n.screenshot({type:"png",omitBackground:!0,...d?{clip:d}:{fullPage:!1}});return Buffer.from(g)}finally{await n.close()}}async function de(e,r,t,i){if(!await X())return null;let s=await(await le()).newPage();try{await s.setCacheEnabled(!1),await s.setViewport({width:i?.width||800,height:i?.height||600,deviceScaleFactor:1});let d=i?.storyId||"",g=`${t}/iframe.html?viewMode=story&id=${d}&globals=`;await s.goto(g,{waitUntil:"load",timeout:15e3}),await s.waitForSelector("#storybook-root > *",{timeout:1e4}),await s.evaluate(m=>{let h=document.getElementById("storybook-root");h&&(h.innerHTML=m)},e),await s.evaluate(()=>document.fonts.ready),await new Promise(m=>setTimeout(m,500));let p=await s.evaluate(()=>{let m=document.querySelector("#storybook-root");if(!m)return null;let h=window.innerWidth;function f(u){let w=u.getBoundingClientRect();if(w.width===0||w.height===0)return null;if(w.width<h*.8&&w.height>0)return w;for(let b of Array.from(u.children)){let S=window.getComputedStyle(b);if(S.position==="fixed"||S.position==="absolute"||S.display==="none"||S.visibility==="hidden")continue;let y=f(b);if(y)return y}return null}let x=f(m);if(x)return{x:Math.max(0,x.x-8),y:Math.max(0,x.y-8),width:x.width+16,height:x.height+16};let a=m.firstElementChild;if(a){let u=a.getBoundingClientRect();return{x:u.x,y:u.y,width:u.width,height:u.height}}return null});if(!p)throw new Error("Could not determine component bounds from snapshot");let c=await s.screenshot({type:"png",clip:p});return Buffer.from(c)}finally{await s.close()}}async function B(){return X()}async function J(){L&&(await L.close(),L=null)}var Z=null,z=null,ye=!1;async function at(){if(!ye){ye=!0;try{let e=await Promise.resolve().then(()=>(ge(),he));Z=e.validateCodeForFile,z=e.formatValidationResult,l.debug("Code validator loaded - fix validation enabled")}catch{l.debug("Code validator not available - skipping fix validation")}}}var ct="UICOPILOT/APPLY_FIXES",lt="UICOPILOT/FIX_STARTED",dt="UICOPILOT/FIX_COMPLETED",ut="UICOPILOT/FIX_FAILED",we="UICOPILOT/ALL_FIXES_APPLIED",pt="UICOPILOT/RELOAD_REQUIRED",xe="UICOPILOT/WORKSPACE_PATH",ft="UICOPILOT/REQUEST_WORKSPACE_PATH",mt="UICOPILOT/DISCOVER_COMPONENT_FILES",Se="UICOPILOT/COMPONENT_FILES_DISCOVERED";async function be(e,r){let t=e.toLowerCase(),i=e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),n=[`src/**/fui-${t}/fui-${t}.css`,`src/**/fui-${t}/*.css`,`src/**/${t}/${t}.css`,`src/**/${i}/${i}.css`,`src/**/*${t}*.css`,`src/**/*${i}*.css`,`styles/**/*${t}*.css`],o=[`src/**/fui-${t}/fui-${t}.tsx`,`src/**/fui-${t}/*.tsx`,`src/**/${t}/${t}.tsx`,`src/**/${i}/${i}.tsx`,`src/**/*${i}*.tsx`,`src/**/*${i}*.jsx`],s=[],d=[];for(let a of n)try{let u=await(0,Y.glob)(a,{cwd:r,nodir:!0,ignore:["**/node_modules/**","**/dist/**","**/.storybook/**"]});u.length>0&&s.push(...u)}catch{}for(let a of o)try{let u=await(0,Y.glob)(a,{cwd:r,nodir:!0,ignore:["**/node_modules/**","**/dist/**","**/.storybook/**","**/*.stories.*","**/*.test.*"]});u.length>0&&d.push(...u)}catch{}let g=[...new Set(s)],p=[...new Set(d)],c=a=>{if(a.length===0)return;let u=a.find(S=>S.includes(`/fui-${t}/`)&&S.endsWith(".css"));if(u)return u;let w=a.find(S=>S.toLowerCase().includes(`/${t}/${t}.css`)||S.includes(`/${i}/${i}.css`));if(w)return w;let b=a.find(S=>S.toLowerCase().endsWith(`/${t}.css`)||S.endsWith(`/${i}.css`));return b||a[0]},m=a=>{if(a.length===0)return;let u=a.filter(y=>!y.includes(".stories.")&&!y.includes(".test."));if(u.length===0)return a[0];let w=u.find(y=>y.includes(`/fui-${t}/`)&&(y.endsWith(".tsx")||y.endsWith(".jsx")));if(w)return w;let b=u.find(y=>y.toLowerCase().includes(`/${t}/${t}.tsx`)||y.includes(`/${i}/${i}.tsx`));if(b)return b;let S=u.find(y=>y.toLowerCase().endsWith(`/${t}.tsx`)||y.endsWith(`/${i}.tsx`));return S||u[0]},h=c(g),f=m(p),x=[...g,...p];return l.debug(`Discovered files for "${e}":`,{cssFile:h,componentFile:f,totalMatches:x.length}),{cssFile:h,componentFile:f,allMatches:[...new Set(x)]}}var ht=100;function gt(e){return new Promise(r=>setTimeout(r,e))}async function yt(e,r){if(await at(),!Z||!z)return l.debug(`Skipping validation (validator not available) for ${r}`),{valid:!0};let t=Z(e,r);if(!t.valid){let i=t.errors.map(n=>n.message).join("; ");return l.warn(`Code validation failed for ${r}:`),console.warn(z(t)),{valid:!1,error:i}}return t.warnings.length>0&&(l.warn(`Code validation warnings for ${r}:`),console.warn(z(t))),l.debug(`Validation passed for ${r}`),{valid:!0}}var Ce=!1;function Ee(e){if(Ce)return e;Ce=!0;let r=process.cwd();return l.debug("Apply fixes initialized"),l.debug("Workspace:",r),e.emit(xe,{path:r}),e.on(ft,()=>{l.debug("Workspace path requested by browser"),l.debug("Emitting workspace path response:",r),e.emit(xe,{path:r})}),e.on(mt,async t=>{let{componentName:i,storyId:n}=t;l.debug(`Discovering files for component: ${i}`);try{let o=await be(i,r);e.emit(Se,{componentName:i,storyId:n,...o,workspacePath:r})}catch(o){l.error("File discovery error:",o),e.emit(Se,{componentName:i,storyId:n,error:o.message,allMatches:[]})}}),e.on(ct,t=>{setTimeout(async()=>{try{let{issues:i,storybookRoot:n}=t,o=n||r;n?l.debug(`Using storybookRoot from API: ${n}`):l.debug(`Using process.cwd(): ${r}`),l.debug(`Received APPLY_FIXES for ${i.length} issue(s)`);let s=new Map;async function d(c){let m=c.targetFileType||"css",h=c.targetFilePath||c.generatedFix?.filePath,f="",x=c.title?.match(/^(\w+)\s/);if(x&&(f=x[1]),!f&&h){let w=h.match(/\/(\w+)\.(?:css|tsx|jsx)$/i);w&&(f=w[1])}if(!f)return l.debug(`Could not extract component name, using provided path: ${h}`),h||null;if(!s.has(f)){let w=await be(f,o);s.set(f,w)}let a=s.get(f),u=m==="css"?a.cssFile:a.componentFile;return u?(l.debug(`Discovered ${m} path: ${u} (was: ${h})`),u):(l.debug(`No ${m} file discovered, using provided: ${h}`),h||null)}let g=[];for(let c of i){let{generatedFix:m}=c,h=c.targetFilePath||m?.filePath,f=await d(c)||h;l.debug("Processing issue:",{id:c.id,type:c.type,targetFileType:c.targetFileType||"css",targetPath:f,providedPath:h!==f?h:"(same)",codeLength:m?.code?.length||0}),e.emit(lt,{issueId:c.id});try{if(!m||!m.code||!f)throw new Error("Missing AI-generated fix data (code or filePath)");l.debug("Code to write (first 200 chars):",m.code.substring(0,200)),l.debug(`Code length: ${m.code.length} chars`);let x=await yt(m.code,f);if(!x.valid)throw new Error(`Code validation failed: ${x.error}. Fix was not applied to prevent breaking the file.`);let a=j.isAbsolute(f)?f:j.join(o,f);l.debug(`Writing to absolute path: ${a}`),await ve.writeFile(a,m.code,"utf-8"),await gt(ht);let u={success:!0,issueId:c.id,filePath:f,timestamp:new Date};e.emit(dt,{issueId:c.id,result:u}),l.debug(`\u2713 Applied ${c.targetFileType||"css"} fix to: ${f}`),g.push(u)}catch(x){let a=x.message||"Unknown error";e.emit(ut,{issueId:c.id,error:a}),l.error(`\u2717 Error: ${a}`),g.push({success:!1,issueId:c.id,error:a,timestamp:new Date})}}let p={total:g.length,succeeded:g.filter(c=>c.success).length,failed:g.filter(c=>!c.success).length};e.emit(we,{results:g,summary:p}),l.debug(`Completed: ${p.succeeded}/${p.total} fixes applied`),p.succeeded>0&&e.emit(pt,{message:"Fixes applied. If Storybook crashes due to HMR, please restart it.",filesChanged:g.filter(c=>c.success).map(c=>c.filePath)})}catch(i){l.error("Fatal error during fix application:",i),e.emit(we,{results:[],summary:{total:t.issues?.length||0,succeeded:0,failed:t.issues?.length||0}})}},0)}),e}function Ie(e){let r=process.cwd();return e.plugins=e.plugins||[],e.plugins.push({name:"uicopilot-server-api",configureServer(t){t.middlewares.use("/__uicopilot/health",(o,s)=>{s.writeHead(200,{"Content-Type":"application/json"}),s.end(JSON.stringify({ok:!0,workspacePath:r}))}),t.middlewares.use("/__uicopilot/screenshot",async(o,s)=>{try{if(!await B()){s.writeHead(501,{"Content-Type":"application/json"}),s.end(JSON.stringify({error:"Puppeteer not installed. Run: npm install puppeteer"}));return}let p=new URL(o.url||"",`http://${o.headers.host}`).searchParams.get("storyId");if(!p){s.writeHead(400,{"Content-Type":"application/json"}),s.end(JSON.stringify({error:"Missing storyId parameter"}));return}let m=`http://${o.headers.host||"localhost:6006"}/iframe.html?viewMode=story&id=${p}&globals=`;l.debug(`Taking screenshot: ${p}`);let h=await q(m,{selector:"#storybook-root > *"});if(!h){s.writeHead(500,{"Content-Type":"application/json"}),s.end(JSON.stringify({error:"Screenshot capture failed"}));return}let f=h.toString("base64");s.writeHead(200,{"Content-Type":"application/json"}),s.end(JSON.stringify({screenshot:`data:image/png;base64,${f}`}))}catch(d){l.error("Screenshot error:",d.message),s.writeHead(500,{"Content-Type":"application/json"}),s.end(JSON.stringify({error:d.message}))}}),t.middlewares.use("/__uicopilot/capture",async(o,s)=>{try{if(!await B()){s.writeHead(501,{"Content-Type":"application/json"}),s.end(JSON.stringify({error:"Puppeteer not installed"}));return}let p=new URL(o.url||"",`http://${o.headers.host}`).searchParams.get("storyId");if(!p){s.writeHead(400,{"Content-Type":"application/json"}),s.end(JSON.stringify({error:"Missing storyId parameter"}));return}let m=`http://${o.headers.host||"localhost:6006"}/iframe.html?viewMode=story&id=${p}&globals=`;l.debug(`Full capture: ${p}`);let h=await q(m,{selector:"#storybook-root > *"});if(!h){s.writeHead(500,{"Content-Type":"application/json"}),s.end(JSON.stringify({error:"Screenshot capture failed"}));return}let f;try{f=(await import("puppeteer")).default}catch{f=(await import("puppeteer-core")).default}let x=await f.launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox"]}),a=await x.newPage();try{await a.setCacheEnabled(!1),await a.setViewport({width:800,height:600}),await a.goto(m,{waitUntil:"networkidle2",timeout:15e3}),await a.evaluate(()=>document.fonts.ready),await a.waitForSelector("#storybook-root > *",{timeout:1e4}),await a.evaluate(()=>new Promise(b=>{let S=setTimeout(b,5e3);try{let y=window.__STORYBOOK_ADDONS_CHANNEL__;if(y){let v=()=>{clearTimeout(S),y.off("storyRendered",v),setTimeout(b,100)};y.on("storyRendered",v)}else clearTimeout(S),setTimeout(b,300)}catch{clearTimeout(S),b()}}));let u=await a.evaluate(()=>{let b=document.querySelector("#storybook-root > *")||document.querySelector("#root > *"),S={};if(b){let C=window.getComputedStyle(b);for(let T=0;T<C.length;T++)S[C[T]]=C.getPropertyValue(C[T])}let y={backgroundColor:["transparent","rgba(0, 0, 0, 0)"],border:["none","0px none","0px none rgb(0, 0, 0)"],borderRadius:["0px"],boxShadow:["none"],opacity:["1"]};function v(C){return C.replace(/-([a-z])/g,(T,_)=>_.toUpperCase())}function I(C,T){if(T>4)return null;let _=C.tagName.toLowerCase();if(["script","style","link","meta","br","hr","noscript"].includes(_))return null;let O=C.className,R=typeof O=="string"?O:O?.baseVal||"",N=C.id||void 0,Q=C.getAttribute("role")||void 0,F;for(let P of Array.from(C.childNodes))if(P.nodeType===3){let E=P.textContent?.trim();if(E){F=E.length>50?E.substring(0,50)+"...":E;break}}let k=_;N?k=`${_}#${N}`:R&&(k=`${_}.${R.split(" ").filter(Boolean).join(".")}`);let Te=window.getComputedStyle(C),Pe=["background-color","border","border-radius","box-shadow","opacity","fill","stroke","stroke-width","font-size","font-family","font-weight","line-height","letter-spacing","color","text-align","display","padding","margin","gap","flex-direction","justify-content","align-items","width","height"],G={};for(let P of Pe){let E=Te.getPropertyValue(P),A=v(P);E&&!y[A]?.includes(E)&&(G[A]=E)}if(_==="svg"||C.closest("svg"))for(let P of["fill","stroke","stroke-width","viewBox","d","r","cx","cy"]){let E=C.getAttribute(P);E&&(G[v(P)]=E)}let ee=[];for(let P of Array.from(C.children)){let E=window.getComputedStyle(P);if(E.display==="none"||E.visibility==="hidden")continue;let A=I(P,T+1);A&&ee.push(A)}return{selector:k,tagName:_,className:R,id:N,role:Q,textContent:F,styles:G,children:ee}}return{computedStyles:S,domTree:b?I(b,0):null}}),w=h.toString("base64");s.writeHead(200,{"Content-Type":"application/json"}),s.end(JSON.stringify({screenshot:`data:image/png;base64,${w}`,computedStyles:u.computedStyles,domTree:u.domTree}))}finally{await a.close(),await x.close()}}catch(d){l.error("Capture error:",d.message),s.writeHead(500,{"Content-Type":"application/json"}),s.end(JSON.stringify({error:d.message}))}}),t.middlewares.use("/__uicopilot/screenshot-snapshot",async(o,s)=>{if(o.method!=="POST"){s.writeHead(405,{"Content-Type":"application/json"}),s.end(JSON.stringify({error:"POST required"}));return}try{if(!await B()){s.writeHead(501,{"Content-Type":"application/json"}),s.end(JSON.stringify({error:"Puppeteer not installed"}));return}let g=[];for await(let w of o)g.push(typeof w=="string"?Buffer.from(w):w);let p=JSON.parse(Buffer.concat(g).toString()),{html:c,stylesheetUrls:m,storyId:h}=p;if(!c){s.writeHead(400,{"Content-Type":"application/json"}),s.end(JSON.stringify({error:"Missing html in body"}));return}let x=`http://${o.headers.host||"localhost:6006"}`;l.debug(`Taking snapshot screenshot for ${h||"unknown"}`);let a=await de(c,m||[],x,{storyId:h});if(!a){s.writeHead(500,{"Content-Type":"application/json"}),s.end(JSON.stringify({error:"Snapshot screenshot failed"}));return}let u=a.toString("base64");s.writeHead(200,{"Content-Type":"application/json"}),s.end(JSON.stringify({screenshot:`data:image/png;base64,${u}`}))}catch(d){l.error("Snapshot screenshot error:",d.message),s.writeHead(500,{"Content-Type":"application/json"}),s.end(JSON.stringify({error:d.message}))}}),t.httpServer?.on("close",()=>{J().catch(()=>{})});let i=o=>{J().catch(()=>{}).finally(()=>{process.kill(process.pid,o)})},n=globalThis;n.__uicopilotShutdownRegistered||(n.__uicopilotShutdownRegistered=!0,process.once("SIGINT",()=>i("SIGINT")),process.once("SIGTERM",()=>i("SIGTERM")))}}),e}var M={},wt=()=>{if(typeof M<"u"&&M.url){let e=(0,K.fileURLToPath)(M.url),r=(0,$.dirname)(e);return(0,$.join)(r,"manager.mjs")}return(0,$.join)(__dirname,"manager.mjs")},xt=()=>{if(typeof M<"u"&&M.url){let e=(0,K.fileURLToPath)(M.url),r=(0,$.dirname)(e);return(0,$.join)(r,"preview.mjs")}return(0,$.join)(__dirname,"preview.mjs")};function St(e=[]){return[...e,wt()]}function bt(e=[]){return[...e,xt()]}0&&(module.exports={experimental_serverChannel,managerEntries,previewAnnotations,viteFinal});
package/dist/preset.mjs CHANGED
@@ -1,3 +1,3 @@
1
- var Se=Object.defineProperty;var be=(e,i)=>()=>(e&&(i=e(e=0)),i);var Ce=(e,i)=>{for(var t in i)Se(e,t,{get:i[t],enumerable:!0})};var oe={};Ce(oe,{detectFileType:()=>se,formatValidationResult:()=>Ye,isValidCode:()=>Je,validateCode:()=>re,validateCodeForFile:()=>ne});function Be(e,i={}){let t=i.minLength??ze;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 i=[/^[+-]{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 i)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 Ge(e){let i=e.split(`
2
- `).filter(o=>o.trim()),t=i.filter(o=>o.trim().startsWith("//")||o.trim().startsWith("/*")||o.trim().startsWith("*")||o.trim().startsWith("#"));if(i.length>0&&t.length/i.length>.8)return{code:"CODE_IS_INSTRUCTIONS",message:"Code appears to be mostly comments/instructions, not actual implementation.",severity:"error"};let s=[/^\/\/\s*(Change|Replace|Update|Modify|Add|Remove|Delete)\s+(from|to|this|the)/im,/^\/\/\s*To:/m,/^\/\/\s*From:/m];for(let o of s)if(o.test(e))return{code:"CODE_IS_INSTRUCTIONS",message:'Code contains instruction comments (e.g., "// Change from:" / "// To:") instead of actual code.',severity:"error"};return null}function We(e){let i={"{":"}","[":"]","(":")"},t=[],s=!1,o="",n=!1;for(let r=0;r<e.length;r++){let d=e[r],g=e[r-1];if((d==='"'||d==="'"||d==="`")&&g!=="\\"){s?d===o&&(s=!1,n=!1):(s=!0,o=d,d==="`"&&(n=!0));continue}if(!s){if(i[d])t.push(i[d]);else if(Object.values(i).includes(d)&&t.pop()!==d)return{code:"UNBALANCED_BRACES",message:`Unbalanced braces/brackets detected. Found unexpected '${d}'.`,severity:"warning"}}}return t.length>0?{code:"UNBALANCED_BRACES",message:`Unbalanced braces/brackets. Missing: ${t.reverse().join("")}`,severity:"warning"}:null}function ie(e,i={}){let t=[],s=[];e.includes("import ")||t.push({code:"TSX_MISSING_IMPORTS",message:"Component file missing import statements. A complete file must have imports.",severity:"error"}),e.includes("export ")||t.push({code:"TSX_MISSING_EXPORTS",message:"Component file missing exports. A complete file must export something.",severity:"error"});let o=/import\s+(?:React|\{[^}]*\})\s+from\s+['"]react['"]/.test(e);/<[A-Z][a-zA-Z]*|<[a-z]+[\s/>]/.test(e)&&!o&&s.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)||s.push({code:"TSX_NO_COMPONENT_DEF",message:"No clear component definition found. Expected function or const export.",severity:"warning"});let d=[{pattern:/\.\.\.\s*$/,message:'Code ends with "..." - likely truncated'},{pattern:/\/\/\s*\.\.\./m,message:'Contains "// ..." - likely incomplete'},{pattern:/{\s*\/\*\s*\.\.\.\s*\*\/\s*}/m,message:'Contains "{/* ... */}" placeholder'}];for(let{pattern:g,message:p}of d)g.test(e)&&t.push({code:"TSX_INCOMPLETE",message:p,severity:"error"});return{errors:t,warnings:s}}function Xe(e,i={}){let t=[],s=[];(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 n=(e.match(/\{[^}]+\}/g)||[]).length;return n===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"}),n>0&&n<3&&!i.allowPartial&&s.push({code:"CSS_FEW_RULES",message:`Only ${n} CSS rule(s) found. Might be incomplete.`,severity:"warning"}),{errors:t,warnings:s}}function qe(e,i={}){let t=[],s=[];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")||s.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")||s.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)||s.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:s}}function se(e){let i=e.toLowerCase();if(i.includes(".stories."))return"stories";switch(i.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 re(e,i,t={}){let s={valid:!0,fileType:i,errors:[],warnings:[]},o=Be(e,t);o&&s.errors.push(o);let n=je(e);n&&s.errors.push(n);let r=Ge(e);r&&s.errors.push(r);let d=We(e);switch(d&&(t.strict?s.errors.push({...d,severity:"error"}):s.warnings.push(d)),i){case"stories":{let{errors:g,warnings:p}=qe(e,t);s.errors.push(...g),s.warnings.push(...p);break}case"tsx":case"jsx":{let{errors:g,warnings:p}=ie(e,t);s.errors.push(...g),s.warnings.push(...p);break}case"css":case"scss":case"less":{let{errors:g,warnings:p}=Xe(e,t);s.errors.push(...g),s.warnings.push(...p);break}case"ts":case"js":{let{errors:g,warnings:p}=ie(e,t);s.errors.push(...g),s.warnings.push(...p.filter(c=>!c.code.includes("JSX")));break}default:break}return s.valid=s.errors.length===0,s}function ne(e,i,t={}){let s=se(i);return re(e,s,t)}function Je(e,i,t={}){return ne(e,i,t).valid}function Ye(e){if(e.valid&&e.warnings.length===0)return`\u2713 Valid ${e.fileType} code`;let i=[];if(e.valid)i.push(`\u26A0 Valid ${e.fileType} code with warnings`);else{i.push(`\u2717 Invalid ${e.fileType} code`),i.push(""),i.push("Errors:");for(let t of e.errors)i.push(` - [${t.code}] ${t.message}`)}if(e.warnings.length>0){i.push(""),i.push("Warnings:");for(let t of e.warnings)i.push(` - [${t.code}] ${t.message}`)}return i.join(`
3
- `)}var ze,ae=be(()=>{"use strict";ze=50});import{dirname as ge,join as U}from"path";import{fileURLToPath as ye}from"url";import*as he from"fs/promises";import*as V from"path";import{glob as ce}from"glob";import{existsSync as He}from"fs";import{createRequire as Ve}from"module";var B={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 k=`[${B.NAME}]`,l={debug:(...e)=>{ve()&&console.log(k,...e)},info:(...e)=>{console.log(k,...e)},warn:(...e)=>{console.warn(k,...e)},error:(...e)=>{console.error(k,...e)}};var ke=["flex","inline-flex"],Ae=["grid","inline-grid"],Rt=[...ke,...Ae];var A=null,$=null,Q=!1;async function j(){if(Q)return!!A;if(Q=!0,process.env.STORYBOOK_UICOPILOT_NO_PUPPETEER==="true")return l.debug("Puppeteer disabled via STORYBOOK_UICOPILOT_NO_PUPPETEER flag"),!1;let e=Ve(process.cwd()+"/");try{return A=e("puppeteer"),l.debug("Puppeteer loaded \u2014 server-side screenshots enabled"),!0}catch{}try{return A=e("puppeteer-core"),l.debug("puppeteer-core loaded \u2014 server-side screenshots enabled"),!0}catch{}return l.debug("Puppeteer not found \u2014 install puppeteer for pixel-perfect screenshots"),!1}function Ue(){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 i of e)if(He(i))return i}async function ee(){if($&&$.connected)return $;let e=Ue(),i={headless:!0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-dev-shm-usage"],...e?{executablePath:e}:{}};return $=await A.launch(i),l.debug("Headless Chrome launched for screenshots"),$}async function G(e,i){if(!await j())return null;let o=await(await ee()).newPage();try{await o.setCacheEnabled(!1),await o.setViewport({width:i?.width||800,height:i?.height||600,deviceScaleFactor:1}),await o.goto(e,{waitUntil:"networkidle2",timeout:15e3}),await o.evaluate(()=>document.fonts.ready),await o.waitForSelector("#storybook-root > *",{timeout:1e4}),await o.waitForFunction(()=>new Promise(p=>{let c=document.querySelectorAll("style").length,m=0,h=()=>{let f=document.querySelectorAll("style").length;if(f===c){if(m++,m>=3){p(!0);return}}else m=0,c=f;setTimeout(h,100)};setTimeout(h,200)}),{timeout:5e3}).catch(()=>{}),await new Promise(p=>setTimeout(p,500));let n=await o.evaluate(()=>{let p=document.querySelector("#storybook-root");if(!p)return null;let c=window.innerHeight,m=window.innerWidth,h=1/0,f=0,x=1/0,a=0,u=!1;function w(S){for(let y of Array.from(S.children)){let v=window.getComputedStyle(y);if(v.display==="none"||v.visibility==="hidden"||v.position==="fixed"||v.position==="absolute")continue;let T=y.getBoundingClientRect();if(T.height<=0||T.width<=0)continue;if((T.width>=m*.9||T.height>=c*.9)&&y.children.length>0){y.setAttribute("data-uic-drilled",""),w(y);continue}if(y.children.length===1){let E=v.backgroundColor,_=E==="rgba(0, 0, 0, 0)"||E==="transparent"||E==="",L=v.borderStyle!=="none"&&v.borderWidth!=="0px",M=v.boxShadow!=="none",O=!_||L||M,R=y.children[0].getBoundingClientRect(),N=R.width>=T.width*.95&&R.height>=T.height*.95;if(!O||N){y.setAttribute("data-uic-drilled",""),w(y);continue}}h=Math.min(h,T.top),f=Math.max(f,T.bottom),x=Math.min(x,T.left),a=Math.max(a,T.right),u=!0}}if(w(p),!u)return null;let b=document.createElement("style");return b.id="uic-drilled-bg-reset",b.textContent="[data-uic-drilled] { background: transparent !important; border-color: transparent !important; box-shadow: none !important; }",document.head.appendChild(b),document.body.offsetHeight,{top:h,bottom:f,left:x,right:a}});await o.evaluate(()=>new Promise(p=>requestAnimationFrame(()=>p())));let r=4,d=n?{x:Math.max(0,n.left-r),y:Math.max(0,n.top-r),width:Math.min(n.right-n.left+r*2,800),height:Math.min(n.bottom-n.top+r*2,600)}:void 0,g=await o.screenshot({type:"png",omitBackground:!0,...d?{clip:d}:{fullPage:!1}});return Buffer.from(g)}finally{await o.close()}}async function te(e,i,t,s){if(!await j())return null;let r=await(await ee()).newPage();try{await r.setCacheEnabled(!1),await r.setViewport({width:s?.width||800,height:s?.height||600,deviceScaleFactor:1});let d=s?.storyId||"",g=`${t}/iframe.html?viewMode=story&id=${d}&globals=`;await r.goto(g,{waitUntil:"load",timeout:15e3}),await r.waitForSelector("#storybook-root > *",{timeout:1e4}),await r.evaluate(m=>{let h=document.getElementById("storybook-root");h&&(h.innerHTML=m)},e),await r.evaluate(()=>document.fonts.ready),await new Promise(m=>setTimeout(m,500));let p=await r.evaluate(()=>{let m=document.querySelector("#storybook-root");if(!m)return null;let h=window.innerWidth;function f(u){let w=u.getBoundingClientRect();if(w.width===0||w.height===0)return null;if(w.width<h*.8&&w.height>0)return w;for(let b of Array.from(u.children)){let S=window.getComputedStyle(b);if(S.position==="fixed"||S.position==="absolute"||S.display==="none"||S.visibility==="hidden")continue;let y=f(b);if(y)return y}return null}let x=f(m);if(x)return{x:Math.max(0,x.x-8),y:Math.max(0,x.y-8),width:x.width+16,height:x.height+16};let a=m.firstElementChild;if(a){let u=a.getBoundingClientRect();return{x:u.x,y:u.y,width:u.width,height:u.height}}return null});if(!p)throw new Error("Could not determine component bounds from snapshot");let c=await r.screenshot({type:"png",clip:p});return Buffer.from(c)}finally{await r.close()}}async function D(){return j()}async function W(){$&&(await $.close(),$=null)}var X=null,H=null,le=!1;async function Ze(){if(!le){le=!0;try{let e=await Promise.resolve().then(()=>(ae(),oe));X=e.validateCodeForFile,H=e.formatValidationResult,l.debug("Code validator loaded - fix validation enabled")}catch{l.debug("Code validator not available - skipping fix validation")}}}var Ke="UICOPILOT/APPLY_FIXES",Qe="UICOPILOT/FIX_STARTED",et="UICOPILOT/FIX_COMPLETED",tt="UICOPILOT/FIX_FAILED",de="UICOPILOT/ALL_FIXES_APPLIED",it="UICOPILOT/RELOAD_REQUIRED",ue="UICOPILOT/WORKSPACE_PATH",st="UICOPILOT/REQUEST_WORKSPACE_PATH",rt="UICOPILOT/DISCOVER_COMPONENT_FILES",pe="UICOPILOT/COMPONENT_FILES_DISCOVERED";async function fe(e,i){let t=e.toLowerCase(),s=e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),o=[`src/**/fui-${t}/fui-${t}.css`,`src/**/fui-${t}/*.css`,`src/**/${t}/${t}.css`,`src/**/${s}/${s}.css`,`src/**/*${t}*.css`,`src/**/*${s}*.css`,`styles/**/*${t}*.css`],n=[`src/**/fui-${t}/fui-${t}.tsx`,`src/**/fui-${t}/*.tsx`,`src/**/${t}/${t}.tsx`,`src/**/${s}/${s}.tsx`,`src/**/*${s}*.tsx`,`src/**/*${s}*.jsx`],r=[],d=[];for(let a of o)try{let u=await ce(a,{cwd:i,nodir:!0,ignore:["**/node_modules/**","**/dist/**","**/.storybook/**"]});u.length>0&&r.push(...u)}catch{}for(let a of n)try{let u=await ce(a,{cwd:i,nodir:!0,ignore:["**/node_modules/**","**/dist/**","**/.storybook/**","**/*.stories.*","**/*.test.*"]});u.length>0&&d.push(...u)}catch{}let g=[...new Set(r)],p=[...new Set(d)],c=a=>{if(a.length===0)return;let u=a.find(S=>S.includes(`/fui-${t}/`)&&S.endsWith(".css"));if(u)return u;let w=a.find(S=>S.toLowerCase().includes(`/${t}/${t}.css`)||S.includes(`/${s}/${s}.css`));if(w)return w;let b=a.find(S=>S.toLowerCase().endsWith(`/${t}.css`)||S.endsWith(`/${s}.css`));return b||a[0]},m=a=>{if(a.length===0)return;let u=a.filter(y=>!y.includes(".stories.")&&!y.includes(".test."));if(u.length===0)return a[0];let w=u.find(y=>y.includes(`/fui-${t}/`)&&(y.endsWith(".tsx")||y.endsWith(".jsx")));if(w)return w;let b=u.find(y=>y.toLowerCase().includes(`/${t}/${t}.tsx`)||y.includes(`/${s}/${s}.tsx`));if(b)return b;let S=u.find(y=>y.toLowerCase().endsWith(`/${t}.tsx`)||y.endsWith(`/${s}.tsx`));return S||u[0]},h=c(g),f=m(p),x=[...g,...p];return l.debug(`Discovered files for "${e}":`,{cssFile:h,componentFile:f,totalMatches:x.length}),{cssFile:h,componentFile:f,allMatches:[...new Set(x)]}}var nt=100;function ot(e){return new Promise(i=>setTimeout(i,e))}async function at(e,i){if(await Ze(),!X||!H)return l.debug(`Skipping validation (validator not available) for ${i}`),{valid:!0};let t=X(e,i);if(!t.valid){let s=t.errors.map(o=>o.message).join("; ");return l.warn(`Code validation failed for ${i}:`),console.warn(H(t)),{valid:!1,error:s}}return t.warnings.length>0&&(l.warn(`Code validation warnings for ${i}:`),console.warn(H(t))),l.debug(`Validation passed for ${i}`),{valid:!0}}var me=!1;function ct(e){if(me)return e;me=!0;let i=process.cwd();return l.debug("Apply fixes initialized"),l.debug("Workspace:",i),e.emit(ue,{path:i}),e.on(st,()=>{l.debug("Workspace path requested by browser"),l.debug("Emitting workspace path response:",i),e.emit(ue,{path:i})}),e.on(rt,async t=>{let{componentName:s,storyId:o}=t;l.debug(`Discovering files for component: ${s}`);try{let n=await fe(s,i);e.emit(pe,{componentName:s,storyId:o,...n,workspacePath:i})}catch(n){l.error("File discovery error:",n),e.emit(pe,{componentName:s,storyId:o,error:n.message,allMatches:[]})}}),e.on(Ke,t=>{setTimeout(async()=>{try{let{issues:s,storybookRoot:o}=t,n=o||i;o?l.debug(`Using storybookRoot from API: ${o}`):l.debug(`Using process.cwd(): ${i}`),l.debug(`Received APPLY_FIXES for ${s.length} issue(s)`);let r=new Map;async function d(c){let m=c.targetFileType||"css",h=c.targetFilePath||c.generatedFix?.filePath,f="",x=c.title?.match(/^(\w+)\s/);if(x&&(f=x[1]),!f&&h){let w=h.match(/\/(\w+)\.(?:css|tsx|jsx)$/i);w&&(f=w[1])}if(!f)return l.debug(`Could not extract component name, using provided path: ${h}`),h||null;if(!r.has(f)){let w=await fe(f,n);r.set(f,w)}let a=r.get(f),u=m==="css"?a.cssFile:a.componentFile;return u?(l.debug(`Discovered ${m} path: ${u} (was: ${h})`),u):(l.debug(`No ${m} file discovered, using provided: ${h}`),h||null)}let g=[];for(let c of s){let{generatedFix:m}=c,h=c.targetFilePath||m?.filePath,f=await d(c)||h;l.debug("Processing issue:",{id:c.id,type:c.type,targetFileType:c.targetFileType||"css",targetPath:f,providedPath:h!==f?h:"(same)",codeLength:m?.code?.length||0}),e.emit(Qe,{issueId:c.id});try{if(!m||!m.code||!f)throw new Error("Missing AI-generated fix data (code or filePath)");l.debug("Code to write (first 200 chars):",m.code.substring(0,200)),l.debug(`Code length: ${m.code.length} chars`);let x=await at(m.code,f);if(!x.valid)throw new Error(`Code validation failed: ${x.error}. Fix was not applied to prevent breaking the file.`);let a=V.isAbsolute(f)?f:V.join(n,f);l.debug(`Writing to absolute path: ${a}`),await he.writeFile(a,m.code,"utf-8"),await ot(nt);let u={success:!0,issueId:c.id,filePath:f,timestamp:new Date};e.emit(et,{issueId:c.id,result:u}),l.debug(`\u2713 Applied ${c.targetFileType||"css"} fix to: ${f}`),g.push(u)}catch(x){let a=x.message||"Unknown error";e.emit(tt,{issueId:c.id,error:a}),l.error(`\u2717 Error: ${a}`),g.push({success:!1,issueId:c.id,error:a,timestamp:new Date})}}let p={total:g.length,succeeded:g.filter(c=>c.success).length,failed:g.filter(c=>!c.success).length};e.emit(de,{results:g,summary:p}),l.debug(`Completed: ${p.succeeded}/${p.total} fixes applied`),p.succeeded>0&&e.emit(it,{message:"Fixes applied. If Storybook crashes due to HMR, please restart it.",filesChanged:g.filter(c=>c.success).map(c=>c.filePath)})}catch(s){l.error("Fatal error during fix application:",s),e.emit(de,{results:[],summary:{total:t.issues?.length||0,succeeded:0,failed:t.issues?.length||0}})}},0)}),e}function lt(e){let i=process.cwd();return e.plugins=e.plugins||[],e.plugins.push({name:"uicopilot-server-api",configureServer(t){t.middlewares.use("/__uicopilot/health",(n,r)=>{r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({ok:!0,workspacePath:i}))}),t.middlewares.use("/__uicopilot/screenshot",async(n,r)=>{try{if(!await D()){r.writeHead(501,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Puppeteer not installed. Run: npm install puppeteer"}));return}let p=new URL(n.url||"",`http://${n.headers.host}`).searchParams.get("storyId");if(!p){r.writeHead(400,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Missing storyId parameter"}));return}let m=`http://${n.headers.host||"localhost:6006"}/iframe.html?viewMode=story&id=${p}&globals=`;l.debug(`Taking screenshot: ${p}`);let h=await G(m,{selector:"#storybook-root > *"});if(!h){r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Screenshot capture failed"}));return}let f=h.toString("base64");r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({screenshot:`data:image/png;base64,${f}`}))}catch(d){l.error("Screenshot error:",d.message),r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:d.message}))}}),t.middlewares.use("/__uicopilot/capture",async(n,r)=>{try{if(!await D()){r.writeHead(501,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Puppeteer not installed"}));return}let p=new URL(n.url||"",`http://${n.headers.host}`).searchParams.get("storyId");if(!p){r.writeHead(400,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Missing storyId parameter"}));return}let m=`http://${n.headers.host||"localhost:6006"}/iframe.html?viewMode=story&id=${p}&globals=`;l.debug(`Full capture: ${p}`);let h=await G(m,{selector:"#storybook-root > *"});if(!h){r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Screenshot capture failed"}));return}let f;try{f=(await import("puppeteer")).default}catch{f=(await import("puppeteer-core")).default}let x=await f.launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox"]}),a=await x.newPage();try{await a.setCacheEnabled(!1),await a.setViewport({width:800,height:600}),await a.goto(m,{waitUntil:"networkidle2",timeout:15e3}),await a.evaluate(()=>document.fonts.ready),await a.waitForSelector("#storybook-root > *",{timeout:1e4}),await a.evaluate(()=>new Promise(b=>{let S=setTimeout(b,5e3);try{let y=window.__STORYBOOK_ADDONS_CHANNEL__;if(y){let v=()=>{clearTimeout(S),y.off("storyRendered",v),setTimeout(b,100)};y.on("storyRendered",v)}else clearTimeout(S),setTimeout(b,300)}catch{clearTimeout(S),b()}}));let u=await a.evaluate(()=>{let b=document.querySelector("#storybook-root > *")||document.querySelector("#root > *"),S={};if(b){let C=window.getComputedStyle(b);for(let E=0;E<C.length;E++)S[C[E]]=C.getPropertyValue(C[E])}let y={backgroundColor:["transparent","rgba(0, 0, 0, 0)"],border:["none","0px none","0px none rgb(0, 0, 0)"],borderRadius:["0px"],boxShadow:["none"],opacity:["1"]};function v(C){return C.replace(/-([a-z])/g,(E,_)=>_.toUpperCase())}function T(C,E){if(E>4)return null;let _=C.tagName.toLowerCase();if(["script","style","link","meta","br","hr","noscript"].includes(_))return null;let L=C.className,M=typeof L=="string"?L:L?.baseVal||"",O=C.id||void 0,q=C.getAttribute("role")||void 0,R;for(let P of Array.from(C.childNodes))if(P.nodeType===3){let I=P.textContent?.trim();if(I){R=I.length>50?I.substring(0,50)+"...":I;break}}let N=_;O?N=`${_}#${O}`:M&&(N=`${_}.${M.split(" ").filter(Boolean).join(".")}`);let we=window.getComputedStyle(C),xe=["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"],z={};for(let P of xe){let I=we.getPropertyValue(P),F=v(P);I&&!y[F]?.includes(I)&&(z[F]=I)}if(_==="svg"||C.closest("svg"))for(let P of["fill","stroke","stroke-width","viewBox","d","r","cx","cy"]){let I=C.getAttribute(P);I&&(z[v(P)]=I)}let J=[];for(let P of Array.from(C.children)){let I=window.getComputedStyle(P);if(I.display==="none"||I.visibility==="hidden")continue;let F=T(P,E+1);F&&J.push(F)}return{selector:N,tagName:_,className:M,id:O,role:q,textContent:R,styles:z,children:J}}return{computedStyles:S,domTree:b?T(b,0):null}}),w=h.toString("base64");r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({screenshot:`data:image/png;base64,${w}`,computedStyles:u.computedStyles,domTree:u.domTree}))}finally{await a.close(),await x.close()}}catch(d){l.error("Capture error:",d.message),r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:d.message}))}}),t.middlewares.use("/__uicopilot/screenshot-snapshot",async(n,r)=>{if(n.method!=="POST"){r.writeHead(405,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"POST required"}));return}try{if(!await D()){r.writeHead(501,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Puppeteer not installed"}));return}let g=[];for await(let w of n)g.push(typeof w=="string"?Buffer.from(w):w);let p=JSON.parse(Buffer.concat(g).toString()),{html:c,stylesheetUrls:m,storyId:h}=p;if(!c){r.writeHead(400,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Missing html in body"}));return}let x=`http://${n.headers.host||"localhost:6006"}`;l.debug(`Taking snapshot screenshot for ${h||"unknown"}`);let a=await te(c,m||[],x,{storyId:h});if(!a){r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Snapshot screenshot failed"}));return}let u=a.toString("base64");r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({screenshot:`data:image/png;base64,${u}`}))}catch(d){l.error("Snapshot screenshot error:",d.message),r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:d.message}))}}),t.httpServer?.on("close",()=>{W().catch(()=>{})});let s=n=>{W().catch(()=>{}).finally(()=>{process.kill(process.pid,n)})},o=globalThis;o.__uicopilotShutdownRegistered||(o.__uicopilotShutdownRegistered=!0,process.once("SIGINT",()=>s("SIGINT")),process.once("SIGTERM",()=>s("SIGTERM")))}}),e}var dt=()=>{if(typeof import.meta<"u"&&import.meta.url){let e=ye(import.meta.url),i=ge(e);return U(i,"manager.mjs")}return U(__dirname,"manager.mjs")},ut=()=>{if(typeof import.meta<"u"&&import.meta.url){let e=ye(import.meta.url),i=ge(e);return U(i,"preview.mjs")}return U(__dirname,"preview.mjs")};function pi(e=[]){return[...e,dt()]}function fi(e=[]){return[...e,ut()]}export{ct as experimental_serverChannel,pi as managerEntries,fi as previewAnnotations,lt as viteFinal};
1
+ var Se=Object.defineProperty;var be=(e,r)=>()=>(e&&(r=e(e=0)),r);var Ce=(e,r)=>{for(var t in r)Se(e,t,{get:r[t],enumerable:!0})};var oe={};Ce(oe,{detectFileType:()=>ie,formatValidationResult:()=>Ye,isValidCode:()=>Je,validateCode:()=>se,validateCodeForFile:()=>ne});function ze(e,r={}){let t=r.minLength??Be;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 r=[/^[+-]{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 r)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 Ge(e){let r=e.split(`
2
+ `).filter(o=>o.trim()),t=r.filter(o=>o.trim().startsWith("//")||o.trim().startsWith("/*")||o.trim().startsWith("*")||o.trim().startsWith("#"));if(r.length>0&&t.length/r.length>.8)return{code:"CODE_IS_INSTRUCTIONS",message:"Code appears to be mostly comments/instructions, not actual implementation.",severity:"error"};let i=[/^\/\/\s*(Change|Replace|Update|Modify|Add|Remove|Delete)\s+(from|to|this|the)/im,/^\/\/\s*To:/m,/^\/\/\s*From:/m];for(let o of i)if(o.test(e))return{code:"CODE_IS_INSTRUCTIONS",message:'Code contains instruction comments (e.g., "// Change from:" / "// To:") instead of actual code.',severity:"error"};return null}function We(e){let r={"{":"}","[":"]","(":")"},t=[],i=!1,o="",n=!1;for(let s=0;s<e.length;s++){let d=e[s],g=e[s-1];if((d==='"'||d==="'"||d==="`")&&g!=="\\"){i?d===o&&(i=!1,n=!1):(i=!0,o=d,d==="`"&&(n=!0));continue}if(!i){if(r[d])t.push(r[d]);else if(Object.values(r).includes(d)&&t.pop()!==d)return{code:"UNBALANCED_BRACES",message:`Unbalanced braces/brackets detected. Found unexpected '${d}'.`,severity:"warning"}}}return t.length>0?{code:"UNBALANCED_BRACES",message:`Unbalanced braces/brackets. Missing: ${t.reverse().join("")}`,severity:"warning"}:null}function re(e,r={}){let t=[],i=[];e.includes("import ")||t.push({code:"TSX_MISSING_IMPORTS",message:"Component file missing import statements. A complete file must have imports.",severity:"error"}),e.includes("export ")||t.push({code:"TSX_MISSING_EXPORTS",message:"Component file missing exports. A complete file must export something.",severity:"error"});let o=/import\s+(?:React|\{[^}]*\})\s+from\s+['"]react['"]/.test(e);/<[A-Z][a-zA-Z]*|<[a-z]+[\s/>]/.test(e)&&!o&&i.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)||i.push({code:"TSX_NO_COMPONENT_DEF",message:"No clear component definition found. Expected function or const export.",severity:"warning"});let d=[{pattern:/\.\.\.\s*$/,message:'Code ends with "..." - likely truncated'},{pattern:/\/\/\s*\.\.\./m,message:'Contains "// ..." - likely incomplete'},{pattern:/{\s*\/\*\s*\.\.\.\s*\*\/\s*}/m,message:'Contains "{/* ... */}" placeholder'}];for(let{pattern:g,message:p}of d)g.test(e)&&t.push({code:"TSX_INCOMPLETE",message:p,severity:"error"});return{errors:t,warnings:i}}function Xe(e,r={}){let t=[],i=[];(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 n=(e.match(/\{[^}]+\}/g)||[]).length;return n===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"}),n>0&&n<3&&!r.allowPartial&&i.push({code:"CSS_FEW_RULES",message:`Only ${n} CSS rule(s) found. Might be incomplete.`,severity:"warning"}),{errors:t,warnings:i}}function qe(e,r={}){let t=[],i=[];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")||i.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")||i.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)||i.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:i}}function ie(e){let r=e.toLowerCase();if(r.includes(".stories."))return"stories";switch(r.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 se(e,r,t={}){let i={valid:!0,fileType:r,errors:[],warnings:[]},o=ze(e,t);o&&i.errors.push(o);let n=je(e);n&&i.errors.push(n);let s=Ge(e);s&&i.errors.push(s);let d=We(e);switch(d&&(t.strict?i.errors.push({...d,severity:"error"}):i.warnings.push(d)),r){case"stories":{let{errors:g,warnings:p}=qe(e,t);i.errors.push(...g),i.warnings.push(...p);break}case"tsx":case"jsx":{let{errors:g,warnings:p}=re(e,t);i.errors.push(...g),i.warnings.push(...p);break}case"css":case"scss":case"less":{let{errors:g,warnings:p}=Xe(e,t);i.errors.push(...g),i.warnings.push(...p);break}case"ts":case"js":{let{errors:g,warnings:p}=re(e,t);i.errors.push(...g),i.warnings.push(...p.filter(c=>!c.code.includes("JSX")));break}default:break}return i.valid=i.errors.length===0,i}function ne(e,r,t={}){let i=ie(r);return se(e,i,t)}function Je(e,r,t={}){return ne(e,r,t).valid}function Ye(e){if(e.valid&&e.warnings.length===0)return`\u2713 Valid ${e.fileType} code`;let r=[];if(e.valid)r.push(`\u26A0 Valid ${e.fileType} code with warnings`);else{r.push(`\u2717 Invalid ${e.fileType} code`),r.push(""),r.push("Errors:");for(let t of e.errors)r.push(` - [${t.code}] ${t.message}`)}if(e.warnings.length>0){r.push(""),r.push("Warnings:");for(let t of e.warnings)r.push(` - [${t.code}] ${t.message}`)}return r.join(`
3
+ `)}var Be,ae=be(()=>{"use strict";Be=50});import{dirname as ge,join as U}from"path";import{fileURLToPath as ye}from"url";import*as he from"fs/promises";import*as V from"path";import{glob as ce}from"glob";import{existsSync as He}from"fs";import{createRequire as Ve}from"module";var z={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 k=`[${z.NAME}]`,l={debug:(...e)=>{ve()&&console.log(k,...e)},info:(...e)=>{console.log(k,...e)},warn:(...e)=>{console.warn(k,...e)},error:(...e)=>{console.error(k,...e)}};var ke=["flex","inline-flex"],Ae=["grid","inline-grid"],Nt=[...ke,...Ae];var A=null,L=null,Q=!1;async function j(){if(Q)return!!A;if(Q=!0,process.env.STORYBOOK_UICOPILOT_NO_PUPPETEER==="true")return l.debug("Puppeteer disabled via STORYBOOK_UICOPILOT_NO_PUPPETEER flag"),!1;let e=Ve(process.cwd()+"/");try{return A=e("puppeteer"),l.debug("Puppeteer loaded \u2014 server-side screenshots enabled"),!0}catch{}try{return A=e("puppeteer-core"),l.debug("puppeteer-core loaded \u2014 server-side screenshots enabled"),!0}catch{}return l.debug("Puppeteer not found \u2014 install puppeteer for pixel-perfect screenshots"),!1}function Ue(){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 r of e)if(He(r))return r}async function ee(){if(L&&L.connected)return L;let e=Ue(),r={headless:!0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-dev-shm-usage"],...e?{executablePath:e}:{}};return L=await A.launch(r),l.debug("Headless Chrome launched for screenshots"),L}async function G(e,r){if(!await j())return null;let o=await(await ee()).newPage();try{await o.setCacheEnabled(!1),await o.setViewport({width:r?.width||800,height:r?.height||600,deviceScaleFactor:1}),await o.goto(e,{waitUntil:"networkidle2",timeout:15e3}),await o.evaluate(()=>document.fonts.ready),await o.waitForSelector("#storybook-root > *",{timeout:1e4}),await o.waitForFunction(()=>new Promise(p=>{let c=document.querySelectorAll("style").length,m=0,h=()=>{let f=document.querySelectorAll("style").length;if(f===c){if(m++,m>=3){p(!0);return}}else m=0,c=f;setTimeout(h,100)};setTimeout(h,200)}),{timeout:5e3}).catch(()=>{}),await new Promise(p=>setTimeout(p,500));let n=await o.evaluate(()=>{let p=document.querySelector("#storybook-root");if(!p)return null;let c=window.innerHeight,m=window.innerWidth,h=1/0,f=0,x=1/0,a=0,u=!1;function w(S){for(let y of Array.from(S.children)){let v=window.getComputedStyle(y);if(v.display==="none"||v.visibility==="hidden"||v.position==="fixed"||v.position==="absolute")continue;let I=y.getBoundingClientRect();if(I.height<=0||I.width<=0)continue;if((I.width>=m*.9||I.height>=c*.9)&&y.children.length>0){y.setAttribute("data-uic-drilled",""),w(y);continue}if(y.children.length===1){let T=v.backgroundColor,_=T==="rgba(0, 0, 0, 0)"||T==="transparent"||T==="",$=v.borderStyle!=="none"&&v.borderWidth!=="0px",M=v.boxShadow!=="none",O=!_||$||M,R=y.children[0].getBoundingClientRect(),N=R.width>=I.width*.95&&R.height>=I.height*.95;if(!O||N){y.setAttribute("data-uic-drilled",""),w(y);continue}}h=Math.min(h,I.top),f=Math.max(f,I.bottom),x=Math.min(x,I.left),a=Math.max(a,I.right),u=!0}}if(w(p),!u)return null;let b=document.createElement("style");return b.id="uic-drilled-bg-reset",b.textContent="[data-uic-drilled] { background: transparent !important; border-color: transparent !important; box-shadow: none !important; }",document.head.appendChild(b),document.body.offsetHeight,{top:h,bottom:f,left:x,right:a}});await o.evaluate(()=>new Promise(p=>requestAnimationFrame(()=>p())));let s=4,d=n?{x:Math.max(0,n.left-s),y:Math.max(0,n.top-s),width:Math.min(n.right-n.left+s*2,800),height:Math.min(n.bottom-n.top+s*2,600)}:void 0,g=await o.screenshot({type:"png",omitBackground:!0,...d?{clip:d}:{fullPage:!1}});return Buffer.from(g)}finally{await o.close()}}async function te(e,r,t,i){if(!await j())return null;let s=await(await ee()).newPage();try{await s.setCacheEnabled(!1),await s.setViewport({width:i?.width||800,height:i?.height||600,deviceScaleFactor:1});let d=i?.storyId||"",g=`${t}/iframe.html?viewMode=story&id=${d}&globals=`;await s.goto(g,{waitUntil:"load",timeout:15e3}),await s.waitForSelector("#storybook-root > *",{timeout:1e4}),await s.evaluate(m=>{let h=document.getElementById("storybook-root");h&&(h.innerHTML=m)},e),await s.evaluate(()=>document.fonts.ready),await new Promise(m=>setTimeout(m,500));let p=await s.evaluate(()=>{let m=document.querySelector("#storybook-root");if(!m)return null;let h=window.innerWidth;function f(u){let w=u.getBoundingClientRect();if(w.width===0||w.height===0)return null;if(w.width<h*.8&&w.height>0)return w;for(let b of Array.from(u.children)){let S=window.getComputedStyle(b);if(S.position==="fixed"||S.position==="absolute"||S.display==="none"||S.visibility==="hidden")continue;let y=f(b);if(y)return y}return null}let x=f(m);if(x)return{x:Math.max(0,x.x-8),y:Math.max(0,x.y-8),width:x.width+16,height:x.height+16};let a=m.firstElementChild;if(a){let u=a.getBoundingClientRect();return{x:u.x,y:u.y,width:u.width,height:u.height}}return null});if(!p)throw new Error("Could not determine component bounds from snapshot");let c=await s.screenshot({type:"png",clip:p});return Buffer.from(c)}finally{await s.close()}}async function D(){return j()}async function W(){L&&(await L.close(),L=null)}var X=null,H=null,le=!1;async function Ze(){if(!le){le=!0;try{let e=await Promise.resolve().then(()=>(ae(),oe));X=e.validateCodeForFile,H=e.formatValidationResult,l.debug("Code validator loaded - fix validation enabled")}catch{l.debug("Code validator not available - skipping fix validation")}}}var Ke="UICOPILOT/APPLY_FIXES",Qe="UICOPILOT/FIX_STARTED",et="UICOPILOT/FIX_COMPLETED",tt="UICOPILOT/FIX_FAILED",de="UICOPILOT/ALL_FIXES_APPLIED",rt="UICOPILOT/RELOAD_REQUIRED",ue="UICOPILOT/WORKSPACE_PATH",it="UICOPILOT/REQUEST_WORKSPACE_PATH",st="UICOPILOT/DISCOVER_COMPONENT_FILES",pe="UICOPILOT/COMPONENT_FILES_DISCOVERED";async function fe(e,r){let t=e.toLowerCase(),i=e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),o=[`src/**/fui-${t}/fui-${t}.css`,`src/**/fui-${t}/*.css`,`src/**/${t}/${t}.css`,`src/**/${i}/${i}.css`,`src/**/*${t}*.css`,`src/**/*${i}*.css`,`styles/**/*${t}*.css`],n=[`src/**/fui-${t}/fui-${t}.tsx`,`src/**/fui-${t}/*.tsx`,`src/**/${t}/${t}.tsx`,`src/**/${i}/${i}.tsx`,`src/**/*${i}*.tsx`,`src/**/*${i}*.jsx`],s=[],d=[];for(let a of o)try{let u=await ce(a,{cwd:r,nodir:!0,ignore:["**/node_modules/**","**/dist/**","**/.storybook/**"]});u.length>0&&s.push(...u)}catch{}for(let a of n)try{let u=await ce(a,{cwd:r,nodir:!0,ignore:["**/node_modules/**","**/dist/**","**/.storybook/**","**/*.stories.*","**/*.test.*"]});u.length>0&&d.push(...u)}catch{}let g=[...new Set(s)],p=[...new Set(d)],c=a=>{if(a.length===0)return;let u=a.find(S=>S.includes(`/fui-${t}/`)&&S.endsWith(".css"));if(u)return u;let w=a.find(S=>S.toLowerCase().includes(`/${t}/${t}.css`)||S.includes(`/${i}/${i}.css`));if(w)return w;let b=a.find(S=>S.toLowerCase().endsWith(`/${t}.css`)||S.endsWith(`/${i}.css`));return b||a[0]},m=a=>{if(a.length===0)return;let u=a.filter(y=>!y.includes(".stories.")&&!y.includes(".test."));if(u.length===0)return a[0];let w=u.find(y=>y.includes(`/fui-${t}/`)&&(y.endsWith(".tsx")||y.endsWith(".jsx")));if(w)return w;let b=u.find(y=>y.toLowerCase().includes(`/${t}/${t}.tsx`)||y.includes(`/${i}/${i}.tsx`));if(b)return b;let S=u.find(y=>y.toLowerCase().endsWith(`/${t}.tsx`)||y.endsWith(`/${i}.tsx`));return S||u[0]},h=c(g),f=m(p),x=[...g,...p];return l.debug(`Discovered files for "${e}":`,{cssFile:h,componentFile:f,totalMatches:x.length}),{cssFile:h,componentFile:f,allMatches:[...new Set(x)]}}var nt=100;function ot(e){return new Promise(r=>setTimeout(r,e))}async function at(e,r){if(await Ze(),!X||!H)return l.debug(`Skipping validation (validator not available) for ${r}`),{valid:!0};let t=X(e,r);if(!t.valid){let i=t.errors.map(o=>o.message).join("; ");return l.warn(`Code validation failed for ${r}:`),console.warn(H(t)),{valid:!1,error:i}}return t.warnings.length>0&&(l.warn(`Code validation warnings for ${r}:`),console.warn(H(t))),l.debug(`Validation passed for ${r}`),{valid:!0}}var me=!1;function ct(e){if(me)return e;me=!0;let r=process.cwd();return l.debug("Apply fixes initialized"),l.debug("Workspace:",r),e.emit(ue,{path:r}),e.on(it,()=>{l.debug("Workspace path requested by browser"),l.debug("Emitting workspace path response:",r),e.emit(ue,{path:r})}),e.on(st,async t=>{let{componentName:i,storyId:o}=t;l.debug(`Discovering files for component: ${i}`);try{let n=await fe(i,r);e.emit(pe,{componentName:i,storyId:o,...n,workspacePath:r})}catch(n){l.error("File discovery error:",n),e.emit(pe,{componentName:i,storyId:o,error:n.message,allMatches:[]})}}),e.on(Ke,t=>{setTimeout(async()=>{try{let{issues:i,storybookRoot:o}=t,n=o||r;o?l.debug(`Using storybookRoot from API: ${o}`):l.debug(`Using process.cwd(): ${r}`),l.debug(`Received APPLY_FIXES for ${i.length} issue(s)`);let s=new Map;async function d(c){let m=c.targetFileType||"css",h=c.targetFilePath||c.generatedFix?.filePath,f="",x=c.title?.match(/^(\w+)\s/);if(x&&(f=x[1]),!f&&h){let w=h.match(/\/(\w+)\.(?:css|tsx|jsx)$/i);w&&(f=w[1])}if(!f)return l.debug(`Could not extract component name, using provided path: ${h}`),h||null;if(!s.has(f)){let w=await fe(f,n);s.set(f,w)}let a=s.get(f),u=m==="css"?a.cssFile:a.componentFile;return u?(l.debug(`Discovered ${m} path: ${u} (was: ${h})`),u):(l.debug(`No ${m} file discovered, using provided: ${h}`),h||null)}let g=[];for(let c of i){let{generatedFix:m}=c,h=c.targetFilePath||m?.filePath,f=await d(c)||h;l.debug("Processing issue:",{id:c.id,type:c.type,targetFileType:c.targetFileType||"css",targetPath:f,providedPath:h!==f?h:"(same)",codeLength:m?.code?.length||0}),e.emit(Qe,{issueId:c.id});try{if(!m||!m.code||!f)throw new Error("Missing AI-generated fix data (code or filePath)");l.debug("Code to write (first 200 chars):",m.code.substring(0,200)),l.debug(`Code length: ${m.code.length} chars`);let x=await at(m.code,f);if(!x.valid)throw new Error(`Code validation failed: ${x.error}. Fix was not applied to prevent breaking the file.`);let a=V.isAbsolute(f)?f:V.join(n,f);l.debug(`Writing to absolute path: ${a}`),await he.writeFile(a,m.code,"utf-8"),await ot(nt);let u={success:!0,issueId:c.id,filePath:f,timestamp:new Date};e.emit(et,{issueId:c.id,result:u}),l.debug(`\u2713 Applied ${c.targetFileType||"css"} fix to: ${f}`),g.push(u)}catch(x){let a=x.message||"Unknown error";e.emit(tt,{issueId:c.id,error:a}),l.error(`\u2717 Error: ${a}`),g.push({success:!1,issueId:c.id,error:a,timestamp:new Date})}}let p={total:g.length,succeeded:g.filter(c=>c.success).length,failed:g.filter(c=>!c.success).length};e.emit(de,{results:g,summary:p}),l.debug(`Completed: ${p.succeeded}/${p.total} fixes applied`),p.succeeded>0&&e.emit(rt,{message:"Fixes applied. If Storybook crashes due to HMR, please restart it.",filesChanged:g.filter(c=>c.success).map(c=>c.filePath)})}catch(i){l.error("Fatal error during fix application:",i),e.emit(de,{results:[],summary:{total:t.issues?.length||0,succeeded:0,failed:t.issues?.length||0}})}},0)}),e}function lt(e){let r=process.cwd();return e.plugins=e.plugins||[],e.plugins.push({name:"uicopilot-server-api",configureServer(t){t.middlewares.use("/__uicopilot/health",(n,s)=>{s.writeHead(200,{"Content-Type":"application/json"}),s.end(JSON.stringify({ok:!0,workspacePath:r}))}),t.middlewares.use("/__uicopilot/screenshot",async(n,s)=>{try{if(!await D()){s.writeHead(501,{"Content-Type":"application/json"}),s.end(JSON.stringify({error:"Puppeteer not installed. Run: npm install puppeteer"}));return}let p=new URL(n.url||"",`http://${n.headers.host}`).searchParams.get("storyId");if(!p){s.writeHead(400,{"Content-Type":"application/json"}),s.end(JSON.stringify({error:"Missing storyId parameter"}));return}let m=`http://${n.headers.host||"localhost:6006"}/iframe.html?viewMode=story&id=${p}&globals=`;l.debug(`Taking screenshot: ${p}`);let h=await G(m,{selector:"#storybook-root > *"});if(!h){s.writeHead(500,{"Content-Type":"application/json"}),s.end(JSON.stringify({error:"Screenshot capture failed"}));return}let f=h.toString("base64");s.writeHead(200,{"Content-Type":"application/json"}),s.end(JSON.stringify({screenshot:`data:image/png;base64,${f}`}))}catch(d){l.error("Screenshot error:",d.message),s.writeHead(500,{"Content-Type":"application/json"}),s.end(JSON.stringify({error:d.message}))}}),t.middlewares.use("/__uicopilot/capture",async(n,s)=>{try{if(!await D()){s.writeHead(501,{"Content-Type":"application/json"}),s.end(JSON.stringify({error:"Puppeteer not installed"}));return}let p=new URL(n.url||"",`http://${n.headers.host}`).searchParams.get("storyId");if(!p){s.writeHead(400,{"Content-Type":"application/json"}),s.end(JSON.stringify({error:"Missing storyId parameter"}));return}let m=`http://${n.headers.host||"localhost:6006"}/iframe.html?viewMode=story&id=${p}&globals=`;l.debug(`Full capture: ${p}`);let h=await G(m,{selector:"#storybook-root > *"});if(!h){s.writeHead(500,{"Content-Type":"application/json"}),s.end(JSON.stringify({error:"Screenshot capture failed"}));return}let f;try{f=(await import("puppeteer")).default}catch{f=(await import("puppeteer-core")).default}let x=await f.launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox"]}),a=await x.newPage();try{await a.setCacheEnabled(!1),await a.setViewport({width:800,height:600}),await a.goto(m,{waitUntil:"networkidle2",timeout:15e3}),await a.evaluate(()=>document.fonts.ready),await a.waitForSelector("#storybook-root > *",{timeout:1e4}),await a.evaluate(()=>new Promise(b=>{let S=setTimeout(b,5e3);try{let y=window.__STORYBOOK_ADDONS_CHANNEL__;if(y){let v=()=>{clearTimeout(S),y.off("storyRendered",v),setTimeout(b,100)};y.on("storyRendered",v)}else clearTimeout(S),setTimeout(b,300)}catch{clearTimeout(S),b()}}));let u=await a.evaluate(()=>{let b=document.querySelector("#storybook-root > *")||document.querySelector("#root > *"),S={};if(b){let C=window.getComputedStyle(b);for(let T=0;T<C.length;T++)S[C[T]]=C.getPropertyValue(C[T])}let y={backgroundColor:["transparent","rgba(0, 0, 0, 0)"],border:["none","0px none","0px none rgb(0, 0, 0)"],borderRadius:["0px"],boxShadow:["none"],opacity:["1"]};function v(C){return C.replace(/-([a-z])/g,(T,_)=>_.toUpperCase())}function I(C,T){if(T>4)return null;let _=C.tagName.toLowerCase();if(["script","style","link","meta","br","hr","noscript"].includes(_))return null;let $=C.className,M=typeof $=="string"?$:$?.baseVal||"",O=C.id||void 0,q=C.getAttribute("role")||void 0,R;for(let P of Array.from(C.childNodes))if(P.nodeType===3){let E=P.textContent?.trim();if(E){R=E.length>50?E.substring(0,50)+"...":E;break}}let N=_;O?N=`${_}#${O}`:M&&(N=`${_}.${M.split(" ").filter(Boolean).join(".")}`);let we=window.getComputedStyle(C),xe=["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"],B={};for(let P of xe){let E=we.getPropertyValue(P),F=v(P);E&&!y[F]?.includes(E)&&(B[F]=E)}if(_==="svg"||C.closest("svg"))for(let P of["fill","stroke","stroke-width","viewBox","d","r","cx","cy"]){let E=C.getAttribute(P);E&&(B[v(P)]=E)}let J=[];for(let P of Array.from(C.children)){let E=window.getComputedStyle(P);if(E.display==="none"||E.visibility==="hidden")continue;let F=I(P,T+1);F&&J.push(F)}return{selector:N,tagName:_,className:M,id:O,role:q,textContent:R,styles:B,children:J}}return{computedStyles:S,domTree:b?I(b,0):null}}),w=h.toString("base64");s.writeHead(200,{"Content-Type":"application/json"}),s.end(JSON.stringify({screenshot:`data:image/png;base64,${w}`,computedStyles:u.computedStyles,domTree:u.domTree}))}finally{await a.close(),await x.close()}}catch(d){l.error("Capture error:",d.message),s.writeHead(500,{"Content-Type":"application/json"}),s.end(JSON.stringify({error:d.message}))}}),t.middlewares.use("/__uicopilot/screenshot-snapshot",async(n,s)=>{if(n.method!=="POST"){s.writeHead(405,{"Content-Type":"application/json"}),s.end(JSON.stringify({error:"POST required"}));return}try{if(!await D()){s.writeHead(501,{"Content-Type":"application/json"}),s.end(JSON.stringify({error:"Puppeteer not installed"}));return}let g=[];for await(let w of n)g.push(typeof w=="string"?Buffer.from(w):w);let p=JSON.parse(Buffer.concat(g).toString()),{html:c,stylesheetUrls:m,storyId:h}=p;if(!c){s.writeHead(400,{"Content-Type":"application/json"}),s.end(JSON.stringify({error:"Missing html in body"}));return}let x=`http://${n.headers.host||"localhost:6006"}`;l.debug(`Taking snapshot screenshot for ${h||"unknown"}`);let a=await te(c,m||[],x,{storyId:h});if(!a){s.writeHead(500,{"Content-Type":"application/json"}),s.end(JSON.stringify({error:"Snapshot screenshot failed"}));return}let u=a.toString("base64");s.writeHead(200,{"Content-Type":"application/json"}),s.end(JSON.stringify({screenshot:`data:image/png;base64,${u}`}))}catch(d){l.error("Snapshot screenshot error:",d.message),s.writeHead(500,{"Content-Type":"application/json"}),s.end(JSON.stringify({error:d.message}))}}),t.httpServer?.on("close",()=>{W().catch(()=>{})});let i=n=>{W().catch(()=>{}).finally(()=>{process.kill(process.pid,n)})},o=globalThis;o.__uicopilotShutdownRegistered||(o.__uicopilotShutdownRegistered=!0,process.once("SIGINT",()=>i("SIGINT")),process.once("SIGTERM",()=>i("SIGTERM")))}}),e}var dt=()=>{if(typeof import.meta<"u"&&import.meta.url){let e=ye(import.meta.url),r=ge(e);return U(r,"manager.mjs")}return U(__dirname,"manager.mjs")},ut=()=>{if(typeof import.meta<"u"&&import.meta.url){let e=ye(import.meta.url),r=ge(e);return U(r,"preview.mjs")}return U(__dirname,"preview.mjs")};function fr(e=[]){return[...e,dt()]}function mr(e=[]){return[...e,ut()]}export{ct as experimental_serverChannel,fr as managerEntries,mr as previewAnnotations,lt as viteFinal};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uicopilot/storybook-addon",
3
- "version": "0.5.41",
3
+ "version": "0.5.42",
4
4
  "description": "Catch design drift between Figma and Storybook before it ships.",
5
5
  "homepage": "https://uiparity.com",
6
6
  "keywords": [