tscircuit 0.0.1214 → 0.0.1215

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.
@@ -5619,7 +5619,7 @@ test("${g} should solve problem correctly", () => {
5619
5619
  // Add more specific assertions based on expected output
5620
5620
  // expect(solver.netLabelPlacementSolver!.netLabelPlacements).toMatchInlineSnapshot()
5621
5621
  })
5622
- `,c=new Blob([I],{type:"text/plain"}),B=URL.createObjectURL(c),l=document.createElement("a");l.href=B,l.download=`${g}.test.ts`,l.click(),URL.revokeObjectURL(B)}catch(a){alert(`Error generating test.ts for ${t.constructor.name}: ${a instanceof Error?a.message:String(a)}`)}i(!1)};return O.jsxs("div",{className:`relative ${A}`,ref:o,children:[O.jsx("button",{className:"px-2 py-1 rounded text-xs cursor-pointer",onClick:()=>i(!e),title:`Download options for ${t.constructor.name}`,children:t.constructor.name}),e&&O.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:[O.jsx("button",{className:"w-full text-left px-3 py-2 hover:bg-gray-100 text-xs",onClick:n,children:"Download JSON"}),O.jsx("button",{className:"w-full text-left px-3 py-2 hover:bg-gray-100 text-xs",onClick:s,children:"Download page.tsx"}),O.jsx("button",{className:"w-full text-left px-3 py-2 hover:bg-gray-100 text-xs",onClick:r,children:"Download test.ts"})]})]})},Aie=t=>t.activeSubSolver?[t,...Aie(t.activeSubSolver)]:[t],MKt=({solver:t})=>{const A=Aie(t);return O.jsx("div",{className:"flex gap-1 items-center text-sm pt-1",children:A.map((e,i)=>O.jsxs("div",{className:"flex items-center",children:[i>0&&O.jsx("span",{className:"text-gray-400 mx-1",children:"→"}),O.jsx(RKt,{solver:e})]},e.constructor.name))})},NKt=({solver:t,triggerRender:A,animationSpeed:e=25,onSolverStarted:i,onSolverCompleted:o})=>{const[n,s]=j.useReducer(Q=>!Q,!1),r=j.useRef(void 0),a=()=>{!t.solved&&!t.failed&&(t.step(),A())},g=()=>{!t.solved&&!t.failed&&(i&&i(t),t.solve(),A(),o&&o(t))},I=()=>{n?(r.current&&(clearInterval(r.current),r.current=void 0),s()):(s(),r.current=setInterval(()=>{if(t.solved||t.failed){r.current&&(clearInterval(r.current),r.current=void 0),s(),A(),o&&t.solved&&o(t);return}t.step(),A()},e))},c=()=>{const Q=t;if(Q.getCurrentPhase&&!t.solved&&!t.failed){const E=Q.getCurrentPhase();for(;Q.getCurrentPhase()===E&&!t.solved&&!t.failed;)t.step();A()}},B=()=>{if(t.solved||t.failed||n)return;const Q=window.prompt("Step until which iteration?",`${t.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(;t.iterations<E&&!t.solved&&!t.failed;)t.step();A(),t.solved&&o&&o(t)};j.useEffect(()=>()=>{r.current&&clearInterval(r.current)},[]),j.useEffect(()=>{(t.solved||t.failed)&&n&&(r.current&&(clearInterval(r.current),r.current=void 0),s())},[t.solved,t.failed,n]);const l=t.getCurrentPhase!==void 0,C=l?t.getCurrentPhase():null;return O.jsxs("div",{className:"space-y-2 p-2 border-b",children:[O.jsx("div",{className:"flex items-center",children:O.jsx(MKt,{solver:t})}),O.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[O.jsx("button",{onClick:a,disabled:t.solved||t.failed||n,className:"bg-blue-500 hover:bg-blue-600 disabled:bg-gray-300 text-white px-3 py-1 rounded text-sm",children:"Step"}),O.jsx("button",{onClick:g,disabled:t.solved||t.failed||n,className:"bg-green-500 hover:bg-green-600 disabled:bg-gray-300 text-white px-3 py-1 rounded text-sm",children:"Solve"}),O.jsx("button",{onClick:I,disabled:t.solved||t.failed,className:`px-3 py-1 rounded text-white text-sm ${n?"bg-red-500 hover:bg-red-600":"bg-yellow-500 hover:bg-yellow-600"} disabled:bg-gray-300`,children:n?"Stop":"Animate"}),O.jsx("button",{onClick:B,disabled:t.solved||t.failed||n,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"}),l&&O.jsx("button",{onClick:c,disabled:t.solved||t.failed||n,className:"bg-purple-500 hover:bg-purple-600 disabled:bg-gray-300 text-white px-3 py-1 rounded text-sm",children:"Next Stage"}),O.jsxs("div",{className:"text-sm text-gray-600",children:["Iterations: ",t.iterations]}),t.timeToSolve!==void 0&&O.jsxs("div",{className:"text-sm text-gray-600",children:["Time: ",(t.timeToSolve/1e3).toFixed(3),"s"]}),C&&O.jsxs("div",{className:"text-sm text-gray-600",children:["Phase: ",O.jsx("span",{className:"font-medium",children:C})]}),t.solved&&O.jsx("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded text-sm",children:"Solved"}),t.failed&&O.jsx("div",{className:"px-2 py-1 bg-red-100 text-red-800 rounded text-sm",children:"Failed"})]}),t.error&&O.jsxs("div",{className:"text-red-600 text-sm",children:["Error: ",t.error]})]})},_Kt=(t,A,e)=>{const i=t.currentPipelineStepIndex;return A<i?"Completed":A===i&&t.activeSubSolver?t.activeSubSolver.failed?"Failed":"In Progress":"Not Started"},vKt=(t,A)=>{const i=t.pipelineDef[A].solverName,o=_Kt(t,A),n=t[i],s=t.firstIterationOfPhase?.[i]??null,r=t.iterations;let a=0;if(o==="Completed"){const B=t.pipelineDef[A+1],l=B?t.firstIterationOfPhase?.[B.solverName]:void 0;l!==void 0&&s!==null?a=l-s:s!==null&&(a=r-s)}else o==="In Progress"&&s!==null&&(a=r-s);const g=t.timeSpentOnPhase?.[i]??0;let I=0;o==="Completed"?I=1:o==="In Progress"&&n&&(I=n.progress??0);const c=n?.stats??null;return{index:A,name:i,status:o,firstIteration:s,iterations:a,progress:I,timeSpent:g,stats:c&&Object.keys(c).length>0?c:null,solverInstance:n??null}},UKt=({status:t})=>{const A={"Not Started":"text-blue-600","In Progress":"text-yellow-600",Completed:"text-green-600",Failed:"text-red-600"};return O.jsx("span",{className:`font-medium ${A[t]}`,children:t})},LKt=({progress:t})=>{if(t===0)return null;const A=Math.round(t*100);return O.jsxs("div",{className:"flex items-center gap-2",children:[O.jsx("div",{className:"w-20 h-2 bg-gray-200 rounded overflow-hidden",children:O.jsx("div",{className:"h-full bg-blue-500 transition-all duration-200",style:{width:`${A}%`}})}),O.jsxs("span",{className:"text-xs text-gray-500",children:[A,"%"]})]})},HKt=t=>Object.entries(t).map(([A,e])=>`${A}: ${e}`).join(", "),YKt=({stats:t})=>{if(!t||Object.keys(t).length===0)return O.jsx("span",{children:"-"});const A=Object.entries(t),e=HKt(t);return O.jsxs("details",{className:"cursor-pointer",children:[O.jsx("summary",{className:"whitespace-nowrap overflow-hidden text-ellipsis max-w-[200px]",children:e}),O.jsx("div",{className:"mt-1 text-xs",children:A.map(([i,o])=>O.jsxs("div",{children:[i,": ",String(o)]},i))})]})},IuA=t=>{if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(IuA);const A={};for(const[e,i]of Object.entries(t))e.startsWith("_")||(A[e]=IuA(i));return A},JKt=(t,A)=>{try{if(typeof t.getConstructorParams!="function"){alert(`getConstructorParams() is not implemented for ${A}`);return}const e=IuA(t.getConstructorParams()),i=new Blob([JSON.stringify(e,null,2)],{type:"application/json"}),o=URL.createObjectURL(i),n=document.createElement("a");n.href=o,n.download=`${A}_input.json`,n.click(),URL.revokeObjectURL(o)}catch(e){alert(`Error downloading input for ${A}: ${e instanceof Error?e.message:String(e)}`)}},TKt=({solver:t,onStepUntilPhase:A,onDownloadInput:e})=>{const i=t.pipelineDef.map((r,a)=>vKt(t,a)),o=r=>{A?.(r)},n=r=>{r.solverInstance&&(e?e(r.solverInstance,r.name):JKt(r.solverInstance,r.name))},s=r=>`${(r/1e3).toFixed(2)}s`;return O.jsxs("div",{className:"border-t border-gray-200",children:[O.jsx("div",{className:"px-4 py-2 bg-gray-50 border-b border-gray-200",children:O.jsx("h3",{className:"text-sm font-semibold text-gray-700",children:"Pipeline Steps"})}),O.jsx("div",{className:"overflow-x-auto",children:O.jsxs("table",{className:"w-full text-sm",children:[O.jsx("thead",{children:O.jsxs("tr",{className:"bg-gray-50 border-b border-gray-200",children:[O.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Step"}),O.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Status"}),O.jsxs("th",{className:"px-4 py-2 text-center font-semibold text-gray-700",children:["i",O.jsx("sub",{children:"0"})]}),O.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Iterations"}),O.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Progress"}),O.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Time"}),O.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Stats"}),O.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Input"})]})}),O.jsx("tbody",{children:i.map(r=>O.jsxs("tr",{className:`border-b border-gray-100 ${r.status==="In Progress"?"bg-yellow-50":""}`,children:[O.jsx("td",{className:"px-4 py-2",children:O.jsxs("div",{className:"flex items-center gap-2",children:[O.jsx("span",{className:"text-gray-400 w-6",children:String(r.index+1).padStart(2,"0")}),O.jsx("button",{onClick:()=>o(r.name),disabled:r.status==="Completed"||t.solved||t.failed,className:"text-blue-500 hover:text-blue-700 disabled:text-gray-300 disabled:cursor-not-allowed",title:`Step until ${r.name} completes`,children:O.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",className:"w-4 h-4",children:O.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"})})}),O.jsx("span",{className:"font-medium text-gray-900",children:r.name})]})}),O.jsx("td",{className:"px-4 py-2",children:O.jsx(UKt,{status:r.status})}),O.jsx("td",{className:"px-4 py-2 text-center text-gray-600",children:r.firstIteration!==null?r.firstIteration:""}),O.jsx("td",{className:"px-4 py-2 text-gray-600",children:r.iterations}),O.jsx("td",{className:"px-4 py-2",children:O.jsx(LKt,{progress:r.progress})}),O.jsx("td",{className:"px-4 py-2 text-gray-600",children:s(r.timeSpent)}),O.jsx("td",{className:"px-4 py-2 text-gray-500",children:O.jsx(YKt,{stats:r.stats})}),O.jsx("td",{className:"px-4 py-2",children:r.solverInstance?O.jsxs("button",{onClick:()=>n(r),className:"flex items-center gap-1 text-blue-500 hover:text-blue-700",title:`Download input for ${r.name}`,children:[O.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",className:"w-4 h-4",children:O.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"})}),O.jsx("span",{children:"Input"})]}):null})]},r.name))})]})})]})},KKt=class extends Xi.Component{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(t){console.error("InteractiveGraphics render error:",t)}render(){return this.state.hasError?this.props.fallback:this.props.children}};function qKt({graphics:t}){const A=t.points??[],e=t.lines??[],i=t.rects??[],o=t.circles??[],n=t.texts??[];let s=Number.POSITIVE_INFINITY,r=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY,g=Number.NEGATIVE_INFINITY;const I=(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)I(E.x,E.y);for(const E of e){const h=E.points??[];for(const u of h)I(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;I(h,u),I(h+d,u+f)}for(const E of o){const h=E.x??0,u=E.y??0,d=E.radius??1;I(h-d,u-d),I(h+d,u+d)}for(const E of n)I(E.x,E.y);(!isFinite(s)||!isFinite(r)||!isFinite(a)||!isFinite(g))&&(s=-20,r=-20,a=20,g=20);const c=10,B=s-c,l=r-c,C=Math.max(1,a-s+2*c),Q=Math.max(1,g-r+2*c);return O.jsxs("svg",{className:"w-full h-[400px] bg-white",viewBox:`${B} ${l} ${C} ${Q}`,role:"img","aria-label":"Graphics fallback",children:[i.map((E,h)=>O.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}`)),e.map((E,h)=>O.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}`)),o.map((E,h)=>O.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)=>O.jsx("circle",{cx:E.x??0,cy:E.y??0,r:E.radius??1.5,fill:E.color??"black"},`point-${h}`)),n.map((E,h)=>O.jsx("text",{x:E.x??0,y:E.y??0,fontSize:E.fontSize??10,fill:E.color??"black",children:E.text??""},`text-${h}`))]})}var PKt=({solver:t,animationSpeed:A=25,onSolverStarted:e,onSolverCompleted:i})=>{const[o,n]=j.useReducer(I=>I+1,0),s=j.useMemo(()=>{try{return t.visualize()||{points:[],lines:[],rects:[],circles:[]}}catch(I){return console.error("Visualization error:",I),{points:[],lines:[],rects:[],circles:[]}}},[t,o]),r=j.useMemo(()=>(s.rects?.length||0)===0&&(s.lines?.length||0)===0&&(s.points?.length||0)===0&&(s.circles?.length||0)===0,[s]);j.useEffect(()=>{if(!(typeof document>"u")&&!document.querySelector('script[src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"]')){const I=document.createElement("script");I.src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4",document.head.appendChild(I)}},[]);const a=t.pipelineDef!==void 0,g=I=>{const c=t;if(!t.solved&&!t.failed){for(;!t.solved&&!t.failed&&c.currentPipelineStepIndex<=c.pipelineDef.findIndex(B=>B.solverName===I);)t.step();n()}};return O.jsxs("div",{children:[O.jsx(NKt,{solver:t,triggerRender:n,animationSpeed:A,onSolverStarted:e,onSolverCompleted:i}),r?O.jsx("div",{className:"p-4 text-gray-500",children:"No Graphics Yet"}):O.jsx(KKt,{fallback:O.jsx(qKt,{graphics:s}),children:O.jsx(FKt,{graphics:s})}),a&&O.jsx(TKt,{solver:t,onStepUntilPhase:g})]})};const OKt=()=>{j.useEffect(()=>{const t="tailwind-cdn-script";if(document.getElementById(t)||window.tailwind)return;const A=document.createElement("div");A.className="hidden",document.body.appendChild(A);const e=window.getComputedStyle(A).display==="none";if(document.body.removeChild(A),e)return;const i=document.createElement("script");i.id=t,i.src="https://cdn.tailwindcss.com",document.head.appendChild(i)},[])},WKt=t=>t.toLowerCase().includes("pack")?tbt:t.toLowerCase().includes("rout")?rbt:JSt,ZKt=({solverEvents:t=[]})=>{const[A,e]=j.useState(null);OKt();const i=j.useMemo(()=>{const r=new Map;for(const a of t){const g=`${a.componentName}-${a.solverName}`;r.set(g,a)}return r},[t]),o=j.useMemo(()=>Array.from(i.keys()),[i]),n=A?i.get(A):null,s=j.useMemo(()=>{if(!n)return{instance:null,error:null,classFound:!1};const r=jeA[n.solverName];if(!r)return{instance:null,error:`Solver class "${n.solverName}" not found in SOLVERS registry. Available: ${Object.keys(jeA).join(", ")}`,classFound:!1};try{const a=n.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}}},[n]);return t.length===0?O.jsx("div",{className:"rf-p-4",children:O.jsx("div",{className:"rf-bg-gray-50 rf-rounded-md rf-border rf-border-gray-200",children:O.jsxs("div",{className:"rf-p-4",children:[O.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-gray-800 rf-mb-3",children:"No Solvers Detected"}),O.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."})]})})}):O.jsxs("div",{className:"rf-flex rf-h-full rf-overflow-hidden",children:[O.jsxs("div",{className:"rf-w-64 rf-border-r rf-border-gray-200 rf-overflow-y-auto rf-flex-shrink-0",children:[O.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:[o.length," ",o.length===1?"Solver":"Solvers"]}),o.map(r=>{const a=i.get(r),g=A===r;return O.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:()=>e(r),children:(()=>{const I=WKt(a.solverName);return O.jsxs("div",{className:"rf-flex rf-items-center rf-gap-2",children:[O.jsx(I,{className:"rf-w-4 rf-h-4 rf-text-blue-500 rf-flex-shrink-0"}),O.jsxs("div",{className:"rf-flex-1 rf-min-w-0",children:[O.jsx("div",{className:"rf-text-sm rf-font-medium rf-text-gray-800 rf-truncate",children:a.componentName}),O.jsx("div",{className:"rf-text-xs rf-text-gray-500 rf-truncate",children:a.solverName})]})]})})()},r)})]}),O.jsx("div",{className:"rf-flex-1 rf-overflow-hidden",children:n?s.instance?O.jsx(ky,{fallback:O.jsx("div",{className:"rf-p-4",children:O.jsxs("div",{className:"rf-bg-red-50 rf-rounded-md rf-border rf-border-red-200 rf-p-4",children:[O.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-red-800 rf-mb-2",children:"Error Loading Solver Debugger"}),O.jsxs("p",{className:"rf-text-sm rf-text-red-600",children:["Failed to render the solver debugger for"," ",n.solverName]})]})}),children:O.jsx(PKt,{solver:s.instance})}):O.jsxs("div",{className:"rf-p-4",children:[O.jsxs("div",{className:"rf-mb-4",children:[O.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-gray-800",children:n.solverName}),O.jsxs("p",{className:"rf-text-sm rf-text-gray-500",children:["Component: ",n.componentName]})]}),s.error&&O.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:O.jsx("p",{className:`rf-text-sm ${s.classFound?"rf-text-red-700":"rf-text-yellow-700"}`,children:s.error})}),O.jsxs("div",{className:"rf-border rf-border-gray-200 rf-rounded-md rf-overflow-hidden",children:[O.jsx("div",{className:"rf-px-3 rf-py-2 rf-bg-gray-50",children:O.jsx("span",{className:"rf-text-sm rf-font-medium rf-text-gray-700",children:"Solver Parameters"})}),O.jsx("div",{className:"rf-p-3 rf-bg-white rf-border-t rf-border-gray-200",children:O.jsx("pre",{className:"rf-text-xs rf-font-mono rf-text-gray-600 rf-whitespace-pre-wrap rf-overflow-x-auto",children:JSON.stringify(n.solverParams,null,2)})})]})]}):O.jsx("div",{className:"rf-flex rf-items-center rf-justify-center rf-h-full",children:O.jsx("p",{className:"rf-text-sm rf-text-gray-500",children:"Select a solver from the list to view details"})})})]})},eie=({errorMessage:t,errorStack:A,circuitJsonErrors:e})=>{j.useEffect(()=>{if(t){const i=new Error(t);A&&(i.stack=A);try{z3.captureException(i)}catch{}}},[t,A]),j.useEffect(()=>{if(e&&e.length>0)for(const i of e){const o=new Error(i.message||"Circuit JSON Error");i.stack&&(o.stack=i.stack);try{z3.captureException(o,{error_type:i.type})}catch{}}},[e])},tie="0.0.1527",VKt={version:tie},JZ=S1A()(b1A(t=>({lastRunEvalVersion:void 0,setLastRunEvalVersion:A=>{t({lastRunEvalVersion:A})}}),{name:"runframe-runner-store"})),jKt=t=>{const[A,e]=j.useState([]),[i,o]=j.useState(null),[n,s]=j.useState(""),[r,a]=gv("eval-version-selection",null),g=JZ(l=>l.setLastRunEvalVersion),I=JZ(l=>l.lastRunEvalVersion);return j.useEffect(()=>{t&&fetch("https://data.jsdelivr.com/v1/package/npm/@tscircuit/eval").then(l=>l.json()).then(l=>{if(Array.isArray(l?.versions)){let C=[...l.versions];l.tags?.latest&&(o(l.tags.latest),C=C.filter(Q=>Q!==l.tags.latest)),e(C)}}).catch(()=>{})},[t]),j.useEffect(()=>{t&&(r?(window.TSCIRCUIT_LATEST_EVAL_VERSION=r,g(r)):i&&(window.TSCIRCUIT_LATEST_EVAL_VERSION=i,g(i)))},[t,r,i]),{versions:j.useMemo(()=>A.filter(l=>l.includes(n)).slice(0,50),[A,n]),latestVersion:i,lastRunEvalVersion:I,search:n,setSearch:s,selectVersion:l=>{a(l),s("")}}},zKt=({snippetNames:t,onSelect:A,onCancel:e,isOpen:i})=>{const[o,n]=j.useState(""),[s,r]=j.useState("");if(!i)return null;const a=t.filter(c=>c.toLowerCase().includes(s.toLowerCase())),g=s&&!t.includes(s),I=c=>{c.key==="Enter"&&(a.length===1?n(a[0]):g&&n(s))};return O.jsx("div",{className:"rf-fixed rf-inset-0 rf-bg-black rf-bg-opacity-50 rf-flex rf-items-center rf-justify-center rf-z-[100]",children:O.jsxs("div",{className:"rf-bg-white rf-rounded-lg rf-p-6 rf-w-96",children:[O.jsx("h2",{className:"rf-text-lg rf-font-semibold rf-mb-4",children:"Select Snippet"}),O.jsx("input",{type:"text",className:"rf-w-full rf-px-4 rf-py-2 rf-border rf-rounded rf-mb-4",placeholder:"Search snippets or new snippet name...",value:s,onChange:c=>r(c.target.value),onKeyDown:I}),O.jsxs("div",{className:"rf-h-60 rf-overflow-y-auto",children:[a.map(c=>O.jsx("button",{type:"button",className:`w-full text-left px-4 py-2 rounded hover:bg-gray-100 ${o===c?"bg-blue-50":""}`,onClick:()=>n(c),children:c},c)),g&&O.jsxs("button",{type:"button",className:`w-full text-left px-4 py-2 rounded hover:bg-gray-100 text-blue-500 ${o===s?"bg-blue-50":""}`,onClick:()=>n(s),children:['Create new "',s,'"']})]}),O.jsxs("div",{className:"rf-mt-4 rf-flex rf-justify-end rf-gap-2",children:[O.jsx("button",{type:"button",className:"rf-px-4 rf-py-2 rf-text-gray-600 rf-hover:text-gray-800",onClick:e,children:"Cancel"}),O.jsx("button",{type:"button",className:"rf-px-4 rf-py-2 rf-bg-blue-500 rf-text-white rf-rounded rf-hover:bg-blue-600 rf-disabled:opacity-50",onClick:()=>o&&A(o),disabled:!o,children:o===s?`Create "${o}"`:`Save to ${o}`})]})]})})},XKt=t=>{const A=j.useRef(null),e=Yc(i=>i.recentEvents);j.useEffect(()=>{if(e.length===0)return;const i=e[0];i.event_id!==A.current&&(t(i),A.current=i.event_id)},[e,t])};function $Kt(t){const A=Aqt(t),e=j.forwardRef((i,o)=>{const{children:n,...s}=i,r=j.Children.toArray(n),a=r.find(tqt);if(a){const g=a.props.children,I=r.map(c=>c===a?j.Children.count(g)>1?j.Children.only(null):j.isValidElement(g)?g.props.children:null:c);return O.jsx(A,{...s,ref:o,children:j.isValidElement(g)?j.cloneElement(g,void 0,I):null})}return O.jsx(A,{...s,ref:o,children:n})});return e.displayName=`${t}.Slot`,e}function Aqt(t){const A=j.forwardRef((e,i)=>{const{children:o,...n}=e;if(j.isValidElement(o)){const s=oqt(o),r=iqt(n,o.props);return o.type!==j.Fragment&&(r.ref=i?jp(i,s):s),j.cloneElement(o,r)}return j.Children.count(o)>1?j.Children.only(null):null});return A.displayName=`${t}.SlotClone`,A}var eqt=Symbol("radix.slottable");function tqt(t){return j.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===eqt}function iqt(t,A){const e={...A};for(const i in A){const o=t[i],n=A[i];/^on[A-Z]/.test(i)?o&&n?e[i]=(...r)=>{const a=n(...r);return o(...r),a}:o&&(e[i]=o):i==="style"?e[i]={...o,...n}:i==="className"&&(e[i]=[o,n].filter(Boolean).join(" "))}return{...t,...e}}function oqt(t){let A=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,e=A&&"isReactWarning"in A&&A.isReactWarning;return e?t.ref:(A=Object.getOwnPropertyDescriptor(t,"ref")?.get,e=A&&"isReactWarning"in A&&A.isReactWarning,e?t.props.ref:t.props.ref||t.ref)}var TZ="Dialog",[iie,oie]=uw(TZ),[nqt,Pw]=iie(TZ),nie=t=>{const{__scopeDialog:A,children:e,open:i,defaultOpen:o,onOpenChange:n,modal:s=!0}=t,r=j.useRef(null),a=j.useRef(null),[g,I]=sx({prop:i,defaultProp:o??!1,onChange:n,caller:TZ});return O.jsx(nqt,{scope:A,triggerRef:r,contentRef:a,contentId:Bh(),titleId:Bh(),descriptionId:Bh(),open:g,onOpenChange:I,onOpenToggle:j.useCallback(()=>I(c=>!c),[I]),modal:s,children:e})};nie.displayName=TZ;var sie="DialogTrigger",rie=j.forwardRef((t,A)=>{const{__scopeDialog:e,...i}=t,o=Pw(sie,e),n=cc(A,o.triggerRef);return O.jsx(Ha.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":luA(o.open),...i,ref:n,onClick:vo(t.onClick,o.onOpenToggle)})});rie.displayName=sie;var cuA="DialogPortal",[sqt,aie]=iie(cuA,{forceMount:void 0}),gie=t=>{const{__scopeDialog:A,forceMount:e,children:i,container:o}=t,n=Pw(cuA,A);return O.jsx(sqt,{scope:A,forceMount:e,children:j.Children.map(i,s=>O.jsx(s0,{present:e||n.open,children:O.jsx(nW,{asChild:!0,container:o,children:s})}))})};gie.displayName=cuA;var KZ="DialogOverlay",Iie=j.forwardRef((t,A)=>{const e=aie(KZ,t.__scopeDialog),{forceMount:i=e.forceMount,...o}=t,n=Pw(KZ,t.__scopeDialog);return n.modal?O.jsx(s0,{present:i||n.open,children:O.jsx(aqt,{...o,ref:A})}):null});Iie.displayName=KZ;var rqt=$Kt("DialogOverlay.RemoveScroll"),aqt=j.forwardRef((t,A)=>{const{__scopeDialog:e,...i}=t,o=Pw(KZ,e);return O.jsx(lW,{as:rqt,allowPinchZoom:!0,shards:[o.contentRef],children:O.jsx(Ha.div,{"data-state":luA(o.open),...i,ref:A,style:{pointerEvents:"auto",...i.style}})})}),VF="DialogContent",cie=j.forwardRef((t,A)=>{const e=aie(VF,t.__scopeDialog),{forceMount:i=e.forceMount,...o}=t,n=Pw(VF,t.__scopeDialog);return O.jsx(s0,{present:i||n.open,children:n.modal?O.jsx(gqt,{...o,ref:A}):O.jsx(Iqt,{...o,ref:A})})});cie.displayName=VF;var gqt=j.forwardRef((t,A)=>{const e=Pw(VF,t.__scopeDialog),i=j.useRef(null),o=cc(A,e.contentRef,i);return j.useEffect(()=>{const n=i.current;if(n)return tEA(n)},[]),O.jsx(Bie,{...t,ref:o,trapFocus:e.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:vo(t.onCloseAutoFocus,n=>{n.preventDefault(),e.triggerRef.current?.focus()}),onPointerDownOutside:vo(t.onPointerDownOutside,n=>{const s=n.detail.originalEvent,r=s.button===0&&s.ctrlKey===!0;(s.button===2||r)&&n.preventDefault()}),onFocusOutside:vo(t.onFocusOutside,n=>n.preventDefault())})}),Iqt=j.forwardRef((t,A)=>{const e=Pw(VF,t.__scopeDialog),i=j.useRef(!1),o=j.useRef(!1);return O.jsx(Bie,{...t,ref:A,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:n=>{t.onCloseAutoFocus?.(n),n.defaultPrevented||(i.current||e.triggerRef.current?.focus(),n.preventDefault()),i.current=!1,o.current=!1},onInteractOutside:n=>{t.onInteractOutside?.(n),n.defaultPrevented||(i.current=!0,n.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const s=n.target;e.triggerRef.current?.contains(s)&&n.preventDefault(),n.detail.originalEvent.type==="focusin"&&o.current&&n.preventDefault()}})}),Bie=j.forwardRef((t,A)=>{const{__scopeDialog:e,trapFocus:i,onOpenAutoFocus:o,onCloseAutoFocus:n,...s}=t,r=Pw(VF,e),a=j.useRef(null),g=cc(A,a);return UQA(),O.jsxs(O.Fragment,{children:[O.jsx(O8,{asChild:!0,loop:!0,trapped:i,onMountAutoFocus:o,onUnmountAutoFocus:n,children:O.jsx(oH,{role:"dialog",id:r.contentId,"aria-describedby":r.descriptionId,"aria-labelledby":r.titleId,"data-state":luA(r.open),...s,ref:g,onDismiss:()=>r.onOpenChange(!1)})}),O.jsxs(O.Fragment,{children:[O.jsx(Bqt,{titleId:r.titleId}),O.jsx(Cqt,{contentRef:a,descriptionId:r.descriptionId})]})]})}),BuA="DialogTitle",lie=j.forwardRef((t,A)=>{const{__scopeDialog:e,...i}=t,o=Pw(BuA,e);return O.jsx(Ha.h2,{id:o.titleId,...i,ref:A})});lie.displayName=BuA;var Cie="DialogDescription",Qie=j.forwardRef((t,A)=>{const{__scopeDialog:e,...i}=t,o=Pw(Cie,e);return O.jsx(Ha.p,{id:o.descriptionId,...i,ref:A})});Qie.displayName=Cie;var Eie="DialogClose",hie=j.forwardRef((t,A)=>{const{__scopeDialog:e,...i}=t,o=Pw(Eie,e);return O.jsx(Ha.button,{type:"button",...i,ref:A,onClick:vo(t.onClick,()=>o.onOpenChange(!1))})});hie.displayName=Eie;function luA(t){return t?"open":"closed"}var uie="DialogTitleWarning",[cqt,die]=H3e(uie,{contentName:VF,titleName:BuA,docsSlug:"dialog"}),Bqt=({titleId:t})=>{const A=die(uie),e=`\`${A.contentName}\` requires a \`${A.titleName}\` for the component to be accessible for screen reader users.
5622
+ `,c=new Blob([I],{type:"text/plain"}),B=URL.createObjectURL(c),l=document.createElement("a");l.href=B,l.download=`${g}.test.ts`,l.click(),URL.revokeObjectURL(B)}catch(a){alert(`Error generating test.ts for ${t.constructor.name}: ${a instanceof Error?a.message:String(a)}`)}i(!1)};return O.jsxs("div",{className:`relative ${A}`,ref:o,children:[O.jsx("button",{className:"px-2 py-1 rounded text-xs cursor-pointer",onClick:()=>i(!e),title:`Download options for ${t.constructor.name}`,children:t.constructor.name}),e&&O.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:[O.jsx("button",{className:"w-full text-left px-3 py-2 hover:bg-gray-100 text-xs",onClick:n,children:"Download JSON"}),O.jsx("button",{className:"w-full text-left px-3 py-2 hover:bg-gray-100 text-xs",onClick:s,children:"Download page.tsx"}),O.jsx("button",{className:"w-full text-left px-3 py-2 hover:bg-gray-100 text-xs",onClick:r,children:"Download test.ts"})]})]})},Aie=t=>t.activeSubSolver?[t,...Aie(t.activeSubSolver)]:[t],MKt=({solver:t})=>{const A=Aie(t);return O.jsx("div",{className:"flex gap-1 items-center text-sm pt-1",children:A.map((e,i)=>O.jsxs("div",{className:"flex items-center",children:[i>0&&O.jsx("span",{className:"text-gray-400 mx-1",children:"→"}),O.jsx(RKt,{solver:e})]},e.constructor.name))})},NKt=({solver:t,triggerRender:A,animationSpeed:e=25,onSolverStarted:i,onSolverCompleted:o})=>{const[n,s]=j.useReducer(Q=>!Q,!1),r=j.useRef(void 0),a=()=>{!t.solved&&!t.failed&&(t.step(),A())},g=()=>{!t.solved&&!t.failed&&(i&&i(t),t.solve(),A(),o&&o(t))},I=()=>{n?(r.current&&(clearInterval(r.current),r.current=void 0),s()):(s(),r.current=setInterval(()=>{if(t.solved||t.failed){r.current&&(clearInterval(r.current),r.current=void 0),s(),A(),o&&t.solved&&o(t);return}t.step(),A()},e))},c=()=>{const Q=t;if(Q.getCurrentPhase&&!t.solved&&!t.failed){const E=Q.getCurrentPhase();for(;Q.getCurrentPhase()===E&&!t.solved&&!t.failed;)t.step();A()}},B=()=>{if(t.solved||t.failed||n)return;const Q=window.prompt("Step until which iteration?",`${t.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(;t.iterations<E&&!t.solved&&!t.failed;)t.step();A(),t.solved&&o&&o(t)};j.useEffect(()=>()=>{r.current&&clearInterval(r.current)},[]),j.useEffect(()=>{(t.solved||t.failed)&&n&&(r.current&&(clearInterval(r.current),r.current=void 0),s())},[t.solved,t.failed,n]);const l=t.getCurrentPhase!==void 0,C=l?t.getCurrentPhase():null;return O.jsxs("div",{className:"space-y-2 p-2 border-b",children:[O.jsx("div",{className:"flex items-center",children:O.jsx(MKt,{solver:t})}),O.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[O.jsx("button",{onClick:a,disabled:t.solved||t.failed||n,className:"bg-blue-500 hover:bg-blue-600 disabled:bg-gray-300 text-white px-3 py-1 rounded text-sm",children:"Step"}),O.jsx("button",{onClick:g,disabled:t.solved||t.failed||n,className:"bg-green-500 hover:bg-green-600 disabled:bg-gray-300 text-white px-3 py-1 rounded text-sm",children:"Solve"}),O.jsx("button",{onClick:I,disabled:t.solved||t.failed,className:`px-3 py-1 rounded text-white text-sm ${n?"bg-red-500 hover:bg-red-600":"bg-yellow-500 hover:bg-yellow-600"} disabled:bg-gray-300`,children:n?"Stop":"Animate"}),O.jsx("button",{onClick:B,disabled:t.solved||t.failed||n,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"}),l&&O.jsx("button",{onClick:c,disabled:t.solved||t.failed||n,className:"bg-purple-500 hover:bg-purple-600 disabled:bg-gray-300 text-white px-3 py-1 rounded text-sm",children:"Next Stage"}),O.jsxs("div",{className:"text-sm text-gray-600",children:["Iterations: ",t.iterations]}),t.timeToSolve!==void 0&&O.jsxs("div",{className:"text-sm text-gray-600",children:["Time: ",(t.timeToSolve/1e3).toFixed(3),"s"]}),C&&O.jsxs("div",{className:"text-sm text-gray-600",children:["Phase: ",O.jsx("span",{className:"font-medium",children:C})]}),t.solved&&O.jsx("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded text-sm",children:"Solved"}),t.failed&&O.jsx("div",{className:"px-2 py-1 bg-red-100 text-red-800 rounded text-sm",children:"Failed"})]}),t.error&&O.jsxs("div",{className:"text-red-600 text-sm",children:["Error: ",t.error]})]})},_Kt=(t,A,e)=>{const i=t.currentPipelineStepIndex;return A<i?"Completed":A===i&&t.activeSubSolver?t.activeSubSolver.failed?"Failed":"In Progress":"Not Started"},vKt=(t,A)=>{const i=t.pipelineDef[A].solverName,o=_Kt(t,A),n=t[i],s=t.firstIterationOfPhase?.[i]??null,r=t.iterations;let a=0;if(o==="Completed"){const B=t.pipelineDef[A+1],l=B?t.firstIterationOfPhase?.[B.solverName]:void 0;l!==void 0&&s!==null?a=l-s:s!==null&&(a=r-s)}else o==="In Progress"&&s!==null&&(a=r-s);const g=t.timeSpentOnPhase?.[i]??0;let I=0;o==="Completed"?I=1:o==="In Progress"&&n&&(I=n.progress??0);const c=n?.stats??null;return{index:A,name:i,status:o,firstIteration:s,iterations:a,progress:I,timeSpent:g,stats:c&&Object.keys(c).length>0?c:null,solverInstance:n??null}},UKt=({status:t})=>{const A={"Not Started":"text-blue-600","In Progress":"text-yellow-600",Completed:"text-green-600",Failed:"text-red-600"};return O.jsx("span",{className:`font-medium ${A[t]}`,children:t})},LKt=({progress:t})=>{if(t===0)return null;const A=Math.round(t*100);return O.jsxs("div",{className:"flex items-center gap-2",children:[O.jsx("div",{className:"w-20 h-2 bg-gray-200 rounded overflow-hidden",children:O.jsx("div",{className:"h-full bg-blue-500 transition-all duration-200",style:{width:`${A}%`}})}),O.jsxs("span",{className:"text-xs text-gray-500",children:[A,"%"]})]})},HKt=t=>Object.entries(t).map(([A,e])=>`${A}: ${e}`).join(", "),YKt=({stats:t})=>{if(!t||Object.keys(t).length===0)return O.jsx("span",{children:"-"});const A=Object.entries(t),e=HKt(t);return O.jsxs("details",{className:"cursor-pointer",children:[O.jsx("summary",{className:"whitespace-nowrap overflow-hidden text-ellipsis max-w-[200px]",children:e}),O.jsx("div",{className:"mt-1 text-xs",children:A.map(([i,o])=>O.jsxs("div",{children:[i,": ",String(o)]},i))})]})},IuA=t=>{if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(IuA);const A={};for(const[e,i]of Object.entries(t))e.startsWith("_")||(A[e]=IuA(i));return A},JKt=(t,A)=>{try{if(typeof t.getConstructorParams!="function"){alert(`getConstructorParams() is not implemented for ${A}`);return}const e=IuA(t.getConstructorParams()),i=new Blob([JSON.stringify(e,null,2)],{type:"application/json"}),o=URL.createObjectURL(i),n=document.createElement("a");n.href=o,n.download=`${A}_input.json`,n.click(),URL.revokeObjectURL(o)}catch(e){alert(`Error downloading input for ${A}: ${e instanceof Error?e.message:String(e)}`)}},TKt=({solver:t,onStepUntilPhase:A,onDownloadInput:e})=>{const i=t.pipelineDef.map((r,a)=>vKt(t,a)),o=r=>{A?.(r)},n=r=>{r.solverInstance&&(e?e(r.solverInstance,r.name):JKt(r.solverInstance,r.name))},s=r=>`${(r/1e3).toFixed(2)}s`;return O.jsxs("div",{className:"border-t border-gray-200",children:[O.jsx("div",{className:"px-4 py-2 bg-gray-50 border-b border-gray-200",children:O.jsx("h3",{className:"text-sm font-semibold text-gray-700",children:"Pipeline Steps"})}),O.jsx("div",{className:"overflow-x-auto",children:O.jsxs("table",{className:"w-full text-sm",children:[O.jsx("thead",{children:O.jsxs("tr",{className:"bg-gray-50 border-b border-gray-200",children:[O.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Step"}),O.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Status"}),O.jsxs("th",{className:"px-4 py-2 text-center font-semibold text-gray-700",children:["i",O.jsx("sub",{children:"0"})]}),O.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Iterations"}),O.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Progress"}),O.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Time"}),O.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Stats"}),O.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Input"})]})}),O.jsx("tbody",{children:i.map(r=>O.jsxs("tr",{className:`border-b border-gray-100 ${r.status==="In Progress"?"bg-yellow-50":""}`,children:[O.jsx("td",{className:"px-4 py-2",children:O.jsxs("div",{className:"flex items-center gap-2",children:[O.jsx("span",{className:"text-gray-400 w-6",children:String(r.index+1).padStart(2,"0")}),O.jsx("button",{onClick:()=>o(r.name),disabled:r.status==="Completed"||t.solved||t.failed,className:"text-blue-500 hover:text-blue-700 disabled:text-gray-300 disabled:cursor-not-allowed",title:`Step until ${r.name} completes`,children:O.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",className:"w-4 h-4",children:O.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"})})}),O.jsx("span",{className:"font-medium text-gray-900",children:r.name})]})}),O.jsx("td",{className:"px-4 py-2",children:O.jsx(UKt,{status:r.status})}),O.jsx("td",{className:"px-4 py-2 text-center text-gray-600",children:r.firstIteration!==null?r.firstIteration:""}),O.jsx("td",{className:"px-4 py-2 text-gray-600",children:r.iterations}),O.jsx("td",{className:"px-4 py-2",children:O.jsx(LKt,{progress:r.progress})}),O.jsx("td",{className:"px-4 py-2 text-gray-600",children:s(r.timeSpent)}),O.jsx("td",{className:"px-4 py-2 text-gray-500",children:O.jsx(YKt,{stats:r.stats})}),O.jsx("td",{className:"px-4 py-2",children:r.solverInstance?O.jsxs("button",{onClick:()=>n(r),className:"flex items-center gap-1 text-blue-500 hover:text-blue-700",title:`Download input for ${r.name}`,children:[O.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",className:"w-4 h-4",children:O.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"})}),O.jsx("span",{children:"Input"})]}):null})]},r.name))})]})})]})},KKt=class extends Xi.Component{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(t){console.error("InteractiveGraphics render error:",t)}render(){return this.state.hasError?this.props.fallback:this.props.children}};function qKt({graphics:t}){const A=t.points??[],e=t.lines??[],i=t.rects??[],o=t.circles??[],n=t.texts??[];let s=Number.POSITIVE_INFINITY,r=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY,g=Number.NEGATIVE_INFINITY;const I=(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)I(E.x,E.y);for(const E of e){const h=E.points??[];for(const u of h)I(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;I(h,u),I(h+d,u+f)}for(const E of o){const h=E.x??0,u=E.y??0,d=E.radius??1;I(h-d,u-d),I(h+d,u+d)}for(const E of n)I(E.x,E.y);(!isFinite(s)||!isFinite(r)||!isFinite(a)||!isFinite(g))&&(s=-20,r=-20,a=20,g=20);const c=10,B=s-c,l=r-c,C=Math.max(1,a-s+2*c),Q=Math.max(1,g-r+2*c);return O.jsxs("svg",{className:"w-full h-[400px] bg-white",viewBox:`${B} ${l} ${C} ${Q}`,role:"img","aria-label":"Graphics fallback",children:[i.map((E,h)=>O.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}`)),e.map((E,h)=>O.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}`)),o.map((E,h)=>O.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)=>O.jsx("circle",{cx:E.x??0,cy:E.y??0,r:E.radius??1.5,fill:E.color??"black"},`point-${h}`)),n.map((E,h)=>O.jsx("text",{x:E.x??0,y:E.y??0,fontSize:E.fontSize??10,fill:E.color??"black",children:E.text??""},`text-${h}`))]})}var PKt=({solver:t,animationSpeed:A=25,onSolverStarted:e,onSolverCompleted:i})=>{const[o,n]=j.useReducer(I=>I+1,0),s=j.useMemo(()=>{try{return t.visualize()||{points:[],lines:[],rects:[],circles:[]}}catch(I){return console.error("Visualization error:",I),{points:[],lines:[],rects:[],circles:[]}}},[t,o]),r=j.useMemo(()=>(s.rects?.length||0)===0&&(s.lines?.length||0)===0&&(s.points?.length||0)===0&&(s.circles?.length||0)===0,[s]);j.useEffect(()=>{if(!(typeof document>"u")&&!document.querySelector('script[src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"]')){const I=document.createElement("script");I.src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4",document.head.appendChild(I)}},[]);const a=t.pipelineDef!==void 0,g=I=>{const c=t;if(!t.solved&&!t.failed){for(;!t.solved&&!t.failed&&c.currentPipelineStepIndex<=c.pipelineDef.findIndex(B=>B.solverName===I);)t.step();n()}};return O.jsxs("div",{children:[O.jsx(NKt,{solver:t,triggerRender:n,animationSpeed:A,onSolverStarted:e,onSolverCompleted:i}),r?O.jsx("div",{className:"p-4 text-gray-500",children:"No Graphics Yet"}):O.jsx(KKt,{fallback:O.jsx(qKt,{graphics:s}),children:O.jsx(FKt,{graphics:s})}),a&&O.jsx(TKt,{solver:t,onStepUntilPhase:g})]})};const OKt=()=>{j.useEffect(()=>{const t="tailwind-cdn-script";if(document.getElementById(t)||window.tailwind)return;const A=document.createElement("div");A.className="hidden",document.body.appendChild(A);const e=window.getComputedStyle(A).display==="none";if(document.body.removeChild(A),e)return;const i=document.createElement("script");i.id=t,i.src="https://cdn.tailwindcss.com",document.head.appendChild(i)},[])},WKt=t=>t.toLowerCase().includes("pack")?tbt:t.toLowerCase().includes("rout")?rbt:JSt,ZKt=({solverEvents:t=[]})=>{const[A,e]=j.useState(null);OKt();const i=j.useMemo(()=>{const r=new Map;for(const a of t){const g=`${a.componentName}-${a.solverName}`;r.set(g,a)}return r},[t]),o=j.useMemo(()=>Array.from(i.keys()),[i]),n=A?i.get(A):null,s=j.useMemo(()=>{if(!n)return{instance:null,error:null,classFound:!1};const r=jeA[n.solverName];if(!r)return{instance:null,error:`Solver class "${n.solverName}" not found in SOLVERS registry. Available: ${Object.keys(jeA).join(", ")}`,classFound:!1};try{const a=n.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}}},[n]);return t.length===0?O.jsx("div",{className:"rf-p-4",children:O.jsx("div",{className:"rf-bg-gray-50 rf-rounded-md rf-border rf-border-gray-200",children:O.jsxs("div",{className:"rf-p-4",children:[O.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-gray-800 rf-mb-3",children:"No Solvers Detected"}),O.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."})]})})}):O.jsxs("div",{className:"rf-flex rf-h-full rf-overflow-hidden",children:[O.jsxs("div",{className:"rf-w-64 rf-border-r rf-border-gray-200 rf-overflow-y-auto rf-flex-shrink-0",children:[O.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:[o.length," ",o.length===1?"Solver":"Solvers"]}),o.map(r=>{const a=i.get(r),g=A===r;return O.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:()=>e(r),children:(()=>{const I=WKt(a.solverName);return O.jsxs("div",{className:"rf-flex rf-items-center rf-gap-2",children:[O.jsx(I,{className:"rf-w-4 rf-h-4 rf-text-blue-500 rf-flex-shrink-0"}),O.jsxs("div",{className:"rf-flex-1 rf-min-w-0",children:[O.jsx("div",{className:"rf-text-sm rf-font-medium rf-text-gray-800 rf-truncate",children:a.componentName}),O.jsx("div",{className:"rf-text-xs rf-text-gray-500 rf-truncate",children:a.solverName})]})]})})()},r)})]}),O.jsx("div",{className:"rf-flex-1 rf-overflow-hidden",children:n?s.instance?O.jsx(ky,{fallback:O.jsx("div",{className:"rf-p-4",children:O.jsxs("div",{className:"rf-bg-red-50 rf-rounded-md rf-border rf-border-red-200 rf-p-4",children:[O.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-red-800 rf-mb-2",children:"Error Loading Solver Debugger"}),O.jsxs("p",{className:"rf-text-sm rf-text-red-600",children:["Failed to render the solver debugger for"," ",n.solverName]})]})}),children:O.jsx(PKt,{solver:s.instance})}):O.jsxs("div",{className:"rf-p-4",children:[O.jsxs("div",{className:"rf-mb-4",children:[O.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-gray-800",children:n.solverName}),O.jsxs("p",{className:"rf-text-sm rf-text-gray-500",children:["Component: ",n.componentName]})]}),s.error&&O.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:O.jsx("p",{className:`rf-text-sm ${s.classFound?"rf-text-red-700":"rf-text-yellow-700"}`,children:s.error})}),O.jsxs("div",{className:"rf-border rf-border-gray-200 rf-rounded-md rf-overflow-hidden",children:[O.jsx("div",{className:"rf-px-3 rf-py-2 rf-bg-gray-50",children:O.jsx("span",{className:"rf-text-sm rf-font-medium rf-text-gray-700",children:"Solver Parameters"})}),O.jsx("div",{className:"rf-p-3 rf-bg-white rf-border-t rf-border-gray-200",children:O.jsx("pre",{className:"rf-text-xs rf-font-mono rf-text-gray-600 rf-whitespace-pre-wrap rf-overflow-x-auto",children:JSON.stringify(n.solverParams,null,2)})})]})]}):O.jsx("div",{className:"rf-flex rf-items-center rf-justify-center rf-h-full",children:O.jsx("p",{className:"rf-text-sm rf-text-gray-500",children:"Select a solver from the list to view details"})})})]})},eie=({errorMessage:t,errorStack:A,circuitJsonErrors:e})=>{j.useEffect(()=>{if(t){const i=new Error(t);A&&(i.stack=A);try{z3.captureException(i)}catch{}}},[t,A]),j.useEffect(()=>{if(e&&e.length>0)for(const i of e){const o=new Error(i.message||"Circuit JSON Error");i.stack&&(o.stack=i.stack);try{z3.captureException(o,{error_type:i.type})}catch{}}},[e])},tie="0.0.1528",VKt={version:tie},JZ=S1A()(b1A(t=>({lastRunEvalVersion:void 0,setLastRunEvalVersion:A=>{t({lastRunEvalVersion:A})}}),{name:"runframe-runner-store"})),jKt=t=>{const[A,e]=j.useState([]),[i,o]=j.useState(null),[n,s]=j.useState(""),[r,a]=gv("eval-version-selection",null),g=JZ(l=>l.setLastRunEvalVersion),I=JZ(l=>l.lastRunEvalVersion);return j.useEffect(()=>{t&&fetch("https://data.jsdelivr.com/v1/package/npm/@tscircuit/eval").then(l=>l.json()).then(l=>{if(Array.isArray(l?.versions)){let C=[...l.versions];l.tags?.latest&&(o(l.tags.latest),C=C.filter(Q=>Q!==l.tags.latest)),e(C)}}).catch(()=>{})},[t]),j.useEffect(()=>{t&&(r?(window.TSCIRCUIT_LATEST_EVAL_VERSION=r,g(r)):i&&(window.TSCIRCUIT_LATEST_EVAL_VERSION=i,g(i)))},[t,r,i]),{versions:j.useMemo(()=>A.filter(l=>l.includes(n)).slice(0,50),[A,n]),latestVersion:i,lastRunEvalVersion:I,search:n,setSearch:s,selectVersion:l=>{a(l),s("")}}},zKt=({snippetNames:t,onSelect:A,onCancel:e,isOpen:i})=>{const[o,n]=j.useState(""),[s,r]=j.useState("");if(!i)return null;const a=t.filter(c=>c.toLowerCase().includes(s.toLowerCase())),g=s&&!t.includes(s),I=c=>{c.key==="Enter"&&(a.length===1?n(a[0]):g&&n(s))};return O.jsx("div",{className:"rf-fixed rf-inset-0 rf-bg-black rf-bg-opacity-50 rf-flex rf-items-center rf-justify-center rf-z-[100]",children:O.jsxs("div",{className:"rf-bg-white rf-rounded-lg rf-p-6 rf-w-96",children:[O.jsx("h2",{className:"rf-text-lg rf-font-semibold rf-mb-4",children:"Select Snippet"}),O.jsx("input",{type:"text",className:"rf-w-full rf-px-4 rf-py-2 rf-border rf-rounded rf-mb-4",placeholder:"Search snippets or new snippet name...",value:s,onChange:c=>r(c.target.value),onKeyDown:I}),O.jsxs("div",{className:"rf-h-60 rf-overflow-y-auto",children:[a.map(c=>O.jsx("button",{type:"button",className:`w-full text-left px-4 py-2 rounded hover:bg-gray-100 ${o===c?"bg-blue-50":""}`,onClick:()=>n(c),children:c},c)),g&&O.jsxs("button",{type:"button",className:`w-full text-left px-4 py-2 rounded hover:bg-gray-100 text-blue-500 ${o===s?"bg-blue-50":""}`,onClick:()=>n(s),children:['Create new "',s,'"']})]}),O.jsxs("div",{className:"rf-mt-4 rf-flex rf-justify-end rf-gap-2",children:[O.jsx("button",{type:"button",className:"rf-px-4 rf-py-2 rf-text-gray-600 rf-hover:text-gray-800",onClick:e,children:"Cancel"}),O.jsx("button",{type:"button",className:"rf-px-4 rf-py-2 rf-bg-blue-500 rf-text-white rf-rounded rf-hover:bg-blue-600 rf-disabled:opacity-50",onClick:()=>o&&A(o),disabled:!o,children:o===s?`Create "${o}"`:`Save to ${o}`})]})]})})},XKt=t=>{const A=j.useRef(null),e=Yc(i=>i.recentEvents);j.useEffect(()=>{if(e.length===0)return;const i=e[0];i.event_id!==A.current&&(t(i),A.current=i.event_id)},[e,t])};function $Kt(t){const A=Aqt(t),e=j.forwardRef((i,o)=>{const{children:n,...s}=i,r=j.Children.toArray(n),a=r.find(tqt);if(a){const g=a.props.children,I=r.map(c=>c===a?j.Children.count(g)>1?j.Children.only(null):j.isValidElement(g)?g.props.children:null:c);return O.jsx(A,{...s,ref:o,children:j.isValidElement(g)?j.cloneElement(g,void 0,I):null})}return O.jsx(A,{...s,ref:o,children:n})});return e.displayName=`${t}.Slot`,e}function Aqt(t){const A=j.forwardRef((e,i)=>{const{children:o,...n}=e;if(j.isValidElement(o)){const s=oqt(o),r=iqt(n,o.props);return o.type!==j.Fragment&&(r.ref=i?jp(i,s):s),j.cloneElement(o,r)}return j.Children.count(o)>1?j.Children.only(null):null});return A.displayName=`${t}.SlotClone`,A}var eqt=Symbol("radix.slottable");function tqt(t){return j.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===eqt}function iqt(t,A){const e={...A};for(const i in A){const o=t[i],n=A[i];/^on[A-Z]/.test(i)?o&&n?e[i]=(...r)=>{const a=n(...r);return o(...r),a}:o&&(e[i]=o):i==="style"?e[i]={...o,...n}:i==="className"&&(e[i]=[o,n].filter(Boolean).join(" "))}return{...t,...e}}function oqt(t){let A=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,e=A&&"isReactWarning"in A&&A.isReactWarning;return e?t.ref:(A=Object.getOwnPropertyDescriptor(t,"ref")?.get,e=A&&"isReactWarning"in A&&A.isReactWarning,e?t.props.ref:t.props.ref||t.ref)}var TZ="Dialog",[iie,oie]=uw(TZ),[nqt,Pw]=iie(TZ),nie=t=>{const{__scopeDialog:A,children:e,open:i,defaultOpen:o,onOpenChange:n,modal:s=!0}=t,r=j.useRef(null),a=j.useRef(null),[g,I]=sx({prop:i,defaultProp:o??!1,onChange:n,caller:TZ});return O.jsx(nqt,{scope:A,triggerRef:r,contentRef:a,contentId:Bh(),titleId:Bh(),descriptionId:Bh(),open:g,onOpenChange:I,onOpenToggle:j.useCallback(()=>I(c=>!c),[I]),modal:s,children:e})};nie.displayName=TZ;var sie="DialogTrigger",rie=j.forwardRef((t,A)=>{const{__scopeDialog:e,...i}=t,o=Pw(sie,e),n=cc(A,o.triggerRef);return O.jsx(Ha.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":luA(o.open),...i,ref:n,onClick:vo(t.onClick,o.onOpenToggle)})});rie.displayName=sie;var cuA="DialogPortal",[sqt,aie]=iie(cuA,{forceMount:void 0}),gie=t=>{const{__scopeDialog:A,forceMount:e,children:i,container:o}=t,n=Pw(cuA,A);return O.jsx(sqt,{scope:A,forceMount:e,children:j.Children.map(i,s=>O.jsx(s0,{present:e||n.open,children:O.jsx(nW,{asChild:!0,container:o,children:s})}))})};gie.displayName=cuA;var KZ="DialogOverlay",Iie=j.forwardRef((t,A)=>{const e=aie(KZ,t.__scopeDialog),{forceMount:i=e.forceMount,...o}=t,n=Pw(KZ,t.__scopeDialog);return n.modal?O.jsx(s0,{present:i||n.open,children:O.jsx(aqt,{...o,ref:A})}):null});Iie.displayName=KZ;var rqt=$Kt("DialogOverlay.RemoveScroll"),aqt=j.forwardRef((t,A)=>{const{__scopeDialog:e,...i}=t,o=Pw(KZ,e);return O.jsx(lW,{as:rqt,allowPinchZoom:!0,shards:[o.contentRef],children:O.jsx(Ha.div,{"data-state":luA(o.open),...i,ref:A,style:{pointerEvents:"auto",...i.style}})})}),VF="DialogContent",cie=j.forwardRef((t,A)=>{const e=aie(VF,t.__scopeDialog),{forceMount:i=e.forceMount,...o}=t,n=Pw(VF,t.__scopeDialog);return O.jsx(s0,{present:i||n.open,children:n.modal?O.jsx(gqt,{...o,ref:A}):O.jsx(Iqt,{...o,ref:A})})});cie.displayName=VF;var gqt=j.forwardRef((t,A)=>{const e=Pw(VF,t.__scopeDialog),i=j.useRef(null),o=cc(A,e.contentRef,i);return j.useEffect(()=>{const n=i.current;if(n)return tEA(n)},[]),O.jsx(Bie,{...t,ref:o,trapFocus:e.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:vo(t.onCloseAutoFocus,n=>{n.preventDefault(),e.triggerRef.current?.focus()}),onPointerDownOutside:vo(t.onPointerDownOutside,n=>{const s=n.detail.originalEvent,r=s.button===0&&s.ctrlKey===!0;(s.button===2||r)&&n.preventDefault()}),onFocusOutside:vo(t.onFocusOutside,n=>n.preventDefault())})}),Iqt=j.forwardRef((t,A)=>{const e=Pw(VF,t.__scopeDialog),i=j.useRef(!1),o=j.useRef(!1);return O.jsx(Bie,{...t,ref:A,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:n=>{t.onCloseAutoFocus?.(n),n.defaultPrevented||(i.current||e.triggerRef.current?.focus(),n.preventDefault()),i.current=!1,o.current=!1},onInteractOutside:n=>{t.onInteractOutside?.(n),n.defaultPrevented||(i.current=!0,n.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const s=n.target;e.triggerRef.current?.contains(s)&&n.preventDefault(),n.detail.originalEvent.type==="focusin"&&o.current&&n.preventDefault()}})}),Bie=j.forwardRef((t,A)=>{const{__scopeDialog:e,trapFocus:i,onOpenAutoFocus:o,onCloseAutoFocus:n,...s}=t,r=Pw(VF,e),a=j.useRef(null),g=cc(A,a);return UQA(),O.jsxs(O.Fragment,{children:[O.jsx(O8,{asChild:!0,loop:!0,trapped:i,onMountAutoFocus:o,onUnmountAutoFocus:n,children:O.jsx(oH,{role:"dialog",id:r.contentId,"aria-describedby":r.descriptionId,"aria-labelledby":r.titleId,"data-state":luA(r.open),...s,ref:g,onDismiss:()=>r.onOpenChange(!1)})}),O.jsxs(O.Fragment,{children:[O.jsx(Bqt,{titleId:r.titleId}),O.jsx(Cqt,{contentRef:a,descriptionId:r.descriptionId})]})]})}),BuA="DialogTitle",lie=j.forwardRef((t,A)=>{const{__scopeDialog:e,...i}=t,o=Pw(BuA,e);return O.jsx(Ha.h2,{id:o.titleId,...i,ref:A})});lie.displayName=BuA;var Cie="DialogDescription",Qie=j.forwardRef((t,A)=>{const{__scopeDialog:e,...i}=t,o=Pw(Cie,e);return O.jsx(Ha.p,{id:o.descriptionId,...i,ref:A})});Qie.displayName=Cie;var Eie="DialogClose",hie=j.forwardRef((t,A)=>{const{__scopeDialog:e,...i}=t,o=Pw(Eie,e);return O.jsx(Ha.button,{type:"button",...i,ref:A,onClick:vo(t.onClick,()=>o.onOpenChange(!1))})});hie.displayName=Eie;function luA(t){return t?"open":"closed"}var uie="DialogTitleWarning",[cqt,die]=H3e(uie,{contentName:VF,titleName:BuA,docsSlug:"dialog"}),Bqt=({titleId:t})=>{const A=die(uie),e=`\`${A.contentName}\` requires a \`${A.titleName}\` for the component to be accessible for screen reader users.
5623
5623
 
5624
5624
  If you want to hide the \`${A.titleName}\`, you can wrap it with our VisuallyHidden component.
5625
5625
 
@@ -5756,7 +5756,7 @@ ${a.join(`
5756
5756
  `)}};NA.register(kjt);var vae=class qwA 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 qwA(!0);const e=Ei(A[0]);return new qwA(e==="yes")}getString(){return this.value?"(locked yes)":"(locked no)"}};NA.register(vae);var Uae=class the extends NA{static token="members";static parentToken="group";token="members";members;constructor(A){super(),this.members=A}static fromSexprPrimitives(A){const e=[];for(const i of A){const o=Ei(i);o&&e.push(o)}return new the(e)}getString(){return this.members.length===0?"(members)":`(members ${this.members.map(e=>`"${e}"`).join(" ")})`}};NA.register(Uae);var jfA=class ihe extends NA{static token="end";static parentToken="segment";token="end";_x;_y;constructor(A,e){super(),this._x=A,this._y=e}static fromSexprPrimitives(A){const[e,i]=A,o=si(e),n=si(i);if(o===void 0||n===void 0)throw new Error("end expects two numeric arguments");return new ihe(o,n)}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(jfA);var Gjt=new Set(["true","yes","1"]),Lae=class xj extends SB{static token="locked";static parentToken="segment";token="locked";constructor(A){super(A)}static fromSexprPrimitives(A){const[e]=A;return typeof e=="boolean"?new xj(e):typeof e=="string"?new xj(Gjt.has(e.toLowerCase())):new xj(!1)}getString(){return`(locked ${this.value?"yes":"no"})`}};NA.register(Lae);var OV=class ohe extends NA{static token="net";static parentToken="segment";token="net";_id;_name;constructor(A,e){super(),this._id=A,this._name=e}static fromSexprPrimitives(A){const[e,i]=A,o=si(e);if(o===void 0)throw new Error("net expects a numeric identifier");const n=i===void 0?void 0:Ei(i);return new ohe(o,n??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?` ${go(this._name)}`:"";return`(net ${this._id}${A})`}};NA.register(OV);var zfA=class nhe extends NA{static token="start";static parentToken="segment";token="start";_x;_y;constructor(A,e){super(),this._x=A,this._y=e}static fromSexprPrimitives(A){const[e,i]=A,o=si(e),n=si(i);if(o===void 0||n===void 0)throw new Error("start expects two numeric arguments");return new nhe(o,n)}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(zfA);var Hae=new Set(["start","end","width","layer","net","tstamp","uuid","locked"]),XfA=class she 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 e=new she,{propertyMap:i,arrayPropertyMap:o}=NA.parsePrimitivesToClassProperties(A,this.token),n=Object.keys(i).filter(r=>!Hae.has(r));if(n.length>0)throw new Error(`Unsupported child tokens inside segment expression: ${n.join(", ")}`);for(const[r,a]of Object.entries(o)){if(!Hae.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}`)}e._sxStart=o.start?.[0]??i.start,e._sxEnd=o.end?.[0]??i.end,e._sxWidth=o.width?.[0]??i.width,e._sxLayer=o.layer?.[0]??i.layer,e._sxNet=o.net?.[0]??i.net;const s=o.locked?.[0]??i.locked;return e._sxLocked=s&&s.value?s:void 0,e._sxTstamp=o.tstamp?.[0]??i.tstamp,e._sxUuid=o.uuid?.[0]??i.uuid,e}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 Dr?A:new Dr(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 hr){this._sxLayer=A;return}const e=Array.isArray(A)?A:[A];this._sxLayer=new hr(e)}get net(){return this._sxNet}set net(A){if(A===void 0){this._sxNet=void 0;return}if(A instanceof OV){this._sxNet=A;return}this._sxNet=new OV(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 Vg?A:new Vg(A)}get uuid(){return this._sxUuid}set uuid(A){if(A===void 0){this._sxUuid=void 0;return}this._sxUuid=A instanceof Ni?A:new Ni(A)}get locked(){return this._sxLocked?.value??!1}set locked(A){this._sxLocked=A?new Lae(!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 zfA?A:new zfA(A.x,A.y)}normalizeEnd(A){if(A!==void 0)return A instanceof jfA?A:new jfA(A.x,A.y)}};NA.register(XfA);var Yae=class rhe extends NA{static token="zone";token="zone";_rawChildren=[];static fromSexprPrimitives(A){const e=new rhe;return e._rawChildren=[...A],e}get rawChildren(){return[...this._rawChildren]}set rawChildren(A){this._rawChildren=[...A]}getChildren(){return[]}getString(){const A=["(zone"];for(const e of this._rawChildren)A.push(` ${yE(e)}`);return A.push(")"),A.join(`
5757
5757
  `)}};NA.register(Yae);var WV=class ahe extends NA{static token="layers";token="layers";_names=[];constructor(A=[]){super(),this.names=A}static fromSexprPrimitives(A){const e=A.map(i=>typeof i=="string"||typeof i=="number"?String(i):yE(i));return new ahe(e)}get names(){return[...this._names]}set names(A){this._names=A.map(e=>String(e))}getString(){return`(layers ${this._names.map(e=>/^[^\s()"]+$/u.test(e)&&!["nil","#t","#f"].includes(e)?e:go(e)).join(" ")})`}};NA.register(WV);var YY=class extends NA{_value;quoteStringValue=!1;constructor(t){super(),this._value=t}static fromSexprPrimitives(t){const[A]=t,e=this.parsePrimitiveValue(A),i=this;return new i(e)}static parsePrimitiveValue(t){const A=Ei(t);if(A===void 0)throw new Error(`${this.name} expects a primitive value`);return A}get value(){return this._value}set value(t){this._value=t}getChildren(){return[]}formatValue(){return typeof this._value=="string"?this.quoteStringValue?go(this._value):this._value:`${this._value}`}getString(){return`(${this.token} ${this.formatValue()})`}},Fjt=class extends NA{_values;constructor(t){super(),this._values=t}static fromSexprPrimitives(t){const A=t.map(i=>{const o=si(i);if(o===void 0)throw new Error(`${this.name} expects numeric primitives but received ${i}`);return o}),e=this;return new e(A)}get values(){return[...this._values]}set values(t){this._values=[...t]}getChildren(){return[]}getString(){return`(${this.token} ${this._values.join(" ")})`}},Rjt=class extends NA{_x;_y;constructor(t,A){super(),this._x=t,this._y=A}static fromSexprPrimitives(t){const[A,e]=t,i=si(A),o=si(e);if(i===void 0||o===void 0)throw new Error(`${this.name} expects two numeric values`);const n=this;return new n(i,o)}get x(){return this._x}set x(t){this._x=t}get y(){return this._y}set y(t){this._y=t}getChildren(){return[]}getString(){return`(${this.token} ${this._x} ${this._y})`}},ur=class extends YY{static parentToken="pcbplotparams"},Ky=class extends ur{static parsePrimitiveValue(t){const A=si(t);if(A===void 0)throw new Error(`pcbplotparams ${this.token} expects a numeric value`);return A}},Jae=class extends ur{static token="layerselection";token="layerselection"};NA.register(Jae);var Tae=class extends ur{static token="plot_on_all_layers_selection";token="plot_on_all_layers_selection"};NA.register(Tae);var Kae=class extends Ky{static token="dashed_line_dash_ratio";token="dashed_line_dash_ratio"};NA.register(Kae);var qae=class extends Ky{static token="dashed_line_gap_ratio";token="dashed_line_gap_ratio"};NA.register(qae);var Pae=class extends Ky{static token="svgprecision";token="svgprecision"};NA.register(Pae);var Oae=class extends Ky{static token="linewidth";token="linewidth"};NA.register(Oae);var Wae=class extends Ky{static token="mode";token="mode"};NA.register(Wae);var Zae=class extends Ky{static token="hpglpennumber";token="hpglpennumber"};NA.register(Zae);var Vae=class extends Ky{static token="hpglpenspeed";token="hpglpenspeed"};NA.register(Vae);var jae=class extends Ky{static token="hpglpendiameter";token="hpglpendiameter"};NA.register(jae);var zae=class extends Ky{static token="hpglpenoverlay";token="hpglpenoverlay"};NA.register(zae);var Xae=class extends Ky{static token="outputformat";token="outputformat"};NA.register(Xae);var $ae=class extends Ky{static token="drillshape";token="drillshape"};NA.register($ae);var Age=class extends Ky{static token="scaleselection";token="scaleselection"};NA.register(Age);var ege=class extends ur{static token="disableapertmacros";token="disableapertmacros"};NA.register(ege);var tge=class extends ur{static token="usegerberextensions";token="usegerberextensions"};NA.register(tge);var ige=class extends ur{static token="usegerberattributes";token="usegerberattributes"};NA.register(ige);var oge=class extends ur{static token="usegerberadvancedattributes";token="usegerberadvancedattributes"};NA.register(oge);var nge=class extends ur{static token="creategerberjobfile";token="creategerberjobfile"};NA.register(nge);var sge=class extends ur{static token="excludeedgelayer";token="excludeedgelayer"};NA.register(sge);var rge=class extends ur{static token="plotframeref";token="plotframeref"};NA.register(rge);var age=class extends ur{static token="viasonmask";token="viasonmask"};NA.register(age);var gge=class extends ur{static token="useauxorigin";token="useauxorigin"};NA.register(gge);var Ige=class extends ur{static token="pdf_front_fp_property_popups";token="pdf_front_fp_property_popups"};NA.register(Ige);var cge=class extends ur{static token="pdf_back_fp_property_popups";token="pdf_back_fp_property_popups"};NA.register(cge);var Bge=class extends ur{static token="pdf_metadata";token="pdf_metadata"};NA.register(Bge);var lge=class extends ur{static token="pdf_single_document";token="pdf_single_document"};NA.register(lge);var Cge=class extends ur{static token="dxfpolygonmode";token="dxfpolygonmode"};NA.register(Cge);var Qge=class extends ur{static token="dxfimperialunits";token="dxfimperialunits"};NA.register(Qge);var Ege=class extends ur{static token="dxfusepcbnewfont";token="dxfusepcbnewfont"};NA.register(Ege);var hge=class extends ur{static token="psnegative";token="psnegative"};NA.register(hge);var uge=class extends ur{static token="psa4output";token="psa4output"};NA.register(uge);var dge=class extends ur{static token="plotreference";token="plotreference"};NA.register(dge);var pge=class extends ur{static token="plotvalue";token="plotvalue"};NA.register(pge);var fge=class extends ur{static token="plotothertext";token="plotothertext"};NA.register(fge);var yge=class extends ur{static token="plotinvisibletext";token="plotinvisibletext"};NA.register(yge);var wge=class extends ur{static token="padsonsilk";token="padsonsilk"};NA.register(wge);var mge=class extends ur{static token="sketchpadsonfab";token="sketchpadsonfab"};NA.register(mge);var Dge=class extends ur{static token="plotpadnumbers";token="plotpadnumbers"};NA.register(Dge);var Sge=class extends ur{static token="hidednponfab";token="hidednponfab"};NA.register(Sge);var bge=class extends ur{static token="sketchdnponfab";token="sketchdnponfab"};NA.register(bge);var xge=class extends ur{static token="crossoutdnponfab";token="crossoutdnponfab"};NA.register(xge);var kge=class extends ur{static token="subtractmaskfromsilk";token="subtractmaskfromsilk"};NA.register(kge);var Gge=class extends ur{static token="plot_black_and_white";token="plot_black_and_white"};NA.register(Gge);var Fge=class extends ur{static token="mirror";token="mirror"};NA.register(Fge);var Rge=class extends ur{static token="outputdirectory";token="outputdirectory";quoteStringValue=!0};NA.register(Rge);var Mge=class extends ur{static token="plot_on_all_layers";token="plot_on_all_layers"};NA.register(Mge);var Nge=class extends ur{static token="plotinvisible";token="plotinvisible"};NA.register(Nge);var Mjt={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"},Njt=["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"],$fA=class ghe extends NA{static token="pcbplotparams";static parentToken="setup";token="pcbplotparams";_properties={};static fromSexprPrimitives(A){const e=new ghe,{propertyMap:i}=NA.parsePrimitivesToClassProperties(A,this.token);for(const[o,n]of Object.entries(i)){const s=Mjt[o];if(!s)throw new Error(`Unsupported pcbplotparams token: ${o}`);e._properties[s]=n}return e}getChildren(){const A=[];for(const e of Njt){const i=this._properties[e];i&&A.push(i)}return A}clearProperty(A){delete this._properties[A]}setStringProperty(A,e,i){if(e===void 0){this.clearProperty(A);return}this._properties[A]=new i(e)}setNumberProperty(A,e,i){if(e===void 0){this.clearProperty(A);return}this._properties[A]=new i(e)}setStringOrNumberProperty(A,e,i){if(e===void 0){this.clearProperty(A);return}this._properties[A]=new i(e)}get layerselection(){return this._properties.layerselection?.value}set layerselection(A){this.setStringOrNumberProperty("layerselection",A,Jae)}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,Tae)}get disableapertmacros(){return this._properties.disableapertmacros?.value}set disableapertmacros(A){this.setStringProperty("disableapertmacros",A,ege)}get usegerberextensions(){return this._properties.usegerberextensions?.value}set usegerberextensions(A){this.setStringProperty("usegerberextensions",A,tge)}get usegerberattributes(){return this._properties.usegerberattributes?.value}set usegerberattributes(A){this.setStringProperty("usegerberattributes",A,ige)}get usegerberadvancedattributes(){return this._properties.usegerberadvancedattributes?.value}set usegerberadvancedattributes(A){this.setStringProperty("usegerberadvancedattributes",A,oge)}get creategerberjobfile(){return this._properties.creategerberjobfile?.value}set creategerberjobfile(A){this.setStringProperty("creategerberjobfile",A,nge)}get excludeedgelayer(){return this._properties.excludeedgelayer?.value}set excludeedgelayer(A){this.setStringProperty("excludeedgelayer",A,sge)}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,Kae)}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,qae)}get svgprecision(){return this._properties.svgprecision?.value}set svgprecision(A){this.setNumberProperty("svgprecision",A,Pae)}get linewidth(){return this._properties.linewidth?.value}set linewidth(A){this.setNumberProperty("linewidth",A,Oae)}get plotframeref(){return this._properties.plotframeref?.value}set plotframeref(A){this.setStringProperty("plotframeref",A,rge)}get plotreference(){return this._properties.plotreference?.value}set plotreference(A){this.setStringProperty("plotreference",A,dge)}get plotvalue(){return this._properties.plotvalue?.value}set plotvalue(A){this.setStringProperty("plotvalue",A,pge)}get plotothertext(){return this._properties.plotothertext?.value}set plotothertext(A){this.setStringProperty("plotothertext",A,fge)}get plotinvisibletext(){return this._properties.plotinvisibletext?.value}set plotinvisibletext(A){this.setStringProperty("plotinvisibletext",A,yge)}get padsonsilk(){return this._properties.padsonsilk?.value}set padsonsilk(A){this.setStringProperty("padsonsilk",A,wge)}get plotpadnumbers(){return this._properties.plotpadnumbers?.value}set plotpadnumbers(A){this.setStringProperty("plotpadnumbers",A,Dge)}get sketchpadsonfab(){return this._properties.sketchpadsonfab?.value}set sketchpadsonfab(A){this.setStringProperty("sketchpadsonfab",A,mge)}get hidednponfab(){return this._properties.hidednponfab?.value}set hidednponfab(A){this.setStringProperty("hidednponfab",A,Sge)}get sketchdnponfab(){return this._properties.sketchdnponfab?.value}set sketchdnponfab(A){this.setStringProperty("sketchdnponfab",A,bge)}get crossoutdnponfab(){return this._properties.crossoutdnponfab?.value}set crossoutdnponfab(A){this.setStringProperty("crossoutdnponfab",A,xge)}get subtractmaskfromsilk(){return this._properties.subtractmaskfromsilk?.value}set subtractmaskfromsilk(A){this.setStringProperty("subtractmaskfromsilk",A,kge)}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,Gge)}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,Mge)}get plotinvisible(){return this._properties.plotinvisible?.value}set plotinvisible(A){this.setStringProperty("plotinvisible",A,Nge)}get mode(){return this._properties.mode?.value}set mode(A){this.setNumberProperty("mode",A,Wae)}get useauxorigin(){return this._properties.useauxorigin?.value}set useauxorigin(A){this.setStringProperty("useauxorigin",A,gge)}get viasonmask(){return this._properties.viasonmask?.value}set viasonmask(A){this.setStringProperty("viasonmask",A,age)}get hpglpennumber(){return this._properties.hpglpennumber?.value}set hpglpennumber(A){this.setNumberProperty("hpglpennumber",A,Zae)}get hpglpenspeed(){return this._properties.hpglpenspeed?.value}set hpglpenspeed(A){this.setNumberProperty("hpglpenspeed",A,Vae)}get hpglpendiameter(){return this._properties.hpglpendiameter?.value}set hpglpendiameter(A){this.setNumberProperty("hpglpendiameter",A,jae)}get hpglpenoverlay(){return this._properties.hpglpenoverlay?.value}set hpglpenoverlay(A){this.setNumberProperty("hpglpenoverlay",A,zae)}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,Ige)}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,cge)}get pdf_metadata(){return this._properties.pdf_metadata?.value}set pdf_metadata(A){this.setStringProperty("pdf_metadata",A,Bge)}get pdf_single_document(){return this._properties.pdf_single_document?.value}set pdf_single_document(A){this.setStringProperty("pdf_single_document",A,lge)}get dxfpolygonmode(){return this._properties.dxfpolygonmode?.value}set dxfpolygonmode(A){this.setStringProperty("dxfpolygonmode",A,Cge)}get dxfimperialunits(){return this._properties.dxfimperialunits?.value}set dxfimperialunits(A){this.setStringProperty("dxfimperialunits",A,Qge)}get dxfusepcbnewfont(){return this._properties.dxfusepcbnewfont?.value}set dxfusepcbnewfont(A){this.setStringProperty("dxfusepcbnewfont",A,Ege)}get psnegative(){return this._properties.psnegative?.value}set psnegative(A){this.setStringProperty("psnegative",A,hge)}get psa4output(){return this._properties.psa4output?.value}set psa4output(A){this.setStringProperty("psa4output",A,uge)}get mirror(){return this._properties.mirror?.value}set mirror(A){this.setStringProperty("mirror",A,Fge)}get outputformat(){return this._properties.outputformat?.value}set outputformat(A){this.setNumberProperty("outputformat",A,Xae)}get drillshape(){return this._properties.drillshape?.value}set drillshape(A){this.setNumberProperty("drillshape",A,$ae)}get scaleselection(){return this._properties.scaleselection?.value}set scaleselection(A){this.setNumberProperty("scaleselection",A,Age)}get outputdirectory(){return this._properties.outputdirectory?.value}set outputdirectory(A){this.setStringProperty("outputdirectory",A,Rge)}};NA.register($fA);var ZV=class extends YY{static parentToken="setup"},A0A=class extends ZV{static token="zone_45_only";token="zone_45_only"};NA.register(A0A);var e0A=class extends ZV{static token="allow_soldermask_bridges_in_footprints";token="allow_soldermask_bridges_in_footprints"};NA.register(e0A);var t0A=class extends ZV{static token="visible_elements";token="visible_elements"};NA.register(t0A);var i0A=class extends ZV{static token="uvias_allowed";token="uvias_allowed"};NA.register(i0A);var o0A=class Ihe extends NA{static token="tenting";static parentToken="setup";token="tenting";_sides=[];constructor(A=[]){super(),this.sides=A}static fromSexprPrimitives(A){const e=A.map(i=>Ei(i)).filter(i=>i!==void 0);return new Ihe(e)}get sides(){return[...this._sides]}set sides(A){this._sides=A.map(e=>String(e))}getChildren(){return[]}getString(){return this._sides.length===0?"(tenting)":`(tenting ${this._sides.join(" ")})`}};NA.register(o0A);var JY=class extends Fjt{static parentToken="setup"},_ge=class extends Rjt{static parentToken="setup"},n0A=class extends JY{static token="pcb_text_size";token="pcb_text_size"};NA.register(n0A);var s0A=class extends JY{static token="mod_text_size";token="mod_text_size"};NA.register(s0A);var r0A=class extends JY{static token="pad_size";token="pad_size"};NA.register(r0A);var a0A=class extends JY{static token="pad_to_paste_clearance_values";token="pad_to_paste_clearance_values"};NA.register(a0A);var g0A=class extends JY{static token="trace_width";token="trace_width"};NA.register(g0A);var I0A=class extends _ge{static token="aux_axis_origin";token="aux_axis_origin"};NA.register(I0A);var c0A=class extends _ge{static token="grid_origin";token="grid_origin"};NA.register(c0A);var il=class extends YY{static parentToken="setup";static parsePrimitiveValue(t){const A=si(t);if(A===void 0)throw new Error(`${this.name} expects a numeric value`);return A}},B0A=class extends il{static token="pad_to_mask_clearance";token="pad_to_mask_clearance"};NA.register(B0A);var l0A=class extends il{static token="solder_mask_min_width";token="solder_mask_min_width"};NA.register(l0A);var C0A=class extends il{static token="pad_to_paste_clearance";token="pad_to_paste_clearance"};NA.register(C0A);var Q0A=class extends il{static token="pad_to_paste_clearance_ratio";token="pad_to_paste_clearance_ratio"};NA.register(Q0A);var E0A=class extends il{static token="last_trace_width";token="last_trace_width"};NA.register(E0A);var h0A=class extends il{static token="trace_clearance";token="trace_clearance"};NA.register(h0A);var u0A=class extends il{static token="zone_clearance";token="zone_clearance"};NA.register(u0A);var d0A=class extends il{static token="trace_min";token="trace_min"};NA.register(d0A);var p0A=class extends il{static token="segment_width";token="segment_width"};NA.register(p0A);var f0A=class extends il{static token="edge_width";token="edge_width"};NA.register(f0A);var y0A=class extends il{static token="via_size";token="via_size"};NA.register(y0A);var w0A=class extends il{static token="via_drill";token="via_drill"};NA.register(w0A);var m0A=class extends il{static token="via_min_size";token="via_min_size"};NA.register(m0A);var D0A=class extends il{static token="via_min_drill";token="via_min_drill"};NA.register(D0A);var S0A=class extends il{static token="uvia_size";token="uvia_size"};NA.register(S0A);var b0A=class extends il{static token="uvia_drill";token="uvia_drill"};NA.register(b0A);var x0A=class extends il{static token="uvia_min_size";token="uvia_min_size"};NA.register(x0A);var k0A=class extends il{static token="uvia_min_drill";token="uvia_min_drill"};NA.register(k0A);var G0A=class extends il{static token="pcb_text_width";token="pcb_text_width"};NA.register(G0A);var F0A=class extends il{static token="mod_edge_width";token="mod_edge_width"};NA.register(F0A);var R0A=class extends il{static token="mod_text_width";token="mod_text_width"};NA.register(R0A);var M0A=class extends il{static token="pad_drill";token="pad_drill"};NA.register(M0A);var TY=class extends YY{static parentToken="stackup"},vge=class extends TY{static token="copper_finish";token="copper_finish";quoteStringValue=!0};NA.register(vge);var Uge=class extends TY{static token="dielectric_constraints";token="dielectric_constraints"};NA.register(Uge);var Lge=class extends TY{static token="edge_connector";token="edge_connector"};NA.register(Lge);var Hge=class extends TY{static token="castellated_pads";token="castellated_pads"};NA.register(Hge);var Yge=class extends TY{static token="edge_plating";token="edge_plating"};NA.register(Yge);var Lv=class extends YY{static parentToken="layer"},N0A=class extends Lv{static token="type";token="type";quoteStringValue=!0};NA.register(N0A);var _0A=class extends Lv{static token="color";token="color";quoteStringValue=!0};NA.register(_0A);var v0A=class extends Lv{static token="thickness";token="thickness";static parsePrimitiveValue(t){const A=si(t);if(A===void 0)throw new Error("Stackup layer thickness expects a numeric value");return A}};NA.register(v0A);var U0A=class extends Lv{static token="material";token="material";quoteStringValue=!0};NA.register(U0A);var L0A=class extends Lv{static token="epsilon_r";token="epsilon_r";static parsePrimitiveValue(t){const A=si(t);if(A===void 0)throw new Error("Stackup layer epsilon_r expects a numeric value");return A}};NA.register(L0A);var H0A=class extends Lv{static token="loss_tangent";token="loss_tangent";static parsePrimitiveValue(t){const A=si(t);if(A===void 0)throw new Error("Stackup layer loss_tangent expects a numeric value");return A}};NA.register(H0A);var Jge=class che extends NA{static token="layer";static parentToken="stackup";token="layer";_name;_number;_sxType;_sxColor;_sxThickness;_sxMaterial;_sxEpsilonR;_sxLossTangent;constructor(A,e={}){super(),this._name=A,this._number=e.number,this._sxType=e.type,this._sxColor=e.color,this._sxThickness=e.thickness,this._sxMaterial=e.material,this._sxEpsilonR=e.epsilonR,this._sxLossTangent=e.lossTangent}static fromSexprPrimitives(A){if(A.length===0)throw new Error("Stackup layer requires at least a name");const e=Ei(A[0]);if(e===void 0)throw new Error("Stackup layer name must be a string");let i=1,o;const n=A[i],s=si(n);s!==void 0&&(o=s,i+=1);const r=A.slice(i),{propertyMap:a}=NA.parsePrimitivesToClassProperties(r,this.token);return new che(e,{number:o,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 e=Ei(A);if(e===void 0)throw new Error("Stackup layer name must be a string");this._name=e}get number(){return this._number}set number(A){if(A===void 0){this._number=void 0;return}const e=si(A);if(e===void 0)throw new Error("Stackup layer number must be numeric");this._number=e}get type(){return this._sxType?.value}set type(A){if(A===void 0){this._sxType=void 0;return}this._sxType=A instanceof N0A?A:new N0A(A)}get color(){return this._sxColor?.value}set color(A){if(A===void 0){this._sxColor=void 0;return}this._sxColor=A instanceof _0A?A:new _0A(A)}get thickness(){return this._sxThickness?.value}set thickness(A){if(A===void 0){this._sxThickness=void 0;return}this._sxThickness=A instanceof v0A?A:new v0A(A)}get material(){return this._sxMaterial?.value}set material(A){if(A===void 0){this._sxMaterial=void 0;return}this._sxMaterial=A instanceof U0A?A:new U0A(A)}get epsilonR(){return this._sxEpsilonR?.value}set epsilonR(A){if(A===void 0){this._sxEpsilonR=void 0;return}this._sxEpsilonR=A instanceof L0A?A:new L0A(A)}get lossTangent(){return this._sxLossTangent?.value}set lossTangent(A){if(A===void 0){this._sxLossTangent=void 0;return}this._sxLossTangent=A instanceof H0A?A:new H0A(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 ${go(this._name)}${this._number!==void 0?` ${this._number}`:""}`,e=this.getChildren();if(e.length===0)return`${A})`;const i=[A];for(const o of e)i.push(o.getStringIndented());return i.push(")"),i.join(`
5758
5758
  `)}};NA.register(Jge);var Y0A=class Bhe 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:e,arrayPropertyMap:i}=NA.parsePrimitivesToClassProperties(A,this.token);return new Bhe({layers:i.layer??[],copperFinish:e.copper_finish,dielectricConstraints:e.dielectric_constraints,edgeConnector:e.edge_connector,castellatedPads:e.castellated_pads,edgePlating:e.edge_plating})}get layers(){return[...this._layers]}set layers(A){this._layers=A.map(e=>{if(!(e instanceof Jge))throw new Error("Stackup layers must be StackupLayer instances");return e})}get copperFinish(){return this._sxCopperFinish?.value}set copperFinish(A){this._sxCopperFinish=A?new vge(A):void 0}get dielectricConstraints(){return this._sxDielectricConstraints?.value}set dielectricConstraints(A){this._sxDielectricConstraints=A?new Uge(A):void 0}get edgeConnector(){return this._sxEdgeConnector?.value}set edgeConnector(A){this._sxEdgeConnector=A?new Lge(A):void 0}get castellatedPads(){return this._sxCastellatedPads?.value}set castellatedPads(A){this._sxCastellatedPads=A?new Hge(A):void 0}get edgePlating(){return this._sxEdgePlating?.value}set edgePlating(A){this._sxEdgePlating=A?new Yge(A):void 0}getChildren(){const A=[...this._layers],e=[this._sxCopperFinish,this._sxDielectricConstraints,this._sxEdgeConnector,this._sxCastellatedPads,this._sxEdgePlating];for(const i of e)i&&A.push(i);return A}};NA.register(Y0A);var _jt={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"},vjt=["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"],J0A=class lhe extends NA{static token="setup";token="setup";_properties={};static fromSexprPrimitives(A){const e=new lhe,{propertyMap:i}=NA.parsePrimitivesToClassProperties(A,this.token);for(const[o,n]of Object.entries(i)){const s=_jt[o];if(!s)throw new Error(`Unsupported setup property token: ${o}`);e._properties[s]=n}return e}getChildren(){const A=[];for(const e of vjt){const i=this._properties[e];i&&A.push(i)}return A}setProperty(A,e){if(e){this._properties[A]=e;return}delete this._properties[A]}setNumberProperty(A,e,i){if(e===void 0){delete this._properties[A];return}this._properties[A]=new i(e)}getPropertyInstance(A,e){const i=this._properties[A];return i instanceof e?i:void 0}get stackup(){return this.getPropertyInstance("stackup",Y0A)}set stackup(A){if(A!==void 0&&!(A instanceof Y0A))throw new Error("stackup must be a Stackup instance");this.setProperty("stackup",A)}get pcbPlotParams(){return this.getPropertyInstance("pcbPlotParams",$fA)}set pcbPlotParams(A){if(A!==void 0&&!(A instanceof $fA))throw new Error("pcbPlotParams must be a PcbPlotParams instance");this.setProperty("pcbPlotParams",A)}get padToMaskClearance(){return this.getPropertyInstance("padToMaskClearance",B0A)?.value}set padToMaskClearance(A){this.setNumberProperty("padToMaskClearance",A,B0A)}get solderMaskMinWidth(){return this.getPropertyInstance("solderMaskMinWidth",l0A)?.value}set solderMaskMinWidth(A){this.setNumberProperty("solderMaskMinWidth",A,l0A)}get padToPasteClearance(){return this.getPropertyInstance("padToPasteClearance",C0A)?.value}set padToPasteClearance(A){this.setNumberProperty("padToPasteClearance",A,C0A)}get padToPasteClearanceRatio(){return this.getPropertyInstance("padToPasteClearanceRatio",Q0A)?.value}set padToPasteClearanceRatio(A){this.setNumberProperty("padToPasteClearanceRatio",A,Q0A)}get lastTraceWidth(){return this.getPropertyInstance("lastTraceWidth",E0A)?.value}set lastTraceWidth(A){this.setNumberProperty("lastTraceWidth",A,E0A)}get traceClearance(){return this.getPropertyInstance("traceClearance",h0A)?.value}set traceClearance(A){this.setNumberProperty("traceClearance",A,h0A)}get zoneClearance(){return this.getPropertyInstance("zoneClearance",u0A)?.value}set zoneClearance(A){this.setNumberProperty("zoneClearance",A,u0A)}get zone45Only(){return this.getPropertyInstance("zone45Only",A0A)?.value}set zone45Only(A){this.setProperty("zone45Only",A===void 0?void 0:new A0A(A))}get traceMin(){return this.getPropertyInstance("traceMin",d0A)?.value}set traceMin(A){this.setNumberProperty("traceMin",A,d0A)}get segmentWidth(){return this.getPropertyInstance("segmentWidth",p0A)?.value}set segmentWidth(A){this.setNumberProperty("segmentWidth",A,p0A)}get edgeWidth(){return this.getPropertyInstance("edgeWidth",f0A)?.value}set edgeWidth(A){this.setNumberProperty("edgeWidth",A,f0A)}get viaSize(){return this.getPropertyInstance("viaSize",y0A)?.value}set viaSize(A){this.setNumberProperty("viaSize",A,y0A)}get viaDrill(){return this.getPropertyInstance("viaDrill",w0A)?.value}set viaDrill(A){this.setNumberProperty("viaDrill",A,w0A)}get viaMinSize(){return this.getPropertyInstance("viaMinSize",m0A)?.value}set viaMinSize(A){this.setNumberProperty("viaMinSize",A,m0A)}get viaMinDrill(){return this.getPropertyInstance("viaMinDrill",D0A)?.value}set viaMinDrill(A){this.setNumberProperty("viaMinDrill",A,D0A)}get uviasAllowed(){return this.getPropertyInstance("uviasAllowed",i0A)?.value}set uviasAllowed(A){this.setProperty("uviasAllowed",A===void 0?void 0:new i0A(A))}get uviaSize(){return this.getPropertyInstance("uviaSize",S0A)?.value}set uviaSize(A){this.setNumberProperty("uviaSize",A,S0A)}get uviaDrill(){return this.getPropertyInstance("uviaDrill",b0A)?.value}set uviaDrill(A){this.setNumberProperty("uviaDrill",A,b0A)}get uviaMinSize(){return this.getPropertyInstance("uviaMinSize",x0A)?.value}set uviaMinSize(A){this.setNumberProperty("uviaMinSize",A,x0A)}get uviaMinDrill(){return this.getPropertyInstance("uviaMinDrill",k0A)?.value}set uviaMinDrill(A){this.setNumberProperty("uviaMinDrill",A,k0A)}get pcbTextWidth(){return this.getPropertyInstance("pcbTextWidth",G0A)?.value}set pcbTextWidth(A){this.setNumberProperty("pcbTextWidth",A,G0A)}get pcbTextSize(){return this.getPropertyInstance("pcbTextSize",n0A)?.values}set pcbTextSize(A){if(A===void 0){delete this._properties.pcbTextSize;return}this.setProperty("pcbTextSize",new n0A(A))}get modEdgeWidth(){return this.getPropertyInstance("modEdgeWidth",F0A)?.value}set modEdgeWidth(A){this.setNumberProperty("modEdgeWidth",A,F0A)}get modTextSize(){return this.getPropertyInstance("modTextSize",s0A)?.values}set modTextSize(A){if(A===void 0){delete this._properties.modTextSize;return}this.setProperty("modTextSize",new s0A(A))}get modTextWidth(){return this.getPropertyInstance("modTextWidth",R0A)?.value}set modTextWidth(A){this.setNumberProperty("modTextWidth",A,R0A)}get padSize(){return this.getPropertyInstance("padSize",r0A)?.values}set padSize(A){if(A===void 0){delete this._properties.padSize;return}this.setProperty("padSize",new r0A(A))}get padDrill(){return this.getPropertyInstance("padDrill",M0A)?.value}set padDrill(A){this.setNumberProperty("padDrill",A,M0A)}get allowSoldermaskBridgesInFootprints(){return this.getPropertyInstance("allowSoldermaskBridgesInFootprints",e0A)?.value}set allowSoldermaskBridgesInFootprints(A){this.setProperty("allowSoldermaskBridgesInFootprints",A===void 0?void 0:new e0A(A))}get tenting(){return this.getPropertyInstance("tenting",o0A)?.sides}set tenting(A){if(A===void 0){delete this._properties.tenting;return}this.setProperty("tenting",new o0A(A))}get auxAxisOrigin(){const A=this.getPropertyInstance("auxAxisOrigin",I0A);if(A)return{x:A.x,y:A.y}}set auxAxisOrigin(A){if(!A){delete this._properties.auxAxisOrigin;return}this.setProperty("auxAxisOrigin",new I0A(A.x,A.y))}get gridOrigin(){const A=this.getPropertyInstance("gridOrigin",c0A);if(A)return{x:A.x,y:A.y}}set gridOrigin(A){if(!A){delete this._properties.gridOrigin;return}this.setProperty("gridOrigin",new c0A(A.x,A.y))}get visibleElements(){return this.getPropertyInstance("visibleElements",t0A)?.value}set visibleElements(A){this.setProperty("visibleElements",A===void 0?void 0:new t0A(A))}get padToPasteClearanceValues(){return this.getPropertyInstance("padToPasteClearanceValues",a0A)?.values}set padToPasteClearanceValues(A){if(A===void 0){delete this._properties.padToPasteClearanceValues;return}this.setProperty("padToPasteClearanceValues",new a0A(A))}get traceWidth(){return this.getPropertyInstance("traceWidth",g0A)?.values}set traceWidth(A){if(A===void 0){delete this._properties.traceWidth;return}this.setProperty("traceWidth",new g0A(A))}};NA.register(J0A);var Tge=class extends ta{static token="thickness";static parentToken="general";token="thickness"};NA.register(Tge);var Kge=class Che extends NA{static token="legacy_teardrops";static parentToken="general";token="legacy_teardrops";_enabled;constructor(A){super(),this._enabled=A}static fromSexprPrimitives(A){const e=Ei(A[0]);if(e===void 0)throw new Error("legacy_teardrops expects a string value");const i=/^(yes|true)$/iu.test(e);return new Che(i)}get enabled(){return this._enabled}set enabled(A){this._enabled=A}getChildren(){return[]}getString(){return`(legacy_teardrops ${this._enabled?"yes":"no"})`}};NA.register(Kge);var qge=new Set(["thickness","legacy_teardrops"]),T0A=class Qhe extends NA{static token="general";static parentToken="kicad_pcb";token="general";_sxThickness;_sxLegacyTeardrops;static fromSexprPrimitives(A){const e=new Qhe,{propertyMap:i,arrayPropertyMap:o}=NA.parsePrimitivesToClassProperties(A,this.token);for(const n of Object.keys(i))if(!qge.has(n))throw new Error(`general encountered unsupported child token "${n}"`);for(const[n,s]of Object.entries(o)){if(!qge.has(n))throw new Error(`general encountered unsupported child token "${n}"`);if(s.length>1)throw new Error(`general encountered repeated child token "${n}"`)}return e._sxThickness=o.thickness?.[0]??i.thickness,e._sxLegacyTeardrops=o.legacy_teardrops?.[0]??i.legacy_teardrops,e}get thickness(){return this._sxThickness?.value}set thickness(A){this._sxThickness=A===void 0?void 0:new Tge(A)}get legacyTeardrops(){return this._sxLegacyTeardrops?.enabled}set legacyTeardrops(A){if(A===void 0){this._sxLegacyTeardrops=void 0;return}this._sxLegacyTeardrops=new Kge(A)}getChildren(){const A=[];return this._sxThickness&&A.push(this._sxThickness),this._sxLegacyTeardrops&&A.push(this._sxLegacyTeardrops),A}};NA.register(T0A);var ol=class Ehe 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[e,i,o,n]=A,s=si(e),r=Ei(i),a=Ei(o),g=n===void 0?void 0:Ei(n);if(s===void 0||r===void 0||a===void 0)throw new Error(`layers entry is missing required values: ${JSON.stringify(A)}`);return new Ehe({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),go(this._name),this._type];return this._userName!==void 0&&A.push(go(this._userName)),`(${A.join(" ")})`}};NA.register(ol);var K0A=class hhe extends NA{static token="layers";static parentToken="kicad_pcb";token="layers";_definitions=[];static fromSexprPrimitives(A){const e=new hhe;return e._definitions=A.map(i=>ol.fromPrimitive(i)),e}get definitions(){return[...this._definitions]}set definitions(A){this._definitions=[...A]}getChildren(){return[...this._definitions]}};NA.register(K0A);var VV=class uhe extends NA{static token="net";static parentToken="kicad_pcb";token="net";_id;_name;constructor(A,e){super(),this._id=A,this._name=e}static fromSexprPrimitives(A){const e=si(A[0]),i=Ei(A[1]);if(e===void 0||i===void 0)throw new Error("net requires numeric id and string name");return new uhe(e,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} ${go(this._name)})`}};NA.register(VV);var q0A=class extends ta{static token="version";static parentToken="kicad_pcb";token="version"};NA.register(q0A);var Ujt=t=>/^[A-Za-z0-9._-]+$/.test(t),P0A=class extends Jy{static token="generator";static parentToken="kicad_pcb";token="generator";getString(){return`(generator ${Ujt(this.value)?this.value:go(this.value)})`}};NA.register(P0A);var Ljt=t=>/^[A-Za-z0-9._-]+$/.test(t),O0A=class extends Jy{static token="generator_version";static parentToken="kicad_pcb";token="generator_version";getString(){return`(generator_version ${Ljt(this.value)?this.value:go(this.value)})`}};NA.register(O0A);var W0A=class dhe extends NA{static token="net";static parentToken="via";token="net";_id;_name;constructor(A,e){super(),this._id=A,this._name=e}static fromSexprPrimitives(A){const e=si(A[0]);if(e===void 0)throw new Error("via net requires a numeric id");const i=A.length>1?Ei(A[1]):void 0;return new dhe(e,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} ${go(this._name)})`:`(net ${this._id})`}};NA.register(W0A);var Hjt=new Set(["locked","free","remove_unused_layers","keep_end_layers"]),Z0A=class phe 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 e=new phe;for(const i of A){if(typeof i=="string"){e.consumeBareToken(i);continue}if(!Array.isArray(i)||i.length===0)throw new Error(`via encountered unsupported primitive child: ${JSON.stringify(i)}`);const[o,...n]=i;if(typeof o!="string")throw new Error(`via encountered child with non-string token: ${JSON.stringify(i)}`);e.consumeNode(o,n)}return e}consumeBareToken(A){if(A==="blind"||A==="micro"){this._type=A;return}if(!Hjt.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,e){switch(A){case"type":{const i=Ei(e[0]);if(i===void 0)throw new Error("via type expects a string value");this._type=i;return}case"locked":this._locked=this.parseYesNo(e);return;case"free":this._free=this.parseYesNo(e);return;case"remove_unused_layers":this._removeUnusedLayers=this.parseYesNo(e);return;case"keep_end_layers":this._keepEndLayers=this.parseYesNo(e);return;case"at":{const i=NA.parsePrimitiveSexpr(["at",...e],{parentToken:this.token});if(!(i instanceof QI))throw new Error("via failed to parse at child");this._sxAt=i;return}case"size":{const i=si(e[0]);if(i===void 0)throw new Error("via size expects a numeric value");this._size=i;return}case"drill":{const i=si(e[0]);if(i===void 0)throw new Error("via drill expects a numeric value");this._drill=i;return}case"layers":{this._sxLayers=WV.fromSexprPrimitives(e);return}case"net":{this._sxNet=W0A.fromSexprPrimitives(e);return}case"teardrops":{this._sxTeardrops=lae.fromSexprPrimitives(e);return}case"uuid":{const i=Ei(e[0]);if(i===void 0)throw new Error("via uuid expects a string value");this._sxUuid=new Ni(i);return}case"tstamp":{const i=Ei(e[0]);if(i===void 0)throw new Error("via tstamp expects a string value");this._sxTstamp=new Vg(i);return}default:throw new Error(`via encountered unsupported child token "${A}"`)}}parseYesNo(A){if(A.length===0)return!0;const e=Ei(A[0]);if(e===void 0)throw new Error("Expected string when parsing via boolean child");return/^(yes|true)$/iu.test(e)}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?QI.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 WV?A:new WV(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 Ni?A:new Ni(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 Vg?A:new Vg(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(`
5759
- `)}};NA.register(Z0A);var V0A=class fhe 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 e=new fhe;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 o=NA.parsePrimitiveSexpr(i,{parentToken:this.token});if(!(o instanceof NA))throw new Error(`kicad_pcb expected SxClass child, received ${JSON.stringify(i)}`);e.consumeChild(o)}return e}consumeChild(A){if(A instanceof q0A){this._sxVersion=A;return}if(A instanceof P0A){this._sxGenerator=A;return}if(A instanceof O0A){this._sxGeneratorVersion=A;return}if(A instanceof T0A){this._sxGeneral=A;return}if(A instanceof MV){this._sxPaper=A;return}if(A instanceof Pse){this._sxTitleBlock=A;return}if(A instanceof K0A){this._sxLayers=A;return}if(A instanceof J0A){this._sxSetup=A;return}if(A instanceof _v){this._properties.push(A);return}if(A instanceof VV){this._nets.push(A);return}if(A instanceof LfA){this._footprints.push(A);return}if(A instanceof Wse){this._images.push(A);return}if(A instanceof XfA){this._segments.push(A);return}if(A instanceof PV){this._grLines.push(A);return}if(A instanceof WfA){this._grTexts.push(A);return}if(A instanceof Nae){this._grPolys.push(A);return}if(A instanceof Fae){this._grRects.push(A);return}if(A instanceof Z0A){this._vias.push(A);return}if(A instanceof Yae){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 q0A(A)}get generator(){return this._sxGenerator?.value}set generator(A){this._sxGenerator=A===void 0?void 0:new P0A(A)}get generatorVersion(){return this._sxGeneratorVersion?.value}set generatorVersion(A){this._sxGeneratorVersion=A===void 0?void 0:new O0A(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(V0A);var Pge=t=>NA.parse(t),Dh=class{MAX_ITERATIONS=1e3;iteration=0;finished=!1;input;ctx;constructor(t,A){this.input=t,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")}},Yjt=class extends Dh{_step(){const{kicadSch:t,schematicPaperSize:A}=this.ctx;if(!t)throw new Error("KicadSch instance not initialized in context");t.version=20250114;const e=new MV;e.size=A?.name??"A4",t.paper=e,t.uuid=new Ni(crypto.randomUUID()),this.finished=!0}getOutput(){return this.ctx.kicadSch}};function jV(t,A){if(t.manufacturer_part_number)return j0A(t.manufacturer_part_number);const e=Jjt(t.ftype),i=A?.footprinter_string;return j0A(i?`${e}_${i}`:e)}function Jjt(t){if(!t)return"component";let A=t.replace(/^simple_/,"");return A||"component"}function j0A(t){return t.replace(/[\\\/:\s]+/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"").trim()||"component"}function Oge(t){return t?t.match(/^([A-Za-z]+)/)?.[1]?.toUpperCase()??"U":"U"}var Wge={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"},Tjt=/^[A-Za-z]+\d+$/;function Zge(t){return t?Tjt.test(t.trim()):!1}function z0A(t){const A=t?.name;if(Zge(A))return Oge(A);const e=t?.ftype;return e&&Wge[e]?Wge[e]:Oge(A)}function Kjt(t){const A=t?.name;return Zge(A)?A.trim():`${z0A(t)}?`}function Vge(t){return t in BQ}function jge(t,A,e){if(t.type!=="source_component")return A.symbol_name?Vge(A.symbol_name)?`Device:${A.symbol_name}`:`Custom:${A.symbol_name}`:"Device:Component";if(A.symbol_name)return Vge(A.symbol_name)?`Device:${A.symbol_name}`:`Custom:${A.symbol_name}`;const i=jV(t,e);return`Device:${z0A(t)}_${i}`}var qjt=class extends Dh{_step(){const{kicadSch:t,db:A}=this.ctx,e=new Bre,i=[],o=A.schematic_component.list();for(const s of o){const r=this.createLibrarySymbolForComponent(s);r&&i.push(r)}const n=A.schematic_net_label?.list?.()||[];for(const s of n)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 I=this.createLibrarySymbolForNetLabel({netLabel:s,isPower:r??!1,isGround:a??!1});I&&i.push(I)}}e.symbols=i,t&&(t.libSymbols=e),this.finished=!0}createLibrarySymbolForComponent(t){const{db:A}=this.ctx,e=t.source_component_id?A.source_component.get(t.source_component_id):null;if(!e)return null;const i=A.cad_component?.list()?.find(g=>g.source_component_id===e.source_component_id),o=t.symbol_name||(e.ftype==="simple_chip"?`generic_chip_${t.source_component_id}`:null);if(!o)return null;const n=this.getSymbolData(o,t);if(!n)return null;const s=jge(e,t,i),r=e.ftype==="simple_chip",a=jV(e,i);return this.createLibrarySymbol({libId:s,symbolData:n,isChip:r,schematicComponent:t,description:this.getDescription(e),keywords:this.getKeywords(e),fpFilters:this.getFpFilters(e),footprintRef:a?`tscircuit:${a}`:"",referencePrefix:z0A(e)})}createLibrarySymbolForNetLabel({netLabel:t,isPower:A,isGround:e}){const i=t.symbol_name;if(!i)return null;const o=BQ[i];if(!o)return null;const n=`Custom:${i}`;return this.createLibrarySymbol({libId:n,symbolData:o,isChip:!1,schematicComponent:void 0,description:A?"Power net label":e?"Ground net label":"Net symbol",keywords:A?"power net":e?"ground net":"net",fpFilters:"",referencePrefix:n.split(":")[1]?.[0]||"U"})}getSymbolData(t,A){return t.startsWith("generic_chip_")?this.createGenericChipSymbolData(A,this.ctx.db):BQ[t]||null}createGenericChipSymbolData(t,A){const e=A.schematic_port.list().filter(r=>r.schematic_component_id===t.schematic_component_id).sort((r,a)=>(r.pin_number||0)-(a.pin_number||0)),i=t.size?.width||1.5,o=t.size?.height||1,n={type:"path",points:[{x:-i/2,y:-o/2},{x:i/2,y:-o/2},{x:i/2,y:o/2},{x:-i/2,y:o/2},{x:-i/2,y:-o/2}]},s=e.map(r=>{const a=r.center.x-t.center.x,g=r.center.y-t.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:[n],ports:s,size:{width:i,height:o}}}createLibrarySymbol({libId:t,symbolData:A,isChip:e,schematicComponent:i,description:o,keywords:n,fpFilters:s,footprintRef:r="",referencePrefix:a}){const g=new Nv({libraryId:t,excludeFromSim:!1,inBom:!0,onBoard:!0}),I=new Xse;I.hide=!e,g._sxPinNumbers=I;const c=new $se;c.offset=e?1.27:0,g._sxPinNames=c,this.addSymbolProperties({symbol:g,libId:t,description:o,keywords:n,fpFilters:s,footprintRef:r,referencePrefix:a});const B=this.createDrawingSubsymbol({libId:t,symbolData:A,isChip:e});g.subSymbols.push(B);const l=this.createPinSubsymbol({libId:t,symbolData:A,isChip:e,schematicComponent:i});return g.subSymbols.push(l),g._sxEmbeddedFonts=new _V(!1),g}addSymbolProperties({symbol:t,libId:A,description:e,keywords:i,fpFilters:o,footprintRef:n="",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:n,id:2,at:[-1.778,0,90],hide:!0},{key:"Datasheet",value:"~",id:3,at:[0,0,0],hide:!0},{key:"Description",value:e,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:o,id:6,at:[0,0,0],hide:!0}];for(const g of a)t.properties.push(new Ty({key:g.key,value:g.value,id:g.id,at:g.at,effects:this.createTextEffects(1.27,g.hide)}))}getDescription(t){return t?.ftype==="simple_resistor"?"Resistor":t?.ftype==="simple_capacitor"?"Capacitor":t?.ftype==="simple_chip"?"Integrated Circuit":"Component"}getKeywords(t){return t?.ftype==="simple_resistor"?"R res resistor":t?.ftype==="simple_capacitor"?"C cap capacitor":t?.ftype==="simple_chip"?"U IC chip":""}getFpFilters(t){return t?.ftype==="simple_resistor"?"R_*":t?.ftype==="simple_capacitor"?"C_*":(t?.ftype==="simple_chip","*")}createDrawingSubsymbol({libId:t,symbolData:A,isChip:e}){const i=new Nv({libraryId:`${t.split(":")[1]}_0_1`}),o=this.ctx.c2kMatSch?.a||15;for(const n of A.primitives||[])if(n.type==="path"&&n.points){const s=e?"background":"none",r=this.createPolylineFromPoints({points:n.points,scale:o,center:A.center,fillType:s});i.polylines.push(r)}return i}createPolylineFromPoints({points:t,scale:A,center:e,fillType:i}){const o=new Vse,n=e?.x??0,s=e?.y??0,r=ah(A,A),a=t.map(B=>{const l=Tt(r,{x:B.x-n,y:B.y-s});return new wE(l.x,l.y)}),g=new SQ(a);o.points=g;const I=new opA;I.width=.254,I.type="default",o.stroke=I;const c=new tre;return c.type=i,o.fill=c,o}createPinSubsymbol({libId:t,symbolData:A,isChip:e,schematicComponent:i}){const o=new Nv({libraryId:`${t.split(":")[1]}_1_1`});for(let n=0;n<(A.ports?.length||0);n++){const s=A.ports[n],r=new LV;r.pinElectricalType="passive",r.pinGraphicStyle="line";const{x:a,y:g,angle:I}=this.calculatePinPosition(s,A.center,A.size,e,n,i);r.at=[a,g,I],r.length=e?6:1.27;const c=new mD;c.size={height:1.27,width:1.27};const B=new wD({font:c}),l=s.labels?.[0]||"~";r._sxName=new GpA({value:l,effects:B});const C=new mD;C.size={height:1.27,width:1.27};const Q=new wD({font:C}),E=s.pinNumber?.toString()||`${n+1}`;r._sxNumber=new nre({value:E,effects:Q}),o.pins.push(r)}return o}calculatePinPosition(t,A,e,i,o,n){const s=this.ctx.c2kMatSch?.a||15;let r=t.x??0,a=t.y??0,g=!1;if(o!==void 0&&n){const d=this.ctx.db.schematic_port.list().filter(f=>f.schematic_component_id===n.schematic_component_id).sort((f,m)=>(f.pin_number||0)-(m.pin_number||0));if(d[o]){const f=d[o];r=f.center.x-n.center.x,a=f.center.y-n.center.y,g=!0}}let I,c;if(g)I=r,c=a;else{const d=A?.x??0,f=A?.y??0;I=r-d,c=a-f}const B=ah(s,s),l=Tt(B,{x:I,y:c});let C;if(i&&e){const d=e.width/2,f=e.height/2,m=Math.abs(I)/d,S=Math.abs(c)/f;C=m>S}else C=Math.abs(I)>Math.abs(c);let Q=l.x,E=l.y;const h=6;if(i&&e){const d=e.width/2*s,f=e.height/2*s;C?(Q=I>0?d:-d,E=c*s):(Q=I*s,E=c>0?f:-f)}let u=0;return C?I>0?i?(u=180,Q=Q+h):u=0:i?(u=0,Q=Q-h):u=180:c>0?i?(u=270,E=E+h):u=90:i?(u=90,E=E-h):u=270,{x:Q,y:E,angle:u}}createTextEffects(t,A){const e=new mD;return e.size={height:t,width:t},new wD({font:e,hiddenText:A})}getOutput(){if(!this.ctx.kicadSch)throw new Error("kicadSch is not initialized");return this.ctx.kicadSch}},Pjt=class extends Dh{_step(){const{kicadSch:t,db:A}=this.ctx,e=A.schematic_component.list();if(e.length===0){this.finished=!0;return}const i=[];for(const o of e){const n=o.source_component_id?A.source_component.get(o.source_component_id):null;if(!n||!this.ctx.c2kMatSch)continue;const{x:s,y:r}=Tt(this.ctx.c2kMatSch,{x:o.center.x,y:o.center.y}),a=crypto.randomUUID(),g=new Nv({at:[s,r,0],unit:1,excludeFromSim:!1,inBom:!0,onBoard:!0,dnp:!1,uuid:a,fieldsAutoplaced:!0}),I=A.cad_component?.list()?.find(_=>_.source_component_id===n.source_component_id),c=jge(n,o,I),B=new bpA(c);g._sxLibId=B;const{reference:l,value:C,description:Q}=this.getComponentMetadata(n),{refTextPos:E,valTextPos:h}=this.getTextPositions(o,{x:s,y:r}),u=new Ty({key:"Reference",value:l,id:0,at:[E.x,E.y,0],effects:this.createTextEffects(1.27,!1)}),d=n.ftype==="simple_chip",f=new Ty({key:"Value",value:C,id:1,at:[h.x,h.y,0],effects:this.createTextEffects(1.27,d)}),m=new Ty({key:"Footprint",value:"",id:2,at:[s-1.778,r,90],effects:this.createTextEffects(1.27,!0)}),S=new Ty({key:"Datasheet",value:"~",id:3,at:[s,r,0],effects:this.createTextEffects(1.27,!0)}),D=new Ty({key:"Description",value:Q,id:4,at:[s,r,0],effects:this.createTextEffects(1.27,!0)});g.properties.push(u,f,m,S,D);const x=A.schematic_port.list().filter(_=>_.schematic_component_id===o.schematic_component_id).sort((_,H)=>(_.pin_number||0)-(H.pin_number||0));for(const _ of x){const H=new LV;H.numberString=`${_.pin_number||1}`,H.uuid=crypto.randomUUID(),g.pins.push(H)}const F=new FpA,k=new MpA(""),v=new NpA(`/${t?.uuid?.value||""}`);v.reference=l,v.unit=1,k.paths.push(v),F.projects.push(k),g._sxInstances=F,i.push(g)}t&&(t.symbols=i),this.finished=!0}getTextPositions(t,A){const i=(this.ctx.db.schematic_text?.list?.()?.filter(l=>l.schematic_component_id===t.schematic_component_id)||[]).find(l=>l.text&&l.text.length>0);if(i&&this.ctx.c2kMatSch){const l=Tt(this.ctx.c2kMatSch,{x:i.position.x,y:i.position.y}),C={x:A.x,y:A.y+6};return{refTextPos:l,valTextPos:C}}const o=t.symbol_name,n=BQ[o];if(!n)return{refTextPos:{x:A.x,y:A.y-6},valTextPos:{x:A.x,y:A.y+6}};let s=null,r=null;for(const l of n.primitives)l.type==="text"&&(l.text==="{REF}"?s=l:l.text==="{VAL}"&&(r=l));const a=n.center||{x:0,y:0},I=o.includes("_down")||o.includes("_up")?.15:0,c=s&&this.ctx.c2kMatSch?Tt(this.ctx.c2kMatSch,{x:t.center.x+(s.x-a.x)+I,y:t.center.y+(s.y-a.y)}):{x:A.x,y:A.y-6},B=r&&this.ctx.c2kMatSch?Tt(this.ctx.c2kMatSch,{x:t.center.x+(r.x-a.x)+I,y:t.center.y+(r.y-a.y)}):{x:A.x,y:A.y+6};return{refTextPos:c,valTextPos:B}}getComponentMetadata(t){const A=t.name||"?",e=Kjt(t);return t.ftype==="simple_resistor"?{reference:e,value:t.display_resistance||"R",description:"Resistor"}:t.ftype==="simple_capacitor"?{reference:e,value:t.display_capacitance||"C",description:"Capacitor"}:t.ftype==="simple_inductor"?{reference:e,value:t.display_inductance||"L",description:"Inductor"}:t.ftype==="simple_diode"?{reference:e,value:"D",description:"Diode"}:t.ftype==="simple_chip"?{reference:e,value:A,description:"Integrated Circuit"}:t.ftype==="simple_led"?{reference:e,value:t.manufacturer_part_number||"",description:"LED"}:{reference:e,value:A,description:"Component"}}createTextEffects(t,A=!1,e){const i=new mD;i.size={height:t,width:t};const o=e?new FV({horizontal:e}):void 0;return new wD({font:i,hiddenText:A,justify:o})}getOutput(){if(!this.ctx.kicadSch)throw new Error("kicadSch is not initialized");return this.ctx.kicadSch}},Ojt=class extends Dh{_step(){const{kicadSch:t,db:A}=this.ctx,e=A.schematic_net_label?.list?.()||[];if(e.length===0){this.finished=!0;return}if(!this.ctx.c2kMatSch){this.finished=!0;return}const i=[],o=[];for(const n of e){const s=n.text||"",r=n.symbol_name;if(r){const a=this.createSymbolFromNetLabel(n,s,r);a&&i.push(a)}else{const a=this.createGlobalLabel(n,s);a&&o.push(a)}}if(t&&i.length>0){const n=t.symbols||[];t.symbols=[...n,...i]}t&&o.length>0&&(t.globalLabels=[...t.globalLabels||[],...o]),this.finished=!0}createSymbolFromNetLabel(t,A,e){if(!this.ctx.c2kMatSch)return null;const{x:i,y:o}=Tt(this.ctx.c2kMatSch,{x:t.anchor_position?.x??t.center?.x??0,y:t.anchor_position?.y??t.center?.y??0}),n=crypto.randomUUID(),s=new Nv({at:[i,o,0],unit:1,excludeFromSim:!1,inBom:!0,onBoard:!0,dnp:!1,uuid:n,fieldsAutoplaced:!0}),r=`Custom:${e}`,a=new bpA(r);s._sxLibId=a;const g=e.includes("_up")||e.toLowerCase().includes("vcc"),I=g?-4:4,c=g?-6:6,B=new Ty({key:"Reference",value:A,id:0,at:[i,o+I,0],effects:this.createTextEffects(1.27,!1)}),l=new Ty({key:"Value",value:A,id:1,at:[i,o+c,0],effects:this.createTextEffects(1.27,!0)}),C=new Ty({key:"Footprint",value:"",id:2,at:[i-1.778,o,90],effects:this.createTextEffects(1.27,!0)}),Q=new Ty({key:"Datasheet",value:"~",id:3,at:[i,o,0],effects:this.createTextEffects(1.27,!0)}),E=new Ty({key:"Description",value:`Power/Net symbol: ${A}`,id:4,at:[i,o,0],effects:this.createTextEffects(1.27,!0)});s.properties.push(B,l,C,Q,E);const h=new LV;h.numberString="1",h.uuid=crypto.randomUUID(),s.pins.push(h);const{kicadSch:u}=this.ctx,d=new FpA,f=new MpA(""),m=new NpA(`/${u?.uuid?.value||""}`);return m.reference=A,m.unit=1,f.paths.push(m),d.projects.push(f),s._sxInstances=d,s}createGlobalLabel(t,A){if(!this.ctx.c2kMatSch||!this.ctx.kicadSch)return null;const{x:e,y:i}=Tt(this.ctx.c2kMatSch,{x:t.anchor_position?.x??t.center?.x??0,y:t.anchor_position?.y??t.center?.y??0}),o=t.anchor_side||"left",s={left:0,right:180,top:270,bottom:90}[o]||0,a={left:{horizontal:"left"},right:{horizontal:"right"},top:{vertical:"top"},bottom:{vertical:"bottom"}}[o]||{},g=this.createTextEffects(1.27,!1);return Object.keys(a).length>0&&(g.justify=new FV(a)),new fre({value:A,at:[e,i,s],effects:g,uuid:crypto.randomUUID(),fieldsAutoplaced:!0})}createTextEffects(t,A=!1){const e=new mD;return e.size={height:t,width:t},new wD({font:e,hiddenText:A})}getOutput(){if(!this.ctx.kicadSch)throw new Error("kicadSch is not initialized");return this.ctx.kicadSch}},Wjt=class extends Dh{_step(){const{kicadSch:t,db:A}=this.ctx;if(!t)throw new Error("KicadSch instance not initialized in context");const e=A.schematic_trace.list();if(e.length===0){this.finished=!0;return}const i=[],o=[];for(const n of e){for(const s of n.edges){const r=this.createWireFromEdge(s);i.push(r)}for(const s of n.junctions){const r=this.createJunction(s);o.push(r)}}t.wires=i,t.junctions=o,this.finished=!0}createWireFromEdge(t){const A=new Cre;if(!this.ctx.c2kMatSch)throw new Error("Schematic transformation matrix not initialized in context");const e=Tt(this.ctx.c2kMatSch,{x:t.from.x,y:t.from.y}),i=Tt(this.ctx.c2kMatSch,{x:t.to.x,y:t.to.y}),o=e.x,n=e.y,s=i.x,r=i.y,a=new SQ([new wE(o,n),new wE(s,r)]);A.points=a;const g=new opA;return g.width=0,g.type="default",A.stroke=g,A.uuid=crypto.randomUUID(),A}createJunction(t){if(!this.ctx.c2kMatSch)throw new Error("Schematic transformation matrix not initialized in context");const{x:A,y:e}=Tt(this.ctx.c2kMatSch,{x:t.x,y:t.y}),i=new Qre({at:[A,e],diameter:0});return i.uuid=crypto.randomUUID(),i}getOutput(){return this.ctx.kicadSch}},Zjt=class extends Dh{_step(){const{kicadSch:t}=this.ctx;if(!t)throw new Error("KicadSch instance not initialized in context");const A=new LpA,e=new mre;e.value="/";const i=new Dre("1");e.pages=[i],A.paths=[e],t.sheetInstances=A,t.embeddedFonts=new _V(!1),this.finished=!0}getOutput(){return this.ctx.kicadSch}};function Vjt(t){const A=t.schematic_component.list(),e=t.schematic_trace.list();let i=1/0,o=1/0,n=-1/0,s=-1/0;for(const g of A){const I=g.size?.width??0,c=g.size?.height??0;i=Math.min(i,g.center.x-I/2),o=Math.min(o,g.center.y-c/2),n=Math.max(n,g.center.x+I/2),s=Math.max(s,g.center.y+c/2)}for(const g of e)for(const I of g.edges)i=Math.min(i,I.from.x,I.to.x),o=Math.min(o,I.from.y,I.to.y),n=Math.max(n,I.from.x,I.to.x),s=Math.max(s,I.from.y,I.to.y);i===1/0&&(i=0,o=0,n=0,s=0);const r=(i+n)/2,a=(o+s)/2;return{center:{x:r,y:a},bounds:{minX:i,minY:o,maxX:n,maxY:s}}}var zV=[{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 jjt(t,A,e=20){const i=t+2*e,o=A+2*e;for(let n=0;n<zV.length;n++){const s=zV[n];if(i<=s.width&&o<=s.height)return s}return zV[zV.length-1]}var zge=class{ctx;pipeline;currentStageIndex=0;finished=!1;get currentStage(){return this.pipeline[this.currentStageIndex]}constructor(t){const e=wa(t),{center:i,bounds:o}=Vjt(e),n=(o.maxX-o.minX)*15,s=(o.maxY-o.minY)*15,r=jjt(n,s),a=r.width/2,g=r.height/2;this.ctx={db:e,circuitJson:t,kicadSch:new YpA({generator:"circuit-json-to-kicad",generatorVersion:"0.0.1"}),schematicPaperSize:r,c2kMatSch:jB(Ir(a,g),ah(15,-15),Ir(-i.x,-i.y))},this.pipeline=[new Yjt(t,this.ctx),new qjt(t,this.ctx),new Pjt(t,this.ctx),new Ojt(t,this.ctx),new Wjt(t,this.ctx),new Zjt(t,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()}},zjt=class extends Dh{_step(){const{kicadPcb:t}=this.ctx;if(!t)throw new Error("KicadPcb instance not initialized in context");t.version=20241229;const A=new MV;A.size="A4",t.paper=A;const e=new T0A;e.thickness=1.6,t.general=e;const i=new J0A;i.padToMaskClearance=0,t.setup=i;const o=new K0A,n=[new ol({index:0,name:"F.Cu",type:"signal"}),new ol({index:2,name:"B.Cu",type:"signal"}),new ol({index:9,name:"F.Adhes",type:"user"}),new ol({index:11,name:"B.Adhes",type:"user"}),new ol({index:13,name:"F.Paste",type:"user"}),new ol({index:15,name:"B.Paste",type:"user"}),new ol({index:5,name:"F.SilkS",type:"user"}),new ol({index:7,name:"B.SilkS",type:"user"}),new ol({index:1,name:"F.Mask",type:"user"}),new ol({index:3,name:"B.Mask",type:"user"}),new ol({index:20,name:"Dwgs.User",type:"user"}),new ol({index:21,name:"Cmts.User",type:"user"}),new ol({index:22,name:"Eco1.User",type:"user"}),new ol({index:23,name:"Eco2.User",type:"user"}),new ol({index:24,name:"Edge.Cuts",type:"user"}),new ol({index:25,name:"Margin",type:"user"}),new ol({index:17,name:"B.CrtYd",type:"user"}),new ol({index:16,name:"F.CrtYd",type:"user"}),new ol({index:19,name:"B.Fab",type:"user"}),new ol({index:18,name:"F.Fab",type:"user"})];o.definitions=n,t.layers=o,this.finished=!0}getOutput(){return this.ctx.kicadPcb}},Xjt=class extends Dh{_step(){const{kicadPcb:t}=this.ctx;if(!t)throw new Error("KicadPcb instance not initialized in context");this.ctx.pcbNetMap=new Map;const A=new Map,e=this.ctx.db.source_net?.list()??[];for(const r of e){const a=r.subcircuit_connectivity_map_key||r.source_net_id;if(!a)continue;const g=r.name||r.source_net_id||"",I=g&&g.trim().length>0?g:a;A.set(a,I)}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 I=this.ctx.db.source_net?.get(g);if(I?.subcircuit_connectivity_map_key&&I.subcircuit_connectivity_map_key.length>0){a=I.subcircuit_connectivity_map_key;break}}if(a&&!A.has(a)){const g=r.display_name||r.source_trace_id||"",I=g&&g.trim().length>0?g:a;A.set(a,I)}}const o=Array.from(A.entries()).sort((r,a)=>r[0].localeCompare(a[0])),n=[];n.push(new VV(0,""));let s=1;for(const[r,a]of o){const g=new VV(s,a);n.push(g);const I={id:s,name:a};this.ctx.pcbNetMap.set(r,I),s++}t.nets=n,this.finished=!0}getOutput(){return this.ctx.kicadPcb}};function $jt(t){let A=0;for(let i=0;i<t.length;i++){const o=t.charCodeAt(i);A=(A<<5)-A+o,A=A&A}let e="";for(let i=0;i<4;i++){let o=A;for(let n=0;n<t.length;n++)o=(o<<5)-o+t.charCodeAt(n)+i*31,o=o&o;e+=Math.abs(o).toString(16).padStart(8,"0")}return e}function SD(t){const A=$jt(t);return`${A.slice(0,8)}-${A.slice(8,12)}-${A.slice(12,16)}-${A.slice(16,20)}-${A.slice(20,32)}`}function Azt({pcbPad:t,componentCenter:A,padNumber:e,componentRotation:i=0,netInfo:o,componentId:n}){let s,r;if("x"in t&&"y"in t)s=t.x,r=t.y;else if("points"in t&&Array.isArray(t.points)){const u=t.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=jB(i!==0?hm(i*Math.PI/180):{a:1,b:0,c:0,d:1,e:0,f:0},ah(1,-1),Ir(-A.x,-A.y)),g=Tt(a,{x:s,y:r}),c={top:"F.Cu",bottom:"B.Cu"}[t.layer]||"F.Cu";let B,l,C,Q;if(t.shape==="circle")B="circle",l=["radius"in t?t.radius*2:.5,"radius"in t?t.radius*2:.5];else if(t.shape==="polygon"&&"points"in t){const u=t.points,d=jB(ah(1,-1),Ir(-s,-r)),f=u.map(S=>{const D=Tt(d,{x:S.x,y:S.y});return new wE(D.x,D.y)}),m=new afA;m.contours=[new SQ(f)],m.width=0,m.filled=!0,Q=new eae,Q.addGraphic(m),B="custom",C=new Lre,C.anchor="circle",l=[.2,.2]}else B="rect",l=["width"in t?t.width:.5,"height"in t?t.height:.5];const E=`pad:${n}:${e}:${g.x},${g.y}`,h=new JV({number:String(e),padType:"smd",shape:B,at:[g.x,g.y,0],size:l,layers:[`${c}`,`${c==="F.Cu"?"F":"B"}.Paste`,`${c==="F.Cu"?"F":"B"}.Mask`],uuid:SD(E)});return C&&(h.options=C),Q&&(h.primitives=Q),o&&(h.net=new tfA(o.id,o.name)),h}function ezt({platedHole:t,componentCenter:A,padNumber:e,componentRotation:i=0,netInfo:o,componentId:n}){if(!("x"in t&&"y"in t))return null;const s=t.x-A.x,r=-(t.y-A.y),a=i!==0?hm(i*Math.PI/180):yd(),g=Tt(a,{x:s,y:r});let I="circle",c,B,l=0;const C="hole_offset_x"in t||"hole_offset_y"in t;let Q;if(C){const u={x:t.hole_offset_x??0,y:t.hole_offset_y??0};(u.x!==0||u.y!==0)&&(Q=Tt(a,{x:-u.x,y:u.y}))}t.shape==="circle"?(I="circle",c=[t.outer_diameter,t.outer_diameter],B=new DD({diameter:t.hole_diameter,offset:Q})):t.shape==="pill"||t.shape==="oval"?(I="oval",c=[t.outer_width,t.outer_height],B=new DD({oval:!0,diameter:t.hole_width,width:t.hole_height,offset:Q})):t.shape==="pill_hole_with_rect_pad"?(I="rect",c=[t.rect_pad_width,t.rect_pad_height],B=new DD({oval:!0,diameter:t.hole_width,width:t.hole_height,offset:Q})):t.shape==="circular_hole_with_rect_pad"?(I="rect",c=[t.rect_pad_width,t.rect_pad_height],B=new DD({diameter:t.hole_diameter,offset:Q})):t.shape==="rotated_pill_hole_with_rect_pad"?(I="rect",c=[t.rect_pad_width,t.rect_pad_height],B=new DD({oval:!0,diameter:t.hole_width,width:t.hole_height,offset:Q}),l=t.rect_ccw_rotation||0):(I="circle",c=[1.6,1.6],B=new DD({diameter:.8,offset:Q}));const E=`thruhole:${n}:${e}:${g.x},${g.y}`,h=new JV({number:String(e),padType:"thru_hole",shape:I,at:[g.x,g.y,l],size:c,drill:B,layers:["*.Cu","*.Mask"],removeUnusedLayers:!1,uuid:SD(E)});return o&&(h.net=new tfA(o.id,o.name)),h}function tzt({pcbHole:t,componentCenter:A,componentRotation:e=0}){if(!("x"in t&&"y"in t))return null;const i=t.x-A.x,o=-(t.y-A.y),n=e!==0?hm(e*Math.PI/180):yd(),s=Tt(n,{x:i,y:o});let r="circle",a,g;if(t.hole_shape==="circle"){r="circle";const I=t.hole_diameter;a=[I,I],g=new DD({diameter:I})}else if(t.hole_shape==="oval"){r="oval";const I=t.hole_width,c=t.hole_height;a=[I,c],g=new DD({oval:!0,diameter:I,width:c})}else{r="circle";const I="hole_diameter"in t?t.hole_diameter:1;a=[I,I],g=new DD({diameter:I})}return new JV({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 izt({textElement:t,componentCenter:A,componentRotation:e=0}){if(!t.text||!t.anchor_position)return null;const i=t.anchor_position.x-A.x,o=-(t.anchor_position.y-A.y),n=e!==0?hm(e*Math.PI/180):yd(),s=Tt(n,{x:i,y:o}),r={x:s.x,y:s.y},g={top:"F.SilkS",bottom:"B.SilkS"}[t.layer]||t.layer||"F.SilkS",I=(t.font_size||1)/1.5,c=new mD;c.size={width:I,height:I};const B=new wD({font:c}),l=t.ccw_rotation||0;return new hae({type:"user",text:t.text,position:{x:r.x,y:r.y,angle:l},layer:g,effects:B})}var ozt=class extends Dh{componentsProcessed=0;pcbComponents=[];getNetInfoForPcbPort(t){if(!t)return;const A=this.ctx.db.pcb_port?.get(t);if(!A)return;const e=A.source_port_id;if(!e)return;const i=this.ctx.db.source_port?.get(e);if(!i)return;const o=i.subcircuit_connectivity_map_key;if(o)return this.ctx.pcbNetMap?.get(o)}getCadComponentForPcbComponent(t){return(this.ctx.db.cad_component?.list()||[]).find(e=>e.pcb_component_id===t)}create3DModelsFromCadComponent(t,A){const e=[],i=t.model_step_url||t.model_wrl_url;if(!i)return e;const o=new _fA(i);if(t.position&&(o.offset={x:(t.position.x||0)-A.x,y:-((t.position.y||0)-A.y),z:t.position.z||0}),t.rotation&&(o.rotate={x:t.rotation.x||0,y:t.rotation.y||0,z:t.rotation.z||0}),t.model_unit_to_mm_scale_factor){const n=t.model_unit_to_mm_scale_factor;o.scale={x:n,y:n,z:n}}return e.push(o),e}constructor(t,A){super(t,A),this.pcbComponents=this.ctx.db.pcb_component.list()}_step(){const{kicadPcb:t,c2kMatPcb:A}=this.ctx;if(!t)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 e=this.pcbComponents[this.componentsProcessed],i=e.source_component_id?this.ctx.db.source_component.get(e.source_component_id):null,o=this.getCadComponentForPcbComponent(e.pcb_component_id),n=i?jV(i,o):"Unknown",s=Tt(A,{x:e.center.x,y:e.center.y}),r=`footprint:${e.pcb_component_id}:${s.x},${s.y}`,a=new LfA({libraryLink:`tscircuit:${n}`,layer:"F.Cu",at:[s.x,s.y,e.rotation||0],uuid:SD(r)}),g=a.fpTexts,I=this.ctx.db.pcb_silkscreen_text?.list().filter(h=>h.pcb_component_id===e.pcb_component_id)||[];for(const h of I){const u=izt({textElement:h,componentCenter:e.center,componentRotation:e.rotation||0});u&&(i?.name&&h.text===i.name&&(u.type="reference"),g.push(u))}a.fpTexts=g;const c=this.ctx.db.pcb_smtpad?.list().filter(h=>h.pcb_component_id===e.pcb_component_id)||[],B=a.fpPads;let l=1;for(const h of c){const u=this.getNetInfoForPcbPort(h.pcb_port_id),d=Azt({pcbPad:h,componentCenter:e.center,padNumber:l,componentRotation:e.rotation||0,netInfo:u,componentId:e.pcb_component_id});B.push(d),l++}const C=this.ctx.db.pcb_plated_hole?.list().filter(h=>h.pcb_component_id===e.pcb_component_id)||[];for(const h of C){const u=this.getNetInfoForPcbPort(h.pcb_port_id),d=ezt({platedHole:h,componentCenter:e.center,padNumber:l,componentRotation:e.rotation||0,netInfo:u,componentId:e.pcb_component_id});d&&(B.push(d),l++)}const Q=this.ctx.db.pcb_hole?.list().filter(h=>h.subcircuit_id===e.subcircuit_id)||[];for(const h of Q){const u=tzt({pcbHole:h,componentCenter:e.center,componentRotation:e.rotation||0});u&&B.push(u)}if(a.fpPads=B,o){const h=this.create3DModelsFromCadComponent(o,e.center);h.length>0&&(a.models=h)}const E=t.footprints;E.push(a),t.footprints=E,this.componentsProcessed++}getOutput(){return this.ctx.kicadPcb}},nzt=class extends Dh{tracesProcessed=0;pcbTraces=[];constructor(t,A){super(t,A),this.pcbTraces=this.ctx.db.pcb_trace.list()}_step(){const{kicadPcb:t,c2kMatPcb:A,pcbNetMap:e}=this.ctx;if(!t)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}for(let o=0;o<i.route.length-1;o++){const n=i.route[o],s=i.route[o+1],r=Tt(A,{x:n.x,y:n.y}),a=Tt(A,{x:s.x,y:s.y});let g;if(e){let Q=i.subcircuit_connectivity_map_key;if(!Q&&i.source_trace_id){const E=this.ctx.db.source_trace?.get(i.source_trace_id);if(E&&(Q=E.subcircuit_connectivity_map_key,!Q&&E.connected_source_net_ids?.length))for(const h of E.connected_source_net_ids){const u=this.ctx.db.source_net?.get(h);if(u?.subcircuit_connectivity_map_key){Q=u.subcircuit_connectivity_map_key;break}}}if(!Q&&typeof i.connection_name=="string"){const E=this.ctx.db.source_net?.get(i.connection_name);E?.subcircuit_connectivity_map_key&&(Q=E.subcircuit_connectivity_map_key)}Q&&(g=e.get(Q))}const c={top:"F.Cu",bottom:"B.Cu"}[n.layer]||n.layer||"F.Cu",B=`segment:${r.x},${r.y}:${a.x},${a.y}:${c}:${g?.id??0}`,l=new XfA({start:{x:r.x,y:r.y},end:{x:a.x,y:a.y},layer:c,width:i.width||.25,net:new OV(g?.id??0),uuid:SD(B)}),C=t.segments;C.push(l),t.segments=C}this.tracesProcessed++}getOutput(){return this.ctx.kicadPcb}},szt=class extends Dh{viasProcessed=0;pcbVias=[];constructor(t,A){super(t,A),this.pcbVias=this.ctx.db.pcb_via?.list()||[]}_step(){const{kicadPcb:t,c2kMatPcb:A,pcbNetMap:e}=this.ctx;if(!t)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],o=Tt(A,{x:i.x,y:i.y});let n;if(e){let g=i.subcircuit_connectivity_map_key;if(!g&&i.pcb_trace_id){const I=this.ctx.db.pcb_trace?.get(i.pcb_trace_id);if(I&&("subcircuit_connectivity_map_key"in I&&(g=I.subcircuit_connectivity_map_key),!g&&I.source_trace_id)){const c=this.ctx.db.source_trace?.get(I.source_trace_id);if(c&&("subcircuit_connectivity_map_key"in c&&(g=c.subcircuit_connectivity_map_key),!g&&c.connected_source_net_ids?.length))for(const B of c.connected_source_net_ids){const l=this.ctx.db.source_net?.get(B);if(l?.subcircuit_connectivity_map_key){g=l.subcircuit_connectivity_map_key;break}}}}if(!g&&i.connection_name){const I=this.ctx.db.source_net?.get(i.connection_name);I?.subcircuit_connectivity_map_key&&(g=I.subcircuit_connectivity_map_key)}g&&(n=e.get(g))}const s=`via:${o.x},${o.y}:${i.outer_diameter||.8}:${i.hole_diameter||.4}:${n?.id??0}`,r=new Z0A({at:[o.x,o.y],size:i.outer_diameter||.8,drill:i.hole_diameter||.4,layers:["F.Cu","B.Cu"],net:new W0A(n?.id??0),uuid:SD(s)}),a=t.vias;a.push(r),t.vias=a,this.viasProcessed++}getOutput(){return this.ctx.kicadPcb}};function rzt({textElement:t,c2kMatPcb:A}){if(!t.text||!t.anchor_position)return null;const e=Tt(A,{x:t.anchor_position.x,y:t.anchor_position.y}),o={top:"F.SilkS",bottom:"B.SilkS"}[t.layer]||t.layer||"F.SilkS",n=(t.font_size||1)/1.5,s=new mD;s.size={width:n,height:n};const r=new FV,a=t.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 wD({font:s});a!=="center"&&(g.justify=r);const I=t.ccw_rotation||0,c=new QI([e.x,e.y,I]),B=new WfA({text:t.text,layer:o,effects:g});return B.position=c,B}var azt=class extends Dh{_step(){const{kicadPcb:t,c2kMatPcb:A}=this.ctx;if(!t)throw new Error("KicadPcb instance not initialized in context");if(!A)throw new Error("PCB transformation matrix not initialized in context");const e=this.ctx.db.pcb_silkscreen_path?.list()||[];for(const n of e)if(!(!n.route||n.route.length<2))for(let s=0;s<n.route.length-1;s++){const r=n.route[s],a=n.route[s+1];if(!r||!a)continue;const g=Tt(A,{x:r.x,y:r.y}),I=Tt(A,{x:a.x,y:a.y}),B={top:"F.SilkS",bottom:"B.SilkS"}[n.layer]||n.layer||"F.SilkS",l=new PV({start:{x:g.x,y:g.y},end:{x:I.x,y:I.y},layer:B,width:n.stroke_width||.15}),C=t.graphicLines;C.push(l),t.graphicLines=C}const i=this.ctx.db.pcb_silkscreen_text?.list().filter(n=>!n.pcb_component_id)||[];for(const n of i){const s=rzt({textElement:n,c2kMatPcb:A});if(s){const r=t.graphicTexts;r.push(s),t.graphicTexts=r}}const o=this.ctx.db.pcb_board?.list()||[];if(o.length>0){const n=o[0];if(!n){this.finished=!0;return}let s;if(n.outline&&n.outline.length>0)s=n.outline;else{const a=n.width?n.width/2:0,g=n.height?n.height/2:0;s=[{x:n.center.x-a,y:n.center.y-g},{x:n.center.x+a,y:n.center.y-g},{x:n.center.x+a,y:n.center.y+g},{x:n.center.x-a,y:n.center.y+g}]}const r=s.map(a=>Tt(A,a));for(let a=0;a<r.length;a++){const g=r[a],I=r[(a+1)%r.length];if(!g||!I)continue;const c=new PV({start:{x:g.x,y:g.y},end:{x:I.x,y:I.y},layer:"Edge.Cuts",width:.1}),B=t.graphicLines;B.push(c),t.graphicLines=B}}this.finished=!0}getOutput(){return this.ctx.kicadPcb}},Xge=class{ctx;pipeline;currentStageIndex=0;finished=!1;get currentStage(){return this.pipeline[this.currentStageIndex]}constructor(t){this.ctx={db:wa(t),circuitJson:t,kicadPcb:new V0A({generator:"circuit-json-to-kicad",generatorVersion:"0.0.1"}),c2kMatPcb:jB(Ir(100,100),ah(1,-1))},this.pipeline=[new zjt(t,this.ctx),new Xjt(t,this.ctx),new ozt(t,this.ctx),new nzt(t,this.ctx),new szt(t,this.ctx),new azt(t,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()}},gzt=class{ctx;project;constructor(t,A={}){const e=A.projectName??t?.project?.name??"circuit-json-project",i=A.schematicFilename??`${e}.kicad_sch`,o=A.pcbFilename??`${e}.kicad_pcb`,n=new Date().toISOString();this.ctx={db:wa(t),circuitJson:t},this.project={version:1,head:{generator:"circuit-json-to-kicad",generator_version:"0.0.1",project_name:e,created:n,modified:n},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:o},sheets:[[Math.random().toString(36).substring(2,15),"Root"]]}}runUntilFinished(){}getOutput(){return this.project}getOutputString(){return`${JSON.stringify(this.project,null,2)}
5759
+ `)}};NA.register(Z0A);var V0A=class fhe 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 e=new fhe;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 o=NA.parsePrimitiveSexpr(i,{parentToken:this.token});if(!(o instanceof NA))throw new Error(`kicad_pcb expected SxClass child, received ${JSON.stringify(i)}`);e.consumeChild(o)}return e}consumeChild(A){if(A instanceof q0A){this._sxVersion=A;return}if(A instanceof P0A){this._sxGenerator=A;return}if(A instanceof O0A){this._sxGeneratorVersion=A;return}if(A instanceof T0A){this._sxGeneral=A;return}if(A instanceof MV){this._sxPaper=A;return}if(A instanceof Pse){this._sxTitleBlock=A;return}if(A instanceof K0A){this._sxLayers=A;return}if(A instanceof J0A){this._sxSetup=A;return}if(A instanceof _v){this._properties.push(A);return}if(A instanceof VV){this._nets.push(A);return}if(A instanceof LfA){this._footprints.push(A);return}if(A instanceof Wse){this._images.push(A);return}if(A instanceof XfA){this._segments.push(A);return}if(A instanceof PV){this._grLines.push(A);return}if(A instanceof WfA){this._grTexts.push(A);return}if(A instanceof Nae){this._grPolys.push(A);return}if(A instanceof Fae){this._grRects.push(A);return}if(A instanceof Z0A){this._vias.push(A);return}if(A instanceof Yae){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 q0A(A)}get generator(){return this._sxGenerator?.value}set generator(A){this._sxGenerator=A===void 0?void 0:new P0A(A)}get generatorVersion(){return this._sxGeneratorVersion?.value}set generatorVersion(A){this._sxGeneratorVersion=A===void 0?void 0:new O0A(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(V0A);var Pge=t=>NA.parse(t),Dh=class{MAX_ITERATIONS=1e3;iteration=0;finished=!1;input;ctx;constructor(t,A){this.input=t,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")}},Yjt=class extends Dh{_step(){const{kicadSch:t,schematicPaperSize:A}=this.ctx;if(!t)throw new Error("KicadSch instance not initialized in context");t.version=20250114;const e=new MV;e.size=A?.name??"A4",t.paper=e,t.uuid=new Ni(crypto.randomUUID()),this.finished=!0}getOutput(){return this.ctx.kicadSch}};function jV(t,A){if(t.manufacturer_part_number)return j0A(t.manufacturer_part_number);const e=Jjt(t.ftype),i=A?.footprinter_string;return j0A(i?`${e}_${i}`:e)}function Jjt(t){if(!t)return"component";let A=t.replace(/^simple_/,"");return A||"component"}function j0A(t){return t.replace(/[\\\/:\s]+/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"").trim()||"component"}function Oge(t){return t?t.match(/^([A-Za-z]+)/)?.[1]?.toUpperCase()??"U":"U"}var Wge={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"},Tjt=/^[A-Za-z]+\d+$/;function Zge(t){return t?Tjt.test(t.trim()):!1}function z0A(t){const A=t?.name;if(Zge(A))return Oge(A);const e=t?.ftype;return e&&Wge[e]?Wge[e]:Oge(A)}function Kjt(t){const A=t?.name;return Zge(A)?A.trim():`${z0A(t)}?`}function Vge(t){return t in BQ}function jge(t,A,e){if(t.type!=="source_component")return A.symbol_name?Vge(A.symbol_name)?`Device:${A.symbol_name}`:`Custom:${A.symbol_name}`:"Device:Component";if(A.symbol_name)return Vge(A.symbol_name)?`Device:${A.symbol_name}`:`Custom:${A.symbol_name}`;const i=jV(t,e);return`Device:${z0A(t)}_${i}`}var qjt=class extends Dh{_step(){const{kicadSch:t,db:A}=this.ctx,e=new Bre,i=[],o=A.schematic_component.list();for(const s of o){const r=this.createLibrarySymbolForComponent(s);r&&i.push(r)}const n=A.schematic_net_label?.list?.()||[];for(const s of n)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 I=this.createLibrarySymbolForNetLabel({netLabel:s,isPower:r??!1,isGround:a??!1});I&&i.push(I)}}e.symbols=i,t&&(t.libSymbols=e),this.finished=!0}createLibrarySymbolForComponent(t){const{db:A}=this.ctx,e=t.source_component_id?A.source_component.get(t.source_component_id):null;if(!e)return null;const i=A.cad_component?.list()?.find(g=>g.source_component_id===e.source_component_id),o=t.symbol_name||(e.ftype==="simple_chip"?`generic_chip_${t.source_component_id}`:null);if(!o)return null;const n=this.getSymbolData(o,t);if(!n)return null;const s=jge(e,t,i),r=e.ftype==="simple_chip",a=jV(e,i);return this.createLibrarySymbol({libId:s,symbolData:n,isChip:r,schematicComponent:t,description:this.getDescription(e),keywords:this.getKeywords(e),fpFilters:this.getFpFilters(e),footprintRef:a?`tscircuit:${a}`:"",referencePrefix:z0A(e)})}createLibrarySymbolForNetLabel({netLabel:t,isPower:A,isGround:e}){const i=t.symbol_name;if(!i)return null;const o=BQ[i];if(!o)return null;const n=`Custom:${i}`;return this.createLibrarySymbol({libId:n,symbolData:o,isChip:!1,schematicComponent:void 0,description:A?"Power net label":e?"Ground net label":"Net symbol",keywords:A?"power net":e?"ground net":"net",fpFilters:"",referencePrefix:n.split(":")[1]?.[0]||"U"})}getSymbolData(t,A){return t.startsWith("generic_chip_")?this.createGenericChipSymbolData(A,this.ctx.db):BQ[t]||null}createGenericChipSymbolData(t,A){const e=A.schematic_port.list().filter(r=>r.schematic_component_id===t.schematic_component_id).sort((r,a)=>(r.pin_number||0)-(a.pin_number||0)),i=t.size?.width||1.5,o=t.size?.height||1,n={type:"path",points:[{x:-i/2,y:-o/2},{x:i/2,y:-o/2},{x:i/2,y:o/2},{x:-i/2,y:o/2},{x:-i/2,y:-o/2}]},s=e.map(r=>{const a=r.center.x-t.center.x,g=r.center.y-t.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:[n],ports:s,size:{width:i,height:o}}}createLibrarySymbol({libId:t,symbolData:A,isChip:e,schematicComponent:i,description:o,keywords:n,fpFilters:s,footprintRef:r="",referencePrefix:a}){const g=new Nv({libraryId:t,excludeFromSim:!1,inBom:!0,onBoard:!0}),I=new Xse;I.hide=!e,g._sxPinNumbers=I;const c=new $se;c.offset=e?1.27:0,g._sxPinNames=c,this.addSymbolProperties({symbol:g,libId:t,description:o,keywords:n,fpFilters:s,footprintRef:r,referencePrefix:a});const B=this.createDrawingSubsymbol({libId:t,symbolData:A,isChip:e});g.subSymbols.push(B);const l=this.createPinSubsymbol({libId:t,symbolData:A,isChip:e,schematicComponent:i});return g.subSymbols.push(l),g._sxEmbeddedFonts=new _V(!1),g}addSymbolProperties({symbol:t,libId:A,description:e,keywords:i,fpFilters:o,footprintRef:n="",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:n,id:2,at:[-1.778,0,90],hide:!0},{key:"Datasheet",value:"~",id:3,at:[0,0,0],hide:!0},{key:"Description",value:e,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:o,id:6,at:[0,0,0],hide:!0}];for(const g of a)t.properties.push(new Ty({key:g.key,value:g.value,id:g.id,at:g.at,effects:this.createTextEffects(1.27,g.hide)}))}getDescription(t){return t?.ftype==="simple_resistor"?"Resistor":t?.ftype==="simple_capacitor"?"Capacitor":t?.ftype==="simple_chip"?"Integrated Circuit":"Component"}getKeywords(t){return t?.ftype==="simple_resistor"?"R res resistor":t?.ftype==="simple_capacitor"?"C cap capacitor":t?.ftype==="simple_chip"?"U IC chip":""}getFpFilters(t){return t?.ftype==="simple_resistor"?"R_*":t?.ftype==="simple_capacitor"?"C_*":(t?.ftype==="simple_chip","*")}createDrawingSubsymbol({libId:t,symbolData:A,isChip:e}){const i=new Nv({libraryId:`${t.split(":")[1]}_0_1`}),o=this.ctx.c2kMatSch?.a||15;for(const n of A.primitives||[])if(n.type==="path"&&n.points){const s=e?"background":"none",r=this.createPolylineFromPoints({points:n.points,scale:o,center:A.center,fillType:s});i.polylines.push(r)}return i}createPolylineFromPoints({points:t,scale:A,center:e,fillType:i}){const o=new Vse,n=e?.x??0,s=e?.y??0,r=ah(A,A),a=t.map(B=>{const l=Tt(r,{x:B.x-n,y:B.y-s});return new wE(l.x,l.y)}),g=new SQ(a);o.points=g;const I=new opA;I.width=.254,I.type="default",o.stroke=I;const c=new tre;return c.type=i,o.fill=c,o}createPinSubsymbol({libId:t,symbolData:A,isChip:e,schematicComponent:i}){const o=new Nv({libraryId:`${t.split(":")[1]}_1_1`});for(let n=0;n<(A.ports?.length||0);n++){const s=A.ports[n],r=new LV;r.pinElectricalType="passive",r.pinGraphicStyle="line";const{x:a,y:g,angle:I}=this.calculatePinPosition(s,A.center,A.size,e,n,i);r.at=[a,g,I],r.length=e?6:1.27;const c=new mD;c.size={height:1.27,width:1.27};const B=new wD({font:c}),l=s.labels?.[0]||"~";r._sxName=new GpA({value:l,effects:B});const C=new mD;C.size={height:1.27,width:1.27};const Q=new wD({font:C}),E=s.pinNumber?.toString()||`${n+1}`;r._sxNumber=new nre({value:E,effects:Q}),o.pins.push(r)}return o}calculatePinPosition(t,A,e,i,o,n){const s=this.ctx.c2kMatSch?.a||15;let r=t.x??0,a=t.y??0,g=!1;if(o!==void 0&&n){const d=this.ctx.db.schematic_port.list().filter(f=>f.schematic_component_id===n.schematic_component_id).sort((f,m)=>(f.pin_number||0)-(m.pin_number||0));if(d[o]){const f=d[o];r=f.center.x-n.center.x,a=f.center.y-n.center.y,g=!0}}let I,c;if(g)I=r,c=a;else{const d=A?.x??0,f=A?.y??0;I=r-d,c=a-f}const B=ah(s,s),l=Tt(B,{x:I,y:c});let C;if(i&&e){const d=e.width/2,f=e.height/2,m=Math.abs(I)/d,S=Math.abs(c)/f;C=m>S}else C=Math.abs(I)>Math.abs(c);let Q=l.x,E=l.y;const h=6;if(i&&e){const d=e.width/2*s,f=e.height/2*s;C?(Q=I>0?d:-d,E=c*s):(Q=I*s,E=c>0?f:-f)}let u=0;return C?I>0?i?(u=180,Q=Q+h):u=0:i?(u=0,Q=Q-h):u=180:c>0?i?(u=270,E=E+h):u=90:i?(u=90,E=E-h):u=270,{x:Q,y:E,angle:u}}createTextEffects(t,A){const e=new mD;return e.size={height:t,width:t},new wD({font:e,hiddenText:A})}getOutput(){if(!this.ctx.kicadSch)throw new Error("kicadSch is not initialized");return this.ctx.kicadSch}},Pjt=class extends Dh{_step(){const{kicadSch:t,db:A}=this.ctx,e=A.schematic_component.list();if(e.length===0){this.finished=!0;return}const i=[];for(const o of e){const n=o.source_component_id?A.source_component.get(o.source_component_id):null;if(!n||!this.ctx.c2kMatSch)continue;const{x:s,y:r}=Tt(this.ctx.c2kMatSch,{x:o.center.x,y:o.center.y}),a=crypto.randomUUID(),g=new Nv({at:[s,r,0],unit:1,excludeFromSim:!1,inBom:!0,onBoard:!0,dnp:!1,uuid:a,fieldsAutoplaced:!0}),I=A.cad_component?.list()?.find(_=>_.source_component_id===n.source_component_id),c=jge(n,o,I),B=new bpA(c);g._sxLibId=B;const{reference:l,value:C,description:Q}=this.getComponentMetadata(n),{refTextPos:E,valTextPos:h}=this.getTextPositions(o,{x:s,y:r}),u=new Ty({key:"Reference",value:l,id:0,at:[E.x,E.y,0],effects:this.createTextEffects(1.27,!1)}),d=n.ftype==="simple_chip",f=new Ty({key:"Value",value:C,id:1,at:[h.x,h.y,0],effects:this.createTextEffects(1.27,d)}),m=new Ty({key:"Footprint",value:"",id:2,at:[s-1.778,r,90],effects:this.createTextEffects(1.27,!0)}),S=new Ty({key:"Datasheet",value:"~",id:3,at:[s,r,0],effects:this.createTextEffects(1.27,!0)}),D=new Ty({key:"Description",value:Q,id:4,at:[s,r,0],effects:this.createTextEffects(1.27,!0)});g.properties.push(u,f,m,S,D);const x=A.schematic_port.list().filter(_=>_.schematic_component_id===o.schematic_component_id).sort((_,H)=>(_.pin_number||0)-(H.pin_number||0));for(const _ of x){const H=new LV;H.numberString=`${_.pin_number||1}`,H.uuid=crypto.randomUUID(),g.pins.push(H)}const F=new FpA,k=new MpA(""),v=new NpA(`/${t?.uuid?.value||""}`);v.reference=l,v.unit=1,k.paths.push(v),F.projects.push(k),g._sxInstances=F,i.push(g)}t&&(t.symbols=i),this.finished=!0}getTextPositions(t,A){const i=(this.ctx.db.schematic_text?.list?.()?.filter(l=>l.schematic_component_id===t.schematic_component_id)||[]).find(l=>l.text&&l.text.length>0);if(i&&this.ctx.c2kMatSch){const l=Tt(this.ctx.c2kMatSch,{x:i.position.x,y:i.position.y}),C={x:A.x,y:A.y+6};return{refTextPos:l,valTextPos:C}}const o=t.symbol_name,n=BQ[o];if(!n)return{refTextPos:{x:A.x,y:A.y-6},valTextPos:{x:A.x,y:A.y+6}};let s=null,r=null;for(const l of n.primitives)l.type==="text"&&(l.text==="{REF}"?s=l:l.text==="{VAL}"&&(r=l));const a=n.center||{x:0,y:0},I=o.includes("_down")||o.includes("_up")?.15:0,c=s&&this.ctx.c2kMatSch?Tt(this.ctx.c2kMatSch,{x:t.center.x+(s.x-a.x)+I,y:t.center.y+(s.y-a.y)}):{x:A.x,y:A.y-6},B=r&&this.ctx.c2kMatSch?Tt(this.ctx.c2kMatSch,{x:t.center.x+(r.x-a.x)+I,y:t.center.y+(r.y-a.y)}):{x:A.x,y:A.y+6};return{refTextPos:c,valTextPos:B}}getComponentMetadata(t){const A=t.name||"?",e=Kjt(t);return t.ftype==="simple_resistor"?{reference:e,value:t.display_resistance||"R",description:"Resistor"}:t.ftype==="simple_capacitor"?{reference:e,value:t.display_capacitance||"C",description:"Capacitor"}:t.ftype==="simple_inductor"?{reference:e,value:t.display_inductance||"L",description:"Inductor"}:t.ftype==="simple_diode"?{reference:e,value:"D",description:"Diode"}:t.ftype==="simple_chip"?{reference:e,value:A,description:"Integrated Circuit"}:t.ftype==="simple_led"?{reference:e,value:t.manufacturer_part_number||"",description:"LED"}:t.ftype==="simple_switch"?{reference:e,value:t.manufacturer_part_number||"",description:"Switch"}:{reference:e,value:A,description:"Component"}}createTextEffects(t,A=!1,e){const i=new mD;i.size={height:t,width:t};const o=e?new FV({horizontal:e}):void 0;return new wD({font:i,hiddenText:A,justify:o})}getOutput(){if(!this.ctx.kicadSch)throw new Error("kicadSch is not initialized");return this.ctx.kicadSch}},Ojt=class extends Dh{_step(){const{kicadSch:t,db:A}=this.ctx,e=A.schematic_net_label?.list?.()||[];if(e.length===0){this.finished=!0;return}if(!this.ctx.c2kMatSch){this.finished=!0;return}const i=[],o=[];for(const n of e){const s=n.text||"",r=n.symbol_name;if(r){const a=this.createSymbolFromNetLabel(n,s,r);a&&i.push(a)}else{const a=this.createGlobalLabel(n,s);a&&o.push(a)}}if(t&&i.length>0){const n=t.symbols||[];t.symbols=[...n,...i]}t&&o.length>0&&(t.globalLabels=[...t.globalLabels||[],...o]),this.finished=!0}createSymbolFromNetLabel(t,A,e){if(!this.ctx.c2kMatSch)return null;const{x:i,y:o}=Tt(this.ctx.c2kMatSch,{x:t.anchor_position?.x??t.center?.x??0,y:t.anchor_position?.y??t.center?.y??0}),n=crypto.randomUUID(),s=new Nv({at:[i,o,0],unit:1,excludeFromSim:!1,inBom:!0,onBoard:!0,dnp:!1,uuid:n,fieldsAutoplaced:!0}),r=`Custom:${e}`,a=new bpA(r);s._sxLibId=a;const g=e.includes("_up")||e.toLowerCase().includes("vcc"),I=g?-4:4,c=g?-6:6,B=new Ty({key:"Reference",value:A,id:0,at:[i,o+I,0],effects:this.createTextEffects(1.27,!1)}),l=new Ty({key:"Value",value:A,id:1,at:[i,o+c,0],effects:this.createTextEffects(1.27,!0)}),C=new Ty({key:"Footprint",value:"",id:2,at:[i-1.778,o,90],effects:this.createTextEffects(1.27,!0)}),Q=new Ty({key:"Datasheet",value:"~",id:3,at:[i,o,0],effects:this.createTextEffects(1.27,!0)}),E=new Ty({key:"Description",value:`Power/Net symbol: ${A}`,id:4,at:[i,o,0],effects:this.createTextEffects(1.27,!0)});s.properties.push(B,l,C,Q,E);const h=new LV;h.numberString="1",h.uuid=crypto.randomUUID(),s.pins.push(h);const{kicadSch:u}=this.ctx,d=new FpA,f=new MpA(""),m=new NpA(`/${u?.uuid?.value||""}`);return m.reference=A,m.unit=1,f.paths.push(m),d.projects.push(f),s._sxInstances=d,s}createGlobalLabel(t,A){if(!this.ctx.c2kMatSch||!this.ctx.kicadSch)return null;const{x:e,y:i}=Tt(this.ctx.c2kMatSch,{x:t.anchor_position?.x??t.center?.x??0,y:t.anchor_position?.y??t.center?.y??0}),o=t.anchor_side||"left",s={left:0,right:180,top:270,bottom:90}[o]||0,a={left:{horizontal:"left"},right:{horizontal:"right"},top:{vertical:"top"},bottom:{vertical:"bottom"}}[o]||{},g=this.createTextEffects(1.27,!1);return Object.keys(a).length>0&&(g.justify=new FV(a)),new fre({value:A,at:[e,i,s],effects:g,uuid:crypto.randomUUID(),fieldsAutoplaced:!0})}createTextEffects(t,A=!1){const e=new mD;return e.size={height:t,width:t},new wD({font:e,hiddenText:A})}getOutput(){if(!this.ctx.kicadSch)throw new Error("kicadSch is not initialized");return this.ctx.kicadSch}},Wjt=class extends Dh{_step(){const{kicadSch:t,db:A}=this.ctx;if(!t)throw new Error("KicadSch instance not initialized in context");const e=A.schematic_trace.list();if(e.length===0){this.finished=!0;return}const i=[],o=[];for(const n of e){for(const s of n.edges){const r=this.createWireFromEdge(s);i.push(r)}for(const s of n.junctions){const r=this.createJunction(s);o.push(r)}}t.wires=i,t.junctions=o,this.finished=!0}createWireFromEdge(t){const A=new Cre;if(!this.ctx.c2kMatSch)throw new Error("Schematic transformation matrix not initialized in context");const e=Tt(this.ctx.c2kMatSch,{x:t.from.x,y:t.from.y}),i=Tt(this.ctx.c2kMatSch,{x:t.to.x,y:t.to.y}),o=e.x,n=e.y,s=i.x,r=i.y,a=new SQ([new wE(o,n),new wE(s,r)]);A.points=a;const g=new opA;return g.width=0,g.type="default",A.stroke=g,A.uuid=crypto.randomUUID(),A}createJunction(t){if(!this.ctx.c2kMatSch)throw new Error("Schematic transformation matrix not initialized in context");const{x:A,y:e}=Tt(this.ctx.c2kMatSch,{x:t.x,y:t.y}),i=new Qre({at:[A,e],diameter:0});return i.uuid=crypto.randomUUID(),i}getOutput(){return this.ctx.kicadSch}},Zjt=class extends Dh{_step(){const{kicadSch:t}=this.ctx;if(!t)throw new Error("KicadSch instance not initialized in context");const A=new LpA,e=new mre;e.value="/";const i=new Dre("1");e.pages=[i],A.paths=[e],t.sheetInstances=A,t.embeddedFonts=new _V(!1),this.finished=!0}getOutput(){return this.ctx.kicadSch}};function Vjt(t){const A=t.schematic_component.list(),e=t.schematic_trace.list();let i=1/0,o=1/0,n=-1/0,s=-1/0;for(const g of A){const I=g.size?.width??0,c=g.size?.height??0;i=Math.min(i,g.center.x-I/2),o=Math.min(o,g.center.y-c/2),n=Math.max(n,g.center.x+I/2),s=Math.max(s,g.center.y+c/2)}for(const g of e)for(const I of g.edges)i=Math.min(i,I.from.x,I.to.x),o=Math.min(o,I.from.y,I.to.y),n=Math.max(n,I.from.x,I.to.x),s=Math.max(s,I.from.y,I.to.y);i===1/0&&(i=0,o=0,n=0,s=0);const r=(i+n)/2,a=(o+s)/2;return{center:{x:r,y:a},bounds:{minX:i,minY:o,maxX:n,maxY:s}}}var zV=[{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 jjt(t,A,e=20){const i=t+2*e,o=A+2*e;for(let n=0;n<zV.length;n++){const s=zV[n];if(i<=s.width&&o<=s.height)return s}return zV[zV.length-1]}var zge=class{ctx;pipeline;currentStageIndex=0;finished=!1;get currentStage(){return this.pipeline[this.currentStageIndex]}constructor(t){const e=wa(t),{center:i,bounds:o}=Vjt(e),n=(o.maxX-o.minX)*15,s=(o.maxY-o.minY)*15,r=jjt(n,s),a=r.width/2,g=r.height/2;this.ctx={db:e,circuitJson:t,kicadSch:new YpA({generator:"circuit-json-to-kicad",generatorVersion:"0.0.1"}),schematicPaperSize:r,c2kMatSch:jB(Ir(a,g),ah(15,-15),Ir(-i.x,-i.y))},this.pipeline=[new Yjt(t,this.ctx),new qjt(t,this.ctx),new Pjt(t,this.ctx),new Ojt(t,this.ctx),new Wjt(t,this.ctx),new Zjt(t,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()}},zjt=class extends Dh{_step(){const{kicadPcb:t}=this.ctx;if(!t)throw new Error("KicadPcb instance not initialized in context");t.version=20241229;const A=new MV;A.size="A4",t.paper=A;const e=new T0A;e.thickness=1.6,t.general=e;const i=new J0A;i.padToMaskClearance=0,t.setup=i;const o=new K0A,n=[new ol({index:0,name:"F.Cu",type:"signal"}),new ol({index:2,name:"B.Cu",type:"signal"}),new ol({index:9,name:"F.Adhes",type:"user"}),new ol({index:11,name:"B.Adhes",type:"user"}),new ol({index:13,name:"F.Paste",type:"user"}),new ol({index:15,name:"B.Paste",type:"user"}),new ol({index:5,name:"F.SilkS",type:"user"}),new ol({index:7,name:"B.SilkS",type:"user"}),new ol({index:1,name:"F.Mask",type:"user"}),new ol({index:3,name:"B.Mask",type:"user"}),new ol({index:20,name:"Dwgs.User",type:"user"}),new ol({index:21,name:"Cmts.User",type:"user"}),new ol({index:22,name:"Eco1.User",type:"user"}),new ol({index:23,name:"Eco2.User",type:"user"}),new ol({index:24,name:"Edge.Cuts",type:"user"}),new ol({index:25,name:"Margin",type:"user"}),new ol({index:17,name:"B.CrtYd",type:"user"}),new ol({index:16,name:"F.CrtYd",type:"user"}),new ol({index:19,name:"B.Fab",type:"user"}),new ol({index:18,name:"F.Fab",type:"user"})];o.definitions=n,t.layers=o,this.finished=!0}getOutput(){return this.ctx.kicadPcb}},Xjt=class extends Dh{_step(){const{kicadPcb:t}=this.ctx;if(!t)throw new Error("KicadPcb instance not initialized in context");this.ctx.pcbNetMap=new Map;const A=new Map,e=this.ctx.db.source_net?.list()??[];for(const r of e){const a=r.subcircuit_connectivity_map_key||r.source_net_id;if(!a)continue;const g=r.name||r.source_net_id||"",I=g&&g.trim().length>0?g:a;A.set(a,I)}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 I=this.ctx.db.source_net?.get(g);if(I?.subcircuit_connectivity_map_key&&I.subcircuit_connectivity_map_key.length>0){a=I.subcircuit_connectivity_map_key;break}}if(a&&!A.has(a)){const g=r.display_name||r.source_trace_id||"",I=g&&g.trim().length>0?g:a;A.set(a,I)}}const o=Array.from(A.entries()).sort((r,a)=>r[0].localeCompare(a[0])),n=[];n.push(new VV(0,""));let s=1;for(const[r,a]of o){const g=new VV(s,a);n.push(g);const I={id:s,name:a};this.ctx.pcbNetMap.set(r,I),s++}t.nets=n,this.finished=!0}getOutput(){return this.ctx.kicadPcb}};function $jt(t){let A=0;for(let i=0;i<t.length;i++){const o=t.charCodeAt(i);A=(A<<5)-A+o,A=A&A}let e="";for(let i=0;i<4;i++){let o=A;for(let n=0;n<t.length;n++)o=(o<<5)-o+t.charCodeAt(n)+i*31,o=o&o;e+=Math.abs(o).toString(16).padStart(8,"0")}return e}function SD(t){const A=$jt(t);return`${A.slice(0,8)}-${A.slice(8,12)}-${A.slice(12,16)}-${A.slice(16,20)}-${A.slice(20,32)}`}function Azt({pcbPad:t,componentCenter:A,padNumber:e,componentRotation:i=0,netInfo:o,componentId:n}){let s,r;if("x"in t&&"y"in t)s=t.x,r=t.y;else if("points"in t&&Array.isArray(t.points)){const u=t.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=jB(i!==0?hm(i*Math.PI/180):{a:1,b:0,c:0,d:1,e:0,f:0},ah(1,-1),Ir(-A.x,-A.y)),g=Tt(a,{x:s,y:r}),c={top:"F.Cu",bottom:"B.Cu"}[t.layer]||"F.Cu";let B,l,C,Q;if(t.shape==="circle")B="circle",l=["radius"in t?t.radius*2:.5,"radius"in t?t.radius*2:.5];else if(t.shape==="polygon"&&"points"in t){const u=t.points,d=jB(ah(1,-1),Ir(-s,-r)),f=u.map(S=>{const D=Tt(d,{x:S.x,y:S.y});return new wE(D.x,D.y)}),m=new afA;m.contours=[new SQ(f)],m.width=0,m.filled=!0,Q=new eae,Q.addGraphic(m),B="custom",C=new Lre,C.anchor="circle",l=[.2,.2]}else B="rect",l=["width"in t?t.width:.5,"height"in t?t.height:.5];const E=`pad:${n}:${e}:${g.x},${g.y}`,h=new JV({number:String(e),padType:"smd",shape:B,at:[g.x,g.y,0],size:l,layers:[`${c}`,`${c==="F.Cu"?"F":"B"}.Paste`,`${c==="F.Cu"?"F":"B"}.Mask`],uuid:SD(E)});return C&&(h.options=C),Q&&(h.primitives=Q),o&&(h.net=new tfA(o.id,o.name)),h}function ezt({platedHole:t,componentCenter:A,padNumber:e,componentRotation:i=0,netInfo:o,componentId:n}){if(!("x"in t&&"y"in t))return null;const s=t.x-A.x,r=-(t.y-A.y),a=i!==0?hm(i*Math.PI/180):yd(),g=Tt(a,{x:s,y:r});let I="circle",c,B,l=0;const C="hole_offset_x"in t||"hole_offset_y"in t;let Q;if(C){const u={x:t.hole_offset_x??0,y:t.hole_offset_y??0};(u.x!==0||u.y!==0)&&(Q=Tt(a,{x:-u.x,y:u.y}))}t.shape==="circle"?(I="circle",c=[t.outer_diameter,t.outer_diameter],B=new DD({diameter:t.hole_diameter,offset:Q})):t.shape==="pill"||t.shape==="oval"?(I="oval",c=[t.outer_width,t.outer_height],B=new DD({oval:!0,diameter:t.hole_width,width:t.hole_height,offset:Q})):t.shape==="pill_hole_with_rect_pad"?(I="rect",c=[t.rect_pad_width,t.rect_pad_height],B=new DD({oval:!0,diameter:t.hole_width,width:t.hole_height,offset:Q})):t.shape==="circular_hole_with_rect_pad"?(I="rect",c=[t.rect_pad_width,t.rect_pad_height],B=new DD({diameter:t.hole_diameter,offset:Q})):t.shape==="rotated_pill_hole_with_rect_pad"?(I="rect",c=[t.rect_pad_width,t.rect_pad_height],B=new DD({oval:!0,diameter:t.hole_width,width:t.hole_height,offset:Q}),l=t.rect_ccw_rotation||0):(I="circle",c=[1.6,1.6],B=new DD({diameter:.8,offset:Q}));const E=`thruhole:${n}:${e}:${g.x},${g.y}`,h=new JV({number:String(e),padType:"thru_hole",shape:I,at:[g.x,g.y,l],size:c,drill:B,layers:["*.Cu","*.Mask"],removeUnusedLayers:!1,uuid:SD(E)});return o&&(h.net=new tfA(o.id,o.name)),h}function tzt({pcbHole:t,componentCenter:A,componentRotation:e=0}){if(!("x"in t&&"y"in t))return null;const i=t.x-A.x,o=-(t.y-A.y),n=e!==0?hm(e*Math.PI/180):yd(),s=Tt(n,{x:i,y:o});let r="circle",a,g;if(t.hole_shape==="circle"){r="circle";const I=t.hole_diameter;a=[I,I],g=new DD({diameter:I})}else if(t.hole_shape==="oval"){r="oval";const I=t.hole_width,c=t.hole_height;a=[I,c],g=new DD({oval:!0,diameter:I,width:c})}else{r="circle";const I="hole_diameter"in t?t.hole_diameter:1;a=[I,I],g=new DD({diameter:I})}return new JV({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 izt({textElement:t,componentCenter:A,componentRotation:e=0}){if(!t.text||!t.anchor_position)return null;const i=t.anchor_position.x-A.x,o=-(t.anchor_position.y-A.y),n=e!==0?hm(e*Math.PI/180):yd(),s=Tt(n,{x:i,y:o}),r={x:s.x,y:s.y},g={top:"F.SilkS",bottom:"B.SilkS"}[t.layer]||t.layer||"F.SilkS",I=(t.font_size||1)/1.5,c=new mD;c.size={width:I,height:I};const B=new wD({font:c}),l=t.ccw_rotation||0;return new hae({type:"user",text:t.text,position:{x:r.x,y:r.y,angle:l},layer:g,effects:B})}var ozt=class extends Dh{componentsProcessed=0;pcbComponents=[];getNetInfoForPcbPort(t){if(!t)return;const A=this.ctx.db.pcb_port?.get(t);if(!A)return;const e=A.source_port_id;if(!e)return;const i=this.ctx.db.source_port?.get(e);if(!i)return;const o=i.subcircuit_connectivity_map_key;if(o)return this.ctx.pcbNetMap?.get(o)}getCadComponentForPcbComponent(t){return(this.ctx.db.cad_component?.list()||[]).find(e=>e.pcb_component_id===t)}create3DModelsFromCadComponent(t,A){const e=[],i=t.model_step_url||t.model_wrl_url;if(!i)return e;const o=new _fA(i);if(t.position&&(o.offset={x:(t.position.x||0)-A.x,y:-((t.position.y||0)-A.y),z:t.position.z||0}),t.rotation&&(o.rotate={x:t.rotation.x||0,y:t.rotation.y||0,z:t.rotation.z||0}),t.model_unit_to_mm_scale_factor){const n=t.model_unit_to_mm_scale_factor;o.scale={x:n,y:n,z:n}}return e.push(o),e}constructor(t,A){super(t,A),this.pcbComponents=this.ctx.db.pcb_component.list()}_step(){const{kicadPcb:t,c2kMatPcb:A}=this.ctx;if(!t)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 e=this.pcbComponents[this.componentsProcessed],i=e.source_component_id?this.ctx.db.source_component.get(e.source_component_id):null,o=this.getCadComponentForPcbComponent(e.pcb_component_id),n=i?jV(i,o):"Unknown",s=Tt(A,{x:e.center.x,y:e.center.y}),r=`footprint:${e.pcb_component_id}:${s.x},${s.y}`,a=new LfA({libraryLink:`tscircuit:${n}`,layer:"F.Cu",at:[s.x,s.y,e.rotation||0],uuid:SD(r)}),g=a.fpTexts,I=this.ctx.db.pcb_silkscreen_text?.list().filter(h=>h.pcb_component_id===e.pcb_component_id)||[];for(const h of I){const u=izt({textElement:h,componentCenter:e.center,componentRotation:e.rotation||0});u&&(i?.name&&h.text===i.name&&(u.type="reference"),g.push(u))}a.fpTexts=g;const c=this.ctx.db.pcb_smtpad?.list().filter(h=>h.pcb_component_id===e.pcb_component_id)||[],B=a.fpPads;let l=1;for(const h of c){const u=this.getNetInfoForPcbPort(h.pcb_port_id),d=Azt({pcbPad:h,componentCenter:e.center,padNumber:l,componentRotation:e.rotation||0,netInfo:u,componentId:e.pcb_component_id});B.push(d),l++}const C=this.ctx.db.pcb_plated_hole?.list().filter(h=>h.pcb_component_id===e.pcb_component_id)||[];for(const h of C){const u=this.getNetInfoForPcbPort(h.pcb_port_id),d=ezt({platedHole:h,componentCenter:e.center,padNumber:l,componentRotation:e.rotation||0,netInfo:u,componentId:e.pcb_component_id});d&&(B.push(d),l++)}const Q=this.ctx.db.pcb_hole?.list().filter(h=>h.subcircuit_id===e.subcircuit_id)||[];for(const h of Q){const u=tzt({pcbHole:h,componentCenter:e.center,componentRotation:e.rotation||0});u&&B.push(u)}if(a.fpPads=B,o){const h=this.create3DModelsFromCadComponent(o,e.center);h.length>0&&(a.models=h)}const E=t.footprints;E.push(a),t.footprints=E,this.componentsProcessed++}getOutput(){return this.ctx.kicadPcb}},nzt=class extends Dh{tracesProcessed=0;pcbTraces=[];constructor(t,A){super(t,A),this.pcbTraces=this.ctx.db.pcb_trace.list()}_step(){const{kicadPcb:t,c2kMatPcb:A,pcbNetMap:e}=this.ctx;if(!t)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}for(let o=0;o<i.route.length-1;o++){const n=i.route[o],s=i.route[o+1],r=Tt(A,{x:n.x,y:n.y}),a=Tt(A,{x:s.x,y:s.y});let g;if(e){let Q=i.subcircuit_connectivity_map_key;if(!Q&&i.source_trace_id){const E=this.ctx.db.source_trace?.get(i.source_trace_id);if(E&&(Q=E.subcircuit_connectivity_map_key,!Q&&E.connected_source_net_ids?.length))for(const h of E.connected_source_net_ids){const u=this.ctx.db.source_net?.get(h);if(u?.subcircuit_connectivity_map_key){Q=u.subcircuit_connectivity_map_key;break}}}if(!Q&&typeof i.connection_name=="string"){const E=this.ctx.db.source_net?.get(i.connection_name);E?.subcircuit_connectivity_map_key&&(Q=E.subcircuit_connectivity_map_key)}Q&&(g=e.get(Q))}const c={top:"F.Cu",bottom:"B.Cu"}[n.layer]||n.layer||"F.Cu",B=`segment:${r.x},${r.y}:${a.x},${a.y}:${c}:${g?.id??0}`,l=new XfA({start:{x:r.x,y:r.y},end:{x:a.x,y:a.y},layer:c,width:i.width||.25,net:new OV(g?.id??0),uuid:SD(B)}),C=t.segments;C.push(l),t.segments=C}this.tracesProcessed++}getOutput(){return this.ctx.kicadPcb}},szt=class extends Dh{viasProcessed=0;pcbVias=[];constructor(t,A){super(t,A),this.pcbVias=this.ctx.db.pcb_via?.list()||[]}_step(){const{kicadPcb:t,c2kMatPcb:A,pcbNetMap:e}=this.ctx;if(!t)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],o=Tt(A,{x:i.x,y:i.y});let n;if(e){let g=i.subcircuit_connectivity_map_key;if(!g&&i.pcb_trace_id){const I=this.ctx.db.pcb_trace?.get(i.pcb_trace_id);if(I&&("subcircuit_connectivity_map_key"in I&&(g=I.subcircuit_connectivity_map_key),!g&&I.source_trace_id)){const c=this.ctx.db.source_trace?.get(I.source_trace_id);if(c&&("subcircuit_connectivity_map_key"in c&&(g=c.subcircuit_connectivity_map_key),!g&&c.connected_source_net_ids?.length))for(const B of c.connected_source_net_ids){const l=this.ctx.db.source_net?.get(B);if(l?.subcircuit_connectivity_map_key){g=l.subcircuit_connectivity_map_key;break}}}}if(!g&&i.connection_name){const I=this.ctx.db.source_net?.get(i.connection_name);I?.subcircuit_connectivity_map_key&&(g=I.subcircuit_connectivity_map_key)}g&&(n=e.get(g))}const s=`via:${o.x},${o.y}:${i.outer_diameter||.8}:${i.hole_diameter||.4}:${n?.id??0}`,r=new Z0A({at:[o.x,o.y],size:i.outer_diameter||.8,drill:i.hole_diameter||.4,layers:["F.Cu","B.Cu"],net:new W0A(n?.id??0),uuid:SD(s)}),a=t.vias;a.push(r),t.vias=a,this.viasProcessed++}getOutput(){return this.ctx.kicadPcb}};function rzt({textElement:t,c2kMatPcb:A}){if(!t.text||!t.anchor_position)return null;const e=Tt(A,{x:t.anchor_position.x,y:t.anchor_position.y}),o={top:"F.SilkS",bottom:"B.SilkS"}[t.layer]||t.layer||"F.SilkS",n=(t.font_size||1)/1.5,s=new mD;s.size={width:n,height:n};const r=new FV,a=t.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 wD({font:s});a!=="center"&&(g.justify=r);const I=t.ccw_rotation||0,c=new QI([e.x,e.y,I]),B=new WfA({text:t.text,layer:o,effects:g});return B.position=c,B}var azt=class extends Dh{_step(){const{kicadPcb:t,c2kMatPcb:A}=this.ctx;if(!t)throw new Error("KicadPcb instance not initialized in context");if(!A)throw new Error("PCB transformation matrix not initialized in context");const e=this.ctx.db.pcb_silkscreen_path?.list()||[];for(const n of e)if(!(!n.route||n.route.length<2))for(let s=0;s<n.route.length-1;s++){const r=n.route[s],a=n.route[s+1];if(!r||!a)continue;const g=Tt(A,{x:r.x,y:r.y}),I=Tt(A,{x:a.x,y:a.y}),B={top:"F.SilkS",bottom:"B.SilkS"}[n.layer]||n.layer||"F.SilkS",l=new PV({start:{x:g.x,y:g.y},end:{x:I.x,y:I.y},layer:B,width:n.stroke_width||.15}),C=t.graphicLines;C.push(l),t.graphicLines=C}const i=this.ctx.db.pcb_silkscreen_text?.list().filter(n=>!n.pcb_component_id)||[];for(const n of i){const s=rzt({textElement:n,c2kMatPcb:A});if(s){const r=t.graphicTexts;r.push(s),t.graphicTexts=r}}const o=this.ctx.db.pcb_board?.list()||[];if(o.length>0){const n=o[0];if(!n){this.finished=!0;return}let s;if(n.outline&&n.outline.length>0)s=n.outline;else{const a=n.width?n.width/2:0,g=n.height?n.height/2:0;s=[{x:n.center.x-a,y:n.center.y-g},{x:n.center.x+a,y:n.center.y-g},{x:n.center.x+a,y:n.center.y+g},{x:n.center.x-a,y:n.center.y+g}]}const r=s.map(a=>Tt(A,a));for(let a=0;a<r.length;a++){const g=r[a],I=r[(a+1)%r.length];if(!g||!I)continue;const c=new PV({start:{x:g.x,y:g.y},end:{x:I.x,y:I.y},layer:"Edge.Cuts",width:.1}),B=t.graphicLines;B.push(c),t.graphicLines=B}}this.finished=!0}getOutput(){return this.ctx.kicadPcb}},Xge=class{ctx;pipeline;currentStageIndex=0;finished=!1;get currentStage(){return this.pipeline[this.currentStageIndex]}constructor(t){this.ctx={db:wa(t),circuitJson:t,kicadPcb:new V0A({generator:"circuit-json-to-kicad",generatorVersion:"0.0.1"}),c2kMatPcb:jB(Ir(100,100),ah(1,-1))},this.pipeline=[new zjt(t,this.ctx),new Xjt(t,this.ctx),new ozt(t,this.ctx),new nzt(t,this.ctx),new szt(t,this.ctx),new azt(t,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()}},gzt=class{ctx;project;constructor(t,A={}){const e=A.projectName??t?.project?.name??"circuit-json-project",i=A.schematicFilename??`${e}.kicad_sch`,o=A.pcbFilename??`${e}.kicad_pcb`,n=new Date().toISOString();this.ctx={db:wa(t),circuitJson:t},this.project={version:1,head:{generator:"circuit-json-to-kicad",generator_version:"0.0.1",project_name:e,created:n,modified:n},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:o},sheets:[[Math.random().toString(36).substring(2,15),"Root"]]}}runUntilFinished(){}getOutput(){return this.project}getOutputString(){return`${JSON.stringify(this.project,null,2)}
5760
5760
  `}},Izt=class extends Dh{_step(){const t=new zge(this.ctx.circuitJson);t.runUntilFinished(),this.ctx.kicadSchString=t.getOutputString();const A=new Xge(this.ctx.circuitJson);A.runUntilFinished(),this.ctx.kicadPcbString=A.getOutputString(),this.finished=!0}getOutput(){return this.ctx.libraryOutput}},czt=class extends Dh{isCustomSymbol(t){return t?.startsWith("Custom:")??!1}_step(){const t=this.ctx.kicadSchString,A=this.ctx.fpLibraryName??"tscircuit";if(!t)throw new Error("Schematic content not available. Run GenerateKicadSchAndPcbStage first.");const e=new Map;try{const o=Pge(t).find(r=>r instanceof YpA);if(!o){this.ctx.symbolEntries=[],this.finished=!0;return}const n=o.libSymbols;if(!n){this.ctx.symbolEntries=[],this.finished=!0;return}const s=n.symbols??[];for(const r of s){const a=this.isCustomSymbol(r.libraryId),g=this.sanitizeSymbolName(r.libraryId);e.has(g)||(r.libraryId=g,this.updateFootprintProperty(r,A),e.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(e.values()),this.finished=!0}updateFootprintProperty(t,A){const e=t.properties??[];for(const i of e)if(i.key==="Footprint"&&i.value){const o=i.value.split(":");o.length>1?i.value=`${A}:${o[1]}`:i.value.trim()&&(i.value=`${A}:${i.value}`)}}sanitizeSymbolName(t){if(!t)return"symbol";const A=t.split(":");return(A.length>1?A[1]:A[0])?.replace(/[\\\/]/g,"-").trim()||"symbol"}getOutput(){return this.ctx.libraryOutput}};function Bzt(t){const A=t.split(/[/\\]/);return A[A.length-1]||t}var lzt=class extends Dh{findCustomFootprintNames(){const t=new Set,A=this.ctx.db.cad_component?.list()??[],e=this.ctx.db.source_component;for(const i of A)if(!i.footprinter_string){const o=i.source_component_id?e?.get(i.source_component_id):null;if(o){const n=jV(o,i);t.add(n)}}return t}_step(){const t=this.ctx.kicadPcbString,A=this.ctx.fpLibraryName??"tscircuit";if(!t)throw new Error("PCB content not available. Run GenerateKicadSchAndPcbStage first.");const e=this.findCustomFootprintNames(),i=new Map;try{const n=Pge(t).find(r=>r instanceof V0A);if(!n){this.ctx.footprintEntries=[],this.finished=!0;return}const s=n.footprints??[];for(const r of s){const a=this.sanitizeFootprint({footprint:r,fpLibraryName:A,customFootprintNames:e});i.has(a.footprintName)||i.set(a.footprintName,a)}}catch(o){console.warn("Failed to parse PCB for footprint extraction:",o)}this.ctx.footprintEntries=Array.from(i.values()),this.finished=!0}sanitizeFootprint({footprint:t,fpLibraryName:A,customFootprintNames:e}){const o=(t.libraryLink??"footprint").split(":"),n=(o.length>1?o[1]:o[0])?.replace(/[\\\/]/g,"-").trim()||"footprint",s=!e.has(n);if(t.libraryLink=n,t.position=QI.from([0,0,0]),t.locked=!1,t.placed=!1,t.descr||(t.descr=""),t.tags||(t.tags=""),t.embeddedFonts||(t.embeddedFonts=new _V(!1)),!t.attr){const C=new Fre,Q=(t.fpPads??[]).map(E=>E.padType);Q.some(E=>E.includes("thru_hole"))?C.type="through_hole":Q.some(E=>E.includes("smd"))&&(C.type="smd"),t.attr=C}t.uuid=void 0,t.path=void 0,t.sheetfile=void 0,t.sheetname=void 0;const r=new mD;r.size={width:1.27,height:1.27},r.thickness=.15;const a=new wD({font:r});t.properties=[new _v({key:"Reference",value:"Ref**",position:[0,0,0],layer:"F.SilkS",uuid:SD(`${n}-property-Reference`),effects:a}),new _v({key:"Value",value:"Val**",position:[0,0,0],layer:"F.Fab",uuid:SD(`${n}-property-Value`),effects:a}),new _v({key:"Datasheet",value:"",position:[0,0,0],layer:"F.Fab",hidden:!0,uuid:SD(`${n}-property-Datasheet`),effects:a}),new _v({key:"Description",value:"",position:[0,0,0],layer:"F.Fab",hidden:!0,uuid:SD(`${n}-property-Description`),effects:a})];const g=t.fpTexts??[];for(const C of g)C.uuid=void 0,C.type==="reference"?C.text="REF**":C.type==="value"&&C.text.trim().length===0&&(C.text=n);t.fpTexts=g;const I=t.fpPads??[];for(let C=0;C<I.length;C++){const Q=I[C];Q&&(Q.uuid=SD(`${n}-pad-${Q.number??C}`),Q.net=void 0)}t.fpPads=I;const c=t.models??[],B=[],l=[];for(const C of c)if(C.path){const Q=Bzt(C.path),E=`../../3dmodels/${A}.3dshapes/${Q}`,h=new _fA(E);C.offset&&(h.offset=C.offset),C.scale&&(h.scale=C.scale),C.rotate&&(h.rotate=C.rotate),B.push(h),l.push(C.path)}return t.models=B,{footprintName:n,kicadModString:t.getString(),model3dSourcePaths:l,isBuiltin:s}}getOutput(){return this.ctx.libraryOutput}},Czt=20211014,Qzt="circuit-json-to-kicad",Ezt=class extends Dh{_step(){const t=this.ctx.symbolEntries??[],A=this.generateSymbolLibrary(t);this.ctx.libraryOutput||(this.ctx.libraryOutput={kicadSymString:"",symbols:[],footprints:[],fpLibTableString:"",symLibTableString:"",model3dSourcePaths:[]}),this.ctx.libraryOutput.kicadSymString=A,this.finished=!0}generateSymbolLibrary(t){return new Ire({version:Czt,generator:Qzt,symbols:t.map(e=>e.symbol)}).getString()}getOutput(){return this.ctx.libraryOutput}},hzt=class extends Dh{_step(){const t=this.ctx.libraryName??"tscircuit",A=this.ctx.fpLibraryName??"tscircuit",e=this.ctx.footprintEntries??[],i=this.ctx.symbolEntries??[],o=new Set;for(const r of e)for(const a of r.model3dSourcePaths)o.add(a);const n=this.generateFpLibTable(A),s=this.generateSymLibTable(t);this.ctx.libraryOutput||(this.ctx.libraryOutput={kicadSymString:"",symbols:[],footprints:[],fpLibTableString:"",symLibTableString:"",model3dSourcePaths:[]}),this.ctx.libraryOutput.symbols=i,this.ctx.libraryOutput.footprints=e,this.ctx.libraryOutput.fpLibTableString=n,this.ctx.libraryOutput.symLibTableString=s,this.ctx.libraryOutput.model3dSourcePaths=Array.from(o),this.finished=!0}generateFpLibTable(t){return`(fp_lib_table
5761
5761
  (version 7)
5762
5762
  (lib (name "${t}") (type "KiCad") (uri "\${KIPRJMOD}/${t}.pretty") (options "") (descr "Generated by circuit-json-to-kicad"))
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "main": "dist/index.js",
4
4
  "types": "dist/index.d.ts",
5
5
  "type": "module",
6
- "version": "0.0.1214",
6
+ "version": "0.0.1215",
7
7
  "repository": {
8
8
  "type": "git",
9
9
  "url": "https://github.com/tscircuit/tscircuit"
@@ -54,7 +54,7 @@
54
54
  "@tscircuit/checks": "^0.0.87",
55
55
  "@tscircuit/circuit-json-flex": "^0.0.3",
56
56
  "@tscircuit/circuit-json-util": "^0.0.77",
57
- "@tscircuit/cli": "^0.1.818",
57
+ "@tscircuit/cli": "^0.1.820",
58
58
  "@tscircuit/copper-pour-solver": "^0.0.14",
59
59
  "@tscircuit/core": "^0.0.988",
60
60
  "@tscircuit/eval": "^0.0.606",
@@ -65,7 +65,7 @@
65
65
  "@tscircuit/miniflex": "^0.0.4",
66
66
  "@tscircuit/ngspice-spice-engine": "^0.0.8",
67
67
  "@tscircuit/props": "^0.0.448",
68
- "@tscircuit/runframe": "^0.0.1528",
68
+ "@tscircuit/runframe": "^0.0.1529",
69
69
  "@tscircuit/schematic-match-adapt": "^0.0.16",
70
70
  "@tscircuit/schematic-trace-solver": "^v0.0.45",
71
71
  "@tscircuit/simple-3d-svg": "^0.0.41",