@tscircuit/runframe 0.0.1640 → 0.0.1641

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.
@@ -5372,7 +5372,7 @@ svg { font-family: 'Inter', 'Helvetica Neue', Arial, sans-serif; }
5372
5372
  50% { opacity: 0.2; }
5373
5373
  100% { opacity: 0.6; }
5374
5374
  }
5375
- `,n.appendChild(u)}})}};o();const s=new MutationObserver(o);return s.observe(n,{childList:!0,subtree:!1,characterData:!1}),()=>{s.disconnect()}},[e,t,A,i])},Eot=["#8B0000","#2F4F4F","#191970","#006400","#FF4500","#800080","#2E8B57","#B8860B","#C71585","#008B8B"],IPe=e=>{const{svgDivRef:A,circuitJson:t,circuitJsonKey:i,showGroups:n}=e;AA.useEffect(()=>{if(A.current&&A.current.querySelectorAll(".schematic-group-overlay").forEach(r=>r.remove()),!A.current||!n||!t||t.length===0)return;const o=setTimeout(()=>{if(!A.current)return;const s=A.current.querySelector("svg");if(!s)return;s.querySelectorAll(".schematic-group-overlay").forEach(a=>a.remove());try{const a=wh(t).source_group?.list().filter(u=>!u.is_subcircuit)||[],g=wh(t).schematic_component?.list()||[],c=new Map;a.forEach(u=>{const d=u;if(d.parent_source_group_id){const f=c.get(d.parent_source_group_id)||[];f.push(u.source_group_id),c.set(d.parent_source_group_id,f)}});const I=u=>{const d=[],f=c.get(u)||[];for(const m of f)d.push(m),d.push(...I(m));return d},l=u=>{const d=a.find(f=>f.source_group_id===u);return d?.parent_source_group_id?1+l(d.parent_source_group_id):0},B=a.length>0&&a.some(u=>u.name&&u.name.trim()!=="");let C=[];if(B){const u=new Map;for(const d of g){const f=wh(t).source_component.get(d.source_component_id);f?.source_group_id&&(u.has(f.source_group_id)||u.set(f.source_group_id,[]),u.get(f.source_group_id).push(d))}a.forEach((d,f)=>{let m=u.get(d.source_group_id)||[];const w=I(d.source_group_id);for(const D of w){const b=u.get(D)||[];m=[...m,...b]}if(m.length>0){const D=l(d.source_group_id),b=I(d.source_group_id).length>0;if(d.name?.startsWith("unnamed_board"))return;C.push({id:d.source_group_id,name:d.name||`Group ${f+1}`,components:m,color:Eot[f%Eot.length],depthLevel:D,hasChildren:b,sourceGroupId:d.source_group_id})}})}const Q=s.viewBox.baseVal,E=s.getBoundingClientRect(),h=Math.min(E.width/Q.width,E.height/Q.height)||1;C.sort((u,d)=>u.depthLevel-d.depthLevel),C.forEach(u=>{if(u.components.length===0)return;const d=lPe(u.components,s);if(!d)return;const f=Math.max(8,Math.min(25,15/Math.max(h,.3))),m=u.hasChildren?f*.6:0,w=f+m,D=Math.max(1,2/Math.max(h,.5)),b=u.depthLevel===0?D:D*.7,k=Math.max(4,8/Math.max(h,.5)),x=u.hasChildren?1.3:1,N=k*x,R=N*.5,U=document.createElementNS("http://www.w3.org/2000/svg","rect");U.setAttribute("class","schematic-group-overlay"),U.setAttribute("x",(d.minX-w).toString()),U.setAttribute("y",(d.minY-w).toString()),U.setAttribute("width",(d.maxX-d.minX+w*2).toString()),U.setAttribute("height",(d.maxY-d.minY+w*2).toString()),U.setAttribute("fill","none"),U.setAttribute("stroke",u.color),U.setAttribute("stroke-width",b.toString()),U.setAttribute("stroke-dasharray",`${N},${R}`),U.setAttribute("opacity","0.8"),U.setAttribute("rx","0"),U.setAttribute("ry","0");const T=Math.max(6,Math.min(20,14/Math.max(h,.2))),Y=u.depthLevel===0||u.depthLevel===1?0:u.depthLevel*.2,O=T*(1-Y),W=Math.max(1,O*.2),X=u.name,iA=document.createElementNS("http://www.w3.org/2000/svg","text");iA.setAttribute("font-size",O.toString()),iA.setAttribute("font-family","Arial, sans-serif"),iA.textContent=X,s.appendChild(iA);const aA=iA.getBBox();s.removeChild(iA);const tA=aA.width+W*2,oA=O+W*2,rA=d.minX-w,CA=d.minY-w-oA,SA=document.createElementNS("http://www.w3.org/2000/svg","rect");SA.setAttribute("class","schematic-group-overlay"),SA.setAttribute("x",rA.toString()),SA.setAttribute("y",(CA-oA).toString()),SA.setAttribute("width",tA.toString()),SA.setAttribute("height",oA.toString()),SA.setAttribute("fill","transparent"),SA.setAttribute("rx","0"),SA.setAttribute("ry","0");const MA=document.createElementNS("http://www.w3.org/2000/svg","text");MA.setAttribute("class","schematic-group-overlay"),MA.setAttribute("x",(rA+W).toString()),MA.setAttribute("y",(CA+oA-W).toString()),MA.setAttribute("fill",u.color),MA.setAttribute("font-size",O.toString()),MA.setAttribute("font-family","Arial, sans-serif"),MA.setAttribute("font-weight",u.depthLevel===0?"600":"500"),MA.setAttribute("stroke",u.color),MA.setAttribute("stroke-width",Math.max(.2,O*.02).toString()),MA.textContent=X,s.appendChild(U),s.appendChild(SA),s.appendChild(MA)})}catch(a){console.error("Error creating group overlays:",a)}},10);return()=>clearTimeout(o)},[A,i,n])};function lPe(e,A){let t=1/0,i=1/0,n=-1/0,o=-1/0;for(const r of e){let a=A.querySelector(`g[data-schematic-component-id="${r.schematic_component_id}"]`);if(a||(a=A.querySelector(`[data-schematic-component-id="${r.schematic_component_id}"]`)),a){const g=a.getBBox();t=Math.min(t,g.x),i=Math.min(i,g.y),n=Math.max(n,g.x+g.width),o=Math.max(o,g.y+g.height)}}return t===1/0?null:{minX:t,minY:i,maxX:n,maxY:o}}var BPe=Bc("schematic-viewer"),CPe=()=>{Bc.enable("schematic-viewer*")},QPe=BPe,hot=e=>{const[A,t]=AA.useState(0),[i,n]=AA.useState(0);return AA.useEffect(()=>{if(!e.current)return;const o=()=>{const r=e.current?.getBoundingClientRect();t(r?.width||0),n(r?.height||0)};o();const s=new ResizeObserver(o);return s.observe(e.current),window.addEventListener("resize",o),()=>{s.disconnect(),window.removeEventListener("resize",o)}},[]),{containerWidth:A,containerHeight:i}},EPe=QPe.extend("useComponentDragging"),hPe=({onEditEvent:e,editEvents:A=[],circuitJson:t,cancelDrag:i,svgToScreenProjection:n,realToSvgProjection:o,enabled:s=!1,snapToGrid:r=!1})=>{const[a,g]=AA.useState(null),c=bl(o,n),I=AA.useRef(null),l=AA.useRef(null),B=AA.useRef(new Map);AA.useEffect(()=>{A.forEach(D=>{"edit_event_type"in D&&D.edit_event_type==="edit_schematic_component_location"&&!D.in_progress&&B.current.set(D.schematic_component_id,{...D.new_center})})},[A]);const C=AA.useCallback((D,b,k)=>{if(!s)return!1;const x=k.closest('[data-circuit-json-type="schematic_component"]');if(!x)return!1;const N=x.getAttribute("data-schematic-component-id");if(!N)return!1;i&&i();const R=wh(t).schematic_component.get(N);if(!R)return!1;I.current={x:D,y:b};let U;const T=B.current.get(N);if(T)U={...T};else{const O=Qot({editEvents:A,schematic_component_id:N});U={x:R.center.x+O.x,y:R.center.y+O.y},B.current.set(N,{...U})}const Y={edit_event_id:Math.random().toString(36).substr(2,9),edit_event_type:"edit_schematic_component_location",schematic_component_id:N,original_center:U,new_center:{...U},in_progress:!0,created_at:Date.now(),_element:x};return l.current=Y,g(Y),!0},[i,s,t,A]),Q=AA.useCallback(D=>{C(D.clientX,D.clientY,D.target)},[C]),E=AA.useCallback(D=>{if(D.touches.length!==1)return;const b=D.touches[0];C(b.clientX,b.clientY,D.target)&&D.preventDefault()},[C]),h=AA.useCallback((D,b)=>{if(!l.current||!I.current)return;const k={x:D-I.current.x,y:b-I.current.y},x={x:k.x/c.a,y:k.y/c.d};let N={x:l.current.original_center.x+x.x,y:l.current.original_center.y+x.y};if(r){const U=T=>Math.round(T*10)/10;N={x:U(N.x),y:U(N.y)}}const R={...l.current,new_center:N};l.current=R,g(R)},[c,r]),u=AA.useCallback(D=>h(D.clientX,D.clientY),[h]),d=AA.useCallback(D=>{if(D.touches.length!==1||!l.current)return;D.preventDefault();const b=D.touches[0];h(b.clientX,b.clientY)},[h]),f=AA.useCallback(()=>{if(!l.current)return;const D={...l.current,in_progress:!1};B.current.set(D.schematic_component_id,{...D.new_center}),EPe("endDrag calling onEditEvent with new edit event",{newEditEvent:D}),e&&e(D),l.current=null,I.current=null,g(null)},[e]),m=AA.useCallback(()=>f(),[f]),w=AA.useCallback(()=>f(),[f]);return AA.useEffect(()=>(window.addEventListener("mousemove",u),window.addEventListener("mouseup",m),window.addEventListener("touchmove",d,{passive:!1}),window.addEventListener("touchend",w),()=>{window.removeEventListener("mousemove",u),window.removeEventListener("mouseup",m),window.removeEventListener("touchmove",d),window.removeEventListener("touchend",w)}),[u,m,d,w]),{handleMouseDown:Q,handleTouchStart:E,isDragging:!!l.current,activeEditEvent:a}},kD={schematicEditIcon:50,schematicGridIcon:49,spiceSimulationIcon:50,viewMenuIcon:48,viewMenu:55,viewMenuBackdrop:54,clickToInteractOverlay:100,schematicComponentHoverOutline:47,schematicPortHoverOutline:48},uPe=({onClick:e,active:A})=>{const t=i=>{i.preventDefault(),e()};return Z.jsx("div",{onClick:t,onTouchEnd:t,title:A?"Disable edit mode":"Enable edit mode",style:{position:"absolute",top:"16px",right:"64px",backgroundColor:A?"#4CAF50":"#fff",color:A?"#fff":"#000",padding:"8px",borderRadius:"4px",cursor:"pointer",boxShadow:"0 2px 4px rgba(0,0,0,0.1)",display:"flex",alignItems:"center",gap:"4px",zIndex:kD.schematicEditIcon},children:Z.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[Z.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),Z.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]})})},dPe=({onClick:e,active:A})=>{const t=i=>{i.preventDefault(),e()};return Z.jsx("div",{onClick:t,onTouchEnd:t,title:A?"Hide grid":"Show grid",style:{position:"absolute",top:"56px",right:"64px",backgroundColor:A?"#4CAF50":"#fff",color:A?"#fff":"#000",padding:"8px",borderRadius:"4px",cursor:"pointer",boxShadow:"0 2px 4px rgba(0,0,0,0.1)",display:"flex",alignItems:"center",gap:"4px",zIndex:kD.schematicGridIcon},children:Z.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:Z.jsx("path",{d:"M3 3h7v7H3zM14 3h7v7h-7zM3 14h7v7H3zM14 14h7v7h-7z"})})})},pPe=({onClick:e,active:A})=>{const t=i=>{i.preventDefault(),e()};return Z.jsx("div",{onClick:t,onTouchEnd:t,title:A?"Hide view menu":"Show view menu",style:{position:"absolute",top:"16px",right:"16px",backgroundColor:A?"#4CAF50":"#fff",color:A?"#fff":"#000",padding:"8px",borderRadius:"4px",cursor:"pointer",boxShadow:"0 2px 4px rgba(0,0,0,0.1)",display:"flex",alignItems:"center",gap:"4px",zIndex:kD.viewMenuIcon},children:Z.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[Z.jsx("circle",{cx:"12",cy:"12",r:"1"}),Z.jsx("circle",{cx:"12",cy:"5",r:"1"}),Z.jsx("circle",{cx:"12",cy:"19",r:"1"})]})})},fPe={version:"2.0.55"},yPe=({circuitJson:e,circuitJsonKey:A,isVisible:t,onClose:i,showGroups:n,onToggleGroups:o,showGrid:s,onToggleGrid:r})=>{const a=AA.useMemo(()=>{if(!e||e.length===0)return!1;try{if((wh(e).source_group?.list()||[]).length>0)return!0;const c=wh(e).schematic_component?.list()||[];if(c.length>1){const I=new Set;for(const l of c){const B=wh(e).source_component.get(l.source_component_id);B?.ftype&&I.add(B.ftype)}return I.size>1}return!1}catch(g){return console.error("Error checking for groups:",g),!1}},[A]);return t?Z.jsxs(Z.Fragment,{children:[Z.jsx("div",{onClick:i,onTouchEnd:g=>{g.preventDefault(),i()},style:{position:"absolute",inset:0,backgroundColor:"transparent",zIndex:kD.viewMenuBackdrop}}),Z.jsxs("div",{style:{position:"absolute",top:"56px",right:"16px",backgroundColor:"#ffffff",color:"#000000",border:"1px solid #ccc",borderRadius:"4px",boxShadow:"0 4px 12px rgba(0,0,0,0.1)",minWidth:"200px",zIndex:kD.viewMenu},children:[Z.jsxs("div",{onClick:()=>{a&&o(!n)},onTouchEnd:g=>{g.preventDefault(),a&&o(!n)},style:{padding:"8px 12px",cursor:a?"pointer":"not-allowed",opacity:a?1:.5,fontSize:"13px",color:"#000000",fontFamily:"sans-serif",display:"flex",alignItems:"center",gap:"8px"},onMouseEnter:g=>{a&&(g.currentTarget.style.backgroundColor="#f0f0f0")},onMouseLeave:g=>{a&&(g.currentTarget.style.backgroundColor="transparent")},children:[Z.jsx("div",{style:{width:"16px",height:"16px",border:"2px solid #000",borderRadius:"2px",backgroundColor:"transparent",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"10px",fontWeight:"bold"},children:n&&"✓"}),"View Schematic Groups"]}),!a&&Z.jsx("div",{style:{padding:"8px 12px",fontSize:"11px",color:"#666",fontStyle:"italic"},children:"No groups found in this schematic"}),Z.jsxs("div",{onClick:()=>r(!s),onTouchEnd:g=>{g.preventDefault(),r(!s)},style:{padding:"8px 12px",cursor:"pointer",fontSize:"13px",color:"#000000",fontFamily:"sans-serif",display:"flex",alignItems:"center",gap:"8px"},onMouseEnter:g=>{g.currentTarget.style.backgroundColor="#f0f0f0"},onMouseLeave:g=>{g.currentTarget.style.backgroundColor="transparent"},children:[Z.jsx("div",{style:{width:"16px",height:"16px",border:"2px solid #000",borderRadius:"2px",backgroundColor:"transparent",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"10px",fontWeight:"bold"},children:s&&"✓"}),"Show Grid"]}),Z.jsxs("div",{style:{padding:"4px 8px",fontSize:"12px",color:"#999",borderTop:"1px solid #eee",textAlign:"center"},children:["v",String(fPe?.version)]})]})]}):null},mPe=()=>Z.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:Z.jsx("path",{d:"M3 12h2.5l2.5-9 4 18 4-9h5.5"})}),wPe=({onClick:e})=>Z.jsx("div",{onClick:e,title:"Run SPICE simulation",style:{position:"absolute",top:"16px",right:"112px",backgroundColor:"#fff",color:"#000",padding:"8px",borderRadius:"4px",cursor:"pointer",boxShadow:"0 2px 4px rgba(0,0,0,0.1)",display:"flex",alignItems:"center",gap:"4px",zIndex:kD.spiceSimulationIcon},children:Z.jsx(mPe,{})});B9.register(jKe,$Ke,kKe,_Ke,UKe,OKe,vKe);var h9=["#8884d8","#82ca9d","#ffc658","#ff7300","#387908"],uot=e=>{if(e===0)return"0s";const A=Math.abs(e);let t="s",i=1;return A<1e-12?(t="fs",i=1e15):A<1e-9?(t="ps",i=1e12):A<1e-6?(t="ns",i=1e9):A<.001?(t="us",i=1e6):A<1&&(t="ms",i=1e3),`${parseFloat((e*i).toPrecision(3))}${t}`},DPe=({plotData:e,nodes:A,isLoading:t,error:i,hasRun:n})=>{const o=AA.useMemo(()=>{const a=A.some(c=>c.toLowerCase().startsWith("v(")),g=A.some(c=>c.toLowerCase().startsWith("i("));return a&&g?"Value":a?"Voltage (V)":g?"Current (A)":"Value"},[A]);if(t)return Z.jsx("div",{style:{height:"300px",width:"100%",display:"flex",alignItems:"center",justifyContent:"center"},children:"Running simulation..."});if(!n)return Z.jsx("div",{style:{height:"300px",width:"100%",display:"flex",alignItems:"center",justifyContent:"center"},children:'Click "Run" to start the simulation.'});if(i)return Z.jsxs("div",{style:{height:"300px",width:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"red"},children:["Error: ",i]});if(e.length===0)return Z.jsx("div",{style:{height:"300px",width:"100%",display:"flex",alignItems:"center",justifyContent:"center"},children:"No data to plot. Check simulation output or SPICE netlist."});const s={datasets:A.map((a,g)=>({label:a,data:e.map(c=>({x:Number(c.name),y:c[a]})),borderColor:h9[g%h9.length],backgroundColor:h9[g%h9.length],fill:!1,tension:.1}))},r={responsive:!0,maintainAspectRatio:!1,plugins:{legend:{position:"top",labels:{font:{family:"sans-serif"}}},title:{display:!1},tooltip:{callbacks:{title:a=>{if(a.length>0){const g=a[0];return uot(g.parsed.x)}return""}}}},scales:{x:{type:"linear",title:{display:!0,text:"Time",font:{family:"sans-serif"}},ticks:{callback:a=>uot(a),font:{family:"sans-serif"}}},y:{title:{display:!0,text:o,font:{family:"sans-serif"}},ticks:{font:{family:"sans-serif"}}}}};return Z.jsx("div",{style:{position:"relative",height:"300px",width:"100%"},children:Z.jsx(aPe,{options:r,data:s})})},SPe=({spiceString:e,onClose:A,plotData:t,nodes:i,isLoading:n,error:o,simOptions:s,onSimOptionsChange:r,hasRun:a})=>{const[g,c]=AA.useState(String(s.startTime)),[I,l]=AA.useState(String(s.duration));AA.useEffect(()=>{c(String(s.startTime)),l(String(s.duration))},[s.startTime,s.duration]);const B=()=>{r({...s,startTime:Number(g),duration:Number(I)})},C=i.filter(Q=>{const E=Q.toLowerCase().startsWith("v("),h=Q.toLowerCase().startsWith("i(");return!!(s.showVoltage&&E||s.showCurrent&&h)});return Z.jsx("div",{style:{position:"fixed",top:0,left:0,right:0,bottom:0,backgroundColor:"rgba(0, 0, 0, 0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1002,fontFamily:"sans-serif"},children:Z.jsxs("div",{style:{backgroundColor:"white",padding:"24px",borderRadius:"12px",width:"90%",maxWidth:"900px",boxShadow:"0 4px 20px rgba(0, 0, 0, 0.15)"},children:[Z.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"24px",borderBottom:"1px solid #eee",paddingBottom:"16px"},children:[Z.jsx("h2",{style:{margin:0,fontSize:"22px",fontWeight:600,color:"#333"},children:"SPICE Simulation"}),Z.jsx("button",{onClick:A,style:{background:"none",border:"none",fontSize:"28px",cursor:"pointer",color:"#888",padding:0,lineHeight:1},children:"×"})]}),Z.jsx("div",{children:Z.jsx(DPe,{plotData:t,nodes:C,isLoading:n,error:o,hasRun:a})}),Z.jsxs("div",{style:{marginTop:"16px",padding:"12px",backgroundColor:"#f7f7f7",borderRadius:"6px",display:"flex",flexWrap:"wrap",gap:"24px",alignItems:"center",fontSize:"14px"},children:[Z.jsxs("div",{style:{display:"flex",gap:"16px"},children:[Z.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[Z.jsx("input",{type:"checkbox",checked:s.showVoltage,onChange:Q=>r({...s,showVoltage:Q.target.checked})}),"Voltage"]}),Z.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[Z.jsx("input",{type:"checkbox",checked:s.showCurrent,onChange:Q=>r({...s,showCurrent:Q.target.checked})}),"Current"]})]}),Z.jsxs("div",{style:{display:"flex",gap:"16px",alignItems:"center"},children:[Z.jsx("label",{htmlFor:"startTime",children:"Start Time (ms):"}),Z.jsx("input",{id:"startTime",type:"number",value:g,onChange:Q=>c(Q.target.value),style:{width:"80px",padding:"4px 8px",borderRadius:"4px",border:"1px solid #ccc"}}),Z.jsx("label",{htmlFor:"duration",children:"Duration (ms):"}),Z.jsx("input",{id:"duration",type:"number",value:I,onChange:Q=>l(Q.target.value),style:{width:"80px",padding:"4px 8px",borderRadius:"4px",border:"1px solid #ccc"}}),Z.jsx("button",{onClick:B,style:{padding:"4px 12px",borderRadius:"4px",border:"1px solid #ccc",backgroundColor:"#f0f0f0",cursor:"pointer"},children:a?"Rerun":"Run"})]})]}),Z.jsxs("div",{style:{marginTop:"24px"},children:[Z.jsx("h3",{style:{marginTop:0,marginBottom:"12px",fontSize:"18px",fontWeight:600,color:"#333"},children:"SPICE Netlist"}),Z.jsx("pre",{style:{backgroundColor:"#fafafa",padding:"16px",borderRadius:"6px",maxHeight:"150px",overflowY:"auto",border:"1px solid #eee",color:"#333",fontSize:"13px",fontFamily:"monospace"},children:e})]})]})})},bPe="dmFyIGU9bnVsbCxzPWFzeW5jKCk9Pihhd2FpdCBpbXBvcnQoImh0dHBzOi8vY2RuLmpzZGVsaXZyLm5ldC9ucG0vZWVjaXJjdWl0LWVuZ2luZUAxLjUuMi8rZXNtIikpLlNpbXVsYXRpb24sYz1hc3luYygpPT57aWYoZSYmZS5pc0luaXRpYWxpemVkKCkpcmV0dXJuO2xldCBpPWF3YWl0IHMoKTtlPW5ldyBpLGF3YWl0IGUuc3RhcnQoKX07c2VsZi5vbm1lc3NhZ2U9YXN5bmMgaT0+e3RyeXtpZihhd2FpdCBjKCksIWUpdGhyb3cgbmV3IEVycm9yKCJTaW11bGF0aW9uIG5vdCBpbml0aWFsaXplZCIpO2xldCB0PWkuZGF0YS5zcGljZVN0cmluZyxhPXQubWF0Y2goL3dyZGF0YVxzKyhcUyspXHMrKC4qKS9pKTtpZihhKXtsZXQgbz1gLnByb2JlICR7YVsyXS50cmltKCkuc3BsaXQoL1xzKy8pLmpvaW4oIiAiKX1gO3Q9dC5yZXBsYWNlKC93cmRhdGEuKi9pLG8pfWVsc2UgaWYoIXQubWF0Y2goL1wucHJvYmUvaSkpdGhyb3cgdC5tYXRjaCgvcGxvdFxzKyguKikvaSk/bmV3IEVycm9yKCJUaGUgJ3Bsb3QnIGNvbW1hbmQgaXMgbm90IHN1cHBvcnRlZCBmb3IgZGF0YSBleHRyYWN0aW9uLiBQbGVhc2UgdXNlICd3cmRhdGEgPGZpbGVuYW1lPiA8dmFyMT4gLi4uJyBvciAnLnByb2JlIDx2YXIxPiAuLi4nIGluc3RlYWQuIik6bmV3IEVycm9yKCJObyAnLnByb2JlJyBvciAnd3JkYXRhJyBjb21tYW5kIGZvdW5kIGluIFNQSUNFIGZpbGUuIFVzZSAnd3JkYXRhIDxmaWxlbmFtZT4gPHZhcjE+IC4uLicgdG8gc3BlY2lmeSBvdXRwdXQuIik7ZS5zZXROZXRMaXN0KHQpO2xldCBuPWF3YWl0IGUucnVuU2ltKCk7c2VsZi5wb3N0TWVzc2FnZSh7dHlwZToicmVzdWx0IixyZXN1bHQ6bn0pfWNhdGNoKHQpe3NlbGYucG9zdE1lc3NhZ2Uoe3R5cGU6ImVycm9yIixlcnJvcjp0Lm1lc3NhZ2V9KX19Owo=",u9=null,xPe=()=>{if(typeof window>"u")return null;if(u9)return u9;try{const e=new Blob([atob(bPe)],{type:"application/javascript"});return u9=URL.createObjectURL(e),u9}catch(e){return console.error("Failed to create blob URL for worker",e),null}},_Pe=e=>{const A={};if(e.dataType==="real")e.data.forEach(r=>{A[r.name]=r.values});else if(e.dataType==="complex")e.data.forEach(r=>{A[r.name]=r.values.map(a=>a.real)});else throw new Error("Unsupported data type in simulation result");const t=Object.keys(A).find(r=>r.toLowerCase()==="time"||r.toLowerCase()==="frequency");if(!t)throw new Error("No time or frequency data in simulation result");const i=A[t],n=Object.keys(A).filter(r=>r!==t),o=n;return{plotData:i.map((r,a)=>{const g={name:r.toExponential(2)};return n.forEach(c=>{g[c]=A[c][a]}),g}),nodes:o}},kPe=e=>{const[A,t]=AA.useState([]),[i,n]=AA.useState([]),[o,s]=AA.useState(!0),[r,a]=AA.useState(null);return AA.useEffect(()=>{if(!e){s(!1),t([]),n([]),a(null);return}s(!0),a(null),t([]),n([]);const g=xPe();if(!g){a("Could not create SPICE simulation worker."),s(!1);return}const c=new Worker(g,{type:"module"});return c.onmessage=I=>{if(I.data.type==="result")try{const{plotData:l,nodes:B}=_Pe(I.data.result);t(l),n(B)}catch(l){a(l.message||"Failed to parse simulation result"),console.error(l)}else I.data.type==="error"&&a(I.data.error);s(!1)},c.onerror=I=>{a(I.message),s(!1)},c.postMessage({spiceString:e}),()=>{c.terminate()}},[e]),{plotData:A,nodes:i,isLoading:o,error:r}},ydA=e=>{if(e===0)return"0";const A=Math.abs(e),t=i=>i.toPrecision(4);return A>=1?t(e):A>=.001?`${t(e*1e3)}m`:A>=1e-6?`${t(e*1e6)}u`:A>=1e-9?`${t(e*1e9)}n`:A>=1e-12?`${t(e*1e12)}p`:A>=1e-15?`${t(e*1e15)}f`:e.toExponential(3)},FPe=(e,A)=>{const i=EPA(e).toSpiceString(),o=i.split(`
5375
+ `,n.appendChild(u)}})}};o();const s=new MutationObserver(o);return s.observe(n,{childList:!0,subtree:!1,characterData:!1}),()=>{s.disconnect()}},[e,t,A,i])},Eot=["#8B0000","#2F4F4F","#191970","#006400","#FF4500","#800080","#2E8B57","#B8860B","#C71585","#008B8B"],IPe=e=>{const{svgDivRef:A,circuitJson:t,circuitJsonKey:i,showGroups:n}=e;AA.useEffect(()=>{if(A.current&&A.current.querySelectorAll(".schematic-group-overlay").forEach(r=>r.remove()),!A.current||!n||!t||t.length===0)return;const o=setTimeout(()=>{if(!A.current)return;const s=A.current.querySelector("svg");if(!s)return;s.querySelectorAll(".schematic-group-overlay").forEach(a=>a.remove());try{const a=wh(t).source_group?.list().filter(u=>!u.is_subcircuit)||[],g=wh(t).schematic_component?.list()||[],c=new Map;a.forEach(u=>{const d=u;if(d.parent_source_group_id){const f=c.get(d.parent_source_group_id)||[];f.push(u.source_group_id),c.set(d.parent_source_group_id,f)}});const I=u=>{const d=[],f=c.get(u)||[];for(const m of f)d.push(m),d.push(...I(m));return d},l=u=>{const d=a.find(f=>f.source_group_id===u);return d?.parent_source_group_id?1+l(d.parent_source_group_id):0},B=a.length>0&&a.some(u=>u.name&&u.name.trim()!=="");let C=[];if(B){const u=new Map;for(const d of g){const f=wh(t).source_component.get(d.source_component_id);f?.source_group_id&&(u.has(f.source_group_id)||u.set(f.source_group_id,[]),u.get(f.source_group_id).push(d))}a.forEach((d,f)=>{let m=u.get(d.source_group_id)||[];const w=I(d.source_group_id);for(const D of w){const b=u.get(D)||[];m=[...m,...b]}if(m.length>0){const D=l(d.source_group_id),b=I(d.source_group_id).length>0;if(d.name?.startsWith("unnamed_board"))return;C.push({id:d.source_group_id,name:d.name||`Group ${f+1}`,components:m,color:Eot[f%Eot.length],depthLevel:D,hasChildren:b,sourceGroupId:d.source_group_id})}})}const Q=s.viewBox.baseVal,E=s.getBoundingClientRect(),h=Math.min(E.width/Q.width,E.height/Q.height)||1;C.sort((u,d)=>u.depthLevel-d.depthLevel),C.forEach(u=>{if(u.components.length===0)return;const d=lPe(u.components,s);if(!d)return;const f=Math.max(8,Math.min(25,15/Math.max(h,.3))),m=u.hasChildren?f*.6:0,w=f+m,D=Math.max(1,2/Math.max(h,.5)),b=u.depthLevel===0?D:D*.7,k=Math.max(4,8/Math.max(h,.5)),x=u.hasChildren?1.3:1,N=k*x,R=N*.5,U=document.createElementNS("http://www.w3.org/2000/svg","rect");U.setAttribute("class","schematic-group-overlay"),U.setAttribute("x",(d.minX-w).toString()),U.setAttribute("y",(d.minY-w).toString()),U.setAttribute("width",(d.maxX-d.minX+w*2).toString()),U.setAttribute("height",(d.maxY-d.minY+w*2).toString()),U.setAttribute("fill","none"),U.setAttribute("stroke",u.color),U.setAttribute("stroke-width",b.toString()),U.setAttribute("stroke-dasharray",`${N},${R}`),U.setAttribute("opacity","0.8"),U.setAttribute("rx","0"),U.setAttribute("ry","0");const T=Math.max(6,Math.min(20,14/Math.max(h,.2))),Y=u.depthLevel===0||u.depthLevel===1?0:u.depthLevel*.2,O=T*(1-Y),W=Math.max(1,O*.2),X=u.name,iA=document.createElementNS("http://www.w3.org/2000/svg","text");iA.setAttribute("font-size",O.toString()),iA.setAttribute("font-family","Arial, sans-serif"),iA.textContent=X,s.appendChild(iA);const aA=iA.getBBox();s.removeChild(iA);const tA=aA.width+W*2,oA=O+W*2,rA=d.minX-w,CA=d.minY-w-oA,SA=document.createElementNS("http://www.w3.org/2000/svg","rect");SA.setAttribute("class","schematic-group-overlay"),SA.setAttribute("x",rA.toString()),SA.setAttribute("y",(CA-oA).toString()),SA.setAttribute("width",tA.toString()),SA.setAttribute("height",oA.toString()),SA.setAttribute("fill","transparent"),SA.setAttribute("rx","0"),SA.setAttribute("ry","0");const MA=document.createElementNS("http://www.w3.org/2000/svg","text");MA.setAttribute("class","schematic-group-overlay"),MA.setAttribute("x",(rA+W).toString()),MA.setAttribute("y",(CA+oA-W).toString()),MA.setAttribute("fill",u.color),MA.setAttribute("font-size",O.toString()),MA.setAttribute("font-family","Arial, sans-serif"),MA.setAttribute("font-weight",u.depthLevel===0?"600":"500"),MA.setAttribute("stroke",u.color),MA.setAttribute("stroke-width",Math.max(.2,O*.02).toString()),MA.textContent=X,s.appendChild(U),s.appendChild(SA),s.appendChild(MA)})}catch(a){console.error("Error creating group overlays:",a)}},10);return()=>clearTimeout(o)},[A,i,n])};function lPe(e,A){let t=1/0,i=1/0,n=-1/0,o=-1/0;for(const r of e){let a=A.querySelector(`g[data-schematic-component-id="${r.schematic_component_id}"]`);if(a||(a=A.querySelector(`[data-schematic-component-id="${r.schematic_component_id}"]`)),a){const g=a.getBBox();t=Math.min(t,g.x),i=Math.min(i,g.y),n=Math.max(n,g.x+g.width),o=Math.max(o,g.y+g.height)}}return t===1/0?null:{minX:t,minY:i,maxX:n,maxY:o}}var BPe=Bc("schematic-viewer"),CPe=()=>{Bc.enable("schematic-viewer*")},QPe=BPe,hot=e=>{const[A,t]=AA.useState(0),[i,n]=AA.useState(0);return AA.useEffect(()=>{if(!e.current)return;const o=()=>{const r=e.current?.getBoundingClientRect();t(r?.width||0),n(r?.height||0)};o();const s=new ResizeObserver(o);return s.observe(e.current),window.addEventListener("resize",o),()=>{s.disconnect(),window.removeEventListener("resize",o)}},[]),{containerWidth:A,containerHeight:i}},EPe=QPe.extend("useComponentDragging"),hPe=({onEditEvent:e,editEvents:A=[],circuitJson:t,cancelDrag:i,svgToScreenProjection:n,realToSvgProjection:o,enabled:s=!1,snapToGrid:r=!1})=>{const[a,g]=AA.useState(null),c=bl(o,n),I=AA.useRef(null),l=AA.useRef(null),B=AA.useRef(new Map);AA.useEffect(()=>{A.forEach(D=>{"edit_event_type"in D&&D.edit_event_type==="edit_schematic_component_location"&&!D.in_progress&&B.current.set(D.schematic_component_id,{...D.new_center})})},[A]);const C=AA.useCallback((D,b,k)=>{if(!s)return!1;const x=k.closest('[data-circuit-json-type="schematic_component"]');if(!x)return!1;const N=x.getAttribute("data-schematic-component-id");if(!N)return!1;i&&i();const R=wh(t).schematic_component.get(N);if(!R)return!1;I.current={x:D,y:b};let U;const T=B.current.get(N);if(T)U={...T};else{const O=Qot({editEvents:A,schematic_component_id:N});U={x:R.center.x+O.x,y:R.center.y+O.y},B.current.set(N,{...U})}const Y={edit_event_id:Math.random().toString(36).substr(2,9),edit_event_type:"edit_schematic_component_location",schematic_component_id:N,original_center:U,new_center:{...U},in_progress:!0,created_at:Date.now(),_element:x};return l.current=Y,g(Y),!0},[i,s,t,A]),Q=AA.useCallback(D=>{C(D.clientX,D.clientY,D.target)},[C]),E=AA.useCallback(D=>{if(D.touches.length!==1)return;const b=D.touches[0];C(b.clientX,b.clientY,D.target)&&D.preventDefault()},[C]),h=AA.useCallback((D,b)=>{if(!l.current||!I.current)return;const k={x:D-I.current.x,y:b-I.current.y},x={x:k.x/c.a,y:k.y/c.d};let N={x:l.current.original_center.x+x.x,y:l.current.original_center.y+x.y};if(r){const U=T=>Math.round(T*10)/10;N={x:U(N.x),y:U(N.y)}}const R={...l.current,new_center:N};l.current=R,g(R)},[c,r]),u=AA.useCallback(D=>h(D.clientX,D.clientY),[h]),d=AA.useCallback(D=>{if(D.touches.length!==1||!l.current)return;D.preventDefault();const b=D.touches[0];h(b.clientX,b.clientY)},[h]),f=AA.useCallback(()=>{if(!l.current)return;const D={...l.current,in_progress:!1};B.current.set(D.schematic_component_id,{...D.new_center}),EPe("endDrag calling onEditEvent with new edit event",{newEditEvent:D}),e&&e(D),l.current=null,I.current=null,g(null)},[e]),m=AA.useCallback(()=>f(),[f]),w=AA.useCallback(()=>f(),[f]);return AA.useEffect(()=>(window.addEventListener("mousemove",u),window.addEventListener("mouseup",m),window.addEventListener("touchmove",d,{passive:!1}),window.addEventListener("touchend",w),()=>{window.removeEventListener("mousemove",u),window.removeEventListener("mouseup",m),window.removeEventListener("touchmove",d),window.removeEventListener("touchend",w)}),[u,m,d,w]),{handleMouseDown:Q,handleTouchStart:E,isDragging:!!l.current,activeEditEvent:a}},kD={schematicEditIcon:50,schematicGridIcon:49,spiceSimulationIcon:50,viewMenuIcon:48,viewMenu:55,viewMenuBackdrop:54,clickToInteractOverlay:100,schematicComponentHoverOutline:47,schematicPortHoverOutline:48},uPe=({onClick:e,active:A})=>{const t=i=>{i.preventDefault(),e()};return Z.jsx("div",{onClick:t,onTouchEnd:t,title:A?"Disable edit mode":"Enable edit mode",style:{position:"absolute",top:"16px",right:"64px",backgroundColor:A?"#4CAF50":"#fff",color:A?"#fff":"#000",padding:"8px",borderRadius:"4px",cursor:"pointer",boxShadow:"0 2px 4px rgba(0,0,0,0.1)",display:"flex",alignItems:"center",gap:"4px",zIndex:kD.schematicEditIcon},children:Z.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[Z.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),Z.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]})})},dPe=({onClick:e,active:A})=>{const t=i=>{i.preventDefault(),e()};return Z.jsx("div",{onClick:t,onTouchEnd:t,title:A?"Hide grid":"Show grid",style:{position:"absolute",top:"56px",right:"64px",backgroundColor:A?"#4CAF50":"#fff",color:A?"#fff":"#000",padding:"8px",borderRadius:"4px",cursor:"pointer",boxShadow:"0 2px 4px rgba(0,0,0,0.1)",display:"flex",alignItems:"center",gap:"4px",zIndex:kD.schematicGridIcon},children:Z.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:Z.jsx("path",{d:"M3 3h7v7H3zM14 3h7v7h-7zM3 14h7v7H3zM14 14h7v7h-7z"})})})},pPe=({onClick:e,active:A})=>{const t=i=>{i.preventDefault(),e()};return Z.jsx("div",{onClick:t,onTouchEnd:t,title:A?"Hide view menu":"Show view menu",style:{position:"absolute",top:"16px",right:"16px",backgroundColor:A?"#4CAF50":"#fff",color:A?"#fff":"#000",padding:"8px",borderRadius:"4px",cursor:"pointer",boxShadow:"0 2px 4px rgba(0,0,0,0.1)",display:"flex",alignItems:"center",gap:"4px",zIndex:kD.viewMenuIcon},children:Z.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[Z.jsx("circle",{cx:"12",cy:"12",r:"1"}),Z.jsx("circle",{cx:"12",cy:"5",r:"1"}),Z.jsx("circle",{cx:"12",cy:"19",r:"1"})]})})},fPe={version:"2.0.56"},yPe=({circuitJson:e,circuitJsonKey:A,isVisible:t,onClose:i,showGroups:n,onToggleGroups:o,showGrid:s,onToggleGrid:r})=>{const a=AA.useMemo(()=>{if(!e||e.length===0)return!1;try{if((wh(e).source_group?.list()||[]).length>0)return!0;const c=wh(e).schematic_component?.list()||[];if(c.length>1){const I=new Set;for(const l of c){const B=wh(e).source_component.get(l.source_component_id);B?.ftype&&I.add(B.ftype)}return I.size>1}return!1}catch(g){return console.error("Error checking for groups:",g),!1}},[A]);return t?Z.jsxs(Z.Fragment,{children:[Z.jsx("div",{onClick:i,onTouchEnd:g=>{g.preventDefault(),i()},style:{position:"absolute",inset:0,backgroundColor:"transparent",zIndex:kD.viewMenuBackdrop}}),Z.jsxs("div",{style:{position:"absolute",top:"56px",right:"16px",backgroundColor:"#ffffff",color:"#000000",border:"1px solid #ccc",borderRadius:"4px",boxShadow:"0 4px 12px rgba(0,0,0,0.1)",minWidth:"200px",zIndex:kD.viewMenu},children:[Z.jsxs("div",{onClick:()=>{a&&o(!n)},onTouchEnd:g=>{g.preventDefault(),a&&o(!n)},style:{padding:"8px 12px",cursor:a?"pointer":"not-allowed",opacity:a?1:.5,fontSize:"13px",color:"#000000",fontFamily:"sans-serif",display:"flex",alignItems:"center",gap:"8px"},onMouseEnter:g=>{a&&(g.currentTarget.style.backgroundColor="#f0f0f0")},onMouseLeave:g=>{a&&(g.currentTarget.style.backgroundColor="transparent")},children:[Z.jsx("div",{style:{width:"16px",height:"16px",border:"2px solid #000",borderRadius:"2px",backgroundColor:"transparent",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"10px",fontWeight:"bold"},children:n&&"✓"}),"View Schematic Groups"]}),!a&&Z.jsx("div",{style:{padding:"8px 12px",fontSize:"11px",color:"#666",fontStyle:"italic"},children:"No groups found in this schematic"}),Z.jsxs("div",{onClick:()=>r(!s),onTouchEnd:g=>{g.preventDefault(),r(!s)},style:{padding:"8px 12px",cursor:"pointer",fontSize:"13px",color:"#000000",fontFamily:"sans-serif",display:"flex",alignItems:"center",gap:"8px"},onMouseEnter:g=>{g.currentTarget.style.backgroundColor="#f0f0f0"},onMouseLeave:g=>{g.currentTarget.style.backgroundColor="transparent"},children:[Z.jsx("div",{style:{width:"16px",height:"16px",border:"2px solid #000",borderRadius:"2px",backgroundColor:"transparent",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"10px",fontWeight:"bold"},children:s&&"✓"}),"Show Grid"]}),Z.jsxs("div",{style:{padding:"4px 8px",fontSize:"12px",color:"#999",borderTop:"1px solid #eee",textAlign:"center"},children:["v",String(fPe?.version)]})]})]}):null},mPe=()=>Z.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:Z.jsx("path",{d:"M3 12h2.5l2.5-9 4 18 4-9h5.5"})}),wPe=({onClick:e})=>Z.jsx("div",{onClick:e,title:"Run SPICE simulation",style:{position:"absolute",top:"16px",right:"112px",backgroundColor:"#fff",color:"#000",padding:"8px",borderRadius:"4px",cursor:"pointer",boxShadow:"0 2px 4px rgba(0,0,0,0.1)",display:"flex",alignItems:"center",gap:"4px",zIndex:kD.spiceSimulationIcon},children:Z.jsx(mPe,{})});B9.register(jKe,$Ke,kKe,_Ke,UKe,OKe,vKe);var h9=["#8884d8","#82ca9d","#ffc658","#ff7300","#387908"],uot=e=>{if(e===0)return"0s";const A=Math.abs(e);let t="s",i=1;return A<1e-12?(t="fs",i=1e15):A<1e-9?(t="ps",i=1e12):A<1e-6?(t="ns",i=1e9):A<.001?(t="us",i=1e6):A<1&&(t="ms",i=1e3),`${parseFloat((e*i).toPrecision(3))}${t}`},DPe=({plotData:e,nodes:A,isLoading:t,error:i,hasRun:n})=>{const o=AA.useMemo(()=>{const a=A.some(c=>c.toLowerCase().startsWith("v(")),g=A.some(c=>c.toLowerCase().startsWith("i("));return a&&g?"Value":a?"Voltage (V)":g?"Current (A)":"Value"},[A]);if(t)return Z.jsx("div",{style:{height:"300px",width:"100%",display:"flex",alignItems:"center",justifyContent:"center"},children:"Running simulation..."});if(!n)return Z.jsx("div",{style:{height:"300px",width:"100%",display:"flex",alignItems:"center",justifyContent:"center"},children:'Click "Run" to start the simulation.'});if(i)return Z.jsxs("div",{style:{height:"300px",width:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"red"},children:["Error: ",i]});if(e.length===0)return Z.jsx("div",{style:{height:"300px",width:"100%",display:"flex",alignItems:"center",justifyContent:"center"},children:"No data to plot. Check simulation output or SPICE netlist."});const s={datasets:A.map((a,g)=>({label:a,data:e.map(c=>({x:Number(c.name),y:c[a]})),borderColor:h9[g%h9.length],backgroundColor:h9[g%h9.length],fill:!1,tension:.1}))},r={responsive:!0,maintainAspectRatio:!1,plugins:{legend:{position:"top",labels:{font:{family:"sans-serif"}}},title:{display:!1},tooltip:{callbacks:{title:a=>{if(a.length>0){const g=a[0];return uot(g.parsed.x)}return""}}}},scales:{x:{type:"linear",title:{display:!0,text:"Time",font:{family:"sans-serif"}},ticks:{callback:a=>uot(a),font:{family:"sans-serif"}}},y:{title:{display:!0,text:o,font:{family:"sans-serif"}},ticks:{font:{family:"sans-serif"}}}}};return Z.jsx("div",{style:{position:"relative",height:"300px",width:"100%"},children:Z.jsx(aPe,{options:r,data:s})})},SPe=({spiceString:e,onClose:A,plotData:t,nodes:i,isLoading:n,error:o,simOptions:s,onSimOptionsChange:r,hasRun:a})=>{const[g,c]=AA.useState(String(s.startTime)),[I,l]=AA.useState(String(s.duration));AA.useEffect(()=>{c(String(s.startTime)),l(String(s.duration))},[s.startTime,s.duration]);const B=()=>{r({...s,startTime:Number(g),duration:Number(I)})},C=i.filter(Q=>{const E=Q.toLowerCase().startsWith("v("),h=Q.toLowerCase().startsWith("i(");return!!(s.showVoltage&&E||s.showCurrent&&h)});return Z.jsx("div",{style:{position:"fixed",top:0,left:0,right:0,bottom:0,backgroundColor:"rgba(0, 0, 0, 0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1002,fontFamily:"sans-serif"},children:Z.jsxs("div",{style:{backgroundColor:"white",padding:"24px",borderRadius:"12px",width:"90%",maxWidth:"900px",boxShadow:"0 4px 20px rgba(0, 0, 0, 0.15)"},children:[Z.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"24px",borderBottom:"1px solid #eee",paddingBottom:"16px"},children:[Z.jsx("h2",{style:{margin:0,fontSize:"22px",fontWeight:600,color:"#333"},children:"SPICE Simulation"}),Z.jsx("button",{onClick:A,style:{background:"none",border:"none",fontSize:"28px",cursor:"pointer",color:"#888",padding:0,lineHeight:1},children:"×"})]}),Z.jsx("div",{children:Z.jsx(DPe,{plotData:t,nodes:C,isLoading:n,error:o,hasRun:a})}),Z.jsxs("div",{style:{marginTop:"16px",padding:"12px",backgroundColor:"#f7f7f7",borderRadius:"6px",display:"flex",flexWrap:"wrap",gap:"24px",alignItems:"center",fontSize:"14px"},children:[Z.jsxs("div",{style:{display:"flex",gap:"16px"},children:[Z.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[Z.jsx("input",{type:"checkbox",checked:s.showVoltage,onChange:Q=>r({...s,showVoltage:Q.target.checked})}),"Voltage"]}),Z.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[Z.jsx("input",{type:"checkbox",checked:s.showCurrent,onChange:Q=>r({...s,showCurrent:Q.target.checked})}),"Current"]})]}),Z.jsxs("div",{style:{display:"flex",gap:"16px",alignItems:"center"},children:[Z.jsx("label",{htmlFor:"startTime",children:"Start Time (ms):"}),Z.jsx("input",{id:"startTime",type:"number",value:g,onChange:Q=>c(Q.target.value),style:{width:"80px",padding:"4px 8px",borderRadius:"4px",border:"1px solid #ccc"}}),Z.jsx("label",{htmlFor:"duration",children:"Duration (ms):"}),Z.jsx("input",{id:"duration",type:"number",value:I,onChange:Q=>l(Q.target.value),style:{width:"80px",padding:"4px 8px",borderRadius:"4px",border:"1px solid #ccc"}}),Z.jsx("button",{onClick:B,style:{padding:"4px 12px",borderRadius:"4px",border:"1px solid #ccc",backgroundColor:"#f0f0f0",cursor:"pointer"},children:a?"Rerun":"Run"})]})]}),Z.jsxs("div",{style:{marginTop:"24px"},children:[Z.jsx("h3",{style:{marginTop:0,marginBottom:"12px",fontSize:"18px",fontWeight:600,color:"#333"},children:"SPICE Netlist"}),Z.jsx("pre",{style:{backgroundColor:"#fafafa",padding:"16px",borderRadius:"6px",maxHeight:"150px",overflowY:"auto",border:"1px solid #eee",color:"#333",fontSize:"13px",fontFamily:"monospace"},children:e})]})]})})},bPe="dmFyIGU9bnVsbCxzPWFzeW5jKCk9Pihhd2FpdCBpbXBvcnQoImh0dHBzOi8vY2RuLmpzZGVsaXZyLm5ldC9ucG0vZWVjaXJjdWl0LWVuZ2luZUAxLjUuMi8rZXNtIikpLlNpbXVsYXRpb24sYz1hc3luYygpPT57aWYoZSYmZS5pc0luaXRpYWxpemVkKCkpcmV0dXJuO2xldCBpPWF3YWl0IHMoKTtlPW5ldyBpLGF3YWl0IGUuc3RhcnQoKX07c2VsZi5vbm1lc3NhZ2U9YXN5bmMgaT0+e3RyeXtpZihhd2FpdCBjKCksIWUpdGhyb3cgbmV3IEVycm9yKCJTaW11bGF0aW9uIG5vdCBpbml0aWFsaXplZCIpO2xldCB0PWkuZGF0YS5zcGljZVN0cmluZyxhPXQubWF0Y2goL3dyZGF0YVxzKyhcUyspXHMrKC4qKS9pKTtpZihhKXtsZXQgbz1gLnByb2JlICR7YVsyXS50cmltKCkuc3BsaXQoL1xzKy8pLmpvaW4oIiAiKX1gO3Q9dC5yZXBsYWNlKC93cmRhdGEuKi9pLG8pfWVsc2UgaWYoIXQubWF0Y2goL1wucHJvYmUvaSkpdGhyb3cgdC5tYXRjaCgvcGxvdFxzKyguKikvaSk/bmV3IEVycm9yKCJUaGUgJ3Bsb3QnIGNvbW1hbmQgaXMgbm90IHN1cHBvcnRlZCBmb3IgZGF0YSBleHRyYWN0aW9uLiBQbGVhc2UgdXNlICd3cmRhdGEgPGZpbGVuYW1lPiA8dmFyMT4gLi4uJyBvciAnLnByb2JlIDx2YXIxPiAuLi4nIGluc3RlYWQuIik6bmV3IEVycm9yKCJObyAnLnByb2JlJyBvciAnd3JkYXRhJyBjb21tYW5kIGZvdW5kIGluIFNQSUNFIGZpbGUuIFVzZSAnd3JkYXRhIDxmaWxlbmFtZT4gPHZhcjE+IC4uLicgdG8gc3BlY2lmeSBvdXRwdXQuIik7ZS5zZXROZXRMaXN0KHQpO2xldCBuPWF3YWl0IGUucnVuU2ltKCk7c2VsZi5wb3N0TWVzc2FnZSh7dHlwZToicmVzdWx0IixyZXN1bHQ6bn0pfWNhdGNoKHQpe3NlbGYucG9zdE1lc3NhZ2Uoe3R5cGU6ImVycm9yIixlcnJvcjp0Lm1lc3NhZ2V9KX19Owo=",u9=null,xPe=()=>{if(typeof window>"u")return null;if(u9)return u9;try{const e=new Blob([atob(bPe)],{type:"application/javascript"});return u9=URL.createObjectURL(e),u9}catch(e){return console.error("Failed to create blob URL for worker",e),null}},_Pe=e=>{const A={};if(e.dataType==="real")e.data.forEach(r=>{A[r.name]=r.values});else if(e.dataType==="complex")e.data.forEach(r=>{A[r.name]=r.values.map(a=>a.real)});else throw new Error("Unsupported data type in simulation result");const t=Object.keys(A).find(r=>r.toLowerCase()==="time"||r.toLowerCase()==="frequency");if(!t)throw new Error("No time or frequency data in simulation result");const i=A[t],n=Object.keys(A).filter(r=>r!==t),o=n;return{plotData:i.map((r,a)=>{const g={name:r.toExponential(2)};return n.forEach(c=>{g[c]=A[c][a]}),g}),nodes:o}},kPe=e=>{const[A,t]=AA.useState([]),[i,n]=AA.useState([]),[o,s]=AA.useState(!0),[r,a]=AA.useState(null);return AA.useEffect(()=>{if(!e){s(!1),t([]),n([]),a(null);return}s(!0),a(null),t([]),n([]);const g=xPe();if(!g){a("Could not create SPICE simulation worker."),s(!1);return}const c=new Worker(g,{type:"module"});return c.onmessage=I=>{if(I.data.type==="result")try{const{plotData:l,nodes:B}=_Pe(I.data.result);t(l),n(B)}catch(l){a(l.message||"Failed to parse simulation result"),console.error(l)}else I.data.type==="error"&&a(I.data.error);s(!1)},c.onerror=I=>{a(I.message),s(!1)},c.postMessage({spiceString:e}),()=>{c.terminate()}},[e]),{plotData:A,nodes:i,isLoading:o,error:r}},ydA=e=>{if(e===0)return"0";const A=Math.abs(e),t=i=>i.toPrecision(4);return A>=1?t(e):A>=.001?`${t(e*1e3)}m`:A>=1e-6?`${t(e*1e6)}u`:A>=1e-9?`${t(e*1e9)}n`:A>=1e-12?`${t(e*1e12)}p`:A>=1e-15?`${t(e*1e15)}f`:e.toExponential(3)},FPe=(e,A)=>{const i=EPA(e).toSpiceString(),o=i.split(`
5376
5376
  `).filter(x=>x.trim()!=="").filter(x=>!x.startsWith("*")&&!x.startsWith(".")&&x.trim()!==""),s=new Set,r=new Set,a=new Set;for(const x of o){const N=x.trim().split(/\s+/);if(N.length<3)continue;const R=N[0],U=R[0].toUpperCase();let T=[];if(["R","C","L","V","I","D"].includes(U))T=N.slice(1,3),U==="V"&&a.add(R);else if(U==="Q"&&N.length>=4)T=N.slice(1,4);else if(U==="M"&&N.length>=5)T=N.slice(1,5);else if(U==="X")T=N.slice(1,-1);else continue;T.forEach(Y=>s.add(Y)),U==="C"&&T.forEach(Y=>r.add(Y))}s.delete("0"),r.delete("0");const g=Array.from(r).map(x=>`.ic V(${x})=0`),c=[],I=Array.from(s).map(x=>`V(${x})`);c.push(...I);const l=Array.from(a).map(x=>`I(${x})`);c.push(...l);const B=c.length>0?`.probe ${c.join(" ")}`:"",C=A?.startTime??0,Q=A?.duration??20,E=C*.001,h=Q*.001,u=E+h,d=h/50,f=`.tran ${ydA(d)} ${ydA(u)} ${ydA(E)} UIC`,m=".end",w=i.split(`
5377
5377
  `);let D=-1;for(let x=w.length-1;x>=0;x--)if(w[x].trim().toLowerCase().startsWith(m)){D=x;break}const b=[...g,B,f].filter(Boolean);let k;if(D!==-1){const x=w.slice(0,D),N=w.slice(D);k=[...x,...b,...N]}else k=[...w,...b,m];return k.join(`
5378
5378
  `)},GPe=(e,A)=>{if(typeof window>"u")return A;try{const t=localStorage.getItem(e);return t!==null?JSON.parse(t):A}catch{return A}},MPe=(e,A)=>{if(!(typeof window>"u"))try{localStorage.setItem(e,JSON.stringify(A))}catch{}},mdA=AA.createContext(null),RPe=5,NPe=(e,A)=>!e&&!A?!0:!e||!A?!1:e.minX===A.minX&&e.maxX===A.maxX&&e.minY===A.minY&&e.maxY===A.maxY,vPe=({children:e})=>{if(AA.useContext(mdA))return Z.jsx(Z.Fragment,{children:e});const t=AA.useRef({pointer:null,boundingBoxes:new Map,hoveringIds:new Set,subscribers:new Set,mouseDownPosition:null}),i=AA.useCallback(()=>{for(const I of t.current.subscribers)I()},[]),n=AA.useCallback(()=>{const I=t.current.pointer,l=new Set;if(I)for(const[C,Q]of t.current.boundingBoxes){const E=Q.bounds;E&&I.x>=E.minX&&I.x<=E.maxX&&I.y>=E.minY&&I.y<=E.maxY&&l.add(C)}const B=t.current.hoveringIds;l.size===B.size&&[...l].every(C=>B.has(C))||(t.current.hoveringIds=l,i())},[i]),o=AA.useCallback((I,l)=>{t.current.boundingBoxes.set(I,l),n()},[n]),s=AA.useCallback((I,l)=>{const B=t.current.boundingBoxes.get(I);B&&NPe(B.bounds,l.bounds)&&B.onClick===l.onClick||(t.current.boundingBoxes.set(I,l),n())},[n]),r=AA.useCallback(I=>{t.current.boundingBoxes.delete(I)&&n()},[n]),a=AA.useCallback(I=>(t.current.subscribers.add(I),()=>{t.current.subscribers.delete(I)}),[]),g=AA.useCallback(I=>t.current.hoveringIds.has(I),[]);AA.useEffect(()=>{const I=Q=>{const{clientX:E,clientY:h}=Q,u=t.current.pointer;u&&u.x===E&&u.y===h||(t.current.pointer={x:E,y:h},n())},l=()=>{t.current.pointer!==null&&(t.current.pointer=null,t.current.mouseDownPosition=null,n())},B=Q=>{t.current.mouseDownPosition={x:Q.clientX,y:Q.clientY}},C=Q=>{const{clientX:E,clientY:h}=Q,u=t.current.mouseDownPosition;if(u&&Math.sqrt(Math.pow(E-u.x,2)+Math.pow(h-u.y,2))>RPe){t.current.mouseDownPosition=null;return}t.current.mouseDownPosition=null;for(const d of t.current.boundingBoxes.values()){const f=d.bounds;f&&E>=f.minX&&E<=f.maxX&&h>=f.minY&&h<=f.maxY&&d.onClick?.(Q)}};return window.addEventListener("pointermove",I,{passive:!0}),window.addEventListener("pointerdown",I,{passive:!0}),window.addEventListener("pointerup",I,{passive:!0}),window.addEventListener("pointerleave",l),window.addEventListener("pointercancel",l),window.addEventListener("blur",l),window.addEventListener("mousedown",B,{passive:!0}),window.addEventListener("click",C,{passive:!0}),()=>{window.removeEventListener("pointermove",I),window.removeEventListener("pointerdown",I),window.removeEventListener("pointerup",I),window.removeEventListener("pointerleave",l),window.removeEventListener("pointercancel",l),window.removeEventListener("blur",l),window.removeEventListener("mousedown",B),window.removeEventListener("click",C)}},[n]);const c=AA.useMemo(()=>({registerBoundingBox:o,updateBoundingBox:s,unregisterBoundingBox:r,subscribe:a,isHovering:g}),[o,s,r,a,g]);return Z.jsx(mdA.Provider,{value:c,children:e})},dot=e=>{const A=AA.useContext(mdA);if(!A)throw new Error("useMouseEventsOverBoundingBox must be used within a MouseTracker");const t=AA.useId(),i=AA.useRef(e);i.current=e;const n=AA.useMemo(()=>s=>{i.current.onClick?.(s)},[]);return AA.useEffect(()=>(A.registerBoundingBox(t,{bounds:i.current.bounds,onClick:i.current.onClick?n:void 0}),()=>{A.unregisterBoundingBox(t)}),[A,n,t]),AA.useEffect(()=>{A.updateBoundingBox(t,{bounds:i.current.bounds,onClick:i.current.onClick?n:void 0})},[A,n,t,e.bounds?.minX,e.bounds?.maxX,e.bounds?.minY,e.bounds?.maxY,e.onClick]),{hovering:AA.useSyncExternalStore(A.subscribe,()=>A.isHovering(t),()=>!1)}},LPe=(e,A)=>!e&&!A?!0:!e||!A?!1:Math.abs(e.bounds.minX-A.bounds.minX)<.5&&Math.abs(e.bounds.maxX-A.bounds.maxX)<.5&&Math.abs(e.bounds.minY-A.bounds.minY)<.5&&Math.abs(e.bounds.maxY-A.bounds.maxY)<.5&&Math.abs(e.rect.left-A.rect.left)<.5&&Math.abs(e.rect.top-A.rect.top)<.5&&Math.abs(e.rect.width-A.rect.width)<.5&&Math.abs(e.rect.height-A.rect.height)<.5,UPe=({componentId:e,svgDivRef:A,containerRef:t,onComponentClick:i,onHoverChange:n,showOutline:o,circuitJsonKey:s})=>{const[r,a]=AA.useState(null),g=AA.useRef(null),c=AA.useCallback(()=>{g.current=null;const E=A.current,h=t.current;if(!E||!h){a(w=>w&&null);return}const u=E.querySelector(`[data-schematic-component-id="${e}"]`);if(!u){a(w=>w&&null);return}const d=u.getBoundingClientRect(),f=h.getBoundingClientRect(),m={bounds:{minX:d.left,maxX:d.right,minY:d.top,maxY:d.bottom},rect:{left:d.left-f.left,top:d.top-f.top,width:d.width,height:d.height}};a(w=>LPe(w,m)?w:m)},[e,t,A]),I=AA.useCallback(()=>{g.current===null&&(g.current=window.requestAnimationFrame(c))},[c]);AA.useEffect(()=>{I()},[I,s]),AA.useEffect(()=>{I();const E=A.current,h=t.current;if(!E||!h)return;const u=typeof ResizeObserver<"u"?new ResizeObserver(()=>{I()}):null;u?.observe(h),u?.observe(E);const d=typeof MutationObserver<"u"?new MutationObserver(()=>{I()}):null;return d?.observe(E,{attributes:!0,attributeFilter:["style","transform"],subtree:!0,childList:!0}),window.addEventListener("scroll",I,!0),window.addEventListener("resize",I),()=>{u?.disconnect(),d?.disconnect(),window.removeEventListener("scroll",I,!0),window.removeEventListener("resize",I),g.current!==null&&(cancelAnimationFrame(g.current),g.current=null)}},[I,A,t]);const l=AA.useCallback(E=>{i&&i(e,E)},[e,i]),B=r?.bounds??null,{hovering:C}=dot({bounds:B,onClick:i?l:void 0});if(AA.useEffect(()=>{n&&n(e,C)},[C,e,n]),!r||!C||!o)return null;const Q=r.rect;return Z.jsx("div",{style:{position:"absolute",left:Q.left,top:Q.top,width:Q.width,height:Q.height,border:"1.5px solid rgba(51, 153, 255, 0.9)",pointerEvents:"none",zIndex:kD.schematicComponentHoverOutline}})},HPe=(e,A)=>!e&&!A?!0:!e||!A?!1:Math.abs(e.bounds.minX-A.bounds.minX)<.5&&Math.abs(e.bounds.maxX-A.bounds.maxX)<.5&&Math.abs(e.bounds.minY-A.bounds.minY)<.5&&Math.abs(e.bounds.maxY-A.bounds.maxY)<.5&&Math.abs(e.rect.left-A.rect.left)<.5&&Math.abs(e.rect.top-A.rect.top)<.5&&Math.abs(e.rect.width-A.rect.width)<.5&&Math.abs(e.rect.height-A.rect.height)<.5,YPe=({portId:e,portLabel:A,svgDivRef:t,containerRef:i,onPortClick:n,onHoverChange:o,showOutline:s,circuitJsonKey:r})=>{const[a,g]=AA.useState(null),c=AA.useRef(null),I=AA.useCallback(()=>{c.current=null;const h=t.current,u=i.current;if(!h||!u){g(b=>b&&null);return}const d=h.querySelector(`[data-schematic-port-id="${e}"]`);if(!d){g(b=>b&&null);return}const f=d.getBoundingClientRect(),m=u.getBoundingClientRect(),w=4,D={bounds:{minX:f.left-w,maxX:f.right+w,minY:f.top-w,maxY:f.bottom+w},rect:{left:f.left-m.left-w,top:f.top-m.top-w,width:f.width+w*2,height:f.height+w*2}};g(b=>HPe(b,D)?b:D)},[e,i,t]),l=AA.useCallback(()=>{c.current===null&&(c.current=window.requestAnimationFrame(I))},[I]);AA.useEffect(()=>{l()},[l,r]),AA.useEffect(()=>{l();const h=t.current,u=i.current;if(!h||!u)return;const d=typeof ResizeObserver<"u"?new ResizeObserver(()=>{l()}):null;d?.observe(u),d?.observe(h);const f=typeof MutationObserver<"u"?new MutationObserver(()=>{l()}):null;return f?.observe(h,{attributes:!0,attributeFilter:["style","transform"],subtree:!0,childList:!0}),window.addEventListener("scroll",l,!0),window.addEventListener("resize",l),()=>{d?.disconnect(),f?.disconnect(),window.removeEventListener("scroll",l,!0),window.removeEventListener("resize",l),c.current!==null&&(cancelAnimationFrame(c.current),c.current=null)}},[l,t,i]);const B=AA.useCallback(h=>{n&&n(e,h)},[e,n]),C=a?.bounds??null,{hovering:Q}=dot({bounds:C,onClick:n?B:void 0});if(AA.useEffect(()=>{o&&o(e,Q)},[Q,e,o]),!a||!s)return null;const E=a.rect;return Z.jsxs(Z.Fragment,{children:[Z.jsx("div",{style:{position:"absolute",left:E.left,top:E.top,width:E.width,height:E.height,border:Q?"1.5px solid rgba(255, 153, 51, 0.9)":"1.5px solid rgba(255, 153, 51, 0.3)",backgroundColor:Q?"rgba(255, 153, 51, 0.15)":"rgba(255, 153, 51, 0.05)",borderRadius:"50%",pointerEvents:"none",zIndex:kD.schematicPortHoverOutline,transition:"border-color 0.15s, background-color 0.15s"}}),Q&&A&&Z.jsx("div",{style:{position:"absolute",left:E.left+E.width/2,top:E.top-24,transform:"translateX(-50%)",backgroundColor:"rgba(0, 0, 0, 0.85)",color:"white",padding:"4px 8px",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace",whiteSpace:"nowrap",pointerEvents:"none",zIndex:kD.schematicPortHoverOutline+1},children:A})]})},JPe=({circuitJson:e,containerStyle:A,editEvents:t=[],onEditEvent:i,defaultEditMode:n=!1,debugGrid:o=!1,editingEnabled:s=!1,debug:r=!1,clickToInteractEnabled:a=!1,colorOverrides:g,spiceSimulationEnabled:c=!1,disableGroups:I=!1,onSchematicComponentClicked:l,showSchematicPorts:B=!1,onSchematicPortClicked:C})=>{r&&CPe();const[Q,E]=AA.useState(!1),[h,u]=AA.useState({showVoltage:!0,showCurrent:!1,startTime:0,duration:20}),d=BA=>`${BA?.length||0}_${BA?.editCount||0}`,f=AA.useMemo(()=>d(e),[e]),m=AA.useMemo(()=>{if(!c)return null;try{return FPe(e,h)}catch(BA){return console.error("Failed to generate SPICE string",BA),null}},[f,c,h.startTime,h.duration]),[w,D]=AA.useState(!1);AA.useEffect(()=>{D(!1)},[f]);const{plotData:b,nodes:k,isLoading:x,error:N}=kPe(w?m:null),[R,U]=AA.useState(n),[T,Y]=AA.useState(!0),[O,W]=AA.useState(!1),X=o||O,[iA,aA]=AA.useState(!a),[tA,oA]=AA.useState(!1),[rA,CA]=AA.useState(()=>I?!1:GPe("schematic_viewer_show_groups",!1)),[SA,MA]=AA.useState(!1),GA=AA.useRef(new Set),TA=AA.useCallback((BA,it)=>{it?GA.current.add(BA):GA.current.delete(BA),MA(GA.current.size>0)},[]),[hA,kA]=AA.useState(!1),dA=AA.useRef(new Set),qA=AA.useCallback((BA,it)=>{it?dA.current.add(BA):dA.current.delete(BA),kA(dA.current.size>0)},[]),ZA=AA.useRef(null),rt=AA.useRef(null),yA=AA.useMemo(()=>{try{return wh(e).schematic_component?.list()?.map(BA=>BA.schematic_component_id)??[]}catch(BA){return console.error("Failed to derive schematic component ids",BA),[]}},[f,e]),$A=AA.useMemo(()=>{if(!B)return[];try{return(wh(e).schematic_port?.list()??[]).map(it=>{const lt=wh(e).source_port.get(it.source_port_id),vt=(lt?.source_component_id?wh(e).source_component.get(lt.source_component_id):null)?.name??"?",Kt=it.display_pin_label??lt?.pin_number??lt?.name??"?";return{portId:it.source_port_id,label:`${vt}.${Kt}`}})}catch(BA){return console.error("Failed to derive schematic port info",BA),[]}},[f,e,B]),KA=BA=>{const it=BA.touches[0];rt.current={x:it.clientX,y:it.clientY}},HA=BA=>{const it=BA.changedTouches[0],lt=rt.current;if(!lt)return;const dt=Math.abs(it.clientX-lt.x),vt=Math.abs(it.clientY-lt.y);dt<10&&vt<10&&(BA.preventDefault(),aA(!0)),rt.current=null},[PA,bA]=AA.useState([]),wA=AA.useRef(e);AA.useEffect(()=>{const BA=d(e),it=d(wA.current);BA!==it&&(bA([]),wA.current=e)},[e]);const{ref:LA,cancelDrag:FA,transform:JA}=uY({onSetTransform(BA){ZA.current&&(ZA.current.style.transform=BF(BA))},enabled:iA&&!Q}),{containerWidth:OA,containerHeight:tt}=hot(LA),DA=AA.useMemo(()=>!OA||!tt?"":KZ(e,{width:OA,height:tt||720,grid:X?{cellSize:1,labelCells:!0}:void 0,colorOverrides:g}),[f,OA,tt,X]),lA=AA.useMemo(()=>DA.match(/<svg[^>]*style="[^"]*background-color:\s*([^;\"]+)/i)?.[1]??"transparent",[DA]),EA=AA.useMemo(()=>{if(!DA)return Ru();const BA=DA.match(/data-real-to-screen-transform="([^"]+)"/)?.[1];try{return eq(BA)}catch(it){return console.error(it),Ru()}},[DA]),UA=BA=>{bA(it=>[...it,BA]),i&&i(BA)},nt=AA.useMemo(()=>[...t,...PA],[t,PA]),{handleMouseDown:Bt,handleTouchStart:pt,isDragging:bt,activeEditEvent:_t}=hPe({onEditEvent:UA,cancelDrag:FA,realToSvgProjection:EA,svgToScreenProjection:JA,circuitJson:e,editEvents:nt,enabled:R&&iA&&!Q,snapToGrid:T});gPe({svgDivRef:ZA,editEvents:nt,realToSvgProjection:EA,svgToScreenProjection:JA,activeEditEvent:_t}),cPe({svgDivRef:ZA,circuitJson:e,activeEditEvent:_t,editEvents:nt}),IPe({svgDivRef:ZA,circuitJson:e,circuitJsonKey:f,showGroups:rA&&!I});const Jt=AA.useRef(pt);AA.useEffect(()=>{Jt.current=pt},[pt]);const ce=AA.useMemo(()=>Z.jsx("div",{ref:ZA,style:{pointerEvents:a?iA?"auto":"none":"auto",transformOrigin:"0 0"},className:l?"schematic-component-clickable":void 0,onTouchStart:BA=>{R&&iA&&!Q&&Jt.current(BA)},dangerouslySetInnerHTML:{__html:DA}}),[DA,iA,a,R,Q]);return Z.jsxs(vPe,{children:[l&&Z.jsx("style",{children:".schematic-component-clickable [data-schematic-component-id]:hover { cursor: pointer !important; }"}),C&&Z.jsx("style",{children:"[data-schematic-port-id]:hover { cursor: pointer !important; }"}),Z.jsxs("div",{ref:LA,style:{position:"relative",backgroundColor:lA,overflow:"hidden",cursor:Q?"auto":bt?"grabbing":a&&!iA||SA&&l||hA&&C?"pointer":"grab",minHeight:"300px",...A},onWheelCapture:BA=>{Q&&BA.stopPropagation()},onMouseDown:BA=>{if(a&&!iA){BA.preventDefault(),BA.stopPropagation();return}Bt(BA)},onMouseDownCapture:BA=>{if(a&&!iA){BA.preventDefault(),BA.stopPropagation();return}},onTouchStart:BA=>{Q||KA(BA)},onTouchEnd:BA=>{Q||HA(BA)},children:[!iA&&a&&Z.jsx("div",{onClick:BA=>{BA.preventDefault(),BA.stopPropagation(),aA(!0)},style:{position:"absolute",inset:0,cursor:"pointer",zIndex:kD.clickToInteractOverlay,display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"all",touchAction:"pan-x pan-y pinch-zoom"},children:Z.jsx("div",{style:{backgroundColor:"rgba(0, 0, 0, 0.8)",color:"white",padding:"12px 24px",borderRadius:"8px",fontSize:"16px",fontFamily:"sans-serif",pointerEvents:"none"},children:typeof window<"u"&&("ontouchstart"in window||navigator.maxTouchPoints>0)?"Touch to Interact":"Click to Interact"})}),Z.jsx(pPe,{active:tA,onClick:()=>oA(!tA)}),s&&Z.jsx(uPe,{active:R,onClick:()=>U(!R)}),s&&R&&Z.jsx(dPe,{active:T,onClick:()=>Y(!T)}),Z.jsx(yPe,{circuitJson:e,circuitJsonKey:f,isVisible:tA,onClose:()=>oA(!1),showGroups:rA,onToggleGroups:BA=>{I||(CA(BA),MPe("schematic_viewer_show_groups",BA))},showGrid:X,onToggleGrid:W}),c&&Z.jsx(wPe,{onClick:()=>E(!0)}),Q&&Z.jsx(SPe,{spiceString:m,onClose:()=>E(!1),plotData:b,nodes:k,isLoading:x,error:N,simOptions:h,onSimOptionsChange:BA=>{D(!0),u(BA)},hasRun:w}),l&&yA.map(BA=>Z.jsx(UPe,{componentId:BA,svgDivRef:ZA,containerRef:LA,showOutline:!0,circuitJsonKey:f,onHoverChange:TA,onComponentClick:(it,lt)=>{l?.({schematicComponentId:it,event:lt})}},BA)),ce,B&&$A.map(({portId:BA,label:it})=>Z.jsx(YPe,{portId:BA,portLabel:it,svgDivRef:ZA,containerRef:LA,showOutline:!0,circuitJsonKey:f,onHoverChange:qA,onPortClick:C?(lt,dt)=>{C?.({schematicPortId:lt,event:dt})}:void 0},BA))]})]})},TPe=({circuitJson:e,containerStyle:A,colorOverrides:t,width:i,height:n,className:o})=>{const[s,r]=AA.useState(null),[a,g]=AA.useState(!0),[c,I]=AA.useState(null),[l,B]=AA.useState(null),C=AA.useRef(null),Q=AA.useRef(null),{containerWidth:E,containerHeight:h}=hot(C),[u,d]=AA.useState(!1),{ref:f}=uY({onSetTransform(U){Q.current&&(Q.current.style.transform=BF(U))}}),m=i||E||1e3,w=n||h||600;AA.useEffect(()=>{g(!0),I(null),r(e),g(!1)},[e]);const D=AA.useMemo(()=>s&&s.find(T=>T.type==="simulation_experiment")?.simulation_experiment_id||null,[s]),b=AA.useMemo(()=>s?s.filter(U=>U.type==="simulation_transient_voltage_graph").map(U=>U.simulation_transient_voltage_graph_id):[],[s]),k=AA.useMemo(()=>{if(!s||!m||!w||!D)return"";try{return cit({circuitJson:s,simulation_experiment_id:D,simulation_transient_voltage_graph_ids:b,width:m,height:w,schematicOptions:{colorOverrides:t}})}catch(U){return console.error("Failed to generate fallback schematic SVG:",U),""}},[s,m,w,t,D,b]);AA.useEffect(()=>{if(!k){B(null);return}try{const U=new Blob([k],{type:"image/svg+xml"}),T=URL.createObjectURL(U);return B(T),()=>{URL.revokeObjectURL(T)}}catch(U){console.error("Failed to create SVG object URL:",U),B(null)}},[k]);const x=AA.useMemo(()=>k?k.match(/<svg[^>]*style="[^"]*background-color:\s*([^;\"]+)/i)?.[1]??"transparent":"transparent",[k]),N=U=>{d(!0)},R=U=>{d(!0)};return AA.useEffect(()=>{const U=()=>{d(!1)},T=()=>{d(!1)};return window.addEventListener("mouseup",U),window.addEventListener("touchend",T),()=>{window.removeEventListener("mouseup",U),window.removeEventListener("touchend",T)}},[]),a?Z.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:"#f5f5f5",minHeight:"300px",fontFamily:"sans-serif",fontSize:"16px",color:"#666",...A},className:o,children:"Loading circuit..."}):c?Z.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:"#fef2f2",minHeight:"300px",fontFamily:"sans-serif",fontSize:"16px",color:"#dc2626",...A},className:o,children:Z.jsxs("div",{style:{textAlign:"center",padding:"20px"},children:[Z.jsx("div",{style:{fontWeight:"bold",marginBottom:"8px"},children:"Circuit Conversion Error"}),Z.jsx("div",{style:{fontSize:"14px"},children:c})]})}):k?Z.jsx("div",{ref:U=>{C.current=U,f.current=U},style:{position:"relative",backgroundColor:x,overflow:"hidden",minHeight:"300px",cursor:u?"grabbing":"grab",...A},className:o,onMouseDown:N,onTouchStart:R,children:l?Z.jsx("img",{ref:Q,src:l,alt:"Circuit Simulation",style:{transformOrigin:"0 0",width:"100%",height:"100%",display:"block",objectFit:"contain"}}):Z.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",minHeight:"300px",color:"#666",fontFamily:"sans-serif"},children:"Failed to render SVG"})}):Z.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",backgroundColor:"#f8fafc",minHeight:"300px",fontFamily:"sans-serif",gap:"12px",...A},className:o,children:[Z.jsx("div",{style:{fontSize:"16px",color:"#475569",fontWeight:500},children:"No Simulation Found"}),Z.jsxs("div",{style:{fontSize:"14px",color:"#64748b"},children:["Use"," ",Z.jsx("code",{style:{backgroundColor:"#e2e8f0",padding:"2px 6px",borderRadius:"4px",fontFamily:"monospace",fontSize:"13px"},children:"<analogsimulation />"})," ","to create simulations"]})]})},pot=e=>{const[A,t]=AA.useState(0),[i,n]=AA.useState(0);return AA.useEffect(()=>{if(!e.current)return;const o=()=>{const r=e.current?.getBoundingClientRect();t(r?.width||0),n(r?.height||0)};o();const s=new ResizeObserver(o);return s.observe(e.current),window.addEventListener("resize",o),()=>{s.disconnect(),window.removeEventListener("resize",o)}},[]),{containerWidth:A,containerHeight:i}};Bc("assembly-viewer");var fot=()=>{Bc.enable("assembly-viewer*")},KPe=({circuitJson:e,containerStyle:A,debugGrid:t=!1,debug:i=!1})=>{i&&fot();const n=AA.useRef(null),{ref:o}=uY({onSetTransform(c){n.current&&(n.current.style.transform=BF(c))}}),{containerWidth:s,containerHeight:r}=pot(o),a=AA.useMemo(()=>!s||!r?"":Yet(e,{width:s,height:r||720}),[e,s,r]);AA.useMemo(()=>{if(!a)return Ru();const c=a.match(/data-real-to-screen-transform="([^"]+)"/)?.[1];try{return eq(c)}catch(I){return console.error(I),Ru()}},[a]);const g=AA.useMemo(()=>Z.jsx("div",{ref:n,style:{pointerEvents:"auto",transformOrigin:"0 0"},dangerouslySetInnerHTML:{__html:a}}),[a]);return Z.jsx("div",{ref:o,style:{position:"relative",backgroundColor:"#FFFFFF",overflow:"hidden",minHeight:"300px",...A},children:g})},PPe=({circuitJson:e,containerStyle:A,debugGrid:t=!1,debug:i=!1})=>{i&&fot();const n=AA.useRef(null),{ref:o}=uY({onSetTransform(c){n.current&&(n.current.style.transform=BF(c))}}),{containerWidth:s,containerHeight:r}=pot(o),a=AA.useMemo(()=>!s||!r?"":YuA(e,{width:s,height:r||720}),[e,s,r]);AA.useMemo(()=>{if(!a)return Ru();const c=a.match(/data-real-to-screen-transform="([^"]+)"/)?.[1];try{return eq(c)}catch(I){return console.error(I),Ru()}},[a]);const g=AA.useMemo(()=>Z.jsx("div",{ref:n,style:{pointerEvents:"auto",transformOrigin:"0 0"},dangerouslySetInnerHTML:{__html:a}}),[a]);return Z.jsx("div",{ref:o,style:{position:"relative",backgroundColor:"#FFFFFF",overflow:"hidden",minHeight:"300px",...A},children:g})};const yot=["Initialize a tscircuit project using [tsci init](https://github.com/tscircuit/cli) before adding components.","Define reusable modules with cached routes using [<subcircuit />](https://docs.tscircuit.com/elements/subcircuit)","Run `tsci dev` on the command line to preview your boards before export",'Use units like mm or mils consistently across your designs (e.g. pcbX="10mm")',"Quickly set footprints with the [footprint prop](https://docs.tscircuit.com/footprints/footprinter-strings)","Check out the guide on [ordering prototypes](https://docs.tscircuit.com/building-electronics/ordering-prototypes)","Use [net labels](https://docs.tscircuit.com/elements/net) and [group elements](https://docs.tscircuit.com/elements/group) to organize complex schematics.","You can manually drag components on the PCB and Schematic using [manual edits](https://docs.tscircuit.com/guides/manual-edits)","Every tscircuit module can export to [Circuit JSON](https://github.com/tscircuit/circuit-json), Gerbers, Pick'n'Place CSV files, Bill of Materials CSV and more","You can import components from [JLCPCB](https://docs.tscircuit.com/guides/importing-modules-and-chips/importing-from-jlcpcb) or [KiCad](https://docs.tscircuit.com/guides/importing-modules-and-chips/importing-from-kicad)","Any module you push to the [registry](https://tscircuit.com/trending) will have [simple image urls](https://docs.tscircuit.com/web-apis/image-generation-api) you can use display images on a website","The default [Parts Engine](https://docs.tscircuit.com/guides/platform-configuration) will automatically find parts from common vendors for your BOM",'[Pin selectors](https://docs.tscircuit.com/guides/using-sel-references) are similar to CSS selectors, ".R1 > .pin1" means "connect to the first pin of the component R1"',"You can use the [sel](https://docs.tscircuit.com/guides/using-sel-references) object to select pins in a type-safe way","Publish modules via the [registry](https://tscircuit.com/trending) for working with a team or sharing your work","[Explore tutorials](https://docs.tscircuit.com/category/tutorials) for real-world circuit design examples.","Upload your Circuit JSON to [circuitjson.com](https://circuitjson.com) for a quick preview.","You can display Circuit JSON in 3D, PCB or Schematic mode with the [<CircuitJsonPreview />](https://docs.tscircuit.com/guides/running-tscircuit/displaying-circuit-json-on-a-webpage#react-display-all-available-previews-with-circuitjsonpreview-) React component","Use a [<group />](https://docs.tscircuit.com/elements/group) element to move multiple components at once in a schematic or PCB layout.","Check out the [GitHub Discussions page](https://github.com/tscircuit/tscircuit/discussions) to upvote features","You can customize the autorouter using the [autorouter prop](https://docs.tscircuit.com/elements/board#setting-the-autorouter)","Use the [<constraint />](https://docs.tscircuit.com/footprints/constraint) element to enforce geometric relationships in PCB designs.","When working on component placement and circuit design, autorouting can slow down your iteration cycle. Use [routingDisabled](https://docs.tscircuit.com/elements/board#disabling-routing-with-routingdisabled) on the <board /> element to disable autorouting temporarily.","Join the [Discord server](https://tscircuit.com/join) to discuss issues and get help directly from the community."],qPe=(()=>{let e=yot[Math.floor(Math.random()*yot.length)];return e=e.replace(/</g,"&lt;"),e=e.replace(/>/g,"&gt;"),e=e.replace(new RegExp('(?<!href=")(?<!\\()(?<!\\]\\()(https?:\\/\\/[^\\s\\)\\]]+)',"g"),(A,t)=>`<a class="rf-text-blue-500 rf-underline" href="${A}" target="_blank">${A}</a>`),e=e.replace(/\[([^\]]+)\]\((https?:\/\/[^\)]+)\)/g,'<a class="rf-text-blue-500 rf-underline" href="$2" target="_blank">$1</a>'),e})(),pb=({onRunClicked:e})=>Z.jsxs("div",{className:"rf-flex rf-flex-col rf-items-center rf-justify-center rf-h-full rf-bg-gray-50 rf-text-gray-500 rf-p-4",children:[Z.jsx(HGe,{className:"rf-size-14 rf-mb-4"}),Z.jsxs("p",{className:"rf-text-md rf-break-words rf-max-w-xl rf-text-center",children:["Tip: ",Z.jsx("span",{dangerouslySetInnerHTML:{__html:qPe}})]}),e&&Z.jsxs(qc,{className:"rf-mt-4 rf-bg-blue-600 rf-hover:bg-blue-500",onClick:e,children:["Run Code",Z.jsx(KGe,{className:"rf-w-3 rf-h-3 rf-ml-2"})]})]}),d9=({text:e,onClick:A})=>Z.jsx("span",{className:"rf-cursor-pointer rf-underline rf-text-blue-600 rf-mx-2",onClick:A,children:e}),p9=e=>Z.jsxs("div",{className:"rf-leading-5",children:[Z.jsx("div",{className:"rf-py-2 rf-font-bold",children:e.column.name}),Z.jsx("div",{children:e.field?.()??Z.jsx("input",{type:"text",className:"rf-border rf-rounded rf-p-1 rf-w-full",onChange:A=>{e.onTextChange?.(A.target.value)}})})]}),OPe=({open:e,children:A,title:t,onClose:i})=>e?Z.jsx("div",{className:"rf-fixed rf-inset-0 rf-bg-black rf-bg-opacity-50 rf-flex rf-justify-center rf-items-center rf-z-50",onClick:i,children:Z.jsxs("div",{className:"rf-bg-white rf-p-5 rf-rounded-lg rf-relative rf-w-11/12 rf-max-w-2xl",onClick:n=>{n.preventDefault(),n.stopPropagation()},children:[Z.jsx("h2",{className:"rf-mt-0 rf-text-md rf-pb-4",children:t}),Z.jsx("button",{type:"button",className:"rf-absolute rf-top-2 rf-right-4 rf-text-2xl rf-font-bold",onClick:i,children:"×"}),A]})}):null,WPe=({elements:e})=>{const[A,t]=AA.useState({open:!1}),[i,n]=AA.useReducer((c,I)=>({...c,...I}),{}),o=[...new Set(e.map(c=>c.type))],s=e.map(c=>{const I=c[`${c.type}_id`],l=Object.fromEntries(Object.entries(c).filter(([C])=>!(C===`${c.type}_id`||!C.endsWith("_id")))),B=Object.fromEntries(Object.entries(c).filter(([C])=>!C.endsWith("_id")));return{primary_id:I,other_ids:l,...B,_og_elm:c}}),r=s.map(c=>{let I="";const l=B=>{const C=Object.keys(B.other_ids).find(h=>h.startsWith("source_"));if(!C)return`.${B.name}`;const Q=C.slice(0,-3),E=s.find(h=>h.type===Q&&h.primary_id===B.other_ids[C]);return E?"name"in E?`${l(E)} > .${B.name}`:`#${E.primary_id} > .${B.name}`:`??? > .${B.name}`};return"name"in c&&(I=l(c)),{...c,selector_path:I}}),a=[{key:"primary_id",name:"primary_id",renderCell:c=>Z.jsxs("div",{className:"rf-flex rf-items-center",children:[Z.jsx(d9,{text:c.primary_id,onClick:()=>n({focused_id:c.primary_id,id_search:void 0,selector_search:void 0})}),Z.jsx("span",{className:"rf-flex-grow"}),Z.jsx(d9,{text:"(JSON)",onClick:()=>t({open:!0,element:c._og_elm,title:c.primary_id})})]}),renderHeaderCell:c=>Z.jsx(p9,{column:c,onTextChange:I=>n({id_search:I}),field:i.focused_id?()=>Z.jsxs("div",{children:["Focus:"," ",Z.jsx("span",{className:"rf-underline",children:i.focused_id}),Z.jsx(d9,{text:"(unfocus)",onClick:()=>n({focused_id:void 0})})]}):void 0})},{key:"type",name:"type",renderHeaderCell:c=>Z.jsx(p9,{column:c,field:()=>Z.jsxs("select",{onChange:I=>n({component_type_filter:I.target.value}),className:"rf-border rf-rounded rf-p-1 rf-w-full",children:[Z.jsx("option",{value:"any",children:"any"},"any"),Z.jsx("option",{value:"source",children:"source"},"source"),Z.jsx("option",{value:"source/pcb",children:"source/pcb"},"source/pcb"),Z.jsx("option",{value:"source/schematic",children:"source/schematic"},"source/schematic"),o.map(I=>Z.jsx("option",{value:I,children:I},I))]})})},{key:"name",name:"name",renderHeaderCell:c=>Z.jsx(p9,{column:c,onTextChange:I=>n({name_search:I})})},{key:"selector_path",name:"selector_path",renderHeaderCell:c=>Z.jsx(p9,{column:c,onTextChange:I=>n({selector_search:I})})},{key:"other_ids",name:"other_ids",renderCell:c=>Z.jsx("div",{className:"rf-space-x-2",children:Object.entries(c.other_ids).map(([I,l])=>Z.jsx(d9,{text:l,onClick:()=>n({focused_id:l})},l))})}],g=r.filter(c=>i.name_search?c.name?.toLowerCase()?.includes(i.name_search.toLowerCase()):!0).filter(c=>!i.component_type_filter||i.component_type_filter==="any"?!0:i.component_type_filter==="source"?c.type.startsWith("source_"):i.component_type_filter==="source/pcb"?c.type.startsWith("source_")||c.type.startsWith("pcb_"):i.component_type_filter==="source/schematic"?c.type.startsWith("source_")||c.type.startsWith("schematic_"):c.type?.includes(i.component_type_filter)).filter(c=>i.selector_search?i.selector_search.split(" ").filter(l=>l.length>0).every(l=>c.selector_path?.includes(l)):!0).filter(c=>i.id_search?c.primary_id?.includes(i.id_search):!0).filter(c=>!!(!i.focused_id||c.primary_id===i.focused_id||Object.values(c.other_ids).includes(i.focused_id)));return Z.jsxs("div",{className:"rf-font-mono rf-text-xs rf-bg-white",children:[Z.jsx("div",{className:"rf-overflow-x-auto",children:Z.jsxs("table",{className:"rf-table-auto rf-w-full rf-text-left",children:[Z.jsx("thead",{children:Z.jsx("tr",{children:a.map(c=>Z.jsx("th",{className:"rf-px-4 rf-py-2 rf-border-b",children:c.renderHeaderCell?c.renderHeaderCell(c):c.name},c.key))})}),Z.jsx("tbody",{children:g.map((c,I)=>Z.jsx("tr",{className:"rf-hover:bg-gray-100",children:a.map(l=>Z.jsx("td",{className:"rf-px-4 rf-py-2 rf-border-b",children:l.renderCell?l.renderCell(c):c[l.key]},l.key))},I))})]})}),Z.jsx(OPe,{open:A.open,onClose:()=>t({open:!1}),title:A.open?A.title:"",children:Z.jsx("div",{className:"rf-bg-gray-800 rf-p-3 rf-text-white rf-rounded",children:Z.jsx("pre",{className:"rf-whitespace-pre-wrap",children:A.open?JSON.stringify(A.element,null,2):""})})})]})},ZPe=(e,A)=>e==="jlcpcb"?Z.jsx("a",{className:"rf-underline rf-text-blue-500",target:"_blank",rel:"noreferrer",href:`https://jlcpcb.com/partdetail/${A}`,children:A}):A,VPe=({circuitJson:e})=>{const A=e.filter(i=>i.type==="source_component"),t=new Set;for(const i of A)if(i.supplier_part_numbers)for(const n of Object.keys(i.supplier_part_numbers))t.add(n);return Z.jsx("div",{className:"rf-overflow-x-auto",children:Z.jsxs("table",{className:"rf-w-full rf-text-left rf-text-sm",children:[Z.jsx("thead",{children:Z.jsxs("tr",{className:"rf-border-b",children:[Z.jsx("th",{className:"rf-p-2",children:"Name"}),Array.from(t).map(i=>Z.jsx("th",{className:"rf-p-2 rf-capitalize",children:i},i))]})}),Z.jsx("tbody",{children:A.map(i=>Z.jsxs("tr",{className:"rf-border-b",children:[Z.jsx("td",{className:"rf-p-2",children:i.name}),Array.from(t).map(n=>Z.jsx("td",{className:"rf-p-2",children:ZPe(n,i.supplier_part_numbers?.[n]?.[0]||"")},n))]},i.source_component_id))})]})})},wdA=AA.forwardRef(({className:e,type:A,...t},i)=>Z.jsx("input",{type:A,className:Eo("rf-flex rf-h-9 rf-w-full rf-rounded-md rf-border rf-border-zinc-200 rf-bg-white rf-px-3 rf-py-1 rf-text-sm rf-shadow-sm rf-transition-colors file:rf-border-0 file:rf-bg-transparent file:rf-text-sm file:rf-font-medium placeholder:rf-text-zinc-500 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 dark:rf-border-zinc-800 dark:rf-bg-zinc-950 dark:rf-placeholder-zinc-400 dark:focus-visible:rf-ring-zinc-300",e),ref:i,...t}));wdA.displayName="Input";var mot={Hz:{baseUnit:"Hz",variants:{MHz:1e6,kHz:1e3,Hz:1}},g:{baseUnit:"g",variants:{kg:1e3,g:1}},Ω:{baseUnit:"Ω",variants:{mΩ:.001,Ω:1,kΩ:1e3,KΩ:1e3,kohm:1e3,MΩ:1e6,GΩ:1e9,TΩ:1e12}},V:{baseUnit:"V",variants:{mV:.001,V:1,kV:1e3,KV:1e3,MV:1e6,GV:1e9,TV:1e12}},A:{baseUnit:"A",variants:{µA:1e-6,mA:.001,ma:.001,A:1,kA:1e3,MA:1e6}},F:{baseUnit:"F",variants:{pF:1e-12,nF:1e-9,µF:1e-6,uF:1e-6,mF:.001,F:1}},ml:{baseUnit:"ml",variants:{ml:1,mL:1,l:1e3,L:1e3}},deg:{baseUnit:"deg",variants:{rad:180/Math.PI}},ms:{baseUnit:"ms",variants:{fs:1e-12,ps:1e-9,ns:1e-6,us:.001,µs:.001,ms:1,s:1e3}},mm:{baseUnit:"mm",variants:{nm:1e-6,µm:.001,um:.001,mm:1,cm:10,dm:100,m:1e3,km:1e6,in:25.4,ft:304.8,IN:25.4,FT:304.8,yd:914.4,mi:1609344,mil:.0254}}},DdA=new Set;for(const[e,A]of Object.entries(mot)){DdA.add(e);for(const t of Object.keys(A.variants))DdA.add(t)}function jPe(e){for(const[A,t]of Object.entries(mot))if(e in t.variants)return{baseUnit:t.baseUnit,conversionFactor:t.variants[e]};return{baseUnit:e,conversionFactor:1}}var wot={tera:1e12,T:1e12,giga:1e9,G:1e9,mega:1e6,M:1e6,kilo:1e3,k:1e3,deci:.1,d:.1,centi:.01,c:.01,milli:.001,m:.001,micro:1e-6,u:1e-6,µ:1e-6,nano:1e-9,n:1e-9,pico:1e-12,p:1e-12};function ew(e){if(e==null)return{parsedUnit:null,unitOfValue:null,value:null};if(typeof e=="string"&&e.match(/^-?[\d\.]+$/))return{value:Number.parseFloat(e),parsedUnit:null,unitOfValue:null};if(typeof e=="number")return{value:e,parsedUnit:null,unitOfValue:null};if(typeof e=="object"&&"x"in e&&"y"in e){const{parsedUnit:r,unitOfValue:a}=ew(e.x),g=ew(e.x),c=ew(e.y);return g.value===null||c.value===null?{parsedUnit:null,unitOfValue:null,value:null}:{parsedUnit:r,unitOfValue:a,value:{x:g.value,y:c.value}}}const t=e.toString().split("").reverse().join("").match(/[^\d\s]+/)?.[0];if(!t)throw new Error(`Could not determine unit: "${e}"`);const i=t.split("").reverse().join(""),n=e.slice(0,-i.length);if(i in wot&&!DdA.has(i)){const r=wot[i];return{parsedUnit:null,unitOfValue:null,value:Number.parseFloat(n)*r}}const{baseUnit:o,conversionFactor:s}=jPe(i);return{parsedUnit:i,unitOfValue:o,value:s*Number.parseFloat(n)}}var f9=H().or(WA()).transform(e=>ew(e).value),SdA=H().or(WA()).transform(e=>ew(e).value).transform(e=>Number.parseFloat(e.toPrecision(12))),Dot=H().or(WA()).transform(e=>ew(e).value),fb=H().or(WA()).transform(e=>ew(e).value),Vi=H().or(WA()).transform(e=>ew(e).value),dG=H().or(WA()).transform(e=>ew(e).value),he=Vi,Pv=H().or(WA()).transform(e=>ew(e).value),HY=H().or(WA()).transform(e=>ew(e).value),zPe=HY,pG=HY,Sot=H().datetime(),bE=H().or(WA()).transform(e=>typeof e=="number"?e:e.endsWith("deg")?Number.parseFloat(e.split("deg")[0]):e.endsWith("rad")?Number.parseFloat(e.split("rad")[0])*180/Math.PI:Number.parseFloat(e)),bot=WA().or(H().endsWith("mAh")).transform(e=>{if(typeof e=="string"){const A=e.replace("mAh",""),t=Number.parseFloat(A);if(Number.isNaN(t))throw new Error("Invalid capacity");return t}return e}).describe("Battery capacity in mAh"),wn=jA({x:he,y:he}),XPe=wn,YY=jA({x:he,y:he,z:he}),$Pe=YY,bdA=jA({width:WA(),height:WA()}),Aqe=e=>{const A="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";return Array.from({length:e},()=>A[Math.floor(Math.random()*A.length)]).join("")},We=e=>H().optional().default(()=>`${e}_${Aqe(10)}`),Z_=se(["top_left","top_center","top_right","center_left","center","center_right","bottom_left","bottom_center","bottom_right"]),tqe=se(["top_silkscreen","bottom_silkscreen","top_copper","bottom_copper","top_soldermask","bottom_soldermask","top_fabrication_note","bottom_fabrication_note","top_user_note","bottom_user_note","inner1_copper","inner2_copper","inner3_copper","inner4_copper","inner5_copper","inner6_copper","edge_cuts","drill"]),Gl=jA({error_type:H(),message:H(),is_fatal:gt().optional()}),xot=se(["jlcpcb","macrofab","pcbway","digikey","mouser","lcsc"]),Wc=jA({type:xA("source_component"),ftype:H().optional(),source_component_id:H(),name:H(),manufacturer_part_number:H().optional(),supplier_part_numbers:ba(xot,St(H())).optional(),display_value:H().optional(),display_name:H().optional(),are_pins_interchangeable:gt().optional(),internally_connected_source_port_ids:St(St(H())).optional(),source_group_id:H().optional(),subcircuit_id:H().optional()}),xdA=Wc.extend({ftype:xA("simple_capacitor"),capacitance:SdA,max_voltage_rating:fb.optional(),display_capacitance:H().optional(),max_decoupling_trace_length:he.optional()}),_dA=Wc.extend({ftype:xA("simple_resistor"),resistance:f9,display_resistance:H().optional()}),y9=Wc.extend({ftype:xA("simple_diode")}),_ot=Wc.extend({ftype:xA("simple_fiducial")}),kdA=y9.extend({ftype:xA("simple_led"),color:H().optional(),wavelength:H().optional()}),kot=Wc.extend({ftype:xA("simple_ground")}),FdA=Wc.extend({ftype:xA("simple_chip")}),GdA=Wc.extend({ftype:xA("simple_power_source"),voltage:fb}),Fot=Wc.extend({ftype:xA("simple_current_source"),current:Pv,frequency:dG.optional(),peak_to_peak_current:Pv.optional(),wave_shape:se(["sine","square","triangle","sawtooth","dc"]).optional().default("dc"),phase:WA().optional(),duty_cycle:WA().min(0).max(1).optional()}),eqe=Wc.extend({ftype:xA("simple_fuse"),current_rating_amps:WA().describe("Nominal current in amps the fuse is rated for"),voltage_rating_volts:WA().describe("Voltage rating in volts, e.g. ±5V would be 5")}),MdA=Wc.extend({ftype:xA("simple_battery"),capacity:bot}),RdA=Wc.extend({ftype:xA("simple_inductor"),inductance:Dot,max_current_rating:WA().optional()}),NdA=Wc.extend({ftype:xA("simple_push_button")}),vdA=Wc.extend({ftype:xA("simple_potentiometer"),max_resistance:f9,display_max_resistance:H().optional()}),Got=Wc.extend({ftype:xA("simple_crystal"),frequency:WA().describe("Frequency in Hz"),load_capacitance:WA().optional().describe("Load capacitance in pF"),pin_variant:se(["two_pin","four_pin"]).optional()}),LdA=Wc.extend({ftype:xA("simple_pin_header"),pin_count:WA(),gender:se(["male","female"]).optional().default("male")}),UdA=Wc.extend({ftype:xA("simple_pinout")}),HdA=Wc.extend({ftype:xA("simple_resonator"),load_capacitance:SdA,equivalent_series_resistance:f9.optional(),frequency:dG}),YdA=Wc.extend({ftype:xA("simple_transistor"),transistor_type:se(["npn","pnp"])}),JdA=Wc.extend({ftype:xA("simple_test_point"),footprint_variant:se(["pad","through_hole"]).optional(),pad_shape:se(["rect","circle"]).optional(),pad_diameter:Ze([WA(),H()]).optional(),hole_diameter:Ze([WA(),H()]).optional(),width:Ze([WA(),H()]).optional(),height:Ze([WA(),H()]).optional()}),TdA=Wc.extend({ftype:xA("simple_mosfet"),channel_type:se(["n","p"]),mosfet_mode:se(["enhancement","depletion"])}),KdA=Wc.extend({ftype:xA("simple_op_amp")}),PdA=Wc.extend({ftype:xA("simple_switch")}),qdA=jA({type:xA("source_project_metadata"),name:H().optional(),software_used_string:H().optional(),project_url:H().optional(),created_at:Sot.optional()}),Mot=Gl.extend({type:xA("source_missing_property_error"),source_missing_property_error_id:We("source_missing_property_error"),source_component_id:H(),property_name:H(),subcircuit_id:H().optional(),error_type:xA("source_missing_property_error").default("source_missing_property_error")}).describe("The source code is missing a property"),Rot=Gl.extend({type:xA("source_failed_to_create_component_error"),source_failed_to_create_component_error_id:We("source_failed_to_create_component_error"),error_type:xA("source_failed_to_create_component_error").default("source_failed_to_create_component_error"),component_name:H().optional(),subcircuit_id:H().optional(),parent_source_component_id:H().optional(),pcb_center:jA({x:WA().optional(),y:WA().optional()}).optional(),schematic_center:jA({x:WA().optional(),y:WA().optional()}).optional()}).describe("Error emitted when a component fails to be constructed"),OdA=Gl.extend({type:xA("source_trace_not_connected_error"),source_trace_not_connected_error_id:We("source_trace_not_connected_error"),error_type:xA("source_trace_not_connected_error").default("source_trace_not_connected_error"),subcircuit_id:H().optional(),source_group_id:H().optional(),source_trace_id:H().optional(),connected_source_port_ids:St(H()).optional(),selectors_not_found:St(H()).optional()}).describe("Occurs when a source trace selector does not match any ports"),Not=jA({type:xA("source_property_ignored_warning"),source_property_ignored_warning_id:We("source_property_ignored_warning"),source_component_id:H(),property_name:H(),subcircuit_id:H().optional(),error_type:xA("source_property_ignored_warning").default("source_property_ignored_warning"),message:H()}).describe("The source property was ignored"),WdA=jA({type:xA("source_pin_missing_trace_warning"),source_pin_missing_trace_warning_id:We("source_pin_missing_trace_warning"),warning_type:xA("source_pin_missing_trace_warning").default("source_pin_missing_trace_warning"),message:H(),source_component_id:H(),source_port_id:H(),subcircuit_id:H().optional()}).describe("Warning emitted when a source component pin is missing a trace connection"),vot=Wc.extend({ftype:xA("simple_voltage_probe")}),Lot=Wc.extend({ftype:xA("interconnect")}),Uot=Wc.extend({ftype:xA("simple_voltage_source"),voltage:fb,frequency:dG.optional(),peak_to_peak_voltage:fb.optional(),wave_shape:se(["sinewave","square","triangle","sawtooth"]).optional(),phase:bE.optional(),duty_cycle:WA().optional().describe("Duty cycle as a fraction (0 to 1)")}),Hot=Ze([_dA,xdA,y9,_ot,kdA,kot,FdA,GdA,Fot,MdA,RdA,NdA,vdA,Got,LdA,UdA,HdA,PdA,YdA,JdA,TdA,KdA,eqe,vot,Lot,Uot,qdA,Mot,Rot,OdA,Not,WdA]),Yot=jA({type:xA("source_port"),pin_number:WA().optional(),port_hints:St(H()).optional(),name:H(),source_port_id:H(),source_component_id:H().optional(),source_group_id:H().optional(),subcircuit_id:H().optional(),subcircuit_connectivity_map_key:H().optional(),must_be_connected:gt().optional()}),Jot=jA({type:xA("source_component_internal_connection"),source_component_internal_connection_id:H(),source_component_id:H(),source_port_ids:St(H()),subcircuit_id:H().optional()}),Tot=jA({type:xA("source_trace"),source_trace_id:H(),connected_source_port_ids:St(H()),connected_source_net_ids:St(H()),subcircuit_id:H().optional(),subcircuit_connectivity_map_key:H().optional(),max_length:WA().optional(),min_trace_thickness:WA().optional(),display_name:H().optional()}),Kot=jA({type:xA("source_group"),source_group_id:H(),subcircuit_id:H().optional(),parent_subcircuit_id:H().optional(),parent_source_group_id:H().optional(),is_subcircuit:gt().optional(),show_as_schematic_box:gt().optional(),name:H().optional(),was_automatically_named:gt().optional()}),Pot=jA({type:xA("source_net"),source_net_id:H(),name:H(),member_source_group_ids:St(H()),is_power:gt().optional(),is_ground:gt().optional(),is_digital_signal:gt().optional(),is_analog_signal:gt().optional(),is_positive_voltage_source:gt().optional(),trace_width:WA().optional(),subcircuit_id:H().optional(),subcircuit_connectivity_map_key:H().optional()}),qot=jA({type:xA("source_board"),source_board_id:H(),source_group_id:H(),title:H().optional()}).describe("Defines a board in the source domain"),Oot=jA({type:xA("source_pcb_ground_plane"),source_pcb_ground_plane_id:H(),source_group_id:H(),source_net_id:H(),subcircuit_id:H().optional()}).describe("Defines a ground plane in the source domain"),Wot=["top","bottom","inner1","inner2","inner3","inner4","inner5","inner6"],ZdA=se(Wot),Gr=ZdA.or(jA({name:ZdA})).transform(e=>typeof e=="string"?e:e.name),qy=se(["top","bottom"]),Zot=jA({type:xA("source_manually_placed_via"),source_manually_placed_via_id:H(),source_group_id:H(),source_net_id:H(),subcircuit_id:H().optional(),source_trace_id:H().optional()}).describe("Defines a via that is manually placed in the source domain"),Vot=Gl.extend({type:xA("source_pin_must_be_connected_error"),source_pin_must_be_connected_error_id:We("source_pin_must_be_connected_error"),error_type:xA("source_pin_must_be_connected_error").default("source_pin_must_be_connected_error"),source_component_id:H(),source_port_id:H(),subcircuit_id:H().optional()}).describe("Error emitted when a pin with mustBeConnected attribute is not connected to any trace"),jot=Gl.extend({type:xA("unknown_error_finding_part"),unknown_error_finding_part_id:We("unknown_error_finding_part"),error_type:xA("unknown_error_finding_part").default("unknown_error_finding_part"),source_component_id:H().optional(),subcircuit_id:H().optional()}).describe("Error emitted when an unexpected error occurs while finding a part"),zot=jA({type:xA("schematic_box"),schematic_component_id:H().optional(),schematic_symbol_id:H().optional(),width:he,height:he,is_dashed:gt().default(!1),x:he,y:he,subcircuit_id:H().optional()}).describe("Draws a box on the schematic"),Xot=jA({type:xA("schematic_path"),schematic_path_id:We("schematic_path"),schematic_component_id:H().optional(),schematic_symbol_id:H().optional(),fill_color:se(["red","blue"]).optional(),is_filled:gt().optional(),stroke_width:he.nullable().optional(),stroke_color:H().optional(),points:St(wn),subcircuit_id:H().optional()}),$ot=ba(jA({left_margin:Vi.optional(),right_margin:Vi.optional(),top_margin:Vi.optional(),bottom_margin:Vi.optional()})),Ast=jA({left_size:WA(),right_size:WA(),top_size:WA().optional(),bottom_size:WA().optional()}),tst=jA({left_side:jA({pins:St(WA()),direction:se(["top-to-bottom","bottom-to-top"]).optional()}).optional(),right_side:jA({pins:St(WA()),direction:se(["top-to-bottom","bottom-to-top"]).optional()}).optional(),top_side:jA({pins:St(WA()),direction:se(["left-to-right","right-to-left"]).optional()}).optional(),bottom_side:jA({pins:St(WA()),direction:se(["left-to-right","right-to-left"]).optional()}).optional()}),est=Ze([Ast,tst]),ist=jA({type:xA("schematic_component"),size:bdA,center:wn,source_component_id:H().optional(),schematic_component_id:H(),schematic_symbol_id:H().optional(),pin_spacing:Vi.optional(),pin_styles:$ot.optional(),box_width:Vi.optional(),symbol_name:H().optional(),port_arrangement:est.optional(),port_labels:ba(H()).optional(),symbol_display_value:H().optional(),subcircuit_id:H().optional(),schematic_group_id:H().optional(),is_schematic_group:gt().optional(),source_group_id:H().optional(),is_box_with_pins:gt().optional().default(!0)}),nst=jA({type:xA("schematic_symbol"),schematic_symbol_id:H(),name:H().optional()}).describe("Defines a named schematic symbol that can be referenced by components."),ost=jA({type:xA("schematic_line"),schematic_line_id:We("schematic_line"),schematic_component_id:H().optional(),schematic_symbol_id:H().optional(),x1:he,y1:he,x2:he,y2:he,stroke_width:he.nullable().optional(),color:H().default("#000000"),is_dashed:gt().default(!1),subcircuit_id:H().optional()}).describe("Draws a styled line on the schematic"),sst=jA({type:xA("schematic_rect"),schematic_rect_id:We("schematic_rect"),schematic_component_id:H().optional(),schematic_symbol_id:H().optional(),center:wn,width:he,height:he,rotation:bE.default(0),stroke_width:he.nullable().optional(),color:H().default("#000000"),is_filled:gt().default(!1),fill_color:H().optional(),is_dashed:gt().default(!1),subcircuit_id:H().optional()}).describe("Draws a styled rectangle on the schematic"),rst=jA({type:xA("schematic_circle"),schematic_circle_id:We("schematic_circle"),schematic_component_id:H().optional(),schematic_symbol_id:H().optional(),center:wn,radius:he,stroke_width:he.nullable().optional(),color:H().default("#000000"),is_filled:gt().default(!1),fill_color:H().optional(),is_dashed:gt().default(!1),subcircuit_id:H().optional()}).describe("Draws a styled circle on the schematic"),ast=jA({type:xA("schematic_arc"),schematic_arc_id:We("schematic_arc"),schematic_component_id:H().optional(),schematic_symbol_id:H().optional(),center:wn,radius:he,start_angle_degrees:bE,end_angle_degrees:bE,direction:se(["clockwise","counterclockwise"]).default("counterclockwise"),stroke_width:he.nullable().optional(),color:H().default("#000000"),is_dashed:gt().default(!1),subcircuit_id:H().optional()}).describe("Draws a styled arc on the schematic"),gst=jA({type:xA("schematic_trace"),schematic_trace_id:H(),source_trace_id:H().optional(),junctions:St(jA({x:WA(),y:WA()})),edges:St(jA({from:jA({x:WA(),y:WA()}),to:jA({x:WA(),y:WA()}),is_crossing:gt().optional(),from_schematic_port_id:H().optional(),to_schematic_port_id:H().optional()})),subcircuit_id:H().optional(),subcircuit_connectivity_map_key:H().optional()}),iqe=se(["center","left","right","top","bottom"]),cst=jA({type:xA("schematic_text"),schematic_component_id:H().optional(),schematic_symbol_id:H().optional(),schematic_text_id:H(),text:H(),font_size:WA().default(.18),position:jA({x:he,y:he}),rotation:WA().default(0),anchor:Ze([iqe.describe("legacy"),Z_]).default("center"),color:H().default("#000000"),subcircuit_id:H().optional()}),Ist=jA({type:xA("schematic_port"),schematic_port_id:H(),source_port_id:H(),schematic_component_id:H().optional(),center:wn,facing_direction:se(["up","down","left","right"]).optional(),distance_from_component_edge:WA().optional(),side_of_component:se(["top","bottom","left","right"]).optional(),true_ccw_index:WA().optional(),pin_number:WA().optional(),display_pin_label:H().optional(),subcircuit_id:H().optional(),is_connected:gt().optional(),has_input_arrow:gt().optional(),has_output_arrow:gt().optional(),is_drawn_with_inversion_circle:gt().optional()}).describe("Defines a port on a schematic component"),lst=jA({type:xA("schematic_net_label"),schematic_net_label_id:We("schematic_net_label"),schematic_trace_id:H().optional(),source_trace_id:H().optional(),source_net_id:H(),center:wn,anchor_position:wn.optional(),anchor_side:se(["top","bottom","left","right"]),text:H(),symbol_name:H().optional(),is_movable:gt().optional(),subcircuit_id:H().optional()}),Bst=Gl.extend({type:xA("schematic_error"),schematic_error_id:H(),error_type:xA("schematic_port_not_found").default("schematic_port_not_found"),subcircuit_id:H().optional()}).describe("Defines a schematic error on the schematic"),Cst=Gl.extend({type:xA("schematic_layout_error"),schematic_layout_error_id:We("schematic_layout_error"),error_type:xA("schematic_layout_error").default("schematic_layout_error"),source_group_id:H(),schematic_group_id:H(),subcircuit_id:H().optional()}).describe("Error emitted when schematic layout fails for a group"),m9=jA({type:xA("schematic_debug_object"),label:H().optional(),subcircuit_id:H().optional()}),Qst=m9.extend({shape:xA("rect"),center:wn,size:bdA}),Est=m9.extend({shape:xA("line"),start:wn,end:wn}),hst=m9.extend({shape:xA("point"),center:wn}),ust=zp("shape",[Qst,Est,hst]),dst=jA({type:xA("schematic_voltage_probe"),schematic_voltage_probe_id:H(),source_component_id:H().optional(),name:H().optional(),position:wn,schematic_trace_id:H(),voltage:fb.optional(),subcircuit_id:H().optional(),color:H().optional(),label_alignment:Z_.optional()}).describe("Defines a voltage probe measurement point on a schematic trace"),pst=jA({type:xA("schematic_manual_edit_conflict_warning"),schematic_manual_edit_conflict_warning_id:We("schematic_manual_edit_conflict_warning"),warning_type:xA("schematic_manual_edit_conflict_warning").default("schematic_manual_edit_conflict_warning"),message:H(),schematic_component_id:H(),schematic_group_id:H().optional(),subcircuit_id:H().optional(),source_component_id:H()}).describe("Warning emitted when a component has both manual placement and explicit schX/schY coordinates"),fst=jA({type:xA("schematic_group"),schematic_group_id:We("schematic_group"),source_group_id:H(),is_subcircuit:gt().optional(),subcircuit_id:H().optional(),width:Vi,height:Vi,center:wn,schematic_component_ids:St(H()),show_as_schematic_box:gt().optional(),name:H().optional(),description:H().optional()}).describe("Defines a group of components on the schematic"),yst=jA({type:xA("schematic_table"),schematic_table_id:We("schematic_table"),anchor_position:wn,column_widths:St(he),row_heights:St(he),cell_padding:he.optional(),border_width:he.optional(),subcircuit_id:H().optional(),schematic_component_id:H().optional(),anchor:Z_.optional()}).describe("Defines a table on the schematic"),mst=jA({type:xA("schematic_table_cell"),schematic_table_cell_id:We("schematic_table_cell"),schematic_table_id:H(),start_row_index:WA(),end_row_index:WA(),start_column_index:WA(),end_column_index:WA(),text:H().optional(),center:wn,width:he,height:he,horizontal_align:se(["left","center","right"]).optional(),vertical_align:se(["top","middle","bottom"]).optional(),font_size:he.optional(),subcircuit_id:H().optional()}).describe("Defines a cell within a schematic_table"),wst=jA({type:xA("schematic_sheet"),schematic_sheet_id:We("schematic_sheet"),name:H().optional(),subcircuit_id:H().optional()}).describe("Defines a schematic sheet or page that components can be placed on"),Dst=jA({x:he,y:he,bulge:WA().optional()}),VdA=jA({vertices:St(Dst)}),Sst=jA({outer_ring:VdA,inner_rings:St(VdA).default([])}),bst=jA({x:he,y:he,via:gt().optional(),via_to_layer:Gr.optional()}),nqe=St(bst),xst=jA({x:he,y:he,via:gt().optional(),to_layer:Gr.optional(),trace_width:he.optional()}),_st=jA({type:xA("pcb_component"),pcb_component_id:We("pcb_component"),source_component_id:H(),center:wn,layer:Gr,rotation:bE,display_offset_x:H().optional().describe("How to display the x offset for this part, usually corresponding with how the user specified it"),display_offset_y:H().optional().describe("How to display the y offset for this part, usually corresponding with how the user specified it"),width:Vi,height:Vi,do_not_place:gt().optional(),subcircuit_id:H().optional(),pcb_group_id:H().optional(),position_mode:se(["packed","relative_to_group_anchor","none"]).optional(),positioned_relative_to_pcb_group_id:H().optional(),positioned_relative_to_pcb_board_id:H().optional(),obstructs_within_bounds:gt().default(!0).describe("Does this component take up all the space within its bounds on a layer. This is generally true except for when separated pin headers are being represented by a single component (in which case, chips can be placed between the pin headers) or for tall modules where chips fit underneath")}).describe("Defines a component on the PCB"),kst=jA({type:xA("pcb_hole"),pcb_hole_id:We("pcb_hole"),pcb_group_id:H().optional(),subcircuit_id:H().optional(),pcb_component_id:H().optional(),hole_shape:xA("circle"),hole_diameter:WA(),x:he,y:he,is_covered_with_solder_mask:gt().optional(),soldermask_margin:WA().optional()}),oqe=kst.describe("Defines a circular hole on the PCB"),Fst=jA({type:xA("pcb_hole"),pcb_hole_id:We("pcb_hole"),pcb_group_id:H().optional(),subcircuit_id:H().optional(),pcb_component_id:H().optional(),hole_shape:xA("rect"),hole_width:WA(),hole_height:WA(),x:he,y:he,is_covered_with_solder_mask:gt().optional(),soldermask_margin:WA().optional()}),sqe=Fst.describe("Defines a rectangular (square-capable) hole on the PCB. Use equal width/height for square."),Gst=jA({type:xA("pcb_hole"),pcb_hole_id:We("pcb_hole"),pcb_group_id:H().optional(),subcircuit_id:H().optional(),pcb_component_id:H().optional(),hole_shape:se(["circle","square"]),hole_diameter:WA(),x:he,y:he,is_covered_with_solder_mask:gt().optional(),soldermask_margin:WA().optional()}),rqe=Gst.describe("Defines a circular or square hole on the PCB"),Mst=jA({type:xA("pcb_hole"),pcb_hole_id:We("pcb_hole"),pcb_group_id:H().optional(),subcircuit_id:H().optional(),pcb_component_id:H().optional(),hole_shape:xA("oval"),hole_width:WA(),hole_height:WA(),x:he,y:he,is_covered_with_solder_mask:gt().optional(),soldermask_margin:WA().optional()}),aqe=Mst.describe("Defines an oval hole on the PCB"),Rst=jA({type:xA("pcb_hole"),pcb_hole_id:We("pcb_hole"),pcb_group_id:H().optional(),subcircuit_id:H().optional(),pcb_component_id:H().optional(),hole_shape:xA("pill"),hole_width:WA(),hole_height:WA(),x:he,y:he,is_covered_with_solder_mask:gt().optional(),soldermask_margin:WA().optional()}),gqe=Rst.describe("Defines a pill-shaped hole on the PCB"),Nst=jA({type:xA("pcb_hole"),pcb_hole_id:We("pcb_hole"),pcb_group_id:H().optional(),subcircuit_id:H().optional(),pcb_component_id:H().optional(),hole_shape:xA("rotated_pill"),hole_width:WA(),hole_height:WA(),x:he,y:he,ccw_rotation:bE,is_covered_with_solder_mask:gt().optional(),soldermask_margin:WA().optional()}),cqe=Nst.describe("Defines a rotated pill-shaped hole on the PCB"),vst=Gst.or(Mst).or(Rst).or(Nst).or(kst).or(Fst),Iqe=jA({type:xA("pcb_plated_hole"),shape:xA("circle"),pcb_group_id:H().optional(),subcircuit_id:H().optional(),outer_diameter:WA(),hole_diameter:WA(),is_covered_with_solder_mask:gt().optional(),x:he,y:he,layers:St(Gr),port_hints:St(H()).optional(),pcb_component_id:H().optional(),pcb_port_id:H().optional(),pcb_plated_hole_id:We("pcb_plated_hole"),soldermask_margin:WA().optional()}),lqe=jA({type:xA("pcb_plated_hole"),shape:se(["oval","pill"]),pcb_group_id:H().optional(),subcircuit_id:H().optional(),outer_width:WA(),outer_height:WA(),hole_width:WA(),hole_height:WA(),is_covered_with_solder_mask:gt().optional(),x:he,y:he,ccw_rotation:bE,layers:St(Gr),port_hints:St(H()).optional(),pcb_component_id:H().optional(),pcb_port_id:H().optional(),pcb_plated_hole_id:We("pcb_plated_hole"),soldermask_margin:WA().optional()}),Bqe=jA({type:xA("pcb_plated_hole"),shape:xA("circular_hole_with_rect_pad"),pcb_group_id:H().optional(),subcircuit_id:H().optional(),hole_shape:xA("circle"),pad_shape:xA("rect"),hole_diameter:WA(),rect_pad_width:WA(),rect_pad_height:WA(),rect_border_radius:WA().optional(),hole_offset_x:he.default(0),hole_offset_y:he.default(0),is_covered_with_solder_mask:gt().optional(),x:he,y:he,layers:St(Gr),port_hints:St(H()).optional(),pcb_component_id:H().optional(),pcb_port_id:H().optional(),pcb_plated_hole_id:We("pcb_plated_hole"),soldermask_margin:WA().optional()}),Cqe=jA({type:xA("pcb_plated_hole"),shape:xA("pill_hole_with_rect_pad"),pcb_group_id:H().optional(),subcircuit_id:H().optional(),hole_shape:xA("pill"),pad_shape:xA("rect"),hole_width:WA(),hole_height:WA(),rect_pad_width:WA(),rect_pad_height:WA(),rect_border_radius:WA().optional(),hole_offset_x:he.default(0),hole_offset_y:he.default(0),is_covered_with_solder_mask:gt().optional(),x:he,y:he,layers:St(Gr),port_hints:St(H()).optional(),pcb_component_id:H().optional(),pcb_port_id:H().optional(),pcb_plated_hole_id:We("pcb_plated_hole"),soldermask_margin:WA().optional()}),Qqe=jA({type:xA("pcb_plated_hole"),shape:xA("rotated_pill_hole_with_rect_pad"),pcb_group_id:H().optional(),subcircuit_id:H().optional(),hole_shape:xA("rotated_pill"),pad_shape:xA("rect"),hole_width:WA(),hole_height:WA(),hole_ccw_rotation:bE,rect_pad_width:WA(),rect_pad_height:WA(),rect_border_radius:WA().optional(),rect_ccw_rotation:bE,hole_offset_x:he.default(0),hole_offset_y:he.default(0),is_covered_with_solder_mask:gt().optional(),x:he,y:he,layers:St(Gr),port_hints:St(H()).optional(),pcb_component_id:H().optional(),pcb_port_id:H().optional(),pcb_plated_hole_id:We("pcb_plated_hole"),soldermask_margin:WA().optional()}),Eqe=jA({type:xA("pcb_plated_hole"),shape:xA("hole_with_polygon_pad"),pcb_group_id:H().optional(),subcircuit_id:H().optional(),hole_shape:se(["circle","oval","pill","rotated_pill"]),hole_diameter:WA().optional(),hole_width:WA().optional(),hole_height:WA().optional(),pad_outline:St(jA({x:he,y:he})).min(3),hole_offset_x:he.default(0),hole_offset_y:he.default(0),is_covered_with_solder_mask:gt().optional(),x:he,y:he,layers:St(Gr),port_hints:St(H()).optional(),pcb_component_id:H().optional(),pcb_port_id:H().optional(),pcb_plated_hole_id:We("pcb_plated_hole"),soldermask_margin:WA().optional(),ccw_rotation:bE.optional()}),Lst=Ze([Iqe,lqe,Bqe,Cqe,Qqe,Eqe]),Ust=jA({type:xA("pcb_port"),pcb_port_id:We("pcb_port"),pcb_group_id:H().optional(),subcircuit_id:H().optional(),source_port_id:H(),pcb_component_id:H().optional(),x:he,y:he,layers:St(Gr),is_board_pinout:gt().optional()}).describe("Defines a port on the PCB"),hqe=jA({type:xA("pcb_smtpad"),shape:xA("circle"),pcb_smtpad_id:We("pcb_smtpad"),pcb_group_id:H().optional(),subcircuit_id:H().optional(),x:he,y:he,radius:WA(),layer:Gr,port_hints:St(H()).optional(),pcb_component_id:H().optional(),pcb_port_id:H().optional(),is_covered_with_solder_mask:gt().optional(),soldermask_margin:WA().optional()}),uqe=jA({type:xA("pcb_smtpad"),shape:xA("rect"),pcb_smtpad_id:We("pcb_smtpad"),pcb_group_id:H().optional(),subcircuit_id:H().optional(),x:he,y:he,width:WA(),height:WA(),rect_border_radius:WA().optional(),corner_radius:WA().optional(),layer:Gr,port_hints:St(H()).optional(),pcb_component_id:H().optional(),pcb_port_id:H().optional(),is_covered_with_solder_mask:gt().optional(),soldermask_margin:WA().optional(),soldermask_margin_left:WA().optional(),soldermask_margin_top:WA().optional(),soldermask_margin_right:WA().optional(),soldermask_margin_bottom:WA().optional()}),dqe=jA({type:xA("pcb_smtpad"),shape:xA("rotated_rect"),pcb_smtpad_id:We("pcb_smtpad"),pcb_group_id:H().optional(),subcircuit_id:H().optional(),x:he,y:he,width:WA(),height:WA(),rect_border_radius:WA().optional(),corner_radius:WA().optional(),ccw_rotation:bE,layer:Gr,port_hints:St(H()).optional(),pcb_component_id:H().optional(),pcb_port_id:H().optional(),is_covered_with_solder_mask:gt().optional(),soldermask_margin:WA().optional(),soldermask_margin_left:WA().optional(),soldermask_margin_top:WA().optional(),soldermask_margin_right:WA().optional(),soldermask_margin_bottom:WA().optional()}),Hst=jA({type:xA("pcb_smtpad"),shape:xA("pill"),pcb_smtpad_id:We("pcb_smtpad"),pcb_group_id:H().optional(),subcircuit_id:H().optional(),x:he,y:he,width:WA(),height:WA(),radius:WA(),layer:Gr,port_hints:St(H()).optional(),pcb_component_id:H().optional(),pcb_port_id:H().optional(),is_covered_with_solder_mask:gt().optional(),soldermask_margin:WA().optional()}),pqe=jA({type:xA("pcb_smtpad"),shape:xA("rotated_pill"),pcb_smtpad_id:We("pcb_smtpad"),pcb_group_id:H().optional(),subcircuit_id:H().optional(),x:he,y:he,width:WA(),height:WA(),radius:WA(),ccw_rotation:bE,layer:Gr,port_hints:St(H()).optional(),pcb_component_id:H().optional(),pcb_port_id:H().optional(),is_covered_with_solder_mask:gt().optional(),soldermask_margin:WA().optional()}),fqe=jA({type:xA("pcb_smtpad"),shape:xA("polygon"),pcb_smtpad_id:We("pcb_smtpad"),pcb_group_id:H().optional(),subcircuit_id:H().optional(),points:St(wn),layer:Gr,port_hints:St(H()).optional(),pcb_component_id:H().optional(),pcb_port_id:H().optional(),is_covered_with_solder_mask:gt().optional(),soldermask_margin:WA().optional()}),Yst=zp("shape",[hqe,uqe,dqe,pqe,Hst,fqe]).describe("Defines an SMT pad on the PCB"),yqe=jA({type:xA("pcb_solder_paste"),shape:xA("circle"),pcb_solder_paste_id:We("pcb_solder_paste"),pcb_group_id:H().optional(),subcircuit_id:H().optional(),x:he,y:he,radius:WA(),layer:Gr,pcb_component_id:H().optional(),pcb_smtpad_id:H().optional()}),mqe=jA({type:xA("pcb_solder_paste"),shape:xA("rect"),pcb_solder_paste_id:We("pcb_solder_paste"),pcb_group_id:H().optional(),subcircuit_id:H().optional(),x:he,y:he,width:WA(),height:WA(),layer:Gr,pcb_component_id:H().optional(),pcb_smtpad_id:H().optional()}),wqe=jA({type:xA("pcb_solder_paste"),shape:xA("pill"),pcb_solder_paste_id:We("pcb_solder_paste"),pcb_group_id:H().optional(),subcircuit_id:H().optional(),x:he,y:he,width:WA(),height:WA(),radius:WA(),layer:Gr,pcb_component_id:H().optional(),pcb_smtpad_id:H().optional()}),Dqe=jA({type:xA("pcb_solder_paste"),shape:xA("rotated_rect"),pcb_solder_paste_id:We("pcb_solder_paste"),pcb_group_id:H().optional(),subcircuit_id:H().optional(),x:he,y:he,width:WA(),height:WA(),ccw_rotation:he,layer:Gr,pcb_component_id:H().optional(),pcb_smtpad_id:H().optional()}),Sqe=jA({type:xA("pcb_solder_paste"),shape:xA("oval"),pcb_solder_paste_id:We("pcb_solder_paste"),pcb_group_id:H().optional(),subcircuit_id:H().optional(),x:he,y:he,width:WA(),height:WA(),layer:Gr,pcb_component_id:H().optional(),pcb_smtpad_id:H().optional()}),Jst=Ze([yqe,mqe,wqe,Dqe,Sqe]).describe("Defines solderpaste on the PCB"),Tst=jA({type:xA("pcb_text"),pcb_text_id:We("pcb_text"),pcb_group_id:H().optional(),subcircuit_id:H().optional(),text:H(),center:wn,layer:Gr,width:Vi,height:Vi,lines:WA(),align:se(["bottom-left"])}).describe("Defines text on the PCB"),Kst=jA({route_type:xA("wire"),x:he,y:he,width:he,start_pcb_port_id:H().optional(),end_pcb_port_id:H().optional(),layer:Gr}),Pst=jA({route_type:xA("via"),x:he,y:he,hole_diameter:he.optional(),outer_diameter:he.optional(),from_layer:H(),to_layer:H()}),qst=Ze([Kst,Pst]),Ost=jA({type:xA("pcb_trace"),source_trace_id:H().optional(),pcb_component_id:H().optional(),pcb_trace_id:We("pcb_trace"),pcb_group_id:H().optional(),subcircuit_id:H().optional(),route_thickness_mode:se(["constant","interpolated"]).default("constant").optional(),route_order_index:WA().optional(),should_round_corners:gt().optional(),trace_length:WA().optional(),highlight_color:H().optional(),route:St(qst)}).describe("Defines a trace on the PCB"),Wst=Gl.extend({type:xA("pcb_trace_error"),pcb_trace_error_id:We("pcb_trace_error"),error_type:xA("pcb_trace_error").default("pcb_trace_error"),center:wn.optional(),pcb_trace_id:H(),source_trace_id:H(),pcb_component_ids:St(H()),pcb_port_ids:St(H()),subcircuit_id:H().optional()}).describe("Defines a trace error on the PCB"),Zst=Gl.extend({type:xA("pcb_trace_missing_error"),pcb_trace_missing_error_id:We("pcb_trace_missing_error"),error_type:xA("pcb_trace_missing_error").default("pcb_trace_missing_error"),center:wn.optional(),source_trace_id:H(),pcb_component_ids:St(H()),pcb_port_ids:St(H()),subcircuit_id:H().optional()}).describe("Defines an error when a source trace has no corresponding PCB trace"),Vst=Gl.extend({type:xA("pcb_port_not_matched_error"),pcb_error_id:We("pcb_error"),error_type:xA("pcb_port_not_matched_error").default("pcb_port_not_matched_error"),pcb_component_ids:St(H()),subcircuit_id:H().optional()}).describe("Defines a trace error on the PCB where a port is not matched"),jst=Gl.extend({type:xA("pcb_port_not_connected_error"),pcb_port_not_connected_error_id:We("pcb_port_not_connected_error"),error_type:xA("pcb_port_not_connected_error").default("pcb_port_not_connected_error"),pcb_port_ids:St(H()),pcb_component_ids:St(H()),subcircuit_id:H().optional()}).describe("Defines an error when a pcb port is not connected to any trace"),zst=jA({type:xA("pcb_net"),pcb_net_id:We("pcb_net"),source_net_id:H().optional(),highlight_color:H().optional()}).describe("Defines a net on the PCB"),Xst=jA({type:xA("pcb_via"),pcb_via_id:We("pcb_via"),pcb_group_id:H().optional(),subcircuit_id:H().optional(),subcircuit_connectivity_map_key:H().optional(),x:he,y:he,outer_diameter:he.default("0.6mm"),hole_diameter:he.default("0.25mm"),from_layer:Gr.optional(),to_layer:Gr.optional(),layers:St(Gr),pcb_trace_id:H().optional(),net_is_assignable:gt().optional(),net_assigned:gt().optional(),is_tented:gt().optional()}).describe("Defines a via on the PCB"),$st=jA({type:xA("pcb_board"),pcb_board_id:We("pcb_board"),pcb_panel_id:H().optional(),is_subcircuit:gt().optional(),subcircuit_id:H().optional(),width:Vi.optional(),height:Vi.optional(),center:wn,display_offset_x:H().optional().describe("How to display the x offset for this board, usually corresponding with how the user specified it"),display_offset_y:H().optional().describe("How to display the y offset for this board, usually corresponding with how the user specified it"),thickness:Vi.optional().default(1.4),num_layers:WA().optional().default(4),outline:St(wn).optional(),shape:se(["rect","polygon"]).optional(),material:se(["fr4","fr1"]).default("fr4"),anchor_position:wn.optional(),anchor_alignment:Z_.optional(),position_mode:se(["relative_to_panel_anchor","none"]).optional()}).describe("Defines the board outline of the PCB"),Art=jA({type:xA("pcb_panel"),pcb_panel_id:We("pcb_panel"),width:Vi,height:Vi,center:wn,covered_with_solder_mask:gt().optional().default(!0)}).describe("Defines a PCB panel that can contain multiple boards"),trt=Gl.extend({type:xA("pcb_placement_error"),pcb_placement_error_id:We("pcb_placement_error"),error_type:xA("pcb_placement_error").default("pcb_placement_error"),subcircuit_id:H().optional()}).describe("Defines a placement error on the PCB"),ert=Gl.extend({type:xA("pcb_panelization_placement_error"),pcb_panelization_placement_error_id:We("pcb_panelization_placement_error"),error_type:xA("pcb_panelization_placement_error").default("pcb_panelization_placement_error"),pcb_panel_id:H().optional(),pcb_board_id:H().optional(),subcircuit_id:H().optional()}).describe("Defines a panelization placement error on the PCB"),irt=jA({type:xA("pcb_trace_hint"),pcb_trace_hint_id:We("pcb_trace_hint"),pcb_port_id:H(),pcb_component_id:H(),route:St(xst),subcircuit_id:H().optional()}).describe("A hint that can be used during generation of a PCB trace"),nrt=jA({type:xA("pcb_silkscreen_line"),pcb_silkscreen_line_id:We("pcb_silkscreen_line"),pcb_component_id:H(),pcb_group_id:H().optional(),subcircuit_id:H().optional(),stroke_width:he.default("0.1mm"),x1:he,y1:he,x2:he,y2:he,layer:qy}).describe("Defines a silkscreen line on the PCB"),ort=jA({type:xA("pcb_silkscreen_path"),pcb_silkscreen_path_id:We("pcb_silkscreen_path"),pcb_component_id:H(),pcb_group_id:H().optional(),subcircuit_id:H().optional(),layer:qy,route:St(wn),stroke_width:Vi}).describe("Defines a silkscreen path on the PCB"),srt=jA({type:xA("pcb_silkscreen_text"),pcb_silkscreen_text_id:We("pcb_silkscreen_text"),pcb_group_id:H().optional(),subcircuit_id:H().optional(),font:xA("tscircuit2024").default("tscircuit2024"),font_size:he.default("0.2mm"),pcb_component_id:H(),text:H(),is_knockout:gt().default(!1).optional(),knockout_padding:jA({left:Vi,top:Vi,bottom:Vi,right:Vi}).default({left:"0.2mm",top:"0.2mm",bottom:"0.2mm",right:"0.2mm"}).optional(),ccw_rotation:WA().optional(),layer:Gr,is_mirrored:gt().default(!1).optional(),anchor_position:wn.default({x:0,y:0}),anchor_alignment:Z_.default("center")}).describe("Defines silkscreen text on the PCB"),rrt=jA({type:xA("pcb_copper_text"),pcb_copper_text_id:We("pcb_copper_text"),pcb_group_id:H().optional(),subcircuit_id:H().optional(),font:xA("tscircuit2024").default("tscircuit2024"),font_size:he.default("0.2mm"),pcb_component_id:H(),text:H(),is_knockout:gt().default(!1).optional(),knockout_padding:jA({left:Vi,top:Vi,bottom:Vi,right:Vi}).default({left:"0.2mm",top:"0.2mm",bottom:"0.2mm",right:"0.2mm"}).optional(),ccw_rotation:WA().optional(),layer:Gr,is_mirrored:gt().default(!1).optional(),anchor_position:wn.default({x:0,y:0}),anchor_alignment:Z_.default("center")}).describe("Defines copper text on the PCB"),art=jA({type:xA("pcb_silkscreen_rect"),pcb_silkscreen_rect_id:We("pcb_silkscreen_rect"),pcb_component_id:H(),pcb_group_id:H().optional(),subcircuit_id:H().optional(),center:wn,width:Vi,height:Vi,layer:Gr,stroke_width:Vi.default("1mm"),corner_radius:Vi.optional(),is_filled:gt().default(!0).optional(),has_stroke:gt().optional(),is_stroke_dashed:gt().optional(),ccw_rotation:WA().optional()}).describe("Defines a silkscreen rect on the PCB"),grt=jA({type:xA("pcb_silkscreen_circle"),pcb_silkscreen_circle_id:We("pcb_silkscreen_circle"),pcb_component_id:H(),pcb_group_id:H().optional(),subcircuit_id:H().optional(),center:wn,radius:Vi,layer:qy,stroke_width:Vi.default("1mm")}).describe("Defines a silkscreen circle on the PCB"),crt=jA({type:xA("pcb_silkscreen_oval"),pcb_silkscreen_oval_id:We("pcb_silkscreen_oval"),pcb_component_id:H(),pcb_group_id:H().optional(),subcircuit_id:H().optional(),center:wn,radius_x:he,radius_y:he,layer:qy,ccw_rotation:bE.optional()}).describe("Defines a silkscreen oval on the PCB"),Irt=jA({type:xA("pcb_silkscreen_pill"),pcb_silkscreen_pill_id:We("pcb_silkscreen_pill"),pcb_component_id:H(),pcb_group_id:H().optional(),subcircuit_id:H().optional(),center:wn,width:Vi,height:Vi,layer:Gr,ccw_rotation:WA().optional()}).describe("Defines a silkscreen pill on the PCB"),lrt=jA({type:xA("pcb_fabrication_note_text"),pcb_fabrication_note_text_id:We("pcb_fabrication_note_text"),subcircuit_id:H().optional(),pcb_group_id:H().optional(),font:xA("tscircuit2024").default("tscircuit2024"),font_size:he.default("1mm"),pcb_component_id:H(),text:H(),layer:qy,anchor_position:wn.default({x:0,y:0}),anchor_alignment:se(["center","top_left","top_right","bottom_left","bottom_right"]).default("center"),color:H().optional()}).describe("Defines a fabrication note in text on the PCB, useful for leaving notes for assemblers or fabricators"),Brt=jA({type:xA("pcb_fabrication_note_path"),pcb_fabrication_note_path_id:We("pcb_fabrication_note_path"),pcb_component_id:H(),subcircuit_id:H().optional(),layer:Gr,route:St(wn),stroke_width:Vi,color:H().optional()}).describe("Defines a fabrication path on the PCB for fabricators or assemblers"),Crt=jA({type:xA("pcb_fabrication_note_rect"),pcb_fabrication_note_rect_id:We("pcb_fabrication_note_rect"),pcb_component_id:H(),pcb_group_id:H().optional(),subcircuit_id:H().optional(),center:wn,width:Vi,height:Vi,layer:qy,stroke_width:Vi.default("0.1mm"),corner_radius:Vi.optional(),is_filled:gt().optional(),has_stroke:gt().optional(),is_stroke_dashed:gt().optional(),color:H().optional()}).describe("Defines a fabrication note rectangle on the PCB"),Qrt=jA({type:xA("pcb_fabrication_note_dimension"),pcb_fabrication_note_dimension_id:We("pcb_fabrication_note_dimension"),pcb_component_id:H(),pcb_group_id:H().optional(),subcircuit_id:H().optional(),layer:qy,from:wn,to:wn,text:H().optional(),text_ccw_rotation:WA().optional(),offset:Vi.optional(),offset_distance:Vi.optional(),offset_direction:jA({x:WA(),y:WA()}).optional(),font:xA("tscircuit2024").default("tscircuit2024"),font_size:Vi.default("1mm"),color:H().optional(),arrow_size:Vi.default("1mm")}).describe("Defines a measurement annotation within PCB fabrication notes"),Ert=jA({type:xA("pcb_note_text"),pcb_note_text_id:We("pcb_note_text"),pcb_component_id:H().optional(),pcb_group_id:H().optional(),subcircuit_id:H().optional(),name:H().optional(),font:xA("tscircuit2024").default("tscircuit2024"),font_size:he.default("1mm"),text:H().optional(),anchor_position:wn.default({x:0,y:0}),anchor_alignment:se(["center","top_left","top_right","bottom_left","bottom_right"]).default("center"),color:H().optional()}).describe("Defines a documentation note in text on the PCB"),hrt=jA({type:xA("pcb_note_rect"),pcb_note_rect_id:We("pcb_note_rect"),pcb_component_id:H().optional(),pcb_group_id:H().optional(),subcircuit_id:H().optional(),name:H().optional(),text:H().optional(),center:wn,width:Vi,height:Vi,stroke_width:Vi.default("0.1mm"),corner_radius:Vi.optional(),is_filled:gt().optional(),has_stroke:gt().optional(),is_stroke_dashed:gt().optional(),color:H().optional()}).describe("Defines a rectangular documentation note on the PCB"),urt=jA({type:xA("pcb_note_path"),pcb_note_path_id:We("pcb_note_path"),pcb_component_id:H().optional(),pcb_group_id:H().optional(),subcircuit_id:H().optional(),name:H().optional(),text:H().optional(),route:St(wn),stroke_width:Vi.default("0.1mm"),color:H().optional()}).describe("Defines a polyline documentation note on the PCB"),drt=jA({type:xA("pcb_note_line"),pcb_note_line_id:We("pcb_note_line"),pcb_component_id:H().optional(),pcb_group_id:H().optional(),subcircuit_id:H().optional(),name:H().optional(),text:H().optional(),x1:he,y1:he,x2:he,y2:he,stroke_width:he.default("0.1mm"),color:H().optional(),is_dashed:gt().optional()}).describe("Defines a straight documentation note line on the PCB"),prt=jA({type:xA("pcb_note_dimension"),pcb_note_dimension_id:We("pcb_note_dimension"),pcb_component_id:H().optional(),pcb_group_id:H().optional(),subcircuit_id:H().optional(),name:H().optional(),from:wn,to:wn,text:H().optional(),text_ccw_rotation:WA().optional(),offset_distance:Vi.optional(),offset_direction:jA({x:WA(),y:WA()}).optional(),font:xA("tscircuit2024").default("tscircuit2024"),font_size:Vi.default("1mm"),color:H().optional(),arrow_size:Vi.default("1mm")}).describe("Defines a measurement annotation within PCB documentation notes"),frt=Gl.extend({type:xA("pcb_footprint_overlap_error"),pcb_error_id:We("pcb_error"),error_type:xA("pcb_footprint_overlap_error").default("pcb_footprint_overlap_error"),pcb_smtpad_ids:St(H()).optional(),pcb_plated_hole_ids:St(H()).optional(),pcb_hole_ids:St(H()).optional(),pcb_keepout_ids:St(H()).optional()}).describe("Error emitted when a pcb footprint overlaps with another element"),yrt=jA({type:xA("pcb_keepout"),shape:xA("rect"),pcb_group_id:H().optional(),subcircuit_id:H().optional(),center:wn,width:he,height:he,pcb_keepout_id:H(),layers:St(H()),description:H().optional()}).or(jA({type:xA("pcb_keepout"),shape:xA("circle"),pcb_group_id:H().optional(),subcircuit_id:H().optional(),center:wn,radius:he,pcb_keepout_id:H(),layers:St(H()),description:H().optional()})),w9=jA({type:xA("pcb_cutout"),pcb_cutout_id:We("pcb_cutout"),pcb_group_id:H().optional(),subcircuit_id:H().optional(),pcb_board_id:H().optional(),pcb_panel_id:H().optional()}),mrt=w9.extend({shape:xA("rect"),center:wn,width:Vi,height:Vi,rotation:bE.optional(),corner_radius:Vi.optional()}),wrt=w9.extend({shape:xA("circle"),center:wn,radius:Vi}),Drt=w9.extend({shape:xA("polygon"),points:St(wn)}),Srt=w9.extend({shape:xA("path"),route:St(wn),slot_width:Vi,slot_length:Vi.optional(),space_between_slots:Vi.optional(),slot_corner_radius:Vi.optional()}),brt=zp("shape",[mrt,wrt,Drt,Srt]).describe("Defines a cutout on the PCB, removing board material."),xrt=Gl.extend({type:xA("pcb_missing_footprint_error"),pcb_missing_footprint_error_id:We("pcb_missing_footprint_error"),pcb_group_id:H().optional(),subcircuit_id:H().optional(),error_type:xA("pcb_missing_footprint_error").default("pcb_missing_footprint_error"),source_component_id:H()}).describe("Defines a missing footprint error on the PCB"),_rt=Gl.extend({type:xA("external_footprint_load_error"),external_footprint_load_error_id:We("external_footprint_load_error"),pcb_component_id:H(),source_component_id:H(),pcb_group_id:H().optional(),subcircuit_id:H().optional(),footprinter_string:H().optional(),error_type:xA("external_footprint_load_error").default("external_footprint_load_error")}).describe("Defines an error when an external footprint fails to load"),krt=Gl.extend({type:xA("circuit_json_footprint_load_error"),circuit_json_footprint_load_error_id:We("circuit_json_footprint_load_error"),pcb_component_id:H(),source_component_id:H(),pcb_group_id:H().optional(),subcircuit_id:H().optional(),error_type:xA("circuit_json_footprint_load_error").default("circuit_json_footprint_load_error"),circuit_json:St(Yc()).optional()}).describe("Defines an error when a circuit JSON footprint fails to load"),Frt=jA({type:xA("pcb_group"),pcb_group_id:We("pcb_group"),source_group_id:H(),is_subcircuit:gt().optional(),subcircuit_id:H().optional(),width:Vi.optional(),height:Vi.optional(),center:wn,display_offset_x:H().optional().describe("How to display the x offset for this group, usually corresponding with how the user specified it"),display_offset_y:H().optional().describe("How to display the y offset for this group, usually corresponding with how the user specified it"),outline:St(wn).optional(),anchor_position:wn.optional(),anchor_alignment:Z_.default("center"),position_mode:se(["packed","relative_to_group_anchor","none"]).optional(),positioned_relative_to_pcb_group_id:H().optional(),positioned_relative_to_pcb_board_id:H().optional(),pcb_component_ids:St(H()),child_layout_mode:se(["packed","none"]).optional(),name:H().optional(),description:H().optional(),layout_mode:H().optional(),autorouter_configuration:jA({trace_clearance:Vi}).optional(),autorouter_used_string:H().optional()}).describe("Defines a group of components on the PCB"),Grt=Gl.extend({type:xA("pcb_autorouting_error"),pcb_error_id:We("pcb_autorouting_error"),error_type:xA("pcb_autorouting_error").default("pcb_autorouting_error"),subcircuit_id:H().optional()}).describe("The autorouting has failed to route a portion of the board"),Mrt=jA({type:xA("pcb_manual_edit_conflict_warning"),pcb_manual_edit_conflict_warning_id:We("pcb_manual_edit_conflict_warning"),warning_type:xA("pcb_manual_edit_conflict_warning").default("pcb_manual_edit_conflict_warning"),message:H(),pcb_component_id:H(),pcb_group_id:H().optional(),subcircuit_id:H().optional(),source_component_id:H()}).describe("Warning emitted when a component has both manual placement and explicit pcbX/pcbY coordinates"),Rrt=jA({type:xA("pcb_breakout_point"),pcb_breakout_point_id:We("pcb_breakout_point"),pcb_group_id:H(),subcircuit_id:H().optional(),source_trace_id:H().optional(),source_port_id:H().optional(),source_net_id:H().optional(),x:he,y:he}).describe("Defines a routing target within a pcb_group for a source_trace or source_net"),Nrt=jA({type:xA("pcb_ground_plane"),pcb_ground_plane_id:We("pcb_ground_plane"),source_pcb_ground_plane_id:H(),source_net_id:H(),pcb_group_id:H().optional(),subcircuit_id:H().optional()}).describe("Defines a ground plane on the PCB"),vrt=jA({type:xA("pcb_ground_plane_region"),pcb_ground_plane_region_id:We("pcb_ground_plane_region"),pcb_ground_plane_id:H(),pcb_group_id:H().optional(),subcircuit_id:H().optional(),layer:Gr,points:St(wn)}).describe("Defines a polygon region of a ground plane"),Lrt=jA({type:xA("pcb_thermal_spoke"),pcb_thermal_spoke_id:We("pcb_thermal_spoke"),pcb_ground_plane_id:H(),shape:H(),spoke_count:WA(),spoke_thickness:he,spoke_inner_diameter:he,spoke_outer_diameter:he,pcb_plated_hole_id:H().optional(),subcircuit_id:H().optional()}).describe("Pattern for connecting a ground plane to a plated hole"),jdA=jA({type:xA("pcb_copper_pour"),pcb_copper_pour_id:We("pcb_copper_pour"),pcb_group_id:H().optional(),subcircuit_id:H().optional(),layer:Gr,source_net_id:H().optional(),covered_with_solder_mask:gt().optional().default(!0)}),Urt=jdA.extend({shape:xA("rect"),center:wn,width:Vi,height:Vi,rotation:bE.optional()}),Hrt=jdA.extend({shape:xA("brep"),brep_shape:Sst}),Yrt=jdA.extend({shape:xA("polygon"),points:St(wn)}),Jrt=zp("shape",[Urt,Hrt,Yrt]).describe("Defines a copper pour on the PCB."),Trt=Gl.extend({type:xA("pcb_component_outside_board_error"),pcb_component_outside_board_error_id:We("pcb_component_outside_board_error"),error_type:xA("pcb_component_outside_board_error").default("pcb_component_outside_board_error"),pcb_component_id:H(),pcb_board_id:H(),component_center:wn,component_bounds:jA({min_x:WA(),max_x:WA(),min_y:WA(),max_y:WA()}),subcircuit_id:H().optional(),source_component_id:H().optional()}).describe("Error emitted when a PCB component is placed outside the board boundaries"),Krt=Gl.extend({type:xA("pcb_component_invalid_layer_error"),pcb_component_invalid_layer_error_id:We("pcb_component_invalid_layer_error"),error_type:xA("pcb_component_invalid_layer_error").default("pcb_component_invalid_layer_error"),pcb_component_id:H().optional(),source_component_id:H(),layer:Gr,subcircuit_id:H().optional()}).describe("Error emitted when a component is placed on an invalid layer (components can only be on 'top' or 'bottom' layers)"),Prt=Gl.extend({type:xA("pcb_via_clearance_error"),pcb_error_id:We("pcb_error"),error_type:xA("pcb_via_clearance_error").default("pcb_via_clearance_error"),pcb_via_ids:St(H()).min(2),minimum_clearance:he.optional(),actual_clearance:he.optional(),pcb_center:jA({x:WA().optional(),y:WA().optional()}).optional(),subcircuit_id:H().optional()}).describe("Error emitted when vias are closer than the allowed clearance"),qrt=jA({type:xA("pcb_courtyard_rect"),pcb_courtyard_rect_id:We("pcb_courtyard_rect"),pcb_component_id:H(),pcb_group_id:H().optional(),subcircuit_id:H().optional(),center:wn,width:Vi,height:Vi,layer:qy,color:H().optional()}).describe("Defines a courtyard rectangle on the PCB"),Ort=jA({type:xA("pcb_courtyard_outline"),pcb_courtyard_outline_id:We("pcb_courtyard_outline"),pcb_component_id:H(),pcb_group_id:H().optional(),subcircuit_id:H().optional(),layer:qy,outline:St(wn).min(2),stroke_width:Vi.default("0.1mm"),is_closed:gt().optional(),is_stroke_dashed:gt().optional(),color:H().optional()}).describe("Defines a courtyard outline on the PCB"),Wrt=jA({type:xA("pcb_courtyard_polygon"),pcb_courtyard_polygon_id:We("pcb_courtyard_polygon"),pcb_component_id:H(),pcb_group_id:H().optional(),subcircuit_id:H().optional(),layer:qy,points:St(wn).min(3),color:H().optional()}).describe("Defines a courtyard polygon on the PCB"),Zrt=jA({type:xA("pcb_courtyard_circle"),pcb_courtyard_circle_id:We("pcb_courtyard_circle"),pcb_component_id:H(),pcb_group_id:H().optional(),subcircuit_id:H().optional(),center:wn,radius:Vi,layer:qy,color:H().optional()}).describe("Defines a courtyard circle on the PCB"),Vrt=jA({type:xA("cad_component"),cad_component_id:H(),pcb_component_id:H(),source_component_id:H(),position:YY,rotation:YY.optional(),size:YY.optional(),layer:Gr.optional(),subcircuit_id:H().optional(),footprinter_string:H().optional(),model_obj_url:H().optional(),model_stl_url:H().optional(),model_3mf_url:H().optional(),model_gltf_url:H().optional(),model_glb_url:H().optional(),model_step_url:H().optional(),model_wrl_url:H().optional(),model_unit_to_mm_scale_factor:WA().optional(),model_jscad:Yc().optional(),show_as_translucent_model:gt().optional(),anchor_alignment:se(["center","xy_center_z_board"]).optional().default("center")}).describe("Defines a component on the PCB"),zdA=se(["sinewave","square","triangle","sawtooth"]),bqe=Ze([H(),WA()]).transform(e=>typeof e=="string"?e.endsWith("%")?parseFloat(e.slice(0,-1))/100:parseFloat(e):e).pipe(WA().min(0,"Duty cycle must be non-negative").max(1,"Duty cycle cannot be greater than 100%")),jrt=jA({type:xA("simulation_voltage_source"),simulation_voltage_source_id:We("simulation_voltage_source"),is_dc_source:xA(!0).optional().default(!0),positive_source_port_id:H().optional(),negative_source_port_id:H().optional(),positive_source_net_id:H().optional(),negative_source_net_id:H().optional(),voltage:fb}).describe("Defines a DC voltage source for simulation"),zrt=jA({type:xA("simulation_voltage_source"),simulation_voltage_source_id:We("simulation_voltage_source"),is_dc_source:xA(!1),terminal1_source_port_id:H().optional(),terminal2_source_port_id:H().optional(),terminal1_source_net_id:H().optional(),terminal2_source_net_id:H().optional(),voltage:fb.optional(),frequency:dG.optional(),peak_to_peak_voltage:fb.optional(),wave_shape:zdA.optional(),phase:bE.optional(),duty_cycle:bqe.optional()}).describe("Defines an AC voltage source for simulation"),Xrt=Ze([jrt,zrt]).describe("Defines a voltage source for simulation"),xqe=Ze([H(),WA()]).transform(e=>typeof e=="string"?e.endsWith("%")?parseFloat(e.slice(0,-1))/100:parseFloat(e):e).pipe(WA().min(0,"Duty cycle must be non-negative").max(1,"Duty cycle cannot be greater than 100%")),$rt=jA({type:xA("simulation_current_source"),simulation_current_source_id:We("simulation_current_source"),is_dc_source:xA(!0).optional().default(!0),positive_source_port_id:H().optional(),negative_source_port_id:H().optional(),positive_source_net_id:H().optional(),negative_source_net_id:H().optional(),current:Pv}).describe("Defines a DC current source for simulation"),Aat=jA({type:xA("simulation_current_source"),simulation_current_source_id:We("simulation_current_source"),is_dc_source:xA(!1),terminal1_source_port_id:H().optional(),terminal2_source_port_id:H().optional(),terminal1_source_net_id:H().optional(),terminal2_source_net_id:H().optional(),current:Pv.optional(),frequency:dG.optional(),peak_to_peak_current:Pv.optional(),wave_shape:zdA.optional(),phase:bE.optional(),duty_cycle:xqe.optional()}).describe("Defines an AC current source for simulation"),tat=Ze([$rt,Aat]).describe("Defines a current source for simulation"),eat=Ze([xA("spice_dc_sweep"),xA("spice_dc_operating_point"),xA("spice_transient_analysis"),xA("spice_ac_analysis")]),iat=jA({type:xA("simulation_experiment"),simulation_experiment_id:We("simulation_experiment"),name:H(),experiment_type:eat,time_per_step:HY.optional(),start_time_ms:pG.optional(),end_time_ms:pG.optional()}).describe("Defines a simulation experiment configuration"),nat=jA({type:xA("simulation_transient_voltage_graph"),simulation_transient_voltage_graph_id:We("simulation_transient_voltage_graph"),simulation_experiment_id:H(),timestamps_ms:St(WA()).optional(),voltage_levels:St(WA()),source_component_id:H().optional(),subcircuit_connectivity_map_key:H().optional(),time_per_step:HY,start_time_ms:pG,end_time_ms:pG,name:H().optional(),color:H().optional()}).describe("Stores voltage measurements over time for a simulation"),oat=jA({type:xA("simulation_switch"),simulation_switch_id:We("simulation_switch"),source_component_id:H().optional(),closes_at:pG.optional(),opens_at:pG.optional(),starts_closed:gt().optional(),switching_frequency:dG.optional()}).describe("Defines a switch for simulation timing control"),sat=jA({type:xA("simulation_voltage_probe"),simulation_voltage_probe_id:We("simulation_voltage_probe"),source_component_id:H().optional(),name:H().optional(),signal_input_source_port_id:H().optional(),signal_input_source_net_id:H().optional(),reference_input_source_port_id:H().optional(),reference_input_source_net_id:H().optional(),subcircuit_id:H().optional(),color:H().optional()}).describe("Defines a voltage probe for simulation. If a reference input is not provided, it measures against ground. If a reference input is provided, it measures the differential voltage between two points.").superRefine((e,A)=>{if(e.reference_input_source_port_id||e.reference_input_source_net_id){const i=!!e.signal_input_source_port_id||!!e.reference_input_source_port_id,n=!!e.signal_input_source_net_id||!!e.reference_input_source_net_id;i&&n?A.addIssue({code:Oe.custom,message:"Cannot mix port and net connections in a differential probe."}):i?(!e.signal_input_source_port_id||!e.reference_input_source_port_id)&&A.addIssue({code:Oe.custom,message:"Differential port probe requires both signal_input_source_port_id and reference_input_source_port_id."}):n&&(!e.signal_input_source_net_id||!e.reference_input_source_net_id)&&A.addIssue({code:Oe.custom,message:"Differential net probe requires both signal_input_source_net_id and reference_input_source_net_id."})}else!!e.signal_input_source_port_id==!!e.signal_input_source_net_id&&A.addIssue({code:Oe.custom,message:"A voltage probe must have exactly one of signal_input_source_port_id or signal_input_source_net_id."})}),rat=Gl.extend({type:xA("simulation_unknown_experiment_error"),simulation_unknown_experiment_error_id:We("simulation_unknown_experiment_error"),error_type:xA("simulation_unknown_experiment_error").default("simulation_unknown_experiment_error"),simulation_experiment_id:H().optional(),subcircuit_id:H().optional()}).describe("An unknown error occurred during the simulation experiment."),aat=jA({type:xA("simulation_op_amp"),simulation_op_amp_id:We("simulation_op_amp"),source_component_id:H().optional(),inverting_input_source_port_id:H(),non_inverting_input_source_port_id:H(),output_source_port_id:H(),positive_supply_source_port_id:H(),negative_supply_source_port_id:H()}).describe("Defines a simple ideal operational amplifier for simulation"),gat=Ze([Tot,Yot,Jot,Hot,Pot,Kot,FdA,xdA,y9,kdA,_dA,GdA,MdA,RdA,LdA,UdA,HdA,PdA,YdA,JdA,TdA,KdA,vdA,NdA,Oot,Zot,qot,qdA,OdA,WdA,Vot,jot,_st,vst,xrt,_rt,krt,Mrt,Lst,yrt,Ust,zst,Tst,Ost,Xst,Yst,Jst,$st,Art,Frt,irt,nrt,ort,srt,Irt,rrt,art,grt,crt,Wst,Zst,trt,ert,Vst,jst,Prt,Brt,lrt,Crt,Qrt,Ert,hrt,urt,drt,prt,Grt,frt,Rrt,brt,Nrt,vrt,Lrt,Jrt,Trt,Krt,qrt,Ort,Wrt,Zrt,zot,cst,ost,sst,rst,ast,ist,nst,Ist,gst,Xot,Bst,Cst,lst,ust,dst,pst,fst,wst,yst,mst,Vrt,Xrt,tat,iat,nat,oat,sat,rat,aat]),XdA=gat;const cat=Object.freeze(Object.defineProperty({__proto__:null,all_layers:Wot,any_circuit_element:gat,any_soup_element:XdA,any_source_component:Hot,base_circuit_json_error:Gl,battery_capacity:bot,brep_shape:Sst,cad_component:Vrt,capacitance:SdA,circuit_json_footprint_load_error:krt,current:Pv,distance:he,duration_ms:HY,experiment_type:eat,external_footprint_load_error:_rt,frequency:dG,getZodPrefixedIdWithDefault:We,inductance:Dot,layer_ref:Gr,layer_string:ZdA,length:Vi,ms:pG,ninePointAnchor:Z_,pcbRenderLayer:tqe,pcb_autorouting_error:Grt,pcb_board:$st,pcb_breakout_point:Rrt,pcb_component:_st,pcb_component_invalid_layer_error:Krt,pcb_component_outside_board_error:Trt,pcb_copper_pour:Jrt,pcb_copper_pour_brep:Hrt,pcb_copper_pour_polygon:Yrt,pcb_copper_pour_rect:Urt,pcb_copper_text:rrt,pcb_courtyard_circle:Zrt,pcb_courtyard_outline:Ort,pcb_courtyard_polygon:Wrt,pcb_courtyard_rect:qrt,pcb_cutout:brt,pcb_cutout_circle:wrt,pcb_cutout_path:Srt,pcb_cutout_polygon:Drt,pcb_cutout_rect:mrt,pcb_fabrication_note_dimension:Qrt,pcb_fabrication_note_path:Brt,pcb_fabrication_note_rect:Crt,pcb_fabrication_note_text:lrt,pcb_footprint_overlap_error:frt,pcb_ground_plane:Nrt,pcb_ground_plane_region:vrt,pcb_group:Frt,pcb_hole:vst,pcb_hole_circle_or_square_shape:rqe,pcb_hole_circle_shape:oqe,pcb_hole_oval_shape:aqe,pcb_hole_pill_shape:gqe,pcb_hole_rect_shape:sqe,pcb_hole_rotated_pill_shape:cqe,pcb_keepout:yrt,pcb_manual_edit_conflict_warning:Mrt,pcb_missing_footprint_error:xrt,pcb_net:zst,pcb_note_dimension:prt,pcb_note_line:drt,pcb_note_path:urt,pcb_note_rect:hrt,pcb_note_text:Ert,pcb_panel:Art,pcb_panelization_placement_error:ert,pcb_placement_error:trt,pcb_plated_hole:Lst,pcb_port:Ust,pcb_port_not_connected_error:jst,pcb_port_not_matched_error:Vst,pcb_route_hint:bst,pcb_route_hints:nqe,pcb_silkscreen_circle:grt,pcb_silkscreen_line:nrt,pcb_silkscreen_oval:crt,pcb_silkscreen_path:ort,pcb_silkscreen_pill:Irt,pcb_silkscreen_rect:art,pcb_silkscreen_text:srt,pcb_smtpad:Yst,pcb_smtpad_pill:Hst,pcb_solder_paste:Jst,pcb_text:Tst,pcb_thermal_spoke:Lrt,pcb_trace:Ost,pcb_trace_error:Wst,pcb_trace_hint:irt,pcb_trace_missing_error:Zst,pcb_trace_route_point:qst,pcb_trace_route_point_via:Pst,pcb_trace_route_point_wire:Kst,pcb_via:Xst,pcb_via_clearance_error:Prt,point:wn,point3:YY,point_with_bulge:Dst,port_arrangement:est,position:XPe,position3:$Pe,resistance:f9,ring:VdA,rotation:bE,route_hint_point:xst,schematic_arc:ast,schematic_box:zot,schematic_circle:rst,schematic_component:ist,schematic_component_port_arrangement_by_sides:tst,schematic_component_port_arrangement_by_size:Ast,schematic_debug_line:Est,schematic_debug_object:ust,schematic_debug_object_base:m9,schematic_debug_point:hst,schematic_debug_rect:Qst,schematic_error:Bst,schematic_group:fst,schematic_layout_error:Cst,schematic_line:ost,schematic_manual_edit_conflict_warning:pst,schematic_net_label:lst,schematic_path:Xot,schematic_pin_styles:$ot,schematic_port:Ist,schematic_rect:sst,schematic_sheet:wst,schematic_symbol:nst,schematic_table:yst,schematic_table_cell:mst,schematic_text:cst,schematic_trace:gst,schematic_voltage_probe:dst,simulation_ac_current_source:Aat,simulation_ac_voltage_source:zrt,simulation_current_source:tat,simulation_dc_current_source:$rt,simulation_dc_voltage_source:jrt,simulation_experiment:iat,simulation_op_amp:aat,simulation_switch:oat,simulation_transient_voltage_graph:nat,simulation_unknown_experiment_error:rat,simulation_voltage_probe:sat,simulation_voltage_source:Xrt,size:bdA,source_board:qot,source_component_base:Wc,source_component_internal_connection:Jot,source_failed_to_create_component_error:Rot,source_group:Kot,source_interconnect:Lot,source_manually_placed_via:Zot,source_missing_property_error:Mot,source_net:Pot,source_pcb_ground_plane:Oot,source_pin_missing_trace_warning:WdA,source_pin_must_be_connected_error:Vot,source_port:Yot,source_project_metadata:qdA,source_property_ignored_warning:Not,source_simple_battery:MdA,source_simple_capacitor:xdA,source_simple_chip:FdA,source_simple_crystal:Got,source_simple_current_source:Fot,source_simple_diode:y9,source_simple_fiducial:_ot,source_simple_ground:kot,source_simple_inductor:RdA,source_simple_led:kdA,source_simple_mosfet:TdA,source_simple_op_amp:KdA,source_simple_pin_header:LdA,source_simple_pinout:UdA,source_simple_potentiometer:vdA,source_simple_power_source:GdA,source_simple_push_button:NdA,source_simple_resistor:_dA,source_simple_resonator:HdA,source_simple_switch:PdA,source_simple_test_point:JdA,source_simple_transistor:YdA,source_simple_voltage_probe:vot,source_simple_voltage_source:Uot,source_trace:Tot,source_trace_not_connected_error:OdA,supplier_name:xot,time:zPe,timestamp:Sot,unknown_error_finding_part:jot,visible_layer:qy,voltage:fb,wave_shape:zdA},Symbol.toStringTag,{value:"Module"}));function qi(e,A){return Array.isArray(A)?[e.a*A[0]+e.c*A[1]+e.e,e.b*A[0]+e.d*A[1]+e.f]:{x:e.a*A.x+e.c*A.y+e.e,y:e.b*A.x+e.d*A.y+e.f}}function yb(){return{a:1,c:0,e:0,b:0,d:1,f:0}}function mb(e){const{a:A,b:t,c:i,d:n,e:o,f:s}=e,r=A*n-t*i;return{a:n/r,b:t/-r,c:i/-r,d:A/r,e:(n*o-i*s)/-r,f:(t*o-A*s)/r}}function JY(e){return typeof e>"u"}function rB(e,A=0){return{a:1,c:0,e,b:0,d:1,f:A}}function D9(...e){e=Array.isArray(e[0])?e[0]:e;const A=(t,i)=>({a:t.a*i.a+t.c*i.b,c:t.a*i.c+t.c*i.d,e:t.a*i.e+t.c*i.f+t.e,b:t.b*i.a+t.d*i.b,d:t.b*i.c+t.d*i.d,f:t.b*i.e+t.d*i.f+t.f});switch(e.length){case 0:throw new Error("no matrices provided");case 1:return e[0];case 2:return A(e[0],e[1]);default:{const[t,i,...n]=e,o=A(t,i);return D9(o,...n)}}}function Oy(...e){return D9(...e)}const{cos:_qe,sin:kqe}=Math;function Fqe(e,A,t){const i=_qe(e),n=kqe(e),o={a:i,c:-n,e:0,b:n,d:i,f:0};return JY(A)||JY(t)?o:D9([rB(A,t),o,rB(-A,-t)])}function TY(e,A=void 0,t=void 0,i=void 0){JY(A)&&(A=e);const n={a:e,c:0,e:0,b:0,d:A,f:0};return JY(t)||JY(i)?n:D9([rB(t,i),n,rB(-t,-i)])}function Gqe(e,A){function t(){this.constructor=e}t.prototype=A.prototype,e.prototype=new t}function S9(e,A,t,i){var n=Error.call(this,e);return Object.setPrototypeOf&&Object.setPrototypeOf(n,S9.prototype),n.expected=A,n.found=t,n.location=i,n.name="SyntaxError",n}Gqe(S9,Error);function $dA(e,A,t){return t=t||" ",e.length>A?e:(A-=e.length,t+=t.repeat(A),e+t.slice(0,A))}S9.prototype.format=function(e){var A="Error: "+this.message;if(this.location){var t=null,i;for(i=0;i<e.length;i++)if(e[i].source===this.location.source){t=e[i].text.split(/\r\n|\n|\r/g);break}var n=this.location.start,o=this.location.source&&typeof this.location.source.offset=="function"?this.location.source.offset(n):n,s=this.location.source+":"+o.line+":"+o.column;if(t){var r=this.location.end,a=$dA("",o.line.toString().length," "),g=t[n.line-1],c=n.line===r.line?r.column:g.length+1,I=c-n.column||1;A+=`
@@ -5684,7 +5684,7 @@ test("${g} should solve problem correctly", () => {
5684
5684
  // Add more specific assertions based on expected output
5685
5685
  // expect(solver.netLabelPlacementSolver!.netLabelPlacements).toMatchInlineSnapshot()
5686
5686
  })
5687
- `,I=new Blob([c],{type:"text/plain"}),l=URL.createObjectURL(I),B=document.createElement("a");B.href=l,B.download=`${g}.test.ts`,B.click(),URL.revokeObjectURL(l)}catch(a){alert(`Error generating test.ts for ${e.constructor.name}: ${a instanceof Error?a.message:String(a)}`)}i(!1)};return Z.jsxs("div",{className:`relative ${A}`,ref:n,children:[Z.jsx("button",{className:"px-2 py-1 rounded text-xs cursor-pointer",onClick:()=>i(!t),title:`Download options for ${e.constructor.name}`,children:e.constructor.name}),t&&Z.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:[Z.jsx("button",{className:"w-full text-left px-3 py-2 hover:bg-gray-100 text-xs",onClick:o,children:"Download JSON"}),Z.jsx("button",{className:"w-full text-left px-3 py-2 hover:bg-gray-100 text-xs",onClick:s,children:"Download page.tsx"}),Z.jsx("button",{className:"w-full text-left px-3 py-2 hover:bg-gray-100 text-xs",onClick:r,children:"Download test.ts"})]})]})},dct=e=>e.activeSubSolver?[e,...dct(e.activeSubSolver)]:[e],vZe=({solver:e})=>{const A=dct(e);return Z.jsx("div",{className:"flex gap-1 items-center text-sm pt-1",children:A.map((t,i)=>Z.jsxs("div",{className:"flex items-center",children:[i>0&&Z.jsx("span",{className:"text-gray-400 mx-1",children:"→"}),Z.jsx(NZe,{solver:t})]},t.constructor.name))})},LZe=({solver:e,triggerRender:A,animationSpeed:t=25,onSolverStarted:i,onSolverCompleted:n})=>{const[o,s]=AA.useReducer(Q=>!Q,!1),r=AA.useRef(void 0),a=()=>{!e.solved&&!e.failed&&(e.step(),A())},g=()=>{!e.solved&&!e.failed&&(i&&i(e),e.solve(),A(),n&&n(e))},c=()=>{o?(r.current&&(clearInterval(r.current),r.current=void 0),s()):(s(),r.current=setInterval(()=>{if(e.solved||e.failed){r.current&&(clearInterval(r.current),r.current=void 0),s(),A(),n&&e.solved&&n(e);return}e.step(),A()},t))},I=()=>{const Q=e;if(Q.getCurrentPhase&&!e.solved&&!e.failed){const E=Q.getCurrentPhase();for(;Q.getCurrentPhase()===E&&!e.solved&&!e.failed;)e.step();A()}},l=()=>{if(e.solved||e.failed||o)return;const Q=window.prompt("Step until which iteration?",`${e.iterations}`);if(Q===null)return;const E=Number(Q);if(!Number.isFinite(E)){window.alert("Please enter a valid number for the iteration");return}for(;e.iterations<E&&!e.solved&&!e.failed;)e.step();A(),e.solved&&n&&n(e)};AA.useEffect(()=>()=>{r.current&&clearInterval(r.current)},[]),AA.useEffect(()=>{(e.solved||e.failed)&&o&&(r.current&&(clearInterval(r.current),r.current=void 0),s())},[e.solved,e.failed,o]);const B=e.getCurrentPhase!==void 0,C=B?e.getCurrentPhase():null;return Z.jsxs("div",{className:"space-y-2 p-2 border-b",children:[Z.jsx("div",{className:"flex items-center",children:Z.jsx(vZe,{solver:e})}),Z.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[Z.jsx("button",{onClick:a,disabled:e.solved||e.failed||o,className:"bg-blue-500 hover:bg-blue-600 disabled:bg-gray-300 text-white px-3 py-1 rounded text-sm",children:"Step"}),Z.jsx("button",{onClick:g,disabled:e.solved||e.failed||o,className:"bg-green-500 hover:bg-green-600 disabled:bg-gray-300 text-white px-3 py-1 rounded text-sm",children:"Solve"}),Z.jsx("button",{onClick:c,disabled:e.solved||e.failed,className:`px-3 py-1 rounded text-white text-sm ${o?"bg-red-500 hover:bg-red-600":"bg-yellow-500 hover:bg-yellow-600"} disabled:bg-gray-300`,children:o?"Stop":"Animate"}),Z.jsx("button",{onClick:l,disabled:e.solved||e.failed||o,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"}),B&&Z.jsx("button",{onClick:I,disabled:e.solved||e.failed||o,className:"bg-purple-500 hover:bg-purple-600 disabled:bg-gray-300 text-white px-3 py-1 rounded text-sm",children:"Next Stage"}),Z.jsxs("div",{className:"text-sm text-gray-600",children:["Iterations: ",e.iterations]}),e.timeToSolve!==void 0&&Z.jsxs("div",{className:"text-sm text-gray-600",children:["Time: ",(e.timeToSolve/1e3).toFixed(3),"s"]}),C&&Z.jsxs("div",{className:"text-sm text-gray-600",children:["Phase: ",Z.jsx("span",{className:"font-medium",children:C})]}),e.solved&&Z.jsx("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded text-sm",children:"Solved"}),e.failed&&Z.jsx("div",{className:"px-2 py-1 bg-red-100 text-red-800 rounded text-sm",children:"Failed"})]}),e.error&&Z.jsxs("div",{className:"text-red-600 text-sm",children:["Error: ",e.error]})]})},UZe=(e,A,t)=>{const i=e.currentPipelineStepIndex;return A<i?"Completed":A===i&&e.activeSubSolver?e.activeSubSolver.failed?"Failed":"In Progress":"Not Started"},HZe=(e,A)=>{const i=e.pipelineDef[A].solverName,n=UZe(e,A),o=e[i],s=e.firstIterationOfPhase?.[i]??null,r=e.iterations;let a=0;if(n==="Completed"){const l=e.pipelineDef[A+1],B=l?e.firstIterationOfPhase?.[l.solverName]:void 0;B!==void 0&&s!==null?a=B-s:s!==null&&(a=r-s)}else n==="In Progress"&&s!==null&&(a=r-s);const g=e.timeSpentOnPhase?.[i]??0;let c=0;n==="Completed"?c=1:n==="In Progress"&&o&&(c=o.progress??0);const I=o?.stats??null;return{index:A,name:i,status:n,firstIteration:s,iterations:a,progress:c,timeSpent:g,stats:I&&Object.keys(I).length>0?I:null,solverInstance:o??null}},YZe=({status:e})=>{const A={"Not Started":"text-blue-600","In Progress":"text-yellow-600",Completed:"text-green-600",Failed:"text-red-600"};return Z.jsx("span",{className:`font-medium ${A[e]}`,children:e})},JZe=({progress:e})=>{if(e===0)return null;const A=Math.round(e*100);return Z.jsxs("div",{className:"flex items-center gap-2",children:[Z.jsx("div",{className:"w-20 h-2 bg-gray-200 rounded overflow-hidden",children:Z.jsx("div",{className:"h-full bg-blue-500 transition-all duration-200",style:{width:`${A}%`}})}),Z.jsxs("span",{className:"text-xs text-gray-500",children:[A,"%"]})]})},TZe=e=>Object.entries(e).map(([A,t])=>`${A}: ${t}`).join(", "),KZe=({stats:e})=>{if(!e||Object.keys(e).length===0)return Z.jsx("span",{children:"-"});const A=Object.entries(e),t=TZe(e);return Z.jsxs("details",{className:"cursor-pointer",children:[Z.jsx("summary",{className:"whitespace-nowrap overflow-hidden text-ellipsis max-w-[200px]",children:t}),Z.jsx("div",{className:"mt-1 text-xs",children:A.map(([i,n])=>Z.jsxs("div",{children:[i,": ",String(n)]},i))})]})},ZpA=e=>{if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(ZpA);const A={};for(const[t,i]of Object.entries(e))t.startsWith("_")||(A[t]=ZpA(i));return A},PZe=(e,A)=>{try{if(typeof e.getConstructorParams!="function"){alert(`getConstructorParams() is not implemented for ${A}`);return}const t=ZpA(e.getConstructorParams()),i=new Blob([JSON.stringify(t,null,2)],{type:"application/json"}),n=URL.createObjectURL(i),o=document.createElement("a");o.href=n,o.download=`${A}_input.json`,o.click(),URL.revokeObjectURL(n)}catch(t){alert(`Error downloading input for ${A}: ${t instanceof Error?t.message:String(t)}`)}},qZe=({solver:e,onStepUntilPhase:A,onDownloadInput:t})=>{const i=e.pipelineDef.map((r,a)=>HZe(e,a)),n=r=>{A?.(r)},o=r=>{r.solverInstance&&(t?t(r.solverInstance,r.name):PZe(r.solverInstance,r.name))},s=r=>`${(r/1e3).toFixed(2)}s`;return Z.jsxs("div",{className:"border-t border-gray-200",children:[Z.jsx("div",{className:"px-4 py-2 bg-gray-50 border-b border-gray-200",children:Z.jsx("h3",{className:"text-sm font-semibold text-gray-700",children:"Pipeline Steps"})}),Z.jsx("div",{className:"overflow-x-auto",children:Z.jsxs("table",{className:"w-full text-sm",children:[Z.jsx("thead",{children:Z.jsxs("tr",{className:"bg-gray-50 border-b border-gray-200",children:[Z.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Step"}),Z.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Status"}),Z.jsxs("th",{className:"px-4 py-2 text-center font-semibold text-gray-700",children:["i",Z.jsx("sub",{children:"0"})]}),Z.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Iterations"}),Z.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Progress"}),Z.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Time"}),Z.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Stats"}),Z.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Input"})]})}),Z.jsx("tbody",{children:i.map(r=>Z.jsxs("tr",{className:`border-b border-gray-100 ${r.status==="In Progress"?"bg-yellow-50":""}`,children:[Z.jsx("td",{className:"px-4 py-2",children:Z.jsxs("div",{className:"flex items-center gap-2",children:[Z.jsx("span",{className:"text-gray-400 w-6",children:String(r.index+1).padStart(2,"0")}),Z.jsx("button",{onClick:()=>n(r.name),disabled:r.status==="Completed"||e.solved||e.failed,className:"text-blue-500 hover:text-blue-700 disabled:text-gray-300 disabled:cursor-not-allowed",title:`Step until ${r.name} completes`,children:Z.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",className:"w-4 h-4",children:Z.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"})})}),Z.jsx("span",{className:"font-medium text-gray-900",children:r.name})]})}),Z.jsx("td",{className:"px-4 py-2",children:Z.jsx(YZe,{status:r.status})}),Z.jsx("td",{className:"px-4 py-2 text-center text-gray-600",children:r.firstIteration!==null?r.firstIteration:""}),Z.jsx("td",{className:"px-4 py-2 text-gray-600",children:r.iterations}),Z.jsx("td",{className:"px-4 py-2",children:Z.jsx(JZe,{progress:r.progress})}),Z.jsx("td",{className:"px-4 py-2 text-gray-600",children:s(r.timeSpent)}),Z.jsx("td",{className:"px-4 py-2 text-gray-500",children:Z.jsx(KZe,{stats:r.stats})}),Z.jsx("td",{className:"px-4 py-2",children:r.solverInstance?Z.jsxs("button",{onClick:()=>o(r),className:"flex items-center gap-1 text-blue-500 hover:text-blue-700",title:`Download input for ${r.name}`,children:[Z.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",className:"w-4 h-4",children:Z.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"})}),Z.jsx("span",{children:"Input"})]}):null})]},r.name))})]})})]})},OZe=class extends nn.Component{constructor(e){super(e),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e){console.error("InteractiveGraphics render error:",e)}render(){return this.state.hasError?this.props.fallback:this.props.children}};function WZe({graphics:e}){const A=e.points??[],t=e.lines??[],i=e.rects??[],n=e.circles??[],o=e.texts??[];let s=Number.POSITIVE_INFINITY,r=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY,g=Number.NEGATIVE_INFINITY;const c=(E,h)=>{typeof E=="number"&&(E<s&&(s=E),E>a&&(a=E)),typeof h=="number"&&(h<r&&(r=h),h>g&&(g=h))};for(const E of A)c(E.x,E.y);for(const E of t){const h=E.points??[];for(const u of h)c(u.x,u.y)}for(const E of i){const h=E.x??0,u=E.y??0,d=E.width??0,f=E.height??0;c(h,u),c(h+d,u+f)}for(const E of n){const h=E.x??0,u=E.y??0,d=E.radius??1;c(h-d,u-d),c(h+d,u+d)}for(const E of o)c(E.x,E.y);(!isFinite(s)||!isFinite(r)||!isFinite(a)||!isFinite(g))&&(s=-20,r=-20,a=20,g=20);const I=10,l=s-I,B=r-I,C=Math.max(1,a-s+2*I),Q=Math.max(1,g-r+2*I);return Z.jsxs("svg",{className:"w-full h-[400px] bg-white",viewBox:`${l} ${B} ${C} ${Q}`,role:"img","aria-label":"Graphics fallback",children:[i.map((E,h)=>Z.jsx("rect",{x:E.x??0,y:E.y??0,width:E.width??0,height:E.height??0,fill:"none",stroke:E.strokeColor??"black",strokeWidth:E.strokeWidth??1},`rect-${h}`)),t.map((E,h)=>Z.jsx("polyline",{fill:"none",stroke:E.strokeColor??"black",strokeWidth:E.strokeWidth??1,points:(E.points??[]).map(u=>`${u.x??0},${u.y??0}`).join(" ")},`line-${h}`)),n.map((E,h)=>Z.jsx("circle",{cx:E.x??0,cy:E.y??0,r:E.radius??1.5,fill:E.fillColor??"none",stroke:E.strokeColor??"black",strokeWidth:E.strokeWidth??1},`circle-${h}`)),A.map((E,h)=>Z.jsx("circle",{cx:E.x??0,cy:E.y??0,r:E.radius??1.5,fill:E.color??"black"},`point-${h}`)),o.map((E,h)=>Z.jsx("text",{x:E.x??0,y:E.y??0,fontSize:E.fontSize??10,fill:E.color??"black",children:E.text??""},`text-${h}`))]})}var ZZe=({solver:e,animationSpeed:A=25,onSolverStarted:t,onSolverCompleted:i})=>{const[n,o]=AA.useReducer(c=>c+1,0),s=AA.useMemo(()=>{try{return e.visualize()||{points:[],lines:[],rects:[],circles:[]}}catch(c){return console.error("Visualization error:",c),{points:[],lines:[],rects:[],circles:[]}}},[e,n]),r=AA.useMemo(()=>(s.rects?.length||0)===0&&(s.lines?.length||0)===0&&(s.points?.length||0)===0&&(s.circles?.length||0)===0,[s]);AA.useEffect(()=>{if(!(typeof document>"u")&&!document.querySelector('script[src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"]')){const c=document.createElement("script");c.src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4",document.head.appendChild(c)}},[]);const a=e.pipelineDef!==void 0,g=c=>{const I=e;if(!e.solved&&!e.failed){for(;!e.solved&&!e.failed&&I.currentPipelineStepIndex<=I.pipelineDef.findIndex(l=>l.solverName===c);)e.step();o()}};return Z.jsxs("div",{children:[Z.jsx(LZe,{solver:e,triggerRender:o,animationSpeed:A,onSolverStarted:t,onSolverCompleted:i}),r?Z.jsx("div",{className:"p-4 text-gray-500",children:"No Graphics Yet"}):Z.jsx(OZe,{fallback:Z.jsx(WZe,{graphics:s}),children:Z.jsx(RZe,{graphics:s})}),a&&Z.jsx(qZe,{solver:e,onStepUntilPhase:g})]})};const VZe=()=>{AA.useEffect(()=>{const e="tailwind-cdn-script";if(document.getElementById(e)||window.tailwind)return;const A=document.createElement("div");A.className="hidden",document.body.appendChild(A);const t=window.getComputedStyle(A).display==="none";if(document.body.removeChild(A),t)return;const i=document.createElement("script");i.id=e,i.src="https://cdn.tailwindcss.com",document.head.appendChild(i)},[])},jZe=e=>e.toLowerCase().includes("pack")?UGe:e.toLowerCase().includes("rout")?PGe:_Ge,zZe=({solverEvents:e=[]})=>{const[A,t]=AA.useState(null);VZe();const i=AA.useMemo(()=>{const r=new Map;for(const a of e){const g=`${a.componentName}-${a.solverName}`;r.set(g,a)}return r},[e]),n=AA.useMemo(()=>Array.from(i.keys()),[i]),o=A?i.get(A):null,s=AA.useMemo(()=>{if(!o)return{instance:null,error:null,classFound:!1};const r=rrA[o.solverName];if(!r)return{instance:null,error:`Solver class "${o.solverName}" not found in SOLVERS registry. Available: ${Object.keys(rrA).join(", ")}`,classFound:!1};try{const a=o.solverParams,g=a?.input!==void 0?a.input:a;return{instance:new r(g),error:null,classFound:!0}}catch(a){const g=a instanceof Error?a.message:String(a);return console.error("Failed to reconstruct solver:",a),{instance:null,error:`Failed to instantiate solver: ${g}`,classFound:!0}}},[o]);return e.length===0?Z.jsx("div",{className:"rf-p-4",children:Z.jsx("div",{className:"rf-bg-gray-50 rf-rounded-md rf-border rf-border-gray-200",children:Z.jsxs("div",{className:"rf-p-4",children:[Z.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-gray-800 rf-mb-3",children:"No Solvers Detected"}),Z.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."})]})})}):Z.jsxs("div",{className:"rf-flex rf-h-full rf-overflow-hidden",children:[Z.jsxs("div",{className:"rf-w-64 rf-border-r rf-border-gray-200 rf-overflow-y-auto rf-flex-shrink-0",children:[Z.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:[n.length," ",n.length===1?"Solver":"Solvers"]}),n.map(r=>{const a=i.get(r),g=A===r;return Z.jsx("div",{className:`rf-px-3 rf-py-2 rf-cursor-pointer rf-border-b rf-border-gray-100 ${g?"rf-bg-blue-50 rf-border-l-2 rf-border-l-blue-500":"hover:rf-bg-gray-50"}`,onClick:()=>t(r),children:(()=>{const c=jZe(a.solverName);return Z.jsxs("div",{className:"rf-flex rf-items-center rf-gap-2",children:[Z.jsx(c,{className:"rf-w-4 rf-h-4 rf-text-blue-500 rf-flex-shrink-0"}),Z.jsxs("div",{className:"rf-flex-1 rf-min-w-0",children:[Z.jsx("div",{className:"rf-text-sm rf-font-medium rf-text-gray-800 rf-truncate",children:a.componentName}),Z.jsx("div",{className:"rf-text-xs rf-text-gray-500 rf-truncate",children:a.solverName})]})]})})()},r)})]}),Z.jsx("div",{className:"rf-flex-1 rf-overflow-hidden",children:o?s.instance?Z.jsx(dD,{fallback:Z.jsx("div",{className:"rf-p-4",children:Z.jsxs("div",{className:"rf-bg-red-50 rf-rounded-md rf-border rf-border-red-200 rf-p-4",children:[Z.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-red-800 rf-mb-2",children:"Error Loading Solver Debugger"}),Z.jsxs("p",{className:"rf-text-sm rf-text-red-600",children:["Failed to render the solver debugger for"," ",o.solverName]})]})}),children:Z.jsx(ZZe,{solver:s.instance})}):Z.jsxs("div",{className:"rf-p-4",children:[Z.jsxs("div",{className:"rf-mb-4",children:[Z.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-gray-800",children:o.solverName}),Z.jsxs("p",{className:"rf-text-sm rf-text-gray-500",children:["Component: ",o.componentName]})]}),s.error&&Z.jsx("div",{className:`rf-rounded-md rf-border rf-p-4 rf-mb-4 ${s.classFound?"rf-bg-red-50 rf-border-red-200":"rf-bg-yellow-50 rf-border-yellow-200"}`,children:Z.jsx("p",{className:`rf-text-sm ${s.classFound?"rf-text-red-700":"rf-text-yellow-700"}`,children:s.error})}),Z.jsxs("div",{className:"rf-border rf-border-gray-200 rf-rounded-md rf-overflow-hidden",children:[Z.jsx("div",{className:"rf-px-3 rf-py-2 rf-bg-gray-50",children:Z.jsx("span",{className:"rf-text-sm rf-font-medium rf-text-gray-700",children:"Solver Parameters"})}),Z.jsx("div",{className:"rf-p-3 rf-bg-white rf-border-t rf-border-gray-200",children:Z.jsx("pre",{className:"rf-text-xs rf-font-mono rf-text-gray-600 rf-whitespace-pre-wrap rf-overflow-x-auto",children:JSON.stringify(o.solverParams,null,2)})})]})]}):Z.jsx("div",{className:"rf-flex rf-items-center rf-justify-center rf-h-full",children:Z.jsx("p",{className:"rf-text-sm rf-text-gray-500",children:"Select a solver from the list to view details"})})})]})},pct=({errorMessage:e,errorStack:A,circuitJsonErrors:t})=>{AA.useEffect(()=>{if(e){const i=new Error(e);A&&(i.stack=A);try{UK.captureException(i)}catch{}}},[e,A]),AA.useEffect(()=>{if(t&&t.length>0)for(const i of t){const n=new Error(i.message||"Circuit JSON Error");i.stack&&(n.stack=i.stack);try{UK.captureException(n,{error_type:i.type})}catch{}}},[t])},fct="0.0.1639",XZe={version:fct},VpA={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1},jpA=new Map,BV=e=>{const A=jpA.get(e);return A?Object.fromEntries(Object.entries(A.stores).map(([t,i])=>[t,i.getState()])):{}},$Ze=(e,A,t)=>{if(e===void 0)return{type:"untracked",connection:A.connect(t)};const i=jpA.get(t.name);if(i)return{type:"tracked",store:e,...i};const n={connection:A.connect(t),stores:{}};return jpA.set(t.name,n),{type:"tracked",store:e,...n}},yct=(e,A={})=>(t,i,n)=>{const{enabled:o,anonymousActionType:s,store:r,...a}=A;let g;try{g=(o??(VpA?"production":void 0)!=="production")&&window.__REDUX_DEVTOOLS_EXTENSION__}catch{}if(!g)return(VpA?"production":void 0)!=="production"&&o&&console.warn("[zustand devtools middleware] Please install/enable Redux devtools extension"),e(t,i,n);const{connection:c,...I}=$Ze(r,g,a);let l=!0;n.setState=(Q,E,h)=>{const u=t(Q,E);if(!l)return u;const d=h===void 0?{type:s||"anonymous"}:typeof h=="string"?{type:h}:h;return r===void 0?(c?.send(d,i()),u):(c?.send({...d,type:`${r}/${d.type}`},{...BV(a.name),[r]:n.getState()}),u)};const B=(...Q)=>{const E=l;l=!1,t(...Q),l=E},C=e(n.setState,i,n);if(I.type==="untracked"?c?.init(C):(I.stores[I.store]=n,c?.init(Object.fromEntries(Object.entries(I.stores).map(([Q,E])=>[Q,Q===I.store?C:E.getState()])))),n.dispatchFromDevtools&&typeof n.dispatch=="function"){let Q=!1;const E=n.dispatch;n.dispatch=(...h)=>{(VpA?"production":void 0)!=="production"&&h[0].type==="__setState"&&!Q&&(console.warn('[zustand devtools middleware] "__setState" action type is reserved to set state from the devtools. Avoid using it.'),Q=!0),E(...h)}}return c.subscribe(Q=>{var E;switch(Q.type){case"ACTION":if(typeof Q.payload!="string"){console.error("[zustand devtools middleware] Unsupported action format");return}return zpA(Q.payload,h=>{if(h.type==="__setState"){if(r===void 0){B(h.state);return}Object.keys(h.state).length!==1&&console.error(`
5687
+ `,I=new Blob([c],{type:"text/plain"}),l=URL.createObjectURL(I),B=document.createElement("a");B.href=l,B.download=`${g}.test.ts`,B.click(),URL.revokeObjectURL(l)}catch(a){alert(`Error generating test.ts for ${e.constructor.name}: ${a instanceof Error?a.message:String(a)}`)}i(!1)};return Z.jsxs("div",{className:`relative ${A}`,ref:n,children:[Z.jsx("button",{className:"px-2 py-1 rounded text-xs cursor-pointer",onClick:()=>i(!t),title:`Download options for ${e.constructor.name}`,children:e.constructor.name}),t&&Z.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:[Z.jsx("button",{className:"w-full text-left px-3 py-2 hover:bg-gray-100 text-xs",onClick:o,children:"Download JSON"}),Z.jsx("button",{className:"w-full text-left px-3 py-2 hover:bg-gray-100 text-xs",onClick:s,children:"Download page.tsx"}),Z.jsx("button",{className:"w-full text-left px-3 py-2 hover:bg-gray-100 text-xs",onClick:r,children:"Download test.ts"})]})]})},dct=e=>e.activeSubSolver?[e,...dct(e.activeSubSolver)]:[e],vZe=({solver:e})=>{const A=dct(e);return Z.jsx("div",{className:"flex gap-1 items-center text-sm pt-1",children:A.map((t,i)=>Z.jsxs("div",{className:"flex items-center",children:[i>0&&Z.jsx("span",{className:"text-gray-400 mx-1",children:"→"}),Z.jsx(NZe,{solver:t})]},t.constructor.name))})},LZe=({solver:e,triggerRender:A,animationSpeed:t=25,onSolverStarted:i,onSolverCompleted:n})=>{const[o,s]=AA.useReducer(Q=>!Q,!1),r=AA.useRef(void 0),a=()=>{!e.solved&&!e.failed&&(e.step(),A())},g=()=>{!e.solved&&!e.failed&&(i&&i(e),e.solve(),A(),n&&n(e))},c=()=>{o?(r.current&&(clearInterval(r.current),r.current=void 0),s()):(s(),r.current=setInterval(()=>{if(e.solved||e.failed){r.current&&(clearInterval(r.current),r.current=void 0),s(),A(),n&&e.solved&&n(e);return}e.step(),A()},t))},I=()=>{const Q=e;if(Q.getCurrentPhase&&!e.solved&&!e.failed){const E=Q.getCurrentPhase();for(;Q.getCurrentPhase()===E&&!e.solved&&!e.failed;)e.step();A()}},l=()=>{if(e.solved||e.failed||o)return;const Q=window.prompt("Step until which iteration?",`${e.iterations}`);if(Q===null)return;const E=Number(Q);if(!Number.isFinite(E)){window.alert("Please enter a valid number for the iteration");return}for(;e.iterations<E&&!e.solved&&!e.failed;)e.step();A(),e.solved&&n&&n(e)};AA.useEffect(()=>()=>{r.current&&clearInterval(r.current)},[]),AA.useEffect(()=>{(e.solved||e.failed)&&o&&(r.current&&(clearInterval(r.current),r.current=void 0),s())},[e.solved,e.failed,o]);const B=e.getCurrentPhase!==void 0,C=B?e.getCurrentPhase():null;return Z.jsxs("div",{className:"space-y-2 p-2 border-b",children:[Z.jsx("div",{className:"flex items-center",children:Z.jsx(vZe,{solver:e})}),Z.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[Z.jsx("button",{onClick:a,disabled:e.solved||e.failed||o,className:"bg-blue-500 hover:bg-blue-600 disabled:bg-gray-300 text-white px-3 py-1 rounded text-sm",children:"Step"}),Z.jsx("button",{onClick:g,disabled:e.solved||e.failed||o,className:"bg-green-500 hover:bg-green-600 disabled:bg-gray-300 text-white px-3 py-1 rounded text-sm",children:"Solve"}),Z.jsx("button",{onClick:c,disabled:e.solved||e.failed,className:`px-3 py-1 rounded text-white text-sm ${o?"bg-red-500 hover:bg-red-600":"bg-yellow-500 hover:bg-yellow-600"} disabled:bg-gray-300`,children:o?"Stop":"Animate"}),Z.jsx("button",{onClick:l,disabled:e.solved||e.failed||o,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"}),B&&Z.jsx("button",{onClick:I,disabled:e.solved||e.failed||o,className:"bg-purple-500 hover:bg-purple-600 disabled:bg-gray-300 text-white px-3 py-1 rounded text-sm",children:"Next Stage"}),Z.jsxs("div",{className:"text-sm text-gray-600",children:["Iterations: ",e.iterations]}),e.timeToSolve!==void 0&&Z.jsxs("div",{className:"text-sm text-gray-600",children:["Time: ",(e.timeToSolve/1e3).toFixed(3),"s"]}),C&&Z.jsxs("div",{className:"text-sm text-gray-600",children:["Phase: ",Z.jsx("span",{className:"font-medium",children:C})]}),e.solved&&Z.jsx("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded text-sm",children:"Solved"}),e.failed&&Z.jsx("div",{className:"px-2 py-1 bg-red-100 text-red-800 rounded text-sm",children:"Failed"})]}),e.error&&Z.jsxs("div",{className:"text-red-600 text-sm",children:["Error: ",e.error]})]})},UZe=(e,A,t)=>{const i=e.currentPipelineStepIndex;return A<i?"Completed":A===i&&e.activeSubSolver?e.activeSubSolver.failed?"Failed":"In Progress":"Not Started"},HZe=(e,A)=>{const i=e.pipelineDef[A].solverName,n=UZe(e,A),o=e[i],s=e.firstIterationOfPhase?.[i]??null,r=e.iterations;let a=0;if(n==="Completed"){const l=e.pipelineDef[A+1],B=l?e.firstIterationOfPhase?.[l.solverName]:void 0;B!==void 0&&s!==null?a=B-s:s!==null&&(a=r-s)}else n==="In Progress"&&s!==null&&(a=r-s);const g=e.timeSpentOnPhase?.[i]??0;let c=0;n==="Completed"?c=1:n==="In Progress"&&o&&(c=o.progress??0);const I=o?.stats??null;return{index:A,name:i,status:n,firstIteration:s,iterations:a,progress:c,timeSpent:g,stats:I&&Object.keys(I).length>0?I:null,solverInstance:o??null}},YZe=({status:e})=>{const A={"Not Started":"text-blue-600","In Progress":"text-yellow-600",Completed:"text-green-600",Failed:"text-red-600"};return Z.jsx("span",{className:`font-medium ${A[e]}`,children:e})},JZe=({progress:e})=>{if(e===0)return null;const A=Math.round(e*100);return Z.jsxs("div",{className:"flex items-center gap-2",children:[Z.jsx("div",{className:"w-20 h-2 bg-gray-200 rounded overflow-hidden",children:Z.jsx("div",{className:"h-full bg-blue-500 transition-all duration-200",style:{width:`${A}%`}})}),Z.jsxs("span",{className:"text-xs text-gray-500",children:[A,"%"]})]})},TZe=e=>Object.entries(e).map(([A,t])=>`${A}: ${t}`).join(", "),KZe=({stats:e})=>{if(!e||Object.keys(e).length===0)return Z.jsx("span",{children:"-"});const A=Object.entries(e),t=TZe(e);return Z.jsxs("details",{className:"cursor-pointer",children:[Z.jsx("summary",{className:"whitespace-nowrap overflow-hidden text-ellipsis max-w-[200px]",children:t}),Z.jsx("div",{className:"mt-1 text-xs",children:A.map(([i,n])=>Z.jsxs("div",{children:[i,": ",String(n)]},i))})]})},ZpA=e=>{if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(ZpA);const A={};for(const[t,i]of Object.entries(e))t.startsWith("_")||(A[t]=ZpA(i));return A},PZe=(e,A)=>{try{if(typeof e.getConstructorParams!="function"){alert(`getConstructorParams() is not implemented for ${A}`);return}const t=ZpA(e.getConstructorParams()),i=new Blob([JSON.stringify(t,null,2)],{type:"application/json"}),n=URL.createObjectURL(i),o=document.createElement("a");o.href=n,o.download=`${A}_input.json`,o.click(),URL.revokeObjectURL(n)}catch(t){alert(`Error downloading input for ${A}: ${t instanceof Error?t.message:String(t)}`)}},qZe=({solver:e,onStepUntilPhase:A,onDownloadInput:t})=>{const i=e.pipelineDef.map((r,a)=>HZe(e,a)),n=r=>{A?.(r)},o=r=>{r.solverInstance&&(t?t(r.solverInstance,r.name):PZe(r.solverInstance,r.name))},s=r=>`${(r/1e3).toFixed(2)}s`;return Z.jsxs("div",{className:"border-t border-gray-200",children:[Z.jsx("div",{className:"px-4 py-2 bg-gray-50 border-b border-gray-200",children:Z.jsx("h3",{className:"text-sm font-semibold text-gray-700",children:"Pipeline Steps"})}),Z.jsx("div",{className:"overflow-x-auto",children:Z.jsxs("table",{className:"w-full text-sm",children:[Z.jsx("thead",{children:Z.jsxs("tr",{className:"bg-gray-50 border-b border-gray-200",children:[Z.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Step"}),Z.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Status"}),Z.jsxs("th",{className:"px-4 py-2 text-center font-semibold text-gray-700",children:["i",Z.jsx("sub",{children:"0"})]}),Z.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Iterations"}),Z.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Progress"}),Z.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Time"}),Z.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Stats"}),Z.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Input"})]})}),Z.jsx("tbody",{children:i.map(r=>Z.jsxs("tr",{className:`border-b border-gray-100 ${r.status==="In Progress"?"bg-yellow-50":""}`,children:[Z.jsx("td",{className:"px-4 py-2",children:Z.jsxs("div",{className:"flex items-center gap-2",children:[Z.jsx("span",{className:"text-gray-400 w-6",children:String(r.index+1).padStart(2,"0")}),Z.jsx("button",{onClick:()=>n(r.name),disabled:r.status==="Completed"||e.solved||e.failed,className:"text-blue-500 hover:text-blue-700 disabled:text-gray-300 disabled:cursor-not-allowed",title:`Step until ${r.name} completes`,children:Z.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",className:"w-4 h-4",children:Z.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"})})}),Z.jsx("span",{className:"font-medium text-gray-900",children:r.name})]})}),Z.jsx("td",{className:"px-4 py-2",children:Z.jsx(YZe,{status:r.status})}),Z.jsx("td",{className:"px-4 py-2 text-center text-gray-600",children:r.firstIteration!==null?r.firstIteration:""}),Z.jsx("td",{className:"px-4 py-2 text-gray-600",children:r.iterations}),Z.jsx("td",{className:"px-4 py-2",children:Z.jsx(JZe,{progress:r.progress})}),Z.jsx("td",{className:"px-4 py-2 text-gray-600",children:s(r.timeSpent)}),Z.jsx("td",{className:"px-4 py-2 text-gray-500",children:Z.jsx(KZe,{stats:r.stats})}),Z.jsx("td",{className:"px-4 py-2",children:r.solverInstance?Z.jsxs("button",{onClick:()=>o(r),className:"flex items-center gap-1 text-blue-500 hover:text-blue-700",title:`Download input for ${r.name}`,children:[Z.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",className:"w-4 h-4",children:Z.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"})}),Z.jsx("span",{children:"Input"})]}):null})]},r.name))})]})})]})},OZe=class extends nn.Component{constructor(e){super(e),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e){console.error("InteractiveGraphics render error:",e)}render(){return this.state.hasError?this.props.fallback:this.props.children}};function WZe({graphics:e}){const A=e.points??[],t=e.lines??[],i=e.rects??[],n=e.circles??[],o=e.texts??[];let s=Number.POSITIVE_INFINITY,r=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY,g=Number.NEGATIVE_INFINITY;const c=(E,h)=>{typeof E=="number"&&(E<s&&(s=E),E>a&&(a=E)),typeof h=="number"&&(h<r&&(r=h),h>g&&(g=h))};for(const E of A)c(E.x,E.y);for(const E of t){const h=E.points??[];for(const u of h)c(u.x,u.y)}for(const E of i){const h=E.x??0,u=E.y??0,d=E.width??0,f=E.height??0;c(h,u),c(h+d,u+f)}for(const E of n){const h=E.x??0,u=E.y??0,d=E.radius??1;c(h-d,u-d),c(h+d,u+d)}for(const E of o)c(E.x,E.y);(!isFinite(s)||!isFinite(r)||!isFinite(a)||!isFinite(g))&&(s=-20,r=-20,a=20,g=20);const I=10,l=s-I,B=r-I,C=Math.max(1,a-s+2*I),Q=Math.max(1,g-r+2*I);return Z.jsxs("svg",{className:"w-full h-[400px] bg-white",viewBox:`${l} ${B} ${C} ${Q}`,role:"img","aria-label":"Graphics fallback",children:[i.map((E,h)=>Z.jsx("rect",{x:E.x??0,y:E.y??0,width:E.width??0,height:E.height??0,fill:"none",stroke:E.strokeColor??"black",strokeWidth:E.strokeWidth??1},`rect-${h}`)),t.map((E,h)=>Z.jsx("polyline",{fill:"none",stroke:E.strokeColor??"black",strokeWidth:E.strokeWidth??1,points:(E.points??[]).map(u=>`${u.x??0},${u.y??0}`).join(" ")},`line-${h}`)),n.map((E,h)=>Z.jsx("circle",{cx:E.x??0,cy:E.y??0,r:E.radius??1.5,fill:E.fillColor??"none",stroke:E.strokeColor??"black",strokeWidth:E.strokeWidth??1},`circle-${h}`)),A.map((E,h)=>Z.jsx("circle",{cx:E.x??0,cy:E.y??0,r:E.radius??1.5,fill:E.color??"black"},`point-${h}`)),o.map((E,h)=>Z.jsx("text",{x:E.x??0,y:E.y??0,fontSize:E.fontSize??10,fill:E.color??"black",children:E.text??""},`text-${h}`))]})}var ZZe=({solver:e,animationSpeed:A=25,onSolverStarted:t,onSolverCompleted:i})=>{const[n,o]=AA.useReducer(c=>c+1,0),s=AA.useMemo(()=>{try{return e.visualize()||{points:[],lines:[],rects:[],circles:[]}}catch(c){return console.error("Visualization error:",c),{points:[],lines:[],rects:[],circles:[]}}},[e,n]),r=AA.useMemo(()=>(s.rects?.length||0)===0&&(s.lines?.length||0)===0&&(s.points?.length||0)===0&&(s.circles?.length||0)===0,[s]);AA.useEffect(()=>{if(!(typeof document>"u")&&!document.querySelector('script[src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"]')){const c=document.createElement("script");c.src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4",document.head.appendChild(c)}},[]);const a=e.pipelineDef!==void 0,g=c=>{const I=e;if(!e.solved&&!e.failed){for(;!e.solved&&!e.failed&&I.currentPipelineStepIndex<=I.pipelineDef.findIndex(l=>l.solverName===c);)e.step();o()}};return Z.jsxs("div",{children:[Z.jsx(LZe,{solver:e,triggerRender:o,animationSpeed:A,onSolverStarted:t,onSolverCompleted:i}),r?Z.jsx("div",{className:"p-4 text-gray-500",children:"No Graphics Yet"}):Z.jsx(OZe,{fallback:Z.jsx(WZe,{graphics:s}),children:Z.jsx(RZe,{graphics:s})}),a&&Z.jsx(qZe,{solver:e,onStepUntilPhase:g})]})};const VZe=()=>{AA.useEffect(()=>{const e="tailwind-cdn-script";if(document.getElementById(e)||window.tailwind)return;const A=document.createElement("div");A.className="hidden",document.body.appendChild(A);const t=window.getComputedStyle(A).display==="none";if(document.body.removeChild(A),t)return;const i=document.createElement("script");i.id=e,i.src="https://cdn.tailwindcss.com",document.head.appendChild(i)},[])},jZe=e=>e.toLowerCase().includes("pack")?UGe:e.toLowerCase().includes("rout")?PGe:_Ge,zZe=({solverEvents:e=[]})=>{const[A,t]=AA.useState(null);VZe();const i=AA.useMemo(()=>{const r=new Map;for(const a of e){const g=`${a.componentName}-${a.solverName}`;r.set(g,a)}return r},[e]),n=AA.useMemo(()=>Array.from(i.keys()),[i]),o=A?i.get(A):null,s=AA.useMemo(()=>{if(!o)return{instance:null,error:null,classFound:!1};const r=rrA[o.solverName];if(!r)return{instance:null,error:`Solver class "${o.solverName}" not found in SOLVERS registry. Available: ${Object.keys(rrA).join(", ")}`,classFound:!1};try{const a=o.solverParams,g=a?.input!==void 0?a.input:a;return{instance:new r(g),error:null,classFound:!0}}catch(a){const g=a instanceof Error?a.message:String(a);return console.error("Failed to reconstruct solver:",a),{instance:null,error:`Failed to instantiate solver: ${g}`,classFound:!0}}},[o]);return e.length===0?Z.jsx("div",{className:"rf-p-4",children:Z.jsx("div",{className:"rf-bg-gray-50 rf-rounded-md rf-border rf-border-gray-200",children:Z.jsxs("div",{className:"rf-p-4",children:[Z.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-gray-800 rf-mb-3",children:"No Solvers Detected"}),Z.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."})]})})}):Z.jsxs("div",{className:"rf-flex rf-h-full rf-overflow-hidden",children:[Z.jsxs("div",{className:"rf-w-64 rf-border-r rf-border-gray-200 rf-overflow-y-auto rf-flex-shrink-0",children:[Z.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:[n.length," ",n.length===1?"Solver":"Solvers"]}),n.map(r=>{const a=i.get(r),g=A===r;return Z.jsx("div",{className:`rf-px-3 rf-py-2 rf-cursor-pointer rf-border-b rf-border-gray-100 ${g?"rf-bg-blue-50 rf-border-l-2 rf-border-l-blue-500":"hover:rf-bg-gray-50"}`,onClick:()=>t(r),children:(()=>{const c=jZe(a.solverName);return Z.jsxs("div",{className:"rf-flex rf-items-center rf-gap-2",children:[Z.jsx(c,{className:"rf-w-4 rf-h-4 rf-text-blue-500 rf-flex-shrink-0"}),Z.jsxs("div",{className:"rf-flex-1 rf-min-w-0",children:[Z.jsx("div",{className:"rf-text-sm rf-font-medium rf-text-gray-800 rf-truncate",children:a.componentName}),Z.jsx("div",{className:"rf-text-xs rf-text-gray-500 rf-truncate",children:a.solverName})]})]})})()},r)})]}),Z.jsx("div",{className:"rf-flex-1 rf-overflow-hidden",children:o?s.instance?Z.jsx(dD,{fallback:Z.jsx("div",{className:"rf-p-4",children:Z.jsxs("div",{className:"rf-bg-red-50 rf-rounded-md rf-border rf-border-red-200 rf-p-4",children:[Z.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-red-800 rf-mb-2",children:"Error Loading Solver Debugger"}),Z.jsxs("p",{className:"rf-text-sm rf-text-red-600",children:["Failed to render the solver debugger for"," ",o.solverName]})]})}),children:Z.jsx(ZZe,{solver:s.instance})}):Z.jsxs("div",{className:"rf-p-4",children:[Z.jsxs("div",{className:"rf-mb-4",children:[Z.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-gray-800",children:o.solverName}),Z.jsxs("p",{className:"rf-text-sm rf-text-gray-500",children:["Component: ",o.componentName]})]}),s.error&&Z.jsx("div",{className:`rf-rounded-md rf-border rf-p-4 rf-mb-4 ${s.classFound?"rf-bg-red-50 rf-border-red-200":"rf-bg-yellow-50 rf-border-yellow-200"}`,children:Z.jsx("p",{className:`rf-text-sm ${s.classFound?"rf-text-red-700":"rf-text-yellow-700"}`,children:s.error})}),Z.jsxs("div",{className:"rf-border rf-border-gray-200 rf-rounded-md rf-overflow-hidden",children:[Z.jsx("div",{className:"rf-px-3 rf-py-2 rf-bg-gray-50",children:Z.jsx("span",{className:"rf-text-sm rf-font-medium rf-text-gray-700",children:"Solver Parameters"})}),Z.jsx("div",{className:"rf-p-3 rf-bg-white rf-border-t rf-border-gray-200",children:Z.jsx("pre",{className:"rf-text-xs rf-font-mono rf-text-gray-600 rf-whitespace-pre-wrap rf-overflow-x-auto",children:JSON.stringify(o.solverParams,null,2)})})]})]}):Z.jsx("div",{className:"rf-flex rf-items-center rf-justify-center rf-h-full",children:Z.jsx("p",{className:"rf-text-sm rf-text-gray-500",children:"Select a solver from the list to view details"})})})]})},pct=({errorMessage:e,errorStack:A,circuitJsonErrors:t})=>{AA.useEffect(()=>{if(e){const i=new Error(e);A&&(i.stack=A);try{UK.captureException(i)}catch{}}},[e,A]),AA.useEffect(()=>{if(t&&t.length>0)for(const i of t){const n=new Error(i.message||"Circuit JSON Error");i.stack&&(n.stack=i.stack);try{UK.captureException(n,{error_type:i.type})}catch{}}},[t])},fct="0.0.1640",XZe={version:fct},VpA={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1},jpA=new Map,BV=e=>{const A=jpA.get(e);return A?Object.fromEntries(Object.entries(A.stores).map(([t,i])=>[t,i.getState()])):{}},$Ze=(e,A,t)=>{if(e===void 0)return{type:"untracked",connection:A.connect(t)};const i=jpA.get(t.name);if(i)return{type:"tracked",store:e,...i};const n={connection:A.connect(t),stores:{}};return jpA.set(t.name,n),{type:"tracked",store:e,...n}},yct=(e,A={})=>(t,i,n)=>{const{enabled:o,anonymousActionType:s,store:r,...a}=A;let g;try{g=(o??(VpA?"production":void 0)!=="production")&&window.__REDUX_DEVTOOLS_EXTENSION__}catch{}if(!g)return(VpA?"production":void 0)!=="production"&&o&&console.warn("[zustand devtools middleware] Please install/enable Redux devtools extension"),e(t,i,n);const{connection:c,...I}=$Ze(r,g,a);let l=!0;n.setState=(Q,E,h)=>{const u=t(Q,E);if(!l)return u;const d=h===void 0?{type:s||"anonymous"}:typeof h=="string"?{type:h}:h;return r===void 0?(c?.send(d,i()),u):(c?.send({...d,type:`${r}/${d.type}`},{...BV(a.name),[r]:n.getState()}),u)};const B=(...Q)=>{const E=l;l=!1,t(...Q),l=E},C=e(n.setState,i,n);if(I.type==="untracked"?c?.init(C):(I.stores[I.store]=n,c?.init(Object.fromEntries(Object.entries(I.stores).map(([Q,E])=>[Q,Q===I.store?C:E.getState()])))),n.dispatchFromDevtools&&typeof n.dispatch=="function"){let Q=!1;const E=n.dispatch;n.dispatch=(...h)=>{(VpA?"production":void 0)!=="production"&&h[0].type==="__setState"&&!Q&&(console.warn('[zustand devtools middleware] "__setState" action type is reserved to set state from the devtools. Avoid using it.'),Q=!0),E(...h)}}return c.subscribe(Q=>{var E;switch(Q.type){case"ACTION":if(typeof Q.payload!="string"){console.error("[zustand devtools middleware] Unsupported action format");return}return zpA(Q.payload,h=>{if(h.type==="__setState"){if(r===void 0){B(h.state);return}Object.keys(h.state).length!==1&&console.error(`
5688
5688
  [zustand devtools middleware] Unsupported __setState action format.
5689
5689
  When using 'store' option in devtools(), the 'state' should have only one key, which is a value of 'store' that was passed in devtools(),
5690
5690
  and value of this only key should be a state object. Example: { "type": "__setState", "state": { "abc123Store": { "foo": "bar" } } }
@@ -5825,7 +5825,7 @@ ${a.join(`
5825
5825
  `)}};NA.register(Fii);var aEt=class cSA extends NA{static token="locked";static parentToken="group";token="locked";value;constructor(A){super(),this.value=A}static fromSexprPrimitives(A){if(A.length===0)return new cSA(!0);const t=pi(A[0]);return new cSA(t==="yes")}getString(){return this.value?"(locked yes)":"(locked no)"}};NA.register(aEt);var gEt=class ayt extends NA{static token="members";static parentToken="group";token="members";members;constructor(A){super(),this.members=A}static fromSexprPrimitives(A){const t=[];for(const i of A){const n=pi(i);n&&t.push(n)}return new ayt(t)}getString(){return this.members.length===0?"(members)":`(members ${this.members.map(t=>`"${t}"`).join(" ")})`}};NA.register(gEt);var HmA=class gyt extends NA{static token="end";static parentToken="segment";token="end";_x;_y;constructor(A,t){super(),this._x=A,this._y=t}static fromSexprPrimitives(A){const[t,i]=A,n=ai(t),o=ai(i);if(n===void 0||o===void 0)throw new Error("end expects two numeric arguments");return new gyt(n,o)}get x(){return this._x}set x(A){this._x=A}get y(){return this._y}set y(A){this._y=A}toObject(){return{x:this._x,y:this._y}}getChildren(){return[]}getString(){return`(end ${this._x} ${this._y})`}};NA.register(HmA);var Gii=new Set(["true","yes","1"]),cEt=class Zz extends Ml{static token="locked";static parentToken="segment";token="locked";constructor(A){super(A)}static fromSexprPrimitives(A){const[t]=A;return typeof t=="boolean"?new Zz(t):typeof t=="string"?new Zz(Gii.has(t.toLowerCase())):new Zz(!1)}getString(){return`(locked ${this.value?"yes":"no"})`}};NA.register(cEt);var uj=class cyt extends NA{static token="net";static parentToken="segment";token="net";_id;_name;constructor(A,t){super(),this._id=A,this._name=t}static fromSexprPrimitives(A){const[t,i]=A,n=ai(t);if(n===void 0)throw new Error("net expects a numeric identifier");const o=i===void 0?void 0:pi(i);return new cyt(n,o??void 0)}get id(){return this._id}set id(A){this._id=A}get name(){return this._name}set name(A){this._name=A===""?void 0:A}toObject(){return this._name===void 0?{id:this._id}:{id:this._id,name:this._name}}getChildren(){return[]}getString(){const A=this._name?` ${Bn(this._name)}`:"";return`(net ${this._id}${A})`}};NA.register(uj);var YmA=class Iyt extends NA{static token="start";static parentToken="segment";token="start";_x;_y;constructor(A,t){super(),this._x=A,this._y=t}static fromSexprPrimitives(A){const[t,i]=A,n=ai(t),o=ai(i);if(n===void 0||o===void 0)throw new Error("start expects two numeric arguments");return new Iyt(n,o)}get x(){return this._x}set x(A){this._x=A}get y(){return this._y}set y(A){this._y=A}toObject(){return{x:this._x,y:this._y}}getChildren(){return[]}getString(){return`(start ${this._x} ${this._y})`}};NA.register(YmA);var IEt=new Set(["start","end","width","layer","net","tstamp","uuid","locked"]),JmA=class lyt extends NA{static token="segment";token="segment";_sxStart;_sxEnd;_sxWidth;_sxLayer;_sxNet;_sxTstamp;_sxUuid;_sxLocked;constructor(A={}){super(),A.start!==void 0&&(this.start=A.start),A.end!==void 0&&(this.end=A.end),A.width!==void 0&&(this.width=A.width),A.layer!==void 0&&(this.layer=A.layer),A.net!==void 0&&(this.net=A.net),A.tstamp!==void 0&&(this.tstamp=A.tstamp),A.uuid!==void 0&&(this.uuid=A.uuid),A.locked!==void 0&&(this.locked=A.locked)}static fromSexprPrimitives(A){const t=new lyt,{propertyMap:i,arrayPropertyMap:n}=NA.parsePrimitivesToClassProperties(A,this.token),o=Object.keys(i).filter(r=>!IEt.has(r));if(o.length>0)throw new Error(`Unsupported child tokens inside segment expression: ${o.join(", ")}`);for(const[r,a]of Object.entries(n)){if(!IEt.has(r))throw new Error(`Unsupported child tokens inside segment expression: ${r}`);if(a.length>1)throw new Error(`Segment does not support repeated child tokens: ${r}`)}t._sxStart=n.start?.[0]??i.start,t._sxEnd=n.end?.[0]??i.end,t._sxWidth=n.width?.[0]??i.width,t._sxLayer=n.layer?.[0]??i.layer,t._sxNet=n.net?.[0]??i.net;const s=n.locked?.[0]??i.locked;return t._sxLocked=s&&s.value?s:void 0,t._sxTstamp=n.tstamp?.[0]??i.tstamp,t._sxUuid=n.uuid?.[0]??i.uuid,t}get start(){return this._sxStart}set start(A){this._sxStart=this.normalizeStart(A)}get end(){return this._sxEnd}set end(A){this._sxEnd=this.normalizeEnd(A)}get startPoint(){return this._sxStart?.toObject()}get endPoint(){return this._sxEnd?.toObject()}get width(){return this._sxWidth?.value}set width(A){if(A===void 0){this._sxWidth=void 0;return}this._sxWidth=A instanceof Mr?A:new Mr(A)}get widthClass(){return this._sxWidth}set widthClass(A){this._sxWidth=A}get layer(){return this._sxLayer}set layer(A){if(A===void 0){this._sxLayer=void 0;return}if(A instanceof mr){this._sxLayer=A;return}const t=Array.isArray(A)?A:[A];this._sxLayer=new mr(t)}get net(){return this._sxNet}set net(A){if(A===void 0){this._sxNet=void 0;return}if(A instanceof uj){this._sxNet=A;return}this._sxNet=new uj(A.id,A.name)}get tstamp(){return this._sxTstamp}set tstamp(A){if(A===void 0){this._sxTstamp=void 0;return}this._sxTstamp=A instanceof Zg?A:new Zg(A)}get uuid(){return this._sxUuid}set uuid(A){if(A===void 0){this._sxUuid=void 0;return}this._sxUuid=A instanceof Li?A:new Li(A)}get locked(){return this._sxLocked?.value??!1}set locked(A){this._sxLocked=A?new cEt(!0):void 0}getChildren(){const A=[];return this._sxStart&&A.push(this._sxStart),this._sxEnd&&A.push(this._sxEnd),this._sxWidth&&A.push(this._sxWidth),this._sxLayer&&A.push(this._sxLayer),this._sxNet&&A.push(this._sxNet),this._sxLocked&&A.push(this._sxLocked),this._sxTstamp&&A.push(this._sxTstamp),this._sxUuid&&A.push(this._sxUuid),A}normalizeStart(A){if(A!==void 0)return A instanceof YmA?A:new YmA(A.x,A.y)}normalizeEnd(A){if(A!==void 0)return A instanceof HmA?A:new HmA(A.x,A.y)}};NA.register(JmA);var lEt=class Byt extends NA{static token="zone";token="zone";_rawChildren=[];static fromSexprPrimitives(A){const t=new Byt;return t._rawChildren=[...A],t}get rawChildren(){return[...this._rawChildren]}set rawChildren(A){this._rawChildren=[...A]}getChildren(){return[]}getString(){const A=["(zone"];for(const t of this._rawChildren)A.push(` ${_E(t)}`);return A.push(")"),A.join(`
5826
5826
  `)}};NA.register(lEt);var dj=class Cyt extends NA{static token="layers";token="layers";_names=[];constructor(A=[]){super(),this.names=A}static fromSexprPrimitives(A){const t=A.map(i=>typeof i=="string"||typeof i=="number"?String(i):_E(i));return new Cyt(t)}get names(){return[...this._names]}set names(A){this._names=A.map(t=>String(t))}getString(){return`(layers ${this._names.map(t=>/^[^\s()"]+$/u.test(t)&&!["nil","#t","#f"].includes(t)?t:Bn(t)).join(" ")})`}};NA.register(dj);var UJ=class extends NA{_value;quoteStringValue=!1;constructor(e){super(),this._value=e}static fromSexprPrimitives(e){const[A]=e,t=this.parsePrimitiveValue(A),i=this;return new i(t)}static parsePrimitiveValue(e){const A=pi(e);if(A===void 0)throw new Error(`${this.name} expects a primitive value`);return A}get value(){return this._value}set value(e){this._value=e}getChildren(){return[]}formatValue(){return typeof this._value=="string"?this.quoteStringValue?Bn(this._value):this._value:`${this._value}`}getString(){return`(${this.token} ${this.formatValue()})`}},Mii=class extends NA{_values;constructor(e){super(),this._values=e}static fromSexprPrimitives(e){const A=e.map(i=>{const n=ai(i);if(n===void 0)throw new Error(`${this.name} expects numeric primitives but received ${i}`);return n}),t=this;return new t(A)}get values(){return[...this._values]}set values(e){this._values=[...e]}getChildren(){return[]}getString(){return`(${this.token} ${this._values.join(" ")})`}},Rii=class extends NA{_x;_y;constructor(e,A){super(),this._x=e,this._y=A}static fromSexprPrimitives(e){const[A,t]=e,i=ai(A),n=ai(t);if(i===void 0||n===void 0)throw new Error(`${this.name} expects two numeric values`);const o=this;return new o(i,n)}get x(){return this._x}set x(e){this._x=e}get y(){return this._y}set y(e){this._y=e}getChildren(){return[]}getString(){return`(${this.token} ${this._x} ${this._y})`}},wr=class extends UJ{static parentToken="pcbplotparams"},jy=class extends wr{static parsePrimitiveValue(e){const A=ai(e);if(A===void 0)throw new Error(`pcbplotparams ${this.token} expects a numeric value`);return A}},BEt=class extends wr{static token="layerselection";token="layerselection"};NA.register(BEt);var CEt=class extends wr{static token="plot_on_all_layers_selection";token="plot_on_all_layers_selection"};NA.register(CEt);var QEt=class extends jy{static token="dashed_line_dash_ratio";token="dashed_line_dash_ratio"};NA.register(QEt);var EEt=class extends jy{static token="dashed_line_gap_ratio";token="dashed_line_gap_ratio"};NA.register(EEt);var hEt=class extends jy{static token="svgprecision";token="svgprecision"};NA.register(hEt);var uEt=class extends jy{static token="linewidth";token="linewidth"};NA.register(uEt);var dEt=class extends jy{static token="mode";token="mode"};NA.register(dEt);var pEt=class extends jy{static token="hpglpennumber";token="hpglpennumber"};NA.register(pEt);var fEt=class extends jy{static token="hpglpenspeed";token="hpglpenspeed"};NA.register(fEt);var yEt=class extends jy{static token="hpglpendiameter";token="hpglpendiameter"};NA.register(yEt);var mEt=class extends jy{static token="hpglpenoverlay";token="hpglpenoverlay"};NA.register(mEt);var wEt=class extends jy{static token="outputformat";token="outputformat"};NA.register(wEt);var DEt=class extends jy{static token="drillshape";token="drillshape"};NA.register(DEt);var SEt=class extends jy{static token="scaleselection";token="scaleselection"};NA.register(SEt);var bEt=class extends wr{static token="disableapertmacros";token="disableapertmacros"};NA.register(bEt);var xEt=class extends wr{static token="usegerberextensions";token="usegerberextensions"};NA.register(xEt);var _Et=class extends wr{static token="usegerberattributes";token="usegerberattributes"};NA.register(_Et);var kEt=class extends wr{static token="usegerberadvancedattributes";token="usegerberadvancedattributes"};NA.register(kEt);var FEt=class extends wr{static token="creategerberjobfile";token="creategerberjobfile"};NA.register(FEt);var GEt=class extends wr{static token="excludeedgelayer";token="excludeedgelayer"};NA.register(GEt);var MEt=class extends wr{static token="plotframeref";token="plotframeref"};NA.register(MEt);var REt=class extends wr{static token="viasonmask";token="viasonmask"};NA.register(REt);var NEt=class extends wr{static token="useauxorigin";token="useauxorigin"};NA.register(NEt);var vEt=class extends wr{static token="pdf_front_fp_property_popups";token="pdf_front_fp_property_popups"};NA.register(vEt);var LEt=class extends wr{static token="pdf_back_fp_property_popups";token="pdf_back_fp_property_popups"};NA.register(LEt);var UEt=class extends wr{static token="pdf_metadata";token="pdf_metadata"};NA.register(UEt);var HEt=class extends wr{static token="pdf_single_document";token="pdf_single_document"};NA.register(HEt);var YEt=class extends wr{static token="dxfpolygonmode";token="dxfpolygonmode"};NA.register(YEt);var JEt=class extends wr{static token="dxfimperialunits";token="dxfimperialunits"};NA.register(JEt);var TEt=class extends wr{static token="dxfusepcbnewfont";token="dxfusepcbnewfont"};NA.register(TEt);var KEt=class extends wr{static token="psnegative";token="psnegative"};NA.register(KEt);var PEt=class extends wr{static token="psa4output";token="psa4output"};NA.register(PEt);var qEt=class extends wr{static token="plotreference";token="plotreference"};NA.register(qEt);var OEt=class extends wr{static token="plotvalue";token="plotvalue"};NA.register(OEt);var WEt=class extends wr{static token="plotothertext";token="plotothertext"};NA.register(WEt);var ZEt=class extends wr{static token="plotinvisibletext";token="plotinvisibletext"};NA.register(ZEt);var VEt=class extends wr{static token="padsonsilk";token="padsonsilk"};NA.register(VEt);var jEt=class extends wr{static token="sketchpadsonfab";token="sketchpadsonfab"};NA.register(jEt);var zEt=class extends wr{static token="plotpadnumbers";token="plotpadnumbers"};NA.register(zEt);var XEt=class extends wr{static token="hidednponfab";token="hidednponfab"};NA.register(XEt);var $Et=class extends wr{static token="sketchdnponfab";token="sketchdnponfab"};NA.register($Et);var Aht=class extends wr{static token="crossoutdnponfab";token="crossoutdnponfab"};NA.register(Aht);var tht=class extends wr{static token="subtractmaskfromsilk";token="subtractmaskfromsilk"};NA.register(tht);var eht=class extends wr{static token="plot_black_and_white";token="plot_black_and_white"};NA.register(eht);var iht=class extends wr{static token="mirror";token="mirror"};NA.register(iht);var nht=class extends wr{static token="outputdirectory";token="outputdirectory";quoteStringValue=!0};NA.register(nht);var oht=class extends wr{static token="plot_on_all_layers";token="plot_on_all_layers"};NA.register(oht);var sht=class extends wr{static token="plotinvisible";token="plotinvisible"};NA.register(sht);var Nii={layerselection:"layerselection",plot_on_all_layers_selection:"plot_on_all_layers_selection",disableapertmacros:"disableapertmacros",usegerberextensions:"usegerberextensions",usegerberattributes:"usegerberattributes",usegerberadvancedattributes:"usegerberadvancedattributes",creategerberjobfile:"creategerberjobfile",excludeedgelayer:"excludeedgelayer",dashed_line_dash_ratio:"dashed_line_dash_ratio",dashed_line_gap_ratio:"dashed_line_gap_ratio",svgprecision:"svgprecision",linewidth:"linewidth",plotframeref:"plotframeref",plotreference:"plotreference",plotvalue:"plotvalue",plotothertext:"plotothertext",plotinvisibletext:"plotinvisibletext",padsonsilk:"padsonsilk",sketchpadsonfab:"sketchpadsonfab",plotpadnumbers:"plotpadnumbers",hidednponfab:"hidednponfab",sketchdnponfab:"sketchdnponfab",crossoutdnponfab:"crossoutdnponfab",subtractmaskfromsilk:"subtractmaskfromsilk",plot_black_and_white:"plot_black_and_white",plot_on_all_layers:"plot_on_all_layers",plotinvisible:"plotinvisible",mode:"mode",useauxorigin:"useauxorigin",viasonmask:"viasonmask",hpglpennumber:"hpglpennumber",hpglpenspeed:"hpglpenspeed",hpglpendiameter:"hpglpendiameter",hpglpenoverlay:"hpglpenoverlay",pdf_front_fp_property_popups:"pdf_front_fp_property_popups",pdf_back_fp_property_popups:"pdf_back_fp_property_popups",pdf_metadata:"pdf_metadata",pdf_single_document:"pdf_single_document",dxfpolygonmode:"dxfpolygonmode",dxfimperialunits:"dxfimperialunits",dxfusepcbnewfont:"dxfusepcbnewfont",psnegative:"psnegative",psa4output:"psa4output",mirror:"mirror",outputformat:"outputformat",drillshape:"drillshape",scaleselection:"scaleselection",outputdirectory:"outputdirectory"},vii=["layerselection","plot_on_all_layers_selection","disableapertmacros","usegerberextensions","usegerberattributes","usegerberadvancedattributes","creategerberjobfile","excludeedgelayer","dashed_line_dash_ratio","dashed_line_gap_ratio","svgprecision","linewidth","plotframeref","plotreference","plotvalue","plotothertext","mode","useauxorigin","viasonmask","hpglpennumber","hpglpenspeed","hpglpendiameter","hpglpenoverlay","pdf_front_fp_property_popups","pdf_back_fp_property_popups","pdf_metadata","pdf_single_document","dxfpolygonmode","dxfimperialunits","dxfusepcbnewfont","psnegative","psa4output","plot_black_and_white","plot_on_all_layers","plotinvisible","plotinvisibletext","padsonsilk","sketchpadsonfab","plotpadnumbers","hidednponfab","sketchdnponfab","crossoutdnponfab","subtractmaskfromsilk","outputformat","mirror","drillshape","scaleselection","outputdirectory"],TmA=class Qyt extends NA{static token="pcbplotparams";static parentToken="setup";token="pcbplotparams";_properties={};static fromSexprPrimitives(A){const t=new Qyt,{propertyMap:i}=NA.parsePrimitivesToClassProperties(A,this.token);for(const[n,o]of Object.entries(i)){const s=Nii[n];if(!s)throw new Error(`Unsupported pcbplotparams token: ${n}`);t._properties[s]=o}return t}getChildren(){const A=[];for(const t of vii){const i=this._properties[t];i&&A.push(i)}return A}clearProperty(A){delete this._properties[A]}setStringProperty(A,t,i){if(t===void 0){this.clearProperty(A);return}this._properties[A]=new i(t)}setNumberProperty(A,t,i){if(t===void 0){this.clearProperty(A);return}this._properties[A]=new i(t)}setStringOrNumberProperty(A,t,i){if(t===void 0){this.clearProperty(A);return}this._properties[A]=new i(t)}get layerselection(){return this._properties.layerselection?.value}set layerselection(A){this.setStringOrNumberProperty("layerselection",A,BEt)}get plot_on_all_layers_selection(){return this._properties.plot_on_all_layers_selection?.value}set plot_on_all_layers_selection(A){this.setStringOrNumberProperty("plot_on_all_layers_selection",A,CEt)}get disableapertmacros(){return this._properties.disableapertmacros?.value}set disableapertmacros(A){this.setStringProperty("disableapertmacros",A,bEt)}get usegerberextensions(){return this._properties.usegerberextensions?.value}set usegerberextensions(A){this.setStringProperty("usegerberextensions",A,xEt)}get usegerberattributes(){return this._properties.usegerberattributes?.value}set usegerberattributes(A){this.setStringProperty("usegerberattributes",A,_Et)}get usegerberadvancedattributes(){return this._properties.usegerberadvancedattributes?.value}set usegerberadvancedattributes(A){this.setStringProperty("usegerberadvancedattributes",A,kEt)}get creategerberjobfile(){return this._properties.creategerberjobfile?.value}set creategerberjobfile(A){this.setStringProperty("creategerberjobfile",A,FEt)}get excludeedgelayer(){return this._properties.excludeedgelayer?.value}set excludeedgelayer(A){this.setStringProperty("excludeedgelayer",A,GEt)}get dashed_line_dash_ratio(){return this._properties.dashed_line_dash_ratio?.value}set dashed_line_dash_ratio(A){this.setNumberProperty("dashed_line_dash_ratio",A,QEt)}get dashed_line_gap_ratio(){return this._properties.dashed_line_gap_ratio?.value}set dashed_line_gap_ratio(A){this.setNumberProperty("dashed_line_gap_ratio",A,EEt)}get svgprecision(){return this._properties.svgprecision?.value}set svgprecision(A){this.setNumberProperty("svgprecision",A,hEt)}get linewidth(){return this._properties.linewidth?.value}set linewidth(A){this.setNumberProperty("linewidth",A,uEt)}get plotframeref(){return this._properties.plotframeref?.value}set plotframeref(A){this.setStringProperty("plotframeref",A,MEt)}get plotreference(){return this._properties.plotreference?.value}set plotreference(A){this.setStringProperty("plotreference",A,qEt)}get plotvalue(){return this._properties.plotvalue?.value}set plotvalue(A){this.setStringProperty("plotvalue",A,OEt)}get plotothertext(){return this._properties.plotothertext?.value}set plotothertext(A){this.setStringProperty("plotothertext",A,WEt)}get plotinvisibletext(){return this._properties.plotinvisibletext?.value}set plotinvisibletext(A){this.setStringProperty("plotinvisibletext",A,ZEt)}get padsonsilk(){return this._properties.padsonsilk?.value}set padsonsilk(A){this.setStringProperty("padsonsilk",A,VEt)}get plotpadnumbers(){return this._properties.plotpadnumbers?.value}set plotpadnumbers(A){this.setStringProperty("plotpadnumbers",A,zEt)}get sketchpadsonfab(){return this._properties.sketchpadsonfab?.value}set sketchpadsonfab(A){this.setStringProperty("sketchpadsonfab",A,jEt)}get hidednponfab(){return this._properties.hidednponfab?.value}set hidednponfab(A){this.setStringProperty("hidednponfab",A,XEt)}get sketchdnponfab(){return this._properties.sketchdnponfab?.value}set sketchdnponfab(A){this.setStringProperty("sketchdnponfab",A,$Et)}get crossoutdnponfab(){return this._properties.crossoutdnponfab?.value}set crossoutdnponfab(A){this.setStringProperty("crossoutdnponfab",A,Aht)}get subtractmaskfromsilk(){return this._properties.subtractmaskfromsilk?.value}set subtractmaskfromsilk(A){this.setStringProperty("subtractmaskfromsilk",A,tht)}get plot_black_and_white(){return this._properties.plot_black_and_white?.value}set plot_black_and_white(A){this.setStringProperty("plot_black_and_white",A,eht)}get plot_on_all_layers(){return this._properties.plot_on_all_layers?.value}set plot_on_all_layers(A){this.setStringProperty("plot_on_all_layers",A,oht)}get plotinvisible(){return this._properties.plotinvisible?.value}set plotinvisible(A){this.setStringProperty("plotinvisible",A,sht)}get mode(){return this._properties.mode?.value}set mode(A){this.setNumberProperty("mode",A,dEt)}get useauxorigin(){return this._properties.useauxorigin?.value}set useauxorigin(A){this.setStringProperty("useauxorigin",A,NEt)}get viasonmask(){return this._properties.viasonmask?.value}set viasonmask(A){this.setStringProperty("viasonmask",A,REt)}get hpglpennumber(){return this._properties.hpglpennumber?.value}set hpglpennumber(A){this.setNumberProperty("hpglpennumber",A,pEt)}get hpglpenspeed(){return this._properties.hpglpenspeed?.value}set hpglpenspeed(A){this.setNumberProperty("hpglpenspeed",A,fEt)}get hpglpendiameter(){return this._properties.hpglpendiameter?.value}set hpglpendiameter(A){this.setNumberProperty("hpglpendiameter",A,yEt)}get hpglpenoverlay(){return this._properties.hpglpenoverlay?.value}set hpglpenoverlay(A){this.setNumberProperty("hpglpenoverlay",A,mEt)}get pdf_front_fp_property_popups(){return this._properties.pdf_front_fp_property_popups?.value}set pdf_front_fp_property_popups(A){this.setStringProperty("pdf_front_fp_property_popups",A,vEt)}get pdf_back_fp_property_popups(){return this._properties.pdf_back_fp_property_popups?.value}set pdf_back_fp_property_popups(A){this.setStringProperty("pdf_back_fp_property_popups",A,LEt)}get pdf_metadata(){return this._properties.pdf_metadata?.value}set pdf_metadata(A){this.setStringProperty("pdf_metadata",A,UEt)}get pdf_single_document(){return this._properties.pdf_single_document?.value}set pdf_single_document(A){this.setStringProperty("pdf_single_document",A,HEt)}get dxfpolygonmode(){return this._properties.dxfpolygonmode?.value}set dxfpolygonmode(A){this.setStringProperty("dxfpolygonmode",A,YEt)}get dxfimperialunits(){return this._properties.dxfimperialunits?.value}set dxfimperialunits(A){this.setStringProperty("dxfimperialunits",A,JEt)}get dxfusepcbnewfont(){return this._properties.dxfusepcbnewfont?.value}set dxfusepcbnewfont(A){this.setStringProperty("dxfusepcbnewfont",A,TEt)}get psnegative(){return this._properties.psnegative?.value}set psnegative(A){this.setStringProperty("psnegative",A,KEt)}get psa4output(){return this._properties.psa4output?.value}set psa4output(A){this.setStringProperty("psa4output",A,PEt)}get mirror(){return this._properties.mirror?.value}set mirror(A){this.setStringProperty("mirror",A,iht)}get outputformat(){return this._properties.outputformat?.value}set outputformat(A){this.setNumberProperty("outputformat",A,wEt)}get drillshape(){return this._properties.drillshape?.value}set drillshape(A){this.setNumberProperty("drillshape",A,DEt)}get scaleselection(){return this._properties.scaleselection?.value}set scaleselection(A){this.setNumberProperty("scaleselection",A,SEt)}get outputdirectory(){return this._properties.outputdirectory?.value}set outputdirectory(A){this.setStringProperty("outputdirectory",A,nht)}};NA.register(TmA);var pj=class extends UJ{static parentToken="setup"},KmA=class extends pj{static token="zone_45_only";token="zone_45_only"};NA.register(KmA);var PmA=class extends pj{static token="allow_soldermask_bridges_in_footprints";token="allow_soldermask_bridges_in_footprints"};NA.register(PmA);var qmA=class extends pj{static token="visible_elements";token="visible_elements"};NA.register(qmA);var OmA=class extends pj{static token="uvias_allowed";token="uvias_allowed"};NA.register(OmA);var WmA=class Eyt extends NA{static token="tenting";static parentToken="setup";token="tenting";_sides=[];constructor(A=[]){super(),this.sides=A}static fromSexprPrimitives(A){const t=A.map(i=>pi(i)).filter(i=>i!==void 0);return new Eyt(t)}get sides(){return[...this._sides]}set sides(A){this._sides=A.map(t=>String(t))}getChildren(){return[]}getString(){return this._sides.length===0?"(tenting)":`(tenting ${this._sides.join(" ")})`}};NA.register(WmA);var HJ=class extends Mii{static parentToken="setup"},rht=class extends Rii{static parentToken="setup"},ZmA=class extends HJ{static token="pcb_text_size";token="pcb_text_size"};NA.register(ZmA);var VmA=class extends HJ{static token="mod_text_size";token="mod_text_size"};NA.register(VmA);var jmA=class extends HJ{static token="pad_size";token="pad_size"};NA.register(jmA);var zmA=class extends HJ{static token="pad_to_paste_clearance_values";token="pad_to_paste_clearance_values"};NA.register(zmA);var XmA=class extends HJ{static token="trace_width";token="trace_width"};NA.register(XmA);var $mA=class extends rht{static token="aux_axis_origin";token="aux_axis_origin"};NA.register($mA);var AwA=class extends rht{static token="grid_origin";token="grid_origin"};NA.register(AwA);var gB=class extends UJ{static parentToken="setup";static parsePrimitiveValue(e){const A=ai(e);if(A===void 0)throw new Error(`${this.name} expects a numeric value`);return A}},twA=class extends gB{static token="pad_to_mask_clearance";token="pad_to_mask_clearance"};NA.register(twA);var ewA=class extends gB{static token="solder_mask_min_width";token="solder_mask_min_width"};NA.register(ewA);var iwA=class extends gB{static token="pad_to_paste_clearance";token="pad_to_paste_clearance"};NA.register(iwA);var nwA=class extends gB{static token="pad_to_paste_clearance_ratio";token="pad_to_paste_clearance_ratio"};NA.register(nwA);var owA=class extends gB{static token="last_trace_width";token="last_trace_width"};NA.register(owA);var swA=class extends gB{static token="trace_clearance";token="trace_clearance"};NA.register(swA);var rwA=class extends gB{static token="zone_clearance";token="zone_clearance"};NA.register(rwA);var awA=class extends gB{static token="trace_min";token="trace_min"};NA.register(awA);var gwA=class extends gB{static token="segment_width";token="segment_width"};NA.register(gwA);var cwA=class extends gB{static token="edge_width";token="edge_width"};NA.register(cwA);var IwA=class extends gB{static token="via_size";token="via_size"};NA.register(IwA);var lwA=class extends gB{static token="via_drill";token="via_drill"};NA.register(lwA);var BwA=class extends gB{static token="via_min_size";token="via_min_size"};NA.register(BwA);var CwA=class extends gB{static token="via_min_drill";token="via_min_drill"};NA.register(CwA);var QwA=class extends gB{static token="uvia_size";token="uvia_size"};NA.register(QwA);var EwA=class extends gB{static token="uvia_drill";token="uvia_drill"};NA.register(EwA);var hwA=class extends gB{static token="uvia_min_size";token="uvia_min_size"};NA.register(hwA);var uwA=class extends gB{static token="uvia_min_drill";token="uvia_min_drill"};NA.register(uwA);var dwA=class extends gB{static token="pcb_text_width";token="pcb_text_width"};NA.register(dwA);var pwA=class extends gB{static token="mod_edge_width";token="mod_edge_width"};NA.register(pwA);var fwA=class extends gB{static token="mod_text_width";token="mod_text_width"};NA.register(fwA);var ywA=class extends gB{static token="pad_drill";token="pad_drill"};NA.register(ywA);var YJ=class extends UJ{static parentToken="stackup"},aht=class extends YJ{static token="copper_finish";token="copper_finish";quoteStringValue=!0};NA.register(aht);var ght=class extends YJ{static token="dielectric_constraints";token="dielectric_constraints"};NA.register(ght);var cht=class extends YJ{static token="edge_connector";token="edge_connector"};NA.register(cht);var Iht=class extends YJ{static token="castellated_pads";token="castellated_pads"};NA.register(Iht);var lht=class extends YJ{static token="edge_plating";token="edge_plating"};NA.register(lht);var b1=class extends UJ{static parentToken="layer"},mwA=class extends b1{static token="type";token="type";quoteStringValue=!0};NA.register(mwA);var wwA=class extends b1{static token="color";token="color";quoteStringValue=!0};NA.register(wwA);var DwA=class extends b1{static token="thickness";token="thickness";static parsePrimitiveValue(e){const A=ai(e);if(A===void 0)throw new Error("Stackup layer thickness expects a numeric value");return A}};NA.register(DwA);var SwA=class extends b1{static token="material";token="material";quoteStringValue=!0};NA.register(SwA);var bwA=class extends b1{static token="epsilon_r";token="epsilon_r";static parsePrimitiveValue(e){const A=ai(e);if(A===void 0)throw new Error("Stackup layer epsilon_r expects a numeric value");return A}};NA.register(bwA);var xwA=class extends b1{static token="loss_tangent";token="loss_tangent";static parsePrimitiveValue(e){const A=ai(e);if(A===void 0)throw new Error("Stackup layer loss_tangent expects a numeric value");return A}};NA.register(xwA);var Bht=class hyt extends NA{static token="layer";static parentToken="stackup";token="layer";_name;_number;_sxType;_sxColor;_sxThickness;_sxMaterial;_sxEpsilonR;_sxLossTangent;constructor(A,t={}){super(),this._name=A,this._number=t.number,this._sxType=t.type,this._sxColor=t.color,this._sxThickness=t.thickness,this._sxMaterial=t.material,this._sxEpsilonR=t.epsilonR,this._sxLossTangent=t.lossTangent}static fromSexprPrimitives(A){if(A.length===0)throw new Error("Stackup layer requires at least a name");const t=pi(A[0]);if(t===void 0)throw new Error("Stackup layer name must be a string");let i=1,n;const o=A[i],s=ai(o);s!==void 0&&(n=s,i+=1);const r=A.slice(i),{propertyMap:a}=NA.parsePrimitivesToClassProperties(r,this.token);return new hyt(t,{number:n,type:a.type,color:a.color,thickness:a.thickness,material:a.material,epsilonR:a.epsilon_r,lossTangent:a.loss_tangent})}get name(){return this._name}set name(A){const t=pi(A);if(t===void 0)throw new Error("Stackup layer name must be a string");this._name=t}get number(){return this._number}set number(A){if(A===void 0){this._number=void 0;return}const t=ai(A);if(t===void 0)throw new Error("Stackup layer number must be numeric");this._number=t}get type(){return this._sxType?.value}set type(A){if(A===void 0){this._sxType=void 0;return}this._sxType=A instanceof mwA?A:new mwA(A)}get color(){return this._sxColor?.value}set color(A){if(A===void 0){this._sxColor=void 0;return}this._sxColor=A instanceof wwA?A:new wwA(A)}get thickness(){return this._sxThickness?.value}set thickness(A){if(A===void 0){this._sxThickness=void 0;return}this._sxThickness=A instanceof DwA?A:new DwA(A)}get material(){return this._sxMaterial?.value}set material(A){if(A===void 0){this._sxMaterial=void 0;return}this._sxMaterial=A instanceof SwA?A:new SwA(A)}get epsilonR(){return this._sxEpsilonR?.value}set epsilonR(A){if(A===void 0){this._sxEpsilonR=void 0;return}this._sxEpsilonR=A instanceof bwA?A:new bwA(A)}get lossTangent(){return this._sxLossTangent?.value}set lossTangent(A){if(A===void 0){this._sxLossTangent=void 0;return}this._sxLossTangent=A instanceof xwA?A:new xwA(A)}getChildren(){const A=[];return this._sxType&&A.push(this._sxType),this._sxColor&&A.push(this._sxColor),this._sxThickness&&A.push(this._sxThickness),this._sxMaterial&&A.push(this._sxMaterial),this._sxEpsilonR&&A.push(this._sxEpsilonR),this._sxLossTangent&&A.push(this._sxLossTangent),A}getString(){const A=`(layer ${Bn(this._name)}${this._number!==void 0?` ${this._number}`:""}`,t=this.getChildren();if(t.length===0)return`${A})`;const i=[A];for(const n of t)i.push(n.getStringIndented());return i.push(")"),i.join(`
5827
5827
  `)}};NA.register(Bht);var _wA=class uyt extends NA{static token="stackup";static parentToken="setup";token="stackup";_layers=[];_sxCopperFinish;_sxDielectricConstraints;_sxEdgeConnector;_sxCastellatedPads;_sxEdgePlating;constructor(A={}){super(),this.layers=A.layers??[],this._sxCopperFinish=A.copperFinish,this._sxDielectricConstraints=A.dielectricConstraints,this._sxEdgeConnector=A.edgeConnector,this._sxCastellatedPads=A.castellatedPads,this._sxEdgePlating=A.edgePlating}static fromSexprPrimitives(A){const{propertyMap:t,arrayPropertyMap:i}=NA.parsePrimitivesToClassProperties(A,this.token);return new uyt({layers:i.layer??[],copperFinish:t.copper_finish,dielectricConstraints:t.dielectric_constraints,edgeConnector:t.edge_connector,castellatedPads:t.castellated_pads,edgePlating:t.edge_plating})}get layers(){return[...this._layers]}set layers(A){this._layers=A.map(t=>{if(!(t instanceof Bht))throw new Error("Stackup layers must be StackupLayer instances");return t})}get copperFinish(){return this._sxCopperFinish?.value}set copperFinish(A){this._sxCopperFinish=A?new aht(A):void 0}get dielectricConstraints(){return this._sxDielectricConstraints?.value}set dielectricConstraints(A){this._sxDielectricConstraints=A?new ght(A):void 0}get edgeConnector(){return this._sxEdgeConnector?.value}set edgeConnector(A){this._sxEdgeConnector=A?new cht(A):void 0}get castellatedPads(){return this._sxCastellatedPads?.value}set castellatedPads(A){this._sxCastellatedPads=A?new Iht(A):void 0}get edgePlating(){return this._sxEdgePlating?.value}set edgePlating(A){this._sxEdgePlating=A?new lht(A):void 0}getChildren(){const A=[...this._layers],t=[this._sxCopperFinish,this._sxDielectricConstraints,this._sxEdgeConnector,this._sxCastellatedPads,this._sxEdgePlating];for(const i of t)i&&A.push(i);return A}};NA.register(_wA);var Lii={stackup:"stackup",pcbplotparams:"pcbPlotParams",pad_to_mask_clearance:"padToMaskClearance",solder_mask_min_width:"solderMaskMinWidth",pad_to_paste_clearance:"padToPasteClearance",pad_to_paste_clearance_ratio:"padToPasteClearanceRatio",last_trace_width:"lastTraceWidth",trace_clearance:"traceClearance",zone_clearance:"zoneClearance",zone_45_only:"zone45Only",trace_min:"traceMin",segment_width:"segmentWidth",edge_width:"edgeWidth",via_size:"viaSize",via_drill:"viaDrill",via_min_size:"viaMinSize",via_min_drill:"viaMinDrill",uvias_allowed:"uviasAllowed",uvia_size:"uviaSize",uvia_drill:"uviaDrill",uvia_min_size:"uviaMinSize",uvia_min_drill:"uviaMinDrill",pcb_text_width:"pcbTextWidth",pcb_text_size:"pcbTextSize",mod_edge_width:"modEdgeWidth",mod_text_size:"modTextSize",mod_text_width:"modTextWidth",pad_size:"padSize",pad_drill:"padDrill",allow_soldermask_bridges_in_footprints:"allowSoldermaskBridgesInFootprints",tenting:"tenting",aux_axis_origin:"auxAxisOrigin",grid_origin:"gridOrigin",visible_elements:"visibleElements",pad_to_paste_clearance_values:"padToPasteClearanceValues",trace_width:"traceWidth"},Uii=["stackup","padToMaskClearance","solderMaskMinWidth","padToPasteClearance","padToPasteClearanceRatio","lastTraceWidth","traceClearance","zoneClearance","zone45Only","traceMin","segmentWidth","edgeWidth","viaSize","viaDrill","viaMinSize","viaMinDrill","uviaSize","uviaDrill","uviasAllowed","uviaMinSize","uviaMinDrill","pcbTextWidth","pcbTextSize","modEdgeWidth","modTextSize","modTextWidth","padSize","padDrill","allowSoldermaskBridgesInFootprints","tenting","auxAxisOrigin","gridOrigin","visibleElements","padToPasteClearanceValues","traceWidth","pcbPlotParams"],kwA=class dyt extends NA{static token="setup";token="setup";_properties={};static fromSexprPrimitives(A){const t=new dyt,{propertyMap:i}=NA.parsePrimitivesToClassProperties(A,this.token);for(const[n,o]of Object.entries(i)){const s=Lii[n];if(!s)throw new Error(`Unsupported setup property token: ${n}`);t._properties[s]=o}return t}getChildren(){const A=[];for(const t of Uii){const i=this._properties[t];i&&A.push(i)}return A}setProperty(A,t){if(t){this._properties[A]=t;return}delete this._properties[A]}setNumberProperty(A,t,i){if(t===void 0){delete this._properties[A];return}this._properties[A]=new i(t)}getPropertyInstance(A,t){const i=this._properties[A];return i instanceof t?i:void 0}get stackup(){return this.getPropertyInstance("stackup",_wA)}set stackup(A){if(A!==void 0&&!(A instanceof _wA))throw new Error("stackup must be a Stackup instance");this.setProperty("stackup",A)}get pcbPlotParams(){return this.getPropertyInstance("pcbPlotParams",TmA)}set pcbPlotParams(A){if(A!==void 0&&!(A instanceof TmA))throw new Error("pcbPlotParams must be a PcbPlotParams instance");this.setProperty("pcbPlotParams",A)}get padToMaskClearance(){return this.getPropertyInstance("padToMaskClearance",twA)?.value}set padToMaskClearance(A){this.setNumberProperty("padToMaskClearance",A,twA)}get solderMaskMinWidth(){return this.getPropertyInstance("solderMaskMinWidth",ewA)?.value}set solderMaskMinWidth(A){this.setNumberProperty("solderMaskMinWidth",A,ewA)}get padToPasteClearance(){return this.getPropertyInstance("padToPasteClearance",iwA)?.value}set padToPasteClearance(A){this.setNumberProperty("padToPasteClearance",A,iwA)}get padToPasteClearanceRatio(){return this.getPropertyInstance("padToPasteClearanceRatio",nwA)?.value}set padToPasteClearanceRatio(A){this.setNumberProperty("padToPasteClearanceRatio",A,nwA)}get lastTraceWidth(){return this.getPropertyInstance("lastTraceWidth",owA)?.value}set lastTraceWidth(A){this.setNumberProperty("lastTraceWidth",A,owA)}get traceClearance(){return this.getPropertyInstance("traceClearance",swA)?.value}set traceClearance(A){this.setNumberProperty("traceClearance",A,swA)}get zoneClearance(){return this.getPropertyInstance("zoneClearance",rwA)?.value}set zoneClearance(A){this.setNumberProperty("zoneClearance",A,rwA)}get zone45Only(){return this.getPropertyInstance("zone45Only",KmA)?.value}set zone45Only(A){this.setProperty("zone45Only",A===void 0?void 0:new KmA(A))}get traceMin(){return this.getPropertyInstance("traceMin",awA)?.value}set traceMin(A){this.setNumberProperty("traceMin",A,awA)}get segmentWidth(){return this.getPropertyInstance("segmentWidth",gwA)?.value}set segmentWidth(A){this.setNumberProperty("segmentWidth",A,gwA)}get edgeWidth(){return this.getPropertyInstance("edgeWidth",cwA)?.value}set edgeWidth(A){this.setNumberProperty("edgeWidth",A,cwA)}get viaSize(){return this.getPropertyInstance("viaSize",IwA)?.value}set viaSize(A){this.setNumberProperty("viaSize",A,IwA)}get viaDrill(){return this.getPropertyInstance("viaDrill",lwA)?.value}set viaDrill(A){this.setNumberProperty("viaDrill",A,lwA)}get viaMinSize(){return this.getPropertyInstance("viaMinSize",BwA)?.value}set viaMinSize(A){this.setNumberProperty("viaMinSize",A,BwA)}get viaMinDrill(){return this.getPropertyInstance("viaMinDrill",CwA)?.value}set viaMinDrill(A){this.setNumberProperty("viaMinDrill",A,CwA)}get uviasAllowed(){return this.getPropertyInstance("uviasAllowed",OmA)?.value}set uviasAllowed(A){this.setProperty("uviasAllowed",A===void 0?void 0:new OmA(A))}get uviaSize(){return this.getPropertyInstance("uviaSize",QwA)?.value}set uviaSize(A){this.setNumberProperty("uviaSize",A,QwA)}get uviaDrill(){return this.getPropertyInstance("uviaDrill",EwA)?.value}set uviaDrill(A){this.setNumberProperty("uviaDrill",A,EwA)}get uviaMinSize(){return this.getPropertyInstance("uviaMinSize",hwA)?.value}set uviaMinSize(A){this.setNumberProperty("uviaMinSize",A,hwA)}get uviaMinDrill(){return this.getPropertyInstance("uviaMinDrill",uwA)?.value}set uviaMinDrill(A){this.setNumberProperty("uviaMinDrill",A,uwA)}get pcbTextWidth(){return this.getPropertyInstance("pcbTextWidth",dwA)?.value}set pcbTextWidth(A){this.setNumberProperty("pcbTextWidth",A,dwA)}get pcbTextSize(){return this.getPropertyInstance("pcbTextSize",ZmA)?.values}set pcbTextSize(A){if(A===void 0){delete this._properties.pcbTextSize;return}this.setProperty("pcbTextSize",new ZmA(A))}get modEdgeWidth(){return this.getPropertyInstance("modEdgeWidth",pwA)?.value}set modEdgeWidth(A){this.setNumberProperty("modEdgeWidth",A,pwA)}get modTextSize(){return this.getPropertyInstance("modTextSize",VmA)?.values}set modTextSize(A){if(A===void 0){delete this._properties.modTextSize;return}this.setProperty("modTextSize",new VmA(A))}get modTextWidth(){return this.getPropertyInstance("modTextWidth",fwA)?.value}set modTextWidth(A){this.setNumberProperty("modTextWidth",A,fwA)}get padSize(){return this.getPropertyInstance("padSize",jmA)?.values}set padSize(A){if(A===void 0){delete this._properties.padSize;return}this.setProperty("padSize",new jmA(A))}get padDrill(){return this.getPropertyInstance("padDrill",ywA)?.value}set padDrill(A){this.setNumberProperty("padDrill",A,ywA)}get allowSoldermaskBridgesInFootprints(){return this.getPropertyInstance("allowSoldermaskBridgesInFootprints",PmA)?.value}set allowSoldermaskBridgesInFootprints(A){this.setProperty("allowSoldermaskBridgesInFootprints",A===void 0?void 0:new PmA(A))}get tenting(){return this.getPropertyInstance("tenting",WmA)?.sides}set tenting(A){if(A===void 0){delete this._properties.tenting;return}this.setProperty("tenting",new WmA(A))}get auxAxisOrigin(){const A=this.getPropertyInstance("auxAxisOrigin",$mA);if(A)return{x:A.x,y:A.y}}set auxAxisOrigin(A){if(!A){delete this._properties.auxAxisOrigin;return}this.setProperty("auxAxisOrigin",new $mA(A.x,A.y))}get gridOrigin(){const A=this.getPropertyInstance("gridOrigin",AwA);if(A)return{x:A.x,y:A.y}}set gridOrigin(A){if(!A){delete this._properties.gridOrigin;return}this.setProperty("gridOrigin",new AwA(A.x,A.y))}get visibleElements(){return this.getPropertyInstance("visibleElements",qmA)?.value}set visibleElements(A){this.setProperty("visibleElements",A===void 0?void 0:new qmA(A))}get padToPasteClearanceValues(){return this.getPropertyInstance("padToPasteClearanceValues",zmA)?.values}set padToPasteClearanceValues(A){if(A===void 0){delete this._properties.padToPasteClearanceValues;return}this.setProperty("padToPasteClearanceValues",new zmA(A))}get traceWidth(){return this.getPropertyInstance("traceWidth",XmA)?.values}set traceWidth(A){if(A===void 0){delete this._properties.traceWidth;return}this.setProperty("traceWidth",new XmA(A))}};NA.register(kwA);var Cht=class extends aa{static token="thickness";static parentToken="general";token="thickness"};NA.register(Cht);var Qht=class pyt extends NA{static token="legacy_teardrops";static parentToken="general";token="legacy_teardrops";_enabled;constructor(A){super(),this._enabled=A}static fromSexprPrimitives(A){const t=pi(A[0]);if(t===void 0)throw new Error("legacy_teardrops expects a string value");const i=/^(yes|true)$/iu.test(t);return new pyt(i)}get enabled(){return this._enabled}set enabled(A){this._enabled=A}getChildren(){return[]}getString(){return`(legacy_teardrops ${this._enabled?"yes":"no"})`}};NA.register(Qht);var Eht=new Set(["thickness","legacy_teardrops"]),FwA=class fyt extends NA{static token="general";static parentToken="kicad_pcb";token="general";_sxThickness;_sxLegacyTeardrops;static fromSexprPrimitives(A){const t=new fyt,{propertyMap:i,arrayPropertyMap:n}=NA.parsePrimitivesToClassProperties(A,this.token);for(const o of Object.keys(i))if(!Eht.has(o))throw new Error(`general encountered unsupported child token "${o}"`);for(const[o,s]of Object.entries(n)){if(!Eht.has(o))throw new Error(`general encountered unsupported child token "${o}"`);if(s.length>1)throw new Error(`general encountered repeated child token "${o}"`)}return t._sxThickness=n.thickness?.[0]??i.thickness,t._sxLegacyTeardrops=n.legacy_teardrops?.[0]??i.legacy_teardrops,t}get thickness(){return this._sxThickness?.value}set thickness(A){this._sxThickness=A===void 0?void 0:new Cht(A)}get legacyTeardrops(){return this._sxLegacyTeardrops?.enabled}set legacyTeardrops(A){if(A===void 0){this._sxLegacyTeardrops=void 0;return}this._sxLegacyTeardrops=new Qht(A)}getChildren(){const A=[];return this._sxThickness&&A.push(this._sxThickness),this._sxLegacyTeardrops&&A.push(this._sxLegacyTeardrops),A}};NA.register(FwA);var Rl=class yyt extends NA{static token="__pcb_layer_definition__";static parentToken="layers";token="__pcb_layer_definition__";_index;_name;_type;_userName;constructor(A){super(),this._index=A.index,this._name=A.name,this._type=A.type,this._userName=A.userName}static fromPrimitive(A){if(!Array.isArray(A)||A.length<3)throw new Error(`layers entry must be an array with at least index, name, and type: ${JSON.stringify(A)}`);const[t,i,n,o]=A,s=ai(t),r=pi(i),a=pi(n),g=o===void 0?void 0:pi(o);if(s===void 0||r===void 0||a===void 0)throw new Error(`layers entry is missing required values: ${JSON.stringify(A)}`);return new yyt({index:s,name:r,type:a,userName:g})}get index(){return this._index}set index(A){this._index=A}get name(){return this._name}set name(A){this._name=A}get type(){return this._type}set type(A){this._type=A}get userName(){return this._userName}set userName(A){this._userName=A}getChildren(){return[]}getString(){if(this._index===void 0||this._name===void 0||this._type===void 0)return"()";const A=[String(this._index),Bn(this._name),this._type];return this._userName!==void 0&&A.push(Bn(this._userName)),`(${A.join(" ")})`}};NA.register(Rl);var GwA=class myt extends NA{static token="layers";static parentToken="kicad_pcb";token="layers";_definitions=[];static fromSexprPrimitives(A){const t=new myt;return t._definitions=A.map(i=>Rl.fromPrimitive(i)),t}get definitions(){return[...this._definitions]}set definitions(A){this._definitions=[...A]}getChildren(){return[...this._definitions]}};NA.register(GwA);var fj=class wyt extends NA{static token="net";static parentToken="kicad_pcb";token="net";_id;_name;constructor(A,t){super(),this._id=A,this._name=t}static fromSexprPrimitives(A){const t=ai(A[0]),i=pi(A[1]);if(t===void 0||i===void 0)throw new Error("net requires numeric id and string name");return new wyt(t,i)}get id(){return this._id}set id(A){this._id=A}get name(){return this._name}set name(A){this._name=A}getChildren(){return[]}getString(){return`(net ${this._id} ${Bn(this._name)})`}};NA.register(fj);var MwA=class extends aa{static token="version";static parentToken="kicad_pcb";token="version"};NA.register(MwA);var Hii=e=>/^[A-Za-z0-9._-]+$/.test(e),RwA=class extends Vy{static token="generator";static parentToken="kicad_pcb";token="generator";getString(){return`(generator ${Hii(this.value)?this.value:Bn(this.value)})`}};NA.register(RwA);var Yii=e=>/^[A-Za-z0-9._-]+$/.test(e),NwA=class extends Vy{static token="generator_version";static parentToken="kicad_pcb";token="generator_version";getString(){return`(generator_version ${Yii(this.value)?this.value:Bn(this.value)})`}};NA.register(NwA);var vwA=class Dyt extends NA{static token="net";static parentToken="via";token="net";_id;_name;constructor(A,t){super(),this._id=A,this._name=t}static fromSexprPrimitives(A){const t=ai(A[0]);if(t===void 0)throw new Error("via net requires a numeric id");const i=A.length>1?pi(A[1]):void 0;return new Dyt(t,i)}get id(){return this._id}set id(A){this._id=A}get name(){return this._name}set name(A){this._name=A}getChildren(){return[]}getString(){return this._name!==void 0?`(net ${this._id} ${Bn(this._name)})`:`(net ${this._id})`}};NA.register(vwA);var Jii=new Set(["locked","free","remove_unused_layers","keep_end_layers"]),LwA=class Syt extends NA{static token="via";token="via";_type;_locked=!1;_free=!1;_removeUnusedLayers=!1;_keepEndLayers=!1;_sxAt;_size;_drill;_sxLayers;_sxNet;_sxUuid;_sxTstamp;_sxTeardrops;constructor(A={}){super(),A.type!==void 0&&(this.type=A.type),A.locked!==void 0&&(this.locked=A.locked),A.free!==void 0&&(this.free=A.free),A.removeUnusedLayers!==void 0&&(this.removeUnusedLayers=A.removeUnusedLayers),A.keepEndLayers!==void 0&&(this.keepEndLayers=A.keepEndLayers),A.at!==void 0&&(this.at=A.at),A.size!==void 0&&(this.size=A.size),A.drill!==void 0&&(this.drill=A.drill),A.layers!==void 0&&(this.layers=A.layers),A.net!==void 0&&(this.net=A.net),A.uuid!==void 0&&(this.uuid=A.uuid),A.tstamp!==void 0&&(this.tstamp=A.tstamp),A.teardrops!==void 0&&(this.teardrops=A.teardrops)}static fromSexprPrimitives(A){const t=new Syt;for(const i of A){if(typeof i=="string"){t.consumeBareToken(i);continue}if(!Array.isArray(i)||i.length===0)throw new Error(`via encountered unsupported primitive child: ${JSON.stringify(i)}`);const[n,...o]=i;if(typeof n!="string")throw new Error(`via encountered child with non-string token: ${JSON.stringify(i)}`);t.consumeNode(n,o)}return t}consumeBareToken(A){if(A==="blind"||A==="micro"){this._type=A;return}if(!Jii.has(A))throw new Error(`via encountered unsupported flag "${A}"`);switch(A){case"locked":this._locked=!0;break;case"free":this._free=!0;break;case"remove_unused_layers":this._removeUnusedLayers=!0;break;case"keep_end_layers":this._keepEndLayers=!0;break}}consumeNode(A,t){switch(A){case"type":{const i=pi(t[0]);if(i===void 0)throw new Error("via type expects a string value");this._type=i;return}case"locked":this._locked=this.parseYesNo(t);return;case"free":this._free=this.parseYesNo(t);return;case"remove_unused_layers":this._removeUnusedLayers=this.parseYesNo(t);return;case"keep_end_layers":this._keepEndLayers=this.parseYesNo(t);return;case"at":{const i=NA.parsePrimitiveSexpr(["at",...t],{parentToken:this.token});if(!(i instanceof Wg))throw new Error("via failed to parse at child");this._sxAt=i;return}case"size":{const i=ai(t[0]);if(i===void 0)throw new Error("via size expects a numeric value");this._size=i;return}case"drill":{const i=ai(t[0]);if(i===void 0)throw new Error("via drill expects a numeric value");this._drill=i;return}case"layers":{this._sxLayers=dj.fromSexprPrimitives(t);return}case"net":{this._sxNet=vwA.fromSexprPrimitives(t);return}case"teardrops":{this._sxTeardrops=HQt.fromSexprPrimitives(t);return}case"uuid":{const i=pi(t[0]);if(i===void 0)throw new Error("via uuid expects a string value");this._sxUuid=new Li(i);return}case"tstamp":{const i=pi(t[0]);if(i===void 0)throw new Error("via tstamp expects a string value");this._sxTstamp=new Zg(i);return}default:throw new Error(`via encountered unsupported child token "${A}"`)}}parseYesNo(A){if(A.length===0)return!0;const t=pi(A[0]);if(t===void 0)throw new Error("Expected string when parsing via boolean child");return/^(yes|true)$/iu.test(t)}get type(){return this._type}set type(A){this._type=A}get locked(){return this._locked}set locked(A){this._locked=A}get free(){return this._free}set free(A){this._free=A}get removeUnusedLayers(){return this._removeUnusedLayers}set removeUnusedLayers(A){this._removeUnusedLayers=A}get keepEndLayers(){return this._keepEndLayers}set keepEndLayers(A){this._keepEndLayers=A}get at(){return this._sxAt}set at(A){this._sxAt=A!==void 0?Wg.from(A):void 0}get size(){return this._size}set size(A){this._size=A}get drill(){return this._drill}set drill(A){this._drill=A}get layers(){return this._sxLayers}set layers(A){if(A===void 0){this._sxLayers=void 0;return}this._sxLayers=A instanceof dj?A:new dj(A)}get net(){return this._sxNet}set net(A){this._sxNet=A}get uuid(){return this._sxUuid}set uuid(A){if(A===void 0){this._sxUuid=void 0;return}this._sxUuid=A instanceof Li?A:new Li(A)}get teardrops(){return this._sxTeardrops}set teardrops(A){this._sxTeardrops=A}get tstamp(){return this._sxTstamp}set tstamp(A){if(A===void 0){this._sxTstamp=void 0;return}this._sxTstamp=A instanceof Zg?A:new Zg(A)}getChildren(){const A=[];return this._sxAt&&A.push(this._sxAt),this._sxLayers&&A.push(this._sxLayers),this._sxNet&&A.push(this._sxNet),this._sxUuid&&A.push(this._sxUuid),this._sxTstamp&&A.push(this._sxTstamp),this._sxTeardrops&&A.push(this._sxTeardrops),A}getString(){const A=["(via"];return this._type!==void 0&&A.push(` (type ${this._type})`),this._locked&&A.push(" (locked)"),this._free&&A.push(" (free)"),this._removeUnusedLayers&&A.push(" (remove_unused_layers)"),this._keepEndLayers&&A.push(" (keep_end_layers)"),this._sxAt&&A.push(this._sxAt.getStringIndented()),this._size!==void 0&&A.push(` (size ${this._size})`),this._drill!==void 0&&A.push(` (drill ${this._drill})`),this._sxLayers&&A.push(this._sxLayers.getStringIndented()),this._sxNet&&A.push(this._sxNet.getStringIndented()),this._sxUuid&&A.push(this._sxUuid.getStringIndented()),this._sxTstamp&&A.push(this._sxTstamp.getStringIndented()),this._sxTeardrops&&A.push(this._sxTeardrops.getStringIndented()),A.push(")"),A.join(`
5828
- `)}};NA.register(LwA);var UwA=class byt extends NA{static token="kicad_pcb";token="kicad_pcb";_sxVersion;_sxGenerator;_sxGeneratorVersion;_sxGeneral;_sxPaper;_sxTitleBlock;_sxLayers;_sxSetup;_properties=[];_nets=[];_footprints=[];_images=[];_segments=[];_grLines=[];_grTexts=[];_grPolys=[];_grRects=[];_vias=[];_zones=[];_otherChildren=[];constructor(A={}){super(),A.version!==void 0&&(this.version=A.version),A.generator!==void 0&&(this.generator=A.generator),A.generatorVersion!==void 0&&(this.generatorVersion=A.generatorVersion),A.general!==void 0&&(this.general=A.general),A.paper!==void 0&&(this.paper=A.paper),A.titleBlock!==void 0&&(this.titleBlock=A.titleBlock),A.layers!==void 0&&(this.layers=A.layers),A.setup!==void 0&&(this.setup=A.setup),A.properties!==void 0&&(this.properties=A.properties),A.nets!==void 0&&(this.nets=A.nets),A.footprints!==void 0&&(this.footprints=A.footprints),A.images!==void 0&&(this.images=A.images),A.segments!==void 0&&(this.segments=A.segments),A.graphicLines!==void 0&&(this.graphicLines=A.graphicLines),A.graphicTexts!==void 0&&(this.graphicTexts=A.graphicTexts),A.graphicPolys!==void 0&&(this.graphicPolys=A.graphicPolys),A.graphicRects!==void 0&&(this.graphicRects=A.graphicRects),A.vias!==void 0&&(this.vias=A.vias),A.zones!==void 0&&(this.zones=A.zones),A.otherChildren!==void 0&&(this.otherChildren=A.otherChildren)}static fromSexprPrimitives(A){const t=new byt;for(const i of A){if(!Array.isArray(i)||i.length===0)throw new Error(`kicad_pcb encountered unsupported primitive child: ${JSON.stringify(i)}`);const n=NA.parsePrimitiveSexpr(i,{parentToken:this.token});if(!(n instanceof NA))throw new Error(`kicad_pcb expected SxClass child, received ${JSON.stringify(i)}`);t.consumeChild(n)}return t}consumeChild(A){if(A instanceof MwA){this._sxVersion=A;return}if(A instanceof RwA){this._sxGenerator=A;return}if(A instanceof NwA){this._sxGeneratorVersion=A;return}if(A instanceof FwA){this._sxGeneral=A;return}if(A instanceof ij){this._sxPaper=A;return}if(A instanceof QCt){this._sxTitleBlock=A;return}if(A instanceof GwA){this._sxLayers=A;return}if(A instanceof kwA){this._sxSetup=A;return}if(A instanceof OD){this._properties.push(A);return}if(A instanceof fj){this._nets.push(A);return}if(A instanceof xmA){this._footprints.push(A);return}if(A instanceof hCt){this._images.push(A);return}if(A instanceof JmA){this._segments.push(A);return}if(A instanceof Ej){this._grLines.push(A);return}if(A instanceof hj){this._grTexts.push(A);return}if(A instanceof sEt){this._grPolys.push(A);return}if(A instanceof iEt){this._grRects.push(A);return}if(A instanceof LwA){this._vias.push(A);return}if(A instanceof lEt){this._zones.push(A);return}this._otherChildren.push(A)}get version(){return this._sxVersion?.value}set version(A){this._sxVersion=A===void 0?void 0:new MwA(A)}get generator(){return this._sxGenerator?.value}set generator(A){this._sxGenerator=A===void 0?void 0:new RwA(A)}get generatorVersion(){return this._sxGeneratorVersion?.value}set generatorVersion(A){this._sxGeneratorVersion=A===void 0?void 0:new NwA(A)}get general(){return this._sxGeneral}set general(A){this._sxGeneral=A}get paper(){return this._sxPaper}set paper(A){this._sxPaper=A}get titleBlock(){return this._sxTitleBlock}set titleBlock(A){this._sxTitleBlock=A}get layers(){return this._sxLayers}set layers(A){this._sxLayers=A}get setup(){return this._sxSetup}set setup(A){this._sxSetup=A}get properties(){return[...this._properties]}set properties(A){this._properties=[...A]}get nets(){return[...this._nets]}set nets(A){this._nets=[...A]}get footprints(){return[...this._footprints]}set footprints(A){this._footprints=[...A]}get images(){return[...this._images]}set images(A){this._images=[...A]}get segments(){return[...this._segments]}set segments(A){this._segments=[...A]}get graphicLines(){return[...this._grLines]}set graphicLines(A){this._grLines=[...A]}get graphicTexts(){return[...this._grTexts]}set graphicTexts(A){this._grTexts=[...A]}get graphicPolys(){return[...this._grPolys]}set graphicPolys(A){this._grPolys=[...A]}get graphicRects(){return[...this._grRects]}set graphicRects(A){this._grRects=[...A]}get vias(){return[...this._vias]}set vias(A){this._vias=[...A]}get zones(){return[...this._zones]}set zones(A){this._zones=[...A]}get otherChildren(){return[...this._otherChildren]}set otherChildren(A){this._otherChildren=[...A]}getChildren(){const A=[];return this._sxVersion&&A.push(this._sxVersion),this._sxGenerator&&A.push(this._sxGenerator),this._sxGeneratorVersion&&A.push(this._sxGeneratorVersion),this._sxGeneral&&A.push(this._sxGeneral),this._sxPaper&&A.push(this._sxPaper),this._sxTitleBlock&&A.push(this._sxTitleBlock),this._sxLayers&&A.push(this._sxLayers),this._sxSetup&&A.push(this._sxSetup),A.push(...this._properties),A.push(...this._nets),A.push(...this._footprints),A.push(...this._images),A.push(...this._segments),A.push(...this._grLines),A.push(...this._grTexts),A.push(...this._grPolys),A.push(...this._grRects),A.push(...this._vias),A.push(...this._zones),A.push(...this._otherChildren),A}};NA.register(UwA);var hht=e=>NA.parse(e),Nh=class{MAX_ITERATIONS=1e3;iteration=0;finished=!1;input;ctx;constructor(e,A){this.input=e,this.ctx=A}step(){if(this.iteration++,this.iteration>this.MAX_ITERATIONS)throw new Error("Max iterations reached");this._step()}_step(){throw new Error("Not implemented")}runUntilFinished(){for(;!this.finished;)this.step()}getOutput(){throw new Error("Not implemented")}},Tii=class extends Nh{_step(){const{kicadSch:e,schematicPaperSize:A}=this.ctx;if(!e)throw new Error("KicadSch instance not initialized in context");e.version=20250114;const t=new ij;t.size=A?.name??"A4",e.paper=t,e.uuid=new Li(crypto.randomUUID()),this.finished=!0}getOutput(){return this.ctx.kicadSch}};function RG(e,A){if(e.manufacturer_part_number)return HwA(e.manufacturer_part_number);const t=Kii(e.ftype),i=A?.footprinter_string;return HwA(i?`${t}_${i}`:t)}function Kii(e){if(!e)return"component";let A=e.replace(/^simple_/,"");return A||"component"}function HwA(e){return e.replace(/[\\\/:\s]+/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"").trim()||"component"}function uht(e){return e?e.match(/^([A-Za-z]+)/)?.[1]?.toUpperCase()??"U":"U"}var dht={simple_resistor:"R",simple_capacitor:"C",simple_inductor:"L",simple_diode:"D",simple_led:"D",simple_chip:"U",simple_transistor:"Q",simple_mosfet:"Q",simple_fuse:"F",simple_switch:"SW",simple_push_button:"SW",simple_potentiometer:"RV",simple_crystal:"Y",simple_resonator:"Y",simple_pin_header:"J",simple_pinout:"J",simple_test_point:"TP",simple_battery:"BT"},Pii=/^[A-Za-z]+\d+$/;function pht(e){return e?Pii.test(e.trim()):!1}function yj(e){const A=e?.ftype;if(A&&dht[A])return dht[A];const t=e?.name;return pht(t),uht(t)}function qii(e){const A=e?.name;return pht(A)?A.trim():`${yj(e)}?`}function fht(e){return e in wQ}function yht(e,A,t,i){if(i)return`Custom:${i}`;if(e.type!=="source_component")return A.symbol_name?fht(A.symbol_name)?`Device:${A.symbol_name}`:`Custom:${A.symbol_name}`:"Device:Component";if(A.symbol_name)return fht(A.symbol_name)?`Device:${A.symbol_name}`:`Custom:${A.symbol_name}`;const n=RG(e,t);return`Device:${yj(e)}_${n}`}function Oii(e){const{circuitJson:A,schematicSymbolId:t,schematicSymbol:i,schematicComponentId:n}=e,o=A.filter(Q=>Q.type==="schematic_circle"&&Q.schematic_symbol_id===t),s=A.filter(Q=>Q.type==="schematic_line"&&Q.schematic_symbol_id===t),r=n?A.filter(Q=>Q.type==="schematic_line"&&Q.schematic_component_id===n&&!Q.schematic_symbol_id):[],a=[...s,...r],g=A.filter(Q=>Q.type==="schematic_path"&&Q.schematic_symbol_id===t),c=A.filter(Q=>Q.type==="schematic_text"&&Q.schematic_symbol_id===t);let I=A.filter(Q=>Q.type==="schematic_port"&&"schematic_symbol_id"in Q&&Q.schematic_symbol_id===t);if(I.length===0&&n&&(I=A.filter(Q=>Q.type==="schematic_port"&&Q.schematic_component_id===n&&Q.display_pin_label!==void 0),I.length===0)){const Q=A.filter(h=>h.type==="schematic_port"&&h.schematic_component_id===n),E=new Set;I=Q.filter(h=>{const u=h.pin_number;if(u!==void 0){if(E.has(u))return!1;E.add(u)}return!0})}const l=[];for(const Q of o)l.push({type:"circle",x:Q.center?.x??0,y:Q.center?.y??0,radius:Q.radius??.5,fill:Q.is_filled??!1,fillColor:Q.fill_color});for(const Q of a)l.push({type:"path",points:[{x:Q.x1??0,y:Q.y1??0},{x:Q.x2??0,y:Q.y2??0}]});for(const Q of g)Q.points&&Q.points.length>0&&l.push({type:"path",points:Q.points,fill:Q.is_filled??!1,fillColor:Q.fill_color});const B=c.map(Q=>({text:Q.text??"",x:Q.position?.x??0,y:Q.position?.y??0,fontSize:Q.font_size??.2,anchor:Q.anchor??"center"})),C=I.map((Q,E)=>({x:Q.center?.x??0,y:Q.center?.y??0,labels:[Q.display_pin_label||`${Q.pin_number||E+1}`],pinNumber:Q.pin_number||E+1,facingDirection:Q.facing_direction}));return C.sort((Q,E)=>Q.pinNumber-E.pinNumber),{center:i.center||{x:0,y:0},size:i.size||{width:1,height:1},primitives:l,texts:B,ports:C}}function Wii({points:e,transform:A,fillType:t}){const i=new dCt,n=e.map(a=>{const g=Ee(A,a);return new LQ(g.x,g.y)}),o=new YC(n);i.points=o;const s=new qD;s.width=.254,s.type="default",i.stroke=s;const r=new SCt;return r.type=t,i.fill=r,i}function Zii({primitive:e,transform:A,scale:t}){const i=new _Ct,n=Ee(A,{x:e.x,y:e.y}),o=i;o._sxCenter=new wCt(n.x,n.y),o._sxRadius=new DCt(e.radius*t);const s=new qD;s.width=.254,s.type="default",o._sxStroke=s;const r=new bCt;return r.type=e.fill?"background":"none",o._sxFill=r,i}function Vii({schText:e,transform:A,scale:t}){const i=new kCt,n=Ee(A,{x:e.x,y:e.y});i.value=e.text,i.at=[n.x,n.y,0];const o=e.fontSize*t,s=new uf;return s.size={height:o,width:o},i.effects=new hf({font:s}),i}function jii({libId:e,symbolData:A,isChip:t,c2kMatSchScale:i}){const n=new w1({libraryId:`${e.split(":")[1]}_0_1`}),s=t?i:15.24,r=A.center?.x??0,a=A.center?.y??0,g=bl(fh(s,s),ir(-r,-a));for(const I of A.primitives||[])if(I.type==="path"&&I.points){const l=t||I.fill?"background":"none",B=Wii({points:I.points,transform:g,fillType:l});n.polylines.push(B)}else if(I.type==="circle"){const l=Zii({primitive:I,transform:g,scale:s});n.circles.push(l)}const c=Array.isArray(A.texts)?A.texts:[];for(const I of c){const l=Vii({schText:I,transform:g,scale:s});n.texts.push(l)}return n}function zii(e,A){const t=A.schematic_port.list().filter(r=>r.schematic_component_id===e.schematic_component_id).sort((r,a)=>(r.pin_number||0)-(a.pin_number||0)),i=e.size?.width||1.5,n=e.size?.height||1,o={type:"path",points:[{x:-i/2,y:-n/2},{x:i/2,y:-n/2},{x:i/2,y:n/2},{x:-i/2,y:n/2},{x:-i/2,y:-n/2}]},s=t.map(r=>{const a=r.center.x-e.center.x,g=r.center.y-e.center.y;return{x:a,y:g,labels:[r.display_pin_label||`${r.pin_number||1}`],pinNumber:r.pin_number||1}});return{center:{x:0,y:0},primitives:[o],ports:s,size:{width:i,height:n}}}function Xii(e,A){const t=new uf;return t.size={height:e,width:e},new hf({font:t,hiddenText:A})}function $ii({symbol:e,libId:A,description:t,keywords:i,fpFilters:n,footprintRef:o="",referencePrefix:s}){const r=s||A.split(":")[1]?.[0]||"U",a=[{key:"Reference",value:r,id:0,at:[2.032,0,90],hide:!1},{key:"Value",value:r,id:1,at:[0,0,90],hide:!1},{key:"Footprint",value:o,id:2,at:[-1.778,0,90],hide:!0},{key:"Datasheet",value:"~",id:3,at:[0,0,0],hide:!0},{key:"Description",value:t,id:4,at:[0,0,0],hide:!0},{key:"ki_keywords",value:i,id:5,at:[0,0,0],hide:!0},{key:"ki_fp_filters",value:n,id:6,at:[0,0,0],hide:!0}];for(const g of a)e.properties.push(new df({key:g.key,value:g.value,id:g.id,at:g.at,effects:Xii(1.27,g.hide)}))}function Ani({port:e,center:A,size:t,isChip:i,portIndex:n,schematicComponent:o,schematicPorts:s,c2kMatSchScale:r}){const g=i?r:15.24;let c=e.x??0,I=e.y??0,l=!1;if(i&&n!==void 0&&o){const w=s.filter(D=>D.schematic_component_id===o.schematic_component_id).sort((D,b)=>(D.pin_number||0)-(b.pin_number||0));if(w[n]){const D=w[n];c=D.center.x-o.center.x,I=D.center.y-o.center.y,l=!0}}let B,C;if(l)B=c,C=I;else{const w=A?.x??0,D=A?.y??0;B=c-w,C=I-D}const Q=fh(g,g),E=Ee(Q,{x:B,y:C});let h;if(i&&t){const w=t.width/2,D=t.height/2,b=Math.abs(B)/w,k=Math.abs(C)/D;h=b>k}else h=Math.abs(B)>Math.abs(C);let u=E.x,d=E.y;const f=6;if(i&&t){const w=t.width/2*g,D=t.height/2*g;h?(u=B>0?w:-w,d=C*g):(u=B*g,d=C>0?D:-D)}let m=0;return h?B>0?(m=180,i&&(u=u+f)):(m=0,i&&(u=u-f)):C>0?(m=270,i&&(d=d+f)):(m=90,i&&(d=d-f)),{x:u,y:d,angle:m}}function tni({libId:e,symbolData:A,isChip:t,schematicComponent:i,schematicPorts:n,c2kMatSchScale:o}){const s=new w1({libraryId:`${e.split(":")[1]}_1_1`}),r=6,a=2.54;for(let g=0;g<(A.ports?.length||0);g++){const c=A.ports[g],I=new rj;I.pinElectricalType="passive",I.pinGraphicStyle="line";const{x:l,y:B,angle:C}=Ani({port:c,center:A.center,size:A.size,isChip:t,portIndex:g,schematicComponent:i,schematicPorts:n,c2kMatSchScale:o});I.at=[l,B,C],I.length=t?r:a;const Q=new uf;Q.size={height:1.27,width:1.27};const E=new hf({font:Q}),h=c.labels?.[0]||"~";I._sxName=new uyA({value:h,effects:E});const u=new uf;u.size={height:1.27,width:1.27};const d=new hf({font:u}),f=c.pinNumber?.toString()||`${g+1}`;I._sxNumber=new GCt({value:f,effects:d}),s.pins.push(I)}return s}var eni=class extends Nh{processedSymbolNames=new Set;_step(){const{kicadSch:e,db:A}=this.ctx,t=new HCt,i=[];this.processedSymbolNames=new Set;const n=A.schematic_component.list();for(const s of n){const r=this.createLibrarySymbolForComponent(s);r&&i.push(r)}const o=A.schematic_net_label?.list?.()||[];for(const s of o)if(s.symbol_name){const r=s.source_net_id?A.source_net.get(s.source_net_id)?.is_power:!1,a=s.source_net_id?A.source_net.get(s.source_net_id)?.is_ground:!1;if(r||a){const c=this.createLibrarySymbolForNetLabel({netLabel:s,isPower:r??!1,isGround:a??!1});c&&i.push(c)}}t.symbols=i,e&&(e.libSymbols=t),this.finished=!0}createLibrarySymbolForComponent(e){const{db:A}=this.ctx,t=e.source_component_id?A.source_component.get(e.source_component_id):null;if(!t)return null;const i=A.cad_component?.list()?.find(c=>c.source_component_id===t.source_component_id);let n=e.schematic_symbol_id;if(!n){const c=this.ctx.circuitJson.find(I=>(I.type==="schematic_line"||I.type==="schematic_circle"||I.type==="schematic_path")&&I.schematic_component_id===e.schematic_component_id&&I.schematic_symbol_id);c&&(n=c.schematic_symbol_id)}if(n)return this.createLibrarySymbolFromSchematicSymbol(e,t,i,n);const o=e.symbol_name||(t.ftype==="simple_chip"?`generic_chip_${e.source_component_id}`:null);if(!o)return null;const s=this.getSymbolData(o,e);if(!s)return null;const r=yht(t,e,i),a=t.ftype==="simple_chip",g=RG(t,i);return this.createLibrarySymbol({libId:r,symbolData:s,isChip:a,schematicComponent:e,description:this.getDescription(t),keywords:this.getKeywords(t),fpFilters:this.getFpFilters(t),footprintRef:g?`tscircuit:${g}`:"",referencePrefix:yj(t)})}createLibrarySymbolFromSchematicSymbol(e,A,t,i){const{db:n}=this.ctx,o=this.ctx.circuitJson.find(c=>c.type==="schematic_symbol"&&c.schematic_symbol_id===i);if(!o)return null;let s;if(o.name)s=o.name;else{const c=RG(A,t);c?s=c:s=`custom_${A.ftype||"component"}_${i}`}const r=`Custom:${s}`;if(this.processedSymbolNames.has(r))return null;this.processedSymbolNames.add(r);const a=Oii({circuitJson:this.ctx.circuitJson,schematicSymbolId:i,schematicSymbol:o,schematicComponentId:e.schematic_component_id}),g=RG(A,t);return this.createLibrarySymbol({libId:r,symbolData:a,isChip:!1,schematicComponent:e,description:this.getDescription(A),keywords:this.getKeywords(A),fpFilters:this.getFpFilters(A,o.name),footprintRef:g?`tscircuit:${g}`:"",referencePrefix:yj(A)})}createLibrarySymbolForNetLabel({netLabel:e,isPower:A,isGround:t}){const i=e.symbol_name;if(!i)return null;const n=wQ[i];if(!n)return null;const o=`Custom:${i}`;return this.createLibrarySymbol({libId:o,symbolData:n,isChip:!1,schematicComponent:void 0,description:A?"Power net label":t?"Ground net label":"Net symbol",keywords:A?"power net":t?"ground net":"net",fpFilters:"",referencePrefix:o.split(":")[1]?.[0]||"U"})}getSymbolData(e,A){return e.startsWith("generic_chip_")?zii(A,this.ctx.db):wQ[e]||null}createLibrarySymbol({libId:e,symbolData:A,isChip:t,schematicComponent:i,description:n,keywords:o,fpFilters:s,footprintRef:r="",referencePrefix:a}){const g=new w1({libraryId:e,excludeFromSim:!1,inBom:!0,onBoard:!0}),c=new QyA;c.hide=!t,g._sxPinNumbers=c;const I=new hyA;I.offset=t?1.27:0,g._sxPinNames=I,$ii({symbol:g,libId:e,description:n,keywords:o,fpFilters:s,footprintRef:r,referencePrefix:a});const l=jii({libId:e,symbolData:A,isChip:t,c2kMatSchScale:this.ctx.c2kMatSch?.a??15});g.subSymbols.push(l);const B=tni({libId:e,symbolData:A,isChip:t,schematicComponent:i,schematicPorts:this.ctx.db.schematic_port.list(),c2kMatSchScale:this.ctx.c2kMatSch?.a??15});return g.subSymbols.push(B),g._sxEmbeddedFonts=new y1(!1),g}getDescription(e){return e?.ftype==="simple_resistor"?"Resistor":e?.ftype==="simple_capacitor"?"Capacitor":e?.ftype==="simple_chip"?"Integrated Circuit":"Component"}getKeywords(e){return e?.ftype==="simple_resistor"?"R res resistor":e?.ftype==="simple_capacitor"?"C cap capacitor":e?.ftype==="simple_chip"?"U IC chip":""}getFpFilters(e,A){return A?`${A}*`:e?.ftype==="simple_resistor"?"R_*":e?.ftype==="simple_capacitor"?"C_*":(e?.ftype==="simple_chip","*")}getOutput(){if(!this.ctx.kicadSch)throw new Error("kicadSch is not initialized");return this.ctx.kicadSch}},ini=class extends Nh{_step(){const{kicadSch:e,db:A}=this.ctx,t=A.schematic_component.list();if(t.length===0){this.finished=!0;return}const i=[];for(const n of t){const o=n.source_component_id?A.source_component.get(n.source_component_id):null;if(!o||!this.ctx.c2kMatSch)continue;const{x:s,y:r}=Ee(this.ctx.c2kMatSch,{x:n.center.x,y:n.center.y}),a=crypto.randomUUID(),g=new w1({at:[s,r,0],unit:1,excludeFromSim:!1,inBom:!0,onBoard:!0,dnp:!1,uuid:a,fieldsAutoplaced:!0}),c=A.cad_component?.list()?.find(oA=>oA.source_component_id===o.source_component_id);let I,l=n.schematic_symbol_id;if(!l){const oA=this.ctx.circuitJson.find(rA=>(rA.type==="schematic_line"||rA.type==="schematic_circle"||rA.type==="schematic_path")&&rA.schematic_component_id===n.schematic_component_id&&rA.schematic_symbol_id);oA&&(l=oA.schematic_symbol_id)}if(l){const oA=this.ctx.circuitJson.find(rA=>rA.type==="schematic_symbol"&&rA.schematic_symbol_id===l);if(oA?.name)I=oA.name;else{const rA=RG(o,c);rA?I=rA:I=`custom_${o.ftype||"component"}_${l}`}}const B=yht(o,n,c,I),C=new ByA(B);g._sxLibId=C;const{reference:Q,value:E,description:h}=this.getComponentMetadata(o),{refTextPos:u,valTextPos:d}=this.getTextPositions(n,{x:s,y:r});let f;if(l){const oA=this.ctx.circuitJson.find(rA=>rA.type==="schematic_symbol"&&rA.schematic_symbol_id===l);oA&&oA.type==="schematic_symbol"&&(f=oA.metadata?.kicad_symbol)}const m=f?.properties?.Reference,w=new df({key:"Reference",value:m?.value??Q,id:0,at:[u.x,u.y,0],effects:this.createTextEffects(Number(m?.effects?.font?.size?.x??1.27),m?.effects?.hide??!1)}),D=o.ftype==="simple_chip",b=f?.properties?.Value,k=new df({key:"Value",value:b?.value??E,id:1,at:[d.x,d.y,0],effects:this.createTextEffects(Number(b?.effects?.font?.size?.x??1.27),b?.effects?.hide??D)}),x=f?.properties?.Footprint,N=new df({key:"Footprint",value:x?.value??"",id:2,at:[s-1.778,r,90],effects:this.createTextEffects(1.27,x?.effects?.hide??!0)}),R=f?.properties?.Datasheet,U=new df({key:"Datasheet",value:R?.value??"~",id:3,at:[s,r,0],effects:this.createTextEffects(1.27,R?.effects?.hide??!0)}),T=f?.properties?.Description,Y=new df({key:"Description",value:T?.value??h,id:4,at:[s,r,0],effects:this.createTextEffects(1.27,T?.effects?.hide??!0)});g.properties.push(w,k,N,U,Y);const O=f?.properties?.ki_keywords;if(O?.value){const oA=new df({key:"ki_keywords",value:O.value,id:5,at:[s,r,0],effects:this.createTextEffects(1.27,O.effects?.hide??!0)});g.properties.push(oA)}const W=f?.properties?.ki_fp_filters;if(W?.value){const oA=new df({key:"ki_fp_filters",value:W.value,id:6,at:[s,r,0],effects:this.createTextEffects(1.27,W.effects?.hide??!0)});g.properties.push(oA)}if(f){if(f.inBom!==void 0&&(g.inBom=f.inBom),f.onBoard!==void 0&&(g.onBoard=f.onBoard),f.excludeFromSim!==void 0&&(g.excludeFromSim=f.excludeFromSim),f.pinNames){const oA=new hyA;f.pinNames.offset!==void 0&&(oA.offset=Number(f.pinNames.offset)),f.pinNames.hide!==void 0&&(oA.hide=f.pinNames.hide),g.pinNames=oA}if(f.pinNumbers){const oA=new QyA;f.pinNumbers.hide!==void 0&&(oA.hide=f.pinNumbers.hide),g.pinNumbers=oA}f.embeddedFonts!==void 0&&(g._sxEmbeddedFonts=new y1(f.embeddedFonts))}let X=A.schematic_port.list().filter(oA=>oA.schematic_component_id===n.schematic_component_id);if(l){const oA=X.filter(rA=>rA.display_pin_label);oA.length>0&&(X=oA)}X.sort((oA,rA)=>(oA.pin_number||0)-(rA.pin_number||0));for(let oA=0;oA<X.length;oA++){const rA=X[oA];if(!rA)continue;const CA=new rj;CA.numberString=`${rA.pin_number||oA+1}`,CA.uuid=crypto.randomUUID(),g.pins.push(CA)}const iA=new dyA,aA=new fyA(""),tA=new yyA(`/${e?.uuid?.value||""}`);tA.reference=Q,tA.unit=1,aA.paths.push(tA),iA.projects.push(aA),g._sxInstances=iA,i.push(g)}e&&(e.symbols=i),this.finished=!0}getTextPositions(e,A){const i=(this.ctx.db.schematic_text?.list?.()?.filter(B=>B.schematic_component_id===e.schematic_component_id)||[]).find(B=>B.text&&B.text.length>0);if(i&&this.ctx.c2kMatSch){const B=Ee(this.ctx.c2kMatSch,{x:i.position.x,y:i.position.y}),C={x:A.x,y:A.y+6};return{refTextPos:B,valTextPos:C}}const n=e.symbol_name,o=wQ[n];if(!o)return{refTextPos:{x:A.x,y:A.y-6},valTextPos:{x:A.x,y:A.y+6}};let s=null,r=null;for(const B of o.primitives)B.type==="text"&&(B.text==="{REF}"?s=B:B.text==="{VAL}"&&(r=B));const a=o.center||{x:0,y:0},c=n.includes("_down")||n.includes("_up")?.15:0,I=s&&this.ctx.c2kMatSch?Ee(this.ctx.c2kMatSch,{x:e.center.x+(s.x-a.x)+c,y:e.center.y+(s.y-a.y)}):{x:A.x,y:A.y-6},l=r&&this.ctx.c2kMatSch?Ee(this.ctx.c2kMatSch,{x:e.center.x+(r.x-a.x)+c,y:e.center.y+(r.y-a.y)}):{x:A.x,y:A.y+6};return{refTextPos:I,valTextPos:l}}getComponentMetadata(e){const A=e.name||"?",t=qii(e);return e.ftype==="simple_resistor"?{reference:t,value:e.display_resistance||"R",description:"Resistor"}:e.ftype==="simple_capacitor"?{reference:t,value:e.display_capacitance||"C",description:"Capacitor"}:e.ftype==="simple_inductor"?{reference:t,value:e.display_inductance||"L",description:"Inductor"}:e.ftype==="simple_diode"?{reference:t,value:"D",description:"Diode"}:e.ftype==="simple_chip"?{reference:t,value:A,description:"Integrated Circuit"}:e.ftype==="simple_led"?{reference:t,value:e.manufacturer_part_number||"",description:"LED"}:e.ftype==="simple_switch"?{reference:t,value:e.manufacturer_part_number||"",description:"Switch"}:e.ftype==="simple_potentiometer"?{reference:t,value:e.display_max_resistance||"",description:"Potentiometer"}:{reference:t,value:A,description:"Component"}}createTextEffects(e,A=!1,t){const i=new uf;i.size={height:e,width:e};const n=t?new MJ({horizontal:t}):void 0;return new hf({font:i,hiddenText:A,justify:n})}getOutput(){if(!this.ctx.kicadSch)throw new Error("kicadSch is not initialized");return this.ctx.kicadSch}},nni=class extends Nh{_step(){const{kicadSch:e,db:A}=this.ctx,t=A.schematic_net_label?.list?.()||[];if(t.length===0){this.finished=!0;return}if(!this.ctx.c2kMatSch){this.finished=!0;return}const i=[],n=[];for(const o of t){const s=o.text||"",r=o.symbol_name;if(r){const a=this.createSymbolFromNetLabel(o,s,r);a&&i.push(a)}else{const a=this.createGlobalLabel(o,s);a&&n.push(a)}}if(e&&i.length>0){const o=e.symbols||[];e.symbols=[...o,...i]}e&&n.length>0&&(e.globalLabels=[...e.globalLabels||[],...n]),this.finished=!0}createSymbolFromNetLabel(e,A,t){if(!this.ctx.c2kMatSch)return null;const{x:i,y:n}=Ee(this.ctx.c2kMatSch,{x:e.anchor_position?.x??e.center?.x??0,y:e.anchor_position?.y??e.center?.y??0}),o=crypto.randomUUID(),s=new w1({at:[i,n,0],unit:1,excludeFromSim:!1,inBom:!0,onBoard:!0,dnp:!1,uuid:o,fieldsAutoplaced:!0}),r=`Custom:${t}`,a=new ByA(r);s._sxLibId=a;const g=t.includes("_up")||t.toLowerCase().includes("vcc"),c=g?-4:4,I=g?-6:6,l=new df({key:"Reference",value:A,id:0,at:[i,n+c,0],effects:this.createTextEffects(1.27,!1)}),B=new df({key:"Value",value:A,id:1,at:[i,n+I,0],effects:this.createTextEffects(1.27,!0)}),C=new df({key:"Footprint",value:"",id:2,at:[i-1.778,n,90],effects:this.createTextEffects(1.27,!0)}),Q=new df({key:"Datasheet",value:"~",id:3,at:[i,n,0],effects:this.createTextEffects(1.27,!0)}),E=new df({key:"Description",value:`Power/Net symbol: ${A}`,id:4,at:[i,n,0],effects:this.createTextEffects(1.27,!0)});s.properties.push(l,B,C,Q,E);const h=new rj;h.numberString="1",h.uuid=crypto.randomUUID(),s.pins.push(h);const{kicadSch:u}=this.ctx,d=new dyA,f=new fyA(""),m=new yyA(`/${u?.uuid?.value||""}`);return m.reference=A,m.unit=1,f.paths.push(m),d.projects.push(f),s._sxInstances=d,s}createGlobalLabel(e,A){if(!this.ctx.c2kMatSch||!this.ctx.kicadSch)return null;const{x:t,y:i}=Ee(this.ctx.c2kMatSch,{x:e.anchor_position?.x??e.center?.x??0,y:e.anchor_position?.y??e.center?.y??0}),n=e.anchor_side||"left",s={left:0,right:180,top:270,bottom:90}[n]||0,a={left:{horizontal:"left"},right:{horizontal:"right"},top:{vertical:"top"},bottom:{vertical:"bottom"}}[n]||{},g=this.createTextEffects(1.27,!1);return Object.keys(a).length>0&&(g.justify=new MJ(a)),new ZCt({value:A,at:[t,i,s],effects:g,uuid:crypto.randomUUID(),fieldsAutoplaced:!0})}createTextEffects(e,A=!1){const t=new uf;return t.size={height:e,width:e},new hf({font:t,hiddenText:A})}getOutput(){if(!this.ctx.kicadSch)throw new Error("kicadSch is not initialized");return this.ctx.kicadSch}},oni=class extends Nh{_step(){const{kicadSch:e,db:A}=this.ctx;if(!e)throw new Error("KicadSch instance not initialized in context");const t=A.schematic_trace.list();if(t.length===0){this.finished=!0;return}const i=[],n=[];for(const o of t){for(const s of o.edges){const r=this.createWireFromEdge(s);i.push(r)}for(const s of o.junctions){const r=this.createJunction(s);n.push(r)}}e.wires=i,e.junctions=n,this.finished=!0}createWireFromEdge(e){const A=new JCt;if(!this.ctx.c2kMatSch)throw new Error("Schematic transformation matrix not initialized in context");const t=Ee(this.ctx.c2kMatSch,{x:e.from.x,y:e.from.y}),i=Ee(this.ctx.c2kMatSch,{x:e.to.x,y:e.to.y}),n=t.x,o=t.y,s=i.x,r=i.y,a=new YC([new LQ(n,o),new LQ(s,r)]);A.points=a;const g=new qD;return g.width=0,g.type="default",A.stroke=g,A.uuid=crypto.randomUUID(),A}createJunction(e){if(!this.ctx.c2kMatSch)throw new Error("Schematic transformation matrix not initialized in context");const{x:A,y:t}=Ee(this.ctx.c2kMatSch,{x:e.x,y:e.y}),i=new TCt({at:[A,t],diameter:0});return i.uuid=crypto.randomUUID(),i}getOutput(){return this.ctx.kicadSch}},sni=class extends Nh{_step(){const{kicadSch:e}=this.ctx;if(!e)throw new Error("KicadSch instance not initialized in context");const A=new SyA,t=new zCt;t.value="/";const i=new XCt("1");t.pages=[i],A.paths=[t],e.sheetInstances=A,e.embeddedFonts=new y1(!1),this.finished=!0}getOutput(){return this.ctx.kicadSch}};function rni(e){const A=e.schematic_component.list(),t=e.schematic_trace.list();let i=1/0,n=1/0,o=-1/0,s=-1/0;for(const g of A){const c=g.size?.width??0,I=g.size?.height??0;i=Math.min(i,g.center.x-c/2),n=Math.min(n,g.center.y-I/2),o=Math.max(o,g.center.x+c/2),s=Math.max(s,g.center.y+I/2)}for(const g of t)for(const c of g.edges)i=Math.min(i,c.from.x,c.to.x),n=Math.min(n,c.from.y,c.to.y),o=Math.max(o,c.from.x,c.to.x),s=Math.max(s,c.from.y,c.to.y);i===1/0&&(i=0,n=0,o=0,s=0);const r=(i+o)/2,a=(n+s)/2;return{center:{x:r,y:a},bounds:{minX:i,minY:n,maxX:o,maxY:s}}}var mj=[{name:"A4",width:297,height:210},{name:"A3",width:420,height:297},{name:"A2",width:594,height:420},{name:"A1",width:841,height:594},{name:"A0",width:1189,height:841}];function ani(e,A,t=20){const i=e+2*t,n=A+2*t;for(let o=0;o<mj.length;o++){const s=mj[o];if(i<=s.width&&n<=s.height)return s}return mj[mj.length-1]}var mht=class{ctx;pipeline;currentStageIndex=0;finished=!1;get currentStage(){return this.pipeline[this.currentStageIndex]}constructor(e){const t=xa(e),{center:i,bounds:n}=rni(t),o=(n.maxX-n.minX)*15,s=(n.maxY-n.minY)*15,r=ani(o,s),a=r.width/2,g=r.height/2;this.ctx={db:t,circuitJson:e,kicadSch:new xyA({generator:"circuit-json-to-kicad",generatorVersion:"0.0.1"}),schematicPaperSize:r,c2kMatSch:bl(ir(a,g),fh(15,-15),ir(-i.x,-i.y))},this.pipeline=[new Tii(e,this.ctx),new eni(e,this.ctx),new ini(e,this.ctx),new nni(e,this.ctx),new oni(e,this.ctx),new sni(e,this.ctx)]}step(){if(!this.currentStage){this.finished=!0;return}this.currentStage.step(),this.currentStage.finished&&this.currentStageIndex++}runUntilFinished(){for(;!this.finished;)this.step()}getOutput(){return this.ctx.kicadSch}getOutputString(){return this.ctx.kicadSch.getString()}},gni=class extends Nh{_step(){const{kicadPcb:e,db:A}=this.ctx;if(!e)throw new Error("KicadPcb instance not initialized in context");const i=A.pcb_board?.list()?.[0]?.num_layers??2;this.ctx.numLayers=i,e.version=20241229;const n=new ij;n.size="A4",e.paper=n;const o=new FwA;o.thickness=1.6,e.general=o;const s=new kwA;s.padToMaskClearance=0,e.setup=s;const r=new GwA,a=[new Rl({index:0,name:"F.Cu",type:"signal"})];for(let g=1;g<i-1;g++)a.push(new Rl({index:g,name:`In${g}.Cu`,type:"signal"}));a.push(new Rl({index:31,name:"B.Cu",type:"signal"})),a.push(new Rl({index:32,name:"B.Adhes",type:"user"}),new Rl({index:33,name:"F.Adhes",type:"user"}),new Rl({index:34,name:"B.Paste",type:"user"}),new Rl({index:35,name:"F.Paste",type:"user"}),new Rl({index:36,name:"B.SilkS",type:"user"}),new Rl({index:37,name:"F.SilkS",type:"user"}),new Rl({index:38,name:"B.Mask",type:"user"}),new Rl({index:39,name:"F.Mask",type:"user"}),new Rl({index:40,name:"Dwgs.User",type:"user"}),new Rl({index:41,name:"Cmts.User",type:"user"}),new Rl({index:42,name:"Eco1.User",type:"user"}),new Rl({index:43,name:"Eco2.User",type:"user"}),new Rl({index:44,name:"Edge.Cuts",type:"user"}),new Rl({index:45,name:"Margin",type:"user"}),new Rl({index:46,name:"B.CrtYd",type:"user"}),new Rl({index:47,name:"F.CrtYd",type:"user"}),new Rl({index:48,name:"B.Fab",type:"user"}),new Rl({index:49,name:"F.Fab",type:"user"})),r.definitions=a,e.layers=r,this.finished=!0}getOutput(){return this.ctx.kicadPcb}},cni=class extends Nh{_step(){const{kicadPcb:e}=this.ctx;if(!e)throw new Error("KicadPcb instance not initialized in context");this.ctx.pcbNetMap=new Map;const A=new Map,t=this.ctx.db.source_net?.list()??[];for(const r of t){const a=r.subcircuit_connectivity_map_key||r.source_net_id;if(!a)continue;const g=r.name||r.source_net_id||"",c=g&&g.trim().length>0?g:a;A.set(a,c)}const i=this.ctx.db.source_trace?.list()??[];for(const r of i){let a=r.subcircuit_connectivity_map_key;if(!a&&r.connected_source_net_ids?.length)for(const g of r.connected_source_net_ids){const c=this.ctx.db.source_net?.get(g);if(c?.subcircuit_connectivity_map_key&&c.subcircuit_connectivity_map_key.length>0){a=c.subcircuit_connectivity_map_key;break}}if(a&&!A.has(a)){const g=r.display_name||r.source_trace_id||"",c=g&&g.trim().length>0?g:a;A.set(a,c)}}const n=Array.from(A.entries()).sort((r,a)=>r[0].localeCompare(a[0])),o=[];o.push(new fj(0,""));let s=1;for(const[r,a]of n){const g=new fj(s,a);o.push(g);const c={id:s,name:a};this.ctx.pcbNetMap.set(r,c),s++}e.nets=o,this.finished=!0}getOutput(){return this.ctx.kicadPcb}};function Ini(e){let A=0;for(let i=0;i<e.length;i++){const n=e.charCodeAt(i);A=(A<<5)-A+n,A=A&A}let t="";for(let i=0;i<4;i++){let n=A;for(let o=0;o<e.length;o++)n=(n<<5)-n+e.charCodeAt(o)+i*31,n=n&n;t+=Math.abs(n).toString(16).padStart(8,"0")}return t}function pf(e){const A=Ini(e);return`${A.slice(0,8)}-${A.slice(8,12)}-${A.slice(12,16)}-${A.slice(16,20)}-${A.slice(20,32)}`}function wj(e){const A=new uf;return e?.font?.size?A.size={width:Number(e.font.size.x),height:Number(e.font.size.y)}:A.size={width:1.27,height:1.27},e?.font?.thickness!==void 0?A.thickness=Number(e.font.thickness):A.thickness=.15,new hf({font:A})}function lni(e,A,t){if(A.properties){const i=[],n=A.properties.Reference;i.push(new OD({key:"Reference",value:n?.value??t,position:n?.at?[Number(n.at.x),Number(n.at.y),Number(n.at.rotation??0)]:[0,-3,0],layer:n?.layer??"F.SilkS",uuid:pf(`${t}-property-Reference`),effects:wj(n?.effects),hidden:n?.hide}));const o=A.properties.Value,s=o?.value??A.footprintName??"";i.push(new OD({key:"Value",value:s,position:o?.at?[Number(o.at.x),Number(o.at.y),Number(o.at.rotation??0)]:[0,3,0],layer:o?.layer??"F.Fab",uuid:pf(`${t}-property-Value`),effects:wj(o?.effects),hidden:o?.hide}));const r=A.properties.Datasheet;i.push(new OD({key:"Datasheet",value:r?.value??"",position:r?.at?[Number(r.at.x),Number(r.at.y),Number(r.at.rotation??0)]:[0,0,0],layer:r?.layer??"F.Fab",uuid:pf(`${t}-property-Datasheet`),effects:wj(r?.effects),hidden:r?.hide??!0}));const a=A.properties.Description;i.push(new OD({key:"Description",value:a?.value??"",position:a?.at?[Number(a.at.x),Number(a.at.y),Number(a.at.rotation??0)]:[0,0,0],layer:a?.layer??"F.Fab",uuid:pf(`${t}-property-Description`),effects:wj(a?.effects),hidden:a?.hide??!0})),e.properties=i}if(A.attributes&&(e.attr||(e.attr=new _yA),A.attributes.through_hole?e.attr.type="through_hole":A.attributes.smd&&(e.attr.type="smd"),A.attributes.exclude_from_pos_files!==void 0&&(e.attr.excludeFromPosFiles=A.attributes.exclude_from_pos_files),A.attributes.exclude_from_bom!==void 0&&(e.attr.excludeFromBom=A.attributes.exclude_from_bom)),A.footprintName&&(e.libraryLink=A.footprintName),A.layer&&(e.layer=A.layer),A.embeddedFonts!==void 0&&(e.embeddedFonts=new y1(A.embeddedFonts)),A.model){const i=new Bj(A.model.path);A.model.offset&&(i.offset={x:Number(A.model.offset.x),y:Number(A.model.offset.y),z:Number(A.model.offset.z)}),A.model.scale&&(i.scale={x:Number(A.model.scale.x),y:Number(A.model.scale.y),z:Number(A.model.scale.z)}),A.model.rotate&&(i.rotate={x:Number(A.model.rotate.x),y:Number(A.model.rotate.y),z:Number(A.model.rotate.z)});const n=e.models||[];e.models=[i,...n]}}function Bni(e,A){const t=[];for(const i of e){const n=i.center.x-A.x,o=-(i.center.y-A.y),r={top:"F.SilkS",bottom:"B.SilkS"}[i.layer]||i.layer||"F.SilkS",a=new lmA({center:{x:n,y:o},end:{x:n+i.radius,y:o},layer:r,stroke:new qD,fill:!1});a.stroke&&(a.stroke.width=i.stroke_width||.05,a.stroke.type="default"),t.push(a)}return t}function Cni(e,A){const t=[];for(const i of e){const n=i.center.x-A.x,o=-(i.center.y-A.y),r={top:"F.CrtYd",bottom:"B.CrtYd"}[i.layer]||"F.CrtYd",a=new lmA({center:{x:n,y:o},end:{x:n+i.radius,y:o},layer:r,stroke:new qD,fill:!1});a.stroke&&(a.stroke.width=.05,a.stroke.type="default"),t.push(a)}return t}function Qni(e,A){const t=[];for(const i of e){const n=i.center.x-A.x,o=-(i.center.y-A.y),s=i.width/2,r=i.height/2,g={top:"F.Fab",bottom:"B.Fab"}[i.layer]||i.layer||"F.Fab",c=new Ij({start:{x:n-s,y:o-r},end:{x:n+s,y:o+r},layer:g,stroke:new qD,fill:!1});c.stroke&&(c.stroke.width=i.stroke_width||.1,c.stroke.type="default"),t.push(c)}return t}function Eni(e,A){const t=[];for(const i of e){const n=i.center.x-A.x,o=-(i.center.y-A.y),s=i.width/2,r=i.height/2,a="F.Fab",g=new Ij({start:{x:n-s,y:o-r},end:{x:n+s,y:o+r},layer:a,stroke:new qD,fill:!1});g.stroke&&(g.stroke.width=i.stroke_width||.1,g.stroke.type="default"),t.push(g)}return t}function hni(e,A){const t=[];for(const i of e){const n=i.center.x-A.x,o=-(i.center.y-A.y),s=i.width/2,r=i.height/2,g={top:"F.CrtYd",bottom:"B.CrtYd"}[i.layer]||"F.CrtYd",c=new Ij({start:{x:n-s,y:o-r},end:{x:n+s,y:o+r},layer:g,stroke:new qD,fill:!1});c.stroke&&(c.stroke.width=.05,c.stroke.type="default"),t.push(c)}return t}function uni(e,A){const t=[];for(const i of e){if(!i.outline||i.outline.length<2)continue;const o={top:"F.CrtYd",bottom:"B.CrtYd"}[i.layer]||"F.CrtYd",s=i.outline.map(g=>{const c=g.x-A.x,I=-(g.y-A.y);return new LQ(c,I)}),r=new PQt;r.points=new YC(s),r.layer=o,r.fill=!1;const a=new qD;a.width=.05,a.type="default",r.stroke=a,t.push(r)}return t}function dni({textElement:e,componentCenter:A,componentRotation:t=0}){if(!e.text||!e.anchor_position)return null;const i=e.anchor_position.x-A.x,n=-(e.anchor_position.y-A.y),o=t!==0?Rm(t*Math.PI/180):Ru(),s=Ee(o,{x:i,y:n}),r={x:s.x,y:s.y},g={top:"F.SilkS",bottom:"B.SilkS"}[e.layer]||e.layer||"F.SilkS",c=(e.font_size||1)/1.5,I=new uf;I.size={width:c,height:c};const l=new hf({font:I}),B=e.ccw_rotation||0;return new emA({type:"user",text:e.text,position:{x:r.x,y:r.y,angle:B},layer:g,effects:l})}function pni(e,A,t,i){const n=[];for(const o of e){const s=dni({textElement:o,componentCenter:A,componentRotation:t});s&&(i&&o.text===i&&(s.type="reference"),n.push(s))}return n}function fni(e,A,t){const i=[];for(const n of e){const o=n.anchor_position.x-A.x,s=-(n.anchor_position.y-A.y),r=t!==0?Rm(t*Math.PI/180):Ru(),a=Ee(r,{x:o,y:s}),g=n.font_size||1,c=new uf;c.size={width:g,height:g};const I=new hf({font:c}),l=new emA({type:"user",text:n.text,position:{x:a.x,y:a.y,angle:0},layer:"F.Fab",effects:I});i.push(l)}return i}function yni(e,A){const t=[],i=e.model_step_url||e.model_wrl_url;if(!i)return t;const n=new Bj(i);if(e.position&&(n.offset={x:(e.position.x||0)-A.x,y:-((e.position.y||0)-A.y),z:e.position.z||0}),e.rotation&&(n.rotate={x:e.rotation.x||0,y:e.rotation.y||0,z:e.rotation.z||0}),e.model_unit_to_mm_scale_factor){const o=e.model_unit_to_mm_scale_factor;n.scale={x:o,y:o,z:o}}return t.push(n),t}function mni({pcbPad:e,componentCenter:A,padNumber:t,componentRotation:i=0,netInfo:n,componentId:o}){let s,r;if("x"in e&&"y"in e)s=e.x,r=e.y;else if("points"in e&&Array.isArray(e.points)){const u=e.points;s=u.reduce((d,f)=>d+f.x,0)/u.length,r=u.reduce((d,f)=>d+f.y,0)/u.length}else throw new Error("Pad must have either x/y coordinates or points array");const a=bl(i!==0?Rm(i*Math.PI/180):{a:1,b:0,c:0,d:1,e:0,f:0},fh(1,-1),ir(-A.x,-A.y)),g=Ee(a,{x:s,y:r}),I={top:"F.Cu",bottom:"B.Cu"}[e.layer]||"F.Cu";let l,B,C,Q;if(e.shape==="circle")l="circle",B=["radius"in e?e.radius*2:.5,"radius"in e?e.radius*2:.5];else if(e.shape==="polygon"&&"points"in e){const u=e.points,d=bl(fh(1,-1),ir(-s,-r)),f=u.map(w=>{const D=Ee(d,{x:w.x,y:w.y});return new LQ(D.x,D.y)}),m=new zyA;m.contours=[new YC(f)],m.width=0,m.filled=!0,Q=new bQt,Q.addGraphic(m),l="custom",C=new cQt,C.anchor="circle",B=[.2,.2]}else l="rect",B=["width"in e?e.width:.5,"height"in e?e.height:.5];const E=`pad:${o}:${t}:${g.x},${g.y}`,h=new cj({number:String(t),padType:"smd",shape:l,at:[g.x,g.y,0],size:B,layers:[`${I}`,`${I==="F.Cu"?"F":"B"}.Paste`,`${I==="F.Cu"?"F":"B"}.Mask`],uuid:pf(E)});return C&&(h.options=C),Q&&(h.primitives=Q),n&&(h.net=new qyA(n.id,n.name)),h}function wni(e,A,t,i,n,o){const s=[];let r=n;for(const a of e){const g=o(a.pcb_port_id),c=mni({pcbPad:a,componentCenter:A,padNumber:r,componentRotation:t,netInfo:g,componentId:i});s.push(c),r++}return{pads:s,nextPadNumber:r}}function Dni({platedHole:e,componentCenter:A,padNumber:t,componentRotation:i=0,netInfo:n,componentId:o}){if(!("x"in e&&"y"in e))return null;const s=e.x-A.x,r=-(e.y-A.y),a=i!==0?Rm(i*Math.PI/180):Ru(),g=Ee(a,{x:s,y:r});let c="circle",I,l,B=0;const C="hole_offset_x"in e||"hole_offset_y"in e;let Q;if(C){const u={x:e.hole_offset_x??0,y:e.hole_offset_y??0};(u.x!==0||u.y!==0)&&(Q=Ee(a,{x:-u.x,y:u.y}))}e.shape==="circle"?(c="circle",I=[e.outer_diameter,e.outer_diameter],l=new WD({diameter:e.hole_diameter,offset:Q})):e.shape==="pill"||e.shape==="oval"?(c="oval",I=[e.outer_width,e.outer_height],l=new WD({oval:!0,diameter:e.hole_width,width:e.hole_height,offset:Q})):e.shape==="pill_hole_with_rect_pad"?(c="rect",I=[e.rect_pad_width,e.rect_pad_height],l=new WD({oval:!0,diameter:e.hole_width,width:e.hole_height,offset:Q})):e.shape==="circular_hole_with_rect_pad"?(c="rect",I=[e.rect_pad_width,e.rect_pad_height],l=new WD({diameter:e.hole_diameter,offset:Q})):e.shape==="rotated_pill_hole_with_rect_pad"?(c="rect",I=[e.rect_pad_width,e.rect_pad_height],l=new WD({oval:!0,diameter:e.hole_width,width:e.hole_height,offset:Q}),B=e.rect_ccw_rotation||0):(c="circle",I=[1.6,1.6],l=new WD({diameter:.8,offset:Q}));const E=`thruhole:${o}:${t}:${g.x},${g.y}`,h=new cj({number:String(t),padType:"thru_hole",shape:c,at:[g.x,g.y,B],size:I,drill:l,layers:["*.Cu","*.Mask"],removeUnusedLayers:!1,uuid:pf(E)});return n&&(h.net=new qyA(n.id,n.name)),h}function Sni(e,A,t,i,n,o){const s=[];let r=n;for(const a of e){const g=o(a.pcb_port_id),c=Dni({platedHole:a,componentCenter:A,padNumber:r,componentRotation:t,netInfo:g,componentId:i});c&&(s.push(c),r++)}return{pads:s,nextPadNumber:r}}function bni({pcbHole:e,componentCenter:A,componentRotation:t=0}){if(!("x"in e&&"y"in e))return null;const i=e.x-A.x,n=-(e.y-A.y),o=t!==0?Rm(t*Math.PI/180):Ru(),s=Ee(o,{x:i,y:n});let r="circle",a,g;if(e.hole_shape==="circle"){r="circle";const c=e.hole_diameter;a=[c,c],g=new WD({diameter:c})}else if(e.hole_shape==="oval"){r="oval";const c=e.hole_width,I=e.hole_height;a=[c,I],g=new WD({oval:!0,diameter:c,width:I})}else{r="circle";const c="hole_diameter"in e?e.hole_diameter:1;a=[c,c],g=new WD({diameter:c})}return new cj({number:"",padType:"np_thru_hole",shape:r,at:[s.x,s.y,0],size:a,drill:g,layers:["*.Cu","*.Mask"],removeUnusedLayers:!1,uuid:crypto.randomUUID()})}function xni(e,A,t){const i=[];for(const n of e){const o=bni({pcbHole:n,componentCenter:A,componentRotation:t});o&&i.push(o)}return i}var _ni=class extends Nh{componentsProcessed=0;pcbComponents=[];getNetInfoForPcbPort(e){if(!e)return;const A=this.ctx.db.pcb_port?.get(e);if(!A)return;const t=A.source_port_id;if(!t)return;const i=this.ctx.db.source_port?.get(t);if(!i)return;const n=i.subcircuit_connectivity_map_key;if(n)return this.ctx.pcbNetMap?.get(n)}getCadComponentForPcbComponent(e){return(this.ctx.db.cad_component?.list()||[]).find(t=>t.pcb_component_id===e)}constructor(e,A){super(e,A),this.pcbComponents=this.ctx.db.pcb_component.list()}_step(){const{kicadPcb:e,c2kMatPcb:A}=this.ctx;if(!e)throw new Error("KicadPcb instance not initialized in context");if(!A)throw new Error("PCB transformation matrix not initialized in context");if(this.componentsProcessed>=this.pcbComponents.length){this.finished=!0;return}const t=this.pcbComponents[this.componentsProcessed],i=t.source_component_id?this.ctx.db.source_component.get(t.source_component_id):null,n=this.getCadComponentForPcbComponent(t.pcb_component_id),o=i?RG(i,n):"Unknown",s=Ee(A,{x:t.center.x,y:t.center.y}),r=`footprint:${t.pcb_component_id}:${s.x},${s.y}`,a=new xmA({libraryLink:`tscircuit:${o}`,layer:"F.Cu",at:[s.x,s.y,t.rotation||0],uuid:pf(r)}),g=a.fpTexts,c=this.ctx.db.pcb_silkscreen_text?.list().filter(O=>O.pcb_component_id===t.pcb_component_id)||[];g.push(...pni(c,t.center,t.rotation||0,i?.name));const I=this.ctx.db.pcb_note_text?.list().filter(O=>O.pcb_component_id===t.pcb_component_id)||[];g.push(...fni(I,t.center,t.rotation||0)),a.fpTexts=g;const l=a.fpPads,B=O=>this.getNetInfoForPcbPort(O),C=this.ctx.db.pcb_smtpad?.list().filter(O=>O.pcb_component_id===t.pcb_component_id)||[],{pads:Q,nextPadNumber:E}=wni(C,t.center,t.rotation||0,t.pcb_component_id,1,B);l.push(...Q);const h=this.ctx.db.pcb_plated_hole?.list().filter(O=>O.pcb_component_id===t.pcb_component_id)||[],{pads:u}=Sni(h,t.center,t.rotation||0,t.pcb_component_id,E,B);l.push(...u);const d=this.ctx.db.pcb_hole?.list().filter(O=>O.subcircuit_id===t.subcircuit_id)||[],f=xni(d,t.center,t.rotation||0);l.push(...f),a.fpPads=l;const m=this.ctx.db.pcb_silkscreen_circle?.list().filter(O=>O.pcb_component_id===t.pcb_component_id)||[],w=a.fpCircles??[];w.push(...Bni(m,t.center));const D=this.ctx.db.pcb_courtyard_circle?.list().filter(O=>O.pcb_component_id===t.pcb_component_id)||[];w.push(...Cni(D,t.center)),a.fpCircles=w;const b=this.ctx.db.pcb_fabrication_note_rect?.list().filter(O=>O.pcb_component_id===t.pcb_component_id)||[],k=a.fpRects??[];k.push(...Qni(b,t.center));const x=this.ctx.db.pcb_note_rect?.list().filter(O=>O.pcb_component_id===t.pcb_component_id)||[];k.push(...Eni(x,t.center));const N=this.ctx.db.pcb_courtyard_rect?.list().filter(O=>O.pcb_component_id===t.pcb_component_id)||[];k.push(...hni(N,t.center)),a.fpRects=k;const R=this.ctx.db.pcb_courtyard_outline?.list().filter(O=>O.pcb_component_id===t.pcb_component_id)||[],U=uni(R,t.center);if(U.length>0&&(a.fpPolys=U),n){const O=yni(n,t.center);O.length>0&&(a.models=O)}const T=t.metadata?.kicad_footprint;T&&i?.name&&lni(a,T,i.name);const Y=e.footprints;Y.push(a),e.footprints=Y,this.componentsProcessed++}getOutput(){return this.ctx.kicadPcb}},kni={top:"F.Cu",bottom:"B.Cu",inner1:"In1.Cu",inner2:"In2.Cu",inner3:"In3.Cu",inner4:"In4.Cu",inner5:"In5.Cu",inner6:"In6.Cu"};function Fni(e){return e&&(kni[e]||e)||"F.Cu"}function Gni(e){const A=["F.Cu"];for(let t=1;t<e-1;t++)A.push(`In${t}.Cu`);return A.push("B.Cu"),A}var Mni=class extends Nh{tracesProcessed=0;pcbTraces=[];constructor(e,A){super(e,A),this.pcbTraces=this.ctx.db.pcb_trace.list()}_step(){const{kicadPcb:e,c2kMatPcb:A,pcbNetMap:t}=this.ctx;if(!e)throw new Error("KicadPcb instance not initialized in context");if(!A)throw new Error("PCB transformation matrix not initialized in context");if(this.tracesProcessed>=this.pcbTraces.length){this.finished=!0;return}const i=this.pcbTraces[this.tracesProcessed];if(!i.route||i.route.length<2){this.tracesProcessed++;return}let n=i.route[0]?.layer;for(let o=0;o<i.route.length-1;o++){const s=i.route[o],r=i.route[o+1],a=Ee(A,{x:s.x,y:s.y}),g=Ee(A,{x:r.x,y:r.y});let c;if(t){let E=i.subcircuit_connectivity_map_key;if(!E&&i.source_trace_id){const h=this.ctx.db.source_trace?.get(i.source_trace_id);if(h&&(E=h.subcircuit_connectivity_map_key,!E&&h.connected_source_net_ids?.length))for(const u of h.connected_source_net_ids){const d=this.ctx.db.source_net?.get(u);if(d?.subcircuit_connectivity_map_key){E=d.subcircuit_connectivity_map_key;break}}}if(!E&&typeof i.connection_name=="string"){const h=this.ctx.db.source_net?.get(i.connection_name);h?.subcircuit_connectivity_map_key&&(E=h.subcircuit_connectivity_map_key)}E&&(c=t.get(E))}const I=s.layer??r.layer??n,l=Fni(I),B=`segment:${a.x},${a.y}:${g.x},${g.y}:${l}:${c?.id??0}`,C=new JmA({start:{x:a.x,y:a.y},end:{x:g.x,y:g.y},layer:l,width:i.width||.25,net:new uj(c?.id??0),uuid:pf(B)}),Q=e.segments;Q.push(C),e.segments=Q,s.layer&&(n=s.layer),r.layer&&(n=r.layer)}this.tracesProcessed++}getOutput(){return this.ctx.kicadPcb}},Rni=class extends Nh{viasProcessed=0;pcbVias=[];constructor(e,A){super(e,A),this.pcbVias=this.ctx.db.pcb_via?.list()||[]}_step(){const{kicadPcb:e,c2kMatPcb:A,pcbNetMap:t}=this.ctx;if(!e)throw new Error("KicadPcb instance not initialized in context");if(!A)throw new Error("PCB transformation matrix not initialized in context");if(this.viasProcessed>=this.pcbVias.length){this.finished=!0;return}const i=this.pcbVias[this.viasProcessed],n=Ee(A,{x:i.x,y:i.y});let o;if(t){let I=i.subcircuit_connectivity_map_key;if(!I&&i.pcb_trace_id){const l=this.ctx.db.pcb_trace?.get(i.pcb_trace_id);if(l&&("subcircuit_connectivity_map_key"in l&&(I=l.subcircuit_connectivity_map_key),!I&&l.source_trace_id)){const B=this.ctx.db.source_trace?.get(l.source_trace_id);if(B&&("subcircuit_connectivity_map_key"in B&&(I=B.subcircuit_connectivity_map_key),!I&&B.connected_source_net_ids?.length))for(const C of B.connected_source_net_ids){const Q=this.ctx.db.source_net?.get(C);if(Q?.subcircuit_connectivity_map_key){I=Q.subcircuit_connectivity_map_key;break}}}}if(!I&&i.connection_name){const l=this.ctx.db.source_net?.get(i.connection_name);l?.subcircuit_connectivity_map_key&&(I=l.subcircuit_connectivity_map_key)}I&&(o=t.get(I))}const s=this.ctx.numLayers??2,r=i.layers?i.layers.map(I=>I==="top"?"F.Cu":I==="bottom"?"B.Cu":`In${I.replace("inner","")}.Cu`):Gni(s),a=`via:${n.x},${n.y}:${i.outer_diameter||.8}:${i.hole_diameter||.4}:${o?.id??0}`,g=new LwA({at:[n.x,n.y],size:i.outer_diameter||.8,drill:i.hole_diameter||.4,layers:r,net:new vwA(o?.id??0),uuid:pf(a)}),c=e.vias;c.push(g),e.vias=c,this.viasProcessed++}getOutput(){return this.ctx.kicadPcb}};function Nni({textElement:e,c2kMatPcb:A}){if(!e.text||!e.anchor_position)return null;const t=Ee(A,{x:e.anchor_position.x,y:e.anchor_position.y}),n={top:"F.Fab",bottom:"B.Fab"}[e.layer]||e.layer||"F.Fab",o=(e.font_size||1)/1.5,s=new uf;s.size={width:o,height:o};const r=new MJ,a=e.anchor_alignment||"center";switch(a){case"top_left":r.horizontal="left",r.vertical="top";break;case"top_right":r.horizontal="right",r.vertical="top";break;case"bottom_left":r.horizontal="left",r.vertical="bottom";break;case"bottom_right":r.horizontal="right",r.vertical="bottom";break}const g=new hf({font:s});a!=="center"&&(g.justify=r);const c=new Wg([t.x,t.y,0]),I=new hj({text:e.text,layer:n,effects:g});return I.position=c,I}function vni({textElement:e,c2kMatPcb:A}){if(!e.text||!e.anchor_position)return null;const t=Ee(A,{x:e.anchor_position.x,y:e.anchor_position.y}),n={top:"F.SilkS",bottom:"B.SilkS"}[e.layer]||e.layer||"F.SilkS",o=(e.font_size||1)/1.5,s=new uf;s.size={width:o,height:o};const r=new MJ,a=e.anchor_alignment||"center";switch(a){case"top_left":r.horizontal="left",r.vertical="top";break;case"top_right":r.horizontal="right",r.vertical="top";break;case"bottom_left":r.horizontal="left",r.vertical="bottom";break;case"bottom_right":r.horizontal="right",r.vertical="bottom";break}const g=new hf({font:s});a!=="center"&&(g.justify=r);const c=e.ccw_rotation||0,I=new Wg([t.x,t.y,c]),l=new hj({text:e.text,layer:n,effects:g});return l.position=I,l}var Lni=class extends Nh{_step(){const{kicadPcb:e,c2kMatPcb:A}=this.ctx;if(!e)throw new Error("KicadPcb instance not initialized in context");if(!A)throw new Error("PCB transformation matrix not initialized in context");const t=this.ctx.db.pcb_silkscreen_path?.list()||[];for(const s of t)if(!(!s.route||s.route.length<2))for(let r=0;r<s.route.length-1;r++){const a=s.route[r],g=s.route[r+1];if(!a||!g)continue;const c=Ee(A,{x:a.x,y:a.y}),I=Ee(A,{x:g.x,y:g.y}),B={top:"F.SilkS",bottom:"B.SilkS"}[s.layer]||s.layer||"F.SilkS",C=new Ej({start:{x:c.x,y:c.y},end:{x:I.x,y:I.y},layer:B,width:s.stroke_width||.15}),Q=e.graphicLines;Q.push(C),e.graphicLines=Q}const i=this.ctx.db.pcb_silkscreen_text?.list().filter(s=>!s.pcb_component_id)||[];for(const s of i){const r=vni({textElement:s,c2kMatPcb:A});if(r){const a=e.graphicTexts;a.push(r),e.graphicTexts=a}}const n=this.ctx.db.pcb_fabrication_note_text?.list()||[];for(const s of n){const r=Nni({textElement:s,c2kMatPcb:A});if(r){const a=e.graphicTexts;a.push(r),e.graphicTexts=a}}const o=this.ctx.db.pcb_board?.list()||[];if(o.length>0){const s=o[0];if(!s){this.finished=!0;return}let r;if(s.outline&&s.outline.length>0)r=s.outline;else{const g=s.width?s.width/2:0,c=s.height?s.height/2:0;r=[{x:s.center.x-g,y:s.center.y-c},{x:s.center.x+g,y:s.center.y-c},{x:s.center.x+g,y:s.center.y+c},{x:s.center.x-g,y:s.center.y+c}]}const a=r.map(g=>Ee(A,g));for(let g=0;g<a.length;g++){const c=a[g],I=a[(g+1)%a.length];if(!c||!I)continue;const l=new Ej({start:{x:c.x,y:c.y},end:{x:I.x,y:I.y},layer:"Edge.Cuts",width:.1}),B=e.graphicLines;B.push(l),e.graphicLines=B}}this.finished=!0}getOutput(){return this.ctx.kicadPcb}},wht=class{ctx;pipeline;currentStageIndex=0;finished=!1;get currentStage(){return this.pipeline[this.currentStageIndex]}constructor(e){this.ctx={db:xa(e),circuitJson:e,kicadPcb:new UwA({generator:"circuit-json-to-kicad",generatorVersion:"0.0.1"}),c2kMatPcb:bl(ir(100,100),fh(1,-1))},this.pipeline=[new gni(e,this.ctx),new cni(e,this.ctx),new _ni(e,this.ctx),new Mni(e,this.ctx),new Rni(e,this.ctx),new Lni(e,this.ctx)]}step(){if(!this.currentStage){this.finished=!0;return}this.currentStage.step(),this.currentStage.finished&&this.currentStageIndex++}runUntilFinished(){for(;!this.finished;)this.step()}getOutput(){return this.ctx.kicadPcb}getOutputString(){return this.ctx.kicadPcb.getString()}},Uni=class{ctx;project;constructor(e,A={}){const t=A.projectName??e?.project?.name??"circuit-json-project",i=A.schematicFilename??`${t}.kicad_sch`,n=A.pcbFilename??`${t}.kicad_pcb`,o=new Date().toISOString();this.ctx={db:xa(e),circuitJson:e},this.project={version:1,head:{generator:"circuit-json-to-kicad",generator_version:"0.0.1",project_name:t,created:o,modified:o},meta:{version:1},text_variables:{},libraries:{pinned_symbol_libs:[],pinned_footprint_libs:[]},boards:[],cvpcb:{meta:{version:0}},erc:{meta:{version:0},erc_exclusions:[]},net_settings:{meta:{version:1},last_net_id:0,classes:[]},pcbnew:{page_layout_descr_file:"",last_paths:{}},schematic:{meta:{version:1},page_layout_descr_file:"",last_opened_files:[i]},board:{meta:{version:1},last_opened_board:n},sheets:[[Math.random().toString(36).substring(2,15),"Root"]]}}runUntilFinished(){}getOutput(){return this.project}getOutputString(){return`${JSON.stringify(this.project,null,2)}
5828
+ `)}};NA.register(LwA);var UwA=class byt extends NA{static token="kicad_pcb";token="kicad_pcb";_sxVersion;_sxGenerator;_sxGeneratorVersion;_sxGeneral;_sxPaper;_sxTitleBlock;_sxLayers;_sxSetup;_properties=[];_nets=[];_footprints=[];_images=[];_segments=[];_grLines=[];_grTexts=[];_grPolys=[];_grRects=[];_vias=[];_zones=[];_otherChildren=[];constructor(A={}){super(),A.version!==void 0&&(this.version=A.version),A.generator!==void 0&&(this.generator=A.generator),A.generatorVersion!==void 0&&(this.generatorVersion=A.generatorVersion),A.general!==void 0&&(this.general=A.general),A.paper!==void 0&&(this.paper=A.paper),A.titleBlock!==void 0&&(this.titleBlock=A.titleBlock),A.layers!==void 0&&(this.layers=A.layers),A.setup!==void 0&&(this.setup=A.setup),A.properties!==void 0&&(this.properties=A.properties),A.nets!==void 0&&(this.nets=A.nets),A.footprints!==void 0&&(this.footprints=A.footprints),A.images!==void 0&&(this.images=A.images),A.segments!==void 0&&(this.segments=A.segments),A.graphicLines!==void 0&&(this.graphicLines=A.graphicLines),A.graphicTexts!==void 0&&(this.graphicTexts=A.graphicTexts),A.graphicPolys!==void 0&&(this.graphicPolys=A.graphicPolys),A.graphicRects!==void 0&&(this.graphicRects=A.graphicRects),A.vias!==void 0&&(this.vias=A.vias),A.zones!==void 0&&(this.zones=A.zones),A.otherChildren!==void 0&&(this.otherChildren=A.otherChildren)}static fromSexprPrimitives(A){const t=new byt;for(const i of A){if(!Array.isArray(i)||i.length===0)throw new Error(`kicad_pcb encountered unsupported primitive child: ${JSON.stringify(i)}`);const n=NA.parsePrimitiveSexpr(i,{parentToken:this.token});if(!(n instanceof NA))throw new Error(`kicad_pcb expected SxClass child, received ${JSON.stringify(i)}`);t.consumeChild(n)}return t}consumeChild(A){if(A instanceof MwA){this._sxVersion=A;return}if(A instanceof RwA){this._sxGenerator=A;return}if(A instanceof NwA){this._sxGeneratorVersion=A;return}if(A instanceof FwA){this._sxGeneral=A;return}if(A instanceof ij){this._sxPaper=A;return}if(A instanceof QCt){this._sxTitleBlock=A;return}if(A instanceof GwA){this._sxLayers=A;return}if(A instanceof kwA){this._sxSetup=A;return}if(A instanceof OD){this._properties.push(A);return}if(A instanceof fj){this._nets.push(A);return}if(A instanceof xmA){this._footprints.push(A);return}if(A instanceof hCt){this._images.push(A);return}if(A instanceof JmA){this._segments.push(A);return}if(A instanceof Ej){this._grLines.push(A);return}if(A instanceof hj){this._grTexts.push(A);return}if(A instanceof sEt){this._grPolys.push(A);return}if(A instanceof iEt){this._grRects.push(A);return}if(A instanceof LwA){this._vias.push(A);return}if(A instanceof lEt){this._zones.push(A);return}this._otherChildren.push(A)}get version(){return this._sxVersion?.value}set version(A){this._sxVersion=A===void 0?void 0:new MwA(A)}get generator(){return this._sxGenerator?.value}set generator(A){this._sxGenerator=A===void 0?void 0:new RwA(A)}get generatorVersion(){return this._sxGeneratorVersion?.value}set generatorVersion(A){this._sxGeneratorVersion=A===void 0?void 0:new NwA(A)}get general(){return this._sxGeneral}set general(A){this._sxGeneral=A}get paper(){return this._sxPaper}set paper(A){this._sxPaper=A}get titleBlock(){return this._sxTitleBlock}set titleBlock(A){this._sxTitleBlock=A}get layers(){return this._sxLayers}set layers(A){this._sxLayers=A}get setup(){return this._sxSetup}set setup(A){this._sxSetup=A}get properties(){return[...this._properties]}set properties(A){this._properties=[...A]}get nets(){return[...this._nets]}set nets(A){this._nets=[...A]}get footprints(){return[...this._footprints]}set footprints(A){this._footprints=[...A]}get images(){return[...this._images]}set images(A){this._images=[...A]}get segments(){return[...this._segments]}set segments(A){this._segments=[...A]}get graphicLines(){return[...this._grLines]}set graphicLines(A){this._grLines=[...A]}get graphicTexts(){return[...this._grTexts]}set graphicTexts(A){this._grTexts=[...A]}get graphicPolys(){return[...this._grPolys]}set graphicPolys(A){this._grPolys=[...A]}get graphicRects(){return[...this._grRects]}set graphicRects(A){this._grRects=[...A]}get vias(){return[...this._vias]}set vias(A){this._vias=[...A]}get zones(){return[...this._zones]}set zones(A){this._zones=[...A]}get otherChildren(){return[...this._otherChildren]}set otherChildren(A){this._otherChildren=[...A]}getChildren(){const A=[];return this._sxVersion&&A.push(this._sxVersion),this._sxGenerator&&A.push(this._sxGenerator),this._sxGeneratorVersion&&A.push(this._sxGeneratorVersion),this._sxGeneral&&A.push(this._sxGeneral),this._sxPaper&&A.push(this._sxPaper),this._sxTitleBlock&&A.push(this._sxTitleBlock),this._sxLayers&&A.push(this._sxLayers),this._sxSetup&&A.push(this._sxSetup),A.push(...this._properties),A.push(...this._nets),A.push(...this._footprints),A.push(...this._images),A.push(...this._segments),A.push(...this._grLines),A.push(...this._grTexts),A.push(...this._grPolys),A.push(...this._grRects),A.push(...this._vias),A.push(...this._zones),A.push(...this._otherChildren),A}};NA.register(UwA);var hht=e=>NA.parse(e),Nh=class{MAX_ITERATIONS=1e3;iteration=0;finished=!1;input;ctx;constructor(e,A){this.input=e,this.ctx=A}step(){if(this.iteration++,this.iteration>this.MAX_ITERATIONS)throw new Error("Max iterations reached");this._step()}_step(){throw new Error("Not implemented")}runUntilFinished(){for(;!this.finished;)this.step()}getOutput(){throw new Error("Not implemented")}},Tii=class extends Nh{_step(){const{kicadSch:e,schematicPaperSize:A}=this.ctx;if(!e)throw new Error("KicadSch instance not initialized in context");e.version=20250114;const t=new ij;t.size=A?.name??"A4",e.paper=t,e.uuid=new Li(crypto.randomUUID()),this.finished=!0}getOutput(){return this.ctx.kicadSch}};function RG(e,A){if(e.manufacturer_part_number)return HwA(e.manufacturer_part_number);const t=Kii(e.ftype),i=A?.footprinter_string;return HwA(i?`${t}_${i}`:t)}function Kii(e){if(!e)return"component";let A=e.replace(/^simple_/,"");return A||"component"}function HwA(e){return e.replace(/[\\\/:\s]+/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"").trim()||"component"}function uht(e){return e?e.match(/^([A-Za-z]+)/)?.[1]?.toUpperCase()??"U":"U"}var dht={simple_resistor:"R",simple_capacitor:"C",simple_inductor:"L",simple_diode:"D",simple_led:"D",simple_chip:"U",simple_transistor:"Q",simple_mosfet:"Q",simple_fuse:"F",simple_switch:"SW",simple_push_button:"SW",simple_potentiometer:"RV",simple_crystal:"Y",simple_resonator:"Y",simple_pin_header:"J",simple_pinout:"J",simple_test_point:"TP",simple_battery:"BT"},Pii=/^[A-Za-z]+\d+$/;function pht(e){return e?Pii.test(e.trim()):!1}function yj(e){const A=e?.ftype;if(A&&dht[A])return dht[A];const t=e?.name;return pht(t),uht(t)}function qii(e){const A=e?.name;return pht(A)?A.trim():`${yj(e)}?`}function fht(e){return e in wQ}function yht(e,A,t,i){if(i)return`Custom:${i}`;if(e.type!=="source_component")return A.symbol_name?fht(A.symbol_name)?`Device:${A.symbol_name}`:`Custom:${A.symbol_name}`:"Device:Component";if(A.symbol_name)return fht(A.symbol_name)?`Device:${A.symbol_name}`:`Custom:${A.symbol_name}`;const n=RG(e,t);return`Device:${yj(e)}_${n}`}function Oii(e){const{circuitJson:A,schematicSymbolId:t,schematicSymbol:i,schematicComponentId:n}=e,o=A.filter(Q=>Q.type==="schematic_circle"&&Q.schematic_symbol_id===t),s=A.filter(Q=>Q.type==="schematic_line"&&Q.schematic_symbol_id===t),r=n?A.filter(Q=>Q.type==="schematic_line"&&Q.schematic_component_id===n&&!Q.schematic_symbol_id):[],a=[...s,...r],g=A.filter(Q=>Q.type==="schematic_path"&&Q.schematic_symbol_id===t),c=A.filter(Q=>Q.type==="schematic_text"&&Q.schematic_symbol_id===t);let I=A.filter(Q=>Q.type==="schematic_port"&&"schematic_symbol_id"in Q&&Q.schematic_symbol_id===t);if(I.length===0&&n){const Q=A.filter(h=>h.type==="schematic_port"&&h.schematic_component_id===n&&h.display_pin_label!==void 0),E=new Map;for(const h of Q)h.display_pin_label&&E.set(h.display_pin_label,h);if(I=E.size>0?Array.from(E.values()):Q,I.length===0){const h=A.filter(d=>d.type==="schematic_port"&&d.schematic_component_id===n),u=new Set;I=h.filter(d=>{const f=d.pin_number;if(f!==void 0){if(u.has(f))return!1;u.add(f)}return!0})}}const l=[];for(const Q of o)l.push({type:"circle",x:Q.center?.x??0,y:Q.center?.y??0,radius:Q.radius??.5,fill:Q.is_filled??!1,fillColor:Q.fill_color});for(const Q of a)l.push({type:"path",points:[{x:Q.x1??0,y:Q.y1??0},{x:Q.x2??0,y:Q.y2??0}]});for(const Q of g)Q.points&&Q.points.length>0&&l.push({type:"path",points:Q.points,fill:Q.is_filled??!1,fillColor:Q.fill_color});const B=c.map(Q=>({text:Q.text??"",x:Q.position?.x??0,y:Q.position?.y??0,fontSize:Q.font_size??.2,anchor:Q.anchor??"center"})),C=I.map((Q,E)=>({x:Q.center?.x??0,y:Q.center?.y??0,labels:[Q.display_pin_label||`${Q.pin_number||E+1}`],pinNumber:Q.pin_number||E+1,facingDirection:Q.facing_direction}));return C.sort((Q,E)=>Q.pinNumber-E.pinNumber),{center:i.center||{x:0,y:0},size:i.size||{width:1,height:1},primitives:l,texts:B,ports:C}}function Wii({points:e,transform:A,fillType:t}){const i=new dCt,n=e.map(a=>{const g=Ee(A,a);return new LQ(g.x,g.y)}),o=new YC(n);i.points=o;const s=new qD;s.width=.254,s.type="default",i.stroke=s;const r=new SCt;return r.type=t,i.fill=r,i}function Zii({primitive:e,transform:A,scale:t}){const i=new _Ct,n=Ee(A,{x:e.x,y:e.y}),o=i;o._sxCenter=new wCt(n.x,n.y),o._sxRadius=new DCt(e.radius*t);const s=new qD;s.width=.254,s.type="default",o._sxStroke=s;const r=new bCt;return r.type=e.fill?"background":"none",o._sxFill=r,i}function Vii({schText:e,transform:A,scale:t}){const i=new kCt,n=Ee(A,{x:e.x,y:e.y});i.value=e.text,i.at=[n.x,n.y,0];const o=e.fontSize*t,s=new uf;return s.size={height:o,width:o},i.effects=new hf({font:s}),i}function jii({libId:e,symbolData:A,isChip:t,c2kMatSchScale:i}){const n=new w1({libraryId:`${e.split(":")[1]}_0_1`}),o=i,s=A.center?.x??0,r=A.center?.y??0,a=bl(fh(o,o),ir(-s,-r));for(const c of A.primitives||[])if(c.type==="path"&&c.points){const I=t||c.fill?"background":"none",l=Wii({points:c.points,transform:a,fillType:I});n.polylines.push(l)}else if(c.type==="circle"){const I=Zii({primitive:c,transform:a,scale:o});n.circles.push(I)}const g=Array.isArray(A.texts)?A.texts:[];for(const c of g){const I=Vii({schText:c,transform:a,scale:o});n.texts.push(I)}return n}function zii(e,A){const t=A.schematic_port.list().filter(r=>r.schematic_component_id===e.schematic_component_id).sort((r,a)=>(r.pin_number||0)-(a.pin_number||0)),i=e.size?.width||1.5,n=e.size?.height||1,o={type:"path",points:[{x:-i/2,y:-n/2},{x:i/2,y:-n/2},{x:i/2,y:n/2},{x:-i/2,y:n/2},{x:-i/2,y:-n/2}]},s=t.map(r=>{const a=r.center.x-e.center.x,g=r.center.y-e.center.y;return{x:a,y:g,labels:[r.display_pin_label||`${r.pin_number||1}`],pinNumber:r.pin_number||1}});return{center:{x:0,y:0},primitives:[o],ports:s,size:{width:i,height:n}}}function Xii(e,A){const t=new uf;return t.size={height:e,width:e},new hf({font:t,hiddenText:A})}function $ii({symbol:e,libId:A,description:t,keywords:i,fpFilters:n,footprintRef:o="",referencePrefix:s}){const r=s||A.split(":")[1]?.[0]||"U",a=[{key:"Reference",value:r,id:0,at:[2.032,0,90],hide:!1},{key:"Value",value:r,id:1,at:[0,0,90],hide:!1},{key:"Footprint",value:o,id:2,at:[-1.778,0,90],hide:!0},{key:"Datasheet",value:"~",id:3,at:[0,0,0],hide:!0},{key:"Description",value:t,id:4,at:[0,0,0],hide:!0},{key:"ki_keywords",value:i,id:5,at:[0,0,0],hide:!0},{key:"ki_fp_filters",value:n,id:6,at:[0,0,0],hide:!0}];for(const g of a)e.properties.push(new df({key:g.key,value:g.value,id:g.id,at:g.at,effects:Xii(1.27,g.hide)}))}function Ani({port:e,center:A,size:t,isChip:i,portIndex:n,schematicComponent:o,schematicPorts:s,c2kMatSchScale:r}){const a=r;let g=e.x??0,c=e.y??0,I=!1;if(i&&n!==void 0&&o){const m=s.filter(w=>w.schematic_component_id===o.schematic_component_id).sort((w,D)=>(w.pin_number||0)-(D.pin_number||0));if(m[n]){const w=m[n];g=w.center.x-o.center.x,c=w.center.y-o.center.y,I=!0}}let l,B;if(I)l=g,B=c;else{const m=A?.x??0,w=A?.y??0;l=g-m,B=c-w}const C=fh(a,a),Q=Ee(C,{x:l,y:B});let E;if(i&&t){const m=t.width/2,w=t.height/2,D=Math.abs(l)/m,b=Math.abs(B)/w;E=D>b}else E=Math.abs(l)>Math.abs(B);let h=Q.x,u=Q.y;const d=6;if(i&&t){const m=t.width/2*a,w=t.height/2*a;E?(h=l>0?m:-m,u=B*a):(h=l*a,u=B>0?w:-w)}let f=0;return E?l>0?(f=180,i&&(h=h+d)):(f=0,i&&(h=h-d)):B>0?(f=270,i&&(u=u+d)):(f=90,i&&(u=u-d)),{x:h,y:u,angle:f}}function tni({libId:e,symbolData:A,isChip:t,schematicComponent:i,schematicPorts:n,c2kMatSchScale:o}){const s=new w1({libraryId:`${e.split(":")[1]}_1_1`}),r=6,a=2.54;for(let g=0;g<(A.ports?.length||0);g++){const c=A.ports[g],I=new rj;I.pinElectricalType="passive",I.pinGraphicStyle="line";const{x:l,y:B,angle:C}=Ani({port:c,center:A.center,size:A.size,isChip:t,portIndex:g,schematicComponent:i,schematicPorts:n,c2kMatSchScale:o});I.at=[l,B,C],I.length=t?r:a;const Q=new uf;Q.size={height:1.27,width:1.27};const E=new hf({font:Q}),h=c.labels?.[0]||"~";I._sxName=new uyA({value:h,effects:E});const u=new uf;u.size={height:1.27,width:1.27};const d=new hf({font:u}),f=c.pinNumber?.toString()||`${g+1}`;I._sxNumber=new GCt({value:f,effects:d}),s.pins.push(I)}return s}var eni=class extends Nh{processedSymbolNames=new Set;_step(){const{kicadSch:e,db:A}=this.ctx,t=new HCt,i=[];this.processedSymbolNames=new Set;const n=A.schematic_component.list();for(const s of n){const r=this.createLibrarySymbolForComponent(s);r&&i.push(r)}const o=A.schematic_net_label?.list?.()||[];for(const s of o)if(s.symbol_name){const r=s.source_net_id?A.source_net.get(s.source_net_id)?.is_power:!1,a=s.source_net_id?A.source_net.get(s.source_net_id)?.is_ground:!1;if(r||a){const c=this.createLibrarySymbolForNetLabel({netLabel:s,isPower:r??!1,isGround:a??!1});c&&i.push(c)}}t.symbols=i,e&&(e.libSymbols=t),this.finished=!0}createLibrarySymbolForComponent(e){const{db:A}=this.ctx,t=e.source_component_id?A.source_component.get(e.source_component_id):null;if(!t)return null;const i=A.cad_component?.list()?.find(c=>c.source_component_id===t.source_component_id);let n=e.schematic_symbol_id;if(!n){const c=this.ctx.circuitJson.find(I=>(I.type==="schematic_line"||I.type==="schematic_circle"||I.type==="schematic_path")&&I.schematic_component_id===e.schematic_component_id&&I.schematic_symbol_id);c&&(n=c.schematic_symbol_id)}if(n)return this.createLibrarySymbolFromSchematicSymbol(e,t,i,n);const o=e.symbol_name||(t.ftype==="simple_chip"?`generic_chip_${e.source_component_id}`:null);if(!o)return null;const s=this.getSymbolData(o,e);if(!s)return null;const r=yht(t,e,i),a=t.ftype==="simple_chip",g=RG(t,i);return this.createLibrarySymbol({libId:r,symbolData:s,isChip:a,schematicComponent:e,description:this.getDescription(t),keywords:this.getKeywords(t),fpFilters:this.getFpFilters(t),footprintRef:g?`tscircuit:${g}`:"",referencePrefix:yj(t)})}createLibrarySymbolFromSchematicSymbol(e,A,t,i){const{db:n}=this.ctx,o=this.ctx.circuitJson.find(c=>c.type==="schematic_symbol"&&c.schematic_symbol_id===i);if(!o)return null;let s;if(o.name)s=o.name;else{const c=RG(A,t);c?s=c:s=`custom_${A.ftype||"component"}_${i}`}const r=`Custom:${s}`;if(this.processedSymbolNames.has(r))return null;this.processedSymbolNames.add(r);const a=Oii({circuitJson:this.ctx.circuitJson,schematicSymbolId:i,schematicSymbol:o,schematicComponentId:e.schematic_component_id}),g=RG(A,t);return this.createLibrarySymbol({libId:r,symbolData:a,isChip:!1,schematicComponent:e,description:this.getDescription(A),keywords:this.getKeywords(A),fpFilters:this.getFpFilters(A,o.name),footprintRef:g?`tscircuit:${g}`:"",referencePrefix:yj(A),symbolScale:1})}createLibrarySymbolForNetLabel({netLabel:e,isPower:A,isGround:t}){const i=e.symbol_name;if(!i)return null;const n=wQ[i];if(!n)return null;const o=`Custom:${i}`;return this.createLibrarySymbol({libId:o,symbolData:n,isChip:!1,schematicComponent:void 0,description:A?"Power net label":t?"Ground net label":"Net symbol",keywords:A?"power net":t?"ground net":"net",fpFilters:"",referencePrefix:o.split(":")[1]?.[0]||"U"})}getSymbolData(e,A){return e.startsWith("generic_chip_")?zii(A,this.ctx.db):wQ[e]||null}createLibrarySymbol({libId:e,symbolData:A,isChip:t,schematicComponent:i,description:n,keywords:o,fpFilters:s,footprintRef:r="",referencePrefix:a,symbolScale:g}){const I=g??this.ctx.c2kMatSch?.a??15,l=new w1({libraryId:e,excludeFromSim:!1,inBom:!0,onBoard:!0}),B=new QyA;B.hide=!t,l._sxPinNumbers=B;const C=new hyA;C.offset=t?1.27:0,l._sxPinNames=C,$ii({symbol:l,libId:e,description:n,keywords:o,fpFilters:s,footprintRef:r,referencePrefix:a});const Q=jii({libId:e,symbolData:A,isChip:t,c2kMatSchScale:I});l.subSymbols.push(Q);const E=tni({libId:e,symbolData:A,isChip:t,schematicComponent:i,schematicPorts:this.ctx.db.schematic_port.list(),c2kMatSchScale:I});return l.subSymbols.push(E),l._sxEmbeddedFonts=new y1(!1),l}getDescription(e){return e?.ftype==="simple_resistor"?"Resistor":e?.ftype==="simple_capacitor"?"Capacitor":e?.ftype==="simple_chip"?"Integrated Circuit":"Component"}getKeywords(e){return e?.ftype==="simple_resistor"?"R res resistor":e?.ftype==="simple_capacitor"?"C cap capacitor":e?.ftype==="simple_chip"?"U IC chip":""}getFpFilters(e,A){return A?`${A}*`:e?.ftype==="simple_resistor"?"R_*":e?.ftype==="simple_capacitor"?"C_*":(e?.ftype==="simple_chip","*")}getOutput(){if(!this.ctx.kicadSch)throw new Error("kicadSch is not initialized");return this.ctx.kicadSch}},ini=class extends Nh{_step(){const{kicadSch:e,db:A}=this.ctx,t=A.schematic_component.list();if(t.length===0){this.finished=!0;return}const i=[];for(const n of t){const o=n.source_component_id?A.source_component.get(n.source_component_id):null;if(!o||!this.ctx.c2kMatSch)continue;const{x:s,y:r}=Ee(this.ctx.c2kMatSch,{x:n.center.x,y:n.center.y}),a=crypto.randomUUID(),g=new w1({at:[s,r,0],unit:1,excludeFromSim:!1,inBom:!0,onBoard:!0,dnp:!1,uuid:a,fieldsAutoplaced:!0}),c=A.cad_component?.list()?.find(oA=>oA.source_component_id===o.source_component_id);let I,l=n.schematic_symbol_id;if(!l){const oA=this.ctx.circuitJson.find(rA=>(rA.type==="schematic_line"||rA.type==="schematic_circle"||rA.type==="schematic_path")&&rA.schematic_component_id===n.schematic_component_id&&rA.schematic_symbol_id);oA&&(l=oA.schematic_symbol_id)}if(l){const oA=this.ctx.circuitJson.find(rA=>rA.type==="schematic_symbol"&&rA.schematic_symbol_id===l);if(oA?.name)I=oA.name;else{const rA=RG(o,c);rA?I=rA:I=`custom_${o.ftype||"component"}_${l}`}}const B=yht(o,n,c,I),C=new ByA(B);g._sxLibId=C;const{reference:Q,value:E,description:h}=this.getComponentMetadata(o),{refTextPos:u,valTextPos:d}=this.getTextPositions(n,{x:s,y:r});let f;if(l){const oA=this.ctx.circuitJson.find(rA=>rA.type==="schematic_symbol"&&rA.schematic_symbol_id===l);oA&&oA.type==="schematic_symbol"&&(f=oA.metadata?.kicad_symbol)}const m=f?.properties?.Reference,w=new df({key:"Reference",value:m?.value??Q,id:0,at:[u.x,u.y,0],effects:this.createTextEffects(Number(m?.effects?.font?.size?.x??1.27),m?.effects?.hide??!1)}),D=o.ftype==="simple_chip",b=f?.properties?.Value,k=new df({key:"Value",value:b?.value??E,id:1,at:[d.x,d.y,0],effects:this.createTextEffects(Number(b?.effects?.font?.size?.x??1.27),b?.effects?.hide??D)}),x=f?.properties?.Footprint,N=new df({key:"Footprint",value:x?.value??"",id:2,at:[s-1.778,r,90],effects:this.createTextEffects(1.27,x?.effects?.hide??!0)}),R=f?.properties?.Datasheet,U=new df({key:"Datasheet",value:R?.value??"~",id:3,at:[s,r,0],effects:this.createTextEffects(1.27,R?.effects?.hide??!0)}),T=f?.properties?.Description,Y=new df({key:"Description",value:T?.value??h,id:4,at:[s,r,0],effects:this.createTextEffects(1.27,T?.effects?.hide??!0)});g.properties.push(w,k,N,U,Y);const O=f?.properties?.ki_keywords;if(O?.value){const oA=new df({key:"ki_keywords",value:O.value,id:5,at:[s,r,0],effects:this.createTextEffects(1.27,O.effects?.hide??!0)});g.properties.push(oA)}const W=f?.properties?.ki_fp_filters;if(W?.value){const oA=new df({key:"ki_fp_filters",value:W.value,id:6,at:[s,r,0],effects:this.createTextEffects(1.27,W.effects?.hide??!0)});g.properties.push(oA)}if(f){if(f.inBom!==void 0&&(g.inBom=f.inBom),f.onBoard!==void 0&&(g.onBoard=f.onBoard),f.excludeFromSim!==void 0&&(g.excludeFromSim=f.excludeFromSim),f.pinNames){const oA=new hyA;f.pinNames.offset!==void 0&&(oA.offset=Number(f.pinNames.offset)),f.pinNames.hide!==void 0&&(oA.hide=f.pinNames.hide),g.pinNames=oA}if(f.pinNumbers){const oA=new QyA;f.pinNumbers.hide!==void 0&&(oA.hide=f.pinNumbers.hide),g.pinNumbers=oA}f.embeddedFonts!==void 0&&(g._sxEmbeddedFonts=new y1(f.embeddedFonts))}let X=A.schematic_port.list().filter(oA=>oA.schematic_component_id===n.schematic_component_id);if(l){const oA=X.filter(rA=>rA.display_pin_label);oA.length>0&&(X=oA)}X.sort((oA,rA)=>(oA.pin_number||0)-(rA.pin_number||0));for(let oA=0;oA<X.length;oA++){const rA=X[oA];if(!rA)continue;const CA=new rj;CA.numberString=`${rA.pin_number||oA+1}`,CA.uuid=crypto.randomUUID(),g.pins.push(CA)}const iA=new dyA,aA=new fyA(""),tA=new yyA(`/${e?.uuid?.value||""}`);tA.reference=Q,tA.unit=1,aA.paths.push(tA),iA.projects.push(aA),g._sxInstances=iA,i.push(g)}e&&(e.symbols=i),this.finished=!0}getTextPositions(e,A){const i=(this.ctx.db.schematic_text?.list?.()?.filter(B=>B.schematic_component_id===e.schematic_component_id)||[]).find(B=>B.text&&B.text.length>0);if(i&&this.ctx.c2kMatSch){const B=Ee(this.ctx.c2kMatSch,{x:i.position.x,y:i.position.y}),C={x:A.x,y:A.y+6};return{refTextPos:B,valTextPos:C}}const n=e.symbol_name,o=wQ[n];if(!o)return{refTextPos:{x:A.x,y:A.y-6},valTextPos:{x:A.x,y:A.y+6}};let s=null,r=null;for(const B of o.primitives)B.type==="text"&&(B.text==="{REF}"?s=B:B.text==="{VAL}"&&(r=B));const a=o.center||{x:0,y:0},c=n.includes("_down")||n.includes("_up")?.15:0,I=s&&this.ctx.c2kMatSch?Ee(this.ctx.c2kMatSch,{x:e.center.x+(s.x-a.x)+c,y:e.center.y+(s.y-a.y)}):{x:A.x,y:A.y-6},l=r&&this.ctx.c2kMatSch?Ee(this.ctx.c2kMatSch,{x:e.center.x+(r.x-a.x)+c,y:e.center.y+(r.y-a.y)}):{x:A.x,y:A.y+6};return{refTextPos:I,valTextPos:l}}getComponentMetadata(e){const A=e.name||"?",t=qii(e);return e.ftype==="simple_resistor"?{reference:t,value:e.display_resistance||"R",description:"Resistor"}:e.ftype==="simple_capacitor"?{reference:t,value:e.display_capacitance||"C",description:"Capacitor"}:e.ftype==="simple_inductor"?{reference:t,value:e.display_inductance||"L",description:"Inductor"}:e.ftype==="simple_diode"?{reference:t,value:"D",description:"Diode"}:e.ftype==="simple_chip"?{reference:t,value:A,description:"Integrated Circuit"}:e.ftype==="simple_led"?{reference:t,value:e.manufacturer_part_number||"",description:"LED"}:e.ftype==="simple_switch"?{reference:t,value:e.manufacturer_part_number||"",description:"Switch"}:e.ftype==="simple_potentiometer"?{reference:t,value:e.display_max_resistance||"",description:"Potentiometer"}:{reference:t,value:A,description:"Component"}}createTextEffects(e,A=!1,t){const i=new uf;i.size={height:e,width:e};const n=t?new MJ({horizontal:t}):void 0;return new hf({font:i,hiddenText:A,justify:n})}getOutput(){if(!this.ctx.kicadSch)throw new Error("kicadSch is not initialized");return this.ctx.kicadSch}},nni=class extends Nh{_step(){const{kicadSch:e,db:A}=this.ctx,t=A.schematic_net_label?.list?.()||[];if(t.length===0){this.finished=!0;return}if(!this.ctx.c2kMatSch){this.finished=!0;return}const i=[],n=[];for(const o of t){const s=o.text||"",r=o.symbol_name;if(r){const a=this.createSymbolFromNetLabel(o,s,r);a&&i.push(a)}else{const a=this.createGlobalLabel(o,s);a&&n.push(a)}}if(e&&i.length>0){const o=e.symbols||[];e.symbols=[...o,...i]}e&&n.length>0&&(e.globalLabels=[...e.globalLabels||[],...n]),this.finished=!0}createSymbolFromNetLabel(e,A,t){if(!this.ctx.c2kMatSch)return null;const{x:i,y:n}=Ee(this.ctx.c2kMatSch,{x:e.anchor_position?.x??e.center?.x??0,y:e.anchor_position?.y??e.center?.y??0}),o=crypto.randomUUID(),s=new w1({at:[i,n,0],unit:1,excludeFromSim:!1,inBom:!0,onBoard:!0,dnp:!1,uuid:o,fieldsAutoplaced:!0}),r=`Custom:${t}`,a=new ByA(r);s._sxLibId=a;const g=t.includes("_up")||t.toLowerCase().includes("vcc"),c=g?-4:4,I=g?-6:6,l=new df({key:"Reference",value:A,id:0,at:[i,n+c,0],effects:this.createTextEffects(1.27,!1)}),B=new df({key:"Value",value:A,id:1,at:[i,n+I,0],effects:this.createTextEffects(1.27,!0)}),C=new df({key:"Footprint",value:"",id:2,at:[i-1.778,n,90],effects:this.createTextEffects(1.27,!0)}),Q=new df({key:"Datasheet",value:"~",id:3,at:[i,n,0],effects:this.createTextEffects(1.27,!0)}),E=new df({key:"Description",value:`Power/Net symbol: ${A}`,id:4,at:[i,n,0],effects:this.createTextEffects(1.27,!0)});s.properties.push(l,B,C,Q,E);const h=new rj;h.numberString="1",h.uuid=crypto.randomUUID(),s.pins.push(h);const{kicadSch:u}=this.ctx,d=new dyA,f=new fyA(""),m=new yyA(`/${u?.uuid?.value||""}`);return m.reference=A,m.unit=1,f.paths.push(m),d.projects.push(f),s._sxInstances=d,s}createGlobalLabel(e,A){if(!this.ctx.c2kMatSch||!this.ctx.kicadSch)return null;const{x:t,y:i}=Ee(this.ctx.c2kMatSch,{x:e.anchor_position?.x??e.center?.x??0,y:e.anchor_position?.y??e.center?.y??0}),n=e.anchor_side||"left",s={left:0,right:180,top:270,bottom:90}[n]||0,a={left:{horizontal:"left"},right:{horizontal:"right"},top:{vertical:"top"},bottom:{vertical:"bottom"}}[n]||{},g=this.createTextEffects(1.27,!1);return Object.keys(a).length>0&&(g.justify=new MJ(a)),new ZCt({value:A,at:[t,i,s],effects:g,uuid:crypto.randomUUID(),fieldsAutoplaced:!0})}createTextEffects(e,A=!1){const t=new uf;return t.size={height:e,width:e},new hf({font:t,hiddenText:A})}getOutput(){if(!this.ctx.kicadSch)throw new Error("kicadSch is not initialized");return this.ctx.kicadSch}},oni=class extends Nh{_step(){const{kicadSch:e,db:A}=this.ctx;if(!e)throw new Error("KicadSch instance not initialized in context");const t=A.schematic_trace.list();if(t.length===0){this.finished=!0;return}const i=[],n=[];for(const o of t){for(const s of o.edges){const r=this.createWireFromEdge(s);i.push(r)}for(const s of o.junctions){const r=this.createJunction(s);n.push(r)}}e.wires=i,e.junctions=n,this.finished=!0}createWireFromEdge(e){const A=new JCt;if(!this.ctx.c2kMatSch)throw new Error("Schematic transformation matrix not initialized in context");const t=Ee(this.ctx.c2kMatSch,{x:e.from.x,y:e.from.y}),i=Ee(this.ctx.c2kMatSch,{x:e.to.x,y:e.to.y}),n=t.x,o=t.y,s=i.x,r=i.y,a=new YC([new LQ(n,o),new LQ(s,r)]);A.points=a;const g=new qD;return g.width=0,g.type="default",A.stroke=g,A.uuid=crypto.randomUUID(),A}createJunction(e){if(!this.ctx.c2kMatSch)throw new Error("Schematic transformation matrix not initialized in context");const{x:A,y:t}=Ee(this.ctx.c2kMatSch,{x:e.x,y:e.y}),i=new TCt({at:[A,t],diameter:0});return i.uuid=crypto.randomUUID(),i}getOutput(){return this.ctx.kicadSch}},sni=class extends Nh{_step(){const{kicadSch:e}=this.ctx;if(!e)throw new Error("KicadSch instance not initialized in context");const A=new SyA,t=new zCt;t.value="/";const i=new XCt("1");t.pages=[i],A.paths=[t],e.sheetInstances=A,e.embeddedFonts=new y1(!1),this.finished=!0}getOutput(){return this.ctx.kicadSch}};function rni(e){const A=e.schematic_component.list(),t=e.schematic_trace.list();let i=1/0,n=1/0,o=-1/0,s=-1/0;for(const g of A){const c=g.size?.width??0,I=g.size?.height??0;i=Math.min(i,g.center.x-c/2),n=Math.min(n,g.center.y-I/2),o=Math.max(o,g.center.x+c/2),s=Math.max(s,g.center.y+I/2)}for(const g of t)for(const c of g.edges)i=Math.min(i,c.from.x,c.to.x),n=Math.min(n,c.from.y,c.to.y),o=Math.max(o,c.from.x,c.to.x),s=Math.max(s,c.from.y,c.to.y);i===1/0&&(i=0,n=0,o=0,s=0);const r=(i+o)/2,a=(n+s)/2;return{center:{x:r,y:a},bounds:{minX:i,minY:n,maxX:o,maxY:s}}}var mj=[{name:"A4",width:297,height:210},{name:"A3",width:420,height:297},{name:"A2",width:594,height:420},{name:"A1",width:841,height:594},{name:"A0",width:1189,height:841}];function ani(e,A,t=20){const i=e+2*t,n=A+2*t;for(let o=0;o<mj.length;o++){const s=mj[o];if(i<=s.width&&n<=s.height)return s}return mj[mj.length-1]}var mht=class{ctx;pipeline;currentStageIndex=0;finished=!1;get currentStage(){return this.pipeline[this.currentStageIndex]}constructor(e){const t=xa(e),{center:i,bounds:n}=rni(t),o=(n.maxX-n.minX)*15,s=(n.maxY-n.minY)*15,r=ani(o,s),a=r.width/2,g=r.height/2;this.ctx={db:t,circuitJson:e,kicadSch:new xyA({generator:"circuit-json-to-kicad",generatorVersion:"0.0.1"}),schematicPaperSize:r,c2kMatSch:bl(ir(a,g),fh(15,-15),ir(-i.x,-i.y))},this.pipeline=[new Tii(e,this.ctx),new eni(e,this.ctx),new ini(e,this.ctx),new nni(e,this.ctx),new oni(e,this.ctx),new sni(e,this.ctx)]}step(){if(!this.currentStage){this.finished=!0;return}this.currentStage.step(),this.currentStage.finished&&this.currentStageIndex++}runUntilFinished(){for(;!this.finished;)this.step()}getOutput(){return this.ctx.kicadSch}getOutputString(){return this.ctx.kicadSch.getString()}},gni=class extends Nh{_step(){const{kicadPcb:e,db:A}=this.ctx;if(!e)throw new Error("KicadPcb instance not initialized in context");const i=A.pcb_board?.list()?.[0]?.num_layers??2;this.ctx.numLayers=i,e.version=20241229;const n=new ij;n.size="A4",e.paper=n;const o=new FwA;o.thickness=1.6,e.general=o;const s=new kwA;s.padToMaskClearance=0,e.setup=s;const r=new GwA,a=[new Rl({index:0,name:"F.Cu",type:"signal"})];for(let g=1;g<i-1;g++)a.push(new Rl({index:g,name:`In${g}.Cu`,type:"signal"}));a.push(new Rl({index:31,name:"B.Cu",type:"signal"})),a.push(new Rl({index:32,name:"B.Adhes",type:"user"}),new Rl({index:33,name:"F.Adhes",type:"user"}),new Rl({index:34,name:"B.Paste",type:"user"}),new Rl({index:35,name:"F.Paste",type:"user"}),new Rl({index:36,name:"B.SilkS",type:"user"}),new Rl({index:37,name:"F.SilkS",type:"user"}),new Rl({index:38,name:"B.Mask",type:"user"}),new Rl({index:39,name:"F.Mask",type:"user"}),new Rl({index:40,name:"Dwgs.User",type:"user"}),new Rl({index:41,name:"Cmts.User",type:"user"}),new Rl({index:42,name:"Eco1.User",type:"user"}),new Rl({index:43,name:"Eco2.User",type:"user"}),new Rl({index:44,name:"Edge.Cuts",type:"user"}),new Rl({index:45,name:"Margin",type:"user"}),new Rl({index:46,name:"B.CrtYd",type:"user"}),new Rl({index:47,name:"F.CrtYd",type:"user"}),new Rl({index:48,name:"B.Fab",type:"user"}),new Rl({index:49,name:"F.Fab",type:"user"})),r.definitions=a,e.layers=r,this.finished=!0}getOutput(){return this.ctx.kicadPcb}},cni=class extends Nh{_step(){const{kicadPcb:e}=this.ctx;if(!e)throw new Error("KicadPcb instance not initialized in context");this.ctx.pcbNetMap=new Map;const A=new Map,t=this.ctx.db.source_net?.list()??[];for(const r of t){const a=r.subcircuit_connectivity_map_key||r.source_net_id;if(!a)continue;const g=r.name||r.source_net_id||"",c=g&&g.trim().length>0?g:a;A.set(a,c)}const i=this.ctx.db.source_trace?.list()??[];for(const r of i){let a=r.subcircuit_connectivity_map_key;if(!a&&r.connected_source_net_ids?.length)for(const g of r.connected_source_net_ids){const c=this.ctx.db.source_net?.get(g);if(c?.subcircuit_connectivity_map_key&&c.subcircuit_connectivity_map_key.length>0){a=c.subcircuit_connectivity_map_key;break}}if(a&&!A.has(a)){const g=r.display_name||r.source_trace_id||"",c=g&&g.trim().length>0?g:a;A.set(a,c)}}const n=Array.from(A.entries()).sort((r,a)=>r[0].localeCompare(a[0])),o=[];o.push(new fj(0,""));let s=1;for(const[r,a]of n){const g=new fj(s,a);o.push(g);const c={id:s,name:a};this.ctx.pcbNetMap.set(r,c),s++}e.nets=o,this.finished=!0}getOutput(){return this.ctx.kicadPcb}};function Ini(e){let A=0;for(let i=0;i<e.length;i++){const n=e.charCodeAt(i);A=(A<<5)-A+n,A=A&A}let t="";for(let i=0;i<4;i++){let n=A;for(let o=0;o<e.length;o++)n=(n<<5)-n+e.charCodeAt(o)+i*31,n=n&n;t+=Math.abs(n).toString(16).padStart(8,"0")}return t}function pf(e){const A=Ini(e);return`${A.slice(0,8)}-${A.slice(8,12)}-${A.slice(12,16)}-${A.slice(16,20)}-${A.slice(20,32)}`}function wj(e){const A=new uf;return e?.font?.size?A.size={width:Number(e.font.size.x),height:Number(e.font.size.y)}:A.size={width:1.27,height:1.27},e?.font?.thickness!==void 0?A.thickness=Number(e.font.thickness):A.thickness=.15,new hf({font:A})}function lni(e,A,t){if(A.properties){const i=[],n=A.properties.Reference;i.push(new OD({key:"Reference",value:n?.value??t,position:n?.at?[Number(n.at.x),Number(n.at.y),Number(n.at.rotation??0)]:[0,-3,0],layer:n?.layer??"F.SilkS",uuid:pf(`${t}-property-Reference`),effects:wj(n?.effects),hidden:n?.hide}));const o=A.properties.Value,s=o?.value??A.footprintName??"";i.push(new OD({key:"Value",value:s,position:o?.at?[Number(o.at.x),Number(o.at.y),Number(o.at.rotation??0)]:[0,3,0],layer:o?.layer??"F.Fab",uuid:pf(`${t}-property-Value`),effects:wj(o?.effects),hidden:o?.hide}));const r=A.properties.Datasheet;i.push(new OD({key:"Datasheet",value:r?.value??"",position:r?.at?[Number(r.at.x),Number(r.at.y),Number(r.at.rotation??0)]:[0,0,0],layer:r?.layer??"F.Fab",uuid:pf(`${t}-property-Datasheet`),effects:wj(r?.effects),hidden:r?.hide??!0}));const a=A.properties.Description;i.push(new OD({key:"Description",value:a?.value??"",position:a?.at?[Number(a.at.x),Number(a.at.y),Number(a.at.rotation??0)]:[0,0,0],layer:a?.layer??"F.Fab",uuid:pf(`${t}-property-Description`),effects:wj(a?.effects),hidden:a?.hide??!0})),e.properties=i}if(A.attributes&&(e.attr||(e.attr=new _yA),A.attributes.through_hole?e.attr.type="through_hole":A.attributes.smd&&(e.attr.type="smd"),A.attributes.exclude_from_pos_files!==void 0&&(e.attr.excludeFromPosFiles=A.attributes.exclude_from_pos_files),A.attributes.exclude_from_bom!==void 0&&(e.attr.excludeFromBom=A.attributes.exclude_from_bom)),A.footprintName&&(e.libraryLink=A.footprintName),A.layer&&(e.layer=A.layer),A.embeddedFonts!==void 0&&(e.embeddedFonts=new y1(A.embeddedFonts)),A.model){const i=new Bj(A.model.path);A.model.offset&&(i.offset={x:Number(A.model.offset.x),y:Number(A.model.offset.y),z:Number(A.model.offset.z)}),A.model.scale&&(i.scale={x:Number(A.model.scale.x),y:Number(A.model.scale.y),z:Number(A.model.scale.z)}),A.model.rotate&&(i.rotate={x:Number(A.model.rotate.x),y:Number(A.model.rotate.y),z:Number(A.model.rotate.z)});const n=e.models||[];e.models=[i,...n]}}function Bni(e,A){const t=[];for(const i of e){const n=i.center.x-A.x,o=-(i.center.y-A.y),r={top:"F.SilkS",bottom:"B.SilkS"}[i.layer]||i.layer||"F.SilkS",a=new lmA({center:{x:n,y:o},end:{x:n+i.radius,y:o},layer:r,stroke:new qD,fill:!1});a.stroke&&(a.stroke.width=i.stroke_width||.05,a.stroke.type="default"),t.push(a)}return t}function Cni(e,A){const t=[];for(const i of e){const n=i.center.x-A.x,o=-(i.center.y-A.y),r={top:"F.CrtYd",bottom:"B.CrtYd"}[i.layer]||"F.CrtYd",a=new lmA({center:{x:n,y:o},end:{x:n+i.radius,y:o},layer:r,stroke:new qD,fill:!1});a.stroke&&(a.stroke.width=.05,a.stroke.type="default"),t.push(a)}return t}function Qni(e,A){const t=[];for(const i of e){const n=i.center.x-A.x,o=-(i.center.y-A.y),s=i.width/2,r=i.height/2,g={top:"F.Fab",bottom:"B.Fab"}[i.layer]||i.layer||"F.Fab",c=new Ij({start:{x:n-s,y:o-r},end:{x:n+s,y:o+r},layer:g,stroke:new qD,fill:!1});c.stroke&&(c.stroke.width=i.stroke_width||.1,c.stroke.type="default"),t.push(c)}return t}function Eni(e,A){const t=[];for(const i of e){const n=i.center.x-A.x,o=-(i.center.y-A.y),s=i.width/2,r=i.height/2,a="F.Fab",g=new Ij({start:{x:n-s,y:o-r},end:{x:n+s,y:o+r},layer:a,stroke:new qD,fill:!1});g.stroke&&(g.stroke.width=i.stroke_width||.1,g.stroke.type="default"),t.push(g)}return t}function hni(e,A){const t=[];for(const i of e){const n=i.center.x-A.x,o=-(i.center.y-A.y),s=i.width/2,r=i.height/2,g={top:"F.CrtYd",bottom:"B.CrtYd"}[i.layer]||"F.CrtYd",c=new Ij({start:{x:n-s,y:o-r},end:{x:n+s,y:o+r},layer:g,stroke:new qD,fill:!1});c.stroke&&(c.stroke.width=.05,c.stroke.type="default"),t.push(c)}return t}function uni(e,A){const t=[];for(const i of e){if(!i.outline||i.outline.length<2)continue;const o={top:"F.CrtYd",bottom:"B.CrtYd"}[i.layer]||"F.CrtYd",s=i.outline.map(g=>{const c=g.x-A.x,I=-(g.y-A.y);return new LQ(c,I)}),r=new PQt;r.points=new YC(s),r.layer=o,r.fill=!1;const a=new qD;a.width=.05,a.type="default",r.stroke=a,t.push(r)}return t}function dni({textElement:e,componentCenter:A,componentRotation:t=0}){if(!e.text||!e.anchor_position)return null;const i=e.anchor_position.x-A.x,n=-(e.anchor_position.y-A.y),o=t!==0?Rm(t*Math.PI/180):Ru(),s=Ee(o,{x:i,y:n}),r={x:s.x,y:s.y},g={top:"F.SilkS",bottom:"B.SilkS"}[e.layer]||e.layer||"F.SilkS",c=(e.font_size||1)/1.5,I=new uf;I.size={width:c,height:c};const l=new hf({font:I}),B=e.ccw_rotation||0;return new emA({type:"user",text:e.text,position:{x:r.x,y:r.y,angle:B},layer:g,effects:l})}function pni(e,A,t,i){const n=[];for(const o of e){const s=dni({textElement:o,componentCenter:A,componentRotation:t});s&&(i&&o.text===i&&(s.type="reference"),n.push(s))}return n}function fni(e,A,t){const i=[];for(const n of e){const o=n.anchor_position.x-A.x,s=-(n.anchor_position.y-A.y),r=t!==0?Rm(t*Math.PI/180):Ru(),a=Ee(r,{x:o,y:s}),g=n.font_size||1,c=new uf;c.size={width:g,height:g};const I=new hf({font:c}),l=new emA({type:"user",text:n.text,position:{x:a.x,y:a.y,angle:0},layer:"F.Fab",effects:I});i.push(l)}return i}function yni(e,A){const t=[],i=e.model_step_url||e.model_wrl_url;if(!i)return t;const n=new Bj(i);if(e.position&&(n.offset={x:(e.position.x||0)-A.x,y:-((e.position.y||0)-A.y),z:e.position.z||0}),e.rotation&&(n.rotate={x:e.rotation.x||0,y:e.rotation.y||0,z:e.rotation.z||0}),e.model_unit_to_mm_scale_factor){const o=e.model_unit_to_mm_scale_factor;n.scale={x:o,y:o,z:o}}return t.push(n),t}function mni({pcbPad:e,componentCenter:A,padNumber:t,componentRotation:i=0,netInfo:n,componentId:o}){let s,r;if("x"in e&&"y"in e)s=e.x,r=e.y;else if("points"in e&&Array.isArray(e.points)){const u=e.points;s=u.reduce((d,f)=>d+f.x,0)/u.length,r=u.reduce((d,f)=>d+f.y,0)/u.length}else throw new Error("Pad must have either x/y coordinates or points array");const a=bl(i!==0?Rm(i*Math.PI/180):{a:1,b:0,c:0,d:1,e:0,f:0},fh(1,-1),ir(-A.x,-A.y)),g=Ee(a,{x:s,y:r}),I={top:"F.Cu",bottom:"B.Cu"}[e.layer]||"F.Cu";let l,B,C,Q;if(e.shape==="circle")l="circle",B=["radius"in e?e.radius*2:.5,"radius"in e?e.radius*2:.5];else if(e.shape==="polygon"&&"points"in e){const u=e.points,d=bl(fh(1,-1),ir(-s,-r)),f=u.map(w=>{const D=Ee(d,{x:w.x,y:w.y});return new LQ(D.x,D.y)}),m=new zyA;m.contours=[new YC(f)],m.width=0,m.filled=!0,Q=new bQt,Q.addGraphic(m),l="custom",C=new cQt,C.anchor="circle",B=[.2,.2]}else l="rect",B=["width"in e?e.width:.5,"height"in e?e.height:.5];const E=`pad:${o}:${t}:${g.x},${g.y}`,h=new cj({number:String(t),padType:"smd",shape:l,at:[g.x,g.y,0],size:B,layers:[`${I}`,`${I==="F.Cu"?"F":"B"}.Paste`,`${I==="F.Cu"?"F":"B"}.Mask`],uuid:pf(E)});return C&&(h.options=C),Q&&(h.primitives=Q),n&&(h.net=new qyA(n.id,n.name)),h}function wni(e,A,t,i,n,o){const s=[];let r=n;for(const a of e){const g=o(a.pcb_port_id),c=mni({pcbPad:a,componentCenter:A,padNumber:r,componentRotation:t,netInfo:g,componentId:i});s.push(c),r++}return{pads:s,nextPadNumber:r}}function Dni({platedHole:e,componentCenter:A,padNumber:t,componentRotation:i=0,netInfo:n,componentId:o}){if(!("x"in e&&"y"in e))return null;const s=e.x-A.x,r=-(e.y-A.y),a=i!==0?Rm(i*Math.PI/180):Ru(),g=Ee(a,{x:s,y:r});let c="circle",I,l,B=0;const C="hole_offset_x"in e||"hole_offset_y"in e;let Q;if(C){const u={x:e.hole_offset_x??0,y:e.hole_offset_y??0};(u.x!==0||u.y!==0)&&(Q=Ee(a,{x:-u.x,y:u.y}))}e.shape==="circle"?(c="circle",I=[e.outer_diameter,e.outer_diameter],l=new WD({diameter:e.hole_diameter,offset:Q})):e.shape==="pill"||e.shape==="oval"?(c="oval",I=[e.outer_width,e.outer_height],l=new WD({oval:!0,diameter:e.hole_width,width:e.hole_height,offset:Q})):e.shape==="pill_hole_with_rect_pad"?(c="rect",I=[e.rect_pad_width,e.rect_pad_height],l=new WD({oval:!0,diameter:e.hole_width,width:e.hole_height,offset:Q})):e.shape==="circular_hole_with_rect_pad"?(c="rect",I=[e.rect_pad_width,e.rect_pad_height],l=new WD({diameter:e.hole_diameter,offset:Q})):e.shape==="rotated_pill_hole_with_rect_pad"?(c="rect",I=[e.rect_pad_width,e.rect_pad_height],l=new WD({oval:!0,diameter:e.hole_width,width:e.hole_height,offset:Q}),B=e.rect_ccw_rotation||0):(c="circle",I=[1.6,1.6],l=new WD({diameter:.8,offset:Q}));const E=`thruhole:${o}:${t}:${g.x},${g.y}`,h=new cj({number:String(t),padType:"thru_hole",shape:c,at:[g.x,g.y,B],size:I,drill:l,layers:["*.Cu","*.Mask"],removeUnusedLayers:!1,uuid:pf(E)});return n&&(h.net=new qyA(n.id,n.name)),h}function Sni(e,A,t,i,n,o){const s=[];let r=n;for(const a of e){const g=o(a.pcb_port_id),c=Dni({platedHole:a,componentCenter:A,padNumber:r,componentRotation:t,netInfo:g,componentId:i});c&&(s.push(c),r++)}return{pads:s,nextPadNumber:r}}function bni({pcbHole:e,componentCenter:A,componentRotation:t=0}){if(!("x"in e&&"y"in e))return null;const i=e.x-A.x,n=-(e.y-A.y),o=t!==0?Rm(t*Math.PI/180):Ru(),s=Ee(o,{x:i,y:n});let r="circle",a,g;if(e.hole_shape==="circle"){r="circle";const c=e.hole_diameter;a=[c,c],g=new WD({diameter:c})}else if(e.hole_shape==="oval"){r="oval";const c=e.hole_width,I=e.hole_height;a=[c,I],g=new WD({oval:!0,diameter:c,width:I})}else{r="circle";const c="hole_diameter"in e?e.hole_diameter:1;a=[c,c],g=new WD({diameter:c})}return new cj({number:"",padType:"np_thru_hole",shape:r,at:[s.x,s.y,0],size:a,drill:g,layers:["*.Cu","*.Mask"],removeUnusedLayers:!1,uuid:crypto.randomUUID()})}function xni(e,A,t){const i=[];for(const n of e){const o=bni({pcbHole:n,componentCenter:A,componentRotation:t});o&&i.push(o)}return i}var _ni=class extends Nh{componentsProcessed=0;pcbComponents=[];getNetInfoForPcbPort(e){if(!e)return;const A=this.ctx.db.pcb_port?.get(e);if(!A)return;const t=A.source_port_id;if(!t)return;const i=this.ctx.db.source_port?.get(t);if(!i)return;const n=i.subcircuit_connectivity_map_key;if(n)return this.ctx.pcbNetMap?.get(n)}getCadComponentForPcbComponent(e){return(this.ctx.db.cad_component?.list()||[]).find(t=>t.pcb_component_id===e)}constructor(e,A){super(e,A),this.pcbComponents=this.ctx.db.pcb_component.list()}_step(){const{kicadPcb:e,c2kMatPcb:A}=this.ctx;if(!e)throw new Error("KicadPcb instance not initialized in context");if(!A)throw new Error("PCB transformation matrix not initialized in context");if(this.componentsProcessed>=this.pcbComponents.length){this.finished=!0;return}const t=this.pcbComponents[this.componentsProcessed],i=t.source_component_id?this.ctx.db.source_component.get(t.source_component_id):null,n=this.getCadComponentForPcbComponent(t.pcb_component_id),o=i?RG(i,n):"Unknown",s=Ee(A,{x:t.center.x,y:t.center.y}),r=`footprint:${t.pcb_component_id}:${s.x},${s.y}`,a=new xmA({libraryLink:`tscircuit:${o}`,layer:"F.Cu",at:[s.x,s.y,t.rotation||0],uuid:pf(r)}),g=a.fpTexts,c=this.ctx.db.pcb_silkscreen_text?.list().filter(O=>O.pcb_component_id===t.pcb_component_id)||[];g.push(...pni(c,t.center,t.rotation||0,i?.name));const I=this.ctx.db.pcb_note_text?.list().filter(O=>O.pcb_component_id===t.pcb_component_id)||[];g.push(...fni(I,t.center,t.rotation||0)),a.fpTexts=g;const l=a.fpPads,B=O=>this.getNetInfoForPcbPort(O),C=this.ctx.db.pcb_smtpad?.list().filter(O=>O.pcb_component_id===t.pcb_component_id)||[],{pads:Q,nextPadNumber:E}=wni(C,t.center,t.rotation||0,t.pcb_component_id,1,B);l.push(...Q);const h=this.ctx.db.pcb_plated_hole?.list().filter(O=>O.pcb_component_id===t.pcb_component_id)||[],{pads:u}=Sni(h,t.center,t.rotation||0,t.pcb_component_id,E,B);l.push(...u);const d=this.ctx.db.pcb_hole?.list().filter(O=>O.subcircuit_id===t.subcircuit_id)||[],f=xni(d,t.center,t.rotation||0);l.push(...f),a.fpPads=l;const m=this.ctx.db.pcb_silkscreen_circle?.list().filter(O=>O.pcb_component_id===t.pcb_component_id)||[],w=a.fpCircles??[];w.push(...Bni(m,t.center));const D=this.ctx.db.pcb_courtyard_circle?.list().filter(O=>O.pcb_component_id===t.pcb_component_id)||[];w.push(...Cni(D,t.center)),a.fpCircles=w;const b=this.ctx.db.pcb_fabrication_note_rect?.list().filter(O=>O.pcb_component_id===t.pcb_component_id)||[],k=a.fpRects??[];k.push(...Qni(b,t.center));const x=this.ctx.db.pcb_note_rect?.list().filter(O=>O.pcb_component_id===t.pcb_component_id)||[];k.push(...Eni(x,t.center));const N=this.ctx.db.pcb_courtyard_rect?.list().filter(O=>O.pcb_component_id===t.pcb_component_id)||[];k.push(...hni(N,t.center)),a.fpRects=k;const R=this.ctx.db.pcb_courtyard_outline?.list().filter(O=>O.pcb_component_id===t.pcb_component_id)||[],U=uni(R,t.center);if(U.length>0&&(a.fpPolys=U),n){const O=yni(n,t.center);O.length>0&&(a.models=O)}const T=t.metadata?.kicad_footprint;T&&i?.name&&lni(a,T,i.name);const Y=e.footprints;Y.push(a),e.footprints=Y,this.componentsProcessed++}getOutput(){return this.ctx.kicadPcb}},kni={top:"F.Cu",bottom:"B.Cu",inner1:"In1.Cu",inner2:"In2.Cu",inner3:"In3.Cu",inner4:"In4.Cu",inner5:"In5.Cu",inner6:"In6.Cu"};function Fni(e){return e&&(kni[e]||e)||"F.Cu"}function Gni(e){const A=["F.Cu"];for(let t=1;t<e-1;t++)A.push(`In${t}.Cu`);return A.push("B.Cu"),A}var Mni=class extends Nh{tracesProcessed=0;pcbTraces=[];constructor(e,A){super(e,A),this.pcbTraces=this.ctx.db.pcb_trace.list()}_step(){const{kicadPcb:e,c2kMatPcb:A,pcbNetMap:t}=this.ctx;if(!e)throw new Error("KicadPcb instance not initialized in context");if(!A)throw new Error("PCB transformation matrix not initialized in context");if(this.tracesProcessed>=this.pcbTraces.length){this.finished=!0;return}const i=this.pcbTraces[this.tracesProcessed];if(!i.route||i.route.length<2){this.tracesProcessed++;return}let n=i.route[0]?.layer;for(let o=0;o<i.route.length-1;o++){const s=i.route[o],r=i.route[o+1],a=Ee(A,{x:s.x,y:s.y}),g=Ee(A,{x:r.x,y:r.y});let c;if(t){let E=i.subcircuit_connectivity_map_key;if(!E&&i.source_trace_id){const h=this.ctx.db.source_trace?.get(i.source_trace_id);if(h&&(E=h.subcircuit_connectivity_map_key,!E&&h.connected_source_net_ids?.length))for(const u of h.connected_source_net_ids){const d=this.ctx.db.source_net?.get(u);if(d?.subcircuit_connectivity_map_key){E=d.subcircuit_connectivity_map_key;break}}}if(!E&&typeof i.connection_name=="string"){const h=this.ctx.db.source_net?.get(i.connection_name);h?.subcircuit_connectivity_map_key&&(E=h.subcircuit_connectivity_map_key)}E&&(c=t.get(E))}const I=s.layer??r.layer??n,l=Fni(I),B=`segment:${a.x},${a.y}:${g.x},${g.y}:${l}:${c?.id??0}`,C=new JmA({start:{x:a.x,y:a.y},end:{x:g.x,y:g.y},layer:l,width:i.width||.25,net:new uj(c?.id??0),uuid:pf(B)}),Q=e.segments;Q.push(C),e.segments=Q,s.layer&&(n=s.layer),r.layer&&(n=r.layer)}this.tracesProcessed++}getOutput(){return this.ctx.kicadPcb}},Rni=class extends Nh{viasProcessed=0;pcbVias=[];constructor(e,A){super(e,A),this.pcbVias=this.ctx.db.pcb_via?.list()||[]}_step(){const{kicadPcb:e,c2kMatPcb:A,pcbNetMap:t}=this.ctx;if(!e)throw new Error("KicadPcb instance not initialized in context");if(!A)throw new Error("PCB transformation matrix not initialized in context");if(this.viasProcessed>=this.pcbVias.length){this.finished=!0;return}const i=this.pcbVias[this.viasProcessed],n=Ee(A,{x:i.x,y:i.y});let o;if(t){let I=i.subcircuit_connectivity_map_key;if(!I&&i.pcb_trace_id){const l=this.ctx.db.pcb_trace?.get(i.pcb_trace_id);if(l&&("subcircuit_connectivity_map_key"in l&&(I=l.subcircuit_connectivity_map_key),!I&&l.source_trace_id)){const B=this.ctx.db.source_trace?.get(l.source_trace_id);if(B&&("subcircuit_connectivity_map_key"in B&&(I=B.subcircuit_connectivity_map_key),!I&&B.connected_source_net_ids?.length))for(const C of B.connected_source_net_ids){const Q=this.ctx.db.source_net?.get(C);if(Q?.subcircuit_connectivity_map_key){I=Q.subcircuit_connectivity_map_key;break}}}}if(!I&&i.connection_name){const l=this.ctx.db.source_net?.get(i.connection_name);l?.subcircuit_connectivity_map_key&&(I=l.subcircuit_connectivity_map_key)}I&&(o=t.get(I))}const s=this.ctx.numLayers??2,r=i.layers?i.layers.map(I=>I==="top"?"F.Cu":I==="bottom"?"B.Cu":`In${I.replace("inner","")}.Cu`):Gni(s),a=`via:${n.x},${n.y}:${i.outer_diameter||.8}:${i.hole_diameter||.4}:${o?.id??0}`,g=new LwA({at:[n.x,n.y],size:i.outer_diameter||.8,drill:i.hole_diameter||.4,layers:r,net:new vwA(o?.id??0),uuid:pf(a)}),c=e.vias;c.push(g),e.vias=c,this.viasProcessed++}getOutput(){return this.ctx.kicadPcb}};function Nni({textElement:e,c2kMatPcb:A}){if(!e.text||!e.anchor_position)return null;const t=Ee(A,{x:e.anchor_position.x,y:e.anchor_position.y}),n={top:"F.Fab",bottom:"B.Fab"}[e.layer]||e.layer||"F.Fab",o=(e.font_size||1)/1.5,s=new uf;s.size={width:o,height:o};const r=new MJ,a=e.anchor_alignment||"center";switch(a){case"top_left":r.horizontal="left",r.vertical="top";break;case"top_right":r.horizontal="right",r.vertical="top";break;case"bottom_left":r.horizontal="left",r.vertical="bottom";break;case"bottom_right":r.horizontal="right",r.vertical="bottom";break}const g=new hf({font:s});a!=="center"&&(g.justify=r);const c=new Wg([t.x,t.y,0]),I=new hj({text:e.text,layer:n,effects:g});return I.position=c,I}function vni({textElement:e,c2kMatPcb:A}){if(!e.text||!e.anchor_position)return null;const t=Ee(A,{x:e.anchor_position.x,y:e.anchor_position.y}),n={top:"F.SilkS",bottom:"B.SilkS"}[e.layer]||e.layer||"F.SilkS",o=(e.font_size||1)/1.5,s=new uf;s.size={width:o,height:o};const r=new MJ,a=e.anchor_alignment||"center";switch(a){case"top_left":r.horizontal="left",r.vertical="top";break;case"top_right":r.horizontal="right",r.vertical="top";break;case"bottom_left":r.horizontal="left",r.vertical="bottom";break;case"bottom_right":r.horizontal="right",r.vertical="bottom";break}const g=new hf({font:s});a!=="center"&&(g.justify=r);const c=e.ccw_rotation||0,I=new Wg([t.x,t.y,c]),l=new hj({text:e.text,layer:n,effects:g});return l.position=I,l}var Lni=class extends Nh{_step(){const{kicadPcb:e,c2kMatPcb:A}=this.ctx;if(!e)throw new Error("KicadPcb instance not initialized in context");if(!A)throw new Error("PCB transformation matrix not initialized in context");const t=this.ctx.db.pcb_silkscreen_path?.list()||[];for(const s of t)if(!(!s.route||s.route.length<2))for(let r=0;r<s.route.length-1;r++){const a=s.route[r],g=s.route[r+1];if(!a||!g)continue;const c=Ee(A,{x:a.x,y:a.y}),I=Ee(A,{x:g.x,y:g.y}),B={top:"F.SilkS",bottom:"B.SilkS"}[s.layer]||s.layer||"F.SilkS",C=new Ej({start:{x:c.x,y:c.y},end:{x:I.x,y:I.y},layer:B,width:s.stroke_width||.15}),Q=e.graphicLines;Q.push(C),e.graphicLines=Q}const i=this.ctx.db.pcb_silkscreen_text?.list().filter(s=>!s.pcb_component_id)||[];for(const s of i){const r=vni({textElement:s,c2kMatPcb:A});if(r){const a=e.graphicTexts;a.push(r),e.graphicTexts=a}}const n=this.ctx.db.pcb_fabrication_note_text?.list()||[];for(const s of n){const r=Nni({textElement:s,c2kMatPcb:A});if(r){const a=e.graphicTexts;a.push(r),e.graphicTexts=a}}const o=this.ctx.db.pcb_board?.list()||[];if(o.length>0){const s=o[0];if(!s){this.finished=!0;return}let r;if(s.outline&&s.outline.length>0)r=s.outline;else{const g=s.width?s.width/2:0,c=s.height?s.height/2:0;r=[{x:s.center.x-g,y:s.center.y-c},{x:s.center.x+g,y:s.center.y-c},{x:s.center.x+g,y:s.center.y+c},{x:s.center.x-g,y:s.center.y+c}]}const a=r.map(g=>Ee(A,g));for(let g=0;g<a.length;g++){const c=a[g],I=a[(g+1)%a.length];if(!c||!I)continue;const l=new Ej({start:{x:c.x,y:c.y},end:{x:I.x,y:I.y},layer:"Edge.Cuts",width:.1}),B=e.graphicLines;B.push(l),e.graphicLines=B}}this.finished=!0}getOutput(){return this.ctx.kicadPcb}},wht=class{ctx;pipeline;currentStageIndex=0;finished=!1;get currentStage(){return this.pipeline[this.currentStageIndex]}constructor(e){this.ctx={db:xa(e),circuitJson:e,kicadPcb:new UwA({generator:"circuit-json-to-kicad",generatorVersion:"0.0.1"}),c2kMatPcb:bl(ir(100,100),fh(1,-1))},this.pipeline=[new gni(e,this.ctx),new cni(e,this.ctx),new _ni(e,this.ctx),new Mni(e,this.ctx),new Rni(e,this.ctx),new Lni(e,this.ctx)]}step(){if(!this.currentStage){this.finished=!0;return}this.currentStage.step(),this.currentStage.finished&&this.currentStageIndex++}runUntilFinished(){for(;!this.finished;)this.step()}getOutput(){return this.ctx.kicadPcb}getOutputString(){return this.ctx.kicadPcb.getString()}},Uni=class{ctx;project;constructor(e,A={}){const t=A.projectName??e?.project?.name??"circuit-json-project",i=A.schematicFilename??`${t}.kicad_sch`,n=A.pcbFilename??`${t}.kicad_pcb`,o=new Date().toISOString();this.ctx={db:xa(e),circuitJson:e},this.project={version:1,head:{generator:"circuit-json-to-kicad",generator_version:"0.0.1",project_name:t,created:o,modified:o},meta:{version:1},text_variables:{},libraries:{pinned_symbol_libs:[],pinned_footprint_libs:[]},boards:[],cvpcb:{meta:{version:0}},erc:{meta:{version:0},erc_exclusions:[]},net_settings:{meta:{version:1},last_net_id:0,classes:[]},pcbnew:{page_layout_descr_file:"",last_paths:{}},schematic:{meta:{version:1},page_layout_descr_file:"",last_opened_files:[i]},board:{meta:{version:1},last_opened_board:n},sheets:[[Math.random().toString(36).substring(2,15),"Root"]]}}runUntilFinished(){}getOutput(){return this.project}getOutputString(){return`${JSON.stringify(this.project,null,2)}
5829
5829
  `}},Hni=class extends Nh{_step(){const e=new mht(this.ctx.circuitJson);e.runUntilFinished(),this.ctx.kicadSchString=e.getOutputString();const A=new wht(this.ctx.circuitJson);A.runUntilFinished(),this.ctx.kicadPcbString=A.getOutputString(),this.finished=!0}getOutput(){return this.ctx.libraryOutput}},Yni=class extends Nh{isCustomSymbol(e){return e?.startsWith("Custom:")??!1}_step(){const e=this.ctx.kicadSchString,A=this.ctx.fpLibraryName??"tscircuit";if(!e)throw new Error("Schematic content not available. Run GenerateKicadSchAndPcbStage first.");const t=new Map;try{const n=hht(e).find(r=>r instanceof xyA);if(!n){this.ctx.symbolEntries=[],this.finished=!0;return}const o=n.libSymbols;if(!o){this.ctx.symbolEntries=[],this.finished=!0;return}const s=o.symbols??[];for(const r of s){const a=this.isCustomSymbol(r.libraryId),g=this.sanitizeSymbolName(r.libraryId);t.has(g)||(r.libraryId=g,this.updateFootprintProperty(r,A),a||this.snapPinPositionsToGrid(r),t.set(g,{symbolName:g,symbol:r,isBuiltin:!a}))}}catch(i){console.warn("Failed to parse schematic for symbol extraction:",i)}this.ctx.symbolEntries=Array.from(t.values()),this.finished=!0}updateFootprintProperty(e,A){const t=e.properties??[];for(const i of t)if(i.key==="Footprint"&&i.value){const n=i.value.split(":");n.length>1?i.value=`${A}:${n[1]}`:i.value.trim()&&(i.value=`${A}:${i.value}`)}}sanitizeSymbolName(e){if(!e)return"symbol";const A=e.split(":");return(A.length>1?A[1]:A[0])?.replace(/[\\\/]/g,"-").trim()||"symbol"}snapPinPositionsToGrid(e){for(const t of e.subSymbols??[]){for(const i of t.pins??[])i.at&&(i.at.x=Math.round(i.at.x/1.27)*1.27,i.at.y=Math.round(i.at.y/1.27)*1.27);for(const i of t.polylines??[])if(i.points?.points)for(const n of i.points.points)"x"in n&&"y"in n&&(n.x=Math.round(n.x/1.27)*1.27,n.y=Math.round(n.y/1.27)*1.27)}}getOutput(){return this.ctx.libraryOutput}},Jni=20240108,Tni="pcbnew",Kni="8.0";function Pni(e){const A=e.split(/[/\\]/);return A[A.length-1]||e}var qni=class extends Nh{findCustomFootprintNames(){const e=new Set,A=this.ctx.db.cad_component?.list()??[],t=this.ctx.db.source_component;for(const i of A)if(!i.footprinter_string){const n=i.source_component_id?t?.get(i.source_component_id):null;if(n){const o=RG(n,i);e.add(o);const s=this.ctx.circuitJson.find(r=>r.type==="pcb_component"&&r.source_component_id===i.source_component_id);s&&s.type==="pcb_component"&&s.metadata?.kicad_footprint?.footprintName&&e.add(s.metadata.kicad_footprint.footprintName)}}return e}_step(){const e=this.ctx.kicadPcbString,A=this.ctx.fpLibraryName??"tscircuit";if(!e)throw new Error("PCB content not available. Run GenerateKicadSchAndPcbStage first.");const t=this.findCustomFootprintNames(),i=new Map;try{const o=hht(e).find(r=>r instanceof UwA);if(!o){this.ctx.footprintEntries=[],this.finished=!0;return}const s=o.footprints??[];for(const r of s){const a=this.sanitizeFootprint({footprint:r,fpLibraryName:A,customFootprintNames:t});i.has(a.footprintName)||i.set(a.footprintName,a)}}catch(n){console.warn("Failed to parse PCB for footprint extraction:",n)}this.ctx.footprintEntries=Array.from(i.values()),this.finished=!0}sanitizeFootprint({footprint:e,fpLibraryName:A,customFootprintNames:t}){const n=(e.libraryLink??"footprint").split(":"),o=(n.length>1?n[1]:n[0])?.replace(/[\\\/]/g,"-").trim()||"footprint",s=!t.has(o);if(e.libraryLink=o,e.position=Wg.from([0,0,0]),e.locked=!1,e.placed=!1,e.version=Jni,e.generator=Tni,e.generatorVersion=Kni,e.descr||(e.descr=""),e.tags||(e.tags=""),e.embeddedFonts||(e.embeddedFonts=new y1(!1)),!e.attr){const d=new _yA,f=(e.fpPads??[]).map(m=>m.padType);f.some(m=>m.includes("thru_hole"))?d.type="through_hole":f.some(m=>m.includes("smd"))&&(d.type="smd"),e.attr=d}e.uuid=void 0,e.path=void 0,e.sheetfile=void 0,e.sheetname=void 0;const r=new uf;r.size={width:1.27,height:1.27},r.thickness=.15;const a=new hf({font:r}),g=e.fpPads??[];let c=0,I=0;for(const d of g){const f=d.at,m=d.size;if(f&&m){const w=f.y??0,D=m.height??0,b=w-D/2,k=w+D/2;c=Math.min(c,b),I=Math.max(I,k)}}const l=c-.5,B=I+.5;e.properties=[new OD({key:"Reference",value:"REF**",position:[0,l,0],layer:"F.SilkS",uuid:pf(`${o}-property-Reference`),effects:a}),new OD({key:"Value",value:"Val**",position:[0,B,0],layer:"F.Fab",uuid:pf(`${o}-property-Value`),effects:a}),new OD({key:"Datasheet",value:"",position:[0,0,0],layer:"F.Fab",hidden:!0,uuid:pf(`${o}-property-Datasheet`),effects:a}),new OD({key:"Description",value:"",position:[0,0,0],layer:"F.Fab",hidden:!0,uuid:pf(`${o}-property-Description`),effects:a})];const C=e.fpTexts??[];for(const d of C)d.uuid=void 0,d.type==="reference"?d.text="REF**":d.type==="value"&&d.text.trim().length===0&&(d.text=o);e.fpTexts=C;const Q=e.fpPads??[];for(let d=0;d<Q.length;d++){const f=Q[d];f&&(f.uuid=pf(`${o}-pad-${f.number??d}`),f.net=void 0)}e.fpPads=Q;const E=e.models??[],h=[],u=[];for(const d of E)if(d.path){const f=Pni(d.path),m=`../../3dmodels/${A}.3dshapes/${f}`,w=new Bj(m);d.offset&&(w.offset=d.offset),d.scale&&(w.scale=d.scale),d.rotate&&(w.rotate=d.rotate),h.push(w),u.push(d.path)}return e.models=h,{footprintName:o,kicadModString:e.getString(),model3dSourcePaths:u,isBuiltin:s}}getOutput(){return this.ctx.libraryOutput}},Oni=20211014,Wni="circuit-json-to-kicad",Zni=class extends Nh{_step(){const e=this.ctx.symbolEntries??[],A=this.generateSymbolLibrary(e);this.ctx.libraryOutput||(this.ctx.libraryOutput={kicadSymString:"",symbols:[],footprints:[],fpLibTableString:"",symLibTableString:"",model3dSourcePaths:[]}),this.ctx.libraryOutput.kicadSymString=A,this.finished=!0}generateSymbolLibrary(e){return new LCt({version:Oni,generator:Wni,symbols:e.map(t=>t.symbol)}).getString()}getOutput(){return this.ctx.libraryOutput}},Vni=class extends Nh{_step(){const e=this.ctx.libraryName??"tscircuit",A=this.ctx.fpLibraryName??"tscircuit",t=this.ctx.footprintEntries??[],i=this.ctx.symbolEntries??[],n=new Set;for(const r of t)for(const a of r.model3dSourcePaths)n.add(a);const o=this.generateFpLibTable(A),s=this.generateSymLibTable(e);this.ctx.libraryOutput||(this.ctx.libraryOutput={kicadSymString:"",symbols:[],footprints:[],fpLibTableString:"",symLibTableString:"",model3dSourcePaths:[]}),this.ctx.libraryOutput.symbols=i,this.ctx.libraryOutput.footprints=t,this.ctx.libraryOutput.fpLibTableString=o,this.ctx.libraryOutput.symLibTableString=s,this.ctx.libraryOutput.model3dSourcePaths=Array.from(n),this.finished=!0}generateFpLibTable(e){return`(fp_lib_table
5830
5830
  (version 7)
5831
5831
  (lib (name "${e}") (type "KiCad") (uri "\${KIPRJMOD}/${e}.pretty") (options "") (descr "Generated by circuit-json-to-kicad"))