@tscircuit/eval 0.0.277 → 0.0.279

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.
@@ -1033,7 +1033,7 @@ ${o.svg()}`;return a+=`" >
1033
1033
  networkId: ${o.networkId}
1034
1034
  d=${this.lastBestPointsResult.distance}`})}return t}getResult(){return this.packedComponents}},oAe=n=>{let t=new S$t(n);return t.solve(),{...n,components:t.packedComponents}},B$t=(n,t,a)=>{let o=[],l=({padId:p,pcbPortId:x,sx:m,sy:g,x:_,y:F})=>o.push({padId:p,networkId:a(x),size:{x:m,y:g},absoluteCenter:{x:_,y:F}});for(let p of t.pcb_plated_hole.list({pcb_component_id:n.pcb_component_id})){switch(p.shape){case"circle":{l({padId:p.pcb_plated_hole_id,pcbPortId:p.pcb_port_id,sx:p.outer_diameter??p.hole_diameter??0,sy:p.outer_diameter??p.hole_diameter??0,x:p.x,y:p.y});break}case"oval":{l({padId:p.pcb_plated_hole_id,pcbPortId:p.pcb_port_id,sx:p.outer_width,sy:p.outer_height,x:p.x,y:p.y});break}case"circular_hole_with_rect_pad":{l({padId:p.pcb_plated_hole_id,pcbPortId:p.pcb_port_id,sx:p.rect_pad_width,sy:p.rect_pad_height,x:p.x,y:p.y});break}case"pill":{l({padId:p.pcb_plated_hole_id,pcbPortId:p.pcb_port_id,sx:p.outer_width,sy:p.outer_height,x:p.x,y:p.y});break}case"pill_hole_with_rect_pad":{l({padId:p.pcb_plated_hole_id,pcbPortId:p.pcb_port_id,sx:p.rect_pad_width,sy:p.rect_pad_height,x:p.x,y:p.y});break}}console.warn(`Unsupported plated hole shape ${p.shape}`)}for(let p of t.pcb_smtpad.list({pcb_component_id:n.pcb_component_id}))switch(p.shape){case"rect":{l({padId:p.pcb_smtpad_id,pcbPortId:p.pcb_port_id,sx:p.width??0,sy:p.height??0,x:p.x,y:p.y});break}case"circle":{l({padId:p.pcb_smtpad_id,pcbPortId:p.pcb_port_id,sx:p.radius??0,sy:p.radius??0,x:p.x,y:p.y});break}case"pill":{l({padId:p.pcb_smtpad_id,pcbPortId:p.pcb_port_id,sx:p.width??0,sy:p.height??0,x:p.x,y:p.y});break}default:{console.warn(`smtpad shape ${p.shape} pads are not supported in pack layout yet`);break}}return o},sAe=(n,t,a,o)=>{let l=n.flatMap(C=>B$t(C,a,o)),p=1/0,x=1/0,m=-1/0,g=-1/0;for(let C of l)p=Math.min(p,C.absoluteCenter.x-C.size.x/2),m=Math.max(m,C.absoluteCenter.x+C.size.x/2),x=Math.min(x,C.absoluteCenter.y-C.size.y/2),g=Math.max(g,C.absoluteCenter.y+C.size.y/2);let _={x:(p+m)/2,y:(x+g)/2},F=l.map(C=>({padId:C.padId,networkId:C.networkId,type:"rect",size:C.size,absoluteCenter:C.absoluteCenter,offset:{x:C.absoluteCenter.x-_.x,y:C.absoluteCenter.y-_.y}}));return{componentId:t,center:_,ccwRotationOffset:0,pads:F}},cAe=(n,t)=>{if(n.nodeType==="component"){let a=n.otherChildElements[0]?.pcb_component_id;return a?[t.pcb_component.get(a)]:[]}return n.childNodes.flatMap(a=>cAe(a,t))},uAe=(n,t={})=>{let a={components:[],minGap:0,packOrderStrategy:"largest_to_smallest",packPlacementStrategy:"shortest_connection_along_outline"},o=Fb(n,{source_group_id:t.source_group_id}),l=vi(n),p=0,x=g=>{if(g){let _=l.pcb_port.get(g);if(_){let F=l.source_port.get(_.source_port_id);if(F?.subcircuit_connectivity_map_key)return F.subcircuit_connectivity_map_key}}return`unnamed${p++}`},m=o.childNodes??[];for(let g of m)if(g.nodeType==="component"){let _=g.otherChildElements.find(F=>F.type==="pcb_component");if(!_)continue;a.components.push(sAe([_],_.pcb_component_id,l,x))}else if(g.nodeType==="group"){let _=cAe(g,l);if(!_.length)continue;let F=g.sourceGroup?.source_group_id??g.sourceGroup?.name??`group_${a.components.length}`;a.components.push(sAe(_,F,l,x))}return a},lAe=n=>{let t=n.components.map(a=>({componentId:a.componentId,pads:a.pads.map(({absoluteCenter:o,...l})=>l)}));return{...n,components:t}};or();za();var B7e=Cr(e0(),1);var dAe=Cr(e0(),1);za();function pAe(n,t={}){var a,o,l;if(n.length===0)return{width:0,height:0};let p=(a=t.direction)!=null?a:"row",x=(o=t.columnGap)!=null?o:0,m=(l=t.rowGap)!=null?l:0;if(p==="row"||p==="row-reverse"){let F=n.reduce((S,P)=>S+P.width,0)+x*Math.max(0,n.length-1),C=n.reduce((S,P)=>Math.max(S,P.height),0);return{width:F,height:C}}else{let F=n.reduce((S,P)=>S+P.height,0)+m*Math.max(0,n.length-1);return{width:n.reduce((S,P)=>Math.max(S,P.width),0),height:F}}}var nlr=(0,dAe.default)("tscircuit:circuit-json-flex:layoutCircuitJsonWithFlex");za();var fAe={flexGrow:0,flexShrink:1,flexBasis:0,alignSelf:"auto",width:void 0,height:void 0},mAe=class{constructor(n={}){J(this,"id");J(this,"metadata");J(this,"size",{width:0,height:0});J(this,"position",{x:0,y:0});J(this,"style");this.style={...fAe,...n},this.id=n.id,this.metadata=n.metadata}},T$t=class extends mAe{build(){}},xAe=class nW extends mAe{constructor(a,o,l={}){super({});J(this,"children",[]);J(this,"direction","row");J(this,"columnGap",0);J(this,"rowGap",0);J(this,"justifyContent","flex-start");J(this,"alignItems","stretch");this.size.width=a,this.size.height=o,this.id=l.id,Object.assign(this,l)}addChild(a,o){if(a instanceof nW){let p=a;return o&&(p.style={...fAe,...o}),this.children.push(p),p}let l=new T$t(a);return this.children.push(l),l}build(){let a=this.direction.startsWith("row"),o=a?"width":"height",l=a?"height":"width",p=a?this.columnGap:this.rowGap,x=a?this.rowGap:this.columnGap,m=p*Math.max(0,this.children.length-1),g=this.size[o],_=this.size[l],F=0,C=0,S=0;for(let U of this.children)F+=U.style.flexBasis,C+=U.style.flexGrow,S+=U.style.flexShrink;let P=g-F-m;for(let U of this.children){let me=U.style.flexBasis;P>0&&C>0?me+=P*U.style.flexGrow/C:P<0&&S>0&&(me+=P*U.style.flexShrink/S,me<0&&(me=0)),U.size[o]=me;let W=U.style.alignSelf!=="auto"?U.style.alignSelf:this.alignItems,pe=a?U.style.height:U.style.width;pe!==void 0?U.size[l]=pe:W==="stretch"&&(U.size[l]=_)}let k=this.children.reduce((U,me)=>U+me.size[o],0)+m,q=g-k,X=0,Q=p,ee=this.children.length;switch(this.justifyContent){case"flex-start":break;case"flex-end":X=q;break;case"center":X=q/2;break;case"space-between":Q=ee>1?p+q/(ee-1):0;break;case"space-around":Q=p+q/ee,X=Q/2;break;case"space-evenly":Q=p+q/(ee+1),X=Q;break}let ue=this.direction.endsWith("reverse")?[...this.children].reverse():this.children,ce=X;for(let U of ue)a?(U.position.x=this.direction==="row"?ce:g-ce-U.size.width,U.position.y=fe(U,l,_,this.alignItems)):(U.position.y=this.direction==="column"?ce:g-ce-U.size.height,U.position.x=fe(U,l,_,this.alignItems)),ce+=U.size[o]+Q;for(let U of this.children)U instanceof nW&&U.build();function fe(U,me,W,pe){switch(U.style.alignSelf!=="auto"?U.style.alignSelf:pe){case"flex-start":return 0;case"flex-end":return W-U.size[me];case"center":return(W-U.size[me])/2;case"stretch":default:return 0}}}},hAe=class extends xAe{constructor(n,t,a={}){super(n,t,a)}getLayout(){this.build();let n={};return this._collectLayout(this,n),n}_collectLayout(n,t,a={counter:0}){for(let o of n.children){let l=o.id??`_$$${a.counter++}`;t[l]={position:o.position,size:o.size},o instanceof xAe&&this._collectLayout(o,t,a)}}};or();za();za();Nu();za();za();or();za();za();Nu();za();var P$t=class{constructor({objects:n,getBounds:t,getId:a,CELL_SIZE:o}){J(this,"buckets");J(this,"objectsById");J(this,"getBounds");J(this,"getId");J(this,"CELL_SIZE",.4);J(this,"_idCounter",0);this.buckets=new Map,this.objectsById=new Map,this.getBounds=t,this.getId=a??(()=>this._getNextId()),this.CELL_SIZE=o??this.CELL_SIZE;for(let l of n)this.addObject(l)}_getNextId(){return`${this._idCounter++}`}addObject(n){let t=this.getBounds(n),a=this.getId(n),o={...n,spatialIndexId:a};this.objectsById.set(a,o);let l=Math.floor(t.minX/this.CELL_SIZE),p=Math.floor(t.minY/this.CELL_SIZE),x=Math.floor(t.maxX/this.CELL_SIZE),m=Math.floor(t.maxY/this.CELL_SIZE);for(let g=l;g<=x;g++)for(let _=p;_<=m;_++){let F=`${g}x${_}`,C=this.buckets.get(F);C?C.push(o):this.buckets.set(F,[o])}}removeObject(n){let t=this.objectsById.get(n);if(!t)return!1;this.objectsById.delete(n);let a=this.getBounds(t),o=Math.floor(a.minX/this.CELL_SIZE),l=Math.floor(a.minY/this.CELL_SIZE),p=Math.floor(a.maxX/this.CELL_SIZE),x=Math.floor(a.maxY/this.CELL_SIZE);for(let m=o;m<=p;m++)for(let g=l;g<=x;g++){let _=`${m}x${g}`,F=this.buckets.get(_);if(F){let C=F.findIndex(S=>S.spatialIndexId===n);C!==-1&&(F.splice(C,1),F.length===0&&this.buckets.delete(_))}}return!0}getBucketKey(n,t){return`${Math.floor(n/this.CELL_SIZE)}x${Math.floor(t/this.CELL_SIZE)}`}getObjectsInBounds(n,t=0){let a=[],o=new Set,l=Math.floor((n.minX-t)/this.CELL_SIZE),p=Math.floor((n.minY-t)/this.CELL_SIZE),x=Math.floor((n.maxX+t)/this.CELL_SIZE),m=Math.floor((n.maxY+t)/this.CELL_SIZE);for(let g=l;g<=x;g++)for(let _=p;_<=m;_++){let F=`${g}x${_}`,C=this.buckets.get(F)||[];for(let S of C){let P=S.spatialIndexId;o.has(P)||(o.add(P),a.push(S))}}return a}},Wb=n=>n.type==="pcb_trace_segment"?{minX:Math.min(n.x1,n.x2),minY:Math.min(n.y1,n.y2),maxX:Math.max(n.x1,n.x2),maxY:Math.max(n.y1,n.y2)}:SCe([n]),aW=.1,k$t=.15;var iW=.005;function j$t(n){let t=new Set;for(let a of n.route)a.route_type==="wire"&&(a.start_pcb_port_id&&t.add(a.start_pcb_port_id),a.end_pcb_port_id&&t.add(a.end_pcb_port_id));return Array.from(t)}function sW(n){let t=new Set;for(let a of n)for(let o of j$t(a))t.add(o);return Array.from(t)}var N$t=(n,t)=>{let a={x:n.x1,y:n.y1},o={x:n.x2,y:n.y2},l={x:t.x1,y:t.y1},p={x:t.x2,y:t.y2},x={x:o.x-a.x,y:o.y-a.y},m={x:p.x-l.x,y:p.y-l.y},g=x.x*x.x+x.y*x.y,_=m.x*m.x+m.y*m.y;if(g===0||_===0){if(g===0&&_===0)return{x:(a.x+l.x)/2,y:(a.y+l.y)/2};if(g===0){let Ae=xx(((a.x-l.x)*m.x+(a.y-l.y)*m.y)/_,0,1),de={x:l.x+Ae*m.x,y:l.y+Ae*m.y};return{x:(a.x+de.x)/2,y:(a.y+de.y)/2}}let pe=xx(((l.x-a.x)*x.x+(l.y-a.y)*x.y)/g,0,1),he={x:a.x+pe*x.x,y:a.y+pe*x.y};return{x:(he.x+l.x)/2,y:(he.y+l.y)/2}}let F={x:a.x-l.x,y:a.y-l.y},C=x.x*x.x+x.y*x.y,S=x.x*m.x+x.y*m.y,P=x.x*F.x+x.y*F.y,k=m.x*m.x+m.y*m.y,q=m.x*F.x+m.y*F.y,X=C*k-S*S;if(X<1e-10)return M$t(a,o,l,p,x,m,g,_);let Q=(S*q-k*P)/X,ee=(C*q-S*P)/X;Q=xx(Q,0,1),ee=xx(ee,0,1),ee=(Q*S+q)/k,ee=xx(ee,0,1),Q=(ee*S-P)/C,Q=xx(Q,0,1);let ue={x:a.x+Q*x.x,y:a.y+Q*x.y},ce={x:l.x+ee*m.x,y:l.y+ee*m.y},fe=ue.x-ce.x,U=ue.y-ce.y,me=Math.sqrt(fe*fe+U*U);return{x:(ue.x+ce.x)/2,y:(ue.y+ce.y)/2}},M$t=(n,t,a,o,l,p,x,m)=>{let g=((a.x-n.x)*l.x+(a.y-n.y)*l.y)/x;g=xx(g,0,1);let _={x:n.x+g*l.x,y:n.y+g*l.y},F=((o.x-n.x)*l.x+(o.y-n.y)*l.y)/x;F=xx(F,0,1);let C={x:n.x+F*l.x,y:n.y+F*l.y},S=((n.x-a.x)*p.x+(n.y-a.y)*p.y)/m;S=xx(S,0,1);let P={x:a.x+S*p.x,y:a.y+S*p.y},k=((t.x-a.x)*p.x+(t.y-a.y)*p.y)/m;k=xx(k,0,1);let q={x:a.x+k*p.x,y:a.y+k*p.y},Q=[{pointA:_,pointB:a,distance:Math.sqrt((_.x-a.x)**2+(_.y-a.y)**2)},{pointA:C,pointB:o,distance:Math.sqrt((C.x-o.x)**2+(C.y-o.y)**2)},{pointA:n,pointB:P,distance:Math.sqrt((n.x-P.x)**2+(n.y-P.y)**2)},{pointA:t,pointB:q,distance:Math.sqrt((t.x-q.x)**2+(t.y-q.y)**2)}].reduce((ee,ue)=>ue.distance<ee.distance?ue:ee);return{x:(Q.pointA.x+Q.pointB.x)/2,y:(Q.pointA.y+Q.pointB.y)/2}},xx=(n,t,a)=>Math.max(t,Math.min(a,n)),O$t=n=>{if(n.type==="pcb_via"||n.type==="pcb_plated_hole"&&n.shape==="circle")return n.outer_diameter/2;if(n.type==="pcb_hole"&&n.hole_shape==="circle")return n.hole_diameter/2;if(n.type==="pcb_smtpad"&&n.shape==="circle")return n.radius;throw new Error(`Could not determine radius of element: ${JSON.stringify(n)}`)},yAe=(n,t)=>{let a={x:n.x1,y:n.y1},o={x:n.x2,y:n.y2},l=t.minX,p=t.minY,x=t.maxX,m=t.maxY;if(a.x===o.x&&a.y===o.y){let W=Math.max(l,Math.min(x,a.x)),pe=Math.max(p,Math.min(m,a.y));return W===a.x&&pe===a.y?{x:a.x,y:a.y}:{x:W,y:pe}}let g=o.x-a.x,_=o.y-a.y,F=g!==0?(l-a.x)/g:Number.NEGATIVE_INFINITY,C=g!==0?(x-a.x)/g:Number.POSITIVE_INFINITY,S=_!==0?(p-a.y)/_:Number.NEGATIVE_INFINITY,P=_!==0?(m-a.y)/_:Number.POSITIVE_INFINITY,k=Math.max(Math.min(F,C),Math.min(S,P)),q=Math.min(Math.max(F,C),Math.max(S,P));if(k<=q&&q>=0&&k<=1){let W=Math.max(0,Math.min(1,k));return{x:a.x+W*g,y:a.y+W*_}}let X={x:Math.max(l,Math.min(x,a.x)),y:Math.max(p,Math.min(m,a.y))},Q={x:Math.max(l,Math.min(x,o.x)),y:Math.max(p,Math.min(m,o.y))},ee=(X.x-a.x)**2+(X.y-a.y)**2,ue=(Q.x-o.x)**2+(Q.y-o.y)**2,ce=[{start:{x:l,y:p},end:{x,y:p}},{start:{x,y:p},end:{x,y:m}},{start:{x,y:m},end:{x:l,y:m}},{start:{x:l,y:m},end:{x:l,y:p}}],fe=Math.min(ee,ue),U=ee<=ue?X:Q,me=(W,pe,he)=>Math.max(pe,Math.min(he,W));for(let W of ce){let pe={x:o.x-a.x,y:o.y-a.y},he={x:W.end.x-W.start.x,y:W.end.y-W.start.y},Ae={x:a.x-W.start.x,y:a.y-W.start.y},de=pe.x*pe.x+pe.y*pe.y,Ne=pe.x*he.x+pe.y*he.y,Te=pe.x*Ae.x+pe.y*Ae.y,Ke=he.x*he.x+he.y*he.y,Qe=he.x*Ae.x+he.y*Ae.y,pt=de*Ke-Ne*Ne;if(Math.abs(pt)<1e-10)continue;let jt=(Ne*Qe-Ke*Te)/pt,vt=(de*Qe-Ne*Te)/pt;jt=me(jt,0,1),vt=me(vt,0,1);let xt={x:a.x+jt*pe.x,y:a.y+jt*pe.y},dt={x:W.start.x+vt*he.x,y:W.start.y+vt*he.y},ar=xt.x-dt.x,Wt=xt.y-dt.y,cr=ar*ar+Wt*Wt;cr<fe&&(fe=cr,U={x:(xt.x+dt.x)/2,y:(xt.y+dt.y)/2})}return U};function L$t(n){return n.type==="pcb_trace_segment"?[n.layer]:n.type==="pcb_smtpad"?[n.layer]:n.type==="pcb_plated_hole"?Array.isArray(n.layers)?n.layers:[...C2]:n.type==="pcb_hole"?[...C2]:n.type==="pcb_via"?Array.isArray(n.layers)?n.layers:[...C2]:n.type==="pcb_keepout"?Array.isArray(n.layers)?n.layers:[]:[]}function gAe(n,{connMap:t}={}){let a=[];t??(t=rx(n));let l=vi(n).pcb_trace.list().flatMap(k=>{let q=[];for(let X=0;X<k.route.length-1;X++){let Q=k.route[X],ee=k.route[X+1];Q.route_type==="wire"&&ee.route_type==="wire"&&Q.layer===ee.layer&&q.push({type:"pcb_trace_segment",pcb_trace_id:k.pcb_trace_id,_pcbTrace:k,thickness:"width"in Q?Q.width:"width"in ee?ee.width:k$t,layer:Q.layer,x1:Q.x,y1:Q.y,x2:ee.x,y2:ee.y})}return q}),p=vi(n).pcb_smtpad.list(),x=vi(n).pcb_plated_hole.list(),m=vi(n).pcb_hole.list(),g=vi(n).pcb_via.list(),_=vi(n).pcb_keepout.list(),F=[...l,...p,...x,...m,...g,..._],C=new P$t({objects:F,getBounds:Wb}),S=k=>bb(n,k),P=new Set;for(let k of l){let q=aW,X=Wb(k),Q=C.getObjectsInBounds(X,q+k.thickness/2);if(!(k.x1===k.x2&&k.y1===k.y2))for(let ee of Q){if(!L$t(ee).includes(k.layer))continue;if(ee.type==="pcb_trace_segment"){let U=ee;if(k.layer!==U.layer||t.areIdsConnected(k.pcb_trace_id,U.pcb_trace_id))continue;let me=n7({x:k.x1,y:k.y1},{x:k.x2,y:k.y2},{x:U.x1,y:U.y1},{x:U.x2,y:U.y2})-k.thickness/2-U.thickness/2;if(me>aW-iW)continue;let W=`overlap_${k.pcb_trace_id}_${U.pcb_trace_id}`,pe=`overlap_${U.pcb_trace_id}_${k.pcb_trace_id}`;if(P.has(W)||P.has(pe))continue;P.add(W),a.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${S(k.pcb_trace_id)} overlaps with ${S(U.pcb_trace_id)} ${me<0?"(accidental contact)":`(gap: ${me.toFixed(3)}mm)`}`,pcb_trace_id:k.pcb_trace_id,source_trace_id:"",pcb_trace_error_id:W,pcb_component_ids:[],center:N$t(k,U),pcb_port_ids:sW([k._pcbTrace,U._pcbTrace])});continue}let ue=Z2(ee);if(t.areIdsConnected(k.pcb_trace_id,"pcb_trace_id"in ee?ee.pcb_trace_id:ue))continue;if(ee.type==="pcb_via"||ee.type==="pcb_plated_hole"&&ee.shape==="circle"||ee.type==="pcb_hole"||ee.type==="pcb_smtpad"&&ee.shape==="circle"){let U=O$t(ee),W=a7({x:k.x1,y:k.y1},{x:k.x2,y:k.y2},{x:ee.x,y:ee.y,radius:U})-k.thickness/2;if(W>aW-iW)continue;let pe=`overlap_${k.pcb_trace_id}_${ue}`;if(P.has(pe))continue;P.add(pe),a.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${S(k.pcb_trace_id)} overlaps with ${ee.type} "${S(Z2(ee))}" ${W<0?"(accidental contact)":`(gap: ${W.toFixed(3)}mm)`}`,pcb_trace_id:k.pcb_trace_id,center:yAe(k,Wb(ee)),source_trace_id:"",pcb_trace_error_id:pe,pcb_component_ids:["pcb_component_id"in ee?ee.pcb_component_id:void 0].filter(Boolean),pcb_port_ids:[...sW([k._pcbTrace]),"pcb_port_id"in ee?ee.pcb_port_id:void 0].filter(Boolean)})}let fe=ub({x:k.x1,y:k.y1},{x:k.x2,y:k.y2},Wb(ee))-k.thickness/2;if(fe+iW<q){let U=`overlap_${k.pcb_trace_id}_${ue}`;if(P.has(U))continue;P.add(U),a.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${S(k.pcb_trace_id)} overlaps with ${ee.type} "${S(Z2(ee))}" ${fe<0?"(accidental contact)":`(gap: ${fe.toFixed(3)}mm)`}`,pcb_trace_id:k.pcb_trace_id,source_trace_id:"",pcb_trace_error_id:U,pcb_component_ids:["pcb_component_id"in ee?ee.pcb_component_id:void 0].filter(Boolean),center:yAe(k,Wb(ee)),pcb_port_ids:[...sW([k._pcbTrace]),"pcb_port_id"in ee?ee.pcb_port_id:void 0].filter(Boolean)})}}}return a}var oW=[{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 o0(n){if(n==null)return"";if(n===0)return"0";let t=Math.abs(n),a=oW.find(p=>{let x=t/p.value;return x>=1&&x<1e3})||oW[oW.length-1],l=(n/a.value).toPrecision(3);return l.includes(".")&&!/\.0+$/.test(l)&&(l=l.replace(/0+$/,"")),l=l.replace(/\.0+$/,""),`${l}${a.symbol}`}Bf();za();var fRe=Cr(ju(),1);var b_=Cr(ju(),1),j1r=Cr(ju(),1);var Gg=Cr(ya(),1);var mRe=Cr(ya(),1),hRe=Cr(ya(),1);var yRe=Cr(ya(),1);var gRe=Cr(ya(),1);var DRe=Cr(ya(),1),_Re=Cr(ju(),1);var oUt=Object.defineProperty,cUt=(n,t)=>{for(var a in t)oUt(n,a,{get:t[a],enumerable:!0})},x7e={};cUt(x7e,{Battery:()=>Z7e,Board:()=>T7e,Breakout:()=>G7e,BreakoutPoint:()=>H7e,Capacitor:()=>P7e,Chip:()=>PW,Constraint:()=>$7e,Crystal:()=>aRe,Cutout:()=>i8,Diode:()=>k7e,FabricationNotePath:()=>q7e,FabricationNoteText:()=>U7e,Footprint:()=>E7e,Fuse:()=>j7e,Group:()=>F_,Hole:()=>SW,Inductor:()=>tRe,Jumper:()=>N7e,Keepout:()=>yR,Led:()=>O7e,Mosfet:()=>sRe,Net:()=>AW,NetLabel:()=>Y7e,NormalComponent:()=>es,PcbTrace:()=>wW,PinHeader:()=>Q7e,PlatedHole:()=>hR,Port:()=>cu,Potentiometer:()=>rRe,PowerSource:()=>L7e,PrimitiveComponent:()=>Ya,PushButton:()=>nRe,Renderable:()=>EW,Resistor:()=>z7e,Resonator:()=>eRe,SchematicBox:()=>lRe,SchematicCell:()=>xRe,SchematicRow:()=>pRe,SchematicTable:()=>dRe,SchematicText:()=>uRe,SilkscreenCircle:()=>X7e,SilkscreenLine:()=>K7e,SilkscreenPath:()=>IW,SilkscreenRect:()=>W7e,SilkscreenText:()=>_R,SmtPad:()=>mR,SolderJumper:()=>M7e,Subcircuit:()=>V7e,Switch:()=>oRe,TestPoint:()=>cRe,Trace:()=>Od,TraceHint:()=>TW,Transistor:()=>iRe,Via:()=>J7e});var uUt=(0,y7e.default)("tscircuit:renderable"),$f=["ReactSubtreesRender","PcbFootprintStringRender","InitializePortsFromChildren","CreateNetsFromProps","CreateTracesFromProps","CreateTracesFromNetLabels","CreateTraceHintsFromProps","SourceGroupRender","AssignNameToUnnamedComponents","SourceRender","SourceParentAttachment","PortMatching","OptimizeSelectorCache","SourceTraceRender","SourceAddConnectivityMapKey","SimulationRender","SchematicComponentRender","SchematicPortRender","SchematicPrimitiveRender","SchematicLayout","SchematicTraceRender","SchematicReplaceNetLabelsWithSymbols","PcbComponentRender","PcbPrimitiveRender","PcbFootprintLayout","PcbPortRender","PcbPortAttachment","PcbComponentSizeCalculation","PcbLayout","PcbBoardAutoSize","PcbTraceHintRender","PcbManualTraceRender","PcbTraceRender","PcbRouteNetIslands","PcbDesignRuleChecks","CadModelRender","PartsEngineRender"],lUt=0,EW=class{constructor(n){J(this,"renderPhaseStates");J(this,"shouldBeRemoved",!1);J(this,"children");J(this,"isPcbPrimitive",!1);J(this,"isSchematicPrimitive",!1);J(this,"_renderId");J(this,"_currentRenderPhase",null);J(this,"_asyncEffects",[]);J(this,"parent",null);this._renderId=`${lUt++}`,this.children=[],this.renderPhaseStates={};for(let t of $f)this.renderPhaseStates[t]={initialized:!1,dirty:!1}}_markDirty(n){this.renderPhaseStates[n].dirty=!0;let t=$f.indexOf(n);for(let a=t+1;a<$f.length;a++)this.renderPhaseStates[$f[a]].dirty=!0;this.parent?._markDirty&&this.parent._markDirty(n)}_queueAsyncEffect(n,t){let a={promise:t(),phase:this._currentRenderPhase,effectName:n,complete:!1};this._asyncEffects.push(a),"root"in this&&this.root&&this.root.emit("asyncEffect:start",{effectName:n,componentDisplayName:this.getString(),phase:a.phase}),a.promise.then(()=>{a.complete=!0,"root"in this&&this.root&&this.root.emit("asyncEffect:end",{effectName:n,componentDisplayName:this.getString(),phase:a.phase})}).catch(o=>{console.error(`Async effect error in ${a.phase} "${n}":
1035
1035
  ${o.stack}`),a.complete=!0,"root"in this&&this.root&&this.root.emit("asyncEffect:end",{effectName:n,componentDisplayName:this.getString(),phase:a.phase,error:o.toString()})})}_emitRenderLifecycleEvent(n,t){uUt(`${n}:${t} ${this.getString()}`);let a=`renderable:renderLifecycle:${n}:${t}`,o={renderId:this._renderId,componentDisplayName:this.getString(),type:a};"root"in this&&this.root&&(this.root.emit(a,o),this.root.emit("renderable:renderLifecycle:anyEvent",{...o,type:a}))}getString(){return this.constructor.name}_hasIncompleteAsyncEffects(){return this._asyncEffects.some(n=>!n.complete)}getCurrentRenderPhase(){return this._currentRenderPhase}getRenderGraph(){return{id:this._renderId,currentPhase:this._currentRenderPhase,renderPhaseStates:this.renderPhaseStates,shouldBeRemoved:this.shouldBeRemoved,children:this.children.map(n=>n.getRenderGraph())}}runRenderCycle(){for(let n of $f)this.runRenderPhaseForChildren(n),this.runRenderPhase(n)}runRenderPhase(n){this._currentRenderPhase=n;let t=this.renderPhaseStates[n],a=t.initialized,o=t.dirty;if(!a&&this.shouldBeRemoved)return;if(this.shouldBeRemoved&&a){this._emitRenderLifecycleEvent(n,"start"),this?.[`remove${n}`]?.(),t.initialized=!1,t.dirty=!1,this._emitRenderLifecycleEvent(n,"end");return}let l=$f.indexOf(n)-1;if(l>=0){let p=$f[l];if(this._asyncEffects.filter(m=>m.phase===p).some(m=>!m.complete))return}if(this._emitRenderLifecycleEvent(n,"start"),a){o&&(this?.[`update${n}`]?.(),t.dirty=!1),this._emitRenderLifecycleEvent(n,"end");return}t.dirty=!1,this?.[`doInitial${n}`]?.(),t.initialized=!0,this._emitRenderLifecycleEvent(n,"end")}runRenderPhaseForChildren(n){for(let t of this.children)t.runRenderPhaseForChildren(n),t.runRenderPhase(n)}renderError(n){throw typeof n=="string"?new Error(n):new Error(JSON.stringify(n,null,2))}},fR={},g7e=n=>{let t=Object.fromEntries(Object.entries(n).map(([a,o])=>[a.toLowerCase(),o]));Object.assign(fR,n),Object.assign(fR,t)},dUt=class extends Error{constructor(n,t,a){let o,l=Object.keys(a).filter(g=>g!=="_errors"),p=[],x=t.pinLabels;if(x)for(let[g,_]of Object.entries(x)){let F=Array.isArray(_)?_:[_];for(let C of F)typeof C=="string"&&(C.startsWith(" ")||C.endsWith(" "))&&p.push(`pinLabels.${g} ("${C}" has leading or trailing spaces)`)}let m=l.map(g=>g==="pinLabels"&&p.length>0?p.join(", "):a[g]._errors[0]?`${g} (${a[g]._errors[0]})`:`${g} (${JSON.stringify(a[g])})`).join(", ");"name"in t?o=`Invalid props for ${n} "${t.name}": ${m}`:"footprint"in t&&typeof t.footprint=="string"?o=`Invalid props for ${n} (unnamed ${t.footprint} component): ${m}`:o=`Invalid props for ${n} (unnamed): ${m}`,super(o),this.componentName=n,this.originalProps=t,this.formattedError=a}};function yW(n,t){let a=t.match(/^#(\w+)/);if(a)return n.props.id===a[1];let o=t.match(/^\.(\w+)/);if(o)return n.isMatchingNameOrAlias(o[1]);let[l,...p]=t.split(/(?=[#.[])/);return l==="pin"&&(l="port"),l&&l!=="*"&&n.lowercaseComponentName!==l.toLowerCase()?!1:p.every(x=>{if(x.startsWith("#"))return n.props.id===x.slice(1);if(x.startsWith("."))return n.isMatchingNameOrAlias(x.slice(1));let m=x.match(/\[(\w+)=['"]?(.+?)['"]?\]/);if(!m)return!0;let[,g,_]=m;return n.props[g].toString()===_})}var CW={isTag:n=>!0,getParent:n=>n.parent,getChildren:n=>n.children,getName:n=>n.lowercaseComponentName,getAttributeValue:(n,t)=>{if(t==="class"&&"getNameAndAliases"in n)return n.getNameAndAliases().join(" ");if(t==="name"&&n._parsedProps?.name)return n._parsedProps.name;if(n._parsedProps&&t in n._parsedProps){let a=n._parsedProps[t];return typeof a=="string"?a:a!=null?String(a):null}return null},hasAttrib:(n,t)=>t==="class"?!!n._parsedProps?.name:n._parsedProps&&t in n._parsedProps,getSiblings:n=>n.parent?n.parent.children:[],prevElementSibling:n=>{if(!n.parent)return null;let t=n.parent.children,a=t.indexOf(n);return a>0?t[a-1]:null},getText:()=>"",removeSubsets:n=>n.filter((t,a)=>!n.some((o,l)=>a!==l&&o!==t&&o.getDescendants().includes(t))),existsOne:(n,t)=>t.some(n),findAll:(n,t)=>{let a=[],o=l=>{n(l)&&a.push(l);for(let p of l.children)o(p)};for(let l of t)o(l);return a},findOne:(n,t)=>{for(let a of t){if(n(a))return a;let o=a.children;if(o.length>0){let l=CW.findOne(n,o);if(l)return l}}return null},equals:(n,t)=>n._renderId===t._renderId,isHovered:n=>!1,isVisited:n=>!1,isActive:n=>!1},pUt={...CW,getChildren:n=>n.children.filter(t=>!t.isSubcircuit)},t7e={...CW,getChildren:n=>n.children.filter(t=>t.isSubcircuit)},r7e=n=>{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 t=n.match(/net\.([^ >]+)/),a=t?t[1]:"";throw new Error(`Net name "${a}" cannot start with a number, try using a prefix like "VBUS1"`)}return n.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,a,o,l)=>{let p=/^\d+$/.test(l)?`pin${l}`:l;return`${a}.${o} > .${p}`}).trim()},gW={adapter:pUt,cacheResults:!0},Ya=class extends EW{constructor(t){super(t);J(this,"parent",null);J(this,"children");J(this,"childrenPendingRemoval");J(this,"props");J(this,"_parsedProps");J(this,"externallyAddedAliases");J(this,"isPrimitiveContainer",!1);J(this,"canHaveTextChildren",!1);J(this,"source_group_id",null);J(this,"source_component_id",null);J(this,"schematic_component_id",null);J(this,"pcb_component_id",null);J(this,"cad_component_id",null);J(this,"fallbackUnassignedName");J(this,"_cachedSelectAllQueries",new Map);J(this,"_cachedSelectOneQueries",new Map);this.children=[],this.childrenPendingRemoval=[],this.props=t??{},this.externallyAddedAliases=[];let o=("partial"in this.config.zodProps?this.config.zodProps.partial({name:!0}):this.config.zodProps).safeParse(t??{});if(o.success)this._parsedProps=o.data;else throw new dUt(this.lowercaseComponentName,this.props,o.error.format())}get config(){return{componentName:"",zodProps:E.object({}).passthrough()}}get componentName(){return this.config.componentName}getInheritedProperty(t){let a=this;for(;a;){if(a._parsedProps&&t in a._parsedProps)return a._parsedProps[t];a=a.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 a=this.config.zodProps.parse({...this.props,...t}),o=this.props;this.props=a,this._parsedProps=this.config.zodProps.parse(t),this.onPropsChange({oldProps:o,newProps:a,changedProps:Object.keys(t)}),this.parent?.onChildChanged?.(this)}computePcbPropsTransform(){let{_parsedProps:t}=this;return qs(si(t.pcbX??0,t.pcbY??0),fg((t.pcbRotation??0)*Math.PI/180))}_computePcbGlobalTransformBeforeLayout(){let{_parsedProps:t}=this,a=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if(a&&this.props.pcbX===void 0&&this.props.pcbY===void 0)return qs(this.parent?._computePcbGlobalTransformBeforeLayout()??gc(),qs(si(a.x,a.y),fg((t.pcbRotation??0)*Math.PI/180)));if(this.isPcbPrimitive){let o=this.getPrimitiveContainer();if(o){let l=o._parsedProps.layer==="bottom",p=o._getGlobalPcbPositionBeforeLayout();if(l){let x=qs(si(p.x,p.y),Hq(),si(-p.x,-p.y));return qs(this.parent?._computePcbGlobalTransformBeforeLayout()??gc(),Hq(),this.computePcbPropsTransform())}}}return qs(this.parent?._computePcbGlobalTransformBeforeLayout()??gc(),this.computePcbPropsTransform())}getPrimitiveContainer(){return this.isPrimitiveContainer?this:this.parent?.getPrimitiveContainer?.()??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(),a=t?t._parsedProps.layer==="bottom":!1;return{isFlipped:a,maybeFlipLayer:l=>a?l==="top"?"bottom":"top":l}}_setPositionFromLayout(t){throw new Error(`_setPositionFromLayout not implemented for ${this.componentName}`)}computeSchematicPropsTransform(){let{_parsedProps:t}=this;return qs(si(t.schX??0,t.schY??0))}computeSchematicGlobalTransform(){let t=this._getSchematicGlobalManualPlacementTransform(this);return t||qs(this.parent?.computeSchematicGlobalTransform?.()??gc(),this.computeSchematicPropsTransform())}_getSchematicSymbolName(){let{_parsedProps:t}=this,a=this.config.schematicSymbolName,o={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},l=t.schOrientation!==void 0?o[t.schOrientation]:t.schRotation;if(l===void 0&&(l=0),l=l%360,l<0&&(l+=360),t.schRotation!==void 0&&l%90!==0)throw new Error(`Schematic rotation ${t.schRotation} is not supported for ${this.componentName}`);let p=`${a}_horz`,x=`${a}_vert`,m=`${a}_up`,g=`${a}_down`,_=`${a}_left`,F=`${a}_right`;if(F in Us&&l===0)return F;if(m in Us&&l===90)return m;if(_ in Us&&l===180)return _;if(g in Us&&l===270)return g;if(p in Us&&(l===0||l===180))return p;if(x in Us&&(l===90||l===270))return x;if(a in Us)return a}_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?Us[t]??null:null}_getPcbManualPlacementForComponent(t){if(!this.isSubcircuit)return null;let a=this.props.manualEdits;if(!a)return null;let o=a?.pcb_placements;if(!o)return null;for(let l of o)if(yW(t,l.selector)||t.props.name===l.selector)return Ss(this._computePcbGlobalTransformBeforeLayout(),l.center);return null}_getSchematicManualPlacementForComponent(t){if(!this.isSubcircuit)return null;let a=this.props.manualEdits;if(!a)return null;let o=a.schematic_placements;if(!o)return null;for(let l of o)if(yW(t,l.selector)||t.props.name===l.selector)return Ss(this.computeSchematicGlobalTransform(),l.center);return null}_getSchematicGlobalManualPlacementTransform(t){let a=this.getSubcircuit()?._parsedProps.manualEdits;if(!a)return null;for(let o of a.schematic_placements??[])if((yW(t,o.selector)||t.props.name===o.selector)&&o.relative_to==="group_center")return qs(this.parent?._computePcbGlobalTransformBeforeLayout()??gc(),si(o.center.x,o.center.y));return null}_getGlobalPcbPositionBeforeLayout(){return Ss(this._computePcbGlobalTransformBeforeLayout(),{x:0,y:0})}_getGlobalSchematicPositionBeforeLayout(){return Ss(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 a=t.__text;if(typeof a=="string"){if(this.canHaveTextChildren||a.trim()==="")return;throw new Error(`Invalid JSX Element: Expected a React component but received text "${a}"`)}if(Object.keys(t).length!==0){if(this.lowercaseComponentName==="board"&&t.lowercaseComponentName==="board")throw new Error("Nested boards are not supported");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 a of t)this.add(a)}remove(t){this.children=this.children.filter(a=>a!==t),this.childrenPendingRemoval.push(t),t.shouldBeRemoved=!0}getSubcircuitSelector(){let t=this.name,a=t?`${this.lowercaseComponentName}.${t}`:this.lowercaseComponentName;return!this.parent||this.parent.isSubcircuit?a:`${this.parent.getSubcircuitSelector()} > ${a}`}getFullPathSelector(){let t=this.name,a=t?`${this.lowercaseComponentName}.${t}`:this.lowercaseComponentName,o=this.parent?.getFullPathSelector?.();return o?`${o} > ${a}`:a}getNameAndAliases(){return[this.name,...this._parsedProps.portHints??[]].filter(Boolean)}isMatchingNameOrAlias(t){return this.getNameAndAliases().includes(t)}isMatchingAnyOf(t){return this.getNameAndAliases().some(a=>t.map(o=>o.toString()).includes(a))}getPcbSize(){throw new Error(`getPcbSize not implemented for ${this.componentName}`)}doesSelectorMatch(t){let a=[this.componentName,this.lowercaseComponentName],o=[this.name].filter(Boolean),l=t.trim().split(/\> /)[0],p=l[0];return l.length>1?!1:!!(t==="*"||t[0]==="#"&&t.slice(1)===this.props.id||t[0]==="."&&o.includes(t.slice(1))||/^[a-zA-Z0-9_]/.test(p)&&a.includes(p))}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 a of t){let o=a.parent?.getNameAndAliases(),l=a.getNameAndAliases();if(o)for(let p of o)for(let x of l){let m=[`.${p} > .${x}`,`.${p} .${x}`];for(let g of m){let _=this._cachedSelectAllQueries.get(g);_?_.push(a):this._cachedSelectAllQueries.set(g,[a])}}}for(let[a,o]of this._cachedSelectAllQueries.entries())o.length===1&&this._cachedSelectOneQueries.set(a,o[0])}selectAll(t){if(this._cachedSelectAllQueries.has(t))return this._cachedSelectAllQueries.get(t);let a=r7e(t),o=tY(a,this,gW);if(o.length>0)return this._cachedSelectAllQueries.set(t,o),o;let[l,...p]=a.split(" "),x=qA(l,this,{adapter:t7e});if(!x)return[];let m=x.selectAll(p.join(" "));return this._cachedSelectAllQueries.set(t,m),m}selectOne(t,a){if(this._cachedSelectOneQueries.has(t))return this._cachedSelectOneQueries.get(t);let o=r7e(t);a?.port&&(a.type="port");let l=null;if(a?.type&&(l=tY(o,this,gW).find(_=>_.lowercaseComponentName===a.type)),l??(l=qA(o,this,gW)),l)return this._cachedSelectOneQueries.set(t,l),l;let[p,...x]=o.split(" "),m=qA(p,this,{adapter:t7e});return m?(l=m.selectOne(x.join(" "),a),this._cachedSelectOneQueries.set(t,l),l):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 a of this.children)t.push(a),t.push(...a.getDescendants());return t}getSelectableDescendants(){let t=[];for(let a of this.children)a.isSubcircuit?t.push(a):(t.push(a),t.push(...a.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);this.root?.db.pcb_placement_error.insert(t)}getString(){let{lowercaseComponentName:t,_parsedProps:a,parent:o}=this;return a?.pinNumber!==void 0&&o?.props?.name&&a?.name?`<${t}#${this._renderId}(pin:${a.pinNumber} .${o?.props.name}>.${a.name}) />`:o?.props?.name&&a?.name?`<${t}#${this._renderId}(.${o?.props.name}>.${a?.name}) />`:a?.from&&a?.to?`<${t}#${this._renderId}(from:${a.from} to:${a?.to}) />`:a?.name?`<${t}#${this._renderId} name=".${a?.name}" />`:a?.portHints?`<${t}#${this._renderId}(${a.portHints.map(l=>`.${l}`).join(", ")}) />`:`<${t}#${this._renderId} />`}get[Symbol.toStringTag](){return this.getString()}[Symbol.for("nodejs.util.inspect.custom")](){return this.getString()}},xUt=class extends Ya{constructor(n,t){super(n),this._parsedProps={...n,error:t,type:n.type||"unknown",component_name:n.name,error_type:"source_failed_to_create_component_error",message:t instanceof Error?t.message:String(t),pcbX:n.pcbX,pcbY:n.pcbY,schX:n.schX,schY:n.schY}}get config(){return{componentName:"ErrorPlaceholder",zodProps:E.object({}).passthrough()}}doInitialSourceRender(){if(this.root?.db){let n=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:this._parsedProps.error?.formattedError?._errors?.join("; ")||this._parsedProps.message,pcb_center:n,schematic_center:t})}}};function fUt(n,t){return new xUt(n,t)}function mUt(n,t){let a=n;return a.__tsci={...t},n}var n7e={supportsMutation:!0,createInstance(n,t){let a=fR[n];if(!a)throw Object.keys(fR).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 "${n}". 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 mUt(new a(t),{})}catch(o){return fUt(t,o)}},createTextInstance(n){return{__text:n}},appendInitialChild(n,t){n.add(t)},appendChild(n,t){n.add(t)},appendChildToContainer(n,t){n.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(n){return n},preparePortalMount(n){throw new Error("Function not implemented.")},scheduleTimeout(n,t){throw new Error("Function not implemented.")},cancelTimeout(n){throw new Error("Function not implemented.")},noTimeout:void 0,isPrimaryRenderer:!1,getInstanceFromNode(n){throw new Error("Function not implemented.")},beforeActiveInstanceBlur(){throw new Error("Function not implemented.")},afterActiveInstanceBlur(){throw new Error("Function not implemented.")},prepareScopeUpdate:(n,t)=>{throw new Error("Function not implemented.")},getInstanceFromScope:n=>{throw new Error("Function not implemented.")},detachDeletedInstance:n=>{throw new Error("Function not implemented.")},getCurrentEventPriority:()=>pR.DefaultEventPriority,getCurrentUpdatePriority:()=>pR.DefaultEventPriority,resolveUpdatePriority:()=>pR.DefaultEventPriority,setCurrentUpdatePriority:()=>{},maySuspendCommit:()=>!1,supportsHydration:!1},Ug;vW.default.version.startsWith("19.")?Ug=(0,m7e.default)(n7e):Ug=(0,h7e.default)(n7e);var D7e=n=>{let t={children:[],props:{name:"$root"},add(p){p.parent=this,this.children.push(p)},computePcbGlobalTransform(){return gc()}},a=[],o=Ug.createContainer(t,0,null,!1,null,"tsci",p=>{console.log("Error in createContainer"),console.error(p),a.push(p)},null);if(vW.default.version.startsWith("19.")?(Ug.updateContainerSync(n,o,null,()=>{}),Ug.flushSyncWork()):Ug.updateContainer(n,o,null,()=>{}),a.length>0)throw a[0];let l=Ug.getPublicRootInstance(o);return l||t.children[0]},s8=(n,t)=>{if(typeof n=="number")return n;if(n.startsWith("pin"))return Number(n.slice(3));if(!t)throw new Error(`No pin labels provided and pin number or label is not a number: "${n}"`);for(let a in t)if((Array.isArray(t[a])?t[a]:[t[a]]).includes(n))return Number(a.replace("pin",""));throw new Error(`No pin labels provided and pin number or label is not a number: "${n}"`)},hUt=(n,t)=>{if(!n)return;let a={},o={};for(let[l,p]of Object.entries(n)){let x=s8(l,t);o[x]={...o[x],...p}}for(let[l,p]of Object.entries(o)){let x=`pin${l}`;a[x]={bottom_margin:p.bottomMargin,left_margin:p.leftMargin,right_margin:p.rightMargin,top_margin:p.topMargin}}return a},yUt=n=>{if(n){if("leftSide"in n||"rightSide"in n||"topSide"in n||"bottomSide"in n)return{left_side:n.leftSide,right_side:n.rightSide,top_side:n.topSide,bottom_side:n.bottomSide};if("leftPinCount"in n||"rightPinCount"in n||"topPinCount"in n||"bottomPinCount"in n)return{left_size:n.leftPinCount,right_size:n.rightPinCount,top_size:n.topPinCount,bottom_size:n.bottomPinCount};if("leftSize"in n||"rightSize"in n||"topSize"in n||"bottomSize"in n)return{left_size:n.leftSize,right_size:n.rightSize,top_size:n.topSize,bottom_size:n.bottomSize}}};function _7e(n){let t=[];for(let a=0;a<n.length-1;a++)t.push([n[a],n[a+1]]);return t}var gUt=E.object({name:E.string().refine(n=>!/[+-]/.test(n),'Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P')}),AW=class extends Ya{constructor(){super(...arguments);J(this,"source_net_id")}get config(){return{componentName:"Net",zodProps:gUt}}getPortSelector(){return`net.${this.props.name}`}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:a}=this,o=t.source_net.insert({name:a.name,member_source_group_ids:[]});this.source_net_id=o.source_net_id}doInitialSourceParentAttachment(){let t=this.getSubcircuit();if(!t)return;let{db:a}=this.root;a.source_net.update(this.source_net_id,{subcircuit_id:t.subcircuit_id})}getAllConnectedPorts(){let t=this.getSubcircuit().selectAll("port"),a=[];for(let o of t){let l=o._getDirectlyConnectedTraces();for(let p of l)if(p._isExplicitlyConnectedToNet(this)){a.push(o);break}}return a}_getAllDirectlyConnectedTraces(){let t=this.getSubcircuit().selectAll("trace"),a=[];for(let o of t)o._isExplicitlyConnectedToNet(this)&&a.push(o);return a}doInitialPcbRouteNetIslands(){if(this.root?.pcbDisabled||this.getSubcircuit()._parsedProps.routingDisabled||this.getSubcircuit()._getAutorouterConfig().groupMode!=="sequential-trace")return;let{db:t}=this.root,{_parsedProps:a}=this,o=this._getAllDirectlyConnectedTraces().filter(x=>(x._portsRoutedOnPcb?.length??0)>0),l=[];for(let x of o){let m=x._portsRoutedOnPcb,g=l.find(_=>m.some(F=>_.ports.includes(F)));if(!g){l.push({ports:[...m],traces:[x]});continue}g.traces.push(x),g.ports.push(...m)}if(l.length===0)return;let p=_7e(l);for(let[x,m]of p){let g=x.ports.map(Q=>Q._getGlobalPcbPositionBeforeLayout()),_=m.ports.map(Q=>Q._getGlobalPcbPositionBeforeLayout()),F=1/0,C=[-1,-1];for(let Q=0;Q<g.length;Q++){let ee=g[Q];for(let ue=0;ue<_.length;ue++){let ce=_[ue],fe=Math.sqrt((ee.x-ce.x)**2+(ee.y-ce.y)**2);fe<F&&(F=fe,C=[Q,ue])}}let S=x.ports[C[0]],P=m.ports[C[1]],k=t.toArray().filter(Q=>Q.type==="pcb_smtpad"||Q.type==="pcb_trace"||Q.type==="pcb_plated_hole"||Q.type==="pcb_hole"||Q.type==="source_port"||Q.type==="pcb_port"),{solution:q}=gEe(k.concat([{type:"source_trace",source_trace_id:"__net_trace_tmp",connected_source_port_ids:[S.source_port_id,P.source_port_id]}])),X=q[0];if(!X){this.renderError({pcb_trace_error_id:"",pcb_trace_id:"__net_trace_tmp",pcb_component_ids:[S.pcb_component_id,P.pcb_component_id].filter(Boolean),pcb_port_ids:[S.pcb_port_id,P.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)}},RW=(n,t)=>{for(let a of t)if(typeof a=="string"&&a.startsWith("net.")){if(/net\.[^\s>]*\./.test(a))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(a))throw new Error('Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P');if(/net\.[0-9]/.test(a)){let l=a.split("net.")[1];throw new Error(`Net name "${l}" cannot start with a number, try using a prefix like "VBUS1"`)}let o=n.getSubcircuit();if(!o.selectOne(a)){let l=new AW({name:a.split("net.")[1]});o.add(l)}}},mR=class extends Ya{constructor(){super(...arguments);J(this,"pcb_smtpad_id",null);J(this,"matchedPort",null);J(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SmtPad",zodProps:zEe}}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==="polygon"){let a=t.points,o=a.map(_=>_.x),l=a.map(_=>_.y),p=Math.min(...o),x=Math.max(...o),m=Math.min(...l),g=Math.max(...l);return{width:x-p,height:g-m}}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 a of t)if(a.isMatchingAnyOf(this.props.portHints)){this.matchedPort=a,a.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:a}=this;if(!a.portHints)return;let o=this.getPrimitiveContainer(),l=this.getSubcircuit(),p=this._getGlobalPcbPositionBeforeLayout(),x=o?._getGlobalPcbPositionBeforeLayout(),m=JC(this._computePcbGlobalTransformBeforeLayout()),g=Math.abs(m.rotation.angle*(180/Math.PI)-90)%180<.01,{maybeFlipLayer:_}=this._getPcbPrimitiveFlippedHelpers(),F=o?._parsedProps.pcbRotation??0,C=null,S=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id;a.shape==="circle"?(C=t.pcb_smtpad.insert({pcb_component_id:S,pcb_port_id:this.matchedPort?.pcb_port_id,layer:_(a.layer??"top"),shape:"circle",radius:a.radius,port_hints:a.portHints.map(P=>P.toString()),x:p.x,y:p.y,subcircuit_id:l?.subcircuit_id??void 0}),t.pcb_solder_paste.insert({layer:C.layer,shape:"circle",radius:C.radius*.7,x:C.x,y:C.y,pcb_component_id:C.pcb_component_id,pcb_smtpad_id:C.pcb_smtpad_id,subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})):a.shape==="rect"?(C=F===0||g?t.pcb_smtpad.insert({pcb_component_id:S,pcb_port_id:this.matchedPort?.pcb_port_id,layer:_(a.layer??"top"),shape:"rect",width:g?a.height:a.width,height:g?a.width:a.height,port_hints:a.portHints.map(P=>P.toString()),x:p.x,y:p.y,subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}):t.pcb_smtpad.insert({pcb_component_id:S,layer:_(a.layer??"top"),shape:"rotated_rect",width:a.width,height:a.height,x:p.x,y:p.y,ccw_rotation:F,port_hints:a.portHints.map(P=>P.toString()),subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),C.shape==="rect"&&t.pcb_solder_paste.insert({layer:_(a.layer??"top"),shape:"rect",width:C.width*.7,height:C.height*.7,x:C.x,y:C.y,pcb_component_id:C.pcb_component_id,pcb_smtpad_id:C.pcb_smtpad_id,subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),C.shape==="rotated_rect"&&t.pcb_solder_paste.insert({layer:_(a.layer??"top"),shape:"rotated_rect",width:C.width*.7,height:C.height*.7,x:C.x,y:C.y,ccw_rotation:F,pcb_component_id:C.pcb_component_id,pcb_smtpad_id:C.pcb_smtpad_id,subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})):a.shape==="polygon"&&(C=t.pcb_smtpad.insert({pcb_component_id:S,pcb_port_id:this.matchedPort?.pcb_port_id,layer:_(a.layer??"top"),shape:"polygon",points:a.points.map(P=>({x:P.x+p.x,y:P.y+p.y})),port_hints:a.portHints.map(P=>P.toString()),subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})),C&&(this.pcb_smtpad_id=C.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,a=t.pcb_smtpad.get(this.pcb_smtpad_id);if(a.shape==="rect")return{center:{x:a.x,y:a.y},bounds:{left:a.x-a.width/2,top:a.y+a.height/2,right:a.x+a.width/2,bottom:a.y-a.height/2},width:a.width,height:a.height};if(a.shape==="rotated_rect"){let o=a.ccw_rotation*Math.PI/180,l=Math.cos(o),p=Math.sin(o),x=a.width/2,m=a.height/2,g=Math.abs(x*l)+Math.abs(m*p),_=Math.abs(x*p)+Math.abs(m*l);return{center:{x:a.x,y:a.y},bounds:{left:a.x-g,right:a.x+g,top:a.y-_,bottom:a.y+_},width:g*2,height:_*2}}if(a.shape==="circle")return{center:{x:a.x,y:a.y},bounds:{left:a.x-a.radius,top:a.y-a.radius,right:a.x+a.radius,bottom:a.y+a.radius},width:a.radius*2,height:a.radius*2};if(a.shape==="polygon"){let o=a.points,l=o.map(F=>F.x),p=o.map(F=>F.y),x=Math.min(...l),m=Math.max(...l),g=Math.min(...p),_=Math.max(...p);return{center:{x:(x+m)/2,y:(g+_)/2},bounds:{left:x,top:_,right:m,bottom:g},width:m-x,height:_-g}}throw new Error(`circuitJson bounds calculation not implemented for shape "${a.shape}"`)}_setPositionFromLayout(t){let{db:a}=this.root;a.pcb_smtpad.update(this.pcb_smtpad_id,{x:t.x,y:t.y});let o=a.pcb_solder_paste.list().find(l=>l.pcb_smtpad_id===this.pcb_smtpad_id);a.pcb_solder_paste.update(o?.pcb_solder_paste_id,{x:t.x,y:t.y}),this.matchedPort?._setPositionFromLayout(t)}},IW=class extends Ya{constructor(){super(...arguments);J(this,"pcb_silkscreen_path_id",null);J(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenPath",zodProps:m4e}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:a}=this,{maybeFlipLayer:o}=this._getPcbPrimitiveFlippedHelpers(),l=o(a.layer??"top");if(l!=="top"&&l!=="bottom")throw new Error(`Invalid layer "${l}" for SilkscreenPath. Must be "top" or "bottom".`);let p=this._computePcbGlobalTransformBeforeLayout(),x=this.getSubcircuit(),m=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,g=t.pcb_silkscreen_path.insert({pcb_component_id:m,layer:l,route:a.route.map(_=>{let F=Ss(p,{x:_.x,y:_.y});return{..._,x:F.x,y:F.y}}),stroke_width:a.strokeWidth??.1,subcircuit_id:x?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_path_id=g.pcb_silkscreen_path_id}_setPositionFromLayout(t){let{db:a}=this.root,{_parsedProps:o}=this,l=a.pcb_silkscreen_path.get(this.pcb_silkscreen_path_id);if(!l)return;let p=0,x=0;for(let F of l.route)p+=F.x,x+=F.y;p/=l.route.length,x/=l.route.length;let m=t.x-p,g=t.y-x,_=l.route.map(F=>({...F,x:F.x+m,y:F.y+g}));a.pcb_silkscreen_path.update(this.pcb_silkscreen_path_id,{route:_})}getPcbSize(){let{_parsedProps:t}=this;if(!t.route||t.route.length===0)return{width:0,height:0};let a=1/0,o=-1/0,l=1/0,p=-1/0;for(let x of t.route)a=Math.min(a,x.x),o=Math.max(o,x.x),l=Math.min(l,x.y),p=Math.max(p,x.y);return{width:o-a,height:p-l}}},DUt=E.object({route:E.array(BC),source_trace_id:E.string().optional()}),wW=class extends Ya{constructor(){super(...arguments);J(this,"pcb_trace_id",null);J(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbTrace",zodProps:DUt}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:a}=this,o=this.getPrimitiveContainer(),l=this.getSubcircuit(),{maybeFlipLayer:p}=this._getPcbPrimitiveFlippedHelpers(),x=this._computePcbGlobalTransformBeforeLayout(),m=a.route.map(_=>{let{x:F,y:C,...S}=_,P=Ss(x,{x:F,y:C});return _.route_type==="wire"&&_.layer?{...P,...S,layer:p(_.layer)}:{...P,...S}}),g=t.pcb_trace.insert({pcb_component_id:o.pcb_component_id,source_trace_id:a.source_trace_id,route:m,subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_trace_id=g.pcb_trace_id}getPcbSize(){let{_parsedProps:t}=this;if(!t.route||t.route.length===0)return{width:0,height:0};let a=1/0,o=-1/0,l=1/0,p=-1/0;for(let x of t.route)a=Math.min(a,x.x),o=Math.max(o,x.x),l=Math.min(l,x.y),p=Math.max(p,x.y),x.route_type==="wire"&&(a=Math.min(a,x.x-x.width/2),o=Math.max(o,x.x+x.width/2),l=Math.min(l,x.y-x.width/2),p=Math.max(p,x.y+x.width/2));return a===1/0||o===-1/0||l===1/0||p===-1/0?{width:0,height:0}:{width:o-a,height:p-l}}},hR=class extends Ya{constructor(){super(...arguments);J(this,"pcb_plated_hole_id",null);J(this,"matchedPort",null);J(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PlatedHole",zodProps:SEe}}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,a=t.pcb_plated_hole.get(this.pcb_plated_hole_id),o=this.getPcbSize();return{center:{x:a.x,y:a.y},bounds:{left:a.x-o.width/2,top:a.y+o.height/2,right:a.x+o.width/2,bottom:a.y-o.height/2},width:o.width,height:o.height}}_setPositionFromLayout(t){let{db:a}=this.root;a.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 a of t)if(a.isMatchingAnyOf(this.props.portHints)){this.matchedPort=a,a.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:a}=this,o=this._getGlobalPcbPositionBeforeLayout(),l=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,p=this.getSubcircuit();if(a.shape==="circle"){let x=t.pcb_plated_hole.insert({pcb_component_id:l,pcb_port_id:this.matchedPort?.pcb_port_id,outer_diameter:a.outerDiameter,hole_diameter:a.holeDiameter,shape:"circle",port_hints:this.getNameAndAliases(),x:o.x,y:o.y,layers:["top","bottom"],subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=x.pcb_plated_hole_id,t.pcb_solder_paste.insert({layer:"top",shape:"circle",radius:a.outerDiameter/2,x:o.x,y:o.y,subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),t.pcb_solder_paste.insert({layer:"bottom",shape:"circle",radius:a.outerDiameter/2,x:o.x,y:o.y,subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(a.shape==="pill"&&a.rectPad){let x=t.pcb_plated_hole.insert({pcb_component_id:l,pcb_port_id:this.matchedPort?.pcb_port_id,outer_width:a.outerWidth,outer_height:a.outerHeight,hole_width:a.holeWidth,hole_height:a.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:o.x,y:o.y,layers:["top","bottom"],subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,hole_shape:"rotated_pill",pad_shape:"rect",hole_ccw_rotation:a.pcbRotation??0,rect_ccw_rotation:a.pcbRotation??0,rect_pad_width:a.outerWidth,rect_pad_height:a.outerHeight});this.pcb_plated_hole_id=x.pcb_plated_hole_id}else if(a.shape==="pill"||a.shape==="oval"){let x=t.pcb_plated_hole.insert({pcb_component_id:l,pcb_port_id:this.matchedPort?.pcb_port_id,outer_width:a.outerWidth,outer_height:a.outerHeight,hole_width:a.holeWidth,hole_height:a.holeHeight,shape:a.shape,port_hints:this.getNameAndAliases(),x:o.x,y:o.y,layers:["top","bottom"],subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=x.pcb_plated_hole_id,t.pcb_solder_paste.insert({layer:"top",shape:a.shape,width:a.outerWidth,height:a.outerHeight,x:o.x,y:o.y,subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),t.pcb_solder_paste.insert({layer:"bottom",shape:a.shape,width:a.outerWidth,height:a.outerHeight,x:o.x,y:o.y,subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(a.shape==="circular_hole_with_rect_pad"){let x=t.pcb_plated_hole.insert({pcb_component_id:l,pcb_port_id:this.matchedPort?.pcb_port_id,hole_diameter:a.holeDiameter,rect_pad_width:a.rectPadWidth,rect_pad_height:a.rectPadHeight,shape:"circular_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:o.x,y:o.y,layers:["top","bottom"],subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=x.pcb_plated_hole_id}else if(a.shape==="pill_hole_with_rect_pad"){let x=t.pcb_plated_hole.insert({pcb_component_id:l,pcb_port_id:this.matchedPort?.pcb_port_id,hole_width:a.holeWidth,hole_height:a.holeHeight,rect_pad_width:a.rectPadWidth,rect_pad_height:a.rectPadHeight,shape:"pill_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:o.x,y:o.y,layers:["top","bottom"],subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=x.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})}},yR=class extends Ya{constructor(){super(...arguments);J(this,"pcb_keepout_id",null);J(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Keepout",zodProps:o4e}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let t=this.getSubcircuit(),{db:a}=this.root,{_parsedProps:o}=this,l=this._getGlobalPcbPositionBeforeLayout(),p=JC(this._computePcbGlobalTransformBeforeLayout()),x=Math.abs(p.rotation.angle*(180/Math.PI)-90)%180<.01,m=null;o.shape==="circle"?m=a.pcb_keepout.insert({layers:["top"],shape:"circle",radius:o.radius,center:{x:l.x,y:l.y},subcircuit_id:t?.subcircuit_id??void 0,pcb_group_id:t?.getGroup()?.pcb_group_id??void 0}):o.shape==="rect"&&(m=a.pcb_keepout.insert({layers:["top"],shape:"rect",...x?{width:o.height,height:o.width}:{width:o.width,height:o.height},center:{x:l.x,y:l.y},subcircuit_id:t?.subcircuit_id??void 0,pcb_group_id:t?.getGroup()?.pcb_group_id??void 0})),m&&(this.pcb_keepout_id=m.pcb_keepout_id)}},SW=class extends Ya{constructor(){super(...arguments);J(this,"pcb_hole_id",null);J(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Hole",zodProps:$Ee}}getPcbSize(){let{_parsedProps:t}=this;return{width:t.diameter,height:t.diameter}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:a}=this,o=this.getSubcircuit(),l=this._getGlobalPcbPositionBeforeLayout(),p=t.pcb_hole.insert({hole_shape:"circle",hole_diameter:a.diameter,x:l.x,y:l.y,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:o?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=p.pcb_hole_id}_getPcbCircuitJsonBounds(){let{db:t}=this.root,a=t.pcb_hole.get(this.pcb_hole_id),o=this.getPcbSize();return{center:{x:a.x,y:a.y},bounds:{left:a.x-o.width/2,top:a.y-o.height/2,right:a.x+o.width/2,bottom:a.y+o.height/2},width:o.width,height:o.height}}_setPositionFromLayout(t){let{db:a}=this.root;a.pcb_hole.update(this.pcb_hole_id,{x:t.x,y:t.y})}},_R=class extends Ya{constructor(){super(...arguments);J(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenText",zodProps:f4e}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:a}=this,o=this.getPrimitiveContainer(),l=this._getGlobalPcbPositionBeforeLayout(),{maybeFlipLayer:p}=this._getPcbPrimitiveFlippedHelpers(),x=this.getSubcircuit();t.pcb_silkscreen_text.insert({anchor_alignment:a.anchorAlignment,anchor_position:{x:l.x,y:l.y},font:a.font??"tscircuit2024",font_size:a.fontSize??1,layer:p(a.layer??"top"),text:a.text??"",ccw_rotation:a.pcbRotation,pcb_component_id:o.pcb_component_id,subcircuit_id:x?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}getPcbSize(){let{_parsedProps:t}=this,a=t.fontSize??1,l=(t.text??"").length*a,p=a;return{width:l*a,height:p*a}}},i8=class extends Ya{constructor(){super(...arguments);J(this,"pcb_cutout_id",null);J(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Cutout",zodProps:LEe}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:a}=this,o=this.getSubcircuit(),l=this.getGroup()?.pcb_group_id??void 0,p=this._getGlobalPcbPositionBeforeLayout(),m=this.getPrimitiveContainer()?._parsedProps.pcbRotation??0,g;if(a.shape==="rect"){let _=typeof m=="string"?parseInt(m.replace("deg",""),10):m,F=Math.abs(_%180)===90,C={shape:"rect",center:p,width:F?a.height:a.width,height:F?a.width:a.height,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:l};g=t.pcb_cutout.insert(C)}else if(a.shape==="circle"){let _={shape:"circle",center:p,radius:a.radius,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:l};g=t.pcb_cutout.insert(_)}else if(a.shape==="polygon"){let _=this._computePcbGlobalTransformBeforeLayout(),C={shape:"polygon",points:a.points.map(S=>Ss(_,S)),subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:l};g=t.pcb_cutout.insert(C)}g&&(this.pcb_cutout_id=g.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 a=1/0,o=-1/0,l=1/0,p=-1/0;for(let x of t.points)a=Math.min(a,x.x),o=Math.max(o,x.x),l=Math.min(l,x.y),p=Math.max(p,x.y);return{width:o-a,height:p-l}}return{width:0,height:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_cutout_id)return super._getPcbCircuitJsonBounds();let{db:t}=this.root,a=t.pcb_cutout.get(this.pcb_cutout_id);if(!a)return super._getPcbCircuitJsonBounds();if(a.shape==="rect")return{center:a.center,bounds:{left:a.center.x-a.width/2,top:a.center.y+a.height/2,right:a.center.x+a.width/2,bottom:a.center.y-a.height/2},width:a.width,height:a.height};if(a.shape==="circle")return{center:a.center,bounds:{left:a.center.x-a.radius,top:a.center.y+a.radius,right:a.center.x+a.radius,bottom:a.center.y-a.radius},width:a.radius*2,height:a.radius*2};if(a.shape==="polygon"){if(a.points.length===0)return super._getPcbCircuitJsonBounds();let o=1/0,l=-1/0,p=1/0,x=-1/0;for(let m of a.points)o=Math.min(o,m.x),l=Math.max(l,m.x),p=Math.min(p,m.y),x=Math.max(x,m.y);return{center:{x:(o+l)/2,y:(p+x)/2},bounds:{left:o,top:x,right:l,bottom:p},width:l-o,height:x-p}}return super._getPcbCircuitJsonBounds()}_setPositionFromLayout(t){if(!this.pcb_cutout_id)return;let{db:a}=this.root,o=a.pcb_cutout.get(this.pcb_cutout_id);if(o){if(o.shape==="rect"||o.shape==="circle")a.pcb_cutout.update(this.pcb_cutout_id,{...o,center:t});else if(o.shape==="polygon"){let l=this._getPcbCircuitJsonBounds().center,p=t.x-l.x,x=t.y-l.y,m=o.points.map(g=>({x:g.x+p,y:g.y+x}));a.pcb_cutout.update(this.pcb_cutout_id,{...o,points:m})}}}},_Ut=({elm:n,pinLabels:t,layer:a,readableRotation:o,anchorAlignment:l})=>{let p=n.text.replace(/[{}]/g,"").toLowerCase(),x=p;if(Array.isArray(t)){let m=parseInt(p.replace(/[^\d]/g,""),10)-1;x=String(t[m]??p)}else typeof t=="object"&&(x=String(t[p]??p));return new _R({anchorAlignment:l||"center",text:x??p,layer:a||"top",fontSize:n.font_size+.2,pcbX:isNaN(n.anchor_position.x)?0:n.anchor_position.x,pcbY:n.anchor_position.y,pcbRotation:o??0})},bUt=(n,t)=>((-parseInt(n||"0",10)+(t??0))%360+360)%360,a7e=({componentName:n,componentRotation:t,footprint:a,pinLabels:o,pcbPinLabels:l},p)=>{let x=[];for(let m of p)if(m.type==="pcb_smtpad"&&m.shape==="rect")x.push(new mR({pcbX:m.x,pcbY:m.y,layer:m.layer,shape:"rect",height:m.height,width:m.width,portHints:m.port_hints}));else if(m.type==="pcb_smtpad"&&m.shape==="circle")x.push(new mR({pcbX:m.x,pcbY:m.y,layer:m.layer,shape:"circle",radius:m.radius,portHints:m.port_hints}));else if(m.type==="pcb_silkscreen_path")x.push(new IW({layer:m.layer,route:m.route,strokeWidth:m.stroke_width}));else if(m.type==="pcb_plated_hole")m.shape==="circle"?x.push(new hR({pcbX:m.x,pcbY:m.y,shape:"circle",holeDiameter:m.hole_diameter,outerDiameter:m.outer_diameter,portHints:m.port_hints})):m.shape==="circular_hole_with_rect_pad"&&x.push(new hR({pcbX:m.x,pcbY:m.y,shape:"circular_hole_with_rect_pad",holeDiameter:m.hole_diameter,rectPadHeight:m.rect_pad_height,rectPadWidth:m.rect_pad_width,portHints:m.port_hints}));else if(m.type==="pcb_keepout"&&m.shape==="circle")x.push(new yR({pcbX:m.center.x,pcbY:m.center.y,shape:"circle",radius:m.radius}));else if(m.type==="pcb_keepout"&&m.shape==="rect")x.push(new yR({pcbX:m.center.x,pcbY:m.center.y,shape:"rect",width:m.width,height:m.height}));else if(m.type==="pcb_hole"&&m.hole_shape==="circle")x.push(new SW({pcbX:m.x,pcbY:m.y,diameter:m.hole_diameter}));else if(m.type==="pcb_cutout")m.shape==="rect"?x.push(new i8({pcbX:m.center.x,pcbY:m.center.y,shape:"rect",width:m.width,height:m.height})):m.shape==="circle"?x.push(new i8({pcbX:m.center.x,pcbY:m.center.y,shape:"circle",radius:m.radius})):m.shape==="polygon"&&x.push(new i8({shape:"polygon",points:m.points}));else if(m.type==="pcb_silkscreen_text"){let g=bUt(t,m.ccw_rotation);a.includes("pinrow")&&m.text.includes("PIN")?x.push(_Ut({elm:m,pinLabels:l??o,layer:m.layer,readableRotation:g,anchorAlignment:m.anchor_alignment})):x.push(new _R({anchorAlignment:m.anchor_alignment||"center",text:n,fontSize:m.font_size+.2,pcbX:Number.isNaN(m.anchor_position.x)?0:m.anchor_position.x,pcbY:m.anchor_position.y,pcbRotation:g??0}))}else m.type==="pcb_trace"&&x.push(new wW({route:m.route}));return x};function bR(n){let t=1/0,a=1/0,o=-1/0,l=-1/0,p=!1;for(let g of n)if(g.isPcbPrimitive&&!g.componentName.startsWith("Silkscreen")){let{x:_,y:F}=g._getGlobalPcbPositionBeforeLayout(),{width:C,height:S}=g.getPcbSize();t=Math.min(t,_-C/2),a=Math.min(a,F-S/2),o=Math.max(o,_+C/2),l=Math.max(l,F+S/2),p=!0}else if(g.children.length>0){let _=bR(g.children);(_.width>0||_.height>0)&&(t=Math.min(t,_.minX),a=Math.min(a,_.minY),o=Math.max(o,_.maxX),l=Math.max(l,_.maxY),p=!0)}if(!p)return{minX:0,minY:0,maxX:0,maxY:0,width:0,height:0};let x=o-t,m=l-a;return x<0&&(x=0),m<0&&(m=0),{minX:t,minY:a,maxX:o,maxY:l,width:x,height:m}}function FUt(n,t){let a=t.x-n.x,o=t.y-n.y;return Math.abs(a)>Math.abs(o)?a>=0?"right":"left":o>=0?"up":"down"}var vUt=n=>{if(n.length<=1)return!0;let t=n.map(p=>{let x=p._getPcbCircuitJsonBounds();return{left:x.bounds.left,right:x.bounds.right,top:x.bounds.top,bottom:x.bounds.bottom}}),a=Array(t.length).fill(!1).map(()=>Array(t.length).fill(!1));for(let p=0;p<t.length;p++)for(let x=p+1;x<t.length;x++){let m=t[p],g=t[x];a[p][x]=a[x][p]=!(m.right<g.left||m.left>g.right||m.bottom>g.top||m.top<g.bottom)}let o=new Set,l=p=>{o.add(p);for(let x=0;x<t.length;x++)a[p][x]&&!o.has(x)&&l(x)};return l(0),o.size===t.length},EUt=n=>{if(n.length===0)throw new Error("Cannot get center of empty PCB primitives array");let t=n.map(l=>l._getPcbCircuitJsonBounds().center).filter(Boolean),a=t.reduce((l,p)=>l+p.x,0),o=t.reduce((l,p)=>l+p.y,0);return{x:a/t.length,y:o/t.length}},CUt=E.object({name:E.string().optional(),pinNumber:E.number().optional(),aliases:E.array(E.string()).optional()}),cu=class extends Ya{constructor(t,a={}){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);J(this,"source_port_id",null);J(this,"pcb_port_id",null);J(this,"schematic_port_id",null);J(this,"schematicSymbolPortDef",null);J(this,"matchedComponents");J(this,"facingDirection",null);J(this,"originDescription",null);a.originDescription&&(this.originDescription=a.originDescription),this.matchedComponents=[]}get config(){return{componentName:"Port",zodProps:CUt}}_getGlobalPcbPositionBeforeLayout(){let t=this.matchedComponents.find(o=>o.isPcbPrimitive),a=this.parent;if(a&&!a.props.footprint)throw new Error(`${a.componentName} "${a.props.name}" does not have a footprint. Add a footprint prop, e.g. <${a.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,a=t.pcb_port.get(this.pcb_port_id);return{center:{x:a.x,y:a.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 a=t._getInternallyConnectedPins();for(let o of a)if(o.some(l=>l===this))return o;return[]}_hasSchematicPort(){if(this.parent?.getSchematicSymbol())return!!(this.schematicSymbolPortDef||this._getPortsInternallyConnectedToThisPort().some(l=>l.schematicSymbolPortDef));let a=this?.parent?._getSchematicBoxDimensions();return!!(a&&this.props.pinNumber!==void 0&&a.getPortPositionByPinNumber(this.props.pinNumber))}_getGlobalSchematicPositionBeforeLayout(){let t=this.parent?.getSchematicSymbol();if(t){let o=this.schematicSymbolPortDef;if(!o&&(o=this._getPortsInternallyConnectedToThisPort().find(p=>p.schematicSymbolPortDef)?.schematicSymbolPortDef??null,!o))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 l=qs(this.parent.computeSchematicGlobalTransform(),si(-t.center.x,-t.center.y));return Ss(l,o)}let a=this?.parent?._getSchematicBoxDimensions();if(a&&this.props.pinNumber!==void 0){let o=a.getPortPositionByPinNumber(this.props.pinNumber);if(!o)throw new Error(`Couldn't find position for schematic_port for port ${this.getString()} inside of the schematic box`);return Ss(this.parent.computeSchematicGlobalTransform(),o)}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 a=t.schematic_port.get(this.schematic_port_id);if(!a)throw new Error(`Schematic port not found when trying to get post-layout position: ${this.schematic_port_id}`);return a.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??[]]))}isMatchingPort(t){return this.isMatchingAnyOf(t.getNameAndAliases())}getPortSelector(){return`.${this.parent?.props.name} > port.${this.props.name}`}getAvailablePcbLayers(){return Array.from(new Set(this.matchedComponents.flatMap(t=>t.getAvailablePcbLayers())))}_getDirectlyConnectedTraces(){return this.getSubcircuit().selectAll("trace").filter(o=>o._isExplicitlyConnectedToPort(this))}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:a}=this,o=this.getNameAndAliases(),l=t.source_port.insert({name:a.name,pin_number:a.pinNumber,port_hints:o,source_component_id:this.parent?.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id});this.source_port_id=l.source_port_id}doInitialSourceParentAttachment(){let{db:t}=this.root;if(!this.parent?.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:this.parent?.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id}),this.source_component_id=this.parent?.source_component_id}doInitialPcbPortRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{matchedComponents:a}=this;if(!this.parent?.pcb_component_id)throw new Error(`${this.getString()} has no parent pcb component, cannot render pcb_port (parent: ${this.parent?.getString()})`);let o=a.filter(p=>p.isPcbPrimitive);if(o.length===0)return;let l=null;if(o.length===1&&(l=o[0]._getPcbCircuitJsonBounds().center),o.length>1){if(!vUt(o))throw new Error(`${this.getString()} has multiple non-overlapping pcb matches, unclear how to place pcb_port: ${o.map(p=>p.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)`);l=EUt(o)}if(l){let p=this.getSubcircuit(),x=t.pcb_port.insert({pcb_component_id:this.parent?.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...l,source_port_id:this.source_port_id});this.pcb_port_id=x.pcb_port_id}else{let p=o[0];throw new Error(`${p.getString()} does not have a center or _getGlobalPcbPositionBeforeLayout method (needed for pcb_port placement)`)}}doInitialSchematicPortRender(){let{db:t}=this.root,{_parsedProps:a}=this,o=this.getPrimitiveContainer();if(!o||!this._hasSchematicPort())return;let l=o._getGlobalSchematicPositionBeforeLayout(),p=this._getGlobalSchematicPositionBeforeLayout(),x=null,m=o._getSchematicBoxDimensions();m&&a.pinNumber!==void 0&&(x=m.getPortPositionByPinNumber(a.pinNumber)),this.getSubcircuit().props._schDebugObjectsEnabled&&t.schematic_debug_object.insert({shape:"rect",center:p,size:{width:.1,height:.1},label:"obstacle"}),x?.side?this.facingDirection={left:"left",right:"right",top:"up",bottom:"down"}[x.side]:this.facingDirection=FUt(l,p);let g=t.source_port.get(this.source_port_id),_=[];for(let P of g?.port_hints??[])P.match(/^(pin)?\d+$/)||P.match(/^(left|right)/)&&!g?.name.match(/^(left|right)/)||_.push(P);let F;this.parent?.props?.showPinAliases&&_.length>0?F=_.join("/"):_.length>0&&(F=_[0]);let S=t.schematic_port.insert({schematic_component_id:this.parent?.schematic_component_id,center:p,source_port_id:this.source_port_id,facing_direction:this.facingDirection,distance_from_component_edge:.4,side_of_component:x?.side,pin_number:a.pinNumber,true_ccw_index:x?.trueIndex,display_pin_label:F,is_connected:!1});this.schematic_port_id=S.schematic_port_id}_setPositionFromLayout(t){let{db:a}=this.root;this.pcb_port_id&&a.pcb_port.update(this.pcb_port_id,{x:t.x,y:t.y})}_hasMatchedPcbPrimitive(){return this.matchedComponents.some(t=>t.isPcbPrimitive)}},b7e=n=>{let t=n.find(a=>/^(pin)?\d+$/.test(a));return t?Number.parseInt(t.replace(/^pin/,"")):null};function n8(n,t){let a=b7e(n);if(!a)return null;let l=[...n.filter(p=>p.toString()!==a.toString()&&p!==`pin${a}`),...t?.additionalAliases?.[`pin${a}`]??[]];return new cu({pinNumber:a,aliases:l})}var AUt=n=>{for(let t of["leftSide","rightSide","topSide","bottomSide"])if(t in n&&typeof n[t]=="number")throw new Error(`A number was specified for "${t}", you probably meant to use "size" not "side"`);return"leftSide"in n||"rightSide"in n||"topSide"in n||"bottomSide"in n},RUt=n=>{if(AUt(n))return{leftSize:n.leftSide?.pins.length??0,rightSize:n.rightSide?.pins.length??0,topSize:n.topSide?.pins.length??0,bottomSize:n.bottomSide?.pins.length??0};let{leftSize:t=0,rightSize:a=0,topSize:o=0,bottomSize:l=0}=n;return{leftSize:t,rightSize:a,topSize:o,bottomSize:l}};function F7e(n){let t=n;return t.leftSide!==void 0||t.rightSide!==void 0||t.topSide!==void 0||t.bottomSide!==void 0}var IUt=n=>{let t=n.portDistanceFromEdge??.4,a=n.schPortArrangement?RUt(n.schPortArrangement):null,o={left:0,right:0,top:0,bottom:0},l=n.pinCount??null;if(l===null)if(a)l=a.leftSize+a.rightSize+a.topSize;else throw new Error("Could not determine pin count for the schematic box");if(l&&!a){let k=Math.floor(l/2);a={leftSize:l-k,rightSize:k,topSize:0,bottomSize:0}}a||(a={leftSize:0,rightSize:0,topSize:0,bottomSize:0});let p=({side:k,sideIndex:q,truePinIndex:X})=>{if(!n.schPortArrangement||!F7e(n.schPortArrangement))return X+1;let Q={left:"top-to-bottom",bottom:"left-to-right",right:"bottom-to-top",top:"right-to-left"}[k],ee=n.schPortArrangement?.[`${k}Side`]?.direction??Q,ue=n.schPortArrangement?.[`${k}Side`]?.pins,ce=q;return ee!==Q&&(ce=ue.length-q-1),s8(ue[ce],n.pinLabels)},x=[],m=0,g=0;for(let k=0;k<a.leftSize;k++){let q=p({side:"left",sideIndex:k,truePinIndex:g}),X=n.numericSchPinStyle?.[`pin${q}`]??n.numericSchPinStyle?.[q];X?.topMargin&&(m+=X.topMargin),x.push({trueIndex:g,pinNumber:q,side:"left",distanceFromOrthogonalEdge:m}),X?.bottomMargin&&(m+=X.bottomMargin),k===a.leftSize-1?o.left=m:m+=n.schPinSpacing,g++}m=0;for(let k=0;k<a.bottomSize;k++){let q=p({side:"bottom",sideIndex:k,truePinIndex:g}),X=n.numericSchPinStyle?.[`pin${q}`]??n.numericSchPinStyle?.[q];X?.leftMargin&&(m+=X.leftMargin),x.push({trueIndex:g,pinNumber:q,side:"bottom",distanceFromOrthogonalEdge:m}),X?.rightMargin&&(m+=X.rightMargin),k===a.bottomSize-1?o.bottom=m:m+=n.schPinSpacing,g++}m=0;for(let k=0;k<a.rightSize;k++){let q=p({side:"right",sideIndex:k,truePinIndex:g}),X=n.numericSchPinStyle?.[`pin${q}`]??n.numericSchPinStyle?.[q];X?.bottomMargin&&(m+=X.bottomMargin),x.push({trueIndex:g,pinNumber:q,side:"right",distanceFromOrthogonalEdge:m}),X?.topMargin&&(m+=X.topMargin),k===a.rightSize-1?o.right=m:m+=n.schPinSpacing,g++}m=0;for(let k=0;k<a.topSize;k++){let q=p({side:"top",sideIndex:k,truePinIndex:g}),X=n.numericSchPinStyle?.[`pin${q}`]??n.numericSchPinStyle?.[q];X?.rightMargin&&(m+=X.rightMargin),x.push({trueIndex:g,pinNumber:q,side:"top",distanceFromOrthogonalEdge:m}),X?.leftMargin&&(m+=X.leftMargin),k===a.topSize-1?o.top=m:m+=n.schPinSpacing,g++}let _=n.schWidth;if(_===void 0){_=Math.max(o.top+n.schPinSpacing*2,o.bottom+n.schPinSpacing*2);let k=n.pinLabels?Math.max(...Object.values(n.pinLabels).map(X=>X.length*.1)):0,q=k>0?1.1:0;_=Math.max(_,k+q)}let F=n.schHeight;F||(F=Math.max(o.left+n.schPinSpacing*2,o.right+n.schPinSpacing*2));let C={left:{x:-_/2-t,y:o.left/2},bottom:{x:-o.bottom/2,y:-F/2-t},right:{x:_/2+t,y:-o.right/2},top:{x:o.top/2,y:F/2+t}},S={left:{x:0,y:-1},right:{x:0,y:1},top:{x:-1,y:0},bottom:{x:1,y:0}},P=x.map(k=>{let{distanceFromOrthogonalEdge:q,side:X}=k,Q=C[X],ee=S[X];return{x:Q.x+q*ee.x,y:Q.y+q*ee.y,...k}});return{getPortPositionByPinNumber(k){let q=P.find(X=>X.pinNumber.toString()===k.toString());return q||null},getSize(){return{width:_,height:F}},getSizeIncludingPins(){return{width:_+(a.leftSize||a.rightSize?.4:0),height:F+(a.topSize||a.bottomSize?.4:0)}},pinCount:l}},wUt=(0,v7e.default)("tscircuit:core:footprint"),E7e=class extends Ya{get config(){return{componentName:"Footprint",zodProps:UEe}}doInitialPcbFootprintLayout(){if(this.root?.pcbDisabled)return;let n=this.children.filter(C=>C.componentName==="Constraint");if(n.length===0)return;let{isFlipped:t}=this._getPcbPrimitiveFlippedHelpers(),a=C=>t&&"left"in C&&"right"in C?{...C,left:C.right,right:C.left}:C,o=n.flatMap(C=>C._getAllReferencedComponents().componentsWithSelectors).map(({component:C,selector:S,componentSelector:P,edge:k})=>({component:C,selector:S,componentSelector:P,edge:k,bounds:C._getPcbCircuitJsonBounds()}));if(o.some(C=>C.edge))throw new Error("edge constraints not implemented yet for footprint layout, contributions welcome!");function l(C){return o.find(({selector:S})=>S===C)}let p=new e7,x={};function m(C){return C in x||(x[C]=new Ag(C),p.addEditVariable(x[C],uo.weak)),x[C]}for(let{selector:C,bounds:S}of o){let P=m(`${C}_x`),k=m(`${C}_y`);p.suggestValue(P,S.center.x),p.suggestValue(k,S.center.y)}for(let C of n){let S=C._parsedProps;if("xDist"in S){let{xDist:P,left:k,right:q,edgeToEdge:X,centerToCenter:Q}=a(S),ee=m(`${k}_x`),ue=m(`${q}_x`),ce=l(k)?.bounds,fe=l(q)?.bounds;if(Q){let U=new Vs(ue,[-1,ee]);p.addConstraint(new ql(U,Dc.Eq,S.xDist,uo.required))}else if(X){let U=new Vs(ue,-fe.width/2,[-1,ee],-ce.width/2);p.addConstraint(new ql(U,Dc.Eq,S.xDist,uo.required))}}else if("yDist"in S){let{yDist:P,top:k,bottom:q,edgeToEdge:X,centerToCenter:Q}=S,ee=m(`${k}_y`),ue=m(`${q}_y`),ce=l(k)?.bounds,fe=l(q)?.bounds;if(Q){let U=new Vs(ee,[-1,ue]);p.addConstraint(new ql(U,Dc.Eq,S.yDist,uo.required))}else if(X){let U=new Vs(ee,ce.height/2,[-1,ue],-fe.height/2);p.addConstraint(new ql(U,Dc.Eq,S.yDist,uo.required))}}else if("sameY"in S){let{for:P}=S;if(P.length<2)continue;let k=P.map(X=>m(`${X}_y`)),q=new Vs(...k.slice(1));p.addConstraint(new ql(q,Dc.Eq,k[0],uo.required))}else if("sameX"in S){let{for:P}=S;if(P.length<2)continue;let k=P.map(X=>m(`${X}_x`)),q=new Vs(...k.slice(1));p.addConstraint(new ql(q,Dc.Eq,k[0],uo.required))}}p.updateVariables(),wUt.enabled&&(console.log("Solution to layout constraints:"),console.table(Object.entries(x).map(([C,S])=>({var:C,val:S.value()}))));let g={left:1/0,right:-1/0,top:-1/0,bottom:1/0};for(let{selector:C,bounds:{width:S,height:P}}of o){let k=m(`${C}_x`),q=m(`${C}_y`),X=k.value()-S/2,Q=k.value()+S/2,ee=q.value()+P/2,ue=q.value()-P/2;g.left=Math.min(g.left,X),g.right=Math.max(g.right,Q),g.top=Math.max(g.top,ee),g.bottom=Math.min(g.bottom,ue)}let _={x:-(g.right+g.left)/2,y:-(g.top+g.bottom)/2},F=this.getPrimitiveContainer()._getGlobalPcbPositionBeforeLayout();_.x+=F.x,_.y+=F.y;for(let{component:C,selector:S}of o){let P=m(`${S}_x`),k=m(`${S}_y`);C._setPositionFromLayout({x:P.value()+_.x,y:k.value()+_.y})}}},SUt=(n,t)=>{if(!n)return;let a={};for(let[o,l]of Object.entries(n)){let p=s8(o,t),x={leftMargin:l.marginLeft??l.leftMargin,rightMargin:l.marginRight??l.rightMargin,topMargin:l.marginTop??l.topMargin,bottomMargin:l.marginBottom??l.bottomMargin};a[`pin${p}`]={...a[`pin${p}`],...x}}return a},i7e=class{constructor({input:n}){J(this,"input");this.input=n}solveAndMapToTraces(){let n=[];for(let t of this.input.connections){if(t.pointsToConnect.length!==2)continue;let[a,o]=t.pointsToConnect,l={type:"pcb_trace",pcb_trace_id:"",connection_name:t.name,route:[{route_type:"wire",x:a.x,y:a.y,layer:"top",width:.1},{route_type:"wire",x:o.x,y:o.y,layer:"top",width:.1}]};n.push(l)}return n}},BUt=n=>{let t=Math.min(...n.map(p=>p.center.x)),a=Math.max(...n.map(p=>p.center.x)),o=Math.min(...n.map(p=>p.center.y)),l=Math.max(...n.map(p=>p.center.y));return{minX:t,maxX:a,minY:o,maxY:l}},s7e=["top","bottom","inner1","inner2"],xR=(n,t=[])=>{let a=[];if(t.length===0){let m=n[0].layers;for(let g of m)a.push(...xR(n.slice(1),[g]));return a}if(n.length===0)return[];let o=n[0],l=o.via||o.optional_via,p=t[t.length-1];if(n.length===1){let m=o;return m.layers&&l?m.layers.map(g=>({layer_path:[...t,g]})):m.layers?.includes(p)?[{layer_path:[...t,p]}]:[]}if(!l)return o.layers&&!o.layers.includes(p)?[]:xR(n.slice(1),t.concat([p]));let x=(o.optional_via?s7e:s7e.filter(m=>m!==p)).filter(m=>!o.layers||o.layers?.includes(m));for(let m of x)a.push(...xR(n.slice(1),t.concat(m)));return a};function o7e(n){let t={x:n.to.x-n.from.x,y:n.to.y-n.from.y},a=Math.abs(t.x),o=Math.abs(t.y);return a>o?t.x>0?"right":"left":t.y>0?"down":"up"}function g_(n,t){return Math.hypot(n.x-t.x,n.y-t.y)}var TUt=n=>{if(n.length===1)return n[0];if(n.some(g=>g.length===0))throw new Error("Cannot merge routes with zero length");let t=[],a=n[0][0],o=n[0][n[0].length-1],l=n[1][0],p=n[1][n[1].length-1],x=Math.min(g_(a,l),g_(a,p)),m=Math.min(g_(o,l),g_(o,p));x<m?t.push(...n[0].reverse()):t.push(...n[0]);for(let g=1;g<n.length;g++){let _=t[t.length-1],F=n[g],C=F[0],S=F[F.length-1],P=g_(_,C),k=g_(_,S);P<k?t.push(...F):t.push(...F.reverse())}for(let g=1;g<t.length-1;g++){let _=t[g-1],F=t[g];_.route_type==="wire"&&F.route_type==="wire"&&_.layer!==F.layer&&t.splice(g,0,{x:_.x,y:_.y,from_layer:_.layer,to_layer:F.layer,route_type:"via"})}return t},PUt=(n,t)=>{let a="_getGlobalPcbPositionBeforeLayout"in n?n._getGlobalPcbPositionBeforeLayout():n,o="_getGlobalPcbPositionBeforeLayout"in t?t._getGlobalPcbPositionBeforeLayout():t;return Math.sqrt((a.x-o.x)**2+(a.y-o.y)**2)};function kUt(n,t){if(t.length===0)throw new Error("No candidates given to getClosest method");let a=t[0],o=1/0;for(let l of t){let p=PUt(n,l);p<o&&(a=l,o=p)}return a}var jUt=(n,t)=>{let a=0;a+=n.length??0,a+=t.filter(o=>o.is_crossing).length;for(let o=1;o<t.length;o++){let l=t[o-1],p=t[o],x=Math.abs(l.from.x-l.to.x)<.01,m=Math.abs(p.from.x-p.to.x)<.01;x!==m&&a++}return a},gR=n=>({up:"bottom",down:"top",left:"right",right:"left"})[n]??null,_W=({firstEdge:n,firstEdgePort:t,firstDominantDirection:a,lastEdge:o,lastEdgePort:l,lastDominantDirection:p})=>{if(n&&t)return _W({lastEdge:{from:n.to,to:n.from},lastEdgePort:t,lastDominantDirection:a}).reverse().map(m=>({from:m.to,to:m.from}));let x=[];if(o&&l){let m={x:o.to.x,y:o.to.y};p==="left"||p==="right"?(m.x=l.position.x,x.push({from:o.to,to:{...m}}),x.push({from:m,to:{...l.position}})):(m.y=l.position.y,x.push({from:o.to,to:{...m}}),x.push({from:m,to:{...l.position}}))}return x=x.filter(m=>n0(m.from,m.to)>.01),x};function NUt(n){try{return[n(),null]}catch(t){return[null,t]}}var MUt=(n,{db:t})=>{let a=n.map(o=>{let l=t.source_port.get(o.source_port_id);if(!l?.source_component_id)return null;let p=t.source_component.get(l.source_component_id);return p?.ftype==="simple_capacitor"?p.max_decoupling_trace_length:null}).filter(o=>o!==null);if(a.length!==0)return Math.min(...a)};function OUt({ports:n,nets:t}){if(n.length>=2)return`${n[0]?.selector} to ${n[1]?.selector}`;if(n.length===1&&t.length===1)return`${n[0]?.selector} to net.${t[0]._parsedProps.name}`}var LUt=(n,{db:t})=>{let a=t.pcb_board.list()[0];if(a.outline){let g=a.outline,_=(F,C)=>{let S=!1;for(let P=0,k=C.length-1;P<C.length;k=P++){let q=C[P].x,X=C[P].y,Q=C[k].x,ee=C[k].y;X>F.y!=ee>F.y&&F.x<(Q-q)*(F.y-X)/(ee-X)+q&&(S=!S)}return S};return n.some(F=>!_(F,g))}let o=a.width,l=a.height,p=a.center.x,x=a.center.y;return n.some(g=>g.x<p-o/2||g.y<x-l/2||g.x>p+o/2||g.y>x+l/2)},c7e=(n,t)=>Math.abs(n-t)<1e-4,zUt=(n,t,{viaDiameter:a=.5}={})=>{let o=[];for(let l=0;l<n.length-1;l++){let[p,x]=[n[l],n[l+1]],m=l-1>=0?n[l-1]:null,g=c7e(p.y,x.y),_=c7e(p.x,x.x);if(!g&&!_)throw new Error(`getObstaclesFromTrace currently only supports horizontal and vertical traces (not diagonals) Conflicting trace: ${t}, start: (${p.x}, ${p.y}), end: (${x.x}, ${x.y})`);let F={type:"rect",layers:[p.layer],center:{x:(p.x+x.x)/2,y:(p.y+x.y)/2},width:g?Math.abs(p.x-x.x):.1,height:_?Math.abs(p.y-x.y):.1,connectedTo:[t]};if(o.push(F),m&&m.layer===p.layer&&p.layer!==x.layer){let C={type:"rect",layers:[p.layer,x.layer],center:{x:p.x,y:p.y},connectedTo:[t],width:a,height:a};o.push(C)}}return o};function $Ut(n,t=4){let{center:a,width:o,height:l,rotation:p}=n,x=[],m=p*Math.PI/180,g=Math.cos(m),_=Math.sin(m),F=(p%360+360)%360;if(l<=o?F>=45&&F<135||F>=225&&F<315:F>=135&&F<225||F>=315||F<45){let S=o/t;for(let P=0;P<t;P++){let k=(P-t/2+.5)*S,q=-k*g,X=-k*_,Q=S*1.1,ee=Math.abs(l*g)+Math.abs(S*_);x.push({center:{x:a.x+q,y:a.y+X},width:Q,height:ee})}}else{let S=l/t;for(let P=0;P<t;P++){let k=(P-t/2+.5)*S,q=-k*_,X=k*g,Q=Math.abs(o*g)+Math.abs(S*_),ee=S*1.1;x.push({center:{x:a.x+q,y:a.y+X},width:Q,height:ee})}}return x}function qUt(n,t={}){if(n.length<3)return[];let{rectHeight:a=.1}=t,o=[],l=n.map(m=>m.y),p=Math.min(...l),x=Math.max(...l);for(let m=p;m<x;m+=a){let g=m+a/2,_=[];for(let F=0;F<n.length;F++){let C=n[F],S=n[(F+1)%n.length];if(C.y<=g&&S.y>g||S.y<=g&&C.y>g){let P=(g-C.y)*(S.x-C.x)/(S.y-C.y)+C.x;_.push(P)}}_.sort((F,C)=>F-C);for(let F=0;F<_.length;F+=2)if(F+1<_.length){let C=_[F],P=_[F+1]-C;P>1e-6&&o.push({center:{x:C+P/2,y:g},width:P,height:a})}}return o}function UUt(n,t={}){let{center:a,radius:o}=n,{rectHeight:l=.1}=t,p=[],x=Math.ceil(o*2/l);for(let m=0;m<x;m++){let g=a.y-o+(m+.5)*l,_=g-a.y,F=Math.sqrt(o*o-_*_);F>0&&p.push({center:{x:a.x,y:g},width:F*2,height:l})}return p}var Jm=["top","inner1","inner2","bottom"],C7e=(n,t)=>{let a=l=>t?l.concat(l.map(p=>t?.getNetConnectedToId(p)).filter(Boolean)):l,o=[];for(let l of n)if(l.type==="pcb_smtpad"){if(l.shape==="circle")o.push({type:"oval",layers:[l.layer],center:{x:l.x,y:l.y},width:l.radius*2,height:l.radius*2,connectedTo:a([l.pcb_smtpad_id])});else if(l.shape==="rect")o.push({type:"rect",layers:[l.layer],center:{x:l.x,y:l.y},width:l.width,height:l.height,connectedTo:a([l.pcb_smtpad_id])});else if(l.shape==="rotated_rect"){let p={center:{x:l.x,y:l.y},width:l.width,height:l.height,rotation:l.ccw_rotation},x=$Ut(p);for(let m of x)o.push({type:"rect",layers:[l.layer],center:m.center,width:m.width,height:m.height,connectedTo:a([l.pcb_smtpad_id])})}}else if(l.type==="pcb_keepout")l.shape==="circle"?o.push({type:"oval",layers:l.layers,center:{x:l.center.x,y:l.center.y},width:l.radius*2,height:l.radius*2,connectedTo:[]}):l.shape==="rect"&&o.push({type:"rect",layers:l.layers,center:{x:l.center.x,y:l.center.y},width:l.width,height:l.height,connectedTo:[]});else if(l.type==="pcb_cutout"){if(l.shape==="rect")o.push({type:"rect",layers:Jm,center:{x:l.center.x,y:l.center.y},width:l.width,height:l.height,connectedTo:[]});else if(l.shape==="circle"){let p=UUt({center:l.center,radius:l.radius},{rectHeight:.6});for(let x of p)o.push({type:"rect",layers:Jm,center:x.center,width:x.width,height:x.height,connectedTo:[]})}else if(l.shape==="polygon"){let p=qUt(l.points,{rectHeight:.6});for(let x of p)o.push({type:"rect",layers:Jm,center:x.center,width:x.width,height:x.height,connectedTo:[]})}}else if(l.type==="pcb_hole")l.hole_shape==="oval"?o.push({type:"oval",center:{x:l.x,y:l.y},width:l.hole_width,height:l.hole_height,connectedTo:[]}):l.hole_shape==="square"?o.push({type:"rect",layers:Jm,center:{x:l.x,y:l.y},width:l.hole_diameter,height:l.hole_diameter,connectedTo:[]}):(l.hole_shape==="round"||l.hole_shape==="circle")&&o.push({type:"rect",layers:Jm,center:{x:l.x,y:l.y},width:l.hole_diameter,height:l.hole_diameter,connectedTo:[]});else if(l.type==="pcb_plated_hole")l.shape==="circle"?o.push({type:"oval",layers:Jm,center:{x:l.x,y:l.y},width:l.outer_diameter,height:l.outer_diameter,connectedTo:a([l.pcb_plated_hole_id])}):l.shape==="circular_hole_with_rect_pad"?o.push({type:"rect",layers:Jm,center:{x:l.x,y:l.y},width:l.rect_pad_width,height:l.rect_pad_height,connectedTo:a([l.pcb_plated_hole_id])}):(l.shape==="oval"||l.shape==="pill")&&o.push({type:"oval",layers:Jm,center:{x:l.x,y:l.y},width:l.outer_width,height:l.outer_height,connectedTo:a([l.pcb_plated_hole_id])});else if(l.type==="pcb_trace"){let p=zUt(l.route.map(x=>({x:x.x,y:x.y,layer:"layer"in x?x.layer:x.from_layer})),l.source_trace_id);o.push(...p)}else l.type==="pcb_via"&&o.push({type:"rect",layers:l.layers,center:{x:l.x,y:l.y},connectedTo:[],width:l.outer_diameter,height:l.outer_diameter});return o},o8=({anchor_position:n,anchor_side:t,text:a,font_size:o=.18})=>{let l=.1*(o/.18),p=a.length*l,x=o,m={...n};switch(t){case"right":m.x-=p/2;break;case"left":m.x+=p/2;break;case"top":m.y-=x/2;break;case"bottom":m.y+=x/2;break}return m},BW=({db:n,source_trace_id:t,sameNetOnly:a,differentNetOnly:o})=>{!a&&!o&&(o=!0);let l=n.source_trace.get(t),p=[];for(let x of n.schematic_trace.list()){if(x.source_trace_id===t)continue;let g=n.source_trace.get(x.source_trace_id)?.subcircuit_connectivity_map_key===l.subcircuit_connectivity_map_key;o&&g||a&&!g||p.push(x)}return p},VUt=({edges:n,otherEdges:t})=>{let a=[...n];for(let o=0;o<a.length;o++){if(o>2e3)throw new Error("Over 2000 iterations spent inside createSchematicTraceCrossingSegments, you have triggered an infinite loop, please report this!");let l=a[o],p=Math.abs(l.from.x-l.to.x)<.01?"vertical":l.from.y===l.to.y?"horizontal":"not-orthogonal";if(p==="not-orthogonal")continue;let x=[];for(let q of t){let X=q.from.x===q.to.x?"vertical":q.from.y===q.to.y?"horizontal":"not-orthogonal";if(X==="not-orthogonal"||p===X)continue;if(jm([l.from,l.to],[q.from,q.to],{lineThickness:.01})){let ee=p==="vertical"?l.from.x:q.from.x,ue=p==="vertical"?q.from.y:l.from.y,ce={x:ee,y:ue};x.push({otherEdge:q,crossingPoint:ce,distanceFromEdgeFrom:n0(l.from,ce)})}}if(x.length===0)continue;let m=x[0];for(let q of x)q.distanceFromEdgeFrom<m.distanceFromEdgeFrom&&(m=q);let g=m.crossingPoint,_=.075;if(g.x===l.from.x&&g.y===l.from.y)continue;let F=i7(l.from,g),C={x:g.x-F.x*_/2,y:g.y-F.y*_/2},S={x:g.x+F.x*_/2,y:g.y+F.y*_/2},P=n0(S,l.to)<_,k=[{from:l.from,to:C},{from:C,to:S,is_crossing:!0},{from:S,to:l.to}];a.splice(o,1,...k),o+=k.length-2,P&&o++}return a},bW=.001,D_=(n,t)=>{let a=Math.min(t.from.x,t.to.x),o=Math.max(t.from.x,t.to.x),l=Math.min(t.from.y,t.to.y),p=Math.max(t.from.y,t.to.y);return n.x>=a&&n.x<=o&&n.y>=l&&n.y<=p},u7e=n=>{let t=Math.abs(n.from.x-n.to.x)<bW,a=Math.abs(n.from.y-n.to.y)<bW;return t?"vertical":a?"horizontal":"diagonal"},GUt=(n,t)=>{let a=u7e(n),o=u7e(t);if(a===o)return null;if(a==="vertical"&&o==="horizontal"||a==="horizontal"&&o==="vertical"){let C=a==="vertical"?n:t,S=a==="horizontal"?n:t,P=C.from.x,k=S.from.y,q={x:P,y:k};return D_(q,n)&&D_(q,t)?q:null}if(a==="vertical"||o==="vertical"){let C=a==="vertical"?n:t,S=a==="vertical"?t:n,P=C.from.x,k=(S.to.y-S.from.y)/(S.to.x-S.from.x),q=S.from.y-k*S.from.x,X=k*P+q,Q={x:P,y:X};return D_(Q,n)&&D_(Q,t)?Q:null}let l=(n.to.y-n.from.y)/(n.to.x-n.from.x),p=n.from.y-l*n.from.x,x=(t.to.y-t.from.y)/(t.to.x-t.from.x),m=t.from.y-x*t.from.x;if(Math.abs(l-x)<bW)return null;let g=(m-p)/(l-x),_=l*g+p,F={x:g,y:_};return D_(F,n)&&D_(F,t)?F:null},HUt=({edges:n,db:t,source_trace_id:a})=>{let o=BW({db:t,source_trace_id:a,sameNetOnly:!0}).flatMap(p=>p.edges),l=new Map;for(let p of n)for(let x of o){let m=GUt(p,x);if(m){let g=`${m.x.toFixed(6)},${m.y.toFixed(6)}`;l.has(g)||l.set(g,m)}}return Array.from(l.values())};function YUt(n){let t=1/0,a=1/0,o=-1/0,l=-1/0;for(let p of n){let x,m,g,_;p.type==="schematic_component"?(x=p.center?.x,m=p.center?.y,g=p.size?.width,_=p.size?.height):p.type==="schematic_box"?(x=p.x,m=p.y,g=p.width,_=p.height):p.type==="schematic_port"?(x=p.center?.x,m=p.center?.y,g=.2,_=.2):p.type==="schematic_text"&&(x=p.position?.x,m=p.position?.y,g=(p.text?.length??0)*.1,_=.2),typeof x=="number"&&typeof m=="number"&&typeof g=="number"&&typeof _=="number"&&(t=Math.min(t,x-g/2),o=Math.max(o,x+g/2),a=Math.min(a,m-_/2),l=Math.max(l,m+_/2))}return{minX:t,maxX:o,minY:a,maxY:l}}function XUt(n,t={}){let{minX:a,maxX:o,minY:l,maxY:p}=n,x=t.padding??1;if(!isFinite(a)||!isFinite(o)||!isFinite(l)||!isFinite(p))return[];let m=a-x,g=o+x,_=p+x,F=l-x,C=.01;return[{type:"rect",layers:["top"],center:{x:(m+g)/2,y:_},width:g-m,height:C,connectedTo:[]},{type:"rect",layers:["top"],center:{x:(m+g)/2,y:F},width:g-m,height:C,connectedTo:[]},{type:"rect",layers:["top"],center:{x:m,y:(_+F)/2},width:C,height:_-F,connectedTo:[]},{type:"rect",layers:["top"],center:{x:g,y:(_+F)/2},width:C,height:_-F,connectedTo:[]}]}var WUt=n=>{let t=n.root.db,a=n._findConnectedPorts().ports??[],o=new Set(a.map(x=>x.schematic_port_id)),l=[];for(let x of t.toArray()){if(x.type==="schematic_component"){let m=!!x.symbol_name,g=x.size.width>x.size.height?"horz":"vert";l.push({type:"rect",layers:["top"],center:x.center,width:x.size.width+(m&&g==="horz"?-.5:0),height:x.size.height+(m&&g==="vert"?-.5:0),connectedTo:[]})}if(x.type==="schematic_port"){if(o.has(x.schematic_port_id))continue;let m=x.facing_direction?s7(x.facing_direction):{x:0,y:0};l.push({type:"rect",layers:["top"],center:{x:x.center.x-m.x*.1,y:x.center.y-m.y*.1},width:.1+Math.abs(m.x)*.3,height:.1+Math.abs(m.y)*.3,connectedTo:[]})}x.type==="schematic_text"&&l.push({type:"rect",layers:["top"],center:x.position,width:(x.text?.length??0)*.1,height:.2,connectedTo:[]}),x.type==="schematic_box"&&l.push({type:"rect",layers:["top"],center:{x:x.x,y:x.y},width:x.width,height:x.height,connectedTo:[]})}let p=YUt(t.toArray());return l.push(...XUt(p,{padding:1})),l},KUt=({edges:n,db:t,source_trace_id:a})=>{let o=t.source_trace.get(a),l=BW({db:t,source_trace_id:a,differentNetOnly:!0}).flatMap(x=>x.edges),p=x=>{let{from:m,to:g}=x;return m.x===g.x?"vertical":"horizontal"};for(let x of n){let m=p(x),g=()=>l.find(F=>p(F)===m&&jm([x.from,x.to],[F.from,F.to],{lineThickness:.05})),_=g();for(;_;)m==="horizontal"?(x.from.y+=.1,x.to.y+=.1):(x.from.x+=.1,x.to.x+=.1),_=g()}},l7e=n=>{switch(n){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:}},JUt=w4e.version??"unknown",a8=class extends Error{constructor(n){super(`${n} (capacity-autorouter@${JUt})`),this.name="AutorouterError"}},DR=class extends Error{constructor(n){super(n.message),this.errorData=n,this.name="TraceConnectionError"}},ZUt=n=>{if(n._couldNotFindPort||n.root?.schematicDisabled)return;let{db:t}=n.root,{_parsedProps:a,parent:o}=n;if(!o)throw new Error("Trace has no parent");let l,p;try{let Te=n._findConnectedPorts();l=Te.allPortsFound,p=Te.portsWithSelectors??[]}catch(Te){if(Te instanceof DR){t.source_trace_not_connected.insert(Te.errorData);return}throw Te}let{netsWithSelectors:x}=n._findConnectedNets();if(!l)return;let g=p.map(Te=>Te.port.schematic_port_id).sort().join(","),_=n.root?._getBoard();if(_?._connectedSchematicPortPairs&&_._connectedSchematicPortPairs.has(g))return;let F={name:n.source_trace_id,pointsToConnect:[]},C=WUt(n),S=p.filter(({port:Te})=>Te.schematic_port_id!==null).map(({port:Te})=>({port:Te,position:Te._getGlobalSchematicPositionAfterLayout(),schematic_port_id:Te.schematic_port_id??void 0,facingDirection:Te.facingDirection}));if(S.length===1&&x.length===1){let Te=x[0].net,{port:Ke,position:Qe}=S[0],pt=n.getSubcircuit().selectAll("netlabel").find(xt=>{let dt=xt._parsedProps.connection??xt._parsedProps.connectsTo;return dt?Array.isArray(dt)?dt.some(Wt=>n.getSubcircuit().selectOne(Wt,{port:!0})===Ke):n.getSubcircuit().selectOne(dt,{port:!0})===Ke:!1});if(!pt){let xt=t.schematic_net_label.getWhere({source_trace_id:n.source_trace_id});xt&&(pt=xt)}if(pt){let xt="_getGlobalSchematicPositionBeforeLayout"in pt?pt._getGlobalSchematicPositionBeforeLayout():pt.anchor_position,dt=[];Qe.x===xt.x||Qe.y===xt.y?dt.push({from:Qe,to:xt}):(dt.push({from:Qe,to:{x:xt.x,y:Qe.y}}),dt.push({from:{x:xt.x,y:Qe.y},to:xt}));let ar=t.schematic_trace.insert({source_trace_id:n.source_trace_id,edges:dt,junctions:[]});n.schematic_trace_id=ar.schematic_trace_id;return}if(n.props.schDisplayLabel){let xt=gR(Ke.facingDirection)??"bottom";t.schematic_net_label.insert({text:n.props.schDisplayLabel,source_net_id:Te.source_net_id,anchor_position:Qe,center:o8({anchor_position:Qe,anchor_side:xt,text:n.props.schDisplayLabel}),anchor_side:xt});return}let jt=gR(Ke.facingDirection)??"bottom",vt=t.schematic_net_label.insert({text:Te._parsedProps.name,source_net_id:Te.source_net_id,anchor_position:Qe,center:o8({anchor_position:Qe,anchor_side:jt,text:Te._parsedProps.name}),anchor_side:jt});return}if(n.props.schDisplayLabel&&("from"in n.props&&"to"in n.props||"path"in n.props)){n._doInitialSchematicTraceRenderWithDisplayLabel();return}if(S.length<2)return;let q=(()=>{let Te=[];for(let Qe=0;Qe<S.length-1;Qe++){let pt=S[Qe],jt=S[Qe+1],vt=I4e({x:pt.position.x,y:pt.position.y,facingDirection:l7e(pt.facingDirection)},{x:jt.position.x,y:jt.position.y,facingDirection:l7e(jt.facingDirection)});for(let xt=0;xt<vt.length-1;xt++)Te.push({from:vt[xt],to:vt[xt+1]})}let Ke=(Qe,pt)=>{let jt=pt.width/2,vt=pt.height/2,xt=pt.center.x-jt,dt=pt.center.x+jt,ar=pt.center.y-vt,Wt=pt.center.y+vt,cr=wt=>wt.x>=xt&&wt.x<=dt&&wt.y>=ar&&wt.y<=Wt;return cr(Qe.from)||cr(Qe.to)?!0:[[{x:xt,y:ar},{x:dt,y:ar}],[{x:dt,y:ar},{x:dt,y:Wt}],[{x:dt,y:Wt},{x:xt,y:Wt}],[{x:xt,y:Wt},{x:xt,y:ar}]].some(wt=>jm([Qe.from,Qe.to],wt,{lineThickness:0}))};for(let Qe of Te)for(let pt of C)if(Ke(Qe,pt))return null;return Te})();q&&q.length===0&&(q=null),F.pointsToConnect=S.map(({position:Te})=>({...Te,layer:"top"}));let X=BUt(C),Q=2,ee={minTraceWidth:.1,obstacles:C,connections:[F],bounds:{minX:X.minX-Q,maxX:X.maxX+Q,minY:X.minY-Q,maxY:X.maxY+Q},layerCount:1},ue=GA,ce=!1;if(n.getSubcircuit().props._schDirectLineRoutingEnabled&&(ue=i7e,ce=!0),!q){let Ke=new ue({input:ee,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(Ke.length===0){if(n._isSymbolToChipConnection()||n._isSymbolToSymbolConnection()||n._isChipToChipConnection()){n._doInitialSchematicTraceRenderWithDisplayLabel();return}Ke=new i7e({input:ee}).solveAndMapToTraces(),ce=!0}let[{route:Qe}]=Ke;q=[];for(let pt=0;pt<Qe.length-1;pt++)q.push({from:Qe[pt],to:Qe[pt+1]})}let fe=n.source_trace_id,U=[];if(!ce){KUt({edges:q,db:t,source_trace_id:fe});let Te=BW({db:t,source_trace_id:fe,differentNetOnly:!0}).flatMap(Ke=>Ke.edges);q=VUt({edges:q,otherEdges:Te}),U=HUt({edges:q,db:t,source_trace_id:n.source_trace_id})}if(!q||q.length===0)return;let me=q[q.length-1],W=S[S.length-1],pe=o7e(me);q.push(..._W({lastEdge:me,lastEdgePort:W,lastDominantDirection:pe}));let he=q[0],Ae=S[0],de=o7e(he);if(q.unshift(..._W({firstEdge:he,firstEdgePort:Ae,firstDominantDirection:de})),!n.source_trace_id)throw new Error("Missing source_trace_id for schematic trace insertion.");if(n.getSubcircuit()._parsedProps.schTraceAutoLabelEnabled&&jUt(U,q)>=5&&(n._isSymbolToChipConnection()||n._isSymbolToSymbolConnection()||n._isChipToChipConnection())){n._doInitialSchematicTraceRenderWithDisplayLabel();return}let Ne=t.schematic_trace.insert({source_trace_id:n.source_trace_id,edges:q,junctions:U});n.schematic_trace_id=Ne.schematic_trace_id;for(let{port:Te}of p)Te.schematic_port_id&&t.schematic_port.update(Te.schematic_port_id,{is_connected:!0});_?._connectedSchematicPortPairs&&_._connectedSchematicPortPairs.add(g)};function A7e(n){let t=0;for(let a=0;a<n.length;a++){let o=n[a];if(o.route_type==="wire"){let l=n[a+1];if(l){let p=l.x-o.x,x=l.y-o.y;t+=Math.sqrt(p*p+x*x)}}else o.route_type==="via"&&(t+=1.6)}return t}var dR=n=>({...n._getGlobalPcbPositionAfterLayout(),layers:n.getAvailablePcbLayers()}),QUt=!1;function eVt(n){if(n.root?.pcbDisabled)return;let{db:t}=n.root,{_parsedProps:a,parent:o}=n,l=n.getSubcircuit();if(!o)throw new Error("Trace has no parent");if(l._parsedProps.routingDisabled)return;let p=l._parsedProps.pcbRouteCache?.pcbTraces;if(p){let pe=t.pcb_trace.insert({route:p.flatMap(he=>he.route),source_trace_id:n.source_trace_id,subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:n.getGroup()?.pcb_group_id??void 0});n.pcb_trace_id=pe.pcb_trace_id;return}if(a.pcbPath&&a.pcbPath.length>0||!l._shouldUseTraceByTraceRouting())return;let{allPortsFound:x,ports:m}=n._findConnectedPorts(),g=[];if(!x)return;let _=[];for(let pe of m)pe._hasMatchedPcbPrimitive()||_.push(pe);if(_.length>0){t.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:n.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, ${n} wasn't routed. Missing ports: ${_.map(pe=>pe.getString()).join(", ")}`,pcb_trace_id:n.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:_.map(pe=>pe.pcb_port_id).filter(Boolean)});return}let F=n._findConnectedNets().netsWithSelectors;if(m.length===0&&F.length===2){n.renderError("Trace connects two nets, we haven't implemented a way to route this yet");return}else if(m.length===1&&F.length===1){let pe=m[0],Ae=F[0].net.getAllConnectedPorts().filter(Ne=>Ne!==pe);if(Ae.length===0){console.log("Nothing to connect this port to, the net is empty. TODO should emit a warning!");return}let de=kUt(pe,Ae);g.push(de),m.push(de)}else if(m.length>1&&F.length>=1){n.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 C=m.flatMap(pe=>pe.matchedComponents.filter(he=>he.componentName==="TraceHint")),S=(n._parsedProps.pcbRouteHints??[]).concat(C.flatMap(pe=>pe.getPcbRouteHints()));if(m.length>2){n.renderError(`Trace has more than two ports (${m.map(pe=>pe.getString()).join(", ")}), routing between more than two ports for a single trace is not implemented`);return}if(n.getSubcircuit().selectAll("trace").filter(pe=>pe.renderPhaseStates.PcbTraceRender.initialized).some(pe=>pe._portsRoutedOnPcb.length===m.length&&pe._portsRoutedOnPcb.every(he=>m.includes(he))))return;let q=[];S.length===0?q=[dR(m[0]),dR(m[1])]:q=[dR(m[0]),...S,dR(m[1])];let X=xR(q);if(QUt&&X.length===0){n.renderError(`Could not find a common layer (using hints) for trace ${n.getString()}`);return}let Q=rx(n.root.db.toArray()),[ee,ue]=NUt(()=>C7e(n.root.db.toArray()));if(ue){n.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:n.pcb_trace_id,message:`Error getting obstacles for autorouting: ${ue.message}`,source_trace_id:n.source_trace_id,center:{x:0,y:0},pcb_port_ids:m.map(pe=>pe.pcb_port_id),pcb_trace_id:n.pcb_trace_id,pcb_component_ids:[]});return}for(let pe of ee)if(pe.connectedTo.length>0){let Ae=Q.getNetConnectedToId(pe.connectedTo[0]);Ae&&pe.connectedTo.push(Ae)}let ce=[];if(X.length===0)ce=q;else{let pe=X[0].layer_path;ce=q.map((he,Ae)=>he.via?{...he,via_to_layer:pe[Ae]}:{...he,layers:[pe[Ae]]})}ce[0].pcb_port_id=m[0].pcb_port_id,ce[ce.length-1].pcb_port_id=m[1].pcb_port_id;let fe=[];for(let[pe,he]of _7e(ce)){let Ae="via_to_layer"in pe?pe.via_to_layer:null,de=2,Ne="layers"in pe&&pe.layers.length===1?pe.layers[0]:Ae??"top",Te="layers"in he&&he.layers.length===1?he.layers[0]:Ae??"top",Ke="pcb_port_id"in pe?pe.pcb_port_id:null,Qe="pcb_port_id"in he?he.pcb_port_id:null,pt=n.getSubcircuit()._parsedProps.minTraceWidth??.16,jt=new GA({OBSTACLE_MARGIN:pt*2,isRemovePathLoopsEnabled:!0,optimizeWithGoalBoxes:!!(Ke&&Qe),connMap:Q,input:{obstacles:ee,minTraceWidth:pt,connections:[{name:n.source_trace_id,pointsToConnect:[{...pe,layer:Ne,pcb_port_id:Ke},{...he,layer:Te,pcb_port_id:Qe}]}],layerCount:n.getSubcircuit()._getSubcircuitLayerCount(),bounds:{minX:Math.min(pe.x,he.x)-de,maxX:Math.max(pe.x,he.x)+de,minY:Math.min(pe.y,he.y)-de,maxY:Math.max(pe.y,he.y)+de}}}),vt=null;try{vt=jt.solveAndMapToTraces()}catch(ar){n.renderError({type:"pcb_trace_error",pcb_trace_error_id:n.source_trace_id,error_type:"pcb_trace_error",message:`error solving route: ${ar.message}`,source_trace_id:n.pcb_trace_id,center:{x:(pe.x+he.x)/2,y:(pe.y+he.y)/2},pcb_port_ids:m.map(Wt=>Wt.pcb_port_id),pcb_trace_id:n.pcb_trace_id,pcb_component_ids:m.map(Wt=>Wt.pcb_component_id)})}if(!vt)return;if(vt.length===0){n.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:n.pcb_trace_id,message:`Could not find a route for ${n}`,source_trace_id:n.source_trace_id,center:{x:(pe.x+he.x)/2,y:(pe.y+he.y)/2},pcb_port_ids:m.map(ar=>ar.pcb_port_id),pcb_trace_id:n.pcb_trace_id,pcb_component_ids:m.map(ar=>ar.pcb_component_id)});return}let[xt]=vt;Ae&&(xt.route=xt.route.map(ar=>(ar.route_type==="wire"&&!ar.layer&&(ar.layer=Ae),ar))),Ke&&xt.route[0].route_type==="wire"&&(xt.route[0].start_pcb_port_id=Ke);let dt=xt.route[xt.route.length-1];Qe&&dt.route_type==="wire"&&(dt.end_pcb_port_id=Qe),fe.push(xt.route)}let U=TUt(fe),me=A7e(U),W=t.pcb_trace.insert({route:U,source_trace_id:n.source_trace_id,subcircuit_id:n.getSubcircuit()?.subcircuit_id,trace_length:me});n._portsRoutedOnPcb=m,n.pcb_trace_id=W.pcb_trace_id;for(let pe of U)pe.route_type==="via"&&t.pcb_via.insert({pcb_trace_id:W.pcb_trace_id,x:pe.x,y:pe.y,hole_diameter:.3,outer_diameter:.6,layers:[pe.from_layer,pe.to_layer],from_layer:pe.from_layer,to_layer:pe.to_layer});n._insertErrorIfTraceIsOutsideBoard(U,m)}function tVt(n){if(n.root?.pcbDisabled)return;let{db:t}=n.root,{_parsedProps:a}=n,o=n.getSubcircuit();if(!a.pcbPath||a.pcbPath.length===0)return;let{allPortsFound:l,ports:p,portsWithSelectors:x}=n._findConnectedPorts();if(!l)return;let m=[];for(let Q of p)Q._hasMatchedPcbPrimitive()||m.push(Q);if(m.length>0){t.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:n.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, ${n} wasn't routed. Missing ports: ${m.map(Q=>Q.getString()).join(", ")}`,pcb_trace_id:n.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:m.map(Q=>Q.pcb_port_id).filter(Boolean)});return}let g;a.pcbPathRelativeTo&&(g=x.find(Q=>Q.selector===a.pcbPathRelativeTo)?.port,g||(g=n.getSubcircuit().selectOne(a.pcbPathRelativeTo))),g||(g=p[0]);let _=p.find(Q=>Q!==g)??p[1],F=g.getAvailablePcbLayers()[0]||"top",C=a.thickness??n.getSubcircuit()._parsedProps.minTraceWidth??.16,S=g._getGlobalPcbPositionAfterLayout(),P=_._getGlobalPcbPositionAfterLayout(),k=[];k.push({route_type:"wire",x:S.x,y:S.y,width:C,layer:F,start_pcb_port_id:g.pcb_port_id});for(let Q of a.pcbPath)k.push({route_type:"wire",x:S.x+Q.x,y:S.y+Q.y,width:C,layer:F});k.push({route_type:"wire",x:P.x,y:P.y,width:C,layer:F,end_pcb_port_id:_.pcb_port_id});let q=A7e(k),X=t.pcb_trace.insert({route:k,source_trace_id:n.source_trace_id,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:n.getGroup()?.pcb_group_id??void 0,trace_length:q});n._portsRoutedOnPcb=p,n.pcb_trace_id=X.pcb_trace_id,n._insertErrorIfTraceIsOutsideBoard(k,p)}function rVt(n){if(n.root?.schematicDisabled)return;let{db:t}=n.root,{_parsedProps:a,parent:o}=n;if(!o)throw new Error("Trace has no parent");let{allPortsFound:l,portsWithSelectors:p}=n._findConnectedPorts();if(!l)return;let x=p.map(({port:ce})=>({port:ce,position:ce._getGlobalSchematicPositionAfterLayout(),schematic_port_id:ce.schematic_port_id,facingDirection:ce.facingDirection}));if(x.length<2)throw new Error("Expected at least two ports in portsWithPosition.");let m,g,_=x[0].position,F=x[0].port;if("path"in n.props){if(n.props.path.length!==2)throw new Error("Invalid 'path': Must contain exactly two elements.");[m,g]=n.props.path}else{if(!("from"in n.props&&"to"in n.props))throw new Error("Missing 'from' or 'to' properties in props.");m=n.props.from,g=n.props.to}if(!F.source_port_id)throw new Error(`Missing source_port_id for the 'from' port (${m}).`);let C=x[1].position,S=x[1].port;if(!S.source_port_id)throw new Error(`Missing source_port_id for the 'to' port (${g}).`);let P=t.schematic_net_label.list().find(ce=>ce.source_net_id===F.source_port_id),k=t.schematic_net_label.list().find(ce=>ce.source_net_id===S.source_port_id),[q,X]=p.map(({port:ce})=>ce),ee=q.parent?.config.shouldRenderAsSchematicBox?`${q?.parent?.props.name}_${q?.props.name}`:`${X?.parent?.props.name}_${X?.props.name}`,ue=n.props.schDisplayLabel??ee;if(P&&P.text!==ue&&(P.text=`${ue} / ${P.text}`),k&&k?.text!==ue&&(k.text=`${ue} / ${k.text}`),!k){let ce=gR(S.facingDirection)??"bottom";t.schematic_net_label.insert({text:n.props.schDisplayLabel??ee,source_net_id:S.source_port_id,anchor_position:C,center:o8({anchor_position:C,anchor_side:ce,text:n.props.schDisplayLabel??ee}),anchor_side:ce})}if(!P){let ce=gR(F.facingDirection)??"bottom";t.schematic_net_label.insert({text:n.props.schDisplayLabel??ee,source_net_id:F.source_port_id,anchor_position:_,center:o8({anchor_position:_,anchor_side:ce,text:n.props.schDisplayLabel??ee}),anchor_side:ce})}}function nVt(n){let{_parsedProps:t,parent:a}=n;if(!a)throw new Error("Trace has no parent");let l=n.getTracePortPathSelectors().map(p=>({selector:p,port:n.getSubcircuit().selectOne(p,{type:"port"})??null}));for(let{selector:p,port:x}of l)if(!x){let m,g,_=p.lastIndexOf(".");if(_!==-1&&_>p.lastIndexOf(" "))m=p.slice(0,_),g=p.slice(_+1);else{let ce=p.match(/^(.*[ >])?([^ >]+)$/);m=ce?.[1]?.trim()??"",g=ce?.[2]??p}let F=m?n.getSubcircuit().selectOne(m):null;if(!F&&m&&!/[.#\[]/.test(m)&&(F=n.getSubcircuit().selectOne(`.${m}`)),!F){let ce=m?`Could not find port for selector "${p}". Component "${m}" not found`:`Could not find port for selector "${p}"`,fe=n.getSubcircuit(),U=fe.getGroup();throw new DR({error_type:"source_trace_not_connected",message:ce,subcircuit_id:fe.subcircuit_id??void 0,source_group_id:U?.source_group_id??void 0,source_trace_id:n.source_trace_id??void 0,selectors_not_found:[p]})}let C=F.children.filter(ce=>ce.componentName==="Port"),S=g.includes(".")?g.split(".").pop()??"":g,P=C.flatMap(ce=>ce.getNameAndAliases()),k=P.some(ce=>!/^(pin\d+|\d+)$/.test(ce)),q=Array.from(new Set(P)).join(", "),X;C.length===0?X="It has no ports":k?X=`It has [${q}]`:X=`It has ${C.length} pins and no pinLabels (consider adding pinLabels)`;let Q=`Could not find port for selector "${p}". Component "${F.props.name??m}" found, but does not have pin "${S}". ${X}`,ee=n.getSubcircuit(),ue=ee.getGroup();throw new DR({error_type:"source_trace_not_connected",message:Q,subcircuit_id:ee.subcircuit_id??void 0,source_group_id:ue?.source_group_id??void 0,source_trace_id:n.source_trace_id??void 0,selectors_not_found:[p]})}return l.some(p=>!p.port)?{allPortsFound:!1}:{allPortsFound:!0,portsWithSelectors:l,ports:l.map(({port:p})=>p)}}var Od=class extends Ya{constructor(t){super(t);J(this,"source_trace_id",null);J(this,"pcb_trace_id",null);J(this,"schematic_trace_id",null);J(this,"_portsRoutedOnPcb");J(this,"subcircuit_connectivity_map_key",null);J(this,"_traceConnectionHash",null);J(this,"_couldNotFindPort");this._portsRoutedOnPcb=[]}get config(){return{zodProps:qEe,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 nVt(this)}_resolveNet(t){let a=this.getSubcircuit().selectOne(t,{type:"net"});if(a)return a;let o=t.match(/^net\.(.+)$/),l=o?o[1]:null;return l&&this.root._getBoard().getDescendants().find(x=>x.componentName==="Net"&&x._parsedProps.name===l)||null}_findConnectedNets(){let t=this.getTracePathNetSelectors().map(o=>({selector:o,net:this._resolveNet(o)})),a=t.filter(o=>!o.net);return a.length>0&&this.renderError(`Could not find net for selector "${a[0].selector}" inside ${this}`),{netsWithSelectors:t,nets:t.map(o=>o.net)}}_getAllTracesConnectedToSameNet(){let t=this.getSubcircuit().selectAll("trace"),a=this._findConnectedNets().nets,o=this._findConnectedPorts().ports??[];return t.filter(l=>{if(l===this)return!1;let p=l._findConnectedNets().nets,x=l._findConnectedPorts().ports??[];return p.some(m=>a.includes(m))||x.some(m=>o.includes(m))})}_isExplicitlyConnectedToPort(t){let{allPortsFound:a,portsWithSelectors:o}=this._findConnectedPorts();return a?o.map(p=>p.port).includes(t):!1}_isExplicitlyConnectedToNet(t){return this._findConnectedNets().nets.includes(t)}doInitialCreateNetsFromProps(){RW(this,this.getTracePathNetSelectors())}_computeTraceConnectionHash(){let{allPortsFound:t,ports:a}=this._findConnectedPorts();return!t||!a?null:[...a].sort((p,x)=>(p.pcb_port_id||"").localeCompare(x.pcb_port_id||"")).map(p=>p.pcb_port_id).join(",")}doInitialSourceTraceRender(){let{db:t}=this.root,{_parsedProps:a,parent:o}=this;if(!o){this.renderError("Trace has no parent");return}let l,p;try{let C=this._findConnectedPorts();l=C.allPortsFound,p=C.portsWithSelectors??[]}catch(C){if(C instanceof DR){t.source_trace_not_connected.insert(C.errorData),this._couldNotFindPort=!0;return}throw C}if(!l)return;this._traceConnectionHash=this._computeTraceConnectionHash();let m=t.source_trace.list().find(C=>C.subcircuit_connectivity_map_key===this.subcircuit_connectivity_map_key&&C.connected_source_port_ids.sort().join(",")===this._traceConnectionHash);if(m){this.source_trace_id=m.source_trace_id;return}let g=this._findConnectedNets().nets,_=OUt({ports:p,nets:g}),F=t.source_trace.insert({connected_source_port_ids:p.map(C=>C.port.source_port_id),connected_source_net_ids:g.map(C=>C.source_net_id),subcircuit_id:this.getSubcircuit()?.subcircuit_id,max_length:MUt(p.map(C=>C.port),{db:t})??a.maxLength,display_name:_,min_trace_thickness:a.thickness});this.source_trace_id=F.source_trace_id}_insertErrorIfTraceIsOutsideBoard(t,a){let{db:o}=this.root;LUt(t,{db:o})&&o.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:a.map(p=>p.pcb_port_id)})}doInitialPcbManualTraceRender(){tVt(this)}doInitialPcbTraceRender(){eVt(this)}_doInitialSchematicTraceRenderWithDisplayLabel(){rVt(this)}_isSymbolToChipConnection(){let{allPortsFound:t,ports:a}=this._findConnectedPorts();if(!t||a.length!==2)return!1;let[o,l]=a;if(!o?.parent||!l?.parent)return!1;let p=o.parent.config.shouldRenderAsSchematicBox,x=l.parent.config.shouldRenderAsSchematicBox;return p&&!x||!p&&x}_isSymbolToSymbolConnection(){let{allPortsFound:t,ports:a}=this._findConnectedPorts();if(!t||a.length!==2)return!1;let[o,l]=a;if(!o?.parent||!l?.parent)return!1;let p=!o.parent.config.shouldRenderAsSchematicBox,x=!l.parent.config.shouldRenderAsSchematicBox;return p&&x}_isChipToChipConnection(){let{allPortsFound:t,ports:a}=this._findConnectedPorts();if(!t||a.length!==2)return!1;let[o,l]=a;if(!o?.parent||!l?.parent)return!1;let p=o.parent.config.shouldRenderAsSchematicBox,x=l.parent.config.shouldRenderAsSchematicBox;return p&&x}doInitialSchematicTraceRender(){ZUt(this)}},aVt=(0,f7e.default)("tscircuit:core"),iVt=E.object({x:ws,y:ws,z:ws}),es=class extends Ya{constructor(t){super(t);J(this,"reactSubtrees",[]);J(this,"_impliedFootprint");J(this,"isPrimitiveContainer",!0);J(this,"_asyncSupplierPartNumbers");J(this,"pcb_missing_footprint_error_id");J(this,"_hasStartedFootprintUrlLoad",!1);this._addChildrenFromStringFootprint(),this.initPorts()}get defaultInternallyConnectedPinNames(){return[]}get internallyConnectedPinNames(){return this._parsedProps.internallyConnectedPins??this.defaultInternallyConnectedPinNames}initPorts(t={}){if(this.root?.schematicDisabled)return;let{config:a}=this,o=[],l=this._getSchematicPortArrangement();if(l&&!this._parsedProps.pinLabels){for(let _ in l){let F=l[_].pins;if(Array.isArray(F))for(let C of F){let S=s8(C,this._parsedProps.pinLabels);o.push(new cu({pinNumber:S,aliases:t.additionalAliases?.[`pin${S}`]??[]},{originDescription:`schPortArrangement:${_}`}))}}let m=["left","right","top","bottom"],g=1;for(let _ of m){let F=l[`${_}Size`];for(let C=0;C<F;C++)o.push(new cu({pinNumber:g++,aliases:t.additionalAliases?.[`pin${g}`]??[]},{originDescription:`schPortArrangement:${_}`}))}}let p=this._parsedProps.pinLabels;if(p)for(let[m,g]of Object.entries(p)){m=m.replace("pin","");let _=o.find(S=>S._parsedProps.pinNumber===Number(m)),F=Array.isArray(g)?g[0]:g,C=Array.isArray(g)?g.slice(1):[];_?(_.externallyAddedAliases.push(F,...C),_.props.name=F):(_=new cu({pinNumber:parseInt(m),name:F,aliases:[...C,...t.additionalAliases?.[`pin${parseInt(m)}`]??[]]},{originDescription:`pinLabels:pin${m}`}),o.push(_))}if(a.schematicSymbolName&&!t.ignoreSymbolPorts){let m=Us[this._getSchematicSymbolNameOrThrow()];if(!m)return;for(let g of m.ports){let _=b7e(g.labels);if(!_)continue;let F=o.find(C=>C._parsedProps.pinNumber===Number(_));if(F)F.schematicSymbolPortDef=g;else{let C=n8(g.labels.concat(t.additionalAliases?.[`pin${_}`]??[]));C&&(C.originDescription=`schematicSymbol:labels[0]:${g.labels[0]}`,C.schematicSymbolPortDef=g,o.push(C))}}this.addAll(o)}if(!this._getSchematicPortArrangement()){let m=this.getPortsFromFootprint(t);for(let g of m)o.some(_=>_.isMatchingAnyOf(g.getNameAndAliases()))||o.push(g)}let x=t.pinCount??this._getPinCount()??0;for(let m=1;m<=x;m++){if(o.find(_=>_._parsedProps.pinNumber===m))continue;if(!l){o.push(new cu({pinNumber:m,aliases:t.additionalAliases?.[`pin${m}`]??[]}));continue}let g=[...l.leftSide?.pins??[],...l.rightSide?.pins??[],...l.topSide?.pins??[],...l.bottomSide?.pins??[]].map(_=>s8(_,this._parsedProps.pinLabels));["leftSize","rightSize","topSize","bottomSize","leftPinCount","rightPinCount","topPinCount","bottomPinCount"].some(_=>_ in l)&&(g=Array.from({length:this._getPinCount()},(_,F)=>F+1)),g.includes(m)&&o.push(new cu({pinNumber:m,aliases:t.additionalAliases?.[`pin${m}`]??[]},{originDescription:`notOtherwiseAddedButDeducedFromPinCount:${m}`}))}o.length>0&&this.addAll(o)}_getImpliedFootprintString(){return null}_isFootprintUrl(t){return t.startsWith("http://")||t.startsWith("https://")}_addChildrenFromStringFootprint(){let{pcbRotation:t,pinLabels:a,pcbPinLabels:o}=this.props,{footprint:l}=this.props;if(l??(l=this._getImpliedFootprintString?.()),!!l&&typeof l=="string"){if(this._isFootprintUrl(l))return;let p=Aq.string(l).soup(),x=a7e({componentName:this.name??this.componentName,componentRotation:t,footprint:l,pinLabels:a,pcbPinLabels:o},p);this.addAll(x)}}get portMap(){return new Proxy({},{get:(t,a)=>{let o=this.children.find(l=>l.componentName==="Port"&&l.isMatchingNameOrAlias(a));if(!o)throw new Error(`There was an issue finding the port "${a.toString()}" inside of a ${this.componentName} component with name: "${this.props.name}". This is a bug in @tscircuit/core`);return o}})}getInstanceForReactElement(t){for(let a of this.reactSubtrees)if(a.element===t)return a.component;return null}doInitialSourceRender(){let t=this.config.sourceFtype;if(!t)return;let{db:a}=this.root,{_parsedProps:o}=this,l=a.source_component.insert({ftype:t,name:this.name,manufacturer_part_number:o.manufacturerPartNumber??o.mfn,supplier_part_numbers:o.supplierPartNumbers});this.source_component_id=l.source_component_id}doInitialSchematicComponentRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{schematicSymbolName:a}=this.config;a?this._doInitialSchematicComponentRenderWithSymbol():this._getSchematicBoxDimensions()&&this._doInitialSchematicComponentRenderWithSchematicBoxDimensions();let o=this.getSubcircuit()?._getSchematicManualPlacementForComponent(this);if(this.schematic_component_id&&(this.props.schX!==void 0||this.props.schY!==void 0)&&o){if(!this.schematic_component_id)return;let l=SC.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(l)}}_getSchematicSymbolDisplayValue(){}_getInternallyConnectedPins(){if(this.internallyConnectedPinNames.length===0)return[];let t=[];for(let a of this.internallyConnectedPinNames){let o=[];for(let l of a)o.push(this.portMap[l]);t.push(o)}return t}_doInitialSchematicComponentRenderWithSymbol(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:a}=this,o=this._getSchematicSymbolNameOrThrow(),l=Us[o],p=this._getGlobalSchematicPositionBeforeLayout();if(l){let x=t.schematic_component.insert({center:p,size:l.size,source_component_id:this.source_component_id,symbol_name:o,symbol_display_value:this._getSchematicSymbolDisplayValue()});this.schematic_component_id=x.schematic_component_id}}_doInitialSchematicComponentRenderWithSchematicBoxDimensions(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:a}=this,o=this._getSchematicBoxDimensions(),l={};if(Array.isArray(a.pinLabels))a.pinLabels.forEach((P,k)=>{l[String(k+1)]=P});else for(let[P,k]of Object.entries(a.pinLabels??{}))l[P]=Array.isArray(k)?k[0]:k;let p=this._getGlobalSchematicPositionBeforeLayout(),x=this._getSchematicPortArrangement(),m=t.schematic_component.insert({center:p,rotation:a.schRotation??0,size:o.getSize(),port_arrangement:yUt(x),pin_spacing:a.schPinSpacing??.2,pin_styles:hUt(a.schPinStyle,a.pinLabels),port_labels:l,source_component_id:this.source_component_id}),g=x?.topSide!==void 0||x?.bottomSide!==void 0,_=o?.getSize().width,F=o?.getSize().height,C=t.schematic_text.insert({text:a.manufacturerPartNumber??"",schematic_component_id:m.schematic_component_id,anchor:"left",rotation:0,position:{x:g?p.x+(_??0)/2+.1:p.x-(_??0)/2,y:g?p.y+(F??0)/2+.35:p.y-(F??0)/2-.13},color:"#006464",font_size:.18}),S=t.schematic_text.insert({text:a.name??"",schematic_component_id:m.schematic_component_id,anchor:"left",rotation:0,position:{x:g?p.x+(_??0)/2+.1:p.x-(_??0)/2,y:g?p.y+(F??0)/2+.55:p.y+(F??0)/2+.13},color:"#006464",font_size:.18});this.schematic_component_id=m.schematic_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:a}=this,o=this.getSubcircuit(),l=t.pcb_component.insert({center:this._getGlobalPcbPositionBeforeLayout(),width:0,height:0,layer:a.layer??"top",rotation:a.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:o.subcircuit_id??void 0});if(!(a.footprint??this._getImpliedFootprintString())&&!this.isGroup){let m=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=m.pcb_missing_footprint_error_id}this.pcb_component_id=l.pcb_component_id;let x=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if((this.props.pcbX!==void 0||this.props.pcbY!==void 0)&&x){let m=TC.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:o.subcircuit_id??void 0});t.pcb_manual_edit_conflict_warning.insert(m)}}doInitialPcbComponentSizeCalculation(){if(this.root?.pcbDisabled||!this.pcb_component_id)return;let{db:t}=this.root,{_parsedProps:a}=this,o=bR(this.children);if(o.width===0||o.height===0)return;let l={x:(o.minX+o.maxX)/2,y:(o.minY+o.maxY)/2};t.pcb_component.update(this.pcb_component_id,{center:l,width:o.width,height:o.height})}_renderReactSubtree(t){return{element:t,component:D7e(t)}}doInitialInitializePortsFromChildren(){this.initPorts()}doInitialReactSubtreesRender(){}doInitialPcbFootprintStringRender(){let{footprint:t}=this.props;if(t??(t=this._getImpliedFootprintString?.()),!t)return;let{pcbRotation:a,pinLabels:o,pcbPinLabels:l}=this.props;if(typeof t=="string"&&this._isFootprintUrl(t)){if(this._hasStartedFootprintUrlLoad)return;this._hasStartedFootprintUrlLoad=!0;let p=t;this._queueAsyncEffect("load-footprint-url",async()=>{let m=await(await fetch(p)).json(),g=a7e({componentName:this.name,componentRotation:a,footprint:p,pinLabels:o,pcbPinLabels:l},m);this.addAll(g),this._markDirty("InitializePortsFromChildren")});return}if((0,Vg.isValidElement)(t)){if(this.reactSubtrees.some(x=>x.element===t))return;let p=this._renderReactSubtree(t);this.reactSubtrees.push(p),this.add(p.component);return}!(0,Vg.isValidElement)(t)&&t.componentName==="Footprint"&&this.add(t)}_hasExistingPortExactly(t){return this.children.filter(o=>o.componentName==="Port").some(o=>{let l=t.getNameAndAliases(),p=o.getNameAndAliases();return l.length===p.length&&l.every(x=>p.includes(x))})}add(t){let a;if((0,Vg.isValidElement)(t)){let o=this._renderReactSubtree(t);this.reactSubtrees.push(o),a=o.component}else a=t;if(a.componentName==="Port"){if(this._hasExistingPortExactly(a))return;let l=this.children.filter(p=>p.componentName==="Port").find(p=>p.isMatchingAnyOf(a.getNameAndAliases()));l&&aVt(`Similar ports added. Port 1: ${l}, Port 2: ${a}`)}super.add(a)}getPortsFromFootprint(t){let{footprint:a}=this.props;if((!a||(0,Vg.isValidElement)(a))&&(a=this.children.find(l=>l.componentName==="Footprint")),typeof a=="string"){if(this._isFootprintUrl(a))return[];let l=Aq.string(a).soup(),p=[];for(let x of l)if("port_hints"in x&&x.port_hints){let m=n8(x.port_hints,t);if(!m)continue;m.originDescription=`footprint:string:${a}:port_hints[0]:${x.port_hints[0]}`,p.push(m)}return p}if(!(0,Vg.isValidElement)(a)&&a&&a.componentName==="Footprint"){let l=a,p=1,x=[];for(let m of l.children){if(!m.props.portHints)continue;let g=m.props.portHints;g.some(C=>C.startsWith("pin"))||(g=[...g,`pin${p}`]),p++;let F=n8(g);F&&(F.originDescription=`footprint:${a}`,x.push(F))}return x}let o=[];if(!a){for(let l of this.children)if(l.props.portHints&&l.isPcbPrimitive){let p=n8(l.props.portHints);p&&o.push(p)}}return o}getPortsFromSchematicSymbol(){if(this.root?.schematicDisabled)return[];let{config:t}=this;if(!t.schematicSymbolName)return[];let a=Us[t.schematicSymbolName];if(!a)return[];let o=[];for(let l of a.ports){let p=n8(l.labels);p&&(p.schematicSymbolPortDef=l,o.push(p))}return o}doInitialCreateNetsFromProps(){this._createNetsFromProps(this._getNetsFromConnectionsProp())}_getNetsFromConnectionsProp(){let{_parsedProps:t}=this,a=[];if(t.connections)for(let[o,l]of Object.entries(t.connections)){let p=Array.isArray(l)?l:[l];for(let x of p)a.push(x)}return a}_createNetsFromProps(t){RW(this,t)}_getPcbCircuitJsonBounds(){let{db:t}=this.root;if(!this.pcb_component_id)return super._getPcbCircuitJsonBounds();let a=t.pcb_component.get(this.pcb_component_id);return{center:{x:a.center.x,y:a.center.y},bounds:{left:a.center.x-a.width/2,top:a.center.y-a.height/2,right:a.center.x+a.width/2,bottom:a.center.y+a.height/2},width:a.width,height:a.height}}_getPinCountFromSchematicPortArrangement(){let t=this._getSchematicPortArrangement();if(!t)return 0;if(!F7e(t))return(t.leftSize??t.leftPinCount??0)+(t.rightSize??t.rightPinCount??0)+(t.topSize??t.topPinCount??0)+(t.bottomSize??t.bottomPinCount??0);let{leftSide:o,rightSide:l,topSide:p,bottomSide:x}=t;return Math.max(...o?.pins??[],...l?.pins??[],...p?.pins??[],...x?.pins??[])}_getPinCount(){if(this._getSchematicPortArrangement())return this._getPinCountFromSchematicPortArrangement();let a=this.getPortsFromFootprint();if(a.length>0)return a.length;let{pinLabels:o}=this._parsedProps;if(o){if(Array.isArray(o))return o.length;let l=Object.keys(o).map(p=>p.startsWith("pin")?parseInt(p.slice(3)):parseInt(p)).filter(p=>!Number.isNaN(p));return l.length>0?Math.max(...l):Object.keys(o).length}return 0}_getSchematicPortArrangement(){return this._parsedProps.schPinArrangement??this._parsedProps.schPortArrangement}_getSchematicBoxDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;let{_parsedProps:t}=this,a=this._getPinCount(),o=t.schPinSpacing??.2;return IUt({schWidth:t.schWidth,schHeight:t.schHeight,schPinSpacing:o,numericSchPinStyle:SUt(t.schPinStyle,t.pinLabels),pinCount:a,schPortArrangement:this._getSchematicPortArrangement(),pinLabels:t.pinLabels})}doInitialCadModelRender(){let{db:t}=this.root,{boardThickness:a=0}=this.root?._getBoard()??{},o=this._parsedProps.cadModel;if(!this.pcb_component_id||!o&&!this.props.footprint||o===null)return;let l=this._getPcbCircuitJsonBounds(),p=t.pcb_component.get(this.pcb_component_id);if(typeof o=="string")throw new Error("String cadModel not yet implemented");let x=iVt.parse({x:0,y:0,z:typeof o?.rotationOffset=="number"?o.rotationOffset:0,...typeof o?.rotationOffset=="object"?o.rotationOffset??{}:{}}),m=sg.parse({x:0,y:0,z:0,...typeof o?.positionOffset=="object"?o.positionOffset:{}}),g=this.props.layer==="bottom"?"bottom":"top",_=t.cad_component.insert({position:{x:l.center.x+m.x,y:l.center.y+m.y,z:(g==="bottom"?-a/2:a/2)+m.z},rotation:{x:x.x,y:(g==="top"?0:180)+x.y,z:g==="bottom"?-((p?.rotation??0)+x.z)+180:(p?.rotation??0)+x.z},pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,model_stl_url:"stlUrl"in(o??{})?this._addCachebustToModelUrl(o.stlUrl):void 0,model_obj_url:"objUrl"in(o??{})?this._addCachebustToModelUrl(o.objUrl):void 0,model_jscad:"jscad"in(o??{})?o.jscad:void 0,footprinter_string:typeof this.props.footprint=="string"&&!o?this.props.footprint:void 0})}_addCachebustToModelUrl(t){if(!t||!t.includes("modelcdn.tscircuit.com"))return t;let a=this.root?.getClientOrigin()??"";return`${t}${t.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(a)}`}_getPartsEngineCacheKey(t,a){return JSON.stringify({ftype:t.ftype,name:t.name,manufacturer_part_number:t.manufacturer_part_number,footprinterString:a})}async _getSupplierPartNumbers(t,a,o){if(this.props.doNotPlace)return{};let l=this.root?.platform?.localCacheEngine,p=this._getPartsEngineCacheKey(a,o);if(l){let g=await l.getItem(p);if(g)try{return JSON.parse(g)}catch{}}let x=await Promise.resolve(t.findPart({sourceComponent:a,footprinterString:o})),m=x==="Not found"?{}:x;if(l)try{await l.setItem(p,JSON.stringify(m))}catch{}return m}doInitialPartsEngineRender(){if(this.props.doNotPlace)return;let t=this.getInheritedProperty("partsEngine");if(!t)return;let{db:a}=this.root,o=a.source_component.get(this.source_component_id);if(!o||o.supplier_part_numbers)return;let l;this.props.footprint&&typeof this.props.footprint=="string"&&(l=this.props.footprint);let p=this._getSupplierPartNumbers(t,o,l);if(!(p instanceof Promise)){a.source_component.update(this.source_component_id,{supplier_part_numbers:p});return}this._queueAsyncEffect("get-supplier-part-numbers",async()=>{this._asyncSupplierPartNumbers=await p,this._markDirty("PartsEngineRender")})}updatePartsEngineRender(){if(this.props.doNotPlace)return;let{db:t}=this.root,a=t.source_component.get(this.source_component_id);if(a&&!a.supplier_part_numbers&&this._asyncSupplierPartNumbers){t.source_component.update(this.source_component_id,{supplier_part_numbers:this._asyncSupplierPartNumbers});return}}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}_createTracesFromConnectionsProp(){let{_parsedProps:t}=this;if(t.connections)for(let[a,o]of Object.entries(t.connections)){let l=Array.isArray(o)?o:[o];for(let p of l)this.add(new Od({from:`${this.getSubcircuitSelector()} > port.${a}`,to:p}))}}},sVt=class{constructor(n,t={}){J(this,"input");J(this,"isRouting",!1);J(this,"solver");J(this,"eventHandlers",{complete:[],error:[],progress:[]});J(this,"cycleCount",0);J(this,"stepDelay");J(this,"timeoutId");this.input=n;let{capacityDepth:a,targetMinCapacity:o,stepDelay:l=0}=t;this.solver=new ECe(n,{capacityDepth:a,targetMinCapacity:o,cacheProvider:null}),this.stepDelay=l}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 a8(this.solver.error||"Routing failed")}):this.emitEvent({type:"complete",traces:this.solver.getOutputSimpleRouteJson().traces||[]}),this.isRouting=!1;return}let n=Date.now(),t=this.solver.iterations;for(;Date.now()-n<250&&!this.solver.failed&&!this.solver.solved;)this.solver.step();let a=(this.solver.iterations-t)/(Date.now()-n)*1e3;this.cycleCount++;let o=this.solver?.preview()||void 0,l=this.solver.progress;this.emitEvent({type:"progress",steps:this.cycleCount,iterationsPerSecond:a,progress:l,phase:this.solver.getCurrentPhase(),debugGraphics:o}),this.stepDelay>0?this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),this.stepDelay):this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),0)}catch(n){this.emitEvent({type:"error",error:n instanceof Error?new a8(n.message):new a8(String(n))}),this.isRouting=!1}}stop(){this.isRouting&&(this.isRouting=!1,this.timeoutId!==void 0&&(clearTimeout(this.timeoutId),this.timeoutId=void 0))}on(n,t){n==="complete"?this.eventHandlers.complete.push(t):n==="error"?this.eventHandlers.error.push(t):n==="progress"&&this.eventHandlers.progress.push(t)}emitEvent(n){if(n.type==="complete")for(let t of this.eventHandlers.complete)t(n);else if(n.type==="error")for(let t of this.eventHandlers.error)t(n);else if(n.type==="progress")for(let t of this.eventHandlers.progress)t(n)}solveSync(){if(this.solver.solve(),this.solver.failed)throw new a8(this.solver.error||"Routing failed");return this.solver.getOutputSimpleRouteJson().traces||[]}},TW=class extends Ya{constructor(){super(...arguments);J(this,"matchedPort",null)}get config(){return{componentName:"TraceHint",zodProps:D4e}}doInitialPortMatching(){let{db:t}=this.root,{_parsedProps:a,parent:o}=this;if(!o)return;if(o.componentName==="Trace"){this.renderError(`Port inference inside trace is not yet supported (${this})`);return}if(!o)throw new Error("TraceHint has no parent");if(!a.for){this.renderError(`TraceHint has no for property (${this})`);return}let l=o.selectOne(a.for,{type:"port"});l||this.renderError(`${this} could not find port for selector "${a.for}"`),this.matchedPort=l,l.registerMatch(this)}getPcbRouteHints(){let{_parsedProps:t}=this,a=t.offset?[t.offset]:t.offsets;if(!a)return[];let o=this._computePcbGlobalTransformBeforeLayout();return a.map(l=>({...Ss(o,l),via:l.via,to_layer:l.to_layer,trace_width:l.trace_width}))}doInitialPcbTraceHintRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:a}=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()})}},R7e=({circuitJson:n,editEvents:t,manualEditsFile:a})=>{let o={...a,pcb_placements:[...a.pcb_placements??[]]};for(let l of t)if(l.edit_event_type==="edit_pcb_component_location"){let{pcb_component_id:p,new_center:x}=l,m=La(n).pcb_component.get(p);if(!m)continue;let g=La(n).source_component.get(m.source_component_id);if(!g)continue;let _=o.pcb_placements?.findIndex(C=>C.selector===g.name),F={selector:g.name,center:x,relative_to:"group_center"};_>=0?o.pcb_placements[_]=F:o.pcb_placements.push(F)}return o},I7e=({circuitJson:n,editEvents:t,manualEditsFile:a})=>{let o={...a,schematic_placements:[...a.schematic_placements??[]]};for(let l of t)if(l.edit_event_type==="edit_schematic_component_location"){let{schematic_component_id:p,new_center:x}=l,m=La(n).schematic_component.get(p);if(!m)continue;let g=La(n).source_component.get(m.source_component_id);if(!g)continue;let _=o.schematic_placements?.findIndex(C=>C.selector===g.name),F={selector:g.name,center:x,relative_to:"group_center"};_>=0?o.schematic_placements[_]=F:o.schematic_placements.push(F)}return o},oVt=({circuitJson:n,editEvents:t,manualEditsFile:a})=>{let o=t.filter(x=>x.edit_event_type==="edit_schematic_component_location"),l=t.filter(x=>x.edit_event_type==="edit_pcb_component_location"),p=a;return o.length>0&&(p=I7e({circuitJson:n,editEvents:o,manualEditsFile:p})),l.length>0&&(p=R7e({circuitJson:n,editEvents:l,manualEditsFile:p})),p},cVt=(n,t)=>{if(La(n).pcb_trace_hint.get(t.pcb_trace_hint_id))n=n.map(o=>o.pcb_trace_hint_id===t.pcb_trace_hint_id?{...o,route:t.route}:o);else{let o=La(n).pcb_port.get(t.pcb_port_id);n=n.filter(l=>!(l.type==="pcb_trace_hint"&&l.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:o?.pcb_component_id}])}return n},uVt=({circuitJson:n,editEvents:t})=>{n=JSON.parse(JSON.stringify(n));for(let a of t)if(a.edit_event_type==="edit_pcb_component_location"){let o=n.find(p=>p.type==="pcb_component"&&p.pcb_component_id===a.pcb_component_id);if((!o||o.center.x!==a.new_center.x||o.center.y!==a.new_center.y)&&a.original_center){let p=si(a.new_center.x-a.original_center.x,a.new_center.y-a.original_center.y);n=n.map(x=>x.pcb_component_id!==a.pcb_component_id?x:XY(x,p))}}else a.edit_event_type==="edit_schematic_component_location"?n=n.map(o=>o.type==="schematic_component"&&o.schematic_component_id===a.schematic_component_id?{...o,center:a.new_center}:o):a.edit_event_type==="edit_pcb_trace_hint"&&(n=cVt(n,a));return n},w7e=(n,t)=>{let a=n.source_group.list(),o=[],l=p=>{let x=a.filter(m=>m.parent_subcircuit_id===p);for(let m of x)m.subcircuit_id&&(o.push(m.subcircuit_id),l(m.subcircuit_id))};return l(t),o},FW=({db:n,circuitJson:t,subcircuit_id:a,minTraceWidth:o=.1})=>{if(!n&&t&&(n=La(t)),!n)throw new Error("db or circuitJson is required");let l=n.pcb_trace_hint.list(),p=a?new Set([a]):null;if(a){let U=w7e(n,a);for(let me of U)p.add(me)}let x=(t??n.toArray()).filter(U=>!a||"subcircuit_id"in U&&p.has(U.subcircuit_id)),m=n.pcb_board.list()[0];n=La(x);let g=rx(x),_=C7e([...n.pcb_component.list(),...n.pcb_smtpad.list(),...n.pcb_plated_hole.list(),...n.pcb_hole.list(),...n.pcb_via.list()].filter(U=>!a||p?.has(U.subcircuit_id)),g);for(let U of _){let me=U.connectedTo.flatMap(W=>g.getIdsConnectedToNet(W));U.connectedTo.push(...me)}let F=_.flatMap(U=>[{x:U.center.x-U.width/2,y:U.center.y-U.height/2},{x:U.center.x+U.width/2,y:U.center.y+U.height/2}]),C;if(m?C={minX:m.center.x-m.width/2,maxX:m.center.x+m.width/2,minY:m.center.y-m.height/2,maxY:m.center.y+m.height/2}:C={minX:Math.min(...F.map(U=>U.x))-1,maxX:Math.max(...F.map(U=>U.x))+1,minY:Math.min(...F.map(U=>U.y))-1,maxY:Math.max(...F.map(U=>U.y))+1},a){let U=n.pcb_group.getWhere({subcircuit_id:a});if(U){let me={minX:U.center.x-U.width/2,maxX:U.center.x+U.width/2,minY:U.center.y-U.height/2,maxY:U.center.y+U.height/2};C={minX:Math.min(C.minX,me.minX),maxX:Math.max(C.maxX,me.maxX),minY:Math.min(C.minY,me.minY),maxY:Math.max(C.maxY,me.maxY)}}}let S=n.source_trace.list().map(U=>{let me=U.connected_source_port_ids.map(Te=>{let Ke=n.source_port.get(Te),Qe=n.pcb_port.getWhere({source_port_id:Te});return{...Ke,...Qe}});if(me.length<2)return null;let[W,pe]=me,he=W.layers?.[0]??"top",Ae=pe.layers?.[0]??"top",de=l.filter(Te=>Te.pcb_port_id===W.pcb_port_id||Te.pcb_port_id===pe.pcb_port_id),Ne=[];for(let Te of de){let Qe=n.pcb_port.get(Te.pcb_port_id)?.layers?.[0]??"top";for(let pt of Te.route)Ne.push({x:pt.x,y:pt.y,layer:Qe})}return{name:U.source_trace_id??g.getNetConnectedToId(U.source_trace_id)??"",source_trace_id:U.source_trace_id,pointsToConnect:[{x:W.x,y:W.y,layer:he,pointId:W.pcb_port_id,pcb_port_id:W.pcb_port_id},...Ne,{x:pe.x,y:pe.y,layer:Ae,pointId:pe.pcb_port_id,pcb_port_id:pe.pcb_port_id}]}}).filter(U=>U!==null),P=new Map(S.map(U=>[U.source_trace_id,U])),k=n.source_net.list().filter(U=>!a||p?.has(U.subcircuit_id)),q=[];for(let U of k){let me=n.source_trace.list().filter(W=>W.connected_source_net_ids?.includes(U.source_net_id));q.push({name:U.source_net_id??g.getNetConnectedToId(U.source_net_id),pointsToConnect:me.flatMap(W=>n.pcb_port.list().filter(he=>W.connected_source_port_ids.includes(he.source_port_id)).map(he=>({x:he.x,y:he.y,layer:he.layers?.[0]??"top",pointId:he.pcb_port_id,pcb_port_id:he.pcb_port_id})))})}let X=n.pcb_breakout_point.list().filter(U=>!a||p?.has(U.subcircuit_id)),Q=[],ee=new Map;for(let U of X){let me={x:U.x,y:U.y,layer:"top"};if(U.source_trace_id){let W=P.get(U.source_trace_id)??ee.get(U.source_trace_id);if(W)W.pointsToConnect.push(me);else{let pe={name:U.source_trace_id,source_trace_id:U.source_trace_id,pointsToConnect:[me]};Q.push(pe),ee.set(U.source_trace_id,pe)}}else if(U.source_net_id){let W=q.find(pe=>pe.name===U.source_net_id);W?W.pointsToConnect.push(me):Q.push({name:U.source_net_id,pointsToConnect:[me]})}else if(U.source_port_id){let W=n.pcb_port.getWhere({source_port_id:U.source_port_id});W&&Q.push({name:U.source_port_id,source_trace_id:void 0,pointsToConnect:[{x:W.x,y:W.y,layer:W.layers?.[0]??"top",pointId:W.pcb_port_id,pcb_port_id:W.pcb_port_id},me]})}}let ue=[...S,...q,...Q],ce=new Map;for(let U of ue)for(let me of U.pointsToConnect)me.pointId&&ce.set(me.pointId,U);let fe=n.pcb_trace.list().filter(U=>!a||p?.has(U.subcircuit_id));for(let U of fe){let me=new Set;for(let he of U.route)he.start_pcb_port_id&&me.add(he.start_pcb_port_id),he.end_pcb_port_id&&me.add(he.end_pcb_port_id);if(me.size<2)continue;let W=me.values().next().value;if(!W)continue;let pe=ce.get(W);pe&&[...me].every(he=>ce.get(he)===pe)&&(pe.externallyConnectedPointIds??(pe.externallyConnectedPointIds=[]),pe.externallyConnectedPointIds.push([...me]))}return{simpleRouteJson:{bounds:C,obstacles:_,connections:ue,layerCount:m?.num_layers??2,minTraceWidth:o},connMap:g}},lVt=n=>{let t={};if(!n)return t;for(let o of $f)t[o]=0;let a=new Map;for(let o of n){let[,,l,p]=o.type.split(":");if(p==="start"){a.set(`${l}:${o.renderId}`,o);continue}if(p==="end"){let x=a.get(`${l}:${o.renderId}`);if(x){let m=o.createdAt-x.createdAt;t[l]=(t[l]||0)+m}}}return t},dVt=n=>{let t=n.map(g=>[...new Set(g)]),a=t.map(()=>[]),o=t.map(()=>null);for(let g=0;g<t.length;g++)for(let _ of t[g])if(/^\d+$/.test(_)){o[g]=Number.parseInt(_);break}let l=0,p=new Set;for(let g=0;g<o.length;g++){let _=o[g];if(_===null||_<1)continue;if(!p.has(_)){p.add(_),a[g].push(`pin${_}`),l=Math.max(l,_);continue}let F=0;for(let C of a[g])C.startsWith(`pin${_}_alt`)&&F++;a[g].push(`pin${_}_alt${F+1}`)}for(let g=0;g<a.length;g++)a[g][0]?.includes("_alt")&&(l++,a[g].unshift(`pin${l}`));for(let g=0;g<a.length;g++)a[g].length===0&&(l++,a[g].push(`pin${l}`));let x={};for(let g of t)for(let _ of g)/^\d+$/.test(_)||(x[_]=(x[_]??0)+1);let m={};for(let g=0;g<t.length;g++){let _=t[g];for(let F of _)/^\d+$/.test(F)||(x[F]===1?a[g].push(F):(m[F]=(m[F]??0)+1,a[g].push(`${F}${m[F]}`)))}return a},d7e=(0,S7e.default)("Group_doInitialSchematicLayoutMatchAdapt");function pVt(n){let{db:t}=n.root,a=J2(t.toArray(),{source_group_id:n.source_group_id}),o=KY(a);d7e.enabled&&global.debugGraphics?.push(Vm(o,{title:`floatingBpcGraph-${n.name}`}));let l=KY(a),p={boxes:l.boxes,pins:l.pins.map(g=>({...g,color:g.color.replace("not_connected","normal")}))},{result:x}=c5e([{variantName:"default",floatingGraph:l},{variantName:"noNotConnected",floatingGraph:p}],{singletonKeys:["vcc/2","gnd/2"],centerPinColors:["netlabel_center","component_center"],floatingBoxIdsWithMutablePinOffsets:new Set(l.boxes.filter(g=>l.pins.filter(C=>C.boxId===g.boxId).filter(C=>!C.color.includes("center")).length<=2).map(g=>g.boxId)),corpus:PCe});d7e.enabled&&global.debugGraphics?.push(Vm(x,{title:`laidOutBpcGraph-${n.name}`}));let m=n._getGlobalSchematicPositionBeforeLayout();for(let g of x.boxes){if(!g.center)continue;let _=t.schematic_component.get(g.boxId);if(_){let C={x:g.center.x+m.x,y:g.center.y+m.y},S=t.schematic_port.list({schematic_component_id:_.schematic_component_id}),P=t.schematic_text.list({schematic_component_id:_.schematic_component_id}),k={x:C.x-_.center.x,y:C.y-_.center.y};for(let q of S)q.center.x+=k.x,q.center.y+=k.y;for(let q of P)q.position.x+=k.x,q.position.y+=k.y;_.center=C;continue}let F=t.schematic_net_label.get(g.boxId);if(F){let C=x.pins.find(P=>P.boxId===g.boxId&&P.color==="netlabel_center");if(!C)throw new Error(`No pin found for net label: ${g.boxId}`);let S={x:g.center.x+m.x,y:g.center.y+m.y};F.center=S,F.anchor_position={x:S.x+C.offset.x,y:S.y+C.offset.y};continue}console.error(`No schematic element found for box: ${g.boxId}. This is a bug in the matchAdapt binding with @tscircuit/core`)}}function xVt(n){if(!n.isSubcircuit)return;let{db:t}=n.root,a=n.selectAll("trace"),o=new tb({});o.addConnections(a.map(m=>{let g=t.source_trace.get(m.source_trace_id);return g?[g.source_trace_id,...g.connected_source_port_ids,...g.connected_source_net_ids]:null}).filter(m=>m!==null));let{name:l}=n._parsedProps;for(let m of a){if(!m.source_trace_id)continue;let g=o.getNetConnectedToId(m.source_trace_id);g&&(m.subcircuit_connectivity_map_key=`${l??`unnamedsubcircuit${n._renderId}`}_${g}`,t.source_trace.update(m.source_trace_id,{subcircuit_connectivity_map_key:m.subcircuit_connectivity_map_key}))}let p=new Set;for(let m of a){if(!m.source_trace_id)continue;let g=t.source_trace.get(m.source_trace_id);if(g)for(let _ of g.connected_source_port_ids)p.add(_)}for(let m of p){let g=o.getNetConnectedToId(m);if(!g)continue;let _=`${l??`unnamedsubcircuit${n._renderId}`}_${g}`;t.source_port.update(m,{subcircuit_connectivity_map_key:_})}let x=new Set;for(let m of a){if(!m.source_trace_id)continue;let g=t.source_trace.get(m.source_trace_id);if(g)for(let _ of g.connected_source_net_ids)x.add(_)}for(let m of x){let g=o.getNetConnectedToId(m);if(!g)continue;let _=`${l??`unnamedsubcircuit${n._renderId}`}_${g}`;t.source_net.update(m,{subcircuit_connectivity_map_key:_})}}function fVt(n){let{db:t}=n.root,a=n._parsedProps,o=n.children.filter(fe=>fe.schematic_component_id);if(o.length===0)return;let l=0,p=0;for(let fe of o){let U=t.schematic_component.get(fe.schematic_component_id);U?.size&&(l=Math.max(l,U.size.width),p=Math.max(p,U.size.height))}l===0&&o.length>0&&(l=1),p===0&&o.length>0&&(p=1);let x=a.gridCols,m,g=a.gridGap,_=a.gridRowGap,F=a.gridColumnGap;a.schLayout?.grid&&(x=a.schLayout.grid.cols??x,m=a.schLayout.grid.rows,g=a.schLayout.gridGap??g,_=a.schLayout.gridRowGap??_,F=a.schLayout.gridColumnGap??F);let C,S;x!==void 0&&m!==void 0?(C=x,S=m):x!==void 0?(C=x,S=Math.ceil(o.length/C)):m!==void 0?(S=m,C=Math.ceil(o.length/S)):(C=Math.ceil(Math.sqrt(o.length)),S=Math.ceil(o.length/C)),C===0&&o.length>0&&(C=1),S===0&&o.length>0&&(S=o.length);let P,k,q=fe=>{if(fe!==void 0)return typeof fe=="number"?fe:ge.parse(fe)};if(_!==void 0||F!==void 0){let fe=typeof g=="object"&&g!==null?g.x:g,U=typeof g=="object"&&g!==null?g.y:g;P=q(F??fe)??1,k=q(_??U)??1}else if(typeof g=="number")P=g,k=g;else if(typeof g=="string"){let fe=ge.parse(g);P=fe,k=fe}else if(typeof g=="object"&&g!==null){let fe=g.x,U=g.y;P=typeof fe=="number"?fe:ge.parse(fe??"0mm"),k=typeof U=="number"?U:ge.parse(U??"0mm")}else P=1,k=1;let X=C*l+Math.max(0,C-1)*P,Q=S*p+Math.max(0,S-1)*k,ee=n._getGlobalSchematicPositionBeforeLayout(),ue=ee.x-X/2+l/2,ce=ee.y+Q/2-p/2;for(let fe=0;fe<o.length;fe++){let U=o[fe];if(!U.schematic_component_id)continue;let me=Math.floor(fe/C),W=fe%C;if(me>=S||W>=C){console.warn(`Schematic grid layout: Child ${U.getString()} at index ${fe} (row ${me}, col ${W}) exceeds specified grid dimensions (${S}x${C}). Skipping placement.`);continue}let pe=ue+W*(l+P),he=ce-me*(p+k),Ae=t.schematic_component.get(U.schematic_component_id);if(Ae){let de=Ae.center,Ne={x:pe,y:he};t.schematic_component.update(U.schematic_component_id,{center:Ne});let Te=Ne.x-de.x,Ke=Ne.y-de.y,Qe=t.schematic_port.list({schematic_component_id:U.schematic_component_id});for(let jt of Qe)t.schematic_port.update(jt.schematic_port_id,{center:{x:jt.center.x+Te,y:jt.center.y+Ke}});let pt=t.schematic_text.list({schematic_component_id:U.schematic_component_id});for(let jt of pt)t.schematic_text.update(jt.schematic_text_id,{position:{x:jt.position.x+Te,y:jt.position.y+Ke}})}}n.schematic_group_id&&t.schematic_group.update(n.schematic_group_id,{width:X,height:Q,center:ee})}function mVt(n){let{db:t}=n.root,a=n._parsedProps,o=n.children.filter(fe=>fe.pcb_component_id);if(o.length===0)return;let l=0,p=0;for(let fe of o){let U=t.pcb_component.get(fe.pcb_component_id),me=U?.width??0,W=U?.height??0;if(me===0||W===0){let pe=bR(fe.children);me=Math.max(me,pe.width),W=Math.max(W,pe.height)}l=Math.max(l,me),p=Math.max(p,W)}l===0&&o.length>0&&(l=1),p===0&&o.length>0&&(p=1);let x=a.pcbGridCols??a.gridCols,m=a.pcbGridRows,g=a.pcbGridGap??a.gridGap,_=a.pcbGridRowGap??a.gridRowGap,F=a.pcbGridColumnGap??a.gridColumnGap;a.pcbLayout?.grid&&(x=a.pcbLayout.grid.cols??x,m=a.pcbLayout.grid.rows,g=a.pcbLayout.gridGap??g,_=a.pcbLayout.gridRowGap??_,F=a.pcbLayout.gridColumnGap??F);let C,S;x!==void 0&&m!==void 0?(C=x,S=m):x!==void 0?(C=x,S=Math.ceil(o.length/C)):m!==void 0?(S=m,C=Math.ceil(o.length/S)):(C=Math.ceil(Math.sqrt(o.length)),S=Math.ceil(o.length/C)),C===0&&o.length>0&&(C=1),S===0&&o.length>0&&(S=o.length);let P,k,q=fe=>{if(fe!==void 0)return typeof fe=="number"?fe:ge.parse(fe)};if(_!==void 0||F!==void 0){let fe=typeof g=="object"&&g!==null?g.x:g,U=typeof g=="object"&&g!==null?g.y:g;P=q(F??fe)??1,k=q(_??U)??1}else if(typeof g=="number")P=g,k=g;else if(typeof g=="string"){let fe=ge.parse(g);P=fe,k=fe}else if(typeof g=="object"&&g!==null){let fe=g.x,U=g.y;P=typeof fe=="number"?fe:ge.parse(fe??"0mm"),k=typeof U=="number"?U:ge.parse(U??"0mm")}else P=1,k=1;let X=C*l+Math.max(0,C-1)*P,Q=S*p+Math.max(0,S-1)*k,ee=n._getGlobalPcbPositionBeforeLayout(),ue=ee.x-X/2+l/2,ce=ee.y+Q/2-p/2;for(let fe=0;fe<o.length;fe++){let U=o[fe];if(!U.pcb_component_id)continue;let me=Math.floor(fe/C),W=fe%C;if(me>=S||W>=C){console.warn(`PCB grid layout: Child ${U.getString()} at index ${fe} (row ${me}, col ${W}) exceeds grid dimensions (${S}x${C}). Skipping placement.`);continue}let pe=ue+W*(l+P),he=ce-me*(p+k),Ae=t.pcb_component.get(U.pcb_component_id);if(Ae){let de=Ae.center,Ne={x:pe,y:he},Te=Ne.x-de.x,Ke=Ne.y-de.y,Qe=si(Te,Ke),pt=t.toArray().filter(vt=>vt.pcb_component_id===U.pcb_component_id),jt=Sg(pt,Qe);for(let vt of jt){let xt=Z2(vt);t[vt.type].update(vt[xt],vt)}t.pcb_component.update(U.pcb_component_id,{center:Ne}),U.setProps({...U.props,pcbX:(U.props.pcbX??0)+Te,pcbY:(U.props.pcbY??0)+Ke})}}n.pcb_group_id&&t.pcb_group.update(n.pcb_group_id,{width:a.width??X,height:a.height??Q,center:ee})}function hVt(n){let t={serverUrl:"https://registry-api.tscircuit.com",serverMode:"job",serverCacheEnabled:!0};if(typeof n=="object"&&!n.preset)return{local:!(n.serverUrl||n.serverMode||n.serverCacheEnabled),...t,...n};switch(typeof n=="object"?n.preset: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":return{local:!1,groupMode:"subcircuit",serverUrl:t.serverUrl,serverMode:t.serverMode,serverCacheEnabled:!0};default:return{local:!0,groupMode:"subcircuit"}}}var yVt=(0,B7e.default)("Group_doInitialPcbLayoutPack"),gVt=n=>{let{db:t}=n.root,{_parsedProps:a}=n,{packOrderStrategy:o,packPlacementStrategy:l,gap:p,pcbGap:x,pcbPackGap:m}=a,g=m??x??p,_=ge.parse(g??"0mm"),F={...lAe(uAe(t.toArray(),{source_group_id:n.source_group_id})),orderStrategy:o??"largest_to_smallest",placementStrategy:l??"shortest_connection_along_outline",minGap:_},C=oAe(F);if(yVt.enabled){let S=rW(C);S.title=`packOutput-${n.name}`,global.debugGraphics?.push(S)}for(let S of C.components){let{center:P,componentId:k,ccwRotationOffset:q}=S,X=t.pcb_component.get(k);if(X){let fe=X.center,U=qs(n._computePcbGlobalTransformBeforeLayout(),si(P.x,P.y),fg(q||0),si(-fe.x,-fe.y)),me=t.toArray().filter(W=>"pcb_component_id"in W&&W.pcb_component_id===k);Sg(me,U);continue}let Q=t.pcb_group.list().find(fe=>fe.source_group_id===k);if(!Q)continue;let ee=Q.center,ue=qs(n._computePcbGlobalTransformBeforeLayout(),si(P.x,P.y),fg(q||0),si(-ee.x,-ee.y)),ce=J2(t.toArray(),{source_group_id:k});Sg(ce,ue),t.pcb_group.update(Q.pcb_group_id,{center:P})}},p7e=(n,t)=>{let{sourceComponent:a,sourceGroup:o}=t;if(t.nodeType==="component"){let l=n.pcb_component.getWhere({source_component_id:a?.source_component_id});return l?{width:l.width,height:l.height}:null}if(t.nodeType==="group"){let l=n.pcb_group.getWhere({source_group_id:o?.source_group_id});return l?{width:l.width,height:l.height}:null}return null},DVt=n=>{let{db:t}=n.root,{_parsedProps:a}=n,o=Fb(t.toArray(),{source_group_id:n.source_group_id}),l=a.pcbJustifyContent??a.justifyContent,p=a.pcbAlignItems??a.alignItems,x=a.pcbFlexGap??a.pcbGap??a.gap,m=a.pcbFlexDirection??"row",g={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"}[l??"space-between"],_={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"stretch",center:"center"}[p??"center"];if(!g)throw new Error(`Invalid justifyContent value: "${l}"`);if(!_)throw new Error(`Invalid alignItems value: "${p}"`);let F=0,C=0;typeof x=="object"?(F=x.y??0,C=x.x??0):typeof x=="number"?(F=x,C=x):typeof x=="string"&&(F=ge.parse(x),C=ge.parse(x));let S,P=a.width??a.pcbWidth??void 0,k=a.height??a.pcbHeight??void 0;(P===void 0||k===void 0)&&(S=pAe(o.childNodes.map(ce=>p7e(t,ce)).filter(ce=>ce!==null),{alignItems:_,justifyContent:g,direction:m,rowGap:F,columnGap:C}),P=S.width,k=S.height);let X=new hAe(P,k,{alignItems:_,justifyContent:g,direction:m,rowGap:F,columnGap:C});for(let ce of o.childNodes){let fe=p7e(t,ce);X.addChild({metadata:ce,width:fe?.width??0,height:fe?.height??0,flexBasis:fe?m==="row"?fe.width:fe.height:void 0})}X.build();let Q=t.toArray(),ee={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let ce of X.children)ee.minX=Math.min(ee.minX,ce.position.x),ee.minY=Math.min(ee.minY,ce.position.y),ee.maxX=Math.max(ee.maxX,ce.position.x+ce.size.width),ee.maxY=Math.max(ee.maxY,ce.position.y+ce.size.height);ee.width=ee.maxX-ee.minX,ee.height=ee.maxY-ee.minY;let ue={x:-(ee.maxX+ee.minX)/2,y:-(ee.maxY+ee.minY)/2};for(let ce of X.children){let{sourceComponent:fe,sourceGroup:U}=ce.metadata;if(fe){let me=t.pcb_component.getWhere({source_component_id:fe.source_component_id});if(!me)continue;WY(Q,me.pcb_component_id,{x:ce.position.x+ce.size.width/2+ue.x,y:ce.position.y+ce.size.height/2+ue.y})}if(U){if(!t.pcb_group.getWhere({source_group_id:U.source_group_id}))continue;TCe(Q,U.source_group_id,{x:ce.position.x+ce.size.width/2+ue.x,y:ce.position.y+ce.size.height/2+ue.y})}}t.pcb_group.update(n.pcb_group_id,{width:ee.width,height:ee.height})},F_=class extends es{constructor(){super(...arguments);J(this,"pcb_group_id",null);J(this,"schematic_group_id",null);J(this,"subcircuit_id",null);J(this,"_hasStartedAsyncAutorouting",!1);J(this,"_asyncAutoroutingResult",null);J(this,"unnamedElementCounter",{})}get config(){return{zodProps:REe,componentName:"Group"}}doInitialSourceGroupRender(){let{db:t}=this.root,a=t.source_group.insert({name:this.name,is_subcircuit:this.isSubcircuit});this.source_group_id=a.source_group_id,this.isSubcircuit&&(this.subcircuit_id=`subcircuit_${a.source_group_id}`,t.source_group.update(a.source_group_id,{subcircuit_id:this.subcircuit_id}))}doInitialSourceRender(){let{db:t}=this.root;for(let a of this.children)t.source_component.update(a.source_component_id,{source_group_id:this.source_group_id})}doInitialSourceParentAttachment(){let{db:t}=this.root,a=this.parent?.getGroup?.();if(a?.source_group_id&&t.source_group.update(this.source_group_id,{parent_source_group_id:a.source_group_id}),!this.isSubcircuit)return;let o=this.parent?.getSubcircuit?.()?.subcircuit_id;o&&t.source_group.update(this.source_group_id,{parent_subcircuit_id:o})}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:a}=this,o=t.pcb_group.insert({is_subcircuit:this.isSubcircuit,subcircuit_id:this.subcircuit_id??this.getSubcircuit()?.subcircuit_id,name:this.name,center:this._getGlobalPcbPositionBeforeLayout(),width:0,height:0,pcb_component_ids:[],source_group_id:this.source_group_id,autorouter_configuration:a.autorouter?{trace_clearance:a.autorouter.traceClearance}:void 0});this.pcb_group_id=o.pcb_group_id;for(let l of this.children)t.pcb_component.update(l.pcb_component_id,{pcb_group_id:o.pcb_group_id})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,a=this._parsedProps,o=bR(this.children);if(this.pcb_group_id){let l=o.width,p=o.height,x=(o.minX+o.maxX)/2,m=(o.minY+o.maxY)/2;if(this.isSubcircuit){let{padLeft:g,padRight:_,padTop:F,padBottom:C}=this._resolvePcbPadding();l+=g+_,p+=F+C,x+=(_-g)/2,m+=(F-C)/2}t.pcb_group.update(this.pcb_group_id,{width:Number(a.width??l),height:Number(a.height??p),center:{x,y:m}})}}getNextAvailableName(t){var a,o;return(a=this.unnamedElementCounter)[o=t.lowercaseComponentName]??(a[o]=1),`unnamed_${t.lowercaseComponentName}${this.unnamedElementCounter[t.lowercaseComponentName]++}`}_resolvePcbPadding(){let t=this._parsedProps,a=t.pcbLayout,o=C=>{let S=a?.[C],P=t[C];if(typeof S=="number")return S;if(typeof P=="number")return P},l=o("padding")??0,p=o("paddingX"),x=o("paddingY"),m=o("paddingLeft")??p??l,g=o("paddingRight")??p??l,_=o("paddingTop")??x??l,F=o("paddingBottom")??x??l;return{padLeft:m,padRight:g,padTop:_,padBottom:F}}doInitialCreateTraceHintsFromProps(){let{_parsedProps:t}=this,{db:a}=this.root,o=t;if(!this.isSubcircuit)return;let l=o.manualEdits?.manual_trace_hints;if(l)for(let p of l)this.add(new TW({for:p.pcb_port_selector,offsets:p.offsets}))}doInitialSourceAddConnectivityMapKey(){xVt(this)}_areChildSubcircuitsRouted(){let t=this.selectAll("group").filter(a=>a.isSubcircuit);for(let a of t)if(a._shouldRouteAsync()&&!a._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,__.default)("tscircuit:core:_hasTracesToRoute"),a=this.selectAll("trace");return t(`[${this.getString()}] has ${a.length} traces to route`),a.length>0}async _runEffectMakeHttpAutoroutingRequest(){let{db:t}=this.root,a=(0,__.default)("tscircuit:core:_runEffectMakeHttpAutoroutingRequest"),o=this._parsedProps,l=this._getAutorouterConfig(),p=l.serverUrl,x=l.serverMode,m=(F,C)=>(a("fetching",F),C.headers&&(C.headers["Tscircuit-Core-Version"]=this.root?.getCoreVersion()),fetch(F,C)),g=this.root.db.toArray().filter(F=>F.type.startsWith("source_")||F.type.startsWith("pcb_"));if(x==="solve-endpoint"){if(this.props.autorouter?.inputFormat==="simplified"){let{autorouting_result:C}=await m(`${p}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_simple_route_json:FW({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(S=>S.json());this._asyncAutoroutingResult=C,this._markDirty("PcbTraceRender");return}let{autorouting_result:F}=await m(`${p}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_circuit_json:g,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(C=>C.json());this._asyncAutoroutingResult=F,this._markDirty("PcbTraceRender");return}let{autorouting_job:_}=await m(`${p}/autorouting/jobs/create`,{method:"POST",body:JSON.stringify({input_circuit_json:g,provider:"freerouting",autostart:!0,display_name:this.root?.name,subcircuit_id:this.subcircuit_id,server_cache_enabled:l.serverCacheEnabled}),headers:{"Content-Type":"application/json"}}).then(F=>F.json());for(;;){let{autorouting_job:F}=await m(`${p}/autorouting/jobs/get`,{method:"POST",body:JSON.stringify({autorouting_job_id:_.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(C=>C.json());if(F.is_finished){let{autorouting_job_output:C}=await m(`${p}/autorouting/jobs/get_output`,{method:"POST",body:JSON.stringify({autorouting_job_id:_.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(S=>S.json());this._asyncAutoroutingResult={output_pcb_traces:C.output_pcb_traces},this._markDirty("PcbTraceRender");break}if(F.has_error){let C=new a8(`Autorouting job failed: ${JSON.stringify(F.error)}`);throw t.pcb_autorouting_error.insert({pcb_error_id:_.autorouting_job_id,error_type:"pcb_autorouting_error",message:C.message}),C}await new Promise(C=>setTimeout(C,100))}}async _runLocalAutorouting(){let{db:t}=this.root,a=this._parsedProps,o=(0,__.default)("tscircuit:core:_runLocalAutorouting");o(`[${this.getString()}] starting local autorouting`);let l=this._getAutorouterConfig(),{simpleRouteJson:p}=FW({db:t,minTraceWidth:this.props.autorouter?.minTraceWidth??.15,subcircuit_id:this.subcircuit_id});if(o.enabled){let g=UY(p);g.title=`autorouting-${this.props.name}`,global.debugGraphics?.push(g)}this.root?.emit("autorouting:start",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),simpleRouteJson:p});let x;l.algorithmFn?x=await l.algorithmFn(p):x=new sVt(p,{capacityDepth:this.props.autorouter?.capacityDepth,targetMinCapacity:this.props.autorouter?.targetMinCapacity});let m=new Promise((g,_)=>{x.on("complete",F=>{o(`[${this.getString()}] local autorouting complete`),g(F.traces)}),x.on("error",F=>{o(`[${this.getString()}] local autorouting error: ${F.error.message}`),_(F.error)})});x.on("progress",g=>{this.root?.emit("autorouting:progress",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),...g})}),x.start();try{let g=await m;this._asyncAutoroutingResult={output_pcb_traces:g},this._markDirty("PcbTraceRender")}catch(g){let{db:_}=this.root;throw _.pcb_autorouting_error.insert({pcb_error_id:`pcb_autorouter_error_subcircuit_${this.subcircuit_id}`,error_type:"pcb_autorouting_error",message:g instanceof Error?g.message:String(g)}),this.root?.emit("autorouting:error",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),error:{message:g instanceof Error?g.message:String(g)},simpleRouteJson:p}),g}finally{x.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,__.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()}}updatePcbTraceRender(){let t=(0,__.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:a}=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:a}=this._asyncAutoroutingResult.output_simple_route_json;if(a)for(let o of a){let l=t.pcb_trace.insert({subcircuit_id:this.subcircuit_id,route:o.route})}}_updatePcbTraceRenderFromPcbTraces(){let{output_pcb_traces:t}=this._asyncAutoroutingResult;if(!t)return;let{db:a}=this.root;for(let o of t)if(o.type==="pcb_trace"){if(o.subcircuit_id=this.subcircuit_id,o.connection_name){let l=o.connection_name;o.source_trace_id=l}a.pcb_trace.insert(o)}for(let o of t)if(o.type!=="pcb_via"&&o.type==="pcb_trace")for(let l of o.route)l.route_type==="via"&&a.pcb_via.insert({pcb_trace_id:o.pcb_trace_id,x:l.x,y:l.y,hole_diameter:.3,outer_diameter:.6,layers:[l.from_layer,l.to_layer],from_layer:l.from_layer,to_layer:l.to_layer})}doInitialSchematicComponentRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:a}=this,o=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=o.schematic_group_id;for(let l of this.children)l.schematic_component_id&&t.schematic_component.update(l.schematic_component_id,{schematic_group_id:o.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.matchAdapt)return"match-adapt";if(t.flex)return"flex";if(t.grid)return"grid";if(t.relative||t.schRelative)return"relative";let a=this.children.some(p=>{let x=p._parsedProps;return x?.schX!==void 0||x?.schY!==void 0}),o=this.children.some(p=>p.isGroup),l=(t.manualEdits?.schematic_placements?.length??0)>0;return!a&&!l&&!o?"match-adapt":"relative"}doInitialSchematicLayout(){let t=this._parsedProps,a=this._getSchematicLayoutMode();a==="match-adapt"&&this._doInitialSchematicLayoutMatchAdapt(),a==="grid"&&this._doInitialSchematicLayoutGrid(),this._insertSchematicBorder()}_doInitialSchematicLayoutMatchAdapt(){pVt(this)}_doInitialSchematicLayoutGrid(){fVt(this)}_getPcbLayoutMode(){let t=this._parsedProps;return t.pcbLayout?.matchAdapt?"match-adapt":t.pcbLayout?.flex?"flex":t.pcbLayout?.grid?"grid":t.pcbLayout?.pack?"pack":t.pcbFlex?"flex":t.pcbGrid?"grid":t.pcbPack||t.pack?"pack":t.matchAdapt?"match-adapt":t.flex?"flex":t.grid?"grid":"none"}doInitialPcbLayout(){let t=this._getPcbLayoutMode();t==="grid"?this._doInitialPcbLayoutGrid():t==="pack"?this._doInitialPcbLayoutPack():t==="flex"&&this._doInitialPcbLayoutFlex()}_doInitialPcbLayoutGrid(){mVt(this)}_doInitialPcbLayoutPack(){gVt(this)}_doInitialPcbLayoutFlex(){DVt(this)}_insertSchematicBorder(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,a=this._parsedProps;if(!a.border)return;let o=typeof a.schWidth=="number"?a.schWidth:void 0,l=typeof a.schHeight=="number"?a.schHeight:void 0,p=typeof a.schPadding=="number"?a.schPadding:0,x=typeof a.schPaddingLeft=="number"?a.schPaddingLeft:p,m=typeof a.schPaddingRight=="number"?a.schPaddingRight:p,g=typeof a.schPaddingTop=="number"?a.schPaddingTop:p,_=typeof a.schPaddingBottom=="number"?a.schPaddingBottom:p,F=this.schematic_group_id?t.schematic_group.get(this.schematic_group_id):null;if(F&&(o===void 0&&typeof F.width=="number"&&(o=F.width),l===void 0&&typeof F.height=="number"&&(l=F.height)),o===void 0||l===void 0)return;let C=F?.center??this._getGlobalSchematicPositionBeforeLayout(),S=C.x-o/2-x,P=C.y-l/2-_,k=o+x+m,q=l+g+_;t.schematic_box.insert({width:k,height:q,x:S,y:P,is_dashed:a.border?.dashed??!1})}_determineSideFromPosition(t,a){if(!t.center||!a.center)return"left";let o=t.center.x-a.center.x,l=t.center.y-a.center.y;return Math.abs(o)>Math.abs(l)?o>0?"right":"left":l>0?"bottom":"top"}_calculateSchematicBounds(t){if(t.length===0)return{minX:0,maxX:0,minY:0,maxY:0};let a=1/0,o=-1/0,l=1/0,p=-1/0;for(let m of t)a=Math.min(a,m.centerX),o=Math.max(o,m.centerX),l=Math.min(l,m.centerY),p=Math.max(p,m.centerY);let x=2;return{minX:a-x,maxX:o+x,minY:l-x,maxY:p+x}}_getAutorouterConfig(){let t=this._parsedProps.autorouter||this.getInheritedProperty("autorouter");return hVt(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 a=new Map;for(let o of this.children)if(!o.isSubcircuit&&o._parsedProps.name){let l=a.get(o._parsedProps.name)||[];l.push(o),a.set(o._parsedProps.name,l)}for(let[o,l]of a.entries())l.length>1&&t.pcb_trace_error.insert({error_type:"pcb_trace_error",message:`Multiple components found with name "${o}" in subcircuit "${this.name||"unnamed"}". Component names must be unique within a subcircuit.`,source_trace_id:"",pcb_trace_id:"",pcb_component_ids:l.map(p=>p.pcb_component_id).filter(Boolean),pcb_port_ids:[]})}}doInitialSchematicReplaceNetLabelsWithSymbols(){if(this.root?.schematicDisabled||!this.isSubcircuit)return;let{db:t}=this.root,a=t;for(let o of a.schematic_net_label.list()){let l=a.source_net.get(o.source_net_id),p=o.text||l?.name||"";if(o.anchor_side==="top"&&/^gnd/i.test(p)){a.schematic_net_label.update(o.schematic_net_label_id,{symbol_name:"ground_down"});continue}o.anchor_side==="bottom"&&/^v/i.test(p)&&a.schematic_net_label.update(o.schematic_net_label_id,{symbol_name:"vcc_up"})}}},T7e=class extends F_{constructor(){super(...arguments);J(this,"pcb_board_id",null);J(this,"_drcChecksComplete",!1);J(this,"_connectedSchematicPortPairs",new Set)}get isSubcircuit(){return!0}get isGroup(){return!0}get config(){return{componentName:"Board",zodProps:pY}}get boardThickness(){let{_parsedProps:t}=this;return 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:a}=this;if(a.width&&a.height)return;let o=1/0,l=1/0,p=-1/0,x=-1/0,m=w7e(t,this.subcircuit_id),g=new Set([this.subcircuit_id,...m]),_=t.pcb_component.list().filter(ue=>ue.subcircuit_id&&g.has(ue.subcircuit_id)),F=t.pcb_group.list().filter(ue=>ue.subcircuit_id&&g.has(ue.subcircuit_id)),C=!1,S=(ue,ce,fe)=>{ce===0||fe===0||(C=!0,o=Math.min(o,ue.x-ce/2),l=Math.min(l,ue.y-fe/2),p=Math.max(p,ue.x+ce/2),x=Math.max(x,ue.y+fe/2))};for(let ue of _)S(ue.center,ue.width,ue.height);for(let ue of F)S(ue.center,ue.width,ue.height);let P=2,k=C?p-o+P*2:0,q=C?x-l+P*2:0,X={x:C?(o+p)/2+(a.outlineOffsetX??0):a.outlineOffsetX??0,y:C?(l+x)/2+(a.outlineOffsetY??0):a.outlineOffsetY??0},Q=a.width??k,ee=a.height??q;t.pcb_board.update(this.pcb_board_id,{width:Q,height:ee,center:X})}_addBoardInformationToSilkscreen(){let t=this.root?.platform;if(!t?.printBoardInformationToSilkscreen)return;let a=this.root.db.pcb_board.get(this.pcb_board_id);if(!a)return;let o=[];if(t.projectName&&o.push(t.projectName),t.version&&o.push(`v${t.version}`),t.url&&o.push(t.url),o.length===0)return;let l=o.join(`
1036
- `),m={x:a.center.x+a.width/2-.25,y:a.center.y-a.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:l,ccw_rotation:0,anchor_alignment:"bottom_right",anchor_position:m})}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:a}=this,o=a.width??0,l=a.height??0,p={x:(a.pcbX??0)+(a.outlineOffsetX??0),y:(a.pcbY??0)+(a.outlineOffsetY??0)};if(a.outline){let m=a.outline.map(P=>P.x),g=a.outline.map(P=>P.y),_=Math.min(...m),F=Math.max(...m),C=Math.min(...g),S=Math.max(...g);o=F-_,l=S-C,p={x:(_+F)/2+(a.outlineOffsetX??0),y:(C+S)/2+(a.outlineOffsetY??0)}}let x=t.pcb_board.insert({center:p,thickness:this.boardThickness,num_layers:this.allLayers.length,width:o,height:l,outline:a.outline?.map(m=>({x:m.x+(a.outlineOffsetX??0),y:m.y+(a.outlineOffsetY??0)})),material:a.material});this.pcb_board_id=x.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 gc()}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 a=gAe(t.toArray());for(let o of a)t.pcb_trace_error.insert(o)}_emitRenderLifecycleEvent(t,a){super._emitRenderLifecycleEvent(t,a),a==="start"&&this.root?.emit("board:renderPhaseStarted",{renderId:this._renderId,phase:t})}},_Vt=new Proxy({},{get:(n,t)=>t}),qf=_Vt,P7e=class extends es{get config(){return{componentName:"Capacitor",schematicSymbolName:this.props.polarized?"capacitor_polarized":this.props.symbolName??"capacitor",zodProps:NEe,sourceFtype:qf.simple_capacitor}}_getSchematicSymbolDisplayValue(){let n=`${o0(this._parsedProps.capacitance)}F`;return this._parsedProps.schShowRatings&&this._parsedProps.maxVoltageRating?`${n}/${o0(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 Od({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.decouplingFor})),this.add(new Od({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.decouplingTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:t}=this,a=n.source_component.insert({ftype:"simple_capacitor",name:this.name,manufacturer_part_number:t.manufacturerPartNumber??t.mfn,supplier_part_numbers:t.supplierPartNumbers,capacitance:t.capacitance,max_voltage_rating:t.maxVoltageRating,max_decoupling_trace_length:t.maxDecouplingTraceLength,display_capacitance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!t.polarized});this.source_component_id=a.source_component_id}},PW=class extends es{constructor(){super(...arguments);J(this,"schematicBoxDimensions",null)}get config(){return{componentName:"Chip",zodProps:xY,shouldRenderAsSchematicBox:!0}}initPorts(t={}){super.initPorts(t);let{_parsedProps:a}=this;if(a.externallyConnectedPins){let o=new Set;for(let[l,p]of a.externallyConnectedPins)o.add(l),o.add(p);for(let l of o)if(!this.children.find(x=>x instanceof cu&&x.isMatchingAnyOf([l]))){let x=l.match(/^pin(\d+)$/);if(x){let m=parseInt(x[1]);this.add(new cu({pinNumber:m,aliases:[l]}))}else this.add(new cu({name:l,aliases:[l]}))}}}doInitialSchematicComponentRender(){let{_parsedProps:t}=this;t?.noSchematicRepresentation!==!0&&super.doInitialSchematicComponentRender()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:a}=this,o=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:a.manufacturerPartNumber,supplier_part_numbers:a.supplierPartNumbers});this.source_component_id=o.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:a}=this,o=t.pcb_component.insert({center:{x:a.pcbX??0,y:a.pcbY??0},width:2,height:3,layer:a.layer??"top",rotation:a.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.pcb_component_id=o.pcb_component_id}doInitialCreateTracesFromProps(){let{_parsedProps:t}=this;if(t.externallyConnectedPins)for(let[a,o]of t.externallyConnectedPins)this.add(new Od({from:`${this.getSubcircuitSelector()} > port.${a}`,to:`${this.getSubcircuitSelector()} > port.${o}`}));this._createTracesFromConnectionsProp()}doInitialSimulationRender(){let{db:t}=this.root,{pinAttributes:a}=this.props;if(!a)return;let o=null,l=null,p,x=this.selectAll("port");for(let C of x)for(let S of C.getNameAndAliases())if(a[S]){let P=a[S];P.providesPower&&(o=C,p=P.providesVoltage),P.providesGround&&(l=C)}if(!o||!l||p===void 0)return;let m=t.source_port.get(o.source_port_id);if(!m?.subcircuit_connectivity_map_key)return;let g=t.source_port.get(l.source_port_id);if(!g?.subcircuit_connectivity_map_key)return;let _=t.source_net.getWhere({subcircuit_connectivity_map_key:m.subcircuit_connectivity_map_key}),F=t.source_net.getWhere({subcircuit_connectivity_map_key:g.subcircuit_connectivity_map_key});!_||!F||t.simulation_voltage_source.insert({type:"simulation_voltage_source",positive_source_port_id:o.source_port_id,positive_source_net_id:_.source_net_id,negative_source_port_id:l.source_port_id,negative_source_net_id:F.source_net_id,voltage:p})}},k7e=class extends es{constructor(){super(...arguments);J(this,"pos",this.portMap.pin1);J(this,"anode",this.portMap.pin1);J(this,"neg",this.portMap.pin2);J(this,"cathode",this.portMap.pin2)}get config(){let t={schottky:"schottky_diode",avalanche:"avalanche_diode",zener:"zener_diode",photodiode:"photodiode"},a=this.props.schottky?"schottky":this.props.avalanche?"avalanche":this.props.zener?"zener":this.props.photo?"photodiode":null;return{schematicSymbolName:a?t[a]:this.props.symbolName??"diode",componentName:"Diode",zodProps:JEe,sourceFtype:"simple_diode"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:a}=this,o=t.source_component.insert({ftype:"simple_diode",name:this.name,manufacturer_part_number:a.manufacturerPartNumber??a.mfn,supplier_part_numbers:a.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=o.source_component_id}},j7e=class extends es{get config(){return{componentName:"fuse",schematicSymbolName:this.props.symbolName??"fuse",zodProps:wEe,sourceFtype:qf.simple_fuse}}_getSchematicSymbolDisplayValue(){let n=this._parsedProps.currentRating,t=this._parsedProps.voltageRating,a=typeof n=="string"?parseFloat(n):n,o=typeof t=="string"?parseFloat(t):t;return`${o0(a)}A / ${o0(o)}V`}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:t}=this,a=typeof t.currentRating=="string"?parseFloat(t.currentRating):t.currentRating,o=typeof t.voltageRating=="string"?parseFloat(t.voltageRating):t.voltageRating,l=n.source_component.insert({name:this.name,ftype:qf.simple_fuse,current_rating_amps:a,voltage_rating_volts:o,display_current_rating:`${o0(a)}A`,display_voltage_rating:`${o0(o)}V`});this.source_component_id=l.source_component_id}},N7e=class extends es{constructor(){super(...arguments);J(this,"schematicDimensions",null)}get config(){return{schematicSymbolName:void 0,componentName:"Jumper",zodProps:mY,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let t=super._getSchematicPortArrangement();if(t&&Object.keys(t).length>0)return t;let a=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length),o=this._parsedProps.schDirection??"right";return{leftSize:o==="left"?a:0,rightSize:o==="right"?a:0}}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:a}=this,o=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:a.manufacturerPartNumber,supplier_part_numbers:a.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=o.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:a}=this,o=t.pcb_component.insert({center:{x:a.pcbX??0,y:a.pcbY??0},width:2,height:3,layer:a.layer??"top",rotation:a.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.pcb_component_id=o.pcb_component_id}doInitialPcbTraceRender(){let{db:t}=this.root,a=t.pcb_port.list({pcb_component_id:this.pcb_component_id}),o={};for(let x=0;x<a.length;x++){let m=a[x],g=t.source_port.get(m.source_port_id),_="";if(typeof g?.pin_number=="number")_=g.pin_number.toString();else if(Array.isArray(g?.port_hints)){let F=g.port_hints.find(C=>/^(pin)?\d+$/.test(C));F&&(/^pin\d+$/.test(F)?_=F.replace(/^pin/,""):_=F)}o[_]=m.pcb_port_id}let l=t.pcb_trace.list({pcb_component_id:this.pcb_component_id}),p=x=>{if(x&&typeof x=="string"&&x.startsWith("{PIN")){let m=x.replace("{PIN","").replace("}","");return o[m]||x}return x};for(let x of l)if(x.route)for(let m of x.route)m.route_type==="wire"&&(m.start_pcb_port_id=p(m.start_pcb_port_id),m.end_pcb_port_id=p(m.end_pcb_port_id))}},M7e=class extends es{constructor(){super(...arguments);J(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(a=>a.componentName==="Port").map(a=>a.name);return t.length>0?[t]:[]}return this._parsedProps.bridgedPins??[]}get config(){let t=this._parsedProps??this.props,a=t.pinCount;if(t.pinCount==null&&!t.footprint&&(a=2),t.pinCount==null){let p=(t.bridgedPins??[]).flat().map(_=>this._getPinNumberFromBridgedPinName(_)).filter(_=>_!==null),x=p.length>0?Math.max(...p):0,m=t.pinLabels?Object.keys(t.pinLabels).length:0,g=Math.max(x,m);(g===2||g===3)&&(a=g),a==null&&t.footprint&&[2,3].includes(this.getPortsFromFootprint().length)&&(a=this.getPortsFromFootprint().length)}let o="";a?o+=`solderjumper${a}`:o="solderjumper";let l=[];return Array.isArray(t.bridgedPins)&&t.bridgedPins.length>0?l=Array.from(new Set(t.bridgedPins.flat().map(p=>this._getPinNumberFromBridgedPinName(p)).filter(p=>p!==null))).sort((p,x)=>p-x):t.bridged&&a&&(l=Array.from({length:a},(p,x)=>x+1)),l.length>0&&(o+=`_bridged${l.join("")}`),{schematicSymbolName:t.symbolName??o,componentName:"SolderJumper",zodProps:IEe,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let t=super._getSchematicPortArrangement();if(t&&Object.keys(t).length>0)return t;let a=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length);a==null&&!this._parsedProps.footprint&&(a=2);let o=this._parsedProps.schDirection??"right";return{leftSize:o==="left"?a:0,rightSize:o==="right"?a:0}}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:a}=this,o=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:a.manufacturerPartNumber,supplier_part_numbers:a.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=o.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:a}=this,o=t.pcb_component.insert({center:{x:a.pcbX??0,y:a.pcbY??0},width:2,height:3,layer:a.layer??"top",rotation:a.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.pcb_component_id=o.pcb_component_id}doInitialPcbTraceRender(){let{db:t}=this.root,a=t.pcb_port.list({pcb_component_id:this.pcb_component_id}),o={};for(let x=0;x<a.length;x++){let m=a[x],g=t.source_port.get(m.source_port_id),_="";if(typeof g?.pin_number=="number")_=g.pin_number.toString();else if(Array.isArray(g?.port_hints)){let F=g.port_hints.find(C=>/^(pin)?\d+$/.test(C));F&&(/^pin\d+$/.test(F)?_=F.replace(/^pin/,""):_=F)}o[_]=m.pcb_port_id}let l=t.pcb_trace.list({pcb_component_id:this.pcb_component_id}),p=x=>{if(x&&typeof x=="string"&&x.startsWith("{PIN")){let m=x.replace("{PIN","").replace("}","");return o[m]||x}return x};for(let x of l)if(x.route)for(let m of x.route)m.route_type==="wire"&&(m.start_pcb_port_id=p(m.start_pcb_port_id),m.end_pcb_port_id=p(m.end_pcb_port_id))}},O7e=class extends es{constructor(){super(...arguments);J(this,"pos",this.portMap.pin1);J(this,"anode",this.portMap.pin1);J(this,"neg",this.portMap.pin2);J(this,"cathode",this.portMap.pin2)}get config(){let t={laser:"laser_diode"},a=this.props.laser?"laser":null;return{schematicSymbolName:a?t[a]:this.props.symbolName??"led",componentName:"Led",zodProps:QEe,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}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:a}=this,o=t.source_component.insert({ftype:"simple_led",name:this.name,wave_length:a.wavelength,color:a.color,symbol_display_value:this._getSchematicSymbolDisplayValue(),manufacturer_part_number:a.manufacturerPartNumber??a.mfn,supplier_part_numbers:a.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=o.source_component_id}},L7e=class extends es{constructor(){super(...arguments);J(this,"pos",this.portMap.pin1);J(this,"positive",this.portMap.pin1);J(this,"neg",this.portMap.pin2);J(this,"negative",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"power_factor_meter_horz",componentName:"PowerSource",zodProps:c4e,sourceFtype:"simple_power_source"}}initPorts(){this.add(new cu({name:"pin1",pinNumber:1,aliases:["positive","pos"]})),this.add(new cu({name:"pin2",pinNumber:2,aliases:["negative","neg"]}))}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:a}=this,o=t.source_component.insert({ftype:"simple_power_source",name:this.name,voltage:a.voltage,supplier_part_numbers:a.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=o.source_component_id}},z7e=class extends es{get config(){return{componentName:"Resistor",schematicSymbolName:this.props.symbolName??"boxresistor",zodProps:BEe,sourceFtype:"simple_resistor"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return`${o0(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 Od({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pullupFor})),this.add(new Od({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pullupTo}))),this.props.pulldownFor&&this.props.pulldownTo&&(this.add(new Od({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pulldownFor})),this.add(new Od({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pulldownTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:t}=this,a=n.source_component.insert({ftype:"simple_resistor",name:this.name,manufacturer_part_number:t.manufacturerPartNumber??t.mfn,supplier_part_numbers:t.supplierPartNumbers,resistance:t.resistance,display_resistance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!0});this.source_component_id=a.source_component_id}},bVt=["leftedge","rightedge","topedge","bottomedge","center"],$7e=class extends Ya{get config(){return{componentName:"Constraint",zodProps:OEe}}constructor(n){if(super(n),("xdist"in n||"ydist"in n)&&!("edgeToEdge"in n)&&!("centerToCenter"in n))throw new Error(`edgeToEdge, centerToCenter must be set for xDist or yDist for ${this}`);if("for"in n&&n.for.length<2)throw new Error(`"for" must have at least two selectors for ${this}`)}_getAllReferencedComponents(){let n=[],t=this.getPrimitiveContainer();function a(o){let l=o.split(" ").pop(),p=bVt.includes(l)?l:void 0,x=p?o.replace(` ${p}`,""):o,m=t.selectOne(x,{pcbPrimitive:!0});m&&n.push({selector:o,component:m,componentSelector:x,edge:p})}for(let o of["left","right","top","bottom"])o in this._parsedProps&&a(this._parsedProps[o]);if("for"in this._parsedProps)for(let o of this._parsedProps.for)a(o);return{componentsWithSelectors:n}}},q7e=class extends Ya{constructor(){super(...arguments);J(this,"fabrication_note_path_id",null)}get config(){return{componentName:"FabricationNotePath",zodProps:n4e}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,a=this.getSubcircuit(),{_parsedProps:o}=this,l=o.layer??"top";if(l!=="top"&&l!=="bottom")throw new Error(`Invalid layer "${l}" for SilkscreenPath. Must be "top" or "bottom".`);let p=this._computePcbGlobalTransformBeforeLayout(),x=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,m=t.pcb_fabrication_note_path.insert({pcb_component_id:x,layer:l,color:o.color,route:o.route.map(g=>{let _=Ss(p,{x:g.x,y:g.y});return{...g,x:_.x,y:_.y}}),stroke_width:o.strokeWidth??.1,subcircuit_id:a?.subcircuit_id??void 0});this.fabrication_note_path_id=m.pcb_fabrication_note_path_id}},U7e=class extends Ya{get config(){return{componentName:"FabricationNoteText",zodProps:r4e}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:n}=this.root,{_parsedProps:t}=this,a=this.getPrimitiveContainer(),o=this.getSubcircuit();n.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:a.pcb_component_id,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}},V7e=class extends F_{constructor(n){super({...n,subcircuit:!0})}},G7e=class extends F_{constructor(n){super({...n,subcircuit:!0})}doInitialPcbPrimitiveRender(){if(super.doInitialPcbPrimitiveRender(),this.root?.pcbDisabled)return;let{db:n}=this.root,t=this._parsedProps;if(!this.pcb_group_id)return;let a=n.pcb_group.get(this.pcb_group_id),o=t.paddingLeft??t.padding??0,l=t.paddingRight??t.padding??0,p=t.paddingTop??t.padding??0,x=t.paddingBottom??t.padding??0;n.pcb_group.update(this.pcb_group_id,{width:a.width+o+l,height:a.height+p+x,center:{x:a.center.x+(l-o)/2,y:a.center.y+(p-x)/2}})}},H7e=class extends Ya{constructor(){super(...arguments);J(this,"pcb_breakout_point_id",null);J(this,"matchedPort",null);J(this,"matchedNet",null);J(this,"isPcbPrimitive",!0)}get config(){return{componentName:"BreakoutPoint",zodProps:s4e}}_matchConnection(){let{connection:t}=this._parsedProps,a=this.getSubcircuit();a&&(this.matchedPort=a.selectOne(t,{type:"port"}),this.matchedPort||(this.matchedNet=a.selectOne(t,{type:"net"})),!this.matchedPort&&!this.matchedNet&&this.renderError(`Could not find connection target "${t}"`))}_getSourceTraceIdForPort(t){let{db:a}=this.root;return a.source_trace.list().find(l=>l.connected_source_port_ids.includes(t.source_port_id))?.source_trace_id}_getSourceNetIdForPort(t){let{db:a}=this.root;return a.source_trace.list().find(l=>l.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:a=0,pcbY:o=0}=this._parsedProps,l=this.parent?.getGroup(),p=this.getSubcircuit();if(!l||!l.pcb_group_id)return;let x=t.pcb_breakout_point.insert({pcb_group_id:l.pcb_group_id,subcircuit_id:p?.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:a,y:o});this.pcb_breakout_point_id=x.pcb_breakout_point_id}_getPcbCircuitJsonBounds(){let{pcbX:t=0,pcbY:a=0}=this._parsedProps;return{center:{x:t,y:a},bounds:{left:t,top:a,right:t,bottom:a},width:0,height:0}}_setPositionFromLayout(t){let{db:a}=this.root;this.pcb_breakout_point_id&&a.pcb_breakout_point.update(this.pcb_breakout_point_id,{x:t.x,y:t.y})}getPcbSize(){return{width:0,height:0}}},Y7e=class extends Ya{constructor(){super(...arguments);J(this,"source_net_label_id")}get config(){return{componentName:"NetLabel",zodProps:HEe}}_getAnchorSide(){let{_parsedProps:t}=this;if(t.anchorSide)return t.anchorSide;if(!this._resolveConnectsTo())return"right";let o=this._getGlobalSchematicPositionBeforeLayout(),l=this._getConnectedPorts();if(l.length===0)return"right";let p=l[0]._getGlobalSchematicPositionBeforeLayout(),x=p.x-o.x,m=p.y-o.y;if(Math.abs(x)>Math.abs(m)){if(x>0)return"right";if(x<0)return"left"}else{if(m>0)return"top";if(m<0)return"bottom"}return"right"}_getConnectedPorts(){let t=this._resolveConnectsTo();if(!t)return[];let a=[];for(let o of t){let l=this.getSubcircuit().selectOne(o);l&&a.push(l)}return a}computeSchematicPropsTransform(){let{_parsedProps:t}=this;if(t.schX===void 0&&t.schY===void 0){let a=this._getConnectedPorts();if(a.length>0){let o=a[0]._getGlobalSchematicPositionBeforeLayout(),l=Ss(this.parent?.computeSchematicGlobalTransform?.()??gc(),{x:0,y:0});return si(o.x-l.x,o.y-l.y)}}return super.computeSchematicPropsTransform()}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:a}=this,o=this._getGlobalSchematicPositionBeforeLayout(),l=this.getSubcircuit().selectOne(`net.${this._getNetName()}`),p=a.anchorSide??"right",x=o8({anchor_position:o,anchor_side:p,text:a.net}),m=t.schematic_net_label.insert({text:a.net,source_net_id:l.source_net_id,anchor_position:o,center:x,anchor_side:this._getAnchorSide()});this.source_net_label_id=m.source_net_id}_resolveConnectsTo(){let{_parsedProps:t}=this,a=t.connectsTo??t.connection;if(Array.isArray(a))return a;if(typeof a=="string")return[a]}_getNetName(){let{_parsedProps:t}=this;return t.net}doInitialCreateNetsFromProps(){let{_parsedProps:t}=this;t.net&&RW(this,[`net.${t.net}`])}doInitialCreateTracesFromNetLabels(){if(this.root?.schematicDisabled)return;let t=this._resolveConnectsTo();if(t)for(let a of t)this.add(new Od({from:a,to:`net.${this._getNetName()}`}))}},X7e=class extends Ya{constructor(){super(...arguments);J(this,"pcb_silkscreen_circle_id",null);J(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenCircle",zodProps:g4e}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:a}=this,{maybeFlipLayer:o}=this._getPcbPrimitiveFlippedHelpers(),l=o(a.layer??"top");if(l!=="top"&&l!=="bottom")throw new Error(`Invalid layer "${l}" for SilkscreenCircle. Must be "top" or "bottom".`);let p=this._computePcbGlobalTransformBeforeLayout(),x=this.getSubcircuit(),m=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,g=t.pcb_silkscreen_circle.insert({pcb_component_id:m,layer:l,center:{x:a.pcbX??0,y:a.pcbY??0},radius:a.radius,subcircuit_id:x?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,stroke_width:a.strokeWidth??.1});this.pcb_silkscreen_circle_id=g.pcb_silkscreen_circle_id}getPcbSize(){let{_parsedProps:t}=this,a=t.radius*2;return{width:a,height:a}}},W7e=class extends Ya{constructor(){super(...arguments);J(this,"pcb_silkscreen_rect_id",null);J(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenRect",zodProps:y4e}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:a}=this,{maybeFlipLayer:o}=this._getPcbPrimitiveFlippedHelpers(),l=o(a.layer??"top");if(l!=="top"&&l!=="bottom")throw new Error(`Invalid layer "${l}" for SilkscreenRect. Must be "top" or "bottom".`);let p=this.getSubcircuit(),x=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,m=t.pcb_silkscreen_rect.insert({pcb_component_id:x,layer:l,center:{x:a.pcbX??0,y:a.pcbY??0},width:a.width,height:a.height,subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this?.getGroup()?.pcb_group_id??void 0,stroke_width:a.strokeWidth??.1});this.pcb_silkscreen_rect_id=m.pcb_silkscreen_rect_id}getPcbSize(){let{_parsedProps:t}=this;return{width:t.width,height:t.height}}},K7e=class extends Ya{constructor(){super(...arguments);J(this,"pcb_silkscreen_line_id",null);J(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenLine",zodProps:h4e}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:a}=this,{maybeFlipLayer:o}=this._getPcbPrimitiveFlippedHelpers(),l=o(a.layer??"top");if(l!=="top"&&l!=="bottom")throw new Error(`Invalid layer "${l}" for SilkscreenLine. Must be "top" or "bottom".`);let p=this.getSubcircuit(),x=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,m=t.pcb_silkscreen_line.insert({pcb_component_id:x,layer:l,x1:a.x1,y1:a.y1,x2:a.x2,y2:a.y2,stroke_width:a.strokeWidth??.1,subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:p?.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_line_id=m.pcb_silkscreen_line_id}getPcbSize(){let{_parsedProps:t}=this,a=Math.abs(t.x2-t.x1),o=Math.abs(t.y2-t.y1);return{width:a,height:o}}},J7e=class extends Ya{constructor(){super(...arguments);J(this,"pcb_via_id",null);J(this,"matchedPort",null);J(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Via",zodProps:a4e}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){let{_parsedProps:t}=this;return{width:t.outerDiameter,height:t.outerDiameter}}_getPcbCircuitJsonBounds(){let{db:t}=this.root,a=t.pcb_via.get(this.pcb_via_id),o=this.getPcbSize();return{center:{x:a.x,y:a.y},bounds:{left:a.x-o.width/2,top:a.y-o.height/2,right:a.x+o.width/2,bottom:a.y+o.height/2},width:o.width,height:o.height}}_setPositionFromLayout(t){let{db:a}=this.root;a.pcb_via.update(this.pcb_via_id,{x:t.x,y:t.y})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:a}=this,o=this._getGlobalPcbPositionBeforeLayout(),l=this.getSubcircuit(),p=t.pcb_via.insert({x:o.x,y:o.y,hole_diameter:a.holeDiameter,outer_diameter:a.outerDiameter,layers:["bottom","top"],from_layer:a.fromLayer||"bottom",to_layer:a.toLayer||"top",subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_via_id=p.pcb_via_id}},Z7e=class extends es{get config(){return{componentName:"Battery",schematicSymbolName:this.props.symbolName??"battery",zodProps:VEe,sourceFtype:"simple_power_source"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:t}=this,a=n.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=a.source_component_id}},Q7e=class extends es{get config(){return{componentName:"PinHeader",zodProps:GEe,shouldRenderAsSchematicBox:!0}}_getImpliedFootprintString(){let n=this._parsedProps.pinCount??this._parsedProps.pinLabels?.length??0,t=this._parsedProps.holeDiameter,a=this._parsedProps.platedDiameter,o=this._parsedProps.pitch;if(n>0){if(o)return!t&&!a?`pinrow${n}_p${o}`:`pinrow${n}_p${o}_id${t}_od${a}`;if(!t&&!a)return`pinrow${n}`}return null}initPorts(){let n=this._parsedProps.pinCount??this._parsedProps.pinLabels?.length??1;for(let t=1;t<=n;t++)this.add(new cu({name:`pin${t}`,pinNumber:t,aliases:[this._parsedProps.pinLabels?.[t-1]].filter(Boolean)}))}_getSchematicPortArrangement(){let n=this._parsedProps.pinCount??1,t=this._parsedProps.schFacingDirection??this._parsedProps.facingDirection??"right",a=this._parsedProps.schPinArrangement;return t==="left"?{leftSide:{direction:a?.leftSide?.direction??"top-to-bottom",pins:a?.leftSide?.pins??Array.from({length:n},(o,l)=>`pin${l+1}`)}}:{rightSide:{direction:a?.rightSide?.direction??"top-to-bottom",pins:a?.rightSide?.pins??Array.from({length:n},(o,l)=>`pin${l+1}`)}}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:t}=this,a=n.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=a.source_component_id}};function FVt(n){switch(n){case"two_ground_pins":return"crystal_4pin";case"ground_pin":return"resonator";case"no_ground":return"crystal";default:return"crystal"}}var eRe=class extends es{get config(){return{componentName:"Resonator",schematicSymbolName:this.props.symbolName??FVt(this.props.pinVariant),zodProps:jEe,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:t}=this,a=t.pinVariant||"no_ground",o=n.source_component.insert({ftype:"simple_resonator",name:this.name,frequency:t.frequency,load_capacitance:t.loadCapacitance,supplier_part_numbers:t.supplierPartNumbers,pin_variant:a,are_pins_interchangeable:a==="no_ground"||a==="ground_pin"});this.source_component_id=o.source_component_id}},tRe=class extends es{get config(){return{componentName:"Inductor",schematicSymbolName:this.props.symbolName??"inductor",zodProps:KEe,sourceFtype:qf.simple_inductor}}_getSchematicSymbolDisplayValue(){return`${o0(this._parsedProps.inductance)}H`}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:t}=this,a=n.source_component.insert({name:this.name,ftype:qf.simple_inductor,inductance:t.inductance,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=a.source_component_id}};function vVt(n){switch(n){case"three_pin":return"potentiometer3";case"two_pin":return"potentiometer2";default:return"potentiometer2"}}var rRe=class extends es{get config(){return{componentName:"Potentiometer",schematicSymbolName:this.props.symbolName??vVt(this.props.pinVariant),zodProps:PEe,shouldRenderAsSchematicBox:!1}}_getSchematicSymbolDisplayValue(){return`${o0(this._parsedProps.maxResistance)}\u03A9`}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:t}=this,a=t.pinVariant||"two_pin",o=n.source_component.insert({ftype:"simple_potentiometer",name:this.name,max_resistance:t.maxResistance,pin_variant:a,are_pins_interchangeable:a==="two_pin"});this.source_component_id=o.source_component_id}},nRe=class extends es{get config(){return{componentName:"PushButton",schematicSymbolName:this.props.symbolName??"push_button_normally_open_momentary",zodProps:YEe,sourceFtype:qf.simple_push_button}}get defaultInternallyConnectedPinNames(){return[]}initPorts(){super.initPorts({pinCount:2,ignoreSymbolPorts:!0});let n=Us[this._getSchematicSymbolNameOrThrow()],t=n.ports.find(_=>_.labels.includes("1")),a=n.ports.find(_=>_.labels.includes("2")),o=this.selectAll("port"),l=o.find(_=>_.props.pinNumber===1),p=o.find(_=>_.props.pinNumber===2),x=o.find(_=>_.props.pinNumber===3),m=o.find(_=>_.props.pinNumber===4),{internallyConnectedPins:g}=this._parsedProps;l.schematicSymbolPortDef=t,(!g||g.length===0)&&(p.schematicSymbolPortDef=a);for(let[_,F]of[[2,p],[3,x],[4,m]]){let C=g?.find(([P,k])=>P===`pin${_}`||k===`pin${_}`);if(!C){F.schematicSymbolPortDef=a;break}(C?.[0]===`pin${_}`?C[1]:C?.[0])!=="pin1"&&(F.schematicSymbolPortDef=a)}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:t}=this,a=n.source_component.insert({name:this.name,ftype:qf.simple_push_button,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=a.source_component_id}},aRe=class extends es{get config(){return{schematicSymbolName:this.props.symbolName??(this.props.pinVariant==="four_pin"?"crystal_4pin":"crystal"),componentName:"Crystal",zodProps:kEe,sourceFtype:"simple_crystal"}}initPorts(){let n=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:n})}_getSchematicSymbolDisplayValue(){let n=`${o0(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${n} / ${o0(this._parsedProps.loadCapacitance)}F`:n}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:t}=this,a=n.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=a.source_component_id}},iRe=class extends es{constructor(){super(...arguments);J(this,"emitter",this.portMap.pin1);J(this,"collector",this.portMap.pin2);J(this,"base",this.portMap.pin3)}get config(){return{componentName:"Transistor",schematicSymbolName:this.props.type==="npn"?"npn_bipolar_transistor":"pnp_bipolar_transistor",zodProps:XEe,sourceFtype:"simple_transistor",shouldRenderAsSchematicBox:!1}}initPorts(){let t=this.props.type==="npn"?{pin1:["emitter","e"],pin2:["collector","c"],pin3:["base","b"]}:{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:a}=this,o=t.source_component.insert({ftype:"simple_transistor",name:this.name,transistor_type:a.type});this.source_component_id=o.source_component_id}},sRe=class extends es{get config(){let n=this.props.mosfetMode==="depletion"?"d":"e";return{componentName:"Mosfet",schematicSymbolName:`${this.props.channelType}_channel_${n}_mosfet_transistor`,zodProps:WEe,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:t}=this,a=n.source_component.insert({ftype:"simple_mosfet",name:this.name,mosfet_mode:t.mosfetMode,channel_type:t.channelType});this.source_component_id=a.source_component_id}},oRe=class extends es{_getSwitchType(){let{spst:n,spdt:t,dpst:a,dpdt:o,type:l}=this._parsedProps??{};return o?"dpdt":n?"spst":t?"spdt":a?"dpst":l??"spst"}get config(){let n=this._getSwitchType(),{isNormallyClosed:t}=this._parsedProps??{};return{componentName:"Switch",schematicSymbolName:{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"}[n]??"spst_switch",zodProps:t4e,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:t}=this,a=n.source_component.insert({ftype:"simple_switch",name:this.name,switch_type:t.type,is_normally_closed:t.isNormallyClosed??!1,are_pins_interchangeable:this._getSwitchType()==="spst"});this.source_component_id=a.source_component_id}},DW={HOLE_DIAMETER:.5,SMT_CIRCLE_DIAMETER:1.2,SMT_RECT_SIZE:2},cRe=class extends es{get config(){return{componentName:"TestPoint",schematicSymbolName:this.props.symbolName??"testpoint",zodProps:i4e,sourceFtype:qf.simple_test_point}}_getPropsWithDefaults(){let{padShape:n,holeDiameter:t,footprintVariant:a,padDiameter:o,width:l,height:p}=this._parsedProps;return!a&&t&&(a="through_hole"),a??(a="through_hole"),n??(n="circle"),a==="pad"?n==="circle"?o??(o=DW.SMT_CIRCLE_DIAMETER):n==="rect"&&(l??(l=DW.SMT_RECT_SIZE),p??(p=l)):a==="through_hole"&&(t??(t=DW.HOLE_DIAMETER)),{padShape:n,holeDiameter:t,footprintVariant:a,padDiameter:o,width:l,height:p}}_getImpliedFootprintString(){let{padShape:n,holeDiameter:t,footprintVariant:a,padDiameter:o,width:l,height:p}=this._getPropsWithDefaults();if(a==="through_hole")return`platedhole_d${t}`;if(a==="pad"){if(n==="circle")return`smtpad_circle_d${o}`;if(n==="rect")return`smtpad_rect_w${l}_h${p}`}throw new Error(`Footprint variant "${a}" with pad shape "${n}" not implemented`)}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:t}=this,{padShape:a,holeDiameter:o,footprintVariant:l,padDiameter:p,width:x,height:m}=this._getPropsWithDefaults(),g=n.source_component.insert({ftype:qf.simple_test_point,name:this.name,supplier_part_numbers:t.supplierPartNumbers,footprint_variant:l,pad_shape:a,pad_diameter:p,hole_diameter:o,width:x,height:m,are_pins_interchangeable:!0});this.source_component_id=g.source_component_id}},uRe=class extends Ya{constructor(){super(...arguments);J(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicText",zodProps:l4e}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:a}=this,o=this._getGlobalSchematicPositionBeforeLayout();t.schematic_text.insert({anchor:a.anchor??"center",text:a.text,font_size:a.fontSize,color:a.color||"#000000",position:{x:o.x,y:o.y},rotation:a.schRotation??0})}};function EVt({anchor:n,x:t,y:a,width:o,height:l,isInside:p}){switch(n){case"top_left":return{x:t,y:a+l,textAnchor:p?"top_left":"bottom_left"};case"top_center":return{x:t+o/2,y:a+l,textAnchor:p?"top_center":"bottom_center"};case"top_right":return{x:t+o,y:a+l,textAnchor:p?"top_right":"bottom_right"};case"center_left":return{x:t,y:a+l/2,textAnchor:p?"center_left":"center_right"};case"center":return{x:t+o/2,y:a+l/2,textAnchor:"center"};case"center_right":return{x:t+o,y:a+l/2,textAnchor:p?"center_right":"center_left"};case"bottom_left":return{x:t,y:a,textAnchor:p?"bottom_left":"top_left"};case"bottom_center":return{x:t+o/2,y:a,textAnchor:p?"bottom_center":"top_center"};case"bottom_right":return{x:t+o,y:a,textAnchor:p?"bottom_right":"top_right"};default:return{x:t+o/2,y:a+l,textAnchor:"center"}}}var lRe=class extends Ya{constructor(){super(...arguments);J(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicBox",zodProps:u4e,shouldRenderAsSchematicBox:!0}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:a}=this,o=.6,l=typeof a.padding=="number"?a.padding:0,p=typeof a.paddingTop=="number"?a.paddingTop:l,x=typeof a.paddingBottom=="number"?a.paddingBottom:l,m=typeof a.paddingLeft=="number"?a.paddingLeft:l,g=typeof a.paddingRight=="number"?a.paddingRight:l,_=a.overlay&&a.overlay.length>0,F=typeof a.width=="number"&&typeof a.height=="number",C,S,P,k,q,X;if(_){let ee=a.overlay.map(dt=>({selector:dt,port:this.getSubcircuit().selectOne(dt,{type:"port"})})).filter(({port:dt})=>dt!=null).map(({port:dt})=>({position:dt._getGlobalSchematicPositionAfterLayout()}));if(ee.length===0)return;let ue=ee.map(dt=>dt.position.x),ce=ee.map(dt=>dt.position.y),fe=Math.min(...ue),U=Math.max(...ue),me=Math.min(...ce),W=Math.max(...ce),pe=U-fe,he=W-me,Ae=pe===0?o:0,de=he===0?o:0,Ne=m+Ae/2,Te=g+Ae/2,Ke=p+de/2,Qe=x+de/2,pt=fe-Ne,jt=U+Te,vt=me-Qe,xt=W+Ke;C=jt-pt,S=xt-vt,P=pt+(a.schX??0),k=vt+(a.schY??0),q=P+C/2,X=k+S/2}else if(F){C=a.width,S=a.height;let Q=this._getGlobalSchematicPositionBeforeLayout();q=Q.x,X=Q.y,P=q-C/2,k=X-S/2}else return;if(t.schematic_box.insert({height:S,width:C,x:P,y:k,is_dashed:a.strokeStyle==="dashed"}),a.title){let Q=a.titleInside,ee=.1,ue=a.titleAlignment,ce=EVt({anchor:ue,x:P,y:k,width:C,height:S,isInside:Q}),fe,U,me=ce.textAnchor;Q?(fe=ue.includes("top")?-ee:ue.includes("bottom")?ee:0,U=ue.includes("left")?ee:ue.includes("right")?-ee:0):(fe=ue.includes("top")?ee:ue.includes("bottom")?-ee:0,U=ue.includes("center_left")?-ee:ue.includes("center_right")?ee:0);let W=ce.x+U,pe=ce.y+fe;t.schematic_text.insert({anchor:me,text:a.title,font_size:a.titleFontSize??.18,color:a.titleColor??"#000000",position:{x:W,y:pe},rotation:0})}}},dRe=class extends Ya{constructor(){super(...arguments);J(this,"isSchematicPrimitive",!0);J(this,"schematic_table_id",null)}get config(){return{componentName:"SchematicTable",zodProps:d4e}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:a}=this,o=this.children.filter(S=>S.componentName==="SchematicRow");if(o.length===0)return;let l=[],p=0;for(let S of o){let P=S.children.filter(k=>k.componentName==="SchematicCell");p=Math.max(p,P.length)}for(let S=0;S<o.length;S++)l[S]=[];for(let S=0;S<o.length;S++){let k=o[S].children.filter(X=>X.componentName==="SchematicCell"),q=0;for(let X=0;X<k.length;X++){for(;l[S][q];)q++;let Q=k[X],ee=Q._parsedProps.colSpan??1,ue=Q._parsedProps.rowSpan??1;for(let ce=0;ce<ue;ce++)for(let fe=0;fe<ee;fe++)l[S+ce]||(l[S+ce]=[]),l[S+ce][q+fe]=Q;q+=ee}}p=Math.max(0,...l.map(S=>S.length));let x=o.map((S,P)=>S._parsedProps.height??1),m=Array.from({length:p},(S,P)=>{let k=0;for(let q=0;q<o.length;q++){let X=l[q]?.[P];if(X){let Q=X._parsedProps.text??X._parsedProps.children,ee=X._parsedProps.width??(Q?.length??2)*.5;ee>k&&(k=ee)}}return k||10}),g=this._getGlobalSchematicPositionBeforeLayout(),_=t.schematic_table.insert({anchor_position:g,column_widths:m,row_heights:x,cell_padding:a.cellPadding,border_width:a.borderWidth,anchor:a.anchor,subcircuit_id:this.getSubcircuit()?.subcircuit_id||"",schematic_component_id:this.parent?.schematic_component_id||""});this.schematic_table_id=_.schematic_table_id;let F=new Set,C=0;for(let S=0;S<o.length;S++){let P=0;for(let k=0;k<p;k++){let q=l[S]?.[k];if(q&&!F.has(q)){F.add(q);let X=q._parsedProps,Q=X.rowSpan??1,ee=X.colSpan??1,ue=0;for(let fe=0;fe<ee;fe++)ue+=m[k+fe];let ce=0;for(let fe=0;fe<Q;fe++)ce+=x[S+fe];t.schematic_table_cell.insert({schematic_table_id:this.schematic_table_id,start_row_index:S,end_row_index:S+Q-1,start_column_index:k,end_column_index:k+ee-1,text:X.text??X.children,center:{x:g.x+P+ue/2,y:g.y-C-ce/2},width:ue,height:ce,horizontal_align:X.horizontalAlign,vertical_align:X.verticalAlign,font_size:X.fontSize??a.fontSize,subcircuit_id:this.getSubcircuit()?.subcircuit_id||""})}m[k]&&(P+=m[k])}C+=x[S]}}},pRe=class extends Ya{constructor(){super(...arguments);J(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicRow",zodProps:p4e}}},xRe=class extends Ya{constructor(){super(...arguments);J(this,"isSchematicPrimitive",!0);J(this,"canHaveTextChildren",!0)}get config(){return{componentName:"SchematicCell",zodProps:x4e}}},CVt={name:"@tscircuit/core",type:"module",version:"0.0.614",types:"dist/index.d.ts",main:"dist/index.js",module:"dist/index.js",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","@tscircuit/capacity-autorouter":"^0.0.100","@tscircuit/checks":"^0.0.64","@tscircuit/circuit-json-util":"^0.0.62","@tscircuit/footprinter":"^0.0.208","@tscircuit/import-snippet":"^0.0.4","@tscircuit/infgrid-ijump-astar":"^0.0.33","@tscircuit/log-soup":"^1.0.2","@tscircuit/math-utils":"^0.0.18","@tscircuit/miniflex":"^0.0.4","@tscircuit/props":"^0.0.281","@tscircuit/schematic-autolayout":"^0.0.6","@tscircuit/schematic-corpus":"^0.0.110","@tscircuit/schematic-match-adapt":"^0.0.16","@tscircuit/simple-3d-svg":"^0.0.38","@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.5","chokidar-cli":"^3.0.0","circuit-json":"^0.0.226","circuit-json-to-bpc":"^0.0.13","circuit-json-to-connectivity-map":"^0.0.22","circuit-json-to-simple-3d":"^0.0.6","circuit-to-svg":"^0.0.174",concurrently:"^9.1.2",debug:"^4.3.6","graphics-debug":"^0.0.60",howfat:"^0.3.8","live-server":"^1.2.2","looks-same":"^9.0.1","pkg-pr-new":"^0.0.37",react:"^19.1.0","react-dom":"^19.1.0","schematic-symbols":"^0.0.180","ts-expect":"^1.3.0","@tscircuit/circuit-json-flex":"^0.0.3",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":"*","@tscircuit/circuit-json-flex":"*","@tscircuit/schematic-corpus":"*","circuit-json-to-bpc":"*","bpc-graph":"*","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.9","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","react-reconciler-18":"npm:react-reconciler@0.29.2","transformation-matrix":"^2.16.1",zod:"^3.25.67"}},v_=class{constructor({platform:n,projectUrl:t}={}){J(this,"firstChild",null);J(this,"children");J(this,"db");J(this,"root",null);J(this,"isRoot",!0);J(this,"schematicDisabled",!1);J(this,"pcbDisabled",!1);J(this,"pcbRoutingDisabled",!1);J(this,"name");J(this,"platform");J(this,"projectUrl");J(this,"_hasRenderedAtleastOnce",!1);J(this,"_eventListeners",{});this.children=[],this.db=La([]),this.root=this,this.platform=n,this.projectUrl=t,this.pcbDisabled=n?.pcbDisabled??!1}add(n){let t;(0,fRe.isValidElement)(n)?t=D7e(n):t=n,this.children.push(t)}_getBoard(){return this.children.find(n=>n.componentName==="Board")}_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(...))");if(this.children.length===1&&this.children[0].isGroup){this.firstChild=this.children[0];return}let n=new F_({subcircuit:!0});n.parent=this,n.addAll(this.children),this.children=[n],this.firstChild=n}render(){this.firstChild||this._guessRootComponent();let{firstChild:n,db:t}=this;if(!n)throw new Error("RootCircuit has no root component");n.parent=this,n.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(n=>n._hasIncompleteAsyncEffects()?!0:n.children.some(t=>t._hasIncompleteAsyncEffects()))}getCircuitJson(){return this._hasRenderedAtleastOnce||this.render(),this.db.toArray()}toJson(){return this.getCircuitJson()}async getSvg(n){let t=await Promise.resolve().then(()=>(e7e(),QAe)).catch(a=>{throw new Error(`To use circuit.getSvg, you must install the "circuit-to-svg" package.
1036
+ `),m={x:a.center.x+a.width/2-.25,y:a.center.y-a.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:l,ccw_rotation:0,anchor_alignment:"bottom_right",anchor_position:m})}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:a}=this,o=a.width??0,l=a.height??0,p={x:(a.pcbX??0)+(a.outlineOffsetX??0),y:(a.pcbY??0)+(a.outlineOffsetY??0)};if(a.outline){let m=a.outline.map(P=>P.x),g=a.outline.map(P=>P.y),_=Math.min(...m),F=Math.max(...m),C=Math.min(...g),S=Math.max(...g);o=F-_,l=S-C,p={x:(_+F)/2+(a.outlineOffsetX??0),y:(C+S)/2+(a.outlineOffsetY??0)}}let x=t.pcb_board.insert({center:p,thickness:this.boardThickness,num_layers:this.allLayers.length,width:o,height:l,outline:a.outline?.map(m=>({x:m.x+(a.outlineOffsetX??0),y:m.y+(a.outlineOffsetY??0)})),material:a.material});this.pcb_board_id=x.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 gc()}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 a=gAe(t.toArray());for(let o of a)t.pcb_trace_error.insert(o)}_emitRenderLifecycleEvent(t,a){super._emitRenderLifecycleEvent(t,a),a==="start"&&this.root?.emit("board:renderPhaseStarted",{renderId:this._renderId,phase:t})}},_Vt=new Proxy({},{get:(n,t)=>t}),qf=_Vt,P7e=class extends es{get config(){return{componentName:"Capacitor",schematicSymbolName:this.props.polarized?"capacitor_polarized":this.props.symbolName??"capacitor",zodProps:NEe,sourceFtype:qf.simple_capacitor}}_getSchematicSymbolDisplayValue(){let n=`${o0(this._parsedProps.capacitance)}F`;return this._parsedProps.schShowRatings&&this._parsedProps.maxVoltageRating?`${n}/${o0(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 Od({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.decouplingFor})),this.add(new Od({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.decouplingTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:t}=this,a=n.source_component.insert({ftype:"simple_capacitor",name:this.name,manufacturer_part_number:t.manufacturerPartNumber??t.mfn,supplier_part_numbers:t.supplierPartNumbers,capacitance:t.capacitance,max_voltage_rating:t.maxVoltageRating,max_decoupling_trace_length:t.maxDecouplingTraceLength,display_capacitance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!t.polarized});this.source_component_id=a.source_component_id}},PW=class extends es{constructor(){super(...arguments);J(this,"schematicBoxDimensions",null)}get config(){return{componentName:"Chip",zodProps:xY,shouldRenderAsSchematicBox:!0}}initPorts(t={}){super.initPorts(t);let{_parsedProps:a}=this;if(a.externallyConnectedPins){let o=new Set;for(let[l,p]of a.externallyConnectedPins)o.add(l),o.add(p);for(let l of o)if(!this.children.find(x=>x instanceof cu&&x.isMatchingAnyOf([l]))){let x=l.match(/^pin(\d+)$/);if(x){let m=parseInt(x[1]);this.add(new cu({pinNumber:m,aliases:[l]}))}else this.add(new cu({name:l,aliases:[l]}))}}}doInitialSchematicComponentRender(){let{_parsedProps:t}=this;t?.noSchematicRepresentation!==!0&&super.doInitialSchematicComponentRender()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:a}=this,o=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:a.manufacturerPartNumber,supplier_part_numbers:a.supplierPartNumbers});this.source_component_id=o.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:a}=this,o=t.pcb_component.insert({center:{x:a.pcbX??0,y:a.pcbY??0},width:2,height:3,layer:a.layer??"top",rotation:a.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.pcb_component_id=o.pcb_component_id}doInitialCreateTracesFromProps(){let{_parsedProps:t}=this;if(t.externallyConnectedPins)for(let[a,o]of t.externallyConnectedPins)this.add(new Od({from:`${this.getSubcircuitSelector()} > port.${a}`,to:`${this.getSubcircuitSelector()} > port.${o}`}));this._createTracesFromConnectionsProp()}doInitialSimulationRender(){let{db:t}=this.root,{pinAttributes:a}=this.props;if(!a)return;let o=null,l=null,p,x=this.selectAll("port");for(let C of x)for(let S of C.getNameAndAliases())if(a[S]){let P=a[S];P.providesPower&&(o=C,p=P.providesVoltage),P.providesGround&&(l=C)}if(!o||!l||p===void 0)return;let m=t.source_port.get(o.source_port_id);if(!m?.subcircuit_connectivity_map_key)return;let g=t.source_port.get(l.source_port_id);if(!g?.subcircuit_connectivity_map_key)return;let _=t.source_net.getWhere({subcircuit_connectivity_map_key:m.subcircuit_connectivity_map_key}),F=t.source_net.getWhere({subcircuit_connectivity_map_key:g.subcircuit_connectivity_map_key});!_||!F||t.simulation_voltage_source.insert({type:"simulation_voltage_source",positive_source_port_id:o.source_port_id,positive_source_net_id:_.source_net_id,negative_source_port_id:l.source_port_id,negative_source_net_id:F.source_net_id,voltage:p})}},k7e=class extends es{constructor(){super(...arguments);J(this,"pos",this.portMap.pin1);J(this,"anode",this.portMap.pin1);J(this,"neg",this.portMap.pin2);J(this,"cathode",this.portMap.pin2)}get config(){let t={schottky:"schottky_diode",avalanche:"avalanche_diode",zener:"zener_diode",photodiode:"photodiode"},a=this.props.schottky?"schottky":this.props.avalanche?"avalanche":this.props.zener?"zener":this.props.photo?"photodiode":null;return{schematicSymbolName:a?t[a]:this.props.symbolName??"diode",componentName:"Diode",zodProps:JEe,sourceFtype:"simple_diode"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:a}=this,o=t.source_component.insert({ftype:"simple_diode",name:this.name,manufacturer_part_number:a.manufacturerPartNumber??a.mfn,supplier_part_numbers:a.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=o.source_component_id}},j7e=class extends es{get config(){return{componentName:"fuse",schematicSymbolName:this.props.symbolName??"fuse",zodProps:wEe,sourceFtype:qf.simple_fuse}}_getSchematicSymbolDisplayValue(){let n=this._parsedProps.currentRating,t=this._parsedProps.voltageRating,a=typeof n=="string"?parseFloat(n):n,o=typeof t=="string"?parseFloat(t):t;return`${o0(a)}A / ${o0(o)}V`}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:t}=this,a=typeof t.currentRating=="string"?parseFloat(t.currentRating):t.currentRating,o=typeof t.voltageRating=="string"?parseFloat(t.voltageRating):t.voltageRating,l=n.source_component.insert({name:this.name,ftype:qf.simple_fuse,current_rating_amps:a,voltage_rating_volts:o,display_current_rating:`${o0(a)}A`,display_voltage_rating:`${o0(o)}V`});this.source_component_id=l.source_component_id}},N7e=class extends es{constructor(){super(...arguments);J(this,"schematicDimensions",null)}get config(){return{schematicSymbolName:void 0,componentName:"Jumper",zodProps:mY,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let t=super._getSchematicPortArrangement();if(t&&Object.keys(t).length>0)return t;let a=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length),o=this._parsedProps.schDirection??"right";return{leftSize:o==="left"?a:0,rightSize:o==="right"?a:0}}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:a}=this,o=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:a.manufacturerPartNumber,supplier_part_numbers:a.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=o.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:a}=this,o=t.pcb_component.insert({center:{x:a.pcbX??0,y:a.pcbY??0},width:2,height:3,layer:a.layer??"top",rotation:a.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.pcb_component_id=o.pcb_component_id}doInitialPcbTraceRender(){let{db:t}=this.root,a=t.pcb_port.list({pcb_component_id:this.pcb_component_id}),o={};for(let x=0;x<a.length;x++){let m=a[x],g=t.source_port.get(m.source_port_id),_="";if(typeof g?.pin_number=="number")_=g.pin_number.toString();else if(Array.isArray(g?.port_hints)){let F=g.port_hints.find(C=>/^(pin)?\d+$/.test(C));F&&(/^pin\d+$/.test(F)?_=F.replace(/^pin/,""):_=F)}o[_]=m.pcb_port_id}let l=t.pcb_trace.list({pcb_component_id:this.pcb_component_id}),p=x=>{if(x&&typeof x=="string"&&x.startsWith("{PIN")){let m=x.replace("{PIN","").replace("}","");return o[m]||x}return x};for(let x of l)if(x.route)for(let m of x.route)m.route_type==="wire"&&(m.start_pcb_port_id=p(m.start_pcb_port_id),m.end_pcb_port_id=p(m.end_pcb_port_id))}},M7e=class extends es{constructor(){super(...arguments);J(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(a=>a.componentName==="Port").map(a=>a.name);return t.length>0?[t]:[]}return this._parsedProps.bridgedPins??[]}get config(){let t=this._parsedProps??this.props,a=t.pinCount;if(t.pinCount==null&&!t.footprint&&(a=2),t.pinCount==null){let p=(t.bridgedPins??[]).flat().map(_=>this._getPinNumberFromBridgedPinName(_)).filter(_=>_!==null),x=p.length>0?Math.max(...p):0,m=t.pinLabels?Object.keys(t.pinLabels).length:0,g=Math.max(x,m);(g===2||g===3)&&(a=g),a==null&&t.footprint&&[2,3].includes(this.getPortsFromFootprint().length)&&(a=this.getPortsFromFootprint().length)}let o="";a?o+=`solderjumper${a}`:o="solderjumper";let l=[];return Array.isArray(t.bridgedPins)&&t.bridgedPins.length>0?l=Array.from(new Set(t.bridgedPins.flat().map(p=>this._getPinNumberFromBridgedPinName(p)).filter(p=>p!==null))).sort((p,x)=>p-x):t.bridged&&a&&(l=Array.from({length:a},(p,x)=>x+1)),l.length>0&&(o+=`_bridged${l.join("")}`),{schematicSymbolName:t.symbolName??o,componentName:"SolderJumper",zodProps:IEe,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let t=super._getSchematicPortArrangement();if(t&&Object.keys(t).length>0)return t;let a=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length);a==null&&!this._parsedProps.footprint&&(a=2);let o=this._parsedProps.schDirection??"right";return{leftSize:o==="left"?a:0,rightSize:o==="right"?a:0}}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:a}=this,o=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:a.manufacturerPartNumber,supplier_part_numbers:a.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=o.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:a}=this,o=t.pcb_component.insert({center:{x:a.pcbX??0,y:a.pcbY??0},width:2,height:3,layer:a.layer??"top",rotation:a.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.pcb_component_id=o.pcb_component_id}doInitialPcbTraceRender(){let{db:t}=this.root,a=t.pcb_port.list({pcb_component_id:this.pcb_component_id}),o={};for(let x=0;x<a.length;x++){let m=a[x],g=t.source_port.get(m.source_port_id),_="";if(typeof g?.pin_number=="number")_=g.pin_number.toString();else if(Array.isArray(g?.port_hints)){let F=g.port_hints.find(C=>/^(pin)?\d+$/.test(C));F&&(/^pin\d+$/.test(F)?_=F.replace(/^pin/,""):_=F)}o[_]=m.pcb_port_id}let l=t.pcb_trace.list({pcb_component_id:this.pcb_component_id}),p=x=>{if(x&&typeof x=="string"&&x.startsWith("{PIN")){let m=x.replace("{PIN","").replace("}","");return o[m]||x}return x};for(let x of l)if(x.route)for(let m of x.route)m.route_type==="wire"&&(m.start_pcb_port_id=p(m.start_pcb_port_id),m.end_pcb_port_id=p(m.end_pcb_port_id))}},O7e=class extends es{constructor(){super(...arguments);J(this,"pos",this.portMap.pin1);J(this,"anode",this.portMap.pin1);J(this,"neg",this.portMap.pin2);J(this,"cathode",this.portMap.pin2)}get config(){let t={laser:"laser_diode"},a=this.props.laser?"laser":null;return{schematicSymbolName:a?t[a]:this.props.symbolName??"led",componentName:"Led",zodProps:QEe,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}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:a}=this,o=t.source_component.insert({ftype:"simple_led",name:this.name,wave_length:a.wavelength,color:a.color,symbol_display_value:this._getSchematicSymbolDisplayValue(),manufacturer_part_number:a.manufacturerPartNumber??a.mfn,supplier_part_numbers:a.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=o.source_component_id}},L7e=class extends es{constructor(){super(...arguments);J(this,"pos",this.portMap.pin1);J(this,"positive",this.portMap.pin1);J(this,"neg",this.portMap.pin2);J(this,"negative",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"power_factor_meter_horz",componentName:"PowerSource",zodProps:c4e,sourceFtype:"simple_power_source"}}initPorts(){this.add(new cu({name:"pin1",pinNumber:1,aliases:["positive","pos"]})),this.add(new cu({name:"pin2",pinNumber:2,aliases:["negative","neg"]}))}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:a}=this,o=t.source_component.insert({ftype:"simple_power_source",name:this.name,voltage:a.voltage,supplier_part_numbers:a.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=o.source_component_id}},z7e=class extends es{get config(){return{componentName:"Resistor",schematicSymbolName:this.props.symbolName??"boxresistor",zodProps:BEe,sourceFtype:"simple_resistor"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return`${o0(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 Od({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pullupFor})),this.add(new Od({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pullupTo}))),this.props.pulldownFor&&this.props.pulldownTo&&(this.add(new Od({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pulldownFor})),this.add(new Od({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pulldownTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:t}=this,a=n.source_component.insert({ftype:"simple_resistor",name:this.name,manufacturer_part_number:t.manufacturerPartNumber??t.mfn,supplier_part_numbers:t.supplierPartNumbers,resistance:t.resistance,display_resistance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!0});this.source_component_id=a.source_component_id}},bVt=["leftedge","rightedge","topedge","bottomedge","center"],$7e=class extends Ya{get config(){return{componentName:"Constraint",zodProps:OEe}}constructor(n){if(super(n),("xdist"in n||"ydist"in n)&&!("edgeToEdge"in n)&&!("centerToCenter"in n))throw new Error(`edgeToEdge, centerToCenter must be set for xDist or yDist for ${this}`);if("for"in n&&n.for.length<2)throw new Error(`"for" must have at least two selectors for ${this}`)}_getAllReferencedComponents(){let n=[],t=this.getPrimitiveContainer();function a(o){let l=o.split(" ").pop(),p=bVt.includes(l)?l:void 0,x=p?o.replace(` ${p}`,""):o,m=t.selectOne(x,{pcbPrimitive:!0});m&&n.push({selector:o,component:m,componentSelector:x,edge:p})}for(let o of["left","right","top","bottom"])o in this._parsedProps&&a(this._parsedProps[o]);if("for"in this._parsedProps)for(let o of this._parsedProps.for)a(o);return{componentsWithSelectors:n}}},q7e=class extends Ya{constructor(){super(...arguments);J(this,"fabrication_note_path_id",null)}get config(){return{componentName:"FabricationNotePath",zodProps:n4e}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,a=this.getSubcircuit(),{_parsedProps:o}=this,l=o.layer??"top";if(l!=="top"&&l!=="bottom")throw new Error(`Invalid layer "${l}" for SilkscreenPath. Must be "top" or "bottom".`);let p=this._computePcbGlobalTransformBeforeLayout(),x=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,m=t.pcb_fabrication_note_path.insert({pcb_component_id:x,layer:l,color:o.color,route:o.route.map(g=>{let _=Ss(p,{x:g.x,y:g.y});return{...g,x:_.x,y:_.y}}),stroke_width:o.strokeWidth??.1,subcircuit_id:a?.subcircuit_id??void 0});this.fabrication_note_path_id=m.pcb_fabrication_note_path_id}},U7e=class extends Ya{get config(){return{componentName:"FabricationNoteText",zodProps:r4e}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:n}=this.root,{_parsedProps:t}=this,a=this.getPrimitiveContainer(),o=this.getSubcircuit();n.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:a.pcb_component_id,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}},V7e=class extends F_{constructor(n){super({...n,subcircuit:!0})}},G7e=class extends F_{constructor(n){super({...n,subcircuit:!0})}doInitialPcbPrimitiveRender(){if(super.doInitialPcbPrimitiveRender(),this.root?.pcbDisabled)return;let{db:n}=this.root,t=this._parsedProps;if(!this.pcb_group_id)return;let a=n.pcb_group.get(this.pcb_group_id),o=t.paddingLeft??t.padding??0,l=t.paddingRight??t.padding??0,p=t.paddingTop??t.padding??0,x=t.paddingBottom??t.padding??0;n.pcb_group.update(this.pcb_group_id,{width:a.width+o+l,height:a.height+p+x,center:{x:a.center.x+(l-o)/2,y:a.center.y+(p-x)/2}})}},H7e=class extends Ya{constructor(){super(...arguments);J(this,"pcb_breakout_point_id",null);J(this,"matchedPort",null);J(this,"matchedNet",null);J(this,"isPcbPrimitive",!0)}get config(){return{componentName:"BreakoutPoint",zodProps:s4e}}_matchConnection(){let{connection:t}=this._parsedProps,a=this.getSubcircuit();a&&(this.matchedPort=a.selectOne(t,{type:"port"}),this.matchedPort||(this.matchedNet=a.selectOne(t,{type:"net"})),!this.matchedPort&&!this.matchedNet&&this.renderError(`Could not find connection target "${t}"`))}_getSourceTraceIdForPort(t){let{db:a}=this.root;return a.source_trace.list().find(l=>l.connected_source_port_ids.includes(t.source_port_id))?.source_trace_id}_getSourceNetIdForPort(t){let{db:a}=this.root;return a.source_trace.list().find(l=>l.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:a=0,pcbY:o=0}=this._parsedProps,l=this.parent?.getGroup(),p=this.getSubcircuit();if(!l||!l.pcb_group_id)return;let x=t.pcb_breakout_point.insert({pcb_group_id:l.pcb_group_id,subcircuit_id:p?.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:a,y:o});this.pcb_breakout_point_id=x.pcb_breakout_point_id}_getPcbCircuitJsonBounds(){let{pcbX:t=0,pcbY:a=0}=this._parsedProps;return{center:{x:t,y:a},bounds:{left:t,top:a,right:t,bottom:a},width:0,height:0}}_setPositionFromLayout(t){let{db:a}=this.root;this.pcb_breakout_point_id&&a.pcb_breakout_point.update(this.pcb_breakout_point_id,{x:t.x,y:t.y})}getPcbSize(){return{width:0,height:0}}},Y7e=class extends Ya{constructor(){super(...arguments);J(this,"source_net_label_id")}get config(){return{componentName:"NetLabel",zodProps:HEe}}_getAnchorSide(){let{_parsedProps:t}=this;if(t.anchorSide)return t.anchorSide;if(!this._resolveConnectsTo())return"right";let o=this._getGlobalSchematicPositionBeforeLayout(),l=this._getConnectedPorts();if(l.length===0)return"right";let p=l[0]._getGlobalSchematicPositionBeforeLayout(),x=p.x-o.x,m=p.y-o.y;if(Math.abs(x)>Math.abs(m)){if(x>0)return"right";if(x<0)return"left"}else{if(m>0)return"top";if(m<0)return"bottom"}return"right"}_getConnectedPorts(){let t=this._resolveConnectsTo();if(!t)return[];let a=[];for(let o of t){let l=this.getSubcircuit().selectOne(o);l&&a.push(l)}return a}computeSchematicPropsTransform(){let{_parsedProps:t}=this;if(t.schX===void 0&&t.schY===void 0){let a=this._getConnectedPorts();if(a.length>0){let o=a[0]._getGlobalSchematicPositionBeforeLayout(),l=Ss(this.parent?.computeSchematicGlobalTransform?.()??gc(),{x:0,y:0});return si(o.x-l.x,o.y-l.y)}}return super.computeSchematicPropsTransform()}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:a}=this,o=this._getGlobalSchematicPositionBeforeLayout(),l=this.getSubcircuit().selectOne(`net.${this._getNetName()}`),p=a.anchorSide??"right",x=o8({anchor_position:o,anchor_side:p,text:a.net}),m=t.schematic_net_label.insert({text:a.net,source_net_id:l.source_net_id,anchor_position:o,center:x,anchor_side:this._getAnchorSide()});this.source_net_label_id=m.source_net_id}_resolveConnectsTo(){let{_parsedProps:t}=this,a=t.connectsTo??t.connection;if(Array.isArray(a))return a;if(typeof a=="string")return[a]}_getNetName(){let{_parsedProps:t}=this;return t.net}doInitialCreateNetsFromProps(){let{_parsedProps:t}=this;t.net&&RW(this,[`net.${t.net}`])}doInitialCreateTracesFromNetLabels(){if(this.root?.schematicDisabled)return;let t=this._resolveConnectsTo();if(t)for(let a of t)this.add(new Od({from:a,to:`net.${this._getNetName()}`}))}},X7e=class extends Ya{constructor(){super(...arguments);J(this,"pcb_silkscreen_circle_id",null);J(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenCircle",zodProps:g4e}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:a}=this,{maybeFlipLayer:o}=this._getPcbPrimitiveFlippedHelpers(),l=o(a.layer??"top");if(l!=="top"&&l!=="bottom")throw new Error(`Invalid layer "${l}" for SilkscreenCircle. Must be "top" or "bottom".`);let p=this._computePcbGlobalTransformBeforeLayout(),x=this.getSubcircuit(),m=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,g=t.pcb_silkscreen_circle.insert({pcb_component_id:m,layer:l,center:{x:a.pcbX??0,y:a.pcbY??0},radius:a.radius,subcircuit_id:x?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,stroke_width:a.strokeWidth??.1});this.pcb_silkscreen_circle_id=g.pcb_silkscreen_circle_id}getPcbSize(){let{_parsedProps:t}=this,a=t.radius*2;return{width:a,height:a}}},W7e=class extends Ya{constructor(){super(...arguments);J(this,"pcb_silkscreen_rect_id",null);J(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenRect",zodProps:y4e}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:a}=this,{maybeFlipLayer:o}=this._getPcbPrimitiveFlippedHelpers(),l=o(a.layer??"top");if(l!=="top"&&l!=="bottom")throw new Error(`Invalid layer "${l}" for SilkscreenRect. Must be "top" or "bottom".`);let p=this.getSubcircuit(),x=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,m=t.pcb_silkscreen_rect.insert({pcb_component_id:x,layer:l,center:{x:a.pcbX??0,y:a.pcbY??0},width:a.width,height:a.height,subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this?.getGroup()?.pcb_group_id??void 0,stroke_width:a.strokeWidth??.1});this.pcb_silkscreen_rect_id=m.pcb_silkscreen_rect_id}getPcbSize(){let{_parsedProps:t}=this;return{width:t.width,height:t.height}}},K7e=class extends Ya{constructor(){super(...arguments);J(this,"pcb_silkscreen_line_id",null);J(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenLine",zodProps:h4e}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:a}=this,{maybeFlipLayer:o}=this._getPcbPrimitiveFlippedHelpers(),l=o(a.layer??"top");if(l!=="top"&&l!=="bottom")throw new Error(`Invalid layer "${l}" for SilkscreenLine. Must be "top" or "bottom".`);let p=this.getSubcircuit(),x=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,m=t.pcb_silkscreen_line.insert({pcb_component_id:x,layer:l,x1:a.x1,y1:a.y1,x2:a.x2,y2:a.y2,stroke_width:a.strokeWidth??.1,subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:p?.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_line_id=m.pcb_silkscreen_line_id}getPcbSize(){let{_parsedProps:t}=this,a=Math.abs(t.x2-t.x1),o=Math.abs(t.y2-t.y1);return{width:a,height:o}}},J7e=class extends Ya{constructor(){super(...arguments);J(this,"pcb_via_id",null);J(this,"matchedPort",null);J(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Via",zodProps:a4e}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){let{_parsedProps:t}=this;return{width:t.outerDiameter,height:t.outerDiameter}}_getPcbCircuitJsonBounds(){let{db:t}=this.root,a=t.pcb_via.get(this.pcb_via_id),o=this.getPcbSize();return{center:{x:a.x,y:a.y},bounds:{left:a.x-o.width/2,top:a.y-o.height/2,right:a.x+o.width/2,bottom:a.y+o.height/2},width:o.width,height:o.height}}_setPositionFromLayout(t){let{db:a}=this.root;a.pcb_via.update(this.pcb_via_id,{x:t.x,y:t.y})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:a}=this,o=this._getGlobalPcbPositionBeforeLayout(),l=this.getSubcircuit(),p=t.pcb_via.insert({x:o.x,y:o.y,hole_diameter:a.holeDiameter,outer_diameter:a.outerDiameter,layers:["bottom","top"],from_layer:a.fromLayer||"bottom",to_layer:a.toLayer||"top",subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_via_id=p.pcb_via_id}},Z7e=class extends es{get config(){return{componentName:"Battery",schematicSymbolName:this.props.symbolName??"battery",zodProps:VEe,sourceFtype:"simple_power_source"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:t}=this,a=n.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=a.source_component_id}},Q7e=class extends es{get config(){return{componentName:"PinHeader",zodProps:GEe,shouldRenderAsSchematicBox:!0}}_getImpliedFootprintString(){let n=this._parsedProps.pinCount??this._parsedProps.pinLabels?.length??0,t=this._parsedProps.holeDiameter,a=this._parsedProps.platedDiameter,o=this._parsedProps.pitch,l=this._parsedProps.showSilkscreenPinLabels;if(n>0){let p;if(o)!t&&!a?p=`pinrow${n}_p${o}`:p=`pinrow${n}_p${o}_id${t}_od${a}`;else if(!t&&!a)p=`pinrow${n}`;else return null;return l!==!0&&(p+="_nopinlabels"),p}return null}initPorts(){let n=this._parsedProps.pinCount??this._parsedProps.pinLabels?.length??1;for(let t=1;t<=n;t++)this.add(new cu({name:`pin${t}`,pinNumber:t,aliases:[this._parsedProps.pinLabels?.[t-1]].filter(Boolean)}))}_getSchematicPortArrangement(){let n=this._parsedProps.pinCount??1,t=this._parsedProps.schFacingDirection??this._parsedProps.facingDirection??"right",a=this._parsedProps.schPinArrangement;return t==="left"?{leftSide:{direction:a?.leftSide?.direction??"top-to-bottom",pins:a?.leftSide?.pins??Array.from({length:n},(o,l)=>`pin${l+1}`)}}:{rightSide:{direction:a?.rightSide?.direction??"top-to-bottom",pins:a?.rightSide?.pins??Array.from({length:n},(o,l)=>`pin${l+1}`)}}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:t}=this,a=n.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=a.source_component_id}};function FVt(n){switch(n){case"two_ground_pins":return"crystal_4pin";case"ground_pin":return"resonator";case"no_ground":return"crystal";default:return"crystal"}}var eRe=class extends es{get config(){return{componentName:"Resonator",schematicSymbolName:this.props.symbolName??FVt(this.props.pinVariant),zodProps:jEe,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:t}=this,a=t.pinVariant||"no_ground",o=n.source_component.insert({ftype:"simple_resonator",name:this.name,frequency:t.frequency,load_capacitance:t.loadCapacitance,supplier_part_numbers:t.supplierPartNumbers,pin_variant:a,are_pins_interchangeable:a==="no_ground"||a==="ground_pin"});this.source_component_id=o.source_component_id}},tRe=class extends es{get config(){return{componentName:"Inductor",schematicSymbolName:this.props.symbolName??"inductor",zodProps:KEe,sourceFtype:qf.simple_inductor}}_getSchematicSymbolDisplayValue(){return`${o0(this._parsedProps.inductance)}H`}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:t}=this,a=n.source_component.insert({name:this.name,ftype:qf.simple_inductor,inductance:t.inductance,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=a.source_component_id}};function vVt(n){switch(n){case"three_pin":return"potentiometer3";case"two_pin":return"potentiometer2";default:return"potentiometer2"}}var rRe=class extends es{get config(){return{componentName:"Potentiometer",schematicSymbolName:this.props.symbolName??vVt(this.props.pinVariant),zodProps:PEe,shouldRenderAsSchematicBox:!1}}_getSchematicSymbolDisplayValue(){return`${o0(this._parsedProps.maxResistance)}\u03A9`}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:t}=this,a=t.pinVariant||"two_pin",o=n.source_component.insert({ftype:"simple_potentiometer",name:this.name,max_resistance:t.maxResistance,pin_variant:a,are_pins_interchangeable:a==="two_pin"});this.source_component_id=o.source_component_id}},nRe=class extends es{get config(){return{componentName:"PushButton",schematicSymbolName:this.props.symbolName??"push_button_normally_open_momentary",zodProps:YEe,sourceFtype:qf.simple_push_button}}get defaultInternallyConnectedPinNames(){return[]}initPorts(){super.initPorts({pinCount:2,ignoreSymbolPorts:!0});let n=Us[this._getSchematicSymbolNameOrThrow()],t=n.ports.find(_=>_.labels.includes("1")),a=n.ports.find(_=>_.labels.includes("2")),o=this.selectAll("port"),l=o.find(_=>_.props.pinNumber===1),p=o.find(_=>_.props.pinNumber===2),x=o.find(_=>_.props.pinNumber===3),m=o.find(_=>_.props.pinNumber===4),{internallyConnectedPins:g}=this._parsedProps;l.schematicSymbolPortDef=t,(!g||g.length===0)&&(p.schematicSymbolPortDef=a);for(let[_,F]of[[2,p],[3,x],[4,m]]){let C=g?.find(([P,k])=>P===`pin${_}`||k===`pin${_}`);if(!C){F.schematicSymbolPortDef=a;break}(C?.[0]===`pin${_}`?C[1]:C?.[0])!=="pin1"&&(F.schematicSymbolPortDef=a)}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:t}=this,a=n.source_component.insert({name:this.name,ftype:qf.simple_push_button,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=a.source_component_id}},aRe=class extends es{get config(){return{schematicSymbolName:this.props.symbolName??(this.props.pinVariant==="four_pin"?"crystal_4pin":"crystal"),componentName:"Crystal",zodProps:kEe,sourceFtype:"simple_crystal"}}initPorts(){let n=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:n})}_getSchematicSymbolDisplayValue(){let n=`${o0(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${n} / ${o0(this._parsedProps.loadCapacitance)}F`:n}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:t}=this,a=n.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=a.source_component_id}},iRe=class extends es{constructor(){super(...arguments);J(this,"emitter",this.portMap.pin1);J(this,"collector",this.portMap.pin2);J(this,"base",this.portMap.pin3)}get config(){return{componentName:"Transistor",schematicSymbolName:this.props.type==="npn"?"npn_bipolar_transistor":"pnp_bipolar_transistor",zodProps:XEe,sourceFtype:"simple_transistor",shouldRenderAsSchematicBox:!1}}initPorts(){let t=this.props.type==="npn"?{pin1:["emitter","e"],pin2:["collector","c"],pin3:["base","b"]}:{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:a}=this,o=t.source_component.insert({ftype:"simple_transistor",name:this.name,transistor_type:a.type});this.source_component_id=o.source_component_id}},sRe=class extends es{get config(){let n=this.props.mosfetMode==="depletion"?"d":"e";return{componentName:"Mosfet",schematicSymbolName:`${this.props.channelType}_channel_${n}_mosfet_transistor`,zodProps:WEe,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:t}=this,a=n.source_component.insert({ftype:"simple_mosfet",name:this.name,mosfet_mode:t.mosfetMode,channel_type:t.channelType});this.source_component_id=a.source_component_id}},oRe=class extends es{_getSwitchType(){let{spst:n,spdt:t,dpst:a,dpdt:o,type:l}=this._parsedProps??{};return o?"dpdt":n?"spst":t?"spdt":a?"dpst":l??"spst"}get config(){let n=this._getSwitchType(),{isNormallyClosed:t}=this._parsedProps??{};return{componentName:"Switch",schematicSymbolName:{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"}[n]??"spst_switch",zodProps:t4e,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:t}=this,a=n.source_component.insert({ftype:"simple_switch",name:this.name,switch_type:t.type,is_normally_closed:t.isNormallyClosed??!1,are_pins_interchangeable:this._getSwitchType()==="spst"});this.source_component_id=a.source_component_id}},DW={HOLE_DIAMETER:.5,SMT_CIRCLE_DIAMETER:1.2,SMT_RECT_SIZE:2},cRe=class extends es{get config(){return{componentName:"TestPoint",schematicSymbolName:this.props.symbolName??"testpoint",zodProps:i4e,sourceFtype:qf.simple_test_point}}_getPropsWithDefaults(){let{padShape:n,holeDiameter:t,footprintVariant:a,padDiameter:o,width:l,height:p}=this._parsedProps;return!a&&t&&(a="through_hole"),a??(a="through_hole"),n??(n="circle"),a==="pad"?n==="circle"?o??(o=DW.SMT_CIRCLE_DIAMETER):n==="rect"&&(l??(l=DW.SMT_RECT_SIZE),p??(p=l)):a==="through_hole"&&(t??(t=DW.HOLE_DIAMETER)),{padShape:n,holeDiameter:t,footprintVariant:a,padDiameter:o,width:l,height:p}}_getImpliedFootprintString(){let{padShape:n,holeDiameter:t,footprintVariant:a,padDiameter:o,width:l,height:p}=this._getPropsWithDefaults();if(a==="through_hole")return`platedhole_d${t}`;if(a==="pad"){if(n==="circle")return`smtpad_circle_d${o}`;if(n==="rect")return`smtpad_rect_w${l}_h${p}`}throw new Error(`Footprint variant "${a}" with pad shape "${n}" not implemented`)}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:t}=this,{padShape:a,holeDiameter:o,footprintVariant:l,padDiameter:p,width:x,height:m}=this._getPropsWithDefaults(),g=n.source_component.insert({ftype:qf.simple_test_point,name:this.name,supplier_part_numbers:t.supplierPartNumbers,footprint_variant:l,pad_shape:a,pad_diameter:p,hole_diameter:o,width:x,height:m,are_pins_interchangeable:!0});this.source_component_id=g.source_component_id}},uRe=class extends Ya{constructor(){super(...arguments);J(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicText",zodProps:l4e}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:a}=this,o=this._getGlobalSchematicPositionBeforeLayout();t.schematic_text.insert({anchor:a.anchor??"center",text:a.text,font_size:a.fontSize,color:a.color||"#000000",position:{x:o.x,y:o.y},rotation:a.schRotation??0})}};function EVt({anchor:n,x:t,y:a,width:o,height:l,isInside:p}){switch(n){case"top_left":return{x:t,y:a+l,textAnchor:p?"top_left":"bottom_left"};case"top_center":return{x:t+o/2,y:a+l,textAnchor:p?"top_center":"bottom_center"};case"top_right":return{x:t+o,y:a+l,textAnchor:p?"top_right":"bottom_right"};case"center_left":return{x:t,y:a+l/2,textAnchor:p?"center_left":"center_right"};case"center":return{x:t+o/2,y:a+l/2,textAnchor:"center"};case"center_right":return{x:t+o,y:a+l/2,textAnchor:p?"center_right":"center_left"};case"bottom_left":return{x:t,y:a,textAnchor:p?"bottom_left":"top_left"};case"bottom_center":return{x:t+o/2,y:a,textAnchor:p?"bottom_center":"top_center"};case"bottom_right":return{x:t+o,y:a,textAnchor:p?"bottom_right":"top_right"};default:return{x:t+o/2,y:a+l,textAnchor:"center"}}}var lRe=class extends Ya{constructor(){super(...arguments);J(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicBox",zodProps:u4e,shouldRenderAsSchematicBox:!0}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:a}=this,o=.6,l=typeof a.padding=="number"?a.padding:0,p=typeof a.paddingTop=="number"?a.paddingTop:l,x=typeof a.paddingBottom=="number"?a.paddingBottom:l,m=typeof a.paddingLeft=="number"?a.paddingLeft:l,g=typeof a.paddingRight=="number"?a.paddingRight:l,_=a.overlay&&a.overlay.length>0,F=typeof a.width=="number"&&typeof a.height=="number",C,S,P,k,q,X;if(_){let ee=a.overlay.map(dt=>({selector:dt,port:this.getSubcircuit().selectOne(dt,{type:"port"})})).filter(({port:dt})=>dt!=null).map(({port:dt})=>({position:dt._getGlobalSchematicPositionAfterLayout()}));if(ee.length===0)return;let ue=ee.map(dt=>dt.position.x),ce=ee.map(dt=>dt.position.y),fe=Math.min(...ue),U=Math.max(...ue),me=Math.min(...ce),W=Math.max(...ce),pe=U-fe,he=W-me,Ae=pe===0?o:0,de=he===0?o:0,Ne=m+Ae/2,Te=g+Ae/2,Ke=p+de/2,Qe=x+de/2,pt=fe-Ne,jt=U+Te,vt=me-Qe,xt=W+Ke;C=jt-pt,S=xt-vt,P=pt+(a.schX??0),k=vt+(a.schY??0),q=P+C/2,X=k+S/2}else if(F){C=a.width,S=a.height;let Q=this._getGlobalSchematicPositionBeforeLayout();q=Q.x,X=Q.y,P=q-C/2,k=X-S/2}else return;if(t.schematic_box.insert({height:S,width:C,x:P,y:k,is_dashed:a.strokeStyle==="dashed"}),a.title){let Q=a.titleInside,ee=.1,ue=a.titleAlignment,ce=EVt({anchor:ue,x:P,y:k,width:C,height:S,isInside:Q}),fe,U,me=ce.textAnchor;Q?(fe=ue.includes("top")?-ee:ue.includes("bottom")?ee:0,U=ue.includes("left")?ee:ue.includes("right")?-ee:0):(fe=ue.includes("top")?ee:ue.includes("bottom")?-ee:0,U=ue.includes("center_left")?-ee:ue.includes("center_right")?ee:0);let W=ce.x+U,pe=ce.y+fe;t.schematic_text.insert({anchor:me,text:a.title,font_size:a.titleFontSize??.18,color:a.titleColor??"#000000",position:{x:W,y:pe},rotation:0})}}},dRe=class extends Ya{constructor(){super(...arguments);J(this,"isSchematicPrimitive",!0);J(this,"schematic_table_id",null)}get config(){return{componentName:"SchematicTable",zodProps:d4e}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:a}=this,o=this.children.filter(S=>S.componentName==="SchematicRow");if(o.length===0)return;let l=[],p=0;for(let S of o){let P=S.children.filter(k=>k.componentName==="SchematicCell");p=Math.max(p,P.length)}for(let S=0;S<o.length;S++)l[S]=[];for(let S=0;S<o.length;S++){let k=o[S].children.filter(X=>X.componentName==="SchematicCell"),q=0;for(let X=0;X<k.length;X++){for(;l[S][q];)q++;let Q=k[X],ee=Q._parsedProps.colSpan??1,ue=Q._parsedProps.rowSpan??1;for(let ce=0;ce<ue;ce++)for(let fe=0;fe<ee;fe++)l[S+ce]||(l[S+ce]=[]),l[S+ce][q+fe]=Q;q+=ee}}p=Math.max(0,...l.map(S=>S.length));let x=o.map((S,P)=>S._parsedProps.height??1),m=Array.from({length:p},(S,P)=>{let k=0;for(let q=0;q<o.length;q++){let X=l[q]?.[P];if(X){let Q=X._parsedProps.text??X._parsedProps.children,ee=X._parsedProps.width??(Q?.length??2)*.5;ee>k&&(k=ee)}}return k||10}),g=this._getGlobalSchematicPositionBeforeLayout(),_=t.schematic_table.insert({anchor_position:g,column_widths:m,row_heights:x,cell_padding:a.cellPadding,border_width:a.borderWidth,anchor:a.anchor,subcircuit_id:this.getSubcircuit()?.subcircuit_id||"",schematic_component_id:this.parent?.schematic_component_id||""});this.schematic_table_id=_.schematic_table_id;let F=new Set,C=0;for(let S=0;S<o.length;S++){let P=0;for(let k=0;k<p;k++){let q=l[S]?.[k];if(q&&!F.has(q)){F.add(q);let X=q._parsedProps,Q=X.rowSpan??1,ee=X.colSpan??1,ue=0;for(let fe=0;fe<ee;fe++)ue+=m[k+fe];let ce=0;for(let fe=0;fe<Q;fe++)ce+=x[S+fe];t.schematic_table_cell.insert({schematic_table_id:this.schematic_table_id,start_row_index:S,end_row_index:S+Q-1,start_column_index:k,end_column_index:k+ee-1,text:X.text??X.children,center:{x:g.x+P+ue/2,y:g.y-C-ce/2},width:ue,height:ce,horizontal_align:X.horizontalAlign,vertical_align:X.verticalAlign,font_size:X.fontSize??a.fontSize,subcircuit_id:this.getSubcircuit()?.subcircuit_id||""})}m[k]&&(P+=m[k])}C+=x[S]}}},pRe=class extends Ya{constructor(){super(...arguments);J(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicRow",zodProps:p4e}}},xRe=class extends Ya{constructor(){super(...arguments);J(this,"isSchematicPrimitive",!0);J(this,"canHaveTextChildren",!0)}get config(){return{componentName:"SchematicCell",zodProps:x4e}}},CVt={name:"@tscircuit/core",type:"module",version:"0.0.615",types:"dist/index.d.ts",main:"dist/index.js",module:"dist/index.js",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","@tscircuit/capacity-autorouter":"^0.0.100","@tscircuit/checks":"^0.0.64","@tscircuit/circuit-json-util":"^0.0.62","@tscircuit/footprinter":"^0.0.208","@tscircuit/import-snippet":"^0.0.4","@tscircuit/infgrid-ijump-astar":"^0.0.33","@tscircuit/log-soup":"^1.0.2","@tscircuit/math-utils":"^0.0.18","@tscircuit/miniflex":"^0.0.4","@tscircuit/props":"^0.0.281","@tscircuit/schematic-autolayout":"^0.0.6","@tscircuit/schematic-corpus":"^0.0.110","@tscircuit/schematic-match-adapt":"^0.0.16","@tscircuit/simple-3d-svg":"^0.0.38","@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.5","chokidar-cli":"^3.0.0","circuit-json":"^0.0.226","circuit-json-to-bpc":"^0.0.13","circuit-json-to-connectivity-map":"^0.0.22","circuit-json-to-simple-3d":"^0.0.6","circuit-to-svg":"^0.0.174",concurrently:"^9.1.2",debug:"^4.3.6","graphics-debug":"^0.0.60",howfat:"^0.3.8","live-server":"^1.2.2","looks-same":"^9.0.1","pkg-pr-new":"^0.0.37",react:"^19.1.0","react-dom":"^19.1.0","schematic-symbols":"^0.0.180","ts-expect":"^1.3.0","@tscircuit/circuit-json-flex":"^0.0.3",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":"*","@tscircuit/circuit-json-flex":"*","@tscircuit/schematic-corpus":"*","circuit-json-to-bpc":"*","bpc-graph":"*","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.9","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","react-reconciler-18":"npm:react-reconciler@0.29.2","transformation-matrix":"^2.16.1",zod:"^3.25.67"}},v_=class{constructor({platform:n,projectUrl:t}={}){J(this,"firstChild",null);J(this,"children");J(this,"db");J(this,"root",null);J(this,"isRoot",!0);J(this,"schematicDisabled",!1);J(this,"pcbDisabled",!1);J(this,"pcbRoutingDisabled",!1);J(this,"name");J(this,"platform");J(this,"projectUrl");J(this,"_hasRenderedAtleastOnce",!1);J(this,"_eventListeners",{});this.children=[],this.db=La([]),this.root=this,this.platform=n,this.projectUrl=t,this.pcbDisabled=n?.pcbDisabled??!1}add(n){let t;(0,fRe.isValidElement)(n)?t=D7e(n):t=n,this.children.push(t)}_getBoard(){return this.children.find(n=>n.componentName==="Board")}_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(...))");if(this.children.length===1&&this.children[0].isGroup){this.firstChild=this.children[0];return}let n=new F_({subcircuit:!0});n.parent=this,n.addAll(this.children),this.children=[n],this.firstChild=n}render(){this.firstChild||this._guessRootComponent();let{firstChild:n,db:t}=this;if(!n)throw new Error("RootCircuit has no root component");n.parent=this,n.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(n=>n._hasIncompleteAsyncEffects()?!0:n.children.some(t=>t._hasIncompleteAsyncEffects()))}getCircuitJson(){return this._hasRenderedAtleastOnce||this.render(),this.db.toArray()}toJson(){return this.getCircuitJson()}async getSvg(n){let t=await Promise.resolve().then(()=>(e7e(),QAe)).catch(a=>{throw new Error(`To use circuit.getSvg, you must install the "circuit-to-svg" package.
1037
1037
 
1038
1038
  "${a.message}"`)});if(n.view==="pcb")return t.convertCircuitJsonToPcbSvg(this.getCircuitJson());if(n.view==="schematic")return t.convertCircuitJsonToSchematicSvg(this.getCircuitJson());throw new Error(`Invalid view: ${n.view}`)}getCoreVersion(){let[n,t,a]=CVt.version.split(".").map(Number);return`${n}.${t}.${a+1}`}async preview(n){let t=typeof n=="object"?n:{previewName:n};throw new Error("project.preview is not yet implemented")}computeSchematicGlobalTransform(){return gc()}_computePcbGlobalTransformBeforeLayout(){return gc()}selectAll(n){return this._guessRootComponent(),this.firstChild?.selectAll(n)??[]}selectOne(n,t){return this._guessRootComponent(),this.firstChild?.selectOne(n,t)??null}emit(n,...t){if(this._eventListeners[n])for(let a of this._eventListeners[n])a(...t)}on(n,t){this._eventListeners[n]||(this._eventListeners[n]=[]),this._eventListeners[n].push(t)}removeListener(n,t){this._eventListeners[n]&&(this._eventListeners[n]=this._eventListeners[n].filter(a=>a!==t))}getClientOrigin(){return typeof window<"u"?window.location.origin:typeof self<"u"?self.origin:""}},AVt=v_,RVt=v_,IVt=n=>{let[t,a]=b_.default.useState(!0),[o,l]=b_.default.useState(null),[p,x]=b_.default.useState(),[m,g]=b_.default.useState();return b_.default.useEffect(()=>{a(!0),l(null),n&&setTimeout(()=>{try{let _=new v_;_.add(n),x(_),g(_.toJson())}catch(_){l(_)}a(!1)},1)},[n]),{isLoading:t,error:o,circuit:p,circuitJson:m}},E_=(n,t)=>(a,o)=>{let l=[];Array.isArray(t)?l.push(...t.flat()):typeof t=="object"&&l.push(...Object.values(t).flat(),...Object.keys(t));let p=x=>{if(x?.name&&x.name!==a)throw new Error(`Component name mismatch. Hook name: ${a}, Component prop name: ${x.name}`);let m={...o,...x,name:a},g=[];for(let _ of l)if(m[_]){let F=`.${a} > .${_}`,C=m[_];g.push({from:F,to:C}),delete m[_]}return(0,Gg.jsxs)(Gg.Fragment,{children:[(0,Gg.jsx)(n,{...m}),g.map((_,F)=>(0,Gg.jsx)("trace",{..._},F))]})};for(let x of l)p[x]=`.${a} > .${x}`;return p},wVt=E_(n=>(0,mRe.jsx)("capacitor",{...n}),MEe),SVt=n=>E_(t=>(0,hRe.jsx)("chip",{pinLabels:n,...t}),n),BVt=E_(n=>(0,yRe.jsx)("diode",{...n}),ZEe),TVt=E_(n=>(0,gRe.jsx)("led",{...n}),e4e),PVt=E_(n=>(0,DRe.jsx)("resistor",{...n}),TEe),kVt=new Proxy(n=>new Proxy({},{get:(t,a)=>`.${n} > .${a}`}),{get:(n,t)=>{let a=(...o)=>{let l=o[0];return new Proxy({},{get:(p,x)=>`.${t} > .${x}`})};return new Proxy(a,{get:(o,l)=>t==="net"?`net.${l}`:t==="subcircuit"?new Proxy({},{get:(p,x)=>new Proxy({},{get:(m,g)=>`subcircuit.${l} > .${x} > .${g}`})}):`.${t} > .${l}`,apply:(o,l,p)=>t==="net"?new Proxy({},{get:(x,m)=>`net.${m}`}):new Proxy({},{get:(x,m)=>{let g=`.${t} > .${m}`;return["U","J","CN"].some(F=>t.startsWith(F))?g:new Proxy(new String(g),{get:(F,C)=>typeof C=="symbol"||C==="toString"?()=>g:`.${t} > .${m} > .${C}`})}})})}});g7e(x7e);g7e({Bug:PW});var qIe=Cr(ju(),1);var GW={};qy(GW,{Circle:()=>qRe,Colorize:()=>$W,Cube:()=>YRe,Cuboid:()=>WRe,Custom:()=>JRe,Cylinder:()=>eIe,CylinderElliptic:()=>rIe,Ellipsoid:()=>aIe,ExtrudeFromSlices:()=>OIe,ExtrudeHelical:()=>sIe,ExtrudeLinear:()=>cIe,ExtrudeRectangular:()=>lIe,ExtrudeRotate:()=>pIe,GeodesicSphere:()=>fIe,Hull:()=>hIe,HullChain:()=>gIe,Polygon:()=>_Ie,Project:()=>FIe,Rectangle:()=>EIe,Rotate:()=>UW,RoundedCuboid:()=>AIe,RoundedCylinder:()=>IIe,Sphere:()=>SIe,Subtract:()=>TIe,Torus:()=>kIe,Translate:()=>qW,Union:()=>NIe,createJSCADRenderer:()=>VW,normalizePointToArray:()=>SR,processRotation:()=>BR,useRenderElementsToJscadPlan:()=>LIe});var zRe=Cr(jq(),1),p8=Cr(ju(),1),$Re=Cr(ya(),1),URe=Cr(LRe(),1),VRe=Cr(ya(),1),RR=Cr(ya(),1),GRe=Cr(ya(),1),IR=Cr(ya(),1),HRe=Cr(ya(),1),XRe=Cr(ya(),1),KRe=Cr(ya(),1),ZRe=Cr(ya(),1),wR=Cr(ya(),1),QRe=Cr(ya(),1),tIe=Cr(ya(),1),nIe=Cr(ya(),1),iIe=Cr(ya(),1),oIe=Cr(ya(),1),uIe=Cr(ya(),1),dIe=Cr(ya(),1),xIe=Cr(ya(),1),mIe=Cr(ya(),1),yIe=Cr(ya(),1),DIe=Cr(ya(),1),bIe=Cr(ya(),1),vIe=Cr(ya(),1),CIe=Cr(ya(),1),RIe=Cr(ya(),1),wIe=Cr(ya(),1),BIe=Cr(ya(),1),PIe=Cr(ya(),1),jIe=Cr(ya(),1),MIe=Cr(ya(),1),x8=Cr(ju(),1);function zW(n){return n.reduce((t,a)=>t.concat(Array.isArray(a)?zW(a):a),[])}var LW=n=>Array.isArray(n)&&n.length===1?n[0]:n;function KVt(n){let t=(o,l,p,x,m)=>{let g=_=>_?Array.isArray(_)?zW(_.filter(p8.default.isValidElement).map(F=>t(F.type,F.props,[],x,m))):p8.default.isValidElement(_)?[t(_.type,_.props,[],x,m)]:[]:[];if(typeof o=="function"){let _=o(l);return t(_.type,_.props,p,x,m)}switch(o){case"cube":return n.primitives.cube({size:l.size});case"sphere":return n.primitives.sphere({radius:l.radius,segments:l.segments});case"cuboid":return n.primitives.cuboid({size:l.size});case"roundedCuboid":return n.primitives.roundedCuboid({size:l.size,roundRadius:l.roundRadius});case"geodesicSphere":return n.primitives.geodesicSphere({radius:l.radius,frequency:l.frequency});case"ellipsoid":return n.primitives.ellipsoid({radius:l.radius});case"cylinder":return n.primitives.cylinder({radius:l.radius,height:l.height});case"roundedCylinder":return n.primitives.roundedCylinder({radius:l.radius,height:l.height,roundRadius:l.roundRadius});case"cylinderElliptic":return n.primitives.cylinderElliptic({radius:l.radius,height:l.height,startRadius:l.startRadius,endRadius:l.endRadius,startAngle:l.startAngle,endAngle:l.endAngle});case"torus":return n.primitives.torus({innerRadius:l.innerRadius,outerRadius:l.outerRadius,innerSegments:l.innerSegments,outerSegments:l.outerSegments,innerRotation:l.innerRotation,outerRotation:l.outerRotation,startAngle:l.startAngle});case"jscadPolygon":return n.primitives.polygon({points:l.points});case"extrudeLinear":{let{children:_,...F}=l,C=g(_);return n.extrusions.extrudeLinear({height:F.height},C)}case"extrudeRotate":{let{children:_,...F}=l,C=g(_);return n.extrusions.extrudeRotate({angle:F.angle},C)}case"extrudeRectangular":{let{children:_,...F}=l,C=g(_);return n.extrusions.extrudeRectangular({size:F.size,height:F.height},C)}case"extrudeHelical":{let{children:_,...F}=l,C=g(_);return n.extrusions.extrudeHelical({height:F.height,angle:F.angle,startAngle:F.startAngle||0,pitch:F.pitch||0,endOffset:F.endOffset||0,segmetsPerRotation:F.segmetsPerRotation||32},C)}case"extrudeFromSlices":{let{baseSlice:_,...F}=l;return n.extrusions.extrudeFromSlices(F,_)}case"project":{let{children:_,...F}=l,C=g(_);return n.extrusions.project({axis:F.axis,origin:F.origin},C)}case"colorize":{let{children:_,...F}=l,C=g(_),S=F.color;return n.colors.colorize(S,LW(C))}case"custom":{let{geometry:_}=l;return _}case"union":{let{children:_}=l;if(!Array.isArray(_)||_.length<2)throw new Error("Union must have at least two children");return _.map(C=>t(C.type,C.props,p,x,m)).reduce((C,S)=>n.booleans.union(C,S))}case"subtract":{let{children:_}=l;if(!_||_.length<2)throw new Error("Subtract must have at least one base component and one component to subtract.");let F=p8.default.Children.toArray(_).filter(p8.default.isValidElement);if(F.length<2)throw new Error("Subtract must have at least one base component and one component to subtract.");let C=t(F[0].type,F[0].props,p,x,m),S=zW(F.slice(1).map(P=>t(P.type,P.props,p,x,m)));if(!C||S.some(P=>P==null))throw new Error("One or more geometries could not be processed for subtraction.");return n.booleans.subtract(C,S)}case"translate":{let{args:_,children:F}=l,C=g(F);return n.transforms.translate(_,LW(C))}case"rotate":{let{children:_,...F}=l,C=g(_);return n.transforms.rotate(F.angles,LW(C))}case"hull":{let{children:_}=l;if(!Array.isArray(_)||_.length<2)throw new Error("Hull must have at least two children");let F=_.map(C=>t(C.type,C.props,p,x,m));return n.hulls.hull(F)}case"hullChain":{let{children:_}=l;if(!Array.isArray(_)||_.length<2)throw new Error("HullChain must have at least two children");let F=_.map(C=>t(C.type,C.props,p,x,m));return n.hulls.hullChain(F)}case"rectangle":{let{size:_}=l;return n.primitives.rectangle({size:_})}case"circle":{let{radius:_}=l;return n.primitives.circle({radius:_})}default:throw new Error(`Unknown element type: ${o}`)}};return{now:Date.now,supportsMutation:!0,supportsPersistence:!1,supportsHydration:!1,createInstance:t,createTextInstance(){throw new Error("Text elements are not supported in JSCAD")},appendInitialChild(o,l){return o},appendChild(o,l){return o},removeChild(o,l){return o},appendChildToContainer(o,l){o.push(l)},removeChildFromContainer(o,l){let p=o.indexOf(l);p!==-1&&o.splice(p,1)},prepareUpdate(){return!0},commitUpdate(o,l,p,x,m){let g=t(p,m,o,{},null);for(let _ in o)delete o[_];Object.assign(o,g)},finalizeInitialChildren(){return!1},prepareForCommit(){return null},resetAfterCommit(){},getPublicInstance(o){return o},getRootHostContext(){return{}},getChildHostContext(){return{}},shouldSetTextContent(){return!1},clearContainer(){},scheduleTimeout:setTimeout,cancelTimeout:clearTimeout,noTimeout:-1,isPrimaryRenderer:!0,getCurrentEventPriority:()=>99,getInstanceFromNode:()=>null,beforeActiveInstanceBlur:()=>{},afterActiveInstanceBlur:()=>{},prepareScopeUpdate:()=>{},getInstanceFromScope:()=>null,detachDeletedInstance:()=>{}}}function qRe({radius:n}){return(0,$Re.jsx)("circle",{radius:n})}function $W({color:n,children:t}){return Array.isArray(n)||(n=(0,URe.default)(n).rgb().array().map(a=>a/255)),(0,VRe.jsx)("colorize",{color:n,children:t})}function xo(n){let t=a=>{let{color:o,...l}=a;return o?(0,RR.jsx)($W,{color:o,children:(0,RR.jsx)(n,{...l})}):(0,RR.jsx)(n,{...l})};return t.displayName=`WithColor(${n.displayName||n.name||"Component"})`,t}var SR=n=>n?Array.isArray(n)?n:[n.x,n.y,n.z]:null;function qW({offset:n,center:t,x:a,y:o,z:l,children:p}){let x=SR(n),m=SR(t),g=[x?.[0]||m?.[0]||a||0,x?.[1]||m?.[1]||o||0,x?.[2]||m?.[2]||l||0];return(0,GRe.jsx)("translate",{args:g,children:p})}function fo(n){let t=a=>{let{center:o,offset:l,...p}=a;return!o&&!l?(0,IR.jsx)(n,{...p}):(0,IR.jsx)(qW,{offset:o||l,children:(0,IR.jsx)(n,{...p})})};return t.displayName=`WithOffset(${n.displayName||n.name||"Component"})`,t}var JVt=({size:n})=>(0,HRe.jsx)("cube",{size:n}),YRe=fo(xo(JVt)),ZVt=({size:n})=>(0,XRe.jsx)("cuboid",{size:n}),WRe=fo(xo(ZVt));function JRe({geometry:n}){return(0,KRe.jsx)("custom",{geometry:n})}var d8=n=>{if(typeof n=="string"){let t=n.replace(/[^\d.-]/g,""),a=parseFloat(t);if(!isNaN(a))return n.toLowerCase().includes("deg")?a*Math.PI/180:a;throw new Error(`Invalid rotation value: ${n}`)}return n},BR=n=>typeof n=="string"||typeof n=="number"?[0,0,d8(n)]:Array.isArray(n)?n.map(d8):n&&typeof n=="object"?[d8(n.x),d8(n.y),d8(n.z)]:[0,0,0],QVt=({rotation:n,angles:t,children:a})=>{let o=BR(n||t);return(0,ZRe.jsx)("rotate",{angles:o,children:a})},UW=fo(xo(QVt));function eGt(n){let t=a=>{let{rotation:o,...l}=a;return o?(0,wR.jsx)(UW,{rotation:o,children:(0,wR.jsx)(n,{...l})}):(0,wR.jsx)(n,{...l})};return t.displayName=`WithRotation(${n.displayName||n.name||"Component"})`,t}var tGt=({radius:n,height:t})=>(0,QRe.jsx)("cylinder",{radius:n,height:t}),eIe=xo(fo(eGt(tGt))),rGt=({height:n,startRadius:t,endRadius:a,segments:o=32,startAngle:l=0,endAngle:p=Math.PI*2})=>(0,tIe.jsx)("cylinderElliptic",{height:n,startRadius:t,endRadius:a,segments:o,startAngle:l,endAngle:p}),rIe=fo(xo(rGt)),nGt=({radius:n})=>(0,nIe.jsx)("ellipsoid",{radius:n}),aIe=fo(xo(nGt)),aGt=({height:n,angle:t,startAngle:a,pitch:o,endOffset:l,segmetsPerRotation:p,children:x})=>(0,iIe.jsx)("extrudeHelical",{height:n,angle:t,startAngle:a,pitch:o,endOffset:l,segmetsPerRotation:p,children:x}),sIe=fo(xo(aGt)),iGt=({height:n,twistAngle:t,twistSteps:a,children:o})=>(0,oIe.jsx)("extrudeLinear",{height:n,twistAngle:t,twistSteps:a,children:o}),cIe=fo(xo(iGt)),sGt=({size:n,height:t,children:a})=>(0,uIe.jsx)("extrudeRectangular",{size:n,height:t,children:a}),lIe=fo(xo(sGt)),oGt=({angle:n,startAngle:t,segments:a,children:o})=>(0,dIe.jsx)("extrudeRotate",{angle:n,startAngle:t,segments:a,children:o}),pIe=fo(xo(oGt)),cGt=({radius:n,frequency:t})=>(0,xIe.jsx)("geodesicSphere",{radius:n,frequency:t}),fIe=fo(xo(cGt)),uGt=({children:n})=>(0,mIe.jsx)("hull",{children:n}),hIe=fo(xo(uGt)),lGt=({children:n})=>(0,yIe.jsx)("hullChain",{children:n}),gIe=fo(xo(lGt));function _Ie({points:n}){return(0,DIe.jsx)("jscadPolygon",{points:n})}function FIe({axis:n,origin:t,children:a}){return(0,bIe.jsx)("project",{axis:n,origin:t,children:a})}function EIe({size:n}){return(0,vIe.jsx)("rectangle",{size:n})}var dGt=({size:n,roundRadius:t})=>(0,CIe.jsx)("roundedCuboid",{size:n,roundRadius:t}),AIe=fo(xo(dGt)),pGt=({radius:n,height:t,roundRadius:a})=>(0,RIe.jsx)("roundedCylinder",{radius:n,height:t,roundRadius:a}),IIe=fo(xo(pGt)),xGt=({radius:n,segments:t})=>(0,wIe.jsx)("sphere",{radius:n,segments:t||32}),SIe=xo(fo(xGt)),fGt=({children:n})=>{if(!Array.isArray(n)||n.length<2)throw new Error("Subtract must have at least two children");return(0,BIe.jsx)("subtract",{children:n})},TIe=fo(xo(fGt)),mGt=({innerRadius:n,outerRadius:t,innerSegments:a=32,outerSegments:o=32,innerRotation:l=0,outerRotation:p=1,startAngle:x=0})=>(0,PIe.jsx)("torus",{innerRadius:n,outerRadius:t,innerSegments:a,outerSegments:o,innerRotation:l,outerRotation:p,startAngle:x}),kIe=fo(xo(mGt));function NIe({children:n}){return(0,jIe.jsx)("union",{children:n})}var hGt=({numberOfSlices:n,capStart:t,capEnd:a,close:o,repair:l,baseSlice:p,callback:x})=>(0,MIe.jsx)("extrudeFromSlices",{numberOfSlices:n,capStart:t,capEnd:a,close:o,repair:l,baseSlice:p,callback:x}),OIe=fo(xo(hGt)),LIe=(n,t)=>{let{renderer:a}=x8.default.useMemo(()=>({renderer:VW(n)}),[n]),[o,l]=x8.default.useState(null),[p,x]=x8.default.useState(!0),m=x8.default.useMemo(()=>{x(!0);let g=[],_=a.createJSCADRoot(g);try{_.render(t),x(!1),l(null)}catch(F){l(F)}return g},[t]);return{loading:p,jscadElms:m,error:o}};function VW(n){let t=KVt(n);function a(o){let l=(0,zRe.default)(t),p=l.createContainer(o,0,null,!1,null,"",x=>console.error(x),null);return{render(x){l.updateContainer(x,p,null,()=>{})}}}return{createJSCADRoot:a}}var HW=new Map,Fc=async(n,t)=>{let a=new URLSearchParams({...t,json:"true"}).toString();if(HW.has(a))return HW.get(a);let l=await(await fetch(`https://jlcsearch.tscircuit.com/${n}/list?${a}`)).json();return HW.set(a,l),l},zIe={findPart:async({sourceComponent:n,footprinterString:t})=>{if(n.type==="source_component"&&n.ftype==="simple_resistor"){let{resistors:a}=await Fc("resistors",{resistance:n.display_resistance??n.resistance,package:t});return{jlcpcb:(a??[]).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_capacitor"){t?.includes("cap")&&(t=t.replace("cap",""));let{capacitors:a}=await Fc("capacitors",{capacitance:n.display_capacitance??n.capacitance,package:t});return{jlcpcb:(a??[]).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_pin_header"){let a;t?.includes("_p")&&(a=Number(t.split("_p")[1]));let{headers:o}=await Fc("headers",a?{pitch:a,num_pins:n.pin_count,gender:n.gender}:{num_pins:n.pin_count,gender:n.gender});return{jlcpcb:(o??[]).map(l=>`C${l.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_potentiometer"){let{potentiometers:a}=await Fc("potentiometers",{resistance:n.max_resistance,package:t});return{jlcpcb:(a??[]).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_diode"){let{diodes:a}=await Fc("diodes",{package:t});return{jlcpcb:(a??[]).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_chip"){let{chips:a}=await Fc("chips",{package:t});return{jlcpcb:(a??[]).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_transistor"){let{transistors:a}=await Fc("transistors",{package:t,transistor_type:n.transistor_type});return{jlcpcb:(a??[]).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_power_source"){let{power_sources:a}=await Fc("power_sources",{voltage:n.voltage,package:t});return{jlcpcb:(a??[]).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_inductor"){let{inductors:a}=await Fc("inductors",{inductance:n.inductance,package:t});return{jlcpcb:(a??[]).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_crystal"){let{crystals:a}=await Fc("crystals",{frequency:n.frequency,load_capacitance:n.load_capacitance,package:t});return{jlcpcb:(a??[]).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_mosfet"){let{mosfets:a}=await Fc("mosfets",{package:t,mosfet_mode:n.mosfet_mode,channel_type:n.channel_type});return{jlcpcb:(a??[]).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_resonator"){let{resonators:a}=await Fc("resonators",{frequency:n.frequency,package:t});return{jlcpcb:(a??[]).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_switch"){let{switches:a}=await Fc("switches",{switch_type:n.type,package:t});return{jlcpcb:(a??[]).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_led"){let{leds:a}=await Fc("leds",{package:t});return{jlcpcb:(a??[]).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_fuse"){let{fuses:a}=await Fc("fuses",{package:t});return{jlcpcb:(a??[]).map(o=>`C${o.lcsc}`).slice(0,3)}}return{}}};var $Ie=()=>({partsEngine:zIe});var UIe=Cr(e0(),1),phr=(0,UIe.default)("tsci:eval:execution-context");function YW(n,t={}){globalThis.React=qIe;let a=new v_({platform:t.platform||$Ie()});return t.name&&(a.name=t.name),{fsMap:{},entrypoint:"",preSuppliedImports:{"@tscircuit/core":FR,tscircuit:FR,"@tscircuit/math-utils":yY,react:qIe,"jscad-fiber":GW,"@tscircuit/props":{}},circuit:a,...n}}function f8(n){let t=n;return t=t.replace(/\\/g,"/"),t=t.trim(),t.startsWith("./")&&(t=t.slice(2)),t.startsWith("/")&&(t=t.slice(1)),t}function VIe(n){let t={};for(let[a,o]of Object.entries(n))t[f8(a)]=o;return t}function Uf(n){if(!n)return".";let a=n.replace(/\\/g,"/").replace(/\/+$/,"");return a.indexOf("/")===-1?".":a.substring(0,a.lastIndexOf("/"))||"/"}function XW(n,t){if(n.startsWith("../")){let a=Uf(t);return XW(n.slice(3),a)}return n.startsWith("./")?XW(n.slice(2),t):n.startsWith("/")?n.slice(1):`${t}/${n}`}var m8=(n,t,a)=>{let o=a?XW(n,a):n,l=new Set(Array.isArray(t)?t:Object.keys(t));if(l.has(o))return o;let p=new Map;for(let g of l)p.set(f8(g),g);let x=f8(o);if(p.has(x))return p.get(x);let m=["tsx","ts","json","js","jsx"];for(let g of m){let _=`${x}.${g}`;if(p.has(_))return p.get(_)}if(!n.startsWith("./")&&!n.startsWith("../")){let g=f8(n);if(p.has(g))return p.get(g);for(let _ of m){let F=`${g}.${_}`;if(p.has(F))return p.get(F)}}return null},TR=(n,t)=>{let a=m8(n,t);if(!a)throw new Error(`File not found "${n}", available paths:
1039
1039
 
@@ -1043,7 +1043,7 @@ ${Object.keys(t).join(", ")}`);return a};function h8(n,t,a){globalThis.__tscircu
1043
1043
  var module = { exports };
1044
1044
  var circuit = globalThis.__tscircuit_circuit;
1045
1045
  ${n};
1046
- return module;`.trim();return Function(o).call(globalThis)}var qhr=Cr(kR(),1);var WW=Cr(kR(),1);var HIe=n=>{let t=/^\s*import\s+(?:(?:[\w\s]+,\s*)?(?:\*\s+as\s+[\w\s]+|\{[\s\w,]+\}|\w+)\s+from\s+)?['"](.+?)['"]/gm,a=[],o;for(;(o=t.exec(n))!==null;)a.push(o[1]);let l=/^\s*export\s+(?:\*|(?:\{[\s\w,]+\}))\s+from\s+['"](.+?)['"]/gm,p;for(;(p=l.exec(n))!==null;)a.push(p[1]);return a};var YIe=Cr(e0(),1),R_=(0,YIe.default)("tsci:eval:import-local-file"),jR=async(n,t,a=0)=>{R_("importLocalFile called with:",{importName:n});let{fsMap:o,preSuppliedImports:l}=t,p=TR(n,o);if(R_("fsPath:",p),!t.fsMap[p])throw R_("fsPath not found in fsMap:",p),new Error(`File "${p}" not found`);let x=o[p];if(R_("fileContent:",x?.slice(0,100)),p.endsWith(".json")){let m=JSON.parse(x);l[p]={__esModule:!0,default:m}}else if(p.endsWith(".tsx")||p.endsWith(".ts")){let m=HIe(x);for(let _ of m)l[_]||await y8(_,t,a+1,{cwd:Uf(p)});let g=WW.transform(x,{presets:["react","typescript"],plugins:["transform-modules-commonjs"],filename:"virtual.tsx"});if(!g||!g.code)throw new Error("Failed to transform code");try{R_("evalCompiledJs called with:",{code:g.code?.slice(0,100),dirname:Uf(p)});let _=h8(g.code,l,Uf(p));R_("importRunResult:",{fsPath:p,importRunResult:_}),l[p]=_.exports}catch(_){throw new Error(`Eval compiled js error for "${n}": ${_.message}`)}}else if(p.endsWith(".js")){let m=WW.transform(x,{presets:["env"],plugins:["transform-modules-commonjs"],filename:p});if(!m||!m.code)throw new Error("Failed to transform JS code");l[p]=h8(m.code,l,Uf(p)).exports}else throw new Error(`Unsupported file extension "${p.split(".").pop()}" for "${p}"`)};var whr=Cr(kR(),1);async function XIe(n,t,a=0){let{preSuppliedImports:o}=t,l=n.replace("@tsci/","").replace(".","/"),{cjs:p,error:x}=await fetch(`${t.cjsRegistryUrl}/${l}`).then(async m=>({cjs:await m.text(),error:null})).catch(m=>({error:m,cjs:null}));if(x){console.error("Error fetching import",n,x);return}try{o[n]=h8(p,o).exports}catch(m){console.error("Error importing snippet",m)}}function yGt(n,t,a){return{fsMap:t,extensions:[".js",".jsx",".ts",".tsx",".json"],basePath:a,modulePath:n}}function gGt(n,t){let a=`${n}/package.json`;if(!t.fsMap[a])return null;try{return JSON.parse(t.fsMap[a])}catch{return null}}function JW(n,t){if(t.fsMap[n])return n;for(let a of t.extensions){let o=n.replace(/\.js$|\.jsx$/,"")+a;if(t.fsMap[o])return o}return null}function KW(n,t,a){let o=`${n}/${t.replace(/^\.\//,"")}`;return JW(o,a)}function DGt(n,t,a,o){if(!t.exports)return null;let l=t.exports["."];if(a===""&&l&&typeof l=="string"){let m=KW(n,l,o);if(m)return m}let p=a?t.exports[`./${a}`]:null;if(p&&typeof p=="string"){let m=KW(n,p,o);if(m)return m}let x=t.exports.import;if(a===""&&x&&typeof x=="string"){let m=KW(n,x,o);if(m)return m}return null}function _Gt(n,t,a){let o=t.module||t.main||"index.js",l=`${n}/${o}`;return JW(l,a)}function bGt(n,t,a){if(!t){for(let p of a.extensions){let x=`${n}/index${p}`;if(a.fsMap[x])return x}return null}let o=`${n}/${t}`,l=JW(o,a);if(l)return l;for(let p of a.extensions){let x=`${o}/index${p}`;if(a.fsMap[x])return x}return null}function WIe(n,t){let a=t.modulePath.split("/"),o=a[0].startsWith("@")?a.slice(0,2).join("/"):a[0],l=a.slice(o.includes("/")?2:1).join("/"),p=`${n=="."?"":`${n}/`}node_modules/${o}`,x=gGt(p,t);if(x){let _=DGt(p,x,l,t);if(_)return _;let F=_Gt(p,x,t);if(F)return F}let m=bGt(p,l,t);if(m)return m;let g=Uf(n);return g&&g!==n?WIe(g,t):null}function NR(n,t,a){let o=yGt(n,t,a);return WIe(o.basePath,o)}var KIe=async(n,t,a=0)=>{let{preSuppliedImports:o}=t;if(o[n])return;let l=NR(n,t.fsMap,"");if(!l)throw new Error(`Node module "${n}" not found`);await jR(l,t,a),o[n]=o[l];let p=l.replace(/^node_modules\//,"");if(o[p]=o[l],l.endsWith("/index.tsx")||l.endsWith("/index.ts")||l.endsWith("/index.js")){let m=l.replace(/\/index\.(tsx?|js)$/,"").replace(/^node_modules\//,"");if(o[m]=o[l],m.startsWith("@")){let g=m.split("/");if(g.length>=2){let _=`${g[0]}/${g[1]}`;o[_]=o[l]}}}};var ZIe=Cr(e0(),1),JIe=(0,ZIe.default)("tsci:eval:import-eval-path");async function y8(n,t,a=0,o={}){JIe("importEvalPath called with:",{importName:n,depth:a,opts:o}),JIe(`${" ".repeat(a)}\u27A1\uFE0F`,n);let{preSuppliedImports:l}=t;if(l[n]||n.startsWith("./")&&l[n.slice(2)])return;if(a>5){console.log("Max depth for imports reached");return}let p=m8(n,t.fsMap,o.cwd);if(p)return jR(p,t,a);if(NR(n,t.fsMap,o.cwd||""))return KIe(n,t,a);if(n.startsWith("@tsci/"))return XIe(n,t,a);throw new Error(`Unresolved import "${n}" ${o.cwd?`from directory "${o.cwd}"`:""}`)}var QIe=Cr(e0(),1),FGt=(0,QIe.default)("tsci:eval:setupDefaultEntrypointIfNeeded"),ewe=n=>{if(!n.entrypoint&&!n.mainComponentPath)if("index.tsx"in n.fsMap)n.mainComponentPath="index.tsx";else if("index.ts"in n.fsMap)n.mainComponentPath="index.ts";else if(Object.keys(n.fsMap).filter(t=>t.endsWith(".tsx")).length===1)n.mainComponentPath=Object.keys(n.fsMap)[0];else if("tscircuit.config.json"in n.fsMap){let t=n.fsMap["tscircuit.config.json"];try{let a=JSON.parse(t);a.mainEntrypoint&&(n.entrypoint=a.mainEntrypoint)}catch(a){console.warn("Failed to parse tscircuit.config.json:",a)}}else throw new Error("Either entrypoint or mainComponentPath must be provided (no index file, could not infer entrypoint)");if(!n.entrypoint&&n.mainComponentPath){n.entrypoint="entrypoint.tsx";let t=n.fsMap[TR(n.mainComponentPath,n.fsMap)];if(!t)throw new Error(`Main component path "${n.mainComponentPath}" not found in fsMap. Available paths: ${Object.keys(n.fsMap).join(", ")}`);let a=t.includes("<board"),o=t.includes("@tsci/")||t.includes('from "@tsci'),l=t.includes("<group"),p=!a&&!o&&!l;n.fsMap[n.entrypoint]=`
1046
+ return module;`.trim();return Function(o).call(globalThis)}var qhr=Cr(kR(),1);var WW=Cr(kR(),1);var HIe=n=>{let t=/^\s*import\s+(?:(?:[\w\s]+,\s*)?(?:\*\s+as\s+[\w\s]+|\{[\s\w,]+\}|\w+)\s+from\s+)?['"](.+?)['"]/gm,a=[],o;for(;(o=t.exec(n))!==null;)a.push(o[1]);let l=/^\s*export\s+(?:\*|(?:\{[\s\w,]+\}))\s+from\s+['"](.+?)['"]/gm,p;for(;(p=l.exec(n))!==null;)a.push(p[1]);return a};var YIe=Cr(e0(),1),R_=(0,YIe.default)("tsci:eval:import-local-file"),jR=async(n,t,a=0)=>{R_("importLocalFile called with:",{importName:n});let{fsMap:o,preSuppliedImports:l}=t,p=TR(n,o);if(R_("fsPath:",p),!t.fsMap[p])throw R_("fsPath not found in fsMap:",p),new Error(`File "${p}" not found`);let x=o[p];if(R_("fileContent:",x?.slice(0,100)),p.endsWith(".json")){let m=JSON.parse(x);l[p]={__esModule:!0,default:m}}else if(p.endsWith(".tsx")||p.endsWith(".ts")){let m=HIe(x);for(let _ of m)l[_]||await y8(_,t,a+1,{cwd:Uf(p)});let g=WW.transform(x,{presets:["react","typescript"],plugins:["transform-modules-commonjs"],filename:"virtual.tsx"});if(!g||!g.code)throw new Error("Failed to transform code");try{R_("evalCompiledJs called with:",{code:g.code?.slice(0,100),dirname:Uf(p)});let _=h8(g.code,l,Uf(p));R_("importRunResult:",{fsPath:p,importRunResult:_}),l[p]=_.exports}catch(_){throw new Error(`Eval compiled js error for "${n}": ${_.message}`)}}else if(p.endsWith(".js")){let m=WW.transform(x,{presets:["env"],plugins:["transform-modules-commonjs"],filename:p});if(!m||!m.code)throw new Error("Failed to transform JS code");l[p]=h8(m.code,l,Uf(p)).exports}else throw new Error(`Unsupported file extension "${p.split(".").pop()}" for "${p}"`)};var whr=Cr(kR(),1);async function XIe(n,t,a=0){let{preSuppliedImports:o}=t,l=n.replace("@tsci/","").replace(".","/"),{cjs:p,error:x}=await fetch(`${t.cjsRegistryUrl}/${l}`).then(async m=>({cjs:await m.text(),error:null})).catch(m=>({error:m,cjs:null}));if(x){console.error("Error fetching import",n,x);return}try{o[n]=h8(p,o).exports}catch(m){console.error("Error importing snippet",m)}}function yGt(n,t,a){return{fsMap:t,extensions:[".js",".jsx",".ts",".tsx",".json"],basePath:a,modulePath:n}}function gGt(n,t){let a=`${n}/package.json`;if(!t.fsMap[a])return null;try{return JSON.parse(t.fsMap[a])}catch{return null}}function JW(n,t){if(t.fsMap[n])return n;for(let a of t.extensions){let o=n.replace(/\.js$|\.jsx$/,"")+a;if(t.fsMap[o])return o}return null}function KW(n,t,a){let o=`${n}/${t.replace(/^\.\//,"")}`;return JW(o,a)}function DGt(n,t,a,o){if(!t.exports)return null;let l=t.exports["."];if(a===""&&l&&typeof l=="string"){let m=KW(n,l,o);if(m)return m}let p=a?t.exports[`./${a}`]:null;if(p&&typeof p=="string"){let m=KW(n,p,o);if(m)return m}let x=t.exports.import;if(a===""&&x&&typeof x=="string"){let m=KW(n,x,o);if(m)return m}return null}function _Gt(n,t,a){let o=t.module||t.main||"index.js",l=`${n}/${o}`;return JW(l,a)}function bGt(n,t,a){if(!t){for(let p of a.extensions){let x=`${n}/index${p}`;if(a.fsMap[x])return x}return null}let o=`${n}/${t}`,l=JW(o,a);if(l)return l;for(let p of a.extensions){let x=`${o}/index${p}`;if(a.fsMap[x])return x}return null}function WIe(n,t){let a=t.modulePath.split("/"),o=a[0].startsWith("@")?a.slice(0,2).join("/"):a[0],l=a.slice(o.includes("/")?2:1).join("/"),p=`${n=="."?"":`${n}/`}node_modules/${o}`,x=gGt(p,t);if(x){let _=DGt(p,x,l,t);if(_)return _;let F=_Gt(p,x,t);if(F)return F}let m=bGt(p,l,t);if(m)return m;let g=Uf(n);return g&&g!==n?WIe(g,t):null}function NR(n,t,a){let o=yGt(n,t,a);return WIe(o.basePath,o)}var KIe=async(n,t,a=0)=>{let{preSuppliedImports:o}=t;if(o[n])return;let l=NR(n,t.fsMap,"");if(!l)throw new Error(`Node module "${n}" not found`);await jR(l,t,a),o[n]=o[l];let p=l.replace(/^node_modules\//,"");if(o[p]=o[l],l.endsWith("/index.tsx")||l.endsWith("/index.ts")||l.endsWith("/index.js")){let m=l.replace(/\/index\.(tsx?|js)$/,"").replace(/^node_modules\//,"");if(o[m]=o[l],m.startsWith("@")){let g=m.split("/");if(g.length>=2){let _=`${g[0]}/${g[1]}`;o[_]=o[l]}}}};var ZIe=Cr(e0(),1),JIe=(0,ZIe.default)("tsci:eval:import-eval-path");async function y8(n,t,a=0,o={}){JIe("importEvalPath called with:",{importName:n,depth:a,opts:o}),JIe(`${" ".repeat(a)}\u27A1\uFE0F`,n);let{preSuppliedImports:l}=t;if(l[n]||n.startsWith("./")&&l[n.slice(2)])return;if(a>5){console.log("Max depth for imports reached");return}let p=m8(n,t.fsMap,o.cwd);if(p)return jR(p,t,a);if(NR(n,t.fsMap,o.cwd||""))return KIe(n,t,a);if(n.startsWith("@tsci/"))return XIe(n,t,a);throw new Error(`Unresolved import "${n}" ${o.cwd?`from directory "${o.cwd}"`:""}`)}var QIe=Cr(e0(),1),FGt=(0,QIe.default)("tsci:eval:setupDefaultEntrypointIfNeeded"),ewe=n=>{if(!n.entrypoint&&!n.mainComponentPath)if("index.tsx"in n.fsMap)n.mainComponentPath="index.tsx";else if("index.ts"in n.fsMap)n.mainComponentPath="index.ts";else if(Object.keys(n.fsMap).filter(t=>t.endsWith(".tsx")).length===1)n.mainComponentPath=Object.keys(n.fsMap)[0];else if("tscircuit.config.json"in n.fsMap){let t=n.fsMap["tscircuit.config.json"];try{let a=JSON.parse(t);a.mainEntrypoint&&(n.entrypoint=a.mainEntrypoint)}catch(a){console.warn("Failed to parse tscircuit.config.json:",a)}}else throw new Error("Either entrypoint or mainComponentPath must be provided (no index file, could not infer entrypoint)");if(!n.entrypoint&&n.mainComponentPath){if(n.entrypoint="entrypoint.tsx",!n.fsMap[TR(n.mainComponentPath,n.fsMap)])throw new Error(`Main component path "${n.mainComponentPath}" not found in fsMap. Available paths: ${Object.keys(n.fsMap).join(", ")}`);n.fsMap[n.entrypoint]=`
1047
1047
  import * as UserComponents from "./${n.mainComponentPath}";
1048
1048
 
1049
1049
  ${n.mainComponentName?`
@@ -1057,14 +1057,8 @@ ${Object.keys(t).join(", ")}`);return a};function h8(n,t,a){globalThis.__tscircu
1057
1057
  console.log("ComponentToRender " + ComponentToRender.toString(), { ComponentToRender })
1058
1058
  `:""}
1059
1059
 
1060
- circuit.add(
1061
- ${p?`
1062
- <board>
1063
- <ComponentToRender name="U1" ${n.mainComponentProps?`{...${JSON.stringify(n.mainComponentProps,null,2)}}`:""} />
1064
- </board>
1065
- `:`
1066
- <ComponentToRender ${n.mainComponentProps?`{...${JSON.stringify(n.mainComponentProps,null,2)}}`:""} />
1067
- `}
1060
+ circuit.add(
1061
+ <ComponentToRender ${n.mainComponentProps?`{...${JSON.stringify(n.mainComponentProps,null,2)}}`:""} />
1068
1062
  );
1069
1063
  `}!n.name&&n.mainComponentName&&(n.name=n.mainComponentName)};globalThis.React=vGt;var Mo=null,Qm={snippetsApiBaseUrl:"https://registry-api.tscircuit.com",cjsRegistryUrl:"https://cjs.tscircuit.com",verbose:!1,platform:void 0},fx={};function twe(n){for(let t in fx)for(let a of fx[t])n.on(t,a)}var EGt={setSnippetsApiBaseUrl:async n=>{Qm.snippetsApiBaseUrl=n},setPlatformConfig:async n=>{Qm.platform=n},version:async()=>"0.0.0",async executeWithFsMap(n){Qm.verbose&&console.log("[Worker] executeWithFsMap called with:",{entrypoint:n.entrypoint,fsMapKeys:Object.keys(n.fsMap),name:n.name}),ewe(n);let t=n.entrypoint;if(Mo=YW(Qm,{name:n.name,platform:Qm.platform}),twe(Mo.circuit),Mo.fsMap=VIe(n.fsMap),!Mo.fsMap[t])throw new Error(`Entrypoint "${n.entrypoint}" not found`);globalThis.__tscircuit_circuit=Mo.circuit,t.startsWith("./")||(t=`./${t}`),await y8(t,Mo)},async execute(n,t={}){Qm.verbose&&console.log("[Worker] execute called with code length:",n.length),Mo=YW(Qm,{...t,platform:Qm.platform}),twe(Mo.circuit),Mo.fsMap["entrypoint.tsx"]=n,globalThis.__tscircuit_circuit=Mo.circuit,await y8("./entrypoint.tsx",Mo)},on:(n,t)=>{fx[n]??(fx[n]=[]),fx[n].push(t),Mo?.circuit.on(n,t)},renderUntilSettled:async()=>{if(!Mo)throw new Error("No circuit has been created");await Mo.circuit.renderUntilSettled()},getCircuitJson:async()=>{if(!Mo)throw new Error("No circuit has been created");return Mo.circuit.getCircuitJson()},clearEventListeners:()=>{if(Mo?.circuit)for(let n in fx)for(let t of fx[n]){let a=Mo.circuit;typeof a.removeListener=="function"&&a.removeListener(n,t)}for(let n in fx)delete fx[n]},kill:async()=>{}};hC(EGt);
1070
1064
  /*! Bundled license information: