@tscircuit/runframe 0.0.1747 → 0.0.1749
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/standalone.min.js
CHANGED
|
@@ -5689,7 +5689,7 @@ test("${g} should solve problem correctly", () => {
|
|
|
5689
5689
|
// Add more specific assertions based on expected output
|
|
5690
5690
|
// expect(solver.netLabelPlacementSolver!.netLabelPlacements).toMatchInlineSnapshot()
|
|
5691
5691
|
})
|
|
5692
|
-
`,I=new Blob([c],{type:"text/plain"}),l=URL.createObjectURL(I),B=document.createElement("a");B.href=l,B.download=`${g}.test.ts`,B.click(),URL.revokeObjectURL(l)}catch(a){alert(`Error generating test.ts for ${t.constructor.name}: ${a instanceof Error?a.message:String(a)}`)}i(!1)};return W.jsxs("div",{className:`relative ${A}`,ref:n,children:[W.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&&W.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:[W.jsx("button",{className:"w-full text-left px-3 py-2 hover:bg-gray-100 text-xs",onClick:o,children:"Download JSON"}),W.jsx("button",{className:"w-full text-left px-3 py-2 hover:bg-gray-100 text-xs",onClick:s,children:"Download page.tsx"}),W.jsx("button",{className:"w-full text-left px-3 py-2 hover:bg-gray-100 text-xs",onClick:r,children:"Download test.ts"})]})]})},fEe=t=>t.activeSubSolver?[t,...fEe(t.activeSubSolver)]:[t],pni=({solver:t})=>{const A=fEe(t);return W.jsx("div",{className:"flex gap-1 items-center text-sm pt-1",children:A.map((e,i)=>W.jsxs("div",{className:"flex items-center",children:[i>0&&W.jsx("span",{className:"text-gray-400 mx-1",children:"→"}),W.jsx(dni,{solver:e})]},e.constructor.name))})},fni=({solver:t,triggerRender:A,animationSpeed:e=25,onSolverStarted:i,onSolverCompleted:n})=>{const[o,s]=V.useReducer(Q=>!Q,!1),r=V.useRef(void 0),a=()=>{!t.solved&&!t.failed&&(t.step(),A())},g=()=>{!t.solved&&!t.failed&&(i&&i(t),t.solve(),A(),n&&n(t))},c=()=>{o?(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(),n&&t.solved&&n(t);return}t.step(),A()},e))},I=()=>{const Q=t;if(Q.getCurrentPhase&&!t.solved&&!t.failed){const h=Q.getCurrentPhase();for(;Q.getCurrentPhase()===h&&!t.solved&&!t.failed;)t.step();A()}},l=()=>{if(t.solved||t.failed||o)return;const Q=window.prompt("Step until which iteration?",`${t.iterations}`);if(Q===null)return;const h=Number(Q);if(!Number.isFinite(h)){window.alert("Please enter a valid number for the iteration");return}for(;t.iterations<h&&!t.solved&&!t.failed;)t.step();A(),t.solved&&n&&n(t)};V.useEffect(()=>()=>{r.current&&clearInterval(r.current)},[]),V.useEffect(()=>{(t.solved||t.failed)&&o&&(r.current&&(clearInterval(r.current),r.current=void 0),s())},[t.solved,t.failed,o]);const B=t.getCurrentPhase!==void 0,C=B?t.getCurrentPhase():null;return W.jsxs("div",{className:"space-y-2 p-2 border-b",children:[W.jsx("div",{className:"flex items-center",children:W.jsx(pni,{solver:t})}),W.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[W.jsx("button",{onClick:a,disabled:t.solved||t.failed||o,className:"bg-blue-500 hover:bg-blue-600 disabled:bg-gray-300 text-white px-3 py-1 rounded text-sm",children:"Step"}),W.jsx("button",{onClick:g,disabled:t.solved||t.failed||o,className:"bg-green-500 hover:bg-green-600 disabled:bg-gray-300 text-white px-3 py-1 rounded text-sm",children:"Solve"}),W.jsx("button",{onClick:c,disabled:t.solved||t.failed,className:`px-3 py-1 rounded text-white text-sm ${o?"bg-red-500 hover:bg-red-600":"bg-yellow-500 hover:bg-yellow-600"} disabled:bg-gray-300`,children:o?"Stop":"Animate"}),W.jsx("button",{onClick:l,disabled:t.solved||t.failed||o,className:"bg-orange-500 hover:bg-orange-600 disabled:bg-gray-300 text-white px-3 py-1 rounded text-sm",children:"Step Until Iteration"}),B&&W.jsx("button",{onClick:I,disabled:t.solved||t.failed||o,className:"bg-purple-500 hover:bg-purple-600 disabled:bg-gray-300 text-white px-3 py-1 rounded text-sm",children:"Next Stage"}),W.jsxs("div",{className:"text-sm text-gray-600",children:["Iterations: ",t.iterations]}),t.timeToSolve!==void 0&&W.jsxs("div",{className:"text-sm text-gray-600",children:["Time: ",(t.timeToSolve/1e3).toFixed(3),"s"]}),C&&W.jsxs("div",{className:"text-sm text-gray-600",children:["Phase: ",W.jsx("span",{className:"font-medium",children:C})]}),t.solved&&W.jsx("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded text-sm",children:"Solved"}),t.failed&&W.jsx("div",{className:"px-2 py-1 bg-red-100 text-red-800 rounded text-sm",children:"Failed"})]}),t.error&&W.jsxs("div",{className:"text-red-600 text-sm",children:["Error: ",t.error]})]})},yni=(t,A,e)=>{const i=t.currentPipelineStepIndex;return A<i?"Completed":A===i&&t.activeSubSolver?t.activeSubSolver.failed?"Failed":"In Progress":"Not Started"},mni=(t,A)=>{const i=t.pipelineDef[A].solverName,n=yni(t,A),o=t[i],s=t.firstIterationOfPhase?.[i]??null,r=t.iterations;let a=0;if(n==="Completed"){const l=t.pipelineDef[A+1],B=l?t.firstIterationOfPhase?.[l.solverName]:void 0;B!==void 0&&s!==null?a=B-s:s!==null&&(a=r-s)}else n==="In Progress"&&s!==null&&(a=r-s);const g=t.timeSpentOnPhase?.[i]??0;let c=0;n==="Completed"?c=1:n==="In Progress"&&o&&(c=o.progress??0);const I=o?.stats??null;return{index:A,name:i,status:n,firstIteration:s,iterations:a,progress:c,timeSpent:g,stats:I&&Object.keys(I).length>0?I:null,solverInstance:o??null}},wni=({status:t})=>{const A={"Not Started":"text-blue-600","In Progress":"text-yellow-600",Completed:"text-green-600",Failed:"text-red-600"};return W.jsx("span",{className:`font-medium ${A[t]}`,children:t})},Dni=({progress:t})=>{if(t===0)return null;const A=Math.round(t*100);return W.jsxs("div",{className:"flex items-center gap-2",children:[W.jsx("div",{className:"w-20 h-2 bg-gray-200 rounded overflow-hidden",children:W.jsx("div",{className:"h-full bg-blue-500 transition-all duration-200",style:{width:`${A}%`}})}),W.jsxs("span",{className:"text-xs text-gray-500",children:[A,"%"]})]})},Sni=t=>Object.entries(t).map(([A,e])=>`${A}: ${e}`).join(", "),bni=({stats:t})=>{if(!t||Object.keys(t).length===0)return W.jsx("span",{children:"-"});const A=Object.entries(t),e=Sni(t);return W.jsxs("details",{className:"cursor-pointer",children:[W.jsx("summary",{className:"whitespace-nowrap overflow-hidden text-ellipsis max-w-[200px]",children:e}),W.jsx("div",{className:"mt-1 text-xs",children:A.map(([i,n])=>W.jsxs("div",{children:[i,": ",String(n)]},i))})]})},MmA=t=>{if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(MmA);const A={};for(const[e,i]of Object.entries(t))e.startsWith("_")||(A[e]=MmA(i));return A},xni=(t,A)=>{try{if(typeof t.getConstructorParams!="function"){alert(`getConstructorParams() is not implemented for ${A}`);return}const e=MmA(t.getConstructorParams()),i=new Blob([JSON.stringify(e,null,2)],{type:"application/json"}),n=URL.createObjectURL(i),o=document.createElement("a");o.href=n,o.download=`${A}_input.json`,o.click(),URL.revokeObjectURL(n)}catch(e){alert(`Error downloading input for ${A}: ${e instanceof Error?e.message:String(e)}`)}},_ni=({solver:t,onStepUntilPhase:A,onDownloadInput:e})=>{const i=t.pipelineDef.map((r,a)=>mni(t,a)),n=r=>{A?.(r)},o=r=>{r.solverInstance&&(e?e(r.solverInstance,r.name):xni(r.solverInstance,r.name))},s=r=>`${(r/1e3).toFixed(2)}s`;return W.jsxs("div",{className:"border-t border-gray-200",children:[W.jsx("div",{className:"px-4 py-2 bg-gray-50 border-b border-gray-200",children:W.jsx("h3",{className:"text-sm font-semibold text-gray-700",children:"Pipeline Steps"})}),W.jsx("div",{className:"overflow-x-auto",children:W.jsxs("table",{className:"w-full text-sm",children:[W.jsx("thead",{children:W.jsxs("tr",{className:"bg-gray-50 border-b border-gray-200",children:[W.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Step"}),W.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Status"}),W.jsxs("th",{className:"px-4 py-2 text-center font-semibold text-gray-700",children:["i",W.jsx("sub",{children:"0"})]}),W.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Iterations"}),W.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Progress"}),W.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Time"}),W.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Stats"}),W.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Input"})]})}),W.jsx("tbody",{children:i.map(r=>W.jsxs("tr",{className:`border-b border-gray-100 ${r.status==="In Progress"?"bg-yellow-50":""}`,children:[W.jsx("td",{className:"px-4 py-2",children:W.jsxs("div",{className:"flex items-center gap-2",children:[W.jsx("span",{className:"text-gray-400 w-6",children:String(r.index+1).padStart(2,"0")}),W.jsx("button",{onClick:()=>n(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:W.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",className:"w-4 h-4",children:W.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"})})}),W.jsx("span",{className:"font-medium text-gray-900",children:r.name})]})}),W.jsx("td",{className:"px-4 py-2",children:W.jsx(wni,{status:r.status})}),W.jsx("td",{className:"px-4 py-2 text-center text-gray-600",children:r.firstIteration!==null?r.firstIteration:""}),W.jsx("td",{className:"px-4 py-2 text-gray-600",children:r.iterations}),W.jsx("td",{className:"px-4 py-2",children:W.jsx(Dni,{progress:r.progress})}),W.jsx("td",{className:"px-4 py-2 text-gray-600",children:s(r.timeSpent)}),W.jsx("td",{className:"px-4 py-2 text-gray-500",children:W.jsx(bni,{stats:r.stats})}),W.jsx("td",{className:"px-4 py-2",children:r.solverInstance?W.jsxs("button",{onClick:()=>o(r),className:"flex items-center gap-1 text-blue-500 hover:text-blue-700",title:`Download input for ${r.name}`,children:[W.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",className:"w-4 h-4",children:W.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"})}),W.jsx("span",{children:"Input"})]}):null})]},r.name))})]})})]})},kni=class extends Qn.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 vni({graphics:t}){const A=t.points??[],e=t.lines??[],i=t.rects??[],n=t.circles??[],o=t.texts??[];let s=Number.POSITIVE_INFINITY,r=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY,g=Number.NEGATIVE_INFINITY;const c=(h,E)=>{typeof h=="number"&&(h<s&&(s=h),h>a&&(a=h)),typeof E=="number"&&(E<r&&(r=E),E>g&&(g=E))};for(const h of A)c(h.x,h.y);for(const h of e){const E=h.points??[];for(const u of E)c(u.x,u.y)}for(const h of i){const E=h.x??0,u=h.y??0,d=h.width??0,f=h.height??0;c(E,u),c(E+d,u+f)}for(const h of n){const E=h.x??0,u=h.y??0,d=h.radius??1;c(E-d,u-d),c(E+d,u+d)}for(const h of o)c(h.x,h.y);(!isFinite(s)||!isFinite(r)||!isFinite(a)||!isFinite(g))&&(s=-20,r=-20,a=20,g=20);const I=10,l=s-I,B=r-I,C=Math.max(1,a-s+2*I),Q=Math.max(1,g-r+2*I);return W.jsxs("svg",{className:"w-full h-[400px] bg-white",viewBox:`${l} ${B} ${C} ${Q}`,role:"img","aria-label":"Graphics fallback",children:[i.map((h,E)=>W.jsx("rect",{x:h.x??0,y:h.y??0,width:h.width??0,height:h.height??0,fill:"none",stroke:h.strokeColor??"black",strokeWidth:h.strokeWidth??1},`rect-${E}`)),e.map((h,E)=>W.jsx("polyline",{fill:"none",stroke:h.strokeColor??"black",strokeWidth:h.strokeWidth??1,points:(h.points??[]).map(u=>`${u.x??0},${u.y??0}`).join(" ")},`line-${E}`)),n.map((h,E)=>W.jsx("circle",{cx:h.x??0,cy:h.y??0,r:h.radius??1.5,fill:h.fillColor??"none",stroke:h.strokeColor??"black",strokeWidth:h.strokeWidth??1},`circle-${E}`)),A.map((h,E)=>W.jsx("circle",{cx:h.x??0,cy:h.y??0,r:h.radius??1.5,fill:h.color??"black"},`point-${E}`)),o.map((h,E)=>W.jsx("text",{x:h.x??0,y:h.y??0,fontSize:h.fontSize??10,fill:h.color??"black",children:h.text??""},`text-${E}`))]})}var Fni=({solver:t,animationSpeed:A=25,onSolverStarted:e,onSolverCompleted:i})=>{const[n,o]=V.useReducer(c=>c+1,0),s=V.useMemo(()=>{try{return t.visualize()||{points:[],lines:[],rects:[],circles:[]}}catch(c){return console.error("Visualization error:",c),{points:[],lines:[],rects:[],circles:[]}}},[t,n]),r=V.useMemo(()=>(s.rects?.length||0)===0&&(s.lines?.length||0)===0&&(s.points?.length||0)===0&&(s.circles?.length||0)===0,[s]);V.useEffect(()=>{if(!(typeof document>"u")&&!document.querySelector('script[src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"]')){const c=document.createElement("script");c.src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4",document.head.appendChild(c)}},[]);const a=t.pipelineDef!==void 0,g=c=>{const I=t;if(!t.solved&&!t.failed){for(;!t.solved&&!t.failed&&I.currentPipelineStepIndex<=I.pipelineDef.findIndex(l=>l.solverName===c);)t.step();o()}};return W.jsxs("div",{children:[W.jsx(fni,{solver:t,triggerRender:o,animationSpeed:A,onSolverStarted:e,onSolverCompleted:i}),r?W.jsx("div",{className:"p-4 text-gray-500",children:"No Graphics Yet"}):W.jsx(kni,{fallback:W.jsx(vni,{graphics:s}),children:W.jsx(uni,{graphics:s})}),a&&W.jsx(_ni,{solver:t,onStepUntilPhase:g})]})};const Mni=()=>{V.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)},[])},Rni=t=>t.toLowerCase().includes("pack")?yqt:t.toLowerCase().includes("rout")?bqt:rqt,Nni=({solverEvents:t=[]})=>{const[A,e]=V.useState(null);Mni();const i=V.useMemo(()=>{const r=new Map;for(const a of t){const g=`${a.componentName}-${a.solverName}`;r.set(g,a)}return r},[t]),n=V.useMemo(()=>Array.from(i.keys()),[i]),o=A?i.get(A):null,s=V.useMemo(()=>{if(!o)return{instance:null,error:null,classFound:!1};const r=WrA[o.solverName];if(!r)return{instance:null,error:`Solver class "${o.solverName}" not found in SOLVERS registry. Available: ${Object.keys(WrA).join(", ")}`,classFound:!1};try{const a=o.solverParams,g=a?.input!==void 0?a.input:a;return{instance:new r(g),error:null,classFound:!0}}catch(a){const g=a instanceof Error?a.message:String(a);return console.error("Failed to reconstruct solver:",a),{instance:null,error:`Failed to instantiate solver: ${g}`,classFound:!0}}},[o]);return t.length===0?W.jsx("div",{className:"rf-p-4",children:W.jsx("div",{className:"rf-bg-gray-50 rf-rounded-md rf-border rf-border-gray-200",children:W.jsxs("div",{className:"rf-p-4",children:[W.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-gray-800 rf-mb-3",children:"No Solvers Detected"}),W.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."})]})})}):W.jsxs("div",{className:"rf-flex rf-h-full rf-overflow-hidden",children:[W.jsxs("div",{className:"rf-w-64 rf-border-r rf-border-gray-200 rf-overflow-y-auto rf-flex-shrink-0",children:[W.jsxs("div",{className:"rf-text-xs rf-font-semibold rf-text-gray-500 rf-px-3 rf-py-2 rf-bg-gray-50 rf-border-b rf-border-gray-200",children:[n.length," ",n.length===1?"Solver":"Solvers"]}),n.map(r=>{const a=i.get(r),g=A===r;return W.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 c=Rni(a.solverName);return W.jsxs("div",{className:"rf-flex rf-items-center rf-gap-2",children:[W.jsx(c,{className:"rf-w-4 rf-h-4 rf-text-blue-500 rf-flex-shrink-0"}),W.jsxs("div",{className:"rf-flex-1 rf-min-w-0",children:[W.jsx("div",{className:"rf-text-sm rf-font-medium rf-text-gray-800 rf-truncate",children:a.componentName}),W.jsx("div",{className:"rf-text-xs rf-text-gray-500 rf-truncate",children:a.solverName})]})]})})()},r)})]}),W.jsx("div",{className:"rf-flex-1 rf-overflow-hidden",children:o?s.instance?W.jsx(Dm,{fallback:W.jsx("div",{className:"rf-p-4",children:W.jsxs("div",{className:"rf-bg-red-50 rf-rounded-md rf-border rf-border-red-200 rf-p-4",children:[W.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-red-800 rf-mb-2",children:"Error Loading Solver Debugger"}),W.jsxs("p",{className:"rf-text-sm rf-text-red-600",children:["Failed to render the solver debugger for"," ",o.solverName]})]})}),children:W.jsx(Fni,{solver:s.instance})}):W.jsxs("div",{className:"rf-p-4",children:[W.jsxs("div",{className:"rf-mb-4",children:[W.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-gray-800",children:o.solverName}),W.jsxs("p",{className:"rf-text-sm rf-text-gray-500",children:["Component: ",o.componentName]})]}),s.error&&W.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:W.jsx("p",{className:`rf-text-sm ${s.classFound?"rf-text-red-700":"rf-text-yellow-700"}`,children:s.error})}),W.jsxs("div",{className:"rf-border rf-border-gray-200 rf-rounded-md rf-overflow-hidden",children:[W.jsx("div",{className:"rf-px-3 rf-py-2 rf-bg-gray-50",children:W.jsx("span",{className:"rf-text-sm rf-font-medium rf-text-gray-700",children:"Solver Parameters"})}),W.jsx("div",{className:"rf-p-3 rf-bg-white rf-border-t rf-border-gray-200",children:W.jsx("pre",{className:"rf-text-xs rf-font-mono rf-text-gray-600 rf-whitespace-pre-wrap rf-overflow-x-auto",children:JSON.stringify(o.solverParams,null,2)})})]})]}):W.jsx("div",{className:"rf-flex rf-items-center rf-justify-center rf-h-full",children:W.jsx("p",{className:"rf-text-sm rf-text-gray-500",children:"Select a solver from the list to view details"})})})]})},yEe=({errorMessage:t,errorStack:A,circuitJsonErrors:e})=>{V.useEffect(()=>{if(t){const i=new Error(t);A&&(i.stack=A);try{qW.captureException(i)}catch{}}},[t,A]),V.useEffect(()=>{if(e&&e.length>0)for(const i of e){const n=new Error(i.message||"Circuit JSON Error");i.stack&&(n.stack=i.stack);try{qW.captureException(n,{error_type:i.type})}catch{}}},[e])},mEe="0.0.1746",Gni={version:mEe},Jz=M4A()(R4A(t=>({lastRunEvalVersion:void 0,setLastRunEvalVersion:A=>{t({lastRunEvalVersion:A})}}),{name:"runframe-runner-store"})),Lni=t=>{const[A,e]=V.useState([]),[i,n]=V.useState(null),[o,s]=V.useState(""),[r,a]=cG("eval-version-selection",null),g=Jz(B=>B.setLastRunEvalVersion),c=Jz(B=>B.lastRunEvalVersion);return V.useEffect(()=>{t&&fetch("https://data.jsdelivr.com/v1/package/npm/@tscircuit/eval").then(B=>B.json()).then(B=>{if(Array.isArray(B?.versions)){let C=[...B.versions];B.tags?.latest&&(n(B.tags.latest),C=C.filter(Q=>Q!==B.tags.latest)),e(C)}}).catch(()=>{})},[t]),V.useEffect(()=>{t&&(r?(window.TSCIRCUIT_LATEST_EVAL_VERSION=r,g(r)):i&&(window.TSCIRCUIT_LATEST_EVAL_VERSION=i,g(i)))},[t,r,i]),{versions:V.useMemo(()=>A.filter(B=>B.includes(o)).slice(0,50),[A,o]),latestVersion:i,lastRunEvalVersion:c,search:o,setSearch:s,selectVersion:B=>{a(B),s("")}}},Uni=({snippetNames:t,onSelect:A,onCancel:e,isOpen:i})=>{const[n,o]=V.useState(""),[s,r]=V.useState("");if(!i)return null;const a=t.filter(I=>I.toLowerCase().includes(s.toLowerCase())),g=s&&!t.includes(s),c=I=>{I.key==="Enter"&&(a.length===1?o(a[0]):g&&o(s))};return W.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:W.jsxs("div",{className:"rf-bg-white rf-rounded-lg rf-p-6 rf-w-96",children:[W.jsx("h2",{className:"rf-text-lg rf-font-semibold rf-mb-4",children:"Select Snippet"}),W.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:I=>r(I.target.value),onKeyDown:c}),W.jsxs("div",{className:"rf-h-60 rf-overflow-y-auto",children:[a.map(I=>W.jsx("button",{type:"button",className:`w-full text-left px-4 py-2 rounded hover:bg-gray-100 ${n===I?"bg-blue-50":""}`,onClick:()=>o(I),children:I},I)),g&&W.jsxs("button",{type:"button",className:`w-full text-left px-4 py-2 rounded hover:bg-gray-100 text-blue-500 ${n===s?"bg-blue-50":""}`,onClick:()=>o(s),children:['Create new "',s,'"']})]}),W.jsxs("div",{className:"rf-mt-4 rf-flex rf-justify-end rf-gap-2",children:[W.jsx("button",{type:"button",className:"rf-px-4 rf-py-2 rf-text-gray-600 rf-hover:text-gray-800",onClick:e,children:"Cancel"}),W.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:()=>n&&A(n),disabled:!n,children:n===s?`Create "${n}"`:`Save to ${n}`})]})]})})},Hni=t=>{const A=V.useRef(null),e=MI(i=>i.recentEvents);V.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 Yni(t){const A=Jni(t),e=V.forwardRef((i,n)=>{const{children:o,...s}=i,r=V.Children.toArray(o),a=r.find(Pni);if(a){const g=a.props.children,c=r.map(I=>I===a?V.Children.count(g)>1?V.Children.only(null):V.isValidElement(g)?g.props.children:null:I);return W.jsx(A,{...s,ref:n,children:V.isValidElement(g)?V.cloneElement(g,void 0,c):null})}return W.jsx(A,{...s,ref:n,children:o})});return e.displayName=`${t}.Slot`,e}function Jni(t){const A=V.forwardRef((e,i)=>{const{children:n,...o}=e;if(V.isValidElement(n)){const s=qni(n),r=Kni(o,n.props);return n.type!==V.Fragment&&(r.ref=i?_f(i,s):s),V.cloneElement(n,r)}return V.Children.count(n)>1?V.Children.only(null):null});return A.displayName=`${t}.SlotClone`,A}var Tni=Symbol("radix.slottable");function Pni(t){return V.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===Tni}function Kni(t,A){const e={...A};for(const i in A){const n=t[i],o=A[i];/^on[A-Z]/.test(i)?n&&o?e[i]=(...r)=>{const a=o(...r);return n(...r),a}:n&&(e[i]=n):i==="style"?e[i]={...n,...o}:i==="className"&&(e[i]=[n,o].filter(Boolean).join(" "))}return{...t,...e}}function qni(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",[wEe,DEe]=dw(Tz),[Oni,Ow]=wEe(Tz),SEe=t=>{const{__scopeDialog:A,children:e,open:i,defaultOpen:n,onOpenChange:o,modal:s=!0}=t,r=V.useRef(null),a=V.useRef(null),[g,c]=G_({prop:i,defaultProp:n??!1,onChange:o,caller:Tz});return W.jsx(Oni,{scope:A,triggerRef:r,contentRef:a,contentId:qE(),titleId:qE(),descriptionId:qE(),open:g,onOpenChange:c,onOpenToggle:V.useCallback(()=>c(I=>!I),[c]),modal:s,children:e})};SEe.displayName=Tz;var bEe="DialogTrigger",xEe=V.forwardRef((t,A)=>{const{__scopeDialog:e,...i}=t,n=Ow(bEe,e),o=RI(A,n.triggerRef);return W.jsx(Ag.button,{type:"button","aria-haspopup":"dialog","aria-expanded":n.open,"aria-controls":n.contentId,"data-state":GmA(n.open),...i,ref:o,onClick:Vn(t.onClick,n.onOpenToggle)})});xEe.displayName=bEe;var RmA="DialogPortal",[Wni,_Ee]=wEe(RmA,{forceMount:void 0}),kEe=t=>{const{__scopeDialog:A,forceMount:e,children:i,container:n}=t,o=Ow(RmA,A);return W.jsx(Wni,{scope:A,forceMount:e,children:V.Children.map(i,s=>W.jsx(q0,{present:e||o.open,children:W.jsx($9,{asChild:!0,container:n,children:s})}))})};kEe.displayName=RmA;var Pz="DialogOverlay",vEe=V.forwardRef((t,A)=>{const e=_Ee(Pz,t.__scopeDialog),{forceMount:i=e.forceMount,...n}=t,o=Ow(Pz,t.__scopeDialog);return o.modal?W.jsx(q0,{present:i||o.open,children:W.jsx(Vni,{...n,ref:A})}):null});vEe.displayName=Pz;var Zni=Yni("DialogOverlay.RemoveScroll"),Vni=V.forwardRef((t,A)=>{const{__scopeDialog:e,...i}=t,n=Ow(Pz,e);return W.jsx(rj,{as:Zni,allowPinchZoom:!0,shards:[n.contentRef],children:W.jsx(Ag.div,{"data-state":GmA(n.open),...i,ref:A,style:{pointerEvents:"auto",...i.style}})})}),PM="DialogContent",FEe=V.forwardRef((t,A)=>{const e=_Ee(PM,t.__scopeDialog),{forceMount:i=e.forceMount,...n}=t,o=Ow(PM,t.__scopeDialog);return W.jsx(q0,{present:i||o.open,children:o.modal?W.jsx(jni,{...n,ref:A}):W.jsx(zni,{...n,ref:A})})});FEe.displayName=PM;var jni=V.forwardRef((t,A)=>{const e=Ow(PM,t.__scopeDialog),i=V.useRef(null),n=RI(A,e.contentRef,i);return V.useEffect(()=>{const o=i.current;if(o)return jfA(o)},[]),W.jsx(MEe,{...t,ref:n,trapFocus:e.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Vn(t.onCloseAutoFocus,o=>{o.preventDefault(),e.triggerRef.current?.focus()}),onPointerDownOutside:Vn(t.onPointerDownOutside,o=>{const s=o.detail.originalEvent,r=s.button===0&&s.ctrlKey===!0;(s.button===2||r)&&o.preventDefault()}),onFocusOutside:Vn(t.onFocusOutside,o=>o.preventDefault())})}),zni=V.forwardRef((t,A)=>{const e=Ow(PM,t.__scopeDialog),i=V.useRef(!1),n=V.useRef(!1);return W.jsx(MEe,{...t,ref:A,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{t.onCloseAutoFocus?.(o),o.defaultPrevented||(i.current||e.triggerRef.current?.focus(),o.preventDefault()),i.current=!1,n.current=!1},onInteractOutside:o=>{t.onInteractOutside?.(o),o.defaultPrevented||(i.current=!0,o.detail.originalEvent.type==="pointerdown"&&(n.current=!0));const s=o.target;e.triggerRef.current?.contains(s)&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&n.current&&o.preventDefault()}})}),MEe=V.forwardRef((t,A)=>{const{__scopeDialog:e,trapFocus:i,onOpenAutoFocus:n,onCloseAutoFocus:o,...s}=t,r=Ow(PM,e),a=V.useRef(null),g=RI(A,a);return vfA(),W.jsxs(W.Fragment,{children:[W.jsx(Y9,{asChild:!0,loop:!0,trapped:i,onMountAutoFocus:n,onUnmountAutoFocus:o,children:W.jsx(qJ,{role:"dialog",id:r.contentId,"aria-describedby":r.descriptionId,"aria-labelledby":r.titleId,"data-state":GmA(r.open),...s,ref:g,onDismiss:()=>r.onOpenChange(!1)})}),W.jsxs(W.Fragment,{children:[W.jsx($ni,{titleId:r.titleId}),W.jsx(eoi,{contentRef:a,descriptionId:r.descriptionId})]})]})}),NmA="DialogTitle",REe=V.forwardRef((t,A)=>{const{__scopeDialog:e,...i}=t,n=Ow(NmA,e);return W.jsx(Ag.h2,{id:n.titleId,...i,ref:A})});REe.displayName=NmA;var NEe="DialogDescription",GEe=V.forwardRef((t,A)=>{const{__scopeDialog:e,...i}=t,n=Ow(NEe,e);return W.jsx(Ag.p,{id:n.descriptionId,...i,ref:A})});GEe.displayName=NEe;var LEe="DialogClose",UEe=V.forwardRef((t,A)=>{const{__scopeDialog:e,...i}=t,n=Ow(LEe,e);return W.jsx(Ag.button,{type:"button",...i,ref:A,onClick:Vn(t.onClick,()=>n.onOpenChange(!1))})});UEe.displayName=LEe;function GmA(t){return t?"open":"closed"}var HEe="DialogTitleWarning",[Xni,YEe]=Kat(HEe,{contentName:PM,titleName:NmA,docsSlug:"dialog"}),$ni=({titleId:t})=>{const A=YEe(HEe),e=`\`${A.contentName}\` requires a \`${A.titleName}\` for the component to be accessible for screen reader users.
|
|
5692
|
+
`,I=new Blob([c],{type:"text/plain"}),l=URL.createObjectURL(I),B=document.createElement("a");B.href=l,B.download=`${g}.test.ts`,B.click(),URL.revokeObjectURL(l)}catch(a){alert(`Error generating test.ts for ${t.constructor.name}: ${a instanceof Error?a.message:String(a)}`)}i(!1)};return W.jsxs("div",{className:`relative ${A}`,ref:n,children:[W.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&&W.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:[W.jsx("button",{className:"w-full text-left px-3 py-2 hover:bg-gray-100 text-xs",onClick:o,children:"Download JSON"}),W.jsx("button",{className:"w-full text-left px-3 py-2 hover:bg-gray-100 text-xs",onClick:s,children:"Download page.tsx"}),W.jsx("button",{className:"w-full text-left px-3 py-2 hover:bg-gray-100 text-xs",onClick:r,children:"Download test.ts"})]})]})},fEe=t=>t.activeSubSolver?[t,...fEe(t.activeSubSolver)]:[t],pni=({solver:t})=>{const A=fEe(t);return W.jsx("div",{className:"flex gap-1 items-center text-sm pt-1",children:A.map((e,i)=>W.jsxs("div",{className:"flex items-center",children:[i>0&&W.jsx("span",{className:"text-gray-400 mx-1",children:"→"}),W.jsx(dni,{solver:e})]},e.constructor.name))})},fni=({solver:t,triggerRender:A,animationSpeed:e=25,onSolverStarted:i,onSolverCompleted:n})=>{const[o,s]=V.useReducer(Q=>!Q,!1),r=V.useRef(void 0),a=()=>{!t.solved&&!t.failed&&(t.step(),A())},g=()=>{!t.solved&&!t.failed&&(i&&i(t),t.solve(),A(),n&&n(t))},c=()=>{o?(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(),n&&t.solved&&n(t);return}t.step(),A()},e))},I=()=>{const Q=t;if(Q.getCurrentPhase&&!t.solved&&!t.failed){const h=Q.getCurrentPhase();for(;Q.getCurrentPhase()===h&&!t.solved&&!t.failed;)t.step();A()}},l=()=>{if(t.solved||t.failed||o)return;const Q=window.prompt("Step until which iteration?",`${t.iterations}`);if(Q===null)return;const h=Number(Q);if(!Number.isFinite(h)){window.alert("Please enter a valid number for the iteration");return}for(;t.iterations<h&&!t.solved&&!t.failed;)t.step();A(),t.solved&&n&&n(t)};V.useEffect(()=>()=>{r.current&&clearInterval(r.current)},[]),V.useEffect(()=>{(t.solved||t.failed)&&o&&(r.current&&(clearInterval(r.current),r.current=void 0),s())},[t.solved,t.failed,o]);const B=t.getCurrentPhase!==void 0,C=B?t.getCurrentPhase():null;return W.jsxs("div",{className:"space-y-2 p-2 border-b",children:[W.jsx("div",{className:"flex items-center",children:W.jsx(pni,{solver:t})}),W.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[W.jsx("button",{onClick:a,disabled:t.solved||t.failed||o,className:"bg-blue-500 hover:bg-blue-600 disabled:bg-gray-300 text-white px-3 py-1 rounded text-sm",children:"Step"}),W.jsx("button",{onClick:g,disabled:t.solved||t.failed||o,className:"bg-green-500 hover:bg-green-600 disabled:bg-gray-300 text-white px-3 py-1 rounded text-sm",children:"Solve"}),W.jsx("button",{onClick:c,disabled:t.solved||t.failed,className:`px-3 py-1 rounded text-white text-sm ${o?"bg-red-500 hover:bg-red-600":"bg-yellow-500 hover:bg-yellow-600"} disabled:bg-gray-300`,children:o?"Stop":"Animate"}),W.jsx("button",{onClick:l,disabled:t.solved||t.failed||o,className:"bg-orange-500 hover:bg-orange-600 disabled:bg-gray-300 text-white px-3 py-1 rounded text-sm",children:"Step Until Iteration"}),B&&W.jsx("button",{onClick:I,disabled:t.solved||t.failed||o,className:"bg-purple-500 hover:bg-purple-600 disabled:bg-gray-300 text-white px-3 py-1 rounded text-sm",children:"Next Stage"}),W.jsxs("div",{className:"text-sm text-gray-600",children:["Iterations: ",t.iterations]}),t.timeToSolve!==void 0&&W.jsxs("div",{className:"text-sm text-gray-600",children:["Time: ",(t.timeToSolve/1e3).toFixed(3),"s"]}),C&&W.jsxs("div",{className:"text-sm text-gray-600",children:["Phase: ",W.jsx("span",{className:"font-medium",children:C})]}),t.solved&&W.jsx("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded text-sm",children:"Solved"}),t.failed&&W.jsx("div",{className:"px-2 py-1 bg-red-100 text-red-800 rounded text-sm",children:"Failed"})]}),t.error&&W.jsxs("div",{className:"text-red-600 text-sm",children:["Error: ",t.error]})]})},yni=(t,A,e)=>{const i=t.currentPipelineStepIndex;return A<i?"Completed":A===i&&t.activeSubSolver?t.activeSubSolver.failed?"Failed":"In Progress":"Not Started"},mni=(t,A)=>{const i=t.pipelineDef[A].solverName,n=yni(t,A),o=t[i],s=t.firstIterationOfPhase?.[i]??null,r=t.iterations;let a=0;if(n==="Completed"){const l=t.pipelineDef[A+1],B=l?t.firstIterationOfPhase?.[l.solverName]:void 0;B!==void 0&&s!==null?a=B-s:s!==null&&(a=r-s)}else n==="In Progress"&&s!==null&&(a=r-s);const g=t.timeSpentOnPhase?.[i]??0;let c=0;n==="Completed"?c=1:n==="In Progress"&&o&&(c=o.progress??0);const I=o?.stats??null;return{index:A,name:i,status:n,firstIteration:s,iterations:a,progress:c,timeSpent:g,stats:I&&Object.keys(I).length>0?I:null,solverInstance:o??null}},wni=({status:t})=>{const A={"Not Started":"text-blue-600","In Progress":"text-yellow-600",Completed:"text-green-600",Failed:"text-red-600"};return W.jsx("span",{className:`font-medium ${A[t]}`,children:t})},Dni=({progress:t})=>{if(t===0)return null;const A=Math.round(t*100);return W.jsxs("div",{className:"flex items-center gap-2",children:[W.jsx("div",{className:"w-20 h-2 bg-gray-200 rounded overflow-hidden",children:W.jsx("div",{className:"h-full bg-blue-500 transition-all duration-200",style:{width:`${A}%`}})}),W.jsxs("span",{className:"text-xs text-gray-500",children:[A,"%"]})]})},Sni=t=>Object.entries(t).map(([A,e])=>`${A}: ${e}`).join(", "),bni=({stats:t})=>{if(!t||Object.keys(t).length===0)return W.jsx("span",{children:"-"});const A=Object.entries(t),e=Sni(t);return W.jsxs("details",{className:"cursor-pointer",children:[W.jsx("summary",{className:"whitespace-nowrap overflow-hidden text-ellipsis max-w-[200px]",children:e}),W.jsx("div",{className:"mt-1 text-xs",children:A.map(([i,n])=>W.jsxs("div",{children:[i,": ",String(n)]},i))})]})},MmA=t=>{if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(MmA);const A={};for(const[e,i]of Object.entries(t))e.startsWith("_")||(A[e]=MmA(i));return A},xni=(t,A)=>{try{if(typeof t.getConstructorParams!="function"){alert(`getConstructorParams() is not implemented for ${A}`);return}const e=MmA(t.getConstructorParams()),i=new Blob([JSON.stringify(e,null,2)],{type:"application/json"}),n=URL.createObjectURL(i),o=document.createElement("a");o.href=n,o.download=`${A}_input.json`,o.click(),URL.revokeObjectURL(n)}catch(e){alert(`Error downloading input for ${A}: ${e instanceof Error?e.message:String(e)}`)}},_ni=({solver:t,onStepUntilPhase:A,onDownloadInput:e})=>{const i=t.pipelineDef.map((r,a)=>mni(t,a)),n=r=>{A?.(r)},o=r=>{r.solverInstance&&(e?e(r.solverInstance,r.name):xni(r.solverInstance,r.name))},s=r=>`${(r/1e3).toFixed(2)}s`;return W.jsxs("div",{className:"border-t border-gray-200",children:[W.jsx("div",{className:"px-4 py-2 bg-gray-50 border-b border-gray-200",children:W.jsx("h3",{className:"text-sm font-semibold text-gray-700",children:"Pipeline Steps"})}),W.jsx("div",{className:"overflow-x-auto",children:W.jsxs("table",{className:"w-full text-sm",children:[W.jsx("thead",{children:W.jsxs("tr",{className:"bg-gray-50 border-b border-gray-200",children:[W.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Step"}),W.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Status"}),W.jsxs("th",{className:"px-4 py-2 text-center font-semibold text-gray-700",children:["i",W.jsx("sub",{children:"0"})]}),W.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Iterations"}),W.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Progress"}),W.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Time"}),W.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Stats"}),W.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Input"})]})}),W.jsx("tbody",{children:i.map(r=>W.jsxs("tr",{className:`border-b border-gray-100 ${r.status==="In Progress"?"bg-yellow-50":""}`,children:[W.jsx("td",{className:"px-4 py-2",children:W.jsxs("div",{className:"flex items-center gap-2",children:[W.jsx("span",{className:"text-gray-400 w-6",children:String(r.index+1).padStart(2,"0")}),W.jsx("button",{onClick:()=>n(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:W.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",className:"w-4 h-4",children:W.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"})})}),W.jsx("span",{className:"font-medium text-gray-900",children:r.name})]})}),W.jsx("td",{className:"px-4 py-2",children:W.jsx(wni,{status:r.status})}),W.jsx("td",{className:"px-4 py-2 text-center text-gray-600",children:r.firstIteration!==null?r.firstIteration:""}),W.jsx("td",{className:"px-4 py-2 text-gray-600",children:r.iterations}),W.jsx("td",{className:"px-4 py-2",children:W.jsx(Dni,{progress:r.progress})}),W.jsx("td",{className:"px-4 py-2 text-gray-600",children:s(r.timeSpent)}),W.jsx("td",{className:"px-4 py-2 text-gray-500",children:W.jsx(bni,{stats:r.stats})}),W.jsx("td",{className:"px-4 py-2",children:r.solverInstance?W.jsxs("button",{onClick:()=>o(r),className:"flex items-center gap-1 text-blue-500 hover:text-blue-700",title:`Download input for ${r.name}`,children:[W.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",className:"w-4 h-4",children:W.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"})}),W.jsx("span",{children:"Input"})]}):null})]},r.name))})]})})]})},kni=class extends Qn.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 vni({graphics:t}){const A=t.points??[],e=t.lines??[],i=t.rects??[],n=t.circles??[],o=t.texts??[];let s=Number.POSITIVE_INFINITY,r=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY,g=Number.NEGATIVE_INFINITY;const c=(h,E)=>{typeof h=="number"&&(h<s&&(s=h),h>a&&(a=h)),typeof E=="number"&&(E<r&&(r=E),E>g&&(g=E))};for(const h of A)c(h.x,h.y);for(const h of e){const E=h.points??[];for(const u of E)c(u.x,u.y)}for(const h of i){const E=h.x??0,u=h.y??0,d=h.width??0,f=h.height??0;c(E,u),c(E+d,u+f)}for(const h of n){const E=h.x??0,u=h.y??0,d=h.radius??1;c(E-d,u-d),c(E+d,u+d)}for(const h of o)c(h.x,h.y);(!isFinite(s)||!isFinite(r)||!isFinite(a)||!isFinite(g))&&(s=-20,r=-20,a=20,g=20);const I=10,l=s-I,B=r-I,C=Math.max(1,a-s+2*I),Q=Math.max(1,g-r+2*I);return W.jsxs("svg",{className:"w-full h-[400px] bg-white",viewBox:`${l} ${B} ${C} ${Q}`,role:"img","aria-label":"Graphics fallback",children:[i.map((h,E)=>W.jsx("rect",{x:h.x??0,y:h.y??0,width:h.width??0,height:h.height??0,fill:"none",stroke:h.strokeColor??"black",strokeWidth:h.strokeWidth??1},`rect-${E}`)),e.map((h,E)=>W.jsx("polyline",{fill:"none",stroke:h.strokeColor??"black",strokeWidth:h.strokeWidth??1,points:(h.points??[]).map(u=>`${u.x??0},${u.y??0}`).join(" ")},`line-${E}`)),n.map((h,E)=>W.jsx("circle",{cx:h.x??0,cy:h.y??0,r:h.radius??1.5,fill:h.fillColor??"none",stroke:h.strokeColor??"black",strokeWidth:h.strokeWidth??1},`circle-${E}`)),A.map((h,E)=>W.jsx("circle",{cx:h.x??0,cy:h.y??0,r:h.radius??1.5,fill:h.color??"black"},`point-${E}`)),o.map((h,E)=>W.jsx("text",{x:h.x??0,y:h.y??0,fontSize:h.fontSize??10,fill:h.color??"black",children:h.text??""},`text-${E}`))]})}var Fni=({solver:t,animationSpeed:A=25,onSolverStarted:e,onSolverCompleted:i})=>{const[n,o]=V.useReducer(c=>c+1,0),s=V.useMemo(()=>{try{return t.visualize()||{points:[],lines:[],rects:[],circles:[]}}catch(c){return console.error("Visualization error:",c),{points:[],lines:[],rects:[],circles:[]}}},[t,n]),r=V.useMemo(()=>(s.rects?.length||0)===0&&(s.lines?.length||0)===0&&(s.points?.length||0)===0&&(s.circles?.length||0)===0,[s]);V.useEffect(()=>{if(!(typeof document>"u")&&!document.querySelector('script[src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"]')){const c=document.createElement("script");c.src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4",document.head.appendChild(c)}},[]);const a=t.pipelineDef!==void 0,g=c=>{const I=t;if(!t.solved&&!t.failed){for(;!t.solved&&!t.failed&&I.currentPipelineStepIndex<=I.pipelineDef.findIndex(l=>l.solverName===c);)t.step();o()}};return W.jsxs("div",{children:[W.jsx(fni,{solver:t,triggerRender:o,animationSpeed:A,onSolverStarted:e,onSolverCompleted:i}),r?W.jsx("div",{className:"p-4 text-gray-500",children:"No Graphics Yet"}):W.jsx(kni,{fallback:W.jsx(vni,{graphics:s}),children:W.jsx(uni,{graphics:s})}),a&&W.jsx(_ni,{solver:t,onStepUntilPhase:g})]})};const Mni=()=>{V.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)},[])},Rni=t=>t.toLowerCase().includes("pack")?yqt:t.toLowerCase().includes("rout")?bqt:rqt,Nni=({solverEvents:t=[]})=>{const[A,e]=V.useState(null);Mni();const i=V.useMemo(()=>{const r=new Map;for(const a of t){const g=`${a.componentName}-${a.solverName}`;r.set(g,a)}return r},[t]),n=V.useMemo(()=>Array.from(i.keys()),[i]),o=A?i.get(A):null,s=V.useMemo(()=>{if(!o)return{instance:null,error:null,classFound:!1};const r=WrA[o.solverName];if(!r)return{instance:null,error:`Solver class "${o.solverName}" not found in SOLVERS registry. Available: ${Object.keys(WrA).join(", ")}`,classFound:!1};try{const a=o.solverParams,g=a?.input!==void 0?a.input:a;return{instance:new r(g),error:null,classFound:!0}}catch(a){const g=a instanceof Error?a.message:String(a);return console.error("Failed to reconstruct solver:",a),{instance:null,error:`Failed to instantiate solver: ${g}`,classFound:!0}}},[o]);return t.length===0?W.jsx("div",{className:"rf-p-4",children:W.jsx("div",{className:"rf-bg-gray-50 rf-rounded-md rf-border rf-border-gray-200",children:W.jsxs("div",{className:"rf-p-4",children:[W.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-gray-800 rf-mb-3",children:"No Solvers Detected"}),W.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."})]})})}):W.jsxs("div",{className:"rf-flex rf-h-full rf-overflow-hidden",children:[W.jsxs("div",{className:"rf-w-64 rf-border-r rf-border-gray-200 rf-overflow-y-auto rf-flex-shrink-0",children:[W.jsxs("div",{className:"rf-text-xs rf-font-semibold rf-text-gray-500 rf-px-3 rf-py-2 rf-bg-gray-50 rf-border-b rf-border-gray-200",children:[n.length," ",n.length===1?"Solver":"Solvers"]}),n.map(r=>{const a=i.get(r),g=A===r;return W.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 c=Rni(a.solverName);return W.jsxs("div",{className:"rf-flex rf-items-center rf-gap-2",children:[W.jsx(c,{className:"rf-w-4 rf-h-4 rf-text-blue-500 rf-flex-shrink-0"}),W.jsxs("div",{className:"rf-flex-1 rf-min-w-0",children:[W.jsx("div",{className:"rf-text-sm rf-font-medium rf-text-gray-800 rf-truncate",children:a.componentName}),W.jsx("div",{className:"rf-text-xs rf-text-gray-500 rf-truncate",children:a.solverName})]})]})})()},r)})]}),W.jsx("div",{className:"rf-flex-1 rf-overflow-hidden",children:o?s.instance?W.jsx(Dm,{fallback:W.jsx("div",{className:"rf-p-4",children:W.jsxs("div",{className:"rf-bg-red-50 rf-rounded-md rf-border rf-border-red-200 rf-p-4",children:[W.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-red-800 rf-mb-2",children:"Error Loading Solver Debugger"}),W.jsxs("p",{className:"rf-text-sm rf-text-red-600",children:["Failed to render the solver debugger for"," ",o.solverName]})]})}),children:W.jsx(Fni,{solver:s.instance})}):W.jsxs("div",{className:"rf-p-4",children:[W.jsxs("div",{className:"rf-mb-4",children:[W.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-gray-800",children:o.solverName}),W.jsxs("p",{className:"rf-text-sm rf-text-gray-500",children:["Component: ",o.componentName]})]}),s.error&&W.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:W.jsx("p",{className:`rf-text-sm ${s.classFound?"rf-text-red-700":"rf-text-yellow-700"}`,children:s.error})}),W.jsxs("div",{className:"rf-border rf-border-gray-200 rf-rounded-md rf-overflow-hidden",children:[W.jsx("div",{className:"rf-px-3 rf-py-2 rf-bg-gray-50",children:W.jsx("span",{className:"rf-text-sm rf-font-medium rf-text-gray-700",children:"Solver Parameters"})}),W.jsx("div",{className:"rf-p-3 rf-bg-white rf-border-t rf-border-gray-200",children:W.jsx("pre",{className:"rf-text-xs rf-font-mono rf-text-gray-600 rf-whitespace-pre-wrap rf-overflow-x-auto",children:JSON.stringify(o.solverParams,null,2)})})]})]}):W.jsx("div",{className:"rf-flex rf-items-center rf-justify-center rf-h-full",children:W.jsx("p",{className:"rf-text-sm rf-text-gray-500",children:"Select a solver from the list to view details"})})})]})},yEe=({errorMessage:t,errorStack:A,circuitJsonErrors:e})=>{V.useEffect(()=>{if(t){const i=new Error(t);A&&(i.stack=A);try{qW.captureException(i)}catch{}}},[t,A]),V.useEffect(()=>{if(e&&e.length>0)for(const i of e){const n=new Error(i.message||"Circuit JSON Error");i.stack&&(n.stack=i.stack);try{qW.captureException(n,{error_type:i.type})}catch{}}},[e])},mEe="0.0.1748",Gni={version:mEe},Jz=M4A()(R4A(t=>({lastRunEvalVersion:void 0,setLastRunEvalVersion:A=>{t({lastRunEvalVersion:A})}}),{name:"runframe-runner-store"})),Lni=t=>{const[A,e]=V.useState([]),[i,n]=V.useState(null),[o,s]=V.useState(""),[r,a]=cG("eval-version-selection",null),g=Jz(B=>B.setLastRunEvalVersion),c=Jz(B=>B.lastRunEvalVersion);return V.useEffect(()=>{t&&fetch("https://data.jsdelivr.com/v1/package/npm/@tscircuit/eval").then(B=>B.json()).then(B=>{if(Array.isArray(B?.versions)){let C=[...B.versions];B.tags?.latest&&(n(B.tags.latest),C=C.filter(Q=>Q!==B.tags.latest)),e(C)}}).catch(()=>{})},[t]),V.useEffect(()=>{t&&(r?(window.TSCIRCUIT_LATEST_EVAL_VERSION=r,g(r)):i&&(window.TSCIRCUIT_LATEST_EVAL_VERSION=i,g(i)))},[t,r,i]),{versions:V.useMemo(()=>A.filter(B=>B.includes(o)).slice(0,50),[A,o]),latestVersion:i,lastRunEvalVersion:c,search:o,setSearch:s,selectVersion:B=>{a(B),s("")}}},Uni=({snippetNames:t,onSelect:A,onCancel:e,isOpen:i})=>{const[n,o]=V.useState(""),[s,r]=V.useState("");if(!i)return null;const a=t.filter(I=>I.toLowerCase().includes(s.toLowerCase())),g=s&&!t.includes(s),c=I=>{I.key==="Enter"&&(a.length===1?o(a[0]):g&&o(s))};return W.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:W.jsxs("div",{className:"rf-bg-white rf-rounded-lg rf-p-6 rf-w-96",children:[W.jsx("h2",{className:"rf-text-lg rf-font-semibold rf-mb-4",children:"Select Snippet"}),W.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:I=>r(I.target.value),onKeyDown:c}),W.jsxs("div",{className:"rf-h-60 rf-overflow-y-auto",children:[a.map(I=>W.jsx("button",{type:"button",className:`w-full text-left px-4 py-2 rounded hover:bg-gray-100 ${n===I?"bg-blue-50":""}`,onClick:()=>o(I),children:I},I)),g&&W.jsxs("button",{type:"button",className:`w-full text-left px-4 py-2 rounded hover:bg-gray-100 text-blue-500 ${n===s?"bg-blue-50":""}`,onClick:()=>o(s),children:['Create new "',s,'"']})]}),W.jsxs("div",{className:"rf-mt-4 rf-flex rf-justify-end rf-gap-2",children:[W.jsx("button",{type:"button",className:"rf-px-4 rf-py-2 rf-text-gray-600 rf-hover:text-gray-800",onClick:e,children:"Cancel"}),W.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:()=>n&&A(n),disabled:!n,children:n===s?`Create "${n}"`:`Save to ${n}`})]})]})})},Hni=t=>{const A=V.useRef(null),e=MI(i=>i.recentEvents);V.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 Yni(t){const A=Jni(t),e=V.forwardRef((i,n)=>{const{children:o,...s}=i,r=V.Children.toArray(o),a=r.find(Pni);if(a){const g=a.props.children,c=r.map(I=>I===a?V.Children.count(g)>1?V.Children.only(null):V.isValidElement(g)?g.props.children:null:I);return W.jsx(A,{...s,ref:n,children:V.isValidElement(g)?V.cloneElement(g,void 0,c):null})}return W.jsx(A,{...s,ref:n,children:o})});return e.displayName=`${t}.Slot`,e}function Jni(t){const A=V.forwardRef((e,i)=>{const{children:n,...o}=e;if(V.isValidElement(n)){const s=qni(n),r=Kni(o,n.props);return n.type!==V.Fragment&&(r.ref=i?_f(i,s):s),V.cloneElement(n,r)}return V.Children.count(n)>1?V.Children.only(null):null});return A.displayName=`${t}.SlotClone`,A}var Tni=Symbol("radix.slottable");function Pni(t){return V.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===Tni}function Kni(t,A){const e={...A};for(const i in A){const n=t[i],o=A[i];/^on[A-Z]/.test(i)?n&&o?e[i]=(...r)=>{const a=o(...r);return n(...r),a}:n&&(e[i]=n):i==="style"?e[i]={...n,...o}:i==="className"&&(e[i]=[n,o].filter(Boolean).join(" "))}return{...t,...e}}function qni(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",[wEe,DEe]=dw(Tz),[Oni,Ow]=wEe(Tz),SEe=t=>{const{__scopeDialog:A,children:e,open:i,defaultOpen:n,onOpenChange:o,modal:s=!0}=t,r=V.useRef(null),a=V.useRef(null),[g,c]=G_({prop:i,defaultProp:n??!1,onChange:o,caller:Tz});return W.jsx(Oni,{scope:A,triggerRef:r,contentRef:a,contentId:qE(),titleId:qE(),descriptionId:qE(),open:g,onOpenChange:c,onOpenToggle:V.useCallback(()=>c(I=>!I),[c]),modal:s,children:e})};SEe.displayName=Tz;var bEe="DialogTrigger",xEe=V.forwardRef((t,A)=>{const{__scopeDialog:e,...i}=t,n=Ow(bEe,e),o=RI(A,n.triggerRef);return W.jsx(Ag.button,{type:"button","aria-haspopup":"dialog","aria-expanded":n.open,"aria-controls":n.contentId,"data-state":GmA(n.open),...i,ref:o,onClick:Vn(t.onClick,n.onOpenToggle)})});xEe.displayName=bEe;var RmA="DialogPortal",[Wni,_Ee]=wEe(RmA,{forceMount:void 0}),kEe=t=>{const{__scopeDialog:A,forceMount:e,children:i,container:n}=t,o=Ow(RmA,A);return W.jsx(Wni,{scope:A,forceMount:e,children:V.Children.map(i,s=>W.jsx(q0,{present:e||o.open,children:W.jsx($9,{asChild:!0,container:n,children:s})}))})};kEe.displayName=RmA;var Pz="DialogOverlay",vEe=V.forwardRef((t,A)=>{const e=_Ee(Pz,t.__scopeDialog),{forceMount:i=e.forceMount,...n}=t,o=Ow(Pz,t.__scopeDialog);return o.modal?W.jsx(q0,{present:i||o.open,children:W.jsx(Vni,{...n,ref:A})}):null});vEe.displayName=Pz;var Zni=Yni("DialogOverlay.RemoveScroll"),Vni=V.forwardRef((t,A)=>{const{__scopeDialog:e,...i}=t,n=Ow(Pz,e);return W.jsx(rj,{as:Zni,allowPinchZoom:!0,shards:[n.contentRef],children:W.jsx(Ag.div,{"data-state":GmA(n.open),...i,ref:A,style:{pointerEvents:"auto",...i.style}})})}),PM="DialogContent",FEe=V.forwardRef((t,A)=>{const e=_Ee(PM,t.__scopeDialog),{forceMount:i=e.forceMount,...n}=t,o=Ow(PM,t.__scopeDialog);return W.jsx(q0,{present:i||o.open,children:o.modal?W.jsx(jni,{...n,ref:A}):W.jsx(zni,{...n,ref:A})})});FEe.displayName=PM;var jni=V.forwardRef((t,A)=>{const e=Ow(PM,t.__scopeDialog),i=V.useRef(null),n=RI(A,e.contentRef,i);return V.useEffect(()=>{const o=i.current;if(o)return jfA(o)},[]),W.jsx(MEe,{...t,ref:n,trapFocus:e.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Vn(t.onCloseAutoFocus,o=>{o.preventDefault(),e.triggerRef.current?.focus()}),onPointerDownOutside:Vn(t.onPointerDownOutside,o=>{const s=o.detail.originalEvent,r=s.button===0&&s.ctrlKey===!0;(s.button===2||r)&&o.preventDefault()}),onFocusOutside:Vn(t.onFocusOutside,o=>o.preventDefault())})}),zni=V.forwardRef((t,A)=>{const e=Ow(PM,t.__scopeDialog),i=V.useRef(!1),n=V.useRef(!1);return W.jsx(MEe,{...t,ref:A,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{t.onCloseAutoFocus?.(o),o.defaultPrevented||(i.current||e.triggerRef.current?.focus(),o.preventDefault()),i.current=!1,n.current=!1},onInteractOutside:o=>{t.onInteractOutside?.(o),o.defaultPrevented||(i.current=!0,o.detail.originalEvent.type==="pointerdown"&&(n.current=!0));const s=o.target;e.triggerRef.current?.contains(s)&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&n.current&&o.preventDefault()}})}),MEe=V.forwardRef((t,A)=>{const{__scopeDialog:e,trapFocus:i,onOpenAutoFocus:n,onCloseAutoFocus:o,...s}=t,r=Ow(PM,e),a=V.useRef(null),g=RI(A,a);return vfA(),W.jsxs(W.Fragment,{children:[W.jsx(Y9,{asChild:!0,loop:!0,trapped:i,onMountAutoFocus:n,onUnmountAutoFocus:o,children:W.jsx(qJ,{role:"dialog",id:r.contentId,"aria-describedby":r.descriptionId,"aria-labelledby":r.titleId,"data-state":GmA(r.open),...s,ref:g,onDismiss:()=>r.onOpenChange(!1)})}),W.jsxs(W.Fragment,{children:[W.jsx($ni,{titleId:r.titleId}),W.jsx(eoi,{contentRef:a,descriptionId:r.descriptionId})]})]})}),NmA="DialogTitle",REe=V.forwardRef((t,A)=>{const{__scopeDialog:e,...i}=t,n=Ow(NmA,e);return W.jsx(Ag.h2,{id:n.titleId,...i,ref:A})});REe.displayName=NmA;var NEe="DialogDescription",GEe=V.forwardRef((t,A)=>{const{__scopeDialog:e,...i}=t,n=Ow(NEe,e);return W.jsx(Ag.p,{id:n.descriptionId,...i,ref:A})});GEe.displayName=NEe;var LEe="DialogClose",UEe=V.forwardRef((t,A)=>{const{__scopeDialog:e,...i}=t,n=Ow(LEe,e);return W.jsx(Ag.button,{type:"button",...i,ref:A,onClick:Vn(t.onClick,()=>n.onOpenChange(!1))})});UEe.displayName=LEe;function GmA(t){return t?"open":"closed"}var HEe="DialogTitleWarning",[Xni,YEe]=Kat(HEe,{contentName:PM,titleName:NmA,docsSlug:"dialog"}),$ni=({titleId:t})=>{const A=YEe(HEe),e=`\`${A.contentName}\` requires a \`${A.titleName}\` for the component to be accessible for screen reader users.
|
|
5693
5693
|
|
|
5694
5694
|
If you want to hide the \`${A.titleName}\`, you can wrap it with our VisuallyHidden component.
|
|
5695
5695
|
|
|
@@ -5826,7 +5826,7 @@ ${a.join(`
|
|
|
5826
5826
|
`)}};UA.register(Vhi);var rye=class EkA extends UA{static token="locked";static parentToken="group";token="locked";value;constructor(A){super(),this.value=A}static fromSexprPrimitives(A){if(A.length===0)return new EkA(!0);const e=Di(A[0]);return new EkA(e==="yes")}getString(){return this.value?"(locked yes)":"(locked no)"}};UA.register(rye);var aye=class Lke extends UA{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 n=Di(i);n&&e.push(n)}return new Lke(e)}getString(){return this.members.length===0?"(members)":`(members ${this.members.map(e=>`"${e}"`).join(" ")})`}};UA.register(aye);var fbA=class Uke extends UA{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,n=Ci(e),o=Ci(i);if(n===void 0||o===void 0)throw new Error("end expects two numeric arguments");return new Uke(n,o)}get x(){return this._x}set x(A){this._x=A}get y(){return this._y}set y(A){this._y=A}toObject(){return{x:this._x,y:this._y}}getChildren(){return[]}getString(){return`(end ${this._x} ${this._y})`}};UA.register(fbA);var jhi=new Set(["true","yes","1"]),gye=class G7 extends Vl{static token="locked";static parentToken="segment";token="locked";constructor(A){super(A)}static fromSexprPrimitives(A){const[e]=A;return typeof e=="boolean"?new G7(e):typeof e=="string"?new G7(jhi.has(e.toLowerCase())):new G7(!1)}getString(){return`(locked ${this.value?"yes":"no"})`}};UA.register(gye);var OX=class Hke extends UA{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,n=Ci(e);if(n===void 0)throw new Error("net expects a numeric identifier");const o=i===void 0?void 0:Di(i);return new Hke(n,o??void 0)}get id(){return this._id}set id(A){this._id=A}get name(){return this._name}set name(A){this._name=A===""?void 0:A}toObject(){return this._name===void 0?{id:this._id}:{id:this._id,name:this._name}}getChildren(){return[]}getString(){const A=this._name?` ${Dn(this._name)}`:"";return`(net ${this._id}${A})`}};UA.register(OX);var ybA=class Yke extends UA{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,n=Ci(e),o=Ci(i);if(n===void 0||o===void 0)throw new Error("start expects two numeric arguments");return new Yke(n,o)}get x(){return this._x}set x(A){this._x=A}get y(){return this._y}set y(A){this._y=A}toObject(){return{x:this._x,y:this._y}}getChildren(){return[]}getString(){return`(start ${this._x} ${this._y})`}};UA.register(ybA);var cye=new Set(["start","end","width","layer","net","tstamp","uuid","locked"]),mbA=class Jke extends UA{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 Jke,{propertyMap:i,arrayPropertyMap:n}=UA.parsePrimitivesToClassProperties(A,this.token),o=Object.keys(i).filter(r=>!cye.has(r));if(o.length>0)throw new Error(`Unsupported child tokens inside segment expression: ${o.join(", ")}`);for(const[r,a]of Object.entries(n)){if(!cye.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=n.start?.[0]??i.start,e._sxEnd=n.end?.[0]??i.end,e._sxWidth=n.width?.[0]??i.width,e._sxLayer=n.layer?.[0]??i.layer,e._sxNet=n.net?.[0]??i.net;const s=n.locked?.[0]??i.locked;return e._sxLocked=s&&s.value?s:void 0,e._sxTstamp=n.tstamp?.[0]??i.tstamp,e._sxUuid=n.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 Yr?A:new Yr(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 kr){this._sxLayer=A;return}const e=Array.isArray(A)?A:[A];this._sxLayer=new kr(e)}get net(){return this._sxNet}set net(A){if(A===void 0){this._sxNet=void 0;return}if(A instanceof OX){this._sxNet=A;return}this._sxNet=new OX(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 gc?A:new gc(A)}get uuid(){return this._sxUuid}set uuid(A){if(A===void 0){this._sxUuid=void 0;return}this._sxUuid=A instanceof qi?A:new qi(A)}get locked(){return this._sxLocked?.value??!1}set locked(A){this._sxLocked=A?new gye(!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 ybA?A:new ybA(A.x,A.y)}normalizeEnd(A){if(A!==void 0)return A instanceof fbA?A:new fbA(A.x,A.y)}};UA.register(mbA);var Iye=class Tke extends UA{static token="zone";token="zone";_rawChildren=[];static fromSexprPrimitives(A){const e=new Tke;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(` ${AE(e)}`);return A.push(")"),A.join(`
|
|
5827
5827
|
`)}};UA.register(Iye);var WX=class Pke extends UA{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):AE(i));return new Pke(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:Dn(e)).join(" ")})`}};UA.register(WX);var _P=class extends UA{_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=Di(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?Dn(this._value):this._value:`${this._value}`}getString(){return`(${this.token} ${this.formatValue()})`}},zhi=class extends UA{_values;constructor(t){super(),this._values=t}static fromSexprPrimitives(t){const A=t.map(i=>{const n=Ci(i);if(n===void 0)throw new Error(`${this.name} expects numeric primitives but received ${i}`);return n}),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(" ")})`}},Xhi=class extends UA{_x;_y;constructor(t,A){super(),this._x=t,this._y=A}static fromSexprPrimitives(t){const[A,e]=t,i=Ci(A),n=Ci(e);if(i===void 0||n===void 0)throw new Error(`${this.name} expects two numeric values`);const o=this;return new o(i,n)}get x(){return this._x}set x(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})`}},vr=class extends _P{static parentToken="pcbplotparams"},Um=class extends vr{static parsePrimitiveValue(t){const A=Ci(t);if(A===void 0)throw new Error(`pcbplotparams ${this.token} expects a numeric value`);return A}},lye=class extends vr{static token="layerselection";token="layerselection"};UA.register(lye);var Bye=class extends vr{static token="plot_on_all_layers_selection";token="plot_on_all_layers_selection"};UA.register(Bye);var Cye=class extends Um{static token="dashed_line_dash_ratio";token="dashed_line_dash_ratio"};UA.register(Cye);var Qye=class extends Um{static token="dashed_line_gap_ratio";token="dashed_line_gap_ratio"};UA.register(Qye);var hye=class extends Um{static token="svgprecision";token="svgprecision"};UA.register(hye);var Eye=class extends Um{static token="linewidth";token="linewidth"};UA.register(Eye);var uye=class extends Um{static token="mode";token="mode"};UA.register(uye);var dye=class extends Um{static token="hpglpennumber";token="hpglpennumber"};UA.register(dye);var pye=class extends Um{static token="hpglpenspeed";token="hpglpenspeed"};UA.register(pye);var fye=class extends Um{static token="hpglpendiameter";token="hpglpendiameter"};UA.register(fye);var yye=class extends Um{static token="hpglpenoverlay";token="hpglpenoverlay"};UA.register(yye);var mye=class extends Um{static token="outputformat";token="outputformat"};UA.register(mye);var wye=class extends Um{static token="drillshape";token="drillshape"};UA.register(wye);var Dye=class extends Um{static token="scaleselection";token="scaleselection"};UA.register(Dye);var Sye=class extends vr{static token="disableapertmacros";token="disableapertmacros"};UA.register(Sye);var bye=class extends vr{static token="usegerberextensions";token="usegerberextensions"};UA.register(bye);var xye=class extends vr{static token="usegerberattributes";token="usegerberattributes"};UA.register(xye);var _ye=class extends vr{static token="usegerberadvancedattributes";token="usegerberadvancedattributes"};UA.register(_ye);var kye=class extends vr{static token="creategerberjobfile";token="creategerberjobfile"};UA.register(kye);var vye=class extends vr{static token="excludeedgelayer";token="excludeedgelayer"};UA.register(vye);var Fye=class extends vr{static token="plotframeref";token="plotframeref"};UA.register(Fye);var Mye=class extends vr{static token="viasonmask";token="viasonmask"};UA.register(Mye);var Rye=class extends vr{static token="useauxorigin";token="useauxorigin"};UA.register(Rye);var Nye=class extends vr{static token="pdf_front_fp_property_popups";token="pdf_front_fp_property_popups"};UA.register(Nye);var Gye=class extends vr{static token="pdf_back_fp_property_popups";token="pdf_back_fp_property_popups"};UA.register(Gye);var Lye=class extends vr{static token="pdf_metadata";token="pdf_metadata"};UA.register(Lye);var Uye=class extends vr{static token="pdf_single_document";token="pdf_single_document"};UA.register(Uye);var Hye=class extends vr{static token="dxfpolygonmode";token="dxfpolygonmode"};UA.register(Hye);var Yye=class extends vr{static token="dxfimperialunits";token="dxfimperialunits"};UA.register(Yye);var Jye=class extends vr{static token="dxfusepcbnewfont";token="dxfusepcbnewfont"};UA.register(Jye);var Tye=class extends vr{static token="psnegative";token="psnegative"};UA.register(Tye);var Pye=class extends vr{static token="psa4output";token="psa4output"};UA.register(Pye);var Kye=class extends vr{static token="plotreference";token="plotreference"};UA.register(Kye);var qye=class extends vr{static token="plotvalue";token="plotvalue"};UA.register(qye);var Oye=class extends vr{static token="plotothertext";token="plotothertext"};UA.register(Oye);var Wye=class extends vr{static token="plotinvisibletext";token="plotinvisibletext"};UA.register(Wye);var Zye=class extends vr{static token="padsonsilk";token="padsonsilk"};UA.register(Zye);var Vye=class extends vr{static token="sketchpadsonfab";token="sketchpadsonfab"};UA.register(Vye);var jye=class extends vr{static token="plotpadnumbers";token="plotpadnumbers"};UA.register(jye);var zye=class extends vr{static token="hidednponfab";token="hidednponfab"};UA.register(zye);var Xye=class extends vr{static token="sketchdnponfab";token="sketchdnponfab"};UA.register(Xye);var $ye=class extends vr{static token="crossoutdnponfab";token="crossoutdnponfab"};UA.register($ye);var Ame=class extends vr{static token="subtractmaskfromsilk";token="subtractmaskfromsilk"};UA.register(Ame);var eme=class extends vr{static token="plot_black_and_white";token="plot_black_and_white"};UA.register(eme);var tme=class extends vr{static token="mirror";token="mirror"};UA.register(tme);var ime=class extends vr{static token="outputdirectory";token="outputdirectory";quoteStringValue=!0};UA.register(ime);var nme=class extends vr{static token="plot_on_all_layers";token="plot_on_all_layers"};UA.register(nme);var ome=class extends vr{static token="plotinvisible";token="plotinvisible"};UA.register(ome);var $hi={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"},AEi=["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"],wbA=class Kke extends UA{static token="pcbplotparams";static parentToken="setup";token="pcbplotparams";_properties={};static fromSexprPrimitives(A){const e=new Kke,{propertyMap:i}=UA.parsePrimitivesToClassProperties(A,this.token);for(const[n,o]of Object.entries(i)){const s=$hi[n];if(!s)throw new Error(`Unsupported pcbplotparams token: ${n}`);e._properties[s]=o}return e}getChildren(){const A=[];for(const e of AEi){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,lye)}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,Bye)}get disableapertmacros(){return this._properties.disableapertmacros?.value}set disableapertmacros(A){this.setStringProperty("disableapertmacros",A,Sye)}get usegerberextensions(){return this._properties.usegerberextensions?.value}set usegerberextensions(A){this.setStringProperty("usegerberextensions",A,bye)}get usegerberattributes(){return this._properties.usegerberattributes?.value}set usegerberattributes(A){this.setStringProperty("usegerberattributes",A,xye)}get usegerberadvancedattributes(){return this._properties.usegerberadvancedattributes?.value}set usegerberadvancedattributes(A){this.setStringProperty("usegerberadvancedattributes",A,_ye)}get creategerberjobfile(){return this._properties.creategerberjobfile?.value}set creategerberjobfile(A){this.setStringProperty("creategerberjobfile",A,kye)}get excludeedgelayer(){return this._properties.excludeedgelayer?.value}set excludeedgelayer(A){this.setStringProperty("excludeedgelayer",A,vye)}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,Cye)}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,Qye)}get svgprecision(){return this._properties.svgprecision?.value}set svgprecision(A){this.setNumberProperty("svgprecision",A,hye)}get linewidth(){return this._properties.linewidth?.value}set linewidth(A){this.setNumberProperty("linewidth",A,Eye)}get plotframeref(){return this._properties.plotframeref?.value}set plotframeref(A){this.setStringProperty("plotframeref",A,Fye)}get plotreference(){return this._properties.plotreference?.value}set plotreference(A){this.setStringProperty("plotreference",A,Kye)}get plotvalue(){return this._properties.plotvalue?.value}set plotvalue(A){this.setStringProperty("plotvalue",A,qye)}get plotothertext(){return this._properties.plotothertext?.value}set plotothertext(A){this.setStringProperty("plotothertext",A,Oye)}get plotinvisibletext(){return this._properties.plotinvisibletext?.value}set plotinvisibletext(A){this.setStringProperty("plotinvisibletext",A,Wye)}get padsonsilk(){return this._properties.padsonsilk?.value}set padsonsilk(A){this.setStringProperty("padsonsilk",A,Zye)}get plotpadnumbers(){return this._properties.plotpadnumbers?.value}set plotpadnumbers(A){this.setStringProperty("plotpadnumbers",A,jye)}get sketchpadsonfab(){return this._properties.sketchpadsonfab?.value}set sketchpadsonfab(A){this.setStringProperty("sketchpadsonfab",A,Vye)}get hidednponfab(){return this._properties.hidednponfab?.value}set hidednponfab(A){this.setStringProperty("hidednponfab",A,zye)}get sketchdnponfab(){return this._properties.sketchdnponfab?.value}set sketchdnponfab(A){this.setStringProperty("sketchdnponfab",A,Xye)}get crossoutdnponfab(){return this._properties.crossoutdnponfab?.value}set crossoutdnponfab(A){this.setStringProperty("crossoutdnponfab",A,$ye)}get subtractmaskfromsilk(){return this._properties.subtractmaskfromsilk?.value}set subtractmaskfromsilk(A){this.setStringProperty("subtractmaskfromsilk",A,Ame)}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,eme)}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,nme)}get plotinvisible(){return this._properties.plotinvisible?.value}set plotinvisible(A){this.setStringProperty("plotinvisible",A,ome)}get mode(){return this._properties.mode?.value}set mode(A){this.setNumberProperty("mode",A,uye)}get useauxorigin(){return this._properties.useauxorigin?.value}set useauxorigin(A){this.setStringProperty("useauxorigin",A,Rye)}get viasonmask(){return this._properties.viasonmask?.value}set viasonmask(A){this.setStringProperty("viasonmask",A,Mye)}get hpglpennumber(){return this._properties.hpglpennumber?.value}set hpglpennumber(A){this.setNumberProperty("hpglpennumber",A,dye)}get hpglpenspeed(){return this._properties.hpglpenspeed?.value}set hpglpenspeed(A){this.setNumberProperty("hpglpenspeed",A,pye)}get hpglpendiameter(){return this._properties.hpglpendiameter?.value}set hpglpendiameter(A){this.setNumberProperty("hpglpendiameter",A,fye)}get hpglpenoverlay(){return this._properties.hpglpenoverlay?.value}set hpglpenoverlay(A){this.setNumberProperty("hpglpenoverlay",A,yye)}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,Nye)}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,Gye)}get pdf_metadata(){return this._properties.pdf_metadata?.value}set pdf_metadata(A){this.setStringProperty("pdf_metadata",A,Lye)}get pdf_single_document(){return this._properties.pdf_single_document?.value}set pdf_single_document(A){this.setStringProperty("pdf_single_document",A,Uye)}get dxfpolygonmode(){return this._properties.dxfpolygonmode?.value}set dxfpolygonmode(A){this.setStringProperty("dxfpolygonmode",A,Hye)}get dxfimperialunits(){return this._properties.dxfimperialunits?.value}set dxfimperialunits(A){this.setStringProperty("dxfimperialunits",A,Yye)}get dxfusepcbnewfont(){return this._properties.dxfusepcbnewfont?.value}set dxfusepcbnewfont(A){this.setStringProperty("dxfusepcbnewfont",A,Jye)}get psnegative(){return this._properties.psnegative?.value}set psnegative(A){this.setStringProperty("psnegative",A,Tye)}get psa4output(){return this._properties.psa4output?.value}set psa4output(A){this.setStringProperty("psa4output",A,Pye)}get mirror(){return this._properties.mirror?.value}set mirror(A){this.setStringProperty("mirror",A,tme)}get outputformat(){return this._properties.outputformat?.value}set outputformat(A){this.setNumberProperty("outputformat",A,mye)}get drillshape(){return this._properties.drillshape?.value}set drillshape(A){this.setNumberProperty("drillshape",A,wye)}get scaleselection(){return this._properties.scaleselection?.value}set scaleselection(A){this.setNumberProperty("scaleselection",A,Dye)}get outputdirectory(){return this._properties.outputdirectory?.value}set outputdirectory(A){this.setStringProperty("outputdirectory",A,ime)}};UA.register(wbA);var ZX=class extends _P{static parentToken="setup"},DbA=class extends ZX{static token="zone_45_only";token="zone_45_only"};UA.register(DbA);var SbA=class extends ZX{static token="allow_soldermask_bridges_in_footprints";token="allow_soldermask_bridges_in_footprints"};UA.register(SbA);var bbA=class extends ZX{static token="visible_elements";token="visible_elements"};UA.register(bbA);var xbA=class extends ZX{static token="uvias_allowed";token="uvias_allowed"};UA.register(xbA);var _bA=class qke extends UA{static token="tenting";static parentToken="setup";token="tenting";_sides=[];constructor(A=[]){super(),this.sides=A}static fromSexprPrimitives(A){const e=A.map(i=>Di(i)).filter(i=>i!==void 0);return new qke(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(" ")})`}};UA.register(_bA);var kP=class extends zhi{static parentToken="setup"},sme=class extends Xhi{static parentToken="setup"},kbA=class extends kP{static token="pcb_text_size";token="pcb_text_size"};UA.register(kbA);var vbA=class extends kP{static token="mod_text_size";token="mod_text_size"};UA.register(vbA);var FbA=class extends kP{static token="pad_size";token="pad_size"};UA.register(FbA);var MbA=class extends kP{static token="pad_to_paste_clearance_values";token="pad_to_paste_clearance_values"};UA.register(MbA);var RbA=class extends kP{static token="trace_width";token="trace_width"};UA.register(RbA);var NbA=class extends sme{static token="aux_axis_origin";token="aux_axis_origin"};UA.register(NbA);var GbA=class extends sme{static token="grid_origin";token="grid_origin"};UA.register(GbA);var DB=class extends _P{static parentToken="setup";static parsePrimitiveValue(t){const A=Ci(t);if(A===void 0)throw new Error(`${this.name} expects a numeric value`);return A}},LbA=class extends DB{static token="pad_to_mask_clearance";token="pad_to_mask_clearance"};UA.register(LbA);var UbA=class extends DB{static token="solder_mask_min_width";token="solder_mask_min_width"};UA.register(UbA);var HbA=class extends DB{static token="pad_to_paste_clearance";token="pad_to_paste_clearance"};UA.register(HbA);var YbA=class extends DB{static token="pad_to_paste_clearance_ratio";token="pad_to_paste_clearance_ratio"};UA.register(YbA);var JbA=class extends DB{static token="last_trace_width";token="last_trace_width"};UA.register(JbA);var TbA=class extends DB{static token="trace_clearance";token="trace_clearance"};UA.register(TbA);var PbA=class extends DB{static token="zone_clearance";token="zone_clearance"};UA.register(PbA);var KbA=class extends DB{static token="trace_min";token="trace_min"};UA.register(KbA);var qbA=class extends DB{static token="segment_width";token="segment_width"};UA.register(qbA);var ObA=class extends DB{static token="edge_width";token="edge_width"};UA.register(ObA);var WbA=class extends DB{static token="via_size";token="via_size"};UA.register(WbA);var ZbA=class extends DB{static token="via_drill";token="via_drill"};UA.register(ZbA);var VbA=class extends DB{static token="via_min_size";token="via_min_size"};UA.register(VbA);var jbA=class extends DB{static token="via_min_drill";token="via_min_drill"};UA.register(jbA);var zbA=class extends DB{static token="uvia_size";token="uvia_size"};UA.register(zbA);var XbA=class extends DB{static token="uvia_drill";token="uvia_drill"};UA.register(XbA);var $bA=class extends DB{static token="uvia_min_size";token="uvia_min_size"};UA.register($bA);var AxA=class extends DB{static token="uvia_min_drill";token="uvia_min_drill"};UA.register(AxA);var exA=class extends DB{static token="pcb_text_width";token="pcb_text_width"};UA.register(exA);var txA=class extends DB{static token="mod_edge_width";token="mod_edge_width"};UA.register(txA);var ixA=class extends DB{static token="mod_text_width";token="mod_text_width"};UA.register(ixA);var nxA=class extends DB{static token="pad_drill";token="pad_drill"};UA.register(nxA);var vP=class extends _P{static parentToken="stackup"},rme=class extends vP{static token="copper_finish";token="copper_finish";quoteStringValue=!0};UA.register(rme);var ame=class extends vP{static token="dielectric_constraints";token="dielectric_constraints"};UA.register(ame);var gme=class extends vP{static token="edge_connector";token="edge_connector"};UA.register(gme);var cme=class extends vP{static token="castellated_pads";token="castellated_pads"};UA.register(cme);var Ime=class extends vP{static token="edge_plating";token="edge_plating"};UA.register(Ime);var AL=class extends _P{static parentToken="layer"},oxA=class extends AL{static token="type";token="type";quoteStringValue=!0};UA.register(oxA);var sxA=class extends AL{static token="color";token="color";quoteStringValue=!0};UA.register(sxA);var rxA=class extends AL{static token="thickness";token="thickness";static parsePrimitiveValue(t){const A=Ci(t);if(A===void 0)throw new Error("Stackup layer thickness expects a numeric value");return A}};UA.register(rxA);var axA=class extends AL{static token="material";token="material";quoteStringValue=!0};UA.register(axA);var gxA=class extends AL{static token="epsilon_r";token="epsilon_r";static parsePrimitiveValue(t){const A=Ci(t);if(A===void 0)throw new Error("Stackup layer epsilon_r expects a numeric value");return A}};UA.register(gxA);var cxA=class extends AL{static token="loss_tangent";token="loss_tangent";static parsePrimitiveValue(t){const A=Ci(t);if(A===void 0)throw new Error("Stackup layer loss_tangent expects a numeric value");return A}};UA.register(cxA);var lme=class Oke extends UA{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=Di(A[0]);if(e===void 0)throw new Error("Stackup layer name must be a string");let i=1,n;const o=A[i],s=Ci(o);s!==void 0&&(n=s,i+=1);const r=A.slice(i),{propertyMap:a}=UA.parsePrimitivesToClassProperties(r,this.token);return new Oke(e,{number:n,type:a.type,color:a.color,thickness:a.thickness,material:a.material,epsilonR:a.epsilon_r,lossTangent:a.loss_tangent})}get name(){return this._name}set name(A){const e=Di(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=Ci(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 oxA?A:new oxA(A)}get color(){return this._sxColor?.value}set color(A){if(A===void 0){this._sxColor=void 0;return}this._sxColor=A instanceof sxA?A:new sxA(A)}get thickness(){return this._sxThickness?.value}set thickness(A){if(A===void 0){this._sxThickness=void 0;return}this._sxThickness=A instanceof rxA?A:new rxA(A)}get material(){return this._sxMaterial?.value}set material(A){if(A===void 0){this._sxMaterial=void 0;return}this._sxMaterial=A instanceof axA?A:new axA(A)}get epsilonR(){return this._sxEpsilonR?.value}set epsilonR(A){if(A===void 0){this._sxEpsilonR=void 0;return}this._sxEpsilonR=A instanceof gxA?A:new gxA(A)}get lossTangent(){return this._sxLossTangent?.value}set lossTangent(A){if(A===void 0){this._sxLossTangent=void 0;return}this._sxLossTangent=A instanceof cxA?A:new cxA(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 ${Dn(this._name)}${this._number!==void 0?` ${this._number}`:""}`,e=this.getChildren();if(e.length===0)return`${A})`;const i=[A];for(const n of e)i.push(n.getStringIndented());return i.push(")"),i.join(`
|
|
5828
5828
|
`)}};UA.register(lme);var IxA=class Wke extends UA{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}=UA.parsePrimitivesToClassProperties(A,this.token);return new Wke({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 lme))throw new Error("Stackup layers must be StackupLayer instances");return e})}get copperFinish(){return this._sxCopperFinish?.value}set copperFinish(A){this._sxCopperFinish=A?new rme(A):void 0}get dielectricConstraints(){return this._sxDielectricConstraints?.value}set dielectricConstraints(A){this._sxDielectricConstraints=A?new ame(A):void 0}get edgeConnector(){return this._sxEdgeConnector?.value}set edgeConnector(A){this._sxEdgeConnector=A?new gme(A):void 0}get castellatedPads(){return this._sxCastellatedPads?.value}set castellatedPads(A){this._sxCastellatedPads=A?new cme(A):void 0}get edgePlating(){return this._sxEdgePlating?.value}set edgePlating(A){this._sxEdgePlating=A?new Ime(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}};UA.register(IxA);var eEi={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"},tEi=["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"],lxA=class Zke extends UA{static token="setup";token="setup";_properties={};static fromSexprPrimitives(A){const e=new Zke,{propertyMap:i}=UA.parsePrimitivesToClassProperties(A,this.token);for(const[n,o]of Object.entries(i)){const s=eEi[n];if(!s)throw new Error(`Unsupported setup property token: ${n}`);e._properties[s]=o}return e}getChildren(){const A=[];for(const e of tEi){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",IxA)}set stackup(A){if(A!==void 0&&!(A instanceof IxA))throw new Error("stackup must be a Stackup instance");this.setProperty("stackup",A)}get pcbPlotParams(){return this.getPropertyInstance("pcbPlotParams",wbA)}set pcbPlotParams(A){if(A!==void 0&&!(A instanceof wbA))throw new Error("pcbPlotParams must be a PcbPlotParams instance");this.setProperty("pcbPlotParams",A)}get padToMaskClearance(){return this.getPropertyInstance("padToMaskClearance",LbA)?.value}set padToMaskClearance(A){this.setNumberProperty("padToMaskClearance",A,LbA)}get solderMaskMinWidth(){return this.getPropertyInstance("solderMaskMinWidth",UbA)?.value}set solderMaskMinWidth(A){this.setNumberProperty("solderMaskMinWidth",A,UbA)}get padToPasteClearance(){return this.getPropertyInstance("padToPasteClearance",HbA)?.value}set padToPasteClearance(A){this.setNumberProperty("padToPasteClearance",A,HbA)}get padToPasteClearanceRatio(){return this.getPropertyInstance("padToPasteClearanceRatio",YbA)?.value}set padToPasteClearanceRatio(A){this.setNumberProperty("padToPasteClearanceRatio",A,YbA)}get lastTraceWidth(){return this.getPropertyInstance("lastTraceWidth",JbA)?.value}set lastTraceWidth(A){this.setNumberProperty("lastTraceWidth",A,JbA)}get traceClearance(){return this.getPropertyInstance("traceClearance",TbA)?.value}set traceClearance(A){this.setNumberProperty("traceClearance",A,TbA)}get zoneClearance(){return this.getPropertyInstance("zoneClearance",PbA)?.value}set zoneClearance(A){this.setNumberProperty("zoneClearance",A,PbA)}get zone45Only(){return this.getPropertyInstance("zone45Only",DbA)?.value}set zone45Only(A){this.setProperty("zone45Only",A===void 0?void 0:new DbA(A))}get traceMin(){return this.getPropertyInstance("traceMin",KbA)?.value}set traceMin(A){this.setNumberProperty("traceMin",A,KbA)}get segmentWidth(){return this.getPropertyInstance("segmentWidth",qbA)?.value}set segmentWidth(A){this.setNumberProperty("segmentWidth",A,qbA)}get edgeWidth(){return this.getPropertyInstance("edgeWidth",ObA)?.value}set edgeWidth(A){this.setNumberProperty("edgeWidth",A,ObA)}get viaSize(){return this.getPropertyInstance("viaSize",WbA)?.value}set viaSize(A){this.setNumberProperty("viaSize",A,WbA)}get viaDrill(){return this.getPropertyInstance("viaDrill",ZbA)?.value}set viaDrill(A){this.setNumberProperty("viaDrill",A,ZbA)}get viaMinSize(){return this.getPropertyInstance("viaMinSize",VbA)?.value}set viaMinSize(A){this.setNumberProperty("viaMinSize",A,VbA)}get viaMinDrill(){return this.getPropertyInstance("viaMinDrill",jbA)?.value}set viaMinDrill(A){this.setNumberProperty("viaMinDrill",A,jbA)}get uviasAllowed(){return this.getPropertyInstance("uviasAllowed",xbA)?.value}set uviasAllowed(A){this.setProperty("uviasAllowed",A===void 0?void 0:new xbA(A))}get uviaSize(){return this.getPropertyInstance("uviaSize",zbA)?.value}set uviaSize(A){this.setNumberProperty("uviaSize",A,zbA)}get uviaDrill(){return this.getPropertyInstance("uviaDrill",XbA)?.value}set uviaDrill(A){this.setNumberProperty("uviaDrill",A,XbA)}get uviaMinSize(){return this.getPropertyInstance("uviaMinSize",$bA)?.value}set uviaMinSize(A){this.setNumberProperty("uviaMinSize",A,$bA)}get uviaMinDrill(){return this.getPropertyInstance("uviaMinDrill",AxA)?.value}set uviaMinDrill(A){this.setNumberProperty("uviaMinDrill",A,AxA)}get pcbTextWidth(){return this.getPropertyInstance("pcbTextWidth",exA)?.value}set pcbTextWidth(A){this.setNumberProperty("pcbTextWidth",A,exA)}get pcbTextSize(){return this.getPropertyInstance("pcbTextSize",kbA)?.values}set pcbTextSize(A){if(A===void 0){delete this._properties.pcbTextSize;return}this.setProperty("pcbTextSize",new kbA(A))}get modEdgeWidth(){return this.getPropertyInstance("modEdgeWidth",txA)?.value}set modEdgeWidth(A){this.setNumberProperty("modEdgeWidth",A,txA)}get modTextSize(){return this.getPropertyInstance("modTextSize",vbA)?.values}set modTextSize(A){if(A===void 0){delete this._properties.modTextSize;return}this.setProperty("modTextSize",new vbA(A))}get modTextWidth(){return this.getPropertyInstance("modTextWidth",ixA)?.value}set modTextWidth(A){this.setNumberProperty("modTextWidth",A,ixA)}get padSize(){return this.getPropertyInstance("padSize",FbA)?.values}set padSize(A){if(A===void 0){delete this._properties.padSize;return}this.setProperty("padSize",new FbA(A))}get padDrill(){return this.getPropertyInstance("padDrill",nxA)?.value}set padDrill(A){this.setNumberProperty("padDrill",A,nxA)}get allowSoldermaskBridgesInFootprints(){return this.getPropertyInstance("allowSoldermaskBridgesInFootprints",SbA)?.value}set allowSoldermaskBridgesInFootprints(A){this.setProperty("allowSoldermaskBridgesInFootprints",A===void 0?void 0:new SbA(A))}get tenting(){return this.getPropertyInstance("tenting",_bA)?.sides}set tenting(A){if(A===void 0){delete this._properties.tenting;return}this.setProperty("tenting",new _bA(A))}get auxAxisOrigin(){const A=this.getPropertyInstance("auxAxisOrigin",NbA);if(A)return{x:A.x,y:A.y}}set auxAxisOrigin(A){if(!A){delete this._properties.auxAxisOrigin;return}this.setProperty("auxAxisOrigin",new NbA(A.x,A.y))}get gridOrigin(){const A=this.getPropertyInstance("gridOrigin",GbA);if(A)return{x:A.x,y:A.y}}set gridOrigin(A){if(!A){delete this._properties.gridOrigin;return}this.setProperty("gridOrigin",new GbA(A.x,A.y))}get visibleElements(){return this.getPropertyInstance("visibleElements",bbA)?.value}set visibleElements(A){this.setProperty("visibleElements",A===void 0?void 0:new bbA(A))}get padToPasteClearanceValues(){return this.getPropertyInstance("padToPasteClearanceValues",MbA)?.values}set padToPasteClearanceValues(A){if(A===void 0){delete this._properties.padToPasteClearanceValues;return}this.setProperty("padToPasteClearanceValues",new MbA(A))}get traceWidth(){return this.getPropertyInstance("traceWidth",RbA)?.values}set traceWidth(A){if(A===void 0){delete this._properties.traceWidth;return}this.setProperty("traceWidth",new RbA(A))}};UA.register(lxA);var Bme=class extends Ea{static token="thickness";static parentToken="general";token="thickness"};UA.register(Bme);var Cme=class Vke extends UA{static token="legacy_teardrops";static parentToken="general";token="legacy_teardrops";_enabled;constructor(A){super(),this._enabled=A}static fromSexprPrimitives(A){const e=Di(A[0]);if(e===void 0)throw new Error("legacy_teardrops expects a string value");const i=/^(yes|true)$/iu.test(e);return new Vke(i)}get enabled(){return this._enabled}set enabled(A){this._enabled=A}getChildren(){return[]}getString(){return`(legacy_teardrops ${this._enabled?"yes":"no"})`}};UA.register(Cme);var Qme=new Set(["thickness","legacy_teardrops"]),BxA=class jke extends UA{static token="general";static parentToken="kicad_pcb";token="general";_sxThickness;_sxLegacyTeardrops;static fromSexprPrimitives(A){const e=new jke,{propertyMap:i,arrayPropertyMap:n}=UA.parsePrimitivesToClassProperties(A,this.token);for(const o of Object.keys(i))if(!Qme.has(o))throw new Error(`general encountered unsupported child token "${o}"`);for(const[o,s]of Object.entries(n)){if(!Qme.has(o))throw new Error(`general encountered unsupported child token "${o}"`);if(s.length>1)throw new Error(`general encountered repeated child token "${o}"`)}return e._sxThickness=n.thickness?.[0]??i.thickness,e._sxLegacyTeardrops=n.legacy_teardrops?.[0]??i.legacy_teardrops,e}get thickness(){return this._sxThickness?.value}set thickness(A){this._sxThickness=A===void 0?void 0:new Bme(A)}get legacyTeardrops(){return this._sxLegacyTeardrops?.enabled}set legacyTeardrops(A){if(A===void 0){this._sxLegacyTeardrops=void 0;return}this._sxLegacyTeardrops=new Cme(A)}getChildren(){const A=[];return this._sxThickness&&A.push(this._sxThickness),this._sxLegacyTeardrops&&A.push(this._sxLegacyTeardrops),A}};UA.register(BxA);var jl=class zke extends UA{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,n,o]=A,s=Ci(e),r=Di(i),a=Di(n),g=o===void 0?void 0:Di(o);if(s===void 0||r===void 0||a===void 0)throw new Error(`layers entry is missing required values: ${JSON.stringify(A)}`);return new zke({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),Dn(this._name),this._type];return this._userName!==void 0&&A.push(Dn(this._userName)),`(${A.join(" ")})`}};UA.register(jl);var CxA=class Xke extends UA{static token="layers";static parentToken="kicad_pcb";token="layers";_definitions=[];static fromSexprPrimitives(A){const e=new Xke;return e._definitions=A.map(i=>jl.fromPrimitive(i)),e}get definitions(){return[...this._definitions]}set definitions(A){this._definitions=[...A]}getChildren(){return[...this._definitions]}};UA.register(CxA);var VX=class $ke extends UA{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=Ci(A[0]),i=Di(A[1]);if(e===void 0||i===void 0)throw new Error("net requires numeric id and string name");return new $ke(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} ${Dn(this._name)})`}};UA.register(VX);var QxA=class extends Ea{static token="version";static parentToken="kicad_pcb";token="version"};UA.register(QxA);var iEi=t=>/^[A-Za-z0-9._-]+$/.test(t),hxA=class extends Lm{static token="generator";static parentToken="kicad_pcb";token="generator";getString(){return`(generator ${iEi(this.value)?this.value:Dn(this.value)})`}};UA.register(hxA);var nEi=t=>/^[A-Za-z0-9._-]+$/.test(t),ExA=class extends Lm{static token="generator_version";static parentToken="kicad_pcb";token="generator_version";getString(){return`(generator_version ${nEi(this.value)?this.value:Dn(this.value)})`}};UA.register(ExA);var uxA=class Ave extends UA{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=Ci(A[0]);if(e===void 0)throw new Error("via net requires a numeric id");const i=A.length>1?Di(A[1]):void 0;return new Ave(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} ${Dn(this._name)})`:`(net ${this._id})`}};UA.register(uxA);var oEi=new Set(["locked","free","remove_unused_layers","keep_end_layers"]),dxA=class eve extends UA{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 eve;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[n,...o]=i;if(typeof n!="string")throw new Error(`via encountered child with non-string token: ${JSON.stringify(i)}`);e.consumeNode(n,o)}return e}consumeBareToken(A){if(A==="blind"||A==="micro"){this._type=A;return}if(!oEi.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=Di(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=UA.parsePrimitiveSexpr(["at",...e],{parentToken:this.token});if(!(i instanceof ac))throw new Error("via failed to parse at child");this._sxAt=i;return}case"size":{const i=Ci(e[0]);if(i===void 0)throw new Error("via size expects a numeric value");this._size=i;return}case"drill":{const i=Ci(e[0]);if(i===void 0)throw new Error("via drill expects a numeric value");this._drill=i;return}case"layers":{this._sxLayers=WX.fromSexprPrimitives(e);return}case"net":{this._sxNet=uxA.fromSexprPrimitives(e);return}case"teardrops":{this._sxTeardrops=U0e.fromSexprPrimitives(e);return}case"uuid":{const i=Di(e[0]);if(i===void 0)throw new Error("via uuid expects a string value");this._sxUuid=new qi(i);return}case"tstamp":{const i=Di(e[0]);if(i===void 0)throw new Error("via tstamp expects a string value");this._sxTstamp=new gc(i);return}default:throw new Error(`via encountered unsupported child token "${A}"`)}}parseYesNo(A){if(A.length===0)return!0;const e=Di(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?ac.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 WX?A:new WX(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 qi?A:new qi(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 gc?A:new gc(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(`
|
|
5829
|
-
`)}};UA.register(dxA);var pxA=class tve extends UA{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 tve;for(const i of A){if(!Array.isArray(i)||i.length===0)throw new Error(`kicad_pcb encountered unsupported primitive child: ${JSON.stringify(i)}`);const n=UA.parsePrimitiveSexpr(i,{parentToken:this.token});if(!(n instanceof UA))throw new Error(`kicad_pcb expected SxClass child, received ${JSON.stringify(i)}`);e.consumeChild(n)}return e}consumeChild(A){if(A instanceof QxA){this._sxVersion=A;return}if(A instanceof hxA){this._sxGenerator=A;return}if(A instanceof ExA){this._sxGeneratorVersion=A;return}if(A instanceof BxA){this._sxGeneral=A;return}if(A instanceof FX){this._sxPaper=A;return}if(A instanceof Cfe){this._sxTitleBlock=A;return}if(A instanceof CxA){this._sxLayers=A;return}if(A instanceof lxA){this._sxSetup=A;return}if(A instanceof vS){this._properties.push(A);return}if(A instanceof VX){this._nets.push(A);return}if(A instanceof cbA){this._footprints.push(A);return}if(A instanceof hfe){this._images.push(A);return}if(A instanceof mbA){this._segments.push(A);return}if(A instanceof KX){this._grLines.push(A);return}if(A instanceof qX){this._grTexts.push(A);return}if(A instanceof oye){this._grPolys.push(A);return}if(A instanceof tye){this._grRects.push(A);return}if(A instanceof dxA){this._vias.push(A);return}if(A instanceof Iye){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 QxA(A)}get generator(){return this._sxGenerator?.value}set generator(A){this._sxGenerator=A===void 0?void 0:new hxA(A)}get generatorVersion(){return this._sxGeneratorVersion?.value}set generatorVersion(A){this._sxGeneratorVersion=A===void 0?void 0:new ExA(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}};UA.register(pxA);var hme=t=>UA.parse(t),iu=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")}},sEi=class extends iu{_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 FX;e.size=A?.name??"A4",t.paper=e,t.uuid=new qi(crypto.randomUUID()),this.finished=!0}getOutput(){return this.ctx.kicadSch}};function $M(t,A){if(t.manufacturer_part_number)return fxA(t.manufacturer_part_number);const e=rEi(t.ftype),i=A?.footprinter_string;return fxA(i?`${e}_${i}`:e)}function rEi(t){if(!t)return"component";let A=t.replace(/^simple_/,"");return A||"component"}function fxA(t){return t.replace(/[\\\/:\s]+/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"").trim()||"component"}function Eme(t){return t?t.match(/^([A-Za-z]+)/)?.[1]?.toUpperCase()??"U":"U"}var ume={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"},aEi=/^[A-Za-z]+\d+$/;function dme(t){return t?aEi.test(t.trim()):!1}function jX(t){const A=t?.ftype;if(A&&ume[A])return ume[A];const e=t?.name;return dme(e),Eme(e)}function gEi(t){const A=t?.name;return dme(A)?A.trim():`${jX(t)}?`}function pme(t){return t in JQ}function fme(t,A,e,i){if(i)return`Custom:${i}`;if(t.type!=="source_component")return A.symbol_name?pme(A.symbol_name)?`Device:${A.symbol_name}`:`Custom:${A.symbol_name}`:"Device:Component";if(A.symbol_name)return pme(A.symbol_name)?`Device:${A.symbol_name}`:`Custom:${A.symbol_name}`;const n=$M(t,e);return`Device:${jX(t)}_${n}`}function cEi(t){const{circuitJson:A,schematicSymbolId:e,schematicSymbol:i,schematicComponentId:n}=t,o=A.filter(Q=>Q.type==="schematic_circle"&&Q.schematic_symbol_id===e),s=A.filter(Q=>Q.type==="schematic_line"&&Q.schematic_symbol_id===e),r=n?A.filter(Q=>Q.type==="schematic_line"&&Q.schematic_component_id===n&&!Q.schematic_symbol_id):[],a=[...s,...r],g=A.filter(Q=>Q.type==="schematic_path"&&Q.schematic_symbol_id===e),c=A.filter(Q=>Q.type==="schematic_text"&&Q.schematic_symbol_id===e);let I=A.filter(Q=>Q.type==="schematic_port"&&"schematic_symbol_id"in Q&&Q.schematic_symbol_id===e);if(I.length===0&&n){const Q=A.filter(E=>E.type==="schematic_port"&&E.schematic_component_id===n&&E.display_pin_label!==void 0),h=new Map;for(const E of Q)E.display_pin_label&&h.set(E.display_pin_label,E);if(I=h.size>0?Array.from(h.values()):Q,I.length===0){const E=A.filter(d=>d.type==="schematic_port"&&d.schematic_component_id===n),u=new Set;I=E.filter(d=>{const f=d.pin_number;if(f!==void 0){if(u.has(f))return!1;u.add(f)}return!0})}}const l=[];for(const Q of o)l.push({type:"circle",x:Q.center?.x??0,y:Q.center?.y??0,radius:Q.radius??.5,fill:Q.is_filled??!1,fillColor:Q.fill_color});for(const Q of a)l.push({type:"path",points:[{x:Q.x1??0,y:Q.y1??0},{x:Q.x2??0,y:Q.y2??0}]});for(const Q of g)Q.points&&Q.points.length>0&&l.push({type:"path",points:Q.points,fill:Q.is_filled??!1,fillColor:Q.fill_color});const B=c.map(Q=>({text:Q.text??"",x:Q.position?.x??0,y:Q.position?.y??0,fontSize:Q.font_size??.2,anchor:Q.anchor??"center"})),C=I.map((Q,h)=>({x:Q.center?.x??0,y:Q.center?.y??0,labels:[Q.display_pin_label||`${Q.pin_number||h+1}`],pinNumber:Q.pin_number||h+1,facingDirection:Q.facing_direction}));return C.sort((Q,h)=>Q.pinNumber-h.pinNumber),{center:i.center||{x:0,y:0},size:i.size||{width:1,height:1},primitives:l,texts:B,ports:C}}function IEi({points:t,transform:A,fillType:e}){const i=new ufe,n=t.map(a=>{const g=Ce(A,a);return new sh(g.x,g.y)}),o=new sQ(n);i.points=o;const s=new kS;s.width=.254,s.type="default",i.stroke=s;const r=new Dfe;return r.type=e,i.fill=r,i}function lEi({primitive:t,transform:A,scale:e}){const i=new xfe,n=Ce(A,{x:t.x,y:t.y}),o=i;o._sxCenter=new mfe(n.x,n.y),o._sxRadius=new wfe(t.radius*e);const s=new kS;s.width=.254,s.type="default",o._sxStroke=s;const r=new Sfe;return r.type=t.fill?"background":"none",o._sxFill=r,i}function BEi({schText:t,transform:A,scale:e}){const i=new _fe,n=Ce(A,{x:t.x,y:t.y});i.value=t.text,i.at=[n.x,n.y,0];const o=t.fontSize*e,s=new Zf;return s.size={height:o,width:o},i.effects=new Wf({font:s}),i}function CEi({libId:t,symbolData:A,isChip:e,c2kMatSchScale:i}){const n=new z2({libraryId:`${t.split(":")[1]}_0_1`}),o=i,s=A.center?.x??0,r=A.center?.y??0,a=An($a(o,o),on(-s,-r));for(const c of A.primitives||[])if(c.type==="path"&&c.points){const I=e||c.fill?"background":"none",l=IEi({points:c.points,transform:a,fillType:I});n.polylines.push(l)}else if(c.type==="circle"){const I=lEi({primitive:c,transform:a,scale:o});n.circles.push(I)}const g=Array.isArray(A.texts)?A.texts:[];for(const c of g){const I=BEi({schText:c,transform:a,scale:o});n.texts.push(I)}return n}function QEi(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,n=t.size?.height||1,o={type:"path",points:[{x:-i/2,y:-n/2},{x:i/2,y:-n/2},{x:i/2,y:n/2},{x:-i/2,y:n/2},{x:-i/2,y:-n/2}]},s=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:[o],ports:s,size:{width:i,height:n}}}function hEi(t,A){const e=new Zf;return e.size={height:t,width:t},new Wf({font:e,hiddenText:A})}function EEi({symbol:t,libId:A,description:e,keywords:i,fpFilters:n,footprintRef:o="",referencePrefix:s}){const r=s||A.split(":")[1]?.[0]||"U",a=[{key:"Reference",value:r,id:0,at:[2.032,0,90],hide:!1},{key:"Value",value:r,id:1,at:[0,0,90],hide:!1},{key:"Footprint",value:o,id:2,at:[-1.778,0,90],hide:!0},{key:"Datasheet",value:"~",id:3,at:[0,0,0],hide:!0},{key:"Description",value: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:n,id:6,at:[0,0,0],hide:!0}];for(const g of a)t.properties.push(new Vf({key:g.key,value:g.value,id:g.id,at:g.at,effects:hEi(1.27,g.hide)}))}function uEi({port:t,center:A,size:e,isChip:i,portIndex:n,schematicComponent:o,schematicPorts:s,c2kMatSchScale:r}){const a=r;let g=t.x??0,c=t.y??0,I=!1;if(i&&n!==void 0&&o){const y=s.filter(w=>w.schematic_component_id===o.schematic_component_id).sort((w,D)=>(w.pin_number||0)-(D.pin_number||0));if(y[n]){const w=y[n];g=w.center.x-o.center.x,c=w.center.y-o.center.y,I=!0}}let l,B;if(I)l=g,B=c;else{const y=A?.x??0,w=A?.y??0;l=g-y,B=c-w}const C=$a(a,a),Q=Ce(C,{x:l,y:B});let h;if(i&&e){const y=e.width/2,w=e.height/2,D=Math.abs(l)/y,S=Math.abs(B)/w;h=D>S}else h=Math.abs(l)>Math.abs(B);let E=Q.x,u=Q.y;const d=6;if(i&&e){const y=e.width/2*a,w=e.height/2*a;h?(E=l>0?y:-y,u=B*a):(E=l*a,u=B>0?w:-w)}let f=0;return h?l>0?(f=180,i&&(E=E+d)):(f=0,i&&(E=E-d)):B>0?(f=270,i&&(u=u+d)):(f=90,i&&(u=u-d)),{x:E,y:u,angle:f}}function dEi({libId:t,symbolData:A,isChip:e,schematicComponent:i,schematicPorts:n,c2kMatSchScale:o}){const s=new z2({libraryId:`${t.split(":")[1]}_1_1`}),r=6,a=2.54;for(let g=0;g<(A.ports?.length||0);g++){const c=A.ports[g],I=new GX;I.pinElectricalType="passive",I.pinGraphicStyle="line";const{x:l,y:B,angle:C}=uEi({port:c,center:A.center,size:A.size,isChip:e,portIndex:g,schematicComponent:i,schematicPorts:n,c2kMatSchScale:o});I.at=[l,B,C],I.length=e?r:a;const Q=new Zf;Q.size={height:1.27,width:1.27};const h=new Wf({font:Q}),E=c.labels?.[0]||"~";I._sxName=new ASA({value:E,effects:h});const u=new Zf;u.size={height:1.27,width:1.27};const d=new Wf({font:u}),f=c.pinNumber?.toString()||`${g+1}`;I._sxNumber=new vfe({value:f,effects:d}),s.pins.push(I)}return s}var pEi=class extends iu{processedSymbolNames=new Set;_step(){const{kicadSch:t,db:A}=this.ctx,e=new Ufe,i=[];this.processedSymbolNames=new Set;const n=A.schematic_component.list();for(const s of n){const r=this.createLibrarySymbolForComponent(s);r&&i.push(r)}const o=A.schematic_net_label?.list?.()||[];for(const s of o)if(s.symbol_name){const r=s.source_net_id?A.source_net.get(s.source_net_id)?.is_power:!1,a=s.source_net_id?A.source_net.get(s.source_net_id)?.is_ground:!1;if(r||a){const c=this.createLibrarySymbolForNetLabel({netLabel:s,isPower:r??!1,isGround:a??!1});c&&i.push(c)}}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(c=>c.source_component_id===e.source_component_id);let n=t.schematic_symbol_id;if(!n){const c=this.ctx.circuitJson.find(I=>(I.type==="schematic_line"||I.type==="schematic_circle"||I.type==="schematic_path")&&I.schematic_component_id===t.schematic_component_id&&I.schematic_symbol_id);c&&(n=c.schematic_symbol_id)}if(n)return this.createLibrarySymbolFromSchematicSymbol(t,e,i,n);const o=t.symbol_name||(e.ftype==="simple_chip"?`generic_chip_${t.source_component_id}`:null);if(!o)return null;const s=this.getSymbolData(o,t);if(!s)return null;const r=fme(e,t,i),a=e.ftype==="simple_chip",g=$M(e,i);return this.createLibrarySymbol({libId:r,symbolData:s,isChip:a,schematicComponent:t,description:this.getDescription(e),keywords:this.getKeywords(e),fpFilters:this.getFpFilters(e),footprintRef:g?`tscircuit:${g}`:"",referencePrefix:jX(e)})}createLibrarySymbolFromSchematicSymbol(t,A,e,i){const{db:n}=this.ctx,o=this.ctx.circuitJson.find(c=>c.type==="schematic_symbol"&&c.schematic_symbol_id===i);if(!o)return null;let s;if(o.name)s=o.name;else{const c=$M(A,e);c?s=c:s=`custom_${A.ftype||"component"}_${i}`}const r=`Custom:${s}`;if(this.processedSymbolNames.has(r))return null;this.processedSymbolNames.add(r);const a=cEi({circuitJson:this.ctx.circuitJson,schematicSymbolId:i,schematicSymbol:o,schematicComponentId:t.schematic_component_id}),g=$M(A,e);return this.createLibrarySymbol({libId:r,symbolData:a,isChip:!1,schematicComponent:t,description:this.getDescription(A),keywords:this.getKeywords(A),fpFilters:this.getFpFilters(A,o.name),footprintRef:g?`tscircuit:${g}`:"",referencePrefix:jX(A),symbolScale:1})}createLibrarySymbolForNetLabel({netLabel:t,isPower:A,isGround:e}){const i=t.symbol_name;if(!i)return null;const n=JQ[i];if(!n)return null;const o=`Custom:${i}`;return this.createLibrarySymbol({libId:o,symbolData:n,isChip:!1,schematicComponent:void 0,description:A?"Power net label":e?"Ground net label":"Net symbol",keywords:A?"power net":e?"ground net":"net",fpFilters:"",referencePrefix:o.split(":")[1]?.[0]||"U"})}getSymbolData(t,A){return t.startsWith("generic_chip_")?QEi(A,this.ctx.db):JQ[t]||null}createLibrarySymbol({libId:t,symbolData:A,isChip:e,schematicComponent:i,description:n,keywords:o,fpFilters:s,footprintRef:r="",referencePrefix:a,symbolScale:g}){const I=g??this.ctx.c2kMatSch?.a??15,l=new z2({libraryId:t,excludeFromSim:!1,inBom:!0,onBoard:!0}),B=new zDA;B.hide=!e,l._sxPinNumbers=B;const C=new $DA;C.offset=e?1.27:0,l._sxPinNames=C,EEi({symbol:l,libId:t,description:n,keywords:o,fpFilters:s,footprintRef:r,referencePrefix:a});const Q=CEi({libId:t,symbolData:A,isChip:e,c2kMatSchScale:I});l.subSymbols.push(Q);const h=dEi({libId:t,symbolData:A,isChip:e,schematicComponent:i,schematicPorts:this.ctx.db.schematic_port.list(),c2kMatSchScale:I});return l.subSymbols.push(h),l._sxEmbeddedFonts=new V2(!1),l}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,A){return A?`${A}*`:t?.ftype==="simple_resistor"?"R_*":t?.ftype==="simple_capacitor"?"C_*":(t?.ftype==="simple_chip","*")}getOutput(){if(!this.ctx.kicadSch)throw new Error("kicadSch is not initialized");return this.ctx.kicadSch}},fEi=class extends iu{_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 n of e){const o=n.source_component_id?A.source_component.get(n.source_component_id):null;if(!o||!this.ctx.c2kMatSch)continue;const{x:s,y:r}=Ce(this.ctx.c2kMatSch,{x:n.center.x,y:n.center.y}),a=crypto.randomUUID(),g=new z2({at:[s,r,0],unit:1,excludeFromSim:!1,inBom:!0,onBoard:!0,dnp:!1,uuid:a,fieldsAutoplaced:!0}),c=A.cad_component?.list()?.find(iA=>iA.source_component_id===o.source_component_id);let I,l=n.schematic_symbol_id;if(!l){const iA=this.ctx.circuitJson.find(sA=>(sA.type==="schematic_line"||sA.type==="schematic_circle"||sA.type==="schematic_path")&&sA.schematic_component_id===n.schematic_component_id&&sA.schematic_symbol_id);iA&&(l=iA.schematic_symbol_id)}if(l){const iA=this.ctx.circuitJson.find(sA=>sA.type==="schematic_symbol"&&sA.schematic_symbol_id===l);if(iA?.name)I=iA.name;else{const sA=$M(o,c);sA?I=sA:I=`custom_${o.ftype||"component"}_${l}`}}const B=fme(o,n,c,I),C=new VDA(B);g._sxLibId=C;const{reference:Q,value:h,description:E}=this.getComponentMetadata(o),{refTextPos:u,valTextPos:d}=this.getTextPositions(n,{x:s,y:r});let f;if(l){const iA=this.ctx.circuitJson.find(sA=>sA.type==="schematic_symbol"&&sA.schematic_symbol_id===l);iA&&iA.type==="schematic_symbol"&&(f=iA.metadata?.kicad_symbol)}const y=f?.properties?.Reference,w=new Vf({key:"Reference",value:y?.value??Q,id:0,at:[u.x,u.y,0],effects:this.createTextEffects(Number(y?.effects?.font?.size?.x??1.27),y?.effects?.hide??!1)}),D=o.ftype==="simple_chip",S=f?.properties?.Value,_=new Vf({key:"Value",value:S?.value??h,id:1,at:[d.x,d.y,0],effects:this.createTextEffects(Number(S?.effects?.font?.size?.x??1.27),S?.effects?.hide??D)}),b=f?.properties?.Footprint,N=new Vf({key:"Footprint",value:b?.value??"",id:2,at:[s-1.778,r,90],effects:this.createTextEffects(1.27,b?.effects?.hide??!0)}),F=f?.properties?.Datasheet,L=new Vf({key:"Datasheet",value:F?.value??"~",id:3,at:[s,r,0],effects:this.createTextEffects(1.27,F?.effects?.hide??!0)}),Y=f?.properties?.Description,J=new Vf({key:"Description",value:Y?.value??E,id:4,at:[s,r,0],effects:this.createTextEffects(1.27,Y?.effects?.hide??!0)});g.properties.push(w,_,N,L,J);const O=f?.properties?.ki_keywords;if(O?.value){const iA=new Vf({key:"ki_keywords",value:O.value,id:5,at:[s,r,0],effects:this.createTextEffects(1.27,O.effects?.hide??!0)});g.properties.push(iA)}const Z=f?.properties?.ki_fp_filters;if(Z?.value){const iA=new Vf({key:"ki_fp_filters",value:Z.value,id:6,at:[s,r,0],effects:this.createTextEffects(1.27,Z.effects?.hide??!0)});g.properties.push(iA)}if(f){if(f.inBom!==void 0&&(g.inBom=f.inBom),f.onBoard!==void 0&&(g.onBoard=f.onBoard),f.excludeFromSim!==void 0&&(g.excludeFromSim=f.excludeFromSim),f.pinNames){const iA=new $DA;f.pinNames.offset!==void 0&&(iA.offset=Number(f.pinNames.offset)),f.pinNames.hide!==void 0&&(iA.hide=f.pinNames.hide),g.pinNames=iA}if(f.pinNumbers){const iA=new zDA;f.pinNumbers.hide!==void 0&&(iA.hide=f.pinNumbers.hide),g.pinNumbers=iA}f.embeddedFonts!==void 0&&(g._sxEmbeddedFonts=new V2(f.embeddedFonts))}let X=A.schematic_port.list().filter(iA=>iA.schematic_component_id===n.schematic_component_id);if(l){const iA=X.filter(sA=>sA.display_pin_label);iA.length>0&&(X=iA)}X.sort((iA,sA)=>(iA.pin_number||0)-(sA.pin_number||0));for(let iA=0;iA<X.length;iA++){const sA=X[iA];if(!sA)continue;const aA=new GX;aA.numberString=`${sA.pin_number||iA+1}`,aA.uuid=crypto.randomUUID(),g.pins.push(aA)}const eA=new eSA,gA=new iSA(""),tA=new nSA(`/${t?.uuid?.value||""}`);tA.reference=Q,tA.unit=1,gA.paths.push(tA),eA.projects.push(gA),g._sxInstances=eA,i.push(g)}t&&(t.symbols=i),this.finished=!0}getTextPositions(t,A){const i=(this.ctx.db.schematic_text?.list?.()?.filter(B=>B.schematic_component_id===t.schematic_component_id)||[]).find(B=>B.text&&B.text.length>0);if(i&&this.ctx.c2kMatSch){const B=Ce(this.ctx.c2kMatSch,{x:i.position.x,y:i.position.y}),C={x:A.x,y:A.y+6};return{refTextPos:B,valTextPos:C}}const n=t.symbol_name,o=JQ[n];if(!o)return{refTextPos:{x:A.x,y:A.y-6},valTextPos:{x:A.x,y:A.y+6}};let s=null,r=null;for(const B of o.primitives)B.type==="text"&&(B.text==="{REF}"?s=B:B.text==="{VAL}"&&(r=B));const a=o.center||{x:0,y:0},c=n.includes("_down")||n.includes("_up")?.15:0,I=s&&this.ctx.c2kMatSch?Ce(this.ctx.c2kMatSch,{x:t.center.x+(s.x-a.x)+c,y:t.center.y+(s.y-a.y)}):{x:A.x,y:A.y-6},l=r&&this.ctx.c2kMatSch?Ce(this.ctx.c2kMatSch,{x:t.center.x+(r.x-a.x)+c,y:t.center.y+(r.y-a.y)}):{x:A.x,y:A.y+6};return{refTextPos:I,valTextPos:l}}getComponentMetadata(t){const A=t.name||"?",e=gEi(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"}:t.ftype==="simple_potentiometer"?{reference:e,value:t.display_max_resistance||"",description:"Potentiometer"}:{reference:e,value:A,description:"Component"}}createTextEffects(t,A=!1,e){const i=new Zf;i.size={height:t,width:t};const n=e?new wP({horizontal:e}):void 0;return new Wf({font:i,hiddenText:A,justify:n})}getOutput(){if(!this.ctx.kicadSch)throw new Error("kicadSch is not initialized");return this.ctx.kicadSch}},yEi=class extends iu{_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=[],n=[];for(const o of e){const s=o.text||"",r=o.symbol_name;if(r){const a=this.createSymbolFromNetLabel(o,s,r);a&&i.push(a)}else{const a=this.createGlobalLabel(o,s);a&&n.push(a)}}if(t&&i.length>0){const o=t.symbols||[];t.symbols=[...o,...i]}t&&n.length>0&&(t.globalLabels=[...t.globalLabels||[],...n]),this.finished=!0}createSymbolFromNetLabel(t,A,e){if(!this.ctx.c2kMatSch)return null;const{x:i,y:n}=Ce(this.ctx.c2kMatSch,{x:t.anchor_position?.x??t.center?.x??0,y:t.anchor_position?.y??t.center?.y??0}),o=crypto.randomUUID(),s=new z2({at:[i,n,0],unit:1,excludeFromSim:!1,inBom:!0,onBoard:!0,dnp:!1,uuid:o,fieldsAutoplaced:!0}),r=`Custom:${e}`,a=new VDA(r);s._sxLibId=a;const g=e.includes("_up")||e.toLowerCase().includes("vcc"),c=g?-4:4,I=g?-6:6,l=new Vf({key:"Reference",value:A,id:0,at:[i,n+c,0],effects:this.createTextEffects(1.27,!1)}),B=new Vf({key:"Value",value:A,id:1,at:[i,n+I,0],effects:this.createTextEffects(1.27,!0)}),C=new Vf({key:"Footprint",value:"",id:2,at:[i-1.778,n,90],effects:this.createTextEffects(1.27,!0)}),Q=new Vf({key:"Datasheet",value:"~",id:3,at:[i,n,0],effects:this.createTextEffects(1.27,!0)}),h=new Vf({key:"Description",value:`Power/Net symbol: ${A}`,id:4,at:[i,n,0],effects:this.createTextEffects(1.27,!0)});s.properties.push(l,B,C,Q,h);const E=new GX;E.numberString="1",E.uuid=crypto.randomUUID(),s.pins.push(E);const{kicadSch:u}=this.ctx,d=new eSA,f=new iSA(""),y=new nSA(`/${u?.uuid?.value||""}`);return y.reference=A,y.unit=1,f.paths.push(y),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}=Ce(this.ctx.c2kMatSch,{x:t.anchor_position?.x??t.center?.x??0,y:t.anchor_position?.y??t.center?.y??0}),n=t.anchor_side||"left",s={left:0,right:180,top:270,bottom:90}[n]||0,a={left:{horizontal:"left"},right:{horizontal:"right"},top:{vertical:"top"},bottom:{vertical:"bottom"}}[n]||{},g=this.createTextEffects(1.27,!1);return Object.keys(a).length>0&&(g.justify=new wP(a)),new Wfe({value:A,at:[e,i,s],effects:g,uuid:crypto.randomUUID(),fieldsAutoplaced:!0})}createTextEffects(t,A=!1){const e=new Zf;return e.size={height:t,width:t},new Wf({font:e,hiddenText:A})}getOutput(){if(!this.ctx.kicadSch)throw new Error("kicadSch is not initialized");return this.ctx.kicadSch}},mEi=class extends iu{_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=[],n=[];for(const o of e){for(const s of o.edges){const r=this.createWireFromEdge(s);i.push(r)}for(const s of o.junctions){const r=this.createJunction(s);n.push(r)}}t.wires=i,t.junctions=n,this.finished=!0}createWireFromEdge(t){const A=new Yfe;if(!this.ctx.c2kMatSch)throw new Error("Schematic transformation matrix not initialized in context");const e=Ce(this.ctx.c2kMatSch,{x:t.from.x,y:t.from.y}),i=Ce(this.ctx.c2kMatSch,{x:t.to.x,y:t.to.y}),n=e.x,o=e.y,s=i.x,r=i.y,a=new sQ([new sh(n,o),new sh(s,r)]);A.points=a;const g=new kS;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}=Ce(this.ctx.c2kMatSch,{x:t.x,y:t.y}),i=new Jfe({at:[A,e],diameter:0});return i.uuid=crypto.randomUUID(),i}getOutput(){return this.ctx.kicadSch}},wEi=class extends iu{_step(){const{kicadSch:t}=this.ctx;if(!t)throw new Error("KicadSch instance not initialized in context");const A=new aSA,e=new jfe;e.value="/";const i=new zfe("1");e.pages=[i],A.paths=[e],t.sheetInstances=A,t.embeddedFonts=new V2(!1),this.finished=!0}getOutput(){return this.ctx.kicadSch}};function DEi(t){const A=t.schematic_component.list(),e=t.schematic_trace.list();let i=1/0,n=1/0,o=-1/0,s=-1/0;for(const g of A){const c=g.size?.width??0,I=g.size?.height??0;i=Math.min(i,g.center.x-c/2),n=Math.min(n,g.center.y-I/2),o=Math.max(o,g.center.x+c/2),s=Math.max(s,g.center.y+I/2)}for(const g of e)for(const c of g.edges)i=Math.min(i,c.from.x,c.to.x),n=Math.min(n,c.from.y,c.to.y),o=Math.max(o,c.from.x,c.to.x),s=Math.max(s,c.from.y,c.to.y);i===1/0&&(i=0,n=0,o=0,s=0);const r=(i+o)/2,a=(n+s)/2;return{center:{x:r,y:a},bounds:{minX:i,minY:n,maxX:o,maxY:s}}}var zX=[{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 SEi(t,A,e=20){const i=t+2*e,n=A+2*e;for(let o=0;o<zX.length;o++){const s=zX[o];if(i<=s.width&&n<=s.height)return s}return zX[zX.length-1]}var yme=class{ctx;pipeline;currentStageIndex=0;finished=!1;get currentStage(){return this.pipeline[this.currentStageIndex]}constructor(t){const e=Ua(t),{center:i,bounds:n}=DEi(e),o=(n.maxX-n.minX)*15,s=(n.maxY-n.minY)*15,r=SEi(o,s),a=r.width/2,g=r.height/2;this.ctx={db:e,circuitJson:t,kicadSch:new cSA({generator:"circuit-json-to-kicad",generatorVersion:"0.0.1"}),schematicPaperSize:r,c2kMatSch:An(on(a,g),$a(15,-15),on(-i.x,-i.y))},this.pipeline=[new sEi(t,this.ctx),new pEi(t,this.ctx),new fEi(t,this.ctx),new yEi(t,this.ctx),new mEi(t,this.ctx),new wEi(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()}},bEi=class extends iu{_step(){const{kicadPcb:t,db:A}=this.ctx;if(!t)throw new Error("KicadPcb instance not initialized in context");const i=A.pcb_board?.list()?.[0]?.num_layers??2;this.ctx.numLayers=i,t.version=20241229;const n=new FX;n.size="A4",t.paper=n;const o=new BxA;o.thickness=1.6,t.general=o;const s=new lxA;s.padToMaskClearance=0,t.setup=s;const r=new CxA,a=[new jl({index:0,name:"F.Cu",type:"signal"})];for(let g=1;g<i-1;g++)a.push(new jl({index:g,name:`In${g}.Cu`,type:"signal"}));a.push(new jl({index:31,name:"B.Cu",type:"signal"})),a.push(new jl({index:32,name:"B.Adhes",type:"user"}),new jl({index:33,name:"F.Adhes",type:"user"}),new jl({index:34,name:"B.Paste",type:"user"}),new jl({index:35,name:"F.Paste",type:"user"}),new jl({index:36,name:"B.SilkS",type:"user"}),new jl({index:37,name:"F.SilkS",type:"user"}),new jl({index:38,name:"B.Mask",type:"user"}),new jl({index:39,name:"F.Mask",type:"user"}),new jl({index:40,name:"Dwgs.User",type:"user"}),new jl({index:41,name:"Cmts.User",type:"user"}),new jl({index:42,name:"Eco1.User",type:"user"}),new jl({index:43,name:"Eco2.User",type:"user"}),new jl({index:44,name:"Edge.Cuts",type:"user"}),new jl({index:45,name:"Margin",type:"user"}),new jl({index:46,name:"B.CrtYd",type:"user"}),new jl({index:47,name:"F.CrtYd",type:"user"}),new jl({index:48,name:"B.Fab",type:"user"}),new jl({index:49,name:"F.Fab",type:"user"})),r.definitions=a,t.layers=r,this.finished=!0}getOutput(){return this.ctx.kicadPcb}},xEi=class extends iu{_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||"",c=g&&g.trim().length>0?g:a;A.set(a,c)}const i=this.ctx.db.source_trace?.list()??[];for(const r of i){let a=r.subcircuit_connectivity_map_key;if(!a&&r.connected_source_net_ids?.length)for(const g of r.connected_source_net_ids){const c=this.ctx.db.source_net?.get(g);if(c?.subcircuit_connectivity_map_key&&c.subcircuit_connectivity_map_key.length>0){a=c.subcircuit_connectivity_map_key;break}}if(a&&!A.has(a)){const g=r.display_name||r.source_trace_id||"",c=g&&g.trim().length>0?g:a;A.set(a,c)}}const n=Array.from(A.entries()).sort((r,a)=>r[0].localeCompare(a[0])),o=[];o.push(new VX(0,""));let s=1;for(const[r,a]of n){const g=new VX(s,a);o.push(g);const c={id:s,name:a};this.ctx.pcbNetMap.set(r,c),s++}t.nets=o,this.finished=!0}getOutput(){return this.ctx.kicadPcb}};function _Ei(t){let A=0;for(let i=0;i<t.length;i++){const n=t.charCodeAt(i);A=(A<<5)-A+n,A=A&A}let e="";for(let i=0;i<4;i++){let n=A;for(let o=0;o<t.length;o++)n=(n<<5)-n+t.charCodeAt(o)+i*31,n=n&n;e+=Math.abs(n).toString(16).padStart(8,"0")}return e}function jf(t){const A=_Ei(t);return`${A.slice(0,8)}-${A.slice(8,12)}-${A.slice(12,16)}-${A.slice(16,20)}-${A.slice(20,32)}`}var mme="https://modelcdn.tscircuit.com/jscad_models",kEi=20240108,vEi="pcbnew",FEi="8.0";function yxA(t){const A=t.split(/[/\\]/);return A[A.length-1]||t}var MEi=class extends iu{classifyFootprints(){const t=new Set,A=new Map,e=this.ctx.db.cad_component?.list()??[],i=this.ctx.db.source_component;for(const n of e){const o=n.source_component_id?i?.get(n.source_component_id):null;if(!o)continue;const s=$M(o,n);if(n.footprinter_string)A.set(s,n.footprinter_string);else{t.add(s);const r=this.ctx.circuitJson.find(a=>a.type==="pcb_component"&&a.source_component_id===n.source_component_id);r&&r.type==="pcb_component"&&r.metadata?.kicad_footprint?.footprintName&&t.add(r.metadata.kicad_footprint.footprintName)}}return{customFootprintNames:t,footprinterStrings:A}}_step(){const t=this.ctx.kicadPcbString,A=this.ctx.fpLibraryName??"tscircuit";if(!t)throw new Error("PCB content not available. Run GenerateKicadSchAndPcbStage first.");const{customFootprintNames:e,footprinterStrings:i}=this.classifyFootprints(),n=new Map;try{const s=hme(t).find(a=>a instanceof pxA);if(!s){this.ctx.footprintEntries=[],this.finished=!0;return}const r=s.footprints??[];for(const a of r){const g=this.sanitizeFootprint({footprint:a,fpLibraryName:A,customFootprintNames:e,footprinterStrings:i});n.has(g.footprintName)||n.set(g.footprintName,g)}}catch(o){console.warn("Failed to parse PCB for footprint extraction:",o)}this.ctx.footprintEntries=Array.from(n.values()),this.finished=!0}sanitizeFootprint({footprint:t,fpLibraryName:A,customFootprintNames:e,footprinterStrings:i}){const o=(t.libraryLink??"footprint").split(":"),s=(o.length>1?o[1]:o[0])?.replace(/[\\\/]/g,"-").trim()||"footprint",r=!e.has(s);if(t.libraryLink=s,t.position=ac.from([0,0,0]),t.locked=!1,t.placed=!1,t.version=kEi,t.generator=vEi,t.generatorVersion=FEi,t.descr||(t.descr=""),t.tags||(t.tags=""),t.embeddedFonts||(t.embeddedFonts=new V2(!1)),!t.attr){const f=new ISA,y=(t.fpPads??[]).map(w=>w.padType);y.some(w=>w.includes("thru_hole"))?f.type="through_hole":y.some(w=>w.includes("smd"))&&(f.type="smd"),t.attr=f}t.uuid=void 0,t.path=void 0,t.sheetfile=void 0,t.sheetname=void 0;const a=new Zf;a.size={width:1.27,height:1.27},a.thickness=.15;const g=new Wf({font:a}),c=t.fpPads??[];let I=0,l=0;for(const f of c){const y=f.at,w=f.size;if(y&&w){const D=y.y??0,S=w.height??0,_=D-S/2,b=D+S/2;I=Math.min(I,_),l=Math.max(l,b)}}const B=I-.5,C=l+.5;t.properties=[new vS({key:"Reference",value:"REF**",position:[0,B,0],layer:"F.SilkS",uuid:jf(`${s}-property-Reference`),effects:g}),new vS({key:"Value",value:"Val**",position:[0,C,0],layer:"F.Fab",uuid:jf(`${s}-property-Value`),effects:g}),new vS({key:"Datasheet",value:"",position:[0,0,0],layer:"F.Fab",hidden:!0,uuid:jf(`${s}-property-Datasheet`),effects:g}),new vS({key:"Description",value:"",position:[0,0,0],layer:"F.Fab",hidden:!0,uuid:jf(`${s}-property-Description`),effects:g})];const Q=t.fpTexts??[];for(const f of Q)f.uuid=void 0,f.type==="reference"?f.text="REF**":f.type==="value"&&f.text.trim().length===0&&(f.text=s);t.fpTexts=Q;const h=t.fpPads??[];for(let f=0;f<h.length;f++){const y=h[f];y&&(y.uuid=jf(`${s}-pad-${y.number??f}`),y.net=void 0)}t.fpPads=h;const E=t.models??[],u=[],d=[];for(const f of E)if(f.path){const y=yxA(f.path),w=`../../3dmodels/${A}.3dshapes/${y}`,D=new XM(w);f.offset&&(D.offset=f.offset),f.scale&&(D.scale=f.scale),f.rotate&&(D.rotate=f.rotate),u.push(D),d.push(f.path)}if(u.length===0){const f=i.get(s);if(f){const y=`${mme}/${f}.step`,D=`../../3dmodels/tscircuit_builtin.3dshapes/${yxA(y)}`;u.push(new XM(D)),d.push(y)}}return t.models=u,{footprintName:s,kicadModString:t.getString(),model3dSourcePaths:d,isBuiltin:r}}getOutput(){return this.ctx.libraryOutput}};function XX(t){const A=new Zf;return t?.font?.size?A.size={width:Number(t.font.size.x),height:Number(t.font.size.y)}:A.size={width:1.27,height:1.27},t?.font?.thickness!==void 0?A.thickness=Number(t.font.thickness):A.thickness=.15,new Wf({font:A})}function REi(t,A,e){if(A.properties){const i=[],n=A.properties.Reference;i.push(new vS({key:"Reference",value:n?.value??e,position:n?.at?[Number(n.at.x),Number(n.at.y),Number(n.at.rotation??0)]:[0,-3,0],layer:n?.layer??"F.SilkS",uuid:jf(`${e}-property-Reference`),effects:XX(n?.effects),hidden:n?.hide}));const o=A.properties.Value,s=o?.value??A.footprintName??"";i.push(new vS({key:"Value",value:s,position:o?.at?[Number(o.at.x),Number(o.at.y),Number(o.at.rotation??0)]:[0,3,0],layer:o?.layer??"F.Fab",uuid:jf(`${e}-property-Value`),effects:XX(o?.effects),hidden:o?.hide}));const r=A.properties.Datasheet;i.push(new vS({key:"Datasheet",value:r?.value??"",position:r?.at?[Number(r.at.x),Number(r.at.y),Number(r.at.rotation??0)]:[0,0,0],layer:r?.layer??"F.Fab",uuid:jf(`${e}-property-Datasheet`),effects:XX(r?.effects),hidden:r?.hide??!0}));const a=A.properties.Description;i.push(new vS({key:"Description",value:a?.value??"",position:a?.at?[Number(a.at.x),Number(a.at.y),Number(a.at.rotation??0)]:[0,0,0],layer:a?.layer??"F.Fab",uuid:jf(`${e}-property-Description`),effects:XX(a?.effects),hidden:a?.hide??!0})),t.properties=i}if(A.attributes&&(t.attr||(t.attr=new ISA),A.attributes.through_hole?t.attr.type="through_hole":A.attributes.smd&&(t.attr.type="smd"),A.attributes.exclude_from_pos_files!==void 0&&(t.attr.excludeFromPosFiles=A.attributes.exclude_from_pos_files),A.attributes.exclude_from_bom!==void 0&&(t.attr.excludeFromBom=A.attributes.exclude_from_bom)),A.footprintName&&(t.libraryLink=A.footprintName),A.layer&&(t.layer=A.layer),A.embeddedFonts!==void 0&&(t.embeddedFonts=new V2(A.embeddedFonts)),A.model){const i=new XM(A.model.path);A.model.offset&&(i.offset={x:Number(A.model.offset.x),y:Number(A.model.offset.y),z:Number(A.model.offset.z)}),A.model.scale&&(i.scale={x:Number(A.model.scale.x),y:Number(A.model.scale.y),z:Number(A.model.scale.z)}),A.model.rotate&&(i.rotate={x:Number(A.model.rotate.x),y:Number(A.model.rotate.y),z:Number(A.model.rotate.z)});const n=t.models||[];t.models=[i,...n]}}function NEi(t,A){const e=[];for(const i of t){const n=i.center.x-A.x,o=-(i.center.y-A.y),r={top:"F.SilkS",bottom:"B.SilkS"}[i.layer]||i.layer||"F.SilkS",a=new ZSA({center:{x:n,y:o},end:{x:n+i.radius,y:o},layer:r,stroke:new kS,fill:!1});a.stroke&&(a.stroke.width=i.stroke_width||.05,a.stroke.type="default"),e.push(a)}return e}function GEi(t,A){const e=[];for(const i of t){const n=i.center.x-A.x,o=-(i.center.y-A.y),r={top:"F.CrtYd",bottom:"B.CrtYd"}[i.layer]||"F.CrtYd",a=new ZSA({center:{x:n,y:o},end:{x:n+i.radius,y:o},layer:r,stroke:new kS,fill:!1});a.stroke&&(a.stroke.width=.05,a.stroke.type="default"),e.push(a)}return e}function LEi(t,A){const e=[];for(const i of t){const n=i.center.x-A.x,o=-(i.center.y-A.y),s=i.width/2,r=i.height/2,g={top:"F.Fab",bottom:"B.Fab"}[i.layer]||i.layer||"F.Fab",c=new YX({start:{x:n-s,y:o-r},end:{x:n+s,y:o+r},layer:g,stroke:new kS,fill:!1});c.stroke&&(c.stroke.width=i.stroke_width||.1,c.stroke.type="default"),e.push(c)}return e}function UEi(t,A){const e=[];for(const i of t){const n=i.center.x-A.x,o=-(i.center.y-A.y),s=i.width/2,r=i.height/2,a="F.Fab",g=new YX({start:{x:n-s,y:o-r},end:{x:n+s,y:o+r},layer:a,stroke:new kS,fill:!1});g.stroke&&(g.stroke.width=i.stroke_width||.1,g.stroke.type="default"),e.push(g)}return e}function HEi(t,A){const e=[];for(const i of t){const n=i.center.x-A.x,o=-(i.center.y-A.y),s=i.width/2,r=i.height/2,g={top:"F.CrtYd",bottom:"B.CrtYd"}[i.layer]||"F.CrtYd",c=new YX({start:{x:n-s,y:o-r},end:{x:n+s,y:o+r},layer:g,stroke:new kS,fill:!1});c.stroke&&(c.stroke.width=.05,c.stroke.type="default"),e.push(c)}return e}function YEi(t,A){const e=[];for(const i of t){if(!i.outline||i.outline.length<2)continue;const o={top:"F.CrtYd",bottom:"B.CrtYd"}[i.layer]||"F.CrtYd",s=i.outline.map(g=>{const c=g.x-A.x,I=-(g.y-A.y);return new sh(c,I)}),r=new P0e;r.points=new sQ(s),r.layer=o,r.fill=!1;const a=new kS;a.width=.05,a.type="default",r.stroke=a,e.push(r)}return e}function JEi({textElement:t,componentCenter:A,componentRotation:e=0}){if(!t.text||!t.anchor_position)return null;const i=t.anchor_position.x-A.x,n=-(t.anchor_position.y-A.y),o=e!==0?Tl(e*Math.PI/180):xa(),s=Ce(o,{x:i,y:n}),r={x:s.x,y:s.y},g={top:"F.SilkS",bottom:"B.SilkS"}[t.layer]||t.layer||"F.SilkS",c=(t.font_size||1)/1.5,I=new Zf;I.size={width:c,height:c};const l=new Wf({font:I}),B=t.ccw_rotation||0;return new USA({type:"user",text:t.text,position:{x:r.x,y:r.y,angle:B},layer:g,effects:l})}function TEi(t,A,e,i){const n=[];for(const o of t){const s=JEi({textElement:o,componentCenter:A,componentRotation:e});s&&(i&&o.text===i&&(s.type="reference"),n.push(s))}return n}function PEi(t,A,e){const i=[];for(const n of t){const o=n.anchor_position.x-A.x,s=-(n.anchor_position.y-A.y),r=e!==0?Tl(e*Math.PI/180):xa(),a=Ce(r,{x:o,y:s}),g=n.font_size||1,c=new Zf;c.size={width:g,height:g};const I=new Wf({font:c}),l=new USA({type:"user",text:n.text,position:{x:a.x,y:a.y,angle:0},layer:"F.Fab",effects:I});i.push(l)}return i}function KEi(t,A){const e=[],i=t.model_step_url||t.model_wrl_url;if(!i)return e;const n=new XM(i);if(t.position&&(n.offset={x:(t.position.x||0)-A.x,y:-((t.position.y||0)-A.y),z:t.position.z||0}),t.rotation&&(n.rotate={x:t.rotation.x||0,y:t.rotation.y||0,z:t.rotation.z||0}),t.model_unit_to_mm_scale_factor){const o=t.model_unit_to_mm_scale_factor;n.scale={x:o,y:o,z:o}}return e.push(n),e}function qEi({pcbPad:t,componentCenter:A,padNumber:e,componentRotation:i=0,netInfo:n,componentId:o}){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=An(i!==0?Tl(i*Math.PI/180):{a:1,b:0,c:0,d:1,e:0,f:0},$a(1,-1),on(-A.x,-A.y)),g=Ce(a,{x:s,y:r}),I={top:"F.Cu",bottom:"B.Cu"}[t.layer]||"F.Cu";let l,B,C,Q;if(t.shape==="circle")l="circle",B=["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=An($a(1,-1),on(-s,-r)),f=u.map(w=>{const D=Ce(d,{x:w.x,y:w.y});return new sh(D.x,D.y)}),y=new MSA;y.contours=[new sQ(f)],y.width=0,y.filled=!0,Q=new S0e,Q.addGraphic(y),l="custom",C=new g0e,C.anchor="circle",B=[.2,.2]}else l="rect",B=["width"in t?t.width:.5,"height"in t?t.height:.5];const h=`pad:${o}:${e}:${g.x},${g.y}`,E=new HX({number:String(e),padType:"smd",shape:l,at:[g.x,g.y,0],size:B,layers:[`${I}`,`${I==="F.Cu"?"F":"B"}.Paste`,`${I==="F.Cu"?"F":"B"}.Mask`],uuid:jf(h)});return C&&(E.options=C),Q&&(E.primitives=Q),n&&(E.net=new bSA(n.id,n.name)),E}function OEi(t,A,e,i,n,o){const s=[];let r=n;for(const a of t){const g=o(a.pcb_port_id),c=qEi({pcbPad:a,componentCenter:A,padNumber:r,componentRotation:e,netInfo:g,componentId:i});s.push(c),r++}return{pads:s,nextPadNumber:r}}function WEi({platedHole:t,componentCenter:A,padNumber:e,componentRotation:i=0,netInfo:n,componentId:o}){if(!("x"in t&&"y"in t))return null;const s=t.x-A.x,r=-(t.y-A.y),a=i!==0?Tl(i*Math.PI/180):xa(),g=Ce(a,{x:s,y:r});let c="circle",I,l,B=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=Ce(a,{x:-u.x,y:u.y}))}t.shape==="circle"?(c="circle",I=[t.outer_diameter,t.outer_diameter],l=new FS({diameter:t.hole_diameter,offset:Q})):t.shape==="pill"||t.shape==="oval"?(c="oval",I=[t.outer_width,t.outer_height],l=new FS({oval:!0,diameter:t.hole_width,width:t.hole_height,offset:Q})):t.shape==="pill_hole_with_rect_pad"?(c="rect",I=[t.rect_pad_width,t.rect_pad_height],l=new FS({oval:!0,diameter:t.hole_width,width:t.hole_height,offset:Q})):t.shape==="circular_hole_with_rect_pad"?(c="rect",I=[t.rect_pad_width,t.rect_pad_height],l=new FS({diameter:t.hole_diameter,offset:Q})):t.shape==="rotated_pill_hole_with_rect_pad"?(c="rect",I=[t.rect_pad_width,t.rect_pad_height],l=new FS({oval:!0,diameter:t.hole_width,width:t.hole_height,offset:Q}),B=t.rect_ccw_rotation||0):(c="circle",I=[1.6,1.6],l=new FS({diameter:.8,offset:Q}));const h=`thruhole:${o}:${e}:${g.x},${g.y}`,E=new HX({number:String(e),padType:"thru_hole",shape:c,at:[g.x,g.y,B],size:I,drill:l,layers:["*.Cu","*.Mask"],removeUnusedLayers:!1,uuid:jf(h)});return n&&(E.net=new bSA(n.id,n.name)),E}function ZEi(t,A,e,i,n,o){const s=[];let r=n;for(const a of t){const g=o(a.pcb_port_id),c=WEi({platedHole:a,componentCenter:A,padNumber:r,componentRotation:e,netInfo:g,componentId:i});c&&(s.push(c),r++)}return{pads:s,nextPadNumber:r}}function VEi({pcbHole:t,componentCenter:A,componentRotation:e=0}){if(!("x"in t&&"y"in t))return null;const i=t.x-A.x,n=-(t.y-A.y),o=e!==0?Tl(e*Math.PI/180):xa(),s=Ce(o,{x:i,y:n});let r="circle",a,g;if(t.hole_shape==="circle"){r="circle";const c=t.hole_diameter;a=[c,c],g=new FS({diameter:c})}else if(t.hole_shape==="oval"){r="oval";const c=t.hole_width,I=t.hole_height;a=[c,I],g=new FS({oval:!0,diameter:c,width:I})}else{r="circle";const c="hole_diameter"in t?t.hole_diameter:1;a=[c,c],g=new FS({diameter:c})}return new HX({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 jEi(t,A,e){const i=[];for(const n of t){const o=VEi({pcbHole:n,componentCenter:A,componentRotation:e});o&&i.push(o)}return i}var zEi=class extends iu{componentsProcessed=0;pcbComponents=[];includeBuiltin3dModels;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 n=i.subcircuit_connectivity_map_key;if(n)return this.ctx.pcbNetMap?.get(n)}getCadComponentForPcbComponent(t){return(this.ctx.db.cad_component?.list()||[]).find(e=>e.pcb_component_id===t)}constructor(t,A,e){super(t,A),this.pcbComponents=this.ctx.db.pcb_component.list(),this.includeBuiltin3dModels=e?.includeBuiltin3dModels??!1}_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,n=this.getCadComponentForPcbComponent(e.pcb_component_id),o=i?$M(i,n):"Unknown",s=Ce(A,{x:e.center.x,y:e.center.y}),r=`footprint:${e.pcb_component_id}:${s.x},${s.y}`,a=new cbA({libraryLink:`tscircuit:${o}`,layer:"F.Cu",at:[s.x,s.y,e.rotation||0],uuid:jf(r)}),g=a.fpTexts,c=this.ctx.db.pcb_silkscreen_text?.list().filter(O=>O.pcb_component_id===e.pcb_component_id)||[];g.push(...TEi(c,e.center,e.rotation||0,i?.name));const I=this.ctx.db.pcb_note_text?.list().filter(O=>O.pcb_component_id===e.pcb_component_id)||[];g.push(...PEi(I,e.center,e.rotation||0)),a.fpTexts=g;const l=a.fpPads,B=O=>this.getNetInfoForPcbPort(O),C=this.ctx.db.pcb_smtpad?.list().filter(O=>O.pcb_component_id===e.pcb_component_id)||[],{pads:Q,nextPadNumber:h}=OEi(C,e.center,e.rotation||0,e.pcb_component_id,1,B);l.push(...Q);const E=this.ctx.db.pcb_plated_hole?.list().filter(O=>O.pcb_component_id===e.pcb_component_id)||[],{pads:u}=ZEi(E,e.center,e.rotation||0,e.pcb_component_id,h,B);l.push(...u);const d=this.ctx.db.pcb_hole?.list().filter(O=>O.subcircuit_id===e.subcircuit_id)||[],f=jEi(d,e.center,e.rotation||0);l.push(...f),a.fpPads=l;const y=this.ctx.db.pcb_silkscreen_circle?.list().filter(O=>O.pcb_component_id===e.pcb_component_id)||[],w=a.fpCircles??[];w.push(...NEi(y,e.center));const D=this.ctx.db.pcb_courtyard_circle?.list().filter(O=>O.pcb_component_id===e.pcb_component_id)||[];w.push(...GEi(D,e.center)),a.fpCircles=w;const S=this.ctx.db.pcb_fabrication_note_rect?.list().filter(O=>O.pcb_component_id===e.pcb_component_id)||[],_=a.fpRects??[];_.push(...LEi(S,e.center));const b=this.ctx.db.pcb_note_rect?.list().filter(O=>O.pcb_component_id===e.pcb_component_id)||[];_.push(...UEi(b,e.center));const N=this.ctx.db.pcb_courtyard_rect?.list().filter(O=>O.pcb_component_id===e.pcb_component_id)||[];_.push(...HEi(N,e.center)),a.fpRects=_;const F=this.ctx.db.pcb_courtyard_outline?.list().filter(O=>O.pcb_component_id===e.pcb_component_id)||[],L=YEi(F,e.center);if(L.length>0&&(a.fpPolys=L),n){const O=KEi(n,e.center),Z="${KIPRJMOD}/3dmodels";if(O.length>0)this.includeBuiltin3dModels?a.models=O.map(X=>{if(!X.path)return X;const eA=yxA(X.path),gA=this.ctx.projectName??eA.replace(/\.[^.]+$/,""),tA=new XM(`${Z}/${gA}.3dshapes/${eA}`);return X.offset&&(tA.offset=X.offset),X.scale&&(tA.scale=X.scale),X.rotate&&(tA.rotate=X.rotate),this.ctx.pcbModel3dSourcePaths?.includes(X.path)||this.ctx.pcbModel3dSourcePaths?.push(X.path),tA}):a.models=O;else if(n.footprinter_string&&this.includeBuiltin3dModels){const{footprinter_string:X}=n,eA=`${Z}/tscircuit_builtin.3dshapes/${X}.step`;a.models=[new XM(eA)];const gA=`${mme}/${X}.step`;this.ctx.pcbModel3dSourcePaths?.includes(gA)||this.ctx.pcbModel3dSourcePaths?.push(gA)}}const Y=e.metadata?.kicad_footprint;Y&&i?.name&&REi(a,Y,i.name);const J=t.footprints;J.push(a),t.footprints=J,this.componentsProcessed++}getOutput(){return this.ctx.kicadPcb}},XEi={top:"F.Cu",bottom:"B.Cu",inner1:"In1.Cu",inner2:"In2.Cu",inner3:"In3.Cu",inner4:"In4.Cu",inner5:"In5.Cu",inner6:"In6.Cu"};function $Ei(t){return t&&(XEi[t]||t)||"F.Cu"}function Aui(t){const A=["F.Cu"];for(let e=1;e<t-1;e++)A.push(`In${e}.Cu`);return A.push("B.Cu"),A}var eui=class extends iu{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}let n=i.route[0]?.layer;for(let o=0;o<i.route.length-1;o++){const s=i.route[o],r=i.route[o+1],a=Ce(A,{x:s.x,y:s.y}),g=Ce(A,{x:r.x,y:r.y});let c;if(e){let h=i.subcircuit_connectivity_map_key;if(!h&&i.source_trace_id){const E=this.ctx.db.source_trace?.get(i.source_trace_id);if(E&&(h=E.subcircuit_connectivity_map_key,!h&&E.connected_source_net_ids?.length))for(const u of E.connected_source_net_ids){const d=this.ctx.db.source_net?.get(u);if(d?.subcircuit_connectivity_map_key){h=d.subcircuit_connectivity_map_key;break}}}if(!h&&typeof i.connection_name=="string"){const E=this.ctx.db.source_net?.get(i.connection_name);E?.subcircuit_connectivity_map_key&&(h=E.subcircuit_connectivity_map_key)}h&&(c=e.get(h))}const I=s.layer??r.layer??n,l=$Ei(I),B=`segment:${a.x},${a.y}:${g.x},${g.y}:${l}:${c?.id??0}`,C=new mbA({start:{x:a.x,y:a.y},end:{x:g.x,y:g.y},layer:l,width:i.width||.25,net:new OX(c?.id??0),uuid:jf(B)}),Q=t.segments;Q.push(C),t.segments=Q,s.layer&&(n=s.layer),r.layer&&(n=r.layer)}this.tracesProcessed++}getOutput(){return this.ctx.kicadPcb}},tui=class extends iu{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],n=Ce(A,{x:i.x,y:i.y});let o;if(e){let I=i.subcircuit_connectivity_map_key;if(!I&&i.pcb_trace_id){const l=this.ctx.db.pcb_trace?.get(i.pcb_trace_id);if(l&&("subcircuit_connectivity_map_key"in l&&(I=l.subcircuit_connectivity_map_key),!I&&l.source_trace_id)){const B=this.ctx.db.source_trace?.get(l.source_trace_id);if(B&&("subcircuit_connectivity_map_key"in B&&(I=B.subcircuit_connectivity_map_key),!I&&B.connected_source_net_ids?.length))for(const C of B.connected_source_net_ids){const Q=this.ctx.db.source_net?.get(C);if(Q?.subcircuit_connectivity_map_key){I=Q.subcircuit_connectivity_map_key;break}}}}if(!I&&i.connection_name){const l=this.ctx.db.source_net?.get(i.connection_name);l?.subcircuit_connectivity_map_key&&(I=l.subcircuit_connectivity_map_key)}I&&(o=e.get(I))}const s=this.ctx.numLayers??2,r=i.layers?i.layers.map(I=>I==="top"?"F.Cu":I==="bottom"?"B.Cu":`In${I.replace("inner","")}.Cu`):Aui(s),a=`via:${n.x},${n.y}:${i.outer_diameter||.8}:${i.hole_diameter||.4}:${o?.id??0}`,g=new dxA({at:[n.x,n.y],size:i.outer_diameter||.8,drill:i.hole_diameter||.4,layers:r,net:new uxA(o?.id??0),uuid:jf(a)}),c=t.vias;c.push(g),t.vias=c,this.viasProcessed++}getOutput(){return this.ctx.kicadPcb}};function iui({textElement:t,c2kMatPcb:A}){if(!t.text||!t.anchor_position)return null;const e=Ce(A,{x:t.anchor_position.x,y:t.anchor_position.y}),n={top:"F.Fab",bottom:"B.Fab"}[t.layer]||t.layer||"F.Fab",o=(t.font_size||1)/1.5,s=new Zf;s.size={width:o,height:o};const r=new wP,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 Wf({font:s});a!=="center"&&(g.justify=r);const c=new ac([e.x,e.y,0]),I=new qX({text:t.text,layer:n,effects:g});return I.position=c,I}function nui({textElement:t,c2kMatPcb:A}){if(!t.text||!t.anchor_position)return null;const e=Ce(A,{x:t.anchor_position.x,y:t.anchor_position.y}),n={top:"F.SilkS",bottom:"B.SilkS"}[t.layer]||t.layer||"F.SilkS",o=(t.font_size||1)/1.5,s=new Zf;s.size={width:o,height:o};const r=new wP,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 Wf({font:s});a!=="center"&&(g.justify=r);const c=t.ccw_rotation||0,I=new ac([e.x,e.y,c]),l=new qX({text:t.text,layer:n,effects:g});return l.position=I,l}var oui=class extends iu{_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 s of e)if(!(!s.route||s.route.length<2))for(let r=0;r<s.route.length-1;r++){const a=s.route[r],g=s.route[r+1];if(!a||!g)continue;const c=Ce(A,{x:a.x,y:a.y}),I=Ce(A,{x:g.x,y:g.y}),B={top:"F.SilkS",bottom:"B.SilkS"}[s.layer]||s.layer||"F.SilkS",C=new KX({start:{x:c.x,y:c.y},end:{x:I.x,y:I.y},layer:B,width:s.stroke_width||.15}),Q=t.graphicLines;Q.push(C),t.graphicLines=Q}const i=this.ctx.db.pcb_silkscreen_text?.list().filter(s=>!s.pcb_component_id)||[];for(const s of i){const r=nui({textElement:s,c2kMatPcb:A});if(r){const a=t.graphicTexts;a.push(r),t.graphicTexts=a}}const n=this.ctx.db.pcb_fabrication_note_text?.list()||[];for(const s of n){const r=iui({textElement:s,c2kMatPcb:A});if(r){const a=t.graphicTexts;a.push(r),t.graphicTexts=a}}const o=this.ctx.db.pcb_board?.list()||[];if(o.length>0){const s=o[0];if(!s){this.finished=!0;return}let r;if(s.outline&&s.outline.length>0)r=s.outline;else{const g=s.width?s.width/2:0,c=s.height?s.height/2:0;r=[{x:s.center.x-g,y:s.center.y-c},{x:s.center.x+g,y:s.center.y-c},{x:s.center.x+g,y:s.center.y+c},{x:s.center.x-g,y:s.center.y+c}]}const a=r.map(g=>Ce(A,g));for(let g=0;g<a.length;g++){const c=a[g],I=a[(g+1)%a.length];if(!c||!I)continue;const l=new KX({start:{x:c.x,y:c.y},end:{x:I.x,y:I.y},layer:"Edge.Cuts",width:.1}),B=t.graphicLines;B.push(l),t.graphicLines=B}}this.finished=!0}getOutput(){return this.ctx.kicadPcb}},wme=class{ctx;pipeline;currentStageIndex=0;finished=!1;get currentStage(){return this.pipeline[this.currentStageIndex]}constructor(t,A){this.ctx={db:Ua(t),circuitJson:t,kicadPcb:new pxA({generator:"circuit-json-to-kicad",generatorVersion:"0.0.1"}),c2kMatPcb:An(on(100,100),$a(1,-1)),projectName:A?.projectName,pcbModel3dSourcePaths:[]},this.pipeline=[new bEi(t,this.ctx),new xEi(t,this.ctx),new zEi(t,this.ctx,{includeBuiltin3dModels:A?.includeBuiltin3dModels}),new eui(t,this.ctx),new tui(t,this.ctx),new oui(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()}getModel3dSourcePaths(){return this.ctx.pcbModel3dSourcePaths??[]}},sui=class{ctx;project;constructor(t,A={}){const e=A.projectName??t?.project?.name??"circuit-json-project",i=A.schematicFilename??`${e}.kicad_sch`,n=A.pcbFilename??`${e}.kicad_pcb`,o=new Date().toISOString();this.ctx={db:Ua(t),circuitJson:t},this.project={version:1,head:{generator:"circuit-json-to-kicad",generator_version:"0.0.1",project_name:e,created:o,modified:o},meta:{version:1},text_variables:{},libraries:{pinned_symbol_libs:[],pinned_footprint_libs:[]},boards:[],cvpcb:{meta:{version:0}},erc:{meta:{version:0},erc_exclusions:[]},net_settings:{meta:{version:1},last_net_id:0,classes:[]},pcbnew:{page_layout_descr_file:"",last_paths:{}},schematic:{meta:{version:1},page_layout_descr_file:"",last_opened_files:[i]},board:{meta:{version:1},last_opened_board:n},sheets:[[Math.random().toString(36).substring(2,15),"Root"]]}}runUntilFinished(){}getOutput(){return this.project}getOutputString(){return`${JSON.stringify(this.project,null,2)}
|
|
5829
|
+
`)}};UA.register(dxA);var pxA=class tve extends UA{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 tve;for(const i of A){if(!Array.isArray(i)||i.length===0)throw new Error(`kicad_pcb encountered unsupported primitive child: ${JSON.stringify(i)}`);const n=UA.parsePrimitiveSexpr(i,{parentToken:this.token});if(!(n instanceof UA))throw new Error(`kicad_pcb expected SxClass child, received ${JSON.stringify(i)}`);e.consumeChild(n)}return e}consumeChild(A){if(A instanceof QxA){this._sxVersion=A;return}if(A instanceof hxA){this._sxGenerator=A;return}if(A instanceof ExA){this._sxGeneratorVersion=A;return}if(A instanceof BxA){this._sxGeneral=A;return}if(A instanceof FX){this._sxPaper=A;return}if(A instanceof Cfe){this._sxTitleBlock=A;return}if(A instanceof CxA){this._sxLayers=A;return}if(A instanceof lxA){this._sxSetup=A;return}if(A instanceof vS){this._properties.push(A);return}if(A instanceof VX){this._nets.push(A);return}if(A instanceof cbA){this._footprints.push(A);return}if(A instanceof hfe){this._images.push(A);return}if(A instanceof mbA){this._segments.push(A);return}if(A instanceof KX){this._grLines.push(A);return}if(A instanceof qX){this._grTexts.push(A);return}if(A instanceof oye){this._grPolys.push(A);return}if(A instanceof tye){this._grRects.push(A);return}if(A instanceof dxA){this._vias.push(A);return}if(A instanceof Iye){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 QxA(A)}get generator(){return this._sxGenerator?.value}set generator(A){this._sxGenerator=A===void 0?void 0:new hxA(A)}get generatorVersion(){return this._sxGeneratorVersion?.value}set generatorVersion(A){this._sxGeneratorVersion=A===void 0?void 0:new ExA(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}};UA.register(pxA);var hme=t=>UA.parse(t),iu=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")}},sEi=class extends iu{_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 FX;e.size=A?.name??"A4",t.paper=e,t.uuid=new qi(crypto.randomUUID()),this.finished=!0}getOutput(){return this.ctx.kicadSch}};function $M(t,A){if(t.manufacturer_part_number)return fxA(t.manufacturer_part_number);const e=rEi(t.ftype),i=A?.footprinter_string;return fxA(i?`${e}_${i}`:e)}function rEi(t){if(!t)return"component";let A=t.replace(/^simple_/,"");return A||"component"}function fxA(t){return t.replace(/[\\\/:\s]+/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"").trim()||"component"}function Eme(t){return t?t.match(/^([A-Za-z]+)/)?.[1]?.toUpperCase()??"U":"U"}var ume={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"},aEi=/^[A-Za-z]+\d+$/;function dme(t){return t?aEi.test(t.trim()):!1}function jX(t){const A=t?.ftype;if(A&&ume[A])return ume[A];const e=t?.name;return dme(e),Eme(e)}function gEi(t){const A=t?.name;return dme(A)?A.trim():`${jX(t)}?`}function pme(t){return t in JQ}function fme(t,A,e,i){if(i)return`Custom:${i}`;if(t.type!=="source_component")return A.symbol_name?pme(A.symbol_name)?`Device:${A.symbol_name}`:`Custom:${A.symbol_name}`:"Device:Component";if(A.symbol_name)return pme(A.symbol_name)?`Device:${A.symbol_name}`:`Custom:${A.symbol_name}`;const n=$M(t,e);return`Device:${jX(t)}_${n}`}function cEi(t){const{circuitJson:A,schematicSymbolId:e,schematicSymbol:i,schematicComponentId:n}=t,o=A.filter(Q=>Q.type==="schematic_circle"&&Q.schematic_symbol_id===e),s=A.filter(Q=>Q.type==="schematic_line"&&Q.schematic_symbol_id===e),r=n?A.filter(Q=>Q.type==="schematic_line"&&Q.schematic_component_id===n&&!Q.schematic_symbol_id):[],a=[...s,...r],g=A.filter(Q=>Q.type==="schematic_path"&&Q.schematic_symbol_id===e),c=A.filter(Q=>Q.type==="schematic_text"&&Q.schematic_symbol_id===e);let I=A.filter(Q=>Q.type==="schematic_port"&&"schematic_symbol_id"in Q&&Q.schematic_symbol_id===e);if(I.length===0&&n){const Q=A.filter(E=>E.type==="schematic_port"&&E.schematic_component_id===n&&E.display_pin_label!==void 0),h=new Map;for(const E of Q)E.display_pin_label&&h.set(E.display_pin_label,E);if(I=h.size>0?Array.from(h.values()):Q,I.length===0){const E=A.filter(d=>d.type==="schematic_port"&&d.schematic_component_id===n),u=new Set;I=E.filter(d=>{const f=d.pin_number;if(f!==void 0){if(u.has(f))return!1;u.add(f)}return!0})}}const l=[];for(const Q of o)l.push({type:"circle",x:Q.center?.x??0,y:Q.center?.y??0,radius:Q.radius??.5,fill:Q.is_filled??!1,fillColor:Q.fill_color});for(const Q of a)l.push({type:"path",points:[{x:Q.x1??0,y:Q.y1??0},{x:Q.x2??0,y:Q.y2??0}]});for(const Q of g)Q.points&&Q.points.length>0&&l.push({type:"path",points:Q.points,fill:Q.is_filled??!1,fillColor:Q.fill_color});const B=c.map(Q=>({text:Q.text??"",x:Q.position?.x??0,y:Q.position?.y??0,fontSize:Q.font_size??.2,anchor:Q.anchor??"center"})),C=I.map((Q,h)=>({x:Q.center?.x??0,y:Q.center?.y??0,labels:[Q.display_pin_label||`${Q.pin_number||h+1}`],pinNumber:Q.pin_number||h+1,facingDirection:Q.facing_direction}));return C.sort((Q,h)=>Q.pinNumber-h.pinNumber),{center:i.center||{x:0,y:0},size:i.size||{width:1,height:1},primitives:l,texts:B,ports:C}}function IEi({points:t,transform:A,fillType:e}){const i=new ufe,n=t.map(a=>{const g=Ce(A,a);return new sh(g.x,g.y)}),o=new sQ(n);i.points=o;const s=new kS;s.width=.254,s.type="default",i.stroke=s;const r=new Dfe;return r.type=e,i.fill=r,i}function lEi({primitive:t,transform:A,scale:e}){const i=new xfe,n=Ce(A,{x:t.x,y:t.y}),o=i;o._sxCenter=new mfe(n.x,n.y),o._sxRadius=new wfe(t.radius*e);const s=new kS;s.width=.254,s.type="default",o._sxStroke=s;const r=new Sfe;return r.type=t.fill?"background":"none",o._sxFill=r,i}function BEi({schText:t,transform:A,scale:e}){const i=new _fe,n=Ce(A,{x:t.x,y:t.y});i.value=t.text,i.at=[n.x,n.y,0];const o=t.fontSize*e,s=new Zf;return s.size={height:o,width:o},i.effects=new Wf({font:s}),i}function CEi({libId:t,symbolData:A,isChip:e,c2kMatSchScale:i}){const n=new z2({libraryId:`${t.split(":")[1]}_0_1`}),o=i,s=A.center?.x??0,r=A.center?.y??0,a=An($a(o,o),on(-s,-r));for(const c of A.primitives||[])if(c.type==="path"&&c.points){const I=e||c.fill?"background":"none",l=IEi({points:c.points,transform:a,fillType:I});n.polylines.push(l)}else if(c.type==="circle"){const I=lEi({primitive:c,transform:a,scale:o});n.circles.push(I)}const g=Array.isArray(A.texts)?A.texts:[];for(const c of g){const I=BEi({schText:c,transform:a,scale:o});n.texts.push(I)}return n}function QEi(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,n=t.size?.height||1,o={type:"path",points:[{x:-i/2,y:-n/2},{x:i/2,y:-n/2},{x:i/2,y:n/2},{x:-i/2,y:n/2},{x:-i/2,y:-n/2}]},s=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:[o],ports:s,size:{width:i,height:n}}}function hEi(t,A){const e=new Zf;return e.size={height:t,width:t},new Wf({font:e,hiddenText:A})}function EEi({symbol:t,libId:A,description:e,keywords:i,fpFilters:n,footprintRef:o="",referencePrefix:s}){const r=s||A.split(":")[1]?.[0]||"U",a=[{key:"Reference",value:r,id:0,at:[2.032,0,90],hide:!1},{key:"Value",value:r,id:1,at:[0,0,90],hide:!1},{key:"Footprint",value:o,id:2,at:[-1.778,0,90],hide:!0},{key:"Datasheet",value:"~",id:3,at:[0,0,0],hide:!0},{key:"Description",value: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:n,id:6,at:[0,0,0],hide:!0}];for(const g of a)t.properties.push(new Vf({key:g.key,value:g.value,id:g.id,at:g.at,effects:hEi(1.27,g.hide)}))}function uEi({port:t,center:A,size:e,isChip:i,portIndex:n,schematicComponent:o,schematicPorts:s,c2kMatSchScale:r}){const a=r;let g=t.x??0,c=t.y??0,I=!1;if(i&&n!==void 0&&o){const y=s.filter(w=>w.schematic_component_id===o.schematic_component_id).sort((w,D)=>(w.pin_number||0)-(D.pin_number||0));if(y[n]){const w=y[n];g=w.center.x-o.center.x,c=w.center.y-o.center.y,I=!0}}let l,B;if(I)l=g,B=c;else{const y=A?.x??0,w=A?.y??0;l=g-y,B=c-w}const C=$a(a,a),Q=Ce(C,{x:l,y:B});let h;if(i&&e){const y=e.width/2,w=e.height/2,D=Math.abs(l)/y,S=Math.abs(B)/w;h=D>S}else h=Math.abs(l)>Math.abs(B);let E=Q.x,u=Q.y;const d=6;if(i&&e){const y=e.width/2*a,w=e.height/2*a;h?(E=l>0?y:-y,u=B*a):(E=l*a,u=B>0?w:-w)}let f=0;return h?l>0?(f=180,i&&(E=E+d)):(f=0,i&&(E=E-d)):B>0?(f=270,i&&(u=u+d)):(f=90,i&&(u=u-d)),{x:E,y:u,angle:f}}function dEi({libId:t,symbolData:A,isChip:e,schematicComponent:i,schematicPorts:n,c2kMatSchScale:o}){const s=new z2({libraryId:`${t.split(":")[1]}_1_1`}),r=6,a=2.54;for(let g=0;g<(A.ports?.length||0);g++){const c=A.ports[g],I=new GX;I.pinElectricalType="passive",I.pinGraphicStyle="line";const{x:l,y:B,angle:C}=uEi({port:c,center:A.center,size:A.size,isChip:e,portIndex:g,schematicComponent:i,schematicPorts:n,c2kMatSchScale:o});I.at=[l,B,C],I.length=e?r:a;const Q=new Zf;Q.size={height:1.27,width:1.27};const h=new Wf({font:Q}),E=c.labels?.[0]||"~";I._sxName=new ASA({value:E,effects:h});const u=new Zf;u.size={height:1.27,width:1.27};const d=new Wf({font:u}),f=c.pinNumber?.toString()||`${g+1}`;I._sxNumber=new vfe({value:f,effects:d}),s.pins.push(I)}return s}var pEi=class extends iu{processedSymbolNames=new Set;_step(){const{kicadSch:t,db:A}=this.ctx,e=new Ufe,i=[];this.processedSymbolNames=new Set;const n=A.schematic_component.list();for(const s of n){const r=this.createLibrarySymbolForComponent(s);r&&i.push(r)}const o=A.schematic_net_label?.list?.()||[];for(const s of o)if(s.symbol_name){const r=s.source_net_id?A.source_net.get(s.source_net_id)?.is_power:!1,a=s.source_net_id?A.source_net.get(s.source_net_id)?.is_ground:!1;if(r||a){const c=this.createLibrarySymbolForNetLabel({netLabel:s,isPower:r??!1,isGround:a??!1});c&&i.push(c)}}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(c=>c.source_component_id===e.source_component_id);let n=t.schematic_symbol_id;if(!n){const c=this.ctx.circuitJson.find(I=>(I.type==="schematic_line"||I.type==="schematic_circle"||I.type==="schematic_path")&&I.schematic_component_id===t.schematic_component_id&&I.schematic_symbol_id);c&&(n=c.schematic_symbol_id)}if(n)return this.createLibrarySymbolFromSchematicSymbol(t,e,i,n);const o=t.symbol_name||(e.ftype==="simple_chip"?`generic_chip_${t.source_component_id}`:null);if(!o)return null;const s=this.getSymbolData(o,t);if(!s)return null;const r=fme(e,t,i),a=e.ftype==="simple_chip",g=$M(e,i);return this.createLibrarySymbol({libId:r,symbolData:s,isChip:a,schematicComponent:t,description:this.getDescription(e),keywords:this.getKeywords(e),fpFilters:this.getFpFilters(e),footprintRef:g?`tscircuit:${g}`:"",referencePrefix:jX(e)})}createLibrarySymbolFromSchematicSymbol(t,A,e,i){const{db:n}=this.ctx,o=this.ctx.circuitJson.find(c=>c.type==="schematic_symbol"&&c.schematic_symbol_id===i);if(!o)return null;let s;if(o.name)s=o.name;else{const c=$M(A,e);c?s=c:s=`custom_${A.ftype||"component"}_${i}`}const r=`Custom:${s}`;if(this.processedSymbolNames.has(r))return null;this.processedSymbolNames.add(r);const a=cEi({circuitJson:this.ctx.circuitJson,schematicSymbolId:i,schematicSymbol:o,schematicComponentId:t.schematic_component_id}),g=$M(A,e);return this.createLibrarySymbol({libId:r,symbolData:a,isChip:!1,schematicComponent:t,description:this.getDescription(A),keywords:this.getKeywords(A),fpFilters:this.getFpFilters(A,o.name),footprintRef:g?`tscircuit:${g}`:"",referencePrefix:jX(A),symbolScale:1})}createLibrarySymbolForNetLabel({netLabel:t,isPower:A,isGround:e}){const i=t.symbol_name;if(!i)return null;const n=JQ[i];if(!n)return null;const o=`Custom:${i}`;return this.createLibrarySymbol({libId:o,symbolData:n,isChip:!1,schematicComponent:void 0,description:A?"Power net label":e?"Ground net label":"Net symbol",keywords:A?"power net":e?"ground net":"net",fpFilters:"",referencePrefix:o.split(":")[1]?.[0]||"U"})}getSymbolData(t,A){return t.startsWith("generic_chip_")?QEi(A,this.ctx.db):JQ[t]||null}createLibrarySymbol({libId:t,symbolData:A,isChip:e,schematicComponent:i,description:n,keywords:o,fpFilters:s,footprintRef:r="",referencePrefix:a,symbolScale:g}){const I=g??this.ctx.c2kMatSch?.a??15,l=new z2({libraryId:t,excludeFromSim:!1,inBom:!0,onBoard:!0}),B=new zDA;B.hide=!e,l._sxPinNumbers=B;const C=new $DA;C.offset=e?1.27:0,l._sxPinNames=C,EEi({symbol:l,libId:t,description:n,keywords:o,fpFilters:s,footprintRef:r,referencePrefix:a});const Q=CEi({libId:t,symbolData:A,isChip:e,c2kMatSchScale:I});l.subSymbols.push(Q);const h=dEi({libId:t,symbolData:A,isChip:e,schematicComponent:i,schematicPorts:this.ctx.db.schematic_port.list(),c2kMatSchScale:I});return l.subSymbols.push(h),l._sxEmbeddedFonts=new V2(!1),l}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,A){return A?`${A}*`:t?.ftype==="simple_resistor"?"R_*":t?.ftype==="simple_capacitor"?"C_*":(t?.ftype==="simple_chip","*")}getOutput(){if(!this.ctx.kicadSch)throw new Error("kicadSch is not initialized");return this.ctx.kicadSch}},fEi=class extends iu{_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 n of e){const o=n.source_component_id?A.source_component.get(n.source_component_id):null;if(!o||!this.ctx.c2kMatSch)continue;const{x:s,y:r}=Ce(this.ctx.c2kMatSch,{x:n.center.x,y:n.center.y}),a=crypto.randomUUID(),g=new z2({at:[s,r,0],unit:1,excludeFromSim:!1,inBom:!0,onBoard:!0,dnp:!1,uuid:a,fieldsAutoplaced:!0}),c=A.cad_component?.list()?.find(iA=>iA.source_component_id===o.source_component_id);let I,l=n.schematic_symbol_id;if(!l){const iA=this.ctx.circuitJson.find(sA=>(sA.type==="schematic_line"||sA.type==="schematic_circle"||sA.type==="schematic_path")&&sA.schematic_component_id===n.schematic_component_id&&sA.schematic_symbol_id);iA&&(l=iA.schematic_symbol_id)}if(l){const iA=this.ctx.circuitJson.find(sA=>sA.type==="schematic_symbol"&&sA.schematic_symbol_id===l);if(iA?.name)I=iA.name;else{const sA=$M(o,c);sA?I=sA:I=`custom_${o.ftype||"component"}_${l}`}}const B=fme(o,n,c,I),C=new VDA(B);g._sxLibId=C;const{reference:Q,value:h,description:E}=this.getComponentMetadata(o),{refTextPos:u,valTextPos:d}=this.getTextPositions(n,{x:s,y:r});let f;if(l){const iA=this.ctx.circuitJson.find(sA=>sA.type==="schematic_symbol"&&sA.schematic_symbol_id===l);iA&&iA.type==="schematic_symbol"&&(f=iA.metadata?.kicad_symbol)}const y=f?.properties?.Reference,w=new Vf({key:"Reference",value:y?.value??Q,id:0,at:[u.x,u.y,0],effects:this.createTextEffects(Number(y?.effects?.font?.size?.x??1.27),y?.effects?.hide??!1)}),D=o.ftype==="simple_chip",S=f?.properties?.Value,_=new Vf({key:"Value",value:S?.value??h,id:1,at:[d.x,d.y,0],effects:this.createTextEffects(Number(S?.effects?.font?.size?.x??1.27),S?.effects?.hide??D)}),b=f?.properties?.Footprint,N=new Vf({key:"Footprint",value:b?.value??"",id:2,at:[s-1.778,r,90],effects:this.createTextEffects(1.27,b?.effects?.hide??!0)}),F=f?.properties?.Datasheet,L=new Vf({key:"Datasheet",value:F?.value??"~",id:3,at:[s,r,0],effects:this.createTextEffects(1.27,F?.effects?.hide??!0)}),Y=f?.properties?.Description,J=new Vf({key:"Description",value:Y?.value??E,id:4,at:[s,r,0],effects:this.createTextEffects(1.27,Y?.effects?.hide??!0)});g.properties.push(w,_,N,L,J);const O=f?.properties?.ki_keywords;if(O?.value){const iA=new Vf({key:"ki_keywords",value:O.value,id:5,at:[s,r,0],effects:this.createTextEffects(1.27,O.effects?.hide??!0)});g.properties.push(iA)}const Z=f?.properties?.ki_fp_filters;if(Z?.value){const iA=new Vf({key:"ki_fp_filters",value:Z.value,id:6,at:[s,r,0],effects:this.createTextEffects(1.27,Z.effects?.hide??!0)});g.properties.push(iA)}if(f){if(f.inBom!==void 0&&(g.inBom=f.inBom),f.onBoard!==void 0&&(g.onBoard=f.onBoard),f.excludeFromSim!==void 0&&(g.excludeFromSim=f.excludeFromSim),f.pinNames){const iA=new $DA;f.pinNames.offset!==void 0&&(iA.offset=Number(f.pinNames.offset)),f.pinNames.hide!==void 0&&(iA.hide=f.pinNames.hide),g.pinNames=iA}if(f.pinNumbers){const iA=new zDA;f.pinNumbers.hide!==void 0&&(iA.hide=f.pinNumbers.hide),g.pinNumbers=iA}f.embeddedFonts!==void 0&&(g._sxEmbeddedFonts=new V2(f.embeddedFonts))}let X=A.schematic_port.list().filter(iA=>iA.schematic_component_id===n.schematic_component_id);if(l){const iA=X.filter(sA=>sA.display_pin_label);iA.length>0&&(X=iA)}X.sort((iA,sA)=>(iA.pin_number||0)-(sA.pin_number||0));for(let iA=0;iA<X.length;iA++){const sA=X[iA];if(!sA)continue;const aA=new GX;aA.numberString=`${sA.pin_number||iA+1}`,aA.uuid=crypto.randomUUID(),g.pins.push(aA)}const eA=new eSA,gA=new iSA(""),tA=new nSA(`/${t?.uuid?.value||""}`);tA.reference=Q,tA.unit=1,gA.paths.push(tA),eA.projects.push(gA),g._sxInstances=eA,i.push(g)}t&&(t.symbols=i),this.finished=!0}getTextPositions(t,A){const i=(this.ctx.db.schematic_text?.list?.()?.filter(B=>B.schematic_component_id===t.schematic_component_id)||[]).find(B=>B.text&&B.text.length>0);if(i&&this.ctx.c2kMatSch){const B=Ce(this.ctx.c2kMatSch,{x:i.position.x,y:i.position.y}),C={x:A.x,y:A.y+6};return{refTextPos:B,valTextPos:C}}const n=t.symbol_name,o=JQ[n];if(!o)return{refTextPos:{x:A.x,y:A.y-6},valTextPos:{x:A.x,y:A.y+6}};let s=null,r=null;for(const B of o.primitives)B.type==="text"&&(B.text==="{REF}"?s=B:B.text==="{VAL}"&&(r=B));const a=o.center||{x:0,y:0},c=n.includes("_down")||n.includes("_up")?.15:0,I=s&&this.ctx.c2kMatSch?Ce(this.ctx.c2kMatSch,{x:t.center.x+(s.x-a.x)+c,y:t.center.y+(s.y-a.y)}):{x:A.x,y:A.y-6},l=r&&this.ctx.c2kMatSch?Ce(this.ctx.c2kMatSch,{x:t.center.x+(r.x-a.x)+c,y:t.center.y+(r.y-a.y)}):{x:A.x,y:A.y+6};return{refTextPos:I,valTextPos:l}}getComponentMetadata(t){const A=t.name||"?",e=gEi(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"}:t.ftype==="simple_potentiometer"?{reference:e,value:t.display_max_resistance||"",description:"Potentiometer"}:{reference:e,value:A,description:"Component"}}createTextEffects(t,A=!1,e){const i=new Zf;i.size={height:t,width:t};const n=e?new wP({horizontal:e}):void 0;return new Wf({font:i,hiddenText:A,justify:n})}getOutput(){if(!this.ctx.kicadSch)throw new Error("kicadSch is not initialized");return this.ctx.kicadSch}},yEi=class extends iu{_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=[],n=[];for(const o of e){const s=o.text||"",r=o.symbol_name;if(r){const a=this.createSymbolFromNetLabel(o,s,r);a&&i.push(a)}else{const a=this.createGlobalLabel(o,s);a&&n.push(a)}}if(t&&i.length>0){const o=t.symbols||[];t.symbols=[...o,...i]}t&&n.length>0&&(t.globalLabels=[...t.globalLabels||[],...n]),this.finished=!0}createSymbolFromNetLabel(t,A,e){if(!this.ctx.c2kMatSch)return null;const{x:i,y:n}=Ce(this.ctx.c2kMatSch,{x:t.anchor_position?.x??t.center?.x??0,y:t.anchor_position?.y??t.center?.y??0}),o=crypto.randomUUID(),s=new z2({at:[i,n,0],unit:1,excludeFromSim:!1,inBom:!0,onBoard:!0,dnp:!1,uuid:o,fieldsAutoplaced:!0}),r=`Custom:${e}`,a=new VDA(r);s._sxLibId=a;const g=e.includes("_up")||e.toLowerCase().includes("vcc"),c=g?-4:4,I=g?-6:6,l=new Vf({key:"Reference",value:A,id:0,at:[i,n+c,0],effects:this.createTextEffects(1.27,!1)}),B=new Vf({key:"Value",value:A,id:1,at:[i,n+I,0],effects:this.createTextEffects(1.27,!0)}),C=new Vf({key:"Footprint",value:"",id:2,at:[i-1.778,n,90],effects:this.createTextEffects(1.27,!0)}),Q=new Vf({key:"Datasheet",value:"~",id:3,at:[i,n,0],effects:this.createTextEffects(1.27,!0)}),h=new Vf({key:"Description",value:`Power/Net symbol: ${A}`,id:4,at:[i,n,0],effects:this.createTextEffects(1.27,!0)});s.properties.push(l,B,C,Q,h);const E=new GX;E.numberString="1",E.uuid=crypto.randomUUID(),s.pins.push(E);const{kicadSch:u}=this.ctx,d=new eSA,f=new iSA(""),y=new nSA(`/${u?.uuid?.value||""}`);return y.reference=A,y.unit=1,f.paths.push(y),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}=Ce(this.ctx.c2kMatSch,{x:t.anchor_position?.x??t.center?.x??0,y:t.anchor_position?.y??t.center?.y??0}),n=t.anchor_side||"left",s={left:0,right:180,top:270,bottom:90}[n]||0,a={left:{horizontal:"left"},right:{horizontal:"right"},top:{vertical:"top"},bottom:{vertical:"bottom"}}[n]||{},g=this.createTextEffects(1.27,!1);return Object.keys(a).length>0&&(g.justify=new wP(a)),new Wfe({value:A,at:[e,i,s],effects:g,uuid:crypto.randomUUID(),fieldsAutoplaced:!0})}createTextEffects(t,A=!1){const e=new Zf;return e.size={height:t,width:t},new Wf({font:e,hiddenText:A})}getOutput(){if(!this.ctx.kicadSch)throw new Error("kicadSch is not initialized");return this.ctx.kicadSch}},mEi=class extends iu{_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=[],n=[];for(const o of e){for(const s of o.edges){const r=this.createWireFromEdge(s);i.push(r)}for(const s of o.junctions){const r=this.createJunction(s);n.push(r)}}t.wires=i,t.junctions=n,this.finished=!0}createWireFromEdge(t){const A=new Yfe;if(!this.ctx.c2kMatSch)throw new Error("Schematic transformation matrix not initialized in context");const e=Ce(this.ctx.c2kMatSch,{x:t.from.x,y:t.from.y}),i=Ce(this.ctx.c2kMatSch,{x:t.to.x,y:t.to.y}),n=e.x,o=e.y,s=i.x,r=i.y,a=new sQ([new sh(n,o),new sh(s,r)]);A.points=a;const g=new kS;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}=Ce(this.ctx.c2kMatSch,{x:t.x,y:t.y}),i=new Jfe({at:[A,e],diameter:0});return i.uuid=crypto.randomUUID(),i}getOutput(){return this.ctx.kicadSch}},wEi=class extends iu{_step(){const{kicadSch:t}=this.ctx;if(!t)throw new Error("KicadSch instance not initialized in context");const A=new aSA,e=new jfe;e.value="/";const i=new zfe("1");e.pages=[i],A.paths=[e],t.sheetInstances=A,t.embeddedFonts=new V2(!1),this.finished=!0}getOutput(){return this.ctx.kicadSch}};function DEi(t){const A=t.schematic_component.list(),e=t.schematic_trace.list();let i=1/0,n=1/0,o=-1/0,s=-1/0;for(const g of A){const c=g.size?.width??0,I=g.size?.height??0;i=Math.min(i,g.center.x-c/2),n=Math.min(n,g.center.y-I/2),o=Math.max(o,g.center.x+c/2),s=Math.max(s,g.center.y+I/2)}for(const g of e)for(const c of g.edges)i=Math.min(i,c.from.x,c.to.x),n=Math.min(n,c.from.y,c.to.y),o=Math.max(o,c.from.x,c.to.x),s=Math.max(s,c.from.y,c.to.y);i===1/0&&(i=0,n=0,o=0,s=0);const r=(i+o)/2,a=(n+s)/2;return{center:{x:r,y:a},bounds:{minX:i,minY:n,maxX:o,maxY:s}}}var zX=[{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 SEi(t,A,e=20){const i=t+2*e,n=A+2*e;for(let o=0;o<zX.length;o++){const s=zX[o];if(i<=s.width&&n<=s.height)return s}return zX[zX.length-1]}var yme=class{ctx;pipeline;currentStageIndex=0;finished=!1;get currentStage(){return this.pipeline[this.currentStageIndex]}constructor(t){const e=Ua(t),{center:i,bounds:n}=DEi(e),o=(n.maxX-n.minX)*15,s=(n.maxY-n.minY)*15,r=SEi(o,s),a=r.width/2,g=r.height/2;this.ctx={db:e,circuitJson:t,kicadSch:new cSA({generator:"circuit-json-to-kicad",generatorVersion:"0.0.1"}),schematicPaperSize:r,c2kMatSch:An(on(a,g),$a(15,-15),on(-i.x,-i.y))},this.pipeline=[new sEi(t,this.ctx),new pEi(t,this.ctx),new fEi(t,this.ctx),new yEi(t,this.ctx),new mEi(t,this.ctx),new wEi(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()}},bEi=class extends iu{_step(){const{kicadPcb:t,db:A}=this.ctx;if(!t)throw new Error("KicadPcb instance not initialized in context");const i=A.pcb_board?.list()?.[0]?.num_layers??2;this.ctx.numLayers=i,t.version=20241229;const n=new FX;n.size="A4",t.paper=n;const o=new BxA;o.thickness=1.6,t.general=o;const s=new lxA;s.padToMaskClearance=0,t.setup=s;const r=new CxA,a=[new jl({index:0,name:"F.Cu",type:"signal"})];for(let g=1;g<i-1;g++)a.push(new jl({index:g,name:`In${g}.Cu`,type:"signal"}));a.push(new jl({index:31,name:"B.Cu",type:"signal"})),a.push(new jl({index:32,name:"B.Adhes",type:"user"}),new jl({index:33,name:"F.Adhes",type:"user"}),new jl({index:34,name:"B.Paste",type:"user"}),new jl({index:35,name:"F.Paste",type:"user"}),new jl({index:36,name:"B.SilkS",type:"user"}),new jl({index:37,name:"F.SilkS",type:"user"}),new jl({index:38,name:"B.Mask",type:"user"}),new jl({index:39,name:"F.Mask",type:"user"}),new jl({index:40,name:"Dwgs.User",type:"user"}),new jl({index:41,name:"Cmts.User",type:"user"}),new jl({index:42,name:"Eco1.User",type:"user"}),new jl({index:43,name:"Eco2.User",type:"user"}),new jl({index:44,name:"Edge.Cuts",type:"user"}),new jl({index:45,name:"Margin",type:"user"}),new jl({index:46,name:"B.CrtYd",type:"user"}),new jl({index:47,name:"F.CrtYd",type:"user"}),new jl({index:48,name:"B.Fab",type:"user"}),new jl({index:49,name:"F.Fab",type:"user"})),r.definitions=a,t.layers=r,this.finished=!0}getOutput(){return this.ctx.kicadPcb}},xEi=class extends iu{_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||"",c=g&&g.trim().length>0?g:a;A.set(a,c)}const i=this.ctx.db.source_trace?.list()??[];for(const r of i){let a=r.subcircuit_connectivity_map_key;if(!a&&r.connected_source_net_ids?.length)for(const g of r.connected_source_net_ids){const c=this.ctx.db.source_net?.get(g);if(c?.subcircuit_connectivity_map_key&&c.subcircuit_connectivity_map_key.length>0){a=c.subcircuit_connectivity_map_key;break}}if(a&&!A.has(a)){const g=r.display_name||r.source_trace_id||"",c=g&&g.trim().length>0?g:a;A.set(a,c)}}const n=Array.from(A.entries()).sort((r,a)=>r[0].localeCompare(a[0])),o=[];o.push(new VX(0,""));let s=1;for(const[r,a]of n){const g=new VX(s,a);o.push(g);const c={id:s,name:a};this.ctx.pcbNetMap.set(r,c),s++}t.nets=o,this.finished=!0}getOutput(){return this.ctx.kicadPcb}};function _Ei(t){let A=0;for(let i=0;i<t.length;i++){const n=t.charCodeAt(i);A=(A<<5)-A+n,A=A&A}let e="";for(let i=0;i<4;i++){let n=A;for(let o=0;o<t.length;o++)n=(n<<5)-n+t.charCodeAt(o)+i*31,n=n&n;e+=Math.abs(n).toString(16).padStart(8,"0")}return e}function jf(t){const A=_Ei(t);return`${A.slice(0,8)}-${A.slice(8,12)}-${A.slice(12,16)}-${A.slice(16,20)}-${A.slice(20,32)}`}var mme="https://modelcdn.tscircuit.com/jscad_models",kEi=20240108,vEi="pcbnew",FEi="8.0";function yxA(t){const A=t.split(/[/\\]/),e=A[A.length-1]||t;return e.split("?")[0]||e}var MEi=class extends iu{classifyFootprints(){const t=new Set,A=new Map,e=this.ctx.db.cad_component?.list()??[],i=this.ctx.db.source_component;for(const n of e){const o=n.source_component_id?i?.get(n.source_component_id):null;if(!o)continue;const s=$M(o,n);if(n.footprinter_string)A.set(s,n.footprinter_string);else{t.add(s);const r=this.ctx.circuitJson.find(a=>a.type==="pcb_component"&&a.source_component_id===n.source_component_id);r&&r.type==="pcb_component"&&r.metadata?.kicad_footprint?.footprintName&&t.add(r.metadata.kicad_footprint.footprintName)}}return{customFootprintNames:t,footprinterStrings:A}}_step(){const t=this.ctx.kicadPcbString,A=this.ctx.fpLibraryName??"tscircuit";if(!t)throw new Error("PCB content not available. Run GenerateKicadSchAndPcbStage first.");const{customFootprintNames:e,footprinterStrings:i}=this.classifyFootprints(),n=new Map;try{const s=hme(t).find(a=>a instanceof pxA);if(!s){this.ctx.footprintEntries=[],this.finished=!0;return}const r=s.footprints??[];for(const a of r){const g=this.sanitizeFootprint({footprint:a,fpLibraryName:A,customFootprintNames:e,footprinterStrings:i});n.has(g.footprintName)||n.set(g.footprintName,g)}}catch(o){console.warn("Failed to parse PCB for footprint extraction:",o)}this.ctx.footprintEntries=Array.from(n.values()),this.finished=!0}sanitizeFootprint({footprint:t,fpLibraryName:A,customFootprintNames:e,footprinterStrings:i}){const o=(t.libraryLink??"footprint").split(":"),s=(o.length>1?o[1]:o[0])?.replace(/[\\\/]/g,"-").trim()||"footprint",r=!e.has(s);if(t.libraryLink=s,t.position=ac.from([0,0,0]),t.locked=!1,t.placed=!1,t.version=kEi,t.generator=vEi,t.generatorVersion=FEi,t.descr||(t.descr=""),t.tags||(t.tags=""),t.embeddedFonts||(t.embeddedFonts=new V2(!1)),!t.attr){const f=new ISA,y=(t.fpPads??[]).map(w=>w.padType);y.some(w=>w.includes("thru_hole"))?f.type="through_hole":y.some(w=>w.includes("smd"))&&(f.type="smd"),t.attr=f}t.uuid=void 0,t.path=void 0,t.sheetfile=void 0,t.sheetname=void 0;const a=new Zf;a.size={width:1.27,height:1.27},a.thickness=.15;const g=new Wf({font:a}),c=t.fpPads??[];let I=0,l=0;for(const f of c){const y=f.at,w=f.size;if(y&&w){const D=y.y??0,S=w.height??0,_=D-S/2,b=D+S/2;I=Math.min(I,_),l=Math.max(l,b)}}const B=I-.5,C=l+.5;t.properties=[new vS({key:"Reference",value:"REF**",position:[0,B,0],layer:"F.SilkS",uuid:jf(`${s}-property-Reference`),effects:g}),new vS({key:"Value",value:"Val**",position:[0,C,0],layer:"F.Fab",uuid:jf(`${s}-property-Value`),effects:g}),new vS({key:"Datasheet",value:"",position:[0,0,0],layer:"F.Fab",hidden:!0,uuid:jf(`${s}-property-Datasheet`),effects:g}),new vS({key:"Description",value:"",position:[0,0,0],layer:"F.Fab",hidden:!0,uuid:jf(`${s}-property-Description`),effects:g})];const Q=t.fpTexts??[];for(const f of Q)f.uuid=void 0,f.type==="reference"?f.text="REF**":f.type==="value"&&f.text.trim().length===0&&(f.text=s);t.fpTexts=Q;const h=t.fpPads??[];for(let f=0;f<h.length;f++){const y=h[f];y&&(y.uuid=jf(`${s}-pad-${y.number??f}`),y.net=void 0)}t.fpPads=h;const E=t.models??[],u=[],d=[];for(const f of E)if(f.path){const y=yxA(f.path),S=`../../3dmodels/${f.path.startsWith("http://modelcdn.tscircuit.com")||f.path.startsWith("https://modelcdn.tscircuit.com")?"tscircuit_builtin":A}.3dshapes/${y}`,_=new XM(S);f.offset&&(_.offset=f.offset),f.scale&&(_.scale=f.scale),f.rotate&&(_.rotate=f.rotate),u.push(_),d.push(f.path.split("?")[0]??f.path)}if(u.length===0){const f=i.get(s);if(f){const y=`${mme}/${f}.step`,D=`../../3dmodels/tscircuit_builtin.3dshapes/${yxA(y)}`;u.push(new XM(D)),d.push(y)}}return t.models=u,{footprintName:s,kicadModString:t.getString(),model3dSourcePaths:d,isBuiltin:r}}getOutput(){return this.ctx.libraryOutput}};function XX(t){const A=new Zf;return t?.font?.size?A.size={width:Number(t.font.size.x),height:Number(t.font.size.y)}:A.size={width:1.27,height:1.27},t?.font?.thickness!==void 0?A.thickness=Number(t.font.thickness):A.thickness=.15,new Wf({font:A})}function REi(t,A,e){if(A.properties){const i=[],n=A.properties.Reference;i.push(new vS({key:"Reference",value:n?.value??e,position:n?.at?[Number(n.at.x),Number(n.at.y),Number(n.at.rotation??0)]:[0,-3,0],layer:n?.layer??"F.SilkS",uuid:jf(`${e}-property-Reference`),effects:XX(n?.effects),hidden:n?.hide}));const o=A.properties.Value,s=o?.value??A.footprintName??"";i.push(new vS({key:"Value",value:s,position:o?.at?[Number(o.at.x),Number(o.at.y),Number(o.at.rotation??0)]:[0,3,0],layer:o?.layer??"F.Fab",uuid:jf(`${e}-property-Value`),effects:XX(o?.effects),hidden:o?.hide}));const r=A.properties.Datasheet;i.push(new vS({key:"Datasheet",value:r?.value??"",position:r?.at?[Number(r.at.x),Number(r.at.y),Number(r.at.rotation??0)]:[0,0,0],layer:r?.layer??"F.Fab",uuid:jf(`${e}-property-Datasheet`),effects:XX(r?.effects),hidden:r?.hide??!0}));const a=A.properties.Description;i.push(new vS({key:"Description",value:a?.value??"",position:a?.at?[Number(a.at.x),Number(a.at.y),Number(a.at.rotation??0)]:[0,0,0],layer:a?.layer??"F.Fab",uuid:jf(`${e}-property-Description`),effects:XX(a?.effects),hidden:a?.hide??!0})),t.properties=i}if(A.attributes&&(t.attr||(t.attr=new ISA),A.attributes.through_hole?t.attr.type="through_hole":A.attributes.smd&&(t.attr.type="smd"),A.attributes.exclude_from_pos_files!==void 0&&(t.attr.excludeFromPosFiles=A.attributes.exclude_from_pos_files),A.attributes.exclude_from_bom!==void 0&&(t.attr.excludeFromBom=A.attributes.exclude_from_bom)),A.footprintName&&(t.libraryLink=A.footprintName),A.layer&&(t.layer=A.layer),A.embeddedFonts!==void 0&&(t.embeddedFonts=new V2(A.embeddedFonts)),A.model){const i=new XM(A.model.path);A.model.offset&&(i.offset={x:Number(A.model.offset.x),y:Number(A.model.offset.y),z:Number(A.model.offset.z)}),A.model.scale&&(i.scale={x:Number(A.model.scale.x),y:Number(A.model.scale.y),z:Number(A.model.scale.z)}),A.model.rotate&&(i.rotate={x:Number(A.model.rotate.x),y:Number(A.model.rotate.y),z:Number(A.model.rotate.z)});const n=t.models||[];t.models=[i,...n]}}function NEi(t,A){const e=[];for(const i of t){const n=i.center.x-A.x,o=-(i.center.y-A.y),r={top:"F.SilkS",bottom:"B.SilkS"}[i.layer]||i.layer||"F.SilkS",a=new ZSA({center:{x:n,y:o},end:{x:n+i.radius,y:o},layer:r,stroke:new kS,fill:!1});a.stroke&&(a.stroke.width=i.stroke_width||.05,a.stroke.type="default"),e.push(a)}return e}function GEi(t,A){const e=[];for(const i of t){const n=i.center.x-A.x,o=-(i.center.y-A.y),r={top:"F.CrtYd",bottom:"B.CrtYd"}[i.layer]||"F.CrtYd",a=new ZSA({center:{x:n,y:o},end:{x:n+i.radius,y:o},layer:r,stroke:new kS,fill:!1});a.stroke&&(a.stroke.width=.05,a.stroke.type="default"),e.push(a)}return e}function LEi(t,A){const e=[];for(const i of t){const n=i.center.x-A.x,o=-(i.center.y-A.y),s=i.width/2,r=i.height/2,g={top:"F.Fab",bottom:"B.Fab"}[i.layer]||i.layer||"F.Fab",c=new YX({start:{x:n-s,y:o-r},end:{x:n+s,y:o+r},layer:g,stroke:new kS,fill:!1});c.stroke&&(c.stroke.width=i.stroke_width||.1,c.stroke.type="default"),e.push(c)}return e}function UEi(t,A){const e=[];for(const i of t){const n=i.center.x-A.x,o=-(i.center.y-A.y),s=i.width/2,r=i.height/2,a="F.Fab",g=new YX({start:{x:n-s,y:o-r},end:{x:n+s,y:o+r},layer:a,stroke:new kS,fill:!1});g.stroke&&(g.stroke.width=i.stroke_width||.1,g.stroke.type="default"),e.push(g)}return e}function HEi(t,A){const e=[];for(const i of t){const n=i.center.x-A.x,o=-(i.center.y-A.y),s=i.width/2,r=i.height/2,g={top:"F.CrtYd",bottom:"B.CrtYd"}[i.layer]||"F.CrtYd",c=new YX({start:{x:n-s,y:o-r},end:{x:n+s,y:o+r},layer:g,stroke:new kS,fill:!1});c.stroke&&(c.stroke.width=.05,c.stroke.type="default"),e.push(c)}return e}function YEi(t,A){const e=[];for(const i of t){if(!i.outline||i.outline.length<2)continue;const o={top:"F.CrtYd",bottom:"B.CrtYd"}[i.layer]||"F.CrtYd",s=i.outline.map(g=>{const c=g.x-A.x,I=-(g.y-A.y);return new sh(c,I)}),r=new P0e;r.points=new sQ(s),r.layer=o,r.fill=!1;const a=new kS;a.width=.05,a.type="default",r.stroke=a,e.push(r)}return e}function JEi({textElement:t,componentCenter:A,componentRotation:e=0}){if(!t.text||!t.anchor_position)return null;const i=t.anchor_position.x-A.x,n=-(t.anchor_position.y-A.y),o=e!==0?Tl(e*Math.PI/180):xa(),s=Ce(o,{x:i,y:n}),r={x:s.x,y:s.y},g={top:"F.SilkS",bottom:"B.SilkS"}[t.layer]||t.layer||"F.SilkS",c=(t.font_size||1)/1.5,I=new Zf;I.size={width:c,height:c};const l=new Wf({font:I}),B=t.ccw_rotation||0;return new USA({type:"user",text:t.text,position:{x:r.x,y:r.y,angle:B},layer:g,effects:l})}function TEi(t,A,e,i){const n=[];for(const o of t){const s=JEi({textElement:o,componentCenter:A,componentRotation:e});s&&(i&&o.text===i&&(s.type="reference"),n.push(s))}return n}function PEi(t,A,e){const i=[];for(const n of t){const o=n.anchor_position.x-A.x,s=-(n.anchor_position.y-A.y),r=e!==0?Tl(e*Math.PI/180):xa(),a=Ce(r,{x:o,y:s}),g=n.font_size||1,c=new Zf;c.size={width:g,height:g};const I=new Wf({font:c}),l=new USA({type:"user",text:n.text,position:{x:a.x,y:a.y,angle:0},layer:"F.Fab",effects:I});i.push(l)}return i}function KEi(t,A){const e=[],i=t.model_step_url||t.model_wrl_url;if(!i)return e;const n=new XM(i);if(t.position&&(n.offset={x:(t.position.x||0)-A.x,y:-((t.position.y||0)-A.y),z:t.position.z||0}),t.rotation&&(n.rotate={x:t.rotation.x||0,y:t.rotation.y||0,z:t.rotation.z||0}),t.model_unit_to_mm_scale_factor){const o=t.model_unit_to_mm_scale_factor;n.scale={x:o,y:o,z:o}}return e.push(n),e}function qEi({pcbPad:t,componentCenter:A,padNumber:e,componentRotation:i=0,netInfo:n,componentId:o}){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=An(i!==0?Tl(i*Math.PI/180):{a:1,b:0,c:0,d:1,e:0,f:0},$a(1,-1),on(-A.x,-A.y)),g=Ce(a,{x:s,y:r}),I={top:"F.Cu",bottom:"B.Cu"}[t.layer]||"F.Cu";let l,B,C,Q;if(t.shape==="circle")l="circle",B=["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=An($a(1,-1),on(-s,-r)),f=u.map(w=>{const D=Ce(d,{x:w.x,y:w.y});return new sh(D.x,D.y)}),y=new MSA;y.contours=[new sQ(f)],y.width=0,y.filled=!0,Q=new S0e,Q.addGraphic(y),l="custom",C=new g0e,C.anchor="circle",B=[.2,.2]}else l="rect",B=["width"in t?t.width:.5,"height"in t?t.height:.5];const h=`pad:${o}:${e}:${g.x},${g.y}`,E=new HX({number:String(e),padType:"smd",shape:l,at:[g.x,g.y,0],size:B,layers:[`${I}`,`${I==="F.Cu"?"F":"B"}.Paste`,`${I==="F.Cu"?"F":"B"}.Mask`],uuid:jf(h)});return C&&(E.options=C),Q&&(E.primitives=Q),n&&(E.net=new bSA(n.id,n.name)),E}function OEi(t,A,e,i,n,o){const s=[];let r=n;for(const a of t){const g=o(a.pcb_port_id),c=qEi({pcbPad:a,componentCenter:A,padNumber:r,componentRotation:e,netInfo:g,componentId:i});s.push(c),r++}return{pads:s,nextPadNumber:r}}function WEi({platedHole:t,componentCenter:A,padNumber:e,componentRotation:i=0,netInfo:n,componentId:o}){if(!("x"in t&&"y"in t))return null;const s=t.x-A.x,r=-(t.y-A.y),a=i!==0?Tl(i*Math.PI/180):xa(),g=Ce(a,{x:s,y:r});let c="circle",I,l,B=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=Ce(a,{x:-u.x,y:u.y}))}t.shape==="circle"?(c="circle",I=[t.outer_diameter,t.outer_diameter],l=new FS({diameter:t.hole_diameter,offset:Q})):t.shape==="pill"||t.shape==="oval"?(c="oval",I=[t.outer_width,t.outer_height],l=new FS({oval:!0,diameter:t.hole_width,width:t.hole_height,offset:Q})):t.shape==="pill_hole_with_rect_pad"?(c="rect",I=[t.rect_pad_width,t.rect_pad_height],l=new FS({oval:!0,diameter:t.hole_width,width:t.hole_height,offset:Q})):t.shape==="circular_hole_with_rect_pad"?(c="rect",I=[t.rect_pad_width,t.rect_pad_height],l=new FS({diameter:t.hole_diameter,offset:Q})):t.shape==="rotated_pill_hole_with_rect_pad"?(c="rect",I=[t.rect_pad_width,t.rect_pad_height],l=new FS({oval:!0,diameter:t.hole_width,width:t.hole_height,offset:Q}),B=t.rect_ccw_rotation||0):(c="circle",I=[1.6,1.6],l=new FS({diameter:.8,offset:Q}));const h=`thruhole:${o}:${e}:${g.x},${g.y}`,E=new HX({number:String(e),padType:"thru_hole",shape:c,at:[g.x,g.y,B],size:I,drill:l,layers:["*.Cu","*.Mask"],removeUnusedLayers:!1,uuid:jf(h)});return n&&(E.net=new bSA(n.id,n.name)),E}function ZEi(t,A,e,i,n,o){const s=[];let r=n;for(const a of t){const g=o(a.pcb_port_id),c=WEi({platedHole:a,componentCenter:A,padNumber:r,componentRotation:e,netInfo:g,componentId:i});c&&(s.push(c),r++)}return{pads:s,nextPadNumber:r}}function VEi({pcbHole:t,componentCenter:A,componentRotation:e=0}){if(!("x"in t&&"y"in t))return null;const i=t.x-A.x,n=-(t.y-A.y),o=e!==0?Tl(e*Math.PI/180):xa(),s=Ce(o,{x:i,y:n});let r="circle",a,g;if(t.hole_shape==="circle"){r="circle";const c=t.hole_diameter;a=[c,c],g=new FS({diameter:c})}else if(t.hole_shape==="oval"){r="oval";const c=t.hole_width,I=t.hole_height;a=[c,I],g=new FS({oval:!0,diameter:c,width:I})}else{r="circle";const c="hole_diameter"in t?t.hole_diameter:1;a=[c,c],g=new FS({diameter:c})}return new HX({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 jEi(t,A,e){const i=[];for(const n of t){const o=VEi({pcbHole:n,componentCenter:A,componentRotation:e});o&&i.push(o)}return i}var zEi=class extends iu{componentsProcessed=0;pcbComponents=[];includeBuiltin3dModels;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 n=i.subcircuit_connectivity_map_key;if(n)return this.ctx.pcbNetMap?.get(n)}getCadComponentForPcbComponent(t){return(this.ctx.db.cad_component?.list()||[]).find(e=>e.pcb_component_id===t)}constructor(t,A,e){super(t,A),this.pcbComponents=this.ctx.db.pcb_component.list(),this.includeBuiltin3dModels=e?.includeBuiltin3dModels??!1}_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,n=this.getCadComponentForPcbComponent(e.pcb_component_id),o=i?$M(i,n):"Unknown",s=Ce(A,{x:e.center.x,y:e.center.y}),r=`footprint:${e.pcb_component_id}:${s.x},${s.y}`,a=new cbA({libraryLink:`tscircuit:${o}`,layer:"F.Cu",at:[s.x,s.y,e.rotation||0],uuid:jf(r)}),g=a.fpTexts,c=this.ctx.db.pcb_silkscreen_text?.list().filter(O=>O.pcb_component_id===e.pcb_component_id)||[];g.push(...TEi(c,e.center,e.rotation||0,i?.name));const I=this.ctx.db.pcb_note_text?.list().filter(O=>O.pcb_component_id===e.pcb_component_id)||[];g.push(...PEi(I,e.center,e.rotation||0)),a.fpTexts=g;const l=a.fpPads,B=O=>this.getNetInfoForPcbPort(O),C=this.ctx.db.pcb_smtpad?.list().filter(O=>O.pcb_component_id===e.pcb_component_id)||[],{pads:Q,nextPadNumber:h}=OEi(C,e.center,e.rotation||0,e.pcb_component_id,1,B);l.push(...Q);const E=this.ctx.db.pcb_plated_hole?.list().filter(O=>O.pcb_component_id===e.pcb_component_id)||[],{pads:u}=ZEi(E,e.center,e.rotation||0,e.pcb_component_id,h,B);l.push(...u);const d=this.ctx.db.pcb_hole?.list().filter(O=>O.subcircuit_id===e.subcircuit_id)||[],f=jEi(d,e.center,e.rotation||0);l.push(...f),a.fpPads=l;const y=this.ctx.db.pcb_silkscreen_circle?.list().filter(O=>O.pcb_component_id===e.pcb_component_id)||[],w=a.fpCircles??[];w.push(...NEi(y,e.center));const D=this.ctx.db.pcb_courtyard_circle?.list().filter(O=>O.pcb_component_id===e.pcb_component_id)||[];w.push(...GEi(D,e.center)),a.fpCircles=w;const S=this.ctx.db.pcb_fabrication_note_rect?.list().filter(O=>O.pcb_component_id===e.pcb_component_id)||[],_=a.fpRects??[];_.push(...LEi(S,e.center));const b=this.ctx.db.pcb_note_rect?.list().filter(O=>O.pcb_component_id===e.pcb_component_id)||[];_.push(...UEi(b,e.center));const N=this.ctx.db.pcb_courtyard_rect?.list().filter(O=>O.pcb_component_id===e.pcb_component_id)||[];_.push(...HEi(N,e.center)),a.fpRects=_;const F=this.ctx.db.pcb_courtyard_outline?.list().filter(O=>O.pcb_component_id===e.pcb_component_id)||[],L=YEi(F,e.center);if(L.length>0&&(a.fpPolys=L),n){const O=KEi(n,e.center),Z="${KIPRJMOD}/3dmodels";if(O.length>0)this.includeBuiltin3dModels?a.models=O.map(X=>{if(!X.path)return X;const eA=yxA(X.path),tA=X.path.startsWith("http://modelcdn.tscircuit.com")||X.path.startsWith("https://modelcdn.tscircuit.com")?"tscircuit_builtin":this.ctx.projectName??eA.replace(/\.[^.]+$/,""),iA=new XM(`${Z}/${tA}.3dshapes/${eA}`);X.offset&&(iA.offset=X.offset),X.scale&&(iA.scale=X.scale),X.rotate&&(iA.rotate=X.rotate);const sA=X.path?.split("?")[0];return sA&&!this.ctx.pcbModel3dSourcePaths?.includes(sA)&&this.ctx.pcbModel3dSourcePaths?.push(sA),iA}):a.models=O;else if(n.footprinter_string&&this.includeBuiltin3dModels){const{footprinter_string:X}=n,eA=`${Z}/tscircuit_builtin.3dshapes/${X}.step`;a.models=[new XM(eA)];const gA=`${mme}/${X}.step`;this.ctx.pcbModel3dSourcePaths?.includes(gA)||this.ctx.pcbModel3dSourcePaths?.push(gA)}}const Y=e.metadata?.kicad_footprint;Y&&i?.name&&REi(a,Y,i.name);const J=t.footprints;J.push(a),t.footprints=J,this.componentsProcessed++}getOutput(){return this.ctx.kicadPcb}},XEi={top:"F.Cu",bottom:"B.Cu",inner1:"In1.Cu",inner2:"In2.Cu",inner3:"In3.Cu",inner4:"In4.Cu",inner5:"In5.Cu",inner6:"In6.Cu"};function $Ei(t){return t&&(XEi[t]||t)||"F.Cu"}function Aui(t){const A=["F.Cu"];for(let e=1;e<t-1;e++)A.push(`In${e}.Cu`);return A.push("B.Cu"),A}var eui=class extends iu{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}let n=i.route[0]?.layer;for(let o=0;o<i.route.length-1;o++){const s=i.route[o],r=i.route[o+1],a=Ce(A,{x:s.x,y:s.y}),g=Ce(A,{x:r.x,y:r.y});let c;if(e){let h=i.subcircuit_connectivity_map_key;if(!h&&i.source_trace_id){const E=this.ctx.db.source_trace?.get(i.source_trace_id);if(E&&(h=E.subcircuit_connectivity_map_key,!h&&E.connected_source_net_ids?.length))for(const u of E.connected_source_net_ids){const d=this.ctx.db.source_net?.get(u);if(d?.subcircuit_connectivity_map_key){h=d.subcircuit_connectivity_map_key;break}}}if(!h&&typeof i.connection_name=="string"){const E=this.ctx.db.source_net?.get(i.connection_name);E?.subcircuit_connectivity_map_key&&(h=E.subcircuit_connectivity_map_key)}h&&(c=e.get(h))}const I=s.layer??r.layer??n,l=$Ei(I),B=`segment:${a.x},${a.y}:${g.x},${g.y}:${l}:${c?.id??0}`,C=new mbA({start:{x:a.x,y:a.y},end:{x:g.x,y:g.y},layer:l,width:i.width||.25,net:new OX(c?.id??0),uuid:jf(B)}),Q=t.segments;Q.push(C),t.segments=Q,s.layer&&(n=s.layer),r.layer&&(n=r.layer)}this.tracesProcessed++}getOutput(){return this.ctx.kicadPcb}},tui=class extends iu{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],n=Ce(A,{x:i.x,y:i.y});let o;if(e){let I=i.subcircuit_connectivity_map_key;if(!I&&i.pcb_trace_id){const l=this.ctx.db.pcb_trace?.get(i.pcb_trace_id);if(l&&("subcircuit_connectivity_map_key"in l&&(I=l.subcircuit_connectivity_map_key),!I&&l.source_trace_id)){const B=this.ctx.db.source_trace?.get(l.source_trace_id);if(B&&("subcircuit_connectivity_map_key"in B&&(I=B.subcircuit_connectivity_map_key),!I&&B.connected_source_net_ids?.length))for(const C of B.connected_source_net_ids){const Q=this.ctx.db.source_net?.get(C);if(Q?.subcircuit_connectivity_map_key){I=Q.subcircuit_connectivity_map_key;break}}}}if(!I&&i.connection_name){const l=this.ctx.db.source_net?.get(i.connection_name);l?.subcircuit_connectivity_map_key&&(I=l.subcircuit_connectivity_map_key)}I&&(o=e.get(I))}const s=this.ctx.numLayers??2,r=i.layers?i.layers.map(I=>I==="top"?"F.Cu":I==="bottom"?"B.Cu":`In${I.replace("inner","")}.Cu`):Aui(s),a=`via:${n.x},${n.y}:${i.outer_diameter||.8}:${i.hole_diameter||.4}:${o?.id??0}`,g=new dxA({at:[n.x,n.y],size:i.outer_diameter||.8,drill:i.hole_diameter||.4,layers:r,net:new uxA(o?.id??0),uuid:jf(a)}),c=t.vias;c.push(g),t.vias=c,this.viasProcessed++}getOutput(){return this.ctx.kicadPcb}};function iui({textElement:t,c2kMatPcb:A}){if(!t.text||!t.anchor_position)return null;const e=Ce(A,{x:t.anchor_position.x,y:t.anchor_position.y}),n={top:"F.Fab",bottom:"B.Fab"}[t.layer]||t.layer||"F.Fab",o=(t.font_size||1)/1.5,s=new Zf;s.size={width:o,height:o};const r=new wP,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 Wf({font:s});a!=="center"&&(g.justify=r);const c=new ac([e.x,e.y,0]),I=new qX({text:t.text,layer:n,effects:g});return I.position=c,I}function nui({textElement:t,c2kMatPcb:A}){if(!t.text||!t.anchor_position)return null;const e=Ce(A,{x:t.anchor_position.x,y:t.anchor_position.y}),n={top:"F.SilkS",bottom:"B.SilkS"}[t.layer]||t.layer||"F.SilkS",o=(t.font_size||1)/1.5,s=new Zf;s.size={width:o,height:o};const r=new wP,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 Wf({font:s});a!=="center"&&(g.justify=r);const c=t.ccw_rotation||0,I=new ac([e.x,e.y,c]),l=new qX({text:t.text,layer:n,effects:g});return l.position=I,l}var oui=class extends iu{_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 s of e)if(!(!s.route||s.route.length<2))for(let r=0;r<s.route.length-1;r++){const a=s.route[r],g=s.route[r+1];if(!a||!g)continue;const c=Ce(A,{x:a.x,y:a.y}),I=Ce(A,{x:g.x,y:g.y}),B={top:"F.SilkS",bottom:"B.SilkS"}[s.layer]||s.layer||"F.SilkS",C=new KX({start:{x:c.x,y:c.y},end:{x:I.x,y:I.y},layer:B,width:s.stroke_width||.15}),Q=t.graphicLines;Q.push(C),t.graphicLines=Q}const i=this.ctx.db.pcb_silkscreen_text?.list().filter(s=>!s.pcb_component_id)||[];for(const s of i){const r=nui({textElement:s,c2kMatPcb:A});if(r){const a=t.graphicTexts;a.push(r),t.graphicTexts=a}}const n=this.ctx.db.pcb_fabrication_note_text?.list()||[];for(const s of n){const r=iui({textElement:s,c2kMatPcb:A});if(r){const a=t.graphicTexts;a.push(r),t.graphicTexts=a}}const o=this.ctx.db.pcb_board?.list()||[];if(o.length>0){const s=o[0];if(!s){this.finished=!0;return}let r;if(s.outline&&s.outline.length>0)r=s.outline;else{const g=s.width?s.width/2:0,c=s.height?s.height/2:0;r=[{x:s.center.x-g,y:s.center.y-c},{x:s.center.x+g,y:s.center.y-c},{x:s.center.x+g,y:s.center.y+c},{x:s.center.x-g,y:s.center.y+c}]}const a=r.map(g=>Ce(A,g));for(let g=0;g<a.length;g++){const c=a[g],I=a[(g+1)%a.length];if(!c||!I)continue;const l=new KX({start:{x:c.x,y:c.y},end:{x:I.x,y:I.y},layer:"Edge.Cuts",width:.1}),B=t.graphicLines;B.push(l),t.graphicLines=B}}this.finished=!0}getOutput(){return this.ctx.kicadPcb}},wme=class{ctx;pipeline;currentStageIndex=0;finished=!1;get currentStage(){return this.pipeline[this.currentStageIndex]}constructor(t,A){this.ctx={db:Ua(t),circuitJson:t,kicadPcb:new pxA({generator:"circuit-json-to-kicad",generatorVersion:"0.0.1"}),c2kMatPcb:An(on(100,100),$a(1,-1)),projectName:A?.projectName,pcbModel3dSourcePaths:[]},this.pipeline=[new bEi(t,this.ctx),new xEi(t,this.ctx),new zEi(t,this.ctx,{includeBuiltin3dModels:A?.includeBuiltin3dModels}),new eui(t,this.ctx),new tui(t,this.ctx),new oui(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()}getModel3dSourcePaths(){return this.ctx.pcbModel3dSourcePaths??[]}},sui=class{ctx;project;constructor(t,A={}){const e=A.projectName??t?.project?.name??"circuit-json-project",i=A.schematicFilename??`${e}.kicad_sch`,n=A.pcbFilename??`${e}.kicad_pcb`,o=new Date().toISOString();this.ctx={db:Ua(t),circuitJson:t},this.project={version:1,head:{generator:"circuit-json-to-kicad",generator_version:"0.0.1",project_name:e,created:o,modified:o},meta:{version:1},text_variables:{},libraries:{pinned_symbol_libs:[],pinned_footprint_libs:[]},boards:[],cvpcb:{meta:{version:0}},erc:{meta:{version:0},erc_exclusions:[]},net_settings:{meta:{version:1},last_net_id:0,classes:[]},pcbnew:{page_layout_descr_file:"",last_paths:{}},schematic:{meta:{version:1},page_layout_descr_file:"",last_opened_files:[i]},board:{meta:{version:1},last_opened_board:n},sheets:[[Math.random().toString(36).substring(2,15),"Root"]]}}runUntilFinished(){}getOutput(){return this.project}getOutputString(){return`${JSON.stringify(this.project,null,2)}
|
|
5830
5830
|
`}},rui=class extends iu{_step(){const t=new yme(this.ctx.circuitJson);t.runUntilFinished(),this.ctx.kicadSchString=t.getOutputString();const A=new wme(this.ctx.circuitJson);A.runUntilFinished(),this.ctx.kicadPcbString=A.getOutputString(),this.finished=!0}getOutput(){return this.ctx.libraryOutput}},aui=class extends iu{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 n=hme(t).find(r=>r instanceof cSA);if(!n){this.ctx.symbolEntries=[],this.finished=!0;return}const o=n.libSymbols;if(!o){this.ctx.symbolEntries=[],this.finished=!0;return}const s=o.symbols??[];for(const r of s){const a=this.isCustomSymbol(r.libraryId),g=this.sanitizeSymbolName(r.libraryId);e.has(g)||(r.libraryId=g,this.updateFootprintProperty(r,A),a||this.snapPinPositionsToGrid(r),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 n=i.value.split(":");n.length>1?i.value=`${A}:${n[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"}snapPinPositionsToGrid(t){for(const e of t.subSymbols??[]){for(const i of e.pins??[])i.at&&(i.at.x=Math.round(i.at.x/1.27)*1.27,i.at.y=Math.round(i.at.y/1.27)*1.27);for(const i of e.polylines??[])if(i.points?.points)for(const n of i.points.points)"x"in n&&"y"in n&&(n.x=Math.round(n.x/1.27)*1.27,n.y=Math.round(n.y/1.27)*1.27)}}getOutput(){return this.ctx.libraryOutput}},gui=20211014,cui="circuit-json-to-kicad",Iui=class extends iu{_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 Gfe({version:gui,generator:cui,symbols:t.map(e=>e.symbol)}).getString()}getOutput(){return this.ctx.libraryOutput}},lui=class extends iu{_step(){const t=this.ctx.libraryName??"tscircuit",A=this.ctx.fpLibraryName??"tscircuit",e=this.ctx.footprintEntries??[],i=this.ctx.symbolEntries??[],n=new Set;for(const r of e)for(const a of r.model3dSourcePaths)n.add(a);const o=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=o,this.ctx.libraryOutput.symLibTableString=s,this.ctx.libraryOutput.model3dSourcePaths=Array.from(n),this.finished=!0}generateFpLibTable(t){return`(fp_lib_table
|
|
5831
5831
|
(version 7)
|
|
5832
5832
|
(lib (name "${t}") (type "KiCad") (uri "\${KIPRJMOD}/${t}.pretty") (options "") (descr "Generated by circuit-json-to-kicad"))
|