tscircuit 0.0.816-libonly → 0.0.817-libonly
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/browser.min.js +675 -675
- package/dist/webworker.min.js +2 -2
- package/package.json +4 -4
package/dist/webworker.min.js
CHANGED
|
@@ -239,9 +239,9 @@ ${_.join(`
|
|
|
239
239
|
${a._facingDirection??Wf(a,s)}`,x:a.x,y:a.y,color:lo(a.pinId,.8)})}for(let s of e.directConnections){let[a,c]=s.pinIds,l=o.get(a),u=o.get(c);r.lines.push({points:[{x:l.x,y:l.y},{x:u.x,y:u.y}],strokeColor:lo(s.netId??`${a}-${c}`,n)})}for(let s of e.netConnections){let a=s.pinIds.map(c=>o.get(c));for(let c=0;c<a.length-1;c++)for(let l=c+1;l<a.length;l++){let u=a[c],h=a[l];r.lines.push({points:[{x:u.x,y:u.y},{x:h.x,y:h.y}],strokeColor:lo(s.netId,n),strokeDash:"4 2"})}}return r},k2t=class extends ss{constructor({inputProblem:t}){super();M(this,"inputProblem");M(this,"mspConnectionPairs",[]);M(this,"dcConnMap");M(this,"globalConnMap");M(this,"queuedDcNetIds");M(this,"chipMap");M(this,"maxMspPairDistance");M(this,"pinMap");M(this,"userNetIdByPinId");this.inputProblem=t,this.maxMspPairDistance=t.maxMspPairDistance??1;let{directConnMap:n,netConnMap:i}=_I(t);this.dcConnMap=n,this.globalConnMap=i,this.pinMap={};for(let r of t.chips)for(let o of r.pins)this.pinMap[o.pinId]={...o,chipId:r.chipId};this.chipMap={};for(let r of t.chips)this.chipMap[r.chipId]=r;this.userNetIdByPinId={};for(let r of t.directConnections)if(r.netId){let[o,s]=r.pinIds;this.userNetIdByPinId[o]=r.netId,this.userNetIdByPinId[s]=r.netId}for(let r of t.netConnections)for(let o of r.pinIds)this.userNetIdByPinId[o]=r.netId;this.queuedDcNetIds=Object.keys(i.netMap)}getConstructorParams(){return{inputProblem:this.inputProblem}}_step(){if(this.queuedDcNetIds.length===0){this.solved=!0;return}let t=this.queuedDcNetIds.shift(),i=this.globalConnMap.getIdsConnectedToNet(t).filter(s=>!!this.pinMap[s]);if(i.length<=1)return;if(i.length===2){let[s,a]=i,c=this.pinMap[s],l=this.pinMap[a];if(Math.abs(c.x-l.x)+Math.abs(c.y-l.y)>this.maxMspPairDistance)return;let h=new Map(Object.entries(this.pinMap));if(uI({inputProblem:this.inputProblem,chipMap:this.chipMap,pinIdMap:h,p1:c,p2:l}))return;let d=this.globalConnMap.getNetConnectedToId(s),_=this.userNetIdByPinId[s]??this.userNetIdByPinId[a];this.mspConnectionPairs.push({mspPairId:`${s}-${a}`,dcConnNetId:t,globalConnNetId:d,userNetId:_,pins:[c,l]});return}let r=new Map(Object.entries(this.pinMap)),o=C2t(i.map(s=>this.pinMap[s]).filter(Boolean),{maxDistance:this.maxMspPairDistance,forbidEdge:(s,a)=>uI({inputProblem:this.inputProblem,chipMap:this.chipMap,pinIdMap:r,p1:s,p2:a})});for(let[s,a]of o){let c=this.pinMap[s],l=this.pinMap[a];if(uI({inputProblem:this.inputProblem,chipMap:this.chipMap,pinIdMap:r,p1:c,p2:l}))continue;let u=this.globalConnMap.getNetConnectedToId(s),h=this.userNetIdByPinId[s]??this.userNetIdByPinId[a];this.mspConnectionPairs.push({mspPairId:`${s}-${a}`,dcConnNetId:t,globalConnNetId:u,userNetId:h,pins:[c,l]})}}visualize(){let t=Ws(this.inputProblem,{chipAlpha:.1,connectionAlpha:.1});for(let n of this.mspConnectionPairs)t.lines.push({points:[{x:n.pins[0].x,y:n.pins[0].y},{x:n.pins[1].x,y:n.pins[1].y}],strokeColor:lo(n.mspPairId,.75)});return t}};function yI(e){let t=e.width/2,n=e.height/2;return{minX:e.center.x-t,maxX:e.center.x+t,minY:e.center.y-n,maxY:e.center.y+n}}var N2t=e=>{let t=yI(e);return{chipId:e.chipId,...t}},Zb=e=>e.chips.map(N2t),gI=1e-9,qs=(e,t,n=gI)=>Math.abs(e.x-t.x)<n,hc=(e,t,n=gI)=>Math.abs(e.y-t.y)<n,gh=(e,t,n,i=gI)=>{let r=qs(e,t,i),o=hc(e,t,i);if(!r&&!o)return!1;if(r){let s=e.x;if(s<n.minX-i||s>n.maxX+i)return!1;let a=Math.min(e.y,t.y),c=Math.max(e.y,t.y);return Math.min(c,n.maxY)-Math.max(a,n.minY)>i}else{let s=e.y;if(s<n.minY-i||s>n.maxY+i)return!1;let a=Math.min(e.x,t.x),c=Math.max(e.x,t.x);return Math.min(c,n.maxX)-Math.max(a,n.minX)>i}},A2t=(e,t,n={})=>{for(let i=0;i<e.length-1;i++){let r=e[i],o=e[i+1],s=n.excludeRectIdsForSegment?.(i)??new Set;for(let a of t)if(!s.has(a.chipId)&&gh(r,o,a))return{segIndex:i,rect:a}}return null},Wb=(e,t)=>{for(let n=0;n<e.length-1;n++)for(let i of t)if(gh(e[n],e[n+1],i))return!0;return!1},vY=1e-9,R2t=(e,t)=>({minX:Math.min(e.x,t.x),maxX:Math.max(e.x,t.x),minY:Math.min(e.y,t.y),maxY:Math.max(e.y,t.y)}),mY=(e,t,n,i=vY)=>e==="x"?t.x<n.minX-i?[(t.x+n.minX)/2]:t.x>n.maxX+i?[(t.x+n.maxX)/2]:[n.minX-.2,n.maxX+.2]:t.y<n.minY-i?[(t.y+n.minY)/2]:t.y>n.maxY+i?[(t.y+n.maxY)/2]:[n.minY-.2,n.maxY+.2],O2t=(e,t,n,i,r,o=vY)=>{let s=[...i].map(a=>n.get(a)).filter(a=>!!a);if(e==="x"){let a=[r.minX,...s.map(d=>d.maxX)].filter(d=>d<t.minX-o),c=[r.maxX,...s.map(d=>d.minX)].filter(d=>d>t.maxX+o),l=a.length>0?Math.max(...a):void 0,u=c.length>0?Math.min(...c):void 0,h=[];return l!==void 0&&h.push((l+t.minX)/2),u!==void 0&&h.push((t.maxX+u)/2),h}else{let a=[r.minY,...s.map(d=>d.maxY)].filter(d=>d<t.minY-o),c=[r.maxY,...s.map(d=>d.minY)].filter(d=>d>t.maxY+o),l=a.length>0?Math.max(...a):void 0,u=c.length>0?Math.min(...c):void 0,h=[];return l!==void 0&&h.push((l+t.minY)/2),u!==void 0&&h.push((t.maxY+u)/2),h}},L2t=1e-9,F2t=(e,t,n,i,r=L2t)=>{if(t<0||t>=e.length-1)return null;let o=e[t],s=e[t+1],a=qs(o,s,r),c=hc(o,s,r);if(!a&&!c||a&&n!=="x"||c&&n!=="y")return null;let l=e.map(u=>({...u}));if(n==="x"){if(Math.abs(o.x-i)<r&&Math.abs(s.x-i)<r)return null;l[t]={...l[t],x:i},l[t+1]={...l[t+1],x:i}}else{if(Math.abs(o.y-i)<r&&Math.abs(s.y-i)<r)return null;l[t]={...l[t],y:i},l[t+1]={...l[t+1],y:i}}if(t-1>=0){let u=l[t-1],h=l[t];if(Math.abs(u.x-h.x)+Math.abs(u.y-h.y)<r)return null}if(t+2<=l.length-1){let u=l[t+1],h=l[t+2];if(Math.abs(u.x-h.x)+Math.abs(u.y-h.y)<r)return null}for(let u=0;u<l.length-1;u++){let h=l[u],d=l[u+1];if(!hc(h,d,r)&&!qs(h,d,r))return null}return l},_Y=(e,t=6)=>e.map(i=>`${i.x.toFixed(t)},${i.y.toFixed(t)}`).join("|"),wY=class extends ss{constructor(t){super();M(this,"pins");M(this,"inputProblem");M(this,"chipMap");M(this,"obstacles");M(this,"rectById");M(this,"aabb");M(this,"baseElbow");M(this,"solvedTracePath",null);M(this,"queue",[]);M(this,"visited",new Set);this.pins=t.pins,this.inputProblem=t.inputProblem,this.chipMap=t.chipMap;for(let r of this.pins)if(!r._facingDirection){let o=this.chipMap[r.chipId];r._facingDirection=Wf(r,o)}this.obstacles=Zb(this.inputProblem),this.rectById=new Map(this.obstacles.map(r=>[r.chipId,r]));let[n,i]=this.pins;this.baseElbow=Qa({x:n.x,y:n.y,facingDirection:n._facingDirection},{x:i.x,y:i.y,facingDirection:i._facingDirection},{overshoot:.2}),this.aabb=R2t({x:n.x,y:n.y},{x:i.x,y:i.y}),this.queue.push({path:this.baseElbow,collisionChipIds:new Set}),this.visited.add(_Y(this.baseElbow))}getConstructorParams(){return{chipMap:this.chipMap,pins:this.pins,inputProblem:this.inputProblem}}axisOfSegment(t,n){return qs(t,n)?"x":hc(t,n)?"y":null}pathLength(t){let n=0;for(let i=0;i<t.length-1;i++)n+=Math.abs(t[i+1].x-t[i].x)+Math.abs(t[i+1].y-t[i].y);return n}_step(){if(this.solvedTracePath){this.solved=!0;return}let t=this.queue.shift();if(!t){this.failed=!0,this.error="No collision-free path found";return}let{path:n,collisionChipIds:i}=t,[r,o]=this.pins,s=A2t(n,this.obstacles);if(!s){let x=n[0],w=n[n.length-1],S=1e-9,C=(I,k)=>Math.abs(I.x-k.x)<S&&Math.abs(I.y-k.y)<S;C(x,{x:r.x,y:r.y})&&C(w,{x:o.x,y:o.y})&&(this.solvedTracePath=n,this.solved=!0);return}let{segIndex:a,rect:c}=s,l=a===0,u=a===n.length-2;if(l){if(n.length<3)return;a=1}else if(u){if(n.length<3)return;a=n.length-3}let h=n[a],d=n[a+1],_=this.axisOfSegment(h,d);if(!_)return;let y=[];if(i.size===0){let x=mY(_,{x:r.x,y:r.y},c),w=mY(_,{x:o.x,y:o.y},c),S=[...x,...w],C=[...new Set(S)];y.push(...C)}else{let x=O2t(_,c,this.rectById,i,this.aabb);y.push(...x)}let g=[];for(let x of y){let w=F2t(n,a,_,x);if(!w)continue;let S=_Y(w);if(this.visited.has(S))continue;this.visited.add(S);let C=new Set(i);C.add(c.chipId);let I=this.pathLength(w);g.push({path:w,collisionRectIds:C,len:I})}g.sort((x,w)=>x.len-w.len);for(let x of g)this.queue.push({path:x.path,collisionChipIds:x.collisionRectIds})}visualize(){let t=Ws(this.inputProblem,{chipAlpha:.1,connectionAlpha:.1});t.lines.push({points:this.baseElbow,strokeColor:"red",strokeDash:"4 4"});let[n,i]=this.pins;t.lines.push({points:[{x:n.x,y:n.y},{x:i.x,y:i.y}],strokeColor:"blue",strokeDash:"5 5"});for(let{path:r,collisionChipIds:o}of this.queue)t.lines.push({points:r,strokeColor:"teal",strokeDash:"2 2"});return this.solvedTracePath?t.lines.push({points:this.solvedTracePath,strokeColor:"green"}):this.queue.length>0&&t.lines.push({points:this.queue[0].path,strokeColor:"orange"}),t}},z2t=class extends ss{constructor(t){super();M(this,"inputProblem");M(this,"mspConnectionPairs");M(this,"dcConnMap");M(this,"globalConnMap");M(this,"queuedConnectionPairs");M(this,"chipMap");M(this,"currentConnectionPair",null);M(this,"solvedTracePaths",[]);M(this,"failedConnectionPairs",[]);this.inputProblem=t.inputProblem,this.mspConnectionPairs=t.mspConnectionPairs,this.dcConnMap=t.dcConnMap,this.globalConnMap=t.globalConnMap,this.chipMap=t.chipMap,this.queuedConnectionPairs=[...this.mspConnectionPairs]}getConstructorParams(){return{inputProblem:this.inputProblem,chipMap:this.chipMap,mspConnectionPairs:this.mspConnectionPairs,dcConnMap:this.dcConnMap,globalConnMap:this.globalConnMap}}_step(){if(this.activeSubSolver?.solved&&(this.solvedTracePaths.push({...this.currentConnectionPair,tracePath:this.activeSubSolver.solvedTracePath,mspConnectionPairIds:[this.currentConnectionPair.mspPairId],pinIds:[this.currentConnectionPair.pins[0].pinId,this.currentConnectionPair.pins[1].pinId]}),this.activeSubSolver=null,this.currentConnectionPair=null),this.activeSubSolver?.failed&&(this.currentConnectionPair&&this.failedConnectionPairs.push({...this.currentConnectionPair,error:this.activeSubSolver.error||void 0}),this.activeSubSolver=null,this.currentConnectionPair=null),this.activeSubSolver){this.activeSubSolver.step();return}let t=this.queuedConnectionPairs.shift();if(!t){this.solved=!0;return}this.currentConnectionPair=t;let{pins:n}=t;this.activeSubSolver=new wY({inputProblem:this.inputProblem,pins:n,chipMap:this.chipMap})}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();let t=Ws(this.inputProblem,{chipAlpha:.1,connectionAlpha:.1});for(let{mspPairId:n,tracePath:i}of this.solvedTracePaths)t.lines.push({points:i,strokeColor:"green"});for(let n of this.failedConnectionPairs)t.lines.push({points:[{x:n.pins[0].x,y:n.pins[0].y},{x:n.pins[1].x,y:n.pins[1].y}],strokeColor:"red",strokeDash:"4 2"});return t}},D2t=({pts:e,segmentIndex:t,offset:n,JOG_SIZE:i,EPS:r=1e-6})=>{if(t!==0&&t!==e.length-2)return;let o=e[t],s=e[t+1],a=Math.abs(o.x-s.x)<r,c=Math.abs(o.y-s.y)<r;if(!a&&!c)return;let l=a?s.y>o.y?1:-1:s.x>o.x?1:-1;if(t===0)if(a){let u=o.y+l*i;e.splice(1,1,{x:o.x,y:u},{x:o.x+n,y:u},{x:s.x+n,y:s.y})}else{let u=o.x+l*i;e.splice(1,1,{x:u,y:o.y},{x:u,y:o.y+n},{x:s.x,y:s.y+n})}else if(a){let u=s.y-l*i;e.splice(t,1,{x:o.x+n,y:o.y},{x:s.x+n,y:u},{x:s.x,y:u})}else{let u=s.x-l*i;e.splice(t,1,{x:o.x,y:o.y+n},{x:u,y:s.y+n},{x:u,y:s.y})}},$2t=class extends ss{constructor(t){super();M(this,"overlappingTraceSegments");M(this,"traceNetIslands");M(this,"SHIFT_DISTANCE",.1);M(this,"correctedTraceMap",{});this.overlappingTraceSegments=t.overlappingTraceSegments,this.traceNetIslands=t.traceNetIslands;for(let{connNetId:n,pathsWithOverlap:i}of this.overlappingTraceSegments)for(let{solvedTracePathIndex:r,traceSegmentIndex:o}of i){let s=this.traceNetIslands[n][r].mspPairId;this.correctedTraceMap[s]=this.traceNetIslands[n][r]}}_step(){let n=this.overlappingTraceSegments.map((o,s)=>{let a=Math.floor(s/2)+1;return(s%2===0?-a:a)*this.SHIFT_DISTANCE}),i=(o,s)=>Math.abs(o-s)<1e-6,r=(o,s)=>!!o&&!!s&&i(o.x,s.x)&&i(o.y,s.y);this.overlappingTraceSegments.forEach((o,s)=>{let a=n[s],c=new Map;for(let l of o.pathsWithOverlap)c.has(l.solvedTracePathIndex)||c.set(l.solvedTracePathIndex,new Set),c.get(l.solvedTracePathIndex).add(l.traceSegmentIndex);for(let[l,u]of c){let h=this.traceNetIslands[o.connNetId][l],d=this.correctedTraceMap[h.mspPairId]??h,_=d.tracePath.map(S=>({...S})),y=Array.from(u).sort((S,C)=>S-C),g=Array.from(u).sort((S,C)=>S-C).reverse(),x=this.SHIFT_DISTANCE;for(let S of g)if(!(S<0||S>=_.length-1))if(S===0||S===_.length-2)D2t({pts:_,segmentIndex:S,offset:a,JOG_SIZE:x,EPS:1e-6});else{let C=_[S],I=_[S+1],k=Math.abs(C.x-I.x)<1e-6,P=Math.abs(C.y-I.y)<1e-6;if(!k&&!P)continue;k?(C.x+=a,I.x+=a):(C.y+=a,I.y+=a)}let w=[];for(let S of _)(w.length===0||!r(w[w.length-1],S))&&w.push(S);this.correctedTraceMap[h.mspPairId]={...d,tracePath:w}}}),this.solved=!0}visualize(){let t={lines:[],points:[],rects:[],circles:[]};for(let n of this.overlappingTraceSegments)for(let{solvedTracePathIndex:i,traceSegmentIndex:r}of n.pathsWithOverlap){let o=this.traceNetIslands[n.connNetId][i],s=o.tracePath[r],a=o.tracePath[r+1];t.lines.push({points:[s,a],strokeColor:"red"})}for(let n of Object.values(this.correctedTraceMap))t.lines.push({points:n.tracePath,strokeColor:"blue",strokeDash:"4 2"});return t}},B2t=class extends ss{constructor(t){super();M(this,"inputProblem");M(this,"inputTracePaths");M(this,"globalConnMap");M(this,"traceNetIslands",{});M(this,"correctedTraceMap",{});this.inputProblem=t.inputProblem,this.inputTracePaths=t.inputTracePaths,this.globalConnMap=t.globalConnMap;for(let n of this.inputTracePaths){let{mspPairId:i}=n;this.correctedTraceMap[i]=n}this.traceNetIslands=this.computeTraceNetIslands()}getConstructorParams(){return{inputProblem:this.inputProblem,inputTracePaths:this.inputTracePaths,globalConnMap:this.globalConnMap}}computeTraceNetIslands(){let t={};for(let n of this.inputTracePaths){let i=this.correctedTraceMap[n.mspPairId]??n,r=i.globalConnNetId;t[r]||(t[r]=[]),t[r].push(i)}return t}findNextOverlapIssue(){let n=Object.keys(this.traceNetIslands);for(let i=0;i<n.length;i++)for(let r=i+1;r<n.length;r++){let o=n[i],s=n[r],a=this.traceNetIslands[o]||[],c=this.traceNetIslands[s]||[],l=[],u=[],h=new Set,d=new Set,_=(y,g,x,w)=>{let S=Math.min(y,g),C=Math.max(y,g),I=Math.min(x,w),k=Math.max(x,w);return Math.min(C,k)-Math.max(S,I)>.002};for(let y=0;y<a.length;y++){let x=a[y].tracePath;for(let w=0;w<x.length-1;w++){let S=x[w],C=x[w+1],I=Math.abs(S.x-C.x)<.002,k=Math.abs(S.y-C.y)<.002;if(!(!I&&!k))for(let P=0;P<c.length;P++){let E=c[P].tracePath;for(let A=0;A<E.length-1;A++){let O=E[A],$=E[A+1],B=Math.abs(O.x-$.x)<.002,H=Math.abs(O.y-$.y)<.002;if(!(!B&&!H)){if(I&&B){if(Math.abs(S.x-O.x)<.002&&_(S.y,C.y,O.y,$.y)){let X=`${y}:${w}`,U=`${P}:${A}`;h.has(X)||(l.push({solvedTracePathIndex:y,traceSegmentIndex:w}),h.add(X)),d.has(U)||(u.push({solvedTracePathIndex:P,traceSegmentIndex:A}),d.add(U))}}else if(k&&H&&Math.abs(S.y-O.y)<.002&&_(S.x,C.x,O.x,$.x)){let X=`${y}:${w}`,U=`${P}:${A}`;h.has(X)||(l.push({solvedTracePathIndex:y,traceSegmentIndex:w}),h.add(X)),d.has(U)||(u.push({solvedTracePathIndex:P,traceSegmentIndex:A}),d.add(U))}}}}}}if(l.length>0&&u.length>0)return{overlappingTraceSegments:[{connNetId:o,pathsWithOverlap:l},{connNetId:s,pathsWithOverlap:u}]}}return null}_step(){if(this.activeSubSolver?.solved){for(let[i,r]of Object.entries(this.activeSubSolver.correctedTraceMap))this.correctedTraceMap[i]=r;this.activeSubSolver=null,this.traceNetIslands=this.computeTraceNetIslands()}if(this.activeSubSolver){this.activeSubSolver.step();return}let t=this.findNextOverlapIssue();if(t===null){this.solved=!0;return}let{overlappingTraceSegments:n}=t;this.activeSubSolver=new $2t({overlappingTraceSegments:n,traceNetIslands:this.traceNetIslands})}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();let t=Ws(this.inputProblem);for(let n of Object.values(this.correctedTraceMap))t.lines.push({points:n.tracePath,strokeColor:"purple"});return t}},j2t=class{constructor(e){M(this,"chips");M(this,"spatialIndex");M(this,"spatialIndexIdToChip");this.chips=e.map(t=>({...t,bounds:yI(t),spatialIndexId:null})),this.spatialIndexIdToChip=new Map,this.spatialIndex=new qf(e.length);for(let t of this.chips)t.spatialIndexId=this.spatialIndex.add(t.bounds.minX,t.bounds.minY,t.bounds.maxX,t.bounds.maxY),this.spatialIndexIdToChip.set(t.spatialIndexId,t);this.spatialIndex.finish()}getChipsInBounds(e){return this.spatialIndex.search(e.minX,e.minY,e.maxX,e.maxY).map(n=>this.spatialIndexIdToChip.get(n))}doesOrthogonalLineIntersectChip(e,t={}){let n=t.excludeChipIds??[],[i,r]=e,{x:o,y:s}=i,{x:a,y:c}=r;return this.getChipsInBounds({minX:Math.min(o,a),minY:Math.min(s,c),maxX:Math.max(o,a),maxY:Math.max(s,c)}).filter(u=>!n.includes(u.chipId)).length>0}},Y2t=.45,yY=.2;function fI(e){let{orientation:t,netLabelWidth:n}=e,i=typeof n=="number"?n:Y2t;return t==="y+"||t==="y-"?{width:yY,height:i}:{width:i,height:yY}}function mI(e,t,n,i){switch(t){case"x+":return{x:e.x+n/2,y:e.y};case"x-":return{x:e.x-n/2,y:e.y};case"y+":return{x:e.x,y:e.y+i/2};case"y-":return{x:e.x,y:e.y-i/2}}}function bh(e,t,n){return{minX:e.x-t/2,minY:e.y-n/2,maxX:e.x+t/2,maxY:e.y+n/2}}function SY(e,t,n,i=1e-9){let r=Math.abs(e.x-t.x)<i,o=Math.abs(e.y-t.y)<i;if(!r&&!o)return!1;if(r){let s=e.x;if(s<n.minX-i||s>n.maxX+i)return!1;let a=Math.min(e.y,t.y),c=Math.max(e.y,t.y);return Math.min(c,n.maxY)-Math.max(a,n.minY)>i}else{let s=e.y;if(s<n.minY-i||s>n.maxY+i)return!1;let a=Math.min(e.x,t.x),c=Math.max(e.x,t.x);return Math.min(c,n.maxX)-Math.max(a,n.minX)>i}}function PY(e,t,n,i){for(let[r,o]of Object.entries(t)){let s=o.tracePath;for(let a=0;a<s.length-1;a++)if(!(r===n&&a===i)&&SY(s[a],s[a+1],e))return{hasIntersection:!0,mspPairId:r,segIndex:a}}return{hasIntersection:!1}}function gY(e){let t=0,n=e.tracePath;for(let i=0;i<n.length-1;i++)t+=Math.abs(n[i+1].x-n[i].x)+Math.abs(n[i+1].y-n[i].y);return t}function TY(e){let{inputProblem:t,inputTraceMap:n,globalConnNetId:i,fallbackTrace:r,mspConnectionPairIds:o}=e,s=Object.fromEntries(t.chips.map(d=>[d.chipId,d])),a=Object.values(n).filter(d=>d.globalConnNetId===i);if(o&&o.length>0){let d=new Set(o);a=a.filter(_=>_.mspConnectionPairIds.some(y=>d.has(y)))}let c=new Set;for(let d of a)c.add(d.pins[0].chipId),c.add(d.pins[1].chipId);let l=null,u=-1;for(let d of c){let y=s[d]?.pins?.length??0;y>u&&(u=y,l=d)}let h=l==null?[]:a.filter(d=>d.pins[0].chipId===l||d.pins[1].chipId===l);return h.length>0?h.reduce((d,_)=>gY(d)>=gY(_)?d:_):r}function X2t(e,t){return[{x:e.x,y:e.y},{x:(e.x+t.x)/2,y:(e.y+t.y)/2},{x:t.x,y:t.y}]}function V2t(e){let{inputProblem:t,inputTraceMap:n,chipObstacleSpatialIndex:i,overlappingSameNetTraceGroup:r,availableOrientations:o,netLabelWidth:s}=e,a=r.portOnlyPinId;if(!a)return{placement:null,testedCandidates:[],error:"No portOnlyPinId provided"};let c=null,l=null;for(let P of t.chips){let N=P.pins.find(E=>E.pinId===a);if(N){c={x:N.x,y:N.y},l=N._facingDirection||Wf(N,P);break}}if(!c||!l)return{placement:null,testedCandidates:[],error:`Port-only pin not found: ${a}`};let u=o.length>0?o:["x+","x-","y+","y-"],h={x:c.x,y:c.y},d=P=>P==="x+"?{x:1,y:0}:P==="x-"?{x:-1,y:0}:P==="y+"?{x:0,y:1}:{x:0,y:-1},_=[];for(let P of u){let{width:N,height:E}=fI({orientation:P,netLabelWidth:s}),A=mI(h,P,N,E),O=d(P),$=.001,B={x:A.x+O.x*$,y:A.y+O.y*$},H=bh(B,N,E);if(i.getChipsInBounds(H).length>0){_.push({center:B,width:N,height:E,bounds:H,anchor:h,orientation:P,status:"chip-collision",hostSegIndex:-1});continue}if(PY(H,n,"",-1).hasIntersection){_.push({center:B,width:N,height:E,bounds:H,anchor:h,orientation:P,status:"trace-collision",hostSegIndex:-1});continue}return _.push({center:B,width:N,height:E,bounds:H,anchor:h,orientation:P,status:"ok",hostSegIndex:-1}),{placement:{globalConnNetId:r.globalConnNetId,dcConnNetId:void 0,netId:r.netId,mspConnectionPairIds:[],pinIds:[a],orientation:P,anchorPoint:h,width:N,height:E,center:B},testedCandidates:_}}let y=l,{width:g,height:x}=fI({orientation:y,netLabelWidth:s}),w=mI(h,y,g,x),S=d(y),C=.001,I={x:w.x+S.x*C,y:w.y+S.y*C};return{placement:{globalConnNetId:r.globalConnNetId,dcConnNetId:void 0,netId:r.netId,mspConnectionPairIds:[],pinIds:[a],orientation:y,anchorPoint:h,width:g,height:x,center:I},testedCandidates:_}}function H2t(e){let t=Ws(e.inputProblem),n=e.overlappingSameNetTraceGroup.globalConnNetId,i=TY({inputProblem:e.inputProblem,inputTraceMap:e.inputTraceMap,globalConnNetId:n,fallbackTrace:e.overlappingSameNetTraceGroup.overlappingTraces}),r=lo(n,.9),o=lo(n,.5);for(let s of Object.values(e.inputTraceMap)){let a=i?s.mspPairId===i.mspPairId:!1;t.lines.push({points:s.tracePath})}for(let s of e.testedCandidates){let a=s.status==="ok"?"rgba(0, 180, 0, 0.25)":s.status==="chip-collision"?"rgba(220, 0, 0, 0.25)":s.status==="trace-collision"?"rgba(220, 140, 0, 0.25)":"rgba(120, 120, 120, 0.15)",c=s.status==="ok"?"green":s.status==="chip-collision"?"red":s.status==="trace-collision"?"orange":"gray";t.rects.push({center:{x:(s.bounds.minX+s.bounds.maxX)/2,y:(s.bounds.minY+s.bounds.maxY)/2},width:s.width,height:s.height,fill:a,strokeColor:c}),t.points.push({x:s.anchor.x,y:s.anchor.y,color:c})}if(e.netLabelPlacement){let s=e.netLabelPlacement;t.rects.push({center:s.center,width:s.width,height:s.height,fill:"rgba(0, 128, 255, 0.35)",strokeColor:"blue"}),t.points.push({x:s.anchorPoint.x,y:s.anchorPoint.y,color:"blue"})}return t}var bY=class extends ss{constructor(t){super();M(this,"inputProblem");M(this,"inputTraceMap");M(this,"overlappingSameNetTraceGroup");M(this,"availableOrientations");M(this,"chipObstacleSpatialIndex");M(this,"netLabelWidth");M(this,"netLabelPlacement",null);M(this,"testedCandidates",[]);this.inputProblem=t.inputProblem,this.inputTraceMap=t.inputTraceMap,this.overlappingSameNetTraceGroup=t.overlappingSameNetTraceGroup,this.availableOrientations=t.availableOrientations,this.netLabelWidth=t.netLabelWidth,this.chipObstacleSpatialIndex=t.inputProblem._chipObstacleSpatialIndex??new j2t(t.inputProblem.chips)}getConstructorParams(){return{inputProblem:this.inputProblem,inputTraceMap:this.inputTraceMap,overlappingSameNetTraceGroup:this.overlappingSameNetTraceGroup,availableOrientations:this.availableOrientations,netLabelWidth:this.netLabelWidth}}_step(){if(this.netLabelPlacement){this.solved=!0;return}if(this.overlappingSameNetTraceGroup.portOnlyPinId){let d=V2t({inputProblem:this.inputProblem,inputTraceMap:this.inputTraceMap,chipObstacleSpatialIndex:this.chipObstacleSpatialIndex,overlappingSameNetTraceGroup:this.overlappingSameNetTraceGroup,availableOrientations:this.availableOrientations,netLabelWidth:this.netLabelWidth});if(this.testedCandidates.push(...d.testedCandidates),d.placement){this.netLabelPlacement=d.placement,this.solved=!0;return}this.failed=!0,this.error=d.error??"Could not place net label at port without collisions";return}let t=this.overlappingSameNetTraceGroup.globalConnNetId,n=TY({inputProblem:this.inputProblem,inputTraceMap:this.inputTraceMap,globalConnNetId:t,fallbackTrace:this.overlappingSameNetTraceGroup.overlappingTraces,mspConnectionPairIds:this.overlappingSameNetTraceGroup.mspConnectionPairIds});if(!n){this.failed=!0,this.error="No host trace found for net label placement";return}let i=new Set(this.overlappingSameNetTraceGroup.mspConnectionPairIds??[]),r=Object.values(this.inputTraceMap).filter(d=>d.globalConnNetId===t&&(i.size===0||d.mspConnectionPairIds.some(_=>i.has(_)))),o=this.availableOrientations.length===1?[n,...r.filter(d=>d.mspPairId!==n.mspPairId)]:[n],s=this.availableOrientations.length>0?this.availableOrientations:["x+","x-","y+","y-"],a=this.availableOrientations.length===1,c=(d,_)=>{switch(d){case"y+":return _.y;case"y-":return-_.y;case"x+":return _.x;case"x-":return-_.x}},l=null,u=-1/0,h=1e-6;for(let d of o){let _=d.tracePath.slice();for(let y=0;y<_.length-1;y++){let g=_[y],x=_[y+1],w=Math.abs(g.y-x.y)<h,S=Math.abs(g.x-x.x)<h;if(!w&&!S)continue;let C=w?["y+","y-"]:["x+","x-"],I=s.filter(P=>C.includes(P));if(I.length===0)continue;let k=X2t(g,x);for(let P of k)for(let N of I){let{width:E,height:A}=fI({orientation:N,netLabelWidth:this.netLabelWidth}),O=mI(P,N,E,A),$=N==="x+"?{x:1,y:0}:N==="x-"?{x:-1,y:0}:N==="y+"?{x:0,y:1}:{x:0,y:-1},B=1e-4,H={x:O.x+$.x*B,y:O.y+$.y*B},X=bh(H,E,A);if(this.chipObstacleSpatialIndex.getChipsInBounds(X).length>0){this.testedCandidates.push({center:H,width:E,height:A,bounds:X,anchor:P,orientation:N,status:"chip-collision",hostSegIndex:y});continue}if(PY(X,this.inputTraceMap,d.mspPairId,y).hasIntersection){this.testedCandidates.push({center:H,width:E,height:A,bounds:X,anchor:P,orientation:N,status:"trace-collision",hostSegIndex:y});continue}if(this.testedCandidates.push({center:H,width:E,height:A,bounds:X,anchor:P,orientation:N,status:"ok",hostSegIndex:y}),a){let J=c(N,P);J>u+1e-9&&(u=J,l={anchor:P,orientation:N,width:E,height:A,center:O,hostSegIndex:y,dcConnNetId:d.dcConnNetId,mspPairId:d.mspPairId,pinIds:[d.pins[0].pinId,d.pins[1].pinId]});continue}this.netLabelPlacement={globalConnNetId:this.overlappingSameNetTraceGroup.globalConnNetId,dcConnNetId:d.dcConnNetId,netId:this.overlappingSameNetTraceGroup.netId,mspConnectionPairIds:[d.mspPairId],pinIds:[d.pins[0].pinId,d.pins[1].pinId],orientation:N,anchorPoint:P,width:E,height:A,center:O},this.solved=!0;return}}}if(a&&l){this.netLabelPlacement={globalConnNetId:this.overlappingSameNetTraceGroup.globalConnNetId,dcConnNetId:l.dcConnNetId,netId:this.overlappingSameNetTraceGroup.netId,mspConnectionPairIds:[l.mspPairId],pinIds:l.pinIds,orientation:l.orientation,anchorPoint:l.anchor,width:l.width,height:l.height,center:l.center},this.solved=!0;return}this.failed=!0,this.error="Could not place net label without collisions"}visualize(){return H2t(this)}},IY=class extends ss{constructor(t){super();M(this,"inputProblem");M(this,"inputTraceMap");M(this,"overlappingSameNetTraceGroups");M(this,"queuedOverlappingSameNetTraceGroups");M(this,"netLabelPlacements",[]);M(this,"currentGroup",null);M(this,"triedAnyOrientationFallbackForCurrentGroup",!1);this.inputProblem=t.inputProblem,this.inputTraceMap=t.inputTraceMap,this.overlappingSameNetTraceGroups=this.computeOverlappingSameNetTraceGroups(),this.queuedOverlappingSameNetTraceGroups=[...this.overlappingSameNetTraceGroups]}computeOverlappingSameNetTraceGroups(){let t={};for(let c of Object.values(this.inputTraceMap)){let l=c.globalConnNetId;t[l]||(t[l]=[]),t[l].push(c)}let{netConnMap:n}=_I(this.inputProblem),i=new Map;for(let c of this.inputProblem.chips)for(let l of c.pins)i.set(l.pinId,l);let r={};for(let c of this.inputProblem.directConnections)if(c.netId){let[l,u]=c.pinIds;r[l]=c.netId,r[u]=c.netId}for(let c of this.inputProblem.netConnections)for(let l of c.pinIds)r[l]=c.netId;let o=[],s=this.inputProblem.chips.flatMap(c=>c.pins.map(l=>l.pinId)),a=new Set;for(let c of s){let l=n.getNetConnectedToId(c);l&&a.add(l)}for(let c of a){let u=n.getIdsConnectedToNet(c).filter(_=>i.has(_)),h={};for(let _ of u)h[_]=new Set;for(let _ of t[c]??[]){let y=_.pins[0].pinId,g=_.pins[1].pinId;h[y]&&h[g]&&(h[y].add(g),h[g].add(y))}let d=new Set;for(let _ of u){if(d.has(_))continue;let y=[_],g=new Set;for(d.add(_);y.length>0;){let w=y.pop();g.add(w);for(let S of h[w]??[])d.has(S)||(d.add(S),y.push(S))}let x=(t[c]??[]).filter(w=>g.has(w.pins[0].pinId)&&g.has(w.pins[1].pinId));if(x.length>0){let w=N=>{let E=0,A=N.tracePath;for(let O=0;O<A.length-1;O++)E+=Math.abs(A[O+1].x-A[O].x)+Math.abs(A[O+1].y-A[O].y);return E},S=x[0],C=w(S);for(let N=1;N<x.length;N++){let E=w(x[N]);E>C&&(S=x[N],C=E)}let I=x.find(N=>N.userNetId!=null)?.userNetId;if(!I){for(let N of g)if(r[N]){I=r[N];break}}let k=Array.from(new Set(x.flatMap(N=>N.mspConnectionPairIds??[N.mspPairId]))),P={globalConnNetId:c,netId:I,overlappingTraces:S,mspConnectionPairIds:k};o.push(P)}else for(let w of g){let S=r[w];S&&o.push({globalConnNetId:c,netId:S,portOnlyPinId:w})}}}return o}_step(){if(this.activeSubSolver?.solved){this.netLabelPlacements.push(this.activeSubSolver.netLabelPlacement),this.activeSubSolver=null,this.currentGroup=null,this.triedAnyOrientationFallbackForCurrentGroup=!1;return}if(this.activeSubSolver?.failed){let r=["x+","x-","y+","y-"],o=this.activeSubSolver.availableOrientations,s=o.length===4&&r.every(a=>o.includes(a));if(!this.triedAnyOrientationFallbackForCurrentGroup&&!s&&this.currentGroup){this.triedAnyOrientationFallbackForCurrentGroup=!0;let a=this.currentGroup.netId?this.inputProblem.netConnections.find(c=>c.netId===this.currentGroup.netId)?.netLabelWidth:void 0;this.activeSubSolver=new bY({inputProblem:this.inputProblem,inputTraceMap:this.inputTraceMap,overlappingSameNetTraceGroup:this.currentGroup,availableOrientations:r,netLabelWidth:a});return}this.failed=!0,this.error=this.activeSubSolver.error;return}if(this.activeSubSolver){this.activeSubSolver.step();return}let t=this.queuedOverlappingSameNetTraceGroups.shift();if(!t){this.solved=!0;return}let n=t.netId??t.globalConnNetId;this.currentGroup=t,this.triedAnyOrientationFallbackForCurrentGroup=!1;let i=this.currentGroup.netId?this.inputProblem.netConnections.find(r=>r.netId===this.currentGroup.netId)?.netLabelWidth:void 0;this.activeSubSolver=new bY({inputProblem:this.inputProblem,inputTraceMap:this.inputTraceMap,overlappingSameNetTraceGroup:t,availableOrientations:this.inputProblem.availableNetLabelOrientations[n]??["x+","x-","y+","y-"],netLabelWidth:i})}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();let t=Ws(this.inputProblem);for(let n of Object.values(this.inputTraceMap))t.lines.push({points:n.tracePath,strokeColor:"purple"});for(let n of this.netLabelPlacements)t.rects.push({center:n.center,width:n.width,height:n.height,fill:lo(n.globalConnNetId,.35),strokeColor:lo(n.globalConnNetId,.9)}),t.points.push({x:n.anchorPoint.x,y:n.anchorPoint.y,color:lo(n.globalConnNetId,.9)});return t}},G2t=(e,t)=>{let n=[];for(let i of e)for(let r of t){let o=bh(r.center,r.width,r.height);for(let s=0;s<i.tracePath.length-1;s++){let a=i.tracePath[s],c=i.tracePath[s+1];if(SY(a,c,o)){if(i.globalConnNetId===r.globalConnNetId)break;n.push({trace:i,label:r});break}}}return n},U2t=(e,t)=>{let n=o=>o.x>t.minX&&o.x<t.maxX&&o.y>t.minY&&o.y<t.maxY,i=-1,r=-1;for(let o=0;o<e.length;o++)n(e[o])&&(i===-1&&(i=o),r=o);return{firstInsideIndex:i,lastInsideIndex:r}},dc=e=>{if(e.length<3)return e;let t=[e[0]];for(let i=1;i<e.length-1;i++){let r=t[t.length-1],o=e[i],s=e[i+1];qs(r,o)&&qs(o,s)||hc(r,o)&&hc(o,s)||t.push(o)}if(t.push(e[e.length-1]),t.length<3)return t;let n=[t[0]];for(let i=1;i<t.length-1;i++){let r=n[n.length-1],o=t[i],s=t[i+1];qs(r,o)&&qs(o,s)||hc(r,o)&&hc(o,s)||n.push(o)}return n.push(t[t.length-1]),n},q2t=({initialTrace:e,firstInsideIndex:t,lastInsideIndex:n,labelBounds:i,obstacles:r})=>{if(t<=0||n>=e.tracePath.length-1)return null;let o=e.tracePath[t-1],s=e.tracePath[n+1],a=e.tracePath.slice(0,t),c=e.tracePath.slice(n+1),l=[];if(o.x!==s.x&&o.y!==s.y)l.push([{x:s.x,y:o.y}]),l.push([{x:o.x,y:s.y}]);else if(o.x===s.x||o.y===s.y){let g=[...a,...c],x=dc(g);if(!Wb(x,r))return{...e,tracePath:x}}for(let g=0;g<l.length;g++){let x=l[g],w=[...a,...x,...c],S=dc(w);if(!Wb(S,r))return{...e,tracePath:S}}l.length=0;let u=.1,h=i.minX-u,d=i.maxX+u,_=i.maxY+u,y=i.minY-u;(o.x<=i.minX||s.x<=i.minX)&&o.x<i.maxX&&s.x<i.maxX&&l.push([{x:h,y:o.y},{x:h,y:s.y}]),(o.x>=i.maxX||s.x>=i.maxX)&&o.x>i.minX&&s.x>i.minX&&l.push([{x:d,y:o.y},{x:d,y:s.y}]),(o.y>=i.maxY||s.y>=i.maxY)&&o.y>i.minY&&s.y>i.minY&&l.push([{x:o.x,y:_},{x:s.x,y:_}]),(o.y<=i.minY||s.y<=i.minY)&&o.y<i.maxY&&s.y<i.maxY&&l.push([{x:o.x,y},{x:s.x,y}]);for(let g=0;g<l.length;g++){let x=l[g],w=[...a,...x,...c],S=dc(w);if(!Wb(S,r))return{...e,tracePath:S}}return null},W2t=({initialTrace:e,label:t,labelBounds:n,obstacles:i,paddingBuffer:r,detourCount:o})=>{let s=-1;for(let d=0;d<e.tracePath.length-1;d++)if(gh(e.tracePath[d],e.tracePath[d+1],n)){s=d;break}if(s===-1)return e;let a=e.tracePath[s],c=e.tracePath[s+1];if(!a||!c)return null;let l=[],u=bh(t.center,t.width,t.height),h=r+o*r;if(qs(a,c)){let d=[u.maxX+h,u.minX-h];for(let _ of d)l.push(c.y>a.y?[{x:a.x,y:u.minY-h},{x:_,y:u.minY-h},{x:_,y:u.maxY+h},{x:c.x,y:u.maxY+h}]:[{x:a.x,y:u.maxY+h},{x:_,y:u.maxY+h},{x:_,y:u.minY-h},{x:c.x,y:u.minY-h}])}else{let d=[u.maxY+h,u.minY-h];for(let _ of d)l.push(c.x>a.x?[{x:u.minX-h,y:a.y},{x:u.minX-h,y:_},{x:u.maxX+h,y:_},{x:u.maxX+h,y:c.y}]:[{x:u.maxX+h,y:a.y},{x:u.maxX+h,y:_},{x:u.minX-h,y:_},{x:u.minX-h,y:c.y}])}for(let d of l){let _=[...e.tracePath.slice(0,s+1),...d,...e.tracePath.slice(s+1)],y=dc(_);if(!Wb(y,i))return{...e,tracePath:y}}return null},Z2t=({trace:e,label:t,problem:n,paddingBuffer:i,detourCount:r})=>{let o={...e,tracePath:dc(e.tracePath)};if(e.globalConnNetId===t.globalConnNetId)return o;let s=Zb(n),a=i,c=bh(t.center,t.width,t.height),l={minX:c.minX-a,minY:c.minY-a,maxX:c.maxX+a,maxY:c.maxY+a,chipId:`netlabel-${t.netId}`},u=W2t({initialTrace:o,label:t,labelBounds:l,obstacles:s,paddingBuffer:i,detourCount:r});u&&(o.tracePath=u.tracePath);let{firstInsideIndex:h,lastInsideIndex:d}=U2t(o.tracePath,l),_=q2t({initialTrace:o,firstInsideIndex:h,lastInsideIndex:d,labelBounds:l,obstacles:s});return _||u||o},pI=(e,t)=>{for(let n=0;n<e.length-1;n++){let i=e[n],r=e[n+1];for(let o of t)if(gh(i,r,o))return!0}return!1},hI=e=>{let t=0;for(let n=1;n<e.length-1;n++){let i=e[n-1],r=e[n],o=e[n+1],s=i.x===r.x,a=r.x===o.x;s!==a&&t++}return t},xY=(e,t)=>{let n=[];return e.x===t.x||e.y===t.y?n.push([e,t]):(n.push([e,{x:t.x,y:e.y},t]),n.push([e,{x:e.x,y:t.y},t])),n},dI=(e,t)=>{for(let n=0;n<e.length-1;n++){let i=e[n],r=e[n+1];for(let o of t)if(gh(i,r,o))return!0}return!1},K2t=({path:e,obstacles:t,labelBounds:n})=>{if(e.length<=2)return e;let i=(c,l)=>{if(l>=c.length-3)return-1;let u=l,h=!0;for(let d=l;d<c.length-2&&d<l+10&&!(d+2>=c.length);d++){let _=c[d],y=c[d+1],g=c[d+2],x=_.x===y.x,w=y.x===g.x;if(x===w)break;let S=Math.sign(x?y.y-_.y:y.x-_.x);if(d>l){let C=c[d-1],I=C.x===_.x,k=Math.sign(I?_.y-C.y:_.x-C.x);if(x&&I&&S!==k||!x&&!I&&S!==k){h=!1;break}}u=d+2}return h&&u-l>=3?u:-1},r=[...e],o=hI(r),s=!0;for(;s;){s=!1;for(let c=0;c<r.length-3;c++){let l=i(r,c);if(l>0){let u=r[c],h=r[l],d=xY(u,h);for(let _ of d){let y=[...r.slice(0,c+1),..._.slice(1,-1),...r.slice(l)],g=pI(_,t),x=dI(_,n);if(!g&&!x){let w=hI(y),S=l-c-1;r=y,o=w,s=!0;break}}if(s)break}}if(!s)for(let c=0;c<r.length-2;c++){let l=Math.min(r.length-c-2,r.length-2);for(let u=1;u<=l;u++){let h=c+u+1;if(h>=r.length)continue;let d=r[c],_=r[h],y=xY(d,_);for(let g of y){let x=[...r.slice(0,c+1),...g.slice(1,-1),...r.slice(h)],w=g,S=pI(w,t),C=dI(w,n);if(!S&&!C){let I=hI(x);if(I<o||I===o&&x.length<r.length){r=x,o=I,s=!0;break}}}if(s)break}if(s)break}if(!s)for(let c=0;c<r.length-2;c++){let l=r[c],u=r[c+1],h=r[c+2],d=l.x===u.x&&u.x===h.x,_=l.y===u.y&&u.y===h.y;if(d||_){let y=[...r.slice(0,c+1),...r.slice(c+2)],g=pI([l,h],t),x=dI([l,h],n);if(!g&&!x){r=y,s=!0;break}}}}return dc(r)},J2t=({traces:e,problem:t,allLabelPlacements:n,mergedLabelNetIdMap:i,paddingBuffer:r})=>{let o=!1,s=Zb(t),a=e.map(c=>{let l=c.tracePath,h=n.filter(_=>{let y=i[_.globalConnNetId];return y?!y.has(c.globalConnNetId):_.globalConnNetId!==c.globalConnNetId}).map(_=>({minX:_.center.x-_.width/2-r,maxX:_.center.x+_.width/2+r,minY:_.center.y-_.height/2-r,maxY:_.center.y+_.height/2+r})),d=K2t({path:l,obstacles:s,labelBounds:h});return(d.length!==l.length||d.some((_,y)=>_.x!==l[y].x||_.y!==l[y].y))&&(o=!0),{...c,tracePath:d}});return o?a:null},Q2t=({traces:e,problem:t,allLabelPlacements:n})=>{let r=!1;for(let l of e)if(l.tracePath.length===4){let[u,h,d,_]=l.tracePath,y=u.y===h.y&&h.x===d.x&&d.y===_.y,g=u.x===h.x&&h.y===d.y&&d.x===_.x,x=u.y===h.y&&h.y===d.y&&d.y===_.y,w=u.x===h.x&&h.x===d.x&&d.x===_.x,S=x||w,C=!1;if(y?C=Math.sign(h.x-u.x)===Math.sign(_.x-d.x):g&&(C=Math.sign(h.y-u.y)===Math.sign(_.y-d.y)),!((y||g)&&!S&&C))return null}let o=Zb(t).map(l=>({...l,minX:l.minX+1e-5,maxX:l.maxX-1e-5,minY:l.minY+1e-5,maxY:l.maxY-1e-5})),s=(l,u,h)=>{for(let d of h)if(gh(l,u,d))return!0;return!1},a=(l,u)=>l.filter(d=>d.globalConnNetId!==u).map(d=>({minX:d.center.x-d.width/2+1e-5,maxX:d.center.x+d.width/2-1e-5,minY:d.center.y-d.height/2+1e-5,maxY:d.center.y+d.height/2-1e-5})),c=e.map(l=>{let u=[...l.tracePath];if(u.length<4)return{...l};let h=a(n,l.globalConnNetId);if(u.length===4){let[_,y,g,x]=u,w,S;if(_.y===y.y&&y.x===g.x&&g.y===x.y){let k=(_.x+x.x)/2;w={x:k,y:y.y},S={x:k,y:g.y}}else{let k=(_.y+x.y)/2;w={x:y.x,y:k},S={x:g.x,y:k}}return s(_,w,o)||s(w,S,o)||s(S,x,o)||s(_,w,h)||s(w,S,h)||s(S,x,h)||(u[1]=w,u[2]=S,r=!0),{...l,tracePath:dc(u)}}for(let _=1;_<u.length-4;_++){let y=u[_],g=u[_+1],x=u[_+2],w=u[_+3],S=y.y===g.y&&g.x===x.x&&x.y===w.y,C=y.x===g.x&&g.y===x.y&&x.x===w.x,I=y.y===g.y&&g.y===x.y&&x.y===w.y,k=y.x===g.x&&g.x===x.x&&x.x===w.x,P=I||k,N=!1;if(S?N=Math.sign(g.x-y.x)===Math.sign(w.x-x.x):C&&(N=Math.sign(g.y-y.y)===Math.sign(w.y-x.y)),!((S||C)&&!P&&N))continue;let A,O,$=Math.abs(S?y.x-g.x:y.y-g.y),B=Math.abs(S?x.x-w.x:x.y-w.y);if(Math.abs($-B)<.001)continue;if(S){let X=(y.x+w.x)/2;A={x:X,y:g.y},O={x:X,y:x.y}}else{let X=(y.y+w.y)/2;A={x:g.x,y:X},O={x:x.x,y:X}}s(y,A,o)||s(A,O,o)||s(O,w,o)||s(y,A,h)||s(A,O,h)||s(O,w,h)||(u[_+1]=A,u[_+2]=O,r=!0,_=0)}let d=dc(u);return{...l,tracePath:d}});return r?c:null},tvt=class extends ss{constructor(t){super();M(this,"problem");M(this,"traces");M(this,"netTempLabelPlacements");M(this,"netLabelPlacements");M(this,"updatedTraces");M(this,"mergedLabelNetIdMap");M(this,"detourCountByLabel");M(this,"PADDING_BUFFER",.1);this.problem=t.inputProblem,this.traces=t.traces,this.updatedTraces=[...t.traces],this.mergedLabelNetIdMap={},this.detourCountByLabel={};let n=t.netLabelPlacements;if(this.netLabelPlacements=n,!n||n.length===0){this.netTempLabelPlacements=[];return}let i={};for(let o of n){if(o.pinIds.length===0)continue;let s=o.pinIds[0].split(".")[0];if(!s)continue;let a=`${s}-${o.orientation}`;a in i||(i[a]=[]),i[a].push(o)}let r=[];for(let[o,s]of Object.entries(i)){if(s.length<=1){r.push(...s);continue}let a=1/0,c=1/0,l=-1/0,u=-1/0;for(let x of s){let w=bh(x.center,x.width,x.height);a=Math.min(a,w.minX),c=Math.min(c,w.minY),l=Math.max(l,w.maxX),u=Math.max(u,w.maxY)}let h=l-a,d=u-c,_=s[0],y=`merged-group-${o}`,g=new Set(s.map(x=>x.globalConnNetId));this.mergedLabelNetIdMap[y]=g,r.push({..._,globalConnNetId:y,width:h,height:d,center:{x:a+h/2,y:c+d/2},pinIds:[...new Set(s.flatMap(x=>x.pinIds))],mspConnectionPairIds:[...new Set(s.flatMap(x=>x.mspConnectionPairIds))]})}this.netTempLabelPlacements=r}_step(){if(!this.traces||this.traces.length===0||!this.netTempLabelPlacements||this.netTempLabelPlacements.length===0){this.solved=!0;return}this.detourCountByLabel={};let t=G2t(this.traces,this.netTempLabelPlacements);if(t.length===0){this.solved=!0;return}let n=t.filter(c=>{let l=this.mergedLabelNetIdMap[c.label.globalConnNetId];return l?!l.has(c.trace.globalConnNetId):c.trace.globalConnNetId!==c.label.globalConnNetId});if(n.length===0){this.solved=!0;return}let i={};for(let c of this.traces)i[c.mspPairId]=c;let r=new Set;for(let c of n){if(r.has(c.trace.mspPairId))continue;let l=i[c.trace.mspPairId],u=c.label.globalConnNetId,h=this.detourCountByLabel[u]||0,d=Z2t({trace:l,label:c.label,problem:this.problem,paddingBuffer:this.PADDING_BUFFER,detourCount:h});d.tracePath!==l.tracePath&&(this.detourCountByLabel[u]=h+1),i[l.mspPairId]=d,r.add(l.mspPairId)}this.updatedTraces=Object.values(i);let o=J2t({traces:this.updatedTraces,problem:this.problem,allLabelPlacements:this.netTempLabelPlacements,mergedLabelNetIdMap:this.mergedLabelNetIdMap,paddingBuffer:this.PADDING_BUFFER});o&&(this.updatedTraces=o);let s=Q2t({traces:this.updatedTraces,problem:this.problem,allLabelPlacements:this.netLabelPlacements});s&&(this.updatedTraces=s);let a=new IY({inputProblem:this.problem,inputTraceMap:Object.fromEntries(this.updatedTraces.map(c=>[c.mspPairId,c]))});a.solve(),a.failed||(this.netLabelPlacements=a.netLabelPlacements),this.solved=!0}getOutput(){return{traces:this.updatedTraces,netLabelPlacements:this.netLabelPlacements}}visualize(){let t=Ws(this.problem);t.lines||(t.lines=[]),t.circles||(t.circles=[]),t.texts||(t.texts=[]),t.rects||(t.rects=[]);for(let n of this.updatedTraces)t.lines.push({points:n.tracePath,strokeColor:"purple"});for(let n of this.netLabelPlacements)t.rects.push({center:n.center,width:n.width,height:n.height,fill:lo(n.globalConnNetId,.35)}),t.points.push({x:n.anchorPoint.x,y:n.anchorPoint.y,color:lo(n.globalConnNetId,.9)});return t}},evt=e=>{for(let t of e.chips){let n=yI(t);for(let i of t.pins){if(!(i.x>n.minX&&i.x<n.maxX&&i.y>n.minY&&i.y<n.maxY))continue;let o=i.x-n.minX,s=n.maxX-i.x,a=i.y-n.minY,c=n.maxY-i.y,l=Math.min(o,s,a,c);l===o?i.x=n.minX:l===s?i.x=n.maxX:l===a?i.y=n.minY:i.y=n.maxY,i._facingDirection=void 0}}},nvt=e=>{for(let t of e.chips){let n=t.width/2,i=t.height/2,r=0,o=0;for(let c of t.pins){let l=Math.abs(c.x-t.center.x),u=Math.abs(c.y-t.center.y);l>r&&(r=l),u>o&&(o=u)}let s=Math.max(n,r),a=Math.max(i,o);if(s>n||a>i){t.width=s*2,t.height=a*2;for(let c of t.pins)c._facingDirection=void 0}}};function ivt(e,t){for(let n=0;n<e.length-1;n++){let i=e[n],r=e[n+1];for(let o of t)for(let s=0;s<o.tracePath.length-1;s++){let a=o.tracePath[s],c=o.tracePath[s+1];if(xi(i,r,a,c))return!0}}return!1}var rvt=3,ovt=(e,t)=>Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2)),svt=class extends ss{constructor(t){super();M(this,"solvedLongDistanceTraces",[]);M(this,"queuedCandidatePairs",[]);M(this,"currentCandidatePair",null);M(this,"subSolver",null);M(this,"chipMap",{});M(this,"inputProblem");M(this,"netConnMap");M(this,"newlyConnectedPinIds",new Set);M(this,"allSolvedTraces",[]);this.params=t;let{inputProblem:n,primaryMspConnectionPairs:i,alreadySolvedTraces:r}=this.params;this.inputProblem=n,this.allSolvedTraces=[...r];let o=new Set;for(let u of i)o.add(u.pins[0].pinId),o.add(u.pins[1].pinId);let{netConnMap:s}=_I(n);this.netConnMap=s;let a=new Map;for(let u of n.chips){this.chipMap[u.chipId]=u;for(let h of u.pins)a.set(h.pinId,{...h,chipId:u.chipId})}let c=[],l=new Set;for(let u of Object.keys(s.netMap)){let h=s.getIdsConnectedToNet(u);if(h.length<2)continue;let d=h.filter(_=>!o.has(_));for(let _ of d){let y=a.get(_);if(!y)continue;let g=h.filter(x=>x!==_).flatMap(x=>{let w=a.get(x);return w?[{pin:w,distance:ovt(y,w)}]:[]}).sort((x,w)=>x.distance-w.distance).slice(0,rvt);for(let x of g){let w=[y,x.pin],S=w.map(C=>C.pinId).sort().join("--");l.has(S)||(c.push(w),l.add(S))}}}this.queuedCandidatePairs=c}getConstructorParams(){return this.params}_step(){if(this.subSolver?.solved){let t=this.subSolver.solvedTracePath;if(t&&this.currentCandidatePair&&!ivt(t,this.allSolvedTraces)){let[i,r]=this.currentCandidatePair,o=this.netConnMap.getNetConnectedToId(i.pinId),s=`${i.pinId}-${r.pinId}`,a={mspPairId:s,dcConnNetId:o,globalConnNetId:o,pins:[i,r],tracePath:t,mspConnectionPairIds:[s],pinIds:[i.pinId,r.pinId]};this.solvedLongDistanceTraces.push(a),this.allSolvedTraces.push(a),this.newlyConnectedPinIds.add(i.pinId),this.newlyConnectedPinIds.add(r.pinId)}this.subSolver=null,this.currentCandidatePair=null}else this.subSolver?.failed&&(this.subSolver=null,this.currentCandidatePair=null);if(this.subSolver){this.subSolver.step();return}for(;this.queuedCandidatePairs.length>0;){let t=this.queuedCandidatePairs.shift(),[n,i]=t;if(!(this.newlyConnectedPinIds.has(n.pinId)||this.newlyConnectedPinIds.has(i.pinId))){this.currentCandidatePair=t,this.subSolver=new wY({inputProblem:this.params.inputProblem,pins:this.currentCandidatePair,chipMap:this.chipMap});return}}this.solved=!0}visualize(){if(this.subSolver)return this.subSolver.visualize();let t=Ws(this.inputProblem);for(let n of this.solvedLongDistanceTraces)t.lines.push({points:n.tracePath,strokeColor:"purple"});for(let[n,i]of this.queuedCandidatePairs)t.lines.push({points:[n,i],strokeColor:"gray",strokeDash:"4 4"});return t}getOutput(){return this.solved?{newTraces:this.solvedLongDistanceTraces,allTracesMerged:[...this.params.alreadySolvedTraces,...this.solvedLongDistanceTraces]}:{newTraces:[],allTracesMerged:this.params.alreadySolvedTraces}}};function yh(e,t,n,i={}){return{solverName:e,solverClass:t,getConstructorParams:n,onSolved:i.onSolved,shouldSkip:i.shouldSkip}}var MY=class extends ss{constructor(t){super();M(this,"mspConnectionPairSolver");M(this,"schematicTraceLinesSolver");M(this,"longDistancePairSolver");M(this,"traceOverlapShiftSolver");M(this,"netLabelPlacementSolver");M(this,"traceLabelOverlapAvoidanceSolver");M(this,"startTimeOfPhase");M(this,"endTimeOfPhase");M(this,"timeSpentOnPhase");M(this,"firstIterationOfPhase");M(this,"inputProblem");M(this,"pipelineDef",[yh("mspConnectionPairSolver",k2t,()=>[{inputProblem:this.inputProblem}],{onSolved:t=>{}}),yh("schematicTraceLinesSolver",z2t,()=>[{mspConnectionPairs:this.mspConnectionPairSolver.mspConnectionPairs,dcConnMap:this.mspConnectionPairSolver.dcConnMap,globalConnMap:this.mspConnectionPairSolver.globalConnMap,inputProblem:this.inputProblem,chipMap:this.mspConnectionPairSolver.chipMap}]),yh("longDistancePairSolver",svt,t=>[{inputProblem:t.inputProblem,primaryMspConnectionPairs:t.mspConnectionPairSolver.mspConnectionPairs,alreadySolvedTraces:t.schematicTraceLinesSolver.solvedTracePaths}],{onSolved:t=>{}}),yh("traceOverlapShiftSolver",B2t,()=>[{inputProblem:this.inputProblem,inputTracePaths:this.longDistancePairSolver?.getOutput().allTracesMerged,globalConnMap:this.mspConnectionPairSolver.globalConnMap}],{onSolved:t=>{}}),yh("netLabelPlacementSolver",IY,()=>[{inputProblem:this.inputProblem,inputTraceMap:this.traceOverlapShiftSolver?.correctedTraceMap??Object.fromEntries(this.longDistancePairSolver.getOutput().allTracesMerged.map(t=>[t.mspPairId,t]))}],{onSolved:t=>{}}),yh("traceLabelOverlapAvoidanceSolver",tvt,t=>{let n=t.traceOverlapShiftSolver?.correctedTraceMap??Object.fromEntries(t.longDistancePairSolver.getOutput().allTracesMerged.map(o=>[o.mspPairId,o])),i=Object.values(n),r=t.netLabelPlacementSolver.netLabelPlacements;return[{inputProblem:t.inputProblem,traces:i,netLabelPlacements:r}]},{onSolved:t=>{if(t.traceLabelOverlapAvoidanceSolver&&t.netLabelPlacementSolver){let{netLabelPlacements:n}=t.traceLabelOverlapAvoidanceSolver.getOutput();t.netLabelPlacementSolver.netLabelPlacements=n}}})]);M(this,"currentPipelineStepIndex",0);this.inputProblem=this.cloneAndCorrectInputProblem(t),this.MAX_ITERATIONS=1e6,this.startTimeOfPhase={},this.endTimeOfPhase={},this.timeSpentOnPhase={},this.firstIterationOfPhase={}}getConstructorParams(){return this.inputProblem}cloneAndCorrectInputProblem(t){let n=structuredClone({...t,_chipObstacleSpatialIndex:void 0});return nvt(n),evt(n),n}_step(){let t=this.pipelineDef[this.currentPipelineStepIndex];if(!t){this.solved=!0;return}if(this.activeSubSolver){this.activeSubSolver.step(),this.activeSubSolver.solved?(this.endTimeOfPhase[t.solverName]=performance.now(),this.timeSpentOnPhase[t.solverName]=this.endTimeOfPhase[t.solverName]-this.startTimeOfPhase[t.solverName],t.onSolved?.(this),this.activeSubSolver=null,this.currentPipelineStepIndex++):this.activeSubSolver.failed&&(this.error=this.activeSubSolver?.error,this.failed=!0,this.activeSubSolver=null);return}let n=t.getConstructorParams(this);this.activeSubSolver=new t.solverClass(...n),this[t.solverName]=this.activeSubSolver,this.timeSpentOnPhase[t.solverName]=0,this.startTimeOfPhase[t.solverName]=performance.now(),this.firstIterationOfPhase[t.solverName]=this.iterations}solveUntilPhase(t){for(;this.getCurrentPhase().toLowerCase()!==t.toLowerCase();)this.step()}getCurrentPhase(){return this.pipelineDef[this.currentPipelineStepIndex]?.solverName??"none"}visualize(){if(!this.solved&&this.activeSubSolver)return this.activeSubSolver.visualize();let t=[Ws(this.inputProblem),...this.pipelineDef.map(n=>this[n.solverName]?.visualize()).filter(Boolean).map((n,i)=>{for(let r of n.rects??[])r.step=i;for(let r of n.points??[])r.step=i;for(let r of n.circles??[])r.step=i;for(let r of n.texts??[])r.step=i;for(let r of n.lines??[])r.step=i;return n})];return t.length===1?t[0]:{points:t.flatMap(n=>n.points||[]),rects:t.flatMap(n=>n.rects||[]),lines:t.flatMap(n=>n.lines||[]),circles:t.flatMap(n=>n.circles||[]),texts:t.flatMap(n=>n.texts||[])}}preview(){return this.activeSubSolver?this.activeSubSolver.preview():super.preview()}};var GV=Vt(Mn(),1);var UV=Vt(Mn(),1);var qV=Vt(Mn(),1);bi();var avt=e=>{let t=[];t.push(e.title),e.models.size>0&&t.push(...Array.from(e.models.values()));for(let n of e.components)t.push(n.toSpiceString());for(let n of e.subcircuits)t.push(n.toSpiceString());return e.printStatements.length>0&&t.push(...e.printStatements),e.controls.length>0&&(t.push(".control"),t.push(...e.controls),t.push(".endc")),e.tranCommand&&!t.some(n=>n.trim().toLowerCase().startsWith(".tran"))&&t.push(e.tranCommand),t.push(".END"),t.join(`
|
|
240
240
|
`)},cvt=class{constructor(e="Circuit Netlist"){M(this,"title");M(this,"components");M(this,"nodes");M(this,"controls");M(this,"subcircuits");M(this,"models");M(this,"tranCommand");M(this,"printStatements");this.title=e,this.components=[],this.nodes=new Set,this.controls=[],this.subcircuits=[],this.models=new Map,this.tranCommand=null,this.printStatements=[]}addComponent(e){this.components.push(e);for(let t of e.nodes)this.nodes.add(t)}addSubcircuit(e){this.subcircuits.find(t=>t.name===e.name)||this.subcircuits.push(e)}toSpiceString(){return avt(this)}},Zs=class{constructor(e,t,n){M(this,"name");M(this,"command");M(this,"nodes");this.name=e,this.command=t,this.nodes=n}toSpiceString(){return this.command.toSpiceString()}},lvt=class{constructor(e){M(this,"commandName","resistor");M(this,"props");this.props=e}toSpiceString(){let{name:e,positiveNode:t,negativeNode:n,model:i,value:r}=this.props,o=`R${e} ${t} ${n}`;return i&&(o+=` ${i}`),o+=` ${r}`,o}},uvt=class{constructor(e){M(this,"commandName","capacitor");M(this,"props");this.props=e}toSpiceString(){let{name:e,positiveNode:t,negativeNode:n,modelName:i,value:r,initialCondition:o}=this.props,s=`C${e} ${t} ${n}`;return i&&(s+=` ${i}`),s+=` ${r}`,o&&(s+=` IC=${o}`),s}},bI=class{constructor(e){M(this,"commandName","voltage_source");M(this,"props");this.props=e}toSpiceString(){let{name:e,positiveNode:t,negativeNode:n,value:i,acMagnitude:r,acPhase:o}=this.props,s=`V${e} ${t} ${n}`;return i&&(s+=` ${i}`),r&&(s+=` AC ${r}`,o&&(s+=` ${o}`)),s}},pvt=class{constructor(e){M(this,"commandName","diode");M(this,"props");this.props=e}toSpiceString(){let{name:e,positiveNode:t,negativeNode:n,model:i,area:r}=this.props,o=`D${e} ${t} ${n} ${i}`;return r&&(o+=` ${r}`),o}},hvt=class{constructor(e){M(this,"commandName","inductor");M(this,"props");this.props=e}toSpiceString(){let{name:e,positiveNode:t,negativeNode:n,model:i,value:r,initialCondition:o}=this.props,s=`L${e} ${t} ${n}`;return i&&(s+=` ${i}`),s+=` ${r}`,o&&(s+=` IC=${o}`),s}},CY=class{constructor(e){M(this,"commandName","voltage_controlled_switch");M(this,"props");this.props=e}toSpiceString(){let{name:e,positiveNode:t,negativeNode:n,positiveControl:i,negativeControl:r,model:o}=this.props;return`S${e} ${t} ${n} ${i} ${r} ${o}`}};function EY(e){let t=new cvt("* Circuit JSON to SPICE Netlist"),n=Io(e).source_component.list(),i=Io(e).source_port.list(),r=e.filter(g=>g.type==="simulation_switch").map(g=>g),o=new Map;for(let g of r)g.source_component_id&&o.set(g.source_component_id,g);let s=QL(e),a=new Map,c=new Map,l=1,u=new Set,h=new Set(Io(e).source_net.list().filter(g=>g.name?.toLowerCase().includes("gnd")).map(g=>g.source_net_id));if(h.size>0){for(let g of Io(e).source_trace.list())if(g.connected_source_port_ids.length>0&&g.connected_source_net_ids.some(w=>h.has(w))){let w=g.connected_source_port_ids[0],S=s.getNetConnectedToId(w);S&&u.add(S)}}let d=i.filter(g=>g.name?.toLowerCase()==="gnd");for(let g of d){let x=s.getNetConnectedToId(g.source_port_id);x&&u.add(x)}for(let g of Io(e).simulation_voltage_source.list()){let x=g.negative_source_port_id??g.terminal2_source_port_id;if(x){let w=s.getNetConnectedToId(x);w&&u.add(w)}}for(let g of u)c.set(g,"0");for(let g of i){let x=g.source_port_id,w=s.getNetConnectedToId(x);w&&(c.has(w)||c.set(w,`N${l++}`),a.set(x,c.get(w)))}for(let g of i){let x=g.source_port_id;a.has(x)||a.set(x,`N${l++}`)}for(let g of n){if(g.type!=="source_component")continue;let x=Io(e).source_port.list({source_component_id:g.source_component_id}).sort((S,C)=>(S.pin_number??0)-(C.pin_number??0)),w=x.map(S=>a.get(S.source_port_id)||"0");if("ftype"in g){let S=null;switch(g.ftype){case"simple_resistor":{if("resistance"in g&&"name"in g){let C=new lvt({name:g.name,positiveNode:w[0]||"0",negativeNode:w[1]||"0",value:dvt(g.resistance)});S=new Zs(g.name,C,w)}break}case"simple_switch":{let C=_vt(g.name??g.source_component_id,"SW"),I=w[0]||"0",k=w[1]||"0",P=`NCTRL_${C}`,N=`SW_${C}`,E=o.get(g.source_component_id),A=yvt(E),O=new CY({name:C,positiveNode:I,negativeNode:k,positiveControl:P,negativeControl:"0",model:N});S=new Zs(C,O,[I,k,P,"0"]),t.models.has(N)||t.models.set(N,`.MODEL ${N} SW(Ron=0.1 Roff=1e9 Vt=2.5 Vh=0.1)`);let $=`CTRL_${C}`,B=new bI({name:$,positiveNode:P,negativeNode:"0",value:A}),H=new Zs($,B,[P,"0"]);t.addComponent(H);break}case"simple_capacitor":{if("capacitance"in g&&"name"in g){let C=new uvt({name:g.name,positiveNode:w[0]||"0",negativeNode:w[1]||"0",value:fvt(g.capacitance)});S=new Zs(g.name,C,w)}break}case"simple_diode":{if("name"in g){let C=x.find(A=>A.name?.toLowerCase()==="anode"||A.port_hints?.includes("anode")),I=x.find(A=>A.name?.toLowerCase()==="cathode"||A.port_hints?.includes("cathode")),k=a.get(C?.source_port_id??"")||"0",P=a.get(I?.source_port_id??"")||"0",N="D",E=new pvt({name:g.name,positiveNode:k,negativeNode:P,model:N});t.models.set(N,`.MODEL ${N} D`),S=new Zs(g.name,E,[k,P])}break}case"simple_inductor":{if("inductance"in g&&"name"in g){let C=new hvt({name:g.name,positiveNode:w[0]||"0",negativeNode:w[1]||"0",value:mvt(g.inductance)});S=new Zs(g.name,C,w)}break}case"simple_mosfet":{if("name"in g){let C=x.find($=>$.name?.toLowerCase()==="drain"||$.port_hints?.includes("drain")),I=x.find($=>$.name?.toLowerCase()==="gate"||$.port_hints?.includes("gate")),k=x.find($=>$.name?.toLowerCase()==="source"||$.port_hints?.includes("source")),P=a.get(C?.source_port_id??"")||"0",N=a.get(I?.source_port_id??"")||"0",E=a.get(k?.source_port_id??"")||"0",A="SWMOD",O=new CY({name:g.name,positiveNode:P,negativeNode:E,positiveControl:N,negativeControl:E,model:A});t.models.set(A,`.MODEL ${A} SW`),S=new Zs(g.name,O,[P,N,E])}break}}S&&t.addComponent(S)}}let _=Io(e).simulation_voltage_source.list();for(let g of _)if(g.type==="simulation_voltage_source")if(g.is_dc_source===!1){if("terminal1_source_port_id"in g&&"terminal2_source_port_id"in g&&g.terminal1_source_port_id&&g.terminal2_source_port_id){let x=a.get(g.terminal1_source_port_id)||"0",w=a.get(g.terminal2_source_port_id)||"0",S="",C=g.wave_shape;if(C==="sinewave"){let k=g.voltage??0,P=g.frequency??0,N=0,E=0,A=g.phase??0;P>0?S=`SIN(0 ${k} ${P} ${N} ${E} ${A})`:S=`DC ${g.voltage??0}`}else if(C==="square"){let k=g.voltage??0,P=g.frequency??0,N=P===0?1/0:1/P,E=g.period??N,A=g.duty_cycle??.5,O=E*A;S=`PULSE(0 ${k} 0 1n 1n ${O} ${E})`}else g.voltage!==void 0&&(S=`DC ${g.voltage}`);if(S){let I=new bI({name:g.simulation_voltage_source_id,positiveNode:x,negativeNode:w,value:S}),k=new Zs(g.simulation_voltage_source_id,I,[x,w]);t.addComponent(k)}}}else{let x=g.positive_source_port_id??g.terminal1_source_port_id,w=g.negative_source_port_id??g.terminal2_source_port_id;if(x&&w&&"voltage"in g&&g.voltage!==void 0){let S=a.get(x)||"0",C=a.get(w)||"0",I=new bI({name:g.simulation_voltage_source_id,positiveNode:S,negativeNode:C,value:`DC ${g.voltage}`}),k=new Zs(g.simulation_voltage_source_id,I,[S,C]);t.addComponent(k)}}let y=e.find(g=>g.type==="simulation_experiment");if(y){let g=e.filter(C=>C.type==="simulation_voltage_probe");if(g.length>0){let C=Io(e).source_trace.list(),I=new Set;for(let k of g){let P;if(k.source_port_id)P=a.get(k.source_port_id);else if(k.source_net_id){let N=C.find(E=>E.connected_source_net_ids.includes(k.source_net_id));if(N&&N.connected_source_port_ids.length>0){let E=N.connected_source_port_ids[0];P=a.get(E)}}P&&P!=="0"&&I.add(`V(${P.toLowerCase()})`)}I.size>0&&y.experiment_type?.includes("transient")&&t.printStatements.push(`.PRINT TRAN ${[...I].join(" ")}`)}let x=y.time_per_step,w=y.end_time_ms,S=y.start_time_ms;if(x&&w){let C=(S??0)/1e3,I=`.tran ${Mi(x/1e3)} ${Mi(w/1e3)}`;C>0&&(I+=` ${Mi(C)}`),t.tranCommand=I}}return t}function dvt(e){return e>=1e6?`${e/1e6}MEG`:e>=1e3?`${e/1e3}K`:e.toString()}function fvt(e){return e>=.001?`${e*1e3}M`:e>=1e-6?`${e*1e6}U`:e>=1e-9?`${e*1e9}N`:e>=1e-12?`${e*1e12}P`:e.toString()}function mvt(e){return e>=1?e.toString():e>=.001?`${e*1e3}m`:e>=1e-6?`${e*1e6}u`:e>=1e-9?`${e*1e9}n`:e>=1e-12?`${e*1e12}p`:e.toString()}function _vt(e,t){if(!e)return t;let n=e.replace(/[^A-Za-z0-9_]/g,"_");return n?/^[0-9]/.test(n)?`${t}_${n}`:n:t}function yvt(e){if(!e)return"DC 0";let o=e.starts_closed??!1,s=e.closes_at??0,a=e.opens_at,c=e.switching_frequency,[l,u]=o?[5,0]:[0,5];if(c&&c>0){let h=1/c,d=a&&a>s?Math.min(a-s,h):0,_=d>0?d:Math.max(h/2,1e-9);return`PULSE(${Mi(l)} ${Mi(u)} ${Mi(s)} 1n 1n ${Mi(_)} ${Mi(h)})`}if(a!==void 0&&a>s){let h=Math.max(a-s,1e-9),d=s+h*2;return`PULSE(${Mi(l)} ${Mi(u)} ${Mi(s)} 1n 1n ${Mi(h)} ${Mi(d)})`}if(s>0){let h=s*2,d=Math.max(h/2,1e-9);return`PULSE(${Mi(l)} ${Mi(u)} ${Mi(s)} 1n 1n ${Mi(d)} ${Mi(h)})`}return`DC ${o?5:0}`}function Mi(e){if(!Number.isFinite(e))return`${e}`;if(e===0)return"0";let t=Math.abs(e);return t>=1e3||t<=.001?Number(e.toExponential(6)).toString():Number(e.toPrecision(6)).toString()}var WV=Vt(Mn(),1);var Vn=1e-15,gvt=class{constructor(){M(this,"map");M(this,"rev");this.map=new Map([["0",0]]),this.rev=["0"]}getOrCreate(e){let t=String(e),n=t.toUpperCase();if(this.map.has(n))return this.map.get(n);let i=this.rev.length;return this.map.set(n,i),this.rev.push(t),i}get(e){return this.map.get(String(e).toUpperCase())}count(){return this.rev.length}matrixIndexOfNode(e){return e===0?-1:e-1}};function Qi(e){if(e==null)return NaN;let t=String(e).trim();if(t==="")return NaN;if(/^[+-]?\d*\.?\d+(?:[eE][+-]?\d+)?$/.test(t))return parseFloat(t);let n={t:1e12,g:1e9,meg:1e6,k:1e3,m:.001,u:1e-6,n:1e-9,p:1e-12,f:1e-15},i=t.match(/^([+-]?\d*\.?\d+(?:[eE][+-]?\d+)?)([a-zA-Z]+)$/);if(!i)return parseFloat(t);let[,r,o]=i;if(r==null)return parseFloat(t);let s=parseFloat(r),a=(o??"").toLowerCase();return a=a.replace(/(ohm|v|a|s|h|f)$/g,""),a==="meg"?s*n.meg:a.length===1&&a in n?s*n[a]:s}function bvt(e){let t=/"[^"]*"|\w+\s*\([^)]*\)|\([^()]*\)|\S+/g,n=[],i;for(;(i=t.exec(e))!==null;)n.push(i[0]);return n}function Qe(e,t,n){let i=e[t];if(i==null)throw new Error(n);return i}function xvt(e){let i=e.trim().replace(/^pulse\s*\(/i,"(").replace(/^\(/,"").replace(/\)$/,"").trim().split(/[\s,]+/).filter(o=>o.length);if(i.length<7)throw new Error("PULSE(...) requires 7 or 8 args");let r=i.map(o=>Qi(o));if(r.some(o=>Number.isNaN(o)))throw new Error("Invalid PULSE() numeric value");return{v1:r[0],v2:r[1],td:r[2],tr:r[3],tf:r[4],ton:r[5],period:r[6],ncycles:i[7]!=null?r[7]:1/0}}function vvt(e){let i=e.trim().replace(/^pwl\s*\(/i,"(").replace(/^\(/,"").replace(/\)$/,"").trim().split(/[\s,]+/).filter(o=>o.length);if(i.length===0||i.length%2!==0)throw new Error("PWL(...) requires an even number of time/value pairs");let r=[];for(let o=0;o<i.length;o+=2){let s=Qi(i[o]),a=Qi(i[o+1]);if(Number.isNaN(s)||Number.isNaN(a))throw new Error("Invalid PWL() numeric value");r.push({t:s,v:a})}return r}function wvt(e,t){if(e.length===0)return 0;if(t<=e[0].t)return e[0].v;for(let n=1;n<e.length;n++){let i=e[n-1],r=e[n];if(t<=r.t){let o=Math.max(r.t-i.t,Vn),s=(t-i.t)/o;return i.v+(r.v-i.v)*s}}return e[e.length-1].v}function Svt(e,t){if(t<e.td)return e.v1;let n=t-e.td,i=Math.floor(n/e.period);if(i>=e.ncycles)return e.v1;let r=n-i*e.period;if(r<e.tr){let o=r/Math.max(e.tr,Vn);return e.v1+(e.v2-e.v1)*o}if(r<e.tr+e.ton)return e.v2;if(r<e.tr+e.ton+e.tf){let o=(r-(e.tr+e.ton))/Math.max(e.tf,Vn);return e.v2+(e.v1-e.v2)*o}return e.v1}function Pvt(e){let t=new Map,n=new Map,i={nodes:new gvt,R:[],C:[],L:[],V:[],S:[],D:[],analyses:{ac:null,tran:null},probes:{tran:[]},skipped:[],models:{vswitch:t,diode:n}},r=e.split(/\r?\n/),o=!1;for(let a of r){let c=a.trim();if(!c||/^\*/.test(c))continue;if(/^\s*\.end\b/i.test(c))break;c=c.replace(/\/\/.*$/,""),c=c.replace(/;.*$/,"");let l=bvt(c);if(l.length===0)continue;let u=l[0];if(u.length===0)continue;if(!o&&!/^[rclvgsmiqd]\w*$/i.test(u)&&!/^\./.test(u)){o=!0;continue}if(/^\./.test(u)){let _=u.toLowerCase();if(_===".ac"){let y=Qe(l,1,".ac missing mode").toLowerCase();if(y!=="dec"&&y!=="lin")throw new Error(".ac supports 'dec' or 'lin'");let g=parseInt(Qe(l,2,".ac missing point count"),10),x=Qi(Qe(l,3,".ac missing start frequency")),w=Qi(Qe(l,4,".ac missing stop frequency"));i.analyses.ac={mode:y,N:g,f1:x,f2:w}}else if(_===".tran"){let y=Qi(Qe(l,1,".tran missing timestep")),g=Qi(Qe(l,2,".tran missing stop time"));i.analyses.tran={dt:y,tstop:g}}else if(_===".print")if(Qe(l,1,".print missing analysis type").toLowerCase()==="tran"){let g=l.slice(2);for(let x of g){let w=x.match(/^v\(([^)]+)\)$/i);if(w&&w[1]){let S=w[1];i.probes.tran.some(C=>C.toUpperCase()===S.toUpperCase())||i.probes.tran.push(S)}}}else i.skipped.push(c);else if(_===".model"){let y=Qe(l,1,".model missing name"),x=Qe(l,2,".model missing type"),w="";if(x.includes("(")){let C=x.indexOf("(");w=x.slice(C+1),x=x.slice(0,C)}if(!w)w=l.slice(3).join(" ").replace(/^\(/,"").replace(/\)$/,"");else{let C=l.slice(3).join(" ").replace(/\)$/,"");w=`${w} ${C}`.trim()}w=w.replace(/^\(/,"").replace(/\)$/,"").trim();let S=x.toLowerCase();if(S==="vswitch"||S==="sw"){let C={name:y,Ron:1,Roff:1e12,Von:0,Voff:0},I,k;if(w.length>0){let P=w.split(/[\s,]+/).filter(Boolean);for(let N of P){let[E,A]=N.split("=");if(!E||A==null)continue;let O=E.toLowerCase(),$=Qi(A);Number.isNaN($)||(O==="ron"?C.Ron=$:O==="roff"?C.Roff=$:O==="von"?C.Von=$:O==="voff"?C.Voff=$:O==="vt"?I=$:O==="vh"&&(k=$))}}if(I!==void 0){let P=k??0;C.Von=I+P/2,C.Voff=I-P/2}t.set(y.toLowerCase(),C)}else if(S==="d"){let C={name:y,Is:1e-14,N:1};if(w.length>0){let I=w.split(/[\s,]+/).filter(Boolean);for(let k of I){let[P,N]=k.split("=");if(!P||N==null)continue;let E=P.toLowerCase(),A=Qi(N);Number.isNaN(A)||(E==="is"?C.Is=A:E==="n"&&(C.N=A))}}n.set(y.toLowerCase(),C)}else i.skipped.push(c)}else i.skipped.push(c);continue}let h=u.charAt(0).toLowerCase(),d=u;try{if(h==="r"){let _=i.nodes.getOrCreate(Qe(l,1,"Resistor missing node")),y=i.nodes.getOrCreate(Qe(l,2,"Resistor missing node")),g=Qi(Qe(l,3,"Resistor missing value"));i.R.push({name:d,n1:_,n2:y,R:g})}else if(h==="c"){let _=i.nodes.getOrCreate(Qe(l,1,"Capacitor missing node")),y=i.nodes.getOrCreate(Qe(l,2,"Capacitor missing node")),g=Qi(Qe(l,3,"Capacitor missing value"));i.C.push({name:d,n1:_,n2:y,C:g,vPrev:0})}else if(h==="l"){let _=i.nodes.getOrCreate(Qe(l,1,"Inductor missing node")),y=i.nodes.getOrCreate(Qe(l,2,"Inductor missing node")),g=Qi(Qe(l,3,"Inductor missing value"));i.L.push({name:d,n1:_,n2:y,L:g,iPrev:0})}else if(h==="v"){let _=i.nodes.getOrCreate(Qe(l,1,"Voltage source missing node")),y=i.nodes.getOrCreate(Qe(l,2,"Voltage source missing node")),g={dc:0,acMag:0,acPhaseDeg:0,waveform:null,index:-1},x=3;for(x<l.length&&!/^[a-zA-Z]/.test(l[x])&&(g.dc=Qi(l[x]),x++);x<l.length;){let w=l[x].toLowerCase();if(w==="dc"){let S=Qe(l,x+1,"DC value missing");g.dc=Qi(S),x+=2}else if(w==="ac"){let S=Qe(l,x+1,"AC magnitude missing");g.acMag=Qi(S);let C=l[x+2];C!=null&&/^[+-]?\d/.test(C)?(g.acPhaseDeg=Qi(C),x+=3):x+=2}else if(w.startsWith("pulse")){let S=w.includes("(")?w:Qe(l,x+1,"PULSE() missing arguments");if(!S||!/\(.*\)/.test(S))throw new Error("Malformed PULSE() specification");let C=xvt(S);g.waveform=I=>Svt(C,I),x+=w.includes("(")?1:2}else if(w.startsWith("pwl")){let S=w.includes("(")?w:Qe(l,x+1,"PWL() missing arguments");if(!S||!/\(.*\)/.test(S))throw new Error("Malformed PWL() specification");let C=vvt(S);g.waveform=I=>wvt(C,I),x+=w.includes("(")?1:2}else/^\(.*\)$/.test(w),x++}i.V.push({name:d,n1:_,n2:y,dc:g.dc,acMag:g.acMag,acPhaseDeg:g.acPhaseDeg,waveform:g.waveform,index:g.index??-1})}else if(h==="s"){let _=i.nodes.getOrCreate(Qe(l,1,"Switch missing node")),y=i.nodes.getOrCreate(Qe(l,2,"Switch missing node")),g=i.nodes.getOrCreate(Qe(l,3,"Switch missing control node")),x=i.nodes.getOrCreate(Qe(l,4,"Switch missing control node")),w=Qe(l,5,"Switch missing model");i.S.push({name:d,n1:_,n2:y,ncPos:g,ncNeg:x,modelName:w.toLowerCase(),model:null,isOn:!1})}else if(h==="d")if(l.length===4){let _=i.nodes.getOrCreate(Qe(l,1,"Diode missing node")),y=i.nodes.getOrCreate(Qe(l,2,"Diode missing node")),g=Qe(l,3,"Diode missing model");i.D.push({name:d,nPlus:_,nMinus:y,modelName:g.toLowerCase(),model:null,vdPrev:0})}else i.skipped.push(c);else i.skipped.push(c)}catch(_){throw _ instanceof Error?new Error(`Parse error on line: "${c}"
|
|
241
241
|
${_.message}`):_}}let s=i.nodes.count()-1;for(let a=0;a<i.V.length;a++){let c=i.V[a];c&&(c.index=s+a)}for(let a of i.S){let c=t.get(a.modelName);if(!c)throw new Error(`Unknown .model ${a.modelName} referenced by switch ${a.name}`);a.model=c,a.isOn=!1}for(let a of i.D){let c=n.get(a.modelName);if(!c)throw new Error(`Unknown .model ${a.modelName} referenced by diode ${a.name}`);a.model=c}return i}var Ue=class Ks{constructor(t=0,n=0){M(this,"re");M(this,"im");this.re=t,this.im=n}static from(t,n=0){return new Ks(t,n)}static fromPolar(t,n=0){let i=n*Math.PI/180;return new Ks(t*Math.cos(i),t*Math.sin(i))}clone(){return new Ks(this.re,this.im)}add(t){return new Ks(this.re+t.re,this.im+t.im)}sub(t){return new Ks(this.re-t.re,this.im-t.im)}mul(t){return new Ks(this.re*t.re-this.im*t.im,this.re*t.im+this.im*t.re)}div(t){let n=t.re*t.re+t.im*t.im;if(n<Vn)throw new Error("Complex divide by ~0");return new Ks((this.re*t.re+this.im*t.im)/n,(this.im*t.re-this.re*t.im)/n)}inv(){let t=this.re*this.re+this.im*this.im;if(t<Vn)throw new Error("Complex invert by ~0");return new Ks(this.re/t,-this.im/t)}abs(){return Math.hypot(this.re,this.im)}phaseDeg(){return Math.atan2(this.im,this.re)*180/Math.PI}};function Tvt(e,t){let n=e.length;for(let r=0;r<n;r++){let o=e[r],s=t[r];if(!o||!s)throw new Error("Matrix dimensions mismatch");let a=o.map(c=>c.clone());a.push(s.clone()),e[r]=a}for(let r=0;r<n;r++){let o=r,s=e[r];if(!s)throw new Error("Matrix row missing");let a=s[r]?.abs()??0;for(let u=r+1;u<n;u++){let h=e[u];if(!h)throw new Error("Matrix row missing");let d=h[r]?.abs()??0;d>a&&(a=d,o=u)}if(a<Vn)throw new Error("Singular matrix (complex)");if(o!==r){let u=e[r];e[r]=e[o],e[o]=u}let c=e[r];if(!c)throw new Error("Pivot row missing");let l=c[r];if(!l)throw new Error("Zero pivot encountered");for(let u=r+1;u<n;u++){let h=e[u];if(!h)throw new Error("Matrix row missing");let d=h[r];if(!d)continue;let _=d.div(l);if(!(_.abs()<Vn))for(let y=r;y<=n;y++){let g=h[y],x=c[y];!g||!x||(h[y]=g.sub(_.mul(x)))}}}let i=new Array(n);for(let r=n-1;r>=0;r--){let o=e[r];if(!o)throw new Error("Matrix row missing");let s=o[n];if(!s)throw new Error("Augmented column missing");for(let c=r+1;c<n;c++){let l=o[c],u=i[c];!l||!u||(s=s.sub(l.mul(u)))}let a=o[r];if(!a)throw new Error("Zero pivot on back-substitution");i[r]=s.div(a)}return i}function Ivt(e,t,n){if(e<=0||t<=0)throw new Error(".ac frequencies must be > 0");t<e&&([e,t]=[t,e]);let i=Math.log10(t/e),r=Math.max(1,Math.ceil(i*n)),o=[];for(let a=0;a<=r;a++)o.push(e*Math.pow(10,a/n));let s=o[o.length-1];return(s==null||s<t*(1-Vn))&&o.push(t),o}function xI(e,t,n,i,r){let o=t.matrixIndexOfNode(n),s=t.matrixIndexOfNode(i);if(o>=0){let a=e[o];if(!a)throw new Error("Matrix row missing while stamping");a[o]=a[o]?.add(r)??r}if(s>=0){let a=e[s];if(!a)throw new Error("Matrix row missing while stamping");a[s]=a[s]?.add(r)??r}if(o>=0&&s>=0){let a=e[o],c=e[s];if(!a||!c)throw new Error("Matrix row missing while stamping");a[s]=a[s]?.sub(r)??Ue.from(0,0).sub(r),c[o]=c[o]?.sub(r)??Ue.from(0,0).sub(r)}}function Mvt(e,t,n,i,r){let o=n.matrixIndexOfNode(i.n1),s=n.matrixIndexOfNode(i.n2),a=i.index,c=Ue.from(1,0);if(o>=0){let u=e[o];if(!u)throw new Error("Matrix row missing while stamping voltage source");u[a]=u[a]?.add(c)??c}if(s>=0){let u=e[s];if(!u)throw new Error("Matrix row missing while stamping voltage source");u[a]=u[a]?.sub(c)??Ue.from(0,0).sub(c)}let l=e[a];if(!l)throw new Error("Branch row missing while stamping voltage source");o>=0&&(l[o]=l[o]?.add(c)??c),s>=0&&(l[s]=l[s]?.sub(c)??Ue.from(0,0).sub(c)),t[a]=(t[a]??Ue.from(0,0)).add(r)}function Cvt(e){var d,_,y,g;if(!e.analyses.ac)return null;let{mode:t,N:n,f1:i,f2:r}=e.analyses.ac,o=e.nodes.count()-1,s=e.V.length,a=o+s,c=t==="dec"?Ivt(i,r,n):(()=>{let x=[],w=Math.max(2,n),S=(r-i)/(w-1);for(let C=0;C<w;C++)x.push(i+C*S);return x})(),l={};e.nodes.rev.forEach((x,w)=>{w!==0&&(l[x]=[])});let u={},h=2*Math.PI;for(let x of c){let w=Array.from({length:a},()=>Array.from({length:a},()=>Ue.from(0,0))),S=Array.from({length:a},()=>Ue.from(0,0));for(let I of e.R){if(I.R<=0)throw new Error(`R ${I.name} must be > 0`);let k=Ue.from(1/I.R,0);xI(w,e.nodes,I.n1,I.n2,k)}for(let I of e.C){let k=Ue.from(0,h*x*I.C);xI(w,e.nodes,I.n1,I.n2,k)}for(let I of e.L){let k=Ue.from(0,h*x*I.L),P=k.abs()<Vn?Ue.from(0,0):Ue.from(1,0).div(k);xI(w,e.nodes,I.n1,I.n2,P)}for(let I of e.V){let k=Ue.fromPolar(I.acMag||0,I.acPhaseDeg||0);Mvt(w,S,e.nodes,I,k)}let C=Tvt(w,S);for(let I=1;I<e.nodes.count();I++){let k=I-1,P=e.nodes.rev[I];if(!P)continue;let N=l[P];N&&N.push(C[k]??Ue.from(0,0))}for(let I of e.R){let k=I.n1===0?Ue.from(0,0):C[I.n1-1]??Ue.from(0,0),P=I.n2===0?Ue.from(0,0):C[I.n2-1]??Ue.from(0,0),E=Ue.from(1/I.R,0).mul(k.sub(P));(u[d=I.name]||(u[d]=[])).push(E)}for(let I of e.C){let k=I.n1===0?Ue.from(0,0):C[I.n1-1]??Ue.from(0,0),P=I.n2===0?Ue.from(0,0):C[I.n2-1]??Ue.from(0,0),E=Ue.from(0,h*x*I.C).mul(k.sub(P));(u[_=I.name]||(u[_]=[])).push(E)}for(let I of e.L){let k=I.n1===0?Ue.from(0,0):C[I.n1-1]??Ue.from(0,0),P=I.n2===0?Ue.from(0,0):C[I.n2-1]??Ue.from(0,0),N=Ue.from(0,h*x*I.L),A=(N.abs()<Vn?Ue.from(0,0):Ue.from(1,0).div(N)).mul(k.sub(P));(u[y=I.name]||(u[y]=[])).push(A)}for(let I of e.V){let k=C[I.index]??Ue.from(0,0);(u[g=I.name]||(u[g]=[])).push(k)}}return{freqs:c,nodeVoltages:l,elementCurrents:u}}function Evt(e,t){let n=e.length;for(let r=0;r<n;r++){let o=e[r],s=t[r];if(!o||s==null)throw new Error("Matrix dimensions mismatch");let a=o.slice();a.push(s),e[r]=a}for(let r=0;r<n;r++){let o=r,s=e[r];if(!s)throw new Error("Matrix row missing");let a=Math.abs(s[r]??0);for(let u=r+1;u<n;u++){let h=e[u];if(!h)throw new Error("Matrix row missing");let d=Math.abs(h[r]??0);d>a&&(a=d,o=u)}if(a<Vn)throw new Error("Singular matrix (real)");if(o!==r){let u=e[r];e[r]=e[o],e[o]=u}let c=e[r];if(!c)throw new Error("Pivot row missing");let l=c[r];if(l==null)throw new Error("Zero pivot encountered");for(let u=r+1;u<n;u++){let h=e[u];if(!h)throw new Error("Matrix row missing");let d=h[r];if(d==null)continue;let _=d/l;if(!(Math.abs(_)<Vn))for(let y=r;y<=n;y++){let g=h[y],x=c[y];g==null||x==null||(h[y]=g-_*x)}}}let i=new Array(n).fill(0);for(let r=n-1;r>=0;r--){let o=e[r];if(!o)throw new Error("Matrix row missing");let s=o[n];if(s==null)throw new Error("Augmented column missing");for(let c=r+1;c<n;c++){let l=o[c],u=i[c];l==null||u==null||(s-=l*u)}let a=o[r];if(a==null)throw new Error("Zero pivot on back-substitution");i[r]=s/a}return i}function Zf(e,t,n,i,r){let o=t.matrixIndexOfNode(n),s=t.matrixIndexOfNode(i);if(o>=0){let a=e[o];if(!a)throw new Error("Matrix row missing while stamping");a[o]=(a[o]??0)+r}if(s>=0){let a=e[s];if(!a)throw new Error("Matrix row missing while stamping");a[s]=(a[s]??0)+r}if(o>=0&&s>=0){let a=e[o],c=e[s];if(!a||!c)throw new Error("Matrix row missing while stamping");a[s]=(a[s]??0)-r,c[o]=(c[o]??0)-r}}function vI(e,t,n,i,r){let o=t.matrixIndexOfNode(n),s=t.matrixIndexOfNode(i);o>=0&&(e[o]=(e[o]??0)-r),s>=0&&(e[s]=(e[s]??0)+r)}function kvt(e,t,n,i,r){let o=n.matrixIndexOfNode(i.n1),s=n.matrixIndexOfNode(i.n2),a=i.index;if(o>=0){let l=e[o];if(!l)throw new Error("Matrix row missing while stamping voltage source");l[a]=(l[a]??0)+1}if(s>=0){let l=e[s];if(!l)throw new Error("Matrix row missing while stamping voltage source");l[a]=(l[a]??0)-1}let c=e[a];if(!c)throw new Error("Branch row missing while stamping voltage source");o>=0&&(c[o]=(c[o]??0)+1),s>=0&&(c[s]=(c[s]??0)-1),t[a]=(t[a]??0)+r}function Nvt(e){var _,y,g,x,w,S;if(!e.analyses.tran)return null;let{dt:t,tstop:n}=e.analyses.tran,i=t>Vn?t:Math.max(n/1e3,Vn),r=Math.max(1,Math.ceil(n/Math.max(i,Vn))),o=r>0?n/r:n,s=e.nodes.count()-1,a=e.V.length,c=s+a,l=[],u={};e.nodes.rev.forEach((C,I)=>{I!==0&&(u[C]=[])});let h={},d=0;for(let C=0;C<=r;C++,d=C*o){l.push(d);let I=new Array(c).fill(0);for(let k=0;k<20;k++){let P=Array.from({length:c},()=>new Array(c).fill(0)),N=new Array(c).fill(0);for(let O of e.R){let $=1/O.R;Zf(P,e.nodes,O.n1,O.n2,$)}for(let O of e.C){let $=O.C/Math.max(o,Vn);Zf(P,e.nodes,O.n1,O.n2,$);let B=-$*O.vPrev;vI(N,e.nodes,O.n1,O.n2,B)}for(let O of e.L){let $=Math.max(o,Vn)/O.L;Zf(P,e.nodes,O.n1,O.n2,$),vI(N,e.nodes,O.n1,O.n2,O.iPrev)}for(let O of e.S){let $=O.model;if(!$)continue;let B=O.isOn?$.Ron:$.Roff,X=1/Math.max(Math.abs(B),Vn);Zf(P,e.nodes,O.n1,O.n2,X)}for(let O of e.V){let $=O.waveform?O.waveform(d):O.dc||0;kvt(P,N,e.nodes,O,$)}let E=.02585;for(let O of e.D){let $=O.model;if(!$)continue;let{nPlus:B,nMinus:H}=O,X=e.nodes.matrixIndexOfNode(B),U=e.nodes.matrixIndexOfNode(H),tt=B===0?0:I[X]??0,J=H===0?0:I[U]??0,V=tt-J,rt=k===0?O.vdPrev:V,K=$.N*E,et=rt;rt>.8&&(et=.8),rt<-1&&(et=-1);let pt=Math.exp(et/K),mt=$.Is*(pt-1),It=Math.max($.Is/K*pt,1e-12),Mt=mt-It*et;Zf(P,e.nodes,B,H,It),vI(N,e.nodes,B,H,Mt)}I=Evt(P,N);let A=!1;for(let O of e.S){let $=O.model;if(!$)continue;let B=O.ncPos===0?0:I[O.ncPos-1]??0,H=O.ncNeg===0?0:I[O.ncNeg-1]??0,X=B-H,U=O.isOn;O.isOn?X<$.Voff&&(U=!1):X>$.Von&&(U=!0),U!==O.isOn&&(O.isOn=U,A=!0)}if(!A||k===19)break}for(let k=1;k<e.nodes.count();k++){let P=k-1,N=e.nodes.rev[k];if(!N)continue;let E=u[N];E&&E.push(I[P]??0)}for(let k of e.R){let P=k.n1===0?0:I[k.n1-1]??0,N=k.n2===0?0:I[k.n2-1]??0,E=(P-N)/k.R;(h[_=k.name]||(h[_]=[])).push(E)}for(let k of e.C){let P=k.n1===0?0:I[k.n1-1]??0,N=k.n2===0?0:I[k.n2-1]??0,E=k.C*(P-N-k.vPrev)/Math.max(o,Vn);(h[y=k.name]||(h[y]=[])).push(E)}for(let k of e.L){let P=k.n1===0?0:I[k.n1-1]??0,N=k.n2===0?0:I[k.n2-1]??0,A=Math.max(o,Vn)/k.L*(P-N)+k.iPrev;(h[g=k.name]||(h[g]=[])).push(A)}for(let k of e.V){let P=I[k.index]??0;(h[x=k.name]||(h[x]=[])).push(P)}for(let k of e.S){let P=k.model;if(!P)continue;let N=k.n1===0?0:I[k.n1-1]??0,E=k.n2===0?0:I[k.n2-1]??0,A=k.isOn?P.Ron:P.Roff,O=Math.max(Math.abs(A),Vn),$=(N-E)/O;(h[w=k.name]||(h[w]=[])).push($)}for(let k of e.D){if(!k.model)continue;let{nPlus:P,nMinus:N,model:E}=k,A=P===0?0:I[P-1]??0,O=N===0?0:I[N-1]??0,$=A-O,H=E.N*.02585,X=Math.exp($/H),U=E.Is*(X-1);(h[S=k.name]||(h[S]=[])).push(U)}for(let k of e.C){let P=k.n1===0?0:I[k.n1-1]??0,N=k.n2===0?0:I[k.n2-1]??0;k.vPrev=P-N}for(let k of e.L){let P=k.n1===0?0:I[k.n1-1]??0,N=k.n2===0?0:I[k.n2-1]??0,E=Math.max(o,Vn)/k.L;k.iPrev=E*(P-N)+k.iPrev}for(let k of e.D){let P=k.nPlus===0?0:I[k.nPlus-1]??0,N=k.nMinus===0?0:I[k.nMinus-1]??0;k.vdPrev=P-N}}if(e.probes.tran.length>0){let C={},I=e.probes.tran.map(k=>k.toUpperCase());for(let k in u)I.includes(k.toUpperCase())&&(C[k]=u[k]);return{times:l,nodeVoltages:C,elementCurrents:h}}return{times:l,nodeVoltages:u,elementCurrents:h}}function kY(e){let t=Pvt(e),n=Cvt(t),i=Nvt(t);return{circuit:t,ac:n,tran:i}}function NY(e,t,n){if(!e||!t.analyses.tran)return[];let{dt:i,tstop:r}=t.analyses.tran,{times:o,nodeVoltages:s}=e,a=[];for(let c in s){let l=s[c];a.push({type:"simulation_transient_voltage_graph",simulation_transient_voltage_graph_id:`stvg_${n}_${c}`,simulation_experiment_id:n,timestamps_ms:o.map(u=>u*1e3),voltage_levels:l,time_per_step:i*1e3,start_time_ms:0,end_time_ms:r*1e3,name:`V(${c})`})}return a}bi();Ne();bi();Ne();Ne();vt();Ne();Ne();Ho();Ne();bi();Ne();bi();Ne();Ne();bi();Ne();function AY(e,t,n,i){return Math.sqrt((n-e)**2+(i-t)**2)}var Avt=e=>{let t=e.filter(o=>o.type==="pcb_port"),n=e.filter(o=>o.type==="pcb_smtpad"),i=e.filter(o=>o.type==="pcb_trace");function r(o,s={}){let a=s.traceWidth||0,c=t.find(l=>AY(l.x,l.y,o.x,o.y)<.01);if(c)return c.pcb_port_id;if(s.isFirstOrLastPoint){let l=n.find(u=>{if(u.shape==="rect")return Math.abs(o.x-u.x)<u.width/2+a/2&&Math.abs(o.y-u.y)<u.height/2+a/2;if(u.shape==="circle")return AY(o.x,o.y,u.x,u.y)<u.radius});if(l)return l.pcb_port_id??null}return null}for(let o of i)for(let s=0;s<o.route.length;s++){let a=o.route[s],c=s===0||s===o.route.length-1;if(a.route_type==="wire"){if(!a.start_pcb_port_id&&s===0){let l=r(a,{isFirstOrLastPoint:c,traceWidth:a.width});l&&(a.start_pcb_port_id=l)}if(!a.end_pcb_port_id&&s===o.route.length-1){let l=r(a,{isFirstOrLastPoint:c,traceWidth:a.width});l&&(a.end_pcb_port_id=l)}}}};function OY(e){Avt(e);let t=e.filter(s=>s.type==="source_trace"),n=e.filter(s=>s.type==="pcb_port"),i=[],r=si(e),o=new Map;for(let s of n)o.set(s.source_port_id,s);for(let s of t){let a=s.connected_source_port_ids;if(a.length<2)continue;let c=[],l=[];for(let y of a){let g=o.get(y);g?c.push(g):l.push(y)}if(c.length<2)continue;let u=c[0],h=r.getNetConnectedToId(u.pcb_port_id);r.getIdsConnectedToNet(h).filter(y=>e.some(g=>g.type==="pcb_trace"&&("pcb_trace_id"in g&&g.pcb_trace_id===y||"route_id"in g&&g.route_id===y))).length===0&&new Set(c.map(g=>g.pcb_component_id)).size>1&&i.push({type:"pcb_port_not_connected_error",message:`pcb_port_not_connected_error: Pcb ports [${c.map(g=>g.pcb_port_id).join(", ")}] are not connected together through the same net.`,error_type:"pcb_port_not_connected_error",pcb_port_ids:c.map(g=>g.pcb_port_id),pcb_component_ids:c.map(g=>g.pcb_component_id),pcb_port_not_connected_error_id:`pcb_port_not_connected_error_trace_${s.source_trace_id}`})}return i}var Rvt=class{constructor({objects:e,getBounds:t,getId:n,CELL_SIZE:i}){M(this,"buckets");M(this,"objectsById");M(this,"getBounds");M(this,"getId");M(this,"CELL_SIZE",.4);M(this,"_idCounter",0);this.buckets=new Map,this.objectsById=new Map,this.getBounds=t,this.getId=n??(()=>this._getNextId()),this.CELL_SIZE=i??this.CELL_SIZE;for(let r of e)this.addObject(r)}_getNextId(){return`${this._idCounter++}`}addObject(e){let t=this.getBounds(e),n=this.getId(e),i={...e,spatialIndexId:n};this.objectsById.set(n,i);let r=Math.floor(t.minX/this.CELL_SIZE),o=Math.floor(t.minY/this.CELL_SIZE),s=Math.floor(t.maxX/this.CELL_SIZE),a=Math.floor(t.maxY/this.CELL_SIZE);for(let c=r;c<=s;c++)for(let l=o;l<=a;l++){let u=`${c}x${l}`,h=this.buckets.get(u);h?h.push(i):this.buckets.set(u,[i])}}removeObject(e){let t=this.objectsById.get(e);if(!t)return!1;this.objectsById.delete(e);let n=this.getBounds(t),i=Math.floor(n.minX/this.CELL_SIZE),r=Math.floor(n.minY/this.CELL_SIZE),o=Math.floor(n.maxX/this.CELL_SIZE),s=Math.floor(n.maxY/this.CELL_SIZE);for(let a=i;a<=o;a++)for(let c=r;c<=s;c++){let l=`${a}x${c}`,u=this.buckets.get(l);if(u){let h=u.findIndex(d=>d.spatialIndexId===e);h!==-1&&(u.splice(h,1),u.length===0&&this.buckets.delete(l))}}return!0}getBucketKey(e,t){return`${Math.floor(e/this.CELL_SIZE)}x${Math.floor(t/this.CELL_SIZE)}`}getObjectsInBounds(e,t=0){let n=[],i=new Set,r=Math.floor((e.minX-t)/this.CELL_SIZE),o=Math.floor((e.minY-t)/this.CELL_SIZE),s=Math.floor((e.maxX+t)/this.CELL_SIZE),a=Math.floor((e.maxY+t)/this.CELL_SIZE);for(let c=r;c<=s;c++)for(let l=o;l<=a;l++){let u=`${c}x${l}`,h=this.buckets.get(u)||[];for(let d of h){let _=d.spatialIndexId;i.has(_)||(i.add(_),n.push(d))}}return n}},Kf=e=>e.type==="pcb_trace_segment"?{minX:Math.min(e.x1,e.x2),minY:Math.min(e.y1,e.y2),maxX:Math.max(e.x1,e.x2),maxY:Math.max(e.y1,e.y2)}:Gp([e]),wI=.1,Ovt=.15;var Lvt=.2,Fvt=.3,Jf=.005;function zvt(e){let t=new Set;for(let n of e.route)n.route_type==="wire"&&(n.start_pcb_port_id&&t.add(n.start_pcb_port_id),n.end_pcb_port_id&&t.add(n.end_pcb_port_id));return Array.from(t)}function SI(e){let t=new Set;for(let n of e)for(let i of zvt(n))t.add(i);return Array.from(t)}var Dvt=(e,t)=>{let n={x:e.x1,y:e.y1},i={x:e.x2,y:e.y2},r={x:t.x1,y:t.y1},o={x:t.x2,y:t.y2},s={x:i.x-n.x,y:i.y-n.y},a={x:o.x-r.x,y:o.y-r.y},c=s.x*s.x+s.y*s.y,l=a.x*a.x+a.y*a.y;if(c===0||l===0){if(c===0&&l===0)return{x:(n.x+r.x)/2,y:(n.y+r.y)/2};if(c===0){let $=as(((n.x-r.x)*a.x+(n.y-r.y)*a.y)/l,0,1),B={x:r.x+$*a.x,y:r.y+$*a.y};return{x:(n.x+B.x)/2,y:(n.y+B.y)/2}}let A=as(((r.x-n.x)*s.x+(r.y-n.y)*s.y)/c,0,1),O={x:n.x+A*s.x,y:n.y+A*s.y};return{x:(O.x+r.x)/2,y:(O.y+r.y)/2}}let u={x:n.x-r.x,y:n.y-r.y},h=s.x*s.x+s.y*s.y,d=s.x*a.x+s.y*a.y,_=s.x*u.x+s.y*u.y,y=a.x*a.x+a.y*a.y,g=a.x*u.x+a.y*u.y,x=h*y-d*d;if(x<1e-10)return $vt(n,i,r,o,s,a,c,l);let w=(d*g-y*_)/x,S=(h*g-d*_)/x;w=as(w,0,1),S=as(S,0,1),S=(w*d+g)/y,S=as(S,0,1),w=(S*d-_)/h,w=as(w,0,1);let C={x:n.x+w*s.x,y:n.y+w*s.y},I={x:r.x+S*a.x,y:r.y+S*a.y},k=C.x-I.x,P=C.y-I.y,N=Math.sqrt(k*k+P*P);return{x:(C.x+I.x)/2,y:(C.y+I.y)/2}},$vt=(e,t,n,i,r,o,s,a)=>{let c=((n.x-e.x)*r.x+(n.y-e.y)*r.y)/s;c=as(c,0,1);let l={x:e.x+c*r.x,y:e.y+c*r.y},u=((i.x-e.x)*r.x+(i.y-e.y)*r.y)/s;u=as(u,0,1);let h={x:e.x+u*r.x,y:e.y+u*r.y},d=((e.x-n.x)*o.x+(e.y-n.y)*o.y)/a;d=as(d,0,1);let _={x:n.x+d*o.x,y:n.y+d*o.y},y=((t.x-n.x)*o.x+(t.y-n.y)*o.y)/a;y=as(y,0,1);let g={x:n.x+y*o.x,y:n.y+y*o.y},w=[{pointA:l,pointB:n,distance:Math.sqrt((l.x-n.x)**2+(l.y-n.y)**2)},{pointA:h,pointB:i,distance:Math.sqrt((h.x-i.x)**2+(h.y-i.y)**2)},{pointA:e,pointB:_,distance:Math.sqrt((e.x-_.x)**2+(e.y-_.y)**2)},{pointA:t,pointB:g,distance:Math.sqrt((t.x-g.x)**2+(t.y-g.y)**2)}].reduce((S,C)=>C.distance<S.distance?C:S);return{x:(w.pointA.x+w.pointB.x)/2,y:(w.pointA.y+w.pointB.y)/2}},as=(e,t,n)=>Math.max(t,Math.min(n,e)),Bvt=e=>{if(e.type==="pcb_via"||e.type==="pcb_plated_hole"&&e.shape==="circle")return e.outer_diameter/2;if(e.type==="pcb_hole"&&e.hole_shape==="circle")return e.hole_diameter/2;if(e.type==="pcb_smtpad"&&e.shape==="circle")return e.radius;throw new Error(`Could not determine radius of element: ${JSON.stringify(e)}`)},RY=(e,t)=>{let n={x:e.x1,y:e.y1},i={x:e.x2,y:e.y2},r=t.minX,o=t.minY,s=t.maxX,a=t.maxY;if(n.x===i.x&&n.y===i.y){let E=Math.max(r,Math.min(s,n.x)),A=Math.max(o,Math.min(a,n.y));return E===n.x&&A===n.y?{x:n.x,y:n.y}:{x:E,y:A}}let c=i.x-n.x,l=i.y-n.y,u=c!==0?(r-n.x)/c:Number.NEGATIVE_INFINITY,h=c!==0?(s-n.x)/c:Number.POSITIVE_INFINITY,d=l!==0?(o-n.y)/l:Number.NEGATIVE_INFINITY,_=l!==0?(a-n.y)/l:Number.POSITIVE_INFINITY,y=Math.max(Math.min(u,h),Math.min(d,_)),g=Math.min(Math.max(u,h),Math.max(d,_));if(y<=g&&g>=0&&y<=1){let E=Math.max(0,Math.min(1,y));return{x:n.x+E*c,y:n.y+E*l}}let x={x:Math.max(r,Math.min(s,n.x)),y:Math.max(o,Math.min(a,n.y))},w={x:Math.max(r,Math.min(s,i.x)),y:Math.max(o,Math.min(a,i.y))},S=(x.x-n.x)**2+(x.y-n.y)**2,C=(w.x-i.x)**2+(w.y-i.y)**2,I=[{start:{x:r,y:o},end:{x:s,y:o}},{start:{x:s,y:o},end:{x:s,y:a}},{start:{x:s,y:a},end:{x:r,y:a}},{start:{x:r,y:a},end:{x:r,y:o}}],k=Math.min(S,C),P=S<=C?x:w,N=(E,A,O)=>Math.max(A,Math.min(O,E));for(let E of I){let A={x:i.x-n.x,y:i.y-n.y},O={x:E.end.x-E.start.x,y:E.end.y-E.start.y},$={x:n.x-E.start.x,y:n.y-E.start.y},B=A.x*A.x+A.y*A.y,H=A.x*O.x+A.y*O.y,X=A.x*$.x+A.y*$.y,U=O.x*O.x+O.y*O.y,tt=O.x*$.x+O.y*$.y,J=B*U-H*H;if(Math.abs(J)<1e-10)continue;let V=(H*tt-U*X)/J,rt=(B*tt-H*X)/J;V=N(V,0,1),rt=N(rt,0,1);let K={x:n.x+V*A.x,y:n.y+V*A.y},et={x:E.start.x+rt*O.x,y:E.start.y+rt*O.y},pt=K.x-et.x,mt=K.y-et.y,It=pt*pt+mt*mt;It<k&&(k=It,P={x:(K.x+et.x)/2,y:(K.y+et.y)/2})}return P};function jvt(e){return e.type==="pcb_trace_segment"?[e.layer]:e.type==="pcb_smtpad"?[e.layer]:e.type==="pcb_plated_hole"?Array.isArray(e.layers)?e.layers:[...yp]:e.type==="pcb_hole"?[...yp]:e.type==="pcb_via"?Array.isArray(e.layers)?e.layers:[...yp]:e.type==="pcb_keepout"?Array.isArray(e.layers)?e.layers:[]:[]}function LY(e,{connMap:t}={}){let n=[];t??(t=si(e));let r=Ze(e).pcb_trace.list().flatMap(y=>{let g=[];for(let x=0;x<y.route.length-1;x++){let w=y.route[x],S=y.route[x+1];w.route_type==="wire"&&S.route_type==="wire"&&w.layer===S.layer&&g.push({type:"pcb_trace_segment",pcb_trace_id:y.pcb_trace_id,_pcbTrace:y,thickness:"width"in w?w.width:"width"in S?S.width:Ovt,layer:w.layer,x1:w.x,y1:w.y,x2:S.x,y2:S.y})}return g}),o=Ze(e).pcb_smtpad.list(),s=Ze(e).pcb_plated_hole.list(),a=Ze(e).pcb_hole.list(),c=Ze(e).pcb_via.list(),l=Ze(e).pcb_keepout.list(),u=[...r,...o,...s,...a,...c,...l],h=new Rvt({objects:u,getBounds:Kf}),d=y=>so(e,y),_=new Set;for(let y of r){let g=wI,x=Kf(y),w=h.getObjectsInBounds(x,g+y.thickness/2);if(!(y.x1===y.x2&&y.y1===y.y2))for(let S of w){if(!jvt(S).includes(y.layer))continue;if(S.type==="pcb_trace_segment"){let P=S;if(y.layer!==P.layer||t.areIdsConnected(y.pcb_trace_id,P.pcb_trace_id))continue;let N=Vp({x:y.x1,y:y.y1},{x:y.x2,y:y.y2},{x:P.x1,y:P.y1},{x:P.x2,y:P.y2})-y.thickness/2-P.thickness/2;if(N>wI-Jf)continue;let E=`overlap_${y.pcb_trace_id}_${P.pcb_trace_id}`,A=`overlap_${P.pcb_trace_id}_${y.pcb_trace_id}`;if(_.has(E)||_.has(A))continue;_.add(E),n.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${d(y.pcb_trace_id)} overlaps with ${d(P.pcb_trace_id)} ${N<0?"(accidental contact)":`(gap: ${N.toFixed(3)}mm)`}`,pcb_trace_id:y.pcb_trace_id,source_trace_id:"",pcb_trace_error_id:E,pcb_component_ids:[],center:Dvt(y,P),pcb_port_ids:SI([y._pcbTrace,P._pcbTrace])});continue}let C=Wo(S);if(t.areIdsConnected(y.pcb_trace_id,"pcb_trace_id"in S?S.pcb_trace_id:C))continue;if(S.type==="pcb_via"||S.type==="pcb_plated_hole"&&S.shape==="circle"||S.type==="pcb_hole"||S.type==="pcb_smtpad"&&S.shape==="circle"){let P=Bvt(S),E=Dg({x:y.x1,y:y.y1},{x:y.x2,y:y.y2},{x:S.x,y:S.y,radius:P})-y.thickness/2;if(E>wI-Jf)continue;let A=`overlap_${y.pcb_trace_id}_${C}`;if(_.has(A))continue;_.add(A),n.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${d(y.pcb_trace_id)} overlaps with ${S.type} "${d(Wo(S))}" ${E<0?"(accidental contact)":`(gap: ${E.toFixed(3)}mm)`}`,pcb_trace_id:y.pcb_trace_id,center:RY(y,Kf(S)),source_trace_id:"",pcb_trace_error_id:A,pcb_component_ids:["pcb_component_id"in S?S.pcb_component_id:void 0].filter(Boolean),pcb_port_ids:[...SI([y._pcbTrace]),"pcb_port_id"in S?S.pcb_port_id:void 0].filter(Boolean)})}let k=cf({x:y.x1,y:y.y1},{x:y.x2,y:y.y2},Kf(S))-y.thickness/2;if(k+Jf<g){let P=`overlap_${y.pcb_trace_id}_${C}`;if(_.has(P))continue;_.add(P),n.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${d(y.pcb_trace_id)} overlaps with ${S.type} "${d(Wo(S))}" ${k<0?"(accidental contact)":`(gap: ${k.toFixed(3)}mm)`}`,pcb_trace_id:y.pcb_trace_id,source_trace_id:"",pcb_trace_error_id:P,pcb_component_ids:["pcb_component_id"in S?S.pcb_component_id:void 0].filter(Boolean),center:RY(y,Kf(S)),pcb_port_ids:[...SI([y._pcbTrace]),"pcb_port_id"in S?S.pcb_port_id:void 0].filter(Boolean)})}}}return n}function FY(e){return e.area()>=0}function zY({center:e,size:t,rotationDeg:n=0}){let i=e.x,r=e.y,o=t.width/2,s=t.height/2,a=[new os(i-o,r-s),new os(i+o,r-s),new os(i+o,r+s),new os(i-o,r+s)],c=new Hf(a);if(n){let l=Sg(n,i,r),u=a.map(h=>{let d=yn(l,{x:h.x,y:h.y});return new os(d.x,d.y)});c=new Hf(u)}return FY(c)||c.reverse(),c}function Yvt({board:e}){if(e.outline&&e.outline.length>0){let t=e.outline.map(i=>new os(i.x,i.y)),n=new Hf(t);return FY(n)||n.reverse(),n}return e.center&&typeof e.width=="number"&&typeof e.height=="number"?zY({center:e.center,size:{width:e.width,height:e.height},rotationDeg:0}):null}function Xvt({circuitJson:e,component:t}){if(t.source_component_id){let n=e.find(i=>i.type==="source_component"&&i.source_component_id===t.source_component_id);if(n&&"name"in n&&n.name)return n.name}return so(e,t.pcb_component_id)||"Unknown"}function Vvt(e,t,n,i,r,o){let s=new os(n.x,n.y);if(!t.contains(s)){let g=t.distanceTo(s);return Array.isArray(g)?g[0]:Number(g)||0}let a=i/2,c=r/2,l=[{x:n.x-a,y:n.y-c},{x:n.x+a,y:n.y-c},{x:n.x+a,y:n.y+c},{x:n.x-a,y:n.y+c}],u=[];for(let g=0;g<4;g++){let x=(g+1)%4;u.push({x:(l[g].x+l[x].x)/2,y:(l[g].y+l[x].y)/2})}let h=Sg(o,n.x,n.y),d=g=>{let x=yn(h,g);return new os(x.x,x.y)},_=l.concat(u).map(d),y=0;for(let g of _)if(!t.contains(g)){let x=t.distanceTo(g),w=Array.isArray(x)?x[0]:Number(x)||0;w>y&&(y=w)}if(y>0)return y;try{let g=ZT.intersect(e,t),x=0;g?Array.isArray(g)?x=g.reduce((S,C)=>S+(typeof C.area=="function"?C.area():0),0):typeof g.area=="function"?x=g.area():x=0:x=0;let w=e.area();if(x>0&&x<w){let S=1-x/w,C=Math.abs(i),I=Math.abs(r);return Math.min(C,I)*S}else return .1}catch{return .1}}function DY(e){let t=e.find(o=>o.type==="pcb_board");if(!t)return[];let n=Yvt({board:t});if(!n)return[];let i=e.filter(o=>o.type==="pcb_component");if(i.length===0)return[];let r=[];for(let o of i){if(!o.center||typeof o.width!="number"||typeof o.height!="number"||o.width<=0||o.height<=0)continue;let s=zY({center:o.center,size:{width:o.width,height:o.height},rotationDeg:o.rotation||0});if(s.area()===0||n.contains(s))continue;let c=Vvt(s,n,o.center,o.width,o.height,o.rotation||0),l=Xvt({circuitJson:e,component:o}),u=Math.round(c*100)/100;r.push({type:"pcb_component_outside_board_error",error_type:"pcb_component_outside_board_error",pcb_component_outside_board_error_id:`pcb_component_outside_board_${o.pcb_component_id}`,message:`Component ${l} (${o.pcb_component_id}) extends outside board boundaries by ${u}mm`,pcb_component_id:o.pcb_component_id,pcb_board_id:t.pcb_board_id,component_center:o.center,component_bounds:{min_x:s.box.xmin,max_x:s.box.xmax,min_y:s.box.ymin,max_y:s.box.ymax},subcircuit_id:o.subcircuit_id,source_component_id:o.source_component_id})}return r}function Hvt(e,t){return Math.hypot(e.x-t.x,e.y-t.y)}function $Y(e,{connMap:t,minSpacing:n=Lvt}={}){let i=e.filter(s=>s.type==="pcb_via");if(i.length<2)return[];t??(t=si(e));let r=[],o=new Set;for(let s=0;s<i.length;s++)for(let a=s+1;a<i.length;a++){let c=i[s],l=i[a];if(!t.areIdsConnected(c.pcb_via_id,l.pcb_via_id))continue;let u=Hvt(c,l)-c.outer_diameter/2-l.outer_diameter/2;if(u+Jf>=n)continue;let h=[c.pcb_via_id,l.pcb_via_id].sort().join("_");o.has(h)||(o.add(h),r.push({type:"pcb_via_clearance_error",pcb_error_id:`same_net_vias_close_${h}`,message:`Vias ${so(e,c.pcb_via_id)} and ${so(e,l.pcb_via_id)} are too close together (gap: ${u.toFixed(3)}mm)`,error_type:"pcb_via_clearance_error",pcb_via_ids:[c.pcb_via_id,l.pcb_via_id],minimum_clearance:n,actual_clearance:u,pcb_center:{x:(c.x+l.x)/2,y:(c.y+l.y)/2}}))}return r}function Gvt(e,t){return Math.hypot(e.x-t.x,e.y-t.y)}function BY(e,{connMap:t,minSpacing:n=Fvt}={}){let i=e.filter(s=>s.type==="pcb_via");if(i.length<2)return[];t??(t=si(e));let r=[],o=new Set;for(let s=0;s<i.length;s++)for(let a=s+1;a<i.length;a++){let c=i[s],l=i[a];if(t.areIdsConnected(c.pcb_via_id,l.pcb_via_id))continue;let u=Gvt(c,l)-c.outer_diameter/2-l.outer_diameter/2;if(u+Jf>=n)continue;let h=[c.pcb_via_id,l.pcb_via_id].sort().join("_");o.has(h)||(o.add(h),r.push({type:"pcb_via_clearance_error",pcb_error_id:`different_net_vias_close_${h}`,message:`Vias ${so(e,c.pcb_via_id)} and ${so(e,l.pcb_via_id)} from different nets are too close together (gap: ${u.toFixed(3)}mm)`,error_type:"pcb_via_clearance_error",pcb_via_ids:[c.pcb_via_id,l.pcb_via_id],minimum_clearance:n,actual_clearance:u,pcb_center:{x:(c.x+l.x)/2,y:(c.y+l.y)/2}}))}return r}var Uvt=.2;function qvt(e){if(e.outline&&e.outline.length>0)return e.outline.map(t=>({x:t.x,y:t.y}));if(e.center&&typeof e.width=="number"&&typeof e.height=="number"){let t=e.center.x,n=e.center.y,i=e.width/2,r=e.height/2;return[{x:t-i,y:n-r},{x:t+i,y:n-r},{x:t+i,y:n+r},{x:t-i,y:n+r}]}return null}function jY(e,t={}){let n=[],i=t.margin??Uvt,r=e.find(a=>a.type==="pcb_board");if(!r)return n;let o=qvt(r);if(!o)return n;let s=Ze(e).pcb_trace.list();for(let a of s)if(!(a.route.length<2))for(let c=0;c<a.route.length-1;c++){let l=a.route[c],u=a.route[c+1];if(l.route_type!=="wire"||u.route_type!=="wire")continue;let h="width"in l?l.width:"width"in u?u.width:.1,d={x:l.x,y:l.y},_={x:u.x,y:u.y},y=1/0;for(let x=0;x<o.length;x++){let w=o[x],S=o[(x+1)%o.length],C=Vp(d,_,w,S);C<y&&(y=C)}let g=h/2+i;if(y<g){let x={type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:`trace_too_close_to_board_${a.pcb_trace_id}_segment_${c}`,message:`Trace too close to board edge (${y.toFixed(3)}mm < ${g.toFixed(3)}mm required, margin: ${i}mm)`,pcb_trace_id:a.pcb_trace_id,source_trace_id:a.source_trace_id||"",center:{x:(d.x+_.x)/2,y:(d.y+_.y)/2},pcb_component_ids:[],pcb_port_ids:[]};n.push(x)}}return n}function Wvt(e,t){let n=Gp([e]),i=Gp([t]);return Ja(n,i)}function YY(e){let t=[],n=si(e),i=Ze(e).pcb_smtpad.list(),r=Ze(e).pcb_plated_hole.list(),o=Ze(e).pcb_hole.list(),s=new Map;for(let c of i){let l=c.pcb_component_id||`standalone_pad_${Wo(c)}`;s.has(l)||s.set(l,{component_id:l,elements:[],bounds:{minX:0,minY:0,maxX:0,maxY:0}}),s.get(l).elements.push(c)}for(let c of r){let l=c.pcb_component_id||`standalone_plated_hole_${Wo(c)}`;s.has(l)||s.set(l,{component_id:l,elements:[],bounds:{minX:0,minY:0,maxX:0,maxY:0}}),s.get(l).elements.push(c)}for(let c of o){let l=`standalone_hole_${Wo(c)}`;s.set(l,{component_id:l,elements:[c],bounds:{minX:0,minY:0,maxX:0,maxY:0}})}for(let[c,l]of s)l.elements.length>0&&(l.bounds=Gp(l.elements));let a=Array.from(s.values());for(let c=0;c<a.length;c++)for(let l=c+1;l<a.length;l++){let u=a[c],h=a[l];if(Ja(u.bounds,h.bounds))for(let d of u.elements)for(let _ of h.elements){let y=Wo(d),g=Wo(_);if(!(d.type==="pcb_smtpad"&&_.type==="pcb_smtpad"&&n.areIdsConnected(y,g))&&Wvt(d,_)){let x={type:"pcb_footprint_overlap_error",pcb_error_id:`pcb_footprint_overlap_${y}_${g}`,error_type:"pcb_footprint_overlap_error",message:`PCB component ${d.type} "${y}" overlaps with ${_.type} "${g}"`};(d.type==="pcb_smtpad"||_.type==="pcb_smtpad")&&(x.pcb_smtpad_ids=[],d.type==="pcb_smtpad"&&x.pcb_smtpad_ids.push(y),_.type==="pcb_smtpad"&&x.pcb_smtpad_ids.push(g)),(d.type==="pcb_plated_hole"||_.type==="pcb_plated_hole")&&(x.pcb_plated_hole_ids=[],d.type==="pcb_plated_hole"&&x.pcb_plated_hole_ids.push(y),_.type==="pcb_plated_hole"&&x.pcb_plated_hole_ids.push(g)),(d.type==="pcb_hole"||_.type==="pcb_hole")&&(x.pcb_hole_ids=[],d.type==="pcb_hole"&&x.pcb_hole_ids.push(y),_.type==="pcb_hole"&&x.pcb_hole_ids.push(g)),t.push(x)}}}return t}var PI=[{value:1e12,symbol:"T"},{value:1e9,symbol:"G"},{value:1e6,symbol:"M"},{value:1e3,symbol:"k"},{value:1,symbol:""},{value:.001,symbol:"m"},{value:1e-6,symbol:"\xB5"},{value:1e-9,symbol:"n"},{value:1e-12,symbol:"p"}];function ti(e){if(e==null)return"";if(e===0)return"0";let t=Math.abs(e),n=PI.find(o=>{let s=t/o.value;return s>=1&&s<1e3})||PI[PI.length-1],r=(e/n.value).toPrecision(3);return r.includes(".")&&!/\.0+$/.test(r)&&(r=r.replace(/0+$/,"")),r=r.replace(/\.0+$/,""),`${r}${n.symbol}`}vt();vt();Z();lf();bi();Ds();vt();Ne();var ZH=Vt(vo(),1);var nM=Vt(Mn(),1),Eh=Vt(vo(),1),fte=Vt(vo(),1);var nu=Vt(Kl(),1);var KH=Vt(Kl(),1),JH=Vt(Kl(),1);var QH=Vt(Kl(),1);var tG=Vt(Kl(),1);var eG=Vt(Kl(),1),nG=Vt(vo(),1);var VPt=Object.defineProperty,HPt=(e,t)=>{for(var n in t)VPt(e,n,{get:t[n],enumerable:!0})},wV={};HPt(wV,{AnalogSimulation:()=>qH,Battery:()=>MH,Board:()=>ZV,Breakout:()=>bH,BreakoutPoint:()=>xH,CadAssembly:()=>zV,CadModel:()=>FV,Capacitor:()=>JV,Chip:()=>gx,Constraint:()=>cH,CopperPour:()=>IH,Crystal:()=>RH,Cutout:()=>mm,Diode:()=>tH,FabricationNoteDimension:()=>hH,FabricationNotePath:()=>uH,FabricationNoteRect:()=>lH,FabricationNoteText:()=>pH,Footprint:()=>RV,Fuse:()=>eH,Group:()=>iu,Hole:()=>fm,Inductor:()=>kH,Jumper:()=>nH,Keepout:()=>ux,Led:()=>rH,Mosfet:()=>LH,Net:()=>oM,NetLabel:()=>vH,NormalComponent:()=>On,Panel:()=>KV,PcbNoteDimension:()=>yH,PcbNoteLine:()=>dH,PcbNotePath:()=>_H,PcbNoteRect:()=>fH,PcbNoteText:()=>mH,PcbTrace:()=>cM,PinHeader:()=>CH,Pinout:()=>QV,PlatedHole:()=>kh,Port:()=>ji,Potentiometer:()=>NH,PowerSource:()=>oH,PrimitiveComponent:()=>xe,PushButton:()=>AH,Renderable:()=>iM,Resistor:()=>aH,Resonator:()=>EH,SchematicArc:()=>jH,SchematicBox:()=>XH,SchematicCell:()=>GH,SchematicCircle:()=>YH,SchematicLine:()=>$H,SchematicRect:()=>BH,SchematicRow:()=>HH,SchematicTable:()=>VH,SchematicText:()=>DH,SilkscreenCircle:()=>wH,SilkscreenLine:()=>PH,SilkscreenPath:()=>aM,SilkscreenRect:()=>SH,SilkscreenText:()=>fx,SmtPad:()=>dm,SolderJumper:()=>iH,Subcircuit:()=>gH,Switch:()=>FH,Symbol:()=>UH,TestPoint:()=>zH,Trace:()=>ko,TraceHint:()=>pM,Transistor:()=>OH,Via:()=>TH,VoltageProbe:()=>WH,VoltageSource:()=>sH});var GPt=(0,TV.default)("tscircuit:renderable"),ea=["ReactSubtreesRender","SourceNameDuplicateComponentRemoval","PcbFootprintStringRender","InitializePortsFromChildren","CreateNetsFromProps","AssignFallbackProps","CreateTracesFromProps","CreateTracesFromNetLabels","CreateTraceHintsFromProps","SourceGroupRender","AssignNameToUnnamedComponents","SourceRender","SourceParentAttachment","PortMatching","OptimizeSelectorCache","SourceTraceRender","SourceAddConnectivityMapKey","SourceDesignRuleChecks","SimulationRender","SchematicComponentRender","SchematicPortRender","SchematicPrimitiveRender","SchematicComponentSizeCalculation","SchematicLayout","SchematicTraceRender","SchematicReplaceNetLabelsWithSymbols","PcbComponentRender","PcbPrimitiveRender","PcbFootprintLayout","PcbPortRender","PcbPortAttachment","PcbComponentSizeCalculation","PcbComponentAnchorAlignment","PcbLayout","PcbBoardAutoSize","PcbTraceHintRender","PcbManualTraceRender","PcbTraceRender","PcbRouteNetIslands","PcbCopperPourRender","PcbDesignRuleChecks","SilkscreenOverlapAdjustment","CadModelRender","PartsEngineRender","SimulationSpiceEngineRender"],UPt={PcbFootprintLayout:["PcbFootprintStringRender"],PcbComponentSizeCalculation:["PcbFootprintStringRender"],PcbLayout:["PcbFootprintStringRender"],PcbBoardAutoSize:["PcbFootprintStringRender"],PcbTraceHintRender:["PcbFootprintStringRender"],PcbManualTraceRender:["PcbFootprintStringRender"],PcbCopperPourRender:["PcbFootprintStringRender","PcbTraceRender","PcbRouteNetIslands"],PcbTraceRender:["PcbFootprintStringRender"],PcbRouteNetIslands:["PcbFootprintStringRender"],PcbDesignRuleChecks:["PcbFootprintStringRender"],SilkscreenOverlapAdjustment:["PcbFootprintStringRender"],CadModelRender:["PcbFootprintStringRender"],PartsEngineRender:["PcbFootprintStringRender"],PcbComponentAnchorAlignment:["PcbFootprintStringRender"]},qPt=0,iM=class{constructor(e){M(this,"renderPhaseStates");M(this,"shouldBeRemoved",!1);M(this,"children");M(this,"isPcbPrimitive",!1);M(this,"isSchematicPrimitive",!1);M(this,"_renderId");M(this,"_currentRenderPhase",null);M(this,"_asyncEffects",[]);M(this,"parent",null);this._renderId=`${qPt++}`,this.children=[],this.renderPhaseStates={};for(let t of ea)this.renderPhaseStates[t]={initialized:!1,dirty:!1}}_markDirty(e){this.renderPhaseStates[e].dirty=!0;let t=ea.indexOf(e);for(let n=t+1;n<ea.length;n++)this.renderPhaseStates[ea[n]].dirty=!0;this.parent?._markDirty&&this.parent._markDirty(e)}_queueAsyncEffect(e,t){let n={promise:t(),phase:this._currentRenderPhase,effectName:e,complete:!1};this._asyncEffects.push(n),"root"in this&&this.root&&this.root.emit("asyncEffect:start",{effectName:e,componentDisplayName:this.getString(),phase:n.phase}),n.promise.then(()=>{n.complete=!0,"root"in this&&this.root&&this.root.emit("asyncEffect:end",{effectName:e,componentDisplayName:this.getString(),phase:n.phase})}).catch(i=>{console.error(`Async effect error in ${n.phase} "${e}":
|
|
242
|
-
${i.stack}`),n.complete=!0,"root"in this&&this.root&&this.root.emit("asyncEffect:end",{effectName:e,componentDisplayName:this.getString(),phase:n.phase,error:i.toString()})})}_emitRenderLifecycleEvent(e,t){GPt(`${e}:${t} ${this.getString()}`);let n=`renderable:renderLifecycle:${e}:${t}`,i={renderId:this._renderId,componentDisplayName:this.getString(),type:n};"root"in this&&this.root&&(this.root.emit(n,i),this.root.emit("renderable:renderLifecycle:anyEvent",{...i,type:n}))}getString(){return this.constructor.name}_hasIncompleteAsyncEffects(){return this._asyncEffects.some(e=>!e.complete)}_hasIncompleteAsyncEffectsInSubtreeForPhase(e){for(let t of this._asyncEffects)if(!t.complete&&t.phase===e)return!0;for(let t of this.children)if(t._hasIncompleteAsyncEffectsInSubtreeForPhase(e))return!0;return!1}getCurrentRenderPhase(){return this._currentRenderPhase}getRenderGraph(){return{id:this._renderId,currentPhase:this._currentRenderPhase,renderPhaseStates:this.renderPhaseStates,shouldBeRemoved:this.shouldBeRemoved,children:this.children.map(e=>e.getRenderGraph())}}runRenderCycle(){for(let e of ea)this.runRenderPhaseForChildren(e),this.runRenderPhase(e)}runRenderPhase(e){this._currentRenderPhase=e;let t=this.renderPhaseStates[e],n=t.initialized,i=t.dirty;if(!n&&this.shouldBeRemoved)return;if(this.shouldBeRemoved&&n){this._emitRenderLifecycleEvent(e,"start"),this?.[`remove${e}`]?.(),t.initialized=!1,t.dirty=!1,this._emitRenderLifecycleEvent(e,"end");return}let r=ea.indexOf(e)-1;if(r>=0){let s=ea[r];if(this._asyncEffects.filter(c=>c.phase===s).some(c=>!c.complete))return}let o=UPt[e]||[];for(let s of o)if(this._hasIncompleteAsyncEffectsInSubtreeForPhase(s))return;if(this._emitRenderLifecycleEvent(e,"start"),n){i&&(this?.[`update${e}`]?.(),t.dirty=!1),this._emitRenderLifecycleEvent(e,"end");return}t.dirty=!1,this?.[`doInitial${e}`]?.(),t.initialized=!0,this._emitRenderLifecycleEvent(e,"end")}runRenderPhaseForChildren(e){for(let t of this.children)t.runRenderPhaseForChildren(e),t.runRenderPhase(e)}renderError(e){throw typeof e=="string"?new Error(e):new Error(JSON.stringify(e,null,2))}},lx={},IV=e=>{let t=Object.fromEntries(Object.entries(e).map(([n,i])=>[n.toLowerCase(),i]));Object.assign(lx,e),Object.assign(lx,t)},WPt=class extends Error{constructor(e,t,n){let i,r=Object.keys(n).filter(c=>c!=="_errors"),o=[],s=t.pinLabels;if(s)for(let[c,l]of Object.entries(s)){let u=Array.isArray(l)?l:[l];for(let h of u)typeof h=="string"&&(h.startsWith(" ")||h.endsWith(" "))&&o.push(`pinLabels.${c} ("${h}" has leading or trailing spaces)`)}let a=r.map(c=>c==="pinLabels"&&o.length>0?o.join(", "):n[c]._errors[0]?`${c} (${n[c]._errors[0]})`:`${c} (${JSON.stringify(n[c])})`).join(", ");"name"in t?i=`Invalid props for ${e} "${t.name}": ${a}`:"footprint"in t&&typeof t.footprint=="string"?i=`Invalid props for ${e} (unnamed ${t.footprint} component): ${a}`:i=`Invalid props for ${e} (unnamed): ${a}`,super(i),this.componentName=e,this.originalProps=t,this.formattedError=n}};function jI(e,t){let n=t.match(/^#(\w+)/);if(n)return e.props.id===n[1];let i=t.match(/^\.(\w+)/);if(i)return e.isMatchingNameOrAlias(i[1]);let[r,...o]=t.split(/(?=[#.[])/);return r==="pin"&&(r="port"),r&&r!=="*"&&e.lowercaseComponentName!==r.toLowerCase()?!1:o.every(s=>{if(s.startsWith("#"))return e.props.id===s.slice(1);if(s.startsWith("."))return e.isMatchingNameOrAlias(s.slice(1));let a=s.match(/\[(\w+)=['"]?(.+?)['"]?\]/);if(!a)return!0;let[,c,l]=a;return e.props[c].toString()===l})}var rM={isTag:e=>!0,getParent:e=>e.parent,getChildren:e=>e.children,getName:e=>e.lowercaseComponentName,getAttributeValue:(e,t)=>{if(t==="class"&&"getNameAndAliases"in e)return e.getNameAndAliases().join(" ");if(t==="name"&&e._parsedProps?.name)return e._parsedProps.name;if(e._parsedProps&&t in e._parsedProps){let i=e._parsedProps[t];return typeof i=="string"?i:i!=null?String(i):null}if(t in e){let i=e[t];return typeof i=="string"?i:i!=null?String(i):null}let n=e._attributeLowerToCamelNameMap;if(n){let i=n[t];if(i&&i in e){let r=e[i];return typeof r=="string"?r:r!=null?String(r):null}}return null},hasAttrib:(e,t)=>{if(t==="class")return!!e._parsedProps?.name;if(e._parsedProps&&t in e._parsedProps||t in e)return!0;let n=e._attributeLowerToCamelNameMap;if(n){let i=n[t];if(i&&i in e)return!0}return!1},getSiblings:e=>e.parent?e.parent.children:[],prevElementSibling:e=>{if(!e.parent)return null;let t=e.parent.children,n=t.indexOf(e);return n>0?t[n-1]:null},getText:()=>"",removeSubsets:e=>e.filter((t,n)=>!e.some((i,r)=>n!==r&&i!==t&&i.getDescendants().includes(t))),existsOne:(e,t)=>t.some(e),findAll:(e,t)=>{let n=[],i=r=>{e(r)&&n.push(r);for(let o of r.children)i(o)};for(let r of t)i(r);return n},findOne:(e,t)=>{for(let n of t){if(e(n))return n;let i=n.children;if(i.length>0){let r=rM.findOne(e,i);if(r)return r}}return null},equals:(e,t)=>e._renderId===t._renderId,isHovered:e=>!1,isVisited:e=>!1,isActive:e=>!1},ZPt={...rM,getChildren:e=>e.children.filter(t=>!t.isSubcircuit)},KX={...rM,getChildren:e=>e.children.filter(t=>t.isSubcircuit)},JX=e=>{if(/net\.[^\s>]*\./.test(e))throw new Error('Net names cannot contain a period, try using "sel.net..." to autocomplete with conventional net names, e.g. V3_3');if(/net\.[^\s>]*[+-]/.test(e))throw new Error('Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P');if(/net\.[0-9]/.test(e)){let t=e.match(/net\.([^ >]+)/),n=t?t[1]:"";throw new Error(`Net name "${n}" cannot start with a number, try using a prefix like "VBUS1"`)}return e.replace(/ pin(?=[\d.])/g," port").replace(/ subcircuit\./g," group[isSubcircuit=true]").replace(/([^ ])\>([^ ])/g,"$1 > $2").replace(/(^|[ >])(?!pin\.)(?!port\.)(?!net\.)([A-Z][A-Za-z0-9_-]*)\.([A-Za-z0-9_-]+)/g,(t,n,i,r)=>{let o=/^\d+$/.test(r)?`pin${r}`:r;return`${n}.${i} > .${o}`}).trim()},YI={adapter:ZPt,cacheResults:!0},xe=class extends iM{constructor(t){super(t);M(this,"parent",null);M(this,"children");M(this,"childrenPendingRemoval");M(this,"props");M(this,"_parsedProps");M(this,"externallyAddedAliases");M(this,"isPrimitiveContainer",!1);M(this,"canHaveTextChildren",!1);M(this,"source_group_id",null);M(this,"source_component_id",null);M(this,"schematic_component_id",null);M(this,"pcb_component_id",null);M(this,"cad_component_id",null);M(this,"fallbackUnassignedName");M(this,"_cachedSelectAllQueries",new Map);M(this,"_cachedSelectOneQueries",new Map);this.children=[],this.childrenPendingRemoval=[],this.props=t??{},this.externallyAddedAliases=[];let i=("partial"in this.config.zodProps?this.config.zodProps.partial({name:!0}):this.config.zodProps).safeParse(t??{});if(i.success)this._parsedProps=i.data;else throw new WPt(this.lowercaseComponentName,this.props,i.error.format())}get config(){return{componentName:"",zodProps:p.object({}).passthrough()}}get componentName(){return this.config.componentName}getInheritedProperty(t){let n=this;for(;n;){if(n._parsedProps&&t in n._parsedProps)return n._parsedProps[t];n=n.parent}if(this.root?.platform&&t in this.root.platform)return this.root.platform[t]}get lowercaseComponentName(){return this.componentName.toLowerCase()}get isSubcircuit(){return!!this.props.subcircuit||this.lowercaseComponentName==="group"&&this?.parent?.isRoot}get isGroup(){return this.lowercaseComponentName==="group"}get name(){return this._parsedProps.name??this.fallbackUnassignedName}setProps(t){let n=this.config.zodProps.parse({...this.props,...t}),i=this.props;this.props=n,this._parsedProps=this.config.zodProps.parse(t),this.onPropsChange({oldProps:i,newProps:n,changedProps:Object.keys(t)}),this.parent?.onChildChanged?.(this)}_getPcbRotationBeforeLayout(){let{pcbRotation:t}=this.props;return typeof t=="string"?parseFloat(t):t??null}computePcbPropsTransform(){let{_parsedProps:t}=this,n=this._getPcbRotationBeforeLayout()??0;return Jn(vn(t.pcbX??0,t.pcbY??0),ja(n*Math.PI/180))}_computePcbGlobalTransformBeforeLayout(){let t=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if(t&&this.props.pcbX===void 0&&this.props.pcbY===void 0){let n=this._getPcbRotationBeforeLayout()??0;return Jn(this.parent?._computePcbGlobalTransformBeforeLayout()??Li(),Jn(vn(t.x,t.y),ja(n*Math.PI/180)))}if(this.isPcbPrimitive){let n=this.getPrimitiveContainer();if(n&&n._parsedProps.layer==="bottom")return Jn(this.parent?._computePcbGlobalTransformBeforeLayout()??Li(),N6(),this.computePcbPropsTransform())}return Jn(this.parent?._computePcbGlobalTransformBeforeLayout()??Li(),this.computePcbPropsTransform())}getPrimitiveContainer(){return this.isPrimitiveContainer?this:this.parent?.getPrimitiveContainer?.()??null}getParentNormalComponent(){let t=this.parent;for(;t;){if(t.isPrimitiveContainer&&t.doInitialPcbComponentRender)return t;t=t.parent}return null}_getPcbCircuitJsonBounds(){return{center:{x:0,y:0},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getPcbPrimitiveFlippedHelpers(){let t=this.getPrimitiveContainer(),n=t?t._parsedProps.layer==="bottom":!1;return{isFlipped:n,maybeFlipLayer:r=>n?r==="top"?"bottom":"top":r}}_setPositionFromLayout(t){throw new Error(`_setPositionFromLayout not implemented for ${this.componentName}`)}computeSchematicPropsTransform(){let{_parsedProps:t}=this;return Jn(vn(t.schX??0,t.schY??0))}computeSchematicGlobalTransform(){let t=this._getSchematicGlobalManualPlacementTransform(this);return t||Jn(this.parent?.computeSchematicGlobalTransform?.()??Li(),this.computeSchematicPropsTransform())}_getSchematicSymbolName(){let{_parsedProps:t}=this,n=this.config.schematicSymbolName,i={horizontal:0,pos_left:0,neg_right:0,pos_right:180,neg_left:180,pos_top:270,neg_bottom:90,vertical:270,pos_bottom:90,neg_top:90},r=t.schOrientation!==void 0?i[t.schOrientation]:t.schRotation;if(r===void 0&&(r=0),r=r%360,r<0&&(r+=360),t.schRotation!==void 0&&r%90!==0)throw new Error(`Schematic rotation ${t.schRotation} is not supported for ${this.componentName}`);let o=`${n}_horz`,s=`${n}_vert`,a=`${n}_up`,c=`${n}_down`,l=`${n}_left`,u=`${n}_right`;if(u in Qn&&r===0)return u;if(a in Qn&&r===90)return a;if(l in Qn&&r===180)return l;if(c in Qn&&r===270)return c;if(o in Qn&&(r===0||r===180))return o;if(s in Qn&&(r===90||r===270))return s;if(n in Qn)return n}_getSchematicSymbolNameOrThrow(){let t=this._getSchematicSymbolName();if(!t)throw new Error(`No schematic symbol found (given: "${this.config.schematicSymbolName}")`);return t}getSchematicSymbol(){let t=this._getSchematicSymbolName();return t?Qn[t]??null:null}_getPcbManualPlacementForComponent(t){if(!this.isSubcircuit)return null;let n=this.props.manualEdits;if(!n)return null;let i=n?.pcb_placements;if(!i)return null;for(let r of i)if(jI(t,r.selector)||t.props.name===r.selector)return Ae(this._computePcbGlobalTransformBeforeLayout(),r.center);return null}_getSchematicManualPlacementForComponent(t){if(!this.isSubcircuit)return null;let n=this.props.manualEdits;if(!n)return null;let i=n.schematic_placements;if(!i)return null;for(let r of i)if(jI(t,r.selector)||t.props.name===r.selector)return Ae(this.computeSchematicGlobalTransform(),r.center);return null}_getSchematicGlobalManualPlacementTransform(t){let n=this.getSubcircuit()?._parsedProps.manualEdits;if(!n)return null;for(let i of n.schematic_placements??[])if((jI(t,i.selector)||t.props.name===i.selector)&&i.relative_to==="group_center")return Jn(this.parent?._computePcbGlobalTransformBeforeLayout()??Li(),vn(i.center.x,i.center.y));return null}_getGlobalPcbPositionBeforeLayout(){return Ae(this._computePcbGlobalTransformBeforeLayout(),{x:0,y:0})}_getGlobalSchematicPositionBeforeLayout(){return Ae(this.computeSchematicGlobalTransform(),{x:0,y:0})}get root(){return this.parent?.root??null}onAddToParent(t){this.parent=t}onPropsChange(t){}onChildChanged(t){this.parent?.onChildChanged?.(t)}add(t){let n=t.__text;if(typeof n=="string"){if(this.canHaveTextChildren||n.trim()==="")return;throw new Error(`Invalid JSX Element: Expected a React component but received text "${n}"`)}if(Object.keys(t).length!==0){if(this.lowercaseComponentName==="board"&&t.lowercaseComponentName==="board")throw new Error("Nested boards are not supported");if(t.lowercaseComponentName==="panel")throw new Error("<panel> must be a root-level element");if(!t.onAddToParent)throw new Error(`Invalid JSX Element: Expected a React component but received "${JSON.stringify(t)}"`);t.onAddToParent(this),t.parent=this,this.children.push(t)}}addAll(t){for(let n of t)this.add(n)}remove(t){this.children=this.children.filter(n=>n!==t),this.childrenPendingRemoval.push(t),t.shouldBeRemoved=!0}getSubcircuitSelector(){let t=this.name,n=t?`${this.lowercaseComponentName}.${t}`:this.lowercaseComponentName;return!this.parent||this.parent.isSubcircuit?n:`${this.parent.getSubcircuitSelector()} > ${n}`}getFullPathSelector(){let t=this.name,n=t?`${this.lowercaseComponentName}.${t}`:this.lowercaseComponentName,i=this.parent?.getFullPathSelector?.();return i?`${i} > ${n}`:n}getNameAndAliases(){return[this.name,...this._parsedProps.portHints??[]].filter(Boolean)}isMatchingNameOrAlias(t){return this.getNameAndAliases().includes(t)}isMatchingAnyOf(t){return this.getNameAndAliases().some(n=>t.map(i=>i.toString()).includes(n))}getPcbSize(){throw new Error(`getPcbSize not implemented for ${this.componentName}`)}doesSelectorMatch(t){let n=[this.componentName,this.lowercaseComponentName],i=[this.name].filter(Boolean),r=t.trim().split(/\> /)[0],o=r[0];return r.length>1?!1:!!(t==="*"||t[0]==="#"&&t.slice(1)===this.props.id||t[0]==="."&&i.includes(t.slice(1))||/^[a-zA-Z0-9_]/.test(o)&&n.includes(o))}getSubcircuit(){if(this.isSubcircuit)return this;let t=this.parent?.getSubcircuit?.();if(!t)throw new Error("Component is not inside an opaque group (no board?)");return t}getGroup(){return this.isGroup?this:this.parent?.getGroup?.()??null}doInitialAssignNameToUnnamedComponents(){this._parsedProps.name||(this.fallbackUnassignedName=this.getSubcircuit().getNextAvailableName(this))}doInitialOptimizeSelectorCache(){if(!this.isSubcircuit)return;let t=this.selectAll("port");for(let n of t){let r=(n.getParentNormalComponent?.()??n.parent)?.getNameAndAliases(),o=n.getNameAndAliases();if(r)for(let s of r)for(let a of o){let c=[`.${s} > .${a}`,`.${s} .${a}`];for(let l of c){let u=this._cachedSelectAllQueries.get(l);u?u.push(n):this._cachedSelectAllQueries.set(l,[n])}}}for(let[n,i]of this._cachedSelectAllQueries.entries())i.length===1&&this._cachedSelectOneQueries.set(n,i[0])}selectAll(t){if(this._cachedSelectAllQueries.has(t))return this._cachedSelectAllQueries.get(t);let n=JX(t),i=Y5(n,this,YI);if(i.length>0)return this._cachedSelectAllQueries.set(t,i),i;let[r,...o]=n.split(" "),s=vg(r,this,{adapter:KX});if(!s)return[];let a=s.selectAll(o.join(" "));return this._cachedSelectAllQueries.set(t,a),a}selectOne(t,n){if(this._cachedSelectOneQueries.has(t))return this._cachedSelectOneQueries.get(t);let i=JX(t);n?.port&&(n.type="port");let r=null;if(n?.type&&(r=Y5(i,this,YI).find(l=>l.lowercaseComponentName===n.type)),r??(r=vg(i,this,YI)),r)return this._cachedSelectOneQueries.set(t,r),r;let[o,...s]=i.split(" "),a=vg(o,this,{adapter:KX});return a?(r=a.selectOne(s.join(" "),n),this._cachedSelectOneQueries.set(t,r),r):null}getAvailablePcbLayers(){if(this.isPcbPrimitive){let{maybeFlipLayer:t}=this._getPcbPrimitiveFlippedHelpers();return"layer"in this._parsedProps||this.componentName==="SmtPad"?[t(this._parsedProps.layer??"top")]:"layers"in this._parsedProps?this._parsedProps.layers:this.componentName==="PlatedHole"?this.root?._getBoard()?.allLayers??["top","bottom"]:[]}return[]}getDescendants(){let t=[];for(let n of this.children)t.push(n),t.push(...n.getDescendants());return t}getSelectableDescendants(){let t=[];for(let n of this.children)n.isSubcircuit?t.push(n):(t.push(n),t.push(...n.getSelectableDescendants()));return t}_getPinCount(){return 0}_getSchematicBoxDimensions(){return null}_getSchematicBoxComponentDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;let{_parsedProps:t}=this;return{schWidth:t.schWidth,schHeight:t.schHeight}}renderError(t){if(typeof t=="string")return super.renderError(t);switch(t.type){case"pcb_placement_error":this.root?.db.pcb_placement_error.insert(t);break;case"pcb_via_clearance_error":this.root?.db.pcb_via_clearance_error.insert(t);break;case"pcb_trace_error":this.root?.db.pcb_trace_error.insert(t);break;case"pcb_manual_edit_conflict_warning":this.root?.db.pcb_manual_edit_conflict_warning.insert(t);break;default:this.root?.db.pcb_placement_error.insert(t)}}getString(){let{lowercaseComponentName:t,_parsedProps:n,parent:i}=this;return n?.pinNumber!==void 0&&i?.props?.name&&n?.name?`<${t}#${this._renderId}(pin:${n.pinNumber} .${i?.props.name}>.${n.name}) />`:i?.props?.name&&n?.name?`<${t}#${this._renderId}(.${i?.props.name}>.${n?.name}) />`:n?.from&&n?.to?`<${t}#${this._renderId}(from:${n.from} to:${n?.to}) />`:n?.name?`<${t}#${this._renderId} name=".${n?.name}" />`:n?.portHints?`<${t}#${this._renderId}(${n.portHints.map(r=>`.${r}`).join(", ")}) />`:`<${t}#${this._renderId} />`}get[Symbol.toStringTag](){return this.getString()}[Symbol.for("nodejs.util.inspect.custom")](){return this.getString()}},KPt=class extends xe{constructor(e,t){super(e),this._parsedProps={...e,error:t,type:e.type||"unknown",component_name:e.name,error_type:"source_failed_to_create_component_error",message:t instanceof Error?t.message:String(t),pcbX:e.pcbX,pcbY:e.pcbY,schX:e.schX,schY:e.schY}}get config(){return{componentName:"ErrorPlaceholder",zodProps:p.object({}).passthrough()}}doInitialSourceRender(){if(this.root?.db){let e=this._getGlobalPcbPositionBeforeLayout(),t=this._getGlobalSchematicPositionBeforeLayout();this.root.db.source_failed_to_create_component_error.insert({component_name:this._parsedProps.component_name,error_type:"source_failed_to_create_component_error",message:`Could not create ${this._parsedProps.componentType??"component"}${this._parsedProps.name?` "${this._parsedProps.name}"`:""}. ${this._parsedProps.error?.formattedError?._errors?.join("; ")||this._parsedProps.message}`,pcb_center:e,schematic_center:t})}}};function JPt(e,t){return new KPt(e,t)}function QPt(e,t){let n=e;return n.__tsci={...t},e}var t3t={supportsMutation:!0,createInstance(e,t){let n=lx[e];if(!n)throw Object.keys(lx).length===0?new Error("No components registered in catalogue, did you forget to import lib/register-catalogue in your test file?"):new Error(`Unsupported component type "${e}". No element with this name is registered in the @tscircuit/core catalogue. Check for typos or see https://docs.tscircuit.com/category/built-in-elements for a list of valid components. To add your own component, see docs/CREATING_NEW_COMPONENTS.md`);try{return QPt(new n(t),{})}catch(i){return JPt({...t,componentType:e},i)}},createTextInstance(e){return{__text:e}},appendInitialChild(e,t){e.add(t)},appendChild(e,t){e.add(t)},appendChildToContainer(e,t){e.add(t)},finalizeInitialChildren(){return!1},prepareUpdate(){return null},shouldSetTextContent(){return!1},getRootHostContext(){return{}},getChildHostContext(){return{}},prepareForCommit(){return null},resetAfterCommit(){},commitMount(){},commitUpdate(){},removeChild(){},clearContainer(){},supportsPersistence:!1,getPublicInstance(e){return e},preparePortalMount(e){throw new Error("Function not implemented.")},scheduleTimeout(e,t){throw new Error("Function not implemented.")},cancelTimeout(e){throw new Error("Function not implemented.")},noTimeout:void 0,isPrimaryRenderer:!1,getInstanceFromNode(e){throw new Error("Function not implemented.")},beforeActiveInstanceBlur(){throw new Error("Function not implemented.")},afterActiveInstanceBlur(){throw new Error("Function not implemented.")},prepareScopeUpdate:(e,t)=>{throw new Error("Function not implemented.")},getInstanceFromScope:e=>{throw new Error("Function not implemented.")},detachDeletedInstance:e=>{throw new Error("Function not implemented.")},getCurrentEventPriority:()=>ax.DefaultEventPriority,getCurrentUpdatePriority:()=>ax.DefaultEventPriority,resolveUpdatePriority:()=>ax.DefaultEventPriority,setCurrentUpdatePriority:()=>{},maySuspendCommit:()=>!1,supportsHydration:!1},rx=(0,PV.default)(t3t),MV=e=>{let t={children:[],props:{name:"$root"},add(o){o.parent=this,this.children.push(o)},computePcbGlobalTransform(){return Li()}},n=[],i=rx.createContainer(t,0,null,!1,null,"tsci",o=>{console.log("Error in createContainer"),console.error(o),n.push(o)},null);if(rx.updateContainerSync(e,i,null,()=>{}),rx.flushSyncWork(),n.length>0)throw n[0];let r=rx.getPublicRootInstance(i);return r||t.children[0]},_m=(e,t)=>{if(typeof e=="number")return e;if(e.startsWith("pin"))return Number(e.slice(3));if(!t)throw new Error(`No pin labels provided and pin number or label is not a number: "${e}"`);for(let n in t)if((Array.isArray(t[n])?t[n]:[t[n]]).includes(e))return Number(n.replace("pin",""));throw new Error(`No pin labels provided and pin number or label is not a number: "${e}"`)},e3t=(e,t)=>{if(!e)return;let n={},i={};for(let[r,o]of Object.entries(e)){let s=_m(r,t);i[s]={...i[s],...o}}for(let[r,o]of Object.entries(i)){let s=`pin${r}`;n[s]={bottom_margin:o.bottomMargin,left_margin:o.leftMargin,right_margin:o.rightMargin,top_margin:o.topMargin}}return n},n3t=e=>{if(e){if("leftSide"in e||"rightSide"in e||"topSide"in e||"bottomSide"in e)return{left_side:e.leftSide,right_side:e.rightSide,top_side:e.topSide,bottom_side:e.bottomSide};if("leftPinCount"in e||"rightPinCount"in e||"topPinCount"in e||"bottomPinCount"in e)return{left_size:e.leftPinCount,right_size:e.rightPinCount,top_size:e.topPinCount,bottom_size:e.bottomPinCount};if("leftSize"in e||"rightSize"in e||"topSize"in e||"bottomSize"in e)return{left_size:e.leftSize,right_size:e.rightSize,top_size:e.topSize,bottom_size:e.bottomSize}}};function CV(e){let t=[];for(let n=0;n<e.length-1;n++)t.push([e[n],e[n+1]]);return t}var i3t=p.object({name:p.string().refine(e=>!/[+-]/.test(e),'Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P')}),oM=class extends xe{constructor(){super(...arguments);M(this,"source_net_id")}get config(){return{componentName:"Net",zodProps:i3t}}getPortSelector(){return`net.${this.props.name}`}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=n.name.startsWith("GND"),r=n.name.startsWith("V"),o=t.source_net.insert({name:n.name,member_source_group_ids:[],is_ground:i,is_power:r,is_positive_voltage_source:r});this.source_net_id=o.source_net_id}doInitialSourceParentAttachment(){let t=this.getSubcircuit();if(!t)return;let{db:n}=this.root;n.source_net.update(this.source_net_id,{subcircuit_id:t.subcircuit_id})}getAllConnectedPorts(){let t=this.getSubcircuit().selectAll("port"),n=[];for(let i of t){let r=i._getDirectlyConnectedTraces();for(let o of r)if(o._isExplicitlyConnectedToNet(this)){n.push(i);break}}return n}_getAllDirectlyConnectedTraces(){let t=this.getSubcircuit().selectAll("trace"),n=[];for(let i of t)i._isExplicitlyConnectedToNet(this)&&n.push(i);return n}doInitialPcbRouteNetIslands(){if(this.root?.pcbDisabled||this.getSubcircuit()._parsedProps.routingDisabled||this.getSubcircuit()._getAutorouterConfig().groupMode!=="sequential-trace")return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getAllDirectlyConnectedTraces().filter(s=>(s._portsRoutedOnPcb?.length??0)>0),r=[];for(let s of i){let a=s._portsRoutedOnPcb,c=r.find(l=>a.some(u=>l.ports.includes(u)));if(!c){r.push({ports:[...a],traces:[s]});continue}c.traces.push(s),c.ports.push(...a)}if(r.length===0)return;let o=CV(r);for(let[s,a]of o){let c=s.ports.map(w=>w._getGlobalPcbPositionBeforeLayout()),l=a.ports.map(w=>w._getGlobalPcbPositionBeforeLayout()),u=1/0,h=[-1,-1];for(let w=0;w<c.length;w++){let S=c[w];for(let C=0;C<l.length;C++){let I=l[C],k=Math.sqrt((S.x-I.x)**2+(S.y-I.y)**2);k<u&&(u=k,h=[w,C])}}let d=s.ports[h[0]],_=a.ports[h[1]],y=t.toArray().filter(w=>w.type==="pcb_smtpad"||w.type==="pcb_trace"||w.type==="pcb_plated_hole"||w.type==="pcb_hole"||w.type==="source_port"||w.type==="pcb_port"),{solution:g}=gF(y.concat([{type:"source_trace",source_trace_id:"__net_trace_tmp",connected_source_port_ids:[d.source_port_id,_.source_port_id]}])),x=g[0];if(!x){this.renderError({pcb_trace_error_id:"",pcb_trace_id:"__net_trace_tmp",pcb_component_ids:[d.pcb_component_id,_.pcb_component_id].filter(Boolean),pcb_port_ids:[d.pcb_port_id,_.pcb_port_id].filter(Boolean),type:"pcb_trace_error",error_type:"pcb_trace_error",message:`Failed to route net islands for "${this.getString()}"`,source_trace_id:"__net_trace_tmp"});return}t.pcb_trace.insert(x)}}renderError(t){if(typeof t=="string")return super.renderError(t);this.root?.db.pcb_trace_error.insert(t)}},sM=(e,t)=>{for(let n of t)if(typeof n=="string"&&n.startsWith("net.")){if(/net\.[^\s>]*\./.test(n))throw new Error('Net names cannot contain a period, try using "sel.net..." to autocomplete with conventional net names, e.g. V3_3');if(/net\.[^\s>]*[+-]/.test(n))throw new Error('Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P');if(/net\.[0-9]/.test(n)){let r=n.split("net.")[1];throw new Error(`Net name "${r}" cannot start with a number, try using a prefix like "VBUS1"`)}let i=e.getSubcircuit();if(!i.selectOne(n)){let r=new oM({name:n.split("net.")[1]});i.add(r)}}},dm=class extends xe{constructor(){super(...arguments);M(this,"pcb_smtpad_id",null);M(this,"matchedPort",null);M(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SmtPad",zodProps:VF}}getPcbSize(){let{_parsedProps:t}=this;if(t.shape==="circle")return{width:t.radius*2,height:t.radius*2};if(t.shape==="rect")return{width:t.width,height:t.height};if(t.shape==="rotated_rect"){let i=(t.ccwRotation??0)*Math.PI/180,r=Math.cos(i),o=Math.sin(i),s=Math.abs(t.width*r)+Math.abs(t.height*o),a=Math.abs(t.width*o)+Math.abs(t.height*r);return{width:s,height:a}}if(t.shape==="polygon"){let n=t.points,i=n.map(l=>l.x),r=n.map(l=>l.y),o=Math.min(...i),s=Math.max(...i),a=Math.min(...r),c=Math.max(...r);return{width:s-o,height:c-a}}if(t.shape==="pill")return{width:t.width,height:t.height};throw new Error(`getPcbSize for shape "${t.shape}" not implemented for ${this.componentName}`)}doInitialPortMatching(){let t=this.getPrimitiveContainer()?.selectAll("port");if(this.props.portHints){for(let n of t)if(n.isMatchingAnyOf(this.props.portHints)){this.matchedPort=n,n.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=n.coveredWithSolderMask??!1,r=!i;if(!n.portHints)return;let o=this.getSubcircuit(),s=this._getGlobalPcbPositionBeforeLayout(),l=(To(this._computePcbGlobalTransformBeforeLayout()).rotation.angle*180/Math.PI%360+360)%360,u=.01,h=Math.abs(l)<u||Math.abs(l-180)<u||Math.abs(l-360)<u,d=Math.abs(l-90)<u||Math.abs(l-270)<u,_=Math.abs(l-360)<u?0:l,y=_,{maybeFlipLayer:g,isFlipped:x}=this._getPcbPrimitiveFlippedHelpers();x&&(_=(360-_+360)%360);let w=null,S=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id;if(n.shape==="circle")w=t.pcb_smtpad.insert({pcb_component_id:S,pcb_port_id:this.matchedPort?.pcb_port_id,layer:g(n.layer??"top"),shape:"circle",radius:n.radius,port_hints:n.portHints.map(C=>C.toString()),is_covered_with_solder_mask:i,x:s.x,y:s.y,subcircuit_id:o?.subcircuit_id??void 0}),r&&t.pcb_solder_paste.insert({layer:w.layer,shape:"circle",radius:w.radius*.7,x:w.x,y:w.y,pcb_component_id:w.pcb_component_id,pcb_smtpad_id:w.pcb_smtpad_id,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});else if(n.shape==="rect")!h&&!d?w=t.pcb_smtpad.insert({pcb_component_id:S,pcb_port_id:this.matchedPort?.pcb_port_id,layer:g(n.layer??"top"),shape:"rotated_rect",width:n.width,height:n.height,corner_radius:n.cornerRadius??0,x:s.x,y:s.y,ccw_rotation:_,port_hints:n.portHints.map(I=>I.toString()),is_covered_with_solder_mask:i,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}):w=t.pcb_smtpad.insert({pcb_component_id:S,pcb_port_id:this.matchedPort?.pcb_port_id,layer:g(n.layer??"top"),shape:"rect",width:d?n.height:n.width,height:d?n.width:n.height,corner_radius:n.cornerRadius??0,port_hints:n.portHints.map(I=>I.toString()),is_covered_with_solder_mask:i,x:s.x,y:s.y,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),r&&(w.shape==="rect"?t.pcb_solder_paste.insert({layer:g(n.layer??"top"),shape:"rect",width:w.width*.7,height:w.height*.7,x:w.x,y:w.y,pcb_component_id:w.pcb_component_id,pcb_smtpad_id:w.pcb_smtpad_id,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}):w.shape==="rotated_rect"&&t.pcb_solder_paste.insert({layer:g(n.layer??"top"),shape:"rotated_rect",width:w.width*.7,height:w.height*.7,x:w.x,y:w.y,ccw_rotation:w.ccw_rotation,pcb_component_id:w.pcb_component_id,pcb_smtpad_id:w.pcb_smtpad_id,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}));else if(n.shape==="rotated_rect"){let C=n.ccwRotation??0,I=(y+C+360)%360,k=x?(360-I+360)%360:I;w=t.pcb_smtpad.insert({pcb_component_id:S,pcb_port_id:this.matchedPort?.pcb_port_id,layer:g(n.layer??"top"),shape:"rotated_rect",width:n.width,height:n.height,corner_radius:n.cornerRadius??0,x:s.x,y:s.y,ccw_rotation:k,port_hints:n.portHints.map(P=>P.toString()),is_covered_with_solder_mask:i,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),r&&t.pcb_solder_paste.insert({layer:g(n.layer??"top"),shape:"rotated_rect",width:w.width*.7,height:w.height*.7,x:s.x,y:s.y,ccw_rotation:k,pcb_component_id:S,pcb_smtpad_id:w.pcb_smtpad_id,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else n.shape==="polygon"?w=t.pcb_smtpad.insert({pcb_component_id:S,pcb_port_id:this.matchedPort?.pcb_port_id,layer:g(n.layer??"top"),shape:"polygon",points:n.points.map(C=>({x:C.x+s.x,y:C.y+s.y})),port_hints:n.portHints.map(C=>C.toString()),is_covered_with_solder_mask:i,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}):n.shape==="pill"&&(w=t.pcb_smtpad.insert({pcb_component_id:S,pcb_port_id:this.matchedPort?.pcb_port_id,layer:g(n.layer??"top"),shape:"pill",x:s.x,y:s.y,radius:n.radius,height:n.height,width:n.width,port_hints:n.portHints.map(C=>C.toString()),is_covered_with_solder_mask:i,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}));w&&(this.pcb_smtpad_id=w.pcb_smtpad_id)}doInitialPcbPortAttachment(){if(this.root?.pcbDisabled)return;let{db:t}=this.root;t.pcb_smtpad.update(this.pcb_smtpad_id,{pcb_port_id:this.matchedPort?.pcb_port_id})}_getPcbCircuitJsonBounds(){let{db:t}=this.root,n=t.pcb_smtpad.get(this.pcb_smtpad_id);if(n.shape==="rect")return{center:{x:n.x,y:n.y},bounds:{left:n.x-n.width/2,top:n.y+n.height/2,right:n.x+n.width/2,bottom:n.y-n.height/2},width:n.width,height:n.height};if(n.shape==="rotated_rect"){let i=n.ccw_rotation*Math.PI/180,r=Math.cos(i),o=Math.sin(i),s=n.width/2,a=n.height/2,c=Math.abs(s*r)+Math.abs(a*o),l=Math.abs(s*o)+Math.abs(a*r);return{center:{x:n.x,y:n.y},bounds:{left:n.x-c,right:n.x+c,top:n.y-l,bottom:n.y+l},width:c*2,height:l*2}}if(n.shape==="circle")return{center:{x:n.x,y:n.y},bounds:{left:n.x-n.radius,top:n.y-n.radius,right:n.x+n.radius,bottom:n.y+n.radius},width:n.radius*2,height:n.radius*2};if(n.shape==="polygon"){let i=n.points,r=i.map(u=>u.x),o=i.map(u=>u.y),s=Math.min(...r),a=Math.max(...r),c=Math.min(...o),l=Math.max(...o);return{center:{x:(s+a)/2,y:(c+l)/2},bounds:{left:s,top:l,right:a,bottom:c},width:a-s,height:l-c}}if(n.shape==="pill"){let i=n.width/2,r=n.height/2;return{center:{x:n.x,y:n.y},bounds:{left:n.x-i,top:n.y-r,right:n.x+i,bottom:n.y+r},width:n.width,height:n.height}}throw new Error(`circuitJson bounds calculation not implemented for shape "${n.shape}"`)}_setPositionFromLayout(t){let{db:n}=this.root;n.pcb_smtpad.update(this.pcb_smtpad_id,{x:t.x,y:t.y});let i=n.pcb_solder_paste.list().find(r=>r.pcb_smtpad_id===this.pcb_smtpad_id);i&&n.pcb_solder_paste.update(i.pcb_solder_paste_id,{x:t.x,y:t.y}),this.matchedPort?._setPositionFromLayout(t)}},aM=class extends xe{constructor(){super(...arguments);M(this,"pcb_silkscreen_path_id",null);M(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenPath",zodProps:Nz}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(n.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenPath. Must be "top" or "bottom".`);let o=this._computePcbGlobalTransformBeforeLayout(),s=this.getSubcircuit(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,c=t.pcb_silkscreen_path.insert({pcb_component_id:a,layer:r,route:n.route.map(l=>{let u=Ae(o,{x:l.x,y:l.y});return{...l,x:u.x,y:u.y}}),stroke_width:n.strokeWidth??.1,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_path_id=c.pcb_silkscreen_path_id}_setPositionFromLayout(t){let{db:n}=this.root,{_parsedProps:i}=this,r=n.pcb_silkscreen_path.get(this.pcb_silkscreen_path_id);if(!r)return;let o=0,s=0;for(let u of r.route)o+=u.x,s+=u.y;o/=r.route.length,s/=r.route.length;let a=t.x-o,c=t.y-s,l=r.route.map(u=>({...u,x:u.x+a,y:u.y+c}));n.pcb_silkscreen_path.update(this.pcb_silkscreen_path_id,{route:l})}getPcbSize(){let{_parsedProps:t}=this;if(!t.route||t.route.length===0)return{width:0,height:0};let n=1/0,i=-1/0,r=1/0,o=-1/0;for(let s of t.route)n=Math.min(n,s.x),i=Math.max(i,s.x),r=Math.min(r,s.y),o=Math.max(o,s.y);return{width:i-n,height:o-r}}},r3t=p.object({route:p.array(p_),source_trace_id:p.string().optional()}),cM=class extends xe{constructor(){super(...arguments);M(this,"pcb_trace_id",null);M(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbTrace",zodProps:r3t}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getPrimitiveContainer(),r=this.getSubcircuit(),{maybeFlipLayer:o}=this._getPcbPrimitiveFlippedHelpers(),s=this._computePcbGlobalTransformBeforeLayout(),a=n.route.map(l=>{let{x:u,y:h,...d}=l,_=Ae(s,{x:u,y:h});return l.route_type==="wire"&&l.layer?{..._,...d,layer:o(l.layer)}:{..._,...d}}),c=t.pcb_trace.insert({pcb_component_id:i.pcb_component_id,source_trace_id:n.source_trace_id,route:a,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_trace_id=c.pcb_trace_id}getPcbSize(){let{_parsedProps:t}=this;if(!t.route||t.route.length===0)return{width:0,height:0};let n=1/0,i=-1/0,r=1/0,o=-1/0;for(let s of t.route)n=Math.min(n,s.x),i=Math.max(i,s.x),r=Math.min(r,s.y),o=Math.max(o,s.y),s.route_type==="wire"&&(n=Math.min(n,s.x-s.width/2),i=Math.max(i,s.x+s.width/2),r=Math.min(r,s.y-s.width/2),o=Math.max(o,s.y+s.width/2));return n===1/0||i===-1/0||r===1/0||o===-1/0?{width:0,height:0}:{width:i-n,height:o-r}}},kh=class extends xe{constructor(){super(...arguments);M(this,"pcb_plated_hole_id",null);M(this,"matchedPort",null);M(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PlatedHole",zodProps:OF}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){let{_parsedProps:t}=this;if(t.shape==="circle")return{width:t.outerDiameter,height:t.outerDiameter};if(t.shape==="oval"||t.shape==="pill")return{width:t.outerWidth,height:t.outerHeight};if(t.shape==="circular_hole_with_rect_pad")return{width:t.rectPadWidth,height:t.rectPadHeight};if(t.shape==="pill_hole_with_rect_pad")return{width:t.rectPadWidth,height:t.rectPadHeight};throw new Error(`getPcbSize for shape "${t.shape}" not implemented for ${this.componentName}`)}_getPcbCircuitJsonBounds(){let{db:t}=this.root,n=t.pcb_plated_hole.get(this.pcb_plated_hole_id),i=this.getPcbSize();return{center:{x:n.x,y:n.y},bounds:{left:n.x-i.width/2,top:n.y+i.height/2,right:n.x+i.width/2,bottom:n.y-i.height/2},width:i.width,height:i.height}}_setPositionFromLayout(t){let{db:n}=this.root;n.pcb_plated_hole.update(this.pcb_plated_hole_id,{x:t.x,y:t.y}),this.matchedPort?._setPositionFromLayout(t)}doInitialPortMatching(){let t=this.getPrimitiveContainer()?.selectAll("port");if(this.props.portHints){for(let n of t)if(n.isMatchingAnyOf(this.props.portHints)){this.matchedPort=n,n.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalPcbPositionBeforeLayout(),r=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,o=this.getSubcircuit();if(n.shape==="circle"){let s=t.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,outer_diameter:n.outerDiameter,hole_diameter:n.holeDiameter,shape:"circle",port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=s.pcb_plated_hole_id,t.pcb_solder_paste.insert({layer:"top",shape:"circle",radius:n.outerDiameter/2,x:i.x,y:i.y,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),t.pcb_solder_paste.insert({layer:"bottom",shape:"circle",radius:n.outerDiameter/2,x:i.x,y:i.y,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(n.shape==="pill"&&n.rectPad){let s=t.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,outer_width:n.outerWidth,outer_height:n.outerHeight,hole_width:n.holeWidth,hole_height:n.holeHeight,shape:"rotated_pill_hole_with_rect_pad",type:"pcb_plated_hole",port_hints:this.getNameAndAliases(),pcb_plated_hole_id:this.pcb_plated_hole_id,x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,hole_shape:"rotated_pill",pad_shape:"rect",hole_ccw_rotation:n.pcbRotation??0,rect_ccw_rotation:n.pcbRotation??0,rect_pad_width:n.outerWidth,rect_pad_height:n.outerHeight,hole_offset_x:n.holeOffsetX,hole_offset_y:n.holeOffsetY});this.pcb_plated_hole_id=s.pcb_plated_hole_id}else if(n.shape==="pill"||n.shape==="oval"){let s=t.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,outer_width:n.outerWidth,outer_height:n.outerHeight,hole_width:n.holeWidth,hole_height:n.holeHeight,shape:n.shape,port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,ccw_rotation:n.pcbRotation??0});this.pcb_plated_hole_id=s.pcb_plated_hole_id,t.pcb_solder_paste.insert({layer:"top",shape:n.shape,width:n.outerWidth,height:n.outerHeight,x:i.x,y:i.y,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),t.pcb_solder_paste.insert({layer:"bottom",shape:n.shape,width:n.outerWidth,height:n.outerHeight,x:i.x,y:i.y,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(n.shape==="circular_hole_with_rect_pad"){let s=t.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,hole_diameter:n.holeDiameter,rect_pad_width:n.rectPadWidth,rect_pad_height:n.rectPadHeight,shape:"circular_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,hole_offset_x:n.holeOffsetX,hole_offset_y:n.holeOffsetY,rect_border_radius:n.rectBorderRadius??0});this.pcb_plated_hole_id=s.pcb_plated_hole_id}else if(n.shape==="pill_hole_with_rect_pad"){let s=t.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,hole_width:n.holeWidth,hole_height:n.holeHeight,rect_pad_width:n.rectPadWidth,rect_pad_height:n.rectPadHeight,hole_offset_x:n.holeOffsetX,hole_offset_y:n.holeOffsetY,shape:"pill_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=s.pcb_plated_hole_id}}doInitialPcbPortAttachment(){if(this.root?.pcbDisabled)return;let{db:t}=this.root;t.pcb_plated_hole.update(this.pcb_plated_hole_id,{pcb_port_id:this.matchedPort?.pcb_port_id})}},ux=class extends xe{constructor(){super(...arguments);M(this,"pcb_keepout_id",null);M(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Keepout",zodProps:mz}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let t=this.getSubcircuit(),{db:n}=this.root,{_parsedProps:i}=this,r=this._getGlobalPcbPositionBeforeLayout(),o=To(this._computePcbGlobalTransformBeforeLayout()),s=Math.abs(o.rotation.angle*(180/Math.PI)-90)%180<.01,a=null;i.shape==="circle"?a=n.pcb_keepout.insert({layers:["top"],shape:"circle",radius:i.radius,center:{x:r.x,y:r.y},subcircuit_id:t?.subcircuit_id??void 0,pcb_group_id:t?.getGroup()?.pcb_group_id??void 0}):i.shape==="rect"&&(a=n.pcb_keepout.insert({layers:["top"],shape:"rect",...s?{width:i.height,height:i.width}:{width:i.width,height:i.height},center:{x:r.x,y:r.y},subcircuit_id:t?.subcircuit_id??void 0,pcb_group_id:t?.getGroup()?.pcb_group_id??void 0})),a&&(this.pcb_keepout_id=a.pcb_keepout_id)}},fm=class extends xe{constructor(){super(...arguments);M(this,"pcb_hole_id",null);M(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Hole",zodProps:HF}}getPcbSize(){let{_parsedProps:t}=this,n=t.shape==="pill";return{width:n?t.width:t.diameter,height:n?t.height:t.diameter}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit(),r=this._getGlobalPcbPositionBeforeLayout();if(n.shape==="pill")if(n.pcbRotation&&n.pcbRotation!==0){let o=t.pcb_hole.insert({type:"pcb_hole",hole_shape:"rotated_pill",hole_width:n.width,hole_height:n.height,x:r.x,y:r.y,ccw_rotation:n.pcbRotation,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:i?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=o.pcb_hole_id}else{let o=t.pcb_hole.insert({type:"pcb_hole",hole_shape:"pill",hole_width:n.width,hole_height:n.height,x:r.x,y:r.y,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:i?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=o.pcb_hole_id}else{let o=t.pcb_hole.insert({hole_shape:"circle",hole_diameter:n.diameter,x:r.x,y:r.y,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:i?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=o.pcb_hole_id}}_getPcbCircuitJsonBounds(){let{db:t}=this.root,n=t.pcb_hole.get(this.pcb_hole_id),i=this.getPcbSize();return{center:{x:n.x,y:n.y},bounds:{left:n.x-i.width/2,top:n.y-i.height/2,right:n.x+i.width/2,bottom:n.y+i.height/2},width:i.width,height:i.height}}_setPositionFromLayout(t){let{db:n}=this.root;n.pcb_hole.update(this.pcb_hole_id,{x:t.x,y:t.y})}},fx=class extends xe{constructor(){super(...arguments);M(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenText",zodProps:kz}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getPrimitiveContainer(),r=this._getGlobalPcbPositionBeforeLayout(),{maybeFlipLayer:o,isFlipped:s}=this._getPcbPrimitiveFlippedHelpers(),a=this.getSubcircuit(),c=0;if(n.pcbRotation!==void 0&&n.pcbRotation!==0)c=n.pcbRotation;else{let h=this._computePcbGlobalTransformBeforeLayout();c=To(h).rotation.angle*180/Math.PI}s&&(c=(c+180)%360);let l=new Set(n.layers);n.layer&&l.add(n.layer);let u=l.size>0?Array.from(l):["top"];for(let h of u)t.pcb_silkscreen_text.insert({anchor_alignment:n.anchorAlignment,anchor_position:{x:r.x,y:r.y},font:n.font??"tscircuit2024",font_size:n.fontSize??1,layer:o(h),text:n.text??"",ccw_rotation:c,pcb_component_id:i.pcb_component_id,subcircuit_id:a?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}getPcbSize(){let{_parsedProps:t}=this,n=t.fontSize??1,r=(t.text??"").length*n,o=n;return{width:r*n,height:o*n}}},mm=class extends xe{constructor(){super(...arguments);M(this,"pcb_cutout_id",null);M(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Cutout",zodProps:XF}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit(),r=this.getGroup()?.pcb_group_id??void 0,o=this._getGlobalPcbPositionBeforeLayout(),a=this.getPrimitiveContainer()?._parsedProps.pcbRotation??0,c;if(n.shape==="rect"){let l=typeof a=="string"?parseInt(a.replace("deg",""),10):a,u=Math.abs(l%180)===90,h={shape:"rect",center:o,width:u?n.height:n.width,height:u?n.width:n.height,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:r};c=t.pcb_cutout.insert(h)}else if(n.shape==="circle"){let l={shape:"circle",center:o,radius:n.radius,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:r};c=t.pcb_cutout.insert(l)}else if(n.shape==="polygon"){let l=this._computePcbGlobalTransformBeforeLayout(),h={shape:"polygon",points:n.points.map(d=>Ae(l,d)),subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:r};c=t.pcb_cutout.insert(h)}c&&(this.pcb_cutout_id=c.pcb_cutout_id)}getPcbSize(){let{_parsedProps:t}=this;if(t.shape==="rect")return{width:t.width,height:t.height};if(t.shape==="circle")return{width:t.radius*2,height:t.radius*2};if(t.shape==="polygon"){if(t.points.length===0)return{width:0,height:0};let n=1/0,i=-1/0,r=1/0,o=-1/0;for(let s of t.points)n=Math.min(n,s.x),i=Math.max(i,s.x),r=Math.min(r,s.y),o=Math.max(o,s.y);return{width:i-n,height:o-r}}return{width:0,height:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_cutout_id)return super._getPcbCircuitJsonBounds();let{db:t}=this.root,n=t.pcb_cutout.get(this.pcb_cutout_id);if(!n)return super._getPcbCircuitJsonBounds();if(n.shape==="rect")return{center:n.center,bounds:{left:n.center.x-n.width/2,top:n.center.y+n.height/2,right:n.center.x+n.width/2,bottom:n.center.y-n.height/2},width:n.width,height:n.height};if(n.shape==="circle")return{center:n.center,bounds:{left:n.center.x-n.radius,top:n.center.y+n.radius,right:n.center.x+n.radius,bottom:n.center.y-n.radius},width:n.radius*2,height:n.radius*2};if(n.shape==="polygon"){if(n.points.length===0)return super._getPcbCircuitJsonBounds();let i=1/0,r=-1/0,o=1/0,s=-1/0;for(let a of n.points)i=Math.min(i,a.x),r=Math.max(r,a.x),o=Math.min(o,a.y),s=Math.max(s,a.y);return{center:{x:(i+r)/2,y:(o+s)/2},bounds:{left:i,top:s,right:r,bottom:o},width:r-i,height:s-o}}return super._getPcbCircuitJsonBounds()}_setPositionFromLayout(t){if(!this.pcb_cutout_id)return;let{db:n}=this.root,i=n.pcb_cutout.get(this.pcb_cutout_id);if(i){if(i.shape==="rect"||i.shape==="circle")n.pcb_cutout.update(this.pcb_cutout_id,{...i,center:t});else if(i.shape==="polygon"){let r=this._getPcbCircuitJsonBounds().center,o=t.x-r.x,s=t.y-r.y,a=i.points.map(c=>({x:c.x+o,y:c.y+s}));n.pcb_cutout.update(this.pcb_cutout_id,{...i,points:a})}}}},o3t=({elm:e,pinLabels:t,layer:n,readableRotation:i,anchorAlignment:r})=>{let o=e.text.replace(/[{}]/g,"").toLowerCase(),s=o;if(Array.isArray(t)){let a=parseInt(o.replace(/[^\d]/g,""),10)-1;s=String(t[a]??o)}else typeof t=="object"&&(s=String(t[o]??o));return new fx({anchorAlignment:r||"center",text:s??o,layer:n||"top",fontSize:e.font_size+.2,pcbX:isNaN(e.anchor_position.x)?0:e.anchor_position.x,pcbY:e.anchor_position.y,pcbRotation:i??0})},s3t=(e,t)=>{let n=parseInt(e||"0",10),i;return t!=null?i=t-n:i=n,(i%360+360)%360},lm=({componentName:e,componentRotation:t,footprint:n,pinLabels:i,pcbPinLabels:r},o)=>{let s=[];for(let a of o)if(a.type==="pcb_smtpad"&&a.shape==="rect")s.push(new dm({pcbX:a.x,pcbY:a.y,layer:a.layer,shape:"rect",height:a.height,width:a.width,portHints:a.port_hints,rectBorderRadius:a.rect_border_radius}));else if(a.type==="pcb_smtpad"&&a.shape==="circle")s.push(new dm({pcbX:a.x,pcbY:a.y,layer:a.layer,shape:"circle",radius:a.radius,portHints:a.port_hints}));else if(a.type==="pcb_smtpad"&&a.shape==="pill")s.push(new dm({shape:"pill",height:a.height,width:a.width,radius:a.radius,portHints:a.port_hints,pcbX:a.x,pcbY:a.y,layer:a.layer}));else if(a.type==="pcb_silkscreen_path")s.push(new aM({layer:a.layer,route:a.route,strokeWidth:a.stroke_width}));else if(a.type==="pcb_plated_hole")a.shape==="circle"?s.push(new kh({pcbX:a.x,pcbY:a.y,shape:"circle",holeDiameter:a.hole_diameter,outerDiameter:a.outer_diameter,portHints:a.port_hints})):a.shape==="circular_hole_with_rect_pad"?s.push(new kh({pcbX:a.x,pcbY:a.y,shape:"circular_hole_with_rect_pad",holeDiameter:a.hole_diameter,rectPadHeight:a.rect_pad_height,rectPadWidth:a.rect_pad_width,portHints:a.port_hints,rectBorderRadius:a.rect_border_radius,holeOffsetX:a.hole_offset_x,holeOffsetY:a.hole_offset_y})):a.shape==="pill"||a.shape==="oval"?s.push(new kh({pcbX:a.x,pcbY:a.y,shape:a.shape,holeWidth:a.hole_width,holeHeight:a.hole_height,outerWidth:a.outer_width,outerHeight:a.outer_height,portHints:a.port_hints})):a.shape==="pill_hole_with_rect_pad"&&s.push(new kh({pcbX:a.x,pcbY:a.y,shape:"pill_hole_with_rect_pad",holeShape:"pill",padShape:"rect",holeWidth:a.hole_width,holeHeight:a.hole_height,rectPadWidth:a.rect_pad_width,rectPadHeight:a.rect_pad_height,portHints:a.port_hints,holeOffsetX:a.hole_offset_x,holeOffsetY:a.hole_offset_y}));else if(a.type==="pcb_keepout"&&a.shape==="circle")s.push(new ux({pcbX:a.center.x,pcbY:a.center.y,shape:"circle",radius:a.radius}));else if(a.type==="pcb_keepout"&&a.shape==="rect")s.push(new ux({pcbX:a.center.x,pcbY:a.center.y,shape:"rect",width:a.width,height:a.height}));else if(a.type==="pcb_hole"&&a.hole_shape==="circle")s.push(new fm({pcbX:a.x,pcbY:a.y,diameter:a.hole_diameter}));else if(a.type==="pcb_hole"&&a.hole_shape==="pill")s.push(new fm({pcbX:a.x,pcbY:a.y,shape:"pill",width:a.hole_width,height:a.hole_height}));else if(a.type==="pcb_hole"&&a.hole_shape==="rotated_pill")s.push(new fm({pcbX:a.x,pcbY:a.y,shape:"pill",width:a.hole_width,height:a.hole_height,pcbRotation:a.ccw_rotation}));else if(a.type==="pcb_cutout")a.shape==="rect"?s.push(new mm({pcbX:a.center.x,pcbY:a.center.y,shape:"rect",width:a.width,height:a.height})):a.shape==="circle"?s.push(new mm({pcbX:a.center.x,pcbY:a.center.y,shape:"circle",radius:a.radius})):a.shape==="polygon"&&s.push(new mm({shape:"polygon",points:a.points}));else if(a.type==="pcb_silkscreen_text"){let c=s3t(t,a.ccw_rotation);n.includes("pinrow")&&a.text.includes("PIN")?s.push(o3t({elm:a,pinLabels:r??i,layer:a.layer,readableRotation:c,anchorAlignment:a.anchor_alignment})):s.push(new fx({anchorAlignment:a.anchor_alignment||"center",text:e,fontSize:a.font_size+.2,pcbX:Number.isNaN(a.anchor_position.x)?0:a.anchor_position.x,pcbY:a.anchor_position.y,pcbRotation:c??0}))}else a.type==="pcb_trace"&&s.push(new cM({route:a.route}));return s};function mx(e){let t=1/0,n=1/0,i=-1/0,r=-1/0,o=!1;for(let c of e)if(c.isPcbPrimitive&&!c.componentName.startsWith("Silkscreen")){let{x:l,y:u}=c._getGlobalPcbPositionBeforeLayout(),{width:h,height:d}=c.getPcbSize();t=Math.min(t,l-h/2),n=Math.min(n,u-d/2),i=Math.max(i,l+h/2),r=Math.max(r,u+d/2),o=!0}else if(c.children.length>0){let l=mx(c.children);(l.width>0||l.height>0)&&(t=Math.min(t,l.minX),n=Math.min(n,l.minY),i=Math.max(i,l.maxX),r=Math.max(r,l.maxY),o=!0)}if(!o)return{minX:0,minY:0,maxX:0,maxY:0,width:0,height:0};let s=i-t,a=r-n;return s<0&&(s=0),a<0&&(a=0),{minX:t,minY:n,maxX:i,maxY:r,width:s,height:a}}function QX(e){let t=e%360;return t<0?t+360:t}function a3t(e,t,n,i){return i==="counterclockwise"?n>=t?e>=t&&e<=n:e>=t||e<=n:n<=t?e<=t&&e>=n:e<=t||e>=n}function c3t(e){let t=e.center,n=e.radius,i=e.start_angle_degrees,r=e.end_angle_degrees,o=e.direction??"counterclockwise";if(!t||typeof t.x!="number"||typeof t.y!="number"||typeof n!="number"||typeof i!="number"||typeof r!="number")return null;let s=QX(i),a=QX(r),c=new Set([s,a]),l=[0,90,180,270];for(let y of l)a3t(y,s,a,o)&&c.add(y);let u=1/0,h=1/0,d=-1/0,_=-1/0;for(let y of c){let g=y*Math.PI/180,x=t.x+n*Math.cos(g),w=t.y+n*Math.sin(g);u=Math.min(u,x),d=Math.max(d,x),h=Math.min(h,w),_=Math.max(_,w)}return!Number.isFinite(u)||!Number.isFinite(h)?null:{minX:u,maxX:d,minY:h,maxY:_}}function EV(e){let t=1/0,n=1/0,i=-1/0,r=-1/0;for(let o of e){let s,a,c,l;if(o.type==="schematic_component")s=o.center?.x,a=o.center?.y,c=o.size?.width,l=o.size?.height;else if(o.type==="schematic_box")s=o.x,a=o.y,c=o.width,l=o.height;else if(o.type==="schematic_port")s=o.center?.x,a=o.center?.y,c=.2,l=.2;else if(o.type==="schematic_text")s=o.position?.x,a=o.position?.y,c=(o.text?.length??0)*.1,l=.2;else if(o.type==="schematic_line"){let u=o.x1??0,h=o.y1??0,d=o.x2??0,_=o.y2??0;s=(u+d)/2,a=(h+_)/2,c=Math.abs(d-u),l=Math.abs(_-h)}else if(o.type==="schematic_rect")s=o.center?.x,a=o.center?.y,c=o.width,l=o.height;else if(o.type==="schematic_circle"){s=o.center?.x,a=o.center?.y;let u=o.radius;typeof u=="number"&&(c=u*2,l=u*2)}else if(o.type==="schematic_arc"){let u=c3t(o);u&&(t=Math.min(t,u.minX),i=Math.max(i,u.maxX),n=Math.min(n,u.minY),r=Math.max(r,u.maxY));continue}typeof s=="number"&&typeof a=="number"&&typeof c=="number"&&typeof l=="number"&&(t=Math.min(t,s-c/2),i=Math.max(i,s+c/2),n=Math.min(n,a-l/2),r=Math.max(r,a+l/2))}return{minX:t,maxX:i,minY:n,maxY:r}}function l3t(e,t){let n=t.x-e.x,i=t.y-e.y;return Math.abs(n)>Math.abs(i)?n>=0?"right":"left":i>=0?"up":"down"}var tV=e=>{if(e.length<=1)return!0;let t=e.map(o=>{let s=o._getPcbCircuitJsonBounds();return{left:s.bounds.left,right:s.bounds.right,top:s.bounds.top,bottom:s.bounds.bottom}}),n=Array(t.length).fill(!1).map(()=>Array(t.length).fill(!1));for(let o=0;o<t.length;o++)for(let s=o+1;s<t.length;s++){let a=t[o],c=t[s];n[o][s]=n[s][o]=!(a.right<c.left||a.left>c.right||a.bottom>c.top||a.top<c.bottom)}let i=new Set,r=o=>{i.add(o);for(let s=0;s<t.length;s++)n[o][s]&&!i.has(s)&&r(s)};return r(0),i.size===t.length},eV=e=>{if(e.length===0)throw new Error("Cannot get center of empty PCB primitives array");let t=e.map(r=>r._getPcbCircuitJsonBounds().center).filter(Boolean),n=t.reduce((r,o)=>r+o.x,0),i=t.reduce((r,o)=>r+o.y,0);return{x:n/t.length,y:i/t.length}},u3t=p.object({name:p.string().optional(),pinNumber:p.number().optional(),aliases:p.array(p.string()).optional(),layer:p.string().optional(),layers:p.array(p.string()).optional(),schX:p.number().optional(),schY:p.number().optional(),direction:p.enum(["up","down","left","right"]).optional()}),ji=class extends xe{constructor(t,n={}){if(!t.name&&t.pinNumber!==void 0&&(t.name=`pin${t.pinNumber}`),!t.name)throw new Error("Port must have a name or a pinNumber");super(t);M(this,"source_port_id",null);M(this,"pcb_port_id",null);M(this,"schematic_port_id",null);M(this,"schematicSymbolPortDef",null);M(this,"matchedComponents");M(this,"facingDirection",null);M(this,"originDescription",null);n.originDescription&&(this.originDescription=n.originDescription),this.matchedComponents=[]}get config(){return{componentName:"Port",zodProps:u3t}}_isBoardPinoutFromAttributes(){let t=this.parent;if(t?._parsedProps?.pinAttributes){let n=t._parsedProps.pinAttributes;for(let i of this.getNameAndAliases())if(n[i]?.includeInBoardPinout)return!0}}_getGlobalPcbPositionBeforeLayout(){let t=this.matchedComponents.find(i=>i.isPcbPrimitive),n=this.parent;if(n&&!n.props.footprint)throw new Error(`${n.componentName} "${n.props.name}" does not have a footprint. Add a footprint prop, e.g. <${n.componentName.toLowerCase()} footprint="..." />`);if(!t)throw new Error(`Port ${this} has no matching PCB primitives. This often means the footprint's pads lack matching port hints.`);return t?._getGlobalPcbPositionBeforeLayout()??{x:0,y:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_port_id)return super._getPcbCircuitJsonBounds();let{db:t}=this.root,n=t.pcb_port.get(this.pcb_port_id);return{center:{x:n.x,y:n.y},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getGlobalPcbPositionAfterLayout(){return this._getPcbCircuitJsonBounds().center}_getPortsInternallyConnectedToThisPort(){let t=this.parent;if(!t||!t._getInternallyConnectedPins)return[];let n=t._getInternallyConnectedPins();for(let i of n)if(i.some(r=>r===this))return i;return[]}_hasSchematicPort(){let{schX:t,schY:n}=this._parsedProps;if(t!==void 0&&n!==void 0)return!0;let i=this.getParentNormalComponent();if(i?.getSchematicSymbol())return!!(this.schematicSymbolPortDef||this._getPortsInternallyConnectedToThisPort().some(a=>a.schematicSymbolPortDef));let o=i?._getSchematicBoxDimensions();return!!(o&&this.props.pinNumber!==void 0&&o.getPortPositionByPinNumber(this.props.pinNumber))}_getGlobalSchematicPositionBeforeLayout(){let{schX:t,schY:n}=this._parsedProps;if(t!==void 0&&n!==void 0)return{x:t,y:n};let i=this.getParentNormalComponent(),r=i?.getSchematicSymbol();if(r){let s=this.schematicSymbolPortDef;if(!s&&(s=this._getPortsInternallyConnectedToThisPort().find(c=>c.schematicSymbolPortDef)?.schematicSymbolPortDef??null,!s))throw new Error(`Couldn't find schematicSymbolPortDef for port ${this.getString()}, searched internally connected ports and none had a schematicSymbolPortDef. Why are we trying to get the schematic position of this port?`);let a=Jn(i.computeSchematicGlobalTransform(),vn(-r.center.x,-r.center.y));return Ae(a,s)}let o=i?._getSchematicBoxDimensions();if(o&&this.props.pinNumber!==void 0){let s=o.getPortPositionByPinNumber(this.props.pinNumber);if(!s)throw new Error(`Couldn't find position for schematic_port for port ${this.getString()} inside of the schematic box`);return Ae(i.computeSchematicGlobalTransform(),s)}throw new Error(`Couldn't find position for schematic_port for port ${this.getString()}`)}_getGlobalSchematicPositionAfterLayout(){let{db:t}=this.root;if(!this.schematic_port_id)throw new Error(`Can't get schematic port position after layout for "${this.getString()}", no schematic_port_id`);let n=t.schematic_port.get(this.schematic_port_id);if(!n)throw new Error(`Schematic port not found when trying to get post-layout position: ${this.schematic_port_id}`);return n.center}registerMatch(t){this.matchedComponents.push(t)}getNameAndAliases(){let{_parsedProps:t}=this;return Array.from(new Set([...t.name?[t.name]:[],...t.aliases??[],...typeof t.pinNumber=="number"?[`pin${t.pinNumber}`,t.pinNumber.toString()]:[],...this.externallyAddedAliases??[]]))}_getMatchingPinAttributes(){let t=this.parent?._parsedProps?.pinAttributes;if(!t)return[];let n=[];for(let i of this.getNameAndAliases()){let r=t[i];r&&n.push(r)}return n}_shouldIncludeInBoardPinout(){return this._getMatchingPinAttributes().some(t=>t.includeInBoardPinout===!0)}isMatchingPort(t){return this.isMatchingAnyOf(t.getNameAndAliases())}getPortSelector(){return`.${(this.getParentNormalComponent()??this.parent)?.props.name} > port.${this.props.name}`}getAvailablePcbLayers(){let{layer:t,layers:n}=this._parsedProps;return n||(t?[t]:Array.from(new Set(this.matchedComponents.flatMap(i=>i.getAvailablePcbLayers()))))}_getDirectlyConnectedTraces(){return this.getSubcircuit().selectAll("trace").filter(i=>!i._couldNotFindPort).filter(i=>i._isExplicitlyConnectedToPort(this))}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=this.getNameAndAliases(),r=this.getParentNormalComponent(),s=(this.parent?.source_component_id?this.parent:r)?.source_component_id??null,a=t.source_port.insert({name:n.name,pin_number:n.pinNumber,port_hints:i,source_component_id:s,subcircuit_id:this.getSubcircuit()?.subcircuit_id});this.source_port_id=a.source_port_id}doInitialSourceParentAttachment(){let{db:t}=this.root,n=this.getParentNormalComponent(),i=this.parent?.source_component_id?this.parent:n;if(!i?.source_component_id)throw new Error(`${this.getString()} has no parent source component (parent: ${this.parent?.getString()})`);t.source_port.update(this.source_port_id,{source_component_id:i.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id}),this.source_component_id=i.source_component_id}doInitialPcbPortRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{matchedComponents:n}=this,i=this.getParentNormalComponent(),r=this.parent?.pcb_component_id?this.parent:i;if(!r?.pcb_component_id)throw new Error(`${this.getString()} has no parent pcb component, cannot render pcb_port (parent: ${this.parent?.getString()}, parentNormalComponent: ${i?.getString()})`);let o=n.filter(a=>a.isPcbPrimitive);if(o.length===0)return;let s=null;if(o.length===1&&(s=o[0]._getPcbCircuitJsonBounds().center),o.length>1){if(!tV(o))throw new Error(`${this.getString()} has multiple non-overlapping pcb matches, unclear how to place pcb_port: ${o.map(a=>a.getString()).join(", ")}. (Note: tscircuit core does not currently allow you to specify internally connected pcb primitives with the same port hints, try giving them different port hints and specifying they are connected externally- or file an issue)`);s=eV(o)}if(s){let a=this.getSubcircuit(),c=this._shouldIncludeInBoardPinout(),l=t.pcb_port.insert({pcb_component_id:r.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:a?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...c?{is_board_pinout:!0}:{},...s,source_port_id:this.source_port_id,is_board_pinout:this._isBoardPinoutFromAttributes()});this.pcb_port_id=l.pcb_port_id}else{let a=o[0];throw new Error(`${a.getString()} does not have a center or _getGlobalPcbPositionBeforeLayout method (needed for pcb_port placement)`)}}updatePcbPortRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root;if(this.pcb_port_id)return;let n=this.matchedComponents.filter(l=>l.isPcbPrimitive);if(n.length===0)return;let i=null;if(n.length===1&&(i=n[0]._getPcbCircuitJsonBounds().center),n.length>1)try{tV(n)&&(i=eV(n))}catch{}if(!i)return;let r=this.getParentNormalComponent(),o=this.parent?.pcb_component_id?this.parent:r,s=this.getSubcircuit(),a=this._shouldIncludeInBoardPinout(),c=t.pcb_port.insert({pcb_component_id:o?.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...a?{is_board_pinout:!0}:{},...i,source_port_id:this.source_port_id,is_board_pinout:this._isBoardPinoutFromAttributes()});this.pcb_port_id=c.pcb_port_id}doInitialSchematicPortRender(){let{db:t}=this.root,{_parsedProps:n}=this,{schX:i,schY:r}=n,o=i!==void 0&&r!==void 0?this.getParentNormalComponent():this.getPrimitiveContainer();if(!o||!this._hasSchematicPort())return;let s=o._getGlobalSchematicPositionBeforeLayout(),a=this._getGlobalSchematicPositionBeforeLayout(),c=null,l=o._getSchematicBoxDimensions();l&&n.pinNumber!==void 0&&(c=l.getPortPositionByPinNumber(n.pinNumber)),this.getSubcircuit().props._schDebugObjectsEnabled&&t.schematic_debug_object.insert({shape:"rect",center:a,size:{width:.1,height:.1},label:"obstacle"}),c?.side?this.facingDirection={left:"left",right:"right",top:"up",bottom:"down"}[c.side]:this.facingDirection=l3t(s,a);let u=t.source_port.get(this.source_port_id),h=[];for(let w of u?.port_hints??[])w.match(/^(pin)?\d+$/)||w.match(/^(left|right)/)&&!u?.name.match(/^(left|right)/)||h.push(w);let d,_=this.getParentNormalComponent();_?.props?.showPinAliases&&h.length>0?d=h.join("/"):h.length>0&&(d=h[0]);let g={type:"schematic_port",schematic_component_id:_?.schematic_component_id,center:a,source_port_id:this.source_port_id,facing_direction:this.facingDirection,distance_from_component_edge:.4,side_of_component:c?.side,pin_number:n.pinNumber,true_ccw_index:c?.trueIndex,display_pin_label:d,is_connected:!1};for(let w of this._getMatchingPinAttributes())w.requiresPower&&(g.has_input_arrow=!0),w.providesPower&&(g.has_output_arrow=!0);let x=t.schematic_port.insert(g);this.schematic_port_id=x.schematic_port_id}_getSubcircuitConnectivityKey(){return this.root?.db.source_port.get(this.source_port_id)?.subcircuit_connectivity_map_key}_setPositionFromLayout(t){let{db:n}=this.root;this.pcb_port_id&&n.pcb_port.update(this.pcb_port_id,{x:t.x,y:t.y})}_hasMatchedPcbPrimitive(){return this.matchedComponents.some(t=>t.isPcbPrimitive)}_getNetLabelText(){return`${this.parent?.props.name}_${this.props.name}`}},kV=e=>{let t=e.find(n=>/^(pin)?\d+$/.test(n));return t?Number.parseInt(t.replace(/^pin/,"")):null};function cm(e,t){let n=kV(e);if(!n)return null;let r=[...e.filter(o=>o.toString()!==n.toString()&&o!==`pin${n}`),...t?.additionalAliases?.[`pin${n}`]??[]];return new ji({pinNumber:n,aliases:r})}var p3t=e=>{for(let t of["leftSide","rightSide","topSide","bottomSide"])if(t in e&&typeof e[t]=="number")throw new Error(`A number was specified for "${t}", you probably meant to use "size" not "side"`);return"leftSide"in e||"rightSide"in e||"topSide"in e||"bottomSide"in e},h3t=e=>{if(p3t(e))return{leftSize:e.leftSide?.pins.length??0,rightSize:e.rightSide?.pins.length??0,topSize:e.topSide?.pins.length??0,bottomSize:e.bottomSide?.pins.length??0};let{leftSize:t=0,rightSize:n=0,topSize:i=0,bottomSize:r=0}=e;return{leftSize:t,rightSize:n,topSize:i,bottomSize:r}};function NV(e){let t=e;return t.leftSide!==void 0||t.rightSide!==void 0||t.topSide!==void 0||t.bottomSide!==void 0}var d3t=e=>{let t=e.portDistanceFromEdge??.4,n=e.schPortArrangement?h3t(e.schPortArrangement):null,i={left:0,right:0,top:0,bottom:0},r=e.pinCount??null;if(r===null)if(n)r=n.leftSize+n.rightSize+n.topSize;else throw new Error("Could not determine pin count for the schematic box");if(r&&!n){let y=Math.floor(r/2);n={leftSize:r-y,rightSize:y,topSize:0,bottomSize:0}}n||(n={leftSize:0,rightSize:0,topSize:0,bottomSize:0});let o=({side:y,sideIndex:g,truePinIndex:x})=>{if(!e.schPortArrangement||!NV(e.schPortArrangement))return x+1;let w={left:"top-to-bottom",bottom:"left-to-right",right:"bottom-to-top",top:"right-to-left"}[y],S=e.schPortArrangement?.[`${y}Side`]?.direction??w,C=e.schPortArrangement?.[`${y}Side`]?.pins,I=g;return S!==w&&(I=C.length-g-1),_m(C[I],e.pinLabels)},s=[],a=0,c=0;for(let y=0;y<n.leftSize;y++){let g=o({side:"left",sideIndex:y,truePinIndex:c}),x=e.numericSchPinStyle?.[`pin${g}`]??e.numericSchPinStyle?.[g];x?.topMargin&&(a+=x.topMargin),s.push({trueIndex:c,pinNumber:g,side:"left",distanceFromOrthogonalEdge:a}),x?.bottomMargin&&(a+=x.bottomMargin),y===n.leftSize-1?i.left=a:a+=e.schPinSpacing,c++}a=0;for(let y=0;y<n.bottomSize;y++){let g=o({side:"bottom",sideIndex:y,truePinIndex:c}),x=e.numericSchPinStyle?.[`pin${g}`]??e.numericSchPinStyle?.[g];x?.leftMargin&&(a+=x.leftMargin),s.push({trueIndex:c,pinNumber:g,side:"bottom",distanceFromOrthogonalEdge:a}),x?.rightMargin&&(a+=x.rightMargin),y===n.bottomSize-1?i.bottom=a:a+=e.schPinSpacing,c++}a=0;for(let y=0;y<n.rightSize;y++){let g=o({side:"right",sideIndex:y,truePinIndex:c}),x=e.numericSchPinStyle?.[`pin${g}`]??e.numericSchPinStyle?.[g];x?.bottomMargin&&(a+=x.bottomMargin),s.push({trueIndex:c,pinNumber:g,side:"right",distanceFromOrthogonalEdge:a}),x?.topMargin&&(a+=x.topMargin),y===n.rightSize-1?i.right=a:a+=e.schPinSpacing,c++}a=0;for(let y=0;y<n.topSize;y++){let g=o({side:"top",sideIndex:y,truePinIndex:c}),x=e.numericSchPinStyle?.[`pin${g}`]??e.numericSchPinStyle?.[g];x?.rightMargin&&(a+=x.rightMargin),s.push({trueIndex:c,pinNumber:g,side:"top",distanceFromOrthogonalEdge:a}),x?.leftMargin&&(a+=x.leftMargin),y===n.topSize-1?i.top=a:a+=e.schPinSpacing,c++}let l=e.schWidth;if(l===void 0){l=Math.max(i.top+e.schPinSpacing*2,i.bottom+e.schPinSpacing*2);let y=e.pinLabels?Math.max(...Object.values(e.pinLabels).map(x=>x.length*.1)):0,g=y>0?1.1:0;l=Math.max(l,y+g)}let u=e.schHeight;u||(u=Math.max(i.left+e.schPinSpacing*2,i.right+e.schPinSpacing*2));let h={left:{x:-l/2-t,y:i.left/2},bottom:{x:-i.bottom/2,y:-u/2-t},right:{x:l/2+t,y:-i.right/2},top:{x:i.top/2,y:u/2+t}},d={left:{x:0,y:-1},right:{x:0,y:1},top:{x:-1,y:0},bottom:{x:1,y:0}},_=s.map(y=>{let{distanceFromOrthogonalEdge:g,side:x}=y,w=h[x],S=d[x];return{x:w.x+g*S.x,y:w.y+g*S.y,...y}});return{getPortPositionByPinNumber(y){let g=_.find(x=>x.pinNumber.toString()===y.toString());return g||null},getSize(){return{width:l,height:u}},getSizeIncludingPins(){return{width:l+(n.leftSize||n.rightSize?.4:0),height:u+(n.topSize||n.bottomSize?.4:0)}},pinCount:r}},f3t=(0,AV.default)("tscircuit:core:footprint"),RV=class extends xe{get config(){return{componentName:"Footprint",zodProps:UF}}doInitialPcbFootprintLayout(){if(this.root?.pcbDisabled)return;let e=this.children.filter(h=>h.componentName==="Constraint");if(e.length===0)return;let{isFlipped:t}=this._getPcbPrimitiveFlippedHelpers(),n=h=>t&&"left"in h&&"right"in h?{...h,left:h.right,right:h.left}:h,i=e.flatMap(h=>h._getAllReferencedComponents().componentsWithSelectors).map(({component:h,selector:d,componentSelector:_,edge:y})=>({component:h,selector:d,componentSelector:_,edge:y,bounds:h._getPcbCircuitJsonBounds()}));if(i.some(h=>h.edge))throw new Error("edge constraints not implemented yet for footprint layout, contributions welcome!");function r(h){return i.find(({selector:d})=>d===h)}let o=new jp,s={};function a(h){return h in s||(s[h]=new Xs(h),o.addEditVariable(s[h],wn.weak)),s[h]}for(let{selector:h,bounds:d}of i){let _=a(`${h}_x`),y=a(`${h}_y`);o.suggestValue(_,d.center.x),o.suggestValue(y,d.center.y)}for(let h of e){let d=h._parsedProps;if("xDist"in d){let{xDist:_,left:y,right:g,edgeToEdge:x,centerToCenter:w}=n(d),S=a(`${y}_x`),C=a(`${g}_x`),I=r(y)?.bounds,k=r(g)?.bounds;if(w){let P=new Cn(C,[-1,S]);o.addConstraint(new ai(P,Yn.Eq,d.xDist,wn.required))}else if(x){let P=new Cn(C,-k.width/2,[-1,S],-I.width/2);o.addConstraint(new ai(P,Yn.Eq,d.xDist,wn.required))}}else if("yDist"in d){let{yDist:_,top:y,bottom:g,edgeToEdge:x,centerToCenter:w}=d,S=a(`${y}_y`),C=a(`${g}_y`),I=r(y)?.bounds,k=r(g)?.bounds;if(w){let P=new Cn(S,[-1,C]);o.addConstraint(new ai(P,Yn.Eq,d.yDist,wn.required))}else if(x){let P=new Cn(S,I.height/2,[-1,C],-k.height/2);o.addConstraint(new ai(P,Yn.Eq,d.yDist,wn.required))}}else if("sameY"in d){let{for:_}=d;if(_.length<2)continue;let y=_.map(x=>a(`${x}_y`)),g=new Cn(...y.slice(1));o.addConstraint(new ai(g,Yn.Eq,y[0],wn.required))}else if("sameX"in d){let{for:_}=d;if(_.length<2)continue;let y=_.map(x=>a(`${x}_x`)),g=new Cn(...y.slice(1));o.addConstraint(new ai(g,Yn.Eq,y[0],wn.required))}}o.updateVariables(),f3t.enabled&&(console.log("Solution to layout constraints:"),console.table(Object.entries(s).map(([h,d])=>({var:h,val:d.value()}))));let c={left:1/0,right:-1/0,top:-1/0,bottom:1/0};for(let{selector:h,bounds:{width:d,height:_}}of i){let y=a(`${h}_x`),g=a(`${h}_y`),x=y.value()-d/2,w=y.value()+d/2,S=g.value()+_/2,C=g.value()-_/2;c.left=Math.min(c.left,x),c.right=Math.max(c.right,w),c.top=Math.max(c.top,S),c.bottom=Math.min(c.bottom,C)}let l={x:-(c.right+c.left)/2,y:-(c.top+c.bottom)/2},u=this.getPrimitiveContainer()._getGlobalPcbPositionBeforeLayout();l.x+=u.x,l.y+=u.y;for(let{component:h,selector:d}of i){let _=a(`${d}_x`),y=a(`${d}_y`);h._setPositionFromLayout({x:_.value()+l.x,y:y.value()+l.y})}}},OV=e=>{if(!e)return null;let n=e.split("?")[0].split("#")[0],i=n.split("/").pop()??n;return i.includes(".")?i.split(".").pop()?.toLowerCase()??null:null},m3t=(e,t)=>{let n=e.replace(/\/+$/,""),i=t.replace(/^\/+/,"");return`${n}/${i}`},LV=(e,t)=>{if(!t||!e.startsWith("/"))return e;try{let n=new URL(t);return n.pathname!=="/"&&e.startsWith(n.pathname)?new URL(e,n.origin).toString():m3t(t,e)}catch{return e}},XI=p.union([p.number(),p.string()]),nV=p.object({x:XI,y:XI,z:XI}),FV=class extends xe{get config(){return{componentName:"CadModel",zodProps:gz}}doInitialCadModelRender(){let e=this._findParentWithPcbComponent();if(!e||!e.pcb_component_id)return;let{db:t}=this.root,{boardThickness:n=0}=this.root?._getBoard()??{},i=e._getPcbCircuitJsonBounds(),r=t.pcb_component.get(e.pcb_component_id),o=this._parsedProps;if(!o||typeof o.modelUrl!="string"&&typeof o.stepUrl!="string")return;let s=e._computePcbGlobalTransformBeforeLayout(),c=To(s).rotation.angle*180/Math.PI,l=nV.parse({x:0,y:0,z:0});if(typeof o.rotationOffset=="number")l.z=Number(o.rotationOffset);else if(typeof o.rotationOffset=="object"){let x=nV.parse(o.rotationOffset);l.x=Number(x.x),l.y=Number(x.y),l.z=Number(x.z)}let u=Ng.parse({x:o.pcbX??0,y:o.pcbY??0,z:o.pcbZ??0,...typeof o.positionOffset=="object"?o.positionOffset:{}}),h=o.zOffsetFromSurface!==void 0?Y.parse(o.zOffsetFromSurface):0,d=e.props.layer==="bottom"?"bottom":"top",_=o.modelUrl?OV(o.modelUrl):void 0,y={};if(_==="stl"?y.model_stl_url=this._addCachebustToModelUrl(o.modelUrl):_==="obj"?y.model_obj_url=this._addCachebustToModelUrl(o.modelUrl):_==="gltf"?y.model_gltf_url=this._addCachebustToModelUrl(o.modelUrl):_==="glb"?y.model_glb_url=this._addCachebustToModelUrl(o.modelUrl):_==="step"||_==="stp"?y.model_step_url=this._addCachebustToModelUrl(o.modelUrl):_==="wrl"||_==="vrml"?y.model_wrl_url=this._addCachebustToModelUrl(o.modelUrl):y.model_stl_url=this._addCachebustToModelUrl(o.modelUrl),o.stepUrl){let x=this._addCachebustToModelUrl(o.stepUrl);x&&(y.model_step_url=x)}let g=t.cad_component.insert({position:{x:i.center.x+Number(u.x),y:i.center.y+Number(u.y),z:(d==="bottom"?-n/2:n/2)+(d==="bottom"?-h:h)+Number(u.z)},rotation:{x:Number(l.x),y:(d==="top"?0:180)+Number(l.y),z:d==="bottom"?-(c+Number(l.z))+180:c+Number(l.z)},pcb_component_id:e.pcb_component_id,source_component_id:e.source_component_id,model_unit_to_mm_scale_factor:typeof o.modelUnitToMmScale=="number"?o.modelUnitToMmScale:void 0,...y});this.cad_component_id=g.cad_component_id}_findParentWithPcbComponent(){let e=this.parent;for(;e&&!e.pcb_component_id;)e=e.parent;return e}_addCachebustToModelUrl(e){if(!e)return e;let t=this.root?.platform?.projectBaseUrl,n=LV(e,t);if(!n.includes("modelcdn.tscircuit.com"))return n;let i=this.root?.getClientOrigin()??"";return`${n}${n.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(i)}`}},zV=class extends xe{constructor(){super(...arguments);M(this,"isPrimitiveContainer",!0)}get config(){return{componentName:"CadAssembly",zodProps:yz}}},_3t=(e,t)=>{if(!e)return;let n={};for(let[i,r]of Object.entries(e)){let o=_m(i,t),s={leftMargin:r.marginLeft??r.leftMargin,rightMargin:r.marginRight??r.rightMargin,topMargin:r.marginTop??r.topMargin,bottomMargin:r.marginBottom??r.bottomMargin};n[`pin${o}`]={...n[`pin${o}`],...s}}return n},iV=class{constructor({input:e}){M(this,"input");this.input=e}solveAndMapToTraces(){let e=[];for(let t of this.input.connections){if(t.pointsToConnect.length!==2)continue;let[n,i]=t.pointsToConnect,r={type:"pcb_trace",pcb_trace_id:"",connection_name:t.name,route:[{route_type:"wire",x:n.x,y:n.y,layer:"top",width:.1},{route_type:"wire",x:i.x,y:i.y,layer:"top",width:.1}]};e.push(r)}return e}},y3t=e=>{let t=Math.min(...e.map(o=>o.center.x)),n=Math.max(...e.map(o=>o.center.x)),i=Math.min(...e.map(o=>o.center.y)),r=Math.max(...e.map(o=>o.center.y));return{minX:t,maxX:n,minY:i,maxY:r}},rV=["top","bottom","inner1","inner2"],cx=(e,t=[])=>{let n=[];if(t.length===0){let a=e[0].layers;for(let c of a)n.push(...cx(e.slice(1),[c]));return n}if(e.length===0)return[];let i=e[0],r=i.via||i.optional_via,o=t[t.length-1];if(e.length===1){let a=i;return a.layers&&r?a.layers.map(c=>({layer_path:[...t,c]})):a.layers?.includes(o)?[{layer_path:[...t,o]}]:[]}if(!r)return i.layers&&!i.layers.includes(o)?[]:cx(e.slice(1),t.concat([o]));let s=(i.optional_via?rV:rV.filter(a=>a!==o)).filter(a=>!i.layers||i.layers?.includes(a));for(let a of s)n.push(...cx(e.slice(1),t.concat(a)));return n};function oV(e){let t={x:e.to.x-e.from.x,y:e.to.y-e.from.y},n=Math.abs(t.x),i=Math.abs(t.y);return n>i?t.x>0?"right":"left":t.y>0?"down":"up"}function Th(e,t){return Math.hypot(e.x-t.x,e.y-t.y)}var g3t=e=>{if(e.length===1)return e[0];if(e.some(c=>c.length===0))throw new Error("Cannot merge routes with zero length");let t=[],n=e[0][0],i=e[0][e[0].length-1],r=e[1][0],o=e[1][e[1].length-1],s=Math.min(Th(n,r),Th(n,o)),a=Math.min(Th(i,r),Th(i,o));s<a?t.push(...e[0].reverse()):t.push(...e[0]);for(let c=1;c<e.length;c++){let l=t[t.length-1],u=e[c],h=u[0],d=u[u.length-1],_=Th(l,h),y=Th(l,d);_<y?t.push(...u):t.push(...u.reverse())}for(let c=1;c<t.length-1;c++){let l=t[c-1],u=t[c];l.route_type==="wire"&&u.route_type==="wire"&&l.layer!==u.layer&&t.splice(c,0,{x:l.x,y:l.y,from_layer:l.layer,to_layer:u.layer,route_type:"via"})}return t},b3t=(e,t)=>{let n="_getGlobalPcbPositionBeforeLayout"in e?e._getGlobalPcbPositionBeforeLayout():e,i="_getGlobalPcbPositionBeforeLayout"in t?t._getGlobalPcbPositionBeforeLayout():t;return Math.sqrt((n.x-i.x)**2+(n.y-i.y)**2)};function x3t(e,t){if(t.length===0)throw new Error("No candidates given to getClosest method");let n=t[0],i=1/0;for(let r of t){let o=b3t(e,r);o<i&&(n=r,i=o)}return n}var v3t=(e,t)=>{let n=0;n+=e.length??0,n+=t.filter(i=>i.is_crossing).length;for(let i=1;i<t.length;i++){let r=t[i-1],o=t[i],s=Math.abs(r.from.x-r.to.x)<.01,a=Math.abs(o.from.x-o.to.x)<.01;s!==a&&n++}return n},ym=e=>({up:"bottom",down:"top",left:"right",right:"left"})[e]??null,WI=({firstEdge:e,firstEdgePort:t,firstDominantDirection:n,lastEdge:i,lastEdgePort:r,lastDominantDirection:o})=>{if(e&&t)return WI({lastEdge:{from:e.to,to:e.from},lastEdgePort:t,lastDominantDirection:n}).reverse().map(a=>({from:a.to,to:a.from}));let s=[];if(i&&r){let a={x:i.to.x,y:i.to.y};o==="left"||o==="right"?(a.x=r.position.x,s.push({from:i.to,to:{...a}}),s.push({from:a,to:{...r.position}})):(a.y=r.position.y,s.push({from:i.to,to:{...a}}),s.push({from:a,to:{...r.position}}))}return s=s.filter(a=>zi(a.from,a.to)>.01),s};function w3t(e){try{return[e(),null]}catch(t){return[null,t]}}var S3t=(e,{db:t})=>{let n=e.map(i=>{let r=t.source_port.get(i.source_port_id);if(!r?.source_component_id)return null;let o=t.source_component.get(r.source_component_id);return o?.ftype==="simple_capacitor"?o.max_decoupling_trace_length:null}).filter(i=>i!==null);if(n.length!==0)return Math.min(...n)};function P3t({ports:e,nets:t}){if(e.length>=2)return`${e[0]?.selector} to ${e[1]?.selector}`;if(e.length===1&&t.length===1)return`${e[0]?.selector} to net.${t[0]._parsedProps.name}`}var T3t=(e,{db:t})=>{let n=t.pcb_board.list()[0];if(n.outline){let c=n.outline,l=(u,h)=>{let d=!1;for(let _=0,y=h.length-1;_<h.length;y=_++){let g=h[_].x,x=h[_].y,w=h[y].x,S=h[y].y;x>u.y!=S>u.y&&u.x<(w-g)*(u.y-x)/(S-x)+g&&(d=!d)}return d};return e.some(u=>!l(u,c))}let i=n.width,r=n.height,o=n.center.x,s=n.center.y;return e.some(c=>c.x<o-i/2||c.y<s-r/2||c.x>o+i/2||c.y>s+r/2)},sV=(e,t)=>Math.abs(e-t)<1e-4,I3t=(e,t,{viaDiameter:n=.5}={})=>{let i=[];for(let r=0;r<e.length-1;r++){let[o,s]=[e[r],e[r+1]],a=r-1>=0?e[r-1]:null,c=sV(o.y,s.y),l=sV(o.x,s.x);if(!c&&!l)throw new Error(`getObstaclesFromTrace currently only supports horizontal and vertical traces (not diagonals) Conflicting trace: ${t}, start: (${o.x}, ${o.y}), end: (${s.x}, ${s.y})`);let u={type:"rect",layers:[o.layer],center:{x:(o.x+s.x)/2,y:(o.y+s.y)/2},width:c?Math.abs(o.x-s.x):.1,height:l?Math.abs(o.y-s.y):.1,connectedTo:[t]};if(i.push(u),a&&a.layer===o.layer&&o.layer!==s.layer){let h={type:"rect",layers:[o.layer,s.layer],center:{x:o.x,y:o.y},connectedTo:[t],width:n,height:n};i.push(h)}}return i};function DV(e,t=4){let{center:n,width:i,height:r,rotation:o}=e,s=[],a=o*Math.PI/180,c=Math.cos(a),l=Math.sin(a),u=(o%360+360)%360;if(r<=i?u>=45&&u<135||u>=225&&u<315:u>=135&&u<225||u>=315||u<45){let d=i/t;for(let _=0;_<t;_++){let y=(_-t/2+.5)*d,g=-y*c,x=-y*l,w=d*1.1,S=Math.abs(r*c)+Math.abs(d*l);s.push({center:{x:n.x+g,y:n.y+x},width:w,height:S})}}else{let d=r/t;for(let _=0;_<t;_++){let y=(_-t/2+.5)*d,g=-y*l,x=y*c,w=Math.abs(i*c)+Math.abs(d*l),S=d*1.1;s.push({center:{x:n.x+g,y:n.y+x},width:w,height:S})}}return s}function M3t(e,t={}){if(e.length<3)return[];let{rectHeight:n=.1}=t,i=[],r=e.map(a=>a.y),o=Math.min(...r),s=Math.max(...r);for(let a=o;a<s;a+=n){let c=a+n/2,l=[];for(let u=0;u<e.length;u++){let h=e[u],d=e[(u+1)%e.length];if(h.y<=c&&d.y>c||d.y<=c&&h.y>c){let _=(c-h.y)*(d.x-h.x)/(d.y-h.y)+h.x;l.push(_)}}l.sort((u,h)=>u-h);for(let u=0;u<l.length;u+=2)if(u+1<l.length){let h=l[u],_=l[u+1]-h;_>1e-6&&i.push({center:{x:h+_/2,y:c},width:_,height:n})}}return i}function C3t(e,t={}){let{center:n,radius:i}=e,{rectHeight:r=.1}=t,o=[],s=Math.ceil(i*2/r);for(let a=0;a<s;a++){let c=n.y-i+(a+.5)*r,l=c-n.y,u=Math.sqrt(i*i-l*l);u>0&&o.push({center:{x:n.x,y:c},width:u*2,height:r})}return o}var bc=["top","inner1","inner2","bottom"],lM=(e,t)=>{let n=r=>t?r.concat(r.map(o=>t?.getNetConnectedToId(o)).filter(Boolean)):r,i=[];for(let r of e)if(r.type==="pcb_smtpad"){if(r.shape==="circle")i.push({type:"oval",layers:[r.layer],center:{x:r.x,y:r.y},width:r.radius*2,height:r.radius*2,connectedTo:n([r.pcb_smtpad_id])});else if(r.shape==="rect")i.push({type:"rect",layers:[r.layer],center:{x:r.x,y:r.y},width:r.width,height:r.height,connectedTo:n([r.pcb_smtpad_id])});else if(r.shape==="rotated_rect"){let o={center:{x:r.x,y:r.y},width:r.width,height:r.height,rotation:r.ccw_rotation},s=DV(o);for(let a of s)i.push({type:"rect",layers:[r.layer],center:a.center,width:a.width,height:a.height,connectedTo:n([r.pcb_smtpad_id])})}}else if(r.type==="pcb_keepout")r.shape==="circle"?i.push({type:"oval",layers:r.layers,center:{x:r.center.x,y:r.center.y},width:r.radius*2,height:r.radius*2,connectedTo:[]}):r.shape==="rect"&&i.push({type:"rect",layers:r.layers,center:{x:r.center.x,y:r.center.y},width:r.width,height:r.height,connectedTo:[]});else if(r.type==="pcb_cutout"){if(r.shape==="rect")i.push({type:"rect",layers:bc,center:{x:r.center.x,y:r.center.y},width:r.width,height:r.height,connectedTo:[]});else if(r.shape==="circle"){let o=C3t({center:r.center,radius:r.radius},{rectHeight:.6});for(let s of o)i.push({type:"rect",layers:bc,center:s.center,width:s.width,height:s.height,connectedTo:[]})}else if(r.shape==="polygon"){let o=M3t(r.points,{rectHeight:.6});for(let s of o)i.push({type:"rect",layers:bc,center:s.center,width:s.width,height:s.height,connectedTo:[]})}}else if(r.type==="pcb_hole")r.hole_shape==="oval"?i.push({type:"oval",center:{x:r.x,y:r.y},width:r.hole_width,height:r.hole_height,connectedTo:[]}):r.hole_shape==="square"?i.push({type:"rect",layers:bc,center:{x:r.x,y:r.y},width:r.hole_diameter,height:r.hole_diameter,connectedTo:[]}):(r.hole_shape==="round"||r.hole_shape==="circle")&&i.push({type:"rect",layers:bc,center:{x:r.x,y:r.y},width:r.hole_diameter,height:r.hole_diameter,connectedTo:[]});else if(r.type==="pcb_plated_hole")r.shape==="circle"?i.push({type:"oval",layers:bc,center:{x:r.x,y:r.y},width:r.outer_diameter,height:r.outer_diameter,connectedTo:n([r.pcb_plated_hole_id])}):r.shape==="circular_hole_with_rect_pad"?i.push({type:"rect",layers:bc,center:{x:r.x,y:r.y},width:r.rect_pad_width,height:r.rect_pad_height,connectedTo:n([r.pcb_plated_hole_id])}):(r.shape==="oval"||r.shape==="pill")&&i.push({type:"oval",layers:bc,center:{x:r.x,y:r.y},width:r.outer_width,height:r.outer_height,connectedTo:n([r.pcb_plated_hole_id])});else if(r.type==="pcb_trace"){let o=I3t(r.route.map(s=>({x:s.x,y:s.y,layer:"layer"in s?s.layer:s.from_layer})),r.source_trace_id);i.push(...o)}else r.type==="pcb_via"&&i.push({type:"rect",layers:r.layers,center:{x:r.x,y:r.y},connectedTo:[],width:r.outer_diameter,height:r.outer_diameter});return i},xc=({anchor_position:e,anchor_side:t,text:n,font_size:i=.18})=>{let r=.1*(i/.18),o=n.length*r,s=i,a={...e};switch(t){case"right":a.x-=o/2;break;case"left":a.x+=o/2;break;case"top":a.y-=s/2;break;case"bottom":a.y+=s/2;break}return a},uM=({db:e,source_trace_id:t,sameNetOnly:n,differentNetOnly:i})=>{!n&&!i&&(i=!0);let r=e.source_trace.get(t),o=[];for(let s of e.schematic_trace.list()){if(s.source_trace_id===t)continue;let c=e.source_trace.get(s.source_trace_id)?.subcircuit_connectivity_map_key===r.subcircuit_connectivity_map_key;i&&c||n&&!c||o.push(s)}return o},E3t=({edges:e,otherEdges:t})=>{let n=[...e];for(let i=0;i<n.length;i++){if(i>2e3)throw new Error("Over 2000 iterations spent inside createSchematicTraceCrossingSegments, you have triggered an infinite loop, please report this!");let r=n[i],o=Math.abs(r.from.x-r.to.x)<.01?"vertical":r.from.y===r.to.y?"horizontal":"not-orthogonal";if(o==="not-orthogonal")continue;let s=[];for(let g of t){let x=g.from.x===g.to.x?"vertical":g.from.y===g.to.y?"horizontal":"not-orthogonal";if(x==="not-orthogonal"||o===x)continue;if(Ka([r.from,r.to],[g.from,g.to],{lineThickness:.01})){let S=o==="vertical"?r.from.x:g.from.x,C=o==="vertical"?g.from.y:r.from.y,I={x:S,y:C};s.push({otherEdge:g,crossingPoint:I,distanceFromEdgeFrom:zi(r.from,I)})}}if(s.length===0)continue;let a=s[0];for(let g of s)g.distanceFromEdgeFrom<a.distanceFromEdgeFrom&&(a=g);let c=a.crossingPoint,l=.075;if(c.x===r.from.x&&c.y===r.from.y)continue;let u=Bg(r.from,c),h={x:c.x-u.x*l/2,y:c.y-u.y*l/2},d={x:c.x+u.x*l/2,y:c.y+u.y*l/2},_=zi(d,r.to)<l,y=[{from:r.from,to:h},{from:h,to:d,is_crossing:!0},{from:d,to:r.to}];n.splice(i,1,...y),i+=y.length-2,_&&i++}return n},ZI=.001,Ih=(e,t)=>{let n=Math.min(t.from.x,t.to.x),i=Math.max(t.from.x,t.to.x),r=Math.min(t.from.y,t.to.y),o=Math.max(t.from.y,t.to.y);return e.x>=n&&e.x<=i&&e.y>=r&&e.y<=o},aV=e=>{let t=Math.abs(e.from.x-e.to.x)<ZI,n=Math.abs(e.from.y-e.to.y)<ZI;return t?"vertical":n?"horizontal":"diagonal"},k3t=(e,t)=>{let n=aV(e),i=aV(t);if(n===i)return null;if(n==="vertical"&&i==="horizontal"||n==="horizontal"&&i==="vertical"){let h=n==="vertical"?e:t,d=n==="horizontal"?e:t,_=h.from.x,y=d.from.y,g={x:_,y};return Ih(g,e)&&Ih(g,t)?g:null}if(n==="vertical"||i==="vertical"){let h=n==="vertical"?e:t,d=n==="vertical"?t:e,_=h.from.x,y=(d.to.y-d.from.y)/(d.to.x-d.from.x),g=d.from.y-y*d.from.x,x=y*_+g,w={x:_,y:x};return Ih(w,e)&&Ih(w,t)?w:null}let r=(e.to.y-e.from.y)/(e.to.x-e.from.x),o=e.from.y-r*e.from.x,s=(t.to.y-t.from.y)/(t.to.x-t.from.x),a=t.from.y-s*t.from.x;if(Math.abs(r-s)<ZI)return null;let c=(a-o)/(r-s),l=r*c+o,u={x:c,y:l};return Ih(u,e)&&Ih(u,t)?u:null},N3t=({edges:e,db:t,source_trace_id:n})=>{let i=uM({db:t,source_trace_id:n,sameNetOnly:!0}).flatMap(o=>o.edges),r=new Map;for(let o of e)for(let s of i){let a=k3t(o,s);if(a){let c=`${a.x.toFixed(6)},${a.y.toFixed(6)}`;r.has(c)||r.set(c,a)}}return Array.from(r.values())};function A3t(e,t={}){let{minX:n,maxX:i,minY:r,maxY:o}=e,s=t.padding??1;if(!isFinite(n)||!isFinite(i)||!isFinite(r)||!isFinite(o))return[];let a=n-s,c=i+s,l=o+s,u=r-s,h=.01;return[{type:"rect",layers:["top"],center:{x:(a+c)/2,y:l},width:c-a,height:h,connectedTo:[]},{type:"rect",layers:["top"],center:{x:(a+c)/2,y:u},width:c-a,height:h,connectedTo:[]},{type:"rect",layers:["top"],center:{x:a,y:(l+u)/2},width:h,height:l-u,connectedTo:[]},{type:"rect",layers:["top"],center:{x:c,y:(l+u)/2},width:h,height:l-u,connectedTo:[]}]}var R3t=e=>{let t=e.root.db,n=e._findConnectedPorts().ports??[],i=new Set(n.map(s=>s.schematic_port_id)),r=[];for(let s of t.toArray()){if(s.type==="schematic_component"){let a=!!s.symbol_name,c=s.size.width>s.size.height?"horz":"vert";r.push({type:"rect",layers:["top"],center:s.center,width:s.size.width+(a&&c==="horz"?-.5:0),height:s.size.height+(a&&c==="vert"?-.5:0),connectedTo:[]})}if(s.type==="schematic_port"){if(i.has(s.schematic_port_id))continue;let a=s.facing_direction?jg(s.facing_direction):{x:0,y:0};r.push({type:"rect",layers:["top"],center:{x:s.center.x-a.x*.1,y:s.center.y-a.y*.1},width:.1+Math.abs(a.x)*.3,height:.1+Math.abs(a.y)*.3,connectedTo:[]})}s.type==="schematic_text"&&r.push({type:"rect",layers:["top"],center:s.position,width:(s.text?.length??0)*.1,height:.2,connectedTo:[]}),s.type==="schematic_box"&&r.push({type:"rect",layers:["top"],center:{x:s.x,y:s.y},width:s.width,height:s.height,connectedTo:[]})}let o=EV(t.toArray());return r.push(...A3t(o,{padding:1})),r},O3t=({edges:e,db:t,source_trace_id:n})=>{let i=t.source_trace.get(n),r=uM({db:t,source_trace_id:n,differentNetOnly:!0}).flatMap(s=>s.edges),o=s=>{let{from:a,to:c}=s;return a.x===c.x?"vertical":"horizontal"};for(let s of e){let a=o(s),c=()=>r.find(u=>o(u)===a&&Ka([s.from,s.to],[u.from,u.to],{lineThickness:.05})),l=c();for(;l;)a==="horizontal"?(s.from.y+=.1,s.to.y+=.1):(s.from.x+=.1,s.to.x+=.1),l=c()}},KI=e=>{switch(e){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:}},L3t=cD.version??"unknown",um=class extends Error{constructor(e){super(`${e} (capacity-autorouter@${L3t})`),this.name="AutorouterError"}},px=class extends Error{constructor(e){super(e.message),this.errorData=e,this.name="TraceConnectionError"}},F3t=e=>{if(e.root?._featureMspSchematicTraceRouting||e._couldNotFindPort||e.root?.schematicDisabled)return;let{db:t}=e.root,{_parsedProps:n,parent:i}=e;if(!i)throw new Error("Trace has no parent");let r,o;try{let X=e._findConnectedPorts();r=X.allPortsFound,o=X.portsWithSelectors??[]}catch(X){if(X instanceof px){t.source_trace_not_connected_error.insert({...X.errorData,error_type:"source_trace_not_connected_error"});return}throw X}let{netsWithSelectors:s}=e._findConnectedNets();if(!r)return;let c=o.map(X=>X.port.schematic_port_id).sort().join(","),l=e.root?._getBoard();if(l?._connectedSchematicPortPairs&&l._connectedSchematicPortPairs.has(c))return;let u={name:e.source_trace_id,pointsToConnect:[]},h=R3t(e),d=o.filter(({port:X})=>X.schematic_port_id!==null).map(({port:X})=>({port:X,position:X._getGlobalSchematicPositionAfterLayout(),schematic_port_id:X.schematic_port_id??void 0,facingDirection:X.facingDirection}));if(d.length===1&&s.length===1){let X=s[0].net,{port:U,position:tt}=d[0],J=e.getSubcircuit().selectAll("netlabel").find(K=>{let et=K._parsedProps.connection??K._parsedProps.connectsTo;return et?Array.isArray(et)?et.some(mt=>e.getSubcircuit().selectOne(mt,{port:!0})===U):e.getSubcircuit().selectOne(et,{port:!0})===U:!1});if(!J){let K=t.schematic_net_label.getWhere({source_trace_id:e.source_trace_id});K&&(J=K)}if(J){let K="_getGlobalSchematicPositionBeforeLayout"in J?J._getGlobalSchematicPositionBeforeLayout():J.anchor_position,et=[];tt.x===K.x||tt.y===K.y?et.push({from:tt,to:K}):(et.push({from:tt,to:{x:K.x,y:tt.y}}),et.push({from:{x:K.x,y:tt.y},to:K}));let pt=t.schematic_trace.insert({source_trace_id:e.source_trace_id,edges:et,junctions:[],subcircuit_connectivity_map_key:e.subcircuit_connectivity_map_key??void 0});e.schematic_trace_id=pt.schematic_trace_id;return}if(e.props.schDisplayLabel){let K=ym(U.facingDirection)??"bottom";t.schematic_net_label.insert({text:e.props.schDisplayLabel,source_net_id:X.source_net_id,anchor_position:tt,center:xc({anchor_position:tt,anchor_side:K,text:e.props.schDisplayLabel}),anchor_side:K});return}let V=ym(U.facingDirection)??"bottom",rt=t.schematic_net_label.insert({text:X._parsedProps.name,source_net_id:X.source_net_id,anchor_position:tt,center:xc({anchor_position:tt,anchor_side:V,text:X._parsedProps.name}),anchor_side:V});return}if(e.props.schDisplayLabel&&("from"in e.props&&"to"in e.props||"path"in e.props)){e._doInitialSchematicTraceRenderWithDisplayLabel();return}if(d.length<2)return;let g=(()=>{let X=[];for(let tt=0;tt<d.length-1;tt++){let J=d[tt],V=d[tt+1],rt=Qa({x:J.position.x,y:J.position.y,facingDirection:KI(J.facingDirection)},{x:V.position.x,y:V.position.y,facingDirection:KI(V.facingDirection)});for(let K=0;K<rt.length-1;K++)X.push({from:rt[K],to:rt[K+1]})}let U=(tt,J)=>{let V=J.width/2,rt=J.height/2,K=J.center.x-V,et=J.center.x+V,pt=J.center.y-rt,mt=J.center.y+rt,It=lt=>lt.x>=K&<.x<=et&<.y>=pt&<.y<=mt;return It(tt.from)||It(tt.to)?!0:[[{x:K,y:pt},{x:et,y:pt}],[{x:et,y:pt},{x:et,y:mt}],[{x:et,y:mt},{x:K,y:mt}],[{x:K,y:mt},{x:K,y:pt}]].some(lt=>Ka([tt.from,tt.to],lt,{lineThickness:0}))};for(let tt of X)for(let J of h)if(U(tt,J))return null;return X})();g&&g.length===0&&(g=null),u.pointsToConnect=d.map(({position:X})=>({...X,layer:"top"}));let x=y3t(h),w=2,S={minTraceWidth:.1,obstacles:h,connections:[u],bounds:{minX:x.minX-w,maxX:x.maxX+w,minY:x.minY-w,maxY:x.maxY+w},layerCount:1},C=Cg,I=!1;if(e.getSubcircuit().props._schDirectLineRoutingEnabled&&(C=iV,I=!0),!g){let U=new C({input:S,MAX_ITERATIONS:100,OBSTACLE_MARGIN:.1,isRemovePathLoopsEnabled:!0,isShortenPathWithShortcutsEnabled:!0,marginsWithCosts:[{margin:1,enterCost:0,travelCostFactor:1},{margin:.3,enterCost:0,travelCostFactor:1},{margin:.2,enterCost:0,travelCostFactor:2},{margin:.1,enterCost:0,travelCostFactor:3}]}).solveAndMapToTraces();if(U.length===0){if(e._isSymbolToChipConnection()||e._isSymbolToSymbolConnection()||e._isChipToChipConnection()){e._doInitialSchematicTraceRenderWithDisplayLabel();return}U=new iV({input:S}).solveAndMapToTraces(),I=!0}let[{route:tt}]=U;g=[];for(let J=0;J<tt.length-1;J++)g.push({from:tt[J],to:tt[J+1]})}let k=e.source_trace_id,P=[];if(!I){O3t({edges:g,db:t,source_trace_id:k});let X=uM({db:t,source_trace_id:k,differentNetOnly:!0}).flatMap(U=>U.edges);g=E3t({edges:g,otherEdges:X}),P=N3t({edges:g,db:t,source_trace_id:e.source_trace_id})}if(!g||g.length===0)return;let N=g[g.length-1],E=d[d.length-1],A=oV(N);g.push(...WI({lastEdge:N,lastEdgePort:E,lastDominantDirection:A}));let O=g[0],$=d[0],B=oV(O);if(g.unshift(...WI({firstEdge:O,firstEdgePort:$,firstDominantDirection:B})),!e.source_trace_id)throw new Error("Missing source_trace_id for schematic trace insertion.");if(e.getSubcircuit()._parsedProps.schTraceAutoLabelEnabled&&v3t(P,g)>=5&&(e._isSymbolToChipConnection()||e._isSymbolToSymbolConnection()||e._isChipToChipConnection())){e._doInitialSchematicTraceRenderWithDisplayLabel();return}let H=t.schematic_trace.insert({source_trace_id:e.source_trace_id,edges:g,junctions:P,subcircuit_connectivity_map_key:e.subcircuit_connectivity_map_key??void 0});e.schematic_trace_id=H.schematic_trace_id;for(let{port:X}of o)X.schematic_port_id&&t.schematic_port.update(X.schematic_port_id,{is_connected:!0});l?._connectedSchematicPortPairs&&l._connectedSchematicPortPairs.add(c)};function $V(e){let t=0;for(let n=0;n<e.length;n++){let i=e[n];if(i.route_type==="wire"){let r=e[n+1];if(r){let o=r.x-i.x,s=r.y-i.y;t+=Math.sqrt(o*o+s*s)}}else i.route_type==="via"&&(t+=1.6)}return t}var ox=e=>({...e._getGlobalPcbPositionAfterLayout(),layers:e.getAvailablePcbLayers()}),z3t=!1;function D3t(e){if(e.root?.pcbDisabled)return;let{db:t}=e.root,{_parsedProps:n,parent:i}=e,r=e.getSubcircuit();if(!i)throw new Error("Trace has no parent");if(r._parsedProps.routingDisabled)return;let o=r._parsedProps.pcbRouteCache?.pcbTraces;if(o){let A=t.pcb_trace.insert({route:o.flatMap(O=>O.route),source_trace_id:e.source_trace_id,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0});e.pcb_trace_id=A.pcb_trace_id;return}if(n.pcbPath&&n.pcbPath.length>0||!r._shouldUseTraceByTraceRouting())return;let{allPortsFound:s,ports:a}=e._findConnectedPorts(),c=[];if(!s)return;let l=[];for(let A of a)A._hasMatchedPcbPrimitive()||l.push(A);if(l.length>0){t.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:e.source_trace_id,message:`Some ports did not have a matching PCB primitive (e.g. a pad or plated hole), this can happen if a footprint is missing. As a result, ${e} wasn't routed. Missing ports: ${l.map(A=>A.getString()).join(", ")}`,pcb_trace_id:e.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:l.map(A=>A.pcb_port_id).filter(Boolean)});return}let u=e._findConnectedNets().netsWithSelectors;if(a.length===0&&u.length===2){e.renderError("Trace connects two nets, we haven't implemented a way to route this yet");return}else if(a.length===1&&u.length===1){let A=a[0],$=u[0].net.getAllConnectedPorts().filter(H=>H!==A);if($.length===0){console.log("Nothing to connect this port to, the net is empty. TODO should emit a warning!");return}let B=x3t(A,$);c.push(B),a.push(B)}else if(a.length>1&&u.length>=1){e.renderError("Trace has more than one port and one or more nets, we don't currently support this type of complex trace routing");return}let h=a.flatMap(A=>A.matchedComponents.filter(O=>O.componentName==="TraceHint")),d=(e._parsedProps.pcbRouteHints??[]).concat(h.flatMap(A=>A.getPcbRouteHints()));if(a.length>2){e.renderError(`Trace has more than two ports (${a.map(A=>A.getString()).join(", ")}), routing between more than two ports for a single trace is not implemented`);return}if(e.getSubcircuit().selectAll("trace").filter(A=>A.renderPhaseStates.PcbTraceRender.initialized).some(A=>A._portsRoutedOnPcb.length===a.length&&A._portsRoutedOnPcb.every(O=>a.includes(O))))return;let g=[];d.length===0?g=[ox(a[0]),ox(a[1])]:g=[ox(a[0]),...d,ox(a[1])];let x=cx(g);if(z3t&&x.length===0){e.renderError(`Could not find a common layer (using hints) for trace ${e.getString()}`);return}let w=si(e.root.db.toArray()),[S,C]=w3t(()=>lM(e.root.db.toArray()));if(C){e.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:e.pcb_trace_id,message:`Error getting obstacles for autorouting: ${C.message}`,source_trace_id:e.source_trace_id,center:{x:0,y:0},pcb_port_ids:a.map(A=>A.pcb_port_id),pcb_trace_id:e.pcb_trace_id,pcb_component_ids:[]});return}for(let A of S)if(A.connectedTo.length>0){let $=w.getNetConnectedToId(A.connectedTo[0]);$&&A.connectedTo.push($)}let I=[];if(x.length===0)I=g;else{let A=x[0].layer_path;I=g.map((O,$)=>O.via?{...O,via_to_layer:A[$]}:{...O,layers:[A[$]]})}I[0].pcb_port_id=a[0].pcb_port_id,I[I.length-1].pcb_port_id=a[1].pcb_port_id;let k=[];for(let[A,O]of CV(I)){let $="via_to_layer"in A?A.via_to_layer:null,B=2,H="layers"in A&&A.layers.length===1?A.layers[0]:$??"top",X="layers"in O&&O.layers.length===1?O.layers[0]:$??"top",U="pcb_port_id"in A?A.pcb_port_id:null,tt="pcb_port_id"in O?O.pcb_port_id:null,J=e._getExplicitTraceThickness()??e.getSubcircuit()._parsedProps.minTraceWidth??.16,V=new Cg({OBSTACLE_MARGIN:J*2,isRemovePathLoopsEnabled:!0,optimizeWithGoalBoxes:!!(U&&tt),connMap:w,input:{obstacles:S,minTraceWidth:J,connections:[{name:e.source_trace_id,pointsToConnect:[{...A,layer:H,pcb_port_id:U},{...O,layer:X,pcb_port_id:tt}]}],layerCount:e.getSubcircuit()._getSubcircuitLayerCount(),bounds:{minX:Math.min(A.x,O.x)-B,maxX:Math.max(A.x,O.x)+B,minY:Math.min(A.y,O.y)-B,maxY:Math.max(A.y,O.y)+B}}}),rt=null;try{rt=V.solveAndMapToTraces()}catch(pt){e.renderError({type:"pcb_trace_error",pcb_trace_error_id:e.source_trace_id,error_type:"pcb_trace_error",message:`error solving route: ${pt.message}`,source_trace_id:e.pcb_trace_id,center:{x:(A.x+O.x)/2,y:(A.y+O.y)/2},pcb_port_ids:a.map(mt=>mt.pcb_port_id),pcb_trace_id:e.pcb_trace_id,pcb_component_ids:a.map(mt=>mt.pcb_component_id)})}if(!rt)return;if(rt.length===0){e.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:e.pcb_trace_id,message:`Could not find a route for ${e}`,source_trace_id:e.source_trace_id,center:{x:(A.x+O.x)/2,y:(A.y+O.y)/2},pcb_port_ids:a.map(pt=>pt.pcb_port_id),pcb_trace_id:e.pcb_trace_id,pcb_component_ids:a.map(pt=>pt.pcb_component_id)});return}let[K]=rt;$&&(K.route=K.route.map(pt=>(pt.route_type==="wire"&&!pt.layer&&(pt.layer=$),pt))),U&&K.route[0].route_type==="wire"&&(K.route[0].start_pcb_port_id=U);let et=K.route[K.route.length-1];tt&&et.route_type==="wire"&&(et.end_pcb_port_id=tt),k.push(K.route)}let P=g3t(k),N=$V(P),E=t.pcb_trace.insert({route:P,source_trace_id:e.source_trace_id,subcircuit_id:e.getSubcircuit()?.subcircuit_id,trace_length:N});e._portsRoutedOnPcb=a,e.pcb_trace_id=E.pcb_trace_id;for(let A of P)A.route_type==="via"&&t.pcb_via.insert({pcb_trace_id:E.pcb_trace_id,x:A.x,y:A.y,hole_diameter:.3,outer_diameter:.6,layers:[A.from_layer,A.to_layer],from_layer:A.from_layer,to_layer:A.to_layer});e._insertErrorIfTraceIsOutsideBoard(P,a)}function $3t(e){if(e.root?.pcbDisabled)return;let{db:t}=e.root,{_parsedProps:n}=e,i=e.getSubcircuit();if(!n.pcbPath)return;let{allPortsFound:r,ports:o,portsWithSelectors:s}=e._findConnectedPorts();if(!r)return;let a=[];for(let S of o)S._hasMatchedPcbPrimitive()||a.push(S);if(a.length>0){t.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:e.source_trace_id,message:`Some ports did not have a matching PCB primitive (e.g. a pad or plated hole), this can happen if a footprint is missing. As a result, ${e} wasn't routed. Missing ports: ${a.map(S=>S.getString()).join(", ")}`,pcb_trace_id:e.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:a.map(S=>S.pcb_port_id).filter(Boolean)});return}let c;n.pcbPathRelativeTo&&(c=s.find(S=>S.selector===n.pcbPathRelativeTo)?.port,c||(c=e.getSubcircuit().selectOne(n.pcbPathRelativeTo))),c||(c=o[0]);let l=o.find(S=>S!==c)??o[1],u=c.getAvailablePcbLayers()[0]||"top",h=e._getExplicitTraceThickness()??e.getSubcircuit()._parsedProps.minTraceWidth??.16,d=c._getGlobalPcbPositionAfterLayout(),_=l._getGlobalPcbPositionAfterLayout(),y=[];y.push({route_type:"wire",x:d.x,y:d.y,width:h,layer:u,start_pcb_port_id:c.pcb_port_id});let g=c?._computePcbGlobalTransformBeforeLayout?.()||Li();for(let S of n.pcbPath){let C,I=!1;if(typeof S=="string"){let P=e.getSubcircuit().selectOne(S,{type:"port"});if(!P){t.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:e.source_trace_id,message:`Could not resolve pcbPath selector "${S}" for ${e}`,pcb_trace_id:e.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:[]});continue}let N=P._getGlobalPcbPositionAfterLayout();C={x:N.x,y:N.y},I=!0}else C={x:S.x,y:S.y},I=!1;let k=I?C:Ae(g,C);y.push({route_type:"wire",x:k.x,y:k.y,width:h,layer:u})}y.push({route_type:"wire",x:_.x,y:_.y,width:h,layer:u,end_pcb_port_id:l.pcb_port_id});let x=$V(y),w=t.pcb_trace.insert({route:y,source_trace_id:e.source_trace_id,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0,trace_length:x});e._portsRoutedOnPcb=o,e.pcb_trace_id=w.pcb_trace_id,e._insertErrorIfTraceIsOutsideBoard(y,o)}function B3t(e){if(e.root?.schematicDisabled)return;let{db:t}=e.root,{_parsedProps:n,parent:i}=e;if(!i)throw new Error("Trace has no parent");let{allPortsFound:r,portsWithSelectors:o}=e._findConnectedPorts();if(!r)return;let s=o.map(({port:I})=>({port:I,position:I._getGlobalSchematicPositionAfterLayout(),schematic_port_id:I.schematic_port_id,facingDirection:I.facingDirection}));if(s.length<2)throw new Error("Expected at least two ports in portsWithPosition.");let a,c,l=s[0].position,u=s[0].port;if("path"in e.props){if(e.props.path.length!==2)throw new Error("Invalid 'path': Must contain exactly two elements.");[a,c]=e.props.path}else{if(!("from"in e.props&&"to"in e.props))throw new Error("Missing 'from' or 'to' properties in props.");a=e.props.from,c=e.props.to}if(!u.source_port_id)throw new Error(`Missing source_port_id for the 'from' port (${a}).`);let h=s[1].position,d=s[1].port;if(!d.source_port_id)throw new Error(`Missing source_port_id for the 'to' port (${c}).`);let _=t.schematic_net_label.list().find(I=>I.source_net_id===u.source_port_id),y=t.schematic_net_label.list().find(I=>I.source_net_id===d.source_port_id),[g,x]=o.map(({port:I})=>I),S=g.parent?.config.shouldRenderAsSchematicBox?`${g?.parent?.props.name}_${g?.props.name}`:`${x?.parent?.props.name}_${x?.props.name}`,C=e.props.schDisplayLabel??S;if(_&&_.text!==C&&(_.text=`${C} / ${_.text}`),y&&y?.text!==C&&(y.text=`${C} / ${y.text}`),!y){let I=ym(d.facingDirection)??"bottom";t.schematic_net_label.insert({text:e.props.schDisplayLabel??S,source_net_id:d.source_port_id,anchor_position:h,center:xc({anchor_position:h,anchor_side:I,text:e.props.schDisplayLabel??S}),anchor_side:I})}if(!_){let I=ym(u.facingDirection)??"bottom";t.schematic_net_label.insert({text:e.props.schDisplayLabel??S,source_net_id:u.source_port_id,anchor_position:l,center:xc({anchor_position:l,anchor_side:I,text:e.props.schDisplayLabel??S}),anchor_side:I})}}function j3t(e){let{_parsedProps:t,parent:n}=e;if(!n)throw new Error("Trace has no parent");let r=e.getTracePortPathSelectors().map(o=>({selector:o,port:e.getSubcircuit().selectOne(o,{type:"port"})??null}));for(let{selector:o,port:s}of r)if(!s){let a,c,l=o.lastIndexOf(".");if(l!==-1&&l>o.lastIndexOf(" "))a=o.slice(0,l),c=o.slice(l+1);else{let I=o.match(/^(.*[ >])?([^ >]+)$/);a=I?.[1]?.trim()??"",c=I?.[2]??o}let u=a?e.getSubcircuit().selectOne(a):null;if(!u&&a&&!/[.#\[]/.test(a)&&(u=e.getSubcircuit().selectOne(`.${a}`)),!u){let I=a?`Could not find port for selector "${o}". Component "${a}" not found`:`Could not find port for selector "${o}"`,k=e.getSubcircuit(),P=k.getGroup();throw new px({error_type:"source_trace_not_connected_error",message:I,subcircuit_id:k.subcircuit_id??void 0,source_group_id:P?.source_group_id??void 0,source_trace_id:e.source_trace_id??void 0,selectors_not_found:[o]})}let h=u.children.filter(I=>I.componentName==="Port"),d=c.includes(".")?c.split(".").pop()??"":c,_=h.flatMap(I=>I.getNameAndAliases()),y=_.some(I=>!/^(pin\d+|\d+)$/.test(I)),g=Array.from(new Set(_)).join(", "),x;h.length===0?x="It has no ports":y?x=`It has [${g}]`:x=`It has ${h.length} pins and no pinLabels (consider adding pinLabels)`;let w=`Could not find port for selector "${o}". Component "${u.props.name??a}" found, but does not have pin "${d}". ${x}`,S=e.getSubcircuit(),C=S.getGroup();throw new px({error_type:"source_trace_not_connected_error",message:w,subcircuit_id:S.subcircuit_id??void 0,source_group_id:C?.source_group_id??void 0,source_trace_id:e.source_trace_id??void 0,selectors_not_found:[o]})}return r.some(o=>!o.port)?{allPortsFound:!1}:{allPortsFound:!0,portsWithSelectors:r,ports:r.map(({port:o})=>o)}}var ko=class extends xe{constructor(t){super(t);M(this,"source_trace_id",null);M(this,"pcb_trace_id",null);M(this,"schematic_trace_id",null);M(this,"_portsRoutedOnPcb");M(this,"subcircuit_connectivity_map_key",null);M(this,"_traceConnectionHash",null);M(this,"_couldNotFindPort");this._portsRoutedOnPcb=[]}_getExplicitTraceThickness(){return this._parsedProps.thickness??this._parsedProps.width}get config(){return{zodProps:GF,componentName:"Trace"}}_getTracePortOrNetSelectorListFromProps(){return"from"in this.props&&"to"in this.props?[typeof this.props.from=="string"?this.props.from:this.props.from.getPortSelector(),typeof this.props.to=="string"?this.props.to:this.props.to.getPortSelector()]:"path"in this.props?this.props.path.map(t=>typeof t=="string"?t:t.getPortSelector()):[]}getTracePortPathSelectors(){return this._getTracePortOrNetSelectorListFromProps().filter(t=>!t.includes("net."))}getTracePathNetSelectors(){return this._getTracePortOrNetSelectorListFromProps().filter(t=>t.includes("net."))}_findConnectedPorts(){return j3t(this)}_resolveNet(t){let n=this.getSubcircuit().selectOne(t,{type:"net"});if(n)return n;let i=t.match(/^net\.(.+)$/),r=i?i[1]:null;if(!r)return null;let o=this.root?._getBoard();return o?o.getDescendants().find(a=>a.componentName==="Net"&&a._parsedProps.name===r)||null:(this.renderError(`Could not find a <board> ancestor for ${this}, so net "${t}" cannot be resolved`),null)}_findConnectedNets(){let t=this.getTracePathNetSelectors().map(i=>({selector:i,net:this._resolveNet(i)})),n=t.filter(i=>!i.net);return n.length>0&&this.renderError(`Could not find net for selector "${n[0].selector}" inside ${this}`),{netsWithSelectors:t,nets:t.map(i=>i.net)}}_getAllTracesConnectedToSameNet(){let t=this.getSubcircuit().selectAll("trace"),n=this._findConnectedNets().nets,i=this._findConnectedPorts().ports??[];return t.filter(r=>{if(r===this)return!1;let o=r._findConnectedNets().nets,s=r._findConnectedPorts().ports??[];return o.some(a=>n.includes(a))||s.some(a=>i.includes(a))})}_isExplicitlyConnectedToPort(t){let{allPortsFound:n,portsWithSelectors:i}=this._findConnectedPorts();return n?i.map(o=>o.port).includes(t):!1}_isExplicitlyConnectedToNet(t){return this._findConnectedNets().nets.includes(t)}doInitialCreateNetsFromProps(){sM(this,this.getTracePathNetSelectors())}_computeTraceConnectionHash(){let{allPortsFound:t,ports:n}=this._findConnectedPorts();return!t||!n?null:[...n].sort((o,s)=>(o.pcb_port_id||"").localeCompare(s.pcb_port_id||"")).map(o=>o.pcb_port_id).join(",")}doInitialSourceTraceRender(){let{db:t}=this.root,{_parsedProps:n,parent:i}=this;if(!i){this.renderError("Trace has no parent");return}let r,o;try{let h=this._findConnectedPorts();r=h.allPortsFound,o=h.portsWithSelectors??[]}catch(h){if(h instanceof px){t.source_trace_not_connected_error.insert({...h.errorData,error_type:"source_trace_not_connected_error"}),this._couldNotFindPort=!0;return}throw h}if(!r)return;this._traceConnectionHash=this._computeTraceConnectionHash();let a=t.source_trace.list().find(h=>h.subcircuit_connectivity_map_key===this.subcircuit_connectivity_map_key&&h.connected_source_port_ids.sort().join(",")===this._traceConnectionHash);if(a){this.source_trace_id=a.source_trace_id;return}let c=this._findConnectedNets().nets,l=P3t({ports:o,nets:c}),u=t.source_trace.insert({connected_source_port_ids:o.map(h=>h.port.source_port_id),connected_source_net_ids:c.map(h=>h.source_net_id),subcircuit_id:this.getSubcircuit()?.subcircuit_id,max_length:S3t(o.map(h=>h.port),{db:t})??n.maxLength,display_name:l,min_trace_thickness:this._getExplicitTraceThickness()});this.source_trace_id=u.source_trace_id}_insertErrorIfTraceIsOutsideBoard(t,n){let{db:i}=this.root;T3t(t,{db:i})&&i.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:this.source_trace_id,message:`Trace ${this.getString()} routed outside the board boundaries.`,pcb_trace_id:this.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:n.map(o=>o.pcb_port_id)})}doInitialPcbManualTraceRender(){$3t(this)}doInitialPcbTraceRender(){D3t(this)}_doInitialSchematicTraceRenderWithDisplayLabel(){B3t(this)}_isSymbolToChipConnection(){let{allPortsFound:t,ports:n}=this._findConnectedPorts();if(!t||n.length!==2)return!1;let[i,r]=n;if(!i?.parent||!r?.parent)return!1;let o=i.parent.config.shouldRenderAsSchematicBox,s=r.parent.config.shouldRenderAsSchematicBox;return o&&!s||!o&&s}_isSymbolToSymbolConnection(){let{allPortsFound:t,ports:n}=this._findConnectedPorts();if(!t||n.length!==2)return!1;let[i,r]=n;if(!i?.parent||!r?.parent)return!1;let o=!i.parent.config.shouldRenderAsSchematicBox,s=!r.parent.config.shouldRenderAsSchematicBox;return o&&s}_isChipToChipConnection(){let{allPortsFound:t,ports:n}=this._findConnectedPorts();if(!t||n.length!==2)return!1;let[i,r]=n;if(!i?.parent||!r?.parent)return!1;let o=i.parent.config.shouldRenderAsSchematicBox,s=r.parent.config.shouldRenderAsSchematicBox;return o&&s}doInitialSchematicTraceRender(){F3t(this)}},Y3t=e=>{let{db:t}=e.root;if(e.pcb_component_id){let n=t.pcb_component.get(e.pcb_component_id);return n?{width:n.width,height:n.height}:null}if(e.pcb_group_id){let n=t.pcb_group.get(e.pcb_group_id);if(!n)return null;if(n.outline&&n.outline.length>0){let i=qo(n.outline);return i?{width:i.maxX-i.minX,height:i.maxY-i.minY}:null}return{width:n.width??0,height:n.height??0}}return null},X3t=(e,t)=>{let{db:n}=e.root,i=n.toArray();if(e.pcb_component_id){Yg(i,e.pcb_component_id,t);return}if(e.source_group_id){Xg(i,e.source_group_id,t);return}throw new Error(`Cannot reposition component ${e.getString()}: no pcb_component_id or source_group_id`)},V3t=e=>{let{db:t}=e.root;if(!e.source_component_id)return;let n=e.selectAll("port"),i=t.source_trace.list(),r=new Set;for(let s of i)for(let a of s.connected_source_port_ids)r.add(a);let o=e._getInternallyConnectedPins();for(let s of o)if(s.some(a=>a.source_port_id&&r.has(a.source_port_id)))for(let a of s)a.source_port_id&&r.add(a.source_port_id);for(let s of n)s.source_port_id&&H3t(e,s)&&(r.has(s.source_port_id)||t.source_pin_missing_trace_warning.insert({message:`Port ${s.getNameAndAliases()[0]} on ${e.props.name} is missing a trace`,source_component_id:e.source_component_id,source_port_id:s.source_port_id,subcircuit_id:e.getSubcircuit().subcircuit_id??void 0,warning_type:"source_pin_missing_trace_warning"}))},H3t=(e,t)=>{if(e.config.componentName==="Chip"){let n=e.props.pinAttributes;if(!n)return!1;for(let i of t.getNameAndAliases()){let r=n[i];if(r?.requiresPower||r?.requiresGround||r?.requiresVoltage!==void 0)return!0}return!1}return!0};function G3t(e){let t=e.font_size,n=e.text.length*t*.6,i=t,r=e.anchor_alignment||"center",o=e.anchor_position.x,s=e.anchor_position.y;switch(r){case"top_left":o=e.anchor_position.x+n/2,s=e.anchor_position.y+i/2;break;case"top_center":o=e.anchor_position.x,s=e.anchor_position.y+i/2;break;case"top_right":o=e.anchor_position.x-n/2,s=e.anchor_position.y+i/2;break;case"center_left":o=e.anchor_position.x+n/2,s=e.anchor_position.y;break;case"center":o=e.anchor_position.x,s=e.anchor_position.y;break;case"center_right":o=e.anchor_position.x-n/2,s=e.anchor_position.y;break;case"bottom_left":o=e.anchor_position.x+n/2,s=e.anchor_position.y-i/2;break;case"bottom_center":o=e.anchor_position.x,s=e.anchor_position.y-i/2;break;case"bottom_right":o=e.anchor_position.x-n/2,s=e.anchor_position.y-i/2;break;default:o=e.anchor_position.x,s=e.anchor_position.y;break}return{x:o-n/2,y:s-i/2,width:n,height:i}}function U3t(e){if(!e._adjustSilkscreenTextAutomatically||e.root?.pcbDisabled||!e.pcb_component_id)return;let{db:t}=e.root,i=e._getPcbCircuitJsonBounds().center,r=t.pcb_silkscreen_text.list({pcb_component_id:e.pcb_component_id}).filter(c=>c.text===e.name);if(r.length===0)return;let a=e.getSubcircuit().selectAll("[_isNormalComponent=true]").filter(c=>c!==e&&c.pcb_component_id).map(c=>{let l=c._getPcbCircuitJsonBounds(),u={center:l.center,width:l.width,height:l.height};return Mo(u)});for(let c of r){let l=c.anchor_position,u=G3t(c),h={center:{x:u.x+u.width/2,y:u.y+u.height/2},width:u.width,height:u.height},d=Mo(h);if(!a.some(C=>Ja(d,C)))continue;let y=2*i.x-l.x,g=2*i.y-l.y,x={center:{x:y,y:g},width:u.width,height:u.height},w=Mo(x);a.some(C=>Ja(w,C))||t.pcb_silkscreen_text.update(c.pcb_silkscreen_text_id,{anchor_position:{x:y,y:g}})}}function q3t(e){if(!e)return{validPinLabels:e,invalidPinLabelsMessages:[]};let t={},n=[];for(let[i,r]of Object.entries(e)){let o=Array.isArray(r)?r.slice():[r],s=[];for(let a of o)W3t(i,a)?s.push(a):n.push(`Invalid pin label: ${i} = '${a}' - excluding from component. Please use a valid pin label.`);s.length>0&&(t[i]=Array.isArray(r)?s:s[0])}return{validPinLabels:Object.keys(t).length>0?t:void 0,invalidPinLabelsMessages:n}}function W3t(e,t){try{let n={name:"test",footprint:"test",pinLabels:{[e]:t}};return Bp.safeParse(n).success}catch{return!1}}var Nh=e=>e.startsWith("http://")||e.startsWith("https://"),QI=e=>{if(Nh(e))return null;let t=e.indexOf(":");if(t<=0)return null;let n=e.slice(0,t),i=e.slice(t+1);return!n||!i?null:{footprintLib:n,footprintName:i}},tM=e=>e.startsWith("/");function Z3t(e,t){let{footprint:n}=e.props;if(n??(n=e._getImpliedFootprintString?.()),!n)return;let{pcbRotation:i,pinLabels:r,pcbPinLabels:o}=e.props,s=OV(String(n)),a=s?e.root?.platform?.footprintFileParserMap?.[s]:null;if(typeof n=="string"&&(Nh(n)||tM(n))&&a){if(e._hasStartedFootprintUrlLoad)return;e._hasStartedFootprintUrlLoad=!0;let c=e.root?.platform?.projectBaseUrl,l=Nh(n)?n:LV(n,c);t("load-footprint-from-platform-file-parser",async()=>{try{let u=await a.loadFromUrl(l),h=lm({componentName:e.name,componentRotation:i,footprint:l,pinLabels:r,pcbPinLabels:o},u.footprintCircuitJson);e.addAll(h),e._markDirty("InitializePortsFromChildren")}catch(u){let h=e.root?.db;if(h&&e.source_component_id&&e.pcb_component_id){let d=e.getSubcircuit(),_=`${e.getString()} failed to load footprint "${l}": `+(u instanceof Error?u.message:String(u)),y=gp.parse({type:"external_footprint_load_error",message:_,pcb_component_id:e.pcb_component_id,source_component_id:e.source_component_id,subcircuit_id:d.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0,footprinter_string:l});h.external_footprint_load_error.insert(y)}throw u}});return}if(typeof n=="string"&&Nh(n)){if(e._hasStartedFootprintUrlLoad)return;e._hasStartedFootprintUrlLoad=!0;let c=n;t("load-footprint-url",async()=>{try{let l=await fetch(c);if(!l.ok)throw new Error(`Failed to fetch footprint: ${l.status}`);let u=await l.json(),h=lm({componentName:e.name,componentRotation:i,footprint:c,pinLabels:r,pcbPinLabels:o},u);e.addAll(h),e._markDirty("InitializePortsFromChildren")}catch(l){let u=e.root?.db;if(u&&e.source_component_id&&e.pcb_component_id){let h=e.getSubcircuit(),d=`${e.getString()} failed to load external footprint "${c}": `+(l instanceof Error?l.message:String(l)),_=gp.parse({type:"external_footprint_load_error",message:d,pcb_component_id:e.pcb_component_id,source_component_id:e.source_component_id,subcircuit_id:h.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0,footprinter_string:c});u.external_footprint_load_error.insert(_)}throw l}});return}if(typeof n=="string"){let c=QI(n);if(!c||e._hasStartedFootprintUrlLoad)return;e._hasStartedFootprintUrlLoad=!0;let u=e.root?.platform?.footprintLibraryMap?.[c.footprintLib],h;if(typeof u=="function"&&(h=u),!h)return;t("load-lib-footprint",async()=>{try{let d=await h(c.footprintName),_=null;if(Array.isArray(d)?_=d:Array.isArray(d.footprintCircuitJson)&&(_=d.footprintCircuitJson),!_)return;let y=lm({componentName:e.name,componentRotation:i,footprint:n,pinLabels:r,pcbPinLabels:o},_);e.addAll(y),!Array.isArray(d)&&d.cadModel&&(e._asyncFootprintCadModel=d.cadModel);for(let g of e.children)g.componentName==="Port"&&g._markDirty?.("PcbPortRender");e._markDirty("InitializePortsFromChildren")}catch(d){let _=e.root?.db;if(_&&e.source_component_id&&e.pcb_component_id){let y=e.getSubcircuit(),g=`${e.getString()} failed to load external footprint "${n}": `+(d instanceof Error?d.message:String(d)),x=gp.parse({type:"external_footprint_load_error",message:g,pcb_component_id:e.pcb_component_id,source_component_id:e.source_component_id,subcircuit_id:y.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0,footprinter_string:n});_.external_footprint_load_error.insert(x)}throw d}});return}if(!(0,JI.isValidElement)(n)&&n.componentName==="Footprint"&&e.add(n),Array.isArray(n)&&!(0,JI.isValidElement)(n)&&n.length>0){try{let c=lm({componentName:e.name,componentRotation:i,footprint:"",pinLabels:r,pcbPinLabels:o},n);e.addAll(c)}catch(c){let l=e.root?.db;if(l&&e.source_component_id&&e.pcb_component_id){let u=e.getSubcircuit(),h=`${e.getString()} failed to load json footprint: `+(c instanceof Error?c.message:String(c)),d=h_.parse({type:"circuit_json_footprint_load_error",message:h,pcb_component_id:e.pcb_component_id,source_component_id:e.source_component_id,subcircuit_id:u.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0});l.circuit_json_footprint_load_error.insert(d)}throw c}return}}function K3t(e){if(e.root?.pcbDisabled||!e.pcb_component_id)return;let{pcbX:t,pcbY:n}=e._parsedProps,i=e.props?.pcbPositionAnchor;if(!i||t===void 0&&n===void 0)return;let r=mx(e.children);if(r.width===0||r.height===0)return;let s={...{x:(r.minX+r.maxX)/2,y:(r.minY+r.maxY)/2}},a=null;if(new Set(["center","top_left","top_center","top_right","center_left","center_right","bottom_left","bottom_center","bottom_right"]).has(i)){let u={left:r.minX,right:r.maxX,top:r.minY,bottom:r.maxY};switch(i){case"center":a=s;break;case"top_left":a={x:u.left,y:u.top};break;case"top_center":a={x:s.x,y:u.top};break;case"top_right":a={x:u.right,y:u.top};break;case"center_left":a={x:u.left,y:s.y};break;case"center_right":a={x:u.right,y:s.y};break;case"bottom_left":a={x:u.left,y:u.bottom};break;case"bottom_center":a={x:s.x,y:u.bottom};break;case"bottom_right":a={x:u.right,y:u.bottom};break}}else try{let u=e.portMap[i];u&&(a=u._getGlobalPcbPositionBeforeLayout())}catch{}if(!a)return;let l={...s};t!==void 0&&(l.x+=t-a.x),n!==void 0&&(l.y+=n-a.y),(Math.abs(l.x-s.x)>1e-6||Math.abs(l.y-s.y)>1e-6)&&e._repositionOnPcb(l)}var J3t=(0,SV.default)("tscircuit:core"),Q3t=p.object({x:$e,y:$e,z:$e}),On=class extends xe{constructor(t){let n={...t},i=[];if(n.pinLabels&&!Array.isArray(n.pinLabels)){let{validPinLabels:r,invalidPinLabelsMessages:o}=q3t(n.pinLabels);n.pinLabels=r,i=o}super(n);M(this,"reactSubtrees",[]);M(this,"_impliedFootprint");M(this,"isPrimitiveContainer",!0);M(this,"_isNormalComponent",!0);M(this,"_attributeLowerToCamelNameMap",{_isnormalcomponent:"_isNormalComponent"});M(this,"_asyncSupplierPartNumbers");M(this,"_asyncFootprintCadModel");M(this,"_isCadModelChild");M(this,"pcb_missing_footprint_error_id");M(this,"_hasStartedFootprintUrlLoad",!1);M(this,"_invalidPinLabelMessages",[]);M(this,"_adjustSilkscreenTextAutomatically",!1);this._invalidPinLabelMessages=i,this._addChildrenFromStringFootprint(),this.initPorts()}get defaultInternallyConnectedPinNames(){return[]}get internallyConnectedPinNames(){return(this._parsedProps.internallyConnectedPins??this.defaultInternallyConnectedPinNames).map(n=>n.map(i=>typeof i=="number"?`pin${i}`:i))}doInitialSourceNameDuplicateComponentRemoval(){if(!this.name)return;let t=this.root;if(this.getSubcircuit().selectAll(`.${this.name}`).filter(r=>r!==this&&r._isNormalComponent&&r.renderPhaseStates?.SourceNameDuplicateComponentRemoval?.initialized).length>0){let r=this._getGlobalPcbPositionBeforeLayout(),o=this._getGlobalSchematicPositionBeforeLayout();t.db.source_failed_to_create_component_error.insert({component_name:this.name,error_type:"source_failed_to_create_component_error",message:`Cannot create component "${this.name}": A component with the same name already exists`,pcb_center:r,schematic_center:o}),this.shouldBeRemoved=!0;let s=[...this.children];for(let a of s)this.remove(a)}}initPorts(t={}){if(this.root?.schematicDisabled)return;let{config:n}=this,i=[],r=this._getSchematicPortArrangement();if(r&&!this._parsedProps.pinLabels){for(let l in r){let u=r[l].pins;if(Array.isArray(u))for(let h of u){let d=_m(h,this._parsedProps.pinLabels);i.push(new ji({pinNumber:d,aliases:t.additionalAliases?.[`pin${d}`]??[]},{originDescription:`schPortArrangement:${l}`}))}}let a=["left","right","top","bottom"],c=1;for(let l of a){let u=r[`${l}Size`];for(let h=0;h<u;h++)i.push(new ji({pinNumber:c++,aliases:t.additionalAliases?.[`pin${c}`]??[]},{originDescription:`schPortArrangement:${l}`}))}}let o=this._parsedProps.pinLabels;if(o)for(let[a,c]of Object.entries(o)){a=a.replace("pin","");let l=i.find(d=>d._parsedProps.pinNumber===Number(a)),u=Array.isArray(c)?c[0]:c,h=Array.isArray(c)?c.slice(1):[];l?(l.externallyAddedAliases.push(u,...h),l.props.name=u):(l=new ji({pinNumber:parseInt(a),name:u,aliases:[...h,...t.additionalAliases?.[`pin${parseInt(a)}`]??[]]},{originDescription:`pinLabels:pin${a}`}),i.push(l))}if(n.schematicSymbolName&&!t.ignoreSymbolPorts){let a=Qn[this._getSchematicSymbolNameOrThrow()];if(!a)return;for(let c of a.ports){let l=kV(c.labels);if(!l)continue;let u=i.find(h=>h._parsedProps.pinNumber===Number(l));if(u)u.schematicSymbolPortDef=c;else{let h=cm(c.labels.concat(t.additionalAliases?.[`pin${l}`]??[]));h&&(h.originDescription=`schematicSymbol:labels[0]:${c.labels[0]}`,h.schematicSymbolPortDef=c,i.push(h))}}this.addAll(i)}if(!this._getSchematicPortArrangement()){let a=this.getPortsFromFootprint(t);for(let c of a)i.some(l=>l.isMatchingAnyOf(c.getNameAndAliases()))||i.push(c)}let s=t.pinCount??this._getPinCount()??0;for(let a=1;a<=s;a++){if(i.find(l=>l._parsedProps.pinNumber===a))continue;if(!r){i.push(new ji({pinNumber:a,aliases:t.additionalAliases?.[`pin${a}`]??[]}));continue}let c=[...r.leftSide?.pins??[],...r.rightSide?.pins??[],...r.topSide?.pins??[],...r.bottomSide?.pins??[]].map(l=>_m(l,this._parsedProps.pinLabels));["leftSize","rightSize","topSize","bottomSize","leftPinCount","rightPinCount","topPinCount","bottomPinCount"].some(l=>l in r)&&(c=Array.from({length:this._getPinCount()},(l,u)=>u+1)),c.includes(a)&&i.push(new ji({pinNumber:a,aliases:t.additionalAliases?.[`pin${a}`]??[]},{originDescription:`notOtherwiseAddedButDeducedFromPinCount:${a}`}))}i.length>0&&this.addAll(i)}_getImpliedFootprintString(){return null}_addChildrenFromStringFootprint(){let{pcbRotation:t,pinLabels:n,pcbPinLabels:i}=this.props,{footprint:r}=this.props;if(r??(r=this._getImpliedFootprintString?.()),!!r&&typeof r=="string"){if(Nh(r)||tM(r)||QI(r))return;let o=ww.string(r).soup(),s=lm({componentName:this.name??this.componentName,componentRotation:t,footprint:r,pinLabels:n,pcbPinLabels:i},o);this.addAll(s)}}get portMap(){return new Proxy({},{get:(t,n)=>{let i=this.children.find(r=>r.componentName==="Port"&&r.isMatchingNameOrAlias(n));if(!i)throw new Error(`There was an issue finding the port "${n.toString()}" inside of a ${this.componentName} component with name: "${this.props.name}". This is a bug in @tscircuit/core`);return i}})}getInstanceForReactElement(t){for(let n of this.reactSubtrees)if(n.element===t)return n.component;return null}doInitialSourceRender(){let t=this.config.sourceFtype;if(!t)return;let{db:n}=this.root,{_parsedProps:i}=this,r=n.source_component.insert({ftype:t,name:this.name,manufacturer_part_number:i.manufacturerPartNumber??i.mfn,supplier_part_numbers:i.supplierPartNumbers});this.source_component_id=r.source_component_id}doInitialSchematicComponentRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root;if(this._invalidPinLabelMessages?.length&&this.root?.db)for(let o of this._invalidPinLabelMessages){let s="pinLabels",a=o.match(/^Invalid pin label:\s*([^=]+)=\s*'([^']+)'/);a&&(s=`pinLabels['${a[2]}']`),this.root.db.source_property_ignored_warning.insert({source_component_id:this.source_component_id,property_name:s,message:o,error_type:"source_property_ignored_warning"})}let{schematicSymbolName:n}=this.config,{_parsedProps:i}=this;i.symbol&&(0,na.isValidElement)(i.symbol)?this._doInitialSchematicComponentRenderWithReactSymbol(i.symbol):n?this._doInitialSchematicComponentRenderWithSymbol():this._getSchematicBoxDimensions()&&this._doInitialSchematicComponentRenderWithSchematicBoxDimensions();let r=this.getSubcircuit()?._getSchematicManualPlacementForComponent(this);if(this.schematic_component_id&&(this.props.schX!==void 0||this.props.schY!==void 0)&&r){if(!this.schematic_component_id)return;let o=u_.parse({type:"schematic_manual_edit_conflict_warning",schematic_manual_edit_conflict_warning_id:`schematic_manual_edit_conflict_${this.source_component_id}`,message:`${this.getString()} has both manual placement and prop coordinates. schX and schY will be used. Remove schX/schY or clear the manual placement.`,schematic_component_id:this.schematic_component_id,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id});t.schematic_manual_edit_conflict_warning.insert(o)}}_getSchematicSymbolDisplayValue(){}_getInternallyConnectedPins(){if(this.internallyConnectedPinNames.length===0)return[];let t=[];for(let n of this.internallyConnectedPinNames){let i=[];for(let r of n)i.push(this.portMap[r]);t.push(i)}return t}_doInitialSchematicComponentRenderWithSymbol(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getSchematicSymbolNameOrThrow(),r=Qn[i],o=this._getGlobalSchematicPositionBeforeLayout();if(r){let s=t.schematic_component.insert({center:o,size:r.size,source_component_id:this.source_component_id,is_box_with_pins:!0,symbol_name:i,symbol_display_value:this._getSchematicSymbolDisplayValue()});this.schematic_component_id=s.schematic_component_id}}_doInitialSchematicComponentRenderWithReactSymbol(t){if(this.root?.schematicDisabled)return;let{db:n}=this.root,i=this._getGlobalSchematicPositionBeforeLayout(),r=n.schematic_component.insert({center:i,size:{width:0,height:0},source_component_id:this.source_component_id,symbol_display_value:this._getSchematicSymbolDisplayValue(),is_box_with_pins:!1});this.schematic_component_id=r.schematic_component_id}_doInitialSchematicComponentRenderWithSchematicBoxDimensions(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getSchematicBoxDimensions(),r={};if(Array.isArray(n.pinLabels))n.pinLabels.forEach((_,y)=>{r[String(y+1)]=_});else for(let[_,y]of Object.entries(n.pinLabels??{}))r[_]=Array.isArray(y)?y[0]:y;let o=this._getGlobalSchematicPositionBeforeLayout(),s=this._getSchematicPortArrangement(),a=t.schematic_component.insert({center:o,rotation:n.schRotation??0,size:i.getSize(),port_arrangement:n3t(s),pin_spacing:n.schPinSpacing??.2,pin_styles:e3t(n.schPinStyle,n.pinLabels),port_labels:r,source_component_id:this.source_component_id}),c=s?.topSide!==void 0||s?.bottomSide!==void 0,l=i?.getSize().width,u=i?.getSize().height,h=t.schematic_text.insert({text:n.manufacturerPartNumber??"",schematic_component_id:a.schematic_component_id,anchor:"left",rotation:0,position:{x:c?o.x+(l??0)/2+.1:o.x-(l??0)/2,y:c?o.y+(u??0)/2+.35:o.y-(u??0)/2-.13},color:"#006464",font_size:.18}),d=t.schematic_text.insert({text:n.name??"",schematic_component_id:a.schematic_component_id,anchor:"left",rotation:0,position:{x:c?o.x+(l??0)/2+.1:o.x-(l??0)/2,y:c?o.y+(u??0)/2+.55:o.y+(u??0)/2+.13},color:"#006464",font_size:.18});this.schematic_component_id=a.schematic_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit(),r=n.layer??"top";if(r!=="top"&&r!=="bottom"){let h=bp.parse({type:"pcb_component_invalid_layer_error",message:`Component cannot be placed on layer '${r}'. Components can only be placed on 'top' or 'bottom' layers.`,source_component_id:this.source_component_id,layer:r,subcircuit_id:i.subcircuit_id??void 0});t.pcb_component_invalid_layer_error.insert(h)}let o=this._computePcbGlobalTransformBeforeLayout(),a=To(o).rotation.angle*180/Math.PI,c=t.pcb_component.insert({center:this._getGlobalPcbPositionBeforeLayout(),width:0,height:0,layer:r==="top"||r==="bottom"?r:"top",rotation:n.pcbRotation??a,source_component_id:this.source_component_id,subcircuit_id:i.subcircuit_id??void 0,do_not_place:n.doNotPlace??!1,obstructs_within_bounds:n.obstructsWithinBounds??!0});if(!(n.footprint??this._getImpliedFootprintString())&&!this.isGroup){let h=t.pcb_missing_footprint_error.insert({message:`No footprint found for component: ${this.getString()}`,source_component_id:`${this.source_component_id}`,error_type:"pcb_missing_footprint_error"});this.pcb_missing_footprint_error_id=h.pcb_missing_footprint_error_id}this.pcb_component_id=c.pcb_component_id;let u=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if((this.props.pcbX!==void 0||this.props.pcbY!==void 0)&&u){let h=d_.parse({type:"pcb_manual_edit_conflict_warning",pcb_manual_edit_conflict_warning_id:`pcb_manual_edit_conflict_${this.source_component_id}`,message:`${this.getString()} has both manual placement and prop coordinates. pcbX and pcbY will be used. Remove pcbX/pcbY or clear the manual placement.`,pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,subcircuit_id:i.subcircuit_id??void 0});t.pcb_manual_edit_conflict_warning.insert(h)}}doInitialPcbComponentSizeCalculation(){if(this.root?.pcbDisabled||!this.pcb_component_id)return;let{db:t}=this.root,{_parsedProps:n}=this,i=mx(this.children);if(i.width===0||i.height===0)return;let r={x:(i.minX+i.maxX)/2,y:(i.minY+i.maxY)/2};t.pcb_component.update(this.pcb_component_id,{center:r,width:i.width,height:i.height})}updatePcbComponentSizeCalculation(){this.doInitialPcbComponentSizeCalculation()}doInitialSchematicComponentSizeCalculation(){if(this.root?.schematicDisabled||!this.schematic_component_id)return;let{db:t}=this.root;if(!t.schematic_component.get(this.schematic_component_id))return;let i=[],r=u=>{for(let h of u){if(h.isSchematicPrimitive&&h.componentName==="SchematicLine"){let d=t.schematic_line.get(h.schematic_line_id);d&&i.push(d)}if(h.isSchematicPrimitive&&h.componentName==="SchematicRect"){let d=t.schematic_rect.get(h.schematic_rect_id);d&&i.push(d)}if(h.isSchematicPrimitive&&h.componentName==="SchematicCircle"){let d=t.schematic_circle.get(h.schematic_circle_id);d&&i.push(d)}if(h.isSchematicPrimitive&&h.componentName==="SchematicArc"){let d=t.schematic_arc.get(h.schematic_arc_id);d&&i.push(d)}if(h.isSchematicPrimitive&&h.componentName==="SchematicText"){let d=t.schematic_text.get(h.schematic_text_id);d&&i.push(d)}h.children&&h.children.length>0&&r(h.children)}};if(r(this.children),i.length===0)return;let o=EV(i),s=Math.abs(o.maxX-o.minX),a=Math.abs(o.maxY-o.minY);if(s===0&&a===0)return;let c=(o.minX+o.maxX)/2,l=(o.minY+o.maxY)/2;t.schematic_component.update(this.schematic_component_id,{center:{x:c,y:l},size:{width:s,height:a}})}updateSchematicComponentSizeCalculation(){this.doInitialSchematicComponentSizeCalculation()}doInitialPcbComponentAnchorAlignment(){K3t(this)}updatePcbComponentAnchorAlignment(){this.doInitialPcbComponentAnchorAlignment()}_renderReactSubtree(t){let n=MV(t);return{element:t,component:n}}doInitialInitializePortsFromChildren(){this.initPorts()}doInitialReactSubtreesRender(){let t=this.props.footprint;(0,na.isValidElement)(t)&&(this.children.some(o=>o.componentName==="Footprint")||this.add(t));let n=this.props.symbol;(0,na.isValidElement)(n)&&(this.children.some(o=>o.componentName==="Symbol")||this.add(n));let i=this.props.cadModel;if((0,na.isValidElement)(i)){this._isCadModelChild=!0;let r=this.children.some(s=>s.componentName==="CadAssembly"),o=this.children.some(s=>s.componentName==="CadModel");!r&&!o&&this.add(i)}}doInitialPcbFootprintStringRender(){Z3t(this,(t,n)=>this._queueAsyncEffect(t,n))}_hasExistingPortExactly(t){return this.children.filter(i=>i.componentName==="Port").some(i=>{let r=t.getNameAndAliases(),o=i.getNameAndAliases();return r.length===o.length&&r.every(s=>o.includes(s))})}add(t){let n;if((0,na.isValidElement)(t)){let i=this._renderReactSubtree(t);this.reactSubtrees.push(i),n=i.component}else n=t;if(n.componentName==="Port"){if(this._hasExistingPortExactly(n))return;let r=this.children.filter(o=>o.componentName==="Port").find(o=>o.isMatchingAnyOf(n.getNameAndAliases()));r&&J3t(`Similar ports added. Port 1: ${r}, Port 2: ${n}`)}super.add(n)}getPortsFromFootprint(t){let{footprint:n}=this.props;if((!n||(0,na.isValidElement)(n))&&(n=this.children.find(r=>r.componentName==="Footprint")),typeof n=="string"){if(Nh(n))return[];if(tM(n))return[];if(QI(n))return[];let r=ww.string(n).soup(),o=[];for(let s of r)if("port_hints"in s&&s.port_hints){let a=cm(s.port_hints,t);if(!a)continue;a.originDescription=`footprint:string:${n}:port_hints[0]:${s.port_hints[0]}`,o.push(a)}return o}if(!(0,na.isValidElement)(n)&&n&&n.componentName==="Footprint"){let r=n,o=1,s=[];for(let a of r.children){if(!a.props.portHints)continue;let c=a.props.portHints;c.some(h=>h.startsWith("pin"))||(c=[...c,`pin${o}`]),o++;let u=cm(c);u&&(u.originDescription=`footprint:${n}`,s.push(u))}return s}let i=[];if(!n){for(let r of this.children)if(r.props.portHints&&r.isPcbPrimitive){let o=cm(r.props.portHints);o&&i.push(o)}}return i}getPortsFromSchematicSymbol(){if(this.root?.schematicDisabled)return[];let{config:t}=this;if(!t.schematicSymbolName)return[];let n=Qn[t.schematicSymbolName];if(!n)return[];let i=[];for(let r of n.ports){let o=cm(r.labels);o&&(o.schematicSymbolPortDef=r,i.push(o))}return i}doInitialCreateNetsFromProps(){this._createNetsFromProps(this._getNetsFromConnectionsProp())}_getNetsFromConnectionsProp(){let{_parsedProps:t}=this,n=[];if(t.connections)for(let[i,r]of Object.entries(t.connections)){let o=Array.isArray(r)?r:[r];for(let s of o)n.push(String(s))}return n}_createNetsFromProps(t){sM(this,t)}_getPcbCircuitJsonBounds(){let{db:t}=this.root;if(!this.pcb_component_id)return super._getPcbCircuitJsonBounds();let n=t.pcb_component.get(this.pcb_component_id);return{center:{x:n.center.x,y:n.center.y},bounds:{left:n.center.x-n.width/2,top:n.center.y-n.height/2,right:n.center.x+n.width/2,bottom:n.center.y+n.height/2},width:n.width,height:n.height}}_getPinCountFromSchematicPortArrangement(){let t=this._getSchematicPortArrangement();if(!t)return 0;if(!NV(t))return(t.leftSize??t.leftPinCount??0)+(t.rightSize??t.rightPinCount??0)+(t.topSize??t.topPinCount??0)+(t.bottomSize??t.bottomPinCount??0);let{leftSide:i,rightSide:r,topSide:o,bottomSide:s}=t;return Math.max(...i?.pins??[],...r?.pins??[],...o?.pins??[],...s?.pins??[])}_getPinCount(){if(this._getSchematicPortArrangement())return this._getPinCountFromSchematicPortArrangement();let n=this.getPortsFromFootprint();if(n.length>0)return n.length;let{pinLabels:i}=this._parsedProps;if(i){if(Array.isArray(i))return i.length;let r=Object.keys(i).map(o=>o.startsWith("pin")?parseInt(o.slice(3)):parseInt(o)).filter(o=>!Number.isNaN(o));return r.length>0?Math.max(...r):Object.keys(i).length}return 0}_getSchematicPortArrangement(){return this._parsedProps.schPinArrangement??this._parsedProps.schPortArrangement}_getSchematicBoxDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;let{_parsedProps:t}=this,n=this._getPinCount(),i=t.schPinSpacing??.2;return d3t({schWidth:t.schWidth,schHeight:t.schHeight,schPinSpacing:i,numericSchPinStyle:_3t(t.schPinStyle,t.pinLabels),pinCount:n,schPortArrangement:this._getSchematicPortArrangement(),pinLabels:t.pinLabels})}getFootprinterString(){return typeof this._parsedProps.footprint=="string"?this._parsedProps.footprint:null}doInitialCadModelRender(){if(this._isCadModelChild||this.props.doNotPlace)return;let{db:t}=this.root,{boardThickness:n=0}=this.root?._getBoard()??{},i=this._parsedProps.cadModel,r=i===void 0?this._asyncFootprintCadModel:i,o=this.getFootprinterString()??this._getImpliedFootprintString();if(!this.pcb_component_id||!r&&!o||r===null)return;let s=this._getPcbCircuitJsonBounds();if(typeof r=="string")throw new Error("String cadModel not yet implemented");let a=Q3t.parse({x:0,y:0,z:typeof r?.rotationOffset=="number"?r.rotationOffset:0,...typeof r?.rotationOffset=="object"?r.rotationOffset??{}:{}}),c=dl.parse({x:0,y:0,z:0,...typeof r?.positionOffset=="object"?r.positionOffset:{}}),l=r&&typeof r=="object"&&"zOffsetFromSurface"in r&&r.zOffsetFromSurface!==void 0?Y.parse(r.zOffsetFromSurface):0,u=this.props.layer==="bottom"?"bottom":"top",h=this._computePcbGlobalTransformBeforeLayout(),_=To(h).rotation.angle*180/Math.PI,y=u==="bottom",g=_+(a.z??0),x=Rl(g),w=t.cad_component.insert({position:{x:s.center.x+c.x,y:s.center.y+c.y,z:(u==="bottom"?-n/2:n/2)+(u==="bottom"?-l:l)+c.z},rotation:{x:a.x,y:a.y+(y?180:0),z:Rl(y?-x:x)},pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,model_stl_url:"stlUrl"in(r??{})?this._addCachebustToModelUrl(r.stlUrl):void 0,model_obj_url:"objUrl"in(r??{})?this._addCachebustToModelUrl(r.objUrl):void 0,model_mtl_url:"mtlUrl"in(r??{})?this._addCachebustToModelUrl(r.mtlUrl):void 0,model_gltf_url:"gltfUrl"in(r??{})?this._addCachebustToModelUrl(r.gltfUrl):void 0,model_glb_url:"glbUrl"in(r??{})?this._addCachebustToModelUrl(r.glbUrl):void 0,model_step_url:"stepUrl"in(r??{})?this._addCachebustToModelUrl(r.stepUrl):void 0,model_wrl_url:"wrlUrl"in(r??{})?this._addCachebustToModelUrl(r.wrlUrl):void 0,model_jscad:"jscad"in(r??{})?r.jscad:void 0,model_unit_to_mm_scale_factor:typeof r?.modelUnitToMmScale=="number"?r.modelUnitToMmScale:void 0,footprinter_string:typeof o=="string"&&!r?o:void 0});this.cad_component_id=w.cad_component_id}_addCachebustToModelUrl(t){if(!t||!t.includes("modelcdn.tscircuit.com"))return t;let n=this.root?.getClientOrigin()??"";return`${t}${t.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(n)}`}_getPartsEngineCacheKey(t,n){return JSON.stringify({ftype:t.ftype,name:t.name,manufacturer_part_number:t.manufacturer_part_number,footprinterString:n})}async _getSupplierPartNumbers(t,n,i){if(this.props.doNotPlace)return{};let r=this.root?.platform?.localCacheEngine,o=this._getPartsEngineCacheKey(n,i);if(r){let c=await r.getItem(o);if(c)try{return JSON.parse(c)}catch{}}let s=await Promise.resolve(t.findPart({sourceComponent:n,footprinterString:i})),a=s==="Not found"?{}:s;if(r)try{await r.setItem(o,JSON.stringify(a))}catch{}return a}doInitialPartsEngineRender(){if(this.props.doNotPlace)return;let t=this.getInheritedProperty("partsEngine");if(!t)return;let{db:n}=this.root,i=n.source_component.get(this.source_component_id);if(!i||i.supplier_part_numbers)return;let r;this.props.footprint&&typeof this.props.footprint=="string"&&(r=this.props.footprint);let o=this._getSupplierPartNumbers(t,i,r);if(!(o instanceof Promise)){n.source_component.update(this.source_component_id,{supplier_part_numbers:o});return}this._queueAsyncEffect("get-supplier-part-numbers",async()=>{this._asyncSupplierPartNumbers=await o,this._markDirty("PartsEngineRender")})}updatePartsEngineRender(){if(this.props.doNotPlace)return;let{db:t}=this.root,n=t.source_component.get(this.source_component_id);if(n&&!n.supplier_part_numbers&&this._asyncSupplierPartNumbers){t.source_component.update(this.source_component_id,{supplier_part_numbers:this._asyncSupplierPartNumbers});return}}doInitialAssignFallbackProps(){let{_parsedProps:t}=this;t.connections&&!this.name&&(this.fallbackUnassignedName=this.getSubcircuit().getNextAvailableName(this))}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}_createTracesFromConnectionsProp(){let{_parsedProps:t}=this;if(t.connections)for(let[n,i]of Object.entries(t.connections)){let r=Array.isArray(i)?i:[i];for(let o of r)this.add(new ko({from:`.${this.name} > .${n}`,to:String(o)}))}}doInitialSourceDesignRuleChecks(){V3t(this)}_getMinimumFlexContainerSize(){return Y3t(this)}_repositionOnPcb(t){return X3t(this,t)}doInitialSilkscreenOverlapAdjustment(){return U3t(this)}isRelativelyPositioned(){return this._parsedProps.pcbX!==void 0||this._parsedProps.pcbY!==void 0}},t5t=({boardAnchorPosition:e,boardAnchorAlignment:t,width:n,height:i})=>{let{x:r,y:o}=e,s=r,a=o;switch(t){case"top_left":s=r+n/2,a=o-i/2;break;case"top_right":s=r-n/2,a=o-i/2;break;case"bottom_left":s=r+n/2,a=o+i/2;break;case"bottom_right":s=r-n/2,a=o+i/2;break;case"top":s=r,a=o-i/2;break;case"bottom":s=r,a=o+i/2;break;case"left":s=r+n/2,a=o;break;case"right":s=r-n/2,a=o;break;case"center":default:break}return{x:s,y:a}},e5t=class{constructor(e,t={}){M(this,"input");M(this,"isRouting",!1);M(this,"solver");M(this,"eventHandlers",{complete:[],error:[],progress:[]});M(this,"cycleCount",0);M(this,"stepDelay");M(this,"timeoutId");this.input=e;let{capacityDepth:n,targetMinCapacity:i,stepDelay:r=0}=t;this.solver=new P$(e,{capacityDepth:n,targetMinCapacity:i,cacheProvider:null}),this.stepDelay=r}start(){this.isRouting||(this.isRouting=!0,this.cycleCount=0,this.runCycleAndQueueNextCycle())}runCycleAndQueueNextCycle(){if(this.isRouting)try{if(this.solver.solved||this.solver.failed){this.solver.failed?this.emitEvent({type:"error",error:new um(this.solver.error||"Routing failed")}):this.emitEvent({type:"complete",traces:this.solver.getOutputSimpleRouteJson().traces||[]}),this.isRouting=!1;return}let e=Date.now(),t=this.solver.iterations;for(;Date.now()-e<250&&!this.solver.failed&&!this.solver.solved;)this.solver.step();let n=(this.solver.iterations-t)/(Date.now()-e)*1e3;this.cycleCount++;let i=this.solver?.preview()||void 0,r=this.solver.progress;this.emitEvent({type:"progress",steps:this.cycleCount,iterationsPerSecond:n,progress:r,phase:this.solver.getCurrentPhase(),debugGraphics:i}),this.stepDelay>0?this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),this.stepDelay):this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),0)}catch(e){this.emitEvent({type:"error",error:e instanceof Error?new um(e.message):new um(String(e))}),this.isRouting=!1}}stop(){this.isRouting&&(this.isRouting=!1,this.timeoutId!==void 0&&(clearTimeout(this.timeoutId),this.timeoutId=void 0))}on(e,t){e==="complete"?this.eventHandlers.complete.push(t):e==="error"?this.eventHandlers.error.push(t):e==="progress"&&this.eventHandlers.progress.push(t)}emitEvent(e){if(e.type==="complete")for(let t of this.eventHandlers.complete)t(e);else if(e.type==="error")for(let t of this.eventHandlers.error)t(e);else if(e.type==="progress")for(let t of this.eventHandlers.progress)t(e)}solveSync(){if(this.solver.solve(),this.solver.failed)throw new um(this.solver.error||"Routing failed");return this.solver.getOutputSimpleRouteJson().traces||[]}},pM=class extends xe{constructor(){super(...arguments);M(this,"matchedPort",null)}get config(){return{componentName:"TraceHint",zodProps:Lz}}doInitialPortMatching(){let{db:t}=this.root,{_parsedProps:n,parent:i}=this;if(!i)return;if(i.componentName==="Trace"){this.renderError(`Port inference inside trace is not yet supported (${this})`);return}if(!i)throw new Error("TraceHint has no parent");if(!n.for){this.renderError(`TraceHint has no for property (${this})`);return}let r=i.selectOne(n.for,{type:"port"});r||this.renderError(`${this} could not find port for selector "${n.for}"`),this.matchedPort=r,r.registerMatch(this)}getPcbRouteHints(){let{_parsedProps:t}=this,n=t.offset?[t.offset]:t.offsets;if(!n)return[];let i=this._computePcbGlobalTransformBeforeLayout();return n.map(r=>({...Ae(i,r),via:r.via,to_layer:r.to_layer,trace_width:r.trace_width}))}doInitialPcbTraceHintRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this;t.pcb_trace_hint.insert({pcb_component_id:this.matchedPort?.pcb_component_id,pcb_port_id:this.matchedPort?.pcb_port_id,route:this.getPcbRouteHints()})}},BV=({circuitJson:e,editEvents:t,manualEditsFile:n})=>{let i={...n,pcb_placements:[...n.pcb_placements??[]]};for(let r of t)if(r.edit_event_type==="edit_pcb_component_location"){let{pcb_component_id:o,new_center:s}=r,a=Re(e).pcb_component.get(o);if(!a)continue;let c=Re(e).source_component.get(a.source_component_id);if(!c)continue;let l=i.pcb_placements?.findIndex(h=>h.selector===c.name),u={selector:c.name,center:s,relative_to:"group_center"};l>=0?i.pcb_placements[l]=u:i.pcb_placements.push(u)}return i},jV=({circuitJson:e,editEvents:t,manualEditsFile:n})=>{let i={...n,schematic_placements:[...n.schematic_placements??[]]};for(let r of t)if(r.edit_event_type==="edit_schematic_component_location"){let{schematic_component_id:o,new_center:s}=r,a=Re(e).schematic_component.get(o);if(!a||!a.source_component_id)continue;let c=Re(e).source_component.get(a.source_component_id);if(!c)continue;let l=i.schematic_placements?.findIndex(h=>h.selector===c.name),u={selector:c.name,center:s,relative_to:"group_center"};l>=0?i.schematic_placements[l]=u:i.schematic_placements.push(u)}return i},n5t=({circuitJson:e,editEvents:t,manualEditsFile:n})=>{let i=t.filter(s=>s.edit_event_type==="edit_schematic_component_location"),r=t.filter(s=>s.edit_event_type==="edit_pcb_component_location"),o=n;return i.length>0&&(o=jV({circuitJson:e,editEvents:i,manualEditsFile:o})),r.length>0&&(o=BV({circuitJson:e,editEvents:r,manualEditsFile:o})),o},i5t=(e,t)=>{if(Re(e).pcb_trace_hint.get(t.pcb_trace_hint_id))e=e.map(i=>i.pcb_trace_hint_id===t.pcb_trace_hint_id?{...i,route:t.route}:i);else{let i=Re(e).pcb_port.get(t.pcb_port_id);e=e.filter(r=>!(r.type==="pcb_trace_hint"&&r.pcb_port_id===t.pcb_port_id)).concat([{type:"pcb_trace_hint",pcb_trace_hint_id:t.pcb_trace_hint_id,route:t.route,pcb_port_id:t.pcb_port_id,pcb_component_id:i?.pcb_component_id}])}return e},r5t=({circuitJson:e,editEvents:t})=>{e=JSON.parse(JSON.stringify(e));for(let n of t)if(n.edit_event_type==="edit_pcb_component_location"){let i=e.find(o=>o.type==="pcb_component"&&o.pcb_component_id===n.pcb_component_id);if((!i||i.center.x!==n.new_center.x||i.center.y!==n.new_center.y)&&n.original_center){let o=vn(n.new_center.x-n.original_center.x,n.new_center.y-n.original_center.y);e=e.map(s=>s.pcb_component_id!==n.pcb_component_id?s:y4(s,o))}}else n.edit_event_type==="edit_schematic_component_location"?e=e.map(i=>i.type==="schematic_component"&&i.schematic_component_id===n.schematic_component_id?{...i,center:n.new_center}:i):n.edit_event_type==="edit_pcb_trace_hint"&&(e=i5t(e,n));return e},YV=(e,t)=>{let n=e.source_group.list(),i=[],r=o=>{let s=n.filter(a=>a.parent_subcircuit_id===o);for(let a of s)a.subcircuit_id&&(i.push(a.subcircuit_id),r(a.subcircuit_id))};return r(t),i},eM=({db:e,circuitJson:t,subcircuit_id:n,minTraceWidth:i=.1})=>{if(!e&&t&&(e=Re(t)),!e)throw new Error("db or circuitJson is required");let r=e.pcb_trace_hint.list(),o=n?new Set([n]):null;if(n){let N=YV(e,n);for(let E of N)o.add(E)}let s=(t??e.toArray()).filter(N=>!n||"subcircuit_id"in N&&o.has(N.subcircuit_id)),a=e.pcb_board.list()[0];e=Re(s);let c=si(s),l=lM([...e.pcb_component.list(),...e.pcb_smtpad.list(),...e.pcb_plated_hole.list(),...e.pcb_hole.list(),...e.pcb_via.list(),...e.pcb_cutout.list()].filter(N=>!n||o?.has(N.subcircuit_id)),c);for(let N of l){let E=N.connectedTo.flatMap(A=>c.getIdsConnectedToNet(A));N.connectedTo.push(...E)}let u=l.flatMap(N=>[{x:N.center.x-N.width/2,y:N.center.y-N.height/2},{x:N.center.x+N.width/2,y:N.center.y+N.height/2}]).concat(a?.outline??[]),h;if(a&&!a.outline?h={minX:a.center.x-a.width/2,maxX:a.center.x+a.width/2,minY:a.center.y-a.height/2,maxY:a.center.y+a.height/2}:h={minX:Math.min(...u.map(N=>N.x))-1,maxX:Math.max(...u.map(N=>N.x))+1,minY:Math.min(...u.map(N=>N.y))-1,maxY:Math.max(...u.map(N=>N.y))+1},n){let N=e.pcb_group.getWhere({subcircuit_id:n});if(N?.width&&N.height){let E={minX:N.center.x-N.width/2,maxX:N.center.x+N.width/2,minY:N.center.y-N.height/2,maxY:N.center.y+N.height/2};h={minX:Math.min(h.minX,E.minX),maxX:Math.max(h.maxX,E.maxX),minY:Math.min(h.minY,E.minY),maxY:Math.max(h.maxY,E.maxY)}}}let d=new Set(e.pcb_trace.list().map(N=>N.source_trace_id).filter(N=>!!N)),_=e.source_trace.list().filter(N=>!d.has(N.source_trace_id)).map(N=>{let E=N.connected_source_port_ids.map(U=>{let tt=e.source_port.get(U),J=e.pcb_port.getWhere({source_port_id:U});return{...tt,...J}});if(E.length<2)return null;let[A,O]=E,$=A.layers?.[0]??"top",B=O.layers?.[0]??"top",H=r.filter(U=>U.pcb_port_id===A.pcb_port_id||U.pcb_port_id===O.pcb_port_id),X=[];for(let U of H){let J=e.pcb_port.get(U.pcb_port_id)?.layers?.[0]??"top";for(let V of U.route)X.push({x:V.x,y:V.y,layer:J})}return{name:N.source_trace_id??c.getNetConnectedToId(N.source_trace_id)??"",source_trace_id:N.source_trace_id,width:N.min_trace_thickness,pointsToConnect:[{x:A.x,y:A.y,layer:$,pointId:A.pcb_port_id,pcb_port_id:A.pcb_port_id},...X,{x:O.x,y:O.y,layer:B,pointId:O.pcb_port_id,pcb_port_id:O.pcb_port_id}]}}).filter(N=>N!==null),y=new Map(_.map(N=>[N.source_trace_id,N])),g=e.source_net.list().filter(N=>!n||o?.has(N.subcircuit_id)),x=[];for(let N of g){let E=e.source_trace.list().filter(A=>A.connected_source_net_ids?.includes(N.source_net_id));x.push({name:N.source_net_id??c.getNetConnectedToId(N.source_net_id),pointsToConnect:E.flatMap(A=>e.pcb_port.list().filter($=>A.connected_source_port_ids.includes($.source_port_id)).map($=>({x:$.x,y:$.y,layer:$.layers?.[0]??"top",pointId:$.pcb_port_id,pcb_port_id:$.pcb_port_id})))})}let w=e.pcb_breakout_point.list().filter(N=>!n||o?.has(N.subcircuit_id)),S=[],C=new Map;for(let N of w){let E={x:N.x,y:N.y,layer:"top"};if(N.source_trace_id){let A=y.get(N.source_trace_id)??C.get(N.source_trace_id);if(A)A.pointsToConnect.push(E);else{let O={name:N.source_trace_id,source_trace_id:N.source_trace_id,pointsToConnect:[E]};S.push(O),C.set(N.source_trace_id,O)}}else if(N.source_net_id){let A=x.find(O=>O.name===N.source_net_id);A?A.pointsToConnect.push(E):S.push({name:N.source_net_id,pointsToConnect:[E]})}else if(N.source_port_id){let A=e.pcb_port.getWhere({source_port_id:N.source_port_id});A&&S.push({name:N.source_port_id,source_trace_id:void 0,pointsToConnect:[{x:A.x,y:A.y,layer:A.layers?.[0]??"top",pointId:A.pcb_port_id,pcb_port_id:A.pcb_port_id},E]})}}let I=[..._,...x,...S],k=new Map;for(let N of I)for(let E of N.pointsToConnect)E.pointId&&k.set(E.pointId,N);let P=e.pcb_trace.list().filter(N=>!n||o?.has(N.subcircuit_id));for(let N of P){let E=new Set;for(let $ of N.route)$.start_pcb_port_id&&E.add($.start_pcb_port_id),$.end_pcb_port_id&&E.add($.end_pcb_port_id);if(E.size<2)continue;let A=E.values().next().value;if(!A)continue;let O=k.get(A);O&&[...E].every($=>k.get($)===O)&&(O.externallyConnectedPointIds??(O.externallyConnectedPointIds=[]),O.externallyConnectedPointIds.push([...E]))}return{simpleRouteJson:{bounds:h,obstacles:l,connections:I,layerCount:a?.num_layers??2,minTraceWidth:i,outline:a?.outline?.map(N=>({...N}))},connMap:c}},o5t=e=>{let t={};if(!e)return t;for(let i of ea)t[i]=0;let n=new Map;for(let i of e){let[,,r,o]=i.type.split(":");if(o==="start"){n.set(`${r}:${i.renderId}`,i);continue}if(o==="end"){let s=n.get(`${r}:${i.renderId}`);if(s){let a=i.createdAt-s.createdAt;t[r]=(t[r]||0)+a}}}return t},s5t=e=>{let t=e.map(c=>[...new Set(c)]),n=t.map(()=>[]),i=t.map(()=>null);for(let c=0;c<t.length;c++)for(let l of t[c])if(/^\d+$/.test(l)){i[c]=Number.parseInt(l);break}let r=0,o=new Set;for(let c=0;c<i.length;c++){let l=i[c];if(l===null||l<1)continue;if(!o.has(l)){o.add(l),n[c].push(`pin${l}`),r=Math.max(r,l);continue}let u=0;for(let h of n[c])h.startsWith(`pin${l}_alt`)&&u++;n[c].push(`pin${l}_alt${u+1}`)}for(let c=0;c<n.length;c++)n[c][0]?.includes("_alt")&&(r++,n[c].unshift(`pin${r}`));for(let c=0;c<n.length;c++)n[c].length===0&&(r++,n[c].push(`pin${r}`));let s={};for(let c of t)for(let l of c)/^\d+$/.test(l)||(s[l]=(s[l]??0)+1);let a={};for(let c=0;c<t.length;c++){let l=t[c];for(let u of l)/^\d+$/.test(u)||(s[u]===1?n[c].push(u):(a[u]=(a[u]??0)+1,n[c].push(`${u}${a[u]}`)))}return n};function hM({db:e,schematicComponentId:t,deltaX:n,deltaY:i}){let r=e.schematic_rect.list({schematic_component_id:t});for(let c of r)c.center.x+=n,c.center.y+=i;let o=e.schematic_line.list({schematic_component_id:t});for(let c of o)c.x1+=n,c.y1+=i,c.x2+=n,c.y2+=i;let s=e.schematic_circle.list({schematic_component_id:t});for(let c of s)c.center.x+=n,c.center.y+=i;let a=e.schematic_arc.list({schematic_component_id:t});for(let c of a)c.center.x+=n,c.center.y+=i}var cV=(0,XV.default)("Group_doInitialSchematicLayoutMatchAdapt");function a5t(e){let{db:t}=e.root,n=uf(t.toArray(),{source_group_id:e.source_group_id}),i=G4(n);cV.enabled&&global.debugGraphics?.push(cc(i,{title:`floatingBpcGraph-${e.name}`}));let r=G4(n),o={boxes:r.boxes,pins:r.pins.map(c=>({...c,color:c.color.replace("not_connected","normal")}))},{result:s}=QB([{variantName:"default",floatingGraph:r},{variantName:"noNotConnected",floatingGraph:o}],{singletonKeys:["vcc/2","gnd/2"],centerPinColors:["netlabel_center","component_center"],floatingBoxIdsWithMutablePinOffsets:new Set(r.boxes.filter(c=>r.pins.filter(h=>h.boxId===c.boxId).filter(h=>!h.color.includes("center")).length<=2).map(c=>c.boxId)),corpus:{}});cV.enabled&&global.debugGraphics?.push(cc(s,{title:`laidOutBpcGraph-${e.name}`}));let a=e._getGlobalSchematicPositionBeforeLayout();for(let c of s.boxes){if(!c.center)continue;let l=t.schematic_component.get(c.boxId);if(l){let h={x:c.center.x+a.x,y:c.center.y+a.y},d=t.schematic_port.list({schematic_component_id:l.schematic_component_id}),_=t.schematic_text.list({schematic_component_id:l.schematic_component_id}),y={x:h.x-l.center.x,y:h.y-l.center.y};for(let g of d)g.center.x+=y.x,g.center.y+=y.y;for(let g of _)g.position.x+=y.x,g.position.y+=y.y;hM({db:t,schematicComponentId:l.schematic_component_id,deltaX:y.x,deltaY:y.y}),l.center=h;continue}let u=t.schematic_net_label.get(c.boxId);if(u){let h=s.pins.find(_=>_.boxId===c.boxId&&_.color==="netlabel_center");if(!h)throw new Error(`No pin found for net label: ${c.boxId}`);let d={x:c.center.x+a.x,y:c.center.y+a.y};u.center=d,u.anchor_position={x:d.x+h.offset.x,y:d.y+h.offset.y};continue}console.error(`No schematic element found for box: ${c.boxId}. This is a bug in the matchAdapt binding with @tscircuit/core`)}}var he=(0,VV.default)("Group_doInitialSchematicLayoutMatchpack");function lV(e){switch(e){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:return"y+"}}function uV(e,t){let n=["right","up","left","down"],i=n.indexOf(e);if(i===-1)return e;let r=Math.round(t/90),o=(i+r)%4;return n[o<0?o+4:o]}function c5t(e,t,n){let i={chipMap:{},chipPinMap:{},netMap:{},pinStrongConnMap:{},netConnMap:{},chipGap:.6,decouplingCapsGap:.4,partitionGap:1.2};he(`[${n.name}] Processing ${e.childNodes.length} child nodes for input problem`),e.childNodes.forEach((o,s)=>{if(he(`[${n.name}] Processing child ${s}: nodeType=${o.nodeType}`),o.nodeType==="component"?he(`[${n.name}] - Component: ${o.sourceComponent?.name}`):o.nodeType==="group"&&he(`[${n.name}] - Group: ${o.sourceGroup?.name}`),o.nodeType==="component"&&o.sourceComponent){let a=o.sourceComponent.name||`chip_${s}`,c=t.schematic_component.getWhere({source_component_id:o.sourceComponent.source_component_id});if(!c)return;let l=n.children.find(S=>S.source_component_id===o.sourceComponent?.source_component_id),u=[0,90,180,270];l?._parsedProps?.schOrientation&&(u=[0]),l?._parsedProps?.schRotation!==void 0&&(u=[0]),l?._parsedProps?.facingDirection&&(u=[0]),l?._parsedProps?.schFacingDirection&&(u=[0]);let h=l?._parsedProps?.schMarginLeft??l?._parsedProps?.schMarginX??0,d=l?._parsedProps?.schMarginRight??l?._parsedProps?.schMarginX??0,_=l?._parsedProps?.schMarginTop??l?._parsedProps?.schMarginY??0,y=l?._parsedProps?.schMarginBottom??l?._parsedProps?.schMarginY??0;l?.config.shouldRenderAsSchematicBox&&(_+=.4,y+=.4);let g=(d-h)/2,x=(_-y)/2;i.chipMap[a]={chipId:a,pins:[],size:{x:(c.size?.width||1)+h+d,y:(c.size?.height||1)+_+y},availableRotations:u};let w=t.schematic_port.list({schematic_component_id:c.schematic_component_id});for(let S of w){let C=t.source_port.get(S.source_port_id);if(!C)continue;let I=`${a}.${C.pin_number||C.name||S.schematic_port_id}`;i.chipMap[a].pins.push(I);let k=lV(S.facing_direction);i.chipPinMap[I]={pinId:I,offset:{x:(S.center?.x||0)-(c.center.x||0)+g,y:(S.center?.y||0)-(c.center.y||0)+x},side:k}}}else if(o.nodeType==="group"&&o.sourceGroup){let a=o.sourceGroup.name||`group_${s}`;he(`[${n.name}] Processing nested group: ${a}`);let c=t.schematic_group?.getWhere?.({source_group_id:o.sourceGroup.source_group_id}),l=n.children.find(u=>u.source_group_id===o.sourceGroup?.source_group_id);if(he(`[${n.name}] Found schematic_group for ${a}:`,c),c){he(`[${n.name}] Treating group ${a} as composite chip`);let u=t.schematic_component.list({schematic_group_id:c.schematic_group_id});he(`[${n.name}] Group ${a} has ${u.length} components:`,u.map(A=>A.source_component_id));let h=1/0,d=-1/0,_=1/0,y=-1/0,g=!1;for(let A of u)if(A.center&&A.size){g=!0;let O=A.size.width/2,$=A.size.height/2;h=Math.min(h,A.center.x-O),d=Math.max(d,A.center.x+O),_=Math.min(_,A.center.y-$),y=Math.max(y,A.center.y+$)}let x=l?._parsedProps?.schMarginLeft??l?._parsedProps?.schMarginX??0,w=l?._parsedProps?.schMarginRight??l?._parsedProps?.schMarginX??0,S=l?._parsedProps?.schMarginTop??l?._parsedProps?.schMarginY??0,C=l?._parsedProps?.schMarginBottom??l?._parsedProps?.schMarginY??0,I=(w-x)/2,k=(S-C)/2,P=(g?d-h:2)+x+w,N=(g?y-_:2)+S+C;he(`[${n.name}] Group ${a} computed size: ${P} x ${N}`);let E=[];for(let A of u){let O=t.schematic_port.list({schematic_component_id:A.schematic_component_id});for(let $ of O){let B=t.source_port.get($.source_port_id);if(!B)continue;let H=`${a}.${B.pin_number||B.name||$.schematic_port_id}`;E.push(H);let X=c.center||{x:0,y:0},U=lV($.facing_direction);i.chipPinMap[H]={pinId:H,offset:{x:($.center?.x||0)-X.x+I,y:($.center?.y||0)-X.y+k},side:U}}}he(`[${n.name}] Group ${a} has ${E.length} pins:`,E),i.chipMap[a]={chipId:a,pins:E,size:{x:P,y:N}},he(`[${n.name}] Added group ${a} to chipMap`)}else he(`[${n.name}] Warning: No schematic_group found for group ${a}`)}}),he(`[${n.name}] Creating connections using connectivity keys`);let r=new Map;for(let[o,s]of Object.entries(i.chipMap))for(let a of s.pins){let c=a.split(".").pop(),l=e.childNodes.find(u=>u.nodeType==="component"&&u.sourceComponent?u.sourceComponent.name===o:u.nodeType==="group"&&u.sourceGroup?`group_${e.childNodes.indexOf(u)}`===o:!1);if(l?.nodeType==="group"&&l.sourceGroup){let u=t.schematic_group?.getWhere?.({source_group_id:l.sourceGroup.source_group_id});if(u){let h=t.schematic_component.list({schematic_group_id:u.schematic_group_id});for(let d of h){let _=t.source_port.list({source_component_id:d.source_component_id});for(let y of _){let g=y.pin_number||y.name;if(String(g)===String(c))if(y.subcircuit_connectivity_map_key){let x=y.subcircuit_connectivity_map_key;r.has(x)||r.set(x,[]),r.get(x).push(a),he(`[${n.name}] \u2713 Pin ${a} has connectivity key: ${x}`)}else he(`[${n.name}] Pin ${a} has no connectivity key`)}}}}else if(l?.nodeType==="component"&&l.sourceComponent){let u=t.source_port.list({source_component_id:l.sourceComponent.source_component_id});for(let h of u){let d=h.pin_number||h.name;if(String(d)===String(c)&&h.subcircuit_connectivity_map_key){let _=h.subcircuit_connectivity_map_key;r.has(_)||r.set(_,[]),r.get(_).push(a),he(`[${n.name}] Pin ${a} has connectivity key: ${_}`)}}}}he(`[${n.name}] Found ${r.size} connectivity groups:`,Array.from(r.entries()).map(([o,s])=>({key:o,pins:s})));for(let[o,s]of r)if(s.length>=2){let a=t.source_trace.list().filter(u=>u.subcircuit_connectivity_map_key===o),c=a.some(u=>u.connected_source_net_ids&&u.connected_source_net_ids.length>0),l=a.some(u=>u.connected_source_port_ids&&u.connected_source_port_ids.length>=2);if(he(`[${n.name}] Connectivity ${o}: hasNetConnections=${c}, hasDirectConnections=${l}`),l){for(let u of a)if(u.connected_source_port_ids&&u.connected_source_port_ids.length>=2){let h=[];for(let d of u.connected_source_port_ids)for(let _ of s){let y=_.split(".").pop(),g=t.source_port.get(d);if(g&&String(g.pin_number||g.name)===String(y)){let x=_.split(".")[0],w=e.childNodes.find(S=>S.nodeType==="component"&&S.sourceComponent?S.sourceComponent.name===x:S.nodeType==="group"&&S.sourceGroup?`group_${e.childNodes.indexOf(S)}`===x:!1);w?.nodeType==="component"&&w.sourceComponent&&t.source_port.list({source_component_id:w.sourceComponent.source_component_id}).some(C=>C.source_port_id===d)&&h.push(_)}}for(let d=0;d<h.length;d++)for(let _=d+1;_<h.length;_++){let y=h[d],g=h[_];i.pinStrongConnMap[`${y}-${g}`]=!0,i.pinStrongConnMap[`${g}-${y}`]=!0,he(`[${n.name}] Created strong connection: ${y} <-> ${g}`)}}}if(c){let u=t.source_net.getWhere({subcircuit_connectivity_map_key:o}),h=u?.is_ground??!1,d=u?.is_power??!1;i.netMap[o]={netId:o,isGround:h,isPositiveVoltageSource:d};for(let _ of s)i.netConnMap[`${_}-${o}`]=!0;he(`[${n.name}] Created net ${o} with ${s.length} pins:`,s)}}return i}function l5t(e){let{db:t}=e.root,n=Up(t.toArray(),{source_group_id:e.source_group_id});if(he(`[${e.name}] Starting matchpack layout with ${n.childNodes.length} children`),he(`[${e.name}] Tree structure:`,JSON.stringify(n,null,2)),n.childNodes.length<=1){he(`[${e.name}] Only ${n.childNodes.length} children, skipping layout`);return}he("Converting circuit tree to InputProblem...");let i=c5t(n,t,e);he.enabled&&e.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`matchpack-input-problem-${e.name}`,content:JSON.stringify(i,null,2)});let r=new iY(i);if(he("Starting LayoutPipelineSolver..."),he.enabled&&global.debugGraphics){let c=r.visualize();global.debugGraphics.push({...c,title:`matchpack-initial-${e.name}`})}if(r.solve(),he(`Solver completed in ${r.iterations} iterations`),he(`Solved: ${r.solved}, Failed: ${r.failed}`),r.failed)throw he(`Solver failed with error: ${r.error}`),new Error(`Matchpack layout solver failed: ${r.error}`);let o=r.getOutputLayout();if(he("OutputLayout:",JSON.stringify(o,null,2)),he("Solver completed successfully:",!r.failed),he.enabled&&global.debugGraphics){let c=r.visualize();global.debugGraphics.push({...c,title:`matchpack-final-${e.name}`})}let s=r.checkForOverlaps(o);if(s.length>0){he(`Warning: Found ${s.length} overlapping components:`);for(let c of s)he(` ${c.chip1} overlaps ${c.chip2} (area: ${c.overlapArea})`)}let a=e._getGlobalSchematicPositionBeforeLayout();he(`Group offset: x=${a.x}, y=${a.y}`),he(`Applying layout results for ${Object.keys(o.chipPlacements).length} chip placements`);for(let[c,l]of Object.entries(o.chipPlacements)){he(`Processing placement for chip: ${c} at (${l.x}, ${l.y})`);let u=n.childNodes.find(d=>{if(d.nodeType==="component"&&d.sourceComponent){let _=d.sourceComponent.name===c;return he(` Checking component ${d.sourceComponent.name}: matches=${_}`),_}if(d.nodeType==="group"&&d.sourceGroup){let _=d.sourceGroup.name,y=`group_${n.childNodes.indexOf(d)}`,g=y===c;return he(` Checking group ${_} (expected chipId: ${y}): matches=${g}`),g}return!1});if(!u){he(`Warning: No tree node found for chip: ${c}`),he("Available tree nodes:",n.childNodes.map((d,_)=>({type:d.nodeType,name:d.nodeType==="component"?d.sourceComponent?.name:d.sourceGroup?.name,expectedChipId:d.nodeType==="group"?`group_${_}`:d.sourceComponent?.name})));continue}let h={x:l.x+a.x,y:l.y+a.y};if(u.nodeType==="component"&&u.sourceComponent){let d=t.schematic_component.getWhere({source_component_id:u.sourceComponent.source_component_id});if(d){he(`Moving component ${c} to (${h.x}, ${h.y})`);let _=t.schematic_port.list({schematic_component_id:d.schematic_component_id}),y=t.schematic_text.list({schematic_component_id:d.schematic_component_id}),g={x:h.x-d.center.x,y:h.y-d.center.y};for(let x of _)x.center.x+=g.x,x.center.y+=g.y;for(let x of y)x.position.x+=g.x,x.position.y+=g.y;if(hM({db:t,schematicComponentId:d.schematic_component_id,deltaX:g.x,deltaY:g.y}),d.center=h,l.ccwRotationDegrees!==0){he(`Component ${c} has rotation: ${l.ccwRotationDegrees}\xB0`);let x=l.ccwRotationDegrees*Math.PI/180,w=Math.cos(x),S=Math.sin(x);for(let C of _){let I=C.center.x-h.x,k=C.center.y-h.y,P=I*w-k*S,N=I*S+k*w;C.center.x=h.x+P,C.center.y=h.y+N;let E=C.facing_direction||"right";C.facing_direction=uV(E,l.ccwRotationDegrees),C.side_of_component=(C.facing_direction==="up"?"top":C.facing_direction==="down"?"bottom":C.facing_direction)||C.side_of_component}for(let C of y){let I=C.position.x-h.x,k=C.position.y-h.y,P=I*w-k*S,N=I*S+k*w;C.position.x=h.x+P,C.position.y=h.y+N}if(d.symbol_name){let C=d.symbol_name.match(/_(right|left|up|down)$/);C&&(d.symbol_name=d.symbol_name.replace(C[0],`_${uV(C[1],l.ccwRotationDegrees)}`))}}}}else if(u.nodeType==="group"&&u.sourceGroup){let d=t.schematic_group?.getWhere?.({source_group_id:u.sourceGroup.source_group_id});if(d){he(`Moving group ${c} to (${h.x}, ${h.y}) from (${d.center?.x}, ${d.center?.y})`);let _=t.schematic_component.list({schematic_group_id:d.schematic_group_id});he(`Group ${c} has ${_.length} components to move`);let y=d.center||{x:0,y:0},g={x:h.x-y.x,y:h.y-y.y};he(`Position delta for group ${c}: (${g.x}, ${g.y})`);for(let x of _)if(x.center){let w={...x.center};x.center.x+=g.x,x.center.y+=g.y,he(`Moved component ${x.source_component_id} from (${w.x}, ${w.y}) to (${x.center.x}, ${x.center.y})`);let S=t.schematic_port.list({schematic_component_id:x.schematic_component_id}),C=t.schematic_text.list({schematic_component_id:x.schematic_component_id});for(let I of S)I.center&&(I.center.x+=g.x,I.center.y+=g.y);for(let I of C)I.position&&(I.position.x+=g.x,I.position.y+=g.y)}d.center=h,he(`Updated group ${c} center to (${h.x}, ${h.y})`)}}}he("Matchpack layout completed successfully")}function u5t(e){if(!e.isSubcircuit)return;let{db:t}=e.root,n=e.selectAll("trace"),i=new zp({});i.addConnections(n.map(a=>{let c=t.source_trace.get(a.source_trace_id);return c?[c.source_trace_id,...c.connected_source_port_ids,...c.connected_source_net_ids]:null}).filter(a=>a!==null));let{name:r}=e._parsedProps;for(let a of n){if(!a.source_trace_id)continue;let c=i.getNetConnectedToId(a.source_trace_id);c&&(a.subcircuit_connectivity_map_key=`${r??`unnamedsubcircuit${e._renderId}`}_${c}`,t.source_trace.update(a.source_trace_id,{subcircuit_connectivity_map_key:a.subcircuit_connectivity_map_key}))}let o=new Set;for(let a of n){if(!a.source_trace_id)continue;let c=t.source_trace.get(a.source_trace_id);if(c)for(let l of c.connected_source_port_ids)o.add(l)}for(let a of o){let c=i.getNetConnectedToId(a);if(!c)continue;let l=`${r??`unnamedsubcircuit${e._renderId}`}_${c}`;t.source_port.update(a,{subcircuit_connectivity_map_key:l})}let s=new Set;for(let a of n){if(!a.source_trace_id)continue;let c=t.source_trace.get(a.source_trace_id);if(c)for(let l of c.connected_source_net_ids)s.add(l)}for(let a of s){let c=i.getNetConnectedToId(a);if(!c)continue;let l=`${r??`unnamedsubcircuit${e._renderId}`}_${c}`;t.source_net.update(a,{subcircuit_connectivity_map_key:l})}}function p5t(e){let{db:t}=e.root,n=e._parsedProps,i=e.children.filter(k=>{let P=k._parsedProps?.schX!==void 0||k._parsedProps?.schY!==void 0;return k.schematic_component_id&&!P});if(i.length===0)return;let r=0,o=0;for(let k of i){let P=t.schematic_component.get(k.schematic_component_id);P?.size&&(r=Math.max(r,P.size.width),o=Math.max(o,P.size.height))}r===0&&i.length>0&&(r=1),o===0&&i.length>0&&(o=1);let s=n.gridCols,a,c=n.gridGap,l=n.gridRowGap,u=n.gridColumnGap;n.schLayout?.grid&&(s=n.schLayout.grid.cols??s,a=n.schLayout.grid.rows,c=n.schLayout.gridGap??c,l=n.schLayout.gridRowGap??l,u=n.schLayout.gridColumnGap??u);let h,d;s!==void 0&&a!==void 0?(h=s,d=a):s!==void 0?(h=s,d=Math.ceil(i.length/h)):a!==void 0?(d=a,h=Math.ceil(i.length/d)):(h=Math.ceil(Math.sqrt(i.length)),d=Math.ceil(i.length/h)),h===0&&i.length>0&&(h=1),d===0&&i.length>0&&(d=i.length);let _,y,g=k=>{if(k!==void 0)return typeof k=="number"?k:D.parse(k)};if(l!==void 0||u!==void 0){let k=typeof c=="object"&&c!==null?c.x:c,P=typeof c=="object"&&c!==null?c.y:c;_=g(u??k)??1,y=g(l??P)??1}else if(typeof c=="number")_=c,y=c;else if(typeof c=="string"){let k=D.parse(c);_=k,y=k}else if(typeof c=="object"&&c!==null){let k=c.x,P=c.y;_=typeof k=="number"?k:D.parse(k??"0mm"),y=typeof P=="number"?P:D.parse(P??"0mm")}else _=1,y=1;let x=h*r+Math.max(0,h-1)*_,w=d*o+Math.max(0,d-1)*y,S=e._getGlobalSchematicPositionBeforeLayout(),C=S.x-x/2+r/2,I=S.y+w/2-o/2;for(let k=0;k<i.length;k++){let P=i[k];if(!P.schematic_component_id)continue;let N=Math.floor(k/h),E=k%h;if(N>=d||E>=h){console.warn(`Schematic grid layout: Child ${P.getString()} at index ${k} (row ${N}, col ${E}) exceeds specified grid dimensions (${d}x${h}). Skipping placement.`);continue}let A=C+E*(r+_),O=I-N*(o+y),$=t.schematic_component.get(P.schematic_component_id);if($){let B=$.center,H={x:A,y:O};t.schematic_component.update(P.schematic_component_id,{center:H});let X=H.x-B.x,U=H.y-B.y,tt=t.schematic_port.list({schematic_component_id:P.schematic_component_id});for(let V of tt)t.schematic_port.update(V.schematic_port_id,{center:{x:V.center.x+X,y:V.center.y+U}});let J=t.schematic_text.list({schematic_component_id:P.schematic_component_id});for(let V of J)t.schematic_text.update(V.schematic_text_id,{position:{x:V.position.x+X,y:V.position.y+U}});hM({db:t,schematicComponentId:P.schematic_component_id,deltaX:X,deltaY:U})}}e.schematic_group_id&&t.schematic_group.update(e.schematic_group_id,{width:x,height:w,center:S})}var pV=(e,t)=>{let{sourceComponent:n,sourceGroup:i}=t;if(t.nodeType==="component"){let r=e.schematic_component.getWhere({source_component_id:n?.source_component_id});return r?.size?{width:r.size.width,height:r.size.height}:null}if(t.nodeType==="group"){let r=e.schematic_group.getWhere({source_group_id:i?.source_group_id});if(r?.width&&r?.height)return{width:r.width,height:r.height};let o=e.schematic_component.list({schematic_group_id:r?.schematic_group_id}),s=1/0,a=-1/0,c=1/0,l=-1/0;for(let d of o)if(d.center&&d.size){let _=d.size.width/2,y=d.size.height/2;s=Math.min(s,d.center.x-_),a=Math.max(a,d.center.x+_),c=Math.min(c,d.center.y-y),l=Math.max(l,d.center.y+y)}let u=a-s,h=l-c;return{width:u,height:h}}return null},h5t=e=>{let{db:t}=e.root,n=e._parsedProps,i=Up(t.toArray(),{source_group_id:e.source_group_id}),r=n.schJustifyContent??n.justifyContent,o=n.schAlignItems??n.alignItems,s=n.schFlexGap??n.schGap??n.gap,a=n.schFlexDirection??"row",c={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"space-between","space-between":"space-between","space-around":"space-around","space-evenly":"space-evenly",center:"center"}[r??"space-between"],l={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"stretch",center:"center"}[o??"center"];if(!c)throw new Error(`Invalid justifyContent value: "${r}"`);if(!l)throw new Error(`Invalid alignItems value: "${o}"`);let u=0,h=0;typeof s=="object"?(u=s.y??0,h=s.x??0):typeof s=="number"?(u=s,h=s):typeof s=="string"&&(u=D.parse(s),h=D.parse(s));let d,_=n.width??n.schWidth??void 0,y=n.height??n.schHeight??void 0;(_===void 0||y===void 0)&&(d=Vg(i.childNodes.map(I=>pV(t,I)).filter(I=>I!==null),{alignItems:l,justifyContent:c,direction:a,rowGap:u,columnGap:h}),_=d.width,y=d.height);let x=new Gb(_,y,{alignItems:l,justifyContent:c,direction:a,rowGap:u,columnGap:h});for(let I of i.childNodes){let k=pV(t,I);x.addChild({metadata:I,width:k?.width??0,height:k?.height??0,flexBasis:k?a==="row"?k.width:k.height:void 0})}x.build();let w={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let I of x.children)w.minX=Math.min(w.minX,I.position.x),w.minY=Math.min(w.minY,I.position.y),w.maxX=Math.max(w.maxX,I.position.x+I.size.width),w.maxY=Math.max(w.maxY,I.position.y+I.size.height);w.width=w.maxX-w.minX,w.height=w.maxY-w.minY;let S={x:-(w.maxX+w.minX)/2,y:-(w.maxY+w.minY)/2},C=t.toArray();for(let I of x.children){let{sourceComponent:k,sourceGroup:P}=I.metadata;if(k){let N=t.schematic_component.getWhere({source_component_id:k.source_component_id});if(!N)continue;yD(C,N.schematic_component_id,{x:I.position.x+I.size.width/2+S.x,y:I.position.y+I.size.height/2+S.y})}if(P){if(!t.schematic_group.getWhere({source_group_id:P.source_group_id}))continue;bD(C,P.source_group_id,{x:I.position.x+I.size.width/2+S.x,y:I.position.y+I.size.height/2+S.y})}}e.schematic_group_id&&t.schematic_group.update(e.schematic_group_id,{width:w.width,height:w.height})},VI=1;function d5t(e){let{db:t}=e.root,n=e._parsedProps,i=f5t(e);if(i.length===0)return;let r=m5t({db:t,pcbChildren:i}),o=_5t(n),s=y5t({props:n,pcbChildren:i,childDimensions:r,gridConfig:o}),a=x5t({pcbChildren:i,childDimensions:r,gridLayout:s,gridConfig:o}),{itemCoordinates:c}=a.layout();v5t({db:t,group:e,pcbChildren:i,itemCoordinates:c,gridLayout:s}),w5t({db:t,group:e,props:n,gridLayout:s})}function f5t(e){return e.children.filter(t=>t.pcb_component_id||t.pcb_group_id)}function m5t(e){let{db:t,pcbChildren:n}=e,i=0,r=0;for(let o of n){let s=0,a=0;if(o.pcb_group_id){let c=t.pcb_group.get(o.pcb_group_id);s=c?.width??0,a=c?.height??0}else if(o.pcb_component_id){let c=t.pcb_component.get(o.pcb_component_id);s=c?.width??0,a=c?.height??0}i=Math.max(i,s),r=Math.max(r,a)}return{width:i,height:r}}function _5t(e){let t=e.pcbGridCols??e.gridCols??e.pcbLayout?.grid?.cols,n=e.pcbGridRows??e.pcbLayout?.grid?.rows,i=e.pcbGridTemplateColumns,r=e.pcbGridTemplateRows,o=h=>h===void 0?VI:typeof h=="number"?h:D.parse(h),s=e.pcbGridGap??e.gridGap??e.pcbLayout?.gridGap,a=e.pcbGridRowGap??e.gridRowGap??e.pcbLayout?.gridRowGap,c=e.pcbGridColumnGap??e.gridColumnGap??e.pcbLayout?.gridColumnGap,l=VI,u=VI;if(a!==void 0||c!==void 0){let h=typeof s=="object"?s?.x:s,d=typeof s=="object"?s?.y:s;l=o(c??h),u=o(a??d)}else if(typeof s=="object"&&s!==null)l=o(s.x),u=o(s.y);else{let h=o(s);l=h,u=h}return{cols:t,rows:n,gapX:l,gapY:u,templateColumns:i,templateRows:r}}function y5t(e){let{props:t,pcbChildren:n,childDimensions:i,gridConfig:r}=e;return t.pcbGridTemplateColumns||t.pcbGridTemplateRows?g5t({props:t,gridConfig:r,pcbChildren:n,childDimensions:i}):b5t({gridConfig:r,pcbChildren:n,childDimensions:i})}function g5t(e){let{props:t,gridConfig:n,pcbChildren:i,childDimensions:r}=e,o=t.pcbGridTemplateColumns??"",s=t.pcbGridTemplateRows??"",a=d=>{let _=d.match(/repeat\((\d+),/);return _?parseInt(_[1]):Math.ceil(Math.sqrt(i.length))},c=t.pcbGridTemplateColumns?a(o):Math.ceil(Math.sqrt(i.length)),l=t.pcbGridTemplateRows?a(s):Math.ceil(i.length/c),u=c*r.width+Math.max(0,c-1)*n.gapX,h=l*r.height+Math.max(0,l-1)*n.gapY;return{gridTemplateColumns:o,gridTemplateRows:s,containerWidth:u,containerHeight:h}}function b5t(e){let{gridConfig:t,pcbChildren:n,childDimensions:i}=e,r,o;t.cols!==void 0&&t.rows!==void 0?(r=t.cols,o=t.rows):t.cols!==void 0?(r=t.cols,o=Math.ceil(n.length/r)):t.rows!==void 0?(o=t.rows,r=Math.ceil(n.length/o)):(r=Math.ceil(Math.sqrt(n.length)),o=Math.ceil(n.length/r)),r=Math.max(1,r),o=Math.max(1,o);let s=r*i.width+Math.max(0,r-1)*t.gapX,a=o*i.height+Math.max(0,o-1)*t.gapY,c=`repeat(${r}, ${i.width}px)`,l=`repeat(${o}, ${i.height}px)`;return{gridTemplateColumns:c,gridTemplateRows:l,containerWidth:s,containerHeight:a}}function x5t(e){let{pcbChildren:t,childDimensions:n,gridLayout:i,gridConfig:r}=e,o=t.map((s,a)=>({key:s.getString()||`child-${a}`,contentWidth:n.width,contentHeight:n.height}));return new hY({containerWidth:i.containerWidth,containerHeight:i.containerHeight,gridTemplateColumns:i.gridTemplateColumns,gridTemplateRows:i.gridTemplateRows,gap:[r.gapY,r.gapX],children:o})}function v5t(e){let{db:t,group:n,pcbChildren:i,itemCoordinates:r,gridLayout:o}=e,s=n._getGlobalPcbPositionBeforeLayout(),a=t.toArray();for(let c=0;c<i.length;c++){let l=i[c],u=l.getString()||`child-${c}`,h=r[u];if(!h){console.warn(`PCB grid layout: No coordinates found for child ${u}`);continue}let d=s.x-o.containerWidth/2+h.x+h.width/2,_=s.y+o.containerHeight/2-h.y-h.height/2;if(l.pcb_component_id)Yg(a,l.pcb_component_id,{x:d,y:_});else{let y=l;y.pcb_group_id&&y.source_group_id&&Xg(a,y.source_group_id,{x:d,y:_})}}}function w5t(e){let{db:t,group:n,props:i,gridLayout:r}=e;if(n.pcb_group_id){let o=n._getGlobalPcbPositionBeforeLayout();t.pcb_group.update(n.pcb_group_id,{width:i.width??r.containerWidth,height:i.height??r.containerHeight,center:o})}}function S5t(e){let t={serverUrl:"https://registry-api.tscircuit.com",serverMode:"job",serverCacheEnabled:!0};if(typeof e=="object"&&!e.preset)return{local:!(e.serverUrl||e.serverMode||e.serverCacheEnabled),...t,...e};let n=typeof e=="object"?e.preset:e,i=typeof e=="object"?e:{};switch(n){case"auto-local":return{local:!0,groupMode:"subcircuit"};case"sequential-trace":return{local:!0,groupMode:"sequential-trace"};case"subcircuit":return{local:!0,groupMode:"subcircuit"};case"auto-cloud":{let{preset:r,local:o,groupMode:s,...a}=i;return{local:!1,groupMode:"subcircuit",...t,...a}}default:return{local:!0,groupMode:"subcircuit"}}}var P5t=(e,t)=>{let n=e.children.filter(h=>h.componentName==="Constraint"&&h._parsedProps.pcb),i=new Map,r={},o=h=>(r[h]!==h&&(r[h]=o(r[h])),r[h]),s=(h,d)=>{let _=o(h),y=o(d);_!==y&&(r[y]=_)},a=h=>{h in r||(r[h]=h)},c=h=>{let d=h.startsWith(".")?h.slice(1):h;return e.children.find(y=>y.name===d)?.pcb_component_id??void 0};for(let h of n){let d=h._parsedProps;if("left"in d&&"right"in d){let _=c(d.left),y=c(d.right);_&&y&&(a(_),a(y),s(_,y))}else if("top"in d&&"bottom"in d){let _=c(d.top),y=c(d.bottom);_&&y&&(a(_),a(y),s(_,y))}else if("for"in d&&Array.isArray(d.for)){let _=d.for.map(y=>c(y)).filter(y=>!!y);for(let y of _)a(y);for(let y=1;y<_.length;y++)s(_[0],_[y])}}for(let h of Object.keys(r)){let d=o(h);i.has(d)||i.set(d,{componentIds:[],constraints:[]}),i.get(d).componentIds.push(h)}for(let h of n){let d=h._parsedProps,_;if("left"in d?_=c(d.left):"top"in d?_=c(d.top):"for"in d&&(_=c(d.for[0])),!_)continue;let y=o(_);i.get(y)?.constraints.push(h)}let l={},u=Object.fromEntries(t.components.map(h=>[h.componentId,h]));for(let[h,d]of i.entries()){if(d.componentIds.length<=1)continue;let _=new jp,y={},g=(A,O)=>{let $=`${A}_${O}`;return y[$]||(y[$]=new Xs($)),y[$]},x=d.componentIds[0];_.addConstraint(new ai(g(x,"x"),Yn.Eq,0,wn.required)),_.addConstraint(new ai(g(x,"y"),Yn.Eq,0,wn.required));for(let A of d.constraints){let O=A._parsedProps;if("xDist"in O){let $=c(O.left),B=c(O.right);$&&B&&_.addConstraint(new ai(new Cn(g(B,"x"),[-1,g($,"x")]),Yn.Eq,O.xDist,wn.required))}else if("yDist"in O){let $=c(O.top),B=c(O.bottom);$&&B&&_.addConstraint(new ai(new Cn(g($,"y"),[-1,g(B,"y")]),Yn.Eq,O.yDist,wn.required))}else if("sameX"in O&&Array.isArray(O.for)){let $=O.for.map(B=>c(B)).filter(B=>!!B);if($.length>1){let B=g($[0],"x");for(let H=1;H<$.length;H++)_.addConstraint(new ai(new Cn(g($[H],"x"),[-1,B]),Yn.Eq,0,wn.required))}}else if("sameY"in O&&Array.isArray(O.for)){let $=O.for.map(B=>c(B)).filter(B=>!!B);if($.length>1){let B=g($[0],"y");for(let H=1;H<$.length;H++)_.addConstraint(new ai(new Cn(g($[H],"y"),[-1,B]),Yn.Eq,0,wn.required))}}}_.updateVariables();let w={};for(let A of d.componentIds)w[A]={x:g(A,"x").value(),y:g(A,"y").value()};let S=1/0,C=1/0,I=-1/0,k=-1/0;for(let A of d.componentIds){let O=u[A],$=w[A];if(O)for(let B of O.pads){let H=$.x+B.offset.x,X=$.y+B.offset.y;S=Math.min(S,H-B.size.x/2),I=Math.max(I,H+B.size.x/2),C=Math.min(C,X-B.size.y/2),k=Math.max(k,X+B.size.y/2)}}let P={x:(S+I)/2,y:(C+k)/2},N=[],E={};for(let A of d.componentIds){let O=u[A],$=w[A];if(O){E[A]={x:$.x-P.x,y:$.y-P.y};for(let B of O.pads)N.push({padId:B.padId,networkId:B.networkId,type:B.type,size:B.size,offset:{x:$.x+B.offset.x-P.x,y:$.y+B.offset.y-P.y}})}}t.components=t.components.filter(A=>!d.componentIds.includes(A.componentId)),t.components.push({componentId:d.componentIds[0],pads:N,availableRotationDegrees:[0]}),d.relativeCenters=E,l[d.componentIds[0]]=d}return l},hV=({db:e,pcbComponentId:t,rotationDegrees:n,layer:i})=>{if(n==null||!e?.cad_component?.list)return;let r=e.cad_component.getWhere({pcb_component_id:t});if(!r)return;let o=i?.toLowerCase?.()==="bottom"?-n:n,s=r.rotation?.z??0,a={...r.rotation??{x:0,y:0,z:0},z:Rl(s+o)};e.cad_component.update(r.cad_component_id,{rotation:a}),r.rotation=a},pm=(e,t,n)=>{if(t===n)return!0;let i=e.source_group.get(t);return!i||!i.parent_source_group_id?!1:pm(e,i.parent_source_group_id,n)},T5t=(e,t,n)=>{let{db:i}=e.root;for(let r of t.components){let{center:o,componentId:s,ccwRotationOffset:a,ccwRotationDegrees:c}=r,l=n[s];if(l){let x=c??a??0,w=x*Math.PI/180;for(let S of l.componentIds){let C=l.relativeCenters[S];if(!C)continue;let I={x:C.x*Math.cos(w)-C.y*Math.sin(w),y:C.x*Math.sin(w)+C.y*Math.cos(w)},k=i.pcb_component.get(S);if(!k)continue;let P=k.center,N=Jn(e._computePcbGlobalTransformBeforeLayout(),vn(o.x+I.x,o.y+I.y),ja(w),vn(-P.x,-P.y)),E=i.toArray().filter(A=>"pcb_component_id"in A&&A.pcb_component_id===S);Hp(E,N),hV({db:i,pcbComponentId:S,rotationDegrees:x,layer:k.layer})}continue}let u=i.pcb_component.get(s);if(u){let x=e.source_group_id,S=i.source_component.get(u.source_component_id)?.source_group_id;if(S!==void 0&&!pm(i,S,x))continue;let C=u.center,I=c??a??0,k=Jn(e._computePcbGlobalTransformBeforeLayout(),vn(o.x,o.y),ja(I*Math.PI/180),vn(-C.x,-C.y)),P=i.toArray().filter(N=>"pcb_component_id"in N&&N.pcb_component_id===s);Hp(P,k),hV({db:i,pcbComponentId:s,rotationDegrees:I,layer:u.layer});continue}let h=i.pcb_group.list().find(x=>x.source_group_id===s);if(!h)continue;let d=h.center,_=c??a??0,y=Jn(e._computePcbGlobalTransformBeforeLayout(),vn(o.x,o.y),ja(_*Math.PI/180),vn(-d.x,-d.y)),g=i.toArray().filter(x=>{if("source_group_id"in x&&x.source_group_id&&(x.source_group_id===s||pm(i,x.source_group_id,s)))return!0;if("source_component_id"in x&&x.source_component_id){let w=i.source_component.get(x.source_component_id);if(w?.source_group_id&&(w.source_group_id===s||pm(i,w.source_group_id,s)))return!0}if("pcb_component_id"in x&&x.pcb_component_id){let w=i.pcb_component.get(x.pcb_component_id);if(w?.source_component_id){let S=i.source_component.get(w.source_component_id);if(S?.source_group_id&&(S.source_group_id===s||pm(i,S.source_group_id,s)))return!0}}return!1});Hp(g,y),i.pcb_group.update(h.pcb_group_id,{center:o})}};function I5t(e){switch(e.shape){case"rect":case"rotated_rect":case"pill":case"rotated_pill":return{width:e.width,height:e.height};case"circle":return{width:e.radius*2,height:e.radius*2};case"polygon":if(!e.points||e.points.length===0)return null;let t=e.points.map(a=>a.x),n=e.points.map(a=>a.y),i=Math.min(...t),r=Math.max(...t),o=Math.min(...n),s=Math.max(...n);return{width:r-i,height:s-o};default:return null}}function M5t(e){switch(e.shape){case"circular_hole_with_rect_pad":case"pill_hole_with_rect_pad":case"rotated_pill_hole_with_rect_pad":return{width:e.rect_pad_width,height:e.rect_pad_height};case"circle":return{width:e.outer_diameter,height:e.outer_diameter};case"oval":return{width:e.outer_width,height:e.outer_height};case"pill":return{width:e.outer_width,height:e.outer_height};default:return null}}var C5t="1mm",dV=(0,HV.default)("Group_doInitialPcbLayoutPack"),E5t=e=>{let{db:t}=e.root,{_parsedProps:n}=e,{packOrderStrategy:i,packPlacementStrategy:r,gap:o,pcbGap:s,pcbPackGap:a}=n,c=a??s??o,l=D.parse(c??C5t),u={},h=new Set,d=I=>{if(I?.pcb_component_id&&I?._parsedProps){let k=I._parsedProps,P=D.parse(k.pcbMarginLeft??k.pcbMarginX??0),N=D.parse(k.pcbMarginRight??k.pcbMarginX??0),E=D.parse(k.pcbMarginTop??k.pcbMarginY??0),A=D.parse(k.pcbMarginBottom??k.pcbMarginY??0);(P||N||E||A)&&(u[I.pcb_component_id]={left:P,right:N,top:E,bottom:A})}I?.children&&I.children.forEach(d)};d(e);let _=new Set;for(let I of e.children){let k=I;k._isNormalComponent&&k.isRelativelyPositioned?.()&&(k.pcb_component_id&&h.add(k.pcb_component_id),k.pcb_group_id&&_.add(k.pcb_group_id))}let y=t.toArray().filter(I=>I.type==="pcb_component"?!h.has(I.pcb_component_id):I.type==="pcb_group"?!_.has(I.pcb_group_id):!0),g=[];for(let I of h){let k=t.toArray().find(O=>O.type==="pcb_component"&&O.pcb_component_id===I);if(!k)continue;let P=k.center.x,N=k.center.y,E=t.toArray().filter(O=>O.type==="pcb_smtpad"&&O.pcb_component_id===I);for(let O of E){let $=I5t(O);if(!$||$.width===0||$.height===0)continue;let B,H;if(O.shape==="polygon"){let X=O.points.map(tt=>tt.x),U=O.points.map(tt=>tt.y);B=P+(Math.min(...X)+Math.max(...X))/2,H=N+(Math.min(...U)+Math.max(...U))/2}else B=P+O.x,H=N+O.y;g.push({obstacleId:O.pcb_smtpad_id,absoluteCenter:{x:B,y:H},width:$.width,height:$.height})}let A=t.toArray().filter(O=>O.type==="pcb_plated_hole"&&O.pcb_component_id===I);for(let O of A){let $=M5t(O);if(!$||$.width===0||$.height===0)continue;let B=P+O.x,H=N+O.y;g.push({obstacleId:O.pcb_plated_hole_id,absoluteCenter:{x:B,y:H},width:$.width,height:$.height})}}let x;if(n.width!==void 0&&n.height!==void 0){let I=D.parse(n.width),k=D.parse(n.height);x={minX:-I/2,maxX:I/2,minY:-k/2,maxY:k/2}}let w={...eY(tY(y,{source_group_id:e.source_group_id,shouldAddInnerObstacles:!0,chipMarginsMap:u})),orderStrategy:i??"largest_to_smallest",placementStrategy:r??"minimum_sum_squared_distance_to_network",minGap:l,obstacles:g,bounds:x},S=P5t(e,w);dV.enabled&&(e.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`packInput-circuitjson-${e.name}`,content:JSON.stringify(t.toArray())}),e.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`packInput-${e.name}`,content:w}));let C=Xb(w);if(dV.enabled){let I=iI(C);I.title=`packOutput-${e.name}`,global.debugGraphics?.push(I)}T5t(e,C,S)},k5t=e=>{let{db:t}=e.root,{_parsedProps:n}=e,i=e.children.filter(k=>k.pcb_component_id||k.pcb_group_id);if(i.some(k=>{let P=k._parsedProps;return P?.pcbX!==void 0||P?.pcbY!==void 0}))return;let o=n.pcbJustifyContent??n.justifyContent,s=n.pcbAlignItems??n.alignItems,a=n.pcbFlexGap??n.pcbGap??n.gap,c=n.pcbFlexDirection??"row",l={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"space-between","space-between":"space-between","space-around":"space-around","space-evenly":"space-evenly",center:"center"}[o??"space-between"],u={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"stretch",center:"center"}[s??"center"];if(!l)throw new Error(`Invalid justifyContent value: "${o}"`);if(!u)throw new Error(`Invalid alignItems value: "${s}"`);let h=0,d=0;typeof a=="object"?(h=a.y??0,d=a.x??0):typeof a=="number"?(h=a,d=a):typeof a=="string"&&(h=D.parse(a),d=D.parse(a));let _,y=n.width??n.pcbWidth??void 0,g=n.height??n.pcbHeight??void 0;(y===void 0||g===void 0)&&(_=Vg(i.map(k=>k._getMinimumFlexContainerSize()).filter(k=>k!==null),{alignItems:u,justifyContent:l,direction:c,rowGap:h,columnGap:d}),y=_.width,g=_.height);let w=new Gb(y,g,{alignItems:u,justifyContent:l,direction:c,rowGap:h,columnGap:d});for(let k of i){let P=k._getMinimumFlexContainerSize();w.addChild({metadata:k,width:P?.width??0,height:P?.height??0,flexBasis:P?c==="row"?P.width:P.height:void 0})}w.build();let S={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let k of w.children)S.minX=Math.min(S.minX,k.position.x),S.minY=Math.min(S.minY,k.position.y),S.maxX=Math.max(S.maxX,k.position.x+k.size.width),S.maxY=Math.max(S.maxY,k.position.y+k.size.height);S.width=S.maxX-S.minX,S.height=S.maxY-S.minY;let C=e._getGlobalPcbPositionBeforeLayout(),I={x:C.x-(S.maxX+S.minX)/2,y:C.y-(S.maxY+S.minY)/2};for(let k of w.children)k.metadata._repositionOnPcb({x:k.position.x+k.size.width/2+I.x,y:k.position.y+k.size.height/2+I.y});t.pcb_group.update(e.pcb_group_id,{width:S.width,height:S.height,center:C})};function N5t(e){let{db:t}=e.root,n=new Map,i=new Map,r=new Set,s=e.selectAll("trace").filter(O=>O._parsedProps?.schDisplayLabel),a=e.selectAll("group"),c=[e.schematic_group_id,...a.map(O=>O.schematic_group_id)],l=t.schematic_component.list().filter(O=>c.includes(O.schematic_group_id)),u=[],h=new Map,d=new Map;for(let O of l){let $=O.schematic_component_id,B=[],H=t.source_component.getWhere({source_component_id:O.source_component_id}),X=t.schematic_port.list({schematic_component_id:O.schematic_component_id});for(let U of X){let tt=`${H?.name??O.schematic_component_id}.${U.pin_number}`;h.set(tt,U.schematic_port_id),d.set(U.schematic_port_id,tt)}for(let U of X){let tt=d.get(U.schematic_port_id);B.push({pinId:tt,x:U.center.x,y:U.center.y})}u.push({chipId:$,center:O.center,width:O.size.width,height:O.size.height,pins:B})}let _=new Set,y=new Map,g=new Map,x=new Map;for(let O of l){let $=t.schematic_port.list({schematic_component_id:O.schematic_component_id});for(let B of $)_.add(B.schematic_port_id),B.source_port_id&&(y.set(B.schematic_port_id,B.source_port_id),g.set(B.source_port_id,B.schematic_port_id))}let w=new Set;e.subcircuit_id&&w.add(e.subcircuit_id);for(let O of a)O.subcircuit_id&&w.add(O.subcircuit_id);let C=t.source_trace.list().filter(O=>{if(O.subcircuit_id===e.subcircuit_id)return!0;for(let $ of O.connected_source_port_ids)if(g.has($))return!0;return!1}).flatMap(O=>O.connected_source_net_ids);for(let O of C){let $=t.source_net.get(O);$?.subcircuit_id&&w.add($.subcircuit_id)}let I=[],k=new Map;for(let O of t.source_trace.list()){if(O.subcircuit_id&&!w.has(O.subcircuit_id))continue;let $=(O.connected_source_port_ids??[]).map(B=>g.get(B)).filter(B=>!!B&&_.has(B));if($.length>=2){let[B,H]=$.slice(0,2),X=[B,H].sort().join("::");if(!k.has(X)){k.set(X,O.source_trace_id);let U=O.display_name??O.source_trace_id;O.subcircuit_connectivity_map_key&&(r.add(O.subcircuit_connectivity_map_key),x.set(U,O.subcircuit_connectivity_map_key),i.set(O.subcircuit_connectivity_map_key,U)),I.push({pinIds:[B,H].map(tt=>d.get(tt)),netId:U})}}}let P=[];for(let O of t.source_net.list().filter($=>!$.subcircuit_id||w.has($.subcircuit_id)))O.subcircuit_connectivity_map_key&&(r.add(O.subcircuit_connectivity_map_key),n.set(O.subcircuit_connectivity_map_key,O));let N=new Map;for(let[O,$]of y){let B=t.source_port.get($);if(!B?.subcircuit_connectivity_map_key)continue;let H=B.subcircuit_connectivity_map_key;r.add(H),N.has(H)||N.set(H,[]),N.get(H).push(O)}for(let[O,$]of N){let B=n.get(O);if(B&&$.length>=2){let H=String(B.name||B.source_net_id||O);x.set(H,O),i.set(O,H);let U=.1*(.18/.18),tt=Number((String(H).length*U).toFixed(2));P.push({netId:H,pinIds:$.map(J=>d.get(J)),netLabelWidth:tt})}}let E=(()=>{let O={},$=new Set(P.map(B=>B.netId));for(let B of t.source_net.list().filter(H=>!H.subcircuit_id||w.has(H.subcircuit_id)))B.name&&$.has(B.name)&&(B.is_ground||B.name.toLowerCase().startsWith("gnd")?O[B.name]=["y-"]:B.is_power||B.name.toLowerCase().startsWith("v")?O[B.name]=["y+"]:O[B.name]=["x-","x+"]);return O})();return{inputProblem:{chips:u,directConnections:I,netConnections:P,availableNetLabelOrientations:E,maxMspPairDistance:e._parsedProps.schMaxTraceDistance??2.4},pinIdToSchematicPortId:h,pairKeyToSourceTraceId:k,sckToSourceNet:n,sckToUserNetId:i,userNetIdToSck:x,allSourceAndSchematicPortIdsInScope:_,schPortIdToSourcePortId:y,displayLabelTraces:s,allScks:r}}var er=1e-6;function fV(e){let t=Math.abs(e.to.x-e.from.x),n=Math.abs(e.to.y-e.from.y);return t>=n}function hx(e,t){return Math.hypot(t.x-e.x,t.y-e.y)}function mV(e,t,n){return{x:e.x+(t.x-e.x)*n,y:e.y+(t.y-e.y)*n}}function _V(e,t,n){let i=hx(e,t);if(i<er)return 0;let r=((n.x-e.x)*(t.x-e.x)+(n.y-e.y)*(t.y-e.y))/((t.x-e.x)*(t.x-e.x)+(t.y-e.y)*(t.y-e.y));return Math.max(0,Math.min(1,r))*i}function sx(e,t,n,i){return e*i-t*n}function A5t(e,t,n,i){let r={x:t.x-e.x,y:t.y-e.y},o={x:i.x-n.x,y:i.y-n.y},s=sx(r.x,r.y,o.x,o.y),a={x:n.x-e.x,y:n.y-e.y},c=sx(a.x,a.y,r.x,r.y);if(Math.abs(s)<er&&Math.abs(c)<er||Math.abs(s)<er&&Math.abs(c)>=er)return null;let l=sx(a.x,a.y,o.x,o.y)/s,u=sx(a.x,a.y,r.x,r.y)/s;return l<-er||l>1+er||u<-er||u>1+er?null:{x:e.x+l*r.x,y:e.y+l*r.y}}function R5t(e,t=er){if(e.length===0)return e;e.sort((r,o)=>r.start-o.start);let n=[],i={...e[0]};for(let r=1;r<e.length;r++){let o=e[r];o.start<=i.end+t?i.end=Math.max(i.end,o.end):(n.push(i),i={...o})}return n.push(i),n}function O5t(e,t,n){let i=hx(e.from,e.to);if(i<er||t.length===0)return[e];let r=n/2,o=t.map(h=>({start:Math.max(0,h-r),end:Math.min(i,h+r)})).filter(h=>h.end-h.start>er),s=R5t(o),a=[],c=0,l={x:e.to.x-e.from.x,y:e.to.y-e.from.y},u=(h,d,_)=>{if(d-h<=er)return;let y=h/i,g=d/i;a.push({from:mV(e.from,e.to,y),to:mV(e.from,e.to,g),..._?{is_crossing:!0}:{}})};for(let h of s)h.start-c>er&&u(c,h.start,!1),u(h.start,h.end,!0),c=h.end;return i-c>er&&u(c,i,!1),a.length>0?a:[e]}function L5t(e,t={}){let n=t.crossSegmentLength??.075,i=t.tolerance??er,r=new Map,o=c=>`${c.traceIdx}:${c.edgeIdx}`,s=c=>e[c.traceIdx].edges[c.edgeIdx];for(let c=0;c<e.length;c++){let l=e[c];for(let u=0;u<l.edges.length;u++){let h=l.edges[u];for(let d=c;d<e.length;d++){let _=e[d];for(let y=d===c?u+1:0;y<_.edges.length;y++){let g=_.edges[y],x=A5t(h.from,h.to,g.from,g.to);if(!x)continue;let w=hx(h.from,h.to),S=hx(g.from,g.to);if(w<i||S<i)continue;let C=_V(h.from,h.to,x),I=_V(g.from,g.to,x),k=C<=i||Math.abs(w-C)<=i||Number.isNaN(C),P=I<=i||Math.abs(S-I)<=i||Number.isNaN(I);if(!k&&!P){let N=fV(h),E=fV(g),A;if(N!==E)A=N;else{let B=Math.abs(h.to.x-h.from.x),H=Math.abs(h.to.y-h.from.y),X=Math.abs(g.to.x-g.from.x),U=Math.abs(g.to.y-g.from.y),tt=B-H,J=X-U;A=tt===J?!0:tt>J}let O=o({traceIdx:A?c:d,edgeIdx:A?u:y}),$=r.get(O)??[];$.push(A?C:I),r.set(O,$)}}}}}let a=e.map(c=>({source_trace_id:c.source_trace_id,edges:[]}));for(let c=0;c<e.length;c++){let l=e[c];for(let u=0;u<l.edges.length;u++){let h=o({traceIdx:c,edgeIdx:u}),d=r.get(h)??[];if(d.length===0){a[c].edges.push(l.edges[u]);continue}let _=Array.from(new Set(d.map(g=>Number(g.toFixed(6))))).sort((g,x)=>g-x),y=O5t(l.edges[u],_,n);a[c].edges.push(...y)}}return a}var cs=1e-6;function dx(e,t,n=cs){return Math.abs(e-t)<=n}function Ah(e,t,n=cs){return dx(e.x,t.x,n)&&dx(e.y,t.y,n)}function yV(e,t,n,i=cs){let r=Math.min(t.x,n.x)-i,o=Math.max(t.x,n.x)+i,s=Math.min(t.y,n.y)-i,a=Math.max(t.y,n.y)+i;return e.x<r||e.x>o||e.y<s||e.y>a?!1:Math.abs((n.x-t.x)*(e.y-t.y)-(n.y-t.y)*(e.x-t.x))<=i}function gV(e,t=cs){let n=new Map;for(let i of e){let r=`${i.x.toFixed(6)},${i.y.toFixed(6)}`;n.has(r)||n.set(r,i)}return Array.from(n.values())}function bV(e){return{x:e.to.x-e.from.x,y:e.to.y-e.from.y}}function HI(e,t,n=cs){let i=bV(e),r=bV(t),o=Math.hypot(i.x,i.y),s=Math.hypot(r.x,r.y);if(o<n||s<n)return!0;let a=i.x*r.y-i.y*r.x;return Math.abs(a)<=n*o*s}function hm(e,t,n=cs){return e.edges.filter(i=>Ah(i.from,t,n)||Ah(i.to,t,n))}function xV(e,t,n=cs){for(let i of e.edges){if(Ah(i.from,t,n))return i.from;if(Ah(i.to,t,n))return i.to}return null}function F5t(e,t,n=cs){let i=Ah(e.from,t,n)||dx(e.from.x,t.x,n)&&dx(e.from.y,t.y,n)?e.to:e.from,r=i.x-t.x,o=i.y-t.y;return Math.abs(r)<n&&Math.abs(o)<n?null:Math.abs(r)>=Math.abs(o)?r>=0?"right":"left":o>=0?"up":"down"}function Mh(e,t,n=cs){let i=hm(e,t,n);if(i.length<2)return null;let r=i.map(h=>F5t(h,t,n)),o=r.includes("up"),s=r.includes("down"),a=r.includes("left"),c=r.includes("right"),l=o?"up":s?"down":null,u=c?"right":a?"left":null;return l&&u?`${l}-${u}`:null}function z5t(e,t={}){let n=t.tolerance??cs,i={};for(let o of e)i[o.source_trace_id]=[];let r=e.map(o=>{let s=[];for(let a of o.edges)s.push(a.from,a.to);return gV(s,n)});for(let o=0;o<e.length;o++){let s=e[o],a=r[o];for(let c=o+1;c<e.length;c++){let l=e[c],u=r[c];for(let h of a)for(let d of u)if(Ah(h,d,n)){let _=hm(s,h,n),y=hm(l,d,n),g=_.some(C=>y.some(I=>!HI(C,I,n))),x=Mh(s,h,n),w=Mh(l,d,n);g&&!(x!==null&&w!==null&&x===w)&&(i[s.source_trace_id].push(h),s.source_trace_id!==l.source_trace_id&&i[l.source_trace_id].push(d))}for(let h of a)for(let d of l.edges)if(yV(h,d.from,d.to,n)){let y=hm(s,h,n).some(C=>!HI(C,d,n)),g=Mh(s,h,n),x=xV(l,h,n*1e3),w=x?Mh(l,x,n):null;y&&!(g!==null&&w!==null&&g===w)&&(i[s.source_trace_id].push(h),s.source_trace_id!==l.source_trace_id&&i[l.source_trace_id].push(h))}for(let h of u)for(let d of s.edges)if(yV(h,d.from,d.to,n)){let y=hm(l,h,n).some(C=>!HI(d,C,n)),g=Mh(l,h,n),x=xV(s,h,n*1e3),w=x?Mh(s,x,n):null;y&&!(w!==null&&g!==null&&w===g)&&(i[l.source_trace_id].push(h),s.source_trace_id!==l.source_trace_id&&i[s.source_trace_id].push(h))}}}for(let o of Object.keys(i))i[o]=gV(i[o],n);return i}var GI=(0,UV.default)("Group_doInitialSchematicTraceRender");function D5t(e){let{group:t,solver:n,pinIdToSchematicPortId:i,userNetIdToSck:r}=e,{db:o}=t.root,s=n.traceLabelOverlapAvoidanceSolver?.getOutput().traces??n.schematicTraceLinesSolver?.solvedTracePaths,a=[];GI(`Traces inside SchematicTraceSolver output: ${(s??[]).length}`);for(let u of s??[]){let h=u?.tracePath;if(!Array.isArray(h)||h.length<2){GI(`Skipping trace ${u?.pinIds.join(",")} because it has less than 2 points`);continue}let d=[];for(let g=0;g<h.length-1;g++)d.push({from:{x:h[g].x,y:h[g].y},to:{x:h[g+1].x,y:h[g+1].y}});let _=null,y;if(Array.isArray(u?.pins)&&u.pins.length===2){let g=i.get(u.pins[0]?.pinId),x=i.get(u.pins[1]?.pinId);if(g&&x){for(let w of[g,x])o.schematic_port.get(w)&&o.schematic_port.update(w,{is_connected:!0});y=r.get(String(u.userNetId))}}_||(_=`solver_${u?.mspPairId}`,y=r.get(String(u.userNetId))),a.push({source_trace_id:_,edges:d,subcircuit_connectivity_map_key:y})}GI(`Applying ${a.length} traces from SchematicTraceSolver output`);let c=L5t(a.map(u=>({source_trace_id:u.source_trace_id,edges:u.edges}))),l=z5t(c);for(let u of c)o.schematic_trace.insert({source_trace_id:u.source_trace_id,edges:u.edges,junctions:l[u.source_trace_id]??[],subcircuit_connectivity_map_key:a.find(h=>h.source_trace_id===u.source_trace_id)?.subcircuit_connectivity_map_key})}var $5t=e=>{switch(e){case"x+":return"left";case"x-":return"right";case"y+":return"bottom";case"y-":return"top";case"left":return"right";case"top":return"bottom";case"right":return"left";case"bottom":return"top"}},B5t=e=>{for(let n of e){let i=n._getDirectlyConnectedTraces();for(let r of i){let o=r._parsedProps.schDisplayLabel;if(o)return{name:o,wasAssignedDisplayLabel:!0}}}return{name:e.map(n=>n._getNetLabelText()).join("/"),wasAssignedDisplayLabel:!1}},UI=(0,qV.default)("Group_doInitialSchematicTraceRender");function j5t(e){let{group:t,solver:n,sckToSourceNet:i,allScks:r,allSourceAndSchematicPortIdsInScope:o,schPortIdToSourcePortId:s,userNetIdToSck:a,pinIdToSchematicPortId:c,schematicPortIdsWithPreExistingNetLabels:l,schematicPortIdsWithRoutedTraces:u}=e,{db:h}=t.root,d=n.traceLabelOverlapAvoidanceSolver?.getOutput().netLabelPlacements??[],_=n.mspConnectionPairSolver.globalConnMap;for(let y of d){UI(`processing placement: ${y.netId}`);let g=_.getIdsConnectedToNet(y.globalConnNetId).find(O=>a.get(O)),x=a.get(g),w=y.anchorPoint,S=y.orientation,C=$5t(S),I=x?i.get(x):void 0,k=y.pinIds.map(O=>c.get(O));if(k.some(O=>l.has(O))){UI(`skipping net label placement for "${y.netId}" REASON:schematic port has pre-existing net label`);continue}if(I){let O=I.name,$=xc({anchor_position:w,anchor_side:C,text:O});h.schematic_net_label.insert({text:O,anchor_position:w,center:$,anchor_side:C,...I?.source_net_id?{source_net_id:I.source_net_id}:{}});continue}let P=t.selectAll("port").filter(O=>O._getSubcircuitConnectivityKey()===x),{name:N,wasAssignedDisplayLabel:E}=B5t(P);if(!E&&k.some(O=>u.has(O))){UI(`skipping net label placement for "${y.netId}" REASON:schematic port has routed traces and no display label`);continue}let A=xc({anchor_position:w,anchor_side:C,text:N});h.schematic_net_label.insert({text:N,anchor_position:w,center:A,anchor_side:C})}}var Y5t=({allSourceAndSchematicPortIdsInScope:e,group:t,schPortIdToSourcePortId:n,sckToSourceNet:i,pinIdToSchematicPortId:r,schematicPortIdsWithPreExistingNetLabels:o})=>{let{db:s}=t.root;for(let a of Array.from(e)){let c=s.schematic_port.get(a);if(!c||c.is_connected)continue;let l=n.get(a);if(!l)continue;let h=s.source_port.get(l)?.subcircuit_connectivity_map_key;if(!h)continue;let d=i.get(h);if(!d||s.schematic_net_label.list().some(w=>Math.abs(w.anchor_position.x-c.center.x)<.1&&Math.abs(w.anchor_position.y-c.center.y)<.1?d.source_net_id&&w.source_net_id?w.source_net_id===d.source_net_id:w.text===(d.name||h):!1))continue;let y=d.name||d.source_net_id||h,g=ym(c.facing_direction||"right")||"right",x=xc({anchor_position:c.center,anchor_side:g,text:y});s.schematic_net_label.insert({text:y,anchor_position:c.center,center:x,anchor_side:g,...d.source_net_id?{source_net_id:d.source_net_id}:{}})}},X5t=e=>{let t=new Set,n=e.selectAll("netlabel");for(let i of n){let r=i._getConnectedPorts();for(let o of r)o.schematic_port_id&&t.add(o.schematic_port_id)}return t},V5t=({solver:e,pinIdToSchematicPortId:t})=>{let n=e.schematicTraceLinesSolver.solvedTracePaths,i=new Set;for(let r of n)for(let o of r.pinIds){let s=t.get(o);s&&i.add(s)}return i},H5t=(0,GV.default)("Group_doInitialSchematicTraceRender"),G5t=e=>{if(!e.root?._featureMspSchematicTraceRouting||!e.isSubcircuit||e.root?.schematicDisabled)return;let{inputProblem:t,pinIdToSchematicPortId:n,pairKeyToSourceTraceId:i,sckToSourceNet:r,allSourceAndSchematicPortIdsInScope:o,schPortIdToSourcePortId:s,displayLabelTraces:a,allScks:c,userNetIdToSck:l}=N5t(e),u=X5t(e);H5t.enabled&&e.root?.emit("debug:logOutput",{type:"debug:logOutput",name:"group-trace-render-input-problem",content:JSON.stringify(t,null,2)});let h=new MY(t);h.solve();let d=V5t({solver:h,pinIdToSchematicPortId:n});D5t({group:e,solver:h,pinIdToSchematicPortId:n,userNetIdToSck:l}),j5t({group:e,solver:h,sckToSourceNet:r,allSourceAndSchematicPortIdsInScope:o,schPortIdToSourcePortId:s,pinIdToSchematicPortId:n,allScks:c,userNetIdToSck:l,schematicPortIdsWithPreExistingNetLabels:u,schematicPortIdsWithRoutedTraces:d}),Y5t({group:e,allSourceAndSchematicPortIdsInScope:o,schPortIdToSourcePortId:s,sckToSourceNet:r,pinIdToSchematicPortId:n,schematicPortIdsWithPreExistingNetLabels:u})},U5t=()=>({async simulate(e){let t="spice-experiment-1",{circuit:n,tran:i}=kY(e);return{simulationResultCircuitJson:NY(i,n,t)}}}),ta=(0,WV.default)("tscircuit:core:Group_doInitialSimulationSpiceEngineRender");function q5t(e){if(!e.isSubcircuit)return;let{root:t}=e;if(!t||e.selectAll("analogsimulation").length===0)return;let i={...t.platform?.spiceEngineMap};i.spicey||(i.spicey=U5t());let r=t.db.toArray(),o;try{o=EY(r).toSpiceString(),ta(`Generated SPICE string:
|
|
242
|
+
${i.stack}`),n.complete=!0,"root"in this&&this.root&&this.root.emit("asyncEffect:end",{effectName:e,componentDisplayName:this.getString(),phase:n.phase,error:i.toString()})})}_emitRenderLifecycleEvent(e,t){GPt(`${e}:${t} ${this.getString()}`);let n=`renderable:renderLifecycle:${e}:${t}`,i={renderId:this._renderId,componentDisplayName:this.getString(),type:n};"root"in this&&this.root&&(this.root.emit(n,i),this.root.emit("renderable:renderLifecycle:anyEvent",{...i,type:n}))}getString(){return this.constructor.name}_hasIncompleteAsyncEffects(){return this._asyncEffects.some(e=>!e.complete)}_hasIncompleteAsyncEffectsInSubtreeForPhase(e){for(let t of this._asyncEffects)if(!t.complete&&t.phase===e)return!0;for(let t of this.children)if(t._hasIncompleteAsyncEffectsInSubtreeForPhase(e))return!0;return!1}getCurrentRenderPhase(){return this._currentRenderPhase}getRenderGraph(){return{id:this._renderId,currentPhase:this._currentRenderPhase,renderPhaseStates:this.renderPhaseStates,shouldBeRemoved:this.shouldBeRemoved,children:this.children.map(e=>e.getRenderGraph())}}runRenderCycle(){for(let e of ea)this.runRenderPhaseForChildren(e),this.runRenderPhase(e)}runRenderPhase(e){this._currentRenderPhase=e;let t=this.renderPhaseStates[e],n=t.initialized,i=t.dirty;if(!n&&this.shouldBeRemoved)return;if(this.shouldBeRemoved&&n){this._emitRenderLifecycleEvent(e,"start"),this?.[`remove${e}`]?.(),t.initialized=!1,t.dirty=!1,this._emitRenderLifecycleEvent(e,"end");return}let r=ea.indexOf(e)-1;if(r>=0){let s=ea[r];if(this._asyncEffects.filter(c=>c.phase===s).some(c=>!c.complete))return}let o=UPt[e]||[];for(let s of o)if(this._hasIncompleteAsyncEffectsInSubtreeForPhase(s))return;if(this._emitRenderLifecycleEvent(e,"start"),n){i&&(this?.[`update${e}`]?.(),t.dirty=!1),this._emitRenderLifecycleEvent(e,"end");return}t.dirty=!1,this?.[`doInitial${e}`]?.(),t.initialized=!0,this._emitRenderLifecycleEvent(e,"end")}runRenderPhaseForChildren(e){for(let t of this.children)t.runRenderPhaseForChildren(e),t.runRenderPhase(e)}renderError(e){throw typeof e=="string"?new Error(e):new Error(JSON.stringify(e,null,2))}},lx={},IV=e=>{let t=Object.fromEntries(Object.entries(e).map(([n,i])=>[n.toLowerCase(),i]));Object.assign(lx,e),Object.assign(lx,t)},WPt=class extends Error{constructor(e,t,n){let i,r=Object.keys(n).filter(c=>c!=="_errors"),o=[],s=t.pinLabels;if(s)for(let[c,l]of Object.entries(s)){let u=Array.isArray(l)?l:[l];for(let h of u)typeof h=="string"&&(h.startsWith(" ")||h.endsWith(" "))&&o.push(`pinLabels.${c} ("${h}" has leading or trailing spaces)`)}let a=r.map(c=>c==="pinLabels"&&o.length>0?o.join(", "):n[c]._errors[0]?`${c} (${n[c]._errors[0]})`:`${c} (${JSON.stringify(n[c])})`).join(", ");"name"in t?i=`Invalid props for ${e} "${t.name}": ${a}`:"footprint"in t&&typeof t.footprint=="string"?i=`Invalid props for ${e} (unnamed ${t.footprint} component): ${a}`:i=`Invalid props for ${e} (unnamed): ${a}`,super(i),this.componentName=e,this.originalProps=t,this.formattedError=n}};function jI(e,t){let n=t.match(/^#(\w+)/);if(n)return e.props.id===n[1];let i=t.match(/^\.(\w+)/);if(i)return e.isMatchingNameOrAlias(i[1]);let[r,...o]=t.split(/(?=[#.[])/);return r==="pin"&&(r="port"),r&&r!=="*"&&e.lowercaseComponentName!==r.toLowerCase()?!1:o.every(s=>{if(s.startsWith("#"))return e.props.id===s.slice(1);if(s.startsWith("."))return e.isMatchingNameOrAlias(s.slice(1));let a=s.match(/\[(\w+)=['"]?(.+?)['"]?\]/);if(!a)return!0;let[,c,l]=a;return e.props[c].toString()===l})}var rM={isTag:e=>!0,getParent:e=>e.parent,getChildren:e=>e.children,getName:e=>e.lowercaseComponentName,getAttributeValue:(e,t)=>{if(t==="class"&&"getNameAndAliases"in e)return e.getNameAndAliases().join(" ");if(t==="name"&&e._parsedProps?.name)return e._parsedProps.name;if(e._parsedProps&&t in e._parsedProps){let i=e._parsedProps[t];return typeof i=="string"?i:i!=null?String(i):null}if(t in e){let i=e[t];return typeof i=="string"?i:i!=null?String(i):null}let n=e._attributeLowerToCamelNameMap;if(n){let i=n[t];if(i&&i in e){let r=e[i];return typeof r=="string"?r:r!=null?String(r):null}}return null},hasAttrib:(e,t)=>{if(t==="class")return!!e._parsedProps?.name;if(e._parsedProps&&t in e._parsedProps||t in e)return!0;let n=e._attributeLowerToCamelNameMap;if(n){let i=n[t];if(i&&i in e)return!0}return!1},getSiblings:e=>e.parent?e.parent.children:[],prevElementSibling:e=>{if(!e.parent)return null;let t=e.parent.children,n=t.indexOf(e);return n>0?t[n-1]:null},getText:()=>"",removeSubsets:e=>e.filter((t,n)=>!e.some((i,r)=>n!==r&&i!==t&&i.getDescendants().includes(t))),existsOne:(e,t)=>t.some(e),findAll:(e,t)=>{let n=[],i=r=>{e(r)&&n.push(r);for(let o of r.children)i(o)};for(let r of t)i(r);return n},findOne:(e,t)=>{for(let n of t){if(e(n))return n;let i=n.children;if(i.length>0){let r=rM.findOne(e,i);if(r)return r}}return null},equals:(e,t)=>e._renderId===t._renderId,isHovered:e=>!1,isVisited:e=>!1,isActive:e=>!1},ZPt={...rM,getChildren:e=>e.children.filter(t=>!t.isSubcircuit)},KX={...rM,getChildren:e=>e.children.filter(t=>t.isSubcircuit)},JX=e=>{if(/net\.[^\s>]*\./.test(e))throw new Error('Net names cannot contain a period, try using "sel.net..." to autocomplete with conventional net names, e.g. V3_3');if(/net\.[^\s>]*[+-]/.test(e))throw new Error('Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P');if(/net\.[0-9]/.test(e)){let t=e.match(/net\.([^ >]+)/),n=t?t[1]:"";throw new Error(`Net name "${n}" cannot start with a number, try using a prefix like "VBUS1"`)}return e.replace(/ pin(?=[\d.])/g," port").replace(/ subcircuit\./g," group[isSubcircuit=true]").replace(/([^ ])\>([^ ])/g,"$1 > $2").replace(/(^|[ >])(?!pin\.)(?!port\.)(?!net\.)([A-Z][A-Za-z0-9_-]*)\.([A-Za-z0-9_-]+)/g,(t,n,i,r)=>{let o=/^\d+$/.test(r)?`pin${r}`:r;return`${n}.${i} > .${o}`}).trim()},YI={adapter:ZPt,cacheResults:!0},xe=class extends iM{constructor(t){super(t);M(this,"parent",null);M(this,"children");M(this,"childrenPendingRemoval");M(this,"props");M(this,"_parsedProps");M(this,"externallyAddedAliases");M(this,"isPrimitiveContainer",!1);M(this,"canHaveTextChildren",!1);M(this,"source_group_id",null);M(this,"source_component_id",null);M(this,"schematic_component_id",null);M(this,"pcb_component_id",null);M(this,"cad_component_id",null);M(this,"fallbackUnassignedName");M(this,"_cachedSelectAllQueries",new Map);M(this,"_cachedSelectOneQueries",new Map);this.children=[],this.childrenPendingRemoval=[],this.props=t??{},this.externallyAddedAliases=[];let i=("partial"in this.config.zodProps?this.config.zodProps.partial({name:!0}):this.config.zodProps).safeParse(t??{});if(i.success)this._parsedProps=i.data;else throw new WPt(this.lowercaseComponentName,this.props,i.error.format())}get config(){return{componentName:"",zodProps:p.object({}).passthrough()}}get componentName(){return this.config.componentName}getInheritedProperty(t){let n=this;for(;n;){if(n._parsedProps&&t in n._parsedProps)return n._parsedProps[t];n=n.parent}if(this.root?.platform&&t in this.root.platform)return this.root.platform[t]}get lowercaseComponentName(){return this.componentName.toLowerCase()}get isSubcircuit(){return!!this.props.subcircuit||this.lowercaseComponentName==="group"&&this?.parent?.isRoot}get isGroup(){return this.lowercaseComponentName==="group"}get name(){return this._parsedProps.name??this.fallbackUnassignedName}setProps(t){let n=this.config.zodProps.parse({...this.props,...t}),i=this.props;this.props=n,this._parsedProps=this.config.zodProps.parse(t),this.onPropsChange({oldProps:i,newProps:n,changedProps:Object.keys(t)}),this.parent?.onChildChanged?.(this)}_getPcbRotationBeforeLayout(){let{pcbRotation:t}=this.props;return typeof t=="string"?parseFloat(t):t??null}computePcbPropsTransform(){let{_parsedProps:t}=this,n=this._getPcbRotationBeforeLayout()??0;return Jn(vn(t.pcbX??0,t.pcbY??0),ja(n*Math.PI/180))}_computePcbGlobalTransformBeforeLayout(){let t=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if(t&&this.props.pcbX===void 0&&this.props.pcbY===void 0){let n=this._getPcbRotationBeforeLayout()??0;return Jn(this.parent?._computePcbGlobalTransformBeforeLayout()??Li(),Jn(vn(t.x,t.y),ja(n*Math.PI/180)))}if(this.isPcbPrimitive){let n=this.getPrimitiveContainer();if(n&&n._parsedProps.layer==="bottom")return Jn(this.parent?._computePcbGlobalTransformBeforeLayout()??Li(),N6(),this.computePcbPropsTransform())}return Jn(this.parent?._computePcbGlobalTransformBeforeLayout()??Li(),this.computePcbPropsTransform())}getPrimitiveContainer(){return this.isPrimitiveContainer?this:this.parent?.getPrimitiveContainer?.()??null}getParentNormalComponent(){let t=this.parent;for(;t;){if(t.isPrimitiveContainer&&t.doInitialPcbComponentRender)return t;t=t.parent}return null}_getPcbCircuitJsonBounds(){return{center:{x:0,y:0},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getPcbPrimitiveFlippedHelpers(){let t=this.getPrimitiveContainer(),n=t?t._parsedProps.layer==="bottom":!1;return{isFlipped:n,maybeFlipLayer:r=>n?r==="top"?"bottom":"top":r}}_setPositionFromLayout(t){throw new Error(`_setPositionFromLayout not implemented for ${this.componentName}`)}computeSchematicPropsTransform(){let{_parsedProps:t}=this;return Jn(vn(t.schX??0,t.schY??0))}computeSchematicGlobalTransform(){let t=this._getSchematicGlobalManualPlacementTransform(this);return t||Jn(this.parent?.computeSchematicGlobalTransform?.()??Li(),this.computeSchematicPropsTransform())}_getSchematicSymbolName(){let{_parsedProps:t}=this,n=this.config.schematicSymbolName,i={horizontal:0,pos_left:0,neg_right:0,pos_right:180,neg_left:180,pos_top:270,neg_bottom:90,vertical:270,pos_bottom:90,neg_top:90},r=t.schOrientation!==void 0?i[t.schOrientation]:t.schRotation;if(r===void 0&&(r=0),r=r%360,r<0&&(r+=360),t.schRotation!==void 0&&r%90!==0)throw new Error(`Schematic rotation ${t.schRotation} is not supported for ${this.componentName}`);let o=`${n}_horz`,s=`${n}_vert`,a=`${n}_up`,c=`${n}_down`,l=`${n}_left`,u=`${n}_right`;if(u in Qn&&r===0)return u;if(a in Qn&&r===90)return a;if(l in Qn&&r===180)return l;if(c in Qn&&r===270)return c;if(o in Qn&&(r===0||r===180))return o;if(s in Qn&&(r===90||r===270))return s;if(n in Qn)return n}_getSchematicSymbolNameOrThrow(){let t=this._getSchematicSymbolName();if(!t)throw new Error(`No schematic symbol found (given: "${this.config.schematicSymbolName}")`);return t}getSchematicSymbol(){let t=this._getSchematicSymbolName();return t?Qn[t]??null:null}_getPcbManualPlacementForComponent(t){if(!this.isSubcircuit)return null;let n=this.props.manualEdits;if(!n)return null;let i=n?.pcb_placements;if(!i)return null;for(let r of i)if(jI(t,r.selector)||t.props.name===r.selector)return Ae(this._computePcbGlobalTransformBeforeLayout(),r.center);return null}_getSchematicManualPlacementForComponent(t){if(!this.isSubcircuit)return null;let n=this.props.manualEdits;if(!n)return null;let i=n.schematic_placements;if(!i)return null;for(let r of i)if(jI(t,r.selector)||t.props.name===r.selector)return Ae(this.computeSchematicGlobalTransform(),r.center);return null}_getSchematicGlobalManualPlacementTransform(t){let n=this.getSubcircuit()?._parsedProps.manualEdits;if(!n)return null;for(let i of n.schematic_placements??[])if((jI(t,i.selector)||t.props.name===i.selector)&&i.relative_to==="group_center")return Jn(this.parent?._computePcbGlobalTransformBeforeLayout()??Li(),vn(i.center.x,i.center.y));return null}_getGlobalPcbPositionBeforeLayout(){return Ae(this._computePcbGlobalTransformBeforeLayout(),{x:0,y:0})}_getGlobalSchematicPositionBeforeLayout(){return Ae(this.computeSchematicGlobalTransform(),{x:0,y:0})}get root(){return this.parent?.root??null}onAddToParent(t){this.parent=t}onPropsChange(t){}onChildChanged(t){this.parent?.onChildChanged?.(t)}add(t){let n=t.__text;if(typeof n=="string"){if(this.canHaveTextChildren||n.trim()==="")return;throw new Error(`Invalid JSX Element: Expected a React component but received text "${n}"`)}if(Object.keys(t).length!==0){if(this.lowercaseComponentName==="board"&&t.lowercaseComponentName==="board")throw new Error("Nested boards are not supported");if(t.lowercaseComponentName==="panel")throw new Error("<panel> must be a root-level element");if(!t.onAddToParent)throw new Error(`Invalid JSX Element: Expected a React component but received "${JSON.stringify(t)}"`);t.onAddToParent(this),t.parent=this,this.children.push(t)}}addAll(t){for(let n of t)this.add(n)}remove(t){this.children=this.children.filter(n=>n!==t),this.childrenPendingRemoval.push(t),t.shouldBeRemoved=!0}getSubcircuitSelector(){let t=this.name,n=t?`${this.lowercaseComponentName}.${t}`:this.lowercaseComponentName;return!this.parent||this.parent.isSubcircuit?n:`${this.parent.getSubcircuitSelector()} > ${n}`}getFullPathSelector(){let t=this.name,n=t?`${this.lowercaseComponentName}.${t}`:this.lowercaseComponentName,i=this.parent?.getFullPathSelector?.();return i?`${i} > ${n}`:n}getNameAndAliases(){return[this.name,...this._parsedProps.portHints??[]].filter(Boolean)}isMatchingNameOrAlias(t){return this.getNameAndAliases().includes(t)}isMatchingAnyOf(t){return this.getNameAndAliases().some(n=>t.map(i=>i.toString()).includes(n))}getPcbSize(){throw new Error(`getPcbSize not implemented for ${this.componentName}`)}doesSelectorMatch(t){let n=[this.componentName,this.lowercaseComponentName],i=[this.name].filter(Boolean),r=t.trim().split(/\> /)[0],o=r[0];return r.length>1?!1:!!(t==="*"||t[0]==="#"&&t.slice(1)===this.props.id||t[0]==="."&&i.includes(t.slice(1))||/^[a-zA-Z0-9_]/.test(o)&&n.includes(o))}getSubcircuit(){if(this.isSubcircuit)return this;let t=this.parent?.getSubcircuit?.();if(!t)throw new Error("Component is not inside an opaque group (no board?)");return t}getGroup(){return this.isGroup?this:this.parent?.getGroup?.()??null}doInitialAssignNameToUnnamedComponents(){this._parsedProps.name||(this.fallbackUnassignedName=this.getSubcircuit().getNextAvailableName(this))}doInitialOptimizeSelectorCache(){if(!this.isSubcircuit)return;let t=this.selectAll("port");for(let n of t){let r=(n.getParentNormalComponent?.()??n.parent)?.getNameAndAliases(),o=n.getNameAndAliases();if(r)for(let s of r)for(let a of o){let c=[`.${s} > .${a}`,`.${s} .${a}`];for(let l of c){let u=this._cachedSelectAllQueries.get(l);u?u.push(n):this._cachedSelectAllQueries.set(l,[n])}}}for(let[n,i]of this._cachedSelectAllQueries.entries())i.length===1&&this._cachedSelectOneQueries.set(n,i[0])}selectAll(t){if(this._cachedSelectAllQueries.has(t))return this._cachedSelectAllQueries.get(t);let n=JX(t),i=Y5(n,this,YI);if(i.length>0)return this._cachedSelectAllQueries.set(t,i),i;let[r,...o]=n.split(" "),s=vg(r,this,{adapter:KX});if(!s)return[];let a=s.selectAll(o.join(" "));return this._cachedSelectAllQueries.set(t,a),a}selectOne(t,n){if(this._cachedSelectOneQueries.has(t))return this._cachedSelectOneQueries.get(t);let i=JX(t);n?.port&&(n.type="port");let r=null;if(n?.type&&(r=Y5(i,this,YI).find(l=>l.lowercaseComponentName===n.type)),r??(r=vg(i,this,YI)),r)return this._cachedSelectOneQueries.set(t,r),r;let[o,...s]=i.split(" "),a=vg(o,this,{adapter:KX});return a?(r=a.selectOne(s.join(" "),n),this._cachedSelectOneQueries.set(t,r),r):null}getAvailablePcbLayers(){if(this.isPcbPrimitive){let{maybeFlipLayer:t}=this._getPcbPrimitiveFlippedHelpers();return"layer"in this._parsedProps||this.componentName==="SmtPad"?[t(this._parsedProps.layer??"top")]:"layers"in this._parsedProps?this._parsedProps.layers:this.componentName==="PlatedHole"?this.root?._getBoard()?.allLayers??["top","bottom"]:[]}return[]}getDescendants(){let t=[];for(let n of this.children)t.push(n),t.push(...n.getDescendants());return t}getSelectableDescendants(){let t=[];for(let n of this.children)n.isSubcircuit?t.push(n):(t.push(n),t.push(...n.getSelectableDescendants()));return t}_getPinCount(){return 0}_getSchematicBoxDimensions(){return null}_getSchematicBoxComponentDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;let{_parsedProps:t}=this;return{schWidth:t.schWidth,schHeight:t.schHeight}}renderError(t){if(typeof t=="string")return super.renderError(t);switch(t.type){case"pcb_placement_error":this.root?.db.pcb_placement_error.insert(t);break;case"pcb_via_clearance_error":this.root?.db.pcb_via_clearance_error.insert(t);break;case"pcb_trace_error":this.root?.db.pcb_trace_error.insert(t);break;case"pcb_manual_edit_conflict_warning":this.root?.db.pcb_manual_edit_conflict_warning.insert(t);break;default:this.root?.db.pcb_placement_error.insert(t)}}getString(){let{lowercaseComponentName:t,_parsedProps:n,parent:i}=this;return n?.pinNumber!==void 0&&i?.props?.name&&n?.name?`<${t}#${this._renderId}(pin:${n.pinNumber} .${i?.props.name}>.${n.name}) />`:i?.props?.name&&n?.name?`<${t}#${this._renderId}(.${i?.props.name}>.${n?.name}) />`:n?.from&&n?.to?`<${t}#${this._renderId}(from:${n.from} to:${n?.to}) />`:n?.name?`<${t}#${this._renderId} name=".${n?.name}" />`:n?.portHints?`<${t}#${this._renderId}(${n.portHints.map(r=>`.${r}`).join(", ")}) />`:`<${t}#${this._renderId} />`}get[Symbol.toStringTag](){return this.getString()}[Symbol.for("nodejs.util.inspect.custom")](){return this.getString()}},KPt=class extends xe{constructor(e,t){super(e),this._parsedProps={...e,error:t,type:e.type||"unknown",component_name:e.name,error_type:"source_failed_to_create_component_error",message:t instanceof Error?t.message:String(t),pcbX:e.pcbX,pcbY:e.pcbY,schX:e.schX,schY:e.schY}}get config(){return{componentName:"ErrorPlaceholder",zodProps:p.object({}).passthrough()}}doInitialSourceRender(){if(this.root?.db){let e=this._getGlobalPcbPositionBeforeLayout(),t=this._getGlobalSchematicPositionBeforeLayout();this.root.db.source_failed_to_create_component_error.insert({component_name:this._parsedProps.component_name,error_type:"source_failed_to_create_component_error",message:`Could not create ${this._parsedProps.componentType??"component"}${this._parsedProps.name?` "${this._parsedProps.name}"`:""}. ${this._parsedProps.error?.formattedError?._errors?.join("; ")||this._parsedProps.message}`,pcb_center:e,schematic_center:t})}}};function JPt(e,t){return new KPt(e,t)}function QPt(e,t){let n=e;return n.__tsci={...t},e}var t3t={supportsMutation:!0,createInstance(e,t){let n=lx[e];if(!n)throw Object.keys(lx).length===0?new Error("No components registered in catalogue, did you forget to import lib/register-catalogue in your test file?"):new Error(`Unsupported component type "${e}". No element with this name is registered in the @tscircuit/core catalogue. Check for typos or see https://docs.tscircuit.com/category/built-in-elements for a list of valid components. To add your own component, see docs/CREATING_NEW_COMPONENTS.md`);try{return QPt(new n(t),{})}catch(i){return JPt({...t,componentType:e},i)}},createTextInstance(e){return{__text:e}},appendInitialChild(e,t){e.add(t)},appendChild(e,t){e.add(t)},appendChildToContainer(e,t){e.add(t)},finalizeInitialChildren(){return!1},prepareUpdate(){return null},shouldSetTextContent(){return!1},getRootHostContext(){return{}},getChildHostContext(){return{}},prepareForCommit(){return null},resetAfterCommit(){},commitMount(){},commitUpdate(){},removeChild(){},clearContainer(){},supportsPersistence:!1,getPublicInstance(e){return e},preparePortalMount(e){throw new Error("Function not implemented.")},scheduleTimeout(e,t){throw new Error("Function not implemented.")},cancelTimeout(e){throw new Error("Function not implemented.")},noTimeout:void 0,isPrimaryRenderer:!1,getInstanceFromNode(e){throw new Error("Function not implemented.")},beforeActiveInstanceBlur(){throw new Error("Function not implemented.")},afterActiveInstanceBlur(){throw new Error("Function not implemented.")},prepareScopeUpdate:(e,t)=>{throw new Error("Function not implemented.")},getInstanceFromScope:e=>{throw new Error("Function not implemented.")},detachDeletedInstance:e=>{throw new Error("Function not implemented.")},getCurrentEventPriority:()=>ax.DefaultEventPriority,getCurrentUpdatePriority:()=>ax.DefaultEventPriority,resolveUpdatePriority:()=>ax.DefaultEventPriority,setCurrentUpdatePriority:()=>{},maySuspendCommit:()=>!1,supportsHydration:!1},rx=(0,PV.default)(t3t),MV=e=>{let t={children:[],props:{name:"$root"},add(o){o.parent=this,this.children.push(o)},computePcbGlobalTransform(){return Li()}},n=[],i=rx.createContainer(t,0,null,!1,null,"tsci",o=>{console.log("Error in createContainer"),console.error(o),n.push(o)},null);if(rx.updateContainerSync(e,i,null,()=>{}),rx.flushSyncWork(),n.length>0)throw n[0];let r=rx.getPublicRootInstance(i);return r||t.children[0]},_m=(e,t)=>{if(typeof e=="number")return e;if(e.startsWith("pin"))return Number(e.slice(3));if(!t)throw new Error(`No pin labels provided and pin number or label is not a number: "${e}"`);for(let n in t)if((Array.isArray(t[n])?t[n]:[t[n]]).includes(e))return Number(n.replace("pin",""));throw new Error(`No pin labels provided and pin number or label is not a number: "${e}"`)},e3t=(e,t)=>{if(!e)return;let n={},i={};for(let[r,o]of Object.entries(e)){let s=_m(r,t);i[s]={...i[s],...o}}for(let[r,o]of Object.entries(i)){let s=`pin${r}`;n[s]={bottom_margin:o.bottomMargin,left_margin:o.leftMargin,right_margin:o.rightMargin,top_margin:o.topMargin}}return n},n3t=e=>{if(e){if("leftSide"in e||"rightSide"in e||"topSide"in e||"bottomSide"in e)return{left_side:e.leftSide,right_side:e.rightSide,top_side:e.topSide,bottom_side:e.bottomSide};if("leftPinCount"in e||"rightPinCount"in e||"topPinCount"in e||"bottomPinCount"in e)return{left_size:e.leftPinCount,right_size:e.rightPinCount,top_size:e.topPinCount,bottom_size:e.bottomPinCount};if("leftSize"in e||"rightSize"in e||"topSize"in e||"bottomSize"in e)return{left_size:e.leftSize,right_size:e.rightSize,top_size:e.topSize,bottom_size:e.bottomSize}}};function CV(e){let t=[];for(let n=0;n<e.length-1;n++)t.push([e[n],e[n+1]]);return t}var i3t=p.object({name:p.string().refine(e=>!/[+-]/.test(e),'Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P')}),oM=class extends xe{constructor(){super(...arguments);M(this,"source_net_id")}get config(){return{componentName:"Net",zodProps:i3t}}getPortSelector(){return`net.${this.props.name}`}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=n.name.startsWith("GND"),r=n.name.startsWith("V"),o=t.source_net.insert({name:n.name,member_source_group_ids:[],is_ground:i,is_power:r,is_positive_voltage_source:r});this.source_net_id=o.source_net_id}doInitialSourceParentAttachment(){let t=this.getSubcircuit();if(!t)return;let{db:n}=this.root;n.source_net.update(this.source_net_id,{subcircuit_id:t.subcircuit_id})}getAllConnectedPorts(){let t=this.getSubcircuit().selectAll("port"),n=[];for(let i of t){let r=i._getDirectlyConnectedTraces();for(let o of r)if(o._isExplicitlyConnectedToNet(this)){n.push(i);break}}return n}_getAllDirectlyConnectedTraces(){let t=this.getSubcircuit().selectAll("trace"),n=[];for(let i of t)i._isExplicitlyConnectedToNet(this)&&n.push(i);return n}doInitialPcbRouteNetIslands(){if(this.root?.pcbDisabled||this.getSubcircuit()._parsedProps.routingDisabled||this.getSubcircuit()._getAutorouterConfig().groupMode!=="sequential-trace")return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getAllDirectlyConnectedTraces().filter(s=>(s._portsRoutedOnPcb?.length??0)>0),r=[];for(let s of i){let a=s._portsRoutedOnPcb,c=r.find(l=>a.some(u=>l.ports.includes(u)));if(!c){r.push({ports:[...a],traces:[s]});continue}c.traces.push(s),c.ports.push(...a)}if(r.length===0)return;let o=CV(r);for(let[s,a]of o){let c=s.ports.map(w=>w._getGlobalPcbPositionBeforeLayout()),l=a.ports.map(w=>w._getGlobalPcbPositionBeforeLayout()),u=1/0,h=[-1,-1];for(let w=0;w<c.length;w++){let S=c[w];for(let C=0;C<l.length;C++){let I=l[C],k=Math.sqrt((S.x-I.x)**2+(S.y-I.y)**2);k<u&&(u=k,h=[w,C])}}let d=s.ports[h[0]],_=a.ports[h[1]],y=t.toArray().filter(w=>w.type==="pcb_smtpad"||w.type==="pcb_trace"||w.type==="pcb_plated_hole"||w.type==="pcb_hole"||w.type==="source_port"||w.type==="pcb_port"),{solution:g}=gF(y.concat([{type:"source_trace",source_trace_id:"__net_trace_tmp",connected_source_port_ids:[d.source_port_id,_.source_port_id]}])),x=g[0];if(!x){this.renderError({pcb_trace_error_id:"",pcb_trace_id:"__net_trace_tmp",pcb_component_ids:[d.pcb_component_id,_.pcb_component_id].filter(Boolean),pcb_port_ids:[d.pcb_port_id,_.pcb_port_id].filter(Boolean),type:"pcb_trace_error",error_type:"pcb_trace_error",message:`Failed to route net islands for "${this.getString()}"`,source_trace_id:"__net_trace_tmp"});return}t.pcb_trace.insert(x)}}renderError(t){if(typeof t=="string")return super.renderError(t);this.root?.db.pcb_trace_error.insert(t)}},sM=(e,t)=>{for(let n of t)if(typeof n=="string"&&n.startsWith("net.")){if(/net\.[^\s>]*\./.test(n))throw new Error('Net names cannot contain a period, try using "sel.net..." to autocomplete with conventional net names, e.g. V3_3');if(/net\.[^\s>]*[+-]/.test(n))throw new Error('Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P');if(/net\.[0-9]/.test(n)){let r=n.split("net.")[1];throw new Error(`Net name "${r}" cannot start with a number, try using a prefix like "VBUS1"`)}let i=e.getSubcircuit();if(!i.selectOne(n)){let r=new oM({name:n.split("net.")[1]});i.add(r)}}},dm=class extends xe{constructor(){super(...arguments);M(this,"pcb_smtpad_id",null);M(this,"matchedPort",null);M(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SmtPad",zodProps:VF}}getPcbSize(){let{_parsedProps:t}=this;if(t.shape==="circle")return{width:t.radius*2,height:t.radius*2};if(t.shape==="rect")return{width:t.width,height:t.height};if(t.shape==="rotated_rect"){let i=(t.ccwRotation??0)*Math.PI/180,r=Math.cos(i),o=Math.sin(i),s=Math.abs(t.width*r)+Math.abs(t.height*o),a=Math.abs(t.width*o)+Math.abs(t.height*r);return{width:s,height:a}}if(t.shape==="polygon"){let n=t.points,i=n.map(l=>l.x),r=n.map(l=>l.y),o=Math.min(...i),s=Math.max(...i),a=Math.min(...r),c=Math.max(...r);return{width:s-o,height:c-a}}if(t.shape==="pill")return{width:t.width,height:t.height};throw new Error(`getPcbSize for shape "${t.shape}" not implemented for ${this.componentName}`)}doInitialPortMatching(){let t=this.getPrimitiveContainer()?.selectAll("port");if(this.props.portHints){for(let n of t)if(n.isMatchingAnyOf(this.props.portHints)){this.matchedPort=n,n.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=n.coveredWithSolderMask??!1,r=!i;if(!n.portHints)return;let o=this.getSubcircuit(),s=this._getGlobalPcbPositionBeforeLayout(),l=(To(this._computePcbGlobalTransformBeforeLayout()).rotation.angle*180/Math.PI%360+360)%360,u=.01,h=Math.abs(l)<u||Math.abs(l-180)<u||Math.abs(l-360)<u,d=Math.abs(l-90)<u||Math.abs(l-270)<u,_=Math.abs(l-360)<u?0:l,y=_,{maybeFlipLayer:g,isFlipped:x}=this._getPcbPrimitiveFlippedHelpers();x&&(_=(360-_+360)%360);let w=null,S=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id;if(n.shape==="circle")w=t.pcb_smtpad.insert({pcb_component_id:S,pcb_port_id:this.matchedPort?.pcb_port_id,layer:g(n.layer??"top"),shape:"circle",radius:n.radius,port_hints:n.portHints.map(C=>C.toString()),is_covered_with_solder_mask:i,x:s.x,y:s.y,subcircuit_id:o?.subcircuit_id??void 0}),r&&t.pcb_solder_paste.insert({layer:w.layer,shape:"circle",radius:w.radius*.7,x:w.x,y:w.y,pcb_component_id:w.pcb_component_id,pcb_smtpad_id:w.pcb_smtpad_id,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});else if(n.shape==="rect")!h&&!d?w=t.pcb_smtpad.insert({pcb_component_id:S,pcb_port_id:this.matchedPort?.pcb_port_id,layer:g(n.layer??"top"),shape:"rotated_rect",width:n.width,height:n.height,corner_radius:n.cornerRadius??0,x:s.x,y:s.y,ccw_rotation:_,port_hints:n.portHints.map(I=>I.toString()),is_covered_with_solder_mask:i,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}):w=t.pcb_smtpad.insert({pcb_component_id:S,pcb_port_id:this.matchedPort?.pcb_port_id,layer:g(n.layer??"top"),shape:"rect",width:d?n.height:n.width,height:d?n.width:n.height,corner_radius:n.cornerRadius??0,port_hints:n.portHints.map(I=>I.toString()),is_covered_with_solder_mask:i,x:s.x,y:s.y,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),r&&(w.shape==="rect"?t.pcb_solder_paste.insert({layer:g(n.layer??"top"),shape:"rect",width:w.width*.7,height:w.height*.7,x:w.x,y:w.y,pcb_component_id:w.pcb_component_id,pcb_smtpad_id:w.pcb_smtpad_id,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}):w.shape==="rotated_rect"&&t.pcb_solder_paste.insert({layer:g(n.layer??"top"),shape:"rotated_rect",width:w.width*.7,height:w.height*.7,x:w.x,y:w.y,ccw_rotation:w.ccw_rotation,pcb_component_id:w.pcb_component_id,pcb_smtpad_id:w.pcb_smtpad_id,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}));else if(n.shape==="rotated_rect"){let C=n.ccwRotation??0,I=(y+C+360)%360,k=x?(360-I+360)%360:I;w=t.pcb_smtpad.insert({pcb_component_id:S,pcb_port_id:this.matchedPort?.pcb_port_id,layer:g(n.layer??"top"),shape:"rotated_rect",width:n.width,height:n.height,corner_radius:n.cornerRadius??0,x:s.x,y:s.y,ccw_rotation:k,port_hints:n.portHints.map(P=>P.toString()),is_covered_with_solder_mask:i,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),r&&t.pcb_solder_paste.insert({layer:g(n.layer??"top"),shape:"rotated_rect",width:w.width*.7,height:w.height*.7,x:s.x,y:s.y,ccw_rotation:k,pcb_component_id:S,pcb_smtpad_id:w.pcb_smtpad_id,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else n.shape==="polygon"?w=t.pcb_smtpad.insert({pcb_component_id:S,pcb_port_id:this.matchedPort?.pcb_port_id,layer:g(n.layer??"top"),shape:"polygon",points:n.points.map(C=>({x:C.x+s.x,y:C.y+s.y})),port_hints:n.portHints.map(C=>C.toString()),is_covered_with_solder_mask:i,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}):n.shape==="pill"&&(w=t.pcb_smtpad.insert({pcb_component_id:S,pcb_port_id:this.matchedPort?.pcb_port_id,layer:g(n.layer??"top"),shape:"pill",x:s.x,y:s.y,radius:n.radius,height:n.height,width:n.width,port_hints:n.portHints.map(C=>C.toString()),is_covered_with_solder_mask:i,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}));w&&(this.pcb_smtpad_id=w.pcb_smtpad_id)}doInitialPcbPortAttachment(){if(this.root?.pcbDisabled)return;let{db:t}=this.root;t.pcb_smtpad.update(this.pcb_smtpad_id,{pcb_port_id:this.matchedPort?.pcb_port_id})}_getPcbCircuitJsonBounds(){let{db:t}=this.root,n=t.pcb_smtpad.get(this.pcb_smtpad_id);if(n.shape==="rect")return{center:{x:n.x,y:n.y},bounds:{left:n.x-n.width/2,top:n.y+n.height/2,right:n.x+n.width/2,bottom:n.y-n.height/2},width:n.width,height:n.height};if(n.shape==="rotated_rect"){let i=n.ccw_rotation*Math.PI/180,r=Math.cos(i),o=Math.sin(i),s=n.width/2,a=n.height/2,c=Math.abs(s*r)+Math.abs(a*o),l=Math.abs(s*o)+Math.abs(a*r);return{center:{x:n.x,y:n.y},bounds:{left:n.x-c,right:n.x+c,top:n.y-l,bottom:n.y+l},width:c*2,height:l*2}}if(n.shape==="circle")return{center:{x:n.x,y:n.y},bounds:{left:n.x-n.radius,top:n.y-n.radius,right:n.x+n.radius,bottom:n.y+n.radius},width:n.radius*2,height:n.radius*2};if(n.shape==="polygon"){let i=n.points,r=i.map(u=>u.x),o=i.map(u=>u.y),s=Math.min(...r),a=Math.max(...r),c=Math.min(...o),l=Math.max(...o);return{center:{x:(s+a)/2,y:(c+l)/2},bounds:{left:s,top:l,right:a,bottom:c},width:a-s,height:l-c}}if(n.shape==="pill"){let i=n.width/2,r=n.height/2;return{center:{x:n.x,y:n.y},bounds:{left:n.x-i,top:n.y-r,right:n.x+i,bottom:n.y+r},width:n.width,height:n.height}}throw new Error(`circuitJson bounds calculation not implemented for shape "${n.shape}"`)}_setPositionFromLayout(t){let{db:n}=this.root;n.pcb_smtpad.update(this.pcb_smtpad_id,{x:t.x,y:t.y});let i=n.pcb_solder_paste.list().find(r=>r.pcb_smtpad_id===this.pcb_smtpad_id);i&&n.pcb_solder_paste.update(i.pcb_solder_paste_id,{x:t.x,y:t.y}),this.matchedPort?._setPositionFromLayout(t)}},aM=class extends xe{constructor(){super(...arguments);M(this,"pcb_silkscreen_path_id",null);M(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenPath",zodProps:Nz}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(n.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenPath. Must be "top" or "bottom".`);let o=this._computePcbGlobalTransformBeforeLayout(),s=this.getSubcircuit(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,c=t.pcb_silkscreen_path.insert({pcb_component_id:a,layer:r,route:n.route.map(l=>{let u=Ae(o,{x:l.x,y:l.y});return{...l,x:u.x,y:u.y}}),stroke_width:n.strokeWidth??.1,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_path_id=c.pcb_silkscreen_path_id}_setPositionFromLayout(t){let{db:n}=this.root,{_parsedProps:i}=this,r=n.pcb_silkscreen_path.get(this.pcb_silkscreen_path_id);if(!r)return;let o=0,s=0;for(let u of r.route)o+=u.x,s+=u.y;o/=r.route.length,s/=r.route.length;let a=t.x-o,c=t.y-s,l=r.route.map(u=>({...u,x:u.x+a,y:u.y+c}));n.pcb_silkscreen_path.update(this.pcb_silkscreen_path_id,{route:l})}getPcbSize(){let{_parsedProps:t}=this;if(!t.route||t.route.length===0)return{width:0,height:0};let n=1/0,i=-1/0,r=1/0,o=-1/0;for(let s of t.route)n=Math.min(n,s.x),i=Math.max(i,s.x),r=Math.min(r,s.y),o=Math.max(o,s.y);return{width:i-n,height:o-r}}},r3t=p.object({route:p.array(p_),source_trace_id:p.string().optional()}),cM=class extends xe{constructor(){super(...arguments);M(this,"pcb_trace_id",null);M(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbTrace",zodProps:r3t}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getPrimitiveContainer(),r=this.getSubcircuit(),{maybeFlipLayer:o}=this._getPcbPrimitiveFlippedHelpers(),s=this._computePcbGlobalTransformBeforeLayout(),a=n.route.map(l=>{let{x:u,y:h,...d}=l,_=Ae(s,{x:u,y:h});return l.route_type==="wire"&&l.layer?{..._,...d,layer:o(l.layer)}:{..._,...d}}),c=t.pcb_trace.insert({pcb_component_id:i.pcb_component_id,source_trace_id:n.source_trace_id,route:a,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_trace_id=c.pcb_trace_id}getPcbSize(){let{_parsedProps:t}=this;if(!t.route||t.route.length===0)return{width:0,height:0};let n=1/0,i=-1/0,r=1/0,o=-1/0;for(let s of t.route)n=Math.min(n,s.x),i=Math.max(i,s.x),r=Math.min(r,s.y),o=Math.max(o,s.y),s.route_type==="wire"&&(n=Math.min(n,s.x-s.width/2),i=Math.max(i,s.x+s.width/2),r=Math.min(r,s.y-s.width/2),o=Math.max(o,s.y+s.width/2));return n===1/0||i===-1/0||r===1/0||o===-1/0?{width:0,height:0}:{width:i-n,height:o-r}}},kh=class extends xe{constructor(){super(...arguments);M(this,"pcb_plated_hole_id",null);M(this,"matchedPort",null);M(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PlatedHole",zodProps:OF}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){let{_parsedProps:t}=this;if(t.shape==="circle")return{width:t.outerDiameter,height:t.outerDiameter};if(t.shape==="oval"||t.shape==="pill")return{width:t.outerWidth,height:t.outerHeight};if(t.shape==="circular_hole_with_rect_pad")return{width:t.rectPadWidth,height:t.rectPadHeight};if(t.shape==="pill_hole_with_rect_pad")return{width:t.rectPadWidth,height:t.rectPadHeight};throw new Error(`getPcbSize for shape "${t.shape}" not implemented for ${this.componentName}`)}_getPcbCircuitJsonBounds(){let{db:t}=this.root,n=t.pcb_plated_hole.get(this.pcb_plated_hole_id),i=this.getPcbSize();return{center:{x:n.x,y:n.y},bounds:{left:n.x-i.width/2,top:n.y+i.height/2,right:n.x+i.width/2,bottom:n.y-i.height/2},width:i.width,height:i.height}}_setPositionFromLayout(t){let{db:n}=this.root;n.pcb_plated_hole.update(this.pcb_plated_hole_id,{x:t.x,y:t.y}),this.matchedPort?._setPositionFromLayout(t)}doInitialPortMatching(){let t=this.getPrimitiveContainer()?.selectAll("port");if(this.props.portHints){for(let n of t)if(n.isMatchingAnyOf(this.props.portHints)){this.matchedPort=n,n.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalPcbPositionBeforeLayout(),r=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,o=this.getSubcircuit();if(n.shape==="circle"){let s=t.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,outer_diameter:n.outerDiameter,hole_diameter:n.holeDiameter,shape:"circle",port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=s.pcb_plated_hole_id,t.pcb_solder_paste.insert({layer:"top",shape:"circle",radius:n.outerDiameter/2,x:i.x,y:i.y,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),t.pcb_solder_paste.insert({layer:"bottom",shape:"circle",radius:n.outerDiameter/2,x:i.x,y:i.y,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(n.shape==="pill"&&n.rectPad){let s=t.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,outer_width:n.outerWidth,outer_height:n.outerHeight,hole_width:n.holeWidth,hole_height:n.holeHeight,shape:"rotated_pill_hole_with_rect_pad",type:"pcb_plated_hole",port_hints:this.getNameAndAliases(),pcb_plated_hole_id:this.pcb_plated_hole_id,x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,hole_shape:"rotated_pill",pad_shape:"rect",hole_ccw_rotation:n.pcbRotation??0,rect_ccw_rotation:n.pcbRotation??0,rect_pad_width:n.outerWidth,rect_pad_height:n.outerHeight,hole_offset_x:n.holeOffsetX,hole_offset_y:n.holeOffsetY});this.pcb_plated_hole_id=s.pcb_plated_hole_id}else if(n.shape==="pill"||n.shape==="oval"){let s=t.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,outer_width:n.outerWidth,outer_height:n.outerHeight,hole_width:n.holeWidth,hole_height:n.holeHeight,shape:n.shape,port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,ccw_rotation:n.pcbRotation??0});this.pcb_plated_hole_id=s.pcb_plated_hole_id,t.pcb_solder_paste.insert({layer:"top",shape:n.shape,width:n.outerWidth,height:n.outerHeight,x:i.x,y:i.y,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),t.pcb_solder_paste.insert({layer:"bottom",shape:n.shape,width:n.outerWidth,height:n.outerHeight,x:i.x,y:i.y,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(n.shape==="circular_hole_with_rect_pad"){let s=t.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,hole_diameter:n.holeDiameter,rect_pad_width:n.rectPadWidth,rect_pad_height:n.rectPadHeight,shape:"circular_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,hole_offset_x:n.holeOffsetX,hole_offset_y:n.holeOffsetY,rect_border_radius:n.rectBorderRadius??0});this.pcb_plated_hole_id=s.pcb_plated_hole_id}else if(n.shape==="pill_hole_with_rect_pad"){let s=t.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,hole_width:n.holeWidth,hole_height:n.holeHeight,rect_pad_width:n.rectPadWidth,rect_pad_height:n.rectPadHeight,hole_offset_x:n.holeOffsetX,hole_offset_y:n.holeOffsetY,shape:"pill_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=s.pcb_plated_hole_id}}doInitialPcbPortAttachment(){if(this.root?.pcbDisabled)return;let{db:t}=this.root;t.pcb_plated_hole.update(this.pcb_plated_hole_id,{pcb_port_id:this.matchedPort?.pcb_port_id})}},ux=class extends xe{constructor(){super(...arguments);M(this,"pcb_keepout_id",null);M(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Keepout",zodProps:mz}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let t=this.getSubcircuit(),{db:n}=this.root,{_parsedProps:i}=this,r=this._getGlobalPcbPositionBeforeLayout(),o=To(this._computePcbGlobalTransformBeforeLayout()),s=Math.abs(o.rotation.angle*(180/Math.PI)-90)%180<.01,a=null;i.shape==="circle"?a=n.pcb_keepout.insert({layers:["top"],shape:"circle",radius:i.radius,center:{x:r.x,y:r.y},subcircuit_id:t?.subcircuit_id??void 0,pcb_group_id:t?.getGroup()?.pcb_group_id??void 0}):i.shape==="rect"&&(a=n.pcb_keepout.insert({layers:["top"],shape:"rect",...s?{width:i.height,height:i.width}:{width:i.width,height:i.height},center:{x:r.x,y:r.y},subcircuit_id:t?.subcircuit_id??void 0,pcb_group_id:t?.getGroup()?.pcb_group_id??void 0})),a&&(this.pcb_keepout_id=a.pcb_keepout_id)}},fm=class extends xe{constructor(){super(...arguments);M(this,"pcb_hole_id",null);M(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Hole",zodProps:HF}}getPcbSize(){let{_parsedProps:t}=this,n=t.shape==="pill";return{width:n?t.width:t.diameter,height:n?t.height:t.diameter}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit(),r=this._getGlobalPcbPositionBeforeLayout();if(n.shape==="pill")if(n.pcbRotation&&n.pcbRotation!==0){let o=t.pcb_hole.insert({type:"pcb_hole",hole_shape:"rotated_pill",hole_width:n.width,hole_height:n.height,x:r.x,y:r.y,ccw_rotation:n.pcbRotation,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:i?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=o.pcb_hole_id}else{let o=t.pcb_hole.insert({type:"pcb_hole",hole_shape:"pill",hole_width:n.width,hole_height:n.height,x:r.x,y:r.y,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:i?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=o.pcb_hole_id}else{let o=t.pcb_hole.insert({hole_shape:"circle",hole_diameter:n.diameter,x:r.x,y:r.y,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:i?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=o.pcb_hole_id}}_getPcbCircuitJsonBounds(){let{db:t}=this.root,n=t.pcb_hole.get(this.pcb_hole_id),i=this.getPcbSize();return{center:{x:n.x,y:n.y},bounds:{left:n.x-i.width/2,top:n.y-i.height/2,right:n.x+i.width/2,bottom:n.y+i.height/2},width:i.width,height:i.height}}_setPositionFromLayout(t){let{db:n}=this.root;n.pcb_hole.update(this.pcb_hole_id,{x:t.x,y:t.y})}},fx=class extends xe{constructor(){super(...arguments);M(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenText",zodProps:kz}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getPrimitiveContainer(),r=this._getGlobalPcbPositionBeforeLayout(),{maybeFlipLayer:o,isFlipped:s}=this._getPcbPrimitiveFlippedHelpers(),a=this.getSubcircuit(),c=0;if(n.pcbRotation!==void 0&&n.pcbRotation!==0)c=n.pcbRotation;else{let h=this._computePcbGlobalTransformBeforeLayout();c=To(h).rotation.angle*180/Math.PI}s&&(c=(c+180)%360);let l=new Set(n.layers);n.layer&&l.add(n.layer);let u=l.size>0?Array.from(l):["top"];for(let h of u)t.pcb_silkscreen_text.insert({anchor_alignment:n.anchorAlignment,anchor_position:{x:r.x,y:r.y},font:n.font??"tscircuit2024",font_size:n.fontSize??1,layer:o(h),text:n.text??"",ccw_rotation:c,pcb_component_id:i.pcb_component_id,subcircuit_id:a?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}getPcbSize(){let{_parsedProps:t}=this,n=t.fontSize??1,r=(t.text??"").length*n,o=n;return{width:r*n,height:o*n}}},mm=class extends xe{constructor(){super(...arguments);M(this,"pcb_cutout_id",null);M(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Cutout",zodProps:XF}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit(),r=this.getGroup()?.pcb_group_id??void 0,o=this._getGlobalPcbPositionBeforeLayout(),a=this.getPrimitiveContainer()?._parsedProps.pcbRotation??0,c;if(n.shape==="rect"){let l=typeof a=="string"?parseInt(a.replace("deg",""),10):a,u=Math.abs(l%180)===90,h={shape:"rect",center:o,width:u?n.height:n.width,height:u?n.width:n.height,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:r};c=t.pcb_cutout.insert(h)}else if(n.shape==="circle"){let l={shape:"circle",center:o,radius:n.radius,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:r};c=t.pcb_cutout.insert(l)}else if(n.shape==="polygon"){let l=this._computePcbGlobalTransformBeforeLayout(),h={shape:"polygon",points:n.points.map(d=>Ae(l,d)),subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:r};c=t.pcb_cutout.insert(h)}c&&(this.pcb_cutout_id=c.pcb_cutout_id)}getPcbSize(){let{_parsedProps:t}=this;if(t.shape==="rect")return{width:t.width,height:t.height};if(t.shape==="circle")return{width:t.radius*2,height:t.radius*2};if(t.shape==="polygon"){if(t.points.length===0)return{width:0,height:0};let n=1/0,i=-1/0,r=1/0,o=-1/0;for(let s of t.points)n=Math.min(n,s.x),i=Math.max(i,s.x),r=Math.min(r,s.y),o=Math.max(o,s.y);return{width:i-n,height:o-r}}return{width:0,height:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_cutout_id)return super._getPcbCircuitJsonBounds();let{db:t}=this.root,n=t.pcb_cutout.get(this.pcb_cutout_id);if(!n)return super._getPcbCircuitJsonBounds();if(n.shape==="rect")return{center:n.center,bounds:{left:n.center.x-n.width/2,top:n.center.y+n.height/2,right:n.center.x+n.width/2,bottom:n.center.y-n.height/2},width:n.width,height:n.height};if(n.shape==="circle")return{center:n.center,bounds:{left:n.center.x-n.radius,top:n.center.y+n.radius,right:n.center.x+n.radius,bottom:n.center.y-n.radius},width:n.radius*2,height:n.radius*2};if(n.shape==="polygon"){if(n.points.length===0)return super._getPcbCircuitJsonBounds();let i=1/0,r=-1/0,o=1/0,s=-1/0;for(let a of n.points)i=Math.min(i,a.x),r=Math.max(r,a.x),o=Math.min(o,a.y),s=Math.max(s,a.y);return{center:{x:(i+r)/2,y:(o+s)/2},bounds:{left:i,top:s,right:r,bottom:o},width:r-i,height:s-o}}return super._getPcbCircuitJsonBounds()}_setPositionFromLayout(t){if(!this.pcb_cutout_id)return;let{db:n}=this.root,i=n.pcb_cutout.get(this.pcb_cutout_id);if(i){if(i.shape==="rect"||i.shape==="circle")n.pcb_cutout.update(this.pcb_cutout_id,{...i,center:t});else if(i.shape==="polygon"){let r=this._getPcbCircuitJsonBounds().center,o=t.x-r.x,s=t.y-r.y,a=i.points.map(c=>({x:c.x+o,y:c.y+s}));n.pcb_cutout.update(this.pcb_cutout_id,{...i,points:a})}}}},o3t=({elm:e,pinLabels:t,layer:n,readableRotation:i,anchorAlignment:r})=>{let o=e.text.replace(/[{}]/g,"").toLowerCase(),s=o;if(Array.isArray(t)){let a=parseInt(o.replace(/[^\d]/g,""),10)-1;s=String(t[a]??o)}else typeof t=="object"&&(s=String(t[o]??o));return new fx({anchorAlignment:r||"center",text:s??o,layer:n||"top",fontSize:e.font_size+.2,pcbX:isNaN(e.anchor_position.x)?0:e.anchor_position.x,pcbY:e.anchor_position.y,pcbRotation:i??0})},s3t=(e,t)=>{let n=parseInt(e||"0",10),i;return t!=null?i=t-n:i=n,(i%360+360)%360},lm=({componentName:e,componentRotation:t,footprint:n,pinLabels:i,pcbPinLabels:r},o)=>{let s=[];for(let a of o)if(a.type==="pcb_smtpad"&&a.shape==="rect")s.push(new dm({pcbX:a.x,pcbY:a.y,layer:a.layer,shape:"rect",height:a.height,width:a.width,portHints:a.port_hints,rectBorderRadius:a.rect_border_radius}));else if(a.type==="pcb_smtpad"&&a.shape==="circle")s.push(new dm({pcbX:a.x,pcbY:a.y,layer:a.layer,shape:"circle",radius:a.radius,portHints:a.port_hints}));else if(a.type==="pcb_smtpad"&&a.shape==="pill")s.push(new dm({shape:"pill",height:a.height,width:a.width,radius:a.radius,portHints:a.port_hints,pcbX:a.x,pcbY:a.y,layer:a.layer}));else if(a.type==="pcb_silkscreen_path")s.push(new aM({layer:a.layer,route:a.route,strokeWidth:a.stroke_width}));else if(a.type==="pcb_plated_hole")a.shape==="circle"?s.push(new kh({pcbX:a.x,pcbY:a.y,shape:"circle",holeDiameter:a.hole_diameter,outerDiameter:a.outer_diameter,portHints:a.port_hints})):a.shape==="circular_hole_with_rect_pad"?s.push(new kh({pcbX:a.x,pcbY:a.y,shape:"circular_hole_with_rect_pad",holeDiameter:a.hole_diameter,rectPadHeight:a.rect_pad_height,rectPadWidth:a.rect_pad_width,portHints:a.port_hints,rectBorderRadius:a.rect_border_radius,holeOffsetX:a.hole_offset_x,holeOffsetY:a.hole_offset_y})):a.shape==="pill"||a.shape==="oval"?s.push(new kh({pcbX:a.x,pcbY:a.y,shape:a.shape,holeWidth:a.hole_width,holeHeight:a.hole_height,outerWidth:a.outer_width,outerHeight:a.outer_height,portHints:a.port_hints})):a.shape==="pill_hole_with_rect_pad"&&s.push(new kh({pcbX:a.x,pcbY:a.y,shape:"pill_hole_with_rect_pad",holeShape:"pill",padShape:"rect",holeWidth:a.hole_width,holeHeight:a.hole_height,rectPadWidth:a.rect_pad_width,rectPadHeight:a.rect_pad_height,portHints:a.port_hints,holeOffsetX:a.hole_offset_x,holeOffsetY:a.hole_offset_y}));else if(a.type==="pcb_keepout"&&a.shape==="circle")s.push(new ux({pcbX:a.center.x,pcbY:a.center.y,shape:"circle",radius:a.radius}));else if(a.type==="pcb_keepout"&&a.shape==="rect")s.push(new ux({pcbX:a.center.x,pcbY:a.center.y,shape:"rect",width:a.width,height:a.height}));else if(a.type==="pcb_hole"&&a.hole_shape==="circle")s.push(new fm({pcbX:a.x,pcbY:a.y,diameter:a.hole_diameter}));else if(a.type==="pcb_hole"&&a.hole_shape==="pill")s.push(new fm({pcbX:a.x,pcbY:a.y,shape:"pill",width:a.hole_width,height:a.hole_height}));else if(a.type==="pcb_hole"&&a.hole_shape==="rotated_pill")s.push(new fm({pcbX:a.x,pcbY:a.y,shape:"pill",width:a.hole_width,height:a.hole_height,pcbRotation:a.ccw_rotation}));else if(a.type==="pcb_cutout")a.shape==="rect"?s.push(new mm({pcbX:a.center.x,pcbY:a.center.y,shape:"rect",width:a.width,height:a.height})):a.shape==="circle"?s.push(new mm({pcbX:a.center.x,pcbY:a.center.y,shape:"circle",radius:a.radius})):a.shape==="polygon"&&s.push(new mm({shape:"polygon",points:a.points}));else if(a.type==="pcb_silkscreen_text"){let c=s3t(t,a.ccw_rotation);n.includes("pinrow")&&a.text.includes("PIN")?s.push(o3t({elm:a,pinLabels:r??i,layer:a.layer,readableRotation:c,anchorAlignment:a.anchor_alignment})):s.push(new fx({anchorAlignment:a.anchor_alignment||"center",text:e,fontSize:a.font_size+.2,pcbX:Number.isNaN(a.anchor_position.x)?0:a.anchor_position.x,pcbY:a.anchor_position.y,pcbRotation:c??0}))}else a.type==="pcb_trace"&&s.push(new cM({route:a.route}));return s};function mx(e){let t=1/0,n=1/0,i=-1/0,r=-1/0,o=!1;for(let c of e)if(c.isPcbPrimitive&&!c.componentName.startsWith("Silkscreen")){let{x:l,y:u}=c._getGlobalPcbPositionBeforeLayout(),{width:h,height:d}=c.getPcbSize();t=Math.min(t,l-h/2),n=Math.min(n,u-d/2),i=Math.max(i,l+h/2),r=Math.max(r,u+d/2),o=!0}else if(c.children.length>0){let l=mx(c.children);(l.width>0||l.height>0)&&(t=Math.min(t,l.minX),n=Math.min(n,l.minY),i=Math.max(i,l.maxX),r=Math.max(r,l.maxY),o=!0)}if(!o)return{minX:0,minY:0,maxX:0,maxY:0,width:0,height:0};let s=i-t,a=r-n;return s<0&&(s=0),a<0&&(a=0),{minX:t,minY:n,maxX:i,maxY:r,width:s,height:a}}function QX(e){let t=e%360;return t<0?t+360:t}function a3t(e,t,n,i){return i==="counterclockwise"?n>=t?e>=t&&e<=n:e>=t||e<=n:n<=t?e<=t&&e>=n:e<=t||e>=n}function c3t(e){let t=e.center,n=e.radius,i=e.start_angle_degrees,r=e.end_angle_degrees,o=e.direction??"counterclockwise";if(!t||typeof t.x!="number"||typeof t.y!="number"||typeof n!="number"||typeof i!="number"||typeof r!="number")return null;let s=QX(i),a=QX(r),c=new Set([s,a]),l=[0,90,180,270];for(let y of l)a3t(y,s,a,o)&&c.add(y);let u=1/0,h=1/0,d=-1/0,_=-1/0;for(let y of c){let g=y*Math.PI/180,x=t.x+n*Math.cos(g),w=t.y+n*Math.sin(g);u=Math.min(u,x),d=Math.max(d,x),h=Math.min(h,w),_=Math.max(_,w)}return!Number.isFinite(u)||!Number.isFinite(h)?null:{minX:u,maxX:d,minY:h,maxY:_}}function EV(e){let t=1/0,n=1/0,i=-1/0,r=-1/0;for(let o of e){let s,a,c,l;if(o.type==="schematic_component")s=o.center?.x,a=o.center?.y,c=o.size?.width,l=o.size?.height;else if(o.type==="schematic_box")s=o.x,a=o.y,c=o.width,l=o.height;else if(o.type==="schematic_port")s=o.center?.x,a=o.center?.y,c=.2,l=.2;else if(o.type==="schematic_text")s=o.position?.x,a=o.position?.y,c=(o.text?.length??0)*.1,l=.2;else if(o.type==="schematic_line"){let u=o.x1??0,h=o.y1??0,d=o.x2??0,_=o.y2??0;s=(u+d)/2,a=(h+_)/2,c=Math.abs(d-u),l=Math.abs(_-h)}else if(o.type==="schematic_rect")s=o.center?.x,a=o.center?.y,c=o.width,l=o.height;else if(o.type==="schematic_circle"){s=o.center?.x,a=o.center?.y;let u=o.radius;typeof u=="number"&&(c=u*2,l=u*2)}else if(o.type==="schematic_arc"){let u=c3t(o);u&&(t=Math.min(t,u.minX),i=Math.max(i,u.maxX),n=Math.min(n,u.minY),r=Math.max(r,u.maxY));continue}typeof s=="number"&&typeof a=="number"&&typeof c=="number"&&typeof l=="number"&&(t=Math.min(t,s-c/2),i=Math.max(i,s+c/2),n=Math.min(n,a-l/2),r=Math.max(r,a+l/2))}return{minX:t,maxX:i,minY:n,maxY:r}}function l3t(e,t){let n=t.x-e.x,i=t.y-e.y;return Math.abs(n)>Math.abs(i)?n>=0?"right":"left":i>=0?"up":"down"}var tV=e=>{if(e.length<=1)return!0;let t=e.map(o=>{let s=o._getPcbCircuitJsonBounds();return{left:s.bounds.left,right:s.bounds.right,top:s.bounds.top,bottom:s.bounds.bottom}}),n=Array(t.length).fill(!1).map(()=>Array(t.length).fill(!1));for(let o=0;o<t.length;o++)for(let s=o+1;s<t.length;s++){let a=t[o],c=t[s];n[o][s]=n[s][o]=!(a.right<c.left||a.left>c.right||a.bottom>c.top||a.top<c.bottom)}let i=new Set,r=o=>{i.add(o);for(let s=0;s<t.length;s++)n[o][s]&&!i.has(s)&&r(s)};return r(0),i.size===t.length},eV=e=>{if(e.length===0)throw new Error("Cannot get center of empty PCB primitives array");let t=e.map(r=>r._getPcbCircuitJsonBounds().center).filter(Boolean),n=t.reduce((r,o)=>r+o.x,0),i=t.reduce((r,o)=>r+o.y,0);return{x:n/t.length,y:i/t.length}},u3t=p.object({name:p.string().optional(),pinNumber:p.number().optional(),aliases:p.array(p.string()).optional(),layer:p.string().optional(),layers:p.array(p.string()).optional(),schX:p.number().optional(),schY:p.number().optional(),direction:p.enum(["up","down","left","right"]).optional()}),ji=class extends xe{constructor(t,n={}){if(!t.name&&t.pinNumber!==void 0&&(t.name=`pin${t.pinNumber}`),!t.name)throw new Error("Port must have a name or a pinNumber");super(t);M(this,"source_port_id",null);M(this,"pcb_port_id",null);M(this,"schematic_port_id",null);M(this,"schematicSymbolPortDef",null);M(this,"matchedComponents");M(this,"facingDirection",null);M(this,"originDescription",null);n.originDescription&&(this.originDescription=n.originDescription),this.matchedComponents=[]}get config(){return{componentName:"Port",zodProps:u3t}}_isBoardPinoutFromAttributes(){let t=this.parent;if(t?._parsedProps?.pinAttributes){let n=t._parsedProps.pinAttributes;for(let i of this.getNameAndAliases())if(n[i]?.includeInBoardPinout)return!0}}_getGlobalPcbPositionBeforeLayout(){let t=this.matchedComponents.find(i=>i.isPcbPrimitive),n=this.parent;if(n&&!n.props.footprint)throw new Error(`${n.componentName} "${n.props.name}" does not have a footprint. Add a footprint prop, e.g. <${n.componentName.toLowerCase()} footprint="..." />`);if(!t)throw new Error(`Port ${this} has no matching PCB primitives. This often means the footprint's pads lack matching port hints.`);return t?._getGlobalPcbPositionBeforeLayout()??{x:0,y:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_port_id)return super._getPcbCircuitJsonBounds();let{db:t}=this.root,n=t.pcb_port.get(this.pcb_port_id);return{center:{x:n.x,y:n.y},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getGlobalPcbPositionAfterLayout(){return this._getPcbCircuitJsonBounds().center}_getPortsInternallyConnectedToThisPort(){let t=this.parent;if(!t||!t._getInternallyConnectedPins)return[];let n=t._getInternallyConnectedPins();for(let i of n)if(i.some(r=>r===this))return i;return[]}_hasSchematicPort(){let{schX:t,schY:n}=this._parsedProps;if(t!==void 0&&n!==void 0)return!0;let i=this.getParentNormalComponent();if(i?.getSchematicSymbol())return!!(this.schematicSymbolPortDef||this._getPortsInternallyConnectedToThisPort().some(a=>a.schematicSymbolPortDef));let o=i?._getSchematicBoxDimensions();return!!(o&&this.props.pinNumber!==void 0&&o.getPortPositionByPinNumber(this.props.pinNumber))}_getGlobalSchematicPositionBeforeLayout(){let{schX:t,schY:n}=this._parsedProps;if(t!==void 0&&n!==void 0)return{x:t,y:n};let i=this.getParentNormalComponent(),r=i?.getSchematicSymbol();if(r){let s=this.schematicSymbolPortDef;if(!s&&(s=this._getPortsInternallyConnectedToThisPort().find(c=>c.schematicSymbolPortDef)?.schematicSymbolPortDef??null,!s))throw new Error(`Couldn't find schematicSymbolPortDef for port ${this.getString()}, searched internally connected ports and none had a schematicSymbolPortDef. Why are we trying to get the schematic position of this port?`);let a=Jn(i.computeSchematicGlobalTransform(),vn(-r.center.x,-r.center.y));return Ae(a,s)}let o=i?._getSchematicBoxDimensions();if(o&&this.props.pinNumber!==void 0){let s=o.getPortPositionByPinNumber(this.props.pinNumber);if(!s)throw new Error(`Couldn't find position for schematic_port for port ${this.getString()} inside of the schematic box`);return Ae(i.computeSchematicGlobalTransform(),s)}throw new Error(`Couldn't find position for schematic_port for port ${this.getString()}`)}_getGlobalSchematicPositionAfterLayout(){let{db:t}=this.root;if(!this.schematic_port_id)throw new Error(`Can't get schematic port position after layout for "${this.getString()}", no schematic_port_id`);let n=t.schematic_port.get(this.schematic_port_id);if(!n)throw new Error(`Schematic port not found when trying to get post-layout position: ${this.schematic_port_id}`);return n.center}registerMatch(t){this.matchedComponents.push(t)}getNameAndAliases(){let{_parsedProps:t}=this;return Array.from(new Set([...t.name?[t.name]:[],...t.aliases??[],...typeof t.pinNumber=="number"?[`pin${t.pinNumber}`,t.pinNumber.toString()]:[],...this.externallyAddedAliases??[]]))}_getMatchingPinAttributes(){let t=this.parent?._parsedProps?.pinAttributes;if(!t)return[];let n=[];for(let i of this.getNameAndAliases()){let r=t[i];r&&n.push(r)}return n}_shouldIncludeInBoardPinout(){return this._getMatchingPinAttributes().some(t=>t.includeInBoardPinout===!0)}isMatchingPort(t){return this.isMatchingAnyOf(t.getNameAndAliases())}getPortSelector(){return`.${(this.getParentNormalComponent()??this.parent)?.props.name} > port.${this.props.name}`}getAvailablePcbLayers(){let{layer:t,layers:n}=this._parsedProps;return n||(t?[t]:Array.from(new Set(this.matchedComponents.flatMap(i=>i.getAvailablePcbLayers()))))}_getDirectlyConnectedTraces(){return this.getSubcircuit().selectAll("trace").filter(i=>!i._couldNotFindPort).filter(i=>i._isExplicitlyConnectedToPort(this))}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=this.getNameAndAliases(),r=this.getParentNormalComponent(),s=(this.parent?.source_component_id?this.parent:r)?.source_component_id??null,a=t.source_port.insert({name:n.name,pin_number:n.pinNumber,port_hints:i,source_component_id:s,subcircuit_id:this.getSubcircuit()?.subcircuit_id});this.source_port_id=a.source_port_id}doInitialSourceParentAttachment(){let{db:t}=this.root,n=this.getParentNormalComponent(),i=this.parent?.source_component_id?this.parent:n;if(!i?.source_component_id)throw new Error(`${this.getString()} has no parent source component (parent: ${this.parent?.getString()})`);t.source_port.update(this.source_port_id,{source_component_id:i.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id}),this.source_component_id=i.source_component_id}doInitialPcbPortRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{matchedComponents:n}=this,i=this.getParentNormalComponent(),r=this.parent?.pcb_component_id?this.parent:i;if(!r?.pcb_component_id)throw new Error(`${this.getString()} has no parent pcb component, cannot render pcb_port (parent: ${this.parent?.getString()}, parentNormalComponent: ${i?.getString()})`);let o=n.filter(a=>a.isPcbPrimitive);if(o.length===0)return;let s=null;if(o.length===1&&(s=o[0]._getPcbCircuitJsonBounds().center),o.length>1){if(!tV(o))throw new Error(`${this.getString()} has multiple non-overlapping pcb matches, unclear how to place pcb_port: ${o.map(a=>a.getString()).join(", ")}. (Note: tscircuit core does not currently allow you to specify internally connected pcb primitives with the same port hints, try giving them different port hints and specifying they are connected externally- or file an issue)`);s=eV(o)}if(s){let a=this.getSubcircuit(),c=this._shouldIncludeInBoardPinout(),l=t.pcb_port.insert({pcb_component_id:r.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:a?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...c?{is_board_pinout:!0}:{},...s,source_port_id:this.source_port_id,is_board_pinout:this._isBoardPinoutFromAttributes()});this.pcb_port_id=l.pcb_port_id}else{let a=o[0];throw new Error(`${a.getString()} does not have a center or _getGlobalPcbPositionBeforeLayout method (needed for pcb_port placement)`)}}updatePcbPortRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root;if(this.pcb_port_id)return;let n=this.matchedComponents.filter(l=>l.isPcbPrimitive);if(n.length===0)return;let i=null;if(n.length===1&&(i=n[0]._getPcbCircuitJsonBounds().center),n.length>1)try{tV(n)&&(i=eV(n))}catch{}if(!i)return;let r=this.getParentNormalComponent(),o=this.parent?.pcb_component_id?this.parent:r,s=this.getSubcircuit(),a=this._shouldIncludeInBoardPinout(),c=t.pcb_port.insert({pcb_component_id:o?.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...a?{is_board_pinout:!0}:{},...i,source_port_id:this.source_port_id,is_board_pinout:this._isBoardPinoutFromAttributes()});this.pcb_port_id=c.pcb_port_id}doInitialSchematicPortRender(){let{db:t}=this.root,{_parsedProps:n}=this,{schX:i,schY:r}=n,o=i!==void 0&&r!==void 0?this.getParentNormalComponent():this.getPrimitiveContainer();if(!o||!this._hasSchematicPort())return;let s=o._getGlobalSchematicPositionBeforeLayout(),a=this._getGlobalSchematicPositionBeforeLayout(),c=null,l=o._getSchematicBoxDimensions();l&&n.pinNumber!==void 0&&(c=l.getPortPositionByPinNumber(n.pinNumber)),this.getSubcircuit().props._schDebugObjectsEnabled&&t.schematic_debug_object.insert({shape:"rect",center:a,size:{width:.1,height:.1},label:"obstacle"}),c?.side?this.facingDirection={left:"left",right:"right",top:"up",bottom:"down"}[c.side]:this.facingDirection=l3t(s,a);let u=t.source_port.get(this.source_port_id),h=[];for(let w of u?.port_hints??[])w.match(/^(pin)?\d+$/)||w.match(/^(left|right)/)&&!u?.name.match(/^(left|right)/)||h.push(w);let d,_=this.getParentNormalComponent();_?.props?.showPinAliases&&h.length>0?d=h.join("/"):h.length>0&&(d=h[0]);let g={type:"schematic_port",schematic_component_id:_?.schematic_component_id,center:a,source_port_id:this.source_port_id,facing_direction:this.facingDirection,distance_from_component_edge:.4,side_of_component:c?.side,pin_number:n.pinNumber,true_ccw_index:c?.trueIndex,display_pin_label:d,is_connected:!1};for(let w of this._getMatchingPinAttributes())w.requiresPower&&(g.has_input_arrow=!0),w.providesPower&&(g.has_output_arrow=!0);let x=t.schematic_port.insert(g);this.schematic_port_id=x.schematic_port_id}_getSubcircuitConnectivityKey(){return this.root?.db.source_port.get(this.source_port_id)?.subcircuit_connectivity_map_key}_setPositionFromLayout(t){let{db:n}=this.root;this.pcb_port_id&&n.pcb_port.update(this.pcb_port_id,{x:t.x,y:t.y})}_hasMatchedPcbPrimitive(){return this.matchedComponents.some(t=>t.isPcbPrimitive)}_getNetLabelText(){return`${this.parent?.props.name}_${this.props.name}`}},kV=e=>{let t=e.find(n=>/^(pin)?\d+$/.test(n));return t?Number.parseInt(t.replace(/^pin/,"")):null};function cm(e,t){let n=kV(e);if(!n)return null;let r=[...e.filter(o=>o.toString()!==n.toString()&&o!==`pin${n}`),...t?.additionalAliases?.[`pin${n}`]??[]];return new ji({pinNumber:n,aliases:r})}var p3t=e=>{for(let t of["leftSide","rightSide","topSide","bottomSide"])if(t in e&&typeof e[t]=="number")throw new Error(`A number was specified for "${t}", you probably meant to use "size" not "side"`);return"leftSide"in e||"rightSide"in e||"topSide"in e||"bottomSide"in e},h3t=e=>{if(p3t(e))return{leftSize:e.leftSide?.pins.length??0,rightSize:e.rightSide?.pins.length??0,topSize:e.topSide?.pins.length??0,bottomSize:e.bottomSide?.pins.length??0};let{leftSize:t=0,rightSize:n=0,topSize:i=0,bottomSize:r=0}=e;return{leftSize:t,rightSize:n,topSize:i,bottomSize:r}};function NV(e){let t=e;return t.leftSide!==void 0||t.rightSide!==void 0||t.topSide!==void 0||t.bottomSide!==void 0}var d3t=e=>{let t=e.portDistanceFromEdge??.4,n=e.schPortArrangement?h3t(e.schPortArrangement):null,i={left:0,right:0,top:0,bottom:0},r=e.pinCount??null;if(r===null)if(n)r=n.leftSize+n.rightSize+n.topSize;else throw new Error("Could not determine pin count for the schematic box");if(r&&!n){let y=Math.floor(r/2);n={leftSize:r-y,rightSize:y,topSize:0,bottomSize:0}}n||(n={leftSize:0,rightSize:0,topSize:0,bottomSize:0});let o=({side:y,sideIndex:g,truePinIndex:x})=>{if(!e.schPortArrangement||!NV(e.schPortArrangement))return x+1;let w={left:"top-to-bottom",bottom:"left-to-right",right:"bottom-to-top",top:"right-to-left"}[y],S=e.schPortArrangement?.[`${y}Side`]?.direction??w,C=e.schPortArrangement?.[`${y}Side`]?.pins,I=g;return S!==w&&(I=C.length-g-1),_m(C[I],e.pinLabels)},s=[],a=0,c=0;for(let y=0;y<n.leftSize;y++){let g=o({side:"left",sideIndex:y,truePinIndex:c}),x=e.numericSchPinStyle?.[`pin${g}`]??e.numericSchPinStyle?.[g];x?.topMargin&&(a+=x.topMargin),s.push({trueIndex:c,pinNumber:g,side:"left",distanceFromOrthogonalEdge:a}),x?.bottomMargin&&(a+=x.bottomMargin),y===n.leftSize-1?i.left=a:a+=e.schPinSpacing,c++}a=0;for(let y=0;y<n.bottomSize;y++){let g=o({side:"bottom",sideIndex:y,truePinIndex:c}),x=e.numericSchPinStyle?.[`pin${g}`]??e.numericSchPinStyle?.[g];x?.leftMargin&&(a+=x.leftMargin),s.push({trueIndex:c,pinNumber:g,side:"bottom",distanceFromOrthogonalEdge:a}),x?.rightMargin&&(a+=x.rightMargin),y===n.bottomSize-1?i.bottom=a:a+=e.schPinSpacing,c++}a=0;for(let y=0;y<n.rightSize;y++){let g=o({side:"right",sideIndex:y,truePinIndex:c}),x=e.numericSchPinStyle?.[`pin${g}`]??e.numericSchPinStyle?.[g];x?.bottomMargin&&(a+=x.bottomMargin),s.push({trueIndex:c,pinNumber:g,side:"right",distanceFromOrthogonalEdge:a}),x?.topMargin&&(a+=x.topMargin),y===n.rightSize-1?i.right=a:a+=e.schPinSpacing,c++}a=0;for(let y=0;y<n.topSize;y++){let g=o({side:"top",sideIndex:y,truePinIndex:c}),x=e.numericSchPinStyle?.[`pin${g}`]??e.numericSchPinStyle?.[g];x?.rightMargin&&(a+=x.rightMargin),s.push({trueIndex:c,pinNumber:g,side:"top",distanceFromOrthogonalEdge:a}),x?.leftMargin&&(a+=x.leftMargin),y===n.topSize-1?i.top=a:a+=e.schPinSpacing,c++}let l=e.schWidth;if(l===void 0){l=Math.max(i.top+e.schPinSpacing*2,i.bottom+e.schPinSpacing*2);let y=e.pinLabels?Math.max(...Object.values(e.pinLabels).map(x=>x.length*.1)):0,g=y>0?1.1:0;l=Math.max(l,y+g)}let u=e.schHeight;u||(u=Math.max(i.left+e.schPinSpacing*2,i.right+e.schPinSpacing*2));let h={left:{x:-l/2-t,y:i.left/2},bottom:{x:-i.bottom/2,y:-u/2-t},right:{x:l/2+t,y:-i.right/2},top:{x:i.top/2,y:u/2+t}},d={left:{x:0,y:-1},right:{x:0,y:1},top:{x:-1,y:0},bottom:{x:1,y:0}},_=s.map(y=>{let{distanceFromOrthogonalEdge:g,side:x}=y,w=h[x],S=d[x];return{x:w.x+g*S.x,y:w.y+g*S.y,...y}});return{getPortPositionByPinNumber(y){let g=_.find(x=>x.pinNumber.toString()===y.toString());return g||null},getSize(){return{width:l,height:u}},getSizeIncludingPins(){return{width:l+(n.leftSize||n.rightSize?.4:0),height:u+(n.topSize||n.bottomSize?.4:0)}},pinCount:r}},f3t=(0,AV.default)("tscircuit:core:footprint"),RV=class extends xe{get config(){return{componentName:"Footprint",zodProps:UF}}doInitialPcbFootprintLayout(){if(this.root?.pcbDisabled)return;let e=this.children.filter(h=>h.componentName==="Constraint");if(e.length===0)return;let{isFlipped:t}=this._getPcbPrimitiveFlippedHelpers(),n=h=>t&&"left"in h&&"right"in h?{...h,left:h.right,right:h.left}:h,i=e.flatMap(h=>h._getAllReferencedComponents().componentsWithSelectors).map(({component:h,selector:d,componentSelector:_,edge:y})=>({component:h,selector:d,componentSelector:_,edge:y,bounds:h._getPcbCircuitJsonBounds()}));if(i.some(h=>h.edge))throw new Error("edge constraints not implemented yet for footprint layout, contributions welcome!");function r(h){return i.find(({selector:d})=>d===h)}let o=new jp,s={};function a(h){return h in s||(s[h]=new Xs(h),o.addEditVariable(s[h],wn.weak)),s[h]}for(let{selector:h,bounds:d}of i){let _=a(`${h}_x`),y=a(`${h}_y`);o.suggestValue(_,d.center.x),o.suggestValue(y,d.center.y)}for(let h of e){let d=h._parsedProps;if("xDist"in d){let{xDist:_,left:y,right:g,edgeToEdge:x,centerToCenter:w}=n(d),S=a(`${y}_x`),C=a(`${g}_x`),I=r(y)?.bounds,k=r(g)?.bounds;if(w){let P=new Cn(C,[-1,S]);o.addConstraint(new ai(P,Yn.Eq,d.xDist,wn.required))}else if(x){let P=new Cn(C,-k.width/2,[-1,S],-I.width/2);o.addConstraint(new ai(P,Yn.Eq,d.xDist,wn.required))}}else if("yDist"in d){let{yDist:_,top:y,bottom:g,edgeToEdge:x,centerToCenter:w}=d,S=a(`${y}_y`),C=a(`${g}_y`),I=r(y)?.bounds,k=r(g)?.bounds;if(w){let P=new Cn(S,[-1,C]);o.addConstraint(new ai(P,Yn.Eq,d.yDist,wn.required))}else if(x){let P=new Cn(S,I.height/2,[-1,C],-k.height/2);o.addConstraint(new ai(P,Yn.Eq,d.yDist,wn.required))}}else if("sameY"in d){let{for:_}=d;if(_.length<2)continue;let y=_.map(x=>a(`${x}_y`)),g=new Cn(...y.slice(1));o.addConstraint(new ai(g,Yn.Eq,y[0],wn.required))}else if("sameX"in d){let{for:_}=d;if(_.length<2)continue;let y=_.map(x=>a(`${x}_x`)),g=new Cn(...y.slice(1));o.addConstraint(new ai(g,Yn.Eq,y[0],wn.required))}}o.updateVariables(),f3t.enabled&&(console.log("Solution to layout constraints:"),console.table(Object.entries(s).map(([h,d])=>({var:h,val:d.value()}))));let c={left:1/0,right:-1/0,top:-1/0,bottom:1/0};for(let{selector:h,bounds:{width:d,height:_}}of i){let y=a(`${h}_x`),g=a(`${h}_y`),x=y.value()-d/2,w=y.value()+d/2,S=g.value()+_/2,C=g.value()-_/2;c.left=Math.min(c.left,x),c.right=Math.max(c.right,w),c.top=Math.max(c.top,S),c.bottom=Math.min(c.bottom,C)}let l={x:-(c.right+c.left)/2,y:-(c.top+c.bottom)/2},u=this.getPrimitiveContainer()._getGlobalPcbPositionBeforeLayout();l.x+=u.x,l.y+=u.y;for(let{component:h,selector:d}of i){let _=a(`${d}_x`),y=a(`${d}_y`);h._setPositionFromLayout({x:_.value()+l.x,y:y.value()+l.y})}}},OV=e=>{if(!e)return null;let n=e.split("?")[0].split("#")[0],i=n.split("/").pop()??n;return i.includes(".")?i.split(".").pop()?.toLowerCase()??null:null},m3t=(e,t)=>{let n=e.replace(/\/+$/,""),i=t.replace(/^\/+/,"");return`${n}/${i}`},LV=(e,t)=>{if(!t||!e.startsWith("/"))return e;try{let n=new URL(t);return n.pathname!=="/"&&e.startsWith(n.pathname)?new URL(e,n.origin).toString():m3t(t,e)}catch{return e}},XI=p.union([p.number(),p.string()]),nV=p.object({x:XI,y:XI,z:XI}),FV=class extends xe{get config(){return{componentName:"CadModel",zodProps:gz}}doInitialCadModelRender(){let e=this._findParentWithPcbComponent();if(!e||!e.pcb_component_id)return;let{db:t}=this.root,{boardThickness:n=0}=this.root?._getBoard()??{},i=e._getPcbCircuitJsonBounds(),r=t.pcb_component.get(e.pcb_component_id),o=this._parsedProps;if(!o||typeof o.modelUrl!="string"&&typeof o.stepUrl!="string")return;let s=e._computePcbGlobalTransformBeforeLayout(),c=To(s).rotation.angle*180/Math.PI,l=nV.parse({x:0,y:0,z:0});if(typeof o.rotationOffset=="number")l.z=Number(o.rotationOffset);else if(typeof o.rotationOffset=="object"){let x=nV.parse(o.rotationOffset);l.x=Number(x.x),l.y=Number(x.y),l.z=Number(x.z)}let u=Ng.parse({x:o.pcbX??0,y:o.pcbY??0,z:o.pcbZ??0,...typeof o.positionOffset=="object"?o.positionOffset:{}}),h=o.zOffsetFromSurface!==void 0?Y.parse(o.zOffsetFromSurface):0,d=e.props.layer==="bottom"?"bottom":"top",_=o.modelUrl?OV(o.modelUrl):void 0,y={};if(_==="stl"?y.model_stl_url=this._addCachebustToModelUrl(o.modelUrl):_==="obj"?y.model_obj_url=this._addCachebustToModelUrl(o.modelUrl):_==="gltf"?y.model_gltf_url=this._addCachebustToModelUrl(o.modelUrl):_==="glb"?y.model_glb_url=this._addCachebustToModelUrl(o.modelUrl):_==="step"||_==="stp"?y.model_step_url=this._addCachebustToModelUrl(o.modelUrl):_==="wrl"||_==="vrml"?y.model_wrl_url=this._addCachebustToModelUrl(o.modelUrl):y.model_stl_url=this._addCachebustToModelUrl(o.modelUrl),o.stepUrl){let x=this._addCachebustToModelUrl(o.stepUrl);x&&(y.model_step_url=x)}let g=t.cad_component.insert({position:{x:i.center.x+Number(u.x),y:i.center.y+Number(u.y),z:(d==="bottom"?-n/2:n/2)+(d==="bottom"?-h:h)+Number(u.z)},rotation:{x:Number(l.x),y:(d==="top"?0:180)+Number(l.y),z:d==="bottom"?-(c+Number(l.z))+180:c+Number(l.z)},pcb_component_id:e.pcb_component_id,source_component_id:e.source_component_id,model_unit_to_mm_scale_factor:typeof o.modelUnitToMmScale=="number"?o.modelUnitToMmScale:void 0,...y});this.cad_component_id=g.cad_component_id}_findParentWithPcbComponent(){let e=this.parent;for(;e&&!e.pcb_component_id;)e=e.parent;return e}_addCachebustToModelUrl(e){if(!e)return e;let t=this.root?.platform?.projectBaseUrl,n=LV(e,t);if(!n.includes("modelcdn.tscircuit.com"))return n;let i=this.root?.getClientOrigin()??"";return`${n}${n.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(i)}`}},zV=class extends xe{constructor(){super(...arguments);M(this,"isPrimitiveContainer",!0)}get config(){return{componentName:"CadAssembly",zodProps:yz}}},_3t=(e,t)=>{if(!e)return;let n={};for(let[i,r]of Object.entries(e)){let o=_m(i,t),s={leftMargin:r.marginLeft??r.leftMargin,rightMargin:r.marginRight??r.rightMargin,topMargin:r.marginTop??r.topMargin,bottomMargin:r.marginBottom??r.bottomMargin};n[`pin${o}`]={...n[`pin${o}`],...s}}return n},iV=class{constructor({input:e}){M(this,"input");this.input=e}solveAndMapToTraces(){let e=[];for(let t of this.input.connections){if(t.pointsToConnect.length!==2)continue;let[n,i]=t.pointsToConnect,r={type:"pcb_trace",pcb_trace_id:"",connection_name:t.name,route:[{route_type:"wire",x:n.x,y:n.y,layer:"top",width:.1},{route_type:"wire",x:i.x,y:i.y,layer:"top",width:.1}]};e.push(r)}return e}},y3t=e=>{let t=Math.min(...e.map(o=>o.center.x)),n=Math.max(...e.map(o=>o.center.x)),i=Math.min(...e.map(o=>o.center.y)),r=Math.max(...e.map(o=>o.center.y));return{minX:t,maxX:n,minY:i,maxY:r}},rV=["top","bottom","inner1","inner2"],cx=(e,t=[])=>{let n=[];if(t.length===0){let a=e[0].layers;for(let c of a)n.push(...cx(e.slice(1),[c]));return n}if(e.length===0)return[];let i=e[0],r=i.via||i.optional_via,o=t[t.length-1];if(e.length===1){let a=i;return a.layers&&r?a.layers.map(c=>({layer_path:[...t,c]})):a.layers?.includes(o)?[{layer_path:[...t,o]}]:[]}if(!r)return i.layers&&!i.layers.includes(o)?[]:cx(e.slice(1),t.concat([o]));let s=(i.optional_via?rV:rV.filter(a=>a!==o)).filter(a=>!i.layers||i.layers?.includes(a));for(let a of s)n.push(...cx(e.slice(1),t.concat(a)));return n};function oV(e){let t={x:e.to.x-e.from.x,y:e.to.y-e.from.y},n=Math.abs(t.x),i=Math.abs(t.y);return n>i?t.x>0?"right":"left":t.y>0?"down":"up"}function Th(e,t){return Math.hypot(e.x-t.x,e.y-t.y)}var g3t=e=>{if(e.length===1)return e[0];if(e.some(c=>c.length===0))throw new Error("Cannot merge routes with zero length");let t=[],n=e[0][0],i=e[0][e[0].length-1],r=e[1][0],o=e[1][e[1].length-1],s=Math.min(Th(n,r),Th(n,o)),a=Math.min(Th(i,r),Th(i,o));s<a?t.push(...e[0].reverse()):t.push(...e[0]);for(let c=1;c<e.length;c++){let l=t[t.length-1],u=e[c],h=u[0],d=u[u.length-1],_=Th(l,h),y=Th(l,d);_<y?t.push(...u):t.push(...u.reverse())}for(let c=1;c<t.length-1;c++){let l=t[c-1],u=t[c];l.route_type==="wire"&&u.route_type==="wire"&&l.layer!==u.layer&&t.splice(c,0,{x:l.x,y:l.y,from_layer:l.layer,to_layer:u.layer,route_type:"via"})}return t},b3t=(e,t)=>{let n="_getGlobalPcbPositionBeforeLayout"in e?e._getGlobalPcbPositionBeforeLayout():e,i="_getGlobalPcbPositionBeforeLayout"in t?t._getGlobalPcbPositionBeforeLayout():t;return Math.sqrt((n.x-i.x)**2+(n.y-i.y)**2)};function x3t(e,t){if(t.length===0)throw new Error("No candidates given to getClosest method");let n=t[0],i=1/0;for(let r of t){let o=b3t(e,r);o<i&&(n=r,i=o)}return n}var v3t=(e,t)=>{let n=0;n+=e.length??0,n+=t.filter(i=>i.is_crossing).length;for(let i=1;i<t.length;i++){let r=t[i-1],o=t[i],s=Math.abs(r.from.x-r.to.x)<.01,a=Math.abs(o.from.x-o.to.x)<.01;s!==a&&n++}return n},ym=e=>({up:"bottom",down:"top",left:"right",right:"left"})[e]??null,WI=({firstEdge:e,firstEdgePort:t,firstDominantDirection:n,lastEdge:i,lastEdgePort:r,lastDominantDirection:o})=>{if(e&&t)return WI({lastEdge:{from:e.to,to:e.from},lastEdgePort:t,lastDominantDirection:n}).reverse().map(a=>({from:a.to,to:a.from}));let s=[];if(i&&r){let a={x:i.to.x,y:i.to.y};o==="left"||o==="right"?(a.x=r.position.x,s.push({from:i.to,to:{...a}}),s.push({from:a,to:{...r.position}})):(a.y=r.position.y,s.push({from:i.to,to:{...a}}),s.push({from:a,to:{...r.position}}))}return s=s.filter(a=>zi(a.from,a.to)>.01),s};function w3t(e){try{return[e(),null]}catch(t){return[null,t]}}var S3t=(e,{db:t})=>{let n=e.map(i=>{let r=t.source_port.get(i.source_port_id);if(!r?.source_component_id)return null;let o=t.source_component.get(r.source_component_id);return o?.ftype==="simple_capacitor"?o.max_decoupling_trace_length:null}).filter(i=>i!==null);if(n.length!==0)return Math.min(...n)};function P3t({ports:e,nets:t}){if(e.length>=2)return`${e[0]?.selector} to ${e[1]?.selector}`;if(e.length===1&&t.length===1)return`${e[0]?.selector} to net.${t[0]._parsedProps.name}`}var T3t=(e,{db:t})=>{let n=t.pcb_board.list()[0];if(n.outline){let c=n.outline,l=(u,h)=>{let d=!1;for(let _=0,y=h.length-1;_<h.length;y=_++){let g=h[_].x,x=h[_].y,w=h[y].x,S=h[y].y;x>u.y!=S>u.y&&u.x<(w-g)*(u.y-x)/(S-x)+g&&(d=!d)}return d};return e.some(u=>!l(u,c))}let i=n.width,r=n.height,o=n.center.x,s=n.center.y;return e.some(c=>c.x<o-i/2||c.y<s-r/2||c.x>o+i/2||c.y>s+r/2)},sV=(e,t)=>Math.abs(e-t)<1e-4,I3t=(e,t,{viaDiameter:n=.5}={})=>{let i=[];for(let r=0;r<e.length-1;r++){let[o,s]=[e[r],e[r+1]],a=r-1>=0?e[r-1]:null,c=sV(o.y,s.y),l=sV(o.x,s.x);if(!c&&!l)throw new Error(`getObstaclesFromTrace currently only supports horizontal and vertical traces (not diagonals) Conflicting trace: ${t}, start: (${o.x}, ${o.y}), end: (${s.x}, ${s.y})`);let u={type:"rect",layers:[o.layer],center:{x:(o.x+s.x)/2,y:(o.y+s.y)/2},width:c?Math.abs(o.x-s.x):.1,height:l?Math.abs(o.y-s.y):.1,connectedTo:[t]};if(i.push(u),a&&a.layer===o.layer&&o.layer!==s.layer){let h={type:"rect",layers:[o.layer,s.layer],center:{x:o.x,y:o.y},connectedTo:[t],width:n,height:n};i.push(h)}}return i};function DV(e,t=4){let{center:n,width:i,height:r,rotation:o}=e,s=[],a=o*Math.PI/180,c=Math.cos(a),l=Math.sin(a),u=(o%360+360)%360;if(r<=i?u>=45&&u<135||u>=225&&u<315:u>=135&&u<225||u>=315||u<45){let d=i/t;for(let _=0;_<t;_++){let y=(_-t/2+.5)*d,g=-y*c,x=-y*l,w=d*1.1,S=Math.abs(r*c)+Math.abs(d*l);s.push({center:{x:n.x+g,y:n.y+x},width:w,height:S})}}else{let d=r/t;for(let _=0;_<t;_++){let y=(_-t/2+.5)*d,g=-y*l,x=y*c,w=Math.abs(i*c)+Math.abs(d*l),S=d*1.1;s.push({center:{x:n.x+g,y:n.y+x},width:w,height:S})}}return s}function M3t(e,t={}){if(e.length<3)return[];let{rectHeight:n=.1}=t,i=[],r=e.map(a=>a.y),o=Math.min(...r),s=Math.max(...r);for(let a=o;a<s;a+=n){let c=a+n/2,l=[];for(let u=0;u<e.length;u++){let h=e[u],d=e[(u+1)%e.length];if(h.y<=c&&d.y>c||d.y<=c&&h.y>c){let _=(c-h.y)*(d.x-h.x)/(d.y-h.y)+h.x;l.push(_)}}l.sort((u,h)=>u-h);for(let u=0;u<l.length;u+=2)if(u+1<l.length){let h=l[u],_=l[u+1]-h;_>1e-6&&i.push({center:{x:h+_/2,y:c},width:_,height:n})}}return i}function C3t(e,t={}){let{center:n,radius:i}=e,{rectHeight:r=.1}=t,o=[],s=Math.ceil(i*2/r);for(let a=0;a<s;a++){let c=n.y-i+(a+.5)*r,l=c-n.y,u=Math.sqrt(i*i-l*l);u>0&&o.push({center:{x:n.x,y:c},width:u*2,height:r})}return o}var bc=["top","inner1","inner2","bottom"],lM=(e,t)=>{let n=r=>t?r.concat(r.map(o=>t?.getNetConnectedToId(o)).filter(Boolean)):r,i=[];for(let r of e)if(r.type==="pcb_smtpad"){if(r.shape==="circle")i.push({type:"oval",layers:[r.layer],center:{x:r.x,y:r.y},width:r.radius*2,height:r.radius*2,connectedTo:n([r.pcb_smtpad_id])});else if(r.shape==="rect")i.push({type:"rect",layers:[r.layer],center:{x:r.x,y:r.y},width:r.width,height:r.height,connectedTo:n([r.pcb_smtpad_id])});else if(r.shape==="rotated_rect"){let o={center:{x:r.x,y:r.y},width:r.width,height:r.height,rotation:r.ccw_rotation},s=DV(o);for(let a of s)i.push({type:"rect",layers:[r.layer],center:a.center,width:a.width,height:a.height,connectedTo:n([r.pcb_smtpad_id])})}}else if(r.type==="pcb_keepout")r.shape==="circle"?i.push({type:"oval",layers:r.layers,center:{x:r.center.x,y:r.center.y},width:r.radius*2,height:r.radius*2,connectedTo:[]}):r.shape==="rect"&&i.push({type:"rect",layers:r.layers,center:{x:r.center.x,y:r.center.y},width:r.width,height:r.height,connectedTo:[]});else if(r.type==="pcb_cutout"){if(r.shape==="rect")i.push({type:"rect",layers:bc,center:{x:r.center.x,y:r.center.y},width:r.width,height:r.height,connectedTo:[]});else if(r.shape==="circle"){let o=C3t({center:r.center,radius:r.radius},{rectHeight:.6});for(let s of o)i.push({type:"rect",layers:bc,center:s.center,width:s.width,height:s.height,connectedTo:[]})}else if(r.shape==="polygon"){let o=M3t(r.points,{rectHeight:.6});for(let s of o)i.push({type:"rect",layers:bc,center:s.center,width:s.width,height:s.height,connectedTo:[]})}}else if(r.type==="pcb_hole")r.hole_shape==="oval"?i.push({type:"oval",center:{x:r.x,y:r.y},width:r.hole_width,height:r.hole_height,connectedTo:[]}):r.hole_shape==="square"?i.push({type:"rect",layers:bc,center:{x:r.x,y:r.y},width:r.hole_diameter,height:r.hole_diameter,connectedTo:[]}):(r.hole_shape==="round"||r.hole_shape==="circle")&&i.push({type:"rect",layers:bc,center:{x:r.x,y:r.y},width:r.hole_diameter,height:r.hole_diameter,connectedTo:[]});else if(r.type==="pcb_plated_hole")r.shape==="circle"?i.push({type:"oval",layers:bc,center:{x:r.x,y:r.y},width:r.outer_diameter,height:r.outer_diameter,connectedTo:n([r.pcb_plated_hole_id])}):r.shape==="circular_hole_with_rect_pad"?i.push({type:"rect",layers:bc,center:{x:r.x,y:r.y},width:r.rect_pad_width,height:r.rect_pad_height,connectedTo:n([r.pcb_plated_hole_id])}):(r.shape==="oval"||r.shape==="pill")&&i.push({type:"oval",layers:bc,center:{x:r.x,y:r.y},width:r.outer_width,height:r.outer_height,connectedTo:n([r.pcb_plated_hole_id])});else if(r.type==="pcb_trace"){let o=I3t(r.route.map(s=>({x:s.x,y:s.y,layer:"layer"in s?s.layer:s.from_layer})),r.source_trace_id);i.push(...o)}else r.type==="pcb_via"&&i.push({type:"rect",layers:r.layers,center:{x:r.x,y:r.y},connectedTo:[],width:r.outer_diameter,height:r.outer_diameter});return i},xc=({anchor_position:e,anchor_side:t,text:n,font_size:i=.18})=>{let r=.1*(i/.18),o=n.length*r,s=i,a={...e};switch(t){case"right":a.x-=o/2;break;case"left":a.x+=o/2;break;case"top":a.y-=s/2;break;case"bottom":a.y+=s/2;break}return a},uM=({db:e,source_trace_id:t,sameNetOnly:n,differentNetOnly:i})=>{!n&&!i&&(i=!0);let r=e.source_trace.get(t),o=[];for(let s of e.schematic_trace.list()){if(s.source_trace_id===t)continue;let c=e.source_trace.get(s.source_trace_id)?.subcircuit_connectivity_map_key===r.subcircuit_connectivity_map_key;i&&c||n&&!c||o.push(s)}return o},E3t=({edges:e,otherEdges:t})=>{let n=[...e];for(let i=0;i<n.length;i++){if(i>2e3)throw new Error("Over 2000 iterations spent inside createSchematicTraceCrossingSegments, you have triggered an infinite loop, please report this!");let r=n[i],o=Math.abs(r.from.x-r.to.x)<.01?"vertical":r.from.y===r.to.y?"horizontal":"not-orthogonal";if(o==="not-orthogonal")continue;let s=[];for(let g of t){let x=g.from.x===g.to.x?"vertical":g.from.y===g.to.y?"horizontal":"not-orthogonal";if(x==="not-orthogonal"||o===x)continue;if(Ka([r.from,r.to],[g.from,g.to],{lineThickness:.01})){let S=o==="vertical"?r.from.x:g.from.x,C=o==="vertical"?g.from.y:r.from.y,I={x:S,y:C};s.push({otherEdge:g,crossingPoint:I,distanceFromEdgeFrom:zi(r.from,I)})}}if(s.length===0)continue;let a=s[0];for(let g of s)g.distanceFromEdgeFrom<a.distanceFromEdgeFrom&&(a=g);let c=a.crossingPoint,l=.075;if(c.x===r.from.x&&c.y===r.from.y)continue;let u=Bg(r.from,c),h={x:c.x-u.x*l/2,y:c.y-u.y*l/2},d={x:c.x+u.x*l/2,y:c.y+u.y*l/2},_=zi(d,r.to)<l,y=[{from:r.from,to:h},{from:h,to:d,is_crossing:!0},{from:d,to:r.to}];n.splice(i,1,...y),i+=y.length-2,_&&i++}return n},ZI=.001,Ih=(e,t)=>{let n=Math.min(t.from.x,t.to.x),i=Math.max(t.from.x,t.to.x),r=Math.min(t.from.y,t.to.y),o=Math.max(t.from.y,t.to.y);return e.x>=n&&e.x<=i&&e.y>=r&&e.y<=o},aV=e=>{let t=Math.abs(e.from.x-e.to.x)<ZI,n=Math.abs(e.from.y-e.to.y)<ZI;return t?"vertical":n?"horizontal":"diagonal"},k3t=(e,t)=>{let n=aV(e),i=aV(t);if(n===i)return null;if(n==="vertical"&&i==="horizontal"||n==="horizontal"&&i==="vertical"){let h=n==="vertical"?e:t,d=n==="horizontal"?e:t,_=h.from.x,y=d.from.y,g={x:_,y};return Ih(g,e)&&Ih(g,t)?g:null}if(n==="vertical"||i==="vertical"){let h=n==="vertical"?e:t,d=n==="vertical"?t:e,_=h.from.x,y=(d.to.y-d.from.y)/(d.to.x-d.from.x),g=d.from.y-y*d.from.x,x=y*_+g,w={x:_,y:x};return Ih(w,e)&&Ih(w,t)?w:null}let r=(e.to.y-e.from.y)/(e.to.x-e.from.x),o=e.from.y-r*e.from.x,s=(t.to.y-t.from.y)/(t.to.x-t.from.x),a=t.from.y-s*t.from.x;if(Math.abs(r-s)<ZI)return null;let c=(a-o)/(r-s),l=r*c+o,u={x:c,y:l};return Ih(u,e)&&Ih(u,t)?u:null},N3t=({edges:e,db:t,source_trace_id:n})=>{let i=uM({db:t,source_trace_id:n,sameNetOnly:!0}).flatMap(o=>o.edges),r=new Map;for(let o of e)for(let s of i){let a=k3t(o,s);if(a){let c=`${a.x.toFixed(6)},${a.y.toFixed(6)}`;r.has(c)||r.set(c,a)}}return Array.from(r.values())};function A3t(e,t={}){let{minX:n,maxX:i,minY:r,maxY:o}=e,s=t.padding??1;if(!isFinite(n)||!isFinite(i)||!isFinite(r)||!isFinite(o))return[];let a=n-s,c=i+s,l=o+s,u=r-s,h=.01;return[{type:"rect",layers:["top"],center:{x:(a+c)/2,y:l},width:c-a,height:h,connectedTo:[]},{type:"rect",layers:["top"],center:{x:(a+c)/2,y:u},width:c-a,height:h,connectedTo:[]},{type:"rect",layers:["top"],center:{x:a,y:(l+u)/2},width:h,height:l-u,connectedTo:[]},{type:"rect",layers:["top"],center:{x:c,y:(l+u)/2},width:h,height:l-u,connectedTo:[]}]}var R3t=e=>{let t=e.root.db,n=e._findConnectedPorts().ports??[],i=new Set(n.map(s=>s.schematic_port_id)),r=[];for(let s of t.toArray()){if(s.type==="schematic_component"){let a=!!s.symbol_name,c=s.size.width>s.size.height?"horz":"vert";r.push({type:"rect",layers:["top"],center:s.center,width:s.size.width+(a&&c==="horz"?-.5:0),height:s.size.height+(a&&c==="vert"?-.5:0),connectedTo:[]})}if(s.type==="schematic_port"){if(i.has(s.schematic_port_id))continue;let a=s.facing_direction?jg(s.facing_direction):{x:0,y:0};r.push({type:"rect",layers:["top"],center:{x:s.center.x-a.x*.1,y:s.center.y-a.y*.1},width:.1+Math.abs(a.x)*.3,height:.1+Math.abs(a.y)*.3,connectedTo:[]})}s.type==="schematic_text"&&r.push({type:"rect",layers:["top"],center:s.position,width:(s.text?.length??0)*.1,height:.2,connectedTo:[]}),s.type==="schematic_box"&&r.push({type:"rect",layers:["top"],center:{x:s.x,y:s.y},width:s.width,height:s.height,connectedTo:[]})}let o=EV(t.toArray());return r.push(...A3t(o,{padding:1})),r},O3t=({edges:e,db:t,source_trace_id:n})=>{let i=t.source_trace.get(n),r=uM({db:t,source_trace_id:n,differentNetOnly:!0}).flatMap(s=>s.edges),o=s=>{let{from:a,to:c}=s;return a.x===c.x?"vertical":"horizontal"};for(let s of e){let a=o(s),c=()=>r.find(u=>o(u)===a&&Ka([s.from,s.to],[u.from,u.to],{lineThickness:.05})),l=c();for(;l;)a==="horizontal"?(s.from.y+=.1,s.to.y+=.1):(s.from.x+=.1,s.to.x+=.1),l=c()}},KI=e=>{switch(e){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:}},L3t=cD.version??"unknown",um=class extends Error{constructor(e){super(`${e} (capacity-autorouter@${L3t})`),this.name="AutorouterError"}},px=class extends Error{constructor(e){super(e.message),this.errorData=e,this.name="TraceConnectionError"}},F3t=e=>{if(e.root?._featureMspSchematicTraceRouting||e._couldNotFindPort||e.root?.schematicDisabled)return;let{db:t}=e.root,{_parsedProps:n,parent:i}=e;if(!i)throw new Error("Trace has no parent");let r,o;try{let X=e._findConnectedPorts();r=X.allPortsFound,o=X.portsWithSelectors??[]}catch(X){if(X instanceof px){t.source_trace_not_connected_error.insert({...X.errorData,error_type:"source_trace_not_connected_error"});return}throw X}let{netsWithSelectors:s}=e._findConnectedNets();if(!r)return;let c=o.map(X=>X.port.schematic_port_id).sort().join(","),l=e.root?._getBoard();if(l?._connectedSchematicPortPairs&&l._connectedSchematicPortPairs.has(c))return;let u={name:e.source_trace_id,pointsToConnect:[]},h=R3t(e),d=o.filter(({port:X})=>X.schematic_port_id!==null).map(({port:X})=>({port:X,position:X._getGlobalSchematicPositionAfterLayout(),schematic_port_id:X.schematic_port_id??void 0,facingDirection:X.facingDirection}));if(d.length===1&&s.length===1){let X=s[0].net,{port:U,position:tt}=d[0],J=e.getSubcircuit().selectAll("netlabel").find(K=>{let et=K._parsedProps.connection??K._parsedProps.connectsTo;return et?Array.isArray(et)?et.some(mt=>e.getSubcircuit().selectOne(mt,{port:!0})===U):e.getSubcircuit().selectOne(et,{port:!0})===U:!1});if(!J){let K=t.schematic_net_label.getWhere({source_trace_id:e.source_trace_id});K&&(J=K)}if(J){let K="_getGlobalSchematicPositionBeforeLayout"in J?J._getGlobalSchematicPositionBeforeLayout():J.anchor_position,et=[];tt.x===K.x||tt.y===K.y?et.push({from:tt,to:K}):(et.push({from:tt,to:{x:K.x,y:tt.y}}),et.push({from:{x:K.x,y:tt.y},to:K}));let pt=t.schematic_trace.insert({source_trace_id:e.source_trace_id,edges:et,junctions:[],subcircuit_connectivity_map_key:e.subcircuit_connectivity_map_key??void 0});e.schematic_trace_id=pt.schematic_trace_id;return}if(e.props.schDisplayLabel){let K=ym(U.facingDirection)??"bottom";t.schematic_net_label.insert({text:e.props.schDisplayLabel,source_net_id:X.source_net_id,anchor_position:tt,center:xc({anchor_position:tt,anchor_side:K,text:e.props.schDisplayLabel}),anchor_side:K});return}let V=ym(U.facingDirection)??"bottom",rt=t.schematic_net_label.insert({text:X._parsedProps.name,source_net_id:X.source_net_id,anchor_position:tt,center:xc({anchor_position:tt,anchor_side:V,text:X._parsedProps.name}),anchor_side:V});return}if(e.props.schDisplayLabel&&("from"in e.props&&"to"in e.props||"path"in e.props)){e._doInitialSchematicTraceRenderWithDisplayLabel();return}if(d.length<2)return;let g=(()=>{let X=[];for(let tt=0;tt<d.length-1;tt++){let J=d[tt],V=d[tt+1],rt=Qa({x:J.position.x,y:J.position.y,facingDirection:KI(J.facingDirection)},{x:V.position.x,y:V.position.y,facingDirection:KI(V.facingDirection)});for(let K=0;K<rt.length-1;K++)X.push({from:rt[K],to:rt[K+1]})}let U=(tt,J)=>{let V=J.width/2,rt=J.height/2,K=J.center.x-V,et=J.center.x+V,pt=J.center.y-rt,mt=J.center.y+rt,It=lt=>lt.x>=K&<.x<=et&<.y>=pt&<.y<=mt;return It(tt.from)||It(tt.to)?!0:[[{x:K,y:pt},{x:et,y:pt}],[{x:et,y:pt},{x:et,y:mt}],[{x:et,y:mt},{x:K,y:mt}],[{x:K,y:mt},{x:K,y:pt}]].some(lt=>Ka([tt.from,tt.to],lt,{lineThickness:0}))};for(let tt of X)for(let J of h)if(U(tt,J))return null;return X})();g&&g.length===0&&(g=null),u.pointsToConnect=d.map(({position:X})=>({...X,layer:"top"}));let x=y3t(h),w=2,S={minTraceWidth:.1,obstacles:h,connections:[u],bounds:{minX:x.minX-w,maxX:x.maxX+w,minY:x.minY-w,maxY:x.maxY+w},layerCount:1},C=Cg,I=!1;if(e.getSubcircuit().props._schDirectLineRoutingEnabled&&(C=iV,I=!0),!g){let U=new C({input:S,MAX_ITERATIONS:100,OBSTACLE_MARGIN:.1,isRemovePathLoopsEnabled:!0,isShortenPathWithShortcutsEnabled:!0,marginsWithCosts:[{margin:1,enterCost:0,travelCostFactor:1},{margin:.3,enterCost:0,travelCostFactor:1},{margin:.2,enterCost:0,travelCostFactor:2},{margin:.1,enterCost:0,travelCostFactor:3}]}).solveAndMapToTraces();if(U.length===0){if(e._isSymbolToChipConnection()||e._isSymbolToSymbolConnection()||e._isChipToChipConnection()){e._doInitialSchematicTraceRenderWithDisplayLabel();return}U=new iV({input:S}).solveAndMapToTraces(),I=!0}let[{route:tt}]=U;g=[];for(let J=0;J<tt.length-1;J++)g.push({from:tt[J],to:tt[J+1]})}let k=e.source_trace_id,P=[];if(!I){O3t({edges:g,db:t,source_trace_id:k});let X=uM({db:t,source_trace_id:k,differentNetOnly:!0}).flatMap(U=>U.edges);g=E3t({edges:g,otherEdges:X}),P=N3t({edges:g,db:t,source_trace_id:e.source_trace_id})}if(!g||g.length===0)return;let N=g[g.length-1],E=d[d.length-1],A=oV(N);g.push(...WI({lastEdge:N,lastEdgePort:E,lastDominantDirection:A}));let O=g[0],$=d[0],B=oV(O);if(g.unshift(...WI({firstEdge:O,firstEdgePort:$,firstDominantDirection:B})),!e.source_trace_id)throw new Error("Missing source_trace_id for schematic trace insertion.");if(e.getSubcircuit()._parsedProps.schTraceAutoLabelEnabled&&v3t(P,g)>=5&&(e._isSymbolToChipConnection()||e._isSymbolToSymbolConnection()||e._isChipToChipConnection())){e._doInitialSchematicTraceRenderWithDisplayLabel();return}let H=t.schematic_trace.insert({source_trace_id:e.source_trace_id,edges:g,junctions:P,subcircuit_connectivity_map_key:e.subcircuit_connectivity_map_key??void 0});e.schematic_trace_id=H.schematic_trace_id;for(let{port:X}of o)X.schematic_port_id&&t.schematic_port.update(X.schematic_port_id,{is_connected:!0});l?._connectedSchematicPortPairs&&l._connectedSchematicPortPairs.add(c)};function $V(e){let t=0;for(let n=0;n<e.length;n++){let i=e[n];if(i.route_type==="wire"){let r=e[n+1];if(r){let o=r.x-i.x,s=r.y-i.y;t+=Math.sqrt(o*o+s*s)}}else i.route_type==="via"&&(t+=1.6)}return t}var ox=e=>({...e._getGlobalPcbPositionAfterLayout(),layers:e.getAvailablePcbLayers()}),z3t=!1;function D3t(e){if(e.root?.pcbDisabled)return;let{db:t}=e.root,{_parsedProps:n,parent:i}=e,r=e.getSubcircuit();if(!i)throw new Error("Trace has no parent");if(r._parsedProps.routingDisabled)return;let o=r._parsedProps.pcbRouteCache?.pcbTraces;if(o){let A=t.pcb_trace.insert({route:o.flatMap(O=>O.route),source_trace_id:e.source_trace_id,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0});e.pcb_trace_id=A.pcb_trace_id;return}if(n.pcbPath&&n.pcbPath.length>0||!r._shouldUseTraceByTraceRouting())return;let{allPortsFound:s,ports:a}=e._findConnectedPorts(),c=[];if(!s)return;let l=[];for(let A of a)A._hasMatchedPcbPrimitive()||l.push(A);if(l.length>0){t.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:e.source_trace_id,message:`Some ports did not have a matching PCB primitive (e.g. a pad or plated hole), this can happen if a footprint is missing. As a result, ${e} wasn't routed. Missing ports: ${l.map(A=>A.getString()).join(", ")}`,pcb_trace_id:e.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:l.map(A=>A.pcb_port_id).filter(Boolean)});return}let u=e._findConnectedNets().netsWithSelectors;if(a.length===0&&u.length===2){e.renderError("Trace connects two nets, we haven't implemented a way to route this yet");return}else if(a.length===1&&u.length===1){let A=a[0],$=u[0].net.getAllConnectedPorts().filter(H=>H!==A);if($.length===0){console.log("Nothing to connect this port to, the net is empty. TODO should emit a warning!");return}let B=x3t(A,$);c.push(B),a.push(B)}else if(a.length>1&&u.length>=1){e.renderError("Trace has more than one port and one or more nets, we don't currently support this type of complex trace routing");return}let h=a.flatMap(A=>A.matchedComponents.filter(O=>O.componentName==="TraceHint")),d=(e._parsedProps.pcbRouteHints??[]).concat(h.flatMap(A=>A.getPcbRouteHints()));if(a.length>2){e.renderError(`Trace has more than two ports (${a.map(A=>A.getString()).join(", ")}), routing between more than two ports for a single trace is not implemented`);return}if(e.getSubcircuit().selectAll("trace").filter(A=>A.renderPhaseStates.PcbTraceRender.initialized).some(A=>A._portsRoutedOnPcb.length===a.length&&A._portsRoutedOnPcb.every(O=>a.includes(O))))return;let g=[];d.length===0?g=[ox(a[0]),ox(a[1])]:g=[ox(a[0]),...d,ox(a[1])];let x=cx(g);if(z3t&&x.length===0){e.renderError(`Could not find a common layer (using hints) for trace ${e.getString()}`);return}let w=si(e.root.db.toArray()),[S,C]=w3t(()=>lM(e.root.db.toArray()));if(C){e.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:e.pcb_trace_id,message:`Error getting obstacles for autorouting: ${C.message}`,source_trace_id:e.source_trace_id,center:{x:0,y:0},pcb_port_ids:a.map(A=>A.pcb_port_id),pcb_trace_id:e.pcb_trace_id,pcb_component_ids:[]});return}for(let A of S)if(A.connectedTo.length>0){let $=w.getNetConnectedToId(A.connectedTo[0]);$&&A.connectedTo.push($)}let I=[];if(x.length===0)I=g;else{let A=x[0].layer_path;I=g.map((O,$)=>O.via?{...O,via_to_layer:A[$]}:{...O,layers:[A[$]]})}I[0].pcb_port_id=a[0].pcb_port_id,I[I.length-1].pcb_port_id=a[1].pcb_port_id;let k=[];for(let[A,O]of CV(I)){let $="via_to_layer"in A?A.via_to_layer:null,B=2,H="layers"in A&&A.layers.length===1?A.layers[0]:$??"top",X="layers"in O&&O.layers.length===1?O.layers[0]:$??"top",U="pcb_port_id"in A?A.pcb_port_id:null,tt="pcb_port_id"in O?O.pcb_port_id:null,J=e._getExplicitTraceThickness()??e.getSubcircuit()._parsedProps.minTraceWidth??.16,V=new Cg({OBSTACLE_MARGIN:J*2,isRemovePathLoopsEnabled:!0,optimizeWithGoalBoxes:!!(U&&tt),connMap:w,input:{obstacles:S,minTraceWidth:J,connections:[{name:e.source_trace_id,pointsToConnect:[{...A,layer:H,pcb_port_id:U},{...O,layer:X,pcb_port_id:tt}]}],layerCount:e.getSubcircuit()._getSubcircuitLayerCount(),bounds:{minX:Math.min(A.x,O.x)-B,maxX:Math.max(A.x,O.x)+B,minY:Math.min(A.y,O.y)-B,maxY:Math.max(A.y,O.y)+B}}}),rt=null;try{rt=V.solveAndMapToTraces()}catch(pt){e.renderError({type:"pcb_trace_error",pcb_trace_error_id:e.source_trace_id,error_type:"pcb_trace_error",message:`error solving route: ${pt.message}`,source_trace_id:e.pcb_trace_id,center:{x:(A.x+O.x)/2,y:(A.y+O.y)/2},pcb_port_ids:a.map(mt=>mt.pcb_port_id),pcb_trace_id:e.pcb_trace_id,pcb_component_ids:a.map(mt=>mt.pcb_component_id)})}if(!rt)return;if(rt.length===0){e.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:e.pcb_trace_id,message:`Could not find a route for ${e}`,source_trace_id:e.source_trace_id,center:{x:(A.x+O.x)/2,y:(A.y+O.y)/2},pcb_port_ids:a.map(pt=>pt.pcb_port_id),pcb_trace_id:e.pcb_trace_id,pcb_component_ids:a.map(pt=>pt.pcb_component_id)});return}let[K]=rt;$&&(K.route=K.route.map(pt=>(pt.route_type==="wire"&&!pt.layer&&(pt.layer=$),pt))),U&&K.route[0].route_type==="wire"&&(K.route[0].start_pcb_port_id=U);let et=K.route[K.route.length-1];tt&&et.route_type==="wire"&&(et.end_pcb_port_id=tt),k.push(K.route)}let P=g3t(k),N=$V(P),E=t.pcb_trace.insert({route:P,source_trace_id:e.source_trace_id,subcircuit_id:e.getSubcircuit()?.subcircuit_id,trace_length:N});e._portsRoutedOnPcb=a,e.pcb_trace_id=E.pcb_trace_id;for(let A of P)A.route_type==="via"&&t.pcb_via.insert({pcb_trace_id:E.pcb_trace_id,x:A.x,y:A.y,hole_diameter:.3,outer_diameter:.6,layers:[A.from_layer,A.to_layer],from_layer:A.from_layer,to_layer:A.to_layer});e._insertErrorIfTraceIsOutsideBoard(P,a)}function $3t(e){if(e.root?.pcbDisabled)return;let{db:t}=e.root,{_parsedProps:n}=e,i=e.getSubcircuit();if(!n.pcbPath)return;let{allPortsFound:r,ports:o,portsWithSelectors:s}=e._findConnectedPorts();if(!r)return;let a=[];for(let S of o)S._hasMatchedPcbPrimitive()||a.push(S);if(a.length>0){t.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:e.source_trace_id,message:`Some ports did not have a matching PCB primitive (e.g. a pad or plated hole), this can happen if a footprint is missing. As a result, ${e} wasn't routed. Missing ports: ${a.map(S=>S.getString()).join(", ")}`,pcb_trace_id:e.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:a.map(S=>S.pcb_port_id).filter(Boolean)});return}let c;n.pcbPathRelativeTo&&(c=s.find(S=>S.selector===n.pcbPathRelativeTo)?.port,c||(c=e.getSubcircuit().selectOne(n.pcbPathRelativeTo))),c||(c=o[0]);let l=o.find(S=>S!==c)??o[1],u=c.getAvailablePcbLayers()[0]||"top",h=e._getExplicitTraceThickness()??e.getSubcircuit()._parsedProps.minTraceWidth??.16,d=c._getGlobalPcbPositionAfterLayout(),_=l._getGlobalPcbPositionAfterLayout(),y=[];y.push({route_type:"wire",x:d.x,y:d.y,width:h,layer:u,start_pcb_port_id:c.pcb_port_id});let g=c?._computePcbGlobalTransformBeforeLayout?.()||Li();for(let S of n.pcbPath){let C,I=!1;if(typeof S=="string"){let P=e.getSubcircuit().selectOne(S,{type:"port"});if(!P){t.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:e.source_trace_id,message:`Could not resolve pcbPath selector "${S}" for ${e}`,pcb_trace_id:e.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:[]});continue}let N=P._getGlobalPcbPositionAfterLayout();C={x:N.x,y:N.y},I=!0}else C={x:S.x,y:S.y},I=!1;let k=I?C:Ae(g,C);y.push({route_type:"wire",x:k.x,y:k.y,width:h,layer:u})}y.push({route_type:"wire",x:_.x,y:_.y,width:h,layer:u,end_pcb_port_id:l.pcb_port_id});let x=$V(y),w=t.pcb_trace.insert({route:y,source_trace_id:e.source_trace_id,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0,trace_length:x});e._portsRoutedOnPcb=o,e.pcb_trace_id=w.pcb_trace_id,e._insertErrorIfTraceIsOutsideBoard(y,o)}function B3t(e){if(e.root?.schematicDisabled)return;let{db:t}=e.root,{_parsedProps:n,parent:i}=e;if(!i)throw new Error("Trace has no parent");let{allPortsFound:r,portsWithSelectors:o}=e._findConnectedPorts();if(!r)return;let s=o.map(({port:I})=>({port:I,position:I._getGlobalSchematicPositionAfterLayout(),schematic_port_id:I.schematic_port_id,facingDirection:I.facingDirection}));if(s.length<2)throw new Error("Expected at least two ports in portsWithPosition.");let a,c,l=s[0].position,u=s[0].port;if("path"in e.props){if(e.props.path.length!==2)throw new Error("Invalid 'path': Must contain exactly two elements.");[a,c]=e.props.path}else{if(!("from"in e.props&&"to"in e.props))throw new Error("Missing 'from' or 'to' properties in props.");a=e.props.from,c=e.props.to}if(!u.source_port_id)throw new Error(`Missing source_port_id for the 'from' port (${a}).`);let h=s[1].position,d=s[1].port;if(!d.source_port_id)throw new Error(`Missing source_port_id for the 'to' port (${c}).`);let _=t.schematic_net_label.list().find(I=>I.source_net_id===u.source_port_id),y=t.schematic_net_label.list().find(I=>I.source_net_id===d.source_port_id),[g,x]=o.map(({port:I})=>I),S=g.parent?.config.shouldRenderAsSchematicBox?`${g?.parent?.props.name}_${g?.props.name}`:`${x?.parent?.props.name}_${x?.props.name}`,C=e.props.schDisplayLabel??S;if(_&&_.text!==C&&(_.text=`${C} / ${_.text}`),y&&y?.text!==C&&(y.text=`${C} / ${y.text}`),!y){let I=ym(d.facingDirection)??"bottom";t.schematic_net_label.insert({text:e.props.schDisplayLabel??S,source_net_id:d.source_port_id,anchor_position:h,center:xc({anchor_position:h,anchor_side:I,text:e.props.schDisplayLabel??S}),anchor_side:I})}if(!_){let I=ym(u.facingDirection)??"bottom";t.schematic_net_label.insert({text:e.props.schDisplayLabel??S,source_net_id:u.source_port_id,anchor_position:l,center:xc({anchor_position:l,anchor_side:I,text:e.props.schDisplayLabel??S}),anchor_side:I})}}function j3t(e){let{_parsedProps:t,parent:n}=e;if(!n)throw new Error("Trace has no parent");let r=e.getTracePortPathSelectors().map(o=>({selector:o,port:e.getSubcircuit().selectOne(o,{type:"port"})??null}));for(let{selector:o,port:s}of r)if(!s){let a,c,l=o.lastIndexOf(".");if(l!==-1&&l>o.lastIndexOf(" "))a=o.slice(0,l),c=o.slice(l+1);else{let I=o.match(/^(.*[ >])?([^ >]+)$/);a=I?.[1]?.trim()??"",c=I?.[2]??o}let u=a?e.getSubcircuit().selectOne(a):null;if(!u&&a&&!/[.#\[]/.test(a)&&(u=e.getSubcircuit().selectOne(`.${a}`)),!u){let I=a?`Could not find port for selector "${o}". Component "${a}" not found`:`Could not find port for selector "${o}"`,k=e.getSubcircuit(),P=k.getGroup();throw new px({error_type:"source_trace_not_connected_error",message:I,subcircuit_id:k.subcircuit_id??void 0,source_group_id:P?.source_group_id??void 0,source_trace_id:e.source_trace_id??void 0,selectors_not_found:[o]})}let h=u.children.filter(I=>I.componentName==="Port"),d=c.includes(".")?c.split(".").pop()??"":c,_=h.flatMap(I=>I.getNameAndAliases()),y=_.some(I=>!/^(pin\d+|\d+)$/.test(I)),g=Array.from(new Set(_)).join(", "),x;h.length===0?x="It has no ports":y?x=`It has [${g}]`:x=`It has ${h.length} pins and no pinLabels (consider adding pinLabels)`;let w=`Could not find port for selector "${o}". Component "${u.props.name??a}" found, but does not have pin "${d}". ${x}`,S=e.getSubcircuit(),C=S.getGroup();throw new px({error_type:"source_trace_not_connected_error",message:w,subcircuit_id:S.subcircuit_id??void 0,source_group_id:C?.source_group_id??void 0,source_trace_id:e.source_trace_id??void 0,selectors_not_found:[o]})}return r.some(o=>!o.port)?{allPortsFound:!1}:{allPortsFound:!0,portsWithSelectors:r,ports:r.map(({port:o})=>o)}}var ko=class extends xe{constructor(t){super(t);M(this,"source_trace_id",null);M(this,"pcb_trace_id",null);M(this,"schematic_trace_id",null);M(this,"_portsRoutedOnPcb");M(this,"subcircuit_connectivity_map_key",null);M(this,"_traceConnectionHash",null);M(this,"_couldNotFindPort");this._portsRoutedOnPcb=[]}_getExplicitTraceThickness(){return this._parsedProps.thickness??this._parsedProps.width}get config(){return{zodProps:GF,componentName:"Trace"}}_getTracePortOrNetSelectorListFromProps(){return"from"in this.props&&"to"in this.props?[typeof this.props.from=="string"?this.props.from:this.props.from.getPortSelector(),typeof this.props.to=="string"?this.props.to:this.props.to.getPortSelector()]:"path"in this.props?this.props.path.map(t=>typeof t=="string"?t:t.getPortSelector()):[]}getTracePortPathSelectors(){return this._getTracePortOrNetSelectorListFromProps().filter(t=>!t.includes("net."))}getTracePathNetSelectors(){return this._getTracePortOrNetSelectorListFromProps().filter(t=>t.includes("net."))}_findConnectedPorts(){return j3t(this)}_resolveNet(t){let n=this.getSubcircuit().selectOne(t,{type:"net"});if(n)return n;let i=t.match(/^net\.(.+)$/),r=i?i[1]:null;if(!r)return null;let o=this.root?._getBoard();return o?o.getDescendants().find(a=>a.componentName==="Net"&&a._parsedProps.name===r)||null:(this.renderError(`Could not find a <board> ancestor for ${this}, so net "${t}" cannot be resolved`),null)}_findConnectedNets(){let t=this.getTracePathNetSelectors().map(i=>({selector:i,net:this._resolveNet(i)})),n=t.filter(i=>!i.net);return n.length>0&&this.renderError(`Could not find net for selector "${n[0].selector}" inside ${this}`),{netsWithSelectors:t,nets:t.map(i=>i.net)}}_getAllTracesConnectedToSameNet(){let t=this.getSubcircuit().selectAll("trace"),n=this._findConnectedNets().nets,i=this._findConnectedPorts().ports??[];return t.filter(r=>{if(r===this)return!1;let o=r._findConnectedNets().nets,s=r._findConnectedPorts().ports??[];return o.some(a=>n.includes(a))||s.some(a=>i.includes(a))})}_isExplicitlyConnectedToPort(t){let{allPortsFound:n,portsWithSelectors:i}=this._findConnectedPorts();return n?i.map(o=>o.port).includes(t):!1}_isExplicitlyConnectedToNet(t){return this._findConnectedNets().nets.includes(t)}doInitialCreateNetsFromProps(){sM(this,this.getTracePathNetSelectors())}_computeTraceConnectionHash(){let{allPortsFound:t,ports:n}=this._findConnectedPorts();return!t||!n?null:[...n].sort((o,s)=>(o.pcb_port_id||"").localeCompare(s.pcb_port_id||"")).map(o=>o.pcb_port_id).join(",")}doInitialSourceTraceRender(){let{db:t}=this.root,{_parsedProps:n,parent:i}=this;if(!i){this.renderError("Trace has no parent");return}let r,o;try{let h=this._findConnectedPorts();r=h.allPortsFound,o=h.portsWithSelectors??[]}catch(h){if(h instanceof px){t.source_trace_not_connected_error.insert({...h.errorData,error_type:"source_trace_not_connected_error"}),this._couldNotFindPort=!0;return}throw h}if(!r)return;this._traceConnectionHash=this._computeTraceConnectionHash();let a=t.source_trace.list().find(h=>h.subcircuit_connectivity_map_key===this.subcircuit_connectivity_map_key&&h.connected_source_port_ids.sort().join(",")===this._traceConnectionHash);if(a){this.source_trace_id=a.source_trace_id;return}let c=this._findConnectedNets().nets,l=P3t({ports:o,nets:c}),u=t.source_trace.insert({connected_source_port_ids:o.map(h=>h.port.source_port_id),connected_source_net_ids:c.map(h=>h.source_net_id),subcircuit_id:this.getSubcircuit()?.subcircuit_id,max_length:S3t(o.map(h=>h.port),{db:t})??n.maxLength,display_name:l,min_trace_thickness:this._getExplicitTraceThickness()});this.source_trace_id=u.source_trace_id}_insertErrorIfTraceIsOutsideBoard(t,n){let{db:i}=this.root;T3t(t,{db:i})&&i.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:this.source_trace_id,message:`Trace ${this.getString()} routed outside the board boundaries.`,pcb_trace_id:this.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:n.map(o=>o.pcb_port_id)})}doInitialPcbManualTraceRender(){$3t(this)}doInitialPcbTraceRender(){D3t(this)}_doInitialSchematicTraceRenderWithDisplayLabel(){B3t(this)}_isSymbolToChipConnection(){let{allPortsFound:t,ports:n}=this._findConnectedPorts();if(!t||n.length!==2)return!1;let[i,r]=n;if(!i?.parent||!r?.parent)return!1;let o=i.parent.config.shouldRenderAsSchematicBox,s=r.parent.config.shouldRenderAsSchematicBox;return o&&!s||!o&&s}_isSymbolToSymbolConnection(){let{allPortsFound:t,ports:n}=this._findConnectedPorts();if(!t||n.length!==2)return!1;let[i,r]=n;if(!i?.parent||!r?.parent)return!1;let o=!i.parent.config.shouldRenderAsSchematicBox,s=!r.parent.config.shouldRenderAsSchematicBox;return o&&s}_isChipToChipConnection(){let{allPortsFound:t,ports:n}=this._findConnectedPorts();if(!t||n.length!==2)return!1;let[i,r]=n;if(!i?.parent||!r?.parent)return!1;let o=i.parent.config.shouldRenderAsSchematicBox,s=r.parent.config.shouldRenderAsSchematicBox;return o&&s}doInitialSchematicTraceRender(){F3t(this)}},Y3t=e=>{let{db:t}=e.root;if(e.pcb_component_id){let n=t.pcb_component.get(e.pcb_component_id);return n?{width:n.width,height:n.height}:null}if(e.pcb_group_id){let n=t.pcb_group.get(e.pcb_group_id);if(!n)return null;if(n.outline&&n.outline.length>0){let i=qo(n.outline);return i?{width:i.maxX-i.minX,height:i.maxY-i.minY}:null}return{width:n.width??0,height:n.height??0}}return null},X3t=(e,t)=>{let{db:n}=e.root,i=n.toArray();if(e.pcb_component_id){Yg(i,e.pcb_component_id,t);return}if(e.source_group_id){Xg(i,e.source_group_id,t);return}throw new Error(`Cannot reposition component ${e.getString()}: no pcb_component_id or source_group_id`)},V3t=e=>{let{db:t}=e.root;if(!e.source_component_id)return;let n=e.selectAll("port"),i=t.source_trace.list(),r=new Set;for(let s of i)for(let a of s.connected_source_port_ids)r.add(a);let o=e._getInternallyConnectedPins();for(let s of o)if(s.some(a=>a.source_port_id&&r.has(a.source_port_id)))for(let a of s)a.source_port_id&&r.add(a.source_port_id);for(let s of n)s.source_port_id&&H3t(e,s)&&(r.has(s.source_port_id)||t.source_pin_missing_trace_warning.insert({message:`Port ${s.getNameAndAliases()[0]} on ${e.props.name} is missing a trace`,source_component_id:e.source_component_id,source_port_id:s.source_port_id,subcircuit_id:e.getSubcircuit().subcircuit_id??void 0,warning_type:"source_pin_missing_trace_warning"}))},H3t=(e,t)=>{if(e.config.componentName==="Chip"){let n=e.props.pinAttributes;if(!n)return!1;for(let i of t.getNameAndAliases()){let r=n[i];if(r?.requiresPower||r?.requiresGround||r?.requiresVoltage!==void 0)return!0}return!1}return!0};function G3t(e){let t=e.font_size,n=e.text.length*t*.6,i=t,r=e.anchor_alignment||"center",o=e.anchor_position.x,s=e.anchor_position.y;switch(r){case"top_left":o=e.anchor_position.x+n/2,s=e.anchor_position.y+i/2;break;case"top_center":o=e.anchor_position.x,s=e.anchor_position.y+i/2;break;case"top_right":o=e.anchor_position.x-n/2,s=e.anchor_position.y+i/2;break;case"center_left":o=e.anchor_position.x+n/2,s=e.anchor_position.y;break;case"center":o=e.anchor_position.x,s=e.anchor_position.y;break;case"center_right":o=e.anchor_position.x-n/2,s=e.anchor_position.y;break;case"bottom_left":o=e.anchor_position.x+n/2,s=e.anchor_position.y-i/2;break;case"bottom_center":o=e.anchor_position.x,s=e.anchor_position.y-i/2;break;case"bottom_right":o=e.anchor_position.x-n/2,s=e.anchor_position.y-i/2;break;default:o=e.anchor_position.x,s=e.anchor_position.y;break}return{x:o-n/2,y:s-i/2,width:n,height:i}}function U3t(e){if(!e._adjustSilkscreenTextAutomatically||e.root?.pcbDisabled||!e.pcb_component_id)return;let{db:t}=e.root,i=e._getPcbCircuitJsonBounds().center,r=t.pcb_silkscreen_text.list({pcb_component_id:e.pcb_component_id}).filter(c=>c.text===e.name);if(r.length===0)return;let a=e.getSubcircuit().selectAll("[_isNormalComponent=true]").filter(c=>c!==e&&c.pcb_component_id).map(c=>{let l=c._getPcbCircuitJsonBounds(),u={center:l.center,width:l.width,height:l.height};return Mo(u)});for(let c of r){let l=c.anchor_position,u=G3t(c),h={center:{x:u.x+u.width/2,y:u.y+u.height/2},width:u.width,height:u.height},d=Mo(h);if(!a.some(C=>Ja(d,C)))continue;let y=2*i.x-l.x,g=2*i.y-l.y,x={center:{x:y,y:g},width:u.width,height:u.height},w=Mo(x);a.some(C=>Ja(w,C))||t.pcb_silkscreen_text.update(c.pcb_silkscreen_text_id,{anchor_position:{x:y,y:g}})}}function q3t(e){if(!e)return{validPinLabels:e,invalidPinLabelsMessages:[]};let t={},n=[];for(let[i,r]of Object.entries(e)){let o=Array.isArray(r)?r.slice():[r],s=[];for(let a of o)W3t(i,a)?s.push(a):n.push(`Invalid pin label: ${i} = '${a}' - excluding from component. Please use a valid pin label.`);s.length>0&&(t[i]=Array.isArray(r)?s:s[0])}return{validPinLabels:Object.keys(t).length>0?t:void 0,invalidPinLabelsMessages:n}}function W3t(e,t){try{let n={name:"test",footprint:"test",pinLabels:{[e]:t}};return Bp.safeParse(n).success}catch{return!1}}var Nh=e=>e.startsWith("http://")||e.startsWith("https://"),QI=e=>{if(Nh(e))return null;let t=e.indexOf(":");if(t<=0)return null;let n=e.slice(0,t),i=e.slice(t+1);return!n||!i?null:{footprintLib:n,footprintName:i}},tM=e=>e.startsWith("/");function Z3t(e,t){let{footprint:n}=e.props;if(n??(n=e._getImpliedFootprintString?.()),!n)return;let{pcbRotation:i,pinLabels:r,pcbPinLabels:o}=e.props,s=OV(String(n)),a=s?e.root?.platform?.footprintFileParserMap?.[s]:null;if(typeof n=="string"&&(Nh(n)||tM(n))&&a){if(e._hasStartedFootprintUrlLoad)return;e._hasStartedFootprintUrlLoad=!0;let c=e.root?.platform?.projectBaseUrl,l=Nh(n)?n:LV(n,c);t("load-footprint-from-platform-file-parser",async()=>{try{let u=await a.loadFromUrl(l),h=lm({componentName:e.name,componentRotation:i,footprint:l,pinLabels:r,pcbPinLabels:o},u.footprintCircuitJson);e.addAll(h),e._markDirty("InitializePortsFromChildren")}catch(u){let h=e.root?.db;if(h&&e.source_component_id&&e.pcb_component_id){let d=e.getSubcircuit(),_=`${e.getString()} failed to load footprint "${l}": `+(u instanceof Error?u.message:String(u)),y=gp.parse({type:"external_footprint_load_error",message:_,pcb_component_id:e.pcb_component_id,source_component_id:e.source_component_id,subcircuit_id:d.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0,footprinter_string:l});h.external_footprint_load_error.insert(y)}throw u}});return}if(typeof n=="string"&&Nh(n)){if(e._hasStartedFootprintUrlLoad)return;e._hasStartedFootprintUrlLoad=!0;let c=n;t("load-footprint-url",async()=>{try{let l=await fetch(c);if(!l.ok)throw new Error(`Failed to fetch footprint: ${l.status}`);let u=await l.json(),h=lm({componentName:e.name,componentRotation:i,footprint:c,pinLabels:r,pcbPinLabels:o},u);e.addAll(h),e._markDirty("InitializePortsFromChildren")}catch(l){let u=e.root?.db;if(u&&e.source_component_id&&e.pcb_component_id){let h=e.getSubcircuit(),d=`${e.getString()} failed to load external footprint "${c}": `+(l instanceof Error?l.message:String(l)),_=gp.parse({type:"external_footprint_load_error",message:d,pcb_component_id:e.pcb_component_id,source_component_id:e.source_component_id,subcircuit_id:h.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0,footprinter_string:c});u.external_footprint_load_error.insert(_)}throw l}});return}if(typeof n=="string"){let c=QI(n);if(!c||e._hasStartedFootprintUrlLoad)return;e._hasStartedFootprintUrlLoad=!0;let u=e.root?.platform?.footprintLibraryMap?.[c.footprintLib],h;if(typeof u=="function"&&(h=u),!h)return;t("load-lib-footprint",async()=>{try{let d=await h(c.footprintName),_=null;if(Array.isArray(d)?_=d:Array.isArray(d.footprintCircuitJson)&&(_=d.footprintCircuitJson),!_)return;let y=lm({componentName:e.name,componentRotation:i,footprint:n,pinLabels:r,pcbPinLabels:o},_);e.addAll(y),!Array.isArray(d)&&d.cadModel&&(e._asyncFootprintCadModel=d.cadModel);for(let g of e.children)g.componentName==="Port"&&g._markDirty?.("PcbPortRender");e._markDirty("InitializePortsFromChildren")}catch(d){let _=e.root?.db;if(_&&e.source_component_id&&e.pcb_component_id){let y=e.getSubcircuit(),g=`${e.getString()} failed to load external footprint "${n}": `+(d instanceof Error?d.message:String(d)),x=gp.parse({type:"external_footprint_load_error",message:g,pcb_component_id:e.pcb_component_id,source_component_id:e.source_component_id,subcircuit_id:y.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0,footprinter_string:n});_.external_footprint_load_error.insert(x)}throw d}});return}if(!(0,JI.isValidElement)(n)&&n.componentName==="Footprint"&&e.add(n),Array.isArray(n)&&!(0,JI.isValidElement)(n)&&n.length>0){try{let c=lm({componentName:e.name,componentRotation:i,footprint:"",pinLabels:r,pcbPinLabels:o},n);e.addAll(c)}catch(c){let l=e.root?.db;if(l&&e.source_component_id&&e.pcb_component_id){let u=e.getSubcircuit(),h=`${e.getString()} failed to load json footprint: `+(c instanceof Error?c.message:String(c)),d=h_.parse({type:"circuit_json_footprint_load_error",message:h,pcb_component_id:e.pcb_component_id,source_component_id:e.source_component_id,subcircuit_id:u.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0});l.circuit_json_footprint_load_error.insert(d)}throw c}return}}function K3t(e){if(e.root?.pcbDisabled||!e.pcb_component_id)return;let{pcbX:t,pcbY:n}=e._parsedProps,i=e.props?.pcbPositionAnchor;if(!i||t===void 0&&n===void 0)return;let r=mx(e.children);if(r.width===0||r.height===0)return;let s={...{x:(r.minX+r.maxX)/2,y:(r.minY+r.maxY)/2}},a=null;if(new Set(["center","top_left","top_center","top_right","center_left","center_right","bottom_left","bottom_center","bottom_right"]).has(i)){let u={left:r.minX,right:r.maxX,top:r.minY,bottom:r.maxY};switch(i){case"center":a=s;break;case"top_left":a={x:u.left,y:u.top};break;case"top_center":a={x:s.x,y:u.top};break;case"top_right":a={x:u.right,y:u.top};break;case"center_left":a={x:u.left,y:s.y};break;case"center_right":a={x:u.right,y:s.y};break;case"bottom_left":a={x:u.left,y:u.bottom};break;case"bottom_center":a={x:s.x,y:u.bottom};break;case"bottom_right":a={x:u.right,y:u.bottom};break}}else try{let u=e.portMap[i];u&&(a=u._getGlobalPcbPositionBeforeLayout())}catch{}if(!a)return;let l={...s};t!==void 0&&(l.x+=t-a.x),n!==void 0&&(l.y+=n-a.y),(Math.abs(l.x-s.x)>1e-6||Math.abs(l.y-s.y)>1e-6)&&e._repositionOnPcb(l)}var J3t=(0,SV.default)("tscircuit:core"),Q3t=p.object({x:$e,y:$e,z:$e}),On=class extends xe{constructor(t){let n={...t},i=[];if(n.pinLabels&&!Array.isArray(n.pinLabels)){let{validPinLabels:r,invalidPinLabelsMessages:o}=q3t(n.pinLabels);n.pinLabels=r,i=o}super(n);M(this,"reactSubtrees",[]);M(this,"_impliedFootprint");M(this,"isPrimitiveContainer",!0);M(this,"_isNormalComponent",!0);M(this,"_attributeLowerToCamelNameMap",{_isnormalcomponent:"_isNormalComponent"});M(this,"_asyncSupplierPartNumbers");M(this,"_asyncFootprintCadModel");M(this,"_isCadModelChild");M(this,"pcb_missing_footprint_error_id");M(this,"_hasStartedFootprintUrlLoad",!1);M(this,"_invalidPinLabelMessages",[]);M(this,"_adjustSilkscreenTextAutomatically",!1);this._invalidPinLabelMessages=i,this._addChildrenFromStringFootprint(),this.initPorts()}get defaultInternallyConnectedPinNames(){return[]}get internallyConnectedPinNames(){return(this._parsedProps.internallyConnectedPins??this.defaultInternallyConnectedPinNames).map(n=>n.map(i=>typeof i=="number"?`pin${i}`:i))}doInitialSourceNameDuplicateComponentRemoval(){if(!this.name)return;let t=this.root;if(this.getSubcircuit().selectAll(`.${this.name}`).filter(r=>r!==this&&r._isNormalComponent&&r.renderPhaseStates?.SourceNameDuplicateComponentRemoval?.initialized).length>0){let r=this._getGlobalPcbPositionBeforeLayout(),o=this._getGlobalSchematicPositionBeforeLayout();t.db.source_failed_to_create_component_error.insert({component_name:this.name,error_type:"source_failed_to_create_component_error",message:`Cannot create component "${this.name}": A component with the same name already exists`,pcb_center:r,schematic_center:o}),this.shouldBeRemoved=!0;let s=[...this.children];for(let a of s)this.remove(a)}}initPorts(t={}){if(this.root?.schematicDisabled)return;let{config:n}=this,i=[],r=this._getSchematicPortArrangement();if(r&&!this._parsedProps.pinLabels){for(let l in r){let u=r[l].pins;if(Array.isArray(u))for(let h of u){let d=_m(h,this._parsedProps.pinLabels);i.push(new ji({pinNumber:d,aliases:t.additionalAliases?.[`pin${d}`]??[]},{originDescription:`schPortArrangement:${l}`}))}}let a=["left","right","top","bottom"],c=1;for(let l of a){let u=r[`${l}Size`];for(let h=0;h<u;h++)i.push(new ji({pinNumber:c++,aliases:t.additionalAliases?.[`pin${c}`]??[]},{originDescription:`schPortArrangement:${l}`}))}}let o=this._parsedProps.pinLabels;if(o)for(let[a,c]of Object.entries(o)){a=a.replace("pin","");let l=i.find(d=>d._parsedProps.pinNumber===Number(a)),u=Array.isArray(c)?c[0]:c,h=Array.isArray(c)?c.slice(1):[];l?(l.externallyAddedAliases.push(u,...h),l.props.name=u):(l=new ji({pinNumber:parseInt(a),name:u,aliases:[...h,...t.additionalAliases?.[`pin${parseInt(a)}`]??[]]},{originDescription:`pinLabels:pin${a}`}),i.push(l))}if(n.schematicSymbolName&&!t.ignoreSymbolPorts){let a=Qn[this._getSchematicSymbolNameOrThrow()];if(!a)return;for(let c of a.ports){let l=kV(c.labels);if(!l)continue;let u=i.find(h=>h._parsedProps.pinNumber===Number(l));if(u)u.schematicSymbolPortDef=c;else{let h=cm(c.labels.concat(t.additionalAliases?.[`pin${l}`]??[]));h&&(h.originDescription=`schematicSymbol:labels[0]:${c.labels[0]}`,h.schematicSymbolPortDef=c,i.push(h))}}this.addAll(i)}if(!this._getSchematicPortArrangement()){let a=this.getPortsFromFootprint(t);for(let c of a)i.some(l=>l.isMatchingAnyOf(c.getNameAndAliases()))||i.push(c)}let s=t.pinCount??this._getPinCount()??0;for(let a=1;a<=s;a++){if(i.find(l=>l._parsedProps.pinNumber===a))continue;if(!r){i.push(new ji({pinNumber:a,aliases:t.additionalAliases?.[`pin${a}`]??[]}));continue}let c=[...r.leftSide?.pins??[],...r.rightSide?.pins??[],...r.topSide?.pins??[],...r.bottomSide?.pins??[]].map(l=>_m(l,this._parsedProps.pinLabels));["leftSize","rightSize","topSize","bottomSize","leftPinCount","rightPinCount","topPinCount","bottomPinCount"].some(l=>l in r)&&(c=Array.from({length:this._getPinCount()},(l,u)=>u+1)),c.includes(a)&&i.push(new ji({pinNumber:a,aliases:t.additionalAliases?.[`pin${a}`]??[]},{originDescription:`notOtherwiseAddedButDeducedFromPinCount:${a}`}))}i.length>0&&this.addAll(i)}_getImpliedFootprintString(){return null}_addChildrenFromStringFootprint(){let{pcbRotation:t,pinLabels:n,pcbPinLabels:i}=this.props,{footprint:r}=this.props;if(r??(r=this._getImpliedFootprintString?.()),!!r&&typeof r=="string"){if(Nh(r)||tM(r)||QI(r))return;let o=ww.string(r).soup(),s=lm({componentName:this.name??this.componentName,componentRotation:t,footprint:r,pinLabels:n,pcbPinLabels:i},o);this.addAll(s)}}get portMap(){return new Proxy({},{get:(t,n)=>{let i=this.children.find(r=>r.componentName==="Port"&&r.isMatchingNameOrAlias(n));if(!i)throw new Error(`There was an issue finding the port "${n.toString()}" inside of a ${this.componentName} component with name: "${this.props.name}". This is a bug in @tscircuit/core`);return i}})}getInstanceForReactElement(t){for(let n of this.reactSubtrees)if(n.element===t)return n.component;return null}doInitialSourceRender(){let t=this.config.sourceFtype;if(!t)return;let{db:n}=this.root,{_parsedProps:i}=this,r=n.source_component.insert({ftype:t,name:this.name,manufacturer_part_number:i.manufacturerPartNumber??i.mfn,supplier_part_numbers:i.supplierPartNumbers});this.source_component_id=r.source_component_id}doInitialSchematicComponentRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root;if(this._invalidPinLabelMessages?.length&&this.root?.db)for(let o of this._invalidPinLabelMessages){let s="pinLabels",a=o.match(/^Invalid pin label:\s*([^=]+)=\s*'([^']+)'/);a&&(s=`pinLabels['${a[2]}']`),this.root.db.source_property_ignored_warning.insert({source_component_id:this.source_component_id,property_name:s,message:o,error_type:"source_property_ignored_warning"})}let{schematicSymbolName:n}=this.config,{_parsedProps:i}=this;i.symbol&&(0,na.isValidElement)(i.symbol)?this._doInitialSchematicComponentRenderWithReactSymbol(i.symbol):n?this._doInitialSchematicComponentRenderWithSymbol():this._getSchematicBoxDimensions()&&this._doInitialSchematicComponentRenderWithSchematicBoxDimensions();let r=this.getSubcircuit()?._getSchematicManualPlacementForComponent(this);if(this.schematic_component_id&&(this.props.schX!==void 0||this.props.schY!==void 0)&&r){if(!this.schematic_component_id)return;let o=u_.parse({type:"schematic_manual_edit_conflict_warning",schematic_manual_edit_conflict_warning_id:`schematic_manual_edit_conflict_${this.source_component_id}`,message:`${this.getString()} has both manual placement and prop coordinates. schX and schY will be used. Remove schX/schY or clear the manual placement.`,schematic_component_id:this.schematic_component_id,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id});t.schematic_manual_edit_conflict_warning.insert(o)}}_getSchematicSymbolDisplayValue(){}_getInternallyConnectedPins(){if(this.internallyConnectedPinNames.length===0)return[];let t=[];for(let n of this.internallyConnectedPinNames){let i=[];for(let r of n)i.push(this.portMap[r]);t.push(i)}return t}_doInitialSchematicComponentRenderWithSymbol(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getSchematicSymbolNameOrThrow(),r=Qn[i],o=this._getGlobalSchematicPositionBeforeLayout();if(r){let s=t.schematic_component.insert({center:o,size:r.size,source_component_id:this.source_component_id,is_box_with_pins:!0,symbol_name:i,symbol_display_value:this._getSchematicSymbolDisplayValue()});this.schematic_component_id=s.schematic_component_id}}_doInitialSchematicComponentRenderWithReactSymbol(t){if(this.root?.schematicDisabled)return;let{db:n}=this.root,i=this._getGlobalSchematicPositionBeforeLayout(),r=n.schematic_component.insert({center:i,size:{width:0,height:0},source_component_id:this.source_component_id,symbol_display_value:this._getSchematicSymbolDisplayValue(),is_box_with_pins:!1});this.schematic_component_id=r.schematic_component_id}_doInitialSchematicComponentRenderWithSchematicBoxDimensions(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getSchematicBoxDimensions(),r={};if(Array.isArray(n.pinLabels))n.pinLabels.forEach((_,y)=>{r[String(y+1)]=_});else for(let[_,y]of Object.entries(n.pinLabels??{}))r[_]=Array.isArray(y)?y[0]:y;let o=this._getGlobalSchematicPositionBeforeLayout(),s=this._getSchematicPortArrangement(),a=t.schematic_component.insert({center:o,rotation:n.schRotation??0,size:i.getSize(),port_arrangement:n3t(s),pin_spacing:n.schPinSpacing??.2,pin_styles:e3t(n.schPinStyle,n.pinLabels),port_labels:r,source_component_id:this.source_component_id}),c=s?.topSide!==void 0||s?.bottomSide!==void 0,l=i?.getSize().width,u=i?.getSize().height,h=t.schematic_text.insert({text:n.manufacturerPartNumber??"",schematic_component_id:a.schematic_component_id,anchor:"left",rotation:0,position:{x:c?o.x+(l??0)/2+.1:o.x-(l??0)/2,y:c?o.y+(u??0)/2+.35:o.y-(u??0)/2-.13},color:"#006464",font_size:.18}),d=t.schematic_text.insert({text:n.name??"",schematic_component_id:a.schematic_component_id,anchor:"left",rotation:0,position:{x:c?o.x+(l??0)/2+.1:o.x-(l??0)/2,y:c?o.y+(u??0)/2+.55:o.y+(u??0)/2+.13},color:"#006464",font_size:.18});this.schematic_component_id=a.schematic_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit(),r=n.layer??"top";if(r!=="top"&&r!=="bottom"){let h=bp.parse({type:"pcb_component_invalid_layer_error",message:`Component cannot be placed on layer '${r}'. Components can only be placed on 'top' or 'bottom' layers.`,source_component_id:this.source_component_id,layer:r,subcircuit_id:i.subcircuit_id??void 0});t.pcb_component_invalid_layer_error.insert(h)}let o=this._computePcbGlobalTransformBeforeLayout(),a=To(o).rotation.angle*180/Math.PI,c=t.pcb_component.insert({center:this._getGlobalPcbPositionBeforeLayout(),width:0,height:0,layer:r==="top"||r==="bottom"?r:"top",rotation:n.pcbRotation??a,source_component_id:this.source_component_id,subcircuit_id:i.subcircuit_id??void 0,do_not_place:n.doNotPlace??!1,obstructs_within_bounds:n.obstructsWithinBounds??!0});if(!(n.footprint??this._getImpliedFootprintString())&&!this.isGroup){let h=t.pcb_missing_footprint_error.insert({message:`No footprint found for component: ${this.getString()}`,source_component_id:`${this.source_component_id}`,error_type:"pcb_missing_footprint_error"});this.pcb_missing_footprint_error_id=h.pcb_missing_footprint_error_id}this.pcb_component_id=c.pcb_component_id;let u=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if((this.props.pcbX!==void 0||this.props.pcbY!==void 0)&&u){let h=d_.parse({type:"pcb_manual_edit_conflict_warning",pcb_manual_edit_conflict_warning_id:`pcb_manual_edit_conflict_${this.source_component_id}`,message:`${this.getString()} has both manual placement and prop coordinates. pcbX and pcbY will be used. Remove pcbX/pcbY or clear the manual placement.`,pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,subcircuit_id:i.subcircuit_id??void 0});t.pcb_manual_edit_conflict_warning.insert(h)}}doInitialPcbComponentSizeCalculation(){if(this.root?.pcbDisabled||!this.pcb_component_id)return;let{db:t}=this.root,{_parsedProps:n}=this,i=mx(this.children);if(i.width===0||i.height===0)return;let r={x:(i.minX+i.maxX)/2,y:(i.minY+i.maxY)/2};t.pcb_component.update(this.pcb_component_id,{center:r,width:i.width,height:i.height})}updatePcbComponentSizeCalculation(){this.doInitialPcbComponentSizeCalculation()}doInitialSchematicComponentSizeCalculation(){if(this.root?.schematicDisabled||!this.schematic_component_id)return;let{db:t}=this.root;if(!t.schematic_component.get(this.schematic_component_id))return;let i=[],r=u=>{for(let h of u){if(h.isSchematicPrimitive&&h.componentName==="SchematicLine"){let d=t.schematic_line.get(h.schematic_line_id);d&&i.push(d)}if(h.isSchematicPrimitive&&h.componentName==="SchematicRect"){let d=t.schematic_rect.get(h.schematic_rect_id);d&&i.push(d)}if(h.isSchematicPrimitive&&h.componentName==="SchematicCircle"){let d=t.schematic_circle.get(h.schematic_circle_id);d&&i.push(d)}if(h.isSchematicPrimitive&&h.componentName==="SchematicArc"){let d=t.schematic_arc.get(h.schematic_arc_id);d&&i.push(d)}if(h.isSchematicPrimitive&&h.componentName==="SchematicText"){let d=t.schematic_text.get(h.schematic_text_id);d&&i.push(d)}h.children&&h.children.length>0&&r(h.children)}};if(r(this.children),i.length===0)return;let o=EV(i),s=Math.abs(o.maxX-o.minX),a=Math.abs(o.maxY-o.minY);if(s===0&&a===0)return;let c=(o.minX+o.maxX)/2,l=(o.minY+o.maxY)/2;t.schematic_component.update(this.schematic_component_id,{center:{x:c,y:l},size:{width:s,height:a}})}updateSchematicComponentSizeCalculation(){this.doInitialSchematicComponentSizeCalculation()}doInitialPcbComponentAnchorAlignment(){K3t(this)}updatePcbComponentAnchorAlignment(){this.doInitialPcbComponentAnchorAlignment()}_renderReactSubtree(t){let n=MV(t);return{element:t,component:n}}doInitialInitializePortsFromChildren(){this.initPorts()}doInitialReactSubtreesRender(){let t=this.props.footprint;(0,na.isValidElement)(t)&&(this.children.some(o=>o.componentName==="Footprint")||this.add(t));let n=this.props.symbol;(0,na.isValidElement)(n)&&(this.children.some(o=>o.componentName==="Symbol")||this.add(n));let i=this.props.cadModel;if((0,na.isValidElement)(i)){this._isCadModelChild=!0;let r=this.children.some(s=>s.componentName==="CadAssembly"),o=this.children.some(s=>s.componentName==="CadModel");!r&&!o&&this.add(i)}}doInitialPcbFootprintStringRender(){Z3t(this,(t,n)=>this._queueAsyncEffect(t,n))}_hasExistingPortExactly(t){return this.children.filter(i=>i.componentName==="Port").some(i=>{let r=t.getNameAndAliases(),o=i.getNameAndAliases();return r.length===o.length&&r.every(s=>o.includes(s))})}add(t){let n;if((0,na.isValidElement)(t)){let i=this._renderReactSubtree(t);this.reactSubtrees.push(i),n=i.component}else n=t;if(n.componentName==="Port"){if(this._hasExistingPortExactly(n))return;let r=this.children.filter(o=>o.componentName==="Port").find(o=>o.isMatchingAnyOf(n.getNameAndAliases()));r&&J3t(`Similar ports added. Port 1: ${r}, Port 2: ${n}`)}super.add(n)}getPortsFromFootprint(t){let{footprint:n}=this.props;if((!n||(0,na.isValidElement)(n))&&(n=this.children.find(r=>r.componentName==="Footprint")),typeof n=="string"){if(Nh(n))return[];if(tM(n))return[];if(QI(n))return[];let r=ww.string(n).soup(),o=[];for(let s of r)if("port_hints"in s&&s.port_hints){let a=cm(s.port_hints,t);if(!a)continue;a.originDescription=`footprint:string:${n}:port_hints[0]:${s.port_hints[0]}`,o.push(a)}return o}if(!(0,na.isValidElement)(n)&&n&&n.componentName==="Footprint"){let r=n,o=1,s=[];for(let a of r.children){if(!a.props.portHints)continue;let c=a.props.portHints;c.some(h=>h.startsWith("pin"))||(c=[...c,`pin${o}`]),o++;let u=cm(c);u&&(u.originDescription=`footprint:${n}`,s.push(u))}return s}let i=[];if(!n){for(let r of this.children)if(r.props.portHints&&r.isPcbPrimitive){let o=cm(r.props.portHints);o&&i.push(o)}}return i}getPortsFromSchematicSymbol(){if(this.root?.schematicDisabled)return[];let{config:t}=this;if(!t.schematicSymbolName)return[];let n=Qn[t.schematicSymbolName];if(!n)return[];let i=[];for(let r of n.ports){let o=cm(r.labels);o&&(o.schematicSymbolPortDef=r,i.push(o))}return i}doInitialCreateNetsFromProps(){this._createNetsFromProps(this._getNetsFromConnectionsProp())}_getNetsFromConnectionsProp(){let{_parsedProps:t}=this,n=[];if(t.connections)for(let[i,r]of Object.entries(t.connections)){let o=Array.isArray(r)?r:[r];for(let s of o)n.push(String(s))}return n}_createNetsFromProps(t){sM(this,t)}_getPcbCircuitJsonBounds(){let{db:t}=this.root;if(!this.pcb_component_id)return super._getPcbCircuitJsonBounds();let n=t.pcb_component.get(this.pcb_component_id);return{center:{x:n.center.x,y:n.center.y},bounds:{left:n.center.x-n.width/2,top:n.center.y-n.height/2,right:n.center.x+n.width/2,bottom:n.center.y+n.height/2},width:n.width,height:n.height}}_getPinCountFromSchematicPortArrangement(){let t=this._getSchematicPortArrangement();if(!t)return 0;if(!NV(t))return(t.leftSize??t.leftPinCount??0)+(t.rightSize??t.rightPinCount??0)+(t.topSize??t.topPinCount??0)+(t.bottomSize??t.bottomPinCount??0);let{leftSide:i,rightSide:r,topSide:o,bottomSide:s}=t;return Math.max(...i?.pins??[],...r?.pins??[],...o?.pins??[],...s?.pins??[])}_getPinCount(){if(this._getSchematicPortArrangement())return this._getPinCountFromSchematicPortArrangement();let n=this.getPortsFromFootprint();if(n.length>0)return n.length;let{pinLabels:i}=this._parsedProps;if(i){if(Array.isArray(i))return i.length;let r=Object.keys(i).map(o=>o.startsWith("pin")?parseInt(o.slice(3)):parseInt(o)).filter(o=>!Number.isNaN(o));return r.length>0?Math.max(...r):Object.keys(i).length}return 0}_getSchematicPortArrangement(){return this._parsedProps.schPinArrangement??this._parsedProps.schPortArrangement}_getSchematicBoxDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;let{_parsedProps:t}=this,n=this._getPinCount(),i=t.schPinSpacing??.2;return d3t({schWidth:t.schWidth,schHeight:t.schHeight,schPinSpacing:i,numericSchPinStyle:_3t(t.schPinStyle,t.pinLabels),pinCount:n,schPortArrangement:this._getSchematicPortArrangement(),pinLabels:t.pinLabels})}getFootprinterString(){return typeof this._parsedProps.footprint=="string"?this._parsedProps.footprint:null}doInitialCadModelRender(){if(this._isCadModelChild||this.props.doNotPlace)return;let{db:t}=this.root,{boardThickness:n=0}=this.root?._getBoard()??{},i=this._parsedProps.cadModel,r=i===void 0?this._asyncFootprintCadModel:i,o=this.getFootprinterString()??this._getImpliedFootprintString();if(!this.pcb_component_id||!r&&!o||r===null)return;let s=this._getPcbCircuitJsonBounds();if(typeof r=="string")throw new Error("String cadModel not yet implemented");let a=Q3t.parse({x:0,y:0,z:typeof r?.rotationOffset=="number"?r.rotationOffset:0,...typeof r?.rotationOffset=="object"?r.rotationOffset??{}:{}}),c=dl.parse({x:0,y:0,z:0,...typeof r?.positionOffset=="object"?r.positionOffset:{}}),l=r&&typeof r=="object"&&"zOffsetFromSurface"in r&&r.zOffsetFromSurface!==void 0?Y.parse(r.zOffsetFromSurface):0,u=this.props.layer==="bottom"?"bottom":"top",h=this._computePcbGlobalTransformBeforeLayout(),_=To(h).rotation.angle*180/Math.PI,y=u==="bottom",g=_+(a.z??0),x=Rl(g),w=t.cad_component.insert({position:{x:s.center.x+c.x,y:s.center.y+c.y,z:(u==="bottom"?-n/2:n/2)+(u==="bottom"?-l:l)+c.z},rotation:{x:a.x,y:a.y+(y?180:0),z:Rl(y?-x:x)},pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,model_stl_url:"stlUrl"in(r??{})?this._addCachebustToModelUrl(r.stlUrl):void 0,model_obj_url:"objUrl"in(r??{})?this._addCachebustToModelUrl(r.objUrl):void 0,model_mtl_url:"mtlUrl"in(r??{})?this._addCachebustToModelUrl(r.mtlUrl):void 0,model_gltf_url:"gltfUrl"in(r??{})?this._addCachebustToModelUrl(r.gltfUrl):void 0,model_glb_url:"glbUrl"in(r??{})?this._addCachebustToModelUrl(r.glbUrl):void 0,model_step_url:"stepUrl"in(r??{})?this._addCachebustToModelUrl(r.stepUrl):void 0,model_wrl_url:"wrlUrl"in(r??{})?this._addCachebustToModelUrl(r.wrlUrl):void 0,model_jscad:"jscad"in(r??{})?r.jscad:void 0,model_unit_to_mm_scale_factor:typeof r?.modelUnitToMmScale=="number"?r.modelUnitToMmScale:void 0,footprinter_string:typeof o=="string"&&!r?o:void 0});this.cad_component_id=w.cad_component_id}_addCachebustToModelUrl(t){if(!t||!t.includes("modelcdn.tscircuit.com"))return t;let n=this.root?.getClientOrigin()??"";return`${t}${t.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(n)}`}_getPartsEngineCacheKey(t,n){return JSON.stringify({ftype:t.ftype,name:t.name,manufacturer_part_number:t.manufacturer_part_number,footprinterString:n})}async _getSupplierPartNumbers(t,n,i){if(this.props.doNotPlace)return{};let r=this.root?.platform?.localCacheEngine,o=this._getPartsEngineCacheKey(n,i);if(r){let c=await r.getItem(o);if(c)try{return JSON.parse(c)}catch{}}let s=await Promise.resolve(t.findPart({sourceComponent:n,footprinterString:i})),a=s==="Not found"?{}:s;if(r)try{await r.setItem(o,JSON.stringify(a))}catch{}return a}doInitialPartsEngineRender(){if(this.props.doNotPlace)return;let t=this.getInheritedProperty("partsEngine");if(!t)return;let{db:n}=this.root,i=n.source_component.get(this.source_component_id);if(!i||i.supplier_part_numbers)return;let r;this.props.footprint&&typeof this.props.footprint=="string"&&(r=this.props.footprint);let o=this._getSupplierPartNumbers(t,i,r);if(!(o instanceof Promise)){n.source_component.update(this.source_component_id,{supplier_part_numbers:o});return}this._queueAsyncEffect("get-supplier-part-numbers",async()=>{this._asyncSupplierPartNumbers=await o,this._markDirty("PartsEngineRender")})}updatePartsEngineRender(){if(this.props.doNotPlace)return;let{db:t}=this.root,n=t.source_component.get(this.source_component_id);if(n&&!n.supplier_part_numbers&&this._asyncSupplierPartNumbers){t.source_component.update(this.source_component_id,{supplier_part_numbers:this._asyncSupplierPartNumbers});return}}doInitialAssignFallbackProps(){let{_parsedProps:t}=this;t.connections&&!this.name&&(this.fallbackUnassignedName=this.getSubcircuit().getNextAvailableName(this))}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}_createTracesFromConnectionsProp(){let{_parsedProps:t}=this;if(t.connections)for(let[n,i]of Object.entries(t.connections)){let r=Array.isArray(i)?i:[i];for(let o of r)this.add(new ko({from:`.${this.name} > .${n}`,to:String(o)}))}}doInitialSourceDesignRuleChecks(){V3t(this)}_getMinimumFlexContainerSize(){return Y3t(this)}_repositionOnPcb(t){return X3t(this,t)}doInitialSilkscreenOverlapAdjustment(){return U3t(this)}isRelativelyPositioned(){return this._parsedProps.pcbX!==void 0||this._parsedProps.pcbY!==void 0}},t5t=({boardAnchorPosition:e,boardAnchorAlignment:t,width:n,height:i})=>{let{x:r,y:o}=e,s=r,a=o;switch(t){case"top_left":s=r+n/2,a=o-i/2;break;case"top_right":s=r-n/2,a=o-i/2;break;case"bottom_left":s=r+n/2,a=o+i/2;break;case"bottom_right":s=r-n/2,a=o+i/2;break;case"top":s=r,a=o-i/2;break;case"bottom":s=r,a=o+i/2;break;case"left":s=r+n/2,a=o;break;case"right":s=r-n/2,a=o;break;case"center":default:break}return{x:s,y:a}},e5t=class{constructor(e,t={}){M(this,"input");M(this,"isRouting",!1);M(this,"solver");M(this,"eventHandlers",{complete:[],error:[],progress:[]});M(this,"cycleCount",0);M(this,"stepDelay");M(this,"timeoutId");this.input=e;let{capacityDepth:n,targetMinCapacity:i,stepDelay:r=0}=t;this.solver=new P$(e,{capacityDepth:n,targetMinCapacity:i,cacheProvider:null}),this.stepDelay=r}start(){this.isRouting||(this.isRouting=!0,this.cycleCount=0,this.runCycleAndQueueNextCycle())}runCycleAndQueueNextCycle(){if(this.isRouting)try{if(this.solver.solved||this.solver.failed){this.solver.failed?this.emitEvent({type:"error",error:new um(this.solver.error||"Routing failed")}):this.emitEvent({type:"complete",traces:this.solver.getOutputSimpleRouteJson().traces||[]}),this.isRouting=!1;return}let e=Date.now(),t=this.solver.iterations;for(;Date.now()-e<250&&!this.solver.failed&&!this.solver.solved;)this.solver.step();let n=(this.solver.iterations-t)/(Date.now()-e)*1e3;this.cycleCount++;let i=this.solver?.preview()||void 0,r=this.solver.progress;this.emitEvent({type:"progress",steps:this.cycleCount,iterationsPerSecond:n,progress:r,phase:this.solver.getCurrentPhase(),debugGraphics:i}),this.stepDelay>0?this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),this.stepDelay):this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),0)}catch(e){this.emitEvent({type:"error",error:e instanceof Error?new um(e.message):new um(String(e))}),this.isRouting=!1}}stop(){this.isRouting&&(this.isRouting=!1,this.timeoutId!==void 0&&(clearTimeout(this.timeoutId),this.timeoutId=void 0))}on(e,t){e==="complete"?this.eventHandlers.complete.push(t):e==="error"?this.eventHandlers.error.push(t):e==="progress"&&this.eventHandlers.progress.push(t)}emitEvent(e){if(e.type==="complete")for(let t of this.eventHandlers.complete)t(e);else if(e.type==="error")for(let t of this.eventHandlers.error)t(e);else if(e.type==="progress")for(let t of this.eventHandlers.progress)t(e)}solveSync(){if(this.solver.solve(),this.solver.failed)throw new um(this.solver.error||"Routing failed");return this.solver.getOutputSimpleRouteJson().traces||[]}},pM=class extends xe{constructor(){super(...arguments);M(this,"matchedPort",null)}get config(){return{componentName:"TraceHint",zodProps:Lz}}doInitialPortMatching(){let{db:t}=this.root,{_parsedProps:n,parent:i}=this;if(!i)return;if(i.componentName==="Trace"){this.renderError(`Port inference inside trace is not yet supported (${this})`);return}if(!i)throw new Error("TraceHint has no parent");if(!n.for){this.renderError(`TraceHint has no for property (${this})`);return}let r=i.selectOne(n.for,{type:"port"});r||this.renderError(`${this} could not find port for selector "${n.for}"`),this.matchedPort=r,r.registerMatch(this)}getPcbRouteHints(){let{_parsedProps:t}=this,n=t.offset?[t.offset]:t.offsets;if(!n)return[];let i=this._computePcbGlobalTransformBeforeLayout();return n.map(r=>({...Ae(i,r),via:r.via,to_layer:r.to_layer,trace_width:r.trace_width}))}doInitialPcbTraceHintRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this;t.pcb_trace_hint.insert({pcb_component_id:this.matchedPort?.pcb_component_id,pcb_port_id:this.matchedPort?.pcb_port_id,route:this.getPcbRouteHints()})}},BV=({circuitJson:e,editEvents:t,manualEditsFile:n})=>{let i={...n,pcb_placements:[...n.pcb_placements??[]]};for(let r of t)if(r.edit_event_type==="edit_pcb_component_location"){let{pcb_component_id:o,new_center:s}=r,a=Re(e).pcb_component.get(o);if(!a)continue;let c=Re(e).source_component.get(a.source_component_id);if(!c)continue;let l=i.pcb_placements?.findIndex(h=>h.selector===c.name),u={selector:c.name,center:s,relative_to:"group_center"};l>=0?i.pcb_placements[l]=u:i.pcb_placements.push(u)}return i},jV=({circuitJson:e,editEvents:t,manualEditsFile:n})=>{let i={...n,schematic_placements:[...n.schematic_placements??[]]};for(let r of t)if(r.edit_event_type==="edit_schematic_component_location"){let{schematic_component_id:o,new_center:s}=r,a=Re(e).schematic_component.get(o);if(!a||!a.source_component_id)continue;let c=Re(e).source_component.get(a.source_component_id);if(!c)continue;let l=i.schematic_placements?.findIndex(h=>h.selector===c.name),u={selector:c.name,center:s,relative_to:"group_center"};l>=0?i.schematic_placements[l]=u:i.schematic_placements.push(u)}return i},n5t=({circuitJson:e,editEvents:t,manualEditsFile:n})=>{let i=t.filter(s=>s.edit_event_type==="edit_schematic_component_location"),r=t.filter(s=>s.edit_event_type==="edit_pcb_component_location"),o=n;return i.length>0&&(o=jV({circuitJson:e,editEvents:i,manualEditsFile:o})),r.length>0&&(o=BV({circuitJson:e,editEvents:r,manualEditsFile:o})),o},i5t=(e,t)=>{if(Re(e).pcb_trace_hint.get(t.pcb_trace_hint_id))e=e.map(i=>i.pcb_trace_hint_id===t.pcb_trace_hint_id?{...i,route:t.route}:i);else{let i=Re(e).pcb_port.get(t.pcb_port_id);e=e.filter(r=>!(r.type==="pcb_trace_hint"&&r.pcb_port_id===t.pcb_port_id)).concat([{type:"pcb_trace_hint",pcb_trace_hint_id:t.pcb_trace_hint_id,route:t.route,pcb_port_id:t.pcb_port_id,pcb_component_id:i?.pcb_component_id}])}return e},r5t=({circuitJson:e,editEvents:t})=>{e=JSON.parse(JSON.stringify(e));for(let n of t)if(n.edit_event_type==="edit_pcb_component_location"){let i=e.find(o=>o.type==="pcb_component"&&o.pcb_component_id===n.pcb_component_id);if((!i||i.center.x!==n.new_center.x||i.center.y!==n.new_center.y)&&n.original_center){let o=vn(n.new_center.x-n.original_center.x,n.new_center.y-n.original_center.y);e=e.map(s=>s.pcb_component_id!==n.pcb_component_id?s:y4(s,o))}}else n.edit_event_type==="edit_schematic_component_location"?e=e.map(i=>i.type==="schematic_component"&&i.schematic_component_id===n.schematic_component_id?{...i,center:n.new_center}:i):n.edit_event_type==="edit_pcb_trace_hint"&&(e=i5t(e,n));return e},YV=(e,t)=>{let n=e.source_group.list(),i=[],r=o=>{let s=n.filter(a=>a.parent_subcircuit_id===o);for(let a of s)a.subcircuit_id&&(i.push(a.subcircuit_id),r(a.subcircuit_id))};return r(t),i},eM=({db:e,circuitJson:t,subcircuit_id:n,minTraceWidth:i=.1})=>{if(!e&&t&&(e=Re(t)),!e)throw new Error("db or circuitJson is required");let r=e.pcb_trace_hint.list(),o=n?new Set([n]):null;if(n){let N=YV(e,n);for(let E of N)o.add(E)}let s=(t??e.toArray()).filter(N=>!n||"subcircuit_id"in N&&o.has(N.subcircuit_id)),a=e.pcb_board.list()[0];e=Re(s);let c=si(s),l=lM([...e.pcb_component.list(),...e.pcb_smtpad.list(),...e.pcb_plated_hole.list(),...e.pcb_hole.list(),...e.pcb_via.list(),...e.pcb_cutout.list()].filter(N=>!n||o?.has(N.subcircuit_id)),c);for(let N of l){let E=N.connectedTo.flatMap(A=>c.getIdsConnectedToNet(A));N.connectedTo.push(...E)}let u=l.flatMap(N=>[{x:N.center.x-N.width/2,y:N.center.y-N.height/2},{x:N.center.x+N.width/2,y:N.center.y+N.height/2}]).concat(a?.outline??[]),h;if(a&&!a.outline?h={minX:a.center.x-a.width/2,maxX:a.center.x+a.width/2,minY:a.center.y-a.height/2,maxY:a.center.y+a.height/2}:h={minX:Math.min(...u.map(N=>N.x))-1,maxX:Math.max(...u.map(N=>N.x))+1,minY:Math.min(...u.map(N=>N.y))-1,maxY:Math.max(...u.map(N=>N.y))+1},n){let N=e.pcb_group.getWhere({subcircuit_id:n});if(N?.width&&N.height){let E={minX:N.center.x-N.width/2,maxX:N.center.x+N.width/2,minY:N.center.y-N.height/2,maxY:N.center.y+N.height/2};h={minX:Math.min(h.minX,E.minX),maxX:Math.max(h.maxX,E.maxX),minY:Math.min(h.minY,E.minY),maxY:Math.max(h.maxY,E.maxY)}}}let d=new Set(e.pcb_trace.list().map(N=>N.source_trace_id).filter(N=>!!N)),_=e.source_trace.list().filter(N=>!d.has(N.source_trace_id)).map(N=>{let E=N.connected_source_port_ids.map(U=>{let tt=e.source_port.get(U),J=e.pcb_port.getWhere({source_port_id:U});return{...tt,...J}});if(E.length<2)return null;let[A,O]=E,$=A.layers?.[0]??"top",B=O.layers?.[0]??"top",H=r.filter(U=>U.pcb_port_id===A.pcb_port_id||U.pcb_port_id===O.pcb_port_id),X=[];for(let U of H){let J=e.pcb_port.get(U.pcb_port_id)?.layers?.[0]??"top";for(let V of U.route)X.push({x:V.x,y:V.y,layer:J})}return{name:N.source_trace_id??c.getNetConnectedToId(N.source_trace_id)??"",source_trace_id:N.source_trace_id,width:N.min_trace_thickness,pointsToConnect:[{x:A.x,y:A.y,layer:$,pointId:A.pcb_port_id,pcb_port_id:A.pcb_port_id},...X,{x:O.x,y:O.y,layer:B,pointId:O.pcb_port_id,pcb_port_id:O.pcb_port_id}]}}).filter(N=>N!==null),y=new Map(_.map(N=>[N.source_trace_id,N])),g=e.source_net.list().filter(N=>!n||o?.has(N.subcircuit_id)),x=[];for(let N of g){let E=e.source_trace.list().filter(A=>A.connected_source_net_ids?.includes(N.source_net_id));x.push({name:N.source_net_id??c.getNetConnectedToId(N.source_net_id),pointsToConnect:E.flatMap(A=>e.pcb_port.list().filter($=>A.connected_source_port_ids.includes($.source_port_id)).map($=>({x:$.x,y:$.y,layer:$.layers?.[0]??"top",pointId:$.pcb_port_id,pcb_port_id:$.pcb_port_id})))})}let w=e.pcb_breakout_point.list().filter(N=>!n||o?.has(N.subcircuit_id)),S=[],C=new Map;for(let N of w){let E={x:N.x,y:N.y,layer:"top"};if(N.source_trace_id){let A=y.get(N.source_trace_id)??C.get(N.source_trace_id);if(A)A.pointsToConnect.push(E);else{let O={name:N.source_trace_id,source_trace_id:N.source_trace_id,pointsToConnect:[E]};S.push(O),C.set(N.source_trace_id,O)}}else if(N.source_net_id){let A=x.find(O=>O.name===N.source_net_id);A?A.pointsToConnect.push(E):S.push({name:N.source_net_id,pointsToConnect:[E]})}else if(N.source_port_id){let A=e.pcb_port.getWhere({source_port_id:N.source_port_id});A&&S.push({name:N.source_port_id,source_trace_id:void 0,pointsToConnect:[{x:A.x,y:A.y,layer:A.layers?.[0]??"top",pointId:A.pcb_port_id,pcb_port_id:A.pcb_port_id},E]})}}let I=[..._,...x,...S],k=new Map;for(let N of I)for(let E of N.pointsToConnect)E.pointId&&k.set(E.pointId,N);let P=e.pcb_trace.list().filter(N=>!n||o?.has(N.subcircuit_id));for(let N of P){let E=new Set;for(let $ of N.route)$.start_pcb_port_id&&E.add($.start_pcb_port_id),$.end_pcb_port_id&&E.add($.end_pcb_port_id);if(E.size<2)continue;let A=E.values().next().value;if(!A)continue;let O=k.get(A);O&&[...E].every($=>k.get($)===O)&&(O.externallyConnectedPointIds??(O.externallyConnectedPointIds=[]),O.externallyConnectedPointIds.push([...E]))}return{simpleRouteJson:{bounds:h,obstacles:l,connections:I,layerCount:a?.num_layers??2,minTraceWidth:i,outline:a?.outline?.map(N=>({...N}))},connMap:c}},o5t=e=>{let t={};if(!e)return t;for(let i of ea)t[i]=0;let n=new Map;for(let i of e){let[,,r,o]=i.type.split(":");if(o==="start"){n.set(`${r}:${i.renderId}`,i);continue}if(o==="end"){let s=n.get(`${r}:${i.renderId}`);if(s){let a=i.createdAt-s.createdAt;t[r]=(t[r]||0)+a}}}return t},s5t=e=>{let t=e.map(c=>[...new Set(c)]),n=t.map(()=>[]),i=t.map(()=>null);for(let c=0;c<t.length;c++)for(let l of t[c])if(/^\d+$/.test(l)){i[c]=Number.parseInt(l);break}let r=0,o=new Set;for(let c=0;c<i.length;c++){let l=i[c];if(l===null||l<1)continue;if(!o.has(l)){o.add(l),n[c].push(`pin${l}`),r=Math.max(r,l);continue}let u=0;for(let h of n[c])h.startsWith(`pin${l}_alt`)&&u++;n[c].push(`pin${l}_alt${u+1}`)}for(let c=0;c<n.length;c++)n[c][0]?.includes("_alt")&&(r++,n[c].unshift(`pin${r}`));for(let c=0;c<n.length;c++)n[c].length===0&&(r++,n[c].push(`pin${r}`));let s={};for(let c of t)for(let l of c)/^\d+$/.test(l)||(s[l]=(s[l]??0)+1);let a={};for(let c=0;c<t.length;c++){let l=t[c];for(let u of l)/^\d+$/.test(u)||(s[u]===1?n[c].push(u):(a[u]=(a[u]??0)+1,n[c].push(`${u}${a[u]}`)))}return n};function hM({db:e,schematicComponentId:t,deltaX:n,deltaY:i}){let r=e.schematic_rect.list({schematic_component_id:t});for(let c of r)c.center.x+=n,c.center.y+=i;let o=e.schematic_line.list({schematic_component_id:t});for(let c of o)c.x1+=n,c.y1+=i,c.x2+=n,c.y2+=i;let s=e.schematic_circle.list({schematic_component_id:t});for(let c of s)c.center.x+=n,c.center.y+=i;let a=e.schematic_arc.list({schematic_component_id:t});for(let c of a)c.center.x+=n,c.center.y+=i}var cV=(0,XV.default)("Group_doInitialSchematicLayoutMatchAdapt");function a5t(e){let{db:t}=e.root,n=uf(t.toArray(),{source_group_id:e.source_group_id}),i=G4(n);cV.enabled&&global.debugGraphics?.push(cc(i,{title:`floatingBpcGraph-${e.name}`}));let r=G4(n),o={boxes:r.boxes,pins:r.pins.map(c=>({...c,color:c.color.replace("not_connected","normal")}))},{result:s}=QB([{variantName:"default",floatingGraph:r},{variantName:"noNotConnected",floatingGraph:o}],{singletonKeys:["vcc/2","gnd/2"],centerPinColors:["netlabel_center","component_center"],floatingBoxIdsWithMutablePinOffsets:new Set(r.boxes.filter(c=>r.pins.filter(h=>h.boxId===c.boxId).filter(h=>!h.color.includes("center")).length<=2).map(c=>c.boxId)),corpus:{}});cV.enabled&&global.debugGraphics?.push(cc(s,{title:`laidOutBpcGraph-${e.name}`}));let a=e._getGlobalSchematicPositionBeforeLayout();for(let c of s.boxes){if(!c.center)continue;let l=t.schematic_component.get(c.boxId);if(l){let h={x:c.center.x+a.x,y:c.center.y+a.y},d=t.schematic_port.list({schematic_component_id:l.schematic_component_id}),_=t.schematic_text.list({schematic_component_id:l.schematic_component_id}),y={x:h.x-l.center.x,y:h.y-l.center.y};for(let g of d)g.center.x+=y.x,g.center.y+=y.y;for(let g of _)g.position.x+=y.x,g.position.y+=y.y;hM({db:t,schematicComponentId:l.schematic_component_id,deltaX:y.x,deltaY:y.y}),l.center=h;continue}let u=t.schematic_net_label.get(c.boxId);if(u){let h=s.pins.find(_=>_.boxId===c.boxId&&_.color==="netlabel_center");if(!h)throw new Error(`No pin found for net label: ${c.boxId}`);let d={x:c.center.x+a.x,y:c.center.y+a.y};u.center=d,u.anchor_position={x:d.x+h.offset.x,y:d.y+h.offset.y};continue}console.error(`No schematic element found for box: ${c.boxId}. This is a bug in the matchAdapt binding with @tscircuit/core`)}}var he=(0,VV.default)("Group_doInitialSchematicLayoutMatchpack");function lV(e){switch(e){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:return"y+"}}function uV(e,t){let n=["right","up","left","down"],i=n.indexOf(e);if(i===-1)return e;let r=Math.round(t/90),o=(i+r)%4;return n[o<0?o+4:o]}function c5t(e,t,n){let i={chipMap:{},chipPinMap:{},netMap:{},pinStrongConnMap:{},netConnMap:{},chipGap:.6,decouplingCapsGap:.4,partitionGap:1.2};he(`[${n.name}] Processing ${e.childNodes.length} child nodes for input problem`),e.childNodes.forEach((o,s)=>{if(he(`[${n.name}] Processing child ${s}: nodeType=${o.nodeType}`),o.nodeType==="component"?he(`[${n.name}] - Component: ${o.sourceComponent?.name}`):o.nodeType==="group"&&he(`[${n.name}] - Group: ${o.sourceGroup?.name}`),o.nodeType==="component"&&o.sourceComponent){let a=o.sourceComponent.name||`chip_${s}`,c=t.schematic_component.getWhere({source_component_id:o.sourceComponent.source_component_id});if(!c)return;let l=n.children.find(S=>S.source_component_id===o.sourceComponent?.source_component_id),u=[0,90,180,270];l?._parsedProps?.schOrientation&&(u=[0]),l?._parsedProps?.schRotation!==void 0&&(u=[0]),l?._parsedProps?.facingDirection&&(u=[0]),l?._parsedProps?.schFacingDirection&&(u=[0]),l?.componentName==="Chip"&&(u=[0]);let h=l?._parsedProps?.schMarginLeft??l?._parsedProps?.schMarginX??0,d=l?._parsedProps?.schMarginRight??l?._parsedProps?.schMarginX??0,_=l?._parsedProps?.schMarginTop??l?._parsedProps?.schMarginY??0,y=l?._parsedProps?.schMarginBottom??l?._parsedProps?.schMarginY??0;l?.config.shouldRenderAsSchematicBox&&(_+=.4,y+=.4);let g=(d-h)/2,x=(_-y)/2;i.chipMap[a]={chipId:a,pins:[],size:{x:(c.size?.width||1)+h+d,y:(c.size?.height||1)+_+y},availableRotations:u};let w=t.schematic_port.list({schematic_component_id:c.schematic_component_id});for(let S of w){let C=t.source_port.get(S.source_port_id);if(!C)continue;let I=`${a}.${C.pin_number||C.name||S.schematic_port_id}`;i.chipMap[a].pins.push(I);let k=lV(S.facing_direction);i.chipPinMap[I]={pinId:I,offset:{x:(S.center?.x||0)-(c.center.x||0)+g,y:(S.center?.y||0)-(c.center.y||0)+x},side:k}}}else if(o.nodeType==="group"&&o.sourceGroup){let a=o.sourceGroup.name||`group_${s}`;he(`[${n.name}] Processing nested group: ${a}`);let c=t.schematic_group?.getWhere?.({source_group_id:o.sourceGroup.source_group_id}),l=n.children.find(u=>u.source_group_id===o.sourceGroup?.source_group_id);if(he(`[${n.name}] Found schematic_group for ${a}:`,c),c){he(`[${n.name}] Treating group ${a} as composite chip`);let u=t.schematic_component.list({schematic_group_id:c.schematic_group_id});he(`[${n.name}] Group ${a} has ${u.length} components:`,u.map(A=>A.source_component_id));let h=1/0,d=-1/0,_=1/0,y=-1/0,g=!1;for(let A of u)if(A.center&&A.size){g=!0;let O=A.size.width/2,$=A.size.height/2;h=Math.min(h,A.center.x-O),d=Math.max(d,A.center.x+O),_=Math.min(_,A.center.y-$),y=Math.max(y,A.center.y+$)}let x=l?._parsedProps?.schMarginLeft??l?._parsedProps?.schMarginX??0,w=l?._parsedProps?.schMarginRight??l?._parsedProps?.schMarginX??0,S=l?._parsedProps?.schMarginTop??l?._parsedProps?.schMarginY??0,C=l?._parsedProps?.schMarginBottom??l?._parsedProps?.schMarginY??0,I=(w-x)/2,k=(S-C)/2,P=(g?d-h:2)+x+w,N=(g?y-_:2)+S+C;he(`[${n.name}] Group ${a} computed size: ${P} x ${N}`);let E=[];for(let A of u){let O=t.schematic_port.list({schematic_component_id:A.schematic_component_id});for(let $ of O){let B=t.source_port.get($.source_port_id);if(!B)continue;let H=`${a}.${B.pin_number||B.name||$.schematic_port_id}`;E.push(H);let X=c.center||{x:0,y:0},U=lV($.facing_direction);i.chipPinMap[H]={pinId:H,offset:{x:($.center?.x||0)-X.x+I,y:($.center?.y||0)-X.y+k},side:U}}}he(`[${n.name}] Group ${a} has ${E.length} pins:`,E),i.chipMap[a]={chipId:a,pins:E,size:{x:P,y:N}},he(`[${n.name}] Added group ${a} to chipMap`)}else he(`[${n.name}] Warning: No schematic_group found for group ${a}`)}}),he(`[${n.name}] Creating connections using connectivity keys`);let r=new Map;for(let[o,s]of Object.entries(i.chipMap))for(let a of s.pins){let c=a.split(".").pop(),l=e.childNodes.find(u=>u.nodeType==="component"&&u.sourceComponent?u.sourceComponent.name===o:u.nodeType==="group"&&u.sourceGroup?`group_${e.childNodes.indexOf(u)}`===o:!1);if(l?.nodeType==="group"&&l.sourceGroup){let u=t.schematic_group?.getWhere?.({source_group_id:l.sourceGroup.source_group_id});if(u){let h=t.schematic_component.list({schematic_group_id:u.schematic_group_id});for(let d of h){let _=t.source_port.list({source_component_id:d.source_component_id});for(let y of _){let g=y.pin_number||y.name;if(String(g)===String(c))if(y.subcircuit_connectivity_map_key){let x=y.subcircuit_connectivity_map_key;r.has(x)||r.set(x,[]),r.get(x).push(a),he(`[${n.name}] \u2713 Pin ${a} has connectivity key: ${x}`)}else he(`[${n.name}] Pin ${a} has no connectivity key`)}}}}else if(l?.nodeType==="component"&&l.sourceComponent){let u=t.source_port.list({source_component_id:l.sourceComponent.source_component_id});for(let h of u){let d=h.pin_number||h.name;if(String(d)===String(c)&&h.subcircuit_connectivity_map_key){let _=h.subcircuit_connectivity_map_key;r.has(_)||r.set(_,[]),r.get(_).push(a),he(`[${n.name}] Pin ${a} has connectivity key: ${_}`)}}}}he(`[${n.name}] Found ${r.size} connectivity groups:`,Array.from(r.entries()).map(([o,s])=>({key:o,pins:s})));for(let[o,s]of r)if(s.length>=2){let a=t.source_trace.list().filter(u=>u.subcircuit_connectivity_map_key===o),c=a.some(u=>u.connected_source_net_ids&&u.connected_source_net_ids.length>0),l=a.some(u=>u.connected_source_port_ids&&u.connected_source_port_ids.length>=2);if(he(`[${n.name}] Connectivity ${o}: hasNetConnections=${c}, hasDirectConnections=${l}`),l){for(let u of a)if(u.connected_source_port_ids&&u.connected_source_port_ids.length>=2){let h=[];for(let d of u.connected_source_port_ids)for(let _ of s){let y=_.split(".").pop(),g=t.source_port.get(d);if(g&&String(g.pin_number||g.name)===String(y)){let x=_.split(".")[0],w=e.childNodes.find(S=>S.nodeType==="component"&&S.sourceComponent?S.sourceComponent.name===x:S.nodeType==="group"&&S.sourceGroup?`group_${e.childNodes.indexOf(S)}`===x:!1);w?.nodeType==="component"&&w.sourceComponent&&t.source_port.list({source_component_id:w.sourceComponent.source_component_id}).some(C=>C.source_port_id===d)&&h.push(_)}}for(let d=0;d<h.length;d++)for(let _=d+1;_<h.length;_++){let y=h[d],g=h[_];i.pinStrongConnMap[`${y}-${g}`]=!0,i.pinStrongConnMap[`${g}-${y}`]=!0,he(`[${n.name}] Created strong connection: ${y} <-> ${g}`)}}}if(c){let u=t.source_net.getWhere({subcircuit_connectivity_map_key:o}),h=u?.is_ground??!1,d=u?.is_power??!1;i.netMap[o]={netId:o,isGround:h,isPositiveVoltageSource:d};for(let _ of s)i.netConnMap[`${_}-${o}`]=!0;he(`[${n.name}] Created net ${o} with ${s.length} pins:`,s)}}return i}function l5t(e){let{db:t}=e.root,n=Up(t.toArray(),{source_group_id:e.source_group_id});if(he(`[${e.name}] Starting matchpack layout with ${n.childNodes.length} children`),he(`[${e.name}] Tree structure:`,JSON.stringify(n,null,2)),n.childNodes.length<=1){he(`[${e.name}] Only ${n.childNodes.length} children, skipping layout`);return}he("Converting circuit tree to InputProblem...");let i=c5t(n,t,e);he.enabled&&e.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`matchpack-input-problem-${e.name}`,content:JSON.stringify(i,null,2)});let r=new iY(i);if(he("Starting LayoutPipelineSolver..."),he.enabled&&global.debugGraphics){let c=r.visualize();global.debugGraphics.push({...c,title:`matchpack-initial-${e.name}`})}if(r.solve(),he(`Solver completed in ${r.iterations} iterations`),he(`Solved: ${r.solved}, Failed: ${r.failed}`),r.failed)throw he(`Solver failed with error: ${r.error}`),new Error(`Matchpack layout solver failed: ${r.error}`);let o=r.getOutputLayout();if(he("OutputLayout:",JSON.stringify(o,null,2)),he("Solver completed successfully:",!r.failed),he.enabled&&global.debugGraphics){let c=r.visualize();global.debugGraphics.push({...c,title:`matchpack-final-${e.name}`})}let s=r.checkForOverlaps(o);if(s.length>0){he(`Warning: Found ${s.length} overlapping components:`);for(let c of s)he(` ${c.chip1} overlaps ${c.chip2} (area: ${c.overlapArea})`)}let a=e._getGlobalSchematicPositionBeforeLayout();he(`Group offset: x=${a.x}, y=${a.y}`),he(`Applying layout results for ${Object.keys(o.chipPlacements).length} chip placements`);for(let[c,l]of Object.entries(o.chipPlacements)){he(`Processing placement for chip: ${c} at (${l.x}, ${l.y})`);let u=n.childNodes.find(d=>{if(d.nodeType==="component"&&d.sourceComponent){let _=d.sourceComponent.name===c;return he(` Checking component ${d.sourceComponent.name}: matches=${_}`),_}if(d.nodeType==="group"&&d.sourceGroup){let _=d.sourceGroup.name,y=`group_${n.childNodes.indexOf(d)}`,g=y===c;return he(` Checking group ${_} (expected chipId: ${y}): matches=${g}`),g}return!1});if(!u){he(`Warning: No tree node found for chip: ${c}`),he("Available tree nodes:",n.childNodes.map((d,_)=>({type:d.nodeType,name:d.nodeType==="component"?d.sourceComponent?.name:d.sourceGroup?.name,expectedChipId:d.nodeType==="group"?`group_${_}`:d.sourceComponent?.name})));continue}let h={x:l.x+a.x,y:l.y+a.y};if(u.nodeType==="component"&&u.sourceComponent){let d=t.schematic_component.getWhere({source_component_id:u.sourceComponent.source_component_id});if(d){he(`Moving component ${c} to (${h.x}, ${h.y})`);let _=t.schematic_port.list({schematic_component_id:d.schematic_component_id}),y=t.schematic_text.list({schematic_component_id:d.schematic_component_id}),g={x:h.x-d.center.x,y:h.y-d.center.y};for(let x of _)x.center.x+=g.x,x.center.y+=g.y;for(let x of y)x.position.x+=g.x,x.position.y+=g.y;if(hM({db:t,schematicComponentId:d.schematic_component_id,deltaX:g.x,deltaY:g.y}),d.center=h,l.ccwRotationDegrees!==0){he(`Component ${c} has rotation: ${l.ccwRotationDegrees}\xB0`);let x=l.ccwRotationDegrees*Math.PI/180,w=Math.cos(x),S=Math.sin(x);for(let C of _){let I=C.center.x-h.x,k=C.center.y-h.y,P=I*w-k*S,N=I*S+k*w;C.center.x=h.x+P,C.center.y=h.y+N;let E=C.facing_direction||"right";C.facing_direction=uV(E,l.ccwRotationDegrees),C.side_of_component=(C.facing_direction==="up"?"top":C.facing_direction==="down"?"bottom":C.facing_direction)||C.side_of_component}for(let C of y){let I=C.position.x-h.x,k=C.position.y-h.y,P=I*w-k*S,N=I*S+k*w;C.position.x=h.x+P,C.position.y=h.y+N}if(d.symbol_name){let C=d.symbol_name.match(/_(right|left|up|down)$/);C&&(d.symbol_name=d.symbol_name.replace(C[0],`_${uV(C[1],l.ccwRotationDegrees)}`))}}}}else if(u.nodeType==="group"&&u.sourceGroup){let d=t.schematic_group?.getWhere?.({source_group_id:u.sourceGroup.source_group_id});if(d){he(`Moving group ${c} to (${h.x}, ${h.y}) from (${d.center?.x}, ${d.center?.y})`);let _=t.schematic_component.list({schematic_group_id:d.schematic_group_id});he(`Group ${c} has ${_.length} components to move`);let y=d.center||{x:0,y:0},g={x:h.x-y.x,y:h.y-y.y};he(`Position delta for group ${c}: (${g.x}, ${g.y})`);for(let x of _)if(x.center){let w={...x.center};x.center.x+=g.x,x.center.y+=g.y,he(`Moved component ${x.source_component_id} from (${w.x}, ${w.y}) to (${x.center.x}, ${x.center.y})`);let S=t.schematic_port.list({schematic_component_id:x.schematic_component_id}),C=t.schematic_text.list({schematic_component_id:x.schematic_component_id});for(let I of S)I.center&&(I.center.x+=g.x,I.center.y+=g.y);for(let I of C)I.position&&(I.position.x+=g.x,I.position.y+=g.y)}d.center=h,he(`Updated group ${c} center to (${h.x}, ${h.y})`)}}}he("Matchpack layout completed successfully")}function u5t(e){if(!e.isSubcircuit)return;let{db:t}=e.root,n=e.selectAll("trace"),i=new zp({});i.addConnections(n.map(a=>{let c=t.source_trace.get(a.source_trace_id);return c?[c.source_trace_id,...c.connected_source_port_ids,...c.connected_source_net_ids]:null}).filter(a=>a!==null));let{name:r}=e._parsedProps;for(let a of n){if(!a.source_trace_id)continue;let c=i.getNetConnectedToId(a.source_trace_id);c&&(a.subcircuit_connectivity_map_key=`${r??`unnamedsubcircuit${e._renderId}`}_${c}`,t.source_trace.update(a.source_trace_id,{subcircuit_connectivity_map_key:a.subcircuit_connectivity_map_key}))}let o=new Set;for(let a of n){if(!a.source_trace_id)continue;let c=t.source_trace.get(a.source_trace_id);if(c)for(let l of c.connected_source_port_ids)o.add(l)}for(let a of o){let c=i.getNetConnectedToId(a);if(!c)continue;let l=`${r??`unnamedsubcircuit${e._renderId}`}_${c}`;t.source_port.update(a,{subcircuit_connectivity_map_key:l})}let s=new Set;for(let a of n){if(!a.source_trace_id)continue;let c=t.source_trace.get(a.source_trace_id);if(c)for(let l of c.connected_source_net_ids)s.add(l)}for(let a of s){let c=i.getNetConnectedToId(a);if(!c)continue;let l=`${r??`unnamedsubcircuit${e._renderId}`}_${c}`;t.source_net.update(a,{subcircuit_connectivity_map_key:l})}}function p5t(e){let{db:t}=e.root,n=e._parsedProps,i=e.children.filter(k=>{let P=k._parsedProps?.schX!==void 0||k._parsedProps?.schY!==void 0;return k.schematic_component_id&&!P});if(i.length===0)return;let r=0,o=0;for(let k of i){let P=t.schematic_component.get(k.schematic_component_id);P?.size&&(r=Math.max(r,P.size.width),o=Math.max(o,P.size.height))}r===0&&i.length>0&&(r=1),o===0&&i.length>0&&(o=1);let s=n.gridCols,a,c=n.gridGap,l=n.gridRowGap,u=n.gridColumnGap;n.schLayout?.grid&&(s=n.schLayout.grid.cols??s,a=n.schLayout.grid.rows,c=n.schLayout.gridGap??c,l=n.schLayout.gridRowGap??l,u=n.schLayout.gridColumnGap??u);let h,d;s!==void 0&&a!==void 0?(h=s,d=a):s!==void 0?(h=s,d=Math.ceil(i.length/h)):a!==void 0?(d=a,h=Math.ceil(i.length/d)):(h=Math.ceil(Math.sqrt(i.length)),d=Math.ceil(i.length/h)),h===0&&i.length>0&&(h=1),d===0&&i.length>0&&(d=i.length);let _,y,g=k=>{if(k!==void 0)return typeof k=="number"?k:D.parse(k)};if(l!==void 0||u!==void 0){let k=typeof c=="object"&&c!==null?c.x:c,P=typeof c=="object"&&c!==null?c.y:c;_=g(u??k)??1,y=g(l??P)??1}else if(typeof c=="number")_=c,y=c;else if(typeof c=="string"){let k=D.parse(c);_=k,y=k}else if(typeof c=="object"&&c!==null){let k=c.x,P=c.y;_=typeof k=="number"?k:D.parse(k??"0mm"),y=typeof P=="number"?P:D.parse(P??"0mm")}else _=1,y=1;let x=h*r+Math.max(0,h-1)*_,w=d*o+Math.max(0,d-1)*y,S=e._getGlobalSchematicPositionBeforeLayout(),C=S.x-x/2+r/2,I=S.y+w/2-o/2;for(let k=0;k<i.length;k++){let P=i[k];if(!P.schematic_component_id)continue;let N=Math.floor(k/h),E=k%h;if(N>=d||E>=h){console.warn(`Schematic grid layout: Child ${P.getString()} at index ${k} (row ${N}, col ${E}) exceeds specified grid dimensions (${d}x${h}). Skipping placement.`);continue}let A=C+E*(r+_),O=I-N*(o+y),$=t.schematic_component.get(P.schematic_component_id);if($){let B=$.center,H={x:A,y:O};t.schematic_component.update(P.schematic_component_id,{center:H});let X=H.x-B.x,U=H.y-B.y,tt=t.schematic_port.list({schematic_component_id:P.schematic_component_id});for(let V of tt)t.schematic_port.update(V.schematic_port_id,{center:{x:V.center.x+X,y:V.center.y+U}});let J=t.schematic_text.list({schematic_component_id:P.schematic_component_id});for(let V of J)t.schematic_text.update(V.schematic_text_id,{position:{x:V.position.x+X,y:V.position.y+U}});hM({db:t,schematicComponentId:P.schematic_component_id,deltaX:X,deltaY:U})}}e.schematic_group_id&&t.schematic_group.update(e.schematic_group_id,{width:x,height:w,center:S})}var pV=(e,t)=>{let{sourceComponent:n,sourceGroup:i}=t;if(t.nodeType==="component"){let r=e.schematic_component.getWhere({source_component_id:n?.source_component_id});return r?.size?{width:r.size.width,height:r.size.height}:null}if(t.nodeType==="group"){let r=e.schematic_group.getWhere({source_group_id:i?.source_group_id});if(r?.width&&r?.height)return{width:r.width,height:r.height};let o=e.schematic_component.list({schematic_group_id:r?.schematic_group_id}),s=1/0,a=-1/0,c=1/0,l=-1/0;for(let d of o)if(d.center&&d.size){let _=d.size.width/2,y=d.size.height/2;s=Math.min(s,d.center.x-_),a=Math.max(a,d.center.x+_),c=Math.min(c,d.center.y-y),l=Math.max(l,d.center.y+y)}let u=a-s,h=l-c;return{width:u,height:h}}return null},h5t=e=>{let{db:t}=e.root,n=e._parsedProps,i=Up(t.toArray(),{source_group_id:e.source_group_id}),r=n.schJustifyContent??n.justifyContent,o=n.schAlignItems??n.alignItems,s=n.schFlexGap??n.schGap??n.gap,a=n.schFlexDirection??"row",c={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"space-between","space-between":"space-between","space-around":"space-around","space-evenly":"space-evenly",center:"center"}[r??"space-between"],l={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"stretch",center:"center"}[o??"center"];if(!c)throw new Error(`Invalid justifyContent value: "${r}"`);if(!l)throw new Error(`Invalid alignItems value: "${o}"`);let u=0,h=0;typeof s=="object"?(u=s.y??0,h=s.x??0):typeof s=="number"?(u=s,h=s):typeof s=="string"&&(u=D.parse(s),h=D.parse(s));let d,_=n.width??n.schWidth??void 0,y=n.height??n.schHeight??void 0;(_===void 0||y===void 0)&&(d=Vg(i.childNodes.map(I=>pV(t,I)).filter(I=>I!==null),{alignItems:l,justifyContent:c,direction:a,rowGap:u,columnGap:h}),_=d.width,y=d.height);let x=new Gb(_,y,{alignItems:l,justifyContent:c,direction:a,rowGap:u,columnGap:h});for(let I of i.childNodes){let k=pV(t,I);x.addChild({metadata:I,width:k?.width??0,height:k?.height??0,flexBasis:k?a==="row"?k.width:k.height:void 0})}x.build();let w={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let I of x.children)w.minX=Math.min(w.minX,I.position.x),w.minY=Math.min(w.minY,I.position.y),w.maxX=Math.max(w.maxX,I.position.x+I.size.width),w.maxY=Math.max(w.maxY,I.position.y+I.size.height);w.width=w.maxX-w.minX,w.height=w.maxY-w.minY;let S={x:-(w.maxX+w.minX)/2,y:-(w.maxY+w.minY)/2},C=t.toArray();for(let I of x.children){let{sourceComponent:k,sourceGroup:P}=I.metadata;if(k){let N=t.schematic_component.getWhere({source_component_id:k.source_component_id});if(!N)continue;yD(C,N.schematic_component_id,{x:I.position.x+I.size.width/2+S.x,y:I.position.y+I.size.height/2+S.y})}if(P){if(!t.schematic_group.getWhere({source_group_id:P.source_group_id}))continue;bD(C,P.source_group_id,{x:I.position.x+I.size.width/2+S.x,y:I.position.y+I.size.height/2+S.y})}}e.schematic_group_id&&t.schematic_group.update(e.schematic_group_id,{width:w.width,height:w.height})},VI=1;function d5t(e){let{db:t}=e.root,n=e._parsedProps,i=f5t(e);if(i.length===0)return;let r=m5t({db:t,pcbChildren:i}),o=_5t(n),s=y5t({props:n,pcbChildren:i,childDimensions:r,gridConfig:o}),a=x5t({pcbChildren:i,childDimensions:r,gridLayout:s,gridConfig:o}),{itemCoordinates:c}=a.layout();v5t({db:t,group:e,pcbChildren:i,itemCoordinates:c,gridLayout:s}),w5t({db:t,group:e,props:n,gridLayout:s})}function f5t(e){return e.children.filter(t=>t.pcb_component_id||t.pcb_group_id)}function m5t(e){let{db:t,pcbChildren:n}=e,i=0,r=0;for(let o of n){let s=0,a=0;if(o.pcb_group_id){let c=t.pcb_group.get(o.pcb_group_id);s=c?.width??0,a=c?.height??0}else if(o.pcb_component_id){let c=t.pcb_component.get(o.pcb_component_id);s=c?.width??0,a=c?.height??0}i=Math.max(i,s),r=Math.max(r,a)}return{width:i,height:r}}function _5t(e){let t=e.pcbGridCols??e.gridCols??e.pcbLayout?.grid?.cols,n=e.pcbGridRows??e.pcbLayout?.grid?.rows,i=e.pcbGridTemplateColumns,r=e.pcbGridTemplateRows,o=h=>h===void 0?VI:typeof h=="number"?h:D.parse(h),s=e.pcbGridGap??e.gridGap??e.pcbLayout?.gridGap,a=e.pcbGridRowGap??e.gridRowGap??e.pcbLayout?.gridRowGap,c=e.pcbGridColumnGap??e.gridColumnGap??e.pcbLayout?.gridColumnGap,l=VI,u=VI;if(a!==void 0||c!==void 0){let h=typeof s=="object"?s?.x:s,d=typeof s=="object"?s?.y:s;l=o(c??h),u=o(a??d)}else if(typeof s=="object"&&s!==null)l=o(s.x),u=o(s.y);else{let h=o(s);l=h,u=h}return{cols:t,rows:n,gapX:l,gapY:u,templateColumns:i,templateRows:r}}function y5t(e){let{props:t,pcbChildren:n,childDimensions:i,gridConfig:r}=e;return t.pcbGridTemplateColumns||t.pcbGridTemplateRows?g5t({props:t,gridConfig:r,pcbChildren:n,childDimensions:i}):b5t({gridConfig:r,pcbChildren:n,childDimensions:i})}function g5t(e){let{props:t,gridConfig:n,pcbChildren:i,childDimensions:r}=e,o=t.pcbGridTemplateColumns??"",s=t.pcbGridTemplateRows??"",a=d=>{let _=d.match(/repeat\((\d+),/);return _?parseInt(_[1]):Math.ceil(Math.sqrt(i.length))},c=t.pcbGridTemplateColumns?a(o):Math.ceil(Math.sqrt(i.length)),l=t.pcbGridTemplateRows?a(s):Math.ceil(i.length/c),u=c*r.width+Math.max(0,c-1)*n.gapX,h=l*r.height+Math.max(0,l-1)*n.gapY;return{gridTemplateColumns:o,gridTemplateRows:s,containerWidth:u,containerHeight:h}}function b5t(e){let{gridConfig:t,pcbChildren:n,childDimensions:i}=e,r,o;t.cols!==void 0&&t.rows!==void 0?(r=t.cols,o=t.rows):t.cols!==void 0?(r=t.cols,o=Math.ceil(n.length/r)):t.rows!==void 0?(o=t.rows,r=Math.ceil(n.length/o)):(r=Math.ceil(Math.sqrt(n.length)),o=Math.ceil(n.length/r)),r=Math.max(1,r),o=Math.max(1,o);let s=r*i.width+Math.max(0,r-1)*t.gapX,a=o*i.height+Math.max(0,o-1)*t.gapY,c=`repeat(${r}, ${i.width}px)`,l=`repeat(${o}, ${i.height}px)`;return{gridTemplateColumns:c,gridTemplateRows:l,containerWidth:s,containerHeight:a}}function x5t(e){let{pcbChildren:t,childDimensions:n,gridLayout:i,gridConfig:r}=e,o=t.map((s,a)=>({key:s.getString()||`child-${a}`,contentWidth:n.width,contentHeight:n.height}));return new hY({containerWidth:i.containerWidth,containerHeight:i.containerHeight,gridTemplateColumns:i.gridTemplateColumns,gridTemplateRows:i.gridTemplateRows,gap:[r.gapY,r.gapX],children:o})}function v5t(e){let{db:t,group:n,pcbChildren:i,itemCoordinates:r,gridLayout:o}=e,s=n._getGlobalPcbPositionBeforeLayout(),a=t.toArray();for(let c=0;c<i.length;c++){let l=i[c],u=l.getString()||`child-${c}`,h=r[u];if(!h){console.warn(`PCB grid layout: No coordinates found for child ${u}`);continue}let d=s.x-o.containerWidth/2+h.x+h.width/2,_=s.y+o.containerHeight/2-h.y-h.height/2;if(l.pcb_component_id)Yg(a,l.pcb_component_id,{x:d,y:_});else{let y=l;y.pcb_group_id&&y.source_group_id&&Xg(a,y.source_group_id,{x:d,y:_})}}}function w5t(e){let{db:t,group:n,props:i,gridLayout:r}=e;if(n.pcb_group_id){let o=n._getGlobalPcbPositionBeforeLayout();t.pcb_group.update(n.pcb_group_id,{width:i.width??r.containerWidth,height:i.height??r.containerHeight,center:o})}}function S5t(e){let t={serverUrl:"https://registry-api.tscircuit.com",serverMode:"job",serverCacheEnabled:!0};if(typeof e=="object"&&!e.preset)return{local:!(e.serverUrl||e.serverMode||e.serverCacheEnabled),...t,...e};let n=typeof e=="object"?e.preset:e,i=typeof e=="object"?e:{};switch(n){case"auto-local":return{local:!0,groupMode:"subcircuit"};case"sequential-trace":return{local:!0,groupMode:"sequential-trace"};case"subcircuit":return{local:!0,groupMode:"subcircuit"};case"auto-cloud":{let{preset:r,local:o,groupMode:s,...a}=i;return{local:!1,groupMode:"subcircuit",...t,...a}}default:return{local:!0,groupMode:"subcircuit"}}}var P5t=(e,t)=>{let n=e.children.filter(h=>h.componentName==="Constraint"&&h._parsedProps.pcb),i=new Map,r={},o=h=>(r[h]!==h&&(r[h]=o(r[h])),r[h]),s=(h,d)=>{let _=o(h),y=o(d);_!==y&&(r[y]=_)},a=h=>{h in r||(r[h]=h)},c=h=>{let d=h.startsWith(".")?h.slice(1):h;return e.children.find(y=>y.name===d)?.pcb_component_id??void 0};for(let h of n){let d=h._parsedProps;if("left"in d&&"right"in d){let _=c(d.left),y=c(d.right);_&&y&&(a(_),a(y),s(_,y))}else if("top"in d&&"bottom"in d){let _=c(d.top),y=c(d.bottom);_&&y&&(a(_),a(y),s(_,y))}else if("for"in d&&Array.isArray(d.for)){let _=d.for.map(y=>c(y)).filter(y=>!!y);for(let y of _)a(y);for(let y=1;y<_.length;y++)s(_[0],_[y])}}for(let h of Object.keys(r)){let d=o(h);i.has(d)||i.set(d,{componentIds:[],constraints:[]}),i.get(d).componentIds.push(h)}for(let h of n){let d=h._parsedProps,_;if("left"in d?_=c(d.left):"top"in d?_=c(d.top):"for"in d&&(_=c(d.for[0])),!_)continue;let y=o(_);i.get(y)?.constraints.push(h)}let l={},u=Object.fromEntries(t.components.map(h=>[h.componentId,h]));for(let[h,d]of i.entries()){if(d.componentIds.length<=1)continue;let _=new jp,y={},g=(A,O)=>{let $=`${A}_${O}`;return y[$]||(y[$]=new Xs($)),y[$]},x=d.componentIds[0];_.addConstraint(new ai(g(x,"x"),Yn.Eq,0,wn.required)),_.addConstraint(new ai(g(x,"y"),Yn.Eq,0,wn.required));for(let A of d.constraints){let O=A._parsedProps;if("xDist"in O){let $=c(O.left),B=c(O.right);$&&B&&_.addConstraint(new ai(new Cn(g(B,"x"),[-1,g($,"x")]),Yn.Eq,O.xDist,wn.required))}else if("yDist"in O){let $=c(O.top),B=c(O.bottom);$&&B&&_.addConstraint(new ai(new Cn(g($,"y"),[-1,g(B,"y")]),Yn.Eq,O.yDist,wn.required))}else if("sameX"in O&&Array.isArray(O.for)){let $=O.for.map(B=>c(B)).filter(B=>!!B);if($.length>1){let B=g($[0],"x");for(let H=1;H<$.length;H++)_.addConstraint(new ai(new Cn(g($[H],"x"),[-1,B]),Yn.Eq,0,wn.required))}}else if("sameY"in O&&Array.isArray(O.for)){let $=O.for.map(B=>c(B)).filter(B=>!!B);if($.length>1){let B=g($[0],"y");for(let H=1;H<$.length;H++)_.addConstraint(new ai(new Cn(g($[H],"y"),[-1,B]),Yn.Eq,0,wn.required))}}}_.updateVariables();let w={};for(let A of d.componentIds)w[A]={x:g(A,"x").value(),y:g(A,"y").value()};let S=1/0,C=1/0,I=-1/0,k=-1/0;for(let A of d.componentIds){let O=u[A],$=w[A];if(O)for(let B of O.pads){let H=$.x+B.offset.x,X=$.y+B.offset.y;S=Math.min(S,H-B.size.x/2),I=Math.max(I,H+B.size.x/2),C=Math.min(C,X-B.size.y/2),k=Math.max(k,X+B.size.y/2)}}let P={x:(S+I)/2,y:(C+k)/2},N=[],E={};for(let A of d.componentIds){let O=u[A],$=w[A];if(O){E[A]={x:$.x-P.x,y:$.y-P.y};for(let B of O.pads)N.push({padId:B.padId,networkId:B.networkId,type:B.type,size:B.size,offset:{x:$.x+B.offset.x-P.x,y:$.y+B.offset.y-P.y}})}}t.components=t.components.filter(A=>!d.componentIds.includes(A.componentId)),t.components.push({componentId:d.componentIds[0],pads:N,availableRotationDegrees:[0]}),d.relativeCenters=E,l[d.componentIds[0]]=d}return l},hV=({db:e,pcbComponentId:t,rotationDegrees:n,layer:i})=>{if(n==null||!e?.cad_component?.list)return;let r=e.cad_component.getWhere({pcb_component_id:t});if(!r)return;let o=i?.toLowerCase?.()==="bottom"?-n:n,s=r.rotation?.z??0,a={...r.rotation??{x:0,y:0,z:0},z:Rl(s+o)};e.cad_component.update(r.cad_component_id,{rotation:a}),r.rotation=a},pm=(e,t,n)=>{if(t===n)return!0;let i=e.source_group.get(t);return!i||!i.parent_source_group_id?!1:pm(e,i.parent_source_group_id,n)},T5t=(e,t,n)=>{let{db:i}=e.root;for(let r of t.components){let{center:o,componentId:s,ccwRotationOffset:a,ccwRotationDegrees:c}=r,l=n[s];if(l){let x=c??a??0,w=x*Math.PI/180;for(let S of l.componentIds){let C=l.relativeCenters[S];if(!C)continue;let I={x:C.x*Math.cos(w)-C.y*Math.sin(w),y:C.x*Math.sin(w)+C.y*Math.cos(w)},k=i.pcb_component.get(S);if(!k)continue;let P=k.center,N=Jn(e._computePcbGlobalTransformBeforeLayout(),vn(o.x+I.x,o.y+I.y),ja(w),vn(-P.x,-P.y)),E=i.toArray().filter(A=>"pcb_component_id"in A&&A.pcb_component_id===S);Hp(E,N),hV({db:i,pcbComponentId:S,rotationDegrees:x,layer:k.layer})}continue}let u=i.pcb_component.get(s);if(u){let x=e.source_group_id,S=i.source_component.get(u.source_component_id)?.source_group_id;if(S!==void 0&&!pm(i,S,x))continue;let C=u.center,I=c??a??0,k=Jn(e._computePcbGlobalTransformBeforeLayout(),vn(o.x,o.y),ja(I*Math.PI/180),vn(-C.x,-C.y)),P=i.toArray().filter(N=>"pcb_component_id"in N&&N.pcb_component_id===s);Hp(P,k),hV({db:i,pcbComponentId:s,rotationDegrees:I,layer:u.layer});continue}let h=i.pcb_group.list().find(x=>x.source_group_id===s);if(!h)continue;let d=h.center,_=c??a??0,y=Jn(e._computePcbGlobalTransformBeforeLayout(),vn(o.x,o.y),ja(_*Math.PI/180),vn(-d.x,-d.y)),g=i.toArray().filter(x=>{if("source_group_id"in x&&x.source_group_id&&(x.source_group_id===s||pm(i,x.source_group_id,s)))return!0;if("source_component_id"in x&&x.source_component_id){let w=i.source_component.get(x.source_component_id);if(w?.source_group_id&&(w.source_group_id===s||pm(i,w.source_group_id,s)))return!0}if("pcb_component_id"in x&&x.pcb_component_id){let w=i.pcb_component.get(x.pcb_component_id);if(w?.source_component_id){let S=i.source_component.get(w.source_component_id);if(S?.source_group_id&&(S.source_group_id===s||pm(i,S.source_group_id,s)))return!0}}return!1});Hp(g,y),i.pcb_group.update(h.pcb_group_id,{center:o})}};function I5t(e){switch(e.shape){case"rect":case"rotated_rect":case"pill":case"rotated_pill":return{width:e.width,height:e.height};case"circle":return{width:e.radius*2,height:e.radius*2};case"polygon":if(!e.points||e.points.length===0)return null;let t=e.points.map(a=>a.x),n=e.points.map(a=>a.y),i=Math.min(...t),r=Math.max(...t),o=Math.min(...n),s=Math.max(...n);return{width:r-i,height:s-o};default:return null}}function M5t(e){switch(e.shape){case"circular_hole_with_rect_pad":case"pill_hole_with_rect_pad":case"rotated_pill_hole_with_rect_pad":return{width:e.rect_pad_width,height:e.rect_pad_height};case"circle":return{width:e.outer_diameter,height:e.outer_diameter};case"oval":return{width:e.outer_width,height:e.outer_height};case"pill":return{width:e.outer_width,height:e.outer_height};default:return null}}var C5t="1mm",dV=(0,HV.default)("Group_doInitialPcbLayoutPack"),E5t=e=>{let{db:t}=e.root,{_parsedProps:n}=e,{packOrderStrategy:i,packPlacementStrategy:r,gap:o,pcbGap:s,pcbPackGap:a}=n,c=a??s??o,l=D.parse(c??C5t),u={},h=new Set,d=I=>{if(I?.pcb_component_id&&I?._parsedProps){let k=I._parsedProps,P=D.parse(k.pcbMarginLeft??k.pcbMarginX??0),N=D.parse(k.pcbMarginRight??k.pcbMarginX??0),E=D.parse(k.pcbMarginTop??k.pcbMarginY??0),A=D.parse(k.pcbMarginBottom??k.pcbMarginY??0);(P||N||E||A)&&(u[I.pcb_component_id]={left:P,right:N,top:E,bottom:A})}I?.children&&I.children.forEach(d)};d(e);let _=new Set;for(let I of e.children){let k=I;k._isNormalComponent&&k.isRelativelyPositioned?.()&&(k.pcb_component_id&&h.add(k.pcb_component_id),k.pcb_group_id&&_.add(k.pcb_group_id))}let y=t.toArray().filter(I=>I.type==="pcb_component"?!h.has(I.pcb_component_id):I.type==="pcb_group"?!_.has(I.pcb_group_id):!0),g=[];for(let I of h){let k=t.toArray().find(O=>O.type==="pcb_component"&&O.pcb_component_id===I);if(!k)continue;let P=k.center.x,N=k.center.y,E=t.toArray().filter(O=>O.type==="pcb_smtpad"&&O.pcb_component_id===I);for(let O of E){let $=I5t(O);if(!$||$.width===0||$.height===0)continue;let B,H;if(O.shape==="polygon"){let X=O.points.map(tt=>tt.x),U=O.points.map(tt=>tt.y);B=P+(Math.min(...X)+Math.max(...X))/2,H=N+(Math.min(...U)+Math.max(...U))/2}else B=P+O.x,H=N+O.y;g.push({obstacleId:O.pcb_smtpad_id,absoluteCenter:{x:B,y:H},width:$.width,height:$.height})}let A=t.toArray().filter(O=>O.type==="pcb_plated_hole"&&O.pcb_component_id===I);for(let O of A){let $=M5t(O);if(!$||$.width===0||$.height===0)continue;let B=P+O.x,H=N+O.y;g.push({obstacleId:O.pcb_plated_hole_id,absoluteCenter:{x:B,y:H},width:$.width,height:$.height})}}let x;if(n.width!==void 0&&n.height!==void 0){let I=D.parse(n.width),k=D.parse(n.height);x={minX:-I/2,maxX:I/2,minY:-k/2,maxY:k/2}}let w={...eY(tY(y,{source_group_id:e.source_group_id,shouldAddInnerObstacles:!0,chipMarginsMap:u})),orderStrategy:i??"largest_to_smallest",placementStrategy:r??"minimum_sum_squared_distance_to_network",minGap:l,obstacles:g,bounds:x},S=P5t(e,w);dV.enabled&&(e.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`packInput-circuitjson-${e.name}`,content:JSON.stringify(t.toArray())}),e.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`packInput-${e.name}`,content:w}));let C=Xb(w);if(dV.enabled){let I=iI(C);I.title=`packOutput-${e.name}`,global.debugGraphics?.push(I)}T5t(e,C,S)},k5t=e=>{let{db:t}=e.root,{_parsedProps:n}=e,i=e.children.filter(k=>k.pcb_component_id||k.pcb_group_id);if(i.some(k=>{let P=k._parsedProps;return P?.pcbX!==void 0||P?.pcbY!==void 0}))return;let o=n.pcbJustifyContent??n.justifyContent,s=n.pcbAlignItems??n.alignItems,a=n.pcbFlexGap??n.pcbGap??n.gap,c=n.pcbFlexDirection??"row",l={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"space-between","space-between":"space-between","space-around":"space-around","space-evenly":"space-evenly",center:"center"}[o??"space-between"],u={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"stretch",center:"center"}[s??"center"];if(!l)throw new Error(`Invalid justifyContent value: "${o}"`);if(!u)throw new Error(`Invalid alignItems value: "${s}"`);let h=0,d=0;typeof a=="object"?(h=a.y??0,d=a.x??0):typeof a=="number"?(h=a,d=a):typeof a=="string"&&(h=D.parse(a),d=D.parse(a));let _,y=n.width??n.pcbWidth??void 0,g=n.height??n.pcbHeight??void 0;(y===void 0||g===void 0)&&(_=Vg(i.map(k=>k._getMinimumFlexContainerSize()).filter(k=>k!==null),{alignItems:u,justifyContent:l,direction:c,rowGap:h,columnGap:d}),y=_.width,g=_.height);let w=new Gb(y,g,{alignItems:u,justifyContent:l,direction:c,rowGap:h,columnGap:d});for(let k of i){let P=k._getMinimumFlexContainerSize();w.addChild({metadata:k,width:P?.width??0,height:P?.height??0,flexBasis:P?c==="row"?P.width:P.height:void 0})}w.build();let S={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let k of w.children)S.minX=Math.min(S.minX,k.position.x),S.minY=Math.min(S.minY,k.position.y),S.maxX=Math.max(S.maxX,k.position.x+k.size.width),S.maxY=Math.max(S.maxY,k.position.y+k.size.height);S.width=S.maxX-S.minX,S.height=S.maxY-S.minY;let C=e._getGlobalPcbPositionBeforeLayout(),I={x:C.x-(S.maxX+S.minX)/2,y:C.y-(S.maxY+S.minY)/2};for(let k of w.children)k.metadata._repositionOnPcb({x:k.position.x+k.size.width/2+I.x,y:k.position.y+k.size.height/2+I.y});t.pcb_group.update(e.pcb_group_id,{width:S.width,height:S.height,center:C})};function N5t(e){let{db:t}=e.root,n=new Map,i=new Map,r=new Set,s=e.selectAll("trace").filter(O=>O._parsedProps?.schDisplayLabel),a=e.selectAll("group"),c=[e.schematic_group_id,...a.map(O=>O.schematic_group_id)],l=t.schematic_component.list().filter(O=>c.includes(O.schematic_group_id)),u=[],h=new Map,d=new Map;for(let O of l){let $=O.schematic_component_id,B=[],H=t.source_component.getWhere({source_component_id:O.source_component_id}),X=t.schematic_port.list({schematic_component_id:O.schematic_component_id});for(let U of X){let tt=`${H?.name??O.schematic_component_id}.${U.pin_number}`;h.set(tt,U.schematic_port_id),d.set(U.schematic_port_id,tt)}for(let U of X){let tt=d.get(U.schematic_port_id);B.push({pinId:tt,x:U.center.x,y:U.center.y})}u.push({chipId:$,center:O.center,width:O.size.width,height:O.size.height,pins:B})}let _=new Set,y=new Map,g=new Map,x=new Map;for(let O of l){let $=t.schematic_port.list({schematic_component_id:O.schematic_component_id});for(let B of $)_.add(B.schematic_port_id),B.source_port_id&&(y.set(B.schematic_port_id,B.source_port_id),g.set(B.source_port_id,B.schematic_port_id))}let w=new Set;e.subcircuit_id&&w.add(e.subcircuit_id);for(let O of a)O.subcircuit_id&&w.add(O.subcircuit_id);let C=t.source_trace.list().filter(O=>{if(O.subcircuit_id===e.subcircuit_id)return!0;for(let $ of O.connected_source_port_ids)if(g.has($))return!0;return!1}).flatMap(O=>O.connected_source_net_ids);for(let O of C){let $=t.source_net.get(O);$?.subcircuit_id&&w.add($.subcircuit_id)}let I=[],k=new Map;for(let O of t.source_trace.list()){if(O.subcircuit_id&&!w.has(O.subcircuit_id))continue;let $=(O.connected_source_port_ids??[]).map(B=>g.get(B)).filter(B=>!!B&&_.has(B));if($.length>=2){let[B,H]=$.slice(0,2),X=[B,H].sort().join("::");if(!k.has(X)){k.set(X,O.source_trace_id);let U=O.display_name??O.source_trace_id;O.subcircuit_connectivity_map_key&&(r.add(O.subcircuit_connectivity_map_key),x.set(U,O.subcircuit_connectivity_map_key),i.set(O.subcircuit_connectivity_map_key,U)),I.push({pinIds:[B,H].map(tt=>d.get(tt)),netId:U})}}}let P=[];for(let O of t.source_net.list().filter($=>!$.subcircuit_id||w.has($.subcircuit_id)))O.subcircuit_connectivity_map_key&&(r.add(O.subcircuit_connectivity_map_key),n.set(O.subcircuit_connectivity_map_key,O));let N=new Map;for(let[O,$]of y){let B=t.source_port.get($);if(!B?.subcircuit_connectivity_map_key)continue;let H=B.subcircuit_connectivity_map_key;r.add(H),N.has(H)||N.set(H,[]),N.get(H).push(O)}for(let[O,$]of N){let B=n.get(O);if(B&&$.length>=2){let H=String(B.name||B.source_net_id||O);x.set(H,O),i.set(O,H);let U=.1*(.18/.18),tt=Number((String(H).length*U).toFixed(2));P.push({netId:H,pinIds:$.map(J=>d.get(J)),netLabelWidth:tt})}}let E=(()=>{let O={},$=new Set(P.map(B=>B.netId));for(let B of t.source_net.list().filter(H=>!H.subcircuit_id||w.has(H.subcircuit_id)))B.name&&$.has(B.name)&&(B.is_ground||B.name.toLowerCase().startsWith("gnd")?O[B.name]=["y-"]:B.is_power||B.name.toLowerCase().startsWith("v")?O[B.name]=["y+"]:O[B.name]=["x-","x+"]);return O})();return{inputProblem:{chips:u,directConnections:I,netConnections:P,availableNetLabelOrientations:E,maxMspPairDistance:e._parsedProps.schMaxTraceDistance??2.4},pinIdToSchematicPortId:h,pairKeyToSourceTraceId:k,sckToSourceNet:n,sckToUserNetId:i,userNetIdToSck:x,allSourceAndSchematicPortIdsInScope:_,schPortIdToSourcePortId:y,displayLabelTraces:s,allScks:r}}var er=1e-6;function fV(e){let t=Math.abs(e.to.x-e.from.x),n=Math.abs(e.to.y-e.from.y);return t>=n}function hx(e,t){return Math.hypot(t.x-e.x,t.y-e.y)}function mV(e,t,n){return{x:e.x+(t.x-e.x)*n,y:e.y+(t.y-e.y)*n}}function _V(e,t,n){let i=hx(e,t);if(i<er)return 0;let r=((n.x-e.x)*(t.x-e.x)+(n.y-e.y)*(t.y-e.y))/((t.x-e.x)*(t.x-e.x)+(t.y-e.y)*(t.y-e.y));return Math.max(0,Math.min(1,r))*i}function sx(e,t,n,i){return e*i-t*n}function A5t(e,t,n,i){let r={x:t.x-e.x,y:t.y-e.y},o={x:i.x-n.x,y:i.y-n.y},s=sx(r.x,r.y,o.x,o.y),a={x:n.x-e.x,y:n.y-e.y},c=sx(a.x,a.y,r.x,r.y);if(Math.abs(s)<er&&Math.abs(c)<er||Math.abs(s)<er&&Math.abs(c)>=er)return null;let l=sx(a.x,a.y,o.x,o.y)/s,u=sx(a.x,a.y,r.x,r.y)/s;return l<-er||l>1+er||u<-er||u>1+er?null:{x:e.x+l*r.x,y:e.y+l*r.y}}function R5t(e,t=er){if(e.length===0)return e;e.sort((r,o)=>r.start-o.start);let n=[],i={...e[0]};for(let r=1;r<e.length;r++){let o=e[r];o.start<=i.end+t?i.end=Math.max(i.end,o.end):(n.push(i),i={...o})}return n.push(i),n}function O5t(e,t,n){let i=hx(e.from,e.to);if(i<er||t.length===0)return[e];let r=n/2,o=t.map(h=>({start:Math.max(0,h-r),end:Math.min(i,h+r)})).filter(h=>h.end-h.start>er),s=R5t(o),a=[],c=0,l={x:e.to.x-e.from.x,y:e.to.y-e.from.y},u=(h,d,_)=>{if(d-h<=er)return;let y=h/i,g=d/i;a.push({from:mV(e.from,e.to,y),to:mV(e.from,e.to,g),..._?{is_crossing:!0}:{}})};for(let h of s)h.start-c>er&&u(c,h.start,!1),u(h.start,h.end,!0),c=h.end;return i-c>er&&u(c,i,!1),a.length>0?a:[e]}function L5t(e,t={}){let n=t.crossSegmentLength??.075,i=t.tolerance??er,r=new Map,o=c=>`${c.traceIdx}:${c.edgeIdx}`,s=c=>e[c.traceIdx].edges[c.edgeIdx];for(let c=0;c<e.length;c++){let l=e[c];for(let u=0;u<l.edges.length;u++){let h=l.edges[u];for(let d=c;d<e.length;d++){let _=e[d];for(let y=d===c?u+1:0;y<_.edges.length;y++){let g=_.edges[y],x=A5t(h.from,h.to,g.from,g.to);if(!x)continue;let w=hx(h.from,h.to),S=hx(g.from,g.to);if(w<i||S<i)continue;let C=_V(h.from,h.to,x),I=_V(g.from,g.to,x),k=C<=i||Math.abs(w-C)<=i||Number.isNaN(C),P=I<=i||Math.abs(S-I)<=i||Number.isNaN(I);if(!k&&!P){let N=fV(h),E=fV(g),A;if(N!==E)A=N;else{let B=Math.abs(h.to.x-h.from.x),H=Math.abs(h.to.y-h.from.y),X=Math.abs(g.to.x-g.from.x),U=Math.abs(g.to.y-g.from.y),tt=B-H,J=X-U;A=tt===J?!0:tt>J}let O=o({traceIdx:A?c:d,edgeIdx:A?u:y}),$=r.get(O)??[];$.push(A?C:I),r.set(O,$)}}}}}let a=e.map(c=>({source_trace_id:c.source_trace_id,edges:[]}));for(let c=0;c<e.length;c++){let l=e[c];for(let u=0;u<l.edges.length;u++){let h=o({traceIdx:c,edgeIdx:u}),d=r.get(h)??[];if(d.length===0){a[c].edges.push(l.edges[u]);continue}let _=Array.from(new Set(d.map(g=>Number(g.toFixed(6))))).sort((g,x)=>g-x),y=O5t(l.edges[u],_,n);a[c].edges.push(...y)}}return a}var cs=1e-6;function dx(e,t,n=cs){return Math.abs(e-t)<=n}function Ah(e,t,n=cs){return dx(e.x,t.x,n)&&dx(e.y,t.y,n)}function yV(e,t,n,i=cs){let r=Math.min(t.x,n.x)-i,o=Math.max(t.x,n.x)+i,s=Math.min(t.y,n.y)-i,a=Math.max(t.y,n.y)+i;return e.x<r||e.x>o||e.y<s||e.y>a?!1:Math.abs((n.x-t.x)*(e.y-t.y)-(n.y-t.y)*(e.x-t.x))<=i}function gV(e,t=cs){let n=new Map;for(let i of e){let r=`${i.x.toFixed(6)},${i.y.toFixed(6)}`;n.has(r)||n.set(r,i)}return Array.from(n.values())}function bV(e){return{x:e.to.x-e.from.x,y:e.to.y-e.from.y}}function HI(e,t,n=cs){let i=bV(e),r=bV(t),o=Math.hypot(i.x,i.y),s=Math.hypot(r.x,r.y);if(o<n||s<n)return!0;let a=i.x*r.y-i.y*r.x;return Math.abs(a)<=n*o*s}function hm(e,t,n=cs){return e.edges.filter(i=>Ah(i.from,t,n)||Ah(i.to,t,n))}function xV(e,t,n=cs){for(let i of e.edges){if(Ah(i.from,t,n))return i.from;if(Ah(i.to,t,n))return i.to}return null}function F5t(e,t,n=cs){let i=Ah(e.from,t,n)||dx(e.from.x,t.x,n)&&dx(e.from.y,t.y,n)?e.to:e.from,r=i.x-t.x,o=i.y-t.y;return Math.abs(r)<n&&Math.abs(o)<n?null:Math.abs(r)>=Math.abs(o)?r>=0?"right":"left":o>=0?"up":"down"}function Mh(e,t,n=cs){let i=hm(e,t,n);if(i.length<2)return null;let r=i.map(h=>F5t(h,t,n)),o=r.includes("up"),s=r.includes("down"),a=r.includes("left"),c=r.includes("right"),l=o?"up":s?"down":null,u=c?"right":a?"left":null;return l&&u?`${l}-${u}`:null}function z5t(e,t={}){let n=t.tolerance??cs,i={};for(let o of e)i[o.source_trace_id]=[];let r=e.map(o=>{let s=[];for(let a of o.edges)s.push(a.from,a.to);return gV(s,n)});for(let o=0;o<e.length;o++){let s=e[o],a=r[o];for(let c=o+1;c<e.length;c++){let l=e[c],u=r[c];for(let h of a)for(let d of u)if(Ah(h,d,n)){let _=hm(s,h,n),y=hm(l,d,n),g=_.some(C=>y.some(I=>!HI(C,I,n))),x=Mh(s,h,n),w=Mh(l,d,n);g&&!(x!==null&&w!==null&&x===w)&&(i[s.source_trace_id].push(h),s.source_trace_id!==l.source_trace_id&&i[l.source_trace_id].push(d))}for(let h of a)for(let d of l.edges)if(yV(h,d.from,d.to,n)){let y=hm(s,h,n).some(C=>!HI(C,d,n)),g=Mh(s,h,n),x=xV(l,h,n*1e3),w=x?Mh(l,x,n):null;y&&!(g!==null&&w!==null&&g===w)&&(i[s.source_trace_id].push(h),s.source_trace_id!==l.source_trace_id&&i[l.source_trace_id].push(h))}for(let h of u)for(let d of s.edges)if(yV(h,d.from,d.to,n)){let y=hm(l,h,n).some(C=>!HI(d,C,n)),g=Mh(l,h,n),x=xV(s,h,n*1e3),w=x?Mh(s,x,n):null;y&&!(w!==null&&g!==null&&w===g)&&(i[l.source_trace_id].push(h),s.source_trace_id!==l.source_trace_id&&i[s.source_trace_id].push(h))}}}for(let o of Object.keys(i))i[o]=gV(i[o],n);return i}var GI=(0,UV.default)("Group_doInitialSchematicTraceRender");function D5t(e){let{group:t,solver:n,pinIdToSchematicPortId:i,userNetIdToSck:r}=e,{db:o}=t.root,s=n.traceLabelOverlapAvoidanceSolver?.getOutput().traces??n.schematicTraceLinesSolver?.solvedTracePaths,a=[];GI(`Traces inside SchematicTraceSolver output: ${(s??[]).length}`);for(let u of s??[]){let h=u?.tracePath;if(!Array.isArray(h)||h.length<2){GI(`Skipping trace ${u?.pinIds.join(",")} because it has less than 2 points`);continue}let d=[];for(let g=0;g<h.length-1;g++)d.push({from:{x:h[g].x,y:h[g].y},to:{x:h[g+1].x,y:h[g+1].y}});let _=null,y;if(Array.isArray(u?.pins)&&u.pins.length===2){let g=i.get(u.pins[0]?.pinId),x=i.get(u.pins[1]?.pinId);if(g&&x){for(let w of[g,x])o.schematic_port.get(w)&&o.schematic_port.update(w,{is_connected:!0});y=r.get(String(u.userNetId))}}_||(_=`solver_${u?.mspPairId}`,y=r.get(String(u.userNetId))),a.push({source_trace_id:_,edges:d,subcircuit_connectivity_map_key:y})}GI(`Applying ${a.length} traces from SchematicTraceSolver output`);let c=L5t(a.map(u=>({source_trace_id:u.source_trace_id,edges:u.edges}))),l=z5t(c);for(let u of c)o.schematic_trace.insert({source_trace_id:u.source_trace_id,edges:u.edges,junctions:l[u.source_trace_id]??[],subcircuit_connectivity_map_key:a.find(h=>h.source_trace_id===u.source_trace_id)?.subcircuit_connectivity_map_key})}var $5t=e=>{switch(e){case"x+":return"left";case"x-":return"right";case"y+":return"bottom";case"y-":return"top";case"left":return"right";case"top":return"bottom";case"right":return"left";case"bottom":return"top"}},B5t=e=>{for(let n of e){let i=n._getDirectlyConnectedTraces();for(let r of i){let o=r._parsedProps.schDisplayLabel;if(o)return{name:o,wasAssignedDisplayLabel:!0}}}return{name:e.map(n=>n._getNetLabelText()).join("/"),wasAssignedDisplayLabel:!1}},UI=(0,qV.default)("Group_doInitialSchematicTraceRender");function j5t(e){let{group:t,solver:n,sckToSourceNet:i,allScks:r,allSourceAndSchematicPortIdsInScope:o,schPortIdToSourcePortId:s,userNetIdToSck:a,pinIdToSchematicPortId:c,schematicPortIdsWithPreExistingNetLabels:l,schematicPortIdsWithRoutedTraces:u}=e,{db:h}=t.root,d=n.traceLabelOverlapAvoidanceSolver?.getOutput().netLabelPlacements??[],_=n.mspConnectionPairSolver.globalConnMap;for(let y of d){UI(`processing placement: ${y.netId}`);let g=_.getIdsConnectedToNet(y.globalConnNetId).find(O=>a.get(O)),x=a.get(g),w=y.anchorPoint,S=y.orientation,C=$5t(S),I=x?i.get(x):void 0,k=y.pinIds.map(O=>c.get(O));if(k.some(O=>l.has(O))){UI(`skipping net label placement for "${y.netId}" REASON:schematic port has pre-existing net label`);continue}if(I){let O=I.name,$=xc({anchor_position:w,anchor_side:C,text:O});h.schematic_net_label.insert({text:O,anchor_position:w,center:$,anchor_side:C,...I?.source_net_id?{source_net_id:I.source_net_id}:{}});continue}let P=t.selectAll("port").filter(O=>O._getSubcircuitConnectivityKey()===x),{name:N,wasAssignedDisplayLabel:E}=B5t(P);if(!E&&k.some(O=>u.has(O))){UI(`skipping net label placement for "${y.netId}" REASON:schematic port has routed traces and no display label`);continue}let A=xc({anchor_position:w,anchor_side:C,text:N});h.schematic_net_label.insert({text:N,anchor_position:w,center:A,anchor_side:C})}}var Y5t=({allSourceAndSchematicPortIdsInScope:e,group:t,schPortIdToSourcePortId:n,sckToSourceNet:i,pinIdToSchematicPortId:r,schematicPortIdsWithPreExistingNetLabels:o})=>{let{db:s}=t.root;for(let a of Array.from(e)){let c=s.schematic_port.get(a);if(!c||c.is_connected)continue;let l=n.get(a);if(!l)continue;let h=s.source_port.get(l)?.subcircuit_connectivity_map_key;if(!h)continue;let d=i.get(h);if(!d||s.schematic_net_label.list().some(w=>Math.abs(w.anchor_position.x-c.center.x)<.1&&Math.abs(w.anchor_position.y-c.center.y)<.1?d.source_net_id&&w.source_net_id?w.source_net_id===d.source_net_id:w.text===(d.name||h):!1))continue;let y=d.name||d.source_net_id||h,g=ym(c.facing_direction||"right")||"right",x=xc({anchor_position:c.center,anchor_side:g,text:y});s.schematic_net_label.insert({text:y,anchor_position:c.center,center:x,anchor_side:g,...d.source_net_id?{source_net_id:d.source_net_id}:{}})}},X5t=e=>{let t=new Set,n=e.selectAll("netlabel");for(let i of n){let r=i._getConnectedPorts();for(let o of r)o.schematic_port_id&&t.add(o.schematic_port_id)}return t},V5t=({solver:e,pinIdToSchematicPortId:t})=>{let n=e.schematicTraceLinesSolver.solvedTracePaths,i=new Set;for(let r of n)for(let o of r.pinIds){let s=t.get(o);s&&i.add(s)}return i},H5t=(0,GV.default)("Group_doInitialSchematicTraceRender"),G5t=e=>{if(!e.root?._featureMspSchematicTraceRouting||!e.isSubcircuit||e.root?.schematicDisabled)return;let{inputProblem:t,pinIdToSchematicPortId:n,pairKeyToSourceTraceId:i,sckToSourceNet:r,allSourceAndSchematicPortIdsInScope:o,schPortIdToSourcePortId:s,displayLabelTraces:a,allScks:c,userNetIdToSck:l}=N5t(e),u=X5t(e);H5t.enabled&&e.root?.emit("debug:logOutput",{type:"debug:logOutput",name:"group-trace-render-input-problem",content:JSON.stringify(t,null,2)});let h=new MY(t);h.solve();let d=V5t({solver:h,pinIdToSchematicPortId:n});D5t({group:e,solver:h,pinIdToSchematicPortId:n,userNetIdToSck:l}),j5t({group:e,solver:h,sckToSourceNet:r,allSourceAndSchematicPortIdsInScope:o,schPortIdToSourcePortId:s,pinIdToSchematicPortId:n,allScks:c,userNetIdToSck:l,schematicPortIdsWithPreExistingNetLabels:u,schematicPortIdsWithRoutedTraces:d}),Y5t({group:e,allSourceAndSchematicPortIdsInScope:o,schPortIdToSourcePortId:s,sckToSourceNet:r,pinIdToSchematicPortId:n,schematicPortIdsWithPreExistingNetLabels:u})},U5t=()=>({async simulate(e){let t="spice-experiment-1",{circuit:n,tran:i}=kY(e);return{simulationResultCircuitJson:NY(i,n,t)}}}),ta=(0,WV.default)("tscircuit:core:Group_doInitialSimulationSpiceEngineRender");function q5t(e){if(!e.isSubcircuit)return;let{root:t}=e;if(!t||e.selectAll("analogsimulation").length===0)return;let i={...t.platform?.spiceEngineMap};i.spicey||(i.spicey=U5t());let r=t.db.toArray(),o;try{o=EY(r).toSpiceString(),ta(`Generated SPICE string:
|
|
243
243
|
${o}`)}catch(s){ta(`Failed to convert circuit JSON to SPICE: ${s}`);return}for(let[s,a]of Object.entries(i))ta(`Queueing simulation for spice engine: ${s}`),e._queueAsyncEffect(`spice-simulation-${s}`,async()=>{try{ta(`Running simulation with engine: ${s}`);let c=await a.simulate(o);ta(`Simulation completed, received ${c.simulationResultCircuitJson.length} elements`);let l=t.db.simulation_experiment.list()[0];if(!l){ta("No simulation experiment found, skipping result insertion");return}for(let u of c.simulationResultCircuitJson){u.type==="simulation_transient_voltage_graph"&&(u.simulation_experiment_id=l.simulation_experiment_id);let h=u.type;h&&t.db[h]?(t.db[h].insert(u),ta(`Inserted ${h} into database`)):(ta(`Warning: Unknown element type ${h}, adding to raw db`),t.db._addElement(u))}e._markDirty("SimulationSpiceEngineRender")}catch(c){ta(`Simulation failed for engine ${s}: ${c}`)}})}function W5t(e){if(e.root?.pcbDisabled||!e.pcb_group_id)return;let t=e._parsedProps?.pcbPositionAnchor;if(!t)return;let n=e._getGlobalPcbPositionBeforeLayout(),{pcbX:i,pcbY:r}=e._parsedProps;if(i===void 0&&r===void 0)return;let{db:o}=e.root,s=o.pcb_group.get(e.pcb_group_id);if(!s)return;let a=s.width,c=s.height,{center:l}=s;if(s.outline&&s.outline.length>0){let g=qo(s.outline);g&&(a=g.maxX-g.minX,c=g.maxY-g.minY)}if(!a||!c)return;let u={left:l.x-a/2,right:l.x+a/2,top:l.y+c/2,bottom:l.y-c/2},h={...l},d=null;if(new Set(["center","top_left","top_center","top_right","center_left","center_right","bottom_left","bottom_center","bottom_right"]).has(t))switch(t){case"center":d=h;break;case"top_left":d={x:u.left,y:u.top};break;case"top_center":d={x:h.x,y:u.top};break;case"top_right":d={x:u.right,y:u.top};break;case"center_left":d={x:u.left,y:h.y};break;case"center_right":d={x:u.right,y:h.y};break;case"bottom_left":d={x:u.left,y:u.bottom};break;case"bottom_center":d={x:h.x,y:u.bottom};break;case"bottom_right":d={x:u.right,y:u.bottom};break}if(!d)return;let y={...h};n.x!==void 0&&(y.x+=n.x-d.x),n.y!==void 0&&(y.y+=n.y-d.y),(Math.abs(y.x-h.x)>1e-6||Math.abs(y.y-h.y)>1e-6)&&(e._repositionOnPcb(y),o.pcb_group.update(e.pcb_group_id,{center:y})),o.pcb_group.update(e.pcb_group_id,{anchor_position:n,anchor_alignment:t})}var iu=class extends On{constructor(){super(...arguments);M(this,"pcb_group_id",null);M(this,"schematic_group_id",null);M(this,"subcircuit_id",null);M(this,"_hasStartedAsyncAutorouting",!1);M(this,"_asyncAutoroutingResult",null);M(this,"unnamedElementCounter",{})}get config(){return{zodProps:EF,componentName:"Group"}}doInitialSourceGroupRender(){let{db:t}=this.root,n=typeof this._parsedProps.name=="string"&&this._parsedProps.name.length>0,i=t.source_group.insert({name:this.name,is_subcircuit:this.isSubcircuit,was_automatically_named:!n});this.source_group_id=i.source_group_id,this.isSubcircuit&&(this.subcircuit_id=`subcircuit_${i.source_group_id}`,t.source_group.update(i.source_group_id,{subcircuit_id:this.subcircuit_id}))}doInitialSourceRender(){let{db:t}=this.root;for(let n of this.children)t.source_component.update(n.source_component_id,{source_group_id:this.source_group_id})}doInitialSourceParentAttachment(){let{db:t}=this.root,n=this.parent?.getGroup?.();if(n?.source_group_id&&t.source_group.update(this.source_group_id,{parent_source_group_id:n.source_group_id}),!this.isSubcircuit)return;let i=this.parent?.getSubcircuit?.()?.subcircuit_id;i&&t.source_group.update(this.source_group_id,{parent_subcircuit_id:i})}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=n,r=i.outline&&i.outline.length>0,o=r?i.outline.map(a=>({x:Y.parse(a.x),y:Y.parse(a.y)})):void 0,s=t.pcb_group.insert({is_subcircuit:this.isSubcircuit,subcircuit_id:this.subcircuit_id??this.getSubcircuit()?.subcircuit_id,name:this.name,center:this._getGlobalPcbPositionBeforeLayout(),...r?{outline:o}:{width:0,height:0},pcb_component_ids:[],source_group_id:this.source_group_id,autorouter_configuration:n.autorouter?{trace_clearance:n.autorouter.traceClearance}:void 0});this.pcb_group_id=s.pcb_group_id;for(let a of this.children)t.pcb_component.update(a.pcb_component_id,{pcb_group_id:s.pcb_group_id})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,n=this._parsedProps,i=n.outline&&n.outline.length>0;if(this.pcb_group_id){let r=this._parsedProps.pcbX!==void 0||this._parsedProps.pcbY!==void 0;if(i){let h=n.outline.map(x=>({x:Y.parse(x.x),y:Y.parse(x.y)})),d=qo(h);if(!d)return;let _=(d.minX+d.maxX)/2,y=(d.minY+d.maxY)/2,g=r?t.pcb_group.get(this.pcb_group_id)?.center??{x:_,y}:{x:_,y};t.pcb_group.update(this.pcb_group_id,{center:g});return}let o=mx(this.children),s=o.width,a=o.height,c=(o.minX+o.maxX)/2,l=(o.minY+o.maxY)/2;if(this.isSubcircuit){let{padLeft:h,padRight:d,padTop:_,padBottom:y}=this._resolvePcbPadding();s+=h+d,a+=_+y,c+=(d-h)/2,l+=(_-y)/2}let u=r?t.pcb_group.get(this.pcb_group_id)?.center??{x:c,y:l}:{x:c,y:l};t.pcb_group.update(this.pcb_group_id,{width:Number(n.width??s),height:Number(n.height??a),center:u})}}getNextAvailableName(t){var n,i;return(n=this.unnamedElementCounter)[i=t.lowercaseComponentName]??(n[i]=1),`unnamed_${t.lowercaseComponentName}${this.unnamedElementCounter[t.lowercaseComponentName]++}`}_resolvePcbPadding(){let t=this._parsedProps,n=t.pcbLayout,i=h=>{let d=n?.[h],_=t[h];if(typeof d=="number")return d;if(typeof _=="number")return _},r=i("padding")??0,o=i("paddingX"),s=i("paddingY"),a=i("paddingLeft")??o??r,c=i("paddingRight")??o??r,l=i("paddingTop")??s??r,u=i("paddingBottom")??s??r;return{padLeft:a,padRight:c,padTop:l,padBottom:u}}doInitialCreateTraceHintsFromProps(){let{_parsedProps:t}=this,{db:n}=this.root,i=t;if(!this.isSubcircuit)return;let r=i.manualEdits?.manual_trace_hints;if(r)for(let o of r)this.add(new pM({for:o.pcb_port_selector,offsets:o.offsets}))}doInitialSourceAddConnectivityMapKey(){u5t(this)}_areChildSubcircuitsRouted(){let t=this.selectAll("group").filter(n=>n.isSubcircuit);for(let n of t)if(n._shouldRouteAsync()&&!n._asyncAutoroutingResult)return!1;return!0}_shouldRouteAsync(){let t=this._getAutorouterConfig();return t.groupMode==="sequential-trace"?!1:!!(t.local&&t.groupMode==="subcircuit"||!t.local)}_hasTracesToRoute(){let t=(0,Ch.default)("tscircuit:core:_hasTracesToRoute"),n=this.selectAll("trace");return t(`[${this.getString()}] has ${n.length} traces to route`),n.length>0}async _runEffectMakeHttpAutoroutingRequest(){let{db:t}=this.root,n=(0,Ch.default)("tscircuit:core:_runEffectMakeHttpAutoroutingRequest"),i=this._parsedProps,r=this._getAutorouterConfig(),o=r.serverUrl,s=r.serverMode,a=(u,h)=>(n("fetching",u),h.headers&&(h.headers["Tscircuit-Core-Version"]=this.root?.getCoreVersion()),fetch(u,h)),c=this.root.db.toArray().filter(u=>u.type.startsWith("source_")||u.type.startsWith("pcb_"));if(s==="solve-endpoint"){if(this.props.autorouter?.inputFormat==="simplified"){let{autorouting_result:h}=await a(`${o}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_simple_route_json:eM({db:t,minTraceWidth:this.props.autorouter?.minTraceWidth??.15,subcircuit_id:this.subcircuit_id}).simpleRouteJson,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(d=>d.json());this._asyncAutoroutingResult=h,this._markDirty("PcbTraceRender");return}let{autorouting_result:u}=await a(`${o}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_circuit_json:c,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(h=>h.json());this._asyncAutoroutingResult=u,this._markDirty("PcbTraceRender");return}let{autorouting_job:l}=await a(`${o}/autorouting/jobs/create`,{method:"POST",body:JSON.stringify({input_circuit_json:c,provider:"freerouting",autostart:!0,display_name:this.root?.name,subcircuit_id:this.subcircuit_id,server_cache_enabled:r.serverCacheEnabled}),headers:{"Content-Type":"application/json"}}).then(u=>u.json());for(;;){let{autorouting_job:u}=await a(`${o}/autorouting/jobs/get`,{method:"POST",body:JSON.stringify({autorouting_job_id:l.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(h=>h.json());if(u.is_finished){let{autorouting_job_output:h}=await a(`${o}/autorouting/jobs/get_output`,{method:"POST",body:JSON.stringify({autorouting_job_id:l.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(d=>d.json());this._asyncAutoroutingResult={output_pcb_traces:h.output_pcb_traces},this._markDirty("PcbTraceRender");break}if(u.has_error){let h=new um(`Autorouting job failed: ${JSON.stringify(u.error)}`);throw t.pcb_autorouting_error.insert({pcb_error_id:l.autorouting_job_id,error_type:"pcb_autorouting_error",message:h.message}),h}await new Promise(h=>setTimeout(h,100))}}async _runLocalAutorouting(){let{db:t}=this.root,n=this._parsedProps,i=(0,Ch.default)("tscircuit:core:_runLocalAutorouting");i(`[${this.getString()}] starting local autorouting`);let r=this._getAutorouterConfig(),{simpleRouteJson:o}=eM({db:t,minTraceWidth:this.props.autorouter?.minTraceWidth??.15,subcircuit_id:this.subcircuit_id});if(i.enabled&&global.debugOutputArray?.push({name:`simpleroutejson-${this.props.name}.json`,obj:o}),i.enabled){let c=X4(o);c.title=`autorouting-${this.props.name}`,global.debugGraphics?.push(c)}this.root?.emit("autorouting:start",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),simpleRouteJson:o});let s;r.algorithmFn?s=await r.algorithmFn(o):s=new e5t(o,{capacityDepth:this.props.autorouter?.capacityDepth,targetMinCapacity:this.props.autorouter?.targetMinCapacity});let a=new Promise((c,l)=>{s.on("complete",u=>{i(`[${this.getString()}] local autorouting complete`),c(u.traces)}),s.on("error",u=>{i(`[${this.getString()}] local autorouting error: ${u.error.message}`),l(u.error)})});s.on("progress",c=>{this.root?.emit("autorouting:progress",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),...c})}),s.start();try{let c=await a;this._asyncAutoroutingResult={output_pcb_traces:c},this._markDirty("PcbTraceRender")}catch(c){let{db:l}=this.root;throw l.pcb_autorouting_error.insert({pcb_error_id:`pcb_autorouter_error_subcircuit_${this.subcircuit_id}`,error_type:"pcb_autorouting_error",message:c instanceof Error?c.message:String(c)}),this.root?.emit("autorouting:error",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),error:{message:c instanceof Error?c.message:String(c)},simpleRouteJson:o}),c}finally{s.stop()}}_startAsyncAutorouting(){this._hasStartedAsyncAutorouting||(this._hasStartedAsyncAutorouting=!0,this._getAutorouterConfig().local?this._queueAsyncEffect("capacity-mesh-autorouting",async()=>this._runLocalAutorouting()):this._queueAsyncEffect("make-http-autorouting-request",async()=>this._runEffectMakeHttpAutoroutingRequest()))}doInitialPcbTraceRender(){let t=(0,Ch.default)("tscircuit:core:doInitialPcbTraceRender");if(this.isSubcircuit&&!this.root?.pcbDisabled&&!this.getInheritedProperty("routingDisabled")&&!this._shouldUseTraceByTraceRouting()){if(!this._areChildSubcircuitsRouted()){t(`[${this.getString()}] child subcircuits are not routed, skipping async autorouting until subcircuits routed`);return}t(`[${this.getString()}] no child subcircuits to wait for, initiating async routing`),this._hasTracesToRoute()&&this._startAsyncAutorouting()}}doInitialSchematicTraceRender(){G5t(this)}updatePcbTraceRender(){let t=(0,Ch.default)("tscircuit:core:updatePcbTraceRender");if(t(`[${this.getString()}] updating...`),!this.isSubcircuit)return;if(this._shouldRouteAsync()&&this._hasTracesToRoute()&&!this._hasStartedAsyncAutorouting){this._areChildSubcircuitsRouted()&&(t(`[${this.getString()}] child subcircuits are now routed, starting async autorouting`),this._startAsyncAutorouting());return}if(!this._asyncAutoroutingResult||this._shouldUseTraceByTraceRouting())return;let{db:n}=this.root;if(this._asyncAutoroutingResult.output_simple_route_json){t(`[${this.getString()}] updating PCB traces from simple route json (${this._asyncAutoroutingResult.output_simple_route_json.traces?.length} traces)`),this._updatePcbTraceRenderFromSimpleRouteJson();return}if(this._asyncAutoroutingResult.output_pcb_traces){t(`[${this.getString()}] updating PCB traces from ${this._asyncAutoroutingResult.output_pcb_traces.length} traces`),this._updatePcbTraceRenderFromPcbTraces();return}}_updatePcbTraceRenderFromSimpleRouteJson(){let{db:t}=this.root,{traces:n}=this._asyncAutoroutingResult.output_simple_route_json;if(n)for(let i of n){let r=t.pcb_trace.insert({subcircuit_id:this.subcircuit_id,route:i.route})}}_updatePcbTraceRenderFromPcbTraces(){let{output_pcb_traces:t}=this._asyncAutoroutingResult;if(!t)return;let{db:n}=this.root;for(let i of t)if(i.type==="pcb_trace"){if(i.subcircuit_id=this.subcircuit_id,i.connection_name){let r=i.connection_name;i.source_trace_id=r}n.pcb_trace.insert(i)}for(let i of t)if(i.type!=="pcb_via"&&i.type==="pcb_trace")for(let r of i.route)r.route_type==="via"&&n.pcb_via.insert({pcb_trace_id:i.pcb_trace_id,x:r.x,y:r.y,hole_diameter:.3,outer_diameter:.6,layers:[r.from_layer,r.to_layer],from_layer:r.from_layer,to_layer:r.to_layer})}doInitialSchematicComponentRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=t.schematic_group.insert({is_subcircuit:this.isSubcircuit,subcircuit_id:this.subcircuit_id,name:this.name,center:this._getGlobalSchematicPositionBeforeLayout(),width:0,height:0,schematic_component_ids:[],source_group_id:this.source_group_id});this.schematic_group_id=i.schematic_group_id;for(let r of this.children)r.schematic_component_id&&t.schematic_component.update(r.schematic_component_id,{schematic_group_id:i.schematic_group_id})}_getSchematicLayoutMode(){let t=this._parsedProps;if(t.schLayout?.layoutMode==="none"||t.schLayout?.layoutMode==="relative")return"relative";if(t.schLayout?.matchAdapt)return"match-adapt";if(t.schLayout?.flex)return"flex";if(t.schLayout?.grid)return"grid";if(t.schMatchAdapt)return"match-adapt";if(t.schFlex)return"flex";if(t.schGrid)return"grid";if(t.matchAdapt)return"match-adapt";if(t.flex)return"flex";if(t.grid)return"grid";if(t.relative||t.schRelative)return"relative";let n=this.children.some(r=>{let o=r._parsedProps;return o?.schX!==void 0||o?.schY!==void 0}),i=(t.manualEdits?.schematic_placements?.length??0)>0;return!n&&!i?"match-adapt":"relative"}doInitialSchematicLayout(){let t=this._getSchematicLayoutMode();t==="match-adapt"&&this._doInitialSchematicLayoutMatchpack(),t==="grid"&&this._doInitialSchematicLayoutGrid(),t==="flex"&&this._doInitialSchematicLayoutFlex(),this._insertSchematicBorder()}_doInitialSchematicLayoutMatchAdapt(){a5t(this)}_doInitialSchematicLayoutMatchpack(){l5t(this)}_doInitialSchematicLayoutGrid(){p5t(this)}_doInitialSchematicLayoutFlex(){h5t(this)}_getPcbLayoutMode(){let t=this._parsedProps;if(t.pcbRelative)return"none";if(t.pcbLayout?.matchAdapt)return"match-adapt";if(t.pcbLayout?.flex)return"flex";if(t.pcbLayout?.grid)return"grid";if(t.pcbLayout?.pack)return"pack";if(t.pcbFlex)return"flex";if(t.pcbGrid)return"grid";if(t.pcbPack||t.pack)return"pack";if(t.matchAdapt)return"match-adapt";if(t.flex)return"flex";if(t.grid)return"grid";let n=t.pcbX!==void 0||t.pcbY!==void 0,i=(t.manualEdits?.pcb_placements?.length??0)>0,r=this.children.reduce((o,s)=>{if(!s.pcb_component_id&&!s.pcb_group_id)return o;let a=s._parsedProps,c=a?.pcbX!==void 0||a?.pcbY!==void 0;return o+(c?0:1)},0);return!n&&!i&&r>1?"pack":"none"}doInitialPcbLayout(){let t=this._getPcbLayoutMode();t==="grid"?this._doInitialPcbLayoutGrid():t==="pack"?this._doInitialPcbLayoutPack():t==="flex"&&this._doInitialPcbLayoutFlex()}_doInitialPcbLayoutGrid(){d5t(this)}_doInitialPcbLayoutPack(){E5t(this)}_doInitialPcbLayoutFlex(){k5t(this)}_insertSchematicBorder(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,n=this._parsedProps;if(!n.border)return;let i=typeof n.schWidth=="number"?n.schWidth:void 0,r=typeof n.schHeight=="number"?n.schHeight:void 0,o=typeof n.schPadding=="number"?n.schPadding:0,s=typeof n.schPaddingLeft=="number"?n.schPaddingLeft:o,a=typeof n.schPaddingRight=="number"?n.schPaddingRight:o,c=typeof n.schPaddingTop=="number"?n.schPaddingTop:o,l=typeof n.schPaddingBottom=="number"?n.schPaddingBottom:o,u=this.schematic_group_id?t.schematic_group.get(this.schematic_group_id):null;if(u&&(i===void 0&&typeof u.width=="number"&&(i=u.width),r===void 0&&typeof u.height=="number"&&(r=u.height)),i===void 0||r===void 0)return;let h=u?.center??this._getGlobalSchematicPositionBeforeLayout(),d=h.x-i/2-s,_=h.y-r/2-l,y=i+s+a,g=r+c+l;t.schematic_box.insert({width:y,height:g,x:d,y:_,is_dashed:n.border?.dashed??!1})}_determineSideFromPosition(t,n){if(!t.center||!n.center)return"left";let i=t.center.x-n.center.x,r=t.center.y-n.center.y;return Math.abs(i)>Math.abs(r)?i>0?"right":"left":r>0?"bottom":"top"}_calculateSchematicBounds(t){if(t.length===0)return{minX:0,maxX:0,minY:0,maxY:0};let n=1/0,i=-1/0,r=1/0,o=-1/0;for(let a of t)n=Math.min(n,a.centerX),i=Math.max(i,a.centerX),r=Math.min(r,a.centerY),o=Math.max(o,a.centerY);let s=2;return{minX:n-s,maxX:i+s,minY:r-s,maxY:o+s}}_getAutorouterConfig(){let t=this._parsedProps.autorouter||this.getInheritedProperty("autorouter");return S5t(t)}_getSubcircuitLayerCount(){let t=this.getInheritedProperty("layers");return typeof t=="number"?t:2}_shouldUseTraceByTraceRouting(){return this._getAutorouterConfig().groupMode==="sequential-trace"}doInitialPcbDesignRuleChecks(){if(this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;let{db:t}=this.root;if(this.isSubcircuit){let n=new Map;for(let i of this.children)if(!i.isSubcircuit&&i._parsedProps.name){let r=n.get(i._parsedProps.name)||[];r.push(i),n.set(i._parsedProps.name,r)}for(let[i,r]of n.entries())r.length>1&&t.pcb_trace_error.insert({error_type:"pcb_trace_error",message:`Multiple components found with name "${i}" in subcircuit "${this.name||"unnamed"}". Component names must be unique within a subcircuit.`,source_trace_id:"",pcb_trace_id:"",pcb_component_ids:r.map(o=>o.pcb_component_id).filter(Boolean),pcb_port_ids:[]})}}doInitialSchematicReplaceNetLabelsWithSymbols(){if(this.root?.schematicDisabled||!this.isSubcircuit)return;let{db:t}=this.root,n=t;for(let i of n.schematic_net_label.list()){let r=n.source_net.get(i.source_net_id),o=i.text||r?.name||"";if(i.anchor_side==="top"&&/^gnd/i.test(o)){n.schematic_net_label.update(i.schematic_net_label_id,{symbol_name:"rail_down"});continue}i.anchor_side==="bottom"&&/^v/i.test(o)&&n.schematic_net_label.update(i.schematic_net_label_id,{symbol_name:"rail_up"})}}doInitialSimulationSpiceEngineRender(){q5t(this)}doInitialPcbComponentAnchorAlignment(){W5t(this)}updatePcbComponentAnchorAlignment(){this.doInitialPcbComponentAnchorAlignment()}_getMinimumFlexContainerSize(){return super._getMinimumFlexContainerSize()}_repositionOnPcb(t){return super._repositionOnPcb(t)}},Z5t=.01,vV=(e,t,n)=>{let i=e/2,r=t/2,o=Math.min(n,i,r);if(o<Z5t)return[{x:-i,y:-r},{x:i,y:-r},{x:i,y:r},{x:-i,y:r}];let a=Math.max(1,Math.ceil(Math.PI/2*o/.1)),c=Math.PI/2/a,l=[];l.push({x:-i+o,y:-r}),l.push({x:i-o,y:-r});for(let u=1;u<=a;u++){let h=-Math.PI/2+u*c;l.push({x:i-o+o*Math.cos(h),y:-r+o+o*Math.sin(h)})}l.push({x:i,y:r-o});for(let u=1;u<=a;u++){let h=0+u*c;l.push({x:i-o+o*Math.cos(h),y:r-o+o*Math.sin(h)})}l.push({x:-i+o,y:r});for(let u=1;u<=a;u++){let h=Math.PI/2+u*c;l.push({x:-i+o+o*Math.cos(h),y:r-o+o*Math.sin(h)})}l.push({x:-i,y:-r+o});for(let u=1;u<=a;u++){let h=Math.PI+u*c;l.push({x:-i+o+o*Math.cos(h),y:-r+o+o*Math.sin(h)})}return l},ZV=class extends iu{constructor(){super(...arguments);M(this,"pcb_board_id",null);M(this,"source_board_id",null);M(this,"_drcChecksComplete",!1);M(this,"_connectedSchematicPortPairs",new Set)}get isSubcircuit(){return!0}get isGroup(){return!0}get config(){return{componentName:"Board",zodProps:l4}}get boardThickness(){let{_parsedProps:t}=this;return t.thickness??1.4}get allLayers(){return(this._parsedProps.layers??2)===4?["top","bottom","inner1","inner2"]:["top","bottom"]}_getSubcircuitLayerCount(){return this._parsedProps.layers??2}doInitialPcbBoardAutoSize(){if(this.root?.pcbDisabled||!this.pcb_board_id)return;let{db:t}=this.root,{_parsedProps:n}=this;if(n.width&&n.height||n.outline)return;let i=1/0,r=1/0,o=-1/0,s=-1/0,a=YV(t,this.subcircuit_id),c=new Set([this.subcircuit_id,...a]),l=t.pcb_component.list().filter(k=>k.subcircuit_id&&c.has(k.subcircuit_id)),u=t.pcb_group.list().filter(k=>k.subcircuit_id&&c.has(k.subcircuit_id)),h=!1,d=(k,P,N)=>{P===0||N===0||(h=!0,i=Math.min(i,k.x-P/2),r=Math.min(r,k.y-N/2),o=Math.max(o,k.x+P/2),s=Math.max(s,k.y+N/2))};for(let k of l)d(k.center,k.width,k.height);for(let k of u){let P=k.width??0,N=k.height??0;if(k.outline&&k.outline.length>0){let E=qo(k.outline);E&&(P=E.maxX-E.minX,N=E.maxY-E.minY)}d(k.center,P,N)}if(n.boardAnchorPosition){let{x:k,y:P}=n.boardAnchorPosition;i=Math.min(i,k),r=Math.min(r,P),o=Math.max(o,k),s=Math.max(s,P)}let _=2,y=h?o-i+_*2:0,g=h?s-r+_*2:0,x={x:h?(i+o)/2+(n.outlineOffsetX??0):n.outlineOffsetX??0,y:h?(r+s)/2+(n.outlineOffsetY??0):n.outlineOffsetY??0},w=n.width??y,S=n.height??g,C=n.outline;!C&&n.borderRadius!=null&&w>0&&S>0&&(C=vV(w,S,n.borderRadius));let I={width:w,height:S,center:x};C&&(I.outline=C.map(k=>({x:k.x+(n.outlineOffsetX??0),y:k.y+(n.outlineOffsetY??0)}))),t.pcb_board.update(this.pcb_board_id,I)}updatePcbBoardAutoSize(){this.doInitialPcbBoardAutoSize()}_addBoardInformationToSilkscreen(){let t=this.root?.platform;if(!t?.printBoardInformationToSilkscreen)return;let n=this.root.db.pcb_board.get(this.pcb_board_id);if(!n)return;let i=[];if(t.projectName&&i.push(t.projectName),t.version&&i.push(`v${t.version}`),t.url&&i.push(t.url),i.length===0)return;let r=i.join(`
|
|
244
|
-
`),a={x:n.center.x+n.width/2-.25,y:n.center.y-n.height/2+1};this.root.db.pcb_silkscreen_text.insert({pcb_component_id:this.pcb_board_id,layer:"top",font:"tscircuit2024",font_size:.45,text:r,ccw_rotation:0,anchor_alignment:"bottom_right",anchor_position:a})}doInitialSourceRender(){super.doInitialSourceRender();let{db:t}=this.root,n=t.source_board.insert({source_group_id:this.source_group_id,title:this.props.title||this.props.name});this.source_board_id=n.source_board_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=n.width??0,r=n.height??0,o={x:(n.pcbX??0)+(n.outlineOffsetX??0),y:(n.pcbY??0)+(n.outlineOffsetY??0)},{boardAnchorPosition:s,boardAnchorAlignment:a}=n;if(s&&(o=t5t({boardAnchorPosition:s,boardAnchorAlignment:a??"center",width:i,height:r})),n.outline){let u=n.outline.map(x=>x.x),h=n.outline.map(x=>x.y),d=Math.min(...u),_=Math.max(...u),y=Math.min(...h),g=Math.max(...h);i=_-d,r=g-y,o={x:(d+_)/2+(n.outlineOffsetX??0),y:(y+g)/2+(n.outlineOffsetY??0)}}let c=n.outline;!c&&n.borderRadius!=null&&i>0&&r>0&&(c=vV(i,r,n.borderRadius));let l=t.pcb_board.insert({center:o,thickness:this.boardThickness,num_layers:this.allLayers.length,width:i,height:r,outline:c?.map(u=>({x:u.x+(n.outlineOffsetX??0),y:u.y+(n.outlineOffsetY??0)})),material:n.material});this.pcb_board_id=l.pcb_board_id,this._addBoardInformationToSilkscreen()}removePcbComponentRender(){let{db:t}=this.root;this.pcb_board_id&&(t.pcb_board.delete(this.pcb_board_id),this.pcb_board_id=null)}_computePcbGlobalTransformBeforeLayout(){return Li()}doInitialPcbDesignRuleChecks(){this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled")||super.doInitialPcbDesignRuleChecks()}updatePcbDesignRuleChecks(){if(this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;let{db:t}=this.root;if(!this._areChildSubcircuitsRouted()||this._drcChecksComplete)return;this._drcChecksComplete=!0;let n=LY(t.toArray());for(let l of n)t.pcb_trace_error.insert(l);let i=OY(t.toArray());for(let l of i)t.pcb_port_not_connected_error.insert(l);let r=DY(t.toArray());for(let l of r)t.pcb_component_outside_board_error.insert(l);let o=jY(t.toArray());for(let l of o)t.pcb_trace_error.insert(l);let s=BY(t.toArray());for(let l of s)t.pcb_via_clearance_error.insert(l);let a=$Y(t.toArray());for(let l of a)t.pcb_via_clearance_error.insert(l);let c=YY(t.toArray());for(let l of c)t.pcb_footprint_overlap_error.insert(l)}_emitRenderLifecycleEvent(t,n){super._emitRenderLifecycleEvent(t,n),n==="start"&&this.root?.emit("board:renderPhaseStarted",{renderId:this._renderId,phase:t})}},KV=class extends iu{get config(){return{componentName:"Panel",zodProps:kF}}get isGroup(){return!0}add(e){if(e.lowercaseComponentName!=="board")throw new Error("<panel> can only contain <board> elements");super.add(e)}runRenderCycle(){if(!this.children.some(e=>e.componentName==="Board"))throw new Error("<panel> must contain at least one <board>");super.runRenderCycle()}},K5t=new Proxy({},{get:(e,t)=>t}),ia=K5t,_x="rgba(132, 0, 0)",yx=.12,JV=class extends On{constructor(){super(...arguments);M(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Capacitor",schematicSymbolName:this.props.polarized?"capacitor_polarized":this.props.symbolName??"capacitor",zodProps:BF,sourceFtype:ia.simple_capacitor}}initPorts(){typeof this.props.footprint=="string"?super.initPorts({additionalAliases:{pin1:["anode","pos"],pin2:["cathode","neg"]}}):super.initPorts()}_getSchematicSymbolDisplayValue(){let t=this.props.capacitance,n=typeof t=="string"?t:`${ti(this._parsedProps.capacitance)}F`;return this._parsedProps.schShowRatings&&this._parsedProps.maxVoltageRating?`${n}/${ti(this._parsedProps.maxVoltageRating)}V`:n}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.decouplingFor,this.props.decouplingTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.decouplingFor&&this.props.decouplingTo&&(this.add(new ko({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.decouplingFor})),this.add(new ko({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.decouplingTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_capacitor",name:this.name,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,capacitance:n.capacitance,max_voltage_rating:n.maxVoltageRating,max_decoupling_trace_length:n.maxDecouplingTraceLength,display_capacitance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!n.polarized});this.source_component_id=i.source_component_id}},gx=class extends On{constructor(t){super(t);M(this,"schematicBoxDimensions",null)}get config(){return{componentName:"Chip",zodProps:Bp,shouldRenderAsSchematicBox:!0}}initPorts(t={}){super.initPorts(t);let{_parsedProps:n}=this;if(n.externallyConnectedPins){let i=new Set;for(let[r,o]of n.externallyConnectedPins)i.add(r),i.add(o);for(let r of i)if(!this.children.find(s=>s instanceof ji&&s.isMatchingAnyOf([r]))){let s=r.match(/^pin(\d+)$/);if(s){let a=parseInt(s[1]);this.add(new ji({pinNumber:a,aliases:[r]}))}else this.add(new ji({name:r,aliases:[r]}))}}}doInitialSchematicComponentRender(){let{_parsedProps:t}=this;t?.noSchematicRepresentation!==!0&&super.doInitialSchematicComponentRender()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:n.manufacturerPartNumber,supplier_part_numbers:n.supplierPartNumbers});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=n.layer??"top";if(i!=="top"&&i!=="bottom"){let o=this.getSubcircuit(),s=bp.parse({type:"pcb_component_invalid_layer_error",message:`Component cannot be placed on layer '${i}'. Components can only be placed on 'top' or 'bottom' layers.`,source_component_id:this.source_component_id,layer:i,subcircuit_id:o.subcircuit_id??void 0});t.pcb_component_invalid_layer_error.insert(s)}let r=t.pcb_component.insert({center:{x:n.pcbX??0,y:n.pcbY??0},width:2,height:3,layer:i==="top"||i==="bottom"?i:"top",rotation:n.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:n.doNotPlace??!1,obstructs_within_bounds:n.obstructsWithinBounds??!0});this.pcb_component_id=r.pcb_component_id}doInitialCreateTracesFromProps(){let{_parsedProps:t}=this;if(t.externallyConnectedPins)for(let[n,i]of t.externallyConnectedPins)this.add(new ko({from:`${this.getSubcircuitSelector()} > port.${n}`,to:`${this.getSubcircuitSelector()} > port.${i}`}));this._createTracesFromConnectionsProp()}doInitialSimulationRender(){let{db:t}=this.root,{pinAttributes:n}=this.props;if(!n)return;let i=null,r=null,o,s=this.selectAll("port");for(let h of s)for(let d of h.getNameAndAliases())if(n[d]){let _=n[d];_.providesPower&&(i=h,o=_.providesVoltage),_.providesGround&&(r=h)}if(!i||!r||o===void 0)return;let a=t.source_port.get(i.source_port_id);if(!a?.subcircuit_connectivity_map_key)return;let c=t.source_port.get(r.source_port_id);if(!c?.subcircuit_connectivity_map_key)return;let l=t.source_net.getWhere({subcircuit_connectivity_map_key:a.subcircuit_connectivity_map_key}),u=t.source_net.getWhere({subcircuit_connectivity_map_key:c.subcircuit_connectivity_map_key});!l||!u||t.simulation_voltage_source.insert({type:"simulation_voltage_source",positive_source_port_id:i.source_port_id,positive_source_net_id:l.source_net_id,negative_source_port_id:r.source_port_id,negative_source_net_id:u.source_net_id,voltage:o})}},QV=class extends gx{constructor(e){super(e)}get config(){return{...super.config,componentName:"Pinout",zodProps:NF}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_pinout",name:this.name,manufacturer_part_number:t.manufacturerPartNumber,supplier_part_numbers:t.supplierPartNumbers});this.source_component_id=n.source_component_id}},tH=class extends On{constructor(){super(...arguments);M(this,"pos",this.portMap.pin1);M(this,"anode",this.portMap.pin1);M(this,"neg",this.portMap.pin2);M(this,"cathode",this.portMap.pin2)}get config(){let t={schottky:"schottky_diode",avalanche:"avalanche_diode",zener:"zener_diode",photodiode:"photodiode"},n=this.props.schottky?"schottky":this.props.avalanche?"avalanche":this.props.zener?"zener":this.props.photo?"photodiode":null;return{schematicSymbolName:n?t[n]:this.props.symbolName??"diode",componentName:"Diode",zodProps:iz,sourceFtype:"simple_diode"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_diode",name:this.name,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},eH=class extends On{get config(){return{componentName:"fuse",schematicSymbolName:this.props.symbolName??"fuse",zodProps:RF,sourceFtype:ia.simple_fuse}}_getSchematicSymbolDisplayValue(){let e=this._parsedProps.currentRating,t=this._parsedProps.voltageRating,n=typeof e=="string"?parseFloat(e):e,i=typeof t=="string"?parseFloat(t):t;return`${ti(n)}A / ${ti(i)}V`}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=typeof t.currentRating=="string"?parseFloat(t.currentRating):t.currentRating,i=typeof t.voltageRating=="string"?parseFloat(t.voltageRating):t.voltageRating,r=e.source_component.insert({name:this.name,ftype:ia.simple_fuse,current_rating_amps:n,voltage_rating_volts:i,display_current_rating:`${ti(n)}A`,display_voltage_rating:`${ti(i)}V`});this.source_component_id=r.source_component_id}},nH=class extends On{constructor(){super(...arguments);M(this,"schematicDimensions",null)}get config(){return{schematicSymbolName:void 0,componentName:"Jumper",zodProps:u4,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let t=super._getSchematicPortArrangement();if(t&&Object.keys(t).length>0)return t;let n=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length),i=this._parsedProps.schDirection??"right";return{leftSize:i==="left"?n:0,rightSize:i==="right"?n:0}}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:n.manufacturerPartNumber,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=t.pcb_component.insert({center:{x:n.pcbX??0,y:n.pcbY??0},width:2,height:3,layer:n.layer??"top",rotation:n.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:n.doNotPlace??!1,obstructs_within_bounds:n.obstructsWithinBounds??!0});this.pcb_component_id=i.pcb_component_id}doInitialPcbTraceRender(){let{db:t}=this.root,n=t.pcb_port.list({pcb_component_id:this.pcb_component_id}),i={};for(let s=0;s<n.length;s++){let a=n[s],c=t.source_port.get(a.source_port_id),l="";if(typeof c?.pin_number=="number")l=c.pin_number.toString();else if(Array.isArray(c?.port_hints)){let u=c.port_hints.find(h=>/^(pin)?\d+$/.test(h));u&&(/^pin\d+$/.test(u)?l=u.replace(/^pin/,""):l=u)}i[l]=a.pcb_port_id}let r=t.pcb_trace.list({pcb_component_id:this.pcb_component_id}),o=s=>{if(s&&typeof s=="string"&&s.startsWith("{PIN")){let a=s.replace("{PIN","").replace("}","");return i[a]||s}return s};for(let s of r)if(s.route)for(let a of s.route)a.route_type==="wire"&&(a.start_pcb_port_id=o(a.start_pcb_port_id),a.end_pcb_port_id=o(a.end_pcb_port_id))}},iH=class extends On{constructor(){super(...arguments);M(this,"schematicDimensions",null)}_getPinNumberFromBridgedPinName(t){return this.selectOne(`port.${t}`,{type:"port"})?._parsedProps.pinNumber??null}get defaultInternallyConnectedPinNames(){if(this._parsedProps.bridged){let t=this.children.filter(n=>n.componentName==="Port").map(n=>n.name);return t.length>0?[t]:[]}return this._parsedProps.bridgedPins??[]}get config(){let t=this._parsedProps??this.props,n=t.pinCount;if(t.pinCount==null&&!t.footprint&&(n=2),t.pinCount==null){let o=(t.bridgedPins??[]).flat().map(l=>this._getPinNumberFromBridgedPinName(l)).filter(l=>l!==null),s=o.length>0?Math.max(...o):0,a=t.pinLabels?Object.keys(t.pinLabels).length:0,c=Math.max(s,a);(c===2||c===3)&&(n=c),n==null&&t.footprint&&[2,3].includes(this.getPortsFromFootprint().length)&&(n=this.getPortsFromFootprint().length)}let i="";n?i+=`solderjumper${n}`:i="solderjumper";let r=[];return Array.isArray(t.bridgedPins)&&t.bridgedPins.length>0?r=Array.from(new Set(t.bridgedPins.flat().map(o=>this._getPinNumberFromBridgedPinName(o)).filter(o=>o!==null))).sort((o,s)=>o-s):t.bridged&&n&&(r=Array.from({length:n},(o,s)=>s+1)),r.length>0&&(i+=`_bridged${r.join("")}`),{schematicSymbolName:t.symbolName??i,componentName:"SolderJumper",zodProps:AF,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let t=super._getSchematicPortArrangement();if(t&&Object.keys(t).length>0)return t;let n=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length);n==null&&!this._parsedProps.footprint&&(n=2);let i=this._parsedProps.schDirection??"right";return{leftSize:i==="left"?n:0,rightSize:i==="right"?n:0}}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:n.manufacturerPartNumber,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=t.pcb_component.insert({center:{x:n.pcbX??0,y:n.pcbY??0},width:2,height:3,layer:n.layer??"top",rotation:n.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:n.doNotPlace??!1,obstructs_within_bounds:n.obstructsWithinBounds??!0});this.pcb_component_id=i.pcb_component_id}doInitialPcbTraceRender(){let{db:t}=this.root,n=t.pcb_port.list({pcb_component_id:this.pcb_component_id}),i={};for(let s=0;s<n.length;s++){let a=n[s],c=t.source_port.get(a.source_port_id),l="";if(typeof c?.pin_number=="number")l=c.pin_number.toString();else if(Array.isArray(c?.port_hints)){let u=c.port_hints.find(h=>/^(pin)?\d+$/.test(h));u&&(/^pin\d+$/.test(u)?l=u.replace(/^pin/,""):l=u)}i[l]=a.pcb_port_id}let r=t.pcb_trace.list({pcb_component_id:this.pcb_component_id}),o=s=>{if(s&&typeof s=="string"&&s.startsWith("{PIN")){let a=s.replace("{PIN","").replace("}","");return i[a]||s}return s};for(let s of r)if(s.route)for(let a of s.route)a.route_type==="wire"&&(a.start_pcb_port_id=o(a.start_pcb_port_id),a.end_pcb_port_id=o(a.end_pcb_port_id))}},rH=class extends On{constructor(){super(...arguments);M(this,"pos",this.portMap.pin1);M(this,"anode",this.portMap.pin1);M(this,"neg",this.portMap.pin2);M(this,"cathode",this.portMap.pin2)}get config(){let t={laser:"laser_diode"},n=this.props.laser?"laser":null;return{schematicSymbolName:n?t[n]:this.props.symbolName??"led",componentName:"Led",zodProps:oz,sourceFtype:"simple_led"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return this._parsedProps.schDisplayValue||this._parsedProps.color||void 0}getFootprinterString(){let t=super.getFootprinterString();return t&&this.props.color?`${t}_color(${this.props.color})`:t}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_led",name:this.name,wave_length:n.wavelength,color:n.color,symbol_display_value:this._getSchematicSymbolDisplayValue(),manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},oH=class extends On{constructor(){super(...arguments);M(this,"pos",this.portMap.pin1);M(this,"positive",this.portMap.pin1);M(this,"neg",this.portMap.pin2);M(this,"negative",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"power_factor_meter_horz",componentName:"PowerSource",zodProps:bz,sourceFtype:"simple_power_source"}}initPorts(){this.add(new ji({name:"pin1",pinNumber:1,aliases:["positive","pos"]})),this.add(new ji({name:"pin2",pinNumber:2,aliases:["negative","neg"]}))}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_power_source",name:this.name,voltage:n.voltage,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},J5t=zn.extend({voltage:oi.optional(),frequency:Wi.optional(),peakToPeakVoltage:oi.optional(),waveShape:p.enum(["sinewave","square","triangle","sawtooth"]).optional(),phase:$e.optional(),dutyCycle:p.number().optional()}),sH=class extends On{constructor(){super(...arguments);M(this,"terminal1",this.portMap.terminal1);M(this,"terminal2",this.portMap.terminal2)}get config(){return{componentName:"VoltageSource",schematicSymbolName:this.props.waveShape==="square"?"square_wave":"ac_voltmeter",zodProps:J5t,sourceFtype:"simple_voltage_source"}}runRenderPhaseForChildren(t){if(!t.startsWith("Pcb"))for(let n of this.children)n.runRenderPhaseForChildren(t),n.runRenderPhase(t)}doInitialPcbComponentRender(){}initPorts(){super.initPorts({additionalAliases:{pin1:["terminal1"],pin2:["terminal2"]}})}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_voltage_source",name:this.name,voltage:n.voltage,frequency:n.frequency,peak_to_peak_voltage:n.peakToPeakVoltage,wave_shape:n.waveShape,phase:n.phase,duty_cycle:n.dutyCycle,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialSimulationRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=this.portMap.terminal1,r=this.portMap.terminal2;t.simulation_voltage_source.insert({type:"simulation_voltage_source",is_dc_source:!1,terminal1_source_port_id:i.source_port_id,terminal2_source_port_id:r.source_port_id,voltage:n.voltage,frequency:n.frequency,peak_to_peak_voltage:n.peakToPeakVoltage,wave_shape:n.waveShape,phase:n.phase,duty_cycle:n.dutyCycle})}},aH=class extends On{constructor(){super(...arguments);M(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Resistor",schematicSymbolName:this.props.symbolName??"boxresistor",zodProps:LF,sourceFtype:"simple_resistor"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return`${ti(this._parsedProps.resistance)}\u03A9`}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.pullupFor,this.props.pullupTo,this.props.pulldownFor,this.props.pulldownTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.pullupFor&&this.props.pullupTo&&(this.add(new ko({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pullupFor})),this.add(new ko({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pullupTo}))),this.props.pulldownFor&&this.props.pulldownTo&&(this.add(new ko({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pulldownFor})),this.add(new ko({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pulldownTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_resistor",name:this.name,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,resistance:n.resistance,display_resistance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}},Q5t=["leftedge","rightedge","topedge","bottomedge","center"],cH=class extends xe{get config(){return{componentName:"Constraint",zodProps:YF}}constructor(e){if(super(e),("xdist"in e||"ydist"in e)&&!("edgeToEdge"in e)&&!("centerToCenter"in e))throw new Error(`edgeToEdge, centerToCenter must be set for xDist or yDist for ${this}`);if("for"in e&&e.for.length<2)throw new Error(`"for" must have at least two selectors for ${this}`)}_getAllReferencedComponents(){let e=[],t=this.getPrimitiveContainer();function n(i){let r=i.split(" ").pop(),o=Q5t.includes(r)?r:void 0,s=o?i.replace(` ${o}`,""):i,a=t.selectOne(s,{pcbPrimitive:!0});a&&e.push({selector:i,component:a,componentSelector:s,edge:o})}for(let i of["left","right","top","bottom"])i in this._parsedProps&&n(this._parsedProps[i]);if("for"in this._parsedProps)for(let i of this._parsedProps.for)n(i);return{componentsWithSelectors:e}}},lH=class extends xe{constructor(){super(...arguments);M(this,"fabrication_note_rect_id",null)}get config(){return{componentName:"FabricationNoteRect",zodProps:lz}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(n.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for FabricationNoteRect. Must be "top" or "bottom".`);let o=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,s=this.getSubcircuit(),a=n.hasStroke??(n.strokeWidth!==void 0&&n.strokeWidth!==null),c=t.pcb_fabrication_note_rect.insert({pcb_component_id:o,layer:r,color:n.color,center:{x:n.pcbX??0,y:n.pcbY??0},width:n.width,height:n.height,stroke_width:n.strokeWidth??1,is_filled:n.isFilled??!1,has_stroke:a,is_stroke_dashed:n.isStrokeDashed??!1,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.fabrication_note_rect_id=c.pcb_fabrication_note_rect_id}getPcbSize(){let{_parsedProps:t}=this;return{width:t.width,height:t.height}}},uH=class extends xe{constructor(){super(...arguments);M(this,"fabrication_note_path_id",null)}get config(){return{componentName:"FabricationNotePath",zodProps:uz}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,n=this.getSubcircuit(),{_parsedProps:i}=this,r=i.layer??"top";if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenPath. Must be "top" or "bottom".`);let o=this._computePcbGlobalTransformBeforeLayout(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=t.pcb_fabrication_note_path.insert({pcb_component_id:s,layer:r,color:i.color,route:i.route.map(c=>{let l=Ae(o,{x:c.x,y:c.y});return{...c,x:l.x,y:l.y}}),stroke_width:i.strokeWidth??.1,subcircuit_id:n?.subcircuit_id??void 0});this.fabrication_note_path_id=a.pcb_fabrication_note_path_id}},pH=class extends xe{get config(){return{componentName:"FabricationNoteText",zodProps:cz}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,n=this.getPrimitiveContainer(),i=this.getSubcircuit();e.pcb_fabrication_note_text.insert({anchor_alignment:t.anchorAlignment,anchor_position:{x:t.pcbX??0,y:t.pcbY??0},font:t.font??"tscircuit2024",font_size:t.fontSize??1,layer:"top",color:t.color,text:t.text??"",pcb_component_id:n.pcb_component_id,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}},hH=class extends xe{constructor(){super(...arguments);M(this,"fabrication_note_dimension_id",null);M(this,"isPcbPrimitive",!0)}get config(){return{componentName:"FabricationNoteDimension",zodProps:pz}}_resolvePoint(t,n){if(typeof t=="string"){let o=this.getSubcircuit().selectOne(t);return o?o._getGlobalPcbPositionBeforeLayout():(this.renderError(`FabricationNoteDimension could not find selector "${t}"`),Ae(n,{x:0,y:0}))}let i=typeof t.x=="string"?parseFloat(t.x):t.x,r=typeof t.y=="string"?parseFloat(t.y):t.y;return Ae(n,{x:i,y:r})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=this._resolvePoint(n.from,i),o=this._resolvePoint(n.to,i),s=this.getSubcircuit(),a=this.getGroup(),{maybeFlipLayer:c}=this._getPcbPrimitiveFlippedHelpers(),l=c(n.layer??"top");if(l!=="top"&&l!=="bottom")throw new Error(`Invalid layer "${l}" for FabricationNoteDimension. Must be "top" or "bottom".`);let u=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,h=n.text??this._formatDistanceText({from:r,to:o,units:n.units??"mm"}),d=t.pcb_fabrication_note_dimension.insert({pcb_component_id:u,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:a?.pcb_group_id??void 0,layer:l,from:r,to:o,text:h,offset:n.offset,font:n.font??"tscircuit2024",font_size:n.fontSize??1,color:n.color,arrow_size:n.arrowSize??1});this.fabrication_note_dimension_id=d.pcb_fabrication_note_dimension_id}getPcbSize(){let t=this._computePcbGlobalTransformBeforeLayout(),n=this._resolvePoint(this._parsedProps.from,t),i=this._resolvePoint(this._parsedProps.to,t);return{width:Math.abs(i.x-n.x),height:Math.abs(i.y-n.y)}}_formatDistanceText({from:t,to:n,units:i}){let r=n.x-t.x,o=n.y-t.y,s=Math.sqrt(r*r+o*o),a=i==="in"?s/25.4:s,c=Math.round(a);if(Math.abs(a-c)<1e-9)return`${c}${i}`;let u=i==="in"?3:2;return`${i==="in"?Number(a.toFixed(u)).toString():a.toFixed(u)}${i}`}},dH=class extends xe{constructor(){super(...arguments);M(this,"pcb_note_line_id",null);M(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteLine",zodProps:$z}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit(),r=this.getGroup(),o=this._computePcbGlobalTransformBeforeLayout(),s=Ae(o,{x:n.x1,y:n.y1}),a=Ae(o,{x:n.x2,y:n.y2}),c=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,l=t.pcb_note_line.insert({pcb_component_id:c,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:r?.pcb_group_id??void 0,x1:s.x,y1:s.y,x2:a.x,y2:a.y,stroke_width:n.strokeWidth??.1,color:n.color,is_dashed:n.isDashed});this.pcb_note_line_id=l.pcb_note_line_id}getPcbSize(){let{_parsedProps:t}=this;return{width:Math.abs(t.x2-t.x1),height:Math.abs(t.y2-t.y1)}}},fH=class extends xe{constructor(){super(...arguments);M(this,"pcb_note_rect_id",null);M(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteRect",zodProps:zz}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=Ae(i,{x:0,y:0}),o=this.getSubcircuit(),s=this.getGroup(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,c=t.pcb_note_rect.insert({pcb_component_id:a,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:s?.pcb_group_id??void 0,center:r,width:n.width,height:n.height,stroke_width:n.strokeWidth??.1,is_filled:n.isFilled??!1,has_stroke:n.hasStroke??!0,is_stroke_dashed:n.isStrokeDashed??!1,color:n.color});this.pcb_note_rect_id=c.pcb_note_rect_id}getPcbSize(){let{_parsedProps:t}=this,n=typeof t.width=="string"?parseFloat(t.width):t.width,i=typeof t.height=="string"?parseFloat(t.height):t.height;return{width:n,height:i}}},mH=class extends xe{constructor(){super(...arguments);M(this,"pcb_note_text_id",null);M(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteText",zodProps:Fz}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=Ae(i,{x:0,y:0}),o=this.getSubcircuit(),s=this.getGroup(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,c=t.pcb_note_text.insert({pcb_component_id:a,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:s?.pcb_group_id??void 0,font:n.font??"tscircuit2024",font_size:n.fontSize??1,text:n.text,anchor_position:r,anchor_alignment:n.anchorAlignment??"center",color:n.color});this.pcb_note_text_id=c.pcb_note_text_id}getPcbSize(){let{_parsedProps:t}=this,n=typeof t.fontSize=="string"?parseFloat(t.fontSize):t.fontSize??1,i=n*.6;return{width:t.text.length*i,height:n}}},_H=class extends xe{constructor(){super(...arguments);M(this,"pcb_note_path_id",null);M(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNotePath",zodProps:Dz}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=this.getSubcircuit(),o=this.getGroup(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,a=n.route.map(l=>{let{x:u,y:h,...d}=l,_=typeof u=="string"?parseFloat(u):u,y=typeof h=="string"?parseFloat(h):h,g=Ae(i,{x:_,y});return{...d,x:g.x,y:g.y}}),c=t.pcb_note_path.insert({pcb_component_id:s,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:o?.pcb_group_id??void 0,route:a,stroke_width:n.strokeWidth??.1,color:n.color});this.pcb_note_path_id=c.pcb_note_path_id}getPcbSize(){let{_parsedProps:t}=this;if(t.route.length===0)return{width:0,height:0};let n=t.route.map(c=>typeof c.x=="string"?parseFloat(c.x):c.x),i=t.route.map(c=>typeof c.y=="string"?parseFloat(c.y):c.y),r=Math.min(...n),o=Math.max(...n),s=Math.min(...i),a=Math.max(...i);return{width:o-r,height:a-s}}},yH=class extends xe{constructor(){super(...arguments);M(this,"pcb_note_dimension_id",null);M(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteDimension",zodProps:Bz}}_resolvePoint(t,n){if(typeof t=="string"){let o=this.getSubcircuit().selectOne(`.${t}`);return o?o._getGlobalPcbPositionBeforeLayout():(this.renderError(`PcbNoteDimension could not find selector "${t}"`),Ae(n,{x:0,y:0}))}let i=typeof t.x=="string"?parseFloat(t.x):t.x,r=typeof t.y=="string"?parseFloat(t.y):t.y;return Ae(n,{x:i,y:r})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=this._resolvePoint(n.from,i),o=this._resolvePoint(n.to,i),s=this.getSubcircuit(),a=this.getGroup(),c=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,l=n.text??this._formatDistanceText({from:r,to:o,units:n.units??"mm"}),u=t.pcb_note_dimension.insert({pcb_component_id:c,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:a?.pcb_group_id??void 0,from:r,to:o,text:l,font:n.font??"tscircuit2024",font_size:n.fontSize??1,color:n.color,arrow_size:n.arrowSize??1});this.pcb_note_dimension_id=u.pcb_note_dimension_id}getPcbSize(){let t=this._computePcbGlobalTransformBeforeLayout(),n=this._resolvePoint(this._parsedProps.from,t),i=this._resolvePoint(this._parsedProps.to,t);return{width:Math.abs(i.x-n.x),height:Math.abs(i.y-n.y)}}_formatDistanceText({from:t,to:n,units:i}){let r=n.x-t.x,o=n.y-t.y,s=Math.sqrt(r*r+o*o),a=i==="in"?s/25.4:s,c=Math.round(a);if(Math.abs(a-c)<1e-9)return`${c}${i}`;let u=i==="in"?3:2;return`${i==="in"?Number(a.toFixed(u)).toString():a.toFixed(u)}${i}`}},gH=class extends iu{constructor(e){super({...e,subcircuit:!0})}},bH=class extends iu{constructor(e){super({...e,subcircuit:!0})}doInitialPcbPrimitiveRender(){if(super.doInitialPcbPrimitiveRender(),this.root?.pcbDisabled)return;let{db:e}=this.root,t=this._parsedProps;if(!this.pcb_group_id)return;let n=e.pcb_group.get(this.pcb_group_id),i=t.paddingLeft??t.padding??0,r=t.paddingRight??t.padding??0,o=t.paddingTop??t.padding??0,s=t.paddingBottom??t.padding??0;e.pcb_group.update(this.pcb_group_id,{width:(n.width??0)+i+r,height:(n.height??0)+o+s,center:{x:n.center.x+(r-i)/2,y:n.center.y+(o-s)/2}})}},xH=class extends xe{constructor(){super(...arguments);M(this,"pcb_breakout_point_id",null);M(this,"matchedPort",null);M(this,"matchedNet",null);M(this,"isPcbPrimitive",!0)}get config(){return{componentName:"BreakoutPoint",zodProps:fz}}_matchConnection(){let{connection:t}=this._parsedProps,n=this.getSubcircuit();n&&(this.matchedPort=n.selectOne(t,{type:"port"}),this.matchedPort||(this.matchedNet=n.selectOne(t,{type:"net"})),!this.matchedPort&&!this.matchedNet&&this.renderError(`Could not find connection target "${t}"`))}_getSourceTraceIdForPort(t){let{db:n}=this.root;return n.source_trace.list().find(r=>r.connected_source_port_ids.includes(t.source_port_id))?.source_trace_id}_getSourceNetIdForPort(t){let{db:n}=this.root;return n.source_trace.list().find(r=>r.connected_source_port_ids.includes(t.source_port_id))?.connected_source_net_ids[0]}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root;this._matchConnection();let{pcbX:n=0,pcbY:i=0}=this._parsedProps,r=this.parent?.getGroup(),o=this.getSubcircuit();if(!r||!r.pcb_group_id)return;let s=t.pcb_breakout_point.insert({pcb_group_id:r.pcb_group_id,subcircuit_id:o?.subcircuit_id??void 0,source_port_id:this.matchedPort?.source_port_id??void 0,source_trace_id:this.matchedPort?this._getSourceTraceIdForPort(this.matchedPort):void 0,source_net_id:this.matchedNet?this.matchedNet.source_net_id:this.matchedPort?this._getSourceNetIdForPort(this.matchedPort):void 0,x:n,y:i});this.pcb_breakout_point_id=s.pcb_breakout_point_id}_getPcbCircuitJsonBounds(){let{pcbX:t=0,pcbY:n=0}=this._parsedProps;return{center:{x:t,y:n},bounds:{left:t,top:n,right:t,bottom:n},width:0,height:0}}_setPositionFromLayout(t){let{db:n}=this.root;this.pcb_breakout_point_id&&n.pcb_breakout_point.update(this.pcb_breakout_point_id,{x:t.x,y:t.y})}getPcbSize(){return{width:0,height:0}}},vH=class extends xe{constructor(){super(...arguments);M(this,"source_net_label_id")}get config(){return{componentName:"NetLabel",zodProps:KF}}_getAnchorSide(){let{_parsedProps:t}=this;if(t.anchorSide)return t.anchorSide;if(!this._resolveConnectsTo())return"right";let i=this._getGlobalSchematicPositionBeforeLayout(),r=this._getConnectedPorts();if(r.length===0)return"right";let o=r[0]._getGlobalSchematicPositionBeforeLayout(),s=o.x-i.x,a=o.y-i.y;if(Math.abs(s)>Math.abs(a)){if(s>0)return"right";if(s<0)return"left"}else{if(a>0)return"top";if(a<0)return"bottom"}return"right"}_getConnectedPorts(){let t=this._resolveConnectsTo();if(!t)return[];let n=[];for(let i of t){let r=this.getSubcircuit().selectOne(i);r&&n.push(r)}return n}computeSchematicPropsTransform(){let{_parsedProps:t}=this;if(t.schX===void 0&&t.schY===void 0){let n=this._getConnectedPorts();if(n.length>0){let i=n[0]._getGlobalSchematicPositionBeforeLayout(),r=Ae(this.parent?.computeSchematicGlobalTransform?.()??Li(),{x:0,y:0});return vn(i.x-r.x,i.y-r.y)}}return super.computeSchematicPropsTransform()}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getSubcircuit().selectOne(`net.${this._getNetName()}`),o=n.anchorSide??"right",s=xc({anchor_position:i,anchor_side:o,text:n.net}),a=t.schematic_net_label.insert({text:n.net,source_net_id:r.source_net_id,anchor_position:i,center:s,anchor_side:this._getAnchorSide()});this.source_net_label_id=a.source_net_id}_resolveConnectsTo(){let{_parsedProps:t}=this,n=t.connectsTo??t.connection;if(Array.isArray(n))return n;if(typeof n=="string")return[n]}_getNetName(){let{_parsedProps:t}=this;return t.net}doInitialCreateNetsFromProps(){let{_parsedProps:t}=this;t.net&&sM(this,[`net.${t.net}`])}doInitialCreateTracesFromNetLabels(){if(this.root?.schematicDisabled)return;let t=this._resolveConnectsTo();if(t)for(let n of t)this.add(new ko({from:n,to:`net.${this._getNetName()}`}))}doInitialSchematicTraceRender(){if(!this.root?._featureMspSchematicTraceRouting||this.root?.schematicDisabled)return;let{db:t}=this.root,n=this._resolveConnectsTo();if(!n||n.length===0)return;let i=this._getGlobalSchematicPositionBeforeLayout(),r=this._getAnchorSide(),s={left:"x-",right:"x+",top:"y+",bottom:"y-"}[r],a=this.getSubcircuit().selectOne(`net.${this._getNetName()}`);for(let c of n){let l=this.getSubcircuit().selectOne(c,{type:"port"});if(!l||!l.schematic_port_id)continue;let u=!1;if(a?.source_net_id){let w=t.source_trace.list().find(S=>S.connected_source_net_ids?.includes(a.source_net_id)&&S.connected_source_port_ids?.includes(l.source_port_id??""));if(w&&(u=t.schematic_trace.list().some(S=>S.source_trace_id===w.source_trace_id)),u)continue}let h=l._getGlobalSchematicPositionAfterLayout(),d=KI(l.facingDirection??"right")??"x+",_=Qa({x:h.x,y:h.y,facingDirection:d},{x:i.x,y:i.y,facingDirection:s});if(!Array.isArray(_)||_.length<2)continue;let y=[];for(let w=0;w<_.length-1;w++)y.push({from:{x:_[w].x,y:_[w].y},to:{x:_[w+1].x,y:_[w+1].y}});let g,x;if(a?.source_net_id&&l.source_port_id){let w=t.source_trace.list().find(S=>S.connected_source_net_ids?.includes(a.source_net_id)&&S.connected_source_port_ids?.includes(l.source_port_id));g=w?.source_trace_id,x=w?.subcircuit_connectivity_map_key||t.source_net.get(a.source_net_id)?.subcircuit_connectivity_map_key}t.schematic_trace.insert({source_trace_id:g,edges:y,junctions:[],subcircuit_connectivity_map_key:x}),t.schematic_port.update(l.schematic_port_id,{is_connected:!0})}}},wH=class extends xe{constructor(){super(...arguments);M(this,"pcb_silkscreen_circle_id",null);M(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenCircle",zodProps:Oz}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(n.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenCircle. Must be "top" or "bottom".`);let o=this._computePcbGlobalTransformBeforeLayout(),s=this.getSubcircuit(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,c=t.pcb_silkscreen_circle.insert({pcb_component_id:a,layer:r,center:{x:n.pcbX??0,y:n.pcbY??0},radius:n.radius,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,stroke_width:n.strokeWidth??.1});this.pcb_silkscreen_circle_id=c.pcb_silkscreen_circle_id}getPcbSize(){let{_parsedProps:t}=this,n=t.radius*2;return{width:n,height:n}}},SH=class extends xe{constructor(){super(...arguments);M(this,"pcb_silkscreen_rect_id",null);M(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenRect",zodProps:Rz}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(n.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenRect. Must be "top" or "bottom".`);let o=this.getSubcircuit(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=t.pcb_silkscreen_rect.insert({pcb_component_id:s,layer:r,center:{x:n.pcbX??0,y:n.pcbY??0},width:n.width,height:n.height,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this?.getGroup()?.pcb_group_id??void 0,stroke_width:n.strokeWidth??.1});this.pcb_silkscreen_rect_id=a.pcb_silkscreen_rect_id}getPcbSize(){let{_parsedProps:t}=this;return{width:t.width,height:t.height}}},PH=class extends xe{constructor(){super(...arguments);M(this,"pcb_silkscreen_line_id",null);M(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenLine",zodProps:Az}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(n.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenLine. Must be "top" or "bottom".`);let o=this.getSubcircuit(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=t.pcb_silkscreen_line.insert({pcb_component_id:s,layer:r,x1:n.x1,y1:n.y1,x2:n.x2,y2:n.y2,stroke_width:n.strokeWidth??.1,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:o?.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_line_id=a.pcb_silkscreen_line_id}getPcbSize(){let{_parsedProps:t}=this,n=Math.abs(t.x2-t.x1),i=Math.abs(t.y2-t.y1);return{width:n,height:i}}},TH=class extends xe{constructor(t){super(t);M(this,"pcb_via_id",null);M(this,"matchedPort",null);M(this,"isPcbPrimitive",!0);M(this,"source_manually_placed_via_id",null);let n=this._getLayers();this._parsedProps.layers=n,this.initPorts()}get config(){return{componentName:"Via",zodProps:hz}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){let{_parsedProps:t}=this;return{width:t.outerDiameter,height:t.outerDiameter}}_getPcbCircuitJsonBounds(){let{db:t}=this.root,n=t.pcb_via.get(this.pcb_via_id),i=this.getPcbSize();return{center:{x:n.x,y:n.y},bounds:{left:n.x-i.width/2,top:n.y-i.height/2,right:n.x+i.width/2,bottom:n.y+i.height/2},width:i.width,height:i.height}}_setPositionFromLayout(t){let{db:n}=this.root;n.pcb_via.update(this.pcb_via_id,{x:t.x,y:t.y})}_getLayers(){let{fromLayer:t="top",toLayer:n="bottom"}=this._parsedProps;return t===n?[t]:[t,n]}initPorts(){let t=this._parsedProps.layers;for(let i of t){let r=new ji({name:i,layer:i});r.registerMatch(this),this.add(r)}let n=new ji({name:"pin1"});n.registerMatch(this),this.add(n)}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalPcbPositionBeforeLayout(),r=this.getSubcircuit(),o=t.pcb_component.insert({center:i,width:n.outerDiameter,height:n.outerDiameter,layer:n.fromLayer??"top",rotation:0,source_component_id:this.source_component_id,subcircuit_id:r?.subcircuit_id??void 0,obstructs_within_bounds:!0});this.pcb_component_id=o.pcb_component_id}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=this.getGroup(),r=this.getSubcircuit(),o=t.source_manually_placed_via.insert({source_group_id:i?.source_group_id,source_net_id:n.net??"",subcircuit_id:r?.subcircuit_id??void 0});this.source_component_id=o.source_manually_placed_via_id}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalPcbPositionBeforeLayout(),r=this.getSubcircuit(),o=t.pcb_via.insert({x:i.x,y:i.y,hole_diameter:n.holeDiameter,outer_diameter:n.outerDiameter,layers:["bottom","top"],from_layer:n.fromLayer||"bottom",to_layer:n.toLayer||"top",subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_via_id=o.pcb_via_id}},IH=class extends xe{constructor(){super(...arguments);M(this,"isPcbPrimitive",!0)}get config(){return{componentName:"CopperPour",zodProps:_z}}getPcbSize(){return{width:0,height:0}}doInitialPcbCopperPourRender(){this.root?.pcbDisabled||this._queueAsyncEffect("PcbCopperPourRender",async()=>{let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit().selectOne(n.connectsTo);if(!i||!i.source_net_id){this.renderError(`Net "${n.connectsTo}" not found for copper pour`);return}let r=t.pcb_board.list()[0];if(!r){this.renderError("No board found for copper pour");return}let o;r.outline&&r.outline.length>0?o=new F.Polygon(r.outline.map(_=>F.point(_.x,_.y))):o=new F.Polygon(new F.Box(r.center.x-r.width/2,r.center.y-r.height/2,r.center.x+r.width/2,r.center.y+r.height/2).toPoints());let s=si(t.toArray()),a=lM(t.toArray(),s).filter(_=>_.layers.includes(n.layer));for(let _ of t.pcb_trace.list())if(_.route)for(let y=0;y<_.route.length-1;y++){let g=_.route[y],x=_.route[y+1];if(g.route_type!=="wire"||x.route_type!=="wire"||g.layer!==n.layer)continue;let w=g.width;if(w===0)continue;let S=Math.hypot(g.x-x.x,g.y-x.y);if(S===0)continue;let C=(g.x+x.x)/2,I=(g.y+x.y)/2,k=Math.atan2(x.y-g.y,x.x-g.x)*180/Math.PI,N=DV({center:{x:C,y:I},width:S,height:w,rotation:k});for(let E of N)a.push({type:"rect",layers:[g.layer],center:E.center,width:E.width,height:E.height,connectedTo:_.source_trace_id?[_.source_trace_id]:[],obstacle_type:"trace"})}let c=[],l=[],u=n.traceMargin??.2,h=n.padMargin??.2;for(let _ of a){if(_.connectedTo.some(w=>s.areIdsConnected(w,i.source_net_id)))continue;if(_.type==="oval"&&_.width===_.height){let w=_.width/2+h;l.push({center:_.center,radius:w});continue}if(_.type==="rect"&&_.width===_.height&&_.connectedTo.length===0){let w=_.width/2;l.push({center:_.center,radius:w});continue}let g=u,x=new F.Box(_.center.x-_.width/2-g,_.center.y-_.height/2-g,_.center.x+_.width/2+g,_.center.y+_.height/2+g);c.push(new F.Polygon(x.toPoints()))}let d=o;if(c.length>0){let _=c.reduce((y,g)=>F.BooleanOperations.unify(y,g));_&&!_.isEmpty()&&(d=F.BooleanOperations.subtract(o,_))}Array.isArray(d)||(d=[d]);for(let _ of d){let y=_.splitToIslands();for(let g of y){if(g.isEmpty())continue;let x=[...g.faces],w=x.find(P=>P.orientation()===F.ORIENTATION.CCW),S=x.filter(P=>P.orientation()===F.ORIENTATION.CW);if(!w)continue;if(!t.pcb_copper_pour){this.renderError("db.pcb_copper_pour not found. The database schema may be outdated.");return}let C=P=>P.edges.map(N=>{let E={x:N.start.x,y:N.start.y};if(N.isArc){let A=Math.tan(N.shape.sweep/4);Math.abs(A)>1e-9&&(E.bulge=A)}return E});w.reverse();let I=C(w),k=S.map(P=>(P.reverse(),{vertices:C(P)}));for(let P of l){let N=F.point(P.center.x,P.center.y);g.contains(N)&&k.push({vertices:[{x:P.center.x,y:P.center.y-P.radius,bulge:1},{x:P.center.x,y:P.center.y+P.radius,bulge:1}]})}t.pcb_copper_pour.insert({shape:"brep",layer:n.layer,brep_shape:{outer_ring:{vertices:I},inner_rings:k},source_net_id:i.source_net_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id??void 0})}}})}},MH=class extends On{get config(){return{componentName:"Battery",schematicSymbolName:this.props.symbolName??"battery",zodProps:WF,sourceFtype:"simple_power_source"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:this.name,ftype:"simple_power_source",capacity:t.capacity,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=n.source_component_id}},CH=class extends On{_getPcbRotationBeforeLayout(){let e=this.props.pcbOrientation==="vertical"?-90:0;return(super._getPcbRotationBeforeLayout()??0)+e}get config(){return{componentName:"PinHeader",zodProps:ZF,shouldRenderAsSchematicBox:!0}}_getImpliedFootprintString(){let e=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:0),t=this._parsedProps.holeDiameter,n=this._parsedProps.platedDiameter,i=this._parsedProps.pitch,r=this._parsedProps.showSilkscreenPinLabels;if(e>0){let o;if(i)!t&&!n?o=`pinrow${e}_p${i}`:o=`pinrow${e}_p${i}_id${t}_od${n}`;else if(!t&&!n)o=`pinrow${e}`;else return null;return r!==!0&&(o+="_nopinlabels"),o}return null}initPorts(){let e=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:1);for(let t=1;t<=e;t++){let n=Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels[t-1]:this._parsedProps.pinLabels?.[`pin${t}`];if(n){let i=Array.isArray(n)?n[0]:n,r=Array.isArray(n)?n.slice(1):[];this.add(new ji({pinNumber:t,name:i,aliases:[`pin${t}`,...r]}))}else this.add(new ji({pinNumber:t,name:`pin${t}`}))}}_getSchematicPortArrangement(){let e=this._parsedProps.pinCount??1,t=this._parsedProps.schFacingDirection??this._parsedProps.facingDirection??"right",n=this._parsedProps.schPinArrangement;return t==="left"?{leftSide:{direction:n?.leftSide?.direction??"top-to-bottom",pins:n?.leftSide?.pins??Array.from({length:e},(i,r)=>`pin${r+1}`)}}:{rightSide:{direction:n?.rightSide?.direction??"top-to-bottom",pins:n?.rightSide?.pins??Array.from({length:e},(i,r)=>`pin${r+1}`)}}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_pin_header",name:this.name,supplier_part_numbers:t.supplierPartNumbers,pin_count:t.pinCount,gender:t.gender,are_pins_interchangeable:!0});this.source_component_id=n.source_component_id}};function t4t(e){switch(e){case"two_ground_pins":return"crystal_4pin";case"ground_pin":return"resonator";case"no_ground":return"crystal";default:return"crystal"}}var EH=class extends On{get config(){return{componentName:"Resonator",schematicSymbolName:this.props.symbolName??t4t(this.props.pinVariant),zodProps:$F,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=t.pinVariant||"no_ground",i=e.source_component.insert({ftype:"simple_resonator",name:this.name,frequency:t.frequency,load_capacitance:t.loadCapacitance,supplier_part_numbers:t.supplierPartNumbers,pin_variant:n,are_pins_interchangeable:n==="no_ground"||n==="ground_pin"});this.source_component_id=i.source_component_id}_getSchematicSymbolDisplayValue(){let e=`${ti(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${e} / ${ti(this._parsedProps.loadCapacitance)}F`:e}},kH=class extends On{constructor(){super(...arguments);M(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Inductor",schematicSymbolName:this.props.symbolName??"inductor",zodProps:nz,sourceFtype:ia.simple_inductor}}_getSchematicSymbolDisplayValue(){return`${ti(this._parsedProps.inductance)}H`}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({name:this.name,ftype:ia.simple_inductor,inductance:n.inductance,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}};function e4t(e){switch(e){case"three_pin":return"potentiometer3";case"two_pin":return"potentiometer2";default:return"potentiometer2"}}var NH=class extends On{get config(){return{componentName:"Potentiometer",schematicSymbolName:this.props.symbolName??e4t(this.props.pinVariant),zodProps:zF,shouldRenderAsSchematicBox:!1}}_getSchematicSymbolDisplayValue(){return`${ti(this._parsedProps.maxResistance)}\u03A9`}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=t.pinVariant||"two_pin",i=e.source_component.insert({ftype:"simple_potentiometer",name:this.name,max_resistance:t.maxResistance,pin_variant:n,are_pins_interchangeable:n==="two_pin"});this.source_component_id=i.source_component_id}},AH=class extends On{get config(){return{componentName:"PushButton",schematicSymbolName:this.props.symbolName??"push_button_normally_open_momentary",zodProps:JF,sourceFtype:ia.simple_push_button}}get defaultInternallyConnectedPinNames(){return[]}initPorts(){super.initPorts({pinCount:2,ignoreSymbolPorts:!0});let e=Qn[this._getSchematicSymbolNameOrThrow()],t=e.ports.find(l=>l.labels.includes("1")),n=e.ports.find(l=>l.labels.includes("2")),i=this.selectAll("port"),r=i.find(l=>l.props.pinNumber===1),o=i.find(l=>l.props.pinNumber===2),s=i.find(l=>l.props.pinNumber===3),a=i.find(l=>l.props.pinNumber===4),{internallyConnectedPins:c}=this._parsedProps;r.schematicSymbolPortDef=t,(!c||c.length===0)&&(o.schematicSymbolPortDef=n);for(let[l,u]of[[2,o],[3,s],[4,a]]){let h=c?.find(([_,y])=>_===`pin${l}`||y===`pin${l}`);if(!h){u.schematicSymbolPortDef=n;break}(h?.[0]===`pin${l}`?h[1]:h?.[0])!=="pin1"&&(u.schematicSymbolPortDef=n)}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:this.name,ftype:ia.simple_push_button,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=n.source_component_id}},RH=class extends On{get config(){return{schematicSymbolName:this.props.symbolName??(this.props.pinVariant==="four_pin"?"crystal_4pin":"crystal"),componentName:"Crystal",zodProps:DF,sourceFtype:"simple_crystal"}}initPorts(){let e=this.props.pinVariant==="four_pin"?{pin1:["left1","1"],pin2:["top1","2","gnd1"],pin3:["right1","3"],pin4:["bottom1","4","gnd2"]}:{pin1:["pos","left"],pin2:["neg","right"]};super.initPorts({additionalAliases:e})}_getSchematicSymbolDisplayValue(){let e=`${ti(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${e} / ${ti(this._parsedProps.loadCapacitance)}F`:e}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:this.name,ftype:"simple_crystal",frequency:t.frequency,load_capacitance:t.loadCapacitance,pin_variant:t.pinVariant||"two_pin",are_pins_interchangeable:(t.pinVariant||"two_pin")==="two_pin"});this.source_component_id=n.source_component_id}},OH=class extends On{constructor(){super(...arguments);M(this,"emitter",this.portMap.pin1);M(this,"collector",this.portMap.pin2);M(this,"base",this.portMap.pin3)}get config(){let t=this.props.type==="npn"?"npn_bipolar_transistor":"pnp_bipolar_transistor";return{componentName:"Transistor",schematicSymbolName:this.props.symbolName??t,zodProps:tz,sourceFtype:"simple_transistor",shouldRenderAsSchematicBox:!1}}initPorts(){let t={pin1:["collector","c"],pin2:["emitter","e"],pin3:["base","b"]};super.initPorts({pinCount:3,additionalAliases:t})}doInitialCreateNetsFromProps(){this._createNetsFromProps([...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_transistor",name:this.name,transistor_type:n.type});this.source_component_id=i.source_component_id}},LH=class extends On{get config(){let e=this.props.mosfetMode==="depletion"?"d":"e",n=`${this.props.channelType}_channel_${e}_mosfet_transistor`;return{componentName:"Mosfet",schematicSymbolName:this.props.symbolName??n,zodProps:ez,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_mosfet",name:this.name,mosfet_mode:t.mosfetMode,channel_type:t.channelType});this.source_component_id=n.source_component_id}};function n4t(e){return e.simSwitchFrequency!==void 0||e.simCloseAt!==void 0||e.simOpenAt!==void 0||e.simStartClosed!==void 0||e.simStartOpen!==void 0}var FH=class extends On{_getSwitchType(){let e=this._parsedProps;return e?e.dpdt?"dpdt":e.spst?"spst":e.spdt?"spdt":e.dpst?"dpst":e.type??"spst":"spst"}get config(){let e=this._getSwitchType(),t=this._parsedProps?.isNormallyClosed??!1,n={spst:t?"spst_normally_closed_switch":"spst_switch",spdt:t?"spdt_normally_closed_switch":"spdt_switch",dpst:t?"dpst_normally_closed_switch":"dpst_switch",dpdt:t?"dpdt_normally_closed_switch":"dpdt_switch"};return{componentName:"Switch",schematicSymbolName:this.props.symbolName??n[e],zodProps:az,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:e}=this.root,t=this._parsedProps??{},n=e.source_component.insert({ftype:"simple_switch",name:this.name,are_pins_interchangeable:this._getSwitchType()==="spst"});this.source_component_id=n.source_component_id}doInitialSimulationRender(){let{_parsedProps:e}=this;if(!n4t(e))return;let{db:t}=this.root,n={type:"simulation_switch",source_component_id:this.source_component_id||""};e.simSwitchFrequency!==void 0&&(n.switching_frequency=Wi.parse(e.simSwitchFrequency)),e.simCloseAt!==void 0&&(n.closes_at=qi.parse(e.simCloseAt)),e.simOpenAt!==void 0&&(n.opens_at=qi.parse(e.simOpenAt)),e.simStartOpen!==void 0&&(n.starts_closed=!e.simStartOpen),e.simStartClosed!==void 0&&(n.starts_closed=e.simStartClosed),t.simulation_switch.insert(n)}},qI={HOLE_DIAMETER:.5,SMT_CIRCLE_DIAMETER:1.2,SMT_RECT_SIZE:2},zH=class extends On{get config(){return{componentName:"TestPoint",schematicSymbolName:this.props.symbolName??"testpoint",zodProps:dz,sourceFtype:ia.simple_test_point}}_getPropsWithDefaults(){let{padShape:e,holeDiameter:t,footprintVariant:n,padDiameter:i,width:r,height:o}=this._parsedProps;return!n&&t&&(n="through_hole"),n??(n="through_hole"),e??(e="circle"),n==="pad"?e==="circle"?i??(i=qI.SMT_CIRCLE_DIAMETER):e==="rect"&&(r??(r=qI.SMT_RECT_SIZE),o??(o=r)):n==="through_hole"&&(t??(t=qI.HOLE_DIAMETER)),{padShape:e,holeDiameter:t,footprintVariant:n,padDiameter:i,width:r,height:o}}_getImpliedFootprintString(){let{padShape:e,holeDiameter:t,footprintVariant:n,padDiameter:i,width:r,height:o}=this._getPropsWithDefaults();if(n==="through_hole")return`platedhole_d${t}`;if(n==="pad"){if(e==="circle")return`smtpad_circle_d${i}`;if(e==="rect")return`smtpad_rect_w${r}_h${o}`}throw new Error(`Footprint variant "${n}" with pad shape "${e}" not implemented`)}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,{padShape:n,holeDiameter:i,footprintVariant:r,padDiameter:o,width:s,height:a}=this._getPropsWithDefaults(),c=e.source_component.insert({ftype:ia.simple_test_point,name:this.name,supplier_part_numbers:t.supplierPartNumbers,footprint_variant:r,pad_shape:n,pad_diameter:o,hole_diameter:i,width:s,height:a,are_pins_interchangeable:!0});this.source_component_id=c.source_component_id}},DH=class extends xe{constructor(){super(...arguments);M(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicText",zodProps:Iz}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout();t.schematic_text.insert({anchor:n.anchor??"center",text:n.text,font_size:n.fontSize,color:n.color||"#000000",position:{x:i.x,y:i.y},rotation:n.schRotation??0})}},$H=class extends xe{constructor(){super(...arguments);M(this,"isSchematicPrimitive",!0);M(this,"schematic_line_id")}get config(){return{componentName:"SchematicLine",zodProps:Tz}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,o=t.schematic_line.insert({schematic_component_id:r,x1:n.x1+i.x,y1:n.y1+i.y,x2:n.x2+i.x,y2:n.y2+i.y,stroke_width:n.strokeWidth??yx,color:n.color??_x,is_dashed:!1,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_line_id=o.schematic_line_id}},BH=class extends xe{constructor(){super(...arguments);M(this,"isSchematicPrimitive",!0);M(this,"schematic_rect_id")}get config(){return{componentName:"SchematicRect",zodProps:Pz}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,o=t.schematic_rect.insert({center:{x:i.x,y:i.y},width:n.width,height:n.height,stroke_width:n.strokeWidth??yx,color:n.color??_x,is_filled:n.isFilled,schematic_component_id:r,is_dashed:n.isDashed,rotation:n.rotation??0,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_rect_id=o.schematic_rect_id}},jH=class extends xe{constructor(){super(...arguments);M(this,"isSchematicPrimitive",!0);M(this,"schematic_arc_id")}get config(){return{componentName:"SchematicArc",zodProps:vz}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,o=t.schematic_arc.insert({schematic_component_id:r,center:{x:n.center.x+i.x,y:n.center.y+i.y},radius:n.radius,start_angle_degrees:n.startAngleDegrees,end_angle_degrees:n.endAngleDegrees,direction:n.direction,stroke_width:n.strokeWidth??yx,color:n.color??_x,is_dashed:n.isDashed,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_arc_id=o.schematic_arc_id}},YH=class extends xe{constructor(){super(...arguments);M(this,"isSchematicPrimitive",!0);M(this,"schematic_circle_id")}get config(){return{componentName:"SchematicCircle",zodProps:Sz}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,o=t.schematic_circle.insert({schematic_component_id:r,center:{x:n.center.x+i.x,y:n.center.y+i.y},radius:n.radius,stroke_width:n.strokeWidth??yx,color:n.color??_x,is_filled:n.isFilled,fill_color:n.fillColor,is_dashed:n.isDashed,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_circle_id=o.schematic_circle_id}};function i4t({anchor:e,x:t,y:n,width:i,height:r,isInside:o}){switch(e){case"top_left":return{x:t,y:n+r,textAnchor:o?"top_left":"bottom_left"};case"top_center":return{x:t+i/2,y:n+r,textAnchor:o?"top_center":"bottom_center"};case"top_right":return{x:t+i,y:n+r,textAnchor:o?"top_right":"bottom_right"};case"center_left":return{x:t,y:n+r/2,textAnchor:o?"center_left":"center_right"};case"center":return{x:t+i/2,y:n+r/2,textAnchor:"center"};case"center_right":return{x:t+i,y:n+r/2,textAnchor:o?"center_right":"center_left"};case"bottom_left":return{x:t,y:n,textAnchor:o?"bottom_left":"top_left"};case"bottom_center":return{x:t+i/2,y:n,textAnchor:o?"bottom_center":"top_center"};case"bottom_right":return{x:t+i,y:n,textAnchor:o?"bottom_right":"top_right"};default:return{x:t+i/2,y:n+r,textAnchor:"center"}}}var XH=class extends xe{constructor(){super(...arguments);M(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicBox",zodProps:wz,shouldRenderAsSchematicBox:!0}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=.6,r=typeof n.padding=="number"?n.padding:0,o=typeof n.paddingTop=="number"?n.paddingTop:r,s=typeof n.paddingBottom=="number"?n.paddingBottom:r,a=typeof n.paddingLeft=="number"?n.paddingLeft:r,c=typeof n.paddingRight=="number"?n.paddingRight:r,l=n.overlay&&n.overlay.length>0,u=typeof n.width=="number"&&typeof n.height=="number",h,d,_,y,g,x;if(l){let S=n.overlay.map(et=>({selector:et,port:this.getSubcircuit().selectOne(et,{type:"port"})})).filter(({port:et})=>et!=null).map(({port:et})=>({position:et._getGlobalSchematicPositionAfterLayout()}));if(S.length===0)return;let C=S.map(et=>et.position.x),I=S.map(et=>et.position.y),k=Math.min(...C),P=Math.max(...C),N=Math.min(...I),E=Math.max(...I),A=P-k,O=E-N,$=A===0?i:0,B=O===0?i:0,H=a+$/2,X=c+$/2,U=o+B/2,tt=s+B/2,J=k-H,V=P+X,rt=N-tt,K=E+U;h=V-J,d=K-rt,_=J+(n.schX??0),y=rt+(n.schY??0),g=_+h/2,x=y+d/2}else if(u){h=n.width,d=n.height;let w=this._getGlobalSchematicPositionBeforeLayout();g=w.x,x=w.y,_=g-h/2,y=x-d/2}else return;if(t.schematic_box.insert({height:d,width:h,x:_,y,is_dashed:n.strokeStyle==="dashed"}),n.title){let w=n.titleInside,S=.1,C=n.titleAlignment,I=i4t({anchor:C,x:_,y,width:h,height:d,isInside:w}),k,P,N=I.textAnchor;w?(k=C.includes("top")?-S:C.includes("bottom")?S:0,P=C.includes("left")?S:C.includes("right")?-S:0):(k=C.includes("top")?S:C.includes("bottom")?-S:0,P=C.includes("center_left")?-S:C.includes("center_right")?S:0);let E=I.x+P,A=I.y+k;t.schematic_text.insert({anchor:N,text:n.title,font_size:n.titleFontSize??.18,color:n.titleColor??"#000000",position:{x:E,y:A},rotation:0})}}},VH=class extends xe{constructor(){super(...arguments);M(this,"isSchematicPrimitive",!0);M(this,"schematic_table_id",null)}get config(){return{componentName:"SchematicTable",zodProps:Mz}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.children.filter(d=>d.componentName==="SchematicRow");if(i.length===0)return;let r=[],o=0;for(let d of i){let _=d.children.filter(y=>y.componentName==="SchematicCell");o=Math.max(o,_.length)}for(let d=0;d<i.length;d++)r[d]=[];for(let d=0;d<i.length;d++){let y=i[d].children.filter(x=>x.componentName==="SchematicCell"),g=0;for(let x=0;x<y.length;x++){for(;r[d][g];)g++;let w=y[x],S=w._parsedProps.colSpan??1,C=w._parsedProps.rowSpan??1;for(let I=0;I<C;I++)for(let k=0;k<S;k++)r[d+I]||(r[d+I]=[]),r[d+I][g+k]=w;g+=S}}o=Math.max(0,...r.map(d=>d.length));let s=i.map((d,_)=>d._parsedProps.height??1),a=Array.from({length:o},(d,_)=>{let y=0;for(let g=0;g<i.length;g++){let x=r[g]?.[_];if(x){let w=x._parsedProps.text??x._parsedProps.children,S=x._parsedProps.width??(w?.length??2)*.5;S>y&&(y=S)}}return y||10}),c=this._getGlobalSchematicPositionBeforeLayout(),l=t.schematic_table.insert({anchor_position:c,column_widths:a,row_heights:s,cell_padding:n.cellPadding,border_width:n.borderWidth,anchor:n.anchor,subcircuit_id:this.getSubcircuit()?.subcircuit_id||"",schematic_component_id:this.parent?.schematic_component_id||""});this.schematic_table_id=l.schematic_table_id;let u=new Set,h=0;for(let d=0;d<i.length;d++){let _=0;for(let y=0;y<o;y++){let g=r[d]?.[y];if(g&&!u.has(g)){u.add(g);let x=g._parsedProps,w=x.rowSpan??1,S=x.colSpan??1,C=0;for(let k=0;k<S;k++)C+=a[y+k];let I=0;for(let k=0;k<w;k++)I+=s[d+k];t.schematic_table_cell.insert({schematic_table_id:this.schematic_table_id,start_row_index:d,end_row_index:d+w-1,start_column_index:y,end_column_index:y+S-1,text:x.text??x.children,center:{x:c.x+_+C/2,y:c.y-h-I/2},width:C,height:I,horizontal_align:x.horizontalAlign,vertical_align:x.verticalAlign,font_size:x.fontSize??n.fontSize,subcircuit_id:this.getSubcircuit()?.subcircuit_id||""})}a[y]&&(_+=a[y])}h+=s[d]}}},HH=class extends xe{constructor(){super(...arguments);M(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicRow",zodProps:Cz}}},GH=class extends xe{constructor(){super(...arguments);M(this,"isSchematicPrimitive",!0);M(this,"canHaveTextChildren",!0)}get config(){return{componentName:"SchematicCell",zodProps:Ez}}},UH=class extends xe{constructor(){super(...arguments);M(this,"isPrimitiveContainer",!0)}get config(){return{componentName:"Symbol",zodProps:qF}}},qH=class extends xe{get config(){return{componentName:"AnalogSimulation",zodProps:QF}}doInitialSimulationRender(){let{db:e}=this.root,{duration:t,timePerStep:n}=this._parsedProps,i=t||10,r=n||.01;e.simulation_experiment.insert({name:"spice_transient_analysis",experiment_type:"spice_transient_analysis",end_time_ms:i,time_per_step:r})}},WH=class extends xe{constructor(){super(...arguments);M(this,"simulation_voltage_probe_id",null)}get config(){return{componentName:"VoltageProbe",zodProps:xz}}doInitialSimulationRender(){let{db:t}=this.root,{connectsTo:n,name:i}=this._parsedProps,r=this.getSubcircuit();if(!r){this.renderError("VoltageProbe must be inside a subcircuit");return}let o=Array.isArray(n)?n:[n];if(o.length!==1){this.renderError("VoltageProbe must connect to exactly one port or net");return}let s=o[0],a=r.selectOne(s,{type:"port"}),c=a?null:r.selectOne(s,{type:"net"});if(c&&c.componentName!=="Net"){this.renderError(`VoltageProbe connection target "${s}" resolved to a non-net component "${c.componentName}".`);return}if(!a&&!c){this.renderError(`VoltageProbe could not find connection target "${s}"`);return}let{simulation_voltage_probe_id:l}=t.simulation_voltage_probe.insert({name:i??this.name,source_port_id:a?.source_port_id??void 0,source_net_id:c?.source_net_id??void 0,subcircuit_id:r.subcircuit_id||void 0});this.simulation_voltage_probe_id=l}},r4t={name:"@tscircuit/core",type:"module",version:"0.0.822",types:"dist/index.d.ts",main:"dist/index.js",module:"dist/index.js",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist"],repository:{type:"git",url:"https://github.com/tscircuit/core"},scripts:{build:"tsup-node index.ts --format esm --dts",format:"biome format . --write","measure-bundle":"howfat -r table .","pkg-pr-new-release":"bunx pkg-pr-new publish --comment=off --peerDeps","smoke-test:dist":"bun run scripts/smoke-tests/test-dist-simple-circuit.tsx","build:benchmarking":"bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist","build:benchmarking:watch":`chokidar "./{benchmarking,lib}/**/*.{ts,tsx}" -c 'bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist'`,"start:benchmarking":'concurrently "bun run build:benchmarking:watch" "live-server ./benchmarking-dist"'},devDependencies:{"@biomejs/biome":"^1.8.3","@resvg/resvg-js":"^2.6.2","@tscircuit/capacity-autorouter":"^0.0.132","@tscircuit/checks":"^0.0.85","@tscircuit/circuit-json-util":"^0.0.72","@tscircuit/common":"^0.0.14","@tscircuit/footprinter":"^0.0.236","@tscircuit/import-snippet":"^0.0.4","@tscircuit/infgrid-ijump-astar":"^0.0.33","@tscircuit/log-soup":"^1.0.2","@tscircuit/matchpack":"^0.0.16","@tscircuit/math-utils":"^0.0.29","@tscircuit/miniflex":"^0.0.4","@tscircuit/props":"0.0.378","@tscircuit/schematic-autolayout":"^0.0.6","@tscircuit/schematic-match-adapt":"^0.0.16","@tscircuit/schematic-trace-solver":"^0.0.41","@types/bun":"^1.2.16","@types/debug":"^4.1.12","@types/react":"^19.1.8","@types/react-dom":"^19.1.6","@types/react-reconciler":"^0.28.9","bpc-graph":"^0.0.57","bun-match-svg":"0.0.12","calculate-elbow":"^0.0.12","chokidar-cli":"^3.0.0","circuit-json":"^0.0.288","circuit-json-to-bpc":"^0.0.13","circuit-json-to-connectivity-map":"^0.0.22","circuit-json-to-gltf":"^0.0.31","circuit-json-to-simple-3d":"^0.0.9","circuit-json-to-spice":"^0.0.15","circuit-to-svg":"^0.0.253",concurrently:"^9.1.2","connectivity-map":"^1.0.0",debug:"^4.3.6",flatbush:"^4.5.0","graphics-debug":"^0.0.60",howfat:"^0.3.8","live-server":"^1.2.2","looks-same":"^9.0.1",minicssgrid:"^0.0.9","pkg-pr-new":"^0.0.37",poppygl:"^0.0.16",react:"^19.1.0","react-dom":"^19.1.0","schematic-symbols":"^0.0.202",spicey:"^0.0.10","ts-expect":"^1.3.0",tsup:"^8.2.4"},peerDependencies:{"@tscircuit/capacity-autorouter":"*","@tscircuit/checks":"*","@tscircuit/circuit-json-util":"*","@tscircuit/footprinter":"*","@tscircuit/infgrid-ijump-astar":"*","@tscircuit/math-utils":"*","@tscircuit/props":"*","@tscircuit/schematic-autolayout":"*","@tscircuit/schematic-match-adapt":"*","circuit-json-to-bpc":"*","bpc-graph":"*","@tscircuit/matchpack":"*","circuit-json":"*","circuit-json-to-connectivity-map":"*","schematic-symbols":"*",typescript:"^5.0.0"},dependencies:{"@flatten-js/core":"^1.6.2","@lume/kiwi":"^0.4.3","calculate-packing":"0.0.50","css-select":"5.1.0","format-si-unit":"^0.0.3",nanoid:"^5.0.7","performance-now":"^2.1.0","react-reconciler":"^0.32.0","transformation-matrix":"^2.16.1",zod:"^3.25.67"}},Rh=class{constructor({platform:e,projectUrl:t}={}){M(this,"firstChild",null);M(this,"children");M(this,"db");M(this,"root",null);M(this,"isRoot",!0);M(this,"schematicDisabled",!1);M(this,"pcbDisabled",!1);M(this,"pcbRoutingDisabled",!1);M(this,"_featureMspSchematicTraceRouting",!0);M(this,"name");M(this,"platform");M(this,"projectUrl");M(this,"_hasRenderedAtleastOnce",!1);M(this,"_eventListeners",{});this.children=[],this.db=Re([]),this.root=this,this.platform=e,this.projectUrl=t,this.pcbDisabled=e?.pcbDisabled??!1}add(e){let t;(0,ZH.isValidElement)(e)?t=MV(e):t=e,this.children.push(t)}_getBoard(){let e=this.children.find(t=>t.componentName==="Board");if(e)return e}_guessRootComponent(){if(this.firstChild)return;if(this.children.length===0)throw new Error("Not able to guess root component: RootCircuit has no children (use circuit.add(...))");let e=this.children.filter(n=>n.lowercaseComponentName==="panel");if(e.length>1)throw new Error("Only one <panel> is allowed per circuit");if(e.length===1){if(this.children.length!==1)throw new Error("<panel> must be the root element of the circuit");this.firstChild=e[0];return}if(this.children.length===1&&this.children[0].isGroup){this.firstChild=this.children[0];return}let t=new iu({subcircuit:!0});t.parent=this,t.addAll(this.children),this.children=[t],this.firstChild=t}render(){this.firstChild||this._guessRootComponent();let{firstChild:e,db:t}=this;if(!e)throw new Error("RootCircuit has no root component");e.parent=this,e.runRenderCycle(),this._hasRenderedAtleastOnce=!0}async renderUntilSettled(){for(this.db.source_project_metadata.list()?.[0]||this.db.source_project_metadata.insert({software_used_string:`@tscircuit/core@${this.getCoreVersion()}`,...this.projectUrl?{project_url:this.projectUrl}:{}}),this.render();this._hasIncompleteAsyncEffects();)await new Promise(t=>setTimeout(t,100)),this.render();this.emit("renderComplete")}_hasIncompleteAsyncEffects(){return this.children.some(e=>e._hasIncompleteAsyncEffects()?!0:e.children.some(t=>t._hasIncompleteAsyncEffects()))}getCircuitJson(){return this._hasRenderedAtleastOnce||this.render(),this.db.toArray()}toJson(){return this.getCircuitJson()}async getSvg(e){let t=await Promise.resolve().then(()=>(ZX(),WX)).catch(n=>{throw new Error(`To use circuit.getSvg, you must install the "circuit-to-svg" package.
|
|
244
|
+
`),a={x:n.center.x+n.width/2-.25,y:n.center.y-n.height/2+1};this.root.db.pcb_silkscreen_text.insert({pcb_component_id:this.pcb_board_id,layer:"top",font:"tscircuit2024",font_size:.45,text:r,ccw_rotation:0,anchor_alignment:"bottom_right",anchor_position:a})}doInitialSourceRender(){super.doInitialSourceRender();let{db:t}=this.root,n=t.source_board.insert({source_group_id:this.source_group_id,title:this.props.title||this.props.name});this.source_board_id=n.source_board_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=n.width??0,r=n.height??0,o={x:(n.pcbX??0)+(n.outlineOffsetX??0),y:(n.pcbY??0)+(n.outlineOffsetY??0)},{boardAnchorPosition:s,boardAnchorAlignment:a}=n;if(s&&(o=t5t({boardAnchorPosition:s,boardAnchorAlignment:a??"center",width:i,height:r})),n.outline){let u=n.outline.map(x=>x.x),h=n.outline.map(x=>x.y),d=Math.min(...u),_=Math.max(...u),y=Math.min(...h),g=Math.max(...h);i=_-d,r=g-y,o={x:(d+_)/2+(n.outlineOffsetX??0),y:(y+g)/2+(n.outlineOffsetY??0)}}let c=n.outline;!c&&n.borderRadius!=null&&i>0&&r>0&&(c=vV(i,r,n.borderRadius));let l=t.pcb_board.insert({center:o,thickness:this.boardThickness,num_layers:this.allLayers.length,width:i,height:r,outline:c?.map(u=>({x:u.x+(n.outlineOffsetX??0),y:u.y+(n.outlineOffsetY??0)})),material:n.material});this.pcb_board_id=l.pcb_board_id,this._addBoardInformationToSilkscreen()}removePcbComponentRender(){let{db:t}=this.root;this.pcb_board_id&&(t.pcb_board.delete(this.pcb_board_id),this.pcb_board_id=null)}_computePcbGlobalTransformBeforeLayout(){return Li()}doInitialPcbDesignRuleChecks(){this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled")||super.doInitialPcbDesignRuleChecks()}updatePcbDesignRuleChecks(){if(this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;let{db:t}=this.root;if(!this._areChildSubcircuitsRouted()||this._drcChecksComplete)return;this._drcChecksComplete=!0;let n=LY(t.toArray());for(let l of n)t.pcb_trace_error.insert(l);let i=OY(t.toArray());for(let l of i)t.pcb_port_not_connected_error.insert(l);let r=DY(t.toArray());for(let l of r)t.pcb_component_outside_board_error.insert(l);let o=jY(t.toArray());for(let l of o)t.pcb_trace_error.insert(l);let s=BY(t.toArray());for(let l of s)t.pcb_via_clearance_error.insert(l);let a=$Y(t.toArray());for(let l of a)t.pcb_via_clearance_error.insert(l);let c=YY(t.toArray());for(let l of c)t.pcb_footprint_overlap_error.insert(l)}_emitRenderLifecycleEvent(t,n){super._emitRenderLifecycleEvent(t,n),n==="start"&&this.root?.emit("board:renderPhaseStarted",{renderId:this._renderId,phase:t})}},KV=class extends iu{get config(){return{componentName:"Panel",zodProps:kF}}get isGroup(){return!0}add(e){if(e.lowercaseComponentName!=="board")throw new Error("<panel> can only contain <board> elements");super.add(e)}runRenderCycle(){if(!this.children.some(e=>e.componentName==="Board"))throw new Error("<panel> must contain at least one <board>");super.runRenderCycle()}},K5t=new Proxy({},{get:(e,t)=>t}),ia=K5t,_x="rgba(132, 0, 0)",yx=.12,JV=class extends On{constructor(){super(...arguments);M(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Capacitor",schematicSymbolName:this.props.polarized?"capacitor_polarized":this.props.symbolName??"capacitor",zodProps:BF,sourceFtype:ia.simple_capacitor}}initPorts(){typeof this.props.footprint=="string"?super.initPorts({additionalAliases:{pin1:["anode","pos"],pin2:["cathode","neg"]}}):super.initPorts()}_getSchematicSymbolDisplayValue(){let t=this.props.capacitance,n=typeof t=="string"?t:`${ti(this._parsedProps.capacitance)}F`;return this._parsedProps.schShowRatings&&this._parsedProps.maxVoltageRating?`${n}/${ti(this._parsedProps.maxVoltageRating)}V`:n}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.decouplingFor,this.props.decouplingTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.decouplingFor&&this.props.decouplingTo&&(this.add(new ko({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.decouplingFor})),this.add(new ko({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.decouplingTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_capacitor",name:this.name,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,capacitance:n.capacitance,max_voltage_rating:n.maxVoltageRating,max_decoupling_trace_length:n.maxDecouplingTraceLength,display_capacitance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!n.polarized});this.source_component_id=i.source_component_id}},gx=class extends On{constructor(t){super(t);M(this,"schematicBoxDimensions",null)}get config(){return{componentName:"Chip",zodProps:Bp,shouldRenderAsSchematicBox:!0}}initPorts(t={}){super.initPorts(t);let{_parsedProps:n}=this;if(n.externallyConnectedPins){let i=new Set;for(let[r,o]of n.externallyConnectedPins)i.add(r),i.add(o);for(let r of i)if(!this.children.find(s=>s instanceof ji&&s.isMatchingAnyOf([r]))){let s=r.match(/^pin(\d+)$/);if(s){let a=parseInt(s[1]);this.add(new ji({pinNumber:a,aliases:[r]}))}else this.add(new ji({name:r,aliases:[r]}))}}}doInitialSchematicComponentRender(){let{_parsedProps:t}=this;t?.noSchematicRepresentation!==!0&&super.doInitialSchematicComponentRender()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:n.manufacturerPartNumber,supplier_part_numbers:n.supplierPartNumbers});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=n.layer??"top";if(i!=="top"&&i!=="bottom"){let o=this.getSubcircuit(),s=bp.parse({type:"pcb_component_invalid_layer_error",message:`Component cannot be placed on layer '${i}'. Components can only be placed on 'top' or 'bottom' layers.`,source_component_id:this.source_component_id,layer:i,subcircuit_id:o.subcircuit_id??void 0});t.pcb_component_invalid_layer_error.insert(s)}let r=t.pcb_component.insert({center:{x:n.pcbX??0,y:n.pcbY??0},width:2,height:3,layer:i==="top"||i==="bottom"?i:"top",rotation:n.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:n.doNotPlace??!1,obstructs_within_bounds:n.obstructsWithinBounds??!0});this.pcb_component_id=r.pcb_component_id}doInitialCreateTracesFromProps(){let{_parsedProps:t}=this;if(t.externallyConnectedPins)for(let[n,i]of t.externallyConnectedPins)this.add(new ko({from:`${this.getSubcircuitSelector()} > port.${n}`,to:`${this.getSubcircuitSelector()} > port.${i}`}));this._createTracesFromConnectionsProp()}doInitialSimulationRender(){let{db:t}=this.root,{pinAttributes:n}=this.props;if(!n)return;let i=null,r=null,o,s=this.selectAll("port");for(let h of s)for(let d of h.getNameAndAliases())if(n[d]){let _=n[d];_.providesPower&&(i=h,o=_.providesVoltage),_.providesGround&&(r=h)}if(!i||!r||o===void 0)return;let a=t.source_port.get(i.source_port_id);if(!a?.subcircuit_connectivity_map_key)return;let c=t.source_port.get(r.source_port_id);if(!c?.subcircuit_connectivity_map_key)return;let l=t.source_net.getWhere({subcircuit_connectivity_map_key:a.subcircuit_connectivity_map_key}),u=t.source_net.getWhere({subcircuit_connectivity_map_key:c.subcircuit_connectivity_map_key});!l||!u||t.simulation_voltage_source.insert({type:"simulation_voltage_source",positive_source_port_id:i.source_port_id,positive_source_net_id:l.source_net_id,negative_source_port_id:r.source_port_id,negative_source_net_id:u.source_net_id,voltage:o})}},QV=class extends gx{constructor(e){super(e)}get config(){return{...super.config,componentName:"Pinout",zodProps:NF}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_pinout",name:this.name,manufacturer_part_number:t.manufacturerPartNumber,supplier_part_numbers:t.supplierPartNumbers});this.source_component_id=n.source_component_id}},tH=class extends On{constructor(){super(...arguments);M(this,"pos",this.portMap.pin1);M(this,"anode",this.portMap.pin1);M(this,"neg",this.portMap.pin2);M(this,"cathode",this.portMap.pin2)}get config(){let t={schottky:"schottky_diode",avalanche:"avalanche_diode",zener:"zener_diode",photodiode:"photodiode"},n=this.props.schottky?"schottky":this.props.avalanche?"avalanche":this.props.zener?"zener":this.props.photo?"photodiode":null;return{schematicSymbolName:n?t[n]:this.props.symbolName??"diode",componentName:"Diode",zodProps:iz,sourceFtype:"simple_diode"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_diode",name:this.name,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},eH=class extends On{get config(){return{componentName:"fuse",schematicSymbolName:this.props.symbolName??"fuse",zodProps:RF,sourceFtype:ia.simple_fuse}}_getSchematicSymbolDisplayValue(){let e=this._parsedProps.currentRating,t=this._parsedProps.voltageRating,n=typeof e=="string"?parseFloat(e):e,i=typeof t=="string"?parseFloat(t):t;return`${ti(n)}A / ${ti(i)}V`}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=typeof t.currentRating=="string"?parseFloat(t.currentRating):t.currentRating,i=typeof t.voltageRating=="string"?parseFloat(t.voltageRating):t.voltageRating,r=e.source_component.insert({name:this.name,ftype:ia.simple_fuse,current_rating_amps:n,voltage_rating_volts:i,display_current_rating:`${ti(n)}A`,display_voltage_rating:`${ti(i)}V`});this.source_component_id=r.source_component_id}},nH=class extends On{constructor(){super(...arguments);M(this,"schematicDimensions",null)}get config(){return{schematicSymbolName:void 0,componentName:"Jumper",zodProps:u4,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let t=super._getSchematicPortArrangement();if(t&&Object.keys(t).length>0)return t;let n=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length),i=this._parsedProps.schDirection??"right";return{leftSize:i==="left"?n:0,rightSize:i==="right"?n:0}}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:n.manufacturerPartNumber,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=t.pcb_component.insert({center:{x:n.pcbX??0,y:n.pcbY??0},width:2,height:3,layer:n.layer??"top",rotation:n.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:n.doNotPlace??!1,obstructs_within_bounds:n.obstructsWithinBounds??!0});this.pcb_component_id=i.pcb_component_id}doInitialPcbTraceRender(){let{db:t}=this.root,n=t.pcb_port.list({pcb_component_id:this.pcb_component_id}),i={};for(let s=0;s<n.length;s++){let a=n[s],c=t.source_port.get(a.source_port_id),l="";if(typeof c?.pin_number=="number")l=c.pin_number.toString();else if(Array.isArray(c?.port_hints)){let u=c.port_hints.find(h=>/^(pin)?\d+$/.test(h));u&&(/^pin\d+$/.test(u)?l=u.replace(/^pin/,""):l=u)}i[l]=a.pcb_port_id}let r=t.pcb_trace.list({pcb_component_id:this.pcb_component_id}),o=s=>{if(s&&typeof s=="string"&&s.startsWith("{PIN")){let a=s.replace("{PIN","").replace("}","");return i[a]||s}return s};for(let s of r)if(s.route)for(let a of s.route)a.route_type==="wire"&&(a.start_pcb_port_id=o(a.start_pcb_port_id),a.end_pcb_port_id=o(a.end_pcb_port_id))}},iH=class extends On{constructor(){super(...arguments);M(this,"schematicDimensions",null)}_getPinNumberFromBridgedPinName(t){return this.selectOne(`port.${t}`,{type:"port"})?._parsedProps.pinNumber??null}get defaultInternallyConnectedPinNames(){if(this._parsedProps.bridged){let t=this.children.filter(n=>n.componentName==="Port").map(n=>n.name);return t.length>0?[t]:[]}return this._parsedProps.bridgedPins??[]}get config(){let t=this._parsedProps??this.props,n=t.pinCount;if(t.pinCount==null&&!t.footprint&&(n=2),t.pinCount==null){let o=(t.bridgedPins??[]).flat().map(l=>this._getPinNumberFromBridgedPinName(l)).filter(l=>l!==null),s=o.length>0?Math.max(...o):0,a=t.pinLabels?Object.keys(t.pinLabels).length:0,c=Math.max(s,a);(c===2||c===3)&&(n=c),n==null&&t.footprint&&[2,3].includes(this.getPortsFromFootprint().length)&&(n=this.getPortsFromFootprint().length)}let i="";n?i+=`solderjumper${n}`:i="solderjumper";let r=[];return Array.isArray(t.bridgedPins)&&t.bridgedPins.length>0?r=Array.from(new Set(t.bridgedPins.flat().map(o=>this._getPinNumberFromBridgedPinName(o)).filter(o=>o!==null))).sort((o,s)=>o-s):t.bridged&&n&&(r=Array.from({length:n},(o,s)=>s+1)),r.length>0&&(i+=`_bridged${r.join("")}`),{schematicSymbolName:t.symbolName??i,componentName:"SolderJumper",zodProps:AF,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let t=super._getSchematicPortArrangement();if(t&&Object.keys(t).length>0)return t;let n=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length);n==null&&!this._parsedProps.footprint&&(n=2);let i=this._parsedProps.schDirection??"right";return{leftSize:i==="left"?n:0,rightSize:i==="right"?n:0}}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:n.manufacturerPartNumber,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=t.pcb_component.insert({center:{x:n.pcbX??0,y:n.pcbY??0},width:2,height:3,layer:n.layer??"top",rotation:n.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:n.doNotPlace??!1,obstructs_within_bounds:n.obstructsWithinBounds??!0});this.pcb_component_id=i.pcb_component_id}doInitialPcbTraceRender(){let{db:t}=this.root,n=t.pcb_port.list({pcb_component_id:this.pcb_component_id}),i={};for(let s=0;s<n.length;s++){let a=n[s],c=t.source_port.get(a.source_port_id),l="";if(typeof c?.pin_number=="number")l=c.pin_number.toString();else if(Array.isArray(c?.port_hints)){let u=c.port_hints.find(h=>/^(pin)?\d+$/.test(h));u&&(/^pin\d+$/.test(u)?l=u.replace(/^pin/,""):l=u)}i[l]=a.pcb_port_id}let r=t.pcb_trace.list({pcb_component_id:this.pcb_component_id}),o=s=>{if(s&&typeof s=="string"&&s.startsWith("{PIN")){let a=s.replace("{PIN","").replace("}","");return i[a]||s}return s};for(let s of r)if(s.route)for(let a of s.route)a.route_type==="wire"&&(a.start_pcb_port_id=o(a.start_pcb_port_id),a.end_pcb_port_id=o(a.end_pcb_port_id))}},rH=class extends On{constructor(){super(...arguments);M(this,"pos",this.portMap.pin1);M(this,"anode",this.portMap.pin1);M(this,"neg",this.portMap.pin2);M(this,"cathode",this.portMap.pin2)}get config(){let t={laser:"laser_diode"},n=this.props.laser?"laser":null;return{schematicSymbolName:n?t[n]:this.props.symbolName??"led",componentName:"Led",zodProps:oz,sourceFtype:"simple_led"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return this._parsedProps.schDisplayValue||this._parsedProps.color||void 0}getFootprinterString(){let t=super.getFootprinterString();return t&&this.props.color?`${t}_color(${this.props.color})`:t}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_led",name:this.name,wave_length:n.wavelength,color:n.color,symbol_display_value:this._getSchematicSymbolDisplayValue(),manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},oH=class extends On{constructor(){super(...arguments);M(this,"pos",this.portMap.pin1);M(this,"positive",this.portMap.pin1);M(this,"neg",this.portMap.pin2);M(this,"negative",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"power_factor_meter_horz",componentName:"PowerSource",zodProps:bz,sourceFtype:"simple_power_source"}}initPorts(){this.add(new ji({name:"pin1",pinNumber:1,aliases:["positive","pos"]})),this.add(new ji({name:"pin2",pinNumber:2,aliases:["negative","neg"]}))}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_power_source",name:this.name,voltage:n.voltage,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},J5t=zn.extend({voltage:oi.optional(),frequency:Wi.optional(),peakToPeakVoltage:oi.optional(),waveShape:p.enum(["sinewave","square","triangle","sawtooth"]).optional(),phase:$e.optional(),dutyCycle:p.number().optional()}),sH=class extends On{constructor(){super(...arguments);M(this,"terminal1",this.portMap.terminal1);M(this,"terminal2",this.portMap.terminal2)}get config(){return{componentName:"VoltageSource",schematicSymbolName:this.props.waveShape==="square"?"square_wave":"ac_voltmeter",zodProps:J5t,sourceFtype:"simple_voltage_source"}}runRenderPhaseForChildren(t){if(!t.startsWith("Pcb"))for(let n of this.children)n.runRenderPhaseForChildren(t),n.runRenderPhase(t)}doInitialPcbComponentRender(){}initPorts(){super.initPorts({additionalAliases:{pin1:["terminal1"],pin2:["terminal2"]}})}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_voltage_source",name:this.name,voltage:n.voltage,frequency:n.frequency,peak_to_peak_voltage:n.peakToPeakVoltage,wave_shape:n.waveShape,phase:n.phase,duty_cycle:n.dutyCycle,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialSimulationRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=this.portMap.terminal1,r=this.portMap.terminal2;t.simulation_voltage_source.insert({type:"simulation_voltage_source",is_dc_source:!1,terminal1_source_port_id:i.source_port_id,terminal2_source_port_id:r.source_port_id,voltage:n.voltage,frequency:n.frequency,peak_to_peak_voltage:n.peakToPeakVoltage,wave_shape:n.waveShape,phase:n.phase,duty_cycle:n.dutyCycle})}},aH=class extends On{constructor(){super(...arguments);M(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Resistor",schematicSymbolName:this.props.symbolName??"boxresistor",zodProps:LF,sourceFtype:"simple_resistor"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return`${ti(this._parsedProps.resistance)}\u03A9`}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.pullupFor,this.props.pullupTo,this.props.pulldownFor,this.props.pulldownTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.pullupFor&&this.props.pullupTo&&(this.add(new ko({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pullupFor})),this.add(new ko({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pullupTo}))),this.props.pulldownFor&&this.props.pulldownTo&&(this.add(new ko({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pulldownFor})),this.add(new ko({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pulldownTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_resistor",name:this.name,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,resistance:n.resistance,display_resistance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}},Q5t=["leftedge","rightedge","topedge","bottomedge","center"],cH=class extends xe{get config(){return{componentName:"Constraint",zodProps:YF}}constructor(e){if(super(e),("xdist"in e||"ydist"in e)&&!("edgeToEdge"in e)&&!("centerToCenter"in e))throw new Error(`edgeToEdge, centerToCenter must be set for xDist or yDist for ${this}`);if("for"in e&&e.for.length<2)throw new Error(`"for" must have at least two selectors for ${this}`)}_getAllReferencedComponents(){let e=[],t=this.getPrimitiveContainer();function n(i){let r=i.split(" ").pop(),o=Q5t.includes(r)?r:void 0,s=o?i.replace(` ${o}`,""):i,a=t.selectOne(s,{pcbPrimitive:!0});a&&e.push({selector:i,component:a,componentSelector:s,edge:o})}for(let i of["left","right","top","bottom"])i in this._parsedProps&&n(this._parsedProps[i]);if("for"in this._parsedProps)for(let i of this._parsedProps.for)n(i);return{componentsWithSelectors:e}}},lH=class extends xe{constructor(){super(...arguments);M(this,"fabrication_note_rect_id",null)}get config(){return{componentName:"FabricationNoteRect",zodProps:lz}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(n.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for FabricationNoteRect. Must be "top" or "bottom".`);let o=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,s=this.getSubcircuit(),a=n.hasStroke??(n.strokeWidth!==void 0&&n.strokeWidth!==null),c=t.pcb_fabrication_note_rect.insert({pcb_component_id:o,layer:r,color:n.color,center:{x:n.pcbX??0,y:n.pcbY??0},width:n.width,height:n.height,stroke_width:n.strokeWidth??1,is_filled:n.isFilled??!1,has_stroke:a,is_stroke_dashed:n.isStrokeDashed??!1,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.fabrication_note_rect_id=c.pcb_fabrication_note_rect_id}getPcbSize(){let{_parsedProps:t}=this;return{width:t.width,height:t.height}}},uH=class extends xe{constructor(){super(...arguments);M(this,"fabrication_note_path_id",null)}get config(){return{componentName:"FabricationNotePath",zodProps:uz}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,n=this.getSubcircuit(),{_parsedProps:i}=this,r=i.layer??"top";if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenPath. Must be "top" or "bottom".`);let o=this._computePcbGlobalTransformBeforeLayout(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=t.pcb_fabrication_note_path.insert({pcb_component_id:s,layer:r,color:i.color,route:i.route.map(c=>{let l=Ae(o,{x:c.x,y:c.y});return{...c,x:l.x,y:l.y}}),stroke_width:i.strokeWidth??.1,subcircuit_id:n?.subcircuit_id??void 0});this.fabrication_note_path_id=a.pcb_fabrication_note_path_id}},pH=class extends xe{get config(){return{componentName:"FabricationNoteText",zodProps:cz}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,n=this.getPrimitiveContainer(),i=this.getSubcircuit();e.pcb_fabrication_note_text.insert({anchor_alignment:t.anchorAlignment,anchor_position:{x:t.pcbX??0,y:t.pcbY??0},font:t.font??"tscircuit2024",font_size:t.fontSize??1,layer:"top",color:t.color,text:t.text??"",pcb_component_id:n.pcb_component_id,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}},hH=class extends xe{constructor(){super(...arguments);M(this,"fabrication_note_dimension_id",null);M(this,"isPcbPrimitive",!0)}get config(){return{componentName:"FabricationNoteDimension",zodProps:pz}}_resolvePoint(t,n){if(typeof t=="string"){let o=this.getSubcircuit().selectOne(t);return o?o._getGlobalPcbPositionBeforeLayout():(this.renderError(`FabricationNoteDimension could not find selector "${t}"`),Ae(n,{x:0,y:0}))}let i=typeof t.x=="string"?parseFloat(t.x):t.x,r=typeof t.y=="string"?parseFloat(t.y):t.y;return Ae(n,{x:i,y:r})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=this._resolvePoint(n.from,i),o=this._resolvePoint(n.to,i),s=this.getSubcircuit(),a=this.getGroup(),{maybeFlipLayer:c}=this._getPcbPrimitiveFlippedHelpers(),l=c(n.layer??"top");if(l!=="top"&&l!=="bottom")throw new Error(`Invalid layer "${l}" for FabricationNoteDimension. Must be "top" or "bottom".`);let u=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,h=n.text??this._formatDistanceText({from:r,to:o,units:n.units??"mm"}),d=t.pcb_fabrication_note_dimension.insert({pcb_component_id:u,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:a?.pcb_group_id??void 0,layer:l,from:r,to:o,text:h,offset:n.offset,font:n.font??"tscircuit2024",font_size:n.fontSize??1,color:n.color,arrow_size:n.arrowSize??1});this.fabrication_note_dimension_id=d.pcb_fabrication_note_dimension_id}getPcbSize(){let t=this._computePcbGlobalTransformBeforeLayout(),n=this._resolvePoint(this._parsedProps.from,t),i=this._resolvePoint(this._parsedProps.to,t);return{width:Math.abs(i.x-n.x),height:Math.abs(i.y-n.y)}}_formatDistanceText({from:t,to:n,units:i}){let r=n.x-t.x,o=n.y-t.y,s=Math.sqrt(r*r+o*o),a=i==="in"?s/25.4:s,c=Math.round(a);if(Math.abs(a-c)<1e-9)return`${c}${i}`;let u=i==="in"?3:2;return`${i==="in"?Number(a.toFixed(u)).toString():a.toFixed(u)}${i}`}},dH=class extends xe{constructor(){super(...arguments);M(this,"pcb_note_line_id",null);M(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteLine",zodProps:$z}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit(),r=this.getGroup(),o=this._computePcbGlobalTransformBeforeLayout(),s=Ae(o,{x:n.x1,y:n.y1}),a=Ae(o,{x:n.x2,y:n.y2}),c=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,l=t.pcb_note_line.insert({pcb_component_id:c,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:r?.pcb_group_id??void 0,x1:s.x,y1:s.y,x2:a.x,y2:a.y,stroke_width:n.strokeWidth??.1,color:n.color,is_dashed:n.isDashed});this.pcb_note_line_id=l.pcb_note_line_id}getPcbSize(){let{_parsedProps:t}=this;return{width:Math.abs(t.x2-t.x1),height:Math.abs(t.y2-t.y1)}}},fH=class extends xe{constructor(){super(...arguments);M(this,"pcb_note_rect_id",null);M(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteRect",zodProps:zz}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=Ae(i,{x:0,y:0}),o=this.getSubcircuit(),s=this.getGroup(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,c=t.pcb_note_rect.insert({pcb_component_id:a,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:s?.pcb_group_id??void 0,center:r,width:n.width,height:n.height,stroke_width:n.strokeWidth??.1,is_filled:n.isFilled??!1,has_stroke:n.hasStroke??!0,is_stroke_dashed:n.isStrokeDashed??!1,color:n.color});this.pcb_note_rect_id=c.pcb_note_rect_id}getPcbSize(){let{_parsedProps:t}=this,n=typeof t.width=="string"?parseFloat(t.width):t.width,i=typeof t.height=="string"?parseFloat(t.height):t.height;return{width:n,height:i}}},mH=class extends xe{constructor(){super(...arguments);M(this,"pcb_note_text_id",null);M(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteText",zodProps:Fz}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=Ae(i,{x:0,y:0}),o=this.getSubcircuit(),s=this.getGroup(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,c=t.pcb_note_text.insert({pcb_component_id:a,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:s?.pcb_group_id??void 0,font:n.font??"tscircuit2024",font_size:n.fontSize??1,text:n.text,anchor_position:r,anchor_alignment:n.anchorAlignment??"center",color:n.color});this.pcb_note_text_id=c.pcb_note_text_id}getPcbSize(){let{_parsedProps:t}=this,n=typeof t.fontSize=="string"?parseFloat(t.fontSize):t.fontSize??1,i=n*.6;return{width:t.text.length*i,height:n}}},_H=class extends xe{constructor(){super(...arguments);M(this,"pcb_note_path_id",null);M(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNotePath",zodProps:Dz}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=this.getSubcircuit(),o=this.getGroup(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,a=n.route.map(l=>{let{x:u,y:h,...d}=l,_=typeof u=="string"?parseFloat(u):u,y=typeof h=="string"?parseFloat(h):h,g=Ae(i,{x:_,y});return{...d,x:g.x,y:g.y}}),c=t.pcb_note_path.insert({pcb_component_id:s,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:o?.pcb_group_id??void 0,route:a,stroke_width:n.strokeWidth??.1,color:n.color});this.pcb_note_path_id=c.pcb_note_path_id}getPcbSize(){let{_parsedProps:t}=this;if(t.route.length===0)return{width:0,height:0};let n=t.route.map(c=>typeof c.x=="string"?parseFloat(c.x):c.x),i=t.route.map(c=>typeof c.y=="string"?parseFloat(c.y):c.y),r=Math.min(...n),o=Math.max(...n),s=Math.min(...i),a=Math.max(...i);return{width:o-r,height:a-s}}},yH=class extends xe{constructor(){super(...arguments);M(this,"pcb_note_dimension_id",null);M(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteDimension",zodProps:Bz}}_resolvePoint(t,n){if(typeof t=="string"){let o=this.getSubcircuit().selectOne(`.${t}`);return o?o._getGlobalPcbPositionBeforeLayout():(this.renderError(`PcbNoteDimension could not find selector "${t}"`),Ae(n,{x:0,y:0}))}let i=typeof t.x=="string"?parseFloat(t.x):t.x,r=typeof t.y=="string"?parseFloat(t.y):t.y;return Ae(n,{x:i,y:r})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=this._resolvePoint(n.from,i),o=this._resolvePoint(n.to,i),s=this.getSubcircuit(),a=this.getGroup(),c=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,l=n.text??this._formatDistanceText({from:r,to:o,units:n.units??"mm"}),u=t.pcb_note_dimension.insert({pcb_component_id:c,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:a?.pcb_group_id??void 0,from:r,to:o,text:l,font:n.font??"tscircuit2024",font_size:n.fontSize??1,color:n.color,arrow_size:n.arrowSize??1});this.pcb_note_dimension_id=u.pcb_note_dimension_id}getPcbSize(){let t=this._computePcbGlobalTransformBeforeLayout(),n=this._resolvePoint(this._parsedProps.from,t),i=this._resolvePoint(this._parsedProps.to,t);return{width:Math.abs(i.x-n.x),height:Math.abs(i.y-n.y)}}_formatDistanceText({from:t,to:n,units:i}){let r=n.x-t.x,o=n.y-t.y,s=Math.sqrt(r*r+o*o),a=i==="in"?s/25.4:s,c=Math.round(a);if(Math.abs(a-c)<1e-9)return`${c}${i}`;let u=i==="in"?3:2;return`${i==="in"?Number(a.toFixed(u)).toString():a.toFixed(u)}${i}`}},gH=class extends iu{constructor(e){super({...e,subcircuit:!0})}},bH=class extends iu{constructor(e){super({...e,subcircuit:!0})}doInitialPcbPrimitiveRender(){if(super.doInitialPcbPrimitiveRender(),this.root?.pcbDisabled)return;let{db:e}=this.root,t=this._parsedProps;if(!this.pcb_group_id)return;let n=e.pcb_group.get(this.pcb_group_id),i=t.paddingLeft??t.padding??0,r=t.paddingRight??t.padding??0,o=t.paddingTop??t.padding??0,s=t.paddingBottom??t.padding??0;e.pcb_group.update(this.pcb_group_id,{width:(n.width??0)+i+r,height:(n.height??0)+o+s,center:{x:n.center.x+(r-i)/2,y:n.center.y+(o-s)/2}})}},xH=class extends xe{constructor(){super(...arguments);M(this,"pcb_breakout_point_id",null);M(this,"matchedPort",null);M(this,"matchedNet",null);M(this,"isPcbPrimitive",!0)}get config(){return{componentName:"BreakoutPoint",zodProps:fz}}_matchConnection(){let{connection:t}=this._parsedProps,n=this.getSubcircuit();n&&(this.matchedPort=n.selectOne(t,{type:"port"}),this.matchedPort||(this.matchedNet=n.selectOne(t,{type:"net"})),!this.matchedPort&&!this.matchedNet&&this.renderError(`Could not find connection target "${t}"`))}_getSourceTraceIdForPort(t){let{db:n}=this.root;return n.source_trace.list().find(r=>r.connected_source_port_ids.includes(t.source_port_id))?.source_trace_id}_getSourceNetIdForPort(t){let{db:n}=this.root;return n.source_trace.list().find(r=>r.connected_source_port_ids.includes(t.source_port_id))?.connected_source_net_ids[0]}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root;this._matchConnection();let{pcbX:n=0,pcbY:i=0}=this._parsedProps,r=this.parent?.getGroup(),o=this.getSubcircuit();if(!r||!r.pcb_group_id)return;let s=t.pcb_breakout_point.insert({pcb_group_id:r.pcb_group_id,subcircuit_id:o?.subcircuit_id??void 0,source_port_id:this.matchedPort?.source_port_id??void 0,source_trace_id:this.matchedPort?this._getSourceTraceIdForPort(this.matchedPort):void 0,source_net_id:this.matchedNet?this.matchedNet.source_net_id:this.matchedPort?this._getSourceNetIdForPort(this.matchedPort):void 0,x:n,y:i});this.pcb_breakout_point_id=s.pcb_breakout_point_id}_getPcbCircuitJsonBounds(){let{pcbX:t=0,pcbY:n=0}=this._parsedProps;return{center:{x:t,y:n},bounds:{left:t,top:n,right:t,bottom:n},width:0,height:0}}_setPositionFromLayout(t){let{db:n}=this.root;this.pcb_breakout_point_id&&n.pcb_breakout_point.update(this.pcb_breakout_point_id,{x:t.x,y:t.y})}getPcbSize(){return{width:0,height:0}}},vH=class extends xe{constructor(){super(...arguments);M(this,"source_net_label_id")}get config(){return{componentName:"NetLabel",zodProps:KF}}_getAnchorSide(){let{_parsedProps:t}=this;if(t.anchorSide)return t.anchorSide;if(!this._resolveConnectsTo())return"right";let i=this._getGlobalSchematicPositionBeforeLayout(),r=this._getConnectedPorts();if(r.length===0)return"right";let o=r[0]._getGlobalSchematicPositionBeforeLayout(),s=o.x-i.x,a=o.y-i.y;if(Math.abs(s)>Math.abs(a)){if(s>0)return"right";if(s<0)return"left"}else{if(a>0)return"top";if(a<0)return"bottom"}return"right"}_getConnectedPorts(){let t=this._resolveConnectsTo();if(!t)return[];let n=[];for(let i of t){let r=this.getSubcircuit().selectOne(i);r&&n.push(r)}return n}computeSchematicPropsTransform(){let{_parsedProps:t}=this;if(t.schX===void 0&&t.schY===void 0){let n=this._getConnectedPorts();if(n.length>0){let i=n[0]._getGlobalSchematicPositionBeforeLayout(),r=Ae(this.parent?.computeSchematicGlobalTransform?.()??Li(),{x:0,y:0});return vn(i.x-r.x,i.y-r.y)}}return super.computeSchematicPropsTransform()}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getSubcircuit().selectOne(`net.${this._getNetName()}`),o=n.anchorSide??"right",s=xc({anchor_position:i,anchor_side:o,text:n.net}),a=t.schematic_net_label.insert({text:n.net,source_net_id:r.source_net_id,anchor_position:i,center:s,anchor_side:this._getAnchorSide()});this.source_net_label_id=a.source_net_id}_resolveConnectsTo(){let{_parsedProps:t}=this,n=t.connectsTo??t.connection;if(Array.isArray(n))return n;if(typeof n=="string")return[n]}_getNetName(){let{_parsedProps:t}=this;return t.net}doInitialCreateNetsFromProps(){let{_parsedProps:t}=this;t.net&&sM(this,[`net.${t.net}`])}doInitialCreateTracesFromNetLabels(){if(this.root?.schematicDisabled)return;let t=this._resolveConnectsTo();if(t)for(let n of t)this.add(new ko({from:n,to:`net.${this._getNetName()}`}))}doInitialSchematicTraceRender(){if(!this.root?._featureMspSchematicTraceRouting||this.root?.schematicDisabled)return;let{db:t}=this.root,n=this._resolveConnectsTo();if(!n||n.length===0)return;let i=this._getGlobalSchematicPositionBeforeLayout(),r=this._getAnchorSide(),s={left:"x-",right:"x+",top:"y+",bottom:"y-"}[r],a=this.getSubcircuit().selectOne(`net.${this._getNetName()}`);for(let c of n){let l=this.getSubcircuit().selectOne(c,{type:"port"});if(!l||!l.schematic_port_id)continue;let u=!1;if(a?.source_net_id){let w=t.source_trace.list().find(S=>S.connected_source_net_ids?.includes(a.source_net_id)&&S.connected_source_port_ids?.includes(l.source_port_id??""));if(w&&(u=t.schematic_trace.list().some(S=>S.source_trace_id===w.source_trace_id)),u)continue}let h=l._getGlobalSchematicPositionAfterLayout(),d=KI(l.facingDirection??"right")??"x+",_=Qa({x:h.x,y:h.y,facingDirection:d},{x:i.x,y:i.y,facingDirection:s});if(!Array.isArray(_)||_.length<2)continue;let y=[];for(let w=0;w<_.length-1;w++)y.push({from:{x:_[w].x,y:_[w].y},to:{x:_[w+1].x,y:_[w+1].y}});let g,x;if(a?.source_net_id&&l.source_port_id){let w=t.source_trace.list().find(S=>S.connected_source_net_ids?.includes(a.source_net_id)&&S.connected_source_port_ids?.includes(l.source_port_id));g=w?.source_trace_id,x=w?.subcircuit_connectivity_map_key||t.source_net.get(a.source_net_id)?.subcircuit_connectivity_map_key}t.schematic_trace.insert({source_trace_id:g,edges:y,junctions:[],subcircuit_connectivity_map_key:x}),t.schematic_port.update(l.schematic_port_id,{is_connected:!0})}}},wH=class extends xe{constructor(){super(...arguments);M(this,"pcb_silkscreen_circle_id",null);M(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenCircle",zodProps:Oz}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(n.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenCircle. Must be "top" or "bottom".`);let o=this._computePcbGlobalTransformBeforeLayout(),s=this.getSubcircuit(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,c=t.pcb_silkscreen_circle.insert({pcb_component_id:a,layer:r,center:{x:n.pcbX??0,y:n.pcbY??0},radius:n.radius,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,stroke_width:n.strokeWidth??.1});this.pcb_silkscreen_circle_id=c.pcb_silkscreen_circle_id}getPcbSize(){let{_parsedProps:t}=this,n=t.radius*2;return{width:n,height:n}}},SH=class extends xe{constructor(){super(...arguments);M(this,"pcb_silkscreen_rect_id",null);M(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenRect",zodProps:Rz}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(n.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenRect. Must be "top" or "bottom".`);let o=this.getSubcircuit(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=t.pcb_silkscreen_rect.insert({pcb_component_id:s,layer:r,center:{x:n.pcbX??0,y:n.pcbY??0},width:n.width,height:n.height,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this?.getGroup()?.pcb_group_id??void 0,stroke_width:n.strokeWidth??.1});this.pcb_silkscreen_rect_id=a.pcb_silkscreen_rect_id}getPcbSize(){let{_parsedProps:t}=this;return{width:t.width,height:t.height}}},PH=class extends xe{constructor(){super(...arguments);M(this,"pcb_silkscreen_line_id",null);M(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenLine",zodProps:Az}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(n.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenLine. Must be "top" or "bottom".`);let o=this.getSubcircuit(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=t.pcb_silkscreen_line.insert({pcb_component_id:s,layer:r,x1:n.x1,y1:n.y1,x2:n.x2,y2:n.y2,stroke_width:n.strokeWidth??.1,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:o?.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_line_id=a.pcb_silkscreen_line_id}getPcbSize(){let{_parsedProps:t}=this,n=Math.abs(t.x2-t.x1),i=Math.abs(t.y2-t.y1);return{width:n,height:i}}},TH=class extends xe{constructor(t){super(t);M(this,"pcb_via_id",null);M(this,"matchedPort",null);M(this,"isPcbPrimitive",!0);M(this,"source_manually_placed_via_id",null);let n=this._getLayers();this._parsedProps.layers=n,this.initPorts()}get config(){return{componentName:"Via",zodProps:hz}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){let{_parsedProps:t}=this;return{width:t.outerDiameter,height:t.outerDiameter}}_getPcbCircuitJsonBounds(){let{db:t}=this.root,n=t.pcb_via.get(this.pcb_via_id),i=this.getPcbSize();return{center:{x:n.x,y:n.y},bounds:{left:n.x-i.width/2,top:n.y-i.height/2,right:n.x+i.width/2,bottom:n.y+i.height/2},width:i.width,height:i.height}}_setPositionFromLayout(t){let{db:n}=this.root;n.pcb_via.update(this.pcb_via_id,{x:t.x,y:t.y})}_getLayers(){let{fromLayer:t="top",toLayer:n="bottom"}=this._parsedProps;return t===n?[t]:[t,n]}initPorts(){let t=this._parsedProps.layers;for(let i of t){let r=new ji({name:i,layer:i});r.registerMatch(this),this.add(r)}let n=new ji({name:"pin1"});n.registerMatch(this),this.add(n)}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalPcbPositionBeforeLayout(),r=this.getSubcircuit(),o=t.pcb_component.insert({center:i,width:n.outerDiameter,height:n.outerDiameter,layer:n.fromLayer??"top",rotation:0,source_component_id:this.source_component_id,subcircuit_id:r?.subcircuit_id??void 0,obstructs_within_bounds:!0});this.pcb_component_id=o.pcb_component_id}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=this.getGroup(),r=this.getSubcircuit(),o=t.source_manually_placed_via.insert({source_group_id:i?.source_group_id,source_net_id:n.net??"",subcircuit_id:r?.subcircuit_id??void 0});this.source_component_id=o.source_manually_placed_via_id}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalPcbPositionBeforeLayout(),r=this.getSubcircuit(),o=t.pcb_via.insert({x:i.x,y:i.y,hole_diameter:n.holeDiameter,outer_diameter:n.outerDiameter,layers:["bottom","top"],from_layer:n.fromLayer||"bottom",to_layer:n.toLayer||"top",subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_via_id=o.pcb_via_id}},IH=class extends xe{constructor(){super(...arguments);M(this,"isPcbPrimitive",!0)}get config(){return{componentName:"CopperPour",zodProps:_z}}getPcbSize(){return{width:0,height:0}}doInitialPcbCopperPourRender(){this.root?.pcbDisabled||this._queueAsyncEffect("PcbCopperPourRender",async()=>{let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit().selectOne(n.connectsTo);if(!i||!i.source_net_id){this.renderError(`Net "${n.connectsTo}" not found for copper pour`);return}let r=t.pcb_board.list()[0];if(!r){this.renderError("No board found for copper pour");return}let o;r.outline&&r.outline.length>0?o=new F.Polygon(r.outline.map(_=>F.point(_.x,_.y))):o=new F.Polygon(new F.Box(r.center.x-r.width/2,r.center.y-r.height/2,r.center.x+r.width/2,r.center.y+r.height/2).toPoints());let s=si(t.toArray()),a=lM(t.toArray(),s).filter(_=>_.layers.includes(n.layer));for(let _ of t.pcb_trace.list())if(_.route)for(let y=0;y<_.route.length-1;y++){let g=_.route[y],x=_.route[y+1];if(g.route_type!=="wire"||x.route_type!=="wire"||g.layer!==n.layer)continue;let w=g.width;if(w===0)continue;let S=Math.hypot(g.x-x.x,g.y-x.y);if(S===0)continue;let C=(g.x+x.x)/2,I=(g.y+x.y)/2,k=Math.atan2(x.y-g.y,x.x-g.x)*180/Math.PI,N=DV({center:{x:C,y:I},width:S,height:w,rotation:k});for(let E of N)a.push({type:"rect",layers:[g.layer],center:E.center,width:E.width,height:E.height,connectedTo:_.source_trace_id?[_.source_trace_id]:[],obstacle_type:"trace"})}let c=[],l=[],u=n.traceMargin??.2,h=n.padMargin??.2;for(let _ of a){if(_.connectedTo.some(w=>s.areIdsConnected(w,i.source_net_id)))continue;if(_.type==="oval"&&_.width===_.height){let w=_.width/2+h;l.push({center:_.center,radius:w});continue}if(_.type==="rect"&&_.width===_.height&&_.connectedTo.length===0){let w=_.width/2;l.push({center:_.center,radius:w});continue}let g=u,x=new F.Box(_.center.x-_.width/2-g,_.center.y-_.height/2-g,_.center.x+_.width/2+g,_.center.y+_.height/2+g);c.push(new F.Polygon(x.toPoints()))}let d=o;if(c.length>0){let _=c.reduce((y,g)=>F.BooleanOperations.unify(y,g));_&&!_.isEmpty()&&(d=F.BooleanOperations.subtract(o,_))}Array.isArray(d)||(d=[d]);for(let _ of d){let y=_.splitToIslands();for(let g of y){if(g.isEmpty())continue;let x=[...g.faces],w=x.find(P=>P.orientation()===F.ORIENTATION.CCW),S=x.filter(P=>P.orientation()===F.ORIENTATION.CW);if(!w)continue;if(!t.pcb_copper_pour){this.renderError("db.pcb_copper_pour not found. The database schema may be outdated.");return}let C=P=>P.edges.map(N=>{let E={x:N.start.x,y:N.start.y};if(N.isArc){let A=Math.tan(N.shape.sweep/4);Math.abs(A)>1e-9&&(E.bulge=A)}return E});w.reverse();let I=C(w),k=S.map(P=>(P.reverse(),{vertices:C(P)}));for(let P of l){let N=F.point(P.center.x,P.center.y);g.contains(N)&&k.push({vertices:[{x:P.center.x,y:P.center.y-P.radius,bulge:1},{x:P.center.x,y:P.center.y+P.radius,bulge:1}]})}t.pcb_copper_pour.insert({shape:"brep",layer:n.layer,brep_shape:{outer_ring:{vertices:I},inner_rings:k},source_net_id:i.source_net_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id??void 0})}}})}},MH=class extends On{get config(){return{componentName:"Battery",schematicSymbolName:this.props.symbolName??"battery",zodProps:WF,sourceFtype:"simple_power_source"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:this.name,ftype:"simple_power_source",capacity:t.capacity,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=n.source_component_id}},CH=class extends On{_getPcbRotationBeforeLayout(){let e=this.props.pcbOrientation==="vertical"?-90:0;return(super._getPcbRotationBeforeLayout()??0)+e}get config(){return{componentName:"PinHeader",zodProps:ZF,shouldRenderAsSchematicBox:!0}}_getImpliedFootprintString(){let e=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:0),t=this._parsedProps.holeDiameter,n=this._parsedProps.platedDiameter,i=this._parsedProps.pitch,r=this._parsedProps.showSilkscreenPinLabels;if(e>0){let o;if(i)!t&&!n?o=`pinrow${e}_p${i}`:o=`pinrow${e}_p${i}_id${t}_od${n}`;else if(!t&&!n)o=`pinrow${e}`;else return null;return r!==!0&&(o+="_nopinlabels"),o}return null}initPorts(){let e=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:1);for(let t=1;t<=e;t++){let n=Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels[t-1]:this._parsedProps.pinLabels?.[`pin${t}`];if(n){let i=Array.isArray(n)?n[0]:n,r=Array.isArray(n)?n.slice(1):[];this.add(new ji({pinNumber:t,name:i,aliases:[`pin${t}`,...r]}))}else this.add(new ji({pinNumber:t,name:`pin${t}`}))}}_getSchematicPortArrangement(){let e=this._parsedProps.pinCount??1,t=this._parsedProps.schFacingDirection??this._parsedProps.facingDirection??"right",n=this._parsedProps.schPinArrangement;return t==="left"?{leftSide:{direction:n?.leftSide?.direction??"top-to-bottom",pins:n?.leftSide?.pins??Array.from({length:e},(i,r)=>`pin${r+1}`)}}:{rightSide:{direction:n?.rightSide?.direction??"top-to-bottom",pins:n?.rightSide?.pins??Array.from({length:e},(i,r)=>`pin${r+1}`)}}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_pin_header",name:this.name,supplier_part_numbers:t.supplierPartNumbers,pin_count:t.pinCount,gender:t.gender,are_pins_interchangeable:!0});this.source_component_id=n.source_component_id}};function t4t(e){switch(e){case"two_ground_pins":return"crystal_4pin";case"ground_pin":return"resonator";case"no_ground":return"crystal";default:return"crystal"}}var EH=class extends On{get config(){return{componentName:"Resonator",schematicSymbolName:this.props.symbolName??t4t(this.props.pinVariant),zodProps:$F,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=t.pinVariant||"no_ground",i=e.source_component.insert({ftype:"simple_resonator",name:this.name,frequency:t.frequency,load_capacitance:t.loadCapacitance,supplier_part_numbers:t.supplierPartNumbers,pin_variant:n,are_pins_interchangeable:n==="no_ground"||n==="ground_pin"});this.source_component_id=i.source_component_id}_getSchematicSymbolDisplayValue(){let e=`${ti(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${e} / ${ti(this._parsedProps.loadCapacitance)}F`:e}},kH=class extends On{constructor(){super(...arguments);M(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Inductor",schematicSymbolName:this.props.symbolName??"inductor",zodProps:nz,sourceFtype:ia.simple_inductor}}_getSchematicSymbolDisplayValue(){return`${ti(this._parsedProps.inductance)}H`}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({name:this.name,ftype:ia.simple_inductor,inductance:n.inductance,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}};function e4t(e){switch(e){case"three_pin":return"potentiometer3";case"two_pin":return"potentiometer2";default:return"potentiometer2"}}var NH=class extends On{get config(){return{componentName:"Potentiometer",schematicSymbolName:this.props.symbolName??e4t(this.props.pinVariant),zodProps:zF,shouldRenderAsSchematicBox:!1}}_getSchematicSymbolDisplayValue(){return`${ti(this._parsedProps.maxResistance)}\u03A9`}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=t.pinVariant||"two_pin",i=e.source_component.insert({ftype:"simple_potentiometer",name:this.name,max_resistance:t.maxResistance,pin_variant:n,are_pins_interchangeable:n==="two_pin"});this.source_component_id=i.source_component_id}},AH=class extends On{get config(){return{componentName:"PushButton",schematicSymbolName:this.props.symbolName??"push_button_normally_open_momentary",zodProps:JF,sourceFtype:ia.simple_push_button}}get defaultInternallyConnectedPinNames(){return[]}initPorts(){super.initPorts({pinCount:2,ignoreSymbolPorts:!0});let e=Qn[this._getSchematicSymbolNameOrThrow()],t=e.ports.find(l=>l.labels.includes("1")),n=e.ports.find(l=>l.labels.includes("2")),i=this.selectAll("port"),r=i.find(l=>l.props.pinNumber===1),o=i.find(l=>l.props.pinNumber===2),s=i.find(l=>l.props.pinNumber===3),a=i.find(l=>l.props.pinNumber===4),{internallyConnectedPins:c}=this._parsedProps;r.schematicSymbolPortDef=t,(!c||c.length===0)&&(o.schematicSymbolPortDef=n);for(let[l,u]of[[2,o],[3,s],[4,a]]){let h=c?.find(([_,y])=>_===`pin${l}`||y===`pin${l}`);if(!h){u.schematicSymbolPortDef=n;break}(h?.[0]===`pin${l}`?h[1]:h?.[0])!=="pin1"&&(u.schematicSymbolPortDef=n)}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:this.name,ftype:ia.simple_push_button,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=n.source_component_id}},RH=class extends On{get config(){return{schematicSymbolName:this.props.symbolName??(this.props.pinVariant==="four_pin"?"crystal_4pin":"crystal"),componentName:"Crystal",zodProps:DF,sourceFtype:"simple_crystal"}}initPorts(){let e=this.props.pinVariant==="four_pin"?{pin1:["left1","1"],pin2:["top1","2","gnd1"],pin3:["right1","3"],pin4:["bottom1","4","gnd2"]}:{pin1:["pos","left"],pin2:["neg","right"]};super.initPorts({additionalAliases:e})}_getSchematicSymbolDisplayValue(){let e=`${ti(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${e} / ${ti(this._parsedProps.loadCapacitance)}F`:e}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:this.name,ftype:"simple_crystal",frequency:t.frequency,load_capacitance:t.loadCapacitance,pin_variant:t.pinVariant||"two_pin",are_pins_interchangeable:(t.pinVariant||"two_pin")==="two_pin"});this.source_component_id=n.source_component_id}},OH=class extends On{constructor(){super(...arguments);M(this,"emitter",this.portMap.pin1);M(this,"collector",this.portMap.pin2);M(this,"base",this.portMap.pin3)}get config(){let t=this.props.type==="npn"?"npn_bipolar_transistor":"pnp_bipolar_transistor";return{componentName:"Transistor",schematicSymbolName:this.props.symbolName??t,zodProps:tz,sourceFtype:"simple_transistor",shouldRenderAsSchematicBox:!1}}initPorts(){let t={pin1:["collector","c"],pin2:["emitter","e"],pin3:["base","b"]};super.initPorts({pinCount:3,additionalAliases:t})}doInitialCreateNetsFromProps(){this._createNetsFromProps([...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_transistor",name:this.name,transistor_type:n.type});this.source_component_id=i.source_component_id}},LH=class extends On{get config(){let e=this.props.mosfetMode==="depletion"?"d":"e",n=`${this.props.channelType}_channel_${e}_mosfet_transistor`;return{componentName:"Mosfet",schematicSymbolName:this.props.symbolName??n,zodProps:ez,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_mosfet",name:this.name,mosfet_mode:t.mosfetMode,channel_type:t.channelType});this.source_component_id=n.source_component_id}};function n4t(e){return e.simSwitchFrequency!==void 0||e.simCloseAt!==void 0||e.simOpenAt!==void 0||e.simStartClosed!==void 0||e.simStartOpen!==void 0}var FH=class extends On{_getSwitchType(){let e=this._parsedProps;return e?e.dpdt?"dpdt":e.spst?"spst":e.spdt?"spdt":e.dpst?"dpst":e.type??"spst":"spst"}get config(){let e=this._getSwitchType(),t=this._parsedProps?.isNormallyClosed??!1,n={spst:t?"spst_normally_closed_switch":"spst_switch",spdt:t?"spdt_normally_closed_switch":"spdt_switch",dpst:t?"dpst_normally_closed_switch":"dpst_switch",dpdt:t?"dpdt_normally_closed_switch":"dpdt_switch"};return{componentName:"Switch",schematicSymbolName:this.props.symbolName??n[e],zodProps:az,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:e}=this.root,t=this._parsedProps??{},n=e.source_component.insert({ftype:"simple_switch",name:this.name,are_pins_interchangeable:this._getSwitchType()==="spst"});this.source_component_id=n.source_component_id}doInitialSimulationRender(){let{_parsedProps:e}=this;if(!n4t(e))return;let{db:t}=this.root,n={type:"simulation_switch",source_component_id:this.source_component_id||""};e.simSwitchFrequency!==void 0&&(n.switching_frequency=Wi.parse(e.simSwitchFrequency)),e.simCloseAt!==void 0&&(n.closes_at=qi.parse(e.simCloseAt)),e.simOpenAt!==void 0&&(n.opens_at=qi.parse(e.simOpenAt)),e.simStartOpen!==void 0&&(n.starts_closed=!e.simStartOpen),e.simStartClosed!==void 0&&(n.starts_closed=e.simStartClosed),t.simulation_switch.insert(n)}},qI={HOLE_DIAMETER:.5,SMT_CIRCLE_DIAMETER:1.2,SMT_RECT_SIZE:2},zH=class extends On{get config(){return{componentName:"TestPoint",schematicSymbolName:this.props.symbolName??"testpoint",zodProps:dz,sourceFtype:ia.simple_test_point}}_getPropsWithDefaults(){let{padShape:e,holeDiameter:t,footprintVariant:n,padDiameter:i,width:r,height:o}=this._parsedProps;return!n&&t&&(n="through_hole"),n??(n="through_hole"),e??(e="circle"),n==="pad"?e==="circle"?i??(i=qI.SMT_CIRCLE_DIAMETER):e==="rect"&&(r??(r=qI.SMT_RECT_SIZE),o??(o=r)):n==="through_hole"&&(t??(t=qI.HOLE_DIAMETER)),{padShape:e,holeDiameter:t,footprintVariant:n,padDiameter:i,width:r,height:o}}_getImpliedFootprintString(){let{padShape:e,holeDiameter:t,footprintVariant:n,padDiameter:i,width:r,height:o}=this._getPropsWithDefaults();if(n==="through_hole")return`platedhole_d${t}`;if(n==="pad"){if(e==="circle")return`smtpad_circle_d${i}`;if(e==="rect")return`smtpad_rect_w${r}_h${o}`}throw new Error(`Footprint variant "${n}" with pad shape "${e}" not implemented`)}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,{padShape:n,holeDiameter:i,footprintVariant:r,padDiameter:o,width:s,height:a}=this._getPropsWithDefaults(),c=e.source_component.insert({ftype:ia.simple_test_point,name:this.name,supplier_part_numbers:t.supplierPartNumbers,footprint_variant:r,pad_shape:n,pad_diameter:o,hole_diameter:i,width:s,height:a,are_pins_interchangeable:!0});this.source_component_id=c.source_component_id}},DH=class extends xe{constructor(){super(...arguments);M(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicText",zodProps:Iz}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout();t.schematic_text.insert({anchor:n.anchor??"center",text:n.text,font_size:n.fontSize,color:n.color||"#000000",position:{x:i.x,y:i.y},rotation:n.schRotation??0})}},$H=class extends xe{constructor(){super(...arguments);M(this,"isSchematicPrimitive",!0);M(this,"schematic_line_id")}get config(){return{componentName:"SchematicLine",zodProps:Tz}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,o=t.schematic_line.insert({schematic_component_id:r,x1:n.x1+i.x,y1:n.y1+i.y,x2:n.x2+i.x,y2:n.y2+i.y,stroke_width:n.strokeWidth??yx,color:n.color??_x,is_dashed:!1,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_line_id=o.schematic_line_id}},BH=class extends xe{constructor(){super(...arguments);M(this,"isSchematicPrimitive",!0);M(this,"schematic_rect_id")}get config(){return{componentName:"SchematicRect",zodProps:Pz}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,o=t.schematic_rect.insert({center:{x:i.x,y:i.y},width:n.width,height:n.height,stroke_width:n.strokeWidth??yx,color:n.color??_x,is_filled:n.isFilled,schematic_component_id:r,is_dashed:n.isDashed,rotation:n.rotation??0,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_rect_id=o.schematic_rect_id}},jH=class extends xe{constructor(){super(...arguments);M(this,"isSchematicPrimitive",!0);M(this,"schematic_arc_id")}get config(){return{componentName:"SchematicArc",zodProps:vz}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,o=t.schematic_arc.insert({schematic_component_id:r,center:{x:n.center.x+i.x,y:n.center.y+i.y},radius:n.radius,start_angle_degrees:n.startAngleDegrees,end_angle_degrees:n.endAngleDegrees,direction:n.direction,stroke_width:n.strokeWidth??yx,color:n.color??_x,is_dashed:n.isDashed,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_arc_id=o.schematic_arc_id}},YH=class extends xe{constructor(){super(...arguments);M(this,"isSchematicPrimitive",!0);M(this,"schematic_circle_id")}get config(){return{componentName:"SchematicCircle",zodProps:Sz}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,o=t.schematic_circle.insert({schematic_component_id:r,center:{x:n.center.x+i.x,y:n.center.y+i.y},radius:n.radius,stroke_width:n.strokeWidth??yx,color:n.color??_x,is_filled:n.isFilled,fill_color:n.fillColor,is_dashed:n.isDashed,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_circle_id=o.schematic_circle_id}};function i4t({anchor:e,x:t,y:n,width:i,height:r,isInside:o}){switch(e){case"top_left":return{x:t,y:n+r,textAnchor:o?"top_left":"bottom_left"};case"top_center":return{x:t+i/2,y:n+r,textAnchor:o?"top_center":"bottom_center"};case"top_right":return{x:t+i,y:n+r,textAnchor:o?"top_right":"bottom_right"};case"center_left":return{x:t,y:n+r/2,textAnchor:o?"center_left":"center_right"};case"center":return{x:t+i/2,y:n+r/2,textAnchor:"center"};case"center_right":return{x:t+i,y:n+r/2,textAnchor:o?"center_right":"center_left"};case"bottom_left":return{x:t,y:n,textAnchor:o?"bottom_left":"top_left"};case"bottom_center":return{x:t+i/2,y:n,textAnchor:o?"bottom_center":"top_center"};case"bottom_right":return{x:t+i,y:n,textAnchor:o?"bottom_right":"top_right"};default:return{x:t+i/2,y:n+r,textAnchor:"center"}}}var XH=class extends xe{constructor(){super(...arguments);M(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicBox",zodProps:wz,shouldRenderAsSchematicBox:!0}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=.6,r=typeof n.padding=="number"?n.padding:0,o=typeof n.paddingTop=="number"?n.paddingTop:r,s=typeof n.paddingBottom=="number"?n.paddingBottom:r,a=typeof n.paddingLeft=="number"?n.paddingLeft:r,c=typeof n.paddingRight=="number"?n.paddingRight:r,l=n.overlay&&n.overlay.length>0,u=typeof n.width=="number"&&typeof n.height=="number",h,d,_,y,g,x;if(l){let S=n.overlay.map(et=>({selector:et,port:this.getSubcircuit().selectOne(et,{type:"port"})})).filter(({port:et})=>et!=null).map(({port:et})=>({position:et._getGlobalSchematicPositionAfterLayout()}));if(S.length===0)return;let C=S.map(et=>et.position.x),I=S.map(et=>et.position.y),k=Math.min(...C),P=Math.max(...C),N=Math.min(...I),E=Math.max(...I),A=P-k,O=E-N,$=A===0?i:0,B=O===0?i:0,H=a+$/2,X=c+$/2,U=o+B/2,tt=s+B/2,J=k-H,V=P+X,rt=N-tt,K=E+U;h=V-J,d=K-rt,_=J+(n.schX??0),y=rt+(n.schY??0),g=_+h/2,x=y+d/2}else if(u){h=n.width,d=n.height;let w=this._getGlobalSchematicPositionBeforeLayout();g=w.x,x=w.y,_=g-h/2,y=x-d/2}else return;if(t.schematic_box.insert({height:d,width:h,x:_,y,is_dashed:n.strokeStyle==="dashed"}),n.title){let w=n.titleInside,S=.1,C=n.titleAlignment,I=i4t({anchor:C,x:_,y,width:h,height:d,isInside:w}),k,P,N=I.textAnchor;w?(k=C.includes("top")?-S:C.includes("bottom")?S:0,P=C.includes("left")?S:C.includes("right")?-S:0):(k=C.includes("top")?S:C.includes("bottom")?-S:0,P=C.includes("center_left")?-S:C.includes("center_right")?S:0);let E=I.x+P,A=I.y+k;t.schematic_text.insert({anchor:N,text:n.title,font_size:n.titleFontSize??.18,color:n.titleColor??"#000000",position:{x:E,y:A},rotation:0})}}},VH=class extends xe{constructor(){super(...arguments);M(this,"isSchematicPrimitive",!0);M(this,"schematic_table_id",null)}get config(){return{componentName:"SchematicTable",zodProps:Mz}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.children.filter(d=>d.componentName==="SchematicRow");if(i.length===0)return;let r=[],o=0;for(let d of i){let _=d.children.filter(y=>y.componentName==="SchematicCell");o=Math.max(o,_.length)}for(let d=0;d<i.length;d++)r[d]=[];for(let d=0;d<i.length;d++){let y=i[d].children.filter(x=>x.componentName==="SchematicCell"),g=0;for(let x=0;x<y.length;x++){for(;r[d][g];)g++;let w=y[x],S=w._parsedProps.colSpan??1,C=w._parsedProps.rowSpan??1;for(let I=0;I<C;I++)for(let k=0;k<S;k++)r[d+I]||(r[d+I]=[]),r[d+I][g+k]=w;g+=S}}o=Math.max(0,...r.map(d=>d.length));let s=i.map((d,_)=>d._parsedProps.height??1),a=Array.from({length:o},(d,_)=>{let y=0;for(let g=0;g<i.length;g++){let x=r[g]?.[_];if(x){let w=x._parsedProps.text??x._parsedProps.children,S=x._parsedProps.width??(w?.length??2)*.5;S>y&&(y=S)}}return y||10}),c=this._getGlobalSchematicPositionBeforeLayout(),l=t.schematic_table.insert({anchor_position:c,column_widths:a,row_heights:s,cell_padding:n.cellPadding,border_width:n.borderWidth,anchor:n.anchor,subcircuit_id:this.getSubcircuit()?.subcircuit_id||"",schematic_component_id:this.parent?.schematic_component_id||""});this.schematic_table_id=l.schematic_table_id;let u=new Set,h=0;for(let d=0;d<i.length;d++){let _=0;for(let y=0;y<o;y++){let g=r[d]?.[y];if(g&&!u.has(g)){u.add(g);let x=g._parsedProps,w=x.rowSpan??1,S=x.colSpan??1,C=0;for(let k=0;k<S;k++)C+=a[y+k];let I=0;for(let k=0;k<w;k++)I+=s[d+k];t.schematic_table_cell.insert({schematic_table_id:this.schematic_table_id,start_row_index:d,end_row_index:d+w-1,start_column_index:y,end_column_index:y+S-1,text:x.text??x.children,center:{x:c.x+_+C/2,y:c.y-h-I/2},width:C,height:I,horizontal_align:x.horizontalAlign,vertical_align:x.verticalAlign,font_size:x.fontSize??n.fontSize,subcircuit_id:this.getSubcircuit()?.subcircuit_id||""})}a[y]&&(_+=a[y])}h+=s[d]}}},HH=class extends xe{constructor(){super(...arguments);M(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicRow",zodProps:Cz}}},GH=class extends xe{constructor(){super(...arguments);M(this,"isSchematicPrimitive",!0);M(this,"canHaveTextChildren",!0)}get config(){return{componentName:"SchematicCell",zodProps:Ez}}},UH=class extends xe{constructor(){super(...arguments);M(this,"isPrimitiveContainer",!0)}get config(){return{componentName:"Symbol",zodProps:qF}}},qH=class extends xe{get config(){return{componentName:"AnalogSimulation",zodProps:QF}}doInitialSimulationRender(){let{db:e}=this.root,{duration:t,timePerStep:n}=this._parsedProps,i=t||10,r=n||.01;e.simulation_experiment.insert({name:"spice_transient_analysis",experiment_type:"spice_transient_analysis",end_time_ms:i,time_per_step:r})}},WH=class extends xe{constructor(){super(...arguments);M(this,"simulation_voltage_probe_id",null)}get config(){return{componentName:"VoltageProbe",zodProps:xz}}doInitialSimulationRender(){let{db:t}=this.root,{connectsTo:n,name:i}=this._parsedProps,r=this.getSubcircuit();if(!r){this.renderError("VoltageProbe must be inside a subcircuit");return}let o=Array.isArray(n)?n:[n];if(o.length!==1){this.renderError("VoltageProbe must connect to exactly one port or net");return}let s=o[0],a=r.selectOne(s,{type:"port"}),c=a?null:r.selectOne(s,{type:"net"});if(c&&c.componentName!=="Net"){this.renderError(`VoltageProbe connection target "${s}" resolved to a non-net component "${c.componentName}".`);return}if(!a&&!c){this.renderError(`VoltageProbe could not find connection target "${s}"`);return}let{simulation_voltage_probe_id:l}=t.simulation_voltage_probe.insert({name:i??this.name,source_port_id:a?.source_port_id??void 0,source_net_id:c?.source_net_id??void 0,subcircuit_id:r.subcircuit_id||void 0});this.simulation_voltage_probe_id=l}},r4t={name:"@tscircuit/core",type:"module",version:"0.0.823",types:"dist/index.d.ts",main:"dist/index.js",module:"dist/index.js",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist"],repository:{type:"git",url:"https://github.com/tscircuit/core"},scripts:{build:"tsup-node index.ts --format esm --dts",format:"biome format . --write","measure-bundle":"howfat -r table .","pkg-pr-new-release":"bunx pkg-pr-new publish --comment=off --peerDeps","smoke-test:dist":"bun run scripts/smoke-tests/test-dist-simple-circuit.tsx","build:benchmarking":"bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist","build:benchmarking:watch":`chokidar "./{benchmarking,lib}/**/*.{ts,tsx}" -c 'bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist'`,"start:benchmarking":'concurrently "bun run build:benchmarking:watch" "live-server ./benchmarking-dist"'},devDependencies:{"@biomejs/biome":"^1.8.3","@resvg/resvg-js":"^2.6.2","@tscircuit/capacity-autorouter":"^0.0.132","@tscircuit/checks":"^0.0.85","@tscircuit/circuit-json-util":"^0.0.72","@tscircuit/common":"^0.0.14","@tscircuit/footprinter":"^0.0.236","@tscircuit/import-snippet":"^0.0.4","@tscircuit/infgrid-ijump-astar":"^0.0.33","@tscircuit/log-soup":"^1.0.2","@tscircuit/matchpack":"^0.0.16","@tscircuit/math-utils":"^0.0.29","@tscircuit/miniflex":"^0.0.4","@tscircuit/props":"0.0.378","@tscircuit/schematic-autolayout":"^0.0.6","@tscircuit/schematic-match-adapt":"^0.0.16","@tscircuit/schematic-trace-solver":"^0.0.41","@types/bun":"^1.2.16","@types/debug":"^4.1.12","@types/react":"^19.1.8","@types/react-dom":"^19.1.6","@types/react-reconciler":"^0.28.9","bpc-graph":"^0.0.57","bun-match-svg":"0.0.12","calculate-elbow":"^0.0.12","chokidar-cli":"^3.0.0","circuit-json":"^0.0.288","circuit-json-to-bpc":"^0.0.13","circuit-json-to-connectivity-map":"^0.0.22","circuit-json-to-gltf":"^0.0.31","circuit-json-to-simple-3d":"^0.0.9","circuit-json-to-spice":"^0.0.15","circuit-to-svg":"^0.0.253",concurrently:"^9.1.2","connectivity-map":"^1.0.0",debug:"^4.3.6",flatbush:"^4.5.0","graphics-debug":"^0.0.60",howfat:"^0.3.8","live-server":"^1.2.2","looks-same":"^9.0.1",minicssgrid:"^0.0.9","pkg-pr-new":"^0.0.37",poppygl:"^0.0.16",react:"^19.1.0","react-dom":"^19.1.0","schematic-symbols":"^0.0.202",spicey:"^0.0.10","ts-expect":"^1.3.0",tsup:"^8.2.4"},peerDependencies:{"@tscircuit/capacity-autorouter":"*","@tscircuit/checks":"*","@tscircuit/circuit-json-util":"*","@tscircuit/footprinter":"*","@tscircuit/infgrid-ijump-astar":"*","@tscircuit/math-utils":"*","@tscircuit/props":"*","@tscircuit/schematic-autolayout":"*","@tscircuit/schematic-match-adapt":"*","circuit-json-to-bpc":"*","bpc-graph":"*","@tscircuit/matchpack":"*","circuit-json":"*","circuit-json-to-connectivity-map":"*","schematic-symbols":"*",typescript:"^5.0.0"},dependencies:{"@flatten-js/core":"^1.6.2","@lume/kiwi":"^0.4.3","calculate-packing":"0.0.50","css-select":"5.1.0","format-si-unit":"^0.0.3",nanoid:"^5.0.7","performance-now":"^2.1.0","react-reconciler":"^0.32.0","transformation-matrix":"^2.16.1",zod:"^3.25.67"}},Rh=class{constructor({platform:e,projectUrl:t}={}){M(this,"firstChild",null);M(this,"children");M(this,"db");M(this,"root",null);M(this,"isRoot",!0);M(this,"schematicDisabled",!1);M(this,"pcbDisabled",!1);M(this,"pcbRoutingDisabled",!1);M(this,"_featureMspSchematicTraceRouting",!0);M(this,"name");M(this,"platform");M(this,"projectUrl");M(this,"_hasRenderedAtleastOnce",!1);M(this,"_eventListeners",{});this.children=[],this.db=Re([]),this.root=this,this.platform=e,this.projectUrl=t,this.pcbDisabled=e?.pcbDisabled??!1}add(e){let t;(0,ZH.isValidElement)(e)?t=MV(e):t=e,this.children.push(t)}_getBoard(){let e=this.children.find(t=>t.componentName==="Board");if(e)return e}_guessRootComponent(){if(this.firstChild)return;if(this.children.length===0)throw new Error("Not able to guess root component: RootCircuit has no children (use circuit.add(...))");let e=this.children.filter(n=>n.lowercaseComponentName==="panel");if(e.length>1)throw new Error("Only one <panel> is allowed per circuit");if(e.length===1){if(this.children.length!==1)throw new Error("<panel> must be the root element of the circuit");this.firstChild=e[0];return}if(this.children.length===1&&this.children[0].isGroup){this.firstChild=this.children[0];return}let t=new iu({subcircuit:!0});t.parent=this,t.addAll(this.children),this.children=[t],this.firstChild=t}render(){this.firstChild||this._guessRootComponent();let{firstChild:e,db:t}=this;if(!e)throw new Error("RootCircuit has no root component");e.parent=this,e.runRenderCycle(),this._hasRenderedAtleastOnce=!0}async renderUntilSettled(){for(this.db.source_project_metadata.list()?.[0]||this.db.source_project_metadata.insert({software_used_string:`@tscircuit/core@${this.getCoreVersion()}`,...this.projectUrl?{project_url:this.projectUrl}:{}}),this.render();this._hasIncompleteAsyncEffects();)await new Promise(t=>setTimeout(t,100)),this.render();this.emit("renderComplete")}_hasIncompleteAsyncEffects(){return this.children.some(e=>e._hasIncompleteAsyncEffects()?!0:e.children.some(t=>t._hasIncompleteAsyncEffects()))}getCircuitJson(){return this._hasRenderedAtleastOnce||this.render(),this.db.toArray()}toJson(){return this.getCircuitJson()}async getSvg(e){let t=await Promise.resolve().then(()=>(ZX(),WX)).catch(n=>{throw new Error(`To use circuit.getSvg, you must install the "circuit-to-svg" package.
|
|
245
245
|
|
|
246
246
|
"${n.message}"`)});if(e.view==="pcb")return t.convertCircuitJsonToPcbSvg(this.getCircuitJson());if(e.view==="schematic")return t.convertCircuitJsonToSchematicSvg(this.getCircuitJson());throw new Error(`Invalid view: ${e.view}`)}getCoreVersion(){let[e,t,n]=r4t.version.split(".").map(Number);return`${e}.${t}.${n+1}`}async preview(e){let t=typeof e=="object"?e:{previewName:e};throw new Error("project.preview is not yet implemented")}computeSchematicGlobalTransform(){return Li()}_computePcbGlobalTransformBeforeLayout(){return Li()}selectAll(e){return this._guessRootComponent(),this.firstChild?.selectAll(e)??[]}selectOne(e,t){return this._guessRootComponent(),this.firstChild?.selectOne(e,t)??null}emit(e,...t){if(this._eventListeners[e])for(let n of this._eventListeners[e])n(...t)}on(e,t){this._eventListeners[e]||(this._eventListeners[e]=[]),this._eventListeners[e].push(t)}removeListener(e,t){this._eventListeners[e]&&(this._eventListeners[e]=this._eventListeners[e].filter(n=>n!==t))}enableDebug(e){typeof e=="string"?nM.default.enable(e):(e===null||e===!1)&&nM.default.disable()}getClientOrigin(){return typeof window<"u"&&window.location?window.location.origin:typeof self<"u"&&self.location?self.location.origin:""}},o4t=Rh,s4t=Rh,a4t=e=>{let[t,n]=Eh.default.useState(!0),[i,r]=Eh.default.useState(null),[o,s]=Eh.default.useState(),[a,c]=Eh.default.useState();return Eh.default.useEffect(()=>{n(!0),r(null),e&&setTimeout(()=>{try{let l=new Rh;l.add(e),s(l),c(l.toJson())}catch(l){r(l)}n(!1)},1)},[e]),{isLoading:t,error:i,circuit:o,circuitJson:a}},Oh=(e,t)=>(n,i)=>{let r=[];Array.isArray(t)?r.push(...t.flat()):typeof t=="object"&&r.push(...Object.values(t).flat(),...Object.keys(t));let o=s=>{if(s?.name&&s.name!==n)throw new Error(`Component name mismatch. Hook name: ${n}, Component prop name: ${s.name}`);let a={...i,...s,name:n},c=[];for(let l of r)if(a[l]){let u=`.${n} > .${l}`,h=a[l];c.push({from:u,to:h}),delete a[l]}return(0,nu.jsxs)(nu.Fragment,{children:[(0,nu.jsx)(e,{...a}),c.map((l,u)=>(0,nu.jsx)("trace",{...l},u))]})};for(let s of r)o[s]=`.${n} > .${s}`;return o},c4t=Oh(e=>(0,KH.jsx)("capacitor",{...e}),jF),l4t=e=>Oh(t=>(0,JH.jsx)("chip",{pinLabels:e,...t}),e),u4t=Oh(e=>(0,QH.jsx)("diode",{...e}),rz),p4t=Oh(e=>(0,tG.jsx)("led",{...e}),sz),h4t=Oh(e=>(0,eG.jsx)("resistor",{...e}),FF),d4t=new Proxy(e=>new Proxy({},{get:(t,n)=>`.${e} > .${n}`}),{get:(e,t)=>{let n=(...i)=>{let r=i[0];return new Proxy({},{get:(o,s)=>`.${t} > .${s}`})};return new Proxy(n,{get:(i,r)=>t==="net"?`net.${r}`:t==="subcircuit"?new Proxy({},{get:(o,s)=>new Proxy({},{get:(a,c)=>`subcircuit.${r} > .${s} > .${c}`})}):`.${t} > .${r}`,apply:(i,r,o)=>t==="net"?new Proxy({},{get:(s,a)=>`net.${a}`}):new Proxy({},{get:(s,a)=>{let c=`.${t} > .${a}`;return["U","J","CN"].some(u=>t.startsWith(u))?c:new Proxy(new String(c),{get:(u,h)=>typeof h=="symbol"||h==="toString"?()=>c:`.${t} > .${a} > .${h}`})}})})}});IV(wV);IV({Bug:gx});var wG=Vt(vo(),1);var iG=e=>{let t=e.match(/:[RC]_(\d{4})_/);if(t||(t=e.match(/:(SOIC-\d+|SOT-\d+|SOD-\d+|SSOP-\d+|TSSOP-\d+|QFP-\d+|QFN-\d+)/),t))return t[1]};var dM=e=>e.includes("cap")?e.replace(/cap/g,""):e;var rG=e=>{if(e){if(e.startsWith("kicad:")){let t=iG(e);return t?dM(t):e}return dM(e)}};var fM=new Map,ar=async(e,t)=>{let n=new URLSearchParams({...t,json:"true"}).toString();if(fM.has(n))return fM.get(n);let r=await(await fetch(`https://jlcsearch.tscircuit.com/${e}/list?${n}`)).json();return fM.set(n,r),r},cr=e=>e?[...e].sort((t,n)=>Number(n.is_basic??!1)-Number(t.is_basic??!1)):[],oG={findPart:async({sourceComponent:e,footprinterString:t})=>{let n=rG(t);if(e.type==="source_component"&&e.ftype==="simple_resistor"){let{resistors:i}=await ar("resistors",{resistance:e.resistance,package:n});return{jlcpcb:cr(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_capacitor"){let{capacitors:i}=await ar("capacitors",{capacitance:e.capacitance,package:n});return{jlcpcb:cr(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_pin_header"){let i;t?.includes("_p")&&(i=Number(t.split("_p")[1]));let{headers:r}=await ar("headers",i?{pitch:i,num_pins:e.pin_count,gender:e.gender}:{num_pins:e.pin_count,gender:e.gender});return{jlcpcb:cr(r).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_potentiometer"){let{potentiometers:i}=await ar("potentiometers",{resistance:e.max_resistance,package:n});return{jlcpcb:cr(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_diode"){let{diodes:i}=await ar("diodes",{package:n});return{jlcpcb:cr(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_chip"){let{chips:i}=await ar("chips",{package:n});return{jlcpcb:cr(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_transistor"){let{transistors:i}=await ar("transistors",{package:n,transistor_type:e.transistor_type});return{jlcpcb:cr(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_power_source"){let{power_sources:i}=await ar("power_sources",{voltage:e.voltage,package:n});return{jlcpcb:cr(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_inductor"){let{inductors:i}=await ar("inductors",{inductance:e.inductance,package:n});return{jlcpcb:cr(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_crystal"){let{crystals:i}=await ar("crystals",{frequency:e.frequency,load_capacitance:e.load_capacitance,package:n});return{jlcpcb:cr(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_mosfet"){let{mosfets:i}=await ar("mosfets",{package:n,mosfet_mode:e.mosfet_mode,channel_type:e.channel_type});return{jlcpcb:cr(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_resonator"){let{resonators:i}=await ar("resonators",{frequency:e.frequency,package:n});return{jlcpcb:cr(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_switch"){let{switches:i}=await ar("switches",{switch_type:e.type,package:n});return{jlcpcb:cr(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_led"){let{leds:i}=await ar("leds",{package:n});return{jlcpcb:cr(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_fuse"){let{fuses:i}=await ar("fuses",{package:n});return{jlcpcb:cr(i).map(r=>`C${r.lcsc}`).slice(0,3)}}return{}}};var lG=Vt(sG(),1);Z();var fG=Vt(Mn(),1),mG=Vt(Mn(),1),Yi=p.tuple([p.coerce.number(),p.coerce.number()]),S4t=p.tuple([p.number(),p.number(),p.number()]),Px=p.union([Yi,S4t]),uG=p.object({at:Px,size:Yi,layer:p.string(),layers:p.array(p.string()),roundrect_rratio:p.number(),uuid:p.string()}).partial(),P4t=p.object({key:p.string(),val:p.string(),attributes:uG}),vx=p.object({oval:p.boolean().default(!1),width:p.number().optional(),height:p.number().optional(),offset:Yi.optional()}),pG=p.object({name:p.string(),pad_type:p.enum(["thru_hole","smd","np_thru_hole","connect"]),pad_shape:p.enum(["roundrect","circle","rect","oval","trapezoid","custom"]),at:Px,drill:p.union([p.number(),p.array(p.any()),vx]).transform(e=>typeof e=="number"?{oval:!1,width:e,height:e}:"oval"in e?e:e.length===2?{oval:!1,width:Number.parseFloat(e[0]),height:Number.parseFloat(e[0]),offset:Yi.parse(e[1].slice(1))}:e.length===3||e.length===4?{oval:e[0]==="oval",width:Number.parseFloat(e[1]),height:Number.parseFloat(e[2]),offset:e[3]?Yi.parse(e[3].slice(1)):void 0}:e).pipe(vx),size:p.union([p.array(p.number()).length(2).transform(([e,t])=>({width:e,height:t})),p.object({width:p.number(),height:p.number()})]),layers:p.array(p.string()).optional(),roundrect_rratio:p.number().optional(),uuid:p.string().optional()}),hG=p.object({name:p.string(),pad_type:p.enum(["thru_hole","smd","np_thru_hole","connect"]),pad_shape:p.enum(["roundrect","circle","rect","oval","trapezoid","custom"]),at:Px,size:Yi,drill:p.union([p.number(),p.array(p.any()),vx]).transform(e=>typeof e=="number"?{oval:!1,width:e,height:e}:"oval"in e?e:e.length===2?{oval:!1,width:Number.parseFloat(e[0]),height:Number.parseFloat(e[0]),offset:Yi.parse(e[1].slice(1))}:e.length===3||e.length===4?{oval:e[0]==="oval",width:Number.parseFloat(e[1]),height:Number.parseFloat(e[2]),offset:e[3]?Yi.parse(e[3].slice(1)):void 0}:e).pipe(vx).optional(),layers:p.array(p.string()).optional(),roundrect_rratio:p.number().optional(),chamfer_ratio:p.number().optional(),solder_paste_margin:p.number().optional(),solder_paste_margin_ratio:p.number().optional(),clearance:p.number().optional(),zone_connection:p.union([p.literal(0).describe("Pad is not connect to zone"),p.literal(1).describe("Pad is connected to zone using thermal relief"),p.literal(2).describe("Pad is connected to zone using solid fill")]).optional(),thermal_width:p.number().optional(),thermal_gap:p.number().optional(),uuid:p.string().optional()}),dG=p.object({font:p.object({size:Yi,thickness:p.number().optional()})}).partial(),T4t=p.object({fp_text_type:p.literal("user"),text:p.string(),at:Px,layer:p.string(),uuid:p.string().optional(),effects:dG.partial()}),I4t=p.object({start:Yi,mid:Yi,end:Yi,stroke:p.object({width:p.number(),type:p.string()}),layer:p.string(),uuid:p.string().optional()}),M4t=p.object({center:Yi,end:Yi,stroke:p.object({width:p.number(),type:p.string()}),fill:p.string().optional(),layer:p.string(),uuid:p.string().optional()}),C4t=p.object({pts:p.array(Yi),stroke:p.object({width:p.number(),type:p.string()}).optional(),width:p.number().optional(),layer:p.string(),uuid:p.string().optional()}).transform(e=>({...e,width:void 0,stroke:e.stroke??{width:e.width}})),E4t=p.object({start:Yi,end:Yi,stroke:p.object({width:p.number(),type:p.string()}).optional(),width:p.number().optional(),layer:p.string(),uuid:p.string().optional()}).transform(e=>({...e,width:void 0,stroke:e.stroke??{width:e.width}})),aG=p.object({footprint_name:p.string(),version:p.string().optional(),generator:p.string().optional(),generator_version:p.string().optional(),layer:p.string(),descr:p.string().default(""),tags:p.array(p.string()).optional(),properties:p.array(P4t),fp_lines:p.array(E4t),fp_texts:p.array(T4t),fp_arcs:p.array(I4t),fp_circles:p.array(M4t).optional(),fp_polys:p.array(C4t).optional(),pads:p.array(hG),holes:p.array(pG).optional()}),wx=(e,t)=>{if(t==="effects"&&Array.isArray(e)){let n={};for(let i of e)if(i[0]==="font"){let r={};for(let o of i.slice(1))o.length===2?r[o[0].valueOf()]=Number.parseFloat(o[1].valueOf()):r[o[0].valueOf()]=o.slice(1).map(s=>Number.parseFloat(s.valueOf()));n.font=r}return dG.parse(n)}if(t==="pts")return e.map(n=>n.slice(1).map(i=>Number.parseFloat(i.valueOf())));if(t==="stroke"){let n={};for(let i of e){let r=i[0].valueOf();n[r]=wx(i.slice(1),r)}return n}return t==="at"||t==="size"||t==="start"||t==="mid"||t==="end"?(Array.isArray(e)?e:[e]).map(i=>i?.valueOf?.()??i).filter(i=>typeof i=="number"||typeof i=="string"&&/^[-+]?\d*\.?\d+(e[-+]?\d+)?$/i.test(i)).map(i=>typeof i=="number"?i:Number.parseFloat(i)):t==="tags"?e.map(n=>n.valueOf()):t==="generator_version"||t==="version"?e[0].valueOf():e.length===2?e.valueOf():t==="uuid"?Array.isArray(e)?e[0].valueOf():e.valueOf():/^[\d\.]+$/.test(e)&&!Number.isNaN(Number.parseFloat(e))?Number.parseFloat(e):Array.isArray(e)&&e.length===1?e[0].valueOf():Array.isArray(e)?e.map(n=>n.valueOf()):e},Be=(e,t)=>{for(let n of e)if(Array.isArray(n)&&n[0]===t)return wx(n.slice(1),t)},mM=(0,fG.default)("kicad-mod-converter"),k4t=e=>{let t=(0,lG.default)(e),n=t[1].valueOf(),i={},r=Object.entries(aG.shape).filter(([C,I])=>I._def.typeName==="ZodString"||C==="tags").map(([C])=>C);for(let C of t.slice(2)){if(!r.includes(C[0]))continue;let I=C[0].valueOf(),k=wx(C.slice(1),I);i[I]=k}let o=t.slice(2).filter(C=>C[0]==="property").map(C=>{let I=C[1].valueOf(),k=C[2].valueOf(),P=uG.parse(C.slice(3).reduce((N,E)=>{let A=E[0].valueOf();return N[A]=wx(E.slice(1),A),N},{}));return{key:I,val:k,attributes:P}}),s=t.slice(2).filter(C=>C[0]==="pad"),a=[];for(let C of s){let I=Be(C,"at"),k=Be(C,"size"),P=Be(C,"drill"),N=Be(C,"layers");if(Array.isArray(N)?N=N.map($=>$.valueOf()):typeof N=="string"?N=[N]:N||(N=[]),!N.includes("F.Cu")){mM(`Skipping pad without F.Cu layer: layers=${N.join(", ")}`);continue}let E=Be(C,"roundrect_rratio"),A=Be(C,"uuid"),O={name:C[1].valueOf(),pad_type:C[2].valueOf(),pad_shape:C[3].valueOf(),at:I,drill:P,size:k,layers:N,roundrect_rratio:E,uuid:A};mM(`attempting to parse pad: ${JSON.stringify(O,null," ")}`),a.push(hG.parse(O))}let c=t.slice(2).filter(C=>C[0]==="fp_text"),l=[];for(let C of c){let I=C[2].valueOf(),k=Be(C,"at"),P=Be(C,"layer"),N=Be(C,"uuid"),E=Be(C,"effects");l.push({fp_text_type:"user",text:I,at:k,layer:P,uuid:N,effects:E})}let u=[],h=t.slice(2).filter(C=>C[0]==="fp_line");for(let C of h){let I=Be(C,"start"),k=Be(C,"end"),P=Be(C,"stroke"),N=Be(C,"layer"),E=Be(C,"uuid");u.push({start:I,end:k,stroke:P,layer:N,uuid:E})}let d=[],_=t.slice(2).filter(C=>C[0]==="fp_arc");for(let C of _){let I=Be(C,"start"),k=Be(C,"mid"),P=Be(C,"end"),N=Be(C,"stroke"),E=Be(C,"layer"),A=Be(C,"uuid");!I||!P||!k||!N||!E||d.push({start:I,mid:k,end:P,stroke:N,layer:E,uuid:A})}let y=[],g=t.slice(2).filter(C=>C[0]==="fp_circle");for(let C of g){let I=Be(C,"center"),k=Be(C,"end"),P=Be(C,"stroke"),N=Be(C,"fill"),E=Be(C,"layer"),A=Be(C,"uuid");!I||!k||!P||!E||y.push({center:I,end:k,stroke:P,fill:N,layer:E,uuid:A})}let x=[],w=t.slice(2).filter(C=>C[0]==="fp_poly");for(let C of w){let I=Be(C,"pts"),k=Be(C,"stroke"),P=Be(C,"layer"),N=Be(C,"uuid");x.push({pts:I,stroke:k,layer:P,uuid:N})}let S=[];for(let C of t.slice(2)){if(C[0]!=="pad"||C[2]?.valueOf?.()!=="thru_hole")continue;let I=C[1]?.valueOf?.(),k=C[2]?.valueOf?.(),P=C[3]?.valueOf?.(),N=Be(C,"at"),E=Be(C,"drill"),A=Be(C,"size");Array.isArray(A)&&(A[0]==="size"&&(A=A.slice(1)),A={width:Number(A[0]),height:Number(A[1])});let O=Be(C,"uuid"),$=Be(C,"roundrect_rratio"),B=Be(C,"layers");Array.isArray(B)?B=B.map(X=>X.valueOf()):typeof B=="string"?B=[B]:B||(B=[]);let H={name:I,pad_type:k,pad_shape:P,at:N,drill:E,size:A,layers:B,roundrect_rratio:$,uuid:O};mM(`attempting to parse holes: ${JSON.stringify(H,null,2)}`),S.push(pG.parse(H))}return aG.parse({footprint_name:n,...i,properties:o,fp_lines:u,fp_texts:l,fp_arcs:d,fp_circles:y,pads:a,holes:S,fp_polys:x})};function _G(e,t,n){let i={x:(e.x+t.x)/2,y:(e.y+t.y)/2},r={x:(t.x+n.x)/2,y:(t.y+n.y)/2},o=-(e.x-t.x)/(e.y-t.y),s=-(t.x-n.x)/(t.y-n.y),a=(i.y-r.y+s*r.x-o*i.x)/(s-o),c=i.y+o*(a-i.x);return{x:a,y:c}}function yG(e,t){return Math.sqrt((e.x-t.x)**2+(e.y-t.y)**2)}function Sx(e,t){return Math.atan2(t.y-e.y,t.x-e.x)}var gG=(e,t,n)=>{let i=_G(e,t,n),r=yG(i,e),o=Sx(i,e),a=Sx(i,n)-o;return a<0&&(a+=2*Math.PI),r*a};function bG(e,t,n,i){let r=_G(e,t,n),o=yG(r,e),s=Sx(r,e),c=Sx(r,n)-s;c<0&&(c+=2*Math.PI);let l=[];for(let u=0;u<=i;u++){let h=s+u/i*c,d=r.x+o*Math.cos(h),_=r.y+o*Math.sin(h);l.push({x:d,y:_})}return l}var gm=e=>Array.isArray(e)?{x:e[0],y:e[1]}:e,_M=(e,t,n=1e-4)=>Math.abs(e.x-t.x)<n&&Math.abs(e.y-t.y)<n,N4t=e=>{let t=[],n=new Set;for(let i=0;i<e.length;i++){if(n.has(i))continue;let r=[e[i]];n.add(i);let o=e[i].end,s=!0;for(;s;){if(s=!1,r.length>1&&_M(o,r[0].start)){t.push(r);break}for(let a=0;a<e.length;a++)if(!n.has(a)){if(_M(o,e[a].start)){r.push(e[a]),n.add(a),o=e[a].end,s=!0;break}else if(_M(o,e[a].end)){e[a].type==="arc"?r.push({...e[a],reversed:!0}):r.push({...e[a],start:e[a].end,end:e[a].start}),n.add(a),o=e[a].start,s=!0;break}}if(!s){for(let a=r.length-1;a>=0;a--){let c=e.indexOf(r[a]);c!==-1&&n.delete(c)}break}}}return t},A4t=e=>{let t=[];for(let n of e)if(n.type==="line")t.push(n.start);else if(n.type==="arc"&&n.mid){let i=gG(n.start,n.mid,n.end),r=Math.max(3,Math.ceil(i)),o=bG(n.start,n.mid,n.end,r);n.reversed&&(o=o.reverse()),t.push(...o.slice(0,-1))}return t};function R4t(e){if(!Array.isArray(e))return null;let t=e.find(s=>s.layer?.toLowerCase()==="f.silks"&&(s.text?.includes("${REFERENCE}")||s.fp_text_type?.toLowerCase()==="reference"||s.text?.match(/^R\d+|C\d+|U\d+/))),n=t||e.find(s=>s.layer?.toLowerCase()==="f.fab"&&(s.text?.includes("${REFERENCE}")||s.fp_text_type?.toLowerCase()==="reference")),i=t||n;if(!i?.effects?.font?.size)return null;let[r,o]=i.effects.font.size;return o??r??1}var O4t=e=>e*Math.PI/180,yM=(e,t,n)=>{let i=O4t(n),r=Math.cos(i),o=Math.sin(i);return{x:e*r-t*o,y:e*o+t*r}},L4t=e=>{let t=[...new Map(e.map(u=>[`${u.x},${u.y}`,u])).values()];if(t.length!==4)return null;let n=t.map(u=>u.x),i=t.map(u=>u.y),r=[...new Set(n)],o=[...new Set(i)];if(r.length!==2||o.length!==2)return null;let[s,a]=r.sort((u,h)=>u-h),[c,l]=o.sort((u,h)=>u-h);return s===void 0||a===void 0||c===void 0||l===void 0?null:{x:(s+a)/2,y:(c+l)/2,width:a-s,height:l-c}},cG=e=>e&&Array.isArray(e)&&e.length>=3&&typeof e[2]=="number"?e[2]:0,uo=e=>{let t=(e%360+360)%360;return t===90||t===270},Lh=(0,mG.default)("kicad-mod-converter"),ls=e=>{switch(e.toLowerCase()){case"f.cu":case"f.fab":case"f.silks":case"edge.cuts":return"top";case"b.cu":case"b.fab":case"b.silks":return"bottom"}},F4t=async e=>{let{fp_lines:t,fp_texts:n,fp_arcs:i,fp_circles:r,pads:o,properties:s,holes:a,fp_polys:c}=e,l=[];l.push({type:"source_component",source_component_id:"source_component_0",supplier_part_numbers:{}}),l.push({type:"schematic_component",schematic_component_id:"schematic_component_0",source_component_id:"source_component_0",center:{x:0,y:0},rotation:0,size:{width:0,height:0}});let u=new Set;for(let V of o)V.name&&u.add(V.name);if(a)for(let V of a)V.name&&u.add(V.name);let h=0,d=new Map;for(let V of u){let rt=`source_port_${h++}`;d.set(V,rt),l.push({type:"source_port",source_port_id:rt,source_component_id:"source_component_0",name:V,port_hints:[V]}),l.push({type:"schematic_port",schematic_port_id:`schematic_port_${h++}`,source_port_id:rt,schematic_component_id:"schematic_component_0",center:{x:0,y:0}})}let _=Number.POSITIVE_INFINITY,y=Number.NEGATIVE_INFINITY,g=Number.POSITIVE_INFINITY,x=Number.NEGATIVE_INFINITY;for(let V of o){let rt=V.at[0],K=-V.at[1],et=V.size[0],pt=V.size[1];_=Math.min(_,rt-et/2),y=Math.max(y,rt+et/2),g=Math.min(g,K-pt/2),x=Math.max(x,K+pt/2)}let w="pcb_component_0";l.push({type:"pcb_component",source_component_id:"source_component_0",pcb_component_id:w,layer:"top",center:{x:0,y:0},rotation:0,width:Number.isFinite(_)?y-_:0,height:Number.isFinite(g)?x-g:0});let S=0,C=new Map;for(let V of u){let rt=`pcb_port_${S++}`,K=d.get(V);C.set(V,rt);let et=0,pt=0,mt=["top","bottom"],It=o.find(Mt=>Mt.name===V);if(It)et=It.at[0],pt=-It.at[1],mt=It.layers?It.layers.map(Mt=>ls(Mt)).filter(Boolean):["top","bottom"];else if(a){let Mt=a.find(lt=>lt.name===V);Mt&&(et=Mt.at[0],pt=-Mt.at[1],mt=Mt.layers?Mt.layers.map(lt=>ls(lt)).filter(Boolean):["top","bottom"])}l.push({type:"pcb_port",pcb_port_id:rt,source_port_id:K,pcb_component_id:w,x:et,y:pt,layers:mt})}let I=0,k=0,P=0;for(let V of o)if(V.pad_type==="smd"){let rt=V.name?C.get(V.name):void 0;l.push({type:"pcb_smtpad",pcb_smtpad_id:`pcb_smtpad_${I++}`,shape:"rect",x:V.at[0],y:-V.at[1],width:V.size[0],height:V.size[1],layer:ls(V.layers?.[0]??"F.Cu"),pcb_component_id:w,port_hints:[V.name],pcb_port_id:rt})}else if(V.pad_type==="thru_hole"){if(V.pad_shape==="rect"){let rt=cG(V.at),K=uo(rt)?V.size[1]:V.size[0],et=uo(rt)?V.size[0]:V.size[1],pt=V.drill?.offset?.[0]??0,mt=V.drill?.offset?.[1]??0,It=yM(pt,mt,rt),Mt=V.name?C.get(V.name):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${k++}`,shape:"circular_hole_with_rect_pad",hole_shape:"circle",pad_shape:"rect",x:V.at[0],y:-V.at[1],hole_offset_x:It.x,hole_offset_y:-It.y,hole_diameter:V.drill?.width,rect_pad_width:K,rect_pad_height:et,layers:["top","bottom"],pcb_component_id:w,port_hints:[V.name],pcb_port_id:Mt})}else if(V.pad_shape==="circle"){let rt=V.name?C.get(V.name):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${k++}`,shape:"circle",x:V.at[0],y:-V.at[1],outer_diameter:V.size[0],hole_diameter:V.drill?.width,layers:["top","bottom"],pcb_component_id:w,port_hints:[V.name],pcb_port_id:rt})}else if(V.pad_shape==="oval"){let rt=V.name?C.get(V.name):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${k++}`,shape:"pill",x:V.at[0],y:-V.at[1],outer_width:V.size[0],outer_height:V.size[1],hole_width:V.drill?.width,hole_height:V.drill?.height,layers:["top","bottom"],pcb_component_id:w,port_hints:[V.name],pcb_port_id:rt})}}else V.pad_type==="np_thru_hole"&&l.push({type:"pcb_hole",pcb_hole_id:`pcb_hole_${P++}`,x:V.at[0],y:-V.at[1],hole_diameter:V.drill?.width,pcb_component_id:w});if(a)for(let V of a){let rt=V.layers?.some(ht=>ht.endsWith(".Cu")||ht==="*.Cu"),K=cG(V.at),et=V.drill?.offset?.[0]??0,pt=V.drill?.offset?.[1]??0,mt=yM(et,pt,K),It=V.at[0]+mt.x,Mt=-(V.at[1]+mt.y),lt=V.drill?.width??0,j=V.size?.width??lt,q=V.roundrect_rratio??0,nt=q>0?Math.min(uo(K)?V.size?.height??j:V.size?.width??j,uo(K)?V.size?.width??j:V.size?.height??j)/2*q:0;if(rt)if(V.pad_shape==="rect"){let ht=V.name?C.get(V.name):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${k++}`,shape:"circular_hole_with_rect_pad",hole_shape:"circle",pad_shape:"rect",x:V.at[0],y:-V.at[1],hole_offset_x:mt.x,hole_offset_y:-mt.y,hole_diameter:lt,rect_pad_width:uo(K)?V.size?.height??j:V.size?.width??j,rect_pad_height:uo(K)?V.size?.width??j:V.size?.height??j,rect_border_radius:nt,port_hints:[V.name],layers:["top","bottom"],pcb_component_id:w,pcb_port_id:ht})}else if(V.pad_shape==="oval"){let ht=V.name?C.get(V.name):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${k++}`,shape:"pill",x:It,y:Mt,outer_width:uo(K)?V.size?.height??j:V.size?.width??j,outer_height:uo(K)?V.size?.width??j:V.size?.height??j,hole_width:uo(K)?V.drill?.height??lt:V.drill?.width??lt,hole_height:uo(K)?V.drill?.width??lt:V.drill?.height??lt,port_hints:[V.name],layers:["top","bottom"],pcb_component_id:w,pcb_port_id:ht})}else if(V.pad_shape==="roundrect"){let ht=V.name?C.get(V.name):void 0,at=V.drill?.offset?.[0]??0,ut=V.drill?.offset?.[1]??0,ot=yM(at,ut,K),wt=uo(K)?V.size?.height??j:V.size?.width??j,Lt=uo(K)?V.size?.width??j:V.size?.height??j;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${k++}`,shape:"circular_hole_with_rect_pad",hole_shape:"circle",pad_shape:"rect",x:It,y:Mt,hole_offset_x:ot.x,hole_offset_y:-ot.y,hole_diameter:lt,rect_pad_width:wt,rect_pad_height:Lt,rect_border_radius:nt,port_hints:[V.name],layers:["top","bottom"],pcb_component_id:w,pcb_port_id:ht})}else{let ht=V.name?C.get(V.name):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${k++}`,shape:"circle",x:It,y:Mt,outer_diameter:j,hole_diameter:lt,port_hints:[V.name],layers:["top","bottom"],pcb_component_id:w,pcb_port_id:ht})}else l.push({type:"pcb_hole",pcb_hole_id:`pcb_hole_${P++}`,x:It,y:Mt,hole_diameter:j,hole_shape:"circle",pcb_component_id:w})}let N=[];for(let V of t)V.layer.toLowerCase()==="edge.cuts"&&N.push({type:"line",start:{x:V.start[0],y:V.start[1]},end:{x:V.end[0],y:V.end[1]},strokeWidth:V.stroke.width});for(let V of i)V.layer.toLowerCase()==="edge.cuts"&&N.push({type:"arc",start:{x:V.start[0],y:V.start[1]},mid:{x:V.mid[0],y:V.mid[1]},end:{x:V.end[0],y:V.end[1]},strokeWidth:V.stroke.width});let E=N4t(N),A=0;for(let V of E){let rt=A4t(V);rt.length>=3&&l.push({type:"pcb_cutout",pcb_cutout_id:`pcb_cutout_${A++}`,shape:"polygon",points:rt.map(K=>({x:K.x,y:-K.y})),pcb_component_id:w})}let O=0,$=0,B=0,H=0;for(let V of t){let rt=[{x:V.start[0],y:-V.start[1]},{x:V.end[0],y:-V.end[1]}],K=V.layer.toLowerCase();K==="f.cu"?l.push({type:"pcb_trace",pcb_trace_id:`pcb_trace_${O++}`,pcb_component_id:w,layer:ls(V.layer),route:rt,thickness:V.stroke.width}):K==="f.silks"?l.push({type:"pcb_silkscreen_path",pcb_silkscreen_path_id:`pcb_silkscreen_path_${$++}`,pcb_component_id:w,layer:"top",route:rt,stroke_width:V.stroke.width}):K==="edge.cuts"?Lh("Skipping Edge.Cuts fp_line (converted to pcb_cutout)",V.layer):K==="f.fab"?l.push({type:"pcb_fabrication_note_path",fabrication_note_path_id:`fabrication_note_path_${B++}`,pcb_component_id:w,layer:"top",route:rt,stroke_width:V.stroke.width,port_hints:[]}):K.startsWith("user.")?l.push({type:"pcb_note_line",pcb_note_line_id:`pcb_note_line_${H++}`,pcb_component_id:w,x1:V.start[0],y1:-V.start[1],x2:V.end[0],y2:-V.end[1],stroke_width:V.stroke.width}):Lh("Unhandled layer for fp_line",V.layer)}if(c)for(let V of c){let rt=V.pts.map(K=>({x:K[0],y:-K[1]}));if(V.layer.endsWith(".Cu")){let K=L4t(rt);K?l.push({type:"pcb_smtpad",pcb_smtpad_id:`pcb_smtpad_${I++}`,shape:"rect",x:K.x,y:K.y,width:K.width,height:K.height,layer:ls(V.layer),pcb_component_id:w}):l.push({type:"pcb_trace",pcb_trace_id:`pcb_trace_${O++}`,pcb_component_id:w,layer:ls(V.layer),route:rt,thickness:V.stroke.width})}else V.layer.endsWith(".SilkS")?l.push({type:"pcb_silkscreen_path",pcb_silkscreen_path_id:`pcb_silkscreen_path_${$++}`,pcb_component_id:w,layer:ls(V.layer),route:rt,stroke_width:V.stroke.width}):V.layer.endsWith(".Fab")?l.push({type:"pcb_fabrication_note_path",fabrication_note_path_id:`fabrication_note_path_${B++}`,pcb_component_id:w,layer:ls(V.layer),route:rt,stroke_width:V.stroke.width,port_hints:[]}):Lh("Unhandled layer for fp_poly",V.layer)}let X=0;for(let V of i){let rt=V.layer.toLowerCase();if(rt==="edge.cuts"){Lh("Skipping Edge.Cuts fp_arc (converted to pcb_cutout)",V.layer);continue}let K=gm(V.start),et=gm(V.mid),pt=gm(V.end),mt=gG(K,et,pt),It=bG(K,et,pt,Math.ceil(mt));if(rt.startsWith("user.")){l.push({type:"pcb_note_path",pcb_note_path_id:`pcb_note_path_${X++}`,pcb_component_id:w,route:It.map(lt=>({x:lt.x,y:-lt.y})),stroke_width:V.stroke.width});continue}let Mt=ls(V.layer);if(!Mt){Lh("Unable to convert layer for fp_arc",V.layer);continue}l.push({type:"pcb_silkscreen_path",pcb_silkscreen_path_id:`pcb_silkscreen_path_${$++}`,layer:Mt,pcb_component_id:w,route:It.map(lt=>({x:lt.x,y:-lt.y})),stroke_width:V.stroke.width})}if(r)for(let V of r){let rt=V.layer.toLowerCase(),K=gm(V.center),et=gm(V.end),pt=Math.sqrt((et.x-K.x)**2+(et.y-K.y)**2),mt=Math.max(16,Math.ceil(2*Math.PI*pt)),It=[];for(let Mt=0;Mt<=mt;Mt++){let lt=Mt/mt*2*Math.PI;It.push({x:K.x+pt*Math.cos(lt),y:K.y+pt*Math.sin(lt)})}rt.startsWith("user.")&&l.push({type:"pcb_note_path",pcb_note_path_id:`pcb_note_path_${X++}`,pcb_component_id:w,route:It.map(Mt=>({x:Mt.x,y:-Mt.y})),stroke_width:V.stroke.width})}for(let V of n){let rt=ls(V.layer);V.layer.endsWith(".SilkS")?l.push({type:"pcb_silkscreen_text",layer:rt,font:"tscircuit2024",font_size:V.effects?.font?.size[0]??1,pcb_component_id:w,anchor_position:{x:V.at[0],y:-V.at[1]},anchor_alignment:"center",text:V.text}):V.layer.endsWith(".Fab")?l.push({type:"pcb_fabrication_note_text",layer:rt,font:"tscircuit2024",font_size:V.effects?.font?.size[0]??1,pcb_component_id:w,anchor_position:{x:V.at[0],y:-V.at[1]},anchor_alignment:"center",text:V.text}):Lh("Unhandled layer for fp_text",V.layer)}let U=s.find(V=>V.key==="Reference"),tt=s.find(V=>V.key==="Value"),J=[U,tt].filter(V=>V&&!!V.val);for(let V of J){let rt=V.attributes.at;if(!rt)continue;let et=V.attributes.layer?.toLowerCase()?.endsWith(".fab"),pt=R4t(n);l.push({type:et?"pcb_fabrication_note_text":"pcb_silkscreen_text",layer:"top",font:"tscircuit2024",font_size:pt,pcb_component_id:w,anchor_position:{x:rt[0],y:-rt[1]},anchor_alignment:"center",text:V.val})}return l},xG=async e=>{let t=k4t(e);return await F4t(t)};var z4t="https://kicad-mod-cache.tscircuit.com",vG=()=>({partsEngine:oG,footprintLibraryMap:{kicad:async e=>{let t=`${z4t}/${e}`,n=`${t}.circuit.json`,r=await(await fetch(n)).json(),o=Array.isArray(r)?r.filter(a=>a?.type==="pcb_silkscreen_text"?a?.text==="REF**":!0):r,s=`${t}.wrl`;return{footprintCircuitJson:o,cadModel:{wrlUrl:s,modelUnitToMmScale:2.54}}}},footprintFileParserMap:{kicad_mod:{loadFromUrl:async e=>{let t=await fetch(e).then(i=>i.text()),n=await xG(t);return{footprintCircuitJson:Array.isArray(n)?n:[n]}}}}});var gM=Vt(Mn(),1),pne=(0,gM.default)("tsci:eval:execution-context");function Tx(e,t={}){globalThis.React=wG;let n=t.platform||vG(),i=t.projectConfig?{...n,...t.projectConfig}:n,r=new Rh({platform:i});t.name&&(r.name=t.name),t.debugNamespace&&r.enableDebug(t.debugNamespace);let o=[];return{fsMap:{},entrypoint:"",logger:{info:s=>{o.push({msg:s})},getLogs:()=>o,stringifyLogs:()=>o.map(s=>s.msg).join(`
|
|
247
247
|
`)},preSuppliedImports:{"@tscircuit/core":bx,tscircuit:bx,"@tscircuit/math-utils":m4,react:wG,debug:gM.default,"@tscircuit/props":{}},circuit:r,tsConfig:null,importStack:[],currentlyImporting:new Set,...e}}function vc(e){let t=e;return t=t.replace(/\\/g,"/"),t=t.trim(),t.startsWith("./")&&(t=t.slice(2)),t.startsWith("/")&&(t=t.slice(1)),t}function SG(e){let t={};for(let[n,i]of Object.entries(e))t[vc(n)]=i;return t}function No(e){if(!e)return".";let n=e.replace(/\\/g,"/").replace(/\/+$/,"");return n.indexOf("/")===-1?".":n.substring(0,n.lastIndexOf("/"))||"/"}function Ix(e,t){if(e.startsWith("../")){let n=No(t);return Ix(e.slice(3),n)}return e.startsWith("./")?Ix(e.slice(2),t):e.startsWith("/")?e.slice(1):`${t}/${e}`}function bm(e){if(Array.isArray(e))return null;let t=e["tsconfig.json"];if(!t)return null;try{let n=t.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g,"");return JSON.parse(n)}catch(n){throw new Error(`Failed to parse tsconfig.json: ${n.message}`)}}function PG(e){let{importPath:t,normalizedFilePathMap:n,extensions:i,tsConfig:r}=e,o=r?.compilerOptions?.paths;if(!o)return null;let s=r?.compilerOptions?.baseUrl||".",a=l=>{let u=vc(l);if(n.has(u))return n.get(u);for(let h of i){let d=`${u}.${h}`;if(n.has(d))return n.get(d)}return null};for(let[l,u]of Object.entries(o))if(l.includes("*")){let[d,_]=l.split("*");if(!t.startsWith(d)||!t.endsWith(_||""))continue;let y=t.slice(d.length,t.length-(_?_.length:0));for(let g of u){let x=g.replace("*",y),w=s&&!x.startsWith("./")&&!x.startsWith("/")?`${s}/${x}`:x,S=a(w);if(S)return S}}else{if(t!==l)continue;for(let d of u){let _=s&&!d.startsWith("./")&&!d.startsWith("/")?`${s}/${d}`:d,y=a(_);if(y)return y}}let c=bM({importPath:t,normalizedFilePathMap:n,extensions:i,tsConfig:r});return c||null}function bM(e){let{importPath:t,normalizedFilePathMap:n,extensions:i,tsConfig:r}=e,o=r?.compilerOptions?.baseUrl;if(!o)return null;let s=`${o}/${t}`,a=vc(s);if(n.has(a))return n.get(a);for(let c of i){let l=`${a}.${c}`;if(n.has(l))return n.get(l)}return null}function TG(e,t){let n=t?.compilerOptions?.paths;if(!n)return!1;for(let[i]of Object.entries(n))if(i.includes("*")){let[o,s]=i.split("*");if(e.startsWith(o)&&e.endsWith(s||""))return!0}else if(e===i)return!0;return!1}var xm=(e,t,n,i={})=>{let r=n?Ix(e,n):e,o=new Set(Array.isArray(t)?t:Object.keys(t));if(o.has(r))return r;let s=new Map;for(let u of o)s.set(vc(u),u);let a=vc(r);if(s.has(a))return s.get(a);let c=["tsx","ts","json","js","jsx","obj","gltf","glb"];for(let u of c){let h=`${a}.${u}`;if(s.has(h))return s.get(h)}let l=i.tsConfig??null;if(!e.startsWith("./")&&!e.startsWith("../")){let u=PG({importPath:e,normalizedFilePathMap:s,extensions:c,tsConfig:l});if(u)return u;let h=bM({importPath:e,normalizedFilePathMap:s,extensions:c,tsConfig:l});if(h)return h}if(!e.startsWith("./")&&!e.startsWith("../")){let u=vc(e);if(s.has(u))return s.get(u);for(let h of c){let d=`${u}.${h}`;if(s.has(d))return s.get(d)}}return null},Mx=(e,t,n,i={})=>{let r=xm(e,t,n,i);if(!r)throw new Error(`File not found "${e}", available paths:
|