@tscircuit/runframe 0.0.2344 → 0.0.2345

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.
@@ -5790,7 +5790,7 @@ test("${c} should solve problem correctly", () => {
5790
5790
  // Add more specific assertions based on expected output
5791
5791
  // expect(solver.netLabelPlacementSolver!.netLabelPlacements).toMatchInlineSnapshot()
5792
5792
  })
5793
- `,g=new Blob([l],{type:"text/plain"}),u=URL.createObjectURL(g),h=document.createElement("a");h.href=u,h.download=`${c}.test.ts`,h.click(),URL.revokeObjectURL(u)}catch(a){alert(`Error generating test.ts for ${t.constructor.name}: ${a instanceof Error?a.message:String(a)}`)}o(!1)};return J.jsxs("div",{className:`relative ${e}`,ref:i,children:[J.jsx("button",{className:"px-2 py-1 rounded text-xs cursor-pointer",onClick:()=>o(!n),title:`Download options for ${t.constructor.name}`,children:t.constructor.name}),n&&J.jsxs("div",{className:"absolute top-full left-0 mt-1 bg-white border border-gray-300 rounded shadow-lg z-10 min-w-[150px]",children:[J.jsx("button",{className:"w-full text-left px-3 py-2 hover:bg-gray-100 text-xs",onClick:r,children:"Download JSON"}),J.jsx("button",{className:"w-full text-left px-3 py-2 hover:bg-gray-100 text-xs",onClick:A,children:"Download page.tsx"}),J.jsx("button",{className:"w-full text-left px-3 py-2 hover:bg-gray-100 text-xs",onClick:s,children:"Download test.ts"})]})]})},rRt=t=>t.activeSubSolver?[t,...rRt(t.activeSubSolver)]:[t],bHo=({solver:t})=>{const e=rRt(t);return J.jsx("div",{className:"flex gap-1 items-center text-sm pt-1",children:e.map((n,o)=>J.jsxs("div",{className:"flex items-center",children:[o>0&&J.jsx("span",{className:"text-gray-400 mx-1",children:"→"}),J.jsx(SHo,{solver:n})]},n.constructor.name))})},DHo=({solver:t,triggerRender:e,animationSpeed:n=25,onSolverStarted:o,onSolverCompleted:i})=>{const[r,A]=j.useReducer(_=>!_,!1),s=j.useRef(void 0),a=()=>{!t.solved&&!t.failed&&(t.step(),e())},c=()=>{!t.solved&&!t.failed&&(o&&o(t),t.solve(),e(),i&&i(t))},l=()=>{r?(s.current&&(clearInterval(s.current),s.current=void 0),A()):(A(),s.current=setInterval(()=>{if(t.solved||t.failed){s.current&&(clearInterval(s.current),s.current=void 0),A(),e(),i&&t.solved&&i(t);return}t.step(),e()},n))},g=()=>{const _=t;if(_.getCurrentPhase&&!t.solved&&!t.failed){const p=_.getCurrentPhase();for(;_.getCurrentPhase()===p&&!t.solved&&!t.failed;)t.step();e()}},u=()=>{if(t.solved||t.failed||r)return;const _=window.prompt("Step until which iteration?",`${t.iterations}`);if(_===null)return;const p=Number(_);if(!Number.isFinite(p)){window.alert("Please enter a valid number for the iteration");return}for(;t.iterations<p&&!t.solved&&!t.failed;)t.step();e(),t.solved&&i&&i(t)};j.useEffect(()=>()=>{s.current&&clearInterval(s.current)},[]),j.useEffect(()=>{(t.solved||t.failed)&&r&&(s.current&&(clearInterval(s.current),s.current=void 0),A())},[t.solved,t.failed,r]);const h=t.getCurrentPhase!==void 0,d=h?t.getCurrentPhase():null;return J.jsxs("div",{className:"space-y-2 p-2 border-b",children:[J.jsx("div",{className:"flex items-center",children:J.jsx(bHo,{solver:t})}),J.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[J.jsx("button",{onClick:a,disabled:t.solved||t.failed||r,className:"bg-blue-500 hover:bg-blue-600 disabled:bg-gray-300 text-white px-3 py-1 rounded text-sm",children:"Step"}),J.jsx("button",{onClick:c,disabled:t.solved||t.failed||r,className:"bg-green-500 hover:bg-green-600 disabled:bg-gray-300 text-white px-3 py-1 rounded text-sm",children:"Solve"}),J.jsx("button",{onClick:l,disabled:t.solved||t.failed,className:`px-3 py-1 rounded text-white text-sm ${r?"bg-red-500 hover:bg-red-600":"bg-yellow-500 hover:bg-yellow-600"} disabled:bg-gray-300`,children:r?"Stop":"Animate"}),J.jsx("button",{onClick:u,disabled:t.solved||t.failed||r,className:"bg-orange-500 hover:bg-orange-600 disabled:bg-gray-300 text-white px-3 py-1 rounded text-sm",children:"Step Until Iteration"}),h&&J.jsx("button",{onClick:g,disabled:t.solved||t.failed||r,className:"bg-purple-500 hover:bg-purple-600 disabled:bg-gray-300 text-white px-3 py-1 rounded text-sm",children:"Next Stage"}),J.jsxs("div",{className:"text-sm text-gray-600",children:["Iterations: ",t.iterations]}),t.timeToSolve!==void 0&&J.jsxs("div",{className:"text-sm text-gray-600",children:["Time: ",(t.timeToSolve/1e3).toFixed(3),"s"]}),d&&J.jsxs("div",{className:"text-sm text-gray-600",children:["Phase: ",J.jsx("span",{className:"font-medium",children:d})]}),t.solved&&J.jsx("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded text-sm",children:"Solved"}),t.failed&&J.jsx("div",{className:"px-2 py-1 bg-red-100 text-red-800 rounded text-sm",children:"Failed"})]}),t.error&&J.jsxs("div",{className:"text-red-600 text-sm",children:["Error: ",t.error]})]})},MHo=(t,e,n)=>{const o=t.currentPipelineStepIndex;return e<o?"Completed":e===o&&t.activeSubSolver?t.activeSubSolver.failed?"Failed":"In Progress":"Not Started"},wHo=(t,e)=>{const o=t.pipelineDef[e].solverName,i=MHo(t,e),r=t[o],A=t.firstIterationOfPhase?.[o]??null,s=t.iterations;let a=0;if(i==="Completed"){const u=t.pipelineDef[e+1],h=u?t.firstIterationOfPhase?.[u.solverName]:void 0;h!==void 0&&A!==null?a=h-A:A!==null&&(a=s-A)}else i==="In Progress"&&A!==null&&(a=s-A);const c=t.timeSpentOnPhase?.[o]??0;let l=0;i==="Completed"?l=1:i==="In Progress"&&r&&(l=r.progress??0);const g=r?.stats??null;return{index:e,name:o,status:i,firstIteration:A,iterations:a,progress:l,timeSpent:c,stats:g&&Object.keys(g).length>0?g:null,solverInstance:r??null}},PHo=({status:t})=>{const e={"Not Started":"text-blue-600","In Progress":"text-yellow-600",Completed:"text-green-600",Failed:"text-red-600"};return J.jsx("span",{className:`font-medium ${e[t]}`,children:t})},vHo=({progress:t})=>{if(t===0)return null;const e=Math.round(t*100);return J.jsxs("div",{className:"flex items-center gap-2",children:[J.jsx("div",{className:"w-20 h-2 bg-gray-200 rounded overflow-hidden",children:J.jsx("div",{className:"h-full bg-blue-500 transition-all duration-200",style:{width:`${e}%`}})}),J.jsxs("span",{className:"text-xs text-gray-500",children:[e,"%"]})]})},NHo=t=>Object.entries(t).map(([e,n])=>`${e}: ${n}`).join(", "),RHo=({stats:t})=>{if(!t||Object.keys(t).length===0)return J.jsx("span",{children:"-"});const e=Object.entries(t),n=NHo(t);return J.jsxs("details",{className:"cursor-pointer",children:[J.jsx("summary",{className:"whitespace-nowrap overflow-hidden text-ellipsis max-w-[200px]",children:n}),J.jsx("div",{className:"mt-1 text-xs",children:e.map(([o,i])=>J.jsxs("div",{children:[o,": ",String(i)]},o))})]})},u3e=t=>{if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(u3e);const e={};for(const[n,o]of Object.entries(t))n.startsWith("_")||(e[n]=u3e(o));return e},THo=(t,e)=>{try{if(typeof t.getConstructorParams!="function"){alert(`getConstructorParams() is not implemented for ${e}`);return}const n=u3e(t.getConstructorParams()),o=new Blob([JSON.stringify(n,null,2)],{type:"application/json"}),i=URL.createObjectURL(o),r=document.createElement("a");r.href=i,r.download=`${e}_input.json`,r.click(),URL.revokeObjectURL(i)}catch(n){alert(`Error downloading input for ${e}: ${n instanceof Error?n.message:String(n)}`)}},kHo=({solver:t,onStepUntilPhase:e,onDownloadInput:n})=>{const o=t.pipelineDef.map((s,a)=>wHo(t,a)),i=s=>{e?.(s)},r=s=>{s.solverInstance&&(n?n(s.solverInstance,s.name):THo(s.solverInstance,s.name))},A=s=>`${(s/1e3).toFixed(2)}s`;return J.jsxs("div",{className:"border-t border-gray-200",children:[J.jsx("div",{className:"px-4 py-2 bg-gray-50 border-b border-gray-200",children:J.jsx("h3",{className:"text-sm font-semibold text-gray-700",children:"Pipeline Steps"})}),J.jsx("div",{className:"overflow-x-auto",children:J.jsxs("table",{className:"w-full text-sm",children:[J.jsx("thead",{children:J.jsxs("tr",{className:"bg-gray-50 border-b border-gray-200",children:[J.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Step"}),J.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Status"}),J.jsxs("th",{className:"px-4 py-2 text-center font-semibold text-gray-700",children:["i",J.jsx("sub",{children:"0"})]}),J.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Iterations"}),J.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Progress"}),J.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Time"}),J.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Stats"}),J.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Input"})]})}),J.jsx("tbody",{children:o.map(s=>J.jsxs("tr",{className:`border-b border-gray-100 ${s.status==="In Progress"?"bg-yellow-50":""}`,children:[J.jsx("td",{className:"px-4 py-2",children:J.jsxs("div",{className:"flex items-center gap-2",children:[J.jsx("span",{className:"text-gray-400 w-6",children:String(s.index+1).padStart(2,"0")}),J.jsx("button",{onClick:()=>i(s.name),disabled:s.status==="Completed"||t.solved||t.failed,className:"text-blue-500 hover:text-blue-700 disabled:text-gray-300 disabled:cursor-not-allowed",title:`Step until ${s.name} completes`,children:J.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",className:"w-4 h-4",children:J.jsx("path",{fillRule:"evenodd",d:"M4.5 5.653c0-1.426 1.529-2.33 2.779-1.643l11.54 6.348c1.295.712 1.295 2.573 0 3.285L7.28 19.991c-1.25.687-2.779-.217-2.779-1.643V5.653z",clipRule:"evenodd"})})}),J.jsx("span",{className:"font-medium text-gray-900",children:s.name})]})}),J.jsx("td",{className:"px-4 py-2",children:J.jsx(PHo,{status:s.status})}),J.jsx("td",{className:"px-4 py-2 text-center text-gray-600",children:s.firstIteration!==null?s.firstIteration:""}),J.jsx("td",{className:"px-4 py-2 text-gray-600",children:s.iterations}),J.jsx("td",{className:"px-4 py-2",children:J.jsx(vHo,{progress:s.progress})}),J.jsx("td",{className:"px-4 py-2 text-gray-600",children:A(s.timeSpent)}),J.jsx("td",{className:"px-4 py-2 text-gray-500",children:J.jsx(RHo,{stats:s.stats})}),J.jsx("td",{className:"px-4 py-2",children:s.solverInstance?J.jsxs("button",{onClick:()=>r(s),className:"flex items-center gap-1 text-blue-500 hover:text-blue-700",title:`Download input for ${s.name}`,children:[J.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",className:"w-4 h-4",children:J.jsx("path",{fillRule:"evenodd",d:"M12 2.25a.75.75 0 01.75.75v11.69l3.22-3.22a.75.75 0 111.06 1.06l-4.5 4.5a.75.75 0 01-1.06 0l-4.5-4.5a.75.75 0 111.06-1.06l3.22 3.22V3a.75.75 0 01.75-.75zm-9 13.5a.75.75 0 01.75.75v2.25a1.5 1.5 0 001.5 1.5h13.5a1.5 1.5 0 001.5-1.5V16.5a.75.75 0 011.5 0v2.25a3 3 0 01-3 3H5.25a3 3 0 01-3-3V16.5a.75.75 0 01.75-.75z",clipRule:"evenodd"})}),J.jsx("span",{children:"Input"})]}):null})]},s.name))})]})})]})},FHo=class extends $r.Component{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(t){console.error("InteractiveGraphics render error:",t)}render(){return this.state.hasError?this.props.fallback:this.props.children}};function LHo({graphics:t}){const e=t.points??[],n=t.lines??[],o=t.rects??[],i=t.circles??[],r=t.texts??[];let A=Number.POSITIVE_INFINITY,s=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY,c=Number.NEGATIVE_INFINITY;const l=(p,m)=>{typeof p=="number"&&(p<A&&(A=p),p>a&&(a=p)),typeof m=="number"&&(m<s&&(s=m),m>c&&(c=m))};for(const p of e)l(p.x,p.y);for(const p of n){const m=p.points??[];for(const C of m)l(C.x,C.y)}for(const p of o){const m=p.x??0,C=p.y??0,I=p.width??0,f=p.height??0;l(m,C),l(m+I,C+f)}for(const p of i){const m=p.x??0,C=p.y??0,I=p.radius??1;l(m-I,C-I),l(m+I,C+I)}for(const p of r)l(p.x,p.y);(!isFinite(A)||!isFinite(s)||!isFinite(a)||!isFinite(c))&&(A=-20,s=-20,a=20,c=20);const g=10,u=A-g,h=s-g,d=Math.max(1,a-A+2*g),_=Math.max(1,c-s+2*g);return J.jsxs("svg",{className:"w-full h-[400px] bg-white",viewBox:`${u} ${h} ${d} ${_}`,role:"img","aria-label":"Graphics fallback",children:[o.map((p,m)=>J.jsx("rect",{x:p.x??0,y:p.y??0,width:p.width??0,height:p.height??0,fill:"none",stroke:p.strokeColor??"black",strokeWidth:p.strokeWidth??1},`rect-${m}`)),n.map((p,m)=>J.jsx("polyline",{fill:"none",stroke:p.strokeColor??"black",strokeWidth:p.strokeWidth??1,points:(p.points??[]).map(C=>`${C.x??0},${C.y??0}`).join(" ")},`line-${m}`)),i.map((p,m)=>J.jsx("circle",{cx:p.x??0,cy:p.y??0,r:p.radius??1.5,fill:p.fillColor??"none",stroke:p.strokeColor??"black",strokeWidth:p.strokeWidth??1},`circle-${m}`)),e.map((p,m)=>J.jsx("circle",{cx:p.x??0,cy:p.y??0,r:p.radius??1.5,fill:p.color??"black"},`point-${m}`)),r.map((p,m)=>J.jsx("text",{x:p.x??0,y:p.y??0,fontSize:p.fontSize??10,fill:p.color??"black",children:p.text??""},`text-${m}`))]})}var HHo=({solver:t,animationSpeed:e=25,onSolverStarted:n,onSolverCompleted:o})=>{const[i,r]=j.useReducer(l=>l+1,0),A=j.useMemo(()=>{try{return t.visualize()||{points:[],lines:[],rects:[],circles:[]}}catch(l){return console.error("Visualization error:",l),{points:[],lines:[],rects:[],circles:[]}}},[t,i]),s=j.useMemo(()=>(A.rects?.length||0)===0&&(A.lines?.length||0)===0&&(A.points?.length||0)===0&&(A.circles?.length||0)===0,[A]);j.useEffect(()=>{if(!(typeof document>"u")&&!document.querySelector('script[src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"]')){const l=document.createElement("script");l.src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4",document.head.appendChild(l)}},[]);const a=t.pipelineDef!==void 0,c=l=>{const g=t;if(!t.solved&&!t.failed){for(;!t.solved&&!t.failed&&g.currentPipelineStepIndex<=g.pipelineDef.findIndex(u=>u.solverName===l);)t.step();r()}};return J.jsxs("div",{children:[J.jsx(DHo,{solver:t,triggerRender:r,animationSpeed:e,onSolverStarted:n,onSolverCompleted:o}),s?J.jsx("div",{className:"p-4 text-gray-500",children:"No Graphics Yet"}):J.jsx(FHo,{fallback:J.jsx(LHo,{graphics:A}),children:J.jsx(QHo,{graphics:A})}),a&&J.jsx(kHo,{solver:t,onStepUntilPhase:c})]})};const GHo=()=>{j.useEffect(()=>{const t="tailwind-cdn-script";if(document.getElementById(t)||window.tailwind)return;const e=document.createElement("div");e.className="hidden",document.body.appendChild(e);const n=window.getComputedStyle(e).display==="none";if(document.body.removeChild(e),n)return;const o=document.createElement("script");o.id=t,o.src="https://cdn.tailwindcss.com",document.head.appendChild(o)},[])},OHo=1e3,DS=(t,e)=>{const{fileName:n,mimeType:o="text/plain"}=e,i=t instanceof Blob?t:new Blob([t],{type:o}),r=URL.createObjectURL(i),A=document.createElement("a");A.href=r,A.download=n,A.target="_blank",A.rel="noopener noreferrer",A.style.display="none",document.body.appendChild(A),A.click(),document.body.removeChild(A),setTimeout(()=>{URL.revokeObjectURL(r)},OHo)},ARt=t=>{let e=t.trim().replace(/[\\/:*?"<>|]/g,"_").replace(/[\x00-\x1f]/g,"").replace(/^\.+/,"").replace(/\.+$/,"").replace(/\s+/g," ").replace(/_+/g,"_");return/^(con|prn|aux|nul|com[0-9]|lpt[0-9])$/i.test(e)&&(e=`_${e}`),e=e.slice(0,200),e||"untitled"},MS="https://github.com/tscircuit/tscircuit-autorouter/issues/new",sRt="https://github.com/tscircuit/copper-pour-solver/issues/new",aRt="https://github.com/tscircuit/calculate-packing/issues/new",cRt="https://github.com/tscircuit/schematic-trace-solver/issues/new?template=json-bug-report.yml",KHo={PackSolver2:aRt,AutoroutingPipelineSolver:MS,AssignableAutoroutingPipeline2:MS,AssignableAutoroutingPipeline3:MS,AutoroutingPipeline1_OriginalUnravel:MS,AutoroutingPipelineSolver3_HgPortPointPathing:MS,AutoroutingPipelineSolver4:MS,AutoroutingPipelineSolver5:MS,AutoroutingPipelineSolver7_MultiGraph:MS,AutoroutingPipelineSolver8:MS,CopperPourPipelineSolver:sRt,SchematicTracePipelineSolver:cRt},UHo=t=>t.toLowerCase().includes("pack")?PPo:t.toLowerCase().includes("rout")?FPo:IPo,lRt=t=>{const e=KHo[t];if(e)return e;const n=t.toLowerCase();return n.includes("autorout")?MS:n.includes("schematic")&&n.includes("trace")?cRt:n.includes("copperpour")?sRt:n.includes("pack")?aRt:null},YHo=t=>`${ARt(`${t.componentName}-${t.solverName}`)}-solver-input.json`,gRt=t=>{DS(JSON.stringify(t.solverParams,null,2),{fileName:YHo(t),mimeType:"application/json"})},zHo=({solverEvent:t})=>{const e=lRt(t.solverName);return J.jsxs("div",{className:"rf-flex rf-items-center rf-justify-end rf-gap-2 rf-border-b rf-border-gray-200 rf-bg-gray-50 rf-px-4 rf-py-2",children:[J.jsxs(ta,{type:"button",variant:"outline",size:"sm",onClick:()=>gRt(t),children:[J.jsx(qwe,{className:"rf-w-4 rf-h-4"}),"Download"]}),e?J.jsx(ta,{asChild:!0,variant:"outline",size:"sm",children:J.jsxs("a",{href:e,target:"_blank",rel:"noopener noreferrer",children:[J.jsx(eoe,{className:"rf-w-4 rf-h-4"}),"Report"]})}):J.jsxs(ta,{type:"button",variant:"outline",size:"sm",disabled:!0,title:"No report link configured for this solver",children:[J.jsx(eoe,{className:"rf-w-4 rf-h-4"}),"Report"]})]})},VHo=({solverEvent:t})=>{const e=lRt(t.solverName);return e?J.jsx(ta,{asChild:!0,variant:"ghost",size:"icon",className:"rf-h-8 rf-w-8",children:J.jsx("a",{href:e,target:"_blank",rel:"noopener noreferrer",title:"Report solver bug","aria-label":"Report solver bug",children:J.jsx(eoe,{className:"rf-w-4 rf-h-4"})})}):J.jsx(ta,{type:"button",variant:"ghost",size:"icon",className:"rf-h-8 rf-w-8",disabled:!0,title:"No report link configured for this solver","aria-label":"Report solver bug",children:J.jsx(eoe,{className:"rf-w-4 rf-h-4"})})},JHo=({solverEvents:t=[]})=>{const[e,n]=j.useState(null);GHo();const o=j.useMemo(()=>{const s=new Map;for(const a of t){const c=`${a.componentName}-${a.solverName}`;s.set(c,a)}return s},[t]),i=j.useMemo(()=>Array.from(o.keys()),[o]),r=e?o.get(e):null,A=j.useMemo(()=>{if(!r)return{instance:null,error:null,classFound:!1};const s=ACe[r.solverName];if(!s)return{instance:null,error:`Solver class "${r.solverName}" not found in SOLVERS registry. Available: ${Object.keys(ACe).join(", ")}`,classFound:!1};try{const a=r.solverParams,c=a?.input!==void 0?a.input:a;return{instance:new s(c),error:null,classFound:!0}}catch(a){const c=a instanceof Error?a.message:String(a);return console.error("Failed to reconstruct solver:",a),{instance:null,error:`Failed to instantiate solver: ${c}`,classFound:!0}}},[r]);return t.length===0?J.jsx("div",{className:"rf-p-4",children:J.jsx("div",{className:"rf-bg-gray-50 rf-rounded-md rf-border rf-border-gray-200",children:J.jsxs("div",{className:"rf-p-4",children:[J.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-gray-800 rf-mb-3",children:"No Solvers Detected"}),J.jsx("p",{className:"rf-text-sm rf-text-gray-600",children:"Solvers will appear here when the circuit runs. Solvers are used for tasks like component packing and autorouting."})]})})}):J.jsxs("div",{className:"rf-flex rf-h-full rf-overflow-hidden",children:[J.jsxs("div",{className:"rf-w-64 rf-border-r rf-border-gray-200 rf-overflow-y-auto rf-flex-shrink-0",children:[J.jsxs("div",{className:"rf-text-xs rf-font-semibold rf-text-gray-500 rf-px-3 rf-py-2 rf-bg-gray-50 rf-border-b rf-border-gray-200",children:[i.length," ",i.length===1?"Solver":"Solvers"]}),i.map(s=>{const a=o.get(s),c=e===s;return J.jsx("div",{className:`rf-px-3 rf-py-2 rf-cursor-pointer rf-border-b rf-border-gray-100 ${c?"rf-bg-blue-50 rf-border-l-2 rf-border-l-blue-500":"hover:rf-bg-gray-50"}`,onClick:()=>n(s),children:(()=>{const l=UHo(a.solverName);return J.jsxs("div",{className:"rf-flex rf-items-center rf-gap-2",children:[J.jsx(l,{className:"rf-w-4 rf-h-4 rf-text-blue-500 rf-flex-shrink-0"}),J.jsxs("div",{className:"rf-flex-1 rf-min-w-0",children:[J.jsx("div",{className:"rf-text-sm rf-font-medium rf-text-gray-800 rf-truncate",children:a.componentName}),J.jsx("div",{className:"rf-text-xs rf-text-gray-500 rf-truncate",children:a.solverName})]})]})})()},s)})]}),J.jsx("div",{className:"rf-flex-1 rf-overflow-hidden",children:r?A.instance?J.jsxs("div",{className:"rf-flex rf-h-full rf-flex-col rf-overflow-y-auto",children:[J.jsx(zHo,{solverEvent:r}),J.jsx("div",{className:"rf-min-h-0 rf-flex-1",children:J.jsx(gx,{fallback:J.jsx("div",{className:"rf-p-4",children:J.jsxs("div",{className:"rf-bg-red-50 rf-rounded-md rf-border rf-border-red-200 rf-p-4",children:[J.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-red-800 rf-mb-2",children:"Error Loading Solver Debugger"}),J.jsxs("p",{className:"rf-text-sm rf-text-red-600",children:["Failed to render the solver debugger for"," ",r.solverName]})]})}),children:J.jsx(HHo,{solver:A.instance})})})]}):J.jsxs("div",{className:"rf-p-4",children:[J.jsxs("div",{className:"rf-mb-4",children:[J.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-gray-800",children:r.solverName}),J.jsxs("p",{className:"rf-text-sm rf-text-gray-500",children:["Component: ",r.componentName]})]}),A.error&&J.jsx("div",{className:`rf-rounded-md rf-border rf-p-4 rf-mb-4 ${A.classFound?"rf-bg-red-50 rf-border-red-200":"rf-bg-yellow-50 rf-border-yellow-200"}`,children:J.jsx("p",{className:`rf-text-sm ${A.classFound?"rf-text-red-700":"rf-text-yellow-700"}`,children:A.error})}),J.jsxs("div",{className:"rf-border rf-border-gray-200 rf-rounded-md rf-overflow-hidden",children:[J.jsxs("div",{className:"rf-px-3 rf-py-2 rf-bg-gray-50 rf-flex rf-items-center rf-justify-between rf-gap-2",children:[J.jsx("span",{className:"rf-text-sm rf-font-medium rf-text-gray-700",children:"Solver Parameters"}),J.jsxs("div",{className:"rf-flex rf-items-center rf-gap-1",children:[J.jsx(VHo,{solverEvent:r}),J.jsx(ta,{type:"button",variant:"ghost",size:"icon",className:"rf-h-8 rf-w-8","aria-label":"Download solver input JSON",title:"Download solver input JSON",onClick:()=>gRt(r),children:J.jsx(qwe,{className:"rf-w-4 rf-h-4"})})]})]}),J.jsx("div",{className:"rf-p-3 rf-bg-white rf-border-t rf-border-gray-200",children:J.jsx("pre",{className:"rf-text-xs rf-font-mono rf-text-gray-600 rf-whitespace-pre-wrap rf-overflow-x-auto",children:JSON.stringify(r.solverParams,null,2)})})]})]}):J.jsx("div",{className:"rf-flex rf-items-center rf-justify-center rf-h-full",children:J.jsx("p",{className:"rf-text-sm rf-text-gray-500",children:"Select a solver from the list to view details"})})})]})},uRt=({errorMessage:t,errorStack:e,circuitJsonErrors:n})=>{j.useEffect(()=>{if(t){const o=new Error(t);e&&(o.stack=e);try{pN.captureException(o)}catch{}}},[t,e]),j.useEffect(()=>{if(n&&n.length>0)for(const o of n){const i=new Error(o.message||"Circuit JSON Error");o.stack&&(i.stack=o.stack);try{pN.captureException(i,{error_type:o.type})}catch{}}},[n])},dRt=t=>{j.useEffect(()=>{try{Tzn(t)}catch{}},[t.source,t.component,t.isWebEmbedded,t.activeTab])},hRt="0.0.2342",qHo={version:hRt},yie=Ggt()(Ogt(t=>({lastRunEvalVersion:void 0,setLastRunEvalVersion:e=>{t({lastRunEvalVersion:e})}}),{name:"runframe-runner-store"})),WHo=t=>{const[e,n]=j.useState([]),[o,i]=j.useState(null),[r,A]=j.useState(""),[s,a]=J7("eval-version-selection",null),c=yie(h=>h.setLastRunEvalVersion),l=yie(h=>h.lastRunEvalVersion);return j.useEffect(()=>{t&&fetch("https://data.jsdelivr.com/v1/package/npm/@tscircuit/eval").then(h=>h.json()).then(h=>{if(Array.isArray(h?.versions)){let d=[...h.versions];h.tags?.latest&&(i(h.tags.latest),d=d.filter(_=>_!==h.tags.latest)),n(d)}}).catch(()=>{})},[t]),j.useEffect(()=>{t&&(s?(window.TSCIRCUIT_LATEST_EVAL_VERSION=s,c(s)):o&&(window.TSCIRCUIT_LATEST_EVAL_VERSION=o,c(o)))},[t,s,o]),{versions:j.useMemo(()=>e.filter(h=>h.includes(r)).slice(0,50),[e,r]),latestVersion:o,lastRunEvalVersion:l,search:r,setSearch:A,selectVersion:h=>{a(h),A("")}}},jHo=({snippetNames:t,onSelect:e,onCancel:n,isOpen:o})=>{const[i,r]=j.useState(""),[A,s]=j.useState("");if(!o)return null;const a=t.filter(g=>g.toLowerCase().includes(A.toLowerCase())),c=A&&!t.includes(A),l=g=>{g.key==="Enter"&&(a.length===1?r(a[0]):c&&r(A))};return J.jsx("div",{className:"rf-fixed rf-inset-0 rf-bg-black rf-bg-opacity-50 rf-flex rf-items-center rf-justify-center rf-z-[100]",children:J.jsxs("div",{className:"rf-bg-white rf-rounded-lg rf-p-6 rf-w-96",children:[J.jsx("h2",{className:"rf-text-lg rf-font-semibold rf-mb-4",children:"Select Snippet"}),J.jsx("input",{type:"text",className:"rf-w-full rf-px-4 rf-py-2 rf-border rf-rounded rf-mb-4",placeholder:"Search snippets or new snippet name...",value:A,onChange:g=>s(g.target.value),onKeyDown:l}),J.jsxs("div",{className:"rf-h-60 rf-overflow-y-auto",children:[a.map(g=>J.jsx("button",{type:"button",className:`w-full text-left px-4 py-2 rounded hover:bg-gray-100 ${i===g?"bg-blue-50":""}`,onClick:()=>r(g),children:g},g)),c&&J.jsxs("button",{type:"button",className:`w-full text-left px-4 py-2 rounded hover:bg-gray-100 text-blue-500 ${i===A?"bg-blue-50":""}`,onClick:()=>r(A),children:['Create new "',A,'"']})]}),J.jsxs("div",{className:"rf-mt-4 rf-flex rf-justify-end rf-gap-2",children:[J.jsx("button",{type:"button",className:"rf-px-4 rf-py-2 rf-text-gray-600 rf-hover:text-gray-800",onClick:n,children:"Cancel"}),J.jsx("button",{type:"button",className:"rf-px-4 rf-py-2 rf-bg-blue-500 rf-text-white rf-rounded rf-hover:bg-blue-600 rf-disabled:opacity-50",onClick:()=>i&&e(i),disabled:!i,children:i===A?`Create "${i}"`:`Save to ${i}`})]})]})})},XHo=t=>{const e=j.useRef(null),n=Yu(o=>o.recentEvents);j.useEffect(()=>{if(n.length===0)return;const o=n[0];o.event_id!==e.current&&(t(o),e.current=o.event_id)},[n,t])};var $Ho=Object.defineProperty,G2=(t,e)=>$Ho(t,"name",{value:e,configurable:!0}),d3e="Dialog",[_Rt,mRt]=y2(d3e),[ZHo,PB]=_Rt(d3e),h3e=G2(t=>{const{__scopeDialog:e,children:n,open:o,defaultOpen:i,onOpenChange:r,modal:A=!0}=t,s=j.useRef(null),a=j.useRef(null),[c,l]=Ub({prop:o,defaultProp:i??!1,onChange:r,caller:d3e}),[g,u]=j.useState(0),[h,d]=j.useState(0);return J.jsx(ZHo,{scope:e,triggerRef:s,contentRef:a,contentId:rp(),titleId:rp(),descriptionId:rp(),titlePresent:g>0,descriptionPresent:h>0,setTitleCount:u,setDescriptionCount:d,open:c,onOpenChange:l,onOpenToggle:j.useCallback(()=>l(_=>!_),[l]),modal:A,children:n})},"Dialog"),eGo="DialogTrigger",tGo=j.forwardRef(G2(function(e,n){const{__scopeDialog:o,...i}=e,r=PB(eGo,o),A=dl(n,r.triggerRef);return J.jsx(Oa.button,{type:"button","aria-haspopup":"dialog","aria-expanded":r.open,"aria-controls":r.open?r.contentId:void 0,"data-state":Bie(r.open),...i,ref:A,onClick:Pr(e.onClick,r.onOpenToggle)})},"DialogTrigger")),pRt="DialogPortal",[nGo,IRt]=_Rt(pRt,{forceMount:void 0}),_3e=G2(t=>{const{__scopeDialog:e,forceMount:n,children:o,container:i}=t,r=PB(pRt,e);return J.jsx(nGo,{scope:e,forceMount:n,children:j.Children.map(o,A=>J.jsx(JE,{present:n||r.open,children:J.jsx(yPe,{asChild:!0,container:i,children:A})}))})},"DialogPortal"),m3e="DialogOverlay",Eie=j.forwardRef(G2(function(e,n){const o=IRt(m3e,e.__scopeDialog),{forceMount:i=o.forceMount,...r}=e,A=PB(m3e,e.__scopeDialog);return A.modal?J.jsx(JE,{present:i||A.open,children:J.jsx(iGo,{...r,ref:n})}):null},"DialogOverlay")),oGo=JQ("DialogOverlay.RemoveScroll"),iGo=j.forwardRef(G2(function(e,n){const{__scopeDialog:o,...i}=e,r=PB(m3e,o),A=GPt(),s=dl(n,A);return J.jsx(xoe,{as:oGo,allowPinchZoom:!0,shards:[r.contentRef],children:J.jsx(Oa.div,{"data-state":Bie(r.open),...i,ref:s,style:{pointerEvents:"auto",...i.style}})})},"DialogOverlayImpl")),$K="DialogContent",xie=j.forwardRef(G2(function(e,n){const o=IRt($K,e.__scopeDialog),{forceMount:i=o.forceMount,...r}=e,A=PB($K,e.__scopeDialog);return J.jsx(JE,{present:i||A.open,children:A.modal?J.jsx(rGo,{...r,ref:n}):J.jsx(AGo,{...r,ref:n})})},"DialogContent")),rGo=j.forwardRef(G2(function(e,n){const o=PB($K,e.__scopeDialog),i=j.useRef(null),r=dl(n,o.contentRef,i);return j.useEffect(()=>{const A=i.current;if(A)return xPe(A)},[]),J.jsx(CRt,{...e,ref:r,trapFocus:o.open,disableOutsidePointerEvents:o.open,onCloseAutoFocus:Pr(e.onCloseAutoFocus,A=>{A.preventDefault(),o.triggerRef.current?.focus()}),onPointerDownOutside:Pr(e.onPointerDownOutside,A=>{const s=A.detail.originalEvent,a=s.button===0&&s.ctrlKey===!0;(s.button===2||a)&&A.preventDefault()}),onFocusOutside:Pr(e.onFocusOutside,A=>A.preventDefault())})},"DialogContentModal")),AGo=j.forwardRef(G2(function(e,n){const o=PB($K,e.__scopeDialog),i=j.useRef(!1),r=j.useRef(!1);return J.jsx(CRt,{...e,ref:n,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:A=>{e.onCloseAutoFocus?.(A),A.defaultPrevented||(i.current||o.triggerRef.current?.focus(),A.preventDefault()),i.current=!1,r.current=!1},onInteractOutside:A=>{e.onInteractOutside?.(A),A.defaultPrevented||(i.current=!0,A.detail.originalEvent.type==="pointerdown"&&(r.current=!0));const s=A.target;o.triggerRef.current?.contains(s)&&A.preventDefault(),A.detail.originalEvent.type==="focusin"&&r.current&&A.preventDefault()}})},"DialogContentNonModal")),CRt=j.forwardRef(G2(function(e,n){const{__scopeDialog:o,trapFocus:i,onOpenAutoFocus:r,onCloseAutoFocus:A,...s}=e,a=PB($K,o);return QK(),J.jsx(J.Fragment,{children:J.jsx(oPe,{asChild:!0,loop:!0,trapped:i,onMountAutoFocus:r,onUnmountAutoFocus:A,children:J.jsx(toe,{role:"dialog",id:a.contentId,"aria-describedby":a.descriptionPresent?a.descriptionId:void 0,"aria-labelledby":a.titlePresent?a.titleId:void 0,"data-state":Bie(a.open),...s,ref:n,deferPointerDownOutside:!0,onDismiss:()=>a.onOpenChange(!1)})})})},"DialogContentImpl")),sGo="DialogTitle",p3e=j.forwardRef(G2(function(e,n){const{__scopeDialog:o,...i}=e,r=PB(sGo,o),{setTitleCount:A}=r;return ty(()=>(A(s=>s+1),()=>A(s=>s-1)),[A]),J.jsx(Oa.h2,{id:r.titleId,...i,ref:n})},"DialogTitle")),aGo="DialogDescription",I3e=j.forwardRef(G2(function(e,n){const{__scopeDialog:o,...i}=e,r=PB(aGo,o),{setDescriptionCount:A}=r;return ty(()=>(A(s=>s+1),()=>A(s=>s-1)),[A]),J.jsx(Oa.p,{id:r.descriptionId,...i,ref:n})},"DialogDescription")),cGo="DialogClose",fRt=j.forwardRef(G2(function(e,n){const{__scopeDialog:o,...i}=e,r=PB(cGo,o);return J.jsx(Oa.button,{type:"button",...i,ref:n,onClick:Pr(e.onClick,()=>r.onOpenChange(!1))})},"DialogClose"));function Bie(t){return t?"open":"closed"}G2(Bie,"getState");var lGo=Object.defineProperty,T5=(t,e)=>lGo(t,"name",{value:e,configurable:!0}),gGo="AlertDialog",[uGo,Rjo]=y2(gGo,[mRt]),k5=mRt(),dGo=T5(t=>{const{__scopeAlertDialog:e,...n}=t,o=k5(e);return J.jsx(h3e,{...o,...n,modal:!0})},"AlertDialog");j.forwardRef(T5(function(e,n){const{__scopeAlertDialog:o,...i}=e,r=k5(o);return J.jsx(tGo,{...r,...i,ref:n})},"AlertDialogTrigger"));var hGo=T5(t=>{const{__scopeAlertDialog:e,...n}=t,o=k5(e);return J.jsx(_3e,{...o,...n})},"AlertDialogPortal"),_Go=j.forwardRef(T5(function(e,n){const{__scopeAlertDialog:o,...i}=e,r=k5(o);return J.jsx(Eie,{...r,...i,ref:n})},"AlertDialogOverlay")),mGo="AlertDialogContent",[pGo,IGo]=uGo(mGo),CGo=j.forwardRef(T5(function(e,n){const{__scopeAlertDialog:o,children:i,...r}=e,A=k5(o),s=j.useRef(null),a=dl(n,s),c=j.useRef(null);return J.jsx(pGo,{scope:o,cancelRef:c,children:J.jsx(xie,{role:"alertdialog",...A,...r,ref:a,onOpenAutoFocus:Pr(r.onOpenAutoFocus,l=>{l.preventDefault(),c.current?.focus({preventScroll:!0})}),onPointerDownOutside:l=>l.preventDefault(),onInteractOutside:l=>l.preventDefault(),children:i})})},"AlertDialogContent")),fGo=j.forwardRef(T5(function(e,n){const{__scopeAlertDialog:o,...i}=e,r=k5(o);return J.jsx(p3e,{...r,...i,ref:n})},"AlertDialogTitle")),yGo=j.forwardRef(T5(function(e,n){const{__scopeAlertDialog:o,...i}=e,r=k5(o);return J.jsx(I3e,{...r,...i,ref:n})},"AlertDialogDescription")),EGo=j.forwardRef(T5(function(e,n){const{__scopeAlertDialog:o,...i}=e,r=k5(o);return J.jsx(fRt,{...r,...i,ref:n})},"AlertDialogAction")),xGo="AlertDialogCancel",BGo=j.forwardRef(T5(function(e,n){const{__scopeAlertDialog:o,...i}=e,{cancelRef:r}=IGo(xGo,o),A=k5(o),s=dl(n,r);return J.jsx(fRt,{...A,...i,ref:s})},"AlertDialogCancel")),QGo=dGo,SGo=hGo,yRt=_Go,ERt=CGo,xRt=EGo,BRt=BGo,QRt=fGo,SRt=yGo;const bRt=QGo,bGo=SGo,DRt=j.forwardRef(({className:t,...e},n)=>J.jsx(yRt,{className:qi("rf-fixed rf-inset-0 rf-z-50 rf-bg-black/80 data-[state=open]:rf-animate-in data-[state=closed]:rf-animate-out data-[state=closed]:rf-fade-out-0 data-[state=open]:rf-fade-in-0",t),...e,ref:n}));DRt.displayName=yRt.displayName;const C3e=j.forwardRef(({className:t,...e},n)=>J.jsxs(bGo,{children:[J.jsx(DRt,{}),J.jsx(ERt,{ref:n,className:qi("rf-fixed rf-left-[50%] rf-top-[50%] rf-z-50 rf-grid rf-w-full rf-max-w-lg rf-translate-x-[-50%] rf-translate-y-[-50%] rf-gap-4 rf-border rf-border-zinc-200 rf-bg-white rf-p-6 rf-shadow-lg rf-duration-200 data-[state=open]:rf-animate-in data-[state=closed]:rf-animate-out data-[state=closed]:rf-fade-out-0 data-[state=open]:rf-fade-in-0 data-[state=closed]:rf-zoom-out-95 data-[state=open]:rf-zoom-in-95 data-[state=closed]:rf-slide-out-to-left-1/2 data-[state=closed]:rf-slide-out-to-top-[48%] data-[state=open]:rf-slide-in-from-left-1/2 data-[state=open]:rf-slide-in-from-top-[48%] sm:rf-rounded-lg dark:rf-border-zinc-800 dark:rf-bg-zinc-950",t),...e})]}));C3e.displayName=ERt.displayName;const f3e=({className:t,...e})=>J.jsx("div",{className:qi("rf-flex rf-flex-col rf-space-y-2 rf-text-center sm:rf-text-left",t),...e});f3e.displayName="AlertDialogHeader";const y3e=({className:t,...e})=>J.jsx("div",{className:qi("rf-flex rf-flex-col-reverse sm:rf-flex-row sm:rf-justify-end sm:rf-space-x-2",t),...e});y3e.displayName="AlertDialogFooter";const E3e=j.forwardRef(({className:t,...e},n)=>J.jsx(QRt,{ref:n,className:qi("rf-text-lg rf-font-semibold",t),...e}));E3e.displayName=QRt.displayName;const x3e=j.forwardRef(({className:t,...e},n)=>J.jsx(SRt,{ref:n,className:qi("rf-text-sm rf-text-zinc-500 dark:rf-text-zinc-400",t),...e}));x3e.displayName=SRt.displayName;const DGo=j.forwardRef(({className:t,...e},n)=>J.jsx(xRt,{ref:n,className:qi(oT(),t),...e}));DGo.displayName=xRt.displayName;const B3e=j.forwardRef(({className:t,...e},n)=>J.jsx(BRt,{ref:n,className:qi(oT({variant:"outline"}),"rf-mt-2 sm:rf-mt-0",t),...e}));B3e.displayName=BRt.displayName;var MGo=Object.defineProperty,F5=(t,e)=>MGo(t,"name",{value:e,configurable:!0}),Q3e="Checkbox",[wGo,Tjo]=y2(Q3e),[PGo,S3e]=wGo(Q3e);function MRt(t){const{__scopeCheckbox:e,checked:n,children:o,defaultChecked:i,disabled:r,form:A,name:s,onCheckedChange:a,required:c,value:l="on",internal_do_not_use_render:g}=t,[u,h]=Ub({prop:n,defaultProp:i??!1,onChange:a,caller:Q3e}),[d,_]=j.useState(null),[p,m]=j.useState(null),C=j.useRef(!1),[I,f]=j.useReducer(B=>B+1,0),y=d?!!A||!!d.closest("form"):!0,x={checked:u,disabled:r,setChecked:h,control:d,setControl:_,name:s,form:A,value:l,hasConsumerStoppedPropagationRef:C,userInteractionCount:I,onUserInteraction:f,required:c,defaultChecked:L5(i)?!1:i,isFormControl:y,bubbleInput:p,setBubbleInput:m};return J.jsx(PGo,{scope:e,...x,children:PRt(g)?g(x):o})}F5(MRt,"CheckboxProvider");var vGo="CheckboxTrigger",NGo=j.forwardRef(F5(function({__scopeCheckbox:e,onKeyDown:n,onClick:o,...i},r){const{control:A,value:s,disabled:a,checked:c,required:l,setControl:g,setChecked:u,hasConsumerStoppedPropagationRef:h,onUserInteraction:d,isFormControl:_,bubbleInput:p}=S3e(vGo,e),m=dl(r,g),C=j.useRef(c);return j.useEffect(()=>{const I=A?.form;if(I){const f=F5(()=>u(C.current),"reset");return I.addEventListener("reset",f),()=>I.removeEventListener("reset",f)}},[A,u]),J.jsx(Oa.button,{type:"button",role:"checkbox","aria-checked":L5(c)?"mixed":c,"aria-required":l,"data-state":b3e(c),"data-disabled":a?"":void 0,disabled:a,value:s,...i,ref:m,onKeyDown:Pr(n,I=>{I.key==="Enter"&&I.preventDefault()}),onClick:Pr(o,I=>{d(),u(f=>L5(f)?!0:!f),p&&_&&(h.current=I.isPropagationStopped(),h.current||I.stopPropagation())})})},"CheckboxTrigger")),wRt=j.forwardRef(F5(function(e,n){const{__scopeCheckbox:o,name:i,checked:r,defaultChecked:A,required:s,disabled:a,value:c,onCheckedChange:l,form:g,...u}=e;return J.jsx(MRt,{__scopeCheckbox:o,checked:r,defaultChecked:A,disabled:a,required:s,onCheckedChange:l,name:i,form:g,value:c,internal_do_not_use_render:({isFormControl:h})=>J.jsxs(J.Fragment,{children:[J.jsx(NGo,{...u,ref:n,__scopeCheckbox:o}),h&&J.jsx(FGo,{__scopeCheckbox:o})]})})},"Checkbox")),RGo="CheckboxIndicator",TGo=j.forwardRef(F5(function(e,n){const{__scopeCheckbox:o,forceMount:i,...r}=e,A=S3e(RGo,o);return J.jsx(JE,{present:i||L5(A.checked)||A.checked===!0,children:J.jsx(Oa.span,{"data-state":b3e(A.checked),"data-disabled":A.disabled?"":void 0,...r,ref:n,style:{pointerEvents:"none",...e.style}})})},"CheckboxIndicator")),kGo="CheckboxBubbleInput",FGo=j.forwardRef(F5(function({__scopeCheckbox:e,onClick:n,...o},i){const{control:r,hasConsumerStoppedPropagationRef:A,userInteractionCount:s,checked:a,defaultChecked:c,required:l,disabled:g,name:u,value:h,form:d,bubbleInput:_,setBubbleInput:p}=S3e(kGo,e),m=dl(i,p),C=IPe(r),I=j.useRef(!1),f=j.useRef(a),y=j.useRef(s);j.useEffect(()=>{const B=_;if(!B)return;const S=window.HTMLInputElement.prototype,w=Object.getOwnPropertyDescriptor(S,"checked").set,F=s!==y.current;y.current=s;const R=f.current!==a;f.current=a;const H=!(F&&A.current);if(R&&w){I.current=!F;const G=new Event("click",{bubbles:H});B.indeterminate=L5(a),w.call(B,L5(a)?!1:a),B.dispatchEvent(G),I.current=!1}},[_,a,A,s]);const x=j.useRef(L5(a)?!1:a);return J.jsx(Oa.input,{type:"checkbox","aria-hidden":!0,defaultChecked:c??x.current,required:l,disabled:g,name:u,value:h,form:d,...o,tabIndex:-1,ref:m,onClick:Pr(n,B=>{I.current&&B.stopPropagation()}),style:{...o.style,...C,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})},"CheckboxBubbleInput"));function PRt(t){return typeof t=="function"}F5(PRt,"isFunction");function L5(t){return t==="indeterminate"}F5(L5,"isIndeterminate");function b3e(t){return L5(t)?"indeterminate":t?"checked":"unchecked"}F5(b3e,"getState");const ZK=j.forwardRef(({className:t,...e},n)=>J.jsx(wRt,{ref:n,className:qi("rf-peer rf-h-4 rf-w-4 rf-shrink-0 rf-rounded-sm rf-border rf-border-zinc-200 rf-border-zinc-900 rf-shadow focus-visible:rf-outline-none focus-visible:rf-ring-1 focus-visible:rf-ring-zinc-950 disabled:rf-cursor-not-allowed disabled:rf-opacity-50 data-[state=checked]:rf-bg-zinc-900 data-[state=checked]:rf-text-zinc-50 dark:rf-border-zinc-800 dark:rf-border-zinc-50 dark:focus-visible:rf-ring-zinc-300 dark:data-[state=checked]:rf-bg-zinc-50 dark:data-[state=checked]:rf-text-zinc-900",t),...e,children:J.jsx(TGo,{className:qi("rf-flex rf-items-center rf-justify-center rf-text-current"),children:J.jsx(L3,{className:"rf-h-4 rf-w-4"})})}));ZK.displayName=wRt.displayName;const DT=h3e,LGo=_3e,vRt=j.forwardRef(({className:t,...e},n)=>J.jsx(Eie,{className:qi("rf-fixed rf-inset-0 rf-z-50 rf-bg-black/80 data-[state=open]:rf-animate-in data-[state=closed]:rf-animate-out data-[state=closed]:rf-fade-out-0 data-[state=open]:rf-fade-in-0",t),...e,ref:n}));vRt.displayName=Eie.displayName;const j3=j.forwardRef(({className:t,children:e,showOverlay:n=!0,...o},i)=>J.jsxs(LGo,{children:[J.jsx(vRt,{className:qi(n?"":"rf-hidden")}),J.jsx(xie,{ref:i,className:qi("rf-fixed rf-left-[50%] rf-top-[50%] rf-z-50 rf-grid rf-w-full rf-max-w-lg rf-translate-x-[-50%] rf-translate-y-[-50%] rf-gap-4 rf-border rf-border-zinc-200 rf-bg-white rf-p-6 rf-shadow-lg rf-duration-200 data-[state=open]:rf-animate-in data-[state=closed]:rf-animate-out data-[state=closed]:rf-fade-out-0 data-[state=open]:rf-fade-in-0 data-[state=closed]:rf-zoom-out-95 data-[state=open]:rf-zoom-in-95 data-[state=closed]:rf-slide-out-to-left-1/2 data-[state=closed]:rf-slide-out-to-top-[48%] data-[state=open]:rf-slide-in-from-left-1/2 data-[state=open]:rf-slide-in-from-top-[48%] sm:rf-rounded-lg dark:rf-border-zinc-800 dark:rf-bg-zinc-950",t),...o,children:e})]}));j3.displayName=xie.displayName;const X3=({className:t,...e})=>J.jsx("div",{className:qi("rf-flex rf-flex-col rf-space-y-2 rf-text-center sm:rf-text-left",t),...e});X3.displayName="DialogHeader";const eU=({className:t,...e})=>J.jsx("div",{className:qi("rf-flex rf-flex-col-reverse sm:rf-flex-row sm:rf-justify-end sm:rf-space-x-2",t),...e});eU.displayName="DialogFooter";const $3=j.forwardRef(({className:t,...e},n)=>J.jsx(p3e,{ref:n,className:qi("rf-text-lg rf-font-semibold",t),...e}));$3.displayName=p3e.displayName;const MT=j.forwardRef(({className:t,...e},n)=>J.jsx(I3e,{ref:n,className:qi("rf-text-sm rf-text-zinc-500 dark:rf-text-zinc-400",t),...e}));MT.displayName=I3e.displayName;const Qie={"tscircuit.com":{label:"tscircuit.com",placeholder:"Search tscircuit packages...",emptyMessage:"No packages found"},jlcpcb:{label:"JLCPCB Parts",placeholder:"Search JLCPCB parts (e.g. C14663)...",emptyMessage:"No parts found"},kicad:{label:"KiCad Footprints",placeholder:"Search KiCad footprints...",emptyMessage:"No footprints found"}},HGo="https://cdn.jsdelivr.net/npm/easyeda@latest/dist/browser/index.js";let D3e=null;const M3e=async()=>(D3e||(D3e=import(HGo)),D3e),GGo=t=>(e,n)=>{const o=new Headers(n?.headers),i={};return o.forEach((r,A)=>{i[A]=r}),fetch(`${t?.apiBase??Qf}/proxy`,{...n,headers:{...i,"X-Target-Url":e.toString(),"X-Sender-Origin":i.origin??"","X-Sender-Host":i.host??"https://easyeda.com","X-Sender-Referer":i.referer??"","X-Sender-User-Agent":i["user-agent"]??"","X-Sender-Cookie":i.cookie??"",authority:i.authority??"","content-type":i["content-type"]??"",...t?.headers}})},OGo=async(t,e=10)=>{const n=encodeURIComponent(t),o=await fetch(`https://jlcsearch.tscircuit.com/api/search?limit=${e}&q=${n}`);if(!o.ok)throw new Error(`JLCPCB API error: ${o.status}`);return(await o.json()).components??[]},KGo=t=>({lcscId:t.lcsc,manufacturer:t.mfr,description:t.description,partNumber:`C${t.lcsc}`,package:t.package,price:t.price,stock:t.stock,isBasic:t.is_basic}),NRt=async(t,e)=>{const{fetchEasyEDAComponent:n}=await M3e();return n(t,{fetch:GGo(e),includeModelMetadata:e?.includeModelMetadata})},UGo=async(t,e)=>{const{convertRawEasyToTsx:n}=await M3e(),o=await NRt(t,e);return n({rawEasy:o})},YGo=async(t,e)=>{const{EasyEdaJsonSchema:n,convertEasyEdaJsonToCircuitJson:o}=await M3e(),i=await NRt(t,{...e,includeModelMetadata:!1}),r=n.parse(i);return o(r,{shouldRecenter:!0,showDesignator:!0,useModelCdn:!1})};function uw(t){return Array.isArray?Array.isArray(t):TRt(t)==="[object Array]"}function zGo(t){if(typeof t=="string")return t;if(typeof t=="bigint")return t.toString();const e=t+"";return e=="0"&&1/t==-1/0?"-0":e}function w3e(t){return t==null?"":zGo(t)}function bC(t){return typeof t=="string"}function Sie(t){return typeof t=="number"}function VGo(t){return t===!0||t===!1||JGo(t)&&TRt(t)=="[object Boolean]"}function RRt(t){return typeof t=="object"}function JGo(t){return RRt(t)&&t!==null}function O2(t){return t!=null}function bie(t){return!t.trim().length}function TRt(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const qGo="Incorrect 'index' type",P3e="Invalid doc index: must be a non-negative integer within the bounds of the docs array",WGo=t=>`Invalid value for key ${t}`,jGo=t=>`Pattern length exceeds max of ${t}.`,XGo=t=>`Missing ${t} property in key`,$Go=t=>`Property 'weight' in key '${t}' must be a positive integer`,ZGo="Fuse.match does not support useTokenSearch: token search requires corpus-level statistics (df, fieldCount) that a one-off string comparison does not have. Use new Fuse(...).search(...) instead.",kRt=Object.prototype.hasOwnProperty;var eOo=class{constructor(t){this._keys=[],this._keyMap={};let e=0;t.forEach(n=>{const o=FRt(n);this._keys.push(o),this._keyMap[o.id]=o,e+=o.weight}),this._keys.forEach(n=>{n.weight/=e})}get(t){return this._keyMap[t]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}};function FRt(t){let e=null,n=null,o=null,i=1,r=null;if(bC(t)||uw(t))o=t,e=LRt(t),n=Die(t);else{if(!kRt.call(t,"name"))throw new Error(XGo("name"));const A=t.name;if(o=A,kRt.call(t,"weight")&&t.weight!==void 0&&(i=t.weight,i<=0))throw new Error($Go(Die(A)));e=LRt(A),n=Die(A),r=t.getFn??null}return{path:e,id:n,weight:i,src:o,getFn:r}}function LRt(t){return uw(t)?t:t.split(".")}function Die(t){return uw(t)?t.join("."):t}function tOo(t,e){const n=[];let o=!1;const i=(r,A,s,a)=>{if(O2(r))if(!A[s])n.push(a!==void 0?{v:r,i:a}:r);else{const c=r[A[s]];if(!O2(c))return;if(s===A.length-1&&(bC(c)||Sie(c)||VGo(c)||typeof c=="bigint"))n.push(a!==void 0?{v:w3e(c),i:a}:w3e(c));else if(uw(c)){o=!0;for(let l=0,g=c.length;l<g;l+=1)i(c[l],A,s+1,l)}else A.length&&i(c,A,s+1,a)}};return i(t,bC(e)?e.split("."):e,0),o?n:n[0]}const vA=Object.freeze({...{isCaseSensitive:!1,ignoreDiacritics:!1,includeScore:!1,keys:[],shouldSort:!0,sortFn:(t,e)=>t.score===e.score?t.idx<e.idx?-1:1:t.score<e.score?-1:1},...{includeMatches:!1,findAllMatches:!1,minMatchCharLength:1},...{location:0,threshold:.6,distance:100},...{useExtendedSearch:!1,useTokenSearch:!1,tokenize:void 0,tokenMatch:"any",getFn:tOo,ignoreLocation:!1,ignoreFieldNorm:!1,fieldNormWeight:1}});function nOo(t){return t>=9&&t<=13||t===32||t===160}function oOo(t=1,e=3){const n=new Map,o=Math.pow(10,e);return{get(i){let r=0,A=!1;for(let a=0;a<i.length;a++)nOo(i.charCodeAt(a))?A=!1:A||(r++,A=!0);if(r===0&&(r=1),n.has(r))return n.get(r);const s=Math.round(o/Math.pow(r,.5*t))/o;return n.set(r,s),s},clear(){n.clear()}}}var v3e=class{constructor({getFn:t=vA.getFn,fieldNormWeight:e=vA.fieldNormWeight}={}){this.norm=oOo(e,3),this.getFn=t,this.isCreated=!1,this.docs=[],this.keys=[],this._keysMap={},this.setIndexRecords()}setSources(t=[]){this.docs=t}setIndexRecords(t=[]){this.records=t}setKeys(t=[]){this.keys=t,this._keysMap={},t.forEach((e,n)=>{this._keysMap[e.id]=n})}create(){if(this.isCreated||!this.docs.length)return;this.isCreated=!0;const t=this.docs.length;this.records=new Array(t);let e=0;if(bC(this.docs[0]))for(let n=0;n<t;n++){const o=this._createStringRecord(this.docs[n],n);o&&(this.records[e++]=o)}else for(let n=0;n<t;n++)this.records[e++]=this._createObjectRecord(this.docs[n],n);this.records.length=e,this.norm.clear()}add(t,e){if(!Number.isInteger(e)||e<0)throw new Error(P3e);if(bC(t)){const o=this._createStringRecord(t,e);return o&&this.records.push(o),o}const n=this._createObjectRecord(t,e);return this.records.push(n),n}removeAt(t){if(!Number.isInteger(t)||t<0)throw new Error(P3e);for(let e=0,n=this.records.length;e<n;e+=1)if(this.records[e].i===t){this.records.splice(e,1);break}for(let e=0,n=this.records.length;e<n;e+=1)this.records[e].i>t&&(this.records[e].i-=1)}removeAll(t){const e=new Set;for(const o of t)Number.isInteger(o)&&o>=0&&e.add(o);if(e.size===0)return;this.records=this.records.filter(o=>!e.has(o.i));const n=Array.from(e).sort((o,i)=>o-i);for(const o of this.records){let i=0,r=n.length;for(;i<r;){const A=i+r>>>1;n[A]<o.i?i=A+1:r=A}o.i-=i}}getValueForItemAtKeyId(t,e){return t[this._keysMap[e]]}size(){return this.records.length}_createStringRecord(t,e){return!O2(t)||bie(t)?null:{v:t,i:e,n:this.norm.get(t)}}_createObjectRecord(t,e){const n={i:e,$:{}};for(let o=0,i=this.keys.length;o<i;o++){const r=this.keys[o],A=r.getFn?r.getFn(t):this.getFn(t,r.path);if(O2(A)){if(uw(A)){const s=[];for(let a=0,c=A.length;a<c;a+=1){const l=A[a];if(O2(l)){if(bC(l)){if(!bie(l)){const g={v:l,i:a,n:this.norm.get(l)};s.push(g)}}else if(O2(l.v)){const g=bC(l.v)?l.v:w3e(l.v);if(!bie(g)){const u={v:g,i:l.i,n:this.norm.get(g)};s.push(u)}}}}n.$[o]=s}else if(bC(A)&&!bie(A)){const s={v:A,n:this.norm.get(A)};n.$[o]=s}}}return n}toJSON(){return{keys:this.keys.map(({getFn:t,...e})=>e),records:this.records}}};function HRt(t,e,{getFn:n=vA.getFn,fieldNormWeight:o=vA.fieldNormWeight}={}){const i=new v3e({getFn:n,fieldNormWeight:o});return i.setKeys(t.map(FRt)),i.setSources(e),i.create(),i}function iOo(t,{getFn:e=vA.getFn,fieldNormWeight:n=vA.fieldNormWeight}={}){const{keys:o,records:i}=t,r=new v3e({getFn:e,fieldNormWeight:n});return r.setKeys(o),r.setIndexRecords(i),r}function rOo(t=[],e=vA.minMatchCharLength){const n=[];let o=-1,i=-1,r=0;for(let A=t.length;r<A;r+=1){const s=t[r];s&&o===-1?o=r:!s&&o!==-1&&(i=r-1,i-o+1>=e&&n.push([o,i]),o=-1)}return t[r-1]&&r-o>=e&&n.push([o,r-1]),n}function AOo(t,e,n,{location:o=vA.location,distance:i=vA.distance,threshold:r=vA.threshold,findAllMatches:A=vA.findAllMatches,minMatchCharLength:s=vA.minMatchCharLength,includeMatches:a=vA.includeMatches,ignoreLocation:c=vA.ignoreLocation}={}){if(e.length>32)throw new Error(jGo(32));const l=e.length,g=t.length,u=Math.max(0,Math.min(o,g));let h=r,d=u;const _=(D,w)=>{const F=D/l;if(c)return F;const R=Math.abs(u-w);return i?F+R/i:R?1:F},p=s>1||a,m=p?Array(g):[];let C;for(;(C=t.indexOf(e,d))>-1;){const D=_(0,C);if(h=Math.min(D,h),d=C+l,p){let w=0;for(;w<l;)m[C+w]=1,w+=1}}d=-1;let I=[],f=1,y=0,x=l+g;const B=1<<l-1;for(let D=0;D<l;D+=1){let w=0,F=x;for(;w<F;)_(D,u+F)<=h?w=F:x=F,F=Math.floor((x-w)/2+w);x=F;let R=Math.max(1,u-F+1);const H=A?g:Math.min(u+F,g)+l,G=Array(H+2);G[H+1]=(1<<D)-1;for(let K=H;K>=R;K-=1){const V=K-1,W=n[t[V]];if(G[K]=(G[K+1]<<1|1)&W,D&&(G[K]|=(I[K+1]|I[K])<<1|1|I[K+1]),G[K]&B&&(f=_(D,V),f<=h)){if(h=f,d=V,y=D,d<=u)break;R=Math.max(1,2*u-d)}}if(_(D+1,u)>h)break;I=G}if(p&&d>=0){const D=Math.min(g-1,d+l-1+y);for(let w=d;w<=D;w+=1)n[t[w]]&&(m[w]=1)}const S={isMatch:d>=0,score:Math.max(.001,f)};if(p){const D=rOo(m,s);D.length?a&&(S.indices=D):S.isMatch=!1}return S}function sOo(t){const e={};for(let n=0,o=t.length;n<o;n+=1){const i=t.charAt(n);e[i]=(e[i]||0)|1<<o-n-1}return e}function N3e(t){if(t.length<=1)return t;t.sort((n,o)=>n[0]-o[0]||n[1]-o[1]);const e=[t[0]];for(let n=1,o=t.length;n<o;n+=1){const i=e[e.length-1],r=t[n];r[0]<=i[1]+1?i[1]=Math.max(i[1],r[1]):e.push(r)}return e}const GRt={ł:"l",Ł:"L",đ:"d",Đ:"D",ø:"o",Ø:"O",ħ:"h",Ħ:"H",ŧ:"t",Ŧ:"T",ı:"i",ß:"ss"},aOo=new RegExp("["+Object.keys(GRt).join("")+"]","g"),tU=typeof String.prototype.normalize=="function"?t=>t.normalize("NFD").replace(/[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C04\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u192B\u1930-\u193B\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F]/g,"").replace(aOo,e=>GRt[e]):t=>t;var R3e=class{constructor(t,{location:e=vA.location,threshold:n=vA.threshold,distance:o=vA.distance,includeMatches:i=vA.includeMatches,findAllMatches:r=vA.findAllMatches,minMatchCharLength:A=vA.minMatchCharLength,isCaseSensitive:s=vA.isCaseSensitive,ignoreDiacritics:a=vA.ignoreDiacritics,ignoreLocation:c=vA.ignoreLocation}={}){if(this.options={location:e,threshold:n,distance:o,includeMatches:i,findAllMatches:r,minMatchCharLength:A,isCaseSensitive:s,ignoreDiacritics:a,ignoreLocation:c},t=s?t:t.toLowerCase(),t=a?tU(t):t,this.pattern=t,this.chunks=[],!this.pattern.length)return;const l=(u,h)=>{this.chunks.push({pattern:u,alphabet:sOo(u),startIndex:h})},g=this.pattern.length;if(g>32){let u=0;const h=g%32,d=g-h;for(;u<d;)l(this.pattern.substr(u,32),u),u+=32;if(h){const _=g-32;l(this.pattern.substr(_),_)}}else l(this.pattern,0)}searchIn(t){const{isCaseSensitive:e,ignoreDiacritics:n,includeMatches:o}=this.options;if(t=e?t:t.toLowerCase(),t=n?tU(t):t,this.pattern===t){if(t.length<this.options.minMatchCharLength)return{isMatch:!1,score:1};const d={isMatch:!0,score:0};return o&&(d.indices=[[0,t.length-1]]),d}const{location:i,distance:r,threshold:A,findAllMatches:s,minMatchCharLength:a,ignoreLocation:c}=this.options,l=[];let g=0,u=!1;this.chunks.forEach(({pattern:d,alphabet:_,startIndex:p})=>{const{isMatch:m,score:C,indices:I}=AOo(t,d,_,{location:i+p,distance:r,threshold:A,findAllMatches:s,minMatchCharLength:a,includeMatches:o,ignoreLocation:c});m&&(u=!0),g+=C,m&&I&&l.push(...I)});const h={isMatch:u,score:u?g/this.chunks.length:1};return u&&o&&(h.indices=N3e(l)),h}};const cOo=new Set(["fuzzy","include"]);function lOo(t){return t.startsWith("inverse")}const T3e=[{type:"exact",multiRegex:/^="(.*)"$/,singleRegex:/^=(.*)$/,create:t=>({type:"exact",search(e){const n=e===t;return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}})},{type:"include",multiRegex:/^'"(.*)"$/,singleRegex:/^'(.*)$/,create:t=>({type:"include",search(e){let n=0,o;const i=[],r=t.length;for(;(o=e.indexOf(t,n))>-1;)n=o+r,i.push([o,n-1]);const A=!!i.length;return{isMatch:A,score:A?0:1,indices:i}}})},{type:"prefix-exact",multiRegex:/^\^"(.*)"$/,singleRegex:/^\^(.*)$/,create:t=>({type:"prefix-exact",search(e){const n=e.startsWith(t);return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}})},{type:"inverse-prefix-exact",multiRegex:/^!\^"(.*)"$/,singleRegex:/^!\^(.*)$/,create:t=>({type:"inverse-prefix-exact",search(e){const n=!e.startsWith(t);return{isMatch:n,score:n?0:1,indices:[0,e.length-1]}}})},{type:"inverse-suffix-exact",multiRegex:/^!"(.*)"\$$/,singleRegex:/^!(.*)\$$/,create:t=>({type:"inverse-suffix-exact",search(e){const n=!e.endsWith(t);return{isMatch:n,score:n?0:1,indices:[0,e.length-1]}}})},{type:"suffix-exact",multiRegex:/^"(.*)"\$$/,singleRegex:/^(.*)\$$/,create:t=>({type:"suffix-exact",search(e){const n=e.endsWith(t);return{isMatch:n,score:n?0:1,indices:[e.length-t.length,e.length-1]}}})},{type:"inverse-exact",multiRegex:/^!"(.*)"$/,singleRegex:/^!(.*)$/,create:t=>({type:"inverse-exact",search(e){const n=e.indexOf(t)===-1;return{isMatch:n,score:n?0:1,indices:[0,e.length-1]}}})},{type:"fuzzy",multiRegex:/^"(.*)"$/,singleRegex:/^(.*)$/,create:(t,e={})=>{const n=new R3e(t,{location:e.location??vA.location,threshold:e.threshold??vA.threshold,distance:e.distance??vA.distance,includeMatches:e.includeMatches??vA.includeMatches,findAllMatches:e.findAllMatches??vA.findAllMatches,minMatchCharLength:e.minMatchCharLength??vA.minMatchCharLength,isCaseSensitive:e.isCaseSensitive??vA.isCaseSensitive,ignoreDiacritics:e.ignoreDiacritics??vA.ignoreDiacritics,ignoreLocation:e.ignoreLocation??vA.ignoreLocation});return{type:"fuzzy",search(o){return n.searchIn(o)}}}}],ORt=T3e.length,gOo="\0",uOo="|";function dOo(t){const e=[],n=t.length;let o=0;for(;o<n;){for(;o<n&&t[o]===" ";)o++;if(o>=n)break;let i=o;for(;i<n&&t[i]!==" "&&t[i]!=='"';)i++;if(i<n&&t[i]==='"'){for(i++;i<n;){if(t[i]==='"'){const r=i+1;if(r>=n||t[r]===" "){i++;break}if(t[r]==="$"&&(r+1>=n||t[r+1]===" ")){i+=2;break}}i++}e.push(t.substring(o,i)),o=i}else{for(;i<n&&t[i]!==" ";)i++;e.push(t.substring(o,i)),o=i}}return e}function KRt(t,e){const n=t.match(e);return n?n[1]:null}function hOo(t,e={}){return t.replace(/\\\|/g,gOo).split(uOo).map(n=>{const o=dOo(n.replace(/\u0000/g,"|").trim()).filter(r=>r&&!!r.trim()),i=[];for(let r=0,A=o.length;r<A;r+=1){const s=o[r];let a=!1,c=-1;for(;!a&&++c<ORt;){const l=T3e[c],g=KRt(s,l.multiRegex);g&&(i.push(l.create(g,e)),a=!0)}if(!a)for(c=-1;++c<ORt;){const l=T3e[c],g=KRt(s,l.singleRegex);if(g){i.push(l.create(g,e));break}}}return i})}var _Oo=class{constructor(t,{isCaseSensitive:e=vA.isCaseSensitive,ignoreDiacritics:n=vA.ignoreDiacritics,includeMatches:o=vA.includeMatches,minMatchCharLength:i=vA.minMatchCharLength,ignoreLocation:r=vA.ignoreLocation,findAllMatches:A=vA.findAllMatches,location:s=vA.location,threshold:a=vA.threshold,distance:c=vA.distance}={}){this.query=null,this.options={isCaseSensitive:e,ignoreDiacritics:n,includeMatches:o,minMatchCharLength:i,findAllMatches:A,ignoreLocation:r,location:s,threshold:a,distance:c},t=e?t:t.toLowerCase(),t=n?tU(t):t,this.pattern=t,this.query=hOo(this.pattern,this.options)}static condition(t,e){return e.useExtendedSearch}searchIn(t){const e=this.query;if(!e)return{isMatch:!1,score:1};const{includeMatches:n,isCaseSensitive:o,ignoreDiacritics:i}=this.options;t=o?t:t.toLowerCase(),t=i?tU(t):t;let r=0;const A=[];let s=0,a=!1;for(let c=0,l=e.length;c<l;c+=1){const g=e[c];A.length=0,r=0,a=!1;for(let u=0,h=g.length;u<h;u+=1){const d=g[u],{isMatch:_,indices:p,score:m}=d.search(t);if(_)r+=1,s+=m,lOo(d.type)&&(a=!0),n&&(cOo.has(d.type)?A.push(...p):A.push(p));else{s=0,r=0,A.length=0,a=!1;break}}if(r){const u={isMatch:!0,score:s/r};return a&&(u.hasInverse=!0),n&&(u.indices=N3e(A)),u}}return{isMatch:!1,score:1}}};const k3e=[];function F3e(...t){k3e.push(...t)}function Mie(t,e){for(let n=0,o=k3e.length;n<o;n+=1){const i=k3e[n];if(i.condition(t,e))return new i(t,e)}return new R3e(t,e)}const wie={AND:"$and",OR:"$or"},L3e={PATH:"$path",PATTERN:"$val"},H3e=t=>!!(t[wie.AND]||t[wie.OR]),mOo=t=>!!t[L3e.PATH],pOo=t=>!uw(t)&&RRt(t)&&!H3e(t),URt=t=>({[wie.AND]:Object.keys(t).map(e=>({[e]:t[e]}))});function YRt(t,e,{auto:n=!0}={}){const o=i=>{if(bC(i)){const a={keyId:null,pattern:i};return n&&(a.searcher=Mie(i,e)),a}const r=Object.keys(i),A=mOo(i);if(!A&&r.length>1&&!H3e(i))return o(URt(i));if(pOo(i)){const a=A?i[L3e.PATH]:r[0],c=A?i[L3e.PATTERN]:i[a];if(!bC(c))throw new Error(WGo(a));const l={keyId:Die(a),pattern:c};return n&&(l.searcher=Mie(c,e)),l}const s={children:[],operator:r[0]};return r.forEach(a=>{const c=i[a];uw(c)&&c.forEach(l=>{s.children.push(o(l))})}),s};return H3e(t)||(t=URt(t)),o(t)}function G3e(t,{ignoreFieldNorm:e=vA.ignoreFieldNorm}){let n=1;return t.forEach(({key:o,norm:i,score:r})=>{const A=o?o.weight:null;n*=Math.pow(r===0&&A?Number.EPSILON:r,(A||1)*(e?1:i))}),n}function IOo(t,{ignoreFieldNorm:e=vA.ignoreFieldNorm}){t.forEach(n=>{n.score=G3e(n.matches,{ignoreFieldNorm:e})})}var COo=class{constructor(t,e){this.limit=t,this.heap=[],this.comparator=e}get size(){return this.heap.length}insert(t){this.size<this.limit?(this.heap.push(t),this._bubbleUp(this.size-1)):this.comparator(t,this.heap[0])<0&&(this.heap[0]=t,this._sinkDown(0))}extractSorted(){return this.heap.sort(this.comparator)}_bubbleUp(t){const e=this.heap;for(;t>0;){const n=t-1>>1;if(this.comparator(e[t],e[n])<=0)break;const o=e[t];e[t]=e[n],e[n]=o,t=n}}_sinkDown(t){const e=this.heap,n=e.length;let o=t;do{t=o;const i=2*t+1,r=2*t+2;if(i<n&&this.comparator(e[i],e[o])>0&&(o=i),r<n&&this.comparator(e[r],e[o])>0&&(o=r),o!==t){const A=e[t];e[t]=e[o],e[o]=A}}while(o!==t)}};function fOo(t){const e=[];return t.matches.forEach(n=>{if(!O2(n.indices)||!n.indices.length)return;const o={indices:n.indices,value:n.value};n.key&&(o.key=n.key.id),n.idx>-1&&(o.refIndex=n.idx),e.push(o)}),e}function yOo(t,e,{includeMatches:n=vA.includeMatches,includeScore:o=vA.includeScore}={}){return t.map(i=>{const{idx:r}=i,A={item:e[r],refIndex:r};return n&&(A.matches=fOo(i)),o&&(A.score=i.score),A})}const EOo=/[\p{L}\p{M}\p{N}_]+/gu,zRt=new WeakSet;function xOo(t){zRt.has(t)||(zRt.add(t),console.warn(`[Fuse] tokenize regex ${t} lacks the global flag; only the first match per text will be returned. Add the 'g' flag.`))}function BOo(t){if(typeof t=="function"){let e=!1;return n=>{const o=t(n);if(!e&&(e=!0,!Array.isArray(o)||o.some(i=>typeof i!="string")))throw new Error(`[Fuse] tokenize function must return string[]; received ${Array.isArray(o)?"array containing non-strings":typeof o}.`);return o}}return t instanceof RegExp?(t.global||xOo(t),e=>e.match(t)||[]):e=>e.match(EOo)||[]}function O3e({isCaseSensitive:t=!1,ignoreDiacritics:e=!1,tokenize:n}={}){const o=BOo(n);return{tokenize(i){return t||(i=i.toLowerCase()),e&&(i=tU(i)),o(i)}}}var QOo=class{static condition(t,e){return e.useTokenSearch}constructor(t,e){this.options=e,this.analyzer=O3e({isCaseSensitive:e.isCaseSensitive,ignoreDiacritics:e.ignoreDiacritics,tokenize:e.tokenize});const n=this.analyzer.tokenize(t),{df:o,fieldCount:i}=e._invertedIndex;this.termSearchers=[],this.idfWeights=[];for(const r of n){this.termSearchers.push(new R3e(r,{location:e.location,threshold:e.threshold,distance:e.distance,includeMatches:e.includeMatches,findAllMatches:e.findAllMatches,minMatchCharLength:e.minMatchCharLength,isCaseSensitive:e.isCaseSensitive,ignoreDiacritics:e.ignoreDiacritics,ignoreLocation:!0}));const A=o.get(r)||0,s=Math.log(1+(i-A+.5)/(A+.5));this.idfWeights.push(s)}this.combineAll=e.tokenMatch==="all",this.numTerms=this.termSearchers.length,this.useMask=this.numTerms<=31}searchIn(t){if(!this.termSearchers.length)return{isMatch:!1,score:1};const e=[];let n=0,o=0,i=0,r=0;const A=this.combineAll&&!this.useMask?new Set:null;for(let c=0;c<this.termSearchers.length;c++){const l=this.termSearchers[c].searchIn(t),g=this.idfWeights[c];o+=g,l.isMatch&&(i++,n+=g*(1-l.score),l.indices&&e.push(...l.indices),this.combineAll&&(this.useMask?r|=1<<c:A.add(c)))}if(i===0)return{isMatch:!1,score:1};const s=o>0?1-n/o:0,a={isMatch:!0,score:Math.max(.001,s)};return this.options.includeMatches&&e.length&&(a.indices=N3e(e)),this.combineAll&&(this.useMask?a.matchedMask=r:a.matchedTerms=A,a.termCount=this.numTerms),a}};function K3e(t,e,n,o){const i=o.tokenize(e);if(!i.length)return;t.fieldCount++,t.docFieldCount.set(n,(t.docFieldCount.get(n)||0)+1);const r=new Set(i);let A=t.docTermFieldHits.get(n);A||(A=new Map,t.docTermFieldHits.set(n,A));for(const s of r)A.set(s,(A.get(s)||0)+1),t.df.set(s,(t.df.get(s)||0)+1)}function VRt(t,e,n,o){const{i,v:r,$:A}=e;if(r!==void 0){K3e(t,r,i,o);return}if(A)for(let s=0;s<n;s++){const a=A[s];if(a)if(Array.isArray(a))for(const c of a)K3e(t,c.v,i,o);else K3e(t,a.v,i,o)}}function SOo(t,e,n){const o={fieldCount:0,df:new Map,docFieldCount:new Map,docTermFieldHits:new Map};for(const i of t)VRt(o,i,e,n);return o}function bOo(t,e,n,o){VRt(t,e,n,o)}function DOo(t,e){const n=t.docFieldCount.get(e);if(n===void 0)return;t.fieldCount-=n,t.docFieldCount.delete(e);const o=t.docTermFieldHits.get(e);if(o){for(const[i,r]of o){const A=(t.df.get(i)||0)-r;A<=0?t.df.delete(i):t.df.set(i,A)}t.docTermFieldHits.delete(e)}}function JRt(t,e){if(e.length===0)return;const n=Array.from(new Set(e)).sort((s,a)=>s-a);for(const s of n)DOo(t,s);const o=s=>{let a=0,c=n.length;for(;a<c;){const l=a+c>>>1;n[l]<s?a=l+1:c=l}return s-a},i=n[0],r=new Map;for(const[s,a]of t.docFieldCount)r.set(s>i?o(s):s,a);t.docFieldCount=r;const A=new Map;for(const[s,a]of t.docTermFieldHits)A.set(s>i?o(s):s,a);t.docTermFieldHits=A}var dw=class{constructor(t,e,n){this.options={...vA,...e},this.options.useExtendedSearch,this.options.useTokenSearch,this._keyStore=new eOo(this.options.keys),this._docs=t,this._myIndex=null,this._invertedIndex=null,this.setCollection(t,n),this._lastQuery=null,this._lastSearcher=null}_getSearcher(t){if(this._lastQuery===t)return this._lastSearcher;const e=Mie(t,this._invertedIndex?{...this.options,_invertedIndex:this._invertedIndex}:this.options);return this._lastQuery=t,this._lastSearcher=e,e}setCollection(t,e){if(this._docs=t,e&&!(e instanceof v3e))throw new Error(qGo);if(this._myIndex=e||HRt(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight}),this.options.useTokenSearch){const n=O3e({isCaseSensitive:this.options.isCaseSensitive,ignoreDiacritics:this.options.ignoreDiacritics,tokenize:this.options.tokenize});this._invertedIndex=SOo(this._myIndex.records,this._myIndex.keys.length,n)}this._invalidateSearcherCache()}add(t){if(!O2(t))return;this._docs.push(t);const e=this._myIndex.add(t,this._docs.length-1);if(this._invertedIndex&&e){const n=O3e({isCaseSensitive:this.options.isCaseSensitive,ignoreDiacritics:this.options.ignoreDiacritics,tokenize:this.options.tokenize});bOo(this._invertedIndex,e,this._myIndex.keys.length,n)}this._invalidateSearcherCache()}remove(t=()=>!1){const e=[],n=[];for(let o=0,i=this._docs.length;o<i;o+=1)t(this._docs[o],o)&&(e.push(this._docs[o]),n.push(o));if(n.length){this._invertedIndex&&JRt(this._invertedIndex,n);const o=new Set(n);this._docs=this._docs.filter((i,r)=>!o.has(r)),this._myIndex.removeAll(n),this._invalidateSearcherCache()}return e}removeAt(t){if(!Number.isInteger(t)||t<0||t>=this._docs.length)throw new Error(P3e);this._invertedIndex&&JRt(this._invertedIndex,[t]);const e=this._docs.splice(t,1)[0];return this._myIndex.removeAt(t),this._invalidateSearcherCache(),e}_invalidateSearcherCache(){this._lastQuery=null,this._lastSearcher=null}getIndex(){return this._myIndex}_normalizedKeys(){return this._myIndex.keys.map(t=>this._keyStore.get(t.id)||t)}search(t,e){const{limit:n=-1}=e||{},{includeMatches:o,includeScore:i,shouldSort:r,sortFn:A,ignoreFieldNorm:s}=this.options;if(bC(t)&&!t.trim()){let u=this._docs.map((h,d)=>({item:h,refIndex:d}));return Sie(n)&&n>-1&&(u=u.slice(0,n)),u}const a=r&&Sie(n)&&n>0&&bC(t),c=A,l=(u,h)=>c(u,h)||u.idx-h.idx;let g;if(a){const u=new COo(n,l);bC(this._docs[0])?this._searchStringList(t,{heap:u,ignoreFieldNorm:s}):this._searchObjectList(t,{heap:u,ignoreFieldNorm:s}),g=u.extractSorted()}else g=bC(t)?bC(this._docs[0])?this._searchStringList(t):this._searchObjectList(t):this._searchLogical(t),IOo(g,{ignoreFieldNorm:s}),r&&g.sort(bC(t)?l:c),Sie(n)&&n>-1&&(g=g.slice(0,n));return yOo(g,this._docs,{includeMatches:o,includeScore:i})}_searchStringList(t,{heap:e,ignoreFieldNorm:n}={}){const o=this._getSearcher(t),i=this.options.useTokenSearch&&this.options.tokenMatch==="all",{records:r}=this._myIndex,A=e?null:[];return r.forEach(({v:s,i:a,n:c})=>{if(!O2(s))return;const l=o.searchIn(s);if(l.isMatch){const g={score:l.score,value:s,norm:c,indices:l.indices};i&&(g.matchedMask=l.matchedMask,g.matchedTerms=l.matchedTerms,g.termCount=l.termCount);const u=[g];if(!i||this._coversAllTokens(u)){const h={item:s,idx:a,matches:u};e?(h.score=G3e(h.matches,{ignoreFieldNorm:n}),e.insert(h)):A.push(h)}}}),A}_searchLogical(t){const e=YRt(t,this.options),n=this._normalizedKeys(),o=(s,a,c)=>{if(!("children"in s)){const{keyId:h,searcher:d}=s;let _;return h===null?(_=[],n.forEach((p,m)=>{_.push(...this._findMatches({key:p,value:a[m],searcher:d}))})):_=this._findMatches({key:this._keyStore.get(h),value:this._myIndex.getValueForItemAtKeyId(a,h),searcher:d}),_&&_.length?[{idx:c,item:a,matches:_}]:[]}const{children:l,operator:g}=s,u=[];for(let h=0,d=l.length;h<d;h+=1){const _=l[h],p=o(_,a,c);if(p.length)u.push(...p);else if(g===wie.AND)return[]}return u},i=this._myIndex.records,r=new Map,A=[];return i.forEach(({$:s,i:a})=>{if(O2(s)){const c=o(e,s,a);c.length&&(r.has(a)||(r.set(a,{idx:a,item:s,matches:[]}),A.push(r.get(a))),c.forEach(({matches:l})=>{r.get(a).matches.push(...l)}))}}),A}_searchObjectList(t,{heap:e,ignoreFieldNorm:n}={}){const o=this._getSearcher(t),i=this.options.useTokenSearch&&this.options.tokenMatch==="all",{records:r}=this._myIndex,A=this._normalizedKeys(),s=e?null:[];return r.forEach(({$:a,i:c})=>{if(!O2(a))return;const l=[];let g=!1,u=!1;if(A.forEach((h,d)=>{const _=this._findMatches({key:h,value:a[d],searcher:o});_.length?(l.push(..._),_[0].hasInverse&&(u=!0)):g=!0}),!(u&&g)&&l.length&&(!i||this._coversAllTokens(l))){const h={idx:c,item:a,matches:l};e?(h.score=G3e(h.matches,{ignoreFieldNorm:n}),e.insert(h)):s.push(h)}}),s}_findMatches({key:t,value:e,searcher:n}){if(!O2(e))return[];const o=[];if(uw(e))e.forEach(({v:i,i:r,n:A})=>{if(!O2(i))return;const s=n.searchIn(i);if(s.isMatch){const a={score:s.score,key:t,value:i,idx:r,norm:A,indices:s.indices,hasInverse:s.hasInverse};s.termCount!==void 0&&(a.matchedMask=s.matchedMask,a.matchedTerms=s.matchedTerms,a.termCount=s.termCount),o.push(a)}});else{const{v:i,n:r}=e,A=n.searchIn(i);if(A.isMatch){const s={score:A.score,key:t,value:i,norm:r,indices:A.indices,hasInverse:A.hasInverse};A.termCount!==void 0&&(s.matchedMask=A.matchedMask,s.matchedTerms=A.matchedTerms,s.termCount=A.termCount),o.push(s)}}return o}_coversAllTokens(t){const e=t.length?t[0].termCount:void 0;if(e===void 0)return!0;if(e<=31){let o=0;for(let i=0;i<t.length;i++)o|=t[i].matchedMask||0;return o===2**e-1}const n=new Set;for(let o=0;o<t.length;o++){const i=t[o].matchedTerms;if(i)for(const r of i)n.add(r)}return n.size===e}};dw.version="7.5.0",dw.createIndex=HRt,dw.parseIndex=iOo,dw.config=vA,dw.match=function(t,e,n){if(n&&n.useTokenSearch)throw new Error(ZGo);return Mie(t,{...vA,...n}).searchIn(e)},dw.parseQuery=YRt,F3e(_Oo),F3e(QOo),dw.use=function(...t){t.forEach(e=>F3e(e))};var MOo=dw;const wOo="https://kicad-mod-cache.tscircuit.com";let U3e=null,nU=null,Y3e=null;const POo=async()=>U3e||nU||(nU=fetch("https://kicad-mod-cache.tscircuit.com/kicad_files.json").then(t=>t.json()).then(t=>(U3e=t,nU=null,t)),nU),vOo=async(t,e=20)=>{const n=await POo();return Y3e||(Y3e=new MOo(n)),Y3e.search(t).slice(0,e).map(o=>o.item)},NOo=t=>{const e=t.replace(".pretty/","/").replace(".kicad_mod",""),n=`kicad:${e}`;return{path:t,qualifiedName:n,description:e}},ROo=t=>t.replace(/^\/+/,"").split("/").map(e=>encodeURIComponent(e)).join("/"),TOo=async t=>{const e=await fetch(`${wOo}/${ROo(t)}`);if(!e.ok)throw new Error(`KiCad footprint fetch failed: ${e.status}`);const n=await e.text(),{KicadFootprintToCircuitJsonConverter:o}=await DB("kicad-to-circuit-json"),i=new o;return i.addFile(t.split("/").pop()??"selected-footprint.kicad_mod",n),i.runUntilFinished(),i.getOutput()},qRt=t=>t?.source==="jlcpcb"||t?.source==="kicad",kOo=async(t,e)=>{if(t.source==="jlcpcb")return YGo(t.component.partNumber,e?.jlcpcb);if(t.source==="kicad")return TOo(t.footprint.path);throw new Error("Footprint preview is not available for this source")},FOo=({query:t,placeholder:e,isSearching:n,onQueryChange:o,onSubmit:i})=>{const r=j.useCallback(A=>{A.key==="Enter"&&(A.preventDefault(),i())},[i]);return J.jsxs("div",{className:"rf-flex rf-items-center rf-gap-2 rf-mt-4",children:[J.jsxs("div",{className:"rf-relative rf-flex-grow",children:[J.jsx(Wwe,{className:"rf-absolute rf-left-2 rf-top-2.5 rf-h-4 rf-w-4 rf-text-muted-foreground"}),J.jsx(YPe,{placeholder:e,className:"rf-pl-8",spellCheck:!1,autoComplete:"off",value:t,onChange:A=>o(A.target.value),onKeyDown:r})]}),J.jsx(ta,{onClick:i,disabled:n||t.trim().length<1,className:"sm:rf-px-4 rf-px-3",children:n?J.jsx(SB,{className:"rf-h-4 rf-w-4 rf-animate-spin"}):J.jsxs(J.Fragment,{children:[J.jsx(Wwe,{className:"rf-h-4 rf-w-4 sm:rf-hidden"}),J.jsx("span",{className:"rf-hidden sm:rf-inline",children:"Search"})]})})]})},LOo=new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}),HOo=t=>LOo.format(t),WRt=t=>{switch(t.source){case"tscircuit.com":{const e=t.package;return`tscircuit-${e.package_id??`${e.org_owner_tscircuit_handle??"unknown"}-${e.unscoped_name??e.name??"package"}`}`}case"jlcpcb":return`jlc-${t.component.lcscId}`;case"kicad":return`kicad-${t.footprint.path}`;default:return"unknown"}},GOo=t=>{switch(t.source){case"tscircuit.com":return t.package.unscoped_name;case"jlcpcb":return t.component.isDirectLookup?t.component.partNumber:t.component.manufacturer;case"kicad":return t.footprint.qualifiedName}},OOo=t=>{switch(t.source){case"tscircuit.com":return t.package.description||(t.package.org_owner_tscircuit_handle?`Component by ${t.package.org_owner_tscircuit_handle}`:void 0);case"jlcpcb":return t.component.description;case"kicad":return t.footprint.description}},KOo=t=>{switch(t.source){case"tscircuit.com":return t.package.name;case"jlcpcb":return t.component.isDirectLookup?void 0:t.component.partNumber;case"kicad":return}},UOo=({results:t,selected:e,onSelect:n,onShowDetails:o})=>{const i=e?WRt(e):null;return J.jsx("div",{className:"rf-divide-y rf-w-full rf-overflow-hidden",children:t.map(r=>{const A=WRt(r),s=i===A,a=GOo(r),c=OOo(r),l=KOo(r),g=r.source==="jlcpcb"?r.component.stock:null,u=r.source==="jlcpcb"?r.component.price:null,h=r.source==="jlcpcb"?r.component.isBasic:null,d=r.source==="jlcpcb"?r.component.isDirectLookup:!1;return J.jsxs("div",{className:`rf-p-3 rf-flex rf-flex-col sm:rf-grid sm:rf-grid-cols-[minmax(0,1fr)_auto] rf-items-start sm:rf-items-center rf-cursor-pointer hover:rf-bg-zinc-100 rf-gap-2 rf-overflow-hidden ${s?"rf-bg-zinc-100":""}`,onClick:()=>n(r),children:[J.jsxs("div",{className:"rf-min-w-0 rf-overflow-hidden rf-w-full",children:[J.jsxs("div",{className:"rf-flex rf-items-start rf-gap-2 rf-min-w-0",children:[J.jsxs("div",{className:"rf-font-medium rf-text-sm rf-truncate rf-flex-1 rf-min-w-0 rf-flex rf-items-center rf-gap-1.5",children:[a,r.source==="jlcpcb"&&h!=null&&J.jsx("span",{className:`rf-text-xs rf-px-1.5 rf-py-0.5 rf-rounded rf-font-medium rf-flex-shrink-0 ${h?"rf-bg-green-100 rf-text-green-700":"rf-bg-orange-100 rf-text-orange-700"}`,children:h?"Basic":"Extended"}),d&&J.jsx("span",{className:"rf-text-xs rf-px-1.5 rf-py-0.5 rf-rounded rf-font-medium rf-flex-shrink-0 rf-bg-blue-100 rf-text-blue-700",children:"Direct lookup"}),r.source==="tscircuit.com"&&r.package.is_private&&J.jsx(NPo,{className:"rf-ml-1 rf-h-3 rf-w-3 rf-text-zinc-400 rf-flex-shrink-0"})]}),r.source==="jlcpcb"&&g!=null?J.jsxs("div",{className:"rf-text-xs rf-text-zinc-500 rf-font-medium rf-whitespace-nowrap rf-flex-shrink-0 sm:rf-hidden",children:[g.toLocaleString()," in stock"]}):null]}),J.jsxs("div",{className:"rf-text-xs rf-text-zinc-500 rf-truncate rf-w-full",children:[l?J.jsx("span",{className:"rf-mr-2",children:l}):null,c]})]}),J.jsxs("div",{children:[r.source==="tscircuit.com"&&o?J.jsx("div",{className:"rf-flex-shrink-0 rf-w-full sm:rf-w-auto",children:J.jsx(ta,{variant:"outline",size:"sm",className:"rf-text-xs rf-w-full sm:rf-w-auto",onClick:_=>{_.stopPropagation(),o(r)},children:"See Details"})}):r.source==="jlcpcb"&&g!=null?J.jsxs("div",{className:"rf-hidden sm:rf-block rf-text-xs rf-text-zinc-500 rf-font-medium rf-whitespace-nowrap rf-flex-shrink-0",children:[g.toLocaleString()," in stock"]}):null,u!=null&&J.jsx("div",{className:"rf-hidden sm:rf-block rf-text-xs rf-text-zinc-500 rf-font-medium rf-whitespace-nowrap rf-flex-shrink-0 rf-text-right",children:HOo(u)})]})]},A)})})},YOo=({circuitJson:t,error:e,isLoading:n,height:o})=>J.jsx("section",{className:"rf-flex rf-min-w-0 rf-items-center rf-justify-center",style:{height:o},children:n?J.jsxs("div",{className:"rf-flex rf-w-full rf-items-center rf-justify-center rf-gap-2 rf-bg-zinc-950 rf-text-sm rf-text-zinc-300",style:{height:o},children:[J.jsx(SB,{className:"rf-h-4 rf-w-4 rf-animate-spin"}),"Loading preview..."]}):e?J.jsx("div",{className:"rf-flex rf-w-full rf-items-center rf-justify-center rf-bg-zinc-950 rf-p-4",style:{height:o},children:J.jsxs("div",{className:"rf-flex rf-max-w-[320px] rf-items-start rf-gap-2 rf-text-sm rf-text-zinc-300",children:[J.jsx(TPt,{className:"rf-mt-0.5 rf-h-4 rf-w-4 rf-flex-shrink-0"}),J.jsx("span",{children:e})]})}):t?J.jsx("div",{className:"rf-w-full rf-min-w-0 rf-overflow-hidden",children:J.jsx(nRt,{circuitJson:t,height:o,allowEditing:!1,clickToInteractEnabled:!1,focusOnHover:!1,disablePcbGroups:!0})}):J.jsx("div",{className:"rf-flex rf-w-full rf-items-center rf-justify-center rf-bg-zinc-950 rf-text-sm rf-text-zinc-300",style:{height:o},children:"No preview"})}),jRt={importComponentDialog:101,importComponentDetailsDialog:102},zOo=({packageResult:t,isOpen:e,onOpenChange:n,isLoading:o,details:i,previewTab:r,onPreviewTabChange:A,isSubmitting:s,onImport:a})=>{const c=t?.package??null,l=c?.latest_pcb_preview_image_url,g=c?.latest_sch_preview_image_url,u=c?.latest_cad_preview_image_url,h=c?.unscoped_name?.split("/").pop()??c?.unscoped_name,d=c?.org_owner_tscircuit_handle??void 0,_=d?`https://tscircuit.com/${d}`:void 0,p=d&&h?`https://tscircuit.com/${d}/${h}`:void 0;return J.jsx(DT,{open:e,onOpenChange:n,children:J.jsxs(j3,{showOverlay:!1,style:{width:"calc(100vw - 2rem)",zIndex:jRt.importComponentDetailsDialog},className:"rf-max-w-5xl no-scrollbar !rf-overflow-y-auto rf-max-h-[90vh] rf-overflow-hidden rf-flex rf-flex-col rf-rounded-sm",children:[J.jsx(X3,{className:"rf-pb-4 rf-border-b",children:J.jsx("div",{className:"rf-flex rf-items-start rf-justify-between rf-gap-4",children:J.jsxs("div",{className:"rf-flex-1 rf-min-w-0",children:[J.jsx($3,{className:"rf-text-xl rf-font-semibold rf-truncate",children:h}),J.jsx(MT,{children:c?.description})]})})}),J.jsxs("div",{className:"rf-flex-1 rf-overflow-y-auto rf-py-4 rf-space-y-6",children:[d?J.jsxs("div",{children:[J.jsx("span",{className:"rf-text-xs rf-font-medium rf-text-gray-500 rf-uppercase rf-tracking-wide",children:"Created by"}),J.jsx("div",{className:"rf-mt-1 rf-text-sm rf-font-medium",children:_?J.jsx("a",{href:_,target:"_blank",rel:"noopener noreferrer",className:"rf-text-black hover:rf-underline",children:d}):d})]}):null,(u||l||g)&&J.jsx(J.Fragment,{children:J.jsxs("div",{children:[J.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-mb-4",children:"Preview"}),J.jsxs(K1e,{value:r,onValueChange:m=>A(m),children:[J.jsxs(FZ,{className:"rf-inline-flex rf-h-9 rf-items-center rf-justify-center rf-rounded-lg rf-bg-zinc-100 rf-p-1 rf-text-zinc-500 dark:rf-bg-zinc-800 dark:rf-text-zinc-400",children:[l&&J.jsx(XQ,{value:"pcb",children:"PCB"}),g&&J.jsx(XQ,{value:"schematic",children:"Schematic"}),u&&J.jsx(XQ,{value:"3d",children:"3D"})]}),J.jsxs("div",{className:"rf-mt-4",children:[J.jsx(IC,{value:"pcb",className:"rf-border rf-rounded-lg rf-overflow-hidden rf-bg-gray-50",children:l?J.jsx("img",{src:l,alt:`${h??"package"} PCB preview`,className:"rf-w-full rf-h-full rf-object-contain rf-bg-white rf-p-4"}):null}),J.jsx(IC,{value:"schematic",className:"rf-border rf-rounded-lg rf-overflow-hidden rf-bg-gray-50",children:g?J.jsx("img",{src:g,alt:`${h??"package"} schematic preview`,className:"rf-w-full rf-h-full rf-object-contain rf-bg-white rf-p-4"}):null}),J.jsx(IC,{value:"3d",className:"rf-border rf-rounded-lg rf-overflow-hidden rf-bg-gray-50",children:u?J.jsx("img",{src:u,alt:`${h??"package"} 3D preview`,className:"rf-w-full rf-h-full rf-object-contain rf-bg-white rf-p-4"}):null})]})]})]})}),i?.ai_description?J.jsxs("section",{children:[J.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-mb-3",children:"AI Description"}),J.jsx("div",{className:"rf-bg-gray-50 rf-border rf-border-gray-200 rf-rounded-lg rf-p-4",children:J.jsx("p",{className:"rf-text-sm rf-text-gray-700 rf-leading-relaxed",children:i.ai_description})})]}):null,i?.ai_usage_instructions?J.jsxs("section",{children:[J.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-mb-3",children:"Usage Instructions"}),J.jsx("div",{className:"rf-bg-gray-50 rf-border rf-border-gray-200 rf-rounded-lg rf-p-4",children:J.jsx("p",{className:"rf-text-sm rf-text-gray-700 rf-leading-relaxed rf-whitespace-pre-wrap",children:i.ai_usage_instructions})})]}):null,o?J.jsxs("div",{className:"rf-flex rf-justify-center rf-items-center rf-gap-2 rf-text-gray-500",children:[J.jsx(SB,{className:"rf-h-4 rf-w-4 rf-animate-spin"}),J.jsx("span",{className:"rf-text-sm",children:"Loading package details..."})]}):null]}),J.jsxs(eU,{className:"rf-pt-4 rf-border-t rf-flex rf-flex-col sm:rf-flex-row rf-justify-between rf-gap-2",children:[J.jsx("div",{className:"rf-flex-1",children:p?J.jsxs(ta,{variant:"outline",size:"sm",className:"rf-gap-2 rf-w-full sm:rf-w-auto",onClick:()=>window.open(p,"_blank"),children:[J.jsx(SPo,{className:"rf-h-4 rf-w-4"}),"View on tscircuit.com"]}):null}),J.jsxs("div",{className:"rf-flex rf-flex-col sm:rf-flex-row rf-gap-2",children:[J.jsx(ta,{variant:"outline",onClick:()=>n(!1),className:"rf-order-2 sm:rf-order-1",children:"Close"}),J.jsx(ta,{onClick:a,disabled:s,className:"rf-bg-blue-600 hover:rf-bg-blue-700",children:s?J.jsx(SB,{className:"rf-h-4 rf-w-4 rf-animate-spin"}):"Import Component"})]})]})]})})},VOo=()=>{const[t,e]=j.useState(null),[n,o]=j.useState(!1),i=j.useCallback(async(A,s)=>{o(!0);try{const a=await fetch(`https://api.tscircuit.com/packages/get?name=${encodeURIComponent(`${A}/${s}`)}`);if(!a.ok)throw new Error(`Failed to load package details: ${a.status}`);const c=await a.json();e(c.package??null)}catch(a){console.error("Failed to fetch package details",a),e(null)}finally{o(!1)}},[]),r=j.useCallback(()=>{e(null),o(!1)},[]);return{details:t,isLoading:n,fetchDetails:i,reset:r}},JOo=(t,e)=>{const[n,o]=j.useState({circuitJson:null,error:null,isLoading:!1});return j.useEffect(()=>{if(!t||!qRt(t)){o({circuitJson:null,error:null,isLoading:!1});return}let i=!1;return o({circuitJson:null,error:null,isLoading:!0}),kOo(t,e).then(r=>{i||o({circuitJson:r,error:null,isLoading:!1})}).catch(r=>{i||o({circuitJson:null,error:r instanceof Error?r.message:"Failed to load footprint preview",isLoading:!1})}),()=>{i=!0}},[t,e]),n},qOo=async(t,e)=>{const n={"Content-Type":"application/json"};e&&(n.Authorization=`Bearer ${e}`);const o=await fetch("https://registry-api.tscircuit.com/packages/search",{method:"POST",headers:n,body:JSON.stringify({query:t})});if(!o.ok)throw new Error(`tscircuit registry error: ${o.status}`);return(await o.json()).packages??[]},WOo=({sessionToken:t})=>{const[e,n]=j.useState([]),[o,i]=j.useState(!1),[r,A]=j.useState(null),[s,a]=j.useState(!1),c=j.useCallback(async g=>{const u=g.trim();if(!u)return[];i(!0),A(null);try{const d=(await qOo(u,t)).map(_=>({source:"tscircuit.com",package:_}));return n(d),d}catch(h){return console.error("Error searching tscircuit packages",h),n([]),A(h instanceof Error?h.message:"Failed to search tscircuit packages"),[]}finally{i(!1),a(!0)}},[t]),l=j.useCallback(()=>{n([]),i(!1),A(null),a(!1)},[]);return{results:e,isSearching:o,error:r,hasSearched:s,search:c,reset:l}},jOo=t=>{const e=/^C(\d+)$/i.exec(t.trim());if(!e)return null;const n=Number(e[1]);if(!Number.isSafeInteger(n))return null;const o=`C${e[1]}`;return{source:"jlcpcb",component:{lcscId:n,manufacturer:o,partNumber:o,description:"Import directly from EasyEDA; stock and availability are unknown",package:"",isDirectLookup:!0}}},XRt=(t,e)=>{const n=jOo(t);return n?e.some(i=>i.component.partNumber.toUpperCase()===n.component.partNumber)?e:[n,...e]:e},XOo=t=>{const e=t.trim();return/^C\d+/i.test(e)?e.replace(/^C/i,""):e},$Oo=()=>{const[t,e]=j.useState([]),[n,o]=j.useState(!1),[i,r]=j.useState(null),[A,s]=j.useState(!1),a=j.useCallback(async l=>{const g=XOo(l);if(!g)return[];o(!0),r(null);try{const u=await OGo(g,10),h=XRt(l,u.map(d=>({source:"jlcpcb",component:KGo(d)})));return e(h),h}catch(u){console.error("Error searching JLCPCB components",u);const h=XRt(l,[]);return e(h),r(h.length>0?null:u instanceof Error?u.message:"Failed to search JLCPCB components"),h}finally{o(!1),s(!0)}},[]),c=j.useCallback(()=>{e([]),o(!1),r(null),s(!1)},[]);return{results:t,isSearching:n,error:i,hasSearched:A,search:a,reset:c}},ZOo=()=>{const[t,e]=j.useState([]),[n,o]=j.useState(!1),[i,r]=j.useState(null),[A,s]=j.useState(!1),a=j.useCallback(async l=>{const g=l.trim();if(!g)return[];o(!0),r(null);try{const h=(await vOo(g,20)).map(d=>({source:"kicad",footprint:NOo(d)}));return e(h),h}catch(u){return console.error("Error searching KiCad footprints",u),e([]),r(u instanceof Error?u.message:"Failed to search KiCad footprints"),[]}finally{o(!1),s(!0)}},[]),c=j.useCallback(()=>{e([]),o(!1),r(null),s(!1)},[]);return{results:t,isSearching:n,error:i,hasSearched:A,search:a,reset:c}},eKo=({onTscircuitPackageSelected:t,onJlcpcbComponentTsxLoaded:e,onKicadStringSelected:n})=>{const o=[];return t&&o.push("tscircuit.com"),e&&o.push("jlcpcb"),n&&o.push("kicad"),o},tKo=({isOpen:t,onClose:e,jlcpcbProxyRequestHeaders:n,onKicadStringSelected:o,onTscircuitPackageSelected:i,onJlcpcbComponentTsxLoaded:r,jlcpcbProxyApiBase:A,tscircuitSessionToken:s})=>{fie();const a=j.useMemo(()=>eKo({onKicadStringSelected:o,onTscircuitPackageSelected:i,onJlcpcbComponentTsxLoaded:r}),[o,i,r]),c=a.length>0,l=a.length===1,[g,u]=j.useState(a[0]??"tscircuit.com"),[h,d]=j.useState(""),[_,p]=j.useState(null),{results:m,isSearching:C,error:I,hasSearched:f,search:y,reset:x}=WOo({sessionToken:s}),{results:B,isSearching:S,error:D,hasSearched:w,search:F,reset:R}=$Oo(),{results:H,isSearching:G,error:K,hasSearched:V,search:W,reset:X}=ZOo(),{details:ie,isLoading:se,fetchDetails:ee,reset:oe}=VOo(),[ae,re]=j.useState(null),[le,fe]=j.useState(!1),[ye,be]=j.useState("pcb"),[ue,Be]=j.useState(null),[pe,Ge]=j.useState(!1),Je=j.useMemo(()=>({jlcpcb:{headers:n,apiBase:A}}),[A,n]),{circuitJson:nt,error:Ie,isLoading:Ze}=JOo(_,Je),Ke=qRt(_);j.useEffect(()=>{Be(null)},[_]);const Ye=j.useCallback(()=>{x(),R(),X(),p(null)},[R,X,x]);j.useEffect(()=>{t||(Ye(),d(""),fe(!1),re(null),Be(null))},[t,Ye]),j.useEffect(()=>{d(""),p(null),g==="tscircuit.com"?x():g==="jlcpcb"?R():g==="kicad"&&X()},[g,R,X,x]);const qe=lt=>{p(lt),re(lt),be("pcb"),fe(!0),oe();const Ct=lt.package.org_owner_tscircuit_handle,Dt=lt.package.unscoped_name;if(Ct&&Dt){const pt=Dt.split("/").pop()??Dt;ee(Ct,pt)}},Le=async()=>{h.trim()&&(p(null),g==="tscircuit.com"?await y(h):g==="jlcpcb"?await F(h):g==="kicad"&&await W(h))},Se=async lt=>{try{if(Be(null),Ge(!0),lt.source==="kicad"){if(!o)throw new Error("KiCad handler not provided");await o({result:lt,footprint:lt.footprint.qualifiedName})}else if(lt.source==="jlcpcb"){if(!r)throw new Error("JLCPCB handler not provided");const Ct=await UGo(lt.component.partNumber,{headers:n,apiBase:A});await r({result:lt,tsx:Ct})}else if(lt.source==="tscircuit.com"){if(!i)throw new Error("tscircuit package handler not provided");const Ct=lt.package.org_owner_tscircuit_handle,Dt=lt.package.unscoped_name;if(!Ct||!Dt)throw new Error("Missing package metadata");const pt=Dt.split("/").pop()??Dt,Nt=`@tsci/${Ct}.${pt}`;await i({result:lt,fullPackageName:Nt})}return!0}catch(Ct){return console.error("Failed to import component",Ct),Be(Ct instanceof Error?Ct.message:"Failed to import component"),!1}finally{Ge(!1)}};let ve=[],Pe=!1,ze=null,Xe=!1;g==="tscircuit.com"?(ve=m,Pe=C,ze=I,Xe=f):g==="jlcpcb"?(ve=B,Pe=S,ze=D,Xe=w):g==="kicad"&&(ve=H,Pe=G,ze=K,Xe=V);const st=async()=>{if(!_)return;await Se(_)&&(e(),Ye(),d(""))},ct=lt=>{lt||e()},ut=lt=>{fe(lt),lt||re(null)};return J.jsxs(DT,{open:t,onOpenChange:ct,children:[J.jsxs(j3,{style:{width:"calc(100vw - 2rem)",maxWidth:Ke?"min(1120px, calc(100vw - 2rem))":"min(672px, calc(100vw - 2rem))",zIndex:jRt.importComponentDialog},className:"rf-rounded-sm rf-max-h-[90vh] rf-overflow-y-auto rf-overflow-x-hidden rf-flex rf-flex-col",children:[J.jsxs(X3,{children:[J.jsxs($3,{className:"rf-text-lg sm:rf-text-xl",children:["Import ",l?Qie[g].label:""," ","Component"]}),J.jsx(MT,{className:"rf-text-sm",children:c?"Search for components from available sources.":"Import options are disabled because no handlers were provided."})]}),c?J.jsxs(K1e,{value:g,onValueChange:lt=>u(lt),className:"rf-min-w-0 rf-w-full",children:[!l&&J.jsx(FZ,{className:"rf-flex rf-w-full rf-gap-2",children:a.map(lt=>J.jsx(XQ,{value:lt,className:"rf-flex-1 rf-text-xs sm:rf-text-sm",children:Qie[lt].label},lt))}),J.jsxs("div",{className:"rf-min-w-0",style:Ke?{display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(360px, 0.95fr)",gap:"1.5rem",alignItems:"start"}:void 0,children:[J.jsxs("div",{className:"rf-min-w-0",children:[J.jsx(FOo,{query:h,placeholder:Qie[g].placeholder,isSearching:Pe,onQueryChange:d,onSubmit:Le}),J.jsx("div",{className:"no-scrollbar rf-mt-4 rf-flex-1 rf-min-h-[200px] !rf-max-h-[40vh] !rf-overflow-y-auto rf-overflow-x-hidden rf-border rf-rounded-md rf-min-w-0",children:Pe?J.jsxs("div",{className:"rf-p-8 rf-text-center rf-text-zinc-500",children:[J.jsx(SB,{className:"rf-h-8 rf-w-8 rf-animate-spin rf-mx-auto rf-mb-2"}),J.jsx("p",{children:"Searching..."})]}):ve.length>0?J.jsx(UOo,{results:ve,selected:_,onSelect:p,onShowDetails:g==="tscircuit.com"?qe:void 0}):J.jsx("div",{className:"rf-p-8 rf-text-center rf-text-zinc-500",children:ze?`Error: ${ze}`:Xe?Qie[g].emptyMessage:"Enter a search term to find components"})})]}),Ke?J.jsx("div",{className:"rf-mt-4",children:J.jsx(YOo,{circuitJson:nt,error:Ie,isLoading:Ze,height:325})}):null]})]}):null,ue?J.jsx("div",{className:"rf-text-sm rf-text-red-600 rf-mt-2",children:ue}):null,J.jsxs(eU,{className:"rf-flex rf-flex-col sm:rf-flex-row rf-gap-2",children:[J.jsx(ta,{variant:"outline",onClick:e,className:"rf-order-2 sm:rf-order-1",children:"Cancel"}),J.jsx(ta,{onClick:st,disabled:!_||pe,className:"rf-order-1 sm:rf-order-2",children:pe?J.jsx(SB,{className:"rf-h-4 rf-w-4 rf-animate-spin"}):"Import"})]})]}),J.jsx(zOo,{packageResult:ae,isOpen:le,onOpenChange:ut,isLoading:se,details:ie,previewTab:ye,onPreviewTabChange:lt=>be(lt),isSubmitting:pe,onImport:()=>{ae&&Se(ae).then(lt=>{lt&&(fe(!1),e(),Ye(),d(""))})}})]})},nKo=t=>{const e=t.match(/export const (\w+) =/);if(!e)throw new Error("Could not determine component name from TSX contents");return e[1]},$Rt=t=>{const e=Yu(A=>A.pushEvent),n=Yu(A=>A.upsertFile),o=async({result:A,fullPackageName:s})=>{const c=A.package.unscoped_name??A.package.name;await zA.promise(e({event_type:"INSTALL_PACKAGE",full_package_name:s}),{loading:`Requesting install for "${c}"`,success:`Install requested for "${c}"`,error:l=>`Failed to request install: ${l instanceof Error?l.message:String(l)}`})},i=async({footprint:A})=>{await zA.promise(navigator.clipboard.writeText(A),{loading:`Copying "${A}"`,success:`Copied "${A}" to clipboard`,error:s=>`Failed to copy footprint: ${s instanceof Error?s.message:String(s)}`})},r=async({result:A,tsx:s})=>{const c=`imports/${nKo(s)}.tsx`;await zA.promise(n(c,s),{loading:`Importing ${A.component.partNumber}`,success:`Imported to "${c}"`,error:l=>`Failed to import component: ${l instanceof Error?l.message:String(l)}`})};return J.jsx(tKo,{...t,onTscircuitPackageSelected:o,onKicadStringSelected:i,onJlcpcbComponentTsxLoaded:r})};$Rt.displayName="ImportComponentDialogForCli";var z3e={exports:{}},ZRt;function oKo(){return ZRt||(ZRt=1,(function(t,e){var n={env:{},version:""};(function(o){t.exports=o()})(function(){return(function o(i,r,A){function s(l,g){if(!r[l]){if(!i[l]){var u=typeof T4=="function"&&T4;if(!g&&u)return u(l,!0);if(a)return a(l,!0);var h=new Error("Cannot find module '"+l+"'");throw h.code="MODULE_NOT_FOUND",h}var d=r[l]={exports:{}};i[l][0].call(d.exports,function(_){var p=i[l][1][_];return s(p||_)},d,d.exports,o,i,r,A)}return r[l].exports}for(var a=typeof T4=="function"&&T4,c=0;c<A.length;c++)s(A[c]);return s})({1:[function(o,i,r){var A=o("./utils"),s=o("./support"),a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";r.encode=function(c){for(var l,g,u,h,d,_,p,m=[],C=0,I=c.length,f=I,y=A.getTypeOf(c)!=="string";C<c.length;)f=I-C,u=y?(l=c[C++],g=C<I?c[C++]:0,C<I?c[C++]:0):(l=c.charCodeAt(C++),g=C<I?c.charCodeAt(C++):0,C<I?c.charCodeAt(C++):0),h=l>>2,d=(3&l)<<4|g>>4,_=1<f?(15&g)<<2|u>>6:64,p=2<f?63&u:64,m.push(a.charAt(h)+a.charAt(d)+a.charAt(_)+a.charAt(p));return m.join("")},r.decode=function(c){var l,g,u,h,d,_,p=0,m=0,C="data:";if(c.substr(0,C.length)===C)throw new Error("Invalid base64 input, it looks like a data url.");var I,f=3*(c=c.replace(/[^A-Za-z0-9+/=]/g,"")).length/4;if(c.charAt(c.length-1)===a.charAt(64)&&f--,c.charAt(c.length-2)===a.charAt(64)&&f--,f%1!=0)throw new Error("Invalid base64 input, bad content length.");for(I=s.uint8array?new Uint8Array(0|f):new Array(0|f);p<c.length;)l=a.indexOf(c.charAt(p++))<<2|(h=a.indexOf(c.charAt(p++)))>>4,g=(15&h)<<4|(d=a.indexOf(c.charAt(p++)))>>2,u=(3&d)<<6|(_=a.indexOf(c.charAt(p++))),I[m++]=l,d!==64&&(I[m++]=g),_!==64&&(I[m++]=u);return I}},{"./support":30,"./utils":32}],2:[function(o,i,r){var A=o("./external"),s=o("./stream/DataWorker"),a=o("./stream/Crc32Probe"),c=o("./stream/DataLengthProbe");function l(g,u,h,d,_){this.compressedSize=g,this.uncompressedSize=u,this.crc32=h,this.compression=d,this.compressedContent=_}l.prototype={getContentWorker:function(){var g=new s(A.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new c("data_length")),u=this;return g.on("end",function(){if(this.streamInfo.data_length!==u.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),g},getCompressedWorker:function(){return new s(A.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},l.createWorkerFrom=function(g,u,h){return g.pipe(new a).pipe(new c("uncompressedSize")).pipe(u.compressWorker(h)).pipe(new c("compressedSize")).withStreamInfo("compression",u)},i.exports=l},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(o,i,r){var A=o("./stream/GenericWorker");r.STORE={magic:"\0\0",compressWorker:function(){return new A("STORE compression")},uncompressWorker:function(){return new A("STORE decompression")}},r.DEFLATE=o("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(o,i,r){var A=o("./utils"),s=(function(){for(var a,c=[],l=0;l<256;l++){a=l;for(var g=0;g<8;g++)a=1&a?3988292384^a>>>1:a>>>1;c[l]=a}return c})();i.exports=function(a,c){return a!==void 0&&a.length?A.getTypeOf(a)!=="string"?(function(l,g,u,h){var d=s,_=h+u;l^=-1;for(var p=h;p<_;p++)l=l>>>8^d[255&(l^g[p])];return-1^l})(0|c,a,a.length,0):(function(l,g,u,h){var d=s,_=h+u;l^=-1;for(var p=h;p<_;p++)l=l>>>8^d[255&(l^g.charCodeAt(p))];return-1^l})(0|c,a,a.length,0):0}},{"./utils":32}],5:[function(o,i,r){r.base64=!1,r.binary=!1,r.dir=!1,r.createFolders=!0,r.date=null,r.compression=null,r.compressionOptions=null,r.comment=null,r.unixPermissions=null,r.dosPermissions=null},{}],6:[function(o,i,r){var A=null;A=typeof Promise<"u"?Promise:o("lie"),i.exports={Promise:A}},{lie:37}],7:[function(o,i,r){var A=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",s=o("pako"),a=o("./utils"),c=o("./stream/GenericWorker"),l=A?"uint8array":"array";function g(u,h){c.call(this,"FlateWorker/"+u),this._pako=null,this._pakoAction=u,this._pakoOptions=h,this.meta={}}r.magic="\b\0",a.inherits(g,c),g.prototype.processChunk=function(u){this.meta=u.meta,this._pako===null&&this._createPako(),this._pako.push(a.transformTo(l,u.data),!1)},g.prototype.flush=function(){c.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},g.prototype.cleanUp=function(){c.prototype.cleanUp.call(this),this._pako=null},g.prototype._createPako=function(){this._pako=new s[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var u=this;this._pako.onData=function(h){u.push({data:h,meta:u.meta})}},r.compressWorker=function(u){return new g("Deflate",u)},r.uncompressWorker=function(){return new g("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(o,i,r){function A(d,_){var p,m="";for(p=0;p<_;p++)m+=String.fromCharCode(255&d),d>>>=8;return m}function s(d,_,p,m,C,I){var f,y,x=d.file,B=d.compression,S=I!==l.utf8encode,D=a.transformTo("string",I(x.name)),w=a.transformTo("string",l.utf8encode(x.name)),F=x.comment,R=a.transformTo("string",I(F)),H=a.transformTo("string",l.utf8encode(F)),G=w.length!==x.name.length,K=H.length!==F.length,V="",W="",X="",ie=x.dir,se=x.date,ee={crc32:0,compressedSize:0,uncompressedSize:0};_&&!p||(ee.crc32=d.crc32,ee.compressedSize=d.compressedSize,ee.uncompressedSize=d.uncompressedSize);var oe=0;_&&(oe|=8),S||!G&&!K||(oe|=2048);var ae=0,re=0;ie&&(ae|=16),C==="UNIX"?(re=798,ae|=(function(fe,ye){var be=fe;return fe||(be=ye?16893:33204),(65535&be)<<16})(x.unixPermissions,ie)):(re=20,ae|=(function(fe){return 63&(fe||0)})(x.dosPermissions)),f=se.getUTCHours(),f<<=6,f|=se.getUTCMinutes(),f<<=5,f|=se.getUTCSeconds()/2,y=se.getUTCFullYear()-1980,y<<=4,y|=se.getUTCMonth()+1,y<<=5,y|=se.getUTCDate(),G&&(W=A(1,1)+A(g(D),4)+w,V+="up"+A(W.length,2)+W),K&&(X=A(1,1)+A(g(R),4)+H,V+="uc"+A(X.length,2)+X);var le="";return le+=`
5793
+ `,g=new Blob([l],{type:"text/plain"}),u=URL.createObjectURL(g),h=document.createElement("a");h.href=u,h.download=`${c}.test.ts`,h.click(),URL.revokeObjectURL(u)}catch(a){alert(`Error generating test.ts for ${t.constructor.name}: ${a instanceof Error?a.message:String(a)}`)}o(!1)};return J.jsxs("div",{className:`relative ${e}`,ref:i,children:[J.jsx("button",{className:"px-2 py-1 rounded text-xs cursor-pointer",onClick:()=>o(!n),title:`Download options for ${t.constructor.name}`,children:t.constructor.name}),n&&J.jsxs("div",{className:"absolute top-full left-0 mt-1 bg-white border border-gray-300 rounded shadow-lg z-10 min-w-[150px]",children:[J.jsx("button",{className:"w-full text-left px-3 py-2 hover:bg-gray-100 text-xs",onClick:r,children:"Download JSON"}),J.jsx("button",{className:"w-full text-left px-3 py-2 hover:bg-gray-100 text-xs",onClick:A,children:"Download page.tsx"}),J.jsx("button",{className:"w-full text-left px-3 py-2 hover:bg-gray-100 text-xs",onClick:s,children:"Download test.ts"})]})]})},rRt=t=>t.activeSubSolver?[t,...rRt(t.activeSubSolver)]:[t],bHo=({solver:t})=>{const e=rRt(t);return J.jsx("div",{className:"flex gap-1 items-center text-sm pt-1",children:e.map((n,o)=>J.jsxs("div",{className:"flex items-center",children:[o>0&&J.jsx("span",{className:"text-gray-400 mx-1",children:"→"}),J.jsx(SHo,{solver:n})]},n.constructor.name))})},DHo=({solver:t,triggerRender:e,animationSpeed:n=25,onSolverStarted:o,onSolverCompleted:i})=>{const[r,A]=j.useReducer(_=>!_,!1),s=j.useRef(void 0),a=()=>{!t.solved&&!t.failed&&(t.step(),e())},c=()=>{!t.solved&&!t.failed&&(o&&o(t),t.solve(),e(),i&&i(t))},l=()=>{r?(s.current&&(clearInterval(s.current),s.current=void 0),A()):(A(),s.current=setInterval(()=>{if(t.solved||t.failed){s.current&&(clearInterval(s.current),s.current=void 0),A(),e(),i&&t.solved&&i(t);return}t.step(),e()},n))},g=()=>{const _=t;if(_.getCurrentPhase&&!t.solved&&!t.failed){const p=_.getCurrentPhase();for(;_.getCurrentPhase()===p&&!t.solved&&!t.failed;)t.step();e()}},u=()=>{if(t.solved||t.failed||r)return;const _=window.prompt("Step until which iteration?",`${t.iterations}`);if(_===null)return;const p=Number(_);if(!Number.isFinite(p)){window.alert("Please enter a valid number for the iteration");return}for(;t.iterations<p&&!t.solved&&!t.failed;)t.step();e(),t.solved&&i&&i(t)};j.useEffect(()=>()=>{s.current&&clearInterval(s.current)},[]),j.useEffect(()=>{(t.solved||t.failed)&&r&&(s.current&&(clearInterval(s.current),s.current=void 0),A())},[t.solved,t.failed,r]);const h=t.getCurrentPhase!==void 0,d=h?t.getCurrentPhase():null;return J.jsxs("div",{className:"space-y-2 p-2 border-b",children:[J.jsx("div",{className:"flex items-center",children:J.jsx(bHo,{solver:t})}),J.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[J.jsx("button",{onClick:a,disabled:t.solved||t.failed||r,className:"bg-blue-500 hover:bg-blue-600 disabled:bg-gray-300 text-white px-3 py-1 rounded text-sm",children:"Step"}),J.jsx("button",{onClick:c,disabled:t.solved||t.failed||r,className:"bg-green-500 hover:bg-green-600 disabled:bg-gray-300 text-white px-3 py-1 rounded text-sm",children:"Solve"}),J.jsx("button",{onClick:l,disabled:t.solved||t.failed,className:`px-3 py-1 rounded text-white text-sm ${r?"bg-red-500 hover:bg-red-600":"bg-yellow-500 hover:bg-yellow-600"} disabled:bg-gray-300`,children:r?"Stop":"Animate"}),J.jsx("button",{onClick:u,disabled:t.solved||t.failed||r,className:"bg-orange-500 hover:bg-orange-600 disabled:bg-gray-300 text-white px-3 py-1 rounded text-sm",children:"Step Until Iteration"}),h&&J.jsx("button",{onClick:g,disabled:t.solved||t.failed||r,className:"bg-purple-500 hover:bg-purple-600 disabled:bg-gray-300 text-white px-3 py-1 rounded text-sm",children:"Next Stage"}),J.jsxs("div",{className:"text-sm text-gray-600",children:["Iterations: ",t.iterations]}),t.timeToSolve!==void 0&&J.jsxs("div",{className:"text-sm text-gray-600",children:["Time: ",(t.timeToSolve/1e3).toFixed(3),"s"]}),d&&J.jsxs("div",{className:"text-sm text-gray-600",children:["Phase: ",J.jsx("span",{className:"font-medium",children:d})]}),t.solved&&J.jsx("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded text-sm",children:"Solved"}),t.failed&&J.jsx("div",{className:"px-2 py-1 bg-red-100 text-red-800 rounded text-sm",children:"Failed"})]}),t.error&&J.jsxs("div",{className:"text-red-600 text-sm",children:["Error: ",t.error]})]})},MHo=(t,e,n)=>{const o=t.currentPipelineStepIndex;return e<o?"Completed":e===o&&t.activeSubSolver?t.activeSubSolver.failed?"Failed":"In Progress":"Not Started"},wHo=(t,e)=>{const o=t.pipelineDef[e].solverName,i=MHo(t,e),r=t[o],A=t.firstIterationOfPhase?.[o]??null,s=t.iterations;let a=0;if(i==="Completed"){const u=t.pipelineDef[e+1],h=u?t.firstIterationOfPhase?.[u.solverName]:void 0;h!==void 0&&A!==null?a=h-A:A!==null&&(a=s-A)}else i==="In Progress"&&A!==null&&(a=s-A);const c=t.timeSpentOnPhase?.[o]??0;let l=0;i==="Completed"?l=1:i==="In Progress"&&r&&(l=r.progress??0);const g=r?.stats??null;return{index:e,name:o,status:i,firstIteration:A,iterations:a,progress:l,timeSpent:c,stats:g&&Object.keys(g).length>0?g:null,solverInstance:r??null}},PHo=({status:t})=>{const e={"Not Started":"text-blue-600","In Progress":"text-yellow-600",Completed:"text-green-600",Failed:"text-red-600"};return J.jsx("span",{className:`font-medium ${e[t]}`,children:t})},vHo=({progress:t})=>{if(t===0)return null;const e=Math.round(t*100);return J.jsxs("div",{className:"flex items-center gap-2",children:[J.jsx("div",{className:"w-20 h-2 bg-gray-200 rounded overflow-hidden",children:J.jsx("div",{className:"h-full bg-blue-500 transition-all duration-200",style:{width:`${e}%`}})}),J.jsxs("span",{className:"text-xs text-gray-500",children:[e,"%"]})]})},NHo=t=>Object.entries(t).map(([e,n])=>`${e}: ${n}`).join(", "),RHo=({stats:t})=>{if(!t||Object.keys(t).length===0)return J.jsx("span",{children:"-"});const e=Object.entries(t),n=NHo(t);return J.jsxs("details",{className:"cursor-pointer",children:[J.jsx("summary",{className:"whitespace-nowrap overflow-hidden text-ellipsis max-w-[200px]",children:n}),J.jsx("div",{className:"mt-1 text-xs",children:e.map(([o,i])=>J.jsxs("div",{children:[o,": ",String(i)]},o))})]})},u3e=t=>{if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(u3e);const e={};for(const[n,o]of Object.entries(t))n.startsWith("_")||(e[n]=u3e(o));return e},THo=(t,e)=>{try{if(typeof t.getConstructorParams!="function"){alert(`getConstructorParams() is not implemented for ${e}`);return}const n=u3e(t.getConstructorParams()),o=new Blob([JSON.stringify(n,null,2)],{type:"application/json"}),i=URL.createObjectURL(o),r=document.createElement("a");r.href=i,r.download=`${e}_input.json`,r.click(),URL.revokeObjectURL(i)}catch(n){alert(`Error downloading input for ${e}: ${n instanceof Error?n.message:String(n)}`)}},kHo=({solver:t,onStepUntilPhase:e,onDownloadInput:n})=>{const o=t.pipelineDef.map((s,a)=>wHo(t,a)),i=s=>{e?.(s)},r=s=>{s.solverInstance&&(n?n(s.solverInstance,s.name):THo(s.solverInstance,s.name))},A=s=>`${(s/1e3).toFixed(2)}s`;return J.jsxs("div",{className:"border-t border-gray-200",children:[J.jsx("div",{className:"px-4 py-2 bg-gray-50 border-b border-gray-200",children:J.jsx("h3",{className:"text-sm font-semibold text-gray-700",children:"Pipeline Steps"})}),J.jsx("div",{className:"overflow-x-auto",children:J.jsxs("table",{className:"w-full text-sm",children:[J.jsx("thead",{children:J.jsxs("tr",{className:"bg-gray-50 border-b border-gray-200",children:[J.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Step"}),J.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Status"}),J.jsxs("th",{className:"px-4 py-2 text-center font-semibold text-gray-700",children:["i",J.jsx("sub",{children:"0"})]}),J.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Iterations"}),J.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Progress"}),J.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Time"}),J.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Stats"}),J.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Input"})]})}),J.jsx("tbody",{children:o.map(s=>J.jsxs("tr",{className:`border-b border-gray-100 ${s.status==="In Progress"?"bg-yellow-50":""}`,children:[J.jsx("td",{className:"px-4 py-2",children:J.jsxs("div",{className:"flex items-center gap-2",children:[J.jsx("span",{className:"text-gray-400 w-6",children:String(s.index+1).padStart(2,"0")}),J.jsx("button",{onClick:()=>i(s.name),disabled:s.status==="Completed"||t.solved||t.failed,className:"text-blue-500 hover:text-blue-700 disabled:text-gray-300 disabled:cursor-not-allowed",title:`Step until ${s.name} completes`,children:J.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",className:"w-4 h-4",children:J.jsx("path",{fillRule:"evenodd",d:"M4.5 5.653c0-1.426 1.529-2.33 2.779-1.643l11.54 6.348c1.295.712 1.295 2.573 0 3.285L7.28 19.991c-1.25.687-2.779-.217-2.779-1.643V5.653z",clipRule:"evenodd"})})}),J.jsx("span",{className:"font-medium text-gray-900",children:s.name})]})}),J.jsx("td",{className:"px-4 py-2",children:J.jsx(PHo,{status:s.status})}),J.jsx("td",{className:"px-4 py-2 text-center text-gray-600",children:s.firstIteration!==null?s.firstIteration:""}),J.jsx("td",{className:"px-4 py-2 text-gray-600",children:s.iterations}),J.jsx("td",{className:"px-4 py-2",children:J.jsx(vHo,{progress:s.progress})}),J.jsx("td",{className:"px-4 py-2 text-gray-600",children:A(s.timeSpent)}),J.jsx("td",{className:"px-4 py-2 text-gray-500",children:J.jsx(RHo,{stats:s.stats})}),J.jsx("td",{className:"px-4 py-2",children:s.solverInstance?J.jsxs("button",{onClick:()=>r(s),className:"flex items-center gap-1 text-blue-500 hover:text-blue-700",title:`Download input for ${s.name}`,children:[J.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",className:"w-4 h-4",children:J.jsx("path",{fillRule:"evenodd",d:"M12 2.25a.75.75 0 01.75.75v11.69l3.22-3.22a.75.75 0 111.06 1.06l-4.5 4.5a.75.75 0 01-1.06 0l-4.5-4.5a.75.75 0 111.06-1.06l3.22 3.22V3a.75.75 0 01.75-.75zm-9 13.5a.75.75 0 01.75.75v2.25a1.5 1.5 0 001.5 1.5h13.5a1.5 1.5 0 001.5-1.5V16.5a.75.75 0 011.5 0v2.25a3 3 0 01-3 3H5.25a3 3 0 01-3-3V16.5a.75.75 0 01.75-.75z",clipRule:"evenodd"})}),J.jsx("span",{children:"Input"})]}):null})]},s.name))})]})})]})},FHo=class extends $r.Component{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(t){console.error("InteractiveGraphics render error:",t)}render(){return this.state.hasError?this.props.fallback:this.props.children}};function LHo({graphics:t}){const e=t.points??[],n=t.lines??[],o=t.rects??[],i=t.circles??[],r=t.texts??[];let A=Number.POSITIVE_INFINITY,s=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY,c=Number.NEGATIVE_INFINITY;const l=(p,m)=>{typeof p=="number"&&(p<A&&(A=p),p>a&&(a=p)),typeof m=="number"&&(m<s&&(s=m),m>c&&(c=m))};for(const p of e)l(p.x,p.y);for(const p of n){const m=p.points??[];for(const C of m)l(C.x,C.y)}for(const p of o){const m=p.x??0,C=p.y??0,I=p.width??0,f=p.height??0;l(m,C),l(m+I,C+f)}for(const p of i){const m=p.x??0,C=p.y??0,I=p.radius??1;l(m-I,C-I),l(m+I,C+I)}for(const p of r)l(p.x,p.y);(!isFinite(A)||!isFinite(s)||!isFinite(a)||!isFinite(c))&&(A=-20,s=-20,a=20,c=20);const g=10,u=A-g,h=s-g,d=Math.max(1,a-A+2*g),_=Math.max(1,c-s+2*g);return J.jsxs("svg",{className:"w-full h-[400px] bg-white",viewBox:`${u} ${h} ${d} ${_}`,role:"img","aria-label":"Graphics fallback",children:[o.map((p,m)=>J.jsx("rect",{x:p.x??0,y:p.y??0,width:p.width??0,height:p.height??0,fill:"none",stroke:p.strokeColor??"black",strokeWidth:p.strokeWidth??1},`rect-${m}`)),n.map((p,m)=>J.jsx("polyline",{fill:"none",stroke:p.strokeColor??"black",strokeWidth:p.strokeWidth??1,points:(p.points??[]).map(C=>`${C.x??0},${C.y??0}`).join(" ")},`line-${m}`)),i.map((p,m)=>J.jsx("circle",{cx:p.x??0,cy:p.y??0,r:p.radius??1.5,fill:p.fillColor??"none",stroke:p.strokeColor??"black",strokeWidth:p.strokeWidth??1},`circle-${m}`)),e.map((p,m)=>J.jsx("circle",{cx:p.x??0,cy:p.y??0,r:p.radius??1.5,fill:p.color??"black"},`point-${m}`)),r.map((p,m)=>J.jsx("text",{x:p.x??0,y:p.y??0,fontSize:p.fontSize??10,fill:p.color??"black",children:p.text??""},`text-${m}`))]})}var HHo=({solver:t,animationSpeed:e=25,onSolverStarted:n,onSolverCompleted:o})=>{const[i,r]=j.useReducer(l=>l+1,0),A=j.useMemo(()=>{try{return t.visualize()||{points:[],lines:[],rects:[],circles:[]}}catch(l){return console.error("Visualization error:",l),{points:[],lines:[],rects:[],circles:[]}}},[t,i]),s=j.useMemo(()=>(A.rects?.length||0)===0&&(A.lines?.length||0)===0&&(A.points?.length||0)===0&&(A.circles?.length||0)===0,[A]);j.useEffect(()=>{if(!(typeof document>"u")&&!document.querySelector('script[src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"]')){const l=document.createElement("script");l.src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4",document.head.appendChild(l)}},[]);const a=t.pipelineDef!==void 0,c=l=>{const g=t;if(!t.solved&&!t.failed){for(;!t.solved&&!t.failed&&g.currentPipelineStepIndex<=g.pipelineDef.findIndex(u=>u.solverName===l);)t.step();r()}};return J.jsxs("div",{children:[J.jsx(DHo,{solver:t,triggerRender:r,animationSpeed:e,onSolverStarted:n,onSolverCompleted:o}),s?J.jsx("div",{className:"p-4 text-gray-500",children:"No Graphics Yet"}):J.jsx(FHo,{fallback:J.jsx(LHo,{graphics:A}),children:J.jsx(QHo,{graphics:A})}),a&&J.jsx(kHo,{solver:t,onStepUntilPhase:c})]})};const GHo=()=>{j.useEffect(()=>{const t="tailwind-cdn-script";if(document.getElementById(t)||window.tailwind)return;const e=document.createElement("div");e.className="hidden",document.body.appendChild(e);const n=window.getComputedStyle(e).display==="none";if(document.body.removeChild(e),n)return;const o=document.createElement("script");o.id=t,o.src="https://cdn.tailwindcss.com",document.head.appendChild(o)},[])},OHo=1e3,DS=(t,e)=>{const{fileName:n,mimeType:o="text/plain"}=e,i=t instanceof Blob?t:new Blob([t],{type:o}),r=URL.createObjectURL(i),A=document.createElement("a");A.href=r,A.download=n,A.target="_blank",A.rel="noopener noreferrer",A.style.display="none",document.body.appendChild(A),A.click(),document.body.removeChild(A),setTimeout(()=>{URL.revokeObjectURL(r)},OHo)},ARt=t=>{let e=t.trim().replace(/[\\/:*?"<>|]/g,"_").replace(/[\x00-\x1f]/g,"").replace(/^\.+/,"").replace(/\.+$/,"").replace(/\s+/g," ").replace(/_+/g,"_");return/^(con|prn|aux|nul|com[0-9]|lpt[0-9])$/i.test(e)&&(e=`_${e}`),e=e.slice(0,200),e||"untitled"},MS="https://github.com/tscircuit/tscircuit-autorouter/issues/new",sRt="https://github.com/tscircuit/copper-pour-solver/issues/new",aRt="https://github.com/tscircuit/calculate-packing/issues/new",cRt="https://github.com/tscircuit/schematic-trace-solver/issues/new?template=json-bug-report.yml",KHo={PackSolver2:aRt,AutoroutingPipelineSolver:MS,AssignableAutoroutingPipeline2:MS,AssignableAutoroutingPipeline3:MS,AutoroutingPipeline1_OriginalUnravel:MS,AutoroutingPipelineSolver3_HgPortPointPathing:MS,AutoroutingPipelineSolver4:MS,AutoroutingPipelineSolver5:MS,AutoroutingPipelineSolver7_MultiGraph:MS,AutoroutingPipelineSolver8:MS,CopperPourPipelineSolver:sRt,SchematicTracePipelineSolver:cRt},UHo=t=>t.toLowerCase().includes("pack")?PPo:t.toLowerCase().includes("rout")?FPo:IPo,lRt=t=>{const e=KHo[t];if(e)return e;const n=t.toLowerCase();return n.includes("autorout")?MS:n.includes("schematic")&&n.includes("trace")?cRt:n.includes("copperpour")?sRt:n.includes("pack")?aRt:null},YHo=t=>`${ARt(`${t.componentName}-${t.solverName}`)}-solver-input.json`,gRt=t=>{DS(JSON.stringify(t.solverParams,null,2),{fileName:YHo(t),mimeType:"application/json"})},zHo=({solverEvent:t})=>{const e=lRt(t.solverName);return J.jsxs("div",{className:"rf-flex rf-items-center rf-justify-end rf-gap-2 rf-border-b rf-border-gray-200 rf-bg-gray-50 rf-px-4 rf-py-2",children:[J.jsxs(ta,{type:"button",variant:"outline",size:"sm",onClick:()=>gRt(t),children:[J.jsx(qwe,{className:"rf-w-4 rf-h-4"}),"Download"]}),e?J.jsx(ta,{asChild:!0,variant:"outline",size:"sm",children:J.jsxs("a",{href:e,target:"_blank",rel:"noopener noreferrer",children:[J.jsx(eoe,{className:"rf-w-4 rf-h-4"}),"Report"]})}):J.jsxs(ta,{type:"button",variant:"outline",size:"sm",disabled:!0,title:"No report link configured for this solver",children:[J.jsx(eoe,{className:"rf-w-4 rf-h-4"}),"Report"]})]})},VHo=({solverEvent:t})=>{const e=lRt(t.solverName);return e?J.jsx(ta,{asChild:!0,variant:"ghost",size:"icon",className:"rf-h-8 rf-w-8",children:J.jsx("a",{href:e,target:"_blank",rel:"noopener noreferrer",title:"Report solver bug","aria-label":"Report solver bug",children:J.jsx(eoe,{className:"rf-w-4 rf-h-4"})})}):J.jsx(ta,{type:"button",variant:"ghost",size:"icon",className:"rf-h-8 rf-w-8",disabled:!0,title:"No report link configured for this solver","aria-label":"Report solver bug",children:J.jsx(eoe,{className:"rf-w-4 rf-h-4"})})},JHo=({solverEvents:t=[]})=>{const[e,n]=j.useState(null);GHo();const o=j.useMemo(()=>{const s=new Map;for(const a of t){const c=`${a.componentName}-${a.solverName}`;s.set(c,a)}return s},[t]),i=j.useMemo(()=>Array.from(o.keys()),[o]),r=e?o.get(e):null,A=j.useMemo(()=>{if(!r)return{instance:null,error:null,classFound:!1};const s=ACe[r.solverName];if(!s)return{instance:null,error:`Solver class "${r.solverName}" not found in SOLVERS registry. Available: ${Object.keys(ACe).join(", ")}`,classFound:!1};try{const a=r.solverParams,c=a?.input!==void 0?a.input:a;return{instance:new s(c),error:null,classFound:!0}}catch(a){const c=a instanceof Error?a.message:String(a);return console.error("Failed to reconstruct solver:",a),{instance:null,error:`Failed to instantiate solver: ${c}`,classFound:!0}}},[r]);return t.length===0?J.jsx("div",{className:"rf-p-4",children:J.jsx("div",{className:"rf-bg-gray-50 rf-rounded-md rf-border rf-border-gray-200",children:J.jsxs("div",{className:"rf-p-4",children:[J.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-gray-800 rf-mb-3",children:"No Solvers Detected"}),J.jsx("p",{className:"rf-text-sm rf-text-gray-600",children:"Solvers will appear here when the circuit runs. Solvers are used for tasks like component packing and autorouting."})]})})}):J.jsxs("div",{className:"rf-flex rf-h-full rf-overflow-hidden",children:[J.jsxs("div",{className:"rf-w-64 rf-border-r rf-border-gray-200 rf-overflow-y-auto rf-flex-shrink-0",children:[J.jsxs("div",{className:"rf-text-xs rf-font-semibold rf-text-gray-500 rf-px-3 rf-py-2 rf-bg-gray-50 rf-border-b rf-border-gray-200",children:[i.length," ",i.length===1?"Solver":"Solvers"]}),i.map(s=>{const a=o.get(s),c=e===s;return J.jsx("div",{className:`rf-px-3 rf-py-2 rf-cursor-pointer rf-border-b rf-border-gray-100 ${c?"rf-bg-blue-50 rf-border-l-2 rf-border-l-blue-500":"hover:rf-bg-gray-50"}`,onClick:()=>n(s),children:(()=>{const l=UHo(a.solverName);return J.jsxs("div",{className:"rf-flex rf-items-center rf-gap-2",children:[J.jsx(l,{className:"rf-w-4 rf-h-4 rf-text-blue-500 rf-flex-shrink-0"}),J.jsxs("div",{className:"rf-flex-1 rf-min-w-0",children:[J.jsx("div",{className:"rf-text-sm rf-font-medium rf-text-gray-800 rf-truncate",children:a.componentName}),J.jsx("div",{className:"rf-text-xs rf-text-gray-500 rf-truncate",children:a.solverName})]})]})})()},s)})]}),J.jsx("div",{className:"rf-flex-1 rf-overflow-hidden",children:r?A.instance?J.jsxs("div",{className:"rf-flex rf-h-full rf-flex-col rf-overflow-y-auto",children:[J.jsx(zHo,{solverEvent:r}),J.jsx("div",{className:"rf-min-h-0 rf-flex-1",children:J.jsx(gx,{fallback:J.jsx("div",{className:"rf-p-4",children:J.jsxs("div",{className:"rf-bg-red-50 rf-rounded-md rf-border rf-border-red-200 rf-p-4",children:[J.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-red-800 rf-mb-2",children:"Error Loading Solver Debugger"}),J.jsxs("p",{className:"rf-text-sm rf-text-red-600",children:["Failed to render the solver debugger for"," ",r.solverName]})]})}),children:J.jsx(HHo,{solver:A.instance})})})]}):J.jsxs("div",{className:"rf-p-4",children:[J.jsxs("div",{className:"rf-mb-4",children:[J.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-gray-800",children:r.solverName}),J.jsxs("p",{className:"rf-text-sm rf-text-gray-500",children:["Component: ",r.componentName]})]}),A.error&&J.jsx("div",{className:`rf-rounded-md rf-border rf-p-4 rf-mb-4 ${A.classFound?"rf-bg-red-50 rf-border-red-200":"rf-bg-yellow-50 rf-border-yellow-200"}`,children:J.jsx("p",{className:`rf-text-sm ${A.classFound?"rf-text-red-700":"rf-text-yellow-700"}`,children:A.error})}),J.jsxs("div",{className:"rf-border rf-border-gray-200 rf-rounded-md rf-overflow-hidden",children:[J.jsxs("div",{className:"rf-px-3 rf-py-2 rf-bg-gray-50 rf-flex rf-items-center rf-justify-between rf-gap-2",children:[J.jsx("span",{className:"rf-text-sm rf-font-medium rf-text-gray-700",children:"Solver Parameters"}),J.jsxs("div",{className:"rf-flex rf-items-center rf-gap-1",children:[J.jsx(VHo,{solverEvent:r}),J.jsx(ta,{type:"button",variant:"ghost",size:"icon",className:"rf-h-8 rf-w-8","aria-label":"Download solver input JSON",title:"Download solver input JSON",onClick:()=>gRt(r),children:J.jsx(qwe,{className:"rf-w-4 rf-h-4"})})]})]}),J.jsx("div",{className:"rf-p-3 rf-bg-white rf-border-t rf-border-gray-200",children:J.jsx("pre",{className:"rf-text-xs rf-font-mono rf-text-gray-600 rf-whitespace-pre-wrap rf-overflow-x-auto",children:JSON.stringify(r.solverParams,null,2)})})]})]}):J.jsx("div",{className:"rf-flex rf-items-center rf-justify-center rf-h-full",children:J.jsx("p",{className:"rf-text-sm rf-text-gray-500",children:"Select a solver from the list to view details"})})})]})},uRt=({errorMessage:t,errorStack:e,circuitJsonErrors:n})=>{j.useEffect(()=>{if(t){const o=new Error(t);e&&(o.stack=e);try{pN.captureException(o)}catch{}}},[t,e]),j.useEffect(()=>{if(n&&n.length>0)for(const o of n){const i=new Error(o.message||"Circuit JSON Error");o.stack&&(i.stack=o.stack);try{pN.captureException(i,{error_type:o.type})}catch{}}},[n])},dRt=t=>{j.useEffect(()=>{try{Tzn(t)}catch{}},[t.source,t.component,t.isWebEmbedded,t.activeTab])},hRt="0.0.2344",qHo={version:hRt},yie=Ggt()(Ogt(t=>({lastRunEvalVersion:void 0,setLastRunEvalVersion:e=>{t({lastRunEvalVersion:e})}}),{name:"runframe-runner-store"})),WHo=t=>{const[e,n]=j.useState([]),[o,i]=j.useState(null),[r,A]=j.useState(""),[s,a]=J7("eval-version-selection",null),c=yie(h=>h.setLastRunEvalVersion),l=yie(h=>h.lastRunEvalVersion);return j.useEffect(()=>{t&&fetch("https://data.jsdelivr.com/v1/package/npm/@tscircuit/eval").then(h=>h.json()).then(h=>{if(Array.isArray(h?.versions)){let d=[...h.versions];h.tags?.latest&&(i(h.tags.latest),d=d.filter(_=>_!==h.tags.latest)),n(d)}}).catch(()=>{})},[t]),j.useEffect(()=>{t&&(s?(window.TSCIRCUIT_LATEST_EVAL_VERSION=s,c(s)):o&&(window.TSCIRCUIT_LATEST_EVAL_VERSION=o,c(o)))},[t,s,o]),{versions:j.useMemo(()=>e.filter(h=>h.includes(r)).slice(0,50),[e,r]),latestVersion:o,lastRunEvalVersion:l,search:r,setSearch:A,selectVersion:h=>{a(h),A("")}}},jHo=({snippetNames:t,onSelect:e,onCancel:n,isOpen:o})=>{const[i,r]=j.useState(""),[A,s]=j.useState("");if(!o)return null;const a=t.filter(g=>g.toLowerCase().includes(A.toLowerCase())),c=A&&!t.includes(A),l=g=>{g.key==="Enter"&&(a.length===1?r(a[0]):c&&r(A))};return J.jsx("div",{className:"rf-fixed rf-inset-0 rf-bg-black rf-bg-opacity-50 rf-flex rf-items-center rf-justify-center rf-z-[100]",children:J.jsxs("div",{className:"rf-bg-white rf-rounded-lg rf-p-6 rf-w-96",children:[J.jsx("h2",{className:"rf-text-lg rf-font-semibold rf-mb-4",children:"Select Snippet"}),J.jsx("input",{type:"text",className:"rf-w-full rf-px-4 rf-py-2 rf-border rf-rounded rf-mb-4",placeholder:"Search snippets or new snippet name...",value:A,onChange:g=>s(g.target.value),onKeyDown:l}),J.jsxs("div",{className:"rf-h-60 rf-overflow-y-auto",children:[a.map(g=>J.jsx("button",{type:"button",className:`w-full text-left px-4 py-2 rounded hover:bg-gray-100 ${i===g?"bg-blue-50":""}`,onClick:()=>r(g),children:g},g)),c&&J.jsxs("button",{type:"button",className:`w-full text-left px-4 py-2 rounded hover:bg-gray-100 text-blue-500 ${i===A?"bg-blue-50":""}`,onClick:()=>r(A),children:['Create new "',A,'"']})]}),J.jsxs("div",{className:"rf-mt-4 rf-flex rf-justify-end rf-gap-2",children:[J.jsx("button",{type:"button",className:"rf-px-4 rf-py-2 rf-text-gray-600 rf-hover:text-gray-800",onClick:n,children:"Cancel"}),J.jsx("button",{type:"button",className:"rf-px-4 rf-py-2 rf-bg-blue-500 rf-text-white rf-rounded rf-hover:bg-blue-600 rf-disabled:opacity-50",onClick:()=>i&&e(i),disabled:!i,children:i===A?`Create "${i}"`:`Save to ${i}`})]})]})})},XHo=t=>{const e=j.useRef(null),n=Yu(o=>o.recentEvents);j.useEffect(()=>{if(n.length===0)return;const o=n[0];o.event_id!==e.current&&(t(o),e.current=o.event_id)},[n,t])};var $Ho=Object.defineProperty,G2=(t,e)=>$Ho(t,"name",{value:e,configurable:!0}),d3e="Dialog",[_Rt,mRt]=y2(d3e),[ZHo,PB]=_Rt(d3e),h3e=G2(t=>{const{__scopeDialog:e,children:n,open:o,defaultOpen:i,onOpenChange:r,modal:A=!0}=t,s=j.useRef(null),a=j.useRef(null),[c,l]=Ub({prop:o,defaultProp:i??!1,onChange:r,caller:d3e}),[g,u]=j.useState(0),[h,d]=j.useState(0);return J.jsx(ZHo,{scope:e,triggerRef:s,contentRef:a,contentId:rp(),titleId:rp(),descriptionId:rp(),titlePresent:g>0,descriptionPresent:h>0,setTitleCount:u,setDescriptionCount:d,open:c,onOpenChange:l,onOpenToggle:j.useCallback(()=>l(_=>!_),[l]),modal:A,children:n})},"Dialog"),eGo="DialogTrigger",tGo=j.forwardRef(G2(function(e,n){const{__scopeDialog:o,...i}=e,r=PB(eGo,o),A=dl(n,r.triggerRef);return J.jsx(Oa.button,{type:"button","aria-haspopup":"dialog","aria-expanded":r.open,"aria-controls":r.open?r.contentId:void 0,"data-state":Bie(r.open),...i,ref:A,onClick:Pr(e.onClick,r.onOpenToggle)})},"DialogTrigger")),pRt="DialogPortal",[nGo,IRt]=_Rt(pRt,{forceMount:void 0}),_3e=G2(t=>{const{__scopeDialog:e,forceMount:n,children:o,container:i}=t,r=PB(pRt,e);return J.jsx(nGo,{scope:e,forceMount:n,children:j.Children.map(o,A=>J.jsx(JE,{present:n||r.open,children:J.jsx(yPe,{asChild:!0,container:i,children:A})}))})},"DialogPortal"),m3e="DialogOverlay",Eie=j.forwardRef(G2(function(e,n){const o=IRt(m3e,e.__scopeDialog),{forceMount:i=o.forceMount,...r}=e,A=PB(m3e,e.__scopeDialog);return A.modal?J.jsx(JE,{present:i||A.open,children:J.jsx(iGo,{...r,ref:n})}):null},"DialogOverlay")),oGo=JQ("DialogOverlay.RemoveScroll"),iGo=j.forwardRef(G2(function(e,n){const{__scopeDialog:o,...i}=e,r=PB(m3e,o),A=GPt(),s=dl(n,A);return J.jsx(xoe,{as:oGo,allowPinchZoom:!0,shards:[r.contentRef],children:J.jsx(Oa.div,{"data-state":Bie(r.open),...i,ref:s,style:{pointerEvents:"auto",...i.style}})})},"DialogOverlayImpl")),$K="DialogContent",xie=j.forwardRef(G2(function(e,n){const o=IRt($K,e.__scopeDialog),{forceMount:i=o.forceMount,...r}=e,A=PB($K,e.__scopeDialog);return J.jsx(JE,{present:i||A.open,children:A.modal?J.jsx(rGo,{...r,ref:n}):J.jsx(AGo,{...r,ref:n})})},"DialogContent")),rGo=j.forwardRef(G2(function(e,n){const o=PB($K,e.__scopeDialog),i=j.useRef(null),r=dl(n,o.contentRef,i);return j.useEffect(()=>{const A=i.current;if(A)return xPe(A)},[]),J.jsx(CRt,{...e,ref:r,trapFocus:o.open,disableOutsidePointerEvents:o.open,onCloseAutoFocus:Pr(e.onCloseAutoFocus,A=>{A.preventDefault(),o.triggerRef.current?.focus()}),onPointerDownOutside:Pr(e.onPointerDownOutside,A=>{const s=A.detail.originalEvent,a=s.button===0&&s.ctrlKey===!0;(s.button===2||a)&&A.preventDefault()}),onFocusOutside:Pr(e.onFocusOutside,A=>A.preventDefault())})},"DialogContentModal")),AGo=j.forwardRef(G2(function(e,n){const o=PB($K,e.__scopeDialog),i=j.useRef(!1),r=j.useRef(!1);return J.jsx(CRt,{...e,ref:n,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:A=>{e.onCloseAutoFocus?.(A),A.defaultPrevented||(i.current||o.triggerRef.current?.focus(),A.preventDefault()),i.current=!1,r.current=!1},onInteractOutside:A=>{e.onInteractOutside?.(A),A.defaultPrevented||(i.current=!0,A.detail.originalEvent.type==="pointerdown"&&(r.current=!0));const s=A.target;o.triggerRef.current?.contains(s)&&A.preventDefault(),A.detail.originalEvent.type==="focusin"&&r.current&&A.preventDefault()}})},"DialogContentNonModal")),CRt=j.forwardRef(G2(function(e,n){const{__scopeDialog:o,trapFocus:i,onOpenAutoFocus:r,onCloseAutoFocus:A,...s}=e,a=PB($K,o);return QK(),J.jsx(J.Fragment,{children:J.jsx(oPe,{asChild:!0,loop:!0,trapped:i,onMountAutoFocus:r,onUnmountAutoFocus:A,children:J.jsx(toe,{role:"dialog",id:a.contentId,"aria-describedby":a.descriptionPresent?a.descriptionId:void 0,"aria-labelledby":a.titlePresent?a.titleId:void 0,"data-state":Bie(a.open),...s,ref:n,deferPointerDownOutside:!0,onDismiss:()=>a.onOpenChange(!1)})})})},"DialogContentImpl")),sGo="DialogTitle",p3e=j.forwardRef(G2(function(e,n){const{__scopeDialog:o,...i}=e,r=PB(sGo,o),{setTitleCount:A}=r;return ty(()=>(A(s=>s+1),()=>A(s=>s-1)),[A]),J.jsx(Oa.h2,{id:r.titleId,...i,ref:n})},"DialogTitle")),aGo="DialogDescription",I3e=j.forwardRef(G2(function(e,n){const{__scopeDialog:o,...i}=e,r=PB(aGo,o),{setDescriptionCount:A}=r;return ty(()=>(A(s=>s+1),()=>A(s=>s-1)),[A]),J.jsx(Oa.p,{id:r.descriptionId,...i,ref:n})},"DialogDescription")),cGo="DialogClose",fRt=j.forwardRef(G2(function(e,n){const{__scopeDialog:o,...i}=e,r=PB(cGo,o);return J.jsx(Oa.button,{type:"button",...i,ref:n,onClick:Pr(e.onClick,()=>r.onOpenChange(!1))})},"DialogClose"));function Bie(t){return t?"open":"closed"}G2(Bie,"getState");var lGo=Object.defineProperty,T5=(t,e)=>lGo(t,"name",{value:e,configurable:!0}),gGo="AlertDialog",[uGo,Rjo]=y2(gGo,[mRt]),k5=mRt(),dGo=T5(t=>{const{__scopeAlertDialog:e,...n}=t,o=k5(e);return J.jsx(h3e,{...o,...n,modal:!0})},"AlertDialog");j.forwardRef(T5(function(e,n){const{__scopeAlertDialog:o,...i}=e,r=k5(o);return J.jsx(tGo,{...r,...i,ref:n})},"AlertDialogTrigger"));var hGo=T5(t=>{const{__scopeAlertDialog:e,...n}=t,o=k5(e);return J.jsx(_3e,{...o,...n})},"AlertDialogPortal"),_Go=j.forwardRef(T5(function(e,n){const{__scopeAlertDialog:o,...i}=e,r=k5(o);return J.jsx(Eie,{...r,...i,ref:n})},"AlertDialogOverlay")),mGo="AlertDialogContent",[pGo,IGo]=uGo(mGo),CGo=j.forwardRef(T5(function(e,n){const{__scopeAlertDialog:o,children:i,...r}=e,A=k5(o),s=j.useRef(null),a=dl(n,s),c=j.useRef(null);return J.jsx(pGo,{scope:o,cancelRef:c,children:J.jsx(xie,{role:"alertdialog",...A,...r,ref:a,onOpenAutoFocus:Pr(r.onOpenAutoFocus,l=>{l.preventDefault(),c.current?.focus({preventScroll:!0})}),onPointerDownOutside:l=>l.preventDefault(),onInteractOutside:l=>l.preventDefault(),children:i})})},"AlertDialogContent")),fGo=j.forwardRef(T5(function(e,n){const{__scopeAlertDialog:o,...i}=e,r=k5(o);return J.jsx(p3e,{...r,...i,ref:n})},"AlertDialogTitle")),yGo=j.forwardRef(T5(function(e,n){const{__scopeAlertDialog:o,...i}=e,r=k5(o);return J.jsx(I3e,{...r,...i,ref:n})},"AlertDialogDescription")),EGo=j.forwardRef(T5(function(e,n){const{__scopeAlertDialog:o,...i}=e,r=k5(o);return J.jsx(fRt,{...r,...i,ref:n})},"AlertDialogAction")),xGo="AlertDialogCancel",BGo=j.forwardRef(T5(function(e,n){const{__scopeAlertDialog:o,...i}=e,{cancelRef:r}=IGo(xGo,o),A=k5(o),s=dl(n,r);return J.jsx(fRt,{...A,...i,ref:s})},"AlertDialogCancel")),QGo=dGo,SGo=hGo,yRt=_Go,ERt=CGo,xRt=EGo,BRt=BGo,QRt=fGo,SRt=yGo;const bRt=QGo,bGo=SGo,DRt=j.forwardRef(({className:t,...e},n)=>J.jsx(yRt,{className:qi("rf-fixed rf-inset-0 rf-z-50 rf-bg-black/80 data-[state=open]:rf-animate-in data-[state=closed]:rf-animate-out data-[state=closed]:rf-fade-out-0 data-[state=open]:rf-fade-in-0",t),...e,ref:n}));DRt.displayName=yRt.displayName;const C3e=j.forwardRef(({className:t,...e},n)=>J.jsxs(bGo,{children:[J.jsx(DRt,{}),J.jsx(ERt,{ref:n,className:qi("rf-fixed rf-left-[50%] rf-top-[50%] rf-z-50 rf-grid rf-w-full rf-max-w-lg rf-translate-x-[-50%] rf-translate-y-[-50%] rf-gap-4 rf-border rf-border-zinc-200 rf-bg-white rf-p-6 rf-shadow-lg rf-duration-200 data-[state=open]:rf-animate-in data-[state=closed]:rf-animate-out data-[state=closed]:rf-fade-out-0 data-[state=open]:rf-fade-in-0 data-[state=closed]:rf-zoom-out-95 data-[state=open]:rf-zoom-in-95 data-[state=closed]:rf-slide-out-to-left-1/2 data-[state=closed]:rf-slide-out-to-top-[48%] data-[state=open]:rf-slide-in-from-left-1/2 data-[state=open]:rf-slide-in-from-top-[48%] sm:rf-rounded-lg dark:rf-border-zinc-800 dark:rf-bg-zinc-950",t),...e})]}));C3e.displayName=ERt.displayName;const f3e=({className:t,...e})=>J.jsx("div",{className:qi("rf-flex rf-flex-col rf-space-y-2 rf-text-center sm:rf-text-left",t),...e});f3e.displayName="AlertDialogHeader";const y3e=({className:t,...e})=>J.jsx("div",{className:qi("rf-flex rf-flex-col-reverse sm:rf-flex-row sm:rf-justify-end sm:rf-space-x-2",t),...e});y3e.displayName="AlertDialogFooter";const E3e=j.forwardRef(({className:t,...e},n)=>J.jsx(QRt,{ref:n,className:qi("rf-text-lg rf-font-semibold",t),...e}));E3e.displayName=QRt.displayName;const x3e=j.forwardRef(({className:t,...e},n)=>J.jsx(SRt,{ref:n,className:qi("rf-text-sm rf-text-zinc-500 dark:rf-text-zinc-400",t),...e}));x3e.displayName=SRt.displayName;const DGo=j.forwardRef(({className:t,...e},n)=>J.jsx(xRt,{ref:n,className:qi(oT(),t),...e}));DGo.displayName=xRt.displayName;const B3e=j.forwardRef(({className:t,...e},n)=>J.jsx(BRt,{ref:n,className:qi(oT({variant:"outline"}),"rf-mt-2 sm:rf-mt-0",t),...e}));B3e.displayName=BRt.displayName;var MGo=Object.defineProperty,F5=(t,e)=>MGo(t,"name",{value:e,configurable:!0}),Q3e="Checkbox",[wGo,Tjo]=y2(Q3e),[PGo,S3e]=wGo(Q3e);function MRt(t){const{__scopeCheckbox:e,checked:n,children:o,defaultChecked:i,disabled:r,form:A,name:s,onCheckedChange:a,required:c,value:l="on",internal_do_not_use_render:g}=t,[u,h]=Ub({prop:n,defaultProp:i??!1,onChange:a,caller:Q3e}),[d,_]=j.useState(null),[p,m]=j.useState(null),C=j.useRef(!1),[I,f]=j.useReducer(B=>B+1,0),y=d?!!A||!!d.closest("form"):!0,x={checked:u,disabled:r,setChecked:h,control:d,setControl:_,name:s,form:A,value:l,hasConsumerStoppedPropagationRef:C,userInteractionCount:I,onUserInteraction:f,required:c,defaultChecked:L5(i)?!1:i,isFormControl:y,bubbleInput:p,setBubbleInput:m};return J.jsx(PGo,{scope:e,...x,children:PRt(g)?g(x):o})}F5(MRt,"CheckboxProvider");var vGo="CheckboxTrigger",NGo=j.forwardRef(F5(function({__scopeCheckbox:e,onKeyDown:n,onClick:o,...i},r){const{control:A,value:s,disabled:a,checked:c,required:l,setControl:g,setChecked:u,hasConsumerStoppedPropagationRef:h,onUserInteraction:d,isFormControl:_,bubbleInput:p}=S3e(vGo,e),m=dl(r,g),C=j.useRef(c);return j.useEffect(()=>{const I=A?.form;if(I){const f=F5(()=>u(C.current),"reset");return I.addEventListener("reset",f),()=>I.removeEventListener("reset",f)}},[A,u]),J.jsx(Oa.button,{type:"button",role:"checkbox","aria-checked":L5(c)?"mixed":c,"aria-required":l,"data-state":b3e(c),"data-disabled":a?"":void 0,disabled:a,value:s,...i,ref:m,onKeyDown:Pr(n,I=>{I.key==="Enter"&&I.preventDefault()}),onClick:Pr(o,I=>{d(),u(f=>L5(f)?!0:!f),p&&_&&(h.current=I.isPropagationStopped(),h.current||I.stopPropagation())})})},"CheckboxTrigger")),wRt=j.forwardRef(F5(function(e,n){const{__scopeCheckbox:o,name:i,checked:r,defaultChecked:A,required:s,disabled:a,value:c,onCheckedChange:l,form:g,...u}=e;return J.jsx(MRt,{__scopeCheckbox:o,checked:r,defaultChecked:A,disabled:a,required:s,onCheckedChange:l,name:i,form:g,value:c,internal_do_not_use_render:({isFormControl:h})=>J.jsxs(J.Fragment,{children:[J.jsx(NGo,{...u,ref:n,__scopeCheckbox:o}),h&&J.jsx(FGo,{__scopeCheckbox:o})]})})},"Checkbox")),RGo="CheckboxIndicator",TGo=j.forwardRef(F5(function(e,n){const{__scopeCheckbox:o,forceMount:i,...r}=e,A=S3e(RGo,o);return J.jsx(JE,{present:i||L5(A.checked)||A.checked===!0,children:J.jsx(Oa.span,{"data-state":b3e(A.checked),"data-disabled":A.disabled?"":void 0,...r,ref:n,style:{pointerEvents:"none",...e.style}})})},"CheckboxIndicator")),kGo="CheckboxBubbleInput",FGo=j.forwardRef(F5(function({__scopeCheckbox:e,onClick:n,...o},i){const{control:r,hasConsumerStoppedPropagationRef:A,userInteractionCount:s,checked:a,defaultChecked:c,required:l,disabled:g,name:u,value:h,form:d,bubbleInput:_,setBubbleInput:p}=S3e(kGo,e),m=dl(i,p),C=IPe(r),I=j.useRef(!1),f=j.useRef(a),y=j.useRef(s);j.useEffect(()=>{const B=_;if(!B)return;const S=window.HTMLInputElement.prototype,w=Object.getOwnPropertyDescriptor(S,"checked").set,F=s!==y.current;y.current=s;const R=f.current!==a;f.current=a;const H=!(F&&A.current);if(R&&w){I.current=!F;const G=new Event("click",{bubbles:H});B.indeterminate=L5(a),w.call(B,L5(a)?!1:a),B.dispatchEvent(G),I.current=!1}},[_,a,A,s]);const x=j.useRef(L5(a)?!1:a);return J.jsx(Oa.input,{type:"checkbox","aria-hidden":!0,defaultChecked:c??x.current,required:l,disabled:g,name:u,value:h,form:d,...o,tabIndex:-1,ref:m,onClick:Pr(n,B=>{I.current&&B.stopPropagation()}),style:{...o.style,...C,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})},"CheckboxBubbleInput"));function PRt(t){return typeof t=="function"}F5(PRt,"isFunction");function L5(t){return t==="indeterminate"}F5(L5,"isIndeterminate");function b3e(t){return L5(t)?"indeterminate":t?"checked":"unchecked"}F5(b3e,"getState");const ZK=j.forwardRef(({className:t,...e},n)=>J.jsx(wRt,{ref:n,className:qi("rf-peer rf-h-4 rf-w-4 rf-shrink-0 rf-rounded-sm rf-border rf-border-zinc-200 rf-border-zinc-900 rf-shadow focus-visible:rf-outline-none focus-visible:rf-ring-1 focus-visible:rf-ring-zinc-950 disabled:rf-cursor-not-allowed disabled:rf-opacity-50 data-[state=checked]:rf-bg-zinc-900 data-[state=checked]:rf-text-zinc-50 dark:rf-border-zinc-800 dark:rf-border-zinc-50 dark:focus-visible:rf-ring-zinc-300 dark:data-[state=checked]:rf-bg-zinc-50 dark:data-[state=checked]:rf-text-zinc-900",t),...e,children:J.jsx(TGo,{className:qi("rf-flex rf-items-center rf-justify-center rf-text-current"),children:J.jsx(L3,{className:"rf-h-4 rf-w-4"})})}));ZK.displayName=wRt.displayName;const DT=h3e,LGo=_3e,vRt=j.forwardRef(({className:t,...e},n)=>J.jsx(Eie,{className:qi("rf-fixed rf-inset-0 rf-z-50 rf-bg-black/80 data-[state=open]:rf-animate-in data-[state=closed]:rf-animate-out data-[state=closed]:rf-fade-out-0 data-[state=open]:rf-fade-in-0",t),...e,ref:n}));vRt.displayName=Eie.displayName;const j3=j.forwardRef(({className:t,children:e,showOverlay:n=!0,...o},i)=>J.jsxs(LGo,{children:[J.jsx(vRt,{className:qi(n?"":"rf-hidden")}),J.jsx(xie,{ref:i,className:qi("rf-fixed rf-left-[50%] rf-top-[50%] rf-z-50 rf-grid rf-w-full rf-max-w-lg rf-translate-x-[-50%] rf-translate-y-[-50%] rf-gap-4 rf-border rf-border-zinc-200 rf-bg-white rf-p-6 rf-shadow-lg rf-duration-200 data-[state=open]:rf-animate-in data-[state=closed]:rf-animate-out data-[state=closed]:rf-fade-out-0 data-[state=open]:rf-fade-in-0 data-[state=closed]:rf-zoom-out-95 data-[state=open]:rf-zoom-in-95 data-[state=closed]:rf-slide-out-to-left-1/2 data-[state=closed]:rf-slide-out-to-top-[48%] data-[state=open]:rf-slide-in-from-left-1/2 data-[state=open]:rf-slide-in-from-top-[48%] sm:rf-rounded-lg dark:rf-border-zinc-800 dark:rf-bg-zinc-950",t),...o,children:e})]}));j3.displayName=xie.displayName;const X3=({className:t,...e})=>J.jsx("div",{className:qi("rf-flex rf-flex-col rf-space-y-2 rf-text-center sm:rf-text-left",t),...e});X3.displayName="DialogHeader";const eU=({className:t,...e})=>J.jsx("div",{className:qi("rf-flex rf-flex-col-reverse sm:rf-flex-row sm:rf-justify-end sm:rf-space-x-2",t),...e});eU.displayName="DialogFooter";const $3=j.forwardRef(({className:t,...e},n)=>J.jsx(p3e,{ref:n,className:qi("rf-text-lg rf-font-semibold",t),...e}));$3.displayName=p3e.displayName;const MT=j.forwardRef(({className:t,...e},n)=>J.jsx(I3e,{ref:n,className:qi("rf-text-sm rf-text-zinc-500 dark:rf-text-zinc-400",t),...e}));MT.displayName=I3e.displayName;const Qie={"tscircuit.com":{label:"tscircuit.com",placeholder:"Search tscircuit packages...",emptyMessage:"No packages found"},jlcpcb:{label:"JLCPCB Parts",placeholder:"Search JLCPCB parts (e.g. C14663)...",emptyMessage:"No parts found"},kicad:{label:"KiCad Footprints",placeholder:"Search KiCad footprints...",emptyMessage:"No footprints found"}},HGo="https://cdn.jsdelivr.net/npm/easyeda@latest/dist/browser/index.js";let D3e=null;const M3e=async()=>(D3e||(D3e=import(HGo)),D3e),GGo=t=>(e,n)=>{const o=new Headers(n?.headers),i={};return o.forEach((r,A)=>{i[A]=r}),fetch(`${t?.apiBase??Qf}/proxy`,{...n,headers:{...i,"X-Target-Url":e.toString(),"X-Sender-Origin":i.origin??"","X-Sender-Host":i.host??"https://easyeda.com","X-Sender-Referer":i.referer??"","X-Sender-User-Agent":i["user-agent"]??"","X-Sender-Cookie":i.cookie??"",authority:i.authority??"","content-type":i["content-type"]??"",...t?.headers}})},OGo=async(t,e=10)=>{const n=encodeURIComponent(t),o=await fetch(`https://jlcsearch.tscircuit.com/api/search?limit=${e}&q=${n}`);if(!o.ok)throw new Error(`JLCPCB API error: ${o.status}`);return(await o.json()).components??[]},KGo=t=>({lcscId:t.lcsc,manufacturer:t.mfr,description:t.description,partNumber:`C${t.lcsc}`,package:t.package,price:t.price,stock:t.stock,isBasic:t.is_basic}),NRt=async(t,e)=>{const{fetchEasyEDAComponent:n}=await M3e();return n(t,{fetch:GGo(e),includeModelMetadata:e?.includeModelMetadata})},UGo=async(t,e)=>{const{convertRawEasyToTsx:n}=await M3e(),o=await NRt(t,e);return n({rawEasy:o})},YGo=async(t,e)=>{const{EasyEdaJsonSchema:n,convertEasyEdaJsonToCircuitJson:o}=await M3e(),i=await NRt(t,{...e,includeModelMetadata:!1}),r=n.parse(i);return o(r,{shouldRecenter:!0,showDesignator:!0,useModelCdn:!1})};function uw(t){return Array.isArray?Array.isArray(t):TRt(t)==="[object Array]"}function zGo(t){if(typeof t=="string")return t;if(typeof t=="bigint")return t.toString();const e=t+"";return e=="0"&&1/t==-1/0?"-0":e}function w3e(t){return t==null?"":zGo(t)}function bC(t){return typeof t=="string"}function Sie(t){return typeof t=="number"}function VGo(t){return t===!0||t===!1||JGo(t)&&TRt(t)=="[object Boolean]"}function RRt(t){return typeof t=="object"}function JGo(t){return RRt(t)&&t!==null}function O2(t){return t!=null}function bie(t){return!t.trim().length}function TRt(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const qGo="Incorrect 'index' type",P3e="Invalid doc index: must be a non-negative integer within the bounds of the docs array",WGo=t=>`Invalid value for key ${t}`,jGo=t=>`Pattern length exceeds max of ${t}.`,XGo=t=>`Missing ${t} property in key`,$Go=t=>`Property 'weight' in key '${t}' must be a positive integer`,ZGo="Fuse.match does not support useTokenSearch: token search requires corpus-level statistics (df, fieldCount) that a one-off string comparison does not have. Use new Fuse(...).search(...) instead.",kRt=Object.prototype.hasOwnProperty;var eOo=class{constructor(t){this._keys=[],this._keyMap={};let e=0;t.forEach(n=>{const o=FRt(n);this._keys.push(o),this._keyMap[o.id]=o,e+=o.weight}),this._keys.forEach(n=>{n.weight/=e})}get(t){return this._keyMap[t]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}};function FRt(t){let e=null,n=null,o=null,i=1,r=null;if(bC(t)||uw(t))o=t,e=LRt(t),n=Die(t);else{if(!kRt.call(t,"name"))throw new Error(XGo("name"));const A=t.name;if(o=A,kRt.call(t,"weight")&&t.weight!==void 0&&(i=t.weight,i<=0))throw new Error($Go(Die(A)));e=LRt(A),n=Die(A),r=t.getFn??null}return{path:e,id:n,weight:i,src:o,getFn:r}}function LRt(t){return uw(t)?t:t.split(".")}function Die(t){return uw(t)?t.join("."):t}function tOo(t,e){const n=[];let o=!1;const i=(r,A,s,a)=>{if(O2(r))if(!A[s])n.push(a!==void 0?{v:r,i:a}:r);else{const c=r[A[s]];if(!O2(c))return;if(s===A.length-1&&(bC(c)||Sie(c)||VGo(c)||typeof c=="bigint"))n.push(a!==void 0?{v:w3e(c),i:a}:w3e(c));else if(uw(c)){o=!0;for(let l=0,g=c.length;l<g;l+=1)i(c[l],A,s+1,l)}else A.length&&i(c,A,s+1,a)}};return i(t,bC(e)?e.split("."):e,0),o?n:n[0]}const vA=Object.freeze({...{isCaseSensitive:!1,ignoreDiacritics:!1,includeScore:!1,keys:[],shouldSort:!0,sortFn:(t,e)=>t.score===e.score?t.idx<e.idx?-1:1:t.score<e.score?-1:1},...{includeMatches:!1,findAllMatches:!1,minMatchCharLength:1},...{location:0,threshold:.6,distance:100},...{useExtendedSearch:!1,useTokenSearch:!1,tokenize:void 0,tokenMatch:"any",getFn:tOo,ignoreLocation:!1,ignoreFieldNorm:!1,fieldNormWeight:1}});function nOo(t){return t>=9&&t<=13||t===32||t===160}function oOo(t=1,e=3){const n=new Map,o=Math.pow(10,e);return{get(i){let r=0,A=!1;for(let a=0;a<i.length;a++)nOo(i.charCodeAt(a))?A=!1:A||(r++,A=!0);if(r===0&&(r=1),n.has(r))return n.get(r);const s=Math.round(o/Math.pow(r,.5*t))/o;return n.set(r,s),s},clear(){n.clear()}}}var v3e=class{constructor({getFn:t=vA.getFn,fieldNormWeight:e=vA.fieldNormWeight}={}){this.norm=oOo(e,3),this.getFn=t,this.isCreated=!1,this.docs=[],this.keys=[],this._keysMap={},this.setIndexRecords()}setSources(t=[]){this.docs=t}setIndexRecords(t=[]){this.records=t}setKeys(t=[]){this.keys=t,this._keysMap={},t.forEach((e,n)=>{this._keysMap[e.id]=n})}create(){if(this.isCreated||!this.docs.length)return;this.isCreated=!0;const t=this.docs.length;this.records=new Array(t);let e=0;if(bC(this.docs[0]))for(let n=0;n<t;n++){const o=this._createStringRecord(this.docs[n],n);o&&(this.records[e++]=o)}else for(let n=0;n<t;n++)this.records[e++]=this._createObjectRecord(this.docs[n],n);this.records.length=e,this.norm.clear()}add(t,e){if(!Number.isInteger(e)||e<0)throw new Error(P3e);if(bC(t)){const o=this._createStringRecord(t,e);return o&&this.records.push(o),o}const n=this._createObjectRecord(t,e);return this.records.push(n),n}removeAt(t){if(!Number.isInteger(t)||t<0)throw new Error(P3e);for(let e=0,n=this.records.length;e<n;e+=1)if(this.records[e].i===t){this.records.splice(e,1);break}for(let e=0,n=this.records.length;e<n;e+=1)this.records[e].i>t&&(this.records[e].i-=1)}removeAll(t){const e=new Set;for(const o of t)Number.isInteger(o)&&o>=0&&e.add(o);if(e.size===0)return;this.records=this.records.filter(o=>!e.has(o.i));const n=Array.from(e).sort((o,i)=>o-i);for(const o of this.records){let i=0,r=n.length;for(;i<r;){const A=i+r>>>1;n[A]<o.i?i=A+1:r=A}o.i-=i}}getValueForItemAtKeyId(t,e){return t[this._keysMap[e]]}size(){return this.records.length}_createStringRecord(t,e){return!O2(t)||bie(t)?null:{v:t,i:e,n:this.norm.get(t)}}_createObjectRecord(t,e){const n={i:e,$:{}};for(let o=0,i=this.keys.length;o<i;o++){const r=this.keys[o],A=r.getFn?r.getFn(t):this.getFn(t,r.path);if(O2(A)){if(uw(A)){const s=[];for(let a=0,c=A.length;a<c;a+=1){const l=A[a];if(O2(l)){if(bC(l)){if(!bie(l)){const g={v:l,i:a,n:this.norm.get(l)};s.push(g)}}else if(O2(l.v)){const g=bC(l.v)?l.v:w3e(l.v);if(!bie(g)){const u={v:g,i:l.i,n:this.norm.get(g)};s.push(u)}}}}n.$[o]=s}else if(bC(A)&&!bie(A)){const s={v:A,n:this.norm.get(A)};n.$[o]=s}}}return n}toJSON(){return{keys:this.keys.map(({getFn:t,...e})=>e),records:this.records}}};function HRt(t,e,{getFn:n=vA.getFn,fieldNormWeight:o=vA.fieldNormWeight}={}){const i=new v3e({getFn:n,fieldNormWeight:o});return i.setKeys(t.map(FRt)),i.setSources(e),i.create(),i}function iOo(t,{getFn:e=vA.getFn,fieldNormWeight:n=vA.fieldNormWeight}={}){const{keys:o,records:i}=t,r=new v3e({getFn:e,fieldNormWeight:n});return r.setKeys(o),r.setIndexRecords(i),r}function rOo(t=[],e=vA.minMatchCharLength){const n=[];let o=-1,i=-1,r=0;for(let A=t.length;r<A;r+=1){const s=t[r];s&&o===-1?o=r:!s&&o!==-1&&(i=r-1,i-o+1>=e&&n.push([o,i]),o=-1)}return t[r-1]&&r-o>=e&&n.push([o,r-1]),n}function AOo(t,e,n,{location:o=vA.location,distance:i=vA.distance,threshold:r=vA.threshold,findAllMatches:A=vA.findAllMatches,minMatchCharLength:s=vA.minMatchCharLength,includeMatches:a=vA.includeMatches,ignoreLocation:c=vA.ignoreLocation}={}){if(e.length>32)throw new Error(jGo(32));const l=e.length,g=t.length,u=Math.max(0,Math.min(o,g));let h=r,d=u;const _=(D,w)=>{const F=D/l;if(c)return F;const R=Math.abs(u-w);return i?F+R/i:R?1:F},p=s>1||a,m=p?Array(g):[];let C;for(;(C=t.indexOf(e,d))>-1;){const D=_(0,C);if(h=Math.min(D,h),d=C+l,p){let w=0;for(;w<l;)m[C+w]=1,w+=1}}d=-1;let I=[],f=1,y=0,x=l+g;const B=1<<l-1;for(let D=0;D<l;D+=1){let w=0,F=x;for(;w<F;)_(D,u+F)<=h?w=F:x=F,F=Math.floor((x-w)/2+w);x=F;let R=Math.max(1,u-F+1);const H=A?g:Math.min(u+F,g)+l,G=Array(H+2);G[H+1]=(1<<D)-1;for(let K=H;K>=R;K-=1){const V=K-1,W=n[t[V]];if(G[K]=(G[K+1]<<1|1)&W,D&&(G[K]|=(I[K+1]|I[K])<<1|1|I[K+1]),G[K]&B&&(f=_(D,V),f<=h)){if(h=f,d=V,y=D,d<=u)break;R=Math.max(1,2*u-d)}}if(_(D+1,u)>h)break;I=G}if(p&&d>=0){const D=Math.min(g-1,d+l-1+y);for(let w=d;w<=D;w+=1)n[t[w]]&&(m[w]=1)}const S={isMatch:d>=0,score:Math.max(.001,f)};if(p){const D=rOo(m,s);D.length?a&&(S.indices=D):S.isMatch=!1}return S}function sOo(t){const e={};for(let n=0,o=t.length;n<o;n+=1){const i=t.charAt(n);e[i]=(e[i]||0)|1<<o-n-1}return e}function N3e(t){if(t.length<=1)return t;t.sort((n,o)=>n[0]-o[0]||n[1]-o[1]);const e=[t[0]];for(let n=1,o=t.length;n<o;n+=1){const i=e[e.length-1],r=t[n];r[0]<=i[1]+1?i[1]=Math.max(i[1],r[1]):e.push(r)}return e}const GRt={ł:"l",Ł:"L",đ:"d",Đ:"D",ø:"o",Ø:"O",ħ:"h",Ħ:"H",ŧ:"t",Ŧ:"T",ı:"i",ß:"ss"},aOo=new RegExp("["+Object.keys(GRt).join("")+"]","g"),tU=typeof String.prototype.normalize=="function"?t=>t.normalize("NFD").replace(/[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C04\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u192B\u1930-\u193B\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F]/g,"").replace(aOo,e=>GRt[e]):t=>t;var R3e=class{constructor(t,{location:e=vA.location,threshold:n=vA.threshold,distance:o=vA.distance,includeMatches:i=vA.includeMatches,findAllMatches:r=vA.findAllMatches,minMatchCharLength:A=vA.minMatchCharLength,isCaseSensitive:s=vA.isCaseSensitive,ignoreDiacritics:a=vA.ignoreDiacritics,ignoreLocation:c=vA.ignoreLocation}={}){if(this.options={location:e,threshold:n,distance:o,includeMatches:i,findAllMatches:r,minMatchCharLength:A,isCaseSensitive:s,ignoreDiacritics:a,ignoreLocation:c},t=s?t:t.toLowerCase(),t=a?tU(t):t,this.pattern=t,this.chunks=[],!this.pattern.length)return;const l=(u,h)=>{this.chunks.push({pattern:u,alphabet:sOo(u),startIndex:h})},g=this.pattern.length;if(g>32){let u=0;const h=g%32,d=g-h;for(;u<d;)l(this.pattern.substr(u,32),u),u+=32;if(h){const _=g-32;l(this.pattern.substr(_),_)}}else l(this.pattern,0)}searchIn(t){const{isCaseSensitive:e,ignoreDiacritics:n,includeMatches:o}=this.options;if(t=e?t:t.toLowerCase(),t=n?tU(t):t,this.pattern===t){if(t.length<this.options.minMatchCharLength)return{isMatch:!1,score:1};const d={isMatch:!0,score:0};return o&&(d.indices=[[0,t.length-1]]),d}const{location:i,distance:r,threshold:A,findAllMatches:s,minMatchCharLength:a,ignoreLocation:c}=this.options,l=[];let g=0,u=!1;this.chunks.forEach(({pattern:d,alphabet:_,startIndex:p})=>{const{isMatch:m,score:C,indices:I}=AOo(t,d,_,{location:i+p,distance:r,threshold:A,findAllMatches:s,minMatchCharLength:a,includeMatches:o,ignoreLocation:c});m&&(u=!0),g+=C,m&&I&&l.push(...I)});const h={isMatch:u,score:u?g/this.chunks.length:1};return u&&o&&(h.indices=N3e(l)),h}};const cOo=new Set(["fuzzy","include"]);function lOo(t){return t.startsWith("inverse")}const T3e=[{type:"exact",multiRegex:/^="(.*)"$/,singleRegex:/^=(.*)$/,create:t=>({type:"exact",search(e){const n=e===t;return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}})},{type:"include",multiRegex:/^'"(.*)"$/,singleRegex:/^'(.*)$/,create:t=>({type:"include",search(e){let n=0,o;const i=[],r=t.length;for(;(o=e.indexOf(t,n))>-1;)n=o+r,i.push([o,n-1]);const A=!!i.length;return{isMatch:A,score:A?0:1,indices:i}}})},{type:"prefix-exact",multiRegex:/^\^"(.*)"$/,singleRegex:/^\^(.*)$/,create:t=>({type:"prefix-exact",search(e){const n=e.startsWith(t);return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}})},{type:"inverse-prefix-exact",multiRegex:/^!\^"(.*)"$/,singleRegex:/^!\^(.*)$/,create:t=>({type:"inverse-prefix-exact",search(e){const n=!e.startsWith(t);return{isMatch:n,score:n?0:1,indices:[0,e.length-1]}}})},{type:"inverse-suffix-exact",multiRegex:/^!"(.*)"\$$/,singleRegex:/^!(.*)\$$/,create:t=>({type:"inverse-suffix-exact",search(e){const n=!e.endsWith(t);return{isMatch:n,score:n?0:1,indices:[0,e.length-1]}}})},{type:"suffix-exact",multiRegex:/^"(.*)"\$$/,singleRegex:/^(.*)\$$/,create:t=>({type:"suffix-exact",search(e){const n=e.endsWith(t);return{isMatch:n,score:n?0:1,indices:[e.length-t.length,e.length-1]}}})},{type:"inverse-exact",multiRegex:/^!"(.*)"$/,singleRegex:/^!(.*)$/,create:t=>({type:"inverse-exact",search(e){const n=e.indexOf(t)===-1;return{isMatch:n,score:n?0:1,indices:[0,e.length-1]}}})},{type:"fuzzy",multiRegex:/^"(.*)"$/,singleRegex:/^(.*)$/,create:(t,e={})=>{const n=new R3e(t,{location:e.location??vA.location,threshold:e.threshold??vA.threshold,distance:e.distance??vA.distance,includeMatches:e.includeMatches??vA.includeMatches,findAllMatches:e.findAllMatches??vA.findAllMatches,minMatchCharLength:e.minMatchCharLength??vA.minMatchCharLength,isCaseSensitive:e.isCaseSensitive??vA.isCaseSensitive,ignoreDiacritics:e.ignoreDiacritics??vA.ignoreDiacritics,ignoreLocation:e.ignoreLocation??vA.ignoreLocation});return{type:"fuzzy",search(o){return n.searchIn(o)}}}}],ORt=T3e.length,gOo="\0",uOo="|";function dOo(t){const e=[],n=t.length;let o=0;for(;o<n;){for(;o<n&&t[o]===" ";)o++;if(o>=n)break;let i=o;for(;i<n&&t[i]!==" "&&t[i]!=='"';)i++;if(i<n&&t[i]==='"'){for(i++;i<n;){if(t[i]==='"'){const r=i+1;if(r>=n||t[r]===" "){i++;break}if(t[r]==="$"&&(r+1>=n||t[r+1]===" ")){i+=2;break}}i++}e.push(t.substring(o,i)),o=i}else{for(;i<n&&t[i]!==" ";)i++;e.push(t.substring(o,i)),o=i}}return e}function KRt(t,e){const n=t.match(e);return n?n[1]:null}function hOo(t,e={}){return t.replace(/\\\|/g,gOo).split(uOo).map(n=>{const o=dOo(n.replace(/\u0000/g,"|").trim()).filter(r=>r&&!!r.trim()),i=[];for(let r=0,A=o.length;r<A;r+=1){const s=o[r];let a=!1,c=-1;for(;!a&&++c<ORt;){const l=T3e[c],g=KRt(s,l.multiRegex);g&&(i.push(l.create(g,e)),a=!0)}if(!a)for(c=-1;++c<ORt;){const l=T3e[c],g=KRt(s,l.singleRegex);if(g){i.push(l.create(g,e));break}}}return i})}var _Oo=class{constructor(t,{isCaseSensitive:e=vA.isCaseSensitive,ignoreDiacritics:n=vA.ignoreDiacritics,includeMatches:o=vA.includeMatches,minMatchCharLength:i=vA.minMatchCharLength,ignoreLocation:r=vA.ignoreLocation,findAllMatches:A=vA.findAllMatches,location:s=vA.location,threshold:a=vA.threshold,distance:c=vA.distance}={}){this.query=null,this.options={isCaseSensitive:e,ignoreDiacritics:n,includeMatches:o,minMatchCharLength:i,findAllMatches:A,ignoreLocation:r,location:s,threshold:a,distance:c},t=e?t:t.toLowerCase(),t=n?tU(t):t,this.pattern=t,this.query=hOo(this.pattern,this.options)}static condition(t,e){return e.useExtendedSearch}searchIn(t){const e=this.query;if(!e)return{isMatch:!1,score:1};const{includeMatches:n,isCaseSensitive:o,ignoreDiacritics:i}=this.options;t=o?t:t.toLowerCase(),t=i?tU(t):t;let r=0;const A=[];let s=0,a=!1;for(let c=0,l=e.length;c<l;c+=1){const g=e[c];A.length=0,r=0,a=!1;for(let u=0,h=g.length;u<h;u+=1){const d=g[u],{isMatch:_,indices:p,score:m}=d.search(t);if(_)r+=1,s+=m,lOo(d.type)&&(a=!0),n&&(cOo.has(d.type)?A.push(...p):A.push(p));else{s=0,r=0,A.length=0,a=!1;break}}if(r){const u={isMatch:!0,score:s/r};return a&&(u.hasInverse=!0),n&&(u.indices=N3e(A)),u}}return{isMatch:!1,score:1}}};const k3e=[];function F3e(...t){k3e.push(...t)}function Mie(t,e){for(let n=0,o=k3e.length;n<o;n+=1){const i=k3e[n];if(i.condition(t,e))return new i(t,e)}return new R3e(t,e)}const wie={AND:"$and",OR:"$or"},L3e={PATH:"$path",PATTERN:"$val"},H3e=t=>!!(t[wie.AND]||t[wie.OR]),mOo=t=>!!t[L3e.PATH],pOo=t=>!uw(t)&&RRt(t)&&!H3e(t),URt=t=>({[wie.AND]:Object.keys(t).map(e=>({[e]:t[e]}))});function YRt(t,e,{auto:n=!0}={}){const o=i=>{if(bC(i)){const a={keyId:null,pattern:i};return n&&(a.searcher=Mie(i,e)),a}const r=Object.keys(i),A=mOo(i);if(!A&&r.length>1&&!H3e(i))return o(URt(i));if(pOo(i)){const a=A?i[L3e.PATH]:r[0],c=A?i[L3e.PATTERN]:i[a];if(!bC(c))throw new Error(WGo(a));const l={keyId:Die(a),pattern:c};return n&&(l.searcher=Mie(c,e)),l}const s={children:[],operator:r[0]};return r.forEach(a=>{const c=i[a];uw(c)&&c.forEach(l=>{s.children.push(o(l))})}),s};return H3e(t)||(t=URt(t)),o(t)}function G3e(t,{ignoreFieldNorm:e=vA.ignoreFieldNorm}){let n=1;return t.forEach(({key:o,norm:i,score:r})=>{const A=o?o.weight:null;n*=Math.pow(r===0&&A?Number.EPSILON:r,(A||1)*(e?1:i))}),n}function IOo(t,{ignoreFieldNorm:e=vA.ignoreFieldNorm}){t.forEach(n=>{n.score=G3e(n.matches,{ignoreFieldNorm:e})})}var COo=class{constructor(t,e){this.limit=t,this.heap=[],this.comparator=e}get size(){return this.heap.length}insert(t){this.size<this.limit?(this.heap.push(t),this._bubbleUp(this.size-1)):this.comparator(t,this.heap[0])<0&&(this.heap[0]=t,this._sinkDown(0))}extractSorted(){return this.heap.sort(this.comparator)}_bubbleUp(t){const e=this.heap;for(;t>0;){const n=t-1>>1;if(this.comparator(e[t],e[n])<=0)break;const o=e[t];e[t]=e[n],e[n]=o,t=n}}_sinkDown(t){const e=this.heap,n=e.length;let o=t;do{t=o;const i=2*t+1,r=2*t+2;if(i<n&&this.comparator(e[i],e[o])>0&&(o=i),r<n&&this.comparator(e[r],e[o])>0&&(o=r),o!==t){const A=e[t];e[t]=e[o],e[o]=A}}while(o!==t)}};function fOo(t){const e=[];return t.matches.forEach(n=>{if(!O2(n.indices)||!n.indices.length)return;const o={indices:n.indices,value:n.value};n.key&&(o.key=n.key.id),n.idx>-1&&(o.refIndex=n.idx),e.push(o)}),e}function yOo(t,e,{includeMatches:n=vA.includeMatches,includeScore:o=vA.includeScore}={}){return t.map(i=>{const{idx:r}=i,A={item:e[r],refIndex:r};return n&&(A.matches=fOo(i)),o&&(A.score=i.score),A})}const EOo=/[\p{L}\p{M}\p{N}_]+/gu,zRt=new WeakSet;function xOo(t){zRt.has(t)||(zRt.add(t),console.warn(`[Fuse] tokenize regex ${t} lacks the global flag; only the first match per text will be returned. Add the 'g' flag.`))}function BOo(t){if(typeof t=="function"){let e=!1;return n=>{const o=t(n);if(!e&&(e=!0,!Array.isArray(o)||o.some(i=>typeof i!="string")))throw new Error(`[Fuse] tokenize function must return string[]; received ${Array.isArray(o)?"array containing non-strings":typeof o}.`);return o}}return t instanceof RegExp?(t.global||xOo(t),e=>e.match(t)||[]):e=>e.match(EOo)||[]}function O3e({isCaseSensitive:t=!1,ignoreDiacritics:e=!1,tokenize:n}={}){const o=BOo(n);return{tokenize(i){return t||(i=i.toLowerCase()),e&&(i=tU(i)),o(i)}}}var QOo=class{static condition(t,e){return e.useTokenSearch}constructor(t,e){this.options=e,this.analyzer=O3e({isCaseSensitive:e.isCaseSensitive,ignoreDiacritics:e.ignoreDiacritics,tokenize:e.tokenize});const n=this.analyzer.tokenize(t),{df:o,fieldCount:i}=e._invertedIndex;this.termSearchers=[],this.idfWeights=[];for(const r of n){this.termSearchers.push(new R3e(r,{location:e.location,threshold:e.threshold,distance:e.distance,includeMatches:e.includeMatches,findAllMatches:e.findAllMatches,minMatchCharLength:e.minMatchCharLength,isCaseSensitive:e.isCaseSensitive,ignoreDiacritics:e.ignoreDiacritics,ignoreLocation:!0}));const A=o.get(r)||0,s=Math.log(1+(i-A+.5)/(A+.5));this.idfWeights.push(s)}this.combineAll=e.tokenMatch==="all",this.numTerms=this.termSearchers.length,this.useMask=this.numTerms<=31}searchIn(t){if(!this.termSearchers.length)return{isMatch:!1,score:1};const e=[];let n=0,o=0,i=0,r=0;const A=this.combineAll&&!this.useMask?new Set:null;for(let c=0;c<this.termSearchers.length;c++){const l=this.termSearchers[c].searchIn(t),g=this.idfWeights[c];o+=g,l.isMatch&&(i++,n+=g*(1-l.score),l.indices&&e.push(...l.indices),this.combineAll&&(this.useMask?r|=1<<c:A.add(c)))}if(i===0)return{isMatch:!1,score:1};const s=o>0?1-n/o:0,a={isMatch:!0,score:Math.max(.001,s)};return this.options.includeMatches&&e.length&&(a.indices=N3e(e)),this.combineAll&&(this.useMask?a.matchedMask=r:a.matchedTerms=A,a.termCount=this.numTerms),a}};function K3e(t,e,n,o){const i=o.tokenize(e);if(!i.length)return;t.fieldCount++,t.docFieldCount.set(n,(t.docFieldCount.get(n)||0)+1);const r=new Set(i);let A=t.docTermFieldHits.get(n);A||(A=new Map,t.docTermFieldHits.set(n,A));for(const s of r)A.set(s,(A.get(s)||0)+1),t.df.set(s,(t.df.get(s)||0)+1)}function VRt(t,e,n,o){const{i,v:r,$:A}=e;if(r!==void 0){K3e(t,r,i,o);return}if(A)for(let s=0;s<n;s++){const a=A[s];if(a)if(Array.isArray(a))for(const c of a)K3e(t,c.v,i,o);else K3e(t,a.v,i,o)}}function SOo(t,e,n){const o={fieldCount:0,df:new Map,docFieldCount:new Map,docTermFieldHits:new Map};for(const i of t)VRt(o,i,e,n);return o}function bOo(t,e,n,o){VRt(t,e,n,o)}function DOo(t,e){const n=t.docFieldCount.get(e);if(n===void 0)return;t.fieldCount-=n,t.docFieldCount.delete(e);const o=t.docTermFieldHits.get(e);if(o){for(const[i,r]of o){const A=(t.df.get(i)||0)-r;A<=0?t.df.delete(i):t.df.set(i,A)}t.docTermFieldHits.delete(e)}}function JRt(t,e){if(e.length===0)return;const n=Array.from(new Set(e)).sort((s,a)=>s-a);for(const s of n)DOo(t,s);const o=s=>{let a=0,c=n.length;for(;a<c;){const l=a+c>>>1;n[l]<s?a=l+1:c=l}return s-a},i=n[0],r=new Map;for(const[s,a]of t.docFieldCount)r.set(s>i?o(s):s,a);t.docFieldCount=r;const A=new Map;for(const[s,a]of t.docTermFieldHits)A.set(s>i?o(s):s,a);t.docTermFieldHits=A}var dw=class{constructor(t,e,n){this.options={...vA,...e},this.options.useExtendedSearch,this.options.useTokenSearch,this._keyStore=new eOo(this.options.keys),this._docs=t,this._myIndex=null,this._invertedIndex=null,this.setCollection(t,n),this._lastQuery=null,this._lastSearcher=null}_getSearcher(t){if(this._lastQuery===t)return this._lastSearcher;const e=Mie(t,this._invertedIndex?{...this.options,_invertedIndex:this._invertedIndex}:this.options);return this._lastQuery=t,this._lastSearcher=e,e}setCollection(t,e){if(this._docs=t,e&&!(e instanceof v3e))throw new Error(qGo);if(this._myIndex=e||HRt(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight}),this.options.useTokenSearch){const n=O3e({isCaseSensitive:this.options.isCaseSensitive,ignoreDiacritics:this.options.ignoreDiacritics,tokenize:this.options.tokenize});this._invertedIndex=SOo(this._myIndex.records,this._myIndex.keys.length,n)}this._invalidateSearcherCache()}add(t){if(!O2(t))return;this._docs.push(t);const e=this._myIndex.add(t,this._docs.length-1);if(this._invertedIndex&&e){const n=O3e({isCaseSensitive:this.options.isCaseSensitive,ignoreDiacritics:this.options.ignoreDiacritics,tokenize:this.options.tokenize});bOo(this._invertedIndex,e,this._myIndex.keys.length,n)}this._invalidateSearcherCache()}remove(t=()=>!1){const e=[],n=[];for(let o=0,i=this._docs.length;o<i;o+=1)t(this._docs[o],o)&&(e.push(this._docs[o]),n.push(o));if(n.length){this._invertedIndex&&JRt(this._invertedIndex,n);const o=new Set(n);this._docs=this._docs.filter((i,r)=>!o.has(r)),this._myIndex.removeAll(n),this._invalidateSearcherCache()}return e}removeAt(t){if(!Number.isInteger(t)||t<0||t>=this._docs.length)throw new Error(P3e);this._invertedIndex&&JRt(this._invertedIndex,[t]);const e=this._docs.splice(t,1)[0];return this._myIndex.removeAt(t),this._invalidateSearcherCache(),e}_invalidateSearcherCache(){this._lastQuery=null,this._lastSearcher=null}getIndex(){return this._myIndex}_normalizedKeys(){return this._myIndex.keys.map(t=>this._keyStore.get(t.id)||t)}search(t,e){const{limit:n=-1}=e||{},{includeMatches:o,includeScore:i,shouldSort:r,sortFn:A,ignoreFieldNorm:s}=this.options;if(bC(t)&&!t.trim()){let u=this._docs.map((h,d)=>({item:h,refIndex:d}));return Sie(n)&&n>-1&&(u=u.slice(0,n)),u}const a=r&&Sie(n)&&n>0&&bC(t),c=A,l=(u,h)=>c(u,h)||u.idx-h.idx;let g;if(a){const u=new COo(n,l);bC(this._docs[0])?this._searchStringList(t,{heap:u,ignoreFieldNorm:s}):this._searchObjectList(t,{heap:u,ignoreFieldNorm:s}),g=u.extractSorted()}else g=bC(t)?bC(this._docs[0])?this._searchStringList(t):this._searchObjectList(t):this._searchLogical(t),IOo(g,{ignoreFieldNorm:s}),r&&g.sort(bC(t)?l:c),Sie(n)&&n>-1&&(g=g.slice(0,n));return yOo(g,this._docs,{includeMatches:o,includeScore:i})}_searchStringList(t,{heap:e,ignoreFieldNorm:n}={}){const o=this._getSearcher(t),i=this.options.useTokenSearch&&this.options.tokenMatch==="all",{records:r}=this._myIndex,A=e?null:[];return r.forEach(({v:s,i:a,n:c})=>{if(!O2(s))return;const l=o.searchIn(s);if(l.isMatch){const g={score:l.score,value:s,norm:c,indices:l.indices};i&&(g.matchedMask=l.matchedMask,g.matchedTerms=l.matchedTerms,g.termCount=l.termCount);const u=[g];if(!i||this._coversAllTokens(u)){const h={item:s,idx:a,matches:u};e?(h.score=G3e(h.matches,{ignoreFieldNorm:n}),e.insert(h)):A.push(h)}}}),A}_searchLogical(t){const e=YRt(t,this.options),n=this._normalizedKeys(),o=(s,a,c)=>{if(!("children"in s)){const{keyId:h,searcher:d}=s;let _;return h===null?(_=[],n.forEach((p,m)=>{_.push(...this._findMatches({key:p,value:a[m],searcher:d}))})):_=this._findMatches({key:this._keyStore.get(h),value:this._myIndex.getValueForItemAtKeyId(a,h),searcher:d}),_&&_.length?[{idx:c,item:a,matches:_}]:[]}const{children:l,operator:g}=s,u=[];for(let h=0,d=l.length;h<d;h+=1){const _=l[h],p=o(_,a,c);if(p.length)u.push(...p);else if(g===wie.AND)return[]}return u},i=this._myIndex.records,r=new Map,A=[];return i.forEach(({$:s,i:a})=>{if(O2(s)){const c=o(e,s,a);c.length&&(r.has(a)||(r.set(a,{idx:a,item:s,matches:[]}),A.push(r.get(a))),c.forEach(({matches:l})=>{r.get(a).matches.push(...l)}))}}),A}_searchObjectList(t,{heap:e,ignoreFieldNorm:n}={}){const o=this._getSearcher(t),i=this.options.useTokenSearch&&this.options.tokenMatch==="all",{records:r}=this._myIndex,A=this._normalizedKeys(),s=e?null:[];return r.forEach(({$:a,i:c})=>{if(!O2(a))return;const l=[];let g=!1,u=!1;if(A.forEach((h,d)=>{const _=this._findMatches({key:h,value:a[d],searcher:o});_.length?(l.push(..._),_[0].hasInverse&&(u=!0)):g=!0}),!(u&&g)&&l.length&&(!i||this._coversAllTokens(l))){const h={idx:c,item:a,matches:l};e?(h.score=G3e(h.matches,{ignoreFieldNorm:n}),e.insert(h)):s.push(h)}}),s}_findMatches({key:t,value:e,searcher:n}){if(!O2(e))return[];const o=[];if(uw(e))e.forEach(({v:i,i:r,n:A})=>{if(!O2(i))return;const s=n.searchIn(i);if(s.isMatch){const a={score:s.score,key:t,value:i,idx:r,norm:A,indices:s.indices,hasInverse:s.hasInverse};s.termCount!==void 0&&(a.matchedMask=s.matchedMask,a.matchedTerms=s.matchedTerms,a.termCount=s.termCount),o.push(a)}});else{const{v:i,n:r}=e,A=n.searchIn(i);if(A.isMatch){const s={score:A.score,key:t,value:i,norm:r,indices:A.indices,hasInverse:A.hasInverse};A.termCount!==void 0&&(s.matchedMask=A.matchedMask,s.matchedTerms=A.matchedTerms,s.termCount=A.termCount),o.push(s)}}return o}_coversAllTokens(t){const e=t.length?t[0].termCount:void 0;if(e===void 0)return!0;if(e<=31){let o=0;for(let i=0;i<t.length;i++)o|=t[i].matchedMask||0;return o===2**e-1}const n=new Set;for(let o=0;o<t.length;o++){const i=t[o].matchedTerms;if(i)for(const r of i)n.add(r)}return n.size===e}};dw.version="7.5.0",dw.createIndex=HRt,dw.parseIndex=iOo,dw.config=vA,dw.match=function(t,e,n){if(n&&n.useTokenSearch)throw new Error(ZGo);return Mie(t,{...vA,...n}).searchIn(e)},dw.parseQuery=YRt,F3e(_Oo),F3e(QOo),dw.use=function(...t){t.forEach(e=>F3e(e))};var MOo=dw;const wOo="https://kicad-mod-cache.tscircuit.com";let U3e=null,nU=null,Y3e=null;const POo=async()=>U3e||nU||(nU=fetch("https://kicad-mod-cache.tscircuit.com/kicad_files.json").then(t=>t.json()).then(t=>(U3e=t,nU=null,t)),nU),vOo=async(t,e=20)=>{const n=await POo();return Y3e||(Y3e=new MOo(n)),Y3e.search(t).slice(0,e).map(o=>o.item)},NOo=t=>{const e=t.replace(".pretty/","/").replace(".kicad_mod",""),n=`kicad:${e}`;return{path:t,qualifiedName:n,description:e}},ROo=t=>t.replace(/^\/+/,"").split("/").map(e=>encodeURIComponent(e)).join("/"),TOo=async t=>{const e=await fetch(`${wOo}/${ROo(t)}`);if(!e.ok)throw new Error(`KiCad footprint fetch failed: ${e.status}`);const n=await e.text(),{KicadFootprintToCircuitJsonConverter:o}=await DB("kicad-to-circuit-json"),i=new o;return i.addFile(t.split("/").pop()??"selected-footprint.kicad_mod",n),i.runUntilFinished(),i.getOutput()},qRt=t=>t?.source==="jlcpcb"||t?.source==="kicad",kOo=async(t,e)=>{if(t.source==="jlcpcb")return YGo(t.component.partNumber,e?.jlcpcb);if(t.source==="kicad")return TOo(t.footprint.path);throw new Error("Footprint preview is not available for this source")},FOo=({query:t,placeholder:e,isSearching:n,onQueryChange:o,onSubmit:i})=>{const r=j.useCallback(A=>{A.key==="Enter"&&(A.preventDefault(),i())},[i]);return J.jsxs("div",{className:"rf-flex rf-items-center rf-gap-2 rf-mt-4",children:[J.jsxs("div",{className:"rf-relative rf-flex-grow",children:[J.jsx(Wwe,{className:"rf-absolute rf-left-2 rf-top-2.5 rf-h-4 rf-w-4 rf-text-muted-foreground"}),J.jsx(YPe,{placeholder:e,className:"rf-pl-8",spellCheck:!1,autoComplete:"off",value:t,onChange:A=>o(A.target.value),onKeyDown:r})]}),J.jsx(ta,{onClick:i,disabled:n||t.trim().length<1,className:"sm:rf-px-4 rf-px-3",children:n?J.jsx(SB,{className:"rf-h-4 rf-w-4 rf-animate-spin"}):J.jsxs(J.Fragment,{children:[J.jsx(Wwe,{className:"rf-h-4 rf-w-4 sm:rf-hidden"}),J.jsx("span",{className:"rf-hidden sm:rf-inline",children:"Search"})]})})]})},LOo=new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}),HOo=t=>LOo.format(t),WRt=t=>{switch(t.source){case"tscircuit.com":{const e=t.package;return`tscircuit-${e.package_id??`${e.org_owner_tscircuit_handle??"unknown"}-${e.unscoped_name??e.name??"package"}`}`}case"jlcpcb":return`jlc-${t.component.lcscId}`;case"kicad":return`kicad-${t.footprint.path}`;default:return"unknown"}},GOo=t=>{switch(t.source){case"tscircuit.com":return t.package.unscoped_name;case"jlcpcb":return t.component.isDirectLookup?t.component.partNumber:t.component.manufacturer;case"kicad":return t.footprint.qualifiedName}},OOo=t=>{switch(t.source){case"tscircuit.com":return t.package.description||(t.package.org_owner_tscircuit_handle?`Component by ${t.package.org_owner_tscircuit_handle}`:void 0);case"jlcpcb":return t.component.description;case"kicad":return t.footprint.description}},KOo=t=>{switch(t.source){case"tscircuit.com":return t.package.name;case"jlcpcb":return t.component.isDirectLookup?void 0:t.component.partNumber;case"kicad":return}},UOo=({results:t,selected:e,onSelect:n,onShowDetails:o})=>{const i=e?WRt(e):null;return J.jsx("div",{className:"rf-divide-y rf-w-full rf-overflow-hidden",children:t.map(r=>{const A=WRt(r),s=i===A,a=GOo(r),c=OOo(r),l=KOo(r),g=r.source==="jlcpcb"?r.component.stock:null,u=r.source==="jlcpcb"?r.component.price:null,h=r.source==="jlcpcb"?r.component.isBasic:null,d=r.source==="jlcpcb"?r.component.isDirectLookup:!1;return J.jsxs("div",{className:`rf-p-3 rf-flex rf-flex-col sm:rf-grid sm:rf-grid-cols-[minmax(0,1fr)_auto] rf-items-start sm:rf-items-center rf-cursor-pointer hover:rf-bg-zinc-100 rf-gap-2 rf-overflow-hidden ${s?"rf-bg-zinc-100":""}`,onClick:()=>n(r),children:[J.jsxs("div",{className:"rf-min-w-0 rf-overflow-hidden rf-w-full",children:[J.jsxs("div",{className:"rf-flex rf-items-start rf-gap-2 rf-min-w-0",children:[J.jsxs("div",{className:"rf-font-medium rf-text-sm rf-truncate rf-flex-1 rf-min-w-0 rf-flex rf-items-center rf-gap-1.5",children:[a,r.source==="jlcpcb"&&h!=null&&J.jsx("span",{className:`rf-text-xs rf-px-1.5 rf-py-0.5 rf-rounded rf-font-medium rf-flex-shrink-0 ${h?"rf-bg-green-100 rf-text-green-700":"rf-bg-orange-100 rf-text-orange-700"}`,children:h?"Basic":"Extended"}),d&&J.jsx("span",{className:"rf-text-xs rf-px-1.5 rf-py-0.5 rf-rounded rf-font-medium rf-flex-shrink-0 rf-bg-blue-100 rf-text-blue-700",children:"Direct lookup"}),r.source==="tscircuit.com"&&r.package.is_private&&J.jsx(NPo,{className:"rf-ml-1 rf-h-3 rf-w-3 rf-text-zinc-400 rf-flex-shrink-0"})]}),r.source==="jlcpcb"&&g!=null?J.jsxs("div",{className:"rf-text-xs rf-text-zinc-500 rf-font-medium rf-whitespace-nowrap rf-flex-shrink-0 sm:rf-hidden",children:[g.toLocaleString()," in stock"]}):null]}),J.jsxs("div",{className:"rf-text-xs rf-text-zinc-500 rf-truncate rf-w-full",children:[l?J.jsx("span",{className:"rf-mr-2",children:l}):null,c]})]}),J.jsxs("div",{children:[r.source==="tscircuit.com"&&o?J.jsx("div",{className:"rf-flex-shrink-0 rf-w-full sm:rf-w-auto",children:J.jsx(ta,{variant:"outline",size:"sm",className:"rf-text-xs rf-w-full sm:rf-w-auto",onClick:_=>{_.stopPropagation(),o(r)},children:"See Details"})}):r.source==="jlcpcb"&&g!=null?J.jsxs("div",{className:"rf-hidden sm:rf-block rf-text-xs rf-text-zinc-500 rf-font-medium rf-whitespace-nowrap rf-flex-shrink-0",children:[g.toLocaleString()," in stock"]}):null,u!=null&&J.jsx("div",{className:"rf-hidden sm:rf-block rf-text-xs rf-text-zinc-500 rf-font-medium rf-whitespace-nowrap rf-flex-shrink-0 rf-text-right",children:HOo(u)})]})]},A)})})},YOo=({circuitJson:t,error:e,isLoading:n,height:o})=>J.jsx("section",{className:"rf-flex rf-min-w-0 rf-items-center rf-justify-center",style:{height:o},children:n?J.jsxs("div",{className:"rf-flex rf-w-full rf-items-center rf-justify-center rf-gap-2 rf-bg-zinc-950 rf-text-sm rf-text-zinc-300",style:{height:o},children:[J.jsx(SB,{className:"rf-h-4 rf-w-4 rf-animate-spin"}),"Loading preview..."]}):e?J.jsx("div",{className:"rf-flex rf-w-full rf-items-center rf-justify-center rf-bg-zinc-950 rf-p-4",style:{height:o},children:J.jsxs("div",{className:"rf-flex rf-max-w-[320px] rf-items-start rf-gap-2 rf-text-sm rf-text-zinc-300",children:[J.jsx(TPt,{className:"rf-mt-0.5 rf-h-4 rf-w-4 rf-flex-shrink-0"}),J.jsx("span",{children:e})]})}):t?J.jsx("div",{className:"rf-w-full rf-min-w-0 rf-overflow-hidden",children:J.jsx(nRt,{circuitJson:t,height:o,allowEditing:!1,clickToInteractEnabled:!1,focusOnHover:!1,disablePcbGroups:!0})}):J.jsx("div",{className:"rf-flex rf-w-full rf-items-center rf-justify-center rf-bg-zinc-950 rf-text-sm rf-text-zinc-300",style:{height:o},children:"No preview"})}),jRt={importComponentDialog:101,importComponentDetailsDialog:102},zOo=({packageResult:t,isOpen:e,onOpenChange:n,isLoading:o,details:i,previewTab:r,onPreviewTabChange:A,isSubmitting:s,onImport:a})=>{const c=t?.package??null,l=c?.latest_pcb_preview_image_url,g=c?.latest_sch_preview_image_url,u=c?.latest_cad_preview_image_url,h=c?.unscoped_name?.split("/").pop()??c?.unscoped_name,d=c?.org_owner_tscircuit_handle??void 0,_=d?`https://tscircuit.com/${d}`:void 0,p=d&&h?`https://tscircuit.com/${d}/${h}`:void 0;return J.jsx(DT,{open:e,onOpenChange:n,children:J.jsxs(j3,{showOverlay:!1,style:{width:"calc(100vw - 2rem)",zIndex:jRt.importComponentDetailsDialog},className:"rf-max-w-5xl no-scrollbar !rf-overflow-y-auto rf-max-h-[90vh] rf-overflow-hidden rf-flex rf-flex-col rf-rounded-sm",children:[J.jsx(X3,{className:"rf-pb-4 rf-border-b",children:J.jsx("div",{className:"rf-flex rf-items-start rf-justify-between rf-gap-4",children:J.jsxs("div",{className:"rf-flex-1 rf-min-w-0",children:[J.jsx($3,{className:"rf-text-xl rf-font-semibold rf-truncate",children:h}),J.jsx(MT,{children:c?.description})]})})}),J.jsxs("div",{className:"rf-flex-1 rf-overflow-y-auto rf-py-4 rf-space-y-6",children:[d?J.jsxs("div",{children:[J.jsx("span",{className:"rf-text-xs rf-font-medium rf-text-gray-500 rf-uppercase rf-tracking-wide",children:"Created by"}),J.jsx("div",{className:"rf-mt-1 rf-text-sm rf-font-medium",children:_?J.jsx("a",{href:_,target:"_blank",rel:"noopener noreferrer",className:"rf-text-black hover:rf-underline",children:d}):d})]}):null,(u||l||g)&&J.jsx(J.Fragment,{children:J.jsxs("div",{children:[J.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-mb-4",children:"Preview"}),J.jsxs(K1e,{value:r,onValueChange:m=>A(m),children:[J.jsxs(FZ,{className:"rf-inline-flex rf-h-9 rf-items-center rf-justify-center rf-rounded-lg rf-bg-zinc-100 rf-p-1 rf-text-zinc-500 dark:rf-bg-zinc-800 dark:rf-text-zinc-400",children:[l&&J.jsx(XQ,{value:"pcb",children:"PCB"}),g&&J.jsx(XQ,{value:"schematic",children:"Schematic"}),u&&J.jsx(XQ,{value:"3d",children:"3D"})]}),J.jsxs("div",{className:"rf-mt-4",children:[J.jsx(IC,{value:"pcb",className:"rf-border rf-rounded-lg rf-overflow-hidden rf-bg-gray-50",children:l?J.jsx("img",{src:l,alt:`${h??"package"} PCB preview`,className:"rf-w-full rf-h-full rf-object-contain rf-bg-white rf-p-4"}):null}),J.jsx(IC,{value:"schematic",className:"rf-border rf-rounded-lg rf-overflow-hidden rf-bg-gray-50",children:g?J.jsx("img",{src:g,alt:`${h??"package"} schematic preview`,className:"rf-w-full rf-h-full rf-object-contain rf-bg-white rf-p-4"}):null}),J.jsx(IC,{value:"3d",className:"rf-border rf-rounded-lg rf-overflow-hidden rf-bg-gray-50",children:u?J.jsx("img",{src:u,alt:`${h??"package"} 3D preview`,className:"rf-w-full rf-h-full rf-object-contain rf-bg-white rf-p-4"}):null})]})]})]})}),i?.ai_description?J.jsxs("section",{children:[J.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-mb-3",children:"AI Description"}),J.jsx("div",{className:"rf-bg-gray-50 rf-border rf-border-gray-200 rf-rounded-lg rf-p-4",children:J.jsx("p",{className:"rf-text-sm rf-text-gray-700 rf-leading-relaxed",children:i.ai_description})})]}):null,i?.ai_usage_instructions?J.jsxs("section",{children:[J.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-mb-3",children:"Usage Instructions"}),J.jsx("div",{className:"rf-bg-gray-50 rf-border rf-border-gray-200 rf-rounded-lg rf-p-4",children:J.jsx("p",{className:"rf-text-sm rf-text-gray-700 rf-leading-relaxed rf-whitespace-pre-wrap",children:i.ai_usage_instructions})})]}):null,o?J.jsxs("div",{className:"rf-flex rf-justify-center rf-items-center rf-gap-2 rf-text-gray-500",children:[J.jsx(SB,{className:"rf-h-4 rf-w-4 rf-animate-spin"}),J.jsx("span",{className:"rf-text-sm",children:"Loading package details..."})]}):null]}),J.jsxs(eU,{className:"rf-pt-4 rf-border-t rf-flex rf-flex-col sm:rf-flex-row rf-justify-between rf-gap-2",children:[J.jsx("div",{className:"rf-flex-1",children:p?J.jsxs(ta,{variant:"outline",size:"sm",className:"rf-gap-2 rf-w-full sm:rf-w-auto",onClick:()=>window.open(p,"_blank"),children:[J.jsx(SPo,{className:"rf-h-4 rf-w-4"}),"View on tscircuit.com"]}):null}),J.jsxs("div",{className:"rf-flex rf-flex-col sm:rf-flex-row rf-gap-2",children:[J.jsx(ta,{variant:"outline",onClick:()=>n(!1),className:"rf-order-2 sm:rf-order-1",children:"Close"}),J.jsx(ta,{onClick:a,disabled:s,className:"rf-bg-blue-600 hover:rf-bg-blue-700",children:s?J.jsx(SB,{className:"rf-h-4 rf-w-4 rf-animate-spin"}):"Import Component"})]})]})]})})},VOo=()=>{const[t,e]=j.useState(null),[n,o]=j.useState(!1),i=j.useCallback(async(A,s)=>{o(!0);try{const a=await fetch(`https://api.tscircuit.com/packages/get?name=${encodeURIComponent(`${A}/${s}`)}`);if(!a.ok)throw new Error(`Failed to load package details: ${a.status}`);const c=await a.json();e(c.package??null)}catch(a){console.error("Failed to fetch package details",a),e(null)}finally{o(!1)}},[]),r=j.useCallback(()=>{e(null),o(!1)},[]);return{details:t,isLoading:n,fetchDetails:i,reset:r}},JOo=(t,e)=>{const[n,o]=j.useState({circuitJson:null,error:null,isLoading:!1});return j.useEffect(()=>{if(!t||!qRt(t)){o({circuitJson:null,error:null,isLoading:!1});return}let i=!1;return o({circuitJson:null,error:null,isLoading:!0}),kOo(t,e).then(r=>{i||o({circuitJson:r,error:null,isLoading:!1})}).catch(r=>{i||o({circuitJson:null,error:r instanceof Error?r.message:"Failed to load footprint preview",isLoading:!1})}),()=>{i=!0}},[t,e]),n},qOo=async(t,e)=>{const n={"Content-Type":"application/json"};e&&(n.Authorization=`Bearer ${e}`);const o=await fetch("https://registry-api.tscircuit.com/packages/search",{method:"POST",headers:n,body:JSON.stringify({query:t})});if(!o.ok)throw new Error(`tscircuit registry error: ${o.status}`);return(await o.json()).packages??[]},WOo=({sessionToken:t})=>{const[e,n]=j.useState([]),[o,i]=j.useState(!1),[r,A]=j.useState(null),[s,a]=j.useState(!1),c=j.useCallback(async g=>{const u=g.trim();if(!u)return[];i(!0),A(null);try{const d=(await qOo(u,t)).map(_=>({source:"tscircuit.com",package:_}));return n(d),d}catch(h){return console.error("Error searching tscircuit packages",h),n([]),A(h instanceof Error?h.message:"Failed to search tscircuit packages"),[]}finally{i(!1),a(!0)}},[t]),l=j.useCallback(()=>{n([]),i(!1),A(null),a(!1)},[]);return{results:e,isSearching:o,error:r,hasSearched:s,search:c,reset:l}},jOo=t=>{const e=/^C(\d+)$/i.exec(t.trim());if(!e)return null;const n=Number(e[1]);if(!Number.isSafeInteger(n))return null;const o=`C${e[1]}`;return{source:"jlcpcb",component:{lcscId:n,manufacturer:o,partNumber:o,description:"Import directly from EasyEDA; stock and availability are unknown",package:"",isDirectLookup:!0}}},XRt=(t,e)=>{const n=jOo(t);return n?e.some(i=>i.component.partNumber.toUpperCase()===n.component.partNumber)?e:[n,...e]:e},XOo=t=>{const e=t.trim();return/^C\d+/i.test(e)?e.replace(/^C/i,""):e},$Oo=()=>{const[t,e]=j.useState([]),[n,o]=j.useState(!1),[i,r]=j.useState(null),[A,s]=j.useState(!1),a=j.useCallback(async l=>{const g=XOo(l);if(!g)return[];o(!0),r(null);try{const u=await OGo(g,10),h=XRt(l,u.map(d=>({source:"jlcpcb",component:KGo(d)})));return e(h),h}catch(u){console.error("Error searching JLCPCB components",u);const h=XRt(l,[]);return e(h),r(h.length>0?null:u instanceof Error?u.message:"Failed to search JLCPCB components"),h}finally{o(!1),s(!0)}},[]),c=j.useCallback(()=>{e([]),o(!1),r(null),s(!1)},[]);return{results:t,isSearching:n,error:i,hasSearched:A,search:a,reset:c}},ZOo=()=>{const[t,e]=j.useState([]),[n,o]=j.useState(!1),[i,r]=j.useState(null),[A,s]=j.useState(!1),a=j.useCallback(async l=>{const g=l.trim();if(!g)return[];o(!0),r(null);try{const h=(await vOo(g,20)).map(d=>({source:"kicad",footprint:NOo(d)}));return e(h),h}catch(u){return console.error("Error searching KiCad footprints",u),e([]),r(u instanceof Error?u.message:"Failed to search KiCad footprints"),[]}finally{o(!1),s(!0)}},[]),c=j.useCallback(()=>{e([]),o(!1),r(null),s(!1)},[]);return{results:t,isSearching:n,error:i,hasSearched:A,search:a,reset:c}},eKo=({onTscircuitPackageSelected:t,onJlcpcbComponentTsxLoaded:e,onKicadStringSelected:n})=>{const o=[];return t&&o.push("tscircuit.com"),e&&o.push("jlcpcb"),n&&o.push("kicad"),o},tKo=({isOpen:t,onClose:e,jlcpcbProxyRequestHeaders:n,onKicadStringSelected:o,onTscircuitPackageSelected:i,onJlcpcbComponentTsxLoaded:r,jlcpcbProxyApiBase:A,tscircuitSessionToken:s})=>{fie();const a=j.useMemo(()=>eKo({onKicadStringSelected:o,onTscircuitPackageSelected:i,onJlcpcbComponentTsxLoaded:r}),[o,i,r]),c=a.length>0,l=a.length===1,[g,u]=j.useState(a[0]??"tscircuit.com"),[h,d]=j.useState(""),[_,p]=j.useState(null),{results:m,isSearching:C,error:I,hasSearched:f,search:y,reset:x}=WOo({sessionToken:s}),{results:B,isSearching:S,error:D,hasSearched:w,search:F,reset:R}=$Oo(),{results:H,isSearching:G,error:K,hasSearched:V,search:W,reset:X}=ZOo(),{details:ie,isLoading:se,fetchDetails:ee,reset:oe}=VOo(),[ae,re]=j.useState(null),[le,fe]=j.useState(!1),[ye,be]=j.useState("pcb"),[ue,Be]=j.useState(null),[pe,Ge]=j.useState(!1),Je=j.useMemo(()=>({jlcpcb:{headers:n,apiBase:A}}),[A,n]),{circuitJson:nt,error:Ie,isLoading:Ze}=JOo(_,Je),Ke=qRt(_);j.useEffect(()=>{Be(null)},[_]);const Ye=j.useCallback(()=>{x(),R(),X(),p(null)},[R,X,x]);j.useEffect(()=>{t||(Ye(),d(""),fe(!1),re(null),Be(null))},[t,Ye]),j.useEffect(()=>{d(""),p(null),g==="tscircuit.com"?x():g==="jlcpcb"?R():g==="kicad"&&X()},[g,R,X,x]);const qe=lt=>{p(lt),re(lt),be("pcb"),fe(!0),oe();const Ct=lt.package.org_owner_tscircuit_handle,Dt=lt.package.unscoped_name;if(Ct&&Dt){const pt=Dt.split("/").pop()??Dt;ee(Ct,pt)}},Le=async()=>{h.trim()&&(p(null),g==="tscircuit.com"?await y(h):g==="jlcpcb"?await F(h):g==="kicad"&&await W(h))},Se=async lt=>{try{if(Be(null),Ge(!0),lt.source==="kicad"){if(!o)throw new Error("KiCad handler not provided");await o({result:lt,footprint:lt.footprint.qualifiedName})}else if(lt.source==="jlcpcb"){if(!r)throw new Error("JLCPCB handler not provided");const Ct=await UGo(lt.component.partNumber,{headers:n,apiBase:A});await r({result:lt,tsx:Ct})}else if(lt.source==="tscircuit.com"){if(!i)throw new Error("tscircuit package handler not provided");const Ct=lt.package.org_owner_tscircuit_handle,Dt=lt.package.unscoped_name;if(!Ct||!Dt)throw new Error("Missing package metadata");const pt=Dt.split("/").pop()??Dt,Nt=`@tsci/${Ct}.${pt}`;await i({result:lt,fullPackageName:Nt})}return!0}catch(Ct){return console.error("Failed to import component",Ct),Be(Ct instanceof Error?Ct.message:"Failed to import component"),!1}finally{Ge(!1)}};let ve=[],Pe=!1,ze=null,Xe=!1;g==="tscircuit.com"?(ve=m,Pe=C,ze=I,Xe=f):g==="jlcpcb"?(ve=B,Pe=S,ze=D,Xe=w):g==="kicad"&&(ve=H,Pe=G,ze=K,Xe=V);const st=async()=>{if(!_)return;await Se(_)&&(e(),Ye(),d(""))},ct=lt=>{lt||e()},ut=lt=>{fe(lt),lt||re(null)};return J.jsxs(DT,{open:t,onOpenChange:ct,children:[J.jsxs(j3,{style:{width:"calc(100vw - 2rem)",maxWidth:Ke?"min(1120px, calc(100vw - 2rem))":"min(672px, calc(100vw - 2rem))",zIndex:jRt.importComponentDialog},className:"rf-rounded-sm rf-max-h-[90vh] rf-overflow-y-auto rf-overflow-x-hidden rf-flex rf-flex-col",children:[J.jsxs(X3,{children:[J.jsxs($3,{className:"rf-text-lg sm:rf-text-xl",children:["Import ",l?Qie[g].label:""," ","Component"]}),J.jsx(MT,{className:"rf-text-sm",children:c?"Search for components from available sources.":"Import options are disabled because no handlers were provided."})]}),c?J.jsxs(K1e,{value:g,onValueChange:lt=>u(lt),className:"rf-min-w-0 rf-w-full",children:[!l&&J.jsx(FZ,{className:"rf-flex rf-w-full rf-gap-2",children:a.map(lt=>J.jsx(XQ,{value:lt,className:"rf-flex-1 rf-text-xs sm:rf-text-sm",children:Qie[lt].label},lt))}),J.jsxs("div",{className:"rf-min-w-0",style:Ke?{display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(360px, 0.95fr)",gap:"1.5rem",alignItems:"start"}:void 0,children:[J.jsxs("div",{className:"rf-min-w-0",children:[J.jsx(FOo,{query:h,placeholder:Qie[g].placeholder,isSearching:Pe,onQueryChange:d,onSubmit:Le}),J.jsx("div",{className:"no-scrollbar rf-mt-4 rf-flex-1 rf-min-h-[200px] !rf-max-h-[40vh] !rf-overflow-y-auto rf-overflow-x-hidden rf-border rf-rounded-md rf-min-w-0",children:Pe?J.jsxs("div",{className:"rf-p-8 rf-text-center rf-text-zinc-500",children:[J.jsx(SB,{className:"rf-h-8 rf-w-8 rf-animate-spin rf-mx-auto rf-mb-2"}),J.jsx("p",{children:"Searching..."})]}):ve.length>0?J.jsx(UOo,{results:ve,selected:_,onSelect:p,onShowDetails:g==="tscircuit.com"?qe:void 0}):J.jsx("div",{className:"rf-p-8 rf-text-center rf-text-zinc-500",children:ze?`Error: ${ze}`:Xe?Qie[g].emptyMessage:"Enter a search term to find components"})})]}),Ke?J.jsx("div",{className:"rf-mt-4",children:J.jsx(YOo,{circuitJson:nt,error:Ie,isLoading:Ze,height:325})}):null]})]}):null,ue?J.jsx("div",{className:"rf-text-sm rf-text-red-600 rf-mt-2",children:ue}):null,J.jsxs(eU,{className:"rf-flex rf-flex-col sm:rf-flex-row rf-gap-2",children:[J.jsx(ta,{variant:"outline",onClick:e,className:"rf-order-2 sm:rf-order-1",children:"Cancel"}),J.jsx(ta,{onClick:st,disabled:!_||pe,className:"rf-order-1 sm:rf-order-2",children:pe?J.jsx(SB,{className:"rf-h-4 rf-w-4 rf-animate-spin"}):"Import"})]})]}),J.jsx(zOo,{packageResult:ae,isOpen:le,onOpenChange:ut,isLoading:se,details:ie,previewTab:ye,onPreviewTabChange:lt=>be(lt),isSubmitting:pe,onImport:()=>{ae&&Se(ae).then(lt=>{lt&&(fe(!1),e(),Ye(),d(""))})}})]})},nKo=t=>{const e=t.match(/export const (\w+) =/);if(!e)throw new Error("Could not determine component name from TSX contents");return e[1]},$Rt=t=>{const e=Yu(A=>A.pushEvent),n=Yu(A=>A.upsertFile),o=async({result:A,fullPackageName:s})=>{const c=A.package.unscoped_name??A.package.name;await zA.promise(e({event_type:"INSTALL_PACKAGE",full_package_name:s}),{loading:`Requesting install for "${c}"`,success:`Install requested for "${c}"`,error:l=>`Failed to request install: ${l instanceof Error?l.message:String(l)}`})},i=async({footprint:A})=>{await zA.promise(navigator.clipboard.writeText(A),{loading:`Copying "${A}"`,success:`Copied "${A}" to clipboard`,error:s=>`Failed to copy footprint: ${s instanceof Error?s.message:String(s)}`})},r=async({result:A,tsx:s})=>{const c=`imports/${nKo(s)}.tsx`;await zA.promise(n(c,s),{loading:`Importing ${A.component.partNumber}`,success:`Imported to "${c}"`,error:l=>`Failed to import component: ${l instanceof Error?l.message:String(l)}`})};return J.jsx(tKo,{...t,onTscircuitPackageSelected:o,onKicadStringSelected:i,onJlcpcbComponentTsxLoaded:r})};$Rt.displayName="ImportComponentDialogForCli";var z3e={exports:{}},ZRt;function oKo(){return ZRt||(ZRt=1,(function(t,e){var n={env:{},version:""};(function(o){t.exports=o()})(function(){return(function o(i,r,A){function s(l,g){if(!r[l]){if(!i[l]){var u=typeof T4=="function"&&T4;if(!g&&u)return u(l,!0);if(a)return a(l,!0);var h=new Error("Cannot find module '"+l+"'");throw h.code="MODULE_NOT_FOUND",h}var d=r[l]={exports:{}};i[l][0].call(d.exports,function(_){var p=i[l][1][_];return s(p||_)},d,d.exports,o,i,r,A)}return r[l].exports}for(var a=typeof T4=="function"&&T4,c=0;c<A.length;c++)s(A[c]);return s})({1:[function(o,i,r){var A=o("./utils"),s=o("./support"),a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";r.encode=function(c){for(var l,g,u,h,d,_,p,m=[],C=0,I=c.length,f=I,y=A.getTypeOf(c)!=="string";C<c.length;)f=I-C,u=y?(l=c[C++],g=C<I?c[C++]:0,C<I?c[C++]:0):(l=c.charCodeAt(C++),g=C<I?c.charCodeAt(C++):0,C<I?c.charCodeAt(C++):0),h=l>>2,d=(3&l)<<4|g>>4,_=1<f?(15&g)<<2|u>>6:64,p=2<f?63&u:64,m.push(a.charAt(h)+a.charAt(d)+a.charAt(_)+a.charAt(p));return m.join("")},r.decode=function(c){var l,g,u,h,d,_,p=0,m=0,C="data:";if(c.substr(0,C.length)===C)throw new Error("Invalid base64 input, it looks like a data url.");var I,f=3*(c=c.replace(/[^A-Za-z0-9+/=]/g,"")).length/4;if(c.charAt(c.length-1)===a.charAt(64)&&f--,c.charAt(c.length-2)===a.charAt(64)&&f--,f%1!=0)throw new Error("Invalid base64 input, bad content length.");for(I=s.uint8array?new Uint8Array(0|f):new Array(0|f);p<c.length;)l=a.indexOf(c.charAt(p++))<<2|(h=a.indexOf(c.charAt(p++)))>>4,g=(15&h)<<4|(d=a.indexOf(c.charAt(p++)))>>2,u=(3&d)<<6|(_=a.indexOf(c.charAt(p++))),I[m++]=l,d!==64&&(I[m++]=g),_!==64&&(I[m++]=u);return I}},{"./support":30,"./utils":32}],2:[function(o,i,r){var A=o("./external"),s=o("./stream/DataWorker"),a=o("./stream/Crc32Probe"),c=o("./stream/DataLengthProbe");function l(g,u,h,d,_){this.compressedSize=g,this.uncompressedSize=u,this.crc32=h,this.compression=d,this.compressedContent=_}l.prototype={getContentWorker:function(){var g=new s(A.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new c("data_length")),u=this;return g.on("end",function(){if(this.streamInfo.data_length!==u.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),g},getCompressedWorker:function(){return new s(A.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},l.createWorkerFrom=function(g,u,h){return g.pipe(new a).pipe(new c("uncompressedSize")).pipe(u.compressWorker(h)).pipe(new c("compressedSize")).withStreamInfo("compression",u)},i.exports=l},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(o,i,r){var A=o("./stream/GenericWorker");r.STORE={magic:"\0\0",compressWorker:function(){return new A("STORE compression")},uncompressWorker:function(){return new A("STORE decompression")}},r.DEFLATE=o("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(o,i,r){var A=o("./utils"),s=(function(){for(var a,c=[],l=0;l<256;l++){a=l;for(var g=0;g<8;g++)a=1&a?3988292384^a>>>1:a>>>1;c[l]=a}return c})();i.exports=function(a,c){return a!==void 0&&a.length?A.getTypeOf(a)!=="string"?(function(l,g,u,h){var d=s,_=h+u;l^=-1;for(var p=h;p<_;p++)l=l>>>8^d[255&(l^g[p])];return-1^l})(0|c,a,a.length,0):(function(l,g,u,h){var d=s,_=h+u;l^=-1;for(var p=h;p<_;p++)l=l>>>8^d[255&(l^g.charCodeAt(p))];return-1^l})(0|c,a,a.length,0):0}},{"./utils":32}],5:[function(o,i,r){r.base64=!1,r.binary=!1,r.dir=!1,r.createFolders=!0,r.date=null,r.compression=null,r.compressionOptions=null,r.comment=null,r.unixPermissions=null,r.dosPermissions=null},{}],6:[function(o,i,r){var A=null;A=typeof Promise<"u"?Promise:o("lie"),i.exports={Promise:A}},{lie:37}],7:[function(o,i,r){var A=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",s=o("pako"),a=o("./utils"),c=o("./stream/GenericWorker"),l=A?"uint8array":"array";function g(u,h){c.call(this,"FlateWorker/"+u),this._pako=null,this._pakoAction=u,this._pakoOptions=h,this.meta={}}r.magic="\b\0",a.inherits(g,c),g.prototype.processChunk=function(u){this.meta=u.meta,this._pako===null&&this._createPako(),this._pako.push(a.transformTo(l,u.data),!1)},g.prototype.flush=function(){c.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},g.prototype.cleanUp=function(){c.prototype.cleanUp.call(this),this._pako=null},g.prototype._createPako=function(){this._pako=new s[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var u=this;this._pako.onData=function(h){u.push({data:h,meta:u.meta})}},r.compressWorker=function(u){return new g("Deflate",u)},r.uncompressWorker=function(){return new g("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(o,i,r){function A(d,_){var p,m="";for(p=0;p<_;p++)m+=String.fromCharCode(255&d),d>>>=8;return m}function s(d,_,p,m,C,I){var f,y,x=d.file,B=d.compression,S=I!==l.utf8encode,D=a.transformTo("string",I(x.name)),w=a.transformTo("string",l.utf8encode(x.name)),F=x.comment,R=a.transformTo("string",I(F)),H=a.transformTo("string",l.utf8encode(F)),G=w.length!==x.name.length,K=H.length!==F.length,V="",W="",X="",ie=x.dir,se=x.date,ee={crc32:0,compressedSize:0,uncompressedSize:0};_&&!p||(ee.crc32=d.crc32,ee.compressedSize=d.compressedSize,ee.uncompressedSize=d.uncompressedSize);var oe=0;_&&(oe|=8),S||!G&&!K||(oe|=2048);var ae=0,re=0;ie&&(ae|=16),C==="UNIX"?(re=798,ae|=(function(fe,ye){var be=fe;return fe||(be=ye?16893:33204),(65535&be)<<16})(x.unixPermissions,ie)):(re=20,ae|=(function(fe){return 63&(fe||0)})(x.dosPermissions)),f=se.getUTCHours(),f<<=6,f|=se.getUTCMinutes(),f<<=5,f|=se.getUTCSeconds()/2,y=se.getUTCFullYear()-1980,y<<=4,y|=se.getUTCMonth()+1,y<<=5,y|=se.getUTCDate(),G&&(W=A(1,1)+A(g(D),4)+w,V+="up"+A(W.length,2)+W),K&&(X=A(1,1)+A(g(R),4)+H,V+="uc"+A(X.length,2)+X);var le="";return le+=`
5794
5794
  \0`,le+=A(oe,2),le+=B.magic,le+=A(f,2),le+=A(y,2),le+=A(ee.crc32,4),le+=A(ee.compressedSize,4),le+=A(ee.uncompressedSize,4),le+=A(D.length,2),le+=A(V.length,2),{fileRecord:u.LOCAL_FILE_HEADER+le+D+V,dirRecord:u.CENTRAL_FILE_HEADER+A(re,2)+le+A(R.length,2)+"\0\0\0\0"+A(ae,4)+A(m,4)+D+V+R}}var a=o("../utils"),c=o("../stream/GenericWorker"),l=o("../utf8"),g=o("../crc32"),u=o("../signature");function h(d,_,p,m){c.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=_,this.zipPlatform=p,this.encodeFileName=m,this.streamFiles=d,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}a.inherits(h,c),h.prototype.push=function(d){var _=d.meta.percent||0,p=this.entriesCount,m=this._sources.length;this.accumulate?this.contentBuffer.push(d):(this.bytesWritten+=d.data.length,c.prototype.push.call(this,{data:d.data,meta:{currentFile:this.currentFile,percent:p?(_+100*(p-m-1))/p:100}}))},h.prototype.openedSource=function(d){this.currentSourceOffset=this.bytesWritten,this.currentFile=d.file.name;var _=this.streamFiles&&!d.file.dir;if(_){var p=s(d,_,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:p.fileRecord,meta:{percent:0}})}else this.accumulate=!0},h.prototype.closedSource=function(d){this.accumulate=!1;var _=this.streamFiles&&!d.file.dir,p=s(d,_,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(p.dirRecord),_)this.push({data:(function(m){return u.DATA_DESCRIPTOR+A(m.crc32,4)+A(m.compressedSize,4)+A(m.uncompressedSize,4)})(d),meta:{percent:100}});else for(this.push({data:p.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},h.prototype.flush=function(){for(var d=this.bytesWritten,_=0;_<this.dirRecords.length;_++)this.push({data:this.dirRecords[_],meta:{percent:100}});var p=this.bytesWritten-d,m=(function(C,I,f,y,x){var B=a.transformTo("string",x(y));return u.CENTRAL_DIRECTORY_END+"\0\0\0\0"+A(C,2)+A(C,2)+A(I,4)+A(f,4)+A(B.length,2)+B})(this.dirRecords.length,p,d,this.zipComment,this.encodeFileName);this.push({data:m,meta:{percent:100}})},h.prototype.prepareNextSource=function(){this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused?this.previous.pause():this.previous.resume()},h.prototype.registerPrevious=function(d){this._sources.push(d);var _=this;return d.on("data",function(p){_.processChunk(p)}),d.on("end",function(){_.closedSource(_.previous.streamInfo),_._sources.length?_.prepareNextSource():_.end()}),d.on("error",function(p){_.error(p)}),this},h.prototype.resume=function(){return!!c.prototype.resume.call(this)&&(!this.previous&&this._sources.length?(this.prepareNextSource(),!0):this.previous||this._sources.length||this.generatedError?void 0:(this.end(),!0))},h.prototype.error=function(d){var _=this._sources;if(!c.prototype.error.call(this,d))return!1;for(var p=0;p<_.length;p++)try{_[p].error(d)}catch{}return!0},h.prototype.lock=function(){c.prototype.lock.call(this);for(var d=this._sources,_=0;_<d.length;_++)d[_].lock()},i.exports=h},{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(o,i,r){var A=o("../compressions"),s=o("./ZipFileWorker");r.generateWorker=function(a,c,l){var g=new s(c.streamFiles,l,c.platform,c.encodeFileName),u=0;try{a.forEach(function(h,d){u++;var _=(function(I,f){var y=I||f,x=A[y];if(!x)throw new Error(y+" is not a valid compression method !");return x})(d.options.compression,c.compression),p=d.options.compressionOptions||c.compressionOptions||{},m=d.dir,C=d.date;d._compressWorker(_,p).withStreamInfo("file",{name:h,dir:m,date:C,comment:d.comment||"",unixPermissions:d.unixPermissions,dosPermissions:d.dosPermissions}).pipe(g)}),g.entriesCount=u}catch(h){g.error(h)}return g}},{"../compressions":3,"./ZipFileWorker":8}],10:[function(o,i,r){function A(){if(!(this instanceof A))return new A;if(arguments.length)throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");this.files=Object.create(null),this.comment=null,this.root="",this.clone=function(){var s=new A;for(var a in this)typeof this[a]!="function"&&(s[a]=this[a]);return s}}(A.prototype=o("./object")).loadAsync=o("./load"),A.support=o("./support"),A.defaults=o("./defaults"),A.version="3.10.1",A.loadAsync=function(s,a){return new A().loadAsync(s,a)},A.external=o("./external"),i.exports=A},{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(o,i,r){var A=o("./utils"),s=o("./external"),a=o("./utf8"),c=o("./zipEntries"),l=o("./stream/Crc32Probe"),g=o("./nodejsUtils");function u(h){return new s.Promise(function(d,_){var p=h.decompressed.getContentWorker().pipe(new l);p.on("error",function(m){_(m)}).on("end",function(){p.streamInfo.crc32!==h.decompressed.crc32?_(new Error("Corrupted zip : CRC32 mismatch")):d()}).resume()})}i.exports=function(h,d){var _=this;return d=A.extend(d||{},{base64:!1,checkCRC32:!1,optimizedBinaryString:!1,createFolders:!1,decodeFileName:a.utf8decode}),g.isNode&&g.isStream(h)?s.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")):A.prepareContent("the loaded zip file",h,!0,d.optimizedBinaryString,d.base64).then(function(p){var m=new c(d);return m.load(p),m}).then(function(p){var m=[s.Promise.resolve(p)],C=p.files;if(d.checkCRC32)for(var I=0;I<C.length;I++)m.push(u(C[I]));return s.Promise.all(m)}).then(function(p){for(var m=p.shift(),C=m.files,I=0;I<C.length;I++){var f=C[I],y=f.fileNameStr,x=A.resolve(f.fileNameStr);_.file(x,f.decompressed,{binary:!0,optimizedBinaryString:!0,date:f.date,dir:f.dir,comment:f.fileCommentStr.length?f.fileCommentStr:null,unixPermissions:f.unixPermissions,dosPermissions:f.dosPermissions,createFolders:d.createFolders}),f.dir||(_.file(x).unsafeOriginalName=y)}return m.zipComment.length&&(_.comment=m.zipComment),_})}},{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(o,i,r){var A=o("../utils"),s=o("../stream/GenericWorker");function a(c,l){s.call(this,"Nodejs stream input adapter for "+c),this._upstreamEnded=!1,this._bindStream(l)}A.inherits(a,s),a.prototype._bindStream=function(c){var l=this;(this._stream=c).pause(),c.on("data",function(g){l.push({data:g,meta:{percent:0}})}).on("error",function(g){l.isPaused?this.generatedError=g:l.error(g)}).on("end",function(){l.isPaused?l._upstreamEnded=!0:l.end()})},a.prototype.pause=function(){return!!s.prototype.pause.call(this)&&(this._stream.pause(),!0)},a.prototype.resume=function(){return!!s.prototype.resume.call(this)&&(this._upstreamEnded?this.end():this._stream.resume(),!0)},i.exports=a},{"../stream/GenericWorker":28,"../utils":32}],13:[function(o,i,r){var A=o("readable-stream").Readable;function s(a,c,l){A.call(this,c),this._helper=a;var g=this;a.on("data",function(u,h){g.push(u)||g._helper.pause(),l&&l(h)}).on("error",function(u){g.emit("error",u)}).on("end",function(){g.push(null)})}o("../utils").inherits(s,A),s.prototype._read=function(){this._helper.resume()},i.exports=s},{"../utils":32,"readable-stream":16}],14:[function(o,i,r){i.exports={isNode:typeof Buffer<"u",newBufferFrom:function(A,s){if(Buffer.from&&Buffer.from!==Uint8Array.from)return Buffer.from(A,s);if(typeof A=="number")throw new Error('The "data" argument must not be a number');return new Buffer(A,s)},allocBuffer:function(A){if(Buffer.alloc)return Buffer.alloc(A);var s=new Buffer(A);return s.fill(0),s},isBuffer:function(A){return Buffer.isBuffer(A)},isStream:function(A){return A&&typeof A.on=="function"&&typeof A.pause=="function"&&typeof A.resume=="function"}}},{}],15:[function(o,i,r){function A(x,B,S){var D,w=a.getTypeOf(B),F=a.extend(S||{},g);F.date=F.date||new Date,F.compression!==null&&(F.compression=F.compression.toUpperCase()),typeof F.unixPermissions=="string"&&(F.unixPermissions=parseInt(F.unixPermissions,8)),F.unixPermissions&&16384&F.unixPermissions&&(F.dir=!0),F.dosPermissions&&16&F.dosPermissions&&(F.dir=!0),F.dir&&(x=C(x)),F.createFolders&&(D=m(x))&&I.call(this,D,!0);var R=w==="string"&&F.binary===!1&&F.base64===!1;S&&S.binary!==void 0||(F.binary=!R),(B instanceof u&&B.uncompressedSize===0||F.dir||!B||B.length===0)&&(F.base64=!1,F.binary=!0,B="",F.compression="STORE",w="string");var H=null;H=B instanceof u||B instanceof c?B:_.isNode&&_.isStream(B)?new p(x,B):a.prepareContent(x,B,F.binary,F.optimizedBinaryString,F.base64);var G=new h(x,H,F);this.files[x]=G}var s=o("./utf8"),a=o("./utils"),c=o("./stream/GenericWorker"),l=o("./stream/StreamHelper"),g=o("./defaults"),u=o("./compressedObject"),h=o("./zipObject"),d=o("./generate"),_=o("./nodejsUtils"),p=o("./nodejs/NodejsStreamInputAdapter"),m=function(x){x.slice(-1)==="/"&&(x=x.substring(0,x.length-1));var B=x.lastIndexOf("/");return 0<B?x.substring(0,B):""},C=function(x){return x.slice(-1)!=="/"&&(x+="/"),x},I=function(x,B){return B=B!==void 0?B:g.createFolders,x=C(x),this.files[x]||A.call(this,x,null,{dir:!0,createFolders:B}),this.files[x]};function f(x){return Object.prototype.toString.call(x)==="[object RegExp]"}var y={load:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},forEach:function(x){var B,S,D;for(B in this.files)D=this.files[B],(S=B.slice(this.root.length,B.length))&&B.slice(0,this.root.length)===this.root&&x(S,D)},filter:function(x){var B=[];return this.forEach(function(S,D){x(S,D)&&B.push(D)}),B},file:function(x,B,S){if(arguments.length!==1)return x=this.root+x,A.call(this,x,B,S),this;if(f(x)){var D=x;return this.filter(function(F,R){return!R.dir&&D.test(F)})}var w=this.files[this.root+x];return w&&!w.dir?w:null},folder:function(x){if(!x)return this;if(f(x))return this.filter(function(w,F){return F.dir&&x.test(w)});var B=this.root+x,S=I.call(this,B),D=this.clone();return D.root=S.name,D},remove:function(x){x=this.root+x;var B=this.files[x];if(B||(x.slice(-1)!=="/"&&(x+="/"),B=this.files[x]),B&&!B.dir)delete this.files[x];else for(var S=this.filter(function(w,F){return F.name.slice(0,x.length)===x}),D=0;D<S.length;D++)delete this.files[S[D].name];return this},generate:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},generateInternalStream:function(x){var B,S={};try{if((S=a.extend(x||{},{streamFiles:!1,compression:"STORE",compressionOptions:null,type:"",platform:"DOS",comment:null,mimeType:"application/zip",encodeFileName:s.utf8encode})).type=S.type.toLowerCase(),S.compression=S.compression.toUpperCase(),S.type==="binarystring"&&(S.type="string"),!S.type)throw new Error("No output type specified.");a.checkSupport(S.type),S.platform!=="darwin"&&S.platform!=="freebsd"&&S.platform!=="linux"&&S.platform!=="sunos"||(S.platform="UNIX"),S.platform==="win32"&&(S.platform="DOS");var D=S.comment||this.comment||"";B=d.generateWorker(this,S,D)}catch(w){(B=new c("error")).error(w)}return new l(B,S.type||"string",S.mimeType)},generateAsync:function(x,B){return this.generateInternalStream(x).accumulate(B)},generateNodeStream:function(x,B){return(x=x||{}).type||(x.type="nodebuffer"),this.generateInternalStream(x).toNodejsStream(B)}};i.exports=y},{"./compressedObject":2,"./defaults":5,"./generate":9,"./nodejs/NodejsStreamInputAdapter":12,"./nodejsUtils":14,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31,"./utils":32,"./zipObject":35}],16:[function(o,i,r){i.exports=o("stream")},{stream:void 0}],17:[function(o,i,r){var A=o("./DataReader");function s(a){A.call(this,a);for(var c=0;c<this.data.length;c++)a[c]=255&a[c]}o("../utils").inherits(s,A),s.prototype.byteAt=function(a){return this.data[this.zero+a]},s.prototype.lastIndexOfSignature=function(a){for(var c=a.charCodeAt(0),l=a.charCodeAt(1),g=a.charCodeAt(2),u=a.charCodeAt(3),h=this.length-4;0<=h;--h)if(this.data[h]===c&&this.data[h+1]===l&&this.data[h+2]===g&&this.data[h+3]===u)return h-this.zero;return-1},s.prototype.readAndCheckSignature=function(a){var c=a.charCodeAt(0),l=a.charCodeAt(1),g=a.charCodeAt(2),u=a.charCodeAt(3),h=this.readData(4);return c===h[0]&&l===h[1]&&g===h[2]&&u===h[3]},s.prototype.readData=function(a){if(this.checkOffset(a),a===0)return[];var c=this.data.slice(this.zero+this.index,this.zero+this.index+a);return this.index+=a,c},i.exports=s},{"../utils":32,"./DataReader":18}],18:[function(o,i,r){var A=o("../utils");function s(a){this.data=a,this.length=a.length,this.index=0,this.zero=0}s.prototype={checkOffset:function(a){this.checkIndex(this.index+a)},checkIndex:function(a){if(this.length<this.zero+a||a<0)throw new Error("End of data reached (data length = "+this.length+", asked index = "+a+"). Corrupted zip ?")},setIndex:function(a){this.checkIndex(a),this.index=a},skip:function(a){this.setIndex(this.index+a)},byteAt:function(){},readInt:function(a){var c,l=0;for(this.checkOffset(a),c=this.index+a-1;c>=this.index;c--)l=(l<<8)+this.byteAt(c);return this.index+=a,l},readString:function(a){return A.transformTo("string",this.readData(a))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var a=this.readInt(4);return new Date(Date.UTC(1980+(a>>25&127),(a>>21&15)-1,a>>16&31,a>>11&31,a>>5&63,(31&a)<<1))}},i.exports=s},{"../utils":32}],19:[function(o,i,r){var A=o("./Uint8ArrayReader");function s(a){A.call(this,a)}o("../utils").inherits(s,A),s.prototype.readData=function(a){this.checkOffset(a);var c=this.data.slice(this.zero+this.index,this.zero+this.index+a);return this.index+=a,c},i.exports=s},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(o,i,r){var A=o("./DataReader");function s(a){A.call(this,a)}o("../utils").inherits(s,A),s.prototype.byteAt=function(a){return this.data.charCodeAt(this.zero+a)},s.prototype.lastIndexOfSignature=function(a){return this.data.lastIndexOf(a)-this.zero},s.prototype.readAndCheckSignature=function(a){return a===this.readData(4)},s.prototype.readData=function(a){this.checkOffset(a);var c=this.data.slice(this.zero+this.index,this.zero+this.index+a);return this.index+=a,c},i.exports=s},{"../utils":32,"./DataReader":18}],21:[function(o,i,r){var A=o("./ArrayReader");function s(a){A.call(this,a)}o("../utils").inherits(s,A),s.prototype.readData=function(a){if(this.checkOffset(a),a===0)return new Uint8Array(0);var c=this.data.subarray(this.zero+this.index,this.zero+this.index+a);return this.index+=a,c},i.exports=s},{"../utils":32,"./ArrayReader":17}],22:[function(o,i,r){var A=o("../utils"),s=o("../support"),a=o("./ArrayReader"),c=o("./StringReader"),l=o("./NodeBufferReader"),g=o("./Uint8ArrayReader");i.exports=function(u){var h=A.getTypeOf(u);return A.checkSupport(h),h!=="string"||s.uint8array?h==="nodebuffer"?new l(u):s.uint8array?new g(A.transformTo("uint8array",u)):new a(A.transformTo("array",u)):new c(u)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(o,i,r){r.LOCAL_FILE_HEADER="PK",r.CENTRAL_FILE_HEADER="PK",r.CENTRAL_DIRECTORY_END="PK",r.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07",r.ZIP64_CENTRAL_DIRECTORY_END="PK",r.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(o,i,r){var A=o("./GenericWorker"),s=o("../utils");function a(c){A.call(this,"ConvertWorker to "+c),this.destType=c}s.inherits(a,A),a.prototype.processChunk=function(c){this.push({data:s.transformTo(this.destType,c.data),meta:c.meta})},i.exports=a},{"../utils":32,"./GenericWorker":28}],25:[function(o,i,r){var A=o("./GenericWorker"),s=o("../crc32");function a(){A.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}o("../utils").inherits(a,A),a.prototype.processChunk=function(c){this.streamInfo.crc32=s(c.data,this.streamInfo.crc32||0),this.push(c)},i.exports=a},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(o,i,r){var A=o("../utils"),s=o("./GenericWorker");function a(c){s.call(this,"DataLengthProbe for "+c),this.propName=c,this.withStreamInfo(c,0)}A.inherits(a,s),a.prototype.processChunk=function(c){if(c){var l=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=l+c.data.length}s.prototype.processChunk.call(this,c)},i.exports=a},{"../utils":32,"./GenericWorker":28}],27:[function(o,i,r){var A=o("../utils"),s=o("./GenericWorker");function a(c){s.call(this,"DataWorker");var l=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,c.then(function(g){l.dataIsReady=!0,l.data=g,l.max=g&&g.length||0,l.type=A.getTypeOf(g),l.isPaused||l._tickAndRepeat()},function(g){l.error(g)})}A.inherits(a,s),a.prototype.cleanUp=function(){s.prototype.cleanUp.call(this),this.data=null},a.prototype.resume=function(){return!!s.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,A.delay(this._tickAndRepeat,[],this)),!0)},a.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(A.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},a.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var c=null,l=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":c=this.data.substring(this.index,l);break;case"uint8array":c=this.data.subarray(this.index,l);break;case"array":case"nodebuffer":c=this.data.slice(this.index,l)}return this.index=l,this.push({data:c,meta:{percent:this.max?this.index/this.max*100:0}})},i.exports=a},{"../utils":32,"./GenericWorker":28}],28:[function(o,i,r){function A(s){this.name=s||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}A.prototype={push:function(s){this.emit("data",s)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(s){this.emit("error",s)}return!0},error:function(s){return!this.isFinished&&(this.isPaused?this.generatedError=s:(this.isFinished=!0,this.emit("error",s),this.previous&&this.previous.error(s),this.cleanUp()),!0)},on:function(s,a){return this._listeners[s].push(a),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(s,a){if(this._listeners[s])for(var c=0;c<this._listeners[s].length;c++)this._listeners[s][c].call(this,a)},pipe:function(s){return s.registerPrevious(this)},registerPrevious:function(s){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.streamInfo=s.streamInfo,this.mergeStreamInfo(),this.previous=s;var a=this;return s.on("data",function(c){a.processChunk(c)}),s.on("end",function(){a.end()}),s.on("error",function(c){a.error(c)}),this},pause:function(){return!this.isPaused&&!this.isFinished&&(this.isPaused=!0,this.previous&&this.previous.pause(),!0)},resume:function(){if(!this.isPaused||this.isFinished)return!1;var s=this.isPaused=!1;return this.generatedError&&(this.error(this.generatedError),s=!0),this.previous&&this.previous.resume(),!s},flush:function(){},processChunk:function(s){this.push(s)},withStreamInfo:function(s,a){return this.extraStreamInfo[s]=a,this.mergeStreamInfo(),this},mergeStreamInfo:function(){for(var s in this.extraStreamInfo)Object.prototype.hasOwnProperty.call(this.extraStreamInfo,s)&&(this.streamInfo[s]=this.extraStreamInfo[s])},lock:function(){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.isLocked=!0,this.previous&&this.previous.lock()},toString:function(){var s="Worker "+this.name;return this.previous?this.previous+" -> "+s:s}},i.exports=A},{}],29:[function(o,i,r){var A=o("../utils"),s=o("./ConvertWorker"),a=o("./GenericWorker"),c=o("../base64"),l=o("../support"),g=o("../external"),u=null;if(l.nodestream)try{u=o("../nodejs/NodejsStreamOutputAdapter")}catch{}function h(_,p){return new g.Promise(function(m,C){var I=[],f=_._internalType,y=_._outputType,x=_._mimeType;_.on("data",function(B,S){I.push(B),p&&p(S)}).on("error",function(B){I=[],C(B)}).on("end",function(){try{var B=(function(S,D,w){switch(S){case"blob":return A.newBlob(A.transformTo("arraybuffer",D),w);case"base64":return c.encode(D);default:return A.transformTo(S,D)}})(y,(function(S,D){var w,F=0,R=null,H=0;for(w=0;w<D.length;w++)H+=D[w].length;switch(S){case"string":return D.join("");case"array":return Array.prototype.concat.apply([],D);case"uint8array":for(R=new Uint8Array(H),w=0;w<D.length;w++)R.set(D[w],F),F+=D[w].length;return R;case"nodebuffer":return Buffer.concat(D);default:throw new Error("concat : unsupported type '"+S+"'")}})(f,I),x);m(B)}catch(S){C(S)}I=[]}).resume()})}function d(_,p,m){var C=p;switch(p){case"blob":case"arraybuffer":C="uint8array";break;case"base64":C="string"}try{this._internalType=C,this._outputType=p,this._mimeType=m,A.checkSupport(C),this._worker=_.pipe(new s(C)),_.lock()}catch(I){this._worker=new a("error"),this._worker.error(I)}}d.prototype={accumulate:function(_){return h(this,_)},on:function(_,p){var m=this;return _==="data"?this._worker.on(_,function(C){p.call(m,C.data,C.meta)}):this._worker.on(_,function(){A.delay(p,arguments,m)}),this},resume:function(){return A.delay(this._worker.resume,[],this._worker),this},pause:function(){return this._worker.pause(),this},toNodejsStream:function(_){if(A.checkSupport("nodestream"),this._outputType!=="nodebuffer")throw new Error(this._outputType+" is not supported by this method");return new u(this,{objectMode:this._outputType!=="nodebuffer"},_)}},i.exports=d},{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(o,i,r){if(r.base64=!0,r.array=!0,r.string=!0,r.arraybuffer=typeof ArrayBuffer<"u"&&typeof Uint8Array<"u",r.nodebuffer=typeof Buffer<"u",r.uint8array=typeof Uint8Array<"u",typeof ArrayBuffer>"u")r.blob=!1;else{var A=new ArrayBuffer(0);try{r.blob=new Blob([A],{type:"application/zip"}).size===0}catch{try{var s=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);s.append(A),r.blob=s.getBlob("application/zip").size===0}catch{r.blob=!1}}}try{r.nodestream=!!o("readable-stream").Readable}catch{r.nodestream=!1}},{"readable-stream":16}],31:[function(o,i,r){for(var A=o("./utils"),s=o("./support"),a=o("./nodejsUtils"),c=o("./stream/GenericWorker"),l=new Array(256),g=0;g<256;g++)l[g]=252<=g?6:248<=g?5:240<=g?4:224<=g?3:192<=g?2:1;l[254]=l[254]=1;function u(){c.call(this,"utf-8 decode"),this.leftOver=null}function h(){c.call(this,"utf-8 encode")}r.utf8encode=function(d){return s.nodebuffer?a.newBufferFrom(d,"utf-8"):(function(_){var p,m,C,I,f,y=_.length,x=0;for(I=0;I<y;I++)(64512&(m=_.charCodeAt(I)))==55296&&I+1<y&&(64512&(C=_.charCodeAt(I+1)))==56320&&(m=65536+(m-55296<<10)+(C-56320),I++),x+=m<128?1:m<2048?2:m<65536?3:4;for(p=s.uint8array?new Uint8Array(x):new Array(x),I=f=0;f<x;I++)(64512&(m=_.charCodeAt(I)))==55296&&I+1<y&&(64512&(C=_.charCodeAt(I+1)))==56320&&(m=65536+(m-55296<<10)+(C-56320),I++),m<128?p[f++]=m:(m<2048?p[f++]=192|m>>>6:(m<65536?p[f++]=224|m>>>12:(p[f++]=240|m>>>18,p[f++]=128|m>>>12&63),p[f++]=128|m>>>6&63),p[f++]=128|63&m);return p})(d)},r.utf8decode=function(d){return s.nodebuffer?A.transformTo("nodebuffer",d).toString("utf-8"):(function(_){var p,m,C,I,f=_.length,y=new Array(2*f);for(p=m=0;p<f;)if((C=_[p++])<128)y[m++]=C;else if(4<(I=l[C]))y[m++]=65533,p+=I-1;else{for(C&=I===2?31:I===3?15:7;1<I&&p<f;)C=C<<6|63&_[p++],I--;1<I?y[m++]=65533:C<65536?y[m++]=C:(C-=65536,y[m++]=55296|C>>10&1023,y[m++]=56320|1023&C)}return y.length!==m&&(y.subarray?y=y.subarray(0,m):y.length=m),A.applyFromCharCode(y)})(d=A.transformTo(s.uint8array?"uint8array":"array",d))},A.inherits(u,c),u.prototype.processChunk=function(d){var _=A.transformTo(s.uint8array?"uint8array":"array",d.data);if(this.leftOver&&this.leftOver.length){if(s.uint8array){var p=_;(_=new Uint8Array(p.length+this.leftOver.length)).set(this.leftOver,0),_.set(p,this.leftOver.length)}else _=this.leftOver.concat(_);this.leftOver=null}var m=(function(I,f){var y;for((f=f||I.length)>I.length&&(f=I.length),y=f-1;0<=y&&(192&I[y])==128;)y--;return y<0||y===0?f:y+l[I[y]]>f?y:f})(_),C=_;m!==_.length&&(s.uint8array?(C=_.subarray(0,m),this.leftOver=_.subarray(m,_.length)):(C=_.slice(0,m),this.leftOver=_.slice(m,_.length))),this.push({data:r.utf8decode(C),meta:d.meta})},u.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:r.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},r.Utf8DecodeWorker=u,A.inherits(h,c),h.prototype.processChunk=function(d){this.push({data:r.utf8encode(d.data),meta:d.meta})},r.Utf8EncodeWorker=h},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(o,i,r){var A=o("./support"),s=o("./base64"),a=o("./nodejsUtils"),c=o("./external");function l(p){return p}function g(p,m){for(var C=0;C<p.length;++C)m[C]=255&p.charCodeAt(C);return m}o("setimmediate"),r.newBlob=function(p,m){r.checkSupport("blob");try{return new Blob([p],{type:m})}catch{try{var C=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);return C.append(p),C.getBlob(m)}catch{throw new Error("Bug : can't construct the Blob.")}}};var u={stringifyByChunk:function(p,m,C){var I=[],f=0,y=p.length;if(y<=C)return String.fromCharCode.apply(null,p);for(;f<y;)m==="array"||m==="nodebuffer"?I.push(String.fromCharCode.apply(null,p.slice(f,Math.min(f+C,y)))):I.push(String.fromCharCode.apply(null,p.subarray(f,Math.min(f+C,y)))),f+=C;return I.join("")},stringifyByChar:function(p){for(var m="",C=0;C<p.length;C++)m+=String.fromCharCode(p[C]);return m},applyCanBeUsed:{uint8array:(function(){try{return A.uint8array&&String.fromCharCode.apply(null,new Uint8Array(1)).length===1}catch{return!1}})(),nodebuffer:(function(){try{return A.nodebuffer&&String.fromCharCode.apply(null,a.allocBuffer(1)).length===1}catch{return!1}})()}};function h(p){var m=65536,C=r.getTypeOf(p),I=!0;if(C==="uint8array"?I=u.applyCanBeUsed.uint8array:C==="nodebuffer"&&(I=u.applyCanBeUsed.nodebuffer),I)for(;1<m;)try{return u.stringifyByChunk(p,C,m)}catch{m=Math.floor(m/2)}return u.stringifyByChar(p)}function d(p,m){for(var C=0;C<p.length;C++)m[C]=p[C];return m}r.applyFromCharCode=h;var _={};_.string={string:l,array:function(p){return g(p,new Array(p.length))},arraybuffer:function(p){return _.string.uint8array(p).buffer},uint8array:function(p){return g(p,new Uint8Array(p.length))},nodebuffer:function(p){return g(p,a.allocBuffer(p.length))}},_.array={string:h,array:l,arraybuffer:function(p){return new Uint8Array(p).buffer},uint8array:function(p){return new Uint8Array(p)},nodebuffer:function(p){return a.newBufferFrom(p)}},_.arraybuffer={string:function(p){return h(new Uint8Array(p))},array:function(p){return d(new Uint8Array(p),new Array(p.byteLength))},arraybuffer:l,uint8array:function(p){return new Uint8Array(p)},nodebuffer:function(p){return a.newBufferFrom(new Uint8Array(p))}},_.uint8array={string:h,array:function(p){return d(p,new Array(p.length))},arraybuffer:function(p){return p.buffer},uint8array:l,nodebuffer:function(p){return a.newBufferFrom(p)}},_.nodebuffer={string:h,array:function(p){return d(p,new Array(p.length))},arraybuffer:function(p){return _.nodebuffer.uint8array(p).buffer},uint8array:function(p){return d(p,new Uint8Array(p.length))},nodebuffer:l},r.transformTo=function(p,m){if(m=m||"",!p)return m;r.checkSupport(p);var C=r.getTypeOf(m);return _[C][p](m)},r.resolve=function(p){for(var m=p.split("/"),C=[],I=0;I<m.length;I++){var f=m[I];f==="."||f===""&&I!==0&&I!==m.length-1||(f===".."?C.pop():C.push(f))}return C.join("/")},r.getTypeOf=function(p){return typeof p=="string"?"string":Object.prototype.toString.call(p)==="[object Array]"?"array":A.nodebuffer&&a.isBuffer(p)?"nodebuffer":A.uint8array&&p instanceof Uint8Array?"uint8array":A.arraybuffer&&p instanceof ArrayBuffer?"arraybuffer":void 0},r.checkSupport=function(p){if(!A[p.toLowerCase()])throw new Error(p+" is not supported by this platform")},r.MAX_VALUE_16BITS=65535,r.MAX_VALUE_32BITS=-1,r.pretty=function(p){var m,C,I="";for(C=0;C<(p||"").length;C++)I+="\\x"+((m=p.charCodeAt(C))<16?"0":"")+m.toString(16).toUpperCase();return I},r.delay=function(p,m,C){setImmediate(function(){p.apply(C||null,m||[])})},r.inherits=function(p,m){function C(){}C.prototype=m.prototype,p.prototype=new C},r.extend=function(){var p,m,C={};for(p=0;p<arguments.length;p++)for(m in arguments[p])Object.prototype.hasOwnProperty.call(arguments[p],m)&&C[m]===void 0&&(C[m]=arguments[p][m]);return C},r.prepareContent=function(p,m,C,I,f){return c.Promise.resolve(m).then(function(y){return A.blob&&(y instanceof Blob||["[object File]","[object Blob]"].indexOf(Object.prototype.toString.call(y))!==-1)&&typeof FileReader<"u"?new c.Promise(function(x,B){var S=new FileReader;S.onload=function(D){x(D.target.result)},S.onerror=function(D){B(D.target.error)},S.readAsArrayBuffer(y)}):y}).then(function(y){var x=r.getTypeOf(y);return x?(x==="arraybuffer"?y=r.transformTo("uint8array",y):x==="string"&&(f?y=s.decode(y):C&&I!==!0&&(y=(function(B){return g(B,A.uint8array?new Uint8Array(B.length):new Array(B.length))})(y))),y):c.Promise.reject(new Error("Can't read the data of '"+p+"'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?"))})}},{"./base64":1,"./external":6,"./nodejsUtils":14,"./support":30,setimmediate:54}],33:[function(o,i,r){var A=o("./reader/readerFor"),s=o("./utils"),a=o("./signature"),c=o("./zipEntry"),l=o("./support");function g(u){this.files=[],this.loadOptions=u}g.prototype={checkSignature:function(u){if(!this.reader.readAndCheckSignature(u)){this.reader.index-=4;var h=this.reader.readString(4);throw new Error("Corrupted zip or bug: unexpected signature ("+s.pretty(h)+", expected "+s.pretty(u)+")")}},isSignature:function(u,h){var d=this.reader.index;this.reader.setIndex(u);var _=this.reader.readString(4)===h;return this.reader.setIndex(d),_},readBlockEndOfCentral:function(){this.diskNumber=this.reader.readInt(2),this.diskWithCentralDirStart=this.reader.readInt(2),this.centralDirRecordsOnThisDisk=this.reader.readInt(2),this.centralDirRecords=this.reader.readInt(2),this.centralDirSize=this.reader.readInt(4),this.centralDirOffset=this.reader.readInt(4),this.zipCommentLength=this.reader.readInt(2);var u=this.reader.readData(this.zipCommentLength),h=l.uint8array?"uint8array":"array",d=s.transformTo(h,u);this.zipComment=this.loadOptions.decodeFileName(d)},readBlockZip64EndOfCentral:function(){this.zip64EndOfCentralSize=this.reader.readInt(8),this.reader.skip(4),this.diskNumber=this.reader.readInt(4),this.diskWithCentralDirStart=this.reader.readInt(4),this.centralDirRecordsOnThisDisk=this.reader.readInt(8),this.centralDirRecords=this.reader.readInt(8),this.centralDirSize=this.reader.readInt(8),this.centralDirOffset=this.reader.readInt(8),this.zip64ExtensibleData={};for(var u,h,d,_=this.zip64EndOfCentralSize-44;0<_;)u=this.reader.readInt(2),h=this.reader.readInt(4),d=this.reader.readData(h),this.zip64ExtensibleData[u]={id:u,length:h,value:d}},readBlockZip64EndOfCentralLocator:function(){if(this.diskWithZip64CentralDirStart=this.reader.readInt(4),this.relativeOffsetEndOfZip64CentralDir=this.reader.readInt(8),this.disksCount=this.reader.readInt(4),1<this.disksCount)throw new Error("Multi-volumes zip are not supported")},readLocalFiles:function(){var u,h;for(u=0;u<this.files.length;u++)h=this.files[u],this.reader.setIndex(h.localHeaderOffset),this.checkSignature(a.LOCAL_FILE_HEADER),h.readLocalPart(this.reader),h.handleUTF8(),h.processAttributes()},readCentralDir:function(){var u;for(this.reader.setIndex(this.centralDirOffset);this.reader.readAndCheckSignature(a.CENTRAL_FILE_HEADER);)(u=new c({zip64:this.zip64},this.loadOptions)).readCentralPart(this.reader),this.files.push(u);if(this.centralDirRecords!==this.files.length&&this.centralDirRecords!==0&&this.files.length===0)throw new Error("Corrupted zip or bug: expected "+this.centralDirRecords+" records in central dir, got "+this.files.length)},readEndOfCentral:function(){var u=this.reader.lastIndexOfSignature(a.CENTRAL_DIRECTORY_END);if(u<0)throw this.isSignature(0,a.LOCAL_FILE_HEADER)?new Error("Corrupted zip: can't find end of central directory"):new Error("Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html");this.reader.setIndex(u);var h=u;if(this.checkSignature(a.CENTRAL_DIRECTORY_END),this.readBlockEndOfCentral(),this.diskNumber===s.MAX_VALUE_16BITS||this.diskWithCentralDirStart===s.MAX_VALUE_16BITS||this.centralDirRecordsOnThisDisk===s.MAX_VALUE_16BITS||this.centralDirRecords===s.MAX_VALUE_16BITS||this.centralDirSize===s.MAX_VALUE_32BITS||this.centralDirOffset===s.MAX_VALUE_32BITS){if(this.zip64=!0,(u=this.reader.lastIndexOfSignature(a.ZIP64_CENTRAL_DIRECTORY_LOCATOR))<0)throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");if(this.reader.setIndex(u),this.checkSignature(a.ZIP64_CENTRAL_DIRECTORY_LOCATOR),this.readBlockZip64EndOfCentralLocator(),!this.isSignature(this.relativeOffsetEndOfZip64CentralDir,a.ZIP64_CENTRAL_DIRECTORY_END)&&(this.relativeOffsetEndOfZip64CentralDir=this.reader.lastIndexOfSignature(a.ZIP64_CENTRAL_DIRECTORY_END),this.relativeOffsetEndOfZip64CentralDir<0))throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir),this.checkSignature(a.ZIP64_CENTRAL_DIRECTORY_END),this.readBlockZip64EndOfCentral()}var d=this.centralDirOffset+this.centralDirSize;this.zip64&&(d+=20,d+=12+this.zip64EndOfCentralSize);var _=h-d;if(0<_)this.isSignature(h,a.CENTRAL_FILE_HEADER)||(this.reader.zero=_);else if(_<0)throw new Error("Corrupted zip: missing "+Math.abs(_)+" bytes.")},prepareReader:function(u){this.reader=A(u)},load:function(u){this.prepareReader(u),this.readEndOfCentral(),this.readCentralDir(),this.readLocalFiles()}},i.exports=g},{"./reader/readerFor":22,"./signature":23,"./support":30,"./utils":32,"./zipEntry":34}],34:[function(o,i,r){var A=o("./reader/readerFor"),s=o("./utils"),a=o("./compressedObject"),c=o("./crc32"),l=o("./utf8"),g=o("./compressions"),u=o("./support");function h(d,_){this.options=d,this.loadOptions=_}h.prototype={isEncrypted:function(){return(1&this.bitFlag)==1},useUTF8:function(){return(2048&this.bitFlag)==2048},readLocalPart:function(d){var _,p;if(d.skip(22),this.fileNameLength=d.readInt(2),p=d.readInt(2),this.fileName=d.readData(this.fileNameLength),d.skip(p),this.compressedSize===-1||this.uncompressedSize===-1)throw new Error("Bug or corrupted zip : didn't get enough information from the central directory (compressedSize === -1 || uncompressedSize === -1)");if((_=(function(m){for(var C in g)if(Object.prototype.hasOwnProperty.call(g,C)&&g[C].magic===m)return g[C];return null})(this.compressionMethod))===null)throw new Error("Corrupted zip : compression "+s.pretty(this.compressionMethod)+" unknown (inner file : "+s.transformTo("string",this.fileName)+")");this.decompressed=new a(this.compressedSize,this.uncompressedSize,this.crc32,_,d.readData(this.compressedSize))},readCentralPart:function(d){this.versionMadeBy=d.readInt(2),d.skip(2),this.bitFlag=d.readInt(2),this.compressionMethod=d.readString(2),this.date=d.readDate(),this.crc32=d.readInt(4),this.compressedSize=d.readInt(4),this.uncompressedSize=d.readInt(4);var _=d.readInt(2);if(this.extraFieldsLength=d.readInt(2),this.fileCommentLength=d.readInt(2),this.diskNumberStart=d.readInt(2),this.internalFileAttributes=d.readInt(2),this.externalFileAttributes=d.readInt(4),this.localHeaderOffset=d.readInt(4),this.isEncrypted())throw new Error("Encrypted zip are not supported");d.skip(_),this.readExtraFields(d),this.parseZIP64ExtraField(d),this.fileComment=d.readData(this.fileCommentLength)},processAttributes:function(){this.unixPermissions=null,this.dosPermissions=null;var d=this.versionMadeBy>>8;this.dir=!!(16&this.externalFileAttributes),d==0&&(this.dosPermissions=63&this.externalFileAttributes),d==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var d=A(this.extraFields[1].value);this.uncompressedSize===s.MAX_VALUE_32BITS&&(this.uncompressedSize=d.readInt(8)),this.compressedSize===s.MAX_VALUE_32BITS&&(this.compressedSize=d.readInt(8)),this.localHeaderOffset===s.MAX_VALUE_32BITS&&(this.localHeaderOffset=d.readInt(8)),this.diskNumberStart===s.MAX_VALUE_32BITS&&(this.diskNumberStart=d.readInt(4))}},readExtraFields:function(d){var _,p,m,C=d.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});d.index+4<C;)_=d.readInt(2),p=d.readInt(2),m=d.readData(p),this.extraFields[_]={id:_,length:p,value:m};d.setIndex(C)},handleUTF8:function(){var d=u.uint8array?"uint8array":"array";if(this.useUTF8())this.fileNameStr=l.utf8decode(this.fileName),this.fileCommentStr=l.utf8decode(this.fileComment);else{var _=this.findExtraFieldUnicodePath();if(_!==null)this.fileNameStr=_;else{var p=s.transformTo(d,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(p)}var m=this.findExtraFieldUnicodeComment();if(m!==null)this.fileCommentStr=m;else{var C=s.transformTo(d,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(C)}}},findExtraFieldUnicodePath:function(){var d=this.extraFields[28789];if(d){var _=A(d.value);return _.readInt(1)!==1||c(this.fileName)!==_.readInt(4)?null:l.utf8decode(_.readData(d.length-5))}return null},findExtraFieldUnicodeComment:function(){var d=this.extraFields[25461];if(d){var _=A(d.value);return _.readInt(1)!==1||c(this.fileComment)!==_.readInt(4)?null:l.utf8decode(_.readData(d.length-5))}return null}},i.exports=h},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(o,i,r){function A(_,p,m){this.name=_,this.dir=m.dir,this.date=m.date,this.comment=m.comment,this.unixPermissions=m.unixPermissions,this.dosPermissions=m.dosPermissions,this._data=p,this._dataBinary=m.binary,this.options={compression:m.compression,compressionOptions:m.compressionOptions}}var s=o("./stream/StreamHelper"),a=o("./stream/DataWorker"),c=o("./utf8"),l=o("./compressedObject"),g=o("./stream/GenericWorker");A.prototype={internalStream:function(_){var p=null,m="string";try{if(!_)throw new Error("No output type specified.");var C=(m=_.toLowerCase())==="string"||m==="text";m!=="binarystring"&&m!=="text"||(m="string"),p=this._decompressWorker();var I=!this._dataBinary;I&&!C&&(p=p.pipe(new c.Utf8EncodeWorker)),!I&&C&&(p=p.pipe(new c.Utf8DecodeWorker))}catch(f){(p=new g("error")).error(f)}return new s(p,m,"")},async:function(_,p){return this.internalStream(_).accumulate(p)},nodeStream:function(_,p){return this.internalStream(_||"nodebuffer").toNodejsStream(p)},_compressWorker:function(_,p){if(this._data instanceof l&&this._data.compression.magic===_.magic)return this._data.getCompressedWorker();var m=this._decompressWorker();return this._dataBinary||(m=m.pipe(new c.Utf8EncodeWorker)),l.createWorkerFrom(m,_,p)},_decompressWorker:function(){return this._data instanceof l?this._data.getContentWorker():this._data instanceof g?this._data:new a(this._data)}};for(var u=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],h=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},d=0;d<u.length;d++)A.prototype[u[d]]=h;i.exports=A},{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(o,i,r){(function(A){var s,a,c=A.MutationObserver||A.WebKitMutationObserver;if(c){var l=0,g=new c(_),u=A.document.createTextNode("");g.observe(u,{characterData:!0}),s=function(){u.data=l=++l%2}}else if(A.setImmediate||A.MessageChannel===void 0)s="document"in A&&"onreadystatechange"in A.document.createElement("script")?function(){var p=A.document.createElement("script");p.onreadystatechange=function(){_(),p.onreadystatechange=null,p.parentNode.removeChild(p),p=null},A.document.documentElement.appendChild(p)}:function(){setTimeout(_,0)};else{var h=new A.MessageChannel;h.port1.onmessage=_,s=function(){h.port2.postMessage(0)}}var d=[];function _(){var p,m;a=!0;for(var C=d.length;C;){for(m=d,d=[],p=-1;++p<C;)m[p]();C=d.length}a=!1}i.exports=function(p){d.push(p)!==1||a||s()}}).call(this,typeof cf<"u"?cf:typeof self<"u"?self:typeof window<"u"?window:{})},{}],37:[function(o,i,r){var A=o("immediate");function s(){}var a={},c=["REJECTED"],l=["FULFILLED"],g=["PENDING"];function u(C){if(typeof C!="function")throw new TypeError("resolver must be a function");this.state=g,this.queue=[],this.outcome=void 0,C!==s&&p(this,C)}function h(C,I,f){this.promise=C,typeof I=="function"&&(this.onFulfilled=I,this.callFulfilled=this.otherCallFulfilled),typeof f=="function"&&(this.onRejected=f,this.callRejected=this.otherCallRejected)}function d(C,I,f){A(function(){var y;try{y=I(f)}catch(x){return a.reject(C,x)}y===C?a.reject(C,new TypeError("Cannot resolve promise with itself")):a.resolve(C,y)})}function _(C){var I=C&&C.then;if(C&&(typeof C=="object"||typeof C=="function")&&typeof I=="function")return function(){I.apply(C,arguments)}}function p(C,I){var f=!1;function y(S){f||(f=!0,a.reject(C,S))}function x(S){f||(f=!0,a.resolve(C,S))}var B=m(function(){I(x,y)});B.status==="error"&&y(B.value)}function m(C,I){var f={};try{f.value=C(I),f.status="success"}catch(y){f.status="error",f.value=y}return f}(i.exports=u).prototype.finally=function(C){if(typeof C!="function")return this;var I=this.constructor;return this.then(function(f){return I.resolve(C()).then(function(){return f})},function(f){return I.resolve(C()).then(function(){throw f})})},u.prototype.catch=function(C){return this.then(null,C)},u.prototype.then=function(C,I){if(typeof C!="function"&&this.state===l||typeof I!="function"&&this.state===c)return this;var f=new this.constructor(s);return this.state!==g?d(f,this.state===l?C:I,this.outcome):this.queue.push(new h(f,C,I)),f},h.prototype.callFulfilled=function(C){a.resolve(this.promise,C)},h.prototype.otherCallFulfilled=function(C){d(this.promise,this.onFulfilled,C)},h.prototype.callRejected=function(C){a.reject(this.promise,C)},h.prototype.otherCallRejected=function(C){d(this.promise,this.onRejected,C)},a.resolve=function(C,I){var f=m(_,I);if(f.status==="error")return a.reject(C,f.value);var y=f.value;if(y)p(C,y);else{C.state=l,C.outcome=I;for(var x=-1,B=C.queue.length;++x<B;)C.queue[x].callFulfilled(I)}return C},a.reject=function(C,I){C.state=c,C.outcome=I;for(var f=-1,y=C.queue.length;++f<y;)C.queue[f].callRejected(I);return C},u.resolve=function(C){return C instanceof this?C:a.resolve(new this(s),C)},u.reject=function(C){var I=new this(s);return a.reject(I,C)},u.all=function(C){var I=this;if(Object.prototype.toString.call(C)!=="[object Array]")return this.reject(new TypeError("must be an array"));var f=C.length,y=!1;if(!f)return this.resolve([]);for(var x=new Array(f),B=0,S=-1,D=new this(s);++S<f;)w(C[S],S);return D;function w(F,R){I.resolve(F).then(function(H){x[R]=H,++B!==f||y||(y=!0,a.resolve(D,x))},function(H){y||(y=!0,a.reject(D,H))})}},u.race=function(C){var I=this;if(Object.prototype.toString.call(C)!=="[object Array]")return this.reject(new TypeError("must be an array"));var f=C.length,y=!1;if(!f)return this.resolve([]);for(var x=-1,B=new this(s);++x<f;)S=C[x],I.resolve(S).then(function(D){y||(y=!0,a.resolve(B,D))},function(D){y||(y=!0,a.reject(B,D))});var S;return B}},{immediate:36}],38:[function(o,i,r){var A={};(0,o("./lib/utils/common").assign)(A,o("./lib/deflate"),o("./lib/inflate"),o("./lib/zlib/constants")),i.exports=A},{"./lib/deflate":39,"./lib/inflate":40,"./lib/utils/common":41,"./lib/zlib/constants":44}],39:[function(o,i,r){var A=o("./zlib/deflate"),s=o("./utils/common"),a=o("./utils/strings"),c=o("./zlib/messages"),l=o("./zlib/zstream"),g=Object.prototype.toString,u=0,h=-1,d=0,_=8;function p(C){if(!(this instanceof p))return new p(C);this.options=s.assign({level:h,method:_,chunkSize:16384,windowBits:15,memLevel:8,strategy:d,to:""},C||{});var I=this.options;I.raw&&0<I.windowBits?I.windowBits=-I.windowBits:I.gzip&&0<I.windowBits&&I.windowBits<16&&(I.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new l,this.strm.avail_out=0;var f=A.deflateInit2(this.strm,I.level,I.method,I.windowBits,I.memLevel,I.strategy);if(f!==u)throw new Error(c[f]);if(I.header&&A.deflateSetHeader(this.strm,I.header),I.dictionary){var y;if(y=typeof I.dictionary=="string"?a.string2buf(I.dictionary):g.call(I.dictionary)==="[object ArrayBuffer]"?new Uint8Array(I.dictionary):I.dictionary,(f=A.deflateSetDictionary(this.strm,y))!==u)throw new Error(c[f]);this._dict_set=!0}}function m(C,I){var f=new p(I);if(f.push(C,!0),f.err)throw f.msg||c[f.err];return f.result}p.prototype.push=function(C,I){var f,y,x=this.strm,B=this.options.chunkSize;if(this.ended)return!1;y=I===~~I?I:I===!0?4:0,typeof C=="string"?x.input=a.string2buf(C):g.call(C)==="[object ArrayBuffer]"?x.input=new Uint8Array(C):x.input=C,x.next_in=0,x.avail_in=x.input.length;do{if(x.avail_out===0&&(x.output=new s.Buf8(B),x.next_out=0,x.avail_out=B),(f=A.deflate(x,y))!==1&&f!==u)return this.onEnd(f),!(this.ended=!0);x.avail_out!==0&&(x.avail_in!==0||y!==4&&y!==2)||(this.options.to==="string"?this.onData(a.buf2binstring(s.shrinkBuf(x.output,x.next_out))):this.onData(s.shrinkBuf(x.output,x.next_out)))}while((0<x.avail_in||x.avail_out===0)&&f!==1);return y===4?(f=A.deflateEnd(this.strm),this.onEnd(f),this.ended=!0,f===u):y!==2||(this.onEnd(u),!(x.avail_out=0))},p.prototype.onData=function(C){this.chunks.push(C)},p.prototype.onEnd=function(C){C===u&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=s.flattenChunks(this.chunks)),this.chunks=[],this.err=C,this.msg=this.strm.msg},r.Deflate=p,r.deflate=m,r.deflateRaw=function(C,I){return(I=I||{}).raw=!0,m(C,I)},r.gzip=function(C,I){return(I=I||{}).gzip=!0,m(C,I)}},{"./utils/common":41,"./utils/strings":42,"./zlib/deflate":46,"./zlib/messages":51,"./zlib/zstream":53}],40:[function(o,i,r){var A=o("./zlib/inflate"),s=o("./utils/common"),a=o("./utils/strings"),c=o("./zlib/constants"),l=o("./zlib/messages"),g=o("./zlib/zstream"),u=o("./zlib/gzheader"),h=Object.prototype.toString;function d(p){if(!(this instanceof d))return new d(p);this.options=s.assign({chunkSize:16384,windowBits:0,to:""},p||{});var m=this.options;m.raw&&0<=m.windowBits&&m.windowBits<16&&(m.windowBits=-m.windowBits,m.windowBits===0&&(m.windowBits=-15)),!(0<=m.windowBits&&m.windowBits<16)||p&&p.windowBits||(m.windowBits+=32),15<m.windowBits&&m.windowBits<48&&(15&m.windowBits)==0&&(m.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new g,this.strm.avail_out=0;var C=A.inflateInit2(this.strm,m.windowBits);if(C!==c.Z_OK)throw new Error(l[C]);this.header=new u,A.inflateGetHeader(this.strm,this.header)}function _(p,m){var C=new d(m);if(C.push(p,!0),C.err)throw C.msg||l[C.err];return C.result}d.prototype.push=function(p,m){var C,I,f,y,x,B,S=this.strm,D=this.options.chunkSize,w=this.options.dictionary,F=!1;if(this.ended)return!1;I=m===~~m?m:m===!0?c.Z_FINISH:c.Z_NO_FLUSH,typeof p=="string"?S.input=a.binstring2buf(p):h.call(p)==="[object ArrayBuffer]"?S.input=new Uint8Array(p):S.input=p,S.next_in=0,S.avail_in=S.input.length;do{if(S.avail_out===0&&(S.output=new s.Buf8(D),S.next_out=0,S.avail_out=D),(C=A.inflate(S,c.Z_NO_FLUSH))===c.Z_NEED_DICT&&w&&(B=typeof w=="string"?a.string2buf(w):h.call(w)==="[object ArrayBuffer]"?new Uint8Array(w):w,C=A.inflateSetDictionary(this.strm,B)),C===c.Z_BUF_ERROR&&F===!0&&(C=c.Z_OK,F=!1),C!==c.Z_STREAM_END&&C!==c.Z_OK)return this.onEnd(C),!(this.ended=!0);S.next_out&&(S.avail_out!==0&&C!==c.Z_STREAM_END&&(S.avail_in!==0||I!==c.Z_FINISH&&I!==c.Z_SYNC_FLUSH)||(this.options.to==="string"?(f=a.utf8border(S.output,S.next_out),y=S.next_out-f,x=a.buf2string(S.output,f),S.next_out=y,S.avail_out=D-y,y&&s.arraySet(S.output,S.output,f,y,0),this.onData(x)):this.onData(s.shrinkBuf(S.output,S.next_out)))),S.avail_in===0&&S.avail_out===0&&(F=!0)}while((0<S.avail_in||S.avail_out===0)&&C!==c.Z_STREAM_END);return C===c.Z_STREAM_END&&(I=c.Z_FINISH),I===c.Z_FINISH?(C=A.inflateEnd(this.strm),this.onEnd(C),this.ended=!0,C===c.Z_OK):I!==c.Z_SYNC_FLUSH||(this.onEnd(c.Z_OK),!(S.avail_out=0))},d.prototype.onData=function(p){this.chunks.push(p)},d.prototype.onEnd=function(p){p===c.Z_OK&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=s.flattenChunks(this.chunks)),this.chunks=[],this.err=p,this.msg=this.strm.msg},r.Inflate=d,r.inflate=_,r.inflateRaw=function(p,m){return(m=m||{}).raw=!0,_(p,m)},r.ungzip=_},{"./utils/common":41,"./utils/strings":42,"./zlib/constants":44,"./zlib/gzheader":47,"./zlib/inflate":49,"./zlib/messages":51,"./zlib/zstream":53}],41:[function(o,i,r){var A=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Int32Array<"u";r.assign=function(c){for(var l=Array.prototype.slice.call(arguments,1);l.length;){var g=l.shift();if(g){if(typeof g!="object")throw new TypeError(g+"must be non-object");for(var u in g)g.hasOwnProperty(u)&&(c[u]=g[u])}}return c},r.shrinkBuf=function(c,l){return c.length===l?c:c.subarray?c.subarray(0,l):(c.length=l,c)};var s={arraySet:function(c,l,g,u,h){if(l.subarray&&c.subarray)c.set(l.subarray(g,g+u),h);else for(var d=0;d<u;d++)c[h+d]=l[g+d]},flattenChunks:function(c){var l,g,u,h,d,_;for(l=u=0,g=c.length;l<g;l++)u+=c[l].length;for(_=new Uint8Array(u),l=h=0,g=c.length;l<g;l++)d=c[l],_.set(d,h),h+=d.length;return _}},a={arraySet:function(c,l,g,u,h){for(var d=0;d<u;d++)c[h+d]=l[g+d]},flattenChunks:function(c){return[].concat.apply([],c)}};r.setTyped=function(c){c?(r.Buf8=Uint8Array,r.Buf16=Uint16Array,r.Buf32=Int32Array,r.assign(r,s)):(r.Buf8=Array,r.Buf16=Array,r.Buf32=Array,r.assign(r,a))},r.setTyped(A)},{}],42:[function(o,i,r){var A=o("./common"),s=!0,a=!0;try{String.fromCharCode.apply(null,[0])}catch{s=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch{a=!1}for(var c=new A.Buf8(256),l=0;l<256;l++)c[l]=252<=l?6:248<=l?5:240<=l?4:224<=l?3:192<=l?2:1;function g(u,h){if(h<65537&&(u.subarray&&a||!u.subarray&&s))return String.fromCharCode.apply(null,A.shrinkBuf(u,h));for(var d="",_=0;_<h;_++)d+=String.fromCharCode(u[_]);return d}c[254]=c[254]=1,r.string2buf=function(u){var h,d,_,p,m,C=u.length,I=0;for(p=0;p<C;p++)(64512&(d=u.charCodeAt(p)))==55296&&p+1<C&&(64512&(_=u.charCodeAt(p+1)))==56320&&(d=65536+(d-55296<<10)+(_-56320),p++),I+=d<128?1:d<2048?2:d<65536?3:4;for(h=new A.Buf8(I),p=m=0;m<I;p++)(64512&(d=u.charCodeAt(p)))==55296&&p+1<C&&(64512&(_=u.charCodeAt(p+1)))==56320&&(d=65536+(d-55296<<10)+(_-56320),p++),d<128?h[m++]=d:(d<2048?h[m++]=192|d>>>6:(d<65536?h[m++]=224|d>>>12:(h[m++]=240|d>>>18,h[m++]=128|d>>>12&63),h[m++]=128|d>>>6&63),h[m++]=128|63&d);return h},r.buf2binstring=function(u){return g(u,u.length)},r.binstring2buf=function(u){for(var h=new A.Buf8(u.length),d=0,_=h.length;d<_;d++)h[d]=u.charCodeAt(d);return h},r.buf2string=function(u,h){var d,_,p,m,C=h||u.length,I=new Array(2*C);for(d=_=0;d<C;)if((p=u[d++])<128)I[_++]=p;else if(4<(m=c[p]))I[_++]=65533,d+=m-1;else{for(p&=m===2?31:m===3?15:7;1<m&&d<C;)p=p<<6|63&u[d++],m--;1<m?I[_++]=65533:p<65536?I[_++]=p:(p-=65536,I[_++]=55296|p>>10&1023,I[_++]=56320|1023&p)}return g(I,_)},r.utf8border=function(u,h){var d;for((h=h||u.length)>u.length&&(h=u.length),d=h-1;0<=d&&(192&u[d])==128;)d--;return d<0||d===0?h:d+c[u[d]]>h?d:h}},{"./common":41}],43:[function(o,i,r){i.exports=function(A,s,a,c){for(var l=65535&A|0,g=A>>>16&65535|0,u=0;a!==0;){for(a-=u=2e3<a?2e3:a;g=g+(l=l+s[c++]|0)|0,--u;);l%=65521,g%=65521}return l|g<<16|0}},{}],44:[function(o,i,r){i.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],45:[function(o,i,r){var A=(function(){for(var s,a=[],c=0;c<256;c++){s=c;for(var l=0;l<8;l++)s=1&s?3988292384^s>>>1:s>>>1;a[c]=s}return a})();i.exports=function(s,a,c,l){var g=A,u=l+c;s^=-1;for(var h=l;h<u;h++)s=s>>>8^g[255&(s^a[h])];return-1^s}},{}],46:[function(o,i,r){var A,s=o("../utils/common"),a=o("./trees"),c=o("./adler32"),l=o("./crc32"),g=o("./messages"),u=0,h=4,d=0,_=-2,p=-1,m=4,C=2,I=8,f=9,y=286,x=30,B=19,S=2*y+1,D=15,w=3,F=258,R=F+w+1,H=42,G=113,K=1,V=2,W=3,X=4;function ie(Ie,Ze){return Ie.msg=g[Ze],Ze}function se(Ie){return(Ie<<1)-(4<Ie?9:0)}function ee(Ie){for(var Ze=Ie.length;0<=--Ze;)Ie[Ze]=0}function oe(Ie){var Ze=Ie.state,Ke=Ze.pending;Ke>Ie.avail_out&&(Ke=Ie.avail_out),Ke!==0&&(s.arraySet(Ie.output,Ze.pending_buf,Ze.pending_out,Ke,Ie.next_out),Ie.next_out+=Ke,Ze.pending_out+=Ke,Ie.total_out+=Ke,Ie.avail_out-=Ke,Ze.pending-=Ke,Ze.pending===0&&(Ze.pending_out=0))}function ae(Ie,Ze){a._tr_flush_block(Ie,0<=Ie.block_start?Ie.block_start:-1,Ie.strstart-Ie.block_start,Ze),Ie.block_start=Ie.strstart,oe(Ie.strm)}function re(Ie,Ze){Ie.pending_buf[Ie.pending++]=Ze}function le(Ie,Ze){Ie.pending_buf[Ie.pending++]=Ze>>>8&255,Ie.pending_buf[Ie.pending++]=255&Ze}function fe(Ie,Ze){var Ke,Ye,qe=Ie.max_chain_length,Le=Ie.strstart,Se=Ie.prev_length,ve=Ie.nice_match,Pe=Ie.strstart>Ie.w_size-R?Ie.strstart-(Ie.w_size-R):0,ze=Ie.window,Xe=Ie.w_mask,st=Ie.prev,ct=Ie.strstart+F,ut=ze[Le+Se-1],lt=ze[Le+Se];Ie.prev_length>=Ie.good_match&&(qe>>=2),ve>Ie.lookahead&&(ve=Ie.lookahead);do if(ze[(Ke=Ze)+Se]===lt&&ze[Ke+Se-1]===ut&&ze[Ke]===ze[Le]&&ze[++Ke]===ze[Le+1]){Le+=2,Ke++;do;while(ze[++Le]===ze[++Ke]&&ze[++Le]===ze[++Ke]&&ze[++Le]===ze[++Ke]&&ze[++Le]===ze[++Ke]&&ze[++Le]===ze[++Ke]&&ze[++Le]===ze[++Ke]&&ze[++Le]===ze[++Ke]&&ze[++Le]===ze[++Ke]&&Le<ct);if(Ye=F-(ct-Le),Le=ct-F,Se<Ye){if(Ie.match_start=Ze,ve<=(Se=Ye))break;ut=ze[Le+Se-1],lt=ze[Le+Se]}}while((Ze=st[Ze&Xe])>Pe&&--qe!=0);return Se<=Ie.lookahead?Se:Ie.lookahead}function ye(Ie){var Ze,Ke,Ye,qe,Le,Se,ve,Pe,ze,Xe,st=Ie.w_size;do{if(qe=Ie.window_size-Ie.lookahead-Ie.strstart,Ie.strstart>=st+(st-R)){for(s.arraySet(Ie.window,Ie.window,st,st,0),Ie.match_start-=st,Ie.strstart-=st,Ie.block_start-=st,Ze=Ke=Ie.hash_size;Ye=Ie.head[--Ze],Ie.head[Ze]=st<=Ye?Ye-st:0,--Ke;);for(Ze=Ke=st;Ye=Ie.prev[--Ze],Ie.prev[Ze]=st<=Ye?Ye-st:0,--Ke;);qe+=st}if(Ie.strm.avail_in===0)break;if(Se=Ie.strm,ve=Ie.window,Pe=Ie.strstart+Ie.lookahead,ze=qe,Xe=void 0,Xe=Se.avail_in,ze<Xe&&(Xe=ze),Ke=Xe===0?0:(Se.avail_in-=Xe,s.arraySet(ve,Se.input,Se.next_in,Xe,Pe),Se.state.wrap===1?Se.adler=c(Se.adler,ve,Xe,Pe):Se.state.wrap===2&&(Se.adler=l(Se.adler,ve,Xe,Pe)),Se.next_in+=Xe,Se.total_in+=Xe,Xe),Ie.lookahead+=Ke,Ie.lookahead+Ie.insert>=w)for(Le=Ie.strstart-Ie.insert,Ie.ins_h=Ie.window[Le],Ie.ins_h=(Ie.ins_h<<Ie.hash_shift^Ie.window[Le+1])&Ie.hash_mask;Ie.insert&&(Ie.ins_h=(Ie.ins_h<<Ie.hash_shift^Ie.window[Le+w-1])&Ie.hash_mask,Ie.prev[Le&Ie.w_mask]=Ie.head[Ie.ins_h],Ie.head[Ie.ins_h]=Le,Le++,Ie.insert--,!(Ie.lookahead+Ie.insert<w)););}while(Ie.lookahead<R&&Ie.strm.avail_in!==0)}function be(Ie,Ze){for(var Ke,Ye;;){if(Ie.lookahead<R){if(ye(Ie),Ie.lookahead<R&&Ze===u)return K;if(Ie.lookahead===0)break}if(Ke=0,Ie.lookahead>=w&&(Ie.ins_h=(Ie.ins_h<<Ie.hash_shift^Ie.window[Ie.strstart+w-1])&Ie.hash_mask,Ke=Ie.prev[Ie.strstart&Ie.w_mask]=Ie.head[Ie.ins_h],Ie.head[Ie.ins_h]=Ie.strstart),Ke!==0&&Ie.strstart-Ke<=Ie.w_size-R&&(Ie.match_length=fe(Ie,Ke)),Ie.match_length>=w)if(Ye=a._tr_tally(Ie,Ie.strstart-Ie.match_start,Ie.match_length-w),Ie.lookahead-=Ie.match_length,Ie.match_length<=Ie.max_lazy_match&&Ie.lookahead>=w){for(Ie.match_length--;Ie.strstart++,Ie.ins_h=(Ie.ins_h<<Ie.hash_shift^Ie.window[Ie.strstart+w-1])&Ie.hash_mask,Ke=Ie.prev[Ie.strstart&Ie.w_mask]=Ie.head[Ie.ins_h],Ie.head[Ie.ins_h]=Ie.strstart,--Ie.match_length!=0;);Ie.strstart++}else Ie.strstart+=Ie.match_length,Ie.match_length=0,Ie.ins_h=Ie.window[Ie.strstart],Ie.ins_h=(Ie.ins_h<<Ie.hash_shift^Ie.window[Ie.strstart+1])&Ie.hash_mask;else Ye=a._tr_tally(Ie,0,Ie.window[Ie.strstart]),Ie.lookahead--,Ie.strstart++;if(Ye&&(ae(Ie,!1),Ie.strm.avail_out===0))return K}return Ie.insert=Ie.strstart<w-1?Ie.strstart:w-1,Ze===h?(ae(Ie,!0),Ie.strm.avail_out===0?W:X):Ie.last_lit&&(ae(Ie,!1),Ie.strm.avail_out===0)?K:V}function ue(Ie,Ze){for(var Ke,Ye,qe;;){if(Ie.lookahead<R){if(ye(Ie),Ie.lookahead<R&&Ze===u)return K;if(Ie.lookahead===0)break}if(Ke=0,Ie.lookahead>=w&&(Ie.ins_h=(Ie.ins_h<<Ie.hash_shift^Ie.window[Ie.strstart+w-1])&Ie.hash_mask,Ke=Ie.prev[Ie.strstart&Ie.w_mask]=Ie.head[Ie.ins_h],Ie.head[Ie.ins_h]=Ie.strstart),Ie.prev_length=Ie.match_length,Ie.prev_match=Ie.match_start,Ie.match_length=w-1,Ke!==0&&Ie.prev_length<Ie.max_lazy_match&&Ie.strstart-Ke<=Ie.w_size-R&&(Ie.match_length=fe(Ie,Ke),Ie.match_length<=5&&(Ie.strategy===1||Ie.match_length===w&&4096<Ie.strstart-Ie.match_start)&&(Ie.match_length=w-1)),Ie.prev_length>=w&&Ie.match_length<=Ie.prev_length){for(qe=Ie.strstart+Ie.lookahead-w,Ye=a._tr_tally(Ie,Ie.strstart-1-Ie.prev_match,Ie.prev_length-w),Ie.lookahead-=Ie.prev_length-1,Ie.prev_length-=2;++Ie.strstart<=qe&&(Ie.ins_h=(Ie.ins_h<<Ie.hash_shift^Ie.window[Ie.strstart+w-1])&Ie.hash_mask,Ke=Ie.prev[Ie.strstart&Ie.w_mask]=Ie.head[Ie.ins_h],Ie.head[Ie.ins_h]=Ie.strstart),--Ie.prev_length!=0;);if(Ie.match_available=0,Ie.match_length=w-1,Ie.strstart++,Ye&&(ae(Ie,!1),Ie.strm.avail_out===0))return K}else if(Ie.match_available){if((Ye=a._tr_tally(Ie,0,Ie.window[Ie.strstart-1]))&&ae(Ie,!1),Ie.strstart++,Ie.lookahead--,Ie.strm.avail_out===0)return K}else Ie.match_available=1,Ie.strstart++,Ie.lookahead--}return Ie.match_available&&(Ye=a._tr_tally(Ie,0,Ie.window[Ie.strstart-1]),Ie.match_available=0),Ie.insert=Ie.strstart<w-1?Ie.strstart:w-1,Ze===h?(ae(Ie,!0),Ie.strm.avail_out===0?W:X):Ie.last_lit&&(ae(Ie,!1),Ie.strm.avail_out===0)?K:V}function Be(Ie,Ze,Ke,Ye,qe){this.good_length=Ie,this.max_lazy=Ze,this.nice_length=Ke,this.max_chain=Ye,this.func=qe}function pe(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=I,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new s.Buf16(2*S),this.dyn_dtree=new s.Buf16(2*(2*x+1)),this.bl_tree=new s.Buf16(2*(2*B+1)),ee(this.dyn_ltree),ee(this.dyn_dtree),ee(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new s.Buf16(D+1),this.heap=new s.Buf16(2*y+1),ee(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new s.Buf16(2*y+1),ee(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function Ge(Ie){var Ze;return Ie&&Ie.state?(Ie.total_in=Ie.total_out=0,Ie.data_type=C,(Ze=Ie.state).pending=0,Ze.pending_out=0,Ze.wrap<0&&(Ze.wrap=-Ze.wrap),Ze.status=Ze.wrap?H:G,Ie.adler=Ze.wrap===2?0:1,Ze.last_flush=u,a._tr_init(Ze),d):ie(Ie,_)}function Je(Ie){var Ze=Ge(Ie);return Ze===d&&(function(Ke){Ke.window_size=2*Ke.w_size,ee(Ke.head),Ke.max_lazy_match=A[Ke.level].max_lazy,Ke.good_match=A[Ke.level].good_length,Ke.nice_match=A[Ke.level].nice_length,Ke.max_chain_length=A[Ke.level].max_chain,Ke.strstart=0,Ke.block_start=0,Ke.lookahead=0,Ke.insert=0,Ke.match_length=Ke.prev_length=w-1,Ke.match_available=0,Ke.ins_h=0})(Ie.state),Ze}function nt(Ie,Ze,Ke,Ye,qe,Le){if(!Ie)return _;var Se=1;if(Ze===p&&(Ze=6),Ye<0?(Se=0,Ye=-Ye):15<Ye&&(Se=2,Ye-=16),qe<1||f<qe||Ke!==I||Ye<8||15<Ye||Ze<0||9<Ze||Le<0||m<Le)return ie(Ie,_);Ye===8&&(Ye=9);var ve=new pe;return(Ie.state=ve).strm=Ie,ve.wrap=Se,ve.gzhead=null,ve.w_bits=Ye,ve.w_size=1<<ve.w_bits,ve.w_mask=ve.w_size-1,ve.hash_bits=qe+7,ve.hash_size=1<<ve.hash_bits,ve.hash_mask=ve.hash_size-1,ve.hash_shift=~~((ve.hash_bits+w-1)/w),ve.window=new s.Buf8(2*ve.w_size),ve.head=new s.Buf16(ve.hash_size),ve.prev=new s.Buf16(ve.w_size),ve.lit_bufsize=1<<qe+6,ve.pending_buf_size=4*ve.lit_bufsize,ve.pending_buf=new s.Buf8(ve.pending_buf_size),ve.d_buf=1*ve.lit_bufsize,ve.l_buf=3*ve.lit_bufsize,ve.level=Ze,ve.strategy=Le,ve.method=Ke,Je(Ie)}A=[new Be(0,0,0,0,function(Ie,Ze){var Ke=65535;for(Ke>Ie.pending_buf_size-5&&(Ke=Ie.pending_buf_size-5);;){if(Ie.lookahead<=1){if(ye(Ie),Ie.lookahead===0&&Ze===u)return K;if(Ie.lookahead===0)break}Ie.strstart+=Ie.lookahead,Ie.lookahead=0;var Ye=Ie.block_start+Ke;if((Ie.strstart===0||Ie.strstart>=Ye)&&(Ie.lookahead=Ie.strstart-Ye,Ie.strstart=Ye,ae(Ie,!1),Ie.strm.avail_out===0)||Ie.strstart-Ie.block_start>=Ie.w_size-R&&(ae(Ie,!1),Ie.strm.avail_out===0))return K}return Ie.insert=0,Ze===h?(ae(Ie,!0),Ie.strm.avail_out===0?W:X):(Ie.strstart>Ie.block_start&&(ae(Ie,!1),Ie.strm.avail_out),K)}),new Be(4,4,8,4,be),new Be(4,5,16,8,be),new Be(4,6,32,32,be),new Be(4,4,16,16,ue),new Be(8,16,32,32,ue),new Be(8,16,128,128,ue),new Be(8,32,128,256,ue),new Be(32,128,258,1024,ue),new Be(32,258,258,4096,ue)],r.deflateInit=function(Ie,Ze){return nt(Ie,Ze,I,15,8,0)},r.deflateInit2=nt,r.deflateReset=Je,r.deflateResetKeep=Ge,r.deflateSetHeader=function(Ie,Ze){return Ie&&Ie.state?Ie.state.wrap!==2?_:(Ie.state.gzhead=Ze,d):_},r.deflate=function(Ie,Ze){var Ke,Ye,qe,Le;if(!Ie||!Ie.state||5<Ze||Ze<0)return Ie?ie(Ie,_):_;if(Ye=Ie.state,!Ie.output||!Ie.input&&Ie.avail_in!==0||Ye.status===666&&Ze!==h)return ie(Ie,Ie.avail_out===0?-5:_);if(Ye.strm=Ie,Ke=Ye.last_flush,Ye.last_flush=Ze,Ye.status===H)if(Ye.wrap===2)Ie.adler=0,re(Ye,31),re(Ye,139),re(Ye,8),Ye.gzhead?(re(Ye,(Ye.gzhead.text?1:0)+(Ye.gzhead.hcrc?2:0)+(Ye.gzhead.extra?4:0)+(Ye.gzhead.name?8:0)+(Ye.gzhead.comment?16:0)),re(Ye,255&Ye.gzhead.time),re(Ye,Ye.gzhead.time>>8&255),re(Ye,Ye.gzhead.time>>16&255),re(Ye,Ye.gzhead.time>>24&255),re(Ye,Ye.level===9?2:2<=Ye.strategy||Ye.level<2?4:0),re(Ye,255&Ye.gzhead.os),Ye.gzhead.extra&&Ye.gzhead.extra.length&&(re(Ye,255&Ye.gzhead.extra.length),re(Ye,Ye.gzhead.extra.length>>8&255)),Ye.gzhead.hcrc&&(Ie.adler=l(Ie.adler,Ye.pending_buf,Ye.pending,0)),Ye.gzindex=0,Ye.status=69):(re(Ye,0),re(Ye,0),re(Ye,0),re(Ye,0),re(Ye,0),re(Ye,Ye.level===9?2:2<=Ye.strategy||Ye.level<2?4:0),re(Ye,3),Ye.status=G);else{var Se=I+(Ye.w_bits-8<<4)<<8;Se|=(2<=Ye.strategy||Ye.level<2?0:Ye.level<6?1:Ye.level===6?2:3)<<6,Ye.strstart!==0&&(Se|=32),Se+=31-Se%31,Ye.status=G,le(Ye,Se),Ye.strstart!==0&&(le(Ye,Ie.adler>>>16),le(Ye,65535&Ie.adler)),Ie.adler=1}if(Ye.status===69)if(Ye.gzhead.extra){for(qe=Ye.pending;Ye.gzindex<(65535&Ye.gzhead.extra.length)&&(Ye.pending!==Ye.pending_buf_size||(Ye.gzhead.hcrc&&Ye.pending>qe&&(Ie.adler=l(Ie.adler,Ye.pending_buf,Ye.pending-qe,qe)),oe(Ie),qe=Ye.pending,Ye.pending!==Ye.pending_buf_size));)re(Ye,255&Ye.gzhead.extra[Ye.gzindex]),Ye.gzindex++;Ye.gzhead.hcrc&&Ye.pending>qe&&(Ie.adler=l(Ie.adler,Ye.pending_buf,Ye.pending-qe,qe)),Ye.gzindex===Ye.gzhead.extra.length&&(Ye.gzindex=0,Ye.status=73)}else Ye.status=73;if(Ye.status===73)if(Ye.gzhead.name){qe=Ye.pending;do{if(Ye.pending===Ye.pending_buf_size&&(Ye.gzhead.hcrc&&Ye.pending>qe&&(Ie.adler=l(Ie.adler,Ye.pending_buf,Ye.pending-qe,qe)),oe(Ie),qe=Ye.pending,Ye.pending===Ye.pending_buf_size)){Le=1;break}Le=Ye.gzindex<Ye.gzhead.name.length?255&Ye.gzhead.name.charCodeAt(Ye.gzindex++):0,re(Ye,Le)}while(Le!==0);Ye.gzhead.hcrc&&Ye.pending>qe&&(Ie.adler=l(Ie.adler,Ye.pending_buf,Ye.pending-qe,qe)),Le===0&&(Ye.gzindex=0,Ye.status=91)}else Ye.status=91;if(Ye.status===91)if(Ye.gzhead.comment){qe=Ye.pending;do{if(Ye.pending===Ye.pending_buf_size&&(Ye.gzhead.hcrc&&Ye.pending>qe&&(Ie.adler=l(Ie.adler,Ye.pending_buf,Ye.pending-qe,qe)),oe(Ie),qe=Ye.pending,Ye.pending===Ye.pending_buf_size)){Le=1;break}Le=Ye.gzindex<Ye.gzhead.comment.length?255&Ye.gzhead.comment.charCodeAt(Ye.gzindex++):0,re(Ye,Le)}while(Le!==0);Ye.gzhead.hcrc&&Ye.pending>qe&&(Ie.adler=l(Ie.adler,Ye.pending_buf,Ye.pending-qe,qe)),Le===0&&(Ye.status=103)}else Ye.status=103;if(Ye.status===103&&(Ye.gzhead.hcrc?(Ye.pending+2>Ye.pending_buf_size&&oe(Ie),Ye.pending+2<=Ye.pending_buf_size&&(re(Ye,255&Ie.adler),re(Ye,Ie.adler>>8&255),Ie.adler=0,Ye.status=G)):Ye.status=G),Ye.pending!==0){if(oe(Ie),Ie.avail_out===0)return Ye.last_flush=-1,d}else if(Ie.avail_in===0&&se(Ze)<=se(Ke)&&Ze!==h)return ie(Ie,-5);if(Ye.status===666&&Ie.avail_in!==0)return ie(Ie,-5);if(Ie.avail_in!==0||Ye.lookahead!==0||Ze!==u&&Ye.status!==666){var ve=Ye.strategy===2?(function(Pe,ze){for(var Xe;;){if(Pe.lookahead===0&&(ye(Pe),Pe.lookahead===0)){if(ze===u)return K;break}if(Pe.match_length=0,Xe=a._tr_tally(Pe,0,Pe.window[Pe.strstart]),Pe.lookahead--,Pe.strstart++,Xe&&(ae(Pe,!1),Pe.strm.avail_out===0))return K}return Pe.insert=0,ze===h?(ae(Pe,!0),Pe.strm.avail_out===0?W:X):Pe.last_lit&&(ae(Pe,!1),Pe.strm.avail_out===0)?K:V})(Ye,Ze):Ye.strategy===3?(function(Pe,ze){for(var Xe,st,ct,ut,lt=Pe.window;;){if(Pe.lookahead<=F){if(ye(Pe),Pe.lookahead<=F&&ze===u)return K;if(Pe.lookahead===0)break}if(Pe.match_length=0,Pe.lookahead>=w&&0<Pe.strstart&&(st=lt[ct=Pe.strstart-1])===lt[++ct]&&st===lt[++ct]&&st===lt[++ct]){ut=Pe.strstart+F;do;while(st===lt[++ct]&&st===lt[++ct]&&st===lt[++ct]&&st===lt[++ct]&&st===lt[++ct]&&st===lt[++ct]&&st===lt[++ct]&&st===lt[++ct]&&ct<ut);Pe.match_length=F-(ut-ct),Pe.match_length>Pe.lookahead&&(Pe.match_length=Pe.lookahead)}if(Pe.match_length>=w?(Xe=a._tr_tally(Pe,1,Pe.match_length-w),Pe.lookahead-=Pe.match_length,Pe.strstart+=Pe.match_length,Pe.match_length=0):(Xe=a._tr_tally(Pe,0,Pe.window[Pe.strstart]),Pe.lookahead--,Pe.strstart++),Xe&&(ae(Pe,!1),Pe.strm.avail_out===0))return K}return Pe.insert=0,ze===h?(ae(Pe,!0),Pe.strm.avail_out===0?W:X):Pe.last_lit&&(ae(Pe,!1),Pe.strm.avail_out===0)?K:V})(Ye,Ze):A[Ye.level].func(Ye,Ze);if(ve!==W&&ve!==X||(Ye.status=666),ve===K||ve===W)return Ie.avail_out===0&&(Ye.last_flush=-1),d;if(ve===V&&(Ze===1?a._tr_align(Ye):Ze!==5&&(a._tr_stored_block(Ye,0,0,!1),Ze===3&&(ee(Ye.head),Ye.lookahead===0&&(Ye.strstart=0,Ye.block_start=0,Ye.insert=0))),oe(Ie),Ie.avail_out===0))return Ye.last_flush=-1,d}return Ze!==h?d:Ye.wrap<=0?1:(Ye.wrap===2?(re(Ye,255&Ie.adler),re(Ye,Ie.adler>>8&255),re(Ye,Ie.adler>>16&255),re(Ye,Ie.adler>>24&255),re(Ye,255&Ie.total_in),re(Ye,Ie.total_in>>8&255),re(Ye,Ie.total_in>>16&255),re(Ye,Ie.total_in>>24&255)):(le(Ye,Ie.adler>>>16),le(Ye,65535&Ie.adler)),oe(Ie),0<Ye.wrap&&(Ye.wrap=-Ye.wrap),Ye.pending!==0?d:1)},r.deflateEnd=function(Ie){var Ze;return Ie&&Ie.state?(Ze=Ie.state.status)!==H&&Ze!==69&&Ze!==73&&Ze!==91&&Ze!==103&&Ze!==G&&Ze!==666?ie(Ie,_):(Ie.state=null,Ze===G?ie(Ie,-3):d):_},r.deflateSetDictionary=function(Ie,Ze){var Ke,Ye,qe,Le,Se,ve,Pe,ze,Xe=Ze.length;if(!Ie||!Ie.state||(Le=(Ke=Ie.state).wrap)===2||Le===1&&Ke.status!==H||Ke.lookahead)return _;for(Le===1&&(Ie.adler=c(Ie.adler,Ze,Xe,0)),Ke.wrap=0,Xe>=Ke.w_size&&(Le===0&&(ee(Ke.head),Ke.strstart=0,Ke.block_start=0,Ke.insert=0),ze=new s.Buf8(Ke.w_size),s.arraySet(ze,Ze,Xe-Ke.w_size,Ke.w_size,0),Ze=ze,Xe=Ke.w_size),Se=Ie.avail_in,ve=Ie.next_in,Pe=Ie.input,Ie.avail_in=Xe,Ie.next_in=0,Ie.input=Ze,ye(Ke);Ke.lookahead>=w;){for(Ye=Ke.strstart,qe=Ke.lookahead-(w-1);Ke.ins_h=(Ke.ins_h<<Ke.hash_shift^Ke.window[Ye+w-1])&Ke.hash_mask,Ke.prev[Ye&Ke.w_mask]=Ke.head[Ke.ins_h],Ke.head[Ke.ins_h]=Ye,Ye++,--qe;);Ke.strstart=Ye,Ke.lookahead=w-1,ye(Ke)}return Ke.strstart+=Ke.lookahead,Ke.block_start=Ke.strstart,Ke.insert=Ke.lookahead,Ke.lookahead=0,Ke.match_length=Ke.prev_length=w-1,Ke.match_available=0,Ie.next_in=ve,Ie.input=Pe,Ie.avail_in=Se,Ke.wrap=Le,d},r.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./messages":51,"./trees":52}],47:[function(o,i,r){i.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],48:[function(o,i,r){i.exports=function(A,s){var a,c,l,g,u,h,d,_,p,m,C,I,f,y,x,B,S,D,w,F,R,H,G,K,V;a=A.state,c=A.next_in,K=A.input,l=c+(A.avail_in-5),g=A.next_out,V=A.output,u=g-(s-A.avail_out),h=g+(A.avail_out-257),d=a.dmax,_=a.wsize,p=a.whave,m=a.wnext,C=a.window,I=a.hold,f=a.bits,y=a.lencode,x=a.distcode,B=(1<<a.lenbits)-1,S=(1<<a.distbits)-1;e:do{f<15&&(I+=K[c++]<<f,f+=8,I+=K[c++]<<f,f+=8),D=y[I&B];t:for(;;){if(I>>>=w=D>>>24,f-=w,(w=D>>>16&255)===0)V[g++]=65535&D;else{if(!(16&w)){if((64&w)==0){D=y[(65535&D)+(I&(1<<w)-1)];continue t}if(32&w){a.mode=12;break e}A.msg="invalid literal/length code",a.mode=30;break e}F=65535&D,(w&=15)&&(f<w&&(I+=K[c++]<<f,f+=8),F+=I&(1<<w)-1,I>>>=w,f-=w),f<15&&(I+=K[c++]<<f,f+=8,I+=K[c++]<<f,f+=8),D=x[I&S];n:for(;;){if(I>>>=w=D>>>24,f-=w,!(16&(w=D>>>16&255))){if((64&w)==0){D=x[(65535&D)+(I&(1<<w)-1)];continue n}A.msg="invalid distance code",a.mode=30;break e}if(R=65535&D,f<(w&=15)&&(I+=K[c++]<<f,(f+=8)<w&&(I+=K[c++]<<f,f+=8)),d<(R+=I&(1<<w)-1)){A.msg="invalid distance too far back",a.mode=30;break e}if(I>>>=w,f-=w,(w=g-u)<R){if(p<(w=R-w)&&a.sane){A.msg="invalid distance too far back",a.mode=30;break e}if(G=C,(H=0)===m){if(H+=_-w,w<F){for(F-=w;V[g++]=C[H++],--w;);H=g-R,G=V}}else if(m<w){if(H+=_+m-w,(w-=m)<F){for(F-=w;V[g++]=C[H++],--w;);if(H=0,m<F){for(F-=w=m;V[g++]=C[H++],--w;);H=g-R,G=V}}}else if(H+=m-w,w<F){for(F-=w;V[g++]=C[H++],--w;);H=g-R,G=V}for(;2<F;)V[g++]=G[H++],V[g++]=G[H++],V[g++]=G[H++],F-=3;F&&(V[g++]=G[H++],1<F&&(V[g++]=G[H++]))}else{for(H=g-R;V[g++]=V[H++],V[g++]=V[H++],V[g++]=V[H++],2<(F-=3););F&&(V[g++]=V[H++],1<F&&(V[g++]=V[H++]))}break}}break}}while(c<l&&g<h);c-=F=f>>3,I&=(1<<(f-=F<<3))-1,A.next_in=c,A.next_out=g,A.avail_in=c<l?l-c+5:5-(c-l),A.avail_out=g<h?h-g+257:257-(g-h),a.hold=I,a.bits=f}},{}],49:[function(o,i,r){var A=o("../utils/common"),s=o("./adler32"),a=o("./crc32"),c=o("./inffast"),l=o("./inftrees"),g=1,u=2,h=0,d=-2,_=1,p=852,m=592;function C(H){return(H>>>24&255)+(H>>>8&65280)+((65280&H)<<8)+((255&H)<<24)}function I(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new A.Buf16(320),this.work=new A.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function f(H){var G;return H&&H.state?(G=H.state,H.total_in=H.total_out=G.total=0,H.msg="",G.wrap&&(H.adler=1&G.wrap),G.mode=_,G.last=0,G.havedict=0,G.dmax=32768,G.head=null,G.hold=0,G.bits=0,G.lencode=G.lendyn=new A.Buf32(p),G.distcode=G.distdyn=new A.Buf32(m),G.sane=1,G.back=-1,h):d}function y(H){var G;return H&&H.state?((G=H.state).wsize=0,G.whave=0,G.wnext=0,f(H)):d}function x(H,G){var K,V;return H&&H.state?(V=H.state,G<0?(K=0,G=-G):(K=1+(G>>4),G<48&&(G&=15)),G&&(G<8||15<G)?d:(V.window!==null&&V.wbits!==G&&(V.window=null),V.wrap=K,V.wbits=G,y(H))):d}function B(H,G){var K,V;return H?(V=new I,(H.state=V).window=null,(K=x(H,G))!==h&&(H.state=null),K):d}var S,D,w=!0;function F(H){if(w){var G;for(S=new A.Buf32(512),D=new A.Buf32(32),G=0;G<144;)H.lens[G++]=8;for(;G<256;)H.lens[G++]=9;for(;G<280;)H.lens[G++]=7;for(;G<288;)H.lens[G++]=8;for(l(g,H.lens,0,288,S,0,H.work,{bits:9}),G=0;G<32;)H.lens[G++]=5;l(u,H.lens,0,32,D,0,H.work,{bits:5}),w=!1}H.lencode=S,H.lenbits=9,H.distcode=D,H.distbits=5}function R(H,G,K,V){var W,X=H.state;return X.window===null&&(X.wsize=1<<X.wbits,X.wnext=0,X.whave=0,X.window=new A.Buf8(X.wsize)),V>=X.wsize?(A.arraySet(X.window,G,K-X.wsize,X.wsize,0),X.wnext=0,X.whave=X.wsize):(V<(W=X.wsize-X.wnext)&&(W=V),A.arraySet(X.window,G,K-V,W,X.wnext),(V-=W)?(A.arraySet(X.window,G,K-V,V,0),X.wnext=V,X.whave=X.wsize):(X.wnext+=W,X.wnext===X.wsize&&(X.wnext=0),X.whave<X.wsize&&(X.whave+=W))),0}r.inflateReset=y,r.inflateReset2=x,r.inflateResetKeep=f,r.inflateInit=function(H){return B(H,15)},r.inflateInit2=B,r.inflate=function(H,G){var K,V,W,X,ie,se,ee,oe,ae,re,le,fe,ye,be,ue,Be,pe,Ge,Je,nt,Ie,Ze,Ke,Ye,qe=0,Le=new A.Buf8(4),Se=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!H||!H.state||!H.output||!H.input&&H.avail_in!==0)return d;(K=H.state).mode===12&&(K.mode=13),ie=H.next_out,W=H.output,ee=H.avail_out,X=H.next_in,V=H.input,se=H.avail_in,oe=K.hold,ae=K.bits,re=se,le=ee,Ze=h;e:for(;;)switch(K.mode){case _:if(K.wrap===0){K.mode=13;break}for(;ae<16;){if(se===0)break e;se--,oe+=V[X++]<<ae,ae+=8}if(2&K.wrap&&oe===35615){Le[K.check=0]=255&oe,Le[1]=oe>>>8&255,K.check=a(K.check,Le,2,0),ae=oe=0,K.mode=2;break}if(K.flags=0,K.head&&(K.head.done=!1),!(1&K.wrap)||(((255&oe)<<8)+(oe>>8))%31){H.msg="incorrect header check",K.mode=30;break}if((15&oe)!=8){H.msg="unknown compression method",K.mode=30;break}if(ae-=4,Ie=8+(15&(oe>>>=4)),K.wbits===0)K.wbits=Ie;else if(Ie>K.wbits){H.msg="invalid window size",K.mode=30;break}K.dmax=1<<Ie,H.adler=K.check=1,K.mode=512&oe?10:12,ae=oe=0;break;case 2:for(;ae<16;){if(se===0)break e;se--,oe+=V[X++]<<ae,ae+=8}if(K.flags=oe,(255&K.flags)!=8){H.msg="unknown compression method",K.mode=30;break}if(57344&K.flags){H.msg="unknown header flags set",K.mode=30;break}K.head&&(K.head.text=oe>>8&1),512&K.flags&&(Le[0]=255&oe,Le[1]=oe>>>8&255,K.check=a(K.check,Le,2,0)),ae=oe=0,K.mode=3;case 3:for(;ae<32;){if(se===0)break e;se--,oe+=V[X++]<<ae,ae+=8}K.head&&(K.head.time=oe),512&K.flags&&(Le[0]=255&oe,Le[1]=oe>>>8&255,Le[2]=oe>>>16&255,Le[3]=oe>>>24&255,K.check=a(K.check,Le,4,0)),ae=oe=0,K.mode=4;case 4:for(;ae<16;){if(se===0)break e;se--,oe+=V[X++]<<ae,ae+=8}K.head&&(K.head.xflags=255&oe,K.head.os=oe>>8),512&K.flags&&(Le[0]=255&oe,Le[1]=oe>>>8&255,K.check=a(K.check,Le,2,0)),ae=oe=0,K.mode=5;case 5:if(1024&K.flags){for(;ae<16;){if(se===0)break e;se--,oe+=V[X++]<<ae,ae+=8}K.length=oe,K.head&&(K.head.extra_len=oe),512&K.flags&&(Le[0]=255&oe,Le[1]=oe>>>8&255,K.check=a(K.check,Le,2,0)),ae=oe=0}else K.head&&(K.head.extra=null);K.mode=6;case 6:if(1024&K.flags&&(se<(fe=K.length)&&(fe=se),fe&&(K.head&&(Ie=K.head.extra_len-K.length,K.head.extra||(K.head.extra=new Array(K.head.extra_len)),A.arraySet(K.head.extra,V,X,fe,Ie)),512&K.flags&&(K.check=a(K.check,V,fe,X)),se-=fe,X+=fe,K.length-=fe),K.length))break e;K.length=0,K.mode=7;case 7:if(2048&K.flags){if(se===0)break e;for(fe=0;Ie=V[X+fe++],K.head&&Ie&&K.length<65536&&(K.head.name+=String.fromCharCode(Ie)),Ie&&fe<se;);if(512&K.flags&&(K.check=a(K.check,V,fe,X)),se-=fe,X+=fe,Ie)break e}else K.head&&(K.head.name=null);K.length=0,K.mode=8;case 8:if(4096&K.flags){if(se===0)break e;for(fe=0;Ie=V[X+fe++],K.head&&Ie&&K.length<65536&&(K.head.comment+=String.fromCharCode(Ie)),Ie&&fe<se;);if(512&K.flags&&(K.check=a(K.check,V,fe,X)),se-=fe,X+=fe,Ie)break e}else K.head&&(K.head.comment=null);K.mode=9;case 9:if(512&K.flags){for(;ae<16;){if(se===0)break e;se--,oe+=V[X++]<<ae,ae+=8}if(oe!==(65535&K.check)){H.msg="header crc mismatch",K.mode=30;break}ae=oe=0}K.head&&(K.head.hcrc=K.flags>>9&1,K.head.done=!0),H.adler=K.check=0,K.mode=12;break;case 10:for(;ae<32;){if(se===0)break e;se--,oe+=V[X++]<<ae,ae+=8}H.adler=K.check=C(oe),ae=oe=0,K.mode=11;case 11:if(K.havedict===0)return H.next_out=ie,H.avail_out=ee,H.next_in=X,H.avail_in=se,K.hold=oe,K.bits=ae,2;H.adler=K.check=1,K.mode=12;case 12:if(G===5||G===6)break e;case 13:if(K.last){oe>>>=7&ae,ae-=7&ae,K.mode=27;break}for(;ae<3;){if(se===0)break e;se--,oe+=V[X++]<<ae,ae+=8}switch(K.last=1&oe,ae-=1,3&(oe>>>=1)){case 0:K.mode=14;break;case 1:if(F(K),K.mode=20,G!==6)break;oe>>>=2,ae-=2;break e;case 2:K.mode=17;break;case 3:H.msg="invalid block type",K.mode=30}oe>>>=2,ae-=2;break;case 14:for(oe>>>=7&ae,ae-=7&ae;ae<32;){if(se===0)break e;se--,oe+=V[X++]<<ae,ae+=8}if((65535&oe)!=(oe>>>16^65535)){H.msg="invalid stored block lengths",K.mode=30;break}if(K.length=65535&oe,ae=oe=0,K.mode=15,G===6)break e;case 15:K.mode=16;case 16:if(fe=K.length){if(se<fe&&(fe=se),ee<fe&&(fe=ee),fe===0)break e;A.arraySet(W,V,X,fe,ie),se-=fe,X+=fe,ee-=fe,ie+=fe,K.length-=fe;break}K.mode=12;break;case 17:for(;ae<14;){if(se===0)break e;se--,oe+=V[X++]<<ae,ae+=8}if(K.nlen=257+(31&oe),oe>>>=5,ae-=5,K.ndist=1+(31&oe),oe>>>=5,ae-=5,K.ncode=4+(15&oe),oe>>>=4,ae-=4,286<K.nlen||30<K.ndist){H.msg="too many length or distance symbols",K.mode=30;break}K.have=0,K.mode=18;case 18:for(;K.have<K.ncode;){for(;ae<3;){if(se===0)break e;se--,oe+=V[X++]<<ae,ae+=8}K.lens[Se[K.have++]]=7&oe,oe>>>=3,ae-=3}for(;K.have<19;)K.lens[Se[K.have++]]=0;if(K.lencode=K.lendyn,K.lenbits=7,Ke={bits:K.lenbits},Ze=l(0,K.lens,0,19,K.lencode,0,K.work,Ke),K.lenbits=Ke.bits,Ze){H.msg="invalid code lengths set",K.mode=30;break}K.have=0,K.mode=19;case 19:for(;K.have<K.nlen+K.ndist;){for(;Be=(qe=K.lencode[oe&(1<<K.lenbits)-1])>>>16&255,pe=65535&qe,!((ue=qe>>>24)<=ae);){if(se===0)break e;se--,oe+=V[X++]<<ae,ae+=8}if(pe<16)oe>>>=ue,ae-=ue,K.lens[K.have++]=pe;else{if(pe===16){for(Ye=ue+2;ae<Ye;){if(se===0)break e;se--,oe+=V[X++]<<ae,ae+=8}if(oe>>>=ue,ae-=ue,K.have===0){H.msg="invalid bit length repeat",K.mode=30;break}Ie=K.lens[K.have-1],fe=3+(3&oe),oe>>>=2,ae-=2}else if(pe===17){for(Ye=ue+3;ae<Ye;){if(se===0)break e;se--,oe+=V[X++]<<ae,ae+=8}ae-=ue,Ie=0,fe=3+(7&(oe>>>=ue)),oe>>>=3,ae-=3}else{for(Ye=ue+7;ae<Ye;){if(se===0)break e;se--,oe+=V[X++]<<ae,ae+=8}ae-=ue,Ie=0,fe=11+(127&(oe>>>=ue)),oe>>>=7,ae-=7}if(K.have+fe>K.nlen+K.ndist){H.msg="invalid bit length repeat",K.mode=30;break}for(;fe--;)K.lens[K.have++]=Ie}}if(K.mode===30)break;if(K.lens[256]===0){H.msg="invalid code -- missing end-of-block",K.mode=30;break}if(K.lenbits=9,Ke={bits:K.lenbits},Ze=l(g,K.lens,0,K.nlen,K.lencode,0,K.work,Ke),K.lenbits=Ke.bits,Ze){H.msg="invalid literal/lengths set",K.mode=30;break}if(K.distbits=6,K.distcode=K.distdyn,Ke={bits:K.distbits},Ze=l(u,K.lens,K.nlen,K.ndist,K.distcode,0,K.work,Ke),K.distbits=Ke.bits,Ze){H.msg="invalid distances set",K.mode=30;break}if(K.mode=20,G===6)break e;case 20:K.mode=21;case 21:if(6<=se&&258<=ee){H.next_out=ie,H.avail_out=ee,H.next_in=X,H.avail_in=se,K.hold=oe,K.bits=ae,c(H,le),ie=H.next_out,W=H.output,ee=H.avail_out,X=H.next_in,V=H.input,se=H.avail_in,oe=K.hold,ae=K.bits,K.mode===12&&(K.back=-1);break}for(K.back=0;Be=(qe=K.lencode[oe&(1<<K.lenbits)-1])>>>16&255,pe=65535&qe,!((ue=qe>>>24)<=ae);){if(se===0)break e;se--,oe+=V[X++]<<ae,ae+=8}if(Be&&(240&Be)==0){for(Ge=ue,Je=Be,nt=pe;Be=(qe=K.lencode[nt+((oe&(1<<Ge+Je)-1)>>Ge)])>>>16&255,pe=65535&qe,!(Ge+(ue=qe>>>24)<=ae);){if(se===0)break e;se--,oe+=V[X++]<<ae,ae+=8}oe>>>=Ge,ae-=Ge,K.back+=Ge}if(oe>>>=ue,ae-=ue,K.back+=ue,K.length=pe,Be===0){K.mode=26;break}if(32&Be){K.back=-1,K.mode=12;break}if(64&Be){H.msg="invalid literal/length code",K.mode=30;break}K.extra=15&Be,K.mode=22;case 22:if(K.extra){for(Ye=K.extra;ae<Ye;){if(se===0)break e;se--,oe+=V[X++]<<ae,ae+=8}K.length+=oe&(1<<K.extra)-1,oe>>>=K.extra,ae-=K.extra,K.back+=K.extra}K.was=K.length,K.mode=23;case 23:for(;Be=(qe=K.distcode[oe&(1<<K.distbits)-1])>>>16&255,pe=65535&qe,!((ue=qe>>>24)<=ae);){if(se===0)break e;se--,oe+=V[X++]<<ae,ae+=8}if((240&Be)==0){for(Ge=ue,Je=Be,nt=pe;Be=(qe=K.distcode[nt+((oe&(1<<Ge+Je)-1)>>Ge)])>>>16&255,pe=65535&qe,!(Ge+(ue=qe>>>24)<=ae);){if(se===0)break e;se--,oe+=V[X++]<<ae,ae+=8}oe>>>=Ge,ae-=Ge,K.back+=Ge}if(oe>>>=ue,ae-=ue,K.back+=ue,64&Be){H.msg="invalid distance code",K.mode=30;break}K.offset=pe,K.extra=15&Be,K.mode=24;case 24:if(K.extra){for(Ye=K.extra;ae<Ye;){if(se===0)break e;se--,oe+=V[X++]<<ae,ae+=8}K.offset+=oe&(1<<K.extra)-1,oe>>>=K.extra,ae-=K.extra,K.back+=K.extra}if(K.offset>K.dmax){H.msg="invalid distance too far back",K.mode=30;break}K.mode=25;case 25:if(ee===0)break e;if(fe=le-ee,K.offset>fe){if((fe=K.offset-fe)>K.whave&&K.sane){H.msg="invalid distance too far back",K.mode=30;break}ye=fe>K.wnext?(fe-=K.wnext,K.wsize-fe):K.wnext-fe,fe>K.length&&(fe=K.length),be=K.window}else be=W,ye=ie-K.offset,fe=K.length;for(ee<fe&&(fe=ee),ee-=fe,K.length-=fe;W[ie++]=be[ye++],--fe;);K.length===0&&(K.mode=21);break;case 26:if(ee===0)break e;W[ie++]=K.length,ee--,K.mode=21;break;case 27:if(K.wrap){for(;ae<32;){if(se===0)break e;se--,oe|=V[X++]<<ae,ae+=8}if(le-=ee,H.total_out+=le,K.total+=le,le&&(H.adler=K.check=K.flags?a(K.check,W,le,ie-le):s(K.check,W,le,ie-le)),le=ee,(K.flags?oe:C(oe))!==K.check){H.msg="incorrect data check",K.mode=30;break}ae=oe=0}K.mode=28;case 28:if(K.wrap&&K.flags){for(;ae<32;){if(se===0)break e;se--,oe+=V[X++]<<ae,ae+=8}if(oe!==(4294967295&K.total)){H.msg="incorrect length check",K.mode=30;break}ae=oe=0}K.mode=29;case 29:Ze=1;break e;case 30:Ze=-3;break e;case 31:return-4;default:return d}return H.next_out=ie,H.avail_out=ee,H.next_in=X,H.avail_in=se,K.hold=oe,K.bits=ae,(K.wsize||le!==H.avail_out&&K.mode<30&&(K.mode<27||G!==4))&&R(H,H.output,H.next_out,le-H.avail_out)?(K.mode=31,-4):(re-=H.avail_in,le-=H.avail_out,H.total_in+=re,H.total_out+=le,K.total+=le,K.wrap&&le&&(H.adler=K.check=K.flags?a(K.check,W,le,H.next_out-le):s(K.check,W,le,H.next_out-le)),H.data_type=K.bits+(K.last?64:0)+(K.mode===12?128:0)+(K.mode===20||K.mode===15?256:0),(re==0&&le===0||G===4)&&Ze===h&&(Ze=-5),Ze)},r.inflateEnd=function(H){if(!H||!H.state)return d;var G=H.state;return G.window&&(G.window=null),H.state=null,h},r.inflateGetHeader=function(H,G){var K;return H&&H.state?(2&(K=H.state).wrap)==0?d:((K.head=G).done=!1,h):d},r.inflateSetDictionary=function(H,G){var K,V=G.length;return H&&H.state?(K=H.state).wrap!==0&&K.mode!==11?d:K.mode===11&&s(1,G,V,0)!==K.check?-3:R(H,G,V,V)?(K.mode=31,-4):(K.havedict=1,h):d},r.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./inffast":48,"./inftrees":50}],50:[function(o,i,r){var A=o("../utils/common"),s=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],a=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],c=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],l=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];i.exports=function(g,u,h,d,_,p,m,C){var I,f,y,x,B,S,D,w,F,R=C.bits,H=0,G=0,K=0,V=0,W=0,X=0,ie=0,se=0,ee=0,oe=0,ae=null,re=0,le=new A.Buf16(16),fe=new A.Buf16(16),ye=null,be=0;for(H=0;H<=15;H++)le[H]=0;for(G=0;G<d;G++)le[u[h+G]]++;for(W=R,V=15;1<=V&&le[V]===0;V--);if(V<W&&(W=V),V===0)return _[p++]=20971520,_[p++]=20971520,C.bits=1,0;for(K=1;K<V&&le[K]===0;K++);for(W<K&&(W=K),H=se=1;H<=15;H++)if(se<<=1,(se-=le[H])<0)return-1;if(0<se&&(g===0||V!==1))return-1;for(fe[1]=0,H=1;H<15;H++)fe[H+1]=fe[H]+le[H];for(G=0;G<d;G++)u[h+G]!==0&&(m[fe[u[h+G]]++]=G);if(S=g===0?(ae=ye=m,19):g===1?(ae=s,re-=257,ye=a,be-=257,256):(ae=c,ye=l,-1),H=K,B=p,ie=G=oe=0,y=-1,x=(ee=1<<(X=W))-1,g===1&&852<ee||g===2&&592<ee)return 1;for(;;){for(D=H-ie,F=m[G]<S?(w=0,m[G]):m[G]>S?(w=ye[be+m[G]],ae[re+m[G]]):(w=96,0),I=1<<H-ie,K=f=1<<X;_[B+(oe>>ie)+(f-=I)]=D<<24|w<<16|F|0,f!==0;);for(I=1<<H-1;oe&I;)I>>=1;if(I!==0?(oe&=I-1,oe+=I):oe=0,G++,--le[H]==0){if(H===V)break;H=u[h+m[G]]}if(W<H&&(oe&x)!==y){for(ie===0&&(ie=W),B+=K,se=1<<(X=H-ie);X+ie<V&&!((se-=le[X+ie])<=0);)X++,se<<=1;if(ee+=1<<X,g===1&&852<ee||g===2&&592<ee)return 1;_[y=oe&x]=W<<24|X<<16|B-p|0}}return oe!==0&&(_[B+oe]=H-ie<<24|64<<16|0),C.bits=W,0}},{"../utils/common":41}],51:[function(o,i,r){i.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],52:[function(o,i,r){var A=o("../utils/common"),s=0,a=1;function c(qe){for(var Le=qe.length;0<=--Le;)qe[Le]=0}var l=0,g=29,u=256,h=u+1+g,d=30,_=19,p=2*h+1,m=15,C=16,I=7,f=256,y=16,x=17,B=18,S=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],D=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],w=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],F=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],R=new Array(2*(h+2));c(R);var H=new Array(2*d);c(H);var G=new Array(512);c(G);var K=new Array(256);c(K);var V=new Array(g);c(V);var W,X,ie,se=new Array(d);function ee(qe,Le,Se,ve,Pe){this.static_tree=qe,this.extra_bits=Le,this.extra_base=Se,this.elems=ve,this.max_length=Pe,this.has_stree=qe&&qe.length}function oe(qe,Le){this.dyn_tree=qe,this.max_code=0,this.stat_desc=Le}function ae(qe){return qe<256?G[qe]:G[256+(qe>>>7)]}function re(qe,Le){qe.pending_buf[qe.pending++]=255&Le,qe.pending_buf[qe.pending++]=Le>>>8&255}function le(qe,Le,Se){qe.bi_valid>C-Se?(qe.bi_buf|=Le<<qe.bi_valid&65535,re(qe,qe.bi_buf),qe.bi_buf=Le>>C-qe.bi_valid,qe.bi_valid+=Se-C):(qe.bi_buf|=Le<<qe.bi_valid&65535,qe.bi_valid+=Se)}function fe(qe,Le,Se){le(qe,Se[2*Le],Se[2*Le+1])}function ye(qe,Le){for(var Se=0;Se|=1&qe,qe>>>=1,Se<<=1,0<--Le;);return Se>>>1}function be(qe,Le,Se){var ve,Pe,ze=new Array(m+1),Xe=0;for(ve=1;ve<=m;ve++)ze[ve]=Xe=Xe+Se[ve-1]<<1;for(Pe=0;Pe<=Le;Pe++){var st=qe[2*Pe+1];st!==0&&(qe[2*Pe]=ye(ze[st]++,st))}}function ue(qe){var Le;for(Le=0;Le<h;Le++)qe.dyn_ltree[2*Le]=0;for(Le=0;Le<d;Le++)qe.dyn_dtree[2*Le]=0;for(Le=0;Le<_;Le++)qe.bl_tree[2*Le]=0;qe.dyn_ltree[2*f]=1,qe.opt_len=qe.static_len=0,qe.last_lit=qe.matches=0}function Be(qe){8<qe.bi_valid?re(qe,qe.bi_buf):0<qe.bi_valid&&(qe.pending_buf[qe.pending++]=qe.bi_buf),qe.bi_buf=0,qe.bi_valid=0}function pe(qe,Le,Se,ve){var Pe=2*Le,ze=2*Se;return qe[Pe]<qe[ze]||qe[Pe]===qe[ze]&&ve[Le]<=ve[Se]}function Ge(qe,Le,Se){for(var ve=qe.heap[Se],Pe=Se<<1;Pe<=qe.heap_len&&(Pe<qe.heap_len&&pe(Le,qe.heap[Pe+1],qe.heap[Pe],qe.depth)&&Pe++,!pe(Le,ve,qe.heap[Pe],qe.depth));)qe.heap[Se]=qe.heap[Pe],Se=Pe,Pe<<=1;qe.heap[Se]=ve}function Je(qe,Le,Se){var ve,Pe,ze,Xe,st=0;if(qe.last_lit!==0)for(;ve=qe.pending_buf[qe.d_buf+2*st]<<8|qe.pending_buf[qe.d_buf+2*st+1],Pe=qe.pending_buf[qe.l_buf+st],st++,ve===0?fe(qe,Pe,Le):(fe(qe,(ze=K[Pe])+u+1,Le),(Xe=S[ze])!==0&&le(qe,Pe-=V[ze],Xe),fe(qe,ze=ae(--ve),Se),(Xe=D[ze])!==0&&le(qe,ve-=se[ze],Xe)),st<qe.last_lit;);fe(qe,f,Le)}function nt(qe,Le){var Se,ve,Pe,ze=Le.dyn_tree,Xe=Le.stat_desc.static_tree,st=Le.stat_desc.has_stree,ct=Le.stat_desc.elems,ut=-1;for(qe.heap_len=0,qe.heap_max=p,Se=0;Se<ct;Se++)ze[2*Se]!==0?(qe.heap[++qe.heap_len]=ut=Se,qe.depth[Se]=0):ze[2*Se+1]=0;for(;qe.heap_len<2;)ze[2*(Pe=qe.heap[++qe.heap_len]=ut<2?++ut:0)]=1,qe.depth[Pe]=0,qe.opt_len--,st&&(qe.static_len-=Xe[2*Pe+1]);for(Le.max_code=ut,Se=qe.heap_len>>1;1<=Se;Se--)Ge(qe,ze,Se);for(Pe=ct;Se=qe.heap[1],qe.heap[1]=qe.heap[qe.heap_len--],Ge(qe,ze,1),ve=qe.heap[1],qe.heap[--qe.heap_max]=Se,qe.heap[--qe.heap_max]=ve,ze[2*Pe]=ze[2*Se]+ze[2*ve],qe.depth[Pe]=(qe.depth[Se]>=qe.depth[ve]?qe.depth[Se]:qe.depth[ve])+1,ze[2*Se+1]=ze[2*ve+1]=Pe,qe.heap[1]=Pe++,Ge(qe,ze,1),2<=qe.heap_len;);qe.heap[--qe.heap_max]=qe.heap[1],(function(lt,Ct){var Dt,pt,Nt,Ht,gn,dn,Jt=Ct.dyn_tree,Ce=Ct.max_code,At=Ct.stat_desc.static_tree,ht=Ct.stat_desc.has_stree,_t=Ct.stat_desc.extra_bits,Gt=Ct.stat_desc.extra_base,Yt=Ct.stat_desc.max_length,un=0;for(Ht=0;Ht<=m;Ht++)lt.bl_count[Ht]=0;for(Jt[2*lt.heap[lt.heap_max]+1]=0,Dt=lt.heap_max+1;Dt<p;Dt++)Yt<(Ht=Jt[2*Jt[2*(pt=lt.heap[Dt])+1]+1]+1)&&(Ht=Yt,un++),Jt[2*pt+1]=Ht,Ce<pt||(lt.bl_count[Ht]++,gn=0,Gt<=pt&&(gn=_t[pt-Gt]),dn=Jt[2*pt],lt.opt_len+=dn*(Ht+gn),ht&&(lt.static_len+=dn*(At[2*pt+1]+gn)));if(un!==0){do{for(Ht=Yt-1;lt.bl_count[Ht]===0;)Ht--;lt.bl_count[Ht]--,lt.bl_count[Ht+1]+=2,lt.bl_count[Yt]--,un-=2}while(0<un);for(Ht=Yt;Ht!==0;Ht--)for(pt=lt.bl_count[Ht];pt!==0;)Ce<(Nt=lt.heap[--Dt])||(Jt[2*Nt+1]!==Ht&&(lt.opt_len+=(Ht-Jt[2*Nt+1])*Jt[2*Nt],Jt[2*Nt+1]=Ht),pt--)}})(qe,Le),be(ze,ut,qe.bl_count)}function Ie(qe,Le,Se){var ve,Pe,ze=-1,Xe=Le[1],st=0,ct=7,ut=4;for(Xe===0&&(ct=138,ut=3),Le[2*(Se+1)+1]=65535,ve=0;ve<=Se;ve++)Pe=Xe,Xe=Le[2*(ve+1)+1],++st<ct&&Pe===Xe||(st<ut?qe.bl_tree[2*Pe]+=st:Pe!==0?(Pe!==ze&&qe.bl_tree[2*Pe]++,qe.bl_tree[2*y]++):st<=10?qe.bl_tree[2*x]++:qe.bl_tree[2*B]++,ze=Pe,ut=(st=0)===Xe?(ct=138,3):Pe===Xe?(ct=6,3):(ct=7,4))}function Ze(qe,Le,Se){var ve,Pe,ze=-1,Xe=Le[1],st=0,ct=7,ut=4;for(Xe===0&&(ct=138,ut=3),ve=0;ve<=Se;ve++)if(Pe=Xe,Xe=Le[2*(ve+1)+1],!(++st<ct&&Pe===Xe)){if(st<ut)for(;fe(qe,Pe,qe.bl_tree),--st!=0;);else Pe!==0?(Pe!==ze&&(fe(qe,Pe,qe.bl_tree),st--),fe(qe,y,qe.bl_tree),le(qe,st-3,2)):st<=10?(fe(qe,x,qe.bl_tree),le(qe,st-3,3)):(fe(qe,B,qe.bl_tree),le(qe,st-11,7));ze=Pe,ut=(st=0)===Xe?(ct=138,3):Pe===Xe?(ct=6,3):(ct=7,4)}}c(se);var Ke=!1;function Ye(qe,Le,Se,ve){le(qe,(l<<1)+(ve?1:0),3),(function(Pe,ze,Xe,st){Be(Pe),re(Pe,Xe),re(Pe,~Xe),A.arraySet(Pe.pending_buf,Pe.window,ze,Xe,Pe.pending),Pe.pending+=Xe})(qe,Le,Se)}r._tr_init=function(qe){Ke||((function(){var Le,Se,ve,Pe,ze,Xe=new Array(m+1);for(Pe=ve=0;Pe<g-1;Pe++)for(V[Pe]=ve,Le=0;Le<1<<S[Pe];Le++)K[ve++]=Pe;for(K[ve-1]=Pe,Pe=ze=0;Pe<16;Pe++)for(se[Pe]=ze,Le=0;Le<1<<D[Pe];Le++)G[ze++]=Pe;for(ze>>=7;Pe<d;Pe++)for(se[Pe]=ze<<7,Le=0;Le<1<<D[Pe]-7;Le++)G[256+ze++]=Pe;for(Se=0;Se<=m;Se++)Xe[Se]=0;for(Le=0;Le<=143;)R[2*Le+1]=8,Le++,Xe[8]++;for(;Le<=255;)R[2*Le+1]=9,Le++,Xe[9]++;for(;Le<=279;)R[2*Le+1]=7,Le++,Xe[7]++;for(;Le<=287;)R[2*Le+1]=8,Le++,Xe[8]++;for(be(R,h+1,Xe),Le=0;Le<d;Le++)H[2*Le+1]=5,H[2*Le]=ye(Le,5);W=new ee(R,S,u+1,h,m),X=new ee(H,D,0,d,m),ie=new ee(new Array(0),w,0,_,I)})(),Ke=!0),qe.l_desc=new oe(qe.dyn_ltree,W),qe.d_desc=new oe(qe.dyn_dtree,X),qe.bl_desc=new oe(qe.bl_tree,ie),qe.bi_buf=0,qe.bi_valid=0,ue(qe)},r._tr_stored_block=Ye,r._tr_flush_block=function(qe,Le,Se,ve){var Pe,ze,Xe=0;0<qe.level?(qe.strm.data_type===2&&(qe.strm.data_type=(function(st){var ct,ut=4093624447;for(ct=0;ct<=31;ct++,ut>>>=1)if(1&ut&&st.dyn_ltree[2*ct]!==0)return s;if(st.dyn_ltree[18]!==0||st.dyn_ltree[20]!==0||st.dyn_ltree[26]!==0)return a;for(ct=32;ct<u;ct++)if(st.dyn_ltree[2*ct]!==0)return a;return s})(qe)),nt(qe,qe.l_desc),nt(qe,qe.d_desc),Xe=(function(st){var ct;for(Ie(st,st.dyn_ltree,st.l_desc.max_code),Ie(st,st.dyn_dtree,st.d_desc.max_code),nt(st,st.bl_desc),ct=_-1;3<=ct&&st.bl_tree[2*F[ct]+1]===0;ct--);return st.opt_len+=3*(ct+1)+5+5+4,ct})(qe),Pe=qe.opt_len+3+7>>>3,(ze=qe.static_len+3+7>>>3)<=Pe&&(Pe=ze)):Pe=ze=Se+5,Se+4<=Pe&&Le!==-1?Ye(qe,Le,Se,ve):qe.strategy===4||ze===Pe?(le(qe,2+(ve?1:0),3),Je(qe,R,H)):(le(qe,4+(ve?1:0),3),(function(st,ct,ut,lt){var Ct;for(le(st,ct-257,5),le(st,ut-1,5),le(st,lt-4,4),Ct=0;Ct<lt;Ct++)le(st,st.bl_tree[2*F[Ct]+1],3);Ze(st,st.dyn_ltree,ct-1),Ze(st,st.dyn_dtree,ut-1)})(qe,qe.l_desc.max_code+1,qe.d_desc.max_code+1,Xe+1),Je(qe,qe.dyn_ltree,qe.dyn_dtree)),ue(qe),ve&&Be(qe)},r._tr_tally=function(qe,Le,Se){return qe.pending_buf[qe.d_buf+2*qe.last_lit]=Le>>>8&255,qe.pending_buf[qe.d_buf+2*qe.last_lit+1]=255&Le,qe.pending_buf[qe.l_buf+qe.last_lit]=255&Se,qe.last_lit++,Le===0?qe.dyn_ltree[2*Se]++:(qe.matches++,Le--,qe.dyn_ltree[2*(K[Se]+u+1)]++,qe.dyn_dtree[2*ae(Le)]++),qe.last_lit===qe.lit_bufsize-1},r._tr_align=function(qe){le(qe,2,3),fe(qe,f,R),(function(Le){Le.bi_valid===16?(re(Le,Le.bi_buf),Le.bi_buf=0,Le.bi_valid=0):8<=Le.bi_valid&&(Le.pending_buf[Le.pending++]=255&Le.bi_buf,Le.bi_buf>>=8,Le.bi_valid-=8)})(qe)}},{"../utils/common":41}],53:[function(o,i,r){i.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(o,i,r){(function(A){(function(s,a){if(!s.setImmediate){var c,l,g,u,h=1,d={},_=!1,p=s.document,m=Object.getPrototypeOf&&Object.getPrototypeOf(s);m=m&&m.setTimeout?m:s,c={}.toString.call(s.process)==="[object process]"?function(y){n.nextTick(function(){I(y)})}:(function(){if(s.postMessage&&!s.importScripts){var y=!0,x=s.onmessage;return s.onmessage=function(){y=!1},s.postMessage("","*"),s.onmessage=x,y}})()?(u="setImmediate$"+Math.random()+"$",s.addEventListener?s.addEventListener("message",f,!1):s.attachEvent("onmessage",f),function(y){s.postMessage(u+y,"*")}):s.MessageChannel?((g=new MessageChannel).port1.onmessage=function(y){I(y.data)},function(y){g.port2.postMessage(y)}):p&&"onreadystatechange"in p.createElement("script")?(l=p.documentElement,function(y){var x=p.createElement("script");x.onreadystatechange=function(){I(y),x.onreadystatechange=null,l.removeChild(x),x=null},l.appendChild(x)}):function(y){setTimeout(I,0,y)},m.setImmediate=function(y){typeof y!="function"&&(y=new Function(""+y));for(var x=new Array(arguments.length-1),B=0;B<x.length;B++)x[B]=arguments[B+1];var S={callback:y,args:x};return d[h]=S,c(h),h++},m.clearImmediate=C}function C(y){delete d[y]}function I(y){if(_)setTimeout(I,0,y);else{var x=d[y];if(x){_=!0;try{(function(B){var S=B.callback,D=B.args;switch(D.length){case 0:S();break;case 1:S(D[0]);break;case 2:S(D[0],D[1]);break;case 3:S(D[0],D[1],D[2]);break;default:S.apply(a,D)}})(x)}finally{C(y),_=!1}}}}function f(y){y.source===s&&typeof y.data=="string"&&y.data.indexOf(u)===0&&I(+y.data.slice(u.length))}})(typeof self>"u"?A===void 0?this:A:self)}).call(this,typeof cf<"u"?cf:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})})(z3e)),z3e.exports}var iKo=oKo();const V3e=R1(iKo),rKo=async({circuitJson:t,projectName:e})=>{await zA.promise((async()=>{const n=new V3e,[{stringifyGerberCommandLayers:o,convertSoupToGerberCommands:i,convertSoupToExcellonDrillCommands:r,stringifyExcellonDrill:A},{convertCircuitJsonToBomRows:s,convertBomRowsToCsv:a},{convertCircuitJsonToPickAndPlaceCsv:c}]=await Promise.all([DB("circuit-json-to-gerber"),DB("circuit-json-to-bom-csv"),DB("circuit-json-to-pnp-csv")]),l=t.filter(I=>!("error_type"in I)&&!("warning_type"in I)),g=i(l,{flip_y_axis:!1}),u=o(g);for(const[I,f]of Object.entries(u))n.file(`gerber/${I}.gbr`,f);const h=r({circuitJson:l,is_plated:!0,flip_y_axis:!1}),d=A(h);n.file("gerber/drill.drl",d);const _=await s({circuitJson:t}),p=await a(_);n.file("bom.csv",p);const m=await c(t);n.file("pick_and_place.csv",m);const C=await n.generateAsync({type:"blob"});DS(C,{fileName:`${e}_fabrication_files.zip`})})(),{loading:"Generating fabrication files...",success:"Fabrication ZIP ready",error:n=>`Failed to generate fabrication files: ${n instanceof Error?n.message:String(n)}`})},AKo=async({circuitJson:t,projectName:e})=>{let n;try{const{convertCircuitJsonToGltf:o}=await DB("circuit-json-to-gltf");console.log("convertCircuitJsonToGltf",o);const i=await o(t,{format:"glb",boardTextureResolution:1024});if(!i||!(i instanceof ArrayBuffer))throw new Error("Invalid GLB data returned from converter");n=new Blob([i],{type:"model/gltf-binary"})}catch(o){console.error("GLB Export Error:",o);return}DS(n,{fileName:`${e}.glb`})},sKo=async({circuitJson:t,libraryName:e})=>{const{CircuitJsonToKicadLibraryConverter:n}=await DB("circuit-json-to-kicad"),o=new n(t,{libraryName:e,footprintLibraryName:e});o.runUntilFinished();const i=o.getOutput(),r=new V3e;r.file(`${e}.kicad_sym`,i.kicadSymString);for(const A of i.footprints){const s=r.folder(`${e}.pretty`);s&&s.file(`${A.footprintName}.kicad_mod`,`${A.kicadModString}
5795
5795
  `)}if(i.model3dSourcePaths.length>0){const A=r.folder(`${e}.3dshapes`);if(A)for(const s of i.model3dSourcePaths)try{const a=s.split("/").pop()||s,c=await fetch(s);if(c.ok){const l=await c.arrayBuffer();A.file(a,l)}}catch{}}return r.file("fp-lib-table",i.fpLibTableString),r.file("sym-lib-table",i.symLibTableString),r},aKo=async({circuitJson:t,projectName:e})=>{await zA.promise((async()=>{const o=await(await sKo({circuitJson:t,libraryName:e})).generateAsync({type:"blob"});DS(o,{fileName:`${e}_kicad_library.zip`})})(),{loading:"Generating KiCad library...",success:"KiCad library ZIP ready",error:n=>`Failed to generate KiCad library: ${n instanceof Error?n.message:String(n)}`})},cKo=async({circuitJson:t,projectName:e})=>{const{CircuitJsonToKicadPcbConverter:n,CircuitJsonToKicadSchConverter:o,CircuitJsonToKicadProConverter:i,resolveAndLoadKicad3dModelFiles:r}=await DB("circuit-json-to-kicad"),A=new o(t);A.runUntilFinished();const s=A.getOutputString(),a=new n(t,{includeBuiltin3dModels:!0,projectName:e});a.runUntilFinished();const c=a.getOutputString(),l=new i(t,{projectName:e,schematicFilename:`${e}.kicad_sch`,pcbFilename:`${e}.kicad_pcb`});l.runUntilFinished();const g=l.getOutputString(),u=new V3e;return u.file(`${e}.kicad_sch`,s),u.file(`${e}.kicad_pcb`,c),u.file(`${e}.kicad_pro`,g),await r({projectName:e,model3dSourcePaths:a.getModel3dSourcePaths(),fetch,onModelFile:({outputPath:h,content:d})=>{u.file(h,d)},onError:({sourcePath:h})=>{console.warn(`Failed to load 3D model from ${h}`)}}),u},lKo=async({circuitJson:t,projectName:e})=>{await zA.promise((async()=>{const o=await(await cKo({circuitJson:t,projectName:e})).generateAsync({type:"blob"});DS(o,{fileName:`${e}_kicad_project.zip`})})(),{loading:"Generating KiCad project...",success:"KiCad project ZIP ready",error:n=>`Failed to generate KiCad project: ${n instanceof Error?n.message:String(n)}`})},eTt=async({circuitJson:t,projectName:e,options:n={}})=>{try{const{convertCircuitJsonToLbrn:o}=await DB("circuit-json-to-lbrn"),r=(await o(t,{includeSilkscreen:n.includeSilkscreen??!1,includeOxidationCleaningLayer:n.includeOxidationCleaningLayer??!0})).toXml(),A=new Blob([r],{type:"application/lbrn"});DS(A,{fileName:`${e}.lbrn2`})}catch(o){const i=o instanceof Error?o.message:"Unknown error";zA.error(`Failed to export to LBRN format: ${i}`)}},gKo=async({circuitJson:t,projectName:e})=>{const{convertCircuitJsonToPinoutSvg:n}=await DB("circuit-to-svg"),o=n(t);DS(o,{fileName:`${e}-pinout.svg`,mimeType:"image/svg+xml"})},uKo=async({circuitJson:t,projectName:e})=>{const{circuitJsonToStep:n}=await DB("circuit-json-to-step"),o=t.find(c=>c.type==="pcb_board"),i=o&&"width"in o?o.width:void 0,r=o&&"height"in o?o.height:void 0,A=o&&"thickness"in o?o.thickness:void 0;if(i===void 0||r===void 0||A===void 0){zA.error("Board dimensions not found. Please add a pcb_board with width, height, and thickness to your circuit.");return}let s;try{s=await n(t,{boardWidth:i,boardHeight:r,boardThickness:A,productName:e,includeComponents:!0,includeExternalMeshes:!0})}catch(c){const l=c instanceof Error?c.message:"Unknown error";zA.error(`Failed to convert circuit to STEP format: ${l}`);return}const a=new Blob([s],{type:"application/step"});try{DS(a,{fileName:`${e}.step`})}catch(c){const l=c instanceof Error?c.message:"Unknown error";zA.error(`Failed to download STEP file: ${l}`)}},dKo=[{extension:"json",name:"Circuit JSON"},{extension:"json",name:"Simple Route JSON"},{extension:"zip",name:"Fabrication Files"},{extension:"zip",name:"KiCad Project"},{extension:"zip",name:"KiCad Library"},{extension:"glb",name:"GLB (Binary GLTF)"},{extension:"svg",name:"Pinout SVG"},{extension:"step",name:"STEP"},{extension:"lbrn2",name:"LightBurn"}],hKo=async({exportName:t,circuitJson:e,simpleRouteJson:n,projectName:o})=>{const i=ARt(o);if(t==="Fabrication Files"){await rKo({circuitJson:e,projectName:i});return}if(t==="KiCad Project"){await lKo({circuitJson:e,projectName:i});return}if(t==="KiCad Library"){await aKo({circuitJson:e,projectName:i});return}if(t==="Circuit JSON"){DS(JSON.stringify(e,null,2),{fileName:`${i}.circuit.json`,mimeType:"application/json"});return}if(t==="Simple Route JSON"){if(!n)throw new Error("No Simple Route JSON available to export");DS(JSON.stringify(n,null,2),{fileName:`${i}.simple-route.json`,mimeType:"application/json"});return}if(t==="GLB (Binary GLTF)"){await AKo({circuitJson:e,projectName:i});return}if(t==="Pinout SVG"){gKo({circuitJson:e,projectName:i});return}if(t==="STEP"){await uKo({circuitJson:e,projectName:i});return}if(t==="LightBurn"){await eTt({circuitJson:e,projectName:i});return}throw new Error(`Unsupported export type: "${t}"`)},_Ko=({packageName:t,onSelectReview:e})=>{const n=Yu(g=>g.fsMap),o=Yu(g=>g.circuitJson),[i,r]=j.useState([]),[A,s]=j.useState(!1),[a,c]=j.useState(!1);j.useEffect(()=>{!t||!kZ()||(s(!0),PG.get("ai_reviews/list",{searchParams:{package_name:t}}).json().then(g=>r(g.ai_reviews)).catch(g=>{console.error("Failed to load AI reviews",g),zA.error("Failed to load AI reviews")}).finally(()=>s(!1)))},[t]);const l=async()=>{if(!o){zA.error("Need Circuit JSON to Request AI Review");return}if(!kZ()){zA.error("Missing registry token");return}c(!0);try{const{ai_review:g}=await PG.post("ai_reviews/create",{json:{package_name:t??"unknown",fs_map:Object.fromEntries(n),circuit_json:o}}).json();r(u=>[g,...u]),e(g),zA.success("AI review requested")}catch(g){console.error("Failed to create AI review",g),zA.error("Failed to request AI review")}finally{c(!1)}};return J.jsxs(J.Fragment,{children:[J.jsxs(X3,{children:[J.jsx($3,{children:"AI Review"}),J.jsx(MT,{children:"Select an AI review or request a new one."})]}),J.jsx("div",{className:"rf-flex rf-gap-4 rf-mt-4",children:J.jsx("div",{className:"rf-w-48 rf-h-64 rf-overflow-y-auto rf-border rf-rounded rf-p-2 rf-flex-shrink-0",children:A?J.jsx("div",{className:"rf-text-sm",children:"Loading..."}):i.length>0?i.map(g=>J.jsx("div",{className:"rf-text-sm rf-p-2 rf-cursor-pointer rf-rounded hover:rf-bg-zinc-100",onClick:()=>e(g),children:new Date(g.created_at||"").toLocaleString()},g.ai_review_id)):J.jsx("div",{className:"rf-text-sm rf-text-muted-foreground",children:"No AI reviews found."})})}),J.jsx(eU,{className:"rf-mt-4",children:J.jsx(ta,{onClick:l,disabled:a,children:a?"Requesting...":"Review my Board"})})]})};function J3e(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Z3=J3e();function tTt(t){Z3=t}var oU={exec:()=>null};function pl(t,e=""){let n=typeof t=="string"?t:t.source;const o={replace:(i,r)=>{let A=typeof r=="string"?r:r.source;return A=A.replace(Gf.caret,"$1"),n=n.replace(i,A),o},getRegex:()=>new RegExp(n,e)};return o}var Gf={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceTabs:/^\t+/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] /,listReplaceTask:/^\[[ xX]\] +/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,unescapeTest:/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:t=>new RegExp(`^( {0,3}${t})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}#`),htmlBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}<(?:[a-z].*>|!--)`,"i")},mKo=/^(?:[ \t]*(?:\n|$))+/,pKo=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,IKo=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,iU=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,CKo=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,q3e=/(?:[*+-]|\d{1,9}[.)])/,nTt=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,oTt=pl(nTt).replace(/bull/g,q3e).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),fKo=pl(nTt).replace(/bull/g,q3e).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),W3e=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,yKo=/^[^\n]+/,j3e=/(?!\s*\])(?:\\.|[^\[\]\\])+/,EKo=pl(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",j3e).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),xKo=pl(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,q3e).getRegex(),Pie="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",X3e=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,BKo=pl("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",X3e).replace("tag",Pie).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),iTt=pl(W3e).replace("hr",iU).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Pie).getRegex(),QKo=pl(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",iTt).getRegex(),$3e={blockquote:QKo,code:pKo,def:EKo,fences:IKo,heading:CKo,hr:iU,html:BKo,lheading:oTt,list:xKo,newline:mKo,paragraph:iTt,table:oU,text:yKo},rTt=pl("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",iU).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Pie).getRegex(),SKo={...$3e,lheading:fKo,table:rTt,paragraph:pl(W3e).replace("hr",iU).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",rTt).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Pie).getRegex()},bKo={...$3e,html:pl(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",X3e).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:oU,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:pl(W3e).replace("hr",iU).replace("heading",` *#{1,6} *[^
5796
5796
  ]`).replace("lheading",oTt).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},DKo=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,MKo=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,ATt=/^( {2,}|\\)\n(?!\s*$)/,wKo=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,vie=/[\p{P}\p{S}]/u,Z3e=/[\s\p{P}\p{S}]/u,sTt=/[^\s\p{P}\p{S}]/u,PKo=pl(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Z3e).getRegex(),aTt=/(?!~)[\p{P}\p{S}]/u,vKo=/(?!~)[\s\p{P}\p{S}]/u,NKo=/(?:[^\s\p{P}\p{S}]|~)/u,RKo=/\[[^[\]]*?\]\((?:\\.|[^\\\(\)]|\((?:\\.|[^\\\(\)])*\))*\)|`[^`]*?`|<[^<>]*?>/g,cTt=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,TKo=pl(cTt,"u").replace(/punct/g,vie).getRegex(),kKo=pl(cTt,"u").replace(/punct/g,aTt).getRegex(),lTt="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",FKo=pl(lTt,"gu").replace(/notPunctSpace/g,sTt).replace(/punctSpace/g,Z3e).replace(/punct/g,vie).getRegex(),LKo=pl(lTt,"gu").replace(/notPunctSpace/g,NKo).replace(/punctSpace/g,vKo).replace(/punct/g,aTt).getRegex(),HKo=pl("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,sTt).replace(/punctSpace/g,Z3e).replace(/punct/g,vie).getRegex(),GKo=pl(/\\(punct)/,"gu").replace(/punct/g,vie).getRegex(),OKo=pl(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),KKo=pl(X3e).replace("(?:-->|$)","-->").getRegex(),UKo=pl("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",KKo).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Nie=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,YKo=pl(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label",Nie).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),gTt=pl(/^!?\[(label)\]\[(ref)\]/).replace("label",Nie).replace("ref",j3e).getRegex(),uTt=pl(/^!?\[(ref)\](?:\[\])?/).replace("ref",j3e).getRegex(),zKo=pl("reflink|nolink(?!\\()","g").replace("reflink",gTt).replace("nolink",uTt).getRegex(),e6e={_backpedal:oU,anyPunctuation:GKo,autolink:OKo,blockSkip:RKo,br:ATt,code:MKo,del:oU,emStrongLDelim:TKo,emStrongRDelimAst:FKo,emStrongRDelimUnd:HKo,escape:DKo,link:YKo,nolink:uTt,punctuation:PKo,reflink:gTt,reflinkSearch:zKo,tag:UKo,text:wKo,url:oU},VKo={...e6e,link:pl(/^!?\[(label)\]\((.*?)\)/).replace("label",Nie).getRegex(),reflink:pl(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Nie).getRegex()},t6e={...e6e,emStrongRDelimAst:LKo,emStrongLDelim:kKo,url:pl(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,"i").replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/},JKo={...t6e,br:pl(ATt).replace("{2,}","*").getRegex(),text:pl(t6e.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Rie={normal:$3e,gfm:SKo,pedantic:bKo},rU={normal:e6e,gfm:t6e,breaks:JKo,pedantic:VKo},qKo={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},dTt=t=>qKo[t];function wS(t,e){if(e){if(Gf.escapeTest.test(t))return t.replace(Gf.escapeReplace,dTt)}else if(Gf.escapeTestNoEncode.test(t))return t.replace(Gf.escapeReplaceNoEncode,dTt);return t}function hTt(t){try{t=encodeURI(t).replace(Gf.percentDecode,"%")}catch{return null}return t}function _Tt(t,e){const n=t.replace(Gf.findPipe,(r,A,s)=>{let a=!1,c=A;for(;--c>=0&&s[c]==="\\";)a=!a;return a?"|":" |"}),o=n.split(Gf.splitPipe);let i=0;if(o[0].trim()||o.shift(),o.length>0&&!o.at(-1)?.trim()&&o.pop(),e)if(o.length>e)o.splice(e);else for(;o.length<e;)o.push("");for(;i<o.length;i++)o[i]=o[i].trim().replace(Gf.slashPipe,"|");return o}function AU(t,e,n){const o=t.length;if(o===0)return"";let i=0;for(;i<o&&t.charAt(o-i-1)===e;)i++;return t.slice(0,o-i)}function WKo(t,e){if(t.indexOf(e[1])===-1)return-1;let n=0;for(let o=0;o<t.length;o++)if(t[o]==="\\")o++;else if(t[o]===e[0])n++;else if(t[o]===e[1]&&(n--,n<0))return o;return n>0?-2:-1}function mTt(t,e,n,o,i){const r=e.href,A=e.title||null,s=t[1].replace(i.other.outputLinkReplace,"$1");o.state.inLink=!0;const a={type:t[0].charAt(0)==="!"?"image":"link",raw:n,href:r,title:A,text:s,tokens:o.inlineTokens(s)};return o.state.inLink=!1,a}function jKo(t,e,n){const o=t.match(n.other.indentCodeCompensation);if(o===null)return e;const i=o[1];return e.split(`
@@ -5867,4 +5867,4 @@ Please report this to https://github.com/markedjs/marked.`,t){const o="<p>An err
5867
5867
  rf-max-h-[90vh] rf-overflow-y-auto
5868
5868
  `,children:J.jsx("div",{className:"rf-relative rf-w-full",children:n==="initial"&&J.jsx(kUo,{onCancel:e,packageReleaseId:r??"",signIn:A??(()=>{}),isLoggedIn:s})})})})}),KUo=({isOpen:t,onClose:e,stage:n,setStage:o,signIn:i,isLoggedIn:r})=>{const A=Yu(s=>s.circuitJson);return J.jsx(OUo,{signIn:i,isOpen:t,onClose:e,stage:n,setStage:o,circuitJson:A,isLoggedIn:r??!1})},UUo=()=>{const[t,e]=j.useState(!1),[n,o]=j.useState("initial");return{isOpen:t,stage:n,open:()=>e(!0),close:()=>{e(!1),o("initial")},setStage:o,OrderDialog:KUo}};async function TTt(){const t=await fetch(`${Qf}/files/list`),{file_list:e}=await t.json(),n=new Map;for(const o of e){const r=await(await fetch(`${Qf}/files/get?file_path=${encodeURIComponent(o.file_path)}`)).json();(r.file?.text_content||r.file?.binary_content_b64)&&n.set(o.file_path,{text_content:r.file.text_content,binary_content_b64:r.file.binary_content_b64})}return n}const YUo="https://api.tscircuit.com/bug_reports/view?bug_report_id=",zUo=t=>`${YUo}${t}`,VUo=t=>{const[e,n]=j.useState(!1),[o,i]=j.useState(!1),[r,A]=j.useState(null),[s,a]=j.useState(null),[c,l]=j.useState([]),g=j.useRef(null),[u,h]=j.useState(null),[d,_]=j.useState(0),p=t?.onLoginRequired,m=j.useMemo(()=>kZ()?!0:typeof document>"u"?!1:document.cookie.split(";").some(x=>x.trim().startsWith("session=")),[e]);j.useEffect(()=>{if(e&&!u&&g.current){const x=typeof window<"u"?window.__TSCIRCUIT_LAST_EXECUTION_ERROR:void 0;x&&(g.current.value=`I'm getting this execution error:
5869
5869
 
5870
- ${x}`)}},[e,u]),j.useEffect(()=>{e&&!u&&TTt().then(x=>{_(x.size)}).catch(x=>{console.error("Failed to fetch file count",x),_(0)})},[e,u]);const C=j.useCallback(()=>{A(null),h(null),a(null),l([]),g.current&&(g.current.value=""),n(!0)},[]),I=j.useCallback(()=>{n(!1)},[]),f=j.useCallback(async()=>{i(!0),A(null),a(null),l([]);const x=lM(),B=g.current?.value||"";try{const S=await TTt();if(S.size===0){zA.error("No project files available to include in the bug report"),i(!1);return}const D=new Date(Date.now()+1440*60*1e3).toISOString(),F=(await x.post("bug_reports/create",{json:{text:B.trim()||void 0,is_auto_deleted:!0,delete_at:D}}).json()).bug_report.bug_report_id,R=Array.from(S.entries()),H=[];for(let K=0;K<R.length;K++){const[V,W]=R[K];a({current:K+1,total:R.length,currentFile:V});try{const X={bug_report_id:F,file_path:V};W.text_content&&(X.content_text=W.text_content),W.binary_content_b64&&(X.content_base64=W.binary_content_b64),await x.post("bug_reports/upload_file",{json:X})}catch(X){const ie=X instanceof cM?`HTTP ${X.response.status}`:X instanceof Error?X.message:"Upload failed";H.push({filePath:V,message:ie}),l([...H])}}a(null);const G=zUo(F);h({bugReportUrl:G})}catch(S){if(console.error("Failed to submit bug report",S),S instanceof cM)if(S.response.status===401)if(m){const D="Your session has expired. Please sign in again to continue.";A(D),zA.error(D),p&&(I(),p())}else{const D="You must be logged in to report a bug. Please sign in via cli and try again.";A(D),zA.error(D),setTimeout(()=>{p&&(I(),p())},1e3)}else{const D=`Failed to submit bug report (${S.response.status})`;A(D),zA.error(D)}else if(S instanceof Error)A(S.message),zA.error(S.message);else{const D="Failed to submit bug report";A(D),zA.error(D)}}finally{i(!1)}},[m,p]);return{BugReportDialog:j.useMemo(()=>{const x=s?Math.round(s.current/s.total*100):0;return J.jsx(bRt,{open:e,onOpenChange:B=>{B?(A(null),h(null),a(null),l([]),n(!0)):o||I()},children:J.jsxs(C3e,{children:[J.jsxs(f3e,{children:[J.jsx(E3e,{children:u?"Bug Report Created":"Report Bug"}),J.jsx(x3e,{asChild:!0,children:u?J.jsxs("div",{className:"rf-text-left rf-space-y-3 rf-text-sm",children:[J.jsx("p",{children:"Bug report created successfully."}),c.length>0&&J.jsxs("div",{className:"rf-bg-red-50 rf-border rf-border-red-200 rf-rounded rf-p-2 rf-max-h-28 rf-overflow-y-auto rf-overflow-x-hidden",children:[J.jsxs("p",{className:"rf-text-red-700 rf-font-medium rf-text-xs rf-mb-1",children:[c.length," file(s) failed:"]}),c.map((B,S)=>J.jsxs("div",{className:"rf-text-red-600 rf-text-xs rf-mb-0.5",title:`${B.filePath}: ${B.message}`,children:[J.jsx("span",{className:"rf-font-medium rf-break-all",children:B.filePath.split("/").pop()}),J.jsx("span",{className:"rf-text-red-500 rf-block rf-truncate",children:B.message})]},S))]}),J.jsx("div",{children:J.jsx("a",{className:"rf-text-blue-600 hover:rf-underline",href:u.bugReportUrl,target:"_blank",rel:"noreferrer",children:"View bug report"})}),J.jsxs("p",{children:["Please share this link privately with tscircuit staff so we can help debug. Join the",J.jsx("a",{className:"rf-ml-1 rf-text-blue-600 hover:rf-underline",href:"https://tscircuit.com/join",target:"_blank",rel:"noreferrer",children:"tscircuit Discord"}),"."]})]}):J.jsx("div",{className:"rf-text-left rf-space-y-3 rf-text-sm",children:s?J.jsxs("div",{className:"rf-space-y-2 rf-overflow-hidden",children:[J.jsxs("div",{className:"rf-flex rf-justify-between rf-text-xs",children:[J.jsx("span",{children:"Uploading files..."}),J.jsxs("span",{children:[s.current,"/",s.total]})]}),J.jsx("div",{className:"rf-w-full rf-h-2 rf-bg-gray-200 rf-rounded-full rf-overflow-hidden",children:J.jsx("div",{className:"rf-h-full rf-bg-blue-500 rf-transition-all rf-duration-150",style:{width:`${x}%`}})}),J.jsx("p",{className:"rf-text-xs rf-text-gray-500 rf-break-all rf-truncate rf-w-full rf-max-w-full",children:`${s.currentFile.slice(0,60)}${s.currentFile.length>60?"...":""}`}),c.length>0&&J.jsx("div",{className:"rf-bg-red-50 rf-border rf-border-red-200 rf-rounded rf-p-2 rf-max-h-20 rf-overflow-y-auto rf-overflow-x-hidden",children:c.map((B,S)=>J.jsxs("div",{className:"rf-text-red-600 rf-text-xs rf-mb-0.5",title:`${B.filePath}: ${B.message}`,children:[J.jsx("span",{className:"rf-font-medium rf-break-all",children:B.filePath.split("/").pop()}),J.jsx("span",{className:"rf-text-red-500 rf-block rf-truncate",children:B.message})]},S))})]}):J.jsxs(J.Fragment,{children:[J.jsxs("p",{children:["Reporting a bug will upload your entire project",d>0?` (${d} file${d===1?"":"s"})`:""," ","to tscircuit support."]}),J.jsxs("div",{className:"rf-space-y-2",children:[J.jsx("label",{htmlFor:"bug-description",className:"rf-block rf-font-medium",children:"Description (optional)"}),J.jsx("textarea",{ref:g,id:"bug-description",className:"rf-w-full rf-min-h-[100px] rf-px-3 rf-py-2 rf-text-sm rf-border rf-border-gray-300 rf-rounded-md focus:rf-outline-none focus:rf-ring-2 focus:rf-ring-blue-500",placeholder:"Describe the issue you're experiencing...",disabled:o})]}),J.jsxs("p",{children:["Share the generated bug report link privately with tscircuit staff so we can help debug your issue. You can also reach out on our",J.jsx("a",{className:"rf-ml-1 rf-text-blue-600 hover:rf-underline",href:"https://tscircuit.com/join",target:"_blank",rel:"noreferrer",children:"Discord community"}),"."]}),!m&&J.jsx("p",{className:"rf-text-red-600",children:"You appear to be logged out. Please log in before reporting a bug or the upload will fail."}),r&&J.jsx("p",{className:"rf-text-red-600",children:r})]})})})]}),J.jsx(y3e,{children:u?J.jsx("button",{type:"button",className:oT(),onClick:()=>{I()},children:"Close"}):J.jsxs(J.Fragment,{children:[J.jsx(B3e,{disabled:o,onClick:()=>{o||I()},children:"Cancel"}),!m&&p?J.jsx("button",{type:"button",className:oT(),onClick:B=>{B.preventDefault(),I(),p()},children:"Sign In"}):J.jsx("button",{type:"button",className:rB(oT(),o&&"rf-opacity-70 rf-cursor-not-allowed"),disabled:o,onClick:B=>{B.preventDefault(),f()},children:o?"Reporting...":"Upload & Report"})]})})]})},"bug-report-dialog")},[e,o,I,r,u,d,m,f,p,s,c]),openBugReportDialog:C}};function JUo({open:t,onOpenChange:e,onExport:n}){const[o,i]=j.useState(!1),r=()=>{n({includeSilkscreen:o}),e(!1)},A=()=>{e(!1)};return J.jsx(DT,{open:t,onOpenChange:e,children:J.jsxs(j3,{children:[J.jsxs(X3,{children:[J.jsx($3,{children:"LightBurn Export Options"}),J.jsx(MT,{children:"Configure export settings for PCB laser ablation with LightBurn"})]}),J.jsx("div",{className:"rf-flex rf-flex-col rf-gap-4 rf-py-4",children:J.jsxs("div",{className:"rf-flex rf-items-center rf-space-x-2",children:[J.jsx(ZK,{id:"includeSilkscreen",checked:o,onCheckedChange:s=>i(s===!0)}),J.jsx("label",{htmlFor:"includeSilkscreen",className:"rf-text-xs rf-font-medium rf-leading-none peer-disabled:rf-cursor-not-allowed peer-disabled:rf-opacity-70",children:"Include silkscreen layer"})]})}),J.jsxs(eU,{children:[J.jsx(ta,{variant:"outline",onClick:A,children:"Cancel"}),J.jsx(ta,{onClick:r,children:"Export"})]})]})})}const qUo=/#(\d+)/,WUo=t=>{const e=t.match(qUo);if(!e)return null;const n=Number.parseInt(e[1],10);return Number.isFinite(n)?n:null},jUo=t=>{if(typeof t=="number")return Number.isFinite(t)?t:null;if(typeof t=="string"){const e=new Date(t).getTime();return Number.isFinite(e)?e:null}return null},XUo=t=>{if(!t)return null;let e=null,n=-1,o=-1;for(const[i,r]of Object.entries(t)){const A=WUo(i),s=jUo(r.createdAt);if(A!==null){A>n&&(n=A,e={key:i,value:r});continue}if(n===-1){if(s!==null&&s>o){o=s,e={key:i,value:r};continue}e||(e={key:i,value:r})}}return e},cU=t=>{const e=yie(be=>be.lastRunEvalVersion),n=Yu(be=>be.currentMainComponentPath),[o,i]=j.useState(null),[r,A]=j.useState(!1),[s,a]=j.useState(!0),[c,l]=j.useState(!1),[g,u]=j.useState(null),[h,d]=j.useState(null),[_,p]=j.useState(!1),[m,C]=j.useState(null),[I,f]=j.useState(null),[y,x]=j.useState(!1),[B,S]=j.useState(!1),[D,w]=j.useState(!1),[F,R]=j.useState(null),H=UUo(),G=Yu(be=>be.pushEvent),K=Yu(be=>be.recentEvents),V=j.useMemo(()=>Date.now(),[]);XHo(be=>{if(!(new Date(be.created_at).valueOf()<V+500)){if(be.event_type==="FILE_UPDATED"){A(!0);return}if(be.event_type==="SNIPPET_SAVED"){A(!1),a(!1),C("Snippet saved successfully."),x(!1);return}be.event_type==="REQUEST_EXPORT"&&(S(!0),C("Export processing..."),x(!1)),be.event_type==="EXPORT_CREATED"&&(C(`Export created: ${be.exportFilePath}`),x(!1),S(!1))}}),j.useEffect(()=>{if(!c||g===null)return;const be=K.filter(pe=>new Date(pe.created_at).valueOf()>g),ue=be.find(pe=>pe.event_type==="FAILED_TO_SAVE_SNIPPET"),Be=be.find(pe=>pe.event_type==="SNIPPET_SAVED");ue&&(l(!1),u(null),f(ue.message??"Failed to save snippet. See console for error."),console.error(ue.message),x(!0),ue.error_code==="SNIPPET_UNSET"&&ue.available_snippet_names&&(d(ue.available_snippet_names),p(!0))),Be&&(l(!1),u(null),C("Snippet saved successfully."),x(!1))},[K,c]);const W=async()=>{l(!0),u(Date.now()),C(null),x(!1),await G({event_type:"REQUEST_TO_SAVE_SNIPPET",snippet_name:o})},ie=Yu(be=>be.circuitJson)??t.circuitJson,[se,ee]=j.useState(!1),[oe,ae]=j.useState(!1),{BugReportDialog:re,openBugReportDialog:le}=VUo({onLoginRequired:t.onLoginRequired}),fe=async be=>{F&&(await eTt({circuitJson:F.circuitJson,projectName:F.projectName,options:be}),R(null))},ye=j.useMemo(()=>XUo(t.autoroutingLog),[t.autoroutingLog]);return J.jsxs(J.Fragment,{children:[J.jsxs("div",{className:"rf-flex rf-items-center rf-gap-1 rf-flex-shrink-0",children:[J.jsxs(woe,{children:[J.jsx(Poe,{asChild:!0,children:J.jsx("div",{className:"rf-whitespace-nowrap rf-text-xs font-medium rf-p-2 rf-mx-1 rf-cursor-pointer rf-relative",children:"File"})}),J.jsxs(TK,{className:"rf-z-[101]",children:[!t.isWebEmbedded&&J.jsxs(J.Fragment,{children:[J.jsx(Sh,{className:"rf-text-xs",onSelect:W,disabled:c,children:c?"Saving...":"Push"}),parseInt(window.location.port)>5e3&&J.jsx(Sh,{className:"rf-text-xs",onSelect:()=>{H.open()},children:"Order"}),J.jsx(Sh,{className:"rf-text-xs",onSelect:()=>ee(!0),disabled:c,children:"Import"}),J.jsx(Sh,{className:"rf-text-xs",onSelect:()=>{if(!kZ()){zA.error("Requires tscircuit token");return}ae(!0)},children:"AI Review"})]}),!t.isWebEmbedded&&t.onLoginRequired&&J.jsx(Sh,{className:"rf-text-xs",onSelect:()=>{t.onLoginRequired?.()},children:"Sign In"}),!t.isWebEmbedded&&J.jsxs(RK,{children:[J.jsx(mT,{className:"rf-text-xs",children:"Report Bug"}),J.jsx(NK,{children:J.jsxs(pT,{children:[J.jsx(Sh,{className:"rf-text-xs",onSelect:()=>{le()},children:"Report Entire Circuit"}),J.jsx(Sh,{className:"rf-text-xs",disabled:!ye||!t.onReportAutoroutingLog,onSelect:()=>{!ye||!t.onReportAutoroutingLog||t.onReportAutoroutingLog(ye.key,{simpleRouteJson:ye.value.simpleRouteJson})},children:"Report Autorouter Bug"})]})})]}),J.jsxs(RK,{children:[J.jsx(mT,{className:"rf-text-xs",disabled:B,children:B?"Exporting...":"Export"}),J.jsx(NK,{children:J.jsx(pT,{children:dKo.map((be,ue)=>J.jsx(Sh,{onSelect:()=>{if(!ie){zA.error("No Circuit JSON to export");return}let Be="Untitled";if(n){const Je=n.split("/").pop();Je&&(Be=Je.replace(/\.[^.]+$/,""))}const pe=t.projectName??o??Be,Ge=ye?.value.simpleRouteJson;if(be.name==="LightBurn"){R({circuitJson:ie,projectName:pe}),w(!0);return}hKo({exportName:be.name,circuitJson:ie,simpleRouteJson:Ge,projectName:pe?.replace(/\.(board|circuit)$/,"")})},disabled:B||be.name==="Simple Route JSON"&&!ye,children:J.jsx("span",{className:"rf-text-xs",children:be.name})},ue))})})]}),!t.isWebEmbedded&&J.jsxs(RK,{children:[J.jsx(mT,{className:"rf-text-xs",children:"Advanced"}),J.jsx(NK,{children:J.jsxs(pT,{children:[J.jsx(Sh,{className:"rf-flex rf-items-center rf-gap-2",children:J.jsxs("div",{className:"rf-flex rf-items-center rf-gap-2",children:[J.jsx(ZK,{id:"load-latest-eval",checked:t.shouldLoadLatestEval,onCheckedChange:be=>{t.onChangeShouldLoadLatestEval?.(be===!0)}}),J.jsx("label",{htmlFor:"load-latest-eval",className:"rf-text-xs rf-cursor-pointer",children:"Force Latest @tscircuit/eval"})]})}),e&&J.jsx(Sh,{className:"rf-flex rf-items-center rf-gap-2",children:J.jsx("div",{className:"rf-flex rf-items-center rf-gap-2",children:J.jsxs("span",{className:"rf-text-xs",children:["@tscircuit/eval@",e]})})}),J.jsx(Sh,{className:"rf-flex rf-items-center rf-gap-2",children:J.jsx("div",{className:"rf-flex rf-items-center rf-gap-2",children:J.jsxs("span",{className:"rf-text-xs",children:["@tscircuit/runframe@",qHo.version]})})}),J.jsx(Sh,{className:"rf-flex rf-items-center rf-gap-2",onClick:()=>{window.open("/api/admin","_blank")},children:J.jsx("div",{className:"rf-flex rf-items-center rf-gap-2",children:J.jsx("span",{className:"rf-text-xs",children:"CLI Admin Panel"})})})]})})]})]}),J.jsx(bRt,{open:y,onOpenChange:x,children:J.jsxs(C3e,{children:[J.jsxs(f3e,{children:[J.jsx(E3e,{children:"Error Saving Snippet"}),J.jsx(x3e,{children:I})]}),J.jsx(y3e,{children:J.jsx(B3e,{onClick:()=>x(!1),children:"Dismiss"})})]})}),J.jsx(jHo,{snippetNames:h??[],onSelect:async be=>{l(!0),u(Date.now()),i(be),await G({event_type:"REQUEST_TO_SAVE_SNIPPET",snippet_name:be}),p(!1)},onCancel:()=>p(!1),isOpen:_})]}),J.jsxs(woe,{children:[J.jsx(Poe,{asChild:!0,children:J.jsx("div",{className:"rf-whitespace-nowrap rf-text-xs font-medium rf-p-2 rf-mx-1 rf-cursor-pointer rf-relative",children:"View"})}),J.jsx(TK,{className:"rf-z-[104]",children:J.jsxs(RK,{children:[J.jsx(mT,{className:"rf-text-xs",children:"Schematic"}),J.jsx(NK,{children:J.jsxs(pT,{children:[J.jsx(Sh,{className:"rf-flex rf-items-center rf-gap-2",onSelect:be=>be.preventDefault(),children:J.jsxs("div",{className:"rf-flex rf-items-center rf-gap-2",children:[J.jsx(ZK,{id:"show-schematic-ports",checked:t.showSchematicPorts,onCheckedChange:be=>{t.onChangeShowSchematicPorts?.(be===!0)}}),J.jsx("label",{htmlFor:"show-schematic-ports",className:"rf-text-xs rf-cursor-pointer",children:"Show Schematic Ports"})]})}),J.jsx(Sh,{className:"rf-flex rf-items-center rf-gap-2",onSelect:be=>be.preventDefault(),children:J.jsxs("div",{className:"rf-flex rf-items-center rf-gap-2",children:[J.jsx(ZK,{id:"show-schematic-grid",checked:t.showSchematicDebugGrid,onCheckedChange:be=>{t.onChangeShowSchematicDebugGrid?.(be===!0)}}),J.jsx("label",{htmlFor:"show-schematic-grid",className:"rf-text-xs rf-cursor-pointer",children:"Show Schematic Grid"})]})})]})})]})})]})]}),re,J.jsx(JUo,{open:D,onOpenChange:w,onExport:fe}),J.jsx($Rt,{isOpen:se,onClose:()=>ee(!1)}),J.jsx(ZKo,{isOpen:oe,onClose:()=>ae(!1),packageName:o}),J.jsx(C5t,{position:"top-center",reverseOrder:!1,containerStyle:{zIndex:1e5},toastOptions:{className:"rf-break-all",style:{zIndex:1e5}}}),J.jsx(H.OrderDialog,{isOpen:H.isOpen,onClose:H.close,stage:H.stage,setStage:H.setStage})]})};var $Uo=Object.defineProperty,ZUo=(t,e)=>$Uo(t,"name",{value:e,configurable:!0}),eYo=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),tYo=j.forwardRef(ZUo(function(e,n){return J.jsx(Oa.span,{...e,ref:n,style:{...eYo,...e.style}})},"VisuallyHidden")),nYo=tYo,oYo=Object.defineProperty,_I=(t,e)=>oYo(t,"name",{value:e,configurable:!0}),[c6e,Gjo]=y2("Tooltip",[cT]),l6e=cT(),iYo="TooltipProvider",rYo=700,g6e="tooltip.open",[AYo,u6e]=c6e(iYo),sYo=_I(t=>{const{__scopeTooltip:e,delayDuration:n=rYo,skipDelayDuration:o=300,disableHoverableContent:i=!1,children:r}=t,A=j.useRef(!0),s=j.useRef(!1),a=j.useRef(0);return j.useEffect(()=>{const c=a.current;return()=>window.clearTimeout(c)},[]),J.jsx(AYo,{scope:e,isOpenDelayedRef:A,delayDuration:n,onOpen:j.useCallback(()=>{o<=0||(window.clearTimeout(a.current),A.current=!1)},[o]),onClose:j.useCallback(()=>{o<=0||(window.clearTimeout(a.current),a.current=window.setTimeout(()=>A.current=!0,o))},[o]),isPointerInTransitRef:s,onPointerInTransitChange:j.useCallback(c=>{s.current=c},[]),disableHoverableContent:i,children:r})},"TooltipProvider"),d6e="Tooltip",[aYo,Jie]=c6e(d6e),cYo=_I(t=>{const{__scopeTooltip:e,children:n,open:o,defaultOpen:i,onOpenChange:r,disableHoverableContent:A,delayDuration:s}=t,a=u6e(d6e,t.__scopeTooltip),c=l6e(e),[l,g]=j.useState(null),[u,h]=j.useState(void 0),d=rp(),_=j.useRef(0),p=A??a.disableHoverableContent,m=s??a.delayDuration,C=j.useRef(!1),[I,f]=Ub({prop:o,defaultProp:i??!1,onChange:_I(w=>{w?(a.onOpen(),document.dispatchEvent(new CustomEvent(g6e))):a.onClose(),r?.(w)},"onChange"),caller:d6e}),y=j.useMemo(()=>I?C.current?"delayed-open":"instant-open":"closed",[I]),x=j.useCallback(()=>{window.clearTimeout(_.current),_.current=0,C.current=!1,f(!0)},[f]),B=j.useCallback(()=>{window.clearTimeout(_.current),_.current=0,f(!1)},[f]),S=j.useCallback(()=>{window.clearTimeout(_.current),_.current=window.setTimeout(()=>{C.current=!0,f(!0),_.current=0},m)},[m,f]);j.useEffect(()=>()=>{_.current&&(window.clearTimeout(_.current),_.current=0)},[]);const D=u??d;return J.jsx(_oe,{...c,children:J.jsx(aYo,{scope:e,contentId:D,setContentId:h,open:I,stateAttribute:y,trigger:l,onTriggerChange:g,onTriggerEnter:j.useCallback(()=>{a.isOpenDelayedRef.current?S():x()},[a.isOpenDelayedRef,S,x]),onTriggerLeave:j.useCallback(()=>{p?B():(window.clearTimeout(_.current),_.current=0)},[B,p]),onOpen:x,onClose:B,disableHoverableContent:p,children:n})})},"Tooltip"),kTt="TooltipTrigger",lYo=j.forwardRef(_I(function(e,n){const{__scopeTooltip:o,...i}=e,r=Jie(kTt,o),A=u6e(kTt,o),s=l6e(o),a=j.useRef(null),c=dl(n,a,r.onTriggerChange),l=j.useRef(!1),g=j.useRef(!1),u=j.useCallback(()=>l.current=!1,[]);return j.useEffect(()=>()=>document.removeEventListener("pointerup",u),[u]),J.jsx(CPe,{asChild:!0,...s,children:J.jsx(Oa.button,{"aria-describedby":r.open?r.contentId:void 0,"data-state":r.stateAttribute,...i,ref:c,onPointerMove:Pr(e.onPointerMove,h=>{h.pointerType!=="touch"&&!g.current&&!A.isPointerInTransitRef.current&&(r.onTriggerEnter(),g.current=!0)}),onPointerLeave:Pr(e.onPointerLeave,()=>{r.onTriggerLeave(),g.current=!1}),onPointerDown:Pr(e.onPointerDown,()=>{r.open&&r.onClose(),l.current=!0,document.addEventListener("pointerup",u,{once:!0})}),onFocus:Pr(e.onFocus,()=>{l.current||r.onOpen()}),onBlur:Pr(e.onBlur,r.onClose),onClick:Pr(e.onClick,r.onClose)})})},"TooltipTrigger")),gYo="TooltipPortal",[Ojo,uYo]=c6e(gYo,{forceMount:void 0}),lU="TooltipContent",dYo=j.forwardRef(_I(function(e,n){const o=uYo(lU,e.__scopeTooltip),{forceMount:i=o.forceMount,side:r="top",...A}=e,s=Jie(lU,e.__scopeTooltip);return J.jsx(JE,{present:i||s.open,children:s.disableHoverableContent?J.jsx(FTt,{side:r,...A,ref:n}):J.jsx(hYo,{side:r,...A,ref:n})})},"TooltipContent")),hYo=j.forwardRef(_I(function(e,n){const o=Jie(lU,e.__scopeTooltip),i=u6e(lU,e.__scopeTooltip),r=j.useRef(null),A=dl(n,r),[s,a]=j.useState(null),{trigger:c,onClose:l}=o,g=r.current,{onPointerInTransitChange:u}=i,h=j.useCallback(()=>{a(null),u(!1)},[u]),d=j.useCallback((_,p)=>{const m=_.currentTarget,C={x:_.clientX,y:_.clientY},I=LTt(C,m.getBoundingClientRect()),f=HTt(C,I),y=GTt(p.getBoundingClientRect()),x=KTt([...f,...y]);a(x),u(!0)},[u]);return j.useEffect(()=>()=>h(),[h]),j.useEffect(()=>{if(c&&g){const _=_I(m=>d(m,g),"handleTriggerLeave"),p=_I(m=>d(m,c),"handleContentLeave");return c.addEventListener("pointerleave",_),g.addEventListener("pointerleave",p),()=>{c.removeEventListener("pointerleave",_),g.removeEventListener("pointerleave",p)}}},[c,g,d,h]),j.useEffect(()=>{if(s){const _=_I(p=>{const m=p.target,C={x:p.clientX,y:p.clientY},I=c?.contains(m)||g?.contains(m),f=!OTt(C,s);I?h():f&&(h(),l())},"handleTrackPointerGrace");return document.addEventListener("pointermove",_),()=>document.removeEventListener("pointermove",_)}},[c,g,s,l,h]),J.jsx(FTt,{...e,ref:A})},"TooltipContentHoverable")),_Yo=qgt("TooltipContent"),FTt=j.forwardRef(_I(function(e,n){const{__scopeTooltip:o,children:i,"aria-label":r,id:A,onEscapeKeyDown:s,onPointerDownOutside:a,...c}=e,l=Jie(lU,o),g=l6e(o),{onClose:u}=l;j.useEffect(()=>(document.addEventListener(g6e,u),()=>document.removeEventListener(g6e,u)),[u]),j.useEffect(()=>{if(l.trigger){const d=_I(_=>{_.target instanceof Node&&_.target.contains(l.trigger)&&u()},"handleScroll");return window.addEventListener("scroll",d,{capture:!0}),()=>window.removeEventListener("scroll",d,{capture:!0})}},[l.trigger,u]);const{setContentId:h}=l;return ty(()=>(h(A),()=>{h(void 0)}),[A,h]),J.jsx(toe,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:s,onPointerDownOutside:a,onFocusOutside:d=>d.preventDefault(),onDismiss:u,children:J.jsxs(fPe,{"data-state":l.stateAttribute,role:r?void 0:"tooltip",id:r?void 0:l.contentId,...g,...c,ref:n,style:{...c.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[J.jsx(_Yo,{children:i}),r?J.jsx(nYo,{id:l.contentId,role:"tooltip",children:r}):null]})})},"TooltipContentImpl"));function LTt(t,e){const n=Math.abs(e.top-t.y),o=Math.abs(e.bottom-t.y),i=Math.abs(e.right-t.x),r=Math.abs(e.left-t.x);switch(Math.min(n,o,i,r)){case r:return"left";case i:return"right";case n:return"top";case o:return"bottom";default:throw new Error("unreachable")}}_I(LTt,"getExitSideFromRect");function HTt(t,e,n=5){const o=[];switch(e){case"top":o.push({x:t.x-n,y:t.y+n},{x:t.x+n,y:t.y+n});break;case"bottom":o.push({x:t.x-n,y:t.y-n},{x:t.x+n,y:t.y-n});break;case"left":o.push({x:t.x+n,y:t.y-n},{x:t.x+n,y:t.y+n});break;case"right":o.push({x:t.x-n,y:t.y-n},{x:t.x-n,y:t.y+n});break}return o}_I(HTt,"getPaddedExitPoints");function GTt(t){const{top:e,right:n,bottom:o,left:i}=t;return[{x:i,y:e},{x:n,y:e},{x:n,y:o},{x:i,y:o}]}_I(GTt,"getPointsFromRect");function OTt(t,e){const{x:n,y:o}=t;let i=!1;for(let r=0,A=e.length-1;r<e.length;A=r++){const s=e[r],a=e[A],c=s.x,l=s.y,g=a.x,u=a.y;l>o!=u>o&&n<(g-c)*(o-l)/(u-l)+c&&(i=!i)}return i}_I(OTt,"isPointInPolygon");function KTt(t){const e=t.slice();return e.sort((n,o)=>n.x<o.x?-1:n.x>o.x?1:n.y<o.y?-1:n.y>o.y?1:0),UTt(e)}_I(KTt,"getHull");function UTt(t){if(t.length<=1)return t.slice();const e=[];for(let o=0;o<t.length;o++){const i=t[o];for(;e.length>=2;){const r=e[e.length-1],A=e[e.length-2];if((r.x-A.x)*(i.y-A.y)>=(r.y-A.y)*(i.x-A.x))e.pop();else break}e.push(i)}e.pop();const n=[];for(let o=t.length-1;o>=0;o--){const i=t[o];for(;n.length>=2;){const r=n[n.length-1],A=n[n.length-2];if((r.x-A.x)*(i.y-A.y)>=(r.y-A.y)*(i.x-A.x))n.pop();else break}n.push(i)}return n.pop(),e.length===1&&n.length===1&&e[0].x===n[0].x&&e[0].y===n[0].y?e:e.concat(n)}_I(UTt,"getHullPresorted");var mYo=sYo,pYo=cYo,IYo=lYo,YTt=dYo;const h6e=mYo,_6e=pYo,m6e=IYo,qie=j.forwardRef(({className:t,sideOffset:e=4,...n},o)=>J.jsx(YTt,{ref:o,sideOffset:e,className:qi("z-50 overflow-hidden rounded-md bg-slate-900 px-3 py-1.5 text-xs text-slate-50 animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 dark:bg-slate-50 dark:text-slate-900",t),...n}));qie.displayName=YTt.displayName;const CYo="24b58135-86c7-4e4b-bf6e-cca862bc4b26",zTt="runframe-crisp-chat-script",fYo="tscircuit.com",gU=t=>{window.$crisp=window.$crisp||[],window.$crisp.push(t)},yYo=()=>{if(window.$crisp=window.$crisp||[],window.CRISP_WEBSITE_ID=CYo,window.__RUNFRAME_CRISP_CONFIGURED__||(window.__RUNFRAME_CRISP_CONFIGURED__=!0,gU(["do","chat:hide"]),gU(["on","chat:closed",()=>gU(["do","chat:hide"])])),!document.getElementById(zTt)){const t=document.createElement("script");t.id=zTt,t.src="https://client.crisp.chat/l.js",t.async=!0,document.head.appendChild(t)}},EYo=()=>{yYo(),gU(["do","chat:show"]),gU(["do","chat:open"])},xYo=({isCli:t,hostname:e=typeof window<"u"?window.location.hostname:void 0}={})=>e?.toLowerCase()===fYo?!1:!!t,BYo=()=>J.jsx(h6e,{children:J.jsxs(_6e,{children:[J.jsx(m6e,{asChild:!0,children:J.jsx(ta,{type:"button",variant:"ghost",size:"icon","aria-label":"Get Support or Give Feedback",onClick:EYo,className:"rf-h-8 rf-w-8",children:J.jsx(RPo,{className:"rf-h-4 rf-w-4 rf-text-gray-500"})})}),J.jsx(qie,{side:"bottom",children:"Get Support or Give Feedback"})]})}),QYo=["assembly","pinout","analog_simulation","bom","circuit_json","errors","render_log","solvers"],p6e=t=>t instanceof Error?t.message:"An unknown error occurred",VTt=({code:t,fsMap:e,onRunClicked:n=void 0,errorMessage:o,errorStack:i,circuitJson:r,autoroutingGraphics:A,showRightHeaderContent:s=!0,showCodeTab:a=!1,codeTabContent:c,showJsonTab:l=!0,showRenderLogTab:g=!0,onActiveTabChange:u,renderLog:h,showImportAndFormatButtons:d=!0,className:_,headerClassName:p,leftHeaderContent:m,readOnly:C,isStreaming:I,autoroutingLog:f,onReportAutoroutingLog:y,isRunningCode:x,hasCodeChangedSinceLastRun:B,onEditEvent:S,editEvents:D,defaultActiveTab:w,defaultTab:F,availableTabs:R,autoRotate3dViewerDisabled:H,showSchematicDebugGrid:G=!1,showSchematicPorts:K=!1,onChangeShowSchematicDebugGrid:V,onChangeShowSchematicPorts:W,showToggleFullScreen:X=!0,defaultToFullScreen:ie=!1,activeEffectName:se,allowSelectingVersion:ee=!0,showFileMenu:oe=!1,isWebEmbedded:ae=!1,isCli:re=!1,projectName:le,schematicSvgOptions:fe,hideSchematicInAnalogSimulation:ye=!1,onRerunWithDebug:be,solverEvents:ue,onPcbBoundsSelected:Be})=>{fie();const{versions:pe,latestVersion:Ge,lastRunEvalVersion:Je,search:nt,setSearch:Ie,selectVersion:Ze}=WHo(ee),Ke=j.useMemo(()=>r?r.filter(_t=>_t&&"error_type"in _t||_t.type.includes("error")):null,[r]),Ye=j.useMemo(()=>r?r.filter(_t=>_t&&"warning_type"in _t||_t.type.includes("warning")):null,[r]),qe=j.useMemo(()=>r?r.some(_t=>_t.type==="schematic_group"):!0,[r]),Le=j.useMemo(()=>r?.some(_t=>_t.type==="pcb_panel"),[r]),Se=j.useMemo(()=>!r||!x||Ke?.length?!1:r.some(Gt=>Gt.type==="simulation_experiment")&&!pjn(r),[r,Ke,x]),ve=j.useMemo(()=>Ke?.find(_t=>_t.type.startsWith("simulation_")),[Ke]);uRt({errorMessage:o,errorStack:i,circuitJsonErrors:Ke});const Pe=F??R?.[0]??"pcb",[ze,Xe]=J7("runframe-active-tab",w??Pe,w);dRt({source:"runframe",component:"CircuitJsonPreview",isWebEmbedded:ae,activeTab:ze});const[st,ct]=j.useState(null),[ut,lt]=j.useState(ie),[Ct,Dt]=j.useState(G),[pt,Nt]=j.useState(K),Ht=V?G:Ct,gn=W?K:pt,dn=V??Dt,Jt=W??Nt;OLo(ut);const Ce=j.useCallback(_t=>{Xe(_t),u?.(_t)},[u,Xe]),At=()=>{lt(!ut)};j.useEffect(()=>{o&&(ze!=="errors"&&ct(ze),Ce("errors"))},[o]),j.useEffect(()=>{(ze==="code"||ze==="errors")&&r&&!o&&Ce(st??w??F??R?.[0]??"pcb")},[r]);const ht=j.useCallback(_t=>{window.TSCIRCUIT_3D_OBJECT_REF=_t===null?void 0:_t},[]);return J.jsx("div",{className:qi("flex flex-col relative rf-overflow-x-hidden rf-h-full",_),children:J.jsx("div",{className:qi("rf-md:sticky rf-md:top-2 rf-h-full",ut&&"rf-fixed rf-top-0 rf-left-0 rf-w-full rf-h-full rf-bg-white rf-overflow-hidden"),children:J.jsxs(K1e,{value:ze,onValueChange:Ce,className:"rf-flex-grow rf-flex rf-flex-col rf-h-full",children:[J.jsxs("div",{className:qi("rf-flex rf-items-center rf-gap-2 rf-p-2 rf-pb-0",p),children:[m,oe&&!m&&J.jsx(cU,{isWebEmbedded:ae,circuitJson:r,projectName:le,autoroutingLog:f,onReportAutoroutingLog:y,showSchematicDebugGrid:Ht,onChangeShowSchematicDebugGrid:dn,showSchematicPorts:gn,onChangeShowSchematicPorts:Jt}),(m||oe)&&J.jsx("div",{className:"rf-flex-grow"}),!m&&!oe&&x&&J.jsx(SB,{className:"rf-w-4 rf-h-4 rf-animate-spin"}),!m&&!oe&&J.jsx("div",{className:"rf-flex-grow"}),h&&h.progress!==1&&!o&&J.jsxs("div",{className:"rf-flex rf-items-center rf-gap-2 rf-min-w-0 rf-max-w-xs",children:[se?J.jsx("div",{className:"rf-text-xs rf-text-gray-500 rf-truncate rf-min-w-0",title:se,children:se}):h.lastRenderEvent&&J.jsx("div",{className:"rf-text-xs rf-text-gray-500 rf-truncate rf-min-w-0",title:h.lastRenderEvent?.phase??"",children:h.lastRenderEvent?.phase??""}),J.jsx("div",{className:"rf-w-4 rf-h-4 rf-bg-blue-500 rf-opacity-50 rf-rounded-full rf-text-white rf-flex-shrink-0",children:J.jsx(SB,{className:"rf-w-4 rf-h-4 rf-animate-spin"})}),J.jsxs("div",{className:"rf-text-xs rf-font-bold rf-text-gray-700 rf-tabular-nums rf-flex-shrink-0",children:[((h.progress??0)*100).toFixed(1),"%"]})]}),s&&xYo({isCli:re})&&J.jsx(BYo,{}),s&&J.jsxs(FZ,{children:[a&&J.jsx(XQ,{value:"code",children:"Code"}),!R||R.includes("pcb")?J.jsxs(XQ,{value:"pcb",className:"rf-whitespace-nowrap",children:[r&&J.jsx("span",{className:qi("rf-inline-flex rf-items-center rf-justify-center rf-w-2 rf-h-2 rf-mr-1 rf-text-xs rf-font-bold rf-text-white rf-rounded-full",B?"rf-bg-gray-500":"rf-bg-blue-500")}),"PCB"]}):null,!R||R.includes("schematic")?J.jsxs(XQ,{value:"schematic",className:qi("rf-whitespace-nowrap",r&&!qe&&"rf-opacity-50"),disabled:r?!qe||Le:!1,children:[r&&J.jsx("span",{className:qi("rf-inline-flex rf-items-center rf-justify-center rf-w-2 rf-h-2 rf-mr-1 rf-text-xs rf-font-bold rf-text-white rf-rounded-full",B?"rf-bg-gray-500":"rf-bg-blue-500")}),"Schematic"]}):null,!R||R.includes("cad")?J.jsxs(XQ,{value:"cad",children:[r&&J.jsx("span",{className:qi("inline-flex items-center justify-center w-2 h-2 mr-1 text-xs font-bold text-white rounded-full",B?"rf-bg-gray-500":"rf-bg-blue-500")}),"3D"]}):null,!["pcb","cad","schematic"].includes(ze)&&J.jsx(XQ,{value:ze,children:kht(ze)}),J.jsxs(woe,{children:[J.jsx(Poe,{asChild:!0,children:J.jsxs("div",{className:"rf-whitespace-nowrap rf-p-2 rf-mr-1 rf-cursor-pointer rf-relative",children:[J.jsx(QPo,{className:"rf-w-4 rf-h-4"}),(Ke&&Ke.length>0||o)&&J.jsx("span",{className:"rf-inline-flex rf-absolute rf-top-[6px] rf-right-[4px] rf-items-center rf-justify-center rf-w-1 rf-h-1 rf-ml-2 rf-text-[8px] rf-font-bold rf-text-white rf-bg-red-500 rf-rounded-full"})]})}),J.jsxs(TK,{className:"rf-*:text-xs rf-z-[101]",children:[QYo.filter(_t=>!R||R.includes(_t)).map(_t=>J.jsxs(Sh,{onSelect:()=>Ce(_t),children:[ze!==_t&&J.jsx(kPt,{className:"rf-w-3 rf-h-3 rf-opacity-30"}),ze===_t&&J.jsx(L3,{className:"rf-w-3 rf-h-3"}),J.jsx("div",{className:"rf-pr-2",children:kht(_t)}),_t==="errors"&&(Ke&&Ke.length>0||o)&&J.jsx("span",{className:"rf-inline-flex rf-items-center rf-justify-center rf-w-3 rf-h-3 rf-ml-2 rf-text-[8px] rf-font-bold rf-text-white rf-bg-red-500 rf-rounded-full",children:o?1:Ke?.length}),_t==="solvers"&&ue&&ue.length>0&&J.jsx("span",{className:"rf-inline-flex rf-items-center rf-justify-center rf-min-w-[12px] rf-h-3 rf-px-1 rf-ml-2 rf-text-[8px] rf-font-bold rf-text-white rf-bg-blue-500 rf-rounded-full",children:ue.length})]},_t)),J.jsx(Sh,{disabled:!0,className:"rf-opacity-60 rf-cursor-default rf-select-none",children:J.jsxs("div",{className:"rf-pr-2 rf-text-xs rf-text-gray-500",children:["@tscircuit/runframe@",hRt.split(".").map((_t,Gt)=>Gt===2?parseInt(_t)+1:_t).join(".")]})}),ee?J.jsxs(RK,{onOpenChange:_t=>!_t&&Ie(""),children:[J.jsx(mT,{className:"rf-text-xs rf-opacity-60",children:J.jsxs("div",{className:"rf-pr-2 rf-text-xs rf-text-gray-500",children:["@tscircuit/eval@",Je??Ge??"latest"]})}),J.jsx(NK,{children:J.jsxs(pT,{className:"rf-*:text-xs rf-w-40 rf-max-h-[200px] rf-overflow-y-auto",children:[J.jsx("div",{className:"rf-p-1",children:J.jsx(YPe,{value:nt,onChange:_t=>Ie(_t.target.value),placeholder:"Search...",className:"rf-h-7 rf-text-xs"})}),J.jsx(s3t,{}),J.jsx(Sh,{onSelect:()=>Ze(null),children:Ge?`${Ge} (latest)`:"latest"}),pe.map(_t=>J.jsx(Sh,{onSelect:()=>Ze(_t),children:_t},_t))]})})]}):Je&&J.jsx(Sh,{disabled:!0,className:"rf-opacity-60 rf-cursor-default rf-select-none",children:J.jsxs("div",{className:"rf-pr-2 rf-text-xs rf-text-gray-500",children:["@tscircuit/eval@",Je]})})]})]})]}),X&&J.jsx(ta,{onClick:At,variant:"ghost",children:ut?J.jsx(TPo,{size:16}):J.jsx(wPo,{size:16})})]}),a&&J.jsx(IC,{value:"code",className:"rf-flex-grow rf-overflow-hidden",children:J.jsx("div",{className:"rf-h-full",children:c})}),(!R||R.includes("pcb"))&&J.jsx(IC,{value:"pcb",children:J.jsx("div",{className:qi("rf-overflow-hidden",ut?"rf-h-[calc(100vh-52px)]":"rf-h-full"),children:J.jsx(gx,{fallbackRender:({error:_t})=>J.jsx("div",{className:"rf-mt-4 rf-bg-red-50 rf-rounded-md rf-border rf-border-red-200",children:J.jsxs("div",{className:"rf-p-4",children:[J.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-red-800 rf-mb-3",children:"Error loading PCB viewer"}),J.jsx("p",{className:"rf-text-xs rf-font-mono rf-whitespace-pre-wrap rf-text-red-600 rf-mt-2",children:p6e(_t)})]})}),children:r?J.jsx(HLo,{focusOnHover:!1,circuitJson:r,debugGraphics:A,onBoundsSelected:Be,containerClassName:qi("rf-h-full rf-w-full",ut?"rf-min-h-[calc(100vh-240px)]":"rf-min-h-[620px]"),onEditEventsChanged:_t=>{if(S)for(const Gt of _t)S(Gt)}}):J.jsx(w5,{onRunClicked:n})})})}),(!R||R.includes("assembly"))&&J.jsx(IC,{value:"assembly",children:J.jsx("div",{className:qi("rf-overflow-auto",ut?"rf-h-[calc(100vh-60px)]":"rf-h-full rf-min-h-[620px]"),children:J.jsx(gx,{fallback:J.jsx("div",{children:"Error loading Assembly"}),children:r?J.jsx(m9o,{circuitJson:r,containerStyle:{height:"100%"},editingEnabled:!0,debugGrid:!0}):J.jsx(w5,{onRunClicked:n})})})}),(!R||R.includes("pinout"))&&J.jsx(IC,{value:"pinout",children:J.jsx("div",{className:qi("rf-overflow-auto",ut?"rf-h-[calc(100vh-60px)]":"rf-h-full rf-min-h-[620px]"),children:J.jsx(gx,{fallback:J.jsx("div",{children:"Error loading Pinout Viewer"}),children:r?J.jsx(p9o,{circuitJson:r,containerStyle:{height:"100%"}}):J.jsx(w5,{onRunClicked:n})})})}),(!R||R.includes("schematic"))&&J.jsx(IC,{value:"schematic",children:J.jsx("div",{className:qi("rf-overflow-auto rf-bg-white",ut?"rf-h-[calc(100vh-60px)]":"rf-h-full rf-min-h-[620px]"),children:J.jsx(gx,{fallbackRender:({error:_t})=>J.jsx("div",{className:"rf-mt-4 rf-bg-red-50 rf-rounded-md rf-border rf-border-red-200",children:J.jsxs("div",{className:"rf-p-4",children:[J.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-red-800 rf-mb-3",children:"Error loading Schematic"}),J.jsx("p",{className:"rf-text-xs rf-font-mono rf-whitespace-pre-wrap rf-text-red-600 rf-mt-2",children:p6e(_t)})]})}),children:r?J.jsx(e9o,{circuitJson:r,containerStyle:{height:"100%"},editingEnabled:!0,onEditEvent:_t=>{S?.(_t)},debugGrid:Ht,showSchematicPorts:gn,css:fe?.css,className:fe?.className}):J.jsx(w5,{onRunClicked:n})})})}),(!R||R.includes("cad"))&&J.jsx(IC,{value:"cad",children:J.jsx("div",{className:qi("rf-overflow-auto",ut?"rf-h-[calc(100vh-60px)]":"rf-h-full rf-min-h-[620px]"),children:J.jsx(gx,{fallbackRender:({error:_t,resetErrorBoundary:Gt})=>J.jsx(aPo,{error:_t,resetErrorBoundary:Gt}),children:r?J.jsx(APo,{ref:ht,circuitJson:r,autoRotateDisabled:H},`cad-${ut}`):J.jsx(w5,{onRunClicked:n})})})}),(!R||R.includes("analog_simulation"))&&J.jsx(IC,{value:"analog_simulation",children:J.jsx("div",{className:qi("rf-overflow-auto",ut?"rf-h-[calc(100vh-60px)]":"rf-h-full rf-min-h-[620px]"),children:J.jsx(gx,{fallback:J.jsx("div",{children:"Error loading Analog Simulation"}),children:r?ve?J.jsx("div",{className:"rf-mt-4 rf-bg-red-50 rf-rounded-md rf-border rf-border-red-200",children:J.jsxs("div",{className:"rf-p-4",children:[J.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-red-800 rf-mb-3",children:"Error running analog simulation"}),J.jsx("p",{className:"rf-text-xs rf-font-mono rf-whitespace-pre-wrap rf-text-red-600 rf-mt-2",children:ve.message})]})}):Se?J.jsx("div",{className:"rf-flex rf-h-full rf-min-h-[300px] rf-items-center rf-justify-center rf-bg-slate-50",children:J.jsxs("div",{className:"rf-flex rf-items-center rf-gap-2 rf-text-sm rf-text-slate-600",children:[J.jsx(SB,{className:"rf-h-4 rf-w-4 rf-animate-spin"}),"Running analog simulation..."]})}):J.jsx(_9o,{circuitJson:r,hideSchematic:ye,containerStyle:{height:"100%"}}):J.jsx(w5,{onRunClicked:n})})})}),(!R||R.includes("bom"))&&J.jsx(IC,{value:"bom",children:J.jsx("div",{className:qi("rf-overflow-auto",ut?"rf-h-[calc(100vh-60px)]":"rf-h-full rf-min-h-[620px]"),children:J.jsx(gx,{fallbackRender:({error:_t})=>J.jsx("div",{className:"rf-mt-4 rf-bg-red-50 rf-rounded-md rf-border rf-border-red-200",children:J.jsxs("div",{className:"rf-p-4",children:[J.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-red-800 rf-mb-3",children:"Error loading Bill of Materials"}),J.jsx("p",{className:"rf-text-xs rf-font-mono rf-whitespace-pre-wrap rf-text-red-600 rf-mt-2",children:p6e(_t)})]})}),children:r?J.jsx(N9o,{circuitJson:r}):J.jsx(w5,{onRunClicked:n})})})}),(!R||R.includes("circuit_json"))&&J.jsx(IC,{value:"circuit_json",children:J.jsx("div",{className:qi("rf-overflow-auto",ut?"rf-h-[calc(100vh-60px)]":"rf-h-full rf-min-h-[620px]"),children:J.jsx(gx,{fallback:J.jsx("div",{children:"Error loading JSON viewer"}),children:r?J.jsx(f9o,{elements:r}):J.jsx(w5,{onRunClicked:n})})})}),(!R||R.includes("errors"))&&J.jsx(IC,{value:"errors",className:"rf-h-full",children:J.jsx("div",{className:qi("rf-overflow-hidden",ut?"rf-h-[calc(100vh-60px)]":"rf-h-full rf-min-h-[620px]"),children:o||Ke&&Ke.length>0||r?J.jsx(d8o,{code:t,fsMap:e,circuitJsonErrors:Ke,circuitJsonWarnings:Ye,errorMessage:o,errorStack:i,circuitJson:r,evalVersion:Je,autoroutingLog:f,onReportAutoroutingLog:y}):J.jsx(w5,{onRunClicked:n})})}),g&&(!R||R.includes("render_log"))&&J.jsx(IC,{value:"render_log",children:J.jsx(YLo,{renderLog:h,onRerunWithDebug:be})}),(!R||R.includes("solvers"))&&J.jsx(IC,{value:"solvers",children:J.jsx("div",{className:qi("rf-overflow-hidden",ut?"rf-h-[calc(100vh-60px)]":"rf-h-full rf-min-h-[620px]"),children:J.jsx(gx,{fallback:J.jsx("div",{children:"Error loading Solvers view"}),children:J.jsx(JHo,{solverEvents:ue})})})})]})})})};const JTt=Symbol("Comlink.proxy"),SYo=Symbol("Comlink.endpoint"),qTt=Symbol("Comlink.releaseProxy"),I6e=Symbol("Comlink.finalizer"),Wie=Symbol("Comlink.thrown"),WTt=t=>typeof t=="object"&&t!==null||typeof t=="function",bYo={canHandle:t=>WTt(t)&&t[JTt],serialize(t){const{port1:e,port2:n}=new MessageChannel;return XTt(t,e),[n,[n]]},deserialize(t){return t.start(),ZTt(t)}},DYo={canHandle:t=>WTt(t)&&Wie in t,serialize({value:t}){let e;return t instanceof Error?e={isError:!0,value:{message:t.message,name:t.name,stack:t.stack}}:e={isError:!1,value:t},[e,[]]},deserialize(t){throw t.isError?Object.assign(new Error(t.value.message),t.value):t.value}},jTt=new Map([["proxy",bYo],["throw",DYo]]);function MYo(t,e){for(const n of t)if(e===n||n==="*"||n instanceof RegExp&&n.test(e))return!0;return!1}function XTt(t,e=globalThis,n=["*"]){e.addEventListener("message",function o(i){if(!i||!i.data)return;if(!MYo(n,i.origin)){console.warn(`Invalid origin '${i.origin}' for comlink proxy`);return}const{id:r,type:A,path:s}=Object.assign({path:[]},i.data),a=(i.data.argumentList||[]).map(n6);let c;try{const l=s.slice(0,-1).reduce((u,h)=>u[h],t),g=s.reduce((u,h)=>u[h],t);switch(A){case"GET":c=g;break;case"SET":l[s.slice(-1)[0]]=n6(i.data.value),c=!0;break;case"APPLY":c=g.apply(l,a);break;case"CONSTRUCT":{const u=new g(...a);c=f6e(u)}break;case"ENDPOINT":{const{port1:u,port2:h}=new MessageChannel;XTt(t,h),c=RYo(u,[u])}break;case"RELEASE":c=void 0;break;default:return}}catch(l){c={value:l,[Wie]:0}}Promise.resolve(c).catch(l=>({value:l,[Wie]:0})).then(l=>{const[g,u]=Zie(l);e.postMessage(Object.assign(Object.assign({},g),{id:r}),u),A==="RELEASE"&&(e.removeEventListener("message",o),$Tt(e),I6e in t&&typeof t[I6e]=="function"&&t[I6e]())}).catch(l=>{const[g,u]=Zie({value:new TypeError("Unserializable return value"),[Wie]:0});e.postMessage(Object.assign(Object.assign({},g),{id:r}),u)})}),e.start&&e.start()}function wYo(t){return t.constructor.name==="MessagePort"}function $Tt(t){wYo(t)&&t.close()}function ZTt(t,e){const n=new Map;return t.addEventListener("message",function(i){const{data:r}=i;if(!r||!r.id)return;const A=n.get(r.id);if(A)try{A(r)}finally{n.delete(r.id)}}),C6e(t,n,[],e)}function jie(t){if(t)throw new Error("Proxy has been released and is not useable")}function ekt(t){return PT(t,new Map,{type:"RELEASE"}).then(()=>{$Tt(t)})}const Xie=new WeakMap,$ie="FinalizationRegistry"in globalThis&&new FinalizationRegistry(t=>{const e=(Xie.get(t)||0)-1;Xie.set(t,e),e===0&&ekt(t)});function PYo(t,e){const n=(Xie.get(e)||0)+1;Xie.set(e,n),$ie&&$ie.register(t,e,t)}function vYo(t){$ie&&$ie.unregister(t)}function C6e(t,e,n=[],o=function(){}){let i=!1;const r=new Proxy(o,{get(A,s){if(jie(i),s===qTt)return()=>{vYo(r),ekt(t),e.clear(),i=!0};if(s==="then"){if(n.length===0)return{then:()=>r};const a=PT(t,e,{type:"GET",path:n.map(c=>c.toString())}).then(n6);return a.then.bind(a)}return C6e(t,e,[...n,s])},set(A,s,a){jie(i);const[c,l]=Zie(a);return PT(t,e,{type:"SET",path:[...n,s].map(g=>g.toString()),value:c},l).then(n6)},apply(A,s,a){jie(i);const c=n[n.length-1];if(c===SYo)return PT(t,e,{type:"ENDPOINT"}).then(n6);if(c==="bind")return C6e(t,e,n.slice(0,-1));const[l,g]=tkt(a);return PT(t,e,{type:"APPLY",path:n.map(u=>u.toString()),argumentList:l},g).then(n6)},construct(A,s){jie(i);const[a,c]=tkt(s);return PT(t,e,{type:"CONSTRUCT",path:n.map(l=>l.toString()),argumentList:a},c).then(n6)}});return PYo(r,t),r}function NYo(t){return Array.prototype.concat.apply([],t)}function tkt(t){const e=t.map(Zie);return[e.map(n=>n[0]),NYo(e.map(n=>n[1]))]}const nkt=new WeakMap;function RYo(t,e){return nkt.set(t,e),t}function f6e(t){return Object.assign(t,{[JTt]:!0})}function Zie(t){for(const[e,n]of jTt)if(n.canHandle(t)){const[o,i]=n.serialize(t);return[{type:"HANDLER",name:e,value:o},i]}return[{type:"RAW",value:t},nkt.get(t)||[]]}function n6(t){switch(t.type){case"HANDLER":return jTt.get(t.name).deserialize(t.value);case"RAW":return t.value}}function PT(t,e,n,o){return new Promise(i=>{const r=TYo();e.set(r,i),t.start&&t.start(),t.postMessage(Object.assign({id:r},n),o)})}function TYo(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}function y6e(t,e=""){const n=[];for(const o in t){if(!Object.prototype.hasOwnProperty.call(t,o))continue;const i=t[o],r=e?`${e}.${o}`:o;if(i!==null&&typeof i=="object"&&!Array.isArray(i)){const A=y6e(i,r);n.push(...A)}else n.push(r)}return n}function okt(t,e){const n=e.split(".");let o=t;for(const i of n)o=o[i];return o}var kYo=(t="latest")=>[`https://jscdn.tscircuit.com/@tscircuit/eval/${t}/dist/webworker/entrypoint.js`,`https://cdn.jsdelivr.net/npm/@tscircuit/eval@${t}/dist/webworker/entrypoint.js`,`https://unpkg.com/@tscircuit/eval@${t}/dist/webworker/entrypoint.js`],FYo=async(t="latest",e=!1)=>{let n;for(const o of kYo(t))try{const i=await globalThis.fetch(o);if(!i.ok)throw new Error(`Failed to fetch webworker entrypoint from ${o}: ${i.status} ${i.statusText}`);return await i.blob()}catch(i){n=i,e&&console.warn(`[Worker] Failed to fetch webworker entrypoint from ${o}, trying next CDN fallback if available`,i)}throw n instanceof Error?n:new Error("Failed to fetch webworker entrypoint from CDN fallbacks")},ikt=async t=>{const e=globalThis.TSCIRCUIT_GLOBAL_CIRCUIT_WORKER;if(e&&typeof e.kill=="function"){t.verbose&&console.log("[Worker] Killing previous global worker instance...");try{await e.kill()}catch(u){t.verbose&&console.warn("[Worker] Error killing previous global worker instance:",u),globalThis.TSCIRCUIT_GLOBAL_CIRCUIT_WORKER===e&&(globalThis.TSCIRCUIT_GLOBAL_CIRCUIT_WORKER=void 0)}}t.verbose&&console.log("[Worker] Creating circuit web worker with config:",t);let n=t.webWorkerBlobUrl??t.webWorkerUrl;if(!n){const u=await FYo(t.evalVersion??"latest",t.verbose);n=URL.createObjectURL(u)}const o=new Worker(n,{type:"module"});let i;o.addEventListener("error",u=>{console.error("[Worker] Error in worker",u),i=u}),o.addEventListener("unhandledrejection",u=>{console.error("[Worker] Unhandled rejection in worker",u)}),o.addEventListener("messageerror",u=>{console.error("[Worker] Message error in worker",u)});const r=u=>{console.log("[Worker] Message in worker",u)};if(o.addEventListener("message",r),o.addEventListener("message",async u=>{const h=u.data;if(h?.type==="worker_fetch")try{const d=await globalThis.fetch(h.input,h.init),_=await d.text();o.postMessage({type:"worker_fetch_result",requestId:h.requestId,success:!0,response:{body:_,status:d.status,statusText:d.statusText,headers:(()=>{const p={};return d.headers.forEach((m,C)=>{p[C]=m}),p})()}})}catch(d){o.postMessage({type:"worker_fetch_result",requestId:h.requestId,success:!1,error:{name:d.name,message:d.message,stack:d.stack}})}}),i)throw i;const A=ZTt(o);o.removeEventListener("message",r);function s(u){return!u||typeof u!="object"?u:u.type&&u.props!==void 0?{__isSerializedReactElement:!0,type:u.type,props:a(u.props),key:u.key}:u}function a(u){if(!u||typeof u!="object")return u;const h={};for(const[d,_]of Object.entries(u))d==="children"?Array.isArray(_)?h.children=_.map(s):h.children=s(_):h[d]=_;return h}t.enableFetchProxy&&o.postMessage({type:"override_global_fetch"}),t.disableCdnLoading&&await A.setDisableCdnLoading(!0),t.snippetsApiBaseUrl&&await A.setSnippetsApiBaseUrl(t.snippetsApiBaseUrl),t.tscircuitSessionToken&&await A.setTscircuitSessionToken(t.tscircuitSessionToken),t.easyEdaProxyConfig&&await A.setEasyEdaProxyConfig(t.easyEdaProxyConfig);const c=u=>typeof u=="function"?f6e(u):u;if(t.platform)for(const u of y6e(t.platform))await A.setPlatformConfigProperty(u,c(okt(t.platform,u))).catch(h=>{throw new Error(`Error setting platform config property ${u}: ${h instanceof Error?h.message:String(h)}`)});if(t.projectConfig)for(const u of y6e(t.projectConfig))await A.setProjectConfigProperty(u,c(okt(t.projectConfig,u))).catch(h=>{throw new Error(`Error setting project config property ${u}: ${h instanceof Error?h.message:String(h)}`)});let l=!1;const g={clearEventListeners:A.clearEventListeners.bind(A),enableDebug:async(...u)=>{if(l)throw new Error("CircuitWebWorker was terminated, can't enableDebug");return A.enableDebug.bind(A)(...u)},version:A.version.bind(A),execute:async(...u)=>{if(l)throw new Error("CircuitWebWorker was terminated, can't execute");return A.execute.bind(A)(...u)},executeComponent:async u=>{if(l)throw new Error("CircuitWebWorker was terminated, can't executeComponent");if(typeof u=="function")return A.executeComponent.bind(A)(u);if(u&&typeof u=="object"&&u.type){const h=s(u);return A.executeComponent.bind(A)(h)}return A.executeComponent.bind(A)(u)},executeWithFsMap:async(...u)=>{if(l)throw new Error("CircuitWebWorker was terminated, can't executeWithFsMap");return A.executeWithFsMap.bind(A)(...u)},renderUntilSettled:A.renderUntilSettled.bind(A),getCircuitJson:A.getCircuitJson.bind(A),on:(u,h)=>{const d=f6e(h);A.on(u,d)},kill:async()=>{A[qTt](),o.terminate(),l=!0,globalThis.TSCIRCUIT_GLOBAL_CIRCUIT_WORKER===g&&(globalThis.TSCIRCUIT_GLOBAL_CIRCUIT_WORKER=void 0)}};return g.__rawWorker=o,globalThis.TSCIRCUIT_GLOBAL_CIRCUIT_WORKER=g,g};const LYo=({error:t,resetErrorBoundary:e})=>{const n=t instanceof Error?t:new Error(String(t));return J.jsx("section",{className:"rf-h-full rf-w-full rf-grid rf-place-items-center",children:J.jsx("div",{className:"rf-min-h-full rf-flex rf-items-center rf-justify-center rf-px-4",children:J.jsxs("div",{className:"rf-max-w-lg rf-w-full rf-text-center",children:[J.jsxs("div",{className:"rf-mb-8",children:[J.jsx("div",{className:"rf-inline-flex rf-items-center rf-justify-center rf-w-20 rf-h-20 rf-bg-red-100 rf-rounded-full rf-mb-6",children:J.jsx(GPo,{className:"rf-w-10 rf-h-10 rf-text-red-600"})}),J.jsx("h1",{className:"rf-text-2xl rf-font-bold rf-text-gray-900 rf-mb-3",children:"Oops! Something went wrong"}),J.jsx("p",{className:"rf-text-gray-600 rf-mb-4",children:"RunFrame encountered an unexpected error."}),J.jsx("pre",{className:"rf-text-xs no-scrollbar rf-font-mono rf-text-left rf-whitespace-pre-wrap rf-text-red-600 rf-bg-red-50 rf-border rf-border-red-200 rf-p-3 rf-rounded-lg rf-mb-4 rf-overflow-auto rf-max-h-[120px]",children:n.message}),n.stack&&J.jsxs("details",{className:"rf-text-center rf-mb-6",children:[J.jsx("summary",{className:"rf-text-xs rf-text-gray-500 rf-cursor-pointer hover:rf-text-gray-700",children:"View stack trace"}),J.jsx("pre",{className:"rf-text-xs rf-font-mono no-scrollbar rf-whitespace-pre-wrap rf-text-gray-500 rf-bg-gray-100 rf-p-3 rf-rounded-lg rf-mt-2 rf-overflow-auto rf-text-left rf-max-h-[150px]",children:n.stack})]})]}),J.jsxs("div",{className:"rf-flex rf-flex-col rf-gap-2 rf-justify-center",children:[J.jsx(ta,{variant:"destructive",size:"lg",onClick:()=>window.location.reload(),children:"Refresh Dev Server"}),J.jsx(ta,{variant:"outline",size:"lg",onClick:e,children:"Try Again"})]})]})})})},rkt=t=>{const e={};if(!t)return e;for(const o of C2)e[o]=0;const n=new Map;for(const o of t){const[,,i,r]=o.type.split(":");if(r==="start"){n.set(`${i}:${o.renderId}`,o);continue}if(r==="end"){const A=n.get(`${i}:${o.renderId}`);if(A){const s=o.createdAt-A.createdAt;e[i]=(e[i]||0)+s}}}return e},HYo=(t,e)=>{const n={};for(const[o,i]of t.entries()){const r=e.get(o);r!==i&&(n[o]={old:i,new:r})}for(const[o,i]of e.entries())t.has(o)||(n[o]={old:void 0,new:i});return n};function GYo(){const t=j.useRef(Promise.resolve()),e=j.useRef(!1),n=j.useRef(null),o=j.useCallback(async A=>{await t.current;const s={cancelled:!1};n.current=s;let a;const c=new Promise(l=>{a=l});try{return t.current=c,e.current=!0,await A()}catch(l){if(!s.cancelled)throw l}finally{e.current=!1,n.current=null,a()}},[]),i=j.useCallback(()=>{n.current&&(n.current.cancelled=!0),t.current=Promise.resolve(),e.current=!1},[]),r=j.useCallback(()=>e.current,[]);return{runWithMutex:o,isLocked:r,cancel:i}}const OYo=({message:t="Loading files..."})=>J.jsxs("div",{className:"rf-flex rf-flex-col rf-w-full rf-h-full",children:[J.jsxs("div",{className:"rf-flex rf-items-center rf-gap-4 rf-p-2 rf-border-b",children:[J.jsx("div",{className:"rf-w-20 rf-h-9 rf-bg-gray-200 dark:rf-bg-gray-700 rf-rounded-md rf-animate-pulse"}),J.jsx("div",{className:"rf-flex rf-gap-6 rf-ml-auto",children:["PCB","Schematic","3D"].map((e,n)=>J.jsx("div",{className:"rf-h-6 rf-w-20 rf-bg-gray-200 dark:rf-bg-gray-700 rf-rounded rf-animate-pulse"},n))})]}),J.jsx("div",{className:"rf-flex-1 rf-p-4",children:J.jsx("div",{className:"rf-w-full rf-h-full rf-rounded-lg rf-bg-gray-100 dark:rf-bg-gray-800 rf-animate-pulse rf-flex rf-items-center rf-justify-center",children:J.jsx("div",{className:"rf-flex rf-flex-col rf-items-center rf-gap-4",children:J.jsx("div",{className:"rf-text-sm rf-text-gray-400 dark:rf-text-gray-500",children:t})})})})]}),ere=t=>{const e=t.toLowerCase(),n=e.split("/").pop();return e.endsWith(".circuit.json")||n==="circuit.json"},KYo=t=>t.endsWith(".tsx")||ere(t)||t.endsWith(".jsx"),UYo=({mainComponentPath:t,fsMap:e})=>j.useMemo(()=>{if(!(t!=null&&ere(t)))return{isStaticCircuitJson:!1,circuitJson:null,error:null};const o=e.get(t);if(!o)return{isStaticCircuitJson:!0,circuitJson:null,error:`Circuit JSON file not found: ${t}`};try{return{isStaticCircuitJson:!0,circuitJson:JSON.parse(o),error:null}}catch(i){return{isStaticCircuitJson:!0,circuitJson:null,error:`Failed to parse circuit.json: ${i instanceof Error?i.message:String(i)}`}}},[t,e]),YYo=t=>!t||typeof t!="object"?!1:!!("error_type"in t||typeof t.type=="string"&&t.type.includes("error")),zYo=t=>t instanceof Error?{name:t.name,message:t.message,stack:t.stack}:typeof t=="string"?{message:t}:t&&typeof t=="object"?t:{message:String(t)},VYo=t=>Array.isArray(t)?t.filter(YYo):[],E6e=({circuitJson:t,executionError:e})=>{const n=[];e&&n.push(zYo(e));const o=VYo(t);return n.push(...o),{hasExecutionError:!!e,...n.length>0?{errors:n}:{}}},JYo=26,py=Ga("run-frame:RunFrame"),qYo=async()=>{try{const t=await fetch("https://data.jsdelivr.com/v1/package/npm/@tscircuit/eval");if(t.ok)return(await t.json()).tags?.latest}catch(t){console.error("Failed to fetch latest eval version",t)}},Akt=async(t,e)=>{if(t)return t;if(e||!window.TSCIRCUIT_LATEST_EVAL_VERSION){const n=await qYo();if(n)return window.TSCIRCUIT_LATEST_EVAL_VERSION=n,n}return window.TSCIRCUIT_LATEST_EVAL_VERSION?window.TSCIRCUIT_LATEST_EVAL_VERSION:"latest"},skt=t=>{fie();const e=Yu(ue=>ue.circuitJson),n=Yu(ue=>ue.setCircuitJson),[o,i]=j.useState(null),r=j.useRef(null),[A,s]=j.useState(null),[a,c]=j.useReducer((ue,Be)=>ue+1,0),l=yie(ue=>ue.setLastRunEvalVersion),g=j.useRef(0),u=GYo(),[h,d]=j.useState(!1),[_,p]=j.useState(!1),[m,C]=j.useState({}),[I,f]=j.useState(""),[y,x]=j.useState(!1),[B,S]=j.useState(!1),D=Object.values(m).sort((ue,Be)=>ue.startTime-Be.startTime)[0]?.effectName,w=ue=>{t.onRunCompleted?.(ue)};j.useEffect(()=>{const ue=Be=>{(Be.ctrlKey||Be.metaKey)&&Be.key==="Enter"&&!h&&c(1)};return window.addEventListener("keydown",ue),()=>window.removeEventListener("keydown",ue)},[h]),j.useEffect(()=>{let ue=!1;return(async()=>{try{if(!globalThis.runFrameWorker){const pe=await Akt(t.evalVersion,t.forceLatestEvalVersion),Ge=await ikt({evalVersion:pe,webWorkerBlobUrl:t.evalWebWorkerBlobUrl,projectConfig:{projectBaseUrl:t.projectBaseUrl||`${Qf}/files/static`},...t.platformConfig&&{platformConfig:t.platformConfig},verbose:!0,...t.enableFetchProxy&&{enableFetchProxy:t.enableFetchProxy},...window.TSCIRCUIT_USE_RUNFRAME_FOR_CLI&&{disableCdnLoading:!0},...t.tscircuitSessionToken&&{tscircuitSessionToken:t.tscircuitSessionToken},...t.easyEdaProxyConfig&&{easyEdaProxyConfig:t.easyEdaProxyConfig}});if(ue)return;globalThis.runFrameWorker=Ge,l(pe)}ue||p(!0)}catch(pe){console.error("Failed to preload eval worker",pe)}})(),()=>{ue=!0}},[t.evalVersion,t.evalWebWorkerBlobUrl,t.forceLatestEvalVersion,t.tscircuitSessionToken]);const[F,R]=j.useState(null),[H,G]=j.useState({}),[K,V]=j.useState([]),[W,X]=j.useState(t.defaultActiveTab??t.defaultTab??"pcb");dRt({source:"runframe",component:"RunFrame",isWebEmbedded:t.isWebEmbedded,activeTab:W}),j.useEffect(()=>{t.debug&&Ga.enable("run-frame*")},[t.debug]);const ie=t.fsMap instanceof Map?t.fsMap:Object.entries(t.fsMap??{}).reduce((ue,[Be,pe])=>ue.set(Be,pe),new Map),se=j.useRef(null),ee=j.useRef(null),{isStaticCircuitJson:oe,circuitJson:ae,error:re}=UYo({mainComponentPath:t.mainComponentPath,fsMap:ie});j.useEffect(()=>{oe&&(ae?(n(ae),i(null)):re&&i({error:re,stack:""}))},[oe,ae,re]),j.useEffect(()=>{if(t.isLoadingFiles||oe)return;const ue=ie instanceof Map?Object.fromEntries(ie.entries()):ie;if(!ue||Object.keys(ue).length===0){i({error:"No files provided. Please provide at least one file with code to execute.",stack:""}),d(!1);return}const Be=a!==g.current;if(se.current&&e){const Ge=HYo(se.current,ie);if(Object.keys(Ge).length>0)py("code changes detected");else if(ee.current!==t.entrypoint)py("render triggered by entrypoint change");else if(!Be){py("render triggered without changes to fsMap, skipping");return}}if(t.showRunButton&&a===g.current)return;se.current=ie,ee.current=t.entrypoint??null,g.current=a,d(!0);const pe=async()=>{py("running render worker"),i(null),R(null),C({}),V([]);const Ge={progress:0,debugOutputs:[]};let Je=!1;r.current=()=>{Je=!0};const nt=await Akt(t.evalVersion,!globalThis.runFrameWorker&&t.forceLatestEvalVersion);py("resolvedEvalVersion",nt);const Ie=globalThis.runFrameWorker??await ikt({evalVersion:nt,webWorkerBlobUrl:t.evalWebWorkerBlobUrl,verbose:!0,projectConfig:{projectBaseUrl:t.projectBaseUrl||`${Qf}/files/static`},...t.platformConfig&&{platformConfig:t.platformConfig},...t.enableFetchProxy&&{enableFetchProxy:t.enableFetchProxy},...window.TSCIRCUIT_USE_RUNFRAME_FOR_CLI&&{disableCdnLoading:!0},...t.tscircuitSessionToken&&{tscircuitSessionToken:t.tscircuitSessionToken},...t.easyEdaProxyConfig&&{easyEdaProxyConfig:t.easyEdaProxyConfig}});globalThis.runFrameWorker=Ie,l(nt),I?.trim()&&Ie.enableDebug(I.replace("DEBUG=","")),py("Starting render..."),t.onRenderStarted?.();const Ze=ie instanceof Map?Object.fromEntries(ie.entries()):ie;let Ke=Date.now();Ie.on("asyncEffect:start",Se=>{const ve=`${Se.phase}|${Se.componentDisplayName??""}|${Se.effectName}`;C(Pe=>({...Pe,[ve]:{...Se,startTime:Date.now()}}))}),Ie.on("asyncEffect:end",Se=>{const ve=`${Se.phase}|${Se.componentDisplayName??""}|${Se.effectName}`;C(Pe=>{const{[ve]:ze,...Xe}=Pe;return Xe})}),Ie.on("autorouting:start",Se=>{G({...H,[Se.componentDisplayName]:{simpleRouteJson:Se.simpleRouteJson,createdAt:Date.now()}})}),Ie.on("solver:started",Se=>{py("solver:started",Se),V(ve=>{const Pe=`${Se.componentName}-${Se.solverName}`;return ve.some(Xe=>`${Xe.componentName}-${Xe.solverName}`===Pe)?ve:[...ve,Se]})}),Ie.on("board:renderPhaseStarted",Se=>{Ge.lastRenderEvent=Se,Ge.eventsProcessed=(Ge.eventsProcessed??0)+1;const ve=C2.indexOf(Se.phase)/JYo*.75+Ge.eventsProcessed/1e3*.25,Pe=1-Math.exp(-ve*3);Ge.progress=Pe,Je||R({...Ge})}),W==="render_log"&&Ie.on("renderable:renderLifecycle:anyEvent",Se=>{Ge.renderEvents=Ge.renderEvents??[],Se.createdAt=Date.now(),Ge.renderEvents.push(Se),Date.now()-Ke>500&&(Ge.phaseTimings=rkt(Ge.renderEvents??[]),Ke=Date.now()),Je||R({...Ge})}),Ie.on("autorouting:progress",Se=>{s(Se.debugGraphics)}),Ie.on("debug:logOutput",Se=>{Ge.debugOutputs=Ge.debugOutputs??[],Ge.debugOutputs.push({type:"debug",name:Se.name,content:Se.content}),Je||R({...Ge})}),py("Executing fsMap...");const Ye=await Ie.executeWithFsMap({entrypoint:t.entrypoint,fsMap:Ze,...t.mainComponentPath?{mainComponentPath:t.mainComponentPath}:{}}).then(()=>({success:!0})).catch(Se=>{const ve=Se.message.replace("Error: ","");return py(`eval error: ${ve}`),t.onError?.(Se),w(E6e({executionError:Se})),i({error:ve,stack:Se.stack}),R(null),console.error(Se),{success:!1}});if(py("worker call started"),!Ye.success){d(!1),C({});return}const qe=Ie.renderUntilSettled();py("waiting for initial circuit json...");let Le=await Ie.getCircuitJson().catch(Se=>(py("error getting initial circuit json",Se),t.onError?.(Se),w(E6e({executionError:Se})),i({error:Se.message,stack:Se.stack}),R(null),d(!1),C({}),null));Le&&(py("got initial circuit json"),n(Le),t.onCircuitJsonChange?.(Le),t.onInitialRender?.({circuitJson:Le}),await qe,py("getting final circuit json"),Le=await Ie.getCircuitJson(),t.onCircuitJsonChange?.(Le),n(Le),w(E6e({circuitJson:Le})),t.onRenderFinished?.({circuitJson:Le}),s({}),W==="render_log"&&(Ge.phaseTimings=rkt(Ge.renderEvents??[])),Ge.progress=1,Je||R({...Ge}),d(!1),C({}),f(""),r.current=null)};u.runWithMutex(pe)},[t.fsMap,t.entrypoint,a,t.evalVersion,t.mainComponentPath,t.isLoadingFiles,I,oe]);const le=j.useRef(null),fe=j.useRef(null),ye=ue=>{if(!ue||ue===null){console.warn("[RunFrame] handleEditEvent received null or undefined event.");return}ue.in_progress?(le.current=ue,fe.current&&(clearTimeout(fe.current),fe.current=null)):(fe.current&&clearTimeout(fe.current),fe.current=setTimeout(()=>{const Be=ue||le.current;t.onEditEvent?.(Be),le.current=null,fe.current=null},100))},be=async(ue,Be)=>{let pe="";const Ge=Array.isArray(e)&&e.find(Ie=>Ie.type==="software_project_metadata"),Je=t.projectUrl??Ge?.project_url;if(Je)try{pe=new URL(Je).pathname}catch{pe=Je}const nt=pe?`${pe} - ${ue}`:ue;await PG.post("autorouting/bug_reports/create",{json:{title:nt,simple_route_json:Be.simpleRouteJson}}).json().then(({autorouting_bug_report:Ie})=>{window.open(`https://api.tscircuit.com/autorouting/bug_reports/view?autorouting_bug_report_id=${Ie.autorouting_bug_report_id}`,"_blank")}).catch(Ie=>{if(console.error("Failed to report autorouting bug",Ie),Ie instanceof cM&&Ie.response?.status===401){t.onLoginRequired?t.onLoginRequired():alert("You must be logged in to report autorouting bugs");return}const Ke=Ie instanceof Error?Ie.message:"Failed to report autorouting bug";alert(`Failed to report autorouting bug: ${Ke}`)})};return t.isLoadingFiles?J.jsx(OYo,{}):J.jsx(gx,{FallbackComponent:LYo,children:J.jsx(VTt,{code:ie.get(t.entrypoint??t.mainComponentPath),fsMap:ie,defaultActiveTab:t.defaultActiveTab??t.defaultTab,defaultTab:t.defaultTab,availableTabs:t.availableTabs,schematicSvgOptions:t.schematicSvgOptions,showToggleFullScreen:t.showToggleFullScreen,autoroutingGraphics:A,autoroutingLog:H,onReportAutoroutingLog:t.onReportAutoroutingLog||be,leftHeaderContent:J.jsxs(J.Fragment,{children:[t.showRunButton&&J.jsx(h6e,{children:J.jsxs(_6e,{children:[J.jsx(m6e,{asChild:!0,children:J.jsxs("div",{className:"rf-relative rf-inline-flex",children:[J.jsxs("button",{type:"button",onClick:()=>{c(1)},className:"rf-flex rf-items-center rf-gap-2 rf-px-4 rf-py-2 rf-bg-blue-600 hover:rf-bg-blue-700 rf-text-white rf-rounded-md disabled:rf-opacity-50 transition-colors duration-200",disabled:h||!_,children:["Run"," ",h||!_?J.jsx(SB,{className:"rf-w-3 rf-h-3 rf-animate-spin"}):J.jsx(FPt,{className:"rf-w-3 rf-h-3"})]}),h&&J.jsx("div",{className:"rf-flex rf-items-center rf-ml-1",children:J.jsx(ta,{onClick:ue=>{ue.stopPropagation(),d(!1),R(null),i(null),r.current&&(r.current(),r.current=null),u.cancel(),C({}),globalThis.runFrameWorker&&(globalThis.runFrameWorker.kill(),globalThis.runFrameWorker=null)},variant:"ghost",size:"icon",className:"rf-text-red-300 hover:rf-text-red-400 hover:!rf-bg-transparent [&>svg]:rf-text-red-300 [&>svg]:hover:rf-text-red-400 rf-flex rf-items-center rf-justify-center",children:J.jsx(HPo,{className:"!rf-h-2.5 !rf-w-2.5",fill:"currentColor",stroke:"currentColor"})})})]})}),J.jsx(qie,{sideOffset:8,className:"rf-p-0 rf-bg-transparent rf-border-none rf-shadow-none rf-pointer-events-none",children:J.jsxs("div",{className:"rf-flex rf-items-center rf-gap-2 rf-px-2.5 rf-py-1.5 rf-bg-slate-900 rf-rounded-md rf-shadow-xl rf-border rf-border-slate-800/60",children:[J.jsx("kbd",{className:"rf-bg-slate-800 rf-px-1.5 rf-py-0.5 rf-rounded rf-text-[10px] rf-font-sans rf-font-medium rf-border rf-border-slate-700 rf-text-slate-200 rf-leading-none",children:"Ctrl"}),J.jsx("span",{className:"rf-text-slate-500 rf-text-[11px] rf-font-medium rf-leading-none",children:"+"}),J.jsx("kbd",{className:"rf-bg-slate-800 rf-px-1.5 rf-py-0.5 rf-rounded rf-text-[10px] rf-font-sans rf-font-medium rf-border rf-border-slate-700 rf-text-slate-200 rf-leading-none",children:"Enter"})]})})]})}),t.showFileMenu!==!1&&J.jsx(cU,{isWebEmbedded:t.isWebEmbedded,onLoginRequired:t.onLoginRequired,showSchematicDebugGrid:y,onChangeShowSchematicDebugGrid:x,showSchematicPorts:B,onChangeShowSchematicPorts:S,autoroutingLog:H,onReportAutoroutingLog:t.onReportAutoroutingLog||be}),t.leftHeaderContent]}),onActiveTabChange:X,circuitJson:e,renderLog:F,activeEffectName:D,isRunningCode:h,errorMessage:o?.error,errorStack:o?.stack,onEditEvent:ye,editEvents:t.editEvents,onPcbBoundsSelected:t.onPcbBoundsSelected,defaultToFullScreen:t.defaultToFullScreen,onRerunWithDebug:ue=>{f(ue||""),c(1)},solverEvents:K,isCli:t.isCli,showSchematicDebugGrid:y,showSchematicPorts:B,onChangeShowSchematicDebugGrid:x,onChangeShowSchematicPorts:S})})},WYo=t=>new Promise(e=>setTimeout(e,t)),jYo=({isOpen:t,onClose:e,onLoginSuccess:n})=>{const[o,i]=j.useState("idle"),[r,A]=j.useState(null),[s,a]=j.useState(null),c=Yu(_=>_.pushEvent),l=j.useRef(null);j.useEffect(()=>()=>{l.current&&l.current.abort()},[]);const g=j.useCallback(async()=>{i("creating"),a(null),l.current=new AbortController;try{const _=lM(),{login_page:p}=await _.post("sessions/login_page/create",{json:{},signal:l.current?.signal}).json();A(p.url),i("waiting");const m=new URL(p.url);for(m.searchParams.set("autoclose","true"),window.open(m.toString(),"_blank");!l.current?.signal.aborted;){const{login_page:I}=await _.post("sessions/login_page/get",{json:{login_page_id:p.login_page_id},headers:{Authorization:`Bearer ${p.login_page_auth_token}`},signal:l.current?.signal}).json();if(I.was_login_successful){i("exchanging");break}if(I.is_expired)throw new Error("Login page expired. Please try again.");await WYo(1e3)}if(l.current?.signal.aborted){i("idle");return}const{session:C}=await _.post("sessions/login_page/exchange_for_cli_session",{json:{login_page_id:p.login_page_id},headers:{Authorization:`Bearer ${p.login_page_auth_token}`},signal:l.current?.signal}).json();typeof window<"u"&&(window.TSCIRCUIT_REGISTRY_TOKEN=C.token),await c({event_type:"TOKEN_UPDATED",registry_token:C.token}),i("success"),zA.success("Successfully logged in!"),n?.(),setTimeout(()=>{e(),i("idle"),A(null)},1e3)}catch(_){if(_ instanceof DOMException&&_.name==="AbortError"){i("idle");return}console.error("Login error:",_);const p=_ instanceof Error?_.message:"Failed to complete login";a(p),i("error"),zA.error(p)}},[c,n,e]),u=j.useCallback(()=>{l.current&&l.current.abort(),i("idle"),A(null),a(null),e()},[e]),h=o==="creating"||o==="waiting"||o==="exchanging",d=()=>{switch(o){case"creating":return"Creating login page...";case"waiting":return"Waiting for you to complete login in the browser...";case"exchanging":return"Generating token...";case"success":return"Successfully logged in!";case"error":return s||"An error occurred";default:return null}};return J.jsx(DT,{open:t,onOpenChange:_=>!_&&!h&&u(),children:J.jsxs(j3,{className:"rf-max-w-md",children:[J.jsxs(X3,{children:[J.jsx($3,{children:"Sign In Required"}),J.jsx(MT,{children:o==="idle"||o==="error"?"Sign in to continue. A new browser window will open for authentication.":"Complete the login process in the opened browser window."})]}),J.jsxs("div",{className:"rf-flex rf-flex-col rf-items-center rf-gap-4 rf-py-4",children:[o==="idle"||o==="error"?J.jsx(ta,{onClick:g,className:"rf-w-full",children:"Sign In"}):J.jsxs("div",{className:"rf-flex rf-flex-col rf-items-center rf-gap-3 rf-w-full",children:[o!=="success"&&J.jsx("div",{className:"rf-animate-spin rf-w-6 rf-h-6 rf-border-2 rf-border-gray-300 rf-border-t-blue-600 rf-rounded-full"}),J.jsx("p",{className:"rf-text-sm rf-text-gray-600 rf-text-center",children:d()}),r&&o==="waiting"&&J.jsx("a",{href:r,target:"_blank",rel:"noreferrer",className:"rf-text-xs rf-text-blue-600 hover:rf-underline",children:"Click here if the window didn't open"})]}),s&&o==="error"&&J.jsx("p",{className:"rf-text-sm rf-text-red-600 rf-text-center",children:s}),h&&J.jsx(ta,{variant:"outline",onClick:u,className:"rf-w-full",children:"Cancel"})]})]})})},XYo=()=>{const[t,e]=j.useState(!1),n=j.useCallback(()=>{e(!0)},[]),o=j.useCallback(()=>{e(!1)},[]),i=j.useCallback(()=>{e(!1)},[]);return{LoginDialog:J.jsx(jYo,{isOpen:t,onClose:o,onLoginSuccess:i}),openLoginDialog:n}},$Yo=t=>{const[e,n]=J7("load-latest-eval",!0),[o]=j.useState(()=>typeof window>"u"?void 0:new URLSearchParams(window.location.hash.slice(1)).get("main_component")??void 0),i=j.useCallback(s=>{if(typeof window>"u")return;const a=new URLSearchParams(window.location.hash.slice(1));if(a.get("main_component")===s)return;a.set("main_component",s);const c=a.toString(),l=`${window.location.pathname}${window.location.search}`+(c.length>0?`#${c}`:"");window.history.replaceState(null,"",l)},[]),{LoginDialog:r,openLoginDialog:A}=XYo();return J.jsxs(J.Fragment,{children:[r,J.jsx(Xkt,{debug:t.debug,forceLatestEvalVersion:!t.workerBlobUrl&&e,defaultToFullScreen:!0,showToggleFullScreen:!1,workerBlobUrl:t.workerBlobUrl,isCli:!0,showFilesSwitch:!0,showFileMenu:!1,enableFetchProxy:t.enableFetchProxy,initialMainComponentPath:o,onLoginRequired:A,onMainComponentPathChange:i,leftHeaderContent:J.jsxs("div",{className:"rf-flex rf-items-center rf-justify-between",children:[J.jsx(cU,{isWebEmbedded:!1,shouldLoadLatestEval:!t.workerBlobUrl&&e,onChangeShouldLoadLatestEval:s=>{n(s),globalThis.runFrameWorker=null},onLoginRequired:A}),t.scenarioSelectorContent]})})]})};Ga("run-frame:ImportComponentDialog");var akt=1,ZYo=.9,ezo=.8,tzo=.17,x6e=.1,B6e=.999,nzo=.9999,ozo=.99,izo=/[\\\/_+.#"@\[\(\{&]/,rzo=/[\\\/_+.#"@\[\(\{&]/g,Azo=/[\s-]/,ckt=/[\s-]/g;function Q6e(t,e,n,o,i,r,A){if(r===e.length)return i===t.length?akt:ozo;var s=`${i},${r}`;if(A[s]!==void 0)return A[s];for(var a=o.charAt(r),c=n.indexOf(a,i),l=0,g,u,h,d;c>=0;)g=Q6e(t,e,n,o,c+1,r+1,A),g>l&&(c===i?g*=akt:izo.test(t.charAt(c-1))?(g*=ezo,h=t.slice(i,c-1).match(rzo),h&&i>0&&(g*=Math.pow(B6e,h.length))):Azo.test(t.charAt(c-1))?(g*=ZYo,d=t.slice(i,c-1).match(ckt),d&&i>0&&(g*=Math.pow(B6e,d.length))):(g*=tzo,i>0&&(g*=Math.pow(B6e,c-i))),t.charAt(c)!==e.charAt(r)&&(g*=nzo)),(g<x6e&&n.charAt(c-1)===o.charAt(r+1)||o.charAt(r+1)===o.charAt(r)&&n.charAt(c-1)!==o.charAt(r))&&(u=Q6e(t,e,n,o,c+1,r+2,A),u*x6e>g&&(g=u*x6e)),g>l&&(l=g),c=n.indexOf(a,c+1);return A[s]=l,l}function lkt(t){return t.toLowerCase().replace(ckt," ")}function szo(t,e,n){return t=n&&n.length>0?`${t+" "+n.join(" ")}`:t,Q6e(t,e,lkt(t),lkt(e),0,0,{})}var uU='[cmdk-group=""]',S6e='[cmdk-group-items=""]',azo='[cmdk-group-heading=""]',gkt='[cmdk-item=""]',ukt=`${gkt}:not([aria-disabled="true"])`,b6e="cmdk-item-select",vT="data-value",czo=(t,e,n)=>szo(t,e,n),dkt=j.createContext(void 0),dU=()=>j.useContext(dkt),hkt=j.createContext(void 0),D6e=()=>j.useContext(hkt),_kt=j.createContext(void 0),mkt=j.forwardRef((t,e)=>{let n=NT(()=>{var oe,ae;return{search:"",value:(ae=(oe=t.value)!=null?oe:t.defaultValue)!=null?ae:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),o=NT(()=>new Set),i=NT(()=>new Map),r=NT(()=>new Map),A=NT(()=>new Set),s=pkt(t),{label:a,children:c,value:l,onValueChange:g,filter:u,shouldFilter:h,loop:d,disablePointerSelection:_=!1,vimBindings:p=!0,...m}=t,C=rp(),I=rp(),f=rp(),y=j.useRef(null),x=fzo();o6(()=>{if(l!==void 0){let oe=l.trim();n.current.value=oe,B.emit()}},[l]),o6(()=>{x(6,H)},[]);let B=j.useMemo(()=>({subscribe:oe=>(A.current.add(oe),()=>A.current.delete(oe)),snapshot:()=>n.current,setState:(oe,ae,re)=>{var le,fe,ye,be;if(!Object.is(n.current[oe],ae)){if(n.current[oe]=ae,oe==="search")R(),w(),x(1,F);else if(oe==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let ue=document.getElementById(f);ue?ue.focus():(le=document.getElementById(C))==null||le.focus()}if(x(7,()=>{var ue;n.current.selectedItemId=(ue=G())==null?void 0:ue.id,B.emit()}),re||x(5,H),((fe=s.current)==null?void 0:fe.value)!==void 0){let ue=ae??"";(be=(ye=s.current).onValueChange)==null||be.call(ye,ue);return}}B.emit()}},emit:()=>{A.current.forEach(oe=>oe())}}),[]),S=j.useMemo(()=>({value:(oe,ae,re)=>{var le;ae!==((le=r.current.get(oe))==null?void 0:le.value)&&(r.current.set(oe,{value:ae,keywords:re}),n.current.filtered.items.set(oe,D(ae,re)),x(2,()=>{w(),B.emit()}))},item:(oe,ae)=>(o.current.add(oe),ae&&(i.current.has(ae)?i.current.get(ae).add(oe):i.current.set(ae,new Set([oe]))),x(3,()=>{R(),w(),n.current.value||F(),B.emit()}),()=>{r.current.delete(oe),o.current.delete(oe),n.current.filtered.items.delete(oe);let re=G();x(4,()=>{R(),re?.getAttribute("id")===oe&&F(),B.emit()})}),group:oe=>(i.current.has(oe)||i.current.set(oe,new Set),()=>{r.current.delete(oe),i.current.delete(oe)}),filter:()=>s.current.shouldFilter,label:a||t["aria-label"],getDisablePointerSelection:()=>s.current.disablePointerSelection,listId:C,inputId:f,labelId:I,listInnerRef:y}),[]);function D(oe,ae){var re,le;let fe=(le=(re=s.current)==null?void 0:re.filter)!=null?le:czo;return oe?fe(oe,n.current.search,ae):0}function w(){if(!n.current.search||s.current.shouldFilter===!1)return;let oe=n.current.filtered.items,ae=[];n.current.filtered.groups.forEach(le=>{let fe=i.current.get(le),ye=0;fe.forEach(be=>{let ue=oe.get(be);ye=Math.max(ue,ye)}),ae.push([le,ye])});let re=y.current;K().sort((le,fe)=>{var ye,be;let ue=le.getAttribute("id"),Be=fe.getAttribute("id");return((ye=oe.get(Be))!=null?ye:0)-((be=oe.get(ue))!=null?be:0)}).forEach(le=>{let fe=le.closest(S6e);fe?fe.appendChild(le.parentElement===fe?le:le.closest(`${S6e} > *`)):re.appendChild(le.parentElement===re?le:le.closest(`${S6e} > *`))}),ae.sort((le,fe)=>fe[1]-le[1]).forEach(le=>{var fe;let ye=(fe=y.current)==null?void 0:fe.querySelector(`${uU}[${vT}="${encodeURIComponent(le[0])}"]`);ye?.parentElement.appendChild(ye)})}function F(){let oe=K().find(re=>re.getAttribute("aria-disabled")!=="true"),ae=oe?.getAttribute(vT);B.setState("value",ae||void 0)}function R(){var oe,ae,re,le;if(!n.current.search||s.current.shouldFilter===!1){n.current.filtered.count=o.current.size;return}n.current.filtered.groups=new Set;let fe=0;for(let ye of o.current){let be=(ae=(oe=r.current.get(ye))==null?void 0:oe.value)!=null?ae:"",ue=(le=(re=r.current.get(ye))==null?void 0:re.keywords)!=null?le:[],Be=D(be,ue);n.current.filtered.items.set(ye,Be),Be>0&&fe++}for(let[ye,be]of i.current)for(let ue of be)if(n.current.filtered.items.get(ue)>0){n.current.filtered.groups.add(ye);break}n.current.filtered.count=fe}function H(){var oe,ae,re;let le=G();le&&(((oe=le.parentElement)==null?void 0:oe.firstChild)===le&&((re=(ae=le.closest(uU))==null?void 0:ae.querySelector(azo))==null||re.scrollIntoView({block:"nearest"})),le.scrollIntoView({block:"nearest"}))}function G(){var oe;return(oe=y.current)==null?void 0:oe.querySelector(`${gkt}[aria-selected="true"]`)}function K(){var oe;return Array.from(((oe=y.current)==null?void 0:oe.querySelectorAll(ukt))||[])}function V(oe){let ae=K()[oe];ae&&B.setState("value",ae.getAttribute(vT))}function W(oe){var ae;let re=G(),le=K(),fe=le.findIndex(be=>be===re),ye=le[fe+oe];(ae=s.current)!=null&&ae.loop&&(ye=fe+oe<0?le[le.length-1]:fe+oe===le.length?le[0]:le[fe+oe]),ye&&B.setState("value",ye.getAttribute(vT))}function X(oe){let ae=G(),re=ae?.closest(uU),le;for(;re&&!le;)re=oe>0?Izo(re,uU):Czo(re,uU),le=re?.querySelector(ukt);le?B.setState("value",le.getAttribute(vT)):W(oe)}let ie=()=>V(K().length-1),se=oe=>{oe.preventDefault(),oe.metaKey?ie():oe.altKey?X(1):W(1)},ee=oe=>{oe.preventDefault(),oe.metaKey?V(0):oe.altKey?X(-1):W(-1)};return j.createElement(Oa.div,{ref:e,tabIndex:-1,...m,"cmdk-root":"",onKeyDown:oe=>{var ae;(ae=m.onKeyDown)==null||ae.call(m,oe);let re=oe.nativeEvent.isComposing||oe.keyCode===229;if(!(oe.defaultPrevented||re))switch(oe.key){case"n":case"j":{p&&oe.ctrlKey&&se(oe);break}case"ArrowDown":{se(oe);break}case"p":case"k":{p&&oe.ctrlKey&&ee(oe);break}case"ArrowUp":{ee(oe);break}case"Home":{oe.preventDefault(),V(0);break}case"End":{oe.preventDefault(),ie();break}case"Enter":{oe.preventDefault();let le=G();if(le){let fe=new Event(b6e);le.dispatchEvent(fe)}}}}},j.createElement("label",{"cmdk-label":"",htmlFor:S.inputId,id:S.labelId,style:Ezo},a),tre(t,oe=>j.createElement(hkt.Provider,{value:B},j.createElement(dkt.Provider,{value:S},oe))))}),lzo=j.forwardRef((t,e)=>{var n,o;let i=rp(),r=j.useRef(null),A=j.useContext(_kt),s=dU(),a=pkt(t),c=(o=(n=a.current)==null?void 0:n.forceMount)!=null?o:A?.forceMount;o6(()=>{if(!c)return s.item(i,A?.id)},[c]);let l=Ikt(i,r,[t.value,t.children,r],t.keywords),g=D6e(),u=_w(x=>x.value&&x.value===l.current),h=_w(x=>c||s.filter()===!1?!0:x.search?x.filtered.items.get(i)>0:!0);j.useEffect(()=>{let x=r.current;if(!(!x||t.disabled))return x.addEventListener(b6e,d),()=>x.removeEventListener(b6e,d)},[h,t.onSelect,t.disabled]);function d(){var x,B;_(),(B=(x=a.current).onSelect)==null||B.call(x,l.current)}function _(){g.setState("value",l.current,!0)}if(!h)return null;let{disabled:p,value:m,onSelect:C,forceMount:I,keywords:f,...y}=t;return j.createElement(Oa.div,{ref:Mv(r,e),...y,id:i,"cmdk-item":"",role:"option","aria-disabled":!!p,"aria-selected":!!u,"data-disabled":!!p,"data-selected":!!u,onPointerMove:p||s.getDisablePointerSelection()?void 0:_,onClick:p?void 0:d},t.children)}),gzo=j.forwardRef((t,e)=>{let{heading:n,children:o,forceMount:i,...r}=t,A=rp(),s=j.useRef(null),a=j.useRef(null),c=rp(),l=dU(),g=_w(h=>i||l.filter()===!1?!0:h.search?h.filtered.groups.has(A):!0);o6(()=>l.group(A),[]),Ikt(A,s,[t.value,t.heading,a]);let u=j.useMemo(()=>({id:A,forceMount:i}),[i]);return j.createElement(Oa.div,{ref:Mv(s,e),...r,"cmdk-group":"",role:"presentation",hidden:g?void 0:!0},n&&j.createElement("div",{ref:a,"cmdk-group-heading":"","aria-hidden":!0,id:c},n),tre(t,h=>j.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?c:void 0},j.createElement(_kt.Provider,{value:u},h))))}),uzo=j.forwardRef((t,e)=>{let{alwaysRender:n,...o}=t,i=j.useRef(null),r=_w(A=>!A.search);return!n&&!r?null:j.createElement(Oa.div,{ref:Mv(i,e),...o,"cmdk-separator":"",role:"separator"})}),dzo=j.forwardRef((t,e)=>{let{onValueChange:n,...o}=t,i=t.value!=null,r=D6e(),A=_w(c=>c.search),s=_w(c=>c.selectedItemId),a=dU();return j.useEffect(()=>{t.value!=null&&r.setState("search",t.value)},[t.value]),j.createElement(Oa.input,{ref:e,...o,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":a.listId,"aria-labelledby":a.labelId,"aria-activedescendant":s,id:a.inputId,type:"text",value:i?t.value:A,onChange:c=>{i||r.setState("search",c.target.value),n?.(c.target.value)}})}),hzo=j.forwardRef((t,e)=>{let{children:n,label:o="Suggestions",...i}=t,r=j.useRef(null),A=j.useRef(null),s=_w(c=>c.selectedItemId),a=dU();return j.useEffect(()=>{if(A.current&&r.current){let c=A.current,l=r.current,g,u=new ResizeObserver(()=>{g=requestAnimationFrame(()=>{let h=c.offsetHeight;l.style.setProperty("--cmdk-list-height",h.toFixed(1)+"px")})});return u.observe(c),()=>{cancelAnimationFrame(g),u.unobserve(c)}}},[]),j.createElement(Oa.div,{ref:Mv(r,e),...i,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":s,"aria-label":o,id:a.listId},tre(t,c=>j.createElement("div",{ref:Mv(A,a.listInnerRef),"cmdk-list-sizer":""},c)))}),_zo=j.forwardRef((t,e)=>{let{open:n,onOpenChange:o,overlayClassName:i,contentClassName:r,container:A,...s}=t;return j.createElement(h3e,{open:n,onOpenChange:o},j.createElement(_3e,{container:A},j.createElement(Eie,{"cmdk-overlay":"",className:i}),j.createElement(xie,{"aria-label":t.label,"cmdk-dialog":"",className:r},j.createElement(mkt,{ref:e,...s}))))}),mzo=j.forwardRef((t,e)=>_w(n=>n.filtered.count===0)?j.createElement(Oa.div,{ref:e,...t,"cmdk-empty":"",role:"presentation"}):null),pzo=j.forwardRef((t,e)=>{let{progress:n,children:o,label:i="Loading...",...r}=t;return j.createElement(Oa.div,{ref:e,...r,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":i},tre(t,A=>j.createElement("div",{"aria-hidden":!0},A)))}),Iy=Object.assign(mkt,{List:hzo,Item:lzo,Input:dzo,Group:gzo,Separator:uzo,Dialog:_zo,Empty:mzo,Loading:pzo});function Izo(t,e){let n=t.nextElementSibling;for(;n;){if(n.matches(e))return n;n=n.nextElementSibling}}function Czo(t,e){let n=t.previousElementSibling;for(;n;){if(n.matches(e))return n;n=n.previousElementSibling}}function pkt(t){let e=j.useRef(t);return o6(()=>{e.current=t}),e}var o6=typeof window>"u"?j.useEffect:j.useLayoutEffect;function NT(t){let e=j.useRef();return e.current===void 0&&(e.current=t()),e}function _w(t){let e=D6e(),n=()=>t(e.snapshot());return j.useSyncExternalStore(e.subscribe,n,n)}function Ikt(t,e,n,o=[]){let i=j.useRef(),r=dU();return o6(()=>{var A;let s=(()=>{var c;for(let l of n){if(typeof l=="string")return l.trim();if(typeof l=="object"&&"current"in l)return l.current?(c=l.current.textContent)==null?void 0:c.trim():i.current}})(),a=o.map(c=>c.trim());r.value(t,s,a),(A=e.current)==null||A.setAttribute(vT,s),i.current=s}),i}var fzo=()=>{let[t,e]=j.useState(),n=NT(()=>new Map);return o6(()=>{n.current.forEach(o=>o()),n.current=new Map},[t]),(o,i)=>{n.current.set(o,i),e({})}};function yzo(t){let e=t.type;return typeof e=="function"?e(t.props):"render"in e?e.render(t.props):t}function tre({asChild:t,children:e},n){return t&&j.isValidElement(e)?j.cloneElement(yzo(e),{ref:e.ref},n(e.props.children)):n(e)}var Ezo={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};const Ckt=j.forwardRef(({className:t,...e},n)=>J.jsx(Iy,{ref:n,className:qi("rf-flex rf-h-full rf-w-full rf-flex-col rf-overflow-hidden rf-rounded-md rf-bg-white rf-text-zinc-950 dark:rf-bg-zinc-950 dark:rf-text-zinc-50",t),...e}));Ckt.displayName=Iy.displayName;const fkt=j.forwardRef(({className:t,...e},n)=>J.jsxs("div",{className:"rf-flex rf-items-center rf-border-b rf-px-3","cmdk-input-wrapper":"",children:[J.jsx(Wwe,{className:"rf-mr-2 rf-h-4 rf-w-4 rf-shrink-0 rf-opacity-50"}),J.jsx(Iy.Input,{ref:n,className:qi("rf-flex rf-h-10 rf-w-full rf-rounded-md rf-bg-transparent rf-py-3 rf-text-sm rf-outline-none placeholder:rf-text-zinc-500 disabled:rf-cursor-not-allowed disabled:rf-opacity-50 dark:placeholder:rf-text-zinc-400",t),...e})]}));fkt.displayName=Iy.Input.displayName;const ykt=j.forwardRef(({className:t,...e},n)=>J.jsx(Iy.List,{ref:n,className:qi("rf-max-h-[300px] rf-overflow-y-auto rf-overflow-x-hidden rf-py-1",t),...e}));ykt.displayName=Iy.List.displayName;const M6e=j.forwardRef((t,e)=>J.jsx(Iy.Empty,{ref:e,className:"rf-py-6 rf-text-center rf-text-sm",...t}));M6e.displayName=Iy.Empty.displayName;const hU=j.forwardRef(({className:t,...e},n)=>J.jsx(Iy.Group,{ref:n,className:qi("rf-overflow-hidden rf-px-1 rf-py-0 rf-text-zinc-950 [&_[cmdk-group-heading]]:rf-px-2 [&_[cmdk-group-heading]]:rf-py-1.5 [&_[cmdk-group-heading]]:rf-text-xs [&_[cmdk-group-heading]]:rf-font-medium [&_[cmdk-group-heading]]:rf-text-zinc-500 dark:rf-text-zinc-50 dark:[&_[cmdk-group-heading]]:rf-text-zinc-400",t),...e}));hU.displayName=Iy.Group.displayName;const xzo=j.forwardRef(({className:t,...e},n)=>J.jsx(Iy.Separator,{ref:n,className:qi("rf--mx-1 rf-h-px rf-bg-zinc-200 dark:rf-bg-zinc-800",t),...e}));xzo.displayName=Iy.Separator.displayName;const _U=j.forwardRef(({className:t,...e},n)=>J.jsx(Iy.Item,{ref:n,className:qi("rf-relative rf-flex rf-cursor-default rf-gap-2 rf-select-none rf-items-center rf-rounded-sm rf-px-2 rf-py-1.5 rf-text-sm rf-outline-none data-[disabled=true]:rf-pointer-events-none data-[selected=true]:rf-bg-zinc-100 data-[selected=true]:rf-text-zinc-900 data-[disabled=true]:rf-opacity-50 [&_svg]:rf-pointer-events-none [&_svg]:rf-size-4 [&_svg]:rf-shrink-0 dark:data-[selected=true]:rf-bg-zinc-800 dark:data-[selected=true]:rf-text-zinc-50",t),...e}));_U.displayName=Iy.Item.displayName;var Bzo=Object.defineProperty,mw=(t,e)=>Bzo(t,"name",{value:e,configurable:!0}),w6e="Popover",[Ekt,Ujo]=y2(w6e,[cT]),P6e=cT(),[Qzo,RT]=Ekt(w6e),Szo=mw(t=>{const{__scopePopover:e,children:n,open:o,defaultOpen:i,onOpenChange:r,modal:A=!1}=t,s=P6e(e),a=j.useRef(null),[c,l]=j.useState(!1),[g,u]=Ub({prop:o,defaultProp:i??!1,onChange:r,caller:w6e});return J.jsx(_oe,{...s,children:J.jsx(Qzo,{scope:e,contentId:rp(),triggerRef:a,open:g,onOpenChange:u,onOpenToggle:j.useCallback(()=>u(h=>!h),[u]),hasCustomAnchor:c,onCustomAnchorAdd:j.useCallback(()=>l(!0),[]),onCustomAnchorRemove:j.useCallback(()=>l(!1),[]),modal:A,children:n})})},"Popover"),bzo="PopoverTrigger",Dzo=j.forwardRef(mw(function(e,n){const{__scopePopover:o,...i}=e,r=RT(bzo,o),A=P6e(o),s=dl(n,r.triggerRef),a=J.jsx(Oa.button,{type:"button","aria-haspopup":"dialog","aria-expanded":r.open,"aria-controls":r.open?r.contentId:void 0,"data-state":v6e(r.open),...i,ref:s,onClick:Pr(e.onClick,r.onOpenToggle)});return r.hasCustomAnchor?a:J.jsx(CPe,{asChild:!0,...A,children:a})},"PopoverTrigger")),xkt="PopoverPortal",[Mzo,wzo]=Ekt(xkt,{forceMount:void 0}),Pzo=mw(t=>{const{__scopePopover:e,forceMount:n,children:o,container:i}=t,r=RT(xkt,e);return J.jsx(Mzo,{scope:e,forceMount:n,children:J.jsx(JE,{present:n||r.open,children:J.jsx(yPe,{asChild:!0,container:i,children:o})})})},"PopoverPortal"),mU="PopoverContent",vzo=j.forwardRef(mw(function(e,n){const o=wzo(mU,e.__scopePopover),{forceMount:i=o.forceMount,...r}=e,A=RT(mU,e.__scopePopover);return J.jsx(JE,{present:i||A.open,children:A.modal?J.jsx(Rzo,{...r,ref:n}):J.jsx(Tzo,{...r,ref:n})})},"PopoverContent")),Nzo=JQ("PopoverContent.RemoveScroll"),Rzo=j.forwardRef(mw(function(e,n){const o=RT(mU,e.__scopePopover),i=j.useRef(null),r=dl(n,i),A=j.useRef(!1);return j.useEffect(()=>{const s=i.current;if(s)return xPe(s)},[]),J.jsx(xoe,{as:Nzo,allowPinchZoom:!0,children:J.jsx(Bkt,{...e,ref:r,trapFocus:o.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Pr(e.onCloseAutoFocus,s=>{s.preventDefault(),A.current||o.triggerRef.current?.focus()}),onPointerDownOutside:Pr(e.onPointerDownOutside,s=>{const a=s.detail.originalEvent,c=a.button===0&&a.ctrlKey===!0,l=a.button===2||c;A.current=l},{checkForDefaultPrevented:!1}),onFocusOutside:Pr(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1})})})},"PopoverContentModal")),Tzo=j.forwardRef(mw(function(e,n){const o=RT(mU,e.__scopePopover),i=j.useRef(!1),r=j.useRef(!1);return J.jsx(Bkt,{...e,ref:n,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:A=>{e.onCloseAutoFocus?.(A),A.defaultPrevented||(i.current||o.triggerRef.current?.focus(),A.preventDefault()),i.current=!1,r.current=!1},onInteractOutside:A=>{e.onInteractOutside?.(A),A.defaultPrevented||(i.current=!0,A.detail.originalEvent.type==="pointerdown"&&(r.current=!0));const s=A.target;o.triggerRef.current?.contains(s)&&A.preventDefault(),A.detail.originalEvent.type==="focusin"&&r.current&&A.preventDefault()}})},"PopoverContentNonModal")),Bkt=j.forwardRef(mw(function(e,n){const{__scopePopover:o,trapFocus:i,onOpenAutoFocus:r,onCloseAutoFocus:A,disableOutsidePointerEvents:s,onEscapeKeyDown:a,onPointerDownOutside:c,onFocusOutside:l,onInteractOutside:g,...u}=e,h=RT(mU,o),d=P6e(o);return QK(),J.jsx(oPe,{asChild:!0,loop:!0,trapped:i,onMountAutoFocus:r,onUnmountAutoFocus:A,children:J.jsx(toe,{asChild:!0,disableOutsidePointerEvents:s,onInteractOutside:g,onEscapeKeyDown:a,onPointerDownOutside:c,onFocusOutside:l,onDismiss:()=>h.onOpenChange(!1),deferPointerDownOutside:!0,children:J.jsx(fPe,{"data-state":v6e(h.open),role:"dialog",id:h.contentId,...d,...u,ref:n,style:{...u.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})},"PopoverContentImpl"));function v6e(t){return t?"open":"closed"}mw(v6e,"getState");var kzo=Szo,Fzo=Dzo,Lzo=Pzo,Qkt=vzo;const Hzo=kzo,Gzo=Fzo,Skt=j.forwardRef(({className:t,align:e="center",sideOffset:n=4,...o},i)=>J.jsx(Lzo,{children:J.jsx(Qkt,{ref:i,align:e,sideOffset:n,className:qi("rf-z-50 rf-w-72 rf-rounded-md rf-border rf-border-zinc-200 rf-bg-white rf-p-4 rf-text-zinc-950 rf-shadow-md rf-outline-none data-[state=open]:rf-animate-in data-[state=closed]:rf-animate-out data-[state=closed]:rf-fade-out-0 data-[state=open]:rf-fade-in-0 data-[state=closed]:rf-zoom-out-95 data-[state=open]:rf-zoom-in-95 data-[side=bottom]:rf-slide-in-from-top-2 data-[side=left]:rf-slide-in-from-right-2 data-[side=right]:rf-slide-in-from-left-2 data-[side=top]:rf-slide-in-from-bottom-2 rf-origin-[--radix-popover-content-transform-origin] dark:rf-border-zinc-800 dark:rf-bg-zinc-950 dark:rf-text-zinc-50",t),...o})}));Skt.displayName=Qkt.displayName;function bkt(t,e){const n=t.lastIndexOf("."),o=e.lastIndexOf("."),i=n>0?t.substring(0,n):t,r=o>0?e.substring(0,o):e;if(i!==r&&t.substring(n)===e.substring(o)){if(i.startsWith(r))return 1;if(r.startsWith(i))return-1}return t.localeCompare(e,void 0,{numeric:!0,sensitivity:"base"})}function Ozo(t){const e=[],n=new Map;n.set("",{name:"",path:"",type:"folder",children:e});for(const o of t){const i=o.split("/");let r="";for(let A=0;A<i.length;A++){const s=i[A],a=r;if(r=r?`${r}/${s}`:s,!n.has(r)){const c=A===i.length-1,l={name:s,path:r,type:c?"file":"folder",children:c?void 0:[]};n.set(r,l);const g=n.get(a);g&&g.children&&g.children.push(l)}}}return e}function Dkt(t,e){for(const n of t){if(n.path===e)return n;if(n.children){const o=Dkt(n.children,e);if(o)return o}}return null}function Kzo(t,e){let n;if(e?n=Dkt(t,e):n={name:"",path:"",type:"folder",children:t},!n||!n.children)return{files:[],folders:[]};const o=n.children.filter(r=>r.type==="file"),i=n.children.filter(r=>r.type==="folder");return o.sort((r,A)=>bkt(r.name,A.name)),i.sort((r,A)=>bkt(r.name,A.name)),{files:o,folders:i}}const Uzo=t=>{const e=t.split("/").pop()||"";return e.endsWith(".py.tsx")?e.slice(0,-4):e};function N6e(t){const e=t.lastIndexOf("/");return e===-1?"/":t.substring(0,e)}function Yzo({currentFile:t,files:e}){const[n,o]=j.useState(!1),[i,r]=j.useState(()=>{if(typeof window<"u"){const a=new URLSearchParams(window.location.search),c=new URLSearchParams(window.location.hash.slice(1)),l=a.get("file")??c.get("file");if(l&&e.includes(l)){const g=N6e(l);return g==="/"?null:g}}if(t&&e.includes(t)){const a=N6e(t);return a==="/"?null:a}return null});return j.useEffect(()=>{if(t&&!n&&e.includes(t)){const a=N6e(t);r(a==="/"?null:a)}},[t,n,e]),{currentFolder:i,navigateToFolder:a=>{r(a),o(!0)},resetManualNavigation:()=>{o(!1)}}}const R6e=t=>t.endsWith(".tsx")||t.endsWith(".jsx")?J.jsx(BPo,{className:"rf-h-4 rf-w-4 rf-text-blue-500"}):t.endsWith(".md")||t.endsWith(".txt")?J.jsx(bPo,{className:"rf-h-4 rf-w-4 rf-text-gray-600"}):J.jsx(DPo,{className:"rf-h-4 rf-w-4 rf-text-gray-500"}),zzo=t=>t.endsWith(".tsx")||ere(t)||t.endsWith(".jsx"),Vzo=t=>Uzo(t),Mkt=t=>t.substring(0,t.lastIndexOf("/"))||"/",wkt=({files:t,onFileChange:e,currentFile:n,fileFilter:o=zzo,getDisplayName:i=Vzo,placeholder:r="Select file",searchPlaceholder:A="Search for file",emptyMessage:s="No files found in this directory.",pinnedFiles:a=[],onToggleFavorite:c,recentlySavedFiles:l=[]})=>{const[g,u]=j.useState(!1),[h,d]=j.useState(n),{currentFolder:_,navigateToFolder:p,resetManualNavigation:m}=Yzo({currentFile:h,files:t}),[C,I]=j.useState(0),[f,y]=j.useState(""),[x,B]=J7("runframe:recentlyViewed",[]),[S,D]=J7("runframe:showRecents",!1);j.useEffect(()=>{const re=le=>{(le.metaKey||le.ctrlKey)&&le.key==="k"&&(le.preventDefault(),u(fe=>!fe))};return window.addEventListener("keydown",re),()=>window.removeEventListener("keydown",re)},[]);const w=t.filter(o),F=j.useRef(null);j.useEffect(()=>{const re=()=>{F.current&&(clearTimeout(F.current),F.current=null)};return d(n),n&&w.includes(n)&&(re(),F.current=setTimeout(()=>{B(le=>{if(le[0]===n)return le;const fe=le.filter(ye=>ye!==n);return[n,...fe].slice(0,10)})},500)),re},[n,w,B]);const R=Ozo(w),{files:H,folders:G}=Kzo(R,_||""),V=(()=>{if(!f.trim())return{currentDirResults:[],globalResults:[]};const re=f.toLowerCase(),fe=w.map(ue=>{const Be=ue.split("/").pop()||"";return{path:ue,fileName:Be}}).filter(ue=>ue.fileName.toLowerCase().includes(re)||ue.path.toLowerCase().includes(re)),ye=fe.filter(ue=>_?ue.path.substring(0,ue.path.lastIndexOf("/"))===_:!ue.path.includes("/")),be=fe.filter(ue=>_?ue.path.substring(0,ue.path.lastIndexOf("/"))!==_:ue.path.includes("/"));return{currentDirResults:ye,globalResults:be}})(),W=f.trim().length>0,X=re=>{p(re),I(0)},ie=j.useCallback(()=>{if(!_)return;const re=_.lastIndexOf("/"),le=re===-1?null:_.substring(0,re);X(le)},[_,X]);j.useEffect(()=>{if(!g)return;const re=le=>{(le.metaKey||le.ctrlKey)&&le.key==="ArrowUp"&&(le.preventDefault(),ie())};return window.addEventListener("keydown",re),()=>window.removeEventListener("keydown",re)},[g,ie]);const se=j.useCallback((re,le,fe=!1)=>{if(d(re),I(le),u(!1),e(re),fe){const ye=re.lastIndexOf("/"),be=ye===-1?null:re.substring(0,ye);X(be)}},[e,X]);j.useEffect(()=>{const re=le=>{if((le.metaKey||le.ctrlKey)&&(le.key==="ArrowLeft"||le.key==="ArrowRight")){if(le.preventDefault(),!n||H.length===0)return;const fe=H.findIndex(ue=>ue.path===n);if(fe===-1)return;let ye;le.key==="ArrowLeft"?ye=fe===0?H.length-1:fe-1:ye=fe===H.length-1?0:fe+1;const be=H[ye];be&&se(be.path,ye)}};return window.addEventListener("keydown",re),()=>window.removeEventListener("keydown",re)},[n,H,se]),j.useEffect(()=>{if(H.length>0){const re=H.findIndex(le=>le.path===n);re>=0&&I(re)}},[H,n]);const ee=j.useMemo(()=>{const re=l.filter(ye=>w.includes(ye)),le=x.filter(ye=>w.includes(ye)),fe=[];re.length>0&&fe.push({path:re[0],type:"saved"});for(const ye of le){if(fe.length>=3)break;fe.some(be=>be.path===ye)||fe.push({path:ye,type:"viewed"})}return fe},[l,x,w]),oe=_??"/";oe.length>25&&""+oe.slice(-22);const ae=()=>`rf-w-full rf-min-w-[600px] ${W?"rf-max-w-[600px]":"rf-max-w-[1000px]"}`;return J.jsx("div",{className:"rf-flex rf-items-center rf-gap-1",children:J.jsxs(Hzo,{open:g,onOpenChange:re=>{u(re),re||(y(""),m())},children:[J.jsx(Gzo,{asChild:!0,children:J.jsxs(ta,{variant:"outline",role:"combobox","aria-expanded":g,className:"rf-w-fit rf-min-w-32 rf-max-w-100 rf-justify-center rf-items-center rf-gap-1 !rf-font-normal",children:[J.jsx("span",{className:"rf-truncate rf-text-left",children:h?i(h):r}),J.jsx(CPo,{className:"rf-opacity-50 rf-flex-shrink-0"})]})}),J.jsx(Skt,{className:qi("!rf-p-0 !rf-overflow-y-auto !rf-max-h-[80vh] !rf-z-[200]",ae()),children:J.jsxs(Ckt,{shouldFilter:!1,children:[J.jsx(fkt,{placeholder:A,className:"rf-h-9 rf-w-full",value:f,onValueChange:y}),ee.length>0&&J.jsxs("div",{className:"rf-border-b rf-border-gray-200",children:[J.jsxs("button",{onClick:()=>D(!S),className:"rf-w-full rf-px-3 rf-py-2 rf-flex rf-items-center rf-justify-between rf-text-xs rf-text-slate-600 hover:rf-bg-slate-50 rf-bg-transparent rf-border-none rf-cursor-pointer",children:[J.jsx("span",{className:"rf-font-medium",children:"Recent Files"}),J.jsx(Jwe,{className:qi("rf-h-4 rf-w-4 rf-transition-transform",!S&&"-rf-rotate-90")})]}),S&&J.jsx("div",{className:"rf-pb-1",children:ee.map((re,le)=>J.jsxs("div",{onClick:()=>se(re.path,le,!0),className:qi("rf-flex rf-items-center rf-px-3 rf-py-1.5 rf-cursor-pointer hover:rf-bg-slate-100",re.path===n&&"rf-font-medium"),children:[re.type==="saved"?J.jsx("span",{title:"Recently saved",children:J.jsx(LPo,{className:"rf-mr-2 rf-h-4 rf-w-4 rf-text-green-500"})}):J.jsx("span",{title:"Recently viewed",children:J.jsx(xPo,{className:"rf-mr-2 rf-h-4 rf-w-4 rf-text-blue-500"})}),J.jsx("span",{className:"rf-text-sm",children:i(re.path.split("/").pop()||"")}),J.jsx("span",{className:"rf-text-xs rf-text-muted-foreground rf-ml-2 rf-truncate rf-max-w-[40%]",children:Mkt(re.path)}),J.jsx(L3,{className:qi("rf-ml-auto rf-h-4 rf-w-4",re.path===n?"rf-opacity-100":"rf-opacity-0")})]},re.path))})]}),J.jsxs("div",{className:"rf-px-3 rf-py-2 rf-bg-slate-50 rf-flex rf-items-center rf-justify-between rf-gap-2",children:[J.jsx("div",{className:"rf-flex rf-items-center rf-text-xs rf-text-slate-600 rf-min-w-0 rf-flex-1",children:J.jsxs("div",{className:"rf-flex rf-items-center rf-min-w-0",children:[J.jsx("button",{onClick:()=>X(null),className:"rf-text-blue-600 hover:rf-text-blue-800 rf-underline rf-cursor-pointer rf-bg-transparent rf-border-none rf-p-0 rf-flex-shrink-0",children:"root"}),_?.split("/").filter(Boolean).map((re,le,fe)=>{const ye=fe.slice(0,le+1).join("/");return J.jsxs("span",{className:"rf-flex rf-items-center rf-min-w-0",children:[J.jsx("span",{className:"rf-mx-1 rf-flex-shrink-0",children:"/"}),le===fe.length-1?J.jsx("span",{className:"rf-text-slate-800 rf-truncate rf-max-w-[200px]",title:re,children:re}):J.jsx("button",{onClick:()=>X(ye),className:"rf-text-blue-600 hover:rf-text-blue-800 rf-underline rf-cursor-pointer rf-bg-transparent rf-border-none rf-p-0 rf-truncate rf-max-w-[150px]",title:re,children:re})]},ye)})]})}),J.jsx("div",{className:"rf-flex rf-items-center rf-gap-2 rf-flex-shrink-0",children:_&&J.jsxs("button",{onClick:ie,className:"rf-flex rf-items-center rf-gap-1 rf-text-slate-600 hover:rf-text-slate-800 rf-bg-transparent rf-border-none rf-p-1 rf-rounded hover:rf-bg-slate-200 rf-transition-colors",title:"Go up one level",children:[J.jsx(pPo,{className:"rf-h-3 rf-w-3"}),J.jsx("span",{className:"rf-text-xs rf-font-medium",children:"Up"})]})})]}),J.jsx(ykt,{className:"rf-overflow-visible rf-max-h-none",children:W?J.jsx(J.Fragment,{children:V.currentDirResults.length===0&&V.globalResults.length===0?J.jsxs(M6e,{children:['No files found matching "',f,'".']}):J.jsxs(J.Fragment,{children:[V.currentDirResults.length>0&&J.jsx(hU,{children:V.currentDirResults.map((re,le)=>J.jsxs(_U,{value:`search-current:${re.path}`,onSelect:()=>{d(re.path),u(!1),e(re.path)},className:qi(re.path===n&&"rf-font-medium","rf-group"),children:[J.jsx("span",{className:"rf-mr-2",children:R6e(re.fileName)}),J.jsxs("div",{className:"rf-flex rf-items-center rf-w-full rf-min-w-0",children:[J.jsx("span",{className:"rf-truncate rf-flex-1",children:i(re.fileName)}),J.jsx("span",{className:"rf-text-xs rf-text-muted-foreground rf-ml-2 rf-truncate rf-max-w-[40%]",children:_||"/"}),re.path===n&&J.jsx(L3,{className:"rf-ml-2 rf-h-4 rf-w-4 rf-flex-shrink-0"})]})]},re.path))}),V.globalResults.length>0&&J.jsx(hU,{children:V.globalResults.map(re=>J.jsxs(_U,{value:`search-global:${re.path}`,onSelect:()=>{d(re.path),u(!1),e(re.path)},className:qi(re.path===n&&"rf-font-medium","rf-group"),children:[J.jsx("span",{className:"rf-mr-2",children:R6e(re.fileName)}),J.jsxs("div",{className:"rf-flex rf-items-center rf-w-full rf-min-w-0",children:[J.jsx("span",{className:"rf-truncate rf-flex-1",children:i(re.fileName)}),J.jsx("span",{className:"rf-text-xs rf-text-muted-foreground rf-ml-2 rf-truncate rf-max-w-[40%]",children:Mkt(re.path)}),re.path===n&&J.jsx(L3,{className:"rf-ml-2 rf-h-4 rf-w-4 rf-flex-shrink-0"})]})]},re.path))})]})}):J.jsxs(J.Fragment,{children:[J.jsx(M6e,{children:s}),H.length>0&&J.jsx(hU,{children:H.map((re,le)=>J.jsxs(_U,{value:`current:${re.path}`,onSelect:()=>se(re.path,le),className:qi(re.path===n&&"rf-font-medium","rf-group"),children:[J.jsx("span",{className:"rf-mr-2",children:R6e(re.name)}),i(re.name),J.jsx("div",{className:"rf-ml-auto rf-flex rf-items-center rf-gap-1",children:J.jsx(L3,{className:qi("rf-h-4 rf-w-4",re.path===n?"rf-opacity-100":"rf-opacity-0")})})]},re.path))}),G.length>0&&J.jsx(hU,{children:G.map(re=>J.jsxs(_U,{value:`folder-${re.path}`,onSelect:()=>X(re.path),className:"rf-text-slate-600 hover:rf-text-slate-900",children:[J.jsx(MPo,{className:"rf-mr-2 rf-h-4 rf-w-4 rf-text-blue-600"}),re.name,J.jsx(iT,{className:"rf-ml-auto rf-h-4 rf-w-4"})]},re.path))}),H.length===0&&G.length===0&&J.jsx("div",{className:"rf-p-4 rf-text-center rf-text-slate-500 rf-text-sm",children:"No files or folders in this directory"})]})})]})})]})})},Pkt=({files:t,onFileChange:e,currentFile:n})=>J.jsx(wkt,{files:t,onFileChange:e,currentFile:n,fileFilter:()=>!0,placeholder:"Select circuit",searchPlaceholder:"Search for circuit file",emptyMessage:"No circuit files found in this directory."}),Jzo=({hash:t,initialCircuitPath:e})=>{const n=new URLSearchParams(t.startsWith("#")?t.slice(1):t);return n.get("file")??n.get("main_component")??e??""},qzo=({hash:t,filePath:e})=>{const n=new URLSearchParams(t.startsWith("#")?t.slice(1):t);if(n.get("file")===e&&(!n.has("main_component")||n.get("main_component")===e))return t.startsWith("#")?t:t?`#${t}`:"";n.set("file",e),n.has("main_component")&&n.set("main_component",e);const o=n.toString();return o?`#${o}`:""},Wzo=t=>{const[e,n]=j.useState(()=>typeof window>"u"?t??"":Jzo({hash:window.location.hash,initialCircuitPath:t})),o=j.useCallback(i=>{if(typeof window>"u")return;const r=qzo({hash:window.location.hash,filePath:i});if(r===window.location.hash)return;const A=`${window.location.pathname}${window.location.search}${r}`;window.history.replaceState(null,"",A)},[]);return{currentCircuitJsonPath:e,setCurrentCircuitJsonPath:n,updateFileHash:o}},jzo=t=>t instanceof Error?t.message:"An unknown error occurred",Xzo=t=>{fie();const{currentCircuitJsonPath:e,setCurrentCircuitJsonPath:n,updateFileHash:o}=Wzo(t.initialCircuitPath),[i,r]=j.useState(null),[A,s]=j.useState(!1),[a,c]=j.useState({}),[l,g]=j.useState(new Set),[u,h]=j.useState(new Set),d=t.files,_=d.map(y=>y.filePath),p=j.useCallback(async y=>{if(!y.fileStaticAssetUrl)throw new Error(`No fileStaticAssetUrl provided for ${y.filePath}`);const x=await fetch(y.fileStaticAssetUrl);if(!x.ok)throw new Error(`Failed to fetch ${y.filePath}: ${x.statusText}`);return await x.json()},[]),m=j.useCallback(async y=>{if(a[y]){r(a[y]),o(y),t.onCircuitJsonPathChange?.(y);return}if(u.has(y)){console.warn(`Skipping failed file: ${y}`),r(null);return}if(!l.has(y)){g(x=>new Set(x).add(y)),s(!0),r(null);try{const x=d.find(D=>D.filePath===y);if(!x)throw new Error(`File reference not found for ${y}`);const S=await(t.onFetchFile||p)(x);c(D=>({...D,[y]:S})),r(S),o(y),t.onCircuitJsonPathChange?.(y),h(D=>{const w=new Set(D);return w.delete(y),w})}catch(x){console.error(`Failed to load circuit JSON file ${y}:`,x),h(B=>new Set(B).add(y)),r(null)}finally{g(x=>{const B=new Set(x);return B.delete(y),B}),s(!1)}}},[d,a,l,u,t.onFetchFile,t.onCircuitJsonPathChange,p,o]);j.useEffect(()=>{if(_.length===0)return;let y=e;(!y||!_.includes(y))&&(y=jkt(_)??_[0],n(y)),y&&_.includes(y)&&m(y)},[e]);const C=j.useCallback(y=>{n(y)},[]),I=j.useCallback(y=>{h(x=>{const B=new Set(x);return B.delete(y),B}),m(y)},[m]);if(_.length===0)return J.jsx("div",{className:"rf-flex rf-flex-col rf-w-full rf-h-full rf-items-center rf-justify-center",children:J.jsxs("div",{className:"rf-text-center rf-p-8",children:[J.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-gray-800 rf-mb-2",children:"No Circuit JSON Files Found"}),J.jsx("p",{className:"rf-text-sm rf-text-gray-600",children:"Please provide circuit JSON files to view."})]})});const f=u.has(e);return J.jsx(gx,{fallbackRender:({error:y})=>J.jsx("div",{className:"rf-mt-4 rf-mx-4 rf-bg-red-50 rf-rounded-md rf-border rf-border-red-200",children:J.jsxs("div",{className:"rf-p-4",children:[J.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-red-800 rf-mb-3",children:"Error loading Circuit JSON Preview"}),J.jsx("p",{className:"rf-text-xs rf-font-mono rf-whitespace-pre-wrap rf-text-red-600 rf-mt-2",children:jzo(y)})]})}),children:f?J.jsxs("div",{className:"rf-w-full rf-h-full rf-flex rf-flex-col",children:[J.jsxs("div",{className:"rf-flex rf-items-center rf-justify-between rf-w-full rf-p-4 rf-border-b rf-border-gray-200",children:[(t.showFileMenu??!0)&&J.jsx(cU,{isWebEmbedded:!0,circuitJson:null,projectName:t.projectName}),_.length>1&&J.jsx("div",{className:"rf-absolute rf-left-1/2 rf-transform rf--translate-x-1/2 rf-flex rf-items-center rf-gap-2",children:J.jsx(Pkt,{currentFile:e,files:_,onFileChange:C})})]}),J.jsx("div",{className:"rf-flex-1 rf-flex rf-items-center rf-justify-center",children:J.jsxs("div",{className:"rf-text-center rf-p-8",children:[J.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-red-600 rf-mb-2",children:"Failed to Load Circuit File"}),J.jsxs("p",{className:"rf-text-sm rf-text-gray-600 rf-mb-4",children:["Could not load: ",e]}),J.jsxs("div",{className:"rf-flex rf-flex-col rf-items-center rf-gap-2",children:[J.jsx("button",{onClick:()=>I(e),className:"rf-px-4 rf-py-2 rf-bg-blue-500 rf-text-white rf-rounded rf-hover:bg-blue-600",children:"Retry"}),_.length>1&&J.jsx("p",{className:"rf-text-xs rf-text-gray-500",children:"Or select a different file from the dropdown above"})]})]})})]}):J.jsx(VTt,{circuitJson:i,defaultToFullScreen:t.defaultToFullScreen,showToggleFullScreen:t.showToggleFullScreen,showFileMenu:!1,isWebEmbedded:!1,projectName:t.projectName,defaultActiveTab:t.tabSelected,leftHeaderContent:J.jsxs("div",{className:"rf-flex rf-items-center rf-justify-between rf-w-full",children:[(t.showFileMenu??!0)&&J.jsx(cU,{isWebEmbedded:!0,circuitJson:i,projectName:t.projectName}),_.length>1&&J.jsx("div",{className:`rf-absolute rf-left-1/2 rf-transform rf--translate-x-1/2 rf-flex rf-items-center rf-gap-2 ${A?"rf-opacity-50":""}`,children:J.jsx(Pkt,{currentFile:e,files:_,onFileChange:C})})]})})})},$zo=()=>{const t=Yu(e=>e.fsMap);j.useEffect(()=>{if(!document||!t)return;const e=Array.from(t.keys()),n=jkt(e),o=t.get("package.json");try{if(o){const i=JSON.parse(o);if(i?.name){document.title=i.name;return}}}catch{}n&&(document.title=n)},[t])},vkt=(t,e,n)=>{const o=t instanceof RegExp?Nkt(t,n):t,i=e instanceof RegExp?Nkt(e,n):e,r=o!==null&&i!=null&&Zzo(o,i,n);return r&&{start:r[0],end:r[1],pre:n.slice(0,r[0]),body:n.slice(r[0]+o.length,r[1]),post:n.slice(r[1]+i.length)}},Nkt=(t,e)=>{const n=e.match(t);return n?n[0]:null},Zzo=(t,e,n)=>{let o,i,r,A,s,a=n.indexOf(t),c=n.indexOf(e,a+1),l=a;if(a>=0&&c>0){if(t===e)return[a,c];for(o=[],r=n.length;l>=0&&!s;){if(l===a)o.push(l),a=n.indexOf(t,l+1);else if(o.length===1){const g=o.pop();g!==void 0&&(s=[g,c])}else i=o.pop(),i!==void 0&&i<r&&(r=i,A=c),c=n.indexOf(e,l+1);l=a<c&&a>=0?a:c}o.length&&A!==void 0&&(s=[r,A])}return s},Rkt="\0SLASH"+Math.random()+"\0",Tkt="\0OPEN"+Math.random()+"\0",T6e="\0CLOSE"+Math.random()+"\0",kkt="\0COMMA"+Math.random()+"\0",Fkt="\0PERIOD"+Math.random()+"\0",eVo=new RegExp(Rkt,"g"),tVo=new RegExp(Tkt,"g"),nVo=new RegExp(T6e,"g"),oVo=new RegExp(kkt,"g"),iVo=new RegExp(Fkt,"g"),rVo=/\\\\/g,AVo=/\\{/g,sVo=/\\}/g,aVo=/\\,/g,cVo=/\\\./g,lVo=1e5,gVo=4e6;function k6e(t){return isNaN(t)?t.charCodeAt(0):parseInt(t,10)}function uVo(t){return t.replace(rVo,Rkt).replace(AVo,Tkt).replace(sVo,T6e).replace(aVo,kkt).replace(cVo,Fkt)}function dVo(t){return t.replace(eVo,"\\").replace(tVo,"{").replace(nVo,"}").replace(oVo,",").replace(iVo,".")}function Lkt(t){if(!t)return[""];const e=[],n=vkt("{","}",t);if(!n)return t.split(",");const{pre:o,body:i,post:r}=n,A=o.split(",");A[A.length-1]+="{"+i+"}";const s=Lkt(r);return r.length&&(A[A.length-1]+=s.shift(),A.push.apply(A,s)),e.push.apply(e,A),e}function hVo(t,e={}){if(!t)return[];const{max:n=lVo,maxLength:o=gVo}=e;return t.slice(0,2)==="{}"&&(t="\\{\\}"+t.slice(2)),F6e(uVo(t),n,o,!0).map(dVo)}function _Vo(t){return"{"+t+"}"}function mVo(t){return/^-?0\d/.test(t)}function pVo(t,e){return t<=e}function IVo(t,e){return t>=e}function pU(t,e,n,o,i,r){const A=[];let s=0;for(let a=0;a<t.length;a++)for(let c=0;c<n.length;c++){if(A.length>=o)return A;const l=t[a]+e+n[c];if(!(r&&!l)){if(s+l.length>i)return A;A.push(l),s+=l.length}}return A}function CVo(t,e,n){const o=t.split(/\.\./),i=[];if(o[0]===void 0||o[1]===void 0)return i;const r=k6e(o[0]),A=k6e(o[1]),s=Math.max(o[0].length,o[1].length);let a=o.length===3&&o[2]!==void 0?Math.max(Math.abs(k6e(o[2])),1):1,c=pVo;A<r&&(a*=-1,c=IVo);const g=o.some(mVo);for(let u=r;c(u,A)&&i.length<n;u+=a){let h;if(e)h=String.fromCharCode(u),h==="\\"&&(h="");else if(h=String(u),g){const d=s-h.length;if(d>0){const _=new Array(d+1).join("0");u<0?h="-"+_+h.slice(1):h=_+h}}i.push(h)}return i}function F6e(t,e,n,o){let i=[""],r=!1,A=!0;for(;;){const s=vkt("{","}",t);if(!s)return pU(i,t,[""],e,n,r);const a=s.pre;if(/\$$/.test(a)){if(i=pU(i,a+"{"+s.body+"}",[""],e,n,r&&!s.post.length),A=!1,!s.post.length)break;t=s.post;continue}const c=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(s.body),l=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(s.body),g=c||l,u=s.body.indexOf(",")>=0;if(!g&&!u){if(s.post.match(/,(?!,).*\}/)){t=s.pre+"{"+s.body+T6e+s.post,o=!0;continue}return pU(i,a+"{"+s.body+"}"+s.post,[""],e,n,r)}A&&(r=o&&!g,A=!1);let h;if(g)h=CVo(s.body,l,e);else{let d=Lkt(s.body);if(d.length===1&&d[0]!==void 0&&(d=F6e(d[0],e,n,!1).map(_Vo),d.length===1)){if(i=pU(i,a+d[0],[""],e,n,r&&!s.post.length),!s.post.length)break;t=s.post;continue}h=[];for(let _=0;_<d.length;_++)h.push.apply(h,F6e(d[_],e,n,!1))}if(i=pU(i,a,h,e,n,r&&!s.post.length),!s.post.length)break;t=s.post}return i}const fVo=1024*64,nre=t=>{if(typeof t!="string")throw new TypeError("invalid pattern");if(t.length>fVo)throw new TypeError("pattern is too long")},yVo={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},IU=t=>t.replace(/[[\]\\-]/g,"\\$&"),EVo=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Hkt=t=>t.join(""),xVo=(t,e)=>{const n=e;if(t.charAt(n)!=="[")throw new Error("not in a brace expression");const o=[],i=[];let r=n+1,A=!1,s=!1,a=!1,c=!1,l=n,g="";e:for(;r<t.length;){const _=t.charAt(r);if((_==="!"||_==="^")&&r===n+1){c=!0,r++;continue}if(_==="]"&&A&&!a){l=r+1;break}if(A=!0,_==="\\"&&!a){a=!0,r++;continue}if(_==="["&&!a){for(const[p,[m,C,I]]of Object.entries(yVo))if(t.startsWith(p,r)){if(g)return["$.",!1,t.length-n,!0];r+=p.length,I?i.push(m):o.push(m),s=s||C;continue e}}if(a=!1,g){_>g?o.push(IU(g)+"-"+IU(_)):_===g&&o.push(IU(_)),g="",r++;continue}if(t.startsWith("-]",r+1)){o.push(IU(_+"-")),r+=2;continue}if(t.startsWith("-",r+1)){g=_,r+=2;continue}o.push(IU(_)),r++}if(l<r)return["",!1,0,!1];if(!o.length&&!i.length)return["$.",!1,t.length-n,!0];if(i.length===0&&o.length===1&&/^\\?.$/.test(o[0])&&!c){const _=o[0].length===2?o[0].slice(-1):o[0];return[EVo(_),!1,l-n,!1]}const u="["+(c?"^":"")+Hkt(o)+"]",h="["+(c?"":"^")+Hkt(i)+"]";return[o.length&&i.length?"("+u+"|"+h+")":o.length?u:h,s,l-n,!0]},CU=(t,{windowsPathsNoEscape:e=!1,magicalBraces:n=!0}={})=>n?e?t.replace(/\[([^/\\])\]/g,"$1"):t.replace(/((?!\\).|^)\[([^/\\])\]/g,"$1$2").replace(/\\([^/])/g,"$1"):e?t.replace(/\[([^/\\{}])\]/g,"$1"):t.replace(/((?!\\).|^)\[([^/\\{}])\]/g,"$1$2").replace(/\\([^/{}])/g,"$1");var Cy;const BVo=new Set(["!","?","+","*","@"]),L6e=t=>BVo.has(t),Gkt=t=>L6e(t.type),QVo=new Map([["!",["@"]],["?",["?","@"]],["@",["@"]],["*",["*","+","?","@"]],["+",["+","@"]]]),SVo=new Map([["!",["?"]],["@",["?"]],["+",["?","*"]]]),bVo=new Map([["!",["?","@"]],["?",["?","@"]],["@",["?","@"]],["*",["*","+","?","@"]],["+",["+","@","?","*"]]]),Okt=new Map([["!",new Map([["!","@"]])],["?",new Map([["*","*"],["+","*"]])],["@",new Map([["!","!"],["?","?"],["@","@"],["*","*"],["+","+"]])],["+",new Map([["?","*"],["*","*"]])]]),DVo="(?!(?:^|/)\\.\\.?(?:$|/))",ore="(?!\\.)",MVo=new Set(["[","."]),wVo=new Set(["..","."]),PVo=new Set("().*{}+?[]^$\\!"),vVo=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),H6e="[^/]",Kkt=H6e+"*?",Ukt=H6e+"+?";let NVo=0;class G6e{type;#i;#n;#o=!1;#t=[];#e;#A;#r;#c=!1;#s;#l;#u=!1;id=++NVo;get depth(){return(this.#e?.depth??-1)+1}[Symbol.for("nodejs.util.inspect.custom")](){return{"@@type":"AST",id:this.id,type:this.type,root:this.#i.id,parent:this.#e?.id,depth:this.depth,partsLength:this.#t.length,parts:this.#t}}constructor(e,n,o={}){this.type=e,e&&(this.#n=!0),this.#e=n,this.#i=this.#e?this.#e.#i:this,this.#s=this.#i===this?o:this.#i.#s,this.#r=this.#i===this?[]:this.#i.#r,e==="!"&&!this.#i.#c&&this.#r.push(this),this.#A=this.#e?this.#e.#t.length:0}get hasMagic(){if(this.#n!==void 0)return this.#n;for(const e of this.#t)if(typeof e!="string"&&(e.type||e.hasMagic))return this.#n=!0;return this.#n}toString(){return this.#l!==void 0?this.#l:this.type?this.#l=this.type+"("+this.#t.map(e=>String(e)).join("|")+")":this.#l=this.#t.map(e=>String(e)).join("")}#d(){if(this!==this.#i)throw new Error("should only call on root");if(this.#c)return this;this.toString(),this.#c=!0;let e;for(;e=this.#r.pop();){if(e.type!=="!")continue;let n=e,o=n.#e;for(;o;){for(let i=n.#A+1;!o.type&&i<o.#t.length;i++)for(const r of e.#t){if(typeof r=="string")throw new Error("string part in extglob AST??");r.copyIn(o.#t[i])}n=o,o=n.#e}}return this}push(...e){for(const n of e)if(n!==""){if(typeof n!="string"&&!(n instanceof Cy&&n.#e===this))throw new Error("invalid part: "+n);this.#t.push(n)}}toJSON(){const e=this.type===null?this.#t.slice().map(n=>typeof n=="string"?n:n.toJSON()):[this.type,...this.#t.map(n=>n.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#i||this.#i.#c&&this.#e?.type==="!")&&e.push({}),e}isStart(){if(this.#i===this)return!0;if(!this.#e?.isStart())return!1;if(this.#A===0)return!0;const e=this.#e;for(let n=0;n<this.#A;n++){const o=e.#t[n];if(!(o instanceof Cy&&o.type==="!"))return!1}return!0}isEnd(){if(this.#i===this||this.#e?.type==="!")return!0;if(!this.#e?.isEnd())return!1;if(!this.type)return this.#e?.isEnd();const e=this.#e?this.#e.#t.length:0;return this.#A===e-1}copyIn(e){typeof e=="string"?this.push(e):this.push(e.clone(this))}clone(e){const n=new Cy(this.type,e);for(const o of this.#t)n.copyIn(o);return n}static#a(e,n,o,i,r){const A=i.maxExtglobRecursion??2;let s=!1,a=!1,c=-1,l=!1;if(n.type===null){let _=o,p="";for(;_<e.length;){const m=e.charAt(_++);if(s||m==="\\"){s=!s,p+=m;continue}if(a){_===c+1?(m==="^"||m==="!")&&(l=!0):m==="]"&&!(_===c+2&&l)&&(a=!1),p+=m;continue}else if(m==="["){a=!0,c=_,l=!1,p+=m;continue}if(!i.noext&&L6e(m)&&e.charAt(_)==="("&&r<=A){n.push(p),p="";const I=new Cy(m,n);_=Cy.#a(e,I,_,i,r+1),n.push(I);continue}p+=m}return n.push(p),_}let g=o+1,u=new Cy(null,n);const h=[];let d="";for(;g<e.length;){const _=e.charAt(g++);if(s||_==="\\"){s=!s,d+=_;continue}if(a){g===c+1?(_==="^"||_==="!")&&(l=!0):_==="]"&&!(g===c+2&&l)&&(a=!1),d+=_;continue}else if(_==="["){a=!0,c=g,l=!1,d+=_;continue}if(!i.noext&&L6e(_)&&e.charAt(g)==="("&&(r<=A||n&&n.#g(_))){const m=n&&n.#g(_)?0:1;u.push(d),d="";const C=new Cy(_,u);u.push(C),g=Cy.#a(e,C,g,i,r+m);continue}if(_==="|"){u.push(d),d="",h.push(u),u=new Cy(null,n);continue}if(_===")")return d===""&&n.#t.length===0&&(n.#u=!0),u.push(d),d="",n.push(...h,u),g;d+=_}return n.type=null,n.#n=void 0,n.#t=[e.substring(o-1)],g}#m(e){return this.#p(e,SVo)}#p(e,n=QVo){if(!e||typeof e!="object"||e.type!==null||e.#t.length!==1||this.type===null)return!1;const o=e.#t[0];return!o||typeof o!="object"||o.type===null?!1:this.#g(o.type,n)}#g(e,n=bVo){return!!n.get(this.type)?.includes(e)}#h(e,n){const o=e.#t[0],i=new Cy(null,o,this.options);i.#t.push(""),o.push(i),this.#_(e,n)}#_(e,n){const o=e.#t[0];this.#t.splice(n,1,...o.#t);for(const i of o.#t)typeof i=="object"&&(i.#e=this);this.#l=void 0}#f(e){return!!Okt.get(this.type)?.has(e)}#y(e){if(!e||typeof e!="object"||e.type!==null||e.#t.length!==1||this.type===null||this.#t.length!==1)return!1;const n=e.#t[0];return!n||typeof n!="object"||n.type===null?!1:this.#f(n.type)}#E(e){const n=Okt.get(this.type),o=e.#t[0],i=n?.get(o.type);if(!i)return!1;this.#t=o.#t;for(const r of this.#t)typeof r=="object"&&(r.#e=this);this.type=i,this.#l=void 0,this.#u=!1}static fromGlob(e,n={}){const o=new Cy(null,void 0,n);return Cy.#a(e,o,0,n,0),o}toMMPattern(){if(this!==this.#i)return this.#i.toMMPattern();const e=this.toString(),[n,o,i,r]=this.toRegExpSource();if(!(i||this.#n||this.#s.nocase&&!this.#s.nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase()))return o;const s=(this.#s.nocase?"i":"")+(r?"u":"");return Object.assign(new RegExp(`^${n}$`,s),{_src:n,_glob:e})}get options(){return this.#s}toRegExpSource(e){const n=e??!!this.#s.dot;if(this.#i===this&&(this.#I(),this.#d()),!Gkt(this)){const a=this.isStart()&&this.isEnd()&&!this.#t.some(h=>typeof h!="string"),c=this.#t.map(h=>{const[d,_,p,m]=typeof h=="string"?Cy.#x(h,this.#n,a):h.toRegExpSource(e);return this.#n=this.#n||p,this.#o=this.#o||m,d}).join("");let l="";if(this.isStart()&&typeof this.#t[0]=="string"&&!(this.#t.length===1&&wVo.has(this.#t[0]))){const d=MVo,_=n&&d.has(c.charAt(0))||c.startsWith("\\.")&&d.has(c.charAt(2))||c.startsWith("\\.\\.")&&d.has(c.charAt(4)),p=!n&&!e&&d.has(c.charAt(0));l=_?DVo:p?ore:""}let g="";return this.isEnd()&&this.#i.#c&&this.#e?.type==="!"&&(g="(?:$|\\/)"),[l+c+g,CU(c),this.#n=!!this.#n,this.#o]}const o=this.type==="*"||this.type==="+",i=this.type==="!"?"(?:(?!(?:":"(?:";let r=this.#C(n);if(this.isStart()&&this.isEnd()&&!r&&this.type!=="!"){const a=this.toString(),c=this;return c.#t=[a],c.type=null,c.#n=void 0,[a,CU(this.toString()),!1,!1]}let A=!o||e||n||!ore?"":this.#C(!0);A===r&&(A=""),A&&(r=`(?:${r})(?:${A})*?`);let s="";if(this.type==="!"&&this.#u)s=(this.isStart()&&!n?ore:"")+Ukt;else{const a=this.type==="!"?"))"+(this.isStart()&&!n&&!e?ore:"")+Kkt+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&A?")":this.type==="*"&&A?")?":`)${this.type}`;s=i+r+a}return[s,CU(r),this.#n=!!this.#n,this.#o]}#I(){if(Gkt(this)){let e=0,n=!1;do{n=!0;for(let o=0;o<this.#t.length;o++){const i=this.#t[o];typeof i=="object"&&(i.#I(),this.#p(i)?(n=!1,this.#_(i,o)):this.#m(i)?(n=!1,this.#h(i,o)):this.#y(i)&&(n=!1,this.#E(i)))}}while(!n&&++e<10)}else for(const e of this.#t)typeof e=="object"&&e.#I();this.#l=void 0}#C(e){return this.#t.map(n=>{if(typeof n=="string")throw new Error("string type in extglob ast??");const[o,i,r,A]=n.toRegExpSource(e);return this.#o=this.#o||A,o}).filter(n=>!(this.isStart()&&this.isEnd())||!!n).join("|")}static#x(e,n,o=!1){let i=!1,r="",A=!1,s=!1;for(let a=0;a<e.length;a++){const c=e.charAt(a);if(i){i=!1,r+=(PVo.has(c)?"\\":"")+c;continue}if(c==="*"){if(s)continue;s=!0,r+=o&&/^[*]+$/.test(e)?Ukt:Kkt,n=!0;continue}else s=!1;if(c==="\\"){a===e.length-1?r+="\\\\":i=!0;continue}if(c==="["){const[l,g,u,h]=xVo(e,a);if(u){r+=l,A=A||g,a+=u-1,n=n||h;continue}}if(c==="?"){r+=H6e,n=!0;continue}r+=vVo(c)}return[r,CU(e),!!n,A]}}Cy=G6e;const RVo=(t,{windowsPathsNoEscape:e=!1,magicalBraces:n=!1}={})=>n?e?t.replace(/[?*()[\]{}]/g,"[$&]"):t.replace(/[?*()[\]\\{}]/g,"\\$&"):e?t.replace(/[?*()[\]]/g,"[$&]"):t.replace(/[?*()[\]\\]/g,"\\$&");var TT={env:{}};const Of=(t,e,n={})=>(nre(e),!n.nocomment&&e.charAt(0)==="#"?!1:new fU(e,n).match(t)),TVo=/^\*+([^+@!?*[(]*)$/,kVo=t=>e=>!e.startsWith(".")&&e.endsWith(t),FVo=t=>e=>e.endsWith(t),LVo=t=>(t=t.toLowerCase(),e=>!e.startsWith(".")&&e.toLowerCase().endsWith(t)),HVo=t=>(t=t.toLowerCase(),e=>e.toLowerCase().endsWith(t)),GVo=/^\*+\.\*+$/,OVo=t=>!t.startsWith(".")&&t.includes("."),KVo=t=>t!=="."&&t!==".."&&t.includes("."),UVo=/^\.\*+$/,YVo=t=>t!=="."&&t!==".."&&t.startsWith("."),zVo=/^\*+$/,VVo=t=>t.length!==0&&!t.startsWith("."),JVo=t=>t.length!==0&&t!=="."&&t!=="..",qVo=/^\?+([^+@!?*[(]*)?$/,WVo=([t,e=""])=>{const n=Ykt([t]);return e?(e=e.toLowerCase(),o=>n(o)&&o.toLowerCase().endsWith(e)):n},jVo=([t,e=""])=>{const n=zkt([t]);return e?(e=e.toLowerCase(),o=>n(o)&&o.toLowerCase().endsWith(e)):n},XVo=([t,e=""])=>{const n=zkt([t]);return e?o=>n(o)&&o.endsWith(e):n},$Vo=([t,e=""])=>{const n=Ykt([t]);return e?o=>n(o)&&o.endsWith(e):n},Ykt=([t])=>{const e=t.length;return n=>n.length===e&&!n.startsWith(".")},zkt=([t])=>{const e=t.length;return n=>n.length===e&&n!=="."&&n!==".."},Vkt=typeof TT=="object"&&TT?typeof TT.env=="object"&&TT.env&&TT.env.__MINIMATCH_TESTING_PLATFORM__||TT.platform:"posix",Jkt={win32:{sep:"\\"},posix:{sep:"/"}},ZVo=Vkt==="win32"?Jkt.win32.sep:Jkt.posix.sep;Of.sep=ZVo;const DC=Symbol("globstar **");Of.GLOBSTAR=DC;const eJo="[^/]"+"*?",tJo="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",nJo="(?:(?!(?:\\/|^)\\.).)*?",oJo=(t,e={})=>n=>Of(n,t,e);Of.filter=oJo;const mx=(t,e={})=>Object.assign({},t,e),iJo=t=>{if(!t||typeof t!="object"||!Object.keys(t).length)return Of;const e=Of;return Object.assign((o,i,r={})=>e(o,i,mx(t,r)),{Minimatch:class extends e.Minimatch{constructor(i,r={}){super(i,mx(t,r))}static defaults(i){return e.defaults(mx(t,i)).Minimatch}},AST:class extends e.AST{constructor(i,r,A={}){super(i,r,mx(t,A))}static fromGlob(i,r={}){return e.AST.fromGlob(i,mx(t,r))}},unescape:(o,i={})=>e.unescape(o,mx(t,i)),escape:(o,i={})=>e.escape(o,mx(t,i)),filter:(o,i={})=>e.filter(o,mx(t,i)),defaults:o=>e.defaults(mx(t,o)),makeRe:(o,i={})=>e.makeRe(o,mx(t,i)),braceExpand:(o,i={})=>e.braceExpand(o,mx(t,i)),match:(o,i,r={})=>e.match(o,i,mx(t,r)),sep:e.sep,GLOBSTAR:DC})};Of.defaults=iJo;const qkt=(t,e={})=>(nre(t),e.nobrace||!/\{(?:(?!\{).)*\}/.test(t)?[t]:hVo(t,{max:e.braceExpandMax}));Of.braceExpand=qkt;const rJo=(t,e={})=>new fU(t,e).makeRe();Of.makeRe=rJo;const AJo=(t,e,n={})=>{const o=new fU(e,n);return t=t.filter(i=>o.match(i)),o.options.nonull&&!t.length&&t.push(e),t};Of.match=AJo;const Wkt=/[?*]|[+@!]\(.*?\)|\[|\]/,sJo=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");class fU{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;maxGlobstarRecursion;regexp;constructor(e,n={}){nre(e),n=n||{},this.options=n,this.maxGlobstarRecursion=n.maxGlobstarRecursion??200,this.pattern=e,this.platform=n.platform||Vkt,this.isWindows=this.platform==="win32";const o="allowWindowsEscape";this.windowsPathsNoEscape=!!n.windowsPathsNoEscape||n[o]===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!n.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!n.nonegate,this.comment=!1,this.empty=!1,this.partial=!!n.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=n.windowsNoMagicRoot!==void 0?n.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(const e of this.set)for(const n of e)if(typeof n!="string")return!0;return!1}debug(...e){}make(){const e=this.pattern,n=this.options;if(!n.nocomment&&e.charAt(0)==="#"){this.comment=!0;return}if(!e){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],n.debug&&(this.debug=(...r)=>console.error(...r)),this.debug(this.pattern,this.globSet);const o=this.globSet.map(r=>this.slashSplit(r));this.globParts=this.preprocess(o),this.debug(this.pattern,this.globParts);let i=this.globParts.map((r,A,s)=>{if(this.isWindows&&this.windowsNoMagicRoot){const a=r[0]===""&&r[1]===""&&(r[2]==="?"||!Wkt.test(r[2]))&&!Wkt.test(r[3]),c=/^[a-z]:/i.test(r[0]);if(a)return[...r.slice(0,4),...r.slice(4).map(l=>this.parse(l))];if(c)return[r[0],...r.slice(1).map(l=>this.parse(l))]}return r.map(a=>this.parse(a))});if(this.debug(this.pattern,i),this.set=i.filter(r=>r.indexOf(!1)===-1),this.isWindows)for(let r=0;r<this.set.length;r++){const A=this.set[r];A[0]===""&&A[1]===""&&this.globParts[r][2]==="?"&&typeof A[3]=="string"&&/^[a-z]:$/i.test(A[3])&&(A[2]="?")}this.debug(this.pattern,this.set)}preprocess(e){if(this.options.noglobstar)for(const o of e)for(let i=0;i<o.length;i++)o[i]==="**"&&(o[i]="*");const{optimizationLevel:n=1}=this.options;return n>=2?(e=this.firstPhasePreProcess(e),e=this.secondPhasePreProcess(e)):n>=1?e=this.levelOneOptimize(e):e=this.adjascentGlobstarOptimize(e),e}adjascentGlobstarOptimize(e){return e.map(n=>{let o=-1;for(;(o=n.indexOf("**",o+1))!==-1;){let i=o;for(;n[i+1]==="**";)i++;i!==o&&n.splice(o,i-o)}return n})}levelOneOptimize(e){return e.map(n=>(n=n.reduce((o,i)=>{const r=o[o.length-1];return i==="**"&&r==="**"?o:i===".."&&r&&r!==".."&&r!=="."&&r!=="**"?(o.pop(),o):(o.push(i),o)},[]),n.length===0?[""]:n))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let n=!1;do{if(n=!1,!this.preserveMultipleSlashes){for(let i=1;i<e.length-1;i++){const r=e[i];i===1&&r===""&&e[0]===""||(r==="."||r==="")&&(n=!0,e.splice(i,1),i--)}e[0]==="."&&e.length===2&&(e[1]==="."||e[1]==="")&&(n=!0,e.pop())}let o=0;for(;(o=e.indexOf("..",o+1))!==-1;){const i=e[o-1];i&&i!=="."&&i!==".."&&i!=="**"&&!(this.isWindows&&/^[a-z]:$/i.test(i))&&(n=!0,e.splice(o-1,2),o-=2)}}while(n);return e.length===0?[""]:e}firstPhasePreProcess(e){let n=!1;do{n=!1;for(let o of e){let i=-1;for(;(i=o.indexOf("**",i+1))!==-1;){let A=i;for(;o[A+1]==="**";)A++;A>i&&o.splice(i+1,A-i);let s=o[i+1];const a=o[i+2],c=o[i+3];if(s!==".."||!a||a==="."||a===".."||!c||c==="."||c==="..")continue;n=!0,o.splice(i,1);const l=o.slice(0);l[i]="**",e.push(l),i--}if(!this.preserveMultipleSlashes){for(let A=1;A<o.length-1;A++){const s=o[A];A===1&&s===""&&o[0]===""||(s==="."||s==="")&&(n=!0,o.splice(A,1),A--)}o[0]==="."&&o.length===2&&(o[1]==="."||o[1]==="")&&(n=!0,o.pop())}let r=0;for(;(r=o.indexOf("..",r+1))!==-1;){const A=o[r-1];if(A&&A!=="."&&A!==".."&&A!=="**"){n=!0;const a=r===1&&o[r+1]==="**"?["."]:[];o.splice(r-1,2,...a),o.length===0&&o.push(""),r-=2}}}}while(n);return e}secondPhasePreProcess(e){for(let n=0;n<e.length-1;n++)for(let o=n+1;o<e.length;o++){const i=this.partsMatch(e[n],e[o],!this.preserveMultipleSlashes);if(i){e[n]=[],e[o]=i;break}}return e.filter(n=>n.length)}partsMatch(e,n,o=!1){let i=0,r=0,A=[],s="";for(;i<e.length&&r<n.length;)if(e[i]===n[r])A.push(s==="b"?n[r]:e[i]),i++,r++;else if(o&&e[i]==="**"&&n[r]===e[i+1])A.push(e[i]),i++;else if(o&&n[r]==="**"&&e[i]===n[r+1])A.push(n[r]),r++;else if(e[i]==="*"&&n[r]&&(this.options.dot||!n[r].startsWith("."))&&n[r]!=="**"){if(s==="b")return!1;s="a",A.push(e[i]),i++,r++}else if(n[r]==="*"&&e[i]&&(this.options.dot||!e[i].startsWith("."))&&e[i]!=="**"){if(s==="a")return!1;s="b",A.push(n[r]),i++,r++}else return!1;return e.length===n.length&&A}parseNegate(){if(this.nonegate)return;const e=this.pattern;let n=!1,o=0;for(let i=0;i<e.length&&e.charAt(i)==="!";i++)n=!n,o++;o&&(this.pattern=e.slice(o)),this.negate=n}matchOne(e,n,o=!1){let i=0,r=0;if(this.isWindows){const s=typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0]),a=!s&&e[0]===""&&e[1]===""&&e[2]==="?"&&/^[a-z]:$/i.test(e[3]),c=typeof n[0]=="string"&&/^[a-z]:$/i.test(n[0]),l=!c&&n[0]===""&&n[1]===""&&n[2]==="?"&&typeof n[3]=="string"&&/^[a-z]:$/i.test(n[3]),g=a?3:s?0:void 0,u=l?3:c?0:void 0;if(typeof g=="number"&&typeof u=="number"){const[h,d]=[e[g],n[u]];h.toLowerCase()===d.toLowerCase()&&(n[u]=h,r=u,i=g)}}const{optimizationLevel:A=1}=this.options;return A>=2&&(e=this.levelTwoFileOptimize(e)),n.includes(DC)?this.#i(e,n,o,i,r):this.#o(e,n,o,i,r)}#i(e,n,o,i,r){const A=n.indexOf(DC,r),s=n.lastIndexOf(DC),[a,c,l]=o?[n.slice(r,A),n.slice(A+1),[]]:[n.slice(r,A),n.slice(A+1,s),n.slice(s+1)];if(a.length){const C=e.slice(i,i+a.length);if(!this.#o(C,a,o,0,0))return!1;i+=a.length,r+=a.length}let g=0;if(l.length){if(l.length+i>e.length)return!1;let C=e.length-l.length;if(this.#o(e,l,o,C,0))g=l.length;else{if(e[e.length-1]!==""||i+l.length===e.length||(C--,!this.#o(e,l,o,C,0)))return!1;g=l.length+1}}if(!c.length){let C=!!g;for(let I=i;I<e.length-g;I++){const f=String(e[I]);if(C=!0,f==="."||f===".."||!this.options.dot&&f.startsWith("."))return!1}return o||C}const u=[[[],0]];let h=u[0],d=0;const _=[0];for(const C of c)C===DC?(_.push(d),h=[[],0],u.push(h)):(h[0].push(C),d++);let p=u.length-1;const m=e.length-g;for(const C of u)C[1]=m-(_[p--]+C[0].length);return!!this.#n(e,u,i,0,o,0,!!g)}#n(e,n,o,i,r,A,s){const a=n[i];if(!a){for(let g=o;g<e.length;g++){s=!0;const u=e[g];if(u==="."||u===".."||!this.options.dot&&u.startsWith("."))return!1}return s}const[c,l]=a;for(;o<=l;){if(this.#o(e.slice(0,o+c.length),c,r,o,0)&&A<this.maxGlobstarRecursion){const h=this.#n(e,n,o+c.length,i+1,r,A+1,s);if(h!==!1)return h}const u=e[o];if(u==="."||u===".."||!this.options.dot&&u.startsWith("."))return!1;o++}return r||null}#o(e,n,o,i,r){let A,s,a,c;for(A=i,s=r,c=e.length,a=n.length;A<c&&s<a;A++,s++){this.debug("matchOne loop");let l=n[s],g=e[A];if(this.debug(n,l,g),l===!1||l===DC)return!1;let u;if(typeof l=="string"?(u=g===l,this.debug("string match",l,g,u)):(u=l.test(g),this.debug("pattern match",l,g,u)),!u)return!1}if(A===c&&s===a)return!0;if(A===c)return o;if(s===a)return A===c-1&&e[A]==="";throw new Error("wtf?")}braceExpand(){return qkt(this.pattern,this.options)}parse(e){nre(e);const n=this.options;if(e==="**")return DC;if(e==="")return"";let o,i=null;(o=e.match(zVo))?i=n.dot?JVo:VVo:(o=e.match(TVo))?i=(n.nocase?n.dot?HVo:LVo:n.dot?FVo:kVo)(o[1]):(o=e.match(qVo))?i=(n.nocase?n.dot?jVo:WVo:n.dot?XVo:$Vo)(o):(o=e.match(GVo))?i=n.dot?KVo:OVo:(o=e.match(UVo))&&(i=YVo);const r=G6e.fromGlob(e,this.options).toMMPattern();return i&&typeof r=="object"&&Reflect.defineProperty(r,"test",{value:i}),r}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;const e=this.set;if(!e.length)return this.regexp=!1,this.regexp;const n=this.options,o=n.noglobstar?eJo:n.dot?tJo:nJo,i=new Set(n.nocase?["i"]:[]);let r=e.map(a=>{const c=a.map(g=>{if(g instanceof RegExp)for(const u of g.flags.split(""))i.add(u);return typeof g=="string"?sJo(g):g===DC?DC:g._src});c.forEach((g,u)=>{const h=c[u+1],d=c[u-1];g!==DC||d===DC||(d===void 0?h!==void 0&&h!==DC?c[u+1]="(?:\\/|"+o+"\\/)?"+h:c[u]=o:h===void 0?c[u-1]=d+"(?:\\/|\\/"+o+")?":h!==DC&&(c[u-1]=d+"(?:\\/|\\/"+o+"\\/)"+h,c[u+1]=DC))});const l=c.filter(g=>g!==DC);if(this.partial&&l.length>=1){const g=[];for(let u=1;u<=l.length;u++)g.push(l.slice(0,u).join("/"));return"(?:"+g.join("|")+")"}return l.join("/")}).join("|");const[A,s]=e.length>1?["(?:",")"]:["",""];r="^"+A+r+s+"$",this.partial&&(r="^(?:\\/|"+A+r.slice(1,-1)+s+")$"),this.negate&&(r="^(?!"+r+").+$");try{this.regexp=new RegExp(r,[...i].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split("/"):this.isWindows&&/^\/\/[^/]+/.test(e)?["",...e.split(/\/+/)]:e.split(/\/+/)}match(e,n=this.partial){if(this.debug("match",e,this.pattern),this.comment)return!1;if(this.empty)return e==="";if(e==="/"&&n)return!0;const o=this.options;this.isWindows&&(e=e.split("\\").join("/"));const i=this.slashSplit(e);this.debug(this.pattern,"split",i);const r=this.set;this.debug(this.pattern,"set",r);let A=i[i.length-1];if(!A)for(let s=i.length-2;!A&&s>=0;s--)A=i[s];for(const s of r){let a=i;if(o.matchBase&&s.length===1&&(a=[A]),this.matchOne(a,s,n))return o.flipNegate?!0:!this.negate}return o.flipNegate?!1:this.negate}static defaults(e){return Of.defaults(e).Minimatch}}Of.AST=G6e,Of.Minimatch=fU,Of.escape=RVo,Of.unescape=CU;const aJo=t=>(t.endsWith(".tsx")||t.endsWith(".ts")||t.endsWith(".jsx")||t.endsWith(".js")||ere(t))&&!t.endsWith(".d.ts"),cJo=t=>{if(!t)return null;try{const e=JSON.parse(t);return BXt.parse(e)}catch(e){return console.warn("Failed to parse tscircuit.config.json",e),null}},lJo=(t,e)=>{const o=cJo(e)?.includeBoardFiles?.filter(Boolean);if(o&&o.length>0){const i=o.map(r=>new fU(r,{dot:!0}));return t.filter(r=>i.some(A=>A.match(r)))}return t.filter(aJo)},O6e=Ga("run-frame:RunFrameWithApi"),gJo=()=>{const e=!!Yu(o=>o.error),n=e?"Dev server disconnected":"Dev server connected";return J.jsx(h6e,{children:J.jsxs(_6e,{children:[J.jsx(m6e,{asChild:!0,children:J.jsx("button",{type:"button","aria-label":n,className:"rf-inline-flex rf-items-center rf-justify-center rf-p-2 rf-rounded-full rf-outline-none",children:J.jsx("span",{className:qi("rf-inline-flex rf-size-2 rf-rounded-full rf-flex-shrink-0",e?"rf-bg-red-600":"rf-bg-green-600 rf-opacity-50"),"aria-hidden":"true"})})}),J.jsx(qie,{side:"right",children:n})]})})},jkt=t=>t.find(e=>e.includes("entrypoint."))??t.find(e=>e.includes("index."))??t.find(e=>e.includes("main."))??t.find(e=>e.endsWith(".tsx")),uJo=t=>t.find(e=>e.includes("manual-edits."))??t.find(e=>e.includes("manual-edit."))??t.find(e=>e.endsWith(".json")),Xkt=t=>{const{apiBaseUrl:e,leftHeaderContent:n}=t;j.useEffect(()=>{t.debug&&Ga.enable("run-frame*")},[t.debug]);const o=Yu(H=>H.startPolling),i=Yu(H=>H.stopPolling),r=Yu(H=>H.setCurrentMainComponentPath),A=Yu(H=>H.pushEvent),s=oOn(),a=Yu(H=>H.fsMap),c=Yu(H=>H.recentlySavedFiles),l=j.useMemo(()=>Array.from(a.keys()),[a]),g=j.useMemo(()=>{const H=a.get("tscircuit.config.json");return typeof H=="string"?H:void 0},[a]),u=j.useMemo(()=>lJo(l,g),[l,g]),h=Yu(H=>H.circuitJson),[d,_]=j.useState(()=>typeof window>"u"?t.initialMainComponentPath??"":new URLSearchParams(window.location.hash.slice(1)).get("file")??t.initialMainComponentPath??""),[p,m]=J7("runframe:favorites",[]),C=!s,I=j.useCallback(H=>{m(G=>G.includes(H)?G.filter(K=>K!==H):[...G,H])},[m]),f=t.fileFilter??KYo,y=j.useMemo(()=>u.filter(f),[u,f]);j.useEffect(()=>{if(d&&(y.includes(d)||u.includes(d)))return;if(d){const W=d.includes("/")?d.substring(0,d.lastIndexOf("/")):"",X=y.find(ie=>(ie.includes("/")?ie.substring(0,ie.lastIndexOf("/")):"")===W);if(X){_(X);return}}const H=window?.TSCIRCUIT_DEFAULT_MAIN_COMPONENT_PATH,G=[t.initialMainComponentPath,H].filter(W=>!!W);for(const W of G)if(y.includes(W)){_(W);return}const V=(y.length>0?y:u)[0];V&&_(V)},[y,u,t.initialMainComponentPath,d]);const x=j.useCallback(H=>{if(typeof window>"u")return;const G=new URLSearchParams(window.location.hash.slice(1));if(G.get("file")===H)return;G.set("file",H);const K=G.toString(),V=`${window.location.pathname}${window.location.search}${K.length>0?`#${K}`:""}`;window.history.replaceState(null,"",V)},[]);j.useEffect(()=>{d&&(x(d),t.onMainComponentPathChange?.(d),r(d))},[d,t.onMainComponentPathChange,x,r]),$zo();const{editEventsForRender:B,pushEditEvent:S,markRenderStarted:D,markRenderComplete:w}=nOn();j.useEffect(()=>{e&&(window.TSCIRCUIT_FILESERVER_API_BASE_URL=e)},[e]),j.useEffect(()=>(o(),()=>i()),[o,i]);const F=j.useMemo(()=>String(d).length>0?{mainComponentPath:d}:{},[d]),R=j.useCallback(async H=>{try{await A({event_type:"RUN_COMPLETED",initiator:"runframe",...H})}catch(G){O6e("Failed to push RUN_COMPLETED event",G)}},[A]);return J.jsx(skt,{fsMap:a,showFileMenu:t.showFileMenu,isCli:t.isCli,schematicSvgOptions:t.schematicSvgOptions,isLoadingFiles:C,evalVersion:t.evalVersion,forceLatestEvalVersion:t.forceLatestEvalVersion,evalWebWorkerBlobUrl:t.evalWebWorkerBlobUrl??t.workerBlobUrl,enableFetchProxy:t.enableFetchProxy,leftHeaderContent:J.jsxs("div",{className:"rf-flex rf-items-center rf-justify-between rf-w-full",children:[J.jsxs("div",{className:"rf-flex rf-items-center rf-gap-2",children:[t.leftHeaderContent,J.jsx(gJo,{})]}),t.showFilesSwitch&&J.jsx("div",{className:"rf-absolute rf-left-1/2 rf-transform rf--translate-x-1/2",children:J.jsx(wkt,{currentFile:d,files:y,onFileChange:H=>{typeof a.get(H)=="string"&&_(H)},pinnedFiles:p,onToggleFavorite:I,fileFilter:f,recentlySavedFiles:c})})]}),defaultToFullScreen:t.defaultToFullScreen,showToggleFullScreen:t.showToggleFullScreen,onInitialRender:()=>{O6e("onInitialRender / markRenderStarted"),D()},onRenderFinished:()=>{O6e("onRenderFinished / markRenderComplete"),w()},onRunCompleted:R,editEvents:B,onEditEvent:H=>{S(H),fetch(`${Qf}/events/create`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event_type:"USER_CREATED_MANUAL_EDIT",...H})});const G=uJo(Array.from(a.keys()))??"manual-edits.json",K=a.get(G),V=JSON.parse(K??"{}");Kct({circuitJson:h,editEvents:[H],manualEditsFile:V}),fetch(`${Qf}/files/upsert`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({file_path:G,text_content:JSON.stringify(V),initiator:"runframe"})})},onLoginRequired:t.onLoginRequired,easyEdaProxyConfig:{proxyEndpointUrl:`${Qf}/proxy`},...F})},dJo=()=>new Promise(t=>{document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>t()):t()}),hJo=()=>{const t=window.location.hash.slice(1),n=new URLSearchParams(t).get("tab")?.toLowerCase()?.trim();return n&&["pcb","schematic","cad"].includes(n)?n:"pcb"},_Jo=()=>{const t=document.getElementById("root");if(t)return t;const e=document.createElement("div");return e.id="root",e.style.height="100vh",document.body.appendChild(e),e},mJo=async()=>{const t=Array.from(document.querySelectorAll("script[type='tscircuit-tsx']")),e=new Map;return await Promise.all(t.map(async(n,o)=>{const i=n.dataset.path||n.getAttribute("data-file-path")||`script${o?o+1:""}.tsx`;if(n.src){const A=await(await fetch(n.src)).text();e.set(i,A)}else e.set(i,n.textContent||"")})),{fsMap:e}},$kt="<--INJECT_TSCIRCUIT_EVAL_WEB_WORKER_BLOB_URL-->",K6e={evalWebWorkerBlobUrl:$kt.includes("<--")?void 0:$kt,enableFetchProxy:"<--INJECT_ENABLE_FETCH_PROXY-->".includes("<--")?void 0:!0};(async()=>{await dJo();const t=VHt.createRoot(_Jo()),e=window.TSCIRCUIT_RUNFRAME_STATIC_FILE_LIST,n=window.TSCIRCUIT_DEFAULT_MAIN_COMPONENT_PATH,o=window.TSCIRCUIT_PACKAGE_NAME;if(Array.isArray(e)){const i=hJo();t.render(J.jsx(Xzo,{files:e,initialCircuitPath:n,tabSelected:i,projectName:o}))}else if(window.TSCIRCUIT_USE_RUNFRAME_FOR_CLI)t.render(J.jsx($Yo,{...K6e}));else{const{fsMap:i}=await mJo();i.size>0?t.render(J.jsx(skt,{...K6e,fsMap:i})):t.render(J.jsx(Xkt,{...K6e}))}})();const pJo=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}))}));
5870
+ ${x}`)}},[e,u]),j.useEffect(()=>{e&&!u&&TTt().then(x=>{_(x.size)}).catch(x=>{console.error("Failed to fetch file count",x),_(0)})},[e,u]);const C=j.useCallback(()=>{A(null),h(null),a(null),l([]),g.current&&(g.current.value=""),n(!0)},[]),I=j.useCallback(()=>{n(!1)},[]),f=j.useCallback(async()=>{i(!0),A(null),a(null),l([]);const x=lM(),B=g.current?.value||"";try{const S=await TTt();if(S.size===0){zA.error("No project files available to include in the bug report"),i(!1);return}const D=new Date(Date.now()+1440*60*1e3).toISOString(),F=(await x.post("bug_reports/create",{json:{text:B.trim()||void 0,is_auto_deleted:!0,delete_at:D}}).json()).bug_report.bug_report_id,R=Array.from(S.entries()),H=[];for(let K=0;K<R.length;K++){const[V,W]=R[K];a({current:K+1,total:R.length,currentFile:V});try{const X={bug_report_id:F,file_path:V};W.text_content&&(X.content_text=W.text_content),W.binary_content_b64&&(X.content_base64=W.binary_content_b64),await x.post("bug_reports/upload_file",{json:X})}catch(X){const ie=X instanceof cM?`HTTP ${X.response.status}`:X instanceof Error?X.message:"Upload failed";H.push({filePath:V,message:ie}),l([...H])}}a(null);const G=zUo(F);h({bugReportUrl:G})}catch(S){if(console.error("Failed to submit bug report",S),S instanceof cM)if(S.response.status===401)if(m){const D="Your session has expired. Please sign in again to continue.";A(D),zA.error(D),p&&(I(),p())}else{const D="You must be logged in to report a bug. Please sign in via cli and try again.";A(D),zA.error(D),setTimeout(()=>{p&&(I(),p())},1e3)}else{const D=`Failed to submit bug report (${S.response.status})`;A(D),zA.error(D)}else if(S instanceof Error)A(S.message),zA.error(S.message);else{const D="Failed to submit bug report";A(D),zA.error(D)}}finally{i(!1)}},[m,p]);return{BugReportDialog:j.useMemo(()=>{const x=s?Math.round(s.current/s.total*100):0;return J.jsx(bRt,{open:e,onOpenChange:B=>{B?(A(null),h(null),a(null),l([]),n(!0)):o||I()},children:J.jsxs(C3e,{children:[J.jsxs(f3e,{children:[J.jsx(E3e,{children:u?"Bug Report Created":"Report Bug"}),J.jsx(x3e,{asChild:!0,children:u?J.jsxs("div",{className:"rf-text-left rf-space-y-3 rf-text-sm",children:[J.jsx("p",{children:"Bug report created successfully."}),c.length>0&&J.jsxs("div",{className:"rf-bg-red-50 rf-border rf-border-red-200 rf-rounded rf-p-2 rf-max-h-28 rf-overflow-y-auto rf-overflow-x-hidden",children:[J.jsxs("p",{className:"rf-text-red-700 rf-font-medium rf-text-xs rf-mb-1",children:[c.length," file(s) failed:"]}),c.map((B,S)=>J.jsxs("div",{className:"rf-text-red-600 rf-text-xs rf-mb-0.5",title:`${B.filePath}: ${B.message}`,children:[J.jsx("span",{className:"rf-font-medium rf-break-all",children:B.filePath.split("/").pop()}),J.jsx("span",{className:"rf-text-red-500 rf-block rf-truncate",children:B.message})]},S))]}),J.jsx("div",{children:J.jsx("a",{className:"rf-text-blue-600 hover:rf-underline",href:u.bugReportUrl,target:"_blank",rel:"noreferrer",children:"View bug report"})}),J.jsxs("p",{children:["Please share this link privately with tscircuit staff so we can help debug. Join the",J.jsx("a",{className:"rf-ml-1 rf-text-blue-600 hover:rf-underline",href:"https://tscircuit.com/join",target:"_blank",rel:"noreferrer",children:"tscircuit Discord"}),"."]})]}):J.jsx("div",{className:"rf-text-left rf-space-y-3 rf-text-sm",children:s?J.jsxs("div",{className:"rf-space-y-2 rf-overflow-hidden",children:[J.jsxs("div",{className:"rf-flex rf-justify-between rf-text-xs",children:[J.jsx("span",{children:"Uploading files..."}),J.jsxs("span",{children:[s.current,"/",s.total]})]}),J.jsx("div",{className:"rf-w-full rf-h-2 rf-bg-gray-200 rf-rounded-full rf-overflow-hidden",children:J.jsx("div",{className:"rf-h-full rf-bg-blue-500 rf-transition-all rf-duration-150",style:{width:`${x}%`}})}),J.jsx("p",{className:"rf-text-xs rf-text-gray-500 rf-break-all rf-truncate rf-w-full rf-max-w-full",children:`${s.currentFile.slice(0,60)}${s.currentFile.length>60?"...":""}`}),c.length>0&&J.jsx("div",{className:"rf-bg-red-50 rf-border rf-border-red-200 rf-rounded rf-p-2 rf-max-h-20 rf-overflow-y-auto rf-overflow-x-hidden",children:c.map((B,S)=>J.jsxs("div",{className:"rf-text-red-600 rf-text-xs rf-mb-0.5",title:`${B.filePath}: ${B.message}`,children:[J.jsx("span",{className:"rf-font-medium rf-break-all",children:B.filePath.split("/").pop()}),J.jsx("span",{className:"rf-text-red-500 rf-block rf-truncate",children:B.message})]},S))})]}):J.jsxs(J.Fragment,{children:[J.jsxs("p",{children:["Reporting a bug will upload your entire project",d>0?` (${d} file${d===1?"":"s"})`:""," ","to tscircuit support."]}),J.jsxs("div",{className:"rf-space-y-2",children:[J.jsx("label",{htmlFor:"bug-description",className:"rf-block rf-font-medium",children:"Description (optional)"}),J.jsx("textarea",{ref:g,id:"bug-description",className:"rf-w-full rf-min-h-[100px] rf-px-3 rf-py-2 rf-text-sm rf-border rf-border-gray-300 rf-rounded-md focus:rf-outline-none focus:rf-ring-2 focus:rf-ring-blue-500",placeholder:"Describe the issue you're experiencing...",disabled:o})]}),J.jsxs("p",{children:["Share the generated bug report link privately with tscircuit staff so we can help debug your issue. You can also reach out on our",J.jsx("a",{className:"rf-ml-1 rf-text-blue-600 hover:rf-underline",href:"https://tscircuit.com/join",target:"_blank",rel:"noreferrer",children:"Discord community"}),"."]}),!m&&J.jsx("p",{className:"rf-text-red-600",children:"You appear to be logged out. Please log in before reporting a bug or the upload will fail."}),r&&J.jsx("p",{className:"rf-text-red-600",children:r})]})})})]}),J.jsx(y3e,{children:u?J.jsx("button",{type:"button",className:oT(),onClick:()=>{I()},children:"Close"}):J.jsxs(J.Fragment,{children:[J.jsx(B3e,{disabled:o,onClick:()=>{o||I()},children:"Cancel"}),!m&&p?J.jsx("button",{type:"button",className:oT(),onClick:B=>{B.preventDefault(),I(),p()},children:"Sign In"}):J.jsx("button",{type:"button",className:rB(oT(),o&&"rf-opacity-70 rf-cursor-not-allowed"),disabled:o,onClick:B=>{B.preventDefault(),f()},children:o?"Reporting...":"Upload & Report"})]})})]})},"bug-report-dialog")},[e,o,I,r,u,d,m,f,p,s,c]),openBugReportDialog:C}};function JUo({open:t,onOpenChange:e,onExport:n}){const[o,i]=j.useState(!1),r=()=>{n({includeSilkscreen:o}),e(!1)},A=()=>{e(!1)};return J.jsx(DT,{open:t,onOpenChange:e,children:J.jsxs(j3,{children:[J.jsxs(X3,{children:[J.jsx($3,{children:"LightBurn Export Options"}),J.jsx(MT,{children:"Configure export settings for PCB laser ablation with LightBurn"})]}),J.jsx("div",{className:"rf-flex rf-flex-col rf-gap-4 rf-py-4",children:J.jsxs("div",{className:"rf-flex rf-items-center rf-space-x-2",children:[J.jsx(ZK,{id:"includeSilkscreen",checked:o,onCheckedChange:s=>i(s===!0)}),J.jsx("label",{htmlFor:"includeSilkscreen",className:"rf-text-xs rf-font-medium rf-leading-none peer-disabled:rf-cursor-not-allowed peer-disabled:rf-opacity-70",children:"Include silkscreen layer"})]})}),J.jsxs(eU,{children:[J.jsx(ta,{variant:"outline",onClick:A,children:"Cancel"}),J.jsx(ta,{onClick:r,children:"Export"})]})]})})}const qUo=/#(\d+)/,WUo=t=>{const e=t.match(qUo);if(!e)return null;const n=Number.parseInt(e[1],10);return Number.isFinite(n)?n:null},jUo=t=>{if(typeof t=="number")return Number.isFinite(t)?t:null;if(typeof t=="string"){const e=new Date(t).getTime();return Number.isFinite(e)?e:null}return null},XUo=t=>{if(!t)return null;let e=null,n=-1,o=-1;for(const[i,r]of Object.entries(t)){const A=WUo(i),s=jUo(r.createdAt);if(A!==null){A>n&&(n=A,e={key:i,value:r});continue}if(n===-1){if(s!==null&&s>o){o=s,e={key:i,value:r};continue}e||(e={key:i,value:r})}}return e},cU=t=>{const e=yie(be=>be.lastRunEvalVersion),n=Yu(be=>be.currentMainComponentPath),[o,i]=j.useState(null),[r,A]=j.useState(!1),[s,a]=j.useState(!0),[c,l]=j.useState(!1),[g,u]=j.useState(null),[h,d]=j.useState(null),[_,p]=j.useState(!1),[m,C]=j.useState(null),[I,f]=j.useState(null),[y,x]=j.useState(!1),[B,S]=j.useState(!1),[D,w]=j.useState(!1),[F,R]=j.useState(null),H=UUo(),G=Yu(be=>be.pushEvent),K=Yu(be=>be.recentEvents),V=j.useMemo(()=>Date.now(),[]);XHo(be=>{if(!(new Date(be.created_at).valueOf()<V+500)){if(be.event_type==="FILE_UPDATED"){A(!0);return}if(be.event_type==="SNIPPET_SAVED"){A(!1),a(!1),C("Snippet saved successfully."),x(!1);return}be.event_type==="REQUEST_EXPORT"&&(S(!0),C("Export processing..."),x(!1)),be.event_type==="EXPORT_CREATED"&&(C(`Export created: ${be.exportFilePath}`),x(!1),S(!1))}}),j.useEffect(()=>{if(!c||g===null)return;const be=K.filter(pe=>new Date(pe.created_at).valueOf()>g),ue=be.find(pe=>pe.event_type==="FAILED_TO_SAVE_SNIPPET"),Be=be.find(pe=>pe.event_type==="SNIPPET_SAVED");ue&&(l(!1),u(null),f(ue.message??"Failed to save snippet. See console for error."),console.error(ue.message),x(!0),ue.error_code==="SNIPPET_UNSET"&&ue.available_snippet_names&&(d(ue.available_snippet_names),p(!0))),Be&&(l(!1),u(null),C("Snippet saved successfully."),x(!1))},[K,c]);const W=async()=>{l(!0),u(Date.now()),C(null),x(!1),await G({event_type:"REQUEST_TO_SAVE_SNIPPET",snippet_name:o})},ie=Yu(be=>be.circuitJson)??t.circuitJson,[se,ee]=j.useState(!1),[oe,ae]=j.useState(!1),{BugReportDialog:re,openBugReportDialog:le}=VUo({onLoginRequired:t.onLoginRequired}),fe=async be=>{F&&(await eTt({circuitJson:F.circuitJson,projectName:F.projectName,options:be}),R(null))},ye=j.useMemo(()=>XUo(t.autoroutingLog),[t.autoroutingLog]);return J.jsxs(J.Fragment,{children:[J.jsxs("div",{className:"rf-flex rf-items-center rf-gap-1 rf-flex-shrink-0",children:[J.jsxs(woe,{children:[J.jsx(Poe,{asChild:!0,children:J.jsx("div",{className:"rf-whitespace-nowrap rf-text-xs font-medium rf-p-2 rf-mx-1 rf-cursor-pointer rf-relative",children:"File"})}),J.jsxs(TK,{className:"rf-z-[101]",children:[!t.isWebEmbedded&&J.jsxs(J.Fragment,{children:[J.jsx(Sh,{className:"rf-text-xs",onSelect:W,disabled:c,children:c?"Saving...":"Push"}),parseInt(window.location.port)>5e3&&J.jsx(Sh,{className:"rf-text-xs",onSelect:()=>{H.open()},children:"Order"}),J.jsx(Sh,{className:"rf-text-xs",onSelect:()=>ee(!0),disabled:c,children:"Import"}),J.jsx(Sh,{className:"rf-text-xs",onSelect:()=>{if(!kZ()){zA.error("Requires tscircuit token");return}ae(!0)},children:"AI Review"})]}),!t.isWebEmbedded&&t.onLoginRequired&&J.jsx(Sh,{className:"rf-text-xs",onSelect:()=>{t.onLoginRequired?.()},children:"Sign In"}),!t.isWebEmbedded&&J.jsxs(RK,{children:[J.jsx(mT,{className:"rf-text-xs",children:"Report Bug"}),J.jsx(NK,{children:J.jsxs(pT,{children:[J.jsx(Sh,{className:"rf-text-xs",onSelect:()=>{le()},children:"Report Entire Circuit"}),J.jsx(Sh,{className:"rf-text-xs",disabled:!ye||!t.onReportAutoroutingLog,onSelect:()=>{!ye||!t.onReportAutoroutingLog||t.onReportAutoroutingLog(ye.key,{simpleRouteJson:ye.value.simpleRouteJson})},children:"Report Autorouter Bug"})]})})]}),J.jsxs(RK,{children:[J.jsx(mT,{className:"rf-text-xs",disabled:B,children:B?"Exporting...":"Export"}),J.jsx(NK,{children:J.jsx(pT,{children:dKo.map((be,ue)=>J.jsx(Sh,{onSelect:()=>{if(!ie){zA.error("No Circuit JSON to export");return}let Be="Untitled";if(n){const Je=n.split("/").pop();Je&&(Be=Je.replace(/\.[^.]+$/,""))}const pe=t.projectName??o??Be,Ge=ye?.value.simpleRouteJson;if(be.name==="LightBurn"){R({circuitJson:ie,projectName:pe}),w(!0);return}hKo({exportName:be.name,circuitJson:ie,simpleRouteJson:Ge,projectName:pe?.replace(/\.(board|circuit)$/,"")})},disabled:B||be.name==="Simple Route JSON"&&!ye,children:J.jsx("span",{className:"rf-text-xs",children:be.name})},ue))})})]}),!t.isWebEmbedded&&J.jsxs(RK,{children:[J.jsx(mT,{className:"rf-text-xs",children:"Advanced"}),J.jsx(NK,{children:J.jsxs(pT,{children:[J.jsx(Sh,{className:"rf-flex rf-items-center rf-gap-2",children:J.jsxs("div",{className:"rf-flex rf-items-center rf-gap-2",children:[J.jsx(ZK,{id:"load-latest-eval",checked:t.shouldLoadLatestEval,onCheckedChange:be=>{t.onChangeShouldLoadLatestEval?.(be===!0)}}),J.jsx("label",{htmlFor:"load-latest-eval",className:"rf-text-xs rf-cursor-pointer",children:"Force Latest @tscircuit/eval"})]})}),e&&J.jsx(Sh,{className:"rf-flex rf-items-center rf-gap-2",children:J.jsx("div",{className:"rf-flex rf-items-center rf-gap-2",children:J.jsxs("span",{className:"rf-text-xs",children:["@tscircuit/eval@",e]})})}),J.jsx(Sh,{className:"rf-flex rf-items-center rf-gap-2",children:J.jsx("div",{className:"rf-flex rf-items-center rf-gap-2",children:J.jsxs("span",{className:"rf-text-xs",children:["@tscircuit/runframe@",qHo.version]})})}),J.jsx(Sh,{className:"rf-flex rf-items-center rf-gap-2",onClick:()=>{window.open("/api/admin","_blank")},children:J.jsx("div",{className:"rf-flex rf-items-center rf-gap-2",children:J.jsx("span",{className:"rf-text-xs",children:"CLI Admin Panel"})})})]})})]})]}),J.jsx(bRt,{open:y,onOpenChange:x,children:J.jsxs(C3e,{children:[J.jsxs(f3e,{children:[J.jsx(E3e,{children:"Error Saving Snippet"}),J.jsx(x3e,{children:I})]}),J.jsx(y3e,{children:J.jsx(B3e,{onClick:()=>x(!1),children:"Dismiss"})})]})}),J.jsx(jHo,{snippetNames:h??[],onSelect:async be=>{l(!0),u(Date.now()),i(be),await G({event_type:"REQUEST_TO_SAVE_SNIPPET",snippet_name:be}),p(!1)},onCancel:()=>p(!1),isOpen:_})]}),J.jsxs(woe,{children:[J.jsx(Poe,{asChild:!0,children:J.jsx("div",{className:"rf-whitespace-nowrap rf-text-xs font-medium rf-p-2 rf-mx-1 rf-cursor-pointer rf-relative",children:"View"})}),J.jsx(TK,{className:"rf-z-[104]",children:J.jsxs(RK,{children:[J.jsx(mT,{className:"rf-text-xs",children:"Schematic"}),J.jsx(NK,{children:J.jsxs(pT,{children:[J.jsx(Sh,{className:"rf-flex rf-items-center rf-gap-2",onSelect:be=>be.preventDefault(),children:J.jsxs("div",{className:"rf-flex rf-items-center rf-gap-2",children:[J.jsx(ZK,{id:"show-schematic-ports",checked:t.showSchematicPorts,onCheckedChange:be=>{t.onChangeShowSchematicPorts?.(be===!0)}}),J.jsx("label",{htmlFor:"show-schematic-ports",className:"rf-text-xs rf-cursor-pointer",children:"Show Schematic Ports"})]})}),J.jsx(Sh,{className:"rf-flex rf-items-center rf-gap-2",onSelect:be=>be.preventDefault(),children:J.jsxs("div",{className:"rf-flex rf-items-center rf-gap-2",children:[J.jsx(ZK,{id:"show-schematic-grid",checked:t.showSchematicDebugGrid,onCheckedChange:be=>{t.onChangeShowSchematicDebugGrid?.(be===!0)}}),J.jsx("label",{htmlFor:"show-schematic-grid",className:"rf-text-xs rf-cursor-pointer",children:"Show Schematic Grid"})]})})]})})]})})]})]}),re,J.jsx(JUo,{open:D,onOpenChange:w,onExport:fe}),J.jsx($Rt,{isOpen:se,onClose:()=>ee(!1)}),J.jsx(ZKo,{isOpen:oe,onClose:()=>ae(!1),packageName:o}),J.jsx(C5t,{position:"top-center",reverseOrder:!1,containerStyle:{zIndex:1e5},toastOptions:{className:"rf-break-all",style:{zIndex:1e5}}}),J.jsx(H.OrderDialog,{isOpen:H.isOpen,onClose:H.close,stage:H.stage,setStage:H.setStage})]})};var $Uo=Object.defineProperty,ZUo=(t,e)=>$Uo(t,"name",{value:e,configurable:!0}),eYo=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),tYo=j.forwardRef(ZUo(function(e,n){return J.jsx(Oa.span,{...e,ref:n,style:{...eYo,...e.style}})},"VisuallyHidden")),nYo=tYo,oYo=Object.defineProperty,_I=(t,e)=>oYo(t,"name",{value:e,configurable:!0}),[c6e,Gjo]=y2("Tooltip",[cT]),l6e=cT(),iYo="TooltipProvider",rYo=700,g6e="tooltip.open",[AYo,u6e]=c6e(iYo),sYo=_I(t=>{const{__scopeTooltip:e,delayDuration:n=rYo,skipDelayDuration:o=300,disableHoverableContent:i=!1,children:r}=t,A=j.useRef(!0),s=j.useRef(!1),a=j.useRef(0);return j.useEffect(()=>{const c=a.current;return()=>window.clearTimeout(c)},[]),J.jsx(AYo,{scope:e,isOpenDelayedRef:A,delayDuration:n,onOpen:j.useCallback(()=>{o<=0||(window.clearTimeout(a.current),A.current=!1)},[o]),onClose:j.useCallback(()=>{o<=0||(window.clearTimeout(a.current),a.current=window.setTimeout(()=>A.current=!0,o))},[o]),isPointerInTransitRef:s,onPointerInTransitChange:j.useCallback(c=>{s.current=c},[]),disableHoverableContent:i,children:r})},"TooltipProvider"),d6e="Tooltip",[aYo,Jie]=c6e(d6e),cYo=_I(t=>{const{__scopeTooltip:e,children:n,open:o,defaultOpen:i,onOpenChange:r,disableHoverableContent:A,delayDuration:s}=t,a=u6e(d6e,t.__scopeTooltip),c=l6e(e),[l,g]=j.useState(null),[u,h]=j.useState(void 0),d=rp(),_=j.useRef(0),p=A??a.disableHoverableContent,m=s??a.delayDuration,C=j.useRef(!1),[I,f]=Ub({prop:o,defaultProp:i??!1,onChange:_I(w=>{w?(a.onOpen(),document.dispatchEvent(new CustomEvent(g6e))):a.onClose(),r?.(w)},"onChange"),caller:d6e}),y=j.useMemo(()=>I?C.current?"delayed-open":"instant-open":"closed",[I]),x=j.useCallback(()=>{window.clearTimeout(_.current),_.current=0,C.current=!1,f(!0)},[f]),B=j.useCallback(()=>{window.clearTimeout(_.current),_.current=0,f(!1)},[f]),S=j.useCallback(()=>{window.clearTimeout(_.current),_.current=window.setTimeout(()=>{C.current=!0,f(!0),_.current=0},m)},[m,f]);j.useEffect(()=>()=>{_.current&&(window.clearTimeout(_.current),_.current=0)},[]);const D=u??d;return J.jsx(_oe,{...c,children:J.jsx(aYo,{scope:e,contentId:D,setContentId:h,open:I,stateAttribute:y,trigger:l,onTriggerChange:g,onTriggerEnter:j.useCallback(()=>{a.isOpenDelayedRef.current?S():x()},[a.isOpenDelayedRef,S,x]),onTriggerLeave:j.useCallback(()=>{p?B():(window.clearTimeout(_.current),_.current=0)},[B,p]),onOpen:x,onClose:B,disableHoverableContent:p,children:n})})},"Tooltip"),kTt="TooltipTrigger",lYo=j.forwardRef(_I(function(e,n){const{__scopeTooltip:o,...i}=e,r=Jie(kTt,o),A=u6e(kTt,o),s=l6e(o),a=j.useRef(null),c=dl(n,a,r.onTriggerChange),l=j.useRef(!1),g=j.useRef(!1),u=j.useCallback(()=>l.current=!1,[]);return j.useEffect(()=>()=>document.removeEventListener("pointerup",u),[u]),J.jsx(CPe,{asChild:!0,...s,children:J.jsx(Oa.button,{"aria-describedby":r.open?r.contentId:void 0,"data-state":r.stateAttribute,...i,ref:c,onPointerMove:Pr(e.onPointerMove,h=>{h.pointerType!=="touch"&&!g.current&&!A.isPointerInTransitRef.current&&(r.onTriggerEnter(),g.current=!0)}),onPointerLeave:Pr(e.onPointerLeave,()=>{r.onTriggerLeave(),g.current=!1}),onPointerDown:Pr(e.onPointerDown,()=>{r.open&&r.onClose(),l.current=!0,document.addEventListener("pointerup",u,{once:!0})}),onFocus:Pr(e.onFocus,()=>{l.current||r.onOpen()}),onBlur:Pr(e.onBlur,r.onClose),onClick:Pr(e.onClick,r.onClose)})})},"TooltipTrigger")),gYo="TooltipPortal",[Ojo,uYo]=c6e(gYo,{forceMount:void 0}),lU="TooltipContent",dYo=j.forwardRef(_I(function(e,n){const o=uYo(lU,e.__scopeTooltip),{forceMount:i=o.forceMount,side:r="top",...A}=e,s=Jie(lU,e.__scopeTooltip);return J.jsx(JE,{present:i||s.open,children:s.disableHoverableContent?J.jsx(FTt,{side:r,...A,ref:n}):J.jsx(hYo,{side:r,...A,ref:n})})},"TooltipContent")),hYo=j.forwardRef(_I(function(e,n){const o=Jie(lU,e.__scopeTooltip),i=u6e(lU,e.__scopeTooltip),r=j.useRef(null),A=dl(n,r),[s,a]=j.useState(null),{trigger:c,onClose:l}=o,g=r.current,{onPointerInTransitChange:u}=i,h=j.useCallback(()=>{a(null),u(!1)},[u]),d=j.useCallback((_,p)=>{const m=_.currentTarget,C={x:_.clientX,y:_.clientY},I=LTt(C,m.getBoundingClientRect()),f=HTt(C,I),y=GTt(p.getBoundingClientRect()),x=KTt([...f,...y]);a(x),u(!0)},[u]);return j.useEffect(()=>()=>h(),[h]),j.useEffect(()=>{if(c&&g){const _=_I(m=>d(m,g),"handleTriggerLeave"),p=_I(m=>d(m,c),"handleContentLeave");return c.addEventListener("pointerleave",_),g.addEventListener("pointerleave",p),()=>{c.removeEventListener("pointerleave",_),g.removeEventListener("pointerleave",p)}}},[c,g,d,h]),j.useEffect(()=>{if(s){const _=_I(p=>{const m=p.target,C={x:p.clientX,y:p.clientY},I=c?.contains(m)||g?.contains(m),f=!OTt(C,s);I?h():f&&(h(),l())},"handleTrackPointerGrace");return document.addEventListener("pointermove",_),()=>document.removeEventListener("pointermove",_)}},[c,g,s,l,h]),J.jsx(FTt,{...e,ref:A})},"TooltipContentHoverable")),_Yo=qgt("TooltipContent"),FTt=j.forwardRef(_I(function(e,n){const{__scopeTooltip:o,children:i,"aria-label":r,id:A,onEscapeKeyDown:s,onPointerDownOutside:a,...c}=e,l=Jie(lU,o),g=l6e(o),{onClose:u}=l;j.useEffect(()=>(document.addEventListener(g6e,u),()=>document.removeEventListener(g6e,u)),[u]),j.useEffect(()=>{if(l.trigger){const d=_I(_=>{_.target instanceof Node&&_.target.contains(l.trigger)&&u()},"handleScroll");return window.addEventListener("scroll",d,{capture:!0}),()=>window.removeEventListener("scroll",d,{capture:!0})}},[l.trigger,u]);const{setContentId:h}=l;return ty(()=>(h(A),()=>{h(void 0)}),[A,h]),J.jsx(toe,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:s,onPointerDownOutside:a,onFocusOutside:d=>d.preventDefault(),onDismiss:u,children:J.jsxs(fPe,{"data-state":l.stateAttribute,role:r?void 0:"tooltip",id:r?void 0:l.contentId,...g,...c,ref:n,style:{...c.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[J.jsx(_Yo,{children:i}),r?J.jsx(nYo,{id:l.contentId,role:"tooltip",children:r}):null]})})},"TooltipContentImpl"));function LTt(t,e){const n=Math.abs(e.top-t.y),o=Math.abs(e.bottom-t.y),i=Math.abs(e.right-t.x),r=Math.abs(e.left-t.x);switch(Math.min(n,o,i,r)){case r:return"left";case i:return"right";case n:return"top";case o:return"bottom";default:throw new Error("unreachable")}}_I(LTt,"getExitSideFromRect");function HTt(t,e,n=5){const o=[];switch(e){case"top":o.push({x:t.x-n,y:t.y+n},{x:t.x+n,y:t.y+n});break;case"bottom":o.push({x:t.x-n,y:t.y-n},{x:t.x+n,y:t.y-n});break;case"left":o.push({x:t.x+n,y:t.y-n},{x:t.x+n,y:t.y+n});break;case"right":o.push({x:t.x-n,y:t.y-n},{x:t.x-n,y:t.y+n});break}return o}_I(HTt,"getPaddedExitPoints");function GTt(t){const{top:e,right:n,bottom:o,left:i}=t;return[{x:i,y:e},{x:n,y:e},{x:n,y:o},{x:i,y:o}]}_I(GTt,"getPointsFromRect");function OTt(t,e){const{x:n,y:o}=t;let i=!1;for(let r=0,A=e.length-1;r<e.length;A=r++){const s=e[r],a=e[A],c=s.x,l=s.y,g=a.x,u=a.y;l>o!=u>o&&n<(g-c)*(o-l)/(u-l)+c&&(i=!i)}return i}_I(OTt,"isPointInPolygon");function KTt(t){const e=t.slice();return e.sort((n,o)=>n.x<o.x?-1:n.x>o.x?1:n.y<o.y?-1:n.y>o.y?1:0),UTt(e)}_I(KTt,"getHull");function UTt(t){if(t.length<=1)return t.slice();const e=[];for(let o=0;o<t.length;o++){const i=t[o];for(;e.length>=2;){const r=e[e.length-1],A=e[e.length-2];if((r.x-A.x)*(i.y-A.y)>=(r.y-A.y)*(i.x-A.x))e.pop();else break}e.push(i)}e.pop();const n=[];for(let o=t.length-1;o>=0;o--){const i=t[o];for(;n.length>=2;){const r=n[n.length-1],A=n[n.length-2];if((r.x-A.x)*(i.y-A.y)>=(r.y-A.y)*(i.x-A.x))n.pop();else break}n.push(i)}return n.pop(),e.length===1&&n.length===1&&e[0].x===n[0].x&&e[0].y===n[0].y?e:e.concat(n)}_I(UTt,"getHullPresorted");var mYo=sYo,pYo=cYo,IYo=lYo,YTt=dYo;const h6e=mYo,_6e=pYo,m6e=IYo,qie=j.forwardRef(({className:t,sideOffset:e=4,...n},o)=>J.jsx(YTt,{ref:o,sideOffset:e,className:qi("z-50 overflow-hidden rounded-md bg-slate-900 px-3 py-1.5 text-xs text-slate-50 animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 dark:bg-slate-50 dark:text-slate-900",t),...n}));qie.displayName=YTt.displayName;const CYo="24b58135-86c7-4e4b-bf6e-cca862bc4b26",zTt="runframe-crisp-chat-script",fYo="tscircuit.com",gU=t=>{window.$crisp=window.$crisp||[],window.$crisp.push(t)},yYo=()=>{if(window.$crisp=window.$crisp||[],window.CRISP_WEBSITE_ID=CYo,window.__RUNFRAME_CRISP_CONFIGURED__||(window.__RUNFRAME_CRISP_CONFIGURED__=!0,gU(["do","chat:hide"]),gU(["on","chat:closed",()=>gU(["do","chat:hide"])])),!document.getElementById(zTt)){const t=document.createElement("script");t.id=zTt,t.src="https://client.crisp.chat/l.js",t.async=!0,document.head.appendChild(t)}},EYo=()=>{yYo(),gU(["do","chat:show"]),gU(["do","chat:open"])},xYo=({isCli:t,hostname:e=typeof window<"u"?window.location.hostname:void 0}={})=>e?.toLowerCase()===fYo?!1:!!t,BYo=()=>J.jsx(h6e,{children:J.jsxs(_6e,{children:[J.jsx(m6e,{asChild:!0,children:J.jsx(ta,{type:"button",variant:"ghost",size:"icon","aria-label":"Get Support or Give Feedback",onClick:EYo,className:"rf-h-8 rf-w-8",children:J.jsx(RPo,{className:"rf-h-4 rf-w-4 rf-text-gray-500"})})}),J.jsx(qie,{side:"bottom",children:"Get Support or Give Feedback"})]})}),QYo=["assembly","pinout","analog_simulation","bom","circuit_json","errors","render_log","solvers"],p6e=t=>t instanceof Error?t.message:"An unknown error occurred",VTt=({code:t,fsMap:e,onRunClicked:n=void 0,errorMessage:o,errorStack:i,circuitJson:r,autoroutingGraphics:A,showRightHeaderContent:s=!0,showCodeTab:a=!1,codeTabContent:c,showJsonTab:l=!0,showRenderLogTab:g=!0,onActiveTabChange:u,renderLog:h,showImportAndFormatButtons:d=!0,className:_,headerClassName:p,leftHeaderContent:m,readOnly:C,isStreaming:I,autoroutingLog:f,onReportAutoroutingLog:y,isRunningCode:x,hasCodeChangedSinceLastRun:B,onEditEvent:S,editEvents:D,defaultActiveTab:w,defaultTab:F,availableTabs:R,autoRotate3dViewerDisabled:H,showSchematicDebugGrid:G=!1,showSchematicPorts:K=!1,onChangeShowSchematicDebugGrid:V,onChangeShowSchematicPorts:W,showToggleFullScreen:X=!0,defaultToFullScreen:ie=!1,activeEffectName:se,allowSelectingVersion:ee=!0,showFileMenu:oe=!1,isWebEmbedded:ae=!1,isCli:re=!1,projectName:le,schematicSvgOptions:fe,hideSchematicInAnalogSimulation:ye=!1,onRerunWithDebug:be,solverEvents:ue,onPcbBoundsSelected:Be})=>{fie();const{versions:pe,latestVersion:Ge,lastRunEvalVersion:Je,search:nt,setSearch:Ie,selectVersion:Ze}=WHo(ee),Ke=j.useMemo(()=>r?r.filter(_t=>_t&&"error_type"in _t||_t.type.includes("error")):null,[r]),Ye=j.useMemo(()=>r?r.filter(_t=>_t&&"warning_type"in _t||_t.type.includes("warning")):null,[r]),qe=j.useMemo(()=>r?r.some(_t=>_t.type==="schematic_group"):!0,[r]),Le=j.useMemo(()=>r?.some(_t=>_t.type==="pcb_panel"),[r]),Se=j.useMemo(()=>!r||!x||Ke?.length?!1:r.some(Gt=>Gt.type==="simulation_experiment")&&!pjn(r),[r,Ke,x]),ve=j.useMemo(()=>Ke?.find(_t=>_t.type.startsWith("simulation_")),[Ke]);uRt({errorMessage:o,errorStack:i,circuitJsonErrors:Ke});const Pe=F??R?.[0]??"pcb",[ze,Xe]=J7("runframe-active-tab",w??Pe,w);dRt({source:"runframe",component:"CircuitJsonPreview",isWebEmbedded:ae,activeTab:ze});const[st,ct]=j.useState(null),[ut,lt]=j.useState(ie),[Ct,Dt]=j.useState(G),[pt,Nt]=j.useState(K),Ht=V?G:Ct,gn=W?K:pt,dn=V??Dt,Jt=W??Nt;OLo(ut);const Ce=j.useCallback(_t=>{Xe(_t),u?.(_t)},[u,Xe]),At=()=>{lt(!ut)};j.useEffect(()=>{o&&(ze!=="errors"&&ct(ze),Ce("errors"))},[o]),j.useEffect(()=>{(ze==="code"||ze==="errors")&&r&&!o&&Ce(st??w??F??R?.[0]??"pcb")},[r]);const ht=j.useCallback(_t=>{window.TSCIRCUIT_3D_OBJECT_REF=_t===null?void 0:_t},[]);return J.jsx("div",{className:qi("flex flex-col relative rf-overflow-x-hidden rf-h-full",_),children:J.jsx("div",{className:qi("rf-md:sticky rf-md:top-2 rf-h-full",ut&&"rf-fixed rf-top-0 rf-left-0 rf-w-full rf-h-full rf-bg-white rf-overflow-hidden"),children:J.jsxs(K1e,{value:ze,onValueChange:Ce,className:"rf-flex-grow rf-flex rf-flex-col rf-h-full",children:[J.jsxs("div",{className:qi("rf-flex rf-items-center rf-gap-2 rf-p-2 rf-pb-0",p),children:[m,oe&&!m&&J.jsx(cU,{isWebEmbedded:ae,circuitJson:r,projectName:le,autoroutingLog:f,onReportAutoroutingLog:y,showSchematicDebugGrid:Ht,onChangeShowSchematicDebugGrid:dn,showSchematicPorts:gn,onChangeShowSchematicPorts:Jt}),(m||oe)&&J.jsx("div",{className:"rf-flex-grow"}),!m&&!oe&&x&&J.jsx(SB,{className:"rf-w-4 rf-h-4 rf-animate-spin"}),!m&&!oe&&J.jsx("div",{className:"rf-flex-grow"}),h&&h.progress!==1&&!o&&J.jsxs("div",{className:"rf-flex rf-items-center rf-gap-2 rf-min-w-0 rf-max-w-xs",children:[se?J.jsx("div",{className:"rf-text-xs rf-text-gray-500 rf-truncate rf-min-w-0",title:se,children:se}):h.lastRenderEvent&&J.jsx("div",{className:"rf-text-xs rf-text-gray-500 rf-truncate rf-min-w-0",title:h.lastRenderEvent?.phase??"",children:h.lastRenderEvent?.phase??""}),J.jsx("div",{className:"rf-w-4 rf-h-4 rf-bg-blue-500 rf-opacity-50 rf-rounded-full rf-text-white rf-flex-shrink-0",children:J.jsx(SB,{className:"rf-w-4 rf-h-4 rf-animate-spin"})}),J.jsxs("div",{className:"rf-text-xs rf-font-bold rf-text-gray-700 rf-tabular-nums rf-flex-shrink-0",children:[((h.progress??0)*100).toFixed(1),"%"]})]}),s&&xYo({isCli:re})&&J.jsx(BYo,{}),s&&J.jsxs(FZ,{children:[a&&J.jsx(XQ,{value:"code",children:"Code"}),!R||R.includes("pcb")?J.jsxs(XQ,{value:"pcb",className:"rf-whitespace-nowrap",children:[r&&J.jsx("span",{className:qi("rf-inline-flex rf-items-center rf-justify-center rf-w-2 rf-h-2 rf-mr-1 rf-text-xs rf-font-bold rf-text-white rf-rounded-full",B?"rf-bg-gray-500":"rf-bg-blue-500")}),"PCB"]}):null,!R||R.includes("schematic")?J.jsxs(XQ,{value:"schematic",className:qi("rf-whitespace-nowrap",r&&!qe&&"rf-opacity-50"),disabled:r?!qe||Le:!1,children:[r&&J.jsx("span",{className:qi("rf-inline-flex rf-items-center rf-justify-center rf-w-2 rf-h-2 rf-mr-1 rf-text-xs rf-font-bold rf-text-white rf-rounded-full",B?"rf-bg-gray-500":"rf-bg-blue-500")}),"Schematic"]}):null,!R||R.includes("cad")?J.jsxs(XQ,{value:"cad",children:[r&&J.jsx("span",{className:qi("inline-flex items-center justify-center w-2 h-2 mr-1 text-xs font-bold text-white rounded-full",B?"rf-bg-gray-500":"rf-bg-blue-500")}),"3D"]}):null,!["pcb","cad","schematic"].includes(ze)&&J.jsx(XQ,{value:ze,children:kht(ze)}),J.jsxs(woe,{children:[J.jsx(Poe,{asChild:!0,children:J.jsxs("div",{className:"rf-whitespace-nowrap rf-p-2 rf-mr-1 rf-cursor-pointer rf-relative",children:[J.jsx(QPo,{className:"rf-w-4 rf-h-4"}),(Ke&&Ke.length>0||o)&&J.jsx("span",{className:"rf-inline-flex rf-absolute rf-top-[6px] rf-right-[4px] rf-items-center rf-justify-center rf-w-1 rf-h-1 rf-ml-2 rf-text-[8px] rf-font-bold rf-text-white rf-bg-red-500 rf-rounded-full"})]})}),J.jsxs(TK,{className:"rf-*:text-xs rf-z-[101]",children:[QYo.filter(_t=>!R||R.includes(_t)).map(_t=>J.jsxs(Sh,{onSelect:()=>Ce(_t),children:[ze!==_t&&J.jsx(kPt,{className:"rf-w-3 rf-h-3 rf-opacity-30"}),ze===_t&&J.jsx(L3,{className:"rf-w-3 rf-h-3"}),J.jsx("div",{className:"rf-pr-2",children:kht(_t)}),_t==="errors"&&(Ke&&Ke.length>0||o)&&J.jsx("span",{className:"rf-inline-flex rf-items-center rf-justify-center rf-w-3 rf-h-3 rf-ml-2 rf-text-[8px] rf-font-bold rf-text-white rf-bg-red-500 rf-rounded-full",children:o?1:Ke?.length}),_t==="solvers"&&ue&&ue.length>0&&J.jsx("span",{className:"rf-inline-flex rf-items-center rf-justify-center rf-min-w-[12px] rf-h-3 rf-px-1 rf-ml-2 rf-text-[8px] rf-font-bold rf-text-white rf-bg-blue-500 rf-rounded-full",children:ue.length})]},_t)),J.jsx(Sh,{disabled:!0,className:"rf-opacity-60 rf-cursor-default rf-select-none",children:J.jsxs("div",{className:"rf-pr-2 rf-text-xs rf-text-gray-500",children:["@tscircuit/runframe@",hRt.split(".").map((_t,Gt)=>Gt===2?parseInt(_t)+1:_t).join(".")]})}),ee?J.jsxs(RK,{onOpenChange:_t=>!_t&&Ie(""),children:[J.jsx(mT,{className:"rf-text-xs rf-opacity-60",children:J.jsxs("div",{className:"rf-pr-2 rf-text-xs rf-text-gray-500",children:["@tscircuit/eval@",Je??Ge??"latest"]})}),J.jsx(NK,{children:J.jsxs(pT,{className:"rf-*:text-xs rf-w-40 rf-max-h-[200px] rf-overflow-y-auto",children:[J.jsx("div",{className:"rf-p-1",children:J.jsx(YPe,{value:nt,onChange:_t=>Ie(_t.target.value),placeholder:"Search...",className:"rf-h-7 rf-text-xs"})}),J.jsx(s3t,{}),J.jsx(Sh,{onSelect:()=>Ze(null),children:Ge?`${Ge} (latest)`:"latest"}),pe.map(_t=>J.jsx(Sh,{onSelect:()=>Ze(_t),children:_t},_t))]})})]}):Je&&J.jsx(Sh,{disabled:!0,className:"rf-opacity-60 rf-cursor-default rf-select-none",children:J.jsxs("div",{className:"rf-pr-2 rf-text-xs rf-text-gray-500",children:["@tscircuit/eval@",Je]})})]})]})]}),X&&J.jsx(ta,{onClick:At,variant:"ghost",children:ut?J.jsx(TPo,{size:16}):J.jsx(wPo,{size:16})})]}),a&&J.jsx(IC,{value:"code",className:"rf-flex-grow rf-overflow-hidden",children:J.jsx("div",{className:"rf-h-full",children:c})}),(!R||R.includes("pcb"))&&J.jsx(IC,{value:"pcb",children:J.jsx("div",{className:qi("rf-overflow-hidden",ut?"rf-h-[calc(100vh-52px)]":"rf-h-full"),children:J.jsx(gx,{fallbackRender:({error:_t})=>J.jsx("div",{className:"rf-mt-4 rf-bg-red-50 rf-rounded-md rf-border rf-border-red-200",children:J.jsxs("div",{className:"rf-p-4",children:[J.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-red-800 rf-mb-3",children:"Error loading PCB viewer"}),J.jsx("p",{className:"rf-text-xs rf-font-mono rf-whitespace-pre-wrap rf-text-red-600 rf-mt-2",children:p6e(_t)})]})}),children:r?J.jsx(HLo,{focusOnHover:!1,circuitJson:r,debugGraphics:A,onBoundsSelected:Be,containerClassName:qi("rf-h-full rf-w-full",ut?"rf-min-h-[calc(100vh-240px)]":"rf-min-h-[620px]"),onEditEventsChanged:_t=>{if(S)for(const Gt of _t)S(Gt)}}):J.jsx(w5,{onRunClicked:n})})})}),(!R||R.includes("assembly"))&&J.jsx(IC,{value:"assembly",children:J.jsx("div",{className:qi("rf-overflow-auto",ut?"rf-h-[calc(100vh-60px)]":"rf-h-full rf-min-h-[620px]"),children:J.jsx(gx,{fallback:J.jsx("div",{children:"Error loading Assembly"}),children:r?J.jsx(m9o,{circuitJson:r,containerStyle:{height:"100%"},editingEnabled:!0,debugGrid:!0}):J.jsx(w5,{onRunClicked:n})})})}),(!R||R.includes("pinout"))&&J.jsx(IC,{value:"pinout",children:J.jsx("div",{className:qi("rf-overflow-auto",ut?"rf-h-[calc(100vh-60px)]":"rf-h-full rf-min-h-[620px]"),children:J.jsx(gx,{fallback:J.jsx("div",{children:"Error loading Pinout Viewer"}),children:r?J.jsx(p9o,{circuitJson:r,containerStyle:{height:"100%"}}):J.jsx(w5,{onRunClicked:n})})})}),(!R||R.includes("schematic"))&&J.jsx(IC,{value:"schematic",children:J.jsx("div",{className:qi("rf-overflow-auto rf-bg-white",ut?"rf-h-[calc(100vh-60px)]":"rf-h-full rf-min-h-[620px]"),children:J.jsx(gx,{fallbackRender:({error:_t})=>J.jsx("div",{className:"rf-mt-4 rf-bg-red-50 rf-rounded-md rf-border rf-border-red-200",children:J.jsxs("div",{className:"rf-p-4",children:[J.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-red-800 rf-mb-3",children:"Error loading Schematic"}),J.jsx("p",{className:"rf-text-xs rf-font-mono rf-whitespace-pre-wrap rf-text-red-600 rf-mt-2",children:p6e(_t)})]})}),children:r?J.jsx(e9o,{circuitJson:r,containerStyle:{height:"100%"},editingEnabled:!0,onEditEvent:_t=>{S?.(_t)},debugGrid:Ht,showSchematicPorts:gn,css:fe?.css,className:fe?.className}):J.jsx(w5,{onRunClicked:n})})})}),(!R||R.includes("cad"))&&J.jsx(IC,{value:"cad",children:J.jsx("div",{className:qi("rf-overflow-auto",ut?"rf-h-[calc(100vh-60px)]":"rf-h-full rf-min-h-[620px]"),children:J.jsx(gx,{fallbackRender:({error:_t,resetErrorBoundary:Gt})=>J.jsx(aPo,{error:_t,resetErrorBoundary:Gt}),children:r?J.jsx(APo,{ref:ht,circuitJson:r,autoRotateDisabled:H},`cad-${ut}`):J.jsx(w5,{onRunClicked:n})})})}),(!R||R.includes("analog_simulation"))&&J.jsx(IC,{value:"analog_simulation",children:J.jsx("div",{className:qi("rf-overflow-auto",ut?"rf-h-[calc(100vh-60px)]":"rf-h-full rf-min-h-[620px]"),children:J.jsx(gx,{fallback:J.jsx("div",{children:"Error loading Analog Simulation"}),children:r?ve?J.jsx("div",{className:"rf-mt-4 rf-bg-red-50 rf-rounded-md rf-border rf-border-red-200",children:J.jsxs("div",{className:"rf-p-4",children:[J.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-red-800 rf-mb-3",children:"Error running analog simulation"}),J.jsx("p",{className:"rf-text-xs rf-font-mono rf-whitespace-pre-wrap rf-text-red-600 rf-mt-2",children:ve.message})]})}):Se?J.jsx("div",{className:"rf-flex rf-h-full rf-min-h-[300px] rf-items-center rf-justify-center rf-bg-slate-50",children:J.jsxs("div",{className:"rf-flex rf-items-center rf-gap-2 rf-text-sm rf-text-slate-600",children:[J.jsx(SB,{className:"rf-h-4 rf-w-4 rf-animate-spin"}),"Running analog simulation..."]})}):J.jsx(_9o,{circuitJson:r,hideSchematic:ye,containerStyle:{height:"100%"}}):J.jsx(w5,{onRunClicked:n})})})}),(!R||R.includes("bom"))&&J.jsx(IC,{value:"bom",children:J.jsx("div",{className:qi("rf-overflow-auto",ut?"rf-h-[calc(100vh-60px)]":"rf-h-full rf-min-h-[620px]"),children:J.jsx(gx,{fallbackRender:({error:_t})=>J.jsx("div",{className:"rf-mt-4 rf-bg-red-50 rf-rounded-md rf-border rf-border-red-200",children:J.jsxs("div",{className:"rf-p-4",children:[J.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-red-800 rf-mb-3",children:"Error loading Bill of Materials"}),J.jsx("p",{className:"rf-text-xs rf-font-mono rf-whitespace-pre-wrap rf-text-red-600 rf-mt-2",children:p6e(_t)})]})}),children:r?J.jsx(N9o,{circuitJson:r}):J.jsx(w5,{onRunClicked:n})})})}),(!R||R.includes("circuit_json"))&&J.jsx(IC,{value:"circuit_json",children:J.jsx("div",{className:qi("rf-overflow-auto",ut?"rf-h-[calc(100vh-60px)]":"rf-h-full rf-min-h-[620px]"),children:J.jsx(gx,{fallback:J.jsx("div",{children:"Error loading JSON viewer"}),children:r?J.jsx(f9o,{elements:r}):J.jsx(w5,{onRunClicked:n})})})}),(!R||R.includes("errors"))&&J.jsx(IC,{value:"errors",className:"rf-h-full",children:J.jsx("div",{className:qi("rf-overflow-hidden",ut?"rf-h-[calc(100vh-60px)]":"rf-h-full rf-min-h-[620px]"),children:o||Ke&&Ke.length>0||r?J.jsx(d8o,{code:t,fsMap:e,circuitJsonErrors:Ke,circuitJsonWarnings:Ye,errorMessage:o,errorStack:i,circuitJson:r,evalVersion:Je,autoroutingLog:f,onReportAutoroutingLog:y}):J.jsx(w5,{onRunClicked:n})})}),g&&(!R||R.includes("render_log"))&&J.jsx(IC,{value:"render_log",children:J.jsx(YLo,{renderLog:h,onRerunWithDebug:be})}),(!R||R.includes("solvers"))&&J.jsx(IC,{value:"solvers",children:J.jsx("div",{className:qi("rf-overflow-hidden",ut?"rf-h-[calc(100vh-60px)]":"rf-h-full rf-min-h-[620px]"),children:J.jsx(gx,{fallback:J.jsx("div",{children:"Error loading Solvers view"}),children:J.jsx(JHo,{solverEvents:ue})})})})]})})})};const JTt=Symbol("Comlink.proxy"),SYo=Symbol("Comlink.endpoint"),qTt=Symbol("Comlink.releaseProxy"),I6e=Symbol("Comlink.finalizer"),Wie=Symbol("Comlink.thrown"),WTt=t=>typeof t=="object"&&t!==null||typeof t=="function",bYo={canHandle:t=>WTt(t)&&t[JTt],serialize(t){const{port1:e,port2:n}=new MessageChannel;return XTt(t,e),[n,[n]]},deserialize(t){return t.start(),ZTt(t)}},DYo={canHandle:t=>WTt(t)&&Wie in t,serialize({value:t}){let e;return t instanceof Error?e={isError:!0,value:{message:t.message,name:t.name,stack:t.stack}}:e={isError:!1,value:t},[e,[]]},deserialize(t){throw t.isError?Object.assign(new Error(t.value.message),t.value):t.value}},jTt=new Map([["proxy",bYo],["throw",DYo]]);function MYo(t,e){for(const n of t)if(e===n||n==="*"||n instanceof RegExp&&n.test(e))return!0;return!1}function XTt(t,e=globalThis,n=["*"]){e.addEventListener("message",function o(i){if(!i||!i.data)return;if(!MYo(n,i.origin)){console.warn(`Invalid origin '${i.origin}' for comlink proxy`);return}const{id:r,type:A,path:s}=Object.assign({path:[]},i.data),a=(i.data.argumentList||[]).map(n6);let c;try{const l=s.slice(0,-1).reduce((u,h)=>u[h],t),g=s.reduce((u,h)=>u[h],t);switch(A){case"GET":c=g;break;case"SET":l[s.slice(-1)[0]]=n6(i.data.value),c=!0;break;case"APPLY":c=g.apply(l,a);break;case"CONSTRUCT":{const u=new g(...a);c=f6e(u)}break;case"ENDPOINT":{const{port1:u,port2:h}=new MessageChannel;XTt(t,h),c=RYo(u,[u])}break;case"RELEASE":c=void 0;break;default:return}}catch(l){c={value:l,[Wie]:0}}Promise.resolve(c).catch(l=>({value:l,[Wie]:0})).then(l=>{const[g,u]=Zie(l);e.postMessage(Object.assign(Object.assign({},g),{id:r}),u),A==="RELEASE"&&(e.removeEventListener("message",o),$Tt(e),I6e in t&&typeof t[I6e]=="function"&&t[I6e]())}).catch(l=>{const[g,u]=Zie({value:new TypeError("Unserializable return value"),[Wie]:0});e.postMessage(Object.assign(Object.assign({},g),{id:r}),u)})}),e.start&&e.start()}function wYo(t){return t.constructor.name==="MessagePort"}function $Tt(t){wYo(t)&&t.close()}function ZTt(t,e){const n=new Map;return t.addEventListener("message",function(i){const{data:r}=i;if(!r||!r.id)return;const A=n.get(r.id);if(A)try{A(r)}finally{n.delete(r.id)}}),C6e(t,n,[],e)}function jie(t){if(t)throw new Error("Proxy has been released and is not useable")}function ekt(t){return PT(t,new Map,{type:"RELEASE"}).then(()=>{$Tt(t)})}const Xie=new WeakMap,$ie="FinalizationRegistry"in globalThis&&new FinalizationRegistry(t=>{const e=(Xie.get(t)||0)-1;Xie.set(t,e),e===0&&ekt(t)});function PYo(t,e){const n=(Xie.get(e)||0)+1;Xie.set(e,n),$ie&&$ie.register(t,e,t)}function vYo(t){$ie&&$ie.unregister(t)}function C6e(t,e,n=[],o=function(){}){let i=!1;const r=new Proxy(o,{get(A,s){if(jie(i),s===qTt)return()=>{vYo(r),ekt(t),e.clear(),i=!0};if(s==="then"){if(n.length===0)return{then:()=>r};const a=PT(t,e,{type:"GET",path:n.map(c=>c.toString())}).then(n6);return a.then.bind(a)}return C6e(t,e,[...n,s])},set(A,s,a){jie(i);const[c,l]=Zie(a);return PT(t,e,{type:"SET",path:[...n,s].map(g=>g.toString()),value:c},l).then(n6)},apply(A,s,a){jie(i);const c=n[n.length-1];if(c===SYo)return PT(t,e,{type:"ENDPOINT"}).then(n6);if(c==="bind")return C6e(t,e,n.slice(0,-1));const[l,g]=tkt(a);return PT(t,e,{type:"APPLY",path:n.map(u=>u.toString()),argumentList:l},g).then(n6)},construct(A,s){jie(i);const[a,c]=tkt(s);return PT(t,e,{type:"CONSTRUCT",path:n.map(l=>l.toString()),argumentList:a},c).then(n6)}});return PYo(r,t),r}function NYo(t){return Array.prototype.concat.apply([],t)}function tkt(t){const e=t.map(Zie);return[e.map(n=>n[0]),NYo(e.map(n=>n[1]))]}const nkt=new WeakMap;function RYo(t,e){return nkt.set(t,e),t}function f6e(t){return Object.assign(t,{[JTt]:!0})}function Zie(t){for(const[e,n]of jTt)if(n.canHandle(t)){const[o,i]=n.serialize(t);return[{type:"HANDLER",name:e,value:o},i]}return[{type:"RAW",value:t},nkt.get(t)||[]]}function n6(t){switch(t.type){case"HANDLER":return jTt.get(t.name).deserialize(t.value);case"RAW":return t.value}}function PT(t,e,n,o){return new Promise(i=>{const r=TYo();e.set(r,i),t.start&&t.start(),t.postMessage(Object.assign({id:r},n),o)})}function TYo(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}function y6e(t,e=""){const n=[];for(const o in t){if(!Object.prototype.hasOwnProperty.call(t,o))continue;const i=t[o],r=e?`${e}.${o}`:o;if(i!==null&&typeof i=="object"&&!Array.isArray(i)){const A=y6e(i,r);n.push(...A)}else n.push(r)}return n}function okt(t,e){const n=e.split(".");let o=t;for(const i of n)o=o[i];return o}var kYo=(t="latest")=>[`https://jscdn.tscircuit.com/@tscircuit/eval/${t}/dist/webworker/entrypoint.js`,`https://cdn.jsdelivr.net/npm/@tscircuit/eval@${t}/dist/webworker/entrypoint.js`,`https://unpkg.com/@tscircuit/eval@${t}/dist/webworker/entrypoint.js`],FYo=async(t="latest",e=!1)=>{let n;for(const o of kYo(t))try{const i=await globalThis.fetch(o);if(!i.ok)throw new Error(`Failed to fetch webworker entrypoint from ${o}: ${i.status} ${i.statusText}`);return await i.blob()}catch(i){n=i,e&&console.warn(`[Worker] Failed to fetch webworker entrypoint from ${o}, trying next CDN fallback if available`,i)}throw n instanceof Error?n:new Error("Failed to fetch webworker entrypoint from CDN fallbacks")},ikt=async t=>{const e=globalThis.TSCIRCUIT_GLOBAL_CIRCUIT_WORKER;if(e&&typeof e.kill=="function"){t.verbose&&console.log("[Worker] Killing previous global worker instance...");try{await e.kill()}catch(u){t.verbose&&console.warn("[Worker] Error killing previous global worker instance:",u),globalThis.TSCIRCUIT_GLOBAL_CIRCUIT_WORKER===e&&(globalThis.TSCIRCUIT_GLOBAL_CIRCUIT_WORKER=void 0)}}t.verbose&&console.log("[Worker] Creating circuit web worker with config:",t);let n=t.webWorkerBlobUrl??t.webWorkerUrl;if(!n){const u=await FYo(t.evalVersion??"latest",t.verbose);n=URL.createObjectURL(u)}const o=new Worker(n,{type:"module"});let i;o.addEventListener("error",u=>{console.error("[Worker] Error in worker",u),i=u}),o.addEventListener("unhandledrejection",u=>{console.error("[Worker] Unhandled rejection in worker",u)}),o.addEventListener("messageerror",u=>{console.error("[Worker] Message error in worker",u)});const r=u=>{console.log("[Worker] Message in worker",u)};if(o.addEventListener("message",r),o.addEventListener("message",async u=>{const h=u.data;if(h?.type==="worker_fetch")try{const d=await globalThis.fetch(h.input,h.init),_=await d.text();o.postMessage({type:"worker_fetch_result",requestId:h.requestId,success:!0,response:{body:_,status:d.status,statusText:d.statusText,headers:(()=>{const p={};return d.headers.forEach((m,C)=>{p[C]=m}),p})()}})}catch(d){o.postMessage({type:"worker_fetch_result",requestId:h.requestId,success:!1,error:{name:d.name,message:d.message,stack:d.stack}})}}),i)throw i;const A=ZTt(o);o.removeEventListener("message",r);function s(u){return!u||typeof u!="object"?u:u.type&&u.props!==void 0?{__isSerializedReactElement:!0,type:u.type,props:a(u.props),key:u.key}:u}function a(u){if(!u||typeof u!="object")return u;const h={};for(const[d,_]of Object.entries(u))d==="children"?Array.isArray(_)?h.children=_.map(s):h.children=s(_):h[d]=_;return h}t.enableFetchProxy&&o.postMessage({type:"override_global_fetch"}),t.disableCdnLoading&&await A.setDisableCdnLoading(!0),t.snippetsApiBaseUrl&&await A.setSnippetsApiBaseUrl(t.snippetsApiBaseUrl),t.tscircuitSessionToken&&await A.setTscircuitSessionToken(t.tscircuitSessionToken),t.easyEdaProxyConfig&&await A.setEasyEdaProxyConfig(t.easyEdaProxyConfig);const c=u=>typeof u=="function"?f6e(u):u;if(t.platform)for(const u of y6e(t.platform))await A.setPlatformConfigProperty(u,c(okt(t.platform,u))).catch(h=>{throw new Error(`Error setting platform config property ${u}: ${h instanceof Error?h.message:String(h)}`)});if(t.projectConfig)for(const u of y6e(t.projectConfig))await A.setProjectConfigProperty(u,c(okt(t.projectConfig,u))).catch(h=>{throw new Error(`Error setting project config property ${u}: ${h instanceof Error?h.message:String(h)}`)});let l=!1;const g={clearEventListeners:A.clearEventListeners.bind(A),enableDebug:async(...u)=>{if(l)throw new Error("CircuitWebWorker was terminated, can't enableDebug");return A.enableDebug.bind(A)(...u)},version:A.version.bind(A),execute:async(...u)=>{if(l)throw new Error("CircuitWebWorker was terminated, can't execute");return A.execute.bind(A)(...u)},executeComponent:async u=>{if(l)throw new Error("CircuitWebWorker was terminated, can't executeComponent");if(typeof u=="function")return A.executeComponent.bind(A)(u);if(u&&typeof u=="object"&&u.type){const h=s(u);return A.executeComponent.bind(A)(h)}return A.executeComponent.bind(A)(u)},executeWithFsMap:async(...u)=>{if(l)throw new Error("CircuitWebWorker was terminated, can't executeWithFsMap");return A.executeWithFsMap.bind(A)(...u)},renderUntilSettled:A.renderUntilSettled.bind(A),getCircuitJson:A.getCircuitJson.bind(A),on:(u,h)=>{const d=f6e(h);A.on(u,d)},kill:async()=>{A[qTt](),o.terminate(),l=!0,globalThis.TSCIRCUIT_GLOBAL_CIRCUIT_WORKER===g&&(globalThis.TSCIRCUIT_GLOBAL_CIRCUIT_WORKER=void 0)}};return g.__rawWorker=o,globalThis.TSCIRCUIT_GLOBAL_CIRCUIT_WORKER=g,g};const LYo=({error:t,resetErrorBoundary:e})=>{const n=t instanceof Error?t:new Error(String(t));return J.jsx("section",{className:"rf-h-full rf-w-full rf-grid rf-place-items-center",children:J.jsx("div",{className:"rf-min-h-full rf-flex rf-items-center rf-justify-center rf-px-4",children:J.jsxs("div",{className:"rf-max-w-lg rf-w-full rf-text-center",children:[J.jsxs("div",{className:"rf-mb-8",children:[J.jsx("div",{className:"rf-inline-flex rf-items-center rf-justify-center rf-w-20 rf-h-20 rf-bg-red-100 rf-rounded-full rf-mb-6",children:J.jsx(GPo,{className:"rf-w-10 rf-h-10 rf-text-red-600"})}),J.jsx("h1",{className:"rf-text-2xl rf-font-bold rf-text-gray-900 rf-mb-3",children:"Oops! Something went wrong"}),J.jsx("p",{className:"rf-text-gray-600 rf-mb-4",children:"RunFrame encountered an unexpected error."}),J.jsx("pre",{className:"rf-text-xs no-scrollbar rf-font-mono rf-text-left rf-whitespace-pre-wrap rf-text-red-600 rf-bg-red-50 rf-border rf-border-red-200 rf-p-3 rf-rounded-lg rf-mb-4 rf-overflow-auto rf-max-h-[120px]",children:n.message}),n.stack&&J.jsxs("details",{className:"rf-text-center rf-mb-6",children:[J.jsx("summary",{className:"rf-text-xs rf-text-gray-500 rf-cursor-pointer hover:rf-text-gray-700",children:"View stack trace"}),J.jsx("pre",{className:"rf-text-xs rf-font-mono no-scrollbar rf-whitespace-pre-wrap rf-text-gray-500 rf-bg-gray-100 rf-p-3 rf-rounded-lg rf-mt-2 rf-overflow-auto rf-text-left rf-max-h-[150px]",children:n.stack})]})]}),J.jsxs("div",{className:"rf-flex rf-flex-col rf-gap-2 rf-justify-center",children:[J.jsx(ta,{variant:"destructive",size:"lg",onClick:()=>window.location.reload(),children:"Refresh Dev Server"}),J.jsx(ta,{variant:"outline",size:"lg",onClick:e,children:"Try Again"})]})]})})})},rkt=t=>{const e={};if(!t)return e;for(const o of C2)e[o]=0;const n=new Map;for(const o of t){const[,,i,r]=o.type.split(":");if(r==="start"){n.set(`${i}:${o.renderId}`,o);continue}if(r==="end"){const A=n.get(`${i}:${o.renderId}`);if(A){const s=o.createdAt-A.createdAt;e[i]=(e[i]||0)+s}}}return e},HYo=(t,e)=>{const n={};for(const[o,i]of t.entries()){const r=e.get(o);r!==i&&(n[o]={old:i,new:r})}for(const[o,i]of e.entries())t.has(o)||(n[o]={old:void 0,new:i});return n};function GYo(){const t=j.useRef(Promise.resolve()),e=j.useRef(!1),n=j.useRef(null),o=j.useCallback(async A=>{await t.current;const s={cancelled:!1};n.current=s;let a;const c=new Promise(l=>{a=l});try{return t.current=c,e.current=!0,await A()}catch(l){if(!s.cancelled)throw l}finally{e.current=!1,n.current=null,a()}},[]),i=j.useCallback(()=>{n.current&&(n.current.cancelled=!0),t.current=Promise.resolve(),e.current=!1},[]),r=j.useCallback(()=>e.current,[]);return{runWithMutex:o,isLocked:r,cancel:i}}const OYo=({message:t="Loading files..."})=>J.jsxs("div",{className:"rf-flex rf-flex-col rf-w-full rf-h-full",children:[J.jsxs("div",{className:"rf-flex rf-items-center rf-gap-4 rf-p-2 rf-border-b",children:[J.jsx("div",{className:"rf-w-20 rf-h-9 rf-bg-gray-200 dark:rf-bg-gray-700 rf-rounded-md rf-animate-pulse"}),J.jsx("div",{className:"rf-flex rf-gap-6 rf-ml-auto",children:["PCB","Schematic","3D"].map((e,n)=>J.jsx("div",{className:"rf-h-6 rf-w-20 rf-bg-gray-200 dark:rf-bg-gray-700 rf-rounded rf-animate-pulse"},n))})]}),J.jsx("div",{className:"rf-flex-1 rf-p-4",children:J.jsx("div",{className:"rf-w-full rf-h-full rf-rounded-lg rf-bg-gray-100 dark:rf-bg-gray-800 rf-animate-pulse rf-flex rf-items-center rf-justify-center",children:J.jsx("div",{className:"rf-flex rf-flex-col rf-items-center rf-gap-4",children:J.jsx("div",{className:"rf-text-sm rf-text-gray-400 dark:rf-text-gray-500",children:t})})})})]}),ere=t=>{const e=t.toLowerCase(),n=e.split("/").pop();return e.endsWith(".circuit.json")||n==="circuit.json"},KYo=t=>t.endsWith(".tsx")||ere(t)||t.endsWith(".jsx"),UYo=({mainComponentPath:t,fsMap:e})=>j.useMemo(()=>{if(!(t!=null&&ere(t)))return{isStaticCircuitJson:!1,circuitJson:null,error:null};const o=e.get(t);if(!o)return{isStaticCircuitJson:!0,circuitJson:null,error:`Circuit JSON file not found: ${t}`};try{return{isStaticCircuitJson:!0,circuitJson:JSON.parse(o),error:null}}catch(i){return{isStaticCircuitJson:!0,circuitJson:null,error:`Failed to parse circuit.json: ${i instanceof Error?i.message:String(i)}`}}},[t,e]),YYo=t=>!t||typeof t!="object"?!1:!!("error_type"in t||typeof t.type=="string"&&t.type.includes("error")),zYo=t=>t instanceof Error?{name:t.name,message:t.message,stack:t.stack}:typeof t=="string"?{message:t}:t&&typeof t=="object"?t:{message:String(t)},VYo=t=>Array.isArray(t)?t.filter(YYo):[],E6e=({circuitJson:t,executionError:e})=>{const n=[];e&&n.push(zYo(e));const o=VYo(t);return n.push(...o),{hasExecutionError:!!e,...n.length>0?{errors:n}:{}}},JYo=26,py=Ga("run-frame:RunFrame"),qYo=async()=>{try{const t=await fetch("https://data.jsdelivr.com/v1/package/npm/@tscircuit/eval");if(t.ok)return(await t.json()).tags?.latest}catch(t){console.error("Failed to fetch latest eval version",t)}},Akt=async(t,e)=>{if(t)return t;if(e||!window.TSCIRCUIT_LATEST_EVAL_VERSION){const n=await qYo();if(n)return window.TSCIRCUIT_LATEST_EVAL_VERSION=n,n}return window.TSCIRCUIT_LATEST_EVAL_VERSION?window.TSCIRCUIT_LATEST_EVAL_VERSION:"latest"},skt=t=>{fie();const e=Yu(ue=>ue.circuitJson),n=Yu(ue=>ue.setCircuitJson),[o,i]=j.useState(null),r=j.useRef(null),[A,s]=j.useState(null),[a,c]=j.useReducer((ue,Be)=>ue+1,0),l=yie(ue=>ue.setLastRunEvalVersion),g=j.useRef(0),u=GYo(),[h,d]=j.useState(!1),[_,p]=j.useState(!1),[m,C]=j.useState({}),[I,f]=j.useState(""),[y,x]=j.useState(!1),[B,S]=j.useState(!1),D=Object.values(m).sort((ue,Be)=>ue.startTime-Be.startTime)[0]?.effectName,w=ue=>{t.onRunCompleted?.(ue)};j.useEffect(()=>{const ue=Be=>{(Be.ctrlKey||Be.metaKey)&&Be.key==="Enter"&&!h&&(Be.preventDefault(),Be.stopPropagation(),c(1))};return window.addEventListener("keydown",ue,{capture:!0}),()=>window.removeEventListener("keydown",ue,{capture:!0})},[h]),j.useEffect(()=>{let ue=!1;return(async()=>{try{if(!globalThis.runFrameWorker){const pe=await Akt(t.evalVersion,t.forceLatestEvalVersion),Ge=await ikt({evalVersion:pe,webWorkerBlobUrl:t.evalWebWorkerBlobUrl,projectConfig:{projectBaseUrl:t.projectBaseUrl||`${Qf}/files/static`},...t.platformConfig&&{platformConfig:t.platformConfig},verbose:!0,...t.enableFetchProxy&&{enableFetchProxy:t.enableFetchProxy},...window.TSCIRCUIT_USE_RUNFRAME_FOR_CLI&&{disableCdnLoading:!0},...t.tscircuitSessionToken&&{tscircuitSessionToken:t.tscircuitSessionToken},...t.easyEdaProxyConfig&&{easyEdaProxyConfig:t.easyEdaProxyConfig}});if(ue)return;globalThis.runFrameWorker=Ge,l(pe)}ue||p(!0)}catch(pe){console.error("Failed to preload eval worker",pe)}})(),()=>{ue=!0}},[t.evalVersion,t.evalWebWorkerBlobUrl,t.forceLatestEvalVersion,t.tscircuitSessionToken]);const[F,R]=j.useState(null),[H,G]=j.useState({}),[K,V]=j.useState([]),[W,X]=j.useState(t.defaultActiveTab??t.defaultTab??"pcb");dRt({source:"runframe",component:"RunFrame",isWebEmbedded:t.isWebEmbedded,activeTab:W}),j.useEffect(()=>{t.debug&&Ga.enable("run-frame*")},[t.debug]);const ie=t.fsMap instanceof Map?t.fsMap:Object.entries(t.fsMap??{}).reduce((ue,[Be,pe])=>ue.set(Be,pe),new Map),se=j.useRef(null),ee=j.useRef(null),{isStaticCircuitJson:oe,circuitJson:ae,error:re}=UYo({mainComponentPath:t.mainComponentPath,fsMap:ie});j.useEffect(()=>{oe&&(ae?(n(ae),i(null)):re&&i({error:re,stack:""}))},[oe,ae,re]),j.useEffect(()=>{if(t.isLoadingFiles||oe)return;const ue=ie instanceof Map?Object.fromEntries(ie.entries()):ie;if(!ue||Object.keys(ue).length===0){i({error:"No files provided. Please provide at least one file with code to execute.",stack:""}),d(!1);return}const Be=a!==g.current;if(se.current&&e){const Ge=HYo(se.current,ie);if(Object.keys(Ge).length>0)py("code changes detected");else if(ee.current!==t.entrypoint)py("render triggered by entrypoint change");else if(!Be){py("render triggered without changes to fsMap, skipping");return}}if(t.showRunButton&&a===g.current)return;se.current=ie,ee.current=t.entrypoint??null,g.current=a,d(!0);const pe=async()=>{py("running render worker"),i(null),R(null),C({}),V([]);const Ge={progress:0,debugOutputs:[]};let Je=!1;r.current=()=>{Je=!0};const nt=await Akt(t.evalVersion,!globalThis.runFrameWorker&&t.forceLatestEvalVersion);py("resolvedEvalVersion",nt);const Ie=globalThis.runFrameWorker??await ikt({evalVersion:nt,webWorkerBlobUrl:t.evalWebWorkerBlobUrl,verbose:!0,projectConfig:{projectBaseUrl:t.projectBaseUrl||`${Qf}/files/static`},...t.platformConfig&&{platformConfig:t.platformConfig},...t.enableFetchProxy&&{enableFetchProxy:t.enableFetchProxy},...window.TSCIRCUIT_USE_RUNFRAME_FOR_CLI&&{disableCdnLoading:!0},...t.tscircuitSessionToken&&{tscircuitSessionToken:t.tscircuitSessionToken},...t.easyEdaProxyConfig&&{easyEdaProxyConfig:t.easyEdaProxyConfig}});globalThis.runFrameWorker=Ie,l(nt),I?.trim()&&Ie.enableDebug(I.replace("DEBUG=","")),py("Starting render..."),t.onRenderStarted?.();const Ze=ie instanceof Map?Object.fromEntries(ie.entries()):ie;let Ke=Date.now();Ie.on("asyncEffect:start",Se=>{const ve=`${Se.phase}|${Se.componentDisplayName??""}|${Se.effectName}`;C(Pe=>({...Pe,[ve]:{...Se,startTime:Date.now()}}))}),Ie.on("asyncEffect:end",Se=>{const ve=`${Se.phase}|${Se.componentDisplayName??""}|${Se.effectName}`;C(Pe=>{const{[ve]:ze,...Xe}=Pe;return Xe})}),Ie.on("autorouting:start",Se=>{G({...H,[Se.componentDisplayName]:{simpleRouteJson:Se.simpleRouteJson,createdAt:Date.now()}})}),Ie.on("solver:started",Se=>{py("solver:started",Se),V(ve=>{const Pe=`${Se.componentName}-${Se.solverName}`;return ve.some(Xe=>`${Xe.componentName}-${Xe.solverName}`===Pe)?ve:[...ve,Se]})}),Ie.on("board:renderPhaseStarted",Se=>{Ge.lastRenderEvent=Se,Ge.eventsProcessed=(Ge.eventsProcessed??0)+1;const ve=C2.indexOf(Se.phase)/JYo*.75+Ge.eventsProcessed/1e3*.25,Pe=1-Math.exp(-ve*3);Ge.progress=Pe,Je||R({...Ge})}),W==="render_log"&&Ie.on("renderable:renderLifecycle:anyEvent",Se=>{Ge.renderEvents=Ge.renderEvents??[],Se.createdAt=Date.now(),Ge.renderEvents.push(Se),Date.now()-Ke>500&&(Ge.phaseTimings=rkt(Ge.renderEvents??[]),Ke=Date.now()),Je||R({...Ge})}),Ie.on("autorouting:progress",Se=>{s(Se.debugGraphics)}),Ie.on("debug:logOutput",Se=>{Ge.debugOutputs=Ge.debugOutputs??[],Ge.debugOutputs.push({type:"debug",name:Se.name,content:Se.content}),Je||R({...Ge})}),py("Executing fsMap...");const Ye=await Ie.executeWithFsMap({entrypoint:t.entrypoint,fsMap:Ze,...t.mainComponentPath?{mainComponentPath:t.mainComponentPath}:{}}).then(()=>({success:!0})).catch(Se=>{const ve=Se.message.replace("Error: ","");return py(`eval error: ${ve}`),t.onError?.(Se),w(E6e({executionError:Se})),i({error:ve,stack:Se.stack}),R(null),console.error(Se),{success:!1}});if(py("worker call started"),!Ye.success){d(!1),C({});return}const qe=Ie.renderUntilSettled();py("waiting for initial circuit json...");let Le=await Ie.getCircuitJson().catch(Se=>(py("error getting initial circuit json",Se),t.onError?.(Se),w(E6e({executionError:Se})),i({error:Se.message,stack:Se.stack}),R(null),d(!1),C({}),null));Le&&(py("got initial circuit json"),n(Le),t.onCircuitJsonChange?.(Le),t.onInitialRender?.({circuitJson:Le}),await qe,py("getting final circuit json"),Le=await Ie.getCircuitJson(),t.onCircuitJsonChange?.(Le),n(Le),w(E6e({circuitJson:Le})),t.onRenderFinished?.({circuitJson:Le}),s({}),W==="render_log"&&(Ge.phaseTimings=rkt(Ge.renderEvents??[])),Ge.progress=1,Je||R({...Ge}),d(!1),C({}),f(""),r.current=null)};u.runWithMutex(pe)},[t.fsMap,t.entrypoint,a,t.evalVersion,t.mainComponentPath,t.isLoadingFiles,I,oe]);const le=j.useRef(null),fe=j.useRef(null),ye=ue=>{if(!ue||ue===null){console.warn("[RunFrame] handleEditEvent received null or undefined event.");return}ue.in_progress?(le.current=ue,fe.current&&(clearTimeout(fe.current),fe.current=null)):(fe.current&&clearTimeout(fe.current),fe.current=setTimeout(()=>{const Be=ue||le.current;t.onEditEvent?.(Be),le.current=null,fe.current=null},100))},be=async(ue,Be)=>{let pe="";const Ge=Array.isArray(e)&&e.find(Ie=>Ie.type==="software_project_metadata"),Je=t.projectUrl??Ge?.project_url;if(Je)try{pe=new URL(Je).pathname}catch{pe=Je}const nt=pe?`${pe} - ${ue}`:ue;await PG.post("autorouting/bug_reports/create",{json:{title:nt,simple_route_json:Be.simpleRouteJson}}).json().then(({autorouting_bug_report:Ie})=>{window.open(`https://api.tscircuit.com/autorouting/bug_reports/view?autorouting_bug_report_id=${Ie.autorouting_bug_report_id}`,"_blank")}).catch(Ie=>{if(console.error("Failed to report autorouting bug",Ie),Ie instanceof cM&&Ie.response?.status===401){t.onLoginRequired?t.onLoginRequired():alert("You must be logged in to report autorouting bugs");return}const Ke=Ie instanceof Error?Ie.message:"Failed to report autorouting bug";alert(`Failed to report autorouting bug: ${Ke}`)})};return t.isLoadingFiles?J.jsx(OYo,{}):J.jsx(gx,{FallbackComponent:LYo,children:J.jsx(VTt,{code:ie.get(t.entrypoint??t.mainComponentPath),fsMap:ie,defaultActiveTab:t.defaultActiveTab??t.defaultTab,defaultTab:t.defaultTab,availableTabs:t.availableTabs,schematicSvgOptions:t.schematicSvgOptions,showToggleFullScreen:t.showToggleFullScreen,autoroutingGraphics:A,autoroutingLog:H,onReportAutoroutingLog:t.onReportAutoroutingLog||be,leftHeaderContent:J.jsxs(J.Fragment,{children:[t.showRunButton&&J.jsx(h6e,{children:J.jsxs(_6e,{children:[J.jsx(m6e,{asChild:!0,children:J.jsxs("div",{className:"rf-relative rf-inline-flex",children:[J.jsxs("button",{type:"button",onClick:()=>{c(1)},className:"rf-flex rf-items-center rf-gap-2 rf-px-4 rf-py-2 rf-bg-blue-600 hover:rf-bg-blue-700 rf-text-white rf-rounded-md disabled:rf-opacity-50 transition-colors duration-200",disabled:h||!_,children:["Run"," ",h||!_?J.jsx(SB,{className:"rf-w-3 rf-h-3 rf-animate-spin"}):J.jsx(FPt,{className:"rf-w-3 rf-h-3"})]}),h&&J.jsx("div",{className:"rf-flex rf-items-center rf-ml-1",children:J.jsx(ta,{onClick:ue=>{ue.stopPropagation(),d(!1),R(null),i(null),r.current&&(r.current(),r.current=null),u.cancel(),C({}),globalThis.runFrameWorker&&(globalThis.runFrameWorker.kill(),globalThis.runFrameWorker=null)},variant:"ghost",size:"icon",className:"rf-text-red-300 hover:rf-text-red-400 hover:!rf-bg-transparent [&>svg]:rf-text-red-300 [&>svg]:hover:rf-text-red-400 rf-flex rf-items-center rf-justify-center",children:J.jsx(HPo,{className:"!rf-h-2.5 !rf-w-2.5",fill:"currentColor",stroke:"currentColor"})})})]})}),J.jsx(qie,{sideOffset:8,className:"rf-p-0 rf-bg-transparent rf-border-none rf-shadow-none rf-pointer-events-none",children:J.jsxs("div",{className:"rf-flex rf-items-center rf-gap-2 rf-px-2.5 rf-py-1.5 rf-bg-slate-900 rf-rounded-md rf-shadow-xl rf-border rf-border-slate-800/60",children:[J.jsx("kbd",{className:"rf-bg-slate-800 rf-px-1.5 rf-py-0.5 rf-rounded rf-text-[10px] rf-font-sans rf-font-medium rf-border rf-border-slate-700 rf-text-slate-200 rf-leading-none",children:"Ctrl"}),J.jsx("span",{className:"rf-text-slate-500 rf-text-[11px] rf-font-medium rf-leading-none",children:"+"}),J.jsx("kbd",{className:"rf-bg-slate-800 rf-px-1.5 rf-py-0.5 rf-rounded rf-text-[10px] rf-font-sans rf-font-medium rf-border rf-border-slate-700 rf-text-slate-200 rf-leading-none",children:"Enter"})]})})]})}),t.showFileMenu!==!1&&J.jsx(cU,{isWebEmbedded:t.isWebEmbedded,onLoginRequired:t.onLoginRequired,showSchematicDebugGrid:y,onChangeShowSchematicDebugGrid:x,showSchematicPorts:B,onChangeShowSchematicPorts:S,autoroutingLog:H,onReportAutoroutingLog:t.onReportAutoroutingLog||be}),t.leftHeaderContent]}),onActiveTabChange:X,circuitJson:e,renderLog:F,activeEffectName:D,isRunningCode:h,errorMessage:o?.error,errorStack:o?.stack,onEditEvent:ye,editEvents:t.editEvents,onPcbBoundsSelected:t.onPcbBoundsSelected,defaultToFullScreen:t.defaultToFullScreen,onRerunWithDebug:ue=>{f(ue||""),c(1)},solverEvents:K,isCli:t.isCli,showSchematicDebugGrid:y,showSchematicPorts:B,onChangeShowSchematicDebugGrid:x,onChangeShowSchematicPorts:S})})},WYo=t=>new Promise(e=>setTimeout(e,t)),jYo=({isOpen:t,onClose:e,onLoginSuccess:n})=>{const[o,i]=j.useState("idle"),[r,A]=j.useState(null),[s,a]=j.useState(null),c=Yu(_=>_.pushEvent),l=j.useRef(null);j.useEffect(()=>()=>{l.current&&l.current.abort()},[]);const g=j.useCallback(async()=>{i("creating"),a(null),l.current=new AbortController;try{const _=lM(),{login_page:p}=await _.post("sessions/login_page/create",{json:{},signal:l.current?.signal}).json();A(p.url),i("waiting");const m=new URL(p.url);for(m.searchParams.set("autoclose","true"),window.open(m.toString(),"_blank");!l.current?.signal.aborted;){const{login_page:I}=await _.post("sessions/login_page/get",{json:{login_page_id:p.login_page_id},headers:{Authorization:`Bearer ${p.login_page_auth_token}`},signal:l.current?.signal}).json();if(I.was_login_successful){i("exchanging");break}if(I.is_expired)throw new Error("Login page expired. Please try again.");await WYo(1e3)}if(l.current?.signal.aborted){i("idle");return}const{session:C}=await _.post("sessions/login_page/exchange_for_cli_session",{json:{login_page_id:p.login_page_id},headers:{Authorization:`Bearer ${p.login_page_auth_token}`},signal:l.current?.signal}).json();typeof window<"u"&&(window.TSCIRCUIT_REGISTRY_TOKEN=C.token),await c({event_type:"TOKEN_UPDATED",registry_token:C.token}),i("success"),zA.success("Successfully logged in!"),n?.(),setTimeout(()=>{e(),i("idle"),A(null)},1e3)}catch(_){if(_ instanceof DOMException&&_.name==="AbortError"){i("idle");return}console.error("Login error:",_);const p=_ instanceof Error?_.message:"Failed to complete login";a(p),i("error"),zA.error(p)}},[c,n,e]),u=j.useCallback(()=>{l.current&&l.current.abort(),i("idle"),A(null),a(null),e()},[e]),h=o==="creating"||o==="waiting"||o==="exchanging",d=()=>{switch(o){case"creating":return"Creating login page...";case"waiting":return"Waiting for you to complete login in the browser...";case"exchanging":return"Generating token...";case"success":return"Successfully logged in!";case"error":return s||"An error occurred";default:return null}};return J.jsx(DT,{open:t,onOpenChange:_=>!_&&!h&&u(),children:J.jsxs(j3,{className:"rf-max-w-md",children:[J.jsxs(X3,{children:[J.jsx($3,{children:"Sign In Required"}),J.jsx(MT,{children:o==="idle"||o==="error"?"Sign in to continue. A new browser window will open for authentication.":"Complete the login process in the opened browser window."})]}),J.jsxs("div",{className:"rf-flex rf-flex-col rf-items-center rf-gap-4 rf-py-4",children:[o==="idle"||o==="error"?J.jsx(ta,{onClick:g,className:"rf-w-full",children:"Sign In"}):J.jsxs("div",{className:"rf-flex rf-flex-col rf-items-center rf-gap-3 rf-w-full",children:[o!=="success"&&J.jsx("div",{className:"rf-animate-spin rf-w-6 rf-h-6 rf-border-2 rf-border-gray-300 rf-border-t-blue-600 rf-rounded-full"}),J.jsx("p",{className:"rf-text-sm rf-text-gray-600 rf-text-center",children:d()}),r&&o==="waiting"&&J.jsx("a",{href:r,target:"_blank",rel:"noreferrer",className:"rf-text-xs rf-text-blue-600 hover:rf-underline",children:"Click here if the window didn't open"})]}),s&&o==="error"&&J.jsx("p",{className:"rf-text-sm rf-text-red-600 rf-text-center",children:s}),h&&J.jsx(ta,{variant:"outline",onClick:u,className:"rf-w-full",children:"Cancel"})]})]})})},XYo=()=>{const[t,e]=j.useState(!1),n=j.useCallback(()=>{e(!0)},[]),o=j.useCallback(()=>{e(!1)},[]),i=j.useCallback(()=>{e(!1)},[]);return{LoginDialog:J.jsx(jYo,{isOpen:t,onClose:o,onLoginSuccess:i}),openLoginDialog:n}},$Yo=t=>{const[e,n]=J7("load-latest-eval",!0),[o]=j.useState(()=>typeof window>"u"?void 0:new URLSearchParams(window.location.hash.slice(1)).get("main_component")??void 0),i=j.useCallback(s=>{if(typeof window>"u")return;const a=new URLSearchParams(window.location.hash.slice(1));if(a.get("main_component")===s)return;a.set("main_component",s);const c=a.toString(),l=`${window.location.pathname}${window.location.search}`+(c.length>0?`#${c}`:"");window.history.replaceState(null,"",l)},[]),{LoginDialog:r,openLoginDialog:A}=XYo();return J.jsxs(J.Fragment,{children:[r,J.jsx(Xkt,{debug:t.debug,forceLatestEvalVersion:!t.workerBlobUrl&&e,defaultToFullScreen:!0,showToggleFullScreen:!1,workerBlobUrl:t.workerBlobUrl,isCli:!0,showFilesSwitch:!0,showFileMenu:!1,enableFetchProxy:t.enableFetchProxy,initialMainComponentPath:o,onLoginRequired:A,onMainComponentPathChange:i,leftHeaderContent:J.jsxs("div",{className:"rf-flex rf-items-center rf-justify-between",children:[J.jsx(cU,{isWebEmbedded:!1,shouldLoadLatestEval:!t.workerBlobUrl&&e,onChangeShouldLoadLatestEval:s=>{n(s),globalThis.runFrameWorker=null},onLoginRequired:A}),t.scenarioSelectorContent]})})]})};Ga("run-frame:ImportComponentDialog");var akt=1,ZYo=.9,ezo=.8,tzo=.17,x6e=.1,B6e=.999,nzo=.9999,ozo=.99,izo=/[\\\/_+.#"@\[\(\{&]/,rzo=/[\\\/_+.#"@\[\(\{&]/g,Azo=/[\s-]/,ckt=/[\s-]/g;function Q6e(t,e,n,o,i,r,A){if(r===e.length)return i===t.length?akt:ozo;var s=`${i},${r}`;if(A[s]!==void 0)return A[s];for(var a=o.charAt(r),c=n.indexOf(a,i),l=0,g,u,h,d;c>=0;)g=Q6e(t,e,n,o,c+1,r+1,A),g>l&&(c===i?g*=akt:izo.test(t.charAt(c-1))?(g*=ezo,h=t.slice(i,c-1).match(rzo),h&&i>0&&(g*=Math.pow(B6e,h.length))):Azo.test(t.charAt(c-1))?(g*=ZYo,d=t.slice(i,c-1).match(ckt),d&&i>0&&(g*=Math.pow(B6e,d.length))):(g*=tzo,i>0&&(g*=Math.pow(B6e,c-i))),t.charAt(c)!==e.charAt(r)&&(g*=nzo)),(g<x6e&&n.charAt(c-1)===o.charAt(r+1)||o.charAt(r+1)===o.charAt(r)&&n.charAt(c-1)!==o.charAt(r))&&(u=Q6e(t,e,n,o,c+1,r+2,A),u*x6e>g&&(g=u*x6e)),g>l&&(l=g),c=n.indexOf(a,c+1);return A[s]=l,l}function lkt(t){return t.toLowerCase().replace(ckt," ")}function szo(t,e,n){return t=n&&n.length>0?`${t+" "+n.join(" ")}`:t,Q6e(t,e,lkt(t),lkt(e),0,0,{})}var uU='[cmdk-group=""]',S6e='[cmdk-group-items=""]',azo='[cmdk-group-heading=""]',gkt='[cmdk-item=""]',ukt=`${gkt}:not([aria-disabled="true"])`,b6e="cmdk-item-select",vT="data-value",czo=(t,e,n)=>szo(t,e,n),dkt=j.createContext(void 0),dU=()=>j.useContext(dkt),hkt=j.createContext(void 0),D6e=()=>j.useContext(hkt),_kt=j.createContext(void 0),mkt=j.forwardRef((t,e)=>{let n=NT(()=>{var oe,ae;return{search:"",value:(ae=(oe=t.value)!=null?oe:t.defaultValue)!=null?ae:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),o=NT(()=>new Set),i=NT(()=>new Map),r=NT(()=>new Map),A=NT(()=>new Set),s=pkt(t),{label:a,children:c,value:l,onValueChange:g,filter:u,shouldFilter:h,loop:d,disablePointerSelection:_=!1,vimBindings:p=!0,...m}=t,C=rp(),I=rp(),f=rp(),y=j.useRef(null),x=fzo();o6(()=>{if(l!==void 0){let oe=l.trim();n.current.value=oe,B.emit()}},[l]),o6(()=>{x(6,H)},[]);let B=j.useMemo(()=>({subscribe:oe=>(A.current.add(oe),()=>A.current.delete(oe)),snapshot:()=>n.current,setState:(oe,ae,re)=>{var le,fe,ye,be;if(!Object.is(n.current[oe],ae)){if(n.current[oe]=ae,oe==="search")R(),w(),x(1,F);else if(oe==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let ue=document.getElementById(f);ue?ue.focus():(le=document.getElementById(C))==null||le.focus()}if(x(7,()=>{var ue;n.current.selectedItemId=(ue=G())==null?void 0:ue.id,B.emit()}),re||x(5,H),((fe=s.current)==null?void 0:fe.value)!==void 0){let ue=ae??"";(be=(ye=s.current).onValueChange)==null||be.call(ye,ue);return}}B.emit()}},emit:()=>{A.current.forEach(oe=>oe())}}),[]),S=j.useMemo(()=>({value:(oe,ae,re)=>{var le;ae!==((le=r.current.get(oe))==null?void 0:le.value)&&(r.current.set(oe,{value:ae,keywords:re}),n.current.filtered.items.set(oe,D(ae,re)),x(2,()=>{w(),B.emit()}))},item:(oe,ae)=>(o.current.add(oe),ae&&(i.current.has(ae)?i.current.get(ae).add(oe):i.current.set(ae,new Set([oe]))),x(3,()=>{R(),w(),n.current.value||F(),B.emit()}),()=>{r.current.delete(oe),o.current.delete(oe),n.current.filtered.items.delete(oe);let re=G();x(4,()=>{R(),re?.getAttribute("id")===oe&&F(),B.emit()})}),group:oe=>(i.current.has(oe)||i.current.set(oe,new Set),()=>{r.current.delete(oe),i.current.delete(oe)}),filter:()=>s.current.shouldFilter,label:a||t["aria-label"],getDisablePointerSelection:()=>s.current.disablePointerSelection,listId:C,inputId:f,labelId:I,listInnerRef:y}),[]);function D(oe,ae){var re,le;let fe=(le=(re=s.current)==null?void 0:re.filter)!=null?le:czo;return oe?fe(oe,n.current.search,ae):0}function w(){if(!n.current.search||s.current.shouldFilter===!1)return;let oe=n.current.filtered.items,ae=[];n.current.filtered.groups.forEach(le=>{let fe=i.current.get(le),ye=0;fe.forEach(be=>{let ue=oe.get(be);ye=Math.max(ue,ye)}),ae.push([le,ye])});let re=y.current;K().sort((le,fe)=>{var ye,be;let ue=le.getAttribute("id"),Be=fe.getAttribute("id");return((ye=oe.get(Be))!=null?ye:0)-((be=oe.get(ue))!=null?be:0)}).forEach(le=>{let fe=le.closest(S6e);fe?fe.appendChild(le.parentElement===fe?le:le.closest(`${S6e} > *`)):re.appendChild(le.parentElement===re?le:le.closest(`${S6e} > *`))}),ae.sort((le,fe)=>fe[1]-le[1]).forEach(le=>{var fe;let ye=(fe=y.current)==null?void 0:fe.querySelector(`${uU}[${vT}="${encodeURIComponent(le[0])}"]`);ye?.parentElement.appendChild(ye)})}function F(){let oe=K().find(re=>re.getAttribute("aria-disabled")!=="true"),ae=oe?.getAttribute(vT);B.setState("value",ae||void 0)}function R(){var oe,ae,re,le;if(!n.current.search||s.current.shouldFilter===!1){n.current.filtered.count=o.current.size;return}n.current.filtered.groups=new Set;let fe=0;for(let ye of o.current){let be=(ae=(oe=r.current.get(ye))==null?void 0:oe.value)!=null?ae:"",ue=(le=(re=r.current.get(ye))==null?void 0:re.keywords)!=null?le:[],Be=D(be,ue);n.current.filtered.items.set(ye,Be),Be>0&&fe++}for(let[ye,be]of i.current)for(let ue of be)if(n.current.filtered.items.get(ue)>0){n.current.filtered.groups.add(ye);break}n.current.filtered.count=fe}function H(){var oe,ae,re;let le=G();le&&(((oe=le.parentElement)==null?void 0:oe.firstChild)===le&&((re=(ae=le.closest(uU))==null?void 0:ae.querySelector(azo))==null||re.scrollIntoView({block:"nearest"})),le.scrollIntoView({block:"nearest"}))}function G(){var oe;return(oe=y.current)==null?void 0:oe.querySelector(`${gkt}[aria-selected="true"]`)}function K(){var oe;return Array.from(((oe=y.current)==null?void 0:oe.querySelectorAll(ukt))||[])}function V(oe){let ae=K()[oe];ae&&B.setState("value",ae.getAttribute(vT))}function W(oe){var ae;let re=G(),le=K(),fe=le.findIndex(be=>be===re),ye=le[fe+oe];(ae=s.current)!=null&&ae.loop&&(ye=fe+oe<0?le[le.length-1]:fe+oe===le.length?le[0]:le[fe+oe]),ye&&B.setState("value",ye.getAttribute(vT))}function X(oe){let ae=G(),re=ae?.closest(uU),le;for(;re&&!le;)re=oe>0?Izo(re,uU):Czo(re,uU),le=re?.querySelector(ukt);le?B.setState("value",le.getAttribute(vT)):W(oe)}let ie=()=>V(K().length-1),se=oe=>{oe.preventDefault(),oe.metaKey?ie():oe.altKey?X(1):W(1)},ee=oe=>{oe.preventDefault(),oe.metaKey?V(0):oe.altKey?X(-1):W(-1)};return j.createElement(Oa.div,{ref:e,tabIndex:-1,...m,"cmdk-root":"",onKeyDown:oe=>{var ae;(ae=m.onKeyDown)==null||ae.call(m,oe);let re=oe.nativeEvent.isComposing||oe.keyCode===229;if(!(oe.defaultPrevented||re))switch(oe.key){case"n":case"j":{p&&oe.ctrlKey&&se(oe);break}case"ArrowDown":{se(oe);break}case"p":case"k":{p&&oe.ctrlKey&&ee(oe);break}case"ArrowUp":{ee(oe);break}case"Home":{oe.preventDefault(),V(0);break}case"End":{oe.preventDefault(),ie();break}case"Enter":{oe.preventDefault();let le=G();if(le){let fe=new Event(b6e);le.dispatchEvent(fe)}}}}},j.createElement("label",{"cmdk-label":"",htmlFor:S.inputId,id:S.labelId,style:Ezo},a),tre(t,oe=>j.createElement(hkt.Provider,{value:B},j.createElement(dkt.Provider,{value:S},oe))))}),lzo=j.forwardRef((t,e)=>{var n,o;let i=rp(),r=j.useRef(null),A=j.useContext(_kt),s=dU(),a=pkt(t),c=(o=(n=a.current)==null?void 0:n.forceMount)!=null?o:A?.forceMount;o6(()=>{if(!c)return s.item(i,A?.id)},[c]);let l=Ikt(i,r,[t.value,t.children,r],t.keywords),g=D6e(),u=_w(x=>x.value&&x.value===l.current),h=_w(x=>c||s.filter()===!1?!0:x.search?x.filtered.items.get(i)>0:!0);j.useEffect(()=>{let x=r.current;if(!(!x||t.disabled))return x.addEventListener(b6e,d),()=>x.removeEventListener(b6e,d)},[h,t.onSelect,t.disabled]);function d(){var x,B;_(),(B=(x=a.current).onSelect)==null||B.call(x,l.current)}function _(){g.setState("value",l.current,!0)}if(!h)return null;let{disabled:p,value:m,onSelect:C,forceMount:I,keywords:f,...y}=t;return j.createElement(Oa.div,{ref:Mv(r,e),...y,id:i,"cmdk-item":"",role:"option","aria-disabled":!!p,"aria-selected":!!u,"data-disabled":!!p,"data-selected":!!u,onPointerMove:p||s.getDisablePointerSelection()?void 0:_,onClick:p?void 0:d},t.children)}),gzo=j.forwardRef((t,e)=>{let{heading:n,children:o,forceMount:i,...r}=t,A=rp(),s=j.useRef(null),a=j.useRef(null),c=rp(),l=dU(),g=_w(h=>i||l.filter()===!1?!0:h.search?h.filtered.groups.has(A):!0);o6(()=>l.group(A),[]),Ikt(A,s,[t.value,t.heading,a]);let u=j.useMemo(()=>({id:A,forceMount:i}),[i]);return j.createElement(Oa.div,{ref:Mv(s,e),...r,"cmdk-group":"",role:"presentation",hidden:g?void 0:!0},n&&j.createElement("div",{ref:a,"cmdk-group-heading":"","aria-hidden":!0,id:c},n),tre(t,h=>j.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?c:void 0},j.createElement(_kt.Provider,{value:u},h))))}),uzo=j.forwardRef((t,e)=>{let{alwaysRender:n,...o}=t,i=j.useRef(null),r=_w(A=>!A.search);return!n&&!r?null:j.createElement(Oa.div,{ref:Mv(i,e),...o,"cmdk-separator":"",role:"separator"})}),dzo=j.forwardRef((t,e)=>{let{onValueChange:n,...o}=t,i=t.value!=null,r=D6e(),A=_w(c=>c.search),s=_w(c=>c.selectedItemId),a=dU();return j.useEffect(()=>{t.value!=null&&r.setState("search",t.value)},[t.value]),j.createElement(Oa.input,{ref:e,...o,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":a.listId,"aria-labelledby":a.labelId,"aria-activedescendant":s,id:a.inputId,type:"text",value:i?t.value:A,onChange:c=>{i||r.setState("search",c.target.value),n?.(c.target.value)}})}),hzo=j.forwardRef((t,e)=>{let{children:n,label:o="Suggestions",...i}=t,r=j.useRef(null),A=j.useRef(null),s=_w(c=>c.selectedItemId),a=dU();return j.useEffect(()=>{if(A.current&&r.current){let c=A.current,l=r.current,g,u=new ResizeObserver(()=>{g=requestAnimationFrame(()=>{let h=c.offsetHeight;l.style.setProperty("--cmdk-list-height",h.toFixed(1)+"px")})});return u.observe(c),()=>{cancelAnimationFrame(g),u.unobserve(c)}}},[]),j.createElement(Oa.div,{ref:Mv(r,e),...i,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":s,"aria-label":o,id:a.listId},tre(t,c=>j.createElement("div",{ref:Mv(A,a.listInnerRef),"cmdk-list-sizer":""},c)))}),_zo=j.forwardRef((t,e)=>{let{open:n,onOpenChange:o,overlayClassName:i,contentClassName:r,container:A,...s}=t;return j.createElement(h3e,{open:n,onOpenChange:o},j.createElement(_3e,{container:A},j.createElement(Eie,{"cmdk-overlay":"",className:i}),j.createElement(xie,{"aria-label":t.label,"cmdk-dialog":"",className:r},j.createElement(mkt,{ref:e,...s}))))}),mzo=j.forwardRef((t,e)=>_w(n=>n.filtered.count===0)?j.createElement(Oa.div,{ref:e,...t,"cmdk-empty":"",role:"presentation"}):null),pzo=j.forwardRef((t,e)=>{let{progress:n,children:o,label:i="Loading...",...r}=t;return j.createElement(Oa.div,{ref:e,...r,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":i},tre(t,A=>j.createElement("div",{"aria-hidden":!0},A)))}),Iy=Object.assign(mkt,{List:hzo,Item:lzo,Input:dzo,Group:gzo,Separator:uzo,Dialog:_zo,Empty:mzo,Loading:pzo});function Izo(t,e){let n=t.nextElementSibling;for(;n;){if(n.matches(e))return n;n=n.nextElementSibling}}function Czo(t,e){let n=t.previousElementSibling;for(;n;){if(n.matches(e))return n;n=n.previousElementSibling}}function pkt(t){let e=j.useRef(t);return o6(()=>{e.current=t}),e}var o6=typeof window>"u"?j.useEffect:j.useLayoutEffect;function NT(t){let e=j.useRef();return e.current===void 0&&(e.current=t()),e}function _w(t){let e=D6e(),n=()=>t(e.snapshot());return j.useSyncExternalStore(e.subscribe,n,n)}function Ikt(t,e,n,o=[]){let i=j.useRef(),r=dU();return o6(()=>{var A;let s=(()=>{var c;for(let l of n){if(typeof l=="string")return l.trim();if(typeof l=="object"&&"current"in l)return l.current?(c=l.current.textContent)==null?void 0:c.trim():i.current}})(),a=o.map(c=>c.trim());r.value(t,s,a),(A=e.current)==null||A.setAttribute(vT,s),i.current=s}),i}var fzo=()=>{let[t,e]=j.useState(),n=NT(()=>new Map);return o6(()=>{n.current.forEach(o=>o()),n.current=new Map},[t]),(o,i)=>{n.current.set(o,i),e({})}};function yzo(t){let e=t.type;return typeof e=="function"?e(t.props):"render"in e?e.render(t.props):t}function tre({asChild:t,children:e},n){return t&&j.isValidElement(e)?j.cloneElement(yzo(e),{ref:e.ref},n(e.props.children)):n(e)}var Ezo={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};const Ckt=j.forwardRef(({className:t,...e},n)=>J.jsx(Iy,{ref:n,className:qi("rf-flex rf-h-full rf-w-full rf-flex-col rf-overflow-hidden rf-rounded-md rf-bg-white rf-text-zinc-950 dark:rf-bg-zinc-950 dark:rf-text-zinc-50",t),...e}));Ckt.displayName=Iy.displayName;const fkt=j.forwardRef(({className:t,...e},n)=>J.jsxs("div",{className:"rf-flex rf-items-center rf-border-b rf-px-3","cmdk-input-wrapper":"",children:[J.jsx(Wwe,{className:"rf-mr-2 rf-h-4 rf-w-4 rf-shrink-0 rf-opacity-50"}),J.jsx(Iy.Input,{ref:n,className:qi("rf-flex rf-h-10 rf-w-full rf-rounded-md rf-bg-transparent rf-py-3 rf-text-sm rf-outline-none placeholder:rf-text-zinc-500 disabled:rf-cursor-not-allowed disabled:rf-opacity-50 dark:placeholder:rf-text-zinc-400",t),...e})]}));fkt.displayName=Iy.Input.displayName;const ykt=j.forwardRef(({className:t,...e},n)=>J.jsx(Iy.List,{ref:n,className:qi("rf-max-h-[300px] rf-overflow-y-auto rf-overflow-x-hidden rf-py-1",t),...e}));ykt.displayName=Iy.List.displayName;const M6e=j.forwardRef((t,e)=>J.jsx(Iy.Empty,{ref:e,className:"rf-py-6 rf-text-center rf-text-sm",...t}));M6e.displayName=Iy.Empty.displayName;const hU=j.forwardRef(({className:t,...e},n)=>J.jsx(Iy.Group,{ref:n,className:qi("rf-overflow-hidden rf-px-1 rf-py-0 rf-text-zinc-950 [&_[cmdk-group-heading]]:rf-px-2 [&_[cmdk-group-heading]]:rf-py-1.5 [&_[cmdk-group-heading]]:rf-text-xs [&_[cmdk-group-heading]]:rf-font-medium [&_[cmdk-group-heading]]:rf-text-zinc-500 dark:rf-text-zinc-50 dark:[&_[cmdk-group-heading]]:rf-text-zinc-400",t),...e}));hU.displayName=Iy.Group.displayName;const xzo=j.forwardRef(({className:t,...e},n)=>J.jsx(Iy.Separator,{ref:n,className:qi("rf--mx-1 rf-h-px rf-bg-zinc-200 dark:rf-bg-zinc-800",t),...e}));xzo.displayName=Iy.Separator.displayName;const _U=j.forwardRef(({className:t,...e},n)=>J.jsx(Iy.Item,{ref:n,className:qi("rf-relative rf-flex rf-cursor-default rf-gap-2 rf-select-none rf-items-center rf-rounded-sm rf-px-2 rf-py-1.5 rf-text-sm rf-outline-none data-[disabled=true]:rf-pointer-events-none data-[selected=true]:rf-bg-zinc-100 data-[selected=true]:rf-text-zinc-900 data-[disabled=true]:rf-opacity-50 [&_svg]:rf-pointer-events-none [&_svg]:rf-size-4 [&_svg]:rf-shrink-0 dark:data-[selected=true]:rf-bg-zinc-800 dark:data-[selected=true]:rf-text-zinc-50",t),...e}));_U.displayName=Iy.Item.displayName;var Bzo=Object.defineProperty,mw=(t,e)=>Bzo(t,"name",{value:e,configurable:!0}),w6e="Popover",[Ekt,Ujo]=y2(w6e,[cT]),P6e=cT(),[Qzo,RT]=Ekt(w6e),Szo=mw(t=>{const{__scopePopover:e,children:n,open:o,defaultOpen:i,onOpenChange:r,modal:A=!1}=t,s=P6e(e),a=j.useRef(null),[c,l]=j.useState(!1),[g,u]=Ub({prop:o,defaultProp:i??!1,onChange:r,caller:w6e});return J.jsx(_oe,{...s,children:J.jsx(Qzo,{scope:e,contentId:rp(),triggerRef:a,open:g,onOpenChange:u,onOpenToggle:j.useCallback(()=>u(h=>!h),[u]),hasCustomAnchor:c,onCustomAnchorAdd:j.useCallback(()=>l(!0),[]),onCustomAnchorRemove:j.useCallback(()=>l(!1),[]),modal:A,children:n})})},"Popover"),bzo="PopoverTrigger",Dzo=j.forwardRef(mw(function(e,n){const{__scopePopover:o,...i}=e,r=RT(bzo,o),A=P6e(o),s=dl(n,r.triggerRef),a=J.jsx(Oa.button,{type:"button","aria-haspopup":"dialog","aria-expanded":r.open,"aria-controls":r.open?r.contentId:void 0,"data-state":v6e(r.open),...i,ref:s,onClick:Pr(e.onClick,r.onOpenToggle)});return r.hasCustomAnchor?a:J.jsx(CPe,{asChild:!0,...A,children:a})},"PopoverTrigger")),xkt="PopoverPortal",[Mzo,wzo]=Ekt(xkt,{forceMount:void 0}),Pzo=mw(t=>{const{__scopePopover:e,forceMount:n,children:o,container:i}=t,r=RT(xkt,e);return J.jsx(Mzo,{scope:e,forceMount:n,children:J.jsx(JE,{present:n||r.open,children:J.jsx(yPe,{asChild:!0,container:i,children:o})})})},"PopoverPortal"),mU="PopoverContent",vzo=j.forwardRef(mw(function(e,n){const o=wzo(mU,e.__scopePopover),{forceMount:i=o.forceMount,...r}=e,A=RT(mU,e.__scopePopover);return J.jsx(JE,{present:i||A.open,children:A.modal?J.jsx(Rzo,{...r,ref:n}):J.jsx(Tzo,{...r,ref:n})})},"PopoverContent")),Nzo=JQ("PopoverContent.RemoveScroll"),Rzo=j.forwardRef(mw(function(e,n){const o=RT(mU,e.__scopePopover),i=j.useRef(null),r=dl(n,i),A=j.useRef(!1);return j.useEffect(()=>{const s=i.current;if(s)return xPe(s)},[]),J.jsx(xoe,{as:Nzo,allowPinchZoom:!0,children:J.jsx(Bkt,{...e,ref:r,trapFocus:o.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Pr(e.onCloseAutoFocus,s=>{s.preventDefault(),A.current||o.triggerRef.current?.focus()}),onPointerDownOutside:Pr(e.onPointerDownOutside,s=>{const a=s.detail.originalEvent,c=a.button===0&&a.ctrlKey===!0,l=a.button===2||c;A.current=l},{checkForDefaultPrevented:!1}),onFocusOutside:Pr(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1})})})},"PopoverContentModal")),Tzo=j.forwardRef(mw(function(e,n){const o=RT(mU,e.__scopePopover),i=j.useRef(!1),r=j.useRef(!1);return J.jsx(Bkt,{...e,ref:n,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:A=>{e.onCloseAutoFocus?.(A),A.defaultPrevented||(i.current||o.triggerRef.current?.focus(),A.preventDefault()),i.current=!1,r.current=!1},onInteractOutside:A=>{e.onInteractOutside?.(A),A.defaultPrevented||(i.current=!0,A.detail.originalEvent.type==="pointerdown"&&(r.current=!0));const s=A.target;o.triggerRef.current?.contains(s)&&A.preventDefault(),A.detail.originalEvent.type==="focusin"&&r.current&&A.preventDefault()}})},"PopoverContentNonModal")),Bkt=j.forwardRef(mw(function(e,n){const{__scopePopover:o,trapFocus:i,onOpenAutoFocus:r,onCloseAutoFocus:A,disableOutsidePointerEvents:s,onEscapeKeyDown:a,onPointerDownOutside:c,onFocusOutside:l,onInteractOutside:g,...u}=e,h=RT(mU,o),d=P6e(o);return QK(),J.jsx(oPe,{asChild:!0,loop:!0,trapped:i,onMountAutoFocus:r,onUnmountAutoFocus:A,children:J.jsx(toe,{asChild:!0,disableOutsidePointerEvents:s,onInteractOutside:g,onEscapeKeyDown:a,onPointerDownOutside:c,onFocusOutside:l,onDismiss:()=>h.onOpenChange(!1),deferPointerDownOutside:!0,children:J.jsx(fPe,{"data-state":v6e(h.open),role:"dialog",id:h.contentId,...d,...u,ref:n,style:{...u.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})},"PopoverContentImpl"));function v6e(t){return t?"open":"closed"}mw(v6e,"getState");var kzo=Szo,Fzo=Dzo,Lzo=Pzo,Qkt=vzo;const Hzo=kzo,Gzo=Fzo,Skt=j.forwardRef(({className:t,align:e="center",sideOffset:n=4,...o},i)=>J.jsx(Lzo,{children:J.jsx(Qkt,{ref:i,align:e,sideOffset:n,className:qi("rf-z-50 rf-w-72 rf-rounded-md rf-border rf-border-zinc-200 rf-bg-white rf-p-4 rf-text-zinc-950 rf-shadow-md rf-outline-none data-[state=open]:rf-animate-in data-[state=closed]:rf-animate-out data-[state=closed]:rf-fade-out-0 data-[state=open]:rf-fade-in-0 data-[state=closed]:rf-zoom-out-95 data-[state=open]:rf-zoom-in-95 data-[side=bottom]:rf-slide-in-from-top-2 data-[side=left]:rf-slide-in-from-right-2 data-[side=right]:rf-slide-in-from-left-2 data-[side=top]:rf-slide-in-from-bottom-2 rf-origin-[--radix-popover-content-transform-origin] dark:rf-border-zinc-800 dark:rf-bg-zinc-950 dark:rf-text-zinc-50",t),...o})}));Skt.displayName=Qkt.displayName;function bkt(t,e){const n=t.lastIndexOf("."),o=e.lastIndexOf("."),i=n>0?t.substring(0,n):t,r=o>0?e.substring(0,o):e;if(i!==r&&t.substring(n)===e.substring(o)){if(i.startsWith(r))return 1;if(r.startsWith(i))return-1}return t.localeCompare(e,void 0,{numeric:!0,sensitivity:"base"})}function Ozo(t){const e=[],n=new Map;n.set("",{name:"",path:"",type:"folder",children:e});for(const o of t){const i=o.split("/");let r="";for(let A=0;A<i.length;A++){const s=i[A],a=r;if(r=r?`${r}/${s}`:s,!n.has(r)){const c=A===i.length-1,l={name:s,path:r,type:c?"file":"folder",children:c?void 0:[]};n.set(r,l);const g=n.get(a);g&&g.children&&g.children.push(l)}}}return e}function Dkt(t,e){for(const n of t){if(n.path===e)return n;if(n.children){const o=Dkt(n.children,e);if(o)return o}}return null}function Kzo(t,e){let n;if(e?n=Dkt(t,e):n={name:"",path:"",type:"folder",children:t},!n||!n.children)return{files:[],folders:[]};const o=n.children.filter(r=>r.type==="file"),i=n.children.filter(r=>r.type==="folder");return o.sort((r,A)=>bkt(r.name,A.name)),i.sort((r,A)=>bkt(r.name,A.name)),{files:o,folders:i}}const Uzo=t=>{const e=t.split("/").pop()||"";return e.endsWith(".py.tsx")?e.slice(0,-4):e};function N6e(t){const e=t.lastIndexOf("/");return e===-1?"/":t.substring(0,e)}function Yzo({currentFile:t,files:e}){const[n,o]=j.useState(!1),[i,r]=j.useState(()=>{if(typeof window<"u"){const a=new URLSearchParams(window.location.search),c=new URLSearchParams(window.location.hash.slice(1)),l=a.get("file")??c.get("file");if(l&&e.includes(l)){const g=N6e(l);return g==="/"?null:g}}if(t&&e.includes(t)){const a=N6e(t);return a==="/"?null:a}return null});return j.useEffect(()=>{if(t&&!n&&e.includes(t)){const a=N6e(t);r(a==="/"?null:a)}},[t,n,e]),{currentFolder:i,navigateToFolder:a=>{r(a),o(!0)},resetManualNavigation:()=>{o(!1)}}}const R6e=t=>t.endsWith(".tsx")||t.endsWith(".jsx")?J.jsx(BPo,{className:"rf-h-4 rf-w-4 rf-text-blue-500"}):t.endsWith(".md")||t.endsWith(".txt")?J.jsx(bPo,{className:"rf-h-4 rf-w-4 rf-text-gray-600"}):J.jsx(DPo,{className:"rf-h-4 rf-w-4 rf-text-gray-500"}),zzo=t=>t.endsWith(".tsx")||ere(t)||t.endsWith(".jsx"),Vzo=t=>Uzo(t),Mkt=t=>t.substring(0,t.lastIndexOf("/"))||"/",wkt=({files:t,onFileChange:e,currentFile:n,fileFilter:o=zzo,getDisplayName:i=Vzo,placeholder:r="Select file",searchPlaceholder:A="Search for file",emptyMessage:s="No files found in this directory.",pinnedFiles:a=[],onToggleFavorite:c,recentlySavedFiles:l=[]})=>{const[g,u]=j.useState(!1),[h,d]=j.useState(n),{currentFolder:_,navigateToFolder:p,resetManualNavigation:m}=Yzo({currentFile:h,files:t}),[C,I]=j.useState(0),[f,y]=j.useState(""),[x,B]=J7("runframe:recentlyViewed",[]),[S,D]=J7("runframe:showRecents",!1);j.useEffect(()=>{const re=le=>{(le.metaKey||le.ctrlKey)&&le.key==="k"&&(le.preventDefault(),u(fe=>!fe))};return window.addEventListener("keydown",re),()=>window.removeEventListener("keydown",re)},[]);const w=t.filter(o),F=j.useRef(null);j.useEffect(()=>{const re=()=>{F.current&&(clearTimeout(F.current),F.current=null)};return d(n),n&&w.includes(n)&&(re(),F.current=setTimeout(()=>{B(le=>{if(le[0]===n)return le;const fe=le.filter(ye=>ye!==n);return[n,...fe].slice(0,10)})},500)),re},[n,w,B]);const R=Ozo(w),{files:H,folders:G}=Kzo(R,_||""),V=(()=>{if(!f.trim())return{currentDirResults:[],globalResults:[]};const re=f.toLowerCase(),fe=w.map(ue=>{const Be=ue.split("/").pop()||"";return{path:ue,fileName:Be}}).filter(ue=>ue.fileName.toLowerCase().includes(re)||ue.path.toLowerCase().includes(re)),ye=fe.filter(ue=>_?ue.path.substring(0,ue.path.lastIndexOf("/"))===_:!ue.path.includes("/")),be=fe.filter(ue=>_?ue.path.substring(0,ue.path.lastIndexOf("/"))!==_:ue.path.includes("/"));return{currentDirResults:ye,globalResults:be}})(),W=f.trim().length>0,X=re=>{p(re),I(0)},ie=j.useCallback(()=>{if(!_)return;const re=_.lastIndexOf("/"),le=re===-1?null:_.substring(0,re);X(le)},[_,X]);j.useEffect(()=>{if(!g)return;const re=le=>{(le.metaKey||le.ctrlKey)&&le.key==="ArrowUp"&&(le.preventDefault(),ie())};return window.addEventListener("keydown",re),()=>window.removeEventListener("keydown",re)},[g,ie]);const se=j.useCallback((re,le,fe=!1)=>{if(d(re),I(le),u(!1),e(re),fe){const ye=re.lastIndexOf("/"),be=ye===-1?null:re.substring(0,ye);X(be)}},[e,X]);j.useEffect(()=>{const re=le=>{if((le.metaKey||le.ctrlKey)&&(le.key==="ArrowLeft"||le.key==="ArrowRight")){if(le.preventDefault(),!n||H.length===0)return;const fe=H.findIndex(ue=>ue.path===n);if(fe===-1)return;let ye;le.key==="ArrowLeft"?ye=fe===0?H.length-1:fe-1:ye=fe===H.length-1?0:fe+1;const be=H[ye];be&&se(be.path,ye)}};return window.addEventListener("keydown",re),()=>window.removeEventListener("keydown",re)},[n,H,se]),j.useEffect(()=>{if(H.length>0){const re=H.findIndex(le=>le.path===n);re>=0&&I(re)}},[H,n]);const ee=j.useMemo(()=>{const re=l.filter(ye=>w.includes(ye)),le=x.filter(ye=>w.includes(ye)),fe=[];re.length>0&&fe.push({path:re[0],type:"saved"});for(const ye of le){if(fe.length>=3)break;fe.some(be=>be.path===ye)||fe.push({path:ye,type:"viewed"})}return fe},[l,x,w]),oe=_??"/";oe.length>25&&""+oe.slice(-22);const ae=()=>`rf-w-full rf-min-w-[600px] ${W?"rf-max-w-[600px]":"rf-max-w-[1000px]"}`;return J.jsx("div",{className:"rf-flex rf-items-center rf-gap-1",children:J.jsxs(Hzo,{open:g,onOpenChange:re=>{u(re),re||(y(""),m())},children:[J.jsx(Gzo,{asChild:!0,children:J.jsxs(ta,{variant:"outline",role:"combobox","aria-expanded":g,className:"rf-w-fit rf-min-w-32 rf-max-w-100 rf-justify-center rf-items-center rf-gap-1 !rf-font-normal",children:[J.jsx("span",{className:"rf-truncate rf-text-left",children:h?i(h):r}),J.jsx(CPo,{className:"rf-opacity-50 rf-flex-shrink-0"})]})}),J.jsx(Skt,{className:qi("!rf-p-0 !rf-overflow-y-auto !rf-max-h-[80vh] !rf-z-[200]",ae()),children:J.jsxs(Ckt,{shouldFilter:!1,children:[J.jsx(fkt,{placeholder:A,className:"rf-h-9 rf-w-full",value:f,onValueChange:y}),ee.length>0&&J.jsxs("div",{className:"rf-border-b rf-border-gray-200",children:[J.jsxs("button",{onClick:()=>D(!S),className:"rf-w-full rf-px-3 rf-py-2 rf-flex rf-items-center rf-justify-between rf-text-xs rf-text-slate-600 hover:rf-bg-slate-50 rf-bg-transparent rf-border-none rf-cursor-pointer",children:[J.jsx("span",{className:"rf-font-medium",children:"Recent Files"}),J.jsx(Jwe,{className:qi("rf-h-4 rf-w-4 rf-transition-transform",!S&&"-rf-rotate-90")})]}),S&&J.jsx("div",{className:"rf-pb-1",children:ee.map((re,le)=>J.jsxs("div",{onClick:()=>se(re.path,le,!0),className:qi("rf-flex rf-items-center rf-px-3 rf-py-1.5 rf-cursor-pointer hover:rf-bg-slate-100",re.path===n&&"rf-font-medium"),children:[re.type==="saved"?J.jsx("span",{title:"Recently saved",children:J.jsx(LPo,{className:"rf-mr-2 rf-h-4 rf-w-4 rf-text-green-500"})}):J.jsx("span",{title:"Recently viewed",children:J.jsx(xPo,{className:"rf-mr-2 rf-h-4 rf-w-4 rf-text-blue-500"})}),J.jsx("span",{className:"rf-text-sm",children:i(re.path.split("/").pop()||"")}),J.jsx("span",{className:"rf-text-xs rf-text-muted-foreground rf-ml-2 rf-truncate rf-max-w-[40%]",children:Mkt(re.path)}),J.jsx(L3,{className:qi("rf-ml-auto rf-h-4 rf-w-4",re.path===n?"rf-opacity-100":"rf-opacity-0")})]},re.path))})]}),J.jsxs("div",{className:"rf-px-3 rf-py-2 rf-bg-slate-50 rf-flex rf-items-center rf-justify-between rf-gap-2",children:[J.jsx("div",{className:"rf-flex rf-items-center rf-text-xs rf-text-slate-600 rf-min-w-0 rf-flex-1",children:J.jsxs("div",{className:"rf-flex rf-items-center rf-min-w-0",children:[J.jsx("button",{onClick:()=>X(null),className:"rf-text-blue-600 hover:rf-text-blue-800 rf-underline rf-cursor-pointer rf-bg-transparent rf-border-none rf-p-0 rf-flex-shrink-0",children:"root"}),_?.split("/").filter(Boolean).map((re,le,fe)=>{const ye=fe.slice(0,le+1).join("/");return J.jsxs("span",{className:"rf-flex rf-items-center rf-min-w-0",children:[J.jsx("span",{className:"rf-mx-1 rf-flex-shrink-0",children:"/"}),le===fe.length-1?J.jsx("span",{className:"rf-text-slate-800 rf-truncate rf-max-w-[200px]",title:re,children:re}):J.jsx("button",{onClick:()=>X(ye),className:"rf-text-blue-600 hover:rf-text-blue-800 rf-underline rf-cursor-pointer rf-bg-transparent rf-border-none rf-p-0 rf-truncate rf-max-w-[150px]",title:re,children:re})]},ye)})]})}),J.jsx("div",{className:"rf-flex rf-items-center rf-gap-2 rf-flex-shrink-0",children:_&&J.jsxs("button",{onClick:ie,className:"rf-flex rf-items-center rf-gap-1 rf-text-slate-600 hover:rf-text-slate-800 rf-bg-transparent rf-border-none rf-p-1 rf-rounded hover:rf-bg-slate-200 rf-transition-colors",title:"Go up one level",children:[J.jsx(pPo,{className:"rf-h-3 rf-w-3"}),J.jsx("span",{className:"rf-text-xs rf-font-medium",children:"Up"})]})})]}),J.jsx(ykt,{className:"rf-overflow-visible rf-max-h-none",children:W?J.jsx(J.Fragment,{children:V.currentDirResults.length===0&&V.globalResults.length===0?J.jsxs(M6e,{children:['No files found matching "',f,'".']}):J.jsxs(J.Fragment,{children:[V.currentDirResults.length>0&&J.jsx(hU,{children:V.currentDirResults.map((re,le)=>J.jsxs(_U,{value:`search-current:${re.path}`,onSelect:()=>{d(re.path),u(!1),e(re.path)},className:qi(re.path===n&&"rf-font-medium","rf-group"),children:[J.jsx("span",{className:"rf-mr-2",children:R6e(re.fileName)}),J.jsxs("div",{className:"rf-flex rf-items-center rf-w-full rf-min-w-0",children:[J.jsx("span",{className:"rf-truncate rf-flex-1",children:i(re.fileName)}),J.jsx("span",{className:"rf-text-xs rf-text-muted-foreground rf-ml-2 rf-truncate rf-max-w-[40%]",children:_||"/"}),re.path===n&&J.jsx(L3,{className:"rf-ml-2 rf-h-4 rf-w-4 rf-flex-shrink-0"})]})]},re.path))}),V.globalResults.length>0&&J.jsx(hU,{children:V.globalResults.map(re=>J.jsxs(_U,{value:`search-global:${re.path}`,onSelect:()=>{d(re.path),u(!1),e(re.path)},className:qi(re.path===n&&"rf-font-medium","rf-group"),children:[J.jsx("span",{className:"rf-mr-2",children:R6e(re.fileName)}),J.jsxs("div",{className:"rf-flex rf-items-center rf-w-full rf-min-w-0",children:[J.jsx("span",{className:"rf-truncate rf-flex-1",children:i(re.fileName)}),J.jsx("span",{className:"rf-text-xs rf-text-muted-foreground rf-ml-2 rf-truncate rf-max-w-[40%]",children:Mkt(re.path)}),re.path===n&&J.jsx(L3,{className:"rf-ml-2 rf-h-4 rf-w-4 rf-flex-shrink-0"})]})]},re.path))})]})}):J.jsxs(J.Fragment,{children:[J.jsx(M6e,{children:s}),H.length>0&&J.jsx(hU,{children:H.map((re,le)=>J.jsxs(_U,{value:`current:${re.path}`,onSelect:()=>se(re.path,le),className:qi(re.path===n&&"rf-font-medium","rf-group"),children:[J.jsx("span",{className:"rf-mr-2",children:R6e(re.name)}),i(re.name),J.jsx("div",{className:"rf-ml-auto rf-flex rf-items-center rf-gap-1",children:J.jsx(L3,{className:qi("rf-h-4 rf-w-4",re.path===n?"rf-opacity-100":"rf-opacity-0")})})]},re.path))}),G.length>0&&J.jsx(hU,{children:G.map(re=>J.jsxs(_U,{value:`folder-${re.path}`,onSelect:()=>X(re.path),className:"rf-text-slate-600 hover:rf-text-slate-900",children:[J.jsx(MPo,{className:"rf-mr-2 rf-h-4 rf-w-4 rf-text-blue-600"}),re.name,J.jsx(iT,{className:"rf-ml-auto rf-h-4 rf-w-4"})]},re.path))}),H.length===0&&G.length===0&&J.jsx("div",{className:"rf-p-4 rf-text-center rf-text-slate-500 rf-text-sm",children:"No files or folders in this directory"})]})})]})})]})})},Pkt=({files:t,onFileChange:e,currentFile:n})=>J.jsx(wkt,{files:t,onFileChange:e,currentFile:n,fileFilter:()=>!0,placeholder:"Select circuit",searchPlaceholder:"Search for circuit file",emptyMessage:"No circuit files found in this directory."}),Jzo=({hash:t,initialCircuitPath:e})=>{const n=new URLSearchParams(t.startsWith("#")?t.slice(1):t);return n.get("file")??n.get("main_component")??e??""},qzo=({hash:t,filePath:e})=>{const n=new URLSearchParams(t.startsWith("#")?t.slice(1):t);if(n.get("file")===e&&(!n.has("main_component")||n.get("main_component")===e))return t.startsWith("#")?t:t?`#${t}`:"";n.set("file",e),n.has("main_component")&&n.set("main_component",e);const o=n.toString();return o?`#${o}`:""},Wzo=t=>{const[e,n]=j.useState(()=>typeof window>"u"?t??"":Jzo({hash:window.location.hash,initialCircuitPath:t})),o=j.useCallback(i=>{if(typeof window>"u")return;const r=qzo({hash:window.location.hash,filePath:i});if(r===window.location.hash)return;const A=`${window.location.pathname}${window.location.search}${r}`;window.history.replaceState(null,"",A)},[]);return{currentCircuitJsonPath:e,setCurrentCircuitJsonPath:n,updateFileHash:o}},jzo=t=>t instanceof Error?t.message:"An unknown error occurred",Xzo=t=>{fie();const{currentCircuitJsonPath:e,setCurrentCircuitJsonPath:n,updateFileHash:o}=Wzo(t.initialCircuitPath),[i,r]=j.useState(null),[A,s]=j.useState(!1),[a,c]=j.useState({}),[l,g]=j.useState(new Set),[u,h]=j.useState(new Set),d=t.files,_=d.map(y=>y.filePath),p=j.useCallback(async y=>{if(!y.fileStaticAssetUrl)throw new Error(`No fileStaticAssetUrl provided for ${y.filePath}`);const x=await fetch(y.fileStaticAssetUrl);if(!x.ok)throw new Error(`Failed to fetch ${y.filePath}: ${x.statusText}`);return await x.json()},[]),m=j.useCallback(async y=>{if(a[y]){r(a[y]),o(y),t.onCircuitJsonPathChange?.(y);return}if(u.has(y)){console.warn(`Skipping failed file: ${y}`),r(null);return}if(!l.has(y)){g(x=>new Set(x).add(y)),s(!0),r(null);try{const x=d.find(D=>D.filePath===y);if(!x)throw new Error(`File reference not found for ${y}`);const S=await(t.onFetchFile||p)(x);c(D=>({...D,[y]:S})),r(S),o(y),t.onCircuitJsonPathChange?.(y),h(D=>{const w=new Set(D);return w.delete(y),w})}catch(x){console.error(`Failed to load circuit JSON file ${y}:`,x),h(B=>new Set(B).add(y)),r(null)}finally{g(x=>{const B=new Set(x);return B.delete(y),B}),s(!1)}}},[d,a,l,u,t.onFetchFile,t.onCircuitJsonPathChange,p,o]);j.useEffect(()=>{if(_.length===0)return;let y=e;(!y||!_.includes(y))&&(y=jkt(_)??_[0],n(y)),y&&_.includes(y)&&m(y)},[e]);const C=j.useCallback(y=>{n(y)},[]),I=j.useCallback(y=>{h(x=>{const B=new Set(x);return B.delete(y),B}),m(y)},[m]);if(_.length===0)return J.jsx("div",{className:"rf-flex rf-flex-col rf-w-full rf-h-full rf-items-center rf-justify-center",children:J.jsxs("div",{className:"rf-text-center rf-p-8",children:[J.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-gray-800 rf-mb-2",children:"No Circuit JSON Files Found"}),J.jsx("p",{className:"rf-text-sm rf-text-gray-600",children:"Please provide circuit JSON files to view."})]})});const f=u.has(e);return J.jsx(gx,{fallbackRender:({error:y})=>J.jsx("div",{className:"rf-mt-4 rf-mx-4 rf-bg-red-50 rf-rounded-md rf-border rf-border-red-200",children:J.jsxs("div",{className:"rf-p-4",children:[J.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-red-800 rf-mb-3",children:"Error loading Circuit JSON Preview"}),J.jsx("p",{className:"rf-text-xs rf-font-mono rf-whitespace-pre-wrap rf-text-red-600 rf-mt-2",children:jzo(y)})]})}),children:f?J.jsxs("div",{className:"rf-w-full rf-h-full rf-flex rf-flex-col",children:[J.jsxs("div",{className:"rf-flex rf-items-center rf-justify-between rf-w-full rf-p-4 rf-border-b rf-border-gray-200",children:[(t.showFileMenu??!0)&&J.jsx(cU,{isWebEmbedded:!0,circuitJson:null,projectName:t.projectName}),_.length>1&&J.jsx("div",{className:"rf-absolute rf-left-1/2 rf-transform rf--translate-x-1/2 rf-flex rf-items-center rf-gap-2",children:J.jsx(Pkt,{currentFile:e,files:_,onFileChange:C})})]}),J.jsx("div",{className:"rf-flex-1 rf-flex rf-items-center rf-justify-center",children:J.jsxs("div",{className:"rf-text-center rf-p-8",children:[J.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-red-600 rf-mb-2",children:"Failed to Load Circuit File"}),J.jsxs("p",{className:"rf-text-sm rf-text-gray-600 rf-mb-4",children:["Could not load: ",e]}),J.jsxs("div",{className:"rf-flex rf-flex-col rf-items-center rf-gap-2",children:[J.jsx("button",{onClick:()=>I(e),className:"rf-px-4 rf-py-2 rf-bg-blue-500 rf-text-white rf-rounded rf-hover:bg-blue-600",children:"Retry"}),_.length>1&&J.jsx("p",{className:"rf-text-xs rf-text-gray-500",children:"Or select a different file from the dropdown above"})]})]})})]}):J.jsx(VTt,{circuitJson:i,defaultToFullScreen:t.defaultToFullScreen,showToggleFullScreen:t.showToggleFullScreen,showFileMenu:!1,isWebEmbedded:!1,projectName:t.projectName,defaultActiveTab:t.tabSelected,leftHeaderContent:J.jsxs("div",{className:"rf-flex rf-items-center rf-justify-between rf-w-full",children:[(t.showFileMenu??!0)&&J.jsx(cU,{isWebEmbedded:!0,circuitJson:i,projectName:t.projectName}),_.length>1&&J.jsx("div",{className:`rf-absolute rf-left-1/2 rf-transform rf--translate-x-1/2 rf-flex rf-items-center rf-gap-2 ${A?"rf-opacity-50":""}`,children:J.jsx(Pkt,{currentFile:e,files:_,onFileChange:C})})]})})})},$zo=()=>{const t=Yu(e=>e.fsMap);j.useEffect(()=>{if(!document||!t)return;const e=Array.from(t.keys()),n=jkt(e),o=t.get("package.json");try{if(o){const i=JSON.parse(o);if(i?.name){document.title=i.name;return}}}catch{}n&&(document.title=n)},[t])},vkt=(t,e,n)=>{const o=t instanceof RegExp?Nkt(t,n):t,i=e instanceof RegExp?Nkt(e,n):e,r=o!==null&&i!=null&&Zzo(o,i,n);return r&&{start:r[0],end:r[1],pre:n.slice(0,r[0]),body:n.slice(r[0]+o.length,r[1]),post:n.slice(r[1]+i.length)}},Nkt=(t,e)=>{const n=e.match(t);return n?n[0]:null},Zzo=(t,e,n)=>{let o,i,r,A,s,a=n.indexOf(t),c=n.indexOf(e,a+1),l=a;if(a>=0&&c>0){if(t===e)return[a,c];for(o=[],r=n.length;l>=0&&!s;){if(l===a)o.push(l),a=n.indexOf(t,l+1);else if(o.length===1){const g=o.pop();g!==void 0&&(s=[g,c])}else i=o.pop(),i!==void 0&&i<r&&(r=i,A=c),c=n.indexOf(e,l+1);l=a<c&&a>=0?a:c}o.length&&A!==void 0&&(s=[r,A])}return s},Rkt="\0SLASH"+Math.random()+"\0",Tkt="\0OPEN"+Math.random()+"\0",T6e="\0CLOSE"+Math.random()+"\0",kkt="\0COMMA"+Math.random()+"\0",Fkt="\0PERIOD"+Math.random()+"\0",eVo=new RegExp(Rkt,"g"),tVo=new RegExp(Tkt,"g"),nVo=new RegExp(T6e,"g"),oVo=new RegExp(kkt,"g"),iVo=new RegExp(Fkt,"g"),rVo=/\\\\/g,AVo=/\\{/g,sVo=/\\}/g,aVo=/\\,/g,cVo=/\\\./g,lVo=1e5,gVo=4e6;function k6e(t){return isNaN(t)?t.charCodeAt(0):parseInt(t,10)}function uVo(t){return t.replace(rVo,Rkt).replace(AVo,Tkt).replace(sVo,T6e).replace(aVo,kkt).replace(cVo,Fkt)}function dVo(t){return t.replace(eVo,"\\").replace(tVo,"{").replace(nVo,"}").replace(oVo,",").replace(iVo,".")}function Lkt(t){if(!t)return[""];const e=[],n=vkt("{","}",t);if(!n)return t.split(",");const{pre:o,body:i,post:r}=n,A=o.split(",");A[A.length-1]+="{"+i+"}";const s=Lkt(r);return r.length&&(A[A.length-1]+=s.shift(),A.push.apply(A,s)),e.push.apply(e,A),e}function hVo(t,e={}){if(!t)return[];const{max:n=lVo,maxLength:o=gVo}=e;return t.slice(0,2)==="{}"&&(t="\\{\\}"+t.slice(2)),F6e(uVo(t),n,o,!0).map(dVo)}function _Vo(t){return"{"+t+"}"}function mVo(t){return/^-?0\d/.test(t)}function pVo(t,e){return t<=e}function IVo(t,e){return t>=e}function pU(t,e,n,o,i,r){const A=[];let s=0;for(let a=0;a<t.length;a++)for(let c=0;c<n.length;c++){if(A.length>=o)return A;const l=t[a]+e+n[c];if(!(r&&!l)){if(s+l.length>i)return A;A.push(l),s+=l.length}}return A}function CVo(t,e,n){const o=t.split(/\.\./),i=[];if(o[0]===void 0||o[1]===void 0)return i;const r=k6e(o[0]),A=k6e(o[1]),s=Math.max(o[0].length,o[1].length);let a=o.length===3&&o[2]!==void 0?Math.max(Math.abs(k6e(o[2])),1):1,c=pVo;A<r&&(a*=-1,c=IVo);const g=o.some(mVo);for(let u=r;c(u,A)&&i.length<n;u+=a){let h;if(e)h=String.fromCharCode(u),h==="\\"&&(h="");else if(h=String(u),g){const d=s-h.length;if(d>0){const _=new Array(d+1).join("0");u<0?h="-"+_+h.slice(1):h=_+h}}i.push(h)}return i}function F6e(t,e,n,o){let i=[""],r=!1,A=!0;for(;;){const s=vkt("{","}",t);if(!s)return pU(i,t,[""],e,n,r);const a=s.pre;if(/\$$/.test(a)){if(i=pU(i,a+"{"+s.body+"}",[""],e,n,r&&!s.post.length),A=!1,!s.post.length)break;t=s.post;continue}const c=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(s.body),l=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(s.body),g=c||l,u=s.body.indexOf(",")>=0;if(!g&&!u){if(s.post.match(/,(?!,).*\}/)){t=s.pre+"{"+s.body+T6e+s.post,o=!0;continue}return pU(i,a+"{"+s.body+"}"+s.post,[""],e,n,r)}A&&(r=o&&!g,A=!1);let h;if(g)h=CVo(s.body,l,e);else{let d=Lkt(s.body);if(d.length===1&&d[0]!==void 0&&(d=F6e(d[0],e,n,!1).map(_Vo),d.length===1)){if(i=pU(i,a+d[0],[""],e,n,r&&!s.post.length),!s.post.length)break;t=s.post;continue}h=[];for(let _=0;_<d.length;_++)h.push.apply(h,F6e(d[_],e,n,!1))}if(i=pU(i,a,h,e,n,r&&!s.post.length),!s.post.length)break;t=s.post}return i}const fVo=1024*64,nre=t=>{if(typeof t!="string")throw new TypeError("invalid pattern");if(t.length>fVo)throw new TypeError("pattern is too long")},yVo={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},IU=t=>t.replace(/[[\]\\-]/g,"\\$&"),EVo=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Hkt=t=>t.join(""),xVo=(t,e)=>{const n=e;if(t.charAt(n)!=="[")throw new Error("not in a brace expression");const o=[],i=[];let r=n+1,A=!1,s=!1,a=!1,c=!1,l=n,g="";e:for(;r<t.length;){const _=t.charAt(r);if((_==="!"||_==="^")&&r===n+1){c=!0,r++;continue}if(_==="]"&&A&&!a){l=r+1;break}if(A=!0,_==="\\"&&!a){a=!0,r++;continue}if(_==="["&&!a){for(const[p,[m,C,I]]of Object.entries(yVo))if(t.startsWith(p,r)){if(g)return["$.",!1,t.length-n,!0];r+=p.length,I?i.push(m):o.push(m),s=s||C;continue e}}if(a=!1,g){_>g?o.push(IU(g)+"-"+IU(_)):_===g&&o.push(IU(_)),g="",r++;continue}if(t.startsWith("-]",r+1)){o.push(IU(_+"-")),r+=2;continue}if(t.startsWith("-",r+1)){g=_,r+=2;continue}o.push(IU(_)),r++}if(l<r)return["",!1,0,!1];if(!o.length&&!i.length)return["$.",!1,t.length-n,!0];if(i.length===0&&o.length===1&&/^\\?.$/.test(o[0])&&!c){const _=o[0].length===2?o[0].slice(-1):o[0];return[EVo(_),!1,l-n,!1]}const u="["+(c?"^":"")+Hkt(o)+"]",h="["+(c?"":"^")+Hkt(i)+"]";return[o.length&&i.length?"("+u+"|"+h+")":o.length?u:h,s,l-n,!0]},CU=(t,{windowsPathsNoEscape:e=!1,magicalBraces:n=!0}={})=>n?e?t.replace(/\[([^/\\])\]/g,"$1"):t.replace(/((?!\\).|^)\[([^/\\])\]/g,"$1$2").replace(/\\([^/])/g,"$1"):e?t.replace(/\[([^/\\{}])\]/g,"$1"):t.replace(/((?!\\).|^)\[([^/\\{}])\]/g,"$1$2").replace(/\\([^/{}])/g,"$1");var Cy;const BVo=new Set(["!","?","+","*","@"]),L6e=t=>BVo.has(t),Gkt=t=>L6e(t.type),QVo=new Map([["!",["@"]],["?",["?","@"]],["@",["@"]],["*",["*","+","?","@"]],["+",["+","@"]]]),SVo=new Map([["!",["?"]],["@",["?"]],["+",["?","*"]]]),bVo=new Map([["!",["?","@"]],["?",["?","@"]],["@",["?","@"]],["*",["*","+","?","@"]],["+",["+","@","?","*"]]]),Okt=new Map([["!",new Map([["!","@"]])],["?",new Map([["*","*"],["+","*"]])],["@",new Map([["!","!"],["?","?"],["@","@"],["*","*"],["+","+"]])],["+",new Map([["?","*"],["*","*"]])]]),DVo="(?!(?:^|/)\\.\\.?(?:$|/))",ore="(?!\\.)",MVo=new Set(["[","."]),wVo=new Set(["..","."]),PVo=new Set("().*{}+?[]^$\\!"),vVo=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),H6e="[^/]",Kkt=H6e+"*?",Ukt=H6e+"+?";let NVo=0;class G6e{type;#i;#n;#o=!1;#t=[];#e;#A;#r;#c=!1;#s;#l;#u=!1;id=++NVo;get depth(){return(this.#e?.depth??-1)+1}[Symbol.for("nodejs.util.inspect.custom")](){return{"@@type":"AST",id:this.id,type:this.type,root:this.#i.id,parent:this.#e?.id,depth:this.depth,partsLength:this.#t.length,parts:this.#t}}constructor(e,n,o={}){this.type=e,e&&(this.#n=!0),this.#e=n,this.#i=this.#e?this.#e.#i:this,this.#s=this.#i===this?o:this.#i.#s,this.#r=this.#i===this?[]:this.#i.#r,e==="!"&&!this.#i.#c&&this.#r.push(this),this.#A=this.#e?this.#e.#t.length:0}get hasMagic(){if(this.#n!==void 0)return this.#n;for(const e of this.#t)if(typeof e!="string"&&(e.type||e.hasMagic))return this.#n=!0;return this.#n}toString(){return this.#l!==void 0?this.#l:this.type?this.#l=this.type+"("+this.#t.map(e=>String(e)).join("|")+")":this.#l=this.#t.map(e=>String(e)).join("")}#d(){if(this!==this.#i)throw new Error("should only call on root");if(this.#c)return this;this.toString(),this.#c=!0;let e;for(;e=this.#r.pop();){if(e.type!=="!")continue;let n=e,o=n.#e;for(;o;){for(let i=n.#A+1;!o.type&&i<o.#t.length;i++)for(const r of e.#t){if(typeof r=="string")throw new Error("string part in extglob AST??");r.copyIn(o.#t[i])}n=o,o=n.#e}}return this}push(...e){for(const n of e)if(n!==""){if(typeof n!="string"&&!(n instanceof Cy&&n.#e===this))throw new Error("invalid part: "+n);this.#t.push(n)}}toJSON(){const e=this.type===null?this.#t.slice().map(n=>typeof n=="string"?n:n.toJSON()):[this.type,...this.#t.map(n=>n.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#i||this.#i.#c&&this.#e?.type==="!")&&e.push({}),e}isStart(){if(this.#i===this)return!0;if(!this.#e?.isStart())return!1;if(this.#A===0)return!0;const e=this.#e;for(let n=0;n<this.#A;n++){const o=e.#t[n];if(!(o instanceof Cy&&o.type==="!"))return!1}return!0}isEnd(){if(this.#i===this||this.#e?.type==="!")return!0;if(!this.#e?.isEnd())return!1;if(!this.type)return this.#e?.isEnd();const e=this.#e?this.#e.#t.length:0;return this.#A===e-1}copyIn(e){typeof e=="string"?this.push(e):this.push(e.clone(this))}clone(e){const n=new Cy(this.type,e);for(const o of this.#t)n.copyIn(o);return n}static#a(e,n,o,i,r){const A=i.maxExtglobRecursion??2;let s=!1,a=!1,c=-1,l=!1;if(n.type===null){let _=o,p="";for(;_<e.length;){const m=e.charAt(_++);if(s||m==="\\"){s=!s,p+=m;continue}if(a){_===c+1?(m==="^"||m==="!")&&(l=!0):m==="]"&&!(_===c+2&&l)&&(a=!1),p+=m;continue}else if(m==="["){a=!0,c=_,l=!1,p+=m;continue}if(!i.noext&&L6e(m)&&e.charAt(_)==="("&&r<=A){n.push(p),p="";const I=new Cy(m,n);_=Cy.#a(e,I,_,i,r+1),n.push(I);continue}p+=m}return n.push(p),_}let g=o+1,u=new Cy(null,n);const h=[];let d="";for(;g<e.length;){const _=e.charAt(g++);if(s||_==="\\"){s=!s,d+=_;continue}if(a){g===c+1?(_==="^"||_==="!")&&(l=!0):_==="]"&&!(g===c+2&&l)&&(a=!1),d+=_;continue}else if(_==="["){a=!0,c=g,l=!1,d+=_;continue}if(!i.noext&&L6e(_)&&e.charAt(g)==="("&&(r<=A||n&&n.#g(_))){const m=n&&n.#g(_)?0:1;u.push(d),d="";const C=new Cy(_,u);u.push(C),g=Cy.#a(e,C,g,i,r+m);continue}if(_==="|"){u.push(d),d="",h.push(u),u=new Cy(null,n);continue}if(_===")")return d===""&&n.#t.length===0&&(n.#u=!0),u.push(d),d="",n.push(...h,u),g;d+=_}return n.type=null,n.#n=void 0,n.#t=[e.substring(o-1)],g}#m(e){return this.#p(e,SVo)}#p(e,n=QVo){if(!e||typeof e!="object"||e.type!==null||e.#t.length!==1||this.type===null)return!1;const o=e.#t[0];return!o||typeof o!="object"||o.type===null?!1:this.#g(o.type,n)}#g(e,n=bVo){return!!n.get(this.type)?.includes(e)}#h(e,n){const o=e.#t[0],i=new Cy(null,o,this.options);i.#t.push(""),o.push(i),this.#_(e,n)}#_(e,n){const o=e.#t[0];this.#t.splice(n,1,...o.#t);for(const i of o.#t)typeof i=="object"&&(i.#e=this);this.#l=void 0}#f(e){return!!Okt.get(this.type)?.has(e)}#y(e){if(!e||typeof e!="object"||e.type!==null||e.#t.length!==1||this.type===null||this.#t.length!==1)return!1;const n=e.#t[0];return!n||typeof n!="object"||n.type===null?!1:this.#f(n.type)}#E(e){const n=Okt.get(this.type),o=e.#t[0],i=n?.get(o.type);if(!i)return!1;this.#t=o.#t;for(const r of this.#t)typeof r=="object"&&(r.#e=this);this.type=i,this.#l=void 0,this.#u=!1}static fromGlob(e,n={}){const o=new Cy(null,void 0,n);return Cy.#a(e,o,0,n,0),o}toMMPattern(){if(this!==this.#i)return this.#i.toMMPattern();const e=this.toString(),[n,o,i,r]=this.toRegExpSource();if(!(i||this.#n||this.#s.nocase&&!this.#s.nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase()))return o;const s=(this.#s.nocase?"i":"")+(r?"u":"");return Object.assign(new RegExp(`^${n}$`,s),{_src:n,_glob:e})}get options(){return this.#s}toRegExpSource(e){const n=e??!!this.#s.dot;if(this.#i===this&&(this.#I(),this.#d()),!Gkt(this)){const a=this.isStart()&&this.isEnd()&&!this.#t.some(h=>typeof h!="string"),c=this.#t.map(h=>{const[d,_,p,m]=typeof h=="string"?Cy.#x(h,this.#n,a):h.toRegExpSource(e);return this.#n=this.#n||p,this.#o=this.#o||m,d}).join("");let l="";if(this.isStart()&&typeof this.#t[0]=="string"&&!(this.#t.length===1&&wVo.has(this.#t[0]))){const d=MVo,_=n&&d.has(c.charAt(0))||c.startsWith("\\.")&&d.has(c.charAt(2))||c.startsWith("\\.\\.")&&d.has(c.charAt(4)),p=!n&&!e&&d.has(c.charAt(0));l=_?DVo:p?ore:""}let g="";return this.isEnd()&&this.#i.#c&&this.#e?.type==="!"&&(g="(?:$|\\/)"),[l+c+g,CU(c),this.#n=!!this.#n,this.#o]}const o=this.type==="*"||this.type==="+",i=this.type==="!"?"(?:(?!(?:":"(?:";let r=this.#C(n);if(this.isStart()&&this.isEnd()&&!r&&this.type!=="!"){const a=this.toString(),c=this;return c.#t=[a],c.type=null,c.#n=void 0,[a,CU(this.toString()),!1,!1]}let A=!o||e||n||!ore?"":this.#C(!0);A===r&&(A=""),A&&(r=`(?:${r})(?:${A})*?`);let s="";if(this.type==="!"&&this.#u)s=(this.isStart()&&!n?ore:"")+Ukt;else{const a=this.type==="!"?"))"+(this.isStart()&&!n&&!e?ore:"")+Kkt+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&A?")":this.type==="*"&&A?")?":`)${this.type}`;s=i+r+a}return[s,CU(r),this.#n=!!this.#n,this.#o]}#I(){if(Gkt(this)){let e=0,n=!1;do{n=!0;for(let o=0;o<this.#t.length;o++){const i=this.#t[o];typeof i=="object"&&(i.#I(),this.#p(i)?(n=!1,this.#_(i,o)):this.#m(i)?(n=!1,this.#h(i,o)):this.#y(i)&&(n=!1,this.#E(i)))}}while(!n&&++e<10)}else for(const e of this.#t)typeof e=="object"&&e.#I();this.#l=void 0}#C(e){return this.#t.map(n=>{if(typeof n=="string")throw new Error("string type in extglob ast??");const[o,i,r,A]=n.toRegExpSource(e);return this.#o=this.#o||A,o}).filter(n=>!(this.isStart()&&this.isEnd())||!!n).join("|")}static#x(e,n,o=!1){let i=!1,r="",A=!1,s=!1;for(let a=0;a<e.length;a++){const c=e.charAt(a);if(i){i=!1,r+=(PVo.has(c)?"\\":"")+c;continue}if(c==="*"){if(s)continue;s=!0,r+=o&&/^[*]+$/.test(e)?Ukt:Kkt,n=!0;continue}else s=!1;if(c==="\\"){a===e.length-1?r+="\\\\":i=!0;continue}if(c==="["){const[l,g,u,h]=xVo(e,a);if(u){r+=l,A=A||g,a+=u-1,n=n||h;continue}}if(c==="?"){r+=H6e,n=!0;continue}r+=vVo(c)}return[r,CU(e),!!n,A]}}Cy=G6e;const RVo=(t,{windowsPathsNoEscape:e=!1,magicalBraces:n=!1}={})=>n?e?t.replace(/[?*()[\]{}]/g,"[$&]"):t.replace(/[?*()[\]\\{}]/g,"\\$&"):e?t.replace(/[?*()[\]]/g,"[$&]"):t.replace(/[?*()[\]\\]/g,"\\$&");var TT={env:{}};const Of=(t,e,n={})=>(nre(e),!n.nocomment&&e.charAt(0)==="#"?!1:new fU(e,n).match(t)),TVo=/^\*+([^+@!?*[(]*)$/,kVo=t=>e=>!e.startsWith(".")&&e.endsWith(t),FVo=t=>e=>e.endsWith(t),LVo=t=>(t=t.toLowerCase(),e=>!e.startsWith(".")&&e.toLowerCase().endsWith(t)),HVo=t=>(t=t.toLowerCase(),e=>e.toLowerCase().endsWith(t)),GVo=/^\*+\.\*+$/,OVo=t=>!t.startsWith(".")&&t.includes("."),KVo=t=>t!=="."&&t!==".."&&t.includes("."),UVo=/^\.\*+$/,YVo=t=>t!=="."&&t!==".."&&t.startsWith("."),zVo=/^\*+$/,VVo=t=>t.length!==0&&!t.startsWith("."),JVo=t=>t.length!==0&&t!=="."&&t!=="..",qVo=/^\?+([^+@!?*[(]*)?$/,WVo=([t,e=""])=>{const n=Ykt([t]);return e?(e=e.toLowerCase(),o=>n(o)&&o.toLowerCase().endsWith(e)):n},jVo=([t,e=""])=>{const n=zkt([t]);return e?(e=e.toLowerCase(),o=>n(o)&&o.toLowerCase().endsWith(e)):n},XVo=([t,e=""])=>{const n=zkt([t]);return e?o=>n(o)&&o.endsWith(e):n},$Vo=([t,e=""])=>{const n=Ykt([t]);return e?o=>n(o)&&o.endsWith(e):n},Ykt=([t])=>{const e=t.length;return n=>n.length===e&&!n.startsWith(".")},zkt=([t])=>{const e=t.length;return n=>n.length===e&&n!=="."&&n!==".."},Vkt=typeof TT=="object"&&TT?typeof TT.env=="object"&&TT.env&&TT.env.__MINIMATCH_TESTING_PLATFORM__||TT.platform:"posix",Jkt={win32:{sep:"\\"},posix:{sep:"/"}},ZVo=Vkt==="win32"?Jkt.win32.sep:Jkt.posix.sep;Of.sep=ZVo;const DC=Symbol("globstar **");Of.GLOBSTAR=DC;const eJo="[^/]"+"*?",tJo="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",nJo="(?:(?!(?:\\/|^)\\.).)*?",oJo=(t,e={})=>n=>Of(n,t,e);Of.filter=oJo;const mx=(t,e={})=>Object.assign({},t,e),iJo=t=>{if(!t||typeof t!="object"||!Object.keys(t).length)return Of;const e=Of;return Object.assign((o,i,r={})=>e(o,i,mx(t,r)),{Minimatch:class extends e.Minimatch{constructor(i,r={}){super(i,mx(t,r))}static defaults(i){return e.defaults(mx(t,i)).Minimatch}},AST:class extends e.AST{constructor(i,r,A={}){super(i,r,mx(t,A))}static fromGlob(i,r={}){return e.AST.fromGlob(i,mx(t,r))}},unescape:(o,i={})=>e.unescape(o,mx(t,i)),escape:(o,i={})=>e.escape(o,mx(t,i)),filter:(o,i={})=>e.filter(o,mx(t,i)),defaults:o=>e.defaults(mx(t,o)),makeRe:(o,i={})=>e.makeRe(o,mx(t,i)),braceExpand:(o,i={})=>e.braceExpand(o,mx(t,i)),match:(o,i,r={})=>e.match(o,i,mx(t,r)),sep:e.sep,GLOBSTAR:DC})};Of.defaults=iJo;const qkt=(t,e={})=>(nre(t),e.nobrace||!/\{(?:(?!\{).)*\}/.test(t)?[t]:hVo(t,{max:e.braceExpandMax}));Of.braceExpand=qkt;const rJo=(t,e={})=>new fU(t,e).makeRe();Of.makeRe=rJo;const AJo=(t,e,n={})=>{const o=new fU(e,n);return t=t.filter(i=>o.match(i)),o.options.nonull&&!t.length&&t.push(e),t};Of.match=AJo;const Wkt=/[?*]|[+@!]\(.*?\)|\[|\]/,sJo=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");class fU{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;maxGlobstarRecursion;regexp;constructor(e,n={}){nre(e),n=n||{},this.options=n,this.maxGlobstarRecursion=n.maxGlobstarRecursion??200,this.pattern=e,this.platform=n.platform||Vkt,this.isWindows=this.platform==="win32";const o="allowWindowsEscape";this.windowsPathsNoEscape=!!n.windowsPathsNoEscape||n[o]===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!n.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!n.nonegate,this.comment=!1,this.empty=!1,this.partial=!!n.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=n.windowsNoMagicRoot!==void 0?n.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(const e of this.set)for(const n of e)if(typeof n!="string")return!0;return!1}debug(...e){}make(){const e=this.pattern,n=this.options;if(!n.nocomment&&e.charAt(0)==="#"){this.comment=!0;return}if(!e){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],n.debug&&(this.debug=(...r)=>console.error(...r)),this.debug(this.pattern,this.globSet);const o=this.globSet.map(r=>this.slashSplit(r));this.globParts=this.preprocess(o),this.debug(this.pattern,this.globParts);let i=this.globParts.map((r,A,s)=>{if(this.isWindows&&this.windowsNoMagicRoot){const a=r[0]===""&&r[1]===""&&(r[2]==="?"||!Wkt.test(r[2]))&&!Wkt.test(r[3]),c=/^[a-z]:/i.test(r[0]);if(a)return[...r.slice(0,4),...r.slice(4).map(l=>this.parse(l))];if(c)return[r[0],...r.slice(1).map(l=>this.parse(l))]}return r.map(a=>this.parse(a))});if(this.debug(this.pattern,i),this.set=i.filter(r=>r.indexOf(!1)===-1),this.isWindows)for(let r=0;r<this.set.length;r++){const A=this.set[r];A[0]===""&&A[1]===""&&this.globParts[r][2]==="?"&&typeof A[3]=="string"&&/^[a-z]:$/i.test(A[3])&&(A[2]="?")}this.debug(this.pattern,this.set)}preprocess(e){if(this.options.noglobstar)for(const o of e)for(let i=0;i<o.length;i++)o[i]==="**"&&(o[i]="*");const{optimizationLevel:n=1}=this.options;return n>=2?(e=this.firstPhasePreProcess(e),e=this.secondPhasePreProcess(e)):n>=1?e=this.levelOneOptimize(e):e=this.adjascentGlobstarOptimize(e),e}adjascentGlobstarOptimize(e){return e.map(n=>{let o=-1;for(;(o=n.indexOf("**",o+1))!==-1;){let i=o;for(;n[i+1]==="**";)i++;i!==o&&n.splice(o,i-o)}return n})}levelOneOptimize(e){return e.map(n=>(n=n.reduce((o,i)=>{const r=o[o.length-1];return i==="**"&&r==="**"?o:i===".."&&r&&r!==".."&&r!=="."&&r!=="**"?(o.pop(),o):(o.push(i),o)},[]),n.length===0?[""]:n))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let n=!1;do{if(n=!1,!this.preserveMultipleSlashes){for(let i=1;i<e.length-1;i++){const r=e[i];i===1&&r===""&&e[0]===""||(r==="."||r==="")&&(n=!0,e.splice(i,1),i--)}e[0]==="."&&e.length===2&&(e[1]==="."||e[1]==="")&&(n=!0,e.pop())}let o=0;for(;(o=e.indexOf("..",o+1))!==-1;){const i=e[o-1];i&&i!=="."&&i!==".."&&i!=="**"&&!(this.isWindows&&/^[a-z]:$/i.test(i))&&(n=!0,e.splice(o-1,2),o-=2)}}while(n);return e.length===0?[""]:e}firstPhasePreProcess(e){let n=!1;do{n=!1;for(let o of e){let i=-1;for(;(i=o.indexOf("**",i+1))!==-1;){let A=i;for(;o[A+1]==="**";)A++;A>i&&o.splice(i+1,A-i);let s=o[i+1];const a=o[i+2],c=o[i+3];if(s!==".."||!a||a==="."||a===".."||!c||c==="."||c==="..")continue;n=!0,o.splice(i,1);const l=o.slice(0);l[i]="**",e.push(l),i--}if(!this.preserveMultipleSlashes){for(let A=1;A<o.length-1;A++){const s=o[A];A===1&&s===""&&o[0]===""||(s==="."||s==="")&&(n=!0,o.splice(A,1),A--)}o[0]==="."&&o.length===2&&(o[1]==="."||o[1]==="")&&(n=!0,o.pop())}let r=0;for(;(r=o.indexOf("..",r+1))!==-1;){const A=o[r-1];if(A&&A!=="."&&A!==".."&&A!=="**"){n=!0;const a=r===1&&o[r+1]==="**"?["."]:[];o.splice(r-1,2,...a),o.length===0&&o.push(""),r-=2}}}}while(n);return e}secondPhasePreProcess(e){for(let n=0;n<e.length-1;n++)for(let o=n+1;o<e.length;o++){const i=this.partsMatch(e[n],e[o],!this.preserveMultipleSlashes);if(i){e[n]=[],e[o]=i;break}}return e.filter(n=>n.length)}partsMatch(e,n,o=!1){let i=0,r=0,A=[],s="";for(;i<e.length&&r<n.length;)if(e[i]===n[r])A.push(s==="b"?n[r]:e[i]),i++,r++;else if(o&&e[i]==="**"&&n[r]===e[i+1])A.push(e[i]),i++;else if(o&&n[r]==="**"&&e[i]===n[r+1])A.push(n[r]),r++;else if(e[i]==="*"&&n[r]&&(this.options.dot||!n[r].startsWith("."))&&n[r]!=="**"){if(s==="b")return!1;s="a",A.push(e[i]),i++,r++}else if(n[r]==="*"&&e[i]&&(this.options.dot||!e[i].startsWith("."))&&e[i]!=="**"){if(s==="a")return!1;s="b",A.push(n[r]),i++,r++}else return!1;return e.length===n.length&&A}parseNegate(){if(this.nonegate)return;const e=this.pattern;let n=!1,o=0;for(let i=0;i<e.length&&e.charAt(i)==="!";i++)n=!n,o++;o&&(this.pattern=e.slice(o)),this.negate=n}matchOne(e,n,o=!1){let i=0,r=0;if(this.isWindows){const s=typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0]),a=!s&&e[0]===""&&e[1]===""&&e[2]==="?"&&/^[a-z]:$/i.test(e[3]),c=typeof n[0]=="string"&&/^[a-z]:$/i.test(n[0]),l=!c&&n[0]===""&&n[1]===""&&n[2]==="?"&&typeof n[3]=="string"&&/^[a-z]:$/i.test(n[3]),g=a?3:s?0:void 0,u=l?3:c?0:void 0;if(typeof g=="number"&&typeof u=="number"){const[h,d]=[e[g],n[u]];h.toLowerCase()===d.toLowerCase()&&(n[u]=h,r=u,i=g)}}const{optimizationLevel:A=1}=this.options;return A>=2&&(e=this.levelTwoFileOptimize(e)),n.includes(DC)?this.#i(e,n,o,i,r):this.#o(e,n,o,i,r)}#i(e,n,o,i,r){const A=n.indexOf(DC,r),s=n.lastIndexOf(DC),[a,c,l]=o?[n.slice(r,A),n.slice(A+1),[]]:[n.slice(r,A),n.slice(A+1,s),n.slice(s+1)];if(a.length){const C=e.slice(i,i+a.length);if(!this.#o(C,a,o,0,0))return!1;i+=a.length,r+=a.length}let g=0;if(l.length){if(l.length+i>e.length)return!1;let C=e.length-l.length;if(this.#o(e,l,o,C,0))g=l.length;else{if(e[e.length-1]!==""||i+l.length===e.length||(C--,!this.#o(e,l,o,C,0)))return!1;g=l.length+1}}if(!c.length){let C=!!g;for(let I=i;I<e.length-g;I++){const f=String(e[I]);if(C=!0,f==="."||f===".."||!this.options.dot&&f.startsWith("."))return!1}return o||C}const u=[[[],0]];let h=u[0],d=0;const _=[0];for(const C of c)C===DC?(_.push(d),h=[[],0],u.push(h)):(h[0].push(C),d++);let p=u.length-1;const m=e.length-g;for(const C of u)C[1]=m-(_[p--]+C[0].length);return!!this.#n(e,u,i,0,o,0,!!g)}#n(e,n,o,i,r,A,s){const a=n[i];if(!a){for(let g=o;g<e.length;g++){s=!0;const u=e[g];if(u==="."||u===".."||!this.options.dot&&u.startsWith("."))return!1}return s}const[c,l]=a;for(;o<=l;){if(this.#o(e.slice(0,o+c.length),c,r,o,0)&&A<this.maxGlobstarRecursion){const h=this.#n(e,n,o+c.length,i+1,r,A+1,s);if(h!==!1)return h}const u=e[o];if(u==="."||u===".."||!this.options.dot&&u.startsWith("."))return!1;o++}return r||null}#o(e,n,o,i,r){let A,s,a,c;for(A=i,s=r,c=e.length,a=n.length;A<c&&s<a;A++,s++){this.debug("matchOne loop");let l=n[s],g=e[A];if(this.debug(n,l,g),l===!1||l===DC)return!1;let u;if(typeof l=="string"?(u=g===l,this.debug("string match",l,g,u)):(u=l.test(g),this.debug("pattern match",l,g,u)),!u)return!1}if(A===c&&s===a)return!0;if(A===c)return o;if(s===a)return A===c-1&&e[A]==="";throw new Error("wtf?")}braceExpand(){return qkt(this.pattern,this.options)}parse(e){nre(e);const n=this.options;if(e==="**")return DC;if(e==="")return"";let o,i=null;(o=e.match(zVo))?i=n.dot?JVo:VVo:(o=e.match(TVo))?i=(n.nocase?n.dot?HVo:LVo:n.dot?FVo:kVo)(o[1]):(o=e.match(qVo))?i=(n.nocase?n.dot?jVo:WVo:n.dot?XVo:$Vo)(o):(o=e.match(GVo))?i=n.dot?KVo:OVo:(o=e.match(UVo))&&(i=YVo);const r=G6e.fromGlob(e,this.options).toMMPattern();return i&&typeof r=="object"&&Reflect.defineProperty(r,"test",{value:i}),r}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;const e=this.set;if(!e.length)return this.regexp=!1,this.regexp;const n=this.options,o=n.noglobstar?eJo:n.dot?tJo:nJo,i=new Set(n.nocase?["i"]:[]);let r=e.map(a=>{const c=a.map(g=>{if(g instanceof RegExp)for(const u of g.flags.split(""))i.add(u);return typeof g=="string"?sJo(g):g===DC?DC:g._src});c.forEach((g,u)=>{const h=c[u+1],d=c[u-1];g!==DC||d===DC||(d===void 0?h!==void 0&&h!==DC?c[u+1]="(?:\\/|"+o+"\\/)?"+h:c[u]=o:h===void 0?c[u-1]=d+"(?:\\/|\\/"+o+")?":h!==DC&&(c[u-1]=d+"(?:\\/|\\/"+o+"\\/)"+h,c[u+1]=DC))});const l=c.filter(g=>g!==DC);if(this.partial&&l.length>=1){const g=[];for(let u=1;u<=l.length;u++)g.push(l.slice(0,u).join("/"));return"(?:"+g.join("|")+")"}return l.join("/")}).join("|");const[A,s]=e.length>1?["(?:",")"]:["",""];r="^"+A+r+s+"$",this.partial&&(r="^(?:\\/|"+A+r.slice(1,-1)+s+")$"),this.negate&&(r="^(?!"+r+").+$");try{this.regexp=new RegExp(r,[...i].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split("/"):this.isWindows&&/^\/\/[^/]+/.test(e)?["",...e.split(/\/+/)]:e.split(/\/+/)}match(e,n=this.partial){if(this.debug("match",e,this.pattern),this.comment)return!1;if(this.empty)return e==="";if(e==="/"&&n)return!0;const o=this.options;this.isWindows&&(e=e.split("\\").join("/"));const i=this.slashSplit(e);this.debug(this.pattern,"split",i);const r=this.set;this.debug(this.pattern,"set",r);let A=i[i.length-1];if(!A)for(let s=i.length-2;!A&&s>=0;s--)A=i[s];for(const s of r){let a=i;if(o.matchBase&&s.length===1&&(a=[A]),this.matchOne(a,s,n))return o.flipNegate?!0:!this.negate}return o.flipNegate?!1:this.negate}static defaults(e){return Of.defaults(e).Minimatch}}Of.AST=G6e,Of.Minimatch=fU,Of.escape=RVo,Of.unescape=CU;const aJo=t=>(t.endsWith(".tsx")||t.endsWith(".ts")||t.endsWith(".jsx")||t.endsWith(".js")||ere(t))&&!t.endsWith(".d.ts"),cJo=t=>{if(!t)return null;try{const e=JSON.parse(t);return BXt.parse(e)}catch(e){return console.warn("Failed to parse tscircuit.config.json",e),null}},lJo=(t,e)=>{const o=cJo(e)?.includeBoardFiles?.filter(Boolean);if(o&&o.length>0){const i=o.map(r=>new fU(r,{dot:!0}));return t.filter(r=>i.some(A=>A.match(r)))}return t.filter(aJo)},O6e=Ga("run-frame:RunFrameWithApi"),gJo=()=>{const e=!!Yu(o=>o.error),n=e?"Dev server disconnected":"Dev server connected";return J.jsx(h6e,{children:J.jsxs(_6e,{children:[J.jsx(m6e,{asChild:!0,children:J.jsx("button",{type:"button","aria-label":n,className:"rf-inline-flex rf-items-center rf-justify-center rf-p-2 rf-rounded-full rf-outline-none",children:J.jsx("span",{className:qi("rf-inline-flex rf-size-2 rf-rounded-full rf-flex-shrink-0",e?"rf-bg-red-600":"rf-bg-green-600 rf-opacity-50"),"aria-hidden":"true"})})}),J.jsx(qie,{side:"right",children:n})]})})},jkt=t=>t.find(e=>e.includes("entrypoint."))??t.find(e=>e.includes("index."))??t.find(e=>e.includes("main."))??t.find(e=>e.endsWith(".tsx")),uJo=t=>t.find(e=>e.includes("manual-edits."))??t.find(e=>e.includes("manual-edit."))??t.find(e=>e.endsWith(".json")),Xkt=t=>{const{apiBaseUrl:e,leftHeaderContent:n}=t;j.useEffect(()=>{t.debug&&Ga.enable("run-frame*")},[t.debug]);const o=Yu(H=>H.startPolling),i=Yu(H=>H.stopPolling),r=Yu(H=>H.setCurrentMainComponentPath),A=Yu(H=>H.pushEvent),s=oOn(),a=Yu(H=>H.fsMap),c=Yu(H=>H.recentlySavedFiles),l=j.useMemo(()=>Array.from(a.keys()),[a]),g=j.useMemo(()=>{const H=a.get("tscircuit.config.json");return typeof H=="string"?H:void 0},[a]),u=j.useMemo(()=>lJo(l,g),[l,g]),h=Yu(H=>H.circuitJson),[d,_]=j.useState(()=>typeof window>"u"?t.initialMainComponentPath??"":new URLSearchParams(window.location.hash.slice(1)).get("file")??t.initialMainComponentPath??""),[p,m]=J7("runframe:favorites",[]),C=!s,I=j.useCallback(H=>{m(G=>G.includes(H)?G.filter(K=>K!==H):[...G,H])},[m]),f=t.fileFilter??KYo,y=j.useMemo(()=>u.filter(f),[u,f]);j.useEffect(()=>{if(d&&(y.includes(d)||u.includes(d)))return;if(d){const W=d.includes("/")?d.substring(0,d.lastIndexOf("/")):"",X=y.find(ie=>(ie.includes("/")?ie.substring(0,ie.lastIndexOf("/")):"")===W);if(X){_(X);return}}const H=window?.TSCIRCUIT_DEFAULT_MAIN_COMPONENT_PATH,G=[t.initialMainComponentPath,H].filter(W=>!!W);for(const W of G)if(y.includes(W)){_(W);return}const V=(y.length>0?y:u)[0];V&&_(V)},[y,u,t.initialMainComponentPath,d]);const x=j.useCallback(H=>{if(typeof window>"u")return;const G=new URLSearchParams(window.location.hash.slice(1));if(G.get("file")===H)return;G.set("file",H);const K=G.toString(),V=`${window.location.pathname}${window.location.search}${K.length>0?`#${K}`:""}`;window.history.replaceState(null,"",V)},[]);j.useEffect(()=>{d&&(x(d),t.onMainComponentPathChange?.(d),r(d))},[d,t.onMainComponentPathChange,x,r]),$zo();const{editEventsForRender:B,pushEditEvent:S,markRenderStarted:D,markRenderComplete:w}=nOn();j.useEffect(()=>{e&&(window.TSCIRCUIT_FILESERVER_API_BASE_URL=e)},[e]),j.useEffect(()=>(o(),()=>i()),[o,i]);const F=j.useMemo(()=>String(d).length>0?{mainComponentPath:d}:{},[d]),R=j.useCallback(async H=>{try{await A({event_type:"RUN_COMPLETED",initiator:"runframe",...H})}catch(G){O6e("Failed to push RUN_COMPLETED event",G)}},[A]);return J.jsx(skt,{fsMap:a,showFileMenu:t.showFileMenu,isCli:t.isCli,schematicSvgOptions:t.schematicSvgOptions,isLoadingFiles:C,evalVersion:t.evalVersion,forceLatestEvalVersion:t.forceLatestEvalVersion,evalWebWorkerBlobUrl:t.evalWebWorkerBlobUrl??t.workerBlobUrl,enableFetchProxy:t.enableFetchProxy,leftHeaderContent:J.jsxs("div",{className:"rf-flex rf-items-center rf-justify-between rf-w-full",children:[J.jsxs("div",{className:"rf-flex rf-items-center rf-gap-2",children:[t.leftHeaderContent,J.jsx(gJo,{})]}),t.showFilesSwitch&&J.jsx("div",{className:"rf-absolute rf-left-1/2 rf-transform rf--translate-x-1/2",children:J.jsx(wkt,{currentFile:d,files:y,onFileChange:H=>{typeof a.get(H)=="string"&&_(H)},pinnedFiles:p,onToggleFavorite:I,fileFilter:f,recentlySavedFiles:c})})]}),defaultToFullScreen:t.defaultToFullScreen,showToggleFullScreen:t.showToggleFullScreen,onInitialRender:()=>{O6e("onInitialRender / markRenderStarted"),D()},onRenderFinished:()=>{O6e("onRenderFinished / markRenderComplete"),w()},onRunCompleted:R,editEvents:B,onEditEvent:H=>{S(H),fetch(`${Qf}/events/create`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event_type:"USER_CREATED_MANUAL_EDIT",...H})});const G=uJo(Array.from(a.keys()))??"manual-edits.json",K=a.get(G),V=JSON.parse(K??"{}");Kct({circuitJson:h,editEvents:[H],manualEditsFile:V}),fetch(`${Qf}/files/upsert`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({file_path:G,text_content:JSON.stringify(V),initiator:"runframe"})})},onLoginRequired:t.onLoginRequired,easyEdaProxyConfig:{proxyEndpointUrl:`${Qf}/proxy`},...F})},dJo=()=>new Promise(t=>{document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>t()):t()}),hJo=()=>{const t=window.location.hash.slice(1),n=new URLSearchParams(t).get("tab")?.toLowerCase()?.trim();return n&&["pcb","schematic","cad"].includes(n)?n:"pcb"},_Jo=()=>{const t=document.getElementById("root");if(t)return t;const e=document.createElement("div");return e.id="root",e.style.height="100vh",document.body.appendChild(e),e},mJo=async()=>{const t=Array.from(document.querySelectorAll("script[type='tscircuit-tsx']")),e=new Map;return await Promise.all(t.map(async(n,o)=>{const i=n.dataset.path||n.getAttribute("data-file-path")||`script${o?o+1:""}.tsx`;if(n.src){const A=await(await fetch(n.src)).text();e.set(i,A)}else e.set(i,n.textContent||"")})),{fsMap:e}},$kt="<--INJECT_TSCIRCUIT_EVAL_WEB_WORKER_BLOB_URL-->",K6e={evalWebWorkerBlobUrl:$kt.includes("<--")?void 0:$kt,enableFetchProxy:"<--INJECT_ENABLE_FETCH_PROXY-->".includes("<--")?void 0:!0};(async()=>{await dJo();const t=VHt.createRoot(_Jo()),e=window.TSCIRCUIT_RUNFRAME_STATIC_FILE_LIST,n=window.TSCIRCUIT_DEFAULT_MAIN_COMPONENT_PATH,o=window.TSCIRCUIT_PACKAGE_NAME;if(Array.isArray(e)){const i=hJo();t.render(J.jsx(Xzo,{files:e,initialCircuitPath:n,tabSelected:i,projectName:o}))}else if(window.TSCIRCUIT_USE_RUNFRAME_FOR_CLI)t.render(J.jsx($Yo,{...K6e}));else{const{fsMap:i}=await mJo();i.size>0?t.render(J.jsx(skt,{...K6e,fsMap:i})):t.render(J.jsx(Xkt,{...K6e}))}})();const pJo=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}))}));