@tscircuit/eval 0.0.353 → 0.0.354

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.
@@ -227,10 +227,10 @@ ${_.join(`
227
227
  `)}
228
228
  </div>`},Bgt=e=>{let t=e.layout(),n={title:"CssGrid",coordinateSystem:"screen",lines:[],circles:[],points:[],rects:[],texts:[]},{cells:i}=t;for(let r of i){let{x:o,y:s,width:a,height:c,key:l}=r;n.rects.push({center:{x:o+a/2,y:s+c/2},width:a,height:c,fill:TB(l),label:l})}return n};function lx(e){return e.replace(/repeat\((\d+),\s*([^)]+)\)/g,(t,n,i)=>Array(Number(n)).fill(i.trim()).join(" "))}function ux(e){return e.trim().split(/\s+/).filter(Boolean)}function wB(e){return e?ux(lx(e)).length:0}function SB(e,t){if(e==="auto")return{fr:1};if(e.endsWith("%")){let i=parseFloat(e);return t!=null?t*i/100:0}if(e.endsWith("px"))return parseFloat(e);if(e.endsWith("em"))return parseFloat(e)*16;if(e.endsWith("fr"))return{fr:parseFloat(e)};let n=parseFloat(e);return Number.isNaN(n)?0:n}function PB(e,t){return e>0?e:t+2+e}var jgt=e=>{let t=e.opts,n=t.children,i,r;if("gridTemplate"in t&&typeof t.gridTemplate=="string"){let[I,k]=t.gridTemplate.split("/");i=I?.trim(),r=k?.trim()}else i=typeof t.gridTemplateRows=="string"?t.gridTemplateRows:void 0,r=typeof t.gridTemplateColumns=="string"?t.gridTemplateColumns:void 0;let o=wB(r),s=wB(i);function a(I,k,M,A){if(!I)return 0;let L=lx(I),B=ux(L),D=B.length,V=0,X=!1;for(let Q=0;Q<B.length;Q++){let J=B[Q];if(J.endsWith("px"))V+=parseFloat(J);else if(J.endsWith("em"))V+=parseFloat(J)*16;else if(J.endsWith("fr")||J==="auto"){X=!0;let _t=0;for(let st of k){let it=M?st.columnStart||st.column:st.rowStart||st.row,et=M?st.columnSpan||1:st.rowSpan||1,vt=M?st.contentWidth:st.contentHeight,mt=(typeof it=="number"?it:parseInt(it||"1"))-1,Tt=typeof et=="number"?et:parseInt(et.toString());if(mt<=Q&&Q<mt+Tt&&vt){let Ot=typeof vt=="string"&&vt.endsWith("px")?parseFloat(vt):typeof vt=="number"?vt:0;_t=Math.max(_t,Ot/Tt)}}V+=_t}}let W=A*(D-1);return V+W}function c(I,k,M,A=!0,L=1){if(!I)return[];if(k==null){let et=lx(I),vt=ux(et),mt=vt.length,Tt=j=>j===void 0?0:typeof j=="number"?j:(j.endsWith("px"),parseFloat(j)),Ot=new Array(mt).fill(0),pt=0;for(let j of n){let q=A?typeof j.columnSpan=="number"?j.columnSpan:j.columnSpan?parseInt(j.columnSpan.toString()):1:typeof j.rowSpan=="number"?j.rowSpan:j.rowSpan?parseInt(j.rowSpan.toString()):1,Y=A?j.contentWidth:j.contentHeight,nt=Tt(Y)/q,lt;A?(j.columnStart!==void 0||j.column!==void 0)&&(lt=parseInt(j.columnStart??j.column)-1):(j.rowStart!==void 0||j.row!==void 0)&&(lt=parseInt(j.rowStart??j.row)-1),(lt===void 0||Number.isNaN(lt))&&(A?lt=pt%mt:lt=Math.floor(pt/L),pt+=q);for(let ut=0;ut<q&&lt+ut<mt;ut++)Ot[lt+ut]=Math.max(Ot[lt+ut],nt)}return vt.forEach((j,q)=>{let Y=SB(j,void 0);typeof Y=="number"&&(Ot[q]=Y)}),Ot}let B=lx(I),D=ux(B),V=D.length,X=k;X==null&&(X=a(I,n,A,M));let W=X-M*(V-1),Q=0,J=0,_t=[],st=[];D.forEach((et,vt)=>{let mt=SB(et,W);typeof mt=="number"?(st.push(mt),Q+=mt):mt&&typeof mt=="object"&&"fr"in mt?(st.push(mt),J+=mt.fr,_t.push({idx:vt,fr:mt.fr})):(st.push(0),Q+=0)});let it=Math.max(W-Q,0);return st.map(et=>typeof et=="number"?et:J>0?it/J*et.fr:0)}let l=typeof t.gap=="number"?t.gap:Array.isArray(t.gap)?t.gap[0]:0,u=typeof t.gap=="number"?t.gap:Array.isArray(t.gap)?t.gap[1]:0,h=c(i,t.containerHeight,l,!1,o||1),f=c(r,t.containerWidth,u,!0,s||1),_=h.length,y=f.length;y===0&&n.length>0&&(y=1);let x=[],v=0;for(let I of n){let k=I.rowStart!==void 0?I.rowStart:I.row,M=I.columnStart!==void 0?I.columnStart:I.column,A=I.rowSpan!==void 0?typeof I.rowSpan=="string"?parseInt(I.rowSpan):I.rowSpan:1,L=I.columnSpan!==void 0?typeof I.columnSpan=="string"?parseInt(I.columnSpan):I.columnSpan:1;if(I.rowEnd!==void 0){let V=typeof I.rowEnd=="string"?parseInt(I.rowEnd):I.rowEnd;k!==void 0?A=V-(typeof k=="string"?parseInt(k):k):k=V-A}if(I.columnEnd!==void 0){let V=typeof I.columnEnd=="string"?parseInt(I.columnEnd):I.columnEnd;M!==void 0?L=V-(typeof M=="string"?parseInt(M):M):M=V-L}if(typeof k=="string"&&(k=parseInt(k)),typeof M=="string"&&(M=parseInt(M)),typeof k=="number"&&k<0&&(k=PB(k,_)),typeof M=="number"&&M<0&&(M=PB(M,y)),k===void 0&&M!==void 0)k=1;else if(M===void 0&&k!==void 0)M=1;else if(k===void 0&&M===void 0){let V=v;k=Math.floor(V/y)+1,M=V%y+1}let B=k-1,D=M-1;A=Math.max(1,A),L=Math.max(1,L),x.push({key:I.key,row:B,column:D,rowSpan:A,columnSpan:L,x:0,y:0,width:0,height:0}),v+=L}let w=h.length,S=f.length;for(let I of x)I.row+I.rowSpan>w&&(w=I.row+I.rowSpan),I.column+I.columnSpan>S&&(S=I.column+I.columnSpan);if(h.length===0&&w>0&&t.containerHeight){let I=w,M=(t.containerHeight-l*(I-1))/I;for(let A=0;A<I;A++)h.push(M)}else for(;h.length<w;)h.push(0);if(f.length===0&&S>0&&t.containerWidth){let I=S,M=(t.containerWidth-u*(I-1))/I;for(let A=0;A<I;A++)f.push(M)}else if(f.length===0&&n.length>0&&t.containerWidth)f.push(t.containerWidth);else for(;f.length<S;)f.push(0);let C=(I,k,M)=>{let A=0;for(let L=0;L<I;L++)A+=k[L]||0,A+=M;return A},E=(I,k,M,A)=>{let L=0;for(let B=I;B<I+k;B++)L+=M[B]||0,B>I&&(L+=A);return L},R={};for(let I of x){let k=n.find(st=>st.key===I.key),M=C(I.column,f,u),A=C(I.row,h,l),L=E(I.column,I.columnSpan,f,u),B=E(I.row,I.rowSpan,h,l),D=st=>st===void 0?0:typeof st=="string"?st.endsWith("px")?parseFloat(st):st.endsWith("%")?0:parseFloat(st):st,V=D(k?.contentWidth),X=D(k?.contentHeight),W=L,Q=B,J=M,_t=A;if(V>0)switch(W=V,t.justifyItems||"stretch"){case"start":J=M;break;case"end":J=M+L-W;break;case"center":J=M+(L-W)/2;break;case"stretch":W=L,J=M;break}if(X>0)switch(Q=X,t.alignItems||"stretch"){case"start":_t=A;break;case"end":_t=A+B-Q;break;case"center":_t=A+(B-Q)/2;break;case"stretch":Q=B,_t=A;break}I.x=J,I.y=_t,I.width=W,I.height=Q,R[I.key]={x:J,y:_t,width:W,height:Q}}return{cells:x,rowSizes:h,columnSizes:f,rowGap:l,columnGap:u,itemCoordinates:R}},IB=class{constructor(e){T(this,"opts");this.opts=e}layout(){return jgt(this)}convertToHtml(){return $gt(this)}visualize(){return Bgt(this)}};St();var OY=Xt(Pn(),1);Oe();Oe();St();var gT=class{constructor(e){T(this,"netMap");T(this,"idToNetMap");this.netMap=e,this.idToNetMap={};for(let[t,n]of Object.entries(e))for(let i of n)this.idToNetMap[i]=t}addConnections(e){for(let t of e){let n=new Set;for(let r of t){let o=this.idToNetMap[r];o&&n.add(o)}let i;if(n.size===0)i=`connectivity_net${Object.keys(this.netMap).length}`,this.netMap[i]=[];else if(n.size===1)i=n.values().next().value??`connectivity_net${Object.keys(this.netMap).length}`;else{i=n.values().next().value??`connectivity_net${Object.keys(this.netMap).length}`;for(let r of n)if(r!==i){let o=this.netMap[i],s=this.netMap[r];if(o&&s){o.push(...s),this.netMap[r]=o;for(let a of o)this.idToNetMap[a]=i}}}for(let r of t){let o=this.netMap[i];o&&!o.includes(r)&&o.push(r),this.idToNetMap[r]=i}}}getIdsConnectedToNet(e){return this.netMap[e]||[]}getNetConnectedToId(e){return this.idToNetMap[e]}areIdsConnected(e,t){if(e===t)return!0;let n=this.getNetConnectedToId(e);if(!n)return!1;let i=this.getNetConnectedToId(t);return i?n===i||i===e||i===e:!1}areAllIdsConnected(e){if(e.length===0)return!0;let t=this.getNetConnectedToId(e[0]);if(!t)return!1;for(let n of e){let i=this.getNetConnectedToId(n);if(i===void 0||i!==t)return!1}return!0}};Cd();var ff=class{constructor(){this.ids=[],this.values=[],this.length=0}clear(){this.length=0}push(t,n){let i=this.length++;for(;i>0;){let r=i-1>>1,o=this.values[r];if(n>=o)break;this.ids[i]=this.ids[r],this.values[i]=o,i=r}this.ids[i]=t,this.values[i]=n}pop(){if(this.length===0)return;let t=this.ids,n=this.values,i=t[0],r=--this.length;if(r>0){let o=t[r],s=n[r],a=0,c=r>>1;for(;a<c;){let l=(a<<1)+1,u=l+1,h=l+(+(u<r)&+(n[u]<n[l]));if(n[h]>=s)break;t[a]=t[h],n[a]=n[h],a=h}t[a]=o,n[a]=s}return i}peek(){return this.length>0?this.ids[0]:void 0}peekValue(){return this.length>0?this.values[0]:void 0}shrink(){this.ids.length=this.values.length=this.length}};var MB=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],xT=3,mf=class e{static from(t,n=0){if(n%8!==0)throw new Error("byteOffset must be 8-byte aligned.");if(!t||t.byteLength===void 0||t.buffer)throw new Error("Data must be an instance of ArrayBuffer or SharedArrayBuffer.");let[i,r]=new Uint8Array(t,n+0,2);if(i!==251)throw new Error("Data does not appear to be in a Flatbush format.");let o=r>>4;if(o!==xT)throw new Error(`Got v${o} data when expected v${xT}.`);let s=MB[r&15];if(!s)throw new Error("Unrecognized array type.");let[a]=new Uint16Array(t,n+2,1),[c]=new Uint32Array(t,n+4,1);return new e(c,a,s,void 0,t,n)}constructor(t,n=16,i=Float64Array,r=ArrayBuffer,o,s=0){if(t===void 0)throw new Error("Missing required argument: numItems.");if(isNaN(t)||t<=0)throw new Error(`Unexpected numItems value: ${t}.`);this.numItems=+t,this.nodeSize=Math.min(Math.max(+n,2),65535),this.byteOffset=s;let a=t,c=a;this._levelBounds=[a*4];do a=Math.ceil(a/this.nodeSize),c+=a,this._levelBounds.push(c*4);while(a!==1);this.ArrayType=i,this.IndexArrayType=c<16384?Uint16Array:Uint32Array;let l=MB.indexOf(i),u=c*4*i.BYTES_PER_ELEMENT;if(l<0)throw new Error(`Unexpected typed array class: ${i}.`);if(o)this.data=o,this._boxes=new i(o,s+8,c*4),this._indices=new this.IndexArrayType(o,s+8+u,c),this._pos=c*4,this.minX=this._boxes[this._pos-4],this.minY=this._boxes[this._pos-3],this.maxX=this._boxes[this._pos-2],this.maxY=this._boxes[this._pos-1];else{let h=this.data=new r(8+u+c*this.IndexArrayType.BYTES_PER_ELEMENT);this._boxes=new i(h,8,c*4),this._indices=new this.IndexArrayType(h,8+u,c),this._pos=0,this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,new Uint8Array(h,0,2).set([251,(xT<<4)+l]),new Uint16Array(h,2,1)[0]=n,new Uint32Array(h,4,1)[0]=t}this._queue=new ff}add(t,n,i=t,r=n){let o=this._pos>>2,s=this._boxes;return this._indices[o]=o,s[this._pos++]=t,s[this._pos++]=n,s[this._pos++]=i,s[this._pos++]=r,t<this.minX&&(this.minX=t),n<this.minY&&(this.minY=n),i>this.maxX&&(this.maxX=i),r>this.maxY&&(this.maxY=r),o}finish(){if(this._pos>>2!==this.numItems)throw new Error(`Added ${this._pos>>2} items when expected ${this.numItems}.`);let t=this._boxes;if(this.numItems<=this.nodeSize){t[this._pos++]=this.minX,t[this._pos++]=this.minY,t[this._pos++]=this.maxX,t[this._pos++]=this.maxY;return}let n=this.maxX-this.minX||1,i=this.maxY-this.minY||1,r=new Uint32Array(this.numItems),o=65535;for(let s=0,a=0;s<this.numItems;s++){let c=t[a++],l=t[a++],u=t[a++],h=t[a++],f=Math.floor(o*((c+u)/2-this.minX)/n),_=Math.floor(o*((l+h)/2-this.minY)/i);r[s]=Xgt(f,_)}bT(r,t,this._indices,0,this.numItems-1,this.nodeSize);for(let s=0,a=0;s<this._levelBounds.length-1;s++){let c=this._levelBounds[s];for(;a<c;){let l=a,u=t[a++],h=t[a++],f=t[a++],_=t[a++];for(let y=1;y<this.nodeSize&&a<c;y++)u=Math.min(u,t[a++]),h=Math.min(h,t[a++]),f=Math.max(f,t[a++]),_=Math.max(_,t[a++]);this._indices[this._pos>>2]=l,t[this._pos++]=u,t[this._pos++]=h,t[this._pos++]=f,t[this._pos++]=_}}}search(t,n,i,r,o){if(this._pos!==this._boxes.length)throw new Error("Data not yet indexed - call index.finish().");let s=this._boxes.length-4,a=[],c=[];for(;s!==void 0;){let l=Math.min(s+this.nodeSize*4,EB(s,this._levelBounds));for(let u=s;u<l;u+=4){let h=this._boxes[u];if(i<h)continue;let f=this._boxes[u+1];if(r<f)continue;let _=this._boxes[u+2];if(t>_)continue;let y=this._boxes[u+3];if(n>y)continue;let x=this._indices[u>>2]|0;s>=this.numItems*4?a.push(x):(o===void 0||o(x,h,f,_,y))&&c.push(x)}s=a.pop()}return c}neighbors(t,n,i=1/0,r=1/0,o){if(this._pos!==this._boxes.length)throw new Error("Data not yet indexed - call index.finish().");let s=this._boxes.length-4,a=this._queue,c=[],l=r*r;t:for(;s!==void 0;){let u=Math.min(s+this.nodeSize*4,EB(s,this._levelBounds));for(let h=s;h<u;h+=4){let f=this._indices[h>>2]|0,_=this._boxes[h],y=this._boxes[h+1],x=this._boxes[h+2],v=this._boxes[h+3],w=t<_?_-t:t>x?t-x:0,S=n<y?y-n:n>v?n-v:0,C=w*w+S*S;C>l||(s>=this.numItems*4?a.push(f<<1,C):(o===void 0||o(f))&&a.push((f<<1)+1,C))}for(;a.length&&a.peek()&1;)if(a.peekValue()>l||(c.push(a.pop()>>1),c.length===i))break t;s=a.length?a.pop()>>1:void 0}return a.clear(),c}};function EB(e,t){let n=0,i=t.length-1;for(;n<i;){let r=n+i>>1;t[r]>e?i=r:n=r+1}return t[n]}function bT(e,t,n,i,r,o){if(Math.floor(i/o)>=Math.floor(r/o))return;let s=e[i],a=e[i+r>>1],c=e[r],l=c,u=Math.max(s,a);c>u?l=u:u===s?l=Math.max(a,c):u===a&&(l=Math.max(s,c));let h=i-1,f=r+1;for(;;){do h++;while(e[h]<l);do f--;while(e[f]>l);if(h>=f)break;Ygt(e,t,n,h,f)}bT(e,t,n,i,f,o),bT(e,t,n,f+1,r,o)}function Ygt(e,t,n,i,r){let o=e[i];e[i]=e[r],e[r]=o;let s=4*i,a=4*r,c=t[s],l=t[s+1],u=t[s+2],h=t[s+3];t[s]=t[a],t[s+1]=t[a+1],t[s+2]=t[a+2],t[s+3]=t[a+3],t[a]=c,t[a+1]=l,t[a+2]=u,t[a+3]=h;let f=n[i];n[i]=n[r],n[r]=f}function Xgt(e,t){let n=e^t,i=65535^n,r=65535^(e|t),o=e&(t^65535),s=n|i>>1,a=n>>1^n,c=r>>1^i&o>>1^r,l=n&r>>1^o>>1^o;n=s,i=a,r=c,o=l,s=n&n>>2^i&i>>2,a=n&i>>2^i&(n^i)>>2,c^=n&r>>2^i&o>>2,l^=i&r>>2^(n^i)&o>>2,n=s,i=a,r=c,o=l,s=n&n>>4^i&i>>4,a=n&i>>4^i&(n^i)>>4,c^=n&r>>4^i&o>>4,l^=i&r>>4^(n^i)&o>>4,n=s,i=a,r=c,o=l,c^=n&r>>8^i&o>>8,l^=i&r>>8^(n^i)&o>>8,n=c^c>>1,i=l^l>>1;let u=e^t,h=i|65535^(u|n);return u=(u|u<<8)&16711935,u=(u|u<<4)&252645135,u=(u|u<<2)&858993459,u=(u|u<<1)&1431655765,h=(h|h<<8)&16711935,h=(h|h<<4)&252645135,h=(h|h<<2)&858993459,h=(h|h<<1)&1431655765,(h<<1|u)>>>0}var Rs=class{constructor(){T(this,"MAX_ITERATIONS",1e5);T(this,"solved",!1);T(this,"failed",!1);T(this,"iterations",0);T(this,"progress",0);T(this,"error",null);T(this,"activeSubSolver");T(this,"failedSubSolvers");T(this,"timeToSolve");T(this,"stats",{})}step(){if(!this.solved&&!this.failed){this.iterations++;try{this._step()}catch(e){throw this.error=`${this.constructor.name} error: ${e}`,this.failed=!0,e}!this.solved&&this.iterations>this.MAX_ITERATIONS&&this.tryFinalAcceptance(),!this.solved&&this.iterations>this.MAX_ITERATIONS&&(this.error=`${this.constructor.name} ran out of iterations`,this.failed=!0),"computeProgress"in this&&(this.progress=this.computeProgress())}}_step(){}getConstructorParams(){throw new Error("getConstructorParams not implemented")}solve(){let e=Date.now();for(;!this.solved&&!this.failed;)this.step();let t=Date.now();this.timeToSolve=t-e}visualize(){return{lines:[],points:[],rects:[],circles:[]}}tryFinalAcceptance(){}preview(){return{lines:[],points:[],rects:[],circles:[]}}},LB=e=>{let t=new gT({});for(let i of e.directConnections)t.addConnections([i.netId?[i.netId,...i.pinIds]:i.pinIds]);let n=new gT(t.netMap);for(let i of e.netConnections)n.addConnections([[i.netId,...i.pinIds]]);return{directConnMap:t,netConnMap:n}};function Vgt(e,t={}){let n=e.length,i=t?.maxDistance??Number.POSITIVE_INFINITY;if(n<=1)return[];{let u=new Set;for(let h of e){if(u.has(h.pinId))throw new Error(`Duplicate pinId detected: "${h.pinId}"`);u.add(h.pinId)}}let r=(u,h)=>Math.abs(u.x-h.x)+Math.abs(u.y-h.y),o=new Array(n).fill(!1),s=new Array(n).fill(Number.POSITIVE_INFINITY),a=new Array(n).fill(-1),c=0;for(let u=1;u<n;u++)e[u].pinId<e[c].pinId&&(c=u);s[c]=0;let l=[];for(let u=0;u<n;u++){let h=-1,f=Number.POSITIVE_INFINITY,_="";for(let y=0;y<n;y++)if(!o[y]){let x=s[y];(x<f||x===f&&(_===""||e[y].pinId<_))&&(f=x,_=e[y].pinId,h=y)}o[h]=!0,a[h]!==-1&&l.push([e[h].pinId,e[a[h]].pinId]);for(let y=0;y<n;y++)if(!o[y]){let x=r(e[h],e[y]),v=t?.forbidEdge?.(e[h],e[y])??!1,w=x>i||v?Number.POSITIVE_INFINITY:x;(w<s[y]||w===s[y]&&e[h].pinId<e[a[y]]?.pinId)&&(s[y]=w,a[y]=h)}}return l}var yf=(e,t)=>{let{x:n,y:i}=e,{center:r,width:o,height:s}=t,a=r.y+s/2,c=r.y-s/2,l=r.x+o/2,u=r.x-o/2,h=a-i,f=i-c,_=l-n,y=n-u,x=Math.min(h,f,_,y);return x===h?"y+":x===f?"y-":x===_?"x+":"x-"},Hgt=e=>{let{pins:t,inputProblem:n,pinIdMap:i,chipMap:r}=e,o=f=>{let _=new Set,y=[f];_.add(f);let x=n.directConnections||[];for(;y.length;){let v=y.shift();for(let w of x)if(w.pinIds.includes(v))for(let S of w.pinIds)_.has(S)||(_.add(S),y.push(S))}return _},s=t[0].pinId,a=t[1].pinId,c=new Set([...o(s),...o(a)]),l=new Map,u=new Map,h=new Set(t.map(f=>f.chipId));for(let f of c){let _=i.get(f);if(!_)continue;let y=r[_.chipId];if(!y)continue;let x=_._facingDirection??yf(_,y),v=u.get(y.chipId);if(!v){v={center:y.center};let w={xPos:0,xNeg:0,yPos:0,yNeg:0};for(let S of y.pins){let C=S._facingDirection??yf(S,y);C==="x+"&&w.xPos++,C==="x-"&&w.xNeg++,C==="y+"&&w.yPos++,C==="y-"&&w.yNeg++}v.counts=w,u.set(y.chipId,v)}x==="x+"&&(v.hasXPos=!0),x==="x-"&&(v.hasXNeg=!0),x==="y+"&&(v.hasYPos=!0),x==="y-"&&(v.hasYNeg=!0)}for(let[f,_]of u){let y=new Set,x={axes:y},v=_.counts;!!!(v&&(v.xPos>1||v.xNeg>1||v.yPos>1||v.yNeg>1))&&h.has(f)||(_.hasXPos&&_.hasXNeg&&(x.x=_.center.x,y.add("x")),_.hasYPos&&_.hasYNeg&&(x.y=_.center.y,y.add("y"))),y.size>0&&l.set(f,x)}return l},vT=e=>{let{inputProblem:t,chipMap:n,pinIdMap:i,p1:r,p2:o}=e,s=Hgt({pins:[r,o],inputProblem:t,pinIdMap:i,chipMap:n});if(s.size===0)return!1;let a=1e-9,c=(_,y)=>{for(let[,x]of s)if(x.axes.has("x")&&typeof x.x=="number"&&(_.x-x.x)*(y.x-x.x)<-a||x.axes.has("y")&&typeof x.y=="number"&&(_.y-x.y)*(y.y-x.y)<-a)return!0;return!1};if(Math.abs(r.x-o.x)<a||Math.abs(r.y-o.y)<a)return c({x:r.x,y:r.y},{x:o.x,y:o.y});let l={x:o.x,y:r.y},u={x:r.x,y:o.y},h=c({x:r.x,y:r.y},l)||c(l,{x:o.x,y:o.y}),f=c({x:r.x,y:r.y},u)||c(u,{x:o.x,y:o.y});return h&&f},Kr=(e,t=1)=>`hsl(${e.split("").reduce((i,r)=>i*31+r.charCodeAt(0),0)%360}, 100%, 50%, ${t})`,Ga=(e,t={})=>{let{connectionAlpha:n=.8,chipAlpha:i=.8}=t,r={lines:[],points:[],rects:[]},o=new Map;for(let s of e.chips)for(let a of s.pins)o.set(a.pinId,a);for(let s of e.chips){r.rects.push({label:s.chipId,center:s.center,width:s.width,height:s.height,fill:Kr(s.chipId,i)});for(let a of s.pins)r.points.push({label:`${a.pinId}
229
229
  ${a._facingDirection??yf(a,s)}`,x:a.x,y:a.y,color:Kr(a.pinId,.8)})}for(let s of e.directConnections){let[a,c]=s.pinIds,l=o.get(a),u=o.get(c);r.lines.push({points:[{x:l.x,y:l.y},{x:u.x,y:u.y}],strokeColor:Kr(s.netId??`${a}-${c}`,n)})}for(let s of e.netConnections){let a=s.pinIds.map(c=>o.get(c));for(let c=0;c<a.length-1;c++)for(let l=c+1;l<a.length;l++){let u=a[c],h=a[l];r.lines.push({points:[{x:u.x,y:u.y},{x:h.x,y:h.y}],strokeColor:Kr(s.netId,n),strokeDash:"4 2"})}}return r},Ggt=class extends Rs{constructor({inputProblem:t}){super();T(this,"inputProblem");T(this,"mspConnectionPairs",[]);T(this,"dcConnMap");T(this,"globalConnMap");T(this,"queuedDcNetIds");T(this,"chipMap");T(this,"maxMspPairDistance");T(this,"pinMap");T(this,"userNetIdByPinId");this.inputProblem=t,this.maxMspPairDistance=t.maxMspPairDistance??1;let{directConnMap:n,netConnMap:i}=LB(t);this.dcConnMap=n,this.globalConnMap=i,this.pinMap={};for(let r of t.chips)for(let o of r.pins)this.pinMap[o.pinId]={...o,chipId:r.chipId};this.chipMap={};for(let r of t.chips)this.chipMap[r.chipId]=r;this.userNetIdByPinId={};for(let r of t.directConnections)if(r.netId){let[o,s]=r.pinIds;this.userNetIdByPinId[o]=r.netId,this.userNetIdByPinId[s]=r.netId}for(let r of t.netConnections)for(let o of r.pinIds)this.userNetIdByPinId[o]=r.netId;this.queuedDcNetIds=Object.keys(i.netMap)}getConstructorParams(){return{inputProblem:this.inputProblem}}_step(){if(this.queuedDcNetIds.length===0){this.solved=!0;return}let t=this.queuedDcNetIds.shift(),i=this.globalConnMap.getIdsConnectedToNet(t).filter(s=>!!this.pinMap[s]);if(i.length<=1)return;if(i.length===2){let[s,a]=i,c=this.pinMap[s],l=this.pinMap[a];if(Math.abs(c.x-l.x)+Math.abs(c.y-l.y)>this.maxMspPairDistance)return;let h=new Map(Object.entries(this.pinMap));if(vT({inputProblem:this.inputProblem,chipMap:this.chipMap,pinIdMap:h,p1:c,p2:l}))return;let f=this.globalConnMap.getNetConnectedToId(s),_=this.userNetIdByPinId[s]??this.userNetIdByPinId[a];this.mspConnectionPairs.push({mspPairId:`${s}-${a}`,dcConnNetId:t,globalConnNetId:f,userNetId:_,pins:[c,l]});return}let r=new Map(Object.entries(this.pinMap)),o=Vgt(i.map(s=>this.pinMap[s]).filter(Boolean),{maxDistance:this.maxMspPairDistance,forbidEdge:(s,a)=>vT({inputProblem:this.inputProblem,chipMap:this.chipMap,pinIdMap:r,p1:s,p2:a})});for(let[s,a]of o){let c=this.pinMap[s],l=this.pinMap[a];if(vT({inputProblem:this.inputProblem,chipMap:this.chipMap,pinIdMap:r,p1:c,p2:l}))continue;let u=this.globalConnMap.getNetConnectedToId(s),h=this.userNetIdByPinId[s]??this.userNetIdByPinId[a];this.mspConnectionPairs.push({mspPairId:`${s}-${a}`,dcConnNetId:t,globalConnNetId:u,userNetId:h,pins:[c,l]})}}visualize(){let t=Ga(this.inputProblem,{chipAlpha:.1,connectionAlpha:.1});for(let n of this.mspConnectionPairs)t.lines.push({points:[{x:n.pins[0].x,y:n.pins[0].y},{x:n.pins[1].x,y:n.pins[1].y}],strokeColor:Kr(n.mspPairId,.75)});return t}};function MT(e){let t=e.width/2,n=e.height/2;return{minX:e.center.x-t,maxX:e.center.x+t,minY:e.center.y-n,maxY:e.center.y+n}}var Ugt=e=>{let t=MT(e);return{chipId:e.chipId,...t}},hx=e=>e.chips.map(Ugt),ET=1e-9,Ns=(e,t,n=ET)=>Math.abs(e.x-t.x)<n,Va=(e,t,n=ET)=>Math.abs(e.y-t.y)<n,Dp=(e,t,n,i=ET)=>{let r=Ns(e,t,i),o=Va(e,t,i);if(!r&&!o)return!1;if(r){let s=e.x;if(s<n.minX-i||s>n.maxX+i)return!1;let a=Math.min(e.y,t.y),c=Math.max(e.y,t.y);return Math.min(c,n.maxY)-Math.max(a,n.minY)>i}else{let s=e.y;if(s<n.minY-i||s>n.maxY+i)return!1;let a=Math.min(e.x,t.x),c=Math.max(e.x,t.x);return Math.min(c,n.maxX)-Math.max(a,n.minX)>i}},qgt=(e,t,n={})=>{for(let i=0;i<e.length-1;i++){let r=e[i],o=e[i+1],s=n.excludeRectIdsForSegment?.(i)??new Set;for(let a of t)if(!s.has(a.chipId)&&Dp(r,o,a))return{segIndex:i,rect:a}}return null},px=(e,t)=>{for(let n=0;n<e.length-1;n++)for(let i of t)if(Dp(e[n],e[n+1],i))return!0;return!1},FB=1e-9,Wgt=(e,t)=>({minX:Math.min(e.x,t.x),maxX:Math.max(e.x,t.x),minY:Math.min(e.y,t.y),maxY:Math.max(e.y,t.y)}),CB=(e,t,n,i=FB)=>e==="x"?t.x<n.minX-i?[(t.x+n.minX)/2]:t.x>n.maxX+i?[(t.x+n.maxX)/2]:[n.minX-.2,n.maxX+.2]:t.y<n.minY-i?[(t.y+n.minY)/2]:t.y>n.maxY+i?[(t.y+n.maxY)/2]:[n.minY-.2,n.maxY+.2],Zgt=(e,t,n,i,r,o=FB)=>{let s=[...i].map(a=>n.get(a)).filter(a=>!!a);if(e==="x"){let a=[r.minX,...s.map(f=>f.maxX)].filter(f=>f<t.minX-o),c=[r.maxX,...s.map(f=>f.minX)].filter(f=>f>t.maxX+o),l=a.length>0?Math.max(...a):void 0,u=c.length>0?Math.min(...c):void 0,h=[];return l!==void 0&&h.push((l+t.minX)/2),u!==void 0&&h.push((t.maxX+u)/2),h}else{let a=[r.minY,...s.map(f=>f.maxY)].filter(f=>f<t.minY-o),c=[r.maxY,...s.map(f=>f.minY)].filter(f=>f>t.maxY+o),l=a.length>0?Math.max(...a):void 0,u=c.length>0?Math.min(...c):void 0,h=[];return l!==void 0&&h.push((l+t.minY)/2),u!==void 0&&h.push((t.maxY+u)/2),h}},Kgt=1e-9,Jgt=(e,t,n,i,r=Kgt)=>{if(t<0||t>=e.length-1)return null;let o=e[t],s=e[t+1],a=Ns(o,s,r),c=Va(o,s,r);if(!a&&!c||a&&n!=="x"||c&&n!=="y")return null;let l=e.map(u=>({...u}));if(n==="x"){if(Math.abs(o.x-i)<r&&Math.abs(s.x-i)<r)return null;l[t]={...l[t],x:i},l[t+1]={...l[t+1],x:i}}else{if(Math.abs(o.y-i)<r&&Math.abs(s.y-i)<r)return null;l[t]={...l[t],y:i},l[t+1]={...l[t+1],y:i}}if(t-1>=0){let u=l[t-1],h=l[t];if(Math.abs(u.x-h.x)+Math.abs(u.y-h.y)<r)return null}if(t+2<=l.length-1){let u=l[t+1],h=l[t+2];if(Math.abs(u.x-h.x)+Math.abs(u.y-h.y)<r)return null}for(let u=0;u<l.length-1;u++){let h=l[u],f=l[u+1];if(!Va(h,f,r)&&!Ns(h,f,r))return null}return l},kB=(e,t=6)=>e.map(i=>`${i.x.toFixed(t)},${i.y.toFixed(t)}`).join("|"),Qgt=class extends Rs{constructor(t){super();T(this,"pins");T(this,"inputProblem");T(this,"chipMap");T(this,"obstacles");T(this,"rectById");T(this,"aabb");T(this,"baseElbow");T(this,"solvedTracePath",null);T(this,"queue",[]);T(this,"visited",new Set);this.pins=t.pins,this.inputProblem=t.inputProblem,this.chipMap=t.chipMap;for(let r of this.pins)if(!r._facingDirection){let o=this.chipMap[r.chipId];r._facingDirection=yf(r,o)}this.obstacles=hx(this.inputProblem),this.rectById=new Map(this.obstacles.map(r=>[r.chipId,r]));let[n,i]=this.pins;this.baseElbow=Na({x:n.x,y:n.y,facingDirection:n._facingDirection},{x:i.x,y:i.y,facingDirection:i._facingDirection},{overshoot:.2}),this.aabb=Wgt({x:n.x,y:n.y},{x:i.x,y:i.y}),this.queue.push({path:this.baseElbow,collisionChipIds:new Set}),this.visited.add(kB(this.baseElbow))}getConstructorParams(){return{chipMap:this.chipMap,pins:this.pins,inputProblem:this.inputProblem}}axisOfSegment(t,n){return Ns(t,n)?"x":Va(t,n)?"y":null}pathLength(t){let n=0;for(let i=0;i<t.length-1;i++)n+=Math.abs(t[i+1].x-t[i].x)+Math.abs(t[i+1].y-t[i].y);return n}_step(){if(this.solvedTracePath){this.solved=!0;return}let t=this.queue.shift();if(!t){this.failed=!0,this.error="No collision-free path found";return}let{path:n,collisionChipIds:i}=t,[r,o]=this.pins,s=qgt(n,this.obstacles);if(!s){let v=n[0],w=n[n.length-1],S=1e-9,C=(E,R)=>Math.abs(E.x-R.x)<S&&Math.abs(E.y-R.y)<S;C(v,{x:r.x,y:r.y})&&C(w,{x:o.x,y:o.y})&&(this.solvedTracePath=n,this.solved=!0);return}let{segIndex:a,rect:c}=s,l=a===0,u=a===n.length-2;if(l){if(n.length<3)return;a=1}else if(u){if(n.length<3)return;a=n.length-3}let h=n[a],f=n[a+1],_=this.axisOfSegment(h,f);if(!_)return;let y=[];if(i.size===0){let v=CB(_,{x:r.x,y:r.y},c),w=CB(_,{x:o.x,y:o.y},c),S=[...v,...w],C=[...new Set(S)];y.push(...C)}else{let v=Zgt(_,c,this.rectById,i,this.aabb);y.push(...v)}let x=[];for(let v of y){let w=Jgt(n,a,_,v);if(!w)continue;let S=kB(w);if(this.visited.has(S))continue;this.visited.add(S);let C=new Set(i);C.add(c.chipId);let E=this.pathLength(w);x.push({path:w,collisionRectIds:C,len:E})}x.sort((v,w)=>v.len-w.len);for(let v of x)this.queue.push({path:v.path,collisionChipIds:v.collisionRectIds})}visualize(){let t=Ga(this.inputProblem,{chipAlpha:.1,connectionAlpha:.1});t.lines.push({points:this.baseElbow,strokeColor:"red",strokeDash:"4 4"});let[n,i]=this.pins;t.lines.push({points:[{x:n.x,y:n.y},{x:i.x,y:i.y}],strokeColor:"blue",strokeDash:"5 5"});for(let{path:r,collisionChipIds:o}of this.queue)t.lines.push({points:r,strokeColor:"teal",strokeDash:"2 2"});return this.solvedTracePath?t.lines.push({points:this.solvedTracePath,strokeColor:"green"}):this.queue.length>0&&t.lines.push({points:this.queue[0].path,strokeColor:"orange"}),t}},txt=class extends Rs{constructor(t){super();T(this,"inputProblem");T(this,"mspConnectionPairs");T(this,"dcConnMap");T(this,"globalConnMap");T(this,"queuedConnectionPairs");T(this,"chipMap");T(this,"currentConnectionPair",null);T(this,"solvedTracePaths",[]);T(this,"failedConnectionPairs",[]);this.inputProblem=t.inputProblem,this.mspConnectionPairs=t.mspConnectionPairs,this.dcConnMap=t.dcConnMap,this.globalConnMap=t.globalConnMap,this.chipMap=t.chipMap,this.queuedConnectionPairs=[...this.mspConnectionPairs]}getConstructorParams(){return{inputProblem:this.inputProblem,chipMap:this.chipMap,mspConnectionPairs:this.mspConnectionPairs,dcConnMap:this.dcConnMap,globalConnMap:this.globalConnMap}}_step(){if(this.activeSubSolver?.solved&&(this.solvedTracePaths.push({...this.currentConnectionPair,tracePath:this.activeSubSolver.solvedTracePath,mspConnectionPairIds:[this.currentConnectionPair.mspPairId],pinIds:[this.currentConnectionPair.pins[0].pinId,this.currentConnectionPair.pins[1].pinId]}),this.activeSubSolver=null,this.currentConnectionPair=null),this.activeSubSolver?.failed&&(this.currentConnectionPair&&this.failedConnectionPairs.push({...this.currentConnectionPair,error:this.activeSubSolver.error||void 0}),this.activeSubSolver=null,this.currentConnectionPair=null),this.activeSubSolver){this.activeSubSolver.step();return}let t=this.queuedConnectionPairs.shift();if(!t){this.solved=!0;return}this.currentConnectionPair=t;let{pins:n}=t;this.activeSubSolver=new Qgt({inputProblem:this.inputProblem,pins:n,chipMap:this.chipMap})}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();let t=Ga(this.inputProblem,{chipAlpha:.1,connectionAlpha:.1});for(let{mspPairId:n,tracePath:i}of this.solvedTracePaths)t.lines.push({points:i,strokeColor:"green"});for(let n of this.failedConnectionPairs)t.lines.push({points:[{x:n.pins[0].x,y:n.pins[0].y},{x:n.pins[1].x,y:n.pins[1].y}],strokeColor:"red",strokeDash:"4 2"});return t}},ext=({pts:e,segmentIndex:t,offset:n,JOG_SIZE:i,EPS:r=1e-6})=>{if(t!==0&&t!==e.length-2)return;let o=e[t],s=e[t+1],a=Math.abs(o.x-s.x)<r,c=Math.abs(o.y-s.y)<r;if(!a&&!c)return;let l=a?s.y>o.y?1:-1:s.x>o.x?1:-1;if(t===0)if(a){let u=o.y+l*i;e.splice(1,1,{x:o.x,y:u},{x:o.x+n,y:u},{x:s.x+n,y:s.y})}else{let u=o.x+l*i;e.splice(1,1,{x:u,y:o.y},{x:u,y:o.y+n},{x:s.x,y:s.y+n})}else if(a){let u=s.y-l*i;e.splice(t,1,{x:o.x+n,y:o.y},{x:s.x+n,y:u},{x:s.x,y:u})}else{let u=s.x-l*i;e.splice(t,1,{x:o.x,y:o.y+n},{x:u,y:s.y+n},{x:u,y:s.y})}},nxt=class extends Rs{constructor(t){super();T(this,"overlappingTraceSegments");T(this,"traceNetIslands");T(this,"SHIFT_DISTANCE",.1);T(this,"correctedTraceMap",{});this.overlappingTraceSegments=t.overlappingTraceSegments,this.traceNetIslands=t.traceNetIslands;for(let{connNetId:n,pathsWithOverlap:i}of this.overlappingTraceSegments)for(let{solvedTracePathIndex:r,traceSegmentIndex:o}of i){let s=this.traceNetIslands[n][r].mspPairId;this.correctedTraceMap[s]=this.traceNetIslands[n][r]}}_step(){let n=this.overlappingTraceSegments.map((o,s)=>{let a=Math.floor(s/2)+1;return(s%2===0?-a:a)*this.SHIFT_DISTANCE}),i=(o,s)=>Math.abs(o-s)<1e-6,r=(o,s)=>!!o&&!!s&&i(o.x,s.x)&&i(o.y,s.y);this.overlappingTraceSegments.forEach((o,s)=>{let a=n[s],c=new Map;for(let l of o.pathsWithOverlap)c.has(l.solvedTracePathIndex)||c.set(l.solvedTracePathIndex,new Set),c.get(l.solvedTracePathIndex).add(l.traceSegmentIndex);for(let[l,u]of c){let h=this.traceNetIslands[o.connNetId][l],f=this.correctedTraceMap[h.mspPairId]??h,_=f.tracePath.map(S=>({...S})),y=Array.from(u).sort((S,C)=>S-C),x=Array.from(u).sort((S,C)=>S-C).reverse(),v=this.SHIFT_DISTANCE;for(let S of x)if(!(S<0||S>=_.length-1))if(S===0||S===_.length-2)ext({pts:_,segmentIndex:S,offset:a,JOG_SIZE:v,EPS:1e-6});else{let C=_[S],E=_[S+1],R=Math.abs(C.x-E.x)<1e-6,I=Math.abs(C.y-E.y)<1e-6;if(!R&&!I)continue;R?(C.x+=a,E.x+=a):(C.y+=a,E.y+=a)}let w=[];for(let S of _)(w.length===0||!r(w[w.length-1],S))&&w.push(S);this.correctedTraceMap[h.mspPairId]={...f,tracePath:w}}}),this.solved=!0}visualize(){let t={lines:[],points:[],rects:[],circles:[]};for(let n of this.overlappingTraceSegments)for(let{solvedTracePathIndex:i,traceSegmentIndex:r}of n.pathsWithOverlap){let o=this.traceNetIslands[n.connNetId][i],s=o.tracePath[r],a=o.tracePath[r+1];t.lines.push({points:[s,a],strokeColor:"red"})}for(let n of Object.values(this.correctedTraceMap))t.lines.push({points:n.tracePath,strokeColor:"blue",strokeDash:"4 2"});return t}},ixt=class extends Rs{constructor(t){super();T(this,"inputProblem");T(this,"inputTracePaths");T(this,"globalConnMap");T(this,"traceNetIslands",{});T(this,"correctedTraceMap",{});this.inputProblem=t.inputProblem,this.inputTracePaths=t.inputTracePaths,this.globalConnMap=t.globalConnMap;for(let n of this.inputTracePaths){let{mspPairId:i}=n;this.correctedTraceMap[i]=n}this.traceNetIslands=this.computeTraceNetIslands()}getConstructorParams(){return{inputProblem:this.inputProblem,inputTracePaths:this.inputTracePaths,globalConnMap:this.globalConnMap}}computeTraceNetIslands(){let t={};for(let n of this.inputTracePaths){let i=this.correctedTraceMap[n.mspPairId]??n,r=i.globalConnNetId;t[r]||(t[r]=[]),t[r].push(i)}return t}findNextOverlapIssue(){let n=Object.keys(this.traceNetIslands);for(let i=0;i<n.length;i++)for(let r=i+1;r<n.length;r++){let o=n[i],s=n[r],a=this.traceNetIslands[o]||[],c=this.traceNetIslands[s]||[],l=[],u=[],h=new Set,f=new Set,_=(y,x,v,w)=>{let S=Math.min(y,x),C=Math.max(y,x),E=Math.min(v,w),R=Math.max(v,w);return Math.min(C,R)-Math.max(S,E)>.002};for(let y=0;y<a.length;y++){let v=a[y].tracePath;for(let w=0;w<v.length-1;w++){let S=v[w],C=v[w+1],E=Math.abs(S.x-C.x)<.002,R=Math.abs(S.y-C.y)<.002;if(!(!E&&!R))for(let I=0;I<c.length;I++){let M=c[I].tracePath;for(let A=0;A<M.length-1;A++){let L=M[A],B=M[A+1],D=Math.abs(L.x-B.x)<.002,V=Math.abs(L.y-B.y)<.002;if(!(!D&&!V)){if(E&&D){if(Math.abs(S.x-L.x)<.002&&_(S.y,C.y,L.y,B.y)){let X=`${y}:${w}`,W=`${I}:${A}`;h.has(X)||(l.push({solvedTracePathIndex:y,traceSegmentIndex:w}),h.add(X)),f.has(W)||(u.push({solvedTracePathIndex:I,traceSegmentIndex:A}),f.add(W))}}else if(R&&V&&Math.abs(S.y-L.y)<.002&&_(S.x,C.x,L.x,B.x)){let X=`${y}:${w}`,W=`${I}:${A}`;h.has(X)||(l.push({solvedTracePathIndex:y,traceSegmentIndex:w}),h.add(X)),f.has(W)||(u.push({solvedTracePathIndex:I,traceSegmentIndex:A}),f.add(W))}}}}}}if(l.length>0&&u.length>0)return{overlappingTraceSegments:[{connNetId:o,pathsWithOverlap:l},{connNetId:s,pathsWithOverlap:u}]}}return null}_step(){if(this.activeSubSolver?.solved){for(let[i,r]of Object.entries(this.activeSubSolver.correctedTraceMap))this.correctedTraceMap[i]=r;this.activeSubSolver=null,this.traceNetIslands=this.computeTraceNetIslands()}if(this.activeSubSolver){this.activeSubSolver.step();return}let t=this.findNextOverlapIssue();if(t===null){this.solved=!0;return}let{overlappingTraceSegments:n}=t;this.activeSubSolver=new nxt({overlappingTraceSegments:n,traceNetIslands:this.traceNetIslands})}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();let t=Ga(this.inputProblem);for(let n of Object.values(this.correctedTraceMap))t.lines.push({points:n.tracePath,strokeColor:"purple"});return t}},rxt=class{constructor(e){T(this,"chips");T(this,"spatialIndex");T(this,"spatialIndexIdToChip");this.chips=e.map(t=>({...t,bounds:MT(t),spatialIndexId:null})),this.spatialIndexIdToChip=new Map,this.spatialIndex=new mf(e.length);for(let t of this.chips)t.spatialIndexId=this.spatialIndex.add(t.bounds.minX,t.bounds.minY,t.bounds.maxX,t.bounds.maxY),this.spatialIndexIdToChip.set(t.spatialIndexId,t);this.spatialIndex.finish()}getChipsInBounds(e){return this.spatialIndex.search(e.minX,e.minY,e.maxX,e.maxY).map(n=>this.spatialIndexIdToChip.get(n))}doesOrthogonalLineIntersectChip(e,t={}){let n=t.excludeChipIds??[],[i,r]=e,{x:o,y:s}=i,{x:a,y:c}=r;return this.getChipsInBounds({minX:Math.min(o,a),minY:Math.min(s,c),maxX:Math.max(o,a),maxY:Math.max(s,c)}).filter(u=>!n.includes(u.chipId)).length>0}},oxt=.45,AB=.2;function TT(e){let{orientation:t,netLabelWidth:n}=e,i=typeof n=="number"?n:oxt;return t==="y+"||t==="y-"?{width:AB,height:i}:{width:i,height:AB}}function IT(e,t,n,i){switch(t){case"x+":return{x:e.x+n/2,y:e.y};case"x-":return{x:e.x-n/2,y:e.y};case"y+":return{x:e.x,y:e.y+i/2};case"y-":return{x:e.x,y:e.y-i/2}}}function $p(e,t,n){return{minX:e.x-t/2,minY:e.y-n/2,maxX:e.x+t/2,maxY:e.y+n/2}}function zB(e,t,n,i=1e-9){let r=Math.abs(e.x-t.x)<i,o=Math.abs(e.y-t.y)<i;if(!r&&!o)return!1;if(r){let s=e.x;if(s<n.minX-i||s>n.maxX+i)return!1;let a=Math.min(e.y,t.y),c=Math.max(e.y,t.y);return Math.min(c,n.maxY)-Math.max(a,n.minY)>i}else{let s=e.y;if(s<n.minY-i||s>n.maxY+i)return!1;let a=Math.min(e.x,t.x),c=Math.max(e.x,t.x);return Math.min(c,n.maxX)-Math.max(a,n.minX)>i}}function DB(e,t,n,i){for(let[r,o]of Object.entries(t)){let s=o.tracePath;for(let a=0;a<s.length-1;a++)if(!(r===n&&a===i)&&zB(s[a],s[a+1],e))return{hasIntersection:!0,mspPairId:r,segIndex:a}}return{hasIntersection:!1}}function NB(e){let t=0,n=e.tracePath;for(let i=0;i<n.length-1;i++)t+=Math.abs(n[i+1].x-n[i].x)+Math.abs(n[i+1].y-n[i].y);return t}function $B(e){let{inputProblem:t,inputTraceMap:n,globalConnNetId:i,fallbackTrace:r,mspConnectionPairIds:o}=e,s=Object.fromEntries(t.chips.map(f=>[f.chipId,f])),a=Object.values(n).filter(f=>f.globalConnNetId===i);if(o&&o.length>0){let f=new Set(o);a=a.filter(_=>_.mspConnectionPairIds.some(y=>f.has(y)))}let c=new Set;for(let f of a)c.add(f.pins[0].chipId),c.add(f.pins[1].chipId);let l=null,u=-1;for(let f of c){let y=s[f]?.pins?.length??0;y>u&&(u=y,l=f)}let h=l==null?[]:a.filter(f=>f.pins[0].chipId===l||f.pins[1].chipId===l);return h.length>0?h.reduce((f,_)=>NB(f)>=NB(_)?f:_):r}function sxt(e,t){return[{x:e.x,y:e.y},{x:(e.x+t.x)/2,y:(e.y+t.y)/2},{x:t.x,y:t.y}]}function axt(e){let{inputProblem:t,inputTraceMap:n,chipObstacleSpatialIndex:i,overlappingSameNetTraceGroup:r,availableOrientations:o,netLabelWidth:s}=e,a=r.portOnlyPinId;if(!a)return{placement:null,testedCandidates:[],error:"No portOnlyPinId provided"};let c=null,l=null;for(let I of t.chips){let k=I.pins.find(M=>M.pinId===a);if(k){c={x:k.x,y:k.y},l=k._facingDirection||yf(k,I);break}}if(!c||!l)return{placement:null,testedCandidates:[],error:`Port-only pin not found: ${a}`};let u=o.length>0?o:["x+","x-","y+","y-"],h={x:c.x,y:c.y},f=I=>I==="x+"?{x:1,y:0}:I==="x-"?{x:-1,y:0}:I==="y+"?{x:0,y:1}:{x:0,y:-1},_=[];for(let I of u){let{width:k,height:M}=TT({orientation:I,netLabelWidth:s}),A=IT(h,I,k,M),L=f(I),B=.001,D={x:A.x+L.x*B,y:A.y+L.y*B},V=$p(D,k,M);if(i.getChipsInBounds(V).length>0){_.push({center:D,width:k,height:M,bounds:V,anchor:h,orientation:I,status:"chip-collision",hostSegIndex:-1});continue}if(DB(V,n,"",-1).hasIntersection){_.push({center:D,width:k,height:M,bounds:V,anchor:h,orientation:I,status:"trace-collision",hostSegIndex:-1});continue}return _.push({center:D,width:k,height:M,bounds:V,anchor:h,orientation:I,status:"ok",hostSegIndex:-1}),{placement:{globalConnNetId:r.globalConnNetId,dcConnNetId:void 0,netId:r.netId,mspConnectionPairIds:[],pinIds:[a],orientation:I,anchorPoint:h,width:k,height:M,center:D},testedCandidates:_}}let y=l,{width:x,height:v}=TT({orientation:y,netLabelWidth:s}),w=IT(h,y,x,v),S=f(y),C=.001,E={x:w.x+S.x*C,y:w.y+S.y*C};return{placement:{globalConnNetId:r.globalConnNetId,dcConnNetId:void 0,netId:r.netId,mspConnectionPairIds:[],pinIds:[a],orientation:y,anchorPoint:h,width:x,height:v,center:E},testedCandidates:_}}function cxt(e){let t=Ga(e.inputProblem),n=e.overlappingSameNetTraceGroup.globalConnNetId,i=$B({inputProblem:e.inputProblem,inputTraceMap:e.inputTraceMap,globalConnNetId:n,fallbackTrace:e.overlappingSameNetTraceGroup.overlappingTraces}),r=Kr(n,.9),o=Kr(n,.5);for(let s of Object.values(e.inputTraceMap)){let a=i?s.mspPairId===i.mspPairId:!1;t.lines.push({points:s.tracePath})}for(let s of e.testedCandidates){let a=s.status==="ok"?"rgba(0, 180, 0, 0.25)":s.status==="chip-collision"?"rgba(220, 0, 0, 0.25)":s.status==="trace-collision"?"rgba(220, 140, 0, 0.25)":"rgba(120, 120, 120, 0.15)",c=s.status==="ok"?"green":s.status==="chip-collision"?"red":s.status==="trace-collision"?"orange":"gray";t.rects.push({center:{x:(s.bounds.minX+s.bounds.maxX)/2,y:(s.bounds.minY+s.bounds.maxY)/2},width:s.width,height:s.height,fill:a,strokeColor:c}),t.points.push({x:s.anchor.x,y:s.anchor.y,color:c})}if(e.netLabelPlacement){let s=e.netLabelPlacement;t.rects.push({center:s.center,width:s.width,height:s.height,fill:"rgba(0, 128, 255, 0.35)",strokeColor:"blue"}),t.points.push({x:s.anchorPoint.x,y:s.anchorPoint.y,color:"blue"})}return t}var RB=class extends Rs{constructor(t){super();T(this,"inputProblem");T(this,"inputTraceMap");T(this,"overlappingSameNetTraceGroup");T(this,"availableOrientations");T(this,"chipObstacleSpatialIndex");T(this,"netLabelWidth");T(this,"netLabelPlacement",null);T(this,"testedCandidates",[]);this.inputProblem=t.inputProblem,this.inputTraceMap=t.inputTraceMap,this.overlappingSameNetTraceGroup=t.overlappingSameNetTraceGroup,this.availableOrientations=t.availableOrientations,this.netLabelWidth=t.netLabelWidth,this.chipObstacleSpatialIndex=t.inputProblem._chipObstacleSpatialIndex??new rxt(t.inputProblem.chips)}getConstructorParams(){return{inputProblem:this.inputProblem,inputTraceMap:this.inputTraceMap,overlappingSameNetTraceGroup:this.overlappingSameNetTraceGroup,availableOrientations:this.availableOrientations,netLabelWidth:this.netLabelWidth}}_step(){if(this.netLabelPlacement){this.solved=!0;return}if(this.overlappingSameNetTraceGroup.portOnlyPinId){let f=axt({inputProblem:this.inputProblem,inputTraceMap:this.inputTraceMap,chipObstacleSpatialIndex:this.chipObstacleSpatialIndex,overlappingSameNetTraceGroup:this.overlappingSameNetTraceGroup,availableOrientations:this.availableOrientations,netLabelWidth:this.netLabelWidth});if(this.testedCandidates.push(...f.testedCandidates),f.placement){this.netLabelPlacement=f.placement,this.solved=!0;return}this.failed=!0,this.error=f.error??"Could not place net label at port without collisions";return}let t=this.overlappingSameNetTraceGroup.globalConnNetId,n=$B({inputProblem:this.inputProblem,inputTraceMap:this.inputTraceMap,globalConnNetId:t,fallbackTrace:this.overlappingSameNetTraceGroup.overlappingTraces,mspConnectionPairIds:this.overlappingSameNetTraceGroup.mspConnectionPairIds});if(!n){this.failed=!0,this.error="No host trace found for net label placement";return}let i=new Set(this.overlappingSameNetTraceGroup.mspConnectionPairIds??[]),r=Object.values(this.inputTraceMap).filter(f=>f.globalConnNetId===t&&(i.size===0||f.mspConnectionPairIds.some(_=>i.has(_)))),o=this.availableOrientations.length===1?[n,...r.filter(f=>f.mspPairId!==n.mspPairId)]:[n],s=this.availableOrientations.length>0?this.availableOrientations:["x+","x-","y+","y-"],a=this.availableOrientations.length===1,c=(f,_)=>{switch(f){case"y+":return _.y;case"y-":return-_.y;case"x+":return _.x;case"x-":return-_.x}},l=null,u=-1/0,h=1e-6;for(let f of o){let _=f.tracePath.slice();for(let y=0;y<_.length-1;y++){let x=_[y],v=_[y+1],w=Math.abs(x.y-v.y)<h,S=Math.abs(x.x-v.x)<h;if(!w&&!S)continue;let C=w?["y+","y-"]:["x+","x-"],E=s.filter(I=>C.includes(I));if(E.length===0)continue;let R=sxt(x,v);for(let I of R)for(let k of E){let{width:M,height:A}=TT({orientation:k,netLabelWidth:this.netLabelWidth}),L=IT(I,k,M,A),B=k==="x+"?{x:1,y:0}:k==="x-"?{x:-1,y:0}:k==="y+"?{x:0,y:1}:{x:0,y:-1},D=1e-4,V={x:L.x+B.x*D,y:L.y+B.y*D},X=$p(V,M,A);if(this.chipObstacleSpatialIndex.getChipsInBounds(X).length>0){this.testedCandidates.push({center:V,width:M,height:A,bounds:X,anchor:I,orientation:k,status:"chip-collision",hostSegIndex:y});continue}if(DB(X,this.inputTraceMap,f.mspPairId,y).hasIntersection){this.testedCandidates.push({center:V,width:M,height:A,bounds:X,anchor:I,orientation:k,status:"trace-collision",hostSegIndex:y});continue}if(this.testedCandidates.push({center:V,width:M,height:A,bounds:X,anchor:I,orientation:k,status:"ok",hostSegIndex:y}),a){let J=c(k,I);J>u+1e-9&&(u=J,l={anchor:I,orientation:k,width:M,height:A,center:L,hostSegIndex:y,dcConnNetId:f.dcConnNetId,mspPairId:f.mspPairId,pinIds:[f.pins[0].pinId,f.pins[1].pinId]});continue}this.netLabelPlacement={globalConnNetId:this.overlappingSameNetTraceGroup.globalConnNetId,dcConnNetId:f.dcConnNetId,netId:this.overlappingSameNetTraceGroup.netId,mspConnectionPairIds:[f.mspPairId],pinIds:[f.pins[0].pinId,f.pins[1].pinId],orientation:k,anchorPoint:I,width:M,height:A,center:L},this.solved=!0;return}}}if(a&&l){this.netLabelPlacement={globalConnNetId:this.overlappingSameNetTraceGroup.globalConnNetId,dcConnNetId:l.dcConnNetId,netId:this.overlappingSameNetTraceGroup.netId,mspConnectionPairIds:[l.mspPairId],pinIds:l.pinIds,orientation:l.orientation,anchorPoint:l.anchor,width:l.width,height:l.height,center:l.center},this.solved=!0;return}this.failed=!0,this.error="Could not place net label without collisions"}visualize(){return cxt(this)}},BB=class extends Rs{constructor(t){super();T(this,"inputProblem");T(this,"inputTraceMap");T(this,"overlappingSameNetTraceGroups");T(this,"queuedOverlappingSameNetTraceGroups");T(this,"netLabelPlacements",[]);T(this,"currentGroup",null);T(this,"triedAnyOrientationFallbackForCurrentGroup",!1);this.inputProblem=t.inputProblem,this.inputTraceMap=t.inputTraceMap,this.overlappingSameNetTraceGroups=this.computeOverlappingSameNetTraceGroups(),this.queuedOverlappingSameNetTraceGroups=[...this.overlappingSameNetTraceGroups]}computeOverlappingSameNetTraceGroups(){let t={};for(let c of Object.values(this.inputTraceMap)){let l=c.globalConnNetId;t[l]||(t[l]=[]),t[l].push(c)}let{netConnMap:n}=LB(this.inputProblem),i=new Map;for(let c of this.inputProblem.chips)for(let l of c.pins)i.set(l.pinId,l);let r={};for(let c of this.inputProblem.directConnections)if(c.netId){let[l,u]=c.pinIds;r[l]=c.netId,r[u]=c.netId}for(let c of this.inputProblem.netConnections)for(let l of c.pinIds)r[l]=c.netId;let o=[],s=this.inputProblem.chips.flatMap(c=>c.pins.map(l=>l.pinId)),a=new Set;for(let c of s){let l=n.getNetConnectedToId(c);l&&a.add(l)}for(let c of a){let u=n.getIdsConnectedToNet(c).filter(_=>i.has(_)),h={};for(let _ of u)h[_]=new Set;for(let _ of t[c]??[]){let y=_.pins[0].pinId,x=_.pins[1].pinId;h[y]&&h[x]&&(h[y].add(x),h[x].add(y))}let f=new Set;for(let _ of u){if(f.has(_))continue;let y=[_],x=new Set;for(f.add(_);y.length>0;){let w=y.pop();x.add(w);for(let S of h[w]??[])f.has(S)||(f.add(S),y.push(S))}let v=(t[c]??[]).filter(w=>x.has(w.pins[0].pinId)&&x.has(w.pins[1].pinId));if(v.length>0){let w=k=>{let M=0,A=k.tracePath;for(let L=0;L<A.length-1;L++)M+=Math.abs(A[L+1].x-A[L].x)+Math.abs(A[L+1].y-A[L].y);return M},S=v[0],C=w(S);for(let k=1;k<v.length;k++){let M=w(v[k]);M>C&&(S=v[k],C=M)}let E=v.find(k=>k.userNetId!=null)?.userNetId;if(!E){for(let k of x)if(r[k]){E=r[k];break}}let R=Array.from(new Set(v.flatMap(k=>k.mspConnectionPairIds??[k.mspPairId]))),I={globalConnNetId:c,netId:E,overlappingTraces:S,mspConnectionPairIds:R};o.push(I)}else for(let w of x){let S=r[w];S&&o.push({globalConnNetId:c,netId:S,portOnlyPinId:w})}}}return o}_step(){if(this.activeSubSolver?.solved){this.netLabelPlacements.push(this.activeSubSolver.netLabelPlacement),this.activeSubSolver=null,this.currentGroup=null,this.triedAnyOrientationFallbackForCurrentGroup=!1;return}if(this.activeSubSolver?.failed){let r=["x+","x-","y+","y-"],o=this.activeSubSolver.availableOrientations,s=o.length===4&&r.every(a=>o.includes(a));if(!this.triedAnyOrientationFallbackForCurrentGroup&&!s&&this.currentGroup){this.triedAnyOrientationFallbackForCurrentGroup=!0;let a=this.currentGroup.netId?this.inputProblem.netConnections.find(c=>c.netId===this.currentGroup.netId)?.netLabelWidth:void 0;this.activeSubSolver=new RB({inputProblem:this.inputProblem,inputTraceMap:this.inputTraceMap,overlappingSameNetTraceGroup:this.currentGroup,availableOrientations:r,netLabelWidth:a});return}this.failed=!0,this.error=this.activeSubSolver.error;return}if(this.activeSubSolver){this.activeSubSolver.step();return}let t=this.queuedOverlappingSameNetTraceGroups.shift();if(!t){this.solved=!0;return}let n=t.netId??t.globalConnNetId;this.currentGroup=t,this.triedAnyOrientationFallbackForCurrentGroup=!1;let i=this.currentGroup.netId?this.inputProblem.netConnections.find(r=>r.netId===this.currentGroup.netId)?.netLabelWidth:void 0;this.activeSubSolver=new RB({inputProblem:this.inputProblem,inputTraceMap:this.inputTraceMap,overlappingSameNetTraceGroup:t,availableOrientations:this.inputProblem.availableNetLabelOrientations[n]??["x+","x-","y+","y-"],netLabelWidth:i})}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();let t=Ga(this.inputProblem);for(let n of Object.values(this.inputTraceMap))t.lines.push({points:n.tracePath,strokeColor:"purple"});for(let n of this.netLabelPlacements)t.rects.push({center:n.center,width:n.width,height:n.height,fill:Kr(n.globalConnNetId,.35),strokeColor:Kr(n.globalConnNetId,.9)}),t.points.push({x:n.anchorPoint.x,y:n.anchorPoint.y,color:Kr(n.globalConnNetId,.9)});return t}},lxt=(e,t)=>{let n=[];for(let i of e)for(let r of t){let o=$p(r.center,r.width,r.height);for(let s=0;s<i.tracePath.length-1;s++){let a=i.tracePath[s],c=i.tracePath[s+1];if(zB(a,c,o)){if(i.globalConnNetId===r.globalConnNetId)break;n.push({trace:i,label:r});break}}}return n},uxt=(e,t)=>{let n=o=>o.x>t.minX&&o.x<t.maxX&&o.y>t.minY&&o.y<t.maxY,i=-1,r=-1;for(let o=0;o<e.length;o++)n(e[o])&&(i===-1&&(i=o),r=o);return{firstInsideIndex:i,lastInsideIndex:r}},Ha=e=>{if(e.length<3)return e;let t=[e[0]];for(let i=1;i<e.length-1;i++){let r=t[t.length-1],o=e[i],s=e[i+1];Ns(r,o)&&Ns(o,s)||Va(r,o)&&Va(o,s)||t.push(o)}if(t.push(e[e.length-1]),t.length<3)return t;let n=[t[0]];for(let i=1;i<t.length-1;i++){let r=n[n.length-1],o=t[i],s=t[i+1];Ns(r,o)&&Ns(o,s)||Va(r,o)&&Va(o,s)||n.push(o)}return n.push(t[t.length-1]),n},pxt=({initialTrace:e,firstInsideIndex:t,lastInsideIndex:n,labelBounds:i,obstacles:r})=>{if(t<=0||n>=e.tracePath.length-1)return null;let o=e.tracePath[t-1],s=e.tracePath[n+1],a=e.tracePath.slice(0,t),c=e.tracePath.slice(n+1),l=[];if(o.x!==s.x&&o.y!==s.y)l.push([{x:s.x,y:o.y}]),l.push([{x:o.x,y:s.y}]);else if(o.x===s.x||o.y===s.y){let x=[...a,...c],v=Ha(x);if(!px(v,r))return{...e,tracePath:v}}for(let x=0;x<l.length;x++){let v=l[x],w=[...a,...v,...c],S=Ha(w);if(!px(S,r))return{...e,tracePath:S}}l.length=0;let u=.1,h=i.minX-u,f=i.maxX+u,_=i.maxY+u,y=i.minY-u;(o.x<=i.minX||s.x<=i.minX)&&o.x<i.maxX&&s.x<i.maxX&&l.push([{x:h,y:o.y},{x:h,y:s.y}]),(o.x>=i.maxX||s.x>=i.maxX)&&o.x>i.minX&&s.x>i.minX&&l.push([{x:f,y:o.y},{x:f,y:s.y}]),(o.y>=i.maxY||s.y>=i.maxY)&&o.y>i.minY&&s.y>i.minY&&l.push([{x:o.x,y:_},{x:s.x,y:_}]),(o.y<=i.minY||s.y<=i.minY)&&o.y<i.maxY&&s.y<i.maxY&&l.push([{x:o.x,y},{x:s.x,y}]);for(let x=0;x<l.length;x++){let v=l[x],w=[...a,...v,...c],S=Ha(w);if(!px(S,r))return{...e,tracePath:S}}return null},hxt=({initialTrace:e,label:t,labelBounds:n,obstacles:i,paddingBuffer:r,detourCount:o})=>{let s=-1;for(let f=0;f<e.tracePath.length-1;f++)if(Dp(e.tracePath[f],e.tracePath[f+1],n)){s=f;break}if(s===-1)return e;let a=e.tracePath[s],c=e.tracePath[s+1];if(!a||!c)return null;let l=[],u=$p(t.center,t.width,t.height),h=r+o*r;if(Ns(a,c)){let f=[u.maxX+h,u.minX-h];for(let _ of f)l.push(c.y>a.y?[{x:a.x,y:u.minY-h},{x:_,y:u.minY-h},{x:_,y:u.maxY+h},{x:c.x,y:u.maxY+h}]:[{x:a.x,y:u.maxY+h},{x:_,y:u.maxY+h},{x:_,y:u.minY-h},{x:c.x,y:u.minY-h}])}else{let f=[u.maxY+h,u.minY-h];for(let _ of f)l.push(c.x>a.x?[{x:u.minX-h,y:a.y},{x:u.minX-h,y:_},{x:u.maxX+h,y:_},{x:u.maxX+h,y:c.y}]:[{x:u.maxX+h,y:a.y},{x:u.maxX+h,y:_},{x:u.minX-h,y:_},{x:u.minX-h,y:c.y}])}for(let f of l){let _=[...e.tracePath.slice(0,s+1),...f,...e.tracePath.slice(s+1)],y=Ha(_);if(!px(y,i))return{...e,tracePath:y}}return null},dxt=({trace:e,label:t,problem:n,paddingBuffer:i,detourCount:r})=>{let o={...e,tracePath:Ha(e.tracePath)};if(e.globalConnNetId===t.globalConnNetId)return o;let s=hx(n),a=i,c=$p(t.center,t.width,t.height),l={minX:c.minX-a,minY:c.minY-a,maxX:c.maxX+a,maxY:c.maxY+a,chipId:`netlabel-${t.netId}`},u=hxt({initialTrace:o,label:t,labelBounds:l,obstacles:s,paddingBuffer:i,detourCount:r});u&&(o.tracePath=u.tracePath);let{firstInsideIndex:h,lastInsideIndex:f}=uxt(o.tracePath,l),_=pxt({initialTrace:o,firstInsideIndex:h,lastInsideIndex:f,labelBounds:l,obstacles:s});return _||u||o},wT=(e,t)=>{for(let n=0;n<e.length-1;n++){let i=e[n],r=e[n+1];for(let o of t)if(Dp(i,r,o))return!0}return!1},ST=e=>{let t=0;for(let n=1;n<e.length-1;n++){let i=e[n-1],r=e[n],o=e[n+1],s=i.x===r.x,a=r.x===o.x;s!==a&&t++}return t},OB=(e,t)=>{let n=[];return e.x===t.x||e.y===t.y?n.push([e,t]):(n.push([e,{x:t.x,y:e.y},t]),n.push([e,{x:e.x,y:t.y},t])),n},PT=(e,t)=>{for(let n=0;n<e.length-1;n++){let i=e[n],r=e[n+1];for(let o of t)if(Dp(i,r,o))return!0}return!1},fxt=({path:e,obstacles:t,labelBounds:n})=>{if(e.length<=2)return e;let i=(c,l)=>{if(l>=c.length-3)return-1;let u=l,h=!0;for(let f=l;f<c.length-2&&f<l+10&&!(f+2>=c.length);f++){let _=c[f],y=c[f+1],x=c[f+2],v=_.x===y.x,w=y.x===x.x;if(v===w)break;let S=Math.sign(v?y.y-_.y:y.x-_.x);if(f>l){let C=c[f-1],E=C.x===_.x,R=Math.sign(E?_.y-C.y:_.x-C.x);if(v&&E&&S!==R||!v&&!E&&S!==R){h=!1;break}}u=f+2}return h&&u-l>=3?u:-1},r=[...e],o=ST(r),s=!0;for(;s;){s=!1;for(let c=0;c<r.length-3;c++){let l=i(r,c);if(l>0){let u=r[c],h=r[l],f=OB(u,h);for(let _ of f){let y=[...r.slice(0,c+1),..._.slice(1,-1),...r.slice(l)],x=wT(_,t),v=PT(_,n);if(!x&&!v){let w=ST(y),S=l-c-1;r=y,o=w,s=!0;break}}if(s)break}}if(!s)for(let c=0;c<r.length-2;c++){let l=Math.min(r.length-c-2,r.length-2);for(let u=1;u<=l;u++){let h=c+u+1;if(h>=r.length)continue;let f=r[c],_=r[h],y=OB(f,_);for(let x of y){let v=[...r.slice(0,c+1),...x.slice(1,-1),...r.slice(h)],w=x,S=wT(w,t),C=PT(w,n);if(!S&&!C){let E=ST(v);if(E<o||E===o&&v.length<r.length){r=v,o=E,s=!0;break}}}if(s)break}if(s)break}if(!s)for(let c=0;c<r.length-2;c++){let l=r[c],u=r[c+1],h=r[c+2],f=l.x===u.x&&u.x===h.x,_=l.y===u.y&&u.y===h.y;if(f||_){let y=[...r.slice(0,c+1),...r.slice(c+2)],x=wT([l,h],t),v=PT([l,h],n);if(!x&&!v){r=y,s=!0;break}}}}return Ha(r)},mxt=({traces:e,problem:t,allLabelPlacements:n,mergedLabelNetIdMap:i,paddingBuffer:r})=>{let o=!1,s=hx(t),a=e.map(c=>{let l=c.tracePath,h=n.filter(_=>{let y=i[_.globalConnNetId];return y?!y.has(c.globalConnNetId):_.globalConnNetId!==c.globalConnNetId}).map(_=>({minX:_.center.x-_.width/2-r,maxX:_.center.x+_.width/2+r,minY:_.center.y-_.height/2-r,maxY:_.center.y+_.height/2+r})),f=fxt({path:l,obstacles:s,labelBounds:h});return(f.length!==l.length||f.some((_,y)=>_.x!==l[y].x||_.y!==l[y].y))&&(o=!0),{...c,tracePath:f}});return o?a:null},_xt=({traces:e,problem:t,allLabelPlacements:n})=>{let r=!1;for(let l of e)if(l.tracePath.length===4){let[u,h,f,_]=l.tracePath,y=u.y===h.y&&h.x===f.x&&f.y===_.y,x=u.x===h.x&&h.y===f.y&&f.x===_.x,v=u.y===h.y&&h.y===f.y&&f.y===_.y,w=u.x===h.x&&h.x===f.x&&f.x===_.x,S=v||w,C=!1;if(y?C=Math.sign(h.x-u.x)===Math.sign(_.x-f.x):x&&(C=Math.sign(h.y-u.y)===Math.sign(_.y-f.y)),!((y||x)&&!S&&C))return null}let o=hx(t).map(l=>({...l,minX:l.minX+1e-5,maxX:l.maxX-1e-5,minY:l.minY+1e-5,maxY:l.maxY-1e-5})),s=(l,u,h)=>{for(let f of h)if(Dp(l,u,f))return!0;return!1},a=(l,u)=>l.filter(f=>f.globalConnNetId!==u).map(f=>({minX:f.center.x-f.width/2+1e-5,maxX:f.center.x+f.width/2-1e-5,minY:f.center.y-f.height/2+1e-5,maxY:f.center.y+f.height/2-1e-5})),c=e.map(l=>{let u=[...l.tracePath];if(u.length<4)return{...l};let h=a(n,l.globalConnNetId);if(u.length===4){let[_,y,x,v]=u,w,S;if(_.y===y.y&&y.x===x.x&&x.y===v.y){let R=(_.x+v.x)/2;w={x:R,y:y.y},S={x:R,y:x.y}}else{let R=(_.y+v.y)/2;w={x:y.x,y:R},S={x:x.x,y:R}}return s(_,w,o)||s(w,S,o)||s(S,v,o)||s(_,w,h)||s(w,S,h)||s(S,v,h)||(u[1]=w,u[2]=S,r=!0),{...l,tracePath:Ha(u)}}for(let _=1;_<u.length-4;_++){let y=u[_],x=u[_+1],v=u[_+2],w=u[_+3],S=y.y===x.y&&x.x===v.x&&v.y===w.y,C=y.x===x.x&&x.y===v.y&&v.x===w.x,E=y.y===x.y&&x.y===v.y&&v.y===w.y,R=y.x===x.x&&x.x===v.x&&v.x===w.x,I=E||R,k=!1;if(S?k=Math.sign(x.x-y.x)===Math.sign(w.x-v.x):C&&(k=Math.sign(x.y-y.y)===Math.sign(w.y-v.y)),!((S||C)&&!I&&k))continue;let A,L,B=Math.abs(S?y.x-x.x:y.y-x.y),D=Math.abs(S?v.x-w.x:v.y-w.y);if(Math.abs(B-D)<.001)continue;if(S){let X=(y.x+w.x)/2;A={x:X,y:x.y},L={x:X,y:v.y}}else{let X=(y.y+w.y)/2;A={x:x.x,y:X},L={x:v.x,y:X}}s(y,A,o)||s(A,L,o)||s(L,w,o)||s(y,A,h)||s(A,L,h)||s(L,w,h)||(u[_+1]=A,u[_+2]=L,r=!0,_=0)}let f=Ha(u);return{...l,tracePath:f}});return r?c:null},yxt=class extends Rs{constructor(t){super();T(this,"problem");T(this,"traces");T(this,"netTempLabelPlacements");T(this,"netLabelPlacements");T(this,"updatedTraces");T(this,"mergedLabelNetIdMap");T(this,"detourCountByLabel");T(this,"PADDING_BUFFER",.1);this.problem=t.inputProblem,this.traces=t.traces,this.updatedTraces=[...t.traces],this.mergedLabelNetIdMap={},this.detourCountByLabel={};let n=t.netLabelPlacements;if(this.netLabelPlacements=n,!n||n.length===0){this.netTempLabelPlacements=[];return}let i={};for(let o of n){if(o.pinIds.length===0)continue;let s=o.pinIds[0].split(".")[0];if(!s)continue;let a=`${s}-${o.orientation}`;a in i||(i[a]=[]),i[a].push(o)}let r=[];for(let[o,s]of Object.entries(i)){if(s.length<=1){r.push(...s);continue}let a=1/0,c=1/0,l=-1/0,u=-1/0;for(let v of s){let w=$p(v.center,v.width,v.height);a=Math.min(a,w.minX),c=Math.min(c,w.minY),l=Math.max(l,w.maxX),u=Math.max(u,w.maxY)}let h=l-a,f=u-c,_=s[0],y=`merged-group-${o}`,x=new Set(s.map(v=>v.globalConnNetId));this.mergedLabelNetIdMap[y]=x,r.push({..._,globalConnNetId:y,width:h,height:f,center:{x:a+h/2,y:c+f/2},pinIds:[...new Set(s.flatMap(v=>v.pinIds))],mspConnectionPairIds:[...new Set(s.flatMap(v=>v.mspConnectionPairIds))]})}this.netTempLabelPlacements=r}_step(){if(!this.traces||this.traces.length===0||!this.netTempLabelPlacements||this.netTempLabelPlacements.length===0){this.solved=!0;return}this.detourCountByLabel={};let t=lxt(this.traces,this.netTempLabelPlacements);if(t.length===0){this.solved=!0;return}let n=t.filter(c=>{let l=this.mergedLabelNetIdMap[c.label.globalConnNetId];return l?!l.has(c.trace.globalConnNetId):c.trace.globalConnNetId!==c.label.globalConnNetId});if(n.length===0){this.solved=!0;return}let i={};for(let c of this.traces)i[c.mspPairId]=c;let r=new Set;for(let c of n){if(r.has(c.trace.mspPairId))continue;let l=i[c.trace.mspPairId],u=c.label.globalConnNetId,h=this.detourCountByLabel[u]||0,f=dxt({trace:l,label:c.label,problem:this.problem,paddingBuffer:this.PADDING_BUFFER,detourCount:h});f.tracePath!==l.tracePath&&(this.detourCountByLabel[u]=h+1),i[l.mspPairId]=f,r.add(l.mspPairId)}this.updatedTraces=Object.values(i);let o=mxt({traces:this.updatedTraces,problem:this.problem,allLabelPlacements:this.netTempLabelPlacements,mergedLabelNetIdMap:this.mergedLabelNetIdMap,paddingBuffer:this.PADDING_BUFFER});o&&(this.updatedTraces=o);let s=_xt({traces:this.updatedTraces,problem:this.problem,allLabelPlacements:this.netLabelPlacements});s&&(this.updatedTraces=s);let a=new BB({inputProblem:this.problem,inputTraceMap:Object.fromEntries(this.updatedTraces.map(c=>[c.mspPairId,c]))});a.solve(),a.failed||(this.netLabelPlacements=a.netLabelPlacements),this.solved=!0}getOutput(){return{traces:this.updatedTraces,netLabelPlacements:this.netLabelPlacements}}visualize(){let t=Ga(this.problem);t.lines||(t.lines=[]),t.circles||(t.circles=[]),t.texts||(t.texts=[]),t.rects||(t.rects=[]);for(let n of this.updatedTraces)t.lines.push({points:n.tracePath,strokeColor:"purple"});for(let n of this.netLabelPlacements)t.rects.push({center:n.center,width:n.width,height:n.height,fill:Kr(n.globalConnNetId,.35)}),t.points.push({x:n.anchorPoint.x,y:n.anchorPoint.y,color:Kr(n.globalConnNetId,.9)});return t}},gxt=e=>{for(let t of e.chips){let n=MT(t);for(let i of t.pins){if(!(i.x>n.minX&&i.x<n.maxX&&i.y>n.minY&&i.y<n.maxY))continue;let o=i.x-n.minX,s=n.maxX-i.x,a=i.y-n.minY,c=n.maxY-i.y,l=Math.min(o,s,a,c);l===o?i.x=n.minX:l===s?i.x=n.maxX:l===a?i.y=n.minY:i.y=n.maxY,i._facingDirection=void 0}}},xxt=e=>{for(let t of e.chips){let n=t.width/2,i=t.height/2,r=0,o=0;for(let c of t.pins){let l=Math.abs(c.x-t.center.x),u=Math.abs(c.y-t.center.y);l>r&&(r=l),u>o&&(o=u)}let s=Math.max(n,r),a=Math.max(i,o);if(s>n||a>i){t.width=s*2,t.height=a*2;for(let c of t.pins)c._facingDirection=void 0}}};function _f(e,t,n,i={}){return{solverName:e,solverClass:t,getConstructorParams:n,onSolved:i.onSolved}}var jB=class extends Rs{constructor(t){super();T(this,"mspConnectionPairSolver");T(this,"schematicTraceLinesSolver");T(this,"traceOverlapShiftSolver");T(this,"netLabelPlacementSolver");T(this,"traceLabelOverlapAvoidanceSolver");T(this,"startTimeOfPhase");T(this,"endTimeOfPhase");T(this,"timeSpentOnPhase");T(this,"firstIterationOfPhase");T(this,"inputProblem");T(this,"pipelineDef",[_f("mspConnectionPairSolver",Ggt,()=>[{inputProblem:this.inputProblem}],{onSolved:t=>{}}),_f("schematicTraceLinesSolver",txt,()=>[{mspConnectionPairs:this.mspConnectionPairSolver.mspConnectionPairs,dcConnMap:this.mspConnectionPairSolver.dcConnMap,globalConnMap:this.mspConnectionPairSolver.globalConnMap,inputProblem:this.inputProblem,chipMap:this.mspConnectionPairSolver.chipMap}],{onSolved:t=>{}}),_f("traceOverlapShiftSolver",ixt,()=>[{inputProblem:this.inputProblem,inputTracePaths:this.schematicTraceLinesSolver.solvedTracePaths,globalConnMap:this.mspConnectionPairSolver.globalConnMap}],{onSolved:t=>{}}),_f("netLabelPlacementSolver",BB,()=>[{inputProblem:this.inputProblem,inputTraceMap:this.traceOverlapShiftSolver?.correctedTraceMap??Object.fromEntries(this.schematicTraceLinesSolver.solvedTracePaths.map(t=>[t.mspPairId,t]))}],{onSolved:t=>{}}),_f("traceLabelOverlapAvoidanceSolver",yxt,t=>{let n=t.traceOverlapShiftSolver?.correctedTraceMap??Object.fromEntries(t.schematicTraceLinesSolver.solvedTracePaths.map(o=>[o.mspPairId,o])),i=Object.values(n),r=t.netLabelPlacementSolver.netLabelPlacements;return[{inputProblem:t.inputProblem,traces:i,netLabelPlacements:r}]},{onSolved:t=>{if(t.traceLabelOverlapAvoidanceSolver&&t.netLabelPlacementSolver){let{netLabelPlacements:n}=t.traceLabelOverlapAvoidanceSolver.getOutput();t.netLabelPlacementSolver.netLabelPlacements=n}}})]);T(this,"currentPipelineStepIndex",0);this.inputProblem=this.cloneAndCorrectInputProblem(t),this.MAX_ITERATIONS=1e6,this.startTimeOfPhase={},this.endTimeOfPhase={},this.timeSpentOnPhase={},this.firstIterationOfPhase={}}getConstructorParams(){return this.inputProblem}cloneAndCorrectInputProblem(t){let n=structuredClone({...t,_chipObstacleSpatialIndex:void 0});return xxt(n),gxt(n),n}_step(){let t=this.pipelineDef[this.currentPipelineStepIndex];if(!t){this.solved=!0;return}if(this.activeSubSolver){this.activeSubSolver.step(),this.activeSubSolver.solved?(this.endTimeOfPhase[t.solverName]=performance.now(),this.timeSpentOnPhase[t.solverName]=this.endTimeOfPhase[t.solverName]-this.startTimeOfPhase[t.solverName],t.onSolved?.(this),this.activeSubSolver=null,this.currentPipelineStepIndex++):this.activeSubSolver.failed&&(this.error=this.activeSubSolver?.error,this.failed=!0,this.activeSubSolver=null);return}let n=t.getConstructorParams(this);this.activeSubSolver=new t.solverClass(...n),this[t.solverName]=this.activeSubSolver,this.timeSpentOnPhase[t.solverName]=0,this.startTimeOfPhase[t.solverName]=performance.now(),this.firstIterationOfPhase[t.solverName]=this.iterations}solveUntilPhase(t){for(;this.getCurrentPhase().toLowerCase()!==t.toLowerCase();)this.step()}getCurrentPhase(){return this.pipelineDef[this.currentPipelineStepIndex]?.solverName??"none"}visualize(){if(!this.solved&&this.activeSubSolver)return this.activeSubSolver.visualize();let t=[Ga(this.inputProblem),...this.pipelineDef.map(n=>this[n.solverName]?.visualize()).filter(Boolean).map((n,i)=>{for(let r of n.rects??[])r.step=i;for(let r of n.points??[])r.step=i;for(let r of n.circles??[])r.step=i;for(let r of n.texts??[])r.step=i;for(let r of n.lines??[])r.step=i;return n})];return t.length===1?t[0]:{points:t.flatMap(n=>n.points||[]),rects:t.flatMap(n=>n.rects||[]),lines:t.flatMap(n=>n.lines||[]),circles:t.flatMap(n=>n.circles||[]),texts:t.flatMap(n=>n.texts||[])}}preview(){return this.activeSubSolver?this.activeSubSolver.preview():super.preview()}};var LY=Xt(Pn(),1);var FY=Xt(Pn(),1);var zY=Xt(Pn(),1);Xi();Oe();Xi();Oe();Oe();St();Oe();Oe();Ao();Oe();Xi();Oe();function YB(e,t,n,i){return Math.sqrt((n-e)**2+(i-t)**2)}var bxt=e=>{let t=e.filter(o=>o.type==="pcb_port"),n=e.filter(o=>o.type==="pcb_smtpad"),i=e.filter(o=>o.type==="pcb_trace");function r(o,s={}){let a=s.traceWidth||0,c=t.find(l=>YB(l.x,l.y,o.x,o.y)<.01);if(c)return c.pcb_port_id;if(s.isFirstOrLastPoint){let l=n.find(u=>{if(u.shape==="rect")return Math.abs(o.x-u.x)<u.width/2+a/2&&Math.abs(o.y-u.y)<u.height/2+a/2;if(u.shape==="circle")return YB(o.x,o.y,u.x,u.y)<u.radius});if(l)return l.pcb_port_id??null}return null}for(let o of i)for(let s=0;s<o.route.length;s++){let a=o.route[s],c=s===0||s===o.route.length-1;if(a.route_type==="wire"){if(!a.start_pcb_port_id&&s===0){let l=r(a,{isFirstOrLastPoint:c,traceWidth:a.width});l&&(a.start_pcb_port_id=l)}if(!a.end_pcb_port_id&&s===o.route.length-1){let l=r(a,{isFirstOrLastPoint:c,traceWidth:a.width});l&&(a.end_pcb_port_id=l)}}}};function VB(e){bxt(e);let t=e.filter(s=>s.type==="source_trace"),n=e.filter(s=>s.type==="pcb_port"),i=[],r=ar(e),o=new Map;for(let s of n)o.set(s.source_port_id,s);for(let s of t){let a=s.connected_source_port_ids;if(a.length<2)continue;let c=[],l=[];for(let y of a){let x=o.get(y);x?c.push(x):l.push(y)}if(c.length<2)continue;let u=c[0],h=r.getNetConnectedToId(u.pcb_port_id);r.getIdsConnectedToNet(h).filter(y=>e.some(x=>x.type==="pcb_trace"&&("pcb_trace_id"in x&&x.pcb_trace_id===y||"route_id"in x&&x.route_id===y))).length===0&&new Set(c.map(x=>x.pcb_component_id)).size>1&&i.push({type:"pcb_port_not_connected_error",message:`pcb_port_not_connected_error: Pcb ports [${c.map(x=>x.pcb_port_id).join(", ")}] are not connected together through the same net.`,error_type:"pcb_port_not_connected_error",pcb_port_ids:c.map(x=>x.pcb_port_id),pcb_component_ids:c.map(x=>x.pcb_component_id),pcb_port_not_connected_error_id:`pcb_port_not_connected_error_trace_${s.source_trace_id}`})}return i}var vxt=class{constructor({objects:e,getBounds:t,getId:n,CELL_SIZE:i}){T(this,"buckets");T(this,"objectsById");T(this,"getBounds");T(this,"getId");T(this,"CELL_SIZE",.4);T(this,"_idCounter",0);this.buckets=new Map,this.objectsById=new Map,this.getBounds=t,this.getId=n??(()=>this._getNextId()),this.CELL_SIZE=i??this.CELL_SIZE;for(let r of e)this.addObject(r)}_getNextId(){return`${this._idCounter++}`}addObject(e){let t=this.getBounds(e),n=this.getId(e),i={...e,spatialIndexId:n};this.objectsById.set(n,i);let r=Math.floor(t.minX/this.CELL_SIZE),o=Math.floor(t.minY/this.CELL_SIZE),s=Math.floor(t.maxX/this.CELL_SIZE),a=Math.floor(t.maxY/this.CELL_SIZE);for(let c=r;c<=s;c++)for(let l=o;l<=a;l++){let u=`${c}x${l}`,h=this.buckets.get(u);h?h.push(i):this.buckets.set(u,[i])}}removeObject(e){let t=this.objectsById.get(e);if(!t)return!1;this.objectsById.delete(e);let n=this.getBounds(t),i=Math.floor(n.minX/this.CELL_SIZE),r=Math.floor(n.minY/this.CELL_SIZE),o=Math.floor(n.maxX/this.CELL_SIZE),s=Math.floor(n.maxY/this.CELL_SIZE);for(let a=i;a<=o;a++)for(let c=r;c<=s;c++){let l=`${a}x${c}`,u=this.buckets.get(l);if(u){let h=u.findIndex(f=>f.spatialIndexId===e);h!==-1&&(u.splice(h,1),u.length===0&&this.buckets.delete(l))}}return!0}getBucketKey(e,t){return`${Math.floor(e/this.CELL_SIZE)}x${Math.floor(t/this.CELL_SIZE)}`}getObjectsInBounds(e,t=0){let n=[],i=new Set,r=Math.floor((e.minX-t)/this.CELL_SIZE),o=Math.floor((e.minY-t)/this.CELL_SIZE),s=Math.floor((e.maxX+t)/this.CELL_SIZE),a=Math.floor((e.maxY+t)/this.CELL_SIZE);for(let c=r;c<=s;c++)for(let l=o;l<=a;l++){let u=`${c}x${l}`,h=this.buckets.get(u)||[];for(let f of h){let _=f.spatialIndexId;i.has(_)||(i.add(_),n.push(f))}}return n}},gf=e=>e.type==="pcb_trace_segment"?{minX:Math.min(e.x1,e.x2),minY:Math.min(e.y1,e.y2),maxX:Math.max(e.x1,e.x2),maxY:Math.max(e.y1,e.y2)}:zF([e]),CT=.1,wxt=.15;var kT=.005;function Sxt(e){let t=new Set;for(let n of e.route)n.route_type==="wire"&&(n.start_pcb_port_id&&t.add(n.start_pcb_port_id),n.end_pcb_port_id&&t.add(n.end_pcb_port_id));return Array.from(t)}function AT(e){let t=new Set;for(let n of e)for(let i of Sxt(n))t.add(i);return Array.from(t)}var Pxt=(e,t)=>{let n={x:e.x1,y:e.y1},i={x:e.x2,y:e.y2},r={x:t.x1,y:t.y1},o={x:t.x2,y:t.y2},s={x:i.x-n.x,y:i.y-n.y},a={x:o.x-r.x,y:o.y-r.y},c=s.x*s.x+s.y*s.y,l=a.x*a.x+a.y*a.y;if(c===0||l===0){if(c===0&&l===0)return{x:(n.x+r.x)/2,y:(n.y+r.y)/2};if(c===0){let B=Xo(((n.x-r.x)*a.x+(n.y-r.y)*a.y)/l,0,1),D={x:r.x+B*a.x,y:r.y+B*a.y};return{x:(n.x+D.x)/2,y:(n.y+D.y)/2}}let A=Xo(((r.x-n.x)*s.x+(r.y-n.y)*s.y)/c,0,1),L={x:n.x+A*s.x,y:n.y+A*s.y};return{x:(L.x+r.x)/2,y:(L.y+r.y)/2}}let u={x:n.x-r.x,y:n.y-r.y},h=s.x*s.x+s.y*s.y,f=s.x*a.x+s.y*a.y,_=s.x*u.x+s.y*u.y,y=a.x*a.x+a.y*a.y,x=a.x*u.x+a.y*u.y,v=h*y-f*f;if(v<1e-10)return Txt(n,i,r,o,s,a,c,l);let w=(f*x-y*_)/v,S=(h*x-f*_)/v;w=Xo(w,0,1),S=Xo(S,0,1),S=(w*f+x)/y,S=Xo(S,0,1),w=(S*f-_)/h,w=Xo(w,0,1);let C={x:n.x+w*s.x,y:n.y+w*s.y},E={x:r.x+S*a.x,y:r.y+S*a.y},R=C.x-E.x,I=C.y-E.y,k=Math.sqrt(R*R+I*I);return{x:(C.x+E.x)/2,y:(C.y+E.y)/2}},Txt=(e,t,n,i,r,o,s,a)=>{let c=((n.x-e.x)*r.x+(n.y-e.y)*r.y)/s;c=Xo(c,0,1);let l={x:e.x+c*r.x,y:e.y+c*r.y},u=((i.x-e.x)*r.x+(i.y-e.y)*r.y)/s;u=Xo(u,0,1);let h={x:e.x+u*r.x,y:e.y+u*r.y},f=((e.x-n.x)*o.x+(e.y-n.y)*o.y)/a;f=Xo(f,0,1);let _={x:n.x+f*o.x,y:n.y+f*o.y},y=((t.x-n.x)*o.x+(t.y-n.y)*o.y)/a;y=Xo(y,0,1);let x={x:n.x+y*o.x,y:n.y+y*o.y},w=[{pointA:l,pointB:n,distance:Math.sqrt((l.x-n.x)**2+(l.y-n.y)**2)},{pointA:h,pointB:i,distance:Math.sqrt((h.x-i.x)**2+(h.y-i.y)**2)},{pointA:e,pointB:_,distance:Math.sqrt((e.x-_.x)**2+(e.y-_.y)**2)},{pointA:t,pointB:x,distance:Math.sqrt((t.x-x.x)**2+(t.y-x.y)**2)}].reduce((S,C)=>C.distance<S.distance?C:S);return{x:(w.pointA.x+w.pointB.x)/2,y:(w.pointA.y+w.pointB.y)/2}},Xo=(e,t,n)=>Math.max(t,Math.min(n,e)),Ixt=e=>{if(e.type==="pcb_via"||e.type==="pcb_plated_hole"&&e.shape==="circle")return e.outer_diameter/2;if(e.type==="pcb_hole"&&e.hole_shape==="circle")return e.hole_diameter/2;if(e.type==="pcb_smtpad"&&e.shape==="circle")return e.radius;throw new Error(`Could not determine radius of element: ${JSON.stringify(e)}`)},XB=(e,t)=>{let n={x:e.x1,y:e.y1},i={x:e.x2,y:e.y2},r=t.minX,o=t.minY,s=t.maxX,a=t.maxY;if(n.x===i.x&&n.y===i.y){let M=Math.max(r,Math.min(s,n.x)),A=Math.max(o,Math.min(a,n.y));return M===n.x&&A===n.y?{x:n.x,y:n.y}:{x:M,y:A}}let c=i.x-n.x,l=i.y-n.y,u=c!==0?(r-n.x)/c:Number.NEGATIVE_INFINITY,h=c!==0?(s-n.x)/c:Number.POSITIVE_INFINITY,f=l!==0?(o-n.y)/l:Number.NEGATIVE_INFINITY,_=l!==0?(a-n.y)/l:Number.POSITIVE_INFINITY,y=Math.max(Math.min(u,h),Math.min(f,_)),x=Math.min(Math.max(u,h),Math.max(f,_));if(y<=x&&x>=0&&y<=1){let M=Math.max(0,Math.min(1,y));return{x:n.x+M*c,y:n.y+M*l}}let v={x:Math.max(r,Math.min(s,n.x)),y:Math.max(o,Math.min(a,n.y))},w={x:Math.max(r,Math.min(s,i.x)),y:Math.max(o,Math.min(a,i.y))},S=(v.x-n.x)**2+(v.y-n.y)**2,C=(w.x-i.x)**2+(w.y-i.y)**2,E=[{start:{x:r,y:o},end:{x:s,y:o}},{start:{x:s,y:o},end:{x:s,y:a}},{start:{x:s,y:a},end:{x:r,y:a}},{start:{x:r,y:a},end:{x:r,y:o}}],R=Math.min(S,C),I=S<=C?v:w,k=(M,A,L)=>Math.max(A,Math.min(L,M));for(let M of E){let A={x:i.x-n.x,y:i.y-n.y},L={x:M.end.x-M.start.x,y:M.end.y-M.start.y},B={x:n.x-M.start.x,y:n.y-M.start.y},D=A.x*A.x+A.y*A.y,V=A.x*L.x+A.y*L.y,X=A.x*B.x+A.y*B.y,W=L.x*L.x+L.y*L.y,Q=L.x*B.x+L.y*B.y,J=D*W-V*V;if(Math.abs(J)<1e-10)continue;let _t=(V*Q-W*X)/J,st=(D*Q-V*X)/J;_t=k(_t,0,1),st=k(st,0,1);let it={x:n.x+_t*A.x,y:n.y+_t*A.y},et={x:M.start.x+st*L.x,y:M.start.y+st*L.y},vt=it.x-et.x,mt=it.y-et.y,Tt=vt*vt+mt*mt;Tt<R&&(R=Tt,I={x:(it.x+et.x)/2,y:(it.y+et.y)/2})}return I};function Mxt(e){return e.type==="pcb_trace_segment"?[e.layer]:e.type==="pcb_smtpad"?[e.layer]:e.type==="pcb_plated_hole"?Array.isArray(e.layers)?e.layers:[...ju]:e.type==="pcb_hole"?[...ju]:e.type==="pcb_via"?Array.isArray(e.layers)?e.layers:[...ju]:e.type==="pcb_keepout"?Array.isArray(e.layers)?e.layers:[]:[]}function HB(e,{connMap:t}={}){let n=[];t??(t=ar(e));let r=_n(e).pcb_trace.list().flatMap(y=>{let x=[];for(let v=0;v<y.route.length-1;v++){let w=y.route[v],S=y.route[v+1];w.route_type==="wire"&&S.route_type==="wire"&&w.layer===S.layer&&x.push({type:"pcb_trace_segment",pcb_trace_id:y.pcb_trace_id,_pcbTrace:y,thickness:"width"in w?w.width:"width"in S?S.width:wxt,layer:w.layer,x1:w.x,y1:w.y,x2:S.x,y2:S.y})}return x}),o=_n(e).pcb_smtpad.list(),s=_n(e).pcb_plated_hole.list(),a=_n(e).pcb_hole.list(),c=_n(e).pcb_via.list(),l=_n(e).pcb_keepout.list(),u=[...r,...o,...s,...a,...c,...l],h=new vxt({objects:u,getBounds:gf}),f=y=>ll(e,y),_=new Set;for(let y of r){let x=CT,v=gf(y),w=h.getObjectsInBounds(v,x+y.thickness/2);if(!(y.x1===y.x2&&y.y1===y.y2))for(let S of w){if(!Mxt(S).includes(y.layer))continue;if(S.type==="pcb_trace_segment"){let I=S;if(y.layer!==I.layer||t.areIdsConnected(y.pcb_trace_id,I.pcb_trace_id))continue;let k=ng({x:y.x1,y:y.y1},{x:y.x2,y:y.y2},{x:I.x1,y:I.y1},{x:I.x2,y:I.y2})-y.thickness/2-I.thickness/2;if(k>CT-kT)continue;let M=`overlap_${y.pcb_trace_id}_${I.pcb_trace_id}`,A=`overlap_${I.pcb_trace_id}_${y.pcb_trace_id}`;if(_.has(M)||_.has(A))continue;_.add(M),n.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${f(y.pcb_trace_id)} overlaps with ${f(I.pcb_trace_id)} ${k<0?"(accidental contact)":`(gap: ${k.toFixed(3)}mm)`}`,pcb_trace_id:y.pcb_trace_id,source_trace_id:"",pcb_trace_error_id:M,pcb_component_ids:[],center:Pxt(y,I),pcb_port_ids:AT([y._pcbTrace,I._pcbTrace])});continue}let C=sg(S);if(t.areIdsConnected(y.pcb_trace_id,"pcb_trace_id"in S?S.pcb_trace_id:C))continue;if(S.type==="pcb_via"||S.type==="pcb_plated_hole"&&S.shape==="circle"||S.type==="pcb_hole"||S.type==="pcb_smtpad"&&S.shape==="circle"){let I=Ixt(S),M=ig({x:y.x1,y:y.y1},{x:y.x2,y:y.y2},{x:S.x,y:S.y,radius:I})-y.thickness/2;if(M>CT-kT)continue;let A=`overlap_${y.pcb_trace_id}_${C}`;if(_.has(A))continue;_.add(A),n.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${f(y.pcb_trace_id)} overlaps with ${S.type} "${f(sg(S))}" ${M<0?"(accidental contact)":`(gap: ${M.toFixed(3)}mm)`}`,pcb_trace_id:y.pcb_trace_id,center:XB(y,gf(S)),source_trace_id:"",pcb_trace_error_id:A,pcb_component_ids:["pcb_component_id"in S?S.pcb_component_id:void 0].filter(Boolean),pcb_port_ids:[...AT([y._pcbTrace]),"pcb_port_id"in S?S.pcb_port_id:void 0].filter(Boolean)})}let R=Md({x:y.x1,y:y.y1},{x:y.x2,y:y.y2},gf(S))-y.thickness/2;if(R+kT<x){let I=`overlap_${y.pcb_trace_id}_${C}`;if(_.has(I))continue;_.add(I),n.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${f(y.pcb_trace_id)} overlaps with ${S.type} "${f(sg(S))}" ${R<0?"(accidental contact)":`(gap: ${R.toFixed(3)}mm)`}`,pcb_trace_id:y.pcb_trace_id,source_trace_id:"",pcb_trace_error_id:I,pcb_component_ids:["pcb_component_id"in S?S.pcb_component_id:void 0].filter(Boolean),center:XB(y,gf(S)),pcb_port_ids:[...AT([y._pcbTrace]),"pcb_port_id"in S?S.pcb_port_id:void 0].filter(Boolean)})}}}return n}function GB(e){return e.area()>=0}function UB({center:e,size:t,rotationDeg:n=0}){let i=e.x,r=e.y,o=t.width/2,s=t.height/2,a=[new Yo(i-o,r-s),new Yo(i+o,r-s),new Yo(i+o,r+s),new Yo(i-o,r+s)],c=new hf(a);if(n){let l=By(n,i,r),u=a.map(h=>{let f=ln(l,{x:h.x,y:h.y});return new Yo(f.x,f.y)});c=new hf(u)}return GB(c)||c.reverse(),c}function Ext({board:e}){if(e.outline&&e.outline.length>0){let t=e.outline.map(i=>new Yo(i.x,i.y)),n=new hf(t);return GB(n)||n.reverse(),n}return e.center&&typeof e.width=="number"&&typeof e.height=="number"?UB({center:e.center,size:{width:e.width,height:e.height},rotationDeg:0}):null}function Cxt({circuitJson:e,component:t}){if(t.source_component_id){let n=e.find(i=>i.type==="source_component"&&i.source_component_id===t.source_component_id);if(n&&"name"in n&&n.name)return n.name}return ll(e,t.pcb_component_id)||"Unknown"}function kxt(e,t,n,i,r,o){let s=new Yo(n.x,n.y);if(!t.contains(s)){let x=t.distanceTo(s);return Array.isArray(x)?x[0]:Number(x)||0}let a=i/2,c=r/2,l=[{x:n.x-a,y:n.y-c},{x:n.x+a,y:n.y-c},{x:n.x+a,y:n.y+c},{x:n.x-a,y:n.y+c}],u=[];for(let x=0;x<4;x++){let v=(x+1)%4;u.push({x:(l[x].x+l[v].x)/2,y:(l[x].y+l[v].y)/2})}let h=By(o,n.x,n.y),f=x=>{let v=ln(h,x);return new Yo(v.x,v.y)},_=l.concat(u).map(f),y=0;for(let x of _)if(!t.contains(x)){let v=t.distanceTo(x),w=Array.isArray(v)?v[0]:Number(v)||0;w>y&&(y=w)}if(y>0)return y;try{let x=sT.intersect(e,t),v=0;x?Array.isArray(x)?v=x.reduce((S,C)=>S+(typeof C.area=="function"?C.area():0),0):typeof x.area=="function"?v=x.area():v=0:v=0;let w=e.area();if(v>0&&v<w){let S=1-v/w,C=Math.abs(i),E=Math.abs(r);return Math.min(C,E)*S}else return .1}catch{return .1}}function qB(e){let t=e.find(o=>o.type==="pcb_board");if(!t)return[];let n=Ext({board:t});if(!n)return[];let i=e.filter(o=>o.type==="pcb_component");if(i.length===0)return[];let r=[];for(let o of i){if(!o.center||typeof o.width!="number"||typeof o.height!="number"||o.width<=0||o.height<=0)continue;let s=UB({center:o.center,size:{width:o.width,height:o.height},rotationDeg:o.rotation||0});if(s.area()===0||n.contains(s))continue;let c=kxt(s,n,o.center,o.width,o.height,o.rotation||0),l=Cxt({circuitJson:e,component:o}),u=Math.round(c*100)/100;r.push({type:"pcb_component_outside_board_error",error_type:"pcb_component_outside_board_error",pcb_component_outside_board_error_id:`pcb_component_outside_board_${o.pcb_component_id}`,message:`Component ${l} (${o.pcb_component_id}) extends outside board boundaries by ${u}mm`,pcb_component_id:o.pcb_component_id,pcb_board_id:t.pcb_board_id,component_center:o.center,component_bounds:{min_x:s.box.xmin,max_x:s.box.xmax,min_y:s.box.ymin,max_y:s.box.ymax},subcircuit_id:o.subcircuit_id,source_component_id:o.source_component_id})}return r}var NT=[{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 qn(e){if(e==null)return"";if(e===0)return"0";let t=Math.abs(e),n=NT.find(o=>{let s=t/o.value;return s>=1&&s<1e3})||NT[NT.length-1],r=(e/n.value).toPrecision(3);return r.includes(".")&&!/\.0+$/.test(r)&&(r=r.replace(/0+$/,"")),r=r.replace(/\.0+$/,""),`${r}${n.symbol}`}St();Z();Cd();Xi();vs();Oe();var EX=Xt(co(),1);var rI=Xt(Pn(),1),Kp=Xt(co(),1),EUt=Xt(co(),1);var Ml=Xt(Sl(),1);var CX=Xt(Sl(),1),kX=Xt(Sl(),1);var AX=Xt(Sl(),1);var NX=Xt(Sl(),1);var RX=Xt(Sl(),1),OX=Xt(co(),1);var v2t=Object.defineProperty,w2t=(e,t)=>{for(var n in t)v2t(e,n,{get:t[n],enumerable:!0})},dY={};w2t(dY,{Battery:()=>aX,Board:()=>DY,Breakout:()=>QY,BreakoutPoint:()=>tX,CadAssembly:()=>IY,CadModel:()=>TY,Capacitor:()=>$Y,Chip:()=>zx,Constraint:()=>WY,CopperPour:()=>sX,Crystal:()=>dX,Cutout:()=>Nf,Diode:()=>jY,FabricationNotePath:()=>ZY,FabricationNoteText:()=>KY,Footprint:()=>PY,Fuse:()=>YY,Group:()=>th,Hole:()=>pI,Inductor:()=>uX,Jumper:()=>XY,Keepout:()=>Cx,Led:()=>HY,Mosfet:()=>mX,Net:()=>aI,NetLabel:()=>eX,NormalComponent:()=>In,PcbTrace:()=>uI,PinHeader:()=>cX,Pinout:()=>BY,PlatedHole:()=>Jp,Port:()=>Ei,Potentiometer:()=>pX,PowerSource:()=>GY,PrimitiveComponent:()=>Ie,PushButton:()=>hX,Renderable:()=>oI,Resistor:()=>qY,Resonator:()=>lX,SchematicArc:()=>vX,SchematicBox:()=>SX,SchematicCell:()=>IX,SchematicCircle:()=>wX,SchematicLine:()=>xX,SchematicRect:()=>bX,SchematicRow:()=>TX,SchematicTable:()=>PX,SchematicText:()=>gX,SilkscreenCircle:()=>nX,SilkscreenLine:()=>rX,SilkscreenPath:()=>lI,SilkscreenRect:()=>iX,SilkscreenText:()=>Rx,SmtPad:()=>Ex,SolderJumper:()=>VY,Subcircuit:()=>JY,Switch:()=>_X,Symbol:()=>MX,TestPoint:()=>yX,Trace:()=>yo,TraceHint:()=>fI,Transistor:()=>fX,Via:()=>oX,VoltageSource:()=>UY});var S2t=(0,_Y.default)("tscircuit:renderable"),Fs=["ReactSubtreesRender","SourceNameDuplicateComponentRemoval","PcbFootprintStringRender","InitializePortsFromChildren","CreateNetsFromProps","AssignFallbackProps","CreateTracesFromProps","CreateTracesFromNetLabels","CreateTraceHintsFromProps","SourceGroupRender","AssignNameToUnnamedComponents","SourceRender","SourceParentAttachment","PortMatching","OptimizeSelectorCache","SourceTraceRender","SourceAddConnectivityMapKey","SourceDesignRuleChecks","SimulationRender","SchematicComponentRender","SchematicPortRender","SchematicPrimitiveRender","SchematicComponentSizeCalculation","SchematicLayout","SchematicTraceRender","SchematicReplaceNetLabelsWithSymbols","PcbComponentRender","PcbPrimitiveRender","PcbFootprintLayout","PcbPortRender","PcbPortAttachment","PcbComponentSizeCalculation","PcbComponentAnchorAlignment","PcbLayout","PcbBoardAutoSize","PcbTraceHintRender","PcbManualTraceRender","PcbTraceRender","PcbRouteNetIslands","PcbCopperPourRender","PcbDesignRuleChecks","SilkscreenOverlapAdjustment","CadModelRender","PartsEngineRender"],P2t={PcbFootprintLayout:["PcbFootprintStringRender"],PcbComponentSizeCalculation:["PcbFootprintStringRender"],PcbLayout:["PcbFootprintStringRender"],PcbBoardAutoSize:["PcbFootprintStringRender"],PcbTraceHintRender:["PcbFootprintStringRender"],PcbManualTraceRender:["PcbFootprintStringRender"],PcbCopperPourRender:["PcbFootprintStringRender","PcbTraceRender","PcbRouteNetIslands"],PcbTraceRender:["PcbFootprintStringRender"],PcbRouteNetIslands:["PcbFootprintStringRender"],PcbDesignRuleChecks:["PcbFootprintStringRender"],SilkscreenOverlapAdjustment:["PcbFootprintStringRender"],CadModelRender:["PcbFootprintStringRender"],PartsEngineRender:["PcbFootprintStringRender"],PcbComponentAnchorAlignment:["PcbFootprintStringRender"]},T2t=0,oI=class{constructor(e){T(this,"renderPhaseStates");T(this,"shouldBeRemoved",!1);T(this,"children");T(this,"isPcbPrimitive",!1);T(this,"isSchematicPrimitive",!1);T(this,"_renderId");T(this,"_currentRenderPhase",null);T(this,"_asyncEffects",[]);T(this,"parent",null);this._renderId=`${T2t++}`,this.children=[],this.renderPhaseStates={};for(let t of Fs)this.renderPhaseStates[t]={initialized:!1,dirty:!1}}_markDirty(e){this.renderPhaseStates[e].dirty=!0;let t=Fs.indexOf(e);for(let n=t+1;n<Fs.length;n++)this.renderPhaseStates[Fs[n]].dirty=!0;this.parent?._markDirty&&this.parent._markDirty(e)}_queueAsyncEffect(e,t){let n={promise:t(),phase:this._currentRenderPhase,effectName:e,complete:!1};this._asyncEffects.push(n),"root"in this&&this.root&&this.root.emit("asyncEffect:start",{effectName:e,componentDisplayName:this.getString(),phase:n.phase}),n.promise.then(()=>{n.complete=!0,"root"in this&&this.root&&this.root.emit("asyncEffect:end",{effectName:e,componentDisplayName:this.getString(),phase:n.phase})}).catch(i=>{console.error(`Async effect error in ${n.phase} "${e}":
230
- ${i.stack}`),n.complete=!0,"root"in this&&this.root&&this.root.emit("asyncEffect:end",{effectName:e,componentDisplayName:this.getString(),phase:n.phase,error:i.toString()})})}_emitRenderLifecycleEvent(e,t){S2t(`${e}:${t} ${this.getString()}`);let n=`renderable:renderLifecycle:${e}:${t}`,i={renderId:this._renderId,componentDisplayName:this.getString(),type:n};"root"in this&&this.root&&(this.root.emit(n,i),this.root.emit("renderable:renderLifecycle:anyEvent",{...i,type:n}))}getString(){return this.constructor.name}_hasIncompleteAsyncEffects(){return this._asyncEffects.some(e=>!e.complete)}_hasIncompleteAsyncEffectsInSubtreeForPhase(e){for(let t of this._asyncEffects)if(!t.complete&&t.phase===e)return!0;for(let t of this.children)if(t._hasIncompleteAsyncEffectsInSubtreeForPhase(e))return!0;return!1}getCurrentRenderPhase(){return this._currentRenderPhase}getRenderGraph(){return{id:this._renderId,currentPhase:this._currentRenderPhase,renderPhaseStates:this.renderPhaseStates,shouldBeRemoved:this.shouldBeRemoved,children:this.children.map(e=>e.getRenderGraph())}}runRenderCycle(){for(let e of Fs)this.runRenderPhaseForChildren(e),this.runRenderPhase(e)}runRenderPhase(e){this._currentRenderPhase=e;let t=this.renderPhaseStates[e],n=t.initialized,i=t.dirty;if(!n&&this.shouldBeRemoved)return;if(this.shouldBeRemoved&&n){this._emitRenderLifecycleEvent(e,"start"),this?.[`remove${e}`]?.(),t.initialized=!1,t.dirty=!1,this._emitRenderLifecycleEvent(e,"end");return}let r=Fs.indexOf(e)-1;if(r>=0){let s=Fs[r];if(this._asyncEffects.filter(c=>c.phase===s).some(c=>!c.complete))return}let o=P2t[e]||[];for(let s of o)if(this._hasIncompleteAsyncEffectsInSubtreeForPhase(s))return;if(this._emitRenderLifecycleEvent(e,"start"),n){i&&(this?.[`update${e}`]?.(),t.dirty=!1),this._emitRenderLifecycleEvent(e,"end");return}t.dirty=!1,this?.[`doInitial${e}`]?.(),t.initialized=!0,this._emitRenderLifecycleEvent(e,"end")}runRenderPhaseForChildren(e){for(let t of this.children)t.runRenderPhaseForChildren(e),t.runRenderPhase(e)}renderError(e){throw typeof e=="string"?new Error(e):new Error(JSON.stringify(e,null,2))}},Mx={},yY=e=>{let t=Object.fromEntries(Object.entries(e).map(([n,i])=>[n.toLowerCase(),i]));Object.assign(Mx,e),Object.assign(Mx,t)},I2t=class extends Error{constructor(e,t,n){let i,r=Object.keys(n).filter(c=>c!=="_errors"),o=[],s=t.pinLabels;if(s)for(let[c,l]of Object.entries(s)){let u=Array.isArray(l)?l:[l];for(let h of u)typeof h=="string"&&(h.startsWith(" ")||h.endsWith(" "))&&o.push(`pinLabels.${c} ("${h}" has leading or trailing spaces)`)}let a=r.map(c=>c==="pinLabels"&&o.length>0?o.join(", "):n[c]._errors[0]?`${c} (${n[c]._errors[0]})`:`${c} (${JSON.stringify(n[c])})`).join(", ");"name"in t?i=`Invalid props for ${e} "${t.name}": ${a}`:"footprint"in t&&typeof t.footprint=="string"?i=`Invalid props for ${e} (unnamed ${t.footprint} component): ${a}`:i=`Invalid props for ${e} (unnamed): ${a}`,super(i),this.componentName=e,this.originalProps=t,this.formattedError=n}};function VT(e,t){let n=t.match(/^#(\w+)/);if(n)return e.props.id===n[1];let i=t.match(/^\.(\w+)/);if(i)return e.isMatchingNameOrAlias(i[1]);let[r,...o]=t.split(/(?=[#.[])/);return r==="pin"&&(r="port"),r&&r!=="*"&&e.lowercaseComponentName!==r.toLowerCase()?!1:o.every(s=>{if(s.startsWith("#"))return e.props.id===s.slice(1);if(s.startsWith("."))return e.isMatchingNameOrAlias(s.slice(1));let a=s.match(/\[(\w+)=['"]?(.+?)['"]?\]/);if(!a)return!0;let[,c,l]=a;return e.props[c].toString()===l})}var sI={isTag:e=>!0,getParent:e=>e.parent,getChildren:e=>e.children,getName:e=>e.lowercaseComponentName,getAttributeValue:(e,t)=>{if(t==="class"&&"getNameAndAliases"in e)return e.getNameAndAliases().join(" ");if(t==="name"&&e._parsedProps?.name)return e._parsedProps.name;if(e._parsedProps&&t in e._parsedProps){let i=e._parsedProps[t];return typeof i=="string"?i:i!=null?String(i):null}if(t in e){let i=e[t];return typeof i=="string"?i:i!=null?String(i):null}let n=e._attributeLowerToCamelNameMap;if(n){let i=n[t];if(i&&i in e){let r=e[i];return typeof r=="string"?r:r!=null?String(r):null}}return null},hasAttrib:(e,t)=>{if(t==="class")return!!e._parsedProps?.name;if(e._parsedProps&&t in e._parsedProps||t in e)return!0;let n=e._attributeLowerToCamelNameMap;if(n){let i=n[t];if(i&&i in e)return!0}return!1},getSiblings:e=>e.parent?e.parent.children:[],prevElementSibling:e=>{if(!e.parent)return null;let t=e.parent.children,n=t.indexOf(e);return n>0?t[n-1]:null},getText:()=>"",removeSubsets:e=>e.filter((t,n)=>!e.some((i,r)=>n!==r&&i!==t&&i.getDescendants().includes(t))),existsOne:(e,t)=>t.some(e),findAll:(e,t)=>{let n=[],i=r=>{e(r)&&n.push(r);for(let o of r.children)i(o)};for(let r of t)i(r);return n},findOne:(e,t)=>{for(let n of t){if(e(n))return n;let i=n.children;if(i.length>0){let r=sI.findOne(e,i);if(r)return r}}return null},equals:(e,t)=>e._renderId===t._renderId,isHovered:e=>!1,isVisited:e=>!1,isActive:e=>!1},M2t={...sI,getChildren:e=>e.children.filter(t=>!t.isSubcircuit)},Xj={...sI,getChildren:e=>e.children.filter(t=>t.isSubcircuit)},Vj=e=>{if(/net\.[^\s>]*\./.test(e))throw new Error('Net names cannot contain a period, try using "sel.net..." to autocomplete with conventional net names, e.g. V3_3');if(/net\.[^\s>]*[+-]/.test(e))throw new Error('Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P');if(/net\.[0-9]/.test(e)){let t=e.match(/net\.([^ >]+)/),n=t?t[1]:"";throw new Error(`Net name "${n}" cannot start with a number, try using a prefix like "VBUS1"`)}return e.replace(/ pin(?=[\d.])/g," port").replace(/ subcircuit\./g," group[isSubcircuit=true]").replace(/([^ ])\>([^ ])/g,"$1 > $2").replace(/(^|[ >])(?!pin\.)(?!port\.)(?!net\.)([A-Z][A-Za-z0-9_-]*)\.([A-Za-z0-9_-]+)/g,(t,n,i,r)=>{let o=/^\d+$/.test(r)?`pin${r}`:r;return`${n}.${i} > .${o}`}).trim()},HT={adapter:M2t,cacheResults:!0},Ie=class extends oI{constructor(t){super(t);T(this,"parent",null);T(this,"children");T(this,"childrenPendingRemoval");T(this,"props");T(this,"_parsedProps");T(this,"externallyAddedAliases");T(this,"isPrimitiveContainer",!1);T(this,"canHaveTextChildren",!1);T(this,"source_group_id",null);T(this,"source_component_id",null);T(this,"schematic_component_id",null);T(this,"pcb_component_id",null);T(this,"cad_component_id",null);T(this,"fallbackUnassignedName");T(this,"_cachedSelectAllQueries",new Map);T(this,"_cachedSelectOneQueries",new Map);this.children=[],this.childrenPendingRemoval=[],this.props=t??{},this.externallyAddedAliases=[];let i=("partial"in this.config.zodProps?this.config.zodProps.partial({name:!0}):this.config.zodProps).safeParse(t??{});if(i.success)this._parsedProps=i.data;else throw new I2t(this.lowercaseComponentName,this.props,i.error.format())}get config(){return{componentName:"",zodProps:p.object({}).passthrough()}}get componentName(){return this.config.componentName}getInheritedProperty(t){let n=this;for(;n;){if(n._parsedProps&&t in n._parsedProps)return n._parsedProps[t];n=n.parent}if(this.root?.platform&&t in this.root.platform)return this.root.platform[t]}get lowercaseComponentName(){return this.componentName.toLowerCase()}get isSubcircuit(){return!!this.props.subcircuit||this.lowercaseComponentName==="group"&&this?.parent?.isRoot}get isGroup(){return this.lowercaseComponentName==="group"}get name(){return this._parsedProps.name??this.fallbackUnassignedName}setProps(t){let n=this.config.zodProps.parse({...this.props,...t}),i=this.props;this.props=n,this._parsedProps=this.config.zodProps.parse(t),this.onPropsChange({oldProps:i,newProps:n,changedProps:Object.keys(t)}),this.parent?.onChildChanged?.(this)}_getPcbRotationBeforeLayout(){let{pcbRotation:t}=this.props;return typeof t=="string"?parseFloat(t):t??null}computePcbPropsTransform(){let{_parsedProps:t}=this,n=this._getPcbRotationBeforeLayout()??0;return Gn(fn(t.pcbX??0,t.pcbY??0),va(n*Math.PI/180))}_computePcbGlobalTransformBeforeLayout(){let t=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if(t&&this.props.pcbX===void 0&&this.props.pcbY===void 0){let n=this._getPcbRotationBeforeLayout()??0;return Gn(this.parent?._computePcbGlobalTransformBeforeLayout()??vi(),Gn(fn(t.x,t.y),va(n*Math.PI/180)))}if(this.isPcbPrimitive){let n=this.getPrimitiveContainer();if(n&&n._parsedProps.layer==="bottom")return Gn(this.parent?._computePcbGlobalTransformBeforeLayout()??vi(),_N(),this.computePcbPropsTransform())}return Gn(this.parent?._computePcbGlobalTransformBeforeLayout()??vi(),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(),n=t?t._parsedProps.layer==="bottom":!1;return{isFlipped:n,maybeFlipLayer:r=>n?r==="top"?"bottom":"top":r}}_setPositionFromLayout(t){throw new Error(`_setPositionFromLayout not implemented for ${this.componentName}`)}computeSchematicPropsTransform(){let{_parsedProps:t}=this;return Gn(fn(t.schX??0,t.schY??0))}computeSchematicGlobalTransform(){let t=this._getSchematicGlobalManualPlacementTransform(this);return t||Gn(this.parent?.computeSchematicGlobalTransform?.()??vi(),this.computeSchematicPropsTransform())}_getSchematicSymbolName(){let{_parsedProps:t}=this,n=this.config.schematicSymbolName,i={horizontal:0,pos_left:0,neg_right:0,pos_right:180,neg_left:180,pos_top:270,neg_bottom:90,vertical:270,pos_bottom:90,neg_top:90},r=t.schOrientation!==void 0?i[t.schOrientation]:t.schRotation;if(r===void 0&&(r=0),r=r%360,r<0&&(r+=360),t.schRotation!==void 0&&r%90!==0)throw new Error(`Schematic rotation ${t.schRotation} is not supported for ${this.componentName}`);let o=`${n}_horz`,s=`${n}_vert`,a=`${n}_up`,c=`${n}_down`,l=`${n}_left`,u=`${n}_right`;if(u in Un&&r===0)return u;if(a in Un&&r===90)return a;if(l in Un&&r===180)return l;if(c in Un&&r===270)return c;if(o in Un&&(r===0||r===180))return o;if(s in Un&&(r===90||r===270))return s;if(n in Un)return n}_getSchematicSymbolNameOrThrow(){let t=this._getSchematicSymbolName();if(!t)throw new Error(`No schematic symbol found (given: "${this.config.schematicSymbolName}")`);return t}getSchematicSymbol(){let t=this._getSchematicSymbolName();return t?Un[t]??null:null}_getPcbManualPlacementForComponent(t){if(!this.isSubcircuit)return null;let n=this.props.manualEdits;if(!n)return null;let i=n?.pcb_placements;if(!i)return null;for(let r of i)if(VT(t,r.selector)||t.props.name===r.selector)return kn(this._computePcbGlobalTransformBeforeLayout(),r.center);return null}_getSchematicManualPlacementForComponent(t){if(!this.isSubcircuit)return null;let n=this.props.manualEdits;if(!n)return null;let i=n.schematic_placements;if(!i)return null;for(let r of i)if(VT(t,r.selector)||t.props.name===r.selector)return kn(this.computeSchematicGlobalTransform(),r.center);return null}_getSchematicGlobalManualPlacementTransform(t){let n=this.getSubcircuit()?._parsedProps.manualEdits;if(!n)return null;for(let i of n.schematic_placements??[])if((VT(t,i.selector)||t.props.name===i.selector)&&i.relative_to==="group_center")return Gn(this.parent?._computePcbGlobalTransformBeforeLayout()??vi(),fn(i.center.x,i.center.y));return null}_getGlobalPcbPositionBeforeLayout(){return kn(this._computePcbGlobalTransformBeforeLayout(),{x:0,y:0})}_getGlobalSchematicPositionBeforeLayout(){return kn(this.computeSchematicGlobalTransform(),{x:0,y:0})}get root(){return this.parent?.root??null}onAddToParent(t){this.parent=t}onPropsChange(t){}onChildChanged(t){this.parent?.onChildChanged?.(t)}add(t){let n=t.__text;if(typeof n=="string"){if(this.canHaveTextChildren||n.trim()==="")return;throw new Error(`Invalid JSX Element: Expected a React component but received text "${n}"`)}if(Object.keys(t).length!==0){if(this.lowercaseComponentName==="board"&&t.lowercaseComponentName==="board")throw new Error("Nested boards are not supported");if(!t.onAddToParent)throw new Error(`Invalid JSX Element: Expected a React component but received "${JSON.stringify(t)}"`);t.onAddToParent(this),t.parent=this,this.children.push(t)}}addAll(t){for(let n of t)this.add(n)}remove(t){this.children=this.children.filter(n=>n!==t),this.childrenPendingRemoval.push(t),t.shouldBeRemoved=!0}getSubcircuitSelector(){let t=this.name,n=t?`${this.lowercaseComponentName}.${t}`:this.lowercaseComponentName;return!this.parent||this.parent.isSubcircuit?n:`${this.parent.getSubcircuitSelector()} > ${n}`}getFullPathSelector(){let t=this.name,n=t?`${this.lowercaseComponentName}.${t}`:this.lowercaseComponentName,i=this.parent?.getFullPathSelector?.();return i?`${i} > ${n}`:n}getNameAndAliases(){return[this.name,...this._parsedProps.portHints??[]].filter(Boolean)}isMatchingNameOrAlias(t){return this.getNameAndAliases().includes(t)}isMatchingAnyOf(t){return this.getNameAndAliases().some(n=>t.map(i=>i.toString()).includes(n))}getPcbSize(){throw new Error(`getPcbSize not implemented for ${this.componentName}`)}doesSelectorMatch(t){let n=[this.componentName,this.lowercaseComponentName],i=[this.name].filter(Boolean),r=t.trim().split(/\> /)[0],o=r[0];return r.length>1?!1:!!(t==="*"||t[0]==="#"&&t.slice(1)===this.props.id||t[0]==="."&&i.includes(t.slice(1))||/^[a-zA-Z0-9_]/.test(o)&&n.includes(o))}getSubcircuit(){if(this.isSubcircuit)return this;let t=this.parent?.getSubcircuit?.();if(!t)throw new Error("Component is not inside an opaque group (no board?)");return t}getGroup(){return this.isGroup?this:this.parent?.getGroup?.()??null}doInitialAssignNameToUnnamedComponents(){this._parsedProps.name||(this.fallbackUnassignedName=this.getSubcircuit().getNextAvailableName(this))}doInitialOptimizeSelectorCache(){if(!this.isSubcircuit)return;let t=this.selectAll("port");for(let n of t){let i=n.parent?.getNameAndAliases(),r=n.getNameAndAliases();if(i)for(let o of i)for(let s of r){let a=[`.${o} > .${s}`,`.${o} .${s}`];for(let c of a){let l=this._cachedSelectAllQueries.get(c);l?l.push(n):this._cachedSelectAllQueries.set(c,[n])}}}for(let[n,i]of this._cachedSelectAllQueries.entries())i.length===1&&this._cachedSelectOneQueries.set(n,i[0])}selectAll(t){if(this._cachedSelectAllQueries.has(t))return this._cachedSelectAllQueries.get(t);let n=Vj(t),i=o5(n,this,HT);if(i.length>0)return this._cachedSelectAllQueries.set(t,i),i;let[r,...o]=n.split(" "),s=Dy(r,this,{adapter:Xj});if(!s)return[];let a=s.selectAll(o.join(" "));return this._cachedSelectAllQueries.set(t,a),a}selectOne(t,n){if(this._cachedSelectOneQueries.has(t))return this._cachedSelectOneQueries.get(t);let i=Vj(t);n?.port&&(n.type="port");let r=null;if(n?.type&&(r=o5(i,this,HT).find(l=>l.lowercaseComponentName===n.type)),r??(r=Dy(i,this,HT)),r)return this._cachedSelectOneQueries.set(t,r),r;let[o,...s]=i.split(" "),a=Dy(o,this,{adapter:Xj});return a?(r=a.selectOne(s.join(" "),n),this._cachedSelectOneQueries.set(t,r),r):null}getAvailablePcbLayers(){if(this.isPcbPrimitive){let{maybeFlipLayer:t}=this._getPcbPrimitiveFlippedHelpers();return"layer"in this._parsedProps||this.componentName==="SmtPad"?[t(this._parsedProps.layer??"top")]:"layers"in this._parsedProps?this._parsedProps.layers:this.componentName==="PlatedHole"?this.root?._getBoard()?.allLayers??["top","bottom"]:[]}return[]}getDescendants(){let t=[];for(let n of this.children)t.push(n),t.push(...n.getDescendants());return t}getSelectableDescendants(){let t=[];for(let n of this.children)n.isSubcircuit?t.push(n):(t.push(n),t.push(...n.getSelectableDescendants()));return t}_getPinCount(){return 0}_getSchematicBoxDimensions(){return null}_getSchematicBoxComponentDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;let{_parsedProps:t}=this;return{schWidth:t.schWidth,schHeight:t.schHeight}}renderError(t){if(typeof t=="string")return super.renderError(t);this.root?.db.pcb_placement_error.insert(t)}getString(){let{lowercaseComponentName:t,_parsedProps:n,parent:i}=this;return n?.pinNumber!==void 0&&i?.props?.name&&n?.name?`<${t}#${this._renderId}(pin:${n.pinNumber} .${i?.props.name}>.${n.name}) />`:i?.props?.name&&n?.name?`<${t}#${this._renderId}(.${i?.props.name}>.${n?.name}) />`:n?.from&&n?.to?`<${t}#${this._renderId}(from:${n.from} to:${n?.to}) />`:n?.name?`<${t}#${this._renderId} name=".${n?.name}" />`:n?.portHints?`<${t}#${this._renderId}(${n.portHints.map(r=>`.${r}`).join(", ")}) />`:`<${t}#${this._renderId} />`}get[Symbol.toStringTag](){return this.getString()}[Symbol.for("nodejs.util.inspect.custom")](){return this.getString()}},E2t=class extends Ie{constructor(e,t){super(e),this._parsedProps={...e,error:t,type:e.type||"unknown",component_name:e.name,error_type:"source_failed_to_create_component_error",message:t instanceof Error?t.message:String(t),pcbX:e.pcbX,pcbY:e.pcbY,schX:e.schX,schY:e.schY}}get config(){return{componentName:"ErrorPlaceholder",zodProps:p.object({}).passthrough()}}doInitialSourceRender(){if(this.root?.db){let e=this._getGlobalPcbPositionBeforeLayout(),t=this._getGlobalSchematicPositionBeforeLayout();this.root.db.source_failed_to_create_component_error.insert({component_name:this._parsedProps.component_name,error_type:"source_failed_to_create_component_error",message:`Could not create ${this._parsedProps.componentType??"component"}${this._parsedProps.name?` "${this._parsedProps.name}"`:""}. ${this._parsedProps.error?.formattedError?._errors?.join("; ")||this._parsedProps.message}`,pcb_center:e,schematic_center:t})}}};function C2t(e,t){return new E2t(e,t)}function k2t(e,t){let n=e;return n.__tsci={...t},e}var A2t={supportsMutation:!0,createInstance(e,t){let n=Mx[e];if(!n)throw Object.keys(Mx).length===0?new Error("No components registered in catalogue, did you forget to import lib/register-catalogue in your test file?"):new Error(`Unsupported component type "${e}". No element with this name is registered in the @tscircuit/core catalogue. Check for typos or see https://docs.tscircuit.com/category/built-in-elements for a list of valid components. To add your own component, see docs/CREATING_NEW_COMPONENTS.md`);try{return k2t(new n(t),{})}catch(i){return C2t({...t,componentType:e},i)}},createTextInstance(e){return{__text:e}},appendInitialChild(e,t){e.add(t)},appendChild(e,t){e.add(t)},appendChildToContainer(e,t){e.add(t)},finalizeInitialChildren(){return!1},prepareUpdate(){return null},shouldSetTextContent(){return!1},getRootHostContext(){return{}},getChildHostContext(){return{}},prepareForCommit(){return null},resetAfterCommit(){},commitMount(){},commitUpdate(){},removeChild(){},clearContainer(){},supportsPersistence:!1,getPublicInstance(e){return e},preparePortalMount(e){throw new Error("Function not implemented.")},scheduleTimeout(e,t){throw new Error("Function not implemented.")},cancelTimeout(e){throw new Error("Function not implemented.")},noTimeout:void 0,isPrimaryRenderer:!1,getInstanceFromNode(e){throw new Error("Function not implemented.")},beforeActiveInstanceBlur(){throw new Error("Function not implemented.")},afterActiveInstanceBlur(){throw new Error("Function not implemented.")},prepareScopeUpdate:(e,t)=>{throw new Error("Function not implemented.")},getInstanceFromScope:e=>{throw new Error("Function not implemented.")},detachDeletedInstance:e=>{throw new Error("Function not implemented.")},getCurrentEventPriority:()=>Tx.DefaultEventPriority,getCurrentUpdatePriority:()=>Tx.DefaultEventPriority,resolveUpdatePriority:()=>Tx.DefaultEventPriority,setCurrentUpdatePriority:()=>{},maySuspendCommit:()=>!1,supportsHydration:!1},wx=(0,mY.default)(A2t),gY=e=>{let t={children:[],props:{name:"$root"},add(o){o.parent=this,this.children.push(o)},computePcbGlobalTransform(){return vi()}},n=[],i=wx.createContainer(t,0,null,!1,null,"tsci",o=>{console.log("Error in createContainer"),console.error(o),n.push(o)},null);if(wx.updateContainerSync(e,i,null,()=>{}),wx.flushSyncWork(),n.length>0)throw n[0];let r=wx.getPublicRootInstance(i);return r||t.children[0]},Rf=(e,t)=>{if(typeof e=="number")return e;if(e.startsWith("pin"))return Number(e.slice(3));if(!t)throw new Error(`No pin labels provided and pin number or label is not a number: "${e}"`);for(let n in t)if((Array.isArray(t[n])?t[n]:[t[n]]).includes(e))return Number(n.replace("pin",""));throw new Error(`No pin labels provided and pin number or label is not a number: "${e}"`)},N2t=(e,t)=>{if(!e)return;let n={},i={};for(let[r,o]of Object.entries(e)){let s=Rf(r,t);i[s]={...i[s],...o}}for(let[r,o]of Object.entries(i)){let s=`pin${r}`;n[s]={bottom_margin:o.bottomMargin,left_margin:o.leftMargin,right_margin:o.rightMargin,top_margin:o.topMargin}}return n},R2t=e=>{if(e){if("leftSide"in e||"rightSide"in e||"topSide"in e||"bottomSide"in e)return{left_side:e.leftSide,right_side:e.rightSide,top_side:e.topSide,bottom_side:e.bottomSide};if("leftPinCount"in e||"rightPinCount"in e||"topPinCount"in e||"bottomPinCount"in e)return{left_size:e.leftPinCount,right_size:e.rightPinCount,top_size:e.topPinCount,bottom_size:e.bottomPinCount};if("leftSize"in e||"rightSize"in e||"topSize"in e||"bottomSize"in e)return{left_size:e.leftSize,right_size:e.rightSize,top_size:e.topSize,bottom_size:e.bottomSize}}};function xY(e){let t=[];for(let n=0;n<e.length-1;n++)t.push([e[n],e[n+1]]);return t}var O2t=p.object({name:p.string().refine(e=>!/[+-]/.test(e),'Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P')}),aI=class extends Ie{constructor(){super(...arguments);T(this,"source_net_id")}get config(){return{componentName:"Net",zodProps:O2t}}getPortSelector(){return`net.${this.props.name}`}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=n.name.startsWith("GND"),r=n.name.startsWith("V"),o=t.source_net.insert({name:n.name,member_source_group_ids:[],is_ground:i,is_power:r,is_positive_voltage_source:r});this.source_net_id=o.source_net_id}doInitialSourceParentAttachment(){let t=this.getSubcircuit();if(!t)return;let{db:n}=this.root;n.source_net.update(this.source_net_id,{subcircuit_id:t.subcircuit_id})}getAllConnectedPorts(){let t=this.getSubcircuit().selectAll("port"),n=[];for(let i of t){let r=i._getDirectlyConnectedTraces();for(let o of r)if(o._isExplicitlyConnectedToNet(this)){n.push(i);break}}return n}_getAllDirectlyConnectedTraces(){let t=this.getSubcircuit().selectAll("trace"),n=[];for(let i of t)i._isExplicitlyConnectedToNet(this)&&n.push(i);return n}doInitialPcbRouteNetIslands(){if(this.root?.pcbDisabled||this.getSubcircuit()._parsedProps.routingDisabled||this.getSubcircuit()._getAutorouterConfig().groupMode!=="sequential-trace")return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getAllDirectlyConnectedTraces().filter(s=>(s._portsRoutedOnPcb?.length??0)>0),r=[];for(let s of i){let a=s._portsRoutedOnPcb,c=r.find(l=>a.some(u=>l.ports.includes(u)));if(!c){r.push({ports:[...a],traces:[s]});continue}c.traces.push(s),c.ports.push(...a)}if(r.length===0)return;let o=xY(r);for(let[s,a]of o){let c=s.ports.map(w=>w._getGlobalPcbPositionBeforeLayout()),l=a.ports.map(w=>w._getGlobalPcbPositionBeforeLayout()),u=1/0,h=[-1,-1];for(let w=0;w<c.length;w++){let S=c[w];for(let C=0;C<l.length;C++){let E=l[C],R=Math.sqrt((S.x-E.x)**2+(S.y-E.y)**2);R<u&&(u=R,h=[w,C])}}let f=s.ports[h[0]],_=a.ports[h[1]],y=t.toArray().filter(w=>w.type==="pcb_smtpad"||w.type==="pcb_trace"||w.type==="pcb_plated_hole"||w.type==="pcb_hole"||w.type==="source_port"||w.type==="pcb_port"),{solution:x}=rL(y.concat([{type:"source_trace",source_trace_id:"__net_trace_tmp",connected_source_port_ids:[f.source_port_id,_.source_port_id]}])),v=x[0];if(!v){this.renderError({pcb_trace_error_id:"",pcb_trace_id:"__net_trace_tmp",pcb_component_ids:[f.pcb_component_id,_.pcb_component_id].filter(Boolean),pcb_port_ids:[f.pcb_port_id,_.pcb_port_id].filter(Boolean),type:"pcb_trace_error",error_type:"pcb_trace_error",message:`Failed to route net islands for "${this.getString()}"`,source_trace_id:"__net_trace_tmp"});return}t.pcb_trace.insert(v)}}renderError(t){if(typeof t=="string")return super.renderError(t);this.root?.db.pcb_trace_error.insert(t)}},cI=(e,t)=>{for(let n of t)if(typeof n=="string"&&n.startsWith("net.")){if(/net\.[^\s>]*\./.test(n))throw new Error('Net names cannot contain a period, try using "sel.net..." to autocomplete with conventional net names, e.g. V3_3');if(/net\.[^\s>]*[+-]/.test(n))throw new Error('Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P');if(/net\.[0-9]/.test(n)){let r=n.split("net.")[1];throw new Error(`Net name "${r}" cannot start with a number, try using a prefix like "VBUS1"`)}let i=e.getSubcircuit();if(!i.selectOne(n)){let r=new aI({name:n.split("net.")[1]});i.add(r)}}},Ex=class extends Ie{constructor(){super(...arguments);T(this,"pcb_smtpad_id",null);T(this,"matchedPort",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SmtPad",zodProps:ML}}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 n=t.points,i=n.map(l=>l.x),r=n.map(l=>l.y),o=Math.min(...i),s=Math.max(...i),a=Math.min(...r),c=Math.max(...r);return{width:s-o,height:c-a}}if(t.shape==="pill")return{width:t.width,height:t.height};throw new Error(`getPcbSize for shape "${t.shape}" not implemented for ${this.componentName}`)}doInitialPortMatching(){let t=this.getPrimitiveContainer()?.selectAll("port");if(this.props.portHints){for(let n of t)if(n.isMatchingAnyOf(this.props.portHints)){this.matchedPort=n,n.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this;if(!n.portHints)return;let i=this.getSubcircuit(),r=this._getGlobalPcbPositionBeforeLayout(),a=(fo(this._computePcbGlobalTransformBeforeLayout()).rotation.angle*180/Math.PI%360+360)%360,c=.01,l=Math.abs(a)<c||Math.abs(a-180)<c||Math.abs(a-360)<c,u=Math.abs(a-90)<c||Math.abs(a-270)<c,h=Math.abs(a-360)<c?0:a,{maybeFlipLayer:f}=this._getPcbPrimitiveFlippedHelpers(),_=null,y=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id;n.shape==="circle"?(_=t.pcb_smtpad.insert({pcb_component_id:y,pcb_port_id:this.matchedPort?.pcb_port_id,layer:f(n.layer??"top"),shape:"circle",radius:n.radius,port_hints:n.portHints.map(x=>x.toString()),is_covered_with_solder_mask:n.coveredWithSolderMask??!1,x:r.x,y:r.y,subcircuit_id:i?.subcircuit_id??void 0}),t.pcb_solder_paste.insert({layer:_.layer,shape:"circle",radius:_.radius*.7,x:_.x,y:_.y,pcb_component_id:_.pcb_component_id,pcb_smtpad_id:_.pcb_smtpad_id,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})):n.shape==="rect"?(_=l||u?t.pcb_smtpad.insert({pcb_component_id:y,pcb_port_id:this.matchedPort?.pcb_port_id,layer:f(n.layer??"top"),shape:"rect",width:u?n.height:n.width,height:u?n.width:n.height,port_hints:n.portHints.map(x=>x.toString()),is_covered_with_solder_mask:n.coveredWithSolderMask??!1,x:r.x,y:r.y,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}):t.pcb_smtpad.insert({pcb_component_id:y,layer:f(n.layer??"top"),shape:"rotated_rect",width:n.width,height:n.height,x:r.x,y:r.y,ccw_rotation:h,port_hints:n.portHints.map(x=>x.toString()),is_covered_with_solder_mask:n.coveredWithSolderMask??!1,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),_.shape==="rect"&&t.pcb_solder_paste.insert({layer:f(n.layer??"top"),shape:"rect",width:_.width*.7,height:_.height*.7,x:_.x,y:_.y,pcb_component_id:_.pcb_component_id,pcb_smtpad_id:_.pcb_smtpad_id,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),_.shape==="rotated_rect"&&t.pcb_solder_paste.insert({layer:f(n.layer??"top"),shape:"rotated_rect",width:_.width*.7,height:_.height*.7,x:_.x,y:_.y,ccw_rotation:h,pcb_component_id:_.pcb_component_id,pcb_smtpad_id:_.pcb_smtpad_id,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})):n.shape==="polygon"?_=t.pcb_smtpad.insert({pcb_component_id:y,pcb_port_id:this.matchedPort?.pcb_port_id,layer:f(n.layer??"top"),shape:"polygon",points:n.points.map(x=>({x:x.x+r.x,y:x.y+r.y})),port_hints:n.portHints.map(x=>x.toString()),is_covered_with_solder_mask:n.coveredWithSolderMask??!1,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}):n.shape==="pill"&&(_=t.pcb_smtpad.insert({pcb_component_id:y,pcb_port_id:this.matchedPort?.pcb_port_id,layer:f(n.layer??"top"),shape:"pill",x:r.x,y:r.y,radius:n.radius,height:n.height,width:n.width,port_hints:n.portHints.map(x=>x.toString()),is_covered_with_solder_mask:n.coveredWithSolderMask??!1,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})),_&&(this.pcb_smtpad_id=_.pcb_smtpad_id)}doInitialPcbPortAttachment(){if(this.root?.pcbDisabled)return;let{db:t}=this.root;t.pcb_smtpad.update(this.pcb_smtpad_id,{pcb_port_id:this.matchedPort?.pcb_port_id})}_getPcbCircuitJsonBounds(){let{db:t}=this.root,n=t.pcb_smtpad.get(this.pcb_smtpad_id);if(n.shape==="rect")return{center:{x:n.x,y:n.y},bounds:{left:n.x-n.width/2,top:n.y+n.height/2,right:n.x+n.width/2,bottom:n.y-n.height/2},width:n.width,height:n.height};if(n.shape==="rotated_rect"){let i=n.ccw_rotation*Math.PI/180,r=Math.cos(i),o=Math.sin(i),s=n.width/2,a=n.height/2,c=Math.abs(s*r)+Math.abs(a*o),l=Math.abs(s*o)+Math.abs(a*r);return{center:{x:n.x,y:n.y},bounds:{left:n.x-c,right:n.x+c,top:n.y-l,bottom:n.y+l},width:c*2,height:l*2}}if(n.shape==="circle")return{center:{x:n.x,y:n.y},bounds:{left:n.x-n.radius,top:n.y-n.radius,right:n.x+n.radius,bottom:n.y+n.radius},width:n.radius*2,height:n.radius*2};if(n.shape==="polygon"){let i=n.points,r=i.map(u=>u.x),o=i.map(u=>u.y),s=Math.min(...r),a=Math.max(...r),c=Math.min(...o),l=Math.max(...o);return{center:{x:(s+a)/2,y:(c+l)/2},bounds:{left:s,top:l,right:a,bottom:c},width:a-s,height:l-c}}if(n.shape==="pill"){let i=n.width/2,r=n.height/2;return{center:{x:n.x,y:n.y},bounds:{left:n.x-i,top:n.y-r,right:n.x+i,bottom:n.y+r},width:n.width,height:n.height}}throw new Error(`circuitJson bounds calculation not implemented for shape "${n.shape}"`)}_setPositionFromLayout(t){let{db:n}=this.root;n.pcb_smtpad.update(this.pcb_smtpad_id,{x:t.x,y:t.y});let i=n.pcb_solder_paste.list().find(r=>r.pcb_smtpad_id===this.pcb_smtpad_id);n.pcb_solder_paste.update(i?.pcb_solder_paste_id,{x:t.x,y:t.y}),this.matchedPort?._setPositionFromLayout(t)}},lI=class extends Ie{constructor(){super(...arguments);T(this,"pcb_silkscreen_path_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenPath",zodProps:uF}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(n.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenPath. Must be "top" or "bottom".`);let o=this._computePcbGlobalTransformBeforeLayout(),s=this.getSubcircuit(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,c=t.pcb_silkscreen_path.insert({pcb_component_id:a,layer:r,route:n.route.map(l=>{let u=kn(o,{x:l.x,y:l.y});return{...l,x:u.x,y:u.y}}),stroke_width:n.strokeWidth??.1,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_path_id=c.pcb_silkscreen_path_id}_setPositionFromLayout(t){let{db:n}=this.root,{_parsedProps:i}=this,r=n.pcb_silkscreen_path.get(this.pcb_silkscreen_path_id);if(!r)return;let o=0,s=0;for(let u of r.route)o+=u.x,s+=u.y;o/=r.route.length,s/=r.route.length;let a=t.x-o,c=t.y-s,l=r.route.map(u=>({...u,x:u.x+a,y:u.y+c}));n.pcb_silkscreen_path.update(this.pcb_silkscreen_path_id,{route:l})}getPcbSize(){let{_parsedProps:t}=this;if(!t.route||t.route.length===0)return{width:0,height:0};let n=1/0,i=-1/0,r=1/0,o=-1/0;for(let s of t.route)n=Math.min(n,s.x),i=Math.max(i,s.x),r=Math.min(r,s.y),o=Math.max(o,s.y);return{width:i-n,height:o-r}}},L2t=p.object({route:p.array(E1),source_trace_id:p.string().optional()}),uI=class extends Ie{constructor(){super(...arguments);T(this,"pcb_trace_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbTrace",zodProps:L2t}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getPrimitiveContainer(),r=this.getSubcircuit(),{maybeFlipLayer:o}=this._getPcbPrimitiveFlippedHelpers(),s=this._computePcbGlobalTransformBeforeLayout(),a=n.route.map(l=>{let{x:u,y:h,...f}=l,_=kn(s,{x:u,y:h});return l.route_type==="wire"&&l.layer?{..._,...f,layer:o(l.layer)}:{..._,...f}}),c=t.pcb_trace.insert({pcb_component_id:i.pcb_component_id,source_trace_id:n.source_trace_id,route:a,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_trace_id=c.pcb_trace_id}getPcbSize(){let{_parsedProps:t}=this;if(!t.route||t.route.length===0)return{width:0,height:0};let n=1/0,i=-1/0,r=1/0,o=-1/0;for(let s of t.route)n=Math.min(n,s.x),i=Math.max(i,s.x),r=Math.min(r,s.y),o=Math.max(o,s.y),s.route_type==="wire"&&(n=Math.min(n,s.x-s.width/2),i=Math.max(i,s.x+s.width/2),r=Math.min(r,s.y-s.width/2),o=Math.max(o,s.y+s.width/2));return n===1/0||i===-1/0||r===1/0||o===-1/0?{width:0,height:0}:{width:i-n,height:o-r}}},Jp=class extends Ie{constructor(){super(...arguments);T(this,"pcb_plated_hole_id",null);T(this,"matchedPort",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PlatedHole",zodProps:yL}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){let{_parsedProps:t}=this;if(t.shape==="circle")return{width:t.outerDiameter,height:t.outerDiameter};if(t.shape==="oval"||t.shape==="pill")return{width:t.outerWidth,height:t.outerHeight};if(t.shape==="circular_hole_with_rect_pad")return{width:t.rectPadWidth,height:t.rectPadHeight};if(t.shape==="pill_hole_with_rect_pad")return{width:t.rectPadWidth,height:t.rectPadHeight};throw new Error(`getPcbSize for shape "${t.shape}" not implemented for ${this.componentName}`)}_getPcbCircuitJsonBounds(){let{db:t}=this.root,n=t.pcb_plated_hole.get(this.pcb_plated_hole_id),i=this.getPcbSize();return{center:{x:n.x,y:n.y},bounds:{left:n.x-i.width/2,top:n.y+i.height/2,right:n.x+i.width/2,bottom:n.y-i.height/2},width:i.width,height:i.height}}_setPositionFromLayout(t){let{db:n}=this.root;n.pcb_plated_hole.update(this.pcb_plated_hole_id,{x:t.x,y:t.y}),this.matchedPort?._setPositionFromLayout(t)}doInitialPortMatching(){let t=this.getPrimitiveContainer()?.selectAll("port");if(this.props.portHints){for(let n of t)if(n.isMatchingAnyOf(this.props.portHints)){this.matchedPort=n,n.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalPcbPositionBeforeLayout(),r=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,o=this.getSubcircuit();if(n.shape==="circle"){let s=t.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,outer_diameter:n.outerDiameter,hole_diameter:n.holeDiameter,shape:"circle",port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=s.pcb_plated_hole_id,t.pcb_solder_paste.insert({layer:"top",shape:"circle",radius:n.outerDiameter/2,x:i.x,y:i.y,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),t.pcb_solder_paste.insert({layer:"bottom",shape:"circle",radius:n.outerDiameter/2,x:i.x,y:i.y,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(n.shape==="pill"&&n.rectPad){let s=t.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,outer_width:n.outerWidth,outer_height:n.outerHeight,hole_width:n.holeWidth,hole_height:n.holeHeight,shape:"rotated_pill_hole_with_rect_pad",type:"pcb_plated_hole",port_hints:this.getNameAndAliases(),pcb_plated_hole_id:this.pcb_plated_hole_id,x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,hole_shape:"rotated_pill",pad_shape:"rect",hole_ccw_rotation:n.pcbRotation??0,rect_ccw_rotation:n.pcbRotation??0,rect_pad_width:n.outerWidth,rect_pad_height:n.outerHeight,hole_offset_x:n.holeOffsetX,hole_offset_y:n.holeOffsetY});this.pcb_plated_hole_id=s.pcb_plated_hole_id}else if(n.shape==="pill"||n.shape==="oval"){let s=t.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,outer_width:n.outerWidth,outer_height:n.outerHeight,hole_width:n.holeWidth,hole_height:n.holeHeight,shape:n.shape,port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,ccw_rotation:n.pcbRotation??0});this.pcb_plated_hole_id=s.pcb_plated_hole_id,t.pcb_solder_paste.insert({layer:"top",shape:n.shape,width:n.outerWidth,height:n.outerHeight,x:i.x,y:i.y,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),t.pcb_solder_paste.insert({layer:"bottom",shape:n.shape,width:n.outerWidth,height:n.outerHeight,x:i.x,y:i.y,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(n.shape==="circular_hole_with_rect_pad"){let s=t.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,hole_diameter:n.holeDiameter,rect_pad_width:n.rectPadWidth,rect_pad_height:n.rectPadHeight,shape:"circular_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,hole_offset_x:n.holeOffsetX,hole_offset_y:n.holeOffsetY,rect_border_radius:n.rectBorderRadius??0});this.pcb_plated_hole_id=s.pcb_plated_hole_id}else if(n.shape==="pill_hole_with_rect_pad"){let s=t.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,hole_width:n.holeWidth,hole_height:n.holeHeight,rect_pad_width:n.rectPadWidth,rect_pad_height:n.rectPadHeight,hole_offset_x:n.holeOffsetX,hole_offset_y:n.holeOffsetY,shape:"pill_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=s.pcb_plated_hole_id}}doInitialPcbPortAttachment(){if(this.root?.pcbDisabled)return;let{db:t}=this.root;t.pcb_plated_hole.update(this.pcb_plated_hole_id,{pcb_port_id:this.matchedPort?.pcb_port_id})}},Cx=class extends Ie{constructor(){super(...arguments);T(this,"pcb_keepout_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Keepout",zodProps:WL}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let t=this.getSubcircuit(),{db:n}=this.root,{_parsedProps:i}=this,r=this._getGlobalPcbPositionBeforeLayout(),o=fo(this._computePcbGlobalTransformBeforeLayout()),s=Math.abs(o.rotation.angle*(180/Math.PI)-90)%180<.01,a=null;i.shape==="circle"?a=n.pcb_keepout.insert({layers:["top"],shape:"circle",radius:i.radius,center:{x:r.x,y:r.y},subcircuit_id:t?.subcircuit_id??void 0,pcb_group_id:t?.getGroup()?.pcb_group_id??void 0}):i.shape==="rect"&&(a=n.pcb_keepout.insert({layers:["top"],shape:"rect",...s?{width:i.height,height:i.width}:{width:i.width,height:i.height},center:{x:r.x,y:r.y},subcircuit_id:t?.subcircuit_id??void 0,pcb_group_id:t?.getGroup()?.pcb_group_id??void 0})),a&&(this.pcb_keepout_id=a.pcb_keepout_id)}},pI=class extends Ie{constructor(){super(...arguments);T(this,"pcb_hole_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Hole",zodProps:EL}}getPcbSize(){let{_parsedProps:t}=this,n=t.shape==="pill";return{width:n?t.width:t.diameter,height:n?t.height:t.diameter}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit(),r=this._getGlobalPcbPositionBeforeLayout(),o=t.pcb_hole.insert({hole_shape:"circle",hole_diameter:n.diameter,x:r.x,y:r.y,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:i?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=o.pcb_hole_id}_getPcbCircuitJsonBounds(){let{db:t}=this.root,n=t.pcb_hole.get(this.pcb_hole_id),i=this.getPcbSize();return{center:{x:n.x,y:n.y},bounds:{left:n.x-i.width/2,top:n.y-i.height/2,right:n.x+i.width/2,bottom:n.y+i.height/2},width:i.width,height:i.height}}_setPositionFromLayout(t){let{db:n}=this.root;n.pcb_hole.update(this.pcb_hole_id,{x:t.x,y:t.y})}},Rx=class extends Ie{constructor(){super(...arguments);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenText",zodProps:lF}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getPrimitiveContainer(),r=this._getGlobalPcbPositionBeforeLayout(),{maybeFlipLayer:o,isFlipped:s}=this._getPcbPrimitiveFlippedHelpers(),a=this.getSubcircuit(),c=0;if(n.pcbRotation!==void 0&&n.pcbRotation!==0)c=n.pcbRotation;else{let h=this._computePcbGlobalTransformBeforeLayout();c=fo(h).rotation.angle*180/Math.PI}s&&(c=(c+180)%360);let l=new Set(n.layers);n.layer&&l.add(n.layer);let u=l.size>0?Array.from(l):["top"];for(let h of u)t.pcb_silkscreen_text.insert({anchor_alignment:n.anchorAlignment,anchor_position:{x:r.x,y:r.y},font:n.font??"tscircuit2024",font_size:n.fontSize??1,layer:o(h),text:n.text??"",ccw_rotation:c,pcb_component_id:i.pcb_component_id,subcircuit_id:a?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}getPcbSize(){let{_parsedProps:t}=this,n=t.fontSize??1,r=(t.text??"").length*n,o=n;return{width:r*n,height:o*n}}},Nf=class extends Ie{constructor(){super(...arguments);T(this,"pcb_cutout_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Cutout",zodProps:IL}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit(),r=this.getGroup()?.pcb_group_id??void 0,o=this._getGlobalPcbPositionBeforeLayout(),a=this.getPrimitiveContainer()?._parsedProps.pcbRotation??0,c;if(n.shape==="rect"){let l=typeof a=="string"?parseInt(a.replace("deg",""),10):a,u=Math.abs(l%180)===90,h={shape:"rect",center:o,width:u?n.height:n.width,height:u?n.width:n.height,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:r};c=t.pcb_cutout.insert(h)}else if(n.shape==="circle"){let l={shape:"circle",center:o,radius:n.radius,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:r};c=t.pcb_cutout.insert(l)}else if(n.shape==="polygon"){let l=this._computePcbGlobalTransformBeforeLayout(),h={shape:"polygon",points:n.points.map(f=>kn(l,f)),subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:r};c=t.pcb_cutout.insert(h)}c&&(this.pcb_cutout_id=c.pcb_cutout_id)}getPcbSize(){let{_parsedProps:t}=this;if(t.shape==="rect")return{width:t.width,height:t.height};if(t.shape==="circle")return{width:t.radius*2,height:t.radius*2};if(t.shape==="polygon"){if(t.points.length===0)return{width:0,height:0};let n=1/0,i=-1/0,r=1/0,o=-1/0;for(let s of t.points)n=Math.min(n,s.x),i=Math.max(i,s.x),r=Math.min(r,s.y),o=Math.max(o,s.y);return{width:i-n,height:o-r}}return{width:0,height:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_cutout_id)return super._getPcbCircuitJsonBounds();let{db:t}=this.root,n=t.pcb_cutout.get(this.pcb_cutout_id);if(!n)return super._getPcbCircuitJsonBounds();if(n.shape==="rect")return{center:n.center,bounds:{left:n.center.x-n.width/2,top:n.center.y+n.height/2,right:n.center.x+n.width/2,bottom:n.center.y-n.height/2},width:n.width,height:n.height};if(n.shape==="circle")return{center:n.center,bounds:{left:n.center.x-n.radius,top:n.center.y+n.radius,right:n.center.x+n.radius,bottom:n.center.y-n.radius},width:n.radius*2,height:n.radius*2};if(n.shape==="polygon"){if(n.points.length===0)return super._getPcbCircuitJsonBounds();let i=1/0,r=-1/0,o=1/0,s=-1/0;for(let a of n.points)i=Math.min(i,a.x),r=Math.max(r,a.x),o=Math.min(o,a.y),s=Math.max(s,a.y);return{center:{x:(i+r)/2,y:(o+s)/2},bounds:{left:i,top:s,right:r,bottom:o},width:r-i,height:s-o}}return super._getPcbCircuitJsonBounds()}_setPositionFromLayout(t){if(!this.pcb_cutout_id)return;let{db:n}=this.root,i=n.pcb_cutout.get(this.pcb_cutout_id);if(i){if(i.shape==="rect"||i.shape==="circle")n.pcb_cutout.update(this.pcb_cutout_id,{...i,center:t});else if(i.shape==="polygon"){let r=this._getPcbCircuitJsonBounds().center,o=t.x-r.x,s=t.y-r.y,a=i.points.map(c=>({x:c.x+o,y:c.y+s}));n.pcb_cutout.update(this.pcb_cutout_id,{...i,points:a})}}}},F2t=({elm:e,pinLabels:t,layer:n,readableRotation:i,anchorAlignment:r})=>{let o=e.text.replace(/[{}]/g,"").toLowerCase(),s=o;if(Array.isArray(t)){let a=parseInt(o.replace(/[^\d]/g,""),10)-1;s=String(t[a]??o)}else typeof t=="object"&&(s=String(t[o]??o));return new Rx({anchorAlignment:r||"center",text:s??o,layer:n||"top",fontSize:e.font_size+.2,pcbX:isNaN(e.anchor_position.x)?0:e.anchor_position.x,pcbY:e.anchor_position.y,pcbRotation:i??0})},z2t=(e,t)=>{let n=parseInt(e||"0",10),i;return t!=null?i=t-n:i=n,(i%360+360)%360},Ef=({componentName:e,componentRotation:t,footprint:n,pinLabels:i,pcbPinLabels:r},o)=>{let s=[];for(let a of o)if(a.type==="pcb_smtpad"&&a.shape==="rect")s.push(new Ex({pcbX:a.x,pcbY:a.y,layer:a.layer,shape:"rect",height:a.height,width:a.width,portHints:a.port_hints,rectBorderRadius:a.rect_border_radius}));else if(a.type==="pcb_smtpad"&&a.shape==="circle")s.push(new Ex({pcbX:a.x,pcbY:a.y,layer:a.layer,shape:"circle",radius:a.radius,portHints:a.port_hints}));else if(a.type==="pcb_silkscreen_path")s.push(new lI({layer:a.layer,route:a.route,strokeWidth:a.stroke_width}));else if(a.type==="pcb_plated_hole")a.shape==="circle"?s.push(new Jp({pcbX:a.x,pcbY:a.y,shape:"circle",holeDiameter:a.hole_diameter,outerDiameter:a.outer_diameter,portHints:a.port_hints})):a.shape==="circular_hole_with_rect_pad"?s.push(new Jp({pcbX:a.x,pcbY:a.y,shape:"circular_hole_with_rect_pad",holeDiameter:a.hole_diameter,rectPadHeight:a.rect_pad_height,rectPadWidth:a.rect_pad_width,portHints:a.port_hints,rectBorderRadius:a.rect_border_radius,holeOffsetX:a.hole_offset_x,holeOffsetY:a.hole_offset_y})):a.shape==="pill"||a.shape==="oval"?s.push(new Jp({pcbX:a.x,pcbY:a.y,shape:a.shape,holeWidth:a.hole_width,holeHeight:a.hole_height,outerWidth:a.outer_width,outerHeight:a.outer_height,portHints:a.port_hints})):a.shape==="pill_hole_with_rect_pad"&&s.push(new Jp({pcbX:a.x,pcbY:a.y,shape:"pill_hole_with_rect_pad",holeShape:"pill",padShape:"rect",holeWidth:a.hole_width,holeHeight:a.hole_height,rectPadWidth:a.rect_pad_width,rectPadHeight:a.rect_pad_height,portHints:a.port_hints,holeOffsetX:a.hole_offset_x,holeOffsetY:a.hole_offset_y}));else if(a.type==="pcb_keepout"&&a.shape==="circle")s.push(new Cx({pcbX:a.center.x,pcbY:a.center.y,shape:"circle",radius:a.radius}));else if(a.type==="pcb_keepout"&&a.shape==="rect")s.push(new Cx({pcbX:a.center.x,pcbY:a.center.y,shape:"rect",width:a.width,height:a.height}));else if(a.type==="pcb_hole"&&a.hole_shape==="circle")s.push(new pI({pcbX:a.x,pcbY:a.y,diameter:a.hole_diameter}));else if(a.type==="pcb_cutout")a.shape==="rect"?s.push(new Nf({pcbX:a.center.x,pcbY:a.center.y,shape:"rect",width:a.width,height:a.height})):a.shape==="circle"?s.push(new Nf({pcbX:a.center.x,pcbY:a.center.y,shape:"circle",radius:a.radius})):a.shape==="polygon"&&s.push(new Nf({shape:"polygon",points:a.points}));else if(a.type==="pcb_silkscreen_text"){let c=z2t(t,a.ccw_rotation);n.includes("pinrow")&&a.text.includes("PIN")?s.push(F2t({elm:a,pinLabels:r??i,layer:a.layer,readableRotation:c,anchorAlignment:a.anchor_alignment})):s.push(new Rx({anchorAlignment:a.anchor_alignment||"center",text:e,fontSize:a.font_size+.2,pcbX:Number.isNaN(a.anchor_position.x)?0:a.anchor_position.x,pcbY:a.anchor_position.y,pcbRotation:c??0}))}else a.type==="pcb_trace"&&s.push(new uI({route:a.route}));return s};function Ox(e){let t=1/0,n=1/0,i=-1/0,r=-1/0,o=!1;for(let c of e)if(c.isPcbPrimitive&&!c.componentName.startsWith("Silkscreen")){let{x:l,y:u}=c._getGlobalPcbPositionBeforeLayout(),{width:h,height:f}=c.getPcbSize();t=Math.min(t,l-h/2),n=Math.min(n,u-f/2),i=Math.max(i,l+h/2),r=Math.max(r,u+f/2),o=!0}else if(c.children.length>0){let l=Ox(c.children);(l.width>0||l.height>0)&&(t=Math.min(t,l.minX),n=Math.min(n,l.minY),i=Math.max(i,l.maxX),r=Math.max(r,l.maxY),o=!0)}if(!o)return{minX:0,minY:0,maxX:0,maxY:0,width:0,height:0};let s=i-t,a=r-n;return s<0&&(s=0),a<0&&(a=0),{minX:t,minY:n,maxX:i,maxY:r,width:s,height:a}}function Hj(e){let t=e%360;return t<0?t+360:t}function D2t(e,t,n,i){return i==="counterclockwise"?n>=t?e>=t&&e<=n:e>=t||e<=n:n<=t?e<=t&&e>=n:e<=t||e>=n}function $2t(e){let t=e.center,n=e.radius,i=e.start_angle_degrees,r=e.end_angle_degrees,o=e.direction??"counterclockwise";if(!t||typeof t.x!="number"||typeof t.y!="number"||typeof n!="number"||typeof i!="number"||typeof r!="number")return null;let s=Hj(i),a=Hj(r),c=new Set([s,a]),l=[0,90,180,270];for(let y of l)D2t(y,s,a,o)&&c.add(y);let u=1/0,h=1/0,f=-1/0,_=-1/0;for(let y of c){let x=y*Math.PI/180,v=t.x+n*Math.cos(x),w=t.y+n*Math.sin(x);u=Math.min(u,v),f=Math.max(f,v),h=Math.min(h,w),_=Math.max(_,w)}return!Number.isFinite(u)||!Number.isFinite(h)?null:{minX:u,maxX:f,minY:h,maxY:_}}function bY(e){let t=1/0,n=1/0,i=-1/0,r=-1/0;for(let o of e){let s,a,c,l;if(o.type==="schematic_component")s=o.center?.x,a=o.center?.y,c=o.size?.width,l=o.size?.height;else if(o.type==="schematic_box")s=o.x,a=o.y,c=o.width,l=o.height;else if(o.type==="schematic_port")s=o.center?.x,a=o.center?.y,c=.2,l=.2;else if(o.type==="schematic_text")s=o.position?.x,a=o.position?.y,c=(o.text?.length??0)*.1,l=.2;else if(o.type==="schematic_line"){let u=o.x1??0,h=o.y1??0,f=o.x2??0,_=o.y2??0;s=(u+f)/2,a=(h+_)/2,c=Math.abs(f-u),l=Math.abs(_-h)}else if(o.type==="schematic_rect")s=o.center?.x,a=o.center?.y,c=o.width,l=o.height;else if(o.type==="schematic_circle"){s=o.center?.x,a=o.center?.y;let u=o.radius;typeof u=="number"&&(c=u*2,l=u*2)}else if(o.type==="schematic_arc"){let u=$2t(o);u&&(t=Math.min(t,u.minX),i=Math.max(i,u.maxX),n=Math.min(n,u.minY),r=Math.max(r,u.maxY));continue}typeof s=="number"&&typeof a=="number"&&typeof c=="number"&&typeof l=="number"&&(t=Math.min(t,s-c/2),i=Math.max(i,s+c/2),n=Math.min(n,a-l/2),r=Math.max(r,a+l/2))}return{minX:t,maxX:i,minY:n,maxY:r}}function B2t(e,t){let n=t.x-e.x,i=t.y-e.y;return Math.abs(n)>Math.abs(i)?n>=0?"right":"left":i>=0?"up":"down"}var Gj=e=>{if(e.length<=1)return!0;let t=e.map(o=>{let s=o._getPcbCircuitJsonBounds();return{left:s.bounds.left,right:s.bounds.right,top:s.bounds.top,bottom:s.bounds.bottom}}),n=Array(t.length).fill(!1).map(()=>Array(t.length).fill(!1));for(let o=0;o<t.length;o++)for(let s=o+1;s<t.length;s++){let a=t[o],c=t[s];n[o][s]=n[s][o]=!(a.right<c.left||a.left>c.right||a.bottom>c.top||a.top<c.bottom)}let i=new Set,r=o=>{i.add(o);for(let s=0;s<t.length;s++)n[o][s]&&!i.has(s)&&r(s)};return r(0),i.size===t.length},Uj=e=>{if(e.length===0)throw new Error("Cannot get center of empty PCB primitives array");let t=e.map(r=>r._getPcbCircuitJsonBounds().center).filter(Boolean),n=t.reduce((r,o)=>r+o.x,0),i=t.reduce((r,o)=>r+o.y,0);return{x:n/t.length,y:i/t.length}},j2t=p.object({name:p.string().optional(),pinNumber:p.number().optional(),aliases:p.array(p.string()).optional(),layer:p.string().optional(),layers:p.array(p.string()).optional()}),Ei=class extends Ie{constructor(t,n={}){if(!t.name&&t.pinNumber!==void 0&&(t.name=`pin${t.pinNumber}`),!t.name)throw new Error("Port must have a name or a pinNumber");super(t);T(this,"source_port_id",null);T(this,"pcb_port_id",null);T(this,"schematic_port_id",null);T(this,"schematicSymbolPortDef",null);T(this,"matchedComponents");T(this,"facingDirection",null);T(this,"originDescription",null);n.originDescription&&(this.originDescription=n.originDescription),this.matchedComponents=[]}get config(){return{componentName:"Port",zodProps:j2t}}_isBoardPinoutFromAttributes(){let t=this.parent;if(t?._parsedProps?.pinAttributes){let n=t._parsedProps.pinAttributes;for(let i of this.getNameAndAliases())if(n[i]?.includeInBoardPinout)return!0}}_getGlobalPcbPositionBeforeLayout(){let t=this.matchedComponents.find(i=>i.isPcbPrimitive),n=this.parent;if(n&&!n.props.footprint)throw new Error(`${n.componentName} "${n.props.name}" does not have a footprint. Add a footprint prop, e.g. <${n.componentName.toLowerCase()} footprint="..." />`);if(!t)throw new Error(`Port ${this} has no matching PCB primitives. This often means the footprint's pads lack matching port hints.`);return t?._getGlobalPcbPositionBeforeLayout()??{x:0,y:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_port_id)return super._getPcbCircuitJsonBounds();let{db:t}=this.root,n=t.pcb_port.get(this.pcb_port_id);return{center:{x:n.x,y:n.y},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getGlobalPcbPositionAfterLayout(){return this._getPcbCircuitJsonBounds().center}_getPortsInternallyConnectedToThisPort(){let t=this.parent;if(!t||!t._getInternallyConnectedPins)return[];let n=t._getInternallyConnectedPins();for(let i of n)if(i.some(r=>r===this))return i;return[]}_hasSchematicPort(){if(this.parent?.getSchematicSymbol())return!!(this.schematicSymbolPortDef||this._getPortsInternallyConnectedToThisPort().some(r=>r.schematicSymbolPortDef));let n=this?.parent?._getSchematicBoxDimensions();return!!(n&&this.props.pinNumber!==void 0&&n.getPortPositionByPinNumber(this.props.pinNumber))}_getGlobalSchematicPositionBeforeLayout(){let t=this.parent?.getSchematicSymbol();if(t){let i=this.schematicSymbolPortDef;if(!i&&(i=this._getPortsInternallyConnectedToThisPort().find(o=>o.schematicSymbolPortDef)?.schematicSymbolPortDef??null,!i))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 r=Gn(this.parent.computeSchematicGlobalTransform(),fn(-t.center.x,-t.center.y));return kn(r,i)}let n=this?.parent?._getSchematicBoxDimensions();if(n&&this.props.pinNumber!==void 0){let i=n.getPortPositionByPinNumber(this.props.pinNumber);if(!i)throw new Error(`Couldn't find position for schematic_port for port ${this.getString()} inside of the schematic box`);return kn(this.parent.computeSchematicGlobalTransform(),i)}throw new Error(`Couldn't find position for schematic_port for port ${this.getString()}`)}_getGlobalSchematicPositionAfterLayout(){let{db:t}=this.root;if(!this.schematic_port_id)throw new Error(`Can't get schematic port position after layout for "${this.getString()}", no schematic_port_id`);let n=t.schematic_port.get(this.schematic_port_id);if(!n)throw new Error(`Schematic port not found when trying to get post-layout position: ${this.schematic_port_id}`);return n.center}registerMatch(t){this.matchedComponents.push(t)}getNameAndAliases(){let{_parsedProps:t}=this;return Array.from(new Set([...t.name?[t.name]:[],...t.aliases??[],...typeof t.pinNumber=="number"?[`pin${t.pinNumber}`,t.pinNumber.toString()]:[],...this.externallyAddedAliases??[]]))}_getMatchingPinAttributes(){let t=this.parent?._parsedProps?.pinAttributes;if(!t)return[];let n=[];for(let i of this.getNameAndAliases()){let r=t[i];r&&n.push(r)}return n}_shouldIncludeInBoardPinout(){return this._getMatchingPinAttributes().some(t=>t.includeInBoardPinout===!0)}isMatchingPort(t){return this.isMatchingAnyOf(t.getNameAndAliases())}getPortSelector(){return`.${this.parent?.props.name} > port.${this.props.name}`}getAvailablePcbLayers(){let{layer:t,layers:n}=this._parsedProps;return n||(t?[t]:Array.from(new Set(this.matchedComponents.flatMap(i=>i.getAvailablePcbLayers()))))}_getDirectlyConnectedTraces(){return this.getSubcircuit().selectAll("trace").filter(i=>!i._couldNotFindPort).filter(i=>i._isExplicitlyConnectedToPort(this))}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=this.getNameAndAliases(),r=t.source_port.insert({name:n.name,pin_number:n.pinNumber,port_hints:i,source_component_id:this.parent?.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id});this.source_port_id=r.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:n}=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 i=n.filter(o=>o.isPcbPrimitive);if(i.length===0)return;let r=null;if(i.length===1&&(r=i[0]._getPcbCircuitJsonBounds().center),i.length>1){if(!Gj(i))throw new Error(`${this.getString()} has multiple non-overlapping pcb matches, unclear how to place pcb_port: ${i.map(o=>o.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)`);r=Uj(i)}if(r){let o=this.getSubcircuit(),s=this._shouldIncludeInBoardPinout(),a=t.pcb_port.insert({pcb_component_id:this.parent?.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...s?{is_board_pinout:!0}:{},...r,source_port_id:this.source_port_id,is_board_pinout:this._isBoardPinoutFromAttributes()});this.pcb_port_id=a.pcb_port_id}else{let o=i[0];throw new Error(`${o.getString()} does not have a center or _getGlobalPcbPositionBeforeLayout method (needed for pcb_port placement)`)}}updatePcbPortRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root;if(this.pcb_port_id)return;let n=this.matchedComponents.filter(a=>a.isPcbPrimitive);if(n.length===0)return;let i=null;if(n.length===1&&(i=n[0]._getPcbCircuitJsonBounds().center),n.length>1)try{Gj(n)&&(i=Uj(n))}catch{}if(!i)return;let r=this.getSubcircuit(),o=this._shouldIncludeInBoardPinout(),s=t.pcb_port.insert({pcb_component_id:this.parent?.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...o?{is_board_pinout:!0}:{},...i,source_port_id:this.source_port_id,is_board_pinout:this._isBoardPinoutFromAttributes()});this.pcb_port_id=s.pcb_port_id}doInitialSchematicPortRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=this.getPrimitiveContainer();if(!i||!this._hasSchematicPort())return;let r=i._getGlobalSchematicPositionBeforeLayout(),o=this._getGlobalSchematicPositionBeforeLayout(),s=null,a=i._getSchematicBoxDimensions();a&&n.pinNumber!==void 0&&(s=a.getPortPositionByPinNumber(n.pinNumber)),this.getSubcircuit().props._schDebugObjectsEnabled&&t.schematic_debug_object.insert({shape:"rect",center:o,size:{width:.1,height:.1},label:"obstacle"}),s?.side?this.facingDirection={left:"left",right:"right",top:"up",bottom:"down"}[s.side]:this.facingDirection=B2t(r,o);let c=t.source_port.get(this.source_port_id),l=[];for(let y of c?.port_hints??[])y.match(/^(pin)?\d+$/)||y.match(/^(left|right)/)&&!c?.name.match(/^(left|right)/)||l.push(y);let u;this.parent?.props?.showPinAliases&&l.length>0?u=l.join("/"):l.length>0&&(u=l[0]);let f={type:"schematic_port",schematic_component_id:this.parent?.schematic_component_id,center:o,source_port_id:this.source_port_id,facing_direction:this.facingDirection,distance_from_component_edge:.4,side_of_component:s?.side,pin_number:n.pinNumber,true_ccw_index:s?.trueIndex,display_pin_label:u,is_connected:!1};for(let y of this._getMatchingPinAttributes())y.requiresPower&&(f.has_input_arrow=!0),y.providesPower&&(f.has_output_arrow=!0);let _=t.schematic_port.insert(f);this.schematic_port_id=_.schematic_port_id}_getSubcircuitConnectivityKey(){return this.root?.db.source_port.get(this.source_port_id)?.subcircuit_connectivity_map_key}_setPositionFromLayout(t){let{db:n}=this.root;this.pcb_port_id&&n.pcb_port.update(this.pcb_port_id,{x:t.x,y:t.y})}_hasMatchedPcbPrimitive(){return this.matchedComponents.some(t=>t.isPcbPrimitive)}_getNetLabelText(){return`${this.parent?.props.name}_${this.props.name}`}},vY=e=>{let t=e.find(n=>/^(pin)?\d+$/.test(n));return t?Number.parseInt(t.replace(/^pin/,"")):null};function Mf(e,t){let n=vY(e);if(!n)return null;let r=[...e.filter(o=>o.toString()!==n.toString()&&o!==`pin${n}`),...t?.additionalAliases?.[`pin${n}`]??[]];return new Ei({pinNumber:n,aliases:r})}var Y2t=e=>{for(let t of["leftSide","rightSide","topSide","bottomSide"])if(t in e&&typeof e[t]=="number")throw new Error(`A number was specified for "${t}", you probably meant to use "size" not "side"`);return"leftSide"in e||"rightSide"in e||"topSide"in e||"bottomSide"in e},X2t=e=>{if(Y2t(e))return{leftSize:e.leftSide?.pins.length??0,rightSize:e.rightSide?.pins.length??0,topSize:e.topSide?.pins.length??0,bottomSize:e.bottomSide?.pins.length??0};let{leftSize:t=0,rightSize:n=0,topSize:i=0,bottomSize:r=0}=e;return{leftSize:t,rightSize:n,topSize:i,bottomSize:r}};function wY(e){let t=e;return t.leftSide!==void 0||t.rightSide!==void 0||t.topSide!==void 0||t.bottomSide!==void 0}var V2t=e=>{let t=e.portDistanceFromEdge??.4,n=e.schPortArrangement?X2t(e.schPortArrangement):null,i={left:0,right:0,top:0,bottom:0},r=e.pinCount??null;if(r===null)if(n)r=n.leftSize+n.rightSize+n.topSize;else throw new Error("Could not determine pin count for the schematic box");if(r&&!n){let y=Math.floor(r/2);n={leftSize:r-y,rightSize:y,topSize:0,bottomSize:0}}n||(n={leftSize:0,rightSize:0,topSize:0,bottomSize:0});let o=({side:y,sideIndex:x,truePinIndex:v})=>{if(!e.schPortArrangement||!wY(e.schPortArrangement))return v+1;let w={left:"top-to-bottom",bottom:"left-to-right",right:"bottom-to-top",top:"right-to-left"}[y],S=e.schPortArrangement?.[`${y}Side`]?.direction??w,C=e.schPortArrangement?.[`${y}Side`]?.pins,E=x;return S!==w&&(E=C.length-x-1),Rf(C[E],e.pinLabels)},s=[],a=0,c=0;for(let y=0;y<n.leftSize;y++){let x=o({side:"left",sideIndex:y,truePinIndex:c}),v=e.numericSchPinStyle?.[`pin${x}`]??e.numericSchPinStyle?.[x];v?.topMargin&&(a+=v.topMargin),s.push({trueIndex:c,pinNumber:x,side:"left",distanceFromOrthogonalEdge:a}),v?.bottomMargin&&(a+=v.bottomMargin),y===n.leftSize-1?i.left=a:a+=e.schPinSpacing,c++}a=0;for(let y=0;y<n.bottomSize;y++){let x=o({side:"bottom",sideIndex:y,truePinIndex:c}),v=e.numericSchPinStyle?.[`pin${x}`]??e.numericSchPinStyle?.[x];v?.leftMargin&&(a+=v.leftMargin),s.push({trueIndex:c,pinNumber:x,side:"bottom",distanceFromOrthogonalEdge:a}),v?.rightMargin&&(a+=v.rightMargin),y===n.bottomSize-1?i.bottom=a:a+=e.schPinSpacing,c++}a=0;for(let y=0;y<n.rightSize;y++){let x=o({side:"right",sideIndex:y,truePinIndex:c}),v=e.numericSchPinStyle?.[`pin${x}`]??e.numericSchPinStyle?.[x];v?.bottomMargin&&(a+=v.bottomMargin),s.push({trueIndex:c,pinNumber:x,side:"right",distanceFromOrthogonalEdge:a}),v?.topMargin&&(a+=v.topMargin),y===n.rightSize-1?i.right=a:a+=e.schPinSpacing,c++}a=0;for(let y=0;y<n.topSize;y++){let x=o({side:"top",sideIndex:y,truePinIndex:c}),v=e.numericSchPinStyle?.[`pin${x}`]??e.numericSchPinStyle?.[x];v?.rightMargin&&(a+=v.rightMargin),s.push({trueIndex:c,pinNumber:x,side:"top",distanceFromOrthogonalEdge:a}),v?.leftMargin&&(a+=v.leftMargin),y===n.topSize-1?i.top=a:a+=e.schPinSpacing,c++}let l=e.schWidth;if(l===void 0){l=Math.max(i.top+e.schPinSpacing*2,i.bottom+e.schPinSpacing*2);let y=e.pinLabels?Math.max(...Object.values(e.pinLabels).map(v=>v.length*.1)):0,x=y>0?1.1:0;l=Math.max(l,y+x)}let u=e.schHeight;u||(u=Math.max(i.left+e.schPinSpacing*2,i.right+e.schPinSpacing*2));let h={left:{x:-l/2-t,y:i.left/2},bottom:{x:-i.bottom/2,y:-u/2-t},right:{x:l/2+t,y:-i.right/2},top:{x:i.top/2,y:u/2+t}},f={left:{x:0,y:-1},right:{x:0,y:1},top:{x:-1,y:0},bottom:{x:1,y:0}},_=s.map(y=>{let{distanceFromOrthogonalEdge:x,side:v}=y,w=h[v],S=f[v];return{x:w.x+x*S.x,y:w.y+x*S.y,...y}});return{getPortPositionByPinNumber(y){let x=_.find(v=>v.pinNumber.toString()===y.toString());return x||null},getSize(){return{width:l,height:u}},getSizeIncludingPins(){return{width:l+(n.leftSize||n.rightSize?.4:0),height:u+(n.topSize||n.bottomSize?.4:0)}},pinCount:r}},H2t=(0,SY.default)("tscircuit:core:footprint"),PY=class extends Ie{get config(){return{componentName:"Footprint",zodProps:kL}}doInitialPcbFootprintLayout(){if(this.root?.pcbDisabled)return;let e=this.children.filter(h=>h.componentName==="Constraint");if(e.length===0)return;let{isFlipped:t}=this._getPcbPrimitiveFlippedHelpers(),n=h=>t&&"left"in h&&"right"in h?{...h,left:h.right,right:h.left}:h,i=e.flatMap(h=>h._getAllReferencedComponents().componentsWithSelectors).map(({component:h,selector:f,componentSelector:_,edge:y})=>({component:h,selector:f,componentSelector:_,edge:y,bounds:h._getPcbCircuitJsonBounds()}));if(i.some(h=>h.edge))throw new Error("edge constraints not implemented yet for footprint layout, contributions welcome!");function r(h){return i.find(({selector:f})=>f===h)}let o=new up,s={};function a(h){return h in s||(s[h]=new Is(h),o.addEditVariable(s[h],mn.weak)),s[h]}for(let{selector:h,bounds:f}of i){let _=a(`${h}_x`),y=a(`${h}_y`);o.suggestValue(_,f.center.x),o.suggestValue(y,f.center.y)}for(let h of e){let f=h._parsedProps;if("xDist"in f){let{xDist:_,left:y,right:x,edgeToEdge:v,centerToCenter:w}=n(f),S=a(`${y}_x`),C=a(`${x}_x`),E=r(y)?.bounds,R=r(x)?.bounds;if(w){let I=new bn(C,[-1,S]);o.addConstraint(new ti(I,zn.Eq,f.xDist,mn.required))}else if(v){let I=new bn(C,-R.width/2,[-1,S],-E.width/2);o.addConstraint(new ti(I,zn.Eq,f.xDist,mn.required))}}else if("yDist"in f){let{yDist:_,top:y,bottom:x,edgeToEdge:v,centerToCenter:w}=f,S=a(`${y}_y`),C=a(`${x}_y`),E=r(y)?.bounds,R=r(x)?.bounds;if(w){let I=new bn(S,[-1,C]);o.addConstraint(new ti(I,zn.Eq,f.yDist,mn.required))}else if(v){let I=new bn(S,E.height/2,[-1,C],-R.height/2);o.addConstraint(new ti(I,zn.Eq,f.yDist,mn.required))}}else if("sameY"in f){let{for:_}=f;if(_.length<2)continue;let y=_.map(v=>a(`${v}_y`)),x=new bn(...y.slice(1));o.addConstraint(new ti(x,zn.Eq,y[0],mn.required))}else if("sameX"in f){let{for:_}=f;if(_.length<2)continue;let y=_.map(v=>a(`${v}_x`)),x=new bn(...y.slice(1));o.addConstraint(new ti(x,zn.Eq,y[0],mn.required))}}o.updateVariables(),H2t.enabled&&(console.log("Solution to layout constraints:"),console.table(Object.entries(s).map(([h,f])=>({var:h,val:f.value()}))));let c={left:1/0,right:-1/0,top:-1/0,bottom:1/0};for(let{selector:h,bounds:{width:f,height:_}}of i){let y=a(`${h}_x`),x=a(`${h}_y`),v=y.value()-f/2,w=y.value()+f/2,S=x.value()+_/2,C=x.value()-_/2;c.left=Math.min(c.left,v),c.right=Math.max(c.right,w),c.top=Math.max(c.top,S),c.bottom=Math.min(c.bottom,C)}let l={x:-(c.right+c.left)/2,y:-(c.top+c.bottom)/2},u=this.getPrimitiveContainer()._getGlobalPcbPositionBeforeLayout();l.x+=u.x,l.y+=u.y;for(let{component:h,selector:f}of i){let _=a(`${f}_x`),y=a(`${f}_y`);h._setPositionFromLayout({x:_.value()+l.x,y:y.value()+l.y})}}},GT=p.union([p.number(),p.string()]),qj=p.object({x:GT,y:GT,z:GT}),TY=class extends Ie{get config(){return{componentName:"CadModel",zodProps:JL}}doInitialCadModelRender(){let e=this._findParentWithPcbComponent();if(!e||!e.pcb_component_id)return;let{db:t}=this.root,{boardThickness:n=0}=this.root?._getBoard()??{},i=e._getPcbCircuitJsonBounds(),r=t.pcb_component.get(e.pcb_component_id),o=this._parsedProps;if(!o||typeof o.modelUrl!="string")return;let s=e._computePcbGlobalTransformBeforeLayout(),c=fo(s).rotation.angle*180/Math.PI,l=qj.parse({x:0,y:0,z:0});if(typeof o.rotationOffset=="number")l.z=Number(o.rotationOffset);else if(typeof o.rotationOffset=="object"){let x=qj.parse(o.rotationOffset);l.x=Number(x.x),l.y=Number(x.y),l.z=Number(x.z)}let u=qy.parse({x:o.pcbX??0,y:o.pcbY??0,z:o.pcbZ??0,...typeof o.positionOffset=="object"?o.positionOffset:{}}),h=e.props.layer==="bottom"?"bottom":"top",f=new URL(o.modelUrl).pathname.split(".").pop()?.toLowerCase(),_={};f==="stl"?_.model_stl_url=this._addCachebustToModelUrl(o.modelUrl):f==="obj"?_.model_obj_url=this._addCachebustToModelUrl(o.modelUrl):f==="gltf"?_.model_gltf_url=this._addCachebustToModelUrl(o.modelUrl):f==="glb"?_.model_glb_url=this._addCachebustToModelUrl(o.modelUrl):f==="step"||f==="stp"?_.model_step_url=this._addCachebustToModelUrl(o.modelUrl):f==="wrl"||f==="vrml"?_.model_wrl_url=this._addCachebustToModelUrl(o.modelUrl):_.model_stl_url=this._addCachebustToModelUrl(o.modelUrl);let y=t.cad_component.insert({position:{x:i.center.x+Number(u.x),y:i.center.y+Number(u.y),z:(h==="bottom"?-n/2:n/2)+Number(u.z)},rotation:{x:Number(l.x),y:(h==="top"?0:180)+Number(l.y),z:h==="bottom"?-(c+Number(l.z))+180:c+Number(l.z)},pcb_component_id:e.pcb_component_id,source_component_id:e.source_component_id,model_unit_to_mm_scale_factor:typeof o.modelUnitToMmScale=="number"?o.modelUnitToMmScale:void 0,..._});this.cad_component_id=y.cad_component_id}_findParentWithPcbComponent(){let e=this.parent;for(;e&&!e.pcb_component_id;)e=e.parent;return e}_addCachebustToModelUrl(e){if(!e||!e.includes("modelcdn.tscircuit.com"))return e;let t=this.root?.getClientOrigin()??"";return`${e}${e.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(t)}`}},IY=class extends Ie{constructor(){super(...arguments);T(this,"isPrimitiveContainer",!0)}get config(){return{componentName:"CadAssembly",zodProps:KL}}},G2t=(e,t)=>{if(!e)return;let n={};for(let[i,r]of Object.entries(e)){let o=Rf(i,t),s={leftMargin:r.marginLeft??r.leftMargin,rightMargin:r.marginRight??r.rightMargin,topMargin:r.marginTop??r.topMargin,bottomMargin:r.marginBottom??r.bottomMargin};n[`pin${o}`]={...n[`pin${o}`],...s}}return n},Wj=class{constructor({input:e}){T(this,"input");this.input=e}solveAndMapToTraces(){let e=[];for(let t of this.input.connections){if(t.pointsToConnect.length!==2)continue;let[n,i]=t.pointsToConnect,r={type:"pcb_trace",pcb_trace_id:"",connection_name:t.name,route:[{route_type:"wire",x:n.x,y:n.y,layer:"top",width:.1},{route_type:"wire",x:i.x,y:i.y,layer:"top",width:.1}]};e.push(r)}return e}},U2t=e=>{let t=Math.min(...e.map(o=>o.center.x)),n=Math.max(...e.map(o=>o.center.x)),i=Math.min(...e.map(o=>o.center.y)),r=Math.max(...e.map(o=>o.center.y));return{minX:t,maxX:n,minY:i,maxY:r}},Zj=["top","bottom","inner1","inner2"],Ix=(e,t=[])=>{let n=[];if(t.length===0){let a=e[0].layers;for(let c of a)n.push(...Ix(e.slice(1),[c]));return n}if(e.length===0)return[];let i=e[0],r=i.via||i.optional_via,o=t[t.length-1];if(e.length===1){let a=i;return a.layers&&r?a.layers.map(c=>({layer_path:[...t,c]})):a.layers?.includes(o)?[{layer_path:[...t,o]}]:[]}if(!r)return i.layers&&!i.layers.includes(o)?[]:Ix(e.slice(1),t.concat([o]));let s=(i.optional_via?Zj:Zj.filter(a=>a!==o)).filter(a=>!i.layers||i.layers?.includes(a));for(let a of s)n.push(...Ix(e.slice(1),t.concat(a)));return n};function Kj(e){let t={x:e.to.x-e.from.x,y:e.to.y-e.from.y},n=Math.abs(t.x),i=Math.abs(t.y);return n>i?t.x>0?"right":"left":t.y>0?"down":"up"}function Up(e,t){return Math.hypot(e.x-t.x,e.y-t.y)}var q2t=e=>{if(e.length===1)return e[0];if(e.some(c=>c.length===0))throw new Error("Cannot merge routes with zero length");let t=[],n=e[0][0],i=e[0][e[0].length-1],r=e[1][0],o=e[1][e[1].length-1],s=Math.min(Up(n,r),Up(n,o)),a=Math.min(Up(i,r),Up(i,o));s<a?t.push(...e[0].reverse()):t.push(...e[0]);for(let c=1;c<e.length;c++){let l=t[t.length-1],u=e[c],h=u[0],f=u[u.length-1],_=Up(l,h),y=Up(l,f);_<y?t.push(...u):t.push(...u.reverse())}for(let c=1;c<t.length-1;c++){let l=t[c-1],u=t[c];l.route_type==="wire"&&u.route_type==="wire"&&l.layer!==u.layer&&t.splice(c,0,{x:l.x,y:l.y,from_layer:l.layer,to_layer:u.layer,route_type:"via"})}return t},W2t=(e,t)=>{let n="_getGlobalPcbPositionBeforeLayout"in e?e._getGlobalPcbPositionBeforeLayout():e,i="_getGlobalPcbPositionBeforeLayout"in t?t._getGlobalPcbPositionBeforeLayout():t;return Math.sqrt((n.x-i.x)**2+(n.y-i.y)**2)};function Z2t(e,t){if(t.length===0)throw new Error("No candidates given to getClosest method");let n=t[0],i=1/0;for(let r of t){let o=W2t(e,r);o<i&&(n=r,i=o)}return n}var K2t=(e,t)=>{let n=0;n+=e.length??0,n+=t.filter(i=>i.is_crossing).length;for(let i=1;i<t.length;i++){let r=t[i-1],o=t[i],s=Math.abs(r.from.x-r.to.x)<.01,a=Math.abs(o.from.x-o.to.x)<.01;s!==a&&n++}return n},Of=e=>({up:"bottom",down:"top",left:"right",right:"left"})[e]??null,JT=({firstEdge:e,firstEdgePort:t,firstDominantDirection:n,lastEdge:i,lastEdgePort:r,lastDominantDirection:o})=>{if(e&&t)return JT({lastEdge:{from:e.to,to:e.from},lastEdgePort:t,lastDominantDirection:n}).reverse().map(a=>({from:a.to,to:a.from}));let s=[];if(i&&r){let a={x:i.to.x,y:i.to.y};o==="left"||o==="right"?(a.x=r.position.x,s.push({from:i.to,to:{...a}}),s.push({from:a,to:{...r.position}})):(a.y=r.position.y,s.push({from:i.to,to:{...a}}),s.push({from:a,to:{...r.position}}))}return s=s.filter(a=>Si(a.from,a.to)>.01),s};function J2t(e){try{return[e(),null]}catch(t){return[null,t]}}var Q2t=(e,{db:t})=>{let n=e.map(i=>{let r=t.source_port.get(i.source_port_id);if(!r?.source_component_id)return null;let o=t.source_component.get(r.source_component_id);return o?.ftype==="simple_capacitor"?o.max_decoupling_trace_length:null}).filter(i=>i!==null);if(n.length!==0)return Math.min(...n)};function tvt({ports:e,nets:t}){if(e.length>=2)return`${e[0]?.selector} to ${e[1]?.selector}`;if(e.length===1&&t.length===1)return`${e[0]?.selector} to net.${t[0]._parsedProps.name}`}var evt=(e,{db:t})=>{let n=t.pcb_board.list()[0];if(n.outline){let c=n.outline,l=(u,h)=>{let f=!1;for(let _=0,y=h.length-1;_<h.length;y=_++){let x=h[_].x,v=h[_].y,w=h[y].x,S=h[y].y;v>u.y!=S>u.y&&u.x<(w-x)*(u.y-v)/(S-v)+x&&(f=!f)}return f};return e.some(u=>!l(u,c))}let i=n.width,r=n.height,o=n.center.x,s=n.center.y;return e.some(c=>c.x<o-i/2||c.y<s-r/2||c.x>o+i/2||c.y>s+r/2)},Jj=(e,t)=>Math.abs(e-t)<1e-4,nvt=(e,t,{viaDiameter:n=.5}={})=>{let i=[];for(let r=0;r<e.length-1;r++){let[o,s]=[e[r],e[r+1]],a=r-1>=0?e[r-1]:null,c=Jj(o.y,s.y),l=Jj(o.x,s.x);if(!c&&!l)throw new Error(`getObstaclesFromTrace currently only supports horizontal and vertical traces (not diagonals) Conflicting trace: ${t}, start: (${o.x}, ${o.y}), end: (${s.x}, ${s.y})`);let u={type:"rect",layers:[o.layer],center:{x:(o.x+s.x)/2,y:(o.y+s.y)/2},width:c?Math.abs(o.x-s.x):.1,height:l?Math.abs(o.y-s.y):.1,connectedTo:[t]};if(i.push(u),a&&a.layer===o.layer&&o.layer!==s.layer){let h={type:"rect",layers:[o.layer,s.layer],center:{x:o.x,y:o.y},connectedTo:[t],width:n,height:n};i.push(h)}}return i};function MY(e,t=4){let{center:n,width:i,height:r,rotation:o}=e,s=[],a=o*Math.PI/180,c=Math.cos(a),l=Math.sin(a),u=(o%360+360)%360;if(r<=i?u>=45&&u<135||u>=225&&u<315:u>=135&&u<225||u>=315||u<45){let f=i/t;for(let _=0;_<t;_++){let y=(_-t/2+.5)*f,x=-y*c,v=-y*l,w=f*1.1,S=Math.abs(r*c)+Math.abs(f*l);s.push({center:{x:n.x+x,y:n.y+v},width:w,height:S})}}else{let f=r/t;for(let _=0;_<t;_++){let y=(_-t/2+.5)*f,x=-y*l,v=y*c,w=Math.abs(i*c)+Math.abs(f*l),S=f*1.1;s.push({center:{x:n.x+x,y:n.y+v},width:w,height:S})}}return s}function ivt(e,t={}){if(e.length<3)return[];let{rectHeight:n=.1}=t,i=[],r=e.map(a=>a.y),o=Math.min(...r),s=Math.max(...r);for(let a=o;a<s;a+=n){let c=a+n/2,l=[];for(let u=0;u<e.length;u++){let h=e[u],f=e[(u+1)%e.length];if(h.y<=c&&f.y>c||f.y<=c&&h.y>c){let _=(c-h.y)*(f.x-h.x)/(f.y-h.y)+h.x;l.push(_)}}l.sort((u,h)=>u-h);for(let u=0;u<l.length;u+=2)if(u+1<l.length){let h=l[u],_=l[u+1]-h;_>1e-6&&i.push({center:{x:h+_/2,y:c},width:_,height:n})}}return i}function rvt(e,t={}){let{center:n,radius:i}=e,{rectHeight:r=.1}=t,o=[],s=Math.ceil(i*2/r);for(let a=0;a<s;a++){let c=n.y-i+(a+.5)*r,l=c-n.y,u=Math.sqrt(i*i-l*l);u>0&&o.push({center:{x:n.x,y:c},width:u*2,height:r})}return o}var Wa=["top","inner1","inner2","bottom"],hI=(e,t)=>{let n=r=>t?r.concat(r.map(o=>t?.getNetConnectedToId(o)).filter(Boolean)):r,i=[];for(let r of e)if(r.type==="pcb_smtpad"){if(r.shape==="circle")i.push({type:"oval",layers:[r.layer],center:{x:r.x,y:r.y},width:r.radius*2,height:r.radius*2,connectedTo:n([r.pcb_smtpad_id])});else if(r.shape==="rect")i.push({type:"rect",layers:[r.layer],center:{x:r.x,y:r.y},width:r.width,height:r.height,connectedTo:n([r.pcb_smtpad_id])});else if(r.shape==="rotated_rect"){let o={center:{x:r.x,y:r.y},width:r.width,height:r.height,rotation:r.ccw_rotation},s=MY(o);for(let a of s)i.push({type:"rect",layers:[r.layer],center:a.center,width:a.width,height:a.height,connectedTo:n([r.pcb_smtpad_id])})}}else if(r.type==="pcb_keepout")r.shape==="circle"?i.push({type:"oval",layers:r.layers,center:{x:r.center.x,y:r.center.y},width:r.radius*2,height:r.radius*2,connectedTo:[]}):r.shape==="rect"&&i.push({type:"rect",layers:r.layers,center:{x:r.center.x,y:r.center.y},width:r.width,height:r.height,connectedTo:[]});else if(r.type==="pcb_cutout"){if(r.shape==="rect")i.push({type:"rect",layers:Wa,center:{x:r.center.x,y:r.center.y},width:r.width,height:r.height,connectedTo:[]});else if(r.shape==="circle"){let o=rvt({center:r.center,radius:r.radius},{rectHeight:.6});for(let s of o)i.push({type:"rect",layers:Wa,center:s.center,width:s.width,height:s.height,connectedTo:[]})}else if(r.shape==="polygon"){let o=ivt(r.points,{rectHeight:.6});for(let s of o)i.push({type:"rect",layers:Wa,center:s.center,width:s.width,height:s.height,connectedTo:[]})}}else if(r.type==="pcb_hole")r.hole_shape==="oval"?i.push({type:"oval",center:{x:r.x,y:r.y},width:r.hole_width,height:r.hole_height,connectedTo:[]}):r.hole_shape==="square"?i.push({type:"rect",layers:Wa,center:{x:r.x,y:r.y},width:r.hole_diameter,height:r.hole_diameter,connectedTo:[]}):(r.hole_shape==="round"||r.hole_shape==="circle")&&i.push({type:"rect",layers:Wa,center:{x:r.x,y:r.y},width:r.hole_diameter,height:r.hole_diameter,connectedTo:[]});else if(r.type==="pcb_plated_hole")r.shape==="circle"?i.push({type:"oval",layers:Wa,center:{x:r.x,y:r.y},width:r.outer_diameter,height:r.outer_diameter,connectedTo:n([r.pcb_plated_hole_id])}):r.shape==="circular_hole_with_rect_pad"?i.push({type:"rect",layers:Wa,center:{x:r.x,y:r.y},width:r.rect_pad_width,height:r.rect_pad_height,connectedTo:n([r.pcb_plated_hole_id])}):(r.shape==="oval"||r.shape==="pill")&&i.push({type:"oval",layers:Wa,center:{x:r.x,y:r.y},width:r.outer_width,height:r.outer_height,connectedTo:n([r.pcb_plated_hole_id])});else if(r.type==="pcb_trace"){let o=nvt(r.route.map(s=>({x:s.x,y:s.y,layer:"layer"in s?s.layer:s.from_layer})),r.source_trace_id);i.push(...o)}else r.type==="pcb_via"&&i.push({type:"rect",layers:r.layers,center:{x:r.x,y:r.y},connectedTo:[],width:r.outer_diameter,height:r.outer_diameter});return i},Ka=({anchor_position:e,anchor_side:t,text:n,font_size:i=.18})=>{let r=.1*(i/.18),o=n.length*r,s=i,a={...e};switch(t){case"right":a.x-=o/2;break;case"left":a.x+=o/2;break;case"top":a.y-=s/2;break;case"bottom":a.y+=s/2;break}return a},dI=({db:e,source_trace_id:t,sameNetOnly:n,differentNetOnly:i})=>{!n&&!i&&(i=!0);let r=e.source_trace.get(t),o=[];for(let s of e.schematic_trace.list()){if(s.source_trace_id===t)continue;let c=e.source_trace.get(s.source_trace_id)?.subcircuit_connectivity_map_key===r.subcircuit_connectivity_map_key;i&&c||n&&!c||o.push(s)}return o},ovt=({edges:e,otherEdges:t})=>{let n=[...e];for(let i=0;i<n.length;i++){if(i>2e3)throw new Error("Over 2000 iterations spent inside createSchematicTraceCrossingSegments, you have triggered an infinite loop, please report this!");let r=n[i],o=Math.abs(r.from.x-r.to.x)<.01?"vertical":r.from.y===r.to.y?"horizontal":"not-orthogonal";if(o==="not-orthogonal")continue;let s=[];for(let x of t){let v=x.from.x===x.to.x?"vertical":x.from.y===x.to.y?"horizontal":"not-orthogonal";if(v==="not-orthogonal"||o===v)continue;if(Aa([r.from,r.to],[x.from,x.to],{lineThickness:.01})){let S=o==="vertical"?r.from.x:x.from.x,C=o==="vertical"?x.from.y:r.from.y,E={x:S,y:C};s.push({otherEdge:x,crossingPoint:E,distanceFromEdgeFrom:Si(r.from,E)})}}if(s.length===0)continue;let a=s[0];for(let x of s)x.distanceFromEdgeFrom<a.distanceFromEdgeFrom&&(a=x);let c=a.crossingPoint,l=.075;if(c.x===r.from.x&&c.y===r.from.y)continue;let u=rg(r.from,c),h={x:c.x-u.x*l/2,y:c.y-u.y*l/2},f={x:c.x+u.x*l/2,y:c.y+u.y*l/2},_=Si(f,r.to)<l,y=[{from:r.from,to:h},{from:h,to:f,is_crossing:!0},{from:f,to:r.to}];n.splice(i,1,...y),i+=y.length-2,_&&i++}return n},QT=.001,qp=(e,t)=>{let n=Math.min(t.from.x,t.to.x),i=Math.max(t.from.x,t.to.x),r=Math.min(t.from.y,t.to.y),o=Math.max(t.from.y,t.to.y);return e.x>=n&&e.x<=i&&e.y>=r&&e.y<=o},Qj=e=>{let t=Math.abs(e.from.x-e.to.x)<QT,n=Math.abs(e.from.y-e.to.y)<QT;return t?"vertical":n?"horizontal":"diagonal"},svt=(e,t)=>{let n=Qj(e),i=Qj(t);if(n===i)return null;if(n==="vertical"&&i==="horizontal"||n==="horizontal"&&i==="vertical"){let h=n==="vertical"?e:t,f=n==="horizontal"?e:t,_=h.from.x,y=f.from.y,x={x:_,y};return qp(x,e)&&qp(x,t)?x:null}if(n==="vertical"||i==="vertical"){let h=n==="vertical"?e:t,f=n==="vertical"?t:e,_=h.from.x,y=(f.to.y-f.from.y)/(f.to.x-f.from.x),x=f.from.y-y*f.from.x,v=y*_+x,w={x:_,y:v};return qp(w,e)&&qp(w,t)?w:null}let r=(e.to.y-e.from.y)/(e.to.x-e.from.x),o=e.from.y-r*e.from.x,s=(t.to.y-t.from.y)/(t.to.x-t.from.x),a=t.from.y-s*t.from.x;if(Math.abs(r-s)<QT)return null;let c=(a-o)/(r-s),l=r*c+o,u={x:c,y:l};return qp(u,e)&&qp(u,t)?u:null},avt=({edges:e,db:t,source_trace_id:n})=>{let i=dI({db:t,source_trace_id:n,sameNetOnly:!0}).flatMap(o=>o.edges),r=new Map;for(let o of e)for(let s of i){let a=svt(o,s);if(a){let c=`${a.x.toFixed(6)},${a.y.toFixed(6)}`;r.has(c)||r.set(c,a)}}return Array.from(r.values())};function cvt(e,t={}){let{minX:n,maxX:i,minY:r,maxY:o}=e,s=t.padding??1;if(!isFinite(n)||!isFinite(i)||!isFinite(r)||!isFinite(o))return[];let a=n-s,c=i+s,l=o+s,u=r-s,h=.01;return[{type:"rect",layers:["top"],center:{x:(a+c)/2,y:l},width:c-a,height:h,connectedTo:[]},{type:"rect",layers:["top"],center:{x:(a+c)/2,y:u},width:c-a,height:h,connectedTo:[]},{type:"rect",layers:["top"],center:{x:a,y:(l+u)/2},width:h,height:l-u,connectedTo:[]},{type:"rect",layers:["top"],center:{x:c,y:(l+u)/2},width:h,height:l-u,connectedTo:[]}]}var lvt=e=>{let t=e.root.db,n=e._findConnectedPorts().ports??[],i=new Set(n.map(s=>s.schematic_port_id)),r=[];for(let s of t.toArray()){if(s.type==="schematic_component"){let a=!!s.symbol_name,c=s.size.width>s.size.height?"horz":"vert";r.push({type:"rect",layers:["top"],center:s.center,width:s.size.width+(a&&c==="horz"?-.5:0),height:s.size.height+(a&&c==="vert"?-.5:0),connectedTo:[]})}if(s.type==="schematic_port"){if(i.has(s.schematic_port_id))continue;let a=s.facing_direction?og(s.facing_direction):{x:0,y:0};r.push({type:"rect",layers:["top"],center:{x:s.center.x-a.x*.1,y:s.center.y-a.y*.1},width:.1+Math.abs(a.x)*.3,height:.1+Math.abs(a.y)*.3,connectedTo:[]})}s.type==="schematic_text"&&r.push({type:"rect",layers:["top"],center:s.position,width:(s.text?.length??0)*.1,height:.2,connectedTo:[]}),s.type==="schematic_box"&&r.push({type:"rect",layers:["top"],center:{x:s.x,y:s.y},width:s.width,height:s.height,connectedTo:[]})}let o=bY(t.toArray());return r.push(...cvt(o,{padding:1})),r},uvt=({edges:e,db:t,source_trace_id:n})=>{let i=t.source_trace.get(n),r=dI({db:t,source_trace_id:n,differentNetOnly:!0}).flatMap(s=>s.edges),o=s=>{let{from:a,to:c}=s;return a.x===c.x?"vertical":"horizontal"};for(let s of e){let a=o(s),c=()=>r.find(u=>o(u)===a&&Aa([s.from,s.to],[u.from,u.to],{lineThickness:.05})),l=c();for(;l;)a==="horizontal"?(s.from.y+=.1,s.to.y+=.1):(s.from.x+=.1,s.to.x+=.1),l=c()}},tI=e=>{switch(e){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:}},pvt=kF.version??"unknown",Cf=class extends Error{constructor(e){super(`${e} (capacity-autorouter@${pvt})`),this.name="AutorouterError"}},kx=class extends Error{constructor(e){super(e.message),this.errorData=e,this.name="TraceConnectionError"}},hvt=e=>{if(e.root?._featureMspSchematicTraceRouting||e._couldNotFindPort||e.root?.schematicDisabled)return;let{db:t}=e.root,{_parsedProps:n,parent:i}=e;if(!i)throw new Error("Trace has no parent");let r,o;try{let X=e._findConnectedPorts();r=X.allPortsFound,o=X.portsWithSelectors??[]}catch(X){if(X instanceof kx){t.source_trace_not_connected_error.insert({...X.errorData,error_type:"source_trace_not_connected_error"});return}throw X}let{netsWithSelectors:s}=e._findConnectedNets();if(!r)return;let c=o.map(X=>X.port.schematic_port_id).sort().join(","),l=e.root?._getBoard();if(l?._connectedSchematicPortPairs&&l._connectedSchematicPortPairs.has(c))return;let u={name:e.source_trace_id,pointsToConnect:[]},h=lvt(e),f=o.filter(({port:X})=>X.schematic_port_id!==null).map(({port:X})=>({port:X,position:X._getGlobalSchematicPositionAfterLayout(),schematic_port_id:X.schematic_port_id??void 0,facingDirection:X.facingDirection}));if(f.length===1&&s.length===1){let X=s[0].net,{port:W,position:Q}=f[0],J=e.getSubcircuit().selectAll("netlabel").find(it=>{let et=it._parsedProps.connection??it._parsedProps.connectsTo;return et?Array.isArray(et)?et.some(mt=>e.getSubcircuit().selectOne(mt,{port:!0})===W):e.getSubcircuit().selectOne(et,{port:!0})===W:!1});if(!J){let it=t.schematic_net_label.getWhere({source_trace_id:e.source_trace_id});it&&(J=it)}if(J){let it="_getGlobalSchematicPositionBeforeLayout"in J?J._getGlobalSchematicPositionBeforeLayout():J.anchor_position,et=[];Q.x===it.x||Q.y===it.y?et.push({from:Q,to:it}):(et.push({from:Q,to:{x:it.x,y:Q.y}}),et.push({from:{x:it.x,y:Q.y},to:it}));let vt=t.schematic_trace.insert({source_trace_id:e.source_trace_id,edges:et,junctions:[],subcircuit_connectivity_map_key:e.subcircuit_connectivity_map_key??void 0});e.schematic_trace_id=vt.schematic_trace_id;return}if(e.props.schDisplayLabel){let it=Of(W.facingDirection)??"bottom";t.schematic_net_label.insert({text:e.props.schDisplayLabel,source_net_id:X.source_net_id,anchor_position:Q,center:Ka({anchor_position:Q,anchor_side:it,text:e.props.schDisplayLabel}),anchor_side:it});return}let _t=Of(W.facingDirection)??"bottom",st=t.schematic_net_label.insert({text:X._parsedProps.name,source_net_id:X.source_net_id,anchor_position:Q,center:Ka({anchor_position:Q,anchor_side:_t,text:X._parsedProps.name}),anchor_side:_t});return}if(e.props.schDisplayLabel&&("from"in e.props&&"to"in e.props||"path"in e.props)){e._doInitialSchematicTraceRenderWithDisplayLabel();return}if(f.length<2)return;let x=(()=>{let X=[];for(let Q=0;Q<f.length-1;Q++){let J=f[Q],_t=f[Q+1],st=Na({x:J.position.x,y:J.position.y,facingDirection:tI(J.facingDirection)},{x:_t.position.x,y:_t.position.y,facingDirection:tI(_t.facingDirection)});for(let it=0;it<st.length-1;it++)X.push({from:st[it],to:st[it+1]})}let W=(Q,J)=>{let _t=J.width/2,st=J.height/2,it=J.center.x-_t,et=J.center.x+_t,vt=J.center.y-st,mt=J.center.y+st,Tt=pt=>pt.x>=it&&pt.x<=et&&pt.y>=vt&&pt.y<=mt;return Tt(Q.from)||Tt(Q.to)?!0:[[{x:it,y:vt},{x:et,y:vt}],[{x:et,y:vt},{x:et,y:mt}],[{x:et,y:mt},{x:it,y:mt}],[{x:it,y:mt},{x:it,y:vt}]].some(pt=>Aa([Q.from,Q.to],pt,{lineThickness:0}))};for(let Q of X)for(let J of h)if(W(Q,J))return null;return X})();x&&x.length===0&&(x=null),u.pointsToConnect=f.map(({position:X})=>({...X,layer:"top"}));let v=U2t(h),w=2,S={minTraceWidth:.1,obstacles:h,connections:[u],bounds:{minX:v.minX-w,maxX:v.maxX+w,minY:v.minY-w,maxY:v.maxY+w},layerCount:1},C=Hy,E=!1;if(e.getSubcircuit().props._schDirectLineRoutingEnabled&&(C=Wj,E=!0),!x){let W=new C({input:S,MAX_ITERATIONS:100,OBSTACLE_MARGIN:.1,isRemovePathLoopsEnabled:!0,isShortenPathWithShortcutsEnabled:!0,marginsWithCosts:[{margin:1,enterCost:0,travelCostFactor:1},{margin:.3,enterCost:0,travelCostFactor:1},{margin:.2,enterCost:0,travelCostFactor:2},{margin:.1,enterCost:0,travelCostFactor:3}]}).solveAndMapToTraces();if(W.length===0){if(e._isSymbolToChipConnection()||e._isSymbolToSymbolConnection()||e._isChipToChipConnection()){e._doInitialSchematicTraceRenderWithDisplayLabel();return}W=new Wj({input:S}).solveAndMapToTraces(),E=!0}let[{route:Q}]=W;x=[];for(let J=0;J<Q.length-1;J++)x.push({from:Q[J],to:Q[J+1]})}let R=e.source_trace_id,I=[];if(!E){uvt({edges:x,db:t,source_trace_id:R});let X=dI({db:t,source_trace_id:R,differentNetOnly:!0}).flatMap(W=>W.edges);x=ovt({edges:x,otherEdges:X}),I=avt({edges:x,db:t,source_trace_id:e.source_trace_id})}if(!x||x.length===0)return;let k=x[x.length-1],M=f[f.length-1],A=Kj(k);x.push(...JT({lastEdge:k,lastEdgePort:M,lastDominantDirection:A}));let L=x[0],B=f[0],D=Kj(L);if(x.unshift(...JT({firstEdge:L,firstEdgePort:B,firstDominantDirection:D})),!e.source_trace_id)throw new Error("Missing source_trace_id for schematic trace insertion.");if(e.getSubcircuit()._parsedProps.schTraceAutoLabelEnabled&&K2t(I,x)>=5&&(e._isSymbolToChipConnection()||e._isSymbolToSymbolConnection()||e._isChipToChipConnection())){e._doInitialSchematicTraceRenderWithDisplayLabel();return}let V=t.schematic_trace.insert({source_trace_id:e.source_trace_id,edges:x,junctions:I,subcircuit_connectivity_map_key:e.subcircuit_connectivity_map_key??void 0});e.schematic_trace_id=V.schematic_trace_id;for(let{port:X}of o)X.schematic_port_id&&t.schematic_port.update(X.schematic_port_id,{is_connected:!0});l?._connectedSchematicPortPairs&&l._connectedSchematicPortPairs.add(c)};function EY(e){let t=0;for(let n=0;n<e.length;n++){let i=e[n];if(i.route_type==="wire"){let r=e[n+1];if(r){let o=r.x-i.x,s=r.y-i.y;t+=Math.sqrt(o*o+s*s)}}else i.route_type==="via"&&(t+=1.6)}return t}var Sx=e=>({...e._getGlobalPcbPositionAfterLayout(),layers:e.getAvailablePcbLayers()}),dvt=!1;function fvt(e){if(e.root?.pcbDisabled)return;let{db:t}=e.root,{_parsedProps:n,parent:i}=e,r=e.getSubcircuit();if(!i)throw new Error("Trace has no parent");if(r._parsedProps.routingDisabled)return;let o=r._parsedProps.pcbRouteCache?.pcbTraces;if(o){let A=t.pcb_trace.insert({route:o.flatMap(L=>L.route),source_trace_id:e.source_trace_id,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0});e.pcb_trace_id=A.pcb_trace_id;return}if(n.pcbPath&&n.pcbPath.length>0||!r._shouldUseTraceByTraceRouting())return;let{allPortsFound:s,ports:a}=e._findConnectedPorts(),c=[];if(!s)return;let l=[];for(let A of a)A._hasMatchedPcbPrimitive()||l.push(A);if(l.length>0){t.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:e.source_trace_id,message:`Some ports did not have a matching PCB primitive (e.g. a pad or plated hole), this can happen if a footprint is missing. As a result, ${e} wasn't routed. Missing ports: ${l.map(A=>A.getString()).join(", ")}`,pcb_trace_id:e.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:l.map(A=>A.pcb_port_id).filter(Boolean)});return}let u=e._findConnectedNets().netsWithSelectors;if(a.length===0&&u.length===2){e.renderError("Trace connects two nets, we haven't implemented a way to route this yet");return}else if(a.length===1&&u.length===1){let A=a[0],B=u[0].net.getAllConnectedPorts().filter(V=>V!==A);if(B.length===0){console.log("Nothing to connect this port to, the net is empty. TODO should emit a warning!");return}let D=Z2t(A,B);c.push(D),a.push(D)}else if(a.length>1&&u.length>=1){e.renderError("Trace has more than one port and one or more nets, we don't currently support this type of complex trace routing");return}let h=a.flatMap(A=>A.matchedComponents.filter(L=>L.componentName==="TraceHint")),f=(e._parsedProps.pcbRouteHints??[]).concat(h.flatMap(A=>A.getPcbRouteHints()));if(a.length>2){e.renderError(`Trace has more than two ports (${a.map(A=>A.getString()).join(", ")}), routing between more than two ports for a single trace is not implemented`);return}if(e.getSubcircuit().selectAll("trace").filter(A=>A.renderPhaseStates.PcbTraceRender.initialized).some(A=>A._portsRoutedOnPcb.length===a.length&&A._portsRoutedOnPcb.every(L=>a.includes(L))))return;let x=[];f.length===0?x=[Sx(a[0]),Sx(a[1])]:x=[Sx(a[0]),...f,Sx(a[1])];let v=Ix(x);if(dvt&&v.length===0){e.renderError(`Could not find a common layer (using hints) for trace ${e.getString()}`);return}let w=ar(e.root.db.toArray()),[S,C]=J2t(()=>hI(e.root.db.toArray()));if(C){e.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:e.pcb_trace_id,message:`Error getting obstacles for autorouting: ${C.message}`,source_trace_id:e.source_trace_id,center:{x:0,y:0},pcb_port_ids:a.map(A=>A.pcb_port_id),pcb_trace_id:e.pcb_trace_id,pcb_component_ids:[]});return}for(let A of S)if(A.connectedTo.length>0){let B=w.getNetConnectedToId(A.connectedTo[0]);B&&A.connectedTo.push(B)}let E=[];if(v.length===0)E=x;else{let A=v[0].layer_path;E=x.map((L,B)=>L.via?{...L,via_to_layer:A[B]}:{...L,layers:[A[B]]})}E[0].pcb_port_id=a[0].pcb_port_id,E[E.length-1].pcb_port_id=a[1].pcb_port_id;let R=[];for(let[A,L]of xY(E)){let B="via_to_layer"in A?A.via_to_layer:null,D=2,V="layers"in A&&A.layers.length===1?A.layers[0]:B??"top",X="layers"in L&&L.layers.length===1?L.layers[0]:B??"top",W="pcb_port_id"in A?A.pcb_port_id:null,Q="pcb_port_id"in L?L.pcb_port_id:null,J=e.getSubcircuit()._parsedProps.minTraceWidth??.16,_t=new Hy({OBSTACLE_MARGIN:J*2,isRemovePathLoopsEnabled:!0,optimizeWithGoalBoxes:!!(W&&Q),connMap:w,input:{obstacles:S,minTraceWidth:J,connections:[{name:e.source_trace_id,pointsToConnect:[{...A,layer:V,pcb_port_id:W},{...L,layer:X,pcb_port_id:Q}]}],layerCount:e.getSubcircuit()._getSubcircuitLayerCount(),bounds:{minX:Math.min(A.x,L.x)-D,maxX:Math.max(A.x,L.x)+D,minY:Math.min(A.y,L.y)-D,maxY:Math.max(A.y,L.y)+D}}}),st=null;try{st=_t.solveAndMapToTraces()}catch(vt){e.renderError({type:"pcb_trace_error",pcb_trace_error_id:e.source_trace_id,error_type:"pcb_trace_error",message:`error solving route: ${vt.message}`,source_trace_id:e.pcb_trace_id,center:{x:(A.x+L.x)/2,y:(A.y+L.y)/2},pcb_port_ids:a.map(mt=>mt.pcb_port_id),pcb_trace_id:e.pcb_trace_id,pcb_component_ids:a.map(mt=>mt.pcb_component_id)})}if(!st)return;if(st.length===0){e.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:e.pcb_trace_id,message:`Could not find a route for ${e}`,source_trace_id:e.source_trace_id,center:{x:(A.x+L.x)/2,y:(A.y+L.y)/2},pcb_port_ids:a.map(vt=>vt.pcb_port_id),pcb_trace_id:e.pcb_trace_id,pcb_component_ids:a.map(vt=>vt.pcb_component_id)});return}let[it]=st;B&&(it.route=it.route.map(vt=>(vt.route_type==="wire"&&!vt.layer&&(vt.layer=B),vt))),W&&it.route[0].route_type==="wire"&&(it.route[0].start_pcb_port_id=W);let et=it.route[it.route.length-1];Q&&et.route_type==="wire"&&(et.end_pcb_port_id=Q),R.push(it.route)}let I=q2t(R),k=EY(I),M=t.pcb_trace.insert({route:I,source_trace_id:e.source_trace_id,subcircuit_id:e.getSubcircuit()?.subcircuit_id,trace_length:k});e._portsRoutedOnPcb=a,e.pcb_trace_id=M.pcb_trace_id;for(let A of I)A.route_type==="via"&&t.pcb_via.insert({pcb_trace_id:M.pcb_trace_id,x:A.x,y:A.y,hole_diameter:.3,outer_diameter:.6,layers:[A.from_layer,A.to_layer],from_layer:A.from_layer,to_layer:A.to_layer});e._insertErrorIfTraceIsOutsideBoard(I,a)}function mvt(e){if(e.root?.pcbDisabled)return;let{db:t}=e.root,{_parsedProps:n}=e,i=e.getSubcircuit();if(!n.pcbPath||n.pcbPath.length===0)return;let{allPortsFound:r,ports:o,portsWithSelectors:s}=e._findConnectedPorts();if(!r)return;let a=[];for(let S of o)S._hasMatchedPcbPrimitive()||a.push(S);if(a.length>0){t.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:e.source_trace_id,message:`Some ports did not have a matching PCB primitive (e.g. a pad or plated hole), this can happen if a footprint is missing. As a result, ${e} wasn't routed. Missing ports: ${a.map(S=>S.getString()).join(", ")}`,pcb_trace_id:e.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:a.map(S=>S.pcb_port_id).filter(Boolean)});return}let c;n.pcbPathRelativeTo&&(c=s.find(S=>S.selector===n.pcbPathRelativeTo)?.port,c||(c=e.getSubcircuit().selectOne(n.pcbPathRelativeTo))),c||(c=o[0]);let l=o.find(S=>S!==c)??o[1],u=c.getAvailablePcbLayers()[0]||"top",h=n.thickness??e.getSubcircuit()._parsedProps.minTraceWidth??.16,f=c._getGlobalPcbPositionAfterLayout(),_=l._getGlobalPcbPositionAfterLayout(),y=[];y.push({route_type:"wire",x:f.x,y:f.y,width:h,layer:u,start_pcb_port_id:c.pcb_port_id});let x=c?._computePcbGlobalTransformBeforeLayout?.()||vi();for(let S of n.pcbPath){let C=kn(x,{x:S.x,y:S.y});y.push({route_type:"wire",x:C.x,y:C.y,width:h,layer:u})}y.push({route_type:"wire",x:_.x,y:_.y,width:h,layer:u,end_pcb_port_id:l.pcb_port_id});let v=EY(y),w=t.pcb_trace.insert({route:y,source_trace_id:e.source_trace_id,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0,trace_length:v});e._portsRoutedOnPcb=o,e.pcb_trace_id=w.pcb_trace_id,e._insertErrorIfTraceIsOutsideBoard(y,o)}function _vt(e){if(e.root?.schematicDisabled)return;let{db:t}=e.root,{_parsedProps:n,parent:i}=e;if(!i)throw new Error("Trace has no parent");let{allPortsFound:r,portsWithSelectors:o}=e._findConnectedPorts();if(!r)return;let s=o.map(({port:E})=>({port:E,position:E._getGlobalSchematicPositionAfterLayout(),schematic_port_id:E.schematic_port_id,facingDirection:E.facingDirection}));if(s.length<2)throw new Error("Expected at least two ports in portsWithPosition.");let a,c,l=s[0].position,u=s[0].port;if("path"in e.props){if(e.props.path.length!==2)throw new Error("Invalid 'path': Must contain exactly two elements.");[a,c]=e.props.path}else{if(!("from"in e.props&&"to"in e.props))throw new Error("Missing 'from' or 'to' properties in props.");a=e.props.from,c=e.props.to}if(!u.source_port_id)throw new Error(`Missing source_port_id for the 'from' port (${a}).`);let h=s[1].position,f=s[1].port;if(!f.source_port_id)throw new Error(`Missing source_port_id for the 'to' port (${c}).`);let _=t.schematic_net_label.list().find(E=>E.source_net_id===u.source_port_id),y=t.schematic_net_label.list().find(E=>E.source_net_id===f.source_port_id),[x,v]=o.map(({port:E})=>E),S=x.parent?.config.shouldRenderAsSchematicBox?`${x?.parent?.props.name}_${x?.props.name}`:`${v?.parent?.props.name}_${v?.props.name}`,C=e.props.schDisplayLabel??S;if(_&&_.text!==C&&(_.text=`${C} / ${_.text}`),y&&y?.text!==C&&(y.text=`${C} / ${y.text}`),!y){let E=Of(f.facingDirection)??"bottom";t.schematic_net_label.insert({text:e.props.schDisplayLabel??S,source_net_id:f.source_port_id,anchor_position:h,center:Ka({anchor_position:h,anchor_side:E,text:e.props.schDisplayLabel??S}),anchor_side:E})}if(!_){let E=Of(u.facingDirection)??"bottom";t.schematic_net_label.insert({text:e.props.schDisplayLabel??S,source_net_id:u.source_port_id,anchor_position:l,center:Ka({anchor_position:l,anchor_side:E,text:e.props.schDisplayLabel??S}),anchor_side:E})}}function yvt(e){let{_parsedProps:t,parent:n}=e;if(!n)throw new Error("Trace has no parent");let r=e.getTracePortPathSelectors().map(o=>({selector:o,port:e.getSubcircuit().selectOne(o,{type:"port"})??null}));for(let{selector:o,port:s}of r)if(!s){let a,c,l=o.lastIndexOf(".");if(l!==-1&&l>o.lastIndexOf(" "))a=o.slice(0,l),c=o.slice(l+1);else{let E=o.match(/^(.*[ >])?([^ >]+)$/);a=E?.[1]?.trim()??"",c=E?.[2]??o}let u=a?e.getSubcircuit().selectOne(a):null;if(!u&&a&&!/[.#\[]/.test(a)&&(u=e.getSubcircuit().selectOne(`.${a}`)),!u){let E=a?`Could not find port for selector "${o}". Component "${a}" not found`:`Could not find port for selector "${o}"`,R=e.getSubcircuit(),I=R.getGroup();throw new kx({error_type:"source_trace_not_connected_error",message:E,subcircuit_id:R.subcircuit_id??void 0,source_group_id:I?.source_group_id??void 0,source_trace_id:e.source_trace_id??void 0,selectors_not_found:[o]})}let h=u.children.filter(E=>E.componentName==="Port"),f=c.includes(".")?c.split(".").pop()??"":c,_=h.flatMap(E=>E.getNameAndAliases()),y=_.some(E=>!/^(pin\d+|\d+)$/.test(E)),x=Array.from(new Set(_)).join(", "),v;h.length===0?v="It has no ports":y?v=`It has [${x}]`:v=`It has ${h.length} pins and no pinLabels (consider adding pinLabels)`;let w=`Could not find port for selector "${o}". Component "${u.props.name??a}" found, but does not have pin "${f}". ${v}`,S=e.getSubcircuit(),C=S.getGroup();throw new kx({error_type:"source_trace_not_connected_error",message:w,subcircuit_id:S.subcircuit_id??void 0,source_group_id:C?.source_group_id??void 0,source_trace_id:e.source_trace_id??void 0,selectors_not_found:[o]})}return r.some(o=>!o.port)?{allPortsFound:!1}:{allPortsFound:!0,portsWithSelectors:r,ports:r.map(({port:o})=>o)}}var yo=class extends Ie{constructor(t){super(t);T(this,"source_trace_id",null);T(this,"pcb_trace_id",null);T(this,"schematic_trace_id",null);T(this,"_portsRoutedOnPcb");T(this,"subcircuit_connectivity_map_key",null);T(this,"_traceConnectionHash",null);T(this,"_couldNotFindPort");this._portsRoutedOnPcb=[]}get config(){return{zodProps:CL,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 yvt(this)}_resolveNet(t){let n=this.getSubcircuit().selectOne(t,{type:"net"});if(n)return n;let i=t.match(/^net\.(.+)$/),r=i?i[1]:null;return r&&this.root._getBoard().getDescendants().find(s=>s.componentName==="Net"&&s._parsedProps.name===r)||null}_findConnectedNets(){let t=this.getTracePathNetSelectors().map(i=>({selector:i,net:this._resolveNet(i)})),n=t.filter(i=>!i.net);return n.length>0&&this.renderError(`Could not find net for selector "${n[0].selector}" inside ${this}`),{netsWithSelectors:t,nets:t.map(i=>i.net)}}_getAllTracesConnectedToSameNet(){let t=this.getSubcircuit().selectAll("trace"),n=this._findConnectedNets().nets,i=this._findConnectedPorts().ports??[];return t.filter(r=>{if(r===this)return!1;let o=r._findConnectedNets().nets,s=r._findConnectedPorts().ports??[];return o.some(a=>n.includes(a))||s.some(a=>i.includes(a))})}_isExplicitlyConnectedToPort(t){let{allPortsFound:n,portsWithSelectors:i}=this._findConnectedPorts();return n?i.map(o=>o.port).includes(t):!1}_isExplicitlyConnectedToNet(t){return this._findConnectedNets().nets.includes(t)}doInitialCreateNetsFromProps(){cI(this,this.getTracePathNetSelectors())}_computeTraceConnectionHash(){let{allPortsFound:t,ports:n}=this._findConnectedPorts();return!t||!n?null:[...n].sort((o,s)=>(o.pcb_port_id||"").localeCompare(s.pcb_port_id||"")).map(o=>o.pcb_port_id).join(",")}doInitialSourceTraceRender(){let{db:t}=this.root,{_parsedProps:n,parent:i}=this;if(!i){this.renderError("Trace has no parent");return}let r,o;try{let h=this._findConnectedPorts();r=h.allPortsFound,o=h.portsWithSelectors??[]}catch(h){if(h instanceof kx){t.source_trace_not_connected_error.insert({...h.errorData,error_type:"source_trace_not_connected_error"}),this._couldNotFindPort=!0;return}throw h}if(!r)return;this._traceConnectionHash=this._computeTraceConnectionHash();let a=t.source_trace.list().find(h=>h.subcircuit_connectivity_map_key===this.subcircuit_connectivity_map_key&&h.connected_source_port_ids.sort().join(",")===this._traceConnectionHash);if(a){this.source_trace_id=a.source_trace_id;return}let c=this._findConnectedNets().nets,l=tvt({ports:o,nets:c}),u=t.source_trace.insert({connected_source_port_ids:o.map(h=>h.port.source_port_id),connected_source_net_ids:c.map(h=>h.source_net_id),subcircuit_id:this.getSubcircuit()?.subcircuit_id,max_length:Q2t(o.map(h=>h.port),{db:t})??n.maxLength,display_name:l,min_trace_thickness:n.thickness});this.source_trace_id=u.source_trace_id}_insertErrorIfTraceIsOutsideBoard(t,n){let{db:i}=this.root;evt(t,{db:i})&&i.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:this.source_trace_id,message:`Trace ${this.getString()} routed outside the board boundaries.`,pcb_trace_id:this.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:n.map(o=>o.pcb_port_id)})}doInitialPcbManualTraceRender(){mvt(this)}doInitialPcbTraceRender(){fvt(this)}_doInitialSchematicTraceRenderWithDisplayLabel(){_vt(this)}_isSymbolToChipConnection(){let{allPortsFound:t,ports:n}=this._findConnectedPorts();if(!t||n.length!==2)return!1;let[i,r]=n;if(!i?.parent||!r?.parent)return!1;let o=i.parent.config.shouldRenderAsSchematicBox,s=r.parent.config.shouldRenderAsSchematicBox;return o&&!s||!o&&s}_isSymbolToSymbolConnection(){let{allPortsFound:t,ports:n}=this._findConnectedPorts();if(!t||n.length!==2)return!1;let[i,r]=n;if(!i?.parent||!r?.parent)return!1;let o=!i.parent.config.shouldRenderAsSchematicBox,s=!r.parent.config.shouldRenderAsSchematicBox;return o&&s}_isChipToChipConnection(){let{allPortsFound:t,ports:n}=this._findConnectedPorts();if(!t||n.length!==2)return!1;let[i,r]=n;if(!i?.parent||!r?.parent)return!1;let o=i.parent.config.shouldRenderAsSchematicBox,s=r.parent.config.shouldRenderAsSchematicBox;return o&&s}doInitialSchematicTraceRender(){hvt(this)}},gvt=e=>{let{db:t}=e.root;if(e.pcb_component_id){let n=t.pcb_component.get(e.pcb_component_id);return n?{width:n.width,height:n.height}:null}if(e.pcb_group_id){let n=t.pcb_group.get(e.pcb_group_id);return n?{width:n.width,height:n.height}:null}return null},xvt=(e,t)=>{let{db:n}=e.root,i=n.toArray();if(e.pcb_component_id){ag(i,e.pcb_component_id,t);return}if(e.source_group_id){cg(i,e.source_group_id,t);return}throw new Error(`Cannot reposition component ${e.getString()}: no pcb_component_id or source_group_id`)},bvt=e=>{let{db:t}=e.root;if(!e.source_component_id)return;let n=e.selectAll("port"),i=t.source_trace.list(),r=new Set;for(let s of i)for(let a of s.connected_source_port_ids)r.add(a);let o=e._getInternallyConnectedPins();for(let s of o)if(s.some(a=>a.source_port_id&&r.has(a.source_port_id)))for(let a of s)a.source_port_id&&r.add(a.source_port_id);for(let s of n)s.source_port_id&&vvt(e,s)&&(r.has(s.source_port_id)||t.source_pin_missing_trace_warning.insert({message:`Port ${s.getNameAndAliases()[0]} on ${e.props.name} is missing a trace`,source_component_id:e.source_component_id,source_port_id:s.source_port_id,subcircuit_id:e.getSubcircuit().subcircuit_id??void 0,warning_type:"source_pin_missing_trace_warning"}))},vvt=(e,t)=>{if(e.config.componentName==="Chip"){let n=e.props.pinAttributes;if(!n)return!1;for(let i of t.getNameAndAliases()){let r=n[i];if(r?.requiresPower||r?.requiresGround||r?.requiresVoltage!==void 0)return!0}return!1}return!0};function wvt(e){let t=e.font_size,n=e.text.length*t*.6,i=t,r=e.anchor_alignment||"center",o=e.anchor_position.x,s=e.anchor_position.y;switch(r){case"top_left":o=e.anchor_position.x+n/2,s=e.anchor_position.y+i/2;break;case"top_center":o=e.anchor_position.x,s=e.anchor_position.y+i/2;break;case"top_right":o=e.anchor_position.x-n/2,s=e.anchor_position.y+i/2;break;case"center_left":o=e.anchor_position.x+n/2,s=e.anchor_position.y;break;case"center":o=e.anchor_position.x,s=e.anchor_position.y;break;case"center_right":o=e.anchor_position.x-n/2,s=e.anchor_position.y;break;case"bottom_left":o=e.anchor_position.x+n/2,s=e.anchor_position.y-i/2;break;case"bottom_center":o=e.anchor_position.x,s=e.anchor_position.y-i/2;break;case"bottom_right":o=e.anchor_position.x-n/2,s=e.anchor_position.y-i/2;break;default:o=e.anchor_position.x,s=e.anchor_position.y;break}return{x:o-n/2,y:s-i/2,width:n,height:i}}function Svt(e){if(!e._adjustSilkscreenTextAutomatically||e.root?.pcbDisabled||!e.pcb_component_id)return;let{db:t}=e.root,i=e._getPcbCircuitJsonBounds().center,r=t.pcb_silkscreen_text.list({pcb_component_id:e.pcb_component_id}).filter(c=>c.text===e.name);if(r.length===0)return;let a=e.getSubcircuit().selectAll("[_isNormalComponent=true]").filter(c=>c!==e&&c.pcb_component_id).map(c=>{let l=c._getPcbCircuitJsonBounds(),u={center:l.center,width:l.width,height:l.height};return Ts(u)});for(let c of r){let l=c.anchor_position,u=wvt(c),h={center:{x:u.x+u.width/2,y:u.y+u.height/2},width:u.width,height:u.height},f=Ts(h);if(!a.some(C=>Ed(f,C)))continue;let y=2*i.x-l.x,x=2*i.y-l.y,v={center:{x:y,y:x},width:u.width,height:u.height},w=Ts(v);a.some(C=>Ed(w,C))||t.pcb_silkscreen_text.update(c.pcb_silkscreen_text_id,{anchor_position:{x:y,y:x}})}}function Pvt(e){if(!e)return{validPinLabels:e,invalidPinLabelsMessages:[]};let t={},n=[];for(let[i,r]of Object.entries(e)){let o=Array.isArray(r)?r.slice():[r],s=[];for(let a of o)Tvt(i,a)?s.push(a):n.push(`Invalid pin label: ${i} = '${a}' - excluding from component. Please use a valid pin label.`);s.length>0&&(t[i]=Array.isArray(r)?s:s[0])}return{validPinLabels:Object.keys(t).length>0?t:void 0,invalidPinLabelsMessages:n}}function Tvt(e,t){try{let n={name:"test",footprint:"test",pinLabels:{[e]:t}};return lp.safeParse(n).success}catch{return!1}}var Lf=e=>e.startsWith("http://")||e.startsWith("https://"),nI=e=>{if(Lf(e))return null;let t=e.indexOf(":");if(t<=0)return null;let n=e.slice(0,t),i=e.slice(t+1);return!n||!i?null:{footprintLib:n,footprintName:i}},Ivt=e=>e?e.split("?")[0].split(".").pop():null;function Mvt(e,t){let{footprint:n}=e.props;if(n??(n=e._getImpliedFootprintString?.()),!n)return;let{pcbRotation:i,pinLabels:r,pcbPinLabels:o}=e.props,s=Ivt(String(n)),a=s?e.root?.platform?.footprintFileParserMap?.[s]:null;if(typeof n=="string"&&Lf(n)&&a){if(e._hasStartedFootprintUrlLoad)return;e._hasStartedFootprintUrlLoad=!0;let c=n;t("load-footprint-from-platform-file-parser",async()=>{try{let l=await a.loadFromUrl(c),u=Ef({componentName:e.name,componentRotation:i,footprint:c,pinLabels:r,pcbPinLabels:o},l.footprintCircuitJson);e.addAll(u),e._markDirty("InitializePortsFromChildren")}catch(l){let u=e.root?.db;if(u&&e.source_component_id&&e.pcb_component_id){let h=e.getSubcircuit(),f=`${e.getString()} failed to load footprint "${c}": `+(l instanceof Error?l.message:String(l)),_=Xu.parse({type:"external_footprint_load_error",message:f,pcb_component_id:e.pcb_component_id,source_component_id:e.source_component_id,subcircuit_id:h.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0,footprinter_string:c});u.external_footprint_load_error.insert(_)}throw l}});return}if(typeof n=="string"&&Lf(n)){if(e._hasStartedFootprintUrlLoad)return;e._hasStartedFootprintUrlLoad=!0;let c=n;t("load-footprint-url",async()=>{try{let l=await fetch(c);if(!l.ok)throw new Error(`Failed to fetch footprint: ${l.status}`);let u=await l.json(),h=Ef({componentName:e.name,componentRotation:i,footprint:c,pinLabels:r,pcbPinLabels:o},u);e.addAll(h),e._markDirty("InitializePortsFromChildren")}catch(l){let u=e.root?.db;if(u&&e.source_component_id&&e.pcb_component_id){let h=e.getSubcircuit(),f=`${e.getString()} failed to load external footprint "${c}": `+(l instanceof Error?l.message:String(l)),_=Xu.parse({type:"external_footprint_load_error",message:f,pcb_component_id:e.pcb_component_id,source_component_id:e.source_component_id,subcircuit_id:h.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0,footprinter_string:c});u.external_footprint_load_error.insert(_)}throw l}});return}if(typeof n=="string"){let c=nI(n);if(!c||e._hasStartedFootprintUrlLoad)return;e._hasStartedFootprintUrlLoad=!0;let u=e.root?.platform?.footprintLibraryMap?.[c.footprintLib],h;if(typeof u=="function"&&(h=u),!h)return;t("load-lib-footprint",async()=>{try{let f=await h(c.footprintName),_=null;if(Array.isArray(f)?_=f:Array.isArray(f.footprintCircuitJson)&&(_=f.footprintCircuitJson),!_)return;let y=Ef({componentName:e.name,componentRotation:i,footprint:n,pinLabels:r,pcbPinLabels:o},_);e.addAll(y),!Array.isArray(f)&&f.cadModel&&(e._asyncFootprintCadModel=f.cadModel);for(let x of e.children)x.componentName==="Port"&&x._markDirty?.("PcbPortRender");e._markDirty("InitializePortsFromChildren")}catch(f){let _=e.root?.db;if(_&&e.source_component_id&&e.pcb_component_id){let y=e.getSubcircuit(),x=`${e.getString()} failed to load external footprint "${n}": `+(f instanceof Error?f.message:String(f)),v=Xu.parse({type:"external_footprint_load_error",message:x,pcb_component_id:e.pcb_component_id,source_component_id:e.source_component_id,subcircuit_id:y.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0,footprinter_string:n});_.external_footprint_load_error.insert(v)}throw f}});return}if(!(0,eI.isValidElement)(n)&&n.componentName==="Footprint"&&e.add(n),Array.isArray(n)&&!(0,eI.isValidElement)(n)&&n.length>0){try{let c=Ef({componentName:e.name,componentRotation:i,footprint:"",pinLabels:r,pcbPinLabels:o},n);e.addAll(c)}catch(c){let l=e.root?.db;if(l&&e.source_component_id&&e.pcb_component_id){let u=e.getSubcircuit(),h=`${e.getString()} failed to load json footprint: `+(c instanceof Error?c.message:String(c)),f=C1.parse({type:"circuit_json_footprint_load_error",message:h,pcb_component_id:e.pcb_component_id,source_component_id:e.source_component_id,subcircuit_id:u.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0});l.circuit_json_footprint_load_error.insert(f)}throw c}return}}function Evt(e){if(e.root?.pcbDisabled||!e.pcb_component_id)return;let{pcbX:t,pcbY:n}=e._parsedProps,i=e.props?.pcbPositionAnchor;if(!i||t===void 0&&n===void 0)return;let r=Ox(e.children);if(r.width===0||r.height===0)return;let s={...{x:(r.minX+r.maxX)/2,y:(r.minY+r.maxY)/2}},a=null;if(new Set(["center","top_left","top_center","top_right","center_left","center_right","bottom_left","bottom_center","bottom_right"]).has(i)){let u={left:r.minX,right:r.maxX,top:r.minY,bottom:r.maxY};switch(i){case"center":a=s;break;case"top_left":a={x:u.left,y:u.top};break;case"top_center":a={x:s.x,y:u.top};break;case"top_right":a={x:u.right,y:u.top};break;case"center_left":a={x:u.left,y:s.y};break;case"center_right":a={x:u.right,y:s.y};break;case"bottom_left":a={x:u.left,y:u.bottom};break;case"bottom_center":a={x:s.x,y:u.bottom};break;case"bottom_right":a={x:u.right,y:u.bottom};break}}else try{let u=e.portMap[i];u&&(a=u._getGlobalPcbPositionBeforeLayout())}catch{}if(!a)return;let l={...s};t!==void 0&&(l.x+=t-a.x),n!==void 0&&(l.y+=n-a.y),(Math.abs(l.x-s.x)>1e-6||Math.abs(l.y-s.y)>1e-6)&&e._repositionOnPcb(l)}var Cvt=(0,fY.default)("tscircuit:core"),kvt=p.object({x:Fe,y:Fe,z:Fe}),In=class extends Ie{constructor(t){let n={...t},i=[];if(n.pinLabels&&!Array.isArray(n.pinLabels)){let{validPinLabels:r,invalidPinLabelsMessages:o}=Pvt(n.pinLabels);n.pinLabels=r,i=o}super(n);T(this,"reactSubtrees",[]);T(this,"_impliedFootprint");T(this,"isPrimitiveContainer",!0);T(this,"_isNormalComponent",!0);T(this,"_attributeLowerToCamelNameMap",{_isnormalcomponent:"_isNormalComponent"});T(this,"_asyncSupplierPartNumbers");T(this,"_asyncFootprintCadModel");T(this,"_isCadModelChild");T(this,"pcb_missing_footprint_error_id");T(this,"_hasStartedFootprintUrlLoad",!1);T(this,"_invalidPinLabelMessages",[]);T(this,"_adjustSilkscreenTextAutomatically",!1);this._invalidPinLabelMessages=i,this._addChildrenFromStringFootprint(),this.initPorts()}get defaultInternallyConnectedPinNames(){return[]}get internallyConnectedPinNames(){return(this._parsedProps.internallyConnectedPins??this.defaultInternallyConnectedPinNames).map(n=>n.map(i=>typeof i=="number"?`pin${i}`:i))}doInitialSourceNameDuplicateComponentRemoval(){if(!this.name)return;let t=this.root;if(this.getSubcircuit().selectAll(`.${this.name}`).filter(r=>r!==this&&r._isNormalComponent&&r.renderPhaseStates?.SourceNameDuplicateComponentRemoval?.initialized).length>0){let r=this._getGlobalPcbPositionBeforeLayout(),o=this._getGlobalSchematicPositionBeforeLayout();t.db.source_failed_to_create_component_error.insert({component_name:this.name,error_type:"source_failed_to_create_component_error",message:`Cannot create component "${this.name}": A component with the same name already exists`,pcb_center:r,schematic_center:o}),this.shouldBeRemoved=!0;let s=[...this.children];for(let a of s)this.remove(a)}}initPorts(t={}){if(this.root?.schematicDisabled)return;let{config:n}=this,i=[],r=this._getSchematicPortArrangement();if(r&&!this._parsedProps.pinLabels){for(let l in r){let u=r[l].pins;if(Array.isArray(u))for(let h of u){let f=Rf(h,this._parsedProps.pinLabels);i.push(new Ei({pinNumber:f,aliases:t.additionalAliases?.[`pin${f}`]??[]},{originDescription:`schPortArrangement:${l}`}))}}let a=["left","right","top","bottom"],c=1;for(let l of a){let u=r[`${l}Size`];for(let h=0;h<u;h++)i.push(new Ei({pinNumber:c++,aliases:t.additionalAliases?.[`pin${c}`]??[]},{originDescription:`schPortArrangement:${l}`}))}}let o=this._parsedProps.pinLabels;if(o)for(let[a,c]of Object.entries(o)){a=a.replace("pin","");let l=i.find(f=>f._parsedProps.pinNumber===Number(a)),u=Array.isArray(c)?c[0]:c,h=Array.isArray(c)?c.slice(1):[];l?(l.externallyAddedAliases.push(u,...h),l.props.name=u):(l=new Ei({pinNumber:parseInt(a),name:u,aliases:[...h,...t.additionalAliases?.[`pin${parseInt(a)}`]??[]]},{originDescription:`pinLabels:pin${a}`}),i.push(l))}if(n.schematicSymbolName&&!t.ignoreSymbolPorts){let a=Un[this._getSchematicSymbolNameOrThrow()];if(!a)return;for(let c of a.ports){let l=vY(c.labels);if(!l)continue;let u=i.find(h=>h._parsedProps.pinNumber===Number(l));if(u)u.schematicSymbolPortDef=c;else{let h=Mf(c.labels.concat(t.additionalAliases?.[`pin${l}`]??[]));h&&(h.originDescription=`schematicSymbol:labels[0]:${c.labels[0]}`,h.schematicSymbolPortDef=c,i.push(h))}}this.addAll(i)}if(!this._getSchematicPortArrangement()){let a=this.getPortsFromFootprint(t);for(let c of a)i.some(l=>l.isMatchingAnyOf(c.getNameAndAliases()))||i.push(c)}let s=t.pinCount??this._getPinCount()??0;for(let a=1;a<=s;a++){if(i.find(l=>l._parsedProps.pinNumber===a))continue;if(!r){i.push(new Ei({pinNumber:a,aliases:t.additionalAliases?.[`pin${a}`]??[]}));continue}let c=[...r.leftSide?.pins??[],...r.rightSide?.pins??[],...r.topSide?.pins??[],...r.bottomSide?.pins??[]].map(l=>Rf(l,this._parsedProps.pinLabels));["leftSize","rightSize","topSize","bottomSize","leftPinCount","rightPinCount","topPinCount","bottomPinCount"].some(l=>l in r)&&(c=Array.from({length:this._getPinCount()},(l,u)=>u+1)),c.includes(a)&&i.push(new Ei({pinNumber:a,aliases:t.additionalAliases?.[`pin${a}`]??[]},{originDescription:`notOtherwiseAddedButDeducedFromPinCount:${a}`}))}i.length>0&&this.addAll(i)}_getImpliedFootprintString(){return null}_addChildrenFromStringFootprint(){let{pcbRotation:t,pinLabels:n,pcbPinLabels:i}=this.props,{footprint:r}=this.props;if(r??(r=this._getImpliedFootprintString?.()),!!r&&typeof r=="string"){if(Lf(r)||nI(r))return;let o=$v.string(r).soup(),s=Ef({componentName:this.name??this.componentName,componentRotation:t,footprint:r,pinLabels:n,pcbPinLabels:i},o);this.addAll(s)}}get portMap(){return new Proxy({},{get:(t,n)=>{let i=this.children.find(r=>r.componentName==="Port"&&r.isMatchingNameOrAlias(n));if(!i)throw new Error(`There was an issue finding the port "${n.toString()}" inside of a ${this.componentName} component with name: "${this.props.name}". This is a bug in @tscircuit/core`);return i}})}getInstanceForReactElement(t){for(let n of this.reactSubtrees)if(n.element===t)return n.component;return null}doInitialSourceRender(){let t=this.config.sourceFtype;if(!t)return;let{db:n}=this.root,{_parsedProps:i}=this,r=n.source_component.insert({ftype:t,name:this.name,manufacturer_part_number:i.manufacturerPartNumber??i.mfn,supplier_part_numbers:i.supplierPartNumbers});this.source_component_id=r.source_component_id}doInitialSchematicComponentRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root;if(this._invalidPinLabelMessages?.length&&this.root?.db)for(let o of this._invalidPinLabelMessages){let s="pinLabels",a=o.match(/^Invalid pin label:\s*([^=]+)=\s*'([^']+)'/);a&&(s=`pinLabels['${a[2]}']`),this.root.db.source_property_ignored_warning.insert({source_component_id:this.source_component_id,property_name:s,message:o,error_type:"source_property_ignored_warning"})}let{schematicSymbolName:n}=this.config,{_parsedProps:i}=this;i.symbol&&(0,Za.isValidElement)(i.symbol)?this._doInitialSchematicComponentRenderWithReactSymbol(i.symbol):n?this._doInitialSchematicComponentRenderWithSymbol():this._getSchematicBoxDimensions()&&this._doInitialSchematicComponentRenderWithSchematicBoxDimensions();let r=this.getSubcircuit()?._getSchematicManualPlacementForComponent(this);if(this.schematic_component_id&&(this.props.schX!==void 0||this.props.schY!==void 0)&&r){if(!this.schematic_component_id)return;let o=M1.parse({type:"schematic_manual_edit_conflict_warning",schematic_manual_edit_conflict_warning_id:`schematic_manual_edit_conflict_${this.source_component_id}`,message:`${this.getString()} has both manual placement and prop coordinates. schX and schY will be used. Remove schX/schY or clear the manual placement.`,schematic_component_id:this.schematic_component_id,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id});t.schematic_manual_edit_conflict_warning.insert(o)}}_getSchematicSymbolDisplayValue(){}_getInternallyConnectedPins(){if(this.internallyConnectedPinNames.length===0)return[];let t=[];for(let n of this.internallyConnectedPinNames){let i=[];for(let r of n)i.push(this.portMap[r]);t.push(i)}return t}_doInitialSchematicComponentRenderWithSymbol(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getSchematicSymbolNameOrThrow(),r=Un[i],o=this._getGlobalSchematicPositionBeforeLayout();if(r){let s=t.schematic_component.insert({center:o,size:r.size,source_component_id:this.source_component_id,is_box_with_pins:!0,symbol_name:i,symbol_display_value:this._getSchematicSymbolDisplayValue()});this.schematic_component_id=s.schematic_component_id}}_doInitialSchematicComponentRenderWithReactSymbol(t){if(this.root?.schematicDisabled)return;let{db:n}=this.root,i=this._getGlobalSchematicPositionBeforeLayout(),r=n.schematic_component.insert({center:i,size:{width:0,height:0},source_component_id:this.source_component_id,symbol_display_value:this._getSchematicSymbolDisplayValue(),is_box_with_pins:!1});this.schematic_component_id=r.schematic_component_id,this.add(t)}_doInitialSchematicComponentRenderWithSchematicBoxDimensions(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getSchematicBoxDimensions(),r={};if(Array.isArray(n.pinLabels))n.pinLabels.forEach((_,y)=>{r[String(y+1)]=_});else for(let[_,y]of Object.entries(n.pinLabels??{}))r[_]=Array.isArray(y)?y[0]:y;let o=this._getGlobalSchematicPositionBeforeLayout(),s=this._getSchematicPortArrangement(),a=t.schematic_component.insert({center:o,rotation:n.schRotation??0,size:i.getSize(),port_arrangement:R2t(s),pin_spacing:n.schPinSpacing??.2,pin_styles:N2t(n.schPinStyle,n.pinLabels),port_labels:r,source_component_id:this.source_component_id}),c=s?.topSide!==void 0||s?.bottomSide!==void 0,l=i?.getSize().width,u=i?.getSize().height,h=t.schematic_text.insert({text:n.manufacturerPartNumber??"",schematic_component_id:a.schematic_component_id,anchor:"left",rotation:0,position:{x:c?o.x+(l??0)/2+.1:o.x-(l??0)/2,y:c?o.y+(u??0)/2+.35:o.y-(u??0)/2-.13},color:"#006464",font_size:.18}),f=t.schematic_text.insert({text:n.name??"",schematic_component_id:a.schematic_component_id,anchor:"left",rotation:0,position:{x:c?o.x+(l??0)/2+.1:o.x-(l??0)/2,y:c?o.y+(u??0)/2+.55:o.y+(u??0)/2+.13},color:"#006464",font_size:.18});this.schematic_component_id=a.schematic_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit(),r=this._computePcbGlobalTransformBeforeLayout(),s=fo(r).rotation.angle*180/Math.PI,a=t.pcb_component.insert({center:this._getGlobalPcbPositionBeforeLayout(),width:0,height:0,layer:n.layer??"top",rotation:n.pcbRotation??s,source_component_id:this.source_component_id,subcircuit_id:i.subcircuit_id??void 0,do_not_place:n.doNotPlace??!1,obstructs_within_bounds:n.obstructsWithinBounds??!0});if(!(n.footprint??this._getImpliedFootprintString())&&!this.isGroup){let u=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=u.pcb_missing_footprint_error_id}this.pcb_component_id=a.pcb_component_id;let l=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if((this.props.pcbX!==void 0||this.props.pcbY!==void 0)&&l){let u=k1.parse({type:"pcb_manual_edit_conflict_warning",pcb_manual_edit_conflict_warning_id:`pcb_manual_edit_conflict_${this.source_component_id}`,message:`${this.getString()} has both manual placement and prop coordinates. pcbX and pcbY will be used. Remove pcbX/pcbY or clear the manual placement.`,pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,subcircuit_id:i.subcircuit_id??void 0});t.pcb_manual_edit_conflict_warning.insert(u)}}doInitialPcbComponentSizeCalculation(){if(this.root?.pcbDisabled||!this.pcb_component_id)return;let{db:t}=this.root,{_parsedProps:n}=this,i=Ox(this.children);if(i.width===0||i.height===0)return;let r={x:(i.minX+i.maxX)/2,y:(i.minY+i.maxY)/2};t.pcb_component.update(this.pcb_component_id,{center:r,width:i.width,height:i.height})}updatePcbComponentSizeCalculation(){this.doInitialPcbComponentSizeCalculation()}doInitialSchematicComponentSizeCalculation(){if(this.root?.schematicDisabled||!this.schematic_component_id)return;let{db:t}=this.root;if(!t.schematic_component.get(this.schematic_component_id))return;let i=[],r=c=>{for(let l of c){if(l.isSchematicPrimitive&&l.componentName==="SchematicLine"){let u=t.schematic_line.get(l.schematic_line_id);u&&i.push(u)}if(l.isSchematicPrimitive&&l.componentName==="SchematicRect"){let u=t.schematic_rect.get(l.schematic_rect_id);u&&i.push(u)}if(l.isSchematicPrimitive&&l.componentName==="SchematicCircle"){let u=t.schematic_circle.get(l.schematic_circle_id);u&&i.push(u)}if(l.isSchematicPrimitive&&l.componentName==="SchematicArc"){let u=t.schematic_arc.get(l.schematic_arc_id);u&&i.push(u)}if(l.isSchematicPrimitive&&l.componentName==="SchematicText"){let u=t.schematic_text.get(l.schematic_text_id);u&&i.push(u)}l.children&&l.children.length>0&&r(l.children)}};if(r(this.children),i.length===0)return;let o=bY(i),s=Math.abs(o.maxX-o.minX),a=Math.abs(o.maxY-o.minY);s===0&&a===0||t.schematic_component.update(this.schematic_component_id,{size:{width:s,height:a}})}updateSchematicComponentSizeCalculation(){this.doInitialSchematicComponentSizeCalculation()}doInitialPcbComponentAnchorAlignment(){Evt(this)}updatePcbComponentAnchorAlignment(){this.doInitialPcbComponentAnchorAlignment()}_renderReactSubtree(t){let n=gY(t);return{element:t,component:n}}doInitialInitializePortsFromChildren(){this.initPorts()}doInitialReactSubtreesRender(){let t=this.props.footprint;(0,Za.isValidElement)(t)&&(this.children.some(r=>r.componentName==="Footprint")||this.add(t));let n=this.props.cadModel;if((0,Za.isValidElement)(n)){this._isCadModelChild=!0;let i=this.children.some(o=>o.componentName==="CadAssembly"),r=this.children.some(o=>o.componentName==="CadModel");!i&&!r&&this.add(n)}}doInitialPcbFootprintStringRender(){Mvt(this,(t,n)=>this._queueAsyncEffect(t,n))}_hasExistingPortExactly(t){return this.children.filter(i=>i.componentName==="Port").some(i=>{let r=t.getNameAndAliases(),o=i.getNameAndAliases();return r.length===o.length&&r.every(s=>o.includes(s))})}add(t){let n;if((0,Za.isValidElement)(t)){let i=this._renderReactSubtree(t);this.reactSubtrees.push(i),n=i.component}else n=t;if(n.componentName==="Port"){if(this._hasExistingPortExactly(n))return;let r=this.children.filter(o=>o.componentName==="Port").find(o=>o.isMatchingAnyOf(n.getNameAndAliases()));r&&Cvt(`Similar ports added. Port 1: ${r}, Port 2: ${n}`)}super.add(n)}getPortsFromFootprint(t){let{footprint:n}=this.props;if((!n||(0,Za.isValidElement)(n))&&(n=this.children.find(r=>r.componentName==="Footprint")),typeof n=="string"){if(Lf(n))return[];if(nI(n))return[];let r=$v.string(n).soup(),o=[];for(let s of r)if("port_hints"in s&&s.port_hints){let a=Mf(s.port_hints,t);if(!a)continue;a.originDescription=`footprint:string:${n}:port_hints[0]:${s.port_hints[0]}`,o.push(a)}return o}if(!(0,Za.isValidElement)(n)&&n&&n.componentName==="Footprint"){let r=n,o=1,s=[];for(let a of r.children){if(!a.props.portHints)continue;let c=a.props.portHints;c.some(h=>h.startsWith("pin"))||(c=[...c,`pin${o}`]),o++;let u=Mf(c);u&&(u.originDescription=`footprint:${n}`,s.push(u))}return s}let i=[];if(!n){for(let r of this.children)if(r.props.portHints&&r.isPcbPrimitive){let o=Mf(r.props.portHints);o&&i.push(o)}}return i}getPortsFromSchematicSymbol(){if(this.root?.schematicDisabled)return[];let{config:t}=this;if(!t.schematicSymbolName)return[];let n=Un[t.schematicSymbolName];if(!n)return[];let i=[];for(let r of n.ports){let o=Mf(r.labels);o&&(o.schematicSymbolPortDef=r,i.push(o))}return i}doInitialCreateNetsFromProps(){this._createNetsFromProps(this._getNetsFromConnectionsProp())}_getNetsFromConnectionsProp(){let{_parsedProps:t}=this,n=[];if(t.connections)for(let[i,r]of Object.entries(t.connections)){let o=Array.isArray(r)?r:[r];for(let s of o)n.push(s)}return n}_createNetsFromProps(t){cI(this,t)}_getPcbCircuitJsonBounds(){let{db:t}=this.root;if(!this.pcb_component_id)return super._getPcbCircuitJsonBounds();let n=t.pcb_component.get(this.pcb_component_id);return{center:{x:n.center.x,y:n.center.y},bounds:{left:n.center.x-n.width/2,top:n.center.y-n.height/2,right:n.center.x+n.width/2,bottom:n.center.y+n.height/2},width:n.width,height:n.height}}_getPinCountFromSchematicPortArrangement(){let t=this._getSchematicPortArrangement();if(!t)return 0;if(!wY(t))return(t.leftSize??t.leftPinCount??0)+(t.rightSize??t.rightPinCount??0)+(t.topSize??t.topPinCount??0)+(t.bottomSize??t.bottomPinCount??0);let{leftSide:i,rightSide:r,topSide:o,bottomSide:s}=t;return Math.max(...i?.pins??[],...r?.pins??[],...o?.pins??[],...s?.pins??[])}_getPinCount(){if(this._getSchematicPortArrangement())return this._getPinCountFromSchematicPortArrangement();let n=this.getPortsFromFootprint();if(n.length>0)return n.length;let{pinLabels:i}=this._parsedProps;if(i){if(Array.isArray(i))return i.length;let r=Object.keys(i).map(o=>o.startsWith("pin")?parseInt(o.slice(3)):parseInt(o)).filter(o=>!Number.isNaN(o));return r.length>0?Math.max(...r):Object.keys(i).length}return 0}_getSchematicPortArrangement(){return this._parsedProps.schPinArrangement??this._parsedProps.schPortArrangement}_getSchematicBoxDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;let{_parsedProps:t}=this,n=this._getPinCount(),i=t.schPinSpacing??.2;return V2t({schWidth:t.schWidth,schHeight:t.schHeight,schPinSpacing:i,numericSchPinStyle:G2t(t.schPinStyle,t.pinLabels),pinCount:n,schPortArrangement:this._getSchematicPortArrangement(),pinLabels:t.pinLabels})}doInitialCadModelRender(){if(this._isCadModelChild)return;let{db:t}=this.root,{boardThickness:n=0}=this.root?._getBoard()??{},i=this._parsedProps.cadModel,r=i===void 0?this._asyncFootprintCadModel:i,o=this.props.footprint??this._getImpliedFootprintString();if(!this.pcb_component_id||!r&&!o||r===null)return;let s=this._getPcbCircuitJsonBounds(),a=t.pcb_component.get(this.pcb_component_id);if(typeof r=="string")throw new Error("String cadModel not yet implemented");let c=kvt.parse({x:0,y:0,z:typeof r?.rotationOffset=="number"?r.rotationOffset:0,...typeof r?.rotationOffset=="object"?r.rotationOffset??{}:{}}),l=Xc.parse({x:0,y:0,z:0,...typeof r?.positionOffset=="object"?r.positionOffset:{}}),u=this.props.layer==="bottom"?"bottom":"top",h=this._computePcbGlobalTransformBeforeLayout(),_=fo(h).rotation.angle*180/Math.PI,y=t.cad_component.insert({position:{x:s.center.x+l.x,y:s.center.y+l.y,z:(u==="bottom"?-n/2:n/2)+l.z},rotation:{x:c.x,y:(u==="top"?0:180)+c.y,z:u==="bottom"?-(_+c.z)+180:_+c.z},pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,model_stl_url:"stlUrl"in(r??{})?this._addCachebustToModelUrl(r.stlUrl):void 0,model_obj_url:"objUrl"in(r??{})?this._addCachebustToModelUrl(r.objUrl):void 0,model_mtl_url:"mtlUrl"in(r??{})?this._addCachebustToModelUrl(r.mtlUrl):void 0,model_gltf_url:"gltfUrl"in(r??{})?this._addCachebustToModelUrl(r.gltfUrl):void 0,model_glb_url:"glbUrl"in(r??{})?this._addCachebustToModelUrl(r.glbUrl):void 0,model_step_url:"stepUrl"in(r??{})?this._addCachebustToModelUrl(r.stepUrl):void 0,model_wrl_url:"wrlUrl"in(r??{})?this._addCachebustToModelUrl(r.wrlUrl):void 0,model_jscad:"jscad"in(r??{})?r.jscad:void 0,model_unit_to_mm_scale_factor:typeof r?.modelUnitToMmScale=="number"?r.modelUnitToMmScale:void 0,footprinter_string:typeof o=="string"&&!r?o:void 0});this.cad_component_id=y.cad_component_id}_addCachebustToModelUrl(t){if(!t||!t.includes("modelcdn.tscircuit.com"))return t;let n=this.root?.getClientOrigin()??"";return`${t}${t.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(n)}`}_getPartsEngineCacheKey(t,n){return JSON.stringify({ftype:t.ftype,name:t.name,manufacturer_part_number:t.manufacturer_part_number,footprinterString:n})}async _getSupplierPartNumbers(t,n,i){if(this.props.doNotPlace)return{};let r=this.root?.platform?.localCacheEngine,o=this._getPartsEngineCacheKey(n,i);if(r){let c=await r.getItem(o);if(c)try{return JSON.parse(c)}catch{}}let s=await Promise.resolve(t.findPart({sourceComponent:n,footprinterString:i})),a=s==="Not found"?{}:s;if(r)try{await r.setItem(o,JSON.stringify(a))}catch{}return a}doInitialPartsEngineRender(){if(this.props.doNotPlace)return;let t=this.getInheritedProperty("partsEngine");if(!t)return;let{db:n}=this.root,i=n.source_component.get(this.source_component_id);if(!i||i.supplier_part_numbers)return;let r;this.props.footprint&&typeof this.props.footprint=="string"&&(r=this.props.footprint);let o=this._getSupplierPartNumbers(t,i,r);if(!(o instanceof Promise)){n.source_component.update(this.source_component_id,{supplier_part_numbers:o});return}this._queueAsyncEffect("get-supplier-part-numbers",async()=>{this._asyncSupplierPartNumbers=await o,this._markDirty("PartsEngineRender")})}updatePartsEngineRender(){if(this.props.doNotPlace)return;let{db:t}=this.root,n=t.source_component.get(this.source_component_id);if(n&&!n.supplier_part_numbers&&this._asyncSupplierPartNumbers){t.source_component.update(this.source_component_id,{supplier_part_numbers:this._asyncSupplierPartNumbers});return}}doInitialAssignFallbackProps(){let{_parsedProps:t}=this;t.connections&&!this.name&&(this.fallbackUnassignedName=this.getSubcircuit().getNextAvailableName(this))}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}_createTracesFromConnectionsProp(){let{_parsedProps:t}=this;if(t.connections)for(let[n,i]of Object.entries(t.connections)){let r=Array.isArray(i)?i:[i];for(let o of r)this.add(new yo({from:`${this.getSubcircuitSelector()} > port.${n}`,to:o}))}}doInitialSourceDesignRuleChecks(){bvt(this)}_getMinimumFlexContainerSize(){return gvt(this)}_repositionOnPcb(t){return xvt(this,t)}doInitialSilkscreenOverlapAdjustment(){return Svt(this)}},Avt=class{constructor(e,t={}){T(this,"input");T(this,"isRouting",!1);T(this,"solver");T(this,"eventHandlers",{complete:[],error:[],progress:[]});T(this,"cycleCount",0);T(this,"stepDelay");T(this,"timeoutId");this.input=e;let{capacityDepth:n,targetMinCapacity:i,stepDelay:r=0}=t;this.solver=new $z(e,{capacityDepth:n,targetMinCapacity:i,cacheProvider:null}),this.stepDelay=r}start(){this.isRouting||(this.isRouting=!0,this.cycleCount=0,this.runCycleAndQueueNextCycle())}runCycleAndQueueNextCycle(){if(this.isRouting)try{if(this.solver.solved||this.solver.failed){this.solver.failed?this.emitEvent({type:"error",error:new Cf(this.solver.error||"Routing failed")}):this.emitEvent({type:"complete",traces:this.solver.getOutputSimpleRouteJson().traces||[]}),this.isRouting=!1;return}let e=Date.now(),t=this.solver.iterations;for(;Date.now()-e<250&&!this.solver.failed&&!this.solver.solved;)this.solver.step();let n=(this.solver.iterations-t)/(Date.now()-e)*1e3;this.cycleCount++;let i=this.solver?.preview()||void 0,r=this.solver.progress;this.emitEvent({type:"progress",steps:this.cycleCount,iterationsPerSecond:n,progress:r,phase:this.solver.getCurrentPhase(),debugGraphics:i}),this.stepDelay>0?this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),this.stepDelay):this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),0)}catch(e){this.emitEvent({type:"error",error:e instanceof Error?new Cf(e.message):new Cf(String(e))}),this.isRouting=!1}}stop(){this.isRouting&&(this.isRouting=!1,this.timeoutId!==void 0&&(clearTimeout(this.timeoutId),this.timeoutId=void 0))}on(e,t){e==="complete"?this.eventHandlers.complete.push(t):e==="error"?this.eventHandlers.error.push(t):e==="progress"&&this.eventHandlers.progress.push(t)}emitEvent(e){if(e.type==="complete")for(let t of this.eventHandlers.complete)t(e);else if(e.type==="error")for(let t of this.eventHandlers.error)t(e);else if(e.type==="progress")for(let t of this.eventHandlers.progress)t(e)}solveSync(){if(this.solver.solve(),this.solver.failed)throw new Cf(this.solver.error||"Routing failed");return this.solver.getOutputSimpleRouteJson().traces||[]}},fI=class extends Ie{constructor(){super(...arguments);T(this,"matchedPort",null)}get config(){return{componentName:"TraceHint",zodProps:fF}}doInitialPortMatching(){let{db:t}=this.root,{_parsedProps:n,parent:i}=this;if(!i)return;if(i.componentName==="Trace"){this.renderError(`Port inference inside trace is not yet supported (${this})`);return}if(!i)throw new Error("TraceHint has no parent");if(!n.for){this.renderError(`TraceHint has no for property (${this})`);return}let r=i.selectOne(n.for,{type:"port"});r||this.renderError(`${this} could not find port for selector "${n.for}"`),this.matchedPort=r,r.registerMatch(this)}getPcbRouteHints(){let{_parsedProps:t}=this,n=t.offset?[t.offset]:t.offsets;if(!n)return[];let i=this._computePcbGlobalTransformBeforeLayout();return n.map(r=>({...kn(i,r),via:r.via,to_layer:r.to_layer,trace_width:r.trace_width}))}doInitialPcbTraceHintRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this;t.pcb_trace_hint.insert({pcb_component_id:this.matchedPort?.pcb_component_id,pcb_port_id:this.matchedPort?.pcb_port_id,route:this.getPcbRouteHints()})}},CY=({circuitJson:e,editEvents:t,manualEditsFile:n})=>{let i={...n,pcb_placements:[...n.pcb_placements??[]]};for(let r of t)if(r.edit_event_type==="edit_pcb_component_location"){let{pcb_component_id:o,new_center:s}=r,a=Me(e).pcb_component.get(o);if(!a)continue;let c=Me(e).source_component.get(a.source_component_id);if(!c)continue;let l=i.pcb_placements?.findIndex(h=>h.selector===c.name),u={selector:c.name,center:s,relative_to:"group_center"};l>=0?i.pcb_placements[l]=u:i.pcb_placements.push(u)}return i},kY=({circuitJson:e,editEvents:t,manualEditsFile:n})=>{let i={...n,schematic_placements:[...n.schematic_placements??[]]};for(let r of t)if(r.edit_event_type==="edit_schematic_component_location"){let{schematic_component_id:o,new_center:s}=r,a=Me(e).schematic_component.get(o);if(!a||!a.source_component_id)continue;let c=Me(e).source_component.get(a.source_component_id);if(!c)continue;let l=i.schematic_placements?.findIndex(h=>h.selector===c.name),u={selector:c.name,center:s,relative_to:"group_center"};l>=0?i.schematic_placements[l]=u:i.schematic_placements.push(u)}return i},Nvt=({circuitJson:e,editEvents:t,manualEditsFile:n})=>{let i=t.filter(s=>s.edit_event_type==="edit_schematic_component_location"),r=t.filter(s=>s.edit_event_type==="edit_pcb_component_location"),o=n;return i.length>0&&(o=kY({circuitJson:e,editEvents:i,manualEditsFile:o})),r.length>0&&(o=CY({circuitJson:e,editEvents:r,manualEditsFile:o})),o},Rvt=(e,t)=>{if(Me(e).pcb_trace_hint.get(t.pcb_trace_hint_id))e=e.map(i=>i.pcb_trace_hint_id===t.pcb_trace_hint_id?{...i,route:t.route}:i);else{let i=Me(e).pcb_port.get(t.pcb_port_id);e=e.filter(r=>!(r.type==="pcb_trace_hint"&&r.pcb_port_id===t.pcb_port_id)).concat([{type:"pcb_trace_hint",pcb_trace_hint_id:t.pcb_trace_hint_id,route:t.route,pcb_port_id:t.pcb_port_id,pcb_component_id:i?.pcb_component_id}])}return e},Ovt=({circuitJson:e,editEvents:t})=>{e=JSON.parse(JSON.stringify(e));for(let n of t)if(n.edit_event_type==="edit_pcb_component_location"){let i=e.find(o=>o.type==="pcb_component"&&o.pcb_component_id===n.pcb_component_id);if((!i||i.center.x!==n.new_center.x||i.center.y!==n.new_center.y)&&n.original_center){let o=fn(n.new_center.x-n.original_center.x,n.new_center.y-n.original_center.y);e=e.map(s=>s.pcb_component_id!==n.pcb_component_id?s:E5(s,o))}}else n.edit_event_type==="edit_schematic_component_location"?e=e.map(i=>i.type==="schematic_component"&&i.schematic_component_id===n.schematic_component_id?{...i,center:n.new_center}:i):n.edit_event_type==="edit_pcb_trace_hint"&&(e=Rvt(e,n));return e},AY=(e,t)=>{let n=e.source_group.list(),i=[],r=o=>{let s=n.filter(a=>a.parent_subcircuit_id===o);for(let a of s)a.subcircuit_id&&(i.push(a.subcircuit_id),r(a.subcircuit_id))};return r(t),i},iI=({db:e,circuitJson:t,subcircuit_id:n,minTraceWidth:i=.1})=>{if(!e&&t&&(e=Me(t)),!e)throw new Error("db or circuitJson is required");let r=e.pcb_trace_hint.list(),o=n?new Set([n]):null;if(n){let k=AY(e,n);for(let M of k)o.add(M)}let s=(t??e.toArray()).filter(k=>!n||"subcircuit_id"in k&&o.has(k.subcircuit_id)),a=e.pcb_board.list()[0];e=Me(s);let c=ar(s),l=hI([...e.pcb_component.list(),...e.pcb_smtpad.list(),...e.pcb_plated_hole.list(),...e.pcb_hole.list(),...e.pcb_via.list(),...e.pcb_cutout.list()].filter(k=>!n||o?.has(k.subcircuit_id)),c);for(let k of l){let M=k.connectedTo.flatMap(A=>c.getIdsConnectedToNet(A));k.connectedTo.push(...M)}let u=l.flatMap(k=>[{x:k.center.x-k.width/2,y:k.center.y-k.height/2},{x:k.center.x+k.width/2,y:k.center.y+k.height/2}]),h;if(a?h={minX:a.center.x-a.width/2,maxX:a.center.x+a.width/2,minY:a.center.y-a.height/2,maxY:a.center.y+a.height/2}:h={minX:Math.min(...u.map(k=>k.x))-1,maxX:Math.max(...u.map(k=>k.x))+1,minY:Math.min(...u.map(k=>k.y))-1,maxY:Math.max(...u.map(k=>k.y))+1},n){let k=e.pcb_group.getWhere({subcircuit_id:n});if(k){let M={minX:k.center.x-k.width/2,maxX:k.center.x+k.width/2,minY:k.center.y-k.height/2,maxY:k.center.y+k.height/2};h={minX:Math.min(h.minX,M.minX),maxX:Math.max(h.maxX,M.maxX),minY:Math.min(h.minY,M.minY),maxY:Math.max(h.maxY,M.maxY)}}}let f=new Set(e.pcb_trace.list().map(k=>k.source_trace_id).filter(k=>!!k)),_=e.source_trace.list().filter(k=>!f.has(k.source_trace_id)).map(k=>{let M=k.connected_source_port_ids.map(W=>{let Q=e.source_port.get(W),J=e.pcb_port.getWhere({source_port_id:W});return{...Q,...J}});if(M.length<2)return null;let[A,L]=M,B=A.layers?.[0]??"top",D=L.layers?.[0]??"top",V=r.filter(W=>W.pcb_port_id===A.pcb_port_id||W.pcb_port_id===L.pcb_port_id),X=[];for(let W of V){let J=e.pcb_port.get(W.pcb_port_id)?.layers?.[0]??"top";for(let _t of W.route)X.push({x:_t.x,y:_t.y,layer:J})}return{name:k.source_trace_id??c.getNetConnectedToId(k.source_trace_id)??"",source_trace_id:k.source_trace_id,pointsToConnect:[{x:A.x,y:A.y,layer:B,pointId:A.pcb_port_id,pcb_port_id:A.pcb_port_id},...X,{x:L.x,y:L.y,layer:D,pointId:L.pcb_port_id,pcb_port_id:L.pcb_port_id}]}}).filter(k=>k!==null),y=new Map(_.map(k=>[k.source_trace_id,k])),x=e.source_net.list().filter(k=>!n||o?.has(k.subcircuit_id)),v=[];for(let k of x){let M=e.source_trace.list().filter(A=>A.connected_source_net_ids?.includes(k.source_net_id));v.push({name:k.source_net_id??c.getNetConnectedToId(k.source_net_id),pointsToConnect:M.flatMap(A=>e.pcb_port.list().filter(B=>A.connected_source_port_ids.includes(B.source_port_id)).map(B=>({x:B.x,y:B.y,layer:B.layers?.[0]??"top",pointId:B.pcb_port_id,pcb_port_id:B.pcb_port_id})))})}let w=e.pcb_breakout_point.list().filter(k=>!n||o?.has(k.subcircuit_id)),S=[],C=new Map;for(let k of w){let M={x:k.x,y:k.y,layer:"top"};if(k.source_trace_id){let A=y.get(k.source_trace_id)??C.get(k.source_trace_id);if(A)A.pointsToConnect.push(M);else{let L={name:k.source_trace_id,source_trace_id:k.source_trace_id,pointsToConnect:[M]};S.push(L),C.set(k.source_trace_id,L)}}else if(k.source_net_id){let A=v.find(L=>L.name===k.source_net_id);A?A.pointsToConnect.push(M):S.push({name:k.source_net_id,pointsToConnect:[M]})}else if(k.source_port_id){let A=e.pcb_port.getWhere({source_port_id:k.source_port_id});A&&S.push({name:k.source_port_id,source_trace_id:void 0,pointsToConnect:[{x:A.x,y:A.y,layer:A.layers?.[0]??"top",pointId:A.pcb_port_id,pcb_port_id:A.pcb_port_id},M]})}}let E=[..._,...v,...S],R=new Map;for(let k of E)for(let M of k.pointsToConnect)M.pointId&&R.set(M.pointId,k);let I=e.pcb_trace.list().filter(k=>!n||o?.has(k.subcircuit_id));for(let k of I){let M=new Set;for(let B of k.route)B.start_pcb_port_id&&M.add(B.start_pcb_port_id),B.end_pcb_port_id&&M.add(B.end_pcb_port_id);if(M.size<2)continue;let A=M.values().next().value;if(!A)continue;let L=R.get(A);L&&[...M].every(B=>R.get(B)===L)&&(L.externallyConnectedPointIds??(L.externallyConnectedPointIds=[]),L.externallyConnectedPointIds.push([...M]))}return{simpleRouteJson:{bounds:h,obstacles:l,connections:E,layerCount:a?.num_layers??2,minTraceWidth:i},connMap:c}},Lvt=e=>{let t={};if(!e)return t;for(let i of Fs)t[i]=0;let n=new Map;for(let i of e){let[,,r,o]=i.type.split(":");if(o==="start"){n.set(`${r}:${i.renderId}`,i);continue}if(o==="end"){let s=n.get(`${r}:${i.renderId}`);if(s){let a=i.createdAt-s.createdAt;t[r]=(t[r]||0)+a}}}return t},Fvt=e=>{let t=e.map(c=>[...new Set(c)]),n=t.map(()=>[]),i=t.map(()=>null);for(let c=0;c<t.length;c++)for(let l of t[c])if(/^\d+$/.test(l)){i[c]=Number.parseInt(l);break}let r=0,o=new Set;for(let c=0;c<i.length;c++){let l=i[c];if(l===null||l<1)continue;if(!o.has(l)){o.add(l),n[c].push(`pin${l}`),r=Math.max(r,l);continue}let u=0;for(let h of n[c])h.startsWith(`pin${l}_alt`)&&u++;n[c].push(`pin${l}_alt${u+1}`)}for(let c=0;c<n.length;c++)n[c][0]?.includes("_alt")&&(r++,n[c].unshift(`pin${r}`));for(let c=0;c<n.length;c++)n[c].length===0&&(r++,n[c].push(`pin${r}`));let s={};for(let c of t)for(let l of c)/^\d+$/.test(l)||(s[l]=(s[l]??0)+1);let a={};for(let c=0;c<t.length;c++){let l=t[c];for(let u of l)/^\d+$/.test(u)||(s[u]===1?n[c].push(u):(a[u]=(a[u]??0)+1,n[c].push(`${u}${a[u]}`)))}return n},tY=(0,NY.default)("Group_doInitialSchematicLayoutMatchAdapt");function zvt(e){let{db:t}=e.root,n=kd(t.toArray(),{source_group_id:e.source_group_id}),i=i4(n);tY.enabled&&global.debugGraphics?.push(Ba(i,{title:`floatingBpcGraph-${e.name}`}));let r=i4(n),o={boxes:r.boxes,pins:r.pins.map(c=>({...c,color:c.color.replace("not_connected","normal")}))},{result:s}=f$([{variantName:"default",floatingGraph:r},{variantName:"noNotConnected",floatingGraph:o}],{singletonKeys:["vcc/2","gnd/2"],centerPinColors:["netlabel_center","component_center"],floatingBoxIdsWithMutablePinOffsets:new Set(r.boxes.filter(c=>r.pins.filter(h=>h.boxId===c.boxId).filter(h=>!h.color.includes("center")).length<=2).map(c=>c.boxId)),corpus:{}});tY.enabled&&global.debugGraphics?.push(Ba(s,{title:`laidOutBpcGraph-${e.name}`}));let a=e._getGlobalSchematicPositionBeforeLayout();for(let c of s.boxes){if(!c.center)continue;let l=t.schematic_component.get(c.boxId);if(l){let h={x:c.center.x+a.x,y:c.center.y+a.y},f=t.schematic_port.list({schematic_component_id:l.schematic_component_id}),_=t.schematic_text.list({schematic_component_id:l.schematic_component_id}),y={x:h.x-l.center.x,y:h.y-l.center.y};for(let x of f)x.center.x+=y.x,x.center.y+=y.y;for(let x of _)x.position.x+=y.x,x.position.y+=y.y;l.center=h;continue}let u=t.schematic_net_label.get(c.boxId);if(u){let h=s.pins.find(_=>_.boxId===c.boxId&&_.color==="netlabel_center");if(!h)throw new Error(`No pin found for net label: ${c.boxId}`);let f={x:c.center.x+a.x,y:c.center.y+a.y};u.center=f,u.anchor_position={x:f.x+h.offset.x,y:f.y+h.offset.y};continue}console.error(`No schematic element found for box: ${c.boxId}. This is a bug in the matchAdapt binding with @tscircuit/core`)}}var ue=(0,RY.default)("Group_doInitialSchematicLayoutMatchpack");function eY(e){switch(e){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:return"y+"}}function nY(e,t){let n=["right","up","left","down"],i=n.indexOf(e);if(i===-1)return e;let r=Math.round(t/90),o=(i+r)%4;return n[o<0?o+4:o]}function Dvt(e,t,n){let i={chipMap:{},chipPinMap:{},netMap:{},pinStrongConnMap:{},netConnMap:{},chipGap:.6,decouplingCapsGap:.4,partitionGap:1.2};ue(`[${n.name}] Processing ${e.childNodes.length} child nodes for input problem`),e.childNodes.forEach((o,s)=>{if(ue(`[${n.name}] Processing child ${s}: nodeType=${o.nodeType}`),o.nodeType==="component"?ue(`[${n.name}] - Component: ${o.sourceComponent?.name}`):o.nodeType==="group"&&ue(`[${n.name}] - Group: ${o.sourceGroup?.name}`),o.nodeType==="component"&&o.sourceComponent){let a=o.sourceComponent.name||`chip_${s}`,c=t.schematic_component.getWhere({source_component_id:o.sourceComponent.source_component_id});if(!c)return;let l=n.children.find(S=>S.source_component_id===o.sourceComponent?.source_component_id),u=[0,90,180,270];l?._parsedProps?.schOrientation&&(u=[0]),l?._parsedProps?.schRotation!==void 0&&(u=[0]);let h=l?._parsedProps?.schMarginLeft??l?._parsedProps?.schMarginX??0,f=l?._parsedProps?.schMarginRight??l?._parsedProps?.schMarginX??0,_=l?._parsedProps?.schMarginTop??l?._parsedProps?.schMarginY??0,y=l?._parsedProps?.schMarginBottom??l?._parsedProps?.schMarginY??0;l?.config.shouldRenderAsSchematicBox&&(_+=.4,y+=.4);let x=(f-h)/2,v=(_-y)/2;i.chipMap[a]={chipId:a,pins:[],size:{x:(c.size?.width||1)+h+f,y:(c.size?.height||1)+_+y},availableRotations:u};let w=t.schematic_port.list({schematic_component_id:c.schematic_component_id});for(let S of w){let C=t.source_port.get(S.source_port_id);if(!C)continue;let E=`${a}.${C.pin_number||C.name||S.schematic_port_id}`;i.chipMap[a].pins.push(E);let R=eY(S.facing_direction);i.chipPinMap[E]={pinId:E,offset:{x:(S.center?.x||0)-(c.center.x||0)+x,y:(S.center?.y||0)-(c.center.y||0)+v},side:R}}}else if(o.nodeType==="group"&&o.sourceGroup){let a=o.sourceGroup.name||`group_${s}`;ue(`[${n.name}] Processing nested group: ${a}`);let c=t.schematic_group?.getWhere?.({source_group_id:o.sourceGroup.source_group_id}),l=n.children.find(u=>u.source_group_id===o.sourceGroup?.source_group_id);if(ue(`[${n.name}] Found schematic_group for ${a}:`,c),c){ue(`[${n.name}] Treating group ${a} as composite chip`);let u=t.schematic_component.list({schematic_group_id:c.schematic_group_id});ue(`[${n.name}] Group ${a} has ${u.length} components:`,u.map(A=>A.source_component_id));let h=1/0,f=-1/0,_=1/0,y=-1/0,x=!1;for(let A of u)if(A.center&&A.size){x=!0;let L=A.size.width/2,B=A.size.height/2;h=Math.min(h,A.center.x-L),f=Math.max(f,A.center.x+L),_=Math.min(_,A.center.y-B),y=Math.max(y,A.center.y+B)}let v=l?._parsedProps?.schMarginLeft??l?._parsedProps?.schMarginX??0,w=l?._parsedProps?.schMarginRight??l?._parsedProps?.schMarginX??0,S=l?._parsedProps?.schMarginTop??l?._parsedProps?.schMarginY??0,C=l?._parsedProps?.schMarginBottom??l?._parsedProps?.schMarginY??0,E=(w-v)/2,R=(S-C)/2,I=(x?f-h:2)+v+w,k=(x?y-_:2)+S+C;ue(`[${n.name}] Group ${a} computed size: ${I} x ${k}`);let M=[];for(let A of u){let L=t.schematic_port.list({schematic_component_id:A.schematic_component_id});for(let B of L){let D=t.source_port.get(B.source_port_id);if(!D)continue;let V=`${a}.${D.pin_number||D.name||B.schematic_port_id}`;M.push(V);let X=c.center||{x:0,y:0},W=eY(B.facing_direction);i.chipPinMap[V]={pinId:V,offset:{x:(B.center?.x||0)-X.x+E,y:(B.center?.y||0)-X.y+R},side:W}}}ue(`[${n.name}] Group ${a} has ${M.length} pins:`,M),i.chipMap[a]={chipId:a,pins:M,size:{x:I,y:k}},ue(`[${n.name}] Added group ${a} to chipMap`)}else ue(`[${n.name}] Warning: No schematic_group found for group ${a}`)}}),ue(`[${n.name}] Creating connections using connectivity keys`);let r=new Map;for(let[o,s]of Object.entries(i.chipMap))for(let a of s.pins){let c=a.split(".").pop(),l=e.childNodes.find(u=>u.nodeType==="component"&&u.sourceComponent?u.sourceComponent.name===o:u.nodeType==="group"&&u.sourceGroup?`group_${e.childNodes.indexOf(u)}`===o:!1);if(l?.nodeType==="group"&&l.sourceGroup){let u=t.schematic_group?.getWhere?.({source_group_id:l.sourceGroup.source_group_id});if(u){let h=t.schematic_component.list({schematic_group_id:u.schematic_group_id});for(let f of h){let _=t.source_port.list({source_component_id:f.source_component_id});for(let y of _){let x=y.pin_number||y.name;if(String(x)===String(c))if(y.subcircuit_connectivity_map_key){let v=y.subcircuit_connectivity_map_key;r.has(v)||r.set(v,[]),r.get(v).push(a),ue(`[${n.name}] \u2713 Pin ${a} has connectivity key: ${v}`)}else ue(`[${n.name}] Pin ${a} has no connectivity key`)}}}}else if(l?.nodeType==="component"&&l.sourceComponent){let u=t.source_port.list({source_component_id:l.sourceComponent.source_component_id});for(let h of u){let f=h.pin_number||h.name;if(String(f)===String(c)&&h.subcircuit_connectivity_map_key){let _=h.subcircuit_connectivity_map_key;r.has(_)||r.set(_,[]),r.get(_).push(a),ue(`[${n.name}] Pin ${a} has connectivity key: ${_}`)}}}}ue(`[${n.name}] Found ${r.size} connectivity groups:`,Array.from(r.entries()).map(([o,s])=>({key:o,pins:s})));for(let[o,s]of r)if(s.length>=2){let a=t.source_trace.list().filter(u=>u.subcircuit_connectivity_map_key===o),c=a.some(u=>u.connected_source_net_ids&&u.connected_source_net_ids.length>0),l=a.some(u=>u.connected_source_port_ids&&u.connected_source_port_ids.length>=2);if(ue(`[${n.name}] Connectivity ${o}: hasNetConnections=${c}, hasDirectConnections=${l}`),l){for(let u of a)if(u.connected_source_port_ids&&u.connected_source_port_ids.length>=2){let h=[];for(let f of u.connected_source_port_ids)for(let _ of s){let y=_.split(".").pop(),x=t.source_port.get(f);if(x&&String(x.pin_number||x.name)===String(y)){let v=_.split(".")[0],w=e.childNodes.find(S=>S.nodeType==="component"&&S.sourceComponent?S.sourceComponent.name===v:S.nodeType==="group"&&S.sourceGroup?`group_${e.childNodes.indexOf(S)}`===v:!1);w?.nodeType==="component"&&w.sourceComponent&&t.source_port.list({source_component_id:w.sourceComponent.source_component_id}).some(C=>C.source_port_id===f)&&h.push(_)}}for(let f=0;f<h.length;f++)for(let _=f+1;_<h.length;_++){let y=h[f],x=h[_];i.pinStrongConnMap[`${y}-${x}`]=!0,i.pinStrongConnMap[`${x}-${y}`]=!0,ue(`[${n.name}] Created strong connection: ${y} <-> ${x}`)}}}if(c){let u=t.source_net.getWhere({subcircuit_connectivity_map_key:o}),h=u?.is_ground??!1,f=u?.is_power??!1;i.netMap[o]={netId:o,isGround:h,isPositiveVoltageSource:f};for(let _ of s)i.netConnMap[`${_}-${o}`]=!0;ue(`[${n.name}] Created net ${o} with ${s.length} pins:`,s)}}return i}function $vt(e){let{db:t}=e.root,n=fp(t.toArray(),{source_group_id:e.source_group_id});if(ue(`[${e.name}] Starting matchpack layout with ${n.childNodes.length} children`),ue(`[${e.name}] Tree structure:`,JSON.stringify(n,null,2)),n.childNodes.length<=1){ue(`[${e.name}] Only ${n.childNodes.length} children, skipping layout`);return}ue("Converting circuit tree to InputProblem...");let i=Dvt(n,t,e);ue.enabled&&e.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`matchpack-input-problem-${e.name}`,content:JSON.stringify(i,null,2)});let r=new yB(i);if(ue("Starting LayoutPipelineSolver..."),ue.enabled&&global.debugGraphics){let c=r.visualize();global.debugGraphics.push({...c,title:`matchpack-initial-${e.name}`})}if(r.solve(),ue(`Solver completed in ${r.iterations} iterations`),ue(`Solved: ${r.solved}, Failed: ${r.failed}`),r.failed)throw ue(`Solver failed with error: ${r.error}`),new Error(`Matchpack layout solver failed: ${r.error}`);let o=r.getOutputLayout();if(ue("OutputLayout:",JSON.stringify(o,null,2)),ue("Solver completed successfully:",!r.failed),ue.enabled&&global.debugGraphics){let c=r.visualize();global.debugGraphics.push({...c,title:`matchpack-final-${e.name}`})}let s=r.checkForOverlaps(o);if(s.length>0){ue(`Warning: Found ${s.length} overlapping components:`);for(let c of s)ue(` ${c.chip1} overlaps ${c.chip2} (area: ${c.overlapArea})`)}let a=e._getGlobalSchematicPositionBeforeLayout();ue(`Group offset: x=${a.x}, y=${a.y}`),ue(`Applying layout results for ${Object.keys(o.chipPlacements).length} chip placements`);for(let[c,l]of Object.entries(o.chipPlacements)){ue(`Processing placement for chip: ${c} at (${l.x}, ${l.y})`);let u=n.childNodes.find(f=>{if(f.nodeType==="component"&&f.sourceComponent){let _=f.sourceComponent.name===c;return ue(` Checking component ${f.sourceComponent.name}: matches=${_}`),_}if(f.nodeType==="group"&&f.sourceGroup){let _=f.sourceGroup.name,y=`group_${n.childNodes.indexOf(f)}`,x=y===c;return ue(` Checking group ${_} (expected chipId: ${y}): matches=${x}`),x}return!1});if(!u){ue(`Warning: No tree node found for chip: ${c}`),ue("Available tree nodes:",n.childNodes.map((f,_)=>({type:f.nodeType,name:f.nodeType==="component"?f.sourceComponent?.name:f.sourceGroup?.name,expectedChipId:f.nodeType==="group"?`group_${_}`:f.sourceComponent?.name})));continue}let h={x:l.x+a.x,y:l.y+a.y};if(u.nodeType==="component"&&u.sourceComponent){let f=t.schematic_component.getWhere({source_component_id:u.sourceComponent.source_component_id});if(f){ue(`Moving component ${c} to (${h.x}, ${h.y})`);let _=t.schematic_port.list({schematic_component_id:f.schematic_component_id}),y=t.schematic_text.list({schematic_component_id:f.schematic_component_id}),x={x:h.x-f.center.x,y:h.y-f.center.y};for(let v of _)v.center.x+=x.x,v.center.y+=x.y;for(let v of y)v.position.x+=x.x,v.position.y+=x.y;if(f.center=h,l.ccwRotationDegrees!==0){ue(`Component ${c} has rotation: ${l.ccwRotationDegrees}\xB0`);let v=l.ccwRotationDegrees*Math.PI/180,w=Math.cos(v),S=Math.sin(v);for(let C of _){let E=C.center.x-h.x,R=C.center.y-h.y,I=E*w-R*S,k=E*S+R*w;C.center.x=h.x+I,C.center.y=h.y+k;let M=C.facing_direction||"right";C.facing_direction=nY(M,l.ccwRotationDegrees)}for(let C of y){let E=C.position.x-h.x,R=C.position.y-h.y,I=E*w-R*S,k=E*S+R*w;C.position.x=h.x+I,C.position.y=h.y+k}if(f.symbol_name){let C=f.symbol_name.match(/_(right|left|up|down)$/);C&&(f.symbol_name=f.symbol_name.replace(C[0],`_${nY(C[1],l.ccwRotationDegrees)}`))}}}}else if(u.nodeType==="group"&&u.sourceGroup){let f=t.schematic_group?.getWhere?.({source_group_id:u.sourceGroup.source_group_id});if(f){ue(`Moving group ${c} to (${h.x}, ${h.y}) from (${f.center?.x}, ${f.center?.y})`);let _=t.schematic_component.list({schematic_group_id:f.schematic_group_id});ue(`Group ${c} has ${_.length} components to move`);let y=f.center||{x:0,y:0},x={x:h.x-y.x,y:h.y-y.y};ue(`Position delta for group ${c}: (${x.x}, ${x.y})`);for(let v of _)if(v.center){let w={...v.center};v.center.x+=x.x,v.center.y+=x.y,ue(`Moved component ${v.source_component_id} from (${w.x}, ${w.y}) to (${v.center.x}, ${v.center.y})`);let S=t.schematic_port.list({schematic_component_id:v.schematic_component_id}),C=t.schematic_text.list({schematic_component_id:v.schematic_component_id});for(let E of S)E.center&&(E.center.x+=x.x,E.center.y+=x.y);for(let E of C)E.position&&(E.position.x+=x.x,E.position.y+=x.y)}f.center=h,ue(`Updated group ${c} center to (${h.x}, ${h.y})`)}}}ue("Matchpack layout completed successfully")}function Bvt(e){if(!e.isSubcircuit)return;let{db:t}=e.root,n=e.selectAll("trace"),i=new bd({});i.addConnections(n.map(a=>{let c=t.source_trace.get(a.source_trace_id);return c?[c.source_trace_id,...c.connected_source_port_ids,...c.connected_source_net_ids]:null}).filter(a=>a!==null));let{name:r}=e._parsedProps;for(let a of n){if(!a.source_trace_id)continue;let c=i.getNetConnectedToId(a.source_trace_id);c&&(a.subcircuit_connectivity_map_key=`${r??`unnamedsubcircuit${e._renderId}`}_${c}`,t.source_trace.update(a.source_trace_id,{subcircuit_connectivity_map_key:a.subcircuit_connectivity_map_key}))}let o=new Set;for(let a of n){if(!a.source_trace_id)continue;let c=t.source_trace.get(a.source_trace_id);if(c)for(let l of c.connected_source_port_ids)o.add(l)}for(let a of o){let c=i.getNetConnectedToId(a);if(!c)continue;let l=`${r??`unnamedsubcircuit${e._renderId}`}_${c}`;t.source_port.update(a,{subcircuit_connectivity_map_key:l})}let s=new Set;for(let a of n){if(!a.source_trace_id)continue;let c=t.source_trace.get(a.source_trace_id);if(c)for(let l of c.connected_source_net_ids)s.add(l)}for(let a of s){let c=i.getNetConnectedToId(a);if(!c)continue;let l=`${r??`unnamedsubcircuit${e._renderId}`}_${c}`;t.source_net.update(a,{subcircuit_connectivity_map_key:l})}}function jvt(e){let{db:t}=e.root,n=e._parsedProps,i=e.children.filter(R=>{let I=R._parsedProps?.schX!==void 0||R._parsedProps?.schY!==void 0;return R.schematic_component_id&&!I});if(i.length===0)return;let r=0,o=0;for(let R of i){let I=t.schematic_component.get(R.schematic_component_id);I?.size&&(r=Math.max(r,I.size.width),o=Math.max(o,I.size.height))}r===0&&i.length>0&&(r=1),o===0&&i.length>0&&(o=1);let s=n.gridCols,a,c=n.gridGap,l=n.gridRowGap,u=n.gridColumnGap;n.schLayout?.grid&&(s=n.schLayout.grid.cols??s,a=n.schLayout.grid.rows,c=n.schLayout.gridGap??c,l=n.schLayout.gridRowGap??l,u=n.schLayout.gridColumnGap??u);let h,f;s!==void 0&&a!==void 0?(h=s,f=a):s!==void 0?(h=s,f=Math.ceil(i.length/h)):a!==void 0?(f=a,h=Math.ceil(i.length/f)):(h=Math.ceil(Math.sqrt(i.length)),f=Math.ceil(i.length/h)),h===0&&i.length>0&&(h=1),f===0&&i.length>0&&(f=i.length);let _,y,x=R=>{if(R!==void 0)return typeof R=="number"?R:$.parse(R)};if(l!==void 0||u!==void 0){let R=typeof c=="object"&&c!==null?c.x:c,I=typeof c=="object"&&c!==null?c.y:c;_=x(u??R)??1,y=x(l??I)??1}else if(typeof c=="number")_=c,y=c;else if(typeof c=="string"){let R=$.parse(c);_=R,y=R}else if(typeof c=="object"&&c!==null){let R=c.x,I=c.y;_=typeof R=="number"?R:$.parse(R??"0mm"),y=typeof I=="number"?I:$.parse(I??"0mm")}else _=1,y=1;let v=h*r+Math.max(0,h-1)*_,w=f*o+Math.max(0,f-1)*y,S=e._getGlobalSchematicPositionBeforeLayout(),C=S.x-v/2+r/2,E=S.y+w/2-o/2;for(let R=0;R<i.length;R++){let I=i[R];if(!I.schematic_component_id)continue;let k=Math.floor(R/h),M=R%h;if(k>=f||M>=h){console.warn(`Schematic grid layout: Child ${I.getString()} at index ${R} (row ${k}, col ${M}) exceeds specified grid dimensions (${f}x${h}). Skipping placement.`);continue}let A=C+M*(r+_),L=E-k*(o+y),B=t.schematic_component.get(I.schematic_component_id);if(B){let D=B.center,V={x:A,y:L};t.schematic_component.update(I.schematic_component_id,{center:V});let X=V.x-D.x,W=V.y-D.y,Q=t.schematic_port.list({schematic_component_id:I.schematic_component_id});for(let _t of Q)t.schematic_port.update(_t.schematic_port_id,{center:{x:_t.center.x+X,y:_t.center.y+W}});let J=t.schematic_text.list({schematic_component_id:I.schematic_component_id});for(let _t of J)t.schematic_text.update(_t.schematic_text_id,{position:{x:_t.position.x+X,y:_t.position.y+W}})}}e.schematic_group_id&&t.schematic_group.update(e.schematic_group_id,{width:v,height:w,center:S})}var iY=(e,t)=>{let{sourceComponent:n,sourceGroup:i}=t;if(t.nodeType==="component"){let r=e.schematic_component.getWhere({source_component_id:n?.source_component_id});return r?.size?{width:r.size.width,height:r.size.height}:null}if(t.nodeType==="group"){let r=e.schematic_group.getWhere({source_group_id:i?.source_group_id});if(r?.width&&r?.height)return{width:r.width,height:r.height};let o=e.schematic_component.list({schematic_group_id:r?.schematic_group_id}),s=1/0,a=-1/0,c=1/0,l=-1/0;for(let f of o)if(f.center&&f.size){let _=f.size.width/2,y=f.size.height/2;s=Math.min(s,f.center.x-_),a=Math.max(a,f.center.x+_),c=Math.min(c,f.center.y-y),l=Math.max(l,f.center.y+y)}let u=a-s,h=l-c;return{width:u,height:h}}return null},Yvt=e=>{let{db:t}=e.root,n=e._parsedProps,i=fp(t.toArray(),{source_group_id:e.source_group_id}),r=n.schJustifyContent??n.justifyContent,o=n.schAlignItems??n.alignItems,s=n.schFlexGap??n.schGap??n.gap,a=n.schFlexDirection??"row",c={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"space-between","space-between":"space-between","space-around":"space-around","space-evenly":"space-evenly",center:"center"}[r??"space-between"],l={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"stretch",center:"center"}[o??"center"];if(!c)throw new Error(`Invalid justifyContent value: "${r}"`);if(!l)throw new Error(`Invalid alignItems value: "${o}"`);let u=0,h=0;typeof s=="object"?(u=s.y??0,h=s.x??0):typeof s=="number"?(u=s,h=s):typeof s=="string"&&(u=$.parse(s),h=$.parse(s));let f,_=n.width??n.schWidth??void 0,y=n.height??n.schHeight??void 0;(_===void 0||y===void 0)&&(f=lg(i.childNodes.map(E=>iY(t,E)).filter(E=>E!==null),{alignItems:l,justifyContent:c,direction:a,rowGap:u,columnGap:h}),_=f.width,y=f.height);let v=new cx(_,y,{alignItems:l,justifyContent:c,direction:a,rowGap:u,columnGap:h});for(let E of i.childNodes){let R=iY(t,E);v.addChild({metadata:E,width:R?.width??0,height:R?.height??0,flexBasis:R?a==="row"?R.width:R.height:void 0})}v.build();let w={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let E of v.children)w.minX=Math.min(w.minX,E.position.x),w.minY=Math.min(w.minY,E.position.y),w.maxX=Math.max(w.maxX,E.position.x+E.size.width),w.maxY=Math.max(w.maxY,E.position.y+E.size.height);w.width=w.maxX-w.minX,w.height=w.maxY-w.minY;let S={x:-(w.maxX+w.minX)/2,y:-(w.maxY+w.minY)/2},C=t.toArray();for(let E of v.children){let{sourceComponent:R,sourceGroup:I}=E.metadata;if(R){let k=t.schematic_component.getWhere({source_component_id:R.source_component_id});if(!k)continue;BF(C,k.schematic_component_id,{x:E.position.x+E.size.width/2+S.x,y:E.position.y+E.size.height/2+S.y})}if(I){if(!t.schematic_group.getWhere({source_group_id:I.source_group_id}))continue;YF(C,I.source_group_id,{x:E.position.x+E.size.width/2+S.x,y:E.position.y+E.size.height/2+S.y})}}e.schematic_group_id&&t.schematic_group.update(e.schematic_group_id,{width:w.width,height:w.height})},UT=1;function Xvt(e){let{db:t}=e.root,n=e._parsedProps,i=Vvt(e);if(i.length===0)return;let r=Hvt({db:t,pcbChildren:i}),o=Gvt(n),s=Uvt({props:n,pcbChildren:i,childDimensions:r,gridConfig:o}),a=Zvt({pcbChildren:i,childDimensions:r,gridLayout:s,gridConfig:o}),{itemCoordinates:c}=a.layout();Kvt({db:t,group:e,pcbChildren:i,itemCoordinates:c,gridLayout:s}),Jvt({db:t,group:e,props:n,gridLayout:s})}function Vvt(e){return e.children.filter(t=>t.pcb_component_id||t.pcb_group_id)}function Hvt(e){let{db:t,pcbChildren:n}=e,i=0,r=0;for(let o of n){let s=0,a=0;if(o.pcb_group_id){let c=t.pcb_group.get(o.pcb_group_id);s=c?.width??0,a=c?.height??0}else if(o.pcb_component_id){let c=t.pcb_component.get(o.pcb_component_id);s=c?.width??0,a=c?.height??0}i=Math.max(i,s),r=Math.max(r,a)}return{width:i,height:r}}function Gvt(e){let t=e.pcbGridCols??e.gridCols??e.pcbLayout?.grid?.cols,n=e.pcbGridRows??e.pcbLayout?.grid?.rows,i=e.pcbGridTemplateColumns,r=e.pcbGridTemplateRows,o=h=>h===void 0?UT:typeof h=="number"?h:$.parse(h),s=e.pcbGridGap??e.gridGap??e.pcbLayout?.gridGap,a=e.pcbGridRowGap??e.gridRowGap??e.pcbLayout?.gridRowGap,c=e.pcbGridColumnGap??e.gridColumnGap??e.pcbLayout?.gridColumnGap,l=UT,u=UT;if(a!==void 0||c!==void 0){let h=typeof s=="object"?s?.x:s,f=typeof s=="object"?s?.y:s;l=o(c??h),u=o(a??f)}else if(typeof s=="object"&&s!==null)l=o(s.x),u=o(s.y);else{let h=o(s);l=h,u=h}return{cols:t,rows:n,gapX:l,gapY:u,templateColumns:i,templateRows:r}}function Uvt(e){let{props:t,pcbChildren:n,childDimensions:i,gridConfig:r}=e;return t.pcbGridTemplateColumns||t.pcbGridTemplateRows?qvt({props:t,gridConfig:r,pcbChildren:n,childDimensions:i}):Wvt({gridConfig:r,pcbChildren:n,childDimensions:i})}function qvt(e){let{props:t,gridConfig:n,pcbChildren:i,childDimensions:r}=e,o=t.pcbGridTemplateColumns??"",s=t.pcbGridTemplateRows??"",a=f=>{let _=f.match(/repeat\((\d+),/);return _?parseInt(_[1]):Math.ceil(Math.sqrt(i.length))},c=t.pcbGridTemplateColumns?a(o):Math.ceil(Math.sqrt(i.length)),l=t.pcbGridTemplateRows?a(s):Math.ceil(i.length/c),u=c*r.width+Math.max(0,c-1)*n.gapX,h=l*r.height+Math.max(0,l-1)*n.gapY;return{gridTemplateColumns:o,gridTemplateRows:s,containerWidth:u,containerHeight:h}}function Wvt(e){let{gridConfig:t,pcbChildren:n,childDimensions:i}=e,r,o;t.cols!==void 0&&t.rows!==void 0?(r=t.cols,o=t.rows):t.cols!==void 0?(r=t.cols,o=Math.ceil(n.length/r)):t.rows!==void 0?(o=t.rows,r=Math.ceil(n.length/o)):(r=Math.ceil(Math.sqrt(n.length)),o=Math.ceil(n.length/r)),r=Math.max(1,r),o=Math.max(1,o);let s=r*i.width+Math.max(0,r-1)*t.gapX,a=o*i.height+Math.max(0,o-1)*t.gapY,c=`repeat(${r}, ${i.width}px)`,l=`repeat(${o}, ${i.height}px)`;return{gridTemplateColumns:c,gridTemplateRows:l,containerWidth:s,containerHeight:a}}function Zvt(e){let{pcbChildren:t,childDimensions:n,gridLayout:i,gridConfig:r}=e,o=t.map((s,a)=>({key:s.getString()||`child-${a}`,contentWidth:n.width,contentHeight:n.height}));return new IB({containerWidth:i.containerWidth,containerHeight:i.containerHeight,gridTemplateColumns:i.gridTemplateColumns,gridTemplateRows:i.gridTemplateRows,gap:[r.gapY,r.gapX],children:o})}function Kvt(e){let{db:t,group:n,pcbChildren:i,itemCoordinates:r,gridLayout:o}=e,s=n._getGlobalPcbPositionBeforeLayout(),a=t.toArray();for(let c=0;c<i.length;c++){let l=i[c],u=l.getString()||`child-${c}`,h=r[u];if(!h){console.warn(`PCB grid layout: No coordinates found for child ${u}`);continue}let f=s.x-o.containerWidth/2+h.x+h.width/2,_=s.y+o.containerHeight/2-h.y-h.height/2;if(l.pcb_component_id)ag(a,l.pcb_component_id,{x:f,y:_});else{let y=l;y.pcb_group_id&&y.source_group_id&&cg(a,y.source_group_id,{x:f,y:_})}}}function Jvt(e){let{db:t,group:n,props:i,gridLayout:r}=e;if(n.pcb_group_id){let o=n._getGlobalPcbPositionBeforeLayout();t.pcb_group.update(n.pcb_group_id,{width:i.width??r.containerWidth,height:i.height??r.containerHeight,center:o})}}function Qvt(e){let t={serverUrl:"https://registry-api.tscircuit.com",serverMode:"job",serverCacheEnabled:!0};if(typeof e=="object"&&!e.preset)return{local:!(e.serverUrl||e.serverMode||e.serverCacheEnabled),...t,...e};let n=typeof e=="object"?e.preset:e,i=typeof e=="object"?e:{};switch(n){case"auto-local":return{local:!0,groupMode:"subcircuit"};case"sequential-trace":return{local:!0,groupMode:"sequential-trace"};case"subcircuit":return{local:!0,groupMode:"subcircuit"};case"auto-cloud":{let{preset:r,local:o,groupMode:s,...a}=i;return{local:!1,groupMode:"subcircuit",...t,...a}}default:return{local:!0,groupMode:"subcircuit"}}}var twt=(e,t)=>{let n=e.children.filter(h=>h.componentName==="Constraint"&&h._parsedProps.pcb),i=new Map,r={},o=h=>(r[h]!==h&&(r[h]=o(r[h])),r[h]),s=(h,f)=>{let _=o(h),y=o(f);_!==y&&(r[y]=_)},a=h=>{h in r||(r[h]=h)},c=h=>{let f=h.startsWith(".")?h.slice(1):h;return e.children.find(y=>y.name===f)?.pcb_component_id??void 0};for(let h of n){let f=h._parsedProps;if("left"in f&&"right"in f){let _=c(f.left),y=c(f.right);_&&y&&(a(_),a(y),s(_,y))}else if("top"in f&&"bottom"in f){let _=c(f.top),y=c(f.bottom);_&&y&&(a(_),a(y),s(_,y))}else if("for"in f&&Array.isArray(f.for)){let _=f.for.map(y=>c(y)).filter(y=>!!y);for(let y of _)a(y);for(let y=1;y<_.length;y++)s(_[0],_[y])}}for(let h of Object.keys(r)){let f=o(h);i.has(f)||i.set(f,{componentIds:[],constraints:[]}),i.get(f).componentIds.push(h)}for(let h of n){let f=h._parsedProps,_;if("left"in f?_=c(f.left):"top"in f?_=c(f.top):"for"in f&&(_=c(f.for[0])),!_)continue;let y=o(_);i.get(y)?.constraints.push(h)}let l={},u=Object.fromEntries(t.components.map(h=>[h.componentId,h]));for(let[h,f]of i.entries()){if(f.componentIds.length<=1)continue;let _=new up,y={},x=(A,L)=>{let B=`${A}_${L}`;return y[B]||(y[B]=new Is(B)),y[B]},v=f.componentIds[0];_.addConstraint(new ti(x(v,"x"),zn.Eq,0,mn.required)),_.addConstraint(new ti(x(v,"y"),zn.Eq,0,mn.required));for(let A of f.constraints){let L=A._parsedProps;if("xDist"in L){let B=c(L.left),D=c(L.right);B&&D&&_.addConstraint(new ti(new bn(x(D,"x"),[-1,x(B,"x")]),zn.Eq,L.xDist,mn.required))}else if("yDist"in L){let B=c(L.top),D=c(L.bottom);B&&D&&_.addConstraint(new ti(new bn(x(B,"y"),[-1,x(D,"y")]),zn.Eq,L.yDist,mn.required))}else if("sameX"in L&&Array.isArray(L.for)){let B=L.for.map(D=>c(D)).filter(D=>!!D);if(B.length>1){let D=x(B[0],"x");for(let V=1;V<B.length;V++)_.addConstraint(new ti(new bn(x(B[V],"x"),[-1,D]),zn.Eq,0,mn.required))}}else if("sameY"in L&&Array.isArray(L.for)){let B=L.for.map(D=>c(D)).filter(D=>!!D);if(B.length>1){let D=x(B[0],"y");for(let V=1;V<B.length;V++)_.addConstraint(new ti(new bn(x(B[V],"y"),[-1,D]),zn.Eq,0,mn.required))}}}_.updateVariables();let w={};for(let A of f.componentIds)w[A]={x:x(A,"x").value(),y:x(A,"y").value()};let S=1/0,C=1/0,E=-1/0,R=-1/0;for(let A of f.componentIds){let L=u[A],B=w[A];if(L)for(let D of L.pads){let V=B.x+D.offset.x,X=B.y+D.offset.y;S=Math.min(S,V-D.size.x/2),E=Math.max(E,V+D.size.x/2),C=Math.min(C,X-D.size.y/2),R=Math.max(R,X+D.size.y/2)}}let I={x:(S+E)/2,y:(C+R)/2},k=[],M={};for(let A of f.componentIds){let L=u[A],B=w[A];if(L){M[A]={x:B.x-I.x,y:B.y-I.y};for(let D of L.pads)k.push({padId:D.padId,networkId:D.networkId,type:D.type,size:D.size,offset:{x:B.x+D.offset.x-I.x,y:B.y+D.offset.y-I.y}})}}t.components=t.components.filter(A=>!f.componentIds.includes(A.componentId)),t.components.push({componentId:f.componentIds[0],pads:k,availableRotationDegrees:[0]}),f.relativeCenters=M,l[f.componentIds[0]]=f}return l},kf=(e,t,n)=>{if(t===n)return!0;let i=e.source_group.get(t);return!i||!i.parent_source_group_id?!1:kf(e,i.parent_source_group_id,n)},ewt=(e,t,n)=>{let{db:i}=e.root;for(let r of t.components){let{center:o,componentId:s,ccwRotationOffset:a,ccwRotationDegrees:c}=r,l=n[s];if(l){let w=(c??a??0)*Math.PI/180;for(let S of l.componentIds){let C=l.relativeCenters[S];if(!C)continue;let E={x:C.x*Math.cos(w)-C.y*Math.sin(w),y:C.x*Math.sin(w)+C.y*Math.cos(w)},R=i.pcb_component.get(S);if(!R)continue;let I=R.center,k=Gn(e._computePcbGlobalTransformBeforeLayout(),fn(o.x+E.x,o.y+E.y),va(w),fn(-I.x,-I.y)),M=i.toArray().filter(A=>"pcb_component_id"in A&&A.pcb_component_id===S);dp(M,k)}continue}let u=i.pcb_component.get(s);if(u){let v=e.source_group_id,S=i.source_component.get(u.source_component_id)?.source_group_id;if(S!==void 0&&!kf(i,S,v))continue;let C=u.center,E=c??a??0,R=Gn(e._computePcbGlobalTransformBeforeLayout(),fn(o.x,o.y),va(E*Math.PI/180),fn(-C.x,-C.y)),I=i.toArray().filter(k=>"pcb_component_id"in k&&k.pcb_component_id===s);dp(I,R);continue}let h=i.pcb_group.list().find(v=>v.source_group_id===s);if(!h)continue;let f=h.center,_=c??a??0,y=Gn(e._computePcbGlobalTransformBeforeLayout(),fn(o.x,o.y),va(_*Math.PI/180),fn(-f.x,-f.y)),x=i.toArray().filter(v=>{if("source_group_id"in v&&v.source_group_id&&(v.source_group_id===s||kf(i,v.source_group_id,s)))return!0;if("source_component_id"in v&&v.source_component_id){let w=i.source_component.get(v.source_component_id);if(w?.source_group_id&&(w.source_group_id===s||kf(i,w.source_group_id,s)))return!0}if("pcb_component_id"in v&&v.pcb_component_id){let w=i.pcb_component.get(v.pcb_component_id);if(w?.source_component_id){let S=i.source_component.get(w.source_component_id);if(S?.source_group_id&&(S.source_group_id===s||kf(i,S.source_group_id,s)))return!0}}return!1});dp(x,y),i.pcb_group.update(h.pcb_group_id,{center:o})}},nwt="1mm",rY=(0,OY.default)("Group_doInitialPcbLayoutPack"),iwt=e=>{let{db:t}=e.root,{_parsedProps:n}=e,{packOrderStrategy:i,packPlacementStrategy:r,gap:o,pcbGap:s,pcbPackGap:a}=n,c=a??s??o,l=$.parse(c??nwt),u={},h=x=>{if(x?.pcb_component_id&&x?._parsedProps){let v=x._parsedProps,w=$.parse(v.pcbMarginLeft??v.pcbMarginX??0),S=$.parse(v.pcbMarginRight??v.pcbMarginX??0),C=$.parse(v.pcbMarginTop??v.pcbMarginY??0),E=$.parse(v.pcbMarginBottom??v.pcbMarginY??0);(w||S||C||E)&&(u[x.pcb_component_id]={left:w,right:S,top:C,bottom:E})}x?.children&&x.children.forEach(h)};h(e);let f={...mB(fB(t.toArray(),{source_group_id:e.source_group_id,shouldAddInnerObstacles:!0,chipMarginsMap:u})),orderStrategy:i??"largest_to_smallest",placementStrategy:r??"minimum_sum_squared_distance_to_network",minGap:l},_=twt(e,f);rY.enabled&&(e.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`packInput-circuitjson-${e.name}`,content:JSON.stringify(t.toArray())}),e.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`packInput-${e.name}`,content:f}));let y=ox(f);if(rY.enabled){let x=fT(y);x.title=`packOutput-${e.name}`,global.debugGraphics?.push(x)}ewt(e,y,_)},rwt=e=>{let{db:t}=e.root,{_parsedProps:n}=e,i=e.children.filter(R=>R.pcb_component_id||R.pcb_group_id);if(i.some(R=>{let I=R._parsedProps;return I?.pcbX!==void 0||I?.pcbY!==void 0}))return;let o=n.pcbJustifyContent??n.justifyContent,s=n.pcbAlignItems??n.alignItems,a=n.pcbFlexGap??n.pcbGap??n.gap,c=n.pcbFlexDirection??"row",l={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"space-between","space-between":"space-between","space-around":"space-around","space-evenly":"space-evenly",center:"center"}[o??"space-between"],u={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"stretch",center:"center"}[s??"center"];if(!l)throw new Error(`Invalid justifyContent value: "${o}"`);if(!u)throw new Error(`Invalid alignItems value: "${s}"`);let h=0,f=0;typeof a=="object"?(h=a.y??0,f=a.x??0):typeof a=="number"?(h=a,f=a):typeof a=="string"&&(h=$.parse(a),f=$.parse(a));let _,y=n.width??n.pcbWidth??void 0,x=n.height??n.pcbHeight??void 0;(y===void 0||x===void 0)&&(_=lg(i.map(R=>R._getMinimumFlexContainerSize()).filter(R=>R!==null),{alignItems:u,justifyContent:l,direction:c,rowGap:h,columnGap:f}),y=_.width,x=_.height);let w=new cx(y,x,{alignItems:u,justifyContent:l,direction:c,rowGap:h,columnGap:f});for(let R of i){let I=R._getMinimumFlexContainerSize();w.addChild({metadata:R,width:I?.width??0,height:I?.height??0,flexBasis:I?c==="row"?I.width:I.height:void 0})}w.build();let S={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let R of w.children)S.minX=Math.min(S.minX,R.position.x),S.minY=Math.min(S.minY,R.position.y),S.maxX=Math.max(S.maxX,R.position.x+R.size.width),S.maxY=Math.max(S.maxY,R.position.y+R.size.height);S.width=S.maxX-S.minX,S.height=S.maxY-S.minY;let C=e._getGlobalPcbPositionBeforeLayout(),E={x:C.x-(S.maxX+S.minX)/2,y:C.y-(S.maxY+S.minY)/2};for(let R of w.children)R.metadata._repositionOnPcb({x:R.position.x+R.size.width/2+E.x,y:R.position.y+R.size.height/2+E.y});t.pcb_group.update(e.pcb_group_id,{width:S.width,height:S.height,center:C})};function owt(e){let{db:t}=e.root,n=new Map,i=new Map,r=new Set,s=e.selectAll("trace").filter(L=>L._parsedProps?.schDisplayLabel),a=e.selectAll("group"),c=[e.schematic_group_id,...a.map(L=>L.schematic_group_id)],l=t.schematic_component.list().filter(L=>c.includes(L.schematic_group_id)),u=[],h=new Map,f=new Map;for(let L of l){let B=L.schematic_component_id,D=[],V=t.source_component.getWhere({source_component_id:L.source_component_id}),X=t.schematic_port.list({schematic_component_id:L.schematic_component_id});for(let W of X){let Q=`${V?.name??L.schematic_component_id}.${W.pin_number}`;h.set(Q,W.schematic_port_id),f.set(W.schematic_port_id,Q)}for(let W of X){let Q=f.get(W.schematic_port_id);D.push({pinId:Q,x:W.center.x,y:W.center.y})}u.push({chipId:B,center:L.center,width:L.size.width,height:L.size.height,pins:D})}let _=new Set,y=new Map,x=new Map,v=new Map;for(let L of l){let B=t.schematic_port.list({schematic_component_id:L.schematic_component_id});for(let D of B)_.add(D.schematic_port_id),D.source_port_id&&(y.set(D.schematic_port_id,D.source_port_id),x.set(D.source_port_id,D.schematic_port_id))}let w=new Set;e.subcircuit_id&&w.add(e.subcircuit_id);for(let L of a)L.subcircuit_id&&w.add(L.subcircuit_id);let C=t.source_trace.list().filter(L=>{if(L.subcircuit_id===e.subcircuit_id)return!0;for(let B of L.connected_source_port_ids)if(x.has(B))return!0;return!1}).flatMap(L=>L.connected_source_net_ids);for(let L of C){let B=t.source_net.get(L);B?.subcircuit_id&&w.add(B.subcircuit_id)}let E=[],R=new Map;for(let L of t.source_trace.list()){if(L.subcircuit_id&&!w.has(L.subcircuit_id))continue;let B=(L.connected_source_port_ids??[]).map(D=>x.get(D)).filter(D=>!!D&&_.has(D));if(B.length>=2){let[D,V]=B.slice(0,2),X=[D,V].sort().join("::");if(!R.has(X)){R.set(X,L.source_trace_id);let W=L.display_name??L.source_trace_id;L.subcircuit_connectivity_map_key&&(r.add(L.subcircuit_connectivity_map_key),v.set(W,L.subcircuit_connectivity_map_key),i.set(L.subcircuit_connectivity_map_key,W)),E.push({pinIds:[D,V].map(Q=>f.get(Q)),netId:W})}}}let I=[];for(let L of t.source_net.list().filter(B=>!B.subcircuit_id||w.has(B.subcircuit_id)))L.subcircuit_connectivity_map_key&&(r.add(L.subcircuit_connectivity_map_key),n.set(L.subcircuit_connectivity_map_key,L));let k=new Map;for(let[L,B]of y){let D=t.source_port.get(B);if(!D?.subcircuit_connectivity_map_key)continue;let V=D.subcircuit_connectivity_map_key;r.add(V),k.has(V)||k.set(V,[]),k.get(V).push(L)}for(let[L,B]of k){let D=n.get(L);if(D&&B.length>=2){let V=String(D.name||D.source_net_id||L);v.set(V,L),i.set(L,V);let W=.1*(.18/.18),Q=Number((String(V).length*W).toFixed(2));I.push({netId:V,pinIds:B.map(J=>f.get(J)),netLabelWidth:Q})}}let M=(()=>{let L={},B=new Set(I.map(D=>D.netId));for(let D of t.source_net.list().filter(V=>!V.subcircuit_id||w.has(V.subcircuit_id)))D.name&&B.has(D.name)&&(D.is_ground||D.name.toLowerCase().startsWith("gnd")?L[D.name]=["y-"]:D.is_power||D.name.toLowerCase().startsWith("v")?L[D.name]=["y+"]:L[D.name]=["x-","x+"]);return L})();return{inputProblem:{chips:u,directConnections:E,netConnections:I,availableNetLabelOrientations:M,maxMspPairDistance:e._parsedProps.schMaxTraceDistance??2.4},pinIdToSchematicPortId:h,pairKeyToSourceTraceId:R,sckToSourceNet:n,sckToUserNetId:i,userNetIdToSck:v,allSourceAndSchematicPortIdsInScope:_,schPortIdToSourcePortId:y,displayLabelTraces:s,allScks:r}}var zi=1e-6;function oY(e){let t=Math.abs(e.to.x-e.from.x),n=Math.abs(e.to.y-e.from.y);return t>=n}function Ax(e,t){return Math.hypot(t.x-e.x,t.y-e.y)}function sY(e,t,n){return{x:e.x+(t.x-e.x)*n,y:e.y+(t.y-e.y)*n}}function aY(e,t,n){let i=Ax(e,t);if(i<zi)return 0;let r=((n.x-e.x)*(t.x-e.x)+(n.y-e.y)*(t.y-e.y))/((t.x-e.x)*(t.x-e.x)+(t.y-e.y)*(t.y-e.y));return Math.max(0,Math.min(1,r))*i}function Px(e,t,n,i){return e*i-t*n}function swt(e,t,n,i){let r={x:t.x-e.x,y:t.y-e.y},o={x:i.x-n.x,y:i.y-n.y},s=Px(r.x,r.y,o.x,o.y),a={x:n.x-e.x,y:n.y-e.y},c=Px(a.x,a.y,r.x,r.y);if(Math.abs(s)<zi&&Math.abs(c)<zi||Math.abs(s)<zi&&Math.abs(c)>=zi)return null;let l=Px(a.x,a.y,o.x,o.y)/s,u=Px(a.x,a.y,r.x,r.y)/s;return l<-zi||l>1+zi||u<-zi||u>1+zi?null:{x:e.x+l*r.x,y:e.y+l*r.y}}function awt(e,t=zi){if(e.length===0)return e;e.sort((r,o)=>r.start-o.start);let n=[],i={...e[0]};for(let r=1;r<e.length;r++){let o=e[r];o.start<=i.end+t?i.end=Math.max(i.end,o.end):(n.push(i),i={...o})}return n.push(i),n}function cwt(e,t,n){let i=Ax(e.from,e.to);if(i<zi||t.length===0)return[e];let r=n/2,o=t.map(h=>({start:Math.max(0,h-r),end:Math.min(i,h+r)})).filter(h=>h.end-h.start>zi),s=awt(o),a=[],c=0,l={x:e.to.x-e.from.x,y:e.to.y-e.from.y},u=(h,f,_)=>{if(f-h<=zi)return;let y=h/i,x=f/i;a.push({from:sY(e.from,e.to,y),to:sY(e.from,e.to,x),..._?{is_crossing:!0}:{}})};for(let h of s)h.start-c>zi&&u(c,h.start,!1),u(h.start,h.end,!0),c=h.end;return i-c>zi&&u(c,i,!1),a.length>0?a:[e]}function lwt(e,t={}){let n=t.crossSegmentLength??.075,i=t.tolerance??zi,r=new Map,o=c=>`${c.traceIdx}:${c.edgeIdx}`,s=c=>e[c.traceIdx].edges[c.edgeIdx];for(let c=0;c<e.length;c++){let l=e[c];for(let u=0;u<l.edges.length;u++){let h=l.edges[u];for(let f=c;f<e.length;f++){let _=e[f];for(let y=f===c?u+1:0;y<_.edges.length;y++){let x=_.edges[y],v=swt(h.from,h.to,x.from,x.to);if(!v)continue;let w=Ax(h.from,h.to),S=Ax(x.from,x.to);if(w<i||S<i)continue;let C=aY(h.from,h.to,v),E=aY(x.from,x.to,v),R=C<=i||Math.abs(w-C)<=i||Number.isNaN(C),I=E<=i||Math.abs(S-E)<=i||Number.isNaN(E);if(!R&&!I){let k=oY(h),M=oY(x),A;if(k!==M)A=k;else{let D=Math.abs(h.to.x-h.from.x),V=Math.abs(h.to.y-h.from.y),X=Math.abs(x.to.x-x.from.x),W=Math.abs(x.to.y-x.from.y),Q=D-V,J=X-W;A=Q===J?!0:Q>J}let L=o({traceIdx:A?c:f,edgeIdx:A?u:y}),B=r.get(L)??[];B.push(A?C:E),r.set(L,B)}}}}}let a=e.map(c=>({source_trace_id:c.source_trace_id,edges:[]}));for(let c=0;c<e.length;c++){let l=e[c];for(let u=0;u<l.edges.length;u++){let h=o({traceIdx:c,edgeIdx:u}),f=r.get(h)??[];if(f.length===0){a[c].edges.push(l.edges[u]);continue}let _=Array.from(new Set(f.map(x=>Number(x.toFixed(6))))).sort((x,v)=>x-v),y=cwt(l.edges[u],_,n);a[c].edges.push(...y)}}return a}var Ho=1e-6;function Nx(e,t,n=Ho){return Math.abs(e-t)<=n}function Qp(e,t,n=Ho){return Nx(e.x,t.x,n)&&Nx(e.y,t.y,n)}function cY(e,t,n,i=Ho){let r=Math.min(t.x,n.x)-i,o=Math.max(t.x,n.x)+i,s=Math.min(t.y,n.y)-i,a=Math.max(t.y,n.y)+i;return e.x<r||e.x>o||e.y<s||e.y>a?!1:Math.abs((n.x-t.x)*(e.y-t.y)-(n.y-t.y)*(e.x-t.x))<=i}function lY(e,t=Ho){let n=new Map;for(let i of e){let r=`${i.x.toFixed(6)},${i.y.toFixed(6)}`;n.has(r)||n.set(r,i)}return Array.from(n.values())}function uY(e){return{x:e.to.x-e.from.x,y:e.to.y-e.from.y}}function qT(e,t,n=Ho){let i=uY(e),r=uY(t),o=Math.hypot(i.x,i.y),s=Math.hypot(r.x,r.y);if(o<n||s<n)return!0;let a=i.x*r.y-i.y*r.x;return Math.abs(a)<=n*o*s}function Af(e,t,n=Ho){return e.edges.filter(i=>Qp(i.from,t,n)||Qp(i.to,t,n))}function pY(e,t,n=Ho){for(let i of e.edges){if(Qp(i.from,t,n))return i.from;if(Qp(i.to,t,n))return i.to}return null}function uwt(e,t,n=Ho){let i=Qp(e.from,t,n)||Nx(e.from.x,t.x,n)&&Nx(e.from.y,t.y,n)?e.to:e.from,r=i.x-t.x,o=i.y-t.y;return Math.abs(r)<n&&Math.abs(o)<n?null:Math.abs(r)>=Math.abs(o)?r>=0?"right":"left":o>=0?"up":"down"}function Wp(e,t,n=Ho){let i=Af(e,t,n);if(i.length<2)return null;let r=i.map(h=>uwt(h,t,n)),o=r.includes("up"),s=r.includes("down"),a=r.includes("left"),c=r.includes("right"),l=o?"up":s?"down":null,u=c?"right":a?"left":null;return l&&u?`${l}-${u}`:null}function pwt(e,t={}){let n=t.tolerance??Ho,i={};for(let o of e)i[o.source_trace_id]=[];let r=e.map(o=>{let s=[];for(let a of o.edges)s.push(a.from,a.to);return lY(s,n)});for(let o=0;o<e.length;o++){let s=e[o],a=r[o];for(let c=o+1;c<e.length;c++){let l=e[c],u=r[c];for(let h of a)for(let f of u)if(Qp(h,f,n)){let _=Af(s,h,n),y=Af(l,f,n),x=_.some(C=>y.some(E=>!qT(C,E,n))),v=Wp(s,h,n),w=Wp(l,f,n);x&&!(v!==null&&w!==null&&v===w)&&(i[s.source_trace_id].push(h),s.source_trace_id!==l.source_trace_id&&i[l.source_trace_id].push(f))}for(let h of a)for(let f of l.edges)if(cY(h,f.from,f.to,n)){let y=Af(s,h,n).some(C=>!qT(C,f,n)),x=Wp(s,h,n),v=pY(l,h,n*1e3),w=v?Wp(l,v,n):null;y&&!(x!==null&&w!==null&&x===w)&&(i[s.source_trace_id].push(h),s.source_trace_id!==l.source_trace_id&&i[l.source_trace_id].push(h))}for(let h of u)for(let f of s.edges)if(cY(h,f.from,f.to,n)){let y=Af(l,h,n).some(C=>!qT(f,C,n)),x=Wp(l,h,n),v=pY(s,h,n*1e3),w=v?Wp(s,v,n):null;y&&!(w!==null&&x!==null&&w===x)&&(i[l.source_trace_id].push(h),s.source_trace_id!==l.source_trace_id&&i[s.source_trace_id].push(h))}}}for(let o of Object.keys(i))i[o]=lY(i[o],n);return i}var WT=(0,FY.default)("Group_doInitialSchematicTraceRender");function hwt(e){let{group:t,solver:n,pinIdToSchematicPortId:i,userNetIdToSck:r}=e,{db:o}=t.root,s=n.traceLabelOverlapAvoidanceSolver?.getOutput().traces??n.schematicTraceLinesSolver?.solvedTracePaths,a=[];WT(`Traces inside SchematicTraceSolver output: ${(s??[]).length}`);for(let u of s??[]){let h=u?.tracePath;if(!Array.isArray(h)||h.length<2){WT(`Skipping trace ${u?.pinIds.join(",")} because it has less than 2 points`);continue}let f=[];for(let x=0;x<h.length-1;x++)f.push({from:{x:h[x].x,y:h[x].y},to:{x:h[x+1].x,y:h[x+1].y}});let _=null,y;if(Array.isArray(u?.pins)&&u.pins.length===2){let x=i.get(u.pins[0]?.pinId),v=i.get(u.pins[1]?.pinId);if(x&&v){for(let w of[x,v])o.schematic_port.get(w)&&o.schematic_port.update(w,{is_connected:!0});y=r.get(String(u.userNetId))}}_||(_=`solver_${u?.mspPairId}`,y=r.get(String(u.userNetId))),a.push({source_trace_id:_,edges:f,subcircuit_connectivity_map_key:y})}WT(`Applying ${a.length} traces from SchematicTraceSolver output`);let c=lwt(a.map(u=>({source_trace_id:u.source_trace_id,edges:u.edges}))),l=pwt(c);for(let u of c)o.schematic_trace.insert({source_trace_id:u.source_trace_id,edges:u.edges,junctions:l[u.source_trace_id]??[],subcircuit_connectivity_map_key:a.find(h=>h.source_trace_id===u.source_trace_id)?.subcircuit_connectivity_map_key})}var dwt=e=>{switch(e){case"x+":return"left";case"x-":return"right";case"y+":return"bottom";case"y-":return"top";case"left":return"right";case"top":return"bottom";case"right":return"left";case"bottom":return"top"}},fwt=e=>{for(let n of e){let i=n._getDirectlyConnectedTraces();for(let r of i){let o=r._parsedProps.schDisplayLabel;if(o)return{name:o,wasAssignedDisplayLabel:!0}}}return{name:e.map(n=>n._getNetLabelText()).join("/"),wasAssignedDisplayLabel:!1}},ZT=(0,zY.default)("Group_doInitialSchematicTraceRender");function mwt(e){let{group:t,solver:n,sckToSourceNet:i,allScks:r,allSourceAndSchematicPortIdsInScope:o,schPortIdToSourcePortId:s,userNetIdToSck:a,pinIdToSchematicPortId:c,schematicPortIdsWithPreExistingNetLabels:l,schematicPortIdsWithRoutedTraces:u}=e,{db:h}=t.root,f=n.traceLabelOverlapAvoidanceSolver?.getOutput().netLabelPlacements??[],_=n.mspConnectionPairSolver.globalConnMap;for(let y of f){ZT(`processing placement: ${y.netId}`);let x=_.getIdsConnectedToNet(y.globalConnNetId).find(L=>a.get(L)),v=a.get(x),w=y.anchorPoint,S=y.orientation,C=dwt(S),E=v?i.get(v):void 0,R=y.pinIds.map(L=>c.get(L));if(R.some(L=>l.has(L))){ZT(`skipping net label placement for "${y.netId}" REASON:schematic port has pre-existing net label`);continue}if(E){let L=E.name,B=Ka({anchor_position:w,anchor_side:C,text:L});h.schematic_net_label.insert({text:L,anchor_position:w,center:B,anchor_side:C,...E?.source_net_id?{source_net_id:E.source_net_id}:{}});continue}let I=t.selectAll("port").filter(L=>L._getSubcircuitConnectivityKey()===v),{name:k,wasAssignedDisplayLabel:M}=fwt(I);if(!M&&R.some(L=>u.has(L))){ZT(`skipping net label placement for "${y.netId}" REASON:schematic port has routed traces and no display label`);continue}let A=Ka({anchor_position:w,anchor_side:C,text:k});h.schematic_net_label.insert({text:k,anchor_position:w,center:A,anchor_side:C})}}var _wt=({allSourceAndSchematicPortIdsInScope:e,group:t,schPortIdToSourcePortId:n,sckToSourceNet:i,pinIdToSchematicPortId:r,schematicPortIdsWithPreExistingNetLabels:o})=>{let{db:s}=t.root;for(let a of Array.from(e)){let c=s.schematic_port.get(a);if(!c||c.is_connected)continue;let l=n.get(a);if(!l)continue;let h=s.source_port.get(l)?.subcircuit_connectivity_map_key;if(!h)continue;let f=i.get(h);if(!f||s.schematic_net_label.list().some(w=>Math.abs(w.anchor_position.x-c.center.x)<.1&&Math.abs(w.anchor_position.y-c.center.y)<.1?f.source_net_id&&w.source_net_id?w.source_net_id===f.source_net_id:w.text===(f.name||h):!1))continue;let y=f.name||f.source_net_id||h,x=Of(c.facing_direction||"right")||"right",v=Ka({anchor_position:c.center,anchor_side:x,text:y});s.schematic_net_label.insert({text:y,anchor_position:c.center,center:v,anchor_side:x,...f.source_net_id?{source_net_id:f.source_net_id}:{}})}},ywt=e=>{let t=new Set,n=e.selectAll("netlabel");for(let i of n){let r=i._getConnectedPorts();for(let o of r)o.schematic_port_id&&t.add(o.schematic_port_id)}return t},gwt=({solver:e,pinIdToSchematicPortId:t})=>{let n=e.schematicTraceLinesSolver.solvedTracePaths,i=new Set;for(let r of n)for(let o of r.pinIds){let s=t.get(o);s&&i.add(s)}return i},xwt=(0,LY.default)("Group_doInitialSchematicTraceRender"),bwt=e=>{if(!e.root?._featureMspSchematicTraceRouting||!e.isSubcircuit||e.root?.schematicDisabled)return;let{inputProblem:t,pinIdToSchematicPortId:n,pairKeyToSourceTraceId:i,sckToSourceNet:r,allSourceAndSchematicPortIdsInScope:o,schPortIdToSourcePortId:s,displayLabelTraces:a,allScks:c,userNetIdToSck:l}=owt(e),u=ywt(e);xwt.enabled&&e.root?.emit("debug:logOutput",{type:"debug:logOutput",name:"group-trace-render-input-problem",content:JSON.stringify(t,null,2)});let h=new jB(t);h.solve();let f=gwt({solver:h,pinIdToSchematicPortId:n});hwt({group:e,solver:h,pinIdToSchematicPortId:n,userNetIdToSck:l}),mwt({group:e,solver:h,sckToSourceNet:r,allSourceAndSchematicPortIdsInScope:o,schPortIdToSourcePortId:s,pinIdToSchematicPortId:n,allScks:c,userNetIdToSck:l,schematicPortIdsWithPreExistingNetLabels:u,schematicPortIdsWithRoutedTraces:f}),_wt({group:e,allSourceAndSchematicPortIdsInScope:o,schPortIdToSourcePortId:s,sckToSourceNet:r,pinIdToSchematicPortId:n,schematicPortIdsWithPreExistingNetLabels:u})},th=class extends In{constructor(){super(...arguments);T(this,"pcb_group_id",null);T(this,"schematic_group_id",null);T(this,"subcircuit_id",null);T(this,"_hasStartedAsyncAutorouting",!1);T(this,"_asyncAutoroutingResult",null);T(this,"unnamedElementCounter",{})}get config(){return{zodProps:dL,componentName:"Group"}}doInitialSourceGroupRender(){let{db:t}=this.root,n=t.source_group.insert({name:this.name,is_subcircuit:this.isSubcircuit});this.source_group_id=n.source_group_id,this.isSubcircuit&&(this.subcircuit_id=`subcircuit_${n.source_group_id}`,t.source_group.update(n.source_group_id,{subcircuit_id:this.subcircuit_id}))}doInitialSourceRender(){let{db:t}=this.root;for(let n of this.children)t.source_component.update(n.source_component_id,{source_group_id:this.source_group_id})}doInitialSourceParentAttachment(){let{db:t}=this.root,n=this.parent?.getGroup?.();if(n?.source_group_id&&t.source_group.update(this.source_group_id,{parent_source_group_id:n.source_group_id}),!this.isSubcircuit)return;let i=this.parent?.getSubcircuit?.()?.subcircuit_id;i&&t.source_group.update(this.source_group_id,{parent_subcircuit_id:i})}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=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:n.autorouter?{trace_clearance:n.autorouter.traceClearance}:void 0});this.pcb_group_id=i.pcb_group_id;for(let r of this.children)t.pcb_component.update(r.pcb_component_id,{pcb_group_id:i.pcb_group_id})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,n=this._parsedProps,i=Ox(this.children);if(this.pcb_group_id){let r=i.width,o=i.height,s=(i.minX+i.maxX)/2,a=(i.minY+i.maxY)/2;if(this.isSubcircuit){let{padLeft:u,padRight:h,padTop:f,padBottom:_}=this._resolvePcbPadding();r+=u+h,o+=f+_,s+=(h-u)/2,a+=(f-_)/2}let l=this._parsedProps.pcbX!==void 0||this._parsedProps.pcbY!==void 0?t.pcb_group.get(this.pcb_group_id)?.center??{x:s,y:a}:{x:s,y:a};t.pcb_group.update(this.pcb_group_id,{width:Number(n.width??r),height:Number(n.height??o),center:l})}}getNextAvailableName(t){var n,i;return(n=this.unnamedElementCounter)[i=t.lowercaseComponentName]??(n[i]=1),`unnamed_${t.lowercaseComponentName}${this.unnamedElementCounter[t.lowercaseComponentName]++}`}_resolvePcbPadding(){let t=this._parsedProps,n=t.pcbLayout,i=h=>{let f=n?.[h],_=t[h];if(typeof f=="number")return f;if(typeof _=="number")return _},r=i("padding")??0,o=i("paddingX"),s=i("paddingY"),a=i("paddingLeft")??o??r,c=i("paddingRight")??o??r,l=i("paddingTop")??s??r,u=i("paddingBottom")??s??r;return{padLeft:a,padRight:c,padTop:l,padBottom:u}}doInitialCreateTraceHintsFromProps(){let{_parsedProps:t}=this,{db:n}=this.root,i=t;if(!this.isSubcircuit)return;let r=i.manualEdits?.manual_trace_hints;if(r)for(let o of r)this.add(new fI({for:o.pcb_port_selector,offsets:o.offsets}))}doInitialSourceAddConnectivityMapKey(){Bvt(this)}_areChildSubcircuitsRouted(){let t=this.selectAll("group").filter(n=>n.isSubcircuit);for(let n of t)if(n._shouldRouteAsync()&&!n._asyncAutoroutingResult)return!1;return!0}_shouldRouteAsync(){let t=this._getAutorouterConfig();return t.groupMode==="sequential-trace"?!1:!!(t.local&&t.groupMode==="subcircuit"||!t.local)}_hasTracesToRoute(){let t=(0,Zp.default)("tscircuit:core:_hasTracesToRoute"),n=this.selectAll("trace");return t(`[${this.getString()}] has ${n.length} traces to route`),n.length>0}async _runEffectMakeHttpAutoroutingRequest(){let{db:t}=this.root,n=(0,Zp.default)("tscircuit:core:_runEffectMakeHttpAutoroutingRequest"),i=this._parsedProps,r=this._getAutorouterConfig(),o=r.serverUrl,s=r.serverMode,a=(u,h)=>(n("fetching",u),h.headers&&(h.headers["Tscircuit-Core-Version"]=this.root?.getCoreVersion()),fetch(u,h)),c=this.root.db.toArray().filter(u=>u.type.startsWith("source_")||u.type.startsWith("pcb_"));if(s==="solve-endpoint"){if(this.props.autorouter?.inputFormat==="simplified"){let{autorouting_result:h}=await a(`${o}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_simple_route_json:iI({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(f=>f.json());this._asyncAutoroutingResult=h,this._markDirty("PcbTraceRender");return}let{autorouting_result:u}=await a(`${o}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_circuit_json:c,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(h=>h.json());this._asyncAutoroutingResult=u,this._markDirty("PcbTraceRender");return}let{autorouting_job:l}=await a(`${o}/autorouting/jobs/create`,{method:"POST",body:JSON.stringify({input_circuit_json:c,provider:"freerouting",autostart:!0,display_name:this.root?.name,subcircuit_id:this.subcircuit_id,server_cache_enabled:r.serverCacheEnabled}),headers:{"Content-Type":"application/json"}}).then(u=>u.json());for(;;){let{autorouting_job:u}=await a(`${o}/autorouting/jobs/get`,{method:"POST",body:JSON.stringify({autorouting_job_id:l.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(h=>h.json());if(u.is_finished){let{autorouting_job_output:h}=await a(`${o}/autorouting/jobs/get_output`,{method:"POST",body:JSON.stringify({autorouting_job_id:l.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(f=>f.json());this._asyncAutoroutingResult={output_pcb_traces:h.output_pcb_traces},this._markDirty("PcbTraceRender");break}if(u.has_error){let h=new Cf(`Autorouting job failed: ${JSON.stringify(u.error)}`);throw t.pcb_autorouting_error.insert({pcb_error_id:l.autorouting_job_id,error_type:"pcb_autorouting_error",message:h.message}),h}await new Promise(h=>setTimeout(h,100))}}async _runLocalAutorouting(){let{db:t}=this.root,n=this._parsedProps,i=(0,Zp.default)("tscircuit:core:_runLocalAutorouting");i(`[${this.getString()}] starting local autorouting`);let r=this._getAutorouterConfig(),{simpleRouteJson:o}=iI({db:t,minTraceWidth:this.props.autorouter?.minTraceWidth??.15,subcircuit_id:this.subcircuit_id});if(i.enabled){let c=Q5(o);c.title=`autorouting-${this.props.name}`,global.debugGraphics?.push(c)}this.root?.emit("autorouting:start",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),simpleRouteJson:o});let s;r.algorithmFn?s=await r.algorithmFn(o):s=new Avt(o,{capacityDepth:this.props.autorouter?.capacityDepth,targetMinCapacity:this.props.autorouter?.targetMinCapacity});let a=new Promise((c,l)=>{s.on("complete",u=>{i(`[${this.getString()}] local autorouting complete`),c(u.traces)}),s.on("error",u=>{i(`[${this.getString()}] local autorouting error: ${u.error.message}`),l(u.error)})});s.on("progress",c=>{this.root?.emit("autorouting:progress",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),...c})}),s.start();try{let c=await a;this._asyncAutoroutingResult={output_pcb_traces:c},this._markDirty("PcbTraceRender")}catch(c){let{db:l}=this.root;throw l.pcb_autorouting_error.insert({pcb_error_id:`pcb_autorouter_error_subcircuit_${this.subcircuit_id}`,error_type:"pcb_autorouting_error",message:c instanceof Error?c.message:String(c)}),this.root?.emit("autorouting:error",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),error:{message:c instanceof Error?c.message:String(c)},simpleRouteJson:o}),c}finally{s.stop()}}_startAsyncAutorouting(){this._hasStartedAsyncAutorouting||(this._hasStartedAsyncAutorouting=!0,this._getAutorouterConfig().local?this._queueAsyncEffect("capacity-mesh-autorouting",async()=>this._runLocalAutorouting()):this._queueAsyncEffect("make-http-autorouting-request",async()=>this._runEffectMakeHttpAutoroutingRequest()))}doInitialPcbTraceRender(){let t=(0,Zp.default)("tscircuit:core:doInitialPcbTraceRender");if(this.isSubcircuit&&!this.root?.pcbDisabled&&!this.getInheritedProperty("routingDisabled")&&!this._shouldUseTraceByTraceRouting()){if(!this._areChildSubcircuitsRouted()){t(`[${this.getString()}] child subcircuits are not routed, skipping async autorouting until subcircuits routed`);return}t(`[${this.getString()}] no child subcircuits to wait for, initiating async routing`),this._hasTracesToRoute()&&this._startAsyncAutorouting()}}doInitialSchematicTraceRender(){bwt(this)}updatePcbTraceRender(){let t=(0,Zp.default)("tscircuit:core:updatePcbTraceRender");if(t(`[${this.getString()}] updating...`),!this.isSubcircuit)return;if(this._shouldRouteAsync()&&this._hasTracesToRoute()&&!this._hasStartedAsyncAutorouting){this._areChildSubcircuitsRouted()&&(t(`[${this.getString()}] child subcircuits are now routed, starting async autorouting`),this._startAsyncAutorouting());return}if(!this._asyncAutoroutingResult||this._shouldUseTraceByTraceRouting())return;let{db:n}=this.root;if(this._asyncAutoroutingResult.output_simple_route_json){t(`[${this.getString()}] updating PCB traces from simple route json (${this._asyncAutoroutingResult.output_simple_route_json.traces?.length} traces)`),this._updatePcbTraceRenderFromSimpleRouteJson();return}if(this._asyncAutoroutingResult.output_pcb_traces){t(`[${this.getString()}] updating PCB traces from ${this._asyncAutoroutingResult.output_pcb_traces.length} traces`),this._updatePcbTraceRenderFromPcbTraces();return}}_updatePcbTraceRenderFromSimpleRouteJson(){let{db:t}=this.root,{traces:n}=this._asyncAutoroutingResult.output_simple_route_json;if(n)for(let i of n){let r=t.pcb_trace.insert({subcircuit_id:this.subcircuit_id,route:i.route})}}_updatePcbTraceRenderFromPcbTraces(){let{output_pcb_traces:t}=this._asyncAutoroutingResult;if(!t)return;let{db:n}=this.root;for(let i of t)if(i.type==="pcb_trace"){if(i.subcircuit_id=this.subcircuit_id,i.connection_name){let r=i.connection_name;i.source_trace_id=r}n.pcb_trace.insert(i)}for(let i of t)if(i.type!=="pcb_via"&&i.type==="pcb_trace")for(let r of i.route)r.route_type==="via"&&n.pcb_via.insert({pcb_trace_id:i.pcb_trace_id,x:r.x,y:r.y,hole_diameter:.3,outer_diameter:.6,layers:[r.from_layer,r.to_layer],from_layer:r.from_layer,to_layer:r.to_layer})}doInitialSchematicComponentRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=t.schematic_group.insert({is_subcircuit:this.isSubcircuit,subcircuit_id:this.subcircuit_id,name:this.name,center:this._getGlobalSchematicPositionBeforeLayout(),width:0,height:0,schematic_component_ids:[],source_group_id:this.source_group_id});this.schematic_group_id=i.schematic_group_id;for(let r of this.children)r.schematic_component_id&&t.schematic_component.update(r.schematic_component_id,{schematic_group_id:i.schematic_group_id})}_getSchematicLayoutMode(){let t=this._parsedProps;if(t.schLayout?.layoutMode==="none"||t.schLayout?.layoutMode==="relative")return"relative";if(t.schLayout?.matchAdapt)return"match-adapt";if(t.schLayout?.flex)return"flex";if(t.schLayout?.grid)return"grid";if(t.schMatchAdapt)return"match-adapt";if(t.schFlex)return"flex";if(t.schGrid)return"grid";if(t.matchAdapt)return"match-adapt";if(t.flex)return"flex";if(t.grid)return"grid";if(t.relative||t.schRelative)return"relative";let n=this.children.some(r=>{let o=r._parsedProps;return o?.schX!==void 0||o?.schY!==void 0}),i=(t.manualEdits?.schematic_placements?.length??0)>0;return!n&&!i?"match-adapt":"relative"}doInitialSchematicLayout(){let t=this._getSchematicLayoutMode();t==="match-adapt"&&this._doInitialSchematicLayoutMatchpack(),t==="grid"&&this._doInitialSchematicLayoutGrid(),t==="flex"&&this._doInitialSchematicLayoutFlex(),this._insertSchematicBorder()}_doInitialSchematicLayoutMatchAdapt(){zvt(this)}_doInitialSchematicLayoutMatchpack(){$vt(this)}_doInitialSchematicLayoutGrid(){jvt(this)}_doInitialSchematicLayoutFlex(){Yvt(this)}_getPcbLayoutMode(){let t=this._parsedProps;if(t.pcbRelative)return"none";if(t.pcbLayout?.matchAdapt)return"match-adapt";if(t.pcbLayout?.flex)return"flex";if(t.pcbLayout?.grid)return"grid";if(t.pcbLayout?.pack)return"pack";if(t.pcbFlex)return"flex";if(t.pcbGrid)return"grid";if(t.pcbPack||t.pack)return"pack";if(t.matchAdapt)return"match-adapt";if(t.flex)return"flex";if(t.grid)return"grid";let n=t.pcbX!==void 0||t.pcbY!==void 0,i=(t.manualEdits?.pcb_placements?.length??0)>0;if(this.children.some(s=>{let a=s._parsedProps;return a?.pcbX!==void 0||a?.pcbY!==void 0}))return"none";let o=this.children.reduce((s,a)=>{let c=a._parsedProps,l=c?.pcbX!==void 0||c?.pcbY!==void 0;return s+(l?0:1)},0);return!n&&!i&&o>1?"pack":"none"}doInitialPcbLayout(){let t=this._getPcbLayoutMode();t==="grid"?this._doInitialPcbLayoutGrid():t==="pack"?this._doInitialPcbLayoutPack():t==="flex"&&this._doInitialPcbLayoutFlex()}_doInitialPcbLayoutGrid(){Xvt(this)}_doInitialPcbLayoutPack(){iwt(this)}_doInitialPcbLayoutFlex(){rwt(this)}_insertSchematicBorder(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,n=this._parsedProps;if(!n.border)return;let i=typeof n.schWidth=="number"?n.schWidth:void 0,r=typeof n.schHeight=="number"?n.schHeight:void 0,o=typeof n.schPadding=="number"?n.schPadding:0,s=typeof n.schPaddingLeft=="number"?n.schPaddingLeft:o,a=typeof n.schPaddingRight=="number"?n.schPaddingRight:o,c=typeof n.schPaddingTop=="number"?n.schPaddingTop:o,l=typeof n.schPaddingBottom=="number"?n.schPaddingBottom:o,u=this.schematic_group_id?t.schematic_group.get(this.schematic_group_id):null;if(u&&(i===void 0&&typeof u.width=="number"&&(i=u.width),r===void 0&&typeof u.height=="number"&&(r=u.height)),i===void 0||r===void 0)return;let h=u?.center??this._getGlobalSchematicPositionBeforeLayout(),f=h.x-i/2-s,_=h.y-r/2-l,y=i+s+a,x=r+c+l;t.schematic_box.insert({width:y,height:x,x:f,y:_,is_dashed:n.border?.dashed??!1})}_determineSideFromPosition(t,n){if(!t.center||!n.center)return"left";let i=t.center.x-n.center.x,r=t.center.y-n.center.y;return Math.abs(i)>Math.abs(r)?i>0?"right":"left":r>0?"bottom":"top"}_calculateSchematicBounds(t){if(t.length===0)return{minX:0,maxX:0,minY:0,maxY:0};let n=1/0,i=-1/0,r=1/0,o=-1/0;for(let a of t)n=Math.min(n,a.centerX),i=Math.max(i,a.centerX),r=Math.min(r,a.centerY),o=Math.max(o,a.centerY);let s=2;return{minX:n-s,maxX:i+s,minY:r-s,maxY:o+s}}_getAutorouterConfig(){let t=this._parsedProps.autorouter||this.getInheritedProperty("autorouter");return Qvt(t)}_getSubcircuitLayerCount(){let t=this.getInheritedProperty("layers");return typeof t=="number"?t:2}_shouldUseTraceByTraceRouting(){return this._getAutorouterConfig().groupMode==="sequential-trace"}doInitialPcbDesignRuleChecks(){if(this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;let{db:t}=this.root;if(this.isSubcircuit){let n=new Map;for(let i of this.children)if(!i.isSubcircuit&&i._parsedProps.name){let r=n.get(i._parsedProps.name)||[];r.push(i),n.set(i._parsedProps.name,r)}for(let[i,r]of n.entries())r.length>1&&t.pcb_trace_error.insert({error_type:"pcb_trace_error",message:`Multiple components found with name "${i}" in subcircuit "${this.name||"unnamed"}". Component names must be unique within a subcircuit.`,source_trace_id:"",pcb_trace_id:"",pcb_component_ids:r.map(o=>o.pcb_component_id).filter(Boolean),pcb_port_ids:[]})}}doInitialSchematicReplaceNetLabelsWithSymbols(){if(this.root?.schematicDisabled||!this.isSubcircuit)return;let{db:t}=this.root,n=t;for(let i of n.schematic_net_label.list()){let r=n.source_net.get(i.source_net_id),o=i.text||r?.name||"";if(i.anchor_side==="top"&&/^gnd/i.test(o)){n.schematic_net_label.update(i.schematic_net_label_id,{symbol_name:"rail_down"});continue}i.anchor_side==="bottom"&&/^v/i.test(o)&&n.schematic_net_label.update(i.schematic_net_label_id,{symbol_name:"rail_up"})}}_getMinimumFlexContainerSize(){return super._getMinimumFlexContainerSize()}_repositionOnPcb(t){return super._repositionOnPcb(t)}},hY=(e,t,n)=>{let i=Math.min(n,e/2,t/2),r=Math.max(1,Math.ceil(Math.PI/2*i)),o=Math.PI/2/r,s=e/2,a=t/2,c=[];c.push({x:-s+i,y:-a}),c.push({x:s-i,y:-a});for(let l=1;l<=r;l++){let u=-Math.PI/2+l*o;c.push({x:s-i+i*Math.cos(u),y:-a+i+i*Math.sin(u)})}c.push({x:s,y:a-i});for(let l=1;l<=r;l++){let u=0+l*o;c.push({x:s-i+i*Math.cos(u),y:a-i+i*Math.sin(u)})}c.push({x:-s+i,y:a});for(let l=1;l<=r;l++){let u=Math.PI/2+l*o;c.push({x:-s+i+i*Math.cos(u),y:a-i+i*Math.sin(u)})}c.push({x:-s,y:-a+i});for(let l=1;l<=r;l++){let u=Math.PI+l*o;c.push({x:-s+i+i*Math.cos(u),y:-a+i+i*Math.sin(u)})}return c},DY=class extends th{constructor(){super(...arguments);T(this,"pcb_board_id",null);T(this,"_drcChecksComplete",!1);T(this,"_connectedSchematicPortPairs",new Set)}get isSubcircuit(){return!0}get isGroup(){return!0}get config(){return{componentName:"Board",zodProps:S5}}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:n}=this;if(n.width&&n.height)return;let i=1/0,r=1/0,o=-1/0,s=-1/0,a=AY(t,this.subcircuit_id),c=new Set([this.subcircuit_id,...a]),l=t.pcb_component.list().filter(R=>R.subcircuit_id&&c.has(R.subcircuit_id)),u=t.pcb_group.list().filter(R=>R.subcircuit_id&&c.has(R.subcircuit_id)),h=!1,f=(R,I,k)=>{I===0||k===0||(h=!0,i=Math.min(i,R.x-I/2),r=Math.min(r,R.y-k/2),o=Math.max(o,R.x+I/2),s=Math.max(s,R.y+k/2))};for(let R of l)f(R.center,R.width,R.height);for(let R of u)f(R.center,R.width,R.height);let _=2,y=h?o-i+_*2:0,x=h?s-r+_*2:0,v={x:h?(i+o)/2+(n.outlineOffsetX??0):n.outlineOffsetX??0,y:h?(r+s)/2+(n.outlineOffsetY??0):n.outlineOffsetY??0},w=n.width??y,S=n.height??x,C=n.outline;!C&&n.borderRadius!=null&&w>0&&S>0&&(C=hY(w,S,n.borderRadius));let E={width:w,height:S,center:v};C&&(E.outline=C.map(R=>({x:R.x+(n.outlineOffsetX??0),y:R.y+(n.outlineOffsetY??0)}))),t.pcb_board.update(this.pcb_board_id,E)}updatePcbBoardAutoSize(){this.doInitialPcbBoardAutoSize()}_addBoardInformationToSilkscreen(){let t=this.root?.platform;if(!t?.printBoardInformationToSilkscreen)return;let n=this.root.db.pcb_board.get(this.pcb_board_id);if(!n)return;let i=[];if(t.projectName&&i.push(t.projectName),t.version&&i.push(`v${t.version}`),t.url&&i.push(t.url),i.length===0)return;let r=i.join(`
231
- `),a={x:n.center.x+n.width/2-.25,y:n.center.y-n.height/2+1};this.root.db.pcb_silkscreen_text.insert({pcb_component_id:this.pcb_board_id,layer:"top",font:"tscircuit2024",font_size:.45,text:r,ccw_rotation:0,anchor_alignment:"bottom_right",anchor_position:a})}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=n.width??0,r=n.height??0,o={x:(n.pcbX??0)+(n.outlineOffsetX??0),y:(n.pcbY??0)+(n.outlineOffsetY??0)};if(n.outline){let c=n.outline.map(y=>y.x),l=n.outline.map(y=>y.y),u=Math.min(...c),h=Math.max(...c),f=Math.min(...l),_=Math.max(...l);i=h-u,r=_-f,o={x:(u+h)/2+(n.outlineOffsetX??0),y:(f+_)/2+(n.outlineOffsetY??0)}}let s=n.outline;!s&&n.borderRadius!=null&&i>0&&r>0&&(s=hY(i,r,n.borderRadius));let a=t.pcb_board.insert({center:o,thickness:this.boardThickness,num_layers:this.allLayers.length,width:i,height:r,outline:s?.map(c=>({x:c.x+(n.outlineOffsetX??0),y:c.y+(n.outlineOffsetY??0)})),material:n.material});this.pcb_board_id=a.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 vi()}doInitialPcbDesignRuleChecks(){this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled")||super.doInitialPcbDesignRuleChecks()}updatePcbDesignRuleChecks(){if(this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;let{db:t}=this.root;if(!this._areChildSubcircuitsRouted()||this._drcChecksComplete)return;this._drcChecksComplete=!0;let n=HB(t.toArray());for(let o of n)t.pcb_trace_error.insert(o);let i=VB(t.toArray());for(let o of i)t.pcb_port_not_connected_error.insert(o);let r=qB(t.toArray());for(let o of r)t.pcb_component_outside_board_error.insert(o)}_emitRenderLifecycleEvent(t,n){super._emitRenderLifecycleEvent(t,n),n==="start"&&this.root?.emit("board:renderPhaseStarted",{renderId:this._renderId,phase:t})}},vwt=new Proxy({},{get:(e,t)=>t}),zs=vwt,Lx="rgba(132, 0, 0)",Fx=.12,$Y=class extends In{constructor(){super(...arguments);T(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Capacitor",schematicSymbolName:this.props.polarized?"capacitor_polarized":this.props.symbolName??"capacitor",zodProps:SL,sourceFtype:zs.simple_capacitor}}initPorts(){typeof this.props.footprint=="string"?super.initPorts({additionalAliases:{pin1:["anode","pos"],pin2:["cathode","neg"]}}):super.initPorts()}_getSchematicSymbolDisplayValue(){let t=this.props.capacitance,n=typeof t=="string"?t:`${qn(this._parsedProps.capacitance)}F`;return this._parsedProps.schShowRatings&&this._parsedProps.maxVoltageRating?`${n}/${qn(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 yo({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.decouplingFor})),this.add(new yo({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.decouplingTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_capacitor",name:this.name,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,capacitance:n.capacitance,max_voltage_rating:n.maxVoltageRating,max_decoupling_trace_length:n.maxDecouplingTraceLength,display_capacitance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!n.polarized});this.source_component_id=i.source_component_id}},zx=class extends In{constructor(t){super(t);T(this,"schematicBoxDimensions",null)}get config(){return{componentName:"Chip",zodProps:lp,shouldRenderAsSchematicBox:!0}}initPorts(t={}){super.initPorts(t);let{_parsedProps:n}=this;if(n.externallyConnectedPins){let i=new Set;for(let[r,o]of n.externallyConnectedPins)i.add(r),i.add(o);for(let r of i)if(!this.children.find(s=>s instanceof Ei&&s.isMatchingAnyOf([r]))){let s=r.match(/^pin(\d+)$/);if(s){let a=parseInt(s[1]);this.add(new Ei({pinNumber:a,aliases:[r]}))}else this.add(new Ei({name:r,aliases:[r]}))}}}doInitialSchematicComponentRender(){let{_parsedProps:t}=this;t?.noSchematicRepresentation!==!0&&super.doInitialSchematicComponentRender()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:n.manufacturerPartNumber,supplier_part_numbers:n.supplierPartNumbers});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=t.pcb_component.insert({center:{x:n.pcbX??0,y:n.pcbY??0},width:2,height:3,layer:n.layer??"top",rotation:n.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:n.doNotPlace??!1,obstructs_within_bounds:n.obstructsWithinBounds??!0});this.pcb_component_id=i.pcb_component_id}doInitialCreateTracesFromProps(){let{_parsedProps:t}=this;if(t.externallyConnectedPins)for(let[n,i]of t.externallyConnectedPins)this.add(new yo({from:`${this.getSubcircuitSelector()} > port.${n}`,to:`${this.getSubcircuitSelector()} > port.${i}`}));this._createTracesFromConnectionsProp()}doInitialSimulationRender(){let{db:t}=this.root,{pinAttributes:n}=this.props;if(!n)return;let i=null,r=null,o,s=this.selectAll("port");for(let h of s)for(let f of h.getNameAndAliases())if(n[f]){let _=n[f];_.providesPower&&(i=h,o=_.providesVoltage),_.providesGround&&(r=h)}if(!i||!r||o===void 0)return;let a=t.source_port.get(i.source_port_id);if(!a?.subcircuit_connectivity_map_key)return;let c=t.source_port.get(r.source_port_id);if(!c?.subcircuit_connectivity_map_key)return;let l=t.source_net.getWhere({subcircuit_connectivity_map_key:a.subcircuit_connectivity_map_key}),u=t.source_net.getWhere({subcircuit_connectivity_map_key:c.subcircuit_connectivity_map_key});!l||!u||t.simulation_voltage_source.insert({type:"simulation_voltage_source",positive_source_port_id:i.source_port_id,positive_source_net_id:l.source_net_id,negative_source_port_id:r.source_port_id,negative_source_net_id:u.source_net_id,voltage:o})}},BY=class extends zx{constructor(e){super(e)}get config(){return{...super.config,componentName:"Pinout",zodProps:fL}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_pinout",name:this.name,manufacturer_part_number:t.manufacturerPartNumber,supplier_part_numbers:t.supplierPartNumbers});this.source_component_id=n.source_component_id}},jY=class extends In{constructor(){super(...arguments);T(this,"pos",this.portMap.pin1);T(this,"anode",this.portMap.pin1);T(this,"neg",this.portMap.pin2);T(this,"cathode",this.portMap.pin2)}get config(){let t={schottky:"schottky_diode",avalanche:"avalanche_diode",zener:"zener_diode",photodiode:"photodiode"},n=this.props.schottky?"schottky":this.props.avalanche?"avalanche":this.props.zener?"zener":this.props.photo?"photodiode":null;return{schematicSymbolName:n?t[n]:this.props.symbolName??"diode",componentName:"Diode",zodProps:$L,sourceFtype:"simple_diode"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_diode",name:this.name,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},YY=class extends In{get config(){return{componentName:"fuse",schematicSymbolName:this.props.symbolName??"fuse",zodProps:_L,sourceFtype:zs.simple_fuse}}_getSchematicSymbolDisplayValue(){let e=this._parsedProps.currentRating,t=this._parsedProps.voltageRating,n=typeof e=="string"?parseFloat(e):e,i=typeof t=="string"?parseFloat(t):t;return`${qn(n)}A / ${qn(i)}V`}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=typeof t.currentRating=="string"?parseFloat(t.currentRating):t.currentRating,i=typeof t.voltageRating=="string"?parseFloat(t.voltageRating):t.voltageRating,r=e.source_component.insert({name:this.name,ftype:zs.simple_fuse,current_rating_amps:n,voltage_rating_volts:i,display_current_rating:`${qn(n)}A`,display_voltage_rating:`${qn(i)}V`});this.source_component_id=r.source_component_id}},XY=class extends In{constructor(){super(...arguments);T(this,"schematicDimensions",null)}get config(){return{schematicSymbolName:void 0,componentName:"Jumper",zodProps:P5,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let t=super._getSchematicPortArrangement();if(t&&Object.keys(t).length>0)return t;let n=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length),i=this._parsedProps.schDirection??"right";return{leftSize:i==="left"?n:0,rightSize:i==="right"?n:0}}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:n.manufacturerPartNumber,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=t.pcb_component.insert({center:{x:n.pcbX??0,y:n.pcbY??0},width:2,height:3,layer:n.layer??"top",rotation:n.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:n.doNotPlace??!1,obstructs_within_bounds:n.obstructsWithinBounds??!0});this.pcb_component_id=i.pcb_component_id}doInitialPcbTraceRender(){let{db:t}=this.root,n=t.pcb_port.list({pcb_component_id:this.pcb_component_id}),i={};for(let s=0;s<n.length;s++){let a=n[s],c=t.source_port.get(a.source_port_id),l="";if(typeof c?.pin_number=="number")l=c.pin_number.toString();else if(Array.isArray(c?.port_hints)){let u=c.port_hints.find(h=>/^(pin)?\d+$/.test(h));u&&(/^pin\d+$/.test(u)?l=u.replace(/^pin/,""):l=u)}i[l]=a.pcb_port_id}let r=t.pcb_trace.list({pcb_component_id:this.pcb_component_id}),o=s=>{if(s&&typeof s=="string"&&s.startsWith("{PIN")){let a=s.replace("{PIN","").replace("}","");return i[a]||s}return s};for(let s of r)if(s.route)for(let a of s.route)a.route_type==="wire"&&(a.start_pcb_port_id=o(a.start_pcb_port_id),a.end_pcb_port_id=o(a.end_pcb_port_id))}},VY=class extends In{constructor(){super(...arguments);T(this,"schematicDimensions",null)}_getPinNumberFromBridgedPinName(t){return this.selectOne(`port.${t}`,{type:"port"})?._parsedProps.pinNumber??null}get defaultInternallyConnectedPinNames(){if(this._parsedProps.bridged){let t=this.children.filter(n=>n.componentName==="Port").map(n=>n.name);return t.length>0?[t]:[]}return this._parsedProps.bridgedPins??[]}get config(){let t=this._parsedProps??this.props,n=t.pinCount;if(t.pinCount==null&&!t.footprint&&(n=2),t.pinCount==null){let o=(t.bridgedPins??[]).flat().map(l=>this._getPinNumberFromBridgedPinName(l)).filter(l=>l!==null),s=o.length>0?Math.max(...o):0,a=t.pinLabels?Object.keys(t.pinLabels).length:0,c=Math.max(s,a);(c===2||c===3)&&(n=c),n==null&&t.footprint&&[2,3].includes(this.getPortsFromFootprint().length)&&(n=this.getPortsFromFootprint().length)}let i="";n?i+=`solderjumper${n}`:i="solderjumper";let r=[];return Array.isArray(t.bridgedPins)&&t.bridgedPins.length>0?r=Array.from(new Set(t.bridgedPins.flat().map(o=>this._getPinNumberFromBridgedPinName(o)).filter(o=>o!==null))).sort((o,s)=>o-s):t.bridged&&n&&(r=Array.from({length:n},(o,s)=>s+1)),r.length>0&&(i+=`_bridged${r.join("")}`),{schematicSymbolName:t.symbolName??i,componentName:"SolderJumper",zodProps:mL,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let t=super._getSchematicPortArrangement();if(t&&Object.keys(t).length>0)return t;let n=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length);n==null&&!this._parsedProps.footprint&&(n=2);let i=this._parsedProps.schDirection??"right";return{leftSize:i==="left"?n:0,rightSize:i==="right"?n:0}}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:n.manufacturerPartNumber,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=t.pcb_component.insert({center:{x:n.pcbX??0,y:n.pcbY??0},width:2,height:3,layer:n.layer??"top",rotation:n.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:n.doNotPlace??!1,obstructs_within_bounds:n.obstructsWithinBounds??!0});this.pcb_component_id=i.pcb_component_id}doInitialPcbTraceRender(){let{db:t}=this.root,n=t.pcb_port.list({pcb_component_id:this.pcb_component_id}),i={};for(let s=0;s<n.length;s++){let a=n[s],c=t.source_port.get(a.source_port_id),l="";if(typeof c?.pin_number=="number")l=c.pin_number.toString();else if(Array.isArray(c?.port_hints)){let u=c.port_hints.find(h=>/^(pin)?\d+$/.test(h));u&&(/^pin\d+$/.test(u)?l=u.replace(/^pin/,""):l=u)}i[l]=a.pcb_port_id}let r=t.pcb_trace.list({pcb_component_id:this.pcb_component_id}),o=s=>{if(s&&typeof s=="string"&&s.startsWith("{PIN")){let a=s.replace("{PIN","").replace("}","");return i[a]||s}return s};for(let s of r)if(s.route)for(let a of s.route)a.route_type==="wire"&&(a.start_pcb_port_id=o(a.start_pcb_port_id),a.end_pcb_port_id=o(a.end_pcb_port_id))}},HY=class extends In{constructor(){super(...arguments);T(this,"pos",this.portMap.pin1);T(this,"anode",this.portMap.pin1);T(this,"neg",this.portMap.pin2);T(this,"cathode",this.portMap.pin2)}get config(){let t={laser:"laser_diode"},n=this.props.laser?"laser":null;return{schematicSymbolName:n?t[n]:this.props.symbolName??"led",componentName:"Led",zodProps:jL,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:n}=this,i=t.source_component.insert({ftype:"simple_led",name:this.name,wave_length:n.wavelength,color:n.color,symbol_display_value:this._getSchematicSymbolDisplayValue(),manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},GY=class extends In{constructor(){super(...arguments);T(this,"pos",this.portMap.pin1);T(this,"positive",this.portMap.pin1);T(this,"neg",this.portMap.pin2);T(this,"negative",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"power_factor_meter_horz",componentName:"PowerSource",zodProps:QL,sourceFtype:"simple_power_source"}}initPorts(){this.add(new Ei({name:"pin1",pinNumber:1,aliases:["positive","pos"]})),this.add(new Ei({name:"pin2",pinNumber:2,aliases:["negative","neg"]}))}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_power_source",name:this.name,voltage:n.voltage,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},wwt=Fn.extend({voltage:Qn.optional(),frequency:po.optional(),peakToPeakVoltage:Qn.optional(),waveShape:p.enum(["sinewave","square","triangle","sawtooth"]).optional(),phase:Fe.optional(),dutyCycle:p.number().optional()}),UY=class extends In{constructor(){super(...arguments);T(this,"terminal1",this.portMap.terminal1);T(this,"terminal2",this.portMap.terminal2)}get config(){return{componentName:"VoltageSource",schematicSymbolName:this.props.waveShape==="square"?"square_wave":"ac_voltmeter",zodProps:wwt,sourceFtype:"simple_voltage_source"}}runRenderPhaseForChildren(t){if(!t.startsWith("Pcb"))for(let n of this.children)n.runRenderPhaseForChildren(t),n.runRenderPhase(t)}doInitialPcbComponentRender(){}initPorts(){super.initPorts({additionalAliases:{pin1:["terminal1"],pin2:["terminal2"]}})}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_voltage_source",name:this.name,voltage:n.voltage,frequency:n.frequency,peak_to_peak_voltage:n.peakToPeakVoltage,wave_shape:n.waveShape,phase:n.phase,duty_cycle:n.dutyCycle,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialSimulationRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=this.portMap.terminal1,r=this.portMap.terminal2;t.simulation_voltage_source.insert({type:"simulation_voltage_source",is_dc_source:!1,terminal1_source_port_id:i.source_port_id,terminal2_source_port_id:r.source_port_id,voltage:n.voltage,frequency:n.frequency,peak_to_peak_voltage:n.peakToPeakVoltage,wave_shape:n.waveShape,phase:n.phase,duty_cycle:n.dutyCycle})}},qY=class extends In{constructor(){super(...arguments);T(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Resistor",schematicSymbolName:this.props.symbolName??"boxresistor",zodProps:gL,sourceFtype:"simple_resistor"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return`${qn(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 yo({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pullupFor})),this.add(new yo({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pullupTo}))),this.props.pulldownFor&&this.props.pulldownTo&&(this.add(new yo({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pulldownFor})),this.add(new yo({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pulldownTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_resistor",name:this.name,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,resistance:n.resistance,display_resistance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}},Swt=["leftedge","rightedge","topedge","bottomedge","center"],WY=class extends Ie{get config(){return{componentName:"Constraint",zodProps:TL}}constructor(e){if(super(e),("xdist"in e||"ydist"in e)&&!("edgeToEdge"in e)&&!("centerToCenter"in e))throw new Error(`edgeToEdge, centerToCenter must be set for xDist or yDist for ${this}`);if("for"in e&&e.for.length<2)throw new Error(`"for" must have at least two selectors for ${this}`)}_getAllReferencedComponents(){let e=[],t=this.getPrimitiveContainer();function n(i){let r=i.split(" ").pop(),o=Swt.includes(r)?r:void 0,s=o?i.replace(` ${o}`,""):i,a=t.selectOne(s,{pcbPrimitive:!0});a&&e.push({selector:i,component:a,componentSelector:s,edge:o})}for(let i of["left","right","top","bottom"])i in this._parsedProps&&n(this._parsedProps[i]);if("for"in this._parsedProps)for(let i of this._parsedProps.for)n(i);return{componentsWithSelectors:e}}},ZY=class extends Ie{constructor(){super(...arguments);T(this,"fabrication_note_path_id",null)}get config(){return{componentName:"FabricationNotePath",zodProps:HL}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,n=this.getSubcircuit(),{_parsedProps:i}=this,r=i.layer??"top";if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenPath. Must be "top" or "bottom".`);let o=this._computePcbGlobalTransformBeforeLayout(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=t.pcb_fabrication_note_path.insert({pcb_component_id:s,layer:r,color:i.color,route:i.route.map(c=>{let l=kn(o,{x:c.x,y:c.y});return{...c,x:l.x,y:l.y}}),stroke_width:i.strokeWidth??.1,subcircuit_id:n?.subcircuit_id??void 0});this.fabrication_note_path_id=a.pcb_fabrication_note_path_id}},KY=class extends Ie{get config(){return{componentName:"FabricationNoteText",zodProps:VL}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,n=this.getPrimitiveContainer(),i=this.getSubcircuit();e.pcb_fabrication_note_text.insert({anchor_alignment:t.anchorAlignment,anchor_position:{x:t.pcbX??0,y:t.pcbY??0},font:t.font??"tscircuit2024",font_size:t.fontSize??1,layer:"top",color:t.color,text:t.text??"",pcb_component_id:n.pcb_component_id,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}},JY=class extends th{constructor(e){super({...e,subcircuit:!0})}},QY=class extends th{constructor(e){super({...e,subcircuit:!0})}doInitialPcbPrimitiveRender(){if(super.doInitialPcbPrimitiveRender(),this.root?.pcbDisabled)return;let{db:e}=this.root,t=this._parsedProps;if(!this.pcb_group_id)return;let n=e.pcb_group.get(this.pcb_group_id),i=t.paddingLeft??t.padding??0,r=t.paddingRight??t.padding??0,o=t.paddingTop??t.padding??0,s=t.paddingBottom??t.padding??0;e.pcb_group.update(this.pcb_group_id,{width:n.width+i+r,height:n.height+o+s,center:{x:n.center.x+(r-i)/2,y:n.center.y+(o-s)/2}})}},tX=class extends Ie{constructor(){super(...arguments);T(this,"pcb_breakout_point_id",null);T(this,"matchedPort",null);T(this,"matchedNet",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"BreakoutPoint",zodProps:qL}}_matchConnection(){let{connection:t}=this._parsedProps,n=this.getSubcircuit();n&&(this.matchedPort=n.selectOne(t,{type:"port"}),this.matchedPort||(this.matchedNet=n.selectOne(t,{type:"net"})),!this.matchedPort&&!this.matchedNet&&this.renderError(`Could not find connection target "${t}"`))}_getSourceTraceIdForPort(t){let{db:n}=this.root;return n.source_trace.list().find(r=>r.connected_source_port_ids.includes(t.source_port_id))?.source_trace_id}_getSourceNetIdForPort(t){let{db:n}=this.root;return n.source_trace.list().find(r=>r.connected_source_port_ids.includes(t.source_port_id))?.connected_source_net_ids[0]}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root;this._matchConnection();let{pcbX:n=0,pcbY:i=0}=this._parsedProps,r=this.parent?.getGroup(),o=this.getSubcircuit();if(!r||!r.pcb_group_id)return;let s=t.pcb_breakout_point.insert({pcb_group_id:r.pcb_group_id,subcircuit_id:o?.subcircuit_id??void 0,source_port_id:this.matchedPort?.source_port_id??void 0,source_trace_id:this.matchedPort?this._getSourceTraceIdForPort(this.matchedPort):void 0,source_net_id:this.matchedNet?this.matchedNet.source_net_id:this.matchedPort?this._getSourceNetIdForPort(this.matchedPort):void 0,x:n,y:i});this.pcb_breakout_point_id=s.pcb_breakout_point_id}_getPcbCircuitJsonBounds(){let{pcbX:t=0,pcbY:n=0}=this._parsedProps;return{center:{x:t,y:n},bounds:{left:t,top:n,right:t,bottom:n},width:0,height:0}}_setPositionFromLayout(t){let{db:n}=this.root;this.pcb_breakout_point_id&&n.pcb_breakout_point.update(this.pcb_breakout_point_id,{x:t.x,y:t.y})}getPcbSize(){return{width:0,height:0}}},eX=class extends Ie{constructor(){super(...arguments);T(this,"source_net_label_id")}get config(){return{componentName:"NetLabel",zodProps:OL}}_getAnchorSide(){let{_parsedProps:t}=this;if(t.anchorSide)return t.anchorSide;if(!this._resolveConnectsTo())return"right";let i=this._getGlobalSchematicPositionBeforeLayout(),r=this._getConnectedPorts();if(r.length===0)return"right";let o=r[0]._getGlobalSchematicPositionBeforeLayout(),s=o.x-i.x,a=o.y-i.y;if(Math.abs(s)>Math.abs(a)){if(s>0)return"right";if(s<0)return"left"}else{if(a>0)return"top";if(a<0)return"bottom"}return"right"}_getConnectedPorts(){let t=this._resolveConnectsTo();if(!t)return[];let n=[];for(let i of t){let r=this.getSubcircuit().selectOne(i);r&&n.push(r)}return n}computeSchematicPropsTransform(){let{_parsedProps:t}=this;if(t.schX===void 0&&t.schY===void 0){let n=this._getConnectedPorts();if(n.length>0){let i=n[0]._getGlobalSchematicPositionBeforeLayout(),r=kn(this.parent?.computeSchematicGlobalTransform?.()??vi(),{x:0,y:0});return fn(i.x-r.x,i.y-r.y)}}return super.computeSchematicPropsTransform()}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getSubcircuit().selectOne(`net.${this._getNetName()}`),o=n.anchorSide??"right",s=Ka({anchor_position:i,anchor_side:o,text:n.net}),a=t.schematic_net_label.insert({text:n.net,source_net_id:r.source_net_id,anchor_position:i,center:s,anchor_side:this._getAnchorSide()});this.source_net_label_id=a.source_net_id}_resolveConnectsTo(){let{_parsedProps:t}=this,n=t.connectsTo??t.connection;if(Array.isArray(n))return n;if(typeof n=="string")return[n]}_getNetName(){let{_parsedProps:t}=this;return t.net}doInitialCreateNetsFromProps(){let{_parsedProps:t}=this;t.net&&cI(this,[`net.${t.net}`])}doInitialCreateTracesFromNetLabels(){if(this.root?.schematicDisabled)return;let t=this._resolveConnectsTo();if(t)for(let n of t)this.add(new yo({from:n,to:`net.${this._getNetName()}`}))}doInitialSchematicTraceRender(){if(!this.root?._featureMspSchematicTraceRouting||this.root?.schematicDisabled)return;let{db:t}=this.root,n=this._resolveConnectsTo();if(!n||n.length===0)return;let i=this._getGlobalSchematicPositionBeforeLayout(),r=this._getAnchorSide(),s={left:"x-",right:"x+",top:"y+",bottom:"y-"}[r],a=this.getSubcircuit().selectOne(`net.${this._getNetName()}`);for(let c of n){let l=this.getSubcircuit().selectOne(c,{type:"port"});if(!l||!l.schematic_port_id)continue;let u=!1;if(a?.source_net_id){let w=t.source_trace.list().find(S=>S.connected_source_net_ids?.includes(a.source_net_id)&&S.connected_source_port_ids?.includes(l.source_port_id??""));if(w&&(u=t.schematic_trace.list().some(S=>S.source_trace_id===w.source_trace_id)),u)continue}let h=l._getGlobalSchematicPositionAfterLayout(),f=tI(l.facingDirection??"right")??"x+",_=Na({x:h.x,y:h.y,facingDirection:f},{x:i.x,y:i.y,facingDirection:s});if(!Array.isArray(_)||_.length<2)continue;let y=[];for(let w=0;w<_.length-1;w++)y.push({from:{x:_[w].x,y:_[w].y},to:{x:_[w+1].x,y:_[w+1].y}});let x,v;if(a?.source_net_id&&l.source_port_id){let w=t.source_trace.list().find(S=>S.connected_source_net_ids?.includes(a.source_net_id)&&S.connected_source_port_ids?.includes(l.source_port_id));x=w?.source_trace_id,v=w?.subcircuit_connectivity_map_key||t.source_net.get(a.source_net_id)?.subcircuit_connectivity_map_key}t.schematic_trace.insert({source_trace_id:x,edges:y,junctions:[],subcircuit_connectivity_map_key:v}),t.schematic_port.update(l.schematic_port_id,{is_connected:!0})}}},nX=class extends Ie{constructor(){super(...arguments);T(this,"pcb_silkscreen_circle_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenCircle",zodProps:dF}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(n.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenCircle. Must be "top" or "bottom".`);let o=this._computePcbGlobalTransformBeforeLayout(),s=this.getSubcircuit(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,c=t.pcb_silkscreen_circle.insert({pcb_component_id:a,layer:r,center:{x:n.pcbX??0,y:n.pcbY??0},radius:n.radius,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,stroke_width:n.strokeWidth??.1});this.pcb_silkscreen_circle_id=c.pcb_silkscreen_circle_id}getPcbSize(){let{_parsedProps:t}=this,n=t.radius*2;return{width:n,height:n}}},iX=class extends Ie{constructor(){super(...arguments);T(this,"pcb_silkscreen_rect_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenRect",zodProps:hF}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(n.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenRect. Must be "top" or "bottom".`);let o=this.getSubcircuit(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=t.pcb_silkscreen_rect.insert({pcb_component_id:s,layer:r,center:{x:n.pcbX??0,y:n.pcbY??0},width:n.width,height:n.height,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this?.getGroup()?.pcb_group_id??void 0,stroke_width:n.strokeWidth??.1});this.pcb_silkscreen_rect_id=a.pcb_silkscreen_rect_id}getPcbSize(){let{_parsedProps:t}=this;return{width:t.width,height:t.height}}},rX=class extends Ie{constructor(){super(...arguments);T(this,"pcb_silkscreen_line_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenLine",zodProps:pF}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(n.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenLine. Must be "top" or "bottom".`);let o=this.getSubcircuit(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=t.pcb_silkscreen_line.insert({pcb_component_id:s,layer:r,x1:n.x1,y1:n.y1,x2:n.x2,y2:n.y2,stroke_width:n.strokeWidth??.1,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:o?.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_line_id=a.pcb_silkscreen_line_id}getPcbSize(){let{_parsedProps:t}=this,n=Math.abs(t.x2-t.x1),i=Math.abs(t.y2-t.y1);return{width:n,height:i}}},oX=class extends Ie{constructor(t){super(t);T(this,"pcb_via_id",null);T(this,"matchedPort",null);T(this,"isPcbPrimitive",!0);T(this,"source_manually_placed_via_id",null);let n=this._getLayers();this._parsedProps.layers=n,this.initPorts()}get config(){return{componentName:"Via",zodProps:GL}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){let{_parsedProps:t}=this;return{width:t.outerDiameter,height:t.outerDiameter}}_getPcbCircuitJsonBounds(){let{db:t}=this.root,n=t.pcb_via.get(this.pcb_via_id),i=this.getPcbSize();return{center:{x:n.x,y:n.y},bounds:{left:n.x-i.width/2,top:n.y-i.height/2,right:n.x+i.width/2,bottom:n.y+i.height/2},width:i.width,height:i.height}}_setPositionFromLayout(t){let{db:n}=this.root;n.pcb_via.update(this.pcb_via_id,{x:t.x,y:t.y})}_getLayers(){let{fromLayer:t="top",toLayer:n="bottom"}=this._parsedProps;return t===n?[t]:[t,n]}initPorts(){let t=this._parsedProps.layers;for(let i of t){let r=new Ei({name:i,layer:i});r.registerMatch(this),this.add(r)}let n=new Ei({name:"pin1"});n.registerMatch(this),this.add(n)}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalPcbPositionBeforeLayout(),r=this.getSubcircuit(),o=t.pcb_component.insert({center:i,width:n.outerDiameter,height:n.outerDiameter,layer:n.fromLayer??"top",rotation:0,source_component_id:this.source_component_id,subcircuit_id:r?.subcircuit_id??void 0,obstructs_within_bounds:!0});this.pcb_component_id=o.pcb_component_id}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=this.getGroup(),r=this.getSubcircuit(),o=t.source_manually_placed_via.insert({source_group_id:i?.source_group_id,source_net_id:n.net??"",subcircuit_id:r?.subcircuit_id??void 0});this.source_component_id=o.source_manually_placed_via_id}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalPcbPositionBeforeLayout(),r=this.getSubcircuit(),o=t.pcb_via.insert({x:i.x,y:i.y,hole_diameter:n.holeDiameter,outer_diameter:n.outerDiameter,layers:["bottom","top"],from_layer:n.fromLayer||"bottom",to_layer:n.toLayer||"top",subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_via_id=o.pcb_via_id}},sX=class extends Ie{constructor(){super(...arguments);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"CopperPour",zodProps:ZL}}getPcbSize(){return{width:0,height:0}}doInitialPcbCopperPourRender(){this.root?.pcbDisabled||this._queueAsyncEffect("PcbCopperPourRender",async()=>{let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit().selectOne(n.connectsTo);if(!i||!i.source_net_id){this.renderError(`Net "${n.connectsTo}" not found for copper pour`);return}let r=t.pcb_board.list()[0];if(!r){this.renderError("No board found for copper pour");return}let o;r.outline&&r.outline.length>0?o=new F.Polygon(r.outline.map(_=>F.point(_.x,_.y))):o=new F.Polygon(new F.Box(r.center.x-r.width/2,r.center.y-r.height/2,r.center.x+r.width/2,r.center.y+r.height/2).toPoints());let s=ar(t.toArray()),a=hI(t.toArray(),s).filter(_=>_.layers.includes(n.layer));for(let _ of t.pcb_trace.list())if(_.route)for(let y=0;y<_.route.length-1;y++){let x=_.route[y],v=_.route[y+1];if(x.route_type!=="wire"||v.route_type!=="wire"||x.layer!==n.layer)continue;let w=x.width;if(w===0)continue;let S=Math.hypot(x.x-v.x,x.y-v.y);if(S===0)continue;let C=(x.x+v.x)/2,E=(x.y+v.y)/2,R=Math.atan2(v.y-x.y,v.x-x.x)*180/Math.PI,k=MY({center:{x:C,y:E},width:S,height:w,rotation:R});for(let M of k)a.push({type:"rect",layers:[x.layer],center:M.center,width:M.width,height:M.height,connectedTo:_.source_trace_id?[_.source_trace_id]:[],obstacle_type:"trace"})}let c=[],l=[],u=n.traceMargin??.2,h=n.padMargin??.2;for(let _ of a){if(_.connectedTo.some(w=>s.areIdsConnected(w,i.source_net_id)))continue;if(_.type==="oval"&&_.width===_.height){let w=_.width/2+h;l.push({center:_.center,radius:w});continue}if(_.type==="rect"&&_.width===_.height&&_.connectedTo.length===0){let w=_.width/2;l.push({center:_.center,radius:w});continue}let x=u,v=new F.Box(_.center.x-_.width/2-x,_.center.y-_.height/2-x,_.center.x+_.width/2+x,_.center.y+_.height/2+x);c.push(new F.Polygon(v.toPoints()))}let f=o;if(c.length>0){let _=c.reduce((y,x)=>F.BooleanOperations.unify(y,x));_&&!_.isEmpty()&&(f=F.BooleanOperations.subtract(o,_))}Array.isArray(f)||(f=[f]);for(let _ of f){let y=_.splitToIslands();for(let x of y){if(x.isEmpty())continue;let v=[...x.faces],w=v.find(I=>I.orientation()===F.ORIENTATION.CCW),S=v.filter(I=>I.orientation()===F.ORIENTATION.CW);if(!w)continue;if(!t.pcb_copper_pour){this.renderError("db.pcb_copper_pour not found. The database schema may be outdated.");return}let C=I=>I.edges.map(k=>{let M={x:k.start.x,y:k.start.y};if(k.isArc){let A=Math.tan(k.shape.sweep/4);Math.abs(A)>1e-9&&(M.bulge=A)}return M});w.reverse();let E=C(w),R=S.map(I=>(I.reverse(),{vertices:C(I)}));for(let I of l){let k=F.point(I.center.x,I.center.y);x.contains(k)&&R.push({vertices:[{x:I.center.x,y:I.center.y-I.radius,bulge:1},{x:I.center.x,y:I.center.y+I.radius,bulge:1}]})}t.pcb_copper_pour.insert({shape:"brep",layer:n.layer,brep_shape:{outer_ring:{vertices:E},inner_rings:R},source_net_id:i.source_net_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id??void 0})}}})}},aX=class extends In{get config(){return{componentName:"Battery",schematicSymbolName:this.props.symbolName??"battery",zodProps:NL,sourceFtype:"simple_power_source"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:this.name,ftype:"simple_power_source",capacity:t.capacity,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=n.source_component_id}},cX=class extends In{_getPcbRotationBeforeLayout(){let e=this.props.pcbOrientation==="vertical"?-90:0;return(super._getPcbRotationBeforeLayout()??0)+e}get config(){return{componentName:"PinHeader",zodProps:RL,shouldRenderAsSchematicBox:!0}}_getImpliedFootprintString(){let e=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:0),t=this._parsedProps.holeDiameter,n=this._parsedProps.platedDiameter,i=this._parsedProps.pitch,r=this._parsedProps.showSilkscreenPinLabels;if(e>0){let o;if(i)!t&&!n?o=`pinrow${e}_p${i}`:o=`pinrow${e}_p${i}_id${t}_od${n}`;else if(!t&&!n)o=`pinrow${e}`;else return null;return r!==!0&&(o+="_nopinlabels"),o}return null}initPorts(){let e=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:1);for(let t=1;t<=e;t++){let n=Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels[t-1]:this._parsedProps.pinLabels?.[`pin${t}`];if(n){let i=Array.isArray(n)?n[0]:n,r=Array.isArray(n)?n.slice(1):[];this.add(new Ei({pinNumber:t,name:i,aliases:[`pin${t}`,...r]}))}else this.add(new Ei({pinNumber:t,name:`pin${t}`}))}}_getSchematicPortArrangement(){let e=this._parsedProps.pinCount??1,t=this._parsedProps.schFacingDirection??this._parsedProps.facingDirection??"right",n=this._parsedProps.schPinArrangement;return t==="left"?{leftSide:{direction:n?.leftSide?.direction??"top-to-bottom",pins:n?.leftSide?.pins??Array.from({length:e},(i,r)=>`pin${r+1}`)}}:{rightSide:{direction:n?.rightSide?.direction??"top-to-bottom",pins:n?.rightSide?.pins??Array.from({length:e},(i,r)=>`pin${r+1}`)}}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_pin_header",name:this.name,supplier_part_numbers:t.supplierPartNumbers,pin_count:t.pinCount,gender:t.gender,are_pins_interchangeable:!0});this.source_component_id=n.source_component_id}};function Pwt(e){switch(e){case"two_ground_pins":return"crystal_4pin";case"ground_pin":return"resonator";case"no_ground":return"crystal";default:return"crystal"}}var lX=class extends In{get config(){return{componentName:"Resonator",schematicSymbolName:this.props.symbolName??Pwt(this.props.pinVariant),zodProps:wL,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=t.pinVariant||"no_ground",i=e.source_component.insert({ftype:"simple_resonator",name:this.name,frequency:t.frequency,load_capacitance:t.loadCapacitance,supplier_part_numbers:t.supplierPartNumbers,pin_variant:n,are_pins_interchangeable:n==="no_ground"||n==="ground_pin"});this.source_component_id=i.source_component_id}_getSchematicSymbolDisplayValue(){let e=`${qn(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${e} / ${qn(this._parsedProps.loadCapacitance)}F`:e}},uX=class extends In{constructor(){super(...arguments);T(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Inductor",schematicSymbolName:this.props.symbolName??"inductor",zodProps:DL,sourceFtype:zs.simple_inductor}}_getSchematicSymbolDisplayValue(){return`${qn(this._parsedProps.inductance)}H`}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({name:this.name,ftype:zs.simple_inductor,inductance:n.inductance,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}};function Twt(e){switch(e){case"three_pin":return"potentiometer3";case"two_pin":return"potentiometer2";default:return"potentiometer2"}}var pX=class extends In{get config(){return{componentName:"Potentiometer",schematicSymbolName:this.props.symbolName??Twt(this.props.pinVariant),zodProps:bL,shouldRenderAsSchematicBox:!1}}_getSchematicSymbolDisplayValue(){return`${qn(this._parsedProps.maxResistance)}\u03A9`}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=t.pinVariant||"two_pin",i=e.source_component.insert({ftype:"simple_potentiometer",name:this.name,max_resistance:t.maxResistance,pin_variant:n,are_pins_interchangeable:n==="two_pin"});this.source_component_id=i.source_component_id}},hX=class extends In{get config(){return{componentName:"PushButton",schematicSymbolName:this.props.symbolName??"push_button_normally_open_momentary",zodProps:LL,sourceFtype:zs.simple_push_button}}get defaultInternallyConnectedPinNames(){return[]}initPorts(){super.initPorts({pinCount:2,ignoreSymbolPorts:!0});let e=Un[this._getSchematicSymbolNameOrThrow()],t=e.ports.find(l=>l.labels.includes("1")),n=e.ports.find(l=>l.labels.includes("2")),i=this.selectAll("port"),r=i.find(l=>l.props.pinNumber===1),o=i.find(l=>l.props.pinNumber===2),s=i.find(l=>l.props.pinNumber===3),a=i.find(l=>l.props.pinNumber===4),{internallyConnectedPins:c}=this._parsedProps;r.schematicSymbolPortDef=t,(!c||c.length===0)&&(o.schematicSymbolPortDef=n);for(let[l,u]of[[2,o],[3,s],[4,a]]){let h=c?.find(([_,y])=>_===`pin${l}`||y===`pin${l}`);if(!h){u.schematicSymbolPortDef=n;break}(h?.[0]===`pin${l}`?h[1]:h?.[0])!=="pin1"&&(u.schematicSymbolPortDef=n)}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:this.name,ftype:zs.simple_push_button,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=n.source_component_id}},dX=class extends In{get config(){return{schematicSymbolName:this.props.symbolName??(this.props.pinVariant==="four_pin"?"crystal_4pin":"crystal"),componentName:"Crystal",zodProps:vL,sourceFtype:"simple_crystal"}}initPorts(){let e=this.props.pinVariant==="four_pin"?{pin1:["left1","1"],pin2:["top1","2","gnd1"],pin3:["right1","3"],pin4:["bottom1","4","gnd2"]}:{pin1:["pos","left"],pin2:["neg","right"]};super.initPorts({additionalAliases:e})}_getSchematicSymbolDisplayValue(){let e=`${qn(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${e} / ${qn(this._parsedProps.loadCapacitance)}F`:e}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:this.name,ftype:"simple_crystal",frequency:t.frequency,load_capacitance:t.loadCapacitance,pin_variant:t.pinVariant||"two_pin",are_pins_interchangeable:(t.pinVariant||"two_pin")==="two_pin"});this.source_component_id=n.source_component_id}},fX=class extends In{constructor(){super(...arguments);T(this,"emitter",this.portMap.pin1);T(this,"collector",this.portMap.pin2);T(this,"base",this.portMap.pin3)}get config(){let t=this.props.type==="npn"?"npn_bipolar_transistor":"pnp_bipolar_transistor";return{componentName:"Transistor",schematicSymbolName:this.props.symbolName??t,zodProps:FL,sourceFtype:"simple_transistor",shouldRenderAsSchematicBox:!1}}initPorts(){let t={pin1:["collector","c"],pin2:["emitter","e"],pin3:["base","b"]};super.initPorts({pinCount:3,additionalAliases:t})}doInitialCreateNetsFromProps(){this._createNetsFromProps([...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_transistor",name:this.name,transistor_type:n.type});this.source_component_id=i.source_component_id}},mX=class extends In{get config(){let e=this.props.mosfetMode==="depletion"?"d":"e",n=`${this.props.channelType}_channel_${e}_mosfet_transistor`;return{componentName:"Mosfet",schematicSymbolName:this.props.symbolName??n,zodProps:zL,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_mosfet",name:this.name,mosfet_mode:t.mosfetMode,channel_type:t.channelType});this.source_component_id=n.source_component_id}},_X=class extends In{_getSwitchType(){let{spst:e,spdt:t,dpst:n,dpdt:i,type:r}=this._parsedProps??{};return i?"dpdt":e?"spst":t?"spdt":n?"dpst":r??"spst"}get config(){let e=this._getSwitchType(),{isNormallyClosed:t}=this._parsedProps??{},i={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"}[e]??"spst_switch";return{componentName:"Switch",schematicSymbolName:this.props.symbolName??i,zodProps:XL,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.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=n.source_component_id}},KT={HOLE_DIAMETER:.5,SMT_CIRCLE_DIAMETER:1.2,SMT_RECT_SIZE:2},yX=class extends In{get config(){return{componentName:"TestPoint",schematicSymbolName:this.props.symbolName??"testpoint",zodProps:UL,sourceFtype:zs.simple_test_point}}_getPropsWithDefaults(){let{padShape:e,holeDiameter:t,footprintVariant:n,padDiameter:i,width:r,height:o}=this._parsedProps;return!n&&t&&(n="through_hole"),n??(n="through_hole"),e??(e="circle"),n==="pad"?e==="circle"?i??(i=KT.SMT_CIRCLE_DIAMETER):e==="rect"&&(r??(r=KT.SMT_RECT_SIZE),o??(o=r)):n==="through_hole"&&(t??(t=KT.HOLE_DIAMETER)),{padShape:e,holeDiameter:t,footprintVariant:n,padDiameter:i,width:r,height:o}}_getImpliedFootprintString(){let{padShape:e,holeDiameter:t,footprintVariant:n,padDiameter:i,width:r,height:o}=this._getPropsWithDefaults();if(n==="through_hole")return`platedhole_d${t}`;if(n==="pad"){if(e==="circle")return`smtpad_circle_d${i}`;if(e==="rect")return`smtpad_rect_w${r}_h${o}`}throw new Error(`Footprint variant "${n}" with pad shape "${e}" not implemented`)}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,{padShape:n,holeDiameter:i,footprintVariant:r,padDiameter:o,width:s,height:a}=this._getPropsWithDefaults(),c=e.source_component.insert({ftype:zs.simple_test_point,name:this.name,supplier_part_numbers:t.supplierPartNumbers,footprint_variant:r,pad_shape:n,pad_diameter:o,hole_diameter:i,width:s,height:a,are_pins_interchangeable:!0});this.source_component_id=c.source_component_id}},gX=class extends Ie{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicText",zodProps:oF}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout();t.schematic_text.insert({anchor:n.anchor??"center",text:n.text,font_size:n.fontSize,color:n.color||"#000000",position:{x:i.x,y:i.y},rotation:n.schRotation??0})}},xX=class extends Ie{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0);T(this,"schematic_line_id")}get config(){return{componentName:"SchematicLine",zodProps:rF}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,o=t.schematic_line.insert({schematic_component_id:r,x1:n.x1+i.x,y1:n.y1+i.y,x2:n.x2+i.x,y2:n.y2+i.y,stroke_width:Fx,color:Lx,is_dashed:!1,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_line_id=o.schematic_line_id}},bX=class extends Ie{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0);T(this,"schematic_rect_id")}get config(){return{componentName:"SchematicRect",zodProps:iF}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,o=t.schematic_rect.insert({center:{x:n.center.x+i.x,y:n.center.y+i.y},width:n.width,height:n.height,stroke_width:Fx,color:Lx,is_filled:n.isFilled,schematic_component_id:r,is_dashed:n.isDashed,rotation:n.rotation??0,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_rect_id=o.schematic_rect_id}},vX=class extends Ie{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0);T(this,"schematic_arc_id")}get config(){return{componentName:"SchematicArc",zodProps:tF}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,o=t.schematic_arc.insert({schematic_component_id:r,center:{x:n.center.x+i.x,y:n.center.y+i.y},radius:n.radius,start_angle_degrees:n.startAngleDegrees,end_angle_degrees:n.endAngleDegrees,direction:n.direction,stroke_width:Fx,color:Lx,is_dashed:n.isDashed,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_arc_id=o.schematic_arc_id}},wX=class extends Ie{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0);T(this,"schematic_circle_id")}get config(){return{componentName:"SchematicCircle",zodProps:nF}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,o=t.schematic_circle.insert({schematic_component_id:r,center:{x:n.center.x+i.x,y:n.center.y+i.y},radius:n.radius,stroke_width:Fx,color:Lx,is_filled:n.isFilled,fill_color:n.fillColor,is_dashed:n.isDashed,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_circle_id=o.schematic_circle_id}};function Iwt({anchor:e,x:t,y:n,width:i,height:r,isInside:o}){switch(e){case"top_left":return{x:t,y:n+r,textAnchor:o?"top_left":"bottom_left"};case"top_center":return{x:t+i/2,y:n+r,textAnchor:o?"top_center":"bottom_center"};case"top_right":return{x:t+i,y:n+r,textAnchor:o?"top_right":"bottom_right"};case"center_left":return{x:t,y:n+r/2,textAnchor:o?"center_left":"center_right"};case"center":return{x:t+i/2,y:n+r/2,textAnchor:"center"};case"center_right":return{x:t+i,y:n+r/2,textAnchor:o?"center_right":"center_left"};case"bottom_left":return{x:t,y:n,textAnchor:o?"bottom_left":"top_left"};case"bottom_center":return{x:t+i/2,y:n,textAnchor:o?"bottom_center":"top_center"};case"bottom_right":return{x:t+i,y:n,textAnchor:o?"bottom_right":"top_right"};default:return{x:t+i/2,y:n+r,textAnchor:"center"}}}var SX=class extends Ie{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicBox",zodProps:eF,shouldRenderAsSchematicBox:!0}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=.6,r=typeof n.padding=="number"?n.padding:0,o=typeof n.paddingTop=="number"?n.paddingTop:r,s=typeof n.paddingBottom=="number"?n.paddingBottom:r,a=typeof n.paddingLeft=="number"?n.paddingLeft:r,c=typeof n.paddingRight=="number"?n.paddingRight:r,l=n.overlay&&n.overlay.length>0,u=typeof n.width=="number"&&typeof n.height=="number",h,f,_,y,x,v;if(l){let S=n.overlay.map(et=>({selector:et,port:this.getSubcircuit().selectOne(et,{type:"port"})})).filter(({port:et})=>et!=null).map(({port:et})=>({position:et._getGlobalSchematicPositionAfterLayout()}));if(S.length===0)return;let C=S.map(et=>et.position.x),E=S.map(et=>et.position.y),R=Math.min(...C),I=Math.max(...C),k=Math.min(...E),M=Math.max(...E),A=I-R,L=M-k,B=A===0?i:0,D=L===0?i:0,V=a+B/2,X=c+B/2,W=o+D/2,Q=s+D/2,J=R-V,_t=I+X,st=k-Q,it=M+W;h=_t-J,f=it-st,_=J+(n.schX??0),y=st+(n.schY??0),x=_+h/2,v=y+f/2}else if(u){h=n.width,f=n.height;let w=this._getGlobalSchematicPositionBeforeLayout();x=w.x,v=w.y,_=x-h/2,y=v-f/2}else return;if(t.schematic_box.insert({height:f,width:h,x:_,y,is_dashed:n.strokeStyle==="dashed"}),n.title){let w=n.titleInside,S=.1,C=n.titleAlignment,E=Iwt({anchor:C,x:_,y,width:h,height:f,isInside:w}),R,I,k=E.textAnchor;w?(R=C.includes("top")?-S:C.includes("bottom")?S:0,I=C.includes("left")?S:C.includes("right")?-S:0):(R=C.includes("top")?S:C.includes("bottom")?-S:0,I=C.includes("center_left")?-S:C.includes("center_right")?S:0);let M=E.x+I,A=E.y+R;t.schematic_text.insert({anchor:k,text:n.title,font_size:n.titleFontSize??.18,color:n.titleColor??"#000000",position:{x:M,y:A},rotation:0})}}},PX=class extends Ie{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0);T(this,"schematic_table_id",null)}get config(){return{componentName:"SchematicTable",zodProps:sF}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.children.filter(f=>f.componentName==="SchematicRow");if(i.length===0)return;let r=[],o=0;for(let f of i){let _=f.children.filter(y=>y.componentName==="SchematicCell");o=Math.max(o,_.length)}for(let f=0;f<i.length;f++)r[f]=[];for(let f=0;f<i.length;f++){let y=i[f].children.filter(v=>v.componentName==="SchematicCell"),x=0;for(let v=0;v<y.length;v++){for(;r[f][x];)x++;let w=y[v],S=w._parsedProps.colSpan??1,C=w._parsedProps.rowSpan??1;for(let E=0;E<C;E++)for(let R=0;R<S;R++)r[f+E]||(r[f+E]=[]),r[f+E][x+R]=w;x+=S}}o=Math.max(0,...r.map(f=>f.length));let s=i.map((f,_)=>f._parsedProps.height??1),a=Array.from({length:o},(f,_)=>{let y=0;for(let x=0;x<i.length;x++){let v=r[x]?.[_];if(v){let w=v._parsedProps.text??v._parsedProps.children,S=v._parsedProps.width??(w?.length??2)*.5;S>y&&(y=S)}}return y||10}),c=this._getGlobalSchematicPositionBeforeLayout(),l=t.schematic_table.insert({anchor_position:c,column_widths:a,row_heights:s,cell_padding:n.cellPadding,border_width:n.borderWidth,anchor:n.anchor,subcircuit_id:this.getSubcircuit()?.subcircuit_id||"",schematic_component_id:this.parent?.schematic_component_id||""});this.schematic_table_id=l.schematic_table_id;let u=new Set,h=0;for(let f=0;f<i.length;f++){let _=0;for(let y=0;y<o;y++){let x=r[f]?.[y];if(x&&!u.has(x)){u.add(x);let v=x._parsedProps,w=v.rowSpan??1,S=v.colSpan??1,C=0;for(let R=0;R<S;R++)C+=a[y+R];let E=0;for(let R=0;R<w;R++)E+=s[f+R];t.schematic_table_cell.insert({schematic_table_id:this.schematic_table_id,start_row_index:f,end_row_index:f+w-1,start_column_index:y,end_column_index:y+S-1,text:v.text??v.children,center:{x:c.x+_+C/2,y:c.y-h-E/2},width:C,height:E,horizontal_align:v.horizontalAlign,vertical_align:v.verticalAlign,font_size:v.fontSize??n.fontSize,subcircuit_id:this.getSubcircuit()?.subcircuit_id||""})}a[y]&&(_+=a[y])}h+=s[f]}}},TX=class extends Ie{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicRow",zodProps:aF}}},IX=class extends Ie{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0);T(this,"canHaveTextChildren",!0)}get config(){return{componentName:"SchematicCell",zodProps:cF}}},MX=class extends Ie{constructor(){super(...arguments);T(this,"isPrimitiveContainer",!0)}get config(){return{componentName:"Symbol",zodProps:AL}}},Mwt={name:"@tscircuit/core",type:"module",version:"0.0.750",types:"dist/index.d.ts",main:"dist/index.js",module:"dist/index.js",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist"],repository:{type:"git",url:"https://github.com/tscircuit/core"},scripts:{build:"tsup-node index.ts --format esm --dts",format:"biome format . --write","measure-bundle":"howfat -r table .","pkg-pr-new-release":"bunx pkg-pr-new publish --comment=off --peerDeps","smoke-test:dist":"bun run scripts/smoke-tests/test-dist-simple-circuit.tsx","build:benchmarking":"bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist","build:benchmarking:watch":`chokidar "./{benchmarking,lib}/**/*.{ts,tsx}" -c 'bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist'`,"start:benchmarking":'concurrently "bun run build:benchmarking:watch" "live-server ./benchmarking-dist"'},devDependencies:{"@biomejs/biome":"^1.8.3","@tscircuit/capacity-autorouter":"^0.0.107","@tscircuit/checks":"^0.0.75","@tscircuit/circuit-json-util":"^0.0.67","@tscircuit/footprinter":"^0.0.236","@tscircuit/import-snippet":"^0.0.4","@tscircuit/infgrid-ijump-astar":"^0.0.33","@tscircuit/log-soup":"^1.0.2","@tscircuit/matchpack":"^0.0.16","@tscircuit/math-utils":"^0.0.21","@tscircuit/miniflex":"^0.0.4","@tscircuit/props":"0.0.341","@tscircuit/schematic-autolayout":"^0.0.6","@tscircuit/schematic-match-adapt":"^0.0.16","@tscircuit/schematic-trace-solver":"^0.0.40","@tscircuit/simple-3d-svg":"^0.0.41","@types/bun":"^1.2.16","@types/debug":"^4.1.12","@types/react":"^19.1.8","@types/react-dom":"^19.1.6","@types/react-reconciler":"^0.28.9","bpc-graph":"^0.0.57","bun-match-svg":"0.0.12","calculate-elbow":"^0.0.12","chokidar-cli":"^3.0.0","circuit-json":"^0.0.267","circuit-json-to-bpc":"^0.0.13","circuit-json-to-connectivity-map":"^0.0.22","circuit-json-to-simple-3d":"^0.0.9","circuit-to-svg":"^0.0.202",concurrently:"^9.1.2","connectivity-map":"^1.0.0",debug:"^4.3.6",flatbush:"^4.5.0","graphics-debug":"^0.0.60",howfat:"^0.3.8","live-server":"^1.2.2","looks-same":"^9.0.1",minicssgrid:"^0.0.9","pkg-pr-new":"^0.0.37",react:"^19.1.0","react-dom":"^19.1.0","schematic-symbols":"^0.0.202","ts-expect":"^1.3.0",tsup:"^8.2.4"},peerDependencies:{"@tscircuit/capacity-autorouter":"*","@tscircuit/checks":"*","@tscircuit/circuit-json-util":"*","@tscircuit/footprinter":"*","@tscircuit/infgrid-ijump-astar":"*","@tscircuit/math-utils":"*","@tscircuit/props":"*","@tscircuit/schematic-autolayout":"*","@tscircuit/schematic-match-adapt":"*","circuit-json-to-bpc":"*","bpc-graph":"*","@tscircuit/matchpack":"*","circuit-json":"*","circuit-json-to-connectivity-map":"*","schematic-symbols":"*",typescript:"^5.0.0"},dependencies:{"@flatten-js/core":"^1.6.2","@lume/kiwi":"^0.4.3","calculate-packing":"0.0.37","css-select":"5.1.0","format-si-unit":"^0.0.3",nanoid:"^5.0.7","performance-now":"^2.1.0","react-reconciler":"^0.32.0","transformation-matrix":"^2.16.1",zod:"^3.25.67"}},eh=class{constructor({platform:e,projectUrl:t}={}){T(this,"firstChild",null);T(this,"children");T(this,"db");T(this,"root",null);T(this,"isRoot",!0);T(this,"schematicDisabled",!1);T(this,"pcbDisabled",!1);T(this,"pcbRoutingDisabled",!1);T(this,"_featureMspSchematicTraceRouting",!0);T(this,"name");T(this,"platform");T(this,"projectUrl");T(this,"_hasRenderedAtleastOnce",!1);T(this,"_eventListeners",{});this.children=[],this.db=Me([]),this.root=this,this.platform=e,this.projectUrl=t,this.pcbDisabled=e?.pcbDisabled??!1}add(e){let t;(0,EX.isValidElement)(e)?t=gY(e):t=e,this.children.push(t)}_getBoard(){return this.children.find(e=>e.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 e=new th({subcircuit:!0});e.parent=this,e.addAll(this.children),this.children=[e],this.firstChild=e}render(){this.firstChild||this._guessRootComponent();let{firstChild:e,db:t}=this;if(!e)throw new Error("RootCircuit has no root component");e.parent=this,e.runRenderCycle(),this._hasRenderedAtleastOnce=!0}async renderUntilSettled(){for(this.db.source_project_metadata.list()?.[0]||this.db.source_project_metadata.insert({software_used_string:`@tscircuit/core@${this.getCoreVersion()}`,...this.projectUrl?{project_url:this.projectUrl}:{}}),this.render();this._hasIncompleteAsyncEffects();)await new Promise(t=>setTimeout(t,100)),this.render();this.emit("renderComplete")}_hasIncompleteAsyncEffects(){return this.children.some(e=>e._hasIncompleteAsyncEffects()?!0:e.children.some(t=>t._hasIncompleteAsyncEffects()))}getCircuitJson(){return this._hasRenderedAtleastOnce||this.render(),this.db.toArray()}toJson(){return this.getCircuitJson()}async getSvg(e){let t=await Promise.resolve().then(()=>(Yj(),jj)).catch(n=>{throw new Error(`To use circuit.getSvg, you must install the "circuit-to-svg" package.
230
+ ${i.stack}`),n.complete=!0,"root"in this&&this.root&&this.root.emit("asyncEffect:end",{effectName:e,componentDisplayName:this.getString(),phase:n.phase,error:i.toString()})})}_emitRenderLifecycleEvent(e,t){S2t(`${e}:${t} ${this.getString()}`);let n=`renderable:renderLifecycle:${e}:${t}`,i={renderId:this._renderId,componentDisplayName:this.getString(),type:n};"root"in this&&this.root&&(this.root.emit(n,i),this.root.emit("renderable:renderLifecycle:anyEvent",{...i,type:n}))}getString(){return this.constructor.name}_hasIncompleteAsyncEffects(){return this._asyncEffects.some(e=>!e.complete)}_hasIncompleteAsyncEffectsInSubtreeForPhase(e){for(let t of this._asyncEffects)if(!t.complete&&t.phase===e)return!0;for(let t of this.children)if(t._hasIncompleteAsyncEffectsInSubtreeForPhase(e))return!0;return!1}getCurrentRenderPhase(){return this._currentRenderPhase}getRenderGraph(){return{id:this._renderId,currentPhase:this._currentRenderPhase,renderPhaseStates:this.renderPhaseStates,shouldBeRemoved:this.shouldBeRemoved,children:this.children.map(e=>e.getRenderGraph())}}runRenderCycle(){for(let e of Fs)this.runRenderPhaseForChildren(e),this.runRenderPhase(e)}runRenderPhase(e){this._currentRenderPhase=e;let t=this.renderPhaseStates[e],n=t.initialized,i=t.dirty;if(!n&&this.shouldBeRemoved)return;if(this.shouldBeRemoved&&n){this._emitRenderLifecycleEvent(e,"start"),this?.[`remove${e}`]?.(),t.initialized=!1,t.dirty=!1,this._emitRenderLifecycleEvent(e,"end");return}let r=Fs.indexOf(e)-1;if(r>=0){let s=Fs[r];if(this._asyncEffects.filter(c=>c.phase===s).some(c=>!c.complete))return}let o=P2t[e]||[];for(let s of o)if(this._hasIncompleteAsyncEffectsInSubtreeForPhase(s))return;if(this._emitRenderLifecycleEvent(e,"start"),n){i&&(this?.[`update${e}`]?.(),t.dirty=!1),this._emitRenderLifecycleEvent(e,"end");return}t.dirty=!1,this?.[`doInitial${e}`]?.(),t.initialized=!0,this._emitRenderLifecycleEvent(e,"end")}runRenderPhaseForChildren(e){for(let t of this.children)t.runRenderPhaseForChildren(e),t.runRenderPhase(e)}renderError(e){throw typeof e=="string"?new Error(e):new Error(JSON.stringify(e,null,2))}},Mx={},yY=e=>{let t=Object.fromEntries(Object.entries(e).map(([n,i])=>[n.toLowerCase(),i]));Object.assign(Mx,e),Object.assign(Mx,t)},I2t=class extends Error{constructor(e,t,n){let i,r=Object.keys(n).filter(c=>c!=="_errors"),o=[],s=t.pinLabels;if(s)for(let[c,l]of Object.entries(s)){let u=Array.isArray(l)?l:[l];for(let h of u)typeof h=="string"&&(h.startsWith(" ")||h.endsWith(" "))&&o.push(`pinLabels.${c} ("${h}" has leading or trailing spaces)`)}let a=r.map(c=>c==="pinLabels"&&o.length>0?o.join(", "):n[c]._errors[0]?`${c} (${n[c]._errors[0]})`:`${c} (${JSON.stringify(n[c])})`).join(", ");"name"in t?i=`Invalid props for ${e} "${t.name}": ${a}`:"footprint"in t&&typeof t.footprint=="string"?i=`Invalid props for ${e} (unnamed ${t.footprint} component): ${a}`:i=`Invalid props for ${e} (unnamed): ${a}`,super(i),this.componentName=e,this.originalProps=t,this.formattedError=n}};function VT(e,t){let n=t.match(/^#(\w+)/);if(n)return e.props.id===n[1];let i=t.match(/^\.(\w+)/);if(i)return e.isMatchingNameOrAlias(i[1]);let[r,...o]=t.split(/(?=[#.[])/);return r==="pin"&&(r="port"),r&&r!=="*"&&e.lowercaseComponentName!==r.toLowerCase()?!1:o.every(s=>{if(s.startsWith("#"))return e.props.id===s.slice(1);if(s.startsWith("."))return e.isMatchingNameOrAlias(s.slice(1));let a=s.match(/\[(\w+)=['"]?(.+?)['"]?\]/);if(!a)return!0;let[,c,l]=a;return e.props[c].toString()===l})}var sI={isTag:e=>!0,getParent:e=>e.parent,getChildren:e=>e.children,getName:e=>e.lowercaseComponentName,getAttributeValue:(e,t)=>{if(t==="class"&&"getNameAndAliases"in e)return e.getNameAndAliases().join(" ");if(t==="name"&&e._parsedProps?.name)return e._parsedProps.name;if(e._parsedProps&&t in e._parsedProps){let i=e._parsedProps[t];return typeof i=="string"?i:i!=null?String(i):null}if(t in e){let i=e[t];return typeof i=="string"?i:i!=null?String(i):null}let n=e._attributeLowerToCamelNameMap;if(n){let i=n[t];if(i&&i in e){let r=e[i];return typeof r=="string"?r:r!=null?String(r):null}}return null},hasAttrib:(e,t)=>{if(t==="class")return!!e._parsedProps?.name;if(e._parsedProps&&t in e._parsedProps||t in e)return!0;let n=e._attributeLowerToCamelNameMap;if(n){let i=n[t];if(i&&i in e)return!0}return!1},getSiblings:e=>e.parent?e.parent.children:[],prevElementSibling:e=>{if(!e.parent)return null;let t=e.parent.children,n=t.indexOf(e);return n>0?t[n-1]:null},getText:()=>"",removeSubsets:e=>e.filter((t,n)=>!e.some((i,r)=>n!==r&&i!==t&&i.getDescendants().includes(t))),existsOne:(e,t)=>t.some(e),findAll:(e,t)=>{let n=[],i=r=>{e(r)&&n.push(r);for(let o of r.children)i(o)};for(let r of t)i(r);return n},findOne:(e,t)=>{for(let n of t){if(e(n))return n;let i=n.children;if(i.length>0){let r=sI.findOne(e,i);if(r)return r}}return null},equals:(e,t)=>e._renderId===t._renderId,isHovered:e=>!1,isVisited:e=>!1,isActive:e=>!1},M2t={...sI,getChildren:e=>e.children.filter(t=>!t.isSubcircuit)},Xj={...sI,getChildren:e=>e.children.filter(t=>t.isSubcircuit)},Vj=e=>{if(/net\.[^\s>]*\./.test(e))throw new Error('Net names cannot contain a period, try using "sel.net..." to autocomplete with conventional net names, e.g. V3_3');if(/net\.[^\s>]*[+-]/.test(e))throw new Error('Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P');if(/net\.[0-9]/.test(e)){let t=e.match(/net\.([^ >]+)/),n=t?t[1]:"";throw new Error(`Net name "${n}" cannot start with a number, try using a prefix like "VBUS1"`)}return e.replace(/ pin(?=[\d.])/g," port").replace(/ subcircuit\./g," group[isSubcircuit=true]").replace(/([^ ])\>([^ ])/g,"$1 > $2").replace(/(^|[ >])(?!pin\.)(?!port\.)(?!net\.)([A-Z][A-Za-z0-9_-]*)\.([A-Za-z0-9_-]+)/g,(t,n,i,r)=>{let o=/^\d+$/.test(r)?`pin${r}`:r;return`${n}.${i} > .${o}`}).trim()},HT={adapter:M2t,cacheResults:!0},Ie=class extends oI{constructor(t){super(t);T(this,"parent",null);T(this,"children");T(this,"childrenPendingRemoval");T(this,"props");T(this,"_parsedProps");T(this,"externallyAddedAliases");T(this,"isPrimitiveContainer",!1);T(this,"canHaveTextChildren",!1);T(this,"source_group_id",null);T(this,"source_component_id",null);T(this,"schematic_component_id",null);T(this,"pcb_component_id",null);T(this,"cad_component_id",null);T(this,"fallbackUnassignedName");T(this,"_cachedSelectAllQueries",new Map);T(this,"_cachedSelectOneQueries",new Map);this.children=[],this.childrenPendingRemoval=[],this.props=t??{},this.externallyAddedAliases=[];let i=("partial"in this.config.zodProps?this.config.zodProps.partial({name:!0}):this.config.zodProps).safeParse(t??{});if(i.success)this._parsedProps=i.data;else throw new I2t(this.lowercaseComponentName,this.props,i.error.format())}get config(){return{componentName:"",zodProps:p.object({}).passthrough()}}get componentName(){return this.config.componentName}getInheritedProperty(t){let n=this;for(;n;){if(n._parsedProps&&t in n._parsedProps)return n._parsedProps[t];n=n.parent}if(this.root?.platform&&t in this.root.platform)return this.root.platform[t]}get lowercaseComponentName(){return this.componentName.toLowerCase()}get isSubcircuit(){return!!this.props.subcircuit||this.lowercaseComponentName==="group"&&this?.parent?.isRoot}get isGroup(){return this.lowercaseComponentName==="group"}get name(){return this._parsedProps.name??this.fallbackUnassignedName}setProps(t){let n=this.config.zodProps.parse({...this.props,...t}),i=this.props;this.props=n,this._parsedProps=this.config.zodProps.parse(t),this.onPropsChange({oldProps:i,newProps:n,changedProps:Object.keys(t)}),this.parent?.onChildChanged?.(this)}_getPcbRotationBeforeLayout(){let{pcbRotation:t}=this.props;return typeof t=="string"?parseFloat(t):t??null}computePcbPropsTransform(){let{_parsedProps:t}=this,n=this._getPcbRotationBeforeLayout()??0;return Gn(fn(t.pcbX??0,t.pcbY??0),va(n*Math.PI/180))}_computePcbGlobalTransformBeforeLayout(){let t=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if(t&&this.props.pcbX===void 0&&this.props.pcbY===void 0){let n=this._getPcbRotationBeforeLayout()??0;return Gn(this.parent?._computePcbGlobalTransformBeforeLayout()??vi(),Gn(fn(t.x,t.y),va(n*Math.PI/180)))}if(this.isPcbPrimitive){let n=this.getPrimitiveContainer();if(n&&n._parsedProps.layer==="bottom")return Gn(this.parent?._computePcbGlobalTransformBeforeLayout()??vi(),_N(),this.computePcbPropsTransform())}return Gn(this.parent?._computePcbGlobalTransformBeforeLayout()??vi(),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(),n=t?t._parsedProps.layer==="bottom":!1;return{isFlipped:n,maybeFlipLayer:r=>n?r==="top"?"bottom":"top":r}}_setPositionFromLayout(t){throw new Error(`_setPositionFromLayout not implemented for ${this.componentName}`)}computeSchematicPropsTransform(){let{_parsedProps:t}=this;return Gn(fn(t.schX??0,t.schY??0))}computeSchematicGlobalTransform(){let t=this._getSchematicGlobalManualPlacementTransform(this);return t||Gn(this.parent?.computeSchematicGlobalTransform?.()??vi(),this.computeSchematicPropsTransform())}_getSchematicSymbolName(){let{_parsedProps:t}=this,n=this.config.schematicSymbolName,i={horizontal:0,pos_left:0,neg_right:0,pos_right:180,neg_left:180,pos_top:270,neg_bottom:90,vertical:270,pos_bottom:90,neg_top:90},r=t.schOrientation!==void 0?i[t.schOrientation]:t.schRotation;if(r===void 0&&(r=0),r=r%360,r<0&&(r+=360),t.schRotation!==void 0&&r%90!==0)throw new Error(`Schematic rotation ${t.schRotation} is not supported for ${this.componentName}`);let o=`${n}_horz`,s=`${n}_vert`,a=`${n}_up`,c=`${n}_down`,l=`${n}_left`,u=`${n}_right`;if(u in Un&&r===0)return u;if(a in Un&&r===90)return a;if(l in Un&&r===180)return l;if(c in Un&&r===270)return c;if(o in Un&&(r===0||r===180))return o;if(s in Un&&(r===90||r===270))return s;if(n in Un)return n}_getSchematicSymbolNameOrThrow(){let t=this._getSchematicSymbolName();if(!t)throw new Error(`No schematic symbol found (given: "${this.config.schematicSymbolName}")`);return t}getSchematicSymbol(){let t=this._getSchematicSymbolName();return t?Un[t]??null:null}_getPcbManualPlacementForComponent(t){if(!this.isSubcircuit)return null;let n=this.props.manualEdits;if(!n)return null;let i=n?.pcb_placements;if(!i)return null;for(let r of i)if(VT(t,r.selector)||t.props.name===r.selector)return kn(this._computePcbGlobalTransformBeforeLayout(),r.center);return null}_getSchematicManualPlacementForComponent(t){if(!this.isSubcircuit)return null;let n=this.props.manualEdits;if(!n)return null;let i=n.schematic_placements;if(!i)return null;for(let r of i)if(VT(t,r.selector)||t.props.name===r.selector)return kn(this.computeSchematicGlobalTransform(),r.center);return null}_getSchematicGlobalManualPlacementTransform(t){let n=this.getSubcircuit()?._parsedProps.manualEdits;if(!n)return null;for(let i of n.schematic_placements??[])if((VT(t,i.selector)||t.props.name===i.selector)&&i.relative_to==="group_center")return Gn(this.parent?._computePcbGlobalTransformBeforeLayout()??vi(),fn(i.center.x,i.center.y));return null}_getGlobalPcbPositionBeforeLayout(){return kn(this._computePcbGlobalTransformBeforeLayout(),{x:0,y:0})}_getGlobalSchematicPositionBeforeLayout(){return kn(this.computeSchematicGlobalTransform(),{x:0,y:0})}get root(){return this.parent?.root??null}onAddToParent(t){this.parent=t}onPropsChange(t){}onChildChanged(t){this.parent?.onChildChanged?.(t)}add(t){let n=t.__text;if(typeof n=="string"){if(this.canHaveTextChildren||n.trim()==="")return;throw new Error(`Invalid JSX Element: Expected a React component but received text "${n}"`)}if(Object.keys(t).length!==0){if(this.lowercaseComponentName==="board"&&t.lowercaseComponentName==="board")throw new Error("Nested boards are not supported");if(!t.onAddToParent)throw new Error(`Invalid JSX Element: Expected a React component but received "${JSON.stringify(t)}"`);t.onAddToParent(this),t.parent=this,this.children.push(t)}}addAll(t){for(let n of t)this.add(n)}remove(t){this.children=this.children.filter(n=>n!==t),this.childrenPendingRemoval.push(t),t.shouldBeRemoved=!0}getSubcircuitSelector(){let t=this.name,n=t?`${this.lowercaseComponentName}.${t}`:this.lowercaseComponentName;return!this.parent||this.parent.isSubcircuit?n:`${this.parent.getSubcircuitSelector()} > ${n}`}getFullPathSelector(){let t=this.name,n=t?`${this.lowercaseComponentName}.${t}`:this.lowercaseComponentName,i=this.parent?.getFullPathSelector?.();return i?`${i} > ${n}`:n}getNameAndAliases(){return[this.name,...this._parsedProps.portHints??[]].filter(Boolean)}isMatchingNameOrAlias(t){return this.getNameAndAliases().includes(t)}isMatchingAnyOf(t){return this.getNameAndAliases().some(n=>t.map(i=>i.toString()).includes(n))}getPcbSize(){throw new Error(`getPcbSize not implemented for ${this.componentName}`)}doesSelectorMatch(t){let n=[this.componentName,this.lowercaseComponentName],i=[this.name].filter(Boolean),r=t.trim().split(/\> /)[0],o=r[0];return r.length>1?!1:!!(t==="*"||t[0]==="#"&&t.slice(1)===this.props.id||t[0]==="."&&i.includes(t.slice(1))||/^[a-zA-Z0-9_]/.test(o)&&n.includes(o))}getSubcircuit(){if(this.isSubcircuit)return this;let t=this.parent?.getSubcircuit?.();if(!t)throw new Error("Component is not inside an opaque group (no board?)");return t}getGroup(){return this.isGroup?this:this.parent?.getGroup?.()??null}doInitialAssignNameToUnnamedComponents(){this._parsedProps.name||(this.fallbackUnassignedName=this.getSubcircuit().getNextAvailableName(this))}doInitialOptimizeSelectorCache(){if(!this.isSubcircuit)return;let t=this.selectAll("port");for(let n of t){let i=n.parent?.getNameAndAliases(),r=n.getNameAndAliases();if(i)for(let o of i)for(let s of r){let a=[`.${o} > .${s}`,`.${o} .${s}`];for(let c of a){let l=this._cachedSelectAllQueries.get(c);l?l.push(n):this._cachedSelectAllQueries.set(c,[n])}}}for(let[n,i]of this._cachedSelectAllQueries.entries())i.length===1&&this._cachedSelectOneQueries.set(n,i[0])}selectAll(t){if(this._cachedSelectAllQueries.has(t))return this._cachedSelectAllQueries.get(t);let n=Vj(t),i=o5(n,this,HT);if(i.length>0)return this._cachedSelectAllQueries.set(t,i),i;let[r,...o]=n.split(" "),s=Dy(r,this,{adapter:Xj});if(!s)return[];let a=s.selectAll(o.join(" "));return this._cachedSelectAllQueries.set(t,a),a}selectOne(t,n){if(this._cachedSelectOneQueries.has(t))return this._cachedSelectOneQueries.get(t);let i=Vj(t);n?.port&&(n.type="port");let r=null;if(n?.type&&(r=o5(i,this,HT).find(l=>l.lowercaseComponentName===n.type)),r??(r=Dy(i,this,HT)),r)return this._cachedSelectOneQueries.set(t,r),r;let[o,...s]=i.split(" "),a=Dy(o,this,{adapter:Xj});return a?(r=a.selectOne(s.join(" "),n),this._cachedSelectOneQueries.set(t,r),r):null}getAvailablePcbLayers(){if(this.isPcbPrimitive){let{maybeFlipLayer:t}=this._getPcbPrimitiveFlippedHelpers();return"layer"in this._parsedProps||this.componentName==="SmtPad"?[t(this._parsedProps.layer??"top")]:"layers"in this._parsedProps?this._parsedProps.layers:this.componentName==="PlatedHole"?this.root?._getBoard()?.allLayers??["top","bottom"]:[]}return[]}getDescendants(){let t=[];for(let n of this.children)t.push(n),t.push(...n.getDescendants());return t}getSelectableDescendants(){let t=[];for(let n of this.children)n.isSubcircuit?t.push(n):(t.push(n),t.push(...n.getSelectableDescendants()));return t}_getPinCount(){return 0}_getSchematicBoxDimensions(){return null}_getSchematicBoxComponentDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;let{_parsedProps:t}=this;return{schWidth:t.schWidth,schHeight:t.schHeight}}renderError(t){if(typeof t=="string")return super.renderError(t);this.root?.db.pcb_placement_error.insert(t)}getString(){let{lowercaseComponentName:t,_parsedProps:n,parent:i}=this;return n?.pinNumber!==void 0&&i?.props?.name&&n?.name?`<${t}#${this._renderId}(pin:${n.pinNumber} .${i?.props.name}>.${n.name}) />`:i?.props?.name&&n?.name?`<${t}#${this._renderId}(.${i?.props.name}>.${n?.name}) />`:n?.from&&n?.to?`<${t}#${this._renderId}(from:${n.from} to:${n?.to}) />`:n?.name?`<${t}#${this._renderId} name=".${n?.name}" />`:n?.portHints?`<${t}#${this._renderId}(${n.portHints.map(r=>`.${r}`).join(", ")}) />`:`<${t}#${this._renderId} />`}get[Symbol.toStringTag](){return this.getString()}[Symbol.for("nodejs.util.inspect.custom")](){return this.getString()}},E2t=class extends Ie{constructor(e,t){super(e),this._parsedProps={...e,error:t,type:e.type||"unknown",component_name:e.name,error_type:"source_failed_to_create_component_error",message:t instanceof Error?t.message:String(t),pcbX:e.pcbX,pcbY:e.pcbY,schX:e.schX,schY:e.schY}}get config(){return{componentName:"ErrorPlaceholder",zodProps:p.object({}).passthrough()}}doInitialSourceRender(){if(this.root?.db){let e=this._getGlobalPcbPositionBeforeLayout(),t=this._getGlobalSchematicPositionBeforeLayout();this.root.db.source_failed_to_create_component_error.insert({component_name:this._parsedProps.component_name,error_type:"source_failed_to_create_component_error",message:`Could not create ${this._parsedProps.componentType??"component"}${this._parsedProps.name?` "${this._parsedProps.name}"`:""}. ${this._parsedProps.error?.formattedError?._errors?.join("; ")||this._parsedProps.message}`,pcb_center:e,schematic_center:t})}}};function C2t(e,t){return new E2t(e,t)}function k2t(e,t){let n=e;return n.__tsci={...t},e}var A2t={supportsMutation:!0,createInstance(e,t){let n=Mx[e];if(!n)throw Object.keys(Mx).length===0?new Error("No components registered in catalogue, did you forget to import lib/register-catalogue in your test file?"):new Error(`Unsupported component type "${e}". No element with this name is registered in the @tscircuit/core catalogue. Check for typos or see https://docs.tscircuit.com/category/built-in-elements for a list of valid components. To add your own component, see docs/CREATING_NEW_COMPONENTS.md`);try{return k2t(new n(t),{})}catch(i){return C2t({...t,componentType:e},i)}},createTextInstance(e){return{__text:e}},appendInitialChild(e,t){e.add(t)},appendChild(e,t){e.add(t)},appendChildToContainer(e,t){e.add(t)},finalizeInitialChildren(){return!1},prepareUpdate(){return null},shouldSetTextContent(){return!1},getRootHostContext(){return{}},getChildHostContext(){return{}},prepareForCommit(){return null},resetAfterCommit(){},commitMount(){},commitUpdate(){},removeChild(){},clearContainer(){},supportsPersistence:!1,getPublicInstance(e){return e},preparePortalMount(e){throw new Error("Function not implemented.")},scheduleTimeout(e,t){throw new Error("Function not implemented.")},cancelTimeout(e){throw new Error("Function not implemented.")},noTimeout:void 0,isPrimaryRenderer:!1,getInstanceFromNode(e){throw new Error("Function not implemented.")},beforeActiveInstanceBlur(){throw new Error("Function not implemented.")},afterActiveInstanceBlur(){throw new Error("Function not implemented.")},prepareScopeUpdate:(e,t)=>{throw new Error("Function not implemented.")},getInstanceFromScope:e=>{throw new Error("Function not implemented.")},detachDeletedInstance:e=>{throw new Error("Function not implemented.")},getCurrentEventPriority:()=>Tx.DefaultEventPriority,getCurrentUpdatePriority:()=>Tx.DefaultEventPriority,resolveUpdatePriority:()=>Tx.DefaultEventPriority,setCurrentUpdatePriority:()=>{},maySuspendCommit:()=>!1,supportsHydration:!1},wx=(0,mY.default)(A2t),gY=e=>{let t={children:[],props:{name:"$root"},add(o){o.parent=this,this.children.push(o)},computePcbGlobalTransform(){return vi()}},n=[],i=wx.createContainer(t,0,null,!1,null,"tsci",o=>{console.log("Error in createContainer"),console.error(o),n.push(o)},null);if(wx.updateContainerSync(e,i,null,()=>{}),wx.flushSyncWork(),n.length>0)throw n[0];let r=wx.getPublicRootInstance(i);return r||t.children[0]},Rf=(e,t)=>{if(typeof e=="number")return e;if(e.startsWith("pin"))return Number(e.slice(3));if(!t)throw new Error(`No pin labels provided and pin number or label is not a number: "${e}"`);for(let n in t)if((Array.isArray(t[n])?t[n]:[t[n]]).includes(e))return Number(n.replace("pin",""));throw new Error(`No pin labels provided and pin number or label is not a number: "${e}"`)},N2t=(e,t)=>{if(!e)return;let n={},i={};for(let[r,o]of Object.entries(e)){let s=Rf(r,t);i[s]={...i[s],...o}}for(let[r,o]of Object.entries(i)){let s=`pin${r}`;n[s]={bottom_margin:o.bottomMargin,left_margin:o.leftMargin,right_margin:o.rightMargin,top_margin:o.topMargin}}return n},R2t=e=>{if(e){if("leftSide"in e||"rightSide"in e||"topSide"in e||"bottomSide"in e)return{left_side:e.leftSide,right_side:e.rightSide,top_side:e.topSide,bottom_side:e.bottomSide};if("leftPinCount"in e||"rightPinCount"in e||"topPinCount"in e||"bottomPinCount"in e)return{left_size:e.leftPinCount,right_size:e.rightPinCount,top_size:e.topPinCount,bottom_size:e.bottomPinCount};if("leftSize"in e||"rightSize"in e||"topSize"in e||"bottomSize"in e)return{left_size:e.leftSize,right_size:e.rightSize,top_size:e.topSize,bottom_size:e.bottomSize}}};function xY(e){let t=[];for(let n=0;n<e.length-1;n++)t.push([e[n],e[n+1]]);return t}var O2t=p.object({name:p.string().refine(e=>!/[+-]/.test(e),'Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P')}),aI=class extends Ie{constructor(){super(...arguments);T(this,"source_net_id")}get config(){return{componentName:"Net",zodProps:O2t}}getPortSelector(){return`net.${this.props.name}`}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=n.name.startsWith("GND"),r=n.name.startsWith("V"),o=t.source_net.insert({name:n.name,member_source_group_ids:[],is_ground:i,is_power:r,is_positive_voltage_source:r});this.source_net_id=o.source_net_id}doInitialSourceParentAttachment(){let t=this.getSubcircuit();if(!t)return;let{db:n}=this.root;n.source_net.update(this.source_net_id,{subcircuit_id:t.subcircuit_id})}getAllConnectedPorts(){let t=this.getSubcircuit().selectAll("port"),n=[];for(let i of t){let r=i._getDirectlyConnectedTraces();for(let o of r)if(o._isExplicitlyConnectedToNet(this)){n.push(i);break}}return n}_getAllDirectlyConnectedTraces(){let t=this.getSubcircuit().selectAll("trace"),n=[];for(let i of t)i._isExplicitlyConnectedToNet(this)&&n.push(i);return n}doInitialPcbRouteNetIslands(){if(this.root?.pcbDisabled||this.getSubcircuit()._parsedProps.routingDisabled||this.getSubcircuit()._getAutorouterConfig().groupMode!=="sequential-trace")return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getAllDirectlyConnectedTraces().filter(s=>(s._portsRoutedOnPcb?.length??0)>0),r=[];for(let s of i){let a=s._portsRoutedOnPcb,c=r.find(l=>a.some(u=>l.ports.includes(u)));if(!c){r.push({ports:[...a],traces:[s]});continue}c.traces.push(s),c.ports.push(...a)}if(r.length===0)return;let o=xY(r);for(let[s,a]of o){let c=s.ports.map(w=>w._getGlobalPcbPositionBeforeLayout()),l=a.ports.map(w=>w._getGlobalPcbPositionBeforeLayout()),u=1/0,h=[-1,-1];for(let w=0;w<c.length;w++){let S=c[w];for(let C=0;C<l.length;C++){let E=l[C],R=Math.sqrt((S.x-E.x)**2+(S.y-E.y)**2);R<u&&(u=R,h=[w,C])}}let f=s.ports[h[0]],_=a.ports[h[1]],y=t.toArray().filter(w=>w.type==="pcb_smtpad"||w.type==="pcb_trace"||w.type==="pcb_plated_hole"||w.type==="pcb_hole"||w.type==="source_port"||w.type==="pcb_port"),{solution:x}=rL(y.concat([{type:"source_trace",source_trace_id:"__net_trace_tmp",connected_source_port_ids:[f.source_port_id,_.source_port_id]}])),v=x[0];if(!v){this.renderError({pcb_trace_error_id:"",pcb_trace_id:"__net_trace_tmp",pcb_component_ids:[f.pcb_component_id,_.pcb_component_id].filter(Boolean),pcb_port_ids:[f.pcb_port_id,_.pcb_port_id].filter(Boolean),type:"pcb_trace_error",error_type:"pcb_trace_error",message:`Failed to route net islands for "${this.getString()}"`,source_trace_id:"__net_trace_tmp"});return}t.pcb_trace.insert(v)}}renderError(t){if(typeof t=="string")return super.renderError(t);this.root?.db.pcb_trace_error.insert(t)}},cI=(e,t)=>{for(let n of t)if(typeof n=="string"&&n.startsWith("net.")){if(/net\.[^\s>]*\./.test(n))throw new Error('Net names cannot contain a period, try using "sel.net..." to autocomplete with conventional net names, e.g. V3_3');if(/net\.[^\s>]*[+-]/.test(n))throw new Error('Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P');if(/net\.[0-9]/.test(n)){let r=n.split("net.")[1];throw new Error(`Net name "${r}" cannot start with a number, try using a prefix like "VBUS1"`)}let i=e.getSubcircuit();if(!i.selectOne(n)){let r=new aI({name:n.split("net.")[1]});i.add(r)}}},Ex=class extends Ie{constructor(){super(...arguments);T(this,"pcb_smtpad_id",null);T(this,"matchedPort",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SmtPad",zodProps:ML}}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 n=t.points,i=n.map(l=>l.x),r=n.map(l=>l.y),o=Math.min(...i),s=Math.max(...i),a=Math.min(...r),c=Math.max(...r);return{width:s-o,height:c-a}}if(t.shape==="pill")return{width:t.width,height:t.height};throw new Error(`getPcbSize for shape "${t.shape}" not implemented for ${this.componentName}`)}doInitialPortMatching(){let t=this.getPrimitiveContainer()?.selectAll("port");if(this.props.portHints){for(let n of t)if(n.isMatchingAnyOf(this.props.portHints)){this.matchedPort=n,n.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=n.coveredWithSolderMask??!1,r=!i;if(!n.portHints)return;let o=this.getSubcircuit(),s=this._getGlobalPcbPositionBeforeLayout(),l=(fo(this._computePcbGlobalTransformBeforeLayout()).rotation.angle*180/Math.PI%360+360)%360,u=.01,h=Math.abs(l)<u||Math.abs(l-180)<u||Math.abs(l-360)<u,f=Math.abs(l-90)<u||Math.abs(l-270)<u,_=Math.abs(l-360)<u?0:l,{maybeFlipLayer:y}=this._getPcbPrimitiveFlippedHelpers(),x=null,v=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id;n.shape==="circle"?(x=t.pcb_smtpad.insert({pcb_component_id:v,pcb_port_id:this.matchedPort?.pcb_port_id,layer:y(n.layer??"top"),shape:"circle",radius:n.radius,port_hints:n.portHints.map(w=>w.toString()),is_covered_with_solder_mask:i,x:s.x,y:s.y,subcircuit_id:o?.subcircuit_id??void 0}),r&&t.pcb_solder_paste.insert({layer:x.layer,shape:"circle",radius:x.radius*.7,x:x.x,y:x.y,pcb_component_id:x.pcb_component_id,pcb_smtpad_id:x.pcb_smtpad_id,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})):n.shape==="rect"?(x=h||f?t.pcb_smtpad.insert({pcb_component_id:v,pcb_port_id:this.matchedPort?.pcb_port_id,layer:y(n.layer??"top"),shape:"rect",width:f?n.height:n.width,height:f?n.width:n.height,port_hints:n.portHints.map(w=>w.toString()),is_covered_with_solder_mask:i,x:s.x,y:s.y,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}):t.pcb_smtpad.insert({pcb_component_id:v,layer:y(n.layer??"top"),shape:"rotated_rect",width:n.width,height:n.height,x:s.x,y:s.y,ccw_rotation:_,port_hints:n.portHints.map(w=>w.toString()),is_covered_with_solder_mask:i,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),r&&x.shape==="rect"&&t.pcb_solder_paste.insert({layer:y(n.layer??"top"),shape:"rect",width:x.width*.7,height:x.height*.7,x:x.x,y:x.y,pcb_component_id:x.pcb_component_id,pcb_smtpad_id:x.pcb_smtpad_id,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),r&&x.shape==="rotated_rect"&&t.pcb_solder_paste.insert({layer:y(n.layer??"top"),shape:"rotated_rect",width:x.width*.7,height:x.height*.7,x:x.x,y:x.y,ccw_rotation:_,pcb_component_id:x.pcb_component_id,pcb_smtpad_id:x.pcb_smtpad_id,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})):n.shape==="polygon"?x=t.pcb_smtpad.insert({pcb_component_id:v,pcb_port_id:this.matchedPort?.pcb_port_id,layer:y(n.layer??"top"),shape:"polygon",points:n.points.map(w=>({x:w.x+s.x,y:w.y+s.y})),port_hints:n.portHints.map(w=>w.toString()),is_covered_with_solder_mask:i,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}):n.shape==="pill"&&(x=t.pcb_smtpad.insert({pcb_component_id:v,pcb_port_id:this.matchedPort?.pcb_port_id,layer:y(n.layer??"top"),shape:"pill",x:s.x,y:s.y,radius:n.radius,height:n.height,width:n.width,port_hints:n.portHints.map(w=>w.toString()),is_covered_with_solder_mask:i,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})),x&&(this.pcb_smtpad_id=x.pcb_smtpad_id)}doInitialPcbPortAttachment(){if(this.root?.pcbDisabled)return;let{db:t}=this.root;t.pcb_smtpad.update(this.pcb_smtpad_id,{pcb_port_id:this.matchedPort?.pcb_port_id})}_getPcbCircuitJsonBounds(){let{db:t}=this.root,n=t.pcb_smtpad.get(this.pcb_smtpad_id);if(n.shape==="rect")return{center:{x:n.x,y:n.y},bounds:{left:n.x-n.width/2,top:n.y+n.height/2,right:n.x+n.width/2,bottom:n.y-n.height/2},width:n.width,height:n.height};if(n.shape==="rotated_rect"){let i=n.ccw_rotation*Math.PI/180,r=Math.cos(i),o=Math.sin(i),s=n.width/2,a=n.height/2,c=Math.abs(s*r)+Math.abs(a*o),l=Math.abs(s*o)+Math.abs(a*r);return{center:{x:n.x,y:n.y},bounds:{left:n.x-c,right:n.x+c,top:n.y-l,bottom:n.y+l},width:c*2,height:l*2}}if(n.shape==="circle")return{center:{x:n.x,y:n.y},bounds:{left:n.x-n.radius,top:n.y-n.radius,right:n.x+n.radius,bottom:n.y+n.radius},width:n.radius*2,height:n.radius*2};if(n.shape==="polygon"){let i=n.points,r=i.map(u=>u.x),o=i.map(u=>u.y),s=Math.min(...r),a=Math.max(...r),c=Math.min(...o),l=Math.max(...o);return{center:{x:(s+a)/2,y:(c+l)/2},bounds:{left:s,top:l,right:a,bottom:c},width:a-s,height:l-c}}if(n.shape==="pill"){let i=n.width/2,r=n.height/2;return{center:{x:n.x,y:n.y},bounds:{left:n.x-i,top:n.y-r,right:n.x+i,bottom:n.y+r},width:n.width,height:n.height}}throw new Error(`circuitJson bounds calculation not implemented for shape "${n.shape}"`)}_setPositionFromLayout(t){let{db:n}=this.root;n.pcb_smtpad.update(this.pcb_smtpad_id,{x:t.x,y:t.y});let i=n.pcb_solder_paste.list().find(r=>r.pcb_smtpad_id===this.pcb_smtpad_id);i&&n.pcb_solder_paste.update(i.pcb_solder_paste_id,{x:t.x,y:t.y}),this.matchedPort?._setPositionFromLayout(t)}},lI=class extends Ie{constructor(){super(...arguments);T(this,"pcb_silkscreen_path_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenPath",zodProps:uF}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(n.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenPath. Must be "top" or "bottom".`);let o=this._computePcbGlobalTransformBeforeLayout(),s=this.getSubcircuit(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,c=t.pcb_silkscreen_path.insert({pcb_component_id:a,layer:r,route:n.route.map(l=>{let u=kn(o,{x:l.x,y:l.y});return{...l,x:u.x,y:u.y}}),stroke_width:n.strokeWidth??.1,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_path_id=c.pcb_silkscreen_path_id}_setPositionFromLayout(t){let{db:n}=this.root,{_parsedProps:i}=this,r=n.pcb_silkscreen_path.get(this.pcb_silkscreen_path_id);if(!r)return;let o=0,s=0;for(let u of r.route)o+=u.x,s+=u.y;o/=r.route.length,s/=r.route.length;let a=t.x-o,c=t.y-s,l=r.route.map(u=>({...u,x:u.x+a,y:u.y+c}));n.pcb_silkscreen_path.update(this.pcb_silkscreen_path_id,{route:l})}getPcbSize(){let{_parsedProps:t}=this;if(!t.route||t.route.length===0)return{width:0,height:0};let n=1/0,i=-1/0,r=1/0,o=-1/0;for(let s of t.route)n=Math.min(n,s.x),i=Math.max(i,s.x),r=Math.min(r,s.y),o=Math.max(o,s.y);return{width:i-n,height:o-r}}},L2t=p.object({route:p.array(E1),source_trace_id:p.string().optional()}),uI=class extends Ie{constructor(){super(...arguments);T(this,"pcb_trace_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbTrace",zodProps:L2t}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getPrimitiveContainer(),r=this.getSubcircuit(),{maybeFlipLayer:o}=this._getPcbPrimitiveFlippedHelpers(),s=this._computePcbGlobalTransformBeforeLayout(),a=n.route.map(l=>{let{x:u,y:h,...f}=l,_=kn(s,{x:u,y:h});return l.route_type==="wire"&&l.layer?{..._,...f,layer:o(l.layer)}:{..._,...f}}),c=t.pcb_trace.insert({pcb_component_id:i.pcb_component_id,source_trace_id:n.source_trace_id,route:a,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_trace_id=c.pcb_trace_id}getPcbSize(){let{_parsedProps:t}=this;if(!t.route||t.route.length===0)return{width:0,height:0};let n=1/0,i=-1/0,r=1/0,o=-1/0;for(let s of t.route)n=Math.min(n,s.x),i=Math.max(i,s.x),r=Math.min(r,s.y),o=Math.max(o,s.y),s.route_type==="wire"&&(n=Math.min(n,s.x-s.width/2),i=Math.max(i,s.x+s.width/2),r=Math.min(r,s.y-s.width/2),o=Math.max(o,s.y+s.width/2));return n===1/0||i===-1/0||r===1/0||o===-1/0?{width:0,height:0}:{width:i-n,height:o-r}}},Jp=class extends Ie{constructor(){super(...arguments);T(this,"pcb_plated_hole_id",null);T(this,"matchedPort",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PlatedHole",zodProps:yL}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){let{_parsedProps:t}=this;if(t.shape==="circle")return{width:t.outerDiameter,height:t.outerDiameter};if(t.shape==="oval"||t.shape==="pill")return{width:t.outerWidth,height:t.outerHeight};if(t.shape==="circular_hole_with_rect_pad")return{width:t.rectPadWidth,height:t.rectPadHeight};if(t.shape==="pill_hole_with_rect_pad")return{width:t.rectPadWidth,height:t.rectPadHeight};throw new Error(`getPcbSize for shape "${t.shape}" not implemented for ${this.componentName}`)}_getPcbCircuitJsonBounds(){let{db:t}=this.root,n=t.pcb_plated_hole.get(this.pcb_plated_hole_id),i=this.getPcbSize();return{center:{x:n.x,y:n.y},bounds:{left:n.x-i.width/2,top:n.y+i.height/2,right:n.x+i.width/2,bottom:n.y-i.height/2},width:i.width,height:i.height}}_setPositionFromLayout(t){let{db:n}=this.root;n.pcb_plated_hole.update(this.pcb_plated_hole_id,{x:t.x,y:t.y}),this.matchedPort?._setPositionFromLayout(t)}doInitialPortMatching(){let t=this.getPrimitiveContainer()?.selectAll("port");if(this.props.portHints){for(let n of t)if(n.isMatchingAnyOf(this.props.portHints)){this.matchedPort=n,n.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalPcbPositionBeforeLayout(),r=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,o=this.getSubcircuit();if(n.shape==="circle"){let s=t.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,outer_diameter:n.outerDiameter,hole_diameter:n.holeDiameter,shape:"circle",port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=s.pcb_plated_hole_id,t.pcb_solder_paste.insert({layer:"top",shape:"circle",radius:n.outerDiameter/2,x:i.x,y:i.y,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),t.pcb_solder_paste.insert({layer:"bottom",shape:"circle",radius:n.outerDiameter/2,x:i.x,y:i.y,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(n.shape==="pill"&&n.rectPad){let s=t.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,outer_width:n.outerWidth,outer_height:n.outerHeight,hole_width:n.holeWidth,hole_height:n.holeHeight,shape:"rotated_pill_hole_with_rect_pad",type:"pcb_plated_hole",port_hints:this.getNameAndAliases(),pcb_plated_hole_id:this.pcb_plated_hole_id,x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,hole_shape:"rotated_pill",pad_shape:"rect",hole_ccw_rotation:n.pcbRotation??0,rect_ccw_rotation:n.pcbRotation??0,rect_pad_width:n.outerWidth,rect_pad_height:n.outerHeight,hole_offset_x:n.holeOffsetX,hole_offset_y:n.holeOffsetY});this.pcb_plated_hole_id=s.pcb_plated_hole_id}else if(n.shape==="pill"||n.shape==="oval"){let s=t.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,outer_width:n.outerWidth,outer_height:n.outerHeight,hole_width:n.holeWidth,hole_height:n.holeHeight,shape:n.shape,port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,ccw_rotation:n.pcbRotation??0});this.pcb_plated_hole_id=s.pcb_plated_hole_id,t.pcb_solder_paste.insert({layer:"top",shape:n.shape,width:n.outerWidth,height:n.outerHeight,x:i.x,y:i.y,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),t.pcb_solder_paste.insert({layer:"bottom",shape:n.shape,width:n.outerWidth,height:n.outerHeight,x:i.x,y:i.y,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(n.shape==="circular_hole_with_rect_pad"){let s=t.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,hole_diameter:n.holeDiameter,rect_pad_width:n.rectPadWidth,rect_pad_height:n.rectPadHeight,shape:"circular_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,hole_offset_x:n.holeOffsetX,hole_offset_y:n.holeOffsetY,rect_border_radius:n.rectBorderRadius??0});this.pcb_plated_hole_id=s.pcb_plated_hole_id}else if(n.shape==="pill_hole_with_rect_pad"){let s=t.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,hole_width:n.holeWidth,hole_height:n.holeHeight,rect_pad_width:n.rectPadWidth,rect_pad_height:n.rectPadHeight,hole_offset_x:n.holeOffsetX,hole_offset_y:n.holeOffsetY,shape:"pill_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=s.pcb_plated_hole_id}}doInitialPcbPortAttachment(){if(this.root?.pcbDisabled)return;let{db:t}=this.root;t.pcb_plated_hole.update(this.pcb_plated_hole_id,{pcb_port_id:this.matchedPort?.pcb_port_id})}},Cx=class extends Ie{constructor(){super(...arguments);T(this,"pcb_keepout_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Keepout",zodProps:WL}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let t=this.getSubcircuit(),{db:n}=this.root,{_parsedProps:i}=this,r=this._getGlobalPcbPositionBeforeLayout(),o=fo(this._computePcbGlobalTransformBeforeLayout()),s=Math.abs(o.rotation.angle*(180/Math.PI)-90)%180<.01,a=null;i.shape==="circle"?a=n.pcb_keepout.insert({layers:["top"],shape:"circle",radius:i.radius,center:{x:r.x,y:r.y},subcircuit_id:t?.subcircuit_id??void 0,pcb_group_id:t?.getGroup()?.pcb_group_id??void 0}):i.shape==="rect"&&(a=n.pcb_keepout.insert({layers:["top"],shape:"rect",...s?{width:i.height,height:i.width}:{width:i.width,height:i.height},center:{x:r.x,y:r.y},subcircuit_id:t?.subcircuit_id??void 0,pcb_group_id:t?.getGroup()?.pcb_group_id??void 0})),a&&(this.pcb_keepout_id=a.pcb_keepout_id)}},pI=class extends Ie{constructor(){super(...arguments);T(this,"pcb_hole_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Hole",zodProps:EL}}getPcbSize(){let{_parsedProps:t}=this,n=t.shape==="pill";return{width:n?t.width:t.diameter,height:n?t.height:t.diameter}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit(),r=this._getGlobalPcbPositionBeforeLayout(),o=t.pcb_hole.insert({hole_shape:"circle",hole_diameter:n.diameter,x:r.x,y:r.y,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:i?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=o.pcb_hole_id}_getPcbCircuitJsonBounds(){let{db:t}=this.root,n=t.pcb_hole.get(this.pcb_hole_id),i=this.getPcbSize();return{center:{x:n.x,y:n.y},bounds:{left:n.x-i.width/2,top:n.y-i.height/2,right:n.x+i.width/2,bottom:n.y+i.height/2},width:i.width,height:i.height}}_setPositionFromLayout(t){let{db:n}=this.root;n.pcb_hole.update(this.pcb_hole_id,{x:t.x,y:t.y})}},Rx=class extends Ie{constructor(){super(...arguments);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenText",zodProps:lF}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getPrimitiveContainer(),r=this._getGlobalPcbPositionBeforeLayout(),{maybeFlipLayer:o,isFlipped:s}=this._getPcbPrimitiveFlippedHelpers(),a=this.getSubcircuit(),c=0;if(n.pcbRotation!==void 0&&n.pcbRotation!==0)c=n.pcbRotation;else{let h=this._computePcbGlobalTransformBeforeLayout();c=fo(h).rotation.angle*180/Math.PI}s&&(c=(c+180)%360);let l=new Set(n.layers);n.layer&&l.add(n.layer);let u=l.size>0?Array.from(l):["top"];for(let h of u)t.pcb_silkscreen_text.insert({anchor_alignment:n.anchorAlignment,anchor_position:{x:r.x,y:r.y},font:n.font??"tscircuit2024",font_size:n.fontSize??1,layer:o(h),text:n.text??"",ccw_rotation:c,pcb_component_id:i.pcb_component_id,subcircuit_id:a?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}getPcbSize(){let{_parsedProps:t}=this,n=t.fontSize??1,r=(t.text??"").length*n,o=n;return{width:r*n,height:o*n}}},Nf=class extends Ie{constructor(){super(...arguments);T(this,"pcb_cutout_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Cutout",zodProps:IL}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit(),r=this.getGroup()?.pcb_group_id??void 0,o=this._getGlobalPcbPositionBeforeLayout(),a=this.getPrimitiveContainer()?._parsedProps.pcbRotation??0,c;if(n.shape==="rect"){let l=typeof a=="string"?parseInt(a.replace("deg",""),10):a,u=Math.abs(l%180)===90,h={shape:"rect",center:o,width:u?n.height:n.width,height:u?n.width:n.height,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:r};c=t.pcb_cutout.insert(h)}else if(n.shape==="circle"){let l={shape:"circle",center:o,radius:n.radius,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:r};c=t.pcb_cutout.insert(l)}else if(n.shape==="polygon"){let l=this._computePcbGlobalTransformBeforeLayout(),h={shape:"polygon",points:n.points.map(f=>kn(l,f)),subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:r};c=t.pcb_cutout.insert(h)}c&&(this.pcb_cutout_id=c.pcb_cutout_id)}getPcbSize(){let{_parsedProps:t}=this;if(t.shape==="rect")return{width:t.width,height:t.height};if(t.shape==="circle")return{width:t.radius*2,height:t.radius*2};if(t.shape==="polygon"){if(t.points.length===0)return{width:0,height:0};let n=1/0,i=-1/0,r=1/0,o=-1/0;for(let s of t.points)n=Math.min(n,s.x),i=Math.max(i,s.x),r=Math.min(r,s.y),o=Math.max(o,s.y);return{width:i-n,height:o-r}}return{width:0,height:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_cutout_id)return super._getPcbCircuitJsonBounds();let{db:t}=this.root,n=t.pcb_cutout.get(this.pcb_cutout_id);if(!n)return super._getPcbCircuitJsonBounds();if(n.shape==="rect")return{center:n.center,bounds:{left:n.center.x-n.width/2,top:n.center.y+n.height/2,right:n.center.x+n.width/2,bottom:n.center.y-n.height/2},width:n.width,height:n.height};if(n.shape==="circle")return{center:n.center,bounds:{left:n.center.x-n.radius,top:n.center.y+n.radius,right:n.center.x+n.radius,bottom:n.center.y-n.radius},width:n.radius*2,height:n.radius*2};if(n.shape==="polygon"){if(n.points.length===0)return super._getPcbCircuitJsonBounds();let i=1/0,r=-1/0,o=1/0,s=-1/0;for(let a of n.points)i=Math.min(i,a.x),r=Math.max(r,a.x),o=Math.min(o,a.y),s=Math.max(s,a.y);return{center:{x:(i+r)/2,y:(o+s)/2},bounds:{left:i,top:s,right:r,bottom:o},width:r-i,height:s-o}}return super._getPcbCircuitJsonBounds()}_setPositionFromLayout(t){if(!this.pcb_cutout_id)return;let{db:n}=this.root,i=n.pcb_cutout.get(this.pcb_cutout_id);if(i){if(i.shape==="rect"||i.shape==="circle")n.pcb_cutout.update(this.pcb_cutout_id,{...i,center:t});else if(i.shape==="polygon"){let r=this._getPcbCircuitJsonBounds().center,o=t.x-r.x,s=t.y-r.y,a=i.points.map(c=>({x:c.x+o,y:c.y+s}));n.pcb_cutout.update(this.pcb_cutout_id,{...i,points:a})}}}},F2t=({elm:e,pinLabels:t,layer:n,readableRotation:i,anchorAlignment:r})=>{let o=e.text.replace(/[{}]/g,"").toLowerCase(),s=o;if(Array.isArray(t)){let a=parseInt(o.replace(/[^\d]/g,""),10)-1;s=String(t[a]??o)}else typeof t=="object"&&(s=String(t[o]??o));return new Rx({anchorAlignment:r||"center",text:s??o,layer:n||"top",fontSize:e.font_size+.2,pcbX:isNaN(e.anchor_position.x)?0:e.anchor_position.x,pcbY:e.anchor_position.y,pcbRotation:i??0})},z2t=(e,t)=>{let n=parseInt(e||"0",10),i;return t!=null?i=t-n:i=n,(i%360+360)%360},Ef=({componentName:e,componentRotation:t,footprint:n,pinLabels:i,pcbPinLabels:r},o)=>{let s=[];for(let a of o)if(a.type==="pcb_smtpad"&&a.shape==="rect")s.push(new Ex({pcbX:a.x,pcbY:a.y,layer:a.layer,shape:"rect",height:a.height,width:a.width,portHints:a.port_hints,rectBorderRadius:a.rect_border_radius}));else if(a.type==="pcb_smtpad"&&a.shape==="circle")s.push(new Ex({pcbX:a.x,pcbY:a.y,layer:a.layer,shape:"circle",radius:a.radius,portHints:a.port_hints}));else if(a.type==="pcb_silkscreen_path")s.push(new lI({layer:a.layer,route:a.route,strokeWidth:a.stroke_width}));else if(a.type==="pcb_plated_hole")a.shape==="circle"?s.push(new Jp({pcbX:a.x,pcbY:a.y,shape:"circle",holeDiameter:a.hole_diameter,outerDiameter:a.outer_diameter,portHints:a.port_hints})):a.shape==="circular_hole_with_rect_pad"?s.push(new Jp({pcbX:a.x,pcbY:a.y,shape:"circular_hole_with_rect_pad",holeDiameter:a.hole_diameter,rectPadHeight:a.rect_pad_height,rectPadWidth:a.rect_pad_width,portHints:a.port_hints,rectBorderRadius:a.rect_border_radius,holeOffsetX:a.hole_offset_x,holeOffsetY:a.hole_offset_y})):a.shape==="pill"||a.shape==="oval"?s.push(new Jp({pcbX:a.x,pcbY:a.y,shape:a.shape,holeWidth:a.hole_width,holeHeight:a.hole_height,outerWidth:a.outer_width,outerHeight:a.outer_height,portHints:a.port_hints})):a.shape==="pill_hole_with_rect_pad"&&s.push(new Jp({pcbX:a.x,pcbY:a.y,shape:"pill_hole_with_rect_pad",holeShape:"pill",padShape:"rect",holeWidth:a.hole_width,holeHeight:a.hole_height,rectPadWidth:a.rect_pad_width,rectPadHeight:a.rect_pad_height,portHints:a.port_hints,holeOffsetX:a.hole_offset_x,holeOffsetY:a.hole_offset_y}));else if(a.type==="pcb_keepout"&&a.shape==="circle")s.push(new Cx({pcbX:a.center.x,pcbY:a.center.y,shape:"circle",radius:a.radius}));else if(a.type==="pcb_keepout"&&a.shape==="rect")s.push(new Cx({pcbX:a.center.x,pcbY:a.center.y,shape:"rect",width:a.width,height:a.height}));else if(a.type==="pcb_hole"&&a.hole_shape==="circle")s.push(new pI({pcbX:a.x,pcbY:a.y,diameter:a.hole_diameter}));else if(a.type==="pcb_cutout")a.shape==="rect"?s.push(new Nf({pcbX:a.center.x,pcbY:a.center.y,shape:"rect",width:a.width,height:a.height})):a.shape==="circle"?s.push(new Nf({pcbX:a.center.x,pcbY:a.center.y,shape:"circle",radius:a.radius})):a.shape==="polygon"&&s.push(new Nf({shape:"polygon",points:a.points}));else if(a.type==="pcb_silkscreen_text"){let c=z2t(t,a.ccw_rotation);n.includes("pinrow")&&a.text.includes("PIN")?s.push(F2t({elm:a,pinLabels:r??i,layer:a.layer,readableRotation:c,anchorAlignment:a.anchor_alignment})):s.push(new Rx({anchorAlignment:a.anchor_alignment||"center",text:e,fontSize:a.font_size+.2,pcbX:Number.isNaN(a.anchor_position.x)?0:a.anchor_position.x,pcbY:a.anchor_position.y,pcbRotation:c??0}))}else a.type==="pcb_trace"&&s.push(new uI({route:a.route}));return s};function Ox(e){let t=1/0,n=1/0,i=-1/0,r=-1/0,o=!1;for(let c of e)if(c.isPcbPrimitive&&!c.componentName.startsWith("Silkscreen")){let{x:l,y:u}=c._getGlobalPcbPositionBeforeLayout(),{width:h,height:f}=c.getPcbSize();t=Math.min(t,l-h/2),n=Math.min(n,u-f/2),i=Math.max(i,l+h/2),r=Math.max(r,u+f/2),o=!0}else if(c.children.length>0){let l=Ox(c.children);(l.width>0||l.height>0)&&(t=Math.min(t,l.minX),n=Math.min(n,l.minY),i=Math.max(i,l.maxX),r=Math.max(r,l.maxY),o=!0)}if(!o)return{minX:0,minY:0,maxX:0,maxY:0,width:0,height:0};let s=i-t,a=r-n;return s<0&&(s=0),a<0&&(a=0),{minX:t,minY:n,maxX:i,maxY:r,width:s,height:a}}function Hj(e){let t=e%360;return t<0?t+360:t}function D2t(e,t,n,i){return i==="counterclockwise"?n>=t?e>=t&&e<=n:e>=t||e<=n:n<=t?e<=t&&e>=n:e<=t||e>=n}function $2t(e){let t=e.center,n=e.radius,i=e.start_angle_degrees,r=e.end_angle_degrees,o=e.direction??"counterclockwise";if(!t||typeof t.x!="number"||typeof t.y!="number"||typeof n!="number"||typeof i!="number"||typeof r!="number")return null;let s=Hj(i),a=Hj(r),c=new Set([s,a]),l=[0,90,180,270];for(let y of l)D2t(y,s,a,o)&&c.add(y);let u=1/0,h=1/0,f=-1/0,_=-1/0;for(let y of c){let x=y*Math.PI/180,v=t.x+n*Math.cos(x),w=t.y+n*Math.sin(x);u=Math.min(u,v),f=Math.max(f,v),h=Math.min(h,w),_=Math.max(_,w)}return!Number.isFinite(u)||!Number.isFinite(h)?null:{minX:u,maxX:f,minY:h,maxY:_}}function bY(e){let t=1/0,n=1/0,i=-1/0,r=-1/0;for(let o of e){let s,a,c,l;if(o.type==="schematic_component")s=o.center?.x,a=o.center?.y,c=o.size?.width,l=o.size?.height;else if(o.type==="schematic_box")s=o.x,a=o.y,c=o.width,l=o.height;else if(o.type==="schematic_port")s=o.center?.x,a=o.center?.y,c=.2,l=.2;else if(o.type==="schematic_text")s=o.position?.x,a=o.position?.y,c=(o.text?.length??0)*.1,l=.2;else if(o.type==="schematic_line"){let u=o.x1??0,h=o.y1??0,f=o.x2??0,_=o.y2??0;s=(u+f)/2,a=(h+_)/2,c=Math.abs(f-u),l=Math.abs(_-h)}else if(o.type==="schematic_rect")s=o.center?.x,a=o.center?.y,c=o.width,l=o.height;else if(o.type==="schematic_circle"){s=o.center?.x,a=o.center?.y;let u=o.radius;typeof u=="number"&&(c=u*2,l=u*2)}else if(o.type==="schematic_arc"){let u=$2t(o);u&&(t=Math.min(t,u.minX),i=Math.max(i,u.maxX),n=Math.min(n,u.minY),r=Math.max(r,u.maxY));continue}typeof s=="number"&&typeof a=="number"&&typeof c=="number"&&typeof l=="number"&&(t=Math.min(t,s-c/2),i=Math.max(i,s+c/2),n=Math.min(n,a-l/2),r=Math.max(r,a+l/2))}return{minX:t,maxX:i,minY:n,maxY:r}}function B2t(e,t){let n=t.x-e.x,i=t.y-e.y;return Math.abs(n)>Math.abs(i)?n>=0?"right":"left":i>=0?"up":"down"}var Gj=e=>{if(e.length<=1)return!0;let t=e.map(o=>{let s=o._getPcbCircuitJsonBounds();return{left:s.bounds.left,right:s.bounds.right,top:s.bounds.top,bottom:s.bounds.bottom}}),n=Array(t.length).fill(!1).map(()=>Array(t.length).fill(!1));for(let o=0;o<t.length;o++)for(let s=o+1;s<t.length;s++){let a=t[o],c=t[s];n[o][s]=n[s][o]=!(a.right<c.left||a.left>c.right||a.bottom>c.top||a.top<c.bottom)}let i=new Set,r=o=>{i.add(o);for(let s=0;s<t.length;s++)n[o][s]&&!i.has(s)&&r(s)};return r(0),i.size===t.length},Uj=e=>{if(e.length===0)throw new Error("Cannot get center of empty PCB primitives array");let t=e.map(r=>r._getPcbCircuitJsonBounds().center).filter(Boolean),n=t.reduce((r,o)=>r+o.x,0),i=t.reduce((r,o)=>r+o.y,0);return{x:n/t.length,y:i/t.length}},j2t=p.object({name:p.string().optional(),pinNumber:p.number().optional(),aliases:p.array(p.string()).optional(),layer:p.string().optional(),layers:p.array(p.string()).optional()}),Ei=class extends Ie{constructor(t,n={}){if(!t.name&&t.pinNumber!==void 0&&(t.name=`pin${t.pinNumber}`),!t.name)throw new Error("Port must have a name or a pinNumber");super(t);T(this,"source_port_id",null);T(this,"pcb_port_id",null);T(this,"schematic_port_id",null);T(this,"schematicSymbolPortDef",null);T(this,"matchedComponents");T(this,"facingDirection",null);T(this,"originDescription",null);n.originDescription&&(this.originDescription=n.originDescription),this.matchedComponents=[]}get config(){return{componentName:"Port",zodProps:j2t}}_isBoardPinoutFromAttributes(){let t=this.parent;if(t?._parsedProps?.pinAttributes){let n=t._parsedProps.pinAttributes;for(let i of this.getNameAndAliases())if(n[i]?.includeInBoardPinout)return!0}}_getGlobalPcbPositionBeforeLayout(){let t=this.matchedComponents.find(i=>i.isPcbPrimitive),n=this.parent;if(n&&!n.props.footprint)throw new Error(`${n.componentName} "${n.props.name}" does not have a footprint. Add a footprint prop, e.g. <${n.componentName.toLowerCase()} footprint="..." />`);if(!t)throw new Error(`Port ${this} has no matching PCB primitives. This often means the footprint's pads lack matching port hints.`);return t?._getGlobalPcbPositionBeforeLayout()??{x:0,y:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_port_id)return super._getPcbCircuitJsonBounds();let{db:t}=this.root,n=t.pcb_port.get(this.pcb_port_id);return{center:{x:n.x,y:n.y},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getGlobalPcbPositionAfterLayout(){return this._getPcbCircuitJsonBounds().center}_getPortsInternallyConnectedToThisPort(){let t=this.parent;if(!t||!t._getInternallyConnectedPins)return[];let n=t._getInternallyConnectedPins();for(let i of n)if(i.some(r=>r===this))return i;return[]}_hasSchematicPort(){if(this.parent?.getSchematicSymbol())return!!(this.schematicSymbolPortDef||this._getPortsInternallyConnectedToThisPort().some(r=>r.schematicSymbolPortDef));let n=this?.parent?._getSchematicBoxDimensions();return!!(n&&this.props.pinNumber!==void 0&&n.getPortPositionByPinNumber(this.props.pinNumber))}_getGlobalSchematicPositionBeforeLayout(){let t=this.parent?.getSchematicSymbol();if(t){let i=this.schematicSymbolPortDef;if(!i&&(i=this._getPortsInternallyConnectedToThisPort().find(o=>o.schematicSymbolPortDef)?.schematicSymbolPortDef??null,!i))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 r=Gn(this.parent.computeSchematicGlobalTransform(),fn(-t.center.x,-t.center.y));return kn(r,i)}let n=this?.parent?._getSchematicBoxDimensions();if(n&&this.props.pinNumber!==void 0){let i=n.getPortPositionByPinNumber(this.props.pinNumber);if(!i)throw new Error(`Couldn't find position for schematic_port for port ${this.getString()} inside of the schematic box`);return kn(this.parent.computeSchematicGlobalTransform(),i)}throw new Error(`Couldn't find position for schematic_port for port ${this.getString()}`)}_getGlobalSchematicPositionAfterLayout(){let{db:t}=this.root;if(!this.schematic_port_id)throw new Error(`Can't get schematic port position after layout for "${this.getString()}", no schematic_port_id`);let n=t.schematic_port.get(this.schematic_port_id);if(!n)throw new Error(`Schematic port not found when trying to get post-layout position: ${this.schematic_port_id}`);return n.center}registerMatch(t){this.matchedComponents.push(t)}getNameAndAliases(){let{_parsedProps:t}=this;return Array.from(new Set([...t.name?[t.name]:[],...t.aliases??[],...typeof t.pinNumber=="number"?[`pin${t.pinNumber}`,t.pinNumber.toString()]:[],...this.externallyAddedAliases??[]]))}_getMatchingPinAttributes(){let t=this.parent?._parsedProps?.pinAttributes;if(!t)return[];let n=[];for(let i of this.getNameAndAliases()){let r=t[i];r&&n.push(r)}return n}_shouldIncludeInBoardPinout(){return this._getMatchingPinAttributes().some(t=>t.includeInBoardPinout===!0)}isMatchingPort(t){return this.isMatchingAnyOf(t.getNameAndAliases())}getPortSelector(){return`.${this.parent?.props.name} > port.${this.props.name}`}getAvailablePcbLayers(){let{layer:t,layers:n}=this._parsedProps;return n||(t?[t]:Array.from(new Set(this.matchedComponents.flatMap(i=>i.getAvailablePcbLayers()))))}_getDirectlyConnectedTraces(){return this.getSubcircuit().selectAll("trace").filter(i=>!i._couldNotFindPort).filter(i=>i._isExplicitlyConnectedToPort(this))}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=this.getNameAndAliases(),r=t.source_port.insert({name:n.name,pin_number:n.pinNumber,port_hints:i,source_component_id:this.parent?.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id});this.source_port_id=r.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:n}=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 i=n.filter(o=>o.isPcbPrimitive);if(i.length===0)return;let r=null;if(i.length===1&&(r=i[0]._getPcbCircuitJsonBounds().center),i.length>1){if(!Gj(i))throw new Error(`${this.getString()} has multiple non-overlapping pcb matches, unclear how to place pcb_port: ${i.map(o=>o.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)`);r=Uj(i)}if(r){let o=this.getSubcircuit(),s=this._shouldIncludeInBoardPinout(),a=t.pcb_port.insert({pcb_component_id:this.parent?.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...s?{is_board_pinout:!0}:{},...r,source_port_id:this.source_port_id,is_board_pinout:this._isBoardPinoutFromAttributes()});this.pcb_port_id=a.pcb_port_id}else{let o=i[0];throw new Error(`${o.getString()} does not have a center or _getGlobalPcbPositionBeforeLayout method (needed for pcb_port placement)`)}}updatePcbPortRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root;if(this.pcb_port_id)return;let n=this.matchedComponents.filter(a=>a.isPcbPrimitive);if(n.length===0)return;let i=null;if(n.length===1&&(i=n[0]._getPcbCircuitJsonBounds().center),n.length>1)try{Gj(n)&&(i=Uj(n))}catch{}if(!i)return;let r=this.getSubcircuit(),o=this._shouldIncludeInBoardPinout(),s=t.pcb_port.insert({pcb_component_id:this.parent?.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...o?{is_board_pinout:!0}:{},...i,source_port_id:this.source_port_id,is_board_pinout:this._isBoardPinoutFromAttributes()});this.pcb_port_id=s.pcb_port_id}doInitialSchematicPortRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=this.getPrimitiveContainer();if(!i||!this._hasSchematicPort())return;let r=i._getGlobalSchematicPositionBeforeLayout(),o=this._getGlobalSchematicPositionBeforeLayout(),s=null,a=i._getSchematicBoxDimensions();a&&n.pinNumber!==void 0&&(s=a.getPortPositionByPinNumber(n.pinNumber)),this.getSubcircuit().props._schDebugObjectsEnabled&&t.schematic_debug_object.insert({shape:"rect",center:o,size:{width:.1,height:.1},label:"obstacle"}),s?.side?this.facingDirection={left:"left",right:"right",top:"up",bottom:"down"}[s.side]:this.facingDirection=B2t(r,o);let c=t.source_port.get(this.source_port_id),l=[];for(let y of c?.port_hints??[])y.match(/^(pin)?\d+$/)||y.match(/^(left|right)/)&&!c?.name.match(/^(left|right)/)||l.push(y);let u;this.parent?.props?.showPinAliases&&l.length>0?u=l.join("/"):l.length>0&&(u=l[0]);let f={type:"schematic_port",schematic_component_id:this.parent?.schematic_component_id,center:o,source_port_id:this.source_port_id,facing_direction:this.facingDirection,distance_from_component_edge:.4,side_of_component:s?.side,pin_number:n.pinNumber,true_ccw_index:s?.trueIndex,display_pin_label:u,is_connected:!1};for(let y of this._getMatchingPinAttributes())y.requiresPower&&(f.has_input_arrow=!0),y.providesPower&&(f.has_output_arrow=!0);let _=t.schematic_port.insert(f);this.schematic_port_id=_.schematic_port_id}_getSubcircuitConnectivityKey(){return this.root?.db.source_port.get(this.source_port_id)?.subcircuit_connectivity_map_key}_setPositionFromLayout(t){let{db:n}=this.root;this.pcb_port_id&&n.pcb_port.update(this.pcb_port_id,{x:t.x,y:t.y})}_hasMatchedPcbPrimitive(){return this.matchedComponents.some(t=>t.isPcbPrimitive)}_getNetLabelText(){return`${this.parent?.props.name}_${this.props.name}`}},vY=e=>{let t=e.find(n=>/^(pin)?\d+$/.test(n));return t?Number.parseInt(t.replace(/^pin/,"")):null};function Mf(e,t){let n=vY(e);if(!n)return null;let r=[...e.filter(o=>o.toString()!==n.toString()&&o!==`pin${n}`),...t?.additionalAliases?.[`pin${n}`]??[]];return new Ei({pinNumber:n,aliases:r})}var Y2t=e=>{for(let t of["leftSide","rightSide","topSide","bottomSide"])if(t in e&&typeof e[t]=="number")throw new Error(`A number was specified for "${t}", you probably meant to use "size" not "side"`);return"leftSide"in e||"rightSide"in e||"topSide"in e||"bottomSide"in e},X2t=e=>{if(Y2t(e))return{leftSize:e.leftSide?.pins.length??0,rightSize:e.rightSide?.pins.length??0,topSize:e.topSide?.pins.length??0,bottomSize:e.bottomSide?.pins.length??0};let{leftSize:t=0,rightSize:n=0,topSize:i=0,bottomSize:r=0}=e;return{leftSize:t,rightSize:n,topSize:i,bottomSize:r}};function wY(e){let t=e;return t.leftSide!==void 0||t.rightSide!==void 0||t.topSide!==void 0||t.bottomSide!==void 0}var V2t=e=>{let t=e.portDistanceFromEdge??.4,n=e.schPortArrangement?X2t(e.schPortArrangement):null,i={left:0,right:0,top:0,bottom:0},r=e.pinCount??null;if(r===null)if(n)r=n.leftSize+n.rightSize+n.topSize;else throw new Error("Could not determine pin count for the schematic box");if(r&&!n){let y=Math.floor(r/2);n={leftSize:r-y,rightSize:y,topSize:0,bottomSize:0}}n||(n={leftSize:0,rightSize:0,topSize:0,bottomSize:0});let o=({side:y,sideIndex:x,truePinIndex:v})=>{if(!e.schPortArrangement||!wY(e.schPortArrangement))return v+1;let w={left:"top-to-bottom",bottom:"left-to-right",right:"bottom-to-top",top:"right-to-left"}[y],S=e.schPortArrangement?.[`${y}Side`]?.direction??w,C=e.schPortArrangement?.[`${y}Side`]?.pins,E=x;return S!==w&&(E=C.length-x-1),Rf(C[E],e.pinLabels)},s=[],a=0,c=0;for(let y=0;y<n.leftSize;y++){let x=o({side:"left",sideIndex:y,truePinIndex:c}),v=e.numericSchPinStyle?.[`pin${x}`]??e.numericSchPinStyle?.[x];v?.topMargin&&(a+=v.topMargin),s.push({trueIndex:c,pinNumber:x,side:"left",distanceFromOrthogonalEdge:a}),v?.bottomMargin&&(a+=v.bottomMargin),y===n.leftSize-1?i.left=a:a+=e.schPinSpacing,c++}a=0;for(let y=0;y<n.bottomSize;y++){let x=o({side:"bottom",sideIndex:y,truePinIndex:c}),v=e.numericSchPinStyle?.[`pin${x}`]??e.numericSchPinStyle?.[x];v?.leftMargin&&(a+=v.leftMargin),s.push({trueIndex:c,pinNumber:x,side:"bottom",distanceFromOrthogonalEdge:a}),v?.rightMargin&&(a+=v.rightMargin),y===n.bottomSize-1?i.bottom=a:a+=e.schPinSpacing,c++}a=0;for(let y=0;y<n.rightSize;y++){let x=o({side:"right",sideIndex:y,truePinIndex:c}),v=e.numericSchPinStyle?.[`pin${x}`]??e.numericSchPinStyle?.[x];v?.bottomMargin&&(a+=v.bottomMargin),s.push({trueIndex:c,pinNumber:x,side:"right",distanceFromOrthogonalEdge:a}),v?.topMargin&&(a+=v.topMargin),y===n.rightSize-1?i.right=a:a+=e.schPinSpacing,c++}a=0;for(let y=0;y<n.topSize;y++){let x=o({side:"top",sideIndex:y,truePinIndex:c}),v=e.numericSchPinStyle?.[`pin${x}`]??e.numericSchPinStyle?.[x];v?.rightMargin&&(a+=v.rightMargin),s.push({trueIndex:c,pinNumber:x,side:"top",distanceFromOrthogonalEdge:a}),v?.leftMargin&&(a+=v.leftMargin),y===n.topSize-1?i.top=a:a+=e.schPinSpacing,c++}let l=e.schWidth;if(l===void 0){l=Math.max(i.top+e.schPinSpacing*2,i.bottom+e.schPinSpacing*2);let y=e.pinLabels?Math.max(...Object.values(e.pinLabels).map(v=>v.length*.1)):0,x=y>0?1.1:0;l=Math.max(l,y+x)}let u=e.schHeight;u||(u=Math.max(i.left+e.schPinSpacing*2,i.right+e.schPinSpacing*2));let h={left:{x:-l/2-t,y:i.left/2},bottom:{x:-i.bottom/2,y:-u/2-t},right:{x:l/2+t,y:-i.right/2},top:{x:i.top/2,y:u/2+t}},f={left:{x:0,y:-1},right:{x:0,y:1},top:{x:-1,y:0},bottom:{x:1,y:0}},_=s.map(y=>{let{distanceFromOrthogonalEdge:x,side:v}=y,w=h[v],S=f[v];return{x:w.x+x*S.x,y:w.y+x*S.y,...y}});return{getPortPositionByPinNumber(y){let x=_.find(v=>v.pinNumber.toString()===y.toString());return x||null},getSize(){return{width:l,height:u}},getSizeIncludingPins(){return{width:l+(n.leftSize||n.rightSize?.4:0),height:u+(n.topSize||n.bottomSize?.4:0)}},pinCount:r}},H2t=(0,SY.default)("tscircuit:core:footprint"),PY=class extends Ie{get config(){return{componentName:"Footprint",zodProps:kL}}doInitialPcbFootprintLayout(){if(this.root?.pcbDisabled)return;let e=this.children.filter(h=>h.componentName==="Constraint");if(e.length===0)return;let{isFlipped:t}=this._getPcbPrimitiveFlippedHelpers(),n=h=>t&&"left"in h&&"right"in h?{...h,left:h.right,right:h.left}:h,i=e.flatMap(h=>h._getAllReferencedComponents().componentsWithSelectors).map(({component:h,selector:f,componentSelector:_,edge:y})=>({component:h,selector:f,componentSelector:_,edge:y,bounds:h._getPcbCircuitJsonBounds()}));if(i.some(h=>h.edge))throw new Error("edge constraints not implemented yet for footprint layout, contributions welcome!");function r(h){return i.find(({selector:f})=>f===h)}let o=new up,s={};function a(h){return h in s||(s[h]=new Is(h),o.addEditVariable(s[h],mn.weak)),s[h]}for(let{selector:h,bounds:f}of i){let _=a(`${h}_x`),y=a(`${h}_y`);o.suggestValue(_,f.center.x),o.suggestValue(y,f.center.y)}for(let h of e){let f=h._parsedProps;if("xDist"in f){let{xDist:_,left:y,right:x,edgeToEdge:v,centerToCenter:w}=n(f),S=a(`${y}_x`),C=a(`${x}_x`),E=r(y)?.bounds,R=r(x)?.bounds;if(w){let I=new bn(C,[-1,S]);o.addConstraint(new ti(I,zn.Eq,f.xDist,mn.required))}else if(v){let I=new bn(C,-R.width/2,[-1,S],-E.width/2);o.addConstraint(new ti(I,zn.Eq,f.xDist,mn.required))}}else if("yDist"in f){let{yDist:_,top:y,bottom:x,edgeToEdge:v,centerToCenter:w}=f,S=a(`${y}_y`),C=a(`${x}_y`),E=r(y)?.bounds,R=r(x)?.bounds;if(w){let I=new bn(S,[-1,C]);o.addConstraint(new ti(I,zn.Eq,f.yDist,mn.required))}else if(v){let I=new bn(S,E.height/2,[-1,C],-R.height/2);o.addConstraint(new ti(I,zn.Eq,f.yDist,mn.required))}}else if("sameY"in f){let{for:_}=f;if(_.length<2)continue;let y=_.map(v=>a(`${v}_y`)),x=new bn(...y.slice(1));o.addConstraint(new ti(x,zn.Eq,y[0],mn.required))}else if("sameX"in f){let{for:_}=f;if(_.length<2)continue;let y=_.map(v=>a(`${v}_x`)),x=new bn(...y.slice(1));o.addConstraint(new ti(x,zn.Eq,y[0],mn.required))}}o.updateVariables(),H2t.enabled&&(console.log("Solution to layout constraints:"),console.table(Object.entries(s).map(([h,f])=>({var:h,val:f.value()}))));let c={left:1/0,right:-1/0,top:-1/0,bottom:1/0};for(let{selector:h,bounds:{width:f,height:_}}of i){let y=a(`${h}_x`),x=a(`${h}_y`),v=y.value()-f/2,w=y.value()+f/2,S=x.value()+_/2,C=x.value()-_/2;c.left=Math.min(c.left,v),c.right=Math.max(c.right,w),c.top=Math.max(c.top,S),c.bottom=Math.min(c.bottom,C)}let l={x:-(c.right+c.left)/2,y:-(c.top+c.bottom)/2},u=this.getPrimitiveContainer()._getGlobalPcbPositionBeforeLayout();l.x+=u.x,l.y+=u.y;for(let{component:h,selector:f}of i){let _=a(`${f}_x`),y=a(`${f}_y`);h._setPositionFromLayout({x:_.value()+l.x,y:y.value()+l.y})}}},GT=p.union([p.number(),p.string()]),qj=p.object({x:GT,y:GT,z:GT}),TY=class extends Ie{get config(){return{componentName:"CadModel",zodProps:JL}}doInitialCadModelRender(){let e=this._findParentWithPcbComponent();if(!e||!e.pcb_component_id)return;let{db:t}=this.root,{boardThickness:n=0}=this.root?._getBoard()??{},i=e._getPcbCircuitJsonBounds(),r=t.pcb_component.get(e.pcb_component_id),o=this._parsedProps;if(!o||typeof o.modelUrl!="string")return;let s=e._computePcbGlobalTransformBeforeLayout(),c=fo(s).rotation.angle*180/Math.PI,l=qj.parse({x:0,y:0,z:0});if(typeof o.rotationOffset=="number")l.z=Number(o.rotationOffset);else if(typeof o.rotationOffset=="object"){let x=qj.parse(o.rotationOffset);l.x=Number(x.x),l.y=Number(x.y),l.z=Number(x.z)}let u=qy.parse({x:o.pcbX??0,y:o.pcbY??0,z:o.pcbZ??0,...typeof o.positionOffset=="object"?o.positionOffset:{}}),h=e.props.layer==="bottom"?"bottom":"top",f=new URL(o.modelUrl).pathname.split(".").pop()?.toLowerCase(),_={};f==="stl"?_.model_stl_url=this._addCachebustToModelUrl(o.modelUrl):f==="obj"?_.model_obj_url=this._addCachebustToModelUrl(o.modelUrl):f==="gltf"?_.model_gltf_url=this._addCachebustToModelUrl(o.modelUrl):f==="glb"?_.model_glb_url=this._addCachebustToModelUrl(o.modelUrl):f==="step"||f==="stp"?_.model_step_url=this._addCachebustToModelUrl(o.modelUrl):f==="wrl"||f==="vrml"?_.model_wrl_url=this._addCachebustToModelUrl(o.modelUrl):_.model_stl_url=this._addCachebustToModelUrl(o.modelUrl);let y=t.cad_component.insert({position:{x:i.center.x+Number(u.x),y:i.center.y+Number(u.y),z:(h==="bottom"?-n/2:n/2)+Number(u.z)},rotation:{x:Number(l.x),y:(h==="top"?0:180)+Number(l.y),z:h==="bottom"?-(c+Number(l.z))+180:c+Number(l.z)},pcb_component_id:e.pcb_component_id,source_component_id:e.source_component_id,model_unit_to_mm_scale_factor:typeof o.modelUnitToMmScale=="number"?o.modelUnitToMmScale:void 0,..._});this.cad_component_id=y.cad_component_id}_findParentWithPcbComponent(){let e=this.parent;for(;e&&!e.pcb_component_id;)e=e.parent;return e}_addCachebustToModelUrl(e){if(!e||!e.includes("modelcdn.tscircuit.com"))return e;let t=this.root?.getClientOrigin()??"";return`${e}${e.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(t)}`}},IY=class extends Ie{constructor(){super(...arguments);T(this,"isPrimitiveContainer",!0)}get config(){return{componentName:"CadAssembly",zodProps:KL}}},G2t=(e,t)=>{if(!e)return;let n={};for(let[i,r]of Object.entries(e)){let o=Rf(i,t),s={leftMargin:r.marginLeft??r.leftMargin,rightMargin:r.marginRight??r.rightMargin,topMargin:r.marginTop??r.topMargin,bottomMargin:r.marginBottom??r.bottomMargin};n[`pin${o}`]={...n[`pin${o}`],...s}}return n},Wj=class{constructor({input:e}){T(this,"input");this.input=e}solveAndMapToTraces(){let e=[];for(let t of this.input.connections){if(t.pointsToConnect.length!==2)continue;let[n,i]=t.pointsToConnect,r={type:"pcb_trace",pcb_trace_id:"",connection_name:t.name,route:[{route_type:"wire",x:n.x,y:n.y,layer:"top",width:.1},{route_type:"wire",x:i.x,y:i.y,layer:"top",width:.1}]};e.push(r)}return e}},U2t=e=>{let t=Math.min(...e.map(o=>o.center.x)),n=Math.max(...e.map(o=>o.center.x)),i=Math.min(...e.map(o=>o.center.y)),r=Math.max(...e.map(o=>o.center.y));return{minX:t,maxX:n,minY:i,maxY:r}},Zj=["top","bottom","inner1","inner2"],Ix=(e,t=[])=>{let n=[];if(t.length===0){let a=e[0].layers;for(let c of a)n.push(...Ix(e.slice(1),[c]));return n}if(e.length===0)return[];let i=e[0],r=i.via||i.optional_via,o=t[t.length-1];if(e.length===1){let a=i;return a.layers&&r?a.layers.map(c=>({layer_path:[...t,c]})):a.layers?.includes(o)?[{layer_path:[...t,o]}]:[]}if(!r)return i.layers&&!i.layers.includes(o)?[]:Ix(e.slice(1),t.concat([o]));let s=(i.optional_via?Zj:Zj.filter(a=>a!==o)).filter(a=>!i.layers||i.layers?.includes(a));for(let a of s)n.push(...Ix(e.slice(1),t.concat(a)));return n};function Kj(e){let t={x:e.to.x-e.from.x,y:e.to.y-e.from.y},n=Math.abs(t.x),i=Math.abs(t.y);return n>i?t.x>0?"right":"left":t.y>0?"down":"up"}function Up(e,t){return Math.hypot(e.x-t.x,e.y-t.y)}var q2t=e=>{if(e.length===1)return e[0];if(e.some(c=>c.length===0))throw new Error("Cannot merge routes with zero length");let t=[],n=e[0][0],i=e[0][e[0].length-1],r=e[1][0],o=e[1][e[1].length-1],s=Math.min(Up(n,r),Up(n,o)),a=Math.min(Up(i,r),Up(i,o));s<a?t.push(...e[0].reverse()):t.push(...e[0]);for(let c=1;c<e.length;c++){let l=t[t.length-1],u=e[c],h=u[0],f=u[u.length-1],_=Up(l,h),y=Up(l,f);_<y?t.push(...u):t.push(...u.reverse())}for(let c=1;c<t.length-1;c++){let l=t[c-1],u=t[c];l.route_type==="wire"&&u.route_type==="wire"&&l.layer!==u.layer&&t.splice(c,0,{x:l.x,y:l.y,from_layer:l.layer,to_layer:u.layer,route_type:"via"})}return t},W2t=(e,t)=>{let n="_getGlobalPcbPositionBeforeLayout"in e?e._getGlobalPcbPositionBeforeLayout():e,i="_getGlobalPcbPositionBeforeLayout"in t?t._getGlobalPcbPositionBeforeLayout():t;return Math.sqrt((n.x-i.x)**2+(n.y-i.y)**2)};function Z2t(e,t){if(t.length===0)throw new Error("No candidates given to getClosest method");let n=t[0],i=1/0;for(let r of t){let o=W2t(e,r);o<i&&(n=r,i=o)}return n}var K2t=(e,t)=>{let n=0;n+=e.length??0,n+=t.filter(i=>i.is_crossing).length;for(let i=1;i<t.length;i++){let r=t[i-1],o=t[i],s=Math.abs(r.from.x-r.to.x)<.01,a=Math.abs(o.from.x-o.to.x)<.01;s!==a&&n++}return n},Of=e=>({up:"bottom",down:"top",left:"right",right:"left"})[e]??null,JT=({firstEdge:e,firstEdgePort:t,firstDominantDirection:n,lastEdge:i,lastEdgePort:r,lastDominantDirection:o})=>{if(e&&t)return JT({lastEdge:{from:e.to,to:e.from},lastEdgePort:t,lastDominantDirection:n}).reverse().map(a=>({from:a.to,to:a.from}));let s=[];if(i&&r){let a={x:i.to.x,y:i.to.y};o==="left"||o==="right"?(a.x=r.position.x,s.push({from:i.to,to:{...a}}),s.push({from:a,to:{...r.position}})):(a.y=r.position.y,s.push({from:i.to,to:{...a}}),s.push({from:a,to:{...r.position}}))}return s=s.filter(a=>Si(a.from,a.to)>.01),s};function J2t(e){try{return[e(),null]}catch(t){return[null,t]}}var Q2t=(e,{db:t})=>{let n=e.map(i=>{let r=t.source_port.get(i.source_port_id);if(!r?.source_component_id)return null;let o=t.source_component.get(r.source_component_id);return o?.ftype==="simple_capacitor"?o.max_decoupling_trace_length:null}).filter(i=>i!==null);if(n.length!==0)return Math.min(...n)};function tvt({ports:e,nets:t}){if(e.length>=2)return`${e[0]?.selector} to ${e[1]?.selector}`;if(e.length===1&&t.length===1)return`${e[0]?.selector} to net.${t[0]._parsedProps.name}`}var evt=(e,{db:t})=>{let n=t.pcb_board.list()[0];if(n.outline){let c=n.outline,l=(u,h)=>{let f=!1;for(let _=0,y=h.length-1;_<h.length;y=_++){let x=h[_].x,v=h[_].y,w=h[y].x,S=h[y].y;v>u.y!=S>u.y&&u.x<(w-x)*(u.y-v)/(S-v)+x&&(f=!f)}return f};return e.some(u=>!l(u,c))}let i=n.width,r=n.height,o=n.center.x,s=n.center.y;return e.some(c=>c.x<o-i/2||c.y<s-r/2||c.x>o+i/2||c.y>s+r/2)},Jj=(e,t)=>Math.abs(e-t)<1e-4,nvt=(e,t,{viaDiameter:n=.5}={})=>{let i=[];for(let r=0;r<e.length-1;r++){let[o,s]=[e[r],e[r+1]],a=r-1>=0?e[r-1]:null,c=Jj(o.y,s.y),l=Jj(o.x,s.x);if(!c&&!l)throw new Error(`getObstaclesFromTrace currently only supports horizontal and vertical traces (not diagonals) Conflicting trace: ${t}, start: (${o.x}, ${o.y}), end: (${s.x}, ${s.y})`);let u={type:"rect",layers:[o.layer],center:{x:(o.x+s.x)/2,y:(o.y+s.y)/2},width:c?Math.abs(o.x-s.x):.1,height:l?Math.abs(o.y-s.y):.1,connectedTo:[t]};if(i.push(u),a&&a.layer===o.layer&&o.layer!==s.layer){let h={type:"rect",layers:[o.layer,s.layer],center:{x:o.x,y:o.y},connectedTo:[t],width:n,height:n};i.push(h)}}return i};function MY(e,t=4){let{center:n,width:i,height:r,rotation:o}=e,s=[],a=o*Math.PI/180,c=Math.cos(a),l=Math.sin(a),u=(o%360+360)%360;if(r<=i?u>=45&&u<135||u>=225&&u<315:u>=135&&u<225||u>=315||u<45){let f=i/t;for(let _=0;_<t;_++){let y=(_-t/2+.5)*f,x=-y*c,v=-y*l,w=f*1.1,S=Math.abs(r*c)+Math.abs(f*l);s.push({center:{x:n.x+x,y:n.y+v},width:w,height:S})}}else{let f=r/t;for(let _=0;_<t;_++){let y=(_-t/2+.5)*f,x=-y*l,v=y*c,w=Math.abs(i*c)+Math.abs(f*l),S=f*1.1;s.push({center:{x:n.x+x,y:n.y+v},width:w,height:S})}}return s}function ivt(e,t={}){if(e.length<3)return[];let{rectHeight:n=.1}=t,i=[],r=e.map(a=>a.y),o=Math.min(...r),s=Math.max(...r);for(let a=o;a<s;a+=n){let c=a+n/2,l=[];for(let u=0;u<e.length;u++){let h=e[u],f=e[(u+1)%e.length];if(h.y<=c&&f.y>c||f.y<=c&&h.y>c){let _=(c-h.y)*(f.x-h.x)/(f.y-h.y)+h.x;l.push(_)}}l.sort((u,h)=>u-h);for(let u=0;u<l.length;u+=2)if(u+1<l.length){let h=l[u],_=l[u+1]-h;_>1e-6&&i.push({center:{x:h+_/2,y:c},width:_,height:n})}}return i}function rvt(e,t={}){let{center:n,radius:i}=e,{rectHeight:r=.1}=t,o=[],s=Math.ceil(i*2/r);for(let a=0;a<s;a++){let c=n.y-i+(a+.5)*r,l=c-n.y,u=Math.sqrt(i*i-l*l);u>0&&o.push({center:{x:n.x,y:c},width:u*2,height:r})}return o}var Wa=["top","inner1","inner2","bottom"],hI=(e,t)=>{let n=r=>t?r.concat(r.map(o=>t?.getNetConnectedToId(o)).filter(Boolean)):r,i=[];for(let r of e)if(r.type==="pcb_smtpad"){if(r.shape==="circle")i.push({type:"oval",layers:[r.layer],center:{x:r.x,y:r.y},width:r.radius*2,height:r.radius*2,connectedTo:n([r.pcb_smtpad_id])});else if(r.shape==="rect")i.push({type:"rect",layers:[r.layer],center:{x:r.x,y:r.y},width:r.width,height:r.height,connectedTo:n([r.pcb_smtpad_id])});else if(r.shape==="rotated_rect"){let o={center:{x:r.x,y:r.y},width:r.width,height:r.height,rotation:r.ccw_rotation},s=MY(o);for(let a of s)i.push({type:"rect",layers:[r.layer],center:a.center,width:a.width,height:a.height,connectedTo:n([r.pcb_smtpad_id])})}}else if(r.type==="pcb_keepout")r.shape==="circle"?i.push({type:"oval",layers:r.layers,center:{x:r.center.x,y:r.center.y},width:r.radius*2,height:r.radius*2,connectedTo:[]}):r.shape==="rect"&&i.push({type:"rect",layers:r.layers,center:{x:r.center.x,y:r.center.y},width:r.width,height:r.height,connectedTo:[]});else if(r.type==="pcb_cutout"){if(r.shape==="rect")i.push({type:"rect",layers:Wa,center:{x:r.center.x,y:r.center.y},width:r.width,height:r.height,connectedTo:[]});else if(r.shape==="circle"){let o=rvt({center:r.center,radius:r.radius},{rectHeight:.6});for(let s of o)i.push({type:"rect",layers:Wa,center:s.center,width:s.width,height:s.height,connectedTo:[]})}else if(r.shape==="polygon"){let o=ivt(r.points,{rectHeight:.6});for(let s of o)i.push({type:"rect",layers:Wa,center:s.center,width:s.width,height:s.height,connectedTo:[]})}}else if(r.type==="pcb_hole")r.hole_shape==="oval"?i.push({type:"oval",center:{x:r.x,y:r.y},width:r.hole_width,height:r.hole_height,connectedTo:[]}):r.hole_shape==="square"?i.push({type:"rect",layers:Wa,center:{x:r.x,y:r.y},width:r.hole_diameter,height:r.hole_diameter,connectedTo:[]}):(r.hole_shape==="round"||r.hole_shape==="circle")&&i.push({type:"rect",layers:Wa,center:{x:r.x,y:r.y},width:r.hole_diameter,height:r.hole_diameter,connectedTo:[]});else if(r.type==="pcb_plated_hole")r.shape==="circle"?i.push({type:"oval",layers:Wa,center:{x:r.x,y:r.y},width:r.outer_diameter,height:r.outer_diameter,connectedTo:n([r.pcb_plated_hole_id])}):r.shape==="circular_hole_with_rect_pad"?i.push({type:"rect",layers:Wa,center:{x:r.x,y:r.y},width:r.rect_pad_width,height:r.rect_pad_height,connectedTo:n([r.pcb_plated_hole_id])}):(r.shape==="oval"||r.shape==="pill")&&i.push({type:"oval",layers:Wa,center:{x:r.x,y:r.y},width:r.outer_width,height:r.outer_height,connectedTo:n([r.pcb_plated_hole_id])});else if(r.type==="pcb_trace"){let o=nvt(r.route.map(s=>({x:s.x,y:s.y,layer:"layer"in s?s.layer:s.from_layer})),r.source_trace_id);i.push(...o)}else r.type==="pcb_via"&&i.push({type:"rect",layers:r.layers,center:{x:r.x,y:r.y},connectedTo:[],width:r.outer_diameter,height:r.outer_diameter});return i},Ka=({anchor_position:e,anchor_side:t,text:n,font_size:i=.18})=>{let r=.1*(i/.18),o=n.length*r,s=i,a={...e};switch(t){case"right":a.x-=o/2;break;case"left":a.x+=o/2;break;case"top":a.y-=s/2;break;case"bottom":a.y+=s/2;break}return a},dI=({db:e,source_trace_id:t,sameNetOnly:n,differentNetOnly:i})=>{!n&&!i&&(i=!0);let r=e.source_trace.get(t),o=[];for(let s of e.schematic_trace.list()){if(s.source_trace_id===t)continue;let c=e.source_trace.get(s.source_trace_id)?.subcircuit_connectivity_map_key===r.subcircuit_connectivity_map_key;i&&c||n&&!c||o.push(s)}return o},ovt=({edges:e,otherEdges:t})=>{let n=[...e];for(let i=0;i<n.length;i++){if(i>2e3)throw new Error("Over 2000 iterations spent inside createSchematicTraceCrossingSegments, you have triggered an infinite loop, please report this!");let r=n[i],o=Math.abs(r.from.x-r.to.x)<.01?"vertical":r.from.y===r.to.y?"horizontal":"not-orthogonal";if(o==="not-orthogonal")continue;let s=[];for(let x of t){let v=x.from.x===x.to.x?"vertical":x.from.y===x.to.y?"horizontal":"not-orthogonal";if(v==="not-orthogonal"||o===v)continue;if(Aa([r.from,r.to],[x.from,x.to],{lineThickness:.01})){let S=o==="vertical"?r.from.x:x.from.x,C=o==="vertical"?x.from.y:r.from.y,E={x:S,y:C};s.push({otherEdge:x,crossingPoint:E,distanceFromEdgeFrom:Si(r.from,E)})}}if(s.length===0)continue;let a=s[0];for(let x of s)x.distanceFromEdgeFrom<a.distanceFromEdgeFrom&&(a=x);let c=a.crossingPoint,l=.075;if(c.x===r.from.x&&c.y===r.from.y)continue;let u=rg(r.from,c),h={x:c.x-u.x*l/2,y:c.y-u.y*l/2},f={x:c.x+u.x*l/2,y:c.y+u.y*l/2},_=Si(f,r.to)<l,y=[{from:r.from,to:h},{from:h,to:f,is_crossing:!0},{from:f,to:r.to}];n.splice(i,1,...y),i+=y.length-2,_&&i++}return n},QT=.001,qp=(e,t)=>{let n=Math.min(t.from.x,t.to.x),i=Math.max(t.from.x,t.to.x),r=Math.min(t.from.y,t.to.y),o=Math.max(t.from.y,t.to.y);return e.x>=n&&e.x<=i&&e.y>=r&&e.y<=o},Qj=e=>{let t=Math.abs(e.from.x-e.to.x)<QT,n=Math.abs(e.from.y-e.to.y)<QT;return t?"vertical":n?"horizontal":"diagonal"},svt=(e,t)=>{let n=Qj(e),i=Qj(t);if(n===i)return null;if(n==="vertical"&&i==="horizontal"||n==="horizontal"&&i==="vertical"){let h=n==="vertical"?e:t,f=n==="horizontal"?e:t,_=h.from.x,y=f.from.y,x={x:_,y};return qp(x,e)&&qp(x,t)?x:null}if(n==="vertical"||i==="vertical"){let h=n==="vertical"?e:t,f=n==="vertical"?t:e,_=h.from.x,y=(f.to.y-f.from.y)/(f.to.x-f.from.x),x=f.from.y-y*f.from.x,v=y*_+x,w={x:_,y:v};return qp(w,e)&&qp(w,t)?w:null}let r=(e.to.y-e.from.y)/(e.to.x-e.from.x),o=e.from.y-r*e.from.x,s=(t.to.y-t.from.y)/(t.to.x-t.from.x),a=t.from.y-s*t.from.x;if(Math.abs(r-s)<QT)return null;let c=(a-o)/(r-s),l=r*c+o,u={x:c,y:l};return qp(u,e)&&qp(u,t)?u:null},avt=({edges:e,db:t,source_trace_id:n})=>{let i=dI({db:t,source_trace_id:n,sameNetOnly:!0}).flatMap(o=>o.edges),r=new Map;for(let o of e)for(let s of i){let a=svt(o,s);if(a){let c=`${a.x.toFixed(6)},${a.y.toFixed(6)}`;r.has(c)||r.set(c,a)}}return Array.from(r.values())};function cvt(e,t={}){let{minX:n,maxX:i,minY:r,maxY:o}=e,s=t.padding??1;if(!isFinite(n)||!isFinite(i)||!isFinite(r)||!isFinite(o))return[];let a=n-s,c=i+s,l=o+s,u=r-s,h=.01;return[{type:"rect",layers:["top"],center:{x:(a+c)/2,y:l},width:c-a,height:h,connectedTo:[]},{type:"rect",layers:["top"],center:{x:(a+c)/2,y:u},width:c-a,height:h,connectedTo:[]},{type:"rect",layers:["top"],center:{x:a,y:(l+u)/2},width:h,height:l-u,connectedTo:[]},{type:"rect",layers:["top"],center:{x:c,y:(l+u)/2},width:h,height:l-u,connectedTo:[]}]}var lvt=e=>{let t=e.root.db,n=e._findConnectedPorts().ports??[],i=new Set(n.map(s=>s.schematic_port_id)),r=[];for(let s of t.toArray()){if(s.type==="schematic_component"){let a=!!s.symbol_name,c=s.size.width>s.size.height?"horz":"vert";r.push({type:"rect",layers:["top"],center:s.center,width:s.size.width+(a&&c==="horz"?-.5:0),height:s.size.height+(a&&c==="vert"?-.5:0),connectedTo:[]})}if(s.type==="schematic_port"){if(i.has(s.schematic_port_id))continue;let a=s.facing_direction?og(s.facing_direction):{x:0,y:0};r.push({type:"rect",layers:["top"],center:{x:s.center.x-a.x*.1,y:s.center.y-a.y*.1},width:.1+Math.abs(a.x)*.3,height:.1+Math.abs(a.y)*.3,connectedTo:[]})}s.type==="schematic_text"&&r.push({type:"rect",layers:["top"],center:s.position,width:(s.text?.length??0)*.1,height:.2,connectedTo:[]}),s.type==="schematic_box"&&r.push({type:"rect",layers:["top"],center:{x:s.x,y:s.y},width:s.width,height:s.height,connectedTo:[]})}let o=bY(t.toArray());return r.push(...cvt(o,{padding:1})),r},uvt=({edges:e,db:t,source_trace_id:n})=>{let i=t.source_trace.get(n),r=dI({db:t,source_trace_id:n,differentNetOnly:!0}).flatMap(s=>s.edges),o=s=>{let{from:a,to:c}=s;return a.x===c.x?"vertical":"horizontal"};for(let s of e){let a=o(s),c=()=>r.find(u=>o(u)===a&&Aa([s.from,s.to],[u.from,u.to],{lineThickness:.05})),l=c();for(;l;)a==="horizontal"?(s.from.y+=.1,s.to.y+=.1):(s.from.x+=.1,s.to.x+=.1),l=c()}},tI=e=>{switch(e){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:}},pvt=kF.version??"unknown",Cf=class extends Error{constructor(e){super(`${e} (capacity-autorouter@${pvt})`),this.name="AutorouterError"}},kx=class extends Error{constructor(e){super(e.message),this.errorData=e,this.name="TraceConnectionError"}},hvt=e=>{if(e.root?._featureMspSchematicTraceRouting||e._couldNotFindPort||e.root?.schematicDisabled)return;let{db:t}=e.root,{_parsedProps:n,parent:i}=e;if(!i)throw new Error("Trace has no parent");let r,o;try{let X=e._findConnectedPorts();r=X.allPortsFound,o=X.portsWithSelectors??[]}catch(X){if(X instanceof kx){t.source_trace_not_connected_error.insert({...X.errorData,error_type:"source_trace_not_connected_error"});return}throw X}let{netsWithSelectors:s}=e._findConnectedNets();if(!r)return;let c=o.map(X=>X.port.schematic_port_id).sort().join(","),l=e.root?._getBoard();if(l?._connectedSchematicPortPairs&&l._connectedSchematicPortPairs.has(c))return;let u={name:e.source_trace_id,pointsToConnect:[]},h=lvt(e),f=o.filter(({port:X})=>X.schematic_port_id!==null).map(({port:X})=>({port:X,position:X._getGlobalSchematicPositionAfterLayout(),schematic_port_id:X.schematic_port_id??void 0,facingDirection:X.facingDirection}));if(f.length===1&&s.length===1){let X=s[0].net,{port:W,position:Q}=f[0],J=e.getSubcircuit().selectAll("netlabel").find(it=>{let et=it._parsedProps.connection??it._parsedProps.connectsTo;return et?Array.isArray(et)?et.some(mt=>e.getSubcircuit().selectOne(mt,{port:!0})===W):e.getSubcircuit().selectOne(et,{port:!0})===W:!1});if(!J){let it=t.schematic_net_label.getWhere({source_trace_id:e.source_trace_id});it&&(J=it)}if(J){let it="_getGlobalSchematicPositionBeforeLayout"in J?J._getGlobalSchematicPositionBeforeLayout():J.anchor_position,et=[];Q.x===it.x||Q.y===it.y?et.push({from:Q,to:it}):(et.push({from:Q,to:{x:it.x,y:Q.y}}),et.push({from:{x:it.x,y:Q.y},to:it}));let vt=t.schematic_trace.insert({source_trace_id:e.source_trace_id,edges:et,junctions:[],subcircuit_connectivity_map_key:e.subcircuit_connectivity_map_key??void 0});e.schematic_trace_id=vt.schematic_trace_id;return}if(e.props.schDisplayLabel){let it=Of(W.facingDirection)??"bottom";t.schematic_net_label.insert({text:e.props.schDisplayLabel,source_net_id:X.source_net_id,anchor_position:Q,center:Ka({anchor_position:Q,anchor_side:it,text:e.props.schDisplayLabel}),anchor_side:it});return}let _t=Of(W.facingDirection)??"bottom",st=t.schematic_net_label.insert({text:X._parsedProps.name,source_net_id:X.source_net_id,anchor_position:Q,center:Ka({anchor_position:Q,anchor_side:_t,text:X._parsedProps.name}),anchor_side:_t});return}if(e.props.schDisplayLabel&&("from"in e.props&&"to"in e.props||"path"in e.props)){e._doInitialSchematicTraceRenderWithDisplayLabel();return}if(f.length<2)return;let x=(()=>{let X=[];for(let Q=0;Q<f.length-1;Q++){let J=f[Q],_t=f[Q+1],st=Na({x:J.position.x,y:J.position.y,facingDirection:tI(J.facingDirection)},{x:_t.position.x,y:_t.position.y,facingDirection:tI(_t.facingDirection)});for(let it=0;it<st.length-1;it++)X.push({from:st[it],to:st[it+1]})}let W=(Q,J)=>{let _t=J.width/2,st=J.height/2,it=J.center.x-_t,et=J.center.x+_t,vt=J.center.y-st,mt=J.center.y+st,Tt=pt=>pt.x>=it&&pt.x<=et&&pt.y>=vt&&pt.y<=mt;return Tt(Q.from)||Tt(Q.to)?!0:[[{x:it,y:vt},{x:et,y:vt}],[{x:et,y:vt},{x:et,y:mt}],[{x:et,y:mt},{x:it,y:mt}],[{x:it,y:mt},{x:it,y:vt}]].some(pt=>Aa([Q.from,Q.to],pt,{lineThickness:0}))};for(let Q of X)for(let J of h)if(W(Q,J))return null;return X})();x&&x.length===0&&(x=null),u.pointsToConnect=f.map(({position:X})=>({...X,layer:"top"}));let v=U2t(h),w=2,S={minTraceWidth:.1,obstacles:h,connections:[u],bounds:{minX:v.minX-w,maxX:v.maxX+w,minY:v.minY-w,maxY:v.maxY+w},layerCount:1},C=Hy,E=!1;if(e.getSubcircuit().props._schDirectLineRoutingEnabled&&(C=Wj,E=!0),!x){let W=new C({input:S,MAX_ITERATIONS:100,OBSTACLE_MARGIN:.1,isRemovePathLoopsEnabled:!0,isShortenPathWithShortcutsEnabled:!0,marginsWithCosts:[{margin:1,enterCost:0,travelCostFactor:1},{margin:.3,enterCost:0,travelCostFactor:1},{margin:.2,enterCost:0,travelCostFactor:2},{margin:.1,enterCost:0,travelCostFactor:3}]}).solveAndMapToTraces();if(W.length===0){if(e._isSymbolToChipConnection()||e._isSymbolToSymbolConnection()||e._isChipToChipConnection()){e._doInitialSchematicTraceRenderWithDisplayLabel();return}W=new Wj({input:S}).solveAndMapToTraces(),E=!0}let[{route:Q}]=W;x=[];for(let J=0;J<Q.length-1;J++)x.push({from:Q[J],to:Q[J+1]})}let R=e.source_trace_id,I=[];if(!E){uvt({edges:x,db:t,source_trace_id:R});let X=dI({db:t,source_trace_id:R,differentNetOnly:!0}).flatMap(W=>W.edges);x=ovt({edges:x,otherEdges:X}),I=avt({edges:x,db:t,source_trace_id:e.source_trace_id})}if(!x||x.length===0)return;let k=x[x.length-1],M=f[f.length-1],A=Kj(k);x.push(...JT({lastEdge:k,lastEdgePort:M,lastDominantDirection:A}));let L=x[0],B=f[0],D=Kj(L);if(x.unshift(...JT({firstEdge:L,firstEdgePort:B,firstDominantDirection:D})),!e.source_trace_id)throw new Error("Missing source_trace_id for schematic trace insertion.");if(e.getSubcircuit()._parsedProps.schTraceAutoLabelEnabled&&K2t(I,x)>=5&&(e._isSymbolToChipConnection()||e._isSymbolToSymbolConnection()||e._isChipToChipConnection())){e._doInitialSchematicTraceRenderWithDisplayLabel();return}let V=t.schematic_trace.insert({source_trace_id:e.source_trace_id,edges:x,junctions:I,subcircuit_connectivity_map_key:e.subcircuit_connectivity_map_key??void 0});e.schematic_trace_id=V.schematic_trace_id;for(let{port:X}of o)X.schematic_port_id&&t.schematic_port.update(X.schematic_port_id,{is_connected:!0});l?._connectedSchematicPortPairs&&l._connectedSchematicPortPairs.add(c)};function EY(e){let t=0;for(let n=0;n<e.length;n++){let i=e[n];if(i.route_type==="wire"){let r=e[n+1];if(r){let o=r.x-i.x,s=r.y-i.y;t+=Math.sqrt(o*o+s*s)}}else i.route_type==="via"&&(t+=1.6)}return t}var Sx=e=>({...e._getGlobalPcbPositionAfterLayout(),layers:e.getAvailablePcbLayers()}),dvt=!1;function fvt(e){if(e.root?.pcbDisabled)return;let{db:t}=e.root,{_parsedProps:n,parent:i}=e,r=e.getSubcircuit();if(!i)throw new Error("Trace has no parent");if(r._parsedProps.routingDisabled)return;let o=r._parsedProps.pcbRouteCache?.pcbTraces;if(o){let A=t.pcb_trace.insert({route:o.flatMap(L=>L.route),source_trace_id:e.source_trace_id,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0});e.pcb_trace_id=A.pcb_trace_id;return}if(n.pcbPath&&n.pcbPath.length>0||!r._shouldUseTraceByTraceRouting())return;let{allPortsFound:s,ports:a}=e._findConnectedPorts(),c=[];if(!s)return;let l=[];for(let A of a)A._hasMatchedPcbPrimitive()||l.push(A);if(l.length>0){t.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:e.source_trace_id,message:`Some ports did not have a matching PCB primitive (e.g. a pad or plated hole), this can happen if a footprint is missing. As a result, ${e} wasn't routed. Missing ports: ${l.map(A=>A.getString()).join(", ")}`,pcb_trace_id:e.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:l.map(A=>A.pcb_port_id).filter(Boolean)});return}let u=e._findConnectedNets().netsWithSelectors;if(a.length===0&&u.length===2){e.renderError("Trace connects two nets, we haven't implemented a way to route this yet");return}else if(a.length===1&&u.length===1){let A=a[0],B=u[0].net.getAllConnectedPorts().filter(V=>V!==A);if(B.length===0){console.log("Nothing to connect this port to, the net is empty. TODO should emit a warning!");return}let D=Z2t(A,B);c.push(D),a.push(D)}else if(a.length>1&&u.length>=1){e.renderError("Trace has more than one port and one or more nets, we don't currently support this type of complex trace routing");return}let h=a.flatMap(A=>A.matchedComponents.filter(L=>L.componentName==="TraceHint")),f=(e._parsedProps.pcbRouteHints??[]).concat(h.flatMap(A=>A.getPcbRouteHints()));if(a.length>2){e.renderError(`Trace has more than two ports (${a.map(A=>A.getString()).join(", ")}), routing between more than two ports for a single trace is not implemented`);return}if(e.getSubcircuit().selectAll("trace").filter(A=>A.renderPhaseStates.PcbTraceRender.initialized).some(A=>A._portsRoutedOnPcb.length===a.length&&A._portsRoutedOnPcb.every(L=>a.includes(L))))return;let x=[];f.length===0?x=[Sx(a[0]),Sx(a[1])]:x=[Sx(a[0]),...f,Sx(a[1])];let v=Ix(x);if(dvt&&v.length===0){e.renderError(`Could not find a common layer (using hints) for trace ${e.getString()}`);return}let w=ar(e.root.db.toArray()),[S,C]=J2t(()=>hI(e.root.db.toArray()));if(C){e.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:e.pcb_trace_id,message:`Error getting obstacles for autorouting: ${C.message}`,source_trace_id:e.source_trace_id,center:{x:0,y:0},pcb_port_ids:a.map(A=>A.pcb_port_id),pcb_trace_id:e.pcb_trace_id,pcb_component_ids:[]});return}for(let A of S)if(A.connectedTo.length>0){let B=w.getNetConnectedToId(A.connectedTo[0]);B&&A.connectedTo.push(B)}let E=[];if(v.length===0)E=x;else{let A=v[0].layer_path;E=x.map((L,B)=>L.via?{...L,via_to_layer:A[B]}:{...L,layers:[A[B]]})}E[0].pcb_port_id=a[0].pcb_port_id,E[E.length-1].pcb_port_id=a[1].pcb_port_id;let R=[];for(let[A,L]of xY(E)){let B="via_to_layer"in A?A.via_to_layer:null,D=2,V="layers"in A&&A.layers.length===1?A.layers[0]:B??"top",X="layers"in L&&L.layers.length===1?L.layers[0]:B??"top",W="pcb_port_id"in A?A.pcb_port_id:null,Q="pcb_port_id"in L?L.pcb_port_id:null,J=e.getSubcircuit()._parsedProps.minTraceWidth??.16,_t=new Hy({OBSTACLE_MARGIN:J*2,isRemovePathLoopsEnabled:!0,optimizeWithGoalBoxes:!!(W&&Q),connMap:w,input:{obstacles:S,minTraceWidth:J,connections:[{name:e.source_trace_id,pointsToConnect:[{...A,layer:V,pcb_port_id:W},{...L,layer:X,pcb_port_id:Q}]}],layerCount:e.getSubcircuit()._getSubcircuitLayerCount(),bounds:{minX:Math.min(A.x,L.x)-D,maxX:Math.max(A.x,L.x)+D,minY:Math.min(A.y,L.y)-D,maxY:Math.max(A.y,L.y)+D}}}),st=null;try{st=_t.solveAndMapToTraces()}catch(vt){e.renderError({type:"pcb_trace_error",pcb_trace_error_id:e.source_trace_id,error_type:"pcb_trace_error",message:`error solving route: ${vt.message}`,source_trace_id:e.pcb_trace_id,center:{x:(A.x+L.x)/2,y:(A.y+L.y)/2},pcb_port_ids:a.map(mt=>mt.pcb_port_id),pcb_trace_id:e.pcb_trace_id,pcb_component_ids:a.map(mt=>mt.pcb_component_id)})}if(!st)return;if(st.length===0){e.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:e.pcb_trace_id,message:`Could not find a route for ${e}`,source_trace_id:e.source_trace_id,center:{x:(A.x+L.x)/2,y:(A.y+L.y)/2},pcb_port_ids:a.map(vt=>vt.pcb_port_id),pcb_trace_id:e.pcb_trace_id,pcb_component_ids:a.map(vt=>vt.pcb_component_id)});return}let[it]=st;B&&(it.route=it.route.map(vt=>(vt.route_type==="wire"&&!vt.layer&&(vt.layer=B),vt))),W&&it.route[0].route_type==="wire"&&(it.route[0].start_pcb_port_id=W);let et=it.route[it.route.length-1];Q&&et.route_type==="wire"&&(et.end_pcb_port_id=Q),R.push(it.route)}let I=q2t(R),k=EY(I),M=t.pcb_trace.insert({route:I,source_trace_id:e.source_trace_id,subcircuit_id:e.getSubcircuit()?.subcircuit_id,trace_length:k});e._portsRoutedOnPcb=a,e.pcb_trace_id=M.pcb_trace_id;for(let A of I)A.route_type==="via"&&t.pcb_via.insert({pcb_trace_id:M.pcb_trace_id,x:A.x,y:A.y,hole_diameter:.3,outer_diameter:.6,layers:[A.from_layer,A.to_layer],from_layer:A.from_layer,to_layer:A.to_layer});e._insertErrorIfTraceIsOutsideBoard(I,a)}function mvt(e){if(e.root?.pcbDisabled)return;let{db:t}=e.root,{_parsedProps:n}=e,i=e.getSubcircuit();if(!n.pcbPath||n.pcbPath.length===0)return;let{allPortsFound:r,ports:o,portsWithSelectors:s}=e._findConnectedPorts();if(!r)return;let a=[];for(let S of o)S._hasMatchedPcbPrimitive()||a.push(S);if(a.length>0){t.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:e.source_trace_id,message:`Some ports did not have a matching PCB primitive (e.g. a pad or plated hole), this can happen if a footprint is missing. As a result, ${e} wasn't routed. Missing ports: ${a.map(S=>S.getString()).join(", ")}`,pcb_trace_id:e.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:a.map(S=>S.pcb_port_id).filter(Boolean)});return}let c;n.pcbPathRelativeTo&&(c=s.find(S=>S.selector===n.pcbPathRelativeTo)?.port,c||(c=e.getSubcircuit().selectOne(n.pcbPathRelativeTo))),c||(c=o[0]);let l=o.find(S=>S!==c)??o[1],u=c.getAvailablePcbLayers()[0]||"top",h=n.thickness??e.getSubcircuit()._parsedProps.minTraceWidth??.16,f=c._getGlobalPcbPositionAfterLayout(),_=l._getGlobalPcbPositionAfterLayout(),y=[];y.push({route_type:"wire",x:f.x,y:f.y,width:h,layer:u,start_pcb_port_id:c.pcb_port_id});let x=c?._computePcbGlobalTransformBeforeLayout?.()||vi();for(let S of n.pcbPath){let C=kn(x,{x:S.x,y:S.y});y.push({route_type:"wire",x:C.x,y:C.y,width:h,layer:u})}y.push({route_type:"wire",x:_.x,y:_.y,width:h,layer:u,end_pcb_port_id:l.pcb_port_id});let v=EY(y),w=t.pcb_trace.insert({route:y,source_trace_id:e.source_trace_id,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0,trace_length:v});e._portsRoutedOnPcb=o,e.pcb_trace_id=w.pcb_trace_id,e._insertErrorIfTraceIsOutsideBoard(y,o)}function _vt(e){if(e.root?.schematicDisabled)return;let{db:t}=e.root,{_parsedProps:n,parent:i}=e;if(!i)throw new Error("Trace has no parent");let{allPortsFound:r,portsWithSelectors:o}=e._findConnectedPorts();if(!r)return;let s=o.map(({port:E})=>({port:E,position:E._getGlobalSchematicPositionAfterLayout(),schematic_port_id:E.schematic_port_id,facingDirection:E.facingDirection}));if(s.length<2)throw new Error("Expected at least two ports in portsWithPosition.");let a,c,l=s[0].position,u=s[0].port;if("path"in e.props){if(e.props.path.length!==2)throw new Error("Invalid 'path': Must contain exactly two elements.");[a,c]=e.props.path}else{if(!("from"in e.props&&"to"in e.props))throw new Error("Missing 'from' or 'to' properties in props.");a=e.props.from,c=e.props.to}if(!u.source_port_id)throw new Error(`Missing source_port_id for the 'from' port (${a}).`);let h=s[1].position,f=s[1].port;if(!f.source_port_id)throw new Error(`Missing source_port_id for the 'to' port (${c}).`);let _=t.schematic_net_label.list().find(E=>E.source_net_id===u.source_port_id),y=t.schematic_net_label.list().find(E=>E.source_net_id===f.source_port_id),[x,v]=o.map(({port:E})=>E),S=x.parent?.config.shouldRenderAsSchematicBox?`${x?.parent?.props.name}_${x?.props.name}`:`${v?.parent?.props.name}_${v?.props.name}`,C=e.props.schDisplayLabel??S;if(_&&_.text!==C&&(_.text=`${C} / ${_.text}`),y&&y?.text!==C&&(y.text=`${C} / ${y.text}`),!y){let E=Of(f.facingDirection)??"bottom";t.schematic_net_label.insert({text:e.props.schDisplayLabel??S,source_net_id:f.source_port_id,anchor_position:h,center:Ka({anchor_position:h,anchor_side:E,text:e.props.schDisplayLabel??S}),anchor_side:E})}if(!_){let E=Of(u.facingDirection)??"bottom";t.schematic_net_label.insert({text:e.props.schDisplayLabel??S,source_net_id:u.source_port_id,anchor_position:l,center:Ka({anchor_position:l,anchor_side:E,text:e.props.schDisplayLabel??S}),anchor_side:E})}}function yvt(e){let{_parsedProps:t,parent:n}=e;if(!n)throw new Error("Trace has no parent");let r=e.getTracePortPathSelectors().map(o=>({selector:o,port:e.getSubcircuit().selectOne(o,{type:"port"})??null}));for(let{selector:o,port:s}of r)if(!s){let a,c,l=o.lastIndexOf(".");if(l!==-1&&l>o.lastIndexOf(" "))a=o.slice(0,l),c=o.slice(l+1);else{let E=o.match(/^(.*[ >])?([^ >]+)$/);a=E?.[1]?.trim()??"",c=E?.[2]??o}let u=a?e.getSubcircuit().selectOne(a):null;if(!u&&a&&!/[.#\[]/.test(a)&&(u=e.getSubcircuit().selectOne(`.${a}`)),!u){let E=a?`Could not find port for selector "${o}". Component "${a}" not found`:`Could not find port for selector "${o}"`,R=e.getSubcircuit(),I=R.getGroup();throw new kx({error_type:"source_trace_not_connected_error",message:E,subcircuit_id:R.subcircuit_id??void 0,source_group_id:I?.source_group_id??void 0,source_trace_id:e.source_trace_id??void 0,selectors_not_found:[o]})}let h=u.children.filter(E=>E.componentName==="Port"),f=c.includes(".")?c.split(".").pop()??"":c,_=h.flatMap(E=>E.getNameAndAliases()),y=_.some(E=>!/^(pin\d+|\d+)$/.test(E)),x=Array.from(new Set(_)).join(", "),v;h.length===0?v="It has no ports":y?v=`It has [${x}]`:v=`It has ${h.length} pins and no pinLabels (consider adding pinLabels)`;let w=`Could not find port for selector "${o}". Component "${u.props.name??a}" found, but does not have pin "${f}". ${v}`,S=e.getSubcircuit(),C=S.getGroup();throw new kx({error_type:"source_trace_not_connected_error",message:w,subcircuit_id:S.subcircuit_id??void 0,source_group_id:C?.source_group_id??void 0,source_trace_id:e.source_trace_id??void 0,selectors_not_found:[o]})}return r.some(o=>!o.port)?{allPortsFound:!1}:{allPortsFound:!0,portsWithSelectors:r,ports:r.map(({port:o})=>o)}}var yo=class extends Ie{constructor(t){super(t);T(this,"source_trace_id",null);T(this,"pcb_trace_id",null);T(this,"schematic_trace_id",null);T(this,"_portsRoutedOnPcb");T(this,"subcircuit_connectivity_map_key",null);T(this,"_traceConnectionHash",null);T(this,"_couldNotFindPort");this._portsRoutedOnPcb=[]}get config(){return{zodProps:CL,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 yvt(this)}_resolveNet(t){let n=this.getSubcircuit().selectOne(t,{type:"net"});if(n)return n;let i=t.match(/^net\.(.+)$/),r=i?i[1]:null;return r&&this.root._getBoard().getDescendants().find(s=>s.componentName==="Net"&&s._parsedProps.name===r)||null}_findConnectedNets(){let t=this.getTracePathNetSelectors().map(i=>({selector:i,net:this._resolveNet(i)})),n=t.filter(i=>!i.net);return n.length>0&&this.renderError(`Could not find net for selector "${n[0].selector}" inside ${this}`),{netsWithSelectors:t,nets:t.map(i=>i.net)}}_getAllTracesConnectedToSameNet(){let t=this.getSubcircuit().selectAll("trace"),n=this._findConnectedNets().nets,i=this._findConnectedPorts().ports??[];return t.filter(r=>{if(r===this)return!1;let o=r._findConnectedNets().nets,s=r._findConnectedPorts().ports??[];return o.some(a=>n.includes(a))||s.some(a=>i.includes(a))})}_isExplicitlyConnectedToPort(t){let{allPortsFound:n,portsWithSelectors:i}=this._findConnectedPorts();return n?i.map(o=>o.port).includes(t):!1}_isExplicitlyConnectedToNet(t){return this._findConnectedNets().nets.includes(t)}doInitialCreateNetsFromProps(){cI(this,this.getTracePathNetSelectors())}_computeTraceConnectionHash(){let{allPortsFound:t,ports:n}=this._findConnectedPorts();return!t||!n?null:[...n].sort((o,s)=>(o.pcb_port_id||"").localeCompare(s.pcb_port_id||"")).map(o=>o.pcb_port_id).join(",")}doInitialSourceTraceRender(){let{db:t}=this.root,{_parsedProps:n,parent:i}=this;if(!i){this.renderError("Trace has no parent");return}let r,o;try{let h=this._findConnectedPorts();r=h.allPortsFound,o=h.portsWithSelectors??[]}catch(h){if(h instanceof kx){t.source_trace_not_connected_error.insert({...h.errorData,error_type:"source_trace_not_connected_error"}),this._couldNotFindPort=!0;return}throw h}if(!r)return;this._traceConnectionHash=this._computeTraceConnectionHash();let a=t.source_trace.list().find(h=>h.subcircuit_connectivity_map_key===this.subcircuit_connectivity_map_key&&h.connected_source_port_ids.sort().join(",")===this._traceConnectionHash);if(a){this.source_trace_id=a.source_trace_id;return}let c=this._findConnectedNets().nets,l=tvt({ports:o,nets:c}),u=t.source_trace.insert({connected_source_port_ids:o.map(h=>h.port.source_port_id),connected_source_net_ids:c.map(h=>h.source_net_id),subcircuit_id:this.getSubcircuit()?.subcircuit_id,max_length:Q2t(o.map(h=>h.port),{db:t})??n.maxLength,display_name:l,min_trace_thickness:n.thickness});this.source_trace_id=u.source_trace_id}_insertErrorIfTraceIsOutsideBoard(t,n){let{db:i}=this.root;evt(t,{db:i})&&i.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:this.source_trace_id,message:`Trace ${this.getString()} routed outside the board boundaries.`,pcb_trace_id:this.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:n.map(o=>o.pcb_port_id)})}doInitialPcbManualTraceRender(){mvt(this)}doInitialPcbTraceRender(){fvt(this)}_doInitialSchematicTraceRenderWithDisplayLabel(){_vt(this)}_isSymbolToChipConnection(){let{allPortsFound:t,ports:n}=this._findConnectedPorts();if(!t||n.length!==2)return!1;let[i,r]=n;if(!i?.parent||!r?.parent)return!1;let o=i.parent.config.shouldRenderAsSchematicBox,s=r.parent.config.shouldRenderAsSchematicBox;return o&&!s||!o&&s}_isSymbolToSymbolConnection(){let{allPortsFound:t,ports:n}=this._findConnectedPorts();if(!t||n.length!==2)return!1;let[i,r]=n;if(!i?.parent||!r?.parent)return!1;let o=!i.parent.config.shouldRenderAsSchematicBox,s=!r.parent.config.shouldRenderAsSchematicBox;return o&&s}_isChipToChipConnection(){let{allPortsFound:t,ports:n}=this._findConnectedPorts();if(!t||n.length!==2)return!1;let[i,r]=n;if(!i?.parent||!r?.parent)return!1;let o=i.parent.config.shouldRenderAsSchematicBox,s=r.parent.config.shouldRenderAsSchematicBox;return o&&s}doInitialSchematicTraceRender(){hvt(this)}},gvt=e=>{let{db:t}=e.root;if(e.pcb_component_id){let n=t.pcb_component.get(e.pcb_component_id);return n?{width:n.width,height:n.height}:null}if(e.pcb_group_id){let n=t.pcb_group.get(e.pcb_group_id);return n?{width:n.width,height:n.height}:null}return null},xvt=(e,t)=>{let{db:n}=e.root,i=n.toArray();if(e.pcb_component_id){ag(i,e.pcb_component_id,t);return}if(e.source_group_id){cg(i,e.source_group_id,t);return}throw new Error(`Cannot reposition component ${e.getString()}: no pcb_component_id or source_group_id`)},bvt=e=>{let{db:t}=e.root;if(!e.source_component_id)return;let n=e.selectAll("port"),i=t.source_trace.list(),r=new Set;for(let s of i)for(let a of s.connected_source_port_ids)r.add(a);let o=e._getInternallyConnectedPins();for(let s of o)if(s.some(a=>a.source_port_id&&r.has(a.source_port_id)))for(let a of s)a.source_port_id&&r.add(a.source_port_id);for(let s of n)s.source_port_id&&vvt(e,s)&&(r.has(s.source_port_id)||t.source_pin_missing_trace_warning.insert({message:`Port ${s.getNameAndAliases()[0]} on ${e.props.name} is missing a trace`,source_component_id:e.source_component_id,source_port_id:s.source_port_id,subcircuit_id:e.getSubcircuit().subcircuit_id??void 0,warning_type:"source_pin_missing_trace_warning"}))},vvt=(e,t)=>{if(e.config.componentName==="Chip"){let n=e.props.pinAttributes;if(!n)return!1;for(let i of t.getNameAndAliases()){let r=n[i];if(r?.requiresPower||r?.requiresGround||r?.requiresVoltage!==void 0)return!0}return!1}return!0};function wvt(e){let t=e.font_size,n=e.text.length*t*.6,i=t,r=e.anchor_alignment||"center",o=e.anchor_position.x,s=e.anchor_position.y;switch(r){case"top_left":o=e.anchor_position.x+n/2,s=e.anchor_position.y+i/2;break;case"top_center":o=e.anchor_position.x,s=e.anchor_position.y+i/2;break;case"top_right":o=e.anchor_position.x-n/2,s=e.anchor_position.y+i/2;break;case"center_left":o=e.anchor_position.x+n/2,s=e.anchor_position.y;break;case"center":o=e.anchor_position.x,s=e.anchor_position.y;break;case"center_right":o=e.anchor_position.x-n/2,s=e.anchor_position.y;break;case"bottom_left":o=e.anchor_position.x+n/2,s=e.anchor_position.y-i/2;break;case"bottom_center":o=e.anchor_position.x,s=e.anchor_position.y-i/2;break;case"bottom_right":o=e.anchor_position.x-n/2,s=e.anchor_position.y-i/2;break;default:o=e.anchor_position.x,s=e.anchor_position.y;break}return{x:o-n/2,y:s-i/2,width:n,height:i}}function Svt(e){if(!e._adjustSilkscreenTextAutomatically||e.root?.pcbDisabled||!e.pcb_component_id)return;let{db:t}=e.root,i=e._getPcbCircuitJsonBounds().center,r=t.pcb_silkscreen_text.list({pcb_component_id:e.pcb_component_id}).filter(c=>c.text===e.name);if(r.length===0)return;let a=e.getSubcircuit().selectAll("[_isNormalComponent=true]").filter(c=>c!==e&&c.pcb_component_id).map(c=>{let l=c._getPcbCircuitJsonBounds(),u={center:l.center,width:l.width,height:l.height};return Ts(u)});for(let c of r){let l=c.anchor_position,u=wvt(c),h={center:{x:u.x+u.width/2,y:u.y+u.height/2},width:u.width,height:u.height},f=Ts(h);if(!a.some(C=>Ed(f,C)))continue;let y=2*i.x-l.x,x=2*i.y-l.y,v={center:{x:y,y:x},width:u.width,height:u.height},w=Ts(v);a.some(C=>Ed(w,C))||t.pcb_silkscreen_text.update(c.pcb_silkscreen_text_id,{anchor_position:{x:y,y:x}})}}function Pvt(e){if(!e)return{validPinLabels:e,invalidPinLabelsMessages:[]};let t={},n=[];for(let[i,r]of Object.entries(e)){let o=Array.isArray(r)?r.slice():[r],s=[];for(let a of o)Tvt(i,a)?s.push(a):n.push(`Invalid pin label: ${i} = '${a}' - excluding from component. Please use a valid pin label.`);s.length>0&&(t[i]=Array.isArray(r)?s:s[0])}return{validPinLabels:Object.keys(t).length>0?t:void 0,invalidPinLabelsMessages:n}}function Tvt(e,t){try{let n={name:"test",footprint:"test",pinLabels:{[e]:t}};return lp.safeParse(n).success}catch{return!1}}var Lf=e=>e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/"),nI=e=>{if(Lf(e))return null;let t=e.indexOf(":");if(t<=0)return null;let n=e.slice(0,t),i=e.slice(t+1);return!n||!i?null:{footprintLib:n,footprintName:i}},Ivt=e=>e?e.split("?")[0].split(".").pop():null;function Mvt(e,t){let{footprint:n}=e.props;if(n??(n=e._getImpliedFootprintString?.()),!n)return;let{pcbRotation:i,pinLabels:r,pcbPinLabels:o}=e.props,s=Ivt(String(n)),a=s?e.root?.platform?.footprintFileParserMap?.[s]:null;if(typeof n=="string"&&Lf(n)&&a){if(e._hasStartedFootprintUrlLoad)return;e._hasStartedFootprintUrlLoad=!0;let c=n;t("load-footprint-from-platform-file-parser",async()=>{try{let l=await a.loadFromUrl(c),u=Ef({componentName:e.name,componentRotation:i,footprint:c,pinLabels:r,pcbPinLabels:o},l.footprintCircuitJson);e.addAll(u),e._markDirty("InitializePortsFromChildren")}catch(l){let u=e.root?.db;if(u&&e.source_component_id&&e.pcb_component_id){let h=e.getSubcircuit(),f=`${e.getString()} failed to load footprint "${c}": `+(l instanceof Error?l.message:String(l)),_=Xu.parse({type:"external_footprint_load_error",message:f,pcb_component_id:e.pcb_component_id,source_component_id:e.source_component_id,subcircuit_id:h.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0,footprinter_string:c});u.external_footprint_load_error.insert(_)}throw l}});return}if(typeof n=="string"&&Lf(n)){if(e._hasStartedFootprintUrlLoad)return;e._hasStartedFootprintUrlLoad=!0;let c=n;t("load-footprint-url",async()=>{try{let l=await fetch(c);if(!l.ok)throw new Error(`Failed to fetch footprint: ${l.status}`);let u=await l.json(),h=Ef({componentName:e.name,componentRotation:i,footprint:c,pinLabels:r,pcbPinLabels:o},u);e.addAll(h),e._markDirty("InitializePortsFromChildren")}catch(l){let u=e.root?.db;if(u&&e.source_component_id&&e.pcb_component_id){let h=e.getSubcircuit(),f=`${e.getString()} failed to load external footprint "${c}": `+(l instanceof Error?l.message:String(l)),_=Xu.parse({type:"external_footprint_load_error",message:f,pcb_component_id:e.pcb_component_id,source_component_id:e.source_component_id,subcircuit_id:h.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0,footprinter_string:c});u.external_footprint_load_error.insert(_)}throw l}});return}if(typeof n=="string"){let c=nI(n);if(!c||e._hasStartedFootprintUrlLoad)return;e._hasStartedFootprintUrlLoad=!0;let u=e.root?.platform?.footprintLibraryMap?.[c.footprintLib],h;if(typeof u=="function"&&(h=u),!h)return;t("load-lib-footprint",async()=>{try{let f=await h(c.footprintName),_=null;if(Array.isArray(f)?_=f:Array.isArray(f.footprintCircuitJson)&&(_=f.footprintCircuitJson),!_)return;let y=Ef({componentName:e.name,componentRotation:i,footprint:n,pinLabels:r,pcbPinLabels:o},_);e.addAll(y),!Array.isArray(f)&&f.cadModel&&(e._asyncFootprintCadModel=f.cadModel);for(let x of e.children)x.componentName==="Port"&&x._markDirty?.("PcbPortRender");e._markDirty("InitializePortsFromChildren")}catch(f){let _=e.root?.db;if(_&&e.source_component_id&&e.pcb_component_id){let y=e.getSubcircuit(),x=`${e.getString()} failed to load external footprint "${n}": `+(f instanceof Error?f.message:String(f)),v=Xu.parse({type:"external_footprint_load_error",message:x,pcb_component_id:e.pcb_component_id,source_component_id:e.source_component_id,subcircuit_id:y.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0,footprinter_string:n});_.external_footprint_load_error.insert(v)}throw f}});return}if(!(0,eI.isValidElement)(n)&&n.componentName==="Footprint"&&e.add(n),Array.isArray(n)&&!(0,eI.isValidElement)(n)&&n.length>0){try{let c=Ef({componentName:e.name,componentRotation:i,footprint:"",pinLabels:r,pcbPinLabels:o},n);e.addAll(c)}catch(c){let l=e.root?.db;if(l&&e.source_component_id&&e.pcb_component_id){let u=e.getSubcircuit(),h=`${e.getString()} failed to load json footprint: `+(c instanceof Error?c.message:String(c)),f=C1.parse({type:"circuit_json_footprint_load_error",message:h,pcb_component_id:e.pcb_component_id,source_component_id:e.source_component_id,subcircuit_id:u.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0});l.circuit_json_footprint_load_error.insert(f)}throw c}return}}function Evt(e){if(e.root?.pcbDisabled||!e.pcb_component_id)return;let{pcbX:t,pcbY:n}=e._parsedProps,i=e.props?.pcbPositionAnchor;if(!i||t===void 0&&n===void 0)return;let r=Ox(e.children);if(r.width===0||r.height===0)return;let s={...{x:(r.minX+r.maxX)/2,y:(r.minY+r.maxY)/2}},a=null;if(new Set(["center","top_left","top_center","top_right","center_left","center_right","bottom_left","bottom_center","bottom_right"]).has(i)){let u={left:r.minX,right:r.maxX,top:r.minY,bottom:r.maxY};switch(i){case"center":a=s;break;case"top_left":a={x:u.left,y:u.top};break;case"top_center":a={x:s.x,y:u.top};break;case"top_right":a={x:u.right,y:u.top};break;case"center_left":a={x:u.left,y:s.y};break;case"center_right":a={x:u.right,y:s.y};break;case"bottom_left":a={x:u.left,y:u.bottom};break;case"bottom_center":a={x:s.x,y:u.bottom};break;case"bottom_right":a={x:u.right,y:u.bottom};break}}else try{let u=e.portMap[i];u&&(a=u._getGlobalPcbPositionBeforeLayout())}catch{}if(!a)return;let l={...s};t!==void 0&&(l.x+=t-a.x),n!==void 0&&(l.y+=n-a.y),(Math.abs(l.x-s.x)>1e-6||Math.abs(l.y-s.y)>1e-6)&&e._repositionOnPcb(l)}var Cvt=(0,fY.default)("tscircuit:core"),kvt=p.object({x:Fe,y:Fe,z:Fe}),In=class extends Ie{constructor(t){let n={...t},i=[];if(n.pinLabels&&!Array.isArray(n.pinLabels)){let{validPinLabels:r,invalidPinLabelsMessages:o}=Pvt(n.pinLabels);n.pinLabels=r,i=o}super(n);T(this,"reactSubtrees",[]);T(this,"_impliedFootprint");T(this,"isPrimitiveContainer",!0);T(this,"_isNormalComponent",!0);T(this,"_attributeLowerToCamelNameMap",{_isnormalcomponent:"_isNormalComponent"});T(this,"_asyncSupplierPartNumbers");T(this,"_asyncFootprintCadModel");T(this,"_isCadModelChild");T(this,"pcb_missing_footprint_error_id");T(this,"_hasStartedFootprintUrlLoad",!1);T(this,"_invalidPinLabelMessages",[]);T(this,"_adjustSilkscreenTextAutomatically",!1);this._invalidPinLabelMessages=i,this._addChildrenFromStringFootprint(),this.initPorts()}get defaultInternallyConnectedPinNames(){return[]}get internallyConnectedPinNames(){return(this._parsedProps.internallyConnectedPins??this.defaultInternallyConnectedPinNames).map(n=>n.map(i=>typeof i=="number"?`pin${i}`:i))}doInitialSourceNameDuplicateComponentRemoval(){if(!this.name)return;let t=this.root;if(this.getSubcircuit().selectAll(`.${this.name}`).filter(r=>r!==this&&r._isNormalComponent&&r.renderPhaseStates?.SourceNameDuplicateComponentRemoval?.initialized).length>0){let r=this._getGlobalPcbPositionBeforeLayout(),o=this._getGlobalSchematicPositionBeforeLayout();t.db.source_failed_to_create_component_error.insert({component_name:this.name,error_type:"source_failed_to_create_component_error",message:`Cannot create component "${this.name}": A component with the same name already exists`,pcb_center:r,schematic_center:o}),this.shouldBeRemoved=!0;let s=[...this.children];for(let a of s)this.remove(a)}}initPorts(t={}){if(this.root?.schematicDisabled)return;let{config:n}=this,i=[],r=this._getSchematicPortArrangement();if(r&&!this._parsedProps.pinLabels){for(let l in r){let u=r[l].pins;if(Array.isArray(u))for(let h of u){let f=Rf(h,this._parsedProps.pinLabels);i.push(new Ei({pinNumber:f,aliases:t.additionalAliases?.[`pin${f}`]??[]},{originDescription:`schPortArrangement:${l}`}))}}let a=["left","right","top","bottom"],c=1;for(let l of a){let u=r[`${l}Size`];for(let h=0;h<u;h++)i.push(new Ei({pinNumber:c++,aliases:t.additionalAliases?.[`pin${c}`]??[]},{originDescription:`schPortArrangement:${l}`}))}}let o=this._parsedProps.pinLabels;if(o)for(let[a,c]of Object.entries(o)){a=a.replace("pin","");let l=i.find(f=>f._parsedProps.pinNumber===Number(a)),u=Array.isArray(c)?c[0]:c,h=Array.isArray(c)?c.slice(1):[];l?(l.externallyAddedAliases.push(u,...h),l.props.name=u):(l=new Ei({pinNumber:parseInt(a),name:u,aliases:[...h,...t.additionalAliases?.[`pin${parseInt(a)}`]??[]]},{originDescription:`pinLabels:pin${a}`}),i.push(l))}if(n.schematicSymbolName&&!t.ignoreSymbolPorts){let a=Un[this._getSchematicSymbolNameOrThrow()];if(!a)return;for(let c of a.ports){let l=vY(c.labels);if(!l)continue;let u=i.find(h=>h._parsedProps.pinNumber===Number(l));if(u)u.schematicSymbolPortDef=c;else{let h=Mf(c.labels.concat(t.additionalAliases?.[`pin${l}`]??[]));h&&(h.originDescription=`schematicSymbol:labels[0]:${c.labels[0]}`,h.schematicSymbolPortDef=c,i.push(h))}}this.addAll(i)}if(!this._getSchematicPortArrangement()){let a=this.getPortsFromFootprint(t);for(let c of a)i.some(l=>l.isMatchingAnyOf(c.getNameAndAliases()))||i.push(c)}let s=t.pinCount??this._getPinCount()??0;for(let a=1;a<=s;a++){if(i.find(l=>l._parsedProps.pinNumber===a))continue;if(!r){i.push(new Ei({pinNumber:a,aliases:t.additionalAliases?.[`pin${a}`]??[]}));continue}let c=[...r.leftSide?.pins??[],...r.rightSide?.pins??[],...r.topSide?.pins??[],...r.bottomSide?.pins??[]].map(l=>Rf(l,this._parsedProps.pinLabels));["leftSize","rightSize","topSize","bottomSize","leftPinCount","rightPinCount","topPinCount","bottomPinCount"].some(l=>l in r)&&(c=Array.from({length:this._getPinCount()},(l,u)=>u+1)),c.includes(a)&&i.push(new Ei({pinNumber:a,aliases:t.additionalAliases?.[`pin${a}`]??[]},{originDescription:`notOtherwiseAddedButDeducedFromPinCount:${a}`}))}i.length>0&&this.addAll(i)}_getImpliedFootprintString(){return null}_addChildrenFromStringFootprint(){let{pcbRotation:t,pinLabels:n,pcbPinLabels:i}=this.props,{footprint:r}=this.props;if(r??(r=this._getImpliedFootprintString?.()),!!r&&typeof r=="string"){if(Lf(r)||nI(r))return;let o=$v.string(r).soup(),s=Ef({componentName:this.name??this.componentName,componentRotation:t,footprint:r,pinLabels:n,pcbPinLabels:i},o);this.addAll(s)}}get portMap(){return new Proxy({},{get:(t,n)=>{let i=this.children.find(r=>r.componentName==="Port"&&r.isMatchingNameOrAlias(n));if(!i)throw new Error(`There was an issue finding the port "${n.toString()}" inside of a ${this.componentName} component with name: "${this.props.name}". This is a bug in @tscircuit/core`);return i}})}getInstanceForReactElement(t){for(let n of this.reactSubtrees)if(n.element===t)return n.component;return null}doInitialSourceRender(){let t=this.config.sourceFtype;if(!t)return;let{db:n}=this.root,{_parsedProps:i}=this,r=n.source_component.insert({ftype:t,name:this.name,manufacturer_part_number:i.manufacturerPartNumber??i.mfn,supplier_part_numbers:i.supplierPartNumbers});this.source_component_id=r.source_component_id}doInitialSchematicComponentRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root;if(this._invalidPinLabelMessages?.length&&this.root?.db)for(let o of this._invalidPinLabelMessages){let s="pinLabels",a=o.match(/^Invalid pin label:\s*([^=]+)=\s*'([^']+)'/);a&&(s=`pinLabels['${a[2]}']`),this.root.db.source_property_ignored_warning.insert({source_component_id:this.source_component_id,property_name:s,message:o,error_type:"source_property_ignored_warning"})}let{schematicSymbolName:n}=this.config,{_parsedProps:i}=this;i.symbol&&(0,Za.isValidElement)(i.symbol)?this._doInitialSchematicComponentRenderWithReactSymbol(i.symbol):n?this._doInitialSchematicComponentRenderWithSymbol():this._getSchematicBoxDimensions()&&this._doInitialSchematicComponentRenderWithSchematicBoxDimensions();let r=this.getSubcircuit()?._getSchematicManualPlacementForComponent(this);if(this.schematic_component_id&&(this.props.schX!==void 0||this.props.schY!==void 0)&&r){if(!this.schematic_component_id)return;let o=M1.parse({type:"schematic_manual_edit_conflict_warning",schematic_manual_edit_conflict_warning_id:`schematic_manual_edit_conflict_${this.source_component_id}`,message:`${this.getString()} has both manual placement and prop coordinates. schX and schY will be used. Remove schX/schY or clear the manual placement.`,schematic_component_id:this.schematic_component_id,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id});t.schematic_manual_edit_conflict_warning.insert(o)}}_getSchematicSymbolDisplayValue(){}_getInternallyConnectedPins(){if(this.internallyConnectedPinNames.length===0)return[];let t=[];for(let n of this.internallyConnectedPinNames){let i=[];for(let r of n)i.push(this.portMap[r]);t.push(i)}return t}_doInitialSchematicComponentRenderWithSymbol(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getSchematicSymbolNameOrThrow(),r=Un[i],o=this._getGlobalSchematicPositionBeforeLayout();if(r){let s=t.schematic_component.insert({center:o,size:r.size,source_component_id:this.source_component_id,is_box_with_pins:!0,symbol_name:i,symbol_display_value:this._getSchematicSymbolDisplayValue()});this.schematic_component_id=s.schematic_component_id}}_doInitialSchematicComponentRenderWithReactSymbol(t){if(this.root?.schematicDisabled)return;let{db:n}=this.root,i=this._getGlobalSchematicPositionBeforeLayout(),r=n.schematic_component.insert({center:i,size:{width:0,height:0},source_component_id:this.source_component_id,symbol_display_value:this._getSchematicSymbolDisplayValue(),is_box_with_pins:!1});this.schematic_component_id=r.schematic_component_id,this.add(t)}_doInitialSchematicComponentRenderWithSchematicBoxDimensions(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getSchematicBoxDimensions(),r={};if(Array.isArray(n.pinLabels))n.pinLabels.forEach((_,y)=>{r[String(y+1)]=_});else for(let[_,y]of Object.entries(n.pinLabels??{}))r[_]=Array.isArray(y)?y[0]:y;let o=this._getGlobalSchematicPositionBeforeLayout(),s=this._getSchematicPortArrangement(),a=t.schematic_component.insert({center:o,rotation:n.schRotation??0,size:i.getSize(),port_arrangement:R2t(s),pin_spacing:n.schPinSpacing??.2,pin_styles:N2t(n.schPinStyle,n.pinLabels),port_labels:r,source_component_id:this.source_component_id}),c=s?.topSide!==void 0||s?.bottomSide!==void 0,l=i?.getSize().width,u=i?.getSize().height,h=t.schematic_text.insert({text:n.manufacturerPartNumber??"",schematic_component_id:a.schematic_component_id,anchor:"left",rotation:0,position:{x:c?o.x+(l??0)/2+.1:o.x-(l??0)/2,y:c?o.y+(u??0)/2+.35:o.y-(u??0)/2-.13},color:"#006464",font_size:.18}),f=t.schematic_text.insert({text:n.name??"",schematic_component_id:a.schematic_component_id,anchor:"left",rotation:0,position:{x:c?o.x+(l??0)/2+.1:o.x-(l??0)/2,y:c?o.y+(u??0)/2+.55:o.y+(u??0)/2+.13},color:"#006464",font_size:.18});this.schematic_component_id=a.schematic_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit(),r=this._computePcbGlobalTransformBeforeLayout(),s=fo(r).rotation.angle*180/Math.PI,a=t.pcb_component.insert({center:this._getGlobalPcbPositionBeforeLayout(),width:0,height:0,layer:n.layer??"top",rotation:n.pcbRotation??s,source_component_id:this.source_component_id,subcircuit_id:i.subcircuit_id??void 0,do_not_place:n.doNotPlace??!1,obstructs_within_bounds:n.obstructsWithinBounds??!0});if(!(n.footprint??this._getImpliedFootprintString())&&!this.isGroup){let u=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=u.pcb_missing_footprint_error_id}this.pcb_component_id=a.pcb_component_id;let l=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if((this.props.pcbX!==void 0||this.props.pcbY!==void 0)&&l){let u=k1.parse({type:"pcb_manual_edit_conflict_warning",pcb_manual_edit_conflict_warning_id:`pcb_manual_edit_conflict_${this.source_component_id}`,message:`${this.getString()} has both manual placement and prop coordinates. pcbX and pcbY will be used. Remove pcbX/pcbY or clear the manual placement.`,pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,subcircuit_id:i.subcircuit_id??void 0});t.pcb_manual_edit_conflict_warning.insert(u)}}doInitialPcbComponentSizeCalculation(){if(this.root?.pcbDisabled||!this.pcb_component_id)return;let{db:t}=this.root,{_parsedProps:n}=this,i=Ox(this.children);if(i.width===0||i.height===0)return;let r={x:(i.minX+i.maxX)/2,y:(i.minY+i.maxY)/2};t.pcb_component.update(this.pcb_component_id,{center:r,width:i.width,height:i.height})}updatePcbComponentSizeCalculation(){this.doInitialPcbComponentSizeCalculation()}doInitialSchematicComponentSizeCalculation(){if(this.root?.schematicDisabled||!this.schematic_component_id)return;let{db:t}=this.root;if(!t.schematic_component.get(this.schematic_component_id))return;let i=[],r=c=>{for(let l of c){if(l.isSchematicPrimitive&&l.componentName==="SchematicLine"){let u=t.schematic_line.get(l.schematic_line_id);u&&i.push(u)}if(l.isSchematicPrimitive&&l.componentName==="SchematicRect"){let u=t.schematic_rect.get(l.schematic_rect_id);u&&i.push(u)}if(l.isSchematicPrimitive&&l.componentName==="SchematicCircle"){let u=t.schematic_circle.get(l.schematic_circle_id);u&&i.push(u)}if(l.isSchematicPrimitive&&l.componentName==="SchematicArc"){let u=t.schematic_arc.get(l.schematic_arc_id);u&&i.push(u)}if(l.isSchematicPrimitive&&l.componentName==="SchematicText"){let u=t.schematic_text.get(l.schematic_text_id);u&&i.push(u)}l.children&&l.children.length>0&&r(l.children)}};if(r(this.children),i.length===0)return;let o=bY(i),s=Math.abs(o.maxX-o.minX),a=Math.abs(o.maxY-o.minY);s===0&&a===0||t.schematic_component.update(this.schematic_component_id,{size:{width:s,height:a}})}updateSchematicComponentSizeCalculation(){this.doInitialSchematicComponentSizeCalculation()}doInitialPcbComponentAnchorAlignment(){Evt(this)}updatePcbComponentAnchorAlignment(){this.doInitialPcbComponentAnchorAlignment()}_renderReactSubtree(t){let n=gY(t);return{element:t,component:n}}doInitialInitializePortsFromChildren(){this.initPorts()}doInitialReactSubtreesRender(){let t=this.props.footprint;(0,Za.isValidElement)(t)&&(this.children.some(r=>r.componentName==="Footprint")||this.add(t));let n=this.props.cadModel;if((0,Za.isValidElement)(n)){this._isCadModelChild=!0;let i=this.children.some(o=>o.componentName==="CadAssembly"),r=this.children.some(o=>o.componentName==="CadModel");!i&&!r&&this.add(n)}}doInitialPcbFootprintStringRender(){Mvt(this,(t,n)=>this._queueAsyncEffect(t,n))}_hasExistingPortExactly(t){return this.children.filter(i=>i.componentName==="Port").some(i=>{let r=t.getNameAndAliases(),o=i.getNameAndAliases();return r.length===o.length&&r.every(s=>o.includes(s))})}add(t){let n;if((0,Za.isValidElement)(t)){let i=this._renderReactSubtree(t);this.reactSubtrees.push(i),n=i.component}else n=t;if(n.componentName==="Port"){if(this._hasExistingPortExactly(n))return;let r=this.children.filter(o=>o.componentName==="Port").find(o=>o.isMatchingAnyOf(n.getNameAndAliases()));r&&Cvt(`Similar ports added. Port 1: ${r}, Port 2: ${n}`)}super.add(n)}getPortsFromFootprint(t){let{footprint:n}=this.props;if((!n||(0,Za.isValidElement)(n))&&(n=this.children.find(r=>r.componentName==="Footprint")),typeof n=="string"){if(Lf(n))return[];if(nI(n))return[];let r=$v.string(n).soup(),o=[];for(let s of r)if("port_hints"in s&&s.port_hints){let a=Mf(s.port_hints,t);if(!a)continue;a.originDescription=`footprint:string:${n}:port_hints[0]:${s.port_hints[0]}`,o.push(a)}return o}if(!(0,Za.isValidElement)(n)&&n&&n.componentName==="Footprint"){let r=n,o=1,s=[];for(let a of r.children){if(!a.props.portHints)continue;let c=a.props.portHints;c.some(h=>h.startsWith("pin"))||(c=[...c,`pin${o}`]),o++;let u=Mf(c);u&&(u.originDescription=`footprint:${n}`,s.push(u))}return s}let i=[];if(!n){for(let r of this.children)if(r.props.portHints&&r.isPcbPrimitive){let o=Mf(r.props.portHints);o&&i.push(o)}}return i}getPortsFromSchematicSymbol(){if(this.root?.schematicDisabled)return[];let{config:t}=this;if(!t.schematicSymbolName)return[];let n=Un[t.schematicSymbolName];if(!n)return[];let i=[];for(let r of n.ports){let o=Mf(r.labels);o&&(o.schematicSymbolPortDef=r,i.push(o))}return i}doInitialCreateNetsFromProps(){this._createNetsFromProps(this._getNetsFromConnectionsProp())}_getNetsFromConnectionsProp(){let{_parsedProps:t}=this,n=[];if(t.connections)for(let[i,r]of Object.entries(t.connections)){let o=Array.isArray(r)?r:[r];for(let s of o)n.push(s)}return n}_createNetsFromProps(t){cI(this,t)}_getPcbCircuitJsonBounds(){let{db:t}=this.root;if(!this.pcb_component_id)return super._getPcbCircuitJsonBounds();let n=t.pcb_component.get(this.pcb_component_id);return{center:{x:n.center.x,y:n.center.y},bounds:{left:n.center.x-n.width/2,top:n.center.y-n.height/2,right:n.center.x+n.width/2,bottom:n.center.y+n.height/2},width:n.width,height:n.height}}_getPinCountFromSchematicPortArrangement(){let t=this._getSchematicPortArrangement();if(!t)return 0;if(!wY(t))return(t.leftSize??t.leftPinCount??0)+(t.rightSize??t.rightPinCount??0)+(t.topSize??t.topPinCount??0)+(t.bottomSize??t.bottomPinCount??0);let{leftSide:i,rightSide:r,topSide:o,bottomSide:s}=t;return Math.max(...i?.pins??[],...r?.pins??[],...o?.pins??[],...s?.pins??[])}_getPinCount(){if(this._getSchematicPortArrangement())return this._getPinCountFromSchematicPortArrangement();let n=this.getPortsFromFootprint();if(n.length>0)return n.length;let{pinLabels:i}=this._parsedProps;if(i){if(Array.isArray(i))return i.length;let r=Object.keys(i).map(o=>o.startsWith("pin")?parseInt(o.slice(3)):parseInt(o)).filter(o=>!Number.isNaN(o));return r.length>0?Math.max(...r):Object.keys(i).length}return 0}_getSchematicPortArrangement(){return this._parsedProps.schPinArrangement??this._parsedProps.schPortArrangement}_getSchematicBoxDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;let{_parsedProps:t}=this,n=this._getPinCount(),i=t.schPinSpacing??.2;return V2t({schWidth:t.schWidth,schHeight:t.schHeight,schPinSpacing:i,numericSchPinStyle:G2t(t.schPinStyle,t.pinLabels),pinCount:n,schPortArrangement:this._getSchematicPortArrangement(),pinLabels:t.pinLabels})}doInitialCadModelRender(){if(this._isCadModelChild)return;let{db:t}=this.root,{boardThickness:n=0}=this.root?._getBoard()??{},i=this._parsedProps.cadModel,r=i===void 0?this._asyncFootprintCadModel:i,o=this.props.footprint??this._getImpliedFootprintString();if(!this.pcb_component_id||!r&&!o||r===null)return;let s=this._getPcbCircuitJsonBounds(),a=t.pcb_component.get(this.pcb_component_id);if(typeof r=="string")throw new Error("String cadModel not yet implemented");let c=kvt.parse({x:0,y:0,z:typeof r?.rotationOffset=="number"?r.rotationOffset:0,...typeof r?.rotationOffset=="object"?r.rotationOffset??{}:{}}),l=Xc.parse({x:0,y:0,z:0,...typeof r?.positionOffset=="object"?r.positionOffset:{}}),u=this.props.layer==="bottom"?"bottom":"top",h=this._computePcbGlobalTransformBeforeLayout(),_=fo(h).rotation.angle*180/Math.PI,y=t.cad_component.insert({position:{x:s.center.x+l.x,y:s.center.y+l.y,z:(u==="bottom"?-n/2:n/2)+l.z},rotation:{x:c.x,y:(u==="top"?0:180)+c.y,z:u==="bottom"?-(_+c.z)+180:_+c.z},pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,model_stl_url:"stlUrl"in(r??{})?this._addCachebustToModelUrl(r.stlUrl):void 0,model_obj_url:"objUrl"in(r??{})?this._addCachebustToModelUrl(r.objUrl):void 0,model_mtl_url:"mtlUrl"in(r??{})?this._addCachebustToModelUrl(r.mtlUrl):void 0,model_gltf_url:"gltfUrl"in(r??{})?this._addCachebustToModelUrl(r.gltfUrl):void 0,model_glb_url:"glbUrl"in(r??{})?this._addCachebustToModelUrl(r.glbUrl):void 0,model_step_url:"stepUrl"in(r??{})?this._addCachebustToModelUrl(r.stepUrl):void 0,model_wrl_url:"wrlUrl"in(r??{})?this._addCachebustToModelUrl(r.wrlUrl):void 0,model_jscad:"jscad"in(r??{})?r.jscad:void 0,model_unit_to_mm_scale_factor:typeof r?.modelUnitToMmScale=="number"?r.modelUnitToMmScale:void 0,footprinter_string:typeof o=="string"&&!r?o:void 0});this.cad_component_id=y.cad_component_id}_addCachebustToModelUrl(t){if(!t||!t.includes("modelcdn.tscircuit.com"))return t;let n=this.root?.getClientOrigin()??"";return`${t}${t.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(n)}`}_getPartsEngineCacheKey(t,n){return JSON.stringify({ftype:t.ftype,name:t.name,manufacturer_part_number:t.manufacturer_part_number,footprinterString:n})}async _getSupplierPartNumbers(t,n,i){if(this.props.doNotPlace)return{};let r=this.root?.platform?.localCacheEngine,o=this._getPartsEngineCacheKey(n,i);if(r){let c=await r.getItem(o);if(c)try{return JSON.parse(c)}catch{}}let s=await Promise.resolve(t.findPart({sourceComponent:n,footprinterString:i})),a=s==="Not found"?{}:s;if(r)try{await r.setItem(o,JSON.stringify(a))}catch{}return a}doInitialPartsEngineRender(){if(this.props.doNotPlace)return;let t=this.getInheritedProperty("partsEngine");if(!t)return;let{db:n}=this.root,i=n.source_component.get(this.source_component_id);if(!i||i.supplier_part_numbers)return;let r;this.props.footprint&&typeof this.props.footprint=="string"&&(r=this.props.footprint);let o=this._getSupplierPartNumbers(t,i,r);if(!(o instanceof Promise)){n.source_component.update(this.source_component_id,{supplier_part_numbers:o});return}this._queueAsyncEffect("get-supplier-part-numbers",async()=>{this._asyncSupplierPartNumbers=await o,this._markDirty("PartsEngineRender")})}updatePartsEngineRender(){if(this.props.doNotPlace)return;let{db:t}=this.root,n=t.source_component.get(this.source_component_id);if(n&&!n.supplier_part_numbers&&this._asyncSupplierPartNumbers){t.source_component.update(this.source_component_id,{supplier_part_numbers:this._asyncSupplierPartNumbers});return}}doInitialAssignFallbackProps(){let{_parsedProps:t}=this;t.connections&&!this.name&&(this.fallbackUnassignedName=this.getSubcircuit().getNextAvailableName(this))}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}_createTracesFromConnectionsProp(){let{_parsedProps:t}=this;if(t.connections)for(let[n,i]of Object.entries(t.connections)){let r=Array.isArray(i)?i:[i];for(let o of r)this.add(new yo({from:`${this.getSubcircuitSelector()} > port.${n}`,to:o}))}}doInitialSourceDesignRuleChecks(){bvt(this)}_getMinimumFlexContainerSize(){return gvt(this)}_repositionOnPcb(t){return xvt(this,t)}doInitialSilkscreenOverlapAdjustment(){return Svt(this)}},Avt=class{constructor(e,t={}){T(this,"input");T(this,"isRouting",!1);T(this,"solver");T(this,"eventHandlers",{complete:[],error:[],progress:[]});T(this,"cycleCount",0);T(this,"stepDelay");T(this,"timeoutId");this.input=e;let{capacityDepth:n,targetMinCapacity:i,stepDelay:r=0}=t;this.solver=new $z(e,{capacityDepth:n,targetMinCapacity:i,cacheProvider:null}),this.stepDelay=r}start(){this.isRouting||(this.isRouting=!0,this.cycleCount=0,this.runCycleAndQueueNextCycle())}runCycleAndQueueNextCycle(){if(this.isRouting)try{if(this.solver.solved||this.solver.failed){this.solver.failed?this.emitEvent({type:"error",error:new Cf(this.solver.error||"Routing failed")}):this.emitEvent({type:"complete",traces:this.solver.getOutputSimpleRouteJson().traces||[]}),this.isRouting=!1;return}let e=Date.now(),t=this.solver.iterations;for(;Date.now()-e<250&&!this.solver.failed&&!this.solver.solved;)this.solver.step();let n=(this.solver.iterations-t)/(Date.now()-e)*1e3;this.cycleCount++;let i=this.solver?.preview()||void 0,r=this.solver.progress;this.emitEvent({type:"progress",steps:this.cycleCount,iterationsPerSecond:n,progress:r,phase:this.solver.getCurrentPhase(),debugGraphics:i}),this.stepDelay>0?this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),this.stepDelay):this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),0)}catch(e){this.emitEvent({type:"error",error:e instanceof Error?new Cf(e.message):new Cf(String(e))}),this.isRouting=!1}}stop(){this.isRouting&&(this.isRouting=!1,this.timeoutId!==void 0&&(clearTimeout(this.timeoutId),this.timeoutId=void 0))}on(e,t){e==="complete"?this.eventHandlers.complete.push(t):e==="error"?this.eventHandlers.error.push(t):e==="progress"&&this.eventHandlers.progress.push(t)}emitEvent(e){if(e.type==="complete")for(let t of this.eventHandlers.complete)t(e);else if(e.type==="error")for(let t of this.eventHandlers.error)t(e);else if(e.type==="progress")for(let t of this.eventHandlers.progress)t(e)}solveSync(){if(this.solver.solve(),this.solver.failed)throw new Cf(this.solver.error||"Routing failed");return this.solver.getOutputSimpleRouteJson().traces||[]}},fI=class extends Ie{constructor(){super(...arguments);T(this,"matchedPort",null)}get config(){return{componentName:"TraceHint",zodProps:fF}}doInitialPortMatching(){let{db:t}=this.root,{_parsedProps:n,parent:i}=this;if(!i)return;if(i.componentName==="Trace"){this.renderError(`Port inference inside trace is not yet supported (${this})`);return}if(!i)throw new Error("TraceHint has no parent");if(!n.for){this.renderError(`TraceHint has no for property (${this})`);return}let r=i.selectOne(n.for,{type:"port"});r||this.renderError(`${this} could not find port for selector "${n.for}"`),this.matchedPort=r,r.registerMatch(this)}getPcbRouteHints(){let{_parsedProps:t}=this,n=t.offset?[t.offset]:t.offsets;if(!n)return[];let i=this._computePcbGlobalTransformBeforeLayout();return n.map(r=>({...kn(i,r),via:r.via,to_layer:r.to_layer,trace_width:r.trace_width}))}doInitialPcbTraceHintRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this;t.pcb_trace_hint.insert({pcb_component_id:this.matchedPort?.pcb_component_id,pcb_port_id:this.matchedPort?.pcb_port_id,route:this.getPcbRouteHints()})}},CY=({circuitJson:e,editEvents:t,manualEditsFile:n})=>{let i={...n,pcb_placements:[...n.pcb_placements??[]]};for(let r of t)if(r.edit_event_type==="edit_pcb_component_location"){let{pcb_component_id:o,new_center:s}=r,a=Me(e).pcb_component.get(o);if(!a)continue;let c=Me(e).source_component.get(a.source_component_id);if(!c)continue;let l=i.pcb_placements?.findIndex(h=>h.selector===c.name),u={selector:c.name,center:s,relative_to:"group_center"};l>=0?i.pcb_placements[l]=u:i.pcb_placements.push(u)}return i},kY=({circuitJson:e,editEvents:t,manualEditsFile:n})=>{let i={...n,schematic_placements:[...n.schematic_placements??[]]};for(let r of t)if(r.edit_event_type==="edit_schematic_component_location"){let{schematic_component_id:o,new_center:s}=r,a=Me(e).schematic_component.get(o);if(!a||!a.source_component_id)continue;let c=Me(e).source_component.get(a.source_component_id);if(!c)continue;let l=i.schematic_placements?.findIndex(h=>h.selector===c.name),u={selector:c.name,center:s,relative_to:"group_center"};l>=0?i.schematic_placements[l]=u:i.schematic_placements.push(u)}return i},Nvt=({circuitJson:e,editEvents:t,manualEditsFile:n})=>{let i=t.filter(s=>s.edit_event_type==="edit_schematic_component_location"),r=t.filter(s=>s.edit_event_type==="edit_pcb_component_location"),o=n;return i.length>0&&(o=kY({circuitJson:e,editEvents:i,manualEditsFile:o})),r.length>0&&(o=CY({circuitJson:e,editEvents:r,manualEditsFile:o})),o},Rvt=(e,t)=>{if(Me(e).pcb_trace_hint.get(t.pcb_trace_hint_id))e=e.map(i=>i.pcb_trace_hint_id===t.pcb_trace_hint_id?{...i,route:t.route}:i);else{let i=Me(e).pcb_port.get(t.pcb_port_id);e=e.filter(r=>!(r.type==="pcb_trace_hint"&&r.pcb_port_id===t.pcb_port_id)).concat([{type:"pcb_trace_hint",pcb_trace_hint_id:t.pcb_trace_hint_id,route:t.route,pcb_port_id:t.pcb_port_id,pcb_component_id:i?.pcb_component_id}])}return e},Ovt=({circuitJson:e,editEvents:t})=>{e=JSON.parse(JSON.stringify(e));for(let n of t)if(n.edit_event_type==="edit_pcb_component_location"){let i=e.find(o=>o.type==="pcb_component"&&o.pcb_component_id===n.pcb_component_id);if((!i||i.center.x!==n.new_center.x||i.center.y!==n.new_center.y)&&n.original_center){let o=fn(n.new_center.x-n.original_center.x,n.new_center.y-n.original_center.y);e=e.map(s=>s.pcb_component_id!==n.pcb_component_id?s:E5(s,o))}}else n.edit_event_type==="edit_schematic_component_location"?e=e.map(i=>i.type==="schematic_component"&&i.schematic_component_id===n.schematic_component_id?{...i,center:n.new_center}:i):n.edit_event_type==="edit_pcb_trace_hint"&&(e=Rvt(e,n));return e},AY=(e,t)=>{let n=e.source_group.list(),i=[],r=o=>{let s=n.filter(a=>a.parent_subcircuit_id===o);for(let a of s)a.subcircuit_id&&(i.push(a.subcircuit_id),r(a.subcircuit_id))};return r(t),i},iI=({db:e,circuitJson:t,subcircuit_id:n,minTraceWidth:i=.1})=>{if(!e&&t&&(e=Me(t)),!e)throw new Error("db or circuitJson is required");let r=e.pcb_trace_hint.list(),o=n?new Set([n]):null;if(n){let k=AY(e,n);for(let M of k)o.add(M)}let s=(t??e.toArray()).filter(k=>!n||"subcircuit_id"in k&&o.has(k.subcircuit_id)),a=e.pcb_board.list()[0];e=Me(s);let c=ar(s),l=hI([...e.pcb_component.list(),...e.pcb_smtpad.list(),...e.pcb_plated_hole.list(),...e.pcb_hole.list(),...e.pcb_via.list(),...e.pcb_cutout.list()].filter(k=>!n||o?.has(k.subcircuit_id)),c);for(let k of l){let M=k.connectedTo.flatMap(A=>c.getIdsConnectedToNet(A));k.connectedTo.push(...M)}let u=l.flatMap(k=>[{x:k.center.x-k.width/2,y:k.center.y-k.height/2},{x:k.center.x+k.width/2,y:k.center.y+k.height/2}]),h;if(a?h={minX:a.center.x-a.width/2,maxX:a.center.x+a.width/2,minY:a.center.y-a.height/2,maxY:a.center.y+a.height/2}:h={minX:Math.min(...u.map(k=>k.x))-1,maxX:Math.max(...u.map(k=>k.x))+1,minY:Math.min(...u.map(k=>k.y))-1,maxY:Math.max(...u.map(k=>k.y))+1},n){let k=e.pcb_group.getWhere({subcircuit_id:n});if(k){let M={minX:k.center.x-k.width/2,maxX:k.center.x+k.width/2,minY:k.center.y-k.height/2,maxY:k.center.y+k.height/2};h={minX:Math.min(h.minX,M.minX),maxX:Math.max(h.maxX,M.maxX),minY:Math.min(h.minY,M.minY),maxY:Math.max(h.maxY,M.maxY)}}}let f=new Set(e.pcb_trace.list().map(k=>k.source_trace_id).filter(k=>!!k)),_=e.source_trace.list().filter(k=>!f.has(k.source_trace_id)).map(k=>{let M=k.connected_source_port_ids.map(W=>{let Q=e.source_port.get(W),J=e.pcb_port.getWhere({source_port_id:W});return{...Q,...J}});if(M.length<2)return null;let[A,L]=M,B=A.layers?.[0]??"top",D=L.layers?.[0]??"top",V=r.filter(W=>W.pcb_port_id===A.pcb_port_id||W.pcb_port_id===L.pcb_port_id),X=[];for(let W of V){let J=e.pcb_port.get(W.pcb_port_id)?.layers?.[0]??"top";for(let _t of W.route)X.push({x:_t.x,y:_t.y,layer:J})}return{name:k.source_trace_id??c.getNetConnectedToId(k.source_trace_id)??"",source_trace_id:k.source_trace_id,pointsToConnect:[{x:A.x,y:A.y,layer:B,pointId:A.pcb_port_id,pcb_port_id:A.pcb_port_id},...X,{x:L.x,y:L.y,layer:D,pointId:L.pcb_port_id,pcb_port_id:L.pcb_port_id}]}}).filter(k=>k!==null),y=new Map(_.map(k=>[k.source_trace_id,k])),x=e.source_net.list().filter(k=>!n||o?.has(k.subcircuit_id)),v=[];for(let k of x){let M=e.source_trace.list().filter(A=>A.connected_source_net_ids?.includes(k.source_net_id));v.push({name:k.source_net_id??c.getNetConnectedToId(k.source_net_id),pointsToConnect:M.flatMap(A=>e.pcb_port.list().filter(B=>A.connected_source_port_ids.includes(B.source_port_id)).map(B=>({x:B.x,y:B.y,layer:B.layers?.[0]??"top",pointId:B.pcb_port_id,pcb_port_id:B.pcb_port_id})))})}let w=e.pcb_breakout_point.list().filter(k=>!n||o?.has(k.subcircuit_id)),S=[],C=new Map;for(let k of w){let M={x:k.x,y:k.y,layer:"top"};if(k.source_trace_id){let A=y.get(k.source_trace_id)??C.get(k.source_trace_id);if(A)A.pointsToConnect.push(M);else{let L={name:k.source_trace_id,source_trace_id:k.source_trace_id,pointsToConnect:[M]};S.push(L),C.set(k.source_trace_id,L)}}else if(k.source_net_id){let A=v.find(L=>L.name===k.source_net_id);A?A.pointsToConnect.push(M):S.push({name:k.source_net_id,pointsToConnect:[M]})}else if(k.source_port_id){let A=e.pcb_port.getWhere({source_port_id:k.source_port_id});A&&S.push({name:k.source_port_id,source_trace_id:void 0,pointsToConnect:[{x:A.x,y:A.y,layer:A.layers?.[0]??"top",pointId:A.pcb_port_id,pcb_port_id:A.pcb_port_id},M]})}}let E=[..._,...v,...S],R=new Map;for(let k of E)for(let M of k.pointsToConnect)M.pointId&&R.set(M.pointId,k);let I=e.pcb_trace.list().filter(k=>!n||o?.has(k.subcircuit_id));for(let k of I){let M=new Set;for(let B of k.route)B.start_pcb_port_id&&M.add(B.start_pcb_port_id),B.end_pcb_port_id&&M.add(B.end_pcb_port_id);if(M.size<2)continue;let A=M.values().next().value;if(!A)continue;let L=R.get(A);L&&[...M].every(B=>R.get(B)===L)&&(L.externallyConnectedPointIds??(L.externallyConnectedPointIds=[]),L.externallyConnectedPointIds.push([...M]))}return{simpleRouteJson:{bounds:h,obstacles:l,connections:E,layerCount:a?.num_layers??2,minTraceWidth:i},connMap:c}},Lvt=e=>{let t={};if(!e)return t;for(let i of Fs)t[i]=0;let n=new Map;for(let i of e){let[,,r,o]=i.type.split(":");if(o==="start"){n.set(`${r}:${i.renderId}`,i);continue}if(o==="end"){let s=n.get(`${r}:${i.renderId}`);if(s){let a=i.createdAt-s.createdAt;t[r]=(t[r]||0)+a}}}return t},Fvt=e=>{let t=e.map(c=>[...new Set(c)]),n=t.map(()=>[]),i=t.map(()=>null);for(let c=0;c<t.length;c++)for(let l of t[c])if(/^\d+$/.test(l)){i[c]=Number.parseInt(l);break}let r=0,o=new Set;for(let c=0;c<i.length;c++){let l=i[c];if(l===null||l<1)continue;if(!o.has(l)){o.add(l),n[c].push(`pin${l}`),r=Math.max(r,l);continue}let u=0;for(let h of n[c])h.startsWith(`pin${l}_alt`)&&u++;n[c].push(`pin${l}_alt${u+1}`)}for(let c=0;c<n.length;c++)n[c][0]?.includes("_alt")&&(r++,n[c].unshift(`pin${r}`));for(let c=0;c<n.length;c++)n[c].length===0&&(r++,n[c].push(`pin${r}`));let s={};for(let c of t)for(let l of c)/^\d+$/.test(l)||(s[l]=(s[l]??0)+1);let a={};for(let c=0;c<t.length;c++){let l=t[c];for(let u of l)/^\d+$/.test(u)||(s[u]===1?n[c].push(u):(a[u]=(a[u]??0)+1,n[c].push(`${u}${a[u]}`)))}return n},tY=(0,NY.default)("Group_doInitialSchematicLayoutMatchAdapt");function zvt(e){let{db:t}=e.root,n=kd(t.toArray(),{source_group_id:e.source_group_id}),i=i4(n);tY.enabled&&global.debugGraphics?.push(Ba(i,{title:`floatingBpcGraph-${e.name}`}));let r=i4(n),o={boxes:r.boxes,pins:r.pins.map(c=>({...c,color:c.color.replace("not_connected","normal")}))},{result:s}=f$([{variantName:"default",floatingGraph:r},{variantName:"noNotConnected",floatingGraph:o}],{singletonKeys:["vcc/2","gnd/2"],centerPinColors:["netlabel_center","component_center"],floatingBoxIdsWithMutablePinOffsets:new Set(r.boxes.filter(c=>r.pins.filter(h=>h.boxId===c.boxId).filter(h=>!h.color.includes("center")).length<=2).map(c=>c.boxId)),corpus:{}});tY.enabled&&global.debugGraphics?.push(Ba(s,{title:`laidOutBpcGraph-${e.name}`}));let a=e._getGlobalSchematicPositionBeforeLayout();for(let c of s.boxes){if(!c.center)continue;let l=t.schematic_component.get(c.boxId);if(l){let h={x:c.center.x+a.x,y:c.center.y+a.y},f=t.schematic_port.list({schematic_component_id:l.schematic_component_id}),_=t.schematic_text.list({schematic_component_id:l.schematic_component_id}),y={x:h.x-l.center.x,y:h.y-l.center.y};for(let x of f)x.center.x+=y.x,x.center.y+=y.y;for(let x of _)x.position.x+=y.x,x.position.y+=y.y;l.center=h;continue}let u=t.schematic_net_label.get(c.boxId);if(u){let h=s.pins.find(_=>_.boxId===c.boxId&&_.color==="netlabel_center");if(!h)throw new Error(`No pin found for net label: ${c.boxId}`);let f={x:c.center.x+a.x,y:c.center.y+a.y};u.center=f,u.anchor_position={x:f.x+h.offset.x,y:f.y+h.offset.y};continue}console.error(`No schematic element found for box: ${c.boxId}. This is a bug in the matchAdapt binding with @tscircuit/core`)}}var ue=(0,RY.default)("Group_doInitialSchematicLayoutMatchpack");function eY(e){switch(e){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:return"y+"}}function nY(e,t){let n=["right","up","left","down"],i=n.indexOf(e);if(i===-1)return e;let r=Math.round(t/90),o=(i+r)%4;return n[o<0?o+4:o]}function Dvt(e,t,n){let i={chipMap:{},chipPinMap:{},netMap:{},pinStrongConnMap:{},netConnMap:{},chipGap:.6,decouplingCapsGap:.4,partitionGap:1.2};ue(`[${n.name}] Processing ${e.childNodes.length} child nodes for input problem`),e.childNodes.forEach((o,s)=>{if(ue(`[${n.name}] Processing child ${s}: nodeType=${o.nodeType}`),o.nodeType==="component"?ue(`[${n.name}] - Component: ${o.sourceComponent?.name}`):o.nodeType==="group"&&ue(`[${n.name}] - Group: ${o.sourceGroup?.name}`),o.nodeType==="component"&&o.sourceComponent){let a=o.sourceComponent.name||`chip_${s}`,c=t.schematic_component.getWhere({source_component_id:o.sourceComponent.source_component_id});if(!c)return;let l=n.children.find(S=>S.source_component_id===o.sourceComponent?.source_component_id),u=[0,90,180,270];l?._parsedProps?.schOrientation&&(u=[0]),l?._parsedProps?.schRotation!==void 0&&(u=[0]);let h=l?._parsedProps?.schMarginLeft??l?._parsedProps?.schMarginX??0,f=l?._parsedProps?.schMarginRight??l?._parsedProps?.schMarginX??0,_=l?._parsedProps?.schMarginTop??l?._parsedProps?.schMarginY??0,y=l?._parsedProps?.schMarginBottom??l?._parsedProps?.schMarginY??0;l?.config.shouldRenderAsSchematicBox&&(_+=.4,y+=.4);let x=(f-h)/2,v=(_-y)/2;i.chipMap[a]={chipId:a,pins:[],size:{x:(c.size?.width||1)+h+f,y:(c.size?.height||1)+_+y},availableRotations:u};let w=t.schematic_port.list({schematic_component_id:c.schematic_component_id});for(let S of w){let C=t.source_port.get(S.source_port_id);if(!C)continue;let E=`${a}.${C.pin_number||C.name||S.schematic_port_id}`;i.chipMap[a].pins.push(E);let R=eY(S.facing_direction);i.chipPinMap[E]={pinId:E,offset:{x:(S.center?.x||0)-(c.center.x||0)+x,y:(S.center?.y||0)-(c.center.y||0)+v},side:R}}}else if(o.nodeType==="group"&&o.sourceGroup){let a=o.sourceGroup.name||`group_${s}`;ue(`[${n.name}] Processing nested group: ${a}`);let c=t.schematic_group?.getWhere?.({source_group_id:o.sourceGroup.source_group_id}),l=n.children.find(u=>u.source_group_id===o.sourceGroup?.source_group_id);if(ue(`[${n.name}] Found schematic_group for ${a}:`,c),c){ue(`[${n.name}] Treating group ${a} as composite chip`);let u=t.schematic_component.list({schematic_group_id:c.schematic_group_id});ue(`[${n.name}] Group ${a} has ${u.length} components:`,u.map(A=>A.source_component_id));let h=1/0,f=-1/0,_=1/0,y=-1/0,x=!1;for(let A of u)if(A.center&&A.size){x=!0;let L=A.size.width/2,B=A.size.height/2;h=Math.min(h,A.center.x-L),f=Math.max(f,A.center.x+L),_=Math.min(_,A.center.y-B),y=Math.max(y,A.center.y+B)}let v=l?._parsedProps?.schMarginLeft??l?._parsedProps?.schMarginX??0,w=l?._parsedProps?.schMarginRight??l?._parsedProps?.schMarginX??0,S=l?._parsedProps?.schMarginTop??l?._parsedProps?.schMarginY??0,C=l?._parsedProps?.schMarginBottom??l?._parsedProps?.schMarginY??0,E=(w-v)/2,R=(S-C)/2,I=(x?f-h:2)+v+w,k=(x?y-_:2)+S+C;ue(`[${n.name}] Group ${a} computed size: ${I} x ${k}`);let M=[];for(let A of u){let L=t.schematic_port.list({schematic_component_id:A.schematic_component_id});for(let B of L){let D=t.source_port.get(B.source_port_id);if(!D)continue;let V=`${a}.${D.pin_number||D.name||B.schematic_port_id}`;M.push(V);let X=c.center||{x:0,y:0},W=eY(B.facing_direction);i.chipPinMap[V]={pinId:V,offset:{x:(B.center?.x||0)-X.x+E,y:(B.center?.y||0)-X.y+R},side:W}}}ue(`[${n.name}] Group ${a} has ${M.length} pins:`,M),i.chipMap[a]={chipId:a,pins:M,size:{x:I,y:k}},ue(`[${n.name}] Added group ${a} to chipMap`)}else ue(`[${n.name}] Warning: No schematic_group found for group ${a}`)}}),ue(`[${n.name}] Creating connections using connectivity keys`);let r=new Map;for(let[o,s]of Object.entries(i.chipMap))for(let a of s.pins){let c=a.split(".").pop(),l=e.childNodes.find(u=>u.nodeType==="component"&&u.sourceComponent?u.sourceComponent.name===o:u.nodeType==="group"&&u.sourceGroup?`group_${e.childNodes.indexOf(u)}`===o:!1);if(l?.nodeType==="group"&&l.sourceGroup){let u=t.schematic_group?.getWhere?.({source_group_id:l.sourceGroup.source_group_id});if(u){let h=t.schematic_component.list({schematic_group_id:u.schematic_group_id});for(let f of h){let _=t.source_port.list({source_component_id:f.source_component_id});for(let y of _){let x=y.pin_number||y.name;if(String(x)===String(c))if(y.subcircuit_connectivity_map_key){let v=y.subcircuit_connectivity_map_key;r.has(v)||r.set(v,[]),r.get(v).push(a),ue(`[${n.name}] \u2713 Pin ${a} has connectivity key: ${v}`)}else ue(`[${n.name}] Pin ${a} has no connectivity key`)}}}}else if(l?.nodeType==="component"&&l.sourceComponent){let u=t.source_port.list({source_component_id:l.sourceComponent.source_component_id});for(let h of u){let f=h.pin_number||h.name;if(String(f)===String(c)&&h.subcircuit_connectivity_map_key){let _=h.subcircuit_connectivity_map_key;r.has(_)||r.set(_,[]),r.get(_).push(a),ue(`[${n.name}] Pin ${a} has connectivity key: ${_}`)}}}}ue(`[${n.name}] Found ${r.size} connectivity groups:`,Array.from(r.entries()).map(([o,s])=>({key:o,pins:s})));for(let[o,s]of r)if(s.length>=2){let a=t.source_trace.list().filter(u=>u.subcircuit_connectivity_map_key===o),c=a.some(u=>u.connected_source_net_ids&&u.connected_source_net_ids.length>0),l=a.some(u=>u.connected_source_port_ids&&u.connected_source_port_ids.length>=2);if(ue(`[${n.name}] Connectivity ${o}: hasNetConnections=${c}, hasDirectConnections=${l}`),l){for(let u of a)if(u.connected_source_port_ids&&u.connected_source_port_ids.length>=2){let h=[];for(let f of u.connected_source_port_ids)for(let _ of s){let y=_.split(".").pop(),x=t.source_port.get(f);if(x&&String(x.pin_number||x.name)===String(y)){let v=_.split(".")[0],w=e.childNodes.find(S=>S.nodeType==="component"&&S.sourceComponent?S.sourceComponent.name===v:S.nodeType==="group"&&S.sourceGroup?`group_${e.childNodes.indexOf(S)}`===v:!1);w?.nodeType==="component"&&w.sourceComponent&&t.source_port.list({source_component_id:w.sourceComponent.source_component_id}).some(C=>C.source_port_id===f)&&h.push(_)}}for(let f=0;f<h.length;f++)for(let _=f+1;_<h.length;_++){let y=h[f],x=h[_];i.pinStrongConnMap[`${y}-${x}`]=!0,i.pinStrongConnMap[`${x}-${y}`]=!0,ue(`[${n.name}] Created strong connection: ${y} <-> ${x}`)}}}if(c){let u=t.source_net.getWhere({subcircuit_connectivity_map_key:o}),h=u?.is_ground??!1,f=u?.is_power??!1;i.netMap[o]={netId:o,isGround:h,isPositiveVoltageSource:f};for(let _ of s)i.netConnMap[`${_}-${o}`]=!0;ue(`[${n.name}] Created net ${o} with ${s.length} pins:`,s)}}return i}function $vt(e){let{db:t}=e.root,n=fp(t.toArray(),{source_group_id:e.source_group_id});if(ue(`[${e.name}] Starting matchpack layout with ${n.childNodes.length} children`),ue(`[${e.name}] Tree structure:`,JSON.stringify(n,null,2)),n.childNodes.length<=1){ue(`[${e.name}] Only ${n.childNodes.length} children, skipping layout`);return}ue("Converting circuit tree to InputProblem...");let i=Dvt(n,t,e);ue.enabled&&e.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`matchpack-input-problem-${e.name}`,content:JSON.stringify(i,null,2)});let r=new yB(i);if(ue("Starting LayoutPipelineSolver..."),ue.enabled&&global.debugGraphics){let c=r.visualize();global.debugGraphics.push({...c,title:`matchpack-initial-${e.name}`})}if(r.solve(),ue(`Solver completed in ${r.iterations} iterations`),ue(`Solved: ${r.solved}, Failed: ${r.failed}`),r.failed)throw ue(`Solver failed with error: ${r.error}`),new Error(`Matchpack layout solver failed: ${r.error}`);let o=r.getOutputLayout();if(ue("OutputLayout:",JSON.stringify(o,null,2)),ue("Solver completed successfully:",!r.failed),ue.enabled&&global.debugGraphics){let c=r.visualize();global.debugGraphics.push({...c,title:`matchpack-final-${e.name}`})}let s=r.checkForOverlaps(o);if(s.length>0){ue(`Warning: Found ${s.length} overlapping components:`);for(let c of s)ue(` ${c.chip1} overlaps ${c.chip2} (area: ${c.overlapArea})`)}let a=e._getGlobalSchematicPositionBeforeLayout();ue(`Group offset: x=${a.x}, y=${a.y}`),ue(`Applying layout results for ${Object.keys(o.chipPlacements).length} chip placements`);for(let[c,l]of Object.entries(o.chipPlacements)){ue(`Processing placement for chip: ${c} at (${l.x}, ${l.y})`);let u=n.childNodes.find(f=>{if(f.nodeType==="component"&&f.sourceComponent){let _=f.sourceComponent.name===c;return ue(` Checking component ${f.sourceComponent.name}: matches=${_}`),_}if(f.nodeType==="group"&&f.sourceGroup){let _=f.sourceGroup.name,y=`group_${n.childNodes.indexOf(f)}`,x=y===c;return ue(` Checking group ${_} (expected chipId: ${y}): matches=${x}`),x}return!1});if(!u){ue(`Warning: No tree node found for chip: ${c}`),ue("Available tree nodes:",n.childNodes.map((f,_)=>({type:f.nodeType,name:f.nodeType==="component"?f.sourceComponent?.name:f.sourceGroup?.name,expectedChipId:f.nodeType==="group"?`group_${_}`:f.sourceComponent?.name})));continue}let h={x:l.x+a.x,y:l.y+a.y};if(u.nodeType==="component"&&u.sourceComponent){let f=t.schematic_component.getWhere({source_component_id:u.sourceComponent.source_component_id});if(f){ue(`Moving component ${c} to (${h.x}, ${h.y})`);let _=t.schematic_port.list({schematic_component_id:f.schematic_component_id}),y=t.schematic_text.list({schematic_component_id:f.schematic_component_id}),x={x:h.x-f.center.x,y:h.y-f.center.y};for(let v of _)v.center.x+=x.x,v.center.y+=x.y;for(let v of y)v.position.x+=x.x,v.position.y+=x.y;if(f.center=h,l.ccwRotationDegrees!==0){ue(`Component ${c} has rotation: ${l.ccwRotationDegrees}\xB0`);let v=l.ccwRotationDegrees*Math.PI/180,w=Math.cos(v),S=Math.sin(v);for(let C of _){let E=C.center.x-h.x,R=C.center.y-h.y,I=E*w-R*S,k=E*S+R*w;C.center.x=h.x+I,C.center.y=h.y+k;let M=C.facing_direction||"right";C.facing_direction=nY(M,l.ccwRotationDegrees)}for(let C of y){let E=C.position.x-h.x,R=C.position.y-h.y,I=E*w-R*S,k=E*S+R*w;C.position.x=h.x+I,C.position.y=h.y+k}if(f.symbol_name){let C=f.symbol_name.match(/_(right|left|up|down)$/);C&&(f.symbol_name=f.symbol_name.replace(C[0],`_${nY(C[1],l.ccwRotationDegrees)}`))}}}}else if(u.nodeType==="group"&&u.sourceGroup){let f=t.schematic_group?.getWhere?.({source_group_id:u.sourceGroup.source_group_id});if(f){ue(`Moving group ${c} to (${h.x}, ${h.y}) from (${f.center?.x}, ${f.center?.y})`);let _=t.schematic_component.list({schematic_group_id:f.schematic_group_id});ue(`Group ${c} has ${_.length} components to move`);let y=f.center||{x:0,y:0},x={x:h.x-y.x,y:h.y-y.y};ue(`Position delta for group ${c}: (${x.x}, ${x.y})`);for(let v of _)if(v.center){let w={...v.center};v.center.x+=x.x,v.center.y+=x.y,ue(`Moved component ${v.source_component_id} from (${w.x}, ${w.y}) to (${v.center.x}, ${v.center.y})`);let S=t.schematic_port.list({schematic_component_id:v.schematic_component_id}),C=t.schematic_text.list({schematic_component_id:v.schematic_component_id});for(let E of S)E.center&&(E.center.x+=x.x,E.center.y+=x.y);for(let E of C)E.position&&(E.position.x+=x.x,E.position.y+=x.y)}f.center=h,ue(`Updated group ${c} center to (${h.x}, ${h.y})`)}}}ue("Matchpack layout completed successfully")}function Bvt(e){if(!e.isSubcircuit)return;let{db:t}=e.root,n=e.selectAll("trace"),i=new bd({});i.addConnections(n.map(a=>{let c=t.source_trace.get(a.source_trace_id);return c?[c.source_trace_id,...c.connected_source_port_ids,...c.connected_source_net_ids]:null}).filter(a=>a!==null));let{name:r}=e._parsedProps;for(let a of n){if(!a.source_trace_id)continue;let c=i.getNetConnectedToId(a.source_trace_id);c&&(a.subcircuit_connectivity_map_key=`${r??`unnamedsubcircuit${e._renderId}`}_${c}`,t.source_trace.update(a.source_trace_id,{subcircuit_connectivity_map_key:a.subcircuit_connectivity_map_key}))}let o=new Set;for(let a of n){if(!a.source_trace_id)continue;let c=t.source_trace.get(a.source_trace_id);if(c)for(let l of c.connected_source_port_ids)o.add(l)}for(let a of o){let c=i.getNetConnectedToId(a);if(!c)continue;let l=`${r??`unnamedsubcircuit${e._renderId}`}_${c}`;t.source_port.update(a,{subcircuit_connectivity_map_key:l})}let s=new Set;for(let a of n){if(!a.source_trace_id)continue;let c=t.source_trace.get(a.source_trace_id);if(c)for(let l of c.connected_source_net_ids)s.add(l)}for(let a of s){let c=i.getNetConnectedToId(a);if(!c)continue;let l=`${r??`unnamedsubcircuit${e._renderId}`}_${c}`;t.source_net.update(a,{subcircuit_connectivity_map_key:l})}}function jvt(e){let{db:t}=e.root,n=e._parsedProps,i=e.children.filter(R=>{let I=R._parsedProps?.schX!==void 0||R._parsedProps?.schY!==void 0;return R.schematic_component_id&&!I});if(i.length===0)return;let r=0,o=0;for(let R of i){let I=t.schematic_component.get(R.schematic_component_id);I?.size&&(r=Math.max(r,I.size.width),o=Math.max(o,I.size.height))}r===0&&i.length>0&&(r=1),o===0&&i.length>0&&(o=1);let s=n.gridCols,a,c=n.gridGap,l=n.gridRowGap,u=n.gridColumnGap;n.schLayout?.grid&&(s=n.schLayout.grid.cols??s,a=n.schLayout.grid.rows,c=n.schLayout.gridGap??c,l=n.schLayout.gridRowGap??l,u=n.schLayout.gridColumnGap??u);let h,f;s!==void 0&&a!==void 0?(h=s,f=a):s!==void 0?(h=s,f=Math.ceil(i.length/h)):a!==void 0?(f=a,h=Math.ceil(i.length/f)):(h=Math.ceil(Math.sqrt(i.length)),f=Math.ceil(i.length/h)),h===0&&i.length>0&&(h=1),f===0&&i.length>0&&(f=i.length);let _,y,x=R=>{if(R!==void 0)return typeof R=="number"?R:$.parse(R)};if(l!==void 0||u!==void 0){let R=typeof c=="object"&&c!==null?c.x:c,I=typeof c=="object"&&c!==null?c.y:c;_=x(u??R)??1,y=x(l??I)??1}else if(typeof c=="number")_=c,y=c;else if(typeof c=="string"){let R=$.parse(c);_=R,y=R}else if(typeof c=="object"&&c!==null){let R=c.x,I=c.y;_=typeof R=="number"?R:$.parse(R??"0mm"),y=typeof I=="number"?I:$.parse(I??"0mm")}else _=1,y=1;let v=h*r+Math.max(0,h-1)*_,w=f*o+Math.max(0,f-1)*y,S=e._getGlobalSchematicPositionBeforeLayout(),C=S.x-v/2+r/2,E=S.y+w/2-o/2;for(let R=0;R<i.length;R++){let I=i[R];if(!I.schematic_component_id)continue;let k=Math.floor(R/h),M=R%h;if(k>=f||M>=h){console.warn(`Schematic grid layout: Child ${I.getString()} at index ${R} (row ${k}, col ${M}) exceeds specified grid dimensions (${f}x${h}). Skipping placement.`);continue}let A=C+M*(r+_),L=E-k*(o+y),B=t.schematic_component.get(I.schematic_component_id);if(B){let D=B.center,V={x:A,y:L};t.schematic_component.update(I.schematic_component_id,{center:V});let X=V.x-D.x,W=V.y-D.y,Q=t.schematic_port.list({schematic_component_id:I.schematic_component_id});for(let _t of Q)t.schematic_port.update(_t.schematic_port_id,{center:{x:_t.center.x+X,y:_t.center.y+W}});let J=t.schematic_text.list({schematic_component_id:I.schematic_component_id});for(let _t of J)t.schematic_text.update(_t.schematic_text_id,{position:{x:_t.position.x+X,y:_t.position.y+W}})}}e.schematic_group_id&&t.schematic_group.update(e.schematic_group_id,{width:v,height:w,center:S})}var iY=(e,t)=>{let{sourceComponent:n,sourceGroup:i}=t;if(t.nodeType==="component"){let r=e.schematic_component.getWhere({source_component_id:n?.source_component_id});return r?.size?{width:r.size.width,height:r.size.height}:null}if(t.nodeType==="group"){let r=e.schematic_group.getWhere({source_group_id:i?.source_group_id});if(r?.width&&r?.height)return{width:r.width,height:r.height};let o=e.schematic_component.list({schematic_group_id:r?.schematic_group_id}),s=1/0,a=-1/0,c=1/0,l=-1/0;for(let f of o)if(f.center&&f.size){let _=f.size.width/2,y=f.size.height/2;s=Math.min(s,f.center.x-_),a=Math.max(a,f.center.x+_),c=Math.min(c,f.center.y-y),l=Math.max(l,f.center.y+y)}let u=a-s,h=l-c;return{width:u,height:h}}return null},Yvt=e=>{let{db:t}=e.root,n=e._parsedProps,i=fp(t.toArray(),{source_group_id:e.source_group_id}),r=n.schJustifyContent??n.justifyContent,o=n.schAlignItems??n.alignItems,s=n.schFlexGap??n.schGap??n.gap,a=n.schFlexDirection??"row",c={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"space-between","space-between":"space-between","space-around":"space-around","space-evenly":"space-evenly",center:"center"}[r??"space-between"],l={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"stretch",center:"center"}[o??"center"];if(!c)throw new Error(`Invalid justifyContent value: "${r}"`);if(!l)throw new Error(`Invalid alignItems value: "${o}"`);let u=0,h=0;typeof s=="object"?(u=s.y??0,h=s.x??0):typeof s=="number"?(u=s,h=s):typeof s=="string"&&(u=$.parse(s),h=$.parse(s));let f,_=n.width??n.schWidth??void 0,y=n.height??n.schHeight??void 0;(_===void 0||y===void 0)&&(f=lg(i.childNodes.map(E=>iY(t,E)).filter(E=>E!==null),{alignItems:l,justifyContent:c,direction:a,rowGap:u,columnGap:h}),_=f.width,y=f.height);let v=new cx(_,y,{alignItems:l,justifyContent:c,direction:a,rowGap:u,columnGap:h});for(let E of i.childNodes){let R=iY(t,E);v.addChild({metadata:E,width:R?.width??0,height:R?.height??0,flexBasis:R?a==="row"?R.width:R.height:void 0})}v.build();let w={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let E of v.children)w.minX=Math.min(w.minX,E.position.x),w.minY=Math.min(w.minY,E.position.y),w.maxX=Math.max(w.maxX,E.position.x+E.size.width),w.maxY=Math.max(w.maxY,E.position.y+E.size.height);w.width=w.maxX-w.minX,w.height=w.maxY-w.minY;let S={x:-(w.maxX+w.minX)/2,y:-(w.maxY+w.minY)/2},C=t.toArray();for(let E of v.children){let{sourceComponent:R,sourceGroup:I}=E.metadata;if(R){let k=t.schematic_component.getWhere({source_component_id:R.source_component_id});if(!k)continue;BF(C,k.schematic_component_id,{x:E.position.x+E.size.width/2+S.x,y:E.position.y+E.size.height/2+S.y})}if(I){if(!t.schematic_group.getWhere({source_group_id:I.source_group_id}))continue;YF(C,I.source_group_id,{x:E.position.x+E.size.width/2+S.x,y:E.position.y+E.size.height/2+S.y})}}e.schematic_group_id&&t.schematic_group.update(e.schematic_group_id,{width:w.width,height:w.height})},UT=1;function Xvt(e){let{db:t}=e.root,n=e._parsedProps,i=Vvt(e);if(i.length===0)return;let r=Hvt({db:t,pcbChildren:i}),o=Gvt(n),s=Uvt({props:n,pcbChildren:i,childDimensions:r,gridConfig:o}),a=Zvt({pcbChildren:i,childDimensions:r,gridLayout:s,gridConfig:o}),{itemCoordinates:c}=a.layout();Kvt({db:t,group:e,pcbChildren:i,itemCoordinates:c,gridLayout:s}),Jvt({db:t,group:e,props:n,gridLayout:s})}function Vvt(e){return e.children.filter(t=>t.pcb_component_id||t.pcb_group_id)}function Hvt(e){let{db:t,pcbChildren:n}=e,i=0,r=0;for(let o of n){let s=0,a=0;if(o.pcb_group_id){let c=t.pcb_group.get(o.pcb_group_id);s=c?.width??0,a=c?.height??0}else if(o.pcb_component_id){let c=t.pcb_component.get(o.pcb_component_id);s=c?.width??0,a=c?.height??0}i=Math.max(i,s),r=Math.max(r,a)}return{width:i,height:r}}function Gvt(e){let t=e.pcbGridCols??e.gridCols??e.pcbLayout?.grid?.cols,n=e.pcbGridRows??e.pcbLayout?.grid?.rows,i=e.pcbGridTemplateColumns,r=e.pcbGridTemplateRows,o=h=>h===void 0?UT:typeof h=="number"?h:$.parse(h),s=e.pcbGridGap??e.gridGap??e.pcbLayout?.gridGap,a=e.pcbGridRowGap??e.gridRowGap??e.pcbLayout?.gridRowGap,c=e.pcbGridColumnGap??e.gridColumnGap??e.pcbLayout?.gridColumnGap,l=UT,u=UT;if(a!==void 0||c!==void 0){let h=typeof s=="object"?s?.x:s,f=typeof s=="object"?s?.y:s;l=o(c??h),u=o(a??f)}else if(typeof s=="object"&&s!==null)l=o(s.x),u=o(s.y);else{let h=o(s);l=h,u=h}return{cols:t,rows:n,gapX:l,gapY:u,templateColumns:i,templateRows:r}}function Uvt(e){let{props:t,pcbChildren:n,childDimensions:i,gridConfig:r}=e;return t.pcbGridTemplateColumns||t.pcbGridTemplateRows?qvt({props:t,gridConfig:r,pcbChildren:n,childDimensions:i}):Wvt({gridConfig:r,pcbChildren:n,childDimensions:i})}function qvt(e){let{props:t,gridConfig:n,pcbChildren:i,childDimensions:r}=e,o=t.pcbGridTemplateColumns??"",s=t.pcbGridTemplateRows??"",a=f=>{let _=f.match(/repeat\((\d+),/);return _?parseInt(_[1]):Math.ceil(Math.sqrt(i.length))},c=t.pcbGridTemplateColumns?a(o):Math.ceil(Math.sqrt(i.length)),l=t.pcbGridTemplateRows?a(s):Math.ceil(i.length/c),u=c*r.width+Math.max(0,c-1)*n.gapX,h=l*r.height+Math.max(0,l-1)*n.gapY;return{gridTemplateColumns:o,gridTemplateRows:s,containerWidth:u,containerHeight:h}}function Wvt(e){let{gridConfig:t,pcbChildren:n,childDimensions:i}=e,r,o;t.cols!==void 0&&t.rows!==void 0?(r=t.cols,o=t.rows):t.cols!==void 0?(r=t.cols,o=Math.ceil(n.length/r)):t.rows!==void 0?(o=t.rows,r=Math.ceil(n.length/o)):(r=Math.ceil(Math.sqrt(n.length)),o=Math.ceil(n.length/r)),r=Math.max(1,r),o=Math.max(1,o);let s=r*i.width+Math.max(0,r-1)*t.gapX,a=o*i.height+Math.max(0,o-1)*t.gapY,c=`repeat(${r}, ${i.width}px)`,l=`repeat(${o}, ${i.height}px)`;return{gridTemplateColumns:c,gridTemplateRows:l,containerWidth:s,containerHeight:a}}function Zvt(e){let{pcbChildren:t,childDimensions:n,gridLayout:i,gridConfig:r}=e,o=t.map((s,a)=>({key:s.getString()||`child-${a}`,contentWidth:n.width,contentHeight:n.height}));return new IB({containerWidth:i.containerWidth,containerHeight:i.containerHeight,gridTemplateColumns:i.gridTemplateColumns,gridTemplateRows:i.gridTemplateRows,gap:[r.gapY,r.gapX],children:o})}function Kvt(e){let{db:t,group:n,pcbChildren:i,itemCoordinates:r,gridLayout:o}=e,s=n._getGlobalPcbPositionBeforeLayout(),a=t.toArray();for(let c=0;c<i.length;c++){let l=i[c],u=l.getString()||`child-${c}`,h=r[u];if(!h){console.warn(`PCB grid layout: No coordinates found for child ${u}`);continue}let f=s.x-o.containerWidth/2+h.x+h.width/2,_=s.y+o.containerHeight/2-h.y-h.height/2;if(l.pcb_component_id)ag(a,l.pcb_component_id,{x:f,y:_});else{let y=l;y.pcb_group_id&&y.source_group_id&&cg(a,y.source_group_id,{x:f,y:_})}}}function Jvt(e){let{db:t,group:n,props:i,gridLayout:r}=e;if(n.pcb_group_id){let o=n._getGlobalPcbPositionBeforeLayout();t.pcb_group.update(n.pcb_group_id,{width:i.width??r.containerWidth,height:i.height??r.containerHeight,center:o})}}function Qvt(e){let t={serverUrl:"https://registry-api.tscircuit.com",serverMode:"job",serverCacheEnabled:!0};if(typeof e=="object"&&!e.preset)return{local:!(e.serverUrl||e.serverMode||e.serverCacheEnabled),...t,...e};let n=typeof e=="object"?e.preset:e,i=typeof e=="object"?e:{};switch(n){case"auto-local":return{local:!0,groupMode:"subcircuit"};case"sequential-trace":return{local:!0,groupMode:"sequential-trace"};case"subcircuit":return{local:!0,groupMode:"subcircuit"};case"auto-cloud":{let{preset:r,local:o,groupMode:s,...a}=i;return{local:!1,groupMode:"subcircuit",...t,...a}}default:return{local:!0,groupMode:"subcircuit"}}}var twt=(e,t)=>{let n=e.children.filter(h=>h.componentName==="Constraint"&&h._parsedProps.pcb),i=new Map,r={},o=h=>(r[h]!==h&&(r[h]=o(r[h])),r[h]),s=(h,f)=>{let _=o(h),y=o(f);_!==y&&(r[y]=_)},a=h=>{h in r||(r[h]=h)},c=h=>{let f=h.startsWith(".")?h.slice(1):h;return e.children.find(y=>y.name===f)?.pcb_component_id??void 0};for(let h of n){let f=h._parsedProps;if("left"in f&&"right"in f){let _=c(f.left),y=c(f.right);_&&y&&(a(_),a(y),s(_,y))}else if("top"in f&&"bottom"in f){let _=c(f.top),y=c(f.bottom);_&&y&&(a(_),a(y),s(_,y))}else if("for"in f&&Array.isArray(f.for)){let _=f.for.map(y=>c(y)).filter(y=>!!y);for(let y of _)a(y);for(let y=1;y<_.length;y++)s(_[0],_[y])}}for(let h of Object.keys(r)){let f=o(h);i.has(f)||i.set(f,{componentIds:[],constraints:[]}),i.get(f).componentIds.push(h)}for(let h of n){let f=h._parsedProps,_;if("left"in f?_=c(f.left):"top"in f?_=c(f.top):"for"in f&&(_=c(f.for[0])),!_)continue;let y=o(_);i.get(y)?.constraints.push(h)}let l={},u=Object.fromEntries(t.components.map(h=>[h.componentId,h]));for(let[h,f]of i.entries()){if(f.componentIds.length<=1)continue;let _=new up,y={},x=(A,L)=>{let B=`${A}_${L}`;return y[B]||(y[B]=new Is(B)),y[B]},v=f.componentIds[0];_.addConstraint(new ti(x(v,"x"),zn.Eq,0,mn.required)),_.addConstraint(new ti(x(v,"y"),zn.Eq,0,mn.required));for(let A of f.constraints){let L=A._parsedProps;if("xDist"in L){let B=c(L.left),D=c(L.right);B&&D&&_.addConstraint(new ti(new bn(x(D,"x"),[-1,x(B,"x")]),zn.Eq,L.xDist,mn.required))}else if("yDist"in L){let B=c(L.top),D=c(L.bottom);B&&D&&_.addConstraint(new ti(new bn(x(B,"y"),[-1,x(D,"y")]),zn.Eq,L.yDist,mn.required))}else if("sameX"in L&&Array.isArray(L.for)){let B=L.for.map(D=>c(D)).filter(D=>!!D);if(B.length>1){let D=x(B[0],"x");for(let V=1;V<B.length;V++)_.addConstraint(new ti(new bn(x(B[V],"x"),[-1,D]),zn.Eq,0,mn.required))}}else if("sameY"in L&&Array.isArray(L.for)){let B=L.for.map(D=>c(D)).filter(D=>!!D);if(B.length>1){let D=x(B[0],"y");for(let V=1;V<B.length;V++)_.addConstraint(new ti(new bn(x(B[V],"y"),[-1,D]),zn.Eq,0,mn.required))}}}_.updateVariables();let w={};for(let A of f.componentIds)w[A]={x:x(A,"x").value(),y:x(A,"y").value()};let S=1/0,C=1/0,E=-1/0,R=-1/0;for(let A of f.componentIds){let L=u[A],B=w[A];if(L)for(let D of L.pads){let V=B.x+D.offset.x,X=B.y+D.offset.y;S=Math.min(S,V-D.size.x/2),E=Math.max(E,V+D.size.x/2),C=Math.min(C,X-D.size.y/2),R=Math.max(R,X+D.size.y/2)}}let I={x:(S+E)/2,y:(C+R)/2},k=[],M={};for(let A of f.componentIds){let L=u[A],B=w[A];if(L){M[A]={x:B.x-I.x,y:B.y-I.y};for(let D of L.pads)k.push({padId:D.padId,networkId:D.networkId,type:D.type,size:D.size,offset:{x:B.x+D.offset.x-I.x,y:B.y+D.offset.y-I.y}})}}t.components=t.components.filter(A=>!f.componentIds.includes(A.componentId)),t.components.push({componentId:f.componentIds[0],pads:k,availableRotationDegrees:[0]}),f.relativeCenters=M,l[f.componentIds[0]]=f}return l},kf=(e,t,n)=>{if(t===n)return!0;let i=e.source_group.get(t);return!i||!i.parent_source_group_id?!1:kf(e,i.parent_source_group_id,n)},ewt=(e,t,n)=>{let{db:i}=e.root;for(let r of t.components){let{center:o,componentId:s,ccwRotationOffset:a,ccwRotationDegrees:c}=r,l=n[s];if(l){let w=(c??a??0)*Math.PI/180;for(let S of l.componentIds){let C=l.relativeCenters[S];if(!C)continue;let E={x:C.x*Math.cos(w)-C.y*Math.sin(w),y:C.x*Math.sin(w)+C.y*Math.cos(w)},R=i.pcb_component.get(S);if(!R)continue;let I=R.center,k=Gn(e._computePcbGlobalTransformBeforeLayout(),fn(o.x+E.x,o.y+E.y),va(w),fn(-I.x,-I.y)),M=i.toArray().filter(A=>"pcb_component_id"in A&&A.pcb_component_id===S);dp(M,k)}continue}let u=i.pcb_component.get(s);if(u){let v=e.source_group_id,S=i.source_component.get(u.source_component_id)?.source_group_id;if(S!==void 0&&!kf(i,S,v))continue;let C=u.center,E=c??a??0,R=Gn(e._computePcbGlobalTransformBeforeLayout(),fn(o.x,o.y),va(E*Math.PI/180),fn(-C.x,-C.y)),I=i.toArray().filter(k=>"pcb_component_id"in k&&k.pcb_component_id===s);dp(I,R);continue}let h=i.pcb_group.list().find(v=>v.source_group_id===s);if(!h)continue;let f=h.center,_=c??a??0,y=Gn(e._computePcbGlobalTransformBeforeLayout(),fn(o.x,o.y),va(_*Math.PI/180),fn(-f.x,-f.y)),x=i.toArray().filter(v=>{if("source_group_id"in v&&v.source_group_id&&(v.source_group_id===s||kf(i,v.source_group_id,s)))return!0;if("source_component_id"in v&&v.source_component_id){let w=i.source_component.get(v.source_component_id);if(w?.source_group_id&&(w.source_group_id===s||kf(i,w.source_group_id,s)))return!0}if("pcb_component_id"in v&&v.pcb_component_id){let w=i.pcb_component.get(v.pcb_component_id);if(w?.source_component_id){let S=i.source_component.get(w.source_component_id);if(S?.source_group_id&&(S.source_group_id===s||kf(i,S.source_group_id,s)))return!0}}return!1});dp(x,y),i.pcb_group.update(h.pcb_group_id,{center:o})}},nwt="1mm",rY=(0,OY.default)("Group_doInitialPcbLayoutPack"),iwt=e=>{let{db:t}=e.root,{_parsedProps:n}=e,{packOrderStrategy:i,packPlacementStrategy:r,gap:o,pcbGap:s,pcbPackGap:a}=n,c=a??s??o,l=$.parse(c??nwt),u={},h=x=>{if(x?.pcb_component_id&&x?._parsedProps){let v=x._parsedProps,w=$.parse(v.pcbMarginLeft??v.pcbMarginX??0),S=$.parse(v.pcbMarginRight??v.pcbMarginX??0),C=$.parse(v.pcbMarginTop??v.pcbMarginY??0),E=$.parse(v.pcbMarginBottom??v.pcbMarginY??0);(w||S||C||E)&&(u[x.pcb_component_id]={left:w,right:S,top:C,bottom:E})}x?.children&&x.children.forEach(h)};h(e);let f={...mB(fB(t.toArray(),{source_group_id:e.source_group_id,shouldAddInnerObstacles:!0,chipMarginsMap:u})),orderStrategy:i??"largest_to_smallest",placementStrategy:r??"minimum_sum_squared_distance_to_network",minGap:l},_=twt(e,f);rY.enabled&&(e.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`packInput-circuitjson-${e.name}`,content:JSON.stringify(t.toArray())}),e.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`packInput-${e.name}`,content:f}));let y=ox(f);if(rY.enabled){let x=fT(y);x.title=`packOutput-${e.name}`,global.debugGraphics?.push(x)}ewt(e,y,_)},rwt=e=>{let{db:t}=e.root,{_parsedProps:n}=e,i=e.children.filter(R=>R.pcb_component_id||R.pcb_group_id);if(i.some(R=>{let I=R._parsedProps;return I?.pcbX!==void 0||I?.pcbY!==void 0}))return;let o=n.pcbJustifyContent??n.justifyContent,s=n.pcbAlignItems??n.alignItems,a=n.pcbFlexGap??n.pcbGap??n.gap,c=n.pcbFlexDirection??"row",l={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"space-between","space-between":"space-between","space-around":"space-around","space-evenly":"space-evenly",center:"center"}[o??"space-between"],u={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"stretch",center:"center"}[s??"center"];if(!l)throw new Error(`Invalid justifyContent value: "${o}"`);if(!u)throw new Error(`Invalid alignItems value: "${s}"`);let h=0,f=0;typeof a=="object"?(h=a.y??0,f=a.x??0):typeof a=="number"?(h=a,f=a):typeof a=="string"&&(h=$.parse(a),f=$.parse(a));let _,y=n.width??n.pcbWidth??void 0,x=n.height??n.pcbHeight??void 0;(y===void 0||x===void 0)&&(_=lg(i.map(R=>R._getMinimumFlexContainerSize()).filter(R=>R!==null),{alignItems:u,justifyContent:l,direction:c,rowGap:h,columnGap:f}),y=_.width,x=_.height);let w=new cx(y,x,{alignItems:u,justifyContent:l,direction:c,rowGap:h,columnGap:f});for(let R of i){let I=R._getMinimumFlexContainerSize();w.addChild({metadata:R,width:I?.width??0,height:I?.height??0,flexBasis:I?c==="row"?I.width:I.height:void 0})}w.build();let S={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let R of w.children)S.minX=Math.min(S.minX,R.position.x),S.minY=Math.min(S.minY,R.position.y),S.maxX=Math.max(S.maxX,R.position.x+R.size.width),S.maxY=Math.max(S.maxY,R.position.y+R.size.height);S.width=S.maxX-S.minX,S.height=S.maxY-S.minY;let C=e._getGlobalPcbPositionBeforeLayout(),E={x:C.x-(S.maxX+S.minX)/2,y:C.y-(S.maxY+S.minY)/2};for(let R of w.children)R.metadata._repositionOnPcb({x:R.position.x+R.size.width/2+E.x,y:R.position.y+R.size.height/2+E.y});t.pcb_group.update(e.pcb_group_id,{width:S.width,height:S.height,center:C})};function owt(e){let{db:t}=e.root,n=new Map,i=new Map,r=new Set,s=e.selectAll("trace").filter(L=>L._parsedProps?.schDisplayLabel),a=e.selectAll("group"),c=[e.schematic_group_id,...a.map(L=>L.schematic_group_id)],l=t.schematic_component.list().filter(L=>c.includes(L.schematic_group_id)),u=[],h=new Map,f=new Map;for(let L of l){let B=L.schematic_component_id,D=[],V=t.source_component.getWhere({source_component_id:L.source_component_id}),X=t.schematic_port.list({schematic_component_id:L.schematic_component_id});for(let W of X){let Q=`${V?.name??L.schematic_component_id}.${W.pin_number}`;h.set(Q,W.schematic_port_id),f.set(W.schematic_port_id,Q)}for(let W of X){let Q=f.get(W.schematic_port_id);D.push({pinId:Q,x:W.center.x,y:W.center.y})}u.push({chipId:B,center:L.center,width:L.size.width,height:L.size.height,pins:D})}let _=new Set,y=new Map,x=new Map,v=new Map;for(let L of l){let B=t.schematic_port.list({schematic_component_id:L.schematic_component_id});for(let D of B)_.add(D.schematic_port_id),D.source_port_id&&(y.set(D.schematic_port_id,D.source_port_id),x.set(D.source_port_id,D.schematic_port_id))}let w=new Set;e.subcircuit_id&&w.add(e.subcircuit_id);for(let L of a)L.subcircuit_id&&w.add(L.subcircuit_id);let C=t.source_trace.list().filter(L=>{if(L.subcircuit_id===e.subcircuit_id)return!0;for(let B of L.connected_source_port_ids)if(x.has(B))return!0;return!1}).flatMap(L=>L.connected_source_net_ids);for(let L of C){let B=t.source_net.get(L);B?.subcircuit_id&&w.add(B.subcircuit_id)}let E=[],R=new Map;for(let L of t.source_trace.list()){if(L.subcircuit_id&&!w.has(L.subcircuit_id))continue;let B=(L.connected_source_port_ids??[]).map(D=>x.get(D)).filter(D=>!!D&&_.has(D));if(B.length>=2){let[D,V]=B.slice(0,2),X=[D,V].sort().join("::");if(!R.has(X)){R.set(X,L.source_trace_id);let W=L.display_name??L.source_trace_id;L.subcircuit_connectivity_map_key&&(r.add(L.subcircuit_connectivity_map_key),v.set(W,L.subcircuit_connectivity_map_key),i.set(L.subcircuit_connectivity_map_key,W)),E.push({pinIds:[D,V].map(Q=>f.get(Q)),netId:W})}}}let I=[];for(let L of t.source_net.list().filter(B=>!B.subcircuit_id||w.has(B.subcircuit_id)))L.subcircuit_connectivity_map_key&&(r.add(L.subcircuit_connectivity_map_key),n.set(L.subcircuit_connectivity_map_key,L));let k=new Map;for(let[L,B]of y){let D=t.source_port.get(B);if(!D?.subcircuit_connectivity_map_key)continue;let V=D.subcircuit_connectivity_map_key;r.add(V),k.has(V)||k.set(V,[]),k.get(V).push(L)}for(let[L,B]of k){let D=n.get(L);if(D&&B.length>=2){let V=String(D.name||D.source_net_id||L);v.set(V,L),i.set(L,V);let W=.1*(.18/.18),Q=Number((String(V).length*W).toFixed(2));I.push({netId:V,pinIds:B.map(J=>f.get(J)),netLabelWidth:Q})}}let M=(()=>{let L={},B=new Set(I.map(D=>D.netId));for(let D of t.source_net.list().filter(V=>!V.subcircuit_id||w.has(V.subcircuit_id)))D.name&&B.has(D.name)&&(D.is_ground||D.name.toLowerCase().startsWith("gnd")?L[D.name]=["y-"]:D.is_power||D.name.toLowerCase().startsWith("v")?L[D.name]=["y+"]:L[D.name]=["x-","x+"]);return L})();return{inputProblem:{chips:u,directConnections:E,netConnections:I,availableNetLabelOrientations:M,maxMspPairDistance:e._parsedProps.schMaxTraceDistance??2.4},pinIdToSchematicPortId:h,pairKeyToSourceTraceId:R,sckToSourceNet:n,sckToUserNetId:i,userNetIdToSck:v,allSourceAndSchematicPortIdsInScope:_,schPortIdToSourcePortId:y,displayLabelTraces:s,allScks:r}}var zi=1e-6;function oY(e){let t=Math.abs(e.to.x-e.from.x),n=Math.abs(e.to.y-e.from.y);return t>=n}function Ax(e,t){return Math.hypot(t.x-e.x,t.y-e.y)}function sY(e,t,n){return{x:e.x+(t.x-e.x)*n,y:e.y+(t.y-e.y)*n}}function aY(e,t,n){let i=Ax(e,t);if(i<zi)return 0;let r=((n.x-e.x)*(t.x-e.x)+(n.y-e.y)*(t.y-e.y))/((t.x-e.x)*(t.x-e.x)+(t.y-e.y)*(t.y-e.y));return Math.max(0,Math.min(1,r))*i}function Px(e,t,n,i){return e*i-t*n}function swt(e,t,n,i){let r={x:t.x-e.x,y:t.y-e.y},o={x:i.x-n.x,y:i.y-n.y},s=Px(r.x,r.y,o.x,o.y),a={x:n.x-e.x,y:n.y-e.y},c=Px(a.x,a.y,r.x,r.y);if(Math.abs(s)<zi&&Math.abs(c)<zi||Math.abs(s)<zi&&Math.abs(c)>=zi)return null;let l=Px(a.x,a.y,o.x,o.y)/s,u=Px(a.x,a.y,r.x,r.y)/s;return l<-zi||l>1+zi||u<-zi||u>1+zi?null:{x:e.x+l*r.x,y:e.y+l*r.y}}function awt(e,t=zi){if(e.length===0)return e;e.sort((r,o)=>r.start-o.start);let n=[],i={...e[0]};for(let r=1;r<e.length;r++){let o=e[r];o.start<=i.end+t?i.end=Math.max(i.end,o.end):(n.push(i),i={...o})}return n.push(i),n}function cwt(e,t,n){let i=Ax(e.from,e.to);if(i<zi||t.length===0)return[e];let r=n/2,o=t.map(h=>({start:Math.max(0,h-r),end:Math.min(i,h+r)})).filter(h=>h.end-h.start>zi),s=awt(o),a=[],c=0,l={x:e.to.x-e.from.x,y:e.to.y-e.from.y},u=(h,f,_)=>{if(f-h<=zi)return;let y=h/i,x=f/i;a.push({from:sY(e.from,e.to,y),to:sY(e.from,e.to,x),..._?{is_crossing:!0}:{}})};for(let h of s)h.start-c>zi&&u(c,h.start,!1),u(h.start,h.end,!0),c=h.end;return i-c>zi&&u(c,i,!1),a.length>0?a:[e]}function lwt(e,t={}){let n=t.crossSegmentLength??.075,i=t.tolerance??zi,r=new Map,o=c=>`${c.traceIdx}:${c.edgeIdx}`,s=c=>e[c.traceIdx].edges[c.edgeIdx];for(let c=0;c<e.length;c++){let l=e[c];for(let u=0;u<l.edges.length;u++){let h=l.edges[u];for(let f=c;f<e.length;f++){let _=e[f];for(let y=f===c?u+1:0;y<_.edges.length;y++){let x=_.edges[y],v=swt(h.from,h.to,x.from,x.to);if(!v)continue;let w=Ax(h.from,h.to),S=Ax(x.from,x.to);if(w<i||S<i)continue;let C=aY(h.from,h.to,v),E=aY(x.from,x.to,v),R=C<=i||Math.abs(w-C)<=i||Number.isNaN(C),I=E<=i||Math.abs(S-E)<=i||Number.isNaN(E);if(!R&&!I){let k=oY(h),M=oY(x),A;if(k!==M)A=k;else{let D=Math.abs(h.to.x-h.from.x),V=Math.abs(h.to.y-h.from.y),X=Math.abs(x.to.x-x.from.x),W=Math.abs(x.to.y-x.from.y),Q=D-V,J=X-W;A=Q===J?!0:Q>J}let L=o({traceIdx:A?c:f,edgeIdx:A?u:y}),B=r.get(L)??[];B.push(A?C:E),r.set(L,B)}}}}}let a=e.map(c=>({source_trace_id:c.source_trace_id,edges:[]}));for(let c=0;c<e.length;c++){let l=e[c];for(let u=0;u<l.edges.length;u++){let h=o({traceIdx:c,edgeIdx:u}),f=r.get(h)??[];if(f.length===0){a[c].edges.push(l.edges[u]);continue}let _=Array.from(new Set(f.map(x=>Number(x.toFixed(6))))).sort((x,v)=>x-v),y=cwt(l.edges[u],_,n);a[c].edges.push(...y)}}return a}var Ho=1e-6;function Nx(e,t,n=Ho){return Math.abs(e-t)<=n}function Qp(e,t,n=Ho){return Nx(e.x,t.x,n)&&Nx(e.y,t.y,n)}function cY(e,t,n,i=Ho){let r=Math.min(t.x,n.x)-i,o=Math.max(t.x,n.x)+i,s=Math.min(t.y,n.y)-i,a=Math.max(t.y,n.y)+i;return e.x<r||e.x>o||e.y<s||e.y>a?!1:Math.abs((n.x-t.x)*(e.y-t.y)-(n.y-t.y)*(e.x-t.x))<=i}function lY(e,t=Ho){let n=new Map;for(let i of e){let r=`${i.x.toFixed(6)},${i.y.toFixed(6)}`;n.has(r)||n.set(r,i)}return Array.from(n.values())}function uY(e){return{x:e.to.x-e.from.x,y:e.to.y-e.from.y}}function qT(e,t,n=Ho){let i=uY(e),r=uY(t),o=Math.hypot(i.x,i.y),s=Math.hypot(r.x,r.y);if(o<n||s<n)return!0;let a=i.x*r.y-i.y*r.x;return Math.abs(a)<=n*o*s}function Af(e,t,n=Ho){return e.edges.filter(i=>Qp(i.from,t,n)||Qp(i.to,t,n))}function pY(e,t,n=Ho){for(let i of e.edges){if(Qp(i.from,t,n))return i.from;if(Qp(i.to,t,n))return i.to}return null}function uwt(e,t,n=Ho){let i=Qp(e.from,t,n)||Nx(e.from.x,t.x,n)&&Nx(e.from.y,t.y,n)?e.to:e.from,r=i.x-t.x,o=i.y-t.y;return Math.abs(r)<n&&Math.abs(o)<n?null:Math.abs(r)>=Math.abs(o)?r>=0?"right":"left":o>=0?"up":"down"}function Wp(e,t,n=Ho){let i=Af(e,t,n);if(i.length<2)return null;let r=i.map(h=>uwt(h,t,n)),o=r.includes("up"),s=r.includes("down"),a=r.includes("left"),c=r.includes("right"),l=o?"up":s?"down":null,u=c?"right":a?"left":null;return l&&u?`${l}-${u}`:null}function pwt(e,t={}){let n=t.tolerance??Ho,i={};for(let o of e)i[o.source_trace_id]=[];let r=e.map(o=>{let s=[];for(let a of o.edges)s.push(a.from,a.to);return lY(s,n)});for(let o=0;o<e.length;o++){let s=e[o],a=r[o];for(let c=o+1;c<e.length;c++){let l=e[c],u=r[c];for(let h of a)for(let f of u)if(Qp(h,f,n)){let _=Af(s,h,n),y=Af(l,f,n),x=_.some(C=>y.some(E=>!qT(C,E,n))),v=Wp(s,h,n),w=Wp(l,f,n);x&&!(v!==null&&w!==null&&v===w)&&(i[s.source_trace_id].push(h),s.source_trace_id!==l.source_trace_id&&i[l.source_trace_id].push(f))}for(let h of a)for(let f of l.edges)if(cY(h,f.from,f.to,n)){let y=Af(s,h,n).some(C=>!qT(C,f,n)),x=Wp(s,h,n),v=pY(l,h,n*1e3),w=v?Wp(l,v,n):null;y&&!(x!==null&&w!==null&&x===w)&&(i[s.source_trace_id].push(h),s.source_trace_id!==l.source_trace_id&&i[l.source_trace_id].push(h))}for(let h of u)for(let f of s.edges)if(cY(h,f.from,f.to,n)){let y=Af(l,h,n).some(C=>!qT(f,C,n)),x=Wp(l,h,n),v=pY(s,h,n*1e3),w=v?Wp(s,v,n):null;y&&!(w!==null&&x!==null&&w===x)&&(i[l.source_trace_id].push(h),s.source_trace_id!==l.source_trace_id&&i[s.source_trace_id].push(h))}}}for(let o of Object.keys(i))i[o]=lY(i[o],n);return i}var WT=(0,FY.default)("Group_doInitialSchematicTraceRender");function hwt(e){let{group:t,solver:n,pinIdToSchematicPortId:i,userNetIdToSck:r}=e,{db:o}=t.root,s=n.traceLabelOverlapAvoidanceSolver?.getOutput().traces??n.schematicTraceLinesSolver?.solvedTracePaths,a=[];WT(`Traces inside SchematicTraceSolver output: ${(s??[]).length}`);for(let u of s??[]){let h=u?.tracePath;if(!Array.isArray(h)||h.length<2){WT(`Skipping trace ${u?.pinIds.join(",")} because it has less than 2 points`);continue}let f=[];for(let x=0;x<h.length-1;x++)f.push({from:{x:h[x].x,y:h[x].y},to:{x:h[x+1].x,y:h[x+1].y}});let _=null,y;if(Array.isArray(u?.pins)&&u.pins.length===2){let x=i.get(u.pins[0]?.pinId),v=i.get(u.pins[1]?.pinId);if(x&&v){for(let w of[x,v])o.schematic_port.get(w)&&o.schematic_port.update(w,{is_connected:!0});y=r.get(String(u.userNetId))}}_||(_=`solver_${u?.mspPairId}`,y=r.get(String(u.userNetId))),a.push({source_trace_id:_,edges:f,subcircuit_connectivity_map_key:y})}WT(`Applying ${a.length} traces from SchematicTraceSolver output`);let c=lwt(a.map(u=>({source_trace_id:u.source_trace_id,edges:u.edges}))),l=pwt(c);for(let u of c)o.schematic_trace.insert({source_trace_id:u.source_trace_id,edges:u.edges,junctions:l[u.source_trace_id]??[],subcircuit_connectivity_map_key:a.find(h=>h.source_trace_id===u.source_trace_id)?.subcircuit_connectivity_map_key})}var dwt=e=>{switch(e){case"x+":return"left";case"x-":return"right";case"y+":return"bottom";case"y-":return"top";case"left":return"right";case"top":return"bottom";case"right":return"left";case"bottom":return"top"}},fwt=e=>{for(let n of e){let i=n._getDirectlyConnectedTraces();for(let r of i){let o=r._parsedProps.schDisplayLabel;if(o)return{name:o,wasAssignedDisplayLabel:!0}}}return{name:e.map(n=>n._getNetLabelText()).join("/"),wasAssignedDisplayLabel:!1}},ZT=(0,zY.default)("Group_doInitialSchematicTraceRender");function mwt(e){let{group:t,solver:n,sckToSourceNet:i,allScks:r,allSourceAndSchematicPortIdsInScope:o,schPortIdToSourcePortId:s,userNetIdToSck:a,pinIdToSchematicPortId:c,schematicPortIdsWithPreExistingNetLabels:l,schematicPortIdsWithRoutedTraces:u}=e,{db:h}=t.root,f=n.traceLabelOverlapAvoidanceSolver?.getOutput().netLabelPlacements??[],_=n.mspConnectionPairSolver.globalConnMap;for(let y of f){ZT(`processing placement: ${y.netId}`);let x=_.getIdsConnectedToNet(y.globalConnNetId).find(L=>a.get(L)),v=a.get(x),w=y.anchorPoint,S=y.orientation,C=dwt(S),E=v?i.get(v):void 0,R=y.pinIds.map(L=>c.get(L));if(R.some(L=>l.has(L))){ZT(`skipping net label placement for "${y.netId}" REASON:schematic port has pre-existing net label`);continue}if(E){let L=E.name,B=Ka({anchor_position:w,anchor_side:C,text:L});h.schematic_net_label.insert({text:L,anchor_position:w,center:B,anchor_side:C,...E?.source_net_id?{source_net_id:E.source_net_id}:{}});continue}let I=t.selectAll("port").filter(L=>L._getSubcircuitConnectivityKey()===v),{name:k,wasAssignedDisplayLabel:M}=fwt(I);if(!M&&R.some(L=>u.has(L))){ZT(`skipping net label placement for "${y.netId}" REASON:schematic port has routed traces and no display label`);continue}let A=Ka({anchor_position:w,anchor_side:C,text:k});h.schematic_net_label.insert({text:k,anchor_position:w,center:A,anchor_side:C})}}var _wt=({allSourceAndSchematicPortIdsInScope:e,group:t,schPortIdToSourcePortId:n,sckToSourceNet:i,pinIdToSchematicPortId:r,schematicPortIdsWithPreExistingNetLabels:o})=>{let{db:s}=t.root;for(let a of Array.from(e)){let c=s.schematic_port.get(a);if(!c||c.is_connected)continue;let l=n.get(a);if(!l)continue;let h=s.source_port.get(l)?.subcircuit_connectivity_map_key;if(!h)continue;let f=i.get(h);if(!f||s.schematic_net_label.list().some(w=>Math.abs(w.anchor_position.x-c.center.x)<.1&&Math.abs(w.anchor_position.y-c.center.y)<.1?f.source_net_id&&w.source_net_id?w.source_net_id===f.source_net_id:w.text===(f.name||h):!1))continue;let y=f.name||f.source_net_id||h,x=Of(c.facing_direction||"right")||"right",v=Ka({anchor_position:c.center,anchor_side:x,text:y});s.schematic_net_label.insert({text:y,anchor_position:c.center,center:v,anchor_side:x,...f.source_net_id?{source_net_id:f.source_net_id}:{}})}},ywt=e=>{let t=new Set,n=e.selectAll("netlabel");for(let i of n){let r=i._getConnectedPorts();for(let o of r)o.schematic_port_id&&t.add(o.schematic_port_id)}return t},gwt=({solver:e,pinIdToSchematicPortId:t})=>{let n=e.schematicTraceLinesSolver.solvedTracePaths,i=new Set;for(let r of n)for(let o of r.pinIds){let s=t.get(o);s&&i.add(s)}return i},xwt=(0,LY.default)("Group_doInitialSchematicTraceRender"),bwt=e=>{if(!e.root?._featureMspSchematicTraceRouting||!e.isSubcircuit||e.root?.schematicDisabled)return;let{inputProblem:t,pinIdToSchematicPortId:n,pairKeyToSourceTraceId:i,sckToSourceNet:r,allSourceAndSchematicPortIdsInScope:o,schPortIdToSourcePortId:s,displayLabelTraces:a,allScks:c,userNetIdToSck:l}=owt(e),u=ywt(e);xwt.enabled&&e.root?.emit("debug:logOutput",{type:"debug:logOutput",name:"group-trace-render-input-problem",content:JSON.stringify(t,null,2)});let h=new jB(t);h.solve();let f=gwt({solver:h,pinIdToSchematicPortId:n});hwt({group:e,solver:h,pinIdToSchematicPortId:n,userNetIdToSck:l}),mwt({group:e,solver:h,sckToSourceNet:r,allSourceAndSchematicPortIdsInScope:o,schPortIdToSourcePortId:s,pinIdToSchematicPortId:n,allScks:c,userNetIdToSck:l,schematicPortIdsWithPreExistingNetLabels:u,schematicPortIdsWithRoutedTraces:f}),_wt({group:e,allSourceAndSchematicPortIdsInScope:o,schPortIdToSourcePortId:s,sckToSourceNet:r,pinIdToSchematicPortId:n,schematicPortIdsWithPreExistingNetLabels:u})},th=class extends In{constructor(){super(...arguments);T(this,"pcb_group_id",null);T(this,"schematic_group_id",null);T(this,"subcircuit_id",null);T(this,"_hasStartedAsyncAutorouting",!1);T(this,"_asyncAutoroutingResult",null);T(this,"unnamedElementCounter",{})}get config(){return{zodProps:dL,componentName:"Group"}}doInitialSourceGroupRender(){let{db:t}=this.root,n=t.source_group.insert({name:this.name,is_subcircuit:this.isSubcircuit});this.source_group_id=n.source_group_id,this.isSubcircuit&&(this.subcircuit_id=`subcircuit_${n.source_group_id}`,t.source_group.update(n.source_group_id,{subcircuit_id:this.subcircuit_id}))}doInitialSourceRender(){let{db:t}=this.root;for(let n of this.children)t.source_component.update(n.source_component_id,{source_group_id:this.source_group_id})}doInitialSourceParentAttachment(){let{db:t}=this.root,n=this.parent?.getGroup?.();if(n?.source_group_id&&t.source_group.update(this.source_group_id,{parent_source_group_id:n.source_group_id}),!this.isSubcircuit)return;let i=this.parent?.getSubcircuit?.()?.subcircuit_id;i&&t.source_group.update(this.source_group_id,{parent_subcircuit_id:i})}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=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:n.autorouter?{trace_clearance:n.autorouter.traceClearance}:void 0});this.pcb_group_id=i.pcb_group_id;for(let r of this.children)t.pcb_component.update(r.pcb_component_id,{pcb_group_id:i.pcb_group_id})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,n=this._parsedProps,i=Ox(this.children);if(this.pcb_group_id){let r=i.width,o=i.height,s=(i.minX+i.maxX)/2,a=(i.minY+i.maxY)/2;if(this.isSubcircuit){let{padLeft:u,padRight:h,padTop:f,padBottom:_}=this._resolvePcbPadding();r+=u+h,o+=f+_,s+=(h-u)/2,a+=(f-_)/2}let l=this._parsedProps.pcbX!==void 0||this._parsedProps.pcbY!==void 0?t.pcb_group.get(this.pcb_group_id)?.center??{x:s,y:a}:{x:s,y:a};t.pcb_group.update(this.pcb_group_id,{width:Number(n.width??r),height:Number(n.height??o),center:l})}}getNextAvailableName(t){var n,i;return(n=this.unnamedElementCounter)[i=t.lowercaseComponentName]??(n[i]=1),`unnamed_${t.lowercaseComponentName}${this.unnamedElementCounter[t.lowercaseComponentName]++}`}_resolvePcbPadding(){let t=this._parsedProps,n=t.pcbLayout,i=h=>{let f=n?.[h],_=t[h];if(typeof f=="number")return f;if(typeof _=="number")return _},r=i("padding")??0,o=i("paddingX"),s=i("paddingY"),a=i("paddingLeft")??o??r,c=i("paddingRight")??o??r,l=i("paddingTop")??s??r,u=i("paddingBottom")??s??r;return{padLeft:a,padRight:c,padTop:l,padBottom:u}}doInitialCreateTraceHintsFromProps(){let{_parsedProps:t}=this,{db:n}=this.root,i=t;if(!this.isSubcircuit)return;let r=i.manualEdits?.manual_trace_hints;if(r)for(let o of r)this.add(new fI({for:o.pcb_port_selector,offsets:o.offsets}))}doInitialSourceAddConnectivityMapKey(){Bvt(this)}_areChildSubcircuitsRouted(){let t=this.selectAll("group").filter(n=>n.isSubcircuit);for(let n of t)if(n._shouldRouteAsync()&&!n._asyncAutoroutingResult)return!1;return!0}_shouldRouteAsync(){let t=this._getAutorouterConfig();return t.groupMode==="sequential-trace"?!1:!!(t.local&&t.groupMode==="subcircuit"||!t.local)}_hasTracesToRoute(){let t=(0,Zp.default)("tscircuit:core:_hasTracesToRoute"),n=this.selectAll("trace");return t(`[${this.getString()}] has ${n.length} traces to route`),n.length>0}async _runEffectMakeHttpAutoroutingRequest(){let{db:t}=this.root,n=(0,Zp.default)("tscircuit:core:_runEffectMakeHttpAutoroutingRequest"),i=this._parsedProps,r=this._getAutorouterConfig(),o=r.serverUrl,s=r.serverMode,a=(u,h)=>(n("fetching",u),h.headers&&(h.headers["Tscircuit-Core-Version"]=this.root?.getCoreVersion()),fetch(u,h)),c=this.root.db.toArray().filter(u=>u.type.startsWith("source_")||u.type.startsWith("pcb_"));if(s==="solve-endpoint"){if(this.props.autorouter?.inputFormat==="simplified"){let{autorouting_result:h}=await a(`${o}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_simple_route_json:iI({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(f=>f.json());this._asyncAutoroutingResult=h,this._markDirty("PcbTraceRender");return}let{autorouting_result:u}=await a(`${o}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_circuit_json:c,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(h=>h.json());this._asyncAutoroutingResult=u,this._markDirty("PcbTraceRender");return}let{autorouting_job:l}=await a(`${o}/autorouting/jobs/create`,{method:"POST",body:JSON.stringify({input_circuit_json:c,provider:"freerouting",autostart:!0,display_name:this.root?.name,subcircuit_id:this.subcircuit_id,server_cache_enabled:r.serverCacheEnabled}),headers:{"Content-Type":"application/json"}}).then(u=>u.json());for(;;){let{autorouting_job:u}=await a(`${o}/autorouting/jobs/get`,{method:"POST",body:JSON.stringify({autorouting_job_id:l.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(h=>h.json());if(u.is_finished){let{autorouting_job_output:h}=await a(`${o}/autorouting/jobs/get_output`,{method:"POST",body:JSON.stringify({autorouting_job_id:l.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(f=>f.json());this._asyncAutoroutingResult={output_pcb_traces:h.output_pcb_traces},this._markDirty("PcbTraceRender");break}if(u.has_error){let h=new Cf(`Autorouting job failed: ${JSON.stringify(u.error)}`);throw t.pcb_autorouting_error.insert({pcb_error_id:l.autorouting_job_id,error_type:"pcb_autorouting_error",message:h.message}),h}await new Promise(h=>setTimeout(h,100))}}async _runLocalAutorouting(){let{db:t}=this.root,n=this._parsedProps,i=(0,Zp.default)("tscircuit:core:_runLocalAutorouting");i(`[${this.getString()}] starting local autorouting`);let r=this._getAutorouterConfig(),{simpleRouteJson:o}=iI({db:t,minTraceWidth:this.props.autorouter?.minTraceWidth??.15,subcircuit_id:this.subcircuit_id});if(i.enabled){let c=Q5(o);c.title=`autorouting-${this.props.name}`,global.debugGraphics?.push(c)}this.root?.emit("autorouting:start",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),simpleRouteJson:o});let s;r.algorithmFn?s=await r.algorithmFn(o):s=new Avt(o,{capacityDepth:this.props.autorouter?.capacityDepth,targetMinCapacity:this.props.autorouter?.targetMinCapacity});let a=new Promise((c,l)=>{s.on("complete",u=>{i(`[${this.getString()}] local autorouting complete`),c(u.traces)}),s.on("error",u=>{i(`[${this.getString()}] local autorouting error: ${u.error.message}`),l(u.error)})});s.on("progress",c=>{this.root?.emit("autorouting:progress",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),...c})}),s.start();try{let c=await a;this._asyncAutoroutingResult={output_pcb_traces:c},this._markDirty("PcbTraceRender")}catch(c){let{db:l}=this.root;throw l.pcb_autorouting_error.insert({pcb_error_id:`pcb_autorouter_error_subcircuit_${this.subcircuit_id}`,error_type:"pcb_autorouting_error",message:c instanceof Error?c.message:String(c)}),this.root?.emit("autorouting:error",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),error:{message:c instanceof Error?c.message:String(c)},simpleRouteJson:o}),c}finally{s.stop()}}_startAsyncAutorouting(){this._hasStartedAsyncAutorouting||(this._hasStartedAsyncAutorouting=!0,this._getAutorouterConfig().local?this._queueAsyncEffect("capacity-mesh-autorouting",async()=>this._runLocalAutorouting()):this._queueAsyncEffect("make-http-autorouting-request",async()=>this._runEffectMakeHttpAutoroutingRequest()))}doInitialPcbTraceRender(){let t=(0,Zp.default)("tscircuit:core:doInitialPcbTraceRender");if(this.isSubcircuit&&!this.root?.pcbDisabled&&!this.getInheritedProperty("routingDisabled")&&!this._shouldUseTraceByTraceRouting()){if(!this._areChildSubcircuitsRouted()){t(`[${this.getString()}] child subcircuits are not routed, skipping async autorouting until subcircuits routed`);return}t(`[${this.getString()}] no child subcircuits to wait for, initiating async routing`),this._hasTracesToRoute()&&this._startAsyncAutorouting()}}doInitialSchematicTraceRender(){bwt(this)}updatePcbTraceRender(){let t=(0,Zp.default)("tscircuit:core:updatePcbTraceRender");if(t(`[${this.getString()}] updating...`),!this.isSubcircuit)return;if(this._shouldRouteAsync()&&this._hasTracesToRoute()&&!this._hasStartedAsyncAutorouting){this._areChildSubcircuitsRouted()&&(t(`[${this.getString()}] child subcircuits are now routed, starting async autorouting`),this._startAsyncAutorouting());return}if(!this._asyncAutoroutingResult||this._shouldUseTraceByTraceRouting())return;let{db:n}=this.root;if(this._asyncAutoroutingResult.output_simple_route_json){t(`[${this.getString()}] updating PCB traces from simple route json (${this._asyncAutoroutingResult.output_simple_route_json.traces?.length} traces)`),this._updatePcbTraceRenderFromSimpleRouteJson();return}if(this._asyncAutoroutingResult.output_pcb_traces){t(`[${this.getString()}] updating PCB traces from ${this._asyncAutoroutingResult.output_pcb_traces.length} traces`),this._updatePcbTraceRenderFromPcbTraces();return}}_updatePcbTraceRenderFromSimpleRouteJson(){let{db:t}=this.root,{traces:n}=this._asyncAutoroutingResult.output_simple_route_json;if(n)for(let i of n){let r=t.pcb_trace.insert({subcircuit_id:this.subcircuit_id,route:i.route})}}_updatePcbTraceRenderFromPcbTraces(){let{output_pcb_traces:t}=this._asyncAutoroutingResult;if(!t)return;let{db:n}=this.root;for(let i of t)if(i.type==="pcb_trace"){if(i.subcircuit_id=this.subcircuit_id,i.connection_name){let r=i.connection_name;i.source_trace_id=r}n.pcb_trace.insert(i)}for(let i of t)if(i.type!=="pcb_via"&&i.type==="pcb_trace")for(let r of i.route)r.route_type==="via"&&n.pcb_via.insert({pcb_trace_id:i.pcb_trace_id,x:r.x,y:r.y,hole_diameter:.3,outer_diameter:.6,layers:[r.from_layer,r.to_layer],from_layer:r.from_layer,to_layer:r.to_layer})}doInitialSchematicComponentRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=t.schematic_group.insert({is_subcircuit:this.isSubcircuit,subcircuit_id:this.subcircuit_id,name:this.name,center:this._getGlobalSchematicPositionBeforeLayout(),width:0,height:0,schematic_component_ids:[],source_group_id:this.source_group_id});this.schematic_group_id=i.schematic_group_id;for(let r of this.children)r.schematic_component_id&&t.schematic_component.update(r.schematic_component_id,{schematic_group_id:i.schematic_group_id})}_getSchematicLayoutMode(){let t=this._parsedProps;if(t.schLayout?.layoutMode==="none"||t.schLayout?.layoutMode==="relative")return"relative";if(t.schLayout?.matchAdapt)return"match-adapt";if(t.schLayout?.flex)return"flex";if(t.schLayout?.grid)return"grid";if(t.schMatchAdapt)return"match-adapt";if(t.schFlex)return"flex";if(t.schGrid)return"grid";if(t.matchAdapt)return"match-adapt";if(t.flex)return"flex";if(t.grid)return"grid";if(t.relative||t.schRelative)return"relative";let n=this.children.some(r=>{let o=r._parsedProps;return o?.schX!==void 0||o?.schY!==void 0}),i=(t.manualEdits?.schematic_placements?.length??0)>0;return!n&&!i?"match-adapt":"relative"}doInitialSchematicLayout(){let t=this._getSchematicLayoutMode();t==="match-adapt"&&this._doInitialSchematicLayoutMatchpack(),t==="grid"&&this._doInitialSchematicLayoutGrid(),t==="flex"&&this._doInitialSchematicLayoutFlex(),this._insertSchematicBorder()}_doInitialSchematicLayoutMatchAdapt(){zvt(this)}_doInitialSchematicLayoutMatchpack(){$vt(this)}_doInitialSchematicLayoutGrid(){jvt(this)}_doInitialSchematicLayoutFlex(){Yvt(this)}_getPcbLayoutMode(){let t=this._parsedProps;if(t.pcbRelative)return"none";if(t.pcbLayout?.matchAdapt)return"match-adapt";if(t.pcbLayout?.flex)return"flex";if(t.pcbLayout?.grid)return"grid";if(t.pcbLayout?.pack)return"pack";if(t.pcbFlex)return"flex";if(t.pcbGrid)return"grid";if(t.pcbPack||t.pack)return"pack";if(t.matchAdapt)return"match-adapt";if(t.flex)return"flex";if(t.grid)return"grid";let n=t.pcbX!==void 0||t.pcbY!==void 0,i=(t.manualEdits?.pcb_placements?.length??0)>0;if(this.children.some(s=>{let a=s._parsedProps;return a?.pcbX!==void 0||a?.pcbY!==void 0}))return"none";let o=this.children.reduce((s,a)=>{let c=a._parsedProps,l=c?.pcbX!==void 0||c?.pcbY!==void 0;return s+(l?0:1)},0);return!n&&!i&&o>1?"pack":"none"}doInitialPcbLayout(){let t=this._getPcbLayoutMode();t==="grid"?this._doInitialPcbLayoutGrid():t==="pack"?this._doInitialPcbLayoutPack():t==="flex"&&this._doInitialPcbLayoutFlex()}_doInitialPcbLayoutGrid(){Xvt(this)}_doInitialPcbLayoutPack(){iwt(this)}_doInitialPcbLayoutFlex(){rwt(this)}_insertSchematicBorder(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,n=this._parsedProps;if(!n.border)return;let i=typeof n.schWidth=="number"?n.schWidth:void 0,r=typeof n.schHeight=="number"?n.schHeight:void 0,o=typeof n.schPadding=="number"?n.schPadding:0,s=typeof n.schPaddingLeft=="number"?n.schPaddingLeft:o,a=typeof n.schPaddingRight=="number"?n.schPaddingRight:o,c=typeof n.schPaddingTop=="number"?n.schPaddingTop:o,l=typeof n.schPaddingBottom=="number"?n.schPaddingBottom:o,u=this.schematic_group_id?t.schematic_group.get(this.schematic_group_id):null;if(u&&(i===void 0&&typeof u.width=="number"&&(i=u.width),r===void 0&&typeof u.height=="number"&&(r=u.height)),i===void 0||r===void 0)return;let h=u?.center??this._getGlobalSchematicPositionBeforeLayout(),f=h.x-i/2-s,_=h.y-r/2-l,y=i+s+a,x=r+c+l;t.schematic_box.insert({width:y,height:x,x:f,y:_,is_dashed:n.border?.dashed??!1})}_determineSideFromPosition(t,n){if(!t.center||!n.center)return"left";let i=t.center.x-n.center.x,r=t.center.y-n.center.y;return Math.abs(i)>Math.abs(r)?i>0?"right":"left":r>0?"bottom":"top"}_calculateSchematicBounds(t){if(t.length===0)return{minX:0,maxX:0,minY:0,maxY:0};let n=1/0,i=-1/0,r=1/0,o=-1/0;for(let a of t)n=Math.min(n,a.centerX),i=Math.max(i,a.centerX),r=Math.min(r,a.centerY),o=Math.max(o,a.centerY);let s=2;return{minX:n-s,maxX:i+s,minY:r-s,maxY:o+s}}_getAutorouterConfig(){let t=this._parsedProps.autorouter||this.getInheritedProperty("autorouter");return Qvt(t)}_getSubcircuitLayerCount(){let t=this.getInheritedProperty("layers");return typeof t=="number"?t:2}_shouldUseTraceByTraceRouting(){return this._getAutorouterConfig().groupMode==="sequential-trace"}doInitialPcbDesignRuleChecks(){if(this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;let{db:t}=this.root;if(this.isSubcircuit){let n=new Map;for(let i of this.children)if(!i.isSubcircuit&&i._parsedProps.name){let r=n.get(i._parsedProps.name)||[];r.push(i),n.set(i._parsedProps.name,r)}for(let[i,r]of n.entries())r.length>1&&t.pcb_trace_error.insert({error_type:"pcb_trace_error",message:`Multiple components found with name "${i}" in subcircuit "${this.name||"unnamed"}". Component names must be unique within a subcircuit.`,source_trace_id:"",pcb_trace_id:"",pcb_component_ids:r.map(o=>o.pcb_component_id).filter(Boolean),pcb_port_ids:[]})}}doInitialSchematicReplaceNetLabelsWithSymbols(){if(this.root?.schematicDisabled||!this.isSubcircuit)return;let{db:t}=this.root,n=t;for(let i of n.schematic_net_label.list()){let r=n.source_net.get(i.source_net_id),o=i.text||r?.name||"";if(i.anchor_side==="top"&&/^gnd/i.test(o)){n.schematic_net_label.update(i.schematic_net_label_id,{symbol_name:"rail_down"});continue}i.anchor_side==="bottom"&&/^v/i.test(o)&&n.schematic_net_label.update(i.schematic_net_label_id,{symbol_name:"rail_up"})}}_getMinimumFlexContainerSize(){return super._getMinimumFlexContainerSize()}_repositionOnPcb(t){return super._repositionOnPcb(t)}},hY=(e,t,n)=>{let i=Math.min(n,e/2,t/2),r=Math.max(1,Math.ceil(Math.PI/2*i)),o=Math.PI/2/r,s=e/2,a=t/2,c=[];c.push({x:-s+i,y:-a}),c.push({x:s-i,y:-a});for(let l=1;l<=r;l++){let u=-Math.PI/2+l*o;c.push({x:s-i+i*Math.cos(u),y:-a+i+i*Math.sin(u)})}c.push({x:s,y:a-i});for(let l=1;l<=r;l++){let u=0+l*o;c.push({x:s-i+i*Math.cos(u),y:a-i+i*Math.sin(u)})}c.push({x:-s+i,y:a});for(let l=1;l<=r;l++){let u=Math.PI/2+l*o;c.push({x:-s+i+i*Math.cos(u),y:a-i+i*Math.sin(u)})}c.push({x:-s,y:-a+i});for(let l=1;l<=r;l++){let u=Math.PI+l*o;c.push({x:-s+i+i*Math.cos(u),y:-a+i+i*Math.sin(u)})}return c},DY=class extends th{constructor(){super(...arguments);T(this,"pcb_board_id",null);T(this,"_drcChecksComplete",!1);T(this,"_connectedSchematicPortPairs",new Set)}get isSubcircuit(){return!0}get isGroup(){return!0}get config(){return{componentName:"Board",zodProps:S5}}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:n}=this;if(n.width&&n.height)return;let i=1/0,r=1/0,o=-1/0,s=-1/0,a=AY(t,this.subcircuit_id),c=new Set([this.subcircuit_id,...a]),l=t.pcb_component.list().filter(R=>R.subcircuit_id&&c.has(R.subcircuit_id)),u=t.pcb_group.list().filter(R=>R.subcircuit_id&&c.has(R.subcircuit_id)),h=!1,f=(R,I,k)=>{I===0||k===0||(h=!0,i=Math.min(i,R.x-I/2),r=Math.min(r,R.y-k/2),o=Math.max(o,R.x+I/2),s=Math.max(s,R.y+k/2))};for(let R of l)f(R.center,R.width,R.height);for(let R of u)f(R.center,R.width,R.height);let _=2,y=h?o-i+_*2:0,x=h?s-r+_*2:0,v={x:h?(i+o)/2+(n.outlineOffsetX??0):n.outlineOffsetX??0,y:h?(r+s)/2+(n.outlineOffsetY??0):n.outlineOffsetY??0},w=n.width??y,S=n.height??x,C=n.outline;!C&&n.borderRadius!=null&&w>0&&S>0&&(C=hY(w,S,n.borderRadius));let E={width:w,height:S,center:v};C&&(E.outline=C.map(R=>({x:R.x+(n.outlineOffsetX??0),y:R.y+(n.outlineOffsetY??0)}))),t.pcb_board.update(this.pcb_board_id,E)}updatePcbBoardAutoSize(){this.doInitialPcbBoardAutoSize()}_addBoardInformationToSilkscreen(){let t=this.root?.platform;if(!t?.printBoardInformationToSilkscreen)return;let n=this.root.db.pcb_board.get(this.pcb_board_id);if(!n)return;let i=[];if(t.projectName&&i.push(t.projectName),t.version&&i.push(`v${t.version}`),t.url&&i.push(t.url),i.length===0)return;let r=i.join(`
231
+ `),a={x:n.center.x+n.width/2-.25,y:n.center.y-n.height/2+1};this.root.db.pcb_silkscreen_text.insert({pcb_component_id:this.pcb_board_id,layer:"top",font:"tscircuit2024",font_size:.45,text:r,ccw_rotation:0,anchor_alignment:"bottom_right",anchor_position:a})}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=n.width??0,r=n.height??0,o={x:(n.pcbX??0)+(n.outlineOffsetX??0),y:(n.pcbY??0)+(n.outlineOffsetY??0)};if(n.outline){let c=n.outline.map(y=>y.x),l=n.outline.map(y=>y.y),u=Math.min(...c),h=Math.max(...c),f=Math.min(...l),_=Math.max(...l);i=h-u,r=_-f,o={x:(u+h)/2+(n.outlineOffsetX??0),y:(f+_)/2+(n.outlineOffsetY??0)}}let s=n.outline;!s&&n.borderRadius!=null&&i>0&&r>0&&(s=hY(i,r,n.borderRadius));let a=t.pcb_board.insert({center:o,thickness:this.boardThickness,num_layers:this.allLayers.length,width:i,height:r,outline:s?.map(c=>({x:c.x+(n.outlineOffsetX??0),y:c.y+(n.outlineOffsetY??0)})),material:n.material});this.pcb_board_id=a.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 vi()}doInitialPcbDesignRuleChecks(){this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled")||super.doInitialPcbDesignRuleChecks()}updatePcbDesignRuleChecks(){if(this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;let{db:t}=this.root;if(!this._areChildSubcircuitsRouted()||this._drcChecksComplete)return;this._drcChecksComplete=!0;let n=HB(t.toArray());for(let o of n)t.pcb_trace_error.insert(o);let i=VB(t.toArray());for(let o of i)t.pcb_port_not_connected_error.insert(o);let r=qB(t.toArray());for(let o of r)t.pcb_component_outside_board_error.insert(o)}_emitRenderLifecycleEvent(t,n){super._emitRenderLifecycleEvent(t,n),n==="start"&&this.root?.emit("board:renderPhaseStarted",{renderId:this._renderId,phase:t})}},vwt=new Proxy({},{get:(e,t)=>t}),zs=vwt,Lx="rgba(132, 0, 0)",Fx=.12,$Y=class extends In{constructor(){super(...arguments);T(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Capacitor",schematicSymbolName:this.props.polarized?"capacitor_polarized":this.props.symbolName??"capacitor",zodProps:SL,sourceFtype:zs.simple_capacitor}}initPorts(){typeof this.props.footprint=="string"?super.initPorts({additionalAliases:{pin1:["anode","pos"],pin2:["cathode","neg"]}}):super.initPorts()}_getSchematicSymbolDisplayValue(){let t=this.props.capacitance,n=typeof t=="string"?t:`${qn(this._parsedProps.capacitance)}F`;return this._parsedProps.schShowRatings&&this._parsedProps.maxVoltageRating?`${n}/${qn(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 yo({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.decouplingFor})),this.add(new yo({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.decouplingTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_capacitor",name:this.name,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,capacitance:n.capacitance,max_voltage_rating:n.maxVoltageRating,max_decoupling_trace_length:n.maxDecouplingTraceLength,display_capacitance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!n.polarized});this.source_component_id=i.source_component_id}},zx=class extends In{constructor(t){super(t);T(this,"schematicBoxDimensions",null)}get config(){return{componentName:"Chip",zodProps:lp,shouldRenderAsSchematicBox:!0}}initPorts(t={}){super.initPorts(t);let{_parsedProps:n}=this;if(n.externallyConnectedPins){let i=new Set;for(let[r,o]of n.externallyConnectedPins)i.add(r),i.add(o);for(let r of i)if(!this.children.find(s=>s instanceof Ei&&s.isMatchingAnyOf([r]))){let s=r.match(/^pin(\d+)$/);if(s){let a=parseInt(s[1]);this.add(new Ei({pinNumber:a,aliases:[r]}))}else this.add(new Ei({name:r,aliases:[r]}))}}}doInitialSchematicComponentRender(){let{_parsedProps:t}=this;t?.noSchematicRepresentation!==!0&&super.doInitialSchematicComponentRender()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:n.manufacturerPartNumber,supplier_part_numbers:n.supplierPartNumbers});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=t.pcb_component.insert({center:{x:n.pcbX??0,y:n.pcbY??0},width:2,height:3,layer:n.layer??"top",rotation:n.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:n.doNotPlace??!1,obstructs_within_bounds:n.obstructsWithinBounds??!0});this.pcb_component_id=i.pcb_component_id}doInitialCreateTracesFromProps(){let{_parsedProps:t}=this;if(t.externallyConnectedPins)for(let[n,i]of t.externallyConnectedPins)this.add(new yo({from:`${this.getSubcircuitSelector()} > port.${n}`,to:`${this.getSubcircuitSelector()} > port.${i}`}));this._createTracesFromConnectionsProp()}doInitialSimulationRender(){let{db:t}=this.root,{pinAttributes:n}=this.props;if(!n)return;let i=null,r=null,o,s=this.selectAll("port");for(let h of s)for(let f of h.getNameAndAliases())if(n[f]){let _=n[f];_.providesPower&&(i=h,o=_.providesVoltage),_.providesGround&&(r=h)}if(!i||!r||o===void 0)return;let a=t.source_port.get(i.source_port_id);if(!a?.subcircuit_connectivity_map_key)return;let c=t.source_port.get(r.source_port_id);if(!c?.subcircuit_connectivity_map_key)return;let l=t.source_net.getWhere({subcircuit_connectivity_map_key:a.subcircuit_connectivity_map_key}),u=t.source_net.getWhere({subcircuit_connectivity_map_key:c.subcircuit_connectivity_map_key});!l||!u||t.simulation_voltage_source.insert({type:"simulation_voltage_source",positive_source_port_id:i.source_port_id,positive_source_net_id:l.source_net_id,negative_source_port_id:r.source_port_id,negative_source_net_id:u.source_net_id,voltage:o})}},BY=class extends zx{constructor(e){super(e)}get config(){return{...super.config,componentName:"Pinout",zodProps:fL}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_pinout",name:this.name,manufacturer_part_number:t.manufacturerPartNumber,supplier_part_numbers:t.supplierPartNumbers});this.source_component_id=n.source_component_id}},jY=class extends In{constructor(){super(...arguments);T(this,"pos",this.portMap.pin1);T(this,"anode",this.portMap.pin1);T(this,"neg",this.portMap.pin2);T(this,"cathode",this.portMap.pin2)}get config(){let t={schottky:"schottky_diode",avalanche:"avalanche_diode",zener:"zener_diode",photodiode:"photodiode"},n=this.props.schottky?"schottky":this.props.avalanche?"avalanche":this.props.zener?"zener":this.props.photo?"photodiode":null;return{schematicSymbolName:n?t[n]:this.props.symbolName??"diode",componentName:"Diode",zodProps:$L,sourceFtype:"simple_diode"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_diode",name:this.name,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},YY=class extends In{get config(){return{componentName:"fuse",schematicSymbolName:this.props.symbolName??"fuse",zodProps:_L,sourceFtype:zs.simple_fuse}}_getSchematicSymbolDisplayValue(){let e=this._parsedProps.currentRating,t=this._parsedProps.voltageRating,n=typeof e=="string"?parseFloat(e):e,i=typeof t=="string"?parseFloat(t):t;return`${qn(n)}A / ${qn(i)}V`}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=typeof t.currentRating=="string"?parseFloat(t.currentRating):t.currentRating,i=typeof t.voltageRating=="string"?parseFloat(t.voltageRating):t.voltageRating,r=e.source_component.insert({name:this.name,ftype:zs.simple_fuse,current_rating_amps:n,voltage_rating_volts:i,display_current_rating:`${qn(n)}A`,display_voltage_rating:`${qn(i)}V`});this.source_component_id=r.source_component_id}},XY=class extends In{constructor(){super(...arguments);T(this,"schematicDimensions",null)}get config(){return{schematicSymbolName:void 0,componentName:"Jumper",zodProps:P5,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let t=super._getSchematicPortArrangement();if(t&&Object.keys(t).length>0)return t;let n=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length),i=this._parsedProps.schDirection??"right";return{leftSize:i==="left"?n:0,rightSize:i==="right"?n:0}}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:n.manufacturerPartNumber,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=t.pcb_component.insert({center:{x:n.pcbX??0,y:n.pcbY??0},width:2,height:3,layer:n.layer??"top",rotation:n.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:n.doNotPlace??!1,obstructs_within_bounds:n.obstructsWithinBounds??!0});this.pcb_component_id=i.pcb_component_id}doInitialPcbTraceRender(){let{db:t}=this.root,n=t.pcb_port.list({pcb_component_id:this.pcb_component_id}),i={};for(let s=0;s<n.length;s++){let a=n[s],c=t.source_port.get(a.source_port_id),l="";if(typeof c?.pin_number=="number")l=c.pin_number.toString();else if(Array.isArray(c?.port_hints)){let u=c.port_hints.find(h=>/^(pin)?\d+$/.test(h));u&&(/^pin\d+$/.test(u)?l=u.replace(/^pin/,""):l=u)}i[l]=a.pcb_port_id}let r=t.pcb_trace.list({pcb_component_id:this.pcb_component_id}),o=s=>{if(s&&typeof s=="string"&&s.startsWith("{PIN")){let a=s.replace("{PIN","").replace("}","");return i[a]||s}return s};for(let s of r)if(s.route)for(let a of s.route)a.route_type==="wire"&&(a.start_pcb_port_id=o(a.start_pcb_port_id),a.end_pcb_port_id=o(a.end_pcb_port_id))}},VY=class extends In{constructor(){super(...arguments);T(this,"schematicDimensions",null)}_getPinNumberFromBridgedPinName(t){return this.selectOne(`port.${t}`,{type:"port"})?._parsedProps.pinNumber??null}get defaultInternallyConnectedPinNames(){if(this._parsedProps.bridged){let t=this.children.filter(n=>n.componentName==="Port").map(n=>n.name);return t.length>0?[t]:[]}return this._parsedProps.bridgedPins??[]}get config(){let t=this._parsedProps??this.props,n=t.pinCount;if(t.pinCount==null&&!t.footprint&&(n=2),t.pinCount==null){let o=(t.bridgedPins??[]).flat().map(l=>this._getPinNumberFromBridgedPinName(l)).filter(l=>l!==null),s=o.length>0?Math.max(...o):0,a=t.pinLabels?Object.keys(t.pinLabels).length:0,c=Math.max(s,a);(c===2||c===3)&&(n=c),n==null&&t.footprint&&[2,3].includes(this.getPortsFromFootprint().length)&&(n=this.getPortsFromFootprint().length)}let i="";n?i+=`solderjumper${n}`:i="solderjumper";let r=[];return Array.isArray(t.bridgedPins)&&t.bridgedPins.length>0?r=Array.from(new Set(t.bridgedPins.flat().map(o=>this._getPinNumberFromBridgedPinName(o)).filter(o=>o!==null))).sort((o,s)=>o-s):t.bridged&&n&&(r=Array.from({length:n},(o,s)=>s+1)),r.length>0&&(i+=`_bridged${r.join("")}`),{schematicSymbolName:t.symbolName??i,componentName:"SolderJumper",zodProps:mL,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let t=super._getSchematicPortArrangement();if(t&&Object.keys(t).length>0)return t;let n=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length);n==null&&!this._parsedProps.footprint&&(n=2);let i=this._parsedProps.schDirection??"right";return{leftSize:i==="left"?n:0,rightSize:i==="right"?n:0}}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:n.manufacturerPartNumber,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=t.pcb_component.insert({center:{x:n.pcbX??0,y:n.pcbY??0},width:2,height:3,layer:n.layer??"top",rotation:n.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:n.doNotPlace??!1,obstructs_within_bounds:n.obstructsWithinBounds??!0});this.pcb_component_id=i.pcb_component_id}doInitialPcbTraceRender(){let{db:t}=this.root,n=t.pcb_port.list({pcb_component_id:this.pcb_component_id}),i={};for(let s=0;s<n.length;s++){let a=n[s],c=t.source_port.get(a.source_port_id),l="";if(typeof c?.pin_number=="number")l=c.pin_number.toString();else if(Array.isArray(c?.port_hints)){let u=c.port_hints.find(h=>/^(pin)?\d+$/.test(h));u&&(/^pin\d+$/.test(u)?l=u.replace(/^pin/,""):l=u)}i[l]=a.pcb_port_id}let r=t.pcb_trace.list({pcb_component_id:this.pcb_component_id}),o=s=>{if(s&&typeof s=="string"&&s.startsWith("{PIN")){let a=s.replace("{PIN","").replace("}","");return i[a]||s}return s};for(let s of r)if(s.route)for(let a of s.route)a.route_type==="wire"&&(a.start_pcb_port_id=o(a.start_pcb_port_id),a.end_pcb_port_id=o(a.end_pcb_port_id))}},HY=class extends In{constructor(){super(...arguments);T(this,"pos",this.portMap.pin1);T(this,"anode",this.portMap.pin1);T(this,"neg",this.portMap.pin2);T(this,"cathode",this.portMap.pin2)}get config(){let t={laser:"laser_diode"},n=this.props.laser?"laser":null;return{schematicSymbolName:n?t[n]:this.props.symbolName??"led",componentName:"Led",zodProps:jL,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:n}=this,i=t.source_component.insert({ftype:"simple_led",name:this.name,wave_length:n.wavelength,color:n.color,symbol_display_value:this._getSchematicSymbolDisplayValue(),manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},GY=class extends In{constructor(){super(...arguments);T(this,"pos",this.portMap.pin1);T(this,"positive",this.portMap.pin1);T(this,"neg",this.portMap.pin2);T(this,"negative",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"power_factor_meter_horz",componentName:"PowerSource",zodProps:QL,sourceFtype:"simple_power_source"}}initPorts(){this.add(new Ei({name:"pin1",pinNumber:1,aliases:["positive","pos"]})),this.add(new Ei({name:"pin2",pinNumber:2,aliases:["negative","neg"]}))}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_power_source",name:this.name,voltage:n.voltage,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},wwt=Fn.extend({voltage:Qn.optional(),frequency:po.optional(),peakToPeakVoltage:Qn.optional(),waveShape:p.enum(["sinewave","square","triangle","sawtooth"]).optional(),phase:Fe.optional(),dutyCycle:p.number().optional()}),UY=class extends In{constructor(){super(...arguments);T(this,"terminal1",this.portMap.terminal1);T(this,"terminal2",this.portMap.terminal2)}get config(){return{componentName:"VoltageSource",schematicSymbolName:this.props.waveShape==="square"?"square_wave":"ac_voltmeter",zodProps:wwt,sourceFtype:"simple_voltage_source"}}runRenderPhaseForChildren(t){if(!t.startsWith("Pcb"))for(let n of this.children)n.runRenderPhaseForChildren(t),n.runRenderPhase(t)}doInitialPcbComponentRender(){}initPorts(){super.initPorts({additionalAliases:{pin1:["terminal1"],pin2:["terminal2"]}})}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_voltage_source",name:this.name,voltage:n.voltage,frequency:n.frequency,peak_to_peak_voltage:n.peakToPeakVoltage,wave_shape:n.waveShape,phase:n.phase,duty_cycle:n.dutyCycle,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialSimulationRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=this.portMap.terminal1,r=this.portMap.terminal2;t.simulation_voltage_source.insert({type:"simulation_voltage_source",is_dc_source:!1,terminal1_source_port_id:i.source_port_id,terminal2_source_port_id:r.source_port_id,voltage:n.voltage,frequency:n.frequency,peak_to_peak_voltage:n.peakToPeakVoltage,wave_shape:n.waveShape,phase:n.phase,duty_cycle:n.dutyCycle})}},qY=class extends In{constructor(){super(...arguments);T(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Resistor",schematicSymbolName:this.props.symbolName??"boxresistor",zodProps:gL,sourceFtype:"simple_resistor"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return`${qn(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 yo({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pullupFor})),this.add(new yo({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pullupTo}))),this.props.pulldownFor&&this.props.pulldownTo&&(this.add(new yo({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pulldownFor})),this.add(new yo({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pulldownTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_resistor",name:this.name,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,resistance:n.resistance,display_resistance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}},Swt=["leftedge","rightedge","topedge","bottomedge","center"],WY=class extends Ie{get config(){return{componentName:"Constraint",zodProps:TL}}constructor(e){if(super(e),("xdist"in e||"ydist"in e)&&!("edgeToEdge"in e)&&!("centerToCenter"in e))throw new Error(`edgeToEdge, centerToCenter must be set for xDist or yDist for ${this}`);if("for"in e&&e.for.length<2)throw new Error(`"for" must have at least two selectors for ${this}`)}_getAllReferencedComponents(){let e=[],t=this.getPrimitiveContainer();function n(i){let r=i.split(" ").pop(),o=Swt.includes(r)?r:void 0,s=o?i.replace(` ${o}`,""):i,a=t.selectOne(s,{pcbPrimitive:!0});a&&e.push({selector:i,component:a,componentSelector:s,edge:o})}for(let i of["left","right","top","bottom"])i in this._parsedProps&&n(this._parsedProps[i]);if("for"in this._parsedProps)for(let i of this._parsedProps.for)n(i);return{componentsWithSelectors:e}}},ZY=class extends Ie{constructor(){super(...arguments);T(this,"fabrication_note_path_id",null)}get config(){return{componentName:"FabricationNotePath",zodProps:HL}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,n=this.getSubcircuit(),{_parsedProps:i}=this,r=i.layer??"top";if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenPath. Must be "top" or "bottom".`);let o=this._computePcbGlobalTransformBeforeLayout(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=t.pcb_fabrication_note_path.insert({pcb_component_id:s,layer:r,color:i.color,route:i.route.map(c=>{let l=kn(o,{x:c.x,y:c.y});return{...c,x:l.x,y:l.y}}),stroke_width:i.strokeWidth??.1,subcircuit_id:n?.subcircuit_id??void 0});this.fabrication_note_path_id=a.pcb_fabrication_note_path_id}},KY=class extends Ie{get config(){return{componentName:"FabricationNoteText",zodProps:VL}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,n=this.getPrimitiveContainer(),i=this.getSubcircuit();e.pcb_fabrication_note_text.insert({anchor_alignment:t.anchorAlignment,anchor_position:{x:t.pcbX??0,y:t.pcbY??0},font:t.font??"tscircuit2024",font_size:t.fontSize??1,layer:"top",color:t.color,text:t.text??"",pcb_component_id:n.pcb_component_id,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}},JY=class extends th{constructor(e){super({...e,subcircuit:!0})}},QY=class extends th{constructor(e){super({...e,subcircuit:!0})}doInitialPcbPrimitiveRender(){if(super.doInitialPcbPrimitiveRender(),this.root?.pcbDisabled)return;let{db:e}=this.root,t=this._parsedProps;if(!this.pcb_group_id)return;let n=e.pcb_group.get(this.pcb_group_id),i=t.paddingLeft??t.padding??0,r=t.paddingRight??t.padding??0,o=t.paddingTop??t.padding??0,s=t.paddingBottom??t.padding??0;e.pcb_group.update(this.pcb_group_id,{width:n.width+i+r,height:n.height+o+s,center:{x:n.center.x+(r-i)/2,y:n.center.y+(o-s)/2}})}},tX=class extends Ie{constructor(){super(...arguments);T(this,"pcb_breakout_point_id",null);T(this,"matchedPort",null);T(this,"matchedNet",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"BreakoutPoint",zodProps:qL}}_matchConnection(){let{connection:t}=this._parsedProps,n=this.getSubcircuit();n&&(this.matchedPort=n.selectOne(t,{type:"port"}),this.matchedPort||(this.matchedNet=n.selectOne(t,{type:"net"})),!this.matchedPort&&!this.matchedNet&&this.renderError(`Could not find connection target "${t}"`))}_getSourceTraceIdForPort(t){let{db:n}=this.root;return n.source_trace.list().find(r=>r.connected_source_port_ids.includes(t.source_port_id))?.source_trace_id}_getSourceNetIdForPort(t){let{db:n}=this.root;return n.source_trace.list().find(r=>r.connected_source_port_ids.includes(t.source_port_id))?.connected_source_net_ids[0]}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root;this._matchConnection();let{pcbX:n=0,pcbY:i=0}=this._parsedProps,r=this.parent?.getGroup(),o=this.getSubcircuit();if(!r||!r.pcb_group_id)return;let s=t.pcb_breakout_point.insert({pcb_group_id:r.pcb_group_id,subcircuit_id:o?.subcircuit_id??void 0,source_port_id:this.matchedPort?.source_port_id??void 0,source_trace_id:this.matchedPort?this._getSourceTraceIdForPort(this.matchedPort):void 0,source_net_id:this.matchedNet?this.matchedNet.source_net_id:this.matchedPort?this._getSourceNetIdForPort(this.matchedPort):void 0,x:n,y:i});this.pcb_breakout_point_id=s.pcb_breakout_point_id}_getPcbCircuitJsonBounds(){let{pcbX:t=0,pcbY:n=0}=this._parsedProps;return{center:{x:t,y:n},bounds:{left:t,top:n,right:t,bottom:n},width:0,height:0}}_setPositionFromLayout(t){let{db:n}=this.root;this.pcb_breakout_point_id&&n.pcb_breakout_point.update(this.pcb_breakout_point_id,{x:t.x,y:t.y})}getPcbSize(){return{width:0,height:0}}},eX=class extends Ie{constructor(){super(...arguments);T(this,"source_net_label_id")}get config(){return{componentName:"NetLabel",zodProps:OL}}_getAnchorSide(){let{_parsedProps:t}=this;if(t.anchorSide)return t.anchorSide;if(!this._resolveConnectsTo())return"right";let i=this._getGlobalSchematicPositionBeforeLayout(),r=this._getConnectedPorts();if(r.length===0)return"right";let o=r[0]._getGlobalSchematicPositionBeforeLayout(),s=o.x-i.x,a=o.y-i.y;if(Math.abs(s)>Math.abs(a)){if(s>0)return"right";if(s<0)return"left"}else{if(a>0)return"top";if(a<0)return"bottom"}return"right"}_getConnectedPorts(){let t=this._resolveConnectsTo();if(!t)return[];let n=[];for(let i of t){let r=this.getSubcircuit().selectOne(i);r&&n.push(r)}return n}computeSchematicPropsTransform(){let{_parsedProps:t}=this;if(t.schX===void 0&&t.schY===void 0){let n=this._getConnectedPorts();if(n.length>0){let i=n[0]._getGlobalSchematicPositionBeforeLayout(),r=kn(this.parent?.computeSchematicGlobalTransform?.()??vi(),{x:0,y:0});return fn(i.x-r.x,i.y-r.y)}}return super.computeSchematicPropsTransform()}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getSubcircuit().selectOne(`net.${this._getNetName()}`),o=n.anchorSide??"right",s=Ka({anchor_position:i,anchor_side:o,text:n.net}),a=t.schematic_net_label.insert({text:n.net,source_net_id:r.source_net_id,anchor_position:i,center:s,anchor_side:this._getAnchorSide()});this.source_net_label_id=a.source_net_id}_resolveConnectsTo(){let{_parsedProps:t}=this,n=t.connectsTo??t.connection;if(Array.isArray(n))return n;if(typeof n=="string")return[n]}_getNetName(){let{_parsedProps:t}=this;return t.net}doInitialCreateNetsFromProps(){let{_parsedProps:t}=this;t.net&&cI(this,[`net.${t.net}`])}doInitialCreateTracesFromNetLabels(){if(this.root?.schematicDisabled)return;let t=this._resolveConnectsTo();if(t)for(let n of t)this.add(new yo({from:n,to:`net.${this._getNetName()}`}))}doInitialSchematicTraceRender(){if(!this.root?._featureMspSchematicTraceRouting||this.root?.schematicDisabled)return;let{db:t}=this.root,n=this._resolveConnectsTo();if(!n||n.length===0)return;let i=this._getGlobalSchematicPositionBeforeLayout(),r=this._getAnchorSide(),s={left:"x-",right:"x+",top:"y+",bottom:"y-"}[r],a=this.getSubcircuit().selectOne(`net.${this._getNetName()}`);for(let c of n){let l=this.getSubcircuit().selectOne(c,{type:"port"});if(!l||!l.schematic_port_id)continue;let u=!1;if(a?.source_net_id){let w=t.source_trace.list().find(S=>S.connected_source_net_ids?.includes(a.source_net_id)&&S.connected_source_port_ids?.includes(l.source_port_id??""));if(w&&(u=t.schematic_trace.list().some(S=>S.source_trace_id===w.source_trace_id)),u)continue}let h=l._getGlobalSchematicPositionAfterLayout(),f=tI(l.facingDirection??"right")??"x+",_=Na({x:h.x,y:h.y,facingDirection:f},{x:i.x,y:i.y,facingDirection:s});if(!Array.isArray(_)||_.length<2)continue;let y=[];for(let w=0;w<_.length-1;w++)y.push({from:{x:_[w].x,y:_[w].y},to:{x:_[w+1].x,y:_[w+1].y}});let x,v;if(a?.source_net_id&&l.source_port_id){let w=t.source_trace.list().find(S=>S.connected_source_net_ids?.includes(a.source_net_id)&&S.connected_source_port_ids?.includes(l.source_port_id));x=w?.source_trace_id,v=w?.subcircuit_connectivity_map_key||t.source_net.get(a.source_net_id)?.subcircuit_connectivity_map_key}t.schematic_trace.insert({source_trace_id:x,edges:y,junctions:[],subcircuit_connectivity_map_key:v}),t.schematic_port.update(l.schematic_port_id,{is_connected:!0})}}},nX=class extends Ie{constructor(){super(...arguments);T(this,"pcb_silkscreen_circle_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenCircle",zodProps:dF}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(n.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenCircle. Must be "top" or "bottom".`);let o=this._computePcbGlobalTransformBeforeLayout(),s=this.getSubcircuit(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,c=t.pcb_silkscreen_circle.insert({pcb_component_id:a,layer:r,center:{x:n.pcbX??0,y:n.pcbY??0},radius:n.radius,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,stroke_width:n.strokeWidth??.1});this.pcb_silkscreen_circle_id=c.pcb_silkscreen_circle_id}getPcbSize(){let{_parsedProps:t}=this,n=t.radius*2;return{width:n,height:n}}},iX=class extends Ie{constructor(){super(...arguments);T(this,"pcb_silkscreen_rect_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenRect",zodProps:hF}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(n.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenRect. Must be "top" or "bottom".`);let o=this.getSubcircuit(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=t.pcb_silkscreen_rect.insert({pcb_component_id:s,layer:r,center:{x:n.pcbX??0,y:n.pcbY??0},width:n.width,height:n.height,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this?.getGroup()?.pcb_group_id??void 0,stroke_width:n.strokeWidth??.1});this.pcb_silkscreen_rect_id=a.pcb_silkscreen_rect_id}getPcbSize(){let{_parsedProps:t}=this;return{width:t.width,height:t.height}}},rX=class extends Ie{constructor(){super(...arguments);T(this,"pcb_silkscreen_line_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenLine",zodProps:pF}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(n.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenLine. Must be "top" or "bottom".`);let o=this.getSubcircuit(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=t.pcb_silkscreen_line.insert({pcb_component_id:s,layer:r,x1:n.x1,y1:n.y1,x2:n.x2,y2:n.y2,stroke_width:n.strokeWidth??.1,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:o?.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_line_id=a.pcb_silkscreen_line_id}getPcbSize(){let{_parsedProps:t}=this,n=Math.abs(t.x2-t.x1),i=Math.abs(t.y2-t.y1);return{width:n,height:i}}},oX=class extends Ie{constructor(t){super(t);T(this,"pcb_via_id",null);T(this,"matchedPort",null);T(this,"isPcbPrimitive",!0);T(this,"source_manually_placed_via_id",null);let n=this._getLayers();this._parsedProps.layers=n,this.initPorts()}get config(){return{componentName:"Via",zodProps:GL}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){let{_parsedProps:t}=this;return{width:t.outerDiameter,height:t.outerDiameter}}_getPcbCircuitJsonBounds(){let{db:t}=this.root,n=t.pcb_via.get(this.pcb_via_id),i=this.getPcbSize();return{center:{x:n.x,y:n.y},bounds:{left:n.x-i.width/2,top:n.y-i.height/2,right:n.x+i.width/2,bottom:n.y+i.height/2},width:i.width,height:i.height}}_setPositionFromLayout(t){let{db:n}=this.root;n.pcb_via.update(this.pcb_via_id,{x:t.x,y:t.y})}_getLayers(){let{fromLayer:t="top",toLayer:n="bottom"}=this._parsedProps;return t===n?[t]:[t,n]}initPorts(){let t=this._parsedProps.layers;for(let i of t){let r=new Ei({name:i,layer:i});r.registerMatch(this),this.add(r)}let n=new Ei({name:"pin1"});n.registerMatch(this),this.add(n)}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalPcbPositionBeforeLayout(),r=this.getSubcircuit(),o=t.pcb_component.insert({center:i,width:n.outerDiameter,height:n.outerDiameter,layer:n.fromLayer??"top",rotation:0,source_component_id:this.source_component_id,subcircuit_id:r?.subcircuit_id??void 0,obstructs_within_bounds:!0});this.pcb_component_id=o.pcb_component_id}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=this.getGroup(),r=this.getSubcircuit(),o=t.source_manually_placed_via.insert({source_group_id:i?.source_group_id,source_net_id:n.net??"",subcircuit_id:r?.subcircuit_id??void 0});this.source_component_id=o.source_manually_placed_via_id}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalPcbPositionBeforeLayout(),r=this.getSubcircuit(),o=t.pcb_via.insert({x:i.x,y:i.y,hole_diameter:n.holeDiameter,outer_diameter:n.outerDiameter,layers:["bottom","top"],from_layer:n.fromLayer||"bottom",to_layer:n.toLayer||"top",subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_via_id=o.pcb_via_id}},sX=class extends Ie{constructor(){super(...arguments);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"CopperPour",zodProps:ZL}}getPcbSize(){return{width:0,height:0}}doInitialPcbCopperPourRender(){this.root?.pcbDisabled||this._queueAsyncEffect("PcbCopperPourRender",async()=>{let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit().selectOne(n.connectsTo);if(!i||!i.source_net_id){this.renderError(`Net "${n.connectsTo}" not found for copper pour`);return}let r=t.pcb_board.list()[0];if(!r){this.renderError("No board found for copper pour");return}let o;r.outline&&r.outline.length>0?o=new F.Polygon(r.outline.map(_=>F.point(_.x,_.y))):o=new F.Polygon(new F.Box(r.center.x-r.width/2,r.center.y-r.height/2,r.center.x+r.width/2,r.center.y+r.height/2).toPoints());let s=ar(t.toArray()),a=hI(t.toArray(),s).filter(_=>_.layers.includes(n.layer));for(let _ of t.pcb_trace.list())if(_.route)for(let y=0;y<_.route.length-1;y++){let x=_.route[y],v=_.route[y+1];if(x.route_type!=="wire"||v.route_type!=="wire"||x.layer!==n.layer)continue;let w=x.width;if(w===0)continue;let S=Math.hypot(x.x-v.x,x.y-v.y);if(S===0)continue;let C=(x.x+v.x)/2,E=(x.y+v.y)/2,R=Math.atan2(v.y-x.y,v.x-x.x)*180/Math.PI,k=MY({center:{x:C,y:E},width:S,height:w,rotation:R});for(let M of k)a.push({type:"rect",layers:[x.layer],center:M.center,width:M.width,height:M.height,connectedTo:_.source_trace_id?[_.source_trace_id]:[],obstacle_type:"trace"})}let c=[],l=[],u=n.traceMargin??.2,h=n.padMargin??.2;for(let _ of a){if(_.connectedTo.some(w=>s.areIdsConnected(w,i.source_net_id)))continue;if(_.type==="oval"&&_.width===_.height){let w=_.width/2+h;l.push({center:_.center,radius:w});continue}if(_.type==="rect"&&_.width===_.height&&_.connectedTo.length===0){let w=_.width/2;l.push({center:_.center,radius:w});continue}let x=u,v=new F.Box(_.center.x-_.width/2-x,_.center.y-_.height/2-x,_.center.x+_.width/2+x,_.center.y+_.height/2+x);c.push(new F.Polygon(v.toPoints()))}let f=o;if(c.length>0){let _=c.reduce((y,x)=>F.BooleanOperations.unify(y,x));_&&!_.isEmpty()&&(f=F.BooleanOperations.subtract(o,_))}Array.isArray(f)||(f=[f]);for(let _ of f){let y=_.splitToIslands();for(let x of y){if(x.isEmpty())continue;let v=[...x.faces],w=v.find(I=>I.orientation()===F.ORIENTATION.CCW),S=v.filter(I=>I.orientation()===F.ORIENTATION.CW);if(!w)continue;if(!t.pcb_copper_pour){this.renderError("db.pcb_copper_pour not found. The database schema may be outdated.");return}let C=I=>I.edges.map(k=>{let M={x:k.start.x,y:k.start.y};if(k.isArc){let A=Math.tan(k.shape.sweep/4);Math.abs(A)>1e-9&&(M.bulge=A)}return M});w.reverse();let E=C(w),R=S.map(I=>(I.reverse(),{vertices:C(I)}));for(let I of l){let k=F.point(I.center.x,I.center.y);x.contains(k)&&R.push({vertices:[{x:I.center.x,y:I.center.y-I.radius,bulge:1},{x:I.center.x,y:I.center.y+I.radius,bulge:1}]})}t.pcb_copper_pour.insert({shape:"brep",layer:n.layer,brep_shape:{outer_ring:{vertices:E},inner_rings:R},source_net_id:i.source_net_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id??void 0})}}})}},aX=class extends In{get config(){return{componentName:"Battery",schematicSymbolName:this.props.symbolName??"battery",zodProps:NL,sourceFtype:"simple_power_source"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:this.name,ftype:"simple_power_source",capacity:t.capacity,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=n.source_component_id}},cX=class extends In{_getPcbRotationBeforeLayout(){let e=this.props.pcbOrientation==="vertical"?-90:0;return(super._getPcbRotationBeforeLayout()??0)+e}get config(){return{componentName:"PinHeader",zodProps:RL,shouldRenderAsSchematicBox:!0}}_getImpliedFootprintString(){let e=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:0),t=this._parsedProps.holeDiameter,n=this._parsedProps.platedDiameter,i=this._parsedProps.pitch,r=this._parsedProps.showSilkscreenPinLabels;if(e>0){let o;if(i)!t&&!n?o=`pinrow${e}_p${i}`:o=`pinrow${e}_p${i}_id${t}_od${n}`;else if(!t&&!n)o=`pinrow${e}`;else return null;return r!==!0&&(o+="_nopinlabels"),o}return null}initPorts(){let e=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:1);for(let t=1;t<=e;t++){let n=Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels[t-1]:this._parsedProps.pinLabels?.[`pin${t}`];if(n){let i=Array.isArray(n)?n[0]:n,r=Array.isArray(n)?n.slice(1):[];this.add(new Ei({pinNumber:t,name:i,aliases:[`pin${t}`,...r]}))}else this.add(new Ei({pinNumber:t,name:`pin${t}`}))}}_getSchematicPortArrangement(){let e=this._parsedProps.pinCount??1,t=this._parsedProps.schFacingDirection??this._parsedProps.facingDirection??"right",n=this._parsedProps.schPinArrangement;return t==="left"?{leftSide:{direction:n?.leftSide?.direction??"top-to-bottom",pins:n?.leftSide?.pins??Array.from({length:e},(i,r)=>`pin${r+1}`)}}:{rightSide:{direction:n?.rightSide?.direction??"top-to-bottom",pins:n?.rightSide?.pins??Array.from({length:e},(i,r)=>`pin${r+1}`)}}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_pin_header",name:this.name,supplier_part_numbers:t.supplierPartNumbers,pin_count:t.pinCount,gender:t.gender,are_pins_interchangeable:!0});this.source_component_id=n.source_component_id}};function Pwt(e){switch(e){case"two_ground_pins":return"crystal_4pin";case"ground_pin":return"resonator";case"no_ground":return"crystal";default:return"crystal"}}var lX=class extends In{get config(){return{componentName:"Resonator",schematicSymbolName:this.props.symbolName??Pwt(this.props.pinVariant),zodProps:wL,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=t.pinVariant||"no_ground",i=e.source_component.insert({ftype:"simple_resonator",name:this.name,frequency:t.frequency,load_capacitance:t.loadCapacitance,supplier_part_numbers:t.supplierPartNumbers,pin_variant:n,are_pins_interchangeable:n==="no_ground"||n==="ground_pin"});this.source_component_id=i.source_component_id}_getSchematicSymbolDisplayValue(){let e=`${qn(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${e} / ${qn(this._parsedProps.loadCapacitance)}F`:e}},uX=class extends In{constructor(){super(...arguments);T(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Inductor",schematicSymbolName:this.props.symbolName??"inductor",zodProps:DL,sourceFtype:zs.simple_inductor}}_getSchematicSymbolDisplayValue(){return`${qn(this._parsedProps.inductance)}H`}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({name:this.name,ftype:zs.simple_inductor,inductance:n.inductance,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}};function Twt(e){switch(e){case"three_pin":return"potentiometer3";case"two_pin":return"potentiometer2";default:return"potentiometer2"}}var pX=class extends In{get config(){return{componentName:"Potentiometer",schematicSymbolName:this.props.symbolName??Twt(this.props.pinVariant),zodProps:bL,shouldRenderAsSchematicBox:!1}}_getSchematicSymbolDisplayValue(){return`${qn(this._parsedProps.maxResistance)}\u03A9`}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=t.pinVariant||"two_pin",i=e.source_component.insert({ftype:"simple_potentiometer",name:this.name,max_resistance:t.maxResistance,pin_variant:n,are_pins_interchangeable:n==="two_pin"});this.source_component_id=i.source_component_id}},hX=class extends In{get config(){return{componentName:"PushButton",schematicSymbolName:this.props.symbolName??"push_button_normally_open_momentary",zodProps:LL,sourceFtype:zs.simple_push_button}}get defaultInternallyConnectedPinNames(){return[]}initPorts(){super.initPorts({pinCount:2,ignoreSymbolPorts:!0});let e=Un[this._getSchematicSymbolNameOrThrow()],t=e.ports.find(l=>l.labels.includes("1")),n=e.ports.find(l=>l.labels.includes("2")),i=this.selectAll("port"),r=i.find(l=>l.props.pinNumber===1),o=i.find(l=>l.props.pinNumber===2),s=i.find(l=>l.props.pinNumber===3),a=i.find(l=>l.props.pinNumber===4),{internallyConnectedPins:c}=this._parsedProps;r.schematicSymbolPortDef=t,(!c||c.length===0)&&(o.schematicSymbolPortDef=n);for(let[l,u]of[[2,o],[3,s],[4,a]]){let h=c?.find(([_,y])=>_===`pin${l}`||y===`pin${l}`);if(!h){u.schematicSymbolPortDef=n;break}(h?.[0]===`pin${l}`?h[1]:h?.[0])!=="pin1"&&(u.schematicSymbolPortDef=n)}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:this.name,ftype:zs.simple_push_button,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=n.source_component_id}},dX=class extends In{get config(){return{schematicSymbolName:this.props.symbolName??(this.props.pinVariant==="four_pin"?"crystal_4pin":"crystal"),componentName:"Crystal",zodProps:vL,sourceFtype:"simple_crystal"}}initPorts(){let e=this.props.pinVariant==="four_pin"?{pin1:["left1","1"],pin2:["top1","2","gnd1"],pin3:["right1","3"],pin4:["bottom1","4","gnd2"]}:{pin1:["pos","left"],pin2:["neg","right"]};super.initPorts({additionalAliases:e})}_getSchematicSymbolDisplayValue(){let e=`${qn(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${e} / ${qn(this._parsedProps.loadCapacitance)}F`:e}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:this.name,ftype:"simple_crystal",frequency:t.frequency,load_capacitance:t.loadCapacitance,pin_variant:t.pinVariant||"two_pin",are_pins_interchangeable:(t.pinVariant||"two_pin")==="two_pin"});this.source_component_id=n.source_component_id}},fX=class extends In{constructor(){super(...arguments);T(this,"emitter",this.portMap.pin1);T(this,"collector",this.portMap.pin2);T(this,"base",this.portMap.pin3)}get config(){let t=this.props.type==="npn"?"npn_bipolar_transistor":"pnp_bipolar_transistor";return{componentName:"Transistor",schematicSymbolName:this.props.symbolName??t,zodProps:FL,sourceFtype:"simple_transistor",shouldRenderAsSchematicBox:!1}}initPorts(){let t={pin1:["collector","c"],pin2:["emitter","e"],pin3:["base","b"]};super.initPorts({pinCount:3,additionalAliases:t})}doInitialCreateNetsFromProps(){this._createNetsFromProps([...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_transistor",name:this.name,transistor_type:n.type});this.source_component_id=i.source_component_id}},mX=class extends In{get config(){let e=this.props.mosfetMode==="depletion"?"d":"e",n=`${this.props.channelType}_channel_${e}_mosfet_transistor`;return{componentName:"Mosfet",schematicSymbolName:this.props.symbolName??n,zodProps:zL,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_mosfet",name:this.name,mosfet_mode:t.mosfetMode,channel_type:t.channelType});this.source_component_id=n.source_component_id}},_X=class extends In{_getSwitchType(){let{spst:e,spdt:t,dpst:n,dpdt:i,type:r}=this._parsedProps??{};return i?"dpdt":e?"spst":t?"spdt":n?"dpst":r??"spst"}get config(){let e=this._getSwitchType(),{isNormallyClosed:t}=this._parsedProps??{},i={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"}[e]??"spst_switch";return{componentName:"Switch",schematicSymbolName:this.props.symbolName??i,zodProps:XL,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.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=n.source_component_id}},KT={HOLE_DIAMETER:.5,SMT_CIRCLE_DIAMETER:1.2,SMT_RECT_SIZE:2},yX=class extends In{get config(){return{componentName:"TestPoint",schematicSymbolName:this.props.symbolName??"testpoint",zodProps:UL,sourceFtype:zs.simple_test_point}}_getPropsWithDefaults(){let{padShape:e,holeDiameter:t,footprintVariant:n,padDiameter:i,width:r,height:o}=this._parsedProps;return!n&&t&&(n="through_hole"),n??(n="through_hole"),e??(e="circle"),n==="pad"?e==="circle"?i??(i=KT.SMT_CIRCLE_DIAMETER):e==="rect"&&(r??(r=KT.SMT_RECT_SIZE),o??(o=r)):n==="through_hole"&&(t??(t=KT.HOLE_DIAMETER)),{padShape:e,holeDiameter:t,footprintVariant:n,padDiameter:i,width:r,height:o}}_getImpliedFootprintString(){let{padShape:e,holeDiameter:t,footprintVariant:n,padDiameter:i,width:r,height:o}=this._getPropsWithDefaults();if(n==="through_hole")return`platedhole_d${t}`;if(n==="pad"){if(e==="circle")return`smtpad_circle_d${i}`;if(e==="rect")return`smtpad_rect_w${r}_h${o}`}throw new Error(`Footprint variant "${n}" with pad shape "${e}" not implemented`)}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,{padShape:n,holeDiameter:i,footprintVariant:r,padDiameter:o,width:s,height:a}=this._getPropsWithDefaults(),c=e.source_component.insert({ftype:zs.simple_test_point,name:this.name,supplier_part_numbers:t.supplierPartNumbers,footprint_variant:r,pad_shape:n,pad_diameter:o,hole_diameter:i,width:s,height:a,are_pins_interchangeable:!0});this.source_component_id=c.source_component_id}},gX=class extends Ie{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicText",zodProps:oF}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout();t.schematic_text.insert({anchor:n.anchor??"center",text:n.text,font_size:n.fontSize,color:n.color||"#000000",position:{x:i.x,y:i.y},rotation:n.schRotation??0})}},xX=class extends Ie{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0);T(this,"schematic_line_id")}get config(){return{componentName:"SchematicLine",zodProps:rF}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,o=t.schematic_line.insert({schematic_component_id:r,x1:n.x1+i.x,y1:n.y1+i.y,x2:n.x2+i.x,y2:n.y2+i.y,stroke_width:Fx,color:Lx,is_dashed:!1,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_line_id=o.schematic_line_id}},bX=class extends Ie{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0);T(this,"schematic_rect_id")}get config(){return{componentName:"SchematicRect",zodProps:iF}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,o=t.schematic_rect.insert({center:{x:n.center.x+i.x,y:n.center.y+i.y},width:n.width,height:n.height,stroke_width:Fx,color:Lx,is_filled:n.isFilled,schematic_component_id:r,is_dashed:n.isDashed,rotation:n.rotation??0,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_rect_id=o.schematic_rect_id}},vX=class extends Ie{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0);T(this,"schematic_arc_id")}get config(){return{componentName:"SchematicArc",zodProps:tF}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,o=t.schematic_arc.insert({schematic_component_id:r,center:{x:n.center.x+i.x,y:n.center.y+i.y},radius:n.radius,start_angle_degrees:n.startAngleDegrees,end_angle_degrees:n.endAngleDegrees,direction:n.direction,stroke_width:Fx,color:Lx,is_dashed:n.isDashed,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_arc_id=o.schematic_arc_id}},wX=class extends Ie{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0);T(this,"schematic_circle_id")}get config(){return{componentName:"SchematicCircle",zodProps:nF}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,o=t.schematic_circle.insert({schematic_component_id:r,center:{x:n.center.x+i.x,y:n.center.y+i.y},radius:n.radius,stroke_width:Fx,color:Lx,is_filled:n.isFilled,fill_color:n.fillColor,is_dashed:n.isDashed,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_circle_id=o.schematic_circle_id}};function Iwt({anchor:e,x:t,y:n,width:i,height:r,isInside:o}){switch(e){case"top_left":return{x:t,y:n+r,textAnchor:o?"top_left":"bottom_left"};case"top_center":return{x:t+i/2,y:n+r,textAnchor:o?"top_center":"bottom_center"};case"top_right":return{x:t+i,y:n+r,textAnchor:o?"top_right":"bottom_right"};case"center_left":return{x:t,y:n+r/2,textAnchor:o?"center_left":"center_right"};case"center":return{x:t+i/2,y:n+r/2,textAnchor:"center"};case"center_right":return{x:t+i,y:n+r/2,textAnchor:o?"center_right":"center_left"};case"bottom_left":return{x:t,y:n,textAnchor:o?"bottom_left":"top_left"};case"bottom_center":return{x:t+i/2,y:n,textAnchor:o?"bottom_center":"top_center"};case"bottom_right":return{x:t+i,y:n,textAnchor:o?"bottom_right":"top_right"};default:return{x:t+i/2,y:n+r,textAnchor:"center"}}}var SX=class extends Ie{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicBox",zodProps:eF,shouldRenderAsSchematicBox:!0}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=.6,r=typeof n.padding=="number"?n.padding:0,o=typeof n.paddingTop=="number"?n.paddingTop:r,s=typeof n.paddingBottom=="number"?n.paddingBottom:r,a=typeof n.paddingLeft=="number"?n.paddingLeft:r,c=typeof n.paddingRight=="number"?n.paddingRight:r,l=n.overlay&&n.overlay.length>0,u=typeof n.width=="number"&&typeof n.height=="number",h,f,_,y,x,v;if(l){let S=n.overlay.map(et=>({selector:et,port:this.getSubcircuit().selectOne(et,{type:"port"})})).filter(({port:et})=>et!=null).map(({port:et})=>({position:et._getGlobalSchematicPositionAfterLayout()}));if(S.length===0)return;let C=S.map(et=>et.position.x),E=S.map(et=>et.position.y),R=Math.min(...C),I=Math.max(...C),k=Math.min(...E),M=Math.max(...E),A=I-R,L=M-k,B=A===0?i:0,D=L===0?i:0,V=a+B/2,X=c+B/2,W=o+D/2,Q=s+D/2,J=R-V,_t=I+X,st=k-Q,it=M+W;h=_t-J,f=it-st,_=J+(n.schX??0),y=st+(n.schY??0),x=_+h/2,v=y+f/2}else if(u){h=n.width,f=n.height;let w=this._getGlobalSchematicPositionBeforeLayout();x=w.x,v=w.y,_=x-h/2,y=v-f/2}else return;if(t.schematic_box.insert({height:f,width:h,x:_,y,is_dashed:n.strokeStyle==="dashed"}),n.title){let w=n.titleInside,S=.1,C=n.titleAlignment,E=Iwt({anchor:C,x:_,y,width:h,height:f,isInside:w}),R,I,k=E.textAnchor;w?(R=C.includes("top")?-S:C.includes("bottom")?S:0,I=C.includes("left")?S:C.includes("right")?-S:0):(R=C.includes("top")?S:C.includes("bottom")?-S:0,I=C.includes("center_left")?-S:C.includes("center_right")?S:0);let M=E.x+I,A=E.y+R;t.schematic_text.insert({anchor:k,text:n.title,font_size:n.titleFontSize??.18,color:n.titleColor??"#000000",position:{x:M,y:A},rotation:0})}}},PX=class extends Ie{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0);T(this,"schematic_table_id",null)}get config(){return{componentName:"SchematicTable",zodProps:sF}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.children.filter(f=>f.componentName==="SchematicRow");if(i.length===0)return;let r=[],o=0;for(let f of i){let _=f.children.filter(y=>y.componentName==="SchematicCell");o=Math.max(o,_.length)}for(let f=0;f<i.length;f++)r[f]=[];for(let f=0;f<i.length;f++){let y=i[f].children.filter(v=>v.componentName==="SchematicCell"),x=0;for(let v=0;v<y.length;v++){for(;r[f][x];)x++;let w=y[v],S=w._parsedProps.colSpan??1,C=w._parsedProps.rowSpan??1;for(let E=0;E<C;E++)for(let R=0;R<S;R++)r[f+E]||(r[f+E]=[]),r[f+E][x+R]=w;x+=S}}o=Math.max(0,...r.map(f=>f.length));let s=i.map((f,_)=>f._parsedProps.height??1),a=Array.from({length:o},(f,_)=>{let y=0;for(let x=0;x<i.length;x++){let v=r[x]?.[_];if(v){let w=v._parsedProps.text??v._parsedProps.children,S=v._parsedProps.width??(w?.length??2)*.5;S>y&&(y=S)}}return y||10}),c=this._getGlobalSchematicPositionBeforeLayout(),l=t.schematic_table.insert({anchor_position:c,column_widths:a,row_heights:s,cell_padding:n.cellPadding,border_width:n.borderWidth,anchor:n.anchor,subcircuit_id:this.getSubcircuit()?.subcircuit_id||"",schematic_component_id:this.parent?.schematic_component_id||""});this.schematic_table_id=l.schematic_table_id;let u=new Set,h=0;for(let f=0;f<i.length;f++){let _=0;for(let y=0;y<o;y++){let x=r[f]?.[y];if(x&&!u.has(x)){u.add(x);let v=x._parsedProps,w=v.rowSpan??1,S=v.colSpan??1,C=0;for(let R=0;R<S;R++)C+=a[y+R];let E=0;for(let R=0;R<w;R++)E+=s[f+R];t.schematic_table_cell.insert({schematic_table_id:this.schematic_table_id,start_row_index:f,end_row_index:f+w-1,start_column_index:y,end_column_index:y+S-1,text:v.text??v.children,center:{x:c.x+_+C/2,y:c.y-h-E/2},width:C,height:E,horizontal_align:v.horizontalAlign,vertical_align:v.verticalAlign,font_size:v.fontSize??n.fontSize,subcircuit_id:this.getSubcircuit()?.subcircuit_id||""})}a[y]&&(_+=a[y])}h+=s[f]}}},TX=class extends Ie{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicRow",zodProps:aF}}},IX=class extends Ie{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0);T(this,"canHaveTextChildren",!0)}get config(){return{componentName:"SchematicCell",zodProps:cF}}},MX=class extends Ie{constructor(){super(...arguments);T(this,"isPrimitiveContainer",!0)}get config(){return{componentName:"Symbol",zodProps:AL}}},Mwt={name:"@tscircuit/core",type:"module",version:"0.0.752",types:"dist/index.d.ts",main:"dist/index.js",module:"dist/index.js",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist"],repository:{type:"git",url:"https://github.com/tscircuit/core"},scripts:{build:"tsup-node index.ts --format esm --dts",format:"biome format . --write","measure-bundle":"howfat -r table .","pkg-pr-new-release":"bunx pkg-pr-new publish --comment=off --peerDeps","smoke-test:dist":"bun run scripts/smoke-tests/test-dist-simple-circuit.tsx","build:benchmarking":"bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist","build:benchmarking:watch":`chokidar "./{benchmarking,lib}/**/*.{ts,tsx}" -c 'bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist'`,"start:benchmarking":'concurrently "bun run build:benchmarking:watch" "live-server ./benchmarking-dist"'},devDependencies:{"@biomejs/biome":"^1.8.3","@tscircuit/capacity-autorouter":"^0.0.107","@tscircuit/checks":"^0.0.75","@tscircuit/circuit-json-util":"^0.0.67","@tscircuit/footprinter":"^0.0.236","@tscircuit/import-snippet":"^0.0.4","@tscircuit/infgrid-ijump-astar":"^0.0.33","@tscircuit/log-soup":"^1.0.2","@tscircuit/matchpack":"^0.0.16","@tscircuit/math-utils":"^0.0.21","@tscircuit/miniflex":"^0.0.4","@tscircuit/props":"0.0.341","@tscircuit/schematic-autolayout":"^0.0.6","@tscircuit/schematic-match-adapt":"^0.0.16","@tscircuit/schematic-trace-solver":"^0.0.40","@tscircuit/simple-3d-svg":"^0.0.41","@types/bun":"^1.2.16","@types/debug":"^4.1.12","@types/react":"^19.1.8","@types/react-dom":"^19.1.6","@types/react-reconciler":"^0.28.9","bpc-graph":"^0.0.57","bun-match-svg":"0.0.12","calculate-elbow":"^0.0.12","chokidar-cli":"^3.0.0","circuit-json":"^0.0.267","circuit-json-to-bpc":"^0.0.13","circuit-json-to-connectivity-map":"^0.0.22","circuit-json-to-simple-3d":"^0.0.9","circuit-to-svg":"^0.0.202",concurrently:"^9.1.2","connectivity-map":"^1.0.0",debug:"^4.3.6",flatbush:"^4.5.0","graphics-debug":"^0.0.60",howfat:"^0.3.8","live-server":"^1.2.2","looks-same":"^9.0.1",minicssgrid:"^0.0.9","pkg-pr-new":"^0.0.37",react:"^19.1.0","react-dom":"^19.1.0","schematic-symbols":"^0.0.202","ts-expect":"^1.3.0",tsup:"^8.2.4"},peerDependencies:{"@tscircuit/capacity-autorouter":"*","@tscircuit/checks":"*","@tscircuit/circuit-json-util":"*","@tscircuit/footprinter":"*","@tscircuit/infgrid-ijump-astar":"*","@tscircuit/math-utils":"*","@tscircuit/props":"*","@tscircuit/schematic-autolayout":"*","@tscircuit/schematic-match-adapt":"*","circuit-json-to-bpc":"*","bpc-graph":"*","@tscircuit/matchpack":"*","circuit-json":"*","circuit-json-to-connectivity-map":"*","schematic-symbols":"*",typescript:"^5.0.0"},dependencies:{"@flatten-js/core":"^1.6.2","@lume/kiwi":"^0.4.3","calculate-packing":"0.0.37","css-select":"5.1.0","format-si-unit":"^0.0.3",nanoid:"^5.0.7","performance-now":"^2.1.0","react-reconciler":"^0.32.0","transformation-matrix":"^2.16.1",zod:"^3.25.67"}},eh=class{constructor({platform:e,projectUrl:t}={}){T(this,"firstChild",null);T(this,"children");T(this,"db");T(this,"root",null);T(this,"isRoot",!0);T(this,"schematicDisabled",!1);T(this,"pcbDisabled",!1);T(this,"pcbRoutingDisabled",!1);T(this,"_featureMspSchematicTraceRouting",!0);T(this,"name");T(this,"platform");T(this,"projectUrl");T(this,"_hasRenderedAtleastOnce",!1);T(this,"_eventListeners",{});this.children=[],this.db=Me([]),this.root=this,this.platform=e,this.projectUrl=t,this.pcbDisabled=e?.pcbDisabled??!1}add(e){let t;(0,EX.isValidElement)(e)?t=gY(e):t=e,this.children.push(t)}_getBoard(){return this.children.find(e=>e.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 e=new th({subcircuit:!0});e.parent=this,e.addAll(this.children),this.children=[e],this.firstChild=e}render(){this.firstChild||this._guessRootComponent();let{firstChild:e,db:t}=this;if(!e)throw new Error("RootCircuit has no root component");e.parent=this,e.runRenderCycle(),this._hasRenderedAtleastOnce=!0}async renderUntilSettled(){for(this.db.source_project_metadata.list()?.[0]||this.db.source_project_metadata.insert({software_used_string:`@tscircuit/core@${this.getCoreVersion()}`,...this.projectUrl?{project_url:this.projectUrl}:{}}),this.render();this._hasIncompleteAsyncEffects();)await new Promise(t=>setTimeout(t,100)),this.render();this.emit("renderComplete")}_hasIncompleteAsyncEffects(){return this.children.some(e=>e._hasIncompleteAsyncEffects()?!0:e.children.some(t=>t._hasIncompleteAsyncEffects()))}getCircuitJson(){return this._hasRenderedAtleastOnce||this.render(),this.db.toArray()}toJson(){return this.getCircuitJson()}async getSvg(e){let t=await Promise.resolve().then(()=>(Yj(),jj)).catch(n=>{throw new Error(`To use circuit.getSvg, you must install the "circuit-to-svg" package.
232
232
 
233
- "${n.message}"`)});if(e.view==="pcb")return t.convertCircuitJsonToPcbSvg(this.getCircuitJson());if(e.view==="schematic")return t.convertCircuitJsonToSchematicSvg(this.getCircuitJson());throw new Error(`Invalid view: ${e.view}`)}getCoreVersion(){let[e,t,n]=Mwt.version.split(".").map(Number);return`${e}.${t}.${n+1}`}async preview(e){let t=typeof e=="object"?e:{previewName:e};throw new Error("project.preview is not yet implemented")}computeSchematicGlobalTransform(){return vi()}_computePcbGlobalTransformBeforeLayout(){return vi()}selectAll(e){return this._guessRootComponent(),this.firstChild?.selectAll(e)??[]}selectOne(e,t){return this._guessRootComponent(),this.firstChild?.selectOne(e,t)??null}emit(e,...t){if(this._eventListeners[e])for(let n of this._eventListeners[e])n(...t)}on(e,t){this._eventListeners[e]||(this._eventListeners[e]=[]),this._eventListeners[e].push(t)}removeListener(e,t){this._eventListeners[e]&&(this._eventListeners[e]=this._eventListeners[e].filter(n=>n!==t))}enableDebug(e){typeof e=="string"?rI.default.enable(e):(e===null||e===!1)&&rI.default.disable()}getClientOrigin(){return typeof window<"u"&&window.location?window.location.origin:typeof self<"u"&&self.location?self.location.origin:""}},Ewt=eh,Cwt=eh,kwt=e=>{let[t,n]=Kp.default.useState(!0),[i,r]=Kp.default.useState(null),[o,s]=Kp.default.useState(),[a,c]=Kp.default.useState();return Kp.default.useEffect(()=>{n(!0),r(null),e&&setTimeout(()=>{try{let l=new eh;l.add(e),s(l),c(l.toJson())}catch(l){r(l)}n(!1)},1)},[e]),{isLoading:t,error:i,circuit:o,circuitJson:a}},nh=(e,t)=>(n,i)=>{let r=[];Array.isArray(t)?r.push(...t.flat()):typeof t=="object"&&r.push(...Object.values(t).flat(),...Object.keys(t));let o=s=>{if(s?.name&&s.name!==n)throw new Error(`Component name mismatch. Hook name: ${n}, Component prop name: ${s.name}`);let a={...i,...s,name:n},c=[];for(let l of r)if(a[l]){let u=`.${n} > .${l}`,h=a[l];c.push({from:u,to:h}),delete a[l]}return(0,Ml.jsxs)(Ml.Fragment,{children:[(0,Ml.jsx)(e,{...a}),c.map((l,u)=>(0,Ml.jsx)("trace",{...l},u))]})};for(let s of r)o[s]=`.${n} > .${s}`;return o},Awt=nh(e=>(0,CX.jsx)("capacitor",{...e}),PL),Nwt=e=>nh(t=>(0,kX.jsx)("chip",{pinLabels:e,...t}),e),Rwt=nh(e=>(0,AX.jsx)("diode",{...e}),BL),Owt=nh(e=>(0,NX.jsx)("led",{...e}),YL),Lwt=nh(e=>(0,RX.jsx)("resistor",{...e}),xL),Fwt=new Proxy(e=>new Proxy({},{get:(t,n)=>`.${e} > .${n}`}),{get:(e,t)=>{let n=(...i)=>{let r=i[0];return new Proxy({},{get:(o,s)=>`.${t} > .${s}`})};return new Proxy(n,{get:(i,r)=>t==="net"?`net.${r}`:t==="subcircuit"?new Proxy({},{get:(o,s)=>new Proxy({},{get:(a,c)=>`subcircuit.${r} > .${s} > .${c}`})}):`.${t} > .${r}`,apply:(i,r,o)=>t==="net"?new Proxy({},{get:(s,a)=>`net.${a}`}):new Proxy({},{get:(s,a)=>{let c=`.${t} > .${a}`;return["U","J","CN"].some(u=>t.startsWith(u))?c:new Proxy(new String(c),{get:(u,h)=>typeof h=="symbol"||h==="toString"?()=>c:`.${t} > .${a} > .${h}`})}})})}});yY(dY);yY({Bug:zx});var JX=Xt(co(),1);var LX=e=>{let t=e.match(/:[RC]_(\d{4})_/);if(t||(t=e.match(/:(SOIC-\d+|SOT-\d+|SOD-\d+|SSOP-\d+|TSSOP-\d+|QFP-\d+|QFN-\d+)/),t))return t[1]};var mI=e=>e.includes("cap")?e.replace(/cap/g,""):e;var FX=e=>{if(e){if(e.startsWith("kicad:")){let t=LX(e);return t?mI(t):e}return mI(e)}};var _I=new Map,Gi=async(e,t)=>{let n=new URLSearchParams({...t,json:"true"}).toString();if(_I.has(n))return _I.get(n);let r=await(await fetch(`https://jlcsearch.tscircuit.com/${e}/list?${n}`)).json();return _I.set(n,r),r},Ui=e=>e?[...e].sort((t,n)=>Number(n.is_basic??!1)-Number(t.is_basic??!1)):[],zX={findPart:async({sourceComponent:e,footprinterString:t})=>{let n=FX(t);if(e.type==="source_component"&&e.ftype==="simple_resistor"){let{resistors:i}=await Gi("resistors",{resistance:e.resistance,package:n});return{jlcpcb:Ui(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_capacitor"){let{capacitors:i}=await Gi("capacitors",{capacitance:e.capacitance,package:n});return{jlcpcb:Ui(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_pin_header"){let i;t?.includes("_p")&&(i=Number(t.split("_p")[1]));let{headers:r}=await Gi("headers",i?{pitch:i,num_pins:e.pin_count,gender:e.gender}:{num_pins:e.pin_count,gender:e.gender});return{jlcpcb:Ui(r).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_potentiometer"){let{potentiometers:i}=await Gi("potentiometers",{resistance:e.max_resistance,package:n});return{jlcpcb:Ui(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_diode"){let{diodes:i}=await Gi("diodes",{package:n});return{jlcpcb:Ui(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_chip"){let{chips:i}=await Gi("chips",{package:n});return{jlcpcb:Ui(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_transistor"){let{transistors:i}=await Gi("transistors",{package:n,transistor_type:e.transistor_type});return{jlcpcb:Ui(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_power_source"){let{power_sources:i}=await Gi("power_sources",{voltage:e.voltage,package:n});return{jlcpcb:Ui(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_inductor"){let{inductors:i}=await Gi("inductors",{inductance:e.inductance,package:n});return{jlcpcb:Ui(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_crystal"){let{crystals:i}=await Gi("crystals",{frequency:e.frequency,load_capacitance:e.load_capacitance,package:n});return{jlcpcb:Ui(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_mosfet"){let{mosfets:i}=await Gi("mosfets",{package:n,mosfet_mode:e.mosfet_mode,channel_type:e.channel_type});return{jlcpcb:Ui(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_resonator"){let{resonators:i}=await Gi("resonators",{frequency:e.frequency,package:n});return{jlcpcb:Ui(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_switch"){let{switches:i}=await Gi("switches",{switch_type:e.type,package:n});return{jlcpcb:Ui(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_led"){let{leds:i}=await Gi("leds",{package:n});return{jlcpcb:Ui(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_fuse"){let{fuses:i}=await Gi("fuses",{package:n});return{jlcpcb:Ui(i).map(r=>`C${r.lcsc}`).slice(0,3)}}return{}}};var jX=Xt(DX(),1);Z();var GX=Xt(Pn(),1),UX=Xt(Pn(),1),qi=p.tuple([p.coerce.number(),p.coerce.number()]),Gwt=p.tuple([p.number(),p.number(),p.number()]),Xx=p.union([qi,Gwt]),YX=p.object({at:Xx,size:qi,layers:p.array(p.string()),roundrect_rratio:p.number(),uuid:p.string()}).partial(),Uwt=p.object({key:p.string(),val:p.string(),attributes:YX}),Bx=p.object({oval:p.boolean().default(!1),width:p.number().optional(),height:p.number().optional(),offset:qi.optional()}),XX=p.object({name:p.string(),pad_type:p.enum(["thru_hole","smd","np_thru_hole","connect"]),pad_shape:p.enum(["roundrect","circle","rect","oval","trapezoid","custom"]),at:Xx,drill:p.union([p.number(),p.array(p.any()),Bx]).transform(e=>typeof e=="number"?{oval:!1,width:e,height:e}:"oval"in e?e:e.length===2?{oval:!1,width:Number.parseFloat(e[0]),height:Number.parseFloat(e[0]),offset:qi.parse(e[1].slice(1))}:e.length===3||e.length===4?{oval:e[0]==="oval",width:Number.parseFloat(e[1]),height:Number.parseFloat(e[2]),offset:e[3]?qi.parse(e[3].slice(1)):void 0}:e).pipe(Bx),size:p.union([p.array(p.number()).length(2).transform(([e,t])=>({width:e,height:t})),p.object({width:p.number(),height:p.number()})]),layers:p.array(p.string()).optional(),roundrect_rratio:p.number().optional(),uuid:p.string().optional()}),VX=p.object({name:p.string(),pad_type:p.enum(["thru_hole","smd","np_thru_hole","connect"]),pad_shape:p.enum(["roundrect","circle","rect","oval","trapezoid","custom"]),at:Xx,size:qi,drill:p.union([p.number(),p.array(p.any()),Bx]).transform(e=>typeof e=="number"?{oval:!1,width:e,height:e}:"oval"in e?e:e.length===2?{oval:!1,width:Number.parseFloat(e[0]),height:Number.parseFloat(e[0]),offset:qi.parse(e[1].slice(1))}:e.length===3||e.length===4?{oval:e[0]==="oval",width:Number.parseFloat(e[1]),height:Number.parseFloat(e[2]),offset:e[3]?qi.parse(e[3].slice(1)):void 0}:e).pipe(Bx).optional(),layers:p.array(p.string()).optional(),roundrect_rratio:p.number().optional(),chamfer_ratio:p.number().optional(),solder_paste_margin:p.number().optional(),solder_paste_margin_ratio:p.number().optional(),clearance:p.number().optional(),zone_connection:p.union([p.literal(0).describe("Pad is not connect to zone"),p.literal(1).describe("Pad is connected to zone using thermal relief"),p.literal(2).describe("Pad is connected to zone using solid fill")]).optional(),thermal_width:p.number().optional(),thermal_gap:p.number().optional(),uuid:p.string().optional()}),HX=p.object({font:p.object({size:qi,thickness:p.number().optional()})}).partial(),qwt=p.object({fp_text_type:p.literal("user"),text:p.string(),at:Xx,layer:p.string(),uuid:p.string().optional(),effects:HX.partial()}),Wwt=p.object({start:qi,mid:qi,end:qi,stroke:p.object({width:p.number(),type:p.string()}),layer:p.string(),uuid:p.string().optional()}),Zwt=p.object({pts:p.array(qi),stroke:p.object({width:p.number(),type:p.string()}).optional(),width:p.number().optional(),layer:p.string(),uuid:p.string().optional()}).transform(e=>({...e,width:void 0,stroke:e.stroke??{width:e.width}})),Kwt=p.object({start:qi,end:qi,stroke:p.object({width:p.number(),type:p.string()}).optional(),width:p.number().optional(),layer:p.string(),uuid:p.string().optional()}).transform(e=>({...e,width:void 0,stroke:e.stroke??{width:e.width}})),$X=p.object({footprint_name:p.string(),version:p.string().optional(),generator:p.string().optional(),generator_version:p.string().optional(),layer:p.string(),descr:p.string().default(""),tags:p.array(p.string()).optional(),properties:p.array(Uwt),fp_lines:p.array(Kwt),fp_texts:p.array(qwt),fp_arcs:p.array(Wwt),fp_polys:p.array(Zwt).optional(),pads:p.array(VX),holes:p.array(XX).optional()}),jx=(e,t)=>{if(t==="effects"&&Array.isArray(e)){let n={};for(let i of e)if(i[0]==="font"){let r={};for(let o of i.slice(1))o.length===2?r[o[0].valueOf()]=Number.parseFloat(o[1].valueOf()):r[o[0].valueOf()]=o.slice(1).map(s=>Number.parseFloat(s.valueOf()));n.font=r}return HX.parse(n)}if(t==="pts")return e.map(n=>n.slice(1).map(i=>Number.parseFloat(i.valueOf())));if(t==="stroke"){let n={};for(let i of e){let r=i[0].valueOf();n[r]=jx(i.slice(1),r)}return n}return t==="at"||t==="size"||t==="start"||t==="mid"||t==="end"?(Array.isArray(e)?e:[e]).map(i=>i?.valueOf?.()??i).filter(i=>typeof i=="number"||typeof i=="string"&&/^[-+]?\d*\.?\d+(e[-+]?\d+)?$/i.test(i)).map(i=>typeof i=="number"?i:Number.parseFloat(i)):t==="tags"?e.map(n=>n.valueOf()):t==="generator_version"||t==="version"?e[0].valueOf():e.length===2?e.valueOf():t==="uuid"?Array.isArray(e)?e[0].valueOf():e.valueOf():/^[\d\.]+$/.test(e)&&!Number.isNaN(Number.parseFloat(e))?Number.parseFloat(e):Array.isArray(e)&&e.length===1?e[0].valueOf():Array.isArray(e)?e.map(n=>n.valueOf()):e},Ke=(e,t)=>{for(let n of e)if(Array.isArray(n)&&n[0]===t)return jx(n.slice(1),t)},yI=(0,GX.default)("kicad-mod-converter"),Jwt=e=>{let t=(0,jX.default)(e),n=t[1].valueOf(),i={},r=Object.entries($X.shape).filter(([w,S])=>S._def.typeName==="ZodString"||w==="tags").map(([w])=>w);for(let w of t.slice(2)){if(!r.includes(w[0]))continue;let S=w[0].valueOf(),C=jx(w.slice(1),S);i[S]=C}let o=t.slice(2).filter(w=>w[0]==="property").map(w=>{let S=w[1].valueOf(),C=w[2].valueOf(),E=YX.parse(w.slice(3).reduce((R,I)=>{let k=I[0].valueOf();return R[k]=jx(I.slice(1),k),R},{}));return{key:S,val:C,attributes:E}}),s=t.slice(2).filter(w=>w[0]==="pad"),a=[];for(let w of s){let S=Ke(w,"at"),C=Ke(w,"size"),E=Ke(w,"drill"),R=Ke(w,"layers");if(Array.isArray(R)?R=R.map(A=>A.valueOf()):typeof R=="string"?R=[R]:R||(R=[]),!R.includes("F.Cu")){yI(`Skipping pad without F.Cu layer: layers=${R.join(", ")}`);continue}let I=Ke(w,"roundrect_rratio"),k=Ke(w,"uuid"),M={name:w[1].valueOf(),pad_type:w[2].valueOf(),pad_shape:w[3].valueOf(),at:S,drill:E,size:C,layers:R,roundrect_rratio:I,uuid:k};yI(`attempting to parse pad: ${JSON.stringify(M,null," ")}`),a.push(VX.parse(M))}let c=t.slice(2).filter(w=>w[0]==="fp_text"),l=[];for(let w of c){let S=w[2].valueOf(),C=Ke(w,"at"),E=Ke(w,"layer"),R=Ke(w,"uuid"),I=Ke(w,"effects");l.push({fp_text_type:"user",text:S,at:C,layer:E,uuid:R,effects:I})}let u=[],h=t.slice(2).filter(w=>w[0]==="fp_line");for(let w of h){let S=Ke(w,"start"),C=Ke(w,"end"),E=Ke(w,"stroke"),R=Ke(w,"layer"),I=Ke(w,"uuid");u.push({start:S,end:C,stroke:E,layer:R,uuid:I})}let f=[],_=t.slice(2).filter(w=>w[0]==="fp_arc");for(let w of _){let S=Ke(w,"start"),C=Ke(w,"mid"),E=Ke(w,"end"),R=Ke(w,"stroke"),I=Ke(w,"layer"),k=Ke(w,"uuid");!S||!E||!C||!R||!I||f.push({start:S,mid:C,end:E,stroke:R,layer:I,uuid:k})}let y=[],x=t.slice(2).filter(w=>w[0]==="fp_poly");for(let w of x){let S=Ke(w,"pts"),C=Ke(w,"stroke"),E=Ke(w,"layer"),R=Ke(w,"uuid");y.push({pts:S,stroke:C,layer:E,uuid:R})}let v=[];for(let w of t.slice(2)){if(w[0]!=="pad"||w[2]?.valueOf?.()!=="thru_hole")continue;let S=w[1]?.valueOf?.(),C=w[2]?.valueOf?.(),E=w[3]?.valueOf?.(),R=Ke(w,"at"),I=Ke(w,"drill"),k=Ke(w,"size");Array.isArray(k)&&(k[0]==="size"&&(k=k.slice(1)),k={width:Number(k[0]),height:Number(k[1])});let M=Ke(w,"uuid"),A=Ke(w,"roundrect_rratio"),L=Ke(w,"layers");Array.isArray(L)?L=L.map(D=>D.valueOf()):typeof L=="string"?L=[L]:L||(L=[]);let B={name:S,pad_type:C,pad_shape:E,at:R,drill:I,size:k,layers:L,roundrect_rratio:A,uuid:M};yI(`attempting to parse holes: ${JSON.stringify(B,null,2)}`),v.push(XX.parse(B))}return $X.parse({footprint_name:n,...i,properties:o,fp_lines:u,fp_texts:l,fp_arcs:f,pads:a,holes:v,fp_polys:y})};function qX(e,t,n){let i={x:(e.x+t.x)/2,y:(e.y+t.y)/2},r={x:(t.x+n.x)/2,y:(t.y+n.y)/2},o=-(e.x-t.x)/(e.y-t.y),s=-(t.x-n.x)/(t.y-n.y),a=(i.y-r.y+s*r.x-o*i.x)/(s-o),c=i.y+o*(a-i.x);return{x:a,y:c}}function WX(e,t){return Math.sqrt((e.x-t.x)**2+(e.y-t.y)**2)}function Yx(e,t){return Math.atan2(t.y-e.y,t.x-e.x)}var Qwt=(e,t,n)=>{let i=qX(e,t,n),r=WX(i,e),o=Yx(i,e),a=Yx(i,n)-o;return a<0&&(a+=2*Math.PI),r*a};function tSt(e,t,n,i){let r=qX(e,t,n),o=WX(r,e),s=Yx(r,e),c=Yx(r,n)-s;c<0&&(c+=2*Math.PI);let l=[];for(let u=0;u<=i;u++){let h=s+u/i*c,f=r.x+o*Math.cos(h),_=r.y+o*Math.sin(h);l.push({x:f,y:_})}return l}var gI=e=>Array.isArray(e)?{x:e[0],y:e[1]}:e,eSt=e=>e*Math.PI/180,xI=(e,t,n)=>{let i=eSt(n),r=Math.cos(i),o=Math.sin(i);return{x:e*r-t*o,y:e*o+t*r}},nSt=e=>{let t=[...new Map(e.map(u=>[`${u.x},${u.y}`,u])).values()];if(t.length!==4)return null;let n=t.map(u=>u.x),i=t.map(u=>u.y),r=[...new Set(n)],o=[...new Set(i)];if(r.length!==2||o.length!==2)return null;let[s,a]=r.sort((u,h)=>u-h),[c,l]=o.sort((u,h)=>u-h);return s===void 0||a===void 0||c===void 0||l===void 0?null:{x:(s+a)/2,y:(c+l)/2,width:a-s,height:l-c}},BX=e=>e&&Array.isArray(e)&&e.length>=3&&typeof e[2]=="number"?e[2]:0,Jr=e=>{let t=(e%360+360)%360;return t===90||t===270},bI=(0,UX.default)("kicad-mod-converter"),Go=e=>{switch(e){case"F.Cu":case"F.Fab":case"F.SilkS":return"top";case"B.Cu":case"B.Fab":case"B.SilkS":return"bottom"}},iSt=async e=>{let{fp_lines:t,fp_texts:n,fp_arcs:i,pads:r,properties:o,holes:s,fp_polys:a}=e,c=[];c.push({type:"source_component",source_component_id:"source_component_0",supplier_part_numbers:{}}),c.push({type:"schematic_component",schematic_component_id:"schematic_component_0",source_component_id:"source_component_0",center:{x:0,y:0},rotation:0,size:{width:0,height:0}});let l=new Set;for(let D of r)D.name&&l.add(D.name);if(s)for(let D of s)D.name&&l.add(D.name);let u=0,h=new Map;for(let D of l){let V=`source_port_${u++}`;h.set(D,V),c.push({type:"source_port",source_port_id:V,source_component_id:"source_component_0",name:D,port_hints:[D]}),c.push({type:"schematic_port",schematic_port_id:`schematic_port_${u++}`,source_port_id:V,schematic_component_id:"schematic_component_0",center:{x:0,y:0}})}let f=Number.POSITIVE_INFINITY,_=Number.NEGATIVE_INFINITY,y=Number.POSITIVE_INFINITY,x=Number.NEGATIVE_INFINITY;for(let D of r){let V=D.at[0],X=-D.at[1],W=D.size[0],Q=D.size[1];f=Math.min(f,V-W/2),_=Math.max(_,V+W/2),y=Math.min(y,X-Q/2),x=Math.max(x,X+Q/2)}let v="pcb_component_0";c.push({type:"pcb_component",source_component_id:"source_component_0",pcb_component_id:v,layer:"top",center:{x:0,y:0},rotation:0,width:Number.isFinite(f)?_-f:0,height:Number.isFinite(y)?x-y:0});let w=0,S=new Map;for(let D of l){let V=`pcb_port_${w++}`,X=h.get(D);S.set(D,V);let W=0,Q=0,J=["top","bottom"],_t=r.find(st=>st.name===D);if(_t)W=_t.at[0],Q=-_t.at[1],J=_t.layers?_t.layers.map(st=>Go(st)).filter(Boolean):["top","bottom"];else if(s){let st=s.find(it=>it.name===D);st&&(W=st.at[0],Q=-st.at[1],J=st.layers?st.layers.map(it=>Go(it)).filter(Boolean):["top","bottom"])}c.push({type:"pcb_port",pcb_port_id:V,source_port_id:X,pcb_component_id:v,x:W,y:Q,layers:J})}let C=0,E=0,R=0;for(let D of r)if(D.pad_type==="smd"){let V=D.name?S.get(D.name):void 0;c.push({type:"pcb_smtpad",pcb_smtpad_id:`pcb_smtpad_${C++}`,shape:"rect",x:D.at[0],y:-D.at[1],width:D.size[0],height:D.size[1],layer:Go(D.layers?.[0]??"F.Cu"),pcb_component_id:v,port_hints:[D.name],pcb_port_id:V})}else if(D.pad_type==="thru_hole"){if(D.pad_shape==="rect"){let V=BX(D.at),X=Jr(V)?D.size[1]:D.size[0],W=Jr(V)?D.size[0]:D.size[1],Q=D.drill?.offset?.[0]??0,J=D.drill?.offset?.[1]??0,_t=xI(Q,J,V),st=D.name?S.get(D.name):void 0;c.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"circular_hole_with_rect_pad",hole_shape:"circle",pad_shape:"rect",x:D.at[0],y:-D.at[1],hole_offset_x:_t.x,hole_offset_y:-_t.y,hole_diameter:D.drill?.width,rect_pad_width:X,rect_pad_height:W,layers:["top","bottom"],pcb_component_id:v,port_hints:[D.name],pcb_port_id:st})}else if(D.pad_shape==="circle"){let V=D.name?S.get(D.name):void 0;c.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"circle",x:D.at[0],y:-D.at[1],outer_diameter:D.size[0],hole_diameter:D.drill?.width,layers:["top","bottom"],pcb_component_id:v,port_hints:[D.name],pcb_port_id:V})}else if(D.pad_shape==="oval"){let V=D.name?S.get(D.name):void 0;c.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"pill",x:D.at[0],y:-D.at[1],outer_width:D.size[0],outer_height:D.size[1],hole_width:D.drill?.width,hole_height:D.drill?.height,layers:["top","bottom"],pcb_component_id:v,port_hints:[D.name],pcb_port_id:V})}}else D.pad_type==="np_thru_hole"&&c.push({type:"pcb_hole",pcb_hole_id:`pcb_hole_${R++}`,x:D.at[0],y:-D.at[1],hole_diameter:D.drill?.width,pcb_component_id:v});if(s)for(let D of s){let V=D.layers?.some(Tt=>Tt.endsWith(".Cu")||Tt==="*.Cu"),X=BX(D.at),W=D.drill?.offset?.[0]??0,Q=D.drill?.offset?.[1]??0,J=xI(W,Q,X),_t=D.at[0]+J.x,st=-(D.at[1]+J.y),it=D.drill?.width??0,et=D.size?.width??it,vt=D.roundrect_rratio??0,mt=vt>0?Math.min(Jr(X)?D.size?.height??et:D.size?.width??et,Jr(X)?D.size?.width??et:D.size?.height??et)/2*vt:0;if(V)if(D.pad_shape==="rect"){let Tt=D.name?S.get(D.name):void 0;c.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"circular_hole_with_rect_pad",hole_shape:"circle",pad_shape:"rect",x:D.at[0],y:-D.at[1],hole_offset_x:J.x,hole_offset_y:-J.y,hole_diameter:it,rect_pad_width:Jr(X)?D.size?.height??et:D.size?.width??et,rect_pad_height:Jr(X)?D.size?.width??et:D.size?.height??et,rect_border_radius:mt,port_hints:[D.name],layers:["top","bottom"],pcb_component_id:v,pcb_port_id:Tt})}else if(D.pad_shape==="oval"){let Tt=D.name?S.get(D.name):void 0;c.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"pill",x:_t,y:st,outer_width:Jr(X)?D.size?.height??et:D.size?.width??et,outer_height:Jr(X)?D.size?.width??et:D.size?.height??et,hole_width:Jr(X)?D.drill?.height??it:D.drill?.width??it,hole_height:Jr(X)?D.drill?.width??it:D.drill?.height??it,port_hints:[D.name],layers:["top","bottom"],pcb_component_id:v,pcb_port_id:Tt})}else if(D.pad_shape==="roundrect"){let Tt=D.name?S.get(D.name):void 0,Ot=D.drill?.offset?.[0]??0,pt=D.drill?.offset?.[1]??0,j=xI(Ot,pt,X),q=Jr(X)?D.size?.height??et:D.size?.width??et,Y=Jr(X)?D.size?.width??et:D.size?.height??et;c.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"circular_hole_with_rect_pad",hole_shape:"circle",pad_shape:"rect",x:_t,y:st,hole_offset_x:j.x,hole_offset_y:-j.y,hole_diameter:it,rect_pad_width:q,rect_pad_height:Y,rect_border_radius:mt,port_hints:[D.name],layers:["top","bottom"],pcb_component_id:v,pcb_port_id:Tt})}else{let Tt=D.name?S.get(D.name):void 0;c.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"circle",x:_t,y:st,outer_diameter:et,hole_diameter:it,port_hints:[D.name],layers:["top","bottom"],pcb_component_id:v,pcb_port_id:Tt})}else c.push({type:"pcb_hole",pcb_hole_id:`pcb_hole_${R++}`,x:_t,y:st,hole_diameter:et,hole_shape:"circle",pcb_component_id:v})}let I=0,k=0,M=0;for(let D of t){let V=[{x:D.start[0],y:-D.start[1]},{x:D.end[0],y:-D.end[1]}];D.layer==="F.Cu"?c.push({type:"pcb_trace",pcb_trace_id:`pcb_trace_${I++}`,pcb_component_id:v,layer:Go(D.layer),route:V,thickness:D.stroke.width}):D.layer==="F.SilkS"?c.push({type:"pcb_silkscreen_path",pcb_silkscreen_path_id:`pcb_silkscreen_path_${k++}`,pcb_component_id:v,layer:"top",route:V,stroke_width:D.stroke.width}):D.layer==="F.Fab"?c.push({type:"pcb_fabrication_note_path",fabrication_note_path_id:`fabrication_note_path_${M++}`,pcb_component_id:v,layer:"top",route:V,stroke_width:D.stroke.width,port_hints:[]}):bI("Unhandled layer for fp_line",D.layer)}if(a)for(let D of a){let V=D.pts.map(X=>({x:X[0],y:-X[1]}));if(D.layer.endsWith(".Cu")){let X=nSt(V);X?c.push({type:"pcb_smtpad",pcb_smtpad_id:`pcb_smtpad_${C++}`,shape:"rect",x:X.x,y:X.y,width:X.width,height:X.height,layer:Go(D.layer),pcb_component_id:v}):c.push({type:"pcb_trace",pcb_trace_id:`pcb_trace_${I++}`,pcb_component_id:v,layer:Go(D.layer),route:V,thickness:D.stroke.width})}else D.layer.endsWith(".SilkS")?c.push({type:"pcb_silkscreen_path",pcb_silkscreen_path_id:`pcb_silkscreen_path_${k++}`,pcb_component_id:v,layer:Go(D.layer),route:V,stroke_width:D.stroke.width}):D.layer.endsWith(".Fab")?c.push({type:"pcb_fabrication_note_path",fabrication_note_path_id:`fabrication_note_path_${M++}`,pcb_component_id:v,layer:Go(D.layer),route:V,stroke_width:D.stroke.width,port_hints:[]}):bI("Unhandled layer for fp_poly",D.layer)}for(let D of i){let V=gI(D.start),X=gI(D.mid),W=gI(D.end),Q=Qwt(V,X,W),J=tSt(V,X,W,Math.ceil(Q));c.push({type:"pcb_silkscreen_path",pcb_silkscreen_path_id:`pcb_silkscreen_path_${k++}`,layer:Go(D.layer),pcb_component_id:v,route:J.map(_t=>({x:_t.x,y:-_t.y})),stroke_width:D.stroke.width})}for(let D of n){let V=Go(D.layer);D.layer.endsWith(".SilkS")?c.push({type:"pcb_silkscreen_text",layer:V,font:"tscircuit2024",font_size:D.effects?.font?.size[0]??1,pcb_component_id:v,anchor_position:{x:D.at[0],y:-D.at[1]},anchor_alignment:"center",text:D.text}):D.layer.endsWith(".Fab")?c.push({type:"pcb_fabrication_note_text",layer:V,font:"tscircuit2024",font_size:D.effects?.font?.size[0]??1,pcb_component_id:v,anchor_position:{x:D.at[0],y:-D.at[1]},anchor_alignment:"center",text:D.text}):bI("Unhandled layer for fp_text",D.layer)}let A=o.find(D=>D.key==="Reference"),L=o.find(D=>D.key==="Value"),B=[A,L].filter(D=>D&&!!D.val);for(let D of B){let V=D.attributes.at;V&&c.push({type:"pcb_silkscreen_text",layer:"top",font:"tscircuit2024",font_size:1.27,pcb_component_id:v,anchor_position:{x:V[0],y:-V[1]},anchor_alignment:"center",text:D.val})}return c},ZX=async e=>{let t=Jwt(e);return await iSt(t)};var rSt="https://kicad-mod-cache.tscircuit.com",KX=()=>({partsEngine:zX,footprintLibraryMap:{kicad:async e=>{let t=`${rSt}/${e}`,n=`${t}.circuit.json`,r=await(await fetch(n)).json(),o=Array.isArray(r)?r.filter(a=>a?.type==="pcb_silkscreen_text"?a?.text==="REF**":!0):r,s=`${t}.wrl`;return{footprintCircuitJson:o,cadModel:{wrlUrl:s,modelUnitToMmScale:2.54}}}},footprintFileParserMap:{kicad_mod:{loadFromUrl:async e=>{let t=await ZX(atob(e.replace("data:text/plain;base64,","")));return{footprintCircuitJson:Array.isArray(t)?t:[t]}}}}});var vI=Xt(Pn(),1),mWt=(0,vI.default)("tsci:eval:execution-context");function Vx(e,t={}){globalThis.React=JX;let n=t.platform||KX(),i=t.projectConfig?{...n,...t.projectConfig}:n,r=new eh({platform:i});return t.name&&(r.name=t.name),t.debugNamespace&&r.enableDebug(t.debugNamespace),{fsMap:{},entrypoint:"",preSuppliedImports:{"@tscircuit/core":Dx,tscircuit:Dx,"@tscircuit/math-utils":I5,react:JX,debug:vI.default,"@tscircuit/props":{}},circuit:r,...e}}function Ff(e){let t=e;return t=t.replace(/\\/g,"/"),t=t.trim(),t.startsWith("./")&&(t=t.slice(2)),t.startsWith("/")&&(t=t.slice(1)),t}function QX(e){let t={};for(let[n,i]of Object.entries(e))t[Ff(n)]=i;return t}function go(e){if(!e)return".";let n=e.replace(/\\/g,"/").replace(/\/+$/,"");return n.indexOf("/")===-1?".":n.substring(0,n.lastIndexOf("/"))||"/"}function wI(e,t){if(e.startsWith("../")){let n=go(t);return wI(e.slice(3),n)}return e.startsWith("./")?wI(e.slice(2),t):e.startsWith("/")?e.slice(1):`${t}/${e}`}var zf=(e,t,n)=>{let i=n?wI(e,n):e,r=new Set(Array.isArray(t)?t:Object.keys(t));if(r.has(i))return i;let o=new Map;for(let c of r)o.set(Ff(c),c);let s=Ff(i);if(o.has(s))return o.get(s);let a=["tsx","ts","json","js","jsx","obj","gltf","glb"];for(let c of a){let l=`${s}.${c}`;if(o.has(l))return o.get(l)}if(!e.startsWith("./")&&!e.startsWith("../")){let c=Ff(e);if(o.has(c))return o.get(c);for(let l of a){let u=`${c}.${l}`;if(o.has(u))return o.get(u)}}return null},Hx=(e,t)=>{let n=zf(e,t);if(!n)throw new Error(`File not found "${e}", available paths:
233
+ "${n.message}"`)});if(e.view==="pcb")return t.convertCircuitJsonToPcbSvg(this.getCircuitJson());if(e.view==="schematic")return t.convertCircuitJsonToSchematicSvg(this.getCircuitJson());throw new Error(`Invalid view: ${e.view}`)}getCoreVersion(){let[e,t,n]=Mwt.version.split(".").map(Number);return`${e}.${t}.${n+1}`}async preview(e){let t=typeof e=="object"?e:{previewName:e};throw new Error("project.preview is not yet implemented")}computeSchematicGlobalTransform(){return vi()}_computePcbGlobalTransformBeforeLayout(){return vi()}selectAll(e){return this._guessRootComponent(),this.firstChild?.selectAll(e)??[]}selectOne(e,t){return this._guessRootComponent(),this.firstChild?.selectOne(e,t)??null}emit(e,...t){if(this._eventListeners[e])for(let n of this._eventListeners[e])n(...t)}on(e,t){this._eventListeners[e]||(this._eventListeners[e]=[]),this._eventListeners[e].push(t)}removeListener(e,t){this._eventListeners[e]&&(this._eventListeners[e]=this._eventListeners[e].filter(n=>n!==t))}enableDebug(e){typeof e=="string"?rI.default.enable(e):(e===null||e===!1)&&rI.default.disable()}getClientOrigin(){return typeof window<"u"&&window.location?window.location.origin:typeof self<"u"&&self.location?self.location.origin:""}},Ewt=eh,Cwt=eh,kwt=e=>{let[t,n]=Kp.default.useState(!0),[i,r]=Kp.default.useState(null),[o,s]=Kp.default.useState(),[a,c]=Kp.default.useState();return Kp.default.useEffect(()=>{n(!0),r(null),e&&setTimeout(()=>{try{let l=new eh;l.add(e),s(l),c(l.toJson())}catch(l){r(l)}n(!1)},1)},[e]),{isLoading:t,error:i,circuit:o,circuitJson:a}},nh=(e,t)=>(n,i)=>{let r=[];Array.isArray(t)?r.push(...t.flat()):typeof t=="object"&&r.push(...Object.values(t).flat(),...Object.keys(t));let o=s=>{if(s?.name&&s.name!==n)throw new Error(`Component name mismatch. Hook name: ${n}, Component prop name: ${s.name}`);let a={...i,...s,name:n},c=[];for(let l of r)if(a[l]){let u=`.${n} > .${l}`,h=a[l];c.push({from:u,to:h}),delete a[l]}return(0,Ml.jsxs)(Ml.Fragment,{children:[(0,Ml.jsx)(e,{...a}),c.map((l,u)=>(0,Ml.jsx)("trace",{...l},u))]})};for(let s of r)o[s]=`.${n} > .${s}`;return o},Awt=nh(e=>(0,CX.jsx)("capacitor",{...e}),PL),Nwt=e=>nh(t=>(0,kX.jsx)("chip",{pinLabels:e,...t}),e),Rwt=nh(e=>(0,AX.jsx)("diode",{...e}),BL),Owt=nh(e=>(0,NX.jsx)("led",{...e}),YL),Lwt=nh(e=>(0,RX.jsx)("resistor",{...e}),xL),Fwt=new Proxy(e=>new Proxy({},{get:(t,n)=>`.${e} > .${n}`}),{get:(e,t)=>{let n=(...i)=>{let r=i[0];return new Proxy({},{get:(o,s)=>`.${t} > .${s}`})};return new Proxy(n,{get:(i,r)=>t==="net"?`net.${r}`:t==="subcircuit"?new Proxy({},{get:(o,s)=>new Proxy({},{get:(a,c)=>`subcircuit.${r} > .${s} > .${c}`})}):`.${t} > .${r}`,apply:(i,r,o)=>t==="net"?new Proxy({},{get:(s,a)=>`net.${a}`}):new Proxy({},{get:(s,a)=>{let c=`.${t} > .${a}`;return["U","J","CN"].some(u=>t.startsWith(u))?c:new Proxy(new String(c),{get:(u,h)=>typeof h=="symbol"||h==="toString"?()=>c:`.${t} > .${a} > .${h}`})}})})}});yY(dY);yY({Bug:zx});var JX=Xt(co(),1);var LX=e=>{let t=e.match(/:[RC]_(\d{4})_/);if(t||(t=e.match(/:(SOIC-\d+|SOT-\d+|SOD-\d+|SSOP-\d+|TSSOP-\d+|QFP-\d+|QFN-\d+)/),t))return t[1]};var mI=e=>e.includes("cap")?e.replace(/cap/g,""):e;var FX=e=>{if(e){if(e.startsWith("kicad:")){let t=LX(e);return t?mI(t):e}return mI(e)}};var _I=new Map,Gi=async(e,t)=>{let n=new URLSearchParams({...t,json:"true"}).toString();if(_I.has(n))return _I.get(n);let r=await(await fetch(`https://jlcsearch.tscircuit.com/${e}/list?${n}`)).json();return _I.set(n,r),r},Ui=e=>e?[...e].sort((t,n)=>Number(n.is_basic??!1)-Number(t.is_basic??!1)):[],zX={findPart:async({sourceComponent:e,footprinterString:t})=>{let n=FX(t);if(e.type==="source_component"&&e.ftype==="simple_resistor"){let{resistors:i}=await Gi("resistors",{resistance:e.resistance,package:n});return{jlcpcb:Ui(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_capacitor"){let{capacitors:i}=await Gi("capacitors",{capacitance:e.capacitance,package:n});return{jlcpcb:Ui(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_pin_header"){let i;t?.includes("_p")&&(i=Number(t.split("_p")[1]));let{headers:r}=await Gi("headers",i?{pitch:i,num_pins:e.pin_count,gender:e.gender}:{num_pins:e.pin_count,gender:e.gender});return{jlcpcb:Ui(r).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_potentiometer"){let{potentiometers:i}=await Gi("potentiometers",{resistance:e.max_resistance,package:n});return{jlcpcb:Ui(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_diode"){let{diodes:i}=await Gi("diodes",{package:n});return{jlcpcb:Ui(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_chip"){let{chips:i}=await Gi("chips",{package:n});return{jlcpcb:Ui(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_transistor"){let{transistors:i}=await Gi("transistors",{package:n,transistor_type:e.transistor_type});return{jlcpcb:Ui(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_power_source"){let{power_sources:i}=await Gi("power_sources",{voltage:e.voltage,package:n});return{jlcpcb:Ui(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_inductor"){let{inductors:i}=await Gi("inductors",{inductance:e.inductance,package:n});return{jlcpcb:Ui(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_crystal"){let{crystals:i}=await Gi("crystals",{frequency:e.frequency,load_capacitance:e.load_capacitance,package:n});return{jlcpcb:Ui(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_mosfet"){let{mosfets:i}=await Gi("mosfets",{package:n,mosfet_mode:e.mosfet_mode,channel_type:e.channel_type});return{jlcpcb:Ui(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_resonator"){let{resonators:i}=await Gi("resonators",{frequency:e.frequency,package:n});return{jlcpcb:Ui(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_switch"){let{switches:i}=await Gi("switches",{switch_type:e.type,package:n});return{jlcpcb:Ui(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_led"){let{leds:i}=await Gi("leds",{package:n});return{jlcpcb:Ui(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_fuse"){let{fuses:i}=await Gi("fuses",{package:n});return{jlcpcb:Ui(i).map(r=>`C${r.lcsc}`).slice(0,3)}}return{}}};var jX=Xt(DX(),1);Z();var GX=Xt(Pn(),1),UX=Xt(Pn(),1),qi=p.tuple([p.coerce.number(),p.coerce.number()]),Gwt=p.tuple([p.number(),p.number(),p.number()]),Xx=p.union([qi,Gwt]),YX=p.object({at:Xx,size:qi,layers:p.array(p.string()),roundrect_rratio:p.number(),uuid:p.string()}).partial(),Uwt=p.object({key:p.string(),val:p.string(),attributes:YX}),Bx=p.object({oval:p.boolean().default(!1),width:p.number().optional(),height:p.number().optional(),offset:qi.optional()}),XX=p.object({name:p.string(),pad_type:p.enum(["thru_hole","smd","np_thru_hole","connect"]),pad_shape:p.enum(["roundrect","circle","rect","oval","trapezoid","custom"]),at:Xx,drill:p.union([p.number(),p.array(p.any()),Bx]).transform(e=>typeof e=="number"?{oval:!1,width:e,height:e}:"oval"in e?e:e.length===2?{oval:!1,width:Number.parseFloat(e[0]),height:Number.parseFloat(e[0]),offset:qi.parse(e[1].slice(1))}:e.length===3||e.length===4?{oval:e[0]==="oval",width:Number.parseFloat(e[1]),height:Number.parseFloat(e[2]),offset:e[3]?qi.parse(e[3].slice(1)):void 0}:e).pipe(Bx),size:p.union([p.array(p.number()).length(2).transform(([e,t])=>({width:e,height:t})),p.object({width:p.number(),height:p.number()})]),layers:p.array(p.string()).optional(),roundrect_rratio:p.number().optional(),uuid:p.string().optional()}),VX=p.object({name:p.string(),pad_type:p.enum(["thru_hole","smd","np_thru_hole","connect"]),pad_shape:p.enum(["roundrect","circle","rect","oval","trapezoid","custom"]),at:Xx,size:qi,drill:p.union([p.number(),p.array(p.any()),Bx]).transform(e=>typeof e=="number"?{oval:!1,width:e,height:e}:"oval"in e?e:e.length===2?{oval:!1,width:Number.parseFloat(e[0]),height:Number.parseFloat(e[0]),offset:qi.parse(e[1].slice(1))}:e.length===3||e.length===4?{oval:e[0]==="oval",width:Number.parseFloat(e[1]),height:Number.parseFloat(e[2]),offset:e[3]?qi.parse(e[3].slice(1)):void 0}:e).pipe(Bx).optional(),layers:p.array(p.string()).optional(),roundrect_rratio:p.number().optional(),chamfer_ratio:p.number().optional(),solder_paste_margin:p.number().optional(),solder_paste_margin_ratio:p.number().optional(),clearance:p.number().optional(),zone_connection:p.union([p.literal(0).describe("Pad is not connect to zone"),p.literal(1).describe("Pad is connected to zone using thermal relief"),p.literal(2).describe("Pad is connected to zone using solid fill")]).optional(),thermal_width:p.number().optional(),thermal_gap:p.number().optional(),uuid:p.string().optional()}),HX=p.object({font:p.object({size:qi,thickness:p.number().optional()})}).partial(),qwt=p.object({fp_text_type:p.literal("user"),text:p.string(),at:Xx,layer:p.string(),uuid:p.string().optional(),effects:HX.partial()}),Wwt=p.object({start:qi,mid:qi,end:qi,stroke:p.object({width:p.number(),type:p.string()}),layer:p.string(),uuid:p.string().optional()}),Zwt=p.object({pts:p.array(qi),stroke:p.object({width:p.number(),type:p.string()}).optional(),width:p.number().optional(),layer:p.string(),uuid:p.string().optional()}).transform(e=>({...e,width:void 0,stroke:e.stroke??{width:e.width}})),Kwt=p.object({start:qi,end:qi,stroke:p.object({width:p.number(),type:p.string()}).optional(),width:p.number().optional(),layer:p.string(),uuid:p.string().optional()}).transform(e=>({...e,width:void 0,stroke:e.stroke??{width:e.width}})),$X=p.object({footprint_name:p.string(),version:p.string().optional(),generator:p.string().optional(),generator_version:p.string().optional(),layer:p.string(),descr:p.string().default(""),tags:p.array(p.string()).optional(),properties:p.array(Uwt),fp_lines:p.array(Kwt),fp_texts:p.array(qwt),fp_arcs:p.array(Wwt),fp_polys:p.array(Zwt).optional(),pads:p.array(VX),holes:p.array(XX).optional()}),jx=(e,t)=>{if(t==="effects"&&Array.isArray(e)){let n={};for(let i of e)if(i[0]==="font"){let r={};for(let o of i.slice(1))o.length===2?r[o[0].valueOf()]=Number.parseFloat(o[1].valueOf()):r[o[0].valueOf()]=o.slice(1).map(s=>Number.parseFloat(s.valueOf()));n.font=r}return HX.parse(n)}if(t==="pts")return e.map(n=>n.slice(1).map(i=>Number.parseFloat(i.valueOf())));if(t==="stroke"){let n={};for(let i of e){let r=i[0].valueOf();n[r]=jx(i.slice(1),r)}return n}return t==="at"||t==="size"||t==="start"||t==="mid"||t==="end"?(Array.isArray(e)?e:[e]).map(i=>i?.valueOf?.()??i).filter(i=>typeof i=="number"||typeof i=="string"&&/^[-+]?\d*\.?\d+(e[-+]?\d+)?$/i.test(i)).map(i=>typeof i=="number"?i:Number.parseFloat(i)):t==="tags"?e.map(n=>n.valueOf()):t==="generator_version"||t==="version"?e[0].valueOf():e.length===2?e.valueOf():t==="uuid"?Array.isArray(e)?e[0].valueOf():e.valueOf():/^[\d\.]+$/.test(e)&&!Number.isNaN(Number.parseFloat(e))?Number.parseFloat(e):Array.isArray(e)&&e.length===1?e[0].valueOf():Array.isArray(e)?e.map(n=>n.valueOf()):e},Ke=(e,t)=>{for(let n of e)if(Array.isArray(n)&&n[0]===t)return jx(n.slice(1),t)},yI=(0,GX.default)("kicad-mod-converter"),Jwt=e=>{let t=(0,jX.default)(e),n=t[1].valueOf(),i={},r=Object.entries($X.shape).filter(([w,S])=>S._def.typeName==="ZodString"||w==="tags").map(([w])=>w);for(let w of t.slice(2)){if(!r.includes(w[0]))continue;let S=w[0].valueOf(),C=jx(w.slice(1),S);i[S]=C}let o=t.slice(2).filter(w=>w[0]==="property").map(w=>{let S=w[1].valueOf(),C=w[2].valueOf(),E=YX.parse(w.slice(3).reduce((R,I)=>{let k=I[0].valueOf();return R[k]=jx(I.slice(1),k),R},{}));return{key:S,val:C,attributes:E}}),s=t.slice(2).filter(w=>w[0]==="pad"),a=[];for(let w of s){let S=Ke(w,"at"),C=Ke(w,"size"),E=Ke(w,"drill"),R=Ke(w,"layers");if(Array.isArray(R)?R=R.map(A=>A.valueOf()):typeof R=="string"?R=[R]:R||(R=[]),!R.includes("F.Cu")){yI(`Skipping pad without F.Cu layer: layers=${R.join(", ")}`);continue}let I=Ke(w,"roundrect_rratio"),k=Ke(w,"uuid"),M={name:w[1].valueOf(),pad_type:w[2].valueOf(),pad_shape:w[3].valueOf(),at:S,drill:E,size:C,layers:R,roundrect_rratio:I,uuid:k};yI(`attempting to parse pad: ${JSON.stringify(M,null," ")}`),a.push(VX.parse(M))}let c=t.slice(2).filter(w=>w[0]==="fp_text"),l=[];for(let w of c){let S=w[2].valueOf(),C=Ke(w,"at"),E=Ke(w,"layer"),R=Ke(w,"uuid"),I=Ke(w,"effects");l.push({fp_text_type:"user",text:S,at:C,layer:E,uuid:R,effects:I})}let u=[],h=t.slice(2).filter(w=>w[0]==="fp_line");for(let w of h){let S=Ke(w,"start"),C=Ke(w,"end"),E=Ke(w,"stroke"),R=Ke(w,"layer"),I=Ke(w,"uuid");u.push({start:S,end:C,stroke:E,layer:R,uuid:I})}let f=[],_=t.slice(2).filter(w=>w[0]==="fp_arc");for(let w of _){let S=Ke(w,"start"),C=Ke(w,"mid"),E=Ke(w,"end"),R=Ke(w,"stroke"),I=Ke(w,"layer"),k=Ke(w,"uuid");!S||!E||!C||!R||!I||f.push({start:S,mid:C,end:E,stroke:R,layer:I,uuid:k})}let y=[],x=t.slice(2).filter(w=>w[0]==="fp_poly");for(let w of x){let S=Ke(w,"pts"),C=Ke(w,"stroke"),E=Ke(w,"layer"),R=Ke(w,"uuid");y.push({pts:S,stroke:C,layer:E,uuid:R})}let v=[];for(let w of t.slice(2)){if(w[0]!=="pad"||w[2]?.valueOf?.()!=="thru_hole")continue;let S=w[1]?.valueOf?.(),C=w[2]?.valueOf?.(),E=w[3]?.valueOf?.(),R=Ke(w,"at"),I=Ke(w,"drill"),k=Ke(w,"size");Array.isArray(k)&&(k[0]==="size"&&(k=k.slice(1)),k={width:Number(k[0]),height:Number(k[1])});let M=Ke(w,"uuid"),A=Ke(w,"roundrect_rratio"),L=Ke(w,"layers");Array.isArray(L)?L=L.map(D=>D.valueOf()):typeof L=="string"?L=[L]:L||(L=[]);let B={name:S,pad_type:C,pad_shape:E,at:R,drill:I,size:k,layers:L,roundrect_rratio:A,uuid:M};yI(`attempting to parse holes: ${JSON.stringify(B,null,2)}`),v.push(XX.parse(B))}return $X.parse({footprint_name:n,...i,properties:o,fp_lines:u,fp_texts:l,fp_arcs:f,pads:a,holes:v,fp_polys:y})};function qX(e,t,n){let i={x:(e.x+t.x)/2,y:(e.y+t.y)/2},r={x:(t.x+n.x)/2,y:(t.y+n.y)/2},o=-(e.x-t.x)/(e.y-t.y),s=-(t.x-n.x)/(t.y-n.y),a=(i.y-r.y+s*r.x-o*i.x)/(s-o),c=i.y+o*(a-i.x);return{x:a,y:c}}function WX(e,t){return Math.sqrt((e.x-t.x)**2+(e.y-t.y)**2)}function Yx(e,t){return Math.atan2(t.y-e.y,t.x-e.x)}var Qwt=(e,t,n)=>{let i=qX(e,t,n),r=WX(i,e),o=Yx(i,e),a=Yx(i,n)-o;return a<0&&(a+=2*Math.PI),r*a};function tSt(e,t,n,i){let r=qX(e,t,n),o=WX(r,e),s=Yx(r,e),c=Yx(r,n)-s;c<0&&(c+=2*Math.PI);let l=[];for(let u=0;u<=i;u++){let h=s+u/i*c,f=r.x+o*Math.cos(h),_=r.y+o*Math.sin(h);l.push({x:f,y:_})}return l}var gI=e=>Array.isArray(e)?{x:e[0],y:e[1]}:e,eSt=e=>e*Math.PI/180,xI=(e,t,n)=>{let i=eSt(n),r=Math.cos(i),o=Math.sin(i);return{x:e*r-t*o,y:e*o+t*r}},nSt=e=>{let t=[...new Map(e.map(u=>[`${u.x},${u.y}`,u])).values()];if(t.length!==4)return null;let n=t.map(u=>u.x),i=t.map(u=>u.y),r=[...new Set(n)],o=[...new Set(i)];if(r.length!==2||o.length!==2)return null;let[s,a]=r.sort((u,h)=>u-h),[c,l]=o.sort((u,h)=>u-h);return s===void 0||a===void 0||c===void 0||l===void 0?null:{x:(s+a)/2,y:(c+l)/2,width:a-s,height:l-c}},BX=e=>e&&Array.isArray(e)&&e.length>=3&&typeof e[2]=="number"?e[2]:0,Jr=e=>{let t=(e%360+360)%360;return t===90||t===270},bI=(0,UX.default)("kicad-mod-converter"),Go=e=>{switch(e){case"F.Cu":case"F.Fab":case"F.SilkS":return"top";case"B.Cu":case"B.Fab":case"B.SilkS":return"bottom"}},iSt=async e=>{let{fp_lines:t,fp_texts:n,fp_arcs:i,pads:r,properties:o,holes:s,fp_polys:a}=e,c=[];c.push({type:"source_component",source_component_id:"source_component_0",supplier_part_numbers:{}}),c.push({type:"schematic_component",schematic_component_id:"schematic_component_0",source_component_id:"source_component_0",center:{x:0,y:0},rotation:0,size:{width:0,height:0}});let l=new Set;for(let D of r)D.name&&l.add(D.name);if(s)for(let D of s)D.name&&l.add(D.name);let u=0,h=new Map;for(let D of l){let V=`source_port_${u++}`;h.set(D,V),c.push({type:"source_port",source_port_id:V,source_component_id:"source_component_0",name:D,port_hints:[D]}),c.push({type:"schematic_port",schematic_port_id:`schematic_port_${u++}`,source_port_id:V,schematic_component_id:"schematic_component_0",center:{x:0,y:0}})}let f=Number.POSITIVE_INFINITY,_=Number.NEGATIVE_INFINITY,y=Number.POSITIVE_INFINITY,x=Number.NEGATIVE_INFINITY;for(let D of r){let V=D.at[0],X=-D.at[1],W=D.size[0],Q=D.size[1];f=Math.min(f,V-W/2),_=Math.max(_,V+W/2),y=Math.min(y,X-Q/2),x=Math.max(x,X+Q/2)}let v="pcb_component_0";c.push({type:"pcb_component",source_component_id:"source_component_0",pcb_component_id:v,layer:"top",center:{x:0,y:0},rotation:0,width:Number.isFinite(f)?_-f:0,height:Number.isFinite(y)?x-y:0});let w=0,S=new Map;for(let D of l){let V=`pcb_port_${w++}`,X=h.get(D);S.set(D,V);let W=0,Q=0,J=["top","bottom"],_t=r.find(st=>st.name===D);if(_t)W=_t.at[0],Q=-_t.at[1],J=_t.layers?_t.layers.map(st=>Go(st)).filter(Boolean):["top","bottom"];else if(s){let st=s.find(it=>it.name===D);st&&(W=st.at[0],Q=-st.at[1],J=st.layers?st.layers.map(it=>Go(it)).filter(Boolean):["top","bottom"])}c.push({type:"pcb_port",pcb_port_id:V,source_port_id:X,pcb_component_id:v,x:W,y:Q,layers:J})}let C=0,E=0,R=0;for(let D of r)if(D.pad_type==="smd"){let V=D.name?S.get(D.name):void 0;c.push({type:"pcb_smtpad",pcb_smtpad_id:`pcb_smtpad_${C++}`,shape:"rect",x:D.at[0],y:-D.at[1],width:D.size[0],height:D.size[1],layer:Go(D.layers?.[0]??"F.Cu"),pcb_component_id:v,port_hints:[D.name],pcb_port_id:V})}else if(D.pad_type==="thru_hole"){if(D.pad_shape==="rect"){let V=BX(D.at),X=Jr(V)?D.size[1]:D.size[0],W=Jr(V)?D.size[0]:D.size[1],Q=D.drill?.offset?.[0]??0,J=D.drill?.offset?.[1]??0,_t=xI(Q,J,V),st=D.name?S.get(D.name):void 0;c.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"circular_hole_with_rect_pad",hole_shape:"circle",pad_shape:"rect",x:D.at[0],y:-D.at[1],hole_offset_x:_t.x,hole_offset_y:-_t.y,hole_diameter:D.drill?.width,rect_pad_width:X,rect_pad_height:W,layers:["top","bottom"],pcb_component_id:v,port_hints:[D.name],pcb_port_id:st})}else if(D.pad_shape==="circle"){let V=D.name?S.get(D.name):void 0;c.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"circle",x:D.at[0],y:-D.at[1],outer_diameter:D.size[0],hole_diameter:D.drill?.width,layers:["top","bottom"],pcb_component_id:v,port_hints:[D.name],pcb_port_id:V})}else if(D.pad_shape==="oval"){let V=D.name?S.get(D.name):void 0;c.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"pill",x:D.at[0],y:-D.at[1],outer_width:D.size[0],outer_height:D.size[1],hole_width:D.drill?.width,hole_height:D.drill?.height,layers:["top","bottom"],pcb_component_id:v,port_hints:[D.name],pcb_port_id:V})}}else D.pad_type==="np_thru_hole"&&c.push({type:"pcb_hole",pcb_hole_id:`pcb_hole_${R++}`,x:D.at[0],y:-D.at[1],hole_diameter:D.drill?.width,pcb_component_id:v});if(s)for(let D of s){let V=D.layers?.some(Tt=>Tt.endsWith(".Cu")||Tt==="*.Cu"),X=BX(D.at),W=D.drill?.offset?.[0]??0,Q=D.drill?.offset?.[1]??0,J=xI(W,Q,X),_t=D.at[0]+J.x,st=-(D.at[1]+J.y),it=D.drill?.width??0,et=D.size?.width??it,vt=D.roundrect_rratio??0,mt=vt>0?Math.min(Jr(X)?D.size?.height??et:D.size?.width??et,Jr(X)?D.size?.width??et:D.size?.height??et)/2*vt:0;if(V)if(D.pad_shape==="rect"){let Tt=D.name?S.get(D.name):void 0;c.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"circular_hole_with_rect_pad",hole_shape:"circle",pad_shape:"rect",x:D.at[0],y:-D.at[1],hole_offset_x:J.x,hole_offset_y:-J.y,hole_diameter:it,rect_pad_width:Jr(X)?D.size?.height??et:D.size?.width??et,rect_pad_height:Jr(X)?D.size?.width??et:D.size?.height??et,rect_border_radius:mt,port_hints:[D.name],layers:["top","bottom"],pcb_component_id:v,pcb_port_id:Tt})}else if(D.pad_shape==="oval"){let Tt=D.name?S.get(D.name):void 0;c.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"pill",x:_t,y:st,outer_width:Jr(X)?D.size?.height??et:D.size?.width??et,outer_height:Jr(X)?D.size?.width??et:D.size?.height??et,hole_width:Jr(X)?D.drill?.height??it:D.drill?.width??it,hole_height:Jr(X)?D.drill?.width??it:D.drill?.height??it,port_hints:[D.name],layers:["top","bottom"],pcb_component_id:v,pcb_port_id:Tt})}else if(D.pad_shape==="roundrect"){let Tt=D.name?S.get(D.name):void 0,Ot=D.drill?.offset?.[0]??0,pt=D.drill?.offset?.[1]??0,j=xI(Ot,pt,X),q=Jr(X)?D.size?.height??et:D.size?.width??et,Y=Jr(X)?D.size?.width??et:D.size?.height??et;c.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"circular_hole_with_rect_pad",hole_shape:"circle",pad_shape:"rect",x:_t,y:st,hole_offset_x:j.x,hole_offset_y:-j.y,hole_diameter:it,rect_pad_width:q,rect_pad_height:Y,rect_border_radius:mt,port_hints:[D.name],layers:["top","bottom"],pcb_component_id:v,pcb_port_id:Tt})}else{let Tt=D.name?S.get(D.name):void 0;c.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"circle",x:_t,y:st,outer_diameter:et,hole_diameter:it,port_hints:[D.name],layers:["top","bottom"],pcb_component_id:v,pcb_port_id:Tt})}else c.push({type:"pcb_hole",pcb_hole_id:`pcb_hole_${R++}`,x:_t,y:st,hole_diameter:et,hole_shape:"circle",pcb_component_id:v})}let I=0,k=0,M=0;for(let D of t){let V=[{x:D.start[0],y:-D.start[1]},{x:D.end[0],y:-D.end[1]}];D.layer==="F.Cu"?c.push({type:"pcb_trace",pcb_trace_id:`pcb_trace_${I++}`,pcb_component_id:v,layer:Go(D.layer),route:V,thickness:D.stroke.width}):D.layer==="F.SilkS"?c.push({type:"pcb_silkscreen_path",pcb_silkscreen_path_id:`pcb_silkscreen_path_${k++}`,pcb_component_id:v,layer:"top",route:V,stroke_width:D.stroke.width}):D.layer==="F.Fab"?c.push({type:"pcb_fabrication_note_path",fabrication_note_path_id:`fabrication_note_path_${M++}`,pcb_component_id:v,layer:"top",route:V,stroke_width:D.stroke.width,port_hints:[]}):bI("Unhandled layer for fp_line",D.layer)}if(a)for(let D of a){let V=D.pts.map(X=>({x:X[0],y:-X[1]}));if(D.layer.endsWith(".Cu")){let X=nSt(V);X?c.push({type:"pcb_smtpad",pcb_smtpad_id:`pcb_smtpad_${C++}`,shape:"rect",x:X.x,y:X.y,width:X.width,height:X.height,layer:Go(D.layer),pcb_component_id:v}):c.push({type:"pcb_trace",pcb_trace_id:`pcb_trace_${I++}`,pcb_component_id:v,layer:Go(D.layer),route:V,thickness:D.stroke.width})}else D.layer.endsWith(".SilkS")?c.push({type:"pcb_silkscreen_path",pcb_silkscreen_path_id:`pcb_silkscreen_path_${k++}`,pcb_component_id:v,layer:Go(D.layer),route:V,stroke_width:D.stroke.width}):D.layer.endsWith(".Fab")?c.push({type:"pcb_fabrication_note_path",fabrication_note_path_id:`fabrication_note_path_${M++}`,pcb_component_id:v,layer:Go(D.layer),route:V,stroke_width:D.stroke.width,port_hints:[]}):bI("Unhandled layer for fp_poly",D.layer)}for(let D of i){let V=gI(D.start),X=gI(D.mid),W=gI(D.end),Q=Qwt(V,X,W),J=tSt(V,X,W,Math.ceil(Q));c.push({type:"pcb_silkscreen_path",pcb_silkscreen_path_id:`pcb_silkscreen_path_${k++}`,layer:Go(D.layer),pcb_component_id:v,route:J.map(_t=>({x:_t.x,y:-_t.y})),stroke_width:D.stroke.width})}for(let D of n){let V=Go(D.layer);D.layer.endsWith(".SilkS")?c.push({type:"pcb_silkscreen_text",layer:V,font:"tscircuit2024",font_size:D.effects?.font?.size[0]??1,pcb_component_id:v,anchor_position:{x:D.at[0],y:-D.at[1]},anchor_alignment:"center",text:D.text}):D.layer.endsWith(".Fab")?c.push({type:"pcb_fabrication_note_text",layer:V,font:"tscircuit2024",font_size:D.effects?.font?.size[0]??1,pcb_component_id:v,anchor_position:{x:D.at[0],y:-D.at[1]},anchor_alignment:"center",text:D.text}):bI("Unhandled layer for fp_text",D.layer)}let A=o.find(D=>D.key==="Reference"),L=o.find(D=>D.key==="Value"),B=[A,L].filter(D=>D&&!!D.val);for(let D of B){let V=D.attributes.at;V&&c.push({type:"pcb_silkscreen_text",layer:"top",font:"tscircuit2024",font_size:1.27,pcb_component_id:v,anchor_position:{x:V[0],y:-V[1]},anchor_alignment:"center",text:D.val})}return c},ZX=async e=>{let t=Jwt(e);return await iSt(t)};var rSt="https://kicad-mod-cache.tscircuit.com",KX=()=>({partsEngine:zX,footprintLibraryMap:{kicad:async e=>{let t=`${rSt}/${e}`,n=`${t}.circuit.json`,r=await(await fetch(n)).json(),o=Array.isArray(r)?r.filter(a=>a?.type==="pcb_silkscreen_text"?a?.text==="REF**":!0):r,s=`${t}.wrl`;return{footprintCircuitJson:o,cadModel:{wrlUrl:s,modelUnitToMmScale:2.54}}}},footprintFileParserMap:{kicad_mod:{loadFromUrl:async e=>{let t=await fetch(e).then(i=>i.text()),n=await ZX(t);return{footprintCircuitJson:Array.isArray(n)?n:[n]}}}}});var vI=Xt(Pn(),1),mWt=(0,vI.default)("tsci:eval:execution-context");function Vx(e,t={}){globalThis.React=JX;let n=t.platform||KX(),i=t.projectConfig?{...n,...t.projectConfig}:n,r=new eh({platform:i});return t.name&&(r.name=t.name),t.debugNamespace&&r.enableDebug(t.debugNamespace),{fsMap:{},entrypoint:"",preSuppliedImports:{"@tscircuit/core":Dx,tscircuit:Dx,"@tscircuit/math-utils":I5,react:JX,debug:vI.default,"@tscircuit/props":{}},circuit:r,...e}}function Ff(e){let t=e;return t=t.replace(/\\/g,"/"),t=t.trim(),t.startsWith("./")&&(t=t.slice(2)),t.startsWith("/")&&(t=t.slice(1)),t}function QX(e){let t={};for(let[n,i]of Object.entries(e))t[Ff(n)]=i;return t}function go(e){if(!e)return".";let n=e.replace(/\\/g,"/").replace(/\/+$/,"");return n.indexOf("/")===-1?".":n.substring(0,n.lastIndexOf("/"))||"/"}function wI(e,t){if(e.startsWith("../")){let n=go(t);return wI(e.slice(3),n)}return e.startsWith("./")?wI(e.slice(2),t):e.startsWith("/")?e.slice(1):`${t}/${e}`}var zf=(e,t,n)=>{let i=n?wI(e,n):e,r=new Set(Array.isArray(t)?t:Object.keys(t));if(r.has(i))return i;let o=new Map;for(let c of r)o.set(Ff(c),c);let s=Ff(i);if(o.has(s))return o.get(s);let a=["tsx","ts","json","js","jsx","obj","gltf","glb"];for(let c of a){let l=`${s}.${c}`;if(o.has(l))return o.get(l)}if(!e.startsWith("./")&&!e.startsWith("../")){let c=Ff(e);if(o.has(c))return o.get(c);for(let l of a){let u=`${c}.${l}`;if(o.has(u))return o.get(u)}}return null},Hx=(e,t)=>{let n=zf(e,t);if(!n)throw new Error(`File not found "${e}", available paths:
234
234
 
235
235
  ${Object.keys(t).join(", ")}`);return n};var Gx=e=>{let t=/^\s*import\s+(?:(?:[\w\s]+,\s*)?(?:\*\s+as\s+[\w\s]+|\{[\s\w,]+\}|\w+)\s+from\s*)?['"](.+?)['"]/gm,n=[],i;for(;(i=t.exec(e))!==null;)n.push(i[1]);let r=/^\s*export\s+(?:\*|(?:\{[\s\w,]+\}))\s+from\s*['"](.+?)['"]/gm,o;for(;(o=r.exec(e))!==null;)n.push(o[1]);return n};function El(e,t,n){globalThis.__tscircuit_require=r=>{let o=zf(r,t,n),s=o&&t[o];if(!t[r]&&!s)throw new Error(`Import "${r}" not found ${n?`in "${n}"`:""}`);let a=t[r]||t[o];return new Proxy(a,{get(c,l){if(!(l in c)){if(l==="default")return c.default!==void 0?c.default:c.__esModule?void 0:typeof c=="function"||typeof c=="object"?c:void 0;if(l==="__esModule")return!0;throw new Error(`Component "${String(l)}" is not exported by "${r}"`)}return c[l]}})};let i=`
236
236
  var exports = {};