astra/am3352-sbc
A 4-layer AM3352 single-board computer with 128‑MiB DDR3, PMIC power regulation, USB‑C 5‑V PD input, dual USB host ports, HDMI output with ESD protection, microSD/UART/JTAG interfaces, addressable RGB indicators, and a PWM-driven buzzer.
- Version
- 0.1.19
- License
- unset
- Stars
- 0
dist/viewer-part-05.txt
n},w1o=[0,90,180,270],ESt=1e-6,$v=(t,e)=>t.x*e.x+t.y*e.y,P1o=({outwardCoordinate:t,tangentCoordinate:e,axes:n})=>({x:n.outward.x*t+n.tangent.x*e,y:n.outward.y*t+n.tangent.y*e}),M1o=({pinOffset:t})=>Math.abs(t.x)>=Math.abs(t.y)?{outward:Jk(t.x>=0?"right":"left"),tangent:Jk("up")}:{outward:Jk(t.y>=0?"up":"down"),tangent:Jk("right")},BSt=({size:t,axis:e})=>(Math.abs(e.x)*t.x+Math.abs(e.y)*t.y)/2,D1o=({chip:t,nearPinId:e,farPinId:n,inputProblem:o,outward:i,originalRotation:r})=>{const s=o.chipPinMap[e],a=o.chipPinMap[n];if(!s||!a)return r;const A=t.availableRotations??w1o;let c=A[0]??0,l=Number.NEGATIVE_INFINITY;for(const u of A){const g=ta(s.offset,u),h=ta(a.offset,u),d=$v({x:h.x-g.x,y:h.y-g.y},i);(d>l||d===l&&u===r)&&(l=d,c=u)}return c},rle=({chip:t,placement:e})=>{const n=dd(t.size,e.ccwRotationDegrees);return Ey({center:e,width:n.x,height:n.y})},bSt=({branch:t,mainPinId:e,mainChip:n,mainPlacement:o,inputProblem:i,axes:r,originalPlacements:s,extraGap:a})=>{const A=i.chipPinMap[e];if(!A)return null;const c=dd(n.size,o.ccwRotationDegrees),l=ta(A.offset,o.ccwRotationDegrees),u={x:o.x+l.x,y:o.y+l.y};let g=$v(o,r.outward)+BSt({size:c,axis:r.outward});g=Math.max(g,$v(u,r.outward));let h=$v(u,r.tangent);const d={};let p=g;for(const m of t){const _=i.chipMap[m.chipId],f=s[m.chipId],I=i.chipPinMap[m.nearPinId],C=i.chipPinMap[m.farPinId];if(!_||!f||!I||!C)return null;const y=D1o({chip:_,nearPinId:m.nearPinId,farPinId:m.farPinId,inputProblem:i,outward:r.outward,originalRotation:f.ccwRotationDegrees}),x=dd(_.size,y),E=BSt({size:x,axis:r.outward}),B=ta(I.offset,y),S=ta(C.offset,y),Q=g+i.chipGap+a+E,w=h-$v(B,r.tangent),M=P1o({outwardCoordinate:Q,tangentCoordinate:w,axes:r});d[_.chipId]={...M,ccwRotationDegrees:y},g=Q+E,h=w+$v(S,r.tangent),p=Q+$v(S,r.outward)}return{placements:d,terminalOutwardCoordinate:p}},SSt=({branchLayout:t,shift:e,tangent:n})=>{for(const o of Object.values(t.placements))o.x+=n.x*e,o.y+=n.y*e},QSt=({branchLayout:t,inputProblem:e,tangent:n})=>{const o=Oh(Object.entries(t.placements).flatMap(([i,r])=>{const s=rle({chip:e.chipMap[i],placement:r});return[{x:s.minX,y:s.minY},{x:s.maxX,y:s.maxY}]}));return o?Math.abs(n.x)>=Math.abs(n.y)?{min:o.minX,max:o.maxX}:{min:o.minY,max:o.maxY}:{min:0,max:0}},N1o=({candidatePlacements:t,originalPlacements:e,inputProblem:n})=>{const o=new Set(Object.keys(t)),i=Object.entries(t);for(let r=0;r<i.length;r++){const[s,a]=i[r],A=n.chipMap[s];if(!A)return!1;const c=rle({chip:A,placement:a});for(let l=r+1;l<i.length;l++){const[u,g]=i[l],h=n.chipMap[u];if(!h||EV(c,rle({chip:h,placement:g}))<n.chipGap-ESt)return!1}for(const[l,u]of Object.entries(e)){if(o.has(l))continue;const g=n.chipMap[l];if(!g||EV(c,rle({chip:g,placement:u}))<n.chipGap-ESt)return!1}}return!0},R1o=({group:t,chipPlacements:e,inputProblem:n})=>{const o=n.chipMap[t.mainChipId],i=e[t.mainChipId],r=n.chipPinMap[t.mainPinIds[0]];if(!o||!i||!r)return null;const s=ta(r.offset,i.ccwRotationDegrees),a=M1o({pinOffset:s}),A=t.branches.map((p,m)=>({branch:p,mainPinId:t.mainPinIds[m]})).sort((p,m)=>{const _=f=>{const I=n.chipPinMap[f],C=ta(I.offset,i.ccwRotationDegrees);return $v({x:i.x+C.x,y:i.y+C.y},a.tangent)};return _(p.mainPinId)-_(m.mainPinId)});let c=A.map(({branch:p,mainPinId:m})=>bSt({branch:p,mainPinId:m,mainChip:o,mainPlacement:i,inputProblem:n,axes:a,originalPlacements:e,extraGap:0}));if(c.some(p=>!p))return null;const l=Math.max(...c.map(p=>p.terminalOutwardCoordinate));if(c=A.map(({branch:p,mainPinId:m},_)=>{const f=c[_],I=(l-f.terminalOutwardCoordinate)/p.length;return bSt({branch:p,mainPinId:m,mainChip:o,mainPlacement:i,inputProblem:n,axes:a,originalPlacements:e,extraGap:I})}),c.some(p=>!p))return null;const u=QSt({branchLayout:c[0],inputProblem:n,tangent:a.tangent}),g=QSt({branchLayout:c[1],inputProblem:n,tangent:a.tangent}),h=Math.max(0,u.max+n.chipGap-g.min);SSt({branchLayout:c[0],shift:-h/2,tangent:a.tangent}),SSt({branchLayout:c[1],shift:h/2,tangent:a.tangent});const d=Object.assign({},c[0].placements,c[1].placements);return N1o({candidatePlacements:d,originalPlacements:e,inputProblem:n})?d:null},T1o=t=>xSt(t).length>0,k1o=class extends Zf{partitionInputProblem;layout=null;pinIdToStronglyConnectedPins;packingSolver=null;constructor(t){super(),this.partitionInputProblem=t.partitionInputProblem,this.pinIdToStronglyConnectedPins=t.pinIdToStronglyConnectedPins}_step(){if(this.packingSolver||(this.packingSolver=new Cve({partitionInputProblem:this.partitionInputProblem,pinIdToStronglyConnectedPins:this.pinIdToStronglyConnectedPins}),this.activeSubSolver=this.packingSolver),this.packingSolver.step(),this.packingSolver.failed){this.failed=!0,this.error=this.packingSolver.error;return}this.packingSolver.solved&&this.packingSolver.layout&&(this.layout=this.refinePackedLayout(this.packingSolver.layout),this.activeSubSolver=null,this.solved=!0)}refinePackedLayout(t){const e={};for(const[n,o]of Object.entries(t.chipPlacements))e[n]={...o};for(const n of xSt(this.partitionInputProblem)){const o=R1o({group:n,chipPlacements:e,inputProblem:this.partitionInputProblem});o&&Object.assign(e,o)}return{chipPlacements:e,groupPlacements:t.groupPlacements}}visualize(){if(this.activeSubSolver&&!this.solved)return this.activeSubSolver.visualize();if(!this.layout){const t=pb(this.partitionInputProblem);return Vh(this.partitionInputProblem,t)}return Vh(this.partitionInputProblem,this.layout)}getConstructorParams(){return[this.partitionInputProblem]}};function cj(t,e,n,o){return{solverName:t,solverClass:e,appliesTo:n,getConstructorParams:o}}var F1o=[cj("crystalCircuitLayoutSolver",b1o,B1o,t=>[{partitionInputProblem:t.partitions[t.currentPartitionIndex]}]),cj("decouplingCapRowSolver",C1o,I1o,t=>[{partitionInputProblem:t.partitions[t.currentPartitionIndex]}]),cj("parallelAlignedPassiveSolver",f1o,t=>ISt(t).length>0,t=>[{partitionInputProblem:t.partitions[t.currentPartitionIndex],pinIdToStronglyConnectedPins:t.pinIdToStronglyConnectedPins}]),cj("parallelSeriesBranchSolver",k1o,T1o,t=>[{partitionInputProblem:t.partitions[t.currentPartitionIndex],pinIdToStronglyConnectedPins:t.pinIdToStronglyConnectedPins}]),cj("singleInnerPartitionPackingSolver",Cve,()=>!0,t=>[{partitionInputProblem:t.partitions[t.currentPartitionIndex],pinIdToStronglyConnectedPins:t.pinIdToStronglyConnectedPins}])],L1o=class extends Zf{partitions;packedPartitions=[];completedSolvers=[];activeSolver=null;currentPartitionIndex=0;pinIdToStronglyConnectedPins;constructor(t){super(),this.partitions=t.partitions,this.pinIdToStronglyConnectedPins=t.pinIdToStronglyConnectedPins}_step(){if(this.currentPartitionIndex>=this.partitions.length){this.solved=!0;return}if(!this.activeSolver){const t=this.partitions[this.currentPartitionIndex],e=F1o.find(o=>o.appliesTo(t)),n=e.getConstructorParams(this);this.activeSolver=new e.solverClass(...n),this.activeSubSolver=this.activeSolver}if(this.activeSolver.step(),this.activeSolver.failed){this.failed=!0,this.error=`Partition ${this.currentPartitionIndex} failed: ${this.activeSolver.error}`;return}if(this.activeSolver.solved){if(this.completedSolvers.push(this.activeSolver),this.activeSolver.layout)this.packedPartitions.push({inputProblem:this.partitions[this.currentPartitionIndex],layout:this.activeSolver.layout});else{this.failed=!0,this.error=`Partition ${this.currentPartitionIndex} completed but has no layout`;return}this.activeSolver=null,this.activeSubSolver=null,this.currentPartitionIndex++}}visualize(){if(this.activeSolver)return this.activeSolver.visualize();if(this.completedSolvers.length===0){const n=this.partitions.map(i=>{const r=pb(i);return Vh(i,r)}),o=this.partitions.map((i,r)=>`partition${r}`);return zce(n,{titles:o})}const t=this.completedSolvers.map(n=>n.visualize()),e=this.completedSolvers.map((n,o)=>`packed_partition_${o}`);return zce(t,{titles:e})}getConstructorParams(){return[this.partitions]}},yve=1e-6,vSt=2,wSt=["x+","y+","x-","y-"],sle=(t,e)=>t===e?0:t<e?-1:1,PSt=(t,e)=>{const n=(Math.round(e/90)%4+4)%4,o=wSt.indexOf(t);return wSt[(o+n)%4]},ale=(t,e,n)=>{const o=t.chipPinMap[e],i=ta(o.offset,n.ccwRotationDegrees);return{x:n.x+i.x,y:n.y+i.y}},H1o=(t,e)=>t.distanceSquared-e.distanceSquared||Math.abs(t.yDelta)-Math.abs(e.yDelta)||sle(t.anchorChipId,e.anchorChipId)||sle(t.anchorPinId,e.anchorPinId)||sle(t.resistorPinId,e.resistorPinId),O1o=(t,e,n,o)=>{const i=o[e],r=o[t.anchorChipId];if(!i||!r)return!0;const s=ale(n,t.resistorPinId,i),a=ale(n,t.anchorPinId,r);return Object.entries(o).some(([A,c])=>{if(A===e||A===t.anchorChipId)return!1;const l=n.chipMap[A];if(!l)return!1;const u=dd(l.size,c.ccwRotationDegrees);return Exe(s,a,Ey({center:c,width:u.x,height:u.y}))})},G1o=({inputProblem:t,chipPlacements:e,pinToNetworkMap:n})=>{const o=FN(t),i=new Map;for(const[s,a]of n){const A=i.get(a)??[];A.push(s),i.set(a,A)}const r=Object.values(t.chipMap).filter(s=>s.isResistor&&!s.fixedPosition&&s.pins.length===vSt).sort((s,a)=>sle(s.chipId,a.chipId));for(const s of r){const a=e[s.chipId];if(!a)continue;const A=[];for(const u of s.pins){const g=t.chipPinMap[u],h=n.get(u);if(!g||!h)continue;const d=PSt(g.side,a.ccwRotationDegrees);if(d!=="x-"&&d!=="x+")continue;const p=d==="x+"?1:-1,m=ale(t,u,a);for(const _ of i.get(h)??[]){const f=o.get(_);if(!f||f.chipId===s.chipId||f.pins.length!==vSt)continue;const I=t.chipPinMap[_],C=e[f.chipId];if(!I||!C)continue;const y=PSt(I.side,C.ccwRotationDegrees);if(d==="x-"&&y!=="x+"||d==="x+"&&y!=="x-")continue;const x=ale(t,_,C),E=x.x-m.x,B=x.y-m.y,S=E*p;S<=yve||Math.abs(B)<=yve||Math.abs(B)>S+yve||A.push({anchorChipId:f.chipId,anchorPinId:_,resistorPinId:u,yDelta:B,distanceSquared:E*E+B*B})}}A.sort(H1o);const c=A[0];if(!c)continue;const l=a.y;LN({chipIds:[s.chipId],dx:0,dy:c.yDelta,chipPlacements:e,inputProblem:t})&&O1o(c,s.chipId,t,e)&&(a.y=l)}},Y1o=class extends Zf{packedPartitions;inputProblem;finalLayout=null;packSolver2=null;pinToNetworkMap=null;constructor(t){super(),this.packedPartitions=t.packedPartitions,this.inputProblem=t.inputProblem}partitionHasFixedChip(t){const e=this.packedPartitions[t];return e?Object.values(e.inputProblem.chipMap).some(n=>n.fixedPosition!==void 0):!1}_step(){try{if(this.packedPartitions.length===0){this.finalLayout={chipPlacements:{},groupPlacements:{}},this.solved=!0;return}if(this.packedPartitions.length===1){this.finalLayout=this.packedPartitions[0].layout,this.solved=!0;return}const t=this.organizePackedPartitions();if(!this.packSolver2){const e=this.createPackInput(t);this.packSolver2=new rj(e),this.activeSubSolver=this.packSolver2}if(this.packSolver2.step(),this.packSolver2.failed){this.failed=!0,this.error=`PackSolver2 failed: ${this.packSolver2.error}`;return}if(this.packSolver2.solved){const e=this.applyPackingResult(this.packSolver2.packedComponents,t);this.finalLayout=e,this.solved=!0,this.activeSubSolver=null}}catch(t){this.failed=!0,this.error=`Failed to pack partitions: ${t}`}}buildConnectivityMap(){const t=new Map;for(const e of this.packedPartitions){for(const[n,o]of Object.entries(e.inputProblem.netConnMap)){if(!o)continue;const[i,r]=n.split("-");i&&r&&t.set(i,r)}for(const[n,o]of Object.entries(e.inputProblem.pinStrongConnMap)){if(!o)continue;const i=n.split("-");if(i.length===2&&i[0]&&i[1]){const r=t.get(i[0])||t.get(i[1]);r?(t.set(i[0],r),t.set(i[1],r)):(t.set(i[0],n),t.set(i[1],n))}}}return t}getConnectivityMap(){return this.pinToNetworkMap??=this.buildConnectivityMap(),this.pinToNetworkMap}organizePackedPartitions(){const t=[];for(let e=0;e<this.packedPartitions.length;e++){const n=this.packedPartitions[e],o=Object.keys(n.layout.chipPlacements);if(o.length>0){let i=1/0,r=-1/0,s=1/0,a=-1/0;for(const A of o){const c=n.layout.chipPlacements[A],l=n.inputProblem.chipMap[A];let u=l.size.x,g=l.size.y;(c.ccwRotationDegrees===90||c.ccwRotationDegrees===270)&&([u,g]=[g,u]);const h=c.x-u/2,d=c.x+u/2,p=c.y-g/2,m=c.y+g/2;i=Math.min(i,h),r=Math.max(r,d),s=Math.min(s,p),a=Math.max(a,m)}t.push({partitionIndex:e,chipIds:o,bounds:{minX:i,maxX:r,minY:s,maxY:a}})}}return t}createPackInput(t){const e=this.getConnectivityMap();return{components:t.map(o=>{const i=this.packedPartitions[o.partitionIndex],r=this.partitionHasFixedChip(o.partitionIndex),s=o.bounds.maxX-o.bounds.minX,a=o.bounds.maxY-o.bounds.minY,A=(o.bounds.minX+o.bounds.maxX)/2,c=(o.bounds.minY+o.bounds.maxY)/2,l=[{padId:`partition_${o.partitionIndex}_body`,networkId:`partition_${o.partitionIndex}_disconnected`,type:"rect",offset:{x:0,y:0},size:{x:Math.max(s,.1),y:Math.max(a,.1)}}],u=new Set;for(const g of o.chipIds){const h=i.layout.chipPlacements[g],d=i.inputProblem.chipMap[g];for(const p of d.pins){const m=i.inputProblem.chipPinMap[p];if(!m)continue;let _={x:m.offset.x,y:m.offset.y};const f=h.ccwRotationDegrees??0;f===90?_={x:-m.offset.y,y:m.offset.x}:f===180?_={x:-m.offset.x,y:-m.offset.y}:f===270&&(_={x:m.offset.y,y:-m.offset.x});const I=h.x+_.x,C=h.y+_.y,y=e.get(p)??`${p}_disconnected`;u.has(y)||(u.add(y),l.push({padId:`${o.partitionIndex}_pin_${p}`,networkId:y,type:"rect",offset:{x:I-A,y:C-c},size:{x:.01,y:.01}}))}}return{componentId:`partition_${o.partitionIndex}`,pads:l,availableRotationDegrees:[0],...r&&{isStatic:!0,center:{x:A,y:c},ccwRotationOffset:0}}}),minGap:this.inputProblem.partitionGap,packOrderStrategy:"largest_to_smallest",packPlacementStrategy:"minimum_sum_squared_distance_to_network"}}applyPackingResult(t,e){const n={};for(const i of t){const r=parseInt(i.componentId.replace("partition_","")),s=e.find(A=>A.partitionIndex===r),a=this.packedPartitions[r];if(s&&a){const A=(s.bounds.minX+s.bounds.maxX)/2,c=(s.bounds.minY+s.bounds.maxY)/2,l=i.center.x,u=i.center.y,g=l-A,h=u-c;for(const d of s.chipIds){const p=a.layout.chipPlacements[d];n[d]={x:p.x+g,y:p.y+h,ccwRotationDegrees:p.ccwRotationDegrees}}}}const o={chipPlacements:n,groupPlacements:{}};return G1o({inputProblem:this.inputProblem,chipPlacements:o.chipPlacements,pinToNetworkMap:this.getConnectivityMap()}),o}getCombinedPackedPartitionsProblem(){const t={chipMap:{},chipPinMap:{},pinStrongConnMap:{},netMap:{},netConnMap:{},chipGap:this.inputProblem.chipGap,partitionGap:this.inputProblem.partitionGap};for(const e of this.packedPartitions)Object.assign(t.chipMap,e.inputProblem.chipMap),Object.assign(t.chipPinMap,e.inputProblem.chipPinMap),Object.assign(t.pinStrongConnMap,e.inputProblem.pinStrongConnMap),Object.assign(t.netMap,e.inputProblem.netMap),Object.assign(t.netConnMap,e.inputProblem.netConnMap);return t}getCombinedPackedPartitionsLayout(){const t={};for(const e of this.packedPartitions)Object.assign(t,e.layout.chipPlacements);return{chipPlacements:t,groupPlacements:{}}}visualize(){return this.packSolver2&&!this.solved?this.packSolver2.visualize():this.finalLayout?Vh(this.getCombinedPackedPartitionsProblem(),this.finalLayout):this.packedPartitions.length===0?super.visualize():Vh(this.getCombinedPackedPartitionsProblem(),this.getCombinedPackedPartitionsLayout())}getConstructorParams(){return{packedPartitions:this.packedPartitions,inputProblem:this.inputProblem}}},U1o=.2,MSt=(t,e)=>e.y+ta(t.offset,e.ccwRotationDegrees).y,Ale=({upperPin:t,upperPlacement:e,lowerPin:n,lowerPlacement:o})=>MSt(t,e)-MSt(n,o)-U1o,DSt=({chipId:t,side:e},n)=>n.chipMap[t]?.pins.filter(i=>!e||n.chipPinMap[i]?.side===e).map(i=>n.chipPinMap[i]).find(i=>i&&Object.values(n.netMap).some(r=>r.isPositiveVoltageSource&&n.netConnMap[`${i.pinId}-${r.netId}`])),xve=(t,{inputProblem:e,layout:n})=>{const o=n.chipPlacements[t],i=e.chipMap[t];if(!o||!i)return null;const r=dd(i.size,o.ccwRotationDegrees);return Ey({center:o,width:r.x,height:r.y})},NSt=(t,e)=>{const n=t.flatMap(o=>{const i=xve(o,e);return i?[{x:i.minX,y:i.minY},{x:i.maxX,y:i.maxY}]:[]});return Oh(n)},K1o=({mainPartition:t,mainChipId:e,side:n},o)=>{const i=new Set(o.chipMap[e]?.pins.filter(s=>o.chipPinMap[s]?.side===n)),r=FN(t.inputProblem);for(const[s,a]of Object.entries(o.pinStrongConnMap)){if(!a)continue;const[A,c]=s.split("-"),l=i.has(A)?c:i.has(c)?A:null;if(!l)continue;const u=r.get(l);if(u?.chipId!==e&&u)return u.chipId}return null},V1o=({partitionA:t,partitionB:e},n)=>{const o=new Set(Object.keys(t.inputProblem.chipPinMap)),i=new Set(Object.keys(e.inputProblem.chipPinMap));return Object.entries(n.pinStrongConnMap).some(([r,s])=>{if(!s)return!1;const[a,A]=r.split("-");return o.has(a)&&i.has(A)||o.has(A)&&i.has(a)})},z1o=(t,e)=>{const n=new Set(t);return t.some(o=>{const i=xve(o,e);return Object.keys(e.layout.chipPlacements).some(r=>{if(!i||n.has(r))return!1;const s=xve(r,e);return s?z4(i,s):!1})})},J1o=({side:t,chipGap:e,mainBounds:n,rowBounds:o,neighbor:i})=>{const r=oD(o),s={x:i.x-r.x,y:i.y-r.y};return t==="x+"&&(s.x=n.maxX+e-o.minX),t==="x-"&&(s.x=n.minX-e-o.maxX),t==="y+"&&(s.y=n.maxY+e-o.minY),t==="y-"&&(s.y=n.minY-e-o.maxY),s},W1o=({layout:t,decouplingPartition:e},{inputProblem:n,packedPartitions:o})=>{const i=e.inputProblem,r=i.decouplingMainChipId,s=i.decouplingMainChipSide;if(i.partitionType!=="decoupling_caps"||!r||!s)return;const a=o.find(f=>f!==e&&f.inputProblem.chipMap[r]);if(!a||V1o({partitionA:e,partitionB:a},n))return;const A=K1o({mainPartition:a,mainChipId:r,side:s},n);let c=t.chipPlacements[r];A&&(c=t.chipPlacements[A]);const l=Object.keys(i.chipMap),u={inputProblem:n,layout:t},g=NSt(Object.keys(a.inputProblem.chipMap),u),h=NSt(l,u);if(!c||!g||!h)return;if(!A){const f=l[0],I=DSt({chipId:r,side:s},n),C=f&&DSt({chipId:f},n),y=f&&t.chipPlacements[f];if(!I||!C||!y)return;c={...c,y:c.y+Ale({upperPin:I,upperPlacement:c,lowerPin:C,lowerPlacement:{...y,y:c.y}})}}let d=n.chipGap;A||(d=n.partitionGap);const p=J1o({side:s,chipGap:d,mainBounds:g,rowBounds:h,neighbor:c}),m=pA(p.x,p.y),_=new Map;for(const f of l){const I=t.chipPlacements[f];I&&(_.set(f,I),t.chipPlacements[f]={...I,...Bn(m,I)})}if(z1o(l,u))for(const[f,I]of _)t.chipPlacements[f]=I},j1o=class extends Zf{constructor(t){super(),this.options=t}options;outputLayout=null;_step(){this.outputLayout=structuredClone(this.options.inputLayout);for(const t of this.options.packedPartitions)W1o({layout:this.outputLayout,decouplingPartition:t},this.options);this.solved=!0}visualize(){return Vh(this.options.inputProblem,this.outputLayout??this.options.inputLayout)}getConstructorParams(){return[this.options]}},$1o=[0,90,180,270],RSt=0,cle=.5,TSt=({chip:t,upperPinId:e,lowerPinId:n,inputProblem:o})=>{const i=o.chipPinMap[e],r=o.chipPinMap[n];if(!i||!r)return RSt;const s=t.availableRotations??$1o;let a=RSt,A=Number.NEGATIVE_INFINITY;for(const c of s){const l=ta(i.offset,c),u=ta(r.offset,c),g=l.y-u.y;g<=A||(A=g,a=c)}return a},q1o=({railLoadPairs:t,inputProblem:e,inputLayout:n})=>{const o=structuredClone(n),{chipPlacements:i}=o,r=new Map;for(const s of t){const a=r.get(s.mainChipId)??[];a.push(s),r.set(s.mainChipId,a)}for(const s of r.values()){let a;for(const A of s){const c=i[A.railComponent.chipId],l=i[A.resistor.chipId],u=i[A.mainChipId],g=e.chipPinMap[A.mainPinId];if(!c||!l||!u||!g)continue;const h=TSt({chip:A.railComponent,upperPinId:A.railPinId,lowerPinId:A.railComponentResistorPinId,inputProblem:e}),d=TSt({chip:A.resistor,upperPinId:A.resistorRailComponentPinId,lowerPinId:A.resistorMainPinId,inputProblem:e}),p=dd(A.railComponent.size,h),m=dd(A.resistor.size,d),_=p.y*cle+e.chipGap+m.y*cle,f=ta(g.offset,u.ccwRotationDegrees),I=e.chipPinMap[A.resistorMainPinId];if(!I)continue;const C=ta(I.offset,d);let y=(c.x+l.x)*cle;const x=u.y+f.y-C.y,E=x+_;i[A.railComponent.chipId]={x:y,y:E,ccwRotationDegrees:h},i[A.resistor.chipId]={x:y,y:x,ccwRotationDegrees:d};const B=Math.max(p.x,m.x)*cle,S=y-B,Q=y+B;if(a!==void 0){const w=a+e.partitionGap-S;y+=w,i[A.railComponent.chipId].x=y,i[A.resistor.chipId].x=y,a=Q+w;continue}a=Q}}return c1o({railLoadPairs:t,inputProblem:e,chipPlacements:i}),o},kSt=2,FSt=({connectedPinsByPinId:t,pinId:e})=>(t[e]??[]).map(n=>n.pinId),X1o=({inputProblem:t,pinId:e})=>{for(const[n,o]of Object.entries(t.netMap))if(o.isPositiveVoltageSource&&t.netConnMap[`${e}-${n}`])return!0;return!1},Z1o=(t,e)=>{const{inputProblem:n,pinOwnerMap:o,connectedPinsByPinId:i}=e;for(const r of t.pins){const s=FSt({connectedPinsByPinId:i,pinId:r}).find(g=>{const h=o.get(g);return h?h.pins.length>kSt&&!h.isCrystal:!1});if(!s)continue;const a=o.get(s);if(!a)continue;const A=t.pins.find(g=>g!==r);if(!A)continue;const c=FSt({connectedPinsByPinId:i,pinId:A}).find(g=>{const h=o.get(g);return!h||h.pins.length!==kSt?!1:!h.isResistor&&!h.isCapacitor&&!h.fixedPosition});if(!c)continue;const l=o.get(c);if(!l)continue;const u=l.pins.find(g=>g!==c&&X1o({inputProblem:n,pinId:g}));if(u)return{railComponent:l,resistor:t,railPinId:u,railComponentResistorPinId:c,resistorRailComponentPinId:A,resistorMainPinId:r,mainChipId:a.chipId,mainPinId:s}}return null},eIo=t=>{const e={inputProblem:t,pinOwnerMap:FN(t),connectedPinsByPinId:sj(t)},n=[];for(const o of Object.values(t.chipMap)){if(!o.isResistor||o.fixedPosition)continue;const i=Z1o(o,e);i&&n.push(i)}return n},tIo=class extends Zf{constructor(t){super(),this.params=t}params;outputLayout=null;_step(){const t=eIo(this.params.inputProblem);this.outputLayout=q1o({railLoadPairs:t,inputProblem:this.params.inputProblem,inputLayout:this.params.inputLayout}),this.solved=!0}visualize(){let t=this.params.inputLayout;return this.outputLayout&&(t=this.outputLayout),Vh(this.params.inputProblem,t)}getConstructorParams(){return[this.params]}},qv=2,lle=({connectedPinsByPinId:t,pinId:e})=>(t[e]??[]).map(n=>n.pinId),ule=({inputProblem:t,pinId:e})=>{const n=[];for(const o of Object.keys(t.netMap))t.netConnMap[`${e}-${o}`]&&n.push(o);return n},LSt=({inputProblem:t,netId:e})=>{const n=[];for(const o of Object.keys(t.chipPinMap))t.netConnMap[`${o}-${e}`]&&n.push(o);return n},Eve=({lowerChip:t,lowerInnerPinId:e,inputProblem:n})=>{for(const o of t.pins){if(o===e)continue;const i=ule({inputProblem:n,pinId:o}).find(r=>n.netMap[r]?.isGround===!0);if(i)return{groundPinId:o,groundNetId:i}}return null},nIo=({inputProblem:t,pinId:e})=>ule({inputProblem:t,pinId:e}).some(n=>t.netMap[n]?.isPositiveVoltageSource===!0),HSt=({upperInnerPinId:t},e)=>{const{inputProblem:n,pinOwnerMap:o,connectedPinsByPinId:i,pairedChipIds:r}=e;for(const s of lle({connectedPinsByPinId:i,pinId:t})){const a=o.get(s);if(!a||a.pins.length!==qv||a.fixedPosition||r.has(a.chipId))continue;const A=Eve({lowerChip:a,lowerInnerPinId:s,inputProblem:n});if(A)return{lowerChip:a,lowerInnerPinId:s,...A}}return null},oIo=(t,e)=>{const{inputProblem:n,pinOwnerMap:o,connectedPinsByPinId:i,pairedChipIds:r}=e;for(const s of t.pins){const a=lle({connectedPinsByPinId:i,pinId:s}).find(h=>{const d=o.get(h);return d?d.pins.length>qv&&!d.isCrystal:!1});if(!a)continue;const A=o.get(a);if(!A)continue;const c=t.pins.find(h=>h!==s);if(!c)continue;const l=lle({connectedPinsByPinId:i,pinId:c}).map(h=>o.get(h)).find(h=>!h||h.pins.length!==qv||h.chipId===t.chipId||h.fixedPosition?!1:!r.has(h.chipId));if(!l)continue;const u=l.pins.find(h=>lle({connectedPinsByPinId:i,pinId:h}).some(d=>o.get(d)?.chipId===t.chipId));if(!u)continue;const g=Eve({lowerChip:l,lowerInnerPinId:u,inputProblem:n});if(g)return{upperChip:t,lowerChip:l,mainChipId:A.chipId,mainPinId:a,upperOuterPinId:s,upperInnerPinId:c,lowerInnerPinId:u,...g}}return null},iIo=(t,e)=>{const{inputProblem:n,pinOwnerMap:o,pairedChipIds:i}=e,r=t.pins.find(h=>nIo({inputProblem:n,pinId:h}));if(!r)return null;const s=t.pins.find(h=>h!==r);if(!s)return null;const a=HSt({upperInnerPinId:s},e);if(a)return{upperChip:t,upperOuterPinId:r,upperInnerPinId:s,...a};const A=ule({inputProblem:n,pinId:s}).find(h=>{const d=n.netMap[h];return!d?.isGround&&!d?.isPositiveVoltageSource});if(!A)return null;const c=LSt({inputProblem:n,netId:A});if(c.length!==qv)return null;const l=c.find(h=>h!==s);if(!l)return null;const u=o.get(l);if(!u||u.pins.length!==qv||u.fixedPosition||i.has(u.chipId))return null;const g=Eve({lowerChip:u,lowerInnerPinId:l,inputProblem:n});return g?{upperChip:t,lowerChip:u,upperOuterPinId:r,upperInnerPinId:s,lowerInnerPinId:l,...g}:null},rIo=(t,e)=>{const{inputProblem:n}=e;for(const o of t.pins){if(!ule({inputProblem:n,pinId:o}).some(a=>{const A=n.netMap[a];return A?.isGround||A?.isPositiveVoltageSource?!1:LSt({inputProblem:n,netId:a}).length===1}))continue;const r=t.pins.find(a=>a!==o);if(!r)continue;const s=HSt({upperInnerPinId:r},e);if(s)return{upperChip:t,upperOuterPinId:o,upperInnerPinId:r,...s,isStandaloneSignalChain:!0}}return null},sIo=t=>{const e=FN(t),n=[],o=new Set,i=sj(t),r={inputProblem:t,pinOwnerMap:e,connectedPinsByPinId:i,pairedChipIds:o};for(const s of Object.values(t.chipMap)){if(s.pins.length!==qv||s.isCrystal||s.fixedPosition||o.has(s.chipId))continue;const a=oIo(s,r);a&&(n.push(a),o.add(a.upperChip.chipId),o.add(a.lowerChip.chipId))}for(const s of Object.values(t.chipMap)){if(s.pins.length!==qv||s.isCrystal||s.fixedPosition||o.has(s.chipId))continue;const a=rIo(s,r);a&&(n.push(a),o.add(a.upperChip.chipId),o.add(a.lowerChip.chipId))}for(const s of Object.values(t.chipMap)){if(s.pins.length!==qv||s.isCrystal||s.fixedPosition||o.has(s.chipId))continue;const a=iIo(s,r);a&&(n.push(a),o.add(a.upperChip.chipId),o.add(a.lowerChip.chipId))}return n},aIo=[0,90,180,270],OSt=0,Bve=.5,GSt=({chip:t,upperPinId:e,lowerPinId:n,inputProblem:o})=>{const i=o.chipPinMap[e],r=o.chipPinMap[n];if(!i||!r)return OSt;let s=aIo;t.availableRotations&&(s=t.availableRotations);let a=OSt,A=Number.NEGATIVE_INFINITY;for(const c of s){const l=ta(i.offset,c),u=ta(r.offset,c),g=l.y-u.y;g<=A||(A=g,a=c)}return a},bve=({chip:t,placement:e})=>{const n=dd(t.size,e.ccwRotationDegrees);return Ey({center:e,width:n.x,height:n.y})},AIo=({groundedLoadPair:t,chipPlacements:e,inputProblem:n})=>{const o=e[t.upperChip.chipId],i=e[t.lowerChip.chipId];if(!o||!i)return;const r=bve({chip:t.upperChip,placement:o}),s=bve({chip:t.lowerChip,placement:i}),a=Oh([{x:r.minX,y:r.minY},{x:r.maxX,y:r.maxY},{x:s.minX,y:s.minY},{x:s.maxX,y:s.maxY}]);if(!a)return;let A=0;for(const[c,l]of Object.entries(e)){if(c===t.upperChip.chipId||c===t.lowerChip.chipId)continue;const u=n.chipMap[c];if(!u)continue;const g=bve({chip:u,placement:l});if(a.maxX+n.chipGap<=g.minX||a.minX-n.chipGap>=g.maxX||g.maxY<=a.maxY)continue;const d=a.maxY+n.chipGap-g.minY;A=Math.max(A,d)}o.y-=A,i.y-=A},cIo=({groundedLoadPair:t,chipPlacements:e,inputProblem:n})=>{const o=e[t.upperChip.chipId],i=e[t.lowerChip.chipId];if(!o||!i)return;const r=GSt({chip:t.upperChip,upperPinId:t.upperOuterPinId,lowerPinId:t.upperInnerPinId,inputProblem:n}),s=GSt({chip:t.lowerChip,upperPinId:t.lowerInnerPinId,lowerPinId:t.groundPinId,inputProblem:n}),a=dd(t.upperChip.size,r),A=dd(t.lowerChip.size,s),c=a.y*Bve+n.chipGap+A.y*Bve,l=n.chipPinMap[t.upperInnerPinId],u=n.chipPinMap[t.lowerInnerPinId];if(!l||!u)return;const g=ta(l.offset,r),h=ta(u.offset,s),d=Oh([o,i]);if(!d)return;const p=oD(d),m={x:p.x-g.x,y:p.y+c*Bve,ccwRotationDegrees:r},_=t.mainPinId;if(_){const f=t.mainChipId;if(!f)return;const I=e[f];if(!I)return;const C=n.chipPinMap[t.upperOuterPinId],y=n.chipPinMap[_];if(!C||!y)return;const x=ta(C.offset,o.ccwRotationDegrees),E=ta(C.offset,r);m.x=o.x+x.x-E.x,m.y=o.y+x.y-E.y,m.y+=Ale({upperPin:y,upperPlacement:I,lowerPin:C,lowerPlacement:m})}e[t.upperChip.chipId]=m,e[t.lowerChip.chipId]={x:m.x+g.x-h.x,y:m.y-c,ccwRotationDegrees:s},AIo({groundedLoadPair:t,chipPlacements:e,inputProblem:n})},YSt=2,Xv=(t,e)=>{const{chipPlacements:n}=e,o=n[t.upperChip.chipId],i=n[t.lowerChip.chipId],r=mb({placement:o,size:t.upperChip.size}),s=mb({placement:i,size:t.lowerChip.size});return{minX:Math.min(r.minX,s.minX),maxX:Math.max(r.maxX,s.maxX),minY:Math.min(r.minY,s.minY),maxY:Math.max(r.maxY,s.maxY)}},USt=(t,e)=>{const{chipPlacements:n,inputProblem:o}=e,i=n[t.lowerChip.chipId],r=o.chipPinMap[t.groundPinId],s=ta(r.offset,i.ccwRotationDegrees);return i.y+s.y},gle=({groundedLoadPair:t,dx:e,dy:n},o)=>{const{chipPlacements:i}=o;for(const r of[t.upperChip.chipId,t.lowerChip.chipId]){const s=i[r];s.x+=e,s.y+=n}},dle=(t,e)=>Xv(t,e).minX,KSt=(t,e)=>{const n=t.map(o=>Xv(o,e));return{minX:Math.min(...n.map(o=>o.minX)),maxX:Math.max(...n.map(o=>o.maxX)),minY:Math.min(...n.map(o=>o.minY)),maxY:Math.max(...n.map(o=>o.maxY))}},VSt=(t,e,n)=>t.maxY+n<=e.minY||e.maxY+n<=t.minY,lIo=(t,e,n)=>{const{inputProblem:o}=n,i=Xv(t,n),r=Xv(e,n),s=i.maxX+o.chipGap<=r.minX||r.maxX+o.chipGap<=i.minX,a=VSt(i,r,o.chipGap);return!s&&!a},uIo=(t,e)=>{const n=new Set(t),o=[];for(;n.size>0;){const i=n.values().next().value;if(!i)break;n.delete(i);const r=[i];for(let s=0;s<r.length;s++){const a=r[s];for(const A of[...n])lIo(a,A,e)&&(n.delete(A),r.push(A))}r.length>=YSt&&o.push(r)}return o},gIo=(t,e)=>{const{inputProblem:n}=e,o=[...t].sort((a,A)=>dle(a,e)-dle(A,e)),i=o.map(a=>USt(a,e)),r=Math.min(...i);for(const a of o){const A=USt(a,e);gle({groundedLoadPair:a,dx:0,dy:r-A},e)}let s;for(const a of o){const A=Xv(a,e);if(s===void 0){s=A.maxX;continue}const c=s+n.partitionGap-A.minX;gle({groundedLoadPair:a,dx:c,dy:0},e),s=A.maxX+c}},dIo=(t,e)=>{const{inputProblem:n}=e,o=[...t].sort((A,c)=>dle(A,e)-dle(c,e)),i=KSt(o,e),r=[];for(const A of o){const c=Xv(A,e);let l=c.minX;for(const u of r){const g=Xv(u,e);VSt(g,c,n.chipGap)||(l=Math.max(l,g.maxX+n.chipGap))}gle({groundedLoadPair:A,dx:l-c.minX,dy:0},e),r.push(A)}const s=KSt(o,e),a=(i.minX+i.maxX-s.minX-s.maxX)/2;for(const A of o)gle({groundedLoadPair:A,dx:a,dy:0},e)},hIo=({groundedLoadPairs:t,chipPlacements:e,inputProblem:n})=>{const o={chipPlacements:e,inputProblem:n},i=new Map;for(const s of t){if(!e[s.upperChip.chipId]||!e[s.lowerChip.chipId]||!n.chipPinMap[s.groundPinId])continue;const a=i.get(s.groundNetId)??new Map,A=a.get(s.mainChipId)??[];A.push(s),a.set(s.mainChipId,A),i.set(s.groundNetId,a)}for(const s of i.values())for(const a of s.values()){if(a.length<YSt)continue;if(!(a[0].mainChipId!==void 0)){gIo(a,o);continue}for(const c of uIo(a,o))dIo(c,o)}const r=_Io({groundedLoadPairs:t,chipPlacements:e,inputProblem:n});A1o({groundedLoadPairs:t.filter(s=>!r.has(s)),chipPlacements:e,inputProblem:n})},pIo={"x-":{x:-1,y:0},"x+":{x:1,y:0},"y-":{x:0,y:-1},"y+":{x:0,y:1}},mIo=2,_Io=({inputProblem:t,chipPlacements:e,groundedLoadPairs:n})=>{const o=new Set,i=new Set(n);for(const r of i){if(!r.mainChipId||!r.mainPinId)continue;const s=t.chipPinMap[r.mainPinId],a=n.filter(g=>g.mainChipId===r.mainChipId&&g.mainPinId&&t.chipPinMap[g.mainPinId].side===s.side);if(a.length<mIo)continue;const A=e[r.mainChipId],c=ta(pIo[s.side],A.ccwRotationDegrees);if(c.x===0)continue;a.sort((g,h)=>{const d=ta(t.chipPinMap[g.mainPinId].offset,A.ccwRotationDegrees);return(ta(t.chipPinMap[h.mainPinId].offset,A.ccwRotationDegrees).y-d.y)*c.x});const l=mb({placement:A,size:t.chipMap[r.mainChipId].size});let u;for(const g of a){i.delete(g);const h=t.chipPinMap[g.mainPinId],d=[g.upperChip.chipId,g.lowerChip.chipId],p=a.filter(x=>x===g||i.has(x)).flatMap(x=>[x.upperChip.chipId,x.lowerChip.chipId]),m=e[g.upperChip.chipId],_=Ale({upperPin:h,upperPlacement:A,lowerPin:t.chipPinMap[g.upperOuterPinId],lowerPlacement:m}),{minX:f,maxX:I}=Xv(g,{chipPlacements:e});let C=Math.max(0,l.maxX+t.chipGap-f);c.x<0&&(C=Math.min(0,l.minX-t.chipGap-I)),u!==void 0&&(c.x<0?C=Math.min(C,u-t.chipGap-I):C=Math.max(C,u+t.chipGap-f));const y=[C];for(const[x,E]of Object.entries(e)){if(p.includes(x))continue;const B=mb({placement:E,size:t.chipMap[x].size});let S=B.maxX+t.chipGap-f;c.x<0&&(S=B.minX-t.chipGap-I),!(S*c.x<C*c.x)&&y.push(S)}y.sort((x,E)=>Math.abs(x)-Math.abs(E));for(const x of y)if(LN({chipIds:d,clearanceGroupChipIds:p,dx:x,dy:_,chipPlacements:e,inputProblem:t})){o.add(g),u=I+x,c.x<0&&(u=f+x);break}}}return o},fIo=class extends Zf{constructor(t){super(),this.params=t}params;outputLayout=null;groundedLoadPairs=[];_step(){const t={};for(const[e,n]of Object.entries(this.params.inputLayout.chipPlacements))t[e]={...n};this.groundedLoadPairs=sIo(this.params.inputProblem);for(const e of this.groundedLoadPairs)cIo({groundedLoadPair:e,chipPlacements:t,inputProblem:this.params.inputProblem});hIo({groundedLoadPairs:this.groundedLoadPairs,chipPlacements:t,inputProblem:this.params.inputProblem}),this.outputLayout={chipPlacements:t,groupPlacements:{...this.params.inputLayout.groupPlacements}},this.solved=!0}visualize(){let t=this.params.inputLayout;return this.outputLayout&&(t=this.outputLayout),Vh(this.params.inputProblem,t)}getConstructorParams(){return[this.params]}},IIo=t=>{const e=Object.values(t.inputProblem.chipMap);return e.length>1&&e.every(n=>n.pins.length===2&&!n.isCapacitor&&!n.fixedPosition)},CIo=({groundedLoadPairs:t,packedPartitions:e})=>{const o=e.filter(IIo).map(r=>({chipIds:Object.keys(r.inputProblem.chipMap)})),i=new Set(o.flatMap(r=>r.chipIds));for(const r of t){if(r.mainChipId||r.isStandaloneSignalChain)continue;const s=[r.upperChip.chipId,r.lowerChip.chipId];if(!s.some(a=>i.has(a))){o.push({chipIds:s});for(const a of s)i.add(a)}}return o},hle=({chipId:t},e)=>{const n=e.inputProblem.chipMap[t],o=e.layout.chipPlacements[t];if(!n||!o)return null;const i=dd(n.size,o.ccwRotationDegrees);return Ey({center:o,width:i.x,height:i.y})},Sve=({chipIds:t},e)=>Oh(t.flatMap(n=>{const o=hle({chipId:n},e);return o?[{x:o.minX,y:o.minY},{x:o.maxX,y:o.maxY}]:[]})),zSt=({chipIds:t,railNetIds:e},n)=>{let o=null;for(const i of t){const r=n.inputProblem.chipMap[i];if(!r)continue;const s=n.layout.chipPlacements[r.chipId];if(s)for(const a of r.pins){if(![...e].some(g=>n.inputProblem.netConnMap[`${a}-${g}`]))continue;const c=n.inputProblem.chipPinMap[a];if(!c)continue;const l=ta(c.offset,s.ccwRotationDegrees),u=s.y+l.y;(o===null||u>o.y)&&(o={chipId:r.chipId,y:u})}}return o},JSt=({chipIds:t},{inputProblem:e})=>{const n=new Set;for(const o of t){const i=e.chipMap[o];if(i)for(const r of i.pins)for(const[s,a]of Object.entries(e.netMap))!a.isGround&&!a.isPositiveVoltageSource||e.netConnMap[`${r}-${s}`]&&n.add(s)}return n},yIo=(t,e)=>t.size>=2&&t.size===e.size&&[...t].every(n=>e.has(n)),xIo=({chipIds:t,offset:e},{layout:n})=>{const o=new Map;for(const i of t){const r=n.chipPlacements[i];r&&(o.set(i,r),n.chipPlacements[i]={...r,x:r.x+e.x,y:r.y+e.y})}return o},EIo=({movedChipIds:t},e)=>{const n=new Set(t);return t.some(o=>{const i=hle({chipId:o},e);return i?Object.keys(e.layout.chipPlacements).some(r=>{if(n.has(r))return!1;const s=hle({chipId:r},e);return s?z4(i,s):!1}):!1})},BIo=t=>{const{groundedLoadPairs:e,inputProblem:n,packedPartitions:o}=t,i=structuredClone(t.inputLayout),r={inputProblem:n,layout:i},s=o.filter(c=>c.inputProblem.partitionType==="decoupling_caps"),a=CIo({groundedLoadPairs:e,packedPartitions:o}),A=new Set;for(const c of s){const l=JSt({chipIds:Object.keys(c.inputProblem.chipMap)},r),u=Object.keys(c.inputProblem.chipMap),g=Sve({chipIds:u},r);if(!g)continue;const h=zSt({chipIds:u,railNetIds:l},r);if(!h)continue;let d=g.maxX;for(const p of a){if(A.has(p))continue;const m=JSt({chipIds:p.chipIds},r);if(!yIo(l,m))continue;const _=p.chipIds;if(!Sve({chipIds:_},r))continue;const I=zSt({chipIds:_,railNetIds:m},r);if(!I)continue;const C=hle({chipId:I.chipId},r);if(!C)continue;const y=xIo({chipIds:_,offset:{x:d+n.partitionGap-C.minX,y:h.y-I.y}},r);if(EIo({movedChipIds:_},r)){for(const[E,B]of y)i.chipPlacements[E]=B;continue}const x=Sve({chipIds:_},r);x&&(d=x.maxX),A.add(p)}}return i},bIo=class extends Zf{constructor(t){super(),this.options=t}options;outputLayout=null;_step(){this.outputLayout=BIo(this.options),this.solved=!0}visualize(){return Vh(this.options.inputProblem,this.outputLayout??this.options.inputLayout)}getConstructorParams(){return[this.options]}},WSt=(t,e)=>Object.keys(e.netMap).filter(n=>e.netConnMap[`${t}-${n}`]),jSt=(t,e)=>new Set(t.pins.flatMap(n=>WSt(n,e))),$St=({chipId:t,railNetId:e},n)=>{const o=n.chipMap[t]?.pins.find(i=>WSt(i,n).includes(e));return o?n.chipPinMap[o]??null:null},ple=(t,{inputProblem:e,layout:n})=>{const o=e.chipMap[t],i=n.chipPlacements[t];return!o||!i?null:mb({placement:i,size:o.size})},qSt=(t,e)=>t.reduce((n,o)=>n+e.chipPlacements[o].x,0)/t.length,SIo=({groundNetId:t,railNetId:e},{inputProblem:n,layout:o})=>Object.values(n.chipMap).filter(i=>{if(!i.isCapacitor||i.fixedPosition||i.pins.length!==2||!o.chipPlacements[i.chipId])return!1;const r=jSt(i,n);return r.size===2&&r.has(t)&&r.has(e)}).map(i=>i.chipId),QIo=(t,e)=>{const{inputProblem:n,layout:o}=e;if(t.fixedPosition||t.pins.length!==3)return null;const i=o.chipPlacements[t.chipId];if(!i)return null;const r=[...jSt(t,n)],s=r.filter(u=>n.netMap[u]?.isGround),a=r.filter(u=>n.netMap[u]?.isPositiveVoltageSource);if(s.length!==1||a.length!==2)return null;const A=a.map(u=>({railNetId:u,capacitorChipIds:SIo({groundNetId:s[0],railNetId:u},e)}));if(A.some(u=>u.capacitorChipIds.length===0))return null;const c=A.find(u=>qSt(u.capacitorChipIds,o)<i.x),l=A.find(u=>qSt(u.capacitorChipIds,o)>i.x);return!c||!l?null:(c.capacitorChipIds.sort((u,g)=>o.chipPlacements[u].x-o.chipPlacements[g].x),l.capacitorChipIds.sort((u,g)=>o.chipPlacements[u].x-o.chipPlacements[g].x),{regulatorChipId:t.chipId,left:c,right:l})},XSt=({group:t,regulatorChipId:e,startX:n,xDirection:o},i)=>{const{inputProblem:r,layout:s}=i,a=s.chipPlacements[e],A=$St({chipId:e,railNetId:t.railNetId},r);if(!a||!A)return!1;const c=[...t.capacitorChipIds];o<0&&c.reverse();const l=r.decouplingCapsGap??r.chipGap;let u=n;for(const g of c){const h=s.chipPlacements[g],d=ple(g,i),p=$St({chipId:g,railNetId:t.railNetId},r);if(!h||!d||!p)return!1;const m=d.maxX-d.minX;s.chipPlacements[g]={...h,x:u+o*m/2,y:h.y+Ale({upperPin:A,upperPlacement:a,lowerPin:p,lowerPlacement:h})},u+=o*(m+l)}return!0},vIo=(t,e)=>{const n=ple(t.regulatorChipId,e);return!n||!XSt({group:t.left,regulatorChipId:t.regulatorChipId,startX:n.minX-e.inputProblem.chipGap,xDirection:-1},e)?!1:XSt({group:t.right,regulatorChipId:t.regulatorChipId,startX:n.maxX+e.inputProblem.chipGap,xDirection:1},e)},wIo=(t,e)=>{const{inputProblem:n,layout:o}=e,i=new Set(t),r=t.map(g=>ple(g,e)),s=Math.min(...r.map(g=>g.minX)),a=Math.min(...r.map(g=>g.minY)),A=Math.max(...r.map(g=>g.maxX)),c=Math.max(...r.map(g=>g.maxY)),l=(s+A)/2;let u=0;for(const g of Object.keys(o.chipPlacements)){if(i.has(g))continue;const h=ple(g,e);!h||(h.minX+h.maxX)/2<=l||Math.max(h.minY-c,a-h.maxY,0)>=n.partitionGap||(u=Math.min(u,h.minX-n.partitionGap-A))}return u},PIo=(t,e)=>{const n=structuredClone(e),o={inputProblem:t,layout:n},i=Object.values(t.chipMap).map(A=>QIo(A,o)).find(A=>A!==null);if(!i)return n;const r=[...i.left.capacitorChipIds,i.regulatorChipId,...i.right.capacitorChipIds];if(!vIo(i,o))return e;const a=wIo(r,o);return LN({chipIds:r,clearanceGroupChipIds:r,dx:a,dy:0,chipPlacements:n.chipPlacements,inputProblem:t,minimumOutsideGap:t.partitionGap})?n:e},MIo=class extends Zf{constructor(t){super(),this.params=t}params;outputLayout=null;_step(){this.outputLayout=PIo(this.params.inputProblem,this.params.inputLayout),this.solved=!0}visualize(){let t=this.params.inputLayout;return this.outputLayout&&(t=this.outputLayout),Vh(this.params.inputProblem,t)}getConstructorParams(){return[this.params]}};function J5(t,e,n,o={}){return{solverName:t,solverClass:e,getConstructorParams:n,onSolved:o.onSolved}}var ZSt=class extends Zf{getSolverName(){return"LayoutPipelineSolver"}identifyCrystalCircuitsSolver;identifyDecouplingCapsSolver;chipPartitionsSolver;packInnerPartitionsSolver;partitionPackingSolver;groundedLoadPairSolver;alignPowerGroundRowsSolver;alignTestPointsSolver;placeNetOnlyDecouplingRowsSolver;placeRailConnectedLoadsSolver;alignChipConnectedRailLoadsSolver;alignRegulatorCapacitorRowSolver;startTimeOfPhase;endTimeOfPhase;timeSpentOnPhase;firstIterationOfPhase;pinIdToStronglyConnectedPins;inputProblem;chipPartitions;packedPartitions;pipelineDef=[J5("identifyCrystalCircuitsSolver",Rfo,()=>[this.inputProblem]),J5("identifyDecouplingCapsSolver",Nfo,()=>[this.inputProblem],{onSolved:t=>{}}),J5("chipPartitionsSolver",vfo,()=>[{inputProblem:this.inputProblem,decouplingCapGroups:this.identifyDecouplingCapsSolver?.outputDecouplingCapGroups,crystalCircuitGroups:this.identifyCrystalCircuitsSolver?.outputCrystalCircuitGroups}],{onSolved:t=>{this.chipPartitions=this.chipPartitionsSolver.partitions}}),J5("packInnerPartitionsSolver",L1o,()=>[{partitions:this.chipPartitions,pinIdToStronglyConnectedPins:this.pinIdToStronglyConnectedPins}],{onSolved:t=>{this.packedPartitions=this.packInnerPartitionsSolver.packedPartitions}}),J5("partitionPackingSolver",Y1o,()=>[{packedPartitions:this.packedPartitions||[],inputProblem:this.inputProblem}],{onSolved:t=>{}}),J5("alignPowerGroundRowsSolver",kfo,()=>[{inputProblem:this.inputProblem,inputLayout:this.partitionPackingSolver.finalLayout}]),J5("placeNetOnlyDecouplingRowsSolver",j1o,()=>[{inputProblem:this.inputProblem,packedPartitions:this.packedPartitions,inputLayout:this.alignPowerGroundRowsSolver.outputLayout}]),J5("groundedLoadPairSolver",fIo,()=>[{inputProblem:this.inputProblem,inputLayout:this.placeNetOnlyDecouplingRowsSolver.outputLayout}]),J5("placeRailConnectedLoadsSolver",bIo,()=>[{inputProblem:this.inputProblem,groundedLoadPairs:this.groundedLoadPairSolver.groundedLoadPairs,packedPartitions:this.packedPartitions,inputLayout:this.groundedLoadPairSolver.outputLayout}]),J5("alignChipConnectedRailLoadsSolver",tIo,()=>[{inputProblem:this.inputProblem,inputLayout:this.placeRailConnectedLoadsSolver.outputLayout}]),J5("alignRegulatorCapacitorRowSolver",MIo,()=>[{inputProblem:this.inputProblem,inputLayout:this.alignChipConnectedRailLoadsSolver.outputLayout??this.placeRailConnectedLoadsSolver.outputLayout}]),J5("alignTestPointsSolver",n1o,()=>[{inputProblem:this.inputProblem,inputLayout:this.alignRegulatorCapacitorRowSolver.outputLayout??this.alignChipConnectedRailLoadsSolver.outputLayout??this.placeRailConnectedLoadsSolver.outputLayout??this.groundedLoadPairSolver.outputLayout??this.placeNetOnlyDecouplingRowsSolver.outputLayout??this.alignPowerGroundRowsSolver.outputLayout??this.partitionPackingSolver.finalLayout}])];constructor(t){super(),this.inputProblem=t,this.MAX_ITERATIONS=1e6,this.startTimeOfPhase={},this.endTimeOfPhase={},this.timeSpentOnPhase={},this.firstIterationOfPhase={},this.pinIdToStronglyConnectedPins=sj(t)}currentPipelineStepIndex=0;_step(){const 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}const e=t.getConstructorParams(this);this.activeSubSolver=new t.solverClass(...e),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()!==t;)this.step()}getCurrentPhase(){return this.pipelineDef[this.currentPipelineStepIndex]?.solverName??"none"}visualize(){if(!this.solved&&this.activeSubSolver)return this.activeSubSolver.visualize();if(this.solved&&this.alignTestPointsSolver?.solved)return this.alignTestPointsSolver.visualize();if(this.solved&&this.placeNetOnlyDecouplingRowsSolver?.solved)return this.placeNetOnlyDecouplingRowsSolver.visualize();if(this.solved&&this.alignPowerGroundRowsSolver?.solved)return this.alignPowerGroundRowsSolver.visualize();if(this.solved&&this.groundedLoadPairSolver?.solved)return this.groundedLoadPairSolver.visualize();if(this.solved&&this.partitionPackingSolver?.solved)return this.partitionPackingSolver.visualize();const t=this.identifyCrystalCircuitsSolver?.visualize(),e=this.identifyDecouplingCapsSolver?.visualize(),n=this.chipPartitionsSolver?.visualize(),o=this.packInnerPartitionsSolver?.visualize(),i=this.partitionPackingSolver?.visualize(),r=this.groundedLoadPairSolver?.visualize(),s=this.alignPowerGroundRowsSolver?.visualize(),a=this.alignTestPointsSolver?.visualize(),A=this.placeNetOnlyDecouplingRowsSolver?.visualize(),c=pb(this.inputProblem),u=[Vh(this.inputProblem,c),t,e,n,o,i,r,s,A,a].filter(Boolean).map((g,h)=>{for(const d of g.rects??[])d.step=h;for(const d of g.points??[])d.step=h;for(const d of g.circles??[])d.step=h;for(const d of g.texts??[])d.step=h;for(const d of g.lines??[])d.step=h;return g});return u.length===1?u[0]:{points:u.flatMap(g=>g.points||[]),rects:u.flatMap(g=>g.rects||[]),lines:u.flatMap(g=>g.lines||[]),circles:u.flatMap(g=>g.circles||[]),texts:u.flatMap(g=>g.texts||[])}}preview(){return this.activeSubSolver?this.activeSubSolver.preview():this.alignTestPointsSolver?.solved?this.alignTestPointsSolver.visualize():this.placeNetOnlyDecouplingRowsSolver?.solved?this.placeNetOnlyDecouplingRowsSolver.visualize():this.alignPowerGroundRowsSolver?.solved?this.alignPowerGroundRowsSolver.visualize():this.partitionPackingSolver?.solved?this.partitionPackingSolver.visualize():this.packInnerPartitionsSolver?.solved?this.packInnerPartitionsSolver.visualize():this.chipPartitionsSolver?.solved?this.chipPartitionsSolver.visualize():this.identifyDecouplingCapsSolver?.solved?this.identifyDecouplingCapsSolver.visualize():this.identifyCrystalCircuitsSolver?.solved?this.identifyCrystalCircuitsSolver.visualize():super.preview()}checkForOverlaps(t){const e=[],n=Object.keys(t.chipPlacements);for(let o=0;o<n.length;o++)for(let i=o+1;i<n.length;i++){const r=n[o],s=n[i],a=t.chipPlacements[r],A=t.chipPlacements[s],c=this.inputProblem.chipMap[r],l=this.inputProblem.chipMap[s];if(!c||!l)continue;const u=this.getRotatedBounds(a,c.size),g=this.getRotatedBounds(A,l.size),h=this.calculateOverlapArea(u,g);h>0&&e.push({chip1:r,chip2:s,overlapArea:h})}return e}getRotatedBounds(t,e){const n=e.x/2,o=e.y/2,i=t.ccwRotationDegrees*Math.PI/180,r=Math.abs(Math.cos(i)),s=Math.abs(Math.sin(i)),a=n*r+o*s,A=n*s+o*r;return{minX:t.x-a,maxX:t.x+a,minY:t.y-A,maxY:t.y+A}}calculateOverlapArea(t,e){if(t.maxX<=e.minX||t.minX>=e.maxX||t.maxY<=e.minY||t.minY>=e.maxY)return 0;const n=Math.min(t.maxX,e.maxX)-Math.max(t.minX,e.minX),o=Math.min(t.maxY,e.maxY)-Math.max(t.minY,e.minY);return n*o}getOutputLayout(){if(!this.solved)throw new Error("Pipeline not solved yet. Call solve() or step() until solved.");let t;if(this.alignTestPointsSolver?.solved&&this.alignTestPointsSolver.outputLayout)t=this.alignTestPointsSolver.outputLayout;else if(this.placeNetOnlyDecouplingRowsSolver?.solved&&this.placeNetOnlyDecouplingRowsSolver.outputLayout)t=this.placeNetOnlyDecouplingRowsSolver.outputLayout;else if(this.alignPowerGroundRowsSolver?.solved&&this.alignPowerGroundRowsSolver.outputLayout)t=this.alignPowerGroundRowsSolver.outputLayout;else if(this.partitionPackingSolver?.solved&&this.partitionPackingSolver.finalLayout)t=this.partitionPackingSolver.finalLayout;else throw new Error("No layout available. Pipeline may have failed or not progressed far enough.");const e=this.checkForOverlaps(t);if(e.length>0){const n=e.map(o=>`${o.chip1} overlaps ${o.chip2} (area: ${o.overlapArea.toFixed(4)})`).join(", ");console.warn(`Warning: ${e.length} chip overlaps detected in final layout: ${n}`)}return t}},mle=class{netMap;idToNetMap;constructor(e){this.netMap=e,this.idToNetMap={};for(const[n,o]of Object.entries(e))for(const i of o)this.idToNetMap[i]=n}addConnections(e){for(const n of e){const o=new Set;for(const r of n){const s=this.idToNetMap[r];s&&o.add(s)}let i;if(o.size===0)i=`connectivity_net${Object.keys(this.netMap).length}`,this.netMap[i]=[];else if(o.size===1)i=o.values().next().value??`connectivity_net${Object.keys(this.netMap).length}`;else{i=o.values().next().value??`connectivity_net${Object.keys(this.netMap).length}`;for(const r of o)if(r!==i){const s=this.netMap[i],a=this.netMap[r];if(s&&a){s.push(...a),this.netMap[r]=s;for(const A of s)this.idToNetMap[A]=i}}}for(const r of n){const s=this.netMap[i];s&&!s.includes(r)&&s.push(r),this.idToNetMap[r]=i}}}getIdsConnectedToNet(e){return this.netMap[e]||[]}getNetConnectedToId(e){return this.idToNetMap[e]}areIdsConnected(e,n){if(e===n)return!0;const o=this.getNetConnectedToId(e);if(!o)return!1;const i=this.getNetConnectedToId(n);return i?o===i||i===e||i===e:!1}areAllIdsConnected(e){if(e.length===0)return!0;const n=this.getNetConnectedToId(e[0]);if(!n)return!1;for(const o of e){const i=this.getNetConnectedToId(o);if(i===void 0||i!==n)return!1}return!0}};class DIo{constructor(e=1/0,n=Float64Array,o=Uint32Array){const i=e!==1/0;this.ids=i?new o(e):[],this.values=i?new n(e):[],this.capacity=e,this.length=0}clear(){this.length=0}push(e,n){if(this.length===this.capacity)throw new RangeError("Queue is at capacity.");let o=this.length++;for(;o>0;){const i=o-1>>1,r=this.values[i];if(n>=r)break;this.ids[o]=this.ids[i],this.values[o]=r,o=i}this.ids[o]=e,this.values[o]=n}pop(){if(this.length===0)return;const e=this.ids,n=this.values,o=e[0],i=--this.length;if(i>0){const r=e[i],s=n[i];let a=0;const A=i>>1;for(;a<A;){const c=(a<<1)+1,l=c+1,u=c+(+(l<i)&+(n[l]<n[c]));if(n[u]>=s)break;e[a]=e[u],n[a]=n[u],a=u}e[a]=r,n[a]=s}return o}peek(){return this.length>0?this.ids[0]:void 0}peekValue(){return this.length>0?this.values[0]:void 0}shrink(){Array.isArray(this.ids)&&(this.ids.length=this.length),Array.isArray(this.values)&&(this.values.length=this.length)}}const eQt=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],Qve=3;class UH{static from(e,n=0){if(n%8!==0)throw new Error("byteOffset must be 8-byte aligned.");if(!e||e.byteLength===void 0||"buffer"in e)throw new Error("Data must be an instance of ArrayBuffer or SharedArrayBuffer.");const[o,i]=new Uint8Array(e,n+0,2);if(o!==251)throw new Error("Data does not appear to be in a Flatbush format.");const r=i>>4;if(r!==Qve)throw new Error(`Got v${r} data when expected v${Qve}.`);const s=eQt[i&15];if(!s)throw new Error("Unrecognized array type.");const[a]=new Uint16Array(e,n+2,1),[A]=new Uint32Array(e,n+4,1);return new UH(A,a,s,void 0,e,n)}constructor(e,n=16,o=Float64Array,i=ArrayBuffer,r,s=0){if(e===void 0)throw new Error("Missing required argument: numItems.");if(isNaN(e)||e<=0)throw new Error(`Unexpected numItems value: ${e}.`);this.numItems=+e,this.nodeSize=Math.min(Math.max(+n,2),65535),this.byteOffset=s;let a=e,A=a;this._levelBounds=[a*4];do a=Math.ceil(a/this.nodeSize),A+=a,this._levelBounds.push(A*4);while(a!==1);this.ArrayType=o,this.IndexArrayType=A<16384?Uint16Array:Uint32Array;const c=eQt.indexOf(o),l=A*4*o.BYTES_PER_ELEMENT;if(c<0)throw new Error(`Unexpected typed array class: ${o}.`);const u=o,g=this.IndexArrayType;if(r)this.data=r,this._boxes=new u(r,s+8,A*4),this._indices=new g(r,s+8+l,A),this._pos=A*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{const h=this.data=new i(8+l+A*this.IndexArrayType.BYTES_PER_ELEMENT);this._boxes=new u(h,8,A*4),this._indices=new g(h,8+l,A),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,(Qve<<4)+c]),new Uint16Array(h,2,1)[0]=n,new Uint32Array(h,4,1)[0]=e}this._queue=new DIo}add(e,n,o=e,i=n){const r=this._pos,s=r>>2,a=this._boxes;return this._indices[s]=s,a[r]=e,a[r+1]=n,a[r+2]=o,a[r+3]=i,this._pos=r+4,e<this.minX&&(this.minX=e),n<this.minY&&(this.minY=n),o>this.maxX&&(this.maxX=o),i>this.maxY&&(this.maxY=i),s}finish(){if(this._pos>>2!==this.numItems)throw new Error(`Added ${this._pos>>2} items when expected ${this.numItems}.`);const e=this._boxes;if(this.numItems<=this.nodeSize){e[this._pos++]=this.minX,e[this._pos++]=this.minY,e[this._pos++]=this.maxX,e[this._pos++]=this.maxY;return}const{numItems:n,minX:o,minY:i,nodeSize:r,_indices:s,_levelBounds:a}=this,A=this.maxX-o||1,c=this.maxY-i||1,l=new Int32Array(n),u=65535,g=u/A,h=u/c;for(let p=0,m=0;p<n;p++){const _=e[m++],f=e[m++],I=e[m++],C=e[m++],y=g*((_+I)/2-o)|0,x=h*((f+C)/2-i)|0;l[p]=kIo(y,x)}RIo(l,e,s,0,n-1,r);let d=n*4;for(let p=0,m=0;p<a.length-1;p++){const _=a[p];for(;m<_;){const f=m;let I=e[m++],C=e[m++],y=e[m++],x=e[m++];for(let E=1;E<r&&m<_;E++)I=Math.min(I,e[m++]),C=Math.min(C,e[m++]),y=Math.max(y,e[m++]),x=Math.max(x,e[m++]);s[d>>2]=f,e[d++]=I,e[d++]=C,e[d++]=y,e[d++]=x}}this._pos=d}search(e,n,o,i,r){if(this._pos!==this._boxes.length)throw new Error("Data not yet indexed - call index.finish().");const{_boxes:s,_levelBounds:a,_indices:A,nodeSize:c}=this,l=this.numItems*4;let u=s.length-4,g=a.length-1;const h=[],d=[];let p=!1;for(;u!==void 0;){const m=Math.min(u+c*4,a[g]),_=u>=l;if(p)this._collectContained(u,m,g,l,d,r);else for(let f=u;f<m;f+=4){const I=s[f];if(o<I)continue;const C=s[f+1];if(i<C)continue;const y=s[f+2];if(e>y)continue;const x=s[f+3];if(n>x)continue;const E=A[f>>2]|0;if(_){const B=+(e<=I&&n<=C&&o>=y&&i>=x);h.push(E|B,g-1)}else(r===void 0||r(E,I,C,y,x))&&d.push(E)}g=h.pop(),u=h.pop(),u!==void 0&&(p=(u&1)===1,u&=-2)}return d}_collectContained(e,n,o,i,r,s){const a=this._boxes,A=this._indices;let c=e;for(let u=o;u>0;u--)c=A[c>>2];const l=Math.min(c+(n-e)*this.nodeSize**o,i);if(s===void 0)for(;c<l;c+=4)r.push(A[c>>2]|0);else for(;c<l;c+=4){const u=A[c>>2]|0;s(u,a[c],a[c+1],a[c+2],a[c+3])&&r.push(u)}}neighbors(e,n,o=1/0,i=1/0,r){if(this._pos!==this._boxes.length)throw new Error("Data not yet indexed - call index.finish().");const{_boxes:s,_levelBounds:a,_indices:A,_queue:c,nodeSize:l}=this,u=this.numItems*4,g=l*4,h=[],d=i*i,p=o===1;let m=d;for(c.push(s.length-4<<1,0);c.length;){const _=c.ids[0];if(_&1){if(c.pop(),h.push(_>>1),h.length===o)break;continue}c.pop();const f=_>>1,I=f<u,C=Math.min(f+g,NIo(f,a));for(let y=f;y<C;y+=4){const x=s[y],E=s[y+1],B=s[y+2],S=s[y+3],Q=Math.max(Math.max(x-e,e-B),0),w=Math.max(Math.max(E-n,n-S),0),M=Q*Q+w*w;if(M>m)continue;const k=A[y>>2]|0;I?(r===void 0||r(k))&&(c.push(k<<1|1,M),p&&M<m&&(m=M)):c.push(k<<1,M)}}return c.clear(),h}}function NIo(t,e){let n=0,o=e.length-1;for(;n<o;){const i=n+o>>1;e[i]>t?o=i:n=i+1}return e[n]}function RIo(t,e,n,o,i,r){const s=[o,i];for(;s.length;){const a=s.pop()||0,A=s.pop()||0;if(a-A<=r&&Math.floor(A/r)>=Math.floor(a/r))continue;const c=t[A],l=t[A+a>>1],u=t[a],g=c>l!=c>u?c:l<c!=l<u?l:u;let h=A-1,d=a+1;for(;;){do h++;while(t[h]<g);do d--;while(t[d]>g);if(h>=d)break;TIo(t,e,n,h,d)}s.push(A,d,d+1,a)}}function TIo(t,e,n,o,i){const r=t[o];t[o]=t[i],t[i]=r;const s=4*o,a=4*i,A=e[s],c=e[s+1],l=e[s+2],u=e[s+3];e[s]=e[a],e[s+1]=e[a+1],e[s+2]=e[a+2],e[s+3]=e[a+3],e[a]=A,e[a+1]=c,e[a+2]=l,e[a+3]=u;const g=n[o];n[o]=n[i],n[i]=g}function kIo(t,e){let n=t^e,o=65535^n,i=65535^(t|e),r=t&(e^65535),s=n|o>>1,a=n>>1^n,A=i^(i>>1^o&r>>1),c=r^(n&i>>1^r>>1);return n=s&s>>2^a&a>>2,o=s&a>>2^a&(s^a)>>2,i=A^(s&A>>2^a&c>>2),r=c^(a&A>>2^(s^a)&c>>2),s=n&n>>4^o&o>>4,a=n&o>>4^o&(n^o)>>4,A=i^(n&i>>4^o&r>>4),c=r^(o&i>>4^(n^o)&r>>4),i=A^(s&A>>8^a&c>>8),r=c^(a&A>>8^(s^a)&c>>8),i^=i>>1,r^=r>>1,n=t^e,o=r|65535^(n|i),n=(n|n<<8)&16711935,n=(n|n<<4)&252645135,n=(n|n<<2)&858993459,n=(n|n<<1)&1431655765,o=(o|o<<8)&16711935,o=(o|o<<4)&252645135,o=(o|o<<2)&858993459,o=(o|o<<1)&1431655765,((o<<1|n)>>>0)-2147483648}var Ng=class{MAX_ITERATIONS=1e5;solved=!1;failed=!1;iterations=0;progress=0;error=null;activeSubSolver;failedSubSolvers;timeToSolve;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(){const e=Date.now();for(;!this.solved&&!this.failed;)this.step();const n=Date.now();this.timeToSolve=n-e}visualize(){return{lines:[],points:[],rects:[],circles:[]}}tryFinalAcceptance(){}preview(){return{lines:[],points:[],rects:[],circles:[]}}},Mc=(t,e=1)=>`hsl(${t.split("").reduce((o,i)=>o*31+i.charCodeAt(0),0)%360}, 100%, 50%, ${e})`,tQt=(t,e,n)=>{if(n.chipId){const o=t.get(n.chipId);if(o)return o}return e.get(n.pinId)},Zv=(t,e,n)=>{const o=new Map,i=new Map;for(const a of t.chips)if(a.sectionId){o.set(a.chipId,a.sectionId);for(const A of a.pins)i.set(A.pinId,a.sectionId)}if(o.size===0)return!1;const r=tQt(o,i,e),s=tQt(o,i,n);return r!==s},vve=(t,e,n)=>{const{x:o,y:i}=t,{center:r,width:s,height:a}=e,A=r.y+a/2,c=r.y-a/2,l=r.x+s/2,u=r.x-s/2,g=A-i,h=i-c,d=l-o,p=o-u,m=Math.min(g,h,d,p),_=m===g?"y+":m===h?"y-":m===d?"x+":"x-",f=[{direction:"y+",distance:g},{direction:"y-",distance:h},{direction:"x+",distance:d},{direction:"x-",distance:p}].filter(({distance:E})=>Math.abs(E-m)<=1e-9).map(({direction:E})=>E),I=[_,...f.filter(E=>E!==_)];if(!n||I.length<=1)return I;const C=n.x-t.x,y=n.y-t.y,x=Math.abs(C)>=Math.abs(y)?C>=0?"x+":"x-":y>=0?"y+":"y-";return I.includes(x)?[x,...I.filter(E=>E!==x)]:I},W5=(t,e,n)=>vve(t,e,n)[0],zh=(t,e={})=>{const{connectionAlpha:n=.8,chipAlpha:o=.8,hideRatsNet:i=t._hideRatsNet??!1}=e,r={lines:[],points:[],rects:[]},s=new Map;for(const a of t.chips)for(const A of a.pins)s.set(A.pinId,A);for(const a of t.chips){r.rects.push({label:a.chipId,center:a.center,width:a.width,height:a.height,fill:Mc(a.chipId,o)});for(const A of a.pins)r.points.push({label:`${A.displayName??A.pinId}
${A._facingDirection??W5(A,a)}`,x:A.x,y:A.y,color:Mc(A.pinId,.8)})}for(const a of t.textBoxes??[])r.rects.push({label:a.text??"schematic_text",center:a.center,width:a.width,height:a.height,fill:"rgba(160, 0, 220, 0.14)",strokeColor:"rgba(160, 0, 220, 0.9)"});if(!i){for(const a of t.directConnections){const[A,c]=a.pinIds,l=s.get(A),u=s.get(c);Zv(t,l,u)||r.lines.push({points:[{x:l.x,y:l.y},{x:u.x,y:u.y}],strokeColor:Mc(a.netId??`${A}-${c}`,n)})}for(const a of t.netConnections){const A=a.pinIds.map(c=>s.get(c));for(let c=0;c<A.length-1;c++)for(let l=c+1;l<A.length;l++){const u=A[c],g=A[l];Zv(t,u,g)||r.lines.push({points:[{x:u.x,y:u.y},{x:g.x,y:g.y}],strokeColor:Mc(a.netId,n),strokeDash:"4 2"})}}}return r},FIo=t=>{const{pins:e,inputProblem:n,pinIdMap:o,chipMap:i}=t,r=g=>{const h=new Set,d=[g];h.add(g);const p=n.directConnections||[];for(;d.length;){const m=d.shift();for(const _ of p)if(_.pinIds.includes(m))for(const f of _.pinIds)h.has(f)||(h.add(f),d.push(f))}return h},s=e[0].pinId,a=e[1].pinId,A=new Set([...r(s),...r(a)]),c=new Map,l=new Map,u=new Set(e.map(g=>g.chipId));for(const g of A){const h=o.get(g);if(!h)continue;const d=i[h.chipId];if(!d)continue;const p=h._facingDirection??W5(h,d);let m=l.get(d.chipId);if(!m){m={center:d.center};const _={xPos:0,xNeg:0,yPos:0,yNeg:0};for(const f of d.pins){const I=f._facingDirection??W5(f,d);I==="x+"&&_.xPos++,I==="x-"&&_.xNeg++,I==="y+"&&_.yPos++,I==="y-"&&_.yNeg++}m.counts=_,l.set(d.chipId,m)}p==="x+"&&(m.hasXPos=!0),p==="x-"&&(m.hasXNeg=!0),p==="y+"&&(m.hasYPos=!0),p==="y-"&&(m.hasYNeg=!0)}for(const[g,h]of l){const d=new Set,p={axes:d},m=h.counts;!(m&&(m.xPos>1||m.xNeg>1||m.yPos>1||m.yNeg>1))&&u.has(g)||(h.hasXPos&&h.hasXNeg&&(p.x=h.center.x,d.add("x")),h.hasYPos&&h.hasYNeg&&(p.y=h.center.y,d.add("y"))),d.size>0&&c.set(g,p)}return c},lj=t=>{const{inputProblem:e,chipMap:n,pinIdMap:o,p1:i,p2:r}=t,s=FIo({pins:[i,r],inputProblem:e,pinIdMap:o,chipMap:n});if(s.size===0)return!1;const a=1e-9,A=(h,d)=>{for(const[,p]of s)if(p.axes.has("x")&&typeof p.x=="number"&&(h.x-p.x)*(d.x-p.x)<-a||p.axes.has("y")&&typeof p.y=="number"&&(h.y-p.y)*(d.y-p.y)<-a)return!0;return!1};if(Math.abs(i.x-r.x)<a||Math.abs(i.y-r.y)<a)return A({x:i.x,y:i.y},{x:r.x,y:r.y});const c={x:r.x,y:i.y},l={x:i.x,y:r.y},u=A({x:i.x,y:i.y},c)||A(c,{x:r.x,y:r.y}),g=A({x:i.x,y:i.y},l)||A(l,{x:r.x,y:r.y});return u&&g},mB=t=>{const e=new mle({});for(const o of t.directConnections)e.addConnections([o.netId?[o.netId,...o.pinIds]:o.pinIds]);const n=new mle(e.netMap);for(const o of t.netConnections)n.addConnections([[o.netId,...o.pinIds]]);return{directConnMap:e,netConnMap:n}},LIo=1,nQt=t=>{const{netConnMap:e}=mB(t),n=e.getNetConnectedToId("GND"),o=new mle({}),i=new Set;for(const l of t.directConnections){o.addConnections([l.pinIds]);const u=e.getNetConnectedToId(l.pinIds[0]),g=t.netConnections.some(h=>h.isGround&&e.getNetConnectedToId(h.netId)===u);u&&g&&i.add(u)}const r=new Map(t.chips.flatMap(l=>l.pins.map(u=>[u.pinId,{pin:u,chip:l}]))),s=[...r.values()].filter(({pin:l,chip:u})=>u.pins.length===2&&e.getNetConnectedToId(l.pinId)===n&&(l._facingDirection??W5(l,u))==="y-"),a=s.some(({pin:l})=>{const u=o.getNetConnectedToId(l.pinId);return u!==void 0&&s.some(({pin:g})=>l.pinId!==g.pinId&&Math.abs(l.y-g.y)<1e-6&&Math.abs(l.x-g.x)>1e-6&&o.getNetConnectedToId(g.pinId)===u)}),A=(l,u)=>{const g=r.get(l)?.chip.chipId,h=r.get(u)?.chip.chipId;if(g!==void 0&&g===h&&!o.getNetConnectedToId(l)&&!o.getNetConnectedToId(u))return!1;const p=e.getNetConnectedToId(l),m=e.getNetConnectedToId(u);if(!p||p!==m||!i.has(p))return!1;const _=o.getNetConnectedToId(l)??`pin:${l}`,f=o.getNetConnectedToId(u)??`pin:${u}`;return _!==f};if(!a)return(l,u)=>!A(l,u);const c=l=>{const u=r.get(l);return u?.chip.pins.length===2&&!o.getNetConnectedToId(l)&&(u.pin._facingDirection??W5(u.pin,u.chip))==="y-"};return(l,u)=>{const g=e.getNetConnectedToId(l),h=e.getNetConnectedToId(u);if(A(l,u))return!1;if(!n||g!==n||h!==n||!c(l)&&!c(u))return!0;const d=r.get(l)?.pin,p=r.get(u)?.pin;return!d||!p||Math.abs(d.y-p.y)<=LIo+1e-6}};function HIo(t,e={}){const n=t.length,o=e?.maxDistance??Number.POSITIVE_INFINITY;if(n<=1)return[];{const l=new Set;for(const u of t){if(l.has(u.pinId))throw new Error(`Duplicate pinId detected: "${u.pinId}"`);l.add(u.pinId)}}const i=(l,u)=>Math.abs(l.x-u.x)+Math.abs(l.y-u.y),r=new Array(n).fill(!1),s=new Array(n).fill(Number.POSITIVE_INFINITY),a=new Array(n).fill(-1);let A=0;for(let l=1;l<n;l++)t[l].pinId<t[A].pinId&&(A=l);s[A]=0;const c=[];for(let l=0;l<n;l++){let u=-1,g=Number.POSITIVE_INFINITY,h="";for(let d=0;d<n;d++)if(!r[d]){const p=s[d];(p<g||p===g&&(h===""||t[d].pinId<h))&&(g=p,h=t[d].pinId,u=d)}r[u]=!0,a[u]!==-1&&c.push([t[u].pinId,t[a[u]].pinId]);for(let d=0;d<n;d++)if(!r[d]){const p=i(t[u],t[d]),m=e?.forbidEdge?.(t[u],t[d])??!1,_=p>o||m?Number.POSITIVE_INFINITY:p;(_<s[d]||_===s[d]&&t[u].pinId<t[a[d]]?.pinId)&&(s[d]=_,a[d]=u)}}return c}var OIo=.45,wve=.2;function _B(t){const{orientation:e,netLabelWidth:n,netLabelHeight:o}=t,i=typeof n=="number"?n:OIo,r=typeof o=="number"?o:wve;return e==="y+"||e==="y-"?{width:r,height:i}:{width:i,height:r}}function IC(t,e,n,o){switch(e){case"x+":return{x:t.x+n/2,y:t.y};case"x-":return{x:t.x-n/2,y:t.y};case"y+":return{x:t.x,y:t.y+o/2};case"y-":return{x:t.x,y:t.y-o/2}}}function Ls(t,e,n){return{minX:t.x-e/2,minY:t.y-n/2,maxX:t.x+e/2,maxY:t.y+n/2}}var oQt=({inputProblem:t,chipMap:e,pins:n})=>{const[o,i]=n,r=t.directConnections.find(f=>f.pinIds.includes(o.pinId)&&f.pinIds.includes(i.pinId));if(r?.netLabelWidth===void 0)return null;const s=e[o.chipId],a=e[i.chipId];if(!s||!a)return null;let A=o._facingDirection;A||(A=W5(o,s));let c=i._facingDirection;if(c||(c=W5(i,a)),!(A==="x-"&&c==="x+"||A==="x+"&&c==="x-"))return null;if(s.pins.length===1||a.pins.length===1)return"single-pin-peripheral";if(!(s.sectionId&&s.sectionId===a.sectionId?s.sectionId:null))return null;const d=o.x<=i.x?A==="x+"&&c==="x-":A==="x-"&&c==="x+",p=Math.abs(o.x-i.x)<r.netLabelWidth*2,m=Math.abs(o.y-i.y)<wve;return d&&p&&m?"overlapping-fallback-labels":null},GIo=t=>oQt(t)!==null,iQt=1e-6,YIo=3;function rQt({pin:t,netPins:e}){const n=e.filter(i=>Math.abs(i.y-t.y)<=iQt);return new Set(n.map(i=>i.chipId)).size>=YIo}function UIo({netConnection:t,netPins:e,pin1:n,pin2:o}){return!t?.isGround||n.chipId===o.chipId||Math.abs(n.y-o.y)<=iQt?!1:rQt({pin:n,netPins:e})&&rQt({pin:o,netPins:e})}var _b=1e-6,KIo=4,sQt=2,_le=(t,e)=>JSON.stringify([t,e].sort()),aQt=(t,e,n)=>{const o=new Set,i=new Set,r=new Set;for(const l of t.netConnections){for(const g of l.pinIds)i.add(g);const u=e.getNetConnectedToId(l.netId);u&&l.isGround&&o.add(u)}for(const l of t.directConnections){const u=l.netLabelWidth===void 0?r:i;for(const g of l.pinIds)u.add(g)}const s=[];for(const l of t.chips){if(l.pins.length!==2||l.symbolName&&!l.symbolName.startsWith("capacitor")||!l.pins.every(p=>i.has(p.pinId))||l.pins.some(p=>r.has(p.pinId)))continue;const u=l.pins.map(p=>e.getNetConnectedToId(p.pinId));if(!u[0]||!u[1]||u[0]===u[1]||o.has(u[0])===o.has(u[1]))continue;const g=l.pins.map(p=>p._facingDirection??W5(p,l));if(g[0][0]!==g[1][0]||g[0]===g[1])continue;const h=g[0][0],d=h==="x"?"y":"x";if(!(Math.abs(l.pins[0][d]-l.pins[1][d])>_b))for(const[p,m]of l.pins.entries()){const _=g[p];let f=s.find(I=>I.sectionId===l.sectionId&&I.direction===_&&Math.abs(I.coordinate-m[h])<=_b);f||(f={sectionId:l.sectionId,direction:_,coordinate:m[h],axis:h,pins:[]},s.push(f)),f.pins.push({...m,chipId:l.chipId,oppositeCoordinate:l.pins[1-p][h]})}}const a=new Set,A=new Set,c=new Set;for(const l of s){const u=l.axis==="x"?"y":"x";l.pins.sort((g,h)=>g[u]-h[u]||g.pinId.localeCompare(h.pinId));for(let g=1;g<l.pins.length;g++){const h=l.pins[g-1],d=l.pins[g],p=d[u]-h[u],m=[h[u]-(l.pins[g-2]?.[u]??h[u]),(l.pins[g+1]?.[u]??d[u])-d[u]].filter(C=>C>_b),_=Math.max(sQt*n,sQt*(m.length?Math.min(...m):0),KIo*Math.max(Math.abs(h[l.axis]-h.oppositeCoordinate),Math.abs(d[l.axis]-d.oppositeCoordinate)));if(p<=_b||e.getNetConnectedToId(h.pinId)!==e.getNetConnectedToId(d.pinId))continue;if(p>_+_b){c.add(h.pinId),c.add(d.pinId);continue}const f=Math.min(h[l.axis],d[l.axis],h.oppositeCoordinate,d.oppositeCoordinate),I=Math.max(h[l.axis],d[l.axis],h.oppositeCoordinate,d.oppositeCoordinate);t.chips.some(C=>{if(C.chipId===h.chipId||C.chipId===d.chipId)return!1;const y=l.axis==="x"?C.width:C.height,x=u==="x"?C.width:C.height;return C.center[l.axis]+y/2>=f-_b&&C.center[l.axis]-y/2<=I+_b&&C.center[u]+x/2>h[u]+_b&&C.center[u]-x/2<d[u]-_b})||(a.add(_le(h.pinId,d.pinId)),p>n&&(A.add(h.pinId),A.add(d.pinId)))}}return{pairKeys:a,extendedRailPinIds:A,separatedRailPinIds:c}},uj=1,AQt=t=>[...t].sort().join("::"),VIo=class extends Ng{inputProblem;mspConnectionPairs=[];mspConnectionPairIds=new Set;dcConnMap;globalConnMap;queuedDcNetIds;chipMap;maxMspPairDistance;pinMap;userNetIdByPinId;directConnectionPinPairKeys;canRouteGroundPair;parallelRailPairKeys;constructor({inputProblem:t}){super(),this.inputProblem=t,this.canRouteGroundPair=nQt(t),this.maxMspPairDistance=t.maxMspPairDistance??uj;const{directConnMap:e,netConnMap:n}=mB(t);this.dcConnMap=e,this.globalConnMap=n,this.parallelRailPairKeys=aQt(t,n,this.maxMspPairDistance).pairKeys,this.pinMap={};for(const o of t.chips)for(const i of o.pins)this.pinMap[i.pinId]={...i,chipId:o.chipId};this.chipMap={};for(const o of t.chips)this.chipMap[o.chipId]=o;this.userNetIdByPinId={},this.directConnectionPinPairKeys=new Set;for(const o of t.directConnections)if(this.directConnectionPinPairKeys.add(AQt(o.pinIds)),o.netId){const[i,r]=o.pinIds;this.userNetIdByPinId[i]=o.netId,this.userNetIdByPinId[r]=o.netId}for(const o of t.netConnections)for(const i of o.pinIds)this.userNetIdByPinId[i]=o.netId;this.queuedDcNetIds=Object.keys(n.netMap)}getConstructorParams(){return{inputProblem:this.inputProblem}}addMspConnectionPair(t){this.mspConnectionPairIds.has(t.mspPairId)||(this.mspConnectionPairIds.add(t.mspPairId),this.mspConnectionPairs.push(t))}_step(){if(this.queuedDcNetIds.length===0){this.solved=!0;return}const t=this.queuedDcNetIds.shift(),n=this.globalConnMap.getIdsConnectedToNet(t).filter(A=>!!this.pinMap[A]);if(n.length<=1)return;if(n.length===2){const[A,c]=n,l=this.pinMap[A],u=this.pinMap[c];if(!this.canRouteGroundPair(A,c))return;const g=AQt([A,c]);let h=Math.abs(l.x-u.x)+Math.abs(l.y-u.y);this.directConnectionPinPairKeys.has(g)&&(h=ad(l,u));const d=oQt({inputProblem:this.inputProblem,chipMap:this.chipMap,pins:[l,u]});if(h>this.maxMspPairDistance&&!this.parallelRailPairKeys.has(_le(A,c))&&!d||Zv(this.inputProblem,l,u))return;const p=new Map(Object.entries(this.pinMap));if(lj({inputProblem:this.inputProblem,chipMap:this.chipMap,pinIdMap:p,p1:l,p2:u}))return;const m=this.globalConnMap.getNetConnectedToId(A),_=this.userNetIdByPinId[A]??this.userNetIdByPinId[c],f=h>this.maxMspPairDistance&&d==="overlapping-fallback-labels";this.addMspConnectionPair({mspPairId:`${A}-${c}`,dcConnNetId:t,globalConnNetId:m,userNetId:_,suppressNetLabel:f,pins:[l,u]});return}const o=new Map(Object.entries(this.pinMap)),i=this.userNetIdByPinId[n[0]],r=this.inputProblem.netConnections.find(A=>A.netId===i),s=n.map(A=>this.pinMap[A]),a=HIo(s,{forbidEdge:(A,c)=>Math.abs(A.x-c.x)+Math.abs(A.y-c.y)>this.maxMspPairDistance&&!this.parallelRailPairKeys.has(_le(A.pinId,c.pinId))||!this.canRouteGroundPair(A.pinId,c.pinId)||UIo({netConnection:r,netPins:s,pin1:A,pin2:c})||Zv(this.inputProblem,A,c)||lj({inputProblem:this.inputProblem,chipMap:this.chipMap,pinIdMap:o,p1:A,p2:c})});for(let[A,c]of a){this.parallelRailPairKeys.has(_le(A,c))&&Math.abs(this.pinMap[A].x-this.pinMap[c].x)+Math.abs(this.pinMap[A].y-this.pinMap[c].y)>this.maxMspPairDistance&&n.indexOf(A)>n.indexOf(c)&&([A,c]=[c,A]);const l=this.pinMap[A],u=this.pinMap[c];if(Zv(this.inputProblem,l,u)||lj({inputProblem:this.inputProblem,chipMap:this.chipMap,pinIdMap:o,p1:l,p2:u}))continue;const g=this.globalConnMap.getNetConnectedToId(A),h=this.userNetIdByPinId[A]??this.userNetIdByPinId[c];this.addMspConnectionPair({mspPairId:`${A}-${c}`,dcConnNetId:t,globalConnNetId:g,userNetId:h,pins:[l,u]})}}visualize(){const t=zh(this.inputProblem,{chipAlpha:.1,connectionAlpha:.1});for(const e of this.mspConnectionPairs)t.lines.push({points:[{x:e.pins[0].x,y:e.pins[0].y},{x:e.pins[1].x,y:e.pins[1].y}],strokeColor:Mc(e.mspPairId,.75)});return t}},cQt=(t,e)=>{const n=t.find(o=>o?.netLabelWidth!==void 0)?.netLabelWidth;return n!==void 0||!e?n:t.find(o=>o?.anchoredNetLabelWidth!==void 0)?.anchoredNetLabelWidth},L7=({inputProblem:t,netId:e,pinIds:n,isPortOnlyLabel:o})=>{if(e){const i=cQt([t.netConnections.find(r=>r.netId===e),t.directConnections.find(r=>r.netId===e)],o);if(i!==void 0)return i}return cQt([t.directConnections.find(i=>i.pinIds.some(r=>n.includes(r))),t.netConnections.find(i=>i.pinIds.some(r=>n.includes(r)))],o)};function fB(t,e={}){return{minX:t.center.x-t.width/2-(e.minX??0),minY:t.center.y-t.height/2-(e.minY??0),maxX:t.center.x+t.width/2+(e.maxX??0),maxY:t.center.y+t.height/2+(e.maxY??0)}}function Dc(t,e,n=1e-9){return t.minX<e.maxX-n&&t.maxX>e.minX+n&&t.minY<e.maxY-n&&t.maxY>e.minY+n}function KH(t,e){for(const n of e.textBoxes??[])if(Dc(t,fB(n)))return!0;return!1}var lQt=.15,gj=lQt/7.5,zIo=.2;function fle(t,e){return e.x>t.x?"x+":e.x<t.x?"x-":e.y>t.y?"y+":e.y<t.y?"y-":null}function Pve({path:t,pin1:e,pin2:n}){const o=fle(t[0],t[1]),i=fle(t[t.length-1],t[t.length-2]);return o===e._facingDirection&&i===n._facingDirection}function JIo(t,e){if(t.x===e.x||t.y===e.y)return null;const n=t._facingDirection,o=e._facingDirection,i={x:t.x,y:t.y},r={x:e.x,y:e.y};let s=null;if(n?.startsWith("y")&&o?.startsWith("x")){let a=-gj;n==="y+"&&(a=gj);const A=i.y+a,c=(i.x+r.x)/2;s=[i,{x:i.x,y:A},{x:c,y:A},{x:c,y:r.y},r]}else if(n?.startsWith("x")&&o?.startsWith("y")){let a=-gj;n==="x+"&&(a=gj);const A=i.x+a,c=(i.y+r.y)/2;s=[i,{x:A,y:i.y},{x:A,y:c},{x:r.x,y:c},r]}return s&&Pve({path:s,pin1:t,pin2:e})?s:null}function WIo(t,e){const n=Math.abs(t.x-e.x)+Math.abs(t.y-e.y);if(n>lQt)return null;const o={x:t.x,y:t.y},i={x:e.x,y:e.y},r=JIo(t,e);if(r)return r;let s=[];t.x!==e.x&&t.y!==e.y?s=[[o,{x:e.x,y:t.y},i],[o,{x:t.x,y:e.y},i]]:s=[[o,i]];for(const a of s)if(Pve({path:a,pin1:t,pin2:e}))return a;return wF({x:t.x,y:t.y,facingDirection:t._facingDirection},{x:e.x,y:e.y,facingDirection:e._facingDirection},{overshoot:Math.min(zIo,Math.max(gj,n/4))})}var Ile=1e-9,e1=(t,e,n=Ile)=>Math.abs(t.x-e.x)<n,X_=(t,e,n=Ile)=>Math.abs(t.y-e.y)<n,CC=(t,e,n,o=Ile)=>{const i=e1(t,e,o),r=X_(t,e,o);if(!i&&!r)return!1;if(i){const s=t.x;if(s<n.minX-o||s>n.maxX+o)return!1;const a=Math.min(t.y,e.y),A=Math.max(t.y,e.y);return Math.min(A,n.maxY)-Math.max(a,n.minY)>o}else{const s=t.y;if(s<n.minY-o||s>n.maxY+o)return!1;const a=Math.min(t.x,e.x),A=Math.max(t.x,e.x);return Math.min(A,n.maxX)-Math.max(a,n.minX)>o}},Mve=(t,e,n,o=Ile)=>e1(t,e,o)?Math.abs(t.x-n.minX)<=o||Math.abs(t.x-n.maxX)<=o?Math.min(Math.max(t.y,e.y),n.maxY)-Math.max(Math.min(t.y,e.y),n.minY)>o:!1:X_(t,e,o)&&(Math.abs(t.y-n.minY)<=o||Math.abs(t.y-n.maxY)<=o)?Math.min(Math.max(t.x,e.x),n.maxX)-Math.max(Math.min(t.x,e.x),n.minX)>o:!1,HN=(t,e,n={})=>{for(let o=0;o<t.length-1;o++){const i=t[o],r=t[o+1],s=n.excludeRectsForSegment?.(o)??new Set;for(const a of e)if(!s.has(a)&&CC(i,r,a))return{segIndex:o,rect:a}}return null},ON=(t,e)=>{for(let n=0;n<t.length-1;n++)for(const o of e)if(CC(t[n],t[n+1],o))return!0;return!1},uQt=1e-9,ew=.2,jIo=(t,e)=>({minX:Math.min(t.x,e.x),maxX:Math.max(t.x,e.x),minY:Math.min(t.y,e.y),maxY:Math.max(t.y,e.y)}),tw=(t,e,n,o=uQt)=>t==="x"?e.x<n.minX-o?[(e.x+n.minX)/2]:e.x>n.maxX+o?[(e.x+n.maxX)/2]:[n.minX-ew,n.maxX+ew]:e.y<n.minY-o?[(e.y+n.minY)/2]:e.y>n.maxY+o?[(e.y+n.maxY)/2]:[n.minY-ew,n.maxY+ew],gQt=(t,e,n,o,i={})=>{const{allowOpenSideCandidates:r=!1,eps:s=uQt}=i,a=[...n];if(t==="x"){const A=[o.minX,...a.map(h=>h.maxX)].filter(h=>h<e.minX-s),c=[o.maxX,...a.map(h=>h.minX)].filter(h=>h>e.maxX+s),l=A.length>0?Math.max(...A):void 0,u=c.length>0?Math.min(...c):void 0,g=[];return l!==void 0?g.push((l+e.minX)/2):r&&g.push(e.minX-ew),u!==void 0?g.push((e.maxX+u)/2):r&&g.push(e.maxX+ew),g}else{const A=[o.minY,...a.map(h=>h.maxY)].filter(h=>h<e.minY-s),c=[o.maxY,...a.map(h=>h.minY)].filter(h=>h>e.maxY+s),l=A.length>0?Math.max(...A):void 0,u=c.length>0?Math.min(...c):void 0,g=[];return l!==void 0?g.push((l+e.minY)/2):r&&g.push(e.minY-ew),u!==void 0?g.push((e.maxY+u)/2):r&&g.push(e.maxY+ew),g}},$Io=1e-9,dQt=t=>t.every((e,n)=>{const o=t[n+1];return o?!X_(e,o)&&!e1(e,o)?!1:Math.abs(e.x-o.x)+Math.abs(e.y-o.y)>0:!0}),Dve=(t,e,n,o,i=$Io)=>{if(e<0||e>=t.length-1)return null;const r=t[e],s=t[e+1],a=e1(r,s,i),A=X_(r,s,i);if(!a&&!A||a&&n!=="x"||A&&n!=="y")return null;const c=t.map(l=>({...l}));if(n==="x"){if(Math.abs(r.x-o)<i&&Math.abs(s.x-o)<i)return null;c[e]={...c[e],x:o},c[e+1]={...c[e+1],x:o}}else{if(Math.abs(r.y-o)<i&&Math.abs(s.y-o)<i)return null;c[e]={...c[e],y:o},c[e+1]={...c[e+1],y:o}}if(e-1>=0){const l=c[e-1],u=c[e];if(Math.abs(l.x-u.x)+Math.abs(l.y-u.y)<i)return null}if(e+2<=c.length-1){const l=c[e+1],u=c[e+2];if(Math.abs(l.x-u.x)+Math.abs(l.y-u.y)<i)return null}for(let l=0;l<c.length-1;l++){const u=c[l],g=c[l+1];if(!X_(u,g,i)&&!e1(u,g,i))return null}return c},Nve=(t,e=6)=>t.map(o=>`${o.x.toFixed(e)},${o.y.toFixed(e)}`).join("|"),hQt=(t,e)=>e1(t,e)?"x":X_(t,e)?"y":null,qIo=({path:t,collidingSegmentIndex:e,obstacle:n})=>{if(t.length<3||t.length>4)return[];const o=t.length-2;if(e!==0&&e!==o)return[];const i=e===o,r=i?[...t].reverse():t,[s,a,A]=r,c=hQt(s,a),l=hQt(a,A);if(!c||!l)return[];if(c===l)return[];const u=[...tw(l,s,n),...tw(l,A,n)],g=[...tw(c,s,n),...tw(c,A,n)],h=[];for(const d of[...new Set(u)])for(const p of[...new Set(g)]){const _=[...c==="y"?[s,{x:d,y:s.y},{x:d,y:p},{x:A.x,y:p},A]:[s,{x:s.x,y:d},{x:p,y:d},{x:p,y:A.y},A],...r.slice(3)],f=i?_.reverse():_;dQt(f)&&h.push(f)}return h},pQt=1e-9,XIo=.2,Cle=(t,e,n)=>t>Math.min(e,n)+pQt&&t<Math.max(e,n)-pQt,ZIo=({path:t,collidingSegmentIndex:e,obstacle:n,clearance:o=XIo})=>{if(e<=0||e>=t.length-2)return[];const i=t[e],r=t[e+1],s=[];if(X_(i,r)){const a=i.x<r.x,A=a?n.minX-o:n.maxX+o,c=a?n.maxX+o:n.minX-o;if(!Cle(A,i.x,r.x)||!Cle(c,i.x,r.x))return[];for(const l of[n.minY-o,n.maxY+o])s.push([{x:A,y:i.y},{x:A,y:l},{x:c,y:l},{x:c,y:r.y}])}else if(e1(i,r)){const a=i.y<r.y,A=a?n.minY-o:n.maxY+o,c=a?n.maxY+o:n.minY-o;if(!Cle(A,i.y,r.y)||!Cle(c,i.y,r.y))return[];for(const l of[n.minX-o,n.maxX+o])s.push([{x:i.x,y:A},{x:l,y:A},{x:l,y:c},{x:r.x,y:c}])}return s.map(a=>[...t.slice(0,e+1),...a,...t.slice(e+1)]).filter(dQt)};function Rve(t){const e=t.width/2,n=t.height/2;return{minX:t.center.x-e,maxX:t.center.x+e,minY:t.center.y-n,maxY:t.center.y+n}}var eCo=.05,mQt=t=>t.kind==="text_box",tCo=t=>{const e=Rve(t);return{kind:"chip",chipId:t.chipId,...e}},Hy=(t,e={})=>{const n=t.chips.map(tCo),o=(t.textBoxes??[]).map(i=>{const r=fB(i,e.textBoxPadding),s=n.find(c=>c.chipId===i.chipId),a=s?EV(r,s):Number.POSITIVE_INFINITY,A=s&&a>0&&a<eCo?{minX:Math.min(r.minX,s.maxX),maxX:Math.max(r.maxX,s.minX),minY:Math.min(r.minY,s.maxY),maxY:Math.max(r.maxY,s.minY)}:r;return{kind:"text_box",textBox:i,...A}});return[...n,...o]},_Qt=({pin1:t,pin2:e,overshoot:n})=>wF({x:t.x,y:t.y,facingDirection:t._facingDirection},{x:e.x,y:e.y,facingDirection:e._facingDirection},{overshoot:n}),nCo=({pin1:t,pin2:e})=>{const n=e.x-t.x,o=e.y-t.y;return Math.abs(n)>=Math.abs(o)?n>0?t._facingDirection==="x+"&&e._facingDirection==="x-":t._facingDirection==="x-"&&e._facingDirection==="x+":o>0?t._facingDirection==="y+"&&e._facingDirection==="y-":t._facingDirection==="y-"&&e._facingDirection==="y+"},dj=t=>{let e=0;for(let n=0;n<t.length-1;n++)e+=Math.abs(t[n+1].x-t[n].x)+Math.abs(t[n+1].y-t[n].y);return e},oCo=({pins:t,obstacles:e})=>{const[n,o]=t,i=WIo(n,o),r=_Qt({pin1:n,pin2:o,overshoot:.2}),s=Math.abs(n.x-o.x)+Math.abs(n.y-o.y),a=_Qt({pin1:n,pin2:o,overshoot:Math.min(.2,Math.max(.02,s/4))}),A=dj(a)<dj(r),c=dj(r)>s+1e-9,l=HN(a,e)===null&&(nCo({pin1:n,pin2:o})&&c&&A||HN(r,e)!==null);return{path:i??(l?a:r),isDirectShortPath:i!==null}},VH=class extends Ng{pins;connectionPair;inputProblem;chipMap;obstacles;textObstacles;endpointTextObstacles;aabb;baseElbow;preferExteriorDetours;reserveNetLabelClearance;solvedTracePath=null;queue=[];visited=new Set;inferredPinIndexes=new Set;hasAmbiguousPinDirections=!1;constructor(t){super(),this.pins=t.pins,this.connectionPair=t.connectionPair,this.inputProblem=t.inputProblem,this.chipMap=t.chipMap,this.preferExteriorDetours=t.preferExteriorDetours??!0,this.reserveNetLabelClearance=t.reserveNetLabelClearance??!0,this.obstacles=Hy(this.inputProblem,{textBoxPadding:this.reserveNetLabelClearance?this.getTextBoxPaddingForConnectionPair():void 0}),this.textObstacles=new Set(this.obstacles.filter(mQt));const e=new Set(this.pins.map(A=>A.chipId));this.endpointTextObstacles=new Set(this.obstacles.filter(mQt).filter(A=>A.textBox.chipId!==void 0&&e.has(A.textBox.chipId)));const n=this.pins.map((A,c)=>{if(A._facingDirection)return[A._facingDirection];this.inferredPinIndexes.add(c);const l=this.pins[c===0?1:0];return vve(A,this.chipMap[A.chipId],l)}),o=n[0].flatMap((A,c)=>n[1].map((l,u)=>({directions:[A,l],preferenceIndex:c+u})));this.hasAmbiguousPinDirections=n.some(A=>A.length>1);const i=o.map(({directions:A,preferenceIndex:c})=>{const l=this.pins.map((g,h)=>({...g,_facingDirection:A[h]})),u=oCo({pins:l,obstacles:this.obstacles});return{directions:A,baseElbow:u.path,isDirectShortPath:u.isDirectShortPath,preferenceIndex:c,collisionCount:HN(u.path,this.obstacles)===null?0:1,pathLength:dj(u.path)}}).sort((A,c)=>A.collisionCount-c.collisionCount||A.pathLength-c.pathLength||A.preferenceIndex-c.preferenceIndex),r=i[0];for(const[A,c]of this.pins.entries())c._facingDirection=r.directions[A];const[s,a]=this.pins;this.baseElbow=r.baseElbow,r.isDirectShortPath&&(this.solvedTracePath=r.baseElbow),this.aabb=jIo({x:s.x,y:s.y},{x:a.x,y:a.y});for(const A of i){const c=Nve(A.baseElbow);this.visited.has(c)||(this.visited.add(c),this.queue.push({path:A.baseElbow,collisionRects:new Set,directions:A.directions}))}}getConstructorParams(){return{chipMap:this.chipMap,pins:this.pins,connectionPair:this.connectionPair,inputProblem:this.inputProblem,preferExteriorDetours:this.preferExteriorDetours,reserveNetLabelClearance:this.reserveNetLabelClearance}}getTextBoxPaddingForConnectionPair(){if(!this.inputProblem.textBoxes?.length)return{};const t=this.connectionPair?.userNetId;if(!t)return{};const e=this.inputProblem.availableNetLabelOrientations[t]??["x+","x-","y+","y-"],n=L7({inputProblem:this.inputProblem,netId:t,pinIds:this.pins.map(r=>r.pinId),isPortOnlyLabel:!1}),o=this.getNetLabelHeightForConnectionPair(t),i={minX:0,minY:0,maxX:0,maxY:0};for(const r of e){const{width:s,height:a}=_B({orientation:r,netLabelWidth:n,netLabelHeight:o});r==="y+"||r==="y-"?(i.minX=Math.max(i.minX,s/2),i.maxX=Math.max(i.maxX,s/2),r==="y+"?i.minY=Math.max(i.minY,a):i.maxY=Math.max(i.maxY,a)):(i.minY=Math.max(i.minY,a/2),i.maxY=Math.max(i.maxY,a/2),r==="x+"?i.minX=Math.max(i.minX,s):i.maxX=Math.max(i.maxX,s))}return i}getNetLabelHeightForConnectionPair(t){const e=this.inputProblem.netConnections.find(o=>o.netId===t)?.netLabelHeight;if(e!==void 0)return e;const n=this.pins.map(o=>o.pinId);return this.inputProblem.netConnections.find(o=>o.pinIds.some(i=>n.includes(i)))?.netLabelHeight}axisOfSegment(t,e){return e1(t,e)?"x":X_(t,e)?"y":null}pathLength(t){return dj(t)}getPinBandPenalty(t){let e=0;for(let n=1;n<t.length-2;n++){const o=t[n],i=t[n+1];(X_(o,i)&&o.y>this.aabb.minY&&o.y<this.aabb.maxY||e1(o,i)&&o.x>this.aabb.minX&&o.x<this.aabb.maxX)&&(e+=10)}return e}isSegmentOutsidePinBand(t,e){return X_(t,e)?t.y<=this.aabb.minY||t.y>=this.aabb.maxY:e1(t,e)?t.x<=this.aabb.minX||t.x>=this.aabb.maxX:!1}_step(){if(this.solvedTracePath){this.solved=!0;return}const t=this.queue.shift();if(!t){this.failed=!0,this.error="No collision-free path found";return}const{path:e,collisionRects:n,directions:o}=t,[i,r]=this.pins,s=HN(e,this.obstacles,{excludeRectsForSegment:B=>{const S=e.length-2,Q=new Set,w=e[B],M=e[B+1],k=B===0?r:B===S?i:null;if(k)for(const U of this.textObstacles){const Y=fB(U.textBox);(U.textBox.chipId!==k.chipId||!CC(w,M,Y))&&Q.add(U)}const R=1e-9,F=U=>[w,M].some(Y=>Math.abs(Y.x-U.x)<=R&&Math.abs(Y.y-U.y)<=R);for(const U of this.pins){if(!F(U))continue;const Y=this.obstacles.find(W=>W.kind==="chip"&&W.chipId===U.chipId);Y&&Mve(w,M,Y)&&Q.add(Y)}const O=B===1?2:B===S-1?S-2:null;if(O!==null&&O>=0&&O<S&&this.isSegmentOutsidePinBand(e[O],e[O+1]))for(const U of this.endpointTextObstacles){const Y=fB(U.textBox);CC(w,M,Y)||Q.add(U)}return Q}});if(!s){const B=e[0],S=e[e.length-1],Q=1e-9,w=(M,k)=>Math.abs(M.x-k.x)<Q&&Math.abs(M.y-k.y)<Q;if(w(B,{x:i.x,y:i.y})&&w(S,{x:r.x,y:r.y})&&(!this.hasAmbiguousPinDirections||Pve({path:e,pin1:{...i,_facingDirection:o[0]},pin2:{...r,_facingDirection:o[1]}}))){for(const M of this.inferredPinIndexes){const k=M===0?fle(e[0],e[1]):fle(e.at(-1),e.at(-2));k&&(this.pins[M]._facingDirection=k)}this.solvedTracePath=e,this.solved=!0}return}const a=s.segIndex;let{segIndex:A,rect:c}=s;const l=A===0,u=A===e.length-2,g=c.kind==="chip"&&this.pins.some(B=>B.chipId===c.chipId);if((e.length===3||e.length===4&&this.connectionPair!==void 0&&!g)&&(l||u)){const B=qIo({path:e,collidingSegmentIndex:A,obstacle:c}).filter(S=>{const Q=Nve(S);return this.visited.has(Q)?!1:(this.visited.add(Q),!0)}).sort((S,Q)=>e.length===4&&this.preferExteriorDetours?this.getPinBandPenalty(S)-this.getPinBandPenalty(Q)||this.pathLength(S)-this.pathLength(Q):this.pathLength(S)-this.pathLength(Q)||this.getPinBandPenalty(S)-this.getPinBandPenalty(Q));for(const S of B){const Q=new Set(n);Q.add(c),this.queue.push({path:S,collisionRects:Q,directions:o})}return}if(l){if(e.length<3)return;A=1}else if(u){if(e.length<3)return;A=e.length-3}const d=e[A],p=e[A+1],m=this.axisOfSegment(d,p);if(!m)return;const _=[],f={allowOpenSideCandidates:this.connectionPair!==void 0};if(n.size===0){const B=tw(m,{x:i.x,y:i.y},c),S=tw(m,{x:r.x,y:r.y},c),Q=[...B,...S],w=[...new Set(Q)];_.push(...w)}else{const B=gQt(m,c,n,this.aabb,f);_.push(...B)}const I=[],C=B=>{const S=Nve(B);if(this.visited.has(S))return;this.visited.add(S);const Q=new Set(n);Q.add(c),I.push({path:B,collisionRects:Q,length:this.pathLength(B),pinBandPenalty:this.getPinBandPenalty(B)})},y=(B,S,Q)=>{const w=Dve(e,B,S,Q);w&&C(w)},x=e.length-2;if(this.connectionPair===void 0&&c.kind==="text_box"&&this.endpointTextObstacles.has(c)&&!n.has(c)&&a>0&&a<x)for(const B of ZIo({path:e,collidingSegmentIndex:a,obstacle:c}))C(B);for(const B of _)y(A,m,B);const E=a===1?[2]:a===x-1?[x-2]:[];for(const B of E){if(B<0||B>=x)continue;const S=this.axisOfSegment(e[B],e[B+1]);if(!S||S===m)continue;const Q=[...tw(S,{x:i.x,y:i.y},c),...tw(S,{x:r.x,y:r.y},c)];n.size>0&&Q.push(...gQt(S,c,n,this.aabb,f));for(const w of[...new Set(Q)])y(B,S,w)}I.sort((B,S)=>B.length-S.length||B.pinBandPenalty-S.pinBandPenalty);for(const B of I)this.queue.push({path:B.path,collisionRects:B.collisionRects,directions:o})}visualize(){const t=zh(this.inputProblem,{chipAlpha:.1,connectionAlpha:.1});t.lines.push({points:this.baseElbow,strokeColor:"red",strokeDash:"4 4"});const[e,n]=this.pins;t.lines.push({points:[{x:e.x,y:e.y},{x:n.x,y:n.y}],strokeColor:"blue",strokeDash:"5 5"});for(const{path:o}of this.queue)t.lines.push({points:o,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}},fQt=({connectionPair:t,allConnectionPairs:e,inputProblem:n})=>{const[o,i]=t.pins;return n.netConnections.some(s=>s.pinIds.includes(o.pinId)&&s.pinIds.includes(i.pinId))?!0:e.some(s=>{if(s===t)return!1;const[a,A]=s.pins;return o.chipId===a.chipId&&i.chipId===A.chipId?!0:o.chipId===A.chipId&&i.chipId===a.chipId})},iCo=class extends Ng{inputProblem;mspConnectionPairs;dcConnMap;globalConnMap;queuedConnectionPairs;chipMap;currentConnectionPair=null;retryingWithoutNetLabelClearance=!1;solvedTracePaths=[];failedConnectionPairs=[];constructor(t){super(),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,pins:this.activeSubSolver.pins,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.retryingWithoutNetLabelClearance=!1),this.activeSubSolver?.failed){if(this.currentConnectionPair&&!this.retryingWithoutNetLabelClearance&&this.activeSubSolver.hasAmbiguousPinDirections){const o=this.currentConnectionPair;this.retryingWithoutNetLabelClearance=!0,this.activeSubSolver=new VH({inputProblem:this.inputProblem,pins:o.pins.map(i=>({...i})),connectionPair:o,chipMap:this.chipMap,preferExteriorDetours:fQt({connectionPair:o,allConnectionPairs:this.mspConnectionPairs,inputProblem:this.inputProblem}),reserveNetLabelClearance:!1});return}this.currentConnectionPair&&this.failedConnectionPairs.push({...this.currentConnectionPair,error:this.activeSubSolver.error||void 0}),this.activeSubSolver=null,this.currentConnectionPair=null,this.retryingWithoutNetLabelClearance=!1}if(this.activeSubSolver){this.activeSubSolver.step();return}const t=this.queuedConnectionPairs.shift();if(!t){this.solved=!0;return}this.currentConnectionPair=t,this.retryingWithoutNetLabelClearance=!1;const n=t.pins.some(o=>{if(o._facingDirection)return!1;const i=this.chipMap[o.chipId];return i&&vve(o,i).length>1})?t.pins.map(o=>({...o})):t.pins;this.activeSubSolver=new VH({inputProblem:this.inputProblem,pins:n,connectionPair:t,chipMap:this.chipMap,preferExteriorDetours:fQt({connectionPair:t,allConnectionPairs:this.mspConnectionPairs,inputProblem:this.inputProblem})})}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();const t=zh(this.inputProblem,{chipAlpha:.1,connectionAlpha:.1});for(const{mspPairId:e,tracePath:n}of this.solvedTracePaths)t.lines.push({points:n,strokeColor:"green"});for(const e of this.failedConnectionPairs)t.lines.push({points:[{x:e.pins[0].x,y:e.pins[0].y},{x:e.pins[1].x,y:e.pins[1].y}],strokeColor:"red",strokeDash:"4 2"});return t}},rCo=({pts:t,segmentIndex:e,offset:n,JOG_SIZE:o,EPS:i=1e-6})=>{if(e!==0&&e!==t.length-2)return;const r=t[e],s=t[e+1],a=Math.abs(r.x-s.x)<i,A=Math.abs(r.y-s.y)<i;if(!a&&!A)return;const c=a?s.y>r.y?1:-1:s.x>r.x?1:-1;if(t.length===2){if(a){const l=r.y+c*o,u=s.y-c*o;t.splice(1,0,{x:r.x,y:l},{x:r.x+n,y:l},{x:s.x+n,y:u},{x:s.x,y:u})}else{const l=r.x+c*o,u=s.x-c*o;t.splice(1,0,{x:l,y:r.y},{x:l,y:r.y+n},{x:u,y:s.y+n},{x:u,y:s.y})}return}if(e===0)if(a){const l=r.y+c*o;t.splice(1,1,{x:r.x,y:l},{x:r.x+n,y:l},{x:s.x+n,y:s.y})}else{const l=r.x+c*o;t.splice(1,1,{x:l,y:r.y},{x:l,y:r.y+n},{x:s.x,y:s.y+n})}else if(a){const l=s.y-c*o;t.splice(e,1,{x:r.x+n,y:r.y},{x:s.x+n,y:l},{x:s.x,y:l})}else{const l=s.x-c*o;t.splice(e,1,{x:r.x,y:r.y+n},{x:l,y:s.y+n},{x:l,y:s.y})}},H7=1e-6,sCo=class extends Ng{overlappingTraceSegments;interactionKind;traceNetIslands;traceIdsToShift;obstacleRects;SHIFT_DISTANCE=.1;correctedTraceMap={};constructor(t){super(),this.overlappingTraceSegments=t.overlappingTraceSegments,this.interactionKind=t.interactionKind,this.traceNetIslands=t.traceNetIslands,this.traceIdsToShift=t.traceIdsToShift,this.obstacleRects=Hy(t.inputProblem);for(const{connNetId:e,pathsWithOverlap:n}of this.overlappingTraceSegments)for(const{solvedTracePathIndex:o,traceSegmentIndex:i}of n){const r=this.traceNetIslands[e][o].mspPairId;this.correctedTraceMap[r]=this.traceNetIslands[e][o]}}_step(){const t=A=>A.pathsWithOverlap.some(({solvedTracePathIndex:c})=>this.traceNetIslands[A.connNetId][c].tracePath.length===2),e=this.overlappingTraceSegments.map(A=>this.traceIdsToShift?A.pathsWithOverlap.every(({solvedTracePathIndex:c})=>{const l=this.traceNetIslands[A.connNetId][c];return!this.traceIdsToShift.has(l.mspPairId)}):t(A)),n=e.some(A=>!A),o=A=>this.overlappingTraceSegments.map((c,l)=>{if(n&&e[l])return 0;const u=Math.floor(l/2)+1,g=l%2===0?A:-A;return this.getObstacleAwareOffset({group:c,offset:g*u*this.SHIFT_DISTANCE})}),i=o(-1);if(this.interactionKind==="overlap"&&this.overlappingTraceSegments.some(A=>A.pathsWithOverlap.length>1)){this.correctedTraceMap=this.applyOffsets(i),this.solved=!0;return}const s=this.interactionKind==="overlap"?[i,o(1)]:[];if(this.interactionKind==="point_contact"){const A=this.overlappingTraceSegments.map((c,l)=>l).filter(c=>!n||!e[c]).reverse();for(const c of A){const l=this.overlappingTraceSegments[c];for(const u of[-1,1]){const g=this.overlappingTraceSegments.map(()=>0);g[c]=this.getObstacleAwareOffset({group:l,offset:u*this.SHIFT_DISTANCE}),s.push(g)}}}const a=s.map(A=>{const c=this.applyOffsets(A);return{correctedTraceMap:c,intersectionCount:this.countDifferentNetIntersections(c),totalDisplacement:A.reduce((l,u)=>l+Math.abs(u),0)}});a.sort((A,c)=>A.intersectionCount-c.intersectionCount||A.totalDisplacement-c.totalDisplacement),this.correctedTraceMap=a[0].correctedTraceMap,this.solved=!0}applyOffsets(t){const e={...this.correctedTraceMap},n=(i,r)=>Math.abs(i-r)<H7,o=(i,r)=>!!i&&!!r&&n(i.x,r.x)&&n(i.y,r.y);return this.overlappingTraceSegments.forEach((i,r)=>{const s=t[r];if(s===0)return;const a=new Map;for(const A of i.pathsWithOverlap)a.has(A.solvedTracePathIndex)||a.set(A.solvedTracePathIndex,new Set),a.get(A.solvedTracePathIndex).add(A.traceSegmentIndex);for(const[A,c]of a){const l=this.traceNetIslands[i.connNetId][A],u=e[l.mspPairId]??l,g=u.tracePath.map(I=>({...I})),h=Array.from(c).sort((I,C)=>I-C).reverse(),d=new Map;for(const I of h){const C=g[I],y=g[I+1];!C||!y||(Math.abs(C.x-y.x)<H7?d.set(I,"vertical"):Math.abs(C.y-y.y)<H7&&d.set(I,"horizontal"))}const p=new Set,m=new Set,_=this.SHIFT_DISTANCE;for(const I of h)if(!(I<0||I>=g.length-1))if(I===0||I===g.length-2)rCo({pts:g,segmentIndex:I,offset:s,JOG_SIZE:_,EPS:H7});else{const C=g[I],y=g[I+1],x=d.get(I);x==="vertical"?(p.has(I)||(C.x+=s,p.add(I)),p.has(I+1)||(y.x+=s,p.add(I+1))):x==="horizontal"&&(m.has(I)||(C.y+=s,m.add(I)),m.has(I+1)||(y.y+=s,m.add(I+1)))}const f=[];for(const I of g)(f.length===0||!o(f[f.length-1],I))&&f.push(I);e[l.mspPairId]={...u,tracePath:f}}}),e}countDifferentNetIntersections(t){const e=Object.values(this.traceNetIslands).flatMap(o=>o.map(i=>t[i.mspPairId]??i));let n=0;for(let o=0;o<e.length;o++){const i=e[o];for(let r=o+1;r<e.length;r++){const s=e[r];if(i.globalConnNetId!==s.globalConnNetId)for(let a=0;a<i.tracePath.length-1;a++)for(let A=0;A<s.tracePath.length-1;A++)X1(i.tracePath[a],i.tracePath[a+1],s.tracePath[A],s.tracePath[A+1])&&n++}}return n}getObstacleAwareOffset({group:t,offset:e}){const n=this.getBlockingCollisions({group:t,offset:e});if(n.length===0)return e;const o=a=>n.some(({start:A,isVertical:c,obstacle:l})=>{let u,g,h;c?(u=A.x,g=l.minX,h=l.maxX):(u=A.y,g=l.minY,h=l.maxY);const d=u+a;return u<=g+H7&&d>=h-H7||u>=h-H7&&d<=g+H7}),i=n.map(({start:a,isVertical:A,obstacle:c})=>A?{coord:a.x,lowEdge:c.minX,highEdge:c.maxX}:{coord:a.y,lowEdge:c.minY,highEdge:c.maxY}),r=a=>i.flatMap(({coord:c,lowEdge:l,highEdge:u})=>[l-c-a,u-c+a]).filter(c=>!o(c)).filter(c=>this.getBlockingCollisions({group:t,offset:c}).length===0).sort((c,l)=>Math.abs(c-e)-Math.abs(l-e))[0],s=this.SHIFT_DISTANCE/10;return r(this.SHIFT_DISTANCE)??r(s)??e}getBlockingCollisions({group:t,offset:e}){const n=[];for(const{solvedTracePathIndex:o,traceSegmentIndex:i}of t.pathsWithOverlap){const r=this.traceNetIslands[t.connNetId][o],s=r.tracePath[i],a=r.tracePath[i+1];if(!s||!a)continue;const A=Math.abs(s.x-a.x)<H7,c=Math.abs(s.y-a.y)<H7;if(!A&&!c)continue;const l=A?[{...s,x:s.x+e},{...a,x:a.x+e}]:[{...s,y:s.y+e},{...a,y:a.y+e}],u=HN(l,this.obstacleRects);u&&n.push({start:s,isVertical:A,obstacle:u.rect})}return n}visualize(){const t={lines:[],points:[],rects:[],circles:[]};for(const e of this.overlappingTraceSegments)for(const{solvedTracePathIndex:n,traceSegmentIndex:o}of e.pathsWithOverlap){const i=this.traceNetIslands[e.connNetId][n],r=i.tracePath[o],s=i.tracePath[o+1];t.lines.push({points:[r,s],strokeColor:"red"})}for(const e of Object.values(this.correctedTraceMap))t.lines.push({points:e.tracePath,strokeColor:"blue",strokeDash:"4 2"});return t}},IQt=1e-6,CQt=class extends Ng{inputProblem;inputTracePaths;globalConnMap;traceIdsToShift;traceNetIslands={};correctedTraceMap={};recentTraceStates=[];cleanupPhase=null;constructor(t){super(),this.inputProblem=t.inputProblem,this.inputTracePaths=t.inputTracePaths,this.globalConnMap=t.globalConnMap,this.traceIdsToShift=t.traceIdsToShift;for(const e of this.inputTracePaths){const{mspPairId:n}=e;this.correctedTraceMap[n]=e}this.rememberTraceState(this.correctedTraceMap),this.traceNetIslands=this.computeTraceNetIslands()}getConstructorParams(){return{inputProblem:this.inputProblem,inputTracePaths:this.inputTracePaths,globalConnMap:this.globalConnMap,traceIdsToShift:this.traceIdsToShift}}computeTraceNetIslands(){const t={};for(const e of this.inputTracePaths){const n=this.correctedTraceMap[e.mspPairId]??e,o=n.globalConnNetId;t[o]||(t[o]=[]),t[o].push(n)}return t}findNextOverlapIssue(){const e=Object.keys(this.traceNetIslands);for(let n=0;n<e.length;n++)for(let o=n+1;o<e.length;o++){const i=e[n],r=e[o],s=this.traceNetIslands[i]||[],a=this.traceNetIslands[r]||[],A=[],c=[],l=[],u=new Set,g=new Set,h=(m,_,f,I)=>{const C=Math.min(m,_),y=Math.max(m,_),x=Math.min(f,I),E=Math.max(f,I);return Math.min(y,E)-Math.max(C,x)},d=({pathAIndex:m,segmentAIndex:_,pathBIndex:f,segmentBIndex:I,rangeOverlap:C})=>{if(C>.002){const M=`${m}:${_}`,k=`${f}:${I}`;u.has(M)||(A.push({solvedTracePathIndex:m,traceSegmentIndex:_}),u.add(M)),g.has(k)||(c.push({solvedTracePathIndex:f,traceSegmentIndex:I}),g.add(k));return}if(C<-.002)return;const y=s[m].tracePath,x=a[f].tracePath,E=y[_],B=y[_+1],S=x[I],Q=x[I+1];_===0||_===y.length-2||I===0||I===x.length-2||l.push({pathAIndex:m,segmentAIndex:_,pathBIndex:f,segmentBIndex:I,combinedLength:Math.abs(E.x-B.x)+Math.abs(E.y-B.y)+Math.abs(S.x-Q.x)+Math.abs(S.y-Q.y)})};for(let m=0;m<s.length;m++){const _=s[m],f=_.tracePath;for(let I=0;I<f.length-1;I++){const C=f[I],y=f[I+1],x=Math.abs(C.x-y.x)<.002,E=Math.abs(C.y-y.y)<.002;if(!(!x&&!E))for(let B=0;B<a.length;B++){const S=a[B];if(this.traceIdsToShift&&!this.traceIdsToShift.has(_.mspPairId)&&!this.traceIdsToShift.has(S.mspPairId))continue;const Q=S.tracePath;for(let w=0;w<Q.length-1;w++){const M=Q[w],k=Q[w+1],R=Math.abs(M.x-k.x)<.002,F=Math.abs(M.y-k.y)<.002;!R&&!F||(x&&R?Math.abs(C.x-M.x)<.002&&d({pathAIndex:m,segmentAIndex:I,pathBIndex:B,segmentBIndex:w,rangeOverlap:h(C.y,y.y,M.y,k.y)}):E&&F&&Math.abs(C.y-M.y)<.002&&d({pathAIndex:m,segmentAIndex:I,pathBIndex:B,segmentBIndex:w,rangeOverlap:h(C.x,y.x,M.x,k.x)}))}}}}if(A.length>0&&c.length>0)return{interactionKind:"overlap",overlappingTraceSegments:[{connNetId:i,pathsWithOverlap:A},{connNetId:r,pathsWithOverlap:c}]};const p=l.sort((m,_)=>_.combinedLength-m.combinedLength)[0];if(p)return{interactionKind:"point_contact",overlappingTraceSegments:[{connNetId:i,pathsWithOverlap:[{solvedTracePathIndex:p.pathAIndex,traceSegmentIndex:p.segmentAIndex}]},{connNetId:r,pathsWithOverlap:[{solvedTracePathIndex:p.pathBIndex,traceSegmentIndex:p.segmentBIndex}]}]}}return null}findNextDiagonalSegment(){for(const e in this.correctedTraceMap){const n=this.correctedTraceMap[e].tracePath;for(let o=0;o<n.length-1;o++){const i=n[o],r=n[o+1],s=Math.abs(i.y-r.y)<.002,a=Math.abs(i.x-r.x)<.002;if(!s&&!a)return{mspPairId:e,tracePath:n,i:o,p1:i,p2:r}}}return null}findAndFixNextDiagonalSegment(){const t=this.findNextDiagonalSegment();if(!t)return!1;const{mspPairId:e,tracePath:n,i:o,p1:i,p2:r}=t,s=.002,a=o>0?n[o-1]:null,A=o+2<n.length?n[o+2]:null,c=a?Math.abs(a.x-i.x)<s:!1,l=a?Math.abs(a.y-i.y)<s:!1,u=A?Math.abs(r.x-A.x)<s:!1,g=A?Math.abs(r.y-A.y)<s:!1,h={x:i.x,y:r.y},d={x:r.x,y:i.y};let p=0;c&&p++,g&&p++;let m=0;l&&m++,u&&m++;const _=p<m?h:d;return n.splice(o+1,0,_),!0}_step(){if(this.activeSubSolver?.solved){const o={...this.correctedTraceMap,...this.activeSubSolver.correctedTraceMap};if(this.returnsToPreviousTraceState(o)){this.activeSubSolver=null,this.solved=!0;return}this.correctedTraceMap=o,this.rememberTraceState(o),this.activeSubSolver=null,this.traceNetIslands=this.computeTraceNetIslands()}if(this.activeSubSolver){this.activeSubSolver.step();return}const t=this.findNextOverlapIssue();if(t===null){if(this.cleanupPhase===null&&(this.cleanupPhase="diagonals"),this.cleanupPhase==="diagonals"){this.findAndFixNextDiagonalSegment()||(this.cleanupPhase="done",this.solved=!0);return}this.solved=!0;return}const{interactionKind:e,overlappingTraceSegments:n}=t;this.activeSubSolver=new sCo({inputProblem:this.inputProblem,interactionKind:e,overlappingTraceSegments:n,traceNetIslands:this.traceNetIslands,traceIdsToShift:this.traceIdsToShift})}rememberTraceState(t){this.recentTraceStates.push({...t}),this.recentTraceStates.length>2&&this.recentTraceStates.shift()}returnsToPreviousTraceState(t){if(this.recentTraceStates.length<2)return!1;const e=this.recentTraceStates[0],n=Object.keys(t);if(n.length!==Object.keys(e).length)return!1;for(const o of n){const i=t[o],r=e[o];if(!i||!r||i.tracePath.length!==r.tracePath.length)return!1;for(let s=0;s<i.tracePath.length;s++){const a=i.tracePath[s],A=r.tracePath[s];if(Math.abs(a.x-A.x)>IQt||Math.abs(a.y-A.y)>IQt)return!1}}return!0}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();const t=zh(this.inputProblem);t.circles=t.circles||[];for(const e of Object.values(this.correctedTraceMap))t.lines.push({points:e.tracePath,strokeColor:"purple"});if(this.cleanupPhase==="diagonals"){const e=this.findNextDiagonalSegment();e&&t.lines.push({points:[e.p1,e.p2],strokeColor:"red",strokeWidth:.05})}return t}},yle=class{chips;spatialIndex;spatialIndexIdToChip;constructor(t){this.chips=t.map(e=>({...e,bounds:Rve(e),spatialIndexId:null})),this.spatialIndexIdToChip=new Map,this.spatialIndex=new UH(t.length);for(const e of this.chips)e.spatialIndexId=this.spatialIndex.add(e.bounds.minX,e.bounds.minY,e.bounds.maxX,e.bounds.maxY),this.spatialIndexIdToChip.set(e.spatialIndexId,e);this.spatialIndex.finish()}getChipsInBounds(t){return this.spatialIndex.search(t.minX,t.minY,t.maxX,t.maxY).map(n=>this.spatialIndexIdToChip.get(n))}doesOrthogonalLineIntersectChip(t,e={}){const n=e.excludeChipIds??[],[o,i]=t,{x:r,y:s}=o,{x:a,y:A}=i;return this.getChipsInBounds({minX:Math.min(r,a),minY:Math.min(s,A),maxX:Math.max(r,a),maxY:Math.max(s,A)}).filter(l=>!n.includes(l.chipId)).length>0}};function O7(t,e,n,o=1e-9){const i=Math.abs(t.x-e.x)<o,r=Math.abs(t.y-e.y)<o;if(!i&&!r)return!1;if(i){const s=t.x;if(s<n.minX-o||s>n.maxX+o)return!1;const a=Math.min(t.y,e.y),A=Math.max(t.y,e.y);return Math.min(A,n.maxY)-Math.max(a,n.minY)>o}else{const s=t.y;if(s<n.minY-o||s>n.maxY+o)return!1;const a=Math.min(t.x,e.x),A=Math.max(t.x,e.x);return Math.min(A,n.maxX)-Math.max(a,n.minX)>o}}function Tve(t,e,n,o){for(const[i,r]of Object.entries(e)){const s=r.tracePath;for(let a=0;a<s.length-1;a++)if(!(i===n&&a===o)&&O7(s[a],s[a+1],t))return{hasIntersection:!0,mspPairId:i,segIndex:a}}return{hasIntersection:!1}}function yQt(t){let e=0;const n=t.tracePath;for(let o=0;o<n.length-1;o++)e+=Math.abs(n[o+1].x-n[o].x)+Math.abs(n[o+1].y-n[o].y);return e}function xQt(t){const{inputProblem:e,inputTraceMap:n,globalConnNetId:o,fallbackTrace:i,mspConnectionPairIds:r}=t,s=Object.fromEntries(e.chips.map(g=>[g.chipId,g]));let a=Object.values(n).filter(g=>g.globalConnNetId===o);if(r&&r.length>0){const g=new Set(r);a=a.filter(h=>h.mspConnectionPairIds.some(d=>g.has(d)))}const A=new Set;for(const g of a)A.add(g.pins[0].chipId),A.add(g.pins[1].chipId);let c=null,l=-1;for(const g of A){const d=s[g]?.pins?.length??0;d>l&&(l=d,c=g)}const u=c==null?[]:a.filter(g=>g.pins[0].chipId===c||g.pins[1].chipId===c);return u.length>0?u.reduce((g,h)=>yQt(g)>=yQt(h)?g:h):i}function aCo(t,e){return[{x:t.x,y:t.y},{x:(t.x+e.x)/2,y:(t.y+e.y)/2},{x:e.x,y:e.y}]}function ACo(t){const{inputProblem:e,inputTraceMap:n,chipObstacleSpatialIndex:o,overlappingSameNetTraceGroup:i,availableOrientations:r,netLabelWidth:s,netLabelHeight:a}=t,A=i.portOnlyPinId;if(!A)return{placement:null,testedCandidates:[],error:"No portOnlyPinId provided"};let c=null,l=null;for(const E of e.chips){const B=E.pins.find(S=>S.pinId===A);if(B){c={x:B.x,y:B.y},l=B._facingDirection||W5(B,E);break}}if(!c||!l)return{placement:null,testedCandidates:[],error:`Port-only pin not found: ${A}`};const u=r.length>0?r:["x+","x-","y+","y-"],g={x:c.x,y:c.y},h=E=>E==="x+"?{x:1,y:0}:E==="x-"?{x:-1,y:0}:E==="y+"?{x:0,y:1}:{x:0,y:-1},d=[];for(const E of u){const{width:B,height:S}=_B({orientation:E,netLabelWidth:s,netLabelHeight:a}),Q=IC(g,E,B,S),w=h(E),M=.001,k={x:Q.x+w.x*M,y:Q.y+w.y*M},R=Ls(k,B,S);if(o.getChipsInBounds(R).length>0){d.push({center:k,width:B,height:S,bounds:R,anchor:g,orientation:E,status:"chip-collision",hostSegIndex:-1});continue}if(KH(R,e)){d.push({center:k,width:B,height:S,bounds:R,anchor:g,orientation:E,status:"text-collision",hostSegIndex:-1});continue}if(Tve(R,n,"",-1).hasIntersection){d.push({center:k,width:B,height:S,bounds:R,anchor:g,orientation:E,status:"trace-collision",hostSegIndex:-1});continue}return d.push({center:k,width:B,height:S,bounds:R,anchor:g,orientation:E,status:"ok",hostSegIndex:-1}),{placement:{globalConnNetId:i.globalConnNetId,dcConnNetId:void 0,netId:i.netId,netLabelText:i.netLabelText,mspConnectionPairIds:[],pinIds:[A],orientation:E,anchorPoint:g,width:B,height:S,center:k},testedCandidates:d}}const p=l,{width:m,height:_}=_B({orientation:p,netLabelWidth:s}),f=IC(g,p,m,_),I=h(p),C=.001,y={x:f.x+I.x*C,y:f.y+I.y*C};return{placement:{globalConnNetId:i.globalConnNetId,dcConnNetId:void 0,netId:i.netId,netLabelText:i.netLabelText,mspConnectionPairIds:[],pinIds:[A],orientation:p,anchorPoint:g,width:m,height:_,center:y},testedCandidates:d}}function cCo(t){const e=zh(t.inputProblem),n=t.overlappingSameNetTraceGroup.globalConnNetId,o=xQt({inputProblem:t.inputProblem,inputTraceMap:t.inputTraceMap,globalConnNetId:n,fallbackTrace:t.overlappingSameNetTraceGroup.overlappingTraces});Mc(n,.9),Mc(n,.5);for(const i of Object.values(t.inputTraceMap))o&&(i.mspPairId,o.mspPairId),e.lines.push({points:i.tracePath});for(const i of t.testedCandidates){const r=i.status==="ok"?"rgba(0, 180, 0, 0.25)":i.status==="chip-collision"?"rgba(220, 0, 0, 0.25)":i.status==="trace-collision"?"rgba(220, 140, 0, 0.25)":i.status==="text-collision"?"rgba(160, 0, 220, 0.2)":"rgba(120, 120, 120, 0.15)",s=i.status==="ok"?"green":i.status==="chip-collision"?"red":i.status==="trace-collision"?"orange":i.status==="text-collision"?"purple":"gray",a=i.status==="ok"?"status: ok(valid net label candidate)":i.status==="chip-collision"?"status: chip-collision":i.status==="trace-collision"?"status: trace-collision":i.status==="text-collision"?"status: text-collision":"status: parallel-to-segment";e.rects.push({center:{x:(i.bounds.minX+i.bounds.maxX)/2,y:(i.bounds.minY+i.bounds.maxY)/2},width:i.width,height:i.height,fill:r,strokeColor:s,label:`${a}
orientation: ${i.orientation}`}),e.points.push({x:i.anchor.x,y:i.anchor.y,color:s,label:`anchor
orientation: ${i.orientation}`})}if(t.netLabelPlacement){const i=t.netLabelPlacement;e.rects.push({center:i.center,width:i.width,height:i.height,fill:"rgba(0, 128, 255, 0.35)",strokeColor:"blue",label:`netId: ${i.netId}
globalConnNetId: ${i.globalConnNetId}`}),e.points.push({x:i.anchorPoint.x,y:i.anchorPoint.y,color:"blue",label:`anchor
orientation: ${i.orientation}`})}return e}var EQt=class extends Ng{inputProblem;inputTraceMap;overlappingSameNetTraceGroup;availableOrientations;chipObstacleSpatialIndex;netLabelWidth;netLabelHeight;netLabelPlacement=null;testedCandidates=[];constructor(t){super(),this.inputProblem=t.inputProblem,this.inputTraceMap=t.inputTraceMap,this.overlappingSameNetTraceGroup=t.overlappingSameNetTraceGroup,this.availableOrientations=t.availableOrientations,this.netLabelWidth=t.netLabelWidth,this.netLabelHeight=t.netLabelHeight,this.chipObstacleSpatialIndex=t.inputProblem._chipObstacleSpatialIndex??new yle(t.inputProblem.chips)}getConstructorParams(){return{inputProblem:this.inputProblem,inputTraceMap:this.inputTraceMap,overlappingSameNetTraceGroup:this.overlappingSameNetTraceGroup,availableOrientations:this.availableOrientations,netLabelWidth:this.netLabelWidth,netLabelHeight:this.netLabelHeight}}_step(){if(this.netLabelPlacement){this.solved=!0;return}if(this.overlappingSameNetTraceGroup.portOnlyPinId){const u=ACo({inputProblem:this.inputProblem,inputTraceMap:this.inputTraceMap,chipObstacleSpatialIndex:this.chipObstacleSpatialIndex,overlappingSameNetTraceGroup:this.overlappingSameNetTraceGroup,availableOrientations:this.availableOrientations,netLabelWidth:this.netLabelWidth,netLabelHeight:this.netLabelHeight});if(this.testedCandidates.push(...u.testedCandidates),u.placement){this.netLabelPlacement=u.placement,this.solved=!0;return}this.failed=!0,this.error=u.error??"Could not place net label at port without collisions";return}const t=this.overlappingSameNetTraceGroup.globalConnNetId;let e=xQt({inputProblem:this.inputProblem,inputTraceMap:this.inputTraceMap,globalConnNetId:t,fallbackTrace:this.overlappingSameNetTraceGroup.overlappingTraces,mspConnectionPairIds:this.overlappingSameNetTraceGroup.mspConnectionPairIds});if(!e){this.failed=!0,this.error="No host trace found for net label placement";return}const n=new Set(this.overlappingSameNetTraceGroup.mspConnectionPairIds??[]),o=Object.values(this.inputTraceMap).filter(u=>u.globalConnNetId===t&&(n.size===0||u.mspConnectionPairIds.some(g=>n.has(g)))),i=this.availableOrientations.length===1?[e,...o.filter(u=>u.mspPairId!==e.mspPairId)]:[e],r=this.availableOrientations.length>0?this.availableOrientations:["x+","x-","y+","y-"],s=this.availableOrientations.length===1,a=(u,g)=>{switch(u){case"y+":return g.y;case"y-":return-g.y;case"x+":return g.x;case"x-":return-g.x}};let A=null,c=-1/0;const l=1e-6;for(const u of i){const g=u.tracePath.slice();for(let h=0;h<g.length-1;h++){const d=g[h],p=g[h+1],m=Math.abs(d.y-p.y)<l,_=Math.abs(d.x-p.x)<l;if(!m&&!_)continue;const f=m?["y+","y-"]:["x+","x-"],I=r.filter(y=>f.includes(y));if(I.length===0)continue;const C=aCo(d,p);for(const y of C)for(const x of I){const{width:E,height:B}=_B({orientation:x,netLabelWidth:this.netLabelWidth,netLabelHeight:this.netLabelHeight}),S=IC(y,x,E,B),Q=x==="x+"?{x:1,y:0}:x==="x-"?{x:-1,y:0}:x==="y+"?{x:0,y:1}:{x:0,y:-1},w=1e-4,M={x:S.x+Q.x*w,y:S.y+Q.y*w},k=Ls(M,E,B);if(this.chipObstacleSpatialIndex.getChipsInBounds(k).length>0){this.testedCandidates.push({center:M,width:E,height:B,bounds:k,anchor:y,orientation:x,status:"chip-collision",hostSegIndex:h});continue}if(KH(k,this.inputProblem)){this.testedCandidates.push({center:M,width:E,height:B,bounds:k,anchor:y,orientation:x,status:"text-collision",hostSegIndex:h});continue}if(Tve(k,this.inputTraceMap,u.mspPairId,h).hasIntersection){this.testedCandidates.push({center:M,width:E,height:B,bounds:k,anchor:y,orientation:x,status:"trace-collision",hostSegIndex:h});continue}if(this.testedCandidates.push({center:M,width:E,height:B,bounds:k,anchor:y,orientation:x,status:"ok",hostSegIndex:h}),s){const O=a(x,y);O>c+1e-9&&(c=O,A={anchor:y,orientation:x,width:E,height:B,center:S,hostSegIndex:h,dcConnNetId:u.dcConnNetId,mspPairId:u.mspPairId,pinIds:[u.pins[0].pinId,u.pins[1].pinId]});continue}this.netLabelPlacement={globalConnNetId:this.overlappingSameNetTraceGroup.globalConnNetId,dcConnNetId:u.dcConnNetId,netId:this.overlappingSameNetTraceGroup.netId,netLabelText:this.overlappingSameNetTraceGroup.netLabelText,mspConnectionPairIds:[u.mspPairId],pinIds:[u.pins[0].pinId,u.pins[1].pinId],orientation:x,anchorPoint:y,width:E,height:B,center:S},this.solved=!0;return}}}if(s&&A){this.netLabelPlacement={globalConnNetId:this.overlappingSameNetTraceGroup.globalConnNetId,dcConnNetId:A.dcConnNetId,netId:this.overlappingSameNetTraceGroup.netId,netLabelText:this.overlappingSameNetTraceGroup.netLabelText,mspConnectionPairIds:[A.mspPairId],pinIds:A.pinIds,orientation:A.orientation,anchorPoint:A.anchor,width:A.width,height:A.height,center:A.center},this.solved=!0;return}this.failed=!0,this.error="Could not place net label without collisions"}visualize(){return cCo(this)}},xle=({pinIds:t,traces:e})=>{const n=new Map;for(const s of t)n.set(s,new Set);const o=e.filter(s=>{if(s.pins.length!==2)return!1;const[a,A]=s.pins;return n.has(a.pinId)&&n.has(A.pinId)});for(const s of o){const[a,A]=s.pins;n.get(a.pinId).add(A.pinId),n.get(A.pinId).add(a.pinId)}const i=[],r=new Set;for(const s of t){if(r.has(s))continue;const a=[],A=[s];for(r.add(s);A.length>0;){const l=A.pop();a.push(l);for(const u of n.get(l)??[])r.has(u)||(r.add(u),A.push(u))}const c=new Set(a);i.push({pinIds:a,traces:o.filter(l=>l.pins.every(u=>c.has(u.pinId)))})}return i},BQt=class extends Ng{inputProblem;inputTraceMap;overlappingSameNetTraceGroups;queuedOverlappingSameNetTraceGroups;netLabelPlacements=[];failedGroups=[];currentGroup=null;triedAnyOrientationFallbackForCurrentGroup=!1;constructor(t){super(),this.inputProblem=t.inputProblem,this.inputTraceMap=t.inputTraceMap,this.overlappingSameNetTraceGroups=this.computeOverlappingSameNetTraceGroups(),this.queuedOverlappingSameNetTraceGroups=[...this.overlappingSameNetTraceGroups]}computeOverlappingSameNetTraceGroups(){const t={};for(const A of Object.values(this.inputTraceMap)){const c=A.globalConnNetId;t[c]||(t[c]=[]),t[c].push(A)}const{netConnMap:e}=mB(this.inputProblem),n=new Map;for(const A of this.inputProblem.chips)for(const c of A.pins)n.set(c.pinId,c);const o={},i={};for(const A of this.inputProblem.directConnections){if(A.netId){const[l,u]=A.pinIds;o[l]=A.netId,o[u]=A.netId}const c=A.netLabelText?.trim();if(c){const[l,u]=A.pinIds;i[l]=c,i[u]=c}}for(const A of this.inputProblem.netConnections)for(const c of A.pinIds){o[c]=A.netId;const l=A.netLabelText?.trim();l&&(i[c]=l)}const r=[],s=this.inputProblem.chips.flatMap(A=>A.pins.map(c=>c.pinId)),a=new Set;for(const A of s){const c=e.getNetConnectedToId(A);c&&a.add(c)}for(const A of a){const l=e.getIdsConnectedToNet(A).filter(u=>n.has(u));for(const u of xle({pinIds:l,traces:t[A]??[]})){const g=new Set(u.pinIds),h=u.traces;if(h.length>0){if(h.some(C=>C.suppressNetLabel))continue;const d=C=>{let y=0;const x=C.tracePath;for(let E=0;E<x.length-1;E++)y+=Math.abs(x[E+1].x-x[E].x)+Math.abs(x[E+1].y-x[E].y);return y};let p=h[0],m=d(p);for(let C=1;C<h.length;C++){const y=d(h[C]);y>m&&(p=h[C],m=y)}let _=h.find(C=>C.userNetId!=null)?.userNetId;if(!_){for(const C of g)if(o[C]){_=o[C];break}}const f=Array.from(new Set(h.flatMap(C=>C.mspConnectionPairIds??[C.mspPairId]))),I={globalConnNetId:A,netId:_,netLabelText:[...g].map(C=>i[C]).find(C=>!!C),overlappingTraces:p,mspConnectionPairIds:f};r.push(I)}else for(const d of g){const p=o[d];p&&r.push({globalConnNetId:A,netId:p,netLabelText:i[d],portOnlyPinId:d})}}}return r}getNetLabelWidthForGroup(t){const e=t.overlappingTraces?.pins.map(n=>n.pinId)??[];return t.portOnlyPinId&&e.push(t.portOnlyPinId),L7({inputProblem:this.inputProblem,netId:t.netId,pinIds:e,isPortOnlyLabel:t.portOnlyPinId!==void 0})}getNetLabelHeightForGroup(t){if(t.netId){const n=this.inputProblem.netConnections.find(o=>o.netId===t.netId)?.netLabelHeight;if(n!==void 0)return n}const e=t.overlappingTraces?.pins.map(n=>n.pinId)??[];return t.portOnlyPinId&&e.push(t.portOnlyPinId),this.inputProblem.netConnections.find(n=>n.pinIds.some(o=>e.includes(o)))?.netLabelHeight}_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){const i=["x+","x-","y+","y-"],r=this.activeSubSolver.availableOrientations,s=r.length===4&&i.every(a=>r.includes(a));if(!this.triedAnyOrientationFallbackForCurrentGroup&&!s&&this.currentGroup){this.triedAnyOrientationFallbackForCurrentGroup=!0;const a=this.getNetLabelWidthForGroup(this.currentGroup),A=this.getNetLabelHeightForGroup(this.currentGroup);this.activeSubSolver=new EQt({inputProblem:this.inputProblem,inputTraceMap:this.inputTraceMap,overlappingSameNetTraceGroup:this.currentGroup,availableOrientations:i,netLabelWidth:a,netLabelHeight:A});return}this.currentGroup&&this.failedGroups.push(this.currentGroup),this.activeSubSolver=null,this.currentGroup=null,this.triedAnyOrientationFallbackForCurrentGroup=!1;return}if(this.activeSubSolver){this.activeSubSolver.step();return}const t=this.queuedOverlappingSameNetTraceGroups.shift();if(!t){this.solved=!0;return}const e=t.netId??t.globalConnNetId;this.currentGroup=t,this.triedAnyOrientationFallbackForCurrentGroup=!1;const n=this.getNetLabelWidthForGroup(this.currentGroup),o=this.getNetLabelHeightForGroup(this.currentGroup);this.activeSubSolver=new EQt({inputProblem:this.inputProblem,inputTraceMap:this.inputTraceMap,overlappingSameNetTraceGroup:t,availableOrientations:this.inputProblem.availableNetLabelOrientations[e]??["x+","x-","y+","y-"],netLabelWidth:n,netLabelHeight:o})}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();const t=zh(this.inputProblem);for(const e of Object.values(this.inputTraceMap))t.lines.push({points:e.tracePath,strokeColor:"purple"});for(const e of this.netLabelPlacements)t.rects.push({center:e.center,width:e.width,height:e.height,fill:Mc(e.globalConnNetId,.35),strokeColor:Mc(e.globalConnNetId,.9),label:`netId: ${e.netId}
globalConnNetId: ${e.globalConnNetId}`}),t.points.push({x:e.anchorPoint.x,y:e.anchorPoint.y,color:Mc(e.globalConnNetId,.9),label:`anchorPoint
orientation: ${e.orientation}`});return t}},lCo="#ef4444",uCo="#000000",gCo="66",dCo=(t,e)=>{const n=e.availableNetLabelOrientations;if(n)for(const o of t.rects??[]){const i=hCo(o.label,n);if(!i)continue;const r=i.includes("y+"),s=i.includes("y-");if(r===s)continue;const a=r?lCo:uCo;o.fill=`${a}${gCo}`,o.stroke=a,o.color=a}},hCo=(t,e)=>{for(const n of pCo(t))if(Object.hasOwn(e,n))return e[n]},pCo=t=>t?[t.match(/^netId: (.+)$/m)?.[1],t.match(/^globalConnNetId: (.+)$/m)?.[1]].filter(e=>!!(e&&e!=="undefined")):[],mCo=({labels:t,chips:e})=>{const n={},o=new Map(e.flatMap(i=>i.pins.map(r=>[r.pinId,i.chipId])));for(const i of t){if(i.pinIds.length===0)continue;const r=i.pinIds[0],a=(r.includes(".")?r.split(".")[0]:void 0)??o.get(r);if(!a)continue;const A=`${a}-${i.orientation}`;n[A]||(n[A]=[]),n[A].push(i)}return n},_Co=(t,e)=>{if(t.length===0)throw new Error("Cannot merge an empty group of labels.");let n=1/0,o=1/0,i=-1/0,r=-1/0;const s=new Set,a=new Set,A=new Set;for(const p of t){const m=Ls(p.center,p.width,p.height);n=Math.min(n,m.minX),o=Math.min(o,m.minY),i=Math.max(i,m.maxX),r=Math.max(r,m.maxY),p.pinIds.forEach(_=>s.add(_)),p.mspConnectionPairIds.forEach(_=>a.add(_)),A.add(p.globalConnNetId)}const c=i-n,l=r-o,u={x:n+c/2,y:o+l/2},g=t[0],h=`merged-group-${e}`;return{mergedLabel:{...g,globalConnNetId:h,center:u,width:c,height:l,pinIds:Array.from(s),mspConnectionPairIds:Array.from(a)},originalNetIds:A}},fCo=({labels:t,traces:e,distanceThreshold:n=.5})=>{const o=new Map;if(!e)throw new Error("No traces provided to filterLabelsAtTraceEdges");for(const r of e)r.globalConnNetId&&(o.has(r.globalConnNetId)||o.set(r.globalConnNetId,[]),o.get(r.globalConnNetId).push(r));const i=[];for(const r of t){if(r.mspConnectionPairIds.length===0){i.push(r);continue}const s=o.get(r.globalConnNetId);let a=!1;if(!(!s||s.length===0)){for(const A of s){if(A.tracePath.length===0)continue;const c=A.tracePath[0],l=A.tracePath[A.tracePath.length-1],u=ad(r.center,c),g=ad(r.center,l);if(u<=n||g<=n){a=!0;break}}a&&i.push(r)}}return i},bQt=class extends Ng{input;output;inputProblem;traces;pipelineStep="filtering_labels";filteredLabels=[];labelGroups={};groupKeysToProcess=[];finalPlacements=[];mergedLabelNetIdMap={};activeMergingGroupKey=null;constructor(t){super(),this.input=t,this.inputProblem=t.inputProblem,this.traces=t.traces,this.output={netLabelPlacements:t.netLabelPlacements,mergedLabelNetIdMap:{}}}_step(){switch(this.pipelineStep){case"filtering_labels":this.filteredLabels=fCo({labels:this.input.netLabelPlacements,traces:this.traces}),this.pipelineStep="grouping_labels";break;case"grouping_labels":this.labelGroups=mCo({labels:this.filteredLabels,chips:this.inputProblem.chips}),this.groupKeysToProcess=Object.keys(this.labelGroups),this.pipelineStep="merging_groups";break;case"merging_groups":if(this.groupKeysToProcess.length===0){this.pipelineStep="finalizing",this.activeMergingGroupKey=null;break}const t=this.groupKeysToProcess.pop();this.activeMergingGroupKey=t;const e=this.labelGroups[t];if(e.length>1){const{mergedLabel:i,originalNetIds:r}=_Co(e,t);this.finalPlacements.push(i),this.mergedLabelNetIdMap[i.globalConnNetId]=r}else this.finalPlacements.push(...e);break;case"finalizing":const n=new Set(this.finalPlacements.flatMap(i=>this.mergedLabelNetIdMap[i.globalConnNetId]?[...this.mergedLabelNetIdMap[i.globalConnNetId]]:[i.globalConnNetId])),o=this.input.netLabelPlacements.filter(i=>!n.has(i.globalConnNetId));this.output={netLabelPlacements:[...this.finalPlacements,...o],mergedLabelNetIdMap:this.mergedLabelNetIdMap},this.solved=!0;break}}getOutput(){return this.output}visualize(){const t=zh(this.inputProblem,{chipAlpha:.1,connectionAlpha:.1});t.rects||(t.rects=[]),t.lines||(t.lines=[]),t.points||(t.points=[]),t.texts||(t.texts=[]);const e=new Map;for(const n of this.input.netLabelPlacements)e.set(n.globalConnNetId,n);for(const n of this.traces){const o={points:n.tracePath.map(i=>({x:i.x,y:i.y})),strokeColor:"blue"};t.lines.push(o)}if(this.activeMergingGroupKey&&this.labelGroups[this.activeMergingGroupKey]){const n=this.labelGroups[this.activeMergingGroupKey];for(const o of n)t.rects.push({center:o.center,width:o.width,height:o.height,fill:"rgba(255, 165, 0, 0.5)",stroke:"orange"})}for(const n of this.output.netLabelPlacements){const o=n.globalConnNetId.startsWith("merged-group-"),i=Mc(n.globalConnNetId);if(o){t.rects.push({center:n.center,width:n.width,height:n.height,fill:i.replace(/, 1\)/,", 0.2)"),stroke:i,label:n.globalConnNetId});const r=this.output.mergedLabelNetIdMap[n.globalConnNetId];if(r)for(const s of r){const a=e.get(s);if(a){const A=Ls(a.center,a.width,a.height),c={x:A.minX,y:A.minY},l={x:A.maxX,y:A.minY},u={x:A.maxX,y:A.maxY},g={x:A.minX,y:A.maxY};t.lines.push({points:[c,l,u,g,c],strokeColor:i,strokeDash:"4 4"}),t.lines.push({points:[a.center,n.center],strokeColor:i,strokeDash:"2 2"})}}}else t.rects.push({center:n.center,width:n.width,height:n.height,stroke:i,label:n.globalConnNetId})}return t}},Jh=({traces:t,netLabels:e=[]})=>{const n=[];for(const o of t)for(const i of e){const r=Ls(i.center,i.width,i.height);for(let s=0;s<o.tracePath.length-1;s++){const a=o.tracePath[s],A=o.tracePath[s+1];if(O7(a,A,r)){if(o.globalConnNetId===i.globalConnNetId)break;n.push({trace:o,label:i});break}}}return n},ICo=({path:t,labelBounds:e,paddedBounds:n=e})=>{let o=-1,i=-1;for(let A=0;A<t.length-1;A++)O7(t[A],t[A+1],e)&&(o===-1&&(o=A),i=A);if(o===-1)return{firstInsideIndex:-1,lastInsideIndex:-1};const r=A=>A.x>n.minX&&A.x<n.maxX&&A.y>n.minY&&A.y<n.maxY;let s=o;for(;s>0&&r(t[s]);)s--;let a=i+1;for(;a<t.length-1&&r(t[a]);)a++;return{firstInsideIndex:s+1,lastInsideIndex:a-1}},CCo=({initialTrace:t,firstInsideIndex:e,lastInsideIndex:n,labelBounds:o,paddingBuffer:i,detourCount:r})=>{if(e<=0||n>=t.tracePath.length-1)return[];const s=t.tracePath[e-1],a=t.tracePath[n+1],A=t.tracePath.slice(0,e),c=t.tracePath.slice(n+1),l=[];s.x!==a.x&&s.y!==a.y?(l.push([{x:a.x,y:s.y}]),l.push([{x:s.x,y:a.y}])):(s.x===a.x||s.y===a.y)&&l.push([]);const u=i+r*i,g=o.minX-u,h=o.maxX+u,d=o.maxY+u,p=o.minY-u;return(s.x<=o.minX||a.x<=o.minX)&&s.x<o.maxX&&a.x<o.maxX&&l.push([{x:g,y:s.y},{x:g,y:a.y}]),(s.x>=o.maxX||a.x>=o.maxX)&&s.x>o.minX&&a.x>o.minX&&l.push([{x:h,y:s.y},{x:h,y:a.y}]),(s.y>=o.maxY||a.y>=o.maxY)&&s.y>o.minY&&a.y>o.minY&&l.push([{x:s.x,y:d},{x:a.x,y:d}]),(s.y<=o.minY||a.y<=o.minY)&&s.y<o.maxY&&a.y<o.maxY&&l.push([{x:s.x,y:p},{x:a.x,y:p}]),l.map(m=>[...A,...m,...c])},yCo=({initialTrace:t,label:e,labelBounds:n,paddingBuffer:o,detourCount:i})=>{const r=e.globalConnNetId.startsWith("merged-group-"),s=o+i*o,a={minX:n.minX-s,maxX:n.maxX+s,minY:n.minY-s,maxY:n.maxY+s};let A,c,l,u;const g=m=>m.x>=a.minX&&m.x<=a.maxX&&m.y>=a.minY&&m.y<=a.maxY;if(r){let m=-1;for(let f=0;f<t.tracePath.length;f++)if(g(t.tracePath[f])){m=f;break}if(m===-1)return[];l=Math.max(0,m-1),A=t.tracePath[l];let _=-1;for(let f=m;f<t.tracePath.length;f++)if(!g(t.tracePath[f])){_=f;break}_===-1?u=t.tracePath.length-1:u=_,c=t.tracePath[u]}else{let m=-1,_=-1;for(let f=0;f<t.tracePath.length-1;f++)CC(t.tracePath[f],t.tracePath[f+1],{...n})&&(m===-1&&(m=f),_=f);if(m===-1)return[];l=m,u=_+1,A=t.tracePath[l],c=t.tracePath[u]}if(!A||!c||l>=u)return[];const h=[],d=c.x-A.x,p=c.y-A.y;if(Math.abs(d)>Math.abs(p)){const m=[a.maxY,a.minY];for(const _ of m)h.push(d>0?[{x:a.minX,y:A.y},{x:a.minX,y:_},{x:a.maxX,y:_},{x:a.maxX,y:c.y}]:[{x:a.maxX,y:A.y},{x:a.maxX,y:_},{x:a.minX,y:_},{x:a.minX,y:c.y}])}else{const m=[a.maxX,a.minX];for(const _ of m)h.push(p>0?[{x:A.x,y:a.minY},{x:_,y:a.minY},{x:_,y:a.maxY},{x:c.x,y:a.maxY}]:[{x:A.x,y:a.maxY},{x:_,y:a.maxY},{x:_,y:a.minY},{x:c.x,y:a.minY}])}return h.map(m=>[...t.tracePath.slice(0,l),A,...m,c,...t.tracePath.slice(u+1)])},Qa=t=>{if(t.length<3)return t;const e=[t[0]];for(let o=1;o<t.length-1;o++){const i=e[e.length-1],r=t[o],s=t[o+1];e1(i,r)&&e1(r,s)||X_(i,r)&&X_(r,s)||e.push(r)}if(e.push(t[t.length-1]),e.length<3)return e;const n=[e[0]];for(let o=1;o<e.length-1;o++){const i=n[n.length-1],r=e[o],s=e[o+1];e1(i,r)&&e1(r,s)||X_(i,r)&&X_(r,s)||n.push(r)}return n.push(e[e.length-1]),n},SQt=({trace:t,label:e,paddingBuffer:n,detourCount:o})=>{const i={...t,tracePath:Qa(t.tracePath)};if(t.globalConnNetId===e.globalConnNetId)return[i.tracePath];const r=Ls(e.center,e.width,e.height),s={minX:r.minX,minY:r.minY,maxX:r.maxX,maxY:r.maxY,chipId:`netlabel-${e.netId}`},a=yCo({initialTrace:i,label:e,labelBounds:s,paddingBuffer:n,detourCount:o}),A=n+o*n,c={minX:s.minX-A,maxX:s.maxX+A,minY:s.minY-A,maxY:s.maxY+A},{firstInsideIndex:l,lastInsideIndex:u}=ICo({path:i.tracePath,labelBounds:s,paddedBounds:c}),g=CCo({initialTrace:i,firstInsideIndex:l,lastInsideIndex:u,labelBounds:s,paddingBuffer:n,detourCount:o});return[...a,...g]},G7=.002,xCo=1e-6,QQt=.02,vQt=QQt+xCo,ECo=QQt*3,nw=(t,e)=>wQt(t,e.map(n=>n.tracePath)),wQt=(t,e)=>{const n=(o,i,r,s)=>Math.min(Math.max(o,i),Math.max(r,s))-Math.max(Math.min(o,i),Math.min(r,s))>G7;for(let o=0;o<t.length-1;o++){const i=t[o],r=t[o+1],s=Math.abs(i.x-r.x)<G7,a=Math.abs(i.y-r.y)<G7;if(!s&&!a)continue;const A=s?"x":"y",c=s?"y":"x";for(const l of e)for(let u=0;u<l.length-1;u++){const g=l[u],h=l[u+1];if(!(!(Math.abs(g[A]-h[A])<G7)||!(Math.abs(i[A]-g[A])<G7))&&n(i[c],r[c],g[c],h[c]))return!0}}return!1},PQt=(t,e)=>{const n=vQt/2,o=(i,r,s)=>s?{minX:i.x-n,maxX:i.x+n,minY:Math.min(i.y,r.y),maxY:Math.max(i.y,r.y)}:{minX:Math.min(i.x,r.x),maxX:Math.max(i.x,r.x),minY:i.y-n,maxY:i.y+n};for(let i=0;i<t.length-1;i++){const r=t[i],s=t[i+1],a=Math.abs(r.x-s.x)<G7,A=Math.abs(r.y-s.y)<G7;if(!a&&!A)continue;const c=o(r,s,a);for(const l of e)for(let u=0;u<l.tracePath.length-1;u++){const g=l.tracePath[u],h=l.tracePath[u+1];if(!(a?Math.abs(g.x-h.x)<G7:Math.abs(g.y-h.y)<G7))continue;const p=fct(c,o(g,h,a));if(!p)continue;if((a?p.maxY-p.minY:p.maxX-p.minX)>G7)return!0}}return!1},BCo=5,bCo=1e-9,MQt=t=>{let e=0;for(let n=0;n<t.length-1;n++){const o=t[n],i=t[n+1];e+=Math.abs(i.x-o.x)+Math.abs(i.y-o.y)}return e},Ele=class extends Ng{queuedCandidatePaths;solvedTracePath=null;initialTrace;problem;obstacles;label;tracesToAvoidOverlapping;netLabelPlacements;detourCount;_tried=0;constructor(t){super(),this.initialTrace=t.trace,this.problem=t.problem,this.label=t.label,this.detourCount=t.detourCount,this.tracesToAvoidOverlapping=(t.tracesToAvoidOverlapping??[]).filter(r=>r.globalConnNetId!==t.trace.globalConnNetId),this.netLabelPlacements=t.netLabelPlacements??[t.label],this.obstacles=Hy(this.problem);const e=t.paddingBuffer+t.detourCount*t.paddingBuffer,n=SQt({...t,paddingBuffer:e}),o=r=>Jh({traces:[{...this.initialTrace,tracePath:r}],netLabels:this.netLabelPlacements}).length,i=new Map;for(const r of n){const s=Qa(r);i.set(s.map(a=>`${a.x},${a.y}`).join(";"),s)}this.queuedCandidatePaths=[...i.values()].sort((r,s)=>{const a=MQt(r)-MQt(s);if(Math.abs(a)>=bCo)return a;const A=o(r)-o(s);return A!==0?A:r.length-s.length})}_step(){if(this.queuedCandidatePaths.length===0||this._tried>=BCo){this.failed=!0;return}this._tried++;const t=this.queuedCandidatePaths.shift(),e=Qa(t),n=Jh({traces:[{...this.initialTrace,tracePath:e}],netLabels:[this.label]}).length>0,o=Qa(this.initialTrace.tracePath),i=Jh({traces:[{...this.initialTrace,tracePath:o}],netLabels:this.netLabelPlacements}),r=Jh({traces:[{...this.initialTrace,tracePath:e}],netLabels:this.netLabelPlacements});!n&&r.length<=i.length&&!ON(e,this.obstacles)&&!nw(e,this.tracesToAvoidOverlapping)&&(this.solvedTracePath=e,this.solved=!0)}visualize(){const t=zh(this.problem,{chipAlpha:.1,connectionAlpha:.1});return t.lines||(t.lines=[]),t.rects||(t.rects=[]),t.lines.push({points:this.initialTrace.tracePath,strokeColor:"red",strokeDash:"4 4"}),t.rects.push({center:this.label.center,width:this.label.width,height:this.label.height,fill:"rgba(255, 0, 0, 0.2)"}),!this.solvedTracePath&&this.queuedCandidatePaths.length>0&&t.lines.push({points:this.queuedCandidatePaths[0],strokeColor:"orange"}),this.solvedTracePath&&t.lines.push({points:this.solvedTracePath,strokeColor:"green"}),t}},SCo=({trace:t,label:e})=>{if(t.tracePath.length<2)return!1;const n={...t,tracePath:[t.tracePath[0],t.tracePath[1]]};if(Jh({traces:[n],netLabels:[e]}).length>0)return!0;if(t.tracePath.length>2){const i=t.tracePath[t.tracePath.length-1],r=t.tracePath[t.tracePath.length-2],s={...t,tracePath:[r,i]};if(Jh({traces:[s],netLabels:[e]}).length>0)return!0}return!1},QCo=t=>{const{decomposedChildLabels:e,collidingTrace:n,mergedLabel:o,graphics:i}=t;i.rects||(i.rects=[]),i.texts||(i.texts=[]);for(const r of e){const s=r.globalConnNetId===n.globalConnNetId;i.rects.push({center:r.center,width:r.width,height:r.height,fill:s?"green":"red"})}return i.texts.push({x:o.center.x,y:o.center.y+o.height/2+.5,text:`DECOMPOSITION: Trace ${n.mspPairId} vs Merged Label ${o.globalConnNetId}`,fontSize:.3,color:"blue"}),i},vCo=class extends Ng{inputProblem;initialNetLabelPlacements;mergedNetLabelPlacements;mergedLabelNetIdMap;allTraces;tracesToAvoidOverlapping;modifiedTraces=[];completedReroutes=[];PADDING_BUFFER=.1;detourCounts=new Map;activeSubSolver=null;overlapQueue=[];activeOverlap=null;recentlyFailed=new Set;currentlyProcessingOverlap=null;decomposedChildLabels=null;constructor(t){super(),this.inputProblem=t.inputProblem,this.initialNetLabelPlacements=t.initialNetLabelPlacements,this.mergedNetLabelPlacements=t.mergedNetLabelPlacements,this.mergedLabelNetIdMap=t.mergedLabelNetIdMap,this.allTraces=[...t.traces],this.tracesToAvoidOverlapping=t.tracesToAvoidOverlapping??[],this.detourCounts=t.detourCounts}_step(){if(this.currentlyProcessingOverlap=null,this.decomposedChildLabels=null,this.activeSubSolver){if(this.activeSubSolver.step(),this.activeSubSolver.solved){const o=this.activeSubSolver.solvedTracePath;if(o){this.completedReroutes.push({initialTrace:{...this.activeSubSolver.initialTrace,tracePath:this.activeSubSolver.initialTrace.tracePath.map(r=>({...r}))},reroutedTracePath:o.map(r=>({...r})),label:this.activeSubSolver.label,detourCount:this.activeSubSolver.detourCount});const i=this.allTraces.findIndex(r=>r.mspPairId===this.activeSubSolver.initialTrace.mspPairId);i!==-1&&(this.allTraces[i].tracePath=o,this.modifiedTraces.push(this.allTraces[i]))}this.activeSubSolver=null,this.activeOverlap=null,this.recentlyFailed.clear()}else if(this.activeSubSolver.failed){const o=`${this.activeOverlap.trace.mspPairId}-${this.activeOverlap.label.globalConnNetId}`;this.recentlyFailed.add(o),this.activeSubSolver=null,this.activeOverlap=null}return}const t=Jh({traces:this.allTraces,netLabels:this.mergedNetLabelPlacements});if(t.length===0){this.solved=!0;return}const e=t.filter(o=>{const i=`${o.trace.mspPairId}-${o.label.globalConnNetId}`;return!this.recentlyFailed.has(i)});if(e.length===0){this.solved=!0;return}this.overlapQueue=e;const n=this.overlapQueue.shift();if(this.currentlyProcessingOverlap=n??null,n){const o=this.allTraces.find(A=>A.mspPairId===n.trace.mspPairId),i=n.label,r=this.mergedLabelNetIdMap[i.globalConnNetId];if(r?.has(o.globalConnNetId)){const A=this.initialNetLabelPlacements.filter(l=>r.has(l.globalConnNetId));this.decomposedChildLabels=A;let c=null;for(const l of A)if(Jh({traces:[o],netLabels:[l]}).length>0){c=l;break}if(c){const l=this.detourCounts.get(c.globalConnNetId)??0;this.detourCounts.set(c.globalConnNetId,l+1),this.activeOverlap=n,this.activeSubSolver=new Ele({trace:o,label:c,problem:this.inputProblem,paddingBuffer:this.PADDING_BUFFER,detourCount:l,tracesToAvoidOverlapping:this.tracesToAvoidOverlapping,netLabelPlacements:this.initialNetLabelPlacements})}else{const l=`${o.mspPairId}-${i.globalConnNetId}`;this.recentlyFailed.add(l)}return}if(r&&SCo({trace:o,label:i})){const A=this.initialNetLabelPlacements.filter(l=>r.has(l.globalConnNetId));this.decomposedChildLabels=A;let c=null;for(const l of A)if(Jh({traces:[o],netLabels:[l]}).length>0){c=l;break}if(c){const l=this.detourCounts.get(c.globalConnNetId)??0;this.detourCounts.set(c.globalConnNetId,l+1),this.activeOverlap=n,this.activeSubSolver=new Ele({trace:o,label:c,problem:this.inputProblem,paddingBuffer:this.PADDING_BUFFER,detourCount:l,tracesToAvoidOverlapping:this.tracesToAvoidOverlapping,netLabelPlacements:this.initialNetLabelPlacements})}else{const l=`${o.mspPairId}-${i.globalConnNetId}`;this.recentlyFailed.add(l)}return}const a=this.detourCounts.get(i.globalConnNetId)??0;this.detourCounts.set(i.globalConnNetId,a+1),this.activeOverlap=n,this.activeSubSolver=new Ele({trace:o,label:i,problem:this.inputProblem,paddingBuffer:this.PADDING_BUFFER,detourCount:a,tracesToAvoidOverlapping:this.tracesToAvoidOverlapping,netLabelPlacements:this.initialNetLabelPlacements})}}getOutput(){return{allTraces:this.allTraces,modifiedTraces:this.modifiedTraces,detourCounts:this.detourCounts}}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();const t=zh(this.inputProblem);t.lines||(t.lines=[]);for(const e of this.allTraces)t.lines.push({points:e.tracePath,strokeColor:"purple"});if(this.currentlyProcessingOverlap){const{trace:e,label:n}=this.currentlyProcessingOverlap;t.lines.push({points:e.tracePath,strokeColor:"red"}),this.decomposedChildLabels?QCo({decomposedChildLabels:this.decomposedChildLabels,collidingTrace:e,mergedLabel:n,graphics:t}):(t.rects||(t.rects=[]),t.rects.push({center:n.center,width:n.width,height:n.height,fill:"yellow"}),t.texts||(t.texts=[]),t.texts.push({x:n.center.x,y:n.center.y+n.height/2+.5,text:`COLLISION: Trace ${e.mspPairId} vs Label ${n.globalConnNetId}`,fontSize:.3,color:"red"}))}return t}},wCo=class extends Ng{inputProblem;netLabelPlacements;unprocessedTraces=[];cleanTraces=[];subSolvers=[];phase="searching_for_overlaps";detourCounts=new Map;labelMergingSolver;allInputTraces;constructor(t){super(),this.inputProblem=t.inputProblem,this.unprocessedTraces=[...t.traces],this.allInputTraces=t.traces,this.netLabelPlacements=t.netLabelPlacements,this.cleanTraces=[],this.subSolvers=[]}_step(){if(this.phase==="searching_for_overlaps"){if(this.unprocessedTraces.length===0){this.phase="fixing_overlaps";return}const t=this.unprocessedTraces.shift(),e=Jh({traces:[t],netLabels:this.netLabelPlacements});if(e.length===0)this.cleanTraces.push(t);else{const n=e.map(s=>s.label),o=new bQt({netLabelPlacements:n,inputProblem:this.inputProblem,traces:[t]});o.solve();const i=o.getOutput(),r=new vCo({inputProblem:this.inputProblem,traces:[t],initialNetLabelPlacements:this.netLabelPlacements,mergedNetLabelPlacements:i.netLabelPlacements,mergedLabelNetIdMap:i.mergedLabelNetIdMap,detourCounts:this.detourCounts,tracesToAvoidOverlapping:this.allInputTraces.filter(s=>s.mspPairId!==t.mspPairId)});this.subSolvers.push(r)}}else if(this.phase==="fixing_overlaps"){if(this.subSolvers.every(t=>t.solved||t.failed)){this.labelMergingSolver||(this.labelMergingSolver=new bQt({netLabelPlacements:this.netLabelPlacements,inputProblem:this.inputProblem,traces:this.getOutput().traces}),this.labelMergingSolver.solve()),this.solved=!0;return}for(const t of this.subSolvers)!t.solved&&!t.failed&&t.step()}}getOutput(){const t=this.subSolvers.flatMap(e=>e.getOutput().allTraces);return{traces:[...this.cleanTraces,...t],completedReroutes:this.subSolvers.flatMap(e=>e.completedReroutes),netLabelPlacements:this.labelMergingSolver?.getOutput().netLabelPlacements??this.netLabelPlacements}}visualize(){const t=zh(this.inputProblem);t.lines||(t.lines=[]),t.rects||(t.rects=[]);for(const e of this.cleanTraces)t.lines.push({points:e.tracePath,strokeColor:"purple"});for(const e of this.subSolvers){const n=e.visualize();t.lines.push(...n.lines??[]),t.rects.push(...n.rects??[]),t.points.push(...n.points??[])}for(const e of this.netLabelPlacements){const n=Mc(e.globalConnNetId,.3);t.rects.push({center:e.center,width:e.width,height:e.height,fill:n,stroke:n.replace("0.3","1"),label:e.globalConnNetId})}return t}},PCo=t=>{for(const e of t.chips){const n=Rve(e);for(const o of e.pins){if(!(o.x>n.minX&&o.x<n.maxX&&o.y>n.minY&&o.y<n.maxY))continue;if(o._facingDirection){o._facingDirection==="x-"?o.x=n.minX:o._facingDirection==="x+"?o.x=n.maxX:o._facingDirection==="y-"?o.y=n.minY:o.y=n.maxY;continue}const r=o.x-n.minX,s=n.maxX-o.x,a=o.y-n.minY,A=n.maxY-o.y,c=Math.min(r,s,a,A);c===r?o.x=n.minX:c===s?o.x=n.maxX:c===a?o.y=n.minY:o.y=n.maxY,o._facingDirection=void 0}}},MCo=t=>{for(const e of t.chips){const n=e.width/2,o=e.height/2;let i=0,r=0;for(const A of e.pins){const c=Math.abs(A.x-e.center.x),l=Math.abs(A.y-e.center.y);c>i&&(i=c),l>r&&(r=l)}const s=Math.max(n,i),a=Math.max(o,r);if(s>n||a>o){e.width=s*2,e.height=a*2;for(const A of e.pins)A._facingDirection=void 0}}};function DCo(t,e){for(let n=0;n<t.length-1;n++){const o=t[n],i=t[n+1];for(const r of e)for(let s=0;s<r.tracePath.length-1;s++){const a=r.tracePath[s],A=r.tracePath[s+1];if(X1(o,i,a,A))return!0}}return!1}var DQt=(t,e,n)=>{const o=t.maxMspPairDistance??uj,{extendedRailPinIds:i,separatedRailPinIds:r}=aQt(t,e,o),s=new Set,a=new Set;for(const u of t.netConnections){const g=e.getNetConnectedToId(u.netId);if(g){for(const h of u.pinIds)a.add(h);u.isGround&&s.add(g)}}const A=new Map;for(const u of t.chips){if(u.pins.length!==2||!u.pins.every(m=>a.has(m.pinId))||u.pins.some(m=>n.has(m.pinId)&&!i.has(m.pinId)))continue;const[g,h]=u.pins.map(m=>e.getNetConnectedToId(m.pinId));if(!g||!h||g===h||s.has(g)===s.has(h))continue;const d=JSON.stringify([u.sectionId??null,...[g,h].sort()]),p=A.get(d)??[];p.push(u.pins.map(m=>m.pinId)),A.set(d,p)}const c=new Set([...A.values()].filter(u=>u.length>1).flat(2));for(const u of[...i,...r])c.add(u);const l=new mle({});for(const u of t.directConnections)u.netLabelWidth===void 0&&l.addConnections([u.pinIds]);return(u,g)=>{if(!c.has(u.pinId)&&!c.has(g.pinId)||Math.abs(u.x-g.x)+Math.abs(u.y-g.y)<=o)return!0;const h=l.getNetConnectedToId(u.pinId);return h!==void 0&&h===l.getNetConnectedToId(g.pinId)}},NCo=3,Ble=(t,e)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2)),RCo=(t,e)=>Math.abs(t.x-e.x)+Math.abs(t.y-e.y),IB=1e-9,ble=(t,e,n)=>t>=Math.min(e,n)-IB&&t<=Math.max(e,n)+IB,TCo=(t,e,n,o)=>{const i=Math.abs(t.y-e.y)<=IB,r=Math.abs(t.x-e.x)<=IB,s=Math.abs(n.y-o.y)<=IB,a=Math.abs(n.x-o.x)<=IB;if(i&&a){const A={x:n.x,y:t.y};return ble(A.x,t.x,e.x)&&ble(A.y,n.y,o.y)?A:null}if(r&&s){const A={x:t.x,y:n.y};return ble(A.y,t.y,e.y)&&ble(A.x,n.x,o.x)?A:null}if(i&&s&&Math.abs(t.y-n.y)<=IB){const A=Math.max(Math.min(t.x,e.x),Math.min(n.x,o.x)),c=Math.min(Math.max(t.x,e.x),Math.max(n.x,o.x));return A>c+IB?null:{x:Math.max(A,Math.min(t.x,c)),y:t.y}}if(r&&a&&Math.abs(t.x-n.x)<=IB){const A=Math.max(Math.min(t.y,e.y),Math.min(n.y,o.y)),c=Math.min(Math.max(t.y,e.y),Math.max(n.y,o.y));return A>c+IB?null:{x:t.x,y:Math.max(A,Math.min(t.y,c))}}return null},kCo=(t,e)=>{for(let n=0;n<t.length-1;n++){const o=t[n],i=t[n+1],r=e.flatMap(A=>A.tracePath.slice(0,-1).flatMap((c,l)=>{const u=TCo(o,i,c,A.tracePath[l+1]);return u?[u]:[]}));r.sort((A,c)=>Ble(o,A)-Ble(o,c));const s=r[0];if(!s)continue;const a=t.slice(0,n+1);return Ble(a.at(-1),s)>IB&&a.push(s),a}return null},FCo=class extends Ng{constructor(t){super(),this.params=t;const{inputProblem:e,primaryMspConnectionPairs:n,alreadySolvedTraces:o}=this.params,i=nQt(e);this.inputProblem=e,this.allSolvedTraces=[...o],this.maxMspPairDistance=e.maxMspPairDistance??uj;const r=new Set;for(const u of n)r.add(u.pins[0].pinId),r.add(u.pins[1].pinId);const{netConnMap:s}=mB(e);this.netConnMap=s;const a=DQt(e,s,r),A=new Map;for(const u of e.chips){this.chipMap[u.chipId]=u;for(const g of u.pins)A.set(g.pinId,{...g,chipId:u.chipId})}this.queuedFailedConnectionPairs=this.params.failedConnectionPairs.filter(u=>i(u.pins[0].pinId,u.pins[1].pinId)&&GIo({inputProblem:this.inputProblem,chipMap:this.chipMap,pins:u.pins}));const c=[],l=new Set;for(const u of Object.keys(s.netMap)){const g=s.getIdsConnectedToNet(u);if(g.length<2)continue;const h=g.filter(d=>!r.has(d));for(const d of h){const p=A.get(d);if(!p)continue;const m=g.filter(_=>_!==d).flatMap(_=>{const f=A.get(_);return f?i(p.pinId,f.pinId)?a(p,f)?e.netConnections.some(C=>C.pinIds.length===2&&C.pinIds.includes(p.pinId)&&C.pinIds.includes(f.pinId))&&RCo(p,f)>this.maxMspPairDistance?[]:[{pin:f,distance:Ble(p,f)}]:[]:[]:[]}).sort((_,f)=>_.distance-f.distance).slice(0,NCo);for(const _ of m){const f=[p,_.pin];if(Zv(e,f[0],f[1]))continue;const I=f.map(C=>C.pinId).sort().join("--");l.has(I)||(c.push(f),l.add(I))}}}this.queuedCandidatePairs=c}params;solvedLongDistanceTraces=[];queuedCandidatePairs=[];currentCandidatePair=null;queuedFailedConnectionPairs=[];currentFailedConnectionPair=null;subSolver=null;chipMap={};inputProblem;netConnMap;newlyConnectedPinIds=new Set;allSolvedTraces=[];maxMspPairDistance;getConstructorParams(){return this.params}acceptFailedConnectionPair(t){const e=this.currentFailedConnectionPair;if(!e)return;const n={...e,tracePath:t,mspConnectionPairIds:[e.mspPairId],pinIds:e.pins.map(o=>o.pinId)};this.solvedLongDistanceTraces.push(n),this.allSolvedTraces.push(n);for(const o of e.pins)this.newlyConnectedPinIds.add(o.pinId)}_step(){if(this.subSolver?.solved&&this.currentFailedConnectionPair){const e=this.subSolver.solvedTracePath;e&&this.acceptFailedConnectionPair(e),this.subSolver=null,this.currentCandidatePair=null,this.currentFailedConnectionPair=null}else if(this.subSolver?.solved){const e=this.subSolver.solvedTracePath;if(e&&this.currentCandidatePair){const[n,o]=this.currentCandidatePair,i=this.netConnMap.getNetConnectedToId(n.pinId),r=this.allSolvedTraces.filter(d=>d.globalConnNetId===i),s=this.inputProblem.netConnections.find(d=>d.pinIds.length===3&&d.pinIds.includes(n.pinId)&&d.pinIds.includes(o.pinId)),a=this.chipMap[n.chipId],A=r.find(d=>d.pinIds.includes(o.pinId)&&d.pins.every(p=>p.chipId===o.chipId)),l=s!==void 0&&a?.pins.length===2&&A!==void 0?kCo(e,r):null,u=l??e,g=l?this.allSolvedTraces.filter(d=>d.globalConnNetId!==i):this.allSolvedTraces;if(!DCo(u,g)){const d=`${n.pinId}-${o.pinId}`,p={mspPairId:d,dcConnNetId:i,globalConnNetId:i,pins:[n,o],tracePath:u,mspConnectionPairIds:[d],pinIds:[n.pinId,o.pinId]};this.solvedLongDistanceTraces.push(p),this.allSolvedTraces.push(p),this.newlyConnectedPinIds.add(n.pinId),this.newlyConnectedPinIds.add(o.pinId)}}this.subSolver=null,this.currentCandidatePair=null}else this.subSolver?.failed&&(this.subSolver=null,this.currentCandidatePair=null,this.currentFailedConnectionPair=null);if(this.subSolver){this.subSolver.step();return}const t=this.queuedFailedConnectionPairs.shift();if(t){this.currentFailedConnectionPair=t,this.currentCandidatePair=t.pins,this.subSolver=new VH({inputProblem:this.params.inputProblem,pins:t.pins,chipMap:this.chipMap});return}for(;this.queuedCandidatePairs.length>0;){const e=this.queuedCandidatePairs.shift(),[n,o]=e;if(!(this.newlyConnectedPinIds.has(n.pinId)||this.newlyConnectedPinIds.has(o.pinId))){this.currentCandidatePair=e,this.subSolver=new VH({inputProblem:this.params.inputProblem,pins:this.currentCandidatePair,chipMap:this.chipMap});return}}this.solved=!0}visualize(){if(this.subSolver)return this.subSolver.visualize();const t=zh(this.inputProblem);for(const e of this.solvedLongDistanceTraces)t.lines.push({points:e.tracePath,strokeColor:"purple"});for(const[e,n]of this.queuedCandidatePairs)t.lines.push({points:[e,n],strokeColor:"gray",strokeDash:"4 4"});return t}getOutput(){return this.solved?{newTraces:this.solvedLongDistanceTraces,allTracesMerged:[...this.params.alreadySolvedTraces,...this.solvedLongDistanceTraces]}:{newTraces:[],allTracesMerged:this.params.alreadySolvedTraces}}},kve=(t,e)=>{for(let n=0;n<t.length-1;n++){const o=t[n],i=t[n+1];for(const r of e){const s={center:{x:r.minX+(r.maxX-r.minX)/2,y:r.minY+(r.maxY-r.minY)/2},width:r.maxX-r.minX,height:r.maxY-r.minY};if(yQn(o,i,s)<=0)return!0}}return!1},j5=t=>{let e=0;for(let n=1;n<t.length-1;n++){const o=t[n-1],i=t[n],r=t[n+1],s=o.x===i.x,a=i.x===r.x;s!==a&&e++}return e},NQt=(t,e)=>{const n=[];return t.x===e.x||t.y===e.y?n.push([t,e]):(n.push([t,{x:e.x,y:t.y},e]),n.push([t,{x:t.x,y:e.y},e])),n},Oy=1e-9,RQt=(t,e,n,o)=>e>=n-Oy&&o>=t-Oy&&Math.min(e,o)-Math.max(t,n)<=Oy,TQt=(t,e)=>Math.abs(t.x-e.x)<=Oy&&Math.abs(t.y-e.y)<=Oy,LCo=({start:t,end:e,label:n,originalPath:o})=>{const i=Math.abs(t.x-e.x)<=Oy,r=Math.abs(t.y-e.y)<=Oy;if(!(i?Math.abs(t.x-n.minX)<=Oy||Math.abs(t.x-n.maxX)<=Oy:r?Math.abs(t.y-n.minY)<=Oy||Math.abs(t.y-n.maxY)<=Oy:!1))return!1;for(let a=0;a<o.length-1;a++){if(!(a===0||a===o.length-2))continue;const c=o[a],l=o[a+1],u=a===0?l:c;if(!(!TQt(t,u)&&!TQt(e,u))&&CC(c,l,n)&&(i&&Math.abs(c.x-l.x)<=Oy&&Math.abs(c.x-t.x)<=Oy&&RQt(Math.min(t.y,e.y),Math.max(t.y,e.y),Math.min(c.y,l.y),Math.max(c.y,l.y))||r&&Math.abs(c.y-l.y)<=Oy&&Math.abs(c.y-t.y)<=Oy&&RQt(Math.min(t.x,e.x),Math.max(t.x,e.x),Math.min(c.x,l.x),Math.max(c.x,l.x))))return!0}return!1},Sle=(t,e,n={})=>{for(let o=0;o<t.length-1;o++){const i=t[o],r=t[o+1];for(const s of e)if(CC(i,r,s)){if(n.originalPath&&LCo({start:i,end:r,label:s,originalPath:n.originalPath}))continue;return!0}}return!1},HCo=(t,e)=>{if(e>=t.length-3)return-1;let n=e,o=!0;for(let i=e;i<t.length-2&&i<e+10&&!(i+2>=t.length);i++){const r=t[i],s=t[i+1],a=t[i+2],A=r.x===s.x,c=s.x===a.x;if(A===c)break;const l=Math.sign(A?s.y-r.y:s.x-r.x);if(i>e){const u=t[i-1],g=u.x===r.x,h=Math.sign(g?r.y-u.y:r.x-u.x);if(A&&g&&l!==h||!A&&!g&&l!==h){o=!1;break}}n=i+2}return o&&n-e>=3?n:-1},zH=(t,e,n)=>{if(n.length<2)return!1;const o=n[0],i=n[n.length-1];return t.x===o.x&&t.y===o.y&&e.x===n[1].x&&e.y===n[1].y||t.x===n[n.length-2].x&&t.y===n[n.length-2].y&&e.x===i.x&&e.y===i.y},kQt=({path:t,obstacles:e,labelBounds:n,originalPath:o,allowLabelBoundaryExtension:i=!1})=>{if(t.length<=2)return t;let r=[...t],s=j5(r),a=!0;for(;a;){a=!1;for(let c=0;c<r.length-3;c++){const l=HCo(r,c);if(l>0){if(zH(r[c],r[c+1],o)||zH(r[l-1],r[l],o))continue;const u=r[c],g=r[l],h=NQt(u,g);for(const d of h){const p=[...r.slice(0,c+1),...d.slice(1,-1),...r.slice(l)],m=kve(d,e),_=Sle(d,n,i?{originalPath:o}:{});if(!m&&!_){const f=j5(p);r=p,s=f,a=!0;break}}if(a)break}}if(!a)for(let c=0;c<r.length-2;c++){const l=Math.min(r.length-c-2,r.length-2);for(let u=1;u<=l;u++){const g=c+u+1;if(g>=r.length||zH(r[c],r[c+1],o)||zH(r[g-1],r[g],o))continue;const h=r[c],d=r[g],p=NQt(h,d);for(const m of p){const _=[...r.slice(0,c+1),...m.slice(1,-1),...r.slice(g)],f=m,I=kve(f,e),C=Sle(f,n,i?{originalPath:o}:{});if(!I&&!C){const y=j5(_);if(y<s||y===s&&_.length<r.length){r=_,s=y,a=!0;break}}}if(a)break}if(a)break}if(!a)for(let c=0;c<r.length-2;c++){const l=r[c],u=r[c+1],g=r[c+2];if(zH(l,u,o)||zH(u,g,o))continue;const h=l.x===u.x&&u.x===g.x,d=l.y===u.y&&u.y===g.y;if(h||d){const p=[...r.slice(0,c+1),...r.slice(c+2)],m=kve([l,g],e),_=Sle([l,g],n,i?{originalPath:o}:{});if(!m&&!_){r=p,a=!0;break}}}}return Qa(r)},Gy=.002,Uc=(t,e)=>Math.abs(t-e)<Gy,CB=(t,e)=>Uc(t.y,e.y),Yy=(t,e)=>Uc(t.x,e.x),OCo=(t,e)=>Math.abs(t.x-e.x)>=Gy||Math.abs(t.y-e.y)>=Gy,JH=(t,e)=>OCo(t,e)?Yy(t,e)?"vertical":CB(t,e)?"horizontal":null:null,FQt=(t,e)=>Math.min(t.maxAlong,e.maxAlong)-Math.max(t.minAlong,e.minAlong)>=-Gy,fb=(t,e)=>Uc(t.x,e.x)&&Uc(t.y,e.y),Fve=t=>{const e=[];for(const n of t)e.some(o=>Uc(o,n))||e.push(n);return e},LQt=t=>{const e=[];for(const n of t){const o=e.find(i=>Uc(i[0].coordinate,n.coordinate));o?o.push(n):e.push([n])}return e.reduce((n,o)=>{const i=[...o].sort((c,l)=>c.min-l.min);let r=0,s=1,a=i[0].min,A=i[0].max;for(const c of i.slice(1))c.min<=A+Gy?A=Math.max(A,c.max):(r+=A-a,s++,a=c.min,A=c.max);return{length:n.length+r+A-a,segmentCount:n.segmentCount+s}},{length:0,segmentCount:0})},HQt=t=>{const e=[],n=[];for(const r of t)for(let s=0;s<r.tracePath.length-1;s++){const a=r.tracePath[s],A=r.tracePath[s+1];CB(a,A)?e.push({coordinate:a.y,min:Math.min(a.x,A.x),max:Math.max(a.x,A.x)}):Yy(a,A)&&n.push({coordinate:a.x,min:Math.min(a.y,A.y),max:Math.max(a.y,A.y)})}const o=LQt(e),i=LQt(n);return{length:o.length+i.length,segmentCount:o.segmentCount+i.segmentCount}},Y7=t=>HQt(t).length,Qle=t=>HQt(t).segmentCount,GCo=2.5,OQt=t=>{let e=0;for(let n=1;n<t.length;n++){const o=t[n-1],i=t[n];e+=Math.abs(i.x-o.x)+Math.abs(i.y-o.y)}return e},YCo=({inputProblem:t,trace:e})=>{const n=t.directConnections.find(a=>a.pinIds.every(A=>e.pinIds.includes(A)));if(!n)return e;const o={};for(const a of t.chips)o[a.chipId]=a;const i=new VH({pins:e.pins,connectionPair:e,inputProblem:{...t,directConnections:[n,...t.directConnections.filter(a=>a!==n)]},chipMap:o});if(i.solve(),!i.solvedTracePath)return e;const r=OQt(e.tracePath),s=OQt(i.solvedTracePath);return r<=s*GCo?e:{...e,tracePath:i.solvedTracePath}},UCo=1e-9,GQt=t=>t.slice(1).reduce((e,n,o)=>{const i=t[o];return e+Math.abs(n.x-i.x)+Math.abs(n.y-i.y)},0),KCo=({strictPath:t,boundaryPath:e})=>{const n=j5(e)<=j5(t),o=Math.abs(GQt(e)-GQt(t))<=UCo;return n&&o?e:t},YQt=({targetMspConnectionPairId:t,traces:e,inputProblem:n,allLabelPlacements:o,mergedLabelNetIdMap:i,paddingBuffer:r})=>{const s=e.find(w=>w.mspPairId===t);if(!s)throw new Error(`Target trace ${t} not found`);const a=YCo({inputProblem:n,trace:s}),A=new Set(a.pinIds),c=e.filter(w=>w.mspPairId!==t),l=c.filter(w=>{const M=w.pinIds.some(k=>A.has(k));return w.globalConnNetId!==a.globalConnNetId||!M}),u=.01,g=w=>w.flatMap((M,k)=>M.tracePath.slice(0,-1).map((R,F)=>{const O=M.tracePath[F+1];return{chipId:`trace-obstacle-${k}-${F}`,minX:Math.min(R.x,O.x)-u/2,minY:Math.min(R.y,O.y)-u/2,maxX:Math.max(R.x,O.x)+u/2,maxY:Math.max(R.y,O.y)+u/2}})),h=Hy(n),d=.01,p=h.map(w=>({...w,minX:w.minX-d,minY:w.minY-d,maxX:w.maxX+d,maxY:w.maxY+d})),m=a.tracePath,f=o.filter(w=>{const M=i[w.globalConnNetId];return M?!M.has(a.globalConnNetId):w.globalConnNetId!==a.globalConnNetId}).map(w=>({minX:w.center.x-w.width/2-r,maxX:w.center.x+w.width/2+r,minY:w.center.y-w.height/2-r,maxY:w.center.y+w.height/2+r})),I=w=>{const M=kQt({path:m,obstacles:w,labelBounds:f,originalPath:m}),k=kQt({path:m,obstacles:w,labelBounds:f,originalPath:m,allowLabelBoundaryExtension:!0});return KCo({strictPath:M,boundaryPath:k})},C=I([...p,...g(c)]),y=I([...p,...g(l)]),x=c.filter(w=>w.globalConnNetId===a.globalConnNetId),E=w=>{const M=[...x,{...a,tracePath:w}];return{segmentCount:Qle(M),visibleLength:Y7(M)}},B=j5(C),S=j5(y);let Q=C;if(S<B)Q=y;else if(S===B){const w=E(C),M=E(y);(M.segmentCount<w.segmentCount||M.segmentCount===w.segmentCount&&M.visibleLength<w.visibleLength-Gy)&&(Q=y)}return{...a,tracePath:Q}},VCo=({targetMspConnectionPairId:t,traces:e,inputProblem:n,allLabelPlacements:o,mergedLabelNetIdMap:i,paddingBuffer:r})=>{const s=e.find(I=>I.mspPairId===t);if(!s)throw new Error(`Target trace ${t} not found`);const a=1e-5,A=(I,C)=>Math.abs(I-C)<a,c=e.filter(I=>I.mspPairId!==t),l=.01,u=c.flatMap((I,C)=>I.tracePath.slice(0,-1).map((y,x)=>{const E=I.tracePath[x+1];return{chipId:`trace-obstacle-${C}-${x}`,minX:Math.min(y.x,E.x)-l/2,minY:Math.min(y.y,E.y)-l/2,maxX:Math.max(y.x,E.x)+l/2,maxY:Math.max(y.y,E.y)+l/2}})),h=[...Hy(n).map(I=>({...I,minX:I.minX+a,maxX:I.maxX-a,minY:I.minY+a,maxY:I.maxY-a})),...u],d=(I,C,y)=>{for(const x of y)if(CC(I,C,x))return!0;return!1},m=o.filter(I=>{const C=i[I.globalConnNetId];return C?!C.has(s.globalConnNetId):I.globalConnNetId!==s.globalConnNetId}).map(I=>({minX:I.center.x-I.width/2+a,maxX:I.center.x+I.width/2-a,minY:I.center.y-I.height/2+a,maxY:I.center.y+I.height/2-a})),_=[...s.tracePath];if(_.length<4)return{...s};if(_.length===4){const[I,C,y,x]=_;let E,B;if(A(I.y,C.y)&&A(C.x,y.x)&&A(y.y,x.y)){const w=(I.x+x.x)/2;E={x:w,y:C.y},B={x:w,y:y.y}}else{const w=(I.y+x.y)/2;E={x:C.x,y:w},B={x:y.x,y:w}}return d(I,E,h)||d(E,B,h)||d(B,x,h)||d(I,E,m)||d(E,B,m)||d(B,x,m)||(_[1]=E,_[2]=B),{...s,tracePath:Qa(_)}}for(let I=1;I<_.length-4;I++){const C=_[I],y=_[I+1],x=_[I+2],E=_[I+3],B=A(C.y,y.y)&&A(y.x,x.x)&&A(x.y,E.y),S=A(C.x,y.x)&&A(y.y,x.y)&&A(x.x,E.x),Q=A(C.y,y.y)&&A(y.y,x.y)&&A(x.y,E.y),w=A(C.x,y.x)&&A(y.x,x.x)&&A(x.x,E.x),M=Q||w;let k=!1;if(B?k=Math.sign(y.x-C.x)===Math.sign(E.x-x.x):S&&(k=Math.sign(y.y-C.y)===Math.sign(E.y-x.y)),!((B||S)&&!M&&k))continue;let F,O;const U=Math.abs(B?C.x-y.x:C.y-y.y),Y=Math.abs(B?x.x-E.x:x.y-E.y);if(Math.abs(U-Y)<.001)continue;if(B){const te=(C.x+E.x)/2;F={x:te,y:y.y},O={x:te,y:x.y}}else{const te=(C.y+E.y)/2;F={x:y.x,y:te},O={x:x.x,y:te}}d(C,F,h)||d(F,O,h)||d(O,E,h)||d(C,F,m)||d(F,O,m)||d(O,E,m)||(_[I+1]=F,_[I+2]=O,I=0)}const f=Qa(_);return{...s,tracePath:f}},UQt=(t,e,n)=>t==="vertical"?{minX:0,maxX:0,minY:e,maxY:n}:{minX:e,maxX:n,minY:0,maxY:0},zCo=(t,e,n)=>{const o=fct(e,n);return o?(t==="vertical"?o.maxY-o.minY:o.maxX-o.minX)>Gy:!1},JCo=({group:t,originalCoordinates:e,otherNetTraces:n})=>{const o=t[0].orientation,i=t.map(a=>UQt(o,a.minAlong,a.maxAlong)),r=ECo,s=[];for(const a of n)for(let A=0;A<a.tracePath.length-1;A++){const c=a.tracePath[A],l=a.tracePath[A+1];if(JH(c,l)!==o)continue;const u=o==="vertical"?Math.min(c.y,l.y):Math.min(c.x,l.x),g=o==="vertical"?Math.max(c.y,l.y):Math.max(c.x,l.x),h=UQt(o,u,g);if(!i.some(m=>zCo(o,m,h)))continue;const d=o==="vertical"?c.x:c.y;e.some(m=>Math.abs(m-d)<=vQt)&&s.push(d-r,d+r)}return Fve(s)},yC=1e-6,WCo=t=>jCo(t.pinIds)>=2,yB=(t,e)=>Math.min(t.maxX,e.maxX)-Math.max(t.minX,e.minX)>yC&&Math.min(t.maxY,e.maxY)-Math.max(t.minY,e.minY)>yC,Lve=t=>{const e=[];for(let n=1;n<t.length-1;n++){const o=t[n-1],i=t[n],r=t[n+1];$Co(o,i,r)&&e.push(i)}return e},jl=(t,e)=>{for(let n=0;n<t.length-1;n++)if(qCo(e,t[n],t[n+1]))return!0;return!1},KQt=(t,e)=>Math.abs(t.x-e.x)+Math.abs(t.y-e.y),jCo=t=>new Set(t).size,$Co=(t,e,n)=>Hve(t,e)!==Hve(e,n),qCo=(t,e,n)=>Hve(e,n)==="horizontal"?Math.abs(t.y-e.y)<=yC&&t.x>=Math.min(e.x,n.x)-yC&&t.x<=Math.max(e.x,n.x)+yC:Math.abs(t.x-e.x)<=yC&&t.y>=Math.min(e.y,n.y)-yC&&t.y<=Math.max(e.y,n.y)+yC,Hve=(t,e)=>Math.abs(t.y-e.y)<=yC?"horizontal":"vertical",XCo=(t,e)=>{const n=t[0].globalConnNetId,o=e.filter(s=>s.globalConnNetId===n),i=new Set(t.map(s=>s.traceId)),r=new Set(o.filter(s=>i.has(s.mspPairId)).flatMap(s=>s.pinIds));for(let s=!0;s;){s=!1;for(const a of o)if(!i.has(a.mspPairId)&&a.pinIds.some(A=>r.has(A))){i.add(a.mspPairId);for(const A of a.pinIds)r.add(A);s=!0}}return i},ZCo=(t,e,n)=>{const o=XCo(t,n);return e.filter(i=>i.mspConnectionPairIds.some(r=>o.has(r)))},VQt=(t,e,n)=>{const o=new Map(n.map(m=>[m.mspPairId,m])),i=new Set(t.map(m=>m.traceId)),r=[...i].every(m=>o.get(m)?.pins.every(_=>_.chipId===t[0].componentId)===!0);if(![...i].every(m=>o.get(m)?.tracePath.length===4))return null;const a=t[0].orientation,A=ZCo(t,e,n),c=new Set(A.filter(m=>a==="vertical"&&(m.orientation==="y+"||m.orientation==="y-")||a==="horizontal"&&(m.orientation==="x+"||m.orientation==="x-"))),l=A.filter(m=>m.orientation!==t[0].componentFacingDirection&&(!r||!c.has(m))?!1:m.mspConnectionPairIds.some(_=>{const f=o.get(_);return f&&jl(f.tracePath,m.anchorPoint)})),u=Fve(l.map(m=>a==="vertical"?m.anchorPoint.x:m.anchorPoint.y));if(u.length!==1)return null;const g=u[0],h=t.find(m=>Math.abs(m.coordinate-g)<=Gy)?.coordinate??g;if(l.some(m=>m.mspConnectionPairIds.some(_=>(o.get(_)?.tracePath.length??0)>4)))return h;if(l.some(m=>c.has(m))){const m=Math.max(...t.map(f=>f.maxAlong))-Math.min(...t.map(f=>f.minAlong));return t.every(f=>Math.abs(f.coordinate-h)<=m+Gy)?h:null}return t.every(m=>{const _=o.get(m.traceId);return _?Math.abs(m.coordinate-h)<=ad(_.pins[0],_.pins[1])+Gy:!1})?h:null},eyo=(t,e,n)=>{const o=new Set;for(const s of e)Uc(s.coordinate,n)||(o.add(s.segmentIndex),o.add(s.segmentIndex+1));const i=e[0].orientation,r=Qa(t.tracePath.map((s,a)=>o.has(a)?i==="vertical"?{...s,x:n}:{...s,y:n}:s));return{...t,tracePath:r}},zQt=(t,e)=>new Set(e.filter(n=>n.globalConnNetId===t.globalConnNetId&&jl(n.tracePath,t.anchorPoint)).map(n=>n.mspPairId)),hj=(t,e,n)=>t.every(o=>{const i=zQt(o,e);if(i.size===0)return!0;const r=zQt(o,n);return[...i].every(s=>r.has(s))}),Rg=1e-9,Ove=(t,e,n)=>{const o=Math.abs(t.x-e.x)<Rg,i=Math.abs(t.y-e.y)<Rg;return o?Math.abs(t.x-n.minX)<Rg||Math.abs(t.x-n.maxX)<Rg:i?Math.abs(t.y-n.minY)<Rg||Math.abs(t.y-n.maxY)<Rg:!1},tyo=t=>t.map(e=>`${e.x},${e.y}`).join(";"),U7=t=>{let e=0;for(let n=0;n<t.length-1;n++)e+=Math.abs(t[n+1].x-t[n].x)+Math.abs(t[n+1].y-t[n].y);return e},JQt=(t,e)=>Math.abs(t.x-e.x)+Math.abs(t.y-e.y),WQt=(t,e)=>Math.abs(t.x-e.x)<Rg||Math.abs(t.y-e.y)<Rg,jQt=(t,e)=>Math.abs(t.y-e.y)<Rg?"horizontal":"vertical",Gve=(t,e,n)=>Math.abs(e.x-n.x)<Rg?{x:e.x,y:Math.min(Math.max(t.y,Math.min(e.y,n.y)),Math.max(e.y,n.y))}:Math.abs(e.y-n.y)<Rg?{x:Math.min(Math.max(t.x,Math.min(e.x,n.x)),Math.max(e.x,n.x)),y:e.y}:e,nyo=(t,e,n)=>JQt(t,Gve(t,e,n)),oyo=t=>{const e=[];for(let n=0;n<t.length-1;n++){const o=t[n],i=t[n+1];WQt(o,i)&&e.push({start:o,end:i,orientation:jQt(o,i)})}return e},iyo=(t,e)=>{for(let n=0;n<t.length-1;n++){const o=t[n],i=t[n+1];if(WQt(o,i)&&!(nyo(e,o,i)>1e-6))return{index:n,start:o,end:i,orientation:jQt(o,i)}}return null},ryo=(t,e)=>e.orientation==="horizontal"?t.x>=Math.min(e.start.x,e.end.x)-Rg&&t.x<=Math.max(e.start.x,e.end.x)+Rg:t.y>=Math.min(e.start.y,e.end.y)-Rg&&t.y<=Math.max(e.start.y,e.end.y)+Rg,syo=(t,e,n,o,i)=>{const r=oyo(t).filter(c=>c.orientation===o);if(r.length===0)return null;const s=r.filter(c=>ryo(i,c)),a=s.length>0?s:r;return e<n/2?a[0]:a[a.length-1]},ayo=(t,e)=>{let n=null,o=Number.POSITIVE_INFINITY;for(let i=0;i<e.length-1;i++){const r=Gve(t,e[i],e[i+1]),s=JQt(t,r);s<o&&(n=r,o=s)}return n},$Qt=(t,e,n,o)=>{const i=Math.abs(t.x-e.x)<Rg,r=Math.abs(n.x-o.x)<Rg,s=(u,g,h)=>u>=Math.min(g,h)-Rg&&u<=Math.max(g,h)+Rg;if(i&&r)return Math.abs(t.x-n.x)>Rg?!1:Math.min(Math.max(t.y,e.y),Math.max(n.y,o.y))-Math.max(Math.min(t.y,e.y),Math.min(n.y,o.y))>Rg;if(!i&&!r)return Math.abs(t.y-n.y)>Rg?!1:Math.min(Math.max(t.x,e.x),Math.max(n.x,o.x))-Math.max(Math.min(t.x,e.x),Math.min(n.x,o.x))>Rg;const a=i?t:n,A=i?e:o,c=i?n:t,l=i?o:e;return s(a.x,c.x,l.x)&&s(c.y,a.y,A.y)},vle=(t,e)=>{let n=0;for(let o=0;o<t.length-1;o++)for(let i=0;i<e.length-1;i++)$Qt(t[o],t[o+1],e[i],e[i+1])&&n++;return n},qQt=(t,e)=>{for(let n=0;n<t.length-1;n++){const o=t[n],i=t[n+1];for(const r of e)if(CC(o,i,r)&&!Ove(o,i,r))return!0}return!1},Ayo=(t,e)=>{let n=0;for(const o of t)for(const i of e)o.globalConnNetId!==i.globalConnNetId&&(n+=vle(o.tracePath,i.tracePath));return n},XQt=(t,e)=>({turnCount:t.reduce((n,o)=>n+j5(o.tracePath),0),visibleLength:Y7(t),pathLength:t.reduce((n,o)=>n+U7(o.tracePath),0),otherNetCrossings:Ayo(t,e)}),cyo=(t,e)=>t.turnCount!==e.turnCount?t.turnCount<e.turnCount:Uc(t.visibleLength,e.visibleLength)?Uc(t.pathLength,e.pathLength)?t.otherNetCrossings!==e.otherNetCrossings?t.otherNetCrossings<e.otherNetCrossings:Uc(t.displacement,e.displacement)?t.coordinate<e.coordinate:t.displacement<e.displacement:t.pathLength<e.pathLength:t.visibleLength<e.visibleLength,lyo=(t,e)=>t.turnCount<=e.turnCount&&(t.turnCount<e.turnCount||t.visibleLength<=e.visibleLength+Gy),uyo=(t,e)=>t.tracePath.length!==e.tracePath.length||e.tracePath.some((n,o)=>!fb(n,t.tracePath[o])),gyo=({group:t,traces:e,netLabelPlacements:n,obstacles:o,eligibleTraceIds:i})=>{const r=new Set(t.map(d=>d.traceId)),s=e.filter(d=>r.has(d.mspPairId)),a=XQt(s,e),A=Fve(t.map(d=>d.coordinate)),c=VQt(t,n,e),l=e.filter(d=>d.globalConnNetId!==t[0].globalConnNetId),u=e.filter(d=>d.globalConnNetId===t[0].globalConnNetId&&!i.has(d.mspPairId)),g=(d,p)=>{let m=null;for(const _ of d){const f=new Map;for(const Q of s){const w=eyo(Q,t.filter(M=>M.traceId===Q.mspPairId),_);f.set(Q.mspPairId,w)}const I=[...f.values()],C=e.map(Q=>f.get(Q.mspPairId)??Q);if(!I.every(Q=>!ON(Q.tracePath,o)&&Jh({traces:[Q],netLabels:n}).length===0&&!PQt(Q.tracePath,l)&&!nw(Q.tracePath,u.filter(w=>w.mspPairId!==Q.mspPairId)))||!hj(n,e,C))continue;const x=XQt(I,C);if(x.otherNetCrossings>a.otherNetCrossings||(p?.coordinateIsFixedByLabel?x.turnCount>a.turnCount:!lyo(x,a)))continue;const E={...x,displacement:t.reduce((Q,w)=>Q+Math.abs(w.coordinate-_),0),coordinate:_},B=I.filter(Q=>{const w=e.find(M=>M.mspPairId===Q.mspPairId);return uyo(w,Q)}).map(Q=>Q.mspPairId);if(B.length===0)continue;const S={traces:C,changedTraceIds:B,score:E};(!m||cyo(S.score,m.score))&&(m=S)}return m},h=g(c===null?A:[c],{coordinateIsFixedByLabel:c!==null});return h||(c!==null?null:g(JCo({group:t,originalCoordinates:A,otherNetTraces:l})))},dyo=t=>{const e=[],n=t.tracePath;for(let o=1;o<n.length-2;o++){const i=n[o-1],r=n[o],s=n[o+1],a=n[o+2],A=JH(r,s);if(!A)continue;const c=JH(i,r),l=JH(s,a);if(!c||!l||c===A||l===A)continue;const u=A==="vertical"?[r.y,s.y]:[r.x,s.x];e.push({traceId:t.mspPairId,segmentIndex:o,globalConnNetId:t.globalConnNetId,orientation:A,coordinate:A==="vertical"?r.x:r.y,minAlong:Math.min(...u),maxAlong:Math.max(...u)})}return e},hyo=(t,e,n)=>{const o=e.center.x-e.width/2,i=e.center.x+e.width/2,r=e.center.y-e.height/2,s=e.center.y+e.height/2;switch(n){case"x-":return t.orientation==="vertical"&&t.coordinate<=o+Gy;case"x+":return t.orientation==="vertical"&&t.coordinate>=i-Gy;case"y+":return t.orientation==="horizontal"&&t.coordinate>=s-Gy;case"y-":return t.orientation==="horizontal"&&t.coordinate<=r+Gy}},ZQt=(t,e,n)=>{const o=[],i=ad(t.pins[0],t.pins[1])<=(n?.maxMspPairDistance??uj);for(const r of dyo(t)){const s=t.pins.flatMap((c,l)=>{const u=e.get(c.chipId);if(!u)return[];const g=c._facingDirection??W5(c,u);return hyo(r,u,g)?[{componentId:u.chipId,componentFacingDirection:g,distanceFromEndpoint:l===0?r.segmentIndex:t.tracePath.length-2-r.segmentIndex}]:[]});s.sort((c,l)=>c.distanceFromEndpoint-l.distanceFromEndpoint);const a=s[0]?.distanceFromEndpoint,A=new Set;for(const c of s){if(A.size>0&&(!n?.includeTiedEndpointAssociations||!i))break;if(c.distanceFromEndpoint!==a)continue;const l=`${c.componentId}:${c.componentFacingDirection}`;A.has(l)||(A.add(l),o.push({...r,...c}))}}return o},pyo=(t,e)=>{const n=Math.max(t.minAlong,e.minAlong),o=Math.min(t.maxAlong,e.maxAlong),i=(n+o)/2;return t.orientation==="vertical"?[{x:t.coordinate,y:i},{x:e.coordinate,y:i}]:[{x:i,y:t.coordinate},{x:i,y:e.coordinate}]},myo=(t,e,n)=>{if(!FQt(t,e))return!0;const[o,i]=pyo(t,e);return!n.some(r=>CC(o,i,r))},_yo=(t,e,n)=>{if(t.traceId===e.traceId)return!0;const o=new Set(n.get(t.traceId).pins.map(i=>i.pinId));return n.get(e.traceId).pins.some(i=>o.has(i.pinId))},fyo=(t,e,n,o,i)=>n.globalConnNetId===t.globalConnNetId&&n.orientation===t.orientation&&n.componentId===t.componentId&&n.componentFacingDirection===t.componentFacingDirection&&(FQt(e,n)||_yo(e,n,o))&&myo(e,n,i),Iyo=(t,e,n,o,i)=>{const r=new Map(n.chips.map(p=>[p.chipId,p])),s=new Map(t.map(p=>[p.mspPairId,p])),a=t.filter(p=>e.has(p.mspPairId)),A=p=>{const m=new Set,_=[];for(let f=0;f<p.length;f++){if(m.has(f))continue;const I=p[f],C=[f],y=[];m.add(f);for(let x=0;x<C.length;x++){const E=p[C[x]];y.push(E);for(let B=0;B<p.length;B++){if(m.has(B))continue;const S=p[B];fyo(I,E,S,s,o)&&(m.add(B),C.push(B))}}_.push(y)}return _},c=p=>[p[0].componentId,p[0].componentFacingDirection,p[0].orientation,...p.map(m=>`${m.traceId}:${m.segmentIndex}`).sort()].join("|"),l=[],u=new Set,g=(p,m)=>{if(new Set(p.map(x=>x.traceId)).size<2)return;const f=VQt(p,i,t);if(m?.requireFixedLabel&&f===null)return;const I=p.some(x=>!Uc(x.coordinate,p[0].coordinate)),C=f!==null&&!Uc(f,p[0].coordinate);if(!I&&!C)return;const y=c(p);u.has(y)||(u.add(y),l.push(p))},h=a.flatMap(p=>ZQt(p,r));for(const p of A(h))g(p);const d=a.flatMap(p=>ZQt(p,r,{includeTiedEndpointAssociations:!0,maxMspPairDistance:n.maxMspPairDistance}));for(const p of A(d))g(p,{requireFixedLabel:!0});return l},evt=t=>JSON.stringify(t.map(e=>({mspPairId:e.mspPairId,tracePath:e.tracePath}))),Cyo=({inputProblem:t,traces:e,netLabelPlacements:n,eligibleTraceIds:o})=>{let i=[...e];const r=new Set([evt(i)]),s=Hy(t),a=new Set;let A=0;const c=Math.max(1,e.reduce((l,u)=>l+u.tracePath.length,0));for(let l=0;l<c;l++){const u=Iyo(i,o,t,s,n);let g=null;for(const p of u)if(g=gyo({group:p,traces:i,netLabelPlacements:n,obstacles:s,eligibleTraceIds:o}),g)break;if(!g)break;const h=evt(g.traces),d=r.has(h);d||r.add(h),i=g.traces,A++;for(const p of g.changedTraceIds)a.add(p);if(d)break}return{traces:i,alignedRailGroupCount:A,alignedTraceCount:a.size}},yyo=t=>{const e=[];if(t.length<3)return e;for(let n=0;n<t.length-2;n++){const o=t[n],i=t[n+1],r=t[n+2],s=i.x-o.x,a=i.y-o.y,A=r.x-i.x,c=r.y-i.y;(s===0&&c===0&&a!==0&&A!==0||a===0&&A===0&&s!==0&&c!==0)&&s*s+a*a>=.25&&A*A+c*c>=.25&&e.push({p1:o,p2:i,p3:r})}return e},xyo=(t,e)=>{const n=[];for(const o of t)o.mspPairId!==e&&n.push({points:o.tracePath});return n},wle=1e-6,tvt=(t,e,n)=>{const o=[];for(const i of n){const r=i.points;for(let s=0;s<r.length-1;s++){const a=r[s],A=r[s+1];if(!a||!A)continue;const c=V4(t,e,a,A);c&&o.push(c)}}return o},Eyo=(t,e)=>Math.abs(t.x-e.x)<wle&&Math.abs(t.y-e.y)<wle,WH=(t,e,n={})=>{const o=[],i=n.includeTerminalSegments?0:1,r=n.includeTerminalSegments?t.length-1:t.length-2,s=n.includeTerminalSegments?0:1,a=n.includeTerminalSegments?e.length-1:e.length-2;for(let A=i;A<r;A++){const c=t[A],l=t[A+1],u=Math.abs(c.x-l.x)<wle;for(let g=s;g<a;g++){const h=e[g],d=e[g+1],p=Math.abs(h.x-d.x)<wle;if(u===p)continue;const m=V4(c,l,h,d);!m||[c,l,h,d].some(_=>Eyo(_,m))||o.push({pathSegmentIndex:A,otherPathSegmentIndex:g})}}return o},K7=1e-6,ow=(t,e,n=K7)=>Math.abs(t.x-e.x)<n,Byo=({lShape:t,rectangle:e,padding:n=.5,interactionPoint1:o,interactionPoint2:i})=>{const{p1:r,p2:s,p3:a}=t,{x:A,y:c,width:l,height:u}=e;let g,h=o,d=i;if(Math.abs(s.x-A)<K7&&Math.abs(s.y-(c+u))<K7)g={x:A+l+n,y:c-n},ow(r,s)?h={x:o.x,y:o.y-n}:h={x:o.x+n,y:o.y},ow(s,a)?d={x:i.x,y:i.y-n}:d={x:i.x+n,y:i.y};else if(Math.abs(s.x-(A+l))<K7&&Math.abs(s.y-(c+u))<K7)g={x:A-n,y:c-n},ow(r,s)?h={x:o.x,y:o.y-n}:h={x:o.x-n,y:o.y},ow(s,a)?d={x:i.x,y:i.y-n}:d={x:i.x-n,y:i.y};else if(Math.abs(s.x-A)<K7&&Math.abs(s.y-c)<K7)g={x:A+l+n,y:c+u+n},ow(r,s)?h={x:o.x,y:o.y+n}:h={x:o.x+n,y:o.y},ow(s,a)?d={x:i.x,y:i.y+n}:d={x:i.x+n,y:i.y};else if(Math.abs(s.x-(A+l))<K7&&Math.abs(s.y-c)<K7)g={x:A-n,y:c+u+n},ow(r,s)?h={x:o.x,y:o.y+n}:h={x:o.x-n,y:o.y},ow(s,a)?d={x:i.x,y:i.y+n}:d={x:i.x-n,y:i.y};else return[];return[[h,g,d]]},nvt=({trace:t,chipBounds:e,clearance:n})=>{if(t.tracePath.length<4||e.length===0)return[];const o=t.tracePath[0],i=t.tracePath[1],r=t.tracePath.at(-2),s=t.tracePath.at(-1),a=Math.min(...e.map(g=>g.minX))-n,A=Math.max(...e.map(g=>g.maxX))+n,c=Math.min(...e.map(g=>g.minY))-n,l=Math.max(...e.map(g=>g.maxY))+n,u=[];for(const g of[a,A])for(const h of[c,l])u.push({traceId:t.mspPairId,path:Qa([o,i,{x:i.x,y:h},{x:g,y:h},{x:g,y:r.y},r,s])}),u.push({traceId:t.mspPairId,path:Qa([o,i,{x:g,y:i.y},{x:g,y:h},{x:r.x,y:h},r,s])});return u},Yve=({trace:t,segmentIndex:e,obstacleStart:n,obstacleEnd:o,obstacleBounds:i,chipBounds:r,clearance:s})=>{const a=(l,u)=>{const g=l[u],h=l[u+1],d=Math.abs(g.x-h.x)<K7?"y":"x",p=d==="x"?"y":"x",m=i??{minX:Math.min(n.x,o.x),minY:Math.min(n.y,o.y),maxX:Math.max(n.x,o.x),maxY:Math.max(n.y,o.y)},_=d==="x"?"minX":"minY",f=d==="x"?"maxX":"maxY";let I=n[d]+Math.sign(g[d]-n[d])*s;if(i){const M=g[d]<(m[_]+m[f])/2?-1:1;I=m[M<0?_:f]+M*s}const C=p==="x"?"minX":"minY",y=p==="x"?"maxX":"maxY",x=m[C]-s,E=m[y]+s,B=i?l[u+2]:void 0,Q=[B?B[p]<x?(B[p]+x)/2:B[p]>E?(B[p]+E)/2:void 0:void 0,x,E,...r.flatMap(M=>[M[C]-s,M[y]+s])].filter(M=>M!==void 0),w=l.slice(u+2);return w.length===0&&w.push(h),[...new Set(Q)].map(M=>Qa([...l.slice(0,u+1),{...g,[d]:I},{...g,[d]:I,[p]:M},{...h,[p]:M},...w]))},A=[...t.tracePath].reverse(),c=t.tracePath.length-2-e;return[...a(t.tracePath,e),...a(A,c).map(l=>l.reverse())].map(l=>({traceId:t.mspPairId,path:l}))},Ple=(t,e,n)=>{if(t.length<2)return{isColliding:!1};for(let o=0;o<t.length-1;o++){const i=t[o],r=t[o+1];for(const s of e)if(s.mspPairId!==n)for(let a=0;a<s.tracePath.length-1;a++){const A=s.tracePath[a],c=s.tracePath[a+1],l=V4(i,r,A,c);if(l)return{isColliding:!0,collidingTraceId:s.mspPairId,collisionPoint:l}}}return{isColliding:!1}},byo=(t,e)=>{const n=[];for(const o of t)for(const i of e){const r=Math.min(o.x,i.x),s=Math.min(o.y,i.y),a=Math.max(o.x,i.x),A=Math.max(o.y,i.y),c=a-r,l=A-s;c>1e-6&&l>1e-6&&n.push({rect:{x:r,y:s,width:c,height:l},i1:o,i2:i})}return n},Mle=t=>{const e={circles:[],lines:[]},n=Array.isArray(t)?t:[t];for(const o of n)e.circles.push({center:{x:o.p2.x,y:o.p2.y},radius:.01,fill:"blue"}),e.lines.push({points:[o.p1,o.p2,o.p3],strokeColor:"lightblue"});return e},ovt=(t,e="red")=>{const n={circles:[]};for(const o of t)n.circles.push({center:{x:o.x,y:o.y},radius:.01,fill:e});return n},ivt=t=>{const e={rects:[]};return e.rects.push({center:{x:t.x+t.width/2,y:t.y+t.height/2},width:t.width,height:t.height,stroke:"green"}),e},Syo=(t,e="gray",n=[])=>{const o={lines:[],circles:[]};for(const i of t)o.lines.push({points:i,strokeColor:e});for(const i of n)o.circles.push({center:i,radius:.01,fill:"green"});return o},Uve=t=>{const e={lines:[],points:[],rects:[],circles:[],texts:[]};for(const n of t)n&&(n.lines&&e.lines.push(...n.lines),n.points&&e.points.push(...n.points),n.rects&&e.rects.push(...n.rects),n.circles&&e.circles.push(...n.circles),n.texts&&e.texts.push(...n.texts));return e},Qyo=t=>{const e={circles:[]};return t?.isColliding&&t.collisionPoint&&e.circles.push({center:t.collisionPoint,radius:.01,fill:"red"}),e},vyo=class extends Ng{input;chipObstacleSpatialIndex;lShapesToProcess=[];ignoredCrossings=new Set;reroutedTraceIds=new Set;processingCrossings=!0;visualizationMode="l_shapes";currentLShape=null;intersectionPoints=[];tightRectangle=null;candidates=[];bestRoute=null;lastCollision=null;collidingCandidate=null;rectangleCandidates=[];currentRectangleIndex=0;isInitialStep=!0;currentCandidateIndex=0;lShapeProcessingStep="idle";lShapeJustProcessed=!1;bestRouteFound=null;constructor(t){super(),this.input=t,this.visualizationMode="l_shapes",this.chipObstacleSpatialIndex=this.input.inputProblem._chipObstacleSpatialIndex??new yle(this.input.inputProblem.chips),this.input.inputProblem._chipObstacleSpatialIndex||(this.input.inputProblem._chipObstacleSpatialIndex=this.chipObstacleSpatialIndex)}_step(){if(this.isInitialStep){this.isInitialStep=!1;return}if(this.processingCrossings){const t=this._findCrossing();if(t){this._resolveCrossing(t)||this.ignoredCrossings.add(this._crossingKey(t));return}this.processingCrossings=!1,this._initializeLShapes();return}if(this.lShapeJustProcessed){this._resetAfterLShapProcessing();return}if(this.lShapesToProcess.length===0&&this.currentLShape===null){this.solved=!0;return}switch(this.lShapeProcessingStep){case"idle":this._handleIdleStep();break;case"intersections":this._handleIntersectionsStep();break;case"rectangle_selection":this._handleRectangleSelectionStep();break;case"candidate_evaluation":this._handleCandidateEvaluationStep();break}}_initializeLShapes(){for(const t of this.input.allTraces)this.lShapesToProcess.push(...yyo(t.tracePath).map(e=>({...e,traceId:t.mspPairId})))}_crossingKey(t){return`${t.trace.mspPairId}:${t.segmentIndex}:${t.otherTrace.mspPairId}:${t.otherSegmentIndex}`}_isTraceBundle(t,e){const n=o=>o.pins.map(i=>i.chipId).sort().join(":");return n(t)!==n(e)?!1:Object.values(this.input.mergedLabelNetIdMap).some(o=>o.has(t.globalConnNetId)&&o.has(e.globalConnNetId))}_findCrossing(){const t=this.input.allTraces;for(let e=0;e<t.length;e++){const n=t[e];for(let o=e+1;o<t.length;o++){const i=t[o];if(n.globalConnNetId===i.globalConnNetId)continue;const r=this._isTraceBundle(n,i),s=this.input.eligibleTraceIds?.has(n.mspPairId)===!0||this.input.eligibleTraceIds?.has(i.mspPairId)===!0;if(!r&&!s&&!this.reroutedTraceIds.has(n.mspPairId)&&!this.reroutedTraceIds.has(i.mspPairId))continue;const a=WH(n.tracePath,i.tracePath);for(const{pathSegmentIndex:A,otherPathSegmentIndex:c}of a){const l={trace:n,segmentIndex:A,otherTrace:i,otherSegmentIndex:c,isInitialBundleCrossing:r};if(!this.ignoredCrossings.has(this._crossingKey(l)))return l}}}return null}_resolveCrossing(t){const e=this.chipObstacleSpatialIndex.chips.map(a=>a.bounds),n=[...Yve({trace:t.trace,segmentIndex:t.segmentIndex,obstacleStart:t.otherTrace.tracePath[t.otherSegmentIndex],obstacleEnd:t.otherTrace.tracePath[t.otherSegmentIndex+1],chipBounds:e,clearance:this.input.paddingBuffer}),...Yve({trace:t.otherTrace,segmentIndex:t.otherSegmentIndex,obstacleStart:t.trace.tracePath[t.segmentIndex],obstacleEnd:t.trace.tracePath[t.segmentIndex+1],chipBounds:e,clearance:this.input.paddingBuffer}),...nvt({trace:t.trace,chipBounds:e,clearance:this.input.paddingBuffer}),...nvt({trace:t.otherTrace,chipBounds:e,clearance:this.input.paddingBuffer})],o=Hy(this.input.inputProblem).filter(a=>a.kind==="chip"),r=n.map(a=>({...a,collision:Ple(a.path,this.input.allTraces,a.traceId)})).filter(a=>!qQt(a.path,o)&&!Ple(a.path,[t.trace,t.otherTrace],a.traceId).isColliding&&(t.isInitialBundleCrossing||!a.collision.isColliding)).sort((a,A)=>Number(a.collision.isColliding)-Number(A.collision.isColliding)||U7(a.path)-U7(A.path))[0];if(!r)return!1;const s=this.input.allTraces.findIndex(a=>a.mspPairId===r.traceId);return this.input.allTraces[s]={...this.input.allTraces[s],tracePath:r.path},this.reroutedTraceIds.add(r.traceId),!0}_resetAfterLShapProcessing(){this.lShapeProcessingStep="idle",this.currentLShape=null,this.currentCandidateIndex=0,this.lShapeJustProcessed=!1,this.visualizationMode="l_shapes",this.intersectionPoints=[],this.tightRectangle=null,this.candidates=[],this.bestRoute=null,this.lastCollision=null,this.collidingCandidate=null}_handleIdleStep(){if(this.currentLShape=this.lShapesToProcess.shift(),!this.currentLShape){this.solved=!0;return}this.lShapeProcessingStep="intersections",this.visualizationMode="l_shapes"}_handleIntersectionsStep(){if(!this.currentLShape.traceId){this.lShapeProcessingStep="idle";return}const t=xyo(this.input.allTraces,this.currentLShape.traceId),e=tvt(this.currentLShape.p1,this.currentLShape.p2,t),n=tvt(this.currentLShape.p2,this.currentLShape.p3,t);if(this.intersectionPoints=[...e,...n],e.length===0||n.length===0){this.lShapeProcessingStep="idle";return}this.rectangleCandidates=byo(e,n),this.currentRectangleIndex=0,this.lShapeProcessingStep="rectangle_selection"}_handleRectangleSelectionStep(){if(this.currentRectangleIndex>=this.rectangleCandidates.length){this.lShapeProcessingStep="idle";return}const{rect:t,i1:e,i2:n}=this.rectangleCandidates[this.currentRectangleIndex];this.tightRectangle=t,this.candidates=Byo({lShape:this.currentLShape,rectangle:this.tightRectangle,padding:2*this.input.paddingBuffer,interactionPoint1:e,interactionPoint2:n}),this.currentCandidateIndex=0,this.lastCollision=null,this.collidingCandidate=null,this.visualizationMode="candidates",this.lShapeProcessingStep="candidate_evaluation"}_handleCandidateEvaluationStep(){if(this.visualizationMode="candidates",this.bestRouteFound){this._applyBestRoute(this.bestRouteFound),this.bestRouteFound=null;return}if(this.currentCandidateIndex>=this.candidates.length){this.currentRectangleIndex++,this.lShapeProcessingStep="rectangle_selection";return}const t=this.candidates[this.currentCandidateIndex],e=Ple(t,this.input.allTraces,this.currentLShape.traceId);if(!e?.isColliding&&this._doesCandidateCrossChip(t)){this.lastCollision=null,this.collidingCandidate=t,this.currentCandidateIndex++;return}e?.isColliding?(this.lastCollision=e,this.collidingCandidate=t,this.currentCandidateIndex++):(this.bestRouteFound=t,this.lastCollision=null,this.collidingCandidate=null)}_doesCandidateCrossChip(t){for(let e=0;e<t.length-1;e++)if(this.chipObstacleSpatialIndex.doesOrthogonalLineIntersectChip([t[e],t[e+1]]))return!0;return!1}_applyBestRoute(t){this.bestRoute=t,this.collidingCandidate=null,this.lastCollision=null;const e=this.input.allTraces.findIndex(n=>n.mspPairId===this.currentLShape.traceId);if(e!==-1){const n=this.input.allTraces[e],o=n.tracePath.findIndex(i=>i.x===this.currentLShape.p2.x&&i.y===this.currentLShape.p2.y);if(o!==-1){const i=[...n.tracePath.slice(0,o),...t,...n.tracePath.slice(o+1)];this.input.allTraces[e]={...n,tracePath:i},this.lShapesToProcess=this.lShapesToProcess.filter(r=>r.traceId!==this.currentLShape.traceId)}}this.lShapeJustProcessed=!0}getOutput(){return{traces:this.input.allTraces}}visualize(){switch(this.visualizationMode){case"l_shapes":return Mle(this.lShapesToProcess);case"intersection_points":return Uve([this.currentLShape?Mle(this.currentLShape):void 0,ovt(this.intersectionPoints)]);case"tight_rectangle":return Uve([this.currentLShape?Mle(this.currentLShape):void 0,ovt(this.intersectionPoints),this.tightRectangle?ivt(this.tightRectangle):void 0]);case"candidates":{if(this.lShapeJustProcessed){const n={lines:[]};for(const o of this.input.allTraces){const i=o.mspPairId===this.currentLShape?.traceId;for(let r=0;r<o.tracePath.length-1;r++)n.lines.push({points:[o.tracePath[r],o.tracePath[r+1]],strokeColor:i?"green":"#ccc"})}return n}const t={lines:[]};for(const n of this.input.allTraces)for(let o=0;o<n.tracePath.length-1;o++)t.lines.push({points:[n.tracePath[o],n.tracePath[o+1]],strokeColor:"#ccc"});let e;return this.bestRouteFound?e=this.bestRouteFound:this.lastCollision?.isColliding?e=this.collidingCandidate??void 0:this.currentCandidateIndex<this.candidates.length&&(e=this.candidates[this.currentCandidateIndex]),Uve([t,this.currentLShape?Mle(this.currentLShape):void 0,this.tightRectangle?ivt(this.tightRectangle):void 0,e?Syo([e],this.bestRouteFound?"green":"blue",this.intersectionPoints):void 0,this.lastCollision?Qyo(this.lastCollision):void 0])}default:return{}}}},rvt=1e-6,Dle=(t,e)=>Math.abs(t.x-e.x)<=rvt,Nle=(t,e)=>Math.abs(t.y-e.y)<=rvt,wyo=t=>{if(t.length!==4)return!1;const[e,n,o,i]=t,r=Nle(e,n)&&Dle(n,o)&&Nle(o,i)&&Dle(e,i),s=Dle(e,n)&&Nle(n,o)&&Dle(o,i)&&Nle(e,i);return r||s},svt=1e-6,Pyo=(t,e,n)=>{const o=t.tracePath[e],i=t.tracePath[e+1],r={minX:Math.min(o.x,i.x),minY:Math.min(o.y,i.y),maxX:Math.max(o.x,i.x),maxY:Math.max(o.y,i.y)};for(const s of n){if(s.globalConnNetId!==t.globalConnNetId||!s.pinIds.every(A=>t.pinIds.includes(A))||!jl(t.tracePath,s.anchorPoint))continue;const a=Ls(s.center,s.width,s.height);r.minX=Math.min(r.minX,a.minX),r.minY=Math.min(r.minY,a.minY),r.maxX=Math.max(r.maxX,a.maxX),r.maxY=Math.max(r.maxY,a.maxY)}return r},Myo=(t,e,n)=>{const o=[];for(const i of t)if(e.has(i.mspPairId))for(let r=0;r<t.length;r++){const s=t[r];if(s.mspPairId!==i.mspPairId&&!e.has(s.mspPairId)&&s.globalConnNetId!==i.globalConnNetId&&!(n&&!n.has(s.mspPairId)))for(const a of WH(s.tracePath,i.tracePath,{includeTerminalSegments:!0}))o.push({traceIndex:r,connector:i,connectorSegmentIndex:a.otherPathSegmentIndex,traceSegmentIndex:a.pathSegmentIndex})}return o},Dyo=({inputProblem:t,traces:e,netLabelPlacements:n,mergedLabelNetIdMap:o,clearance:i,eligibleTraceIds:r,connectorTraceIds:s})=>{const a=[...e],A=Hy(t).filter(l=>l.kind==="chip"||l.kind==="text_box");let c=0;for(;;){const l=Myo(a,s,r).flatMap(g=>{const h=a[g.traceIndex],d=Pyo(g.connector,g.connectorSegmentIndex,n),p=a.filter(_=>_.mspPairId!==h.mspPairId&&_.globalConnNetId!==h.globalConnNetId),m=n.filter(_=>{const f=o[_.globalConnNetId];return f?!f.has(h.globalConnNetId):_.globalConnNetId!==h.globalConnNetId}).map(_=>Ls(_.center,_.width,_.height));return Yve({trace:h,segmentIndex:g.traceSegmentIndex,obstacleStart:g.connector.tracePath[g.connectorSegmentIndex],obstacleEnd:g.connector.tracePath[g.connectorSegmentIndex+1],obstacleBounds:d,chipBounds:[],clearance:i}).filter(_=>U7(_.path)<=U7(h.tracePath)+svt&&j5(_.path)<=j5(h.tracePath)+2&&!ON(_.path,A)&&!Sle(_.path,m)&&!Ple(_.path,p,h.mspPairId).isColliding&&!nw(_.path,p)).map(_=>({..._,traceIndex:g.traceIndex}))});l.sort((g,h)=>{const d=U7(g.path)-U7(h.path);return Math.abs(d)>svt?d:j5(g.path)-j5(h.path)});const u=l[0];if(!u)break;a[u.traceIndex]={...a[u.traceIndex],tracePath:u.path},c++}return{traces:a,reroutedTraceCount:c}},Nyo=["untangling_traces","minimizing_turns","balancing_l_shapes"],avt=class extends Ng{input;outputTraces;traceIdQueue;tracesMap;operations;operationIndex=0;pipelineStep;activeTraceId=null;activeSubSolver=null;constructor(t){super(),this.input=t,this.outputTraces=[...t.allTraces],this.tracesMap=new Map(this.outputTraces.map(e=>[e.mspPairId,e])),this.operations=t.operations??Nyo,this.pipelineStep=this.operations[0]??null,this.traceIdQueue=Array.from(t.allTraces.map(e=>e.mspPairId))}_step(){if(this.activeSubSolver){if(this.activeSubSolver.step(),this.activeSubSolver.solved){const t=this.activeSubSolver.getOutput();this.outputTraces=t.traces,this.tracesMap=new Map(this.outputTraces.map(e=>[e.mspPairId,e])),this.activeSubSolver=null,this._advancePipeline()}else this.activeSubSolver.failed&&(this.activeSubSolver=null,this._advancePipeline());return}if(!this.pipelineStep){this.solved=!0;return}switch(this.pipelineStep){case"untangling_traces":this._runUntangleTracesStep();break;case"rerouting_generated_net_label_connector_crossings":this._runGeneratedNetLabelConnectorCrossingRerouteStep();break;case"minimizing_turns":this._runMinimizeTurnsStep();break;case"balancing_l_shapes":this._runBalanceLShapesStep();break;case"aligning_same_net_rails":this._runAlignSameNetRailsStep();break}}_advancePipeline(){this.operationIndex++,this.pipelineStep=this.operations[this.operationIndex]??null,this.traceIdQueue=this.outputTraces.map(t=>t.mspPairId),this.pipelineStep&&(this.activeTraceId=null)}_runUntangleTracesStep(){this.activeSubSolver=new vyo({...this.input,allTraces:Array.from(this.tracesMap.values())})}_runGeneratedNetLabelConnectorCrossingRerouteStep(){const t=Dyo({inputProblem:this.input.inputProblem,traces:this.outputTraces,netLabelPlacements:this.input.allLabelPlacements,mergedLabelNetIdMap:this.input.mergedLabelNetIdMap,clearance:this.input.paddingBuffer,eligibleTraceIds:this.input.eligibleTraceIds,connectorTraceIds:this.input.netLabelConnectorTraceIds??new Set});this.outputTraces=t.traces,this.tracesMap=new Map(this.outputTraces.map(e=>[e.mspPairId,e])),this.stats.reroutedGeneratedConnectorCrossingTraceCount=t.reroutedTraceCount,this._advancePipeline()}_runMinimizeTurnsStep(){if(this.traceIdQueue.length===0){this._advancePipeline();return}this._processTrace("minimizing_turns")}_runBalanceLShapesStep(){if(this.traceIdQueue.length===0){this._advancePipeline();return}this._processTrace("balancing_l_shapes")}_processTrace(t){const e=this.traceIdQueue.shift();this.activeTraceId=e;const n=this.tracesMap.get(e);if(wyo(n.tracePath))return;const o=Array.from(this.tracesMap.values());let i;t==="minimizing_turns"?i=YQt({...this.input,targetMspConnectionPairId:e,traces:o}):i=VCo({...this.input,targetMspConnectionPairId:e,traces:o}),this.tracesMap.set(e,i),this.outputTraces=Array.from(this.tracesMap.values())}_runAlignSameNetRailsStep(){const t=Cyo({inputProblem:this.input.inputProblem,traces:this.outputTraces,netLabelPlacements:this.input.allLabelPlacements,eligibleTraceIds:this.input.eligibleTraceIds??new Set(this.outputTraces.map(e=>e.mspPairId))});this.outputTraces=t.traces,this.tracesMap=new Map(this.outputTraces.map(e=>[e.mspPairId,e])),this.stats.alignedRailGroupCount=t.alignedRailGroupCount,this.stats.alignedTraceCount=t.alignedTraceCount,this._advancePipeline()}getOutput(){return{traces:this.outputTraces}}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();const t=zh(this.input.inputProblem,{chipAlpha:.1,connectionAlpha:.1});t.lines||(t.lines=[]),t.points||(t.points=[]),t.rects||(t.rects=[]),t.circles||(t.circles=[]),t.texts||(t.texts=[]);for(const e of this.outputTraces){const n={points:e.tracePath.map(o=>({x:o.x,y:o.y})),strokeColor:e.mspPairId===this.activeTraceId?"red":"blue"};t.lines.push(n)}return t}},Ryo=({tracePath:t,sourcePoint:e,extensionEndPoint:n})=>{const o=t.findIndex(s=>fb(s,e));if(o<=0||o>=t.length-1)return null;const i=n.y-e.y,r=[o-1,o+1].find(s=>{const a=t[s];return Yy(a,e)&&(a.y-e.y)*i<0});return r===void 0?null:t.toSpliced(Math.max(o,r),0,n)},Kve=t=>{const e={};for(const n of t.chips)for(const o of n.pins)e[o.pinId]={...o,chipId:n.chipId};return e},Vve=(t,e)=>{const n=t.pinIds.flatMap(i=>{const r=e[i];return r?[r]:[]});if(n.length>=2)return[n[0],n[1]];if(n.length===1)return[n[0],n[0]];const o={pinId:`${t.globalConnNetId}-netlabel-anchor`,x:t.anchorPoint.x,y:t.anchorPoint.y,chipId:"available-net-orientation"};return[o,o]},Tyo=t=>({orientation:t.orientation,anchorPoint:t.anchorPoint,center:t.center,width:t.width,height:t.height}),sm=t=>{switch(t){case"x+":return{x:1,y:0};case"x-":return{x:-1,y:0};case"y+":return{x:0,y:1};case"y-":return{x:0,y:-1}}throw new Error(`Invalid facing direction: ${t}`)},zve=(t,e,n)=>{const o=iyo(e,t);if(!o)return null;const i=syo(n,o.index,e.length-1,o.orientation,t);return i?Gve(t,i.start,i.end):ayo(t,n)},Avt=(t,e)=>t.globalConnNetId===e.globalConnNetId||t.mspConnectionPairIds.includes(e.mspPairId),jH=({trace:t,originalTracePath:e,reroutedTracePath:n,netLabelPlacements:o})=>o.map(i=>{if(!Avt(i,t))return i;const r=zve(i.anchorPoint,e,n);if(!r)return i;const s={x:r.x-i.anchorPoint.x,y:r.y-i.anchorPoint.y};return{...i,anchorPoint:r,center:{x:i.center.x+s.x,y:i.center.y+s.y}}}),kyo=({originalTraces:t,reroutedTraces:e,netLabelPlacements:n})=>{const o=[...e],i=new Map(e.map(s=>[s.mspPairId,s])),r=n.map(s=>{const a=t.find(p=>{if(!s.mspConnectionPairIds.includes(p.mspPairId))return!1;const m=i.get(p.mspPairId);return m?m.tracePath!==p.tracePath:!1});if(!a)return s;const A=i.get(a.mspPairId),c=t.findIndex(p=>p.mspPairId===a.mspPairId||p.globalConnNetId!==s.globalConnNetId||!jl(p.tracePath,s.anchorPoint)?!1:s.pinIds.every(m=>p.pinIds.includes(m)));if(c<0)return s;const l=t[c],u=l.tracePath.find(p=>jl(a.tracePath,p));if(!u)return s;const g=zve(u,a.tracePath,A.tracePath);if(!g)return s;const h={x:g.x-u.x,y:g.y-u.y},d={...l,tracePath:l.tracePath.map(p=>({x:p.x+h.x,y:p.y+h.y}))};return o[c]=d,jH({trace:l,originalTracePath:l.tracePath,reroutedTracePath:d.tracePath,netLabelPlacements:[s]})[0]});return{traces:o,netLabelPlacements:r}},Fyo=(t,e)=>{for(let n=0;n<t.length-1;n++){const o=t[n],i=t[n+1];for(const r of e)if(Ove(o,i,r)&&cvt(o,i,r)>Rg)return!0}return!1},Lyo=(t,e)=>{let n=0;for(let o=0;o<t.length-1;o++){const i=t[o],r=t[o+1];for(const s of e){if(!Ove(i,r,s))continue;const a=cvt(i,r,s);a>Rg&&(n+=a)}}return n},cvt=(t,e,n)=>Math.abs(t.x-e.x)<Rg?Math.min(Math.max(t.y,e.y),n.maxY)-Math.max(Math.min(t.y,e.y),n.minY):Math.min(Math.max(t.x,e.x),n.maxX)-Math.max(Math.min(t.x,e.x),n.minX),nE=.1,Hyo=16,Oyo=({x:t,lowY:e,highY:n,outputTraces:o,netId:i})=>{for(const r of o){if(r.globalConnNetId===i)continue;const s=r.tracePath;for(let a=0;a+1<s.length;a++){const A=s[a],c=s[a+1];if(Math.abs(A.x-c.x)>=1e-9||Math.abs(A.x-t)>=nE/2)continue;const l=Math.min(A.y,c.y),u=Math.max(A.y,c.y);if(Math.min(n,u)-Math.max(e,l)>1e-6)return!0}}return!1},Gyo=({trace:t,obstacleLabel:e,inputProblem:n,outputTraces:o,outputNetLabelPlacements:i,chipObstacles:r})=>{const s=Yyo({trace:t,label:e,inputProblem:n,outputTraces:o,outputNetLabelPlacements:i,chipObstacles:r}),a=Vyo({trace:t,obstacleLabel:e,outputTraces:o,outputNetLabelPlacements:i,candidateResults:s,chipObstacles:r});return Jyo(s,a),{bestPath:a,candidateResults:s}},Yyo=({trace:t,label:e,inputProblem:n,outputTraces:o,outputNetLabelPlacements:i,chipObstacles:r})=>{const s=new Set,a=[],A=zyo({trace:t,label:e,outputTraces:o});A&&a.push(lvt({trace:t,obstacleLabel:e,path:A,seen:s,outputTraces:o,outputNetLabelPlacements:i,chipObstacles:r,usesHorizontalSegmentPush:!0}));const c=[...Kyo(t,e),...SQt({trace:t,label:e,paddingBuffer:nE,detourCount:0}),...Uyo(t,e)];for(const l of c)a.push(lvt({trace:t,obstacleLabel:e,path:Qa(l),seen:s,outputTraces:o,outputNetLabelPlacements:i,chipObstacles:r}));return a},lvt=({trace:t,obstacleLabel:e,path:n,seen:o,outputTraces:i,outputNetLabelPlacements:r,chipObstacles:s,usesHorizontalSegmentPush:a})=>{const A=tyo(n);return o.has(A)?{path:n,status:"duplicate",usesHorizontalSegmentPush:a,selected:!1}:(o.add(A),qQt(n,s)?{path:n,status:"chip-collision",usesHorizontalSegmentPush:a,selected:!1}:{path:n,score:gvt({trace:t,tracePath:n,obstacleLabel:e,outputTraces:i,outputNetLabelPlacements:r,chipObstacles:s}),status:"valid",usesHorizontalSegmentPush:a,selected:!1})},Uyo=(t,e)=>{const n=t.tracePath[0],o=t.tracePath[t.tracePath.length-1];if(!n||!o)return[];const i=t.tracePath[1]??n,r=t.tracePath[t.tracePath.length-2]??o,s=Ls(e.center,e.width,e.height),a=nE,A=sm(e.orientation),c=A.x<0?s.minX-a:s.maxX+a,l=A.x<0?s.maxX+a:s.minX-a,u=s.maxY+a,g=s.minY-a,h=[];for(const d of[c,l])h.push([n,i,{x:i.x,y:u},{x:d,y:u},{x:d,y:g},{x:r.x,y:g},r,o],[n,i,{x:i.x,y:g},{x:d,y:g},{x:d,y:u},{x:r.x,y:u},r,o]);return h},Kyo=(t,e)=>{const n=t.tracePath[0],o=t.tracePath[t.tracePath.length-1];if(!n||!o)return[];const i=t.tracePath[1]??n,r=t.tracePath[t.tracePath.length-2]??o,s=sm(e.orientation);if(s.x===0)return[];const a=Ls(e.center,e.width,e.height),A=s.x<0?a.minX-nE:a.maxX+nE,c=a.maxY+nE,l=a.minY-nE,u=i.y>=r.y,g=u?c:l,h=u?l:c;return[[n,i,{x:i.x,y:g},{x:A,y:g},{x:A,y:h},{x:r.x,y:h},r,o],[n,i,{x:i.x,y:h},{x:A,y:h},{x:A,y:g},{x:r.x,y:g},r,o]]},Vyo=({trace:t,obstacleLabel:e,outputTraces:n,outputNetLabelPlacements:o,candidateResults:i,chipObstacles:r})=>{for(const A of i)if(A.usesHorizontalSegmentPush&&A.status==="valid"&&A.score)return A.path;let s=null,a=gvt({trace:t,tracePath:t.tracePath,obstacleLabel:e,outputTraces:n,outputNetLabelPlacements:o,chipObstacles:r});for(const A of i)A.status!=="valid"||!A.score||jyo(A.score,a)&&(a=A.score,s=A.path);return s},zyo=({trace:t,label:e,outputTraces:n})=>{const o=sm(e.orientation);if(o.x===0)return null;const i=t.tracePath,r=Ls(e.center,e.width,e.height),s=i.findIndex((f,I)=>{const C=i[I+1];return!C||Math.abs(f.x-C.x)>=1e-9?!1:O7(f,C,r)});if(s<=0||s>=i.length-2)return null;const a=i[s-1],A=i[s],c=i[s+1],l=i[s+2];if(Math.abs(a.y-A.y)>=1e-9||Math.abs(c.y-l.y)>=1e-9)return null;let u=r.minX-nE;o.x>0&&(u=r.maxX+nE);const g=o.x>0?nE:-nE,h=Math.min(A.y,c.y),d=Math.max(A.y,c.y);for(let f=0;f<Hyo&&Oyo({x:u,lowY:h,highY:d,outputTraces:n,netId:t.globalConnNetId});f++)u+=g;const p=uvt({start:a,end:{x:u,y:A.y},labelBounds:r}),m=uvt({start:{x:u,y:c.y},end:l,labelBounds:r}),_=[...i.slice(0,s-1),a];return Math.abs(a.y-p)>=1e-9&&_.push({x:a.x,y:p}),_.push({x:u,y:p}),_.push({x:u,y:m}),Math.abs(l.y-m)>=1e-9&&_.push({x:l.x,y:m}),_.push(l,...i.slice(s+3)),Qa(_)},uvt=({start:t,end:e,labelBounds:n})=>{if(!O7(t,e,n))return t.y;const o=(n.minY+n.maxY)/2;return t.y>=o?n.maxY+nE:n.minY-nE},Jyo=(t,e)=>{if(e)for(const n of t)n.selected=n.path===e},gvt=({trace:t,tracePath:e,obstacleLabel:n,outputTraces:o,outputNetLabelPlacements:i,chipObstacles:r})=>{const s={...t,tracePath:e};return{labelIntersections:Jh({traces:[s],netLabels:i}).length,labelHugDistance:$yo(e,n),traceIntersections:Wyo(s,o),chipBoundaryOverlap:Lyo(e,r),pathLength:U7(e)}},Wyo=(t,e)=>{let n=0;for(const o of e)o.mspPairId!==t.mspPairId&&(n+=vle(t.tracePath,o.tracePath));return n},jyo=(t,e)=>{const n=t.labelIntersections>0,o=e.labelIntersections>0;return n!==o?!n:t.chipBoundaryOverlap!==e.chipBoundaryOverlap?t.chipBoundaryOverlap<e.chipBoundaryOverlap:t.labelIntersections!==e.labelIntersections?t.labelIntersections<e.labelIntersections:t.labelHugDistance!==e.labelHugDistance?t.labelHugDistance<e.labelHugDistance:t.traceIntersections!==e.traceIntersections?t.traceIntersections<e.traceIntersections:t.pathLength<e.pathLength},$yo=(t,e)=>{const n=Ls(e.center,e.width,e.height);let o=0;for(const i of t)o+=qyo(i,n);return o},qyo=(t,e)=>{const n=Math.max(e.minX-t.x,0,t.x-e.maxX),o=Math.max(e.minY-t.y,0,t.y-e.maxY);return n+o},Xyo=t=>{const{trace:e,outputTraces:n}=t;let o=0;for(const i of n)i.mspPairId!==e.mspPairId&&i.globalConnNetId!==e.globalConnNetId&&(o+=vle(e.tracePath,i.tracePath));return o},dvt=t=>{const{traces:e,outputTraces:n,chipObstacles:o}=t;let i=0,r=0;for(const s of e)Fyo(s.tracePath,o)&&(i+=1),r+=Xyo({trace:s,outputTraces:n});return{chipEdgeRuns:i,traceCrossings:r}},Zyo="blue",hvt="red",e2o=t=>{const e=zh(t.inputProblem);return t2o(e,t),n2o(e,t),t.solved||(o2o(e,t.currentCandidateResults),i2o(e,t)),e},t2o=(t,e)=>{for(const n of e.outputTraces)t.lines.push({points:n.tracePath,strokeColor:"purple"})},n2o=(t,e)=>{for(const n of e.outputNetLabelPlacements){const o=Mc(n.globalConnNetId,.35);t.rects.push({center:n.center,width:n.width,height:n.height,fill:o,strokeColor:Mc(n.globalConnNetId,.9),label:`netId: ${n.netId}
globalConnNetId: ${n.globalConnNetId}`}),t.points.push({...n.anchorPoint,color:Mc(n.globalConnNetId,.9),label:`anchorPoint
orientation: ${n.orientation}`})}},o2o=(t,e)=>{for(const n of e){const o=n.score?`
label intersections: ${n.score.labelIntersections}
trace intersections: ${n.score.traceIntersections}`:"";t.lines.push({points:n.path,strokeColor:n.selected?Zyo:hvt,strokeDash:n.selected?void 0:"4 2",label:`${n.selected?"selected":n.status} reroute${o}`})}},i2o=(t,e)=>{if(!e.currentOverlap)return;const n=e.currentOverlap.label;t.rects.push({center:n.center,width:n.width,height:n.height,fill:"rgba(255, 0, 0, 0.2)",strokeColor:hvt,label:`overlap target
${n.netId??n.globalConnNetId}`})},r2o=.1,s2o=10,pvt=.1,a2o=(t,e)=>t?t.chipEdgeRuns!==e.chipEdgeRuns?t.chipEdgeRuns<e.chipEdgeRuns:t.traceCrossings<e.traceCrossings:!1,A2o=class extends Ng{inputProblem;traces;netLabelPlacements;outputTraces;outputNetLabelPlacements;queuedOverlaps=[];currentOverlap=null;currentCandidateResults=[];chipObstacles;pinMap;constructor(t){super(),this.inputProblem=t.inputProblem,this.traces=t.traces,this.netLabelPlacements=t.netLabelPlacements,this.outputTraces=[...t.traces],this.outputNetLabelPlacements=[...t.netLabelPlacements],this.chipObstacles=Hy(t.inputProblem),this.pinMap=Kve(t.inputProblem),this.initializeQueuedOverlaps(),this.currentOverlap=this.queuedOverlaps[0]??null}getConstructorParams(){return{inputProblem:this.inputProblem,traces:this.traces,netLabelPlacements:this.netLabelPlacements}}_step(){const t=this.queuedOverlaps.shift();if(!t){this.finish();return}if(!this.isOverlapStillPresent(t)){this.currentOverlap=t,this.currentCandidateResults=[];return}this.rerouteOverlappingTrace(t)}finish(){this.currentOverlap=null,this.currentCandidateResults=[],this.solved=!0}initializeQueuedOverlaps(){const t=[],e=new Set;for(const n of this.getTraceLabelOverlaps()){if(!this.shouldRerouteOverlap(n))continue;const o=this.getOverlapKey(n);e.has(o)||(e.add(o),t.push(n))}this.queuedOverlaps=t}getTraceLabelOverlaps(){return Jh({traces:this.outputTraces,netLabels:this.outputNetLabelPlacements})}shouldRerouteOverlap(t){return this.isXFacingLabel(t.label)&&!this.hasExplicitOrientationConstraint(t.label)}isXFacingLabel(t){return t.orientation==="x+"||t.orientation==="x-"}hasExplicitOrientationConstraint(t){const e=t.netId??t.globalConnNetId;return Object.hasOwn(this.inputProblem.availableNetLabelOrientations,e)}getOverlapKey(t){const e=t.label.netId??t.label.globalConnNetId;return`${t.trace.mspPairId}:${e}:${t.label.anchorPoint.x}:${t.label.anchorPoint.y}`}isOverlapStillPresent(t){const e=this.getCurrentTrace(t.trace);return e?Jh({traces:[e],netLabels:[t.label]}).length>0:!1}getCurrentTrace(t){return this.outputTraces.find(e=>e.mspPairId===t.mspPairId)}rerouteOverlappingTrace(t){this.currentOverlap=t,this.currentCandidateResults=[];const e=this.outputTraces.findIndex(a=>a.mspPairId===t.trace.mspPairId);if(e===-1)return;const n=this.outputTraces[e],o=this.tryMoveLabelOutward(t.label),i=Gyo({trace:n,obstacleLabel:t.label,inputProblem:this.inputProblem,outputTraces:this.outputTraces,outputNetLabelPlacements:this.outputNetLabelPlacements,chipObstacles:this.chipObstacles});this.currentCandidateResults=i.candidateResults;let r=null;if(i.bestPath&&(r=dvt({traces:[{...n,tracePath:i.bestPath}],outputTraces:this.outputTraces,chipObstacles:this.chipObstacles})),o){const a=dvt({traces:[o.connectorTrace,n],outputTraces:this.outputTraces,chipObstacles:this.chipObstacles});if(!a2o(r,a)){this.outputNetLabelPlacements[o.labelIndex]=o.movedLabel,this.outputTraces.push(o.connectorTrace);return}}if(!i.bestPath)return;const s=n.tracePath;this.outputTraces[e]={...n,tracePath:i.bestPath},this.outputNetLabelPlacements=jH({trace:n,originalTracePath:s,reroutedTracePath:i.bestPath,netLabelPlacements:this.outputNetLabelPlacements})}tryMoveLabelOutward(t){const e=this.outputNetLabelPlacements.findIndex(i=>i.globalConnNetId===t.globalConnNetId&&i.anchorPoint.x===t.anchorPoint.x&&i.anchorPoint.y===t.anchorPoint.y&&i.pinIds.join(",")===t.pinIds.join(","));if(e===-1)return null;const n=this.outputNetLabelPlacements[e];if(n.mspConnectionPairIds.length>0||n.pinIds.length!==1||this.outputNetLabelPlacements.filter(i=>i.globalConnNetId===n.globalConnNetId).length!==1)return null;const o=sm(n.orientation);if(o.x===0&&o.y===0)return null;for(let i=1;i<=s2o;i++){const r=i*r2o,s={...n,anchorPoint:{x:n.anchorPoint.x+o.x*r,y:n.anchorPoint.y+o.y*r},center:{x:n.center.x+o.x*r,y:n.center.y+o.y*r}},a={...s,width:s.width+pvt*2,height:s.height+pvt*2};if(Jh({traces:this.outputTraces,netLabels:[a]}).length>0)continue;const A=l2o({label:n,movedLabel:s,pinMap:this.pinMap});if(!(Jh({traces:[A],netLabels:this.outputNetLabelPlacements}).length>0))return{labelIndex:e,movedLabel:s,connectorTrace:A}}return null}visualize(){return e2o({inputProblem:this.inputProblem,outputTraces:this.outputTraces,outputNetLabelPlacements:this.outputNetLabelPlacements,solved:this.solved,currentOverlap:this.currentOverlap,currentCandidateResults:this.currentCandidateResults})}},c2o=t=>`port-only-label-connector-${t.globalConnNetId}-${t.pinIds[0]}`,l2o=({label:t,movedLabel:e,pinMap:n})=>{const o=c2o(t);return{mspPairId:o,dcConnNetId:t.dcConnNetId??t.globalConnNetId,globalConnNetId:t.globalConnNetId,userNetId:t.netId,pins:Vve(t,n),tracePath:[t.anchorPoint,e.anchorPoint],mspConnectionPairIds:[o],pinIds:t.pinIds}},Z_=.05,mvt=2e3,$5=.001,lr=1e-9,Rle=$5+lr,u2o="blue",_vt="red",ju=t=>t==="y+"||t==="y-",$H=t=>t==="x+"||t==="x-",pj=(t,e)=>Math.min(t.maxX,e.maxX)-Math.max(t.minX,e.minX)>lr&&Math.min(t.maxY,e.maxY)-Math.max(t.minY,e.minY)>lr,Tle=(t,e,n,o)=>Math.min(e,o)-Math.max(t,n)>lr,mj=(t,e)=>{for(const n of Object.values(e)){const o=n.tracePath;for(let i=0;i<o.length-1;i++)if(kle(o[i],o[i+1],t))return!0}return!1},kle=(t,e,n)=>{const o={minX:n.minX+Rle,minY:n.minY+Rle,maxX:n.maxX-Rle,maxY:n.maxY-Rle};return o.minX>=o.maxX||o.minY>=o.maxY?!1:Fle(t,e)?t.x<=o.minX+lr||t.x>=o.maxX-lr?!1:Tle(Math.min(t.y,e.y),Math.max(t.y,e.y),o.minY,o.maxY):Lle(t,e)?t.y<=o.minY+lr||t.y>=o.maxY-lr?!1:Tle(Math.min(t.x,e.x),Math.max(t.x,e.x),o.minX,o.maxX):!1},Jve=(t,e)=>{for(let n=0;n<t.length-1;n++)if(O7(t[n],t[n+1],e))return!0;return!1},fvt=(t,e)=>[["left",Math.abs(t.x-e.minX)],["right",Math.abs(t.x-e.maxX)],["bottom",Math.abs(t.y-e.minY)],["top",Math.abs(t.y-e.maxY)]],Wve=(t,e,n)=>jve(ju(n)?[t,{x:e.x,y:t.y},e]:[t,{x:t.x,y:e.y},e]),jve=t=>{const e=t.filter((o,i)=>i===0||!g2o(o,t[i-1]));if(e.length<3)return e;const n=[e[0]];for(let o=1;o<e.length-1;o++){const i=n[n.length-1],r=e[o],s=e[o+1];Fle(i,r)&&Fle(r,s)||Lle(i,r)&&Lle(r,s)||n.push(r)}return n.push(e[e.length-1]),n},g2o=(t,e)=>Fle(t,e)&&Lle(t,e),Fle=(t,e)=>Math.abs(t.x-e.x)<=lr,Lle=(t,e)=>Math.abs(t.y-e.y)<=lr,d2o=t=>Math.max(...t.chips.map(n=>n.width),1)*3,Ivt=t=>t.mspConnectionPairIds.length===0,h2o=({labelIndices:t,netLabelPlacements:e})=>{const n=[...t];for(const o of t){const i=e[o];if(Ivt(i))continue;const r=Ls(i.center,i.width,i.height),s=n.findIndex(A=>{const c=e[A];if(!Ivt(c)||c.globalConnNetId===i.globalConnNetId)return!1;const l=Ls(c.center,c.width,c.height);return pj(r,l)}),a=n.indexOf(o);s===-1||s>a||(n.splice(a,1),n.splice(s,0,o))}return n},p2o=t=>{const e=zh(t.inputProblem);return C2o(e),m2o(e,t.traces),_2o(e,t.outputNetLabelPlacements),f2o(e,t.currentLabel,t.solved),I2o(e,t.currentCandidateResults,t.solved),e},m2o=(t,e)=>{for(const n of e)t.lines.push({points:n.tracePath,strokeColor:"purple"})},_2o=(t,e)=>{for(const n of e)t.rects.push({center:n.center,width:n.width,height:n.height,fill:Mc(n.globalConnNetId,.35),strokeColor:Mc(n.globalConnNetId,.9),label:`netId: ${n.netId}
globalConnNetId: ${n.globalConnNetId}`}),t.points.push({x:n.anchorPoint.x,y:n.anchorPoint.y,color:Mc(n.globalConnNetId,.9),label:`anchorPoint
orientation: ${n.orientation}`})},f2o=(t,e,n)=>{!e||n||t.rects.push({center:e.center,width:e.width,height:e.height,fill:"rgba(255, 0, 0, 0.2)",strokeColor:_vt,label:`available orientation target
${e.netId??e.globalConnNetId}`})},I2o=(t,e,n)=>{if(!n)for(const o of e){const i=o.selected?u2o:_vt,r=o.distance===void 0?"":`
distance: ${o.distance.toFixed(3)}`,s=o.outwardDistance===void 0||o.outwardDistance===0?"":`
outward distance: ${o.outwardDistance.toFixed(3)}`;t.rects.push({center:o.center,width:o.width,height:o.height,fill:o.selected?"rgba(0, 0, 255, 0.2)":"rgba(255, 0, 0, 0.15)",strokeColor:i,strokeDash:o.selected?void 0:"4 2",label:`${o.selected?"selected":o.status} available orientation
phase: ${o.phase}
orientation: ${o.orientation}${r}${s}`}),t.points.push({x:o.anchorPoint.x,y:o.anchorPoint.y,color:i,label:`candidate anchor
${o.phase}
${o.orientation}`})}},C2o=t=>{t.lines||(t.lines=[]),t.points||(t.points=[]),t.rects||(t.rects=[]),t.circles||(t.circles=[]),t.texts||(t.texts=[])},y2o=class{chipObstacleSpatialIndex;labelIndex=null;traceSegmentIndex=null;traceSegments=[];constructor(t){this.chipObstacleSpatialIndex=t.chipObstacleSpatialIndex,this.rebuild(t)}rebuild(t){this.labelIndex=this.buildLabelIndex(t.netLabelPlacements),this.traceSegments=this.getTraceSegments(t.traces),this.traceSegmentIndex=this.buildTraceSegmentIndex(this.traceSegments)}getLabelIndicesInBounds(t){return this.labelIndex?this.labelIndex.search(t.minX,t.minY,t.maxX,t.maxY):[]}getTraceSegmentsInBounds(t){if(!this.traceSegmentIndex)return[];const e=$ve(t,lr);return this.traceSegmentIndex.search(e.minX,e.minY,e.maxX,e.maxY).map(n=>this.traceSegments[n])}getLabelIndicesNearTracePath(t){const e=new Set;for(let n=0;n<t.length-1;n++){const o=$ve(Cvt(t[n],t[n+1]),lr);for(const i of this.getLabelIndicesInBounds(o))e.add(i)}return[...e].sort((n,o)=>n-o)}doesTracePathCrossChip(t){for(let e=0;e<t.length-1;e++){const n=t[e],o=t[e+1],i=this.chipObstacleSpatialIndex.getChipsInBounds($ve(Cvt(n,o),lr));for(const r of i)if(kle(n,o,r.bounds))return!0}return!1}doesTraceCrossBoundsInterior(t){for(const e of this.getTraceSegmentsInBounds(t))if(kle(e.start,e.end,t))return!0;return!1}doesTraceIntersectBounds(t){for(const e of this.getTraceSegmentsInBounds(t.bounds))if(e.trace.globalConnNetId!==t.excludedGlobalConnNetId&&O7(e.start,e.end,t.bounds))return!0;return!1}buildLabelIndex(t){if(t.length===0)return null;const e=new UH(t.length);for(const n of t)e.add(n.center.x-n.width/2,n.center.y-n.height/2,n.center.x+n.width/2,n.center.y+n.height/2);return e.finish(),e}getTraceSegments(t){const e=[];for(const n of t)for(let o=0;o<n.tracePath.length-1;o++)e.push({trace:n,start:n.tracePath[o],end:n.tracePath[o+1]});return e}buildTraceSegmentIndex(t){if(t.length===0)return null;const e=new UH(t.length);for(const n of t)e.add(Math.min(n.start.x,n.end.x),Math.min(n.start.y,n.end.y),Math.max(n.start.x,n.end.x),Math.max(n.start.y,n.end.y));return e.finish(),e}};function Cvt(t,e){return{minX:Math.min(t.x,e.x),minY:Math.min(t.y,e.y),maxX:Math.max(t.x,e.x),maxY:Math.max(t.y,e.y)}}function $ve(t,e){return{minX:t.minX-e,minY:t.minY-e,maxX:t.maxX+e,maxY:t.maxY+e}}var _j=.1,x2o=.2,yvt=.1,E2o=class extends Ng{inputProblem;traces;netLabelPlacements;netLabelConnectorTraceIds=new Set;outputNetLabelPlacements;queuedLabelIndices=[];currentLabelIndex=null;currentLabel=null;currentCandidateResults=[];crowdedPortOnlyLabelIndices=new Set;blockedStandaloneLabelIndex=null;blockedStandaloneLabelTargetAnchorX=null;traceMap;chipObstacleSpatialIndex;maxSearchDistance;pinMap;obstacleIndex;constructor(t){super(),this.inputProblem=t.inputProblem,this.traces=[...t.traces],this.netLabelPlacements=t.netLabelPlacements,this.outputNetLabelPlacements=[...t.netLabelPlacements],this.traceMap=Object.fromEntries(this.traces.map(e=>[e.mspPairId,e])),this.pinMap=Kve(t.inputProblem),this.chipObstacleSpatialIndex=t.inputProblem._chipObstacleSpatialIndex??new yle(t.inputProblem.chips),this.maxSearchDistance=d2o(t.inputProblem),this.obstacleIndex=new y2o({chipObstacleSpatialIndex:this.chipObstacleSpatialIndex,netLabelPlacements:this.outputNetLabelPlacements,traces:this.traces}),this.crowdedPortOnlyLabelIndices=this.getCrowdedPortOnlyLabelIndices(),this.queuedLabelIndices=this.getProcessableLabelIndices(),this.setCurrentLabel(this.queuedLabelIndices[0]??null)}getConstructorParams(){return{inputProblem:this.inputProblem,traces:this.traces,netLabelPlacements:this.netLabelPlacements}}_step(){const t=this.queuedLabelIndices.shift();if(t===void 0){this.finish();return}this.processLabel(t)}getOutput(){return{traces:this.traces,netLabelPlacements:this.outputNetLabelPlacements,netLabelConnectorTraceIds:this.netLabelConnectorTraceIds}}getProcessableLabelIndices(){const t=[];for(let l=0;l<this.outputNetLabelPlacements.length;l++)this.shouldProcessLabel(this.outputNetLabelPlacements[l],l)&&t.push(l);this.sortCrowdedTopBankByPin(t);const e=h2o({labelIndices:t,netLabelPlacements:this.outputNetLabelPlacements}),n=e.find(l=>{const u=this.outputNetLabelPlacements[l],g=this.getAvailableOrientations(u);return this.isPortOnlyLabel(u)&&this.isStandaloneSinglePinNetLabel(u)&&g.length===1&&ju(g[0])&&this.labelIntersectsDifferentNetTrace(u)});if(n===void 0)return e;this.blockedStandaloneLabelIndex=n,this.blockedStandaloneLabelTargetAnchorX=null;const o=this.outputNetLabelPlacements[n],i=this.getAvailableOrientations(o)[0],r=this.getChipSideForPoint(o.anchorPoint),s=[],a=[];for(let l=0;l<e.length;l++){const u=e[l],g=this.outputNetLabelPlacements[u],h=this.getAvailableOrientations(g);this.getChipSideForPoint(g.anchorPoint)===r&&h.length===1&&h[0]===i&&(s.push(l),a.push(u))}a.sort((l,u)=>{const g=this.outputNetLabelPlacements[l].anchorPoint.y,h=this.outputNetLabelPlacements[u].anchorPoint.y;return i==="y+"?h-g:g-h});const A=L7({inputProblem:this.inputProblem,netId:o.netId,pinIds:o.pinIds,isPortOnlyLabel:this.isPortOnlyLabel(o)});let c;if(A!==void 0&&(c=a.find(l=>{if(l===n)return!1;const u=this.outputNetLabelPlacements[l];return L7({inputProblem:this.inputProblem,netId:u.netId,pinIds:u.pinIds,isPortOnlyLabel:this.isPortOnlyLabel(u)})===A})),c!==void 0){const l=this.outputNetLabelPlacements[c];this.blockedStandaloneLabelTargetAnchorX=this.getSearchStartAnchor(l,i).x}for(let l=0;l<s.length;l++)e[s[l]]=a[l];return e}sortCrowdedTopBankByPin(t){const e=new Map;for(let n=0;n<t.length;n++){const o=t[n];if(!this.crowdedPortOnlyLabelIndices.has(o))continue;const i=this.outputNetLabelPlacements[o];if(this.getChipSideForPoint(i.anchorPoint)!=="top")continue;const r=this.pinMap[i.pinIds[0]];if(!r)continue;const s=e.get(r.chipId)??[];s.push(n),e.set(r.chipId,s)}for(const n of e.values()){const o=n.map(i=>t[i]).sort((i,r)=>{const s=this.pinMap[this.outputNetLabelPlacements[i].pinIds[0]],a=this.pinMap[this.outputNetLabelPlacements[r].pinIds[0]];return s.x-a.x});for(let i=0;i<n.length;i++)t[n[i]]=o[i]}}shouldProcessLabel(t,e){const n=this.getAvailableOrientations(t);if(n.length===0)return!1;if(!n.includes(t.orientation)||this.getTextBlockedMultiPinRailTraces(t,n[0]))return!0;if(n.length===1&&ju(n[0])&&this.isGroundLabel(t)){const r=Ls(t.center,t.width,t.height);if(this.outputNetLabelPlacements.some((a,A)=>{if(A===e||a.globalConnNetId===t.globalConnNetId)return!1;const c=this.getHorizontalConstraintMismatchBounds(a);return c?pj(r,c):!1}))return!0}if(!this.crowdedPortOnlyLabelIndices.has(e))return!1;const i=Ls(t.center,t.width,t.height);return this.outputNetLabelPlacements.some((r,s)=>s===e||r.globalConnNetId===t.globalConnNetId?!1:pj(i,Ls(r.center,r.width,r.height)))}getCrowdedPortOnlyLabelIndices(){const t=new Map;for(let n=0;n<this.outputNetLabelPlacements.length;n++){const o=this.outputNetLabelPlacements[n];if(!this.isPortOnlyLabel(o)||!this.isStandaloneSinglePinNetLabel(o)||this.getAvailableOrientations(o).length===0)continue;const i=this.pinMap[o.pinIds[0]];if(!i)continue;const r=this.getChipSideForPoint(o.anchorPoint);if(!r)continue;const s=t.get(i.chipId)??new Map,a=s.get(r)??[];a.push(n),s.set(r,a),t.set(i.chipId,s)}const e=new Set;for(const n of t.values())for(const o of n.values()){const i=o.some(s=>{const a=this.outputNetLabelPlacements[s];return!this.getAvailableOrientations(a).includes(a.orientation)}),r=o.some((s,a)=>{const A=this.outputNetLabelPlacements[s],c=Ls(A.center,A.width,A.height);return o.slice(a+1).some(l=>{const u=this.outputNetLabelPlacements[l];return pj(c,Ls(u.center,u.width,u.height))})});if(!(!i||!r))for(const s of o)e.add(s)}return e}processLabel(t){const e=this.outputNetLabelPlacements[t];this.setCurrentLabel(t),this.currentCandidateResults=[];const n=this.findCorrectedCandidate(e,t);n&&this.applyCandidate(e,n,t)}applyCandidate(t,e,n){this.outputNetLabelPlacements[n]={...t,...Tyo(e)},this.addConnectorTrace(t,e,n),this.obstacleIndex.rebuild({netLabelPlacements:this.outputNetLabelPlacements,traces:this.traces})}addConnectorTrace(t,e,n){if(e.phase==="trace-anchor")return;if(e.phase==="downward-ground-rail-extension")for(const s of t.mspConnectionPairIds){const a=this.traceMap[s];if(!a)continue;const A=Ryo({tracePath:a.tracePath,sourcePoint:t.anchorPoint,extensionEndPoint:e.anchorPoint});if(A){a.tracePath=A;return}}const o=this.getCandidateConnectorTrace(t,e,n);if(o.length<2)return;const i=`available-net-orientation-${n}-${t.netId??t.globalConnNetId}`,r={mspPairId:i,dcConnNetId:t.dcConnNetId??t.globalConnNetId,globalConnNetId:t.globalConnNetId,userNetId:t.netId,pins:Vve(t,this.pinMap),tracePath:o,mspConnectionPairIds:[i],pinIds:t.pinIds};this.traces.push(r),this.traceMap[i]=r,this.netLabelConnectorTraceIds.add(i)}finish(){this.currentLabelIndex=null,this.currentLabel=null,this.currentCandidateResults=[],this.solved=!0}setCurrentLabel(t){this.currentLabelIndex=t,this.currentLabel=t===null?null:this.outputNetLabelPlacements[t]}findCorrectedCandidate(t,e){const n=this.getAvailableOrientations(t),o=n[0];if(this.crowdedPortOnlyLabelIndices.has(e)&&this.getChipSideForPoint(t.anchorPoint)==="top"&&ju(o)){const d=this.findValidCrowdedTopVerticalFanoutCandidate(t,e,o);if(d)return d}const i=this.inputProblem.netConnections.find(d=>d.netId===t.netId),r=i?.pinIds.length===2,s=i?.isGround&&$H(t.orientation)&&n.length===1&&o==="y-"&&this.hasTraceContinuingInOrientation(t,"y+"),a=(i?.pinIds.length??0)>2&&ju(o)&&this.hasPortOnlyLabelOnSameNet(t),A=this.getTextBlockedMultiPinRailTraces(t,o),c=ju(o)&&this.hasOppositeVerticalRailOnSameChipSide(t,o);if(A){const d=this.findValidNearbyRailCandidate(t,o,e,A);if(d)return d}if(n.length===1&&ju(o)&&this.isOutwardHorizontalFallback(t)&&this.hasTraceContinuingInOrientation(t,o)&&(a||c)){const d=this.findValidTraceAnchorCandidate(t,o,e);if(d){if(this.canPlaceVerticalLabelOnHostRail(d,t))return d;d.selected=!1}const p=this.findValidOutwardTraceAnchorCandidate(t,o,e);if(p)return p}if(r&&n.length===1&&ju(o)&&this.hasTraceContinuingInOrientation(t,o)){const d=this.findValidCandidateInShiftColumn({label:t,labelIndex:e,orientation:o,direction:sm(o),baseAnchor:this.getWickOffsetAnchor(t.anchorPoint,o),maxSearchDistance:this.maxSearchDistance,outwardDistance:0,stopOnTraceCollision:!1});if(d)return d}const l=this.findValidRotatedCandidate(t,e,n),u=l!==null&&Math.abs(l.anchorPoint.x-t.anchorPoint.x)>lr;if(s&&u){const d=this.findValidCandidateInShiftColumn({label:t,labelIndex:e,orientation:o,direction:sm(o),baseAnchor:t.anchorPoint,maxSearchDistance:this.getSearchDistanceLimit(t,o),outwardDistance:0,phase:"downward-ground-rail-extension",stopOnTraceCollision:!1,connectorSource:t.anchorPoint,startDistance:x2o});if(d)return d}if(l)return l;const g=this.findValidTraceAnchorCandidate(t,n[0],e);if(g)return g;const h=this.findValidShiftedCandidate(t,n[0],e);return h||this.findValidLateralShiftedCandidate(t,n[0],e)}findValidCrowdedTopVerticalFanoutCandidate(t,e,n){const o=this.pinMap[t.pinIds[0]],i=o?this.chipObstacleSpatialIndex.chips.find(m=>m.chipId===o.chipId):void 0;if(!i)return null;const{width:r,height:s}=_B({orientation:n,netLabelWidth:L7({inputProblem:this.inputProblem,netId:t.netId,pinIds:t.pinIds,isPortOnlyLabel:this.isPortOnlyLabel(t)}),netLabelHeight:this.getNetLabelHeight(t)}),a=this.outputNetLabelPlacements.map((m,_)=>({index:_,pin:this.pinMap[m.pinIds[0]]})).filter(({index:m,pin:_})=>this.crowdedPortOnlyLabelIndices.has(m)&&_?.chipId===o.chipId&&_.x>o.x+lr).sort((m,_)=>m.pin.x-_.pin.x)[0]?.pin;if(n==="y-"&&a)return null;const A=n==="y-"?Math.max(t.anchorPoint.x+Z_,i.bounds.maxX+r/2+_j):Math.min(t.anchorPoint.x,(a?.x??i.bounds.maxX)-Z_-r/2);let c=i.bounds.maxY,l=Number.POSITIVE_INFINITY,u=Number.NEGATIVE_INFINITY;for(let m=0;m<this.outputNetLabelPlacements.length;m++){if(m===e||!this.crowdedPortOnlyLabelIndices.has(m)||this.queuedLabelIndices.includes(m))continue;const _=this.outputNetLabelPlacements[m],f=Ls(_.center,_.width,_.height);c=Math.max(c,f.maxY),_.orientation==="y+"&&(l=Math.min(l,f.minY),u=Math.max(u,f.maxY))}const g=c+Z_+(n==="y-"?s:0),d=Number.isFinite(l)&&Number.isFinite(u)?(l+u)/2:g,p=n==="y-"?[d,g]:[g];for(const m of p){if(m-t.anchorPoint.y>this.maxSearchDistance+lr)continue;const _=this.createCandidate(t,{x:A,y:m},n),f=this.evaluateCandidate(_,t,e,"lateral-shift",m-t.anchorPoint.y,A-t.anchorPoint.x);if(this.recordCandidateResult(f),f.status==="valid")return f.selected=!0,f}return null}hasTraceContinuingInOrientation(t,e){const n=sm(e);return Object.values(this.traceMap).some(o=>{if(o.globalConnNetId!==t.globalConnNetId)return!1;const i=o.tracePath;return i.some((r,s)=>Math.abs(r.x-t.anchorPoint.x)>lr||Math.abs(r.y-t.anchorPoint.y)>lr?!1:[i[s-1],i[s+1]].some(a=>a&&Math.abs(a.x-r.x)<=lr&&(a.y-r.y)*n.y>lr))})}findValidRotatedCandidate(t,e,n){for(const o of n){const i=this.createCandidate(t,this.getSearchStartAnchor(t,o),o),r=this.evaluateCandidate(i,t,e,"rotate");if(this.recordCandidateResult(r),r.status==="valid")return r.selected=!0,r}return null}findValidTraceAnchorCandidate(t,e,n){const o=sm(e),{points:i}=this.getTraceAnchorCandidates(t,e),r=i.sort((s,a)=>{const A=s.x*o.x+s.y*o.y;return a.x*o.x+a.y*o.y-A});for(const s of r){const a=this.createCandidate(t,s,e),A=this.evaluateCandidate(a,t,n,"trace-anchor");if(this.recordCandidateResult(A),A.status==="valid")return A.selected=!0,A}return null}findValidOutwardTraceAnchorCandidate(t,e,n){const o=sm(e),i=this.getSearchStartAnchor(t,e),{points:r,preferNearestBendOnOutwardRow:s}=this.getTraceAnchorCandidates(t,e),a=r.sort((A,c)=>{const l=A.x*o.x+A.y*o.y,u=c.x*o.x+c.y*o.y;if(!s)return u-l;const g=ju(e)?Math.abs(A.x-i.x):Math.abs(A.y-i.y),h=ju(e)?Math.abs(c.x-i.x):Math.abs(c.y-i.y);return u-l||g-h});for(const A of a){const c=this.createCandidate(t,{x:i.x,y:A.y},e,A),l=this.evaluateCandidate(c,t,n,"outward-trace-anchor");if(this.recordCandidateResult(l),l.status==="valid")return l.selected=!0,l;const u=this.getPerpendicularOutwardDirection(A,e);if(!(u.x===0&&u.y===0))for(let g=Z_;g<=this.maxSearchDistance+lr;g+=Z_){const h={x:A.x+u.x*g,y:A.y+u.y*g},d=this.createCandidate(t,h,e,A),p=this.evaluateCandidate(d,t,n,"outward-trace-anchor",g);if(this.recordCandidateResult(p),p.status==="valid")return p.selected=!0,p}}return null}getTraceAnchorCandidates(t,e){const n=new Set,o=[],i=new Set(t.mspConnectionPairIds??[]),r=new Set(i);if(ju(e)){const u=new Set;for(const h of r)for(const d of this.traceMap[h]?.pinIds??[])u.add(d);let g=!0;for(;g;){g=!1;for(const h of Object.values(this.traceMap)){if(r.has(h.mspPairId)||this.netLabelConnectorTraceIds.has(h.mspPairId)||h.globalConnNetId!==t.globalConnNetId||!h.pinIds.some(p=>u.has(p)))continue;const d=[...r].flatMap(p=>{const m=this.traceMap[p];return m?[m]:[]});if(this.sharesVerticalRailWithAny(h,d)){r.add(h.mspPairId);for(const p of h.pinIds)u.add(p);g=!0}}}}for(const u of r){const g=this.traceMap[u];if(g)for(const h of g.tracePath){const d=`${h.x.toFixed(9)},${h.y.toFixed(9)}`;n.has(d)||(n.add(d),o.push(h))}}const s=sm(e),a=Math.max(...o.map(u=>u.x*s.x+u.y*s.y)),A=o.filter(u=>Math.abs(u.x*s.x+u.y*s.y-a)<=lr),c=new Set([...i].flatMap(u=>this.traceMap[u]?.pinIds??[])),l=[...r].flatMap(u=>{if(i.has(u))return[];const g=this.traceMap[u];return g?.pinIds.some(h=>c.has(h))?[g]:[]});return{points:o,preferNearestBendOnOutwardRow:l.some(u=>A.some(g=>u.tracePath.some(h=>Math.abs(h.x-g.x)<=lr&&Math.abs(h.y-g.y)<=lr)))}}sharesVerticalRailWithAny(t,e){const n=new Set;for(const o of e)for(let i=0;i<o.tracePath.length-1;i++){const r=o.tracePath[i],s=o.tracePath[i+1];Math.abs(r.x-s.x)<=lr&&Math.abs(r.y-s.y)>lr&&n.add(r.x)}for(let o=0;o<t.tracePath.length-1;o++){const i=t.tracePath[o],r=t.tracePath[o+1];if(Math.abs(i.x-r.x)<=lr&&Math.abs(i.y-r.y)>lr&&[...n].some(s=>Math.abs(s-i.x)<=lr))return!0}return!1}getAvailableOrientations(t){const e=t.netId??t.globalConnNetId;return this.inputProblem.availableNetLabelOrientations[e]??[]}findValidShiftedCandidate(t,e,n){const o=sm(e),i=this.getSearchStartAnchor(t,e),r=this.getPerpendicularOutwardDirection(t.anchorPoint,e),s=this.getSearchDistanceLimit(t,e),a=r.x===0&&r.y===0?0:this.maxSearchDistance;for(let A=0;A<=a+lr;A+=Z_){const c={x:i.x+r.x*A,y:i.y+r.y*A},l=this.findValidCandidateInShiftColumn({label:t,labelIndex:n,orientation:e,direction:o,baseAnchor:c,maxSearchDistance:s,outwardDistance:A});if(l)return l}return null}findValidLateralShiftedCandidate(t,e,n){const o=sm(e),i=this.getSearchStartAnchor(t,e),r={x:ju(e)?1:0,y:$H(e)?1:0},s=Math.ceil(this.maxSearchDistance/Z_);for(let a=1;a<=s;a++)for(const A of[-1,1]){const c=A*a*Z_,l={x:i.x+r.x*c,y:i.y+r.y*c},u=this.getLateralColumnMaxDistance(t,e,l),g=this.findValidCandidateInShiftColumn({label:t,labelIndex:n,orientation:e,direction:o,baseAnchor:l,maxSearchDistance:u,outwardDistance:c,phase:"lateral-shift"});if(g)return g}return null}findValidCandidateInShiftColumn(t){const{label:e,labelIndex:n,orientation:o,direction:i,baseAnchor:r,maxSearchDistance:s,outwardDistance:a,phase:A="shift",stopOnTraceCollision:c=!0,connectorSource:l,startDistance:u=Z_}=t;for(let g=u;g<=s+lr;g+=Z_){const h={x:r.x+i.x*g,y:r.y+i.y*g},d=l??(A==="lateral-shift"?this.findProjectedConnectorSourceOnHostTrace(e,h,o):void 0),p=this.createCandidate(e,h,o,d),m=this.evaluateCandidate(p,e,n,A,g,a);if(this.recordCandidateResult(m),m.status==="valid")return m.selected=!0,m;if(c&&m.status==="trace-collision")break}return null}evaluateCandidate(t,e,n,o,i,r){return{...t,phase:o,distance:i,outwardDistance:r,selected:!1,status:this.getCandidateStatus({candidate:t,label:e,labelIndex:n,phase:o})}}recordCandidateResult(t){this.stats.candidateEvaluations=(this.stats.candidateEvaluations??0)+1,this.currentCandidateResults.length<mvt?this.currentCandidateResults.push(t):t.status==="valid"&&(this.currentCandidateResults[mvt-1]=t),this.stats.maxRecordedCandidates=Math.max(this.stats.maxRecordedCandidates??0,this.currentCandidateResults.length)}getCandidateConnectorTrace(t,e,n){if(this.crowdedPortOnlyLabelIndices.has(n)&&this.getChipSideForPoint(t.anchorPoint)==="top"&&ju(e.orientation))return jve([t.anchorPoint,{x:t.anchorPoint.x,y:e.anchorPoint.y},e.anchorPoint]);if(e.connectorSource)return Wve(e.connectorSource,e.anchorPoint,e.orientation);if(e.phase==="lateral-shift"){const o=this.crowdedPortOnlyLabelIndices.has(n)?this.getChipOutwardDirection(t.anchorPoint):(()=>{const r=sm(e.orientation);return{x:-r.x,y:-r.y}})(),i={x:t.anchorPoint.x+o.x*Z_,y:t.anchorPoint.y+o.y*Z_};return jve([t.anchorPoint,...Wve(i,e.anchorPoint,e.orientation)])}return Wve(t.anchorPoint,e.anchorPoint,e.orientation)}findProjectedConnectorSourceOnHostTrace(t,e,n){const o=sm(n),i=[];for(const r of t.mspConnectionPairIds){const s=this.traceMap[r];if(s)for(let a=0;a<s.tracePath.length-1;a++){const A=s.tracePath[a],c=s.tracePath[a+1];if(!(ju(n)?Math.abs(A.y-c.y)<=lr:Math.abs(A.x-c.x)<=lr))continue;const u=ju(n)?{x:e.x,y:A.y}:{x:A.x,y:e.y};if(!jl([A,c],t.anchorPoint)||!jl([A,c],u))continue;(e.x-u.x)*o.x+(e.y-u.y)*o.y>=-lr&&i.push(u)}}return i.sort((r,s)=>Math.abs(r.x-e.x)+Math.abs(r.y-e.y)-(Math.abs(s.x-e.x)+Math.abs(s.y-e.y)))[0]}isStandaloneSinglePinNetLabel(t){return this.inputProblem.netConnections.some(e=>e.netId===t.netId&&e.pinIds.length===1&&e.pinIds[0]===t.pinIds[0])}labelIntersectsDifferentNetTrace(t){const{width:e,height:n}=_B({orientation:t.orientation,netLabelWidth:L7({inputProblem:this.inputProblem,netId:t.netId,pinIds:t.pinIds,isPortOnlyLabel:this.isPortOnlyLabel(t)}),netLabelHeight:this.getNetLabelHeight(t)}),o=IC(t.anchorPoint,t.orientation,e,n),i=Ls(o,e,n);return Object.values(this.traceMap).some(r=>r.globalConnNetId!==t.globalConnNetId&&Jve(r.tracePath,i))}getSearchStartAnchor(t,e){const n=this.getWickOffsetAnchor(t.anchorPoint,e),{width:o,height:i}=_B({orientation:e,netLabelWidth:L7({inputProblem:this.inputProblem,netId:t.netId,pinIds:t.pinIds,isPortOnlyLabel:this.isPortOnlyLabel(t)}),netLabelHeight:this.getNetLabelHeight(t)}),r=this.getSideOffsetAnchor({anchorPoint:n,labelAnchorPoint:t.anchorPoint,orientation:e,width:o,height:i});return this.blockedStandaloneLabelIndex!==null&&t===this.outputNetLabelPlacements[this.blockedStandaloneLabelIndex]&&ju(e)&&this.blockedStandaloneLabelTargetAnchorX!==null&&(r.x=this.blockedStandaloneLabelTargetAnchorX),r}getWickOffsetAnchor(t,e){const n=sm(e);return{x:t.x+n.x*$5,y:t.y+n.y*$5}}getSideOffsetAnchor(t){const{anchorPoint:e,labelAnchorPoint:n,orientation:o,width:i,height:r}=t,s=this.getChipSideForPoint(n),a=this.getContainingChipSide(n)?$5:Z_;return ju(o)&&s==="left"?{x:e.x-i/2-a,y:e.y}:ju(o)&&s==="right"?{x:e.x+i/2+a,y:e.y}:$H(o)&&s==="bottom"?{x:e.x,y:e.y-r/2-a}:$H(o)&&s==="top"?{x:e.x,y:e.y+r/2+a}:e}getSearchDistanceLimit(t,e){const{width:n,height:o}=_B({orientation:e,netLabelWidth:L7({inputProblem:this.inputProblem,netId:t.netId,pinIds:t.pinIds,isPortOnlyLabel:this.isPortOnlyLabel(t)}),netLabelHeight:this.getNetLabelHeight(t)}),i=e==="y+"||e==="y-"?o:n;return Math.min(this.maxSearchDistance,i*2)}getLateralColumnMaxDistance(t,e,n){const o=this.getAvailableOrientations(t),i=o.length===1&&ju(o[0]),r=new Set(t.pinIds.map(l=>this.pinMap[l]?.chipId).filter(l=>!!l)),s=this.chipObstacleSpatialIndex.chips.filter(l=>r.has(l.chipId)),a=t.pinIds.map(l=>this.pinMap[l]?.chipId).find(Boolean),A=s.find(l=>l.chipId===a),c=i?s:A?[A]:[];if(c.length>0){if(e==="y-")return Math.max(0,...c.map(l=>n.y-l.bounds.minY));if(e==="y+")return Math.max(0,...c.map(l=>l.bounds.maxY-n.y));if(e==="x-")return Math.max(0,...c.map(l=>n.x-l.bounds.minX));if(e==="x+")return Math.max(0,...c.map(l=>l.bounds.maxX-n.x))}return this.getSearchDistanceLimit(t,e)}createCandidate(t,e,n,o){const{width:i,height:r}=_B({orientation:n,netLabelWidth:L7({inputProblem:this.inputProblem,netId:t.netId,pinIds:t.pinIds,isPortOnlyLabel:this.isPortOnlyLabel(t)}),netLabelHeight:this.getNetLabelHeight(t)});return{orientation:n,anchorPoint:e,connectorSource:o,width:i,height:r,center:IC(e,n,i,r)}}getNetLabelHeight(t){if(t.netId){const e=this.inputProblem.netConnections.find(n=>n.netId===t.netId)?.netLabelHeight;if(e!==void 0)return e}return this.inputProblem.netConnections.find(e=>e.pinIds.some(n=>t.pinIds.includes(n)))?.netLabelHeight}getCandidateStatus(t){const{candidate:e,label:n,labelIndex:o,phase:i}=t,r=Ls(e.center,e.width,e.height),s=this.getBoundsStatus({bounds:r,labelIndex:o,label:n});if(s!=="valid"){if(!(i==="trace-anchor"||i==="connected-rail-shift"||i==="downward-ground-rail-extension")||s!=="chip-collision"||!this.isAcceptableConnectedChipBoundaryOverlap(e,n,r)||i==="connected-rail-shift"&&!this.staysOutsideConnectedPinRow({candidate:e,label:n,bounds:r}))return s;const l=this.getBoundsStatus({bounds:r,labelIndex:o,label:n,ignoreChipCollisions:!0});if(l!=="valid")return l}const a=this.getCandidateConnectorTrace(n,{anchorPoint:e.anchorPoint,connectorSource:i==="lateral-shift"?e.connectorSource:void 0,orientation:e.orientation,phase:i},o);if(this.obstacleIndex.doesTracePathCrossChip(a))return"chip-collision";for(const c of this.inputProblem.textBoxes??[])if(Jve(a,fB(c)))return"text-collision";const A=this.includeHorizontalConstraintMismatches(this.obstacleIndex.getLabelIndicesNearTracePath(a),this.isGroundLabel(n));for(const c of A){if(c===o||this.shouldIgnorePendingCrowdedLabel(o,c))continue;const l=this.outputNetLabelPlacements[c];if(Jve(a,this.getLabelBoundsForCollisionWithGround(l,n)))return"netlabel-collision"}return"valid"}isAcceptableConnectedChipBoundaryOverlap(t,e,n){const o=this.chipObstacleSpatialIndex.getChipsInBounds(n);if(o.length===0)return!1;const i=new Set(e.pinIds.map(r=>this.pinMap[r]?.chipId).filter(r=>!!r));return o.every(r=>{if(!i.has(r.chipId))return!1;const{anchorPoint:s,orientation:a}=t,A=r.bounds;return ju(a)?s.x<A.minX-lr||s.x>A.maxX+lr:s.y<A.minY-lr||s.y>A.maxY+lr})}staysOutsideConnectedPinRow(t){const{candidate:e,label:n,bounds:o}=t,i=this.pinMap[n.pinIds[0]];return!i||!ju(e.orientation)?!1:e.anchorPoint.x<i.x?o.maxX<=i.x+yvt+lr:o.minX>=i.x-yvt-lr}getBoundsStatus(t){const{bounds:e,labelIndex:n,label:o,ignoreChipCollisions:i}=t;return!i&&(this.chipObstacleSpatialIndex.getChipsInBounds(e).length>0||this.sharesChipBoundary(e))?"chip-collision":KH(e,this.inputProblem)?"text-collision":this.obstacleIndex.doesTraceCrossBoundsInterior(e)?"trace-collision":this.isTraceTooCloseToLabel(e,o)?"trace-clearance-violation":this.intersectsAnyOtherNetLabel(e,n,o)?"netlabel-collision":"valid"}isTraceTooCloseToLabel(t,e){if(!this.shouldCheckTraceClearanceForLabel(e))return!1;const n=this.getLabelTraceClearanceBounds(t);return this.obstacleIndex.doesTraceIntersectBounds({bounds:n,excludedGlobalConnNetId:e.globalConnNetId})}getLabelTraceClearanceBounds(t){return{minX:t.minX-_j,minY:t.minY-_j,maxX:t.maxX+_j,maxY:t.maxY+_j}}shouldCheckTraceClearanceForLabel(t){return!this.isPortOnlyLabel(t)||!this.hasRoutedLabelOnSameNet(t)?!1:this.getAvailableOrientations(t).length===1}hasRoutedLabelOnSameNet(t){for(const e of this.outputNetLabelPlacements)if(e.globalConnNetId===t.globalConnNetId&&e.mspConnectionPairIds.length>0)return!0;return!1}isOutwardHorizontalFallback(t){const e=this.getChipSideForPoint(t.anchorPoint);return e==="left"&&t.orientation==="x-"||e==="right"&&t.orientation==="x+"}canPlaceVerticalLabelOnHostRail(t,e){if(!e.mspConnectionPairIds.some(s=>{const a=this.traceMap[s];return a&&jl(a.tracePath,t.anchorPoint)}))return!1;const o=this.pinMap[e.pinIds[0]];if(!o||e.pinIds.some(s=>this.pinMap[s]?.chipId!==o.chipId))return!1;const i=this.chipObstacleSpatialIndex.chips.find(s=>s.chipId===o.chipId);if(!i)return!1;const r=Ls(t.center,t.width,t.height);return r.minY<i.bounds.minY-lr||r.maxY>i.bounds.maxY+lr||t.anchorPoint.x>=i.bounds.minX-lr&&t.anchorPoint.x<=i.bounds.maxX+lr?!1:i.pins.every(s=>e.pinIds.includes(s.pinId)||s.y<=r.minY+lr||s.y>=r.maxY-lr)}getTextBlockedMultiPinRailTraces(t,e){if(!ju(e))return null;const n=this.pinMap[t.pinIds[0]]?.chipId,o=Object.values(this.traceMap).filter(d=>d.globalConnNetId===t.globalConnNetId&&d.pins.every(p=>p.chipId===n)),i=new Set(t.pinIds),r=new Set;for(let d=!0;d;){d=!1;for(const p of o)if(!r.has(p)&&p.pinIds.some(m=>i.has(m))){r.add(p);for(const m of p.pinIds)i.add(m);d=!0}}if(i.size<3||i.size===3&&!this.hasPortOnlyLabelOnSameNet(t))return null;const s=[...i].map(d=>this.pinMap[d]),a=sm(e),A=s[0].x;if(s.some(d=>Math.abs(d.x-A)>lr))return null;const c=this.inputProblem.chips.find(d=>d.chipId===n).pins.filter(d=>Math.abs(d.x-A)<=lr),l=Math.min(...s.map(d=>d.y)),u=Math.max(...s.map(d=>d.y));if(c.some(d=>d.y>=l-lr&&d.y<=u+lr&&!i.has(d.pinId))||e==="y-"&&l>Math.min(...c.map(d=>d.y))+lr||e==="y+"&&u<Math.max(...c.map(d=>d.y))-lr)return null;const g=Math.max(...s.map(d=>d.x*a.x+d.y*a.y));return(this.inputProblem.textBoxes??[]).some(d=>d.chipId===n&&d.center.x*a.x+d.center.y*a.y>g+lr)?[...r]:null}findValidNearbyRailCandidate(t,e,n,o){if(!ju(e))return null;const i=sm(e),r=[...new Set(o.flatMap(A=>A.pinIds))].map(A=>this.pinMap[A]).sort((A,c)=>c.y*i.y-A.y*i.y)[0]?.y;if(r===void 0)return null;const s=this.pinMap[t.pinIds[0]].x,a=[...new Set(o.flatMap(A=>A.tracePath.map(c=>c.x)))].filter(A=>Math.abs(A-s)>lr).sort((A,c)=>Math.abs(A-s)-Math.abs(c-s));for(const A of a){const c={x:A,y:r};if(!Object.values(this.traceMap).some(u=>u.globalConnNetId===t.globalConnNetId&&jl(u.tracePath,c)))continue;const l=this.findValidCandidateInShiftColumn({label:t,labelIndex:n,orientation:e,direction:i,baseAnchor:c,maxSearchDistance:this.getSearchDistanceLimit(t,e),outwardDistance:0,phase:"connected-rail-shift",stopOnTraceCollision:!1,connectorSource:c,startDistance:0});if(l)return l}return null}hasPortOnlyLabelOnSameNet(t){return this.outputNetLabelPlacements.some(e=>e!==t&&e.globalConnNetId===t.globalConnNetId&&this.isPortOnlyLabel(e))}hasOppositeVerticalRailOnSameChipSide(t,e){const n=this.inputProblem.netConnections.find(r=>r.netId===t.netId);if(!n)return!1;const o=this.getSingleChipSideForNetConnection(n);if(!o)return!1;const i=e==="y+"?"y-":"y+";return this.inputProblem.netConnections.some(r=>{if(r===n||r.pinIds.length<2)return!1;const s=this.inputProblem.availableNetLabelOrientations[r.netId]??[];if(s.length!==1||s[0]!==i)return!1;const a=this.getSingleChipSideForNetConnection(r);return a?.chipId===o.chipId&&a.side===o.side})}getSingleChipSideForNetConnection(t){if(t.pinIds.length<2)return null;const e=t.pinIds.map(s=>this.pinMap[s]);if(e.some(s=>!s)||new Set(e.map(s=>s.chipId)).size!==1)return null;const o=e[0].chipId,i=this.chipObstacleSpatialIndex.chips.find(s=>s.chipId===o);if(!i)return null;const r=new Set(e.map(s=>Math.abs(s.x-i.bounds.minX)<=lr?"left":Math.abs(s.x-i.bounds.maxX)<=lr?"right":null));return r.size!==1||r.has(null)?null:{chipId:o,side:[...r][0]}}isPortOnlyLabel(t){return t.mspConnectionPairIds.length===0}getNetConnectionForLabel(t){return t.netId?this.inputProblem.netConnections.find(e=>e.netId===t.netId):this.inputProblem.netConnections.find(e=>e.pinIds.some(n=>t.pinIds.includes(n)))}isGroundLabel(t){return this.getNetConnectionForLabel(t)?.isGround===!0}getHorizontalConstraintMismatchBounds(t){if(!this.isPortOnlyLabel(t)||t.orientation!=="x+"&&t.orientation!=="x-")return null;const e=t.netId??t.globalConnNetId,n=this.inputProblem.availableNetLabelOrientations[e]??[];if(n.length===0||n.some(s=>!ju(s)))return null;const o=this.getNetConnectionForLabel(t)?.netLabelHeight;if(o===void 0||o<=t.width+t.height+lr)return null;const i=IC(t.anchorPoint,t.orientation,t.width,t.height),r=IC(t.anchorPoint,t.orientation,o,t.height);return Ls({x:r.x+t.center.x-i.x,y:r.y+t.center.y-i.y},o,t.height)}includeHorizontalConstraintMismatches(t,e){if(!e)return[...t].sort((o,i)=>o-i);const n=new Set(t);for(let o=0;o<this.outputNetLabelPlacements.length;o++)this.getHorizontalConstraintMismatchBounds(this.outputNetLabelPlacements[o])&&n.add(o);return[...n].sort((o,i)=>o-i)}getLabelBoundsForCollisionWithGround(t,e){if(this.isGroundLabel(e)){const n=this.getHorizontalConstraintMismatchBounds(t);if(n)return n}return Ls(t.center,t.width,t.height)}shouldIgnorePendingCrowdedLabel(t,e){return this.crowdedPortOnlyLabelIndices.has(t)&&this.crowdedPortOnlyLabelIndices.has(e)&&this.queuedLabelIndices.includes(e)}intersectsAnyOtherNetLabel(t,e,n){const o={minX:t.minX-Z_,minY:t.minY-Z_,maxX:t.maxX+Z_,maxY:t.maxY+Z_},i=this.includeHorizontalConstraintMismatches(this.obstacleIndex.getLabelIndicesInBounds(o),this.isGroundLabel(n));for(const r of i){if(r===e||this.shouldIgnorePendingCrowdedLabel(e,r))continue;const s=this.outputNetLabelPlacements[r],a=this.getLabelBoundsForCollisionWithGround(s,n);if(r===this.blockedStandaloneLabelIndex&&ju(s.orientation)&&(a.minX-=Z_,a.maxX+=Z_),pj(t,a))return!0}return!1}sharesChipBoundary(t){const e={minX:t.minX-$5-lr,minY:t.minY-$5-lr,maxX:t.maxX+$5+lr,maxY:t.maxY+$5+lr},n=this.chipObstacleSpatialIndex.getChipsInBounds(e);for(const o of n){const i=o.bounds,r=Math.abs(t.minX-i.maxX)<=$5+lr||Math.abs(t.maxX-i.minX)<=$5+lr,s=Math.abs(t.minY-i.maxY)<=$5+lr||Math.abs(t.maxY-i.minY)<=$5+lr;if(r&&Tle(t.minY,t.maxY,i.minY,i.maxY)||s&&Tle(t.minX,t.maxX,i.minX,i.maxX))return!0}return!1}getChipSideForPoint(t){const e=this.getContainingChipSide(t);if(e)return e;const n=this.getOutsideChipSide(t);return n||this.getNearestChipSide(t)}getPerpendicularOutwardDirection(t,e){const n=this.getChipSideForPoint(t);return ju(e)&&n==="left"?{x:-1,y:0}:ju(e)&&n==="right"?{x:1,y:0}:$H(e)&&n==="bottom"?{x:0,y:-1}:$H(e)&&n==="top"?{x:0,y:1}:{x:0,y:0}}getChipOutwardDirection(t){switch(this.getChipSideForPoint(t)){case"left":return{x:-1,y:0};case"right":return{x:1,y:0};case"bottom":return{x:0,y:-1};case"top":return{x:0,y:1};default:return{x:0,y:0}}}getContainingChipSide(t){let e=null,n=Number.POSITIVE_INFINITY;for(const o of this.chipObstacleSpatialIndex.chips){const i=o.bounds;if(!(t.x<i.minX-lr||t.x>i.maxX+lr||t.y<i.minY-lr||t.y>i.maxY+lr))for(const[r,s]of fvt(t,i))s<n&&(e=r,n=s)}return e}getOutsideChipSide(t){let e=null,n=Number.POSITIVE_INFINITY;for(const o of this.chipObstacleSpatialIndex.chips){const i=o.bounds,r=t.x<i.minX-lr?i.minX-t.x:t.x>i.maxX+lr?t.x-i.maxX:0,s=t.y<i.minY-lr?i.minY-t.y:t.y>i.maxY+lr?t.y-i.maxY:0;if(r===0&&s===0)continue;const a=r**2+s**2;a>=n||(n=a,r>0?e=t.x<i.minX?"left":"right":e=t.y<i.minY?"bottom":"top")}return e}getNearestChipSide(t){let e=null,n=Number.POSITIVE_INFINITY;for(const o of this.chipObstacleSpatialIndex.chips)for(const[i,r]of fvt(t,o.bounds))r<n&&(e=i,n=r);return e}visualize(){return p2o({inputProblem:this.inputProblem,traces:this.traces,outputNetLabelPlacements:this.outputNetLabelPlacements,currentLabel:this.currentLabel,currentCandidateResults:this.currentCandidateResults,solved:this.solved})}},B2o="blue",xvt="red",b2o=t=>{const e=zh(t.inputProblem);return P2o(e),S2o(e,t.traces),Q2o(e,t.outputNetLabelPlacements),t.solved||(v2o(e,t.currentLabel),w2o(e,t.currentCandidateResults)),e},S2o=(t,e)=>{for(const n of e)t.lines.push({points:n.tracePath,strokeColor:"purple"})},Q2o=(t,e)=>{for(const n of e)t.rects.push({center:n.center,width:n.width,height:n.height,fill:Mc(n.globalConnNetId,.35),strokeColor:Mc(n.globalConnNetId,.9),label:`netId: ${n.netId}
globalConnNetId: ${n.globalConnNetId}`}),t.points.push({x:n.anchorPoint.x,y:n.anchorPoint.y,color:Mc(n.globalConnNetId,.9),label:`anchorPoint
orientation: ${n.orientation}`})},v2o=(t,e)=>{e&&t.rects.push({center:e.center,width:e.width,height:e.height,fill:"rgba(255, 0, 0, 0.2)",strokeColor:xvt,label:`trace-line VCC target
${e.netId??e.globalConnNetId}`})},w2o=(t,e)=>{for(const n of e){const o=n.selected?B2o:xvt;t.rects.push({center:n.center,width:n.width,height:n.height,fill:n.selected?"rgba(0, 0, 255, 0.2)":"rgba(255, 0, 0, 0.15)",strokeColor:o,strokeDash:n.selected?void 0:"4 2",label:`${n.selected?"selected":n.status} trace corner
trace: ${n.traceId}
distance: ${n.distance.toFixed(3)}`}),t.points.push({...n.anchorPoint,color:o,label:`candidate anchor
${n.status}`})}},P2o=t=>{t.lines||(t.lines=[]),t.points||(t.points=[]),t.rects||(t.rects=[]),t.circles||(t.circles=[]),t.texts||(t.texts=[])},Hle=.1,M2o=class extends Ng{inputProblem;traces;netLabelPlacements;outputNetLabelPlacements;queuedLabelIndices=[];currentLabelIndex=null;currentLabel=null;currentCandidateResults=[];queuedCornerCandidates=[];shouldAdvanceToNextLabel=!1;traceMap;constructor(t){super(),this.inputProblem=t.inputProblem,this.traces=t.traces,this.netLabelPlacements=t.netLabelPlacements,this.outputNetLabelPlacements=[...t.netLabelPlacements],this.traceMap=Object.fromEntries(t.traces.map(e=>[e.mspPairId,e])),this.queuedLabelIndices=this.getProcessableLabelIndices(),this.prepareNextLabel()}getConstructorParams(){return{inputProblem:this.inputProblem,traces:this.traces,netLabelPlacements:this.netLabelPlacements}}_step(){if(this.shouldAdvanceToNextLabel){this.advanceToNextLabel();return}const t=this.currentLabel,e=this.currentLabelIndex;if(t===null||e===null){this.finish();return}const n=this.queuedCornerCandidates.shift();if(!n){this.shouldAdvanceToNextLabel=!0;return}const o=this.evaluateCornerCandidate(t,e,n);this.currentCandidateResults.push(o),o.status==="valid"&&(o.selected=!0,this.applyCandidate(e,t,o),this.shouldAdvanceToNextLabel=!0)}getOutput(){return{traces:this.traces,netLabelPlacements:this.outputNetLabelPlacements}}getProcessableLabelIndices(){const t=[];for(let e=0;e<this.outputNetLabelPlacements.length;e++){const n=this.outputNetLabelPlacements[e];this.shouldProcessLabel(n)&&t.push(e)}return t}prepareNextLabel(){const t=this.queuedLabelIndices.shift();if(t===void 0)return this.clearCurrentLabel(),!1;const e=this.outputNetLabelPlacements[t];return this.currentLabelIndex=t,this.currentLabel=e,this.currentCandidateResults=[],this.queuedCornerCandidates=this.getCornerCandidatesForLabel(e),!0}advanceToNextLabel(){this.shouldAdvanceToNextLabel=!1,this.prepareNextLabel()||this.finish()}clearCurrentLabel(){this.currentLabelIndex=null,this.currentLabel=null,this.currentCandidateResults=[],this.queuedCornerCandidates=[]}finish(){this.clearCurrentLabel(),this.solved=!0}evaluateCornerCandidate(t,e,n){const o=IC(n.anchorPoint,t.orientation,t.width,t.height),i=Ls(o,t.width,t.height);return{...n,center:o,width:t.width,height:t.height,status:this.getCandidateStatus(i,e,n),selected:!1}}getCandidateStatus(t,e,n){if(this.intersectsAnyChip(t))return"chip-collision";if(KH(t,this.inputProblem))return"text-collision";const o=n.reroutedTracePath?{...this.traceMap,[n.traceId]:{...this.traceMap[n.traceId],tracePath:n.reroutedTracePath}}:this.traceMap;return mj(t,o)||n.reroutedTracePath&&!this.isReroutedTraceClear(n,e)?"trace-collision":this.intersectsAnyOtherNetLabel(t,e)?"netlabel-collision":"valid"}applyCandidate(t,e,n){if(n.reroutedTracePath){const o=this.traceMap[n.traceId],i={...o,tracePath:n.reroutedTracePath};this.traces=this.traces.map(r=>r.mspPairId===n.traceId?i:r),this.traceMap[n.traceId]=i,this.outputNetLabelPlacements=jH({trace:o,originalTracePath:o.tracePath,reroutedTracePath:n.reroutedTracePath,netLabelPlacements:this.outputNetLabelPlacements})}this.outputNetLabelPlacements[t]={...e,anchorPoint:n.anchorPoint,center:n.center}}shouldProcessLabel(t){return(t.orientation==="y+"||t.orientation==="y-")&&this.getCornerCandidatesForLabel(t).length>0}intersectsAnyChip(t){return this.inputProblem.chips.some(e=>yB(t,Ls(e.center,e.width,e.height)))}intersectsAnyOtherNetLabel(t,e){return this.outputNetLabelPlacements.some((n,o)=>o===e?!1:yB(t,Ls(n.center,n.width,n.height)))}getCornerCandidatesForLabel(t){const e=[],n=[],o=this.getTraceLinesForLabel(t),i=this.isConfiguredRailLabel(t)&&(this.isLabelCrossedByOtherNetTrace(t)||!o.some(r=>Lve(r.tracePath).some(s=>this.pointsEqual(s,t.anchorPoint))));for(const r of o){const s=r.tracePath,a=[s[0],s[s.length-1]];for(const A of Lve(s)){const c=s.indexOf(A),l=a.some(h=>Math.abs(h.x-A.x)<=yC),u=l||i&&this.isPinAlignedCorner(s,c);if(!u)continue;(l?e:n).push({anchorPoint:A,traceId:r.mspPairId,distance:KQt(A,t.anchorPoint),pinAligned:u},...this.getClearanceShiftedCornerCandidates({label:t,trace:r,cornerIndex:c,pinAligned:u}))}}return[...e.sort((r,s)=>r.distance-s.distance),...n.sort((r,s)=>r.distance-s.distance)]}isConfiguredRailLabel(t){return t.netId?this.inputProblem.availableNetLabelOrientations[t.netId]?.some(e=>e==="y+"||e==="y-"):!1}isLabelCrossedByOtherNetTrace(t){const e=Ls(t.center,t.width,t.height),n=Object.fromEntries(this.traces.filter(o=>o.globalConnNetId!==t.globalConnNetId).map(o=>[o.mspPairId,o]));return mj(e,n)}pointsEqual(t,e){return Math.abs(t.x-e.x)<=yC&&Math.abs(t.y-e.y)<=yC}getVerticalSegmentPointIndices(t,e){const n=t[e],o=Math.abs(t[e-1].x-n.x)<=yC,i=Math.abs(t[e+1].x-n.x)<=yC;return o===i?null:o?[e-1,e]:[e,e+1]}isPinAlignedCorner(t,e){const n=this.getVerticalSegmentPointIndices(t,e);if(!n)return!1;const[o,i]=n;return o<=1||i>=t.length-2}getClearanceShiftedCornerCandidates({label:t,trace:e,cornerIndex:n,pinAligned:o}){if(t.orientation!=="y+"&&t.orientation!=="y-")return[];const i=e.tracePath,r=i[n],s=this.getVerticalSegmentPointIndices(i,n);if(!s||s.includes(0)||s.includes(i.length-1))return[];const a=IC(r,t.orientation,t.width,t.height),A=Ls(a,t.width,t.height),c=this.inputProblem.chips.map(u=>Ls(u.center,u.width,u.height)).filter(u=>yB(A,u)),l=new Set;for(const u of c)l.add(u.minX-t.width/2),l.add(u.maxX+t.width/2);for(const u of this.traces)if(u.globalConnNetId!==t.globalConnNetId)for(let g=0;g<u.tracePath.length-1;g++){const h=u.tracePath[g],d=u.tracePath[g+1];if(!kle(h,d,A))continue;const p=t.width/2;Math.abs(h.x-d.x)<=yC?(l.add(h.x-p-Hle),l.add(h.x+p+Hle)):(l.add(Math.min(h.x,d.x)-p-Hle),l.add(Math.max(h.x,d.x)+p+Hle))}return[...l].flatMap(u=>{if(Math.abs(u-r.x)<=yC)return[];const g=Qa(i.map((p,m)=>s.includes(m)?{...p,x:u}:p)),h={x:u,y:r.y};return Lve(g).some(p=>this.pointsEqual(p,h))?[{anchorPoint:h,traceId:e.mspPairId,distance:KQt(h,t.anchorPoint),pinAligned:o,reroutedTracePath:g}]:[]})}isReroutedTraceClear(t,e){const n=t.reroutedTracePath;if(ON(n,Hy(this.inputProblem)))return!1;const o=this.traceMap[t.traceId],i=this.traces.filter(s=>s.mspPairId!==t.traceId&&s.globalConnNetId!==o.globalConnNetId);if(PQt(n,i))return!1;const r={[t.traceId]:{...o,tracePath:n}};return this.outputNetLabelPlacements.every((s,a)=>a===e?!0:!mj(Ls(s.center,s.width,s.height),r))}getTraceLinesForLabel(t){return this.traces.filter(e=>WCo(e)&&this.isTraceForLabel(e,t))}isTraceForLabel(t,e){if(!jl(t.tracePath,e.anchorPoint))return!1;const n=new Set(e.mspConnectionPairIds);return n.size>0?n.has(t.mspPairId):t.globalConnNetId===e.globalConnNetId}visualize(){return b2o({inputProblem:this.inputProblem,traces:this.traces,outputNetLabelPlacements:this.outputNetLabelPlacements,currentLabel:this.currentLabel,currentCandidateResults:this.currentCandidateResults,solved:this.solved})}},qve=t=>[...new Set(t)],D2o=t=>[...new Set(t.filter(e=>e!==void 0))],N2o=(t,e)=>D2o([e.netId,e.globalConnNetId,...t.netConnections.filter(n=>e.pinIds.some(o=>n.pinIds.includes(o))).map(n=>n.netId)]),R2o=t=>{switch(t){case"x+":case"+x":return"x+";case"x-":case"-x":return"x-";case"y+":case"+y":return"y+";case"y-":case"-y":return"y-"}},T2o=(t,e)=>{const n=t.availableNetLabelOrientations??{};for(const o of N2o(t,e))if(Object.hasOwn(n,o))return qve((n[o]??[]).map(R2o).filter(i=>i!==void 0));return null},hd=1e-6,Ole=1e-6,Gle=t=>Ls(t.center,t.width,t.height),Evt=(t,e)=>Math.min(t.maxX,e.maxX)-Math.max(t.minX,e.minX)>hd&&Math.min(t.maxY,e.maxY)-Math.max(t.minY,e.minY)>hd,k2o=(t,e)=>Math.min(t.maxX,e.maxX)-Math.max(t.minX,e.minX)>=-hd&&Math.min(t.maxY,e.maxY)-Math.max(t.minY,e.minY)>=-hd,F2o=(t,e)=>{for(const n of e){const o=n.tracePath;for(let i=0;i<o.length-1;i++)if(G2o(o[i],o[i+1],t))return!0}return!1},Bvt=(t,e)=>{const n=[];for(const o of e){if(K2o(o.pinIds)<2)continue;let i=0;for(let r=0;r<o.tracePath.length-1;r++){const s=o.tracePath[r],a=o.tracePath[r+1],A=qH(s,a);Y2o(t,s,a)&&n.push({trace:o,distance:i+qH(s,t)}),i+=A}}return n},L2o=t=>{let e=0;for(let n=0;n<t.tracePath.length-1;n++)e+=qH(t.tracePath[n],t.tracePath[n+1]);return e},H2o=(t,e)=>{let n=0;for(let o=0;o<t.tracePath.length-1;o++){const i=t.tracePath[o],r=t.tracePath[o+1],s=qH(i,r),a=n+s;if(e<=a+hd){const A=Math.max(0,Math.min(s,e-n)),c=U2o(i,r);return{x:i.x+c.x*A,y:i.y+c.y*A}}n=a}return t.tracePath[t.tracePath.length-1]},O2o=t=>{const e=[];let n=0;for(let o=0;o<t.tracePath.length;o++){e.push(n);const i=t.tracePath[o+1];i&&(n+=qH(t.tracePath[o],i))}return e},qH=(t,e)=>Math.abs(t.x-e.x)+Math.abs(t.y-e.y),G2o=(t,e,n)=>{const o={minX:n.minX+Ole,minY:n.minY+Ole,maxX:n.maxX-Ole,maxY:n.maxY-Ole};return o.minX>=o.maxX||o.minY>=o.maxY?!1:Zve(t,e)?t.x<=o.minX+hd||t.x>=o.maxX-hd?!1:bvt(Math.min(t.y,e.y),Math.max(t.y,e.y),o.minY,o.maxY):Xve(t,e)?t.y<=o.minY+hd||t.y>=o.maxY-hd?!1:bvt(Math.min(t.x,e.x),Math.max(t.x,e.x),o.minX,o.maxX):!1},Y2o=(t,e,n)=>Xve(e,n)?Math.abs(t.y-e.y)<=hd&&t.x>=Math.min(e.x,n.x)-hd&&t.x<=Math.max(e.x,n.x)+hd:Zve(e,n)?Math.abs(t.x-e.x)<=hd&&t.y>=Math.min(e.y,n.y)-hd&&t.y<=Math.max(e.y,n.y)+hd:!1,U2o=(t,e)=>({x:Zve(t,e)?0:Math.sign(e.x-t.x),y:Xve(t,e)?0:Math.sign(e.y-t.y)}),Xve=(t,e)=>Math.abs(t.y-e.y)<=hd,Zve=(t,e)=>Math.abs(t.x-e.x)<=hd,bvt=(t,e,n,o)=>Math.min(e,o)-Math.max(t,n)>hd,K2o=t=>new Set(t).size,Svt=.1,V2o=t=>{const{inputProblem:e,label:n,traceLocation:o}=t,i=L2o(o.trace),r=T2o(e,n),s=z2o(i,O2o(o.trace)),a=oxo(e,n),A=ixo(e,n),c=[],l=new Set;for(const u of s){const g=H2o(o.trace,u),h=J2o({inputProblem:e,label:n,point:g,orientationConstraint:r});for(const d of h){if(rxo(n,g,d))continue;const p=[g.x.toFixed(6),g.y.toFixed(6),d].join(":");l.has(p)||(l.add(p),c.push(W2o({point:g,orientation:d,netLabelWidth:a,netLabelHeight:A,traceLocation:o,pathDistance:u,label:n})))}}return c},z2o=(t,e)=>{const n=new Set,o=Math.ceil(t/Svt);for(let i=0;i<=o;i++){const r=Math.min(t,i*Svt);n.add(vvt(r))}for(const i of e)n.add(vvt(i));return[...n].filter(i=>i>=-hd&&i<=t+hd).sort((i,r)=>i-r)},J2o=t=>{const{inputProblem:e,label:n,point:o,orientationConstraint:i}=t;return i||j2o({label:n,inputProblem:e,point:o})},W2o=t=>{const{point:e,orientation:n,netLabelWidth:o,netLabelHeight:i,traceLocation:r,pathDistance:s,label:a}=t,{width:A,height:c}=_B({orientation:n,netLabelWidth:o,netLabelHeight:i});return{anchorPoint:e,center:IC(e,n,A,c),width:A,height:c,orientation:n,traceId:r.trace.mspPairId,pathDistance:s,distanceFromOriginal:qH(e,a.anchorPoint),status:"valid",selected:!1}},j2o=t=>{const{label:e,inputProblem:n,point:o}=t;return qve([...$2o(e),...q2o({inputProblem:n,point:o}),...exo])},$2o=t=>[t.orientation,txo(t.orientation)],q2o=t=>{const{inputProblem:e,point:n}=t,o=nxo(e);return qve(X2o(n,o).sort((i,r)=>r.outwardScore-i.outwardScore).map(({orientation:i})=>i))},X2o=(t,e)=>{const n=[];return n.push(Qvt({value:t.y,min:e.minY,max:e.maxY,center:e.centerY,positiveOrientation:"y+",negativeOrientation:"y-"})),n.push(Qvt({value:t.x,min:e.minX,max:e.maxX,center:e.centerX,positiveOrientation:"x+",negativeOrientation:"x-"})),n},Qvt=t=>{const{value:e,min:n,max:o,center:i,positiveOrientation:r,negativeOrientation:s}=t;return e>o+hd?{orientation:r,outwardScore:1+e-o}:e<n-hd?{orientation:s,outwardScore:1+n-e}:{orientation:e>=i?r:s,outwardScore:Z2o(e,i,o-n)}},Z2o=(t,e,n)=>Math.abs(t-e)/Math.max(hd,n/2),exo=["x+","x-","y+","y-"],txo=t=>{switch(t){case"x+":return"x-";case"x-":return"x+";case"y+":return"y-";case"y-":return"y+"}},nxo=t=>{if(t.chips.length===0)return{minX:0,minY:0,maxX:0,maxY:0,centerX:0,centerY:0};const e=t.chips.reduce((n,o)=>({minX:Math.min(n.minX,o.center.x-o.width/2),minY:Math.min(n.minY,o.center.y-o.height/2),maxX:Math.max(n.maxX,o.center.x+o.width/2),maxY:Math.max(n.maxY,o.center.y+o.height/2)}),{minX:Number.POSITIVE_INFINITY,minY:Number.POSITIVE_INFINITY,maxX:Number.NEGATIVE_INFINITY,maxY:Number.NEGATIVE_INFINITY});return{...e,centerX:(e.minX+e.maxX)/2,centerY:(e.minY+e.maxY)/2}},oxo=(t,e)=>{const n=L7({inputProblem:t,netId:e.netId,pinIds:e.pinIds,isPortOnlyLabel:e.mspConnectionPairIds.length===0});return n!==void 0?n:e.orientation==="y+"||e.orientation==="y-"?e.height:e.width},ixo=(t,e)=>{const n=t.netConnections.find(o=>o.netId===e.netId)?.netLabelHeight;return n!==void 0?n:t.netConnections.find(o=>o.pinIds.some(i=>e.pinIds.includes(i)))?.netLabelHeight},vvt=t=>Number(t.toFixed(6)),rxo=(t,e,n)=>Math.abs(e.x-t.anchorPoint.x)<=hd&&Math.abs(e.y-t.anchorPoint.y)<=hd&&n===t.orientation,sxo="blue",wvt="red",axo=t=>{const e=zh(t.inputProblem);return gxo(e),Axo(e,t.traces),cxo(e,t.inputProblem,t.outputNetLabelPlacements),t.solved||(lxo(e,t),uxo(e,t.currentCandidateResults)),e},Axo=(t,e)=>{for(const n of e)t.lines.push({points:n.tracePath,strokeColor:"purple"})},cxo=(t,e,n)=>{for(const o of n)t.rects.push({center:o.center,width:o.width,height:o.height,fill:Mc(o.globalConnNetId,.35),strokeColor:Mc(o.globalConnNetId,.9),label:dxo(e,o)}),t.points.push({x:o.anchorPoint.x,y:o.anchorPoint.y,color:Mc(o.globalConnNetId,.9),label:`anchorPoint
orientation: ${o.orientation}`})},lxo=(t,e)=>{if(e.currentOverlap)for(const n of[e.currentOverlap.firstLabelIndex,e.currentOverlap.secondLabelIndex]){const o=e.outputNetLabelPlacements[n];o&&t.rects.push({center:o.center,width:o.width,height:o.height,fill:"rgba(255, 0, 0, 0.2)",strokeColor:wvt,label:`netlabel overlap target
${o.netId??o.globalConnNetId}
${Pvt(e.inputProblem,o)}`})}},uxo=(t,e)=>{for(const n of e){const o=n.selected?sxo:wvt;t.rects.push({center:n.center,width:n.width,height:n.height,fill:n.selected?"rgba(0, 0, 255, 0.2)":"rgba(255, 0, 0, 0.15)",strokeColor:o,strokeDash:n.selected?void 0:"4 2",label:`${n.selected?"selected":n.status} netlabel overlap candidate
trace: ${n.traceId}
path distance: ${n.pathDistance.toFixed(3)}
orientation: ${n.orientation}
distance from original: ${n.distanceFromOriginal.toFixed(3)}`}),t.points.push({...n.anchorPoint,color:o,label:`candidate anchor
${n.status}`})}},gxo=t=>{t.lines||(t.lines=[]),t.points||(t.points=[]),t.rects||(t.rects=[]),t.circles||(t.circles=[]),t.texts||(t.texts=[])},Pvt=(t,e)=>`available orientations: ${hxo(t,e)?.join(", ")??"any"}`,dxo=(t,e)=>[`netId: ${e.netId}`,`globalConnNetId: ${e.globalConnNetId}`,Pvt(t,e)].join(`
`),hxo=(t,e)=>{const n=t.availableNetLabelOrientations??{};for(const o of[e.netId,e.globalConnNetId])if(o&&Object.hasOwn(n,o))return n[o]},pxo=class extends Ng{inputProblem;traces;netLabelPlacements;outputNetLabelPlacements;currentOverlap=null;currentCandidateResults=[];activeSearch=null;skippedOverlapKeys=new Set;constructor(t){super(),this.inputProblem=t.inputProblem,this.traces=t.traces,this.netLabelPlacements=t.netLabelPlacements,this.outputNetLabelPlacements=[...t.netLabelPlacements]}getConstructorParams(){return{inputProblem:this.inputProblem,traces:this.traces,netLabelPlacements:this.netLabelPlacements}}_step(){this.activeSearch?.completed&&this.clearActiveSearch();const t=this.getNextSearchWithCandidates();if(!t){this.finish();return}this.evaluateNextCandidate(t)}getOutput(){return{netLabelPlacements:this.outputNetLabelPlacements}}findNextOverlap(){for(let t=0;t<this.outputNetLabelPlacements.length;t++)for(let e=t+1;e<this.outputNetLabelPlacements.length;e++){if(!this.isLabelEligible(t)&&!this.isLabelEligible(e))continue;const n={firstLabelIndex:t,secondLabelIndex:e};if(!this.skippedOverlapKeys.has(this.getOverlapKey(n))&&this.labelsOverlap(n))return n}return null}isLabelEligible(t){return this.getTraceLocationsForLabel(t).length>0}labelsOverlap(t){const e=this.outputNetLabelPlacements[t.firstLabelIndex],n=this.outputNetLabelPlacements[t.secondLabelIndex];return!e||!n?!1:Evt(Gle(e),Gle(n))}startNextOverlapSearch(){const t=this.findNextOverlap();if(!t)return null;const e={overlap:t,queuedLabelIndices:this.getMoveLabelIndices(t),labelIndex:null,candidates:[],candidateIndex:0,candidateResults:[],completed:!1};return this.setActiveSearch(e),e}getMoveLabelIndices(t){const e=[];return this.isLabelEligible(t.secondLabelIndex)&&e.push(t.secondLabelIndex),this.isLabelEligible(t.firstLabelIndex)&&e.push(t.firstLabelIndex),e}getNextSearchWithCandidates(){for(;;){const t=this.activeSearch??this.startNextOverlapSearch();if(!t)return null;if(this.activateNextLabelSearch(t))return t;this.skipSearch(t)}}activateNextLabelSearch(t){if(t.labelIndex!==null&&t.candidateIndex<t.candidates.length)return!0;for(;t.queuedLabelIndices.length>0;){const e=t.queuedLabelIndices.shift(),n=this.outputNetLabelPlacements[e];if(n&&(t.labelIndex=e,t.candidates=this.getCandidatesForLabel(n),t.candidateIndex=0,t.candidates.length>0))return!0}return t.labelIndex=null,t.candidates=[],t.candidateIndex=0,!1}skipSearch(t){this.skippedOverlapKeys.add(this.getOverlapKey(t.overlap)),this.clearActiveSearch()}evaluateNextCandidate(t){const e=t.labelIndex;if(e===null)return;const n=this.outputNetLabelPlacements[e],o=t.candidates[t.candidateIndex];if(!n||!o)return;t.candidateIndex+=1;const i={...o,status:this.getCandidateStatus(o,e)};t.candidateResults.push(i),i.status==="valid"&&(i.selected=!0,this.applyCandidate(e,n,i),t.completed=!0)}getCandidatesForLabel(t){const e=[];for(const n of Bvt(t.anchorPoint,this.traces).filter(({trace:o})=>this.isTraceAssociatedWithLabel(o,t)))e.push(...V2o({inputProblem:this.inputProblem,label:t,traceLocation:n}));return e}getCandidateStatus(t,e){const n=Gle(t);return this.intersectsAnyChip(n)?"chip-collision":KH(n,this.inputProblem)?"text-collision":F2o(n,this.traces)?"trace-collision":this.intersectsAnyOtherLabel(n,e)?"netlabel-collision":"valid"}applyCandidate(t,e,n){this.outputNetLabelPlacements[t]={...e,anchorPoint:n.anchorPoint,center:n.center,width:n.width,height:n.height,orientation:n.orientation}}intersectsAnyChip(t){return this.inputProblem.chips.some(e=>k2o(t,Ls(e.center,e.width,e.height)))}intersectsAnyOtherLabel(t,e){return this.outputNetLabelPlacements.some((n,o)=>o===e?!1:Evt(t,Gle(n)))}getTraceLocationsForLabel(t){const e=this.outputNetLabelPlacements[t];return e?Bvt(e.anchorPoint,this.traces).filter(({trace:n})=>this.isTraceAssociatedWithLabel(n,e)):[]}isTraceAssociatedWithLabel(t,e){return e.mspConnectionPairIds.includes(t.mspPairId)||e.netId!==void 0&&e.netId===t.userNetId?!0:e.globalConnNetId===t.globalConnNetId}getOverlapKey(t){const e=this.outputNetLabelPlacements[t.firstLabelIndex],n=this.outputNetLabelPlacements[t.secondLabelIndex];return[t.firstLabelIndex,t.secondLabelIndex,e?.anchorPoint.x,e?.anchorPoint.y,n?.anchorPoint.x,n?.anchorPoint.y].join(":")}finish(){this.clearActiveSearch(),this.solved=!0}setActiveSearch(t){this.activeSearch=t,this.currentOverlap=t.overlap,this.currentCandidateResults=t.candidateResults}clearActiveSearch(){this.activeSearch=null,this.currentOverlap=null,this.currentCandidateResults=[]}visualize(){return axo({inputProblem:this.inputProblem,traces:this.traces,outputNetLabelPlacements:this.outputNetLabelPlacements,currentOverlap:this.currentOverlap,currentCandidateResults:this.currentCandidateResults,solved:this.solved})}},mxo=1e-6;function _xo(t){const{point:e,segmentStart:n,segmentEnd:o}=t,i=o.x-n.x,r=o.y-n.y,s=i*i+r*r;if(s===0)return{x:n.x,y:n.y};const a=((e.x-n.x)*i+(e.y-n.y)*r)/s,A=Math.max(0,Math.min(1,a));return{x:n.x+A*i,y:n.y+A*r}}function Mvt(t,e){let n=e[0],o=1/0;for(let i=0;i<e.length-1;i++){const r=_xo({point:t,segmentStart:e[i],segmentEnd:e[i+1]}),s=r.x-t.x,a=r.y-t.y,A=s*s+a*a;A<o&&(o=A,n=r)}return n}function Dvt(t,e){const n=Mvt(t,e);return Math.hypot(n.x-t.x,n.y-t.y)<mxo}function fxo(t,e){const o=p=>Ls(p.center,p.width,p.height),i=(p,m)=>{const _=o(p),f=o(m);return _.minX<=f.maxX+.01&&_.maxX>=f.minX-.01&&_.minY<=f.maxY+.01&&_.maxY>=f.minY-.01},r=new Set([t]);let s=!0;for(;s;){s=!1;for(const p of e)r.has(p)||[...r].some(m=>i(m,p))&&(r.add(p),s=!0)}let a=1/0,A=1/0,c=-1/0,l=-1/0;for(const p of r){const m=o(p);m.minX<a&&(a=m.minX),m.minY<A&&(A=m.minY),m.maxX>c&&(c=m.maxX),m.maxY>l&&(l=m.maxY)}const u=(a+c)/2,g=(A+l)/2,h=c-a,d=l-A;return{...t,center:{x:u,y:g},width:h,height:d}}function Ixo(t,e){const n=[];for(const o of t)for(const i of e){if(o.globalConnNetId===i.globalConnNetId)continue;const r=Ls(i.center,i.width,i.height),s=o.tracePath;for(let a=0;a<s.length-1;a++)if(O7(s[a],s[a+1],r)){n.push({trace:o,label:i});break}}return n}var Cxo=.1,yxo=3,Nvt=class extends Ng{inputProblem;traces;netLabelPlacements;outputTraces;outputNetLabelPlacements;completedReroutes=[];activeSubSolver=null;recentlyFailed=new Set;detourCounts=new Map;currentOverlap=null;constructor(t){super(),this.inputProblem=t.inputProblem,this.traces=t.traces,this.netLabelPlacements=t.netLabelPlacements,this.outputTraces=[...t.traces],this.outputNetLabelPlacements=[...t.netLabelPlacements]}getConstructorParams(){return{inputProblem:this.inputProblem,traces:this.traces,netLabelPlacements:this.netLabelPlacements}}_step(){if(this.activeSubSolver){if(this.activeSubSolver.step(),this.activeSubSolver.solved){const a=this.activeSubSolver.solvedTracePath;if(a){this.completedReroutes.push({initialTrace:{...this.activeSubSolver.initialTrace,tracePath:this.activeSubSolver.initialTrace.tracePath.map(c=>({...c}))},reroutedTracePath:a.map(c=>({...c})),label:this.activeSubSolver.label,detourCount:this.activeSubSolver.detourCount});const A=this.outputTraces.findIndex(c=>c.mspPairId===this.activeSubSolver.initialTrace.mspPairId);if(A!==-1){const c=this.outputTraces[A].tracePath;this.outputTraces[A]={...this.outputTraces[A],tracePath:a},this.reanchorLabelsOnMovedTrace(this.outputTraces[A],c)}}this.activeSubSolver=null,this.currentOverlap=null}else if(this.activeSubSolver.failed){const a=this.getOverlapKey(this.activeSubSolver.initialTrace,this.activeSubSolver.label);this.recentlyFailed.add(a),this.activeSubSolver=null,this.currentOverlap=null}return}const e=Ixo(this.outputTraces,this.outputNetLabelPlacements).filter(a=>{const A=this.getOverlapKey(a.trace,a.label);return!this.recentlyFailed.has(A)});if(e.length===0){this.solved=!0;return}const n=e[0],o=this.outputTraces.find(a=>a.mspPairId===n.trace.mspPairId);this.currentOverlap=n;const i=fxo(n.label,this.outputNetLabelPlacements.filter(a=>a.globalConnNetId!==o.globalConnNetId)),r=`${n.trace.mspPairId}::merged::${i.center.x},${i.center.y},${i.width},${i.height}`,s=this.detourCounts.get(r)??0;if(s>=yxo){this.recentlyFailed.add(this.getOverlapKey(n.trace,n.label)),this.currentOverlap=null;return}this.detourCounts.set(r,s+1),this.activeSubSolver=new Ele({trace:o,label:i,problem:this.inputProblem,paddingBuffer:Cxo,detourCount:s,tracesToAvoidOverlapping:this.outputTraces,netLabelPlacements:this.outputNetLabelPlacements})}reanchorLabelsOnMovedTrace(t,e){for(let n=0;n<this.outputNetLabelPlacements.length;n++){const o=this.outputNetLabelPlacements[n];if(o.globalConnNetId!==t.globalConnNetId||Dvt(o.anchorPoint,t.tracePath)||!Dvt(o.anchorPoint,e))continue;const i=Mvt(o.anchorPoint,t.tracePath);this.outputNetLabelPlacements[n]={...o,anchorPoint:i,center:IC(i,o.orientation,o.width,o.height)}}}getOutput(){return{traces:this.outputTraces,completedReroutes:this.completedReroutes,netLabelPlacements:this.outputNetLabelPlacements}}getOverlapKey(t,e){return`${t.mspPairId}::${e.globalConnNetId}`}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();const t=zh(this.inputProblem);t.lines||(t.lines=[]),t.rects||(t.rects=[]),t.points||(t.points=[]);for(const e of this.outputTraces)t.lines.push({points:e.tracePath,strokeColor:"purple"});for(const e of this.outputNetLabelPlacements)t.rects.push({center:e.center,width:e.width,height:e.height,fill:Mc(e.globalConnNetId,.35),strokeColor:Mc(e.globalConnNetId,.9),label:`netId: ${e.netId}
globalConnNetId: ${e.globalConnNetId}`}),t.points.push({x:e.anchorPoint.x,y:e.anchorPoint.y,color:Mc(e.globalConnNetId,.9)});return this.currentOverlap&&(t.lines.push({points:this.currentOverlap.trace.tracePath,strokeColor:"red"}),t.rects.push({center:this.currentOverlap.label.center,width:this.currentOverlap.label.width,height:this.currentOverlap.label.height,fill:"rgba(255,0,0,0.3)",strokeColor:"red"})),t}},yp=t=>{if(t.orientation!=="x-"&&t.orientation!=="x+"){if(t.netLabelText&&t.width>t.height){const i=t.height,r=t.width,s=IC(t.anchorPoint,t.orientation,i,r);return Ls(s,i,r)}return Ls(t.center,t.width,t.height)}const e=Math.max(t.width,t.height),n=wve,o=IC(t.anchorPoint,t.orientation,e,n);return Ls(o,e,n)},Rvt=1e-4,Tvt=1e-6,xxo=.1,Exo={"x+":{x:1,y:0},"x-":{x:-1,y:0},"y+":{x:0,y:1},"y-":{x:0,y:-1}},Bxo={ok:"green","label-collision":"orange","trace-collision":"darkorange","chip-collision":"red","text-collision":"purple"},bxo={ok:"rgba(0, 200, 0, 0.25)","label-collision":"rgba(255, 160, 0, 0.2)","trace-collision":"rgba(200, 80, 0, 0.2)","chip-collision":"rgba(220, 0, 0, 0.15)","text-collision":"rgba(128, 0, 128, 0.15)"};function kvt(t,e){return t.minX<e.maxX-1e-9&&t.maxX>e.minX+1e-9&&t.minY<e.maxY-1e-9&&t.maxY>e.minY+1e-9}function Sxo(t,e){const n=e.x-t.x,o=e.y-t.y,i=Math.sqrt(n*n+o*o),r=Math.max(1,Math.round(i/xxo)),s=[];for(let a=0;a<=r;a++){const A=a/r;s.push({x:t.x+A*n,y:t.y+A*o})}return s}var ewe=class extends Ng{constructor(t){super(),this.params=t,this.inputProblem=t.inputProblem,this.traces=t.traces,this.netLabelPlacements=t.netLabelPlacements,this.outputNetLabelPlacements=[...t.netLabelPlacements],this.chipIndex=t.inputProblem._chipObstacleSpatialIndex??(t.inputProblem.chips.length>0?new yle(t.inputProblem.chips):void 0),this.traceMap=Object.fromEntries(t.traces.map(e=>[e.mspPairId,e]))}params;inputProblem;traces;netLabelPlacements;outputNetLabelPlacements;currentCollision=null;currentLabelToMove=null;candidateResults=[];chipIndex;traceMap;skippedCollisionKeys=new Set;labelsToTry=[];candidateQueue=[];candidateIndex=0;getConstructorParams(){return{inputProblem:this.inputProblem,traces:this.traces,netLabelPlacements:this.netLabelPlacements,fixedNetLabelPlacements:this.params.fixedNetLabelPlacements,useRenderedLabelBounds:this.params.useRenderedLabelBounds}}getOutput(){return{netLabelPlacements:this.outputNetLabelPlacements}}labelBounds(t){return!this.params.useRenderedLabelBounds||this.params.fixedNetLabelPlacements?.includes(t)?Ls(t.center,t.width,t.height):yp(t)}collisionKey(t,e){return[t.globalConnNetId,e.globalConnNetId].sort().join("::")}findNextCollidingPair(){const t=[...this.outputNetLabelPlacements,...this.params.fixedNetLabelPlacements??[]];for(let e=0;e<this.outputNetLabelPlacements.length;e++)for(let n=e+1;n<t.length;n++){const o=t[e],i=t[n];if(!(o.globalConnNetId===i.globalConnNetId&&!this.params.fixedNetLabelPlacements?.includes(i))&&!this.skippedCollisionKeys.has(this.collisionKey(o,i))&&kvt(this.labelBounds(o),this.labelBounds(i)))return[o,i]}return null}netLabelWidthOf(t){return t.orientation==="x+"||t.orientation==="x-"?t.width:t.height}netLabelHeightOf(t){return t.orientation==="x+"||t.orientation==="x-"?t.height:t.width}buildCandidatesForLabel(t){const e=this.netLabelWidthOf(t),n=this.netLabelHeightOf(t),o=[],i=(s,a,A,c)=>{const{width:l,height:u}=_B({orientation:s,netLabelWidth:e,netLabelHeight:n}),g=IC(a,s,l,u),h=Exo[s],d={x:g.x+h.x*Rvt,y:g.y+h.y*Rvt};return{orientation:s,anchor:a,center:d,width:l,height:u,bounds:this.params.useRenderedLabelBounds?yp({...t,orientation:s,anchorPoint:a,center:d,width:l,height:u}):Ls(d,l,u),hostPairId:A,hostSegIndex:c,status:null}},r=this.traces.some(s=>this.params.netLabelConnectorTraceIds?.has(s.mspPairId)&&s.globalConnNetId===t.globalConnNetId&&jl(s.tracePath,t.anchorPoint));if(t.mspConnectionPairIds.length===0||r){const s=["x+","x-","y+","y-"],a=[t.orientation,...s.filter(A=>A!==t.orientation)];for(const A of a)o.push(i(A,t.anchorPoint))}else for(const s of t.mspConnectionPairIds){const a=this.traceMap[s];if(!a)continue;const A=a.tracePath;for(let c=0;c<A.length-1;c++){const l=A[c],u=A[c+1],g=Math.abs(l.y-u.y)<Tvt,h=Math.abs(l.x-u.x)<Tvt;if(!g&&!h)continue;let d;g?d=["y+","y-"]:d=["x+","x-"];for(const p of Sxo(l,u))for(const m of d)o.push(i(m,p,s,c))}}return o}checkCandidate(t,e,n){const{bounds:o,hostPairId:i,hostSegIndex:r}=t;if((this.chipIndex?.getChipsInBounds(o).length??0)>0)return"chip-collision";if(KH(o,this.inputProblem))return"text-collision";if(Tve(o,this.traceMap,i,r).hasIntersection)return"trace-collision";for(const s of n)if(!(s.globalConnNetId===e&&!this.params.fixedNetLabelPlacements?.includes(s))&&kvt(o,this.labelBounds(s)))return"label-collision";return"ok"}beginSearchForLabel(t){this.currentLabelToMove=t,this.candidateQueue=this.buildCandidatesForLabel(t),this.candidateIndex=0,this.candidateResults=[]}getNearbyValidPlacements(t,e){const n=i=>Math.hypot(i.anchor.x-t.anchorPoint.x,i.anchor.y-t.anchorPoint.y),o=[...this.outputNetLabelPlacements.filter(i=>i!==t),...this.params.fixedNetLabelPlacements??[]];return this.buildCandidatesForLabel(t).filter(i=>n(i)<=e&&this.checkCandidate(i,t.globalConnNetId,o)==="ok").sort((i,r)=>n(i)-n(r)).map(i=>({...t,orientation:i.orientation,anchorPoint:i.anchor,center:i.center,width:i.width,height:i.height}))}clearActiveSearch(){this.currentCollision=null,this.currentLabelToMove=null,this.labelsToTry=[],this.candidateQueue=[],this.candidateIndex=0,this.candidateResults=[]}_step(){if(!this.currentCollision){const s=this.findNextCollidingPair();if(!s){this.solved=!0;return}this.currentCollision=s,this.labelsToTry=[s[1],s[0]].filter(a=>!(this.params.fixedNetLabelPlacements??[]).includes(a)),this.beginSearchForLabel(this.labelsToTry.shift());return}if(this.candidateIndex>=this.candidateQueue.length){this.labelsToTry.length>0?this.beginSearchForLabel(this.labelsToTry.shift()):(this.skippedCollisionKeys.add(this.collisionKey(this.currentCollision[0],this.currentCollision[1])),this.clearActiveSearch());return}const t=this.candidateQueue[this.candidateIndex++],[e,n]=this.currentCollision;let o;this.currentLabelToMove===n?o=e:o=n;const i=[...[...this.outputNetLabelPlacements,...this.params.fixedNetLabelPlacements??[]].filter(s=>s!==e&&s!==n),o],r=this.checkCandidate(t,this.currentLabelToMove.globalConnNetId,i);if(t.status=r,this.candidateResults.push({...t}),r==="ok"){const s=this.outputNetLabelPlacements.indexOf(this.currentLabelToMove);s!==-1&&(this.outputNetLabelPlacements[s]={...this.currentLabelToMove,orientation:t.orientation,anchorPoint:t.anchor,width:t.width,height:t.height,center:t.center}),this.clearActiveSearch()}}visualize(){const t=zh(this.inputProblem);t.lines||(t.lines=[]),t.rects||(t.rects=[]),t.points||(t.points=[]);for(const n of this.traces)t.lines.push({points:n.tracePath,strokeColor:"purple"});for(const n of this.outputNetLabelPlacements){const o=this.currentCollision!=null&&(n===this.currentCollision[0]||n===this.currentCollision[1]);let i,r,s,a;o?(i="rgba(255, 0, 0, 0.2)",r="red",s=`netId: ${n.netId}
globalConnNetId: ${n.globalConnNetId}
⚠ COLLIDING`,a="red"):(i=Mc(n.globalConnNetId,.35),r=Mc(n.globalConnNetId,.9),s=`netId: ${n.netId}
globalConnNetId: ${n.globalConnNetId}`,a=Mc(n.globalConnNetId,.9)),t.rects.push({center:n.center,width:n.width,height:n.height,fill:i,strokeColor:r,label:s}),t.points.push({x:n.anchorPoint.x,y:n.anchorPoint.y,color:a,label:`anchorPoint
orientation: ${n.orientation}`})}const e=this.currentLabelToMove?this.currentLabelToMove.netId:"?";for(const n of this.candidateResults){const o=Bxo[n.status],i=bxo[n.status];let r;n.status!=="ok"&&(r="4 2"),t.rects.push({center:n.center,width:n.width,height:n.height,fill:i,strokeColor:o,strokeDash:r,label:`candidate: ${n.status}
orientation: ${n.orientation}
moving: ${e}`}),t.points.push({x:n.anchor.x,y:n.anchor.y,color:o,label:`candidate anchor
${n.status}`})}return t}},rI=.2,fj=1e-9,Qxo="GND",GN=(t,e)=>Math.abs(t.x-e.x)<=fj&&Math.abs(t.y-e.y)<=fj,XH=t=>{const e=[];for(const n of t){const o=e.at(-1);(!o||!GN(o,n))&&e.push(n)}return e},iw=t=>{let e=0;for(let n=0;n<t.length-1;n++){const o=t[n],i=t[n+1];e+=Math.abs(i.x-o.x)+Math.abs(i.y-o.y)}return e},twe=({pin:t,facingDirection:e})=>{const n={x:t.x,y:t.y};return e==="x+"&&(n.x+=rI),e==="x-"&&(n.x-=rI),e==="y+"&&(n.y+=rI),e==="y-"&&(n.y-=rI),n},Fvt=t=>({minX:Math.min(...t.map(e=>e.minX)),minY:Math.min(...t.map(e=>e.minY)),maxX:Math.max(...t.map(e=>e.maxX)),maxY:Math.max(...t.map(e=>e.maxY))}),Lvt=({connectionPair:t,obstacles:e,channelObstacles:n=e})=>{const[o,i]=t.pins,r=twe({pin:o,facingDirection:o._facingDirection}),s=twe({pin:i,facingDirection:i._facingDirection}),a=Fvt(e),A=[a.minY-rI,a.maxY+rI,...n.flatMap(u=>[u.minY-rI,u.maxY+rI])],c=[a.minX-rI,a.maxX+rI,...n.flatMap(u=>[u.minX-rI,u.maxX+rI])],l=[wF({...o,facingDirection:o._facingDirection},{...i,facingDirection:i._facingDirection},{overshoot:rI})];for(const u of new Set(A))l.push(XH([o,r,{x:r.x,y:u},{x:s.x,y:u},s,i]));for(const u of new Set(c))l.push(XH([o,r,{x:u,y:r.y},{x:u,y:s.y},s,i]));return l.sort((u,g)=>iw(u)-iw(g))},vxo=(t,e)=>({x:(t.x+e.x)/2,y:(t.y+e.y)/2}),wxo=t=>{const e=[];for(const n of t){for(let i=0;i<n.tracePath.length-1;i++){const r=n.tracePath[i],s=n.tracePath[i+1];e.push(r),e.push(vxo(r,s))}const o=n.tracePath.at(-1);o&&e.push(o)}return e},Pxo=({connectionPair:t,sameNetTraces:e})=>{const n=new Set(e.flatMap(o=>o.pinIds));return t.pins.filter(o=>!n.has(o.pinId))},Mxo=({connectionPair:t,sameNetTraces:e,obstacles:n,maxConnectionDistance:o})=>{const i=Fvt(n),r=[i.minY-rI,i.maxY+rI],s=[i.minX-rI,i.maxX+rI],a=[],A=wxo(e),c=Pxo({connectionPair:t,sameNetTraces:e});for(const l of c){const u=twe({pin:l,facingDirection:l._facingDirection});for(const g of A)if(!(ad(l,g)>o)){a.push(XH([l,u,{x:u.x,y:g.y},g])),a.push(XH([l,u,{x:g.x,y:u.y},g]));for(const h of r)a.push(XH([l,u,{x:u.x,y:h},{x:g.x,y:h},g]));for(const h of s)a.push(XH([l,u,{x:h,y:u.y},{x:h,y:g.y},g]))}}return a.sort((l,u)=>iw(l)-iw(u))},Dxo=({path:t,obstacles:e,connectionPair:n,rejectComponentBoundaryTravel:o})=>{const i=t[0],r=t.at(-1),s=n.pins.find(g=>GN(g,i)),a=n.pins.find(g=>GN(g,r));for(const[g,h]of[[s,t[1]],[a,t[t.length-2]]]){if(!g?._facingDirection)continue;const d=sm(g._facingDirection);if((h.x-g.x)*d.x+(h.y-g.y)*d.y<-fj)return!0}const A=s!==void 0&&a!==void 0,c=e.find(g=>g.kind==="chip"&&g.chipId===s?.chipId),l=e.find(g=>g.kind==="chip"&&g.chipId===a?.chipId);return o&&c&&Mve(t[0],t[1],c)||o&&l&&Mve(t[t.length-2],t[t.length-1],l)?!0:HN(t,e,{excludeRectsForSegment:g=>{const h=new Set;return g===0&&c&&h.add(c),A&&g===t.length-2&&l&&h.add(l),h}})!==null},Nxo=({connectionPair:t,failedConnectionPairs:e})=>{const n=new Set(t.pins.map(o=>o.chipId));return e.some(o=>o.mspPairId===t.mspPairId?!1:o.pins.every(i=>n.has(i.chipId)))},Rxo=({firstStart:t,firstEnd:e,secondStart:n,secondEnd:o})=>X_(t,e)&&X_(n,o)?Math.min(Math.max(t.x,e.x),Math.max(n.x,o.x))-Math.max(Math.min(t.x,e.x),Math.min(n.x,o.x))>fj:e1(t,e)&&e1(n,o)?Math.min(Math.max(t.y,e.y),Math.max(n.y,o.y))-Math.max(Math.min(t.y,e.y),Math.min(n.y,o.y))>fj:!1,Txo=({connectionPair:t,existingTrace:e})=>{const n=new Set(e.pinIds);return t.pins.filter(o=>n.has(o.pinId))},kxo=({path:t,connectionPair:e,existingTraces:n})=>{for(const o of n){if(o.globalConnNetId===e.globalConnNetId)continue;const i=Txo({connectionPair:e,existingTrace:o});for(let r=0;r<t.length-1;r++){const s=t[r],a=t[r+1];for(let A=0;A<o.tracePath.length-1;A++){const c=o.tracePath[A],l=o.tracePath[A+1];if(!(!X1(s,a,c,l)||i.some(g=>(GN(s,g)||GN(a,g))&&(GN(c,g)||GN(l,g)))&&!Rxo({firstStart:s,firstEnd:a,secondStart:c,secondEnd:l})))return!0}}}return!1},Fxo=class extends Ng{constructor(t){super(),this.params=t,this.inputProblem=t.inputProblem,this.alreadySolvedTraces=t.alreadySolvedTraces,this.failedConnectionPairs=t.failedConnectionPairs,this.queuedConnectionPairs=[...t.failedConnectionPairs],this.maxConnectionDistance=this.inputProblem.maxMspPairDistance??uj;const{netConnMap:e}=mB(this.inputProblem);this.groundGlobalConnNetId=e.getNetConnectedToId(Qxo)??void 0}params;inputProblem;alreadySolvedTraces;failedConnectionPairs;queuedConnectionPairs;maxConnectionDistance;groundGlobalConnNetId;solvedUnroutedTraces=[];getConstructorParams(){return this.params}_step(){const t=this.queuedConnectionPairs.shift();if(!t){this.solved=!0;return}if(t.globalConnNetId===this.groundGlobalConnNetId||ad(t.pins[0],t.pins[1])>this.maxConnectionDistance)return;const e=Hy(this.inputProblem),n=[...this.alreadySolvedTraces,...this.solvedUnroutedTraces],o=n.filter(c=>c.globalConnNetId===t.globalConnNetId),i=Mxo({connectionPair:t,sameNetTraces:o,obstacles:e,maxConnectionDistance:this.maxConnectionDistance}),r=Lvt({connectionPair:t,obstacles:e,channelObstacles:[]}),s=[...i,...r].sort((c,l)=>iw(c)-iw(l)),a=Nxo({connectionPair:t,failedConnectionPairs:this.failedConnectionPairs});let A;for(const c of s)A&&iw(c)>=iw(A)||Dxo({path:c,obstacles:e,connectionPair:t,rejectComponentBoundaryTravel:a})||kxo({path:c,connectionPair:t,existingTraces:n})||(A||s.push(...Lvt({connectionPair:t,obstacles:e})),A=c);A&&this.solvedUnroutedTraces.push({...t,tracePath:A,mspConnectionPairIds:[t.mspPairId],pinIds:t.pins.map(c=>c.pinId)})}getOutput(){return{newTraces:this.solvedUnroutedTraces,allTracesMerged:[...this.alreadySolvedTraces,...this.solvedUnroutedTraces]}}visualize(){const t=zh(this.inputProblem);for(const e of this.solvedUnroutedTraces)t.lines.push({points:e.tracePath,strokeColor:"blue"});return t}},Yle=1e-6,Ule=({path:t,netLabelPlacements:e})=>{for(const n of e){const o=Ls(n.center,n.width,n.height);for(let i=0;i<t.length-1;i++)if(O7(t[i],t[i+1],o))return!0}return!1},Hvt=({path:t,netLabelPlacements:e})=>{for(const n of e){const o=Ls(n.center,n.width,n.height),i={minX:o.minX+Yle,minY:o.minY+Yle,maxX:o.maxX-Yle,maxY:o.maxY-Yle};for(let r=0;r<t.length-1;r++)if(O7(t[r],t[r+1],i))return!0}return!1},nwe=t=>t._facingDirection?sm(t._facingDirection).x===0?"y":"x":null,Ovt=({coordinate:t,axis:e,pin:n})=>{if(!n._facingDirection)return!1;const o=sm(n._facingDirection);return(t-n[e])*o[e]>0},Lxo=(t,e)=>CB(t,e)?"x":Yy(t,e)?"y":null,Gvt=t=>{const e=[];for(let n=0;n<t.length-1;n++){const o=t[n],i=t[n+1],r=Lxo(o,i);if(!r)continue;const s=r==="x"?"y":"x";e.push({start:o,end:i,axis:r,coordinate:o[s]})}return e},Yvt=({pin:t,departureAxis:e,railCoordinate:n})=>e==="x"?{x:n,y:t.y}:{x:t.x,y:n},Hxo=({donorPath:t,branchDepartureSegment:e,sharedPin:n,adjacentPin:o})=>{const i=nwe(n);if(!i)return null;const r=i==="x"?"y":"x",s=Gvt(e)[0];if(!s||s.axis!==i)return null;let a=null,A=Number.POSITIVE_INFINITY;for(const c of Gvt(t)){if(c.axis!==r||!Ovt({coordinate:c.coordinate,axis:i,pin:n}))continue;const l=Yvt({pin:n,departureAxis:i,railCoordinate:c.coordinate}),u=Yvt({pin:o,departureAxis:i,railCoordinate:c.coordinate});if(!jl([c.start,c.end],l)||!jl([c.start,c.end],u)||!jl([s.start,s.end],l))continue;const g=Math.abs(c.coordinate-n[i]);g>=A||(a={segment:c,sharedPinExit:l},A=g)}return a},YN=({donorTrace:t,branchTrace:e})=>{const n=new Set(e.pins.map(o=>o.pinId));return t.pins.find(o=>n.has(o.pinId))??null},Kle=(t,e)=>Uc(t.x,e.x)?"y":Uc(t.y,e.y)?"x":null,Uvt=({trace:t,sharedPinId:e})=>{const n=Qa(t.tracePath),o=t.pins.find(r=>r.pinId===e);if(!o)return null;const i=t.pins[0]?.pinId===e?n:n.reverse();return fb(i[0],o)?i:null},Vle=({trace:t,sharedPrefix:e,netLabelPlacements:n})=>!n.some(o=>o.mspConnectionPairIds.includes(t.mspPairId)&&jl(e,o.anchorPoint)),Kvt=({trace:t,pathFromSharedPin:e,sharedPinId:n,branchPoint:o})=>{const i=e.findIndex((a,A)=>{const c=e[A+1];return c?jl([a,c],o):!1});if(i<0)return null;const r=Qa([o,...e.slice(i+1)]);let s=r;return t.pins[0]?.pinId!==n&&(s=r.reverse()),{...t,tracePath:s}},Oxo=({traces:t,netLabelPlacements:e,netLabelConnectorTraceIds:n,multiPinNetPinIds:o})=>{const i=[...t];for(let r=0;r<i.length;r++)if(!n.has(i[r].mspPairId))for(let s=r+1;s<i.length;s++){const a=i[r],A=i[s];if(n.has(A.mspPairId)||a.globalConnNetId!==A.globalConnNetId)continue;const c=YN({donorTrace:a,branchTrace:A});if(!c||!o.has(c.pinId))continue;const l=Uvt({trace:a,sharedPinId:c.pinId}),u=Uvt({trace:A,sharedPinId:c.pinId});if(!l||!u||l.length<2||u.length<2)continue;const g=Kle(l[0],l[1]),h=Kle(u[0],u[1]);if(!g||g!==h)continue;const d=l[1][g]-l[0][g],p=u[1][g]-u[0][g];if(!fb(l[1],u[1])&&Math.sign(d)===Math.sign(p)){let M=s,k=A,R=u;Math.abs(d)<Math.abs(p)&&(M=r,k=a,R=l);const F=R[1];if(Vle({trace:k,sharedPrefix:[R[0],F],netLabelPlacements:e})||(M===r?(M=s,k=A,R=u):(M=r,k=a,R=l)),!Vle({trace:k,sharedPrefix:[R[0],F],netLabelPlacements:e}))continue;const O=Kvt({trace:k,pathFromSharedPin:R,sharedPinId:c.pinId,branchPoint:F});if(!O)continue;i[M]=O;continue}if(l.length<3||u.length<3||!fb(l[1],u[1]))continue;const m=Kle(l[1],l[2]),_=Kle(u[1],u[2]);if(!m||m!==_||m===g)continue;const f=l[2][m]-l[1][m],I=u[2][m]-u[1][m],C=Math.sign(f)===Math.sign(I),y=l.slice(0,2);if(!C&&!Uc(Math.abs(f),Math.abs(I))&&e.some(M=>M.globalConnNetId===a.globalConnNetId&&jl(y,M.anchorPoint)))continue;let x=s,E=A,B=u,S=l[1];C&&Math.abs(f)<Math.abs(I)?(x=r,E=a,B=l,S=l[2]):C&&(S=u[2]);const Q=[B[0],B[1],S];if(Vle({trace:E,sharedPrefix:Q,netLabelPlacements:e})||(x===r?(x=s,E=A,B=u):(x=r,E=a,B=l)),!Vle({trace:E,sharedPrefix:[B[0],B[1],S],netLabelPlacements:e}))continue;const w=Kvt({trace:E,pathFromSharedPin:B,sharedPinId:c.pinId,branchPoint:S});w&&(i[x]=w)}return i},owe=1e-6,Vvt=(t,e)=>{const n=t.tracePath[0],o=t.tracePath.at(-1);return!n||!o?null:fb(n,e)?t.tracePath:fb(o,e)?[...t.tracePath].reverse():null},Gxo=(t,e)=>{const n=[],o=t[0];for(let i=0;i<t.length-1;i++){const r=t[i],s=t[i+1],a=JH(r,s);if(a)for(let A=0;A<e.length-1;A++){const c=e[A],l=e[A+1],u=JH(c,l);if(!u||u===a)continue;const g=V4(r,s,c,l);!g||fb(g,o)||n.push({intersectionPoint:g,targetSegmentIndex:i,donorSegmentIndex:A})}}return n},Yxo=(t,e,n)=>{const o=V4(t[e],t[e+1],t[n],t[n+1]);return o?Qa([...t.slice(0,e+1),o,...t.slice(n+1)]):t},Uxo=({targetTrace:t,targetPath:e,donorPath:n,crossing:o})=>{const i=Qa([...n.slice(0,o.donorSegmentIndex+1),o.intersectionPoint,...e.slice(o.targetSegmentIndex+1)]);return fb(t.tracePath[0],e[0])?i:i.reverse()},Kxo=({targetTrace:t,tracePath:e,netLabelPlacements:n})=>{const o=jH({trace:t,originalTracePath:t.tracePath,reroutedTracePath:e,netLabelPlacements:n});for(let s=0;s<n.length;s++){const a=n[s];if(a.globalConnNetId!==t.globalConnNetId||!jl(t.tracePath,a.anchorPoint))continue;const A=o[s];if(!jl(e,A.anchorPoint))return null}const i=o.filter(s=>s.globalConnNetId!==t.globalConnNetId);if(Ule({path:e,netLabelPlacements:i}))return null;const r=o.filter(s=>s.globalConnNetId===t.globalConnNetId);return Hvt({path:e,netLabelPlacements:r})?null:o},Vxo=(t,e)=>{if(!e)return!0;const n=t.netVisibleLength-e.netVisibleLength;return Math.abs(n)>owe?n<0:t.netVisibleSegmentCount<e.netVisibleSegmentCount},zxo=({targetTrace:t,traces:e,netLabelPlacements:n})=>{const o=e.filter(c=>c.globalConnNetId===t.globalConnNetId),i=Y7(o),r=Y7([t]);let s=null;const a=c=>{const l={...t,tracePath:c};if(Y7([l])>r+owe)return;const g=Kxo({targetTrace:t,tracePath:c,netLabelPlacements:n});if(!g)return;const h=o.map(m=>m.mspPairId===t.mspPairId?l:m),d=Y7(h);if(d>=i-owe)return;const p={tracePath:c,netLabelPlacements:g,netVisibleLength:d,netVisibleSegmentCount:Qle(h)};Vxo(p,s)&&(s=p)},A=WH(t.tracePath,t.tracePath,{includeTerminalSegments:!0}).filter(({pathSegmentIndex:c,otherPathSegmentIndex:l})=>c<l);for(const c of A)a(Yxo(t.tracePath,c.pathSegmentIndex,c.otherPathSegmentIndex));for(const c of o){if(c.mspPairId===t.mspPairId)continue;const l=YN({donorTrace:c,branchTrace:t});if(!l)continue;const u=Vvt(t,l),g=Vvt(c,l);if(!u||!g)continue;const h=Gxo(u,g);for(const d of h){const p=Uxo({targetTrace:t,targetPath:u,donorPath:g,crossing:d});a(p)}}return s},Jxo=({traces:t,netLabelPlacements:e})=>{const n=[...t];let o=[...e],i=0,r=0;for(;r<n.length;){const s=n[r],a=zxo({targetTrace:s,traces:n,netLabelPlacements:o});if(!a){r++;continue}n[r]={...s,tracePath:a.tracePath},o=a.netLabelPlacements,i++,r=0}return{traces:n,netLabelPlacements:o,collapsedCycleCount:i}},iwe=.2,Wxo=.2,jxo=.05,zvt=.8,$xo=.05,qxo=t=>{const{netConnMap:e}=mB(t),n=new Set(t.chips.flatMap(o=>o.pins.map(i=>i.pinId)));return new Set([...n].filter(o=>{const i=e.getNetConnectedToId(o);return i?e.getIdsConnectedToNet(i).filter(r=>n.has(r)).length>2:!1}))},oE=(t,e)=>CB(t,e)?"x":Yy(t,e)?"y":null,rw=({trace:t,sharedPin:e})=>t.pins.find(n=>n.pinId!==e.pinId)??null,Ij=t=>{let e=null;for(let n=0;n<t.tracePath.length-1;n++){const o=t.tracePath[n],i=t.tracePath[n+1];CB(o,i)&&(!e||Math.abs(i.x-o.x)>Math.abs(e.end.x-e.start.x))&&(e={start:o,end:i})}return e},Xxo=({segment:t,sharedPin:e})=>{const n=Math.abs(t.start.x-e.x),o=Math.abs(t.end.x-e.x);return n<=o?t.start:t.end},Cj=({railY:t,pin:e})=>e._facingDirection==="y+"?t>e.y:e._facingDirection==="y-"?t<e.y:!1,Zxo=({railY:t,pin:e})=>e._facingDirection==="y+"?t>e.y:e._facingDirection==="y-"?t<e.y:!1,e3o=({branchTrace:t,sharedPin:e,otherPin:n})=>{if(n._facingDirection!=="x-"&&n._facingDirection!=="x+")return null;const i=(t.pins[0].pinId===e.pinId?t.tracePath:[...t.tracePath].reverse()).at(-2);return!i||!Uc(i.y,n.y)?null:(n._facingDirection==="x-"?i.x<n.x:i.x>n.x)?i:null},Jvt=(t,e)=>e.flatMap((n,o)=>Avt(n,t)&&jl(t.tracePath,n.anchorPoint)?[o]:[]),t3o=({trace:t,reroutedTracePath:e,netLabelPlacements:n,attachedLabelIndexes:o})=>{const i=o.map(a=>n[a]),r=jH({trace:t,originalTracePath:t.tracePath,reroutedTracePath:e,netLabelPlacements:i}),s=new Map(o.map((a,A)=>[a,r[A]]));return n.map((a,A)=>s.get(A)??a)},n3o=({donorTrace:t,branchTrace:e})=>{const n=YN({donorTrace:t,branchTrace:e});if(!n)return null;const o=rw({trace:t,sharedPin:n});if(!o)return null;const i=rw({trace:e,sharedPin:n});if(!i||Math.abs(n.y-i.y)>iwe)return null;const r=Ij(t);if(!r)return null;const s=Ij(e);if(s&&Uc(s.start.y,r.start.y))return null;const a=Cj({railY:r.start.y,pin:i}),A=Zxo({railY:r.start.y,pin:n})&&Math.abs(r.start.y-n.y)<=jxo;if(!a&&!A)return null;const c=Xxo({segment:r,sharedPin:n});if(!(o.x<c.x&&i.x>c.x||o.x>c.x&&i.x<c.x))return null;let u;if(!a&&A){const g=e3o({branchTrace:e,sharedPin:n,otherPin:i});if(!g)return null;u=Qa([{x:n.x,y:n.y},{x:c.x,y:n.y},{x:c.x,y:c.y},{x:g.x,y:c.y},{x:g.x,y:i.y},{x:i.x,y:i.y}])}else u=Qa([{x:n.x,y:n.y},{x:c.x,y:n.y},{x:c.x,y:c.y},{x:i.x,y:c.y},{x:i.x,y:i.y}]);return e.pins[0].pinId===n.pinId?u:[...u].reverse()},o3o=({donorTrace:t,branchTrace:e})=>{const n=YN({donorTrace:t,branchTrace:e});if(!n)return null;const o=rw({trace:t,sharedPin:n}),i=rw({trace:e,sharedPin:n});if(!o||!i)return null;const r=n._facingDirection,s=nwe(n);if(!r||!s)return null;const a=s==="x"?"y":"x";if(o.chipId!==n.chipId||o._facingDirection!==r||!Uc(o[s],n[s])||nwe(i)!==a)return null;const A=Math.abs(o[a]-n[a]);if(A>iwe&&!Uc(A,iwe))return null;const c=e.pins[0].pinId===n.pinId;let l=Qa(e.tracePath);if(c||l.reverse(),l.length<2)return null;const u=[l[0],l[1]],g=Hxo({donorPath:t.tracePath,branchDepartureSegment:u,sharedPin:n,adjacentPin:o});if(!g)return null;const h=o[a];if(!Ovt({coordinate:h,axis:a,pin:i}))return null;const d={...g.sharedPinExit,[a]:h},p={x:i.x,y:i.y,[a]:h},m=Qa([{x:n.x,y:n.y},g.sharedPinExit,d,p,{x:i.x,y:i.y}]);return c?m:m.reverse()},i3o=({donorTrace:t,branchTrace:e,netLabelConnectorTraceIds:n})=>{if(n.has(t.mspPairId)||n.has(e.mspPairId))return null;const o=YN({donorTrace:t,branchTrace:e});if(!o)return null;const i=B=>{const S=Qa(B.tracePath);return B.pins[0].pinId===o.pinId?S:[...S].reverse()},r=i(t),s=i(e);if(r.length<3||s.length<4)return null;const a=oE(r[0],r[1]),A=oE(s[0],s[1]);if(!a||a!==A)return null;const c=r[1][a]-r[0][a],l=s[1][A]-s[0][A];if(Math.sign(c)!==Math.sign(l))return null;let u=1,g=oE(r[1],r[2]),h=oE(s[1],s[2]);if(!g||g!==h||g===a||(g==="x"&&Uc(r[1].y,s[1].y)||g==="y"&&Uc(r[1].x,s[1].x))&&(u++,!r[u+2]||!s[u+2]||(g=oE(r[u],r[u+1]),h=oE(s[u],s[u+1]),!g||g!==h)))return null;let p=0;for(let B=1;B<s.length-2;B++)oE(s[B],s[B+1])===h&&p++;if(p!==1)return null;const m=g==="x"?"y":"x",_=r[u][m],f=s[u][m],I=Math.abs(_-f);if(Uc(_,f)||I>zvt)return null;const C=[r[u][g],r[u+1][g]].sort((B,S)=>B-S),y=[s[u][h],s[u+1][h]].sort((B,S)=>B-S);if(!(Math.min(C[1],y[1])>=Math.max(C[0],y[0])-1e-6))return null;const E=Qa(s.map((B,S)=>S===u||S===u+1?{...B,[m]:_}:B));return e.pins[0].pinId===o.pinId?E:E.reverse()},r3o=({donorTrace:t,connectorTrace:e,netLabelConnectorTraceIds:n})=>{if(n.has(t.mspPairId)||!n.has(e.mspPairId))return null;const o=a=>{if(a.length<3)return null;const A=a[0],c=a[1],l=a[2],u=oE(A,c),g=oE(c,l);if(!u||!g||u===g)return null;const h=t.tracePath.findIndex((y,x,E)=>{const B=E[x+1];return B&&oE(y,B)===u&&jl([y,B],A)&&jl([y,B],c)});if(h<0)return null;const d=t.tracePath[h],p=t.tracePath[h+1];if(Uc(A.x,d.x)&&Uc(A.y,d.y)||Uc(A.x,p.x)&&Uc(A.y,p.y))return null;const m=[h>0?[t.tracePath[h-1],d]:null,h+2<t.tracePath.length?[p,t.tracePath[h+2]]:null].flatMap(y=>y&&oE(y[0],y[1])===g?[y]:[]);if(m.length===0)return null;const _=g==="x"?"y":"x",f=c[_],I=[c[g],l[g]].sort((y,x)=>y-x),C=m.map(y=>({segment:y,coordinate:y[0][_],offset:Math.abs(y[0][_]-f)})).filter(({segment:y,offset:x})=>{if(x>zvt)return!1;const E=[y[0][g],y[1][g]].sort((Q,w)=>Q-w),B=Math.max(E[0],I[0]),S=Math.min(E[1],I[1]);return S>=B-1e-6&&Math.abs(S-B)<=1e-6}).sort((y,x)=>y.offset-x.offset)[0];return!C||Uc(C.offset,0)?null:Qa(a.map((y,x)=>x===1||x===2?{...y,[_]:C.coordinate}:y))},i=Qa(e.tracePath),r=o(i);if(r)return r;const s=o([...i].reverse());return s?s.reverse():null},rwe=(t,e)=>{if(t.some(n=>jl(e,n))||e.some(n=>jl(t,n)))return!0;for(let n=1;n<t.length;n++)for(let o=1;o<e.length;o++)if(V4(t[n-1],t[n],e[o-1],e[o]))return!0;return!1},s3o=({originalTrace:t,candidateTrace:e,traces:n})=>{let o=n.map(i=>i.mspPairId===t.mspPairId?e:i);for(const i of n){if(i.mspPairId===t.mspPairId||i.globalConnNetId!==t.globalConnNetId||!rwe(t.tracePath,i.tracePath)||rwe(e.tracePath,i.tracePath))continue;const r=[0,i.tracePath.length-1].find(u=>jl(t.tracePath,i.tracePath[u]));if(r===void 0)return null;const s=i.tracePath[r];if(i.pins.some(u=>Uc(u.x,s.x)&&Uc(u.y,s.y)))return null;const a=zve(s,t.tracePath,e.tracePath);if(!a)return null;const A=r===0?1:r-1,c=i.tracePath[A];if(!c||oE(s,c)!==oE(a,c))return null;const l={...i,tracePath:i.tracePath.map((u,g)=>g===r?a:u)};if(!rwe(e.tracePath,l.tracePath))return null;o=o.map(u=>u.mspPairId===i.mspPairId?l:u)}return o},Wvt=({trace:t,endpointPin:e})=>{const n=rw({trace:t,sharedPin:e});if(!n)return null;const o=t.pins[0].pinId===e.pinId;let i=Qa(t.tracePath);if(o||i.reverse(),i.length!==3)return null;const[r,s,a]=i,A=e._facingDirection;if(A==="y+"||A==="y-")return n._facingDirection!=="x+"&&n._facingDirection!=="x-"||!Yy(r,s)||!CB(s,a)||!Cj({railY:s.y,pin:e})?null:(n._facingDirection==="x-"?s.x<n.x:s.x>n.x)?{railCoordinate:s.y}:null;if(A!=="x+"&&A!=="x-"||n._facingDirection!=="y+"&&n._facingDirection!=="y-"||!CB(r,s)||!Yy(s,a))return null;const c=A==="x+"?s.x>e.x:s.x<e.x,l=n._facingDirection==="y+"?s.y>n.y:s.y<n.y;return c&&l?{railCoordinate:s.x}:null},a3o=({donorTrace:t,branchTrace:e,traces:n})=>{const o=YN({donorTrace:t,branchTrace:e});if(!o)return null;const i=rw({trace:e,sharedPin:o});if(!i)return null;const r=f=>n.filter(I=>I.mspPairId!==e.mspPairId&&I.globalConnNetId===e.globalConnNetId&&I.pinIds.includes(f.pinId)),s=r(o),a=r(i);if(s.length!==1||s[0].mspPairId!==t.mspPairId||a.length!==1)return null;const A=Wvt({trace:t,endpointPin:o});if(!A)return null;const c=o._facingDirection,l=c==="y+"||c==="y-";if(!l&&!(c==="x+"||c==="x-")||l!==(i._facingDirection==="y+"||i._facingDirection==="y-"))return null;const g=e.pins[0].pinId===o.pinId;let h=Qa(e.tracePath);if(g||h.reverse(),h.length!==6)return null;const d=l?["V","H","V","H","V"]:["H","V","H","V","H"];if(h.slice(1).map((f,I)=>CB(h[I],f)?"H":Yy(h[I],f)?"V":"D").some((f,I)=>f!==d[I]))return null;const m=Wvt({trace:a[0],endpointPin:i});if(!m)return null;const _=Qa(l?[{x:o.x,y:o.y},{x:o.x,y:A.railCoordinate},{x:h[2].x,y:A.railCoordinate},{x:h[3].x,y:m.railCoordinate},{x:i.x,y:m.railCoordinate},{x:i.x,y:i.y}]:[{x:o.x,y:o.y},{x:A.railCoordinate,y:o.y},{x:A.railCoordinate,y:h[2].y},{x:m.railCoordinate,y:h[3].y},{x:m.railCoordinate,y:i.y},{x:i.x,y:i.y}]);return g?_:_.reverse()},jvt=({candidateTrace:t,originalTrace:e,traces:n,inputProblem:o,originalNetLabelPlacements:i,candidateNetLabelPlacements:r,attachedLabelIndexes:s})=>{const a=Hy(o);if(ON(t.tracePath,a))return!1;const A=n.filter(d=>d.globalConnNetId!==t.globalConnNetId);if(nw(t.tracePath,A))return!1;for(const d of A){const p=m=>{const _=new Set;for(let f=1;f<m.length;f++)for(let I=1;I<d.tracePath.length;I++){const C=V4(m[f-1],m[f],d.tracePath[I-1],d.tracePath[I]);C&&_.add(`${C.x.toFixed(6)},${C.y.toFixed(6)}`)}return _.size};if(p(t.tracePath)>p(e.tracePath))return!1}if(!s.every(d=>jl(t.tracePath,r[d].anchorPoint)))return!1;const c=(d,p)=>Ule({path:p.tracePath,netLabelPlacements:[d]});for(const d of s){const p=i[d],m=r[d],_=Ls(p.center,p.width,p.height),f=Ls(m.center,m.width,m.height);for(const I of n)if(I.globalConnNetId!==m.globalConnNetId&&c(m,I)&&!c(p,I))return!1;for(const I of a)if(yB(f,I)&&!yB(_,I))return!1;for(let I=0;I<r.length;I++){if(I===d)continue;const C=i[I],y=r[I],x=Ls(C.center,C.width,C.height),E=Ls(y.center,y.width,y.height);if(yB(f,E)&&!yB(_,x))return!1}}const l=r.filter(d=>d.globalConnNetId!==t.globalConnNetId);if(Ule({path:t.tracePath,netLabelPlacements:l}))return!1;const u=r.filter(d=>d.globalConnNetId===t.globalConnNetId);if(!Ule({path:t.tracePath,netLabelPlacements:u}))return!0;if(Hvt({path:t.tracePath,netLabelPlacements:u}))return!1;const g=Ij(e),h=Ij(t);return!g||!h?!1:Math.abs(g.start.y-h.start.y)<=Wxo},A3o=({donorTrace:t,branchTrace:e,returnStemScale:n=1})=>{const o=YN({donorTrace:t,branchTrace:e});if(!o)return null;const i=rw({trace:t,sharedPin:o}),r=rw({trace:e,sharedPin:o});if(!i||!r)return null;const s=o._facingDirection;if(s!=="y+"&&s!=="y-"||i._facingDirection!==s||r._facingDirection!==s||!Uc(o.y,i.y))return null;const a=Qa(t.tracePath);if(a.length!==4)return null;const A=Ij(t);if(!A||!Cj({railY:A.start.y,pin:o})||!Yy(a[0],a[1])||!Yy(a[2],a[3]))return null;const c=e.pins[0].pinId===o.pinId,l=Qa(c?e.tracePath:[...e.tracePath].reverse());if(l.length!==6||!Yy(l[0],l[1])||!CB(l[1],l[2])||!Yy(l[2],l[3])||!CB(l[3],l[4])||!Yy(l[4],l[5])||!Cj({railY:l[1].y,pin:o})||!Cj({railY:l[4].y,pin:r})||(s==="y+"?1:-1)*(r.y-A.start.y)<=0)return null;const g=Math.min(o.x,i.x),h=Math.max(o.x,i.x);if(l[2].x<g||l[2].x>h||Uc(l[2].x,i.x)&&Uc(l[1].y,A.start.y))return null;const d=r.y+(l[4].y-r.y)*n;if(Math.abs(d-r.y)<$xo-1e-6)return null;const p=Qa([{x:o.x,y:o.y},{x:o.x,y:A.start.y},{x:i.x,y:A.start.y},{x:i.x,y:d},{x:r.x,y:d},{x:r.x,y:r.y}]);return c?p:p.reverse()},c3o=({inputProblem:t,traces:e,netLabelPlacements:n,netLabelConnectorTraceIds:o})=>{let i=[...e],r=[...n],s=0;const a=new Set;for(const c of[!1,!0]){const l=e.map(g=>g.mspPairId),u=new Set(l);for(let g=0;g<l.length;g++){const h=l[g];u.delete(h);const d=i.find(p=>p.mspPairId===h);for(const p of i){if(a.has(p.mspPairId)||d.mspPairId===p.mspPairId||d.globalConnNetId!==p.globalConnNetId)continue;const m=o.has(d.mspPairId),f=o.has(p.mspPairId)?c&&!m?[r3o({donorTrace:d,connectorTrace:p,netLabelConnectorTraceIds:o})]:[]:m?[]:c?[...[1,.5,.25].map(I=>A3o({donorTrace:d,branchTrace:p,returnStemScale:I})),a3o({donorTrace:d,branchTrace:p,traces:i}),i3o({donorTrace:d,branchTrace:p,netLabelConnectorTraceIds:o})]:[n3o({donorTrace:d,branchTrace:p}),o3o({donorTrace:d,branchTrace:p})];for(const I of f){if(!I)continue;const C={...p,tracePath:I},y=[d,p],x=[d,C],E=Qle(x)<Qle(y),B=Y7(x)<Y7(y)&&!Uc(Y7(x),Y7(y));if(!E&&!B)continue;const S=Jvt(p,r),Q=t3o({trace:p,reroutedTracePath:I,netLabelPlacements:r,attachedLabelIndexes:S}),w=s3o({originalTrace:p,candidateTrace:C,traces:i});if(!(!w||!jvt({candidateTrace:C,originalTrace:p,traces:w,inputProblem:t,originalNetLabelPlacements:r,candidateNetLabelPlacements:Q,attachedLabelIndexes:S})||!w.every(k=>{if(k.mspPairId===p.mspPairId)return!0;const R=i.find(F=>F.mspPairId===k.mspPairId);return R.tracePath===k.tracePath?!0:jvt({candidateTrace:k,originalTrace:R,traces:w,inputProblem:t,originalNetLabelPlacements:r,candidateNetLabelPlacements:Q,attachedLabelIndexes:Jvt(R,r)})}))){i=w,r=Q,a.add(p.mspPairId),s++,u.has(p.mspPairId)||(l.push(p.mspPairId),u.add(p.mspPairId));break}}}}}const A=Jxo({traces:i,netLabelPlacements:r});return i=Oxo({traces:A.traces,netLabelPlacements:A.netLabelPlacements,netLabelConnectorTraceIds:o,multiPinNetPinIds:qxo(t)}),r=A.netLabelPlacements,{traces:i,netLabelPlacements:r,alignedJunctionCount:s,collapsedCycleCount:A.collapsedCycleCount}},l3o=({inputProblem:t,traces:e,netLabelPlacements:n})=>{const{netConnMap:o}=mB(t),i=o.getNetConnectedToId("GND");if(!i)return n;const r=new Map(t.chips.map(c=>[c.chipId,c])),s=Object.fromEntries(e.map(c=>[c.mspPairId,c])),a=Hy(t),A=[...n];for(const c of e){if(c.globalConnNetId!==i)continue;const[l,u]=c.pins;if(l.chipId===u.chipId||!Uc(l.y,u.y)||![l,u].every(h=>h._facingDirection==="y-"&&r.get(h.chipId)?.pins.length===2))continue;const g=Qa(c.tracePath);if(!(g.length!==4||!Yy(g[0],g[1])||!CB(g[1],g[2])||!Yy(g[2],g[3])||g[1].y>=l.y))for(const h of e){if(h.globalConnNetId!==i)continue;const d=h.pins.find(f=>c.pinIds.includes(f.pinId)),p=h.pins.find(f=>!c.pinIds.includes(f.pinId)&&(r.get(f.chipId)?.pins.length??0)>2);if(!d||!p||!Uc(p.y,g[1].y))continue;const m=d.pinId===l.pinId?u:l;if(Math.abs(m.x-p.x)<=Math.abs(d.x-p.x))continue;const _={x:m.x,y:g[1].y};if(jl(c.tracePath,_))for(let f=0;f<A.length;f++){const I=A[f];if(I.globalConnNetId!==i||I.orientation!=="y-"||!I.mspConnectionPairIds.some(x=>x===h.mspPairId||x===c.mspPairId)||!jl(h.tracePath,I.anchorPoint)&&!jl(c.tracePath,I.anchorPoint))continue;const C=IC(_,I.orientation,I.width,I.height),y=Ls(C,I.width,I.height);a.some(x=>yB(y,x))||mj(y,s)||A.some((x,E)=>E!==f&&yB(y,Ls(x.center,x.width,x.height)))||(A[f]={...I,anchorPoint:_,center:C,mspConnectionPairIds:[c.mspPairId],pinIds:[...c.pinIds]})}}}for(let c=0;c<A.length;c++){const l=A[c];if(l.orientation!=="y-"||!t.netConnections.find(p=>p.isGround&&p.netId===l.netId&&p.pinIds.length>2))continue;const g=e.filter(p=>p.globalConnNetId===l.globalConnNetId).flatMap(p=>p.tracePath).filter(p=>Uc(p.x,l.anchorPoint.x)&&p.y<l.anchorPoint.y).sort((p,m)=>p.y-m.y)[0];if(!g)continue;const h=IC(g,l.orientation,l.width,l.height),d=Ls(h,l.width,l.height);a.some(p=>yB(d,p))||mj(d,s)||A.some((p,m)=>m!==c&&yB(d,Ls(p.center,p.width,p.height)))||(A[c]={...l,anchorPoint:g,center:h})}return A},u3o=class extends Ng{input;outputTraces;outputNetLabelPlacements;constructor(t){super(),this.input=t,this.outputTraces=t.traces,this.outputNetLabelPlacements=t.netLabelPlacements}_step(){const t=c3o(this.input);this.outputTraces=t.traces,this.outputNetLabelPlacements=l3o({inputProblem:this.input.inputProblem,traces:t.traces,netLabelPlacements:t.netLabelPlacements}),this.stats.alignedJunctionCount=t.alignedJunctionCount,this.stats.collapsedCycleCount=t.collapsedCycleCount,this.solved=!0}getOutput(){return{traces:this.outputTraces,netLabelPlacements:this.outputNetLabelPlacements}}visualize(){const t=zh(this.input.inputProblem);t.lines??=[],t.rects??=[],t.points??=[];for(const e of this.outputTraces)t.lines.push({points:e.tracePath,strokeColor:"purple"});for(const e of this.outputNetLabelPlacements){const n={center:e.center,width:e.width,height:e.height,fill:Mc(e.globalConnNetId,.35),strokeColor:Mc(e.globalConnNetId,.9),label:`netId: ${e.netId}
globalConnNetId: ${e.globalConnNetId}`};t.rects.push(n),t.points.push({x:e.anchorPoint.x,y:e.anchorPoint.y,color:Mc(e.globalConnNetId,.9),label:`anchorPoint
orientation: ${e.orientation}`})}return t}},$vt=t=>{const e=Qa(t);if(e.length!==6)return!1;const n=e.slice(0,-1).map((o,i)=>X_(o,e[i+1]));return n.every((o,i)=>i===0||o!==n[i-1])},g3o=({trace:t,label:e,paddingBuffer:n,detourCount:o})=>{if(t.globalConnNetId===e.globalConnNetId)return[];const i=Qa(t.tracePath);if(!$vt(i))return[];const r=Ls(e.center,e.width,e.height),s=n+o*n,a={minX:r.minX-s,maxX:r.maxX+s,minY:r.minY-s,maxY:r.maxY+s},A=[];for(let c=1;c<i.length-2;c++){const l=i[c],u=i[c+1];if(!CC(l,u,r))continue;const g=X_(l,u),h=e1(l,u);if(!g&&!h)continue;const d=g?"y":"x",p=g?[a.minY,a.maxY]:[a.minX,a.maxX];for(const m of p){const _=Dve(i,c,d,m);_&&A.push(_)}}return A},d3o=({trace:t,label:e,paddingBuffer:n,detourCount:o})=>{const i=Qa(t.tracePath);if(!$vt(i))return[];const r=Ls(e.center,e.width,e.height),s=n+o*n,a={minX:r.minX-s,maxX:r.maxX+s,minY:r.minY-s,maxY:r.maxY+s},A=i[0],c=i[i.length-1],l=2,u=[];for(let g=0;g<i.length-1;g++){const h=i[g],d=i[g+1];if(!CC(h,d,r)||Math.abs(g-l)!==1)continue;const p=X_(h,d),m=e1(h,d);if(!p&&!m)continue;const _=p?"x":"y",f=p?a.minX:a.minY,I=p?a.maxX:a.maxY,C=p?A.x:A.y,y=p?c.x:c.y,x=[];C<f?x.push((C+f)/2):C>I&&x.push((C+I)/2),y<f?x.push((y+f)/2):y>I&&x.push((y+I)/2);for(const E of new Set(x)){const B=Dve(i,l,_,E);B&&u.push(B)}}return u},h3o=({trace:t,label:e,netLabelPlacements:n,paddingBuffer:o,detourCount:i})=>d3o({trace:t,label:e,paddingBuffer:o,detourCount:i}).flatMap(s=>{const a={...t,tracePath:s};return Jh({traces:[a],netLabels:n}).flatMap(({label:c})=>g3o({trace:a,label:c,paddingBuffer:o,detourCount:i}))}),qvt=1e-9,ZH=t=>t.slice(1).reduce((e,n,o)=>{const i=t[o];return e+Math.abs(n.x-i.x)+Math.abs(n.y-i.y)},0),swe=class extends Ng{input;outputTraces;traceIdQueue;obstacles;constructor(t){super(),this.input=t,this.outputTraces=[...t.traces];const e=new Set(t.completedReroutes.map(n=>n.initialTrace.mspPairId));this.traceIdQueue=t.traces.map(n=>n.mspPairId).filter(n=>e.has(n)),this.obstacles=Hy(t.inputProblem)}_step(){const t=this.traceIdQueue.shift();if(!t){this.solved=!0;return}const e=this.outputTraces.findIndex(h=>h.mspPairId===t),n=this.outputTraces[e],o=Qa(n.tracePath),i=Jh({traces:[{...n,tracePath:o}],netLabels:this.input.netLabelPlacements}),r=this.outputTraces.filter(h=>h.mspPairId!==n.mspPairId&&h.globalConnNetId!==n.globalConnNetId),s=new Map,a=this.input.completedReroutes.filter(h=>h.initialTrace.mspPairId===n.mspPairId);for(const h of a){const d=Qa(h.initialTrace.tracePath),p=Qa(h.reroutedTracePath),m=Jh({traces:[{...h.initialTrace,tracePath:d}],netLabels:this.input.netLabelPlacements}).length,_=h3o({trace:h.initialTrace,label:h.label,netLabelPlacements:this.input.netLabelPlacements,paddingBuffer:this.input.paddingBuffer,detourCount:h.detourCount});for(const f of _){const I=Qa(f),C={...h.initialTrace,tracePath:I};Jh({traces:[C],netLabels:this.input.netLabelPlacements}).length<m&&Math.abs(ZH(I)-ZH(p))<qvt&&I.length<p.length&&hj(this.input.netLabelPlacements,[h.initialTrace],[C])&&s.set(I.map(E=>`${E.x},${E.y}`).join(";"),I)}}const A=new Set(i.map(({label:h})=>`${h.globalConnNetId}:${h.netId}`)),c=ZH(o),l=[...s.values()].filter(h=>{const d={...n,tracePath:h},p=Jh({traces:[d],netLabels:this.input.netLabelPlacements}),m=p.every(({label:I})=>A.has(`${I.globalConnNetId}:${I.netId}`)),_=p.length<i.length,f=p.length===i.length&&ZH(h)<=c+qvt&&h.length<o.length;return m&&(_||f)&&hj(this.input.netLabelPlacements,[n],[d])&&!ON(h,this.obstacles)&&!nw(h,r)}),u=h=>Jh({traces:[{...n,tracePath:h}],netLabels:this.input.netLabelPlacements}).length;l.sort((h,d)=>{const p=u(h)-u(d);return p!==0?p:ZH(h)-ZH(d)||h.length-d.length});const g=l[0];g&&(this.outputTraces[e]={...n,tracePath:g},this.stats.simplifiedTraceCount=(this.stats.simplifiedTraceCount??0)+1)}getOutput(){return{traces:this.outputTraces,netLabelPlacements:this.input.netLabelPlacements}}visualize(){const t=zh(this.input.inputProblem);t.lines??=[];for(const e of this.outputTraces)t.lines.push({points:e.tracePath,strokeColor:"purple"});return t}},Xvt=t=>{if(!t.stubTracePath)return null;const e=1e-6;return{minX:Math.min(...t.stubTracePath.map(n=>n.x))-e,maxX:Math.max(...t.stubTracePath.map(n=>n.x))+e,minY:Math.min(...t.stubTracePath.map(n=>n.y))-e,maxY:Math.max(...t.stubTracePath.map(n=>n.y))+e}},awe=(t,e)=>{const n=e.map(i=>({globalConnNetId:i.globalConnNetId,netId:i.netId,pinIds:i.pinIds,mspConnectionPairIds:[],anchorPoint:i.anchorPoint,orientation:"y+",center:i.center,width:i.axis==="x"?i.width:i.height,height:i.axis==="x"?i.height:i.width})),o=e.flatMap(i=>{if(!i.stubTracePath)return[];const r=t.chips.find(A=>A.pins.some(c=>i.pinIds.includes(c.pinId))),s=r?.pins.find(A=>i.pinIds.includes(A.pinId));if(!r||!s)return[];const a=JSON.stringify(["inline-terminal",i.globalConnNetId,[...i.pinIds].sort()]);return[{mspPairId:a,mspConnectionPairIds:[a],globalConnNetId:i.globalConnNetId,dcConnNetId:i.globalConnNetId,pinIds:i.pinIds,pins:[{...s,chipId:r.chipId},{...s,...i.stubTracePath[1],chipId:r.chipId}],tracePath:i.stubTracePath}]});return{fixedLabels:n,terminalTraces:o}},xC=1e-6,iE=.05,UN=(t,e)=>t.slice(1).some((n,o)=>CC(t[o],n,e)),Zvt=(t,e)=>Math.hypot(t.x-e.x,t.y-e.y)<xC,KN=(t,e,n)=>({...t,[e]:t[e]+n}),Awe=(t,e)=>t.slice(1).flatMap((n,o)=>e.slice(1).flatMap((i,r)=>{const s=V4(t[o],n,e[r],i);return s?[s]:[]}));function*ewt(t,e,n=[]){const o=[...e.inlineNetLabelPlacements,...n],{fixedLabels:i,terminalTraces:r}=awe(t,o),s=o.flatMap(l=>{const u=Xvt(l);return u?[{label:l,bounds:u}]:[]}),a=[...t.chips.map(l=>({minX:l.center.x-l.width/2,maxX:l.center.x+l.width/2,minY:l.center.y-l.height/2,maxY:l.center.y+l.height/2})),...(t.textBoxes??[]).map(l=>fB(l))],A=i.map(l=>({minX:l.center.x-l.width/2,maxX:l.center.x+l.width/2,minY:l.center.y-l.height/2,maxY:l.center.y+l.height/2})),c=[...t.chips.flatMap(l=>l.pins),...e.traces.flatMap(l=>l.pins)];for(const l of e.traces){const u=Qa(l.tracePath);for(let g=0;g<u.length-1;g++){const h=u[g],d=u[g+1],p=Math.abs(h.x-d.x)<xC?"x":"y",m=p==="x"?"y":"x";if(Math.abs(h[p]-d[p])>xC||Zvt(h,d))continue;const _=[...e.netLabelPlacements.filter(w=>w.globalConnNetId!==l.globalConnNetId).map(yp),...A,...s.filter(({label:w})=>!l.pinIds.some(M=>w.pinIds.includes(M))).map(({bounds:w})=>w)].filter(w=>CC(h,d,w));if(!_.length)continue;let f=Math.min(h[m],d[m]),I=Math.max(h[m],d[m]),C=!0;for(;C;){C=!1;for(const w of e.traces)if(w.globalConnNetId===l.globalConnNetId)for(let M=1;M<w.tracePath.length;M++){const k=w.tracePath[M-1],R=w.tracePath[M];if(Math.abs(k[p]-h[p])>xC||Math.abs(R[p]-h[p])>xC)continue;const F=Math.min(k[m],R[m]),O=Math.max(k[m],R[m]);O<f-xC||F>I+xC||((F<f||O>I)&&(C=!0),f=Math.min(f,F),I=Math.max(I,O))}}const y=w=>Math.abs(w[p]-h[p])<xC&&w[m]>=f-xC&&w[m]<=I+xC;if(c.some(y))continue;const x=p==="x"?"minX":"minY",E=p==="x"?"maxX":"maxY",B=Math.max(..._.map(w=>w[E]-w[x])),S=e.netLabelPlacements.filter(w=>w.globalConnNetId===l.globalConnNetId&&y(w.anchorPoint)).map(yp),Q=[...new Set(_.flatMap(w=>[w[x]-iE,w[E]+iE,...S.filter(M=>Dc(M,w)).flatMap(M=>[h[p]+w[x]-iE-M[E],h[p]+w[E]+iE-M[x]])]))].sort((w,M)=>Math.abs(w-h[p])-Math.abs(M-h[p]));for(const w of Q){const M=w-h[p];if(Math.abs(M)>B+2*iE)continue;const k=e.traces.map(Y=>Y.globalConnNetId!==l.globalConnNetId||!Y.tracePath.some(y)?Y:{...Y,tracePath:Y.tracePath.map(W=>y(W)?KN(W,p,M):W)}),R=k.filter((Y,W)=>Y!==e.traces[W]).map(Y=>Y.tracePath);let F=e.netLabelPlacements.map(Y=>Y.globalConnNetId!==l.globalConnNetId||!y(Y.anchorPoint)?Y:{...Y,anchorPoint:KN(Y.anchorPoint,p,M),center:KN(Y.center,p,M)}),O=!1;const U=F.flatMap((Y,W)=>Y!==e.netLabelPlacements[W]?[yp(Y)]:[]);for(const[Y,W]of F.entries()){if(W.globalConnNetId===l.globalConnNetId)continue;const te=yp(W),j=U.filter(ue=>Dc(ue,te)).map(ue=>ue[M>0?E:x]);if(R.some(ue=>UN(ue,te))&&!e.traces.some(ue=>ue.globalConnNetId===l.globalConnNetId&&UN(ue.tracePath,te))&&j.push(w),!j.length)continue;const J=k.findIndex(ue=>ue.globalConnNetId===W.globalConnNetId&&ue.pinIds.length===1&&ue.tracePath.length===3&&Zvt(ue.tracePath.at(-1),W.anchorPoint)),oe=k[J];if(!oe){const fe=new ewe({inputProblem:t,traces:[...k,...r],netLabelPlacements:F,fixedNetLabelPlacements:i,useRenderedLabelBounds:!0}).getNearbyValidPlacements(W,B+Math.max(W.width,W.height))[0];if(!fe){O=!0;break}F[Y]=fe;continue}const[ie,ne,le]=oe.tracePath;if(Math.abs(ne[p]-le[p])>xC||Math.abs(ie[m]-ne[m])>xC){O=!0;break}const ge=M>0?Math.max(...j)+iE-te[x]:Math.min(...j)-iE-te[E];if(Math.abs(ge)>B+te[E]-te[x]+2*iE){O=!0;break}const _e={...W,anchorPoint:KN(W.anchorPoint,p,ge),center:KN(W.center,p,ge)};F[Y]=_e,k[J]={...oe,tracePath:[ie,KN(ne,p,ge),_e.anchorPoint]}}if(!O){for(const[Y,W]of k.entries()){if(W.globalConnNetId===l.globalConnNetId||Qa(W.tracePath).length<=4||!R.some(j=>nw(j,[W])))continue;const te=YQt({inputProblem:t,traces:[...k,...r],targetMspConnectionPairId:W.mspPairId,allLabelPlacements:[...F,...i],mergedLabelNetIdMap:{},paddingBuffer:iE});Qa(te.tracePath).length<Qa(W.tracePath).length&&hj(F,[W],[te])&&(k[Y]=te)}for(const[Y,W]of k.entries()){const te=e.traces[Y];if(W===te)continue;const j=W.tracePath,J=te.tracePath;if(j.slice(1).some((le,ge)=>Math.abs(le.x-j[ge].x)>xC&&Math.abs(le.y-j[ge].y)>xC)){O=!0;break}const oe=(le,ge,_e,ue)=>(ge.x-le.x)*(ue.x-_e.x)+(ge.y-le.y)*(ue.y-_e.y);if(oe(J[0],J[1],j[0],j[1])<=xC||oe(J.at(-1),J.at(-2),j.at(-1),j.at(-2))<=xC){O=!0;break}const ie=e.traces.filter(le=>le!==te&&le.globalConnNetId===te.globalConnNetId).flatMap(le=>[...le.tracePath,...Awe(J,le.tracePath)]).filter(le=>jl(J,le)).map(le=>te.globalConnNetId===l.globalConnNetId&&y(le)?KN(le,p,M):le);if([...c.filter(le=>jl(J,le)),...ie].some(le=>!jl(j,le))||c.some(le=>{const ge={minX:le.x-iE,maxX:le.x+iE,minY:le.y-iE,maxY:le.y+iE};return UN(j,ge)&&!UN(J,ge)})||a.some(le=>UN(j,le)&&!UN(J,le))){O=!0;break}for(const le of[...k,...r]){if(le.mspPairId===W.mspPairId||le.globalConnNetId===W.globalConnNetId)continue;const ge=e.traces.find(_e=>_e.mspPairId===le.mspPairId)??le;if(nw(j,[le])||Awe(j,le.tracePath).length>Awe(J,ge.tracePath).length){O=!0;break}}if(O)break}if(!O){for(const[Y,W]of F.entries()){if(W===e.netLabelPlacements[Y])continue;const te=yp(W);if(a.some(j=>Dc(te,j))||A.some(j=>Dc(te,j))){O=!0;break}if(F.some((j,J)=>Y!==J&&Dc(te,yp(j)))){O=!0;break}if([...k,...r].some(j=>j.globalConnNetId!==W.globalConnNetId&&UN(j.tracePath,te))){O=!0;break}}O||(yield{...e,traces:k,netLabelPlacements:F})}}}}}}var eO=(t,e)=>{const n=[...t.pinIds].sort(),o=[...e.pinIds].sort();return t.globalConnNetId===e.globalConnNetId&&n.length===o.length&&n.every((i,r)=>i===o[r])},twt=(t,e)=>t.kind==="label-label"&&e.kind==="label-label"?eO(t.labels[0],e.labels[0])&&eO(t.labels[1],e.labels[1])||eO(t.labels[0],e.labels[1])&&eO(t.labels[1],e.labels[0]):t.kind!=="trace-label"||e.kind!=="trace-label"?!1:(t.trace.kind==="routed"&&e.trace.kind==="routed"?t.trace.id===e.trace.id:t.trace.kind==="terminal"&&e.trace.kind==="terminal"&&eO(t.trace.label,e.trace.label))&&t.target===e.target&&eO(t.label,e.label),nwt=t=>{const e=[...t.netLabelPlacements,...t.inlineNetLabelPlacements].map(r=>({label:r,bounds:"axis"in r?{minX:r.center.x-(r.axis==="x"?r.width:r.height)/2,maxX:r.center.x+(r.axis==="x"?r.width:r.height)/2,minY:r.center.y-(r.axis==="x"?r.height:r.width)/2,maxY:r.center.y+(r.axis==="x"?r.height:r.width)/2}:yp(r)})),n=[],o=r=>{n.some(s=>twt(r,s))||n.push(r)};for(let r=0;r<e.length;r++)for(const s of e.slice(r+1))Dc(e[r].bounds,s.bounds)&&o({kind:"label-label",labels:[e[r].label,s.label]});const i=[...t.traces.map(r=>({...r,identity:{kind:"routed",id:r.mspPairId}})),...t.inlineNetLabelPlacements.flatMap(r=>r.stubTracePath?[{identity:{kind:"terminal",label:r},globalConnNetId:r.globalConnNetId,tracePath:r.stubTracePath}]:[])];for(const r of i)for(const{label:s,bounds:a}of e)("axis"in s||s.globalConnNetId!==r.globalConnNetId)&&r.tracePath.slice(1).some((A,c)=>CC(r.tracePath[c],A,a))&&o({kind:"trace-label",trace:r.identity,label:s,target:"text"});for(const r of t.inlineNetLabelPlacements){const s=Xvt(r);if(s)for(const a of t.traces)a.pinIds.some(A=>r.pinIds.includes(A))||a.tracePath.slice(1).some((A,c)=>CC(a.tracePath[c],A,s))&&o({kind:"trace-label",trace:{kind:"routed",id:a.mspPairId},label:r,target:"terminal"})}return n},cwe=(t,e)=>t.pinIds.length>0&&t.pinIds.every(n=>e.some(o=>o.globalConnNetId===t.globalConnNetId&&o.pinIds.includes(n))),p3o=t=>{const[e,n]=t;return Math.abs(n.x-e.x)>=Math.abs(n.y-e.y)?n.x>=e.x?"x+":"x-":n.y>=e.y?"y+":"y-"},m3o=t=>{const[e,n]=t;return Math.abs(n.x-e.x)+Math.abs(n.y-e.y)},zle=t=>{const e=t.axis==="y",n=e?t.height:t.width,o=e?t.width:t.height;return{minX:t.center.x-n/2,maxX:t.center.x+n/2,minY:t.center.y-o/2,maxY:t.center.y+o/2}},owt=t=>({minX:Math.min(...t.map(e=>e.x)),maxX:Math.max(...t.map(e=>e.x)),minY:Math.min(...t.map(e=>e.y)),maxY:Math.max(...t.map(e=>e.y))}),yj=(t,e)=>{for(let n=0;n<t.length-1;n++){const o=owt([t[n],t[n+1]]);if(Dc(o,e))return!0}return!1},_3o=(t,e,n)=>{const[o]=t.stubTracePath,i=e==="x+"?{x:o.x+n,y:o.y}:e==="x-"?{x:o.x-n,y:o.y}:e==="y+"?{x:o.x,y:o.y+n}:{x:o.x,y:o.y-n},r={x:(o.x+i.x)/2,y:(o.y+i.y)/2};return{...t,stubTracePath:[o,i],anchorPoint:r,center:t.center}},f3o=({placements:t,inputProblem:e,traces:n,netLabelPlacements:o})=>{const i=new Map;for(const A of e.chips)for(const c of A.pins)i.set(c.pinId,A.chipId);const r=new Map;for(const[A,c]of t.entries()){if(!c.stubTracePath||c.pinIds.length!==1)continue;const l=p3o(c.stubTracePath);if(!l)continue;const u=i.get(c.pinIds[0]),g=`${u??c.pinIds[0]}::${l}`,h=r.get(g)??[];h.push({placementIndex:A,placement:c,direction:l,ownerChipId:u}),r.set(g,h)}const s=[...t],a=o.filter(A=>!cwe(A,t)).map(zle);for(const A of r.values()){if(A.length<2)continue;const c=Math.max(...A.map(({placement:d})=>m3o(d.stubTracePath))),l=A.map(({placement:d,direction:p})=>_3o(d,p,c)),u=new Set(A.map(({placementIndex:d})=>d)),g=t.filter((d,p)=>!u.has(p));if(!l.some((d,p)=>{const m=zle(d),_=d.stubTracePath,f=owt(_),I=A[p].ownerChipId;for(const C of e.chips){const y={minX:C.center.x-C.width/2,maxX:C.center.x+C.width/2,minY:C.center.y-C.height/2,maxY:C.center.y+C.height/2};if(Dc(m,y)||C.chipId!==I&&Dc(f,y))return!0}for(const C of e.textBoxes??[]){const y=fB(C);if(Dc(m,y)||Dc(f,y))return!0}for(const C of n)if(C.globalConnNetId!==d.globalConnNetId&&(yj(C.tracePath,m)||yj(C.tracePath,f)))return!0;if(a.some(C=>Dc(m,C)||Dc(f,C)))return!0;for(const C of g){const y=zle(C);if(Dc(m,y)||Dc(f,y)||C.stubTracePath&&(yj(C.stubTracePath,m)||yj(_,y)))return!0}for(const[C,y]of l.entries()){if(C===p)continue;const x=zle(y);if(Dc(m,x)||yj(_,x))return!0}return!1}))for(const[d,{placementIndex:p}]of A.entries())s[p]=l[d]}return s},iwt=(t,e=1e-6)=>{const n=[];let o=null,i=null,r=0;const s=a=>{if(o&&i){const A=Math.abs(i==="x"?a.x-o.x:a.y-o.y);A>e&&n.push({start:o,end:a,axis:i,length:A})}o=null,i=null,r=0};for(let a=0;a<t.length-1;a++){const A=t[a],c=t[a+1],l=c.x-A.x,u=c.y-A.y;if(Math.abs(l)<=e&&Math.abs(u)<=e)continue;const g=Math.abs(u)<=e?"x":Math.abs(l)<=e?"y":null;if(!g){s(A);continue}const h=Math.sign(g==="x"?l:u);o&&i===g&&r===h||(s(A),o=A,i=g,r=h)}return t.length>=2&&s(t[t.length-1]),n.sort((a,A)=>A.length-a.length)},q5=.05,X5=1e-6,I3o=.01,rwt=5,C3o=t=>{const e=t.axis==="y"?t.height:t.width,n=t.axis==="y"?t.width:t.height;return{minX:t.center.x-e/2,maxX:t.center.x+e/2,minY:t.center.y-n/2,maxY:t.center.y+n/2}},xj=(t,e)=>Math.abs(t.x-e.x)<=X5&&Math.abs(t.y-e.y)<=X5,Ej=(t,e)=>{for(let n=0;n<t.length-1;n++){const o=t[n],i=t[n+1],r={minX:Math.min(o.x,i.x),maxX:Math.max(o.x,i.x),minY:Math.min(o.y,i.y),maxY:Math.max(o.y,i.y)};if(Dc(r,e))return!0}return!1},y3o=(t,e)=>{for(let n=0;n<e.length-1;n++){const o=e[n],i=e[n+1],r=Math.min(o.x,i.x)-X5,s=Math.max(o.x,i.x)+X5,a=Math.min(o.y,i.y)-X5,A=Math.max(o.y,i.y)+X5,c=Math.abs(o.y-i.y)<=X5,l=Math.abs(o.x-i.x)<=X5;if((c&&Math.abs(t.y-o.y)<=X5||l&&Math.abs(t.x-o.x)<=X5)&&t.x>=r&&t.x<=s&&t.y>=a&&t.y<=A)return!0}return!1},x3o=(t,e)=>{let n=0;for(let o=0;o<e.length;o++){const i=yp(Jle(t,t.orientation,n)),r=t.orientation==="x-"||t.orientation==="x+",s=e.filter(a=>Dc(i,{minX:a.minX-(r?q5:0),maxX:a.maxX+(r?q5:0),minY:a.minY-(r?0:q5),maxY:a.maxY+(r?0:q5)}));if(s.length===0)break;switch(t.orientation){case"x-":n+=i.maxX-Math.min(...s.map(a=>a.minX))+q5;break;case"x+":n+=Math.max(...s.map(a=>a.maxX))-i.minX+q5;break;case"y-":n+=i.maxY-Math.min(...s.map(a=>a.minY))+q5;break;case"y+":n+=Math.max(...s.map(a=>a.maxY))-i.minY+q5;break}}return n},Jle=(t,e,n)=>{const o=sm(e);return{...t,anchorPoint:{x:t.anchorPoint.x+o.x*n,y:t.anchorPoint.y+o.y*n},center:{x:t.center.x+o.x*n,y:t.center.y+o.y*n}}},E3o=(t,e,n)=>{switch(n){case"x-":return t.maxX-e.minX+q5;case"x+":return e.maxX-t.minX+q5;case"y-":return t.maxY-e.minY+q5;case"y+":return e.maxY-t.minY+q5}},B3o=(t,e,n)=>n==="x-"||n==="x+"?Math.max(0,t.minY-e.maxY,e.minY-t.maxY):Math.max(0,t.minX-e.maxX,e.minX-t.maxX),swt=(t,e,n)=>t.pinIds.some(o=>e.has(n.get(o)??"")),awt=(t,e,n)=>e.findIndex(o=>{if(o.globalConnNetId!==t.globalConnNetId||!n.has(o.mspPairId))return!1;const i=o.tracePath[0],r=o.tracePath.at(-1);return!!(i&&xj(i,t.anchorPoint)||r&&xj(r,t.anchorPoint))}),Awt=(t,e,n)=>t.pinIds.some(o=>{const i=n[o];return i&&xj(i,t.anchorPoint)})?!0:e.some(o=>o.globalConnNetId===t.globalConnNetId&&y3o(t.anchorPoint,o.tracePath)),b3o=(t,e,n)=>{const o=t.tracePath.map(i=>({...i}));return xj(o[0],e)&&(o[0]=n),xj(o.at(-1),e)&&(o[o.length-1]=n),{...t,tracePath:o}},S3o=({label:t,labelIndex:e,newAnchor:n,pinMap:o})=>{const i=`inline-net-label-clearance-${e}-${t.netId??t.globalConnNetId}`;return{mspPairId:i,dcConnNetId:t.dcConnNetId??t.globalConnNetId,globalConnNetId:t.globalConnNetId,userNetId:t.netId,pins:Vve(t,o),tracePath:[t.anchorPoint,n],mspConnectionPairIds:[i],pinIds:t.pinIds}},Q3o=({triggerIndex:t,labels:e,chipIdByPinId:n})=>{const o=e[t],i=new Set(o.pinIds.flatMap(A=>{const c=n.get(A);return c?[c]:[]})),r=e.map((A,c)=>({label:A,labelIndex:c})).filter(({label:A})=>A.orientation===o.orientation&&A.mspConnectionPairIds.length===0&&swt(A,i,n)),s=new Set([t]);let a=!0;for(;a;){a=!1;for(const{label:A,labelIndex:c}of r)s.has(c)||[...s].some(l=>B3o(yp(e[l]),yp(A),o.orientation)<=I3o)&&(s.add(c),a=!0)}return{group:s,ownerChipIds:i}},v3o=({inputProblem:t,traces:e,netLabelPlacements:n,inlineNetLabelPlacements:o,netLabelConnectorTraceIds:i=new Set})=>{const r=new Set(i),s=e.map(g=>({...g,tracePath:g.tracePath.map(h=>({...h}))})),a=n.map(g=>({...g})),A=o.map(C3o),c=Kve(t),l=new Map;for(const g of t.chips)for(const h of g.pins)l.set(h.pinId,g.chipId);const u=new Set;for(let g=0;g<a.length;g++){const h=a[g],d=x3o(h,A);if(d<=X5||d>rwt)continue;const{group:p,ownerChipIds:m}=Q3o({triggerIndex:g,labels:a,chipIdByPinId:l}),_=new Map([...p].map(x=>[x,d]));let f=!1;for(let x=0;x<a.length;x++){let E=!1;for(const[B,S]of _){const Q=yp(Jle(a[B],h.orientation,S));for(let w=0;w<a.length;w++){if(p.has(w))continue;const M=a[w],k=_.get(w)??0,R=yp(Jle(M,h.orientation,k));if(!Dc(Q,R))continue;if(!swt(M,m,l)||awt(M,s,r)===-1&&!Awt(M,s,c)){f=!0;break}const F=E3o(yp(M),Q,h.orientation);if(F>rwt||F<=k+X5){f=!0;break}_.set(w,F),E=!0}if(f)break}if(f||!E)break}if(f)continue;const I=new Map;for(const[x,E]of _)I.set(x,Jle(a[x],h.orientation,E));const C=x=>I.get(x)??a[x];for(const[x,E]of I){const B=yp(E);if(A.some(S=>Dc(B,S))){f=!0;break}if(t.chips.some(S=>Dc(B,{minX:S.center.x-S.width/2,maxX:S.center.x+S.width/2,minY:S.center.y-S.height/2,maxY:S.center.y+S.height/2}))||(t.textBoxes??[]).some(S=>Dc(B,fB(S)))){f=!0;break}if(a.some((S,Q)=>Q!==x&&Dc(B,yp(C(Q))))){f=!0;break}if(s.some(S=>S.globalConnNetId!==E.globalConnNetId&&Ej(S.tracePath,B))){f=!0;break}}if(f)continue;const y=[];for(const[x,E]of I){const B=a[x],S=awt(B,s,r);if(S===-1&&!Awt(B,s,c)){f=!0;break}const Q=S===-1?S3o({label:B,labelIndex:x,newAnchor:E.anchorPoint,pinMap:c}):b3o(s[S],B.anchorPoint,E.anchorPoint);if(s.some(M=>M.globalConnNetId!==Q.globalConnNetId&&WH(Q.tracePath,M.tracePath,{includeTerminalSegments:!0}).length>0)||A.some(M=>Ej(Q.tracePath,M))||t.chips.some(M=>!m.has(M.chipId)&&Ej(Q.tracePath,{minX:M.center.x-M.width/2,maxX:M.center.x+M.width/2,minY:M.center.y-M.height/2,maxY:M.center.y+M.height/2}))||(t.textBoxes??[]).some(M=>Ej(Q.tracePath,fB(M)))||a.some((M,k)=>k!==x&&Ej(Q.tracePath,yp(C(k))))){f=!0;break}y.push({labelIndex:x,connectorIndex:S,trace:Q})}if(!f){for(const[x,E]of I)a[x]=E,u.add(x);for(const x of y)r.add(x.trace.mspPairId),x.connectorIndex===-1?s.push(x.trace):s[x.connectorIndex]=x.trace}}return{traces:s,netLabelPlacements:a,movedLabelCount:u.size,netLabelConnectorTraceIds:r}},Wle=.05,w3o=5,P3o=t=>{const[e,n]=t;return Math.abs(n.x-e.x)>=Math.abs(n.y-e.y)?n.x>=e.x?"x+":"x-":n.y>=e.y?"y+":"y-"},lwe=t=>{const e=t.axis==="y"?t.height:t.width,n=t.axis==="y"?t.width:t.height;return{minX:t.center.x-e/2,maxX:t.center.x+e/2,minY:t.center.y-n/2,maxY:t.center.y+n/2}},cwt=t=>({minX:Math.min(...t.map(e=>e.x)),maxX:Math.max(...t.map(e=>e.x)),minY:Math.min(...t.map(e=>e.y)),maxY:Math.max(...t.map(e=>e.y))}),VN=(t,e)=>{for(let n=0;n<t.length-1;n++)if(Dc(cwt([t[n],t[n+1]]),e))return!0;return!1},uwe=(t,e,n)=>{switch(e){case"x+":return{x:t.x+n,y:t.y};case"x-":return{x:t.x-n,y:t.y};case"y+":return{x:t.x,y:t.y+n};case"y-":return{x:t.x,y:t.y-n}}},lwt=(t,e,n)=>{const[o,i]=t.stubTracePath,r=uwe(i,e,n);return{...t,stubTracePath:[o,r],anchorPoint:uwe(t.anchorPoint,e,n),center:uwe(t.center,e,n)}},M3o=(t,e,n)=>{switch(n){case"x+":return e.maxX-t.minX+Wle;case"x-":return t.maxX-e.minX+Wle;case"y+":return e.maxY-t.minY+Wle;case"y-":return t.maxY-e.minY+Wle}},D3o=({inputProblem:t,traces:e,anchoredNetLabelPlacements:n,inlineNetLabelPlacements:o})=>{const i=new Map;for(const A of t.chips)for(const c of A.pins)i.set(c.pinId,A.chipId);const r=new Map;for(const[A,c]of o.entries()){if(!c.stubTracePath||c.pinIds.length!==1)continue;const l=P3o(c.stubTracePath),u=i.get(c.pinIds[0]),g=`${u??c.pinIds[0]}::${l}`,h=r.get(g)??[];h.push({placementIndex:A,placement:c,direction:l,ownerChipId:u}),r.set(g,h)}const s=[...o];let a=0;for(const A of r.values()){const c=new Set(A.map(({placementIndex:p})=>p)),l=s.filter((p,m)=>!c.has(m)),u=A[0].direction;let g=0;for(let p=0;p<=n.length;p++){let m=0;for(const{placement:_}of A){const f=lwt(_,u,g),I=lwe(f);for(const C of n){if(C.globalConnNetId===_.globalConnNetId)continue;const y=yp(C);Dc(I,y)&&(m=Math.max(m,M3o(I,y,u)))}}if(m<=0)break;g+=m}if(g<=0||g>w3o)continue;const h=A.map(({placement:p})=>lwt(p,u,g));if(!h.some((p,m)=>{const f=A[m].placement.stubTracePath[1],I=p.stubTracePath[1],C=[f,I],y=lwe(p),x=A[m].ownerChipId;if(n.some(E=>{if(E.globalConnNetId===p.globalConnNetId)return!1;const B=yp(E);return Dc(y,B)||VN(C,B)}))return!0;for(const E of t.chips){if(E.chipId===x)continue;const B={minX:E.center.x-E.width/2,maxX:E.center.x+E.width/2,minY:E.center.y-E.height/2,maxY:E.center.y+E.height/2};if(Dc(y,B)||VN(C,B))return!0}for(const E of t.textBoxes??[]){const B=fB(E);if(Dc(y,B)||VN(C,B))return!0}for(const E of e)if(E.globalConnNetId!==p.globalConnNetId&&(VN(E.tracePath,y)||VN(E.tracePath,cwt(C))))return!0;for(const E of l){const B=lwe(E);if(Dc(y,B)||VN(C,B)||E.stubTracePath&&VN(E.stubTracePath,y))return!0}return!1})){for(const[p,{placementIndex:m}]of A.entries())s[m]=h[p];a++}}return{inlineNetLabelPlacements:s,movedGroupCount:a}},gwe=(t,e)=>{let n=e.width,o=e.height;"axis"in e&&e.axis==="y"&&(n=e.height,o=e.width);const i=Ey({center:e.center,width:n,height:o});for(let r=0;r<t.length-1;r++)if(Exe(t[r],t[r+1],i))return!0;return!1},dwe=1e-6,uwt=t=>t.slice(1).reduce((e,n,o)=>{const i=t[o];return e+Math.abs(n.x-i.x)+Math.abs(n.y-i.y)},0),N3o=(t,e)=>t.length===e.length&&t.every((n,o)=>Math.abs(n.x-e[o].x)<=dwe&&Math.abs(n.y-e[o].y)<=dwe),R3o=(t,e)=>t.length<e.length&&uwt(t)<=uwt(e)+dwe,gwt=(t,e)=>{const n=new Set;for(let o=0;o<t.length-1;o++)for(let i=0;i<e.length-1;i++){const r=V4(t[o],t[o+1],e[i],e[i+1]);r&&n.add(`${r.x.toFixed(6)},${r.y.toFixed(6)}`)}return n},dwt=(t,e,n)=>n.some(o=>{const i=gwt(e,o);return[...gwt(t,o)].some(s=>!i.has(s))}),T3o=({inputProblem:t,traces:e,netLabelPlacements:n,inlineNetLabelPlacements:o,completedReroutes:i})=>{const r=[...e],s=new Set(o.map(c=>c.globalConnNetId)),a=Hy(t);let A=0;for(const c of[...i].reverse()){if(!s.has(c.label.globalConnNetId))continue;const l=r.findIndex(I=>I.mspPairId===c.initialTrace.mspPairId);if(l<0)continue;const u=r[l],g=Qa(u.tracePath),h=Qa(c.reroutedTracePath);if(!N3o(g,h))continue;const d=Qa(c.initialTrace.tracePath);if(!R3o(d,g))continue;const p={...u,tracePath:d},m=r.filter(I=>I.mspPairId!==u.mspPairId&&I.globalConnNetId!==u.globalConnNetId),_=o.filter(I=>I.globalConnNetId!==u.globalConnNetId),f=_.flatMap(I=>I.stubTracePath?[[...I.stubTracePath]]:[]);ON(d,a)||Jh({traces:[p],netLabels:n}).length>0||_.some(I=>gwe(d,I))||nw(d,m)||wQt(d,f)||dwt(d,g,m.map(I=>I.tracePath))||dwt(d,g,f)||!hj(n,[u],[p])||(r[l]=p,A++)}return{traces:r,restoredTraceCount:A}},hwe=.18,pwe=.05,jle=.05,k3o=.4,hwt=t=>JSON.stringify([...t].sort()),pwt=t=>{let e=0;for(let n=0;n<t.tracePath.length-1;n++){const o=t.tracePath[n],i=t.tracePath[n+1];e+=Math.abs(i.x-o.x)+Math.abs(i.y-o.y)}return e},F3o=(t,e)=>t.size===e.size&&[...t].every(n=>e.has(n)),mwe=t=>{const e=t.axis==="y"?t.height:t.width,n=t.axis==="y"?t.width:t.height;return{minX:t.center.x-e/2,maxX:t.center.x+e/2,minY:t.center.y-n/2,maxY:t.center.y+n/2}},V7=t=>JSON.stringify([t.globalConnNetId,[...t.pinIds].sort(),t.mspPairId??null]),L3o=(t,e)=>{const n=jle-Qx,o={minX:Math.min(t[0].x,t[1].x)-n,maxX:Math.max(t[0].x,t[1].x)+n,minY:Math.min(t[0].y,t[1].y)-n,maxY:Math.max(t[0].y,t[1].y)+n};return tO(e.tracePath,o)},H3o=class E5n extends Ng{constructor(e){super(),this.input=e,this.netLabelConnectorTraceIds=e.netLabelConnectorTraceIds??new Set,this.inputProblem=e.inputProblem,this.traces=e.traces,this.inputNetLabelPlacements=e.netLabelPlacements,this.completedReroutes=e.completedReroutes??[],this.globalConnMap=mB(this.inputProblem).netConnMap,this.queuedConnections=[...this.inputProblem.directConnections.filter(n=>n.allowInlineNetLabel&&n.netId&&!this.inputProblem.netConnections.some(o=>o.allowInlineNetLabel&&o.netId&&n.pinIds.every(i=>o.pinIds.includes(i)))).map(n=>({kind:"direct_connection",connection:n})),...this.inputProblem.netConnections.filter(n=>n.allowInlineNetLabel&&n.pinIds.length>=1&&n.netId).map(n=>({kind:"net_connection",connection:n}))],this.tracesByPinPairKey=new Map;for(const n of this.traces){if(this.netLabelConnectorTraceIds.has(n.mspPairId))continue;const o=hwt(n.pins.map(r=>r.pinId)),i=this.tracesByPinPairKey.get(o);i?i.push(n):this.tracesByPinPairKey.set(o,[n])}}input;inputProblem;traces;inputNetLabelPlacements;completedReroutes;inlineNetLabelPlacements=[];queuedConnections;netLabelConnectorTraceIds;tracesByPinPairKey;globalConnMap;inlineConversions=[];hasAlignedPortOnlyStubs=!1;postProcessedOutput;refinementComplete=!1;refinement;currentProposal;getConstructorParams(){return[{inputProblem:this.inputProblem,traces:this.traces,netLabelPlacements:this.inputNetLabelPlacements,completedReroutes:this.completedReroutes,resolveTraceCollisions:this.input.resolveTraceCollisions,netLabelConnectorTraceIds:this.netLabelConnectorTraceIds}]}_step(){const e=this.queuedConnections.shift();if(e){if(e.kind==="net_connection"&&e.connection.pinIds.length>2){const i=[e.connection,...this.queuedConnections.filter(r=>r.kind==="net_connection"&&r.connection.pinIds.length>2).map(r=>r.connection)];this.queuedConnections=this.queuedConnections.filter(r=>r.kind!=="net_connection"||r.connection.pinIds.length<=2);for(const r of this.computeNetConnectionInlineConversions(i))this.inlineNetLabelPlacements.push(...r.placements),this.inlineConversions.push(r);return}const{connection:n}=e,o=n.pinIds.length===2?this.tracesByPinPairKey.get(hwt(n.pinIds))??[]:[];if(o.length>0){const i=this.computeInlinePlacement({connection:n,trace:o[0],pinIds:n.pinIds});i&&this.inlineNetLabelPlacements.push(i)}else for(const i of n.pinIds){const r=this.computeTerminalInlinePlacement(n,i);r&&this.inlineNetLabelPlacements.push(r)}return}if(!this.hasAlignedPortOnlyStubs){this.inlineNetLabelPlacements=f3o({placements:this.inlineNetLabelPlacements,inputProblem:this.inputProblem,traces:this.traces,netLabelPlacements:this.inputNetLabelPlacements}),this.hasAlignedPortOnlyStubs=!0;return}if(!this.postProcessedOutput){this.postProcessedOutput=this.buildPostProcessedOutput();return}if(this.input.resolveTraceCollisions&&!this.refinementComplete){this.stepTraceRefinement();return}this.solved=!0,this.stats.inlineNetLabelCount=this.inlineNetLabelPlacements.length}computeNetConnectionInlineConversions(e){const n=new Map;for(const i of e){const r=new Set;for(const s of this.getNetConnectionComponents(i)){if(s.traces.length===0)continue;if(!s.traces.some(A=>!!this.computeInlinePlacement({connection:i,trace:A,pinIds:s.pinIds})))for(const A of s.traces)r.add(A.mspPairId)}n.set(i,r)}let o=new Set([...n.values()].flatMap(i=>[...i]));for(;;){const i=e.map(s=>({connection:s,conversion:this.computeNetConnectionInlinePlacements(s,o,n.get(s)??new Set)})),r=new Set(i.flatMap(({conversion:s})=>s.flatMap(a=>[...a.supersededTraceIds])));if(F3o(o,r))return i.flatMap(({conversion:s})=>s);o=r}}getNetConnectionComponents(e){const n=e.pinIds[0];if(!n)return[];const o=this.globalConnMap.getNetConnectedToId(n);if(!o)return[];const i=new Set(this.inputProblem.chips.flatMap(a=>a.pins.map(A=>A.pinId))),r=this.globalConnMap.getIdsConnectedToNet(o).filter(a=>i.has(a)),s=new Set(e.pinIds);return xle({pinIds:r,traces:this.traces.filter(a=>!this.netLabelConnectorTraceIds.has(a.mspPairId))}).map(a=>({pinIds:a.pinIds,labeledPinIds:a.pinIds.filter(A=>s.has(A)),traces:a.traces.sort((A,c)=>pwt(c)-pwt(A))})).filter(a=>a.labeledPinIds.length>0)}getGlobalConnNetId(e){const n=e.pinIds[0];if(!n)return;const o=new Set(e.pinIds);return this.traces.find(i=>i.pins.some(r=>o.has(r.pinId)))?.globalConnNetId??this.inputNetLabelPlacements.find(i=>i.netId===e.netId)?.globalConnNetId??this.globalConnMap.getNetConnectedToId(n)??void 0}computeNetConnectionInlinePlacements(e,n,o){const i=this.getNetConnectionComponents(e),r=this.getGlobalConnNetId(e);if(!r)return[];const s=[];for(const a of i){const A=a.traces.some(u=>o.has(u.mspPairId));let c=null;if(!A){for(const u of a.traces)if(c=this.computeInlinePlacement({connection:e,trace:u,pinIds:a.pinIds,ignoredTraceIds:n}),c)break}if(c){s.push({globalConnNetId:r,placements:[c],supersededTraceIds:new Set});continue}if(a.traces.length>0&&!A||a.labeledPinIds.length!==a.pinIds.length)continue;const l=a.pinIds.map(u=>this.computeTerminalInlinePlacement(e,u,r,n));l.some(u=>u===null)||s.push({globalConnNetId:r,placements:l,supersededTraceIds:new Set(a.traces.map(u=>u.mspPairId))})}return s}getInlineOffsets(e,n,o,i,r,s,a){const A=r/2+pwe,c=n==="x"?"y":"x",l=o==="x+"||o==="y+"?1:-1;let u=1/0;for(const g of s)if(!a.has(g.mspPairId))for(const h of iwt(g.tracePath)){if(h.axis!==n||Math.max(h.start[n],h.end[n])<=e[n]-i/2||Math.min(h.start[n],h.end[n])>=e[n]+i/2)continue;const d=l*(h.start[c]-e[c]);d>Qx&&(u=Math.min(u,d))}return u>r+Qx&&u/2<A-Qx?[A,u/2]:[A]}computeTerminalInlinePlacement(e,n,o,i=new Set,r){if(!e.netId)return null;const s=this.inputNetLabelPlacements.find(y=>y.netId===e.netId&&y.pinIds.length===1&&y.pinIds[0]===n),a=o??s?.globalConnNetId;if(!a)return null;const A=this.inputProblem.chips.find(y=>y.pins.some(x=>x.pinId===n)),c=A?.pins.find(y=>y.pinId===n),l=e.inlineNetLabelHeight??hwe,u=e.netLabelText?.trim()||void 0,g=e.inlineNetLabelWidth??e.netLabelWidth??_wt(u??e.netId,l),h=Math.max(g+.2,.6);if(!c&&!s)return null;const d=c?{x:c.x,y:c.y}:s.anchorPoint,p=c&&A?c._facingDirection??W5(c,A):s.orientation,m=p==="x+"?{x:d.x+h,y:d.y}:p==="x-"?{x:d.x-h,y:d.y}:p==="y+"?{x:d.x,y:d.y+h}:{x:d.x,y:d.y-h},_=G3o({start:d,intendedEnd:m,minimumLength:g+2*pwe,traces:r?.traces??this.traces,ownGlobalConnNetId:a,ignoredTraceIds:i});if(!_)return null;const f=p==="x+"||p==="x-"?"x":"y",I={x:(d.x+_.x)/2,y:(d.y+_.y)/2},C=f==="x"?["y+","y-"]:["x-","x+"];for(const y of C)for(const x of this.getInlineOffsets(I,f,y,g,l,r?.traces??this.traces,i)){const E=y==="y+"?{x:I.x,y:I.y+x}:y==="y-"?{x:I.x,y:I.y-x}:y==="x-"?{x:I.x-x,y:I.y}:{x:I.x+x,y:I.y},B=g/2,S=l/2,Q=f==="x"?{minX:E.x-B,maxX:E.x+B,minY:E.y-S,maxY:E.y+S}:{minX:E.x-S,maxX:E.x+S,minY:E.y-B,maxY:E.y+B};if(!this.isObstructed(Q,{ownGlobalConnNetId:a,ignoredTraceIds:i,obstacles:r}))return{globalConnNetId:a,netId:e.netId,netLabelText:u,pinIds:[n],stubTracePath:[d,_],axis:f,anchorPoint:I,center:E,width:g,height:l,side:y}}return null}computeInlinePlacement({connection:e,trace:n,pinIds:o,ignoredTraceIds:i=new Set}){const r=iwt(n.tracePath);if(r.length===0)return null;const s=e.inlineNetLabelHeight??hwe,a=e.netLabelText?.trim()||void 0,A=e.inlineNetLabelWidth??e.netLabelWidth??_wt(a??e.netId,s),c=s/2+pwe,l=r.filter(g=>g.length>=A).sort((g,h)=>h.length-g.length);for(const g of l){const h=g.axis==="x"?["y+","y-"]:["x-","x+"];for(const d of h)for(const p of O3o(g,A))for(const m of this.getInlineOffsets(p,g.axis,d,A,s,this.traces,i)){const _=d==="y+"?{x:p.x,y:p.y+m}:d==="y-"?{x:p.x,y:p.y-m}:d==="x-"?{x:p.x-m,y:p.y}:{x:p.x+m,y:p.y},f=A/2,I=s/2,C=g.axis==="x"?{minX:_.x-f,maxX:_.x+f,minY:_.y-I,maxY:_.y+I}:{minX:_.x-I,maxX:_.x+I,minY:_.y-f,maxY:_.y+f};if(!this.isObstructed(C,{ownTrace:n,ownGlobalConnNetId:n.globalConnNetId,ignoredTraceIds:i}))return{globalConnNetId:n.globalConnNetId,netId:e.netId,netLabelText:a,mspPairId:n.mspPairId,pinIds:[...o],axis:g.axis,anchorPoint:p,center:_,width:A,height:s,side:d}}}const u=this.computeSpanPlacement({trace:n,connection:e,netLabelText:a,width:A,height:s,offset:c,pinIds:o,ignoredTraceIds:i});return u||null}computeSpanPlacement({trace:e,connection:n,netLabelText:o,width:i,height:r,offset:s,pinIds:a,ignoredTraceIds:A}){const c=e.tracePath;if(c.length<2)return null;let l=1/0,u=-1/0,g=1/0,h=-1/0;for(const S of c)l=Math.min(l,S.x),u=Math.max(u,S.x),g=Math.min(g,S.y),h=Math.max(h,S.y);const d=u-l,p=h-g,m=d>=p?"x":"y",_=m==="x"?d:p;if((m==="x"?p:d)>k3o||_<i)return null;const y=((m==="x"?l:g)+(m==="x"?u:h))/2,x=(_-i)/2,E=[0];for(let S=.1;S<=x+1e-9;S+=.1)E.push(S,-S);E.push(x,-x);const B=m==="x"?["y+","y-"]:["x-","x+"];for(const S of B)for(const Q of E){const w=y+Q,M=S==="y+"?{x:w,y:h+s}:S==="y-"?{x:w,y:g-s}:S==="x-"?{x:l-s,y:w}:{x:u+s,y:w},k=i/2,R=r/2,F=m==="x"?{minX:M.x-k,maxX:M.x+k,minY:M.y-R,maxY:M.y+R}:{minX:M.x-R,maxX:M.x+R,minY:M.y-k,maxY:M.y+k};if(this.isObstructed(F,{ownTrace:e,ownGlobalConnNetId:e.globalConnNetId,ignoredTraceIds:A}))continue;const O=m==="x"?{x:w,y:S==="y+"?h:g}:{x:S==="x-"?l:u,y:w};return{globalConnNetId:e.globalConnNetId,netId:n.netId,netLabelText:o,mspPairId:e.mspPairId,pinIds:[...a],axis:m,anchorPoint:O,center:M,width:i,height:r,side:S}}return null}isObstructed(e,{ownTrace:n,ownGlobalConnNetId:o,ignoredTraceIds:i=new Set,obstacles:r}){for(const s of this.inputProblem.chips){const a={minX:s.center.x-s.width/2,maxX:s.center.x+s.width/2,minY:s.center.y-s.height/2,maxY:s.center.y+s.height/2};if(Dc(e,a))return!0}for(const s of this.inputProblem.textBoxes??[])if(Dc(e,fB(s)))return!0;for(const s of r?.traces??this.traces)if(!i.has(s.mspPairId)&&!(n&&s.mspPairId===n.mspPairId)&&s.globalConnNetId!==o&&tO(s.tracePath,e))return!0;return!!(r?.anchored.some(s=>Dc(e,yp(s)))||r?.inline.some(s=>Dc(e,mwe(s))||s.stubTracePath&&s.globalConnNetId!==o&&tO(s.stubTracePath,e)))}getOutputTraces(e){const n=new Set(e.map(V7)),o=new Set(this.inlineConversions.filter(i=>i.placements.every(r=>n.has(V7(r)))).flatMap(i=>[...i.supersededTraceIds]));return this.traces.filter(i=>!o.has(i.mspPairId)&&!(this.netLabelConnectorTraceIds.has(i.mspPairId)&&cwe(i,e)))}getBlockedInlinePlacements({inlineNetLabelPlacements:e,anchoredNetLabelPlacements:n,traces:o}){const i=new Set;for(const r of e){const s=mwe(r),a=n.some(u=>{const g=yp(u);return Dc(s,g)||r.stubTracePath&&tO(r.stubTracePath,g)}),A=o.some(u=>u.globalConnNetId!==r.globalConnNetId&&(tO(u.tracePath,s)||r.stubTracePath&&L3o(r.stubTracePath,u))),c=e.some(u=>u!==r&&u.globalConnNetId!==r.globalConnNetId&&u.stubTracePath&&tO(u.stubTracePath,s)),l=e.some(u=>u!==r&&Dc(s,mwe(u)));(a||A||c||l)&&i.add(V7(r))}for(const r of this.inlineConversions)if(r.placements.some(s=>i.has(V7(s))))for(const s of r.placements)i.add(V7(s));return i}buildPostProcessedOutput(){let e=this.inlineNetLabelPlacements;for(;;){const n=this.inputNetLabelPlacements.filter(c=>!cwe(c,e)),o=this.getOutputTraces(e),{fixedLabels:i,terminalTraces:r}=awe(this.inputProblem,e),s=new ewe({inputProblem:this.inputProblem,traces:[...o,...r],netLabelPlacements:n,fixedNetLabelPlacements:i,netLabelConnectorTraceIds:this.netLabelConnectorTraceIds,useRenderedLabelBounds:e.length>0});e.length>0&&s.solve();const a=v3o({inputProblem:this.inputProblem,traces:o,netLabelPlacements:s.solved&&!s.failed?s.getOutput().netLabelPlacements:n,inlineNetLabelPlacements:e,netLabelConnectorTraceIds:this.netLabelConnectorTraceIds});let A=this.getBlockedInlinePlacements({inlineNetLabelPlacements:e,anchoredNetLabelPlacements:a.netLabelPlacements,traces:a.traces});if(A.size>0){const c=D3o({inputProblem:this.inputProblem,traces:a.traces,anchoredNetLabelPlacements:a.netLabelPlacements,inlineNetLabelPlacements:e});if(c.movedGroupCount>0){e=c.inlineNetLabelPlacements;continue}const{terminalTraces:l}=awe(this.inputProblem,e),u=e.filter(d=>!d.stubTracePath),g=e.filter(d=>d.stubTracePath).sort((d,p)=>Number(A.has(V7(p)))-Number(A.has(V7(d))));for(const d of g){const p=[...this.inputProblem.netConnections,...this.inputProblem.directConnections].find(_=>_.netId===d.netId&&_.allowInlineNetLabel),m=p?this.computeTerminalInlinePlacement(p,d.pinIds[0],d.globalConnNetId,new Set,{traces:[...a.traces,...l],anchored:a.netLabelPlacements,inline:u}):null;u.push(m??d)}const h=new Map(u.map(d=>[V7(d),d]));e=e.map(d=>h.get(V7(d))??d),A=this.getBlockedInlinePlacements({inlineNetLabelPlacements:e,anchoredNetLabelPlacements:a.netLabelPlacements,traces:a.traces})}if(A.size===0){this.inlineNetLabelPlacements=e,this.stats.pushedAnchoredNetLabelCount=a.movedLabelCount;const c=T3o({inputProblem:this.inputProblem,traces:a.traces,netLabelPlacements:a.netLabelPlacements,inlineNetLabelPlacements:e,completedReroutes:this.completedReroutes});this.stats.restoredSupersededLabelRerouteCount=c.restoredTraceCount;const l={traces:c.traces,netLabelConnectorTraceIds:a.netLabelConnectorTraceIds,netLabelPlacements:a.netLabelPlacements,inlineNetLabelPlacements:e};return this.inlineNetLabelPlacements=l.inlineNetLabelPlacements,l}e=e.filter(c=>!A.has(V7(c)))}}*getTraceRefinementProposals(e){yield*ewt(this.inputProblem,e);for(const n of e.netLabelPlacements){if(n.pinIds.length!==1)continue;const o=[...this.inputProblem.netConnections,...this.inputProblem.directConnections].find(r=>r.allowInlineNetLabel&&r.netId===n.netId&&r.pinIds.includes(n.pinIds[0]));if(!o)continue;const i=this.computeTerminalInlinePlacement(o,n.pinIds[0],n.globalConnNetId,new Set,{traces:[],anchored:[],inline:[]});i&&(yield*ewt(this.inputProblem,e,[i]))}}createRefinementCandidate(e){const n=new Map(e.traces.map(s=>[s.mspPairId,s])),o=s=>JSON.stringify([s.globalConnNetId,[...s.pinIds].sort()]),i=new Map(e.netLabelPlacements.map(s=>[o(s),s])),r=new Set(this.traces.map(s=>s.mspPairId));return new E5n({inputProblem:this.inputProblem,traces:[...this.traces.map(s=>n.get(s.mspPairId)??s),...e.traces.filter(s=>!r.has(s.mspPairId))],netLabelPlacements:this.inputNetLabelPlacements.map(s=>i.get(o(s))??s),completedReroutes:this.completedReroutes,netLabelConnectorTraceIds:e.netLabelConnectorTraceIds})}acceptRefinementCandidate(e,n){const o=this.postProcessedOutput,i=this.refinement.before,r=nwt(n);if(r.some(a=>!i.some(A=>twt(a,A))))return!1;const s=new Set(e.traces.filter((a,A)=>a!==o.traces[A]).map(a=>a.mspPairId));return r.some(a=>a.kind==="trace-label"&&a.trace.kind==="routed"&&s.has(a.trace.id))||r.length>=i.length&&n.inlineNetLabelPlacements.length<=o.inlineNetLabelPlacements.length?!1:(this.postProcessedOutput=n,this.inlineNetLabelPlacements=n.inlineNetLabelPlacements,!0)}stepTraceRefinement(){if(this.activeSubSolver){if(this.activeSubSolver.step(),!this.activeSubSolver.solved&&!this.activeSubSolver.failed)return;this.activeSubSolver.solved&&!this.activeSubSolver.failed&&this.acceptRefinementCandidate(this.currentProposal,this.activeSubSolver.getOutput())&&(this.refinement=void 0),this.activeSubSolver=null,this.currentProposal=void 0;return}const e=this.postProcessedOutput;this.refinement||(this.refinement={proposals:this.getTraceRefinementProposals(e),queue:[],collecting:!0,before:nwt(e)});const n=this.refinement;if(n.collecting){const i=n.proposals.next();if(i.done)n.queue.sort((r,s)=>r.distance-s.distance),n.collecting=!1;else{const r=i.value.traces.reduce((s,a,A)=>s+a.tracePath.reduce((c,l,u)=>{const g=e.traces[A].tracePath[u];return c+Math.abs(l.x-g.x)+Math.abs(l.y-g.y)},0),0);n.queue.push({output:i.value,distance:r})}return}const o=n.queue.shift();if(!o){this.refinementComplete=!0;return}this.currentProposal=o.output,this.activeSubSolver=this.createRefinementCandidate(o.output)}getOutput(){return this.postProcessedOutput?this.postProcessedOutput:this.buildPostProcessedOutput()}visualize(){return mwt({inputProblem:this.inputProblem,...this.getOutput()})}},mwt=({inputProblem:t,traces:e,netLabelPlacements:n,inlineNetLabelPlacements:o})=>{const i=zh(t);i.lines??=[],i.rects??=[],i.points??=[],i.texts??=[];for(const r of e)i.lines.push({points:r.tracePath,strokeColor:"purple"});for(const r of n)i.rects.push({center:r.center,width:r.width,height:r.height,fill:Mc(r.globalConnNetId,.35),strokeColor:Mc(r.globalConnNetId,.9),label:`netId: ${r.netId}
globalConnNetId: ${r.globalConnNetId}`}),i.points.push({x:r.anchorPoint.x,y:r.anchorPoint.y,color:Mc(r.globalConnNetId,.9),label:`anchorPoint
orientation: ${r.orientation}`});for(const r of o){r.stubTracePath&&i.lines.push({points:r.stubTracePath,strokeColor:"purple"});const s=r.axis==="x";let a=r.width,A=r.height;s||(a=r.height,A=r.width),i.rects.push({center:r.center,width:a,height:A,fill:Mc(r.globalConnNetId,.35),strokeColor:"green",label:[`INLINE netId: ${r.netId}`,`axis: ${r.axis}`,`side: ${r.side}`].join(`
`)});let c=r.center.x,l=r.center.y,u="center",g;if(r.stubTracePath){const h=r.stubTracePath[0],d=r.stubTracePath[1];let p=r.width/2;d[r.axis]>h[r.axis]?(p=-r.width/2,u="center_left"):u="center_right",r.axis==="x"?c+=p:l+=p}r.axis==="y"&&(g=90),i.texts.push({x:c,y:l,text:r.netLabelText??r.netId??"",color:"green",fontSize:r.height,anchorSide:u,rotation:g}),i.points.push({x:r.anchorPoint.x,y:r.anchorPoint.y,color:"green",label:`inline anchor
${r.netLabelText??r.netId}`})}return i},_wt=(t,e=hwe)=>{const n=e/.18;return t.length*.12*n+.12*n},O3o=(t,e,n=.1)=>{const o=t.axis==="x"?"x":"y",i=t.start[o],r=t.end[o],s=(i+r)/2,a=Math.sign(r-i)||1,A=u=>t.axis==="x"?{x:u,y:t.start.y}:{x:t.start.x,y:t.start.y+(u-i)},c=t.length-e;if(c<=0)return[A(s)];const l=[0];for(let u=n;u<=c/2+1e-9;u+=n)l.push(u,-u);return l.push(c/2,-c/2),l.map(u=>A(s+u*a))},tO=(t,e)=>{for(let n=0;n<t.length-1;n++){const o=t[n],i=t[n+1],r={minX:Math.min(o.x,i.x),maxX:Math.max(o.x,i.x),minY:Math.min(o.y,i.y),maxY:Math.max(o.y,i.y)};if(Dc(r,e))return!0}return!1},Qx=1e-6,G3o=({start:t,intendedEnd:e,minimumLength:n,traces:o,ownGlobalConnNetId:i,ignoredTraceIds:r})=>{const s=Math.abs(e.x-t.x)>=Math.abs(e.y-t.y),a=s?"x":"y",A=s?"y":"x",c=Math.sign(e[a]-t[a])||1,l=Math.abs(e[a]-t[a]);let u=l;for(const g of o)if(!r.has(g.mspPairId)&&g.globalConnNetId!==i)for(let h=0;h<g.tracePath.length-1;h++){const d=g.tracePath[h],p=g.tracePath[h+1],m=(d[a]-t[a])*c,_=(p[a]-t[a])*c,f=d[A]-t[A],I=p[A]-t[A],C=Math.min(m,_),y=Math.max(m,_),x=Math.min(f,I),E=Math.max(f,I);let B;if(Math.abs(f)<=Qx&&Math.abs(I)<=Qx&&y>=-Qx&&C<=l+jle+Qx)B=Math.max(0,C);else{const Q=x<=Qx&&E>=-Qx,w=(m+_)/2;Q&&Math.abs(m-_)<=Qx&&w>=-Qx&&w<=l+jle+Qx&&(B=Math.max(0,w))}B!==void 0&&(u=Math.min(u,B-jle))}return u+Qx<n?null:s?{x:t.x+c*u,y:t.y}:{x:t.x,y:t.y+c*u}},nO=1e-6,fwt=({coordinate:t,segmentStartCoordinate:e,segmentEndCoordinate:n})=>t>Math.min(e,n)+nO&&t<Math.max(e,n)-nO,Y3o=({firstSegmentStart:t,firstSegmentEnd:e,secondSegmentStart:n,secondSegmentEnd:o})=>{const i=Math.abs(t.y-e.y)<=nO,r=Math.abs(t.x-e.x)<=nO,s=Math.abs(n.y-o.y)<=nO,a=Math.abs(n.x-o.x)<=nO;let A,c;if(i)A=t,c=e;else if(s)A=n,c=o;else return!1;let l,u;if(r)l=t,u=e;else if(a)l=n,u=o;else return!1;return fwt({coordinate:l.x,segmentStartCoordinate:A.x,segmentEndCoordinate:c.x})&&fwt({coordinate:A.y,segmentStartCoordinate:l.y,segmentEndCoordinate:u.y})},Iwt=(t,e)=>{for(let n=0;n<t.length-1;n++){const o=t[n],i=t[n+1];for(const r of e)for(let s=0;s<r.tracePath.length-1;s++){const a=r.tracePath[s],A=r.tracePath[s+1];if(X1(o,i,a,A)&&!Y3o({firstSegmentStart:o,firstSegmentEnd:i,secondSegmentStart:a,secondSegmentEnd:A}))return!0}}return!1},U3o=t=>{const e={},n=new Map;for(const o of t.chips){e[o.chipId]=o;for(const i of o.pins)n.set(i.pinId,{...i,chipId:o.chipId,_facingDirection:i._facingDirection??W5(i,o)})}return{chipMap:e,pinMap:n}},Bj=1e-9,$le=(t,e)=>Math.abs(t.y-e.y)<Bj,qle=(t,e)=>Math.abs(t.x-e.x)<Bj,K3o=t=>t.filter((e,n)=>{const o=t[n-1];return!o||Math.abs(e.x-o.x)>=Bj||Math.abs(e.y-o.y)>=Bj}),V3o=t=>{if(t.length<2||!t.every((e,n)=>{const o=t[n+1];return o?$le(e,o)||qle(e,o):!0}))return!1;for(let e=0;e<t.length-1;e++)for(let n=e+2;n<t.length-1;n++)if($Qt(t[e],t[e+1],t[n],t[n+1]))return!1;return!0},z3o=t=>{const e=[];for(let n=2;n<=t.length-4;n++){const o=t[n-1],i=t[n],r=t[n+1],s=t[n+2],a=qle(i,r),A=$le(i,r);if(!a&&!A||a&&(!$le(o,i)||!$le(r,s))||A&&(!qle(o,i)||!qle(r,s)))continue;const c=a?[o.x,s.x]:[o.y,s.y];for(const l of c){if(Math.abs(l-(a?i.x:i.y))<Bj)continue;const u=t.map(h=>({...h}));a?(u[n].x=l,u[n+1].x=l):(u[n].y=l,u[n+1].y=l);const g=K3o(u);V3o(g)&&e.push(g)}}return e},Cwt=({tracePath:t,globalConnNetId:e,otherTraces:n})=>n.reduce((o,i)=>o+(i.globalConnNetId===e?0:vle(t,i.tracePath)),0),J3o=({tracePath:t,globalConnNetId:e,otherTraces:n,isCandidateValid:o})=>{let i=t,r=Cwt({tracePath:t,globalConnNetId:e,otherTraces:n}),s=U7(t);for(const a of z3o(t)){if(!o(a))continue;const A=Cwt({tracePath:a,globalConnNetId:e,otherTraces:n}),c=U7(a);(A<r||A===r&&c<s)&&(i=a,r=A,s=c)}return i},W3o="net-label-to-trace-",j3o=.05,ywt=.25,xwt=(t,e)=>[t,e].sort().join("--"),_we=(t,e)=>{const n=Math.abs(t.x-e.x),o=Math.abs(t.y-e.y);return n>=o?o:n},$3o=(t,e)=>{if(t._facingDirection!==e._facingDirection)return!1;const n=Math.abs(t.x-e.x),o=Math.abs(t.y-e.y);return n>=o?t._facingDirection==="x+"||t._facingDirection==="x-":t._facingDirection==="y+"||t._facingDirection==="y-"},q3o=class extends Ng{constructor(t){super(),this.input=t,this.inputProblem=t.inputProblem,this.outputTraces=[...t.traces],this.outputNetLabelPlacements=[...t.netLabelPlacements];const{chipMap:e,pinMap:n}=U3o(this.inputProblem);this.chipMap=e,this.pinMap=n,this.canRecoverParallelPair=DQt(this.inputProblem,mB(this.inputProblem).netConnMap,new Set(t.traces.filter(o=>o.pinIds.length>1).flatMap(o=>o.pinIds))),this.queuedCandidates=this.buildCandidatePairs(),this.stats.candidateCount=this.queuedCandidates.length,this.stats.recoveredTraceCount=0}input;inputProblem;outputTraces;outputNetLabelPlacements;recoveredTraceIds=new Set;chipMap;pinMap;canRecoverParallelPair;queuedCandidates;currentCandidate=null;getConstructorParams(){return[this.input]}isPortOnlyFallbackLabel(t,e){return!(t.pinIds.length!==1||t.mspConnectionPairIds.length!==0||!t.netId||e.has(t.globalConnNetId))}isDirectConnectionLabel(t){if(!t.netId||t.pinIds.length!==1)return!1;const e=t.pinIds[0];return this.inputProblem.directConnections.some(n=>n.netId===t.netId&&n.pinIds.includes(e))}getMultiPinNetConnection(t){if(!t.netId||t.pinIds.length!==1)return;const e=t.pinIds[0];return this.inputProblem.netConnections.find(n=>n.isGround===!1&&n.pinIds.length>2&&n.netId===t.netId&&n.pinIds.includes(e))}buildCandidatePairs(){const{netConnMap:t}=mB(this.inputProblem),e=new Set;for(const i of this.inputProblem.netConnections){if(!i.isGround)continue;const r=t.getNetConnectedToId(i.netId);r&&e.add(r)}const n=new Map;for(const i of this.input.netLabelPlacements){if(!this.isPortOnlyFallbackLabel(i,e)||!this.isDirectConnectionLabel(i)&&!this.getMultiPinNetConnection(i))continue;const r=n.get(i.globalConnNetId)??[];r.push(i),n.set(i.globalConnNetId,r)}const o=[];for(const i of n.values())for(let r=0;r<i.length;r++)for(let s=r+1;s<i.length;s++){const a=i[r],A=i[s],c=this.pinMap.get(a.pinIds[0]),l=this.pinMap.get(A.pinIds[0]);if(!c||!l||!this.canRecoverParallelPair(c,l))continue;const u=_we(c,l),g=this.isDirectConnectionLabel(a)&&this.isDirectConnectionLabel(A),h=this.getMultiPinNetConnection(a),d=this.getMultiPinNetConnection(A);!g&&(!h||h!==d||u>j3o)||Zv(this.inputProblem,c,l)||lj({inputProblem:this.inputProblem,chipMap:this.chipMap,pinIdMap:this.pinMap,p1:c,p2:l})||o.push({firstLabel:a,secondLabel:A,pins:[c,l],perpendicularOffset:u,routeDistance:Math.abs(c.x-l.x)+Math.abs(c.y-l.y),key:xwt(c.pinId,l.pinId),recoveryMode:"fallback_labels"})}return o.push(...this.buildRoutedComponentCandidates(e)),o.sort((i,r)=>i.perpendicularOffset-r.perpendicularOffset||i.routeDistance-r.routeDistance||i.key.localeCompare(r.key)),o}buildRoutedComponentCandidates(t){const{netConnMap:e}=mB(this.inputProblem),n=[],o=new Set(this.inputProblem.directConnections);for(const i of[...this.inputProblem.netConnections.filter(r=>r.pinIds.length>2&&r.isGround===!1),...this.inputProblem.directConnections]){const r=o.has(i),s=e.getNetConnectedToId(i.pinIds[0]);if(!s||r&&t.has(s))continue;let a=i.pinIds;r&&(a=[...this.pinMap.keys()].filter(c=>e.getNetConnectedToId(c)===s));const A=xle({pinIds:a,traces:this.outputTraces.filter(c=>c.globalConnNetId===s)}).filter(c=>c.traces.length>0);for(let c=0;c<A.length;c++)for(let l=c+1;l<A.length;l++){const u=A[c],g=A[l];if(r&&!(u.pinIds.includes(i.pinIds[0])&&g.pinIds.includes(i.pinIds[1])||u.pinIds.includes(i.pinIds[1])&&g.pinIds.includes(i.pinIds[0])))continue;const h=this.input.netLabelPlacements.find(f=>f.globalConnNetId===s&&f.mspConnectionPairIds.length>0&&f.pinIds.some(I=>u.pinIds.includes(I))),d=this.input.netLabelPlacements.find(f=>f.globalConnNetId===s&&f.mspConnectionPairIds.length>0&&f.pinIds.some(I=>g.pinIds.includes(I)));if(!h||!d||h===d||_we(h.anchorPoint,d.anchorPoint)>ywt)continue;let p,m=u.pinIds,_=g.pinIds;r&&(m=i.pinIds.filter(f=>u.pinIds.includes(f)),_=i.pinIds.filter(f=>g.pinIds.includes(f)));for(const f of m)for(const I of _){const C=this.pinMap.get(f),y=this.pinMap.get(I);if(!C||!y||!this.canRecoverParallelPair(C,y)||r&&C.chipId===y.chipId)continue;const x=_we(C,y);if(x>ywt||$3o(C,y)||Zv(this.inputProblem,C,y)||lj({inputProblem:this.inputProblem,chipMap:this.chipMap,pinIdMap:this.pinMap,p1:C,p2:y}))continue;const E=Math.abs(C.x-y.x)+Math.abs(C.y-y.y);let B="routed_components";r&&(B="routed_direct_connection");const S={firstLabel:h,secondLabel:d,pins:[C,y],perpendicularOffset:x,routeDistance:E,key:xwt(C.pinId,y.pinId),recoveryMode:B,netConnectionPinIds:a};(!p||S.routeDistance<p.routeDistance||S.routeDistance===p.routeDistance&&(S.perpendicularOffset<p.perpendicularOffset||S.perpendicularOffset===p.perpendicularOffset&&S.key.localeCompare(p.key)<0))&&(p=S)}p&&n.push(p)}}return n}isSupersededConnectorTrace(t,e){return!this.input.netLabelConnectorTraceIds?.has(t.mspPairId)||t.pinIds.length!==1?!1:e.pins.some(n=>n.pinId===t.pinIds[0])}routeIntersectsRemainingLabels(t,e){for(const n of this.outputNetLabelPlacements)if(!(n===e.firstLabel||n===e.secondLabel)&&gwe(t,n))return!0;return this.input.inlineNetLabelPlacements.some(n=>gwe(t,n))}tryAcceptCurrentRoute(){const t=this.currentCandidate;let e=this.activeSubSolver?.solvedTracePath;if(!t||!e)return;const n=this.outputTraces.filter(A=>!this.isSupersededConnectorTrace(A,t));let o=n;if(t.recoveryMode!=="fallback_labels"&&(o=n.filter(A=>A.globalConnNetId!==t.firstLabel.globalConnNetId)),Iwt(e,o)||this.routeIntersectsRemainingLabels(e,t))return;e=J3o({tracePath:e,globalConnNetId:t.firstLabel.globalConnNetId,otherTraces:o,isCandidateValid:A=>HN(A,this.activeSubSolver.obstacles)===null&&!Iwt(A,o)&&!this.routeIntersectsRemainingLabels(A,t)});const[i,r]=t.pins,s=`${W3o}${t.key}`,a={mspPairId:s,dcConnNetId:t.firstLabel.globalConnNetId,globalConnNetId:t.firstLabel.globalConnNetId,pins:[i,r],tracePath:e,mspConnectionPairIds:[s],pinIds:[i.pinId,r.pinId]};this.recoveredTraceIds.add(s),this.outputTraces=[...n,a],t.recoveryMode!=="routed_components"&&(this.outputNetLabelPlacements=this.outputNetLabelPlacements.filter(A=>A!==t.firstLabel&&A!==t.secondLabel)),this.stats.recoveredTraceCount++}areCandidatePinsAlreadyConnected(t){return t.netConnectionPinIds?xle({pinIds:t.netConnectionPinIds,traces:this.outputTraces}).some(e=>e.pinIds.includes(t.pins[0].pinId)&&e.pinIds.includes(t.pins[1].pinId)):!1}_step(){if(this.activeSubSolver){this.activeSubSolver.step(),this.activeSubSolver.solved?(this.tryAcceptCurrentRoute(),this.activeSubSolver=null,this.currentCandidate=null):this.activeSubSolver.failed&&(this.activeSubSolver=null,this.currentCandidate=null);return}let t=this.queuedCandidates.shift();for(;t&&(!this.outputNetLabelPlacements.includes(t.firstLabel)||!this.outputNetLabelPlacements.includes(t.secondLabel)||this.areCandidatePinsAlreadyConnected(t));)t=this.queuedCandidates.shift();if(!t){this.solved=!0;return}this.currentCandidate=t,this.activeSubSolver=new VH({inputProblem:this.inputProblem,pins:t.pins,chipMap:this.chipMap})}getOutput(){return{traces:this.outputTraces,netLabelPlacements:this.outputNetLabelPlacements,inlineNetLabelPlacements:this.input.inlineNetLabelPlacements}}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();const t=mwt({inputProblem:this.inputProblem,...this.getOutput()});for(const e of this.outputTraces)this.recoveredTraceIds.has(e.mspPairId)&&t.lines.push({points:e.tracePath,strokeColor:"green",label:`recovered from net labels: ${e.pinIds.join(" -> ")}`});return t}};function sh(t,e,n,o={}){return{solverName:t,solverClass:e,getConstructorParams:n,onSolved:o.onSolved,shouldSkip:o.shouldSkip}}var Ewt=class extends Ng{getSolverName(){return"SchematicTracePipelineSolver"}mspConnectionPairSolver;schematicTraceLinesSolver;longDistancePairSolver;unroutedTraceRecoverySolver;traceOverlapShiftSolver;netLabelPlacementSolver;labelMergingSolver;traceLabelOverlapAvoidanceSolver;traceCleanupSolver;example28Solver;availableNetOrientationSolver;postLabelTraceOverlapShiftSolver;railNetLabelCornerPlacementSolver;traceAnchoredNetLabelOverlapSolver;preAlignmentNetLabelTraceCollisionSolver;netLabelTraceCollisionSolver;traceCleanupSolver2;netLabelNetLabelCollisionSolver;traceElbowTransitionSimplificationSolver;preAlignmentTraceElbowTransitionSimplificationSolver;finalTraceElbowTransitionSimplificationSolver;sameNetJunctionAlignmentSolver;inlineNetLabelSolver;netLabelToTraceSolver;startTimeOfPhase;endTimeOfPhase;timeSpentOnPhase;firstIterationOfPhase;inputProblem;hideRatsNet;pipelineDef=[sh("mspConnectionPairSolver",VIo,()=>[{inputProblem:this.inputProblem}],{onSolved:t=>{}}),sh("schematicTraceLinesSolver",iCo,()=>[{mspConnectionPairs:this.mspConnectionPairSolver.mspConnectionPairs,dcConnMap:this.mspConnectionPairSolver.dcConnMap,globalConnMap:this.mspConnectionPairSolver.globalConnMap,inputProblem:this.inputProblem,chipMap:this.mspConnectionPairSolver.chipMap}]),sh("longDistancePairSolver",FCo,t=>[{inputProblem:t.inputProblem,primaryMspConnectionPairs:t.mspConnectionPairSolver.mspConnectionPairs,alreadySolvedTraces:t.schematicTraceLinesSolver.solvedTracePaths,failedConnectionPairs:t.schematicTraceLinesSolver.failedConnectionPairs}],{onSolved:t=>{}}),sh("unroutedTraceRecoverySolver",Fxo,t=>[{inputProblem:t.inputProblem,failedConnectionPairs:t.schematicTraceLinesSolver.failedConnectionPairs,alreadySolvedTraces:t.longDistancePairSolver.getOutput().allTracesMerged}]),sh("traceOverlapShiftSolver",CQt,()=>[{inputProblem:this.inputProblem,inputTracePaths:this.unroutedTraceRecoverySolver?.getOutput().allTracesMerged,globalConnMap:this.mspConnectionPairSolver.globalConnMap}],{onSolved:t=>{}}),sh("netLabelPlacementSolver",BQt,()=>[{inputProblem:this.inputProblem,inputTraceMap:this.traceOverlapShiftSolver?.correctedTraceMap??Object.fromEntries(this.unroutedTraceRecoverySolver.getOutput().allTracesMerged.map(t=>[t.mspPairId,t]))}],{onSolved:t=>{}}),sh("traceLabelOverlapAvoidanceSolver",wCo,t=>{const e=t.traceOverlapShiftSolver?.correctedTraceMap??Object.fromEntries(t.unroutedTraceRecoverySolver.getOutput().allTracesMerged.map(i=>[i.mspPairId,i])),n=Object.values(e),o=t.netLabelPlacementSolver.netLabelPlacements;return[{inputProblem:t.inputProblem,traces:n,netLabelPlacements:o}]}),sh("traceElbowTransitionSimplificationSolver",swe,t=>{const e=t.traceLabelOverlapAvoidanceSolver.getOutput();return[{inputProblem:t.inputProblem,traces:e.traces,completedReroutes:e.completedReroutes,netLabelPlacements:t.traceLabelOverlapAvoidanceSolver.netLabelPlacements,paddingBuffer:.1}]}),sh("traceCleanupSolver",avt,t=>{const n=t.traceElbowTransitionSimplificationSolver.getOutput().traces,o=t.traceOverlapShiftSolver,i=new Set([...t.inputProblem.directConnections,...t.inputProblem.netConnections].filter(a=>a.allowInlineNetLabel).map(a=>a.netId)),r=new Set;for(let a=0;a<o.inputTracePaths.length;a++){const A=o.inputTracePaths[a],c=o.correctedTraceMap[A.mspPairId];for(let l=a+1;l<o.inputTracePaths.length;l++){const u=o.inputTracePaths[l];if(A.globalConnNetId===u.globalConnNetId||!i.has(A.userNetId??"")&&!i.has(u.userNetId??""))continue;const g=o.correctedTraceMap[u.mspPairId],h=WH(A.tracePath,u.tracePath).length;WH(c.tracePath,g.tracePath).length>h&&(r.add(A.mspPairId),r.add(u.mspPairId))}}const s=t.traceLabelOverlapAvoidanceSolver.labelMergingSolver.getOutput();return[{inputProblem:t.inputProblem,allTraces:n,allLabelPlacements:s.netLabelPlacements,mergedLabelNetIdMap:s.mergedLabelNetIdMap,paddingBuffer:.1,eligibleTraceIds:r}]}),sh("netLabelPlacementSolver",BQt,t=>{const e=t.traceCleanupSolver?.getOutput().traces??t.traceLabelOverlapAvoidanceSolver.getOutput().traces;return[{inputProblem:t.inputProblem,inputTraceMap:Object.fromEntries(e.map(n=>[n.mspPairId,n]))}]}),sh("example28Solver",A2o,t=>{const e=t.traceCleanupSolver?.getOutput().traces??t.traceLabelOverlapAvoidanceSolver.getOutput().traces;return[{inputProblem:t.inputProblem,traces:e,netLabelPlacements:t.netLabelPlacementSolver.netLabelPlacements}]}),sh("availableNetOrientationSolver",E2o,t=>[{inputProblem:t.inputProblem,traces:t.example28Solver.outputTraces,netLabelPlacements:t.example28Solver.outputNetLabelPlacements}]),sh("postLabelTraceOverlapShiftSolver",CQt,t=>[{inputProblem:t.inputProblem,inputTracePaths:t.availableNetOrientationSolver.traces,globalConnMap:t.mspConnectionPairSolver.globalConnMap,traceIdsToShift:new Set(t.availableNetOrientationSolver.netLabelConnectorTraceIds)}]),sh("railNetLabelCornerPlacementSolver",M2o,t=>[{inputProblem:t.inputProblem,traces:Object.values(t.postLabelTraceOverlapShiftSolver.correctedTraceMap),netLabelPlacements:t.availableNetOrientationSolver.outputNetLabelPlacements}]),sh("traceAnchoredNetLabelOverlapSolver",pxo,t=>[{inputProblem:t.inputProblem,traces:t.railNetLabelCornerPlacementSolver.getOutput().traces,netLabelPlacements:t.railNetLabelCornerPlacementSolver.outputNetLabelPlacements}]),sh("preAlignmentNetLabelTraceCollisionSolver",Nvt,t=>[{inputProblem:t.inputProblem,traces:t.railNetLabelCornerPlacementSolver.getOutput().traces,netLabelPlacements:t.traceAnchoredNetLabelOverlapSolver.outputNetLabelPlacements}]),sh("preAlignmentTraceElbowTransitionSimplificationSolver",swe,t=>{const e=t.preAlignmentNetLabelTraceCollisionSolver.getOutput();return[{inputProblem:t.inputProblem,traces:e.traces,completedReroutes:e.completedReroutes,netLabelPlacements:e.netLabelPlacements,paddingBuffer:.1}]}),sh("traceCleanupSolver2",avt,t=>{const e=t.preAlignmentTraceElbowTransitionSimplificationSolver.getOutput(),n=t.traceLabelOverlapAvoidanceSolver.labelMergingSolver.getOutput();return[{inputProblem:t.inputProblem,allTraces:e.traces,allLabelPlacements:e.netLabelPlacements,mergedLabelNetIdMap:n.mergedLabelNetIdMap,paddingBuffer:.1,operations:["rerouting_generated_net_label_connector_crossings","aligning_same_net_rails"],eligibleTraceIds:new Set(t.traceCleanupSolver.getOutput().traces.map(o=>o.mspPairId)),netLabelConnectorTraceIds:t.availableNetOrientationSolver.netLabelConnectorTraceIds}]}),sh("netLabelTraceCollisionSolver",Nvt,t=>{const e=t.preAlignmentNetLabelTraceCollisionSolver.getOutput(),n=t.traceCleanupSolver2.getOutput(),o=kyo({originalTraces:e.traces,reroutedTraces:n.traces,netLabelPlacements:e.netLabelPlacements}),i=new Map(e.traces.map(s=>[s.mspPairId,s]));let r=o.netLabelPlacements;for(const s of o.traces){const a=i.get(s.mspPairId);if(!a||a.tracePath===s.tracePath)continue;const A=r;r=jH({trace:a,originalTracePath:a.tracePath,reroutedTracePath:s.tracePath,netLabelPlacements:A}).map((l,u)=>{const g=A[u];return g.orientation==="y+"||g.orientation==="y-"?l:g})}return[{inputProblem:t.inputProblem,traces:o.traces,netLabelPlacements:r}]}),sh("finalTraceElbowTransitionSimplificationSolver",swe,t=>{const e=t.netLabelTraceCollisionSolver.getOutput();return[{inputProblem:t.inputProblem,traces:e.traces,completedReroutes:e.completedReroutes,netLabelPlacements:e.netLabelPlacements,paddingBuffer:.1}]}),sh("netLabelNetLabelCollisionSolver",ewe,t=>{const e=t.finalTraceElbowTransitionSimplificationSolver.getOutput();return[{inputProblem:t.inputProblem,traces:e.traces,netLabelPlacements:e.netLabelPlacements}]}),sh("sameNetJunctionAlignmentSolver",u3o,t=>{const e=t.netLabelNetLabelCollisionSolver.getOutput();return[{inputProblem:t.inputProblem,traces:t.netLabelNetLabelCollisionSolver.traces,netLabelPlacements:e.netLabelPlacements,netLabelConnectorTraceIds:t.availableNetOrientationSolver.netLabelConnectorTraceIds}]}),sh("inlineNetLabelSolver",H3o,t=>{const e=t.sameNetJunctionAlignmentSolver.getOutput(),n=[...t.traceLabelOverlapAvoidanceSolver.getOutput().completedReroutes,...t.preAlignmentNetLabelTraceCollisionSolver.getOutput().completedReroutes,...t.netLabelTraceCollisionSolver.getOutput().completedReroutes];return[{inputProblem:t.inputProblem,traces:e.traces,netLabelPlacements:e.netLabelPlacements,completedReroutes:n,resolveTraceCollisions:!0,netLabelConnectorTraceIds:t.availableNetOrientationSolver.netLabelConnectorTraceIds}]}),sh("netLabelToTraceSolver",q3o,t=>{const e=t.inlineNetLabelSolver.getOutput();return[{inputProblem:t.inputProblem,...e}]})];constructor(t,e){super(),this.hideRatsNet=e?.hideRatsNet??!1,this.inputProblem=this.cloneAndCorrectInputProblem(t),this.MAX_ITERATIONS=1e6,this.startTimeOfPhase={},this.endTimeOfPhase={},this.timeSpentOnPhase={},this.firstIterationOfPhase={}}getConstructorParams(){return[this.inputProblem,{hideRatsNet:this.hideRatsNet}]}currentPipelineStepIndex=0;cloneAndCorrectInputProblem(t){const e=structuredClone({...t,_chipObstacleSpatialIndex:void 0,_hideRatsNet:this.hideRatsNet});return MCo(e),PCo(e),e}_step(){const 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}const e=t.getConstructorParams(this);this.activeSubSolver=new t.solverClass(...e),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();const t=[zh(this.inputProblem,{hideRatsNet:this.hideRatsNet}),...this.pipelineDef.map(n=>this[n.solverName]?.visualize()).filter(Boolean).map((n,o)=>{for(const i of n.rects??[])i.step=o;for(const i of n.points??[])i.step=o;for(const i of n.circles??[])i.step=o;for(const i of n.texts??[])i.step=o;for(const i of n.lines??[])i.step=o;return n})];if(t.length===1)return t[0];const e={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||[])};return dCo(e,this.inputProblem),e}preview(){return this.activeSubSolver?this.activeSubSolver.preview():super.preview()}},Bwt={flexGrow:0,flexShrink:1,flexBasis:0,alignSelf:"auto",width:void 0,height:void 0},bwt=class{id;metadata;size={width:0,height:0};position={x:0,y:0};style;constructor(t={}){this.style={...Bwt,...t},this.id=t.id,this.metadata=t.metadata}},X3o=class extends bwt{build(){}},Swt=class Cit extends bwt{children=[];direction="row";columnGap=0;rowGap=0;justifyContent="flex-start";alignItems="stretch";constructor(e,n,o={}){super({}),this.size.width=e,this.size.height=n,this.id=o.id,Object.assign(this,o)}addChild(e,n){if(e instanceof Cit){const i=e;return n&&(i.style={...Bwt,...n}),this.children.push(i),i}const o=new X3o(e);return this.children.push(o),o}build(){const e=this.direction.startsWith("row"),n=e?"width":"height",o=e?"height":"width",i=e?this.columnGap:this.rowGap;e?this.rowGap:this.columnGap;const r=i*Math.max(0,this.children.length-1),s=this.size[n],a=this.size[o];let A=0,c=0,l=0;for(const C of this.children)A+=C.style.flexBasis,c+=C.style.flexGrow,l+=C.style.flexShrink;const u=s-A-r;for(const C of this.children){let y=C.style.flexBasis;u>0&&c>0?y+=u*C.style.flexGrow/c:u<0&&l>0&&(y+=u*C.style.flexShrink/l,y<0&&(y=0)),C.size[n]=y;const x=C.style.alignSelf!=="auto"?C.style.alignSelf:this.alignItems,E=e?C.style.height:C.style.width;E!==void 0?C.size[o]=E:x==="stretch"&&(C.size[o]=a)}const g=this.children.reduce((C,y)=>C+y.size[n],0)+r,h=s-g;let d=0,p=i;const m=this.children.length;switch(this.justifyContent){case"flex-start":break;case"flex-end":d=h;break;case"center":d=h/2;break;case"space-between":p=m>1?i+h/(m-1):0;break;case"space-around":p=i+h/m,d=p/2;break;case"space-evenly":p=i+h/(m+1),d=p;break}const _=this.direction.endsWith("reverse")?[...this.children].reverse():this.children;let f=d;for(const C of _)e?(C.position.x=this.direction==="row"?f:s-f-C.size.width,C.position.y=I(C,o,a,this.alignItems)):(C.position.y=this.direction==="column"?f:s-f-C.size.height,C.position.x=I(C,o,a,this.alignItems)),f+=C.size[n]+p;for(const C of this.children)C instanceof Cit&&C.build();function I(C,y,x,E){switch(C.style.alignSelf!=="auto"?C.style.alignSelf:E){case"flex-start":return 0;case"flex-end":return x-C.size[y];case"center":return(x-C.size[y])/2;default:return 0}}}},Qwt=class extends Swt{constructor(t,e,n={}){super(t,e,n)}getLayout(){this.build();const t={};return this._collectLayout(this,t),t}_collectLayout(t,e,n={counter:0}){for(const o of t.children){const i=o.id??`_$$${n.counter++}`;e[i]={position:o.position,size:o.size},o instanceof Swt&&this._collectLayout(o,e,n)}}},vwt=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20].map(t=>`hsl(${t*360/21}deg, 100%, 50%)`),Z3o=t=>{let e=0;for(let n=0;n<t.length;n++)e=(e<<5)-e+t.charCodeAt(n);return e},wwt=t=>vwt[Math.abs(Z3o(t))%vwt.length],eEo=t=>{const e=d=>d?typeof d=="string"?d:d.join(" "):void 0,n=["display:grid","background-color:gray"],{gridTemplateRows:o,gridTemplateColumns:i,gap:r,justifyItems:s,alignItems:a,containerWidth:A,containerHeight:c}=t.opts,l=e(o);l&&n.push(`grid-template-rows:${l}`);const u=e(i);if(u&&n.push(`grid-template-columns:${u}`),r!==void 0)if(typeof r=="number")n.push(`gap:${r}px`);else{const[d,p]=r;n.push(`row-gap:${d}px`,`column-gap:${p}px`)}s&&n.push(`justify-items:${s}`),a&&n.push(`align-items:${a}`),A!=null&&n.push(`width:${A}px`),c!=null&&n.push(`height:${c}px`);const g=n.join(";"),h=t.opts.children.map(d=>{const p=["display:flex",`background-color:${wwt(d.key)}`];if(d.area)p.push(`grid-area:${d.area}`);else{if(typeof d.row=="string"&&d.row.includes("/"))p.push(`grid-row:${d.row}`);else{const I=d.rowStart??d.row,C=d.rowEnd,y=d.rowSpan;I!==void 0||C!==void 0?I!==void 0&&C!==void 0?p.push(`grid-row:${I} / ${C}`):I!==void 0?y!==void 0?p.push(`grid-row:${I} / span ${y}`):p.push(`grid-row-start:${I}`):p.push(`grid-row-end:${C}`):y!==void 0&&p.push(`grid-row:auto / span ${y}`)}if(typeof d.column=="string"&&d.column.includes("/"))p.push(`grid-column:${d.column}`);else{const I=d.columnStart??d.column,C=d.columnEnd,y=d.columnSpan;I!==void 0||C!==void 0?I!==void 0&&C!==void 0?p.push(`grid-column:${I} / ${C}`):I!==void 0?y!==void 0?p.push(`grid-column:${I} / span ${y}`):p.push(`grid-column-start:${I}`):p.push(`grid-column-end:${C}`):y!==void 0&&p.push(`grid-column:auto / span ${y}`)}}const m=p.join(";"),_=["font-size: 7px"];if(d.contentWidth!==void 0){const I=typeof d.contentWidth=="string"?d.contentWidth:`${d.contentWidth}px`;_.push(`width:${I}`)}else _.push(`width:${d.key.length*5}px`);if(d.contentHeight!==void 0){const I=typeof d.contentHeight=="string"?d.contentHeight:`${d.contentHeight}px`;_.push(`height:${I}`)}const f=_.join(";");return` <div id="${d.key}" style="${m}"><div style="${f}">${d.key}</div></div>`});return`<div style="${g}">
${h.join(`
`)}
</div>`},tEo=t=>{const e=t.layout(),n={title:"CssGrid",coordinateSystem:"screen",lines:[],circles:[],points:[],rects:[],texts:[]},{cells:o}=e;for(const i of o){const{x:r,y:s,width:a,height:A,key:c}=i;n.rects.push({center:{x:r+a/2,y:s+A/2},width:a,height:A,fill:wwt(c),label:c})}return n};function Xle(t){return t.replace(/repeat\((\d+),\s*([^)]+)\)/g,(e,n,o)=>Array(Number(n)).fill(o.trim()).join(" "))}function Zle(t){return t.trim().split(/\s+/).filter(Boolean)}function Pwt(t){return t?Zle(Xle(t)).length:0}function Mwt(t,e){if(t==="auto")return{fr:1};if(t.endsWith("%")){const o=parseFloat(t);return e!=null?e*o/100:0}if(t.endsWith("px"))return parseFloat(t);if(t.endsWith("em"))return parseFloat(t)*16;if(t.endsWith("fr"))return{fr:parseFloat(t)};const n=parseFloat(t);return Number.isNaN(n)?0:n}function Dwt(t,e){return t>0?t:e+2+t}var nEo=t=>{const e=t.opts,n=e.children;let o,i;if("gridTemplate"in e&&typeof e.gridTemplate=="string"){const[x,E]=e.gridTemplate.split("/");o=x?.trim(),i=E?.trim()}else o=typeof e.gridTemplateRows=="string"?e.gridTemplateRows:void 0,i=typeof e.gridTemplateColumns=="string"?e.gridTemplateColumns:void 0;const r=Pwt(i),s=Pwt(o);function a(x,E,B,S){if(!x)return 0;const Q=Xle(x),w=Zle(Q),M=w.length;let k=0;for(let F=0;F<w.length;F++){const O=w[F];if(O.endsWith("px"))k+=parseFloat(O);else if(O.endsWith("em"))k+=parseFloat(O)*16;else if(O.endsWith("fr")||O==="auto"){let U=0;for(const Y of E){const W=B?Y.columnStart||Y.column:Y.rowStart||Y.row,te=B?Y.columnSpan||1:Y.rowSpan||1,j=B?Y.contentWidth:Y.contentHeight,J=(typeof W=="number"?W:parseInt(W||"1"))-1,oe=typeof te=="number"?te:parseInt(te.toString());if(J<=F&&F<J+oe&&j){const ie=typeof j=="string"&&j.endsWith("px")?parseFloat(j):typeof j=="number"?j:0;U=Math.max(U,ie/oe)}}k+=U}}const R=S*(M-1);return k+R}function A(x,E,B,S=!0,Q=1){if(!x)return[];if(E==null){const j=Xle(x),J=Zle(j),oe=J.length,ie=ge=>ge===void 0?0:typeof ge=="number"?ge:(ge.endsWith("px"),parseFloat(ge)),ne=new Array(oe).fill(0);let le=0;for(const ge of n){const _e=S?typeof ge.columnSpan=="number"?ge.columnSpan:ge.columnSpan?parseInt(ge.columnSpan.toString()):1:typeof ge.rowSpan=="number"?ge.rowSpan:ge.rowSpan?parseInt(ge.rowSpan.toString()):1,ue=S?ge.contentWidth:ge.contentHeight,fe=ie(ue)/_e;let pe;S?(ge.columnStart!==void 0||ge.column!==void 0)&&(pe=parseInt(ge.columnStart??ge.column)-1):(ge.rowStart!==void 0||ge.row!==void 0)&&(pe=parseInt(ge.rowStart??ge.row)-1),(pe===void 0||Number.isNaN(pe))&&(S?pe=le%oe:pe=Math.floor(le/Q),le+=_e);for(let ye=0;ye<_e&&pe+ye<oe;ye++)ne[pe+ye]=Math.max(ne[pe+ye],fe)}return J.forEach((ge,_e)=>{const ue=Mwt(ge,void 0);typeof ue=="number"&&(ne[_e]=ue)}),ne}const w=Xle(x),M=Zle(w),k=M.length;let R=E;R==null&&(R=a(x,n,S,B));const F=R-B*(k-1);let O=0,U=0;const Y=[],W=[];M.forEach((j,J)=>{const oe=Mwt(j,F);typeof oe=="number"?(W.push(oe),O+=oe):oe&&typeof oe=="object"&&"fr"in oe?(W.push(oe),U+=oe.fr,Y.push({idx:J,fr:oe.fr})):(W.push(0),O+=0)});const te=Math.max(F-O,0);return W.map(j=>typeof j=="number"?j:U>0?te/U*j.fr:0)}const c=typeof e.gap=="number"?e.gap:Array.isArray(e.gap)?e.gap[0]:0,l=typeof e.gap=="number"?e.gap:Array.isArray(e.gap)?e.gap[1]:0,u=A(o,e.containerHeight,c,!1,r||1),g=A(i,e.containerWidth,l,!0,s||1),h=u.length;let d=g.length;d===0&&n.length>0&&(d=1);const p=[];let m=0;for(const x of n){let E=x.rowStart!==void 0?x.rowStart:x.row,B=x.columnStart!==void 0?x.columnStart:x.column,S=x.rowSpan!==void 0?typeof x.rowSpan=="string"?parseInt(x.rowSpan):x.rowSpan:1,Q=x.columnSpan!==void 0?typeof x.columnSpan=="string"?parseInt(x.columnSpan):x.columnSpan:1;if(x.rowEnd!==void 0){const k=typeof x.rowEnd=="string"?parseInt(x.rowEnd):x.rowEnd;E!==void 0?S=k-(typeof E=="string"?parseInt(E):E):E=k-S}if(x.columnEnd!==void 0){const k=typeof x.columnEnd=="string"?parseInt(x.columnEnd):x.columnEnd;B!==void 0?Q=k-(typeof B=="string"?parseInt(B):B):B=k-Q}if(typeof E=="string"&&(E=parseInt(E)),typeof B=="string"&&(B=parseInt(B)),typeof E=="number"&&E<0&&(E=Dwt(E,h)),typeof B=="number"&&B<0&&(B=Dwt(B,d)),E===void 0&&B!==void 0)E=1;else if(B===void 0&&E!==void 0)B=1;else if(E===void 0&&B===void 0){const k=m;E=Math.floor(k/d)+1,B=k%d+1}const w=E-1,M=B-1;S=Math.max(1,S),Q=Math.max(1,Q),p.push({key:x.key,row:w,column:M,rowSpan:S,columnSpan:Q,x:0,y:0,width:0,height:0}),m+=Q}let _=u.length,f=g.length;for(const x of p)x.row+x.rowSpan>_&&(_=x.row+x.rowSpan),x.column+x.columnSpan>f&&(f=x.column+x.columnSpan);if(u.length===0&&_>0&&e.containerHeight){const x=_,B=(e.containerHeight-c*(x-1))/x;for(let S=0;S<x;S++)u.push(B)}else for(;u.length<_;)u.push(0);if(g.length===0&&f>0&&e.containerWidth){const x=f,B=(e.containerWidth-l*(x-1))/x;for(let S=0;S<x;S++)g.push(B)}else if(g.length===0&&n.length>0&&e.containerWidth)g.push(e.containerWidth);else for(;g.length<f;)g.push(0);const I=(x,E,B)=>{let S=0;for(let Q=0;Q<x;Q++)S+=E[Q]||0,S+=B;return S},C=(x,E,B,S)=>{let Q=0;for(let w=x;w<x+E;w++)Q+=B[w]||0,w>x&&(Q+=S);return Q},y={};for(const x of p){const E=n.find(W=>W.key===x.key),B=I(x.column,g,l),S=I(x.row,u,c),Q=C(x.column,x.columnSpan,g,l),w=C(x.row,x.rowSpan,u,c),M=W=>W===void 0?0:typeof W=="string"?W.endsWith("px")?parseFloat(W):W.endsWith("%")?0:parseFloat(W):W,k=M(E?.contentWidth),R=M(E?.contentHeight);let F=Q,O=w,U=B,Y=S;if(k>0)switch(F=k,e.justifyItems||"stretch"){case"start":U=B;break;case"end":U=B+Q-F;break;case"center":U=B+(Q-F)/2;break;case"stretch":F=Q,U=B;break}if(R>0)switch(O=R,e.alignItems||"stretch"){case"start":Y=S;break;case"end":Y=S+w-O;break;case"center":Y=S+(w-O)/2;break;case"stretch":O=w,Y=S;break}x.x=U,x.y=Y,x.width=F,x.height=O,y[x.key]={x:U,y:Y,width:F,height:O}}return{cells:p,rowSizes:u,columnSizes:g,rowGap:c,columnGap:l,itemCoordinates:y}},oEo=class{opts;constructor(t){this.opts=t}layout(){return nEo(this)}convertToHtml(){return eEo(this)}visualize(){return tEo(this)}},iEo=Object.defineProperty,Nwt=Object.getOwnPropertySymbols,rEo=Object.prototype.hasOwnProperty,sEo=Object.prototype.propertyIsEnumerable,Rwt=(t,e,n)=>e in t?iEo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Twt=(t,e)=>{for(var n in e||(e={}))rEo.call(e,n)&&Rwt(t,n,e[n]);if(Nwt)for(var n of Nwt(e))sEo.call(e,n)&&Rwt(t,n,e[n]);return t},aEo=t=>{switch(t){case"left":return{x:-1,y:0};case"right":return{x:1,y:0};case"top":return{x:0,y:1};case"bottom":return{x:0,y:-1}}},AEo=t=>{var e,n;const o=Xc(t).schematic_component.list(),i=Xc(t).schematic_net_label.list(),r=Xc(t).schematic_port.list(),s={};for(const a of o){const A=Xc(t).source_component.get(a.source_component_id);s[a.schematic_component_id]=A?.name}for(const a of i){const A=Xc(t).source_net.get(a.source_net_id);if(!A?.name)continue;let c=0;for(;Object.values(s).includes(`NL_${A.name}${c}`);)c++;s[a.schematic_net_label_id]=`NL_${A.name}${c}`}for(const a of r){const A=Xc(t).source_port.get(a.source_port_id);if(!A)continue;const c=Xc(t).source_component.get(A.source_component_id);if(!c?.name)continue;const l=`${c.name}_${(n=(e=A?.name)!=null?e:A?.pin_number)!=null?n:""}`;s[a.schematic_port_id]=l}return s},cEo=t=>{var e;const n=Xc(t),o=new Set(n.schematic_net_label.list().map(r=>{var s,a,A,c;return`${(a=(s=r.anchor_position)==null?void 0:s.x)!=null?a:r.center.x},${(c=(A=r.anchor_position)==null?void 0:A.y)!=null?c:r.center.y}`})),i=[];for(const r of n.schematic_port.list()){const s=`${r.center.x},${r.center.y}`;if(o.has(s))continue;const a=n.source_port.get(r.source_port_id);if(!a)continue;const A=n.source_net.getWhere({subcircuit_connectivity_map_key:a.subcircuit_connectivity_map_key});if(!A)continue;const c=n.source_trace.list().find(h=>{var d;return(d=h.connected_source_port_ids)==null?void 0:d.includes(r.source_port_id)}),l=n.schematic_trace.getWhere({source_trace_id:c?.source_trace_id}),g={type:"schematic_net_label",schematic_net_label_id:`netlabel_for_${r.schematic_port_id}`,schematic_port_id:r.schematic_port_id,text:A.name,source_net_id:A.source_net_id,source_trace_id:c?.source_trace_id,schematic_trace_id:l?.schematic_trace_id,anchor_position:Twt({},r.center),center:Twt({},r.center),anchor_side:dWn((e=r.facing_direction)!=null?e:"right")};i.push(g)}return i},lEo=(t,e={})=>{const n={boxes:[],pins:[]},o=Xc(t).schematic_component.list();let i=Xc(t).schematic_net_label.list();e.inferNetLabels&&(i=i.concat(cEo(t)));const r=e.useReadableIds?AEo(t):{},s=A=>e.useReadableIds&&r[A]?r[A]:A;let a=0;for(const A of o){const c={boxId:s(A.schematic_component_id),kind:"floating",center:A.center};n.boxes.push(c);const l={pinId:`${s(A.schematic_component_id)}_center`,color:"component_center",networkId:`center_${A.schematic_component_id}`,offset:{x:0,y:0},boxId:s(A.schematic_component_id)};n.pins.push(l);const u=Xc(t).schematic_port.list({schematic_component_id:A.schematic_component_id});for(const g of u){const h=Xc(t).source_port.get(g.source_port_id);let d=h?.subcircuit_connectivity_map_key,p="normal";if(d){const _=Xc(t).source_net.getWhere({subcircuit_connectivity_map_key:h?.subcircuit_connectivity_map_key});_&&(_.is_power||_.name.startsWith("V"))&&(p="vcc"),_&&(_.is_ground||_.name.startsWith("GND"))&&(p="gnd")}else d=`disconnected-${a++}`,p="not_connected";const m={pinId:s(g.schematic_port_id),color:p,networkId:d,offset:{x:g.center.x-c.center.x,y:g.center.y-c.center.y},boxId:s(A.schematic_component_id)};n.pins.push(m)}}for(const A of i){const c=Xc(t).source_net.get(A.source_net_id);let l=c?.subcircuit_connectivity_map_key,u="normal";l?(c&&(c.is_power||c.name.startsWith("V"))&&(u="vcc"),c&&(c.is_ground||c.name.startsWith("GND"))&&(u="gnd")):(l=`disconnected-${a++}`,u="not_connected");const g=aEo(A.anchor_side),h={x:A.anchor_position.x-g.x*A.text.length*.18*.5,y:A.anchor_position.y-g.y*.18};let d={x:0,y:0};A.anchor_position&&(d={x:A.anchor_position.x-h.x,y:A.anchor_position.y-h.y});const p={boxId:s(A.schematic_net_label_id),kind:"fixed",center:h,boxAttributes:{is_net_label:!0,source_net_id:A.source_net_id,source_trace_id:A.source_trace_id}};n.boxes.push(p);const m={pinId:`${s(A.schematic_net_label_id)}_pin`,boxId:s(A.schematic_net_label_id),networkId:l,color:u,offset:d};n.pins.push(m),n.pins.push({pinId:`${s(A.schematic_net_label_id)}_center`,boxId:s(A.schematic_net_label_id),networkId:`${s(A.schematic_net_label_id)}_center`,color:"netlabel_center",offset:{x:0,y:0}})}return n},uEo=t=>t?"x"in t&&"y"in t?t:"center"in t?t.center:{x:(t.minX+t.maxX)/2,y:(t.minY+t.maxY)/2}:{x:0,y:0},e0e=(t,e)=>{const n=t.boxes.find(c=>c.boxId===e),o=t.pins.filter(c=>c.boxId===e);if(!n)throw new Error(`Box "${e}" not found`);const i=n.center??{x:0,y:0};let r=1/0,s=1/0,a=-1/0,A=-1/0;for(const c of o)r=Math.min(r,c.offset.x+i.x),s=Math.min(s,c.offset.y+i.y),a=Math.max(a,c.offset.x+i.x),A=Math.max(A,c.offset.y+i.y);return{minX:r,minY:s,maxX:a,maxY:A}},oO=(t,e,n)=>`hsl(${t*360/e}, 100%, 50%, ${n??1})`,gEo=t=>{const e=new Set;for(const n of t.pins)e.add(n.networkId);return Array.from(e)},kwt={not_connected:"rgba(0, 0, 0, 0.2)",normal:"blue",vcc:"orange",gnd:"purple",component_center:"gray"},dEo=["red","green","blue","yellow","purple","orange","brown","gray","black","white"];function hEo(t){let e=0;for(let n=0;n<t.length;n++)e=(e<<5)-e+t.charCodeAt(n);return e}var Fwt=t=>t.startsWith("rgb")||t.startsWith("hsl")||t.startsWith("#")||dEo.includes(t)?t:t in kwt?kwt[t]:oO(hEo(t)%50,50),zN=(t,e)=>{const n={points:[],lines:[],rects:[],circles:[],texts:[],coordinateSystem:"cartesian",title:"BPC Graph Graphics"},o=new Map,i=new Map;for(const a of t.boxes){const A=e0e(t,a.boxId),c=uEo(A);n.rects.push({label:a.boxId,center:c,width:A.maxX-A.minX+.1,height:A.maxY-A.minY+.1,fill:"rgba(0, 0, 0, 0.2)"});const l=t.pins.filter(g=>g.boxId===a.boxId),u=a.center??{x:0,y:0};for(const g of l){const h={x:g.offset.x+u.x,y:g.offset.y+u.y},d=`${h.x.toFixed(6)},${h.y.toFixed(6)}`;i.has(d)||i.set(d,[]),i.get(d).push({box:a,pin:g}),o.set(`${a.boxId}.${g.pinId}`,h)}}for(const[a,A]of i){const c=a.split(",").map(Number),l=c[0],u=c[1];for(let g=0;g<A.length;g++){const h=A[g],{box:d,pin:p}=h;let m={x:l,y:u};if(A.length>1){const _=d.center??{x:0,y:0},f=_.x-l,I=_.y-u,C=Math.sqrt(f*f+I*I);let y=0,x=0;if(C>0)y=f/C,x=I/C;else{const E=g*2*Math.PI/A.length;y=Math.cos(E),x=Math.sin(E)}m={x:l+.01*y,y:u+.01*x}}o.set(`${d.boxId}.${p.pinId}`,m),n.points.push({...m,label:[p.pinId,p.color,p.networkId].join(`
`),color:Fwt(p.color)})}}const r=gEo(t);for(let a=0;a<r.length;a++){const A=r[a],c=oO(a,r.length,.5),u=t.pins.filter(g=>g.networkId===A).map(g=>({pin:g,position:o.get(`${g.boxId}.${g.pinId}`)}));for(let g=0;g<u.length;g++){const{position:h}=u[g];for(let d=g+1;d<u.length;d++){const{position:p}=u[d];n.lines.push({points:[h,p],strokeColor:e?.grayNetworks?"rgba(0, 0, 0, 0.05)":c})}}}const s=V5(n);return e?.title&&(n.title=e.title,n.texts.push({text:e.title,x:s.minX,y:s.maxY,fontSize:(s.maxY-s.minY)*.05,anchorSide:"bottom_left"})),e?.caption&&n.texts.push({text:e.caption,x:s.minX,y:s.minY,fontSize:(s.maxY-s.minY)*.05,anchorSide:"top_left"}),n},t0e=(t,e,n)=>{const o=t.pins.find(s=>s.pinId===n&&s.boxId===e);if(!o)throw new Error(`Pin "${n}" not found`);const i=t.boxes.find(s=>s.boxId===o.boxId);if(!i)throw new Error(`Box "${o.boxId}" not found`);const r=i.center??{x:0,y:0};return{x:o.offset.x+r.x,y:o.offset.y+r.y}},pEo=(t,e,n)=>{const o=typeof n=="string"?t.pins.find(h=>h.pinId===n&&h.boxId===e):n;if(!o)throw new Error(`Pin not found "${n}"`);if(!(typeof e=="string"?t.boxes.find(h=>h.boxId===e):e))throw new Error(`Box not found for pin "${n}" (looked for "${o.boxId}")`);const r=e0e(t,o.boxId),s=t0e(t,o.boxId,o.pinId),a=r.maxX-r.minX,A=r.maxY-r.minY;if(a===0&&A===0)return Math.abs(o.offset.x)>Math.abs(o.offset.y)?o.offset.x>0?"x+":"x-":o.offset.y>0?"y+":"y-";if(a===0){if(Math.abs(s.y-r.minY)<1e-4)return"y-";if(Math.abs(s.y-r.maxY)<1e-4)return"y+"}if(A===0){if(Math.abs(s.x-r.minX)<1e-4)return"x-";if(Math.abs(s.x-r.maxX)<1e-4)return"x+"}const c=Math.abs(s.x-r.minX)<1e-4,l=Math.abs(s.x-r.maxX)<1e-4,u=Math.abs(s.y-r.minY)<1e-4,g=Math.abs(s.y-r.maxY)<1e-4;if((c||l)&&(u||g))return o.offset.x>0?"x+":"x-";if(c)return"x-";if(l)return"x+";if(u)return"y-";if(g)return"y+";throw new Error(`Pin "${o.pinId}" not on the edge of the box "${o.boxId}" so we couldn't determine the direction`)},iO=(t,e,n)=>{try{return pEo(t,e,n)}catch{return null}},mEo=t=>{const e=new Map,n=[];t.nodes.forEach((r,s)=>{e.set(r.id,s),n.push(r.id)});const o=t.nodes.length,i=Array.from({length:o},()=>Array.from({length:o},()=>0));for(const[r,s]of t.undirectedEdges){const a=e.get(r),A=e.get(s);a!==void 0&&A!==void 0&&a!==A&&(i[a][A]=1,i[A][a]=1)}for(let r=0;r<o;++r)i[r][r]=1;return{matrix:i,mapping:e,indexMapping:n}},n0e=t=>{const e=[],n=[],o=new Map;for(const r of t.boxes)r.kind,o.set(r.boxId,r.center),e.push({id:r.boxId,boxId:r.boxId,color:"box",x:r.center?.x,y:r.center?.y});const i={};for(const r of t.pins){const s=`${r.boxId}-${r.pinId}`,a=o.get(r.boxId);e.push({id:s,boxId:r.boxId,pinId:r.pinId,color:r.color,x:a?a.x+r.offset.x:void 0,y:a?a.y+r.offset.y:void 0}),i[r.networkId]??=[],i[r.networkId].push(s)}for(const r of Object.values(i))for(let s=0;s<r.length;s++)for(let a=s+1;a<r.length;a++)n.push([r[s],r[a]]);for(const r of t.boxes)for(const s of t.pins)s.boxId===r.boxId&&n.push([r.boxId,`${r.boxId}-${s.pinId}`]);return{nodes:e,undirectedEdges:n}},_Eo=(t,e,n={})=>{const o=t.length;if(t.some(a=>a.length!==o))throw new Error("adjMatrix must be square");let i=(n.nodeInitialColors??Array.from({length:o},()=>"_")).slice();const r=a=>{const A={};for(const c of a)A[c]=(A[c]??0)+1;return A},s=[];s.push(r(i));for(let a=0;a<e;a++){const A=Array(o);for(let c=0;c<o;c++){const l=[];for(let u=0;u<o;u++)t[c][u]&&l.push(i[u]);l.sort(),A[c]=`${i[c]}|${l.join(",")}`}i=A,s.push(r(i))}return s},fEo=(t,e)=>{let n=0;const o=Math.min(t.length,e.length);for(let i=0;i<o;i++){const r=t[i],s=e[i],a=new Set([...Object.keys(r),...Object.keys(s)]);let A=0,c=0;for(const l of a){const u=r[l]??0,g=s[l]??0;A+=Math.min(u,g),c+=Math.max(u,g)}n+=c===0?0:A/c}return n},IEo=fEo,o0e=2,i0e=(t,e=o0e)=>{const n=n0e(t),{matrix:o,indexMapping:i}=mEo(n);return _Eo(o,e,{nodeInitialColors:i.map(r=>n.nodes.find(s=>s.id===r)?.color??"_")})},fwe=(t,e,{wlDegrees:n=o0e}={})=>{const o=i0e(t,n),i=i0e(e,n);return(o0e+1-IEo(o,i))/(o0e+1)},CEo=t=>{let e=0;for(let n=0;n<t.length;n++)e=(e<<5)-e+t.charCodeAt(n);return Math.abs(e)},Iwe=(t,e={})=>{const n={points:[],lines:[],rects:[],circles:[],texts:[],coordinateSystem:"cartesian",title:"Flat-BPC Graphics"},o=new Map;for(const r of t.nodes){if(r.x===void 0||r.y===void 0)continue;const s={x:r.x,y:r.y};o.set(r.id,s),n.points.push({...s,color:Fwt(r.color),label:r.id})}for(const[r,s]of t.undirectedEdges){const a=o.get(r),A=o.get(s);a&&A&&n.lines.push({points:[a,A],strokeColor:"rgba(0,0,0,0.3)"})}const i=V5(n);return e.title&&n.texts.push({text:e.title,x:i.minX,y:i.maxY,fontSize:(i.maxY-i.minY)*.05,anchorSide:"bottom_left"}),e.caption&&n.texts.push({text:e.caption,x:i.minX,y:i.minY,fontSize:(i.maxY-i.minY)*.05,anchorSide:"top_left"}),n},yEo=t=>{const e=new Map;for(const i of t.pins){const r=t.boxes.find(a=>a.boxId===i.boxId);if(!r||!r.center)throw new Error(`Expected fixed graph – box "${i.boxId}" missing or has no center`);const s={x:r.center.x+i.offset.x,y:r.center.y+i.offset.y};e.has(i.networkId)||e.set(i.networkId,[]),e.get(i.networkId).push(s)}const n=new Map;let o=0;for(const[i,r]of e){if(r.length===0){n.set(i,0);continue}const s=r.reduce((A,c)=>({x:A.x+c.x,y:A.y+c.y}),{x:0,y:0});s.x/=r.length,s.y/=r.length;const a=r.reduce((A,c)=>{const l=c.x-s.x,u=c.y-s.y;return A+Math.sqrt(l*l+u*u)},0);n.set(i,a),o+=a}return{totalNetworkLength:o,networkLengths:n}},xEo=(t,e)=>{const n=t.pins.filter(i=>i.networkId===e),o=[];for(const i of n){const r=Math.atan2(i.offset.y,i.offset.x);o.push(r)}return o},Lwt=t=>{const e=new Map,n=Array.from(new Set(t.pins.map(o=>o.networkId)));for(const o of n){const i=xEo(t,o);e.set(o,i)}return e},EEo=(t,e)=>{const n=2*Math.PI,o=(t%n+n)%n,i=(e%n+n)%n,r=Math.abs(o-i);return Math.min(r,n-r)},BEo=(t,e)=>{if(t.length===0&&e.length===0)return 0;if(t.length===0||e.length===0)return Math.PI;const n=(o,i)=>{let r=0;for(const s of o){let a=1/0;for(const A of i){const c=EEo(s,A);c<a&&(a=c)}r+=a}return r/o.length};return(n(t,e)+n(e,t))/2},bEo=(t,e)=>{const n=new Map,o=Array.from(t.entries()),i=Array.from(e.entries()),r=o.length,s=i.length,a=Array.from({length:r},()=>new Array(s).fill(0));for(let g=0;g<r;g++){const[,h]=o[g];for(let d=0;d<s;d++){const[,p]=i[d];a[g][d]=BEo(h,p)}}const A=new Set(Array.from({length:r},(g,h)=>h)),c=new Set(Array.from({length:s},(g,h)=>h));let l=0;for(;A.size&&c.size;){let g=-1,h=-1,d=1/0;for(const _ of A)for(const f of c){const I=a[_][f];I<d&&(d=I,g=_,h=f)}const[p]=o[g],[m]=i[h];n.set(p,m),l+=d,A.delete(g),c.delete(h)}const u=Math.PI;return l+=(A.size+c.size)*u,{networkMapping:n,distance:l}},Hwt=t=>{const e=Math.min(...t.map(r=>r.offset.x)),n=Math.max(...t.map(r=>r.offset.x)),o=Math.min(...t.map(r=>r.offset.y)),i=Math.max(...t.map(r=>r.offset.y));return{minX:e,maxX:n,minY:o,maxY:i}},SEo=(t,e)=>{const n=A=>{switch(A.side){case"x+":return A.cwDistanceFromCorner;case"y-":return 1+A.cwDistanceFromCorner;case"x-":return 2+A.cwDistanceFromCorner;case"y+":return 3+A.cwDistanceFromCorner}},o=n(t)%4,i=n(e)%4,r=(i-o+4)%4,s=(o-i+4)%4,a=Math.min(r,s);return{cwDistance:r,ccwDistance:s,minDistance:a}},Ib=1e-6,Owt=(t,e)=>{const{minX:n,minY:o,maxX:i,maxY:r}=t,s=(c,l)=>Math.abs(c-l)<Ib;let a,A;if(s(e.x,i)&&e.y>=o-Ib&&e.y<=r+Ib)a="x+",A=(r-e.y)/(r-o);else if(s(e.y,r)&&e.x<=i+Ib&&e.x>=n-Ib)a="y+",A=(e.x-n)/(i-n);else if(s(e.x,n)&&e.y<=r+Ib&&e.y>=o-Ib)a="x-",A=(e.y-o)/(r-o);else if(s(e.y,o)&&e.x>=n-Ib&&e.x<=i+Ib)a="y-",A=(i-e.x)/(i-n);else return null;return A=Math.min(1,Math.max(0,A)),{side:a,cwDistanceFromCorner:A}},QEo=(t,e)=>{const n=[],o=new Set,i=new Set,r=new Set,s=new Set,a=Hwt(t),A=Hwt(e);for(const c of t){const l=e.filter(d=>d.color===c.color).filter(d=>!s.has(d.pinId));if(l.length===0){o.add(c.pinId);continue}const u=Owt(a,c.offset);if(u===null){o.add(c.pinId);continue}let g=1/0,h=l[0];for(const d of l){const p=Owt(A,d.offset);if(p===null)continue;const{minDistance:m}=SEo(u,p);m<g&&(g=m,h=d)}n.push([c,h]),r.add(c.pinId),s.add(h.pinId)}for(const c of e)s.has(c.pinId)||i.add(c.pinId);return{matchedPins:n,unmatchedPin1Ids:o,unmatchedPin2Ids:i}},vEo=class{constructor(t,e){this.floatingGraph=t,this.fixedGraph=e,this.wipGraph={pins:[],boxes:[]},this.fixedToFloatingNetworkMap=this.computeFixedToFloatingNetworkMap(),this.floatingToFixedNetworkMap=new Map(Array.from(this.fixedToFloatingNetworkMap.entries()).map(([n,o])=>[o,n]))}wipGraph;iterations=0;solved=!1;acceptedFloatingBoxIds=new Set;rejectedFloatingBoxIds=new Set;acceptedFixedBoxIds=new Set;assignment=new Map;lastAcceptedEvaluation=null;fixedToFloatingNetworkMap;floatingToFixedNetworkMap;lastComputedEvaluations=[];computeFixedToFloatingNetworkMap(){const t=Lwt(this.floatingGraph),e=Lwt(this.fixedGraph),{networkMapping:n}=bEo(e,t);return n}getNextFloatingBoxId(){const t=this.floatingGraph.boxes.map(o=>o.boxId).filter(o=>!this.acceptedFloatingBoxIds.has(o)&&!this.rejectedFloatingBoxIds.has(o));if(!t.length)throw new Error("No remaining floating box ids");let e=t[0],n=0;for(const o of t){const i=this.floatingGraph.pins.filter(r=>r.boxId===o);i.length>n&&(e=o,n=i.length)}return e}getRemainingFloatingBoxIds(){return this.floatingGraph.boxes.map(t=>t.boxId).filter(t=>!this.acceptedFloatingBoxIds.has(t)&&!this.rejectedFloatingBoxIds.has(t))}getPartialFloatingGraph(t){const e={pins:[],boxes:[]};for(const n of this.floatingGraph.boxes)(this.acceptedFloatingBoxIds.has(n.boxId)||n.boxId===t)&&(e.boxes.push(n),e.pins.push(...this.floatingGraph.pins.filter(o=>o.boxId===n.boxId)));return e}evaluateFloatingBoxAssignment(t){const e=this.getPartialFloatingGraph(t),n=fwe(e,this.wipGraph);let o=null,i=null;const r={floatingBoxId:t,originalWipGraph:this.wipGraph,partialFloatingGraph:e,currentWlDist:n,networkLengths:new Map,wlDistances:new Map,wlVecs:new Map,wipGraphsWithAddedFixedBoxId:new Map};let s=n,a=n,A=1/0;const c=i0e(e);for(const l of this.fixedGraph.boxes.map(u=>u.boxId)){if(this.acceptedFixedBoxIds.has(l))continue;const u=this.getWipGraphWithAddedFixedBoxIdForFloatingAssignment(l,t),g=fwe(e,u),h=i0e(u),{totalNetworkLength:d}=yEo(u);r.wipGraphsWithAddedFixedBoxId.set(l,u),r.wlVecs.set(l,h),r.wlDistances.set(l,g),r.networkLengths.set(l,d);const p=g+d/100;p<s&&(s=p,a=g,A=d,i=u,o=l)}return{bestFixedBoxId:o,bestNewWipGraph:i,bestDist:s,bestWlDist:a,bestTotalNetworkLength:A,lastDistanceEvaluation:r,nextFloatingBoxId:t,partialFloatingGraph:e,floatingBoxWlVec:c}}getPinAssignment(){const t={},e={};for(const[n,o]of this.assignment)t[n]={},e[o]=n;for(const n of this.wipGraph.pins){const o=n.boxId,i=e[o],r=n._floatingPinId,s=n._fixedPinId;t[i][r]=s}return t}step(){if(this.solved)return;if(this.iterations>1e3)throw new Error("Too many iterations");if(this.iterations++,this.iterations===1){const o=this.getNextFloatingBoxId(),i=this.evaluateFloatingBoxAssignment(o);this.lastComputedEvaluations=[i],this.acceptEvaluationResult(i);return}const t=this.getRemainingFloatingBoxIds();if(t.length===0){this.solved=!0;return}let e=1/0,n=null;this.lastComputedEvaluations=[];for(const o of t){const i=this.evaluateFloatingBoxAssignment(o);this.lastComputedEvaluations.push(i),i.bestDist<e&&(e=i.bestDist,n=i)}n&&this.acceptEvaluationResult(n)}acceptEvaluationResult(t){const{bestFixedBoxId:e,bestNewWipGraph:n,nextFloatingBoxId:o}=t;if(e===null){this.rejectedFloatingBoxIds.add(o);return}this.acceptedFloatingBoxIds.add(o),this.assignment.set(o,e),this.acceptedFixedBoxIds.add(e),this.wipGraph=n,this.lastAcceptedEvaluation=t.lastDistanceEvaluation}getWipGraphWithAddedFixedBoxIdForFloatingAssignment(t,e){const n=structuredClone(this.wipGraph),o=this.fixedGraph.boxes.find(a=>a.boxId===t);n.boxes.push(o);const i=this.floatingGraph.pins.filter(a=>a.boxId===e),r=this.fixedGraph.pins.filter(a=>a.boxId===t),{matchedPins:s}=QEo(i,r);return n.pins.push(...s.map(a=>{const[A,c]=a;return{...c,networkId:this.floatingToFixedNetworkMap.get(A.networkId),_floatingPinId:A.pinId,_fixedPinId:c.pinId}})),n}visualize(){const t=zN(this.floatingGraph,{title:"Floating"}),e=zN(this.wipGraph,{title:"WIP"}),n=zN(this.fixedGraph,{title:"Fixed"}),o=zN(this.getPartialFloatingGraph(),{title:"Partial Floating"}),i=new Map,r=new Map;for(const[p,m]of this.assignment){const _=oO(CEo(p)*47%100,100,.5);i.set(p,_),r.set(m,p)}function s(p,m,_){const f=i.get(m);p.fill=f,p.label=`${m}→${_}`}for(const p of t.rects??[]){const m=p.label;if(!m)continue;const _=this.assignment.get(m);_&&s(p,m,_)}for(const p of o.rects??[]){const m=p.label;if(!m)continue;const _=this.assignment.get(m);_&&s(p,m,_)}const a=[e,n];for(const p of a)for(const m of p.rects??[]){const _=m.label;if(!_)continue;const f=r.get(_);f&&s(m,f,_)}const A=n0e(this.floatingGraph),c=n0e(this.wipGraph),l=n0e(this.fixedGraph),u=Iwe(A,{title:"Floating Flat"}),g=Iwe(c,{title:"WIP Flat"}),h=Iwe(l,{title:"Fixed Flat"});return zce([ZQe([t,u,o]),ZQe([e,g]),ZQe([n,h])])}},wEo=(t,e)=>{const n=new vEo(t,e);for(;!n.solved&&n.iterations<1e3;)n.step();const o={};for(const[s,a]of n.assignment.entries())o[s]=a;const i={};for(const[s,a]of n.floatingToFixedNetworkMap.entries())i[s]=a;const r=n.getPinAssignment();return{floatingToFixedBoxAssignment:o,floatingToFixedNetworkAssignment:i,floatingToFixedPinAssignment:r}},PEo=(t,{renetworkedNetworkIdMap:e}={})=>{if(e??={},t.length===1)return t[0];const n={boxes:[],pins:[]},o=new Map,i=new Map,r=Object.entries(t.flatMap(a=>Array.from(new Set(a.boxes.map(A=>A.boxId)))).reduce((a,A)=>(a[A]=(a[A]||0)+1,a),{})).filter(([a,A])=>A===t.length).map(([a])=>a);if(r.length>1)throw new Error(`Expected at most one shared box across all partitions, the following box ids are shared across all graphs: ${r.join(", ")}`);const s=r[0];for(const a of t){const A=a.boxes.find(c=>c.boxId===s)?.center;for(const c of a.boxes){if(o.has(c.boxId))continue;const l=structuredClone(c);l.center&&A&&(l.center={x:l.center.x-A.x,y:l.center.y-A.y}),o.set(c.boxId,l)}for(const c of a.pins)i.has(`${c.boxId}-${c.pinId}`)||i.set(`${c.boxId}-${c.pinId}`,structuredClone(c))}return n.boxes=Array.from(o.values()),n.pins=Array.from(i.values()),n},Gwt=({graph:t,axis:e,centerBoxId:n})=>{const o=structuredClone(t),i=o.boxes.find(a=>a.boxId===n);if(!i||!i.center)throw new Error(`Center box "${n}" not found or has no center`);const{x:r,y:s}=i.center;for(const a of o.boxes)a.center&&(a.center.x=2*r-a.center.x);for(const a of o.pins)a.offset.x=-a.offset.x;return o},MEo=t=>{let e=null,n=-1/0;for(const r of t.boxes){const s=t.pins.filter(a=>a.boxId===r.boxId).filter(a=>["x-","x+"].includes(iO(t,r,a)??"none"));s.length>n&&s.length>1&&(e=r,n=s.length)}if(!e)return{g:t,reflected:!1,centerBoxId:null};const o=t.pins.filter(r=>r.boxId===e.boxId).map(r=>iO(t,e,r)),i={"x+":0,"x-":0,"y+":0,"y-":0};for(const r of o)r&&i[r]++;return i["x+"]>=i["x-"]?{g:t,reflected:!1,centerBoxId:e.boxId}:{g:Gwt({graph:t,axis:"x",centerBoxId:e.boxId}),reflected:!0,centerBoxId:e.boxId}},sw=vc("schematic-partition-processor"),DEo=class{constructor(t,e={}){this.initialGraph=t,this.lastGraph=t,this.singletonKeys=e.singletonKeys??[],this.centerPinColors=e.centerPinColors??[];const n=this.initializeWipPartitions();this.wipPartitions=n.wipPartitions,this.splitBoxIds=n.splitBoxIds,this.addedPins=n.addedPins,this.exploredPins=new Set,this.unexploredPins=this.wipPartitions.flatMap(r=>r.pins.map(s=>({...s,partitionId:r.partitionId}))),this.boxSingletonKeys=this.initializeBoxSingletonKeys(),this.pinConnectionCount=(()=>{const r={};for(const s of this.initialGraph.pins)r[`${s.boxId}:${s.pinId}`]=this.getNeighbors(s).length;return r})();const o={};for(const r of this.initialGraph.pins)o[r.networkId]=(o[r.networkId]??0)+1;this.networkSize=o;const i={};for(const r of this.initialGraph.pins)i[`${r.boxId}:${r.pinId}`]=o[r.networkId];this.pinNetworkSize=i}lastGraph;lastExploredPin;solved=!1;iteration=0;wipPartitions;unexploredPins=[];boxSingletonKeys;exploredPins;addedPins;allAcceptedPins=new Set;pinConnectionCount;networkSize;pinNetworkSize;splitBoxIds;acceptedBoxPartitionMap=new Map;singletonKeys;centerPinColors;initializeBoxSingletonKeys(){const t={};for(const e of this.initialGraph.boxes){const n=this.initialGraph.pins.filter(r=>r.boxId===e.boxId),o=n.length,i=n.map(r=>`${r.color}/${o}`).filter(r=>this.singletonKeys.includes(r));t[e.boxId]=new Set(i)}return t}initializeWipPartitions(){const t=[],e=new Set,n=new Set;let o=0;for(const i of this.initialGraph.boxes){const r=this.initialGraph.pins.filter(a=>a.boxId===i.boxId).filter(a=>iO(this.initialGraph,i,a)).filter(a=>!this.centerPinColors.includes(a.color));if(r.length<4)continue;const s=new Set(r.map(a=>iO(this.initialGraph,i,a)));s.size>1&&n.add(i.boxId);for(const a of s){const A={partitionId:`partition${o++}`,filledSingletonSlots:new Set,pins:[]};for(const c of r)iO(this.initialGraph,i,c)===a&&(A.pins.push({boxId:i.boxId,pinId:c.pinId}),e.add(`${i.boxId}:${c.pinId}`));t.push(A)}}return t.length===0&&(t.push(this.createWipPartitionFromEntireGraph()),this.solved=!0),sw(`splitBoxIds = ${Array.from(n).join(", ")}`),sw(`wipPartitions = ${t.map(i=>i.partitionId).join(", ")}`),{wipPartitions:t,splitBoxIds:n,addedPins:e}}createWipPartitionFromEntireGraph(){return{partitionId:"entire-graph",filledSingletonSlots:new Set,pins:this.initialGraph.pins.map(t=>({boxId:t.boxId,pinId:t.pinId}))}}step(){if(this.solved)return;if(this.iteration++,sw(`
── Iteration ${this.iteration} ── unexplored=${this.unexploredPins.length} explored=${this.exploredPins.size}`),this.unexploredPins.sort((c,l)=>{const u=`${c.boxId}:${c.pinId}`,g=`${l.boxId}:${l.pinId}`,h=this.pinNetworkSize[u]-this.pinNetworkSize[g];return h!==0?h:this.pinConnectionCount[u]-this.pinConnectionCount[g]}),this.unexploredPins.length===0){this.solved=!0;return}const t=this.unexploredPins.shift(),e=`${t.boxId}:${t.pinId}`;sw(`Exploring pin ${t.boxId}:${t.pinId} for partition "${t.partitionId}"`),this.lastExploredPin={...t,partitionId:t.partitionId};const n=`${t.partitionId}[${e}]`,o=this.initialGraph.pins.find(c=>c.boxId===t.boxId&&c.pinId===t.pinId);if(!o||this.exploredPins.has(n))return;const i=this.wipPartitions.find(c=>c.partitionId===t.partitionId);if(!i)return;const r=this.acceptedBoxPartitionMap.get(t.boxId);if(r&&r!==t.partitionId&&!this.splitBoxIds.has(t.boxId)){sw(` ↳ rejected (box ${t.boxId} for partition ${t.partitionId} already in partition ${this.acceptedBoxPartitionMap.get(t.boxId)})`),this.exploredPins.add(n);return}const s=this.boxSingletonKeys[t.boxId];if(Array.from(s).some(c=>i.filledSingletonSlots.has(c))){sw(` ↳ rejected (singleton already in partition "${t.partitionId}")`),this.exploredPins.add(n);return}for(const c of s)i.filledSingletonSlots.add(c);i.pins.push({boxId:t.boxId,pinId:t.pinId}),this.allAcceptedPins.add(e),this.addedPins.add(e),this.splitBoxIds.has(t.boxId)||this.acceptedBoxPartitionMap.set(t.boxId,t.partitionId),this.exploredPins.add(n),sw(` ↳ accepted → pins in partition now = ${i.pins.length}`);const A=this.getNeighbors(o);for(const c of A){const l=`${c.boxId}:${c.pinId}`;this.addedPins.has(l)||this.centerPinColors.includes(c.color)||this.exploredPins.has(`${t.partitionId}[${l}]`)||this.unexploredPins.push({boxId:c.boxId,pinId:c.pinId,partitionId:t.partitionId})}this.unexploredPins.length===0&&(this.solved=!0),this.solved&&sw(`Solver finished in ${this.iteration} iterations, partitions=${this.getPartitions().length}`)}getNeighbors(t){const e=[];for(const n of this.initialGraph.pins)n.networkId===t.networkId&&(t.boxId===n.boxId&&n.pinId===t.pinId||e.push(n));for(const n of this.initialGraph.pins)n.boxId===t.boxId&&e.push(n);return e}solve(){for(;!this.solved&&this.iteration<1e3;)this.step()}getPartitions(){if(!this.solved)throw new Error("Graph not solved");const t=[];for(const e of this.wipPartitions){if(e.pins.length===0)continue;const n=new Set(e.pins.map(i=>i.boxId)),o=this.initialGraph.boxes.filter(i=>n.has(i.boxId));t.push({boxes:o,pins:this.initialGraph.pins.filter(i=>e.pins.some(r=>r.pinId===i.pinId&&r.boxId===i.boxId)||this.centerPinColors.includes(i.color)&&n.has(i.boxId))})}return t}getGraphicsForLastGraph(){const t=zN(this.lastGraph,{title:`Iteration ${this.iteration}`}),e=this.wipPartitions.length,n=.4;if(this.wipPartitions.forEach((i,r)=>{if(i.pins.length===0)return;const s=oO(r,e,.25);for(const{boxId:a,pinId:A}of i.pins){const{x:c,y:l}=t0e(this.lastGraph,a,A);t.rects.push({center:{x:c,y:l},width:n,height:n,fill:s})}}),this.lastExploredPin){const{boxId:i,pinId:r,color:s}=this.lastExploredPin,a=t0e(this.lastGraph,i,r),A=.25;t.rects.push({center:{x:a.x,y:a.y},width:A,height:A,fill:this.lastExploredPin.partitionId?oO(this.wipPartitions.findIndex(c=>c.partitionId===this.lastExploredPin.partitionId),this.wipPartitions.length,1):"black"}),t.texts.push({x:a.x,y:a.y,text:`${i}:${r}-${Array.from(this.boxSingletonKeys[i]??[]).join(",")}`,fontSize:.1})}const o=n;for(const i of this.unexploredPins){const{boxId:r,pinId:s,partitionId:a}=i,A=this.wipPartitions.findIndex(h=>h.partitionId===a);if(A===-1)continue;const c=oO(A,this.wipPartitions.length,1),{x:l,y:u}=t0e(this.lastGraph,r,s),g=1+.1*A;t.rects.push({center:{x:l,y:u},width:o*g,height:o*g,fill:"none",stroke:c})}return t}},NEo=(t,e,n={})=>{n.similarityMethod??="wl-distance";const o=fwe,i=Object.fromEntries(Object.entries(e).map(([s,a])=>[s,o(t,a)])),r=Object.entries(i).reduce((s,[a,A])=>A<s[1]?[a,A]:s);return{graphName:r[0],graph:e[r[0]],distance:r[1],corpusScores:i}},REo=t=>t.x>0?"x+":t.x<0?"x-":t.y>0?"y+":t.y<0?"y-":null,TEo=t=>{switch(t){case"x+":return{x:1,y:0};case"x-":return{x:-1,y:0};case"y+":return{x:0,y:1};case"y-":return{x:0,y:-1}}},Ywt=(t,e)=>{const n=t.boxes.find(a=>a.boxId===e);if(!n)throw new Error(`Box ${e} not found`);const i=t.pins.filter(a=>a.boxId===e).map(a=>iO(t,n,a)),r={"x-":0,"x+":0,"y-":0,"y+":0};for(const a of i)a&&r[a]++;const s=Math.max(...Object.values(r));for(const a of Object.keys(r))if(r[a]===s)return a;return null},kEo=(t,e,{floatingToFixedBoxAssignment:n,floatingBoxIdsWithMutablePinOffsets:o})=>{for(const i of t.boxes){const r=n[i.boxId];if(!r||!i.center||o?.has(i.boxId))continue;const s=e0e(e,r),a=e0e(t,i.boxId),A=Ywt(e,r),c=Ywt(t,i.boxId);if(A===null||c===null||A!==c)continue;const l=TEo(A),u=s.maxX-s.minX,g=a.maxX-a.minX,h=s.maxY-s.minY,d=a.maxY-a.minY,p=g-u,m=d-h;if(!(p<.001&&m<.001))for(const _ of t.boxes){if(_.boxId===i.boxId||!_.center)continue;const f={x:_.center.x-i.center.x,y:_.center.y-i.center.y};REo({x:f.x*Math.abs(l.x),y:f.y*Math.abs(l.y)})===A&&(_.center.x+=l.x*p,_.center.y+=l.y*m)}}},FEo=(t,e,n={})=>{const{floatingBoxIdsWithMutablePinOffsets:o=new Set}=n,{floatingToFixedBoxAssignment:i,floatingToFixedPinAssignment:r}=wEo(t,e),s=structuredClone(t);for(const a of s.pins)if(o.has(a.boxId)&&r[a.boxId]?.[a.pinId]){const A=r[a.boxId]?.[a.pinId],c=i[a.boxId],l=e.pins.find(u=>u.boxId===c&&u.pinId===A);l&&(a.offset=l.offset)}for(const a of s.boxes)if(i[a.boxId]){const A=i[a.boxId],c=e.boxes.find(l=>l.boxId===A);c&&(a.center=c.center,a.kind="fixed")}return n.pushBoxesAsBoxesChangeSize&&kEo(s,e,{floatingToFixedBoxAssignment:i,floatingBoxIdsWithMutablePinOffsets:o}),s},LEo=(t,{corpus:e,singletonKeys:n,centerPinColors:o,floatingBoxIdsWithMutablePinOffsets:i})=>{const r=new DEo(t,{singletonKeys:n,centerPinColors:o});for(;!r.solved&&r.iteration<1e3;)r.step();const A=r.getPartitions().map(MEo).map(g=>{const{graph:h,distance:d}=NEo(g.g,e);return{adaptedBpcGraph:FEo(structuredClone(g.g),h,{floatingBoxIdsWithMutablePinOffsets:i,pushBoxesAsBoxesChangeSize:!0}),reflected:g.reflected,centerBoxId:g.centerBoxId,distance:d}}),c=A.map(({adaptedBpcGraph:g,reflected:h,centerBoxId:d})=>h?Gwt({graph:g,axis:"x",centerBoxId:d}):g),l=PEo(c),u=A.reduce((g,h)=>g+(h.distance||0),0);return{fixedGraph:l,distance:u}},HEo=(t,{corpus:e,singletonKeys:n,centerPinColors:o,floatingBoxIdsWithMutablePinOffsets:i})=>{const r=[];let s=null;for(const a of t){const{fixedGraph:A,distance:c}=LEo(a.floatingGraph,{corpus:e,singletonKeys:n,centerPinColors:o,floatingBoxIdsWithMutablePinOffsets:i});r.push({variantName:a.variantName,distance:c}),(!s||c<s.distance)&&(s={variantName:a.variantName,result:A,distance:c})}return{result:s.result,selectedVariantName:s.variantName,variantResults:r}},xp=1e-15,OEo=class{map;rev;constructor(){this.map=new Map([["0",0]]),this.rev=["0"]}getOrCreate(t){const e=String(t),n=e.toUpperCase();if(this.map.has(n))return this.map.get(n);const o=this.rev.length;return this.map.set(n,o),this.rev.push(e),o}get(t){return this.map.get(String(t).toUpperCase())}count(){return this.rev.length}matrixIndexOfNode(t){return t===0?-1:t-1}};function EC(t){if(t==null)return NaN;let e=String(t).trim();if(e==="")return NaN;if(/^[+-]?\d*\.?\d+(?:[eE][+-]?\d+)?$/.test(e))return parseFloat(e);const n={t:1e12,g:1e9,meg:1e6,k:1e3,m:.001,u:1e-6,n:1e-9,p:1e-12,f:1e-15},o=e.match(/^([+-]?\d*\.?\d+(?:[eE][+-]?\d+)?)([a-zA-Z]+)$/);if(!o)return parseFloat(e);const[,i,r]=o;if(i==null)return parseFloat(e);let s=parseFloat(i),a=(r??"").toLowerCase();return a=a.replace(/(ohm|v|a|s|h|f)$/g,""),a==="meg"?s*n.meg:a.length===1&&a in n?s*n[a]:s}function GEo(t){const o=t.trim().replace(/^pulse\s*\(/i,"(").replace(/^\(/,"").replace(/\)$/,"").trim().split(/[\s,]+/).filter(r=>r.length);if(o.length<7)throw new Error("PULSE(...) requires 7 or 8 args");const i=o.map(r=>EC(r));if(i.some(r=>Number.isNaN(r)))throw new Error("Invalid PULSE() numeric value");return{v1:i[0],v2:i[1],td:i[2],tr:i[3],tf:i[4],ton:i[5],period:i[6],ncycles:o[7]!=null?i[7]:1/0}}function YEo(t){const o=t.trim().replace(/^pwl\s*\(/i,"(").replace(/^\(/,"").replace(/\)$/,"").trim().split(/[\s,]+/).filter(r=>r.length);if(o.length===0||o.length%2!==0)throw new Error("PWL(...) requires an even number of time/value pairs");const i=[];for(let r=0;r<o.length;r+=2){const s=EC(o[r]),a=EC(o[r+1]);if(Number.isNaN(s)||Number.isNaN(a))throw new Error("Invalid PWL() numeric value");i.push({t:s,v:a})}return i}function UEo(t,e){if(e<t.td)return t.v1;const n=e-t.td,o=Math.floor(n/t.period);if(o>=t.ncycles)return t.v1;const i=n-o*t.period;if(i<t.tr){const r=i/Math.max(t.tr,xp);return t.v1+(t.v2-t.v1)*r}if(i<t.tr+t.ton)return t.v2;if(i<t.tr+t.ton+t.tf){const r=(i-(t.tr+t.ton))/Math.max(t.tf,xp);return t.v2+(t.v1-t.v2)*r}return t.v1}function KEo(t,e){if(t.length===0)return 0;if(e<=t[0].t)return t[0].v;for(let n=1;n<t.length;n++){const o=t[n-1],i=t[n];if(e<=i.t){const r=Math.max(i.t-o.t,xp),s=(e-o.t)/r;return o.v+(i.v-o.v)*s}}return t[t.length-1].v}function VEo(t){const e=/"[^"]*"|\w+\s*\([^)]*\)|\([^()]*\)|\S+/g,n=[];let o;for(;(o=e.exec(t))!==null;)n.push(o[0]);return n}function $l(t,e,n){const o=t[e];if(o==null)throw new Error(n);return o}function zEo(t){const e=new Map,n=new Map,o={nodes:new OEo,R:[],C:[],L:[],V:[],S:[],D:[],analyses:{ac:null,tran:null},probes:{tran:[]},skipped:[],models:{vswitch:e,diode:n}},i=t.split(/\r?\n/);let r=!1;for(const a of i){let A=a.trim();if(!A||/^\*/.test(A))continue;if(/^\s*\.end\b/i.test(A))break;A=A.replace(/\/\/.*$/,""),A=A.replace(/;.*$/,"");const c=VEo(A);if(c.length===0)continue;const l=c[0];if(l.length===0)continue;if(!r&&!/^[rclvgsmiqd]\w*$/i.test(l)&&!/^\./.test(l)){r=!0;continue}if(/^\./.test(l)){const h=l.toLowerCase();if(h===".ac"){const d=$l(c,1,".ac missing mode").toLowerCase();if(d!=="dec"&&d!=="lin")throw new Error(".ac supports 'dec' or 'lin'");const p=parseInt($l(c,2,".ac missing point count"),10),m=EC($l(c,3,".ac missing start frequency")),_=EC($l(c,4,".ac missing stop frequency"));o.analyses.ac={mode:d,N:p,f1:m,f2:_}}else if(h===".tran"){const d=EC($l(c,1,".tran missing timestep")),p=EC($l(c,2,".tran missing stop time"));o.analyses.tran={dt:d,tstop:p}}else if(h===".print")if($l(c,1,".print missing analysis type").toLowerCase()==="tran"){const p=c.slice(2);for(const m of p){const _=m.match(/^v\(([^)]+)\)$/i);if(_&&_[1]){const f=_[1];o.probes.tran.some(I=>I.toUpperCase()===f.toUpperCase())||o.probes.tran.push(f)}}}else o.skipped.push(A);else if(h===".model"){const d=$l(c,1,".model missing name");let m=$l(c,2,".model missing type"),_="";if(m.includes("(")){const I=m.indexOf("(");_=m.slice(I+1),m=m.slice(0,I)}if(!_)_=c.slice(3).join(" ").replace(/^\(/,"").replace(/\)$/,"");else{const I=c.slice(3).join(" ").replace(/\)$/,"");_=`${_} ${I}`.trim()}_=_.replace(/^\(/,"").replace(/\)$/,"").trim();const f=m.toLowerCase();if(f==="vswitch"||f==="sw"){const I={name:d,Ron:1,Roff:1e12,Von:0,Voff:0};let C,y;if(_.length>0){const x=_.split(/[\s,]+/).filter(Boolean);for(const E of x){const[B,S]=E.split("=");if(!B||S==null)continue;const Q=B.toLowerCase(),w=EC(S);Number.isNaN(w)||(Q==="ron"?I.Ron=w:Q==="roff"?I.Roff=w:Q==="von"?I.Von=w:Q==="voff"?I.Voff=w:Q==="vt"?C=w:Q==="vh"&&(y=w))}}if(C!==void 0){const x=y??0;I.Von=C+x/2,I.Voff=C-x/2}e.set(d.toLowerCase(),I)}else if(f==="d"){const I={name:d,Is:1e-14,N:1};if(_.length>0){const C=_.split(/[\s,]+/).filter(Boolean);for(const y of C){const[x,E]=y.split("=");if(!x||E==null)continue;const B=x.toLowerCase(),S=EC(E);Number.isNaN(S)||(B==="is"?I.Is=S:B==="n"&&(I.N=S))}}n.set(d.toLowerCase(),I)}else o.skipped.push(A)}else o.skipped.push(A);continue}const u=l.charAt(0).toLowerCase(),g=l;try{if(u==="r"){const h=o.nodes.getOrCreate($l(c,1,"Resistor missing node")),d=o.nodes.getOrCreate($l(c,2,"Resistor missing node")),p=EC($l(c,3,"Resistor missing value"));o.R.push({name:g,n1:h,n2:d,R:p})}else if(u==="c"){const h=o.nodes.getOrCreate($l(c,1,"Capacitor missing node")),d=o.nodes.getOrCreate($l(c,2,"Capacitor missing node")),p=EC($l(c,3,"Capacitor missing value"));o.C.push({name:g,n1:h,n2:d,C:p,vPrev:0})}else if(u==="l"){const h=o.nodes.getOrCreate($l(c,1,"Inductor missing node")),d=o.nodes.getOrCreate($l(c,2,"Inductor missing node")),p=EC($l(c,3,"Inductor missing value"));o.L.push({name:g,n1:h,n2:d,L:p,iPrev:0})}else if(u==="v"){const h=o.nodes.getOrCreate($l(c,1,"Voltage source missing node")),d=o.nodes.getOrCreate($l(c,2,"Voltage source missing node")),p={dc:0,acMag:0,acPhaseDeg:0,waveform:null,index:-1};let m=3;for(m<c.length&&!/^[a-zA-Z]/.test(c[m])&&(p.dc=EC(c[m]),m++);m<c.length;){const _=c[m].toLowerCase();if(_==="dc"){const f=$l(c,m+1,"DC value missing");p.dc=EC(f),m+=2}else if(_==="ac"){const f=$l(c,m+1,"AC magnitude missing");p.acMag=EC(f);const I=c[m+2];I!=null&&/^[+-]?\d/.test(I)?(p.acPhaseDeg=EC(I),m+=3):m+=2}else if(_.startsWith("pulse")){const f=_.includes("(")?_:$l(c,m+1,"PULSE() missing arguments");if(!f||!/\(.*\)/.test(f))throw new Error("Malformed PULSE() specification");const I=GEo(f);p.waveform=C=>UEo(I,C),m+=_.includes("(")?1:2}else if(_.startsWith("pwl")){const f=_.includes("(")?_:$l(c,m+1,"PWL() missing arguments");if(!f||!/\(.*\)/.test(f))throw new Error("Malformed PWL() specification");const I=YEo(f);p.waveform=C=>KEo(I,C),m+=_.includes("(")?1:2}else/^\(.*\)$/.test(_),m++}o.V.push({name:g,n1:h,n2:d,dc:p.dc,acMag:p.acMag,acPhaseDeg:p.acPhaseDeg,waveform:p.waveform,index:p.index??-1})}else if(u==="s"){const h=o.nodes.getOrCreate($l(c,1,"Switch missing node")),d=o.nodes.getOrCreate($l(c,2,"Switch missing node")),p=o.nodes.getOrCreate($l(c,3,"Switch missing control node")),m=o.nodes.getOrCreate($l(c,4,"Switch missing control node")),_=$l(c,5,"Switch missing model");o.S.push({name:g,n1:h,n2:d,ncPos:p,ncNeg:m,modelName:_.toLowerCase(),model:null,isOn:!1})}else if(u==="d")if(c.length===4){const h=o.nodes.getOrCreate($l(c,1,"Diode missing node")),d=o.nodes.getOrCreate($l(c,2,"Diode missing node")),p=$l(c,3,"Diode missing model");o.D.push({name:g,nPlus:h,nMinus:d,modelName:p.toLowerCase(),model:null,vdPrev:0})}else o.skipped.push(A);else o.skipped.push(A)}catch(h){throw h instanceof Error?new Error(`Parse error on line: "${A}"
${h.message}`):h}}const s=o.nodes.count()-1;for(let a=0;a<o.V.length;a++){const A=o.V[a];A&&(A.index=s+a)}for(const a of o.S){const A=e.get(a.modelName);if(!A)throw new Error(`Unknown .model ${a.modelName} referenced by switch ${a.name}`);a.model=A,a.isOn=!1}for(const a of o.D){const A=n.get(a.modelName);if(!A)throw new Error(`Unknown .model ${a.modelName} referenced by diode ${a.name}`);a.model=A}return o}var ql=class dQ{re;im;constructor(e=0,n=0){this.re=e,this.im=n}static from(e,n=0){return new dQ(e,n)}static fromPolar(e,n=0){const o=n*Math.PI/180;return new dQ(e*Math.cos(o),e*Math.sin(o))}clone(){return new dQ(this.re,this.im)}add(e){return new dQ(this.re+e.re,this.im+e.im)}sub(e){return new dQ(this.re-e.re,this.im-e.im)}mul(e){return new dQ(this.re*e.re-this.im*e.im,this.re*e.im+this.im*e.re)}div(e){const n=e.re*e.re+e.im*e.im;if(n<xp)throw new Error("Complex divide by ~0");return new dQ((this.re*e.re+this.im*e.im)/n,(this.im*e.re-this.re*e.im)/n)}inv(){const e=this.re*this.re+this.im*this.im;if(e<xp)throw new Error("Complex invert by ~0");return new dQ(this.re/e,-this.im/e)}abs(){return Math.hypot(this.re,this.im)}phaseDeg(){return Math.atan2(this.im,this.re)*180/Math.PI}};function JEo(t,e){const n=t.length;for(let i=0;i<n;i++){const r=t[i],s=e[i];if(!r||!s)throw new Error("Matrix dimensions mismatch");const a=r.map(A=>A.clone());a.push(s.clone()),t[i]=a}for(let i=0;i<n;i++){let r=i;const s=t[i];if(!s)throw new Error("Matrix row missing");let a=s[i]?.abs()??0;for(let l=i+1;l<n;l++){const u=t[l];if(!u)throw new Error("Matrix row missing");const g=u[i]?.abs()??0;g>a&&(a=g,r=l)}if(a<xp)throw new Error("Singular matrix (complex)");if(r!==i){const l=t[i];t[i]=t[r],t[r]=l}const A=t[i];if(!A)throw new Error("Pivot row missing");const c=A[i];if(!c)throw new Error("Zero pivot encountered");for(let l=i+1;l<n;l++){const u=t[l];if(!u)throw new Error("Matrix row missing");const g=u[i];if(!g)continue;const h=g.div(c);if(!(h.abs()<xp))for(let d=i;d<=n;d++){const p=u[d],m=A[d];!p||!m||(u[d]=p.sub(h.mul(m)))}}}const o=new Array(n);for(let i=n-1;i>=0;i--){const r=t[i];if(!r)throw new Error("Matrix row missing");let s=r[n];if(!s)throw new Error("Augmented column missing");for(let A=i+1;A<n;A++){const c=r[A],l=o[A];!c||!l||(s=s.sub(c.mul(l)))}const a=r[i];if(!a)throw new Error("Zero pivot on back-substitution");o[i]=s.div(a)}return o}function WEo(t,e,n){if(t<=0||e<=0)throw new Error(".ac frequencies must be > 0");e<t&&([t,e]=[e,t]);const o=Math.log10(e/t),i=Math.max(1,Math.ceil(o*n)),r=[];for(let a=0;a<=i;a++)r.push(t*Math.pow(10,a/n));const s=r[r.length-1];return(s==null||s<e*(1-xp))&&r.push(e),r}function Cwe(t,e,n,o,i){const r=e.matrixIndexOfNode(n),s=e.matrixIndexOfNode(o);if(r>=0){const a=t[r];if(!a)throw new Error("Matrix row missing while stamping");a[r]=a[r]?.add(i)??i}if(s>=0){const a=t[s];if(!a)throw new Error("Matrix row missing while stamping");a[s]=a[s]?.add(i)??i}if(r>=0&&s>=0){const a=t[r],A=t[s];if(!a||!A)throw new Error("Matrix row missing while stamping");a[s]=a[s]?.sub(i)??ql.from(0,0).sub(i),A[r]=A[r]?.sub(i)??ql.from(0,0).sub(i)}}function jEo(t,e,n,o,i){const r=n.matrixIndexOfNode(o.n1),s=n.matrixIndexOfNode(o.n2),a=o.index,A=ql.from(1,0),c=ql.from(-1,0);if(r>=0){const u=t[r];if(!u)throw new Error("Matrix row missing while stamping voltage source");u[a]=u[a]?.add(A)??A}if(s>=0){const u=t[s];if(!u)throw new Error("Matrix row missing while stamping voltage source");u[a]=u[a]?.sub(A)??c}const l=t[a];if(!l)throw new Error("Branch row missing while stamping voltage source");r>=0&&(l[r]=l[r]?.add(A)??A),s>=0&&(l[s]=l[s]?.sub(A)??c),e[a]=(e[a]??ql.from(0,0)).add(i)}function $Eo(t){const{mode:e,N:n,f1:o,f2:i}=t;if(e==="dec")return WEo(o,i,n);const r=[],s=Math.max(2,n),a=(i-o)/(s-1);for(let A=0;A<s;A++)r.push(o+A*a);return r}function qEo(t,e,n){const o=Array.from({length:n},()=>Array.from({length:n},()=>ql.from(0,0))),i=Array.from({length:n},()=>ql.from(0,0)),r=2*Math.PI;for(const s of t.R){if(s.R<=0)throw new Error(`R ${s.name} must be > 0`);const a=ql.from(1/s.R,0);Cwe(o,t.nodes,s.n1,s.n2,a)}for(const s of t.C){const a=ql.from(0,r*e*s.C);Cwe(o,t.nodes,s.n1,s.n2,a)}for(const s of t.L){const a=ql.from(0,r*e*s.L),A=a.abs()<xp?ql.from(0,0):ql.from(1,0).div(a);Cwe(o,t.nodes,s.n1,s.n2,A)}for(const s of t.V){const a=ql.fromPolar(s.acMag||0,s.acPhaseDeg||0);jEo(o,i,t.nodes,s,a)}return{A:o,b:i}}function XEo(t){if(!t.analyses.ac)return null;const{mode:e,N:n,f1:o,f2:i}=t.analyses.ac,r=t.nodes.count()-1,s=t.V.length,a=r+s,A=$Eo({mode:e,N:n,f1:o,f2:i}),c={};t.nodes.rev.forEach((g,h)=>{h!==0&&(c[g]=[])});const l={},u=2*Math.PI;for(const g of A){const{A:h,b:d}=qEo(t,g,a),p=JEo(h,d);for(let m=1;m<t.nodes.count();m++){const _=m-1,f=t.nodes.rev[m];if(!f)continue;const I=c[f];I&&I.push(p[_]??ql.from(0,0))}for(const m of t.R){const _=m.n1===0?ql.from(0,0):p[m.n1-1]??ql.from(0,0),f=m.n2===0?ql.from(0,0):p[m.n2-1]??ql.from(0,0),C=ql.from(1/m.R,0).mul(_.sub(f));(l[m.name]||=[]).push(C)}for(const m of t.C){const _=m.n1===0?ql.from(0,0):p[m.n1-1]??ql.from(0,0),f=m.n2===0?ql.from(0,0):p[m.n2-1]??ql.from(0,0),C=ql.from(0,u*g*m.C).mul(_.sub(f));(l[m.name]||=[]).push(C)}for(const m of t.L){const _=m.n1===0?ql.from(0,0):p[m.n1-1]??ql.from(0,0),f=m.n2===0?ql.from(0,0):p[m.n2-1]??ql.from(0,0),I=ql.from(0,u*g*m.L),y=(I.abs()<xp?ql.from(0,0):ql.from(1,0).div(I)).mul(_.sub(f));(l[m.name]||=[]).push(y)}for(const m of t.V){const _=p[m.index]??ql.from(0,0);(l[m.name]||=[]).push(_)}}return{freqs:A,nodeVoltages:c,elementCurrents:l}}var Uwt=.02585;function ZEo(t,e){const n=t.length;for(let i=0;i<n;i++){const r=t[i],s=e[i];if(!r||s==null)throw new Error("Matrix dimensions mismatch");const a=r.slice();a.push(s),t[i]=a}for(let i=0;i<n;i++){let r=i;const s=t[i];if(!s)throw new Error("Matrix row missing");let a=Math.abs(s[i]??0);for(let l=i+1;l<n;l++){const u=t[l];if(!u)throw new Error("Matrix row missing");const g=Math.abs(u[i]??0);g>a&&(a=g,r=l)}if(a<xp)throw new Error("Singular matrix (real)");if(r!==i){const l=t[i];t[i]=t[r],t[r]=l}const A=t[i];if(!A)throw new Error("Pivot row missing");const c=A[i];if(c==null)throw new Error("Zero pivot encountered");for(let l=i+1;l<n;l++){const u=t[l];if(!u)throw new Error("Matrix row missing");const g=u[i];if(g==null)continue;const h=g/c;if(!(Math.abs(h)<xp))for(let d=i;d<=n;d++){const p=u[d],m=A[d];p==null||m==null||(u[d]=p-h*m)}}}const o=new Array(n).fill(0);for(let i=n-1;i>=0;i--){const r=t[i];if(!r)throw new Error("Matrix row missing");let s=r[n];if(s==null)throw new Error("Augmented column missing");for(let A=i+1;A<n;A++){const c=r[A],l=o[A];c==null||l==null||(s-=c*l)}const a=r[i];if(a==null)throw new Error("Zero pivot on back-substitution");o[i]=s/a}return o}function bj(t,e,n,o,i){const r=e.matrixIndexOfNode(n),s=e.matrixIndexOfNode(o);if(r>=0){const a=t[r];if(!a)throw new Error("Matrix row missing while stamping");a[r]=(a[r]??0)+i}if(s>=0){const a=t[s];if(!a)throw new Error("Matrix row missing while stamping");a[s]=(a[s]??0)+i}if(r>=0&&s>=0){const a=t[r],A=t[s];if(!a||!A)throw new Error("Matrix row missing while stamping");a[s]=(a[s]??0)-i,A[r]=(A[r]??0)-i}}function ywe(t,e,n,o,i){const r=e.matrixIndexOfNode(n),s=e.matrixIndexOfNode(o);r>=0&&(t[r]=(t[r]??0)-i),s>=0&&(t[s]=(t[s]??0)+i)}function e5o(t,e,n,o,i){const r=n.matrixIndexOfNode(o.n1),s=n.matrixIndexOfNode(o.n2),a=o.index;if(r>=0){const c=t[r];if(!c)throw new Error("Matrix row missing while stamping voltage source");c[a]=(c[a]??0)+1}if(s>=0){const c=t[s];if(!c)throw new Error("Matrix row missing while stamping voltage source");c[a]=(c[a]??0)-1}const A=t[a];if(!A)throw new Error("Branch row missing while stamping voltage source");r>=0&&(A[r]=(A[r]??0)+1),s>=0&&(A[s]=(A[s]??0)-1),e[a]=(e[a]??0)+i}function t5o(t,e){const n=t>xp?t:Math.max(e/1e3,xp),o=Math.max(1,Math.ceil(e/Math.max(n,xp)));return{dt:o>0?e/o:e,steps:o}}function n5o(t,e,n,o,i,r,s){for(const a of n.R){const A=1/a.R;bj(t,n.nodes,a.n1,a.n2,A)}for(const a of n.C){const A=a.C/Math.max(i,xp);bj(t,n.nodes,a.n1,a.n2,A);const c=-A*a.vPrev;ywe(e,n.nodes,a.n1,a.n2,c)}for(const a of n.L){const A=Math.max(i,xp)/a.L;bj(t,n.nodes,a.n1,a.n2,A),ywe(e,n.nodes,a.n1,a.n2,a.iPrev)}for(const a of n.S){const A=a.model;if(!A)continue;const c=a.isOn?A.Ron:A.Roff,u=1/Math.max(Math.abs(c),xp);bj(t,n.nodes,a.n1,a.n2,u)}for(const a of n.V){const A=a.waveform?a.waveform(o):a.dc||0;e5o(t,e,n.nodes,a,A)}for(const a of n.D){const A=a.model;if(!A)continue;const{nPlus:c,nMinus:l}=a,u=n.nodes.matrixIndexOfNode(c),g=n.nodes.matrixIndexOfNode(l),h=c===0?0:r[u]??0,d=l===0?0:r[g]??0,p=h-d,m=s===0?a.vdPrev:p,_=A.N*Uwt;let f=m;m>.8&&(f=.8),m<-1&&(f=-1);const I=Math.exp(f/_),C=A.Is*(I-1),y=Math.max(A.Is/_*I,1e-12),x=C-y*f;bj(t,n.nodes,c,l,y),ywe(e,n.nodes,c,l,x)}}function o5o(t,e){let n=!1;for(const o of t.S){const i=o.model;if(!i)continue;const r=o.ncPos===0?0:e[o.ncPos-1]??0,s=o.ncNeg===0?0:e[o.ncNeg-1]??0,a=r-s;let A=o.isOn;o.isOn?a<i.Voff&&(A=!1):a>i.Von&&(A=!0),A!==o.isOn&&(o.isOn=A,n=!0)}return n}function i5o(t){if(!t.analyses.tran)return null;const{dt:e,tstop:n}=t.analyses.tran,{dt:o,steps:i}=t5o(e,n),r=t.nodes.count()-1,s=t.V.length,a=r+s,A=[],c={};t.nodes.rev.forEach((g,h)=>{h!==0&&(c[g]=[])});const l={};let u=0;for(let g=0;g<=i;g++,u=g*o){A.push(u);let h=new Array(a).fill(0);for(let d=0;d<20;d++){const p=Array.from({length:a},()=>new Array(a).fill(0)),m=new Array(a).fill(0);if(n5o(p,m,t,u,o,h,d),h=ZEo(p,m),!o5o(t,h)||d===19)break}for(let d=1;d<t.nodes.count();d++){const p=d-1,m=t.nodes.rev[d];if(!m)continue;const _=c[m];_&&_.push(h[p]??0)}for(const d of t.R){const p=d.n1===0?0:h[d.n1-1]??0,m=d.n2===0?0:h[d.n2-1]??0,_=(p-m)/d.R;(l[d.name]||=[]).push(_)}for(const d of t.C){const p=d.n1===0?0:h[d.n1-1]??0,m=d.n2===0?0:h[d.n2-1]??0,_=d.C*(p-m-d.vPrev)/Math.max(o,xp);(l[d.name]||=[]).push(_)}for(const d of t.L){const p=d.n1===0?0:h[d.n1-1]??0,m=d.n2===0?0:h[d.n2-1]??0,f=Math.max(o,xp)/d.L*(p-m)+d.iPrev;(l[d.name]||=[]).push(f)}for(const d of t.V){const p=h[d.index]??0;(l[d.name]||=[]).push(p)}for(const d of t.S){const p=d.model;if(!p)continue;const m=d.n1===0?0:h[d.n1-1]??0,_=d.n2===0?0:h[d.n2-1]??0,f=d.isOn?p.Ron:p.Roff,I=Math.max(Math.abs(f),xp),C=(m-_)/I;(l[d.name]||=[]).push(C)}for(const d of t.D){if(!d.model)continue;const{nPlus:p,nMinus:m,model:_}=d,f=p===0?0:h[p-1]??0,I=m===0?0:h[m-1]??0,C=f-I,y=_.N*Uwt,x=Math.exp(C/y),E=_.Is*(x-1);(l[d.name]||=[]).push(E)}for(const d of t.C){const p=d.n1===0?0:h[d.n1-1]??0,m=d.n2===0?0:h[d.n2-1]??0;d.vPrev=p-m}for(const d of t.L){const p=d.n1===0?0:h[d.n1-1]??0,m=d.n2===0?0:h[d.n2-1]??0,_=Math.max(o,xp)/d.L;d.iPrev=_*(p-m)+d.iPrev}for(const d of t.D){const p=d.nPlus===0?0:h[d.nPlus-1]??0,m=d.nMinus===0?0:h[d.nMinus-1]??0;d.vdPrev=p-m}}if(t.probes.tran.length>0){const g={},h=t.probes.tran.map(d=>d.toUpperCase());for(const d in c)h.includes(d.toUpperCase())&&(g[d]=c[d]);return{times:A,nodeVoltages:g,elementCurrents:l}}return{times:A,nodeVoltages:c,elementCurrents:l}}function r5o(t){const e=zEo(t),n=XEo(e),o=i5o(e);return{circuit:e,ac:n,tran:o}}function s5o(t,e,n){if(!t||!e.analyses.tran)return[];const{dt:o,tstop:i}=e.analyses.tran,{times:r,nodeVoltages:s}=t,a=[];for(const A in s){const c=s[A];a.push({type:"simulation_transient_voltage_graph",simulation_transient_voltage_graph_id:`stvg_${n}_${A}`,simulation_experiment_id:n,timestamps_ms:r.map(l=>l*1e3),voltage_levels:c,time_per_step:o*1e3,start_time_ms:0,end_time_ms:i*1e3,name:`${A}`})}return a}var xwe=class{sourceSpan;leadingTrivia=[];trailingComment;constructor(t={}){this.sourceSpan=t.sourceSpan,this.trailingComment=t.trailingComment}getString(t){return this.toSource(t)}},Kwt="__default__",Cb=class Zte extends xwe{originalSource;constructor(e={}){super(e),this.originalSource=e.originalSource}static classes={};static register(e){if(!e.spiceTokenKeys||e.spiceTokenKeys.length===0)throw new Error("Class must declare static spiceTokenKeys");for(const n of e.spiceTokenKeys)Zte.classes[n.toLowerCase()]=e}static parseSpiceTokens(e){const n=e.tokens.find(r=>r.type!=="whitespace"),o=n===void 0?"blank":n.type==="directive"?`.${n.value}`:n.type==="comment"?"comment":n.type==="identifier"?n.raw[0]?.toUpperCase()??Kwt:n.type,i=Zte.classes[o.toLowerCase()]??(n?.type==="identifier"?Zte.classes.__unknown_element__:void 0)??Zte.classes[Kwt];if(i===void 0)throw new Error(`No SPICE card class registered for "${o}"`);return i.fromSpiceTokens(e)}},Zc=class extends Cb{cardKind="directive"},yb=class extends Zc{},Vwt=class extends xwe{};function Sj(t,e){const n=t?.dialect??"generic";if(n!=="pspice")throw new Error(`PSpice-only construct ${e} cannot be serialized to target dialect "${n}". Serialize with { dialect: "pspice" } or translate/remove the construct before exporting.`)}function a5o(t){const e=[];let n=[],o,i;const r=a=>{e.push({tokens:[],originalSource:"",range:{start:a.range.end,end:a.range.end},leadingNewlineRaw:a.raw})},s=()=>{if(n.length===0)return;const a={start:n[0].range.start,end:n.at(-1).range.end};e.push({tokens:n,originalSource:n.map(A=>A.raw).join(""),range:a,leadingNewlineRaw:i}),n=[],o=void 0,i=void 0};for(const a of t){if(a.type==="newline"){if(o!==void 0){const A=o;s(),r(A),o=a;continue}n.length===0?r(a):o=a;continue}if(o!==void 0){if(a.type==="continuation")n.push(o,a),o=void 0;else{const A=o.raw;s(),i=A,o=void 0,n.push(a)}continue}if(a.type==="continuation"){n.push(a);continue}n.push(a)}return s(),e}function Ewe(t){return t.filter(e=>e.type!=="whitespace"&&e.type!=="newline"&&e.type!=="continuation")}function zwt(t){if(t!==void 0)return"value"in t&&typeof t.value=="string"?t.value:t.raw}function A5o(t){const e=[];for(let n=0;n<t.length;n+=1){const o=t[n];if(o===void 0)continue;const i=Bwe(o);if(i===".control"){const r=[];let s,a=o.originalSource;for(n+=1;n<t.length;n+=1){const A=t[n];if(A!==void 0){if(a=`${a}${A.leadingNewlineRaw??`
`}${A.originalSource}`,Bwe(A)===".endc"){s=A;break}r.push(A)}}e.push({...o,childCards:r,endCard:s,originalSource:a});continue}if(i===".subckt"){const r=[];let s,a=o.originalSource;for(n+=1;n<t.length;n+=1){const A=t[n];if(A!==void 0){if(a=`${a}${A.leadingNewlineRaw??`
`}${A.originalSource}`,Bwe(A)===".ends"){s=A;break}r.push(A)}}e.push({...o,childCards:r,endCard:s,originalSource:a});continue}e.push(o)}return e}function Bwe(t){const[e]=Ewe(t.tokens);if(e!==void 0)return e.type==="directive"?`.${e.value}`:zwt(e)}function aw(t){return zwt(t)}function Jwt(t){return t.type==="punctuation"&&(t.value==="("||t.value===")"||t.value===",")}var kA=class B5n{constructor(e){this.card=e,this.tokens=Ewe(e.tokens),this.originalSource=e.originalSource}card;tokens;originalSource;static from(e){return new B5n(e)}head(){return aw(this.tokens[0])??""}headRaw(){return this.tokens[0]?.raw??""}headDesignator(){return this.tokens[0]?.raw[0]?.toUpperCase()??""}arg(e){return aw(this.tokens[e+1])}args(){return this.tokens.slice(1).map(e=>aw(e)??e.raw)}argsAfter(e){return this.args().slice(e)}argsUntilLast(){return this.args().slice(0,-1)}lastArg(){return this.args().at(-1)}keywordIndex(e){return this.findKeyword(e)?.argIndex??-1}argAfterKeyword(e){const n=this.findKeyword(e);return n===void 0?void 0:aw(this.tokens[n.tokenIndex+n.tokenCount])}hasKeyword(e){return this.findKeyword(e)!==void 0}sweepArg(e,n){const o=this.arg(e)?.toLowerCase();return o==="oct"||o==="lin"||o==="dec"?o:n}paramsAfter(e){return this.readParamsFrom(1+e)}paramAfter(e,n){const o=n.toLowerCase();return this.paramsAfter(e).find(([i])=>i.toLowerCase()===o)?.[1]}paramsAfterExcept(e,n){const o=new Set(n.map(i=>i.toLowerCase()));return this.paramsAfter(e).filter(([i])=>!o.has(i.toLowerCase()))}paramsAfterKeyword(e){const n=this.findKeyword(e);if(n!==void 0)return this.readParamsFrom(n.tokenIndex+n.tokenCount)}argsBeforeKeyword(e,n=0){const i=this.findKeyword(e,n)?.tokenIndex??this.tokens.length;return this.tokens.slice(1+n,i).map(r=>aw(r)??r.raw)}restJoined(e){return this.argsAfter(e).join(" ")}findKeyword(e,n=0){const o=e.endsWith(":"),i=o?e.slice(0,-1):e;for(let r=1+n;r<this.tokens.length;r+=1){const s=this.tokens[r],a=aw(s);if(a!==void 0&&a.toLowerCase()===i.toLowerCase()){if(o){const A=this.tokens[r+1];if(A?.type!=="punctuation"||A.value!==":")continue;return{argIndex:r-1,tokenIndex:r,tokenCount:2}}return{argIndex:r-1,tokenIndex:r,tokenCount:1}}}}readParamsFrom(e){const n=[];let o=e;for(;o<this.tokens.length;){const i=this.tokens[o];if(i===void 0)break;if(Jwt(i)){o+=1;continue}const r=this.tokens[o+1],s=this.tokens[o+2];if(r?.type==="operator"&&r.value==="="&&s!==void 0&&!Jwt(s)){const a=aw(i),A=aw(s);a!==void 0&&A!==void 0&&n.push([a,A]),o+=3;continue}o+=1}return n}},Wwt=class b5n{name;constructor(e){this.name=e}static ground(){return new b5n("0")}getString(){return this.name}},jwt=class{raw;constructor(t){this.raw=t}getString(){return this.raw}},r0e=class{raw;constructor(t){this.raw=String(t)}getString(){return this.raw}};function $wt(t){return t instanceof Wwt?t:new Wwt(t)}function Tg(t){return t instanceof r0e?t:t instanceof jwt?new r0e(t.getString()):new r0e(t)}function c5o(t){return typeof t=="object"&&!(t instanceof r0e)&&!(t instanceof jwt)?{magnitude:t.magnitude===void 0?void 0:Tg(t.magnitude),phase:t.phase===void 0?void 0:Tg(t.phase)}:{magnitude:Tg(t)}}var Qj=class S5n{values;constructor(e=[]){e instanceof S5n?this.values=e.entries():Array.isArray(e)?this.values=e.map(([n,o])=>[n,Tg(o)]):this.values=Object.entries(e).map(([n,o])=>[n,Tg(o)])}get(e){return this.values.find(([n])=>n.toLowerCase()===e.toLowerCase())?.[1]}set(e,n){const o=this.values.findIndex(([r])=>r.toLowerCase()===e.toLowerCase()),i=[e,Tg(n)];o===-1?this.values.push(i):this.values[o]=i}delete(e){const n=this.values.findIndex(([o])=>o.toLowerCase()===e.toLowerCase());return n===-1?!1:(this.values.splice(n,1),!0)}entries(){return this.values.map(([e,n])=>[e,n])}getString(e){return this.values.map(([n,o])=>`${n}=${o.getString()}`).join(" ")}get isEmpty(){return this.values.length===0}},qwt=class Q5n extends yb{static spiceTokenKeys=[".ac"];type="ac";command=".ac";sweep;points;start;stop;constructor(e){super(e),this.sweep=e.sweep,this.points=e.points,this.start=Tg(e.start),this.stop=Tg(e.stop)}static fromSpiceTokens(e){const n=kA.from(e);return new Q5n({sweep:n.sweepArg(0,"dec"),points:Number(n.arg(1)??0),start:n.arg(2)??"",stop:n.arg(3)??"",originalSource:n.originalSource})}getChildren(){return[]}toSource(e){return e?.format!=="pretty"&&this.originalSource!==void 0?this.originalSource:`${this.command} ${this.sweep} ${this.points} ${this.start.getString()} ${this.stop.getString()}`}};yb.register(qwt);var l5o=class v5n extends Zc{static spiceTokenKeys=[".control"];type="control";command=".control";lines;constructor(e){super(e),this.lines=e.lines}static fromSpiceTokens(e){const n=kA.from(e);return new v5n({lines:e.childCards?.map(o=>o.originalSource)??[],originalSource:n.originalSource})}getChildren(){return[]}toSource(e){return e?.format!=="pretty"&&this.originalSource!==void 0?this.originalSource:[this.command,...this.lines,".endc"].join(`
`)}};Zc.register(l5o);var Xwt=class w5n extends yb{static spiceTokenKeys=[".dc"];type="dc";command=".dc";sweeps;constructor(e){super(e);const n="sweeps"in e?e.sweeps:[e];this.sweeps=n.map(o=>({source:o.source,start:Tg(o.start),stop:Tg(o.stop),step:Tg(o.step)}))}static fromSpiceTokens(e){const n=kA.from(e);return new w5n({source:n.arg(0)??"",start:n.arg(1)??"",stop:n.arg(2)??"",step:n.arg(3)??"",originalSource:n.originalSource})}getChildren(){return[]}toSource(e){return e?.format!=="pretty"&&this.originalSource!==void 0?this.originalSource:[this.command,...this.sweeps.flatMap(n=>[n.source,n.start.getString(),n.stop.getString(),n.step.getString()])].join(" ")}};yb.register(Xwt);var vj=class P5n extends Zc{static spiceTokenKeys=[".end"];type="end";command=".end";static fromSpiceTokens(e){return new P5n({originalSource:kA.from(e).originalSource})}getChildren(){return[]}toSource(e){return e?.format!=="pretty"&&this.originalSource!==void 0?this.originalSource:this.command}};Zc.register(vj);var u5o=class M5n extends Zc{static spiceTokenKeys=[".include"];type="include";command=".include";path;constructor(e,n={}){super(n),this.path=typeof e=="string"?e:e.path}static fromSpiceTokens(e){const n=kA.from(e);return new M5n(n.restJoined(0),{originalSource:n.originalSource})}getChildren(){return[]}toSource(e){return e?.format!=="pretty"&&this.originalSource!==void 0?this.originalSource:`${this.command} ${this.path}`}};Zc.register(u5o);var g5o=class D5n extends Zc{static spiceTokenKeys=[".lib"];type="lib";command=".lib";path;section;constructor(e={}){super(e),this.path=e.path,this.section=e.section}static fromSpiceTokens(e){const n=kA.from(e);return new D5n({path:n.arg(0),section:n.arg(1),originalSource:n.originalSource})}getChildren(){return[]}toSource(e){return e?.format!=="pretty"&&this.originalSource!==void 0?this.originalSource:[this.command,this.path,this.section].filter(Boolean).join(" ")}};Zc.register(g5o);var d5o=class N5n extends Zc{static spiceTokenKeys=[".measure"];type="measure";command=".measure";analysis;name;expression;constructor(e){super(e),this.analysis=e.analysis,this.name=e.name,this.expression=e.expression}static fromSpiceTokens(e){const n=kA.from(e);return new N5n({analysis:n.arg(0),name:n.arg(1)??"",expression:n.restJoined(2),originalSource:n.originalSource})}getChildren(){return[]}toSource(e){return e?.format!=="pretty"&&this.originalSource!==void 0?this.originalSource:[this.command,this.analysis,this.name,this.expression].filter(Boolean).join(" ")}};Zc.register(d5o);var Zwt=class R5n extends Zc{static spiceTokenKeys=[".model"];type="model";command=".model";name;modelType;params;constructor(e){super(e),this.name=e.name,this.modelType=e.type,this.params=new Qj(e.params)}static fromSpiceTokens(e){const n=kA.from(e);return new R5n({name:n.arg(0)??"",type:n.arg(1)??"",params:n.paramsAfter(2),originalSource:n.originalSource})}getChildren(){return[]}toSource(e){if(e?.format!=="pretty"&&this.originalSource!==void 0)return this.originalSource;const n=this.params.getString(e);return[this.command,this.name,this.modelType,n&&`(${n})`].filter(Boolean).join(" ")}};Zc.register(Zwt);var ePt=class T5n extends yb{static spiceTokenKeys=[".op"];type="op";command=".op";static fromSpiceTokens(e){return new T5n({originalSource:kA.from(e).originalSource})}getChildren(){return[]}toSource(e){return e?.format!=="pretty"&&this.originalSource!==void 0?this.originalSource:this.command}};yb.register(ePt);var tPt=class k5n extends Zc{static spiceTokenKeys=[".options"];type="options";command=".options";values;constructor(e,n={}){super(n),this.values=new Qj(e)}static fromSpiceTokens(e){const n=kA.from(e);return new k5n(n.paramsAfter(0),{originalSource:n.originalSource})}getChildren(){return[]}toSource(e){return e?.format!=="pretty"&&this.originalSource!==void 0?this.originalSource:`${this.command} ${this.values.getString(e)}`.trimEnd()}};Zc.register(tPt);var h5o=class F5n extends Zc{static spiceTokenKeys=[".param"];type="param";command=".param";values;constructor(e,n={}){super(n),this.values=new Qj(e)}static fromSpiceTokens(e){const n=kA.from(e);return new F5n(n.paramsAfter(0),{originalSource:n.originalSource})}getChildren(){return[]}toSource(e){return e?.format!=="pretty"&&this.originalSource!==void 0?this.originalSource:`${this.command} ${this.values.getString(e)}`.trimEnd()}};Zc.register(h5o);function p5o(t){const e=t.trim().replace(/^\.print\s+/i,""),[n,...o]=e.split(/\s+/),i=o.join(" ");return{analysis:n,expressions:i.length===0?[]:i.split(",").map(r=>r.trim())}}var nPt=class L5n extends Zc{static spiceTokenKeys=[".print"];type="print";command=".print";analysis;expressions;constructor(e={}){super(e),this.analysis=e.analysis,this.expressions=e.expressions??[]}static fromSpiceTokens(e){const n=kA.from(e);return new L5n({...p5o(n.originalSource),originalSource:n.originalSource})}getChildren(){return[]}toSource(e){return e?.format!=="pretty"&&this.originalSource!==void 0?this.originalSource:[this.command,this.analysis,this.expressions.length>0?this.expressions.join(", "):void 0].filter(Boolean).join(" ")}};Zc.register(nPt);var m5o=class H5n extends Zc{static spiceTokenKeys=[".probe"];type="probe";command=".probe";expressions;constructor(e=[],n={}){super(n),this.expressions=e}static fromSpiceTokens(e){const n=kA.from(e);return new H5n(n.args(),{originalSource:n.originalSource})}getChildren(){return[]}toSource(e){return e?.format!=="pretty"&&this.originalSource!==void 0?this.originalSource:[this.command,...this.expressions].join(" ")}};Zc.register(m5o);var _5o=class O5n extends Zc{static spiceTokenKeys=[".text"];type="pspice_text";command=".TEXT";args;constructor(e,n={}){super(n),this.args=e}static fromSpiceTokens(e){const n=kA.from(e);return new O5n(n.args(),{originalSource:n.originalSource})}getChildren(){return[]}toSource(e){return Sj(e,".TEXT"),e?.format!=="pretty"&&this.originalSource!==void 0?this.originalSource:[this.command,...this.args].join(" ")}};Zc.register(_5o);var f5o=class G5n extends Zc{static spiceTokenKeys=[".vector"];type="pspice_vector";command=".VECTOR";args;constructor(e,n={}){super(n),this.args=e}static fromSpiceTokens(e){const n=kA.from(e);return new G5n(n.args(),{originalSource:n.originalSource})}getChildren(){return[]}toSource(e){return Sj(e,".VECTOR"),e?.format!=="pretty"&&this.originalSource!==void 0?this.originalSource:[this.command,...this.args].join(" ")}};Zc.register(f5o);var I5o=class Y5n extends Zc{static spiceTokenKeys=[".watch"];type="pspice_watch";command=".WATCH";args;constructor(e,n={}){super(n),this.args=e}static fromSpiceTokens(e){const n=kA.from(e);return new Y5n(n.args(),{originalSource:n.originalSource})}getChildren(){return[]}toSource(e){return Sj(e,".WATCH"),e?.format!=="pretty"&&this.originalSource!==void 0?this.originalSource:[this.command,...this.args].join(" ")}};Zc.register(I5o);var oPt=class U5n extends Zc{static spiceTokenKeys=[".save"];type="save";command=".save";expressions;constructor(e,n={}){super(n),this.expressions=e}static fromSpiceTokens(e){const n=kA.from(e);return new U5n(n.args(),{originalSource:n.originalSource})}getChildren(){return[]}toSource(e){return e?.format!=="pretty"&&this.originalSource!==void 0?this.originalSource:[this.command,...this.expressions].join(" ")}};Zc.register(oPt);var iPt=class K5n extends Zc{static spiceTokenKeys=[".subckt"];type="subckt";command=".subckt";name;pins;params;cards;endsName;constructor(e){super(e),this.name=e.name,this.pins=(e.pins??[]).map($wt),this.params=new Qj(e.params),this.cards=e.cards??[],this.endsName=e.endsName}static fromSpiceTokens(e){const n=kA.from(e),o=e.endCard===void 0?void 0:kA.from(e.endCard);return new K5n({name:n.arg(0)??"",pins:n.argsBeforeKeyword("params:",1),params:n.paramsAfterKeyword("params:"),cards:e.childCards?.map(i=>Cb.parseSpiceTokens(i)),endsName:o?.arg(0),originalSource:n.originalSource})}add(e){this.cards.push(e)}getChildren(){return this.cards}toSource(e){if(e?.format!=="pretty"&&this.originalSource!==void 0)return this.originalSource;const n=this.params.getString(e);return[[this.command,this.name,...this.pins.map(o=>o.getString()),n?"params:":void 0,n||void 0].filter(o=>o!==void 0).join(" "),...this.cards.map(o=>o.toSource(e)),[".ends",this.endsName??this.name].join(" ")].join(`
`)}};Zc.register(iPt);var C5o=class V5n extends Zc{static spiceTokenKeys=[".temp"];type="temp";command=".temp";values;constructor(e,n={}){super(n),this.values=e.map(Tg)}static fromSpiceTokens(e){const n=kA.from(e);return new V5n(n.args(),{originalSource:n.originalSource})}getChildren(){return[]}toSource(e){return e?.format!=="pretty"&&this.originalSource!==void 0?this.originalSource:[this.command,...this.values.map(n=>n.getString())].join(" ")}};Zc.register(C5o);var rPt=class z5n extends yb{static spiceTokenKeys=[".tran"];type="tran";command=".tran";step;stop;start;maxStep;uic;pspiceOp;constructor(e){super(e),this.step=e.step===void 0?void 0:Tg(e.step),this.stop=Tg(e.stop),this.start=e.start===void 0?void 0:Tg(e.start),this.maxStep=e.maxStep===void 0?void 0:Tg(e.maxStep),this.uic=e.uic,this.pspiceOp=e.pspiceOp??!1}static fromSpiceTokens(e){const n=kA.from(e);return new z5n({step:n.arg(0),stop:n.arg(1)??"",start:n.arg(2),maxStep:n.arg(3),uic:n.hasKeyword("uic"),pspiceOp:n.originalSource.trimStart().toLowerCase().startsWith(".tran/op"),originalSource:n.originalSource})}getChildren(){return[]}toSource(e){return this.pspiceOp&&Sj(e,".TRAN/OP"),e?.format!=="pretty"&&this.originalSource!==void 0?this.originalSource:[this.command,this.step?.getString(),this.stop.getString(),this.start?.getString(),this.maxStep?.getString(),this.uic?"UIC":void 0].filter(Boolean).join(" ")}};yb.register(rPt);var y5o=class J5n extends Zc{static spiceTokenKeys=["__default__"];type="unknown_dot_command";command;args;constructor(e){super(e),this.command=e.command,this.args=e.args}static fromSpiceTokens(e){const n=kA.from(e);return new J5n({command:n.headRaw(),args:n.args(),originalSource:n.originalSource})}getChildren(){return[]}toSource(e){return e?.format!=="pretty"&&this.originalSource!==void 0?this.originalSource:[this.command,...this.args].join(" ")}};Zc.register(y5o);var wu=class extends Cb{cardKind="element";name;nodes;params;constructor(t){super(t),this.name=t.name,this.nodes=(t.nodes??[]).map($wt),this.params=new Qj(t.params)}renameNode(t,e){for(const n of this.nodes)n.name===t&&(n.name=e)}getChildren(){return[]}formatParts(t,e){if(e?.format!=="pretty"&&this.originalSource!==void 0)return this.originalSource;const n=this.params.getString(e);return[...t,n||void 0].filter(o=>o!==void 0&&o.length>0).join(" ")}},x5o=class W5n extends wu{static spiceTokenKeys=["Q"];type="bjt";model;constructor(e){super({...e,nodes:e.nodes.filter(n=>n!==void 0)}),this.model=e.model}static fromSpiceTokens(e){const n=kA.from(e),o=n.args().length>4,i=o?[n.arg(0)??"",n.arg(1)??"",n.arg(2)??"",n.arg(3)??""]:[n.arg(0)??"",n.arg(1)??"",n.arg(2)??""],r=o?4:3;return new W5n({name:n.head(),nodes:i,model:n.arg(r)??"",params:n.paramsAfter(r+1),originalSource:n.originalSource})}toSource(e){return this.formatParts([this.name,...this.nodes.map(n=>n.getString()),this.model],e)}};wu.register(x5o);var E5o=class j5n extends wu{static spiceTokenKeys=["C"];type="capacitor";capacitance;initialCondition;constructor(e){super(e),this.capacitance=Tg(e.capacitance),this.initialCondition=e.ic===void 0?void 0:Tg(e.ic)}static fromSpiceTokens(e){const n=kA.from(e);return new j5n({name:n.head(),nodes:[n.arg(0)??"",n.arg(1)??""],capacitance:n.arg(2)??"",ic:n.paramAfter(3,"ic"),params:n.paramsAfterExcept(3,["ic"]),originalSource:n.originalSource})}toSource(e){return this.formatParts([this.name,...this.nodes.map(n=>n.getString()),this.capacitance.getString(),this.initialCondition===void 0?void 0:`IC=${this.initialCondition.getString()}`],e)}};wu.register(E5o);var B5o=class $5n extends wu{static spiceTokenKeys=["F"];type="cccs";source;gain;constructor(e){super({...e,nodes:e.output}),this.source=e.source,this.gain=Tg(e.gain)}static fromSpiceTokens(e){const n=kA.from(e);return new $5n({name:n.head(),output:[n.arg(0)??"",n.arg(1)??""],source:n.arg(2)??"",gain:n.arg(3)??"",originalSource:n.originalSource})}toSource(e){return this.formatParts([this.name,...this.nodes.map(n=>n.getString()),this.source,this.gain.getString()],e)}};wu.register(B5o);var b5o=class q5n extends wu{static spiceTokenKeys=["H"];type="ccvs";source;transresistance;constructor(e){super({...e,nodes:e.output}),this.source=e.source,this.transresistance=Tg(e.transresistance)}static fromSpiceTokens(e){const n=kA.from(e);return new q5n({name:n.head(),output:[n.arg(0)??"",n.arg(1)??""],source:n.arg(2)??"",transresistance:n.arg(3)??"",originalSource:n.originalSource})}toSource(e){return this.formatParts([this.name,...this.nodes.map(n=>n.getString()),this.source,this.transresistance.getString()],e)}};wu.register(b5o);function sPt(t){const e={},n=t.argAfterKeyword("dc"),o=t.keywordIndex("ac");return n!==void 0?e.dc=n:o===-1&&(e.dc=t.arg(2)),o!==-1&&(e.ac={magnitude:t.arg(o+1),phase:t.arg(o+2)}),e}var s0e=class extends wu{dc;ac;transient;constructor(t){super(t),this.dc=t.dc===void 0?void 0:Tg(t.dc),this.ac=t.ac===void 0?void 0:c5o(t.ac),this.transient=t.transient}getChildren(){return this.transient===void 0?[]:[this.transient]}sourceParts(){const t=[this.name,...this.nodes.map(e=>e.getString())];return this.dc!==void 0&&t.push("DC",this.dc.getString()),this.ac!==void 0&&(t.push("AC"),this.ac.magnitude!==void 0&&t.push(this.ac.magnitude.getString()),this.ac.phase!==void 0&&t.push(this.ac.phase.getString())),this.transient!==void 0&&t.push(this.transient.toSource()),t}},S5o=class X5n extends s0e{static spiceTokenKeys=["I"];type="current_source";static fromSpiceTokens(e){const n=kA.from(e),o=sPt(n);return new X5n({name:n.head(),nodes:[n.arg(0)??"",n.arg(1)??""],dc:o.dc,ac:o.ac,originalSource:n.originalSource})}toSource(e){return this.formatParts(this.sourceParts(),e)}};s0e.register(S5o);var Q5o=class Z5n extends wu{static spiceTokenKeys=["D"];type="diode";model;constructor(e){super(e),this.model=e.model}static fromSpiceTokens(e){const n=kA.from(e);return new Z5n({name:n.head(),nodes:[n.arg(0)??"",n.arg(1)??""],model:n.arg(2)??"",params:n.paramsAfter(3),originalSource:n.originalSource})}toSource(e){return this.formatParts([this.name,...this.nodes.map(n=>n.getString()),this.model],e)}};wu.register(Q5o);var v5o=class e4n extends wu{static spiceTokenKeys=["L"];type="inductor";inductance;initialCondition;constructor(e){super(e),this.inductance=Tg(e.inductance),this.initialCondition=e.ic===void 0?void 0:Tg(e.ic)}static fromSpiceTokens(e){const n=kA.from(e);return new e4n({name:n.head(),nodes:[n.arg(0)??"",n.arg(1)??""],inductance:n.arg(2)??"",ic:n.paramAfter(3,"ic"),params:n.paramsAfterExcept(3,["ic"]),originalSource:n.originalSource})}toSource(e){return this.formatParts([this.name,...this.nodes.map(n=>n.getString()),this.inductance.getString(),this.initialCondition===void 0?void 0:`IC=${this.initialCondition.getString()}`],e)}};wu.register(v5o);var w5o=class t4n extends wu{static spiceTokenKeys=["M"];type="mosfet";model;constructor(e){super(e),this.model=e.model}static fromSpiceTokens(e){const n=kA.from(e);return new t4n({name:n.head(),nodes:[n.arg(0)??"",n.arg(1)??"",n.arg(2)??"",n.arg(3)??""],model:n.arg(4)??"",params:n.paramsAfter(5),originalSource:n.originalSource})}toSource(e){return this.formatParts([this.name,...this.nodes.map(n=>n.getString()),this.model],e)}};wu.register(w5o);var P5o=new Set(["VALUE","TABLE","LAPLACE","FREQ","CHEBYSHEV"]);function aPt(t){return t!==void 0&&P5o.has(t.toUpperCase())}function APt(t,e,n){const o=t?.dialect??"generic";o==="pspice"||o==="ngspice"&&(e==="VALUE"||e==="TABLE")||Sj(t,n)}var M5o=class n4n extends wu{type="pspice_abm_voltage_source";form;args;constructor(e){super({...e,nodes:e.output}),this.form=e.form,this.args=e.args}static fromTokenCard(e){return new n4n({name:e.head(),output:[e.arg(0)??"",e.arg(1)??""],form:e.arg(2)?.toUpperCase(),args:e.argsAfter(3),originalSource:e.originalSource})}toSource(e){return APt(e,this.form,`${this.form} behavioral voltage source`),this.formatParts([this.name,...this.nodes.map(n=>n.getString()),this.form,...this.args],e)}},D5o=class o4n extends wu{type="pspice_abm_current_source";form;args;constructor(e){super({...e,nodes:e.output}),this.form=e.form,this.args=e.args}static fromTokenCard(e){return new o4n({name:e.head(),output:[e.arg(0)??"",e.arg(1)??""],form:e.arg(2)?.toUpperCase(),args:e.argsAfter(3),originalSource:e.originalSource})}toSource(e){return APt(e,this.form,`${this.form} behavioral current source`),this.formatParts([this.name,...this.nodes.map(n=>n.getString()),this.form,...this.args],e)}};function N5o(t){return M5o.fromTokenCard(kA.from(t))}function R5o(t){return D5o.fromTokenCard(kA.from(t))}var T5o=class i4n extends wu{static spiceTokenKeys=["R"];type="resistor";resistance;constructor(e){super({...e,nodes:e.nodes.filter(n=>n!==void 0)}),this.resistance=Tg(e.resistance)}static fromSpiceTokens(e){const n=kA.from(e);return new i4n({name:n.head(),nodes:[n.arg(0)??"",n.arg(1)??""],resistance:n.arg(2)??"",params:n.paramsAfter(3),originalSource:n.originalSource})}toSource(e){return this.formatParts([this.name,...this.nodes.map(n=>n.getString()),this.resistance.getString()],e)}};wu.register(T5o);var k5o=class r4n extends wu{static spiceTokenKeys=["X"];type="subckt_instance";subckt;constructor(e){super(e),this.subckt=e.subckt}static fromSpiceTokens(e){const n=kA.from(e);return new r4n({name:n.head(),nodes:n.argsUntilLast(),subckt:n.lastArg()??"",originalSource:n.originalSource})}toSource(e){return this.formatParts([this.name,...this.nodes.map(n=>n.getString()),this.subckt],e)}};wu.register(k5o);var F5o=class s4n extends wu{static spiceTokenKeys=["__unknown_element__"];type="unknown_element";designator;tokens;constructor(e){super(e),this.designator=e.designator,this.tokens=e.tokens}static fromSpiceTokens(e){const n=kA.from(e),o=n.head();return new s4n({name:o,designator:n.headDesignator(),tokens:n.args(),originalSource:n.originalSource})}toSource(e){return this.formatParts([this.name,...this.tokens],e)}};wu.register(F5o);var L5o=class a4n extends wu{static spiceTokenKeys=["G"];type="vccs";transconductance;constructor(e){super({...e,nodes:[...e.output,...e.control]}),this.transconductance=Tg(e.transconductance)}static fromSpiceTokens(e){const n=kA.from(e);return aPt(n.arg(2))?R5o(e):new a4n({name:n.head(),output:[n.arg(0)??"",n.arg(1)??""],control:[n.arg(2)??"",n.arg(3)??""],transconductance:n.arg(4)??"",originalSource:n.originalSource})}toSource(e){return this.formatParts([this.name,...this.nodes.map(n=>n.getString()),this.transconductance.getString()],e)}};wu.register(L5o);var H5o=class A4n extends wu{static spiceTokenKeys=["E"];type="vcvs";gain;constructor(e){super({...e,nodes:[...e.output,...e.control]}),this.gain=Tg(e.gain)}static fromSpiceTokens(e){const n=kA.from(e);return aPt(n.arg(2))?N5o(e):new A4n({name:n.head(),output:[n.arg(0)??"",n.arg(1)??""],control:[n.arg(2)??"",n.arg(3)??""],gain:n.arg(4)??"",originalSource:n.originalSource})}toSource(e){return this.formatParts([this.name,...this.nodes.map(n=>n.getString()),this.gain.getString()],e)}};wu.register(H5o);var O5o=class c4n extends s0e{static spiceTokenKeys=["V"];type="voltage_source";static fromSpiceTokens(e){const n=kA.from(e),o=sPt(n);return new c4n({name:n.head(),nodes:[n.arg(0)??"",n.arg(1)??""],dc:o.dc,ac:o.ac,originalSource:n.originalSource})}toSource(e){return this.formatParts(this.sourceParts(),e)}};s0e.register(O5o);var G5o=class extends xwe{type="netlist";title;cards;end;dialect;trailingNewline;lineEnding;constructor(e={}){super(),this.title=e.title,this.cards=e.cards??[],this.end=e.end instanceof vj?e.end:e.end===!1?void 0:new vj,this.dialect=e.dialect??"generic",this.trailingNewline=e.trailingNewline??!0,this.lineEnding=e.lineEnding??`
`}get elements(){return this.cards.filter(e=>e.cardKind==="element")}get directives(){return this.cards.filter(e=>e.cardKind==="directive")}get subckts(){return this.cards.filter(e=>e instanceof iPt)}get models(){return this.cards.filter(e=>e instanceof Zwt)}get analyses(){return this.cards.filter(e=>e instanceof yb)}add(e){this.cards.push(e)}addAll(e){this.cards.push(...e)}findElement(e){return this.elements.find(n=>n.name.toLowerCase()===e.toLowerCase())}findModel(e){return this.models.find(n=>n.name.toLowerCase()===e.toLowerCase())}findSubckt(e){return this.subckts.find(n=>n.name.toLowerCase()===e.toLowerCase())}renameNode(e,n){for(const o of this.elements)o.renameNode(e,n);for(const o of this.subckts)for(const i of o.cards)i instanceof wu&&i.renameNode(e,n)}getChildren(){return[...this.cards,...this.end===void 0?[]:[this.end]]}getString(e={}){return this.toSource(e)}toSource(e={}){const n=e.end??"auto",i=[this.title,...this.cards.map(r=>r.toSource(e)),n==="never"?void 0:n==="always"?(this.end??new vj).toSource(e):this.end?.toSource(e)].filter(r=>r!==void 0).join(this.lineEnding);return this.trailingNewline?`${i}${this.lineEnding}`:i}},Y5o=class l4n extends Vwt{static spiceTokenKeys=["blank"];type="blank";cardKind="blank";originalSource;constructor(e={}){super(),this.originalSource=e.originalSource}static fromSpiceTokens(e){return new l4n({originalSource:kA.from(e).originalSource})}getChildren(){return[]}toSource(){return this.originalSource??""}};Cb.register(Y5o);var U5o=class yit extends Vwt{static spiceTokenKeys=["comment"];type="comment";cardKind="comment";text;marker;originalSource;constructor(e,n={}){super(),this.text=e,this.marker=n.marker??"*",this.originalSource=n.originalSource}static fromSpiceTokens(e){const n=kA.from(e),[o]=n.tokens;return o?.type==="comment"?new yit(o.value,{marker:o.marker,originalSource:n.originalSource}):new yit(n.originalSource,{originalSource:n.originalSource})}getChildren(){return[]}toSource(e){return e?.format!=="pretty"&&this.originalSource!==void 0?this.originalSource:`${this.marker} ${this.text}`.trimEnd()}};Cb.register(U5o);var K5o=class u4n extends Cb{static spiceTokenKeys=["raw","error","number","operator","punctuation"];type="raw_card";cardKind="raw";source;constructor(e){super({originalSource:e}),this.source=e}static fromSpiceTokens(e){return new u4n(kA.from(e).originalSource)}getChildren(){return[]}toSource(){return this.source}};Cb.register(K5o);var V5o=/^[+-]?(?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:[eE][+-]?\d+)?([a-zA-Z]+)?$/,cPt=new Set(["=","+","-","*","/","^"]),lPt=new Set(["(",")",",",":"]),z5o={f:1e-15,p:1e-12,n:1e-9,u:1e-6,m:.001,k:1e3,meg:1e6,g:1e9,t:1e12};function J5o(t,e={}){const n=e.preserveWhitespace??!1,o=e.preserveComments??!0,i=e.normalizeNumbers??!0,r=[],s=[];let a=0,A=1,c=1,l=!0;const u=()=>({offset:a,line:A,column:c}),g=C=>({start:C,end:u()}),h=C=>{for(let y=0;y<C.length;y+=1){const x=C[y];a+=1,x===`
`?(A+=1,c=1,l=!0):c+=1}},d=C=>{C.type==="whitespace"&&!n||C.type==="comment"&&!o||r.push(C)},p=C=>C!==void 0&&C>="0"&&C<="9",m=C=>{const y=t[C],x=t[C+1];return p(y)||y==="."&&p(x)?!0:(y==="+"||y==="-")&&!_()?!1:(y==="+"||y==="-")&&p(x)?!0:(y==="+"||y==="-")&&x==="."&&p(t[C+2])},_=()=>{const C=r.at(-1);return C===void 0||C.type==="whitespace"||C.type==="newline"||C.type==="continuation"||C.type==="operator"||C.type==="punctuation"},f=()=>{let C="";for((t[a]==="+"||t[a]==="-")&&(C+=t[a],h(t[a]));p(t[a]);)C+=t[a],h(t[a]);if(t[a]===".")for(C+=t[a],h(t[a]);p(t[a]);)C+=t[a],h(t[a]);if(t[a]==="e"||t[a]==="E")for(C+=t[a],h(t[a]),(t[a]==="+"||t[a]==="-")&&(C+=t[a],h(t[a]));p(t[a]);)C+=t[a],h(t[a]);for(;t[a]!==void 0&&t[a]>="a"&&t[a]<="z"||t[a]!==void 0&&t[a]>="A"&&t[a]<="Z";)C+=t[a],h(t[a]);return C},I=(C,y)=>{const x=C.match(V5o);if(!x)return!1;const E=x[1],B=E?.toLowerCase(),S=E===void 0?C:C.slice(0,-E.length),Q=Number(S),w=i&&!Number.isNaN(Q)?Q*(B===void 0?1:z5o[B]??1):null;return d({type:"number",raw:C,value:w,unitSuffix:E,range:y}),!0};for(;a<t.length;){const C=u(),y=t[a],x=t[a+1];if(y==="\r"||y===`
`){const S=y==="\r"&&x===`
`?`\r
`:y;h(S),d({type:"newline",raw:S,range:g(C)});continue}if(y===" "||y===" "){let S="";for(;t[a]===" "||t[a]===" ";)S+=t[a],h(t[a]);d({type:"whitespace",raw:S,range:g(C)});continue}if(l&&y==="+"){h(y),l=!1,d({type:"continuation",raw:y,range:g(C)});continue}if(l&&y==="*"||y===";"||y==="$"){const S=y;let Q="";for(;a<t.length&&t[a]!==`
`&&t[a]!=="\r";)Q+=t[a],h(t[a]);l=!1,d({type:"comment",marker:S,raw:Q,value:Q.slice(1).trimStart(),range:g(C)});continue}if(y==="#"){let S="";for(;a<t.length&&t[a]!==`
`&&t[a]!=="\r";)S+=t[a],h(t[a]);const Q=g(C),w={message:"Unsupported preprocessor-style line",raw:S,range:Q};s.push(w),l=!1,d({type:"error",raw:S,message:w.message,range:Q});continue}if(y==='"'||y==="'"){const S=y;let Q="",w="";for(h(y),Q+=y;a<t.length&&t[a]!==S&&!(t[a]===`
`||t[a]==="\r");)w+=t[a],Q+=t[a],h(t[a]);if(t[a]===S)Q+=S,h(S),d({type:"string",quote:S,raw:Q,value:w,range:g(C)});else{const M=g(C),k={message:"Unterminated string",raw:Q,range:M};s.push(k),d({type:"error",raw:Q,message:k.message,range:M})}l=!1;continue}if(m(a)){const S=f();if(l=!1,I(S,g(C)))continue}if(cPt.has(y)){h(y),l=!1,d({type:"operator",raw:y,value:y,range:g(C)});continue}if(lPt.has(y)){h(y),l=!1,d({type:"punctuation",raw:y,value:y,range:g(C)});continue}let E="";for(;a<t.length&&![" "," ","\r",`
`,'"',"'",";","$"].includes(t[a])&&!cPt.has(t[a])&&!lPt.has(t[a]);)E+=t[a],h(t[a]);if(E.length===0){h(y);const S=g(C),Q={message:`Unexpected character "${y}"`,raw:y,range:S};s.push(Q),d({type:"error",raw:y,message:Q.message,range:S});continue}l=!1;const B=g(C);if(E.startsWith(".")){d({type:"directive",raw:E,value:E.slice(1).toLowerCase(),range:B});continue}I(E,B)||d({type:"identifier",raw:E,value:E,range:B})}return{tokens:r,errors:s,source:{text:t,lineCount:A}}}function W5o(t,e={}){const n=X5o(t),o=$5o(t),i=o[0],r=i!==void 0&&q5o(i)?i.originalSource:void 0,s=r===void 0?o:o.slice(1),a=j5o(s),A=a.findIndex(l=>l instanceof vj),c=A===-1?void 0:a.splice(A,1)[0];return new G5o({title:r,cards:a,end:c??!1,dialect:e.dialect,trailingNewline:n.trailingNewline,lineEnding:n.lineEnding})}function j5o(t,e){return t.map(n=>Cb.parseSpiceTokens(n))}function $5o(t){const e=J5o(t,{preserveWhitespace:!0,preserveComments:!0,normalizeNumbers:!0});return A5o(a5o(e.tokens))}function q5o(t){const e=Ewe(t.tokens),[n]=e;return n===void 0||n.type==="directive"||n.type==="comment"||n.type!=="identifier"?!1:e.length===1?!0:Cb.classes[n.raw[0]?.toLowerCase()??""]===void 0}function X5o(t){const e=t.includes(`\r
`)?`\r
`:t.includes("\r")?"\r":`
`;return{trailingNewline:e===`\r
`?t.endsWith(`\r
`):t.endsWith(e),lineEnding:e}}var Z5o=t=>{const e=[];e.push(t.title),t.models.size>0&&e.push(...Array.from(t.models.values()));for(const n of t.components)e.push(n.toSpiceString());t.optionStatements.length>0&&e.push(...t.optionStatements),t.metadataComments.length>0&&e.push(...t.metadataComments);for(const n of t.subcircuits)e.push(n.toSpiceString());if(t.printStatements.length>0&&e.push(...t.printStatements),t.saveStatements.length>0&&e.push(...t.saveStatements),t.controls.length>0&&(e.push(".control"),e.push(...t.controls),e.push(".endc")),t.analysisCommand){const n=t.analysisCommand.trim().toLowerCase().split(/\s+/)[0];e.some(i=>i.trim().toLowerCase().split(/\s+/)[0]===n)||e.push(t.analysisCommand)}return e.push(".END"),e.join(`
`)},e4o=class{title;components;nodes;controls;subcircuits;models;optionStatements;metadataComments;analysisCommand;printStatements;saveStatements;constructor(t="Circuit Netlist"){this.title=t,this.components=[],this.nodes=new Set,this.controls=[],this.subcircuits=[],this.models=new Map,this.optionStatements=[],this.metadataComments=[],this.analysisCommand=null,this.printStatements=[],this.saveStatements=[]}addComponent(t){this.components.push(t);for(const e of t.nodes)this.nodes.add(e)}addSubcircuit(t){this.subcircuits.find(e=>e.name===t.name)||this.subcircuits.push(t)}get tranCommand(){return this.analysisCommand?.trim().toLowerCase().startsWith(".tran")?this.analysisCommand:null}set tranCommand(t){this.analysisCommand=t}toSpiceString(){return Z5o(this)}},Uy=class{name;command;nodes;constructor(t,e,n){this.name=t,this.command=e,this.nodes=n}toSpiceString(){return this.command.toSpiceString()}},t4o=class{commandName="bjt";props;constructor(t){this.props=t}toSpiceString(){const{name:t,collector:e,base:n,emitter:o,substrate:i,model:r,area:s}=this.props;let a=`Q${t} ${e} ${n} ${o}`;return i&&(a+=` ${i}`),a+=` ${r}`,s&&(a+=` ${s}`),a}},n4o=class{commandName="capacitor";props;constructor(t){this.props=t}toSpiceString(){const{name:t,positiveNode:e,negativeNode:n,modelName:o,value:i,initialCondition:r}=this.props;let s=`C${t} ${e} ${n}`;return o&&(s+=` ${o}`),s+=` ${i}`,r&&(s+=` IC=${r}`),s}},uPt=class{commandName="current_source";props;constructor(t){this.props=t}toSpiceString(){const{name:t,positiveNode:e,negativeNode:n,value:o,acMagnitude:i,acPhase:r}=this.props;let s=`I${t} ${e} ${n}`;return o&&(s+=` ${o}`),i&&(s+=` AC ${i}`,r&&(s+=` ${r}`)),s}},o4o=class{commandName="diode";props;constructor(t){this.props=t}toSpiceString(){const{name:t,positiveNode:e,negativeNode:n,model:o,area:i}=this.props;let r=`D${t} ${e} ${n} ${o}`;return i&&(r+=` ${i}`),r}},i4o=class{commandName="inductor";props;constructor(t){this.props=t}toSpiceString(){const{name:t,positiveNode:e,negativeNode:n,model:o,value:i,initialCondition:r}=this.props;let s=`L${t} ${e} ${n}`;return o&&(s+=` ${o}`),s+=` ${i}`,r&&(s+=` IC=${r}`),s}},r4o=class{commandName="mosfet";props;constructor(t){this.props=t}toSpiceString(){const{name:t,drain:e,gate:n,source:o,substrate:i,model:r,length:s,width:a,drainArea:A,sourceArea:c,drainPerimeter:l,sourcePerimeter:u,drainResistance:g,sourceResistance:h}=this.props;let d=`M${t} ${e} ${n} ${o} ${i} ${r}`;return Object.entries({L:s,W:a,AD:A,AS:c,PD:l,PS:u,NRD:g,NRS:h}).forEach(([m,_])=>{_&&(d+=` ${m}=${_}`)}),d}},s4o=class{commandName="resistor";props;constructor(t){this.props=t}toSpiceString(){const{name:t,positiveNode:e,negativeNode:n,model:o,value:i}=this.props;let r=`R${t} ${e} ${n}`;return o&&(r+=` ${o}`),r+=` ${i}`,r}},gPt=class{commandName="subcircuit_call";props;constructor(t){this.props=t}toSpiceString(){const{name:t,nodes:e,subcircuitName:n}=this.props;return`X${t} ${e.join(" ")} ${n}`}},a4o=class{commandName="voltage_controlled_switch";props;constructor(t){this.props=t}toSpiceString(){const{name:t,positiveNode:e,negativeNode:n,positiveControl:o,negativeControl:i,model:r}=this.props;return`S${t} ${e} ${n} ${o} ${i} ${r}`}},a0e=class{commandName="voltage_source";props;constructor(t){this.props=t}toSpiceString(){const{name:t,positiveNode:e,negativeNode:n,value:o,acMagnitude:i,acPhase:r}=this.props;let s=`V${t} ${e} ${n}`;return o&&(s+=` ${o}`),i&&(s+=` AC ${i}`,r&&(s+=` ${r}`)),s}};function A4o(t){return t>=1e6?`${t/1e6}MEG`:t>=1e3?`${t/1e3}K`:t.toString()}function c4o(t){return t>=.001?`${t*1e3}M`:t>=1e-6?`${t*1e6}U`:t>=1e-9?`${t*1e9}N`:t>=1e-12?`${t*1e12}P`:t.toString()}function l4o(t){return t>=1?t.toString():t>=.001?`${t*1e3}m`:t>=1e-6?`${t*1e6}u`:t>=1e-9?`${t*1e9}n`:t>=1e-12?`${t*1e12}p`:t.toString()}function dPt(t,e){if(!t)return e;const n=t.replace(/[^A-Za-z0-9_]/g,"_");return n?/^[0-9]/.test(n)?`${e}_${n}`:n:e}function u4o(t){if(!t)return"DC 0";const r=t.starts_closed??!1,s=t.closes_at??0,a=t.opens_at,A=t.switching_frequency,[c,l]=r?[5,0]:[0,5];if(A&&A>0){const u=1/A,g=a&&a>s?Math.min(a-s,u):0,h=g>0?g:Math.max(u/2,1e-9);return`PULSE(${Xl(c)} ${Xl(l)} ${Xl(s)} 1n 1n ${Xl(h)} ${Xl(u)})`}if(a!==void 0&&a>s){const u=Math.max(a-s,1e-9),g=s+u*2;return`PULSE(${Xl(c)} ${Xl(l)} ${Xl(s)} 1n 1n ${Xl(u)} ${Xl(g)})`}if(s>0){const u=s*2,g=Math.max(u/2,1e-9);return`PULSE(${Xl(c)} ${Xl(l)} ${Xl(s)} 1n 1n ${Xl(g)} ${Xl(u)})`}return`DC ${r?5:0}`}function Xl(t){if(!Number.isFinite(t))return`${t}`;if(t===0)return"0";const e=Math.abs(t);return e>=1e3||e<=.001?Number(t.toExponential(6)).toString():Number(t.toPrecision(6)).toString()}function rO(t){if(!Number.isFinite(t))return`${t}`;if(t===0)return"0";const e=[["T",1e12],["G",1e9],["MEG",1e6],["k",1e3],["m",.001],["u",1e-6],["n",1e-9],["p",1e-12]];for(const[n,o]of e){const i=t/o;if(Math.abs(i)>=.999999&&Math.abs(i)<999.999999){const r=Number(i.toPrecision(6));if(Math.abs(r*o-t)<=Math.abs(t)*1e-9)return`${r}${n}`}}return Xl(t)}var g4o=1e-12,d4o=({component:t,nodes:e})=>{if("resistance"in t&&"name"in t){const n=t.resistance,o=new s4o({name:t.name,positiveNode:e[0]||"0",negativeNode:e[1]||"0",value:A4o(n===0?g4o:n)});return new Uy(t.name,o,e)}return null},h4o=({netlist:t,component:e,nodes:n,simulationSwitchMap:o})=>{const i=dPt(e.name??e.source_component_id,"SW"),r=n[0]||"0",s=n[1]||"0",a=`NCTRL_${i}`,A=`SW_${i}`,c=o.get(e.source_component_id),l=u4o(c),u=new a4o({name:i,positiveNode:r,negativeNode:s,positiveControl:a,negativeControl:"0",model:A});t.models.has(A)||t.models.set(A,`.MODEL ${A} SW(Ron=0.1 Roff=1e9 Vt=2.5 Vh=0.1)`);const g=`CTRL_${i}`,h=new a0e({name:g,positiveNode:a,negativeNode:"0",value:l}),d=new Uy(g,h,[a,"0"]);return t.addComponent(d),new Uy(i,u,[r,s,a,"0"])},p4o=({component:t,nodes:e})=>{if("capacitance"in t&&"name"in t){const n=new n4o({name:t.name,positiveNode:e[0]||"0",negativeNode:e[1]||"0",value:c4o(t.capacitance)});return new Uy(t.name,n,e)}return null},m4o=(t,e)=>{const n=t.find(i=>i.name?.toLowerCase()==="anode"||i.port_hints?.includes("anode")),o=t.find(i=>i.name?.toLowerCase()==="cathode"||i.port_hints?.includes("cathode"));return{positiveNode:e.get(n?.source_port_id??"")||"0",negativeNode:e.get(o?.source_port_id??"")||"0"}},hPt=({netlist:t,component:e,componentPorts:n,nodeMap:o,modelName:i,modelDefinition:r})=>{if("name"in e){const{positiveNode:s,negativeNode:a}=m4o(n,o),A=new o4o({name:e.name,positiveNode:s,negativeNode:a,model:i});return t.models.set(i,r),new Uy(e.name,A,[s,a])}return null},_4o=({netlist:t,component:e,componentPorts:n,nodeMap:o})=>hPt({netlist:t,component:e,componentPorts:n,nodeMap:o,modelName:"D",modelDefinition:".MODEL D D"}),f4o=({netlist:t,component:e,componentPorts:n,nodeMap:o})=>hPt({netlist:t,component:e,componentPorts:n,nodeMap:o,modelName:"LED",modelDefinition:".MODEL LED D(IS=1e-20 N=2 RS=10 CJO=2p EG=2.1 BV=5 IBV=10u)"}),I4o=({component:t,nodes:e})=>{if("inductance"in t&&"name"in t){const n=new i4o({name:t.name,positiveNode:e[0]||"0",negativeNode:e[1]||"0",value:l4o(t.inductance)});return new Uy(t.name,n,e)}return null},C4o=({netlist:t,component:e,componentPorts:n,nodeMap:o})=>{if("name"in e){const i=n.find(m=>m.name?.toLowerCase()==="drain"||m.port_hints?.includes("drain")),r=n.find(m=>m.name?.toLowerCase()==="gate"||m.port_hints?.includes("gate")),s=n.find(m=>m.name?.toLowerCase()==="source"||m.port_hints?.includes("source")),a=o.get(i?.source_port_id??"")||"0",A=o.get(r?.source_port_id??"")||"0",c=o.get(s?.source_port_id??"")||"0",l=c,u=e.channel_type??"n",g=e.mosfet_mode??"enhancement",h=`${u.toUpperCase()}MOS`,d=`${h}_${g.toUpperCase()}`;if(!t.models.has(d))if(g==="enhancement"){const m=u==="p"?-1:1;t.models.set(d,`.MODEL ${d} ${h} (VTO=${m} KP=0.1)`)}else t.models.set(d,`.MODEL ${d} ${h} (KP=0.1)`);const p=new r4o({name:e.name,drain:a,gate:A,source:c,substrate:l,model:d});return new Uy(e.name,p,[a,A,c])}return null},y4o=({netlist:t,component:e,componentPorts:n,nodeMap:o})=>{if("name"in e){const i=n.find(h=>h.name?.toLowerCase()==="collector"||h.port_hints?.includes("collector")),r=n.find(h=>h.name?.toLowerCase()==="base"||h.port_hints?.includes("base")),s=n.find(h=>h.name?.toLowerCase()==="emitter"||h.port_hints?.includes("emitter"));if(!i||!r||!s)throw new Error(`Transistor ${e.name} is missing required ports (collector, base, emitter)`);const a=o.get(i.source_port_id)||"0",A=o.get(r.source_port_id)||"0",c=o.get(s.source_port_id)||"0",l=e.transistor_type??"npn",u=l.toUpperCase();t.models.has(u)||t.models.set(u,`.MODEL ${u} ${l.toUpperCase()}`);const g=new t4o({name:e.name,collector:a,base:A,emitter:c,model:u});return new Uy(e.name,g,[a,A,c])}return null},x4o=({netlist:t,simulationVoltageSources:e,nodeMap:n})=>{for(const o of e)if(o.type==="simulation_voltage_source")if(o.is_dc_source===!1){const i=o.terminal1_source_port_id??o.terminal1_source_net_id,r=o.terminal2_source_port_id??o.terminal2_source_net_id;if(i&&r){const s=n.get(i)||"0",a=n.get(r)||"0";let A="";if(o.wave_shape==="sinewave"){const l=o.voltage??(o.peak_to_peak_voltage??0)/2,u=o.frequency??0,g=0,h=0,d=o.phase??0;u>0?A=`SIN(0 ${l} ${u} ${g} ${h} ${d})`:A=`DC ${o.voltage??0}`}else if(o.wave_shape==="square"){const l=o.voltage??o.peak_to_peak_voltage??0,u=o.frequency??0,g=u===0?1/0:1/u,h=o.period===void 0?g:o.period/1e3,d=o.duty_cycle??.5,p=h*d,m=o.pulse_delay!==void 0?o.pulse_delay/1e3:0,_=o.rise_time!==void 0?rO(o.rise_time/1e3):"1n",f=o.fall_time!==void 0?rO(o.fall_time/1e3):"1n",I=o.pulse_width===void 0?rO(p):rO(o.pulse_width/1e3),C=rO(h);A=`PULSE(0 ${l} ${rO(m)} ${_} ${f} ${I} ${C})`}else o.voltage!==void 0&&(A=`DC ${o.voltage}`);if(A||o.ac_magnitude!==void 0){const c=new a0e({name:o.simulation_voltage_source_id,positiveNode:s,negativeNode:a,value:A,acMagnitude:o.ac_magnitude===void 0?void 0:Xl(o.ac_magnitude),acPhase:o.ac_phase===void 0?void 0:Xl(o.ac_phase)}),l=new Uy(o.simulation_voltage_source_id,c,[s,a]);t.addComponent(l)}}}else{const i="terminal1_source_port_id"in o&&typeof o.terminal1_source_port_id=="string"?o.terminal1_source_port_id:void 0,r="terminal2_source_port_id"in o&&typeof o.terminal2_source_port_id=="string"?o.terminal2_source_port_id:void 0,s=o.positive_source_port_id??o.positive_source_net_id??i,a=o.negative_source_port_id??o.negative_source_net_id??r;if(s&&a){const A=n.get(s)||"0",c=n.get(a)||"0",l=new a0e({name:o.simulation_voltage_source_id,positiveNode:A,negativeNode:c,value:`DC ${o.voltage}`,acMagnitude:o.ac_magnitude===void 0?void 0:Xl(o.ac_magnitude),acPhase:o.ac_phase===void 0?void 0:Xl(o.ac_phase)}),u=new Uy(o.simulation_voltage_source_id,l,[A,c]);t.addComponent(u)}}},E4o=({netlist:t,simulationCurrentSources:e,nodeMap:n})=>{for(const o of e)if(o.type==="simulation_current_source")if(o.is_dc_source===!1){const i=o.terminal1_source_port_id??o.terminal1_source_net_id,r=o.terminal2_source_port_id??o.terminal2_source_net_id;if(i&&r){const s=n.get(i)||"0",a=n.get(r)||"0";let A="";if(o.wave_shape==="sinewave"){const l=(o.peak_to_peak_current??0)/2,u=o.frequency??0,g=0,h=0,d=o.phase??0;u>0?A=`SIN(0 ${l} ${u} ${g} ${h} ${d})`:A=`DC ${l}`}else if(o.wave_shape==="square"){const l=o.peak_to_peak_current??0,u=o.frequency??0,g=u===0?1/0:1/u,h=o.duty_cycle??.5,d=g*h;A=`PULSE(0 ${l} 0 1n 1n ${d} ${g})`}if(A||o.ac_magnitude!==void 0){const c=new uPt({name:o.simulation_current_source_id,positiveNode:s,negativeNode:a,value:A,acMagnitude:o.ac_magnitude===void 0?void 0:Xl(o.ac_magnitude),acPhase:o.ac_phase===void 0?void 0:Xl(o.ac_phase)}),l=new Uy(o.simulation_current_source_id,c,[s,a]);t.addComponent(l)}}}else{const i="terminal1_source_port_id"in o&&typeof o.terminal1_source_port_id=="string"?o.terminal1_source_port_id:void 0,r="terminal2_source_port_id"in o&&typeof o.terminal2_source_port_id=="string"?o.terminal2_source_port_id:void 0,s=o.positive_source_port_id??o.positive_source_net_id??i,a=o.negative_source_port_id??o.negative_source_net_id??r;if(s&&a){const A=n.get(s)||"0",c=n.get(a)||"0",l=new uPt({name:o.simulation_current_source_id,positiveNode:A,negativeNode:c,value:`DC ${o.current}`,acMagnitude:o.ac_magnitude===void 0?void 0:Xl(o.ac_magnitude),acPhase:o.ac_phase===void 0?void 0:Xl(o.ac_phase)}),u=new Uy(o.simulation_current_source_id,l,[A,c]);t.addComponent(u)}}},B4o=["method","reltol","abstol","vntol"],b4o=(t,e)=>t.find(o=>o.connected_source_net_ids.includes(e))?.connected_source_port_ids[0],A0e=({sourcePortId:t,sourceNetId:e,sourceTraces:n,nodeMap:o})=>{if(t)return o.get(t);if(!e)return;const i=b4o(n,e);if(i)return o.get(i)},S4o=t=>dPt(`sense_${t.simulation_current_probe_id}`,"sense_current_probe"),Q4o=t=>{switch(t){case"spice_transient_analysis":return"TRAN";case"spice_dc_operating_point":return"OP";case"spice_dc_sweep":return"DC";case"spice_ac_analysis":return"AC"}},v4o=t=>{switch(t){case"linear":return"lin";case"decade":return"dec";case"octave":return"oct"}},w4o=t=>{if(t.experiment_type==="spice_transient_analysis"){const A=t.time_per_step,c=t.end_time_ms,l=t.start_time_ms;if(A===void 0||c===void 0)return null;const u=(l??0)/1e3;return new rPt({step:Xl(A/1e3),stop:Xl(c/1e3),...u>0?{start:Xl(u)}:{},uic:!0})}if(t.experiment_type==="spice_dc_operating_point")return new ePt;if(t.experiment_type==="spice_dc_sweep"){const{dc_sweep_voltage_source_id:A,dc_sweep_current_source_id:c,dc_sweep_start:l,dc_sweep_stop:u,dc_sweep_step:g}=t;if(l===void 0||u===void 0||g===void 0)return null;let h;if(A!==void 0)h=`V${A}`;else if(c!==void 0)h=`I${c}`;else return null;return new Xwt({source:h,start:Xl(l),stop:Xl(u),step:Xl(g)})}const{ac_sweep_type:e,ac_samples_per_interval:n,ac_sample_count:o,ac_start_frequency_hz:i,ac_stop_frequency_hz:r}=t;if(e===void 0||i===void 0||r===void 0)return null;const s=e==="linear"?o:n;if(s===void 0)return null;const a=v4o(e);return new qwt({sweep:a,points:s,start:Xl(i),stop:Xl(r)})},P4o=({netlist:t,simulationExperiment:e,simulationVoltageProbes:n,simulationCurrentProbes:o,sourceTraces:i,nodeMap:r})=>{const s=Q4o(e.experiment_type),a=new Set,A=e.spice_options;if(A){const c={};for(const l of B4o){const u=A[l];u!==void 0&&(c[l]=u)}Object.keys(c).length>0&&t.optionStatements.push(new tPt(c).getString())}if(n.length>0){const c=[];for(const l of n){const u=A0e({sourcePortId:l.signal_input_source_port_id,sourceNetId:l.signal_input_source_net_id,sourceTraces:i,nodeMap:r});if(!u)continue;if(l.reference_input_source_port_id||l.reference_input_source_net_id){const h=A0e({sourcePortId:l.reference_input_source_port_id,sourceNetId:l.reference_input_source_net_id,sourceTraces:i,nodeMap:r});if(h&&h!=="0"){const d=`V(${u},${h})`;a.add(d),c.push({simulation_voltage_probe_id:l.simulation_voltage_probe_id,name:l.name,spice_vector:d,source_node_name:u,reference_node_name:h})}else if(u!=="0"){const d=`V(${u})`;a.add(d),c.push({simulation_voltage_probe_id:l.simulation_voltage_probe_id,name:l.name,spice_vector:d,source_node_name:u,reference_node_name:h})}}else if(u!=="0"){const h=`V(${u})`;a.add(h),c.push({simulation_voltage_probe_id:l.simulation_voltage_probe_id,name:l.name,spice_vector:h,source_node_name:u})}}if(c.length>0)for(const l of c)t.metadataComments.push(`* tscircuit_probe ${JSON.stringify(l)}`)}if(o.length>0){const c=new Set,l=[];for(const u of o){const g=A0e({sourcePortId:u.positive_source_port_id,sourceNetId:u.positive_source_net_id,sourceTraces:i,nodeMap:r}),h=A0e({sourcePortId:u.negative_source_port_id,sourceNetId:u.negative_source_net_id,sourceTraces:i,nodeMap:r});if(!g||!h)continue;const d=S4o(u);let p=d,m=2;for(;c.has(p);)p=`${d}_${m++}`;c.add(p);const _=`V${p}`,f=`I(${_})`,I=new a0e({name:p,positiveNode:g,negativeNode:h,value:"DC 0"});t.addComponent(new Uy(p,I,[g,h])),a.add(f),l.push({simulation_current_probe_id:u.simulation_current_probe_id,name:u.name,spice_vector:f,sense_voltage_source_name:_,positive_node_name:g,negative_node_name:h})}if(l.length>0)for(const u of l)t.metadataComments.push(`* tscircuit_current_probe ${JSON.stringify(u)}`)}if(a.size>0){const c=[...a].join(" "),l=new nPt({analysis:s,expressions:[c]});l.command=".PRINT",t.printStatements.push(l.getString());const u=new oPt([c]);u.command=".SAVE",t.saveStatements.push(u.getString())}t.analysisCommand=w4o(e)?.getString()??null},wj="GENERIC_OPAMP",M4o=`
.SUBCKT ${wj} non_inverting_input inverting_input positive_supply negative_supply output
* Generic Op-Amp Model
E1 internal_output 0 non_inverting_input inverting_input 100k
Rin non_inverting_input inverting_input 10Meg
Rout internal_output output 75
D1 output positive_supply opamp_diode
D2 negative_supply output opamp_diode
.model opamp_diode D
.ENDS ${wj}
`.trim(),D4o=(t,e,n)=>{if(e.length!==0){t.models.has(wj)||t.models.set(wj,M4o);for(const o of e){if(o.type!=="simulation_op_amp")continue;const i=n.get(o.non_inverting_input_source_port_id)??"0",r=n.get(o.inverting_input_source_port_id)??"0",s=n.get(o.output_source_port_id)??"0",a=n.get(o.positive_supply_source_port_id)??"0",A=n.get(o.negative_supply_source_port_id)??"0",c=[i,r,a,A,s],l=new gPt({name:o.simulation_op_amp_id,nodes:c,subcircuitName:wj}),u=new Uy(o.simulation_op_amp_id,l,c);t.addComponent(u)}}};function N4o(t){const e=[];for(const s of t.split(/\r?\n/)){const a=s.trim();if(/^\+/.test(a)&&e.length>0){e[e.length-1]+=` ${a.slice(1).trim()}`;continue}e.push(a)}const n=e.find(s=>/^\.subckt\s+/i.test(s));if(!n)return null;const o=n.split(/\s+/),i=o[1],r=o.slice(2);return!i||r.length===0?null:{modelName:i,pinNames:r}}function R4o(t,e,n){if(e.length!==0)for(const o of e){const i=N4o(o.subcircuit_source);if(!i)continue;const{modelName:r,pinNames:s}=i;t.models.has(r)||t.models.set(r,o.subcircuit_source);const a=s.map(c=>{const l=o.spice_pin_to_source_port_map[c];return n.get(l)??"0"}),A=new gPt({name:o.simulation_spice_subcircuit_id,nodes:a,subcircuitName:r});t.addComponent(new Uy(o.simulation_spice_subcircuit_id,A,a))}}function T4o(t){const e=new e4o("* Circuit JSON to SPICE Netlist"),n=Mr(t).source_component.list(),o=Mr(t).source_port.list(),i=Mr(t).source_trace.list(),r=t.filter(y=>y.type==="simulation_voltage_probe"),s=t.filter(y=>y.type==="simulation_current_probe"),a=t.filter(y=>y.type==="simulation_switch").map(y=>y),A=t.filter(y=>y.type==="simulation_op_amp"),c=t.filter(y=>y.type==="simulation_spice_subcircuit"),l=new Map;for(const y of a)y.source_component_id&&l.set(y.source_component_id,y);const u=Mxe(t),g=new Map,h=new Map;let d=1;const p=new Set;if(r.length>0)for(const y of r)y.name&&p.add(y.name);const m=[...p].map(y=>/^N(\d+)$/i.exec(y)).filter(y=>y!==null).map(y=>parseInt(y[1],10));m.length>0&&(d=Math.max(...m)+1);const _=new Set,f=new Set(Mr(t).source_net.list().filter(y=>y.name?.toLowerCase().includes("gnd")).map(y=>y.source_net_id));if(f.size>0){for(const y of Mr(t).source_trace.list())if(y.connected_source_port_ids.length>0&&y.connected_source_net_ids.some(E=>f.has(E))){const E=y.connected_source_port_ids[0],B=u.getNetConnectedToId(E);B&&_.add(B)}}const I=o.filter(y=>y.name?.toLowerCase()==="gnd");for(const y of I){const x=u.getNetConnectedToId(y.source_port_id);x&&_.add(x)}for(const y of Mr(t).simulation_voltage_source.list()){const x=y.negative_source_port_id??y.terminal2_source_port_id;if(x){const E=u.getNetConnectedToId(x);E&&_.add(E)}}for(const y of _)h.set(y,"0");if(r.length>0)for(const y of r){if(!y.name||y.reference_input_source_port_id||y.reference_input_source_net_id)continue;let x;const E=y.signal_input_source_port_id,B=y.signal_input_source_net_id;if(E)x=u.getNetConnectedToId(E);else if(B){const S=i.find(Q=>Q.connected_source_net_ids.includes(B));if(S&&S.connected_source_port_ids.length>0){const Q=S.connected_source_port_ids[0];x=u.getNetConnectedToId(Q)}}x?h.has(x)||h.set(x,y.name):E&&y.name&&g.set(E,y.name)}for(const y of o){const x=y.source_port_id,E=u.getNetConnectedToId(x);E&&(h.has(E)||h.set(E,`N${d++}`),g.set(x,h.get(E)))}for(const y of i){const x=y.connected_source_port_ids.map(E=>g.get(E)).find(E=>E!==void 0);if(x)for(const E of y.connected_source_net_ids)g.set(E,x)}for(const y of o){const x=y.source_port_id;g.has(x)||g.set(x,`N${d++}`)}for(const y of n){if(y.type!=="source_component")continue;const x=Mr(t).source_port.list({source_component_id:y.source_component_id}).sort((B,S)=>(B.pin_number??0)-(S.pin_number??0)),E=x.map(B=>g.get(B.source_port_id)||"0");if("ftype"in y){let B=null;switch(y.ftype){case"simple_resistor":{B=d4o({component:y,nodes:E});break}case"simple_switch":{B=h4o({netlist:e,component:y,nodes:E,simulationSwitchMap:l});break}case"simple_capacitor":{B=p4o({component:y,nodes:E});break}case"simple_diode":{B=_4o({netlist:e,component:y,componentPorts:x,nodeMap:g});break}case"simple_led":{B=f4o({netlist:e,component:y,componentPorts:x,nodeMap:g});break}case"simple_inductor":{B=I4o({component:y,nodes:E});break}case"simple_mosfet":{B=C4o({netlist:e,component:y,componentPorts:x,nodeMap:g});break}case"simple_transistor":{B=y4o({netlist:e,component:y,componentPorts:x,nodeMap:g});break}}B&&e.addComponent(B)}}x4o({netlist:e,simulationVoltageSources:Mr(t).simulation_voltage_source.list(),nodeMap:g}),E4o({netlist:e,simulationCurrentSources:Mr(t).simulation_current_source.list(),nodeMap:g}),D4o(e,A,g),R4o(e,c,g);const C=t.find(y=>y.type==="simulation_experiment");return C&&P4o({netlist:e,simulationExperiment:C,simulationVoltageProbes:r,simulationCurrentProbes:s,sourceTraces:i,nodeMap:g}),e}function bwe(t,e){e=pPt(e||{R:255,G:255,B:255}),t=pPt(t);let n=t;return t.A!==void 0&&(n={R:e.R+(t.R-e.R)*t.A,G:e.G+(t.G-e.G)*t.A,B:e.B+(t.B-e.B)*t.A}),F4o(k4o(n))}function k4o(t){let e=t.R/255,n=t.G/255,o=t.B/255;e>.04045?e=Math.pow((e+.055)/1.055,2.4):e=e/12.92,n>.04045?n=Math.pow((n+.055)/1.055,2.4):n=n/12.92,o>.04045?o=Math.pow((o+.055)/1.055,2.4):o=o/12.92,e*=100,n*=100,o*=100;const i=e*.4124+n*.3576+o*.1805,r=e*.2126+n*.7152+o*.0722,s=e*.0193+n*.1192+o*.9505;return{X:i,Y:r,Z:s}}function F4o(t){let i=t.Y/100,r=t.Z/108.883,s=t.X/95.047;s>.008856?s=Math.pow(s,1/3):s=7.787*s+16/116,i>.008856?i=Math.pow(i,1/3):i=7.787*i+16/116,r>.008856?r=Math.pow(r,1/3):r=7.787*r+16/116;const a=116*i-16,A=500*(s-i),c=200*(i-r);return{L:a,a:A,b:c}}function pPt(t){let e,n,o,i;"R"in t?(e=t.R,n=t.G,o=t.B,i=t.A):(e=t.r,n=t.g,o=t.b,i=t.a);const r={R:e,G:n,B:o};return i!==void 0&&(r.A=i),r}function L4o(t,e,n){("R"in t||"r"in t)&&(t=bwe(t,n)),("R"in e||"r"in e)&&(e=bwe(e,n));const o=t.L,i=t.a,r=t.b,s=e.L,a=e.a,A=e.b,c=1,l=1,u=1,g=Math.sqrt(Math.pow(i,2)+Math.pow(r,2)),h=Math.sqrt(Math.pow(a,2)+Math.pow(A,2)),d=(g+h)/2,p=.5*(1-Math.sqrt(Math.pow(d,7)/(Math.pow(d,7)+Math.pow(25,7)))),m=(1+p)*i,_=(1+p)*a,f=Math.sqrt(Math.pow(m,2)+Math.pow(r,2)),I=Math.sqrt(Math.pow(_,2)+Math.pow(A,2)),C=mPt(r,m),y=mPt(A,_),x=s-o,E=I-f,B=O4o(g,h,C,y),S=2*Math.sqrt(f*I)*Math.sin(sO(B)/2),Q=(o+s)/2,w=(f+I)/2,M=G4o(g,h,C,y),k=1-.17*Math.cos(sO(M-30))+.24*Math.cos(sO(2*M))+.32*Math.cos(sO(3*M+6))-.2*Math.cos(sO(4*M-63)),R=30*Math.exp(-Math.pow((M-275)/25,2)),F=Math.sqrt(Math.pow(w,7)/(Math.pow(w,7)+Math.pow(25,7))),O=1+.015*Math.pow(Q-50,2)/Math.sqrt(20+Math.pow(Q-50,2)),U=1+.045*w,Y=1+.015*w*k,W=-2*F*Math.sin(sO(2*R));return Math.sqrt(Math.pow(x/(O*c),2)+Math.pow(E/(U*l),2)+Math.pow(S/(Y*u),2)+W*(E/(U*l))*(S/(Y*u)))}function H4o(t){return t*(180/Math.PI)}function sO(t){return t*(Math.PI/180)}function mPt(t,e){if(t===0&&e===0)return 0;{const n=H4o(Math.atan2(t,e));return n>=0?n:n+360}}function O4o(t,e,n,o){if(t*e===0)return 0;if(Math.abs(o-n)<=180)return o-n;if(o-n>180)return o-n-360;if(o-n<-180)return o-n+360;throw new Error}function G4o(t,e,n,o){if(t*e===0)return n+o;if(Math.abs(n-o)<=180)return(n+o)/2;if(Math.abs(n-o)>180&&n+o<360)return(n+o+360)/2;if(Math.abs(n-o)>180&&n+o>=360)return(n+o-360)/2;throw new Error}function _Pt(t){return bwe(t)}var Y4o=2.3,fPt={R:255,G:0,B:255},xb=({color1:t,color2:e})=>t.R===e.R&&t.G===e.G&&t.B===e.B,c0e=t=>{try{const e=Cpo(t);if(e.depth!==8)return null;const n=e.channels,o=e.data,i=new Uint8Array(e.width*e.height*4);if(n===4)i.set(o);else if(n===3)for(let r=0,s=0;r<o.length;r+=3,s+=4)i[s]=o[r],i[s+1]=o[r+1],i[s+2]=o[r+2],i[s+3]=255;else return null;return{width:e.width,height:e.height,data:i,getPixel:(r,s)=>{const a=(s*e.width+r)*4;return{R:i[a],G:i[a+1],B:i[a+2]}}}}catch{return null}},l0e=async t=>t instanceof Uint8Array?t:new Uint8Array(t),U4o=(t,e)=>{if(t.byteLength!==e.byteLength)return!1;for(let n=0;n<t.byteLength;n+=1)if(t[n]!==e[n])return!1;return!0},K4o=t=>{if(!t)return fPt;const e=/^#?([0-9a-fA-F]{6})$/.exec(t.trim());if(!e)return fPt;const n=e[1];return{R:Number.parseInt(n.slice(0,2),16),G:Number.parseInt(n.slice(2,4),16),B:Number.parseInt(n.slice(4,6),16)}},V4o=t=>{const e=t*6.2,n=t*.695;let o=null,i=null,r=null,s=null;return a=>{if(xb(a))return!0;let A=null,c=null;o&&xb({color1:a.color1,color2:o})?A=r:i&&xb({color1:a.color1,color2:i})&&(A=s),o&&xb({color1:a.color2,color2:o})?c=r:i&&xb({color1:a.color2,color2:i})&&(c=s),A||(A=_Pt(a.color1),o=a.color1,r=A),c||(c=_Pt(a.color2),i=a.color2,s=c);const l=Math.sqrt((A.L-c.L)*(A.L-c.L)+(A.a-c.a)*(A.a-c.a)+(A.b-c.b)*(A.b-c.b));return l>=e?!1:l<=n?!0:L4o(A,c)<t}},z4o=class{_baseComparator;_img1;_img2;_brightnessTolerance;constructor(t,e,n,{antialiasingTolerance:o=0}){this._baseComparator=t,this._img1=e,this._img2=n,this._brightnessTolerance=o}compare(t){return this._baseComparator(t)||this._checkIsAntialiased(t)}_checkIsAntialiased(t){return this._isAntialiased(this._img2,t.x,t.y,t,this._img1)||this._isAntialiased(this._img1,t.x,t.y,t,this._img2)}_isAntialiased(t,e,n,o,i){const r=t.getPixel(e,n),s=Math.max(e-1,0),a=Math.max(n-1,0),A=Math.min(e+1,o.width-1),c=Math.min(n+1,o.height-1),l=!i,u=l?this._brightnessTolerance:0;let g=0,h=0,d=0,p=0,m=0,_=0,f=0,I=0,C=0;for(let y=a;y<=c;y+=1)for(let x=s;x<=A;x+=1){if(x===e&&y===n)continue;const E=this._brightnessDelta(t.getPixel(x,y),r);if(Math.abs(E)<=u?g+=1:E>u?h+=1:d+=1,g>2)return!1;l||(E<p&&(p=E,_=x,f=y),E>m&&(m=E,I=x,C=y))}return l?!0:d===0||h===0?!1:!this._isAntialiased(t,_,f,o)&&!this._isAntialiased(i,_,f,o)||!this._isAntialiased(t,I,C,o)&&!this._isAntialiased(i,I,C,o)}_brightnessDelta(t,e){return t.R*.29889531+t.G*.58662247+t.B*.11448223-(e.R*.29889531+e.G*.58662247+e.B*.11448223)}},J4o=class{pixelRatio;caretTopLeft=null;caretBottomRight=null;_baseComparator;_state="init";constructor(t,e){this.pixelRatio=e?Math.floor(e):1,this._baseComparator=t}compare(t){return this._baseComparator(t)||this._checkIsCaret(t)}_checkIsCaret(t){if(this._state==="caretDetected")return this.caretTopLeft!==null&&this.caretBottomRight!==null&&t.x>=this.caretTopLeft.x&&t.x<=this.caretBottomRight.x&&t.y>=this.caretTopLeft.y&&t.y<=this.caretBottomRight.y;if(this.caretTopLeft&&this.caretBottomRight&&t.x>=this.caretTopLeft.x&&t.x<=this.caretBottomRight.x&&t.y>=this.caretTopLeft.y&&t.y<=this.caretBottomRight.y)return!0;const e=this._getLastCaretPoint(t);return this._looksLikeCaret({x:t.x,y:t.y},e)?(this.caretTopLeft={x:t.x,y:t.y},this.caretBottomRight=e,this._state="caretDetected",!0):!1}_getLastCaretPoint(t){let e={x:t.x,y:t.y};for(;;){const n=this._getNextCaretPoint({x:t.x,y:t.y},e);if(this._isPointOutsideImages(n,t)||this._areColorsSame(n,t))return e;e=n}}_isPointOutsideImages(t,e){return t.x>=e.minWidth||t.y>=e.minHeight}_areColorsSame(t,e){const n=e.img1.getPixel(t.x,t.y),o=e.img2.getPixel(t.x,t.y);return xb({color1:n,color2:o})}_getNextCaretPoint(t,e){const n=e.x+1;return n<t.x+this.pixelRatio?{x:n,y:e.y}:{x:t.x,y:e.y+1}}_looksLikeCaret(t,e){return this._caretHeight(t,e)>1&&this._caretWidth(t,e)===this.pixelRatio}_caretHeight(t,e){return e.y-t.y+1}_caretWidth(t,e){return e.x-t.x+1}},IPt=(t={})=>{if(t.strict&&t.tolerance!==void 0)throw new TypeError('Unable to use "strict" and "tolerance" options together');if(t.percentThreshold!==void 0&&(!Number.isFinite(t.percentThreshold)||t.percentThreshold<0))throw new TypeError('Expected "percentThreshold" to be a non-negative number');return{strict:!!t.strict,tolerance:t.tolerance??Y4o,ignoreCaret:t.ignoreCaret??!0,ignoreAntialiasing:t.ignoreAntialiasing??!0,antialiasingTolerance:t.antialiasingTolerance??0,pixelRatio:t.pixelRatio}},CPt=(t,e,n)=>{let o=n.strict?i=>xb(i):V4o(n.tolerance);if(n.ignoreAntialiasing){const i=new z4o(o,t,e,n);o=r=>i.compare(r)}if(n.ignoreCaret){const i=new J4o(o,n.pixelRatio);o=r=>i.compare(r)}return o},W4o=async(t,e,n)=>{const o=c0e(t),i=c0e(e);if(!o||!i)return{equal:U4o(t,e)};const r=CPt(o,i,n),s=Math.max(o.width,i.width),a=Math.max(o.height,i.height),A=Math.min(o.width,i.width),c=Math.min(o.height,i.height),l=s*a;let u=0;for(let g=0;g<a;g+=1)for(let h=0;h<s;h+=1){if(h>=A||g>=c){u+=1;continue}const d=o.getPixel(h,g),p=i.getPixel(h,g);xb({color1:d,color2:p})||r({color1:d,color2:p,img1:o,img2:i,x:h,y:g,width:s,height:a,minWidth:A,minHeight:c})||(u+=1)}return{equal:u===0,differentPixels:u,totalPixels:l}},j4o=async(t,e,n={})=>{const o=IPt(n),i=await l0e(t),r=await l0e(e);return W4o(i,r,o)},$4o=async({reference:t,current:e,highlightColor:n,...o})=>{const i=IPt(o),r=await l0e(t),s=await l0e(e),a=c0e(r),A=c0e(s);if(!(a&&A))return s;const c=CPt(a,A,i),l=Math.max(a.width,A.width),u=Math.max(a.height,A.height),g=Math.min(a.width,A.width),h=Math.min(a.height,A.height),d=K4o(n),p=new Uint8Array(l*u*4);for(let _=0;_<u;_+=1)for(let f=0;f<l;f+=1){const I=(_*l+f)*4;if(f>=g||_>=h){p[I]=d.R,p[I+1]=d.G,p[I+2]=d.B,p[I+3]=255;continue}const C=a.getPixel(f,_),y=A.getPixel(f,_);xb({color1:C,color2:y})||c({color1:C,color2:y,img1:a,img2:A,x:f,y:_,width:l,height:u,minWidth:g,minHeight:h})?(p[I]=C.R,p[I+1]=C.G,p[I+2]=C.B,p[I+3]=255):(p[I]=d.R,p[I+1]=d.G,p[I+2]=d.B,p[I+3]=255)}return ypo({width:l,height:u,data:p,channels:4,depth:8})};Object.assign(j4o,{createDiff:$4o});function q4o(t,e){return Array.isArray(e)?[t.a*e[0]+t.c*e[1]+t.e,t.b*e[0]+t.d*e[1]+t.f]:{x:t.a*e.x+t.c*e.y+t.e,y:t.b*e.x+t.d*e.y+t.f}}function X4o(t,e){function n(){this.constructor=t}n.prototype=e.prototype,t.prototype=new n}function u0e(t,e,n,o){var i=Error.call(this,t);return Object.setPrototypeOf&&Object.setPrototypeOf(i,u0e.prototype),i.expected=e,i.found=n,i.location=o,i.name="SyntaxError",i}X4o(u0e,Error);function Swe(t,e,n){return n=n||" ",t.length>e?t:(e-=t.length,n+=n.repeat(e),t+n.slice(0,e))}u0e.prototype.format=function(t){var e="Error: "+this.message;if(this.location){var n=null,o;for(o=0;o<t.length;o++)if(t[o].source===this.location.source){n=t[o].text.split(/\r\n|\n|\r/g);break}var i=this.location.start,r=this.location.source&&typeof this.location.source.offset=="function"?this.location.source.offset(i):i,s=this.location.source+":"+r.line+":"+r.column;if(n){var a=this.location.end,A=Swe("",r.line.toString().length," "),c=n[i.line-1],l=i.line===a.line?a.column:c.length+1,u=l-i.column||1;e+=`
--> `+s+`
`+A+` |
`+r.line+" | "+c+`
`+A+" | "+Swe("",i.column-1," ")+Swe("",u,"^")}else e+=`
at `+s}return e},u0e.buildMessage=function(t,e){var n={literal:function(c){return'"'+i(c.text)+'"'},class:function(c){var l=c.parts.map(function(u){return Array.isArray(u)?r(u[0])+"-"+r(u[1]):r(u)});return"["+(c.inverted?"^":"")+l.join("")+"]"},any:function(){return"any character"},end:function(){return"end of input"},other:function(c){return c.description}};function o(c){return c.charCodeAt(0).toString(16).toUpperCase()}function i(c){return c.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,function(l){return"\\x0"+o(l)}).replace(/[\x10-\x1F\x7F-\x9F]/g,function(l){return"\\x"+o(l)})}function r(c){return c.replace(/\\/g,"\\\\").replace(/\]/g,"\\]").replace(/\^/g,"\\^").replace(/-/g,"\\-").replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,function(l){return"\\x0"+o(l)}).replace(/[\x10-\x1F\x7F-\x9F]/g,function(l){return"\\x"+o(l)})}function s(c){return n[c.type](c)}function a(c){var l=c.map(s),u,g;if(l.sort(),l.length>0){for(u=1,g=1;u<l.length;u++)l[u-1]!==l[u]&&(l[g]=l[u],g++);l.length=g}switch(l.length){case 1:return l[0];case 2:return l[0]+" or "+l[1];default:return l.slice(0,-1).join(", ")+", or "+l[l.length-1]}}function A(c){return c?'"'+i(c)+'"':"end of input"}return"Expected "+a(t)+" but "+A(e)+" found."};function Pj(t,e){const n=new lse(t),o=n.getTotalLength(),i=Math.max(2,Math.ceil(o*e)),r=[];for(let s=1;s<=i;s++){const a=s/i*o,A=n.getPointAtLength(a);r.push({x:A.x,y:A.y})}return r}function Z4o(t,e=10){const n=new lse(t);n.toAbsolute();const o=n.segments,i=[];let r=[],s=0,a=0,A=0,c=0;for(const l of o)switch(l[0]){case"M":{r.length>0&&i.push(r),s=l[1],a=l[2],A=s,c=a,r=[{x:s,y:a}];break}case"L":{s=l[1],a=l[2],r.push({x:s,y:a});break}case"H":{s=l[1],r.push({x:s,y:a});break}case"V":{a=l[1],r.push({x:s,y:a});break}case"Z":{(s!==A||a!==c)&&r.push({x:A,y:c}),s=A,a=c;break}case"C":{const g=l[5],h=l[6],d=`M ${s} ${a} C ${l[1]} ${l[2]} ${l[3]} ${l[4]} ${g} ${h}`,p=Pj(d,e);r.push(...p),s=g,a=h;break}case"S":{const g=l[3],h=l[4],d=`M ${s} ${a} S ${l[1]} ${l[2]} ${g} ${h}`,p=Pj(d,e);r.push(...p),s=g,a=h;break}case"Q":{const g=l[3],h=l[4],d=`M ${s} ${a} Q ${l[1]} ${l[2]} ${g} ${h}`,p=Pj(d,e);r.push(...p),s=g,a=h;break}case"T":{const g=l[1],h=l[2],d=`M ${s} ${a} T ${g} ${h}`,p=Pj(d,e);r.push(...p),s=g,a=h;break}case"A":{const g=l[6],h=l[7],d=`M ${s} ${a} A ${l[1]} ${l[2]} ${l[3]} ${l[4]} ${l[5]} ${g} ${h}`,p=Pj(d,e);r.push(...p),s=g,a=h;break}}return r.length>0&&i.push(r),i.map(l=>{const u=[];for(const g of l)(u.length===0||Math.abs(u[u.length-1].x-g.x)>1e-9||Math.abs(u[u.length-1].y-g.y)>1e-9)&&u.push(g);return u})}var Eb="image/svg+xml",yPt="image/png";async function xPt(t){if(t.startsWith("data:"))return tBo(t);let e;try{e=await fetch(t)}catch(i){throw new Error(`Failed to fetch image "${t}". Pass a data URL or a fetchable URL.`,{cause:i})}if(!e.ok)throw new Error(`Failed to fetch image "${t}": ${e.status} ${e.statusText}`);const n=e.headers.get("content-type")?.split(";")[0],o=n&&n!=="application/octet-stream"?n:nBo(t);return{mimetype:o,text:o===Eb?await e.text():"",dataUrl:t,projectRelativePath:t}}function eBo({svg:t,width:e,height:n,transform:o}){const i=EPt({svg:t,width:e,height:n,transform:o}).map(oBo).filter(s=>s.length>=3).map(s=>({vertices:s,polygon:bPt(s),samplePoint:rBo(s)})).map(s=>({...s,area:s.polygon.area()})).filter(s=>s.area>1e-9),r=i.filter(s=>i.filter(A=>A!==s&&A.area>s.area&&A.polygon.contains(by(s.samplePoint.x,s.samplePoint.y))).length%2===0);return r.map(s=>{const a=i.filter(A=>A!==s&&A.area<s.area&&s.polygon.contains(by(A.samplePoint.x,A.samplePoint.y))&&!r.some(c=>c!==s&&c.area<s.area&&c.area>A.area&&c.polygon.contains(by(A.samplePoint.x,A.samplePoint.y)))).map(A=>({vertices:iBo(A.vertices)}));return{outer_ring:{vertices:BPt(s.vertices)},inner_rings:a}})}function EPt({svg:t,width:e,height:n,transform:o}){const i=sBo(t),r=e/i.width,s=n/i.height;return aBo(t).flatMap(a=>Z4o(a,.03).map(A=>A.map(c=>q4o(o,{x:(c.x-i.x-i.width/2)*r,y:-(c.y-i.y-i.height/2)*s})).filter((c,l,u)=>l===0||Math.abs(c.x-u[l-1].x)>1e-6||Math.abs(c.y-u[l-1].y)>1e-6)))}function BPt(t){return SPt(t)>0?[...t].reverse():t}function tBo(t){const e=t.indexOf(",");if(!t.startsWith("data:")||e===-1)throw new Error("Invalid data URL for image source");const n=t.slice(5,e),o=t.slice(e+1),i=n.split(";")[0]||Eb,r=n.includes(";base64")?new TextDecoder().decode(Uint8Array.from(atob(o),s=>s.charCodeAt(0))):decodeURIComponent(o);return{mimetype:i,text:r,dataUrl:t,projectRelativePath:"inline"}}function nBo(t){const e=t.toLowerCase();return e.endsWith(".svg")?Eb:e.endsWith(".png")?yPt:"application/octet-stream"}function oBo(t){if(t.length<2)return t;const e=t[0],n=t[t.length-1];return Math.abs(e.x-n.x)<1e-6&&Math.abs(e.y-n.y)<1e-6?t.slice(0,-1):t}function iBo(t){return SPt(t)<0?[...t].reverse():t}function rBo(t){let e=0,n=0;for(const o of t)e+=o.x,n+=o.y;return{x:e/t.length,y:n/t.length}}function bPt(t){const e=new Ip;return e.addFace(t.map(n=>by(n.x,n.y))),e}function SPt(t){return[...bPt(t).faces][0].signedArea()}function sBo(t){const n=t.match(/\bviewBox\s*=\s*["']([^"']+)["']/i)?.[1]?.trim().split(/[\s,]+/).map(Number);return n?.length===4&&n.every(Number.isFinite)?{x:n[0],y:n[1],width:n[2],height:n[3]}:{x:0,y:0,width:1,height:1}}function aBo(t){const e=[],n=/<path\b[^>]*>/gi;for(const o of t.match(n)??[]){const i=o.match(/\bd\s*=\s*(["'])(.*?)\1/i);i?.[2]&&e.push(i[2])}return e}var z7=class{MAX_ITERATIONS=1e5;solved=!1;failed=!1;iterations=0;progress=0;error=null;activeSubSolver;failedSubSolvers;timeToSolve;stats={};_setupDone=!1;getSolverName(){return this.constructor.name}setup(){this._setupDone||(this._setup(),this._setupDone=!0)}_setup(){}step(){if(this._setupDone||this.setup(),!this.solved&&!this.failed){this.iterations++;try{this._step()}catch(t){throw this.error=`${this.getSolverName()} error: ${t}`,this.failed=!0,t}!this.solved&&this.iterations>=this.MAX_ITERATIONS&&this.tryFinalAcceptance(),!this.solved&&this.iterations>=this.MAX_ITERATIONS&&(this.error=`${this.getSolverName()} ran out of iterations`,this.failed=!0),"computeProgress"in this&&(this.progress=this.computeProgress())}}_step(){}getConstructorParams(){throw new Error("getConstructorParams not implemented")}getOutput(){return null}solve(){const t=Date.now();for(;!this.solved&&!this.failed;)this.step();const e=Date.now();this.timeToSolve=e-t}visualize(){return{lines:[],points:[],rects:[],circles:[]}}tryFinalAcceptance(){}preview(){return{lines:[],points:[],rects:[],circles:[]}}};function Bb(t,e,n,o={}){return{solverName:t,solverClass:e,getConstructorParams:n,onSolved:o.onSolved}}var ABo=class extends z7{startTimeOfStage={};endTimeOfStage={};timeSpentOnStage={};firstIterationOfStage={};currentPipelineStageIndex=0;inputProblem;pipelineOutputs={};constructor(t){super(),this.inputProblem=t,this.MAX_ITERATIONS=1e6}_step(){const t=this.pipelineDef[this.currentPipelineStageIndex];if(!t){this.solved=!0;return}if(this.activeSubSolver){if(this.activeSubSolver.step(),this.activeSubSolver.solved){this.endTimeOfStage[t.solverName]=performance.now(),this.timeSpentOnStage[t.solverName]=this.endTimeOfStage[t.solverName]-this.startTimeOfStage[t.solverName];const n=this.activeSubSolver.getOutput();n!==null&&(this.pipelineOutputs[t.solverName]=n),t.onSolved?.(this),this.activeSubSolver=null,this.currentPipelineStageIndex++}else this.activeSubSolver.failed&&(this.error=this.activeSubSolver?.error,this.failed=!0,this.activeSubSolver=null);return}const e=t.getConstructorParams(this);this.activeSubSolver=new t.solverClass(...e),this[t.solverName]=this.activeSubSolver,this.timeSpentOnStage[t.solverName]=0,this.startTimeOfStage[t.solverName]=performance.now(),this.firstIterationOfStage[t.solverName]=this.iterations}solveUntilStage(t){for(;this.getCurrentStageName().toLowerCase()!==t.toLowerCase()&&(this.step(),!(this.failed||this.solved)););}getCurrentStageName(){return this.pipelineDef[this.currentPipelineStageIndex]?.solverName??"none"}getStageProgress(){const t=this.pipelineDef.length;if(t===0)return 1;const e=this.activeSubSolver?.progress??0;return(this.currentPipelineStageIndex+e)/t}getStageStats(){const t={};for(const e of this.pipelineDef){const n=this.timeSpentOnStage[e.solverName]||0,o=this.firstIterationOfStage[e.solverName]||0,i=this.iterations,r=e.solverName===this.getCurrentStageName()?i-o:0,s=this.currentPipelineStageIndex>this.pipelineDef.findIndex(a=>a.solverName===e.solverName);t[e.solverName]={timeSpent:n,iterations:r,completed:s}}return t}initialVisualize(){return null}finalVisualize(){return null}visualize(){if(!this.solved&&this.activeSubSolver)return this.activeSubSolver.visualize();let t=0;const e=this.initialVisualize();e&&(RH(e,0),t=1);let n=null;this.solved&&(n=this.finalVisualize());const o=[e].filter(Boolean).concat(this.pipelineDef.map((i,r)=>{const a=this[i.solverName]?.visualize();return a?(RH(a,r+t),a):null}).filter(Boolean));return o.length===0?{points:[],rects:[],lines:[],circles:[],texts:[]}:(this.solved&&n&&(RH(n,o.length+t+1),o.push(n)),o.length===1?o[0]:{points:o.flatMap(i=>i.points||[]),rects:o.flatMap(i=>i.rects||[]),lines:o.flatMap(i=>i.lines||[]),circles:o.flatMap(i=>i.circles||[]),texts:o.flatMap(i=>i.texts||[])})}preview(){return this.activeSubSolver?this.activeSubSolver.preview():super.preview()}computeProgress(){return this.getStageProgress()}getStageOutput(t){return this.pipelineOutputs[t]}getAllOutputs(){return{...this.pipelineOutputs}}hasStageOutput(t){return t in this.pipelineOutputs}getSolver(t){return this[t]}},cBo=class extends z7{constructor(t){super(),this.params=t;const{cellContents:e}=t;for(let n=0;n<e.length;n++)for(let o=n+1;o<e.length;o++)this._allPairs.push([n,o])}params;midlines=[];_pairIdx=0;_allPairs=[];_step(){const{cellContents:t,containerWidth:e,containerHeight:n}=this.params;if(this._pairIdx>=this._allPairs.length){this.solved=!0;return}const[o,i]=this._allPairs[this._pairIdx],r=t[o],s=t[i],a=r.x+r.width,A=s.x+s.width,c=r.y+r.height,l=s.y+s.height;if(a<s.x||A<r.x){const u=a<s.x?(a+s.x)/2:(A+r.x)/2;this.midlines.push({id:`midline-${this.midlines.length}`,start:{x:u,y:0},end:{x:u,y:n},cellIds:[r.cellId,s.cellId],type:"vertical"})}if(c<s.y||l<r.y){const u=c<s.y?(c+s.y)/2:(l+r.y)/2;this.midlines.push({id:`midline-${this.midlines.length}`,start:{x:0,y:u},end:{x:e,y:u},cellIds:[r.cellId,s.cellId],type:"horizontal"})}this._pairIdx++,this._pairIdx>=this._allPairs.length&&(this.solved=!0)}getOutput(){return this.midlines}getConstructorParams(){return[this.params]}visualize(){const{cellContents:t}=this.params,e=this._allPairs[this._pairIdx],n=e?new Set([t[e[0]]?.cellId,t[e[1]]?.cellId]):new Set;return{rects:t.map(o=>({center:{x:o.x+o.width/2,y:o.y+o.height/2},width:o.width,height:o.height,fill:n.has(o.cellId)?"rgba(255, 80, 80, 0.45)":"rgba(255, 165, 0, 0.3)",stroke:n.has(o.cellId)?"#ff2020":"#c87000",label:o.cellId})),lines:this.midlines.map(o=>({points:[o.start,o.end],strokeColor:"#888888",strokeDash:[4,4],label:o.id}))}}},lBo=(t,e)=>{const n=t.start.x,o=t.start.y,i=t.end.x,r=t.end.y,s=e.start.x,a=e.start.y,A=e.end.x,c=e.end.y,l=(n-i)*(a-c)-(o-r)*(s-A);if(Math.abs(l)<1e-4)return null;const u=((n-s)*(a-c)-(o-a)*(s-A))/l,g=-((n-i)*(o-a)-(o-r)*(n-s))/l;return u>=0&&u<=1&&g>=0&&g<=1?{x:n+u*(i-n),y:o+u*(r-o)}:null},uBo=class extends z7{constructor(t){super(),this.params=t}params;intersections=[];_outerIdx=0;_step(){const{midlines:t}=this.params;if(t.length<=1){this.solved=!0;return}if(this._outerIdx>=t.length-1){this.solved=!0;return}const e=t[this._outerIdx];for(const n of t.slice(this._outerIdx+1)){const o=lBo(e,n);o&&this.intersections.push({point:o,midlineIds:[e.id,n.id]})}this._outerIdx++,this._outerIdx>=t.length-1&&(this.solved=!0)}getOutput(){return this.intersections}getConstructorParams(){return[this.params]}visualize(){const{midlines:t}=this.params,e=t[this._outerIdx];return{lines:t.map(n=>({points:[n.start,n.end],strokeColor:n===e?"#2196f3":"#cccccc",strokeWidth:n===e?2.5:1,strokeDash:n===e?void 0:[4,4]})),points:this.intersections.map(n=>({x:n.point.x,y:n.point.y,color:"#e63946",label:`(${n.point.x.toFixed(1)}, ${n.point.y.toFixed(1)})`}))}}},gBo=t=>{const e=[];for(let n=0;n+1<t.length;n++){const o=t[n],i=t[n+1];o!==void 0&&i!==void 0&&e.push([o,i])}return e},dBo=(t,e)=>{const n=Math.max(e.x,Math.min(t.x,e.x+e.width)),o=Math.max(e.y,Math.min(t.y,e.y+e.height)),i=t.x-n,r=t.y-o;return Math.sqrt(i*i+r*r)},hBo=(t,e,n)=>{let i=1/0;for(let r=0;r<=10;r++){const s=r/10,a={x:t.x+s*(e.x-t.x),y:t.y+s*(e.y-t.y)};i=Math.min(i,dBo(a,n))}return i},pBo=(t,e,n)=>Math.min(...n.map(o=>hBo(t,e,o))),mBo=class extends z7{constructor(t){super(),this.params=t}params;allSegments=[];_midlineIdx=0;_segmentId=0;_step(){const{midlines:t,intersections:e,cellContents:n}=this.params;if(this._midlineIdx>=t.length){this.solved=!0;return}const o=t[this._midlineIdx],i=e.filter(r=>r.midlineIds.includes(o.id)).map(r=>r.point).sort((r,s)=>o.type==="vertical"?r.y-s.y:r.x-s.x);for(const[r,s]of gBo([o.start,...i,o.end]))this.allSegments.push({id:`segment-${this._segmentId++}`,start:r,end:s,fromCellIds:o.cellIds,distanceToAnyCell:pBo(r,s,n)});this._midlineIdx++,this._midlineIdx>=t.length&&(this.solved=!0)}getOutput(){return this.allSegments}getConstructorParams(){return[this.params]}visualize(){const{cellContents:t,midlines:e}=this.params,n=e[this._midlineIdx],o=Math.max(...this.allSegments.map(i=>i.distanceToAnyCell??0),1);return{rects:t.map(i=>({center:{x:i.x+i.width/2,y:i.y+i.height/2},width:i.width,height:i.height,fill:"rgba(255, 165, 0, 0.2)",stroke:"#c87000"})),lines:[...this.allSegments.map(i=>{const r=(i.distanceToAnyCell??0)/o,s=Math.round(255*(1-r)),a=Math.round(200*r);return{points:[i.start,i.end],strokeColor:`rgb(${s}, ${a}, 80)`,strokeWidth:1.5}}),...n?[{points:[n.start,n.end],strokeColor:"#2196f3",strokeWidth:2,strokeDash:[8,4]}]:[]]}}},QPt=t=>{const e=[];for(let n=0;n+1<t.length;n++){const o=t[n],i=t[n+1];o!==void 0&&i!==void 0&&e.push([o,i])}return e},_Bo=(t,e,n,o)=>{const i=t.x,r=t.y,s=e.x,a=e.y,A=n.x,c=n.y,l=o.x,u=o.y,g=(i-s)*(c-u)-(r-a)*(A-l);if(Math.abs(g)<1e-4)return!1;const h=((i-A)*(c-u)-(r-c)*(A-l))/g,d=-((i-s)*(r-c)-(r-a)*(i-A))/g;return h>=0&&h<=1&&d>=0&&d<=1},fBo=(t,e,n)=>{const{x:o,y:i,width:r,height:s}=n,a=t.x>=o&&t.x<=o+r&&t.y>=i&&t.y<=i+s,A=e.x>=o&&e.x<=o+r&&e.y>=i&&e.y<=i+s;if(a||A)return!0;const c=[{start:{x:o,y:i},end:{x:o+r,y:i}},{start:{x:o+r,y:i},end:{x:o+r,y:i+s}},{start:{x:o+r,y:i+s},end:{x:o,y:i+s}},{start:{x:o,y:i+s},end:{x:o,y:i}}];for(const l of c)if(_Bo(t,e,l.start,l.end))return!0;return!1},IBo=(t,e)=>t.x<e.x+e.width&&t.x+t.width>e.x&&t.y<e.y+e.height&&t.y+t.height>e.y,vPt=["rgba(100, 149, 237, 0.25)","rgba(144, 238, 144, 0.25)","rgba(255, 182, 193, 0.25)","rgba(221, 160, 221, 0.25)","rgba(255, 218, 185, 0.25)","rgba(175, 238, 238, 0.25)"],CBo=class extends z7{constructor(t){super(),this.params=t}params;validSegments=[];cellContainingRects=[];gridRects=[];_phase=0;_segIdx=0;_acceptedSegs=[];_rejectedSegs=[];_step(){const{allSegments:t,cellContents:e,containerWidth:n,containerHeight:o}=this.params;if(this._phase===0){if(this._segIdx>=t.length){this._phase=1;return}const u=t[this._segIdx];!e.some(h=>fBo(u.start,u.end,h))?this._acceptedSegs.push(u):this._rejectedSegs.push(u),this._segIdx++;return}const i=new Set([0,n]),r=new Set([0,o]);this._acceptedSegs.forEach(u=>{Math.abs(u.start.x-u.end.x)<.001?i.add(u.start.x):r.add(u.start.y)});const s=Array.from(i).sort((u,g)=>u-g),a=Array.from(r).sort((u,g)=>u-g),A=[];e.forEach(u=>{const g=s.filter(m=>m<=u.x).pop()??s[0],h=s.find(m=>m>=u.x+u.width)??s[s.length-1],d=a.filter(m=>m<=u.y).pop()??a[0],p=a.find(m=>m>=u.y+u.height)??a[a.length-1];A.push({cellId:`contain-${u.cellId}`,x:g,y:d,width:Math.max(0,h-g),height:Math.max(0,p-d)})});const c=[];let l=0;for(const[u,g]of QPt(s))if(!(g-u<=0))for(const[h,d]of QPt(a)){if(d-h<=0)continue;const p={cellId:`gridRect-${l++}`,x:u,y:h,width:g-u,height:d-h};e.some(m=>IBo(p,m))||c.push(p)}A.forEach(u=>{const g=`${u.x},${u.y},${u.width},${u.height}`;c.some(h=>`${h.x},${h.y},${h.width},${h.height}`===g)||c.push(u)}),this.validSegments=this._acceptedSegs,this.cellContainingRects=A,this.gridRects=c,this.solved=!0}getOutput(){return{validSegments:this.validSegments,cellContainingRects:this.cellContainingRects,gridRects:this.gridRects}}getConstructorParams(){return[this.params]}visualize(){const{cellContents:t,allSegments:e}=this.params,n=e[this._segIdx];return{rects:[...this.gridRects.map((o,i)=>({center:{x:o.x+o.width/2,y:o.y+o.height/2},width:o.width,height:o.height,fill:vPt[i%vPt.length],stroke:"#999999"})),...t.map(o=>({center:{x:o.x+o.width/2,y:o.y+o.height/2},width:o.width,height:o.height,fill:"rgba(255, 165, 0, 0.4)",stroke:"#c87000",label:o.cellId}))],lines:[...this._rejectedSegs.map(o=>({points:[o.start,o.end],strokeColor:"rgba(220, 50, 50, 0.35)",strokeDash:[3,3],strokeWidth:1})),...this._acceptedSegs.map(o=>({points:[o.start,o.end],strokeColor:"#2196f3",strokeWidth:1.5})),...n&&this._phase===0?[{points:[n.start,n.end],strokeColor:"#ff9800",strokeWidth:3}]:[],...this.validSegments.map(o=>({points:[o.start,o.end],strokeColor:"#2196f3",strokeWidth:2}))]}}},Ky=.001,yBo=(t,e,n=Ky)=>Math.abs(t.x-e.x)<n&&Math.abs(t.y-e.y)<n,xBo=(t,e)=>{const n=Math.max(t.x-(e.x+e.width),e.x-(t.x+t.width),0),o=Math.max(t.y-(e.y+e.height),e.y-(t.y+t.height),0);return n+o},EBo=(t,e,n=.5)=>{const o=(Math.abs(t.x+t.width-e.x)<n||Math.abs(e.x+e.width-t.x)<n)&&!(t.y+t.height<=e.y||e.y+e.height<=t.y),i=(Math.abs(t.y+t.height-e.y)<n||Math.abs(e.y+e.height-t.y)<n)&&!(t.x+t.width<=e.x||e.x+e.width<=t.x);return o||i},wPt=["rgba(100, 149, 237, 0.35)","rgba(144, 238, 144, 0.35)","rgba(255, 182, 193, 0.35)","rgba(221, 160, 221, 0.35)","rgba(255, 218, 185, 0.35)","rgba(175, 238, 238, 0.35)","rgba(250, 200, 100, 0.35)","rgba(180, 220, 180, 0.35)"],PPt=["#6495ed","#3cb371","#ff69b4","#9370db","#ffa07a","#20b2aa","#daa520","#5f9e5f"],BBo=class extends z7{constructor(t){super(),this.params=t}params;mergedRectGroups=[];groupedRects=[];_phase=0;_workRects=[];_unmergedQueue=[];_step(){const{validSegments:t,gridRects:e,cellContainingRects:n,cellContents:o}=this.params;if(this._phase===0){this._workRects=e.map(s=>{let a=1/0;const{x:A,y:c,width:l,height:u}=s;return t.forEach(g=>{const h=Math.min(g.start.x,g.end.x),d=Math.max(g.start.x,g.end.x),p=Math.min(g.start.y,g.end.y),m=Math.max(g.start.y,g.end.y),_=Math.abs(g.start.y-g.end.y)<Ky,f=Math.abs(g.start.x-g.end.x)<Ky;let I=!1;_?(Math.abs(p-c)<Ky||Math.abs(p-(c+u))<Ky)&&h<A+l-Ky&&d>A+Ky&&Math.max(h,A)+Ky<Math.min(d,A+l)&&(I=!0):f&&(Math.abs(h-A)<Ky||Math.abs(h-(A+l))<Ky)&&p<c+u-Ky&&m>c+Ky&&Math.max(p,c)+Ky<Math.min(m,c+u)&&(I=!0),I&&g.distanceToAnyCell!==void 0&&(a=Math.min(a,g.distanceToAnyCell))}),{...s,merged:!1,groupId:null,minBoundingSegmentDistance:a}}),n.forEach((s,a)=>{const A=this._workRects.find(c=>yBo({x:c.x,y:c.y},{x:s.x,y:s.y})&&Math.abs(c.width-s.width)<Ky&&Math.abs(c.height-s.height)<Ky);A&&(A.merged=!0,A.groupId=a)}),this._unmergedQueue=this._workRects.filter(s=>!s.merged).sort((s,a)=>s.minBoundingSegmentDistance-a.minBoundingSegmentDistance),this._updateOutput(),this._phase=1;return}if(this._unmergedQueue.length===0){this._finalize(),this.solved=!0;return}let i=!1;const r=[];for(const s of this._unmergedQueue){const a=this._workRects.find(c=>c.cellId===s.cellId);if(!a||a.merged)continue;const A=this._workRects.filter(c=>c.merged&&EBo(a,c));if(A.length>0&&!i){if(a.merged=!0,A.length===1)a.groupId=A[0].groupId;else{let c=null,l=1/0;for(const u of A){if(u.groupId===null)continue;const g=o[u.groupId];if(!g)continue;const h=xBo(a,g);(h<l||h===l&&(c===null||u.groupId!==null&&u.groupId<c))&&(l=h,c=u.groupId)}a.groupId=c}i=!0}else r.push(s)}this._unmergedQueue=r.sort((s,a)=>s.minBoundingSegmentDistance-a.minBoundingSegmentDistance),i||(this._finalize(),this.solved=!0),this._updateOutput()}_updateOutput(){this.groupedRects=this._workRects.filter(t=>t.groupId!==null)}_finalize(){const{cellContainingRects:t,cellContents:e}=this.params;this.mergedRectGroups=[],t.forEach((n,o)=>{const i=this._workRects.filter(s=>s.merged&&s.groupId===o).map(({merged:s,groupId:a,minBoundingSegmentDistance:A,...c})=>c),r=e[o];r&&this.mergedRectGroups.push([n,r,...i.filter(s=>s.cellId!==n.cellId)])})}getOutput(){return{mergedRectGroups:this.mergedRectGroups,groupedRects:this.groupedRects}}getConstructorParams(){return[this.params]}visualize(){const{cellContents:t}=this.params;return{rects:[...this.groupedRects.map(e=>({center:{x:e.x+e.width/2,y:e.y+e.height/2},width:e.width,height:e.height,fill:wPt[e.groupId%wPt.length],stroke:PPt[e.groupId%PPt.length]})),...this._workRects.filter(e=>!e.merged).map(e=>({center:{x:e.x+e.width/2,y:e.y+e.height/2},width:e.width,height:e.height,fill:"rgba(200, 200, 200, 0.2)",stroke:"#aaaaaa",strokeDash:[3,3]})),...t.map(e=>({center:{x:e.x+e.width/2,y:e.y+e.height/2},width:e.width,height:e.height,fill:"rgba(255, 165, 0, 0.5)",stroke:"#c87000",label:e.cellId}))]}}},bBo=.001,MPt=(t,e)=>{const n=parseFloat(t.x.toFixed(4)),o=parseFloat(t.y.toFixed(4)),i=parseFloat(e.x.toFixed(4)),r=parseFloat(e.y.toFixed(4));return n<i||n===i&&o<r?`${n},${o}_${i},${r}`:`${i},${r}_${n},${o}`},DPt=["rgba(100, 149, 237, 0.25)","rgba(144, 238, 144, 0.25)","rgba(255, 182, 193, 0.25)","rgba(221, 160, 221, 0.25)","rgba(255, 218, 185, 0.25)","rgba(175, 238, 238, 0.25)","rgba(250, 200, 100, 0.25)","rgba(180, 220, 180, 0.25)"],SBo=class extends z7{constructor(t){super(),this.params=t}params;outlineLines=[];_outerIdx=0;_segMap=new Map;_step(){const{groupedRects:t}=this.params,e=bBo;if(this._outerIdx>=t.length){this._rebuildLines(),this.solved=!0;return}const n=t[this._outerIdx];for(const o of t.slice(this._outerIdx+1)){if(n.groupId===o.groupId)continue;const i=n.x+n.width,r=o.x+o.width;if(Math.abs(i-o.x)<e||Math.abs(r-n.x)<e){const A=Math.abs(i-o.x)<e?i:r,c=Math.max(n.y,o.y),l=Math.min(n.y+n.height,o.y+o.height);if(l-c>e){const u={x:A,y:c},g={x:A,y:l};this._segMap.set(MPt(u,g),{start:u,end:g})}}const s=n.y+n.height,a=o.y+o.height;if(Math.abs(s-o.y)<e||Math.abs(a-n.y)<e){const A=Math.abs(s-o.y)<e?s:a,c=Math.max(n.x,o.x),l=Math.min(n.x+n.width,o.x+o.width);if(l-c>e){const u={x:c,y:A},g={x:l,y:A};this._segMap.set(MPt(u,g),{start:u,end:g})}}}this._outerIdx++,this._rebuildLines(),this._outerIdx>=t.length&&(this.solved=!0)}_rebuildLines(){let t=0;this.outlineLines=[],this._segMap.forEach(({start:e,end:n})=>{this.outlineLines.push({id:`outline-${t++}`,start:e,end:n})})}getOutput(){return this.outlineLines}getConstructorParams(){return[this.params]}visualize(){const{groupedRects:t}=this.params,e=t[this._outerIdx];return{rects:t.map(n=>({center:{x:n.x+n.width/2,y:n.y+n.height/2},width:n.width,height:n.height,fill:n===e?"rgba(255, 152, 0, 0.45)":DPt[n.groupId%DPt.length],stroke:n===e?"#ff6600":"#cccccc"})),lines:this.outlineLines.map(n=>({points:[n.start,n.end],strokeColor:"#000000",strokeWidth:3}))}}},Zi=.001,Aw=(t,e,n=Zi)=>Math.abs(t.x-e.x)<n&&Math.abs(t.y-e.y)<n,Z5=t=>`${t.x.toFixed(4)},${t.y.toFixed(4)}`,g0e=(t,e)=>{const n=Z5(t),o=Z5(e);return n<o?`${n}_${o}`:`${o}_${n}`},Mj=t=>Aw(t.start,t.end),QBo=t=>Math.abs(t.start.x-t.end.x)<Zi||Math.abs(t.start.y-t.end.y)<Zi,cw=(t,e,n,o)=>Math.min(e,o)-Math.max(t,n)>Zi,aO=t=>t.reduce((e,n)=>e+Math.abs(n.start.x-n.end.x)+Math.abs(n.start.y-n.end.y),0),am=(t,e)=>Math.abs(t.start.x-t.end.x)<Zi?Math.abs(e.x-t.start.x)<Zi&&e.y>=Math.min(t.start.y,t.end.y)-Zi&&e.y<=Math.max(t.start.y,t.end.y)+Zi:Math.abs(t.start.y-t.end.y)<Zi?Math.abs(e.y-t.start.y)<Zi&&e.x>=Math.min(t.start.x,t.end.x)-Zi&&e.x<=Math.max(t.start.x,t.end.x)+Zi:!1,d0e=(t,e,n)=>e==="start"?{start:n,end:t.end}:{start:t.start,end:n},NPt=t=>{const e=new Map;for(const n of t)e.set(Z5(n.start),(e.get(Z5(n.start))??0)+1),e.set(Z5(n.end),(e.get(Z5(n.end))??0)+1);return e},vBo=(t,e)=>e.some(n=>{const o=(Math.abs(t.x-n.minX)<Zi||Math.abs(t.x-n.maxX)<Zi)&&t.y>=n.minY-Zi&&t.y<=n.maxY+Zi,i=(Math.abs(t.y-n.minY)<Zi||Math.abs(t.y-n.maxY)<Zi)&&t.x>=n.minX-Zi&&t.x<=n.maxX+Zi;return o||i}),wBo=(t,e)=>{const n=t.start.x,o=t.start.y,i=t.end.x,r=t.end.y;if(Math.abs(n-i)<Zi){const s=Math.min(o,r),a=Math.max(o,r);return n>e.minX+Zi&&n<e.maxX-Zi&&a>e.minY-Zi&&s<e.maxY+Zi}if(Math.abs(o-r)<Zi){const s=Math.min(n,i),a=Math.max(n,i);return o>e.minY+Zi&&o<e.maxY-Zi&&a>e.minX+Zi&&s<e.maxX-Zi}return!0},PBo=(t,e)=>{const n=t.start.x,o=t.start.y,i=t.end.x,r=t.end.y;if(Math.abs(n-i)<Zi){const s=Math.min(o,r),a=Math.max(o,r);return(Math.abs(n-e.minX)<Zi||Math.abs(n-e.maxX)<Zi)&&cw(s,a,e.minY,e.maxY)}if(Math.abs(o-r)<Zi){const s=Math.min(n,i),a=Math.max(n,i);return(Math.abs(o-e.minY)<Zi||Math.abs(o-e.maxY)<Zi)&&cw(s,a,e.minX,e.maxX)}return!1},Dj=(t,e)=>t.length>0&&t.every(n=>!Mj(n)&&QBo(n)&&!e.some(o=>wBo(n,o)||PBo(n,o))),MBo=(t,e)=>{if(Math.abs(t.start.x-t.end.x)<Zi){const n=t.start.x,o=Math.min(t.start.y,t.end.y),i=Math.max(t.start.y,t.end.y);return e.some(r=>r.maxX<=n+Zi&&cw(o,i,r.minY,r.maxY)&&e.some(s=>s.minX>=n-Zi&&cw(o,i,s.minY,s.maxY)&&cw(r.minY,r.maxY,s.minY,s.maxY)))}if(Math.abs(t.start.y-t.end.y)<Zi){const n=t.start.y,o=Math.min(t.start.x,t.end.x),i=Math.max(t.start.x,t.end.x);return e.some(r=>r.maxY<=n+Zi&&cw(o,i,r.minX,r.maxX)&&e.some(s=>s.minY>=n-Zi&&cw(o,i,s.minX,s.maxX)&&cw(r.minX,r.maxX,s.minX,s.maxX)))}return!1},AO=t=>{const e=new Map,n=t.map(s=>[s.start,s.end]),o=(s,a)=>{const A=Z5(s),c=Z5(a);e.has(A)||e.set(A,new Set),e.has(c)||e.set(c,new Set),e.get(A)?.add(c),e.get(c)?.add(A)};for(let s=0;s<t.length;s++){const a=t[s];if(!(!a||Mj(a)))for(let A=s+1;A<t.length;A++){const c=t[A];if(!c||Mj(c))continue;const l=Math.abs(a.start.x-a.end.x)<Zi,u=Math.abs(a.start.y-a.end.y)<Zi,g=Math.abs(c.start.x-c.end.x)<Zi,h=Math.abs(c.start.y-c.end.y)<Zi;if(l&&h){const d={x:a.start.x,y:c.start.y};am(a,d)&&am(c,d)&&(n[s]?.push(d),n[A]?.push(d))}if(u&&g){const d={x:c.start.x,y:a.start.y};am(a,d)&&am(c,d)&&(n[s]?.push(d),n[A]?.push(d))}}}for(let s=0;s<t.length;s++){const a=t[s];if(!a||Mj(a))continue;const A=[...new Map(n[s]?.map(c=>[Z5(c),c]))].map(([,c])=>c).sort((c,l)=>Math.abs(a.start.x-a.end.x)<Zi?c.y-l.y:c.x-l.x);for(let c=0;c+1<A.length;c++){const l=A[c],u=A[c+1];l&&u&&!Aw(l,u)&&o(l,u)}}let i=0;const r=new Set;for(const s of e.keys()){if(r.has(s))continue;i++;const a=[s];for(r.add(s);a.length>0;){const A=a.pop();if(A)for(const c of e.get(A)??[])r.has(c)||(r.add(c),a.push(c))}}return i},DBo=(t,e,n)=>{let o=t,i=!0;for(;i;){i=!1;const r=NPt(o);for(let s=0;s<o.length;s++){const a=o[s];if(a){for(const A of["start","end"]){const c=a[A];if(r.get(Z5(c))!==1)continue;const l=[],u=Math.abs(a.start.x-a.end.x)<Zi,g=Math.abs(a.start.y-a.end.y)<Zi;for(let d=0;d<o.length;d++){if(s===d)continue;const p=o[d];if(p){if(u&&Math.abs(p.start.y-p.end.y)<Zi){const m={x:a.start.x,y:p.start.y};am(p,m)&&l.push(m)}if(g&&Math.abs(p.start.x-p.end.x)<Zi){const m={x:p.start.x,y:a.start.y};am(p,m)&&l.push(m)}}}const h=l.filter(d=>!Aw(d,c)).map(d=>({point:d,line:d0e(a,A,d)})).filter(({line:d})=>aO([d])>aO([a])+Zi).filter(({line:d})=>!0).filter(({line:d})=>Dj([d],e)).sort((d,p)=>aO([d.line])-aO([p.line])||JSON.stringify(d.point).localeCompare(JSON.stringify(p.point))).at(0);if(h){o=o.map((d,p)=>p===s?h.line:d),i=!0;break}}if(i)break}}}return o},NBo=(t,e)=>{const n=[],o=Math.abs(t.start.x-t.end.x)<Zi,i=Math.abs(t.start.y-t.end.y)<Zi;for(const r of e){if(r===t)continue;const s=Math.abs(r.start.x-r.end.x)<Zi,a=Math.abs(r.start.y-r.end.y)<Zi;if(o&&a){const A={x:t.start.x,y:r.start.y};am(t,A)&&am(r,A)&&n.push(A)}if(i&&s){const A={x:r.start.x,y:t.start.y};am(t,A)&&am(r,A)&&n.push(A)}}return n},RBo=(t,e,n)=>{let o=t,i=!0;for(;i;){i=!1;const r=NPt(o),s=AO(o);for(let a=0;a<o.length;a++){const A=o[a];if(!A)continue;const c=NBo(A,o).filter(l=>!Aw(l,A.start)&&!Aw(l,A.end));if(c.length!==0){for(const l of["start","end"]){const u=A[l];if(r.get(Z5(u))!==1||vBo(u,e))continue;const g=c.map(m=>({point:m,distance:Math.abs(m.x-u.x)+Math.abs(m.y-u.y)})).sort((m,_)=>m.distance-_.distance).at(0);if(!g)continue;const h={start:u,end:g.point};if(MBo(h,e))continue;const d=d0e(A,l,g.point);if(!Dj([d],e))continue;const p=o.map((m,_)=>_===a?d:m);if(!(AO(p)>s)){o=p,i=!0;break}}if(i)break}}}return o},TBo=t=>{let{start:e,end:n}=t;return e.y===n.y&&e.x>n.x?[e,n]=[{x:n.x,y:e.y},{x:e.x,y:n.y}]:e.x===n.x&&e.y>n.y&&([e,n]=[{x:e.x,y:n.y},{x:n.x,y:e.y}]),{start:e,end:n}},Qwe=t=>{if(!t||t.length===0)return[];const e=t.map(TBo),n=[],o=[];for(const a of e)a.start.y===a.end.y?n.push(a):a.start.x===a.end.x&&o.push(a);const i=[],r=new Map;for(const a of n){const A=r.get(a.start.y)??[];A.push(a),r.set(a.start.y,A)}for(const[,a]of r){a.sort((c,l)=>c.start.x-l.start.x);let A;for(const c of a){if(!A){A={...c};continue}c.start.x<=A.end.x?A.end.x=Math.max(A.end.x,c.end.x):(i.push(A),A={...c})}A&&i.push(A)}const s=new Map;for(const a of o){const A=s.get(a.start.x)??[];A.push(a),s.set(a.start.x,A)}for(const[,a]of s){a.sort((c,l)=>c.start.y-l.start.y);let A;for(const c of a){if(!A){A={...c};continue}c.start.y<=A.end.y?A.end.y=Math.max(A.end.y,c.end.y):(i.push(A),A={...c})}A&&i.push(A)}return i},Nj=t=>{const e=[];for(let n=0;n+1<t.length;n++){const o=t[n],i=t[n+1];!o||!i||Aw(o,i)||e.push({start:o,end:i})}return e},kBo=(t,e)=>{const n=Nj(t),o=t.at(0),i=t.at(-1);if(!o||!i||n.length<2)return n;const r=[];Math.abs(o.x-i.x)<Zi||Math.abs(o.y-i.y)<Zi?r.push([{start:o,end:i}]):r.push(Nj([o,{x:o.x,y:i.y},i]),Nj([o,{x:i.x,y:o.y},i]));const s=[...new Set(t.map(c=>c.x))],a=[...new Set(t.map(c=>c.y))];for(const c of s)Math.abs(c-o.x)<Zi||Math.abs(c-i.x)<Zi||r.push(Nj([o,{x:c,y:o.y},{x:c,y:i.y},i]));for(const c of a)Math.abs(c-o.y)<Zi||Math.abs(c-i.y)<Zi||r.push(Nj([o,{x:o.x,y:c},{x:i.x,y:c},i]));return r.filter(c=>c.length<n.length).filter(c=>Dj(c,e)).sort((c,l)=>c.length-l.length||aO(c)-aO(l)||JSON.stringify(c).localeCompare(JSON.stringify(l))).at(0)??n},FBo=(t,e)=>{const n=new Map,o=new Map,i=a=>{const A=Z5(a);return n.set(A,a),o.has(A)||o.set(A,new Set),A};for(const a of t){if(Mj(a))continue;const A=i(a.start),c=i(a.end);o.get(A)?.add(c),o.get(c)?.add(A)}const r=new Set,s=[];for(const[a,A]of o)if(A.size!==2)for(const c of A){const l=g0e(n.get(a),n.get(c));if(r.has(l))continue;const u=[n.get(a)];let g=a,h=c;for(;;){r.add(g0e(n.get(g),n.get(h))),u.push(n.get(h));const d=o.get(h);if(!d||d.size!==2)break;const p=[...d].find(_=>_!==g);if(!p)break;const m=g0e(n.get(h),n.get(p));if(r.has(m))break;g=h,h=p}s.push(...kBo(u,e))}for(const[a,A]of o)for(const c of A){const l=g0e(n.get(a),n.get(c));r.has(l)||(r.add(l),s.push({start:n.get(a),end:n.get(c)}))}return s},LBo=(t,e)=>{let n=t,o=!0;for(;o;){o=!1;const i=AO(n),r=Qwe(n).length;for(let s=0;s<n.length;s++){const a=n[s];if(!a)continue;const A=Math.abs(a.start.x-a.end.x)<Zi,c=Math.abs(a.start.y-a.end.y)<Zi;if(!(!A&&!c)){for(let l=0;l<n.length;l++){if(s===l)continue;const u=n[l];if(!u)continue;const g=Math.abs(u.start.x-u.end.x)<Zi,h=Math.abs(u.start.y-u.end.y)<Zi;if(A!==g||c!==h||A&&Math.abs(a.start.x-u.start.x)<Zi||c&&Math.abs(a.start.y-u.start.y)<Zi||!n.some((f,I)=>I===s||I===l?!1:A&&Math.abs(f.start.y-f.end.y)<Zi?am(f,{x:a.start.x,y:f.start.y})&&am(a,{x:a.start.x,y:f.start.y})&&am(f,{x:u.start.x,y:f.start.y})&&am(u,{x:u.start.x,y:f.start.y}):c&&Math.abs(f.start.x-f.end.x)<Zi?am(f,{x:f.start.x,y:a.start.y})&&am(a,{x:f.start.x,y:a.start.y})&&am(f,{x:f.start.x,y:u.start.y})&&am(u,{x:f.start.x,y:u.start.y}):!1))continue;let p;if(A?p={start:{x:u.start.x,y:a.start.y},end:{x:u.start.x,y:a.end.y}}:p={start:{x:a.start.x,y:u.start.y},end:{x:a.end.x,y:u.start.y}},!Dj([p],e))continue;const m=n.map((f,I)=>I===s?p:f);if(AO(m)>i)continue;const _=Qwe(m);if(!(_.length>=r)){n=_,o=!0;break}}if(o)break}}}return n},HBo=(t,e)=>{let n=t,o=!0;for(;o;){o=!1;const i=AO(n);for(let r=0;r<n.length;r++){const s=n[r];if(!s)continue;const a=Math.abs(s.start.y-s.end.y)<Zi,A=Math.abs(s.start.x-s.end.x)<Zi;if(!(!a&&!A)){for(let c=0;c<n.length;c++){if(r===c)continue;const l=n[c];if(!l)continue;const u=Math.abs(l.start.y-l.end.y)<Zi,g=Math.abs(l.start.x-l.end.x)<Zi;if(a!==u||A!==g)continue;const h=[s.start,s.end];let d;if(a?d=h.map(f=>({x:f.x,y:l.start.y})):d=h.map(f=>({x:l.start.x,y:f.y})),!d.every(f=>am(l,f)))continue;const p=new Map;let m=!0;for(let f=0;f<h.length;f++){const I=h[f],C=d[f];if(!I||!C){m=!1;break}const y=n.findIndex((Q,w)=>{if(w===r||w===c)return!1;const M=Math.abs(Q.start.y-Q.end.y)<Zi,k=Math.abs(Q.start.x-Q.end.x)<Zi;return(a&&k||A&&M)&&am(Q,I)});if(y===-1)continue;const x=n[y];if(!x){m=!1;break}const E=Aw(x.start,I),B=Aw(x.end,I);if(!E&&!B&&am(x,C))continue;if(!E&&!B){m=!1;break}let S;if(E?S=d0e(x,"start",C):S=d0e(x,"end",C),!Dj([S],e)){m=!1;break}p.set(y,S)}if(!m)continue;const _=n.map((f,I)=>p.get(I)??f).filter((f,I)=>I!==r);if(!(AO(_)>i)){n=_,o=!0;break}}if(o)break}}}return n},RPt=(t=>(t[t.MergeAlignedSegments=0]="MergeAlignedSegments",t[t.SimplifyChains=1]="SimplifyChains",t[t.ConnectDanglingEndpoints=2]="ConnectDanglingEndpoints",t[t.AlignParallelLinesAcrossConnectors=3]="AlignParallelLinesAcrossConnectors",t[t.RemoveRedundantParallelBridges=4]="RemoveRedundantParallelBridges",t[t.TrimDanglingOverhangs=5]="TrimDanglingOverhangs",t))(RPt||{}),OBo=class extends z7{constructor(t){super(),this.params=t;const e=t.offsetX??0,n=t.offsetY??0;this._inputRects=t.cellContents.map(o=>({minX:o.x+e,minY:o.y+n,maxX:o.x+o.width+e,maxY:o.y+o.height+n}))}params;mergedOriginalLines=[];reducedLines=[];_stage=0;_currentLines=[];_inputRects;_step(){const{outlineLines:t}=this.params,e=this.params.offsetX??0,n=this.params.offsetY??0,o=this._inputRects;switch(this._stage){case 0:{const r=Qwe(t.map(s=>({start:{x:s.start.x+e,y:s.start.y+n},end:{x:s.end.x+e,y:s.end.y+n}})));this._currentLines=r,this.mergedOriginalLines=r.map(s=>({start:{x:s.start.x,y:s.start.y},end:{x:s.end.x,y:s.end.y}}));break}case 1:this._currentLines=FBo(this._currentLines,o);break;case 2:this._currentLines=DBo(this._currentLines,o);break;case 3:this._currentLines=LBo(this._currentLines,o);break;case 4:this._currentLines=HBo(this._currentLines,o);break;case 5:this._currentLines=RBo(this._currentLines,o),this.reducedLines=this._currentLines.map(r=>({start:{x:r.start.x-e,y:r.start.y-n},end:{x:r.end.x-e,y:r.end.y-n}})),this.mergedOriginalLines=this.mergedOriginalLines.map(r=>({start:{x:r.start.x-e,y:r.start.y-n},end:{x:r.end.x-e,y:r.end.y-n}})),this.solved=!0;break}const i=this.getNextStage(this._stage);i&&(this._stage=i)}getNextStage(t){const e=Object.values(RPt);return e[e.indexOf(t)+1]}getOutput(){return this.reducedLines}getConstructorParams(){return[this.params]}visualize(){const{cellContents:t,outlineLines:e}=this.params;return{rects:t.map(n=>({center:{x:n.x+n.width/2,y:n.y+n.height/2},width:n.width,height:n.height,fill:"rgba(255, 165, 0, 0.2)",stroke:"#c87000"})),lines:[...e.map(n=>({points:[n.start,n.end],strokeColor:"rgba(180, 180, 180, 0.4)",strokeWidth:1,strokeDash:[4,4]})),...this._currentLines.map(n=>({points:[n.start,n.end],strokeColor:"#0055cc",strokeWidth:2}))]}}},vs=.001,TPt=(t,e,n=vs)=>Math.abs(t.x-e.x)<n&&Math.abs(t.y-e.y)<n,vwe=t=>`${t.x.toFixed(4)},${t.y.toFixed(4)}`,h0e=t=>TPt(t.start,t.end),GBo=t=>Math.abs(t.start.x-t.end.x)<vs||Math.abs(t.start.y-t.end.y)<vs,cO=(t,e,n,o)=>Math.min(e,o)-Math.max(t,n)>vs,p0e=t=>t.reduce((e,n)=>e+Math.abs(n.start.x-n.end.x)+Math.abs(n.start.y-n.end.y),0),m0e=(t,e)=>Math.abs(t.start.x-t.end.x)<vs?Math.abs(e.x-t.start.x)<vs&&e.y>=Math.min(t.start.y,t.end.y)-vs&&e.y<=Math.max(t.start.y,t.end.y)+vs:Math.abs(t.start.y-t.end.y)<vs?Math.abs(e.y-t.start.y)<vs&&e.x>=Math.min(t.start.x,t.end.x)-vs&&e.x<=Math.max(t.start.x,t.end.x)+vs:!1,Rj=t=>({x:(t.minX+t.maxX)/2,y:(t.minY+t.maxY)/2}),kPt=(t,e,n)=>t>Math.min(e,n)+vs&&t<Math.max(e,n)-vs,YBo=(t,e)=>{const n=t.start.x,o=t.start.y,i=t.end.x,r=t.end.y;if(Math.abs(n-i)<vs){const s=Math.min(o,r),a=Math.max(o,r);return n>e.minX+vs&&n<e.maxX-vs&&a>e.minY-vs&&s<e.maxY+vs}if(Math.abs(o-r)<vs){const s=Math.min(n,i),a=Math.max(n,i);return o>e.minY+vs&&o<e.maxY-vs&&a>e.minX+vs&&s<e.maxX-vs}return!0},UBo=(t,e)=>{const n=t.start.x,o=t.start.y,i=t.end.x,r=t.end.y;if(Math.abs(n-i)<vs){const s=Math.min(o,r),a=Math.max(o,r);return(Math.abs(n-e.minX)<vs||Math.abs(n-e.maxX)<vs)&&cO(s,a,e.minY,e.maxY)}if(Math.abs(o-r)<vs){const s=Math.min(n,i),a=Math.max(n,i);return(Math.abs(o-e.minY)<vs||Math.abs(o-e.maxY)<vs)&&cO(s,a,e.minX,e.maxX)}return!1},wwe=(t,e)=>t.length>0&&t.every(n=>!h0e(n)&&GBo(n)&&!e.some(o=>YBo(n,o)||UBo(n,o))),FPt=(t,e,n)=>{const o=Rj(e),i=Rj(n);if(Math.abs(t.start.x-t.end.x)<vs){const r=t.start.x,s=Math.min(t.start.y,t.end.y),a=Math.max(t.start.y,t.end.y);return kPt(r,o.x,i.x)&&cO(s,a,e.minY,e.maxY)&&cO(s,a,n.minY,n.maxY)}if(Math.abs(t.start.y-t.end.y)<vs){const r=t.start.y,s=Math.min(t.start.x,t.end.x),a=Math.max(t.start.x,t.end.x);return kPt(r,o.y,i.y)&&cO(s,a,e.minX,e.maxX)&&cO(s,a,n.minX,n.maxX)}return!1},_0e=(t,e)=>{const n=new Set;for(let o=0;o<e.length;o++){const i=e[o];if(i)for(let r=o+1;r<e.length;r++){const s=e[r];s&&t.some(a=>FPt(a,i,s))&&n.add(`${o}:${r}`)}}return n},KBo=(t,e,n)=>{const o=_0e(t,e);return[...n].every(i=>o.has(i))},LPt=(t,e)=>{const n=new Set,o=new Set;for(const i of e)n.add(i.minX),n.add(i.maxX),n.add(Rj(i).x),o.add(i.minY),o.add(i.maxY),o.add(Rj(i).y);for(const i of t)n.add(i.start.x),n.add(i.end.x),o.add(i.start.y),o.add(i.end.y);return{xs:[...n].sort((i,r)=>i-r),ys:[...o].sort((i,r)=>i-r)}},VBo=(t,e,n,o)=>t.some(i=>{if(Math.abs(i.start.x-i.end.x)>=vs||Math.abs(i.start.x-e)>=vs)return!1;const r=Math.min(i.start.y,i.end.y),s=Math.max(i.start.y,i.end.y);return n>=r-vs&&o<=s+vs}),zBo=(t,e,n,o)=>t.some(i=>{if(Math.abs(i.start.y-i.end.y)>=vs||Math.abs(i.start.y-e)>=vs)return!1;const r=Math.min(i.start.x,i.end.x),s=Math.max(i.start.x,i.end.x);return n>=r-vs&&o<=s+vs}),JBo=(t,e)=>{const{xs:n,ys:o}=LPt(t,e),i=n.length-1,r=o.length-1,s=new Map,a=(c,l)=>`${c}:${l}`;let A=0;for(let c=0;c<i;c++)for(let l=0;l<r;l++){const u=a(c,l);if(s.has(u))continue;const g=[{x:c,y:l}];for(s.set(u,A);g.length>0;){const h=g.pop();if(!h)continue;const d=[{x:h.x-1,y:h.y},{x:h.x+1,y:h.y},{x:h.x,y:h.y-1},{x:h.x,y:h.y+1}];for(const p of d){if(p.x<0||p.x>=i||p.y<0||p.y>=r)continue;const m=a(p.x,p.y);if(s.has(m))continue;let _=!1;if(p.x!==h.x){const f=n[Math.max(p.x,h.x)],I=o[h.y],C=o[h.y+1];if(f===void 0||I===void 0||C===void 0)continue;_=VBo(t,f,I,C)}else{const f=o[Math.max(p.y,h.y)],I=n[h.x],C=n[h.x+1];if(f===void 0||I===void 0||C===void 0)continue;_=zBo(t,f,I,C)}_||(s.set(m,A),g.push(p))}}A++}return e.map(c=>{const l=Rj(c),u=n.findIndex((h,d)=>d+1<n.length&&l.x>=h-vs&&l.x<=(n[d+1]??h)+vs),g=o.findIndex((h,d)=>d+1<o.length&&l.y>=h-vs&&l.y<=(o[d+1]??h)+vs);return s.get(a(u,g))??-1})},f0e=(t,e)=>{const n=JBo(t,e);let o=0;for(let i=0;i<n.length;i++)for(let r=i+1;r<n.length;r++)n[i]===n[r]&&o++;return o},HPt=t=>{const e=new Map,n=t.map(s=>[s.start,s.end]),o=(s,a)=>{const A=vwe(s),c=vwe(a);e.has(A)||e.set(A,new Set),e.has(c)||e.set(c,new Set),e.get(A)?.add(c),e.get(c)?.add(A)};for(let s=0;s<t.length;s++){const a=t[s];if(!(!a||h0e(a)))for(let A=s+1;A<t.length;A++){const c=t[A];if(!c||h0e(c))continue;const l=Math.abs(a.start.x-a.end.x)<vs,u=Math.abs(a.start.y-a.end.y)<vs,g=Math.abs(c.start.x-c.end.x)<vs,h=Math.abs(c.start.y-c.end.y)<vs;if(l&&h){const d={x:a.start.x,y:c.start.y};m0e(a,d)&&m0e(c,d)&&(n[s]?.push(d),n[A]?.push(d))}if(u&&g){const d={x:c.start.x,y:a.start.y};m0e(a,d)&&m0e(c,d)&&(n[s]?.push(d),n[A]?.push(d))}}}for(let s=0;s<t.length;s++){const a=t[s];if(!a||h0e(a))continue;const A=[...new Map(n[s]?.map(c=>[vwe(c),c]))].map(([,c])=>c).sort((c,l)=>Math.abs(a.start.x-a.end.x)<vs?c.y-l.y:c.x-l.x);for(let c=0;c+1<A.length;c++){const l=A[c],u=A[c+1];l&&u&&!TPt(l,u)&&o(l,u)}}let i=0;const r=new Set;for(const s of e.keys()){if(r.has(s))continue;i++;const a=[s];for(r.add(s);a.length>0;){const A=a.pop();if(A)for(const c of e.get(A)??[])r.has(c)||(r.add(c),a.push(c))}}return i},WBo=t=>{let{start:e,end:n}=t;return e.y===n.y&&e.x>n.x?[e,n]=[{x:n.x,y:e.y},{x:e.x,y:n.y}]:e.x===n.x&&e.y>n.y&&([e,n]=[{x:e.x,y:n.y},{x:n.x,y:e.y}]),{start:e,end:n}},OPt=t=>{if(!t||t.length===0)return[];const e=t.map(WBo),n=[],o=[];for(const a of e)a.start.y===a.end.y?n.push(a):a.start.x===a.end.x&&o.push(a);const i=[],r=new Map;for(const a of n){const A=r.get(a.start.y)??[];A.push(a),r.set(a.start.y,A)}for(const[,a]of r){a.sort((c,l)=>c.start.x-l.start.x);let A;for(const c of a){if(!A){A={...c};continue}c.start.x<=A.end.x?A.end.x=Math.max(A.end.x,c.end.x):(i.push(A),A={...c})}A&&i.push(A)}const s=new Map;for(const a of o){const A=s.get(a.start.x)??[];A.push(a),s.set(a.start.x,A)}for(const[,a]of s){a.sort((c,l)=>c.start.y-l.start.y);let A;for(const c of a){if(!A){A={...c};continue}c.start.y<=A.end.y?A.end.y=Math.max(A.end.y,c.end.y):(i.push(A),A={...c})}A&&i.push(A)}return i},jBo=(t,e,n,o)=>{let i=t;for(;;){const r=_0e(i,n),s=[...o].find(g=>!r.has(g));if(!s)break;const[a,A]=s.split(":"),c=n[Number(a)],l=n[Number(A)];if(!c||!l)break;const u=e.filter(g=>FPt(g,c,l)).sort((g,h)=>p0e([g])-p0e([h])||JSON.stringify(g).localeCompare(JSON.stringify(h))).at(0);if(!u)break;i=OPt([...i,u])}return i},$Bo=(t,e,n)=>{let o=t;for(;;){const i=f0e(o,n);if(i===0)break;const{xs:r,ys:s}=LPt(o,n),a=[];for(let c=0;c<o.length;c++){const l=o[c];if(l){if(Math.abs(l.start.y-l.end.y)<vs){const u=Math.min(l.start.x,l.end.x),g=Math.max(l.start.x,l.end.x);for(const h of r){if(h>=u-vs&&h<=g+vs)continue;const d={start:{x:Math.min(h,u),y:l.start.y},end:{x:Math.max(h,g),y:l.start.y}};wwe([d],n)&&a.push(o.map((p,m)=>m===c?d:p))}}if(Math.abs(l.start.x-l.end.x)<vs){const u=Math.min(l.start.y,l.end.y),g=Math.max(l.start.y,l.end.y);for(const h of s){if(h>=u-vs&&h<=g+vs)continue;const d={start:{x:l.start.x,y:Math.min(h,u)},end:{x:l.start.x,y:Math.max(h,g)}};wwe([d],n)&&a.push(o.map((p,m)=>m===c?d:p))}}}}for(const c of e)a.push([...o,c]);const A=a.map(c=>({lines:OPt(c),shared:f0e(c,n)})).filter(c=>c.shared<i).sort((c,l)=>c.shared-l.shared||c.lines.length-l.lines.length||p0e(c.lines)-p0e(l.lines)).at(0);if(!A)break;o=A.lines}return o},qBo=(t,e)=>{let n=t,o=!0;for(;o;){o=!1;const i=_0e(n,e),r=f0e(n,e),s=HPt(n);for(let a=0;a<n.length;a++){const A=n.filter((c,l)=>l!==a);if(wwe(A,e)&&KBo(A,e,i)&&!(f0e(A,e)>r)&&!(HPt(A)>s)){n=A,o=!0;break}}}return n},GPt=(t=>(t[t.RestoreMissingSeparators=0]="RestoreMissingSeparators",t[t.FixSharedCellRegions=1]="FixSharedCellRegions",t[t.RemoveRedundantSeparators=2]="RemoveRedundantSeparators",t))(GPt||{}),XBo=class extends z7{constructor(t){super(),this.params=t,this._inputRects=t.cellContents.map(e=>({minX:e.x,minY:e.y,maxX:e.x+e.width,maxY:e.y+e.height})),this._currentLines=t.reducedLines}params;repairedLines=[];_stage=0;_currentLines=[];_inputRects;_step(){const{originalLines:t}=this.params,e=this._inputRects;switch(this._stage){case 0:{const o=_0e(t,e);this._currentLines=jBo(this._currentLines,t,e,o);break}case 1:this._currentLines=$Bo(this._currentLines,t,e);break;case 2:this._currentLines=qBo(this._currentLines,e),this.repairedLines=this._currentLines,this.solved=!0;break}const n=this.getNextStage(this._stage);n&&(this._stage=n)}getNextStage(t){const e=Object.values(GPt);return e[e.indexOf(t)+1]}getOutput(){return this.repairedLines}getConstructorParams(){return[this.params]}visualize(){const{cellContents:t,reducedLines:e}=this.params;return{rects:t.map(n=>({center:{x:n.x+n.width/2,y:n.y+n.height/2},width:n.width,height:n.height,fill:"rgba(255, 165, 0, 0.2)",stroke:"#c87000"})),lines:[...e.map(n=>({points:[n.start,n.end],strokeColor:"rgba(180, 180, 180, 0.4)",strokeWidth:1,strokeDash:[4,4]})),...this._currentLines.map(n=>({points:[n.start,n.end],strokeColor:"#cc5500",strokeWidth:2}))]}}},ri=.001,JN=(t,e,n=ri)=>Math.abs(t.x-e.x)<n&&Math.abs(t.y-e.y)<n,bb=t=>`${t.x.toFixed(4)},${t.y.toFixed(4)}`,Tj=t=>JN(t.start,t.end),ZBo=t=>Math.abs(t.start.x-t.end.x)<ri||Math.abs(t.start.y-t.end.y)<ri,lO=(t,e,n,o)=>Math.min(e,o)-Math.max(t,n)>ri,I0e=t=>t.reduce((e,n)=>e+Math.abs(n.start.x-n.end.x)+Math.abs(n.start.y-n.end.y),0),$u=(t,e)=>Math.abs(t.start.x-t.end.x)<ri?Math.abs(e.x-t.start.x)<ri&&e.y>=Math.min(t.start.y,t.end.y)-ri&&e.y<=Math.max(t.start.y,t.end.y)+ri:Math.abs(t.start.y-t.end.y)<ri?Math.abs(e.y-t.start.y)<ri&&e.x>=Math.min(t.start.x,t.end.x)-ri&&e.x<=Math.max(t.start.x,t.end.x)+ri:!1,C0e=(t,e,n)=>e==="start"?{start:n,end:t.end}:{start:t.start,end:n},y0e=(t,e)=>e==="start"?t.end:t.start,kj=t=>({x:(t.minX+t.maxX)/2,y:(t.minY+t.maxY)/2}),YPt=(t,e,n)=>t>Math.min(e,n)+ri&&t<Math.max(e,n)-ri,UPt=t=>{const e=new Map;for(const n of t)e.set(bb(n.start),(e.get(bb(n.start))??0)+1),e.set(bb(n.end),(e.get(bb(n.end))??0)+1);return e},e9o=(t,e)=>e.some(n=>{const o=(Math.abs(t.x-n.minX)<ri||Math.abs(t.x-n.maxX)<ri)&&t.y>=n.minY-ri&&t.y<=n.maxY+ri,i=(Math.abs(t.y-n.minY)<ri||Math.abs(t.y-n.maxY)<ri)&&t.x>=n.minX-ri&&t.x<=n.maxX+ri;return o||i}),Pwe=(t,e)=>{if(!(Math.abs(t.start.x-t.end.x)>=ri)){if(Math.abs(t.start.y-e)<ri)return"start";if(Math.abs(t.end.y-e)<ri)return"end"}},KPt=(t,e)=>{if(!(Math.abs(t.start.y-t.end.y)>=ri)){if(Math.abs(t.start.x-e)<ri)return"start";if(Math.abs(t.end.x-e)<ri)return"end"}},t9o=(t,e)=>{const n=t.start.x,o=t.start.y,i=t.end.x,r=t.end.y;if(Math.abs(n-i)<ri){const s=Math.min(o,r),a=Math.max(o,r);return n>e.minX+ri&&n<e.maxX-ri&&a>e.minY-ri&&s<e.maxY+ri}if(Math.abs(o-r)<ri){const s=Math.min(n,i),a=Math.max(n,i);return o>e.minY+ri&&o<e.maxY-ri&&a>e.minX+ri&&s<e.maxX-ri}return!0},n9o=(t,e)=>{const n=t.start.x,o=t.start.y,i=t.end.x,r=t.end.y;if(Math.abs(n-i)<ri){const s=Math.min(o,r),a=Math.max(o,r);return(Math.abs(n-e.minX)<ri||Math.abs(n-e.maxX)<ri)&&lO(s,a,e.minY,e.maxY)}if(Math.abs(o-r)<ri){const s=Math.min(n,i),a=Math.max(n,i);return(Math.abs(o-e.minY)<ri||Math.abs(o-e.maxY)<ri)&&lO(s,a,e.minX,e.maxX)}return!1},vx=(t,e)=>t.length>0&&t.every(n=>!Tj(n)&&ZBo(n)&&!e.some(o=>t9o(n,o)||n9o(n,o))),o9o=(t,e,n)=>{const o=kj(e),i=kj(n);if(Math.abs(t.start.x-t.end.x)<ri){const r=t.start.x,s=Math.min(t.start.y,t.end.y),a=Math.max(t.start.y,t.end.y);return YPt(r,o.x,i.x)&&lO(s,a,e.minY,e.maxY)&&lO(s,a,n.minY,n.maxY)}if(Math.abs(t.start.y-t.end.y)<ri){const r=t.start.y,s=Math.min(t.start.x,t.end.x),a=Math.max(t.start.x,t.end.x);return YPt(r,o.y,i.y)&&lO(s,a,e.minX,e.maxX)&&lO(s,a,n.minX,n.maxX)}return!1},Sb=(t,e)=>{const n=new Set;for(let o=0;o<e.length;o++){const i=e[o];if(i)for(let r=o+1;r<e.length;r++){const s=e[r];s&&t.some(a=>o9o(a,i,s))&&n.add(`${o}:${r}`)}}return n},Fj=(t,e,n)=>{const o=Sb(t,e);return[...n].every(i=>o.has(i))},i9o=(t,e)=>{const n=new Set,o=new Set;for(const i of e)n.add(i.minX),n.add(i.maxX),n.add(kj(i).x),o.add(i.minY),o.add(i.maxY),o.add(kj(i).y);for(const i of t)n.add(i.start.x),n.add(i.end.x),o.add(i.start.y),o.add(i.end.y);return{xs:[...n].sort((i,r)=>i-r),ys:[...o].sort((i,r)=>i-r)}},r9o=(t,e,n,o)=>t.some(i=>{if(Math.abs(i.start.x-i.end.x)>=ri||Math.abs(i.start.x-e)>=ri)return!1;const r=Math.min(i.start.y,i.end.y),s=Math.max(i.start.y,i.end.y);return n>=r-ri&&o<=s+ri}),s9o=(t,e,n,o)=>t.some(i=>{if(Math.abs(i.start.y-i.end.y)>=ri||Math.abs(i.start.y-e)>=ri)return!1;const r=Math.min(i.start.x,i.end.x),s=Math.max(i.start.x,i.end.x);return n>=r-ri&&o<=s+ri}),a9o=(t,e)=>{const{xs:n,ys:o}=i9o(t,e),i=n.length-1,r=o.length-1,s=new Map,a=(c,l)=>`${c}:${l}`;let A=0;for(let c=0;c<i;c++)for(let l=0;l<r;l++){const u=a(c,l);if(s.has(u))continue;const g=[{x:c,y:l}];for(s.set(u,A);g.length>0;){const h=g.pop();if(!h)continue;const d=[{x:h.x-1,y:h.y},{x:h.x+1,y:h.y},{x:h.x,y:h.y-1},{x:h.x,y:h.y+1}];for(const p of d){if(p.x<0||p.x>=i||p.y<0||p.y>=r)continue;const m=a(p.x,p.y);if(s.has(m))continue;let _=!1;if(p.x!==h.x){const f=n[Math.max(p.x,h.x)],I=o[h.y],C=o[h.y+1];if(f===void 0||I===void 0||C===void 0)continue;_=r9o(t,f,I,C)}else{const f=o[Math.max(p.y,h.y)],I=n[h.x],C=n[h.x+1];if(f===void 0||I===void 0||C===void 0)continue;_=s9o(t,f,I,C)}_||(s.set(m,A),g.push(p))}}A++}return e.map(c=>{const l=kj(c),u=n.findIndex((h,d)=>d+1<n.length&&l.x>=h-ri&&l.x<=(n[d+1]??h)+ri),g=o.findIndex((h,d)=>d+1<o.length&&l.y>=h-ri&&l.y<=(o[d+1]??h)+ri);return s.get(a(u,g))??-1})},J7=(t,e)=>{const n=a9o(t,e);let o=0;for(let i=0;i<n.length;i++)for(let r=i+1;r<n.length;r++)n[i]===n[r]&&o++;return o},xB=t=>{const e=new Map,n=t.map(s=>[s.start,s.end]),o=(s,a)=>{const A=bb(s),c=bb(a);e.has(A)||e.set(A,new Set),e.has(c)||e.set(c,new Set),e.get(A)?.add(c),e.get(c)?.add(A)};for(let s=0;s<t.length;s++){const a=t[s];if(!(!a||Tj(a)))for(let A=s+1;A<t.length;A++){const c=t[A];if(!c||Tj(c))continue;const l=Math.abs(a.start.x-a.end.x)<ri,u=Math.abs(a.start.y-a.end.y)<ri,g=Math.abs(c.start.x-c.end.x)<ri,h=Math.abs(c.start.y-c.end.y)<ri;if(l&&h){const d={x:a.start.x,y:c.start.y};$u(a,d)&&$u(c,d)&&(n[s]?.push(d),n[A]?.push(d))}if(u&&g){const d={x:c.start.x,y:a.start.y};$u(a,d)&&$u(c,d)&&(n[s]?.push(d),n[A]?.push(d))}}}for(let s=0;s<t.length;s++){const a=t[s];if(!a||Tj(a))continue;const A=[...new Map(n[s]?.map(c=>[bb(c),c]))].map(([,c])=>c).sort((c,l)=>Math.abs(a.start.x-a.end.x)<ri?c.y-l.y:c.x-l.x);for(let c=0;c+1<A.length;c++){const l=A[c],u=A[c+1];l&&u&&!JN(l,u)&&o(l,u)}}let i=0;const r=new Set;for(const s of e.keys()){if(r.has(s))continue;i++;const a=[s];for(r.add(s);a.length>0;){const A=a.pop();if(A)for(const c of e.get(A)??[])r.has(c)||(r.add(c),a.push(c))}}return i},Mwe=(t,e,n)=>{let o=t,i=!0;for(;i;){i=!1;const r=UPt(o);for(let s=0;s<o.length;s++){const a=o[s];if(a){for(const A of["start","end"]){const c=a[A];if(r.get(bb(c))!==1)continue;const l=[],u=Math.abs(a.start.x-a.end.x)<ri,g=Math.abs(a.start.y-a.end.y)<ri;for(let d=0;d<o.length;d++){if(s===d)continue;const p=o[d];if(p){if(u&&Math.abs(p.start.y-p.end.y)<ri){const m={x:a.start.x,y:p.start.y};$u(p,m)&&l.push(m)}if(g&&Math.abs(p.start.x-p.end.x)<ri){const m={x:p.start.x,y:a.start.y};$u(p,m)&&l.push(m)}}}const h=l.filter(d=>!JN(d,c)).map(d=>({point:d,line:C0e(a,A,d)})).filter(({line:d})=>I0e([d])>I0e([a])+ri).filter(({line:d})=>!n?.preserveOriginalSpan||$u(d,c)).filter(({line:d})=>vx([d],e)).sort((d,p)=>I0e([d.line])-I0e([p.line])||JSON.stringify(d.point).localeCompare(JSON.stringify(p.point))).at(0);if(h){o=o.map((d,p)=>p===s?h.line:d),i=!0;break}}if(i)break}}}return o},A9o=(t,e)=>{const n=[],o=Math.abs(t.start.x-t.end.x)<ri,i=Math.abs(t.start.y-t.end.y)<ri;for(const r of e){if(r===t)continue;const s=Math.abs(r.start.x-r.end.x)<ri,a=Math.abs(r.start.y-r.end.y)<ri;if(o&&a){const A={x:t.start.x,y:r.start.y};$u(t,A)&&$u(r,A)&&n.push(A)}if(i&&s){const A={x:r.start.x,y:t.start.y};$u(t,A)&&$u(r,A)&&n.push(A)}}return n},VPt=(t,e,n)=>{let o=t,i=!0;for(;i;){i=!1;const r=UPt(o),s=xB(o);for(let a=0;a<o.length;a++){const A=o[a];if(!A)continue;const c=A9o(A,o).filter(l=>!JN(l,A.start)&&!JN(l,A.end));if(c.length!==0){for(const l of["start","end"]){const u=A[l];if(r.get(bb(u))!==1||e9o(u,e))continue;const g=c.map(p=>({point:p,distance:Math.abs(p.x-u.x)+Math.abs(p.y-u.y)})).sort((p,m)=>p.distance-m.distance).at(0);if(!g)continue;const h=C0e(A,l,g.point);if(!vx([h],e))continue;const d=o.map((p,m)=>m===a?h:p);if(!(xB(d)>s)&&!(n&&!Fj(d,e,n))){o=d,i=!0;break}}if(i)break}}}return o},c9o=t=>{let{start:e,end:n}=t;return e.y===n.y&&e.x>n.x?[e,n]=[{x:n.x,y:e.y},{x:e.x,y:n.y}]:e.x===n.x&&e.y>n.y&&([e,n]=[{x:e.x,y:n.y},{x:n.x,y:e.y}]),{start:e,end:n}},Lj=t=>{if(!t||t.length===0)return[];const e=t.map(c9o),n=[],o=[];for(const a of e)a.start.y===a.end.y?n.push(a):a.start.x===a.end.x&&o.push(a);const i=[],r=new Map;for(const a of n){const A=r.get(a.start.y)??[];A.push(a),r.set(a.start.y,A)}for(const[,a]of r){a.sort((c,l)=>c.start.x-l.start.x);let A;for(const c of a){if(!A){A={...c};continue}c.start.x<=A.end.x?A.end.x=Math.max(A.end.x,c.end.x):(i.push(A),A={...c})}A&&i.push(A)}const s=new Map;for(const a of o){const A=s.get(a.start.x)??[];A.push(a),s.set(a.start.x,A)}for(const[,a]of s){a.sort((c,l)=>c.start.y-l.start.y);let A;for(const c of a){if(!A){A={...c};continue}c.start.y<=A.end.y?A.end.y=Math.max(A.end.y,c.end.y):(i.push(A),A={...c})}A&&i.push(A)}return i},l9o=(t,e)=>{let n=t,o=!0;const i=r=>{const s=Sb(n,e),a=Sb(r,e);return[...s].every(A=>a.has(A))};for(;o;){o=!1;const r=J7(n,e);for(let a=0;a<n.length;a++){const A=n[a];if(!A||Math.abs(A.start.y-A.end.y)>=ri)continue;const c=A.start.y;for(let l=0;l<n.length;l++){if(l===a)continue;const u=n[l];if(!u)continue;const g=Pwe(u,c);if(g&&$u(A,{x:u.start.x,y:c})){for(let h=l+1;h<n.length;h++){if(h===a)continue;const d=n[h];if(!d)continue;const p=Pwe(d,c);if(!p||!$u(A,{x:d.start.x,y:c}))continue;const m=y0e(u,g),_=y0e(d,p);if((m.y-c)*(_.y-c)>=-ri)continue;const f=(u.start.x+d.start.x)/2,I={start:{x:f,y:Math.min(m.y,_.y)},end:{x:f,y:Math.max(m.y,_.y)}};if(!vx([I],e))continue;const C=n.filter((y,x)=>x!==l&&x!==h).concat(I);if(vx(C,e)&&i(C)&&!(J7(C,e)>r)){n=Lj(C),o=!0;break}}if(o)break}}if(o)break}if(o)continue;const s=xB(n);for(let a=0;a<n.length;a++){const A=n[a];if(!(!A||Math.abs(A.start.x-A.end.x)>=ri)){for(let c=a+1;c<n.length;c++){const l=n[c];if(!l||Math.abs(l.start.x-l.end.x)>=ri||Math.abs(A.start.x-l.start.x)<ri)continue;const u=Math.max(Math.min(A.start.y,A.end.y),Math.min(l.start.y,l.end.y)),g=Math.min(Math.max(A.start.y,A.end.y),Math.max(l.start.y,l.end.y));if(g-u<-ri||!n.some((_,f)=>{if(f===a||f===c||Math.abs(_.start.y-_.end.y)>=ri)return!1;const I=_.start.y;return I<u-ri||I>g+ri?!1:$u(_,{x:A.start.x,y:I})&&$u(_,{x:l.start.x,y:I})}))continue;const d=Math.min(A.start.y,A.end.y,l.start.y,l.end.y),p=Math.max(A.start.y,A.end.y,l.start.y,l.end.y),m=[A.start.x,l.start.x].map(_=>({start:{x:_,y:d},end:{x:_,y:p}})).filter(_=>vx([_],e));for(const _ of m){let f=n.filter((I,C)=>C!==a&&C!==c).concat(_);if(vx(f,e)&&i(f)&&!(xB(f)>s)&&!(J7(f,e)>r)){for(let I=0;I<f.length;){const C=f[I];if(!C||Math.abs(C.start.y-C.end.y)>=ri||C.start.y<u-ri||C.start.y>g+ri||!$u(C,{x:A.start.x,y:C.start.y})||!$u(C,{x:l.start.x,y:C.start.y})){I++;continue}const y=f.filter((x,E)=>E!==I);if(vx(y,e)&&i(y)&&xB(y)<=s&&J7(y,e)<=r){f=y;continue}I++}n=Lj(f),o=!0;break}}if(o)break}if(o)break}}}return n},zPt=(t,e)=>{let n=t,o=!0;for(;o;){o=!1;const i=J7(n,e),r=Sb(n,e);for(let s=0;s<n.length;s++){const a=n[s];if(!a||Math.abs(a.start.x-a.end.x)>=ri)continue;const A=a.start.x;for(let c=0;c<n.length;c++){if(c===s)continue;const l=n[c];if(l&&KPt(l,A)&&$u(a,{x:A,y:l.start.y})){for(let u=c+1;u<n.length;u++){if(u===s)continue;const g=n[u];if(g&&$u(g,{x:A,y:g.start.y})&&$u(a,{x:A,y:g.start.y})&&!(Math.abs(l.start.y-g.start.y)<ri)){for(const[h,d]of[[l,g],[g,l]]){const p=Pwe(a,h.start.y);if(!p)continue;const m=KPt(h,A);if(!m)continue;const _=y0e(h,m),f=Math.min(d.start.x,d.end.x),I=Math.max(d.start.x,d.end.x);if(_.x<A-ri&&I<=A+ri||_.x>A+ri&&f>=A-ri)continue;const C=y0e(a,p);for(const y of[h.start.y,d.start.y]){const x={start:{x:Math.min(_.x,f),y},end:{x:Math.max(_.x,I),y}};if(!vx([x],e))continue;const E={start:C,end:{x:A,y}};if(Tj(E)||!vx([E],e))continue;let B=n.filter((S,Q)=>Q!==c&&Q!==u&&Q!==s).concat(x,E);if(B=Mwe(B,e,{preserveOriginalSpan:!0}),!!vx(B,e)&&Fj(B,e,r)&&!(J7(B,e)>i)){n=Lj(B),o=!0;break}}if(o)break}if(o)break}}if(o)break}}if(o)break}}return n},JPt=t=>Math.abs(t.start.y-t.end.y)<ri,WPt=t=>Math.abs(t.start.x-t.end.x)<ri,jPt=(t,e)=>{const n=Sb(t,e),o=J7(t,e),i=xB(t);for(let r=0;r<t.length;r++){const s=t[r];if(!(!s||!JPt(s)))for(let a=r+1;a<t.length;a++){const A=t[a];if(!A||!JPt(A))continue;const c=Math.min(s.start.y,A.start.y),l=Math.max(s.start.y,A.start.y);if(l-c<ri)continue;const u=Math.min(s.start.x,s.end.x),g=Math.max(s.start.x,s.end.x),h=Math.min(A.start.x,A.end.x),d=Math.max(A.start.x,A.end.x),p=Math.max(u,h),m=Math.min(g,d);if(m-p<ri||!t.some(x=>{if(!WPt(x))return!1;const E=x.start.x;return E>=p-ri&&E<=m+ri&&$u(x,{x:E,y:c})&&$u(x,{x:E,y:l})}))continue;const f=Math.min(u,h),I=Math.max(g,d),C=new Set([c,l]);for(const x of e)x.maxX<=f+ri||x.minX>=I-ri||(x.minY>c&&x.minY<l&&C.add(x.minY),x.maxY>c&&x.maxY<l&&C.add(x.maxY));const y=[...C].sort((x,E)=>x-E);for(let x=1;x<y.length;x++){const E=y[x-1],B=y[x];if(E===void 0||B===void 0)continue;const S=(E+B)/2,Q={start:{x:f,y:S},end:{x:I,y:S}};if(!vx([Q],e))continue;const w=[];for(let M=0;M<t.length;M++){if(M===r||M===a)continue;const k=t[M];if(!k)continue;if(!WPt(k)||k.start.x<f||k.start.x>I){w.push(k);continue}const R=k.start.x;if(!($u(k,{x:R,y:c})||$u(k,{x:R,y:l}))){w.push(k);continue}const O=k.start.y>=c&&k.start.y<=l,U=k.end.y>=c&&k.end.y<=l;O&&U||(O?w.push({start:{x:R,y:S},end:k.end}):U?w.push({start:k.start,end:{x:R,y:S}}):w.push(k))}if(w.push(Q),!!vx(w,e)&&Fj(w,e,n)&&!(J7(w,e)>o)&&!(xB(w)>i))return jPt(Lj(w),e)}}}return t},u9o=(t,e)=>{let n=t,o=!0;for(;o;){o=!1;const i=xB(n),r=Sb(n,e);for(let s=0;s<n.length;s++){const a=n[s];if(!a)continue;const A=Math.abs(a.start.y-a.end.y)<ri,c=Math.abs(a.start.x-a.end.x)<ri;if(!(!A&&!c)){for(let l=0;l<n.length;l++){if(s===l)continue;const u=n[l];if(!u)continue;const g=Math.abs(u.start.y-u.end.y)<ri,h=Math.abs(u.start.x-u.end.x)<ri;if(A!==g||c!==h)continue;const d=[a.start,a.end];let p;if(A?p=d.map(I=>({x:I.x,y:u.start.y})):p=d.map(I=>({x:u.start.x,y:I.y})),!p.every(I=>$u(u,I)))continue;const m=new Map;let _=!0;for(let I=0;I<d.length;I++){const C=d[I],y=p[I];if(!C||!y){_=!1;break}const x=n.findIndex((w,M)=>{if(M===s||M===l)return!1;const k=Math.abs(w.start.y-w.end.y)<ri,R=Math.abs(w.start.x-w.end.x)<ri;return(A&&R||c&&k)&&$u(w,C)});if(x===-1)continue;const E=n[x];if(!E){_=!1;break}const B=JN(E.start,C),S=JN(E.end,C);if(!B&&!S&&$u(E,y))continue;if(!B&&!S){_=!1;break}let Q;if(B?Q=C0e(E,"start",y):Q=C0e(E,"end",y),!vx([Q],e)){_=!1;break}m.set(x,Q)}if(!_)continue;const f=n.map((I,C)=>m.get(C)??I).filter((I,C)=>C!==s);if(!(xB(f)>i)&&Fj(f,e,r)){n=f,o=!0;break}}if(o)break}}}return n},g9o=(t,e)=>{let n=t,o=!0;for(;o;){o=!1;const i=Sb(n,e),r=J7(n,e),s=xB(n);for(let a=0;a<n.length;a++){const A=n.filter((c,l)=>l!==a);if(vx(A,e)&&Fj(A,e,i)&&!(J7(A,e)>r)&&!(xB(A)>s)){n=A,o=!0;break}}}return n},$Pt=(t=>(t[t.ConnectDanglingEndpoints=0]="ConnectDanglingEndpoints",t[t.CollapseVerticalDoglegs=1]="CollapseVerticalDoglegs",t[t.CollapseHorizontalSteps=2]="CollapseHorizontalSteps",t[t.RemoveRedundantParallelBridges=3]="RemoveRedundantParallelBridges",t[t.ReconnectDanglingEndpoints=4]="ReconnectDanglingEndpoints",t[t.TrimDanglingOverhangs=5]="TrimDanglingOverhangs",t[t.RemoveRedundantSeparators=6]="RemoveRedundantSeparators",t[t.MergeAlignedSegments=7]="MergeAlignedSegments",t))($Pt||{}),d9o=class extends z7{constructor(t){super(),this.params=t,this._inputRects=t.cellContents.map(e=>({minX:e.x,minY:e.y,maxX:e.x+e.width,maxY:e.y+e.height})),this._currentLines=t.repairedLines}params;refinedLines=[];_stage=0;_currentLines=[];_inputRects;_step(){const t=this._inputRects;switch(this._stage){case 0:this._currentLines=Mwe(this._currentLines,t,{preserveOriginalSpan:!0});break;case 1:this._currentLines=l9o(this._currentLines,t);break;case 2:this._currentLines=zPt(this._currentLines,t);break;case 3:this._currentLines=u9o(this._currentLines,t);break;case 4:this._currentLines=Mwe(this._currentLines,t,{preserveOriginalSpan:!0});break;case 5:this._currentLines=VPt(this._currentLines,t,Sb(this._currentLines,t));break;case 6:this._currentLines=g9o(this._currentLines,t);break;case 7:this._currentLines=Lj(this._currentLines),this._currentLines=zPt(this._currentLines,t),this._currentLines=jPt(this._currentLines,t),this._currentLines=VPt(this._currentLines,t,Sb(this._currentLines,t)),this.refinedLines=this._currentLines,this.solved=!0;break}const e=this.getNextStage(this._stage);e&&(this._stage=e)}getNextStage(t){const e=Object.values($Pt);return e[e.indexOf(t)+1]}getOutput(){return this.refinedLines}getConstructorParams(){return[this.params]}visualize(){const{cellContents:t,repairedLines:e}=this.params;return{rects:t.map(n=>({center:{x:n.x+n.width/2,y:n.y+n.height/2},width:n.width,height:n.height,fill:"rgba(255, 165, 0, 0.2)",stroke:"#c87000"})),lines:[...e.map(n=>({points:[n.start,n.end],strokeColor:"rgba(180, 180, 180, 0.4)",strokeWidth:1,strokeDash:[4,4]})),...this._currentLines.map(n=>({points:[n.start,n.end],strokeColor:"#000000",strokeWidth:3}))]}}},h9o=class extends ABo{computeMidlinesSolver;computeIntersectionsSolver;computeSegmentsSolver;buildGridSolver;mergeGridSolver;buildOutlineSolver;reduceBoundaryLinesSolver;repairBoundaryLinesSolver;refineBoundaryLinesSolver;pipelineDef=[Bb("computeMidlinesSolver",cBo,t=>[{cellContents:t.inputProblem.cellContents,containerWidth:t.inputProblem.containerWidth,containerHeight:t.inputProblem.containerHeight}]),Bb("computeIntersectionsSolver",uBo,t=>[{midlines:t.getSolver("computeMidlinesSolver").midlines}]),Bb("computeSegmentsSolver",mBo,t=>[{midlines:t.getSolver("computeMidlinesSolver").midlines,intersections:t.getSolver("computeIntersectionsSolver").intersections,cellContents:t.inputProblem.cellContents}]),Bb("buildGridSolver",CBo,t=>[{allSegments:t.getSolver("computeSegmentsSolver").allSegments,cellContents:t.inputProblem.cellContents,containerWidth:t.inputProblem.containerWidth,containerHeight:t.inputProblem.containerHeight}]),Bb("mergeGridSolver",BBo,t=>[{validSegments:t.getSolver("buildGridSolver").validSegments,gridRects:t.getSolver("buildGridSolver").gridRects,cellContainingRects:t.getSolver("buildGridSolver").cellContainingRects,cellContents:t.inputProblem.cellContents}]),Bb("buildOutlineSolver",SBo,t=>[{groupedRects:t.getSolver("mergeGridSolver").groupedRects}]),Bb("reduceBoundaryLinesSolver",OBo,t=>[{outlineLines:t.getSolver("buildOutlineSolver").outlineLines,cellContents:t.inputProblem.cellContents,offsetX:t.inputProblem.offsetX,offsetY:t.inputProblem.offsetY}]),Bb("repairBoundaryLinesSolver",XBo,t=>[{reducedLines:t.getSolver("reduceBoundaryLinesSolver").reducedLines,originalLines:t.getSolver("reduceBoundaryLinesSolver").mergedOriginalLines,cellContents:t.inputProblem.cellContents}]),Bb("refineBoundaryLinesSolver",d9o,t=>[{repairedLines:t.getSolver("repairBoundaryLinesSolver").repairedLines,cellContents:t.inputProblem.cellContents}])];finalVisualize(){const t=this.getSolver("refineBoundaryLinesSolver"),e=this.getSolver("buildOutlineSolver"),n=t?.refinedLines??e?.outlineLines;return n?{rects:this.inputProblem.cellContents.map(o=>({center:{x:o.x+o.width/2,y:o.y+o.height/2},width:o.width,height:o.height,fill:"rgba(255, 165, 0, 0.3)",stroke:"#c87000",label:o.cellId})),lines:n.map(o=>({points:[o.start,o.end],strokeColor:"#000000",strokeWidth:3}))}:null}initialVisualize(){return{rects:this.inputProblem.cellContents.map(t=>({center:{x:t.x+t.width/2,y:t.y+t.height/2},width:t.width,height:t.height,fill:"rgba(255, 165, 0, 0.3)",stroke:"#c87000",label:t.cellId}))}}getConstructorParams(){return[this.inputProblem]}getOutput(){return{midlines:this.getSolver("computeMidlinesSolver")?.midlines??[],allSegments:this.getSolver("computeSegmentsSolver")?.allSegments??[],validSegments:this.getSolver("buildGridSolver")?.validSegments??[],mergedRectGroups:this.getSolver("mergeGridSolver")?.mergedRectGroups??[],cellRects:this.inputProblem.cellContents,gridRects:this.getSolver("buildGridSolver")?.gridRects??[],outlineLines:this.getSolver("refineBoundaryLinesSolver")?.refinedLines??this.getSolver("buildOutlineSolver")?.outlineLines??[]}}},p9o=(t,e,n)=>({...t,start:{x:t.start.x+e,y:t.start.y+n},end:{x:t.end.x+e,y:t.end.y+n}}),Dwe=t=>{let e=1/0,n=1/0,o=-1/0,i=-1/0;for(const r of t)e=Math.min(e,r.minX),n=Math.min(n,r.minY),o=Math.max(o,r.maxX),i=Math.max(i,r.maxY);return{minX:e,minY:n,maxX:o,maxY:i}},m9o=t=>{let{start:e,end:n}=t;return e.y===n.y&&e.x>n.x?[e,n]=[{x:n.x,y:e.y},{x:e.x,y:n.y}]:e.x===n.x&&e.y>n.y&&([e,n]=[{x:e.x,y:n.y},{x:n.x,y:e.y}]),{...t,start:e,end:n}},_9o=t=>{if(!t||t.length===0)return[];const e=t.map(m9o),n=[],o=[];for(const a of e)a.start.y===a.end.y?n.push(a):a.start.x===a.end.x&&o.push(a);const i=[],r=new Map;for(const a of n){const A=r.get(a.start.y)??[];A.push(a),r.set(a.start.y,A)}for(const[,a]of r){a.sort((c,l)=>c.start.x-l.start.x);let A;for(const c of a){if(!A){A={...c};continue}c.start.x<=A.end.x?A.end.x=Math.max(A.end.x,c.end.x):(i.push(A),A={...c})}A&&i.push(A)}const s=new Map;for(const a of o){const A=s.get(a.start.x)??[];A.push(a),s.set(a.start.x,A)}for(const[,a]of s){a.sort((c,l)=>c.start.y-l.start.y);let A;for(const c of a){if(!A){A={...c};continue}c.start.y<=A.end.y?A.end.y=Math.max(A.end.y,c.end.y):(i.push(A),A={...c})}A&&i.push(A)}return i},x0e=(t,e)=>t.x!==e.x?t.x-e.x:t.y-e.y,f9o=(t,e,n)=>{const o=t.map((h,d)=>({...h,cellId:`cell-${d}`})),i=Dwe(o.map(h=>({minX:h.x,minY:h.y,maxX:h.x+h.width,maxY:h.y+h.height}))),r=i.minX,s=i.minY;e??=i.maxX-i.minX,n??=i.maxY-i.minY;const a=o.map(h=>({...h,x:h.x-r,y:h.y-s})),A=new h9o({cellContents:a,containerWidth:e,containerHeight:n,offsetX:r,offsetY:s});A.solve();const c=A.getOutput(),l=h=>p9o(h,r,s),u=c.outlineLines.map(l);return _9o(u).map(h=>({start:x0e(h.start,h.end)<0?h.start:h.end,end:x0e(h.start,h.end)<0?h.end:h.start})).sort((h,d)=>x0e(h.start,d.start)||x0e(h.end,d.end))};function I9o(t,e){if(!Number.isFinite(e)||e<0)throw new Error("cellMargin must be finite and nonnegative");if(e===0||t.length<2)return t;const n=t.map(r=>({...r,minX:r.minX-e,maxX:r.maxX+e,minY:r.minY-e,maxY:r.maxY+e})),o=[n[0]],i=n.slice(1);for(;i.length>0;){const r=i.findIndex(s=>o.some(a=>a.minX<=s.maxX&&a.maxX>=s.minX&&a.minY<=s.maxY&&a.maxY>=s.minY));if(r<0)return n;o.push(...i.splice(r,1))}return t}var C9o=(t,e={})=>f9o(I9o(t,e.cellMargin??0).map(n=>({x:n.minX,y:n.minY,width:n.maxX-n.minX,height:n.maxY-n.minY}))),y9o=Object.defineProperty,x9o=(t,e)=>{for(var n in e)y9o(t,n,{get:e[n],enumerable:!0})},qPt={};x9o(qPt,{Ammeter:()=>DTo,AnalogAcSweepSimulation:()=>gFo,AnalogAnalysisSimulation:()=>HO,AnalogDcOperatingPointSimulation:()=>lFo,AnalogDcSweepSimulation:()=>uFo,AnalogSimulation:()=>AFo,AnalogSweepParameter:()=>fFo,AnalogTransientSimulation:()=>cFo,Antenna:()=>ITo,AssemblyDevice:()=>qkt,AutoroutingPhase:()=>TTo,Battery:()=>Lko,Board:()=>wB,Breakout:()=>JMe,BreakoutPoint:()=>dR,Bus:()=>FPo,CadAssembly:()=>d6o,CadModel:()=>p6o,Capacitor:()=>MDt,Chip:()=>zj,Connector:()=>LDt,Constraint:()=>RTo,CopperPour:()=>Qkt,CopperText:()=>FMt,CourtyardCircle:()=>LMt,CourtyardOutline:()=>HMt,CourtyardRect:()=>OMt,Crystal:()=>Vko,CurrentSource:()=>Lkt,Cutout:()=>T0e,DifferentialPair:()=>UPo,Diode:()=>ODt,DrcCheck:()=>RRo,EnclosureCutoutAperture:()=>WMe,EnclosureFdmBox:()=>Zkt,FabricationNoteDimension:()=>kTo,FabricationNotePath:()=>GMt,FabricationNoteRect:()=>YMt,FabricationNoteText:()=>KMt,Fanout:()=>JMe,FanoutPoint:()=>dR,Fiducial:()=>Pko,Footprint:()=>Y0e,Fuse:()=>yTo,Group:()=>A6,Hole:()=>mO,Inductor:()=>ukt,Interconnect:()=>ETo,Jumper:()=>xTo,Keepout:()=>k0e,Led:()=>dkt,Mosfet:()=>hkt,MountedBoard:()=>lTo,Net:()=>Qb,NetLabel:()=>pDo,NormalComponent:()=>g0,OpAmp:()=>zko,Panel:()=>pTo,PcbNoteDimension:()=>FTo,PcbNoteLine:()=>VMt,PcbNotePath:()=>zMt,PcbNoteRect:()=>JMt,PcbNoteText:()=>WMt,PcbTrace:()=>tPe,PcbVia:()=>jMt,PinHeader:()=>Hko,Pinout:()=>CTo,PlatedHole:()=>Pb,Port:()=>Pu,Potentiometer:()=>Uko,PowerSource:()=>bTo,PrimitiveComponent:()=>Ir,PushButton:()=>pkt,Renderable:()=>tMt,Resistor:()=>mkt,Resonator:()=>Gko,SchematicArc:()=>qMt,SchematicBox:()=>ZRt,SchematicCell:()=>aFo,SchematicCircle:()=>XMt,SchematicGraphic:()=>iFo,SchematicLine:()=>nPe,SchematicPath:()=>ZMt,SchematicRect:()=>eDt,SchematicRow:()=>sFo,SchematicSection:()=>Xko,SchematicSheet:()=>oFo,SchematicSymbol:()=>qko,SchematicTable:()=>rFo,SchematicText:()=>tDt,SilkscreenCircle:()=>nDt,SilkscreenGraphic:()=>wko,SilkscreenLine:()=>oDt,SilkscreenPath:()=>iDt,SilkscreenRect:()=>rDt,SilkscreenText:()=>oPe,SmtPad:()=>Mb,SolderJumper:()=>BTo,SpiceModel:()=>BFo,Subcircuit:()=>Dkt,Subpanel:()=>Tkt,Switch:()=>_kt,Symbol:()=>iPe,TestPoint:()=>Jko,Trace:()=>t1,TraceHint:()=>qRt,Transistor:()=>fkt,Via:()=>BMt,VoltageProbe:()=>EFo,VoltageSource:()=>Fkt});var XPt=class{input;constructor({input:t}){this.input=t}solveAndMapToTraces(){const t=[];for(const e of this.input.connections){if(e.pointsToConnect.length!==2)continue;const[n,o]=e.pointsToConnect,i={type:"pcb_trace",pcb_trace_id:"",connection_name:e.name,route:[{route_type:"wire",x:n.x,y:n.y,layer:"top",width:.1},{route_type:"wire",x:o.x,y:o.y,layer:"top",width:.1}]};t.push(i)}return t}},E9o=t=>{const e=Math.min(...t.map(r=>r.center.x)),n=Math.max(...t.map(r=>r.center.x)),o=Math.min(...t.map(r=>r.center.y)),i=Math.max(...t.map(r=>r.center.y));return{minX:e,maxX:n,minY:o,maxY:i}},B9o=["top","bottom","inner1","inner2"],E0e=(t,e,n)=>{const o=[];if(n.length===0){const A=t[0].layers;for(const c of A)o.push(...E0e(t.slice(1),e,[c]));return o}if(t.length===0)return[];const i=t[0],r=i.via||i.optional_via,s=n[n.length-1];if(t.length===1){const A=i;return A.layers&&r?A.layers.map(c=>({layer_path:[...n,c]})):A.layers?.includes(s)?[{layer_path:[...n,s]}]:[]}if(!r)return i.layers&&!i.layers.includes(s)?[]:E0e(t.slice(1),e,n.concat([s]));const a=(i.optional_via?e:e.filter(A=>A!==s)).filter(A=>!i.layers||i.layers?.includes(A));for(const A of a)o.push(...E0e(t.slice(1),e,n.concat(A)));return o},b9o=(t,e={})=>E0e(t,e.layerSelectionPreference??B9o,[]);function ZPt(t){const e={x:t.to.x-t.from.x,y:t.to.y-t.from.y},n=Math.abs(e.x),o=Math.abs(e.y);return n>o?e.x>0?"right":"left":e.y>0?"down":"up"}var W7=t=>t.route_type==="through_pad"?t.start:{x:t.x,y:t.y},S9o=t=>t.route_type==="through_pad"?[t.start,t.end]:[{x:t.x,y:t.y}],B0e=(t,e="constant")=>{const n=t.slice().reverse().map(o=>o.route_type!=="through_pad"?{...o}:{...o,start:o.end,end:o.start,start_layer:o.end_layer,end_layer:o.start_layer});if(e==="interpolated")return n;for(let o=0;o<n.length-1;o++){const i=n[o],r=n[o+1];if(i?.route_type!=="wire"||r?.route_type!=="wire"||i.layer!==r.layer)continue;const s=t[t.length-o-2];s?.route_type==="wire"&&(i.width=s.width)}for(let o=0;o<n.length;o++){const i=n[o];if(i?.route_type!=="wire")continue;const r=n[o+1];if(r?.route_type==="wire"&&r.layer===i.layer)continue;let s=t.length-o-1;for(;s<t.length-1;){const A=t[s],c=t[s+1];if(A?.route_type!=="wire"||c?.route_type!=="wire"||A.layer!==c.layer)break;s++}const a=t[s];a?.route_type==="wire"&&(i.width=a.width)}return n};function uO(t,e){const n=W7(t),o=W7(e);return Math.hypot(n.x-o.x,n.y-o.y)}var Q9o=t=>{if(t.length===1)return t[0];if(t.some(A=>A.length===0))throw new Error("Cannot merge routes with zero length");const e=[],n=t[0][0],o=t[0][t[0].length-1],i=t[1][0],r=t[1][t[1].length-1],s=Math.min(uO(n,i),uO(n,r)),a=Math.min(uO(o,i),uO(o,r));s<a?e.push(...B0e(t[0])):e.push(...t[0]);for(let A=1;A<t.length;A++){const c=e[e.length-1],l=t[A],u=l[0],g=l[l.length-1],h=uO(c,u),d=uO(c,g);h<d?e.push(...l):e.push(...B0e(l))}for(let A=1;A<e.length-1;A++){const c=e[A-1],l=e[A];c.route_type==="wire"&&l.route_type==="wire"&&c.layer!==l.layer&&e.splice(A,0,{x:c.x,y:c.y,from_layer:c.layer,to_layer:l.layer,route_type:"via"})}return e},v9o=vc("tscircuit:renderable"),rE=["ReactSubtreesRender","RenderIsolatedSubcircuits","InflateSubcircuitCircuitJson","SourceNameDuplicateComponentRemoval","PcbFootprintStringRender","FetchPartFootprint","ResolveFootprintPinLabels","InitializePortsFromChildren","CreateNetsFromProps","AssignFallbackProps","CreateTracesFromProps","CreateTracesFromNetLabels","CreateTraceHintsFromProps","CreateAutoplacedBreakoutPoints","SourceGroupRender","AssignNameToUnnamedComponents","SourceRender","CheckRefDesConvention","SourceComponentPropertyValidation","SourceParentAttachment","PortMatching","OptimizeSelectorCache","SourceTraceRender","SourceAddConnectivityMapKey","SourceDesignRuleChecks","SimulationRender","SchematicComponentRender","SchematicPortRender","SymbolContainerRender","SchematicPrimitiveRender","SchematicSymbolResize","SchematicComponentSizeCalculation","SchematicLayout","SchematicSectionRender","SchematicTraceRender","SchematicSheetRender","SchematicReplaceNetLabelsWithSymbols","SchematicLabelNetsWithConflictingNames","PanelBoardLayout","ValidatePcbCoordinates","PcbComponentRender","PcbPrimitiveRender","PcbFootprintLayout","PcbPortRender","PcbPortAttachment","PcbComponentSizeCalculation","PcbComponentAnchorAlignment","PcbCalcPlacementResolution","PcbLayout","PcbBoardAutoSize","PanelLayout","PcbAutoplaceBreakoutPoints","PcbTraceHintRender","PcbManualTraceRender","PcbPlacementDesignRuleChecks","PcbTraceRender","PcbRouteNetIslands","PcbImplicitCopperPourRender","PcbCopperPourRender","PcbViaStitchRender","PcbCopperPourCleanup","PcbDesignRuleChecks","SilkscreenOverlapAdjustment","CadModelRender","PartsEngineRender","PartOrientationAnalysis","SupplierFootprintMismatchWarning","SimulationSpiceEngineRender"],eMt=new Map(rE.map((t,e)=>[t,e])),w9o={InflateSubcircuitCircuitJson:["RenderIsolatedSubcircuits"],ResolveFootprintPinLabels:["PcbFootprintStringRender","FetchPartFootprint"],SchematicComponentRender:["PcbFootprintStringRender","FetchPartFootprint"],SchematicPortRender:["PcbFootprintStringRender","FetchPartFootprint"],SymbolContainerRender:["PcbFootprintStringRender","FetchPartFootprint"],SchematicPrimitiveRender:["PcbFootprintStringRender","FetchPartFootprint"],SchematicSymbolResize:["PcbFootprintStringRender","FetchPartFootprint"],SchematicComponentSizeCalculation:["PcbFootprintStringRender","FetchPartFootprint"],SchematicLayout:["PcbFootprintStringRender","FetchPartFootprint"],SchematicSectionRender:["PcbFootprintStringRender","FetchPartFootprint"],SchematicTraceRender:["PcbFootprintStringRender","FetchPartFootprint"],SchematicSheetRender:["PcbFootprintStringRender","FetchPartFootprint"],SchematicReplaceNetLabelsWithSymbols:["PcbFootprintStringRender","FetchPartFootprint"],SchematicLabelNetsWithConflictingNames:["RenderIsolatedSubcircuits","PcbFootprintStringRender","FetchPartFootprint","SchematicTraceRender"],PcbFootprintLayout:["PcbFootprintStringRender","FetchPartFootprint"],PcbComponentSizeCalculation:["PcbFootprintStringRender","FetchPartFootprint"],PcbLayout:["PcbFootprintStringRender","FetchPartFootprint"],PcbBoardAutoSize:["PcbFootprintStringRender","FetchPartFootprint"],PcbTraceHintRender:["PcbFootprintStringRender","FetchPartFootprint"],PcbManualTraceRender:["PcbFootprintStringRender","FetchPartFootprint"],PcbCopperPourRender:["PcbFootprintStringRender","FetchPartFootprint","PcbPlacementDesignRuleChecks","PcbTraceRender","PcbRouteNetIslands","PcbImplicitCopperPourRender"],PcbImplicitCopperPourRender:["PcbFootprintStringRender","FetchPartFootprint","PcbPlacementDesignRuleChecks","PcbTraceRender","PcbRouteNetIslands"],PcbViaStitchRender:["PcbFootprintStringRender","FetchPartFootprint","PcbPlacementDesignRuleChecks","PcbTraceRender","PcbRouteNetIslands","PcbImplicitCopperPourRender","PcbCopperPourRender"],PcbPlacementDesignRuleChecks:["PcbFootprintStringRender","FetchPartFootprint"],PcbCopperPourCleanup:["PcbFootprintStringRender","FetchPartFootprint","PcbPlacementDesignRuleChecks","PcbTraceRender","PcbRouteNetIslands","PcbImplicitCopperPourRender","PcbCopperPourRender","PcbViaStitchRender"],PcbTraceRender:["PcbFootprintStringRender","FetchPartFootprint"],PcbRouteNetIslands:["PcbFootprintStringRender","FetchPartFootprint","PcbPlacementDesignRuleChecks"],PcbDesignRuleChecks:["PcbFootprintStringRender","FetchPartFootprint","PcbPlacementDesignRuleChecks","PcbTraceRender","PcbImplicitCopperPourRender","PcbCopperPourRender","PcbViaStitchRender","PcbCopperPourCleanup"],SilkscreenOverlapAdjustment:["PcbFootprintStringRender","FetchPartFootprint"],CadModelRender:["PcbFootprintStringRender","FetchPartFootprint"],PartsEngineRender:["PcbFootprintStringRender","FetchPartFootprint"],PartOrientationAnalysis:["PcbFootprintStringRender","FetchPartFootprint","PartsEngineRender"],SupplierFootprintMismatchWarning:["PcbFootprintStringRender","FetchPartFootprint","PartsEngineRender"],SourceAddConnectivityMapKey:["PcbFootprintStringRender","FetchPartFootprint"],PcbComponentAnchorAlignment:["PcbFootprintStringRender","FetchPartFootprint"],PcbCalcPlacementResolution:["PcbFootprintStringRender","FetchPartFootprint"],ValidatePcbCoordinates:["PcbFootprintStringRender","FetchPartFootprint"],SourceTraceRender:["PcbFootprintStringRender","FetchPartFootprint"]},P9o=0,M9o=0,tMt=class g4n{renderPhaseStates;shouldBeRemoved=!1;children;isPcbPrimitive=!1;isSchematicPrimitive=!1;_renderId;_currentRenderPhase=null;_pcbTraceRenderWaitingForPlacementChecks=!1;_asyncEffects=[];parent=null;constructor(e){this._renderId=`${P9o++}`,this.children=[],this.renderPhaseStates={};for(const n of rE)this.renderPhaseStates[n]={initialized:!1,dirty:!1}}_markDirty(e){this.renderPhaseStates[e].dirty=!0;const n=eMt.get(e);for(let o=n+1;o<rE.length;o++)this.renderPhaseStates[rE[o]].dirty=!0;this.parent?._markDirty&&this.parent._markDirty(e)}_queueAsyncEffect(e,n){const o=`${this._renderId}:${M9o++}`,i={asyncEffectId:o,promise:n(),phase:this._currentRenderPhase,effectName:e,complete:!1};this._asyncEffects.push(i);const r=this._getRootCircuit();r&&r.emit("asyncEffect:start",{asyncEffectId:o,effectName:e,componentDisplayName:this.getString(),phase:i.phase}),i.promise.then(()=>{i.complete=!0;const s=this._getRootCircuit();s&&s.emit("asyncEffect:end",{asyncEffectId:o,effectName:e,componentDisplayName:this.getString(),phase:i.phase})}).catch(s=>{console.error(`Async effect error in ${i.phase} "${e}":
${s.stack}`),i.complete=!0;const a=this._getRootCircuit();a&&a.emit("asyncEffect:end",{asyncEffectId:o,effectName:e,componentDisplayName:this.getString(),phase:i.phase,error:s.toString()})})}_emitRenderLifecycleEvent(e,n){v9o(`${e}:${n} ${this.getString()}`);const o=`renderable:renderLifecycle:${e}:${n}`,i={renderId:this._renderId,componentDisplayName:this.getString(),type:o},r=this._getRootCircuit();r&&(r.emit(o,i),r.emit("renderable:renderLifecycle:anyEvent",{...i,type:o}))}getString(){return this.constructor.name}_hasIncompleteAsyncEffects(){return this._asyncEffects.some(e=>!e.complete)?!0:this.children.some(e=>typeof e._hasIncompleteAsyncEffects=="function"?e._hasIncompleteAsyncEffects():!1)}_hasIncompleteAsyncEffectsInSubtreeForPhase(e){for(const n of this._asyncEffects)if(!n.complete&&n.phase===e)return!0;for(const n of this.children)if(n._hasIncompleteAsyncEffectsInSubtreeForPhase(e))return!0;return!1}_hasIncompleteAsyncEffectsForPhase(e){const n=this._getRootCircuit();return n?._hasIncompleteAsyncEffectsForPhase?n._hasIncompleteAsyncEffectsForPhase(e):this._hasIncompleteAsyncEffectsInSubtreeForPhase(e)}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())}}getTopLevelRenderable(){let e=this;for(;e.parent&&e.parent instanceof g4n;)e=e.parent;return e}runRenderCycle(){for(const e of rE)this.runRenderPhaseForChildren(e),this.runRenderPhase(e)}runRenderPhase(e){this._currentRenderPhase=e;const n=this.renderPhaseStates[e],o=n.initialized,i=n.dirty;if(!o&&this.shouldBeRemoved)return;if(this.shouldBeRemoved&&o){this._emitRenderLifecycleEvent(e,"start"),this?.[`remove${e}`]?.(),n.initialized=!1,n.dirty=!1,this._emitRenderLifecycleEvent(e,"end");return}const r=eMt.get(e)-1;if(r>=0){const a=rE[r];if(this._asyncEffects.filter(c=>c.phase===a).some(c=>!c.complete))return}const s=w9o[e]||[];if(s.length>0){for(const a of s)if(this._hasIncompleteAsyncEffectsForPhase(a))return}if(this._emitRenderLifecycleEvent(e,"start"),o){i&&(this?.[`update${e}`]?.(),n.dirty=!1),this._emitRenderLifecycleEvent(e,"end");return}n.dirty=!1,this?.[`doInitial${e}`]?.(),n.initialized=!0,this._emitRenderLifecycleEvent(e,"end")}runRenderPhaseForChildren(e){for(const n of this.children)"_isIsolatedSubcircuit"in this&&this._isIsolatedSubcircuit&&"doInitialRenderIsolatedSubcircuits"in this&&e==="RenderIsolatedSubcircuits"||(n.runRenderPhaseForChildren(e),n.runRenderPhase(e))}_getRootCircuit(){return"root"in this?this.root??null:null}renderError(e){throw typeof e=="string"?new Error(e):new Error(JSON.stringify(e,null,2))}},nMt=class extends Error{constructor(t,e,n){let o;const i=Object.keys(n).filter(A=>A!=="_errors"),r=[],s=e.pinLabels;if(s)for(const[A,c]of Object.entries(s)){const l=Array.isArray(c)?c:[c];for(const u of l)typeof u=="string"&&(u.startsWith(" ")||u.endsWith(" "))&&r.push(`pinLabels.${A} ("${u}" has leading or trailing spaces)`)}const a=i.map(A=>A==="pinLabels"&&r.length>0?r.join(", "):n[A]._errors[0]?`${A} (${n[A]._errors[0]})`:`${A} (${JSON.stringify(n[A])})`).join(", ");"name"in e?o=`Invalid props for ${t} "${e.name}": ${a}`:"footprint"in e&&typeof e.footprint=="string"?o=`Invalid props for ${t} (unnamed ${e.footprint} component): ${a}`:o=`Invalid props for ${t} (unnamed): ${a}`,super(o),this.componentName=t,this.originalProps=e,this.formattedError=n}componentName;originalProps;formattedError},oMt={mm:1};function D9o(t,e){const{knownVariables:n,units:o}=e,i={...oMt,...o??{}},r=iMt(rMt(t)),s=sMt(r,i);return N9o(s,n)}function Nwe(t){const e=iMt(rMt(t));return sMt(e,oMt).filter(o=>o.type==="identifier").map(o=>o.value)}function iMt(t){const e={minx:"minX",maxx:"maxX",miny:"minY",maxy:"maxY"};return t.replace(/\.(minx|maxx|miny|maxy)\b/gi,(n,o)=>`.${e[String(o).toLowerCase()]??n.slice(1)}`)}function rMt(t){const e=t.trim();if(!e.toLowerCase().startsWith("calc"))return e;const n=e.match(/^calc\s*\((.*)\)$/is);if(!n)throw new Error(`Invalid calc() expression: "${t}"`);return n[1].trim()}function sMt(t,e){const n=[];let o=0;const i=a=>a>="0"&&a<="9",r=a=>a>="A"&&a<="Z"||a>="a"&&a<="z"||a==="_",s=a=>r(a)||i(a)||a===".";for(;o<t.length;){const a=t[o];if(a===" "||a===" "||a===`
`||a==="\r"){o++;continue}if(i(a)||a==="."&&o+1<t.length&&i(t[o+1])){const A=o;for(o++;o<t.length;){const g=t[o];if(i(g)||g===".")o++;else break}const c=t.slice(A,o);let l=Number(c);if(Number.isNaN(l))throw new Error(`Invalid number: "${c}"`);const u=o;for(;o<t.length&&/[A-Za-z]/.test(t[o]);)o++;if(o>u){const g=t.slice(u,o),h=e[g];if(h==null)throw new Error(`Unknown unit: "${g}"`);l*=h}n.push({type:"number",value:l});continue}if(r(a)){const A=o;for(o++;o<t.length&&s(t[o]);)o++;const c=t.slice(A,o);n.push({type:"identifier",value:c});continue}if(a==="("||a===")"){n.push({type:"paren",value:a}),o++;continue}if(a==="+"||a==="-"||a==="*"||a==="/"){n.push({type:"operator",value:a}),o++;continue}throw new Error(`Unexpected character "${a}" in expression "${t}"`)}return n}function N9o(t,e){let n=0;const o=()=>t[n],i=()=>t[n++],r=()=>{const l=o();if(!l)throw new Error("Unexpected end of expression");if(l.type==="number")return i(),l.value;if(l.type==="identifier"){i();const u=e[l.value];if(u==null)throw new Error(`Unknown variable: "${l.value}"`);return u}if(l.type==="paren"&&l.value==="("){i();const u=A(),g=o();if(!g||g.type!=="paren"||g.value!==")")throw new Error('Expected ")"');return i(),u}throw new Error(`Unexpected token "${l.value}"`)},s=()=>{const l=o();if(l&&l.type==="operator"&&(l.value==="+"||l.value==="-")){i();const u=s();return l.value==="+"?u:-u}return r()},a=()=>{let l=s();for(;;){const u=o();if(!u||u.type!=="operator"||u.value!=="*"&&u.value!=="/")break;i();const g=s();u.value==="*"?l*=g:l/=g}return l},A=()=>{let l=a();for(;;){const u=o();if(!u||u.type!=="operator"||u.value!=="+"&&u.value!=="-")break;i();const g=a();u.value==="+"?l+=g:l-=g}return l},c=A();if(n<t.length){const l=t.slice(n).map(u=>"value"in u?u.value:"?").join(" ");throw new Error(`Unexpected tokens at end of expression: ${l}`)}return c}function aMt(t){const{vars:e,componentName:n,position:o,size:i}=t;e[`${n}.x`]=o.x,e[`${n}.y`]=o.y,e[`${n}.width`]=i.width,e[`${n}.height`]=i.height,e[`${n}.minX`]=o.x-i.width/2,e[`${n}.maxX`]=o.x+i.width/2,e[`${n}.minY`]=o.y-i.height/2,e[`${n}.maxY`]=o.y+i.height/2}function R9o(t){const e={};for(const n of t.source_component.list()){if(!n.name)continue;const o=t.pcb_component.getWhere({source_component_id:n.source_component_id});o&&aMt({vars:e,componentName:n.name,position:{x:o.center.x,y:o.center.y},size:{width:o.width??0,height:o.height??0}})}return e}var T9o={from_left:{x:-1,y:0,z:0},from_right:{x:1,y:0,z:0},from_top:{x:0,y:1,z:0},from_bottom:{x:0,y:-1,z:0},from_above:{x:0,y:0,z:1},from_below:{x:0,y:0,z:-1}},b0e=t=>{const{componentLayer:e,originalLayer:n}=t;return e==="bottom"!=(n==="bottom")},AMt=t=>{const{insertionDirection:e,rotationDegrees:n=0,isFlipped:o=!1}=t;if(!e)return;const i=G2e[e],r=T9o[i],s=D0(W4(k9(n)*Math.PI/180),o?g3e():hC()),a=ts(s,r);return{x:a.x,y:a.y,z:o?-r.z:r.z}},k9o=t=>{const e=AMt(t);if(e)return e.z!==0?e.z>0?"from_above":"from_below":Math.abs(e.x)>=Math.abs(e.y)?e.x>=0?"from_right":"from_left":e.y>=0?"from_top":"from_bottom"};function F9o(t){if(!t)return;const e={},n={};if(t.silkscreenFontSize!==void 0&&(n.fontSize=t.silkscreenFontSize),t.silkscreenTextVisibility!==void 0&&(n.visibility=t.silkscreenTextVisibility),Object.keys(n).length>0&&(e["& silkscreentext"]=n),Object.keys(e).length!==0)return e}function L9o({parentResolvedPcbSx:t,pcbStyle:e,ownPcbSx:n}){const o=F9o(e),i={},r=new Set;if(t)for(const s of Object.keys(t))r.add(s);if(o)for(const s of Object.keys(o))r.add(s);if(n)for(const s of Object.keys(n))r.add(s);for(const s of r)i[s]={...t?.[s],...o?.[s],...n?.[s]};return i}function cMt(t,e){const n=["right","up","left","down"],o=n.indexOf(t);if(o===-1)return t;const i=Math.round(e/90),r=(o+i)%4;return n[r<0?r+4:r]}function Rwe(t,e){if(!t)return t;let n=t;const o=n.match(/_(right|left|up|down)$/);o&&(n=n.replace(o[0],`_${cMt(o[1],e)}`));const i=n.match(/_(horz|vert)$/);return i&&Twe(e)&&(n=n.replace(i[0],i[1]==="horz"?"_vert":"_horz")),n}function Twe(t){const e=(Math.round(t)%360+360)%360;return e===90||e===270}function kwe(t,e){return Twe(e)?{width:t.height,height:t.width}:t}function Fwe(t,e){const n=e.match(/^#(\w+)/);if(n)return t.props.id===n[1];const o=e.match(/^\.(\w+)/);if(o)return t.isMatchingNameOrAlias(o[1]);let[i,...r]=e.split(/(?=[#.[])/);return i==="pin"&&(i="port"),i&&i!=="*"&&t.lowercaseComponentName!==i.toLowerCase()?!1:r.every(s=>{if(s.startsWith("#"))return t.props.id===s.slice(1);if(s.startsWith("."))return t.isMatchingNameOrAlias(s.slice(1));const a=s.match(/\[(\w+)=['"]?(.+?)['"]?\]/);if(!a)return!0;const[,A,c]=a;return t.props[A].toString()===c})}var S0e={isTag:t=>!0,getParent:t=>t.parent,getChildren:t=>t.children,getName:t=>t.lowercaseComponentName,getAttributeValue:(t,e)=>{if(e==="class"&&"getNameAndAliases"in t)return t.getNameAndAliases().join(" ");if(e==="name"&&t._parsedProps?.name)return t._parsedProps.name;if(t._parsedProps&&e in t._parsedProps){const i=t._parsedProps[e];return typeof i=="string"?i:i!=null?String(i):null}const n=Object.keys(t._parsedProps??{}).find(i=>i.toLowerCase()===e);if(n){const i=t._parsedProps[n];return typeof i=="string"?i:i!=null?String(i):null}if(e in t){const i=t[e];return typeof i=="string"?i:i!=null?String(i):null}const o=t._attributeLowerToCamelNameMap;if(o){const i=o[e];if(i&&i in t){const r=t[i];return typeof r=="string"?r:r!=null?String(r):null}}return null},hasAttrib:(t,e)=>{if(e==="class")return!!t._parsedProps?.name;if(t._parsedProps&&e in t._parsedProps||Object.keys(t._parsedProps??{}).some(o=>o.toLowerCase()===e)||e in t)return!0;const n=t._attributeLowerToCamelNameMap;if(n){const o=n[e];if(o&&o in t)return!0}return!1},getSiblings:t=>t.parent?t.parent.children:[],prevElementSibling:t=>{if(!t.parent)return null;const e=t.parent.children,n=e.indexOf(t);return n>0?e[n-1]:null},getText:()=>"",removeSubsets:t=>t.filter((e,n)=>!t.some((o,i)=>n!==i&&o!==e&&o.getDescendants().includes(e))),existsOne:(t,e)=>e.some(t),findAll:(t,e)=>{const n=[],o=i=>{t(i)&&n.push(i);for(const r of i.children)o(r)};for(const i of e)o(i);return n},findOne:(t,e)=>{for(const n of e){if(t(n))return n;const o=n.children;if(o.length>0){const i=S0e.findOne(t,o);if(i)return i}}return null},equals:(t,e)=>t._renderId===e._renderId,isHovered:t=>!1,isVisited:t=>!1,isActive:t=>!1},H9o={...S0e,getChildren:t=>t.children.filter(e=>!e.isSubcircuit)},lMt={...S0e,getChildren:t=>t.children.filter(e=>e.isSubcircuit)},O9o=(t,e)=>{const n=t.split("net.")[1]?.split(/[ >]/)[0]??t;return`Net names cannot contain "+" or "-" (component "${e?.componentName??"Unknown component"}" received "${n}" via "${t}"). Try using underscores instead, e.g. VCC_P`},uMt=(t,e)=>{if(/net\.[^\s>]*\./.test(t))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(t))throw new Error(O9o(t,e));if(/net\.[0-9]/.test(t)){const n=t.match(/net\.([^ >]+)/),o=n?n[1]:"";throw new Error(`Net name "${o}" cannot start with a number, try using a prefix like "VBUS1"`)}return t.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,(n,o,i,r)=>{const s=/^\d+$/.test(r)?`pin${r}`:r;return`${o}.${i} > .${s}`}).trim()},Lwe={adapter:H9o,cacheResults:!0},G9o={componentName:"",zodProps:Pt({}).passthrough()},Ir=class extends tMt{parent=null;children;childrenPendingRemoval;get config(){return G9o}props;_parsedProps;get componentName(){return this.config.componentName}getInheritedProperty(t){let e=this;for(;e;){if(e._parsedProps&&t in e._parsedProps)return e._parsedProps[t];e=e.parent}if(this.root?.platform&&t in this.root.platform)return this.root.platform[t]}getInheritedMergedProperty(t){const e=this.parent?.getInheritedMergedProperty?.(t),n=this._parsedProps?.[t];return{...e,...n}}getResolvedPcbSx(){return L9o({parentResolvedPcbSx:this.parent?.getResolvedPcbSx?.(),pcbStyle:this._parsedProps?.pcbStyle,ownPcbSx:this._parsedProps?.pcbSx})}getSchematicSectionName(){return this._parsedProps?.schSectionName??null}get lowercaseComponentName(){return this.componentName.toLowerCase()}externallyAddedAliases;get isSubcircuit(){return!!this.props.subcircuit||this.lowercaseComponentName==="group"&&this?.parent?.isRootCircuit}get isGroup(){return this.lowercaseComponentName==="group"}get isRoutingDirective(){return!1}get name(){return this._parsedProps.name??this.fallbackUnassignedName}isPrimitiveContainer=!1;canHaveTextChildren=!1;source_group_id=null;source_component_id=null;schematic_component_id=null;schematic_sheet_id=null;pcb_component_id=null;cad_component_id=null;_reportedInvalidPcbCalcWarnings=new Set;_reportInvalidComponentPropertyError(t,e){!this.root||this._reportedInvalidPcbCalcWarnings.has(t)||(this.root.db.source_invalid_component_property_error.insert({source_component_id:this.source_component_id||"",property_name:t,message:e,error_type:"source_invalid_component_property_error"}),this._reportedInvalidPcbCalcWarnings.add(t))}fallbackUnassignedName;constructor(t){super(t),this.children=[],this.childrenPendingRemoval=[],this.props=t??{},this.externallyAddedAliases=[];const n=("partial"in this.config.zodProps?this.config.zodProps.partial({name:!0}):this.config.zodProps).safeParse(t??{});if(n.success)this._parsedProps=n.data;else throw new nMt(this.lowercaseComponentName,this.props,n.error.format())}setProps(t){const e=this.config.zodProps.parse({...this.props,...t}),n=this.props;this.props=e,this._parsedProps=this.config.zodProps.parse(t),this.onPropsChange({oldProps:n,newProps:e,changedProps:Object.keys(t)}),this.parent?.onChildChanged?.(this)}_getPcbRotationBeforeLayout(){const{pcbRotation:t}=this.props;return typeof t=="string"?parseFloat(t):t??null}getResolvedPcbPositionProp(){return{pcbX:this._resolvePcbCoordinate(this._parsedProps.pcbX,"pcbX"),pcbY:this._resolvePcbCoordinate(this._parsedProps.pcbY,"pcbY")}}doInitialValidatePcbCoordinates(){if(this.root?.pcbDisabled)return;const t=this.props,e=t.pcbX,n=t.pcbY;this._validatePcbCoordinateReferences({rawValue:e,axis:"pcbX",propertyName:"pcbX"}),this._validatePcbCoordinateReferences({rawValue:n,axis:"pcbY",propertyName:"pcbY"})}_validatePcbCoordinateReferences(t){const{rawValue:e,axis:n,propertyName:o=n}=t;if(typeof e!="string")return;const r=!(this._isNormalComponent===!0)&&!this._isInsideFootprint();let s=[];try{s=Nwe(e)}catch{this._reportInvalidComponentPropertyError(o,`Invalid ${o} value for ${this.componentName}: Invalid calc() expression. expression="${e}"`);return}s.some(A=>!A.startsWith("board."))&&!r&&this._reportInvalidComponentPropertyError(o,`Invalid ${o} value for ${this.componentName}: component-relative calc references are not supported for footprint elements (${this.componentName}); ${o} will be ignored. expression="${e}"`)}_resolvePcbCoordinate(t,e,n={}){if(t==null)return 0;const o=n.propertyName??e;if(typeof t=="number")return Number.isFinite(t)?t:0;if(typeof t!="string")throw new Error(`Invalid ${e} value for ${this.componentName}: ${String(t)}`);const i=n.allowBoardVariables??this._shouldAllowBoardVariablesByDefault(),r=this._isNormalComponent===!0,s=n.allowComponentVariables??(!r&&!this._isInsideFootprint()),a=t.includes("board."),A={};if(i){const c=this._getBoard(),l=c?._getBoardCalcVariables()??{};if(a&&!c)return this._reportInvalidComponentPropertyError(o,`Invalid ${o} value for ${this.componentName}: no board found for board.* variables. expression="${t}"`),0;if(a&&c&&Object.keys(l).length===0)return this._reportInvalidComponentPropertyError(o,`Invalid ${o} value for ${this.componentName}: Cannot do calculations based on board size when the board is auto-sized. expression="${t}"`),0;Object.assign(A,l)}if(s){const c=this.root?.db;c&&Object.assign(A,R9o(c)),Object.assign(A,n.componentVariables??{})}try{return Nwe(t).some(u=>!u.startsWith("board."))&&!s?(this._isInsideFootprint()&&this.root&&!this._reportedInvalidPcbCalcWarnings.has(e)&&(this.root.db.source_invalid_component_property_error.insert({source_component_id:this.source_component_id||"",property_name:e,message:`component-relative calc references are not supported for footprint elements (${this.componentName}); ${e} will be ignored. expression="${t}"`,error_type:"source_invalid_component_property_error"}),this._reportedInvalidPcbCalcWarnings.add(e)),0):D9o(t,{knownVariables:A})}catch(c){const l=c instanceof Error?c.message:String(c);return this._reportInvalidComponentPropertyError(o,`Invalid ${o} value for ${this.componentName}: ${l}. expression="${t}"`),0}}_shouldAllowBoardVariablesByDefault(){return this._isNormalComponent===!0?!0:!this._isInsideFootprint()&&!this._isInsideNonBoardSubcircuit()}_isInsideFootprint(){let t=this.parent;for(;t;){if(t.componentName==="Footprint")return!0;t=t.parent}return!1}_isInsideNonBoardSubcircuit(){let t=this.parent;for(;t;){const e=t.componentName;if(e==="Board"||e==="MountedBoard")return!1;if(t.isSubcircuit)return!0;t=t.parent}return!1}_hasUserDefinedPcbPosition(){const t=this._parsedProps;return t.pcbX!==void 0||t.pcbY!==void 0||t.pcbLeftEdgeX!==void 0||t.pcbRightEdgeX!==void 0||t.pcbTopEdgeY!==void 0||t.pcbBottomEdgeY!==void 0}resolvePcbCoordinate(t){const{rawValue:e,axis:n,allowBoardVariables:o,allowComponentVariables:i,componentVariables:r,propertyName:s}=t;return this._resolvePcbCoordinate(e,n,{allowBoardVariables:o,allowComponentVariables:i,componentVariables:r,propertyName:s})}computePcbPropsTransform(){const t=this._getPcbRotationBeforeLayout()??0,{pcbX:e,pcbY:n}=this.getResolvedPcbPositionProp();return D0(M0(e,n),W4(t*Math.PI/180))}_computePcbGlobalTransformBeforeLayout(){const t=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if(t&&this.props.pcbX===void 0&&this.props.pcbY===void 0){const e=this._getPcbRotationBeforeLayout()??0;return D0(this.parent?._computePcbGlobalTransformBeforeLayout()??hC(),D0(M0(t.x,t.y),W4(e*Math.PI/180)))}if(this.isPcbPrimitive){const{isFlipped:e}=this._getPcbPrimitiveFlippedHelpers();if(e)return D0(this.parent?._computePcbGlobalTransformBeforeLayout()??hC(),g3e(),this.computePcbPropsTransform())}return D0(this.parent?._computePcbGlobalTransformBeforeLayout()??hC(),this.computePcbPropsTransform())}_getEnclosingFootprint(){let t=this.parent;for(;t;){if(t.componentName==="Footprint")return t;t=t.parent}return null}getPrimitiveContainer(){return this.isPrimitiveContainer?this:this.parent?.getPrimitiveContainer?.()??null}_getSymbolAncestor(){const t=this.getPrimitiveContainer();return t?.componentName==="Symbol"?t:null}getParentNormalComponent(){let t=this.parent;for(;t;){if(t.isPrimitiveContainer&&t.doInitialPcbComponentRender)return t;t=t.parent}return null}getCollapsedSchematicBoxAncestor(){let t=this.parent;for(;t;){if(t.componentName==="Group"&&t._parsedProps?.showAsSchematicBox)return t;t=t.parent}return null}_resolveText(){const t=this._parsedProps.text;if(!t)return"";if(!t.includes("{NAME}")&&!t.includes("{REF}")&&!t.includes("{REFERENCE}"))return t;const n=this.getParentNormalComponent()?.name;return n?t.replace(/\{NAME\}/g,n).replace(/\{REF\}/g,n).replace(/\{REFERENCE\}/g,n):t}emitSolderMaskMarginWarning(t,e){if(t&&e!==void 0){const n=this.getParentNormalComponent();n?.source_component_id&&this.root.db.source_property_ignored_warning.insert({source_component_id:n.source_component_id,property_name:"solderMaskMargin",message:"solderMaskMargin is set but coveredWithSolderMask is true. When a component is fully covered with solder mask, a margin doesn't apply.",error_type:"source_property_ignored_warning"})}}_getPcbCircuitJsonBounds(){return{center:{x:0,y:0},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getPcbLocalBoundsBeforeLayout(){const{width:t,height:e}=this.getPcbSize();return{left:-t/2,right:t/2,top:e/2,bottom:-e/2}}_getPcbComponentLayer(){return this._parsedProps.layer}_getPcbPrimitiveFlippedHelpers(){const t=this.getPrimitiveContainer(),e=this.componentName==="Footprint"?this:this._getEnclosingFootprint(),n=t?._getPcbComponentLayer(),o=t?b0e({componentLayer:n,originalLayer:e?._parsedProps.originalLayer}):!1;return{isFlipped:o,maybeFlipLayer:r=>o?r==="top"?"bottom":"top":r}}_setPositionFromLayout(t){throw new Error(`_setPositionFromLayout not implemented for ${this.componentName}`)}computeSchematicPropsTransform(){const{_parsedProps:t}=this;return D0(M0(t.schX??0,t.schY??0))}computeSchematicGlobalTransform(){const t=this._getSchematicGlobalManualPlacementTransform(this);return t||D0(this.parent?.computeSchematicGlobalTransform?.()??hC(),this.computeSchematicPropsTransform())}_getSchematicSymbolName(){const{_parsedProps:t}=this,e=this.config.schematicSymbolName,n={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};let o=t.schOrientation!==void 0?n[t.schOrientation]:t.schRotation;if(o===void 0&&(o=0),o=o%360,o<0&&(o+=360),t.schRotation!==void 0&&o%90!==0)throw new Error(`Schematic rotation ${t.schRotation} is not supported for ${this.componentName}`);if(/_(horz|vert|up|down|left|right)$/.test(e)&&e in Su){const u=Rwe(e,o);return u&&u in Su?u:e}const r=`${e}_horz`,s=`${e}_vert`,a=`${e}_up`,A=`${e}_down`,c=`${e}_left`,l=`${e}_right`;if(l in Su&&o===0)return l;if(a in Su&&o===90)return a;if(c in Su&&o===180)return c;if(A in Su&&o===270)return A;if(r in Su&&(o===0||o===180))return r;if(s in Su&&(o===90||o===270))return s;if(e in Su)return e}_getSchematicSymbolNameOrThrow(){const t=this._getSchematicSymbolName();if(!t)throw new Error(`No schematic symbol found (given: "${this.config.schematicSymbolName}")`);return t}getSchematicSymbol(){const t=this._getSchematicSymbolName();return t?Su[t]??null:null}_getPcbManualPlacementForComponent(t){if(!this.isSubcircuit)return null;const e=this.props.manualEdits;if(!e)return null;const n=e?.pcb_placements;if(!n)return null;for(const o of n)if(Fwe(t,o.selector)||t.props.name===o.selector)return ts(this._computePcbGlobalTransformBeforeLayout(),o.center);return null}_getSchematicManualPlacementForComponent(t){if(!this.isSubcircuit)return null;const e=this.props.manualEdits;if(!e)return null;const n=e.schematic_placements;if(!n)return null;for(const o of n)if(Fwe(t,o.selector)||t.props.name===o.selector)return ts(this.computeSchematicGlobalTransform(),o.center);return null}_getSchematicGlobalManualPlacementTransform(t){const e=this.getSubcircuit()?._parsedProps.manualEdits;if(!e)return null;for(const n of e.schematic_placements??[])if((Fwe(t,n.selector)||t.props.name===n.selector)&&n.relative_to==="group_center")return D0(this.parent?._computePcbGlobalTransformBeforeLayout()??hC(),M0(n.center.x,n.center.y));return null}_getGlobalPcbPositionBeforeLayout(){return ts(this._computePcbGlobalTransformBeforeLayout(),{x:0,y:0})}_getGlobalSchematicPositionBeforeLayout(){return ts(this.computeSchematicGlobalTransform(),{x:0,y:0})}_getBoard(){let t=this;for(;t;){const e=t,n=e.componentName;if(n==="Board"||n==="MountedBoard")return e;t=t.parent??null}return this.root?._getBoard()}get root(){return this.parent?.root??null}onAddToParent(t){this.parent=t}onPropsChange(t){}onChildChanged(t){this.parent?.onChildChanged?.(t)}add(t){const e=t.__text;if(typeof e=="string"){if(this.canHaveTextChildren||e.trim()==="")return;const n=this._parsedProps?.name,o=n?`<${this.componentName} name="${n}">`:`<${this.componentName}>`,r=/^NaN/.test(e.trim())?` This looks like a numeric expression that evaluated to NaN (e.g. \`\${value}${e.trim().replace(/^NaN/,"")}\` where \`value\` is NaN) — check the computation that produces this value.`:"";throw new Error(`Invalid JSX Element: ${o} received stray text "${e}" as a child, but it cannot hold text children. Remove the text or wrap it in an appropriate component.${r}`)}if(Object.keys(t).length!==0){if(t.lowercaseComponentName==="panel")throw new Error("<panel> must be a root-level element");if(!t.onAddToParent)throw new Error(`Invalid JSX Element: Expected a React component but received "${JSON.stringify(t)}"`);t.onAddToParent(this),t.parent=this,this.children.push(t),this._clearSelectorCachesUpTree()}}addAll(t){for(const e of t)this.add(e)}remove(t){this.children=this.children.filter(e=>e!==t),this.childrenPendingRemoval.push(t),t.shouldBeRemoved=!0,this._clearSelectorCachesUpTree()}_clearSelectorCachesUpTree(){let t=this;for(;t;)t._cachedSelectAllQueries?.clear(),t._cachedSelectOneQueries?.clear(),t=t.parent}getSubcircuitSelector(){const t=this.name,e=t?`${this.lowercaseComponentName}.${t}`:this.lowercaseComponentName;return!this.parent||this.parent.isSubcircuit?e:`${this.parent.getSubcircuitSelector()} > ${e}`}getFullPathSelector(){const t=this.name,e=t?`${this.lowercaseComponentName}.${t}`:this.lowercaseComponentName,n=this.parent?.getFullPathSelector?.();return n?`${n} > ${e}`:e}getNameAndAliases(){return[this.name,...this._parsedProps.portHints??[]].filter(Boolean)}isMatchingNameOrAlias(t){return this.getNameAndAliases().includes(t)}isMatchingAnyOf(t){return this.getNameAndAliases().some(e=>t.map(n=>n.toString()).includes(e))}getPcbSize(){throw new Error(`getPcbSize not implemented for ${this.componentName}`)}doesSelectorMatch(t){const e=[this.componentName,this.lowercaseComponentName],n=[this.name].filter(Boolean),o=t.trim().split(/\> /)[0],i=o[0];return o.length>1?!1:!!(t==="*"||t[0]==="#"&&t.slice(1)===this.props.id||t[0]==="."&&n.includes(t.slice(1))||/^[a-zA-Z0-9_]/.test(i)&&e.includes(i))}getSubcircuit(){if(this.isSubcircuit)return this;const 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}_resolveSchematicSheetId(){const t=this._parsedProps?.schSheetName??this.props.schSheetName;if(t){const e=this.root?.db.schematic_sheet.list().find(n=>n.name===t);if(e)return e.schematic_sheet_id}return this.schematic_sheet_id?this.schematic_sheet_id:this.parent?._resolveSchematicSheetId?.()}doInitialAssignNameToUnnamedComponents(){this._parsedProps.name||(this.fallbackUnassignedName=this.getSubcircuit().getNextAvailableName(this))}doInitialOptimizeSelectorCache(){if(!this.isSubcircuit)return;const t=this.selectAll("port"),e=n=>/^[A-Za-z_][A-Za-z0-9_-]*$/.test(n);for(const n of t){const i=(n.getParentNormalComponent?.()??n.parent)?.getNameAndAliases(),r=n.getNameAndAliases();if(i)for(const s of i)for(const a of r){const A=[`.${s} > .${a}`,`.${s} .${a}`];e(s)&&e(a)&&A.push(`${s}.${a}`);for(const c of A){const l=this._cachedSelectAllQueries.get(c);l?l.push(n):this._cachedSelectAllQueries.set(c,[n])}}}for(const[n,o]of this._cachedSelectAllQueries.entries())o.length===1&&this._cachedSelectOneQueries.set(n,o[0])}updateOptimizeSelectorCache(){this._cachedSelectAllQueries.clear(),this._cachedSelectOneQueries.clear(),this.doInitialOptimizeSelectorCache()}_cachedSelectAllQueries=new Map;selectAll(t){if(this._cachedSelectAllQueries.has(t))return this._cachedSelectAllQueries.get(t);const e=uMt(t,this),n=t0t(e,this,Lwe);if(n.length>0)return this._cachedSelectAllQueries.set(t,n),n;const[o,...i]=e.split(" "),r=poe(o,this,{adapter:lMt});if(!r)return[];const s=r.selectAll(i.join(" "));return this._cachedSelectAllQueries.set(t,s),s}_cachedSelectOneQueries=new Map;selectOne(t,e){if(this._cachedSelectOneQueries.has(t))return this._cachedSelectOneQueries.get(t);const n=uMt(t,this);e?.port&&(e.type="port");let o=null;if(e?.type&&(o=t0t(n,this,Lwe).find(A=>A.lowercaseComponentName===e.type)),e?.type||(o??=poe(n,this,Lwe)),o)return this._cachedSelectOneQueries.set(t,o),o;const[i,...r]=n.split(" "),s=poe(i,this,{adapter:lMt});return s?(o=s.selectOne(r.join(" "),e),this._cachedSelectOneQueries.set(t,o),o):null}getAvailablePcbLayers(){if(this.isPcbPrimitive){const{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(){const t=[];for(const e of this.children)t.push(e),t.push(...e.getDescendants());return t}getSelectableDescendants(){const t=[];for(const e of this.children)e.isSubcircuit?t.push(e):(t.push(e),t.push(...e.getSelectableDescendants()));return t}_getPrimaryPinCount(){return 0}_getSchematicBoxDimensions(){return null}_getSchematicBoxComponentDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;const{_parsedProps:t}=this;return{schWidth:t.schWidth,schHeight:t.schHeight}}renderError(t){if(typeof t=="string")return super.renderError(t);switch(t.type){case"pcb_placement_error":this.root?.db.pcb_placement_error.insert(t);break;case"pcb_via_clearance_error":this.root?.db.pcb_via_clearance_error.insert(t);break;case"pcb_trace_error":this.root?.db.pcb_trace_error.insert(t);break;case"pcb_manual_edit_conflict_warning":this.root?.db.pcb_manual_edit_conflict_warning.insert(t);break;default:this.root?.db.pcb_placement_error.insert(t)}}getString(){const{lowercaseComponentName:t,_parsedProps:e,parent:n}=this;return e?.pinNumber!==void 0&&n?.props?.name&&e?.name?`<${t}#${this._renderId}(pin:${e.pinNumber} .${n?.props.name}>.${e.name}) />`:n?.props?.name&&e?.name?`<${t}#${this._renderId}(.${n?.props.name}>.${e?.name}) />`:e?.from&&e?.to?`<${t}#${this._renderId}(from:${e.from} to:${e?.to}) />`:e?.name?`<${t}#${this._renderId} name=".${e?.name}" />`:e?.portHints?`<${t}#${this._renderId}(${e.portHints.map(o=>`.${o}`).join(", ")}) />`:`<${t}#${this._renderId} />`}getDisplayName(){return this.name?`${this.lowercaseComponentName} "${this.name}"`:`${this.lowercaseComponentName} (unnamed)`}get[Symbol.toStringTag](){return this.getString()}[Symbol.for("nodejs.util.inspect.custom")](){return this.getString()}};function gMt(t){const e=[];for(let n=0;n<t.length-1;n++)e.push([t[n],t[n+1]]);return e}var Q0e=/(?:^|_)(?:GND|AGND|DGND|PGND|VSS)/i,Hwe=/(?:^|_)(?:V(?!SS)|\d+(?:[_.]\d+)?V)/i,Qb=class extends Ir{source_net_id;subcircuit_connectivity_map_key=null;get config(){return{componentName:"Net",zodProps:Xwn}}getPortSelector(){return`net.${this.props.name}`}doInitialSourceRender(){const{db:t}=this.root,{_parsedProps:e}=this,n=e.isGroundNet??Q0e.test(e.name),o=e.isPowerNet??Hwe.test(e.name),i=t.source_net.insert({name:e.name,member_source_group_ids:[],is_ground:n,is_power:o,is_positive_voltage_source:o});this.source_net_id=i.source_net_id}doInitialSourceParentAttachment(){const t=this.getSubcircuit();if(!t)return;const{db:e}=this.root;e.source_net.update(this.source_net_id,{subcircuit_id:t.subcircuit_id})}getAllConnectedPorts(){const t=this.getSubcircuit().selectAll("port"),e=[];for(const n of t){const o=n._getDirectlyConnectedTraces();for(const i of o)if(i._isExplicitlyConnectedToNet(this)){e.push(n);break}}return e}_getAllDirectlyConnectedTraces(){const t=this.getSubcircuit().selectAll("trace"),e=[];for(const n of t)n._isExplicitlyConnectedToNet(this)&&e.push(n);return e}doInitialPcbRouteNetIslands(){if(this.root?.pcbDisabled)return;const t=this.getSubcircuit();if(this.root?.pcbRoutingDisabled||t.getInheritedProperty("routingDisabled")||t._isInflatedFromCircuitJson||t._getAutorouterConfig().groupMode!=="sequential-trace")return;const{db:e}=this.root,{_parsedProps:n}=this,o=this._getAllDirectlyConnectedTraces().filter(s=>(s._portsRoutedOnPcb?.length??0)>0),i=[];for(const s of o){const a=s._portsRoutedOnPcb,A=i.find(c=>a.some(l=>c.ports.includes(l)));if(!A){i.push({ports:[...a],traces:[s]});continue}A.traces.push(s),A.ports.push(...a)}if(i.length===0)return;const r=gMt(i);for(const[s,a]of r){const A=s.ports.map(_=>_._getGlobalPcbPositionBeforeLayout()),c=a.ports.map(_=>_._getGlobalPcbPositionBeforeLayout());let l=1/0,u=[-1,-1];for(let _=0;_<A.length;_++){const f=A[_];for(let I=0;I<c.length;I++){const C=c[I],y=Math.sqrt((f.x-C.x)**2+(f.y-C.y)**2);y<l&&(l=y,u=[_,I])}}const g=s.ports[u[0]],h=a.ports[u[1]],d=e.toArray().filter(_=>_.type==="pcb_smtpad"||_.type==="pcb_trace"||_.type==="pcb_plated_hole"||_.type==="pcb_hole"||_.type==="source_port"||_.type==="pcb_port"),{solution:p}=dvn(d.concat([{type:"source_trace",source_trace_id:"__net_trace_tmp",connected_source_port_ids:[g.source_port_id,h.source_port_id]}])),m=p[0];if(!m){this.renderError({pcb_trace_error_id:"",pcb_trace_id:"__net_trace_tmp",pcb_component_ids:[g.pcb_component_id,h.pcb_component_id].filter(Boolean),pcb_port_ids:[g.pcb_port_id,h.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}e.pcb_trace.insert(m)}}renderError(t){if(typeof t=="string")return super.renderError(t);this.root?.db.pcb_trace_error.insert(t)}},Hj=(t,e)=>{for(const n of e)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)){const i=n.split("net.")[1],r=`Net names cannot contain "+" or "-" (component "${t.componentName}" received "${i}" via "${n}"). Try using underscores instead, e.g. VCC_P`;throw new Error(r)}if(/net\.[0-9]/.test(n)){const i=n.split("net.")[1];throw new Error(`Net name "${i}" cannot start with a number, try using a prefix like "VBUS1"`)}const o=t.getSubcircuit();if(!o.selectOne(n)){const i=new Qb({name:n.split("net.")[1]});o.add(i)}}},Y9o=(t,e)=>{const n="_getGlobalPcbPositionBeforeLayout"in t?t._getGlobalPcbPositionBeforeLayout():t,o="_getGlobalPcbPositionBeforeLayout"in e?e._getGlobalPcbPositionBeforeLayout():e;return Math.sqrt((n.x-o.x)**2+(n.y-o.y)**2)};function dMt(t,e){if(e.length===0)throw new Error("No candidates given to getClosest method");let n=e[0],o=1/0;for(const i of e){const r=Y9o(t,i);r<o&&(n=i,o=r)}return n}var U9o=t=>t.outline&&t.outline.length>0?new Ip(t.outline.map(e=>by(e.x,e.y))):new Ip(new VBe(t.center.x-t.width/2,t.center.y-t.height/2,t.center.x+t.width/2,t.center.y+t.height/2).toPoints()),K9o=({mergedRoute:t,db:e,pcbBoardId:n})=>{const o=e.pcb_board.get(n);if(!o)return!1;const i=U9o(o);return!t.flatMap(S9o).every(r=>i.contains(by(r.x,r.y)))},lw=({fromLayer:t,toLayer:e,layerCount:n})=>{if(t===e)return[t];const o=["top"];for(let s=1;s<=n-2;s++)o.push(`inner${s}`);o.push("bottom");const i=o.indexOf(t),r=o.indexOf(e);return i===-1||r===-1?[t,e]:i<=r?o.slice(i,r+1):o.slice(r,i+1).reverse()},WN=t=>t<=1?["top"]:lw({fromLayer:"top",toLayer:"bottom",layerCount:t}),hMt=({fromLayer:t,toLayer:e,layerCount:n,allowBlindAndBuriedVias:o=!1,physicalLayers:i})=>{const r=WN(n);if(!o)return r;if(i?.length){const s=new Set(i),a=r.filter(u=>s.has(u)),A=r.indexOf(a[0]),c=r.indexOf(a[a.length-1]),l=r.slice(A,c+1);if(s.has(t)&&s.has(e)&&s.size===l.length&&l.every(u=>s.has(u)))return l}return lw({fromLayer:t,toLayer:e,layerCount:n})},Owe=t=>{const e=WN(t);return e.length<=1?e:[e[0],e[e.length-1],...e.slice(1,-1)]};function V9o(t,e={}){const{center:n,radius:o}=t,{rectHeight:i=.1}=e,r=[],s=Math.ceil(o*2/i);for(let a=0;a<s;a++){const A=n.y-o+(a+.5)*i,c=A-n.y,l=Math.sqrt(o*o-c*c);l>0&&r.push({center:{x:n.x,y:A},width:l*2,height:i})}return r}function Gwe(t,e={}){if(t.length<3)return[];const{rectHeight:n=.1}=e,o=[],i=t.map(a=>a.y),r=Math.min(...i),s=Math.max(...i);for(let a=r;a<s;a+=n){const A=a+n/2,c=[];for(let l=0;l<t.length;l++){const u=t[l],g=t[(l+1)%t.length];if(u.y<=A&&g.y>A||g.y<=A&&u.y>A){const h=(A-u.y)*(g.x-u.x)/(g.y-u.y)+u.x;c.push(h)}}c.sort((l,u)=>l-u);for(let l=0;l<c.length;l+=2)if(l+1<c.length){const u=c[l],h=c[l+1]-u;h>1e-6&&o.push({center:{x:u+h/2,y:A},width:h,height:n})}}return o}var z9o=.001,J9o=t=>{const e=(A,c)=>Math.abs(A-c)<=z9o,n=t.filter((A,c)=>c===0||!e(A.x,t[c-1].x)||!e(A.y,t[c-1].y));if(n.length>1&&e(n[0].x,n.at(-1).x)&&e(n[0].y,n.at(-1).y)&&n.pop(),n.length<4)return null;const o=Math.min(...n.map(A=>A.x)),i=Math.max(...n.map(A=>A.x)),r=Math.min(...n.map(A=>A.y)),s=Math.max(...n.map(A=>A.y)),a=[{x:o,y:r},{x:o,y:s},{x:i,y:r},{x:i,y:s}];return!n.every(A=>e(A.x,o)||e(A.x,i)||e(A.y,r)||e(A.y,s))||!a.every(A=>n.some(c=>e(c.x,A.x)&&e(c.y,A.y)))?null:{center:{x:(o+i)/2,y:(r+s)/2},width:i-o,height:s-r}},pMt=(t,e)=>Math.abs(t-e)<1e-4,W9o=(t,e,{viaDiameter:n=.5}={})=>{const o=[];for(let i=0;i<t.length-1;i++){const[r,s]=[t[i],t[i+1]],a=i-1>=0?t[i-1]:null,A=pMt(r.y,s.y),c=pMt(r.x,s.x);if(!A&&!c)throw new Error(`getObstaclesFromTrace currently only supports horizontal and vertical traces (not diagonals) Conflicting trace: ${e}, start: (${r.x}, ${r.y}), end: (${s.x}, ${s.y})`);const l={type:"rect",layers:[r.layer],center:{x:(r.x+s.x)/2,y:(r.y+s.y)/2},width:A?Math.abs(r.x-s.x):.1,height:c?Math.abs(r.y-s.y):.1,connectedTo:[e]};if(o.push(l),a&&a.layer===r.layer&&r.layer!==s.layer){const u={type:"rect",layers:[r.layer,s.layer],center:{x:r.x,y:r.y},connectedTo:[e],width:n,height:n};o.push(u)}}return o},j9o=.01,mMt=t=>{const e=(t.rotation%360+360)%360,n=[0,90,180,270];for(const o of n){if(Math.min(Math.abs(e-o),360-Math.abs(e-o))>j9o)continue;const r=o===90||o===270;return{center:t.center,width:r?t.height:t.width,height:r?t.width:t.height}}return null},_Mt=(t,e)=>{const n=t.find(u=>u.type==="pcb_board"),o=WN(n?.num_layers??4),i=new Map(t.flatMap(u=>u.type==="pcb_component"?[[u.pcb_component_id,u]]:[])),r=new Map(t.flatMap(u=>u.type==="pcb_port"?[[u.pcb_port_id,u]]:[])),s=new Map(t.flatMap(u=>u.type==="source_component"?[[u.source_component_id,u]]:[])),a=new Map(t.flatMap(u=>u.type==="source_port"?[[u.source_port_id,u]]:[])),A=({pcbComponentId:u,pcbPortId:g})=>{const h=g?r.get(g):void 0,d=h?a.get(h.source_port_id):void 0,p=(u?i.get(u)?.source_component_id:void 0)??d?.source_component_id,m=p?s.get(p):void 0;return{...m?.name?{source_component_name:m.name}:{},...d?.name?{source_port_name:d.name}:{}}},c=u=>e?u.concat(u.map(g=>e?.getNetConnectedToId(g)).filter(Boolean)):u,l=[];for(const u of t){const g=u.pcb_component_id??void 0;if(u.type==="pcb_smtpad"){const h={pcb_smtpad_id:u.pcb_smtpad_id,pcb_port_id:u.pcb_port_id,...A({pcbComponentId:g,pcbPortId:u.pcb_port_id})};if(u.shape==="circle")l.push({circuitJsonMetadata:h,componentId:g,type:"rect",shape:"circle",layers:[u.layer],center:{x:u.x,y:u.y},width:u.radius*2,height:u.radius*2,connectedTo:c([u.pcb_smtpad_id])});else if(u.shape==="rect")l.push({circuitJsonMetadata:h,componentId:g,type:"rect",layers:[u.layer],center:{x:u.x,y:u.y},width:u.width,height:u.height,connectedTo:c([u.pcb_smtpad_id])});else if(u.shape==="rotated_rect"){const d={center:{x:u.x,y:u.y},width:u.width,height:u.height,rotation:u.ccw_rotation},p=mMt(d),m=p??d;l.push({circuitJsonMetadata:h,componentId:g,type:"rect",layers:[u.layer],center:m.center,width:m.width,height:m.height,ccwRotationDegrees:p?void 0:u.ccw_rotation,connectedTo:c([u.pcb_smtpad_id])})}else if(u.shape==="pill"||u.shape==="rotated_pill")l.push({circuitJsonMetadata:h,componentId:g,type:"rect",layers:[u.layer],center:{x:u.x,y:u.y},width:u.width,height:u.height,...u.shape==="rotated_pill"?{ccwRotationDegrees:u.ccw_rotation}:{},connectedTo:c([u.pcb_smtpad_id])});else if(u.shape==="polygon"){const d=J9o(u.points);if(d){l.push({circuitJsonMetadata:h,componentId:g,type:"rect",layers:[u.layer],...d,connectedTo:c([u.pcb_smtpad_id])});continue}const p=Gwe(u.points,{rectHeight:.1});for(const m of p)l.push({circuitJsonMetadata:h,componentId:g,type:"rect",layers:[u.layer],center:m.center,width:m.width,height:m.height,connectedTo:c([u.pcb_smtpad_id])})}}else if(u.type==="pcb_keepout")u.shape==="circle"?l.push({componentId:g,type:"oval",layers:u.layers,center:{x:u.center.x,y:u.center.y},width:u.radius*2,height:u.radius*2,connectedTo:[]}):u.shape==="rect"&&l.push({componentId:g,type:"rect",layers:u.layers,center:{x:u.center.x,y:u.center.y},width:u.width,height:u.height,connectedTo:[]});else if(u.type==="pcb_cutout"){if(u.shape==="rect")l.push({componentId:g,type:"rect",layers:o,center:{x:u.center.x,y:u.center.y},width:u.width,height:u.height,connectedTo:[]});else if(u.shape==="circle"){const h=V9o({center:u.center,radius:u.radius},{rectHeight:.6});for(const d of h)l.push({componentId:g,type:"rect",layers:o,center:d.center,width:d.width,height:d.height,connectedTo:[]})}else if(u.shape==="polygon"){const h=Gwe(u.points,{rectHeight:.6});for(const d of h)l.push({componentId:g,type:"rect",layers:o,center:d.center,width:d.width,height:d.height,connectedTo:[]})}}else if(u.type==="pcb_hole")u.hole_shape==="oval"?l.push({componentId:g,type:"oval",layers:o,center:{x:u.x,y:u.y},width:u.hole_width,height:u.hole_height,connectedTo:[]}):u.hole_shape==="pill"||u.hole_shape==="rotated_pill"?l.push({componentId:g,type:"rect",layers:o,center:{x:u.x,y:u.y},width:u.hole_width,height:u.hole_height,...u.hole_shape==="rotated_pill"?{ccwRotationDegrees:u.ccw_rotation}:{},connectedTo:[]}):u.hole_shape==="rect"?l.push({componentId:g,type:"rect",layers:o,center:{x:u.x,y:u.y},width:u.hole_width,height:u.hole_height,connectedTo:[]}):u.hole_shape==="square"?l.push({componentId:g,type:"rect",layers:o,center:{x:u.x,y:u.y},width:u.hole_diameter,height:u.hole_diameter,connectedTo:[]}):(u.hole_shape==="round"||u.hole_shape==="circle")&&l.push({componentId:g,type:"rect",layers:o,center:{x:u.x,y:u.y},width:u.hole_diameter,height:u.hole_diameter,connectedTo:[]});else if(u.type==="pcb_plated_hole"){const h={pcb_plated_hole_id:u.pcb_plated_hole_id,pcb_port_id:u.pcb_port_id,...A({pcbComponentId:g,pcbPortId:u.pcb_port_id})};if(u.shape==="circle")l.push({circuitJsonMetadata:h,componentId:g,type:"oval",layers:o,center:{x:u.x,y:u.y},width:u.outer_diameter,height:u.outer_diameter,connectedTo:c([u.pcb_plated_hole_id])});else if(u.shape==="pill_hole_with_rect_pad"||u.shape==="rotated_pill_hole_with_rect_pad"){const d={center:{x:u.x,y:u.y},width:u.rect_pad_width,height:u.rect_pad_height,rotation:u.shape==="rotated_pill_hole_with_rect_pad"?u.rect_ccw_rotation:0},p=mMt(d),m=p??d;l.push({circuitJsonMetadata:h,componentId:g,type:"rect",layers:o,center:m.center,width:m.width,height:m.height,ccwRotationDegrees:p?void 0:d.rotation,connectedTo:c([u.pcb_plated_hole_id])})}else if(u.shape==="circular_hole_with_rect_pad")l.push({circuitJsonMetadata:h,componentId:g,type:"rect",layers:o,center:{x:u.x,y:u.y},width:u.rect_pad_width,height:u.rect_pad_height,connectedTo:c([u.pcb_plated_hole_id])});else if(u.shape==="oval")l.push({circuitJsonMetadata:h,componentId:g,type:"oval",layers:o,center:{x:u.x,y:u.y},width:u.outer_width,height:u.outer_height,connectedTo:c([u.pcb_plated_hole_id])});else if(u.shape==="pill")l.push({circuitJsonMetadata:h,componentId:g,type:"rect",layers:o,center:{x:u.x,y:u.y},width:u.outer_width,height:u.outer_height,ccwRotationDegrees:u.ccw_rotation,connectedTo:c([u.pcb_plated_hole_id])});else if(u.shape==="hole_with_polygon_pad"&&"pad_outline"in u&&u.pad_outline&&u.pad_outline.length>0){const d=u.pad_outline.map(x=>u.x+x.x),p=u.pad_outline.map(x=>u.y+x.y),m=Math.min(...d),_=Math.max(...d),f=Math.min(...p),I=Math.max(...p),C=(m+_)/2,y=(f+I)/2;l.push({circuitJsonMetadata:h,componentId:g,type:"rect",layers:o,center:{x:C,y},width:_-m,height:I-f,connectedTo:c([u.pcb_plated_hole_id])})}}else if(u.type==="pcb_trace"){const h=W9o(u.route.flatMap(d=>d.route_type==="through_pad"?[{x:d.start.x,y:d.start.y,layer:d.start_layer},{x:d.end.x,y:d.end.y,layer:d.end_layer}]:[{x:d.x,y:d.y,layer:d.route_type==="wire"?d.layer:d.from_layer}]),u.source_trace_id??u.pcb_trace_id);l.push(...h.map(d=>({...d,componentId:g})))}else if(u.type==="pcb_via"){const h=!!(u.net_is_assignable??u.netIsAssignable);l.push({circuitJsonMetadata:{pcb_via_id:u.pcb_via_id,...A({pcbComponentId:g})},componentId:g,type:"rect",shape:"circle",layers:u.layers,center:{x:u.x,y:u.y},connectedTo:c([u.pcb_via_id]),width:u.outer_diameter,height:u.outer_diameter,netIsAssignable:h||void 0})}}return l},vb=({text:t,font_size:e=.18})=>{const n=e/.18,o=.12*n,i=.12*n;return t.length*o+i},j7=({anchor_position:t,anchor_side:e,text:n,font_size:o=.18})=>{const i=vb({text:n,font_size:o}),r=o,s={...t};switch(e){case"right":s.x-=i/2;break;case"left":s.x+=i/2;break;case"top":s.y-=r/2;break;case"bottom":s.y+=r/2;break}return s},$9o=(t,e)=>{let n=0;n+=t.length??0,n+=e.filter(o=>o.is_crossing).length;for(let o=1;o<e.length;o++){const i=e[o-1],r=e[o],s=Math.abs(i.from.x-i.to.x)<.01,a=Math.abs(r.from.x-r.to.x)<.01;s!==a&&n++}return n},gO=t=>({up:"bottom",down:"top",left:"right",right:"left"})[t]??null,Ywe=({firstEdge:t,firstEdgePort:e,firstDominantDirection:n,lastEdge:o,lastEdgePort:i,lastDominantDirection:r})=>{if(t&&e)return Ywe({lastEdge:{from:t.to,to:t.from},lastEdgePort:e,lastDominantDirection:n}).reverse().map(a=>({from:a.to,to:a.from}));let s=[];if(o&&i){const a={x:o.to.x,y:o.to.y};r==="left"||r==="right"?(a.x=i.position.x,s.push({from:o.to,to:{...a}}),s.push({from:a,to:{...i.position}})):(a.y=i.position.y,s.push({from:o.to,to:{...a}}),s.push({from:a,to:{...i.position}}))}return s=s.filter(a=>ad(a.from,a.to)>.01),s};function q9o(t){try{return[t(),null]}catch(e){return[null,e]}}var X9o=tJn.version,Oj=class extends Error{constructor(t){super(`${t} (capacity-autorouter@${X9o})`),this.name="AutorouterError"}},jN=class extends Error{constructor(t){super(t.message),this.errorData=t,this.name="TraceConnectionError"}errorData},Z9o=.2,e7o=.3,fMt=(t,e)=>{if(t===void 0)return e;if(typeof t=="number")return t;const n=parseFloat(t);return Number.isFinite(n)?n:e},$N=t=>({holeDiameter:fMt(t?.viaHoleDiameter,Z9o),padDiameter:fMt(t?.viaPadDiameter,e7o)}),t7o=(t,e)=>{const n=$N(e);return{holeDiameter:t.holeDiameter??n.holeDiameter,padDiameter:t.padDiameter??n.padDiameter}};function IMt(t,e){const n=e.x-t.x,o=e.y-t.y;return Math.abs(n)>Math.abs(o)?n>=0?"right":"left":o>=0?"up":"down"}var n7o=new Proxy({},{get:(t,e)=>e}),$7=n7o,wb="rgba(132, 0, 0)",v0e=.12,w0e=t=>{if(t.length<=1)return!0;const e=t.map(r=>{const s=r._getPcbCircuitJsonBounds();return{left:s.bounds.left,right:s.bounds.right,top:s.bounds.top,bottom:s.bounds.bottom}}),n=Array(e.length).fill(!1).map(()=>Array(e.length).fill(!1));for(let r=0;r<e.length;r++)for(let s=r+1;s<e.length;s++){const a=e[r],A=e[s];n[r][s]=n[s][r]=!(a.right<A.left||a.left>A.right||a.bottom>A.top||a.top<A.bottom)}const o=new Set,i=r=>{o.add(r);for(let s=0;s<e.length;s++)n[r][s]&&!o.has(s)&&i(s)};return i(0),o.size===e.length},Uwe=t=>{if(t.length===0)throw new Error("Cannot get center of empty PCB primitives array");const e=t.map(i=>i._getPcbCircuitJsonBounds().center).filter(Boolean),n=e.reduce((i,r)=>i+r.x,0),o=e.reduce((i,r)=>i+r.y,0);return{x:n/e.length,y:o/e.length}},o7o=(t,e)=>{switch(e){case"i2c_sda":t.supports_i2c_sda=!0;return;case"i2c_scl":t.supports_i2c_scl=!0;return;case"spi_cs":t.supports_spi_cs=!0;return;case"spi_sck":t.supports_spi_sck=!0;return;case"spi_mosi":t.supports_spi_mosi=!0;return;case"spi_miso":t.supports_spi_miso=!0;return;case"uart_tx":t.supports_uart_tx=!0;return;case"uart_rx":t.supports_uart_rx=!0;return;default:{const n=e;throw new Error(`Unhandled pin capability: ${n}`)}}},i7o=(t,e)=>{switch(e){case"i2c_sda":t.is_configured_for_i2c_sda=!0;return;case"i2c_scl":t.is_configured_for_i2c_scl=!0;return;case"spi_cs":t.is_configured_for_spi_cs=!0;return;case"spi_sck":t.is_configured_for_spi_sck=!0;return;case"spi_mosi":t.is_configured_for_spi_mosi=!0;return;case"spi_miso":t.is_configured_for_spi_miso=!0;return;case"uart_tx":t.is_configured_for_uart_tx=!0;return;case"uart_rx":t.is_configured_for_uart_rx=!0;return;default:{const n=e;throw new Error(`Unhandled configured pin capability: ${n}`)}}},r7o=(t,e)=>{for(const o of e.capabilities??[])o7o(t,o);const n=new Set([...e.activeCapabilities??[],...e.activeCapability?[e.activeCapability]:[]]);for(const o of n)i7o(t,o);e.mustBeConnected!==void 0&&(t.must_be_connected=e.mustBeConnected),e.providesPower!==void 0&&(t.provides_power=e.providesPower),e.requiresPower!==void 0&&(t.requires_power=e.requiresPower),e.providesGround!==void 0&&(t.provides_ground=e.providesGround),e.requiresGround!==void 0&&(t.requires_ground=e.requiresGround),e.providesVoltage!==void 0&&(t.provides_voltage=e.providesVoltage),e.requiresVoltage!==void 0&&(t.requires_voltage=e.requiresVoltage),e.doNotConnect!==void 0&&(t.do_not_connect=e.doNotConnect),e.includeInBoardPinout!==void 0&&(t.include_in_board_pinout=e.includeInBoardPinout),e.canUseInternalPullup!==void 0&&(t.can_use_internal_pullup=e.canUseInternalPullup),e.isUsingInternalPullup!==void 0&&(t.is_using_internal_pullup=e.isUsingInternalPullup),e.needsExternalPullup!==void 0&&(t.needs_external_pullup=e.needsExternalPullup),e.canUseInternalPulldown!==void 0&&(t.can_use_internal_pulldown=e.canUseInternalPulldown),e.isUsingInternalPulldown!==void 0&&(t.is_using_internal_pulldown=e.isUsingInternalPulldown),e.needsExternalPulldown!==void 0&&(t.needs_external_pulldown=e.needsExternalPulldown),e.canUseOpenDrain!==void 0&&(t.can_use_open_drain=e.canUseOpenDrain),e.isUsingOpenDrain!==void 0&&(t.is_using_open_drain=e.isUsingOpenDrain),e.canUsePushPull!==void 0&&(t.can_use_push_pull=e.canUsePushPull),e.isUsingPushPull!==void 0&&(t.is_using_push_pull=e.isUsingPushPull),e.shouldHaveDecouplingCapacitor!==void 0&&(t.should_have_decoupling_capacitor=e.shouldHaveDecouplingCapacitor),e.recommendedDecouplingCapacitorCapacitance!==void 0&&(t.recommended_decoupling_capacitor_capacitance=e.recommendedDecouplingCapacitorCapacitance)},s7o=t=>t?typeof t=="string"?[t]:[...t]:[];function a7o(t){if(!t.isGroupPort())return;const e=t._parsedProps.connectsTo;if(!e)return;const n=t.parent;if(!n)return;const o=n._parsedProps?.connections;if(Object.keys(o??{}).some(A=>t.isMatchingAnyOf([A])))return;const r=n.name,s=t.name;if(!r||!s)return;const a=`.${r} > .${s}`;for(const A of s7o(e))n.children.some(l=>{if(!(l instanceof t1))return!1;const u=l._parsedProps;return!("from"in u)||!("to"in u)?!1:u.from===a&&u.to===A||u.from===A&&u.to===a})||n.add(new t1({from:a,to:A}))}function A7o(t){for(const e of t._getMatchingPinAttributes())if(e.requiresGround===!0||e.providesGround===!0)return!0;for(const e of t.getNameAndAliases())if(Q0e.test(e))return!0;return!1}function c7o(t){return t._parsedProps.isGroundNet??Q0e.test(t._parsedProps.name)}function l7o(t){for(const e of t._getDirectlyConnectedTraces()){const n=e._findConnectedPorts().ports??[];for(const o of n)if(o!==t&&A7o(o))return!0;for(const o of e._findConnectedNets().nets)if(o&&c7o(o))return!0}return!1}function u7o(t){if(t.getParentNormalComponent()?.config.componentName!=="Chip")return!1;let e,n,o;for(const i of t._getMatchingPinAttributes())i.shouldHaveDecouplingCapacitor!==void 0&&(e=i.shouldHaveDecouplingCapacitor),i.requiresPower!==void 0&&(n=i.requiresPower),i.providesPower!==void 0&&(o=i.providesPower);if(e!==void 0)return e;if(n!==void 0)return n;if(o===!0)return!1;for(const i of t.getNameAndAliases())if(Hwe.test(i))return!0;return!1}function g7o(t){for(const e of t._getDirectlyConnectedTraces()){const n=e._findConnectedPorts().ports??[];for(const o of n)if(o!==t&&u7o(o))return!0}return!1}function Kwe(t){if(t.root?.pcbDisabled)return!1;if(t.pcb_port_id)return!0;const{db:e}=t.root,n=t.matchedComponents.filter(A=>A.isPcbPrimitive),o=n.length===1?n[0]._getPcbCircuitJsonBounds().center:n.length>1&&w0e(n)?Uwe(n):null;if(o){const A=e.pcb_port.insert({pcb_component_id:void 0,layers:t.getAvailablePcbLayers(),subcircuit_id:t.getSubcircuit()?.subcircuit_id??void 0,pcb_group_id:t.getGroup()?.pcb_group_id??void 0,...o,source_port_id:t.source_port_id,is_board_pinout:t.parent?.componentName==="Board"});return t.pcb_port_id=A.pcb_port_id,!0}const i=t._getConnectedPortsFromConnectsTo()[0];if(!i?.pcb_port_id)return!1;const r=e.pcb_port.get(i.pcb_port_id);if(!r)return!1;const s=t.getSubcircuit(),a=e.pcb_port.insert({pcb_component_id:void 0,layers:i.getAvailablePcbLayers(),subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:t.getGroup()?.pcb_group_id??void 0,x:r.x,y:r.y,source_port_id:t.source_port_id,is_board_pinout:!1});return t.pcb_port_id=a.pcb_port_id,!0}var CMt=(t,e)=>t.localeCompare(e,void 0,{numeric:!0,sensitivity:"base"}),yMt=(t,e)=>{const n=e.source_component_id?t.source_component.get(e.source_component_id):void 0,o=n?void 0:t.source_group.list().find(i=>i.subcircuit_id===e.subcircuit_id);return n?.name??o?.name},xMt=(t,e)=>{const n=t.source_port.get(e);if(!n?.name)return;const o=yMt(t,n);if(o)return`${o}_${n.name}`},Vwe=(t,e)=>{const n=e.map(r=>t.source_port.get(r)).filter(r=>!!r);if(n.length===0)return;const o=new Map;for(const r of t.source_port.list())r.source_component_id&&o.set(r.source_component_id,(o.get(r.source_component_id)??0)+1);const i=n.map(r=>{const s=yMt(t,r);return!s||!r.name?null:{sourcePort:r,ownerName:s,label:`${s}_${r.name}`,ownerPinCount:r.source_component_id?o.get(r.source_component_id)??0:0}}).filter(r=>!!r);return i.sort((r,s)=>{const a=s.ownerPinCount-r.ownerPinCount;if(a!==0)return a;const A=CMt(r.ownerName,s.ownerName);if(A!==0)return A;const c=r.sourcePort.pin_number??Number.POSITIVE_INFINITY,l=s.sourcePort.pin_number??Number.POSITIVE_INFINITY,u=c-l;return u!==0?u:CMt(r.sourcePort.name,s.sourcePort.name)}),i[0]?.label},d7o=.12,Pu=class extends Ir{source_port_id=null;pcb_port_id=null;schematic_port_id=null;schematic_stem_line_id=null;shouldCreateSourcePort;schematicSymbolPortDef=null;matchedComponents;_isPrimaryPort=!0;_primaryPinNumber=null;facingDirection=null;originDescription=null;get config(){return{componentName:"Port",zodProps:xDn}}constructor(t,e={}){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),e.originDescription&&(this.originDescription=e.originDescription),this.shouldCreateSourcePort=e.shouldCreateSourcePort??!0,this.matchedComponents=[]}isGroupPort(){return this.parent?.isGroup===!0}isComponentPort(){return!this.isGroupPort()}_getConnectedPortsFromConnectsTo(){const{_parsedProps:t}=this,e=t.connectsTo;if(!e)return[];const n=[],o=Array.isArray(e)?e:[e];for(const i of o){const r=this.getSubcircuit().selectOne(i,{type:"port"});r&&n.push(r)}return n}_isBoardPinoutFromAttributes(){const t=this.parent;if(t?._parsedProps?.pinAttributes){const e=t._parsedProps.pinAttributes;for(const n of this.getNameAndAliases())if(e[n]?.includeInBoardPinout)return!0}}_getGlobalPcbPositionBeforeLayout(){if(this.pcb_port_id){const n=this.root?.db.pcb_port.get(this.pcb_port_id);if(n?.pcb_component_id)return{x:n.x,y:n.y}}const t=this.matchedComponents.find(n=>n.isPcbPrimitive),e=this.parent;if(e&&!e.props.footprint)throw new Error(`${e.componentName} "${e.props.name}" does not have a footprint. Add a footprint prop, e.g. <${e.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();const{db:t}=this.root,e=t.pcb_port.get(this.pcb_port_id);return{center:{x:e.x,y:e.y},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getGlobalPcbPositionAfterLayout(){return this._getPcbCircuitJsonBounds().center}_getPortsInternallyConnectedToThisPort(){const t=this.parent;if(!t||!t._getInternallyConnectedPins)return[];const e=t._getInternallyConnectedPins();for(const n of e)if(n.some(o=>o===this))return n;return[]}_hasSchematicPort(){const t=this.getParentNormalComponent();if(t?._parsedProps?.noSchematicRepresentation===!0)return!1;const{schX:e,schY:n}=this._parsedProps;if(e!==void 0&&n!==void 0)return!0;if(t?.getSchematicSymbol())return!!(this.schematicSymbolPortDef||this._getPortsInternallyConnectedToThisPort().some(s=>s.schematicSymbolPortDef));const i=t?._getSchematicBoxDimensions();return!!(i&&this._parsedProps.pinNumber!==void 0&&i.getPortPositionByPinNumber(this._parsedProps.pinNumber))}_getGlobalSchematicPositionBeforeLayout(){const{schX:t,schY:e}=this._parsedProps;if(t!==void 0&&e!==void 0)return this._getSymbolAncestor()?ts(this.computeSchematicGlobalTransform(),{x:0,y:0}):{x:t,y:e};const n=this.getParentNormalComponent(),o=n?.getSchematicSymbol();if(o){let r=this.schematicSymbolPortDef;if(!r&&(r=this._getPortsInternallyConnectedToThisPort().find(a=>a.schematicSymbolPortDef)?.schematicSymbolPortDef??null,!r))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?`);const s=D0(n.computeSchematicGlobalTransform(),M0(-o.center.x,-o.center.y));return ts(s,r)}const i=n?._getSchematicBoxDimensions();if(i&&this._parsedProps.pinNumber!==void 0){const r=i.getPortPositionByPinNumber(this._parsedProps.pinNumber);if(!r)throw new Error(`Couldn't find position for schematic_port for port ${this.getString()} inside of the schematic box`);return ts(n.computeSchematicGlobalTransform(),r)}throw new Error(`Couldn't find position for schematic_port for port ${this.getString()}`)}_getGlobalSchematicPositionAfterLayout(){const{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`);const e=t.schematic_port.get(this.schematic_port_id);if(!e)throw new Error(`Schematic port not found when trying to get post-layout position: ${this.schematic_port_id}`);return e.center}registerMatch(t){this.matchedComponents.push(t)}getNameAndAliases(){const{_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(){const e=(this.getParentNormalComponent()??this.parent)?._parsedProps,n=e?.pinAttributes,o=e?.noConnect,i=[];for(const r of this.getNameAndAliases()){if(n){const s=n[r];s&&i.push(s)}o?.includes(r)&&i.push({doNotConnect:!0})}return i.length===0?[]:i}_shouldIncludeInBoardPinout(){return this._getMatchingPinAttributes().some(t=>t.includeInBoardPinout===!0)}isMatchingPort(t){return this.isMatchingAnyOf(t.getNameAndAliases())}getPortSelector(){return`.${(this.getParentNormalComponent()??this.parent)?.props.name} > port.${this.props.name}`}getAvailablePcbLayers(){const{layer:t,layers:e}=this._parsedProps;if(e)return e;if(t)return[t];if(this.pcb_port_id){const n=this.root?.db.pcb_port.get(this.pcb_port_id);if(n?.pcb_component_id)return n.layers}return Array.from(new Set(this.matchedComponents.flatMap(n=>n.getAvailablePcbLayers())))}_getDirectlyConnectedTraces(){const t=this.getSubcircuit().selectAll("trace"),e=[];for(const n of t)if(!n._couldNotFindPort)try{n._isExplicitlyConnectedToPort(this)&&e.push(n)}catch(o){if(o instanceof jN)continue;throw o}return e}isConnectedToPower(){return g7o(this)}isConnectedToGround(){return l7o(this)}doInitialCreateTracesFromProps(){a7o(this)}doInitialSourceRender(){if(!this.shouldCreateSourcePort)return;const{db:t}=this.root,{_parsedProps:e}=this,n=this.getNameAndAliases(),o=this.getParentNormalComponent(),r=(this.parent?.source_component_id?this.parent:o)?.source_component_id??null,s=this._getMatchingPinAttributes(),a={};for(const c of s)r7o(a,c);const A=t.source_port.insert({name:e.name,pin_number:e.pinNumber,port_hints:n,source_component_id:r,subcircuit_id:this.getSubcircuit()?.subcircuit_id,...a});this.source_port_id=A.source_port_id}doInitialSourceParentAttachment(){if(!this.shouldCreateSourcePort)return;const{db:t}=this.root,e=this.getParentNormalComponent(),n=this.parent?.source_component_id?this.parent:e;if(this.isGroupPort()){t.source_port.update(this.source_port_id,{source_component_id:null,subcircuit_id:this.getSubcircuit()?.subcircuit_id});return}if(!n?.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:n.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id}),this.source_component_id=n.source_component_id}doInitialPcbPortRender(){if(this.root?.pcbDisabled||this.getPrimitiveContainer()?.isSchematicPrimitive)return;const{db:t}=this.root,{matchedComponents:e}=this;if(this.isGroupPort()){Kwe(this);return}const n=this.getParentNormalComponent(),o=this.parent?.pcb_component_id?this.parent:n;if(!o?.pcb_component_id)throw new Error(`${this.getString()} has no parent pcb component, cannot render pcb_port (parent: ${this.parent?.getString()}, parentNormalComponent: ${n?.getString()})`);const i=e.filter(s=>s.isPcbPrimitive);if(i.length===0)return;let r=null;if(i.length===1&&(r=i[0]._getPcbCircuitJsonBounds().center),i.length>1){if(!w0e(i)){const s=this.props.name,a=this.getParentNormalComponent()?.props.name??"unknown",A=this.getNameAndAliases().filter(l=>l!==s),c=A.length>0?` (consider using alternate aliases: ${A.join(", ")})`:"";t.source_ambiguous_port_reference.insert({error_type:"source_ambiguous_port_reference",message:`${a}.${s} is ambiguous: ${a}.${s} references multiple non-overlapping pads: ${i.map(l=>l.getString()).join(", ")}${c}`,source_port_id:this.source_port_id??void 0,source_component_id:this.getParentNormalComponent()?.source_component_id??void 0});return}r=Uwe(i)}if(r){const s=this.getSubcircuit(),a=this._shouldIncludeInBoardPinout(),A=t.pcb_port.insert({pcb_component_id:o.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...a?{is_board_pinout:!0}:{},...r,source_port_id:this.source_port_id,is_board_pinout:this._isBoardPinoutFromAttributes()});this.pcb_port_id=A.pcb_port_id}else{const s=i[0];throw new Error(`${s.getString()} does not have a center or _getGlobalPcbPositionBeforeLayout method (needed for pcb_port placement)`)}}updatePcbPortRender(){if(this.root?.pcbDisabled||this.getPrimitiveContainer()?.isSchematicPrimitive)return;const{db:t}=this.root;if(this.pcb_port_id)return;if(this.isGroupPort()){Kwe(this);return}const e=this.matchedComponents.filter(A=>A.isPcbPrimitive);if(e.length===0)return;let n=null;if(e.length===1&&(n=e[0]._getPcbCircuitJsonBounds().center),e.length>1)try{w0e(e)&&(n=Uwe(e))}catch{}if(!n)return;const o=this.getParentNormalComponent(),i=this.parent?.pcb_component_id?this.parent:o,r=this.getSubcircuit(),s=this._shouldIncludeInBoardPinout(),a=t.pcb_port.insert({pcb_component_id:i?.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...s?{is_board_pinout:!0}:{},...n,source_port_id:this.source_port_id,is_board_pinout:this._isBoardPinoutFromAttributes()});this.pcb_port_id=a.pcb_port_id}doInitialPcbPortAttachment(){if(!this.pcb_port_id&&this.source_port_id){const t=this.root?.db.pcb_port.list({source_port_id:this.source_port_id}).find(e=>!!e.pcb_component_id);if(t){this.pcb_port_id=t.pcb_port_id;return}}!this.isGroupPort()||this.pcb_port_id||Kwe(this)}_getBestDisplayPinLabel(){const{db:t}=this.root,e=t.source_port.get(this.source_port_id),n=[];for(const r of e?.port_hints??[])r.match(/^(pin)?\d+$/)||r.match(/^(left|right)/)&&!e?.name.match(/^(left|right)/)||n.push(r);if(this.getParentNormalComponent()?.props?.showPinAliases&&n.length>0)return n.join("/");if(n.length>0)return n[0]}doInitialSchematicPortRender(){if(this.root?.schematicDisabled)return;const t=this.getCollapsedSchematicBoxAncestor();if(t&&this.parent!==t)return;const{db:e}=this.root,{_parsedProps:n}=this,{schX:o,schY:i}=n,r=o!==void 0&&i!==void 0?this.getParentNormalComponent():this.getPrimitiveContainer();if(!r||!this._hasSchematicPort())return;const s=r._getGlobalSchematicPositionBeforeLayout(),a=this._getGlobalSchematicPositionBeforeLayout();let A=null;const c=r._getSchematicBoxDimensions();c&&n.pinNumber!==void 0&&(A=c.getPortPositionByPinNumber(n.pinNumber)),this.getSubcircuit().props._schDebugObjectsEnabled&&e.schematic_debug_object.insert({shape:"rect",center:a,size:{width:.1,height:.1},label:"obstacle"});const l=o!==void 0&&i!==void 0&&!!this._getSymbolAncestor();l&&n.direction?this.facingDirection=n.direction:A?.side?this.facingDirection={left:"left",right:"right",top:"up",bottom:"down"}[A.side]:this.facingDirection=IMt(s,a);const u=this._getBestDisplayPinLabel(),g=this.getParentNormalComponent(),h=n.direction==="up"?"top":n.direction==="down"?"bottom":n.direction,p=(l&&n.direction?h:void 0)??A?.side??h,m=n.schPinLabelFontSize==="sm"?d7o:n.schPinLabelFontSize==="default"?void 0:n.schPinLabelFontSize,_={type:"schematic_port",schematic_component_id:g?.schematic_component_id,center:a,source_port_id:this.source_port_id,facing_direction:this.facingDirection,distance_from_component_edge:n.schStemLength??.4,side_of_component:p,pin_number:n.pinNumber,true_ccw_index:A?.trueIndex,display_pin_label:u,display_pin_label_font_size:m,is_connected:!1,schematic_sheet_id:this._resolveSchematicSheetId()};for(const I of this._getMatchingPinAttributes())I.requiresPower&&(_.has_input_arrow=!0),I.providesPower&&(_.has_output_arrow=!0);const f=e.schematic_port.insert(_);if(this.schematic_port_id=f.schematic_port_id,n.schStemLength!==void 0&&n.schStemLength!==0){const{schStemLength:I,direction:C}=n;let y=a.x,x=a.y;C==="right"?y-=I:C==="left"?y+=I:C==="up"?x-=I:C==="down"&&(x+=I);const E=e.schematic_line.insert({schematic_component_id:g?.schematic_component_id,x1:a.x,y1:a.y,x2:y,y2:x,stroke_width:.02,color:wb,is_dashed:!1,schematic_sheet_id:this._resolveSchematicSheetId()});this.schematic_stem_line_id=E.schematic_line_id}}doInitialSchematicSymbolResize(){if(this.root?.schematicDisabled||!this.schematic_port_id)return;const e=this._getSymbolAncestor()?.getUserCoordinateToResizedSymbolTransform();if(!e)return;const{db:n}=this.root,o=n.schematic_port.get(this.schematic_port_id);if(o){const i=ts(e,o.center);if(n.schematic_port.update(this.schematic_port_id,{center:i}),this.schematic_stem_line_id){const r=n.schematic_line.get(this.schematic_stem_line_id);if(r){const s=ts(e,{x:r.x1,y:r.y1}),a=ts(e,{x:r.x2,y:r.y2});n.schematic_line.update(this.schematic_stem_line_id,{x1:s.x,y1:s.y,x2:a.x,y2:a.y});const A=Math.sqrt((s.x-a.x)**2+(s.y-a.y)**2);n.schematic_port.update(this.schematic_port_id,{distance_from_component_edge:A})}}}}_getSubcircuitConnectivityKey(){return this.root?.db.source_port.get(this.source_port_id)?.subcircuit_connectivity_map_key}_setPositionFromLayout(t){const{db:e}=this.root;this.pcb_port_id&&e.pcb_port.update(this.pcb_port_id,{x:t.x,y:t.y})}_hasMatchedPcbPrimitive(){return!!(this.pcb_port_id?this.root?.db.pcb_port.get(this.pcb_port_id):null)?.pcb_component_id||this.matchedComponents.some(e=>e.isPcbPrimitive)}_getNetLabelText(){if(!(!this.root||!this.source_port_id))return xMt(this.root.db,this.source_port_id)}};function P0e(t){try{const e=t._getGlobalPcbPositionBeforeLayout(),n=t.getPcbSize();return{left:e.x-n.width/2,right:e.x+n.width/2,top:e.y+n.height/2,bottom:e.y-n.height/2}}catch{return null}}function EMt(t,e){const n=P0e(t),o=P0e(e);return!n||!o?!1:!(n.right<o.left||n.left>o.right||n.bottom>o.top||n.top<o.bottom)}function h7o(t,e){const n=P0e(t),o=P0e(e);return!n||!o?!1:n.left>=o.left&&n.right<=o.right&&n.bottom>=o.bottom&&n.top<=o.top}function p7o(t){const e=[],n=new Set;for(const o of t){if(n.has(o))continue;const i=[],r=[o];for(n.add(o);r.length>0;){const s=r.pop();i.push(s);for(const a of t)n.has(a)||EMt(s,a)&&(n.add(a),r.push(a))}e.push(i)}return e}var BMt=class extends Ir{pcb_via_id=null;matchedPort=null;isPcbPrimitive=!0;source_manually_placed_via_id=null;source_trace_id=null;subcircuit_connectivity_map_key=null;constructor(t){super(t);const e=this._getLayers();this._parsedProps.layers=e,this.initPorts()}get config(){return{componentName:"Via",zodProps:_lt}}getAvailablePcbLayers(){return this._getLayers()}_getResolvedViaDiameters(t){return t7o({holeDiameter:this._parsedProps.holeDiameter,padDiameter:this._parsedProps.outerDiameter},t)}getPcbSize(){const t=this.getInheritedMergedProperty("pcbStyle"),{padDiameter:e}=this._getResolvedViaDiameters(t);return{width:e,height:e}}_getPcbCircuitJsonBounds(){const{db:t}=this.root,e=t.pcb_via.get(this.pcb_via_id),n=this.getPcbSize();return{center:{x:e.x,y:e.y},bounds:{left:e.x-n.width/2,top:e.y-n.height/2,right:e.x+n.width/2,bottom:e.y+n.height/2},width:n.width,height:n.height}}_setPositionFromLayout(t){const{db:e}=this.root;e.pcb_via.update(this.pcb_via_id,{x:t.x,y:t.y})}_getLayers(){const{fromLayer:t="top",toLayer:e="bottom"}=this._parsedProps,n=this.parent?this.getSubcircuit()._getSubcircuitLayerCount():2;return lw({fromLayer:t,toLayer:e,layerCount:n})}initPorts(){const t=this._parsedProps.layers;for(const n of t){const o=new Pu({name:n,layer:n});o.registerMatch(this),this.add(o)}const e=new Pu({name:"pin1"});e.registerMatch(this),this.add(e)}_getConnectedNetOrTrace(){const t=this._parsedProps.connectsTo;if(!t)return this._getPortFromContainingPad()?._getDirectlyConnectedTraces()[0]??null;const e=this.getSubcircuit(),n=Array.isArray(t)?t:[t];for(const o of n)if(o.startsWith("net.")){const i=e.selectOne(o,{type:"net"});if(i)return i}return null}doInitialCreateNetsFromProps(){const t=this._parsedProps.connectsTo;t&&Hj(this,Array.isArray(t)?t:[t])}_getPortFromContainingPad(){if(this.parent?.componentName!=="Footprint")return null;const t=new Set(this.parent.children.filter(e=>e.componentName==="SmtPad").filter(e=>h7o(this,e)).map(e=>e.matchedPort).filter(e=>e!==null));return t.size===1?[...t][0]:null}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;const{db:t}=this.root,e=this.getInheritedMergedProperty("pcbStyle"),{padDiameter:n}=this._getResolvedViaDiameters(e),o=this._getGlobalPcbPositionBeforeLayout(),i=this.getSubcircuit(),r=t.pcb_component.insert({center:o,width:n,height:n,layer:this._parsedProps.fromLayer??"top",rotation:0,source_component_id:this.source_component_id,subcircuit_id:i?.subcircuit_id??void 0,obstructs_within_bounds:!0});this.pcb_component_id=r.pcb_component_id}doInitialSourceRender(){const{db:t}=this.root,e=this.getGroup(),n=this.getSubcircuit(),o=t.source_manually_placed_via.insert({source_group_id:e?.source_group_id,subcircuit_id:n?.subcircuit_id??void 0});this.source_manually_placed_via_id=o.source_manually_placed_via_id,this.source_component_id=o.source_manually_placed_via_id}doInitialSourceTraceRender(){const t=this._parsedProps.connectsTo;if(!t)return;const{db:e}=this.root,n=this.getSubcircuit(),o=Array.isArray(t)?t:[t],i=[],r=[];for(const s of o){if(s.startsWith("net.")){const A=n.selectOne(s,{type:"net"});if(!A?.source_net_id){this.renderError(`Could not find net for via selector "${s}"`);return}r.push(A);continue}const a=n.selectOne(s,{type:"port"})??this.getParentNormalComponent()?.children.find(A=>A instanceof Pu&&A.isMatchingAnyOf([s]))??null;if(!a?.source_port_id){this.renderError(`Could not find port for via selector "${s}"`);return}i.push(a)}if(i.length>0){const s=e.source_trace.insert({connected_source_port_ids:i.map(a=>a.source_port_id),connected_source_net_ids:r.map(a=>a.source_net_id),subcircuit_id:n.subcircuit_id??void 0,display_name:this._parsedProps.name?`${this._parsedProps.name} connectivity`:"Manually placed via connectivity"});this.source_trace_id=s.source_trace_id}e.source_manually_placed_via.update(this.source_manually_placed_via_id,{source_net_id:r[0]?.source_net_id,source_trace_id:this.source_trace_id??void 0})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;const{db:t}=this.root,e=this.getInheritedMergedProperty("pcbStyle"),{holeDiameter:n,padDiameter:o}=this._getResolvedViaDiameters(e),i=this._getGlobalPcbPositionBeforeLayout(),r=this.getSubcircuit(),s=this._getConnectedNetOrTrace(),a=this.source_trace_id??(s instanceof Qb?void 0:s?.source_trace_id),A=!a&&s instanceof Qb?s.source_net_id:void 0,c=t.pcb_via.insert({x:i.x,y:i.y,hole_diameter:n,outer_diameter:o,layers:this._getLayers(),from_layer:this._parsedProps.fromLayer||"bottom",to_layer:this._parsedProps.toLayer||"top",subcircuit_id:r?.subcircuit_id??void 0,subcircuit_connectivity_map_key:this.subcircuit_connectivity_map_key??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,net_is_assignable:this._parsedProps.netIsAssignable??void 0,...a?{source_trace_id:a}:{},...A?{source_net_id:A}:{}});this.pcb_via_id=c.pcb_via_id}};function m7o(t){if(t.root?.schematicDisabled)return;const{db:e}=t.root,{_parsedProps:n,parent:o}=t;if(!o)throw new Error("Trace has no parent");const{allPortsFound:i,portsWithSelectors:r}=t._findConnectedPorts();if(!i)return;const s=r.map(({port:C})=>({port:C,position:C._getGlobalSchematicPositionAfterLayout(),schematic_port_id:C.schematic_port_id,facingDirection:C.facingDirection}));if(s.length<2)throw new Error("Expected at least two ports in portsWithPosition.");let a,A;const c=s[0].position,l=s[0].port;if("path"in t.props){if(t.props.path.length!==2)throw new Error("Invalid 'path': Must contain exactly two elements.");[a,A]=t.props.path}else{if(!("from"in t.props&&"to"in t.props))throw new Error("Missing 'from' or 'to' properties in props.");a=t.props.from,A=t.props.to}if(!l.source_port_id)throw new Error(`Missing source_port_id for the 'from' port (${a}).`);const u=s[1].position,g=s[1].port;if(!g.source_port_id)throw new Error(`Missing source_port_id for the 'to' port (${A}).`);const h=e.schematic_net_label.list().find(C=>C.source_net_id===l.source_port_id),d=e.schematic_net_label.list().find(C=>C.source_net_id===g.source_port_id),[p,m]=r.map(({port:C})=>C),f=p.parent?.config.shouldRenderAsSchematicBox?`${p?.parent?.props.name}_${p?.props.name}`:`${m?.parent?.props.name}_${m?.props.name}`,I=t._getSchematicNetLabelText()??f;if(h&&h.text!==I&&(h.text=`${I} / ${h.text}`),d&&d?.text!==I&&(d.text=`${I} / ${d.text}`),!d){const C=gO(g.facingDirection)??"bottom";e.schematic_net_label.insert({text:I,source_net_id:g.source_port_id,anchor_position:u,center:j7({anchor_position:u,anchor_side:C,text:I}),anchor_side:C,schematic_sheet_id:t._resolveSchematicSheetId()})}if(!h){const C=gO(l.facingDirection)??"bottom";e.schematic_net_label.insert({text:I,source_net_id:l.source_port_id,anchor_position:c,center:j7({anchor_position:c,anchor_side:C,text:I}),anchor_side:C,schematic_sheet_id:t._resolveSchematicSheetId()})}}function _7o(t){const{_parsedProps:e,parent:n}=t;if(!n)throw new Error("Trace has no parent");const o=t.getTracePortPathSelectors(),i=s=>{if(s.lastIndexOf(".")>s.lastIndexOf(" "))return null;let A=t.getSubcircuit().selectOne(s);if(!A&&!/[.#\[]/.test(s)&&(A=t.getSubcircuit().selectOne(`.${s}`)),!A)return null;const c=A.children.filter(l=>l.componentName==="Port");return c.length===1?c[0]:null},r=o.map(s=>({selector:s,port:t.getSubcircuit().selectOne(s,{type:"port"})??i(s)}));for(const{selector:s,port:a}of r)if(!a){let A,c;const l=s.lastIndexOf(".");if(l!==-1&&l>s.lastIndexOf(" "))A=s.slice(0,l),c=s.slice(l+1);else{const y=s.match(/^(.*[ >])?([^ >]+)$/);A=y?.[1]?.trim()??"",c=y?.[2]??s}let u=A?t.getSubcircuit().selectOne(A):null;if(!u&&A&&!/[.#\[]/.test(A)&&(u=t.getSubcircuit().selectOne(`.${A}`)),!u){const y=A?`Could not find port for selector "${s}". Component "${A}" not found`:`Could not find port for selector "${s}"`,x=t.getSubcircuit(),E=x.getGroup();throw new jN({error_type:"source_trace_not_connected_error",message:y,subcircuit_id:x.subcircuit_id??void 0,source_group_id:E?.source_group_id??void 0,source_trace_id:t.source_trace_id??void 0,selectors_not_found:[s]})}const g=u.children.filter(y=>y.componentName==="Port"),h=c.includes(".")?c.split(".").pop()??"":c,d=g.flatMap(y=>y.getNameAndAliases()),p=d.some(y=>!/^(pin\d+|\d+)$/.test(y)),m=Array.from(new Set(d)).join(", ");let _;g.length===0?_="It has no ports":p?_=`It has [${m}]`:_=`It has ${g.length} pins and no pinLabels (consider adding pinLabels)`;const f=`Could not find port for selector "${s}". Component "${u.props.name??A}" found, but does not have pin "${h}". ${_}`,I=t.getSubcircuit(),C=I.getGroup();throw new jN({error_type:"source_trace_not_connected_error",message:f,subcircuit_id:I.subcircuit_id??void 0,source_group_id:C?.source_group_id??void 0,source_trace_id:t.source_trace_id??void 0,selectors_not_found:[s]})}return r.some(s=>!s.port)?{allPortsFound:!1}:{allPortsFound:!0,portsWithSelectors:r,ports:r.map(({port:s})=>s)}}function zwe(t){let e=0;for(let n=0;n<t.length;n++){const o=t[n];if(o.route_type==="wire"){const i=t[n+1];if(i){const r=W7(i),s=W7(o),a=r.x-s.x,A=r.y-s.y;e+=Math.sqrt(a*a+A*A)}}else o.route_type==="via"&&(e+=1.6)}return e}function bMt(t){const{lineStart:e,lineEnd:n,rectCenter:o,rectWidth:i,rectHeight:r}=t,s=o.x-i/2,a=o.x+i/2,A=o.y+r/2,c=o.y-r/2,l=n.x-e.x,u=n.y-e.y,g=[];if(l!==0){const h=(s-e.x)/l;if(h>=0&&h<=1){const d=e.y+h*u;d>=c&&d<=A&&g.push({x:s,y:d,t:h})}}if(l!==0){const h=(a-e.x)/l;if(h>=0&&h<=1){const d=e.y+h*u;d>=c&&d<=A&&g.push({x:a,y:d,t:h})}}if(u!==0){const h=(c-e.y)/u;if(h>=0&&h<=1){const d=e.x+h*l;d>=s&&d<=a&&g.push({x:d,y:c,t:h})}}if(u!==0){const h=(A-e.y)/u;if(h>=0&&h<=1){const d=e.x+h*l;d>=s&&d<=a&&g.push({x:d,y:A,t:h})}}return g.length===0?null:(g.sort((h,d)=>h.t-d.t),{x:g[0].x,y:g[0].y})}function SMt(t){const{lineStart:e,lineEnd:n,circleCenter:o,circleRadius:i}=t,r=e.x-o.x,s=e.y-o.y,a=n.x-o.x,A=n.y-o.y,c=a-r,l=A-s,u=c*c+l*l,g=2*(r*c+s*l),h=r*r+s*s-i*i,d=g*g-4*u*h;if(d<0)return null;const p=Math.sqrt(d),m=(-g-p)/(2*u),_=(-g+p)/(2*u);let f=null;return m>=0&&m<=1?f=m:_>=0&&_<=1&&(f=_),f===null?null:{x:e.x+f*c,y:e.y+f*l}}function QMt(t){const{traceStart:e,traceEnd:n,traceWidth:o,port:i}=t,r=i.matchedComponents.find(g=>g.isPcbPrimitive);if(!r)return n;const s=r._getPcbCircuitJsonBounds(),a=s.width,A=s.height,c=s.center,l=Math.min(a,A);if(o<=l/2)return n;let u=null;if(r.componentName==="SmtPad"){const g=r,h=g._parsedProps.shape;if(h==="circle"){const d=g._parsedProps.radius;u=SMt({lineStart:e,lineEnd:n,circleCenter:c,circleRadius:d})}else(h==="rect"||h==="rotated_rect"||h==="pill"||h==="polygon")&&(u=bMt({lineStart:e,lineEnd:n,rectCenter:c,rectWidth:a,rectHeight:A}))}else if(r.componentName==="PlatedHole"){const g=r;if(g._parsedProps.shape==="circle"){const d=g._parsedProps.outerDiameter;u=SMt({lineStart:e,lineEnd:n,circleCenter:c,circleRadius:d/2})}else u=bMt({lineStart:e,lineEnd:n,rectCenter:c,rectWidth:a,rectHeight:A})}return u??n}function vMt(t){const n=(t._parsedProps?.portHints??[]).filter(Boolean);return n.length>0?`<${t.lowercaseComponentName}(${n.map(o=>`.${o}`).join(", ")}) />`:`<${t.lowercaseComponentName} />`}function Jwe(t,e){const n=e.matchedComponents.filter(a=>a.isPcbPrimitive),o=e.getParentNormalComponent()?.props.name??e.parent?.props.name??"unknown",i=e.getParentNormalComponent(),r=t.trim().split(/\s+|>/).filter(Boolean).at(-1)?.replace(/^port\./,"").replace(/^\./,"");if(r&&!/^(pin)?\d+$/.test(r)){const a=(i?.children??[]).filter(A=>A.componentName==="Port"&&A.isMatchingAnyOf([r]));if(a.length>1&&!(i?._getInternallyConnectedPins?.()??[]).some(l=>a.every(u=>l.includes(u)))){const l=Array.from(new Set(a.flatMap(h=>h.getNameAndAliases().filter(d=>/^pin\d+$/.test(d)).map(d=>`${o}.${d}`)))),u=l.length>0?` Use a raw pin selector like ${l.map(h=>`"${h}"`).join(" or ")}.`:"",g=a.flatMap(h=>h.matchedComponents.filter(d=>d.isPcbPrimitive));return`Trace selector "${t}" resolved to "${o}.${e.props.name}", but alias "${r}" matches multiple PCB pads: ${g.map(h=>vMt(h)).join(", ")}.${u}`}}if(e.pcb_port_id)return null;const s=Array.from(new Set(e.getNameAndAliases().filter(a=>/^pin\d+$/.test(a)).map(a=>`${o}.${a}`)));if(n.length>1&&!w0e(n)){const a=s.length>0?` Use a raw pin selector like ${s.map(A=>`"${A}"`).join(" or ")}.`:"";return`Trace selector "${t}" resolved to "${o}.${e.props.name}", but that target maps to multiple non-overlapping PCB pads: ${n.map(A=>vMt(A)).join(", ")}.${a}`}return null}var EB={min_trace_width:.1,min_via_hole_edge_to_via_hole_edge_clearance:.1,min_plated_hole_drill_edge_to_drill_edge_clearance:.15,min_trace_to_pad_edge_clearance:.1,min_pad_edge_to_pad_edge_clearance:.1,min_board_edge_clearance:.2,min_via_hole_diameter:.2,min_via_pad_diameter:.3},f7o=(t,e)=>{if(e.route_type==="via")return t?.find(n=>Math.abs(n.x-e.x)<1e-4&&Math.abs(n.y-e.y)<1e-4&&(!n.from_layer||n.from_layer===e.from_layer)&&(!n.to_layer||n.to_layer===e.to_layer))},I7o=t=>{const e=t;return{holeDiameter:e.hole_diameter??e.via_hole_diameter,outerDiameter:e.outer_diameter??e.via_diameter}};function C7o(t){if(t.root?.pcbDisabled)return;const{db:e}=t.root,{_parsedProps:n}=t,o=t.getSubcircuit(),i=n.pcbPath!==void 0,r=!!n.pcbStraightLine,s=t._inflatedPcbTraces??[];if(!i&&!r&&s.length===0)return;let a,A,c;try{const M=t._findConnectedPorts();a=M.allPortsFound,A=M.ports??[],c=M.portsWithSelectors??[]}catch(M){if(M instanceof jN){e.source_trace_not_connected_error.insert({...M.errorData,error_type:"source_trace_not_connected_error"}),t._couldNotFindPort=!0;return}throw M}if(!a)return;const l=c.map(({selector:M,port:k})=>Jwe(M,k)).find(Boolean);if(l){e.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:t.source_trace_id,message:l,pcb_trace_id:t.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:A.map(M=>M.pcb_port_id).filter(Boolean)});return}const u=[];for(const M of A)M._hasMatchedPcbPrimitive()||u.push(M);if(u.length>0){e.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:t.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, ${t} wasn't routed. Missing ports: ${u.map(M=>M.getString()).join(", ")}`,pcb_trace_id:t.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:u.map(M=>M.pcb_port_id).filter(Boolean)});return}const g=t._getExplicitTraceThickness()??t.getSubcircuit()._parsedProps.minTraceWidth??EB.min_trace_width;if(s.length>0){const{isFlipped:M,maybeFlipLayer:k}=t._getPcbPrimitiveFlippedHelpers(),R=t._computePcbGlobalTransformBeforeLayout(),F=[],O=t.subcircuit_connectivity_map_key??e.source_trace.get(t.source_trace_id)?.subcircuit_connectivity_map_key;for(const U of s){const Y=U.route.map(oe=>{if(oe.route_type==="wire"){const{x:ie,y:ne,...le}=oe,ge=ts(R,{x:ie,y:ne});return{...le,...ge,layer:k(oe.layer)}}if(oe.route_type==="via"){const{x:ie,y:ne,...le}=oe,ge=ts(R,{x:ie,y:ne});return{...le,...ge,from_layer:k(oe.from_layer),to_layer:k(oe.to_layer)}}return{...oe,start:ts(R,oe.start),end:ts(R,oe.end),start_layer:k(oe.start_layer),end_layer:k(oe.end_layer)}}),W=e.pcb_trace.insert({...U,route:Y,source_trace_id:t.source_trace_id,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:t.getGroup()?.pcb_group_id??void 0}),te=t.getInheritedMergedProperty("pcbStyle"),{holeDiameter:j,padDiameter:J}=$N(te);for(let oe=0;oe<Y.length;oe++){const ie=Y[oe];if(ie.route_type==="via"){const ne=U.route[oe],le=f7o(t._inflatedPcbVias,ne),ge=le?Sne.parse(le):void 0,_e=I7o(ie),ue=k(ge?.from_layer??ie.from_layer),fe=k(ge?.to_layer??ie.to_layer),pe=(ge?.layers??lw({fromLayer:ie.from_layer,toLayer:ie.to_layer,layerCount:o._getSubcircuitLayerCount()})).map(ye=>k(ye));e.pcb_via.insert({pcb_trace_id:W.pcb_trace_id,x:ie.x,y:ie.y,hole_diameter:ge?.hole_diameter??_e.holeDiameter??j,outer_diameter:ge?.outer_diameter??_e.outerDiameter??J,layers:pe,from_layer:ue,to_layer:fe,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:t.getGroup()?.pcb_group_id??void 0,subcircuit_connectivity_map_key:ge?.subcircuit_connectivity_map_key??O,net_is_assignable:ge?.net_is_assignable,net_assigned:ge?.net_assigned,tented_on_top:M?ge?.tented_on_bottom:ge?.tented_on_top,tented_on_bottom:M?ge?.tented_on_top:ge?.tented_on_bottom})}}t.pcb_trace_id||(t.pcb_trace_id=W.pcb_trace_id),F.push(W.route)}for(const U of F)t._insertErrorIfTraceIsOutsideBoard(U,A);t._portsRoutedOnPcb=A;return}if(r&&!i){if(!A||A.length<2){t.renderError("pcbStraightLine requires exactly two connected ports");return}const[M,k]=A,R=M.getAvailablePcbLayers(),F=k.getAvailablePcbLayers(),U=R.find(ne=>F.includes(ne))??R[0]??F[0]??"top",Y=M._getGlobalPcbPositionAfterLayout(),W=k._getGlobalPcbPositionAfterLayout(),te=QMt({traceStart:W,traceEnd:Y,traceWidth:g,port:M}),j=QMt({traceStart:Y,traceEnd:W,traceWidth:g,port:k}),J=[{route_type:"wire",x:te.x,y:te.y,width:g,layer:U,start_pcb_port_id:M.pcb_port_id},{route_type:"wire",x:j.x,y:j.y,width:g,layer:U,end_pcb_port_id:k.pcb_port_id}],oe=zwe(J),ie=e.pcb_trace.insert({route:J,source_trace_id:t.source_trace_id,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:t.getGroup()?.pcb_group_id??void 0,trace_length:oe});t._portsRoutedOnPcb=A,t.pcb_trace_id=ie.pcb_trace_id,t._insertErrorIfTraceIsOutsideBoard(J,A);return}if(!n.pcbPath)return;let h;n.pcbPathRelativeTo&&(h=c.find(M=>M.selector===n.pcbPathRelativeTo)?.port,h||(h=t.getSubcircuit().selectOne(n.pcbPathRelativeTo))),h||(h=A[0]);const d=A.find(M=>M!==h)??A[1];let m=h.getAvailablePcbLayers()[0]||"top";const _=h._getGlobalPcbPositionAfterLayout(),f=d?._getGlobalPcbPositionAfterLayout(),I=[];I.push({route_type:"wire",x:_.x,y:_.y,width:g,layer:m,start_pcb_port_id:h.pcb_port_id});const C=o._isInflatedFromCircuitJson?t._computePcbGlobalTransformBeforeLayout():h?._computePcbGlobalTransformBeforeLayout?.()||hC(),y=n.pcbPath;for(const M of y){let k,R=!1;const F=typeof M!="string"&&M.via;let O,U;if(typeof M=="string"){const W=t.getSubcircuit().selectOne(M,{type:"port"});if(!W){e.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:t.source_trace_id,message:`Could not resolve pcbPath selector "${M}" for ${t}`,pcb_trace_id:t.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:[]});continue}const te=Jwe(M,W);if(te){e.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:t.source_trace_id,message:te,pcb_trace_id:t.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:[]});return}const j=W._getGlobalPcbPositionAfterLayout();k={x:j.x,y:j.y},R=!0}else k={x:M.x,y:M.y},R=!1,M.via&&(O=M.fromLayer??m,U=M.toLayer);const Y=R?k:ts(C,k);F?(I.push({route_type:"via",x:Y.x,y:Y.y,from_layer:O??m,to_layer:U??m}),m=U??m):I.push({route_type:"wire",x:Y.x,y:Y.y,width:g,layer:m})}d&&f&&I.push({route_type:"wire",x:f.x,y:f.y,width:g,layer:m,end_pcb_port_id:d.pcb_port_id});const x=zwe(I),E=e.pcb_trace.insert({route:I,source_trace_id:t.source_trace_id,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:t.getGroup()?.pcb_group_id??void 0,trace_length:x}),B=t.subcircuit_connectivity_map_key??e.source_trace.get(t.source_trace_id)?.subcircuit_connectivity_map_key,S=t.getInheritedMergedProperty("pcbStyle"),{holeDiameter:Q,padDiameter:w}=$N(S);for(const M of I)if(M.route_type==="via"){const k=M.from_layer,R=M.to_layer;e.pcb_via.insert({pcb_trace_id:E.pcb_trace_id,x:M.x,y:M.y,hole_diameter:Q,outer_diameter:w,layers:lw({fromLayer:k,toLayer:R,layerCount:o._getSubcircuitLayerCount()}),from_layer:k,to_layer:R,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:t.getGroup()?.pcb_group_id??void 0,subcircuit_connectivity_map_key:B})}t._portsRoutedOnPcb=A,t.pcb_trace_id=E.pcb_trace_id,t._insertErrorIfTraceIsOutsideBoard(I,A)}var Wwe=t=>t.map(e=>{const{circuitJsonMetadata:n,...o}=e;if(o.route_type!=="via")return o;const{layers:i,...r}=o;return r}),jwe=({component:t,subcircuit:e})=>{t._pcbTraceRenderWaitingForPlacementChecks=!1;let n=t,o=0,i=null,r=!1;for(;n;){if("_pcbPlacementDrcErrorCount"in n){if("_pcbPlacementDrcChecksPending"in n&&n._pcbPlacementDrcChecksPending===!0){r=!0;break}if(typeof n._pcbPlacementDrcErrorCount=="number"){o=n._pcbPlacementDrcErrorCount;break}if("_pcbPlacementDrcCheckError"in n&&typeof n._pcbPlacementDrcCheckError=="string"){i=n._pcbPlacementDrcCheckError;break}}n=n.parent}if(r)return t._pcbTraceRenderWaitingForPlacementChecks=!0,!0;if(o===0&&!i)return!1;const{db:s}=t.root,a=`pcb_autorouting_skipped_placement_errors_${e.subcircuit_id}`;return s.pcb_autorouting_error.list().some(c=>c.pcb_error_id===a)||s.pcb_autorouting_error.insert({pcb_error_id:a,error_type:"pcb_autorouting_error",subcircuit_id:e.subcircuit_id??void 0,message:i?`Autorouting was skipped because PCB placement checks could not be completed: ${i}`:`Autorouting was skipped because ${o} PCB placement error${o===1?" was":"s were"} found. Fix the placement errors or set placementDrcChecksDisabled to true to route anyway.`}),!0},y7o=1e-6,x7o=t=>{let e=0;for(let n=0;n<t.length;n++){const o=t[n];for(let i=n+1;i<t.length;i++){const r=t[i];e=Math.max(e,Math.hypot(r.x-o.x,r.y-o.y))}}return e},E7o=(t,e)=>{let n=Number.POSITIVE_INFINITY;for(const o of t)for(const i of e)n=Math.min(n,Math.hypot(i.x-o.x,i.y-o.y));return n},B7o=({component:t,subcircuit:e})=>{const{db:n}=t.root,o=n.source_trace.list().filter(a=>a.subcircuit_id===e.subcircuit_id),i=new wQ({});i.addConnections(o.map(a=>[a.source_trace_id,...a.connected_source_port_ids,...a.connected_source_net_ids]));const r=new Map;for(const a of n.pcb_port.list())typeof a.source_port_id!="string"||typeof a.x!="number"||typeof a.y!="number"||r.set(a.source_port_id,{pcb_port_id:a.pcb_port_id,source_port_id:a.source_port_id,x:a.x,y:a.y});const s=[];for(const a of o){if(typeof a.max_length!="number")continue;const A=a.connected_source_port_ids.map(l=>r.get(l)).filter(l=>!!l);let c;if(A.length>=2)c=x7o(A);else{if(A.length!==1||a.connected_source_net_ids.length===0)continue;const l=i.getNetConnectedToId(a.source_trace_id);if(!l)continue;const g=i.getIdsConnectedToNet(l).filter(d=>!a.connected_source_port_ids.includes(d)&&r.has(d)).map(d=>r.get(d)).filter(d=>!!d);if(g.length===0||n.toArray().some(d=>(d.type==="source_pcb_ground_plane"||d.type==="pcb_ground_plane"||d.type==="pcb_copper_pour")&&typeof d.source_net_id=="string"&&i.areIdsConnected(a.source_trace_id,d.source_net_id)))continue;c=E7o(A,g)}c<=a.max_length+y7o||s.push({sourceTraceId:a.source_trace_id,traceDisplayName:a.display_name,straightLineDistance:c,maximumTraceLength:a.max_length})}return s},$we=({component:t,subcircuit:e})=>{const n=B7o({component:t,subcircuit:e});if(n.length===0)return!1;const{db:o}=t.root,i=`pcb_autorouting_skipped_trace_length_violations_${e.subcircuit_id}`;if(!o.pcb_autorouting_error.list().some(s=>s.pcb_error_id===i)){const s=n[0],a=s.traceDisplayName??s.sourceTraceId,A=n.length-1,c=A>0?` (${A} additional violation${A===1?"":"s"})`:"";o.pcb_autorouting_error.insert({pcb_error_id:i,error_type:"pcb_autorouting_error",subcircuit_id:e.subcircuit_id??void 0,message:`Autorouting was skipped because the ${s.maximumTraceLength}mm maximum length for ${a} cannot be satisfied: its endpoints are ${s.straightLineDistance.toFixed(2)}mm apart${c}.`})}return!0},M0e=t=>({...t._getGlobalPcbPositionAfterLayout(),layers:t.getAvailablePcbLayers()}),wMt=(t,e)=>{const n=W7(t);return Math.hypot(n.x-e.x,n.y-e.y)},b7o=(t,e)=>{if(t.length<2)return t;const n=t[0],o=t[t.length-1];return wMt(o,e)<wMt(n,e)?B0e(t):t};function S7o(t){if(t.root?.pcbDisabled)return;const{db:e}=t.root,{_parsedProps:n,parent:o}=t,i=t.getSubcircuit(),r=t._getBoard(),s=r?.pcb_board_id?e.pcb_board.get(r.pcb_board_id):void 0;if(!o)throw new Error("Trace has no parent");if(t.root?.pcbRoutingDisabled||i.getInheritedProperty("routingDisabled")||i._isInflatedFromCircuitJson)return;const a=i._parsedProps.pcbRouteCache?.pcbTraces;if(a){if(i._isLegacyAutorouterDisabled())return;const Y=e.pcb_trace.insert({route:a.flatMap(W=>W.route),source_trace_id:t.source_trace_id,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:t.getGroup()?.pcb_group_id??void 0});t.pcb_trace_id=Y.pcb_trace_id;return}if(n.pcbPath&&n.pcbPath.length>0||n.pcbStraightLine||!i._shouldUseTraceByTraceRouting())return;let A,c,l;try{const Y=t._findConnectedPorts();A=Y.allPortsFound,c=Y.ports??[],l=Y.portsWithSelectors??[]}catch(Y){if(Y instanceof jN){e.source_trace_not_connected_error.insert({...Y.errorData,error_type:"source_trace_not_connected_error"}),t._couldNotFindPort=!0;return}throw Y}if(!A)return;const u=l.map(({selector:Y,port:W})=>Jwe(Y,W)).find(Boolean);if(u){e.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:t.source_trace_id,message:u,pcb_trace_id:t.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:c.map(Y=>Y.pcb_port_id).filter(Boolean)});return}const g=[];for(const Y of c)Y._hasMatchedPcbPrimitive()||g.push(Y);if(g.length>0){e.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:t.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, ${t} wasn't routed. Missing ports: ${g.map(Y=>Y.getString()).join(", ")}`,pcb_trace_id:t.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:g.map(Y=>Y.pcb_port_id).filter(Boolean)});return}const h=jwe({component:t,subcircuit:i}),d=$we({component:t,subcircuit:i});if(h||d)return;const p=t._findConnectedNets().netsWithSelectors;if(c.length===0&&p.length===2){const[Y,W]=p.map(({net:ie})=>ie),te=Y.getAllConnectedPorts(),j=W.getAllConnectedPorts();if(te.length===0||j.length===0){console.log("Nothing to connect this net to, one of the nets is empty. TODO should emit a warning!");return}let J=[te[0],j[0]],oe=1/0;for(const ie of te){const ne=dMt(ie,j),le=ie._getGlobalPcbPositionBeforeLayout(),ge=ne._getGlobalPcbPositionBeforeLayout(),_e=Math.sqrt((le.x-ge.x)**2+(le.y-ge.y)**2);_e<oe&&(oe=_e,J=[ie,ne])}c.push(...J)}else if(c.length===1&&p.length===1){const Y=c[0],te=p[0].net.getAllConnectedPorts().filter(J=>J!==Y);if(te.length===0){console.log("Nothing to connect this port to, the net is empty. TODO should emit a warning!");return}const j=dMt(Y,te);c.push(j)}else if(c.length>1&&p.length>=1){t.renderError("Trace has more than one port and one or more nets, we don't currently support this type of complex trace routing");return}const m=c.flatMap(Y=>Y.matchedComponents.filter(W=>W.componentName==="TraceHint")),_=(t._parsedProps.pcbRouteHints??[]).concat(m.flatMap(Y=>Y.getPcbRouteHints()));if(c.length>2){t.renderError(`Trace has more than two ports (${c.map(Y=>Y.getString()).join(", ")}), routing between more than two ports for a single trace is not implemented`);return}if(t.getSubcircuit().selectAll("trace").filter(Y=>Y.renderPhaseStates.PcbTraceRender.initialized).some(Y=>Y._portsRoutedOnPcb.length===c.length&&Y._portsRoutedOnPcb.every(W=>c.includes(W))))return;let C=[];_.length===0?C=[M0e(c[0]),M0e(c[1])]:C=[M0e(c[0]),..._,M0e(c[1])];const y=b9o(C,{layerSelectionPreference:Owe(i._getSubcircuitLayerCount())}),x=Vf(t.root.db.toArray()),[E,B]=q9o(()=>_Mt(t.root.db.toArray()));if(B){t.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:t.pcb_trace_id,message:`Error getting obstacles for autorouting: ${B.message}`,source_trace_id:t.source_trace_id,center:{x:0,y:0},pcb_port_ids:c.map(Y=>Y.pcb_port_id),pcb_trace_id:t.pcb_trace_id,pcb_component_ids:[]});return}for(const Y of E)if(Y.connectedTo.length>0){const te=x.getNetConnectedToId(Y.connectedTo[0]);te&&Y.connectedTo.push(te)}let S=[];if(y.length===0)S=C;else{const Y=y[0].layer_path;S=C.map((W,te)=>W.via?{...W,via_to_layer:Y[te]}:{...W,layers:[Y[te]]})}S[0].pcb_port_id=c[0].pcb_port_id,S[S.length-1].pcb_port_id=c[1].pcb_port_id;const Q=[];for(const[Y,W]of gMt(S)){const te="via_to_layer"in Y?Y.via_to_layer:null,j=2,J="layers"in Y&&Y.layers.length===1?Y.layers[0]:te??"top",oe="layers"in W&&W.layers.length===1?W.layers[0]:te??"top",ie="pcb_port_id"in Y?Y.pcb_port_id:null,ne="pcb_port_id"in W?W.pcb_port_id:null,le=t._getExplicitTraceThickness()??t.getSubcircuit()._parsedProps.minTraceWidth??EB.min_trace_width,ge=new Vct({OBSTACLE_MARGIN:le*2,isRemovePathLoopsEnabled:!0,optimizeWithGoalBoxes:!!(ie&&ne),connMap:x,input:{obstacles:E,minTraceWidth:le,connections:[{name:t.source_trace_id,pointsToConnect:[{...Y,layer:J,pcb_port_id:ie},{...W,layer:oe,pcb_port_id:ne}]}],layerCount:t.getSubcircuit()._getSubcircuitLayerCount(),bounds:{minX:Math.min(Y.x,W.x)-j,maxX:Math.max(Y.x,W.x)+j,minY:Math.min(Y.y,W.y)-j,maxY:Math.max(Y.y,W.y)+j}}});let _e=null;try{_e=ge.solveAndMapToTraces()}catch(pe){t.renderError({type:"pcb_trace_error",pcb_trace_error_id:t.source_trace_id,error_type:"pcb_trace_error",message:`error solving route: ${pe.message}`,source_trace_id:t.pcb_trace_id,center:{x:(Y.x+W.x)/2,y:(Y.y+W.y)/2},pcb_port_ids:c.map(ye=>ye.pcb_port_id),pcb_trace_id:t.pcb_trace_id,pcb_component_ids:c.map(ye=>ye.pcb_component_id)})}if(!_e)return;if(_e.length===0){t.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:t.pcb_trace_id,message:`Could not find a route for ${t}`,source_trace_id:t.source_trace_id,center:{x:(Y.x+W.x)/2,y:(Y.y+W.y)/2},pcb_port_ids:c.map(pe=>pe.pcb_port_id),pcb_trace_id:t.pcb_trace_id,pcb_component_ids:c.map(pe=>pe.pcb_component_id)});return}const[ue]=_e;ue.route=b7o(ue.route,Y),te&&(ue.route=ue.route.map(pe=>(pe.route_type==="wire"&&!pe.layer&&(pe.layer=te),pe))),ie&&ue.route[0].route_type==="wire"&&(ue.route[0].start_pcb_port_id=ie);const fe=ue.route[ue.route.length-1];ne&&fe.route_type==="wire"&&(fe.end_pcb_port_id=ne),Q.push(ue.route)}const w=Q9o(Q),M=zwe(w),k=t.getInheritedMergedProperty("pcbStyle"),{holeDiameter:R,padDiameter:F}=$N(k),O=e.pcb_trace.insert({route:Wwe(w),source_trace_id:t.source_trace_id,subcircuit_id:t.getSubcircuit()?.subcircuit_id,trace_length:M}),U=t.subcircuit_connectivity_map_key??e.source_trace.get(t.source_trace_id)?.subcircuit_connectivity_map_key;t._portsRoutedOnPcb=c,t.pcb_trace_id=O.pcb_trace_id;for(const Y of w)if(Y.route_type==="via"){const W=Y,te=Y.from_layer,j=Y.to_layer;e.pcb_via.insert({pcb_trace_id:O.pcb_trace_id,x:Y.x,y:Y.y,hole_diameter:R,outer_diameter:F,layers:hMt({fromLayer:te,toLayer:j,layerCount:i._getSubcircuitLayerCount(),allowBlindAndBuriedVias:s?.allow_blind_and_buried_vias??!1,physicalLayers:W.layers}),from_layer:te,to_layer:j,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:t.getGroup()?.pcb_group_id??void 0,subcircuit_connectivity_map_key:U})}t._insertErrorIfTraceIsOutsideBoard(w,c)}var D0e=t=>{switch(t){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+"}},qwe=({db:t,source_trace_id:e,schematic_sheet_id:n,sameNetOnly:o,differentNetOnly:i})=>{!o&&!i&&(i=!0);const r=t.source_trace.get(e),s=[];for(const a of t.schematic_trace.list()){if(a.source_trace_id===e||n!==void 0&&a.schematic_sheet_id!==n)continue;const c=t.source_trace.get(a.source_trace_id)?.subcircuit_connectivity_map_key===r.subcircuit_connectivity_map_key;i&&c||o&&!c||s.push(a)}return s},Q7o=({edges:t,otherEdges:e})=>{const n=[...t];for(let o=0;o<n.length;o++){if(o>2e3)throw new Error("Over 2000 iterations spent inside createSchematicTraceCrossingSegments, you have triggered an infinite loop, please report this!");const i=n[o],r=Math.abs(i.from.x-i.to.x)<.01?"vertical":i.from.y===i.to.y?"horizontal":"not-orthogonal";if(r==="not-orthogonal")continue;const s=[];for(const p of e){const m=p.from.x===p.to.x?"vertical":p.from.y===p.to.y?"horizontal":"not-orthogonal";if(m==="not-orthogonal"||r===m)continue;if(xxe([i.from,i.to],[p.from,p.to],{lineThickness:.01})){const f=r==="vertical"?i.from.x:p.from.x,I=r==="vertical"?p.from.y:i.from.y,C={x:f,y:I};s.push({otherEdge:p,crossingPoint:C,distanceFromEdgeFrom:ad(i.from,C)})}}if(s.length===0)continue;let a=s[0];for(const p of s)p.distanceFromEdgeFrom<a.distanceFromEdgeFrom&&(a=p);const A=a.crossingPoint,c=.075;if(A.x===i.from.x&&A.y===i.from.y)continue;const l=Bxe(i.from,A),u={x:A.x-l.x*c/2,y:A.y-l.y*c/2},g={x:A.x+l.x*c/2,y:A.y+l.y*c/2},h=ad(g,i.to)<c,d=[{from:i.from,to:u},{from:u,to:g,is_crossing:!0},{from:g,to:i.to}];n.splice(o,1,...d),o+=d.length-2,h&&o++}return n},Xwe=.001,dO=(t,e)=>{const n=Math.min(e.from.x,e.to.x),o=Math.max(e.from.x,e.to.x),i=Math.min(e.from.y,e.to.y),r=Math.max(e.from.y,e.to.y);return t.x>=n&&t.x<=o&&t.y>=i&&t.y<=r},PMt=t=>{const e=Math.abs(t.from.x-t.to.x)<Xwe,n=Math.abs(t.from.y-t.to.y)<Xwe;return e?"vertical":n?"horizontal":"diagonal"},v7o=(t,e)=>{const n=PMt(t),o=PMt(e);if(n===o)return null;if(n==="vertical"&&o==="horizontal"||n==="horizontal"&&o==="vertical"){const u=n==="vertical"?t:e,g=n==="horizontal"?t:e,h=u.from.x,d=g.from.y,p={x:h,y:d};return dO(p,t)&&dO(p,e)?p:null}if(n==="vertical"||o==="vertical"){const u=n==="vertical"?t:e,g=n==="vertical"?e:t,h=u.from.x,d=(g.to.y-g.from.y)/(g.to.x-g.from.x),p=g.from.y-d*g.from.x,m=d*h+p,_={x:h,y:m};return dO(_,t)&&dO(_,e)?_:null}const i=(t.to.y-t.from.y)/(t.to.x-t.from.x),r=t.from.y-i*t.from.x,s=(e.to.y-e.from.y)/(e.to.x-e.from.x),a=e.from.y-s*e.from.x;if(Math.abs(i-s)<Xwe)return null;const A=(a-r)/(i-s),c=i*A+r,l={x:A,y:c};return dO(l,t)&&dO(l,e)?l:null},MMt=({edges:t,db:e,source_trace_id:n,schematic_sheet_id:o})=>{const i=qwe({db:e,source_trace_id:n,schematic_sheet_id:o,sameNetOnly:!0}).flatMap(s=>s.edges),r=new Map;for(const s of t)for(const a of i){const A=v7o(s,a);if(A){const c=`${A.x.toFixed(6)},${A.y.toFixed(6)}`;r.has(c)||r.set(c,A)}}return Array.from(r.values())};function DMt(t){const e=t%360;return e<0?e+360:e}function w7o(t,e,n,o){return o==="counterclockwise"?n>=e?t>=e&&t<=n:t>=e||t<=n:n<=e?t<=e&&t>=n:t<=e||t>=n}function P7o(t){const e=t.center,n=t.radius,o=t.start_angle_degrees,i=t.end_angle_degrees,r=t.direction??"counterclockwise";if(!e||typeof e.x!="number"||typeof e.y!="number"||typeof n!="number"||typeof o!="number"||typeof i!="number")return null;const s=DMt(o),a=DMt(i),A=new Set([s,a]),c=[0,90,180,270];for(const d of c)w7o(d,s,a,r)&&A.add(d);let l=1/0,u=1/0,g=-1/0,h=-1/0;for(const d of A){const p=d*Math.PI/180,m=e.x+n*Math.cos(p),_=e.y+n*Math.sin(p);l=Math.min(l,m),g=Math.max(g,m),u=Math.min(u,_),h=Math.max(h,_)}return!Number.isFinite(l)||!Number.isFinite(u)?null:{minX:l,maxX:g,minY:u,maxY:h}}function Gj(t){let e=1/0,n=1/0,o=-1/0,i=-1/0;for(const r of t){let s,a,A,c;if(r.type==="schematic_component")s=r.center?.x,a=r.center?.y,A=r.size?.width,c=r.size?.height;else if(r.type==="schematic_box")s=r.x,a=r.y,A=r.width,c=r.height;else if(r.type==="schematic_port")s=r.center?.x,a=r.center?.y,A=.2,c=.2;else if(r.type==="schematic_text")s=r.position?.x,a=r.position?.y,A=(r.text?.length??0)*.1,c=.2;else if(r.type==="schematic_line"){const l=r.x1??0,u=r.y1??0,g=r.x2??0,h=r.y2??0;s=(l+g)/2,a=(u+h)/2,A=Math.abs(g-l),c=Math.abs(h-u)}else if(r.type==="schematic_rect")s=r.center?.x,a=r.center?.y,A=r.width,c=r.height;else if(r.type==="schematic_circle"){s=r.center?.x,a=r.center?.y;const l=r.radius;typeof l=="number"&&(A=l*2,c=l*2)}else if(r.type==="schematic_arc"){const l=P7o(r);l&&(e=Math.min(e,l.minX),o=Math.max(o,l.maxX),n=Math.min(n,l.minY),i=Math.max(i,l.maxY));continue}else if(r.type==="schematic_path"){const l=r.points;if(Array.isArray(l))for(const u of l)typeof u.x=="number"&&typeof u.y=="number"&&(e=Math.min(e,u.x),o=Math.max(o,u.x),n=Math.min(n,u.y),i=Math.max(i,u.y));continue}typeof s=="number"&&typeof a=="number"&&typeof A=="number"&&typeof c=="number"&&(e=Math.min(e,s-A/2),o=Math.max(o,s+A/2),n=Math.min(n,a-c/2),i=Math.max(i,a+c/2))}return{minX:e,maxX:o,minY:n,maxY:i}}function M7o(t,e={}){const{minX:n,maxX:o,minY:i,maxY:r}=t,s=e.padding??1;if(!isFinite(n)||!isFinite(o)||!isFinite(i)||!isFinite(r))return[];const a=n-s,A=o+s,c=r+s,l=i-s,u=.01;return[{type:"rect",layers:["top"],center:{x:(a+A)/2,y:c},width:A-a,height:u,connectedTo:[]},{type:"rect",layers:["top"],center:{x:(a+A)/2,y:l},width:A-a,height:u,connectedTo:[]},{type:"rect",layers:["top"],center:{x:a,y:(c+l)/2},width:u,height:c-l,connectedTo:[]},{type:"rect",layers:["top"],center:{x:A,y:(c+l)/2},width:u,height:c-l,connectedTo:[]}]}var D7o=t=>{const e=t.root.db,n=t._findConnectedPorts().ports??[],o=new Set(n.map(s=>s.schematic_port_id)),i=[];for(const s of e.toArray()){if(s.type==="schematic_component"){const a=!!s.symbol_name,A=s.size.width>s.size.height?"horz":"vert";i.push({type:"rect",layers:["top"],center:s.center,width:s.size.width+(a&&A==="horz"?-.5:0),height:s.size.height+(a&&A==="vert"?-.5:0),connectedTo:[]})}if(s.type==="schematic_port"){if(o.has(s.schematic_port_id))continue;const a=s.facing_direction?Jk(s.facing_direction):{x:0,y:0};i.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"&&i.push({type:"rect",layers:["top"],center:s.position,width:(s.text?.length??0)*.1,height:.2,connectedTo:[]}),s.type==="schematic_box"&&i.push({type:"rect",layers:["top"],center:{x:s.x,y:s.y},width:s.width,height:s.height,connectedTo:[]})}const r=Gj(e.toArray());return i.push(...M7o(r,{padding:1})),i},N7o=({edges:t,db:e,source_trace_id:n,schematic_sheet_id:o})=>{const i=qwe({db:e,source_trace_id:n,schematic_sheet_id:o,differentNetOnly:!0}).flatMap(s=>s.edges),r=s=>{const{from:a,to:A}=s;return a.x===A.x?"vertical":"horizontal"};for(const s of t){const a=r(s),A=()=>i.find(l=>r(l)===a&&xxe([s.from,s.to],[l.from,l.to],{lineThickness:.05}));let c=A();for(;c;)a==="horizontal"?(s.from.y+=.1,s.to.y+=.1):(s.from.x+=.1,s.to.x+=.1),c=A()}},R7o=t=>{if(t.root?._featureMspSchematicTraceRouting||t._couldNotFindPort||t.root?.schematicDisabled||t.getCollapsedSchematicBoxAncestor())return;const{db:e}=t.root,{_parsedProps:n,parent:o}=t,i=t._getSchematicNetLabelText(),r=t._resolveSchematicSheetId();if(!o)throw new Error("Trace has no parent");let s,a;try{const Y=t._findConnectedPorts();s=Y.allPortsFound,a=Y.portsWithSelectors??[]}catch(Y){if(Y instanceof jN){e.source_trace_not_connected_error.insert({...Y.errorData,error_type:"source_trace_not_connected_error"});return}throw Y}const{netsWithSelectors:A}=t._findConnectedNets();if(!s)return;const c=Y=>{if(r&&Y.source_port_id){const W=e.schematic_port.getWhere({source_port_id:Y.source_port_id,schematic_sheet_id:r});if(W)return W}if(Y.schematic_port_id)return e.schematic_port.get(Y.schematic_port_id)??null;if(!r&&Y.source_port_id){const W=e.schematic_port.list({source_port_id:Y.source_port_id}).filter(te=>!te.schematic_sheet_id);if(W.length===1)return W[0]}return null},l=a.flatMap(({port:Y})=>{const W=c(Y);return W?[{port:Y,position:W.center,schematic_port_id:W.schematic_port_id,facingDirection:W.facing_direction??null}]:[]}),u=l.map(({schematic_port_id:Y})=>Y).sort(),g=l.some(({port:Y,schematic_port_id:W})=>Y.schematic_port_id!==W),h=u.join(","),d=t.root?._getBoard();if(d?._connectedSchematicPortPairs&&d._connectedSchematicPortPairs.has(h))return;const p={name:t.source_trace_id,pointsToConnect:[]},m=D7o(t);if(l.length===1&&A.length===1){const Y=A[0].net,{port:W,position:te}=l[0];let j=t.getSubcircuit().selectAll("netlabel").find(oe=>{const ie=oe._parsedProps.connection??oe._parsedProps.connectsTo;return ie?Array.isArray(ie)?ie.some(le=>t.getSubcircuit().selectOne(le,{port:!0})===W):t.getSubcircuit().selectOne(ie,{port:!0})===W:!1});if(!j){const oe=e.schematic_net_label.getWhere({source_trace_id:t.source_trace_id});oe&&(j=oe)}if(j){const oe="_getGlobalSchematicPositionBeforeLayout"in j?j._getGlobalSchematicPositionBeforeLayout():j.anchor_position,ie=[];te.x===oe.x||te.y===oe.y?ie.push({from:te,to:oe}):(ie.push({from:te,to:{x:oe.x,y:te.y}}),ie.push({from:{x:oe.x,y:te.y},to:oe}));const ne=MMt({edges:ie,db:e,source_trace_id:t.source_trace_id,schematic_sheet_id:r}),le=e.schematic_trace.insert({source_trace_id:t.source_trace_id,edges:ie,junctions:ne,subcircuit_connectivity_map_key:t.subcircuit_connectivity_map_key??void 0,schematic_sheet_id:r});t.schematic_trace_id=le.schematic_trace_id;return}if(i){const oe=gO(W.facingDirection)??"bottom";e.schematic_net_label.insert({text:i,source_net_id:Y.source_net_id,anchor_position:te,center:j7({anchor_position:te,anchor_side:oe,text:i}),anchor_side:oe,schematic_sheet_id:t._resolveSchematicSheetId()});return}const J=gO(W.facingDirection)??"bottom";e.schematic_net_label.insert({text:Y._parsedProps.name,source_net_id:Y.source_net_id,anchor_position:te,center:j7({anchor_position:te,anchor_side:J,text:Y._parsedProps.name}),anchor_side:J,schematic_sheet_id:t._resolveSchematicSheetId()});return}if(i&&!g&&("from"in t.props&&"to"in t.props||"path"in t.props)){t._doInitialSchematicTraceRenderWithDisplayLabel();return}if(l.length<2)return;let I=(()=>{const Y=[];for(let te=0;te<l.length-1;te++){const j=l[te],J=l[te+1],oe=wF({x:j.position.x,y:j.position.y,facingDirection:D0e(j.facingDirection)},{x:J.position.x,y:J.position.y,facingDirection:D0e(J.facingDirection)});for(let ie=0;ie<oe.length-1;ie++)Y.push({from:oe[ie],to:oe[ie+1]})}const W=(te,j)=>{const J=j.width/2,oe=j.height/2,ie=j.center.x-J,ne=j.center.x+J,le=j.center.y-oe,ge=j.center.y+oe,_e=fe=>fe.x>=ie&&fe.x<=ne&&fe.y>=le&&fe.y<=ge;return _e(te.from)||_e(te.to)?!0:[[{x:ie,y:le},{x:ne,y:le}],[{x:ne,y:le},{x:ne,y:ge}],[{x:ne,y:ge},{x:ie,y:ge}],[{x:ie,y:ge},{x:ie,y:le}]].some(fe=>xxe([te.from,te.to],fe,{lineThickness:0}))};for(const te of Y)for(const j of m)if(W(te,j))return null;return Y})();I&&I.length===0&&(I=null),p.pointsToConnect=l.map(({position:Y})=>({...Y,layer:"top"}));const C=E9o(m),y=2,x={minTraceWidth:.1,obstacles:m,connections:[p],bounds:{minX:C.minX-y,maxX:C.maxX+y,minY:C.minY-y,maxY:C.maxY+y},layerCount:1};let E=Vct,B=!1;if(t.getSubcircuit().props._schDirectLineRoutingEnabled&&(E=XPt,B=!0),!I){let W=new E({input:x,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(!g&&(t._isSymbolToChipConnection()||t._isSymbolToSymbolConnection()||t._isChipToChipConnection())){t._doInitialSchematicTraceRenderWithDisplayLabel();return}W=new XPt({input:x}).solveAndMapToTraces(),B=!0}const[{route:te}]=W;I=[];const j=te.filter(J=>J.route_type==="wire"||J.route_type==="via");for(let J=0;J<j.length-1;J++)I.push({from:j[J],to:j[J+1]})}const S=t.source_trace_id;let Q=[];if(!B){N7o({edges:I,db:e,source_trace_id:S,schematic_sheet_id:r});const Y=qwe({db:e,source_trace_id:S,schematic_sheet_id:r,differentNetOnly:!0}).flatMap(W=>W.edges);I=Q7o({edges:I,otherEdges:Y}),Q=MMt({edges:I,db:e,source_trace_id:t.source_trace_id,schematic_sheet_id:r})}if(!I||I.length===0)return;const w=I[I.length-1],M=l[l.length-1],k=ZPt(w);I.push(...Ywe({lastEdge:w,lastEdgePort:M,lastDominantDirection:k}));const R=I[0],F=l[0],O=ZPt(R);if(I.unshift(...Ywe({firstEdge:R,firstEdgePort:F,firstDominantDirection:O})),!t.source_trace_id)throw new Error("Missing source_trace_id for schematic trace insertion.");if(!g&&t.getSubcircuit()._parsedProps.schTraceAutoLabelEnabled&&$9o(Q,I)>=5&&(t._isSymbolToChipConnection()||t._isSymbolToSymbolConnection()||t._isChipToChipConnection())){t._doInitialSchematicTraceRenderWithDisplayLabel();return}const U=e.schematic_trace.insert({source_trace_id:t.source_trace_id,edges:I,junctions:Q,subcircuit_connectivity_map_key:t.subcircuit_connectivity_map_key??void 0,schematic_sheet_id:r});t.schematic_trace_id=U.schematic_trace_id;for(const{schematic_port_id:Y}of l)e.schematic_port.update(Y,{is_connected:!0});d?._connectedSchematicPortPairs&&d._connectedSchematicPortPairs.add(h)},T7o=(t,{db:e})=>{const n=t.map(o=>{const i=e.source_port.get(o.source_port_id);if(!i?.source_component_id)return null;const r=e.source_component.get(i.source_component_id);return r?.ftype==="simple_capacitor"?r.max_decoupling_trace_length:null}).filter(o=>typeof o=="number");if(n.length!==0)return Math.min(...n)};function k7o({ports:t,nets:e}){if(t.length>=2)return`${t[0]?.selector} to ${t[1]?.selector}`;if(t.length===1&&e.length===1)return`${t[0]?.selector} to net.${e[0]._parsedProps.name}`}function F7o(t){const e=new Set;for(const{port:n}of t){if(!(n.parent instanceof BMt))continue;const o=n.parent._getConnectedNetOrTrace();o instanceof Qb&&e.add(o)}return[...e]}var t1=class extends Ir{source_trace_id=null;pcb_trace_id=null;schematic_trace_id=null;_inflatedPcbTraces;_inflatedPcbVias;_portsRoutedOnPcb;subcircuit_connectivity_map_key=null;_exposesSubcircuitConnection=!1;_traceConnectionHash=null;_couldNotFindPort;constructor(t){super(t),this._portsRoutedOnPcb=[]}_getExplicitTraceThickness(){return this._parsedProps.thickness??this._parsedProps.width}_getSchematicNetLabelText(){return this._parsedProps.schDisplayLabel??this._parsedProps.displayName??this._parsedProps.name}get config(){return{zodProps:vPn,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 _7o(this)}_resolveNet(t){const e=this.getSubcircuit().selectOne(t,{type:"net"});if(e)return e;const n=t.match(/^net\.(.+)$/),o=n?n[1]:null;if(!o)return null;const i=this.root?._getBoard();return i?i.getDescendants().find(s=>s.componentName==="Net"&&s._parsedProps.name===o)||null:(this.renderError(`Could not find a <board> ancestor for ${this}, so net "${t}" cannot be resolved`),null)}_findConnectedNets(){const t=this.getTracePathNetSelectors().map(n=>({selector:n,net:this._resolveNet(n)})),e=t.filter(n=>!n.net);return e.length>0&&this.renderError(`Could not find net for selector "${e[0].selector}" inside ${this}`),{netsWithSelectors:t,nets:t.map(n=>n.net)}}_getAllTracesConnectedToSameNet(){const t=this.getSubcircuit().selectAll("trace"),e=this._findConnectedNets().nets,n=this._findConnectedPorts().ports??[];return t.filter(o=>{if(o===this)return!1;const i=o._findConnectedNets().nets,r=o._findConnectedPorts().ports??[];return i.some(s=>e.includes(s))||r.some(s=>n.includes(s))})}_isExplicitlyConnectedToPort(t){const{allPortsFound:e,portsWithSelectors:n}=this._findConnectedPorts();return e?n.map(i=>i.port).includes(t):!1}_isExplicitlyConnectedToNet(t){return this._findConnectedNets().nets.includes(t)}doInitialCreateNetsFromProps(){Hj(this,this.getTracePathNetSelectors())}_computeTraceConnectionHash(){const{allPortsFound:t,ports:e}=this._findConnectedPorts();return!t||!e?null:[...e].sort((i,r)=>(i.pcb_port_id||"").localeCompare(r.pcb_port_id||"")).map(i=>i.pcb_port_id).join(",")}doInitialSourceTraceRender(){const{db:t}=this.root,{_parsedProps:e,parent:n}=this;if(!n){this.renderError("Trace has no parent");return}let o,i;try{const l=this._findConnectedPorts();o=l.allPortsFound,i=l.portsWithSelectors??[]}catch(l){if(l instanceof jN){t.source_trace_not_connected_error.insert({...l.errorData,error_type:"source_trace_not_connected_error"}),this._couldNotFindPort=!0;return}throw l}if(!o)return;this._traceConnectionHash=this._computeTraceConnectionHash();const s=t.source_trace.list().find(l=>l.subcircuit_connectivity_map_key===this.subcircuit_connectivity_map_key&&[...l.connected_source_port_ids].sort().join(",")===this._traceConnectionHash);if(s){this.source_trace_id=s.source_trace_id;return}const a=this._findConnectedNets().nets;for(const l of F7o(i))a.includes(l)||a.push(l);const A=k7o({ports:i,nets:a}),c=t.source_trace.insert({connected_source_port_ids:i.map(l=>l.port.source_port_id),connected_source_net_ids:a.map(l=>l.source_net_id),subcircuit_id:this.getSubcircuit()?.subcircuit_id,name:e.name,max_length:e.maxLength??T7o(i.map(l=>l.port),{db:t}),max_via_count:e.maxViaCount,display_name:e.displayName??A,min_trace_thickness:this._getExplicitTraceThickness()});this.source_trace_id=c.source_trace_id,!e.name&&a.length===0&&t.source_unnamed_trace_warning.insert({message:`${this.getString()} is missing a name. Add a name prop to make the trace easier to identify.`,source_trace_id:c.source_trace_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id??void 0,warning_type:"source_unnamed_trace_warning"})}_insertErrorIfTraceIsOutsideBoard(t,e){const{db:n}=this.root,o=this._getBoard();if(!o)return;const i=o.pcb_board_id;if(!i)return;K9o({mergedRoute:t,db:n,pcbBoardId:i})&&n.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:e.map(s=>s.pcb_port_id)})}doInitialPcbManualTraceRender(){C7o(this)}doInitialPcbTraceRender(){S7o(this)}_doInitialSchematicTraceRenderWithDisplayLabel(){m7o(this)}_isSymbolToChipConnection(){const{allPortsFound:t,ports:e}=this._findConnectedPorts();if(!t||e.length!==2)return!1;const[n,o]=e;if(!n?.parent||!o?.parent)return!1;const i=n.parent.config.shouldRenderAsSchematicBox,r=o.parent.config.shouldRenderAsSchematicBox;return i&&!r||!i&&r}_isSymbolToSymbolConnection(){const{allPortsFound:t,ports:e}=this._findConnectedPorts();if(!t||e.length!==2)return!1;const[n,o]=e;if(!n?.parent||!o?.parent)return!1;const i=!n.parent.config.shouldRenderAsSchematicBox,r=!o.parent.config.shouldRenderAsSchematicBox;return i&&r}_isChipToChipConnection(){const{allPortsFound:t,ports:e}=this._findConnectedPorts();if(!t||e.length!==2)return!1;const[n,o]=e;if(!n?.parent||!o?.parent)return!1;const i=n.parent.config.shouldRenderAsSchematicBox,r=o.parent.config.shouldRenderAsSchematicBox;return i&&r}doInitialSchematicTraceRender(){R7o(this)}},N0e={},NMt=t=>{const e=Object.fromEntries(Object.entries(t).map(([n,o])=>[n.toLowerCase(),o]));Object.assign(N0e,t),Object.assign(N0e,e)},L7o=class extends Ir{constructor(t,e){super(t);const n=(o,i)=>{if(typeof o=="number")return o;if(typeof o=="string")try{return this._resolvePcbCoordinate(o,i,{allowBoardVariables:!1})}catch{return 0}return 0};this._parsedProps={...t,error:e,type:t.type||"unknown",component_name:t.name,error_type:"source_failed_to_create_component_error",message:e instanceof Error?e.message:String(e),pcbX:n(t.pcbX,"pcbX"),pcbY:n(t.pcbY,"pcbY"),schX:t.schX,schY:t.schY}}formatErrorDetails(){const t=this._parsedProps.selector??this._parsedProps.selectors??this._parsedProps.in??this._parsedProps.within,e=t===void 0?void 0:typeof t=="string"?t:this.safeStringify(t),n=this.safeStringify(this._parsedProps);return{selectorText:e,propsText:n}}safeStringify(t){const e=new WeakSet,n=JSON.stringify(t,(o,i)=>{if(typeof i=="bigint")return i.toString();if(typeof i=="function")return`[Function ${i.name||"anonymous"}]`;if(typeof i=="symbol")return i.toString();if(typeof i=="object"&&i!==null){if(e.has(i))return"[Circular]";e.add(i)}return i},2);return n?n.length>2e3?`${n.slice(0,2e3)}…`:n:"undefined"}get config(){return{componentName:"ErrorPlaceholder",zodProps:Pt({}).passthrough()}}doInitialSourceRender(){if(this.root?.db){const t=this._getGlobalPcbPositionBeforeLayout(),e=this._getGlobalSchematicPositionBeforeLayout(),{selectorText:n,propsText:o}=this.formatErrorDetails(),i=[n?`Within selector: ${n}`:null,`Props: ${o}`].filter(Boolean).join(" "),r=`Could not create ${this._parsedProps.componentType??"component"}${this._parsedProps.name?` "${this._parsedProps.name}"`:""}. ${this._parsedProps.error?.formattedError?._errors?.join("; ")||this._parsedProps.message}`;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:`${r}${i?` Details: ${i}`:""}`,pcb_center:t,schematic_center:e})}}};function H7o(t,e){return new L7o(t,e)}function O7o(t,e){const n=t;return n.__tsci={...e},t}var G7o={supportsMutation:!0,createInstance(t,e){const n=N0e[t];if(!n)throw Object.keys(N0e).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 "${t}". 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 O7o(new n(e),{})}catch(o){return H7o({...e,componentType:t},o)}},createTextInstance(t){return{__text:t}},appendInitialChild(t,e){t.add(e)},appendChild(t,e){t.add(e)},appendChildToContainer(t,e){t.add(e)},finalizeInitialChildren(){return!1},prepareUpdate(){return null},shouldSetTextContent(){return!1},getRootHostContext(){return{}},getChildHostContext(){return{}},prepareForCommit(){return null},resetAfterCommit(){},commitMount(){},commitUpdate(){},removeChild(){},clearContainer(){},supportsPersistence:!1,getPublicInstance(t){return t},preparePortalMount(t){throw new Error("Function not implemented.")},scheduleTimeout(t,e){throw new Error("Function not implemented.")},cancelTimeout(t){throw new Error("Function not implemented.")},noTimeout:void 0,isPrimaryRenderer:!1,getInstanceFromNode(t){throw new Error("Function not implemented.")},beforeActiveInstanceBlur(){throw new Error("Function not implemented.")},afterActiveInstanceBlur(){throw new Error("Function not implemented.")},prepareScopeUpdate:(t,e)=>{throw new Error("Function not implemented.")},getInstanceFromScope:t=>{throw new Error("Function not implemented.")},detachDeletedInstance:t=>{throw new Error("Function not implemented.")},getCurrentEventPriority:()=>XBe.DefaultEventPriority,getCurrentUpdatePriority:()=>XBe.DefaultEventPriority,resolveUpdatePriority:()=>XBe.DefaultEventPriority,setCurrentUpdatePriority:()=>{},maySuspendCommit:()=>!1,supportsHydration:!1},R0e=aJn(G7o),RMt=t=>{const e={children:[],props:{name:"$root"},add(r){r.parent=this,this.children.push(r)},computePcbGlobalTransform(){return hC()}},n=[],o=R0e.createContainer(e,0,null,!1,null,"tsci",r=>{console.log("Error in createContainer"),console.error(r),n.push(r)},null);if(R0e.updateContainerSync(t,o,null,()=>{}),R0e.flushSyncWork(),n.length>0)throw n[0];const i=R0e.getPublicRootInstance(o);return i||e.children[0]},Y7o=/^(?:pin)?(\d+)$/,uw=t=>{const e=t.match(Y7o);return e?Number.parseInt(e[1],10):null};function U7o(t){if(!t)return{validPinLabels:t,invalidPinLabelsMessages:[]};const e={},n=[];for(const[o,i]of Object.entries(t)){const r=Array.isArray(i)?i.slice():[i],s=[];for(const a of r)if(K7o(o,a))s.push(a);else{const A=TMt(a),c=A?` Try using "${A}" instead.`:"";n.push(`Invalid pin label: ${o} = '${a}' - excluding from component. Pin labels can only contain letters, numbers and underscores.${c}`)}s.length>0&&(e[o]=Array.isArray(i)?s:s[0])}return{validPinLabels:Object.keys(e).length>0?e:void 0,invalidPinLabelsMessages:n}}function K7o(t,e){return/^[A-Za-z0-9_]+$/.test(e)}function TMt(t){const e=t.match(/^\+?(\d+)\.(\d+)V(_\d+)?$/i);if(e)return`V${e[1]}_${e[2]}${e[3]??""}`;const n=t.match(/^\+?(\d+)V(\d+)(_\d+)?$/i);if(n)return`V${n[1]}_${n[2]}${n[3]??""}`;const o=t.match(/^\+?(\d+)V(_\d+)?$/i);if(o)return`V${o[1]}${o[2]??""}`}var kMt=t=>{const e=TMt(t),n=e?` Try using "${e}" instead.`:"";return`No pin labels provided and pin number or label is not a number: "${t}".${n}`},hO=(t,e)=>{if(typeof t=="number")return t;const n=uw(t);if(n!==null)return n;if(t.startsWith("pin"))throw new Error(`Invalid pinLabels key "${t}". Expected "pin\${number}" (e.g. pin1, pin2).`);if(!e)throw new Error(kMt(t));for(const o in e)if((Array.isArray(e[o])?e[o]:[e[o]]).includes(t)){const r=uw(o);if(r===null)throw new Error(`Invalid pinLabels key "${o}". Expected "pin\${number}" (e.g. pin1, pin2).`);return r}throw new Error(kMt(t))},Zwe=(t,e)=>{if(!t)return;const n={},o={};for(const[i,r]of Object.entries(t)){const s=hO(i,e);o[s]={...o[s],...r}}for(const[i,r]of Object.entries(o)){const s=`pin${i}`;n[s]={bottom_margin:r.bottomMargin,left_margin:r.leftMargin,right_margin:r.rightMargin,top_margin:r.topMargin}}return n},ePe=t=>{if(t){if("leftSide"in t||"rightSide"in t||"topSide"in t||"bottomSide"in t)return{left_side:t.leftSide,right_side:t.rightSide,top_side:t.topSide,bottom_side:t.bottomSide};if("leftPinCount"in t||"rightPinCount"in t||"topPinCount"in t||"bottomPinCount"in t)return{left_size:t.leftPinCount,right_size:t.rightPinCount,top_size:t.topPinCount,bottom_size:t.bottomPinCount};if("leftSize"in t||"rightSize"in t||"topSize"in t||"bottomSize"in t)return{left_size:t.leftSize,right_size:t.rightSize,top_size:t.topSize,bottom_size:t.bottomSize}}};function Yj(t){return t.replace(/\\n/g,`
`)}var FMt=class extends Ir{isPcbPrimitive=!0;pcb_copper_text_id=null;get config(){return{componentName:"CopperText",zodProps:hDn}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:e}=this,n=this.getPrimitiveContainer(),o=this._getGlobalPcbPositionBeforeLayout(),i=this.getSubcircuit(),r=t.pcb_copper_text.insert({anchor_alignment:e.anchorAlignment,anchor_position:{x:o.x,y:o.y},font:"tscircuit2024",font_size:e.fontSize,layer:e.layer??"top",text:Yj(e.text),ccw_rotation:e.pcbRotation,is_mirrored:e.mirrored,is_knockout:e.knockout,pcb_component_id:n.pcb_component_id,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_copper_text_id=r.pcb_copper_text_id}getPcbSize(){const{_parsedProps:t}=this,e=t.fontSize??1,o=(t.text??"").length*e,i=e;return{width:o*e,height:i*e}}_moveCircuitJsonElements({deltaX:t,deltaY:e}){if(this.root?.pcbDisabled)return;const{db:n}=this.root;if(!this.pcb_copper_text_id)return;const o=n.pcb_copper_text.get(this.pcb_copper_text_id);o&&n.pcb_copper_text.update(this.pcb_copper_text_id,{anchor_position:{x:o.anchor_position.x+t,y:o.anchor_position.y+e}})}},LMt=class extends Ir{pcb_courtyard_circle_id=null;isPcbPrimitive=!0;get config(){return{componentName:"CourtyardCircle",zodProps:NMn}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:e}=this,n=this._getGlobalPcbPositionBeforeLayout(),{maybeFlipLayer:o}=this._getPcbPrimitiveFlippedHelpers(),i=o(e.layer??"top");if(i!=="top"&&i!=="bottom")throw new Error(`Invalid layer "${i}" for CourtyardCircle. Must be "top" or "bottom".`);const r=this.getSubcircuit(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=t.pcb_courtyard_circle.insert({pcb_component_id:s,layer:i,center:{x:n.x,y:n.y},radius:e.radius,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_courtyard_circle_id=a.pcb_courtyard_circle_id}getPcbSize(){const{_parsedProps:t}=this,e=t.radius*2;return{width:e,height:e}}_moveCircuitJsonElements({deltaX:t,deltaY:e}){if(this.root?.pcbDisabled)return;const{db:n}=this.root;if(!this.pcb_courtyard_circle_id)return;const o=n.pcb_courtyard_circle.get(this.pcb_courtyard_circle_id);o&&n.pcb_courtyard_circle.update(this.pcb_courtyard_circle_id,{center:{x:o.center.x+t,y:o.center.y+e}})}},HMt=class extends Ir{pcb_courtyard_outline_id=null;isPcbPrimitive=!0;get config(){return{componentName:"CourtyardOutline",zodProps:DMn}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:e}=this,{maybeFlipLayer:n}=this._getPcbPrimitiveFlippedHelpers(),o=n(e.layer??"top");if(o!=="top"&&o!=="bottom")throw new Error(`Invalid layer "${o}" for CourtyardOutline. Must be "top" or "bottom".`);const i=this._computePcbGlobalTransformBeforeLayout(),r=this.getSubcircuit(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=t.pcb_courtyard_outline.insert({pcb_component_id:s,layer:o,outline:e.outline.map(A=>{const c=ts(i,{x:A.x,y:A.y});return{x:c.x,y:c.y}}),subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_courtyard_outline_id=a.pcb_courtyard_outline_id}_setPositionFromLayout(t){const{db:e}=this.root,n=e.pcb_courtyard_outline.get(this.pcb_courtyard_outline_id);if(!n)return;let o=0,i=0;for(const A of n.outline)o+=A.x,i+=A.y;o/=n.outline.length,i/=n.outline.length;const r=t.x-o,s=t.y-i,a=n.outline.map(A=>({x:A.x+r,y:A.y+s}));e.pcb_courtyard_outline.update(this.pcb_courtyard_outline_id,{outline:a})}_moveCircuitJsonElements({deltaX:t,deltaY:e}){if(this.root?.pcbDisabled)return;const{db:n}=this.root;if(!this.pcb_courtyard_outline_id)return;const o=n.pcb_courtyard_outline.get(this.pcb_courtyard_outline_id);o&&n.pcb_courtyard_outline.update(this.pcb_courtyard_outline_id,{outline:o.outline.map(i=>({x:i.x+t,y:i.y+e}))})}getPcbSize(){const{_parsedProps:t}=this;if(!t.outline||t.outline.length===0)return{width:0,height:0};const e=Oh(t.outline);return e?{width:e.maxX-e.minX,height:e.maxY-e.minY}:{width:0,height:0}}},OMt=class extends Ir{pcb_courtyard_rect_id=null;isPcbPrimitive=!0;get config(){return{componentName:"CourtyardRect",zodProps:MMn}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:e}=this,n=this._getGlobalPcbPositionBeforeLayout(),{maybeFlipLayer:o,isFlipped:i}=this._getPcbPrimitiveFlippedHelpers(),r=o(e.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for CourtyardRect. Must be "top" or "bottom".`);const s=this.getSubcircuit(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id;let l=(O9(this._computePcbGlobalTransformBeforeLayout()).rotation.angle*180/Math.PI%360+360)%360;i&&(l=(180-l+360)%360);const u=t.pcb_courtyard_rect.insert({pcb_component_id:a,layer:r,center:{x:n.x,y:n.y},width:e.width,height:e.height,ccw_rotation:l||void 0,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_courtyard_rect_id=u.pcb_courtyard_rect_id}getPcbSize(){const{_parsedProps:t}=this;return{width:t.width,height:t.height}}_moveCircuitJsonElements({deltaX:t,deltaY:e}){if(this.root?.pcbDisabled)return;const{db:n}=this.root;if(!this.pcb_courtyard_rect_id)return;const o=n.pcb_courtyard_rect.get(this.pcb_courtyard_rect_id);o&&n.pcb_courtyard_rect.update(this.pcb_courtyard_rect_id,{center:{x:o.center.x+t,y:o.center.y+e}})}},T0e=class extends Ir{pcb_cutout_id=null;isPcbPrimitive=!0;get config(){return{componentName:"Cutout",zodProps:aPn}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:e}=this,n=this.getSubcircuit(),o=this.getGroup()?.pcb_group_id??void 0,i=this._getGlobalPcbPositionBeforeLayout(),r=this.getPrimitiveContainer(),s=this.parent?.pcb_component_id??r?.pcb_component_id??void 0,a=r?._parsedProps.pcbRotation??0;let A;if(e.shape==="rect"){const c=typeof a=="string"?parseInt(a.replace("deg",""),10):a,l=Math.abs(c%180)===90,u={shape:"rect",center:i,width:l?e.height:e.width,height:l?e.width:e.height,subcircuit_id:n?.subcircuit_id??void 0,pcb_group_id:o,pcb_component_id:s};A=t.pcb_cutout.insert(u)}else if(e.shape==="circle"){const c={shape:"circle",center:i,radius:e.radius,subcircuit_id:n?.subcircuit_id??void 0,pcb_group_id:o,pcb_component_id:s};A=t.pcb_cutout.insert(c)}else if(e.shape==="polygon"){const c=this._computePcbGlobalTransformBeforeLayout(),u={shape:"polygon",points:e.points.map(g=>ts(c,g)),subcircuit_id:n?.subcircuit_id??void 0,pcb_group_id:o,pcb_component_id:s};A=t.pcb_cutout.insert(u)}A&&(this.pcb_cutout_id=A.pcb_cutout_id)}getPcbSize(){const{_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 e=1/0,n=-1/0,o=1/0,i=-1/0;for(const r of t.points)e=Math.min(e,r.x),n=Math.max(n,r.x),o=Math.min(o,r.y),i=Math.max(i,r.y);return{width:n-e,height:i-o}}return{width:0,height:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_cutout_id)return super._getPcbCircuitJsonBounds();const{db:t}=this.root,e=t.pcb_cutout.get(this.pcb_cutout_id);if(!e)return super._getPcbCircuitJsonBounds();if(e.shape==="rect")return{center:e.center,bounds:{left:e.center.x-e.width/2,top:e.center.y+e.height/2,right:e.center.x+e.width/2,bottom:e.center.y-e.height/2},width:e.width,height:e.height};if(e.shape==="circle")return{center:e.center,bounds:{left:e.center.x-e.radius,top:e.center.y+e.radius,right:e.center.x+e.radius,bottom:e.center.y-e.radius},width:e.radius*2,height:e.radius*2};if(e.shape==="polygon"){if(e.points.length===0)return super._getPcbCircuitJsonBounds();let n=1/0,o=-1/0,i=1/0,r=-1/0;for(const s of e.points)n=Math.min(n,s.x),o=Math.max(o,s.x),i=Math.min(i,s.y),r=Math.max(r,s.y);return{center:{x:(n+o)/2,y:(i+r)/2},bounds:{left:n,top:r,right:o,bottom:i},width:o-n,height:r-i}}return super._getPcbCircuitJsonBounds()}_setPositionFromLayout(t){if(!this.pcb_cutout_id)return;const{db:e}=this.root,n=e.pcb_cutout.get(this.pcb_cutout_id);if(n){if(n.shape==="rect"||n.shape==="circle")e.pcb_cutout.update(this.pcb_cutout_id,{...n,center:t});else if(n.shape==="polygon"){const o=this._getPcbCircuitJsonBounds().center,i=t.x-o.x,r=t.y-o.y,s=n.points.map(a=>({x:a.x+i,y:a.y+r}));e.pcb_cutout.update(this.pcb_cutout_id,{...n,points:s})}}}_moveCircuitJsonElements({deltaX:t,deltaY:e}){if(!this.pcb_cutout_id)return;const{db:n}=this.root,o=n.pcb_cutout.get(this.pcb_cutout_id);o&&(o.shape==="rect"||o.shape==="circle"?n.pcb_cutout.update(this.pcb_cutout_id,{center:{x:o.center.x+t,y:o.center.y+e}}):o.shape==="polygon"&&n.pcb_cutout.update(this.pcb_cutout_id,{points:o.points.map(i=>({x:i.x+t,y:i.y+e}))}))}},GMt=class extends Ir{fabrication_note_path_id=null;isPcbPrimitive=!0;get config(){return{componentName:"FabricationNotePath",zodProps:bMn}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;const{db:t}=this.root,e=this.getSubcircuit(),{_parsedProps:n}=this,{maybeFlipLayer:o}=this._getPcbPrimitiveFlippedHelpers(),i=o(n.layer??"top");if(i!=="top"&&i!=="bottom")throw new Error(`Invalid layer "${i}" for FabricationNotePath. Must be "top" or "bottom".`);const r=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:i,color:n.color,route:n.route.map(A=>{const c=ts(r,{x:A.x,y:A.y});return{...A,x:c.x,y:c.y}}),stroke_width:n.strokeWidth??.1,subcircuit_id:e?.subcircuit_id??void 0});this.fabrication_note_path_id=a.pcb_fabrication_note_path_id}getPcbSize(){const{_parsedProps:t}=this;if(t.route.length===0)return{width:0,height:0};const e=t.route.map(a=>typeof a.x=="string"?parseFloat(a.x):a.x),n=t.route.map(a=>typeof a.y=="string"?parseFloat(a.y):a.y),o=Math.min(...e),i=Math.max(...e),r=Math.min(...n),s=Math.max(...n);return{width:i-o,height:s-r}}_moveCircuitJsonElements({deltaX:t,deltaY:e}){if(this.root?.pcbDisabled)return;const{db:n}=this.root;if(!this.fabrication_note_path_id)return;const o=n.pcb_fabrication_note_path.get(this.fabrication_note_path_id);o&&n.pcb_fabrication_note_path.update(this.fabrication_note_path_id,{route:o.route.map(i=>({...i,x:i.x+t,y:i.y+e}))})}},YMt=class extends Ir{fabrication_note_rect_id=null;isPcbPrimitive=!0;get config(){return{componentName:"FabricationNoteRect",zodProps:BMn}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:e}=this,n=this._getGlobalPcbPositionBeforeLayout(),{maybeFlipLayer:o}=this._getPcbPrimitiveFlippedHelpers(),i=o(e.layer??"top");if(i!=="top"&&i!=="bottom")throw new Error(`Invalid layer "${i}" for FabricationNoteRect. Must be "top" or "bottom".`);const r=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,s=this.getSubcircuit(),a=e.hasStroke??(e.strokeWidth!==void 0&&e.strokeWidth!==null),A=t.pcb_fabrication_note_rect.insert({pcb_component_id:r,layer:i,color:e.color,center:{x:n.x,y:n.y},width:e.width,height:e.height,stroke_width:e.strokeWidth??1,is_filled:e.isFilled??!1,has_stroke:a,is_stroke_dashed:e.isStrokeDashed??!1,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,corner_radius:e.cornerRadius??void 0});this.fabrication_note_rect_id=A.pcb_fabrication_note_rect_id}getPcbSize(){const{_parsedProps:t}=this;return{width:t.width,height:t.height}}_moveCircuitJsonElements({deltaX:t,deltaY:e}){if(this.root?.pcbDisabled)return;const{db:n}=this.root;if(!this.fabrication_note_rect_id)return;const o=n.pcb_fabrication_note_rect.get(this.fabrication_note_rect_id);o&&n.pcb_fabrication_note_rect.update(this.fabrication_note_rect_id,{center:{x:o.center.x+t,y:o.center.y+e}})}};function V7o(t){const e=t.indexOf("[");if(e===-1)return{tag:t};const n=t.slice(0,e),i=t.slice(e+1,t.lastIndexOf("]")).match(/^(\w+)(\^=|\$=|=)['"]?(.*?)['"]?$/);return i?{tag:n,attrName:i[1],attrOp:i[2],attrValue:i[3]}:{tag:n}}function UMt(t,e){if(t.lowercaseComponentName!==e.tag)return!1;if(!e.attrName)return!0;const n=t.props?.[e.attrName];if(n===void 0)return!1;const o=String(n);switch(e.attrOp){case"^=":return o.startsWith(e.attrValue);case"$=":return o.endsWith(e.attrValue);case"=":return o===e.attrValue;default:return!1}}function z7o(t,e){if(!UMt(t,e[e.length-1]))return!1;let n=e.length-2,o=t.parent;for(;n>=0&&o;)UMt(o,e[n])&&n--,o=o.parent;return n<0}function pO({propertyName:t,resolvedPcbSx:e,pathFromAmpersand:n,component:o}){if(!e)return;let i,r=0;for(const[s,a]of Object.entries(e)){if(!a||!(t in a))continue;const A=s.startsWith("& ")?s.slice(2):s;if(A===n){1>r&&(r=1,i=a[t]);continue}if(!o)continue;const c=A.split(/\s+/).map(V7o);if(!(c.length<2)&&z7o(o,c)){const l=c.length;l>r&&(r=l,i=a[t])}}return i}var KMt=class extends Ir{pcb_fabrication_note_text_id=null;isPcbPrimitive=!0;get config(){return{componentName:"FabricationNoteText",zodProps:EMn}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:e}=this,n=this._getGlobalPcbPositionBeforeLayout(),r=(O9(this._computePcbGlobalTransformBeforeLayout()).rotation.angle*180/Math.PI%360+360)%360,s=this.getPrimitiveContainer(),a=this.getSubcircuit(),{maybeFlipLayer:A}=this._getPcbPrimitiveFlippedHelpers(),c=A(e.layer??"top");if(c!=="top"&&c!=="bottom")throw new Error(`Invalid layer "${c}" for FabricationNoteText. Must be "top" or "bottom".`);if(pO({propertyName:"visibility",resolvedPcbSx:this.getResolvedPcbSx(),pathFromAmpersand:"fabricationnotetext",component:this})==="hidden")return;const u=t.pcb_fabrication_note_text.insert({anchor_alignment:e.anchorAlignment,anchor_position:{x:n.x,y:n.y},font:e.font??"tscircuit2024",font_size:e.fontSize??1,layer:c,color:e.color,ccw_rotation:r,text:Yj(e.text??""),pcb_component_id:s.pcb_component_id,subcircuit_id:a?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_fabrication_note_text_id=u.pcb_fabrication_note_text_id}getPcbSize(){const{_parsedProps:t}=this,e=typeof t.fontSize=="string"?parseFloat(t.fontSize):t.fontSize??1,n=e*.6;return{width:(t.text??"").length*n,height:e}}_moveCircuitJsonElements({deltaX:t,deltaY:e}){if(this.root?.pcbDisabled)return;const{db:n}=this.root;if(this.pcb_fabrication_note_text_id){const o=n.pcb_fabrication_note_text.get(this.pcb_fabrication_note_text_id);o&&n.pcb_fabrication_note_text.update(this.pcb_fabrication_note_text_id,{anchor_position:{x:o.anchor_position.x+t,y:o.anchor_position.y+e}})}}},mO=class extends Ir{pcb_hole_id=null;isPcbPrimitive=!0;get config(){return{componentName:"Hole",zodProps:xPn}}getPcbSize(){const{_parsedProps:t}=this,e=t.shape==="pill",n=t.shape==="oval",o=t.shape==="rect";return e||n?{width:t.width,height:t.height}:o?{width:t.width,height:t.height}:{width:t.diameter,height:t.diameter}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:e}=this,n=this.getSubcircuit(),o=this._getGlobalPcbPositionBeforeLayout(),i=e.solderMaskMargin,r=e.coveredWithSolderMask??!1,s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id;if(this.emitSolderMaskMarginWarning(r,i),e.shape==="pill")if(e.pcbRotation&&e.pcbRotation!==0){const a=t.pcb_hole.insert({pcb_component_id:s,type:"pcb_hole",hole_shape:"rotated_pill",hole_width:e.width,hole_height:e.height,x:o.x,y:o.y,ccw_rotation:e.pcbRotation,soldermask_margin:i,is_covered_with_solder_mask:r,subcircuit_id:n?.subcircuit_id??void 0,pcb_group_id:n?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=a.pcb_hole_id}else{const a=t.pcb_hole.insert({pcb_component_id:s,type:"pcb_hole",hole_shape:"pill",hole_width:e.width,hole_height:e.height,x:o.x,y:o.y,soldermask_margin:i,is_covered_with_solder_mask:r,subcircuit_id:n?.subcircuit_id??void 0,pcb_group_id:n?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=a.pcb_hole_id}else if(e.shape==="oval"){const a=t.pcb_hole.insert({pcb_component_id:s,type:"pcb_hole",hole_shape:"oval",hole_width:e.width,hole_height:e.height,x:o.x,y:o.y,soldermask_margin:i,is_covered_with_solder_mask:r,subcircuit_id:n?.subcircuit_id??void 0,pcb_group_id:n?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=a.pcb_hole_id}else if(e.shape==="rect"){const a=t.pcb_hole.insert({pcb_component_id:s,type:"pcb_hole",hole_shape:"rect",hole_width:e.width,hole_height:e.height,x:o.x,y:o.y,soldermask_margin:i,is_covered_with_solder_mask:r,subcircuit_id:n?.subcircuit_id??void 0,pcb_group_id:n?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=a.pcb_hole_id}else{const a=t.pcb_hole.insert({pcb_component_id:s,type:"pcb_hole",hole_shape:"circle",hole_diameter:e.diameter,x:o.x,y:o.y,soldermask_margin:i,is_covered_with_solder_mask:r,subcircuit_id:n?.subcircuit_id??void 0,pcb_group_id:n?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=a.pcb_hole_id}}_getPcbCircuitJsonBounds(){const{db:t}=this.root,e=t.pcb_hole.get(this.pcb_hole_id),n=this.getPcbSize();return{center:{x:e.x,y:e.y},bounds:{left:e.x-n.width/2,top:e.y-n.height/2,right:e.x+n.width/2,bottom:e.y+n.height/2},width:n.width,height:n.height}}_setPositionFromLayout(t){const{db:e}=this.root;e.pcb_hole.update(this.pcb_hole_id,{x:t.x,y:t.y})}_moveCircuitJsonElements({deltaX:t,deltaY:e}){if(this.root?.pcbDisabled)return;const{db:n}=this.root;if(!this.pcb_hole_id)return;const o=n.pcb_hole.get(this.pcb_hole_id);o&&n.pcb_hole.update(this.pcb_hole_id,{x:o.x+t,y:o.y+e})}},k0e=class extends Ir{pcb_keepout_id=null;isPcbPrimitive=!0;get config(){return{componentName:"Keepout",zodProps:PMn}}getExcludedPcbComponentIds(){const t=this._parsedProps.excludeRefs?.flatMap(e=>this.getSubcircuit().selectAll(e).map(n=>n.pcb_component_id).filter(n=>n!==null))??[];return Array.from(new Set(t))}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;const t=this.getSubcircuit(),{db:e}=this.root,{_parsedProps:n}=this,o=this._getGlobalPcbPositionBeforeLayout(),i=O9(this._computePcbGlobalTransformBeforeLayout()),r=Math.abs(i.rotation.angle*(180/Math.PI)-90)%180<.01;let s=n.layers;!s&&n.layer&&(s=[n.layer]),s||(s=["top"]);const a=this.getExcludedPcbComponentIds(),A=a.length>0?{excluded_pcb_component_ids:a}:{};let c=null;n.shape==="circle"?c=e.pcb_keepout.insert({layers:s,shape:"circle",...A,radius:n.radius,center:{x:o.x,y:o.y},subcircuit_id:t?.subcircuit_id??void 0,pcb_group_id:t?.getGroup()?.pcb_group_id??void 0}):n.shape==="rect"&&(c=e.pcb_keepout.insert({layers:s,shape:"rect",...A,...r?{width:n.height,height:n.width}:{width:n.width,height:n.height},center:{x:o.x,y:o.y},subcircuit_id:t?.subcircuit_id??void 0,pcb_group_id:t?.getGroup()?.pcb_group_id??void 0})),c&&(this.pcb_keepout_id=c.pcb_keepout_id)}getPcbSize(){const{_parsedProps:t}=this;return t.shape==="circle"?{width:t.radius*2,height:t.radius*2}:t.shape==="rect"?{width:t.width,height:t.height}:{width:0,height:0}}},VMt=class extends Ir{pcb_note_line_id=null;isPcbPrimitive=!0;get config(){return{componentName:"PcbNoteLine",zodProps:SDn}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:e}=this,n=this.getSubcircuit(),o=this.getGroup(),i=this._computePcbGlobalTransformBeforeLayout(),r=ts(i,{x:e.x1,y:e.y1}),s=ts(i,{x:e.x2,y:e.y2}),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,A=t.pcb_note_line.insert({pcb_component_id:a,subcircuit_id:n?.subcircuit_id??void 0,pcb_group_id:o?.pcb_group_id??void 0,x1:r.x,y1:r.y,x2:s.x,y2:s.y,layer:e.layer==="bottom"?"bottom":"top",stroke_width:e.strokeWidth??.1,color:e.color,is_dashed:e.isDashed});this.pcb_note_line_id=A.pcb_note_line_id}getPcbSize(){const{_parsedProps:t}=this;return{width:Math.abs(t.x2-t.x1),height:Math.abs(t.y2-t.y1)}}_moveCircuitJsonElements({deltaX:t,deltaY:e}){if(this.root?.pcbDisabled)return;const{db:n}=this.root;if(!this.pcb_note_line_id)return;const o=n.pcb_note_line.get(this.pcb_note_line_id);o&&n.pcb_note_line.update(this.pcb_note_line_id,{x1:o.x1+t,y1:o.y1+e,x2:o.x2+t,y2:o.y2+e})}},zMt=class extends Ir{pcb_note_path_id=null;isPcbPrimitive=!0;get config(){return{componentName:"PcbNotePath",zodProps:bDn}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:e}=this,n=this._computePcbGlobalTransformBeforeLayout(),o=this.getSubcircuit(),i=this.getGroup(),r=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,s=e.route.map(A=>{const{x:c,y:l,...u}=A,g=typeof c=="string"?parseFloat(c):c,h=typeof l=="string"?parseFloat(l):l,d=ts(n,{x:g,y:h});return{...u,x:d.x,y:d.y}}),a=t.pcb_note_path.insert({pcb_component_id:r,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:i?.pcb_group_id??void 0,route:s,layer:e.layer==="bottom"?"bottom":"top",stroke_width:e.strokeWidth??.1,color:e.color});this.pcb_note_path_id=a.pcb_note_path_id}getPcbSize(){const{_parsedProps:t}=this;if(t.route.length===0)return{width:0,height:0};const e=t.route.map(a=>typeof a.x=="string"?parseFloat(a.x):a.x),n=t.route.map(a=>typeof a.y=="string"?parseFloat(a.y):a.y),o=Math.min(...e),i=Math.max(...e),r=Math.min(...n),s=Math.max(...n);return{width:i-o,height:s-r}}_moveCircuitJsonElements({deltaX:t,deltaY:e}){if(this.root?.pcbDisabled)return;const{db:n}=this.root;if(!this.pcb_note_path_id)return;const o=n.pcb_note_path.get(this.pcb_note_path_id);o&&n.pcb_note_path.update(this.pcb_note_path_id,{route:o.route.map(i=>({...i,x:i.x+t,y:i.y+e}))})}},JMt=class extends Ir{pcb_note_rect_id=null;isPcbPrimitive=!0;get config(){return{componentName:"PcbNoteRect",zodProps:BDn}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:e}=this,n=this._computePcbGlobalTransformBeforeLayout(),o=ts(n,{x:0,y:0}),i=this.getSubcircuit(),r=this.getGroup(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,a=t.pcb_note_rect.insert({pcb_component_id:s,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:r?.pcb_group_id??void 0,center:o,width:e.width,height:e.height,layer:e.layer==="bottom"?"bottom":"top",stroke_width:e.strokeWidth??.1,is_filled:e.isFilled??!1,has_stroke:e.hasStroke??!0,is_stroke_dashed:e.isStrokeDashed??!1,color:e.color,corner_radius:e.cornerRadius??void 0});this.pcb_note_rect_id=a.pcb_note_rect_id}getPcbSize(){const{_parsedProps:t}=this,e=typeof t.width=="string"?parseFloat(t.width):t.width,n=typeof t.height=="string"?parseFloat(t.height):t.height;return{width:e,height:n}}_moveCircuitJsonElements({deltaX:t,deltaY:e}){if(this.root?.pcbDisabled)return;const{db:n}=this.root;if(!this.pcb_note_rect_id)return;const o=n.pcb_note_rect.get(this.pcb_note_rect_id);o&&n.pcb_note_rect.update(this.pcb_note_rect_id,{center:{x:o.center.x+t,y:o.center.y+e}})}},WMt=class extends Ir{pcb_note_text_id=null;isPcbPrimitive=!0;get config(){return{componentName:"PcbNoteText",zodProps:EDn}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:e}=this,n=this._computePcbGlobalTransformBeforeLayout(),o=ts(n,{x:0,y:0}),i=this.getSubcircuit(),r=this.getGroup(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,a=t.pcb_note_text.insert({pcb_component_id:s,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:r?.pcb_group_id??void 0,font:e.font??"tscircuit2024",font_size:e.fontSize??1,text:Yj(e.text),anchor_position:o,anchor_alignment:e.anchorAlignment??"center",layer:e.layer==="bottom"?"bottom":"top",color:e.color});this.pcb_note_text_id=a.pcb_note_text_id}getPcbSize(){const{_parsedProps:t}=this,e=typeof t.fontSize=="string"?parseFloat(t.fontSize):t.fontSize??1,n=e*.6;return{width:t.text.length*n,height:e}}_moveCircuitJsonElements({deltaX:t,deltaY:e}){if(this.root?.pcbDisabled)return;const{db:n}=this.root;if(!this.pcb_note_text_id)return;const o=n.pcb_note_text.get(this.pcb_note_text_id);o&&n.pcb_note_text.update(this.pcb_note_text_id,{anchor_position:{x:o.anchor_position.x+t,y:o.anchor_position.y+e}})}},J7o=Pt({route:dn(Y2e),source_trace_id:Z().optional()}),tPe=class extends Ir{pcb_trace_id=null;isPcbPrimitive=!0;get config(){return{componentName:"PcbTrace",zodProps:J7o}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:e}=this,n=this.getPrimitiveContainer(),o=this.getSubcircuit(),{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=this._computePcbGlobalTransformBeforeLayout(),s=e.route.map(A=>{if(A.route_type==="wire"){const{x:c,y:l,...u}=A,g=ts(r,{x:c,y:l});return{...u,...g,layer:i(A.layer)}}if(A.route_type==="via"){const{x:c,y:l,...u}=A,g=ts(r,{x:c,y:l});return{...u,...g,from_layer:i(A.from_layer),to_layer:i(A.to_layer)}}return{...A,start:ts(r,A.start),end:ts(r,A.end),start_layer:i(A.start_layer),end_layer:i(A.end_layer)}}),a=t.pcb_trace.insert({pcb_component_id:n.pcb_component_id,source_trace_id:e.source_trace_id,route:s,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_trace_id=a.pcb_trace_id}getPcbSize(){const t=this._getPcbLocalBoundsBeforeLayout();return{width:t.right-t.left,height:t.top-t.bottom}}_getPcbLocalBoundsBeforeLayout(){const{_parsedProps:t}=this;if(!t.route||t.route.length===0)return{left:0,right:0,top:0,bottom:0};let e=1/0,n=-1/0,o=1/0,i=-1/0;for(const r of t.route)r.route_type==="through_pad"?(e=Math.min(e,r.start.x,r.end.x),n=Math.max(n,r.start.x,r.end.x),o=Math.min(o,r.start.y,r.end.y),i=Math.max(i,r.start.y,r.end.y)):(e=Math.min(e,r.x),n=Math.max(n,r.x),o=Math.min(o,r.y),i=Math.max(i,r.y)),r.route_type==="wire"?(e=Math.min(e,r.x-r.width/2),n=Math.max(n,r.x+r.width/2),o=Math.min(o,r.y-r.width/2),i=Math.max(i,r.y+r.width/2)):r.route_type==="through_pad"&&(e=Math.min(e,r.start.x-r.width/2,r.end.x-r.width/2),n=Math.max(n,r.start.x+r.width/2,r.end.x+r.width/2),o=Math.min(o,r.start.y-r.width/2,r.end.y-r.width/2),i=Math.max(i,r.start.y+r.width/2,r.end.y+r.width/2));return e===1/0||n===-1/0||o===1/0||i===-1/0?{left:0,right:0,top:0,bottom:0}:{left:e,right:n,top:i,bottom:o}}},W7o=_lt.extend({layers:dn(Pr).optional(),isTented:je().optional(),tentedOnTop:je().optional(),tentedOnBottom:je().optional()}).partial({fromLayer:!0,toLayer:!0}),jMt=class extends Ir{pcb_via_id=null;_importedPcbTraceId;isPcbPrimitive=!0;get config(){return{componentName:"PcbVia",zodProps:W7o}}_getLayers(){const{layers:t,fromLayer:e="top",toLayer:n="bottom"}=this._parsedProps;if(t&&t.length>0)return t;const o=this.parent?this.getSubcircuit()._getSubcircuitLayerCount():2;return lw({fromLayer:e,toLayer:n,layerCount:o})}getAvailablePcbLayers(){return this._getLayers()}getPcbSize(){const t=this._parsedProps.outerDiameter??.6;return{width:t,height:t}}_getPcbCircuitJsonBounds(){const{db:t}=this.root,e=t.pcb_via.get(this.pcb_via_id),n=this.getPcbSize();return{center:{x:e.x,y:e.y},bounds:{left:e.x-n.width/2,top:e.y-n.height/2,right:e.x+n.width/2,bottom:e.y+n.height/2},width:n.width,height:n.height}}_setPositionFromLayout(t){const{db:e}=this.root;e.pcb_via.update(this.pcb_via_id,{x:t.x,y:t.y})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;const{db:t}=this.root,{holeDiameter:e,outerDiameter:n,netIsAssignable:o,isTented:i,tentedOnTop:r,tentedOnBottom:s}=this._parsedProps,a=this.getSubcircuit(),A=this._getGlobalPcbPositionBeforeLayout(),{isFlipped:c,maybeFlipLayer:l}=this._getPcbPrimitiveFlippedHelpers(),u=this._getLayers().map(p=>l(p)),g=this._parsedProps.fromLayer?l(this._parsedProps.fromLayer):u[0],h=this._parsedProps.toLayer?l(this._parsedProps.toLayer):u[u.length-1]??g,d=t.pcb_via.insert({x:A.x,y:A.y,...e!==void 0?{hole_diameter:e}:{},...n!==void 0?{outer_diameter:n}:{},layers:u,from_layer:g,to_layer:h,pcb_trace_id:this._importedPcbTraceId,subcircuit_id:a?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,net_is_assignable:o,tented_on_top:(c?s:r)??i,tented_on_bottom:(c?r:s)??i});this.pcb_via_id=d.pcb_via_id}},j7o=t=>{for(const e of t){const n=e.toString();if(/^(pin)?\d+$/.test(n))return Number.parseInt(n.replace(/^pin/,""))}return null};function $Mt(t,e,n){const o=j7o(n),i=t.filter(c=>c.isMatchingAnyOf(n));if(i.length===0)return null;const r=o===null?i:i.filter(c=>c._parsedProps.pinNumber===o||c._primaryPinNumber===o),s=r.length>0?r:i,a=s.find(c=>c.matchedComponents.some(l=>l.isPcbPrimitive&&EMt(l,e)));return a||(s.find(c=>!c.matchedComponents.some(l=>l.isPcbPrimitive))??s[0])}var Pb=class extends Ir{pcb_plated_hole_id=null;matchedPort=null;isPcbPrimitive=!0;get config(){return{componentName:"PlatedHole",zodProps:Hwn}}getAvailablePcbLayers(){return[...this.root?._getBoard()?.allLayers??["top","bottom"]]}getPcbSize(){const{_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};if(t.shape==="hole_with_polygon_pad"){if(!t.padOutline||t.padOutline.length===0)throw new Error("padOutline is required for hole_with_polygon_pad shape");const e=t.padOutline.map(a=>typeof a.x=="number"?a.x:parseFloat(String(a.x))),n=t.padOutline.map(a=>typeof a.y=="number"?a.y:parseFloat(String(a.y))),o=Math.min(...e),i=Math.max(...e),r=Math.min(...n),s=Math.max(...n);return{width:i-o,height:s-r}}throw new Error(`getPcbSize for shape "${t.shape}" not implemented for ${this.componentName}`)}_getPcbCircuitJsonBounds(){const{db:t}=this.root,e=t.pcb_plated_hole.get(this.pcb_plated_hole_id),n=this.getPcbSize();return{center:{x:e.x,y:e.y},bounds:{left:e.x-n.width/2,top:e.y+n.height/2,right:e.x+n.width/2,bottom:e.y-n.height/2},width:n.width,height:n.height}}_setPositionFromLayout(t){const{db:e}=this.root;e.pcb_plated_hole.update(this.pcb_plated_hole_id,{x:t.x,y:t.y}),this.matchedPort?._setPositionFromLayout(t)}doInitialPortMatching(){const t=this.getPrimitiveContainer()?.selectAll("port");if(!this._parsedProps.portHints)return;const e=$Mt(t,this,this._parsedProps.portHints);e&&(this.matchedPort=e,e.registerMatch(this))}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:e}=this,n=this._getGlobalPcbPositionBeforeLayout(),o=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,i=this.getSubcircuit(),r=this.getAvailablePcbLayers(),s=e.solderMaskMargin,a=e.coveredWithSolderMask??!1;this.emitSolderMaskMarginWarning(a,s);const u=(O9(this._computePcbGlobalTransformBeforeLayout()).rotation.angle*180/Math.PI%360+360)%360;if(e.shape==="circle"){const g=t.pcb_plated_hole.insert({pcb_component_id:o,pcb_port_id:this.matchedPort?.pcb_port_id,outer_diameter:e.outerDiameter,hole_diameter:e.holeDiameter,shape:"circle",port_hints:this.getNameAndAliases(),x:n.x,y:n.y,layers:r,soldermask_margin:s,is_covered_with_solder_mask:a,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=g.pcb_plated_hole_id,t.pcb_solder_paste.insert({layer:"top",shape:"circle",radius:e.outerDiameter/2,x:n.x,y:n.y,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),t.pcb_solder_paste.insert({layer:"bottom",shape:"circle",radius:e.outerDiameter/2,x:n.x,y:n.y,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(e.shape==="pill"&&e.rectPad){const g=t.pcb_plated_hole.insert({pcb_component_id:o,pcb_port_id:this.matchedPort?.pcb_port_id,outer_width:e.outerWidth,outer_height:e.outerHeight,hole_width:e.holeWidth,hole_height:e.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:n.x,y:n.y,layers:r,soldermask_margin:s,is_covered_with_solder_mask:a,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,hole_shape:"rotated_pill",pad_shape:"rect",hole_ccw_rotation:u,rect_ccw_rotation:u,rect_pad_width:e.outerWidth,rect_pad_height:e.outerHeight,hole_offset_x:e.holeOffsetX,hole_offset_y:e.holeOffsetY});this.pcb_plated_hole_id=g.pcb_plated_hole_id}else if(e.shape==="pill"||e.shape==="oval"){const g=t.pcb_plated_hole.insert({pcb_component_id:o,pcb_port_id:this.matchedPort?.pcb_port_id,outer_width:e.outerWidth,outer_height:e.outerHeight,hole_width:e.holeWidth,hole_height:e.holeHeight,shape:e.shape,port_hints:this.getNameAndAliases(),x:n.x,y:n.y,layers:r,soldermask_margin:s,is_covered_with_solder_mask:a,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,ccw_rotation:u});this.pcb_plated_hole_id=g.pcb_plated_hole_id,t.pcb_solder_paste.insert({layer:"top",shape:e.shape,width:e.outerWidth,height:e.outerHeight,x:n.x,y:n.y,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),t.pcb_solder_paste.insert({layer:"bottom",shape:e.shape,width:e.outerWidth,height:e.outerHeight,x:n.x,y:n.y,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(e.shape==="circular_hole_with_rect_pad"){const g=t.pcb_plated_hole.insert({pcb_component_id:o,pcb_port_id:this.matchedPort?.pcb_port_id,hole_diameter:e.holeDiameter,rect_pad_width:e.rectPadWidth,rect_pad_height:e.rectPadHeight,shape:"circular_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:n.x,y:n.y,layers:r,soldermask_margin:s,is_covered_with_solder_mask:a,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,hole_offset_x:e.holeOffsetX,hole_offset_y:e.holeOffsetY,rect_border_radius:e.rectBorderRadius??0,rect_ccw_rotation:u});this.pcb_plated_hole_id=g.pcb_plated_hole_id}else if(e.shape==="pill_hole_with_rect_pad")if(u!==0){const g=t.pcb_plated_hole.insert({pcb_component_id:o,pcb_port_id:this.matchedPort?.pcb_port_id,hole_width:e.holeWidth,hole_height:e.holeHeight,rect_pad_width:e.rectPadWidth,rect_pad_height:e.rectPadHeight,hole_offset_x:e.holeOffsetX,hole_offset_y:e.holeOffsetY,shape:"rotated_pill_hole_with_rect_pad",type:"pcb_plated_hole",hole_shape:"rotated_pill",pad_shape:"rect",hole_ccw_rotation:u,rect_ccw_rotation:u,rect_border_radius:e.rectBorderRadius,port_hints:this.getNameAndAliases(),x:n.x,y:n.y,layers:r,soldermask_margin:s,is_covered_with_solder_mask:a,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=g.pcb_plated_hole_id}else{const g=t.pcb_plated_hole.insert({pcb_component_id:o,pcb_port_id:this.matchedPort?.pcb_port_id,hole_width:e.holeWidth,hole_height:e.holeHeight,rect_pad_width:e.rectPadWidth,rect_pad_height:e.rectPadHeight,hole_offset_x:e.holeOffsetX,hole_offset_y:e.holeOffsetY,shape:"pill_hole_with_rect_pad",rect_border_radius:e.rectBorderRadius,port_hints:this.getNameAndAliases(),x:n.x,y:n.y,layers:r,soldermask_margin:s,is_covered_with_solder_mask:a,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=g.pcb_plated_hole_id}else if(e.shape==="hole_with_polygon_pad"){const g=(e.padOutline||[]).map(d=>{const p=typeof d.x=="number"?d.x:parseFloat(String(d.x)),m=typeof d.y=="number"?d.y:parseFloat(String(d.y));return{x:p,y:m}}),h=t.pcb_plated_hole.insert({pcb_component_id:o,pcb_port_id:this.matchedPort?.pcb_port_id,shape:"hole_with_polygon_pad",hole_shape:e.holeShape||"circle",hole_diameter:e.holeDiameter,hole_width:e.holeWidth,hole_height:e.holeHeight,pad_outline:g,hole_offset_x:typeof e.holeOffsetX=="number"?e.holeOffsetX:parseFloat(String(e.holeOffsetX||0)),hole_offset_y:typeof e.holeOffsetY=="number"?e.holeOffsetY:parseFloat(String(e.holeOffsetY||0)),port_hints:this.getNameAndAliases(),x:n.x,y:n.y,layers:r,soldermask_margin:s,is_covered_with_solder_mask:a,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=h.pcb_plated_hole_id}}doInitialPcbPortAttachment(){if(this.root?.pcbDisabled)return;const{db:t}=this.root;t.pcb_plated_hole.update(this.pcb_plated_hole_id,{pcb_port_id:this.matchedPort?.pcb_port_id})}_moveCircuitJsonElements({deltaX:t,deltaY:e}){if(this.root?.pcbDisabled)return;const{db:n}=this.root;if(!this.pcb_plated_hole_id)return;const o=n.pcb_plated_hole.get(this.pcb_plated_hole_id);if(o){const i={x:o.x+t,y:o.y+e};this._setPositionFromLayout(i)}}},qMt=class extends Ir{isSchematicPrimitive=!0;get config(){return{componentName:"SchematicArc",zodProps:qMn}}schematic_arc_id;doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled||this.getCollapsedSchematicBoxAncestor())return;const{db:t}=this.root,{_parsedProps:e}=this,n=this._getGlobalSchematicPositionBeforeLayout(),o=this.getPrimitiveContainer()?.parent?.schematic_component_id,i=this._getSymbolAncestor()?.schematic_symbol_id,r=t.schematic_arc.insert({schematic_component_id:o,schematic_symbol_id:i,center:{x:e.center.x+n.x,y:e.center.y+n.y},radius:e.radius,start_angle_degrees:e.startAngleDegrees,end_angle_degrees:e.endAngleDegrees,direction:e.direction,stroke_width:e.strokeWidth??v0e,color:e.color??wb,is_dashed:e.isDashed,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,schematic_sheet_id:this._resolveSchematicSheetId()});this.schematic_arc_id=r.schematic_arc_id}doInitialSchematicSymbolResize(){if(this.root?.schematicDisabled||!this.schematic_arc_id)return;const e=this._getSymbolAncestor()?.getUserCoordinateToResizedSymbolTransform();if(!e)return;const{db:n}=this.root,o=n.schematic_arc.get(this.schematic_arc_id);if(!o)return;const i=ts(e,o.center),r=ts(e,{x:o.center.x+o.radius,y:o.center.y}),s=Math.abs(r.x-i.x);n.schematic_arc.update(this.schematic_arc_id,{center:{x:i.x,y:i.y},radius:s})}},XMt=class extends Ir{isSchematicPrimitive=!0;get config(){return{componentName:"SchematicCircle",zodProps:tDn}}schematic_circle_id;doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled||this.getCollapsedSchematicBoxAncestor())return;const{db:t}=this.root,{_parsedProps:e}=this,n=this._getGlobalSchematicPositionBeforeLayout(),o=this.getPrimitiveContainer()?.parent?.schematic_component_id,i=this._getSymbolAncestor()?.schematic_symbol_id,r=t.schematic_circle.insert({schematic_component_id:o,schematic_symbol_id:i,center:{x:e.center.x+n.x,y:e.center.y+n.y},radius:e.radius,stroke_width:e.strokeWidth??v0e,color:e.color??wb,is_filled:e.isFilled,fill_color:e.fillColor,is_dashed:e.isDashed,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,schematic_sheet_id:this._resolveSchematicSheetId()});this.schematic_circle_id=r.schematic_circle_id}doInitialSchematicSymbolResize(){if(this.root?.schematicDisabled||!this.schematic_circle_id)return;const e=this._getSymbolAncestor()?.getUserCoordinateToResizedSymbolTransform();if(!e)return;const{db:n}=this.root,o=n.schematic_circle.get(this.schematic_circle_id);if(!o)return;const i=ts(e,o.center),r=ts(e,{x:o.center.x+o.radius,y:o.center.y}),s=Math.abs(r.x-i.x);n.schematic_circle.update(this.schematic_circle_id,{center:{x:i.x,y:i.y},radius:s})}},nPe=class extends Ir{isSchematicPrimitive=!0;get config(){return{componentName:"SchematicLine",zodProps:oDn}}schematic_line_id;doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled||this.getCollapsedSchematicBoxAncestor())return;const{db:t}=this.root,{_parsedProps:e}=this,n=this._getGlobalSchematicPositionBeforeLayout(),o=this.getPrimitiveContainer()?.parent?.schematic_component_id,i=this._getSymbolAncestor()?.schematic_symbol_id,r=t.schematic_line.insert({schematic_component_id:o,schematic_symbol_id:i,x1:e.x1+n.x,y1:e.y1+n.y,x2:e.x2+n.x,y2:e.y2+n.y,stroke_width:e.strokeWidth??v0e,color:e.color??wb,is_dashed:e.isDashed||e.dashLength!==void 0||e.dashGap!==void 0,dash_length:e.dashLength,dash_gap:e.dashGap,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,schematic_sheet_id:this._resolveSchematicSheetId()});this.schematic_line_id=r.schematic_line_id}doInitialSchematicSymbolResize(){if(this.root?.schematicDisabled||!this.schematic_line_id)return;const e=this._getSymbolAncestor()?.getUserCoordinateToResizedSymbolTransform();if(!e)return;const{db:n}=this.root,o=n.schematic_line.get(this.schematic_line_id);if(!o)return;const i=ts(e,{x:o.x1,y:o.y1}),r=ts(e,{x:o.x2,y:o.y2});n.schematic_line.update(this.schematic_line_id,{x1:i.x,y1:i.y,x2:r.x,y2:r.y})}};function Uj(t,e){const n=new lse(t),o=n.getTotalLength(),i=Math.max(2,Math.ceil(o*e)),r=[];for(let s=1;s<=i;s++){const a=s/i*o,A=n.getPointAtLength(a);r.push({x:A.x,y:A.y})}return r}function $7o(t,e=10){const n=new lse(t);n.toAbsolute();const o=n.segments,i=[];let r=[],s=0,a=0,A=0,c=0;for(const l of o)switch(l[0]){case"M":{r.length>0&&i.push(r),s=l[1],a=l[2],A=s,c=a,r=[{x:s,y:a}];break}case"L":{s=l[1],a=l[2],r.push({x:s,y:a});break}case"H":{s=l[1],r.push({x:s,y:a});break}case"V":{a=l[1],r.push({x:s,y:a});break}case"Z":{(s!==A||a!==c)&&r.push({x:A,y:c}),s=A,a=c;break}case"C":{const g=l[5],h=l[6],d=`M ${s} ${a} C ${l[1]} ${l[2]} ${l[3]} ${l[4]} ${g} ${h}`,p=Uj(d,e);r.push(...p),s=g,a=h;break}case"S":{const g=l[3],h=l[4],d=`M ${s} ${a} S ${l[1]} ${l[2]} ${g} ${h}`,p=Uj(d,e);r.push(...p),s=g,a=h;break}case"Q":{const g=l[3],h=l[4],d=`M ${s} ${a} Q ${l[1]} ${l[2]} ${g} ${h}`,p=Uj(d,e);r.push(...p),s=g,a=h;break}case"T":{const g=l[1],h=l[2],d=`M ${s} ${a} T ${g} ${h}`,p=Uj(d,e);r.push(...p),s=g,a=h;break}case"A":{const g=l[6],h=l[7],d=`M ${s} ${a} A ${l[1]} ${l[2]} ${l[3]} ${l[4]} ${l[5]} ${g} ${h}`,p=Uj(d,e);r.push(...p),s=g,a=h;break}}return r.length>0&&i.push(r),i.map(l=>{const u=[];for(const g of l)(u.length===0||Math.abs(u[u.length-1].x-g.x)>1e-9||Math.abs(u[u.length-1].y-g.y)>1e-9)&&u.push(g);return u})}var ZMt=class extends Ir{isSchematicPrimitive=!0;schematic_path_ids=[];get config(){return{componentName:"SchematicPath",zodProps:sDn}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled||this.getCollapsedSchematicBoxAncestor())return;const{db:t}=this.root,{_parsedProps:e}=this,n=this._getGlobalSchematicPositionBeforeLayout(),o=this.getPrimitiveContainer()?.parent?.schematic_component_id,i=this._getSymbolAncestor()?.schematic_symbol_id,r=this.getSubcircuit().subcircuit_id??void 0;if(this.schematic_path_ids=[],e.svgPath){const s=$7o(e.svgPath);for(const a of s){const A=t.schematic_path.insert({schematic_component_id:o,schematic_symbol_id:i,points:a.map(c=>({x:c.x+n.x,y:c.y+n.y})),is_filled:e.isFilled,is_dashed:e.dashLength!==void 0||e.dashGap!==void 0,fill_color:e.fillColor,stroke_color:e.strokeColor,stroke_width:e.strokeWidth,dash_length:e.dashLength,dash_gap:e.dashGap,subcircuit_id:r,schematic_sheet_id:this._resolveSchematicSheetId()});this.schematic_path_ids.push(A.schematic_path_id)}}else if(e.points&&e.points.length>0){const s=t.schematic_path.insert({schematic_component_id:o,schematic_symbol_id:i,points:e.points.map(a=>({x:a.x+n.x,y:a.y+n.y})),is_filled:e.isFilled,is_dashed:e.dashLength!==void 0||e.dashGap!==void 0,fill_color:e.fillColor,stroke_color:e.strokeColor,stroke_width:e.strokeWidth,dash_length:e.dashLength,dash_gap:e.dashGap,subcircuit_id:r,schematic_sheet_id:this._resolveSchematicSheetId()});this.schematic_path_ids.push(s.schematic_path_id)}}doInitialSchematicSymbolResize(){if(this.root?.schematicDisabled||this.schematic_path_ids.length===0)return;const e=this._getSymbolAncestor()?.getUserCoordinateToResizedSymbolTransform();if(!e)return;const{db:n}=this.root;for(const o of this.schematic_path_ids){const i=n.schematic_path.get(o);if(!i)continue;const r=i.points.map(s=>{const a=ts(e,s);return{x:a.x,y:a.y}});n.schematic_path.update(o,{points:r})}}},eDt=class extends Ir{isSchematicPrimitive=!0;get config(){return{componentName:"SchematicRect",zodProps:nDn}}schematic_rect_id;doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled||this.getCollapsedSchematicBoxAncestor())return;const{db:t}=this.root,{_parsedProps:e}=this,n=this._getGlobalSchematicPositionBeforeLayout(),o=this.getPrimitiveContainer()?.parent?.schematic_component_id,i=this._getSymbolAncestor()?.schematic_symbol_id,r=t.schematic_rect.insert({schematic_symbol_id:i,center:{x:n.x,y:n.y},width:e.width,height:e.height,stroke_width:e.strokeWidth??v0e,color:e.color??wb,is_filled:e.isFilled,schematic_component_id:o,is_dashed:e.isDashed,rotation:e.rotation??0,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,schematic_sheet_id:this._resolveSchematicSheetId()});this.schematic_rect_id=r.schematic_rect_id}doInitialSchematicSymbolResize(){if(this.root?.schematicDisabled||!this.schematic_rect_id)return;const e=this._getSymbolAncestor()?.getUserCoordinateToResizedSymbolTransform();if(!e)return;const{db:n}=this.root,o=n.schematic_rect.get(this.schematic_rect_id);if(!o)return;const i=ts(e,{x:o.center.x-o.width/2,y:o.center.y+o.height/2}),r=ts(e,{x:o.center.x+o.width/2,y:o.center.y-o.height/2}),s=Math.abs(r.x-i.x),a=Math.abs(i.y-r.y),A={x:(i.x+r.x)/2,y:(i.y+r.y)/2};n.schematic_rect.update(this.schematic_rect_id,{center:A,width:s,height:a})}},tDt=class extends Ir{isSchematicPrimitive=!0;schematic_text_id;get config(){return{componentName:"SchematicText",zodProps:rDn}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled||this.getCollapsedSchematicBoxAncestor())return;const{db:t}=this.root,{_parsedProps:e}=this,n=this._getGlobalSchematicPositionBeforeLayout(),o=this._getSymbolAncestor()?.schematic_symbol_id,i=this._resolveText(),r=t.schematic_text.insert({schematic_symbol_id:o,anchor:e.anchor??"center",text:Yj(i),font_size:e.fontSize,color:e.color||"#000000",position:{x:n.x,y:n.y},rotation:e.schRotation??0,schematic_sheet_id:this._resolveSchematicSheetId()});this.schematic_text_id=r.schematic_text_id}doInitialSchematicSymbolResize(){if(this.root?.schematicDisabled||!this.schematic_text_id)return;const e=this._getSymbolAncestor()?.getUserCoordinateToResizedSymbolTransform();if(!e)return;const{db:n}=this.root,o=n.schematic_text.get(this.schematic_text_id);if(!o)return;const i=ts(e,o.position);n.schematic_text.update(this.schematic_text_id,{position:{x:i.x,y:i.y}})}},nDt=class extends Ir{pcb_silkscreen_circle_id=null;isPcbPrimitive=!0;get config(){return{componentName:"SilkscreenCircle",zodProps:IDn}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:e}=this,n=this._getGlobalPcbPositionBeforeLayout(),{maybeFlipLayer:o}=this._getPcbPrimitiveFlippedHelpers(),i=o(e.layer??"top");if(i!=="top"&&i!=="bottom")throw new Error(`Invalid layer "${i}" for SilkscreenCircle. Must be "top" or "bottom".`);const r=this.getSubcircuit(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=t.pcb_silkscreen_circle.insert({pcb_component_id:s,layer:i,center:{x:n.x,y:n.y},radius:e.radius,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,stroke_width:e.strokeWidth??.1});this.pcb_silkscreen_circle_id=a.pcb_silkscreen_circle_id}getPcbSize(){const{_parsedProps:t}=this,e=t.radius*2;return{width:e,height:e}}_moveCircuitJsonElements({deltaX:t,deltaY:e}){if(this.root?.pcbDisabled)return;const{db:n}=this.root;if(!this.pcb_silkscreen_circle_id)return;const o=n.pcb_silkscreen_circle.get(this.pcb_silkscreen_circle_id);o&&n.pcb_silkscreen_circle.update(this.pcb_silkscreen_circle_id,{center:{x:o.center.x+t,y:o.center.y+e}})}},oDt=class extends Ir{pcb_silkscreen_line_id=null;isPcbPrimitive=!0;get config(){return{componentName:"SilkscreenLine",zodProps:_Dn}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:e}=this,{maybeFlipLayer:n}=this._getPcbPrimitiveFlippedHelpers(),o=n(e.layer??"top");if(o!=="top"&&o!=="bottom")throw new Error(`Invalid layer "${o}" for SilkscreenLine. Must be "top" or "bottom".`);const i=this.getSubcircuit(),r=this._computePcbGlobalTransformBeforeLayout(),s=ts(r,{x:e.x1,y:e.y1}),a=ts(r,{x:e.x2,y:e.y2}),A=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,c=t.pcb_silkscreen_line.insert({pcb_component_id:A,layer:o,x1:s.x,y1:s.y,x2:a.x,y2:a.y,stroke_width:e.strokeWidth??.1,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:i?.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_line_id=c.pcb_silkscreen_line_id}getPcbSize(){const{_parsedProps:t}=this,e=Math.abs(t.x2-t.x1),n=Math.abs(t.y2-t.y1);return{width:e,height:n}}_moveCircuitJsonElements({deltaX:t,deltaY:e}){if(this.root?.pcbDisabled)return;const{db:n}=this.root;if(!this.pcb_silkscreen_line_id)return;const o=n.pcb_silkscreen_line.get(this.pcb_silkscreen_line_id);o&&n.pcb_silkscreen_line.update(this.pcb_silkscreen_line_id,{x1:o.x1+t,y1:o.y1+e,x2:o.x2+t,y2:o.y2+e})}},iDt=class extends Ir{pcb_silkscreen_path_id=null;isPcbPrimitive=!0;get config(){return{componentName:"SilkscreenPath",zodProps:mDn}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:e}=this,{maybeFlipLayer:n}=this._getPcbPrimitiveFlippedHelpers(),o=n(e.layer??"top");if(o!=="top"&&o!=="bottom")throw new Error(`Invalid layer "${o}" for SilkscreenPath. Must be "top" or "bottom".`);const i=this._computePcbGlobalTransformBeforeLayout(),r=this.getSubcircuit(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=t.pcb_silkscreen_path.insert({pcb_component_id:s,layer:o,route:e.route.map(A=>{const c=ts(i,{x:A.x,y:A.y});return{...A,x:c.x,y:c.y}}),stroke_width:e.strokeWidth??.1,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_path_id=a.pcb_silkscreen_path_id}_setPositionFromLayout(t){const{db:e}=this.root,{_parsedProps:n}=this,o=e.pcb_silkscreen_path.get(this.pcb_silkscreen_path_id);if(!o)return;let i=0,r=0;for(const c of o.route)i+=c.x,r+=c.y;i/=o.route.length,r/=o.route.length;const s=t.x-i,a=t.y-r,A=o.route.map(c=>({...c,x:c.x+s,y:c.y+a}));e.pcb_silkscreen_path.update(this.pcb_silkscreen_path_id,{route:A})}_moveCircuitJsonElements({deltaX:t,deltaY:e}){if(this.root?.pcbDisabled)return;const{db:n}=this.root;if(!this.pcb_silkscreen_path_id)return;const o=n.pcb_silkscreen_path.get(this.pcb_silkscreen_path_id);o&&n.pcb_silkscreen_path.update(this.pcb_silkscreen_path_id,{route:o.route.map(i=>({...i,x:i.x+t,y:i.y+e}))})}getPcbSize(){const{_parsedProps:t}=this;if(!t.route||t.route.length===0)return{width:0,height:0};let e=1/0,n=-1/0,o=1/0,i=-1/0;for(const r of t.route)e=Math.min(e,r.x),n=Math.max(n,r.x),o=Math.min(o,r.y),i=Math.max(i,r.y);return{width:n-e,height:i-o}}},rDt=class extends Ir{pcb_silkscreen_rect_id=null;isPcbPrimitive=!0;get config(){return{componentName:"SilkscreenRect",zodProps:fDn}}_isRotated90Degrees(){const t=this._computePcbGlobalTransformBeforeLayout(),o=(O9(t).rotation.angle*180/Math.PI%360+360)%360,i=.01;return Math.abs(o-90)<i||Math.abs(o-270)<i}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:e}=this,{maybeFlipLayer:n}=this._getPcbPrimitiveFlippedHelpers(),o=n(e.layer??"top");if(o!=="top"&&o!=="bottom")throw new Error(`Invalid layer "${o}" for SilkscreenRect. Must be "top" or "bottom".`);const i=this.getSubcircuit(),r=this._getGlobalPcbPositionBeforeLayout(),s=this._isRotated90Degrees(),a=s?e.height:e.width,A=s?e.width:e.height,c=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,l=t.pcb_silkscreen_rect.insert({pcb_component_id:c,layer:o,center:{x:r.x,y:r.y},width:a,height:A,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:this?.getGroup()?.pcb_group_id??void 0,stroke_width:e.strokeWidth??.1,is_filled:e.filled??!1,corner_radius:e.cornerRadius??void 0});this.pcb_silkscreen_rect_id=l.pcb_silkscreen_rect_id}getPcbSize(){const{_parsedProps:t}=this;return this._isRotated90Degrees()?{width:t.height,height:t.width}:{width:t.width,height:t.height}}_moveCircuitJsonElements({deltaX:t,deltaY:e}){if(this.root?.pcbDisabled)return;const{db:n}=this.root;if(!this.pcb_silkscreen_rect_id)return;const o=n.pcb_silkscreen_rect.get(this.pcb_silkscreen_rect_id);o&&n.pcb_silkscreen_rect.update(this.pcb_silkscreen_rect_id,{center:{x:o.center.x+t,y:o.center.y+e}})}},oPe=class extends Ir{pcb_silkscreen_text_ids=[];isPcbPrimitive=!0;_footprinterFontSize;get config(){return{componentName:"SilkscreenText",zodProps:pDn}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:e}=this,n=this.getPrimitiveContainer(),{maybeFlipLayer:o,isFlipped:i}=this._getPcbPrimitiveFlippedHelpers(),r=this.getSubcircuit();let s=0;if(e.pcbRotation!==void 0&&e.pcbRotation!==0)s=e.pcbRotation;else{const C=this._computePcbGlobalTransformBeforeLayout();s=O9(C).rotation.angle*180/Math.PI}i&&(s=(s+180)%360);const a=new Set(e.layers);e.layer&&a.add(e.layer);const A=a.size>0?Array.from(a):["top"],c=pO({propertyName:"fontSize",resolvedPcbSx:this.getResolvedPcbSx(),pathFromAmpersand:"silkscreentext",component:this}),l=pO({propertyName:"pcbX",resolvedPcbSx:this.getResolvedPcbSx(),pathFromAmpersand:"silkscreentext",component:this}),u=pO({propertyName:"pcbY",resolvedPcbSx:this.getResolvedPcbSx(),pathFromAmpersand:"silkscreentext",component:this});if(pO({propertyName:"visibility",resolvedPcbSx:this.getResolvedPcbSx(),pathFromAmpersand:"silkscreentext",component:this})==="hidden")return;const h=e.fontSize??c??this.getInheritedProperty("pcbStyle")?.silkscreenFontSize??this._footprinterFontSize??1,p=(l!==void 0||u!==void 0)&&this._footprinterFontSize!==void 0?ts(D0(this.parent?._computePcbGlobalTransformBeforeLayout()??hC(),i?g3e():hC()),{x:this.resolvePcbCoordinate({rawValue:l??e.pcbX??0,axis:"pcbX"}),y:this.resolvePcbCoordinate({rawValue:u??e.pcbY??0,axis:"pcbY"})}):this._getGlobalPcbPositionBeforeLayout(),m=e.knockoutPadding??0,f=e.knockoutPadding!==void 0||e.knockoutPaddingLeft!==void 0||e.knockoutPaddingRight!==void 0||e.knockoutPaddingTop!==void 0||e.knockoutPaddingBottom!==void 0?{left:e.knockoutPaddingLeft??m,right:e.knockoutPaddingRight??m,top:e.knockoutPaddingTop??m,bottom:e.knockoutPaddingBottom??m}:void 0,I=this._resolveText();for(const C of A){const y=t.pcb_silkscreen_text.insert({anchor_alignment:e.anchorAlignment,anchor_position:{x:p.x,y:p.y},font:e.font??"tscircuit2024",font_size:h,layer:o(C),text:Yj(I),ccw_rotation:s,pcb_component_id:n.pcb_component_id,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,is_knockout:e.isKnockout,knockout_padding:f});this.pcb_silkscreen_text_ids.push(y.pcb_silkscreen_text_id)}}getPcbSize(){const{_parsedProps:t}=this,e=pO({propertyName:"fontSize",resolvedPcbSx:this.getResolvedPcbSx(),pathFromAmpersand:"silkscreentext",component:this}),n=t.fontSize??e??this.getInheritedProperty("pcbStyle")?.silkscreenFontSize??this._footprinterFontSize??1,i=this._resolveText().length*n,r=n;return{width:i*n,height:r*n}}_moveCircuitJsonElements({deltaX:t,deltaY:e}){if(this.root?.pcbDisabled)return;const{db:n}=this.root;for(const o of this.pcb_silkscreen_text_ids){const i=n.pcb_silkscreen_text.get(o);i&&n.pcb_silkscreen_text.update(o,{anchor_position:{x:i.anchor_position.x+t,y:i.anchor_position.y+e}})}}};function F0e({width:t,height:e,ccwRotationDegrees:n}){const o=n*Math.PI/180,i=Math.cos(o),r=Math.sin(o),s=t/2,a=e/2,A=Math.abs(s*i)+Math.abs(a*r),c=Math.abs(s*r)+Math.abs(a*i);return{width:A*2,height:c*2,xExtent:A,yExtent:c}}var Mb=class extends Ir{pcb_smtpad_id=null;matchedPort=null;isPcbPrimitive=!0;get config(){return{componentName:"SmtPad",zodProps:pPn}}getPcbSize(){const{_parsedProps:t}=this;if(t.shape==="circle")return{width:t.radius*2,height:t.radius*2};if(t.shape==="rect")return{width:t.width,height:t.height};if(t.shape==="rotated_rect"){const{width:e,height:n}=F0e({width:t.width,height:t.height,ccwRotationDegrees:t.ccwRotation??0});return{width:e,height:n}}if(t.shape==="polygon"){const e=t.points,n=e.map(A=>A.x),o=e.map(A=>A.y),i=Math.min(...n),r=Math.max(...n),s=Math.min(...o),a=Math.max(...o);return{width:r-i,height:a-s}}if(t.shape==="pill")return{width:t.width,height:t.height};if(t.shape==="rotated_pill"){const{width:e,height:n}=F0e({width:t.width,height:t.height,ccwRotationDegrees:t.ccwRotation});return{width:e,height:n}}throw new Error(`getPcbSize for shape "${t.shape}" not implemented for ${this.componentName}`)}doInitialPortMatching(){const t=this.getPrimitiveContainer()?.selectAll("port");if(!this.props.portHints)return;const e=$Mt(t,this,this.props.portHints);e&&(this.matchedPort=e,e.registerMatch(this))}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:e}=this,n=e.coveredWithSolderMask??!1,o=!n,i=e.solderMaskMargin,r=e.solderPasteMargin,s=(Q,w=2)=>r!==void 0?Math.max(Q+w*r,0):Q*.7;this.emitSolderMaskMarginWarning(n,i);const a=this.getSubcircuit(),A=this._getGlobalPcbPositionBeforeLayout(),c=this._computePcbGlobalTransformBeforeLayout(),g=(O9(this._computePcbGlobalTransformBeforeLayout()).rotation.angle*180/Math.PI%360+360)%360,h=.01,d=Math.abs(g)<h||Math.abs(g-180)<h||Math.abs(g-360)<h,p=Math.abs(g-90)<h||Math.abs(g-270)<h;let m=Math.abs(g-360)<h?0:g;const _=m,{maybeFlipLayer:f,isFlipped:I}=this._getPcbPrimitiveFlippedHelpers(),C=this.getPrimitiveContainer(),y=C?.props?.layer!==void 0?C?._parsedProps.layer:void 0,x=Q=>y??f(Q);I&&(m=(360-m+360)%360);const E=e.portHints?.map(Q=>Q.toString())??[];let B=null;const S=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id;if(e.shape==="circle"){B=t.pcb_smtpad.insert({pcb_component_id:S,pcb_port_id:this.matchedPort?.pcb_port_id,layer:x(e.layer??"top"),shape:"circle",radius:e.radius,port_hints:E,is_covered_with_solder_mask:n,soldermask_margin:i,x:A.x,y:A.y,subcircuit_id:a?.subcircuit_id??void 0});const Q=s(B.radius,1);o&&Q>0&&t.pcb_solder_paste.insert({layer:B.layer,shape:"circle",radius:Q,x:B.x,y:B.y,pcb_component_id:B.pcb_component_id,pcb_smtpad_id:B.pcb_smtpad_id,subcircuit_id:a?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(e.shape==="rect"){!d&&!p?B=t.pcb_smtpad.insert({pcb_component_id:S,pcb_port_id:this.matchedPort?.pcb_port_id,layer:x(e.layer??"top"),shape:"rotated_rect",width:e.width,height:e.height,corner_radius:e.cornerRadius??void 0,x:A.x,y:A.y,ccw_rotation:m,port_hints:E,is_covered_with_solder_mask:n,soldermask_margin:i,subcircuit_id:a?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}):B=t.pcb_smtpad.insert({pcb_component_id:S,pcb_port_id:this.matchedPort?.pcb_port_id,layer:x(e.layer??"top"),shape:"rect",width:p?e.height:e.width,height:p?e.width:e.height,corner_radius:e.cornerRadius??void 0,port_hints:E,is_covered_with_solder_mask:n,soldermask_margin:i,x:A.x,y:A.y,subcircuit_id:a?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});const w=s(B.width),M=s(B.height);o&&w>0&&M>0&&(B.shape==="rect"?t.pcb_solder_paste.insert({layer:x(e.layer??"top"),shape:"rect",width:w,height:M,x:B.x,y:B.y,pcb_component_id:B.pcb_component_id,pcb_smtpad_id:B.pcb_smtpad_id,subcircuit_id:a?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}):B.shape==="rotated_rect"&&t.pcb_solder_paste.insert({layer:x(e.layer??"top"),shape:"rotated_rect",width:w,height:M,x:B.x,y:B.y,ccw_rotation:B.ccw_rotation,pcb_component_id:B.pcb_component_id,pcb_smtpad_id:B.pcb_smtpad_id,subcircuit_id:a?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}))}else if(e.shape==="rotated_rect"){const Q=e.ccwRotation??0,w=(_+Q+360)%360,M=I?(360-w+360)%360:w;B=t.pcb_smtpad.insert({pcb_component_id:S,pcb_port_id:this.matchedPort?.pcb_port_id,layer:x(e.layer??"top"),shape:"rotated_rect",width:e.width,height:e.height,corner_radius:e.cornerRadius??void 0,x:A.x,y:A.y,ccw_rotation:M,port_hints:E,is_covered_with_solder_mask:n,soldermask_margin:i,subcircuit_id:a?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});const k=s(B.width),R=s(B.height);o&&k>0&&R>0&&t.pcb_solder_paste.insert({layer:x(e.layer??"top"),shape:"rotated_rect",width:k,height:R,x:A.x,y:A.y,ccw_rotation:M,pcb_component_id:S,pcb_smtpad_id:B.pcb_smtpad_id,subcircuit_id:a?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(e.shape==="polygon"){const Q=e.points.map(w=>{const M=ts(c,{x:lt.parse(w.x),y:lt.parse(w.y)});return{x:M.x,y:M.y}});B=t.pcb_smtpad.insert({pcb_component_id:S,pcb_port_id:this.matchedPort?.pcb_port_id,layer:x(e.layer??"top"),shape:"polygon",points:Q,port_hints:E,is_covered_with_solder_mask:n,soldermask_margin:i,subcircuit_id:a?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(e.shape==="rotated_pill"){const Q=(_+e.ccwRotation+360)%360,w=I?(360-Q+360)%360:Q;B=t.pcb_smtpad.insert({pcb_component_id:S,pcb_port_id:this.matchedPort?.pcb_port_id,layer:x(e.layer??"top"),shape:"rotated_pill",x:A.x,y:A.y,radius:e.radius,height:e.height,width:e.width,ccw_rotation:w,port_hints:E,is_covered_with_solder_mask:n,soldermask_margin:i,subcircuit_id:a?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else e.shape==="pill"&&(m!==0?B=t.pcb_smtpad.insert({pcb_component_id:S,pcb_port_id:this.matchedPort?.pcb_port_id,layer:x(e.layer??"top"),shape:"rotated_pill",x:A.x,y:A.y,radius:e.radius,height:e.height,width:e.width,ccw_rotation:m,port_hints:E,is_covered_with_solder_mask:n,soldermask_margin:i,subcircuit_id:a?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}):B=t.pcb_smtpad.insert({pcb_component_id:S,pcb_port_id:this.matchedPort?.pcb_port_id,layer:x(e.layer??"top"),shape:"pill",x:A.x,y:A.y,radius:e.radius,height:e.height,width:e.width,port_hints:E,is_covered_with_solder_mask:n,soldermask_margin:i,subcircuit_id:a?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}));B&&(this.pcb_smtpad_id=B.pcb_smtpad_id)}doInitialPcbPortAttachment(){if(this.root?.pcbDisabled)return;const{db:t}=this.root;t.pcb_smtpad.update(this.pcb_smtpad_id,{pcb_port_id:this.matchedPort?.pcb_port_id})}getAvailablePcbLayers(){const{maybeFlipLayer:t}=this._getPcbPrimitiveFlippedHelpers(),e=this.getPrimitiveContainer();return[(e?.props?.layer!==void 0?e?._parsedProps.layer:void 0)??t(this._parsedProps.layer??"top")]}_getPcbCircuitJsonBounds(){const{db:t}=this.root,e=t.pcb_smtpad.get(this.pcb_smtpad_id);if(e.shape==="rect")return{center:{x:e.x,y:e.y},bounds:{left:e.x-e.width/2,top:e.y+e.height/2,right:e.x+e.width/2,bottom:e.y-e.height/2},width:e.width,height:e.height};if(e.shape==="rotated_rect"){const{width:n,height:o,xExtent:i,yExtent:r}=F0e({width:e.width,height:e.height,ccwRotationDegrees:e.ccw_rotation});return{center:{x:e.x,y:e.y},bounds:{left:e.x-i,right:e.x+i,top:e.y-r,bottom:e.y+r},width:n,height:o}}if(e.shape==="circle")return{center:{x:e.x,y:e.y},bounds:{left:e.x-e.radius,top:e.y-e.radius,right:e.x+e.radius,bottom:e.y+e.radius},width:e.radius*2,height:e.radius*2};if(e.shape==="polygon"){const n=e.points,o=n.map(c=>c.x),i=n.map(c=>c.y),r=Math.min(...o),s=Math.max(...o),a=Math.min(...i),A=Math.max(...i);return{center:{x:(r+s)/2,y:(a+A)/2},bounds:{left:r,top:A,right:s,bottom:a},width:s-r,height:A-a}}if(e.shape==="pill"){const n=e.width/2,o=e.height/2;return{center:{x:e.x,y:e.y},bounds:{left:e.x-n,top:e.y-o,right:e.x+n,bottom:e.y+o},width:e.width,height:e.height}}if(e.shape==="rotated_pill"){const{width:n,height:o,xExtent:i,yExtent:r}=F0e({width:e.width,height:e.height,ccwRotationDegrees:e.ccw_rotation});return{center:{x:e.x,y:e.y},bounds:{left:e.x-i,right:e.x+i,top:e.y-r,bottom:e.y+r},width:n,height:o}}throw new Error(`circuitJson bounds calculation not implemented for shape "${e.shape}"`)}_setPositionFromLayout(t){const{db:e}=this.root;e.pcb_smtpad.update(this.pcb_smtpad_id,{x:t.x,y:t.y});const n=e.pcb_solder_paste.list().find(o=>o.pcb_smtpad_id===this.pcb_smtpad_id);n&&e.pcb_solder_paste.update(n.pcb_solder_paste_id,{x:t.x,y:t.y}),this.matchedPort?._setPositionFromLayout(t)}_moveCircuitJsonElements({deltaX:t,deltaY:e}){if(this.root?.pcbDisabled)return;const{db:n}=this.root;if(!this.pcb_smtpad_id)return;const o=n.pcb_smtpad.get(this.pcb_smtpad_id);if(o.shape==="rect"||o.shape==="circle"||o.shape==="rotated_rect"||o.shape==="pill"||o.shape==="rotated_pill")this._setPositionFromLayout({x:o.x+t,y:o.y+e});else if(o.shape==="polygon"){n.pcb_smtpad.update(this.pcb_smtpad_id,{points:o.points.map(r=>({x:r.x+t,y:r.y+e}))});const i={x:this._getPcbCircuitJsonBounds().center.x+t/2,y:this._getPcbCircuitJsonBounds().center.y+e/2};this.matchedPort?._setPositionFromLayout(i)}}},iPe=class extends Ir{isPrimitiveContainer=!0;schematic_symbol_id;userCoordinateToResizedSymbolTransformMat;schematicSymbolBoundsInUserCoordinates;get config(){return{componentName:"Symbol",zodProps:DPn}}hasExplicitSize(){const{_parsedProps:t}=this;return t.width!==void 0||t.height!==void 0}doInitialSymbolContainerRender(){if(this.root?.schematicDisabled)return;const{db:t}=this.root,{_parsedProps:e}=this,o=this.getParentNormalComponent()?._parsedProps?.kicadSymbolMetadata,i=t.schematic_symbol.insert({name:e.name,metadata:o?{kicad_symbol:o}:void 0});this.schematic_symbol_id=i.schematic_symbol_id}getSchematicSymbolBounds(){return this.schematicSymbolBoundsInUserCoordinates?this.schematicSymbolBoundsInUserCoordinates:(this._computeSchematicSymbolBounds(),this.schematicSymbolBoundsInUserCoordinates??null)}getUserCoordinateToResizedSymbolTransform(){return this.hasExplicitSize()?this.userCoordinateToResizedSymbolTransformMat?this.userCoordinateToResizedSymbolTransformMat:(this._computeUserCoordinateToResizedSymbolTransform(),this.userCoordinateToResizedSymbolTransformMat??null):null}_computeSchematicSymbolBounds(){if(this.root?.schematicDisabled)return;const{db:t}=this.root,e=[];for(const o of this.children){if(o.componentName==="Port"){const i=o.schematic_port_id;if(i){const r=t.schematic_port.get(i);r&&e.push(r)}continue}if(o.isSchematicPrimitive){if(o.componentName==="SchematicLine"){const i=t.schematic_line.get(o.schematic_line_id);i&&e.push(i)}else if(o.componentName==="SchematicRect"){const i=t.schematic_rect.get(o.schematic_rect_id);i&&e.push(i)}else if(o.componentName==="SchematicCircle"){const i=t.schematic_circle.get(o.schematic_circle_id);i&&e.push(i)}else if(o.componentName==="SchematicArc"){const i=t.schematic_arc.get(o.schematic_arc_id);i&&e.push(i)}else if(o.componentName==="SchematicText"){const i=t.schematic_text.get(o.schematic_text_id);i&&e.push(i)}else if(o.componentName==="SchematicPath"){const i=o.schematic_path_ids;if(i)for(const r of i){const s=t.schematic_path.get(r);s&&e.push(s)}}}}if(e.length===0)return;const n=Gj(e);this.schematicSymbolBoundsInUserCoordinates=n}_computeUserCoordinateToResizedSymbolTransform(){const t=this.getSchematicSymbolBounds();if(!t)return;const{_parsedProps:e}=this,n=e.width,o=e.height;if(n===void 0&&o===void 0)return;const i=t.maxX-t.minX,r=t.maxY-t.minY;if(i===0&&r===0)return;const s=(t.minX+t.maxX)/2,a=(t.minY+t.maxY)/2,A=n!==void 0&&i>0?n/i:1,c=o!==void 0&&r>0?o/r:1,l=this._getGlobalSchematicPositionBeforeLayout();this.userCoordinateToResizedSymbolTransformMat=D0(M0(l.x,l.y),FV(A,c),M0(-s,-a))}},q7o=({elm:t,pinLabels:e,layer:n,readableRotation:o,anchorAlignment:i})=>{const r=t.text.replace(/[{}]/g,"").toLowerCase();let s=r;if(Array.isArray(e)){const A=parseInt(r.replace(/[^\d]/g,""),10)-1;s=String(e[A]??r)}else typeof e=="object"&&(s=String(e[r]??r));const a=new oPe({anchorAlignment:i||"center",text:s??r,layer:n||"top",pcbX:isNaN(t.anchor_position.x)?0:t.anchor_position.x,pcbY:t.anchor_position.y,pcbRotation:o??0});return a._footprinterFontSize=t.font_size+.2,a},X7o=(t,e)=>{const n=parseInt(t||"0",10);let o;return e!=null?o=e-n:o=n,(o%360+360)%360},_O=t=>t??void 0,Z7o=t=>{for(const e of t??[]){if(/^\d+$/.test(e))return Number(e);const n=/^pin(\d+)$/i.exec(e);if(n)return Number(n[1])}},e6o=t=>{switch(t){case"left":case"right":return t;case"top":return"up";case"bottom":return"down"}return null},t6o=["schematic_line","schematic_rect","schematic_circle","schematic_arc","schematic_path"],n6o=t=>t6o.includes(t.type),sDt=t=>{if("schematic_symbol_id"in t)return typeof t.schematic_symbol_id=="string"?t.schematic_symbol_id:void 0},Db=({componentName:t,componentRotation:e,footprinterString:n,pinLabels:o,pcbPinLabels:i},r)=>{const s=[],a=new Map,A=new Map,c=new Map,l=new Map,u=new Map,g=new Map;for(const p of r)if(p.type==="pcb_component"&&typeof p.source_component_id=="string"&&c.set(p.pcb_component_id,p.source_component_id),p.type==="source_port"&&(l.set(p.source_port_id,p),typeof p.pin_number=="number"&&typeof p.source_component_id=="string")){let m=u.get(p.source_component_id);m||(m=new Map,u.set(p.source_component_id,m)),m.set(p.pin_number,p)}const h=(p,m)=>{const _=Z7o(p),f=typeof m=="string"?c.get(m):void 0,I=typeof _=="number"&&f?u.get(f)?.get(_):void 0;if(!I)return p;const C=Array.from(new Set([...p??[],...I.port_hints??[],I.name].filter(y=>typeof y=="string"&&y.length>0)));return C.length>0?C:p};for(const p of r){if(p.type!=="schematic_symbol")continue;const m=new iPe({name:p.name});a.set(p.schematic_symbol_id,m),s.push(m)}for(const p of r){if(!n6o(p))continue;const m=sDt(p),_=p.stroke_width;!m||typeof _!="number"||!Number.isFinite(_)||g.has(m)||g.set(m,_)}for(const p of r)p.type==="schematic_component"&&A.set(p.schematic_component_id,p);const d=(p,m)=>{const _=sDt(p)??("schematic_component_id"in p&&typeof p.schematic_component_id=="string"?A.get(p.schematic_component_id)?.schematic_symbol_id:void 0),f=typeof _=="string"?a.get(_):void 0;f?f.add(m):s.push(m)};for(const p of r){const m="port_hints"in p?h(p.port_hints,"pcb_component_id"in p?p.pcb_component_id:void 0):void 0;if(p.type==="pcb_smtpad"&&p.shape==="rect")s.push(new Mb({pcbX:p.x,pcbY:p.y,layer:p.layer,shape:"rect",height:p.height,width:p.width,portHints:m,rectBorderRadius:p.rect_border_radius}));else if(p.type==="pcb_smtpad"&&p.shape==="circle")s.push(new Mb({pcbX:p.x,pcbY:p.y,layer:p.layer,shape:"circle",radius:p.radius,portHints:m}));else if(p.type==="pcb_smtpad"&&p.shape==="pill")s.push(new Mb({shape:"pill",height:p.height,width:p.width,radius:p.radius,portHints:m,pcbX:p.x,pcbY:p.y,layer:p.layer}));else if(p.type==="pcb_smtpad"&&p.shape==="rotated_pill")s.push(new Mb({shape:"rotated_pill",height:p.height,width:p.width,radius:p.radius,portHints:m,pcbX:p.x,pcbY:p.y,layer:p.layer,ccwRotation:p.ccw_rotation}));else if(p.type==="pcb_smtpad"&&p.shape==="rotated_rect")s.push(new Mb({pcbX:p.x,pcbY:p.y,layer:p.layer,shape:"rotated_rect",height:p.height,width:p.width,ccwRotation:p.ccw_rotation,cornerRadius:p.corner_radius,portHints:m}));else if(p.type==="pcb_smtpad"&&p.shape==="polygon")s.push(new Mb({shape:"polygon",points:p.points,portHints:m,layer:p.layer}));else if(p.type==="pcb_silkscreen_path")s.push(new iDt({layer:p.layer,route:p.route,strokeWidth:p.stroke_width}));else if(p.type==="pcb_copper_text")s.push(new FMt({text:p.text,pcbX:p.anchor_position.x,pcbY:p.anchor_position.y,pcbRotation:p.ccw_rotation,anchorAlignment:p.anchor_alignment,fontSize:p.font_size,layer:p.layer,mirrored:p.is_mirrored,knockout:p.is_knockout}));else if(p.type==="pcb_plated_hole")p.shape==="circle"?s.push(new Pb({pcbX:p.x,pcbY:p.y,shape:"circle",holeDiameter:p.hole_diameter,outerDiameter:p.outer_diameter,portHints:m})):p.shape==="circular_hole_with_rect_pad"?s.push(new Pb({pcbX:p.x,pcbY:p.y,shape:"circular_hole_with_rect_pad",holeDiameter:p.hole_diameter,rectPadHeight:p.rect_pad_height,rectPadWidth:p.rect_pad_width,portHints:m,rectBorderRadius:p.rect_border_radius,holeOffsetX:p.hole_offset_x,holeOffsetY:p.hole_offset_y})):p.shape==="pill"||p.shape==="oval"?s.push(new Pb({pcbX:p.x,pcbY:p.y,shape:p.shape,holeWidth:p.hole_width,holeHeight:p.hole_height,outerWidth:p.outer_width,outerHeight:p.outer_height,portHints:m})):p.shape==="pill_hole_with_rect_pad"?s.push(new Pb({pcbX:p.x,pcbY:p.y,shape:"pill_hole_with_rect_pad",holeShape:"pill",padShape:"rect",holeWidth:p.hole_width,holeHeight:p.hole_height,rectPadWidth:p.rect_pad_width,rectPadHeight:p.rect_pad_height,rectBorderRadius:p.rect_border_radius,portHints:m,holeOffsetX:p.hole_offset_x,holeOffsetY:p.hole_offset_y})):p.shape==="rotated_pill_hole_with_rect_pad"?s.push(new Pb({pcbX:p.x,pcbY:p.y,shape:"pill_hole_with_rect_pad",holeShape:"pill",padShape:"rect",holeWidth:p.hole_width,holeHeight:p.hole_height,rectPadWidth:p.rect_pad_width,rectPadHeight:p.rect_pad_height,rectBorderRadius:p.rect_border_radius,portHints:m,holeOffsetX:p.hole_offset_x,holeOffsetY:p.hole_offset_y,pcbRotation:p.hole_ccw_rotation})):p.shape==="hole_with_polygon_pad"&&s.push(new Pb({pcbX:p.x,pcbY:p.y,shape:"hole_with_polygon_pad",holeShape:p.hole_shape||"circle",holeDiameter:p.hole_diameter,holeWidth:p.hole_width,holeHeight:p.hole_height,padOutline:p.pad_outline||[],holeOffsetX:p.hole_offset_x,holeOffsetY:p.hole_offset_y,portHints:m}));else if(p.type==="pcb_keepout"&&p.shape==="circle")s.push(new k0e({pcbX:p.center.x,pcbY:p.center.y,shape:"circle",radius:p.radius}));else if(p.type==="pcb_keepout"&&p.shape==="rect")s.push(new k0e({pcbX:p.center.x,pcbY:p.center.y,shape:"rect",width:p.width,height:p.height}));else if(p.type==="pcb_hole"&&p.hole_shape==="circle")s.push(new mO({pcbX:p.x,pcbY:p.y,diameter:p.hole_diameter}));else if(p.type==="pcb_hole"&&p.hole_shape==="rect")s.push(new mO({pcbX:p.x,pcbY:p.y,shape:"rect",width:p.hole_width,height:p.hole_height}));else if(p.type==="pcb_hole"&&p.hole_shape==="pill")s.push(new mO({pcbX:p.x,pcbY:p.y,shape:"pill",width:p.hole_width,height:p.hole_height}));else if(p.type==="pcb_hole"&&p.hole_shape==="oval")s.push(new mO({pcbX:p.x,pcbY:p.y,shape:"oval",width:p.hole_width,height:p.hole_height}));else if(p.type==="pcb_hole"&&p.hole_shape==="rotated_pill")s.push(new mO({pcbX:p.x,pcbY:p.y,shape:"pill",width:p.hole_width,height:p.hole_height,pcbRotation:p.ccw_rotation}));else if(p.type==="pcb_cutout")p.shape==="rect"?s.push(new T0e({pcbX:p.center.x,pcbY:p.center.y,shape:"rect",width:p.width,height:p.height})):p.shape==="circle"?s.push(new T0e({pcbX:p.center.x,pcbY:p.center.y,shape:"circle",radius:p.radius})):p.shape==="polygon"&&s.push(new T0e({shape:"polygon",points:p.points}));else if(p.type==="pcb_silkscreen_text"){const _=X7o(e,p.ccw_rotation);if((n?.includes("pinrow")||n?.includes("headermodule"))&&p.text.includes("PIN"))s.push(q7o({elm:p,pinLabels:i??o??{},layer:p.layer,readableRotation:_,anchorAlignment:p.anchor_alignment}));else{const f=new oPe({anchorAlignment:p.anchor_alignment||"center",text:n?.includes("silkscreenlabel(")&&p.text!=="{REF}"&&p.text!=="{NAME}"&&p.text!=="{REFERENCE}"?p.text:t||p.text,pcbX:Number.isNaN(p.anchor_position.x)?0:p.anchor_position.x,pcbY:p.anchor_position.y,pcbRotation:_??0});f._footprinterFontSize=p.font_size+.2,s.push(f)}}else if(p.type==="pcb_trace")s.push(new tPe({route:p.route}));else if(p.type==="pcb_via"){const _=Sne.parse(p),f=p.layers??[],I=new jMt({pcbX:p.x,pcbY:p.y,holeDiameter:p.hole_diameter,outerDiameter:p.outer_diameter,fromLayer:p.from_layer??f[0],toLayer:p.to_layer??f[f.length-1],layers:f,netIsAssignable:p.net_is_assignable,tentedOnTop:_.tented_on_top,tentedOnBottom:_.tented_on_bottom});I._importedPcbTraceId=p.pcb_trace_id,s.push(I)}else if(p.type==="pcb_silkscreen_rect")s.push(new rDt({pcbX:p.center.x,pcbY:p.center.y,width:p.width,height:p.height,layer:p.layer,strokeWidth:p.stroke_width,filled:p.is_filled,cornerRadius:p.corner_radius}));else if(p.type==="pcb_silkscreen_circle")s.push(new nDt({pcbX:p.center.x,pcbY:p.center.y,radius:p.radius,layer:p.layer,strokeWidth:p.stroke_width}));else if(p.type==="pcb_silkscreen_line")s.push(new oDt({x1:p.x1,y1:p.y1,x2:p.x2,y2:p.y2,layer:p.layer,strokeWidth:p.stroke_width}));else if(p.type==="pcb_fabrication_note_text")s.push(new KMt({pcbX:p.anchor_position.x,pcbY:p.anchor_position.y,text:p.text,fontSize:p.font_size,anchorAlignment:p.anchor_alignment,color:p.color,font:p.font,layer:p.layer,pcbRotation:p.ccw_rotation}));else if(p.type==="pcb_fabrication_note_path")s.push(new GMt({route:p.route,strokeWidth:p.stroke_width,color:p.color,layer:p.layer}));else if(p.type==="pcb_fabrication_note_rect")s.push(new YMt({pcbX:p.center.x,pcbY:p.center.y,width:p.width,height:p.height,strokeWidth:p.stroke_width,isFilled:p.is_filled,color:p.color,layer:p.layer,cornerRadius:p.corner_radius,hasStroke:p.has_stroke,isStrokeDashed:p.is_stroke_dashed}));else if(p.type==="pcb_note_text")s.push(new WMt({pcbX:p.anchor_position.x,pcbY:p.anchor_position.y,text:p.text??"",fontSize:p.font_size,anchorAlignment:p.anchor_alignment,color:p.color,font:p.font}));else if(p.type==="pcb_note_rect")s.push(new JMt({pcbX:p.center.x,pcbY:p.center.y,width:p.width,height:p.height,strokeWidth:p.stroke_width,isFilled:p.is_filled,color:p.color,cornerRadius:p.corner_radius,hasStroke:p.has_stroke,isStrokeDashed:p.is_stroke_dashed}));else if(p.type==="pcb_note_path")s.push(new zMt({route:p.route,strokeWidth:p.stroke_width,color:p.color}));else if(p.type==="pcb_note_line")s.push(new VMt({x1:p.x1,y1:p.y1,x2:p.x2,y2:p.y2,strokeWidth:p.stroke_width,color:p.color,isDashed:p.is_dashed}));else if(p.type==="pcb_courtyard_rect")s.push(new OMt({pcbX:p.center.x,pcbY:p.center.y,width:p.width,height:p.height,pcbRotation:p.ccw_rotation,layer:p.layer}));else if(p.type==="pcb_courtyard_circle")s.push(new LMt({pcbX:p.center.x,pcbY:p.center.y,radius:p.radius,layer:p.layer}));else if(p.type==="pcb_courtyard_outline")s.push(new HMt({outline:p.outline,layer:p.layer}));else if(p.type==="schematic_line")d(p,new nPe({x1:p.x1,y1:p.y1,x2:p.x2,y2:p.y2,strokeWidth:_O(p.stroke_width),color:p.color,isDashed:p.is_dashed}));else if(p.type==="schematic_rect")d(p,new eDt({schX:p.center.x,schY:p.center.y,width:p.width,height:p.height,rotation:p.rotation,strokeWidth:_O(p.stroke_width),color:p.color,isFilled:p.is_filled,fillColor:p.fill_color,isDashed:p.is_dashed}));else if(p.type==="schematic_circle")d(p,new XMt({center:p.center,radius:p.radius,strokeWidth:_O(p.stroke_width),color:p.color,isFilled:p.is_filled,fillColor:p.fill_color,isDashed:p.is_dashed}));else if(p.type==="schematic_arc")d(p,new qMt({center:p.center,radius:p.radius,startAngleDegrees:p.start_angle_degrees,endAngleDegrees:p.end_angle_degrees,direction:p.direction,strokeWidth:_O(p.stroke_width),color:p.color,isDashed:p.is_dashed}));else if(p.type==="schematic_text")d(p,new tDt({schX:p.position.x,schY:p.position.y,text:p.text,fontSize:p.font_size,anchor:p.anchor,color:p.color,schRotation:p.rotation}));else if(p.type==="schematic_path")d(p,new ZMt({points:p.points,strokeWidth:_O(p.stroke_width),strokeColor:p.stroke_color,dashLength:p.dash_length,dashGap:p.dash_gap,isFilled:p.is_filled,fillColor:p.fill_color}));else if(p.type==="schematic_port"){const _=p.schematic_component_id;if(typeof _!="string")continue;const f=A.get(_),I=f?.schematic_symbol_id,C=typeof I=="string"?a.get(I):void 0;if(C&&f?.is_box_with_pins===!0&&p.center&&p.side_of_component){const y=p.distance_from_component_edge,x=e6o(p.side_of_component);if(!x)continue;const E=Jk(x),B=p.facing_direction===x?1:-1,S={x:p.center.x+E.x*y*B,y:p.center.y+E.y*y*B},Q=l.get(p.source_port_id),w=Array.from(new Set([p.display_pin_label,Q?.name,...Q?.port_hints??[]].filter(R=>typeof R=="string"&&R.length>0))),M=p.pin_number?`pin${p.pin_number}`:p.schematic_port_id,k=w[0]??p.source_port_id??M;C.add(new Pu({pinNumber:p.pin_number,name:k,aliases:w,schX:p.center.x,schY:p.center.y,direction:x})),C.add(new nPe({x1:p.center.x,y1:p.center.y,x2:S.x,y2:S.y,strokeWidth:typeof I=="string"?_O(g.get(I)):void 0,isDashed:!1}))}}}return s},o6o=["Silkscreen","PcbNote","Courtyard","FabricationNote"];function L0e(t){let e=1/0,n=1/0,o=-1/0,i=-1/0,r=!1;for(const A of t)if(A.isPcbPrimitive&&!o6o.some(c=>A.componentName.startsWith(c))){const c=A._getPcbLocalBoundsBeforeLayout(),u=[{x:c.left,y:c.bottom},{x:c.right,y:c.bottom},{x:c.right,y:c.top},{x:c.left,y:c.top}].map(d=>ts(A._computePcbGlobalTransformBeforeLayout(),d)),g=u.map(d=>d.x),h=u.map(d=>d.y);e=Math.min(e,...g),n=Math.min(n,...h),o=Math.max(o,...g),i=Math.max(i,...h),r=!0}else if(A.children.length>0){const c=L0e(A.children);(c.width>0||c.height>0)&&(e=Math.min(e,c.minX),n=Math.min(n,c.minY),o=Math.max(o,c.maxX),i=Math.max(i,c.maxY),r=!0)}if(!r)return{minX:0,minY:0,maxX:0,maxY:0,width:0,height:0};let s=o-e,a=i-n;return s<0&&(s=0),a<0&&(a=0),{minX:e,minY:n,maxX:o,maxY:i,width:s,height:a}}var H0e=t=>{const e=t.find(n=>/^(pin)?\d+$/.test(n));return e?Number.parseInt(e.replace(/^pin/,"")):null};function O0e(t,e){const n=H0e(t);if(!n)return null;const i=[...t.filter(r=>r.toString()!==n.toString()&&r!==`pin${n}`&&r.trim()!==""),...e?.additionalAliases?.[`pin${n}`]??[]];return new Pu({pinNumber:n,aliases:i})}function gw(t){return t?Array.isArray(t)?t:t.pins??[]:[]}var aDt=t=>{for(const e of["leftSide","rightSide","topSide","bottomSide"])if(e in t&&typeof t[e]=="number")throw new Error(`A number was specified for "${e}", you probably meant to use "size" not "side"`);return"leftSide"in t||"rightSide"in t||"topSide"in t||"bottomSide"in t},rPe=t=>!t||!aDt(t)?[]:[...gw(t.leftSide),...gw(t.rightSide),...gw(t.topSide),...gw(t.bottomSide)],i6o=t=>{if(aDt(t))return{leftSize:gw(t.leftSide).length,rightSize:gw(t.rightSide).length,topSize:gw(t.topSide).length,bottomSize:gw(t.bottomSide).length};const{leftSize:e=0,rightSize:n=0,topSize:o=0,bottomSize:i=0}=t;return{leftSize:e,rightSize:n,topSize:o,bottomSize:i}},G0e=.4,ADt=.1,cDt=.1,r6o=t=>typeof t=="string"?t:t?.[0]??"",s6o=t=>Array.from(r6o(t)).length*ADt;function lDt(t){const e=t;return e.leftSide!==void 0||e.rightSide!==void 0||e.topSide!==void 0||e.bottomSide!==void 0}var sPe=t=>{const e=t.portDistanceFromEdge??.4;let n=t.schPortArrangement?i6o(t.schPortArrangement):null;const o={left:0,right:0,top:0,bottom:0};let i=t.pinCount??null;if(i===null)if(n)i=n.leftSize+n.rightSize+n.topSize;else throw new Error("Could not determine pin count for the schematic box");if(i&&!n){const d=Math.floor(i/2);n={leftSize:i-d,rightSize:d,topSize:0,bottomSize:0}}n||(n={leftSize:0,rightSize:0,topSize:0,bottomSize:0});const r=({side:d,sideIndex:p,truePinIndex:m})=>{if(!t.schPortArrangement||!lDt(t.schPortArrangement))return m+1;const _={left:"top-to-bottom",bottom:"left-to-right",right:"bottom-to-top",top:"right-to-left"}[d],f=t.schPortArrangement?.[`${d}Side`]?.direction??_,I=t.schPortArrangement?.[`${d}Side`]?.pins;let C=p;return f!==_&&(C=I.length-p-1),hO(I[C],t.pinLabels)},s=[];let a=0,A=0;for(let d=0;d<n.leftSize;d++){const p=r({side:"left",sideIndex:d,truePinIndex:A}),m=t.numericSchPinStyle?.[`pin${p}`]??t.numericSchPinStyle?.[p];m?.topMargin&&(a+=m.topMargin),s.push({trueIndex:p-1,pinNumber:p,side:"left",distanceFromOrthogonalEdge:a}),m?.bottomMargin&&(a+=m.bottomMargin),d===n.leftSize-1?o.left=a:a+=t.schPinSpacing,A++}a=0;for(let d=0;d<n.bottomSize;d++){const p=r({side:"bottom",sideIndex:d,truePinIndex:A}),m=t.numericSchPinStyle?.[`pin${p}`]??t.numericSchPinStyle?.[p];m?.leftMargin&&(a+=m.leftMargin),s.push({trueIndex:p-1,pinNumber:p,side:"bottom",distanceFromOrthogonalEdge:a}),m?.rightMargin&&(a+=m.rightMargin),d===n.bottomSize-1?o.bottom=a:a+=t.schPinSpacing,A++}a=0;for(let d=0;d<n.rightSize;d++){const p=r({side:"right",sideIndex:d,truePinIndex:A}),m=t.numericSchPinStyle?.[`pin${p}`]??t.numericSchPinStyle?.[p];m?.bottomMargin&&(a+=m.bottomMargin),s.push({trueIndex:p-1,pinNumber:p,side:"right",distanceFromOrthogonalEdge:a}),m?.topMargin&&(a+=m.topMargin),d===n.rightSize-1?o.right=a:a+=t.schPinSpacing,A++}a=0;for(let d=0;d<n.topSize;d++){const p=r({side:"top",sideIndex:d,truePinIndex:A}),m=t.numericSchPinStyle?.[`pin${p}`]??t.numericSchPinStyle?.[p];m?.rightMargin&&(a+=m.rightMargin),s.push({trueIndex:p-1,pinNumber:p,side:"top",distanceFromOrthogonalEdge:a}),m?.leftMargin&&(a+=m.leftMargin),d===n.topSize-1?o.top=a:a+=t.schPinSpacing,A++}let c=t.schWidth;if(c===void 0){c=Math.max(o.top+G0e,o.bottom+G0e),t.pinLabels&&s.filter(I=>I.side==="left"||I.side==="right").some(I=>t.pinLabels?.[`pin${I.pinNumber}`]||t.pinLabels?.[I.pinNumber])&&(c=Math.max(c,.5));const d=t.pinLabels?Math.max(...Object.values(t.pinLabels).map(_=>_.length*ADt)):0,p=d>0?1.1:0;c=Math.max(c,d+p);const m={left:0,right:0};for(const _ of s){if(_.side!=="left"&&_.side!=="right")continue;const f=t.pinLabels?.[`pin${_.pinNumber}`]??t.pinLabels?.[_.pinNumber];m[_.side]=Math.max(m[_.side],s6o(f))}c=Math.max(c,m.left+m.right+2*cDt)}let l=t.schHeight;if(l||(l=Math.max(o.left+G0e,o.right+G0e)),t.pinLabels){const p=cDt,m=.075,_=w=>{const M=t.pinLabels[`pin${w}`]??t.pinLabels[`${w}`];return M?M.length*.13:0},f=s.filter(w=>w.side==="left").map(w=>({y:o.left/2-w.distanceFromOrthogonalEdge,len:_(w.pinNumber)})).filter(w=>w.len>0),I=s.filter(w=>w.side==="right").map(w=>({y:-o.right/2+w.distanceFromOrthogonalEdge,len:_(w.pinNumber)})).filter(w=>w.len>0),C=s.filter(w=>w.side==="top").map(w=>({x:o.top/2-w.distanceFromOrthogonalEdge,len:_(w.pinNumber)})).filter(w=>w.len>0),y=s.filter(w=>w.side==="bottom").map(w=>({x:-o.bottom/2+w.distanceFromOrthogonalEdge,len:_(w.pinNumber)})).filter(w=>w.len>0),x=(w,M)=>Math.min(w.maxX,M.maxX)>Math.max(w.minX,M.minX)&&Math.min(w.maxY,M.maxY)>Math.max(w.minY,M.minY),E=(w,M)=>({minX:-M/2+p,maxX:-M/2+p+w.len,minY:w.y-m,maxY:w.y+m}),B=(w,M)=>({minX:M/2-p-w.len,maxX:M/2-p,minY:w.y-m,maxY:w.y+m}),S=(w,M)=>({minX:w.x-m,maxX:w.x+m,minY:M/2-p-w.len,maxY:M/2-p}),Q=(w,M)=>({minX:w.x-m,maxX:w.x+m,minY:-M/2+p,maxY:-M/2+p+w.len});if(!t.schHeight){let w=!1;for(const M of C)for(const k of y)x(S(M,l),Q(k,l))&&(w=!0,l=Math.max(l,M.len+k.len+2*p));if(w){for(const M of C){const k=S(M,l);for(const R of f){const F=E(R,c);x(k,F)&&(l=Math.max(l,2*(F.maxY+p+M.len)))}for(const R of I){const F=B(R,c);x(k,F)&&(l=Math.max(l,2*(F.maxY+p+M.len)))}}for(const M of y){const k=Q(M,l);for(const R of f){const F=E(R,c);x(k,F)&&(l=Math.max(l,2*(p+M.len-F.minY)))}for(const R of I){const F=B(R,c);x(k,F)&&(l=Math.max(l,2*(p+M.len-F.minY)))}}}}}const u={left:{x:-c/2-e,y:o.left/2},bottom:{x:-o.bottom/2,y:-l/2-e},right:{x:c/2+e,y:-o.right/2},top:{x:o.top/2,y:l/2+e}},g={left:{x:0,y:-1},right:{x:0,y:1},top:{x:-1,y:0},bottom:{x:1,y:0}},h=s.map(d=>{const{distanceFromOrthogonalEdge:p,side:m}=d,_=u[m],f=g[m];return{x:_.x+p*f.x,y:_.y+p*f.y,...d}});return{getPortPositionByPinNumber(d){const p=h.find(m=>m.pinNumber.toString()===d.toString());return p||null},getSize(){return{width:c,height:l}},getSizeIncludingPins(){return{width:c+(n.leftSize||n.rightSize?.4:0),height:l+(n.topSize||n.bottomSize?.4:0)}},pinCount:i}},Kj=(t,e)=>{if(!t)return;const n={};for(const[o,i]of Object.entries(t)){const r=hO(o,e),s=i.marginLeft??i.leftMargin,a=i.marginRight??i.rightMargin,A=i.marginTop??i.topMargin,c=i.marginBottom??i.bottomMargin,u={...n[`pin${r}`]??{}};s!==void 0&&(u.leftMargin=lt.parse(s)),a!==void 0&&(u.rightMargin=lt.parse(a)),A!==void 0&&(u.topMargin=lt.parse(A)),c!==void 0&&(u.bottomMargin=lt.parse(c)),n[`pin${r}`]=u}return n},a6o=t=>t==="schematic_symbol"||t==="schematic_component"||t==="schematic_line"||t==="schematic_rect"||t==="schematic_circle"||t==="schematic_arc"||t==="schematic_text"||t==="schematic_path",aPe=t=>Array.isArray(t)&&t.length>0&&t.some(e=>a6o(e.type)),APe=t=>typeof t?.x=="number"&&Number.isFinite(t.x)&&typeof t.y=="number"&&Number.isFinite(t.y),cPe=(t,e)=>({x:t.x-e.x,y:t.y-e.y}),A6o=t=>t.type==="schematic_component"||t.type==="schematic_port"||t.type==="schematic_line"||t.type==="schematic_rect"||t.type==="schematic_circle"||t.type==="schematic_arc"||t.type==="schematic_text"||t.type==="schematic_path",c6o=t=>{const e=t.find(i=>i.type==="schematic_component"&&APe(i.center));if(e)return e.center;const n=t.filter(A6o);if(n.length===0)return null;const o=Gj(n);return!Number.isFinite(o.minX)||!Number.isFinite(o.maxX)||!Number.isFinite(o.minY)||!Number.isFinite(o.maxY)?null:{x:(o.minX+o.maxX)/2,y:(o.minY+o.maxY)/2}},l6o=(t,e)=>{switch(t.type){case"schematic_component":case"schematic_port":case"schematic_rect":case"schematic_circle":case"schematic_arc":return APe(t.center)?{...t,center:cPe(t.center,e)}:t;case"schematic_line":return{...t,x1:t.x1-e.x,y1:t.y1-e.y,x2:t.x2-e.x,y2:t.y2-e.y};case"schematic_text":return APe(t.position)?{...t,position:cPe(t.position,e)}:t;case"schematic_path":return{...t,points:t.points.map(n=>cPe(n,e))};default:return t}},u6o=t=>{const e=c6o(t);return e?e.x===0&&e.y===0?[...t]:t.map(n=>l6o(n,e)):[...t]},uDt=t=>t.type==="schematic_line"||t.type==="schematic_rect"||t.type==="schematic_circle"||t.type==="schematic_arc"||t.type==="schematic_text"||t.type==="schematic_path",gDt=(t,e)=>{if(!(e in t))return;const n=t[e];return typeof n=="string"?n:void 0},g6o=t=>{const e=t.filter(g=>g.type==="schematic_symbol"),n=t.filter(g=>g.type==="schematic_component"),o=n.find(g=>typeof g.schematic_symbol_id=="string")?.schematic_symbol_id??e[0]?.schematic_symbol_id,i=(o?n.find(g=>g.schematic_symbol_id===o):void 0)??n[0],r=i?.schematic_component_id,s=typeof i?.source_component_id=="string"?i.source_component_id:void 0,a=(o?e.find(g=>g.schematic_symbol_id===o):void 0)??e[0],A=new Set,c=new Set,l=[],u=g=>{!g||c.has(g)||(c.add(g),l.push(g))};u(a),u(i);for(const g of t)g.type==="schematic_port"&&(!r||g.schematic_component_id!==r||(u(g),typeof g.source_port_id=="string"&&A.add(g.source_port_id)));for(const g of t){if(!uDt(g))continue;const h=gDt(g,"schematic_symbol_id"),d=gDt(g,"schematic_component_id");(o&&h===o||r&&d===r||!o&&!r)&&u(g)}for(const g of t)g.type==="source_port"&&(A.has(g.source_port_id)||s&&g.source_component_id===s)&&u(g);return l.length>0?l:t.filter(g=>g.type==="schematic_symbol"||g.type==="schematic_component"||g.type==="schematic_port"||uDt(g))},d6o=class extends Ir{isPrimitiveContainer=!0;get config(){return{componentName:"CadAssembly",zodProps:TMn}}},dDt=t=>{if(!t)return null;const e=t.match(/#ext=(\w+)$/);if(e)return e[1].toLowerCase();const o=t.split("?")[0].split("#")[0],i=o.split("/").pop()??o;return i.includes(".")?i.split(".").pop()?.toLowerCase()??null:null},h6o=(t,e)=>{const n=t.replace(/\/+$/,""),o=e.replace(/^\/+/,"");return`${n}/${o}`},hDt=(t,e)=>{if(!e||!t.startsWith("/"))return t;try{const n=new URL(e);return n.pathname!=="/"&&t.startsWith(n.pathname)?new URL(t,n.origin).toString():h6o(e,t)}catch{return t}},lPe=xo([_t(),Z()]),pDt=Pt({x:lPe,y:lPe,z:lPe}),p6o=class extends Ir{get config(){return{componentName:"CadModel",zodProps:HMn}}doInitialCadModelRender(){const t=this._findParentWithPcbComponent();if(!t||!t.pcb_component_id)return;const{db:e}=this.root,{boardThickness:n=0}=t._getBoard()??{},o=t._getPcbCircuitJsonBounds();e.pcb_component.get(t.pcb_component_id);const i=this._parsedProps;if(!i||typeof i.modelUrl!="string"&&typeof i.stepUrl!="string")return;const r=t._computePcbGlobalTransformBeforeLayout(),a=O9(r).rotation.angle*180/Math.PI,A=i.pcbRotationOffset??i.rotationOffset,c=pDt.parse({x:0,y:0,z:0});if(typeof A=="number")c.z=Number(A);else if(typeof A=="object"){const I=pDt.parse(A);c.x=Number(I.x),c.y=Number(I.y),c.z=Number(I.z)}const{pcbX:l,pcbY:u}=this.getResolvedPcbPositionProp(),g=L9.parse({x:l,y:u,z:i.pcbZ??0,...typeof i.positionOffset=="object"?i.positionOffset:{}}),h=i.zOffsetFromSurface!==void 0?lt.parse(i.zOffsetFromSurface):0,d=t.props.layer==="bottom"?"bottom":"top",p=i.modelUrl?dDt(i.modelUrl):void 0,m=i.modelUrl?.replace(/#ext=\w+$/,""),_={};if(p==="stl"?_.model_stl_url=this._addCachebustToModelUrl(m):p==="obj"?_.model_obj_url=this._addCachebustToModelUrl(m):p==="gltf"?_.model_gltf_url=this._addCachebustToModelUrl(m):p==="glb"?_.model_glb_url=this._addCachebustToModelUrl(m):p==="step"||p==="stp"?_.model_step_url=this._addCachebustToModelUrl(m):p==="wrl"||p==="vrml"?_.model_wrl_url=this._addCachebustToModelUrl(m):_.model_stl_url=this._addCachebustToModelUrl(m),i.stepUrl){const I=this._addCachebustToModelUrl(i.stepUrl);I&&(_.model_step_url=I)}const f=e.cad_component.insert({position:{x:o.center.x+Number(g.x),y:o.center.y+Number(g.y),z:(d==="bottom"?-n/2:n/2)+(d==="bottom"?-h:h)+Number(g.z)},rotation:{x:Number(c.x),y:(d==="top"?0:180)+Number(c.y),z:k9(d==="bottom"?-(a+Number(c.z)):a+Number(c.z))},pcb_component_id:t.pcb_component_id,model_board_normal_direction:i.modelBoardNormalDirection,model_origin_alignment:"center_of_component_on_board_surface",anchor_alignment:"center_of_component_on_board_surface",model_origin_position:i.modelOriginPosition,size:i.size?L9.parse(i.size):void 0,source_component_id:t.source_component_id,model_unit_to_mm_scale_factor:typeof i.modelUnitToMmScale=="number"?i.modelUnitToMmScale:void 0,show_as_translucent_model:i.showAsTranslucentModel??t._parsedProps.showAsTranslucentModel,..._});this.cad_component_id=f.cad_component_id}_findParentWithPcbComponent(){let t=this.parent;for(;t&&!t.pcb_component_id;)t=t.parent;return t}_addCachebustToModelUrl(t){if(!t)return t;const e=this.root?.platform?.projectBaseUrl,n=hDt(t,e);if(!n.includes("modelcdn.tscircuit.com"))return n;const o=this.root?.getClientOrigin()??"";return`${n}${n.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(o)}`}},m6o=vc("tscircuit:core:footprint"),Y0e=class extends Ir{get config(){return{componentName:"Footprint",zodProps:MPn}}doInitialPcbFootprintLayout(){if(this.root?.pcbDisabled)return;const t=this.children.filter(u=>u.componentName==="Constraint");if(t.length===0)return;const{isFlipped:e}=this._getPcbPrimitiveFlippedHelpers(),n=u=>e&&"left"in u&&"right"in u?{...u,left:u.right,right:u.left}:u,o=t.flatMap(u=>u._getAllReferencedComponents().componentsWithSelectors).map(({component:u,selector:g,componentSelector:h,edge:d})=>({component:u,selector:g,componentSelector:h,edge:d,bounds:u._getPcbCircuitJsonBounds()}));if(o.some(u=>u.edge))throw new Error("edge constraints not implemented yet for footprint layout, contributions welcome!");function i(u){return o.find(({selector:g})=>g===u)}const r=new qpt,s={};function a(u){return u in s||(s[u]=new gse(u),r.addEditVariable(s[u],wg.weak)),s[u]}for(const{selector:u,bounds:g}of o){const h=a(`${u}_x`),d=a(`${u}_y`);r.suggestValue(h,g.center.x),r.suggestValue(d,g.center.y)}for(const u of t){const g=u._parsedProps;if("xDist"in g){const{xDist:h,left:d,right:p,edgeToEdge:m,centerToCenter:_}=n(g),f=a(`${d}_x`),I=a(`${p}_x`),C=i(d)?.bounds,y=i(p)?.bounds;if(_){const x=new Gh(I,[-1,f]);r.addConstraint(new ux(x,V_.Eq,g.xDist,wg.required))}else if(m){const x=new Gh(I,-y.width/2,[-1,f],-C.width/2);r.addConstraint(new ux(x,V_.Eq,g.xDist,wg.required))}}else if("yDist"in g){const{yDist:h,top:d,bottom:p,edgeToEdge:m,centerToCenter:_}=g,f=a(`${d}_y`),I=a(`${p}_y`),C=i(d)?.bounds,y=i(p)?.bounds;if(_){const x=new Gh(f,[-1,I]);r.addConstraint(new ux(x,V_.Eq,g.yDist,wg.required))}else if(m){const x=new Gh(f,C.height/2,[-1,I],-y.height/2);r.addConstraint(new ux(x,V_.Eq,g.yDist,wg.required))}}else if("sameY"in g){const{for:h}=g;if(h.length<2)continue;const d=h.map(m=>a(`${m}_y`)),p=new Gh(...d.slice(1));r.addConstraint(new ux(p,V_.Eq,d[0],wg.required))}else if("sameX"in g){const{for:h}=g;if(h.length<2)continue;const d=h.map(m=>a(`${m}_x`)),p=new Gh(...d.slice(1));r.addConstraint(new ux(p,V_.Eq,d[0],wg.required))}}r.updateVariables(),m6o.enabled&&(console.log("Solution to layout constraints:"),console.table(Object.entries(s).map(([u,g])=>({var:u,val:g.value()}))));const A={left:1/0,right:-1/0,top:-1/0,bottom:1/0};for(const{selector:u,bounds:{width:g,height:h}}of o){const d=a(`${u}_x`),p=a(`${u}_y`),m=d.value()-g/2,_=d.value()+g/2,f=p.value()+h/2,I=p.value()-h/2;A.left=Math.min(A.left,m),A.right=Math.max(A.right,_),A.top=Math.max(A.top,f),A.bottom=Math.min(A.bottom,I)}const c={x:-(A.right+A.left)/2,y:-(A.top+A.bottom)/2},l=this.getPrimitiveContainer()._getGlobalPcbPositionBeforeLayout();c.x+=l.x,c.y+=l.y;for(const{component:u,selector:g}of o){const h=a(`${g}_x`),d=a(`${g}_y`);u._setPositionFromLayout({x:h.value()+c.x,y:d.value()+c.y})}}},_6o=t=>{const{db:e}=t.root;if(t.pcb_component_id){const n=e.pcb_component.get(t.pcb_component_id);return n?{width:n.width,height:n.height}:null}if(t.pcb_group_id){const n=e.pcb_group.get(t.pcb_group_id);if(!n)return null;if(n.outline&&n.outline.length>0){const o=Oh(n.outline);return o?{width:o.maxX-o.minX,height:o.maxY-o.minY}:null}return{width:n.width??0,height:n.height??0}}return null},f6o=(t,e)=>{const{db:n}=t.root,o=n.toArray();if(t.pcb_component_id){smt(o,t.pcb_component_id,e);return}if(t.source_group_id){Amt(o,t.source_group_id,e);return}throw new Error(`Cannot reposition component ${t.getString()}: no pcb_component_id or source_group_id`)},I6o="MARKED INTERNALLY CONNECTED",C6o=.12,y6o=.05,mDt=.12,x6o=t=>{const{db:e}=t.root,n={pcb_component_id:t.pcb_component_id};return e.pcb_fabrication_note_text.list(n).length>0||e.pcb_fabrication_note_path.list(n).length>0||e.pcb_fabrication_note_rect.list(n).length>0||e.pcb_fabrication_note_dimension.list(n).length>0},E6o=t=>{let e={from:t[0],to:t[1],length:-1/0};for(let s=1;s<t.length;s++){const a=t[s-1],A=t[s],c=Math.hypot(A.x-a.x,A.y-a.y);c>e.length&&(e={from:a,to:A,length:c})}const n=e.to.x-e.from.x,o=e.to.y-e.from.y,i=Math.max(e.length,Number.EPSILON);let r=Math.atan2(o,n)*180/Math.PI;return r>90&&(r-=180),r<-90&&(r+=180),{anchorPosition:{x:(e.from.x+e.to.x)/2-o/i*mDt,y:(e.from.y+e.to.y)/2+n/i*mDt},ccwRotation:(r%360+360)%360}},B6o=t=>{const e=t.root;if(!e||e.pcbDisabled||!t.pcb_component_id||t.componentName==="SolderJumper"||x6o(t))return;const{db:n}=e,o=n.pcb_component.get(t.pcb_component_id);if(!o)return;const i=o.layer;if(i!=="top"&&i!=="bottom")return;const r=t.getSubcircuit()?.subcircuit_id??void 0,s=t.getGroup()?.pcb_group_id??void 0;for(const a of t._getInternallyConnectedPins()){const A=a.flatMap(g=>{if(!g?.pcb_port_id)return[];const h=n.pcb_port.get(g.pcb_port_id);return h?[{x:h.x,y:h.y}]:[]}),c=A.filter((g,h)=>A.findIndex(d=>d.x===g.x&&d.y===g.y)===h);if(c.length<2)continue;const{anchorPosition:l,ccwRotation:u}=E6o(c);n.pcb_fabrication_note_path.insert({pcb_component_id:t.pcb_component_id,subcircuit_id:r,layer:i,route:c,stroke_width:y6o}),n.pcb_fabrication_note_text.insert({pcb_component_id:t.pcb_component_id,pcb_group_id:s,subcircuit_id:r,font:"tscircuit2024",font_size:C6o,text:I6o,ccw_rotation:u,layer:i,anchor_position:l,anchor_alignment:"center"})}},b6o={simple_ammeter:["A"],simple_battery:["B","BT"],simple_capacitor:["C"],simple_chip:["U","IC"],simple_connector:["J","P","CONN"],simple_crystal:["Y","X"],simple_current_source:["I","IS"],simple_diode:["D"],simple_fuse:["F"],simple_inductor:["L","FB"],simple_interconnect:["ICN"],simple_led:["D","LED"],simple_mosfet:["Q"],simple_op_amp:["U","IC"],simple_pin_header:["J","P","JP"],simple_pinout:["J","P"],simple_potentiometer:["RV","RP"],simple_power_source:["B","BT","V","VS"],simple_push_button:["SW","S"],simple_resistor:["R"],simple_resonator:["Y","X"],simple_switch:["SW","S"],simple_test_point:["TP"],simple_transistor:["Q"],simple_voltage_probe:["VP"],simple_voltage_source:["V","VS"]},_Dt=t=>{if(t)return b6o[t]},S6o=t=>t.match(/^[A-Za-z]+/)?.[0]?.toUpperCase(),Q6o=[{prefix:"J",recommendation:"a <connector /> or <jumper />"},{prefix:"Q",recommendation:"a <transistor />"},{prefix:"C",recommendation:"a <capacitor />"},{prefix:"R",recommendation:"a <resistor />"},{prefix:"L",recommendation:"an <inductor />"},{prefix:"Y",recommendation:"a <crystal />"},{prefix:"X",recommendation:"a <crystal />"},{prefix:"F",recommendation:"a <fuse />"},{prefix:"S",recommendation:"a <switch /> or <pushbutton />"},{prefix:"TP",recommendation:"a <testpoint />"}],v6o=t=>{const{db:e}=t.root;if(!t.source_component_id)return;const n=e.source_component.get(t.source_component_id);if(!n?.name||!n.ftype)return;const o=S6o(n.name),i=t.componentName==="Chip"&&n.ftype==="simple_chip"&&o!==void 0?Q6o.find(({prefix:A})=>o.startsWith(A)):void 0,r=t.getRefDesPrefixes()??(i?_Dt("simple_chip"):void 0);if(!r||r.length===0||o&&r.includes(o))return;const s=r.length===1?r[0]:`one of ${r.join(", ")}`,a=i?`The "${i.prefix}" prefix is being used with a <chip />, try using it with ${i.recommendation}`:`Component ${n.name} has ftype="${n.ftype}" but reference designator should start with ${s}`;e.insert({type:"source_refdes_convention_warning",warning_type:"source_refdes_convention_warning",message:a,source_component_id:n.source_component_id,refdes:n.name,source_component_ftype:n.ftype,expected_prefixes:r,actual_prefix:o,subcircuit_id:n.subcircuit_id})},fDt=new WeakMap,w6o=t=>{const e=fDt.get(t);if(e)return e;const n=new Map;return fDt.set(t,n),n},P6o=new Set(["a","anode","pos","positive","+"]),M6o=new Set(["c","k","cathode","neg","negative","-"]),IDt=t=>t.toLowerCase().replace(/[^a-z0-9+-]/g,""),CDt=(t,e)=>{const n=t.filter(o=>o.type==="source_port"&&(!e||o.source_component_id===e));return n.find(o=>o.pin_number===1)??n.find(o=>[o.name,...o.port_hints??[]].map(IDt).includes("pin1"))??null},yDt=t=>{if(!t)return null;const e=[t.name,...t.port_hints??[]].map(IDt),n=e.some(i=>P6o.has(i)),o=e.some(i=>M6o.has(i));return n===o?null:n?"anode":"cathode"},D6o=t=>{if(!t)return[];const e=[];for(const n of Object.keys(t)){const o=t[n]?.[0];o&&e.push({supplierName:n,supplierPartNumber:o})}return e},N6o=t=>{if(typeof t!="string")return null;const e=t.match(/(?:^|_)pin1location\((leftside|rightside|topside|bottomside),(left|right|top|bottom)\)(?:_|$)/i);if(!e)return null;const n=pV.safeParse(`${e[1].toLowerCase()}_${e[2].toLowerCase()}`);return n.success?n.data:null},R6o=({component:t,pcbComponent:e,pcbElements:n})=>{const o=-e.rotation*Math.PI/180,i=Math.cos(o),r=Math.sin(o),s=b0e({componentLayer:e.layer,originalLayer:t._getFootprintOriginalLayer()}),a=A=>{const c=A.x-e.center.x,l=A.y-e.center.y,u=s?-l:l;return{x:c*i-u*r,y:c*r+u*i}};return n.map(A=>{const c=structuredClone(A);if(typeof c.x=="number"&&typeof c.y=="number"){const l=a(c);c.x=l.x,c.y=l.y}return c.points&&(c.points=c.points.map(a)),c})},T6o=({supplierName:t,supplierPartNumber:e})=>`part-orientation-analysis:v3:${t}:${e}`,k6o=async({cacheKey:t,component:e})=>{const n=await e.root?.platform?.localCacheEngine?.getItem(t);if(!n)return{cacheHit:!1};try{const o=JSON.parse(n),i=pV.safeParse(o.pin1_location),r=o.pin1_location===null?null:i.success?i.data:void 0,s=o.pin1_polarity===null||o.pin1_polarity==="anode"||o.pin1_polarity==="cathode"?o.pin1_polarity:void 0;return r===void 0||s===void 0?{cacheHit:!1}:{cacheHit:!0,analysis:{pin1Location:r,pin1Polarity:s}}}catch{return{cacheHit:!1}}},F6o=async({component:t,partsEngine:e,supplierPartCandidate:n})=>{const o=T6o(n),i=await k6o({cacheKey:o,component:t});if(i.cacheHit)return i.analysis;const r=w6o(e),s=r.get(o);if(s)return s;const a=(async()=>{const A=await Promise.resolve(e.fetchPartCircuitJson({supplierPartNumber:n.supplierPartNumber,platformFetch:t.root?.platform?.platformFetch}));if(!A?.length)return{pin1Location:null,pin1Polarity:null};const c=dmt(A),l=yDt(CDt(A));try{await t.root?.platform?.localCacheEngine?.setItem(o,JSON.stringify({pin1_location:c,pin1_polarity:l}))}catch{}return{pin1Location:c,pin1Polarity:l}})().finally(()=>{r.delete(o)});return r.set(o,a),a},L6o=t=>{if(!t.root?.platform?.enablePartOrientationAnalysis||t.root.pcbDisabled||t.props.doNotPlace||!t.pcb_component_id)return;const{db:e}=t.root,n=e.pcb_component.get(t.pcb_component_id);if(!n)return;const o=[...e.pcb_smtpad.list({pcb_component_id:t.pcb_component_id}),...e.pcb_plated_hole.list({pcb_component_id:t.pcb_component_id})],i=N6o(t.resolveFootprint())??dmt(R6o({component:t,pcbComponent:n,pcbElements:o}));if(i&&e.pcb_component.update(t.pcb_component_id,{pin1_location:i}),t.getInheritedProperty("bomDisabled")||t.getInheritedProperty("partsEngineDisabled"))return;const r=t.getInheritedProperty("partsEngine");if(!r?.fetchPartCircuitJson)return;const s=e.source_component.get(t.source_component_id),A=s?.ftype==="simple_diode"||s?.ftype==="simple_led"?CDt(e.source_port.list(),t.source_component_id??void 0):null,c=yDt(A),l=D6o(s?.supplier_part_numbers);l.length!==0&&(t._hasStartedPartOrientationAnalysis||(t._hasStartedPartOrientationAnalysis=!0,t._queueAsyncEffect("analyze-part-orientation",async()=>{const u={};for(const g of l)try{const{pin1Location:h,pin1Polarity:d}=await F6o({component:t,partsEngine:r,supplierPartCandidate:g});if(h&&(u[g.supplierName]=h),c&&d&&c!==d){const p=dV.parse({type:"source_component_misconfigured_error",error_type:"source_component_misconfigured_error",message:`${t.getString()} maps pin 1 to the ${c}, but supplier part ${g.supplierName}:${g.supplierPartNumber} maps pin 1 to the ${d}. Update pinLabels or use a supplier part with matching diode polarity.`,source_component_ids:[t.source_component_id],source_port_ids:A?.source_port_id?[A.source_port_id]:void 0});t.root.db.source_component_misconfigured_error.insert(p)}}catch{}t._asyncSupplierPin1LocationMap=u,t._markDirty("PartOrientationAnalysis")})))},H6o=t=>{const e=t._asyncSupplierPin1LocationMap;if(!e||!t.pcb_component_id)return;const{db:n}=t.root,o=n.pcb_component.get(t.pcb_component_id);!o||Object.keys(e).length===0||n.pcb_component.update(t.pcb_component_id,{supplier_pin1_location_map:{...o.supplier_pin1_location_map,...e}})};function O6o(t){if(t.root?.pcbDisabled||!t.pcb_component_id)return;const{pcbX:e,pcbY:n}=t._parsedProps,o=t.props?.pcbPositionAnchor;if(!o||e===void 0&&n===void 0)return;const i=L0e(t.children);if(i.width===0||i.height===0)return;const s={...{x:(i.minX+i.maxX)/2,y:(i.minY+i.maxY)/2}};let a=null;if(new Set(["center","top_left","top_center","top_right","center_left","center_right","bottom_left","bottom_center","bottom_right"]).has(o)){const l={left:i.minX,right:i.maxX,top:i.minY,bottom:i.maxY};switch(o){case"center":a=s;break;case"top_left":a={x:l.left,y:l.top};break;case"top_center":a={x:s.x,y:l.top};break;case"top_right":a={x:l.right,y:l.top};break;case"center_left":a={x:l.left,y:s.y};break;case"center_right":a={x:l.right,y:s.y};break;case"bottom_left":a={x:l.left,y:l.bottom};break;case"bottom_center":a={x:s.x,y:l.bottom};break;case"bottom_right":a={x:l.right,y:l.bottom};break}}else try{const l=t.portMap[o];l&&(a=l._getGlobalPcbPositionBeforeLayout())}catch{}if(!a)return;const c={...s};e!==void 0&&(c.x+=e-a.x),n!==void 0&&(c.y+=n-a.y),(Math.abs(c.x-s.x)>1e-6||Math.abs(c.y-s.y)>1e-6)&&t._repositionOnPcb(c)}var xDt=t=>{const e=t.find(i=>i.type==="cad_component");if(!e)return;const n={stlUrl:e.model_stl_url,objUrl:e.model_obj_url,gltfUrl:e.model_gltf_url,glbUrl:e.model_glb_url,stepUrl:e.model_step_url,wrlUrl:e.model_wrl_url,modelOriginPosition:e.model_origin_position??void 0,modelUnitToMmScale:e.model_unit_to_mm_scale_factor,modelBoardNormalDirection:e.model_board_normal_direction,size:e.size??void 0,rotationOffset:e.rotation??void 0,positionOffset:e.position??void 0,showAsTranslucentModel:e.show_as_translucent_model};if(!n.stlUrl&&!n.objUrl&&!n.gltfUrl&&!n.glbUrl&&!n.stepUrl&&!n.wrlUrl&&!e.model_jscad)return;e.model_jscad&&typeof e.model_jscad=="object"&&(n.jscad=e.model_jscad);const o=kxe.safeParse(n);return o.success?o.data:void 0},G6o=vc("tscircuit:core:resolveStaticFileImport");async function EDt(t,e){if(!t)return t;const n=t.startsWith("./")?t.slice(1):t,o=e?.resolveProjectStaticFileImportUrl;if(o&&(t.startsWith("/")||t.startsWith("./")))try{const i=await o(n);if(i)return i}catch(i){G6o("failed to resolve static file via platform resolver",i)}return hDt(n,e?.projectBaseUrl)}var dw=t=>t.startsWith("blob:"),hw=t=>t.startsWith("http://")||t.startsWith("https://"),Vj=t=>t.startsWith("/")||t.startsWith("./"),fO=t=>{if(hw(t)||dw(t))return null;const e=t.indexOf(":");if(e<=0)return null;const n=t.slice(0,e),o=t.slice(e+1);return!n||!o?null:{footprintLib:n,footprintName:o}},Y6o=Gxe.shape.supplierPartNumbers.unwrap().keySchema.options,U6o=t=>t.componentName==="Symbol"||t.isSchematicPrimitive,K6o=(t,e,n)=>{if(t.getInheritedProperty("partsEngineDisabled"))return;const o=t.props.supplierPartNumbers,i=Y6o.find(A=>A===e);if(!i||!o?.[i]?.includes(n))return;const a=t.getInheritedProperty("partsEngine")?.fetchPartCircuitJson;if(a)return async A=>({footprintCircuitJson:await a({supplierPartNumber:A,platformFetch:t.root?.platform?.platformFetch})??[]})},V6o=async(t,e,n)=>{if(!t)throw new Error(`No footprint resolver is configured for library "${e}".`);return t(n)};function z6o(t,e){const n=t.resolveFootprint();if(!n)return;const{pcbRotation:o,pcbPinLabels:i}=t.props,r=t._resolvePinLabels(),s=dDt(String(n)),a=s?t.root?.platform?.footprintFileParserMap?.[s]:null;if(typeof n=="string"&&(hw(n)||dw(n)||Vj(n))&&a){if(t._hasStartedFootprintUrlLoad)return;t._hasStartedFootprintUrlLoad=!0,e("load-footprint-from-platform-file-parser",async()=>{const A=hw(n)||dw(n)?n:await EDt(n,t.root?.platform);try{const c=await a.loadFromUrl(A),l=Db({componentName:t.name,componentRotation:o,footprinterString:A,pinLabels:r,pcbPinLabels:i},c.footprintCircuitJson);t.addAll(l);for(const u of t.children)u.componentName==="Port"&&u._markDirty("PcbPortRender");t._markDirty("ResolveFootprintPinLabels"),t._markDirty("InitializePortsFromChildren")}catch(c){const l=t.root?.db;if(l&&t.source_component_id&&t.pcb_component_id){const u=t.getSubcircuit(),g=`${t.getString()} failed to load footprint "${A}": `+(c instanceof Error?c.message:String(c)),h=mV.parse({type:"external_footprint_load_error",message:g,pcb_component_id:t.pcb_component_id,source_component_id:t.source_component_id,subcircuit_id:u.subcircuit_id??void 0,pcb_group_id:t.getGroup()?.pcb_group_id??void 0,footprinter_string:A});l.external_footprint_load_error.insert(h)}throw c}});return}if(typeof n=="string"&&hw(n)){if(t._hasStartedFootprintUrlLoad)return;t._hasStartedFootprintUrlLoad=!0;const A=n;e("load-footprint-url",async()=>{try{const c=await fetch(A);if(!c.ok)throw new Error(`Failed to fetch footprint: ${c.status}`);const l=await c.json(),u=Db({componentName:t.name,componentRotation:o,footprinterString:A,pinLabels:r,pcbPinLabels:i},l);t.addAll(u),t._markDirty("ResolveFootprintPinLabels"),t._markDirty("InitializePortsFromChildren")}catch(c){const l=t.root?.db;if(l&&t.source_component_id&&t.pcb_component_id){const u=t.getSubcircuit(),g=`${t.getString()} failed to load external footprint "${A}": `+(c instanceof Error?c.message:String(c)),h=mV.parse({type:"external_footprint_load_error",message:g,pcb_component_id:t.pcb_component_id,source_component_id:t.source_component_id,subcircuit_id:u.subcircuit_id??void 0,pcb_group_id:t.getGroup()?.pcb_group_id??void 0,footprinter_string:A});l.external_footprint_load_error.insert(h)}throw c}});return}if(!(typeof n=="string"&&dw(n))){if(typeof n=="string"){const A=fO(n);if(!A||t._hasStartedFootprintUrlLoad)return;t._hasStartedFootprintUrlLoad=!0;const l=t.root?.platform?.footprintLibraryMap?.[A.footprintLib],u=typeof l=="function"?l:void 0,g=K6o(t,A.footprintLib,A.footprintName),h=u??g;e("load-lib-footprint",async()=>{try{const d=await V6o(h,A.footprintLib,A.footprintName);let p=null;if(Array.isArray(d)?p=d:Array.isArray(d.footprintCircuitJson)&&(p=d.footprintCircuitJson),!p||p.length===0)throw new Error(`Footprint resolver returned no circuit elements for "${n}".`);const m=Db({componentName:t.name,componentRotation:o,footprinterString:n,pinLabels:r,pcbPinLabels:i},p),_=new Y0e({src:n}),f=[];for(const I of m)U6o(I)?f.push(I):_.add(I);t.add(_),t.addAll(f),t._asyncFootprintCadModel=!Array.isArray(d)&&d.cadModel||xDt(p);for(const I of t.children)I.componentName==="Port"&&I._markDirty?.("PcbPortRender");t._markDirty("ResolveFootprintPinLabels"),t._markDirty("InitializePortsFromChildren")}catch(d){const p=t.root?.db;if(p&&t.source_component_id&&t.pcb_component_id){const m=t.getSubcircuit(),_=`${t.getString()} failed to load external footprint "${n}": `+(d instanceof Error?d.message:String(d)),f=mV.parse({type:"external_footprint_load_error",message:_,pcb_component_id:t.pcb_component_id,source_component_id:t.source_component_id,subcircuit_id:m.subcircuit_id??void 0,pcb_group_id:t.getGroup()?.pcb_group_id??void 0,footprinter_string:n});p.external_footprint_load_error.insert(f)}throw d}});return}if(!ee.isValidElement(n)&&n.componentName==="Footprint"&&t.add(n),Array.isArray(n)&&!ee.isValidElement(n)&&n.length>0){try{const A=Db({componentName:t.name,componentRotation:o,footprinterString:"",pinLabels:r,pcbPinLabels:i},n);t.addAll(A)}catch(A){const c=t.root?.db;if(c&&t.source_component_id&&t.pcb_component_id){const l=t.getSubcircuit(),u=`${t.getString()} failed to load json footprint: `+(A instanceof Error?A.message:String(A)),g=exe.parse({type:"circuit_json_footprint_load_error",message:u,pcb_component_id:t.pcb_component_id,source_component_id:t.source_component_id,subcircuit_id:l.subcircuit_id??void 0,pcb_group_id:t.getGroup()?.pcb_group_id??void 0});c.circuit_json_footprint_load_error.insert(g)}throw A}return}}}function J6o(t){const e=t._impliedFootprintPinLabels??{},n={},o=t.getPortsFromFootprint({allowImplicitPinNumbers:!t._parsedProps.pinLabels});for(const r of o){const s=r._parsedProps.pinNumber;if(s===void 0)continue;const a=new Set([`pin${s}`,`${s}`]),A=r.getNameAndAliases().filter(c=>!a.has(c));A.length>0&&(n[`pin${s}`]=A)}const i={...n};for(const[r,s]of Object.entries(e))i[r]=Array.isArray(s)?s:[s];if(t._impliedFootprintPinLabels=i,Object.keys(t._impliedFootprintPinLabels).length!==0)for(const r of t.children){if(r.componentName!=="Port")continue;const s=r,a=s._parsedProps.pinNumber;if(a===void 0)continue;const A=`pin${a}`,c=t._impliedFootprintPinLabels[A];if(!c)continue;const l=Array.isArray(c)?c:[c],u=s.getNameAndAliases();for(const g of l)u.includes(g)||s.externallyAddedAliases.push(g)}}function W6o(t){if(t.root?.schematicDisabled||t.getCollapsedSchematicBoxAncestor()||t._parsedProps?.noSchematicRepresentation===!0)return;const{db:e}=t.root;if(t._invalidPinLabelMessages?.length&&t.root?.db)for(const a of t._invalidPinLabelMessages){let A="pinLabels";const c=a.match(/^Invalid pin label:\s*([^=]+)=\s*'([^']+)'/);c&&(A=`pinLabels['${c[2]}']`),t.root.db.source_property_ignored_warning.insert({source_component_id:t.source_component_id,property_name:A,message:a,error_type:"source_property_ignored_warning"})}t._parsedProps.schPinSpacing!==void 0&&t.root?.db&&t.root.db.source_property_ignored_warning.insert({source_component_id:t.source_component_id,property_name:"schPinSpacing",error_type:"source_property_ignored_warning",message:"schPinSpacing is deprecated and will be ignored. Pin spacing is always 0.2."});const{schematicSymbolName:n}=t.config,{_parsedProps:o}=t,i=t.children.some(a=>a.componentName==="Symbol");if(o.symbol&&ee.isValidElement(o.symbol)||i)t._doInitialSchematicComponentRenderWithReactSymbol(o.symbol);else if(n)t._doInitialSchematicComponentRenderWithSymbol();else{const a=t._getSchematicBoxDimensions();a&&t._doInitialSchematicComponentRenderWithSchematicBoxDimensions(a)}const r=t.getSubcircuit()?._getSchematicManualPlacementForComponent(t);if(t.schematic_component_id&&(t.props.schX!==void 0||t.props.schY!==void 0)&&r){if(!t.schematic_component_id)return;const a=F2e.parse({type:"schematic_manual_edit_conflict_warning",schematic_manual_edit_conflict_warning_id:`schematic_manual_edit_conflict_${t.source_component_id}`,message:`${t.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:t.schematic_component_id,source_component_id:t.source_component_id,subcircuit_id:t.getSubcircuit()?.subcircuit_id});e.schematic_manual_edit_conflict_warning.insert(a)}const s=t._parsedProps?.schSheetName??t.props.schSheetName;s&&t.source_component_id&&!t._resolveSchematicSheetId()&&e.source_property_ignored_warning.insert({source_component_id:t.source_component_id,property_name:"schSheetName",error_type:"source_property_ignored_warning",subcircuit_id:t.getSubcircuit()?.subcircuit_id??void 0,message:`${t.getString()} references schSheetName "${s}", which does not match any schematic sheet and will be ignored.`})}function j6o(t){const e=t.font_size,n=t.text.length*e*.6,o=e,i=t.anchor_alignment||"center";let r=t.anchor_position.x,s=t.anchor_position.y;switch(i){case"top_left":r=t.anchor_position.x+n/2,s=t.anchor_position.y+o/2;break;case"top_center":r=t.anchor_position.x,s=t.anchor_position.y+o/2;break;case"top_right":r=t.anchor_position.x-n/2,s=t.anchor_position.y+o/2;break;case"center_left":r=t.anchor_position.x+n/2,s=t.anchor_position.y;break;case"center":r=t.anchor_position.x,s=t.anchor_position.y;break;case"center_right":r=t.anchor_position.x-n/2,s=t.anchor_position.y;break;case"bottom_left":r=t.anchor_position.x+n/2,s=t.anchor_position.y-o/2;break;case"bottom_center":r=t.anchor_position.x,s=t.anchor_position.y-o/2;break;case"bottom_right":r=t.anchor_position.x-n/2,s=t.anchor_position.y-o/2;break;default:r=t.anchor_position.x,s=t.anchor_position.y;break}return{x:r-n/2,y:s-o/2,width:n,height:o}}function $6o(t){if(!t._adjustSilkscreenTextAutomatically||t.root?.pcbDisabled||!t.pcb_component_id)return;const{db:e}=t.root,o=t._getPcbCircuitJsonBounds().center;let i=e.pcb_silkscreen_text.list({pcb_component_id:t.pcb_component_id}).filter(A=>A.text===t.name);if(i.length===0)return;const a=t.getSubcircuit().selectAll("[_isNormalComponent=true]").filter(A=>A!==t&&A.pcb_component_id).map(A=>{const c=A._getPcbCircuitJsonBounds(),l={center:c.center,width:c.width,height:c.height};return yV(l)});for(const A of i){const c=A.anchor_position,l=j6o(A),u={center:{x:l.x+l.width/2,y:l.y+l.height/2},width:l.width,height:l.height},g=yV(u);if(!a.some(I=>z4(g,I)))continue;const d=2*o.x-c.x,p=2*o.y-c.y,m={center:{x:d,y:p},width:l.width,height:l.height},_=yV(m);a.some(I=>z4(_,I))||e.pcb_silkscreen_text.update(A.pcb_silkscreen_text_id,{anchor_position:{x:d,y:p}})}}var q6o=t=>{const{db:e}=t.root;if(!t.source_component_id)return;const n=t.selectAll("port"),o=e.source_trace.list(),i=new Set;for(const s of o)for(const a of s.connected_source_port_ids)i.add(a);const r=t._getInternallyConnectedPins();for(const s of r)if(s.some(a=>a.source_port_id&&i.has(a.source_port_id)))for(const a of s)a.source_port_id&&i.add(a.source_port_id);for(const s of n)!s.source_port_id||!X6o(t,s)||e.source_port.get(s.source_port_id)?.do_not_connect||i.has(s.source_port_id)||e.source_pin_missing_trace_warning.insert({message:`Port ${s.getNameAndAliases()[0]} on ${t.props.name} is missing a trace`,source_component_id:t.source_component_id,source_port_id:s.source_port_id,subcircuit_id:t.getSubcircuit().subcircuit_id??void 0,warning_type:"source_pin_missing_trace_warning"})},X6o=(t,e)=>{if(t.config.componentName==="Interconnect")return!1;if(t.config.componentName==="Chip"){const n=t.props.pinAttributes;if(!n)return!1;for(const o of e.getNameAndAliases()){const i=n[o];if(i?.requiresPower||i?.requiresGround||i?.requiresVoltage!==void 0)return!0}return!1}return!0},Z6o=.8,e8o=Gxe.shape.supplierPartNumbers.unwrap().keySchema.options,t8o=t=>t.type==="pcb_smtpad"||t.type==="pcb_plated_hole",n8o=t=>Number.isFinite(t.minX)&&Number.isFinite(t.minY)&&Number.isFinite(t.maxX)&&Number.isFinite(t.maxY)&&t.maxX>t.minX&&t.maxY>t.minY,BDt=t=>{const e=t.filter(t8o);if(e.length===0)return null;const n=H8(e);return n8o(n)?n:null},bDt=t=>({width:t.maxX-t.minX,height:t.maxY-t.minY}),SDt=(t,e,n)=>{const o=bDt(t),i=bDt(e),r=n?.rotateB?i.height:i.width,s=n?.rotateB?i.width:i.height,a=Math.min(o.width,r),A=Math.min(o.height,s),c=a*A,l=o.width*o.height+r*s-c;return l<=0?0:c/l},o8o=(t,e)=>Math.max(SDt(t,e),SDt(t,e,{rotateB:!0})),i8o=t=>{if(!t)return[];const e=[];for(const n of e8o){const o=t[n];if(Array.isArray(o))for(const i of o)i&&e.push({supplierName:n,supplierPartNumber:i})}return e};function r8o(t){if(t.root?.pcbDisabled||t.props.doNotPlace||t.props.footprint===void 0||t.getInheritedProperty("bomDisabled")||t.getInheritedProperty("partsEngineDisabled"))return;const e=t.getInheritedProperty("partsEngine");if(!e?.fetchPartCircuitJson)return;const{db:n}=t.root,o=n.source_component.get(t.source_component_id);if(!o?.supplier_part_numbers||!t.pcb_component_id||t._hasStartedSupplierFootprintMismatchWarningCheck)return;const i=i8o(o.supplier_part_numbers);if(i.length===0)return;const r=[...n.pcb_smtpad.list({pcb_component_id:t.pcb_component_id}),...n.pcb_plated_hole.list({pcb_component_id:t.pcb_component_id})],s=BDt(r);s&&(t._hasStartedSupplierFootprintMismatchWarningCheck=!0,t._queueAsyncEffect("check-supplier-footprint-mismatch",async()=>{const{db:a}=t.root,A=e.fetchPartCircuitJson;for(const c of i){const{supplierName:l,supplierPartNumber:u}=c;try{const g=await Promise.resolve(A({supplierPartNumber:u}))??null;if(!g?.length)continue;const h=BDt(g);if(!h)continue;const d=o8o(s,h);if(d>=Z6o)return;const p=typeof t.props.footprint=="string"?`"${t.props.footprint}"`:"the provided footprint",m=Number(d.toFixed(4)),_=nxe.parse({type:"supplier_footprint_mismatch_warning",message:`${t.getString()} footprint ${p} does not match supplier footprint ${l}:${u} (copper IoU ${m}).`,source_component_id:t.source_component_id,pcb_component_id:t.pcb_component_id,pcb_group_id:t.getGroup()?.pcb_group_id??void 0,subcircuit_id:t.getSubcircuit()?.subcircuit_id??void 0,supplier_name:l,supplier_part_number:u,footprint_copper_intersection_over_union:m});a.supplier_footprint_mismatch_warning.insert(_);return}catch(g){const h=g instanceof Error?g.message:String(g),d=hV.parse({type:"source_part_not_found_warning",message:`Failed to fetch supplier footprint for ${t.getString()} (${l}:${u}): ${h}`,source_component_id:t.source_component_id??void 0,subcircuit_id:t.getSubcircuit()?.subcircuit_id??void 0,supplier_name:l,supplier_part_number:u});a.source_part_not_found_warning.insert(d);return}}}))}var QDt=(t,e)=>{const n=t._parsedProps.pinNumber,o=e._parsedProps.pinNumber;return n!==void 0&&o!==void 0&&n!==o?!1:t.isMatchingAnyOf(e.getNameAndAliases())},s8o=(t,e)=>{const n=t.toSorted(),o=e.toSorted();return n.length===o.length&&n.every((i,r)=>i===o[r])},a8o=t=>t.getNameAndAliases().find(e=>/^pin\d+$/.test(e))??null,A8o=(t,e)=>{if(!t._isPrimaryPort&&t.props.name||t.props.name&&(e.get(t.props.name)??0)<=1)return t.props.name;const n=a8o(t);return n||(t.props.name??null)};function vDt(t,e){const n=new Map;for(const o of t)for(const i of new Set(o.getNameAndAliases()))/^(pin)?\d+$/.test(i)||!o._isPrimaryPort&&i===o.props.name||(n.has(i)||n.set(i,[]),n.get(i).push(o));for(const o of n.values()){const i=Array.from(new Set(o));if(i.length<2)continue;const r=new Map;for(const A of i)A.props.name&&r.set(A.props.name,(r.get(A.props.name)??0)+1);const s=i.map(A=>A8o(A,r)).filter(A=>!!A),a=Array.from(new Set(s));a.length<2||e.some(A=>s8o(A,a))||e.push(a)}}function wDt(t,e){let n=1;const o=new Map;for(const r of t){const s=r.hints.filter(u=>u&&u.trim()!=="");if(s.length===0)continue;let a=s;if(!a.some(u=>u.startsWith("pin")||/^(?:pin)?\d+$/.test(u))){const u=a.map(g=>e?.implicitPinNumberByHint?.get(g)).find(g=>g!==void 0);if(u!==void 0)a=[...a,`pin${u}`];else{if(e?.allowImplicitPinNumbers===!1)continue;a=[...a,`pin${n}`]}}n++;const c=O0e(a,e);if(!c)continue;c.originDescription=r.originDescription;const l=c._parsedProps.pinNumber;l!==void 0&&(o.has(l)||o.set(l,[]),o.get(l).push({port:c,component:r.component}))}const i=[];for(const[r,s]of o){const a=(g,h)=>{const d=h.getNameAndAliases().filter(p=>!g.getNameAndAliases().includes(p));g.externallyAddedAliases.push(...d)},A=s[0].port,c=s.filter(g=>!!g.component);if(c.length!==s.length){for(const g of s.slice(1))a(A,g.port);i.push(A);continue}const l=p7o(c.map(g=>g.component));if(l.length<=1){for(const g of s.slice(1))a(A,g.port);i.push(A);continue}const u=[A.props.name];for(const[g,h]of l.entries()){const d=c.filter(m=>h.includes(m.component));if(g===0){for(const m of d.slice(1))a(A,m.port);i.push(A);continue}const p=new Pu({name:`pin${r}_internal_${g}`,aliases:A.getNameAndAliases()});p._isPrimaryPort=!1,p._primaryPinNumber=r,p.originDescription=`implicitInternalPhysicalPort:pin${r}:${g}`;for(const m of d)a(p,m.port);u.push(p.props.name),i.push(p)}e?.inferredInternallyConnectedPinNames?.push(u)}return e?.inferredInternallyConnectedPinNames&&vDt(i,e.inferredInternallyConnectedPinNames),i}var c8o=vc("tscircuit:core"),l8o=Pt({x:oA,y:oA,z:oA}),g0=class extends Ir{schematicBoxDimensions=null;reactSubtrees=[];_impliedFootprint;_resolvedPcbCalcOffsetX;_resolvedPcbCalcOffsetY;isPrimitiveContainer=!0;_isNormalComponent=!0;_attributeLowerToCamelNameMap={_isnormalcomponent:"_isNormalComponent"};_asyncSupplierPartNumbers;_asyncFootprintCadModel;_isCadModelChild;_inferredInternallyConnectedPinNames=[];pcb_missing_footprint_error_id;_hasStartedFootprintUrlLoad=!1;_hasStartedPartOrientationAnalysis=!1;_asyncSupplierPin1LocationMap;_hasStartedSupplierFootprintMismatchWarningCheck=!1;_hasInflatedCircuitJsonSymbol=!1;_invalidFootprintPropMessages=[];_invalidPinLabelMessages=[];_impliedFootprintPinLabels;_adjustSilkscreenTextAutomatically=!1;get defaultInternallyConnectedPinNames(){return[]}get internallyConnectedPinNames(){return[...this._parsedProps.internallyConnectedPins??this.defaultInternallyConnectedPinNames,...this._inferredInternallyConnectedPinNames].map(e=>e.map(n=>typeof n=="number"?`pin${n}`:n))}constructor(t){const e={...t};let n=[];if(e.pinLabels&&!Array.isArray(e.pinLabels)){const{validPinLabels:o,invalidPinLabelsMessages:i}=U7o(e.pinLabels);e.pinLabels=o,n=i}if(super(e),e.pinLabels&&!Array.isArray(e.pinLabels)){const o=Object.keys(e.pinLabels).find(i=>uw(i)===null);if(o)throw new nMt(this.lowercaseComponentName,this.props,{_errors:[],pinLabels:{_errors:[`Invalid pinLabels key "${o}". Expected "pin\${number}" (e.g. pin1, pin2).`]}})}this._invalidPinLabelMessages=n,this._addChildrenFromStringFootprint(),this._addChildrenFromCircuitJsonSymbol(),this.initPorts()}doInitialSourceNameDuplicateComponentRemoval(){if(!this.name)return;const t=this.root;if((this.getSubcircuit().getNormalComponentNameMap?.()?.get(this.props.name)??[]).filter(i=>i!==this&&i.renderPhaseStates.SourceNameDuplicateComponentRemoval.initialized).length>0){const i=this._getGlobalPcbPositionBeforeLayout(),r=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:i,schematic_center:r}),this.shouldBeRemoved=!0;const s=[...this.children];for(const a of s)this.remove(a)}}initPorts(t={}){if(ee.isValidElement(this.props.symbol)&&!this.children.some(u=>u.componentName==="Symbol"))return;this._inferredInternallyConnectedPinNames=[];const{config:n}=this,o=[],i=this._resolvePinLabels(),r=this._parsedProps.pinLabels,s=r&&Array.isArray(r)?Object.fromEntries(r.map((u,g)=>[`pin${g+1}`,u])):r,a=this._getAllPortsFromChildren(),A=u=>a.some(g=>g._parsedProps.pinNumber===u)||o.some(g=>g._parsedProps.pinNumber===u),c=this._getSchematicPortArrangement();if(c&&!i){for(const h in c){const d=c[h].pins;if(Array.isArray(d))for(const p of d){const m=hO(p,i);A(m)||o.push(new Pu({pinNumber:m,aliases:t.additionalAliases?.[`pin${m}`]??[]},{originDescription:`schPortArrangement:${h}`}))}}const u=["left","right","top","bottom"];let g=1;for(const h of u){const d=c[`${h}Size`];for(let p=0;p<d;p++){const m=g++;A(m)||o.push(new Pu({pinNumber:m,aliases:t.additionalAliases?.[`pin${m}`]??[]},{originDescription:`schPortArrangement:${h}`}))}}}if(i)for(const[u,g]of Object.entries(i)){const h=uw(u);if(h===null)throw new Error(`Invalid pinLabels key "${u}". Expected "pin\${number}" (e.g. pin1, pin2).`);let d=a.find(C=>C._parsedProps.pinNumber===h)??o.find(C=>C._parsedProps.pinNumber===h);const p=Array.isArray(g)?g:[g],_=s?.[u]!==void 0,f=_?p[0]:`pin${h}`,I=_?p.slice(1):p;d?d.externallyAddedAliases.push(f,...I):(d=new Pu({pinNumber:h,name:f,aliases:[..._?[]:t.additionalAliases?.[`pin${h}`]??[],...I,..._?t.additionalAliases?.[`pin${h}`]??[]:[]]},{originDescription:`pinLabels:pin${h}`}),o.push(d))}if(n.schematicSymbolName&&!t.ignoreSymbolPorts){const u=Su[this._getSchematicSymbolNameOrThrow()];if(!u)return;for(const g of u.ports){const h=H0e(g.labels);if(!h)continue;const d=this._getAllPortsFromChildren().find(p=>p._parsedProps.pinNumber===Number(h))??o.find(p=>p._parsedProps.pinNumber===Number(h));if(d)d.schematicSymbolPortDef=g;else{const p=O0e(g.labels.concat(t.additionalAliases?.[`pin${h}`]??[]));p&&(p.originDescription=`schematicSymbol:labels[0]:${g.labels[0]}`,p.schematicSymbolPortDef=g,o.push(p))}}this.addAll(o)}if(!this._getSchematicPortArrangement()){const u=ee.isValidElement(this.props.symbol),g=aPe(this.props.symbol);if(!(u||g)){const h=this.getPortsFromFootprint({...t,allowImplicitPinNumbers:!s,collectInferredInternallyConnectedPins:!0}),d=this._getAllPortsFromChildren();for(const p of h){if(!p._isPrimaryPort){o.push(p);continue}const m=d.find(_=>QDt(_,p))??o.find(_=>QDt(_,p));if(m){const _=p.getNameAndAliases().filter(f=>!m.getNameAndAliases().includes(f));m.externallyAddedAliases.push(..._)}else o.push(p)}}}const l=t.pinCount??this._getPrimaryPinCount()??0;for(let u=1;u<=l;u++){if(A(u)||!c&&s&&!Array.isArray(r)&&!s[`pin${u}`])continue;if(!c){o.push(new Pu({pinNumber:u,aliases:t.additionalAliases?.[`pin${u}`]??[]}));continue}let g=rPe(c).map(h=>hO(h,i));["leftSize","rightSize","topSize","bottomSize","leftPinCount","rightPinCount","topPinCount","bottomPinCount"].some(h=>h in c)&&(g=Array.from({length:this._getPrimaryPinCount()},(h,d)=>d+1)),g.includes(u)&&o.push(new Pu({pinNumber:u,aliases:t.additionalAliases?.[`pin${u}`]??[]},{originDescription:`notOtherwiseAddedButDeducedFromPinCount:${u}`}))}vDt(Array.from(new Set([...this._getAllPortsFromChildren(),...o])),this._inferredInternallyConnectedPinNames),o.length>0&&this.addAll(o)}_resolvePinLabels(){const t=this._parsedProps.pinLabels,e=t&&Array.isArray(t)?Object.fromEntries(t.map((o,i)=>[`pin${i+1}`,o])):t,n={...this._impliedFootprintPinLabels??{},...e??{}};if(Object.keys(n).length!==0)return n}_getImpliedFootprintString(){return null}resolveFootprint(){return this._parsedProps.footprint??this.props.footprint??this._getImpliedFootprintString?.()}_addChildrenFromStringFootprint(){const{pcbRotation:t,pcbPinLabels:e}=this.props,n=this._resolvePinLabels(),o=this.resolveFootprint();if(o&&typeof o=="string"){if(hw(o)||dw(o)||Vj(o)||fO(o))return;let i;try{i=pct.string(o).soup()}catch(s){this._queueInvalidFootprintPropMessage(o,s);return}const r=Db({componentName:this.name??this.componentName,componentRotation:t,footprinterString:o,pinLabels:n,pcbPinLabels:e},i);this.addAll(r)}}_addChildrenFromCircuitJsonSymbol(){if(this._hasInflatedCircuitJsonSymbol)return;const t=this._parsedProps.symbol;if(!aPe(t))return;if(this.children.some(r=>r.componentName==="Symbol")){this._hasInflatedCircuitJsonSymbol=!0;return}const e=g6o(t);if(e.length===0)return;const n=u6o(e),o=Db({componentName:this.name??this.componentName,componentRotation:String(this.props.schRotation??0)},n);if(o.length===0)return;if(this._hasInflatedCircuitJsonSymbol=!0,!o.some(r=>r.componentName==="Symbol")){const r=new iPe({name:this.name??this.componentName});r.addAll(o),this.add(r);return}this.addAll(o)}get portMap(){return new Proxy({},{get:(t,e)=>{const n=this.children.find(i=>i.componentName==="Symbol"),o=[...this.children,...n?.children??[]].find(i=>i.componentName==="Port"&&i.isMatchingNameOrAlias(e));if(!o)throw new Error(`There was an issue finding the port "${e.toString()}" inside of a ${this.componentName} component with name: "${this.props.name}". This is a bug in @tscircuit/core`);return o}})}getInstanceForReactElement(t){for(const e of this.reactSubtrees)if(e.element===t)return e.component;return null}doInitialSourceRender(){const t=this.config.sourceFtype;if(!t)return;const{db:e}=this.root,{_parsedProps:n}=this,o=e.source_component.insert({ftype:t,name:this.name,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,display_name:n.displayName});this.source_component_id=o.source_component_id}getRefDesPrefixes(){return _Dt(this.config.sourceFtype)}doInitialCheckRefDesConvention(){v6o(this)}doInitialSourceParentAttachment(){const{db:t}=this.root,e=this._getInternallyConnectedPins().map(n=>n.map(o=>o.source_port_id).filter(o=>o!==null)).filter(n=>n.length>=2);this.source_component_id&&e.length>0&&t.source_component.update(this.source_component_id,{internally_connected_source_port_ids:e});for(const n of e)t.source_component_internal_connection.insert({source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id,source_port_ids:n})}updateSourceParentAttachment(){const{db:t}=this.root;for(const e of t.source_component_internal_connection.list({source_component_id:this.source_component_id}))t.source_component_internal_connection.delete(e.source_component_internal_connection_id);this.doInitialSourceParentAttachment()}doInitialSchematicComponentRender(){W6o(this)}_getSchematicSymbolDisplayValue(){}_getInternallyConnectedPins(){if(this.internallyConnectedPinNames.length===0)return[];const t=[];for(const e of this.internallyConnectedPinNames){const n=[];for(const o of e)n.push(this.portMap[o]);t.push(n)}return t}_doInitialSchematicComponentRenderWithSymbol(){if(this.root?.schematicDisabled)return;const{db:t}=this.root,{_parsedProps:e}=this,n=this._getSchematicSymbolNameOrThrow(),o=Su[n],i=this._getGlobalSchematicPositionBeforeLayout();if(o){const r=t.schematic_component.insert({center:i,size:{...o.size},source_component_id:this.source_component_id,is_box_with_pins:!0,symbol_name:n,schematic_sheet_id:this._resolveSchematicSheetId(),symbol_display_value:this._getSchematicSymbolDisplayValue()});this.schematic_component_id=r.schematic_component_id}}_doInitialSchematicComponentRenderWithReactSymbol(t){if(this.root?.schematicDisabled)return;const{db:e}=this.root,n=this._getGlobalSchematicPositionBeforeLayout(),o=e.schematic_component.insert({center:n,size:{width:0,height:0},source_component_id:this.source_component_id,symbol_display_value:this._getSchematicSymbolDisplayValue(),is_box_with_pins:!1,schematic_sheet_id:this._resolveSchematicSheetId()});this.schematic_component_id=o.schematic_component_id}_doInitialSchematicComponentRenderWithSchematicBoxDimensions(t){if(this.root?.schematicDisabled)return;const{db:e}=this.root,{_parsedProps:n}=this;this.schematicBoxDimensions=t;const o={};if(Array.isArray(n.pinLabels))n.pinLabels.forEach((u,g)=>{o[String(g+1)]=u});else for(const[u,g]of Object.entries(n.pinLabels??{}))o[u]=Array.isArray(g)?g[0]:g;const i=this._getGlobalSchematicPositionBeforeLayout(),r=this._getSchematicPortArrangement(),s=e.schematic_component.insert({center:i,rotation:n.schRotation??0,size:t.getSize(),port_arrangement:ePe(r),pin_spacing:.2,pin_styles:Zwe(n.schPinStyle,n.pinLabels),port_labels:o,source_component_id:this.source_component_id,schematic_sheet_id:this._resolveSchematicSheetId()}),a=r?.topSide!==void 0,A=a||r?.bottomSide!==void 0,c=t?.getSize().width,l=t?.getSize().height;e.schematic_text.insert({text:n.manufacturerPartNumber??"",schematic_component_id:s.schematic_component_id,anchor:"left",rotation:0,position:{x:a?i.x+(c??0)/2+.1:i.x-(c??0)/2,y:A?i.y+(l??0)/2+.35:i.y-(l??0)/2-.13},color:"#006464",font_size:.18,schematic_sheet_id:this._resolveSchematicSheetId()}),e.schematic_text.insert({text:n.displayName??n.name??"",schematic_component_id:s.schematic_component_id,anchor:"left",rotation:0,position:{x:a?i.x+(c??0)/2+.1:i.x-(c??0)/2,y:A?i.y+(l??0)/2+.55:i.y+(l??0)/2+.13},color:"#006464",font_size:.18,schematic_sheet_id:this._resolveSchematicSheetId()}),this.schematic_component_id=s.schematic_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:e}=this,n=this.getSubcircuit(),o=this._getPcbComponentLayer();if(o!=="top"&&o!=="bottom"){const c=vne.parse({type:"pcb_component_invalid_layer_error",message:`Component cannot be placed on layer '${o}'. Components can only be placed on 'top' or 'bottom' layers.`,source_component_id:this.source_component_id,layer:o,subcircuit_id:n.subcircuit_id??void 0});t.pcb_component_invalid_layer_error.insert(c)}const i=this.getGlobalTransformRotation(),r=t.pcb_component.insert({center:this._getGlobalPcbPositionBeforeLayout(),width:0,height:0,layer:o==="top"||o==="bottom"?o:"top",rotation:k9(i),insertion_direction:this._getPcbComponentInsertionDirection(o,i),source_component_id:this.source_component_id,subcircuit_id:n.subcircuit_id??void 0,do_not_place:e.doNotPlace??!1,obstructs_within_bounds:e.obstructsWithinBounds??!0,is_allowed_to_be_off_board:e.allowOffBoard??!1,metadata:e.kicadFootprintMetadata?{kicad_footprint:e.kicadFootprintMetadata}:void 0}),s=this.resolveFootprint(),a=this.children.some(c=>c.componentName==="Footprint");if(!s&&!a&&!this.isGroup){const c=t.pcb_missing_footprint_error.insert({message:`No footprint specified for component: ${this.getString()}`,source_component_id:`${this.source_component_id}`,error_type:"pcb_missing_footprint_error"});this.pcb_missing_footprint_error_id=c.pcb_missing_footprint_error_id}this.pcb_component_id=r.pcb_component_id;const A=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if((this.props.pcbX!==void 0||this.props.pcbY!==void 0)&&A){const c=txe.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:n.subcircuit_id??void 0});t.pcb_manual_edit_conflict_warning.insert(c)}}doInitialPcbComponentSizeCalculation(){if(this.root?.pcbDisabled||!this.pcb_component_id)return;const{db:t}=this.root;B6o(this);const e=L0e(this.children);if(e.width===0||e.height===0)return;const n={x:(e.minX+e.maxX)/2,y:(e.minY+e.maxY)/2};t.pcb_component.update(this.pcb_component_id,{center:n,width:e.width,height:e.height})}updatePcbComponentSizeCalculation(){this.doInitialPcbComponentSizeCalculation()}doInitialSchematicComponentSizeCalculation(){if(this.root?.schematicDisabled||!this.schematic_component_id)return;const{db:t}=this.root;if(!t.schematic_component.get(this.schematic_component_id))return;const n=[],o=c=>{for(const l of c){if(l.isSchematicPrimitive&&l.componentName==="SchematicLine"){const u=t.schematic_line.get(l.schematic_line_id);u&&n.push(u)}if(l.isSchematicPrimitive&&l.componentName==="SchematicRect"){const u=t.schematic_rect.get(l.schematic_rect_id);u&&n.push(u)}if(l.isSchematicPrimitive&&l.componentName==="SchematicCircle"){const u=t.schematic_circle.get(l.schematic_circle_id);u&&n.push(u)}if(l.isSchematicPrimitive&&l.componentName==="SchematicArc"){const u=t.schematic_arc.get(l.schematic_arc_id);u&&n.push(u)}if(l.isSchematicPrimitive&&l.componentName==="SchematicText"){const u=t.schematic_text.get(l.schematic_text_id);u&&n.push(u)}if(l.isSchematicPrimitive&&l.componentName==="SchematicPath"){const u=l.schematic_path_ids;if(u)for(const g of u){const h=t.schematic_path.get(g);h&&n.push(h)}}l.children&&l.children.length>0&&o(l.children)}};if(o(this.children),n.length===0)return;const i=Gj(n),r=Math.abs(i.maxX-i.minX),s=Math.abs(i.maxY-i.minY);if(r===0&&s===0)return;const a=(i.minX+i.maxX)/2,A=(i.minY+i.maxY)/2;t.schematic_component.update(this.schematic_component_id,{center:{x:a,y:A},size:{width:r,height:s}})}updateSchematicComponentSizeCalculation(){this.doInitialSchematicComponentSizeCalculation()}doInitialPcbComponentAnchorAlignment(){O6o(this)}updatePcbComponentAnchorAlignment(){this.doInitialPcbComponentAnchorAlignment()}doInitialResolveFootprintPinLabels(){J6o(this)}updateResolveFootprintPinLabels(){this.doInitialResolveFootprintPinLabels()}_renderReactSubtree(t){const e=RMt(t);return{element:t,component:e}}doInitialInitializePortsFromChildren(){this.initPorts()}updateInitializePortsFromChildren(){this.initPorts()}getGlobalTransformRotation(){const t=this._computePcbGlobalTransformBeforeLayout();return O9(t).rotation.angle*180/Math.PI}_getFootprintMetadataForPcbComponent(){const t=this.children.find(n=>n.componentName==="Footprint");if(t)return{insertionDirection:t._parsedProps.insertionDirection,cutoutApertureDirection:t._parsedProps.cutoutApertureDirection,originalLayer:t._parsedProps.originalLayer};const e=this.props.footprint;if(ee.isValidElement(e)){const n=e.props;return{insertionDirection:n.insertionDirection,cutoutApertureDirection:n.cutoutApertureDirection,originalLayer:n.originalLayer}}if(e?.componentName==="Footprint")return{insertionDirection:e._parsedProps?.insertionDirection??e.props?.insertionDirection,cutoutApertureDirection:e._parsedProps?.cutoutApertureDirection??e.props?.cutoutApertureDirection,originalLayer:e._parsedProps?.originalLayer??e.props?.originalLayer}}_getPcbComponentLayer(){return this._parsedProps.layer??(this._getFootprintOriginalLayer()==="bottom"?"bottom":"top")}_getFootprintOriginalLayer(){return this._getFootprintMetadataForPcbComponent()?.originalLayer}_getPcbComponentInsertionDirection(t,e=this.getGlobalTransformRotation()){const n=this._getFootprintMetadataForPcbComponent();if(n?.insertionDirection)return k9o({insertionDirection:n.insertionDirection,rotationDegrees:e,isFlipped:b0e({componentLayer:t,originalLayer:n.originalLayer})})}_getEnclosureApertureAxisDirection(t,e=this.getGlobalTransformRotation()){const n=this._getFootprintMetadataForPcbComponent(),o=n?.cutoutApertureDirection??n?.insertionDirection;if(o)return AMt({insertionDirection:o,rotationDegrees:e,isFlipped:b0e({componentLayer:t,originalLayer:n?.originalLayer})})}doInitialReactSubtreesRender(){const t=this.props.footprint;ee.isValidElement(t)&&(this.children.some(r=>r.componentName==="Footprint")||this.add(t));const e=this.props.symbol;ee.isValidElement(e)&&(this.children.some(r=>r.componentName==="Symbol")||this.add(e));const n=this.props.cadModel;if(ee.isValidElement(n)){this._isCadModelChild=!0;const i=this.children.some(s=>s.componentName==="CadAssembly"),r=this.children.some(s=>s.componentName==="CadModel");!i&&!r&&this.add(n)}const o=this.props.spiceModel;ee.isValidElement(o)&&(this.children.some(r=>r.componentName==="SpiceModel")||this.add(o))}doInitialPcbFootprintStringRender(){z6o(this,(t,e)=>this._queueAsyncEffect(t,e))}_getAllPortsFromChildren(){const t=[],e=n=>{n.componentName==="Port"&&t.push(n);for(const o of n.children)e(o)};for(const n of this.children)e(n);return t}_hasExistingPortExactly(t){return this._getAllPortsFromChildren().some(n=>{const o=t.getNameAndAliases(),i=n.getNameAndAliases();return o.length===i.length&&o.every(r=>i.includes(r))})}_hasMatchingPort(t){const e=this._getAllPortsFromChildren(),n=t._parsedProps.pinNumber;return n===void 0?!1:e.some(o=>o._parsedProps.pinNumber===n)}add(t){let e;if(ee.isValidElement(t)){const n=this._renderReactSubtree(t);this.reactSubtrees.push(n),e=n.component}else e=t;if(e.componentName==="Port"){if(this._hasExistingPortExactly(e))return;if(this._hasMatchingPort(e)){c8o(`Skipping port ${e} because a matching port already exists`);return}}super.add(e)}getPortsFromFootprint(t){let e;t?.collectInferredInternallyConnectedPins&&(e=this._inferredInternallyConnectedPinNames);const n=new Map,o=this._parsedProps?.pinLabels??this.props.pinLabels;if(o){const a=Array.isArray(o)?o.map((A,c)=>[`pin${c+1}`,A]):Object.entries(o);for(const[A,c]of a){const l=uw(A);if(l===null)continue;const u=Array.isArray(c)?c:[c];for(const g of u)typeof g=="string"&&g.length>0&&n.set(g,l)}}const i={...t,inferredInternallyConnectedPinNames:e,implicitPinNumberByHint:n};let{footprint:r}=this.props;if(typeof r=="string"&&fO(r)&&this.children.some(a=>a.componentName==="Footprint")?r=this.children.find(a=>a.componentName==="Footprint"):(!r||ee.isValidElement(r))&&(r=this.children.find(a=>a.componentName==="Footprint")),typeof r=="string"){if(hw(r))return[];if(dw(r))return[];if(Vj(r))return[];if(fO(r))return[];let a;try{a=pct.string(r).soup()}catch(A){return this._queueInvalidFootprintPropMessage(r,A),[]}return wDt(a.flatMap(A=>"port_hints"in A&&A.port_hints?[{hints:A.port_hints,originDescription:`footprint:string:${r}:port_hints[0]:${A.port_hints[0]}`}]:[]),i)}if(!ee.isValidElement(r)&&r&&r.componentName==="Footprint")return wDt(r.children.flatMap(A=>A.props.portHints?[{hints:A.props.portHints,originDescription:`footprint:${r}`,component:A}]:[]),i);const s=[];if(!r){for(const a of this.children)if(a.props.portHints&&a.isPcbPrimitive){const A=O0e(a.props.portHints);A&&s.push(A)}}return s}_queueInvalidFootprintPropMessage(t,e){const n=e instanceof Error?e.message:String(e),o=t.includes("/")&&!t.includes(":"),r=/^c\d+$/i.test(t)?`C${t.replace(/^c/i,"")}`:null,s=o?` If this is a KiCad footprint, use "kicad:${t}".`:r?` If this is a JLCPCB part number, use "jlcpcb:${r}".`:"",a=`Invalid footprint prop on ${this.getDisplayName()}: "${t}".${s} Parser details: ${n}`;this._invalidFootprintPropMessages.includes(a)||this._invalidFootprintPropMessages.push(a)}_insertInvalidFootprintPropErrors(){for(const t of this._invalidFootprintPropMessages)this.root.db.source_invalid_component_property_error.insert({source_component_id:this.source_component_id||"",property_name:"footprint",message:t,error_type:"source_invalid_component_property_error"});this._invalidFootprintPropMessages=[]}getPortsFromSchematicSymbol(){if(this.root?.schematicDisabled)return[];const{config:t}=this;if(!t.schematicSymbolName)return[];const e=Su[t.schematicSymbolName];if(!e)return[];const n=[];for(const o of e.ports){const i=O0e(o.labels);i&&(i.schematicSymbolPortDef=o,n.push(i))}return n}doInitialCreateNetsFromProps(){this._createNetsFromProps(this._getNetsFromConnectionsProp())}_getNetsFromConnectionsProp(){const{_parsedProps:t}=this,e=[];if(t.connections)for(const[n,o]of Object.entries(t.connections)){const i=Array.isArray(o)?o:[o];for(const r of i)e.push(String(r))}return e}_createNetsFromProps(t){Hj(this,t)}_getPcbCircuitJsonBounds(){const{db:t}=this.root;if(!this.pcb_component_id)return super._getPcbCircuitJsonBounds();const e=t.pcb_component.get(this.pcb_component_id);return{center:{x:e.center.x,y:e.center.y},bounds:{left:e.center.x-e.width/2,top:e.center.y-e.height/2,right:e.center.x+e.width/2,bottom:e.center.y+e.height/2},width:e.width,height:e.height}}_getPinCountFromSchematicPortArrangement(){const t=this._getSchematicPortArrangement();if(!t)return 0;if(!lDt(t))return(t.leftSize??t.leftPinCount??0)+(t.rightSize??t.rightPinCount??0)+(t.topSize??t.topPinCount??0)+(t.bottomSize??t.bottomPinCount??0);const n=rPe(t);let o=0;for(const i of n){if(typeof i=="number"){o=Math.max(o,i);continue}const r=uw(i);if(r!==null){o=Math.max(o,r);continue}const s=this._parsedProps.pinLabels;s&&(o=Math.max(o,hO(i,s)))}return Math.max(o,n.length)}_getPrimaryPinCount(){if(this._getSchematicPortArrangement())return this._getPinCountFromSchematicPortArrangement();const e=this.getPortsFromFootprint();if(e.length>0)return e.filter(o=>o._isPrimaryPort).length;const{pinLabels:n}=this._parsedProps;if(n){if(Array.isArray(n))return n.length;const o=Object.keys(n).map(i=>uw(i)).filter(i=>i!==null&&!Number.isNaN(i));return o.length>0?Math.max(...o):Object.keys(n).length}return 0}_getSchematicPortArrangement(){return this._parsedProps.schPinArrangement??this._parsedProps.schPortArrangement}_getPinLabelsFromPorts(){const t=this.selectAll("port"),e={};for(const n of t){const o=n.props.pinNumber;if(o!==void 0){const i=n._getBestDisplayPinLabel();i&&(e[`pin${o}`]=i)}}return e}_getImplicitSparseSchematicPortArrangement(t){const e=Array.from(new Set(this._getAllPortsFromChildren().filter(r=>r._isPrimaryPort).map(r=>r._parsedProps.pinNumber).filter(r=>r!==void 0))).sort((r,s)=>r-s);if(e.length!==t||!e.some((r,s)=>r!==s+1))return;const o=Math.floor(t/2),i=t-o;return{leftSide:{pins:e.slice(0,i)},rightSide:{pins:e.slice(i)}}}_getSchematicBoxDimensions(){return this.schematicBoxDimensions?this.schematicBoxDimensions:this._computeSchematicBoxDimensions()}_computeSchematicBoxDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox&&!this._parsedProps?.showAsSchematicBox)return null;const{_parsedProps:t}=this,e=this._getPrimaryPinCount(),n=.2,i={...this._getPinLabelsFromPorts(),...t.pinLabels},r=this._getSchematicPortArrangement()??this._getImplicitSparseSchematicPortArrangement(e);return sPe({schWidth:t.schWidth,schHeight:t.schHeight,schPinSpacing:n,numericSchPinStyle:Kj(t.schPinStyle,i),pinCount:e,schPortArrangement:r,pinLabels:i})}getFootprinterString(){const t=this.resolveFootprint();return typeof t=="string"?t:null}doInitialCadModelRender(){if(this._isCadModelChild||this.props.doNotPlace)return;const{db:t}=this.root,{boardThickness:e=0}=this._getBoard()??{},n=this._parsedProps.cadModel,o=n===void 0?this._asyncFootprintCadModel:n,i=this.getFootprinterString()??void 0;let r=!1;if(i&&(r=!fO(i)&&!hw(i)&&!dw(i)&&!Vj(i)),!this.pcb_component_id||o===null)return;const s=this._getPcbCircuitJsonBounds();if(typeof o=="string")throw new Error("String cadModel not yet implemented");const a=o?.pcbRotationOffset??o?.rotationOffset,A=l8o.parse({x:0,y:0,z:typeof a=="number"?a:0,...typeof a=="object"?a:{}}),c=D9.parse({x:0,y:0,z:0,...typeof o?.positionOffset=="object"?o.positionOffset:{}}),l=o&&typeof o=="object"&&"zOffsetFromSurface"in o&&o.zOffsetFromSurface!==void 0?lt.parse(o.zOffsetFromSurface):0,u=this.props.layer==="bottom"?"bottom":"top",g=t.pcb_component.get(this.pcb_component_id),h=this._computePcbGlobalTransformBeforeLayout(),p=O9(h).rotation.angle*180/Math.PI,m=g?.position_mode==="packed"?g.rotation??p:p,_=u==="bottom";if(!o&&!r){const x=t.cad_component.insert({position:{x:s.center.x,y:s.center.y,z:u==="bottom"?-e/2:e/2},rotation:{x:0,y:_?180:0,z:k9(_?-m:m)},pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,model_origin_alignment:"center_of_component_on_board_surface",anchor_alignment:"center_of_component_on_board_surface",show_as_bounding_box:!0,show_as_translucent_model:this._parsedProps.showAsTranslucentModel});this.cad_component_id=x.cad_component_id;return}const f=m+(A.z??0),I=k9(f);let C;!o&&r&&(C=i);const y=t.cad_component.insert({position:{x:s.center.x+c.x,y:s.center.y+c.y,z:(u==="bottom"?-e/2:e/2)+(u==="bottom"?-l:l)+c.z},rotation:{x:A.x,y:A.y+(_?180:0),z:k9(_?-I:I)},pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,model_stl_url:"stlUrl"in(o??{})?this._addCachebustToModelUrl(o.stlUrl):void 0,model_obj_url:"objUrl"in(o??{})?this._addCachebustToModelUrl(o.objUrl):void 0,model_mtl_url:"mtlUrl"in(o??{})?this._addCachebustToModelUrl(o.mtlUrl):void 0,model_gltf_url:"gltfUrl"in(o??{})?this._addCachebustToModelUrl(o.gltfUrl):void 0,model_glb_url:"glbUrl"in(o??{})?this._addCachebustToModelUrl(o.glbUrl):void 0,model_step_url:"stepUrl"in(o??{})?this._addCachebustToModelUrl(o.stepUrl):void 0,model_wrl_url:"wrlUrl"in(o??{})?this._addCachebustToModelUrl(o.wrlUrl):void 0,model_jscad:"jscad"in(o??{})?o.jscad:void 0,model_unit_to_mm_scale_factor:typeof o?.modelUnitToMmScale=="number"?o.modelUnitToMmScale:void 0,model_board_normal_direction:o?.modelBoardNormalDirection,model_origin_alignment:"center_of_component_on_board_surface",anchor_alignment:"center_of_component_on_board_surface",model_origin_position:o?.modelOriginPosition,...o?.size?{size:o.size}:{},footprinter_string:C,show_as_translucent_model:this._parsedProps.showAsTranslucentModel});this.cad_component_id=y.cad_component_id}_addCachebustToModelUrl(t){if(!t||!t.includes("modelcdn.tscircuit.com"))return t;const e=this.root?.getClientOrigin()??"";return`${t}${t.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(e)}`}_getPartsEngineCacheKey(t,e){return JSON.stringify({ftype:t.ftype,name:t.name,manufacturer_part_number:t.manufacturer_part_number,standard:t.standard,pin_count:t.pin_count,footprinterString:e})}async _getSupplierPartNumbers(t,e,n){if(this.props.doNotPlace)return{};const o=this.root?.platform?.localCacheEngine,i=this._getPartsEngineCacheKey(e,n);if(o){const a=await o.getItem(i);if(a)try{return JSON.parse(a)}catch{}}const r=await Promise.resolve(t.findPart({sourceComponent:e,footprinterString:n}));if(typeof r=="string")throw r.includes("<!DOCTYPE")||r.includes("<html")?new Error(`Failed to fetch supplier part numbers: Received HTML response instead of JSON. Response starts with: ${r.substring(0,100)}`):r==="Not found"?new Error(`Part not found for ${this.getString()}${n?` with footprint "${n}"`:""}`):new Error(`Invalid supplier part numbers format: Expected object but got string: "${r}"`);if(!r||Array.isArray(r)||typeof r!="object"){const a=r===null?"null":Array.isArray(r)?"array":typeof r;throw new Error(`Invalid supplier part numbers format: Expected object but got ${a}`)}const s=r;if(o)try{await o.setItem(i,JSON.stringify(s))}catch{}return s}doInitialPartsEngineRender(){if(this.props.doNotPlace||this.getInheritedProperty("bomDisabled")||this.getInheritedProperty("partsEngineDisabled"))return;const t=this.getInheritedProperty("partsEngine");if(!t)return;const{db:e}=this.root,n=e.source_component.get(this.source_component_id);if(!n||n.supplier_part_numbers)return;const o=this.props.footprint??this._getImpliedFootprintString(),i=typeof o=="string"?o:void 0,r=this._getSupplierPartNumbers(t,n,i);if(!(r instanceof Promise)){e.source_component.update(this.source_component_id,{supplier_part_numbers:r});return}this._queueAsyncEffect("get-supplier-part-numbers",async()=>{await r.then(s=>{this._asyncSupplierPartNumbers=s,this._markDirty("PartsEngineRender")}).catch(s=>{this._asyncSupplierPartNumbers={};const a=hV.parse({type:"source_part_not_found_warning",message:`Failed to fetch supplier part numbers for ${this.getString()}: ${s.message}`,source_component_id:this.source_component_id??void 0,subcircuit_id:this.getSubcircuit()?.subcircuit_id??void 0,manufacturer_part_number:n.manufacturer_part_number??void 0,part_name:n.name??void 0});e.source_part_not_found_warning.insert(a),this._markDirty("PartsEngineRender")})})}updatePartsEngineRender(){if(this.props.doNotPlace||this.getInheritedProperty("bomDisabled")||this.getInheritedProperty("partsEngineDisabled"))return;const{db:t}=this.root,e=t.source_component.get(this.source_component_id);if(e&&!e.supplier_part_numbers&&this._asyncSupplierPartNumbers){t.source_component.update(this.source_component_id,{supplier_part_numbers:this._asyncSupplierPartNumbers});return}}doInitialPartOrientationAnalysis(){L6o(this)}updatePartOrientationAnalysis(){H6o(this)}doInitialSupplierFootprintMismatchWarning(){r8o(this)}updateSupplierFootprintMismatchWarning(){this.doInitialSupplierFootprintMismatchWarning()}doInitialAssignFallbackProps(){const{_parsedProps:t}=this;t.connections&&!this.name&&(this.fallbackUnassignedName=this.getSubcircuit().getNextAvailableName(this))}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}_createTracesFromConnectionsProp(){const{_parsedProps:t}=this;if(t.connections)for(const[e,n]of Object.entries(t.connections)){const o=Array.isArray(n)?n:[n];for(const i of o)this.add(new t1({from:`.${this.name} > .${e}`,to:String(i)}))}}doInitialSourceDesignRuleChecks(){q6o(this)}doInitialSourceComponentPropertyValidation(){this._insertInvalidFootprintPropErrors()}doInitialValidatePcbCoordinates(){if(super.doInitialValidatePcbCoordinates(),this.root?.pcbDisabled)return;const t=this._parsedProps,e=this.props,n=typeof e.pcbLeftEdgeX=="string"?e.pcbLeftEdgeX:t.pcbLeftEdgeX??e.pcbLeftEdgeX,o=typeof e.pcbRightEdgeX=="string"?e.pcbRightEdgeX:t.pcbRightEdgeX??e.pcbRightEdgeX,i=typeof e.pcbTopEdgeY=="string"?e.pcbTopEdgeY:t.pcbTopEdgeY??e.pcbTopEdgeY,r=typeof e.pcbBottomEdgeY=="string"?e.pcbBottomEdgeY:t.pcbBottomEdgeY??e.pcbBottomEdgeY;(t.pcbX!==void 0||t.pcbY!==void 0||n!==void 0||o!==void 0||i!==void 0||r!==void 0)&&(n!==void 0&&this._validatePcbCoordinateReferences({rawValue:n,axis:"pcbX",propertyName:"pcbLeftEdgeX"}),o!==void 0&&this._validatePcbCoordinateReferences({rawValue:o,axis:"pcbX",propertyName:"pcbRightEdgeX"}),i!==void 0&&this._validatePcbCoordinateReferences({rawValue:i,axis:"pcbY",propertyName:"pcbTopEdgeY"}),r!==void 0&&this._validatePcbCoordinateReferences({rawValue:r,axis:"pcbY",propertyName:"pcbBottomEdgeY"}))}doInitialPcbLayout(){if(this.root?.pcbDisabled||!this.pcb_component_id)return;const{db:t}=this.root,e=this._parsedProps,n=this.props,o=e.pcbLeftEdgeX??n.pcbLeftEdgeX,i=e.pcbRightEdgeX??n.pcbRightEdgeX,r=e.pcbTopEdgeY??n.pcbTopEdgeY,s=e.pcbBottomEdgeY??n.pcbBottomEdgeY;if(!(e.pcbX!==void 0||e.pcbY!==void 0||o!==void 0||i!==void 0||r!==void 0||s!==void 0))return;if(o!==void 0&&i!==void 0)throw new Error(`${this.componentName} cannot set both pcbLeftEdgeX and pcbRightEdgeX`);if(r!==void 0&&s!==void 0)throw new Error(`${this.componentName} cannot set both pcbTopEdgeY and pcbBottomEdgeY`);const A=t.pcb_component.get(this.pcb_component_id),c=A?.width??0,l=A?.height??0,g=this.getGroup()?.pcb_group_id??void 0,h=g?void 0:this._getBoard()?.pcb_board_id??void 0,d=this._resolvedPcbCalcOffsetX??(e.pcbX!==void 0?this._resolvePcbCoordinate(e.pcbX,"pcbX"):o!==void 0?this._resolvePcbCoordinate(o,"pcbX",{propertyName:"pcbLeftEdgeX"})+c/2:i!==void 0?this._resolvePcbCoordinate(i,"pcbX",{propertyName:"pcbRightEdgeX"})-c/2:void 0),p=this._resolvedPcbCalcOffsetY??(e.pcbY!==void 0?this._resolvePcbCoordinate(e.pcbY,"pcbY"):r!==void 0?this._resolvePcbCoordinate(r,"pcbY",{propertyName:"pcbTopEdgeY"})-l/2:s!==void 0?this._resolvePcbCoordinate(s,"pcbY",{propertyName:"pcbBottomEdgeY"})+l/2:void 0);t.pcb_component.update(this.pcb_component_id,{position_mode:"relative_to_group_anchor",positioned_relative_to_pcb_group_id:g,positioned_relative_to_pcb_board_id:h,display_offset_x:d,display_offset_y:p})}_getMinimumFlexContainerSize(){return _6o(this)}_repositionOnPcb(t){return f6o(this,t)}doInitialSilkscreenOverlapAdjustment(){return $6o(this)}isRelativelyPositioned(){const t=this.props;return this._parsedProps.pcbX!==void 0||this._parsedProps.pcbY!==void 0||this._parsedProps.pcbLeftEdgeX!==void 0||this._parsedProps.pcbRightEdgeX!==void 0||this._parsedProps.pcbTopEdgeY!==void 0||this._parsedProps.pcbBottomEdgeY!==void 0||t.pcbLeftEdgeX!==void 0||t.pcbRightEdgeX!==void 0||t.pcbTopEdgeY!==void 0||t.pcbBottomEdgeY!==void 0}},uPe=(t,e)=>{const n=t.source_group.list(),o=[],i=r=>{const s=n.filter(a=>a.parent_subcircuit_id===r);for(const a of s)a.subcircuit_id&&(o.push(a.subcircuit_id),i(a.subcircuit_id))};return i(e),o},u8o=({boardAnchorPosition:t,boardAnchorAlignment:e,width:n,height:o})=>{const{x:i,y:r}=t;let s=i,a=r;switch(e){case"top_left":s=i+n/2,a=r-o/2;break;case"top_right":s=i-n/2,a=r-o/2;break;case"bottom_left":s=i+n/2,a=r+o/2;break;case"bottom_right":s=i-n/2,a=r+o/2;break;case"top":s=i,a=r-o/2;break;case"bottom":s=i,a=r+o/2;break;case"left":s=i+n/2,a=r;break;case"right":s=i-n/2,a=r;break}return{x:s,y:a}};function g8o(t,e){const{subcircuit:n}=e;if(n.lowercaseComponentName==="board"||n.lowercaseComponentName==="mountedboard"||n.parent?.lowercaseComponentName==="board")return;const o={name:"inflated_board"};t.width&&(o.width=t.width),t.height&&(o.height=t.height),t.center&&(o.pcbX=t.center.x,o.pcbY=t.center.y),t.outline&&(o.outline=t.outline),t.thickness&&(o.thickness=t.thickness),t.material&&(o.material=t.material),t.is_via_in_pad_allowed!==void 0&&(o.isViaInPadAllowed=t.is_via_in_pad_allowed),t.allow_blind_and_buried_vias!==void 0&&(o.allowBlindAndBuriedVias=t.allow_blind_and_buried_vias);const i=new wB(o);return i.pcb_board_id=t.pcb_board_id,n.add(i),i}var gPe=new WeakMap,PDt=t=>{const e=[t.name,...t.port_hints??[]].map(i=>i.toLowerCase().replace(/[^a-z0-9+-]/g,"")),n=e.some(i=>["a","anode","pos","positive","+"].includes(i)),o=e.some(i=>["k","cathode","neg","negative","-"].includes(i));return n===o?null:n?"positive":"negative"},d8o=t=>{const e=t.root;if(!e)return;const{db:n}=e;for(const m of gPe.get(t)??[])n.pcb_fabrication_note_path.delete(m.pcb_fabrication_note_path_id);if(gPe.delete(t),e.pcbDisabled||!t.props.polarized||!t.pcb_component_id)return;const o=n.pcb_component.get(t.pcb_component_id);if(!o||o.layer!=="top"&&o.layer!=="bottom")return;const i=n.source_port.list({source_component_id:t.source_component_id}),r=i.filter(m=>PDt(m)==="positive"),s=i.filter(m=>PDt(m)==="negative");if(r.length!==1||s.length!==1)return;const a=n.pcb_port.getWhere({source_port_id:r[0].source_port_id}),A=n.pcb_port.getWhere({source_port_id:s[0].source_port_id});if(!a||!A)return;const c=Math.hypot(A.x-a.x,A.y-a.y);if(c<1e-6)return;const l=D0(M0((a.x+A.x)/2,(a.y+A.y)/2),W4(Math.atan2(A.y-a.y,A.x-a.x))),u=(m,_)=>ts(l,{x:m,y:_}),g=c/4,h=Math.min(c*.12,.3),d=[[u(-g-h,0),u(-g+h,0)],[u(-g,-h),u(-g,h)],[u(g-h,0),u(g+h,0)]],p=[];gPe.set(t,p);for(const m of d)p.push(n.pcb_fabrication_note_path.insert({pcb_component_id:o.pcb_component_id,subcircuit_id:t.getSubcircuit()?.subcircuit_id??void 0,layer:o.layer,route:m,stroke_width:Math.min(.08,h*.4)}))},h8o=1;function p8o(t){const e=[];for(const n of t.children)n instanceof Pu&&e.push(n);return e}function m8o(t){const e=p8o(t);if(e.length!==2)return;const n=e[0].isConnectedToPower(),o=e[0].isConnectedToGround(),i=e[1].isConnectedToPower(),r=e[1].isConnectedToGround();return n&&!o&&r&&!i||i&&!r&&o&&!n?h8o:void 0}var _8o=new Set(["01005","0201","0402","0603","0805","1206","1210","2010","2512"]),MDt=class extends g0{_adjustSilkscreenTextAutomatically=!0;get config(){const t=this.props.symbolName??"capacitor",e=this.props.schSize==="sm"||this.props.schSize==="xs"?this.props.schSize:void 0,n=e&&t==="capacitor"?`capacitor_${e}`:void 0,o=n&&`${n}_right`in Su?n:t;return{componentName:"Capacitor",schematicSymbolName:this.props.polarized?"capacitor_polarized":o,zodProps:qwn,sourceFtype:$7.simple_capacitor}}initPorts(){typeof this.props.footprint=="string"?super.initPorts({additionalAliases:{pin1:["anode","pos"],pin2:["cathode","neg"]}}):super.initPorts()}_getSchematicSymbolDisplayValue(){const t=this.props.capacitance;let e;return this._parsedProps.capacitance!==void 0&&!isNaN(this._parsedProps.capacitance)?e=typeof t=="string"?t:`${H_(this._parsedProps.capacitance)}F`:e=`${H_(this._parsedProps.capacitance)}F`,this._parsedProps.schShowRatings&&this._parsedProps.maxVoltageRating?`${e}/${H_(this._parsedProps.maxVoltageRating)}V`:e}getFootprinterString(){const t=super.getFootprinterString();return t&&_8o.has(t)?`cap${t}`:t}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.decouplingFor,this.props.decouplingTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.decouplingFor&&this.props.decouplingTo&&(this.add(new t1({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.decouplingFor})),this.add(new t1({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.decouplingTo}))),this._createTracesFromConnectionsProp()}doInitialPcbComponentSizeCalculation(){super.doInitialPcbComponentSizeCalculation(),d8o(this)}doInitialSourceRender(){const{db:t}=this.root,{_parsedProps:e}=this,n=t.source_component.insert({ftype:"simple_capacitor",name:this.name,manufacturer_part_number:e.manufacturerPartNumber??e.mfn,supplier_part_numbers:e.supplierPartNumbers,capacitance:e.capacitance,max_voltage_rating:e.maxVoltageRating,max_decoupling_trace_length:e.maxDecouplingTraceLength??m8o(this),display_capacitance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!e.polarized,display_name:e.displayName});this.source_component_id=n.source_component_id}},f8o=({pcbComponent:t,db:e,componentName:n})=>{const o=t.center||{x:0,y:0},i=t.rotation||0,r=CRn(D0(M0(o.x,o.y),W4(i*Math.PI/180))),s=e.toArray().filter(c=>"pcb_component_id"in c&&c.pcb_component_id===t.pcb_component_id),a=structuredClone(s);return FF(a,r),Db({componentName:n,componentRotation:"0deg"},a)},e4=(t,e)=>{const{injectionDb:n,normalComponent:o}=e;if(!o)return null;const i=f8o({pcbComponent:t,db:n,componentName:o.name});if(i.length===0)return null;const r=new Y0e({originalLayer:t.layer});return r.addAll(i),r},t4=({pcbComponent:t,sourceGroupId:e,inflatorContext:n})=>{if(!t?.center)return{pcbX:void 0,pcbY:void 0};if(e){const o=n.injectionDb.pcb_group.getWhere({source_group_id:e});if(o?.anchor_position)return{pcbX:t.center.x-o.anchor_position.x,pcbY:t.center.y-o.anchor_position.y}}return{pcbX:t.center.x,pcbY:t.center.y}};function I8o(t,e){const{injectionDb:n,subcircuit:o,groupsMap:i}=e,r=n.pcb_component.getWhere({source_component_id:t.source_component_id});n.cad_component.getWhere({source_component_id:t.source_component_id});const{pcbX:s,pcbY:a}=t4({pcbComponent:r,sourceGroupId:t.source_group_id,inflatorContext:e}),A=new MDt({name:t.name,capacitance:t.capacitance,layer:r?.layer,pcbX:s,pcbY:a,pcbRotation:r?.rotation,doNotPlace:r?.do_not_place,obstructsWithinBounds:r?.obstructs_within_bounds});if(r){const c=e4(r,{...e,normalComponent:A});c&&A.add(c)}t.source_group_id&&i?.has(t.source_group_id)?i.get(t.source_group_id).add(A):o.add(A)}var DDt=({circuitJson:t,pcbComponentId:e,sourceComponentId:n})=>{const o=t.filter(r=>r.type==="pcb_component"?r.pcb_component_id===e:r.type==="source_component"?r.source_component_id===n:"pcb_component_id"in r&&r.pcb_component_id===e||"source_component_id"in r&&r.source_component_id===n);if(o.length===0)return null;const i=P$n(o);return{x:i.x,y:i.y}},C8o=t=>{if(t.root?.pcbDisabled||!t.name.toUpperCase().startsWith("J")||!t.pcb_component_id||!t.source_component_id)return;const e=t.root?.platform?.placementDrcChecksDisabled??t.getInheritedProperty("placementDrcChecksDisabled"),n=t.root?.platform?.drcChecksDisabled??t.getInheritedProperty("drcChecksDisabled");if(e||n)return;const{db:o}=t.root;if(o.source_component.get(t.source_component_id)?.ftype!=="simple_chip")return;const r=o.subtree({subcircuit_id:t.getSubcircuit().subcircuit_id}).toArray(),s=DDt({circuitJson:r,pcbComponentId:t.pcb_component_id,sourceComponentId:t.source_component_id});if(!s)return;const a=r.map(l=>l.type==="pcb_component"&&l.pcb_component_id===t.pcb_component_id?{...l,cable_insertion_center:s}:l),A=Vmt(a).find(l=>l.pcb_component_id===t.pcb_component_id);!A||o.toArray().some(l=>l.type===A.type&&l.message===A.message)||o.insertAll([A])},zj=class extends g0{get config(){return{componentName:"Chip",zodProps:Y3,shouldRenderAsSchematicBox:!0}}initPorts(t={}){super.initPorts(t);const{_parsedProps:e}=this;if(e.externallyConnectedPins){const n=new Set;for(const[o,i]of e.externallyConnectedPins)n.add(o),n.add(i);for(const o of n)if(!this.children.find(r=>r instanceof Pu&&r.isMatchingAnyOf([o]))){const r=o.match(/^pin(\d+)$/);if(r){const s=parseInt(r[1]);this.add(new Pu({pinNumber:s,aliases:[o]}))}else this.add(new Pu({name:o,aliases:[o]}))}}}doInitialSourceRender(){const{db:t}=this.root,{_parsedProps:e}=this,n=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:e.manufacturerPartNumber,supplier_part_numbers:e.supplierPartNumbers,display_name:e.displayName});this.source_component_id=n.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:e}=this,{pcbX:n,pcbY:o}=this.getResolvedPcbPositionProp(),i=e.footprint??this._getImpliedFootprintString(),r=this.children.some(c=>c.componentName==="Footprint");if(!i&&!r&&!this._hasStartedFootprintUrlLoad){const c=t.pcb_missing_footprint_error.insert({message:`No footprint specified for component: ${this.getString()}`,source_component_id:`${this.source_component_id}`,error_type:"pcb_missing_footprint_error"});this.pcb_missing_footprint_error_id=c.pcb_missing_footprint_error_id}const s=this._getPcbComponentLayer();if(s!=="top"&&s!=="bottom"){const c=this.getSubcircuit(),l=vne.parse({type:"pcb_component_invalid_layer_error",message:`Component cannot be placed on layer '${s}'. Components can only be placed on 'top' or 'bottom' layers.`,source_component_id:this.source_component_id,layer:s,subcircuit_id:c.subcircuit_id??void 0});t.pcb_component_invalid_layer_error.insert(l)}const a=this.getGlobalTransformRotation(),A=t.pcb_component.insert({center:{x:n,y:o},width:2,height:3,layer:s==="top"||s==="bottom"?s:"top",rotation:k9(a),insertion_direction:this._getPcbComponentInsertionDirection(s,a),source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:e.doNotPlace??!1,obstructs_within_bounds:e.obstructsWithinBounds??!0,is_allowed_to_be_off_board:e.allowOffBoard??!1,metadata:e.kicadFootprintMetadata?{kicad_footprint:e.kicadFootprintMetadata}:void 0});this.pcb_component_id=A.pcb_component_id}doInitialPcbPlacementDesignRuleChecks(){C8o(this)}doInitialCreateTracesFromProps(){const{_parsedProps:t}=this;if(t.externallyConnectedPins)for(const[e,n]of t.externallyConnectedPins)this.add(new t1({from:`${this.getSubcircuitSelector()} > port.${e}`,to:`${this.getSubcircuitSelector()} > port.${n}`}));this._createTracesFromConnectionsProp()}doInitialSimulationRender(){const{db:t}=this.root,{pinAttributes:e}=this.props;if(!e)return;let n=null,o=null,i;const r=this.selectAll("port");for(const l of r)for(const u of l.getNameAndAliases())if(e[u]){const g=e[u];g.providesPower&&(n=l,i=g.providesVoltage),g.providesGround&&(o=l)}if(!n||!o||i===void 0)return;const s=t.source_port.get(n.source_port_id);if(!s?.subcircuit_connectivity_map_key)return;const a=t.source_port.get(o.source_port_id);if(!a?.subcircuit_connectivity_map_key)return;const A=t.source_net.getWhere({subcircuit_connectivity_map_key:s.subcircuit_connectivity_map_key}),c=t.source_net.getWhere({subcircuit_connectivity_map_key:a.subcircuit_connectivity_map_key});!A||!c||t.simulation_voltage_source.insert({type:"simulation_voltage_source",positive_source_port_id:n.source_port_id,positive_source_net_id:A.source_net_id,negative_source_port_id:o.source_port_id,negative_source_net_id:c.source_net_id,voltage:i})}},y8o=(t,e)=>{if(!t||t.length===0)return;const{injectionDb:n}=e,o=t.map(i=>i.map(r=>{const s=n.source_port.get(r);return s?s.pin_number!==void 0&&s.pin_number!==null?`pin${s.pin_number}`:s.name:null}).filter(r=>r!==null)).filter(i=>i.length>0);return o.length>0?o:void 0},x8o=(t,e)=>{const{injectionDb:n,subcircuit:o,groupsMap:i}=e,r=n.pcb_component.getWhere({source_component_id:t.source_component_id}),s=n.schematic_component.getWhere({source_component_id:t.source_component_id}),a=n.cad_component.getWhere({source_component_id:t.source_component_id}),A=y8o(t.internally_connected_source_port_ids,e),c=a?.footprinter_string??null,{pcbX:l,pcbY:u}=t4({pcbComponent:r,sourceGroupId:t.source_group_id,inflatorContext:e}),g=new zj({name:t.name,manufacturerPartNumber:t.manufacturer_part_number,supplierPartNumbers:t.supplier_part_numbers??void 0,pinLabels:s?.port_labels??void 0,schWidth:s?.size?.width,schHeight:s?.size?.height,schPinSpacing:s?.pin_spacing,schX:s?.center?.x,schY:s?.center?.y,layer:r?.layer,pcbX:l,pcbY:u,pcbRotation:r?.rotation,doNotPlace:r?.do_not_place,obstructsWithinBounds:r?.obstructs_within_bounds,internallyConnectedPins:A});if(c&&(Object.assign(g.props,{footprint:c}),Object.assign(g._parsedProps,{footprint:c})),r){const h=e4(r,{...e,normalComponent:g});h&&g.add(h)}t.source_group_id&&i?.has(t.source_group_id)?i.get(t.source_group_id).add(g):o.add(g)},E8o=/^(?:pin)?(\d+)$/i,B8o=t=>{for(const e of t??[]){const n=e.trim().match(E8o);if(n)return Number.parseInt(n[1],10)}},NDt=(t,e)=>t!==void 0&&t>=1&&t<=e,b8o=(t,e)=>{const n=new Map;for(const i of t)i.type==="source_port"&&typeof i.pin_number=="number"&&n.set(i.source_port_id,i.pin_number);const o=new Map;for(const i of t){if(i.type!=="pcb_port")continue;const r=n.get(i.source_port_id);r!==void 0&&o.set(i.pcb_port_id,r)}return t.filter(i=>!i.type.startsWith("schematic_")).map(i=>{if(i.type==="source_port"){const A=i.pin_number;return{...i,name:typeof A=="number"?`pin${A}`:i.name,port_hints:NDt(A,e)?[`pin${A}`]:[]}}if(!("port_hints"in i)&&!("pcb_port_id"in i))return i;const r="port_hints"in i?B8o(i.port_hints):void 0,s="pcb_port_id"in i&&typeof i.pcb_port_id=="string"?o.get(i.pcb_port_id):void 0,a=r??s;return{...i,port_hints:NDt(a,e)?[`pin${a}`]:[]}})},RDt=[{label:"GND1",aliases:[]},{label:"VBUS1",aliases:[]},{label:"CC1",aliases:[]},{label:"DP1",aliases:[]},{label:"DM1",aliases:["DN1"]},{label:"SBU1",aliases:[]},{label:"SBU2",aliases:[]},{label:"DM2",aliases:["DN2"]},{label:"DP2",aliases:[]},{label:"CC2",aliases:[]},{label:"VBUS2",aliases:[]},{label:"GND2",aliases:[]},{label:"SHELL1",aliases:["MH1","EH1","MOUNT1"]},{label:"SHELL2",aliases:["MH2","EH2","MOUNT2"]},{label:"SHELL3",aliases:["MH3","EH3","MOUNT3"]},{label:"SHELL4",aliases:["MH4","EH4","MOUNT4"]}],S8o=/^(?:pin)?(\d+)$/i,Q8o=t=>Array.from(new Set(t)),v8o=t=>{const e=[];for(const o of t){if(o.type!=="source_port")continue;const i=o.pin_number;if(typeof i!="number")continue;const r=new Set;for(const s of o.port_hints??[])r.add(s.trim().toUpperCase());e.push({pinKey:`pin${i}`,upperCaseHints:r})}const n={};for(const{label:o,aliases:i}of RDt){const r=[o,...i].map(A=>A.toUpperCase()),s=e.findIndex(A=>r.some(c=>A.upperCaseHints.has(c)));if(s===-1)continue;const{pinKey:a}=e[s];n[a]=[o],e.splice(s,1)}return Object.keys(n).length===0?t:t.map(o=>{if(!("port_hints"in o)||!Array.isArray(o.port_hints))return o;const i=o.port_hints.filter(a=>typeof a=="string").map(a=>a.trim()).filter(a=>a.length>0);if(i.length===0)return o;const r=new Set;o.type==="source_port"&&typeof o.pin_number=="number"&&r.add(`pin${o.pin_number}`);for(const a of i){const A=a.match(S8o);A&&r.add(`pin${Number.parseInt(A[1],10)}`)}const s=[];for(const a of r)s.push(...n[a]??[]);return s.length===0?o:{...o,port_hints:Q8o([...i,...s])}})},TDt=.5,w8o=.15;function P8o(t,e){if(!t.schematic_component_id||!t.root)return;const{db:n}=t.root,o=n.schematic_component.get(t.schematic_component_id);if(!o||o.symbol_name)return;const i=o.size.width*TDt,r=o.size.height*TDt,s=Math.min(i/e.size.width,r/e.size.height);if(!Number.isFinite(s)||s<=0)return;const a=t.getSubcircuit()?.subcircuit_id??void 0,A=o.center,c=e.center,l=-o.size.width*w8o,u=g=>({x:A.x+l+(g.x-c.x)*s,y:A.y+(g.y-c.y)*s});for(const g of e.primitives)if(g.type==="path"){const h=g.points.map(u);if(g.closed&&h.length>1){const d=h[0],p=h[h.length-1];(d.x!==p.x||d.y!==p.y)&&h.push(d)}n.schematic_path.insert({schematic_component_id:t.schematic_component_id,points:h,is_filled:g.fill??!1,is_dashed:!1,fill_color:g.fill?wb:void 0,stroke_width:.02,subcircuit_id:a,schematic_sheet_id:t._resolveSchematicSheetId()})}else if(g.type==="circle")n.schematic_circle.insert({schematic_component_id:t.schematic_component_id,center:u({x:g.x,y:g.y}),radius:g.radius*s,stroke_width:.02,color:wb,is_filled:g.fill,fill_color:g.fill?wb:void 0,is_dashed:!1,subcircuit_id:a,schematic_sheet_id:t._resolveSchematicSheetId()});else if(g.type==="box"){const h=u({x:g.x,y:g.y}),d=u({x:g.x+g.width,y:g.y+g.height});n.schematic_rect.insert({schematic_component_id:t.schematic_component_id,center:{x:(h.x+d.x)/2,y:(h.y+d.y)/2},width:Math.abs(d.x-h.x),height:Math.abs(d.y-h.y),stroke_width:.02,color:wb,is_filled:!1,is_dashed:!1,rotation:0,subcircuit_id:a,schematic_sheet_id:t._resolveSchematicSheetId()})}}var kDt=["VBUS1","VBUS2","CC1","CC2","DP1","DP2","DM1","DM2","SBU1","SBU2","GND1","GND2"],FDt=["SHELL1","SHELL2","SHELL3","SHELL4"],M8o=[...kDt,...FDt],D8o=new Set([...M8o]),N8o=new Set(["jst_sh","jst_gh","jst_zh","jst_ph","jst_xh","jst_vh"]),dPe=t=>t!==void 0&&N8o.has(t),R8o=[["CC1",{marginTop:.15}],["DP1",{marginTop:.15}],["SBU1",{marginTop:.15}],["GND1",{marginTop:.15}],["SHELL4",{marginRight:.15}]],LDt=class extends zj{_getConnectorProps(){return this._parsedProps}initPorts(){const t=this._getConnectorProps();super.initPorts({pinCount:dPe(t.standard)?t.pinCount:void 0})}_hasExplicitFootprint(){return this._getConnectorProps().footprint!==void 0||this.children.some(e=>e.componentName==="Footprint")}_shouldUseStandardPartsEngineCircuitJsonFlow(){return!(!this._getConnectorProps().standard||this._hasExplicitFootprint()||this.getInheritedProperty("partsEngineDisabled"))}_addUsbCCanonicalFallbackPorts(){this.selectAll("port").length>0||(this.addAll(RDt.map(({label:t,aliases:e},n)=>new Pu({pinNumber:n+1,name:t,aliases:[...e]}))),this._markDirty("InitializePortsFromChildren"))}_handleStandardConnectorCircuitJsonFailure(t,e){const{db:n}=this.root,o=hV.parse({type:"source_part_not_found_warning",message:`Failed to fetch circuit JSON for ${this.getString()} (standard="${t}"): ${e}`,source_component_id:this.source_component_id??void 0,subcircuit_id:this.getSubcircuit()?.subcircuit_id??void 0,manufacturer_part_number:this._getConnectorProps().manufacturerPartNumber??this._getConnectorProps().mfn??void 0,part_name:this.name});n.source_part_not_found_warning.insert(o),t==="usb_c"&&this._addUsbCCanonicalFallbackPorts()}_getSupplierPartNumbersToTry(t){const e=[];for(const n of Object.keys(t??{})){const o=t?.[n];Array.isArray(o)&&o.length>0&&e.push(o[0])}return e}async _tryFetchPartCircuitJson(t,e){const n=await Promise.resolve(t(e))??null;return Array.isArray(n)&&n.length>0?n:null}async _fetchStandardConnectorCircuitJson(t,e,n){for(const o of this._getSupplierPartNumbersToTry(e)){const i=await this._tryFetchPartCircuitJson(t,{supplierPartNumber:o});if(i)return i}return n?this._tryFetchPartCircuitJson(t,{manufacturerPartNumber:n}):null}_addConnectorFootprintFromCircuitJson(t,e){const n=this._getConnectorProps(),o=t==="usb_c"?v8o(e):dPe(t)?b8o(e,n.pinCount??0):e,i=Db({componentName:this.name,componentRotation:String(n.pcbRotation??0),footprinterString:`standard:${t}`,pinLabels:n.pinLabels,pcbPinLabels:n.pcbPinLabels},o),r=xDt(o);r&&(this._asyncFootprintCadModel=r),this.addAll(i),this._markDirty("InitializePortsFromChildren")}_getUsbCCanonicalLabelToPinNumberMap(){const t=new Map,e=this.selectAll("port");for(const n of e){const o=n.props.pinNumber;if(typeof o=="number")for(const i of n.getNameAndAliases()){const r=i.trim().toUpperCase();if(!D8o.has(r))continue;const s=r;t.has(s)||t.set(s,o)}}return t}_getSchematicPortArrangement(){const t=super._getSchematicPortArrangement();if(t&&Object.keys(t).length>0)return t;const e=this._getConnectorProps();if(dPe(e.standard))return{leftSize:0,rightSize:e.pinCount??0};if(e.standard!=="usb_c")return t;const n=this._getUsbCCanonicalLabelToPinNumberMap(),o=kDt.map(s=>n.get(s)).filter(s=>typeof s=="number"),i=FDt.map(s=>n.get(s)).filter(s=>typeof s=="number");if(o.length===0&&i.length===0)return t;const r={};return o.length>0&&(r.rightSide={pins:o,direction:"top-to-bottom"}),i.length>0&&(r.bottomSide={pins:i,direction:"left-to-right"}),r}_computeSchematicBoxDimensions(){if(this._getConnectorProps().standard!=="usb_c")return super._computeSchematicBoxDimensions();if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;const{_parsedProps:t}=this,e=this._getPrimaryPinCount(),n=.2,i={...this._getPinLabelsFromPorts()};if(t.pinLabels)for(const[c,l]of Object.entries(t.pinLabels))typeof l=="string"&&(i[c]=l);const r=this._getUsbCCanonicalLabelToPinNumberMap(),s={};for(const[c,l]of R8o){const u=r.get(c);typeof u=="number"&&(s[`pin${u}`]=l)}const a={...s,...t.schPinStyle??{}},A=this._getSchematicPortArrangement();return sPe({schWidth:t.schWidth,schHeight:t.schHeight,schPinSpacing:n,numericSchPinStyle:Kj(a,i),pinCount:e,schPortArrangement:A??void 0,pinLabels:i})}get config(){return{componentName:"Connector",zodProps:Dwn,shouldRenderAsSchematicBox:!0}}doInitialSourceRender(){const{db:t}=this.root,e=this._getConnectorProps(),n=e.manufacturerPartNumber??e.mfn,o=t.source_component.insert({ftype:"simple_connector",name:this.name,manufacturer_part_number:n,supplier_part_numbers:e.supplierPartNumbers,display_name:e.displayName,standard:e.standard,pin_count:e.pinCount});this.source_component_id=o.source_component_id,e.standard&&!n&&t.source_missing_manufacturer_part_number_warning.insert({source_component_id:this.source_component_id,standard:e.standard,subcircuit_id:this.getSubcircuit()?.subcircuit_id??void 0,warning_type:"source_missing_manufacturer_part_number_warning",message:`${this.getString()} has standard="${e.standard}" but no manufacturerPartNumber (mfn). Add mfn if you do not want the connector part to change in future.`})}_isUsingStandardPartsEngineCircuitJsonFlow(){return this._shouldUseStandardPartsEngineCircuitJsonFlow()?!!this.getInheritedProperty("partsEngine")?.fetchPartCircuitJson:!1}doInitialFetchPartFootprint(){const t=this._getConnectorProps(),e=t.standard;if(!e||!this._shouldUseStandardPartsEngineCircuitJsonFlow()||this._hasStartedFootprintUrlLoad)return;const n=this.getInheritedProperty("partsEngine");if(n&&!n.fetchPartCircuitJson){this._handleStandardConnectorCircuitJsonFailure(e,"partsEngine.fetchPartCircuitJson is not configured");return}const o=n?.fetchPartCircuitJson;if(!o)return;this._hasStartedFootprintUrlLoad=!0;const i={type:"source_component",ftype:"simple_connector",name:this.name,manufacturer_part_number:t.manufacturerPartNumber??t.mfn,standard:e,pin_count:t.pinCount};this._queueAsyncEffect("load-standard-connector-circuit-json",async()=>{const{db:r}=this.root;try{const s=await this._getSupplierPartNumbers(n,i,`standard:${e}`);this.source_component_id&&r.source_component.update(this.source_component_id,{supplier_part_numbers:s});const a=await this._fetchStandardConnectorCircuitJson(o,s,i.manufacturer_part_number);if(!a){this._handleStandardConnectorCircuitJsonFailure(e,"part circuit JSON was not found");return}this._addConnectorFootprintFromCircuitJson(e,a)}catch(s){this.source_component_id&&r.source_component.update(this.source_component_id,{supplier_part_numbers:{}}),this._handleStandardConnectorCircuitJsonFailure(e,s.message)}})}doInitialPartsEngineRender(){this._isUsingStandardPartsEngineCircuitJsonFlow()||super.doInitialPartsEngineRender()}updatePartsEngineRender(){this._isUsingStandardPartsEngineCircuitJsonFlow()||super.updatePartsEngineRender()}doInitialSchematicComponentRender(){if(super.doInitialSchematicComponentRender(),!this.root?.schematicDisabled&&this.schematic_component_id&&this._getConnectorProps().standard==="usb_c"){const t=Su.usbc;t&&P8o(this,t)}}doInitialPcbComponentSizeCalculation(){if(super.doInitialPcbComponentSizeCalculation(),this.root?.pcbDisabled||!this.pcb_component_id||!this.source_component_id)return;const{db:t}=this.root,e=DDt({circuitJson:t.toArray(),pcbComponentId:this.pcb_component_id,sourceComponentId:this.source_component_id});e&&t.pcb_component.update(this.pcb_component_id,{cable_insertion_center:{x:e.x,y:e.y}})}},T8o=t=>{const e=t?.port_arrangement;if(!e)return;if("left_size"in e)return{leftPinCount:e.left_size,rightPinCount:e.right_size,topPinCount:e.top_size,bottomPinCount:e.bottom_size};const n={};return e.left_side&&(n.leftSide={pins:e.left_side.pins,direction:e.left_side.direction??"top-to-bottom"}),e.right_side&&(n.rightSide={pins:e.right_side.pins,direction:e.right_side.direction??"top-to-bottom"}),e.top_side&&(n.topSide={pins:e.top_side.pins,direction:e.top_side.direction??"left-to-right"}),e.bottom_side&&(n.bottomSide={pins:e.bottom_side.pins,direction:e.bottom_side.direction??"left-to-right"}),n},k8o=(t,e)=>{const n=e.injectionDb.source_port.list().filter(i=>i.source_component_id===t.source_component_id),o={};for(const i of n){const r=i.pin_number;if(r==null)continue;const s=Array.from(new Set([i.name,...i.port_hints??[]].filter(a=>typeof a=="string"&&a.length>0)));s.length>0&&(o[`pin${r}`]=s)}if(Object.keys(o).length!==0)return o};function F8o(t,e){const{injectionDb:n,subcircuit:o,groupsMap:i}=e,r=n.pcb_component.getWhere({source_component_id:t.source_component_id}),s=n.schematic_component.getWhere({source_component_id:t.source_component_id}),a=n.cad_component.getWhere({source_component_id:t.source_component_id}),{pcbX:A,pcbY:c}=t4({pcbComponent:r,sourceGroupId:t.source_group_id,inflatorContext:e}),l={name:t.name,standard:t.standard,manufacturerPartNumber:t.manufacturer_part_number,supplierPartNumbers:t.supplier_part_numbers??void 0,pinLabels:k8o(t,e)??s?.port_labels??void 0,schPortArrangement:T8o(s),schWidth:s?.size?.width,schHeight:s?.size?.height,schPinSpacing:s?.pin_spacing,schX:s?.center?.x,schY:s?.center?.y,layer:r?.layer,pcbX:A,pcbY:c,pcbRotation:r?.rotation,doNotPlace:r?.do_not_place,obstructsWithinBounds:r?.obstructs_within_bounds},u=new LDt(l);if(a?.footprinter_string&&(Object.assign(u.props,{footprint:a.footprinter_string}),Object.assign(u._parsedProps,{footprint:a.footprinter_string})),r){const g=e4(r,{...e,normalComponent:u});g&&u.add(g)}t.source_group_id&&i?.has(t.source_group_id)?i.get(t.source_group_id).add(u):o.add(u)}var HDt=t=>typeof t=="string"&&!fO(t)&&!hw(t)&&!dw(t)&&!Vj(t),ODt=class extends g0{get config(){const t={schottky:"schottky_diode",avalanche:"avalanche_diode",zener:"zener_diode",photodiode:"photodiode"},e=this.props.schottky?"schottky":this.props.avalanche?"avalanche":this.props.zener?"zener":this.props.photo?"photodiode":null;return{schematicSymbolName:e?t[e]:this.props.symbolName??"diode",componentName:"Diode",zodProps:IMn,sourceFtype:"simple_diode"}}initPorts(){const t=this.children.some(i=>i.componentName==="Footprint"),e=this.resolveFootprint(),n=!!this._resolvePinLabels(),o=!n&&!t&&(!e||HDt(e));super.initPorts({pinCount:2,ignoreSymbolPorts:!n&&!o,additionalAliases:{pin1:o?["anode","pos","left"]:[],pin2:o?["cathode","neg","right"]:[]}})}doInitialSourceRender(){const{db:t}=this.root,{_parsedProps:e}=this,n=t.source_component.insert({ftype:"simple_diode",name:this.name,manufacturer_part_number:e.manufacturerPartNumber??e.mfn,supplier_part_numbers:e.supplierPartNumbers,are_pins_interchangeable:!1,display_name:e.displayName});this.source_component_id=n.source_component_id}getRefDesPrefixes(){return["D"]}get pos(){return this.portMap.pos}get anode(){return this.portMap.anode}get neg(){return this.portMap.neg}get cathode(){return this.portMap.cathode}},L8o=t=>Array.from(new Set([t?.name,...t?.port_hints??[]].filter(e=>typeof e=="string"&&e.length>0))),H8o=(t,e)=>{const n=e.injectionDb.source_port.list().filter(i=>i.source_component_id===t.source_component_id),o={};for(const i of n){if(i.pin_number===void 0||i.pin_number===null)continue;const r=L8o(i);r.length!==0&&(o[`pin${i.pin_number}`]=r)}return Object.keys(o).length>0?o:void 0};function O8o(t,e){const{injectionDb:n,subcircuit:o,groupsMap:i}=e,r=n.pcb_component.getWhere({source_component_id:t.source_component_id}),{pcbX:s,pcbY:a}=t4({pcbComponent:r,sourceGroupId:t.source_group_id,inflatorContext:e}),A=H8o(t,e),c={name:t.name,manufacturerPartNumber:t.manufacturer_part_number,supplierPartNumbers:t.supplier_part_numbers??void 0,pinLabels:A,layer:r?.layer,pcbX:s,pcbY:a,pcbRotation:r?.rotation,doNotPlace:r?.do_not_place,obstructsWithinBounds:r?.obstructs_within_bounds},l=new ODt(c);if(r){const u=e4(r,{...e,normalComponent:l});u&&l.add(u)}t.source_group_id&&i?.has(t.source_group_id)?i.get(t.source_group_id).add(l):o.add(l)}var G8o=class extends g0{get config(){return{componentName:"Fiducial",zodProps:llt,sourceFtype:"simple_fiducial"}}doInitialSchematicComponentRender(){}};function Y8o(t,e){const{injectionDb:n,subcircuit:o,groupsMap:i}=e,r=n.pcb_component.getWhere({source_component_id:t.source_component_id}),{pcbX:s,pcbY:a}=t4({pcbComponent:r,sourceGroupId:t.source_group_id,inflatorContext:e}),A=n.pcb_smtpad.list({pcb_component_id:r?.pcb_component_id}).find(u=>u.shape==="circle"),c=A&&"radius"in A?A.radius*2:"1mm",l=new G8o({name:t.name,padDiameter:c,layer:r?.layer,pcbX:s,pcbY:a,pcbRotation:r?.rotation,doNotPlace:r?.do_not_place,obstructsWithinBounds:r?.obstructs_within_bounds});if(r){const u=e4(r,{...e,normalComponent:l});u&&l.add(u)}t.source_group_id&&i?.has(t.source_group_id)?i.get(t.source_group_id).add(l):o.add(l)}function U8o(t,e){if(e.size===0)return t;const n=(t.traces??[]).filter(i=>e.has(i.pcb_trace_id));if(n.length===0)return t;const o=[];for(const i of n){const r=[i.connection_name??i.pcb_trace_id,...i.connectsTo??[]];for(const[s,a]of i.route.entries()){if(a.route_type==="via"){const g=WN(t.layerCount),h=g.findIndex(m=>m===a.from_layer),d=g.findIndex(m=>m===a.to_layer),p=a.via_diameter??t.minViaPadDiameter??t.minViaDiameter??.6;o.push({type:"rect",center:{x:a.x,y:a.y},width:p,height:p,layers:g.slice(Math.min(h,d),Math.max(h,d)+1),connectedTo:r})}const A=i.route[s+1];if(!A||a.route_type!=="wire"&&a.route_type!=="via"||A.route_type!=="wire"&&A.route_type!=="via")continue;const c=a.route_type==="wire"?a.width:A.route_type==="wire"?A.width:t.minTraceWidth,l=a.route_type==="wire"?a.layer:a.to_layer,u=a.x===A.x||a.y===A.y?1:Math.max(1,Math.ceil(Math.hypot(A.x-a.x,A.y-a.y)/c));for(let g=0;g<u;g++){const h=a.x+(A.x-a.x)*g/u,d=a.y+(A.y-a.y)*g/u,p=a.x+(A.x-a.x)*(g+1)/u,m=a.y+(A.y-a.y)*(g+1)/u;o.push({type:"rect",center:{x:(h+p)/2,y:(d+m)/2},width:Math.abs(p-h)+c,height:Math.abs(m-d)+c,layers:[l],connectedTo:r})}}}return{...t,traces:t.traces?.filter(i=>!e.has(i.pcb_trace_id)),obstacles:[...t.obstacles,...o]}}function K8o(t){const e=[...t.schematic_net_label.list(),...t.schematic_text.list().filter(a=>a.source_trace_id)];if(e.length===0)return;const n=Vf(t.toArray().filter(a=>a.type.startsWith("source_")));n.addConnections([...t.source_net.list().map(a=>[a.source_net_id]),...t.source_component_internal_connection.list().map(a=>a.source_port_ids)]);const o=e.map(a=>{const A=a.type==="schematic_net_label",c=a.source_trace_id??(A&&a.schematic_trace_id?t.schematic_trace.get(a.schematic_trace_id)?.source_trace_id:void 0),l=(A?n.getNetConnectedToId(a.source_net_id):void 0)??(c?n.getNetConnectedToId(c):void 0);return{label:a,network:l}}),i=new Map,r=(a,A)=>{if(!a.trim()||A===void 0)return;const c=i.get(a)??[];c.includes(A)||c.push(A),i.set(a,c)};for(const{label:a,network:A}of o)r(a.text,A);const s=a=>[...n.getIdsConnectedToNet(a)].sort()[0];for(const a of i.values())a.sort((A,c)=>s(A).localeCompare(s(c),"en",{numeric:!0}));for(const{label:a,network:A}of o){const c=i.get(a.text)??[],l=A!==void 0&&c.length>1?String(c.indexOf(A)+1):void 0;a.display_superscript!==l&&(a.type==="schematic_net_label"?t.schematic_net_label.update(a.schematic_net_label_id,{display_superscript:l}):t.schematic_text.update(a.schematic_text_id,{display_superscript:l}))}}var U0e=t=>typeof t=="object"&&t!==null&&"isAssemblyDeviceContainer"in t&&t.isAssemblyDeviceContainer===!0;function qN(t){const e=`${t.connectionName}:source-${t.sourcePointIndex}`;return{boundaryExitPointId:`fanout-exit:${e}`,planeExitPointId:`fanout-plane:${e}`,traceId:`fanout:${e}`,viaObstacleId:`fanout-via:${e}`,planeEndpointPointId:`fanout-plane-endpoint-point:${e}`,planeEndpointTraceId:`fanout-plane-endpoint:${e}`,planeEndpointViaObstacleId:`fanout-plane-endpoint-via:${e}`}}function V8o(t){return`fanout-completion:${t.connectionName}:source-${t.sourcePointIndex}:${t.candidateIndex}`}var Nb=1e-9;function K0e(t){return t.shape==="circle"}function Jj(t,e){const n=-(e.ccwRotationDegrees??0)*Math.PI/180,o=t.x-e.center.x,i=t.y-e.center.y;return{x:o*Math.cos(n)-i*Math.sin(n),y:o*Math.sin(n)+i*Math.cos(n)}}function tn(t,e){return Math.hypot(t.x-e.x,t.y-e.y)}function Cr(t,e,n){const o=n.x-e.x,i=n.y-e.y,r=o*o+i*i,s=r<Nb?0:((t.x-e.x)*o+(t.y-e.y)*i)/r,a=Math.max(0,Math.min(1,s));return Math.hypot(t.x-(e.x+a*o),t.y-(e.y+a*i))}function V0e(t,e,n){return(e.x-t.x)*(n.y-t.y)-(e.y-t.y)*(n.x-t.x)}function z8o(t,e,n,o){const i=V0e(n,o,t),r=V0e(n,o,e),s=V0e(t,e,n),a=V0e(t,e,o);return(i>0&&r<0||i<0&&r>0)&&(s>0&&a<0||s<0&&a>0)}function tu(t,e,n,o){return z8o(t,e,n,o)?0:Math.min(Cr(t,n,o),Cr(e,n,o),Cr(n,t,e),Cr(o,t,e))}function IO(t,e,n=Nb){if(K0e(e))return tn(t,e.center)<=e.width/2+n;const o=Jj(t,e);return Math.abs(o.x)<=e.width/2+n&&Math.abs(o.y)<=e.height/2+n}function z0e(t){const{center:e,diameter:n,obstacle:o,tolerance:i=Nb}=t,r=n/2;if(K0e(o))return tn(e,o.center)+r<=o.width/2+i;const s=Jj(e,o);return Math.abs(s.x)+r<=o.width/2+i&&Math.abs(s.y)+r<=o.height/2+i}function wx(t,e){if(K0e(e))return Math.max(0,tn(t,e.center)-e.width/2);const n=Jj(t,e),o=Math.max(Math.abs(n.x)-e.width/2,0),i=Math.max(Math.abs(n.y)-e.height/2,0);return Math.hypot(o,i)}function Tl(t,e){if(K0e(e))return Math.max(0,Cr(e.center,t.start,t.end)-e.width/2);const n=Jj(t.start,e),o=Jj(t.end,e);if(Math.abs(n.x)<=e.width/2+Nb&&Math.abs(n.y)<=e.height/2+Nb||Math.abs(o.x)<=e.width/2+Nb&&Math.abs(o.y)<=e.height/2+Nb)return 0;const i=-e.width/2,r=e.width/2,s=-e.height/2,a=e.height/2,A=[{x:i,y:s},{x:r,y:s},{x:r,y:a},{x:i,y:a}];let c=Number.POSITIVE_INFINITY;for(let l=0;l<A.length;l++)c=Math.min(c,tu(n,o,A[l],A[(l+1)%A.length]));return c}function Zm(t,e,n){if(t.layer!==e.layer)return!0;const o=(t.width+e.width)/2+n,i=o+Nb;return Math.min(t.start.x,t.end.x)-Math.max(e.start.x,e.end.x)>i||Math.min(e.start.x,e.end.x)-Math.max(t.start.x,t.end.x)>i||Math.min(t.start.y,t.end.y)-Math.max(e.start.y,e.end.y)>i||Math.min(e.start.y,e.end.y)-Math.max(t.start.y,t.end.y)>i?!0:tu(t.start,t.end,e.start,e.end)>=o-Nb}var GDt=new WeakMap;function YDt(t){return t.netConnectionName??t.rootConnectionName??t.name}function XN(t,e,n){if(!e)return!1;const o=t.get(e)??new Set,i=o.size;return o.add(n),t.set(e,o),o.size!==i}function hPe(t,e){const n=new Set;for(const o of e)for(const i of t.get(o)??[])n.add(i);return n}function J8o(t){const e=new Map,n=new Map;for(const a of t.connections){const A=YDt(a);e.set(a.name,A),XN(n,a.name,A),XN(n,a.rootConnectionName,A),XN(n,a.netConnectionName,A);for(const c of a.pointsToConnect)XN(n,c.pointId,A),XN(n,c.pcb_port_id,A)}for(const a of t.traces??[]){const A=[a.connection_name,a.pcb_trace_id,...a.connectsTo??[]],c=hPe(n,A);if(c.size!==1)continue;const l=[...c][0];e.set(a.connection_name,l);for(const u of A)XN(n,u,l)}for(let a=0;a<2;a++){let A=!1;for(const c of t.obstacles){const l=hPe(n,c.connectedTo);if(l.size!==1)continue;const u=[...l][0];for(const g of c.connectedTo)A=XN(n,g,u)||A}if(!A)break}const o=new Map,i=a=>{const A=o.get(a)??a;if(o.set(a,A),A===a)return a;const c=i(A);return o.set(a,c),c},r=(a,A)=>{const c=i(a),l=i(A);c!==l&&o.set(l,c)};for(const a of n.values()){const[A,...c]=[...a];if(A)for(const l of c)r(A,l)}for(const a of[...t.obstacles.map(A=>A.connectedTo),...(t.traces??[]).map(A=>A.connectsTo??[])]){const[A,...c]=[...hPe(n,a)];if(A)for(const l of c)r(A,l)}for(const[a,A]of e)e.set(a,i(A));const s=new Map;for(const[a,A]of n){const c=A.values().next().value;c!==void 0&&s.set(a,i(c))}return{connectionNetKeys:e,tokenNetKeys:s}}function UDt(t){const e=GDt.get(t);if(e)return e;const n=J8o(t);return GDt.set(t,n),n}function Px(t,e,n){const o=UDt(t),i=o.connectionNetKeys.get(e),r=o.connectionNetKeys.get(n);return i!==void 0&&i===r}function n4(t,e,n){const o=UDt(t),i=o.connectionNetKeys.get(n);if(!i)return!1;for(const r of e.connectedTo)if(o.tokenNetKeys.get(r)===i)return!0;return!1}function Rb(t){if(!Number.isInteger(t)||t<1)throw new Error(`FanoutSolver: layerCount must be a positive integer, received ${t}`);return t===1?["top"]:t===2?["top","bottom"]:["top",...Array.from({length:t-2},(e,n)=>`inner${n+1}`),"bottom"]}function KDt(t,e,n){const o=n.indexOf(t),i=n.indexOf(e);if(o<0||i<0)throw new Error(`FanoutSolver: cannot build via span from "${t}" to "${e}"`);const r=Math.min(o,i),s=Math.max(o,i);return n.slice(r,s+1)}function Mx(t){const{fromLayer:e,toLayer:n,layerNames:o,allowBlindAndBuriedVias:i}=t,r=KDt(e,n,o);return i?r:[...o]}function VDt(t){const{fromLayer:e,toLayer:n,layers:o,layerNames:i,allowBlindAndBuriedVias:r}=t,s=Mx({fromLayer:e,toLayer:n,layerNames:i,allowBlindAndBuriedVias:r});if(!o)return s;if(o.length===0||!o.includes(e)||!o.includes(n)||o.some(a=>!i.includes(a)))throw new Error(`FanoutSolver: route via from "${e}" to "${n}" has an invalid physical layer span`);return[...o]}function W8o(t){const{busIds:e,layers:n,layersByBusId:o,maxAssignments:i}=t;if(n.length===0)throw new Error("FanoutSolver: no escape layers are available");if(!Number.isInteger(i)||i<1)throw new Error(`FanoutSolver: maxLayerCombinations must be positive, received ${i}`);const r=e.map(p=>o?.[p]??n),s=r.findIndex(p=>p.length===0);if(s>=0)throw new Error(`FanoutSolver: no escape layers are available for bus "${e[s]}"`);const a=r.reduce((p,m)=>p*m.length,1),A=Math.min(i,Number.isFinite(a)?a:i),c=[],l=new Set;function u(p){const m={};for(let f=0;f<e.length;f++)m[e[f]]=r[f][p[f]];const _=JSON.stringify(m);l.has(_)||(l.add(_),c.push(m))}if(a<=i){for(let p=0;p<A;p++){const m=[];let _=p;for(let f=0;f<e.length;f++){const I=r[f].length,C=_%I;_=Math.floor(_/I),m.push((C+f)%I)}u(m)}return c}function g(p){let m=p|0;return m=Math.imul(m^m>>>16,569420461),m=Math.imul(m^m>>>15,1935289751),(m^m>>>15)>>>0}const h=e.map((p,m)=>m%r[m].length);u(h);const d=Math.max(...r.map(p=>p.length));for(let p=1;p<d&&c.length<A;p++)u(h.map((m,_)=>(m+p)%r[_].length));for(let p=0;p<e.length&&c.length<A;p++)for(let m=1;m<r[p].length&&c.length<A;m++){const _=[...h];_[p]=(h[p]+m)%r[p].length,u(_)}for(let p=1;c.length<A&&p<A*20;p++)u(e.map((m,_)=>g(p*2654435761+_*2246822507)%r[_].length));return c}var q7=1e-6;function j8o(t){return"layer"in t?[t.layer]:t.layers}function Wj(t,e){return t.some(n=>e.includes(n))}function $8o(t,e){const n=[];let o;for(const i of t.route){if(i.route_type==="via"){n.push({type:"via",center:{x:i.x,y:i.y},diameter:i.via_diameter??0,layers:KDt(i.from_layer,i.to_layer,e)}),o=void 0;continue}i.route_type==="wire"&&(o&&o.layer===i.layer&&tn(o,i)>q7&&n.push({type:"segment",segment:{start:{x:o.x,y:o.y},end:{x:i.x,y:i.y},width:i.width,layer:i.layer}}),o=i)}return n}function Tb(t,e){return t.type==="plane"&&e.type==="plane"?t.layer===e.layer:t.type==="plane"&&e.type==="via"?e.layers.includes(t.layer):t.type==="via"&&e.type==="plane"?Tb(e,t):t.type==="plane"&&e.type==="segment"?t.layer===e.segment.layer:t.type==="segment"&&e.type==="plane"?Tb(e,t):t.type==="endpoint"&&e.type==="endpoint"?Wj(t.layers,e.layers)&&tn(t.point,e.point)<=q7:t.type==="endpoint"&&e.type==="obstacle"?Wj(t.layers,e.obstacle.layers)&&IO(t.point,e.obstacle,q7):t.type==="obstacle"&&e.type==="endpoint"?Tb(e,t):t.type==="endpoint"&&e.type==="segment"?t.layers.includes(e.segment.layer)&&Cr(t.point,e.segment.start,e.segment.end)<=e.segment.width/2+q7:t.type==="segment"&&e.type==="endpoint"?Tb(e,t):t.type==="endpoint"&&e.type==="via"?Wj(t.layers,e.layers)&&tn(t.point,e.center)<=e.diameter/2+q7:t.type==="via"&&e.type==="endpoint"?Tb(e,t):t.type==="obstacle"&&e.type==="segment"?t.obstacle.layers.includes(e.segment.layer)&&Tl(e.segment,t.obstacle)<=e.segment.width/2+q7:t.type==="segment"&&e.type==="obstacle"?Tb(e,t):t.type==="obstacle"&&e.type==="via"?Wj(t.obstacle.layers,e.layers)&&wx(e.center,t.obstacle)<=e.diameter/2+q7:t.type==="via"&&e.type==="obstacle"?Tb(e,t):t.type==="segment"&&e.type==="segment"?t.segment.layer===e.segment.layer&&tu(t.segment.start,t.segment.end,e.segment.start,e.segment.end)<=(t.segment.width+e.segment.width)/2+q7:t.type==="segment"&&e.type==="via"?e.layers.includes(t.segment.layer)&&Cr(e.center,t.segment.start,t.segment.end)<=e.diameter/2+t.segment.width/2+q7:t.type==="via"&&e.type==="segment"?Tb(e,t):t.type==="via"&&e.type==="via"?Wj(t.layers,e.layers)&&tn(t.center,e.center)<=(t.diameter+e.diameter)/2+q7:!1}var q8o=class{parent;constructor(e){this.parent=Array.from({length:e},(n,o)=>o)}find(e){const n=this.parent[e];if(n===e)return e;const o=this.find(n);return this.parent[e]=o,o}union(e,n){const o=this.find(e),i=this.find(n);o!==i&&(this.parent[i]=o)}};function X8o(t,e,n){return!!(e.connection_name&&Px(t,e.connection_name,n.name))}function o4(t){const{inputSrj:e,routedSrj:n}=t,o=n.fanoutPlaneConnectivity,i=Rb(n.layerCount),r=new Map;for(const l of e.connections){const u=YDt(l),g=r.get(u)??[];g.push(l),r.set(u,g)}const s=[];let a=0,A=0;for(const l of r.values()){const u=l[0],g=l.flatMap(I=>I.pointsToConnect.map((C,y)=>({type:"endpoint",connectionName:I.name,endpointIndex:y,point:C,layers:j8o(C)}))),h=e.obstacles.filter(I=>n4(e,I,u.name)).map(I=>({type:"obstacle",obstacle:I})),d=(n.traces??[]).filter(I=>X8o(e,I,u)).flatMap(I=>$8o(I,i)),p=[...new Set((o??[]).flatMap(I=>Px(e,I.connectionName,u.name)?[I.layer]:[]))].map(I=>({type:"plane",layer:I})),m=[...g,...h,...d,...p],_=new q8o(m.length);for(let I=0;I<m.length;I++)for(let C=I+1;C<m.length;C++)Tb(m[I],m[C])&&_.union(I,C);const f=new Map;for(let I=0;I<g.length;I++){const C=g[I],y=f.get(C.connectionName)??[];y[C.endpointIndex]=I,f.set(C.connectionName,y)}for(const I of l){const C=f.get(I.name)??[],y=C[0],x=y===void 0?void 0:_.find(y),E=C.flatMap((B,S)=>x===void 0||_.find(B)!==x?[S]:[]);A+=C.length-E.length,E.length===0?a++:s.push({code:"original-endpoints-disconnected",connectionName:I.name,disconnectedEndpointIndices:E,message:`Connection ${I.name} has no physical copper path from endpoint 0 to original endpoint${E.length===1?"":"s"} ${E.join(", ")}`})}}const c=e.connections.reduce((l,u)=>l+u.pointsToConnect.length,0);return{valid:s.length===0,checkedConnectionCount:e.connections.length,connectedConnectionCount:a,checkedEndpointCount:c,connectedEndpointCount:A,issues:s}}var X7=1e-6;function jj(t){const{inputSrj:e,segment:n,bodyObstacle:o,connectionName:i}=t;if(o.connectedTo.length>0||!o.componentId)return!1;const r=e.obstacles.filter(s=>s.componentId===o.componentId&&s.layers.includes(n.layer)&&n4(e,s,i));for(const s of r)for(const[a,A]of[[n.start,n.end],[n.end,n.start]]){if(!IO(a,s,X7))continue;const c={x:a.x-o.center.x,y:a.y-o.center.y},l={x:A.x-a.x,y:A.y-a.y};if(c.x*l.x+c.y*l.y>X7)return!0}return!1}function pPe(t,e){return tn(t,e)<=X7}function sE(t,e){t.push(e)}function Z8o(t){const{srj:e,trace:n,connectionName:o,layerNames:i,allowBlindAndBuriedVias:r,issues:s}=t,a=[],A=[];let c,l;for(const u of n.route){if(u.route_type==="via"){const g=VDt({fromLayer:u.from_layer,toLayer:u.to_layer,layers:"layers"in u&&Array.isArray(u.layers)?u.layers:void 0,layerNames:i,allowBlindAndBuriedVias:r});A.push({center:{x:u.x,y:u.y},diameter:u.via_diameter??e.minViaPadDiameter??e.minTraceWidth,spanLayers:g}),(!c||!pPe(c,u)||c.layer!==u.from_layer)&&sE(s,{code:"disconnected-trace",traceId:n.pcb_trace_id,connectionName:o,message:`Trace ${n.pcb_trace_id} reaches a via without a matching ${u.from_layer} wire endpoint`}),l=u;continue}if(u.route_type!=="wire"){sE(s,{code:"unsupported-route-point",traceId:n.pcb_trace_id,connectionName:o,message:`Trace ${n.pcb_trace_id} contains unsupported ${u.route_type} geometry`}),c=void 0,l=void 0;continue}if(l){(!pPe(u,l)||u.layer!==l.to_layer)&&sE(s,{code:"disconnected-trace",traceId:n.pcb_trace_id,connectionName:o,message:`Trace ${n.pcb_trace_id} does not continue from its via on ${l.to_layer}`}),c=u,l=void 0;continue}c&&(c.layer!==u.layer?sE(s,{code:"disconnected-trace",traceId:n.pcb_trace_id,connectionName:o,message:`Trace ${n.pcb_trace_id} changes from ${c.layer} to ${u.layer} without a via`}):pPe(c,u)||a.push({start:{x:c.x,y:c.y},end:{x:u.x,y:u.y},width:u.width,layer:u.layer})),c=u}return l&&sE(s,{code:"disconnected-trace",traceId:n.pcb_trace_id,connectionName:o,message:`Trace ${n.pcb_trace_id} ends at a via without a wire on ${l.to_layer}`}),{trace:n,connectionName:o,segments:a,vias:A}}function qu(t){const{inputSrj:e,routedSrj:n,clearance:o,allowBlindAndBuriedVias:i=!0}=t,r=[],s=Rb(n.layerCount),a=[],A=[e,n].flatMap(c=>c.connections.flatMap(l=>l.pointsToConnect.map(u=>({connectionName:l.name,point:u}))));for(const c of n.traces??[]){const l=c.connection_name;if(!l||!e.connections.some(u=>u.name===l)){sE(r,{code:"unknown-trace-connection",traceId:c.pcb_trace_id,...l?{connectionName:l}:{},message:`Trace ${c.pcb_trace_id} does not identify an input connection`});continue}a.push(Z8o({srj:n,trace:c,connectionName:l,layerNames:s,allowBlindAndBuriedVias:i,issues:r}))}for(const c of a){const l=new Set(e.obstacles.filter(g=>n4(e,g,c.connectionName))),u=e.obstacles.filter(g=>!l.has(g));for(const g of c.segments)for(const h of u){if(!h.layers.includes(g.layer)||jj({inputSrj:e,segment:g,bodyObstacle:h,connectionName:c.connectionName}))continue;const d=Tl(g,h),p=g.width/2+o;d<p-X7&&sE(r,{code:"trace-obstacle-clearance",traceId:c.trace.pcb_trace_id,connectionName:c.connectionName,layer:g.layer,obstacleId:h.obstacleId,message:`Trace ${c.trace.pcb_trace_id} on ${g.layer} is ${d.toFixed(4)}mm from different-net obstacle ${h.obstacleId}; ${p.toFixed(4)}mm is required`})}for(const g of c.vias){const h=A.find(({point:p})=>tn(g.center,p)<=X7),d=e.allowViaInPad===!0&&e.obstacles.some(p=>p.layers.some(m=>g.spanLayers.includes(m))&&l.has(p)&&z0e({center:g.center,diameter:g.diameter,obstacle:p,tolerance:X7}));h&&!d&&sE(r,{code:"via-at-endpoint",traceId:c.trace.pcb_trace_id,connectionName:c.connectionName,otherConnectionName:h.connectionName,message:`Via in ${c.trace.pcb_trace_id} is placed directly at an original or routed connection endpoint`});for(const p of u){if(!p.layers.some(f=>g.spanLayers.includes(f)))continue;const m=wx(g.center,p),_=g.diameter/2+o;m<_-X7&&sE(r,{code:"via-obstacle-clearance",traceId:c.trace.pcb_trace_id,connectionName:c.connectionName,obstacleId:p.obstacleId,message:`Via in ${c.trace.pcb_trace_id} is ${m.toFixed(4)}mm from different-net obstacle ${p.obstacleId} on its layer span; ${_.toFixed(4)}mm is required`})}}}for(let c=0;c<a.length;c++){const l=a[c];for(let u=c+1;u<a.length;u++){const g=a[u];if(!Px(e,l.connectionName,g.connectionName)){for(const h of l.segments){for(const d of g.segments)Zm(h,d,o)||sE(r,{code:"different-net-trace-clearance",traceId:l.trace.pcb_trace_id,connectionName:l.connectionName,otherTraceId:g.trace.pcb_trace_id,otherConnectionName:g.connectionName,layer:h.layer,message:`Different-net traces ${l.trace.pcb_trace_id} and ${g.trace.pcb_trace_id} intersect or violate clearance on ${h.layer}`});for(const d of g.vias)!d.spanLayers.includes(h.layer)||Cr(d.center,h.start,h.end)>=d.diameter/2+h.width/2+o-X7||sE(r,{code:"different-net-trace-via-clearance",traceId:l.trace.pcb_trace_id,connectionName:l.connectionName,otherTraceId:g.trace.pcb_trace_id,otherConnectionName:g.connectionName,layer:h.layer,message:`Trace ${l.trace.pcb_trace_id} violates via clearance to ${g.trace.pcb_trace_id} on ${h.layer}`})}for(const h of l.vias){for(const d of g.segments)!h.spanLayers.includes(d.layer)||Cr(h.center,d.start,d.end)>=h.diameter/2+d.width/2+o-X7||sE(r,{code:"different-net-trace-via-clearance",traceId:l.trace.pcb_trace_id,connectionName:l.connectionName,otherTraceId:g.trace.pcb_trace_id,otherConnectionName:g.connectionName,layer:d.layer,message:`Via in ${l.trace.pcb_trace_id} violates trace clearance to ${g.trace.pcb_trace_id} on ${d.layer}`});for(const d of g.vias)!h.spanLayers.some(p=>d.spanLayers.includes(p))||tn(h.center,d.center)>=(h.diameter+d.diameter)/2+o-X7||sE(r,{code:"different-net-via-clearance",traceId:l.trace.pcb_trace_id,connectionName:l.connectionName,otherTraceId:g.trace.pcb_trace_id,otherConnectionName:g.connectionName,message:`Different-net vias in ${l.trace.pcb_trace_id} and ${g.trace.pcb_trace_id} violate clearance on an overlapping layer span`})}}}}return{valid:r.length===0,checkedTraceCount:n.traces?.length??0,checkedSegmentCount:a.reduce((c,l)=>c+l.segments.length,0),checkedViaCount:a.reduce((c,l)=>c+l.vias.length,0),issues:r}}var mPe=1e-9;function $j(t,e){if("layer"in t)return t.layer;const n=t.layers[0];if(!n)throw new Error("Endpoint completion received a layerless point");return n}function zDt(t){const e=[];for(const n of t)e.at(-1)&&tn(e.at(-1),n)<mPe||e.push(n);return e}function JDt(t,e){const n=zDt(t);if(n.length<3)return n;const o=[n[0]];for(let i=1;i<n.length-1;i++){const r=n[i-1],s=n[i],a=n[i+1],A=tn(r,s),c=tn(s,a),l={x:(s.x-r.x)/A,y:(s.y-r.y)/A},u={x:(a.x-s.x)/c,y:(a.y-s.y)/c};if(Math.abs(l.x*u.x+l.y*u.y)>1e-6){o.push(s);continue}const g=Math.min(e,A/2,c/2);o.push({x:s.x-l.x*g,y:s.y-l.y*g}),o.push({x:s.x+u.x*g,y:s.y+u.y*g})}return o.push(n.at(-1)),zDt(o)}function ebo(t){const{inputSrj:e,connectionName:n,target:o,targetLayer:i}=t;return e.obstacles.find(r=>r.layers.includes(i)&&n4(e,r,n)&&IO(o,r,1e-6))}function tbo(t){const{inputSrj:e,plan:n}=t,o=$j(n.targetPoint),i=ebo({inputSrj:e,connectionName:n.connectionName,target:n.targetPoint,targetLayer:o}),r=e.obstacles.find(c=>c.componentId===i?.componentId&&c.connectedTo.length===0),s=r?{x:n.targetPoint.x-r.center.x,y:n.targetPoint.y-r.center.y}:{x:n.targetPoint.x-n.sourcePoint.x,y:n.targetPoint.y-n.sourcePoint.y},a=Math.hypot(s.x,s.y),A=a>mPe?{x:s.x/a,y:s.y/a}:{x:1,y:0};return{outward:A,perpendicular:{x:-A.y,y:A.x}}}function WDt(t){const{plan:e,branchStart:n,viaPoint:o,assignedLayerPath:i,terminalApproach:r,traceWidth:s,viaDiameter:a,viaHoleDiameter:A,candidateIndex:c,chamfer:l}=t,u=$j(e.targetPoint),g=JDt(i,l),h=JDt([o,...r?[r]:[],e.targetPoint],l),d=g.map(p=>({route_type:"wire",x:p.x,y:p.y,width:s,layer:n.layer}));n.layer!==u&&(d.push({route_type:"via",x:o.x,y:o.y,from_layer:n.layer,to_layer:u,via_diameter:a,via_hole_diameter:A}),d.push({route_type:"wire",x:o.x,y:o.y,width:s,layer:u}));for(const p of h.slice(1))d.push({route_type:"wire",x:p.x,y:p.y,width:s,layer:u});return{type:"pcb_trace",pcb_trace_id:V8o({connectionName:e.connectionName,sourcePointIndex:e.sourcePointIndex,candidateIndex:c}),connection_name:e.connectionName,route:d}}function ZN(t,e){return!t.issues.some(n=>n.connectionName===e)}function _Pe(t){const{trace:e,endpointSrjs:n}=t,o=n.flatMap(i=>i.connections.flatMap(r=>r.pointsToConnect));return e.route.some(i=>i.route_type==="via"&&o.some(r=>tn(i,r)<=1e-6))}function nbo(t){const{inputSrj:e,fanoutSrj:n,plan:o,acceptedTraces:i,traceWidth:r,viaDiameter:s,viaHoleDiameter:a,clearance:A,allowBlindAndBuriedVias:c}=t,{outward:l,perpendicular:u}=tbo({inputSrj:e,plan:o}),g=[...o.via?[{x:o.via.center.x,y:o.via.center.y,layer:o.targetLayer}]:[],{x:o.sourcePoint.x,y:o.sourcePoint.y,layer:o.sourceLayer}];let h=[],d=Number.POSITIVE_INFINITY,p=0;const m=e.connections.length>32?600:Number.POSITIVE_INFINITY,_=o.termination.type==="plane"?$Dt({trace:o.trace,endpoint:o.exitPoint,layer:o.sourceLayer,distances:[.2,.3,.4]}):[],f=[...o.termination.type==="plane"&&o.via?[{...o.via.center}]:[],..._,...[.4,.8,1.2,1.6].flatMap(I=>[0,.4,-.4,.8,-.8,1.2,-1.2,1.6,-1.6].map(C=>({x:o.sourcePoint.x+l.x*I+u.x*C,y:o.sourcePoint.y+l.y*I+u.y*C})))];for(const I of f){const C=[...o.termination.type==="plane"?[{...I,layer:o.targetLayer}]:[],...g,..._.flatMap(y=>tn(y,I)<=1e-6?[{...y,layer:o.sourceLayer}]:[])];for(const y of C){const x=tn(y,I)<=1e-6?[[y]]:[[y,I],[y,{x:I.x,y:y.y},I],[y,{x:y.x,y:I.y},I],...[.4,-.4].map(E=>[y,{x:y.x+E,y:y.y},{x:y.x+E,y:I.y},I])];for(const E of x){const B=[void 0,...[.4,.8].map(S=>({x:o.targetPoint.x+l.x*S,y:o.targetPoint.y+l.y*S})),...[.4,-.4].map(S=>({x:o.targetPoint.x+l.x*.4+u.x*S,y:o.targetPoint.y+l.y*.4+u.y*S}))];for(const S of B){if(p>=m)return{blockingConnectionNames:h};const Q=WDt({plan:o,branchStart:y,viaPoint:I,assignedLayerPath:E,terminalApproach:S,traceWidth:r,viaDiameter:s,viaHoleDiameter:a,candidateIndex:p++,chamfer:0});if(_Pe({trace:Q,endpointSrjs:[e,n]}))continue;const w={...n,traces:[...n.traces??[],...i,Q]},M=qu({inputSrj:e,routedSrj:w,clearance:A,allowBlindAndBuriedVias:c});if(!M.valid){M.issues.length<d&&(d=M.issues.length,h=[...new Set(M.issues.flatMap(R=>[R.connectionName,R.otherConnectionName].flatMap(F=>F&&F!==o.connectionName?[F]:[])))]);continue}const k=o4({inputSrj:e,routedSrj:w});if(ZN(k,o.connectionName))return{trace:Q,blockingConnectionNames:[]}}}}}return{blockingConnectionNames:h}}function obo(t){const{inputSrj:e,fanoutSrj:n,plans:o,traceWidth:i,viaDiameter:r,viaHoleDiameter:s,clearance:a,allowBlindAndBuriedVias:A}=t,c=[],l=[],u=new Set;for(const h of o){const d=nbo({inputSrj:e,fanoutSrj:n,plan:h,acceptedTraces:c,traceWidth:i,viaDiameter:r,viaHoleDiameter:s,clearance:a,allowBlindAndBuriedVias:A});if(d.trace)c.push(d.trace);else{l.push(h.connectionName);for(const p of d.blockingConnectionNames)u.add(p)}}const g={...n,traces:[...n.traces??[],...c]};return{traces:c,failedConnectionNames:l,blockingConnectionNames:[...u],connectivity:o4({inputSrj:e,routedSrj:g}),drc:qu({inputSrj:e,routedSrj:g,clearance:a,allowBlindAndBuriedVias:A})}}function jDt(t){let e=0,n;for(const o of t.route){if(o.route_type!=="wire"){n=void 0;continue}n?.layer===o.layer&&(e+=tn(n,o)),n=o}return e}function ibo(t){const{fanoutSrj:e,completionTraces:n}=t,o=new Map(n.flatMap(r=>{const s=r.route.find(a=>a.route_type==="wire");return s?[[r.connection_name,{x:s.x,y:s.y,layer:s.layer}]]:[]})),i=(e.traces??[]).map(r=>{if(!r.pcb_trace_id.startsWith("fanout:"))return r;const s=o.get(r.connection_name);if(!s)return r;let a;for(let A=0;A<r.route.length;A++){const c=r.route[A];if(c?.route_type!=="wire"){a=void 0;continue}if(a!==void 0){const l=r.route[a];if(l?.route_type==="wire"&&l.layer===s.layer&&c.layer===s.layer&&Cr(s,l,c)<=1e-6){const u=r.route.slice(0,a+1);return tn(l,s)>1e-6&&u.push({route_type:"wire",x:s.x,y:s.y,width:c.width,layer:s.layer}),{...r,route:u}}}a=A}return r});return{...e,traces:i}}function rbo(t){const{inputSrj:e,fanoutSrj:n,localTraces:o,candidates:i,clearance:r,allowBlindAndBuriedVias:s}=t,a=[...n.traces??[],...o],A={...n,traces:a},c=o4({inputSrj:e,routedSrj:A}),u=i.filter(d=>d.route.length>1&&d.route.every(p=>p.route_type==="wire"||p.route_type==="via")&&!_Pe({trace:d,endpointSrjs:[e,n]})).filter(d=>{const p=o4({inputSrj:e,routedSrj:{...n,traces:[...a,d]}});return p.connectedConnectionCount>c.connectedConnectionCount&&ZN(p,d.connection_name)}),g={...n,traces:[...a,...u]};if(qu({inputSrj:e,routedSrj:g,clearance:r,allowBlindAndBuriedVias:s}).valid)return u;const h=[];for(const d of u.toSorted((p,m)=>jDt(p)-jDt(m))){const p={...n,traces:[...a,...h,d]};if(!qu({inputSrj:e,routedSrj:p,clearance:r,allowBlindAndBuriedVias:s}).valid)continue;const _=o4({inputSrj:e,routedSrj:{...n,traces:[...a,...h]}}),f=o4({inputSrj:e,routedSrj:p});f.connectedConnectionCount>_.connectedConnectionCount&&ZN(f,d.connection_name)&&h.push(d)}return h}function $Dt(t){const{trace:e,endpoint:n,layer:o,distances:i}=t,r=e.route.findLastIndex(s=>s.route_type==="wire"&&s.layer===o&&tn(s,n)<=1e-6);return r<0?[]:i.flatMap(s=>{let a=s,A=n;for(let c=r-1;c>=0;c--){const l=e.route[c];if(l?.route_type!=="wire"||l.layer!==o)break;const u=tn(A,l);if(!(u<=mPe)){if(a<u-1e-6)return[{x:A.x+(l.x-A.x)*a/u,y:A.y+(l.y-A.y)*a/u}];a-=u,A=l}}return[]})}function qDt(t){const{inputSrj:e,fanoutSrj:n,plan:o,acceptedTraces:i,traceWidth:r,viaDiameter:s,viaHoleDiameter:a,clearance:A,allowBlindAndBuriedVias:c}=t,l={x:o.exitPoint.x,y:o.exitPoint.y,layer:o.targetLayer},u=o.targetPoint,g=$j(u);let h=0;const d=m=>{const _=WDt({plan:o,branchStart:m.start,viaPoint:m.viaPoint,assignedLayerPath:[m.start,m.viaPoint],terminalApproach:m.terminalApproach,traceWidth:r,viaDiameter:s,viaHoleDiameter:a,candidateIndex:1e4+h++,chamfer:Math.max(r,.1)});if(_Pe({trace:_,endpointSrjs:[e,n]}))return;const f={...n,traces:[...n.traces??[],...i,_]};if(qu({inputSrj:e,routedSrj:f,clearance:A,allowBlindAndBuriedVias:c}).valid&&ZN(o4({inputSrj:e,routedSrj:f}),o.connectionName))return _};if(l.layer!==g){const m=$Dt({trace:o.trace,endpoint:o.exitPoint,layer:o.targetLayer,distances:[.4,.8,1.2,1.6]});for(const _ of m){const f={..._,layer:o.targetLayer};for(const I of[void 0,{x:u.x,y:_.y},{x:_.x,y:u.y}]){const C=d({start:f,viaPoint:_,terminalApproach:I});if(C)return C}}}const p=[[u],[{x:u.x,y:l.y},u],[{x:l.x,y:u.y},u]];for(const m of p){const _=m[0],f=tn(l,_),I=l.layer===g?[0]:[.4,.8,1.2,1.6];for(const C of I){if(l.layer!==g&&(f<=C+.2||C<=1e-6))continue;const y=l.layer===g?{x:l.x,y:l.y}:{x:l.x+(_.x-l.x)*C/f,y:l.y+(_.y-l.y)*C/f},x=d({start:l,viaPoint:y,terminalApproach:m.length>1?_:void 0});if(x)return x}}}function sbo(t){const{inputSrj:e,fanoutSrj:n,plans:o,traceWidth:i,viaDiameter:r,viaHoleDiameter:s,clearance:a,allowBlindAndBuriedVias:A=!0,effort:c=1,routeDownstreamConnections:l}=t,u=[],g=qu({inputSrj:e,routedSrj:n,clearance:a,allowBlindAndBuriedVias:A}),h=o4({inputSrj:e,routedSrj:n}),d=o.filter(k=>{const R=$j(k.sourcePoint),F=$j(k.targetPoint);return R!==F&&tn(k.sourcePoint,k.targetPoint)<=.25&&!ZN(h,k.connectionName)});let p={traces:[],failedConnectionNames:d.map(k=>k.connectionName),blockingConnectionNames:[],connectivity:h,drc:g},m=0;if(!g.valid)u.push("Fanout prefix failed emitted-copper DRC; skipped completion");else{let k=[];const R=new Map(d.map((O,U)=>[O.connectionName,U])),F=e.connections.length>32?1:3;for(let O=0;O<F;O++){const U=new Map(k.map((te,j)=>[te,j])),Y=d.toSorted((te,j)=>(U.get(te.connectionName)??Number.MAX_SAFE_INTEGER)-(U.get(j.connectionName)??Number.MAX_SAFE_INTEGER)||(R.get(te.connectionName)??0)-(R.get(j.connectionName)??0)),W=obo({inputSrj:e,fanoutSrj:n,plans:Y,traceWidth:i,viaDiameter:r,viaHoleDiameter:s,clearance:a,allowBlindAndBuriedVias:A});if(m++,W.drc.valid&&(W.connectivity.connectedConnectionCount>p.connectivity.connectedConnectionCount||W.connectivity.connectedConnectionCount===p.connectivity.connectedConnectionCount&&W.traces.length<p.traces.length)&&(p=W),k=[...new Set([...W.failedConnectionNames,...W.blockingConnectionNames,...k])],W.failedConnectionNames.length===0)break}}const _=new Set(d.map(k=>k.connectionName)),f=o.filter(k=>!_.has(k.connectionName)&&!ZN(h,k.connectionName)),I=[];if(g.valid)for(const k of f){const R=qDt({inputSrj:e,fanoutSrj:n,plan:k,acceptedTraces:[...p.traces,...I],traceWidth:i,viaDiameter:r,viaHoleDiameter:s,clearance:a,allowBlindAndBuriedVias:A});R&&I.push(R)}const C={...n,traces:[...n.traces??[],...p.traces,...I]},y=new Set(o4({inputSrj:e,routedSrj:C}).issues.map(k=>k.connectionName)),x=n.connections.filter(k=>!_.has(k.name)&&y.has(k.name));let E=[];if(g.valid&&x.length>0&&x.length<=12&&l){const k=new Set(x.map(F=>F.name)),R={...n,connections:x,buses:n.buses?.map(F=>({...F,connectionNames:F.connectionNames.filter(O=>k.has(O))})).filter(F=>F.connectionNames.length>0),obstacles:n.obstacles,traces:C.traces};try{const F=l(R,{effort:c});E=rbo({inputSrj:e,fanoutSrj:n,localTraces:[...p.traces,...I],candidates:F.filter(O=>k.has(O.connection_name)),clearance:a,allowBlindAndBuriedVias:A})}catch(F){u.push(`Downstream router failed: ${F instanceof Error?F.message:String(F)}`)}}else!g.valid&&x.length>0?u.push("Skipped downstream router because the endpoint-completion baseline failed emitted-copper DRC"):x.length>12?u.push(`Skipped downstream router for ${x.length} unresolved connections (bounded at 12)`):x.length>0&&!l&&u.push(`Skipped downstream router for ${x.length} unresolved connections because no routeDownstreamConnections callback was provided`);const B=[...p.traces,...I,...E];for(const k of f){const R={...n,traces:[...n.traces??[],...B]};if(ZN(o4({inputSrj:e,routedSrj:R}),k.connectionName))continue;const F=qDt({inputSrj:e,fanoutSrj:n,plan:k,acceptedTraces:B,traceWidth:i,viaDiameter:r,viaHoleDiameter:s,clearance:a,allowBlindAndBuriedVias:A});F&&B.push(F)}const S={...n,traces:[...n.traces??[],...B]},Q=ibo({fanoutSrj:S,completionTraces:B}),w=o4({inputSrj:e,routedSrj:Q}),M=qu({inputSrj:e,routedSrj:Q,clearance:a,allowBlindAndBuriedVias:A});return M.valid?{simpleRouteJson:Q,traces:B,report:{attemptedLocalConnectionCount:d.length,attemptedDownstreamConnectionCount:f.length,completionTraceCount:B.length,searchPassCount:m,errors:u,connectivity:w,drc:M}}:(u.push("Final endpoint-completion output failed emitted-copper DRC"),{simpleRouteJson:n,traces:[],report:{attemptedLocalConnectionCount:d.length,attemptedDownstreamConnectionCount:f.length,completionTraceCount:0,searchPassCount:m,errors:u,connectivity:o4({inputSrj:e,routedSrj:n}),drc:g}})}var abo={topside_left:{direction:"left",preferredExit:"top-left",exitEdge:"top"},topside_center:{direction:"up",preferredExit:"top",exitEdge:"top"},topside_right:{direction:"right",preferredExit:"top-right",exitEdge:"top"},rightside_top:{direction:"up",preferredExit:"top-right",exitEdge:"right"},rightside_center:{direction:"right",preferredExit:"right",exitEdge:"right"},rightside_bottom:{direction:"down",preferredExit:"bottom-right",exitEdge:"right"},bottomside_right:{direction:"right",preferredExit:"bottom-right",exitEdge:"bottom"},bottomside_center:{direction:"down",preferredExit:"bottom",exitEdge:"bottom"},bottomside_left:{direction:"left",preferredExit:"bottom-left",exitEdge:"bottom"},leftside_bottom:{direction:"down",preferredExit:"bottom-left",exitEdge:"left"},leftside_center:{direction:"left",preferredExit:"left",exitEdge:"left"},leftside_top:{direction:"up",preferredExit:"top-left",exitEdge:"left"},center:{}};function XDt(t){const e=abo[t];if(!e)throw new Error(`Invalid fanout exit position "${t}"`);return e}function fPe(t){const e=t.differentialPairs;if(e===void 0)return[];if(!Array.isArray(e))throw new Error("Differential pairs must be an array");const n=new Map;return t.connections.forEach((o,i)=>{const r=n.get(o.name)??[];r.push(i),n.set(o.name,r)}),e.map((o,i)=>{const r=o,s=r?.connectionNames,a=r?.lengthTolerance;if(!Array.isArray(s)||s.length!==2||s.some(c=>typeof c!="string"||c.length===0)||s[0]===s[1]||typeof a!="number"||!Number.isFinite(a)||a<0)throw new Error(`Differential pair ${i} requires two distinct connection names and a finite nonnegative tolerance`);const A=s.map(c=>{const l=n.get(c);if(l?.length!==1)throw new Error(`Differential pair ${i} cannot resolve original connection ${c}`);return l[0]});return{connectionNames:s,connectionIndices:A,lengthTolerance:a}})}function J0e(t,e,n=!0){const o=Rb(t.layerCount),i=[],r=[];let s;for(const a of e.route){if(a.route_type==="via"){r.push({center:{x:a.x,y:a.y},diameter:a.via_diameter??t.minViaPadDiameter??t.min_via_pad_diameter??t.minViaDiameter??t.minTraceWidth,spanLayers:VDt({fromLayer:a.from_layer,toLayer:a.to_layer,layers:"layers"in a&&Array.isArray(a.layers)?a.layers:void 0,layerNames:o,allowBlindAndBuriedVias:n})}),s=void 0;continue}if(a.route_type!=="wire"){s=void 0;continue}s?.layer===a.layer&&(s.x!==a.x||s.y!==a.y)&&i.push({start:{x:s.x,y:s.y},end:{x:a.x,y:a.y},width:Math.max(s.width,a.width),layer:a.layer}),s=a}return{trace:e,connectionName:e.connection_name,segments:i,vias:r}}function Z7(t,e=!0){return(t.traces??[]).map(n=>J0e(t,n,e))}function*Abo(t){const{plan:e,bus:n,inputSrj:o,layerNames:i,clearance:r,consumeWork:s}=t;if(!e.via||(e.additionalVias?.length??0)>4)return;const a=(n.routableEscapeLayers??n.allowedLayers??i).filter(f=>f!==e.targetLayer&&i.includes(f)&&(n.allowedLayers??i).includes(f));if(!a.length)return;const A=t.plans.filter(f=>f.connectionIndex!==e.connectionIndex),c=Z7(o,!1),l=[...A.flatMap(f=>[...f.segments,...f.planeEndpointSegments??[]]),...c.flatMap(f=>f.segments)],u=[...t.plans.flatMap(f=>[f.via,...f.additionalVias??[],f.planeEndpointVia].filter(I=>!!I)),...c.flatMap(f=>f.vias)],g=e.via.diameter,h=n.sharedBoundary,d=n.componentBounds,p=g/2+r,m=[];for(const[f,I]of e.segments.entries()){if(I.layer!==e.targetLayer||f<(e.sourceEscapeSegmentCount??1))continue;const C=tn(I.start,I.end),y=Math.max(1,Math.ceil(C/(I.width/2)));for(let x=0;x<=y;x++){s();const E=x/y,B={x:I.start.x+(I.end.x-I.start.x)*E,y:I.start.y+(I.end.y-I.start.y)*E};if(!(B.x>=d.minX-p&&B.x<=d.maxX+p&&B.y>=d.minY-p&&B.y<=d.maxY+p)&&!(Math.min(B.x-h.minX,h.maxX-B.x,B.y-h.minY,h.maxY-B.y)<g/2+1e-7)&&!m.some(S=>tn(S.point,B)<1e-7)&&!o.obstacles.some(S=>wx(B,S)<p-1e-9)&&!u.some(S=>tn(B,S.center)<(g+S.diameter)/2+r-1e-9)&&!l.some(S=>Cr(B,S.start,S.end)<(g+S.width)/2+r-1e-9)&&(m.push({index:f,point:B}),m.length===64))break}if(m.length===64)break}const _=m.flatMap((f,I)=>m.slice(I+1).flatMap(C=>{if(f.index>=C.index||tn(f.point,C.point)<g+r)return[];const y=e.segments.slice(f.index,C.index+1);return y.some(x=>x.layer!==e.targetLayer)?[]:[{a:f,b:C,length:y.reduce((x,E)=>x+tn(E.start,E.end),0)}]})).sort((f,I)=>I.length-f.length);for(const{a:f,b:I}of _){const C=e.segments[f.index],y=e.segments[I.index],x=[...e.segments.slice(0,f.index),{...C,end:f.point}].filter(R=>tn(R.start,R.end)>1e-7),E=[{...y,start:I.point},...e.segments.slice(I.index+1)].filter(R=>tn(R.start,R.end)>1e-7),B=[{...C,start:f.point},...e.segments.slice(f.index+1,I.index),{...y,end:I.point}].filter(R=>tn(R.start,R.end)>1e-7),S=I.point.x-f.point.x,Q=I.point.y-f.point.y,w=Math.min(Math.abs(S),Math.abs(Q)),M=[{x:f.point.x+Math.sign(S)*w,y:f.point.y+Math.sign(Q)*w},{x:I.point.x-Math.sign(S)*w,y:I.point.y-Math.sign(Q)*w}],k=[B,...M.map(R=>[{...C,start:f.point,end:R},{...C,start:R,end:I.point}].filter(F=>tn(F.start,F.end)>1e-7))];for(const R of a){const F=l.filter(W=>W.layer===R),O=u.filter(W=>W.spanLayers.includes(R)),U=o.obstacles.filter(W=>W.layers.includes(R)),Y=[{...e.via,center:f.point,fromLayer:e.targetLayer,toLayer:R,spanLayers:i},{...e.via,center:I.point,fromLayer:R,toLayer:e.targetLayer,spanLayers:i}];for(const W of k){s();const te=W.map(j=>({...j,layer:R}));te.some(j=>F.some(J=>!Zm(j,J,r))||O.some(J=>Cr(J.center,j.start,j.end)<(J.diameter+j.width)/2+r-1e-9)||U.some(J=>Tl(j,J)<j.width/2+r-1e-9))||(yield{before:x,window:te,after:E,tuningLayer:R,addedVias:Y})}}}}function eR(t){const{points:e,chamfer:n,segmentIsClear:o}=t;if(e.length<2)return null;const i=1e-7;let r=[[e[0]]];for(let s=1;s<e.length;s++){const a=e[s-1],A=e[s],c=A.x-a.x,l=A.y-a.y;if(a.z!==A.z||Math.abs(c)<i||Math.abs(l)<i||Math.abs(Math.abs(c)-Math.abs(l))<i){for(const h of r)h.push(A);continue}const u=Math.min(Math.abs(c),Math.abs(l)),g=[{x:a.x+Math.sign(c)*u,y:a.y+Math.sign(l)*u,z:a.z},{x:A.x-Math.sign(c)*u,y:A.y-Math.sign(l)*u,z:a.z},{x:A.x,y:a.y,z:a.z},{x:a.x,y:A.y,z:a.z}].filter(h=>o(a,h)&&o(h,A));if(r=r.flatMap(h=>g.map(d=>[...h,d,A])).slice(0,16),r.length===0)return null}for(const s of r){const a=[s[0]];let A=!0;for(let c=1;c<s.length-1;c++){const l=s[c-1],u=s[c],g=s[c+1],h=tn(l,u),d=tn(u,g);if(l.z!==u.z||u.z!==g.z||h<i||d<i){a.push(u);continue}const p=(u.x-l.x)/h,m=(u.y-l.y)/h,_=(g.x-u.x)/d,f=(g.y-u.y)/d,I=p*_+m*f,C=t.repairReversingDiagonalCorners===!0&&Math.abs(I+Math.SQRT1_2)<i;if(Math.abs(I)>i&&!C){a.push(u);continue}let y=Math.min(n,h/3,d/3),x=!1;for(;y>=1e-6;){const E={x:u.x-p*y,y:u.y-m*y,z:u.z},B={x:u.x+_*y,y:u.y+f*y,z:u.z},S=Math.sign(p*f-m*_),Q=C?{x:E.x+(p-S*m)*Math.SQRT1_2*y*(Math.SQRT2-1),y:E.y+(m+S*p)*Math.SQRT1_2*y*(Math.SQRT2-1),z:u.z}:void 0;if(Q?o(E,Q)&&o(Q,B):o(E,B)){a.push(E,...Q?[Q]:[],B),x=!0;break}y/=2}if(!x){A=!1;break}}if(A){a.push(s.at(-1));for(let c=1;c<a.length;c++){const l=a[c-1],u=a[c];if(l.z!==u.z){tn(l,u)>i&&(A=!1);continue}if(!o(l,u)){A=!1;break}const g=Math.abs(l.x-u.x),h=Math.abs(l.y-u.y);if(g>i&&h>i&&Math.abs(g-h)>i){A=!1;break}const d=a[c+1];if(d?.z===u.z&&tn(l,u)>i&&tn(u,d)>i&&((u.x-l.x)*(d.x-u.x)+(u.y-l.y)*(d.y-u.y))/(tn(l,u)*tn(u,d))<Math.SQRT1_2-i){A=!1;break}}if(A)return a}}return null}var qj=class{layers=new Map;constructor(t){const e=new Map;for(const n of t){const o=n.width/2,i={segment:n,minX:Math.min(n.start.x,n.end.x)-o,maxX:Math.max(n.start.x,n.end.x)+o,minY:Math.min(n.start.y,n.end.y)-o,maxY:Math.max(n.start.y,n.end.y)+o},r=e.get(n.layer)??[];r.push(i),e.set(n.layer,r)}for(const[n,o]of e)this.layers.set(n,this.build(o))}querySegment(t,e){const n=t.width/2+e+1e-8;return this.query([t.layer],{minX:Math.min(t.start.x,t.end.x)-n,maxX:Math.max(t.start.x,t.end.x)+n,minY:Math.min(t.start.y,t.end.y)-n,maxY:Math.max(t.start.y,t.end.y)+n})}queryVia(t,e){const n=t.diameter/2+e+1e-8;return this.query(t.spanLayers,{minX:t.center.x-n,maxX:t.center.x+n,minY:t.center.y-n,maxY:t.center.y+n})}query(t,e){const n=[],o=r=>!(r.minX>e.maxX||r.maxX<e.minX||r.minY>e.maxY||r.maxY<e.minY),i=r=>{if(o(r))if(r.entries)for(const s of r.entries)o(s)&&n.push(s.segment);else i(r.left),i(r.right)};for(const r of t){const s=this.layers.get(r);s&&i(s)}return n}build(t){const e=t.reduce((i,r)=>({minX:Math.min(i.minX,r.minX),maxX:Math.max(i.maxX,r.maxX),minY:Math.min(i.minY,r.minY),maxY:Math.max(i.maxY,r.maxY)}),{minX:1/0,maxX:-1/0,minY:1/0,maxY:-1/0});if(t.length<=8)return{...e,entries:t};const n=e.maxX-e.minX>=e.maxY-e.minY;t.sort((i,r)=>n?i.minX+i.maxX-r.minX-r.maxX:i.minY+i.maxY-r.minY-r.maxY);const o=Math.floor(t.length/2);return{...e,left:this.build(t.slice(0,o)),right:this.build(t.slice(o))}}};function Xj(t){switch(t){case"left":return"left";case"right":return"right";case"up":return"top";case"down":return"bottom"}}function e6(t){switch(t){case"left":return"left";case"right":return"right";case"top":return"up";case"bottom":return"down"}}function ZDt(t,e){return t===e||t.includes(e)}function Ds(t,e){if(!(!t||!e?.includes("-"))&&ZDt(e,t))return t==="left"||t==="right"?e.startsWith("top-")?"maximum":"minimum":e.endsWith("-right")?"maximum":"minimum"}function cbo(t,e){const n=e==="up"||e==="down"?"y":"x",o=t.slice(0,32).map(({connectionIndex:i})=>[i]);for(let i=0;i<t.length;i++)for(let r=i+1;r<t.length;r++){if(o.length>=32)return o;const s=t[i],a=t[r];Math.abs(s.sourcePoint[n]-a.sourcePoint[n])<=1e-9&&o.push([s.connectionIndex,a.connectionIndex])}return o}var kg=1e-9,lbo=1e5;function eNt(t){for(const[n,o]of[["viaDiameter",t.viaDiameter],["traceWidth",t.traceWidth]])if(!Number.isFinite(o)||o<=0)throw new Error(`FanoutSolver: dogbone ${n} must be a positive finite number, received ${o}`);if(!Number.isFinite(t.clearance)||t.clearance<0)throw new Error(`FanoutSolver: dogbone clearance must be a non-negative finite number, received ${t.clearance}`);if(t.viaHoleDiameter!==void 0&&(!Number.isFinite(t.viaHoleDiameter)||t.viaHoleDiameter<=0))throw new Error(`FanoutSolver: dogbone viaHoleDiameter must be a positive finite number, received ${t.viaHoleDiameter}`);if(t.holeToHoleClearance!==void 0&&(!Number.isFinite(t.holeToHoleClearance)||t.holeToHoleClearance<0))throw new Error(`FanoutSolver: dogbone holeToHoleClearance must be a non-negative finite number, received ${t.holeToHoleClearance}`);if(t.holeToHoleClearance!==void 0&&t.viaHoleDiameter===void 0)throw new Error("FanoutSolver: dogbone holeToHoleClearance requires viaHoleDiameter");const e=t.maximumSearchStates??lbo;if(!Number.isInteger(e)||e<1)throw new Error(`FanoutSolver: dogbone maximumSearchStates must be a positive integer, received ${e}`);return e}function IPe(t){const e=[];for(const n of t.toSorted((o,i)=>o-i))Number.isFinite(n)&&(e.length===0||Math.abs(e.at(-1)-n)>kg)&&e.push(n);return e}function tNt(t){const e=new Map,n=new Map,o=new Map;for(const i of t){let r=e.get(i.componentId);r||(r={componentId:i.componentId,connections:[],obstacles:[],xCoordinates:[],yCoordinates:[],pitchX:Number.POSITIVE_INFINITY,pitchY:Number.POSITIVE_INFINITY},e.set(i.componentId,r),o.set(i.componentId,new Set)),r.xCoordinates.push(...i.xCoordinates),r.yCoordinates.push(...i.yCoordinates),Number.isFinite(i.pitchX)&&i.pitchX>kg&&(r.pitchX=Math.min(r.pitchX,i.pitchX)),Number.isFinite(i.pitchY)&&i.pitchY>kg&&(r.pitchY=Math.min(r.pitchY,i.pitchY));const s=o.get(i.componentId);for(const a of i.componentObstacles)s.has(a)||(s.add(a),r.obstacles.push(a));for(const a of i.connections){const A=n.get(a.connectionIndex);if(A!==void 0){if(A!==i.componentId)throw new Error(`FanoutSolver: connection index ${a.connectionIndex} belongs to multiple components`);continue}n.set(a.connectionIndex,i.componentId),r.connections.push({preparedConnection:a,busId:i.busId,direction:i.direction,terminationType:i.termination.type})}}return[...e.values()].map(i=>({...i,connections:i.connections.toSorted((r,s)=>r.preparedConnection.connectionIndex-s.preparedConnection.connectionIndex),xCoordinates:IPe(i.xCoordinates),yCoordinates:IPe(i.yCoordinates)})).toSorted((i,r)=>i.componentId.localeCompare(r.componentId))}function ubo(t){const{coordinates:e,pitch:n}=t;if(e.length===0||!Number.isFinite(n)||n<=kg)return[];const o=[e[0]-n/2];for(let i=1;i<e.length;i++)o.push((e[i-1]+e[i])/2);return o.push(e.at(-1)+n/2),IPe(o)}function nNt(t){const{sourceCoordinate:e,coordinates:n,pitch:o}=t,i=ubo({coordinates:n,pitch:o}),r=i.filter(a=>a<e-kg).at(-1),s=i.find(a=>a>e+kg);return[r,s].filter(a=>a!==void 0)}function gbo(t,e){const n=Math.abs(e.x-t.x),o=Math.abs(e.y-t.y);return n<=kg||o<=kg||Math.abs(n-o)<=kg}function dbo(t){const{source:e,site:n,direction:o}=t,i=o==="right"?n.x-e.x:o==="left"?e.x-n.x:o==="up"?n.y-e.y:e.y-n.y;return i>kg?0:Math.abs(i)<=kg?1:2}function hbo(t){const{point:e,obstacles:n,viaDiameter:o,clearance:i}=t,r=o/2+i;return n.every(s=>wx(e,s)>=r-kg)}function pbo(t){const{segment:e,sourceObstacle:n,obstacles:o,clearance:i}=t,r=e.width/2+i;return o.every(s=>s===n||Tl(e,s)>=r-kg)}function oNt(t){const{connection:e,component:n,rules:o}=t,{preparedConnection:i,direction:r}=e,s=o.additionalObstacles?[...new Set([...n.obstacles,...o.additionalObstacles])]:n.obstacles,a={x:i.sourcePoint.x,y:i.sourcePoint.y},A=nNt({sourceCoordinate:a.x,coordinates:n.xCoordinates,pitch:n.pitchX}),c=nNt({sourceCoordinate:a.y,coordinates:n.yCoordinates,pitch:n.pitchY}),l=[...A.map(E=>({x:E,y:a.y})),...c.map(E=>({x:a.x,y:E})),...A.flatMap(E=>c.map(B=>({x:E,y:B})))],u=[];for(const E of l)u.some(B=>tn(B,E)<=kg)||u.push(E);const g=o.fixedViaPointsByConnectionIndex?.get(i.connectionIndex),h=g?[g]:u,d=[];for(const E of h){if(e.terminationType==="plane"&&!gbo(a,E)||!hbo({point:E,obstacles:s,viaDiameter:o.viaDiameter,clearance:o.clearance}))continue;const B={start:a,end:E,width:o.traceWidth,layer:i.sourceLayer};!pbo({segment:B,sourceObstacle:i.sourceObstacle,obstacles:s,clearance:o.clearance})||!(o.blockingSegments??[]).every(w=>{if(w.connectionIndex===i.connectionIndex||o.canShareCopper?.(i.connectionIndex,w.connectionIndex))return!0;const M=o.viaDiameter/2+w.segment.width/2+o.clearance;return Cr(E,w.segment.start,w.segment.end)<M-kg?!1:w.segment.layer!==B.layer||Zm(B,w.segment,o.clearance)})||!(o.blockingVias??[]).every(w=>w.connectionIndex===i.connectionIndex?!0:!(tn(E,w.center)<(o.viaDiameter+w.diameter)/2+o.clearance-kg||w.spanLayers.includes(B.layer)&&Cr(w.center,B.start,B.end)<w.diameter/2+B.width/2+o.clearance-kg))||d.push({connectionIndex:i.connectionIndex,point:E,sourceSegment:B,outwardRank:dbo({source:a,site:E,direction:r})})}const p=r==="left"||r==="right"?n.yCoordinates:n.xCoordinates,m=r==="left"||r==="right"?a.y:a.x,_=p.findIndex(E=>Math.abs(E-m)<=kg),f=_>=0?_%2===0?1:-1:void 0,I=e.terminationType==="boundary"?o.preferredBoundaryPerpendicularSideByBusId?.get(e.busId):o.preferPlaneCheckerboardSites&&e.terminationType==="plane"&&(r==="left"||r==="right")?f:void 0,C=e.terminationType==="boundary"?o.preferBoundaryOutwardByBusId?.get(e.busId)??!0:!0,y=o.preferredViaPointsByConnectionIndex?.get(i.connectionIndex),x=E=>{if(I===void 0)return 0;const B=r==="left"||r==="right"?E.point.y-a.y:E.point.x-a.x;return B*I>kg?0:Math.abs(B)<=kg?1:2};return d.toSorted((E,B)=>(y?+(tn(E.point,y)>kg)-+(tn(B.point,y)>kg):0)||(C?E.outwardRank-B.outwardRank:B.outwardRank-E.outwardRank)||x(E)-x(B)||tn(a,E.point)-tn(a,B.point)||E.point.x-B.point.x||E.point.y-B.point.y)}function mbo(t){const{first:e,second:n,rules:o}=t,i=o.canShareCopper?.(e.connectionIndex,n.connectionIndex)??!1,r=o.viaHoleDiameter?o.viaHoleDiameter+(o.holeToHoleClearance??o.clearance):0,s=i?r:Math.max(o.viaDiameter+o.clearance,r);if(tn(e.point,n.point)<s-kg)return!1;const a=o.viaDiameter/2+o.traceWidth/2+o.clearance;return!i&&(Cr(e.point,n.sourceSegment.start,n.sourceSegment.end)<a-kg||Cr(n.point,e.sourceSegment.start,e.sourceSegment.end)<a-kg)?!1:i?!0:Zm(e.sourceSegment,n.sourceSegment,o.clearance)}function _bo(t){const{component:e,rules:n,consumeSearchState:o}=t,i=e.connections.map(h=>({connection:h,candidates:oNt({connection:h,component:e,rules:n})}));if(i.some(h=>h.candidates.length===0))return null;const r=new Map,s=(h,d)=>{const p=r.get(h)?.get(d);if(p!==void 0)return p;const m=mbo({first:h,second:d,rules:n}),_=r.get(h)??new Map;_.set(d,m),r.set(h,_);const f=r.get(d)??new Map;return f.set(h,m),r.set(d,f),m},a=i.flatMap(h=>h.candidates.length===1?[h.candidates[0]]:[]);for(let h=0;h<a.length;h++){const d=a[h];for(let p=0;p<h;p++)if(!s(d,a[p]))return null}const A=new Map(a.map(h=>[h.connectionIndex,h])),c=new Set(i.flatMap(h=>h.candidates.length>1?[h.connection.preparedConnection.connectionIndex]:[])),l=new Map(i.map(h=>[h.connection.preparedConnection.connectionIndex,h]));if(c.size===0)return new Map([...A.entries()].map(([h,d])=>[h,{...d.point}]));const u=h=>h.candidates.filter(d=>[...A.values()].every(p=>s(d,p))),g=()=>{if(!o())return!1;if(c.size===0)return!0;let h,d=[];for(const m of[...c].toSorted((_,f)=>_-f)){const _=l.get(m),f=u(_);if(f.length===0)return!1;(!h||f.length<d.length||f.length===d.length&&m<h.connection.preparedConnection.connectionIndex)&&(h=_,d=f)}const p=h.connection.preparedConnection.connectionIndex;c.delete(p);for(const m of d){if(A.set(p,m),g())return!0;A.delete(p)}return c.add(p),!1};return g()?new Map([...A.entries()].toSorted(([h],[d])=>h-d).map(([h,d])=>[h,{...d.point}])):null}function pd(t,e){const n=eNt(e);if(t.length===0)return new Map;let o=0;const i=()=>(o++,o<=n),r=new Map;for(const s of tNt(t)){const a=_bo({component:s,rules:e,consumeSearchState:i});if(!a)return null;for(const[A,c]of a)r.set(A,c)}return r}function pw(t,e){return eNt(e),tNt(t).flatMap(n=>n.connections.flatMap(o=>oNt({connection:o,component:n,rules:e}).map(i=>({connectionIndex:i.connectionIndex,point:{...i.point}}))))}function*fbo(t,e,n){const o=pw([t],e);let i=24;for(const r of t.connections.toReversed()){const s=n.get(r.connectionIndex);if(s)for(const a of o){if(a.connectionIndex!==r.connectionIndex||tn(a.point,s)<=kg)continue;if(i--<=0)return;const A=new Map(n);A.set(r.connectionIndex,a.point),yield A}}}var d0=1e-7,Ibo=16e4,Cbo=24e4,ybo=5e3,xbo=24,iNt=3.25,Ebo=class{constructor(t,e,n,o,i,r,s,a){this.minX=e,this.minY=n,this.cellSize=r,this.columnCount=Math.max(1,Math.ceil((o-e)/r)),this.rowCount=Math.max(1,Math.ceil((i-n)/r)),this.cells=new Array(this.columnCount*this.rowCount);for(const A of t){const c={...A,minX:Math.min(A.segment.start.x,A.segment.end.x),maxX:Math.max(A.segment.start.x,A.segment.end.x),minY:Math.min(A.segment.start.y,A.segment.end.y),maxY:Math.max(A.segment.start.y,A.segment.end.y)},l=(A.segment.width+s)/2+a,u=this.column(c.minX-l),g=this.column(c.maxX+l),h=this.row(c.minY-l),d=this.row(c.maxY+l);for(let p=h;p<=d;p++)for(let m=u;m<=g;m++){const _=p*this.columnCount+m;(this.cells[_]??=[]).push(c)}}}minX;minY;cellSize;cells;columnCount;rowCount;seen=new Map;queryCount=0;column(t){return Math.max(0,Math.min(this.columnCount-1,Math.floor((t-this.minX)/this.cellSize)))}row(t){return Math.max(0,Math.min(this.rowCount-1,Math.floor((t-this.minY)/this.cellSize)))}querySegment(t){const e=this.column(Math.min(t.start.x,t.end.x)),n=this.column(Math.max(t.start.x,t.end.x)),o=this.row(Math.min(t.start.y,t.end.y)),i=this.row(Math.max(t.start.y,t.end.y));if(e===n&&o===i)return this.cells[o*this.columnCount+e]??[];const r=[],s=++this.queryCount;for(let a=o;a<=i;a++)for(let A=e;A<=n;A++)for(const c of this.cells[a*this.columnCount+A]??[])this.seen.get(c)!==s&&(this.seen.set(c,s),r.push(c));return r}};function Bbo(t){const e=t;if(e.shape==="circle"){const c=t.width/2;return{minX:t.center.x-c,maxX:t.center.x+c,minY:t.center.y-c,maxY:t.center.y+c,xRadius:c}}const n=(e.ccwRotationDegrees??0)*Math.PI/180,o=Math.abs(Math.cos(n)),i=Math.abs(Math.sin(n)),r=t.width/2,s=t.height/2,a=o*r+i*s,A=i*r+o*s;return{minX:t.center.x-a,maxX:t.center.x+a,minY:t.center.y-A,maxY:t.center.y+A,xRadius:a}}var bbo=class{obstaclesByCenterX;maximumXRadius;constructor(t){this.obstaclesByCenterX=t.map(e=>({obstacle:e,...Bbo(e)})).toSorted((e,n)=>e.obstacle.center.x-n.obstacle.center.x),this.maximumXRadius=this.obstaclesByCenterX.reduce((e,n)=>Math.max(e,n.xRadius),0)}querySegment(t,e){const n=Math.min(t.start.x,t.end.x),o=Math.max(t.start.x,t.end.x),i=Math.min(t.start.y,t.end.y),r=Math.max(t.start.y,t.end.y),s=n-e-this.maximumXRadius,a=o+e+this.maximumXRadius;let A=0,c=this.obstaclesByCenterX.length;for(;A<c;){const u=Math.floor((A+c)/2);this.obstaclesByCenterX[u].obstacle.center.x<s?A=u+1:c=u}const l=[];for(let u=A;u<this.obstaclesByCenterX.length;u++){const g=this.obstaclesByCenterX[u];if(g.obstacle.center.x>a)break;g.maxX<n-e||g.minX>o+e||g.maxY<i-e||g.minY>r+e||l.push(g.obstacle)}return l}};function*Sbo(t){const{initialOrderFactories:e,rotationBase:n,getItemKey:o,maximumOrderCount:i=Number.POSITIVE_INFINITY}=t,r=new Set;let s=0;const a=A=>A.map(o).join("\0");for(const A of e){if(s>=i)return;const c=A(),l=a(c);r.has(l)||(r.add(l),s++,yield c)}for(let A=1;A<n.length;A++){if(s>=i)return;const c=[...n.slice(A),...n.slice(0,A)],l=a(c);r.has(l)||(r.add(l),s++,yield c)}}var Qbo=class{values=[];get size(){return this.values.length}sampleEntries(t){if(this.values.length<=t)return this.values;const e=Math.ceil(this.values.length/t);return this.values.filter((n,o)=>o%e===0)}push(t){this.values.push(t);let e=this.values.length-1;for(;e>0;){const n=Math.floor((e-1)/2);if(this.values[n].score<=t.score)break;this.values[e]=this.values[n],e=n}this.values[e]=t}pop(){const t=this.values[0],e=this.values.pop();if(!t||!e||this.values.length===0)return t;let n=0;for(;;){const o=n*2+1,i=o+1;if(o>=this.values.length)break;const r=i<this.values.length&&this.values[i].score<this.values[o].score?i:o;if(this.values[r].score>=e.score)break;this.values[n]=this.values[r],n=r}return this.values[n]=e,t}};function CO(t,e){return e==="left"||e==="right"?t.y:t.x}function vbo(t,e){const n=e.x-t.x,o=e.y-t.y,i=Math.abs(n),r=Math.abs(o);return i<d0||r<d0||Math.abs(i-r)<d0?[[t,e]]:i>r?[[t,{x:t.x+Math.sign(n)*r,y:e.y},e],[t,{x:e.x-Math.sign(n)*r,y:t.y},e]]:[[t,{x:e.x,y:t.y+Math.sign(o)*i},e],[t,{x:t.x,y:e.y-Math.sign(o)*i},e]]}function wbo(t){if(t.length<3)return t;const e=[t[0]];for(let n=1;n<t.length-1;n++){const o=e.at(-1),i=t[n],r=t[n+1],s=Math.sign(i.x-o.x),a=Math.sign(i.y-o.y),A=Math.sign(r.x-i.x),c=Math.sign(r.y-i.y);(s!==A||a!==c)&&e.push(i)}return e.push(t.at(-1)),e}function Zj(t,e,n){return t.slice(1).flatMap((o,i)=>{const r=t[i];return tn(r,o)<d0?[]:[{start:r,end:o,width:e,layer:n}]})}function Pbo(t){const e=Math.abs(t.end.x-t.start.x),n=Math.abs(t.end.y-t.start.y);return e<d0||n<d0||Math.abs(e-n)<d0}function Mbo(t){for(let e=0;e<t.length;e++)for(let n=e+2;n<t.length;n++)if(!(e===0&&n===t.length-1&&tn(t[e].start,t[n].end)<d0)&&tu(t[e].start,t[e].end,t[n].start,t[n].end)<d0)return!1;return!0}function Dbo(t){return[t.via,...t.additionalVias??[],t.planeEndpointVia].filter(e=>!!e)}function Nbo(t){const{srj:e,acceptedPlans:n,allowBlindAndBuriedVias:o}=t,i=Z7(e,o);return{segments:[...i.flatMap(r=>r.segments.map(s=>({connectionName:r.connectionName,segment:s}))),...n.flatMap(r=>[...r.segments,...r.planeEndpointSegments??[]].map(s=>({connectionName:r.connectionName,segment:s})))],vias:[...i.flatMap(r=>r.vias.map(s=>({connectionName:r.connectionName,via:s}))),...n.flatMap(r=>Dbo(r).map(s=>({connectionName:r.connectionName,via:s})))]}}function i4(t){const{bus:e,terminal:n,targetLayer:o,targetLayerPoints:i,layerNames:r,traceWidth:s,viaDiameter:a,viaHoleDiameter:A,allowBlindAndBuriedVias:c}=t,l=n.connection,u={x:l.sourcePoint.x,y:l.sourcePoint.y},g=t.sourceEscapePoints??[u,n.viaPoint];if(g.length<2||tn(g[0],u)>d0||tn(g.at(-1),n.viaPoint)>d0)throw new Error("FanoutSolver: source escape must connect the source pad to its first via");const h=Zj([...g],s,l.sourceLayer),d=tn(u,n.viaPoint)>d0,p=l.sourceLayer!==o,m=Zj(i,s,o),_=Mx({fromLayer:l.sourceLayer,toLayer:o,layerNames:r,allowBlindAndBuriedVias:c}),f={center:n.viaPoint,diameter:a,holeDiameter:A,fromLayer:l.sourceLayer,toLayer:o,spanLayers:_},I=[{route_type:"wire",...u,width:s,layer:l.sourceLayer,...l.sourcePoint.pcb_port_id?{start_pcb_port_id:l.sourcePoint.pcb_port_id}:{}},...d?[...g.slice(1).map(E=>({route_type:"wire",...E,width:s,layer:l.sourceLayer}))]:[],...p?[{route_type:"via",...n.viaPoint,from_layer:l.sourceLayer,to_layer:o,via_diameter:a,via_hole_diameter:A},{route_type:"wire",...n.viaPoint,width:s,layer:o}]:[],...i.slice(1).map(E=>({route_type:"wire",...E,width:s,layer:o}))],C=qN({connectionName:l.connection.name,sourcePointIndex:l.sourcePointIndex}),y=[...d?h:[],...m],x=Ds(e.exitEdge,e.preferredExit);return{busId:e.busId,connectionName:l.connection.name,connectionIndex:l.connectionIndex,sourcePointIndex:l.sourcePointIndex,sourcePoint:l.sourcePoint,sourceObstacle:l.sourceObstacle,sourceLayer:l.sourceLayer,targetPoint:l.targetPoint,targetLayer:o,termination:e.termination,direction:e.direction,...e.exitEdge?{exitEdge:e.exitEdge}:{},...x?{cornerBandSide:x}:{},exitPoint:n.exitPoint,trace:{type:"pcb_trace",pcb_trace_id:C.traceId,connection_name:l.connection.name,connectsTo:[...l.sourcePoint.pointId?[l.sourcePoint.pointId]:[],...l.sourcePoint.pcb_port_id?[l.sourcePoint.pcb_port_id]:[],C.boundaryExitPointId],route:I},segments:y,...h.length>1?{sourceEscapeSegmentCount:h.length}:{},via:p?f:void 0,length:y.reduce((E,B)=>E+tn(B.start,B.end),0)}}function*BC(t,e=1,n=!1){if(!Number.isInteger(e)||e<1)throw new Error(`FanoutSolver: maximum winding alternatives must be a positive integer, received ${e}`);const{srj:o,bus:i,targetLayer:r,terminals:s,acceptedPlans:a,layerNames:A,traceWidth:c,viaDiameter:l,viaHoleDiameter:u,clearance:g,allowBlindAndBuriedVias:h=!0,allowSameNetMerges:d=!1,maximumRouteOrderAttempts:p,maximumSearchStates:m=Cbo,reservedVias:_=[],softReservedVias:f=[],gridStepDivisor:I=1,heuristicWeight:C=1,preferTargetDirectedLaneBias:y=!1,allowSourceLayerRouting:x=!1,adaptiveRouteOrder:E=!1,alignGridToPads:B=!1,includeReverseTargetRotation:S=!1,reserveTerminalExitPoints:Q=!1,forbidEarlyExitBoundaryContact:w=!1}=t;if(p!==void 0&&(!Number.isInteger(p)||p<1))throw new Error(`FanoutSolver: maximumRouteOrderAttempts must be a positive integer, received ${p}`);if(!Number.isSafeInteger(m)||m<1)throw new Error(`FanoutSolver: maximumSearchStates must be a positive safe integer, received ${m}`);if(!Number.isFinite(C)||C<=0)throw new Error(`FanoutSolver: heuristicWeight must be a positive finite number, received ${C}`);if(I!==1&&I!==2)throw new Error(`FanoutSolver: gridStepDivisor must be 1 or 2, received ${I}`);if(s.length===0||!i.exitEdge||!x&&s.some(Ze=>Ze.connection.sourceLayer===r))return[];const M=(c+g)/I,k=Math.min(i.pitchX,i.pitchY),R=B&&I===2&&Number.isFinite(k),F=t.gridStep??(R?k/(2*Math.ceil(k/(2*M))):M);if(!Number.isFinite(F)||F<=0)return[];const{minX:O,maxX:U,minY:Y,maxY:W}=i.sharedBoundary,te=t.gridOrigin?.x??i.xCoordinates[0]??O,j=t.gridOrigin?.y??i.yCoordinates[0]??Y,J=R?te+Math.ceil((O-te)/F)*F:O,oe=R?j+Math.ceil((Y-j)/F)*F:Y,ie=Math.floor((U-J)/F)+1,ne=Math.floor((W-oe)/F)+1,le=ie*ne;if(ie<2||ne<2||le>Ibo)return[];const ge=Array.from({length:le},(Ze,dt)=>{const Ut=dt%ie,Wt=Math.floor(dt/ie);return{column:Ut,row:Wt,point:{x:J+Ut*F,y:oe+Wt*F}}}),_e=f.length?new Float32Array(le):void 0;if(_e)for(const{via:Ze}of f){if(!Ze.spanLayers.includes(r))continue;const dt=Ze.diameter/2+c/2+g,Ut=Math.max(0,Math.ceil((Ze.center.x-dt-J)/F)),Wt=Math.min(ie-1,Math.floor((Ze.center.x+dt-J)/F)),Xt=Math.max(0,Math.ceil((Ze.center.y-dt-oe)/F)),Jt=Math.min(ne-1,Math.floor((Ze.center.y+dt-oe)/F));for(let yn=Xt;yn<=Jt;yn++)for(let An=Ut;An<=Wt;An++){const kn=yn*ie+An;tn(ge[kn].point,Ze.center)<dt&&(_e[kn]=_e[kn]+25*F)}}const ue=n?ge.filter((Ze,dt)=>dt%Math.max(1,Math.ceil(ge.length/1e3))===0).map(Ze=>Ze.point):[],fe=o.obstacles.filter(Ze=>Ze.layers.includes(r)),pe=new bbo(fe),ye=Nbo({srj:o,acceptedPlans:a,allowBlindAndBuriedVias:h}),Me=ye.segments.filter(({segment:Ze})=>{if(Ze.layer!==r)return!1;const dt=(Ze.width+c)/2+g;return!(Math.max(Ze.start.x,Ze.end.x)<O-dt||Math.min(Ze.start.x,Ze.end.x)>U+dt||Math.max(Ze.start.y,Ze.end.y)<Y-dt||Math.min(Ze.start.y,Ze.end.y)>W+dt)});x&&Me.push(..._.flatMap(Ze=>Ze.sourceEscapeSegment?.layer===r?[{connectionName:Ze.connectionName,segment:Ze.sourceEscapeSegment}]:[]));const ve=ye.vias.filter(({via:Ze})=>{if(!Ze.spanLayers.includes(r))return!1;const dt=Ze.diameter/2+c/2+g;return!(Ze.center.x<O-dt||Ze.center.x>U+dt||Ze.center.y<Y-dt||Ze.center.y>W+dt)});ve.push(..._.filter(({via:Ze})=>{if(!Ze.spanLayers.includes(r))return!1;const dt=Ze.diameter/2+c/2+g;return!(Ze.center.x<O-dt||Ze.center.x>U+dt||Ze.center.y<Y-dt||Ze.center.y>W+dt)}));const he=s.filter(Ze=>Ze.connection.sourceLayer!==r).map(Ze=>({connectionName:Ze.connection.connection.name,via:{center:Ze.viaPoint,diameter:l,spanLayers:Mx({fromLayer:Ze.connection.sourceLayer,toLayer:r,layerNames:A,allowBlindAndBuriedVias:h})}})),Qe=e6(i.exitEdge),Pe=(Ze,dt)=>Ze===dt||d&&Px(o,Ze,dt),we=Ze=>new Ebo(Ze,O,Y,U,W,F*8,c,g),Te=we(Me),Re=[...ve,...he],Ee=Re.reduce((Ze,{via:dt})=>Math.max(Ze,dt.diameter/2+c/2+g),c/2+g),ke=Re.toSorted((Ze,dt)=>Ze.via.center.x-dt.via.center.x),Ce=Ze=>{let dt=0,Ut=ke.length;for(;dt<Ut;){const Wt=Math.floor((dt+Ut)/2);ke[Wt].via.center.x<Ze?dt=Wt+1:Ut=Wt}return dt},Le=Ze=>{const{segment:dt,terminal:Ut,acceptedAttemptSegmentIndex:Wt}=Ze;if(w){const ht=i.sharedBoundary;for(const Kt of[dt.start,dt.end])if((Math.abs(Kt.x-ht.minX)<d0||Math.abs(Kt.x-ht.maxX)<d0||Math.abs(Kt.y-ht.minY)<d0||Math.abs(Kt.y-ht.maxY)<d0)&&tn(Kt,Ut.exitPoint)>d0)return!1}const Xt=Ut.connection.connection.name,Jt=Math.min(dt.start.x,dt.end.x),yn=Math.max(dt.start.x,dt.end.x),An=Math.min(dt.start.y,dt.end.y),kn=Math.max(dt.start.y,dt.end.y),$n=dt.width/2+g;for(const ht of pe.querySegment(dt,$n))if(!(ht.connectedTo.includes(Xt)||d&&n4(o,ht,Xt))&&Tl(dt,ht)<$n-d0)return!1;for(const ht of Te.querySegment(dt)){if(Pe(Xt,ht.connectionName))continue;const Kt=(dt.width+ht.segment.width)/2+g;if(!(yn+Kt<ht.minX||Jt-Kt>ht.maxX||kn+Kt<ht.minY||An-Kt>ht.maxY)&&tu(dt.start,dt.end,ht.segment.start,ht.segment.end)<Kt-d0)return!1}for(const ht of Wt.querySegment(dt)){if(Pe(Xt,ht.connectionName))continue;const Kt=(dt.width+ht.segment.width)/2+g;if(!(yn+Kt<ht.minX||Jt-Kt>ht.maxX||kn+Kt<ht.minY||An-Kt>ht.maxY)&&tu(dt.start,dt.end,ht.segment.start,ht.segment.end)<(dt.width+ht.segment.width)/2+g-d0)return!1}for(const ht of Q?s:[])if(!Pe(Xt,ht.connection.connection.name)&&Cr(ht.exitPoint,dt.start,dt.end)<c+g-d0)return!1;for(let ht=Ce(Jt-Ee);ht<ke.length;ht++){const Kt=ke[ht];if(Kt.via.center.x>yn+Ee)break;if(Pe(Xt,Kt.connectionName))continue;const rn=Kt.via.diameter/2+dt.width/2+g;if(!(Kt.via.center.x<Jt-rn||Kt.via.center.x>yn+rn||Kt.via.center.y<An-rn||Kt.via.center.y>kn+rn)&&Cr(Kt.via.center,dt.start,dt.end)<rn-d0)return!1}return!0},Ye=Ze=>{const{terminal:dt,endpoint:Ut,acceptedAttemptSegmentIndex:Wt}=Ze,Xt=[],Jt=F*iNt,yn=Math.max(0,Math.ceil((Ut.x-Jt-J)/F)-1),An=Math.min(ie-1,Math.floor((Ut.x+Jt-J)/F)+1),kn=Math.max(0,Math.ceil((Ut.y-Jt-oe)/F)-1),$n=Math.min(ne-1,Math.floor((Ut.y+Jt-oe)/F)+1);for(let ht=kn;ht<=$n;ht++)for(let Kt=yn;Kt<=An;Kt++){const rn=ht*ie+Kt,Lt=ge[rn],Ho=tn(Ut,Lt.point);if(!(Ho>F*iNt))for(const Ao of vbo(Ut,Lt.point)){const qe=Zj(Ao,c,r);qe.every(vt=>Le({segment:vt,terminal:dt,acceptedAttemptSegmentIndex:Wt}))&&Xt.push({nodeIndex:rn,points:Ao,radialDistance:Ho,length:qe.reduce((vt,qt)=>vt+tn(qt.start,qt.end),0)})}}return Xt.toSorted((ht,Kt)=>ht.radialDistance-Kt.radialDistance||ht.length-Kt.length||ht.nodeIndex-Kt.nodeIndex).slice(0,xbo)},tt=Ze=>{const{terminal:dt,acceptedAttemptSegments:Ut,expandedPoints:Wt,frontierPoints:Xt,bestPath:Jt,expandedStateCount:yn,searchBatch:An,connectionComplete:kn}=Ze;return{title:`Winding ${i.busId}: ${dt.connection.connection.name}`,rects:[{center:{x:(O+U)/2,y:(Y+W)/2},width:U-O,height:W-Y,fill:"rgba(0, 0, 0, 0)",stroke:"rgba(14, 165, 233, 0.9)",label:"A* search boundary"}],points:[...ue.map($n=>({...$n,color:"rgba(148, 163, 184, 0.22)"})),...Xt.map($n=>({...$n,color:"rgba(6, 182, 212, 0.75)",label:"open frontier"})),...Wt.map($n=>({...$n,color:"rgba(244, 63, 94, 0.8)",label:"expanded in current step"})),{...dt.connection.sourcePoint,color:"#f97316",label:`source: ${dt.connection.connection.name}`},{...dt.exitPoint,color:"#a855f7",label:"target exit"}],circles:s.map($n=>({center:$n.viaPoint,radius:l/2,fill:$n===dt?"rgba(250, 204, 21, 0.85)":"rgba(250, 204, 21, 0.25)",stroke:$n===dt?"#ca8a04":"#a16207",label:$n===dt?"active via":`reserved via: ${$n.connection.connection.name}`})),lines:[...Ut.map(({segment:$n,connectionName:ht})=>({points:[$n.start,$n.end],strokeColor:"rgba(34, 197, 94, 0.9)",strokeWidth:Math.max(c,F*.35),label:`accepted: ${ht}`})),{points:[dt.viaPoint,dt.exitPoint],strokeColor:"rgba(168, 85, 247, 0.45)",strokeWidth:Math.max(c*.5,F*.15),strokeDash:[F,F],label:"active via-to-exit search"},...Jt?[{points:[...Jt],strokeColor:"#facc15",strokeWidth:Math.max(c,F*.45),label:"best path so far"}]:[]],texts:[{x:O,y:W+F*2,text:kn?`connection complete · ${yn.toLocaleString()} states`:`A* batch ${An} · ${yn.toLocaleString()} states`,color:"#0f172a",fontSize:Math.max(F*2.5,.5),anchorSide:"bottom_left"}]}},At=function*(Ze){const{terminal:dt,acceptedAttemptSegments:Ut,laneBias:Wt}=Ze,Xt=we(Ut),Jt=Ye({terminal:dt,endpoint:dt.viaPoint,acceptedAttemptSegmentIndex:Xt}),yn=Ye({terminal:dt,endpoint:dt.exitPoint,acceptedAttemptSegmentIndex:Xt});if(Jt.length===0||yn.length===0)return{points:null,expandedStateCount:0};const An=new Map;for(const To of yn){const yo=An.get(To.nodeIndex)??[];yo.push(To),An.set(To.nodeIndex,yo)}const kn=le*9,$n=new Uint8Array(le*8),ht=C>1?new Uint8Array(kn):void 0,Kt=new Float64Array(kn).fill(Number.POSITIVE_INFINITY),rn=new Int32Array(kn).fill(-1),Lt=new Qbo,Ho=new Float64Array(le),Ao=new Float64Array(le),qe=CO(dt.exitPoint,Qe);for(let To=0;To<le;To++){const yo=ge[To].point,Ro=Math.abs(yo.x-dt.exitPoint.x),On=Math.abs(yo.y-dt.exitPoint.y);Ho[To]=Math.max(Ro,On)+(Math.SQRT2-1)*Math.min(Ro,On);const uo=CO(yo,Qe);Ao[To]=Wt===0?0:Wt>0?Math.max(0,qe-uo)*.2:Math.max(0,uo-qe)*.2}for(const To of Jt){const yo=To.nodeIndex*9+8;if(To.length>=Kt[yo])continue;Kt[yo]=To.length;const Ro=Ho[To.nodeIndex];Lt.push({node:To.nodeIndex,direction:8,score:To.length+C*Ro})}const vt=[[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1],[0,-1],[1,-1]],qt=Array.from({length:9},(To,yo)=>vt.flatMap((Ro,On)=>{const uo=Math.abs(yo-On);return yo===8||Math.min(uo,8-uo)<=1?[On]:[]})),Zt=new Map;for(const To of Jt){const yo=Zt.get(To.nodeIndex)??[];yo.push(To),Zt.set(To.nodeIndex,yo)}let nn=Number.POSITIVE_INFINITY,zn=null,Nn=0,Co=0,ei=0,ro=[];for(;Lt.size>0&&Nn<m;){const To=Lt.pop();if(To.score>=nn-d0)break;const yo=To.node*9+To.direction;if(ht?.[yo])continue;const Ro=Kt[yo];if(To.score>Ro+C*Ho[To.node]+d0)continue;ht&&(ht[yo]=1),Nn++,Co++,n&&Co%50===0&&ro.push(ge[To.node].point);const On=An.get(To.node);if(On){const Oo=[];let ko=yo;for(;ko>=0;)Oo.push(ge[Math.floor(ko/9)].point),ko=rn[ko];Oo.reverse();let Ko=yo;for(;rn[Ko]>=0;)Ko=rn[Ko];const mi=Math.floor(Ko/9),Fo=Zt.get(mi)??[],Nr=Math.min(...Fo.map(Rs=>Rs.length));for(const Rs of Fo)for(const ur of On){const zi=Ro-Nr+Rs.length+ur.length;if(zi>=nn-d0)continue;const bi=wbo([...Rs.points,...Oo.slice(1),...ur.points.toReversed().slice(1)]),Ar=Zj(bi,c,r);!Ar.every(Pbo)||!Mbo(Ar)||!Ar.every(ws=>Le({segment:ws,terminal:dt,acceptedAttemptSegmentIndex:Xt}))||(nn=zi,zn=bi)}}if(C>1&&zn)return{points:zn,expandedStateCount:Nn};const uo=ge[To.node];for(const Oo of qt[To.direction]){const[ko,Ko]=vt[Oo],mi=uo.column+ko,Fo=uo.row+Ko;if(mi<0||mi>=ie||Fo<0||Fo>=ne)continue;const Nr=Fo*ie+mi,Rs=ge[Nr].point,ur=To.direction!==8&&To.direction!==Oo,zi=Ao[Nr],bi=Ro+(ko!==0&&Ko!==0?F*Math.SQRT2:F)+(ur?F*.2:0)+zi+(_e?.[Nr]??0),Ar=Nr*9+Oo;if(ht?.[Ar]||bi>=Kt[Ar]-d0)continue;const ws=To.node*8+Oo;if($n[ws]===0){const Et=Le({segment:{start:uo.point,end:Rs,width:c,layer:r},terminal:dt,acceptedAttemptSegmentIndex:Xt});$n[ws]=Et?1:2,$n[Nr*8+(Oo+4)%8]=Et?1:2}if($n[ws]===2)continue;Kt[Ar]=bi,rn[Ar]=yo;const ds=Ho[Nr];Lt.push({node:Nr,direction:Oo,score:bi+C*ds})}Co>=ybo&&(Co=0,ei++,yield{expandedStateCount:Nn,...n?{visualization:tt({terminal:dt,acceptedAttemptSegments:Ut,expandedPoints:ro,frontierPoints:Lt.sampleEntries(120).map(Oo=>ge[Oo.node].point),bestPath:zn,expandedStateCount:Nn,searchBatch:ei,connectionComplete:!1})}:{}},ro=[])}return{points:zn,expandedStateCount:Nn}},at=s.toSorted((Ze,dt)=>CO(Ze.exitPoint,Qe)-CO(dt.exitPoint,Qe)||Ze.connection.connection.name.localeCompare(dt.connection.connection.name)),nt=s.map(Ze=>CO(Ze.viaPoint,Qe)),gt=at.map(Ze=>CO(Ze.exitPoint,Qe)),bt=nt.reduce((Ze,dt)=>Ze+dt,0)/nt.length,Ct=gt.reduce((Ze,dt)=>Ze+dt,0)/gt.length,Dt=Math.max(...nt)<Math.min(...gt)-d0,kt=Math.min(...nt)>Math.max(...gt)+d0,it=t.routeOrder?[t.laneBias??0]:y?Dt?[0,1,-1]:kt?[0,-1,1]:i.direction===Qe&&Ct>bt+d0?[1,0,-1]:i.direction===Qe&&Ct<bt-d0?[-1,0,1]:[0,1,-1]:Dt?[1,0,-1]:kt?[-1,0,1]:[0,1,-1],Yt=[];if(t.routeOrder){if(t.routeOrder.length!==s.length||new Set(t.routeOrder).size!==s.length||t.routeOrder.some(Ze=>!Number.isInteger(Ze)||Ze<0||Ze>=s.length))throw new Error("FanoutSolver: routeOrder must contain every terminal index exactly once");Yt.push(()=>t.routeOrder.map(Ze=>s[Ze]))}B&&y&&Dt&&Yt.push(()=>at),Dt?Yt.push(()=>[...at.slice(1),at[0]]):kt&&(Yt.push(()=>[...at].reverse()),S&&at.length>2&&Yt.push(()=>[...at.slice(0,-1).toReversed(),at.at(-1)])),Yt.push(...y&&i.direction===Qe&&Ct<bt-d0&&!Dt&&!kt?[()=>[...at].reverse(),()=>at]:[()=>at,()=>[...at].reverse()],()=>s.toSorted((Ze,dt)=>Ze.viaPoint.x-dt.viaPoint.x||Ze.viaPoint.y-dt.viaPoint.y),()=>s.toSorted((Ze,dt)=>dt.viaPoint.x-Ze.viaPoint.x||dt.viaPoint.y-Ze.viaPoint.y),()=>s.toSorted((Ze,dt)=>Ze.viaPoint.y-dt.viaPoint.y||Ze.viaPoint.x-dt.viaPoint.x),()=>s.toSorted((Ze,dt)=>dt.viaPoint.y-Ze.viaPoint.y||dt.viaPoint.x-Ze.viaPoint.x));const pn=p===void 0?void 0:Math.ceil(p/it.length),be=Sbo({initialOrderFactories:Yt,rotationBase:at,getItemKey:Ze=>Ze.connection.connection.name,maximumOrderCount:pn}),et=[],It=new Set,Bt=function*(){for(;;){const Ze=et.shift(),dt=Ze?{done:!1,value:Ze}:be.next();if(dt.done)return;const Ut=dt.value.map(Wt=>Wt.connection.connection.name).join("|");It.has(Ut)||(It.add(Ut),yield dt.value)}},mt=[],st=new Set,xt=new Map;let Xe=0;for(const Ze of Bt())for(const dt of it){if(p!==void 0&&Xe>=p)return mt;Xe++;const Ut=[],Wt=new Map;let Xt=!1;for(let An=0;An<Ze.length;An++){const kn=Ze[An],$n=JSON.stringify([s.indexOf(kn),dt,Ut.map(({connectionName:qt,segment:Zt})=>[qt,Zt.start.x,Zt.start.y,Zt.end.x,Zt.end.y,Zt.width,Zt.layer])]),ht=xt.get($n),Kt=At({terminal:kn,acceptedAttemptSegments:Ut,laneBias:dt});let rn=ht===void 0?Kt.next():{done:!0,value:{points:null,expandedStateCount:ht.expandedStateCount}},Lt=ht?.searchBatch??0,Ho=0;for(;!rn.done;)Ho=rn.value.expandedStateCount,yield{phase:"route-connection",routeOrderAttempt:Xe,connectionIndex:An,connectionCount:Ze.length,connectionName:kn.connection.connection.name,searchBatch:++Lt,expandedStateCount:Ho,connectionComplete:!1,...rn.value.visualization?{visualization:rn.value.visualization}:{}},rn=Kt.next();const{points:Ao,expandedStateCount:qe}=rn.value;if(Ho=qe,yield{phase:"route-connection",routeOrderAttempt:Xe,connectionIndex:An,connectionCount:Ze.length,connectionName:kn.connection.connection.name,searchBatch:Lt,expandedStateCount:Ho,connectionComplete:!0,...n?{visualization:tt({terminal:kn,acceptedAttemptSegments:Ut,expandedPoints:[],frontierPoints:[],bestPath:Ao,expandedStateCount:Ho,searchBatch:Lt,connectionComplete:!0})}:{}},!Ao){if(xt.set($n,{expandedStateCount:qe,searchBatch:Lt}),E&&p!==void 0&&An>0){const qt=Ze.filter(Zt=>Zt!==kn);et.push([kn,...qt])}Xt=!0;break}const vt=kn.connection.connection.name;Wt.set(vt,Ao),Ut.push(...Zj(Ao,c,r).map(qt=>({connectionName:vt,segment:qt})))}if(Xt)continue;const Jt=s.map(An=>{const kn=Wt.get(An.connection.connection.name);if(!kn)throw new Error(`FanoutSolver: via-minimal winding route omitted "${An.connection.connection.name}"`);return i4({bus:i,terminal:An,targetLayer:r,targetLayerPoints:kn,sourceEscapePoints:t.sourceEscapePaths?.get(An.connection.connectionIndex),layerNames:A,traceWidth:c,viaDiameter:l,viaHoleDiameter:u,allowBlindAndBuriedVias:h})}),yn=Jt.map(An=>An.segments.map(kn=>`${kn.start.x},${kn.start.y},${kn.end.x},${kn.end.y},${kn.layer}`).join(";")).join("|");if(!st.has(yn)&&(st.add(yn),mt.push(Jt),mt.length>=e))return mt}return mt}function Rbo(t,e=1){const n=BC(t,e);let o=n.next();for(;!o.done;)o=n.next();return o.value}function rNt(t){return Rbo(t,1)[0]??null}function CPe(t){return t.allowViaInPad===!0}function h0(t){return t==="left"||t==="right"}function t6(t){return t==="right"||t==="up"?1:-1}function aE(t,e){return h0(e)?t.x:t.y}function Xu(t,e){return h0(e)?t.y:t.x}function r4(t){return Ds(t.exitEdge,t.preferredExit)}function Tbo(t){return Ds(Xj(t.direction),t.preferredExit)}function yO(t){return!!(t.exitEdge&&t.termination.type==="boundary"&&t.connections.length>0&&t.connections.every(e=>e.hasExplicitLayeredExitTarget===!0))}function W0e(t){return"source_trace_id"in t&&typeof t.source_trace_id=="string"?t.source_trace_id:t.name}function sNt(t){const{bus:e,boundaryDirection:n,layerNames:o,targetLayer:i}=t,r=_=>_.exitTargetPoint?.layer??SPe(_.targetPoint),s=(_,f)=>{const I=Xu(_.exitTargetPoint??_.targetPoint,n)-Xu(f.exitTargetPoint??f.targetPoint,n);if(I!==0)return I;const C=W0e(_.connection),y=W0e(f.connection),x=C.localeCompare(y);return x!==0?x:_.connection.name.localeCompare(f.connection.name)||_.connectionIndex-f.connectionIndex},a=e.connections.toSorted((_,f)=>{const I=Xu(_.exitTargetPoint??_.targetPoint,n)-Xu(f.exitTargetPoint??f.targetPoint,n);return I!==0?I:_.connection.name.localeCompare(f.connection.name)||W0e(_.connection).localeCompare(W0e(f.connection))||o.indexOf(r(_))-o.indexOf(r(f))||_.connectionIndex-f.connectionIndex}),A=new Map;for(const _ of e.connections){const f=r(_),I=A.get(f)??[];I.push(_),A.set(f,I)}const c=[...A.keys()].toSorted((_,f)=>+(f===i)-+(_===i)||o.indexOf(_)-o.indexOf(f)||_.localeCompare(f)),l=new Map(c.map((_,f)=>[_,f])),u=new Map;for(const _ of c)for(const[f,I]of A.get(_).toSorted(s).entries())u.set(I.connectionIndex,f);const g=e.connections.toSorted((_,f)=>(u.get(_.connectionIndex)??0)-(u.get(f.connectionIndex)??0)||(l.get(r(_))??0)-(l.get(r(f))??0)||s(_,f)),h=[g];for(let _=0;_+1<g.length;_++){const f=g[_],I=g[_+1];if(r(f)===r(I))continue;const C=[...g];C[_]=I,C[_+1]=f,h.push(C)}h.push(a);const d=new Set(h.map(_=>_.map(f=>f.connectionIndex).join(","))).size;if(!r4(e)&&e.connections.length<=8&&c.length>1){const _=c.map(y=>A.get(y).toSorted(s)),f=_.map(()=>0),I=[],C=()=>{if(!(h.length>=128)){if(I.length===e.connections.length){h.push([...I]);return}for(let y=0;y<_.length;y++){const x=f[y],E=_[y][x];E&&(f[y]=x+1,I.push(E),C(),I.pop(),f[y]=x)}}};C()}const p=new Set;return{orders:h.filter(_=>{const f=_.map(I=>I.connectionIndex).join(",");return p.has(f)?!1:(p.add(f),!0)}),legacyOrder:a,ordinaryOrderCount:d}}function aNt(t){const{connection:e,windingOrderIndex:n=0}=t,{orders:o,legacyOrder:i}=sNt(t),r=t.windingOrderIndex===void 0?i:o[n]??o[0]??i,s=r.findIndex(a=>a.connectionIndex===e.connectionIndex);if(s<0)throw new Error(`FanoutSolver: connection "${e.connection.name}" is missing from winding order`);return{rank:s,connectionCount:r.length}}function kbo(t){const{bus:e,escapeLayer:n}=t;return(e.routableEscapeLayers??e.allowedLayers)?.find(o=>o!==n)}function yPe(t){const{bus:e,boundaryDirection:n,traceWidth:o,clearance:i}=t;if(r4(e)||!yO(e))return;const r=new Set(e.connections.map(u=>u.exitTargetPoint?.layer??SPe(u.targetPoint))),s=h0(n)?e.sharedBoundary.minY:e.sharedBoundary.minX,a=h0(n)?e.sharedBoundary.maxY:e.sharedBoundary.maxX,A=e.connections.map(u=>Math.max(s,Math.min(a,Xu(u.exitTargetPoint??u.targetPoint,n)))).toSorted((u,g)=>u-g),c=o+i;if((r.size<2||!t.allowLayerInterleaving)&&A.every((u,g)=>g===0||u-A[g-1]>=c-1e-9)||a-s<(A.length-1)*c-1e-9)return;const l=[];for(const[u,g]of A.entries())for(l.push({start:u,count:1,mean:g-u*c});l.length>1&&l.at(-2).mean>l.at(-1).mean;){const h=l.pop(),d=l.pop();l.push({start:d.start,count:d.count+h.count,mean:(d.mean*d.count+h.mean*h.count)/(d.count+h.count)})}for(const u of l){const g=Math.max(s,Math.min(a-(A.length-1)*c,u.mean));for(let h=u.start;h<u.start+u.count;h++)A[h]=g+h*c}return A}function tR(t){const e=t.fixedBoundaryTracksByConnectionIndex?.get(t.connection.connectionIndex);if(e!==void 0)return e;const n=Xu(t.connection.exitTargetPoint??t.connection.targetPoint,t.boundaryDirection),o=h0(t.boundaryDirection)?t.bus.sharedBoundary.minY:t.bus.sharedBoundary.minX,i=h0(t.boundaryDirection)?t.bus.sharedBoundary.maxY:t.bus.sharedBoundary.maxX,r=t.traceWidth!==void 0&&t.clearance!==void 0?yPe({...t,traceWidth:t.traceWidth,clearance:t.clearance}):void 0;if(r&&t.layerNames&&t.targetLayer){const{rank:s}=aNt({...t,layerNames:t.layerNames,targetLayer:t.targetLayer});return r[s]}return Math.max(o,Math.min(i,n))}function BB(t){const e=t.fixedBoundaryTracksByConnectionIndex?.get(t.connection.connectionIndex);if(e!==void 0)return e;const{bus:n,connection:o,cornerExitLaneOffset:i,traceWidth:r,viaDiameter:s,clearance:a,layerNames:A,targetLayer:c,windingOrderIndex:l,cornerBandTargetTrackOffset:u=0}=t,g=r4(n);if(!g||!n.exitEdge)return Xu(o.exitTargetPoint??o.targetPoint,n.direction);const h=e6(n.exitEdge),d=h0(h)?n.sharedBoundary.minY:n.sharedBoundary.minX,p=h0(h)?n.sharedBoundary.maxY:n.sharedBoundary.maxX,m=Math.max(r+a,s+a),_=d+(p-d)*(g==="minimum"?.25:.75)+u,f=yO(n)?aNt({bus:n,connection:o,boundaryDirection:h,layerNames:A,targetLayer:c,windingOrderIndex:l}):void 0,I=Math.max(n.connections.length,n.cornerBandConnectionCount??n.connections.length,i+(f?.connectionCount??0)),C=_-(I-1)*m/2,y=f?.rank??e$(n,o),x=i+y,B=!f&&g==="maximum"==t6(h)>0?I-1-x:x;return C+B*m}function ANt(t,e){const n=r4(t);if(!n||!t.exitEdge)return{exit:0,localChannel:0,boundaryChannel:0};const o=e.filter(s=>s.exitEdge&&s.cornerBandSide!==void 0),i=o.filter(s=>s.exitEdge===t.exitEdge&&s.cornerBandSide===n),r=o.filter(s=>s.direction===t.direction);return{exit:i.length,localChannel:r.length,boundaryChannel:i.length}}function n1(t,e,n){return h0(n)?{x:t,y:e}:{x:e,y:t}}function n6(t,e=t.direction){switch(e){case"right":return t.sharedBoundary.maxX;case"left":return t.sharedBoundary.minX;case"up":return t.sharedBoundary.maxY;case"down":return t.sharedBoundary.minY}}function xO(t){return h0(t.direction)?t.pitchX:t.pitchY}function cNt(t){return h0(t.direction)?t.pitchY:t.pitchX}function lNt(t,e){if(t.length<3)return[...t];const n=[t[0]];for(let o=1;o<t.length-1;o++){const i=t[o-1],r=t[o],s=t[o+1],a={x:r.x-i.x,y:r.y-i.y},A={x:s.x-r.x,y:s.y-r.y},c=Math.hypot(a.x,a.y),l=Math.hypot(A.x,A.y),u=Math.abs(a.x)<=1e-9||Math.abs(a.y)<=1e-9,g=Math.abs(A.x)<=1e-9||Math.abs(A.y)<=1e-9,h=Math.abs(a.x*A.x+a.y*A.y)<=1e-9;if(c<=1e-9||l<=1e-9||!u||!g||!h){n.push(r);continue}const d=Math.min(e,c/3,l/3);n.push({x:r.x-a.x/c*d,y:r.y-a.y/c*d}),n.push({x:r.x+A.x/l*d,y:r.y+A.y/l*d})}return n.push(t.at(-1)),n.filter((o,i)=>i===0||tn(o,n[i-1])>1e-9)}function uNt(t,e){const n=e.x-t.x,o=e.y-t.y,i=Math.abs(n),r=Math.abs(o);return i<=1e-9||r<=1e-9||Math.abs(i-r)<=1e-9?[[t,e]]:i>r?[[t,{x:t.x+Math.sign(n)*r,y:e.y},e],[t,{x:e.x-Math.sign(n)*r,y:t.y},e]]:[[t,{x:e.x,y:t.y+Math.sign(o)*i},e],[t,{x:t.x,y:e.y-Math.sign(o)*i},e]]}function Fbo(t){const e=(h0(t.direction)?t.xCoordinates:t.yCoordinates).toSorted((i,r)=>i-r),n=t.connections.reduce((i,r)=>i+aE(r.sourcePoint,t.direction),0)/t.connections.length,o=t6(t.direction)>0?e.at(-1):e[0];return Math.abs(o-n)/xO(t)}function xPe(t){const e=h0(t.direction)?t.xCoordinates:t.yCoordinates,n=t.connections.reduce((i,r)=>i+aE(r.sourcePoint,t.direction),0)/t.connections.length,o=t6(t.direction)>0?Math.max(...e):Math.min(...e);return Math.abs(n-o)<1e-6}function e$(t,e){const n=[...t.connections].sort((o,i)=>Xu(o.sourcePoint,t.direction)-Xu(i.sourcePoint,t.direction)).findIndex(o=>o.connectionIndex===e.connectionIndex);if(n<0)throw new Error(`FanoutSolver: connection "${e.connection.name}" is missing from bus "${t.busId}"`);return n}function Lbo(t,e){return{minX:Math.min(t.minX,e.minX),maxX:Math.max(t.maxX,e.maxX),minY:Math.min(t.minY,e.minY),maxY:Math.max(t.maxY,e.maxY)}}function EPe(t,e){return t.x>=e.minX-1e-6&&t.x<=e.maxX+1e-6&&t.y>=e.minY-1e-6&&t.y<=e.maxY+1e-6}function BPe(t,e,n,o,i){const r=e-t,s=Math.floor((r-o)/(n+o)+1e-9);if(s<1)return[];const a=s*n+(s-1)*o,A=t+(r-a)/2+n/2;return Array.from({length:s},(c,l)=>({value:A+l*(n+o),kind:i}))}function Hbo(t){const{bus:e,connection:n,preferredTrack:o,traceWidth:i,clearance:r}=t,s=(h0(e.direction)?e.yCoordinates:e.xCoordinates).toSorted((m,_)=>m-_),a=Math.max(...e.componentObstacles.map(m=>h0(e.direction)?m.height/2:m.width/2)),A=h0(e.direction)?e.sharedBoundary.minY:e.sharedBoundary.minX,c=h0(e.direction)?e.sharedBoundary.maxY:e.sharedBoundary.maxX,l=c-A,u=A,g=c,h=[{value:o,kind:"preferred"},...BPe(u,s[0]-a,i,r,"margin")];for(let m=0;m<s.length;m++)h.push({value:s[m],kind:"corridor"}),m<s.length-1&&h.push(...BPe(s[m]+a,s[m+1]-a,i,r,"gap"));h.push(...BPe(s.at(-1)+a,g,i,r,"margin"));const d=Xu(n.sourcePoint,e.direction),p=(s[0]+s.at(-1))/2;return h.filter(m=>Math.abs(m.value-d)<=l+1e-9).filter((m,_,f)=>f.findIndex(I=>Math.abs(I.value-m.value)<1e-9)===_).sort((m,_)=>Math.abs(m.value-o)-Math.abs(_.value-o)-(Math.abs(m.value-p)-Math.abs(_.value-p))*.001)}function Obo(t){const e=r4(t.bus)||yO(t.bus)?Xu(t.connection.sourcePoint,t.bus.direction):Xu(t.connection.exitTargetPoint??t.connection.targetPoint,t.bus.direction),n=h0(t.bus.direction)?t.bus.sharedBoundary.minY:t.bus.sharedBoundary.minX,o=h0(t.bus.direction)?t.bus.sharedBoundary.maxY:t.bus.sharedBoundary.maxX;return Math.max(n+t.traceWidth/2,Math.min(o-t.traceWidth/2,e))}function Gbo(t){const{bus:e,connection:n,targetUsesVia:o,interstitialEscape:i,compactBusTracks:r,traceWidth:s,viaDiameter:a,clearance:A}=t,c=(h0(e.direction)?e.yCoordinates:e.xCoordinates).toSorted((B,S)=>B-S),l=Xu(n.sourcePoint,e.direction);if(r){const B=e$(e,n);return(c[0]+c.at(-1))/2+(B-(e.connections.length-1)/2)*(s+A)}if(!o||!i)return l;const u=Fbo(e),g=s+A,h=Math.ceil(e.connections.length/2),d=(h-1)*g,p=a/2+s/2+A+.001,m=Math.round(u)+1,_=m*p+(m-1)*d,f=e$(e,n),I=c[0],C=c.at(-1),y=f<h?I-_-(h-f-1)*g:C+_+(f-h)*g,x=h0(e.direction)?e.sharedBoundary.minY:e.sharedBoundary.minX,E=h0(e.direction)?e.sharedBoundary.maxY:e.sharedBoundary.maxX;return Math.max(x+s/2,Math.min(E-s/2,y))}function gNt(t){const e=t6(t.direction),n=[...t.connections].sort((r,s)=>{const a=e*(aE(s.sourcePoint,t.direction)-aE(r.sourcePoint,t.direction));return Math.abs(a)>1e-6?a:Xu(r.sourcePoint,t.direction)-Xu(s.sourcePoint,t.direction)}),o=[...t.connections].sort((r,s)=>Xu(r.sourcePoint,t.direction)-Xu(s.sourcePoint,t.direction)||e*(aE(s.sourcePoint,t.direction)-aE(r.sourcePoint,t.direction))),i=[n,[...n].reverse(),o,[...o].reverse()];for(let r=1;r<Math.min(n.length,8);r++)i.push([...n.slice(r),...n.slice(0,r)]);return i}function dNt(t,e,n,o,i){tn(e,n)<1e-9||t.push({start:e,end:n,width:o,layer:i})}function bPe(t,e){if(t.length<3)return t;const n=[t[0]];for(let o=1;o<t.length-1;o++){const i=t[o-1],r=t[o],s=t[o+1],a=tn(i,r),A=tn(r,s);if(a<1e-9||A<1e-9)continue;const c={x:(r.x-i.x)/a,y:(r.y-i.y)/a},l={x:(s.x-r.x)/A,y:(s.y-r.y)/A},u=c.x*l.x+c.y*l.y;if(Math.abs(u)>1e-6){n.push(r);continue}const g=Math.min(e,a/2,A/2);n.push({x:r.x-c.x*g,y:r.y-c.y*g}),n.push({x:r.x+l.x*g,y:r.y+l.y*g})}return n.push(t.at(-1)),n}function j0e(t){const{preparedConnection:e,bus:n,targetLayer:o,traceWidth:i,viaDiameter:r,clearance:s,viaHandedness:a}=t,A={x:e.sourcePoint.x,y:e.sourcePoint.y},c=o!==e.sourceLayer,l=xO(n),u=cNt(n),g=h0(n.direction)?e.sourceObstacle.width:e.sourceObstacle.height,h=c&&!xPe(n)?g>=l?g/2+r/2+s+.001:l*.5:c?Math.max(l*.5,g/2+(c?r:i)/2+s+.001):g/2+i/2+s+.001,d=aE(A,n.direction)+t6(n.direction)*h,p=Xu(A,n.direction)+a*u*.5;return n1(d,p,n.direction)}function $0e(t){const{preparedConnection:e,bus:n,targetLayer:o,track:i,exitAxis:r,layerNames:s,traceWidth:a,viaDiameter:A,viaHoleDiameter:c,viaHandedness:l,interstitialEscape:u,spreadLaneIndex:g,cornerExitLaneOffset:h,cornerLocalChannelLaneOffset:d,cornerBoundaryChannelLaneOffset:p,clearance:m,terminateAtVia:_,allowBlindAndBuriedVias:f,initialViaPoint:I,sourceEscapePath:C,cornerBandTargetTrackOffset:y,fixedBoundaryTracksByConnectionIndex:x}=t,E=x?.get(e.connectionIndex),B=r4(n),S=n.exitEdge?e6(n.exitEdge):n.direction,Q=E!==void 0&&!B&&n.direction===S?E:i,w={x:e.sourcePoint.x,y:e.sourcePoint.y},M=o,k=yO(n)?kbo({bus:n,escapeLayer:M}):void 0,R=!!k,F=t6(n.direction),O=xO(n),U=C?.at(-1),Y=U!==void 0?{x:U.x,y:U.y}:I===void 0?j0e({preparedConnection:e,bus:n,targetLayer:o,traceWidth:a,viaDiameter:A,clearance:m,viaHandedness:l}):{x:I.x,y:I.y},W=C?C.map(Ct=>({x:Ct.x,y:Ct.y})):[w,Y];if(W.length<2||tn(W[0],w)>1e-9||tn(W.at(-1),Y)>1e-9)throw new Error(`FanoutSolver: source escape path for "${e.connection.name}" must run from its source point to its via`);const te=aE(Y,n.direction),j=Xu(Y,n.direction),J=A/2+a/2+m+.001+g*(a+m),oe=u&&O>=J+A/2+m,ie=oe?n1(te+F*J,j,n.direction):Y,ne=oe?aE(ie,n.direction):te+F*Math.abs(Q-j),le=n1(ne,Q,n.direction),ge=t6(S),_e=n6(n,S),ue=E??(B&&n.exitEdge?BB({bus:n,connection:e,cornerExitLaneOffset:h,traceWidth:a,viaDiameter:A,clearance:m,layerNames:s,targetLayer:o,cornerBandTargetTrackOffset:y}):R?tR({bus:n,connection:e,boundaryDirection:S,traceWidth:a,clearance:m,layerNames:s,targetLayer:o}):Q),fe=e$(n,e),ye=Tbo(n)==="maximum"?d+fe:d+n.connections.length-1-fe,Me=p+fe,ve=Math.max(n.connections.length,n.cornerBandConnectionCount??n.connections.length),he=ge>0?Me:ve-1-Me,Qe=R?A/2+a/2+m:a+m,Pe=Ct=>A/2+a/2+m+Ct*Qe,we=n6(n,n.direction)-F*Pe(ye),Te=_e-ge*Pe(he),Re=n1(we,Q,n.direction),Ee=n1(Te,we,S),ke=n1(Te,ue,S),Ce=h0(n.direction)!==h0(S)?Ee:n1(Te,Q,S),Le=_?Y:B||R||E!==void 0?n1(_e,ue,S):n1(r,Q,n.direction),Ye=[],tt=[];tt.push({route_type:"wire",x:w.x,y:w.y,width:a,layer:e.sourceLayer,start_pcb_port_id:e.sourcePoint.pcb_port_id});for(let Ct=1;Ct<W.length;Ct++){const Dt=W[Ct-1],kt=W[Ct];dNt(Ye,Dt,kt,a,e.sourceLayer),!(tn(Dt,kt)<=1e-9)&&tt.push({route_type:"wire",x:kt.x,y:kt.y,width:a,layer:e.sourceLayer})}const At=Ye.length;let at;if(o!==e.sourceLayer){const Ct=Mx({fromLayer:e.sourceLayer,toLayer:o,layerNames:s,allowBlindAndBuriedVias:f});at={center:Y,diameter:A,holeDiameter:c,fromLayer:e.sourceLayer,toLayer:o,spanLayers:Ct},tt.push({route_type:"via",x:Y.x,y:Y.y,from_layer:e.sourceLayer,to_layer:o,via_diameter:A,via_hole_diameter:c}),tt.push({route_type:"wire",x:Y.x,y:Y.y,width:a,layer:o})}const nt=(Ct,Dt)=>{for(let kt=1;kt<Ct.length;kt++){const it=Ct[kt-1],Yt=Ct[kt];dNt(Ye,it,Yt,a,Dt),tt.push({route_type:"wire",x:Yt.x,y:Yt.y,width:a,layer:Dt})}},gt=[];if(R&&k){const Ct=bPe([Y,...oe?[ie]:[],le,...h0(n.direction)!==h0(S)?[Re]:[],Ce],Math.max(a+m,a*2));nt(Ct,M);const Dt=(kt,it,Yt)=>{it!==Yt&&(gt.push({center:kt,diameter:A,holeDiameter:c,fromLayer:it,toLayer:Yt,spanLayers:Mx({fromLayer:it,toLayer:Yt,layerNames:s,allowBlindAndBuriedVias:f})}),tt.push({route_type:"via",x:kt.x,y:kt.y,from_layer:it,to_layer:Yt,via_diameter:A,via_hole_diameter:c}),tt.push({route_type:"wire",x:kt.x,y:kt.y,width:a,layer:Yt}))};Dt(Ce,M,k),nt([Ce,ke],k),Dt(ke,k,M),nt([ke,Le],M)}else{const Ct=_?[Y]:B?bPe([Y,...oe?[ie]:[],le,Re,...h0(n.direction)!==h0(S)?[Ee]:[],ke,Le],Math.max(a+m,a*2)):oe?bPe([Y,ie,le,Le],Math.max(a+m,a*2)):[Y,le,Le];nt(Ct,M)}const bt=qN({connectionName:e.connection.name,sourcePointIndex:e.sourcePointIndex});return{busId:n.busId,connectionName:e.connection.name,connectionIndex:e.connectionIndex,sourcePointIndex:e.sourcePointIndex,sourcePoint:e.sourcePoint,sourceObstacle:e.sourceObstacle,sourceLayer:e.sourceLayer,targetPoint:e.targetPoint,targetLayer:o,termination:n.termination,direction:n.direction,...n.exitEdge?{exitEdge:n.exitEdge}:{},...B?{cornerBandSide:B}:{},exitPoint:Le,trace:{type:"pcb_trace",pcb_trace_id:bt.traceId,connection_name:e.connection.name,connectsTo:[...e.sourcePoint.pointId?[e.sourcePoint.pointId]:[],...e.sourcePoint.pcb_port_id?[e.sourcePoint.pcb_port_id]:[],bt.boundaryExitPointId],route:tt},segments:Ye,...At>1?{sourceEscapeSegmentCount:At}:{},via:at,...gt.length>0?{additionalVias:gt}:{},length:Ye.reduce((Ct,Dt)=>Ct+tn(Dt.start,Dt.end),0)}}function SPe(t){const e="layer"in t?t.layer:t.layers[0];if(!e)throw new Error("FanoutSolver: plane endpoint has no copper layer");return e}function QPe(t){const{preparedConnection:e,bus:n,viaDiameter:o,clearance:i}=t,{sourcePoint:r,targetPoint:s}=e,a=Math.max(n.pitchX,n.pitchY)*.5;if(tn(r,s)<=1e-6||tn(r,s)>a)return[];const A=(()=>{switch(n.direction){case"left":return{x:-1,y:0};case"right":return{x:1,y:0};case"up":return{x:0,y:1};case"down":return{x:0,y:-1}}})(),c=Math.SQRT1_2,l=[A,...[{x:c,y:c},{x:c,y:-c},{x:-c,y:c},{x:-c,y:-c},{x:1,y:0},{x:-1,y:0},{x:0,y:1},{x:0,y:-1}].toSorted((d,p)=>p.x*A.x+p.y*A.y-(d.x*A.x+d.y*A.y))],u=Math.max(o,o/2+i),g=[u,Math.max(u,Math.min(n.pitchX,n.pitchY)*.5),Math.max(u,Math.min(n.pitchX,n.pitchY)*.625),Math.max(u,Math.min(n.pitchX,n.pitchY)*.75)],h=[];for(const d of[r,s])for(const p of g)for(const m of l){const _={x:d.x+m.x*p,y:d.y+m.y*p};tn(_,r)<=1e-6||tn(_,s)<=1e-6||h.some(f=>tn(f,_)<=1e-6)||h.push(_)}return h}function vPe(t){const{plan:e,preparedConnection:n,planeLayer:o,viaPoint:i,layerNames:r,traceWidth:s,viaDiameter:a,viaHoleDiameter:A,allowBlindAndBuriedVias:c}=t,l={x:n.targetPoint.x,y:n.targetPoint.y},u=SPe(n.targetPoint),g=Mx({fromLayer:o,toLayer:u,layerNames:r,allowBlindAndBuriedVias:c});if(!g.includes(o))throw new Error(`FanoutSolver: via for "${n.connection.name}" does not cross plane ${o}`);const h=[{start:i,end:l,width:s,layer:u}],d={center:i,diameter:a,holeDiameter:A,fromLayer:o,toLayer:u,spanLayers:g},p=qN({connectionName:n.connection.name,sourcePointIndex:n.sourcePointIndex}),m={type:"pcb_trace",pcb_trace_id:p.planeEndpointTraceId,connection_name:n.connection.name,connectsTo:[...n.targetPoint.pointId?[n.targetPoint.pointId]:[],...n.targetPoint.pcb_port_id?[n.targetPoint.pcb_port_id]:[],p.planeEndpointPointId],route:[{route_type:"wire",...i,width:s,layer:o},{route_type:"via",...i,from_layer:o,to_layer:u,via_diameter:a,via_hole_diameter:A},{route_type:"wire",...i,width:s,layer:u},{route_type:"wire",...l,width:s,layer:u}]};return{...e,planeEndpointTrace:m,planeEndpointSegments:h,planeEndpointVia:d,length:e.length+h.reduce((_,f)=>_+tn(f.start,f.end),0)}}function Ybo(t){const{segment:e,plan:n,segmentIndex:o,srj:i,allowSameNetMerges:r,obstacles:s,clearance:a}=t;for(const A of s)if(A.layers.includes(e.layer)&&!A.connectedTo.includes(n.connectionName)&&!(r&&n4(i,A,n.connectionName))&&!jj({inputSrj:i,segment:e,bodyObstacle:A,connectionName:n.connectionName})&&!(o>=0&&o<(n.sourceEscapeSegmentCount??1)&&A===n.sourceObstacle&&e.layer===n.sourceLayer)&&Tl(e,A)<e.width/2+a-1e-9)return!1;return!0}function kb(t){return t.planeEndpointSegments?.length?[...t.segments,...t.planeEndpointSegments]:t.segments}function EO(t){return[t.via,...t.additionalVias??[],t.planeEndpointVia].filter(e=>!!e)}function Ubo(t,e){return tn(e.center,t.sourcePoint)<=1e-9&&z0e({center:e.center,diameter:e.diameter,obstacle:t.sourceObstacle})}function wPe(t){const{plan:e,srj:n,sharedBoundary:o,clearance:i,allowBlindAndBuriedVias:r,allowSameNetMerges:s}=t,a=Lbo(n.bounds,o);if(!EPe(e.exitPoint,a)||kb(e).some(l=>!EPe(l.start,a)||!EPe(l.end,a)))return!1;const A=kb(e);let c;if(t.segmentCache){let l=t.segmentCache.byConnection.get(e.connectionName);l||(l=new WeakMap,t.segmentCache.byConnection.set(e.connectionName,l)),c=l.get(e.sourceObstacle),c||(c=[new WeakMap,new WeakMap],l.set(e.sourceObstacle,c))}for(let l=0;l<A.length;l++){const u=A[l],g=l<e.segments.length?l:-1,h=g>=0&&g<(e.sourceEscapeSegmentCount??1)&&u.layer===e.sourceLayer,d=c?.[h?1:0];let p=d?.get(u);if(p===void 0&&(p=Ybo({segment:u,plan:e,segmentIndex:g,srj:n,allowSameNetMerges:s,obstacles:t.segmentCache?t.segmentCache.obstaclesByLayer.get(u.layer)??[]:n.obstacles,clearance:i}),d?.set(u,p)),!p)return!1}for(const l of EO(e))for(const u of n.obstacles)if(!(CPe(n)&&u===e.sourceObstacle&&Ubo(e,l))&&u.layers.some(g=>l.spanLayers.includes(g))&&!(s&&n4(n,u,e.connectionName))&&wx(l.center,u)<l.diameter/2+i-1e-9)return!1;for(const l of Z7(n,r))if(!(e.connectionName===l.connectionName||s&&Px(n,e.connectionName,l.connectionName))){for(const u of kb(e)){for(const g of l.segments)if(!Zm(u,g,i))return!1;for(const g of l.vias)if(g.spanLayers.includes(u.layer)&&Cr(g.center,u.start,u.end)<g.diameter/2+u.width/2+i-1e-9)return!1}for(const u of EO(e)){for(const g of l.segments)if(u.spanLayers.includes(g.layer)&&Cr(u.center,g.start,g.end)<u.diameter/2+g.width/2+i-1e-9)return!1;for(const g of l.vias)if(u.spanLayers.some(h=>g.spanLayers.includes(h))&&tn(u.center,g.center)<(u.diameter+g.diameter)/2+i-1e-9)return!1}}return!0}function q0e(t){const{plan:e,otherPlans:n,srj:o,allowSameNetMerges:i,clearance:r,blockingBusCounts:s,segmentIndexes:a}=t,A=kb(e),c=EO(e);for(const l of n){if(i&&Px(o,e.connectionName,l.connectionName)||e.sourcePoint.pcb_port_id&&e.sourcePoint.pcb_port_id===l.sourcePoint.pcb_port_id||e.sourcePoint.pointId&&e.sourcePoint.pointId===l.sourcePoint.pointId)continue;const g=()=>{l.busId!==e.busId&&s?.set(l.busId,(s.get(l.busId)??0)+1)},h=kb(l),d=EO(l);let p=a?.get(l);a&&!p&&(p=new qj(h),a.set(l,p));for(const m of A){for(const _ of p?.querySegment(m,r)??h)if(!Zm(m,_,r))return g(),!1;for(const _ of d)if(_.spanLayers.includes(m.layer)&&Cr(_.center,m.start,m.end)<_.diameter/2+m.width/2+r-1e-9)return g(),!1}for(const m of c){for(const _ of p?.queryVia(m,r)??h)if(m.spanLayers.includes(_.layer)&&Cr(m.center,_.start,_.end)<m.diameter/2+_.width/2+r-1e-9)return g(),!1;for(const _ of d)if(m.spanLayers.some(f=>_.spanLayers.includes(f))&&tn(m.center,_.center)<(m.diameter+_.diameter)/2+r-1e-9)return g(),!1}}return!0}function hNt(t){const{plans:e,srj:n,clearance:o,allowSameNetMerges:i=!1}=t;return e.every((r,s)=>q0e({plan:r,otherPlans:e.filter((a,A)=>A!==s),srj:n,allowSameNetMerges:i,clearance:o}))}function X0e(t){const{plan:e,otherPlans:n,staticClearanceCache:o,blockingBusCounts:i,cacheKey:r,srj:s,sharedBoundary:a,clearance:A,allowBlindAndBuriedVias:c,allowSameNetMerges:l}=t;let u=o?.get(r);return u===void 0&&(u=wPe({plan:e,srj:s,sharedBoundary:a,clearance:A,allowBlindAndBuriedVias:c,allowSameNetMerges:l}),o?.set(r,u)),u&&q0e({plan:e,otherPlans:n,srj:s,allowSameNetMerges:l,clearance:A,blockingBusCounts:i})}function Wh(t){const{plans:e,srj:n,sharedBoundary:o,clearance:i,allowBlindAndBuriedVias:r=!0,allowSameNetMerges:s=!1,allowSameNetPlaneMerges:a=!1}=t;for(let A=0;A<e.length;A++){const c=e[A];if(!wPe({plan:c,srj:n,sharedBoundary:o,clearance:i,allowBlindAndBuriedVias:r,allowSameNetMerges:s||a&&c.termination.type==="plane"}))return!1;const l=e.filter((u,g)=>g!==A&&!(a&&c.termination.type==="plane"&&u.termination.type==="plane"&&Px(n,c.connectionName,u.connectionName)));if(!q0e({plan:c,otherPlans:l,srj:n,allowSameNetMerges:s,clearance:i}))return!1}return!0}function Z0e(t){const{srj:e,sharedBoundary:n,clearance:o,allowBlindAndBuriedVias:i=!0,allowSameNetMerges:r=!1,allowSameNetPlaneMerges:s=!1}=t,a={obstaclesByLayer:new Map,byConnection:new Map};for(const m of e.obstacles)for(const _ of m.layers){const f=a.obstaclesByLayer.get(_)??[];f.push(m),a.obstaclesByLayer.set(_,f)}const A=s&&!r?{obstaclesByLayer:a.obstaclesByLayer,byConnection:new Map}:a,c=new WeakMap,l=new WeakMap,u=new WeakMap;let g=new Set;const h=m=>{let _=l.get(m);return _===void 0&&(_=wPe({segmentCache:m.termination.type==="plane"?A:a,plan:m,srj:e,sharedBoundary:n,clearance:o,allowBlindAndBuriedVias:i,allowSameNetMerges:r||s&&m.termination.type==="plane"}),l.set(m,_)),_},d=(m,_)=>{let f=u.get(m);f||(f=new WeakMap,u.set(m,f));let I=f.get(_);if(I===void 0){const C=kb(m).length>kb(_).length;I=q0e({plan:C?_:m,otherPlans:[C?m:_],segmentIndexes:c,srj:e,clearance:o,allowSameNetMerges:r||s&&m.termination.type==="plane"&&_.termination.type==="plane"}),f.set(_,I);let y=u.get(_);y||(y=new WeakMap,u.set(_,y)),y.set(m,I)}return I};return Object.assign(m=>{const _=new Set(m);if(_.size===m.length){const f=m.filter(I=>!g.has(I));for(const I of m){const C=g.has(I);if(!C&&!h(I))return!1;for(const y of C?f:m)if(I!==y&&!d(I,y))return!1}}else for(const[f,I]of m.entries()){if(!h(I))return!1;for(const[C,y]of m.entries())if(C!==f&&!d(I,y))return!1}return g=_,!0},{mutuallyClear:m=>m.every((_,f)=>m.every((I,C)=>C===f?!0:d(_,I)))})}function pNt(t){const{srj:e,bus:n,targetLayer:o,acceptedPlans:i,layerNames:r,traceWidth:s,viaDiameter:a,viaHoleDiameter:A,clearance:c,staticClearanceCache:l,blockingBusCounts:u,allowBlindAndBuriedVias:g=!0,allowSameNetMerges:h=!1,fixedViaPointsByConnectionIndex:d,planeCandidateSkipCount:p=0}=t,m=n.connections[0]?.sourceObstacle;if(!m||n.termination.type!=="plane")return null;const _=n.connections[0].sourceLayer;if(o===_)return null;let f=p;const I=(x,E)=>{for(const[B,S]of x.entries())if(E(S,B)){if(f>0){f--;continue}if(!(t.collectAlternative&&!t.collectAlternative(S)))return S}};if(d){const x=[];for(const E of n.connections){const B=d.get(E.connectionIndex);if(!B)return null;const S={x:E.sourcePoint.x,y:E.sourcePoint.y},Q=$0e({preparedConnection:E,bus:n,targetLayer:o,track:Xu(S,n.direction),exitAxis:n6(n),layerNames:r,traceWidth:s,viaDiameter:a,viaHoleDiameter:A,viaHandedness:0,interstitialEscape:!1,spreadLaneIndex:0,cornerExitLaneOffset:0,cornerLocalChannelLaneOffset:0,cornerBoundaryChannelLaneOffset:0,clearance:c,terminateAtVia:!0,allowBlindAndBuriedVias:g,initialViaPoint:B,sourceEscapePath:t.sourceEscapePaths?.get(E.connectionIndex)?[...t.sourceEscapePaths.get(E.connectionIndex)]:[S,B]}),M=[...QPe({preparedConnection:E,bus:n,viaDiameter:a,clearance:c}).map(R=>vPe({plan:Q,preparedConnection:E,planeLayer:o,viaPoint:R,layerNames:r,traceWidth:s,viaDiameter:a,viaHoleDiameter:A,allowBlindAndBuriedVias:g})),Q],k=I(M,(R,F)=>X0e({plan:R,otherPlans:[...i,...x],staticClearanceCache:l,blockingBusCounts:u,cacheKey:`plane-fixed:${n.busId}:${o}:${E.connectionIndex}:${B.x}:${B.y}:${F}`,srj:e,sharedBoundary:n.sharedBoundary,clearance:c,allowBlindAndBuriedVias:g,allowSameNetMerges:h}));if(!k)return null;x.push(k)}return x}if(CPe(e)&&n.connections.length===1&&z0e({center:n.connections[0].sourcePoint,diameter:a,obstacle:m})){const x=n.connections[0],E=$0e({preparedConnection:x,bus:n,targetLayer:o,track:Xu(x.sourcePoint,n.direction),exitAxis:n6(n),layerNames:r,traceWidth:s,viaDiameter:a,viaHoleDiameter:A,viaHandedness:0,interstitialEscape:!1,spreadLaneIndex:0,cornerExitLaneOffset:0,cornerLocalChannelLaneOffset:0,cornerBoundaryChannelLaneOffset:0,clearance:c,terminateAtVia:!0,allowBlindAndBuriedVias:g,initialViaPoint:x.sourcePoint}),S=[...QPe({preparedConnection:x,bus:n,viaDiameter:a,clearance:c}).map(w=>vPe({plan:E,preparedConnection:x,planeLayer:o,viaPoint:w,layerNames:r,traceWidth:s,viaDiameter:a,viaHoleDiameter:A,allowBlindAndBuriedVias:g})),E],Q=I(S,(w,M)=>X0e({plan:w,otherPlans:i,staticClearanceCache:l,blockingBusCounts:u,cacheKey:`plane-via-in-pad:${n.busId}:${o}:${M}`,srj:e,sharedBoundary:n.sharedBoundary,clearance:c,allowBlindAndBuriedVias:g,allowSameNetMerges:h}));if(Q)return[Q]}const C=[n.direction,...["left","right","up","down"].filter(x=>x!==n.direction)],y=[...C.map(x=>({direction:x,centeredOutward:!1})),...C.map(x=>({direction:x,centeredOutward:!0}))];for(const{direction:x,centeredOutward:E}of y){const B=x===n.direction?n:{...n,direction:x},S=h0(x)?m.width:m.height,Q=xO(B)/2-S/2>=a/2+c-1e-9,w=E?!Q&&xPe(B)?[0]:[]:Q?[0]:[1,-1];for(const M of w)for(const k of gNt(B)){const R=[];let F=!0;for(const O of k){const U=Xu(O.sourcePoint,x),Y=j0e({preparedConnection:O,bus:B,targetLayer:o,traceWidth:s,viaDiameter:a,clearance:c,viaHandedness:M}),W=xO(B),te=t6(x),j=n6(B,x),J=te*(j-aE(Y,x))-(a/2+c),oe=Math.max(0,Math.floor(J/W)),ie={x:O.sourcePoint.x,y:O.sourcePoint.y},ne=aE(Y,x),le=Xu(Y,x),ge=cNt(B),_e=[],ue=128;for(let pe=0;pe<=oe&&_e.length<ue;pe++){const ye=n1(ne+te*pe*W,le,x);if(pe===0)_e.push([ie,Y]);else{for(const Me of uNt(ie,ye))if(_e.push(Me),_e.length>=ue)break;_e.length<ue&&_e.push([ie,Y,ye])}for(let Me=1;Me<=Math.min(3,pe-1)&&_e.length<ue;Me++){const ve=pe-Me;if(!(ve<1||ve>oe))for(const he of[-1,1]){const Qe=le+he*Me*ge,Pe=n1(ne,Qe,x),we=n1(ne+te*ve*W,le,x),Te=n1(ne+te*ve*W,Qe,x),Re=Math.min(W,ge)*.2;for(const Ee of uNt(ie,Te))if(_e.push(Ee),_e.length>=ue)break;if(_e.length>=ue||(_e.push(lNt([ie,Y,Pe,Te],Re),lNt([ie,Y,we,Te],Re)),_e.length>=ue))break}}}let fe;for(const[pe,ye]of _e.entries()){const Me=$0e({preparedConnection:O,bus:B,targetLayer:o,track:U,exitAxis:n6(B),layerNames:r,traceWidth:s,viaDiameter:a,viaHoleDiameter:A,viaHandedness:M,interstitialEscape:!Q,spreadLaneIndex:0,cornerExitLaneOffset:0,cornerLocalChannelLaneOffset:0,cornerBoundaryChannelLaneOffset:0,clearance:c,terminateAtVia:!0,allowBlindAndBuriedVias:g,sourceEscapePath:ye}),he=[...QPe({preparedConnection:O,bus:B,viaDiameter:a,clearance:c}).map(Qe=>vPe({plan:Me,preparedConnection:O,planeLayer:o,viaPoint:Qe,layerNames:r,traceWidth:s,viaDiameter:a,viaHoleDiameter:A,allowBlindAndBuriedVias:g})),Me];if(fe=I(he,(Qe,Pe)=>X0e({plan:Qe,otherPlans:[...i,...R],staticClearanceCache:l,blockingBusCounts:u,cacheKey:`plane:${n.busId}:${o}:${x}:${O.connectionIndex}:${M}:${pe}:${Pe}`,srj:e,sharedBoundary:n.sharedBoundary,clearance:c,allowBlindAndBuriedVias:g,allowSameNetMerges:h})),fe)break}if(!fe){F=!1;break}R.push(fe)}if(F)return R}}return null}function*eue(t,e=1,n=!1){const{srj:o,bus:i,targetLayer:r,acceptedPlans:s,layerNames:a,traceWidth:A,viaDiameter:c,viaHoleDiameter:l,clearance:u,compactBusTracks:g,staticClearanceCache:h,blockingBusCounts:d,allowBlindAndBuriedVias:p=!0,allowSameNetMerges:m=!1,rejectedViaMinimalCandidates:_,stopAfterFirstRejectedViaMinimalCandidate:f=!1,fixedViaPointsByConnectionIndex:I,fixedBoundaryTracksByConnectionIndex:C,reservedVias:y=[],softReservedVias:x=[],viaMinimalOnly:E=!1,allowBoundarySideViaFallback:B=!1,preferCornerBoundaryVia:S=!1,adaptiveWindingRouteOrder:Q=!1,alignWindingGridToPads:w=!1,fixedViaFallbackRouteOrderAttempts:M=24,allowFixedViaReservedExitFallback:k=!1,cornerBandTargetTrackOffset:R,cornerExitLaneOffset:F,forbidEarlyExitBoundaryContact:O=!1}=t;if(!Number.isInteger(e)||e<1)throw new Error(`FanoutSolver: maxAlternatives must be a positive integer, received ${e}`);if(F!==void 0&&(!Number.isSafeInteger(F)||F<0))throw new Error(`FanoutSolver: cornerExitLaneOffset must be a non-negative safe integer, received ${F}`);if(I&&i.connections.some(ye=>!I.has(ye.connectionIndex)))return[];if(i.termination.type==="plane"){const ye=[];if(i.connections.length===1&&e>1)return pNt({...t,planeCandidateSkipCount:0,collectAlternative:Me=>(ye.push([Me]),ye.length>=e)}),ye;for(let Me=0;Me<e;Me++){const ve=pNt({...t,planeCandidateSkipCount:Me});if(!ve)break;ye.push(ve)}return ye}if(C){if(!i.exitEdge)throw new Error("FanoutSolver: fixed boundary tracks require an exit edge");const ye=i.exitEdge==="left"||i.exitEdge==="right",Me=ye?i.sharedBoundary.minY:i.sharedBoundary.minX,ve=ye?i.sharedBoundary.maxY:i.sharedBoundary.maxX;for(const he of i.connections){const Qe=C.get(he.connectionIndex);if(Qe===void 0||!Number.isFinite(Qe)||Qe<Me-1e-9||Qe>ve+1e-9)throw new Error(`FanoutSolver: invalid fixed boundary track for ${he.connection.name}`)}}const U=n6(i),Y=i.connections[0]?.sourceObstacle;if(!Y)return[[]];const W=h0(i.direction)?Y.width:Y.height,te=i.connections[0].sourceLayer,j=r!==te,J=xPe(i),oe=xO(i)/2-W/2>=c/2+u-1e-9,ie=j&&!J&&!oe,ne=j?oe||J?[0]:p?[1,-1]:[-1,1]:[0],le=(()=>{if(p||ne.length!==2||!ne.includes(-1)||!ne.includes(1))return ne;const ye=i.connections.reduce((ve,he)=>ve+Xu(he.sourcePoint,i.direction),0)/i.connections.length,Me=i.connections.reduce((ve,he)=>ve+Xu(he.exitTargetPoint??he.targetPoint,i.direction),0)/i.connections.length;return Me>ye+1e-9?[-1,1]:Me<ye-1e-9?[1,-1]:ne})(),ge=[],_e=new Set,ue=ANt(i,s);F!==void 0&&(ue.exit=F);const fe=ye=>{if(C&&ye.some(ve=>{const he=C.get(ve.connectionIndex),Qe=i.exitEdge==="left"||i.exitEdge==="right"?ve.exitPoint.y:ve.exitPoint.x;return Math.abs(Qe-he)>1e-9}))return;const Me=ye.map(ve=>`${ve.connectionIndex}:${ve.targetLayer}:${ve.exitPoint.x}:${ve.exitPoint.y}:${ve.segments.map(he=>`${he.start.x},${he.start.y},${he.end.x},${he.end.y},${he.layer}`).join(";")}`).join("|");_e.has(Me)||(_e.add(Me),ge.push(ye))};if(!yO(i)&&i.exitEdge&&i.connections.length===1&&a.includes(r)&&(i.allowedLayers===void 0||i.allowedLayers.includes(r))&&(i.routableEscapeLayers===void 0||i.routableEscapeLayers.includes(r))&&i.connections[0].sourceLayer!==r&&I&&t.sourceEscapePaths?.has(i.connections[0].connectionIndex)){const ye=i.connections[0],Me=e6(i.exitEdge),ve=BC({srj:o,bus:i,targetLayer:r,terminals:[{connection:ye,viaPoint:I.get(ye.connectionIndex),exitPoint:n1(n6(i,Me),tR({fixedBoundaryTracksByConnectionIndex:C,bus:i,connection:ye,boundaryDirection:Me}),Me)}],acceptedPlans:s,layerNames:a,traceWidth:A,viaDiameter:c,viaHoleDiameter:l,clearance:u,allowBlindAndBuriedVias:p,allowSameNetMerges:m,maximumRouteOrderAttempts:3,reservedVias:y,softReservedVias:x,gridStepDivisor:2,gridStep:t.windingGridStep,alignGridToPads:w,sourceEscapePaths:t.sourceEscapePaths,heuristicWeight:t.windingHeuristicWeight,forbidEarlyExitBoundaryContact:O},e,n);let he=ve.next();for(;!he.done;)yield{phase:"via-minimal-winding",busId:i.busId,targetLayer:r,winding:he.value},he=ve.next();for(const Qe of he.value)if(Wh({plans:[...s,...Qe],srj:o,sharedBoundary:i.sharedBoundary,clearance:u,allowBlindAndBuriedVias:p,allowSameNetMerges:m})&&(fe(Qe),ge.length>=e))return ge}if(yO(i)&&i.exitEdge){const ye=e6(i.exitEdge),Me=n6(i,ye),ve=r4(i),he=CPe(o)&&i.connections.every(be=>z0e({center:be.sourcePoint,diameter:c,obstacle:be.sourceObstacle})),Qe=24,Pe=!!(ve||yPe({bus:i,boundaryDirection:ye,traceWidth:A,clearance:u})),we=sNt({bus:i,boundaryDirection:ye,layerNames:a,targetLayer:r}),Te=we.orders.length,Re=Pe?we.ordinaryOrderCount:1,Ee=le.map(be=>({label:`uniform-${be}`,useViaInPad:!1,getViaHandedness:()=>be,maximumRouteOrderAttempts:p?void 0:Qe})),ke=i.connections.toSorted((be,et)=>Xu(be.sourcePoint,i.direction)-Xu(et.sourcePoint,i.direction)||aE(be.sourcePoint,i.direction)-aE(et.sourcePoint,i.direction)||be.connectionIndex-et.connectionIndex),Ce=new Map(ke.map((be,et)=>[be.connectionIndex,et])),Le=be=>be<ke.length/2?1:-1,Ye=Math.floor(ke.length/2),tt=[0,1,Ye,Ye+1,...ke.map((be,et)=>et)].filter((be,et,It)=>be>=0&&be<ke.length&&It.indexOf(be)===et),At=[[Ye],[Ye+1],[0],[1],[0,Ye+1],[1,Ye],[0,Ye],[1,Ye+1],[0,1],[Ye,Ye+1],...tt.map(be=>[be])].map(be=>be.filter(et=>et>=0&&et<ke.length).toSorted((et,It)=>et-It)).filter((be,et,It)=>be.length>0&&It.findIndex(Bt=>Bt.join(",")===be.join(","))===et),at=!p&&(y.length>0||s.some(be=>be.termination.type==="plane"))&&le.includes(-1)&&le.includes(1)?[{label:"toward-source-median",useViaInPad:!1,maximumRouteOrderAttempts:Qe,getViaHandedness:be=>Le(Ce.get(be.connectionIndex)??0)},...At.slice(0,12).map(be=>({label:`toward-source-median-with-ranks-${be.join("-")}-flipped`,useViaInPad:!1,maximumRouteOrderAttempts:6,getViaHandedness:et=>{const It=Ce.get(et.connectionIndex)??0,Bt=Le(It);return be.includes(It)?-Bt:Bt}})),{label:"alternating-source-grid-a",useViaInPad:!1,maximumRouteOrderAttempts:3,getViaHandedness:be=>(Ce.get(be.connectionIndex)??0)%2===0?-1:1},{label:"alternating-source-grid-b",useViaInPad:!1,maximumRouteOrderAttempts:3,getViaHandedness:be=>(Ce.get(be.connectionIndex)??0)%2===0?1:-1},{label:"away-from-source-median",useViaInPad:!1,maximumRouteOrderAttempts:Qe,getViaHandedness:be=>(Ce.get(be.connectionIndex)??0)<ke.length/2?-1:1}]:[],nt={label:"via-in-pad",useViaInPad:!0,getViaHandedness:()=>0},gt=I??(!p&&(i.connections.length>=8||yPe({bus:i,boundaryDirection:ye,traceWidth:A,clearance:u}))&&y.length===0?pd([i],{viaDiameter:c,viaHoleDiameter:l,traceWidth:A,clearance:u,additionalObstacles:o.obstacles,blockingSegments:s.flatMap(be=>kb(be).map(et=>({connectionIndex:be.connectionIndex,segment:et}))),blockingVias:s.flatMap(be=>EO(be).map(et=>({connectionIndex:be.connectionIndex,...et.center,center:et.center,diameter:et.diameter,spanLayers:et.spanLayers})))}):null),bt=gt?[...Array.from({length:Re},(be,et)=>({label:`component-matched-vias-winding-${et}`,useViaInPad:!1,getViaHandedness:()=>0,getViaPoint:It=>gt.get(It.connectionIndex),maximumRouteOrderAttempts:1,windingOrderIndex:et,preferTargetDirectedLaneBias:!0})),{label:"component-matched-vias-fallback",useViaInPad:!1,getViaHandedness:()=>0,getViaPoint:be=>gt.get(be.connectionIndex),maximumRouteOrderAttempts:M,windingOrderIndex:0,preferTargetDirectedLaneBias:!0},...!r4(i)&&Te>1?Array.from({length:Te},(be,et)=>[!0,!1].map(It=>({label:`expanded-winding-${et}-${It}`,useViaInPad:!1,getViaHandedness:()=>0,getViaPoint:Bt=>gt.get(Bt.connectionIndex),maximumRouteOrderAttempts:1,windingOrderIndex:et,preferTargetDirectedLaneBias:It,reserveTerminalExitPoints:!It,allowLayerInterleaving:!0}))).flat():[],...k&&I&&!r4(i)&&Te===1&&i.connections.length>2?[!0,!1].map(be=>({label:`fixed-vias-reserved-exits-${be}`,useViaInPad:!1,getViaHandedness:()=>0,getViaPoint:et=>gt.get(et.connectionIndex),maximumRouteOrderAttempts:Math.min(Qe,M),windingOrderIndex:0,preferTargetDirectedLaneBias:be,reserveTerminalExitPoints:!0})):[]]:[],Ct=s.some(be=>be.termination.type==="plane"),kt=s.some(be=>be.termination.type==="boundary")&&!p?[...at,...Ee]:[...Ee,...at],it=he?Ct?[nt,...kt]:[...kt,nt]:kt,Yt=I?bt:[...bt,...it];if(!I&&!p&&i.connections.length>1&&i.connections.every(be=>be.sourceLayer!==r)&&le.includes(-1)&&le.includes(1)){const be=cbo(i.connections,i.direction);for(const et of le)for(const It of be)Yt.push({label:`local-dogbone-repair-${et}-${It.join("-")}`,useViaInPad:!1,getViaHandedness:()=>et,maximumRouteOrderAttempts:6,localDogboneRepair:!0,getViaPoint:Bt=>{const mt=j0e({preparedConnection:Bt,bus:i,targetLayer:r,traceWidth:A,viaDiameter:c,clearance:u,viaHandedness:et});return It.includes(Bt.connectionIndex)?i.direction==="up"||i.direction==="down"?{x:mt.x,y:2*Bt.sourcePoint.y-mt.y}:{x:2*Bt.sourcePoint.x-mt.x,y:mt.y}:mt}})}if(w&&ve&&F===void 0){const be=ANt(i,s.filter(et=>et.targetLayer===r)).exit;be!==ue.exit&&Yt.push(...Yt.map(et=>({...et,label:`${et.label}-layer-local-corner`,cornerExitLaneOffset:be})))}const pn=new Set;for(const be of Yt){const et=i.connections.map(Ze=>{const dt=be.getViaHandedness(Ze),Ut=ve?BB({fixedBoundaryTracksByConnectionIndex:C,bus:i,connection:Ze,cornerExitLaneOffset:be.cornerExitLaneOffset??ue.exit,traceWidth:A,viaDiameter:c,clearance:u,layerNames:a,targetLayer:r,windingOrderIndex:be.windingOrderIndex,cornerBandTargetTrackOffset:R}):tR({fixedBoundaryTracksByConnectionIndex:C,allowLayerInterleaving:be.allowLayerInterleaving,bus:i,connection:Ze,boundaryDirection:ye,traceWidth:A,clearance:u,layerNames:a,targetLayer:r,windingOrderIndex:be.windingOrderIndex});return{connection:Ze,viaPoint:be.getViaPoint?be.getViaPoint(Ze):be.useViaInPad?{x:Ze.sourcePoint.x,y:Ze.sourcePoint.y}:j0e({preparedConnection:Ze,bus:i,targetLayer:r,traceWidth:A,viaDiameter:c,clearance:u,viaHandedness:dt}),exitPoint:n1(Me,Ut,ye)}}),It=w||!!(be.getViaPoint&&!I);if(be.localDogboneRepair&&!pd([i],{viaDiameter:c,viaHoleDiameter:l,traceWidth:A,clearance:u,additionalObstacles:o.obstacles,fixedViaPointsByConnectionIndex:new Map(et.map(Ze=>[Ze.connection.connectionIndex,Ze.viaPoint])),blockingSegments:s.flatMap(Ze=>kb(Ze).map(dt=>({connectionIndex:Ze.connectionIndex,segment:dt}))),blockingVias:[...s.flatMap(Ze=>EO(Ze).map(dt=>({connectionIndex:Ze.connectionIndex,center:dt.center,diameter:dt.diameter,spanLayers:dt.spanLayers}))),...y.map(({via:Ze})=>({connectionIndex:-1,...Ze}))]}))continue;const Bt=be.getViaPoint&&Math.min(i.pitchX,i.pitchY)-2*(c/2+A/2+u)<A+u?2:1,mt=`${et.map(Ze=>`${Ze.connection.connectionIndex}:${Ze.viaPoint.x}:${Ze.viaPoint.y}:${Ze.exitPoint.x}:${Ze.exitPoint.y}`).join("|")}:${be.maximumRouteOrderAttempts??"all"}:${Bt}:${It}:${!!be.localDogboneRepair}:${!!be.preferTargetDirectedLaneBias}:${!!be.reserveTerminalExitPoints}`;if(pn.has(mt))continue;pn.add(mt);const st=BC({heuristicWeight:t.windingHeuristicWeight,srj:o,bus:i,targetLayer:r,terminals:et,acceptedPlans:s,layerNames:a,traceWidth:A,viaDiameter:c,viaHoleDiameter:l,clearance:u,allowBlindAndBuriedVias:p,allowSameNetMerges:m,maximumRouteOrderAttempts:be.maximumRouteOrderAttempts,adaptiveRouteOrder:Q,alignGridToPads:It,includeReverseTargetRotation:be.localDogboneRepair,reservedVias:y,softReservedVias:x,reserveTerminalExitPoints:be.reserveTerminalExitPoints,gridStepDivisor:Bt,gridStep:t.windingGridStep,sourceEscapePaths:t.sourceEscapePaths,preferTargetDirectedLaneBias:be.preferTargetDirectedLaneBias,forbidEarlyExitBoundaryContact:O},I&&E?Math.min(2,Math.max(1,e-ge.length)):be.maximumRouteOrderAttempts===void 0?Math.min(2,e-ge.length):2,n);let xt=st.next();for(;!xt.done;)yield{phase:"via-minimal-winding",busId:i.busId,targetLayer:r,winding:xt.value},xt=st.next();const Xe=xt.value;for(const Ze of Xe){if(!Wh({plans:[...s,...Ze],srj:o,sharedBoundary:i.sharedBoundary,clearance:u,allowBlindAndBuriedVias:p,allowSameNetMerges:m})){if(Wh({plans:Ze,srj:o,sharedBoundary:i.sharedBoundary,clearance:u,allowBlindAndBuriedVias:p,allowSameNetMerges:m})&&_&&(_.push(Ze),f))return ge;continue}if(fe(Ze),ge.length>=e)return ge}}}if(ge.length===0&&B&&I&&i.connections.length<=2&&i.exitEdge&&i.connections.every(ye=>ye.sourceLayer===i.connections[0].sourceLayer&&ye.sourceLayer!==r)){const ye=i.connections[0].sourceLayer,Me=e6(i.exitEdge),ve=n6(i,Me),he=i.connections.map(at=>S&&r4(i)?BB({fixedBoundaryTracksByConnectionIndex:C,bus:i,connection:at,cornerExitLaneOffset:ue.exit,traceWidth:A,viaDiameter:c,clearance:u,layerNames:a,targetLayer:r,cornerBandTargetTrackOffset:R}):tR({fixedBoundaryTracksByConnectionIndex:C,bus:i,connection:at,boundaryDirection:Me,traceWidth:A,clearance:u,layerNames:a,targetLayer:r})),Qe=he.map(at=>n1(ve,at,Me)),Pe={...o,obstacles:o.obstacles.map(at=>{const nt=i.connections.find(gt=>at===gt.sourceObstacle||tn(at.center,gt.sourcePoint)<=1e-7&&at.layers.includes(gt.sourceLayer));return nt?{...at,connectedTo:[...at.connectedTo,nt.connection.name]}:at})},we=Math.max(c/2+u,Math.min(i.pitchX,i.pitchY)/2),Te=S?r4(i):void 0,Re=[1,2,3,4,5].flatMap(at=>{const nt=at*we,gt=he.map(bt=>n1(ve-t6(Me)*nt,bt,Me));return Te?[he.map(bt=>n1(ve-t6(Me)*nt,bt+(Te==="maximum"?nt:-nt),Me)),gt]:[gt]}),Ee={x:i.connections.reduce((at,nt)=>at+nt.sourcePoint.x,0)/i.connections.length,y:i.connections.reduce((at,nt)=>at+nt.sourcePoint.y,0)/i.connections.length},ke=[{x:-1,y:0,distance:Ee.x-Math.min(...i.xCoordinates)},{x:1,y:0,distance:Math.max(...i.xCoordinates)-Ee.x},{x:0,y:-1,distance:Ee.y-Math.min(...i.yCoordinates)},{x:0,y:1,distance:Math.max(...i.yCoordinates)-Ee.y}].toSorted((at,nt)=>at.distance-nt.distance),Ce=i.connections.length===2?ke.flatMap(at=>[3].map(nt=>i.connections.map(gt=>{const bt=I.get(gt.connectionIndex);return{x:bt.x+at.x*nt*i.pitchX,y:bt.y+at.y*nt*i.pitchY}}))):[],Le=i.connections.map(at=>I.get(at.connectionIndex)),Ye=[{distance:Ee.x-i.componentBounds.minX,axis:"x",value:i.componentBounds.minX-2*we},{distance:i.componentBounds.maxX-Ee.x,axis:"x",value:i.componentBounds.maxX+2*we},{distance:Ee.y-i.componentBounds.minY,axis:"y",value:i.componentBounds.minY-2*we},{distance:i.componentBounds.maxY-Ee.y,axis:"y",value:i.componentBounds.maxY+2*we}].toSorted((at,nt)=>at.distance-nt.distance).flatMap(({axis:at,value:nt})=>{const gt=at==="x"?"y":"x",bt=Le.reduce((it,Yt)=>it+Yt[gt],0)/Le.length,Ct=Le.map((it,Yt)=>({index:Yt,track:it[gt]})).toSorted((it,Yt)=>it.track-Yt.track||it.index-Yt.index),Dt=c+u,kt=Le.map((it,Yt)=>({...it,[at]:nt,[gt]:Ct.length===2&&Math.abs(Ct[1].track-Ct[0].track)<Dt?bt+(Ct.findIndex(pn=>pn.index===Yt)-.5)*Dt:it[gt]}));return kt.length===2?[kt,[kt[1],kt[0]]]:[kt]}),tt=i.connections.length===2&&!!r4(i),At=[...(tt?Ye:[]).map(at=>({points:at,boundarySide:!1})),...Ce.map(at=>({points:at,boundarySide:!1})),...Re.map(at=>({points:at,boundarySide:!0})),...(tt?[]:Ye).map(at=>({points:at,boundarySide:!1}))];for(const{points:at,boundarySide:nt}of At){const gt=i.connections.map((be,et)=>({connectionName:be.connection.name,via:{center:at[et],diameter:c,spanLayers:Mx({fromLayer:ye,toLayer:r,layerNames:a,allowBlindAndBuriedVias:p})}}));if(gt.some((be,et)=>gt.some((It,Bt)=>et!==Bt&&(tn(be.via.center,It.via.center)<c+u-1e-9||nt&&Cr(be.via.center,It.via.center,Qe[Bt])<c/2+A/2+u-1e-9)))||gt.some(({via:be})=>o.obstacles.some(et=>et.layers.some(It=>be.spanLayers.includes(It))&&wx(be.center,et)<be.diameter/2+u-1e-9)))continue;const bt=BC({heuristicWeight:t.windingHeuristicWeight,srj:Pe,bus:i,targetLayer:ye,terminals:i.connections.map((be,et)=>({connection:be,viaPoint:be.sourcePoint,exitPoint:at[et]})),acceptedPlans:s,layerNames:a,traceWidth:A,viaDiameter:c,viaHoleDiameter:l,clearance:u,allowBlindAndBuriedVias:p,allowSameNetMerges:m,maximumRouteOrderAttempts:i.connections.length===1?3:6,softReservedVias:x,reservedVias:i.connections.length>1?[...y,...gt]:y,gridStepDivisor:2,allowSourceLayerRouting:!0,alignGridToPads:!0,forbidEarlyExitBoundaryContact:O},1,n);let Ct=bt.next();for(;!Ct.done;)yield{phase:"via-minimal-winding",busId:i.busId,targetLayer:ye,winding:Ct.value},Ct=bt.next();const Dt=Ct.value[0];if(!Dt||Dt.length!==i.connections.length)continue;let kt;if(!nt){const be=BC({heuristicWeight:t.windingHeuristicWeight,srj:o,bus:i,targetLayer:r,terminals:i.connections.map((It,Bt)=>({connection:It,viaPoint:at[Bt],exitPoint:Qe[Bt]})),acceptedPlans:s,layerNames:a,traceWidth:A,viaDiameter:c,viaHoleDiameter:l,clearance:u,allowBlindAndBuriedVias:p,allowSameNetMerges:m,maximumRouteOrderAttempts:6,reservedVias:y,softReservedVias:x,gridStepDivisor:2,alignGridToPads:!0,forbidEarlyExitBoundaryContact:O},1,n);let et=be.next();for(;!et.done;)yield{phase:"via-minimal-winding",busId:i.busId,targetLayer:r,winding:et.value},et=be.next();if(kt=et.value[0],!kt)continue}const it=Dt.map((be,et)=>{const It=at[et],Bt=Qe[et],st=kt?kt[et].segments.filter(Ze=>Ze.layer===r):[{start:It,end:Bt,width:A,layer:r}],xt={center:It,diameter:c,holeDiameter:l,fromLayer:ye,toLayer:r,spanLayers:Mx({fromLayer:ye,toLayer:r,layerNames:a,allowBlindAndBuriedVias:p})},Xe=be.trace.route.filter(Ze=>Ze.route_type==="wire");return{...be,...S||i.connections.length>1||!nt?{sourceEscapeSegmentCount:be.segments.length}:{},targetLayer:r,exitPoint:Bt,via:xt,segments:[...be.segments,...st],length:be.length+st.reduce((Ze,dt)=>Ze+tn(dt.start,dt.end),0),trace:{...be.trace,route:[...Xe,{route_type:"via",...It,from_layer:ye,to_layer:r,via_diameter:c,via_hole_diameter:l},{route_type:"wire",...It,width:A,layer:r},...st.map(Ze=>({route_type:"wire",...Ze.end,width:A,layer:r}))]}}}),Yt=Wh({plans:[...s,...it],srj:o,sharedBoundary:i.sharedBoundary,clearance:u,allowBlindAndBuriedVias:p,allowSameNetMerges:m}),pn=it.every(be=>y.every(et=>{const It=be.via;return et.connectionName===be.connectionName||m&&Px(o,et.connectionName,be.connectionName)?!0:It.spanLayers.some(Bt=>et.via.spanLayers.includes(Bt))&&tn(It.center,et.via.center)<(It.diameter+et.via.diameter)/2+u-1e-9?!1:be.segments.every(Bt=>!et.via.spanLayers.includes(Bt.layer)||Cr(et.via.center,Bt.start,Bt.end)>=et.via.diameter/2+A/2+u-1e-9)}));if(Yt&&pn)return fe(it),ge}}if(E||I||t.sourceEscapePaths||y.length>0)return ge;const pe=(ye,Me,ve,he)=>{if(ge.length>=e)return;if(ve>=ye.length){fe(he);return}const Qe=ye[ve],Pe=e$(i,Qe),Te=[Obo({bus:i,connection:Qe,traceWidth:A}),Gbo({bus:i,connection:Qe,targetUsesVia:j,interstitialEscape:ie,compactBusTracks:g,traceWidth:A,viaDiameter:c,clearance:u})].filter((Re,Ee,ke)=>ke.findIndex(Ce=>Math.abs(Ce-Re)<1e-9)===Ee).flatMap(Re=>Hbo({bus:i,connection:Qe,preferredTrack:Re,traceWidth:A,clearance:u})).filter((Re,Ee,ke)=>ke.findIndex(Ce=>Math.abs(Ce.value-Re.value)<1e-9)===Ee);for(let Re=0;Re<Te.length;Re++){const Ee=Te[Re],ke=$0e({preparedConnection:Qe,bus:i,targetLayer:r,track:Ee.value,exitAxis:U,layerNames:a,traceWidth:A,viaDiameter:c,viaHoleDiameter:l,viaHandedness:Me,interstitialEscape:ie,spreadLaneIndex:Math.min(Pe,i.connections.length-Pe-1),cornerExitLaneOffset:ue.exit,cornerLocalChannelLaneOffset:ue.localChannel,cornerBoundaryChannelLaneOffset:ue.boundaryChannel,clearance:u,terminateAtVia:!1,allowBlindAndBuriedVias:p,cornerBandTargetTrackOffset:R,fixedBoundaryTracksByConnectionIndex:C});if(X0e({plan:ke,otherPlans:[...s,...he],staticClearanceCache:h,blockingBusCounts:d,cacheKey:`boundary:${i.busId}:${r}:${Qe.connectionIndex}:${Me}:${Re}:${i.exitEdge??"legacy"}:${ue.exit}:${ue.localChannel}:${ue.boundaryChannel}:${R??0}:${C?.get(Qe.connectionIndex)??"default"}`,srj:o,sharedBoundary:i.sharedBoundary,clearance:u,allowBlindAndBuriedVias:p,allowSameNetMerges:m})&&(pe(ye,Me,ve+1,[...he,ke]),ge.length>=e||e===1))return}};for(const ye of le)for(const Me of gNt(i))if(pe(Me,ye,0,[]),ge.length>=e)return ge;return ge}function BO(t,e=1){const n=eue(t,e);let o=n.next();for(;!o.done;)o=n.next();return o.value}function nR(t){return BO(t,1)[0]??null}var Fg=1e-7,t$=(t,e,n)=>e==="left"?t.x-n.minX:e==="right"?n.maxX-t.x:e==="top"?n.maxY-t.y:t.y-n.minY;function Kbo(t,e,n,o){const i=t$(t.start,e,n),r=t$(t.end,e,n);if(Math.min(i,r)>o)return null;if(Math.max(i,r)<=o)return t;const s=(o-i)/(r-i),a={x:t.start.x+(t.end.x-t.start.x)*s,y:t.start.y+(t.end.y-t.start.y)*s};return{...t,...i>o?{start:a}:{end:a}}}function PPe(t){let e=t.segments.length-1;for(;e>0&&t.segments[e-1].layer===t.targetLayer;)e--;const n=t.segments.slice(e);return{first:e,points:n.length?[n[0].start,...n.map(o=>o.end)]:[]}}function mNt(t,e,n){const o=[...t.segments.slice(0,e),...n.slice(1).flatMap((r,s)=>tn(n[s],r)>Fg?[{start:n[s],end:r,layer:t.targetLayer,width:t.segments.at(-1).width}]:[])];let i=t.trace.route.length;for(;i>0;){const r=t.trace.route[i-1];if(r.route_type!=="wire"||r.layer!==t.targetLayer)break;i--}return{...t,segments:o,length:o.reduce((r,s)=>r+tn(s.start,s.end),0),trace:{...t.trace,route:[...t.trace.route.slice(0,i),...n.map(r=>({route_type:"wire",x:r.x,y:r.y,layer:t.targetLayer,width:t.segments.at(-1).width}))]}}}function Vbo(t,e){const n=[...t],o=(i,r)=>{const s=Math.abs(r.x-i.x),a=Math.abs(r.y-i.y);return s<Fg||a<Fg||Math.abs(s-a)<Fg};for(let i=Math.max(1,e);i<n.length-1;i++){const r=n[i-1],s=n[i],a=n[i+1],A=tn(r,s),c=tn(s,a);if(A<Fg||c<Fg||((s.x-r.x)*(a.x-s.x)+(s.y-r.y)*(a.y-s.y))/(A*c)>=-Fg)continue;if(o(r,a)){n.splice(i,1),i--;continue}const l=[];for(const g of["x","y"]){const h=(r[g]-s[g])/(a[g]-s[g]);h>Fg&&h<1-Fg&&l.push({x:s.x+(a.x-s.x)*h,y:s.y+(a.y-s.y)*h});const d=(a[g]-r[g])/(s[g]-r[g]);d>Fg&&d<1-Fg&&l.push({x:r.x+(s.x-r.x)*d,y:r.y+(s.y-r.y)*d})}const u=l.find(g=>o(r,g)&&o(g,a));u&&(n[i]=u)}return n}function zbo(t,e){const n=o=>{const i=new Map;for(const r of t)for(const s of PPe(r).points.slice(0,-1)){const a=(s[o]%e+e)%e,A=a<1e-6||e-a<1e-6?0:Math.round(a*1e6)/1e6;i.set(A,(i.get(A)??0)+1)}return[...i].sort((r,s)=>s[1]-r[1]||r[0]-s[0])[0]?.[0]??0};return{x:n("x"),y:n("y")}}function Jbo(t,e,n,o){const i=e==="left"||e==="right"?"y":"x",r=t.map(A=>A.exitPoint[i]).sort((A,c)=>A-c),s=[],a=(A,c)=>Math.abs(A-c-Math.round((A-c)/o)*o)<=Fg;r.length===1&&!a(r[0],n[i])&&s.push({coordinate:r[0],count:1});for(let A=1;A<r.length;A++)for(const c of[r[A-1],r[A]]){if(a(c,n[i]))continue;const l=s.find(u=>a(u.coordinate,c));l?l.count++:s.push({coordinate:c,count:1})}return[n,...s.sort((A,c)=>c.count-A.count||A.coordinate-c.coordinate).slice(0,3).map(({coordinate:A})=>({...n,[i]:A}))]}function Wbo(t,e,n,o,i){const r=o+i,s=t.map((l,u)=>u),a=l=>{for(;s[l]!==l;)l=s[l];return l},A=(l,u)=>{const g={x:u.x+(n==="left"?2*r:n==="right"?-2*r:0),y:u.y+(n==="bottom"?2*r:n==="top"?-2*r:0)};return l.some(h=>tu(h.start,h.end,u,g)<(h.width+o)/2+i-Fg)};for(let l=0;l<t.length;l++)for(let u=l+1;u<t.length;u++){if(a(l)===a(u))continue;(tn(t[l].exitPoint,t[u].exitPoint)<=2*r+Fg||A(e[l],t[u].exitPoint)||A(e[u],t[l].exitPoint)||e[l].some(h=>e[u].some(d=>tu(h.start,h.end,d.start,d.end)<(h.width+d.width)/2+i-Fg)))&&(s[a(u)]=a(l))}const c=new Map;return t.forEach((l,u)=>{const g=a(u),h=c.get(g)??[];h.push(l),c.set(g,h)}),[...c.values()]}function MPe(t){const{inputSrj:e,preparedBuses:n,reservedPlans:o=[],traceWidth:i,clearance:r}=t,s=i+r,a=t.gridStep??i;if(!(s>0)||!(a>0)||!Number.isFinite(a))throw new Error("FanoutSolver: boundary tail repair requires positive finite trace/grid spacing");const A=new Map(n.flatMap(d=>d.connections.map(p=>[p.connectionIndex,{bus:d,connection:p}]))),c=[...t.plans],l=new Map;for(const d of c){const p=A.get(d.connectionIndex);if(!p)throw new Error(`FanoutSolver: missing prepared boundary-tail connection ${d.connectionIndex}`);if(d.termination.type!=="boundary"||!d.exitEdge||Math.abs(t$(d.exitPoint,d.exitEdge,p.bus.sharedBoundary))>Fg)continue;const m=`${d.exitEdge}:${d.targetLayer}`,_=l.get(m)??[];_.push(d),l.set(m,_)}const u=[...l.values()];for(let d=0;d<u.length;d++){const p=u[d],m=p[0].exitEdge,_=p[0].targetLayer,f=A.get(p[0].connectionIndex).bus.sharedBoundary,I=Math.min(24*s,(m==="left"||m==="right"?f.maxX-f.minX:f.maxY-f.minY)/3),C=p.map(w=>w.segments.filter(M=>M.layer===_).flatMap(M=>Kbo(M,m,f,I)??[])),y=Wbo(p,C,m,i,r);if(y.length>1){u.splice(d,1,...y),d--;continue}const x=new Set;for(const w of p)PPe(w).points.slice(0,-1).some(M=>Math.abs(t$(M,m,f))<=Fg&&tn(M,w.exitPoint)>Fg)&&x.add(w);for(let w=0;w<p.length;w++)for(let M=w+1;M<p.length;M++)C[w].some(k=>C[M].some(R=>tu(k.start,k.end,R.start,R.end)<(k.width+R.width)/2+r-Fg))&&(x.add(p[w]),x.add(p[M]));if(!x.size)continue;let E=!0;for(;E;){E=!1;for(const w of p)!x.has(w)&&[...x].some(M=>{if(tn(w.exitPoint,M.exitPoint)<=2*s+Fg)return!0;const k={x:M.exitPoint.x+(m==="left"?2*s:m==="right"?-2*s:0),y:M.exitPoint.y+(m==="bottom"?2*s:m==="top"?-2*s:0)};return w.segments.some(R=>R.layer===_&&tu(R.start,R.end,M.exitPoint,k)<(R.width+i)/2+r-Fg)})&&(x.add(w),E=!0)}const B=p.filter(w=>x.has(w));if(B.length>32)return null;const S=Jbo(B,m,t.gridOrigin??zbo(B,a),a);let Q=null;for(const w of S){for(const M of[8,16,24]){const k=Math.min(M*s,I),R=m==="left"||m==="right"?"x":"y",F=m==="left"||m==="bottom"?1:-1,O=m==="left"?f.minX:m==="right"?f.maxX:m==="top"?f.maxY:f.minY,U=O+F*k,Y=w[R]+(F>0?Math.ceil((U-w[R])/a):Math.floor((U-w[R])/a))*a,W=(Y-O)*F,te=B.map(ve=>{const{first:he,points:Qe}=PPe(ve),Pe=Qe.findLastIndex(Ce=>t$(Ce,m,f)>=W-Fg);if(Pe<0){const Ce=ve.additionalVias?.at(-1)??ve.via;return!Ce||Ce.toLayer!==ve.targetLayer||!Qe[0]||tn(Ce.center,Qe[0])>Fg||he<(ve.sourceEscapeSegmentCount??1)?null:{plan:ve,first:he,prefix:[Qe[0]],point:Qe[0]}}if(Pe>=Qe.length-1)return null;const we=Qe[Pe],Te=Qe[Pe+1],Re=(Y-we[R])/(Te[R]-we[R]);if(!Number.isFinite(Re)||Re<-Fg||Re>1+Fg)return null;const Ee={x:we.x+(Te.x-we.x)*Re,y:we.y+(Te.y-we.y)*Re},ke=[...Qe.slice(0,Pe+1),...tn(we,Ee)>Fg?[Ee]:[]];return he+ke.length-1<(ve.sourceEscapeSegmentCount??1)?null:{plan:ve,first:he,prefix:ke,point:Ee}});if(te.some(ve=>!ve))continue;const j=te.filter(ve=>ve!==null),J=[...c.filter(ve=>!x.has(ve)),...o],oe=j.map(ve=>({...mNt(ve.plan,ve.first,ve.prefix),exitPoint:ve.point})),ie=[...J,...oe],ne=j.map(ve=>({connection:{...A.get(ve.plan.connectionIndex).connection,sourcePoint:{...ve.point,layer:_},sourceLayer:_},viaPoint:ve.point,exitPoint:ve.plan.exitPoint})),le={...f};m==="left"&&(le.maxX=Math.min(f.maxX,Y+3*s)),m==="right"&&(le.minX=Math.max(f.minX,Y-3*s)),m==="bottom"&&(le.maxY=Math.min(f.maxY,Y+3*s)),m==="top"&&(le.minY=Math.max(f.minY,Y-3*s));const ge=R==="x"?"y":"x",_e=ne.flatMap(ve=>[ve.viaPoint[ge],ve.exitPoint[ge]]);ge==="x"?(le.minX=Math.max(le.minX,Math.min(..._e)-3*s),le.maxX=Math.min(le.maxX,Math.max(..._e)+3*s)):(le.minY=Math.max(le.minY,Math.min(..._e)-3*s),le.maxY=Math.min(le.maxY,Math.max(..._e)+3*s));const ue={...A.get(B[0].connectionIndex).bus,connections:ne.map(ve=>ve.connection),sharedBoundary:le},fe=BC({...t,srj:e,bus:ue,terminals:ne,targetLayer:_,sourceEscapePaths:void 0,acceptedPlans:ie,reservedVias:ie.flatMap(ve=>[ve.via,...ve.additionalVias??[],ve.planeEndpointVia].filter(he=>!!he).map(he=>({connectionName:ve.connectionName,via:he}))),gridStep:a,gridOrigin:w,gridStepDivisor:2,alignGridToPads:!0,heuristicWeight:2,maximumRouteOrderAttempts:72,reserveTerminalExitPoints:!0,adaptiveRouteOrder:!0,allowSourceLayerRouting:!0,forbidEarlyExitBoundaryContact:!0},1,!1);let pe=fe.next();for(;!pe.done;)pe=fe.next();const ye=pe.value[0];if(!ye)continue;const Me=j.map(ve=>{const he=ye.find(Pe=>Pe.connectionIndex===ve.plan.connectionIndex);if(!he||he.via||he.additionalVias?.length)throw new Error("FanoutSolver: boundary-tail repair added a physical via");const Qe=Vbo([...ve.prefix,...he.segments.map(Pe=>Pe.end)],ve.prefix.length-1);return mNt(ve.plan,ve.first,Qe)});if(Wh({plans:Me,srj:{...e,traces:[...e.traces??[],...J.flatMap(ve=>[ve.trace,...ve.planeEndpointTrace?[ve.planeEndpointTrace]:[]])]},sharedBoundary:f,clearance:r,allowBlindAndBuriedVias:t.allowBlindAndBuriedVias,allowSameNetMerges:t.allowSameNetMerges})){Q=Me;break}}if(Q)break}if(!Q)return null;for(const w of Q)c[c.findIndex(M=>M.connectionIndex===w.connectionIndex)]=w}const g=[...c,...o];if(e.traces?.length&&g.length){const d=n.map(m=>m.sharedBoundary);if(!Z0e({srj:e,sharedBoundary:{minX:Math.min(...d.map(m=>m.minX)),maxX:Math.max(...d.map(m=>m.maxX)),minY:Math.min(...d.map(m=>m.minY)),maxY:Math.max(...d.map(m=>m.maxY))},clearance:r,allowBlindAndBuriedVias:t.allowBlindAndBuriedVias,allowSameNetMerges:t.allowSameNetMerges})(g))return null}return qu({inputSrj:e,routedSrj:{...e,traces:[...g.flatMap(d=>[d.trace,...d.planeEndpointTrace?[d.planeEndpointTrace]:[]])]},clearance:r,allowBlindAndBuriedVias:t.allowBlindAndBuriedVias}).valid?c:null}var Da=1e-7;function bO(t,e,n,o){const i=new Float64Array(e.length+1),r=new Int32Array(e.length);for(let A=0;A<e.length;A++){const c=e[A],l=e[A-1];i[A+1]=i[A]+tn(c.start,c.end),r[A]=A===0?0:r[A-1]+ +(l.layer!==c.layer||tn(l.end,c.start)>Da)}const s=[t.via,...t.additionalVias??[],t.planeEndpointVia].filter(A=>!!A),a=(A,c)=>{if(r[A]!==r[c])return!1;let l=0,u=0;for(let g=A;g<=c;g++){const h=e[g],d=h.end.x-h.start.x,p=h.end.y-h.start.y;if(Math.abs(d)>Da){const m=Math.sign(d);if(l&&l!==m)return!1;l=m}if(Math.abs(p)>Da){const m=Math.sign(p);if(u&&u!==m)return!1;u=m}}return!0};for(const[A,c]of e.entries())if(!(o&&!o.has(A))&&!(!o&&t.segments.some(l=>l.layer===c.layer&&l.width===c.width&&Cr(c.start,l.start,l.end)<=Da&&Cr(c.end,l.start,l.end)<=Da))){for(const[l,u]of e.entries()){if(u.layer!==c.layer)continue;const g=(c.width+u.width)/2+n,h=Math.min(A,l),d=Math.max(A,l);if(!(r[A]===r[l]&&Math.max(0,i[d]-i[h+1])<=g+Da)&&!Zm(c,u,n)&&!a(h,d))return!1}for(const l of s){if(!l.spanLayers.includes(c.layer))continue;const u=(c.width+l.diameter)/2+n;if(Cr(l.center,c.start,c.end)>=u-Da||[c.start,c.end].some(h=>tn(h,l.center)<=Da))continue;const g=h=>{let d=h===-1?c.start:c.end;const p=h===-1?c.end:c.start;if(tn(d,l.center)>u+Da||(d.x-l.center.x)*(p.x-d.x)+(d.y-l.center.y)*(p.y-d.y)<-Da)return!1;for(let m=A+h;m>=0&&m<e.length;m+=h){const _=e[m];if(_.layer!==c.layer||tn(d,h===-1?_.end:_.start)>Da)return!1;const f=h===-1?_.start:_.end;if(tn(f,l.center)>u+Da||(f.x-l.center.x)*(f.x-d.x)+(f.y-l.center.y)*(f.y-d.y)>Da)return!1;if(d=f,tn(d,l.center)<=Da)return!0}return!1};if(!g(-1)&&!g(1))return!1}}return!0}function n$(t,e,n,o,i=!1,r=t.traceWidth/4){const{inputSrj:s,layerNames:a,traceWidth:A,clearance:c}=t,l=e.trace.route.findIndex(y=>y.route_type==="via");if(l<0)return null;const u=e.trace.route.slice(l+1).flatMap(y=>y.route_type==="wire"?[{x:y.x,y:y.y,z:a.indexOf(y.layer)}]:[]);for(let y=1;i&&y<u.length-1;y++){const x=u[y-1],E=u[y],B=u[y+1];if(x.z!==E.z||E.z!==B.z)continue;((E.x-x.x)*(B.x-E.x)+(E.y-x.y)*(B.y-E.y))/(tn(x,E)*tn(E,B))<-Da&&(u.splice(y,1),y--)}const g=Z7(s,!1),h=new qj([...n.flatMap(y=>[...y.segments,...y.planeEndpointSegments??[]]),...g.flatMap(y=>y.segments)]),d=[...n.flatMap(y=>[y.via,...y.additionalVias??[],y.planeEndpointVia].filter(x=>!!x)),...g.flatMap(y=>y.vias)],p=eR({points:u,chamfer:r,repairReversingDiagonalCorners:!0,segmentIsClear:(y,x)=>{const E={start:y,end:x,layer:a[y.z],width:A};for(const B of[y,x]){const S=o.sharedBoundary;if(B.x<S.minX-Da||B.x>S.maxX+Da||B.y<S.minY-Da||B.y>S.maxY+Da||(Math.abs(B.x-S.minX)<Da||Math.abs(B.x-S.maxX)<Da||Math.abs(B.y-S.minY)<Da||Math.abs(B.y-S.maxY)<Da)&&tn(B,e.exitPoint)>Da)return!1}return s.obstacles.every(B=>!B.layers.includes(E.layer)||Tl(E,B)>=A/2+c-1e-9)&&h.querySegment(E,c).every(B=>Zm(E,B,c))&&d.every(B=>!B.spanLayers.includes(E.layer)||Cr(B.center,y,x)>=(A+B.diameter)/2+c-1e-9)}});if(!p)return null;const m=e.trace.route.slice(0,l+1);for(let y=0;y<p.length;y++){const x=p[y],E=p[y-1];if(E&&E.z!==x.z){const B=e.trace.route.find(S=>S.route_type==="via"&&tn(S,x)<Da&&S.from_layer===a[E.z]&&S.to_layer===a[x.z]);if(!B)return null;m.push(B)}m.push({route_type:"wire",x:x.x,y:x.y,layer:a[x.z],width:A})}m[m.length-1]=e.trace.route.at(-1);const _={...e.trace,route:m},f=J0e(s,_,!1).segments,I=e.sourceEscapeSegmentCount??1,C=[...e.segments.slice(0,I),...f.slice(I)];return bO(e,C,c)?{...e,trace:_,segments:C,length:C.reduce((y,x)=>y+tn(x.start,x.end),0)}:null}function mw(t){for(let e=0;e<t.length;e++){const n=t[e],o=n.end.x-n.start.x,i=n.end.y-n.start.y,r=Math.hypot(o,i);if(Math.min(Math.abs(o),Math.abs(i),Math.abs(Math.abs(o)-Math.abs(i)))>Da)return!1;const s=t[e+1];if(s&&tn(n.end,s.start)>Da)return!1;if(!s||s.layer!==n.layer||r<Da)continue;const a=s.end.x-s.start.x,A=s.end.y-s.start.y,c=Math.hypot(a,A);if(!(c<Da)&&(o*a+i*A)/(r*c)<Math.SQRT1_2-Da)return!1}return!0}function o$(t,e){const n=e.sharedBoundary;return t.segments.every(o=>[o.start,o.end].every(i=>i.x<n.minX-Da||i.x>n.maxX+Da||i.y<n.minY-Da||i.y>n.maxY+Da?!1:t.termination.type!=="boundary"?!0:!(Math.abs(i.x-n.minX)<Da||Math.abs(i.x-n.maxX)<Da||Math.abs(i.y-n.minY)<Da||Math.abs(i.y-n.maxY)<Da)||tn(i,t.exitPoint)<Da))}function jbo(t,e,n,o,i=!1){const r=e.sourceEscapeSegmentCount??1;if(e.termination.type!==(i?"boundary":"plane")||!e.via||!i&&e.additionalVias?.length||e.planeEndpointTrace||e.planeEndpointSegments?.length||e.planeEndpointVia||!i&&e.segments.length!==r)return null;const s=e.segments.slice(0,r);if(!s.length||s.some(E=>E.layer!==e.sourceLayer)||tn(s[0].start,e.sourcePoint)>Da||tn(s.at(-1).end,e.via.center)>Da)return null;const a=o.connections.find(E=>E.connectionIndex===e.connectionIndex);if(!a?.sourceObstacle)return null;const A=e.trace.route.findIndex(E=>E.route_type==="via");if(A<1)return null;const{inputSrj:c,traceWidth:l,clearance:u,layerNames:g}=t,h=E=>e.termination.type==="plane"&&Px(c,e.connectionName,E),d=n.filter(E=>E.termination.type!=="plane"||!h(E.connectionName)),p=Z7(c,!1).filter(E=>!h(E.connectionName)),m=new qj([...e.segments.slice(r),...d.flatMap(E=>[...E.segments,...E.planeEndpointSegments??[]]),...p.flatMap(E=>E.segments)]),_=[...e.additionalVias??[],...d.flatMap(E=>[E.via,...E.additionalVias??[],E.planeEndpointVia].filter(B=>!!B)),...p.flatMap(E=>E.vias)],f=eR({points:[e.sourcePoint,...s.map(E=>E.end)].map(E=>({...E,z:g.indexOf(e.sourceLayer)})),chamfer:l/4,repairReversingDiagonalCorners:!0,segmentIsClear:(E,B)=>{const S={start:E,end:B,layer:e.sourceLayer,width:l},Q=o.sharedBoundary;return[E,B].some(w=>w.x<Q.minX||w.x>Q.maxX||w.y<Q.minY||w.y>Q.maxY)?!1:c.obstacles.every(w=>!w.layers.includes(e.sourceLayer)||Tl(S,w)>=l/2+u-1e-9||w===a.sourceObstacle&&IO(E,w,l/2+u)&&(E.x-a.sourcePoint.x)*(B.x-E.x)+(E.y-a.sourcePoint.y)*(B.y-E.y)>=-Da||w!==a.sourceObstacle&&e.termination.type==="plane"&&n4(c,w,e.connectionName)?!0:jj({inputSrj:c,segment:S,bodyObstacle:w,connectionName:e.connectionName}))&&m.querySegment(S,u).every(w=>Zm(S,w,u))&&_.every(w=>!w.spanLayers.includes(S.layer)||Cr(w.center,E,B)>=(l+w.diameter)/2+u-1e-9)}});if(!f)return null;const I={...e.trace,route:[e.trace.route[0],...f.slice(1).map(E=>({route_type:"wire",x:E.x,y:E.y,layer:e.sourceLayer,width:l})),...e.trace.route.slice(A)]},C=J0e(c,{...I,route:I.route.slice(0,f.length)},!1).segments,y=[...C,...e.segments.slice(r)];let x=!1;for(const E of C){const B=Tl(E,a.sourceObstacle);if(x&&B<l/2+u-1e-9)return null;wx(E.end,a.sourceObstacle)>=l/2+u-1e-9&&(x=!0)}return!mw(C)||!bO(e,y,u,new Set(C.map((E,B)=>B)))?null:{...e,trace:I,segments:y,sourceEscapeSegmentCount:C.length,length:[...y,...e.planeEndpointSegments??[]].reduce((E,B)=>E+tn(B.start,B.end),0)}}function DPe(t){const e=new Map(t.preparedBuses.map(A=>[A.busId,A]));if(new Set(t.plans.map(A=>A.connectionIndex)).size!==t.plans.length)return null;let n=[...t.plans],o=!1;if(t.repairPlaneSourceCorners||t.repairSignalSourceCorners)for(let A=0;A<n.length;A++){const c=n[A];if(mw(c.segments.slice(0,c.sourceEscapeSegmentCount??1)))continue;const l=e.get(c.busId);if(!l||(c.termination.type==="plane"?!t.repairPlaneSourceCorners:!t.repairSignalSourceCorners))return null;const u=jbo(t,c,n.filter((g,h)=>h!==A),l,c.termination.type==="boundary");if(!u)return null;n[A]=u,o=!0}if(o&&t.rematchRepairedLengths){const A=t.rematchRepairedLengths(n);if(!A)return null;n=A}const i=[...n],r=fPe(t.inputSrj);for(const A of n){if(!e.has(A.busId))throw new Error("Final normalization requires each original prepared bus");if(!mw(A.segments.slice(0,A.sourceEscapeSegmentCount??1))||!o$({...A,segments:A.segments.slice(0,A.sourceEscapeSegmentCount??1)},e.get(A.busId))||!mw(A.planeEndpointSegments??[]))return null}if(n.some(A=>!o$(A,e.get(A.busId)))){const A=MPe({...t,plans:n,allowBlindAndBuriedVias:!1,allowSameNetMerges:!1});if(!A)return null;if(n=A,t.rematchRepairedLengths){const c=t.rematchRepairedLengths(n);if(!c)return null;n=c}}for(let A=0;A<n.length;A++){const c=n[A];if(mw(c.segments)&&o$(c,e.get(c.busId)))continue;const l=e.get(c.busId);let u=null,g=null;for(let h=t.traceWidth/4;h>=1e-6;h=Math.max(1e-6,h/4)){const d=n$(t,c,n.filter((p,m)=>m!==A),l,!1,h);if(d){g??=d;const p=n.filter(_=>_.busId===l.busId).map(_=>_===c?d.length:_.length);if(r.every(_=>{if(!_.connectionIndices.includes(c.connectionIndex))return!0;const f=_.connectionIndices.map(C=>n.find(y=>y.connectionIndex===C));if(f.some(C=>!C))return!0;const I=f.map(C=>C===c?d.length:C.length);return Math.abs(I[0]-I[1])<=_.lengthTolerance+Da})&&(l.maxLengthSkew===void 0||Math.max(...p)-Math.min(...p)<=l.maxLengthSkew+Da)){u=d;break}}if(h===1e-6)break}if(!u&&g&&t.rematchRepairedLengths){const h=t.rematchRepairedLengths(n.map((p,m)=>m===A?g:p)),d=h?.find(p=>p.connectionIndex===c.connectionIndex);h&&d&&mw(d.segments)&&(n=h,u=d)}if(!u)return null;n[A]=u}for(let A=0;A<n.length;A++){const c=n[A],l=i.find(d=>d.connectionIndex===c.connectionIndex);if(!l||c.targetLayer!==l.targetLayer||tn(c.exitPoint,l.exitPoint)>Da||JSON.stringify(c.via)!==JSON.stringify(l.via)||JSON.stringify(c.additionalVias)!==JSON.stringify(l.additionalVias)||!mw(c.segments)||!o$(c,e.get(c.busId)))return null;if(c===l)continue;const u=l.trace.route.findIndex(d=>d.route_type==="via"),g=c.trace.route.findIndex(d=>d.route_type==="via");if(u<0||g<0)return null;const h=l.sourceEscapeSegmentCount??1;n[A]={...c,sourcePoint:l.sourcePoint,via:l.via,additionalVias:l.additionalVias,exitPoint:l.exitPoint,sourceEscapeSegmentCount:h,segments:[...l.segments.slice(0,h),...c.segments.slice(c.sourceEscapeSegmentCount??1)],trace:{...l.trace,route:[...l.trace.route.slice(0,u+1),...c.trace.route.slice(g+1)]}}}for(const A of t.preparedBuses){const c=n.filter(l=>l.busId===A.busId);if(c.length!==A.connections.length||c.some(l=>!mw(l.segments)||!o$(l,A)))return null;if(A.maxLengthSkew!==void 0&&Math.max(...c.map(l=>l.length))-Math.min(...c.map(l=>l.length))>A.maxLengthSkew+Da)return null}const s=new Map(n.map(A=>[A.connectionIndex,A]));for(const A of r){const c=A.connectionIndices.map(u=>s.get(u));if(c.some(u=>!u))continue;const l=c.map(u=>[...u.segments,...u.planeEndpointSegments??[]].reduce((g,h)=>g+tn(h.start,h.end),0));if(l.some(u=>!Number.isFinite(u))||Math.abs(l[0]-l[1])>A.lengthTolerance+Da)return null}if(t.inputSrj.traces?.length&&n.length){const A=t.preparedBuses.map(l=>l.sharedBoundary);if(!Z0e({srj:t.inputSrj,sharedBoundary:{minX:Math.min(...A.map(l=>l.minX)),maxX:Math.max(...A.map(l=>l.maxX)),minY:Math.min(...A.map(l=>l.minY)),maxY:Math.max(...A.map(l=>l.maxY))},clearance:t.clearance,allowBlindAndBuriedVias:!1,allowSameNetPlaneMerges:!0})(n))return null}return qu({inputSrj:t.inputSrj,routedSrj:{...t.inputSrj,traces:[...n.flatMap(A=>[A.trace,...A.planeEndpointTrace?[A.planeEndpointTrace]:[]])]},clearance:t.clearance,allowBlindAndBuriedVias:!1}).valid?n:null}function $bo(t){const{inputSrj:e,plans:n,unroutedSourceBuses:o,clearance:i}=t,r=new Map(n.map(I=>[I.connectionIndex,I])),s=Rb(e.layerCount),a=o.filter(I=>I.termination.type==="boundary"&&I.connections.length>0&&I.connections.every(C=>{const y=r.get(C.connectionIndex),x=y?.segments[0],E=y?.via;return y?.connectionName===C.connection.name&&y.termination.type==="boundary"&&y.segments.length===1&&(y.sourceEscapeSegmentCount??1)===1&&!y.additionalVias?.length&&!y.planeEndpointTrace&&!y.planeEndpointVia&&x&&x.layer===C.sourceLayer&&E&&E.fromLayer===C.sourceLayer&&E.toLayer===y.targetLayer&&E.toLayer!==E.fromLayer&&E.spanLayers.length===s.length&&s.every(B=>E.spanLayers.includes(B))&&tn(x.start,C.sourcePoint)<1e-7&&tn(x.end,E.center)<1e-7&&tn(y.exitPoint,E.center)<1e-7})),A=a[0]?.connections[0];if(!A)return null;const c=r.get(A.connectionIndex),l=c.via,u=c.segments[0].width;if(a.some(I=>I.connections.some(C=>{const y=r.get(C.connectionIndex);return y.via.diameter!==l.diameter||y.via.holeDiameter!==l.holeDiameter||y.segments[0].width!==u})))return null;const g=new Set(a.flatMap(I=>I.connections.map(C=>C.connectionIndex))),h=n.filter(I=>!g.has(I.connectionIndex)),d=Z7(e,!1),p=pd(a,{traceWidth:u,clearance:i,viaDiameter:l.diameter,viaHoleDiameter:l.holeDiameter,maximumSearchStates:1e4,preferredViaPointsByConnectionIndex:new Map(n.filter(I=>g.has(I.connectionIndex)).map(I=>[I.connectionIndex,I.via.center])),additionalObstacles:e.obstacles,blockingSegments:[...h.flatMap(I=>[...I.segments,...I.planeEndpointSegments??[]].map(C=>({connectionIndex:I.connectionIndex,segment:C}))),...d.flatMap(I=>I.segments.map(C=>({connectionIndex:-1,segment:C})))],blockingVias:[...h.flatMap(I=>[I.via,...I.additionalVias??[],I.planeEndpointVia].filter(C=>C!==void 0).map(C=>({connectionIndex:I.connectionIndex,...C}))),...d.flatMap(I=>I.vias.map(C=>({connectionIndex:-1,...C})))]});if(!p)return null;const m=new Map;for(const I of a)for(const C of I.connections){const y=r.get(C.connectionIndex),x=p.get(C.connectionIndex);if(tn(x,y.via.center)<1e-7)continue;const E=x.x-C.sourcePoint.x,B=x.y-C.sourcePoint.y;if(Math.min(Math.abs(E),Math.abs(B),Math.abs(Math.abs(E)-Math.abs(B)))>1e-7)return null;m.set(C.connectionIndex,i4({bus:I,terminal:{connection:C,viaPoint:x,exitPoint:x},targetLayer:y.targetLayer,targetLayerPoints:[x],layerNames:s,traceWidth:u,viaDiameter:l.diameter,viaHoleDiameter:l.holeDiameter,allowBlindAndBuriedVias:!1}))}if(!m.size)return null;const _=n.map(I=>m.get(I.connectionIndex)??I);return Wh({plans:_,srj:e,sharedBoundary:a[0].sharedBoundary,clearance:i,allowBlindAndBuriedVias:!1,allowSameNetMerges:!1})&&qu({inputSrj:e,routedSrj:{...e,traces:[...e.traces??[],..._.flatMap(I=>[I.trace,...I.planeEndpointTrace?[I.planeEndpointTrace]:[]])]},clearance:i,allowBlindAndBuriedVias:!1}).valid?_:null}var Jr=1e-6;function Vy(t,e){return tn(t,e)<=Jr}function tue(t){return[t.via,...t.additionalVias??[]].filter(e=>e!==void 0)}function qbo(t,e){const n=e[0];if(!n)return null;const o=t.trace.route.find(g=>g.route_type==="wire"),i=t.trace.route.findLast(g=>g.route_type==="wire"),r=g=>{if(g?.route_type!=="wire")return{};const h={...g};return delete h.route_type,delete h.x,delete h.y,delete h.width,delete h.layer,h},s=tue(t),A=Vy(n.start,t.sourcePoint)&&n.layer!==t.sourceLayer&&s.some(g=>Vy(g.center,n.start)&&g.spanLayers.includes(t.sourceLayer)&&g.spanLayers.includes(n.layer))?t.sourceLayer:n.layer,c=[{...r(o),route_type:"wire",...n.start,width:n.width,layer:A}];let l=n.start,u=A;for(const[g,h]of e.entries()){if(!Vy(l,h.start))return null;if(u!==h.layer){const d=s.find(p=>Vy(p.center,h.start)&&p.spanLayers.includes(u)&&p.spanLayers.includes(h.layer));if(!d)return null;c.push({route_type:"via",...h.start,from_layer:u,to_layer:h.layer,via_diameter:d.diameter,via_hole_diameter:d.holeDiameter}),c.push({route_type:"wire",...h.start,width:h.width,layer:h.layer}),u=h.layer}c.push({...g===e.length-1?r(i):{},route_type:"wire",...h.end,width:h.width,layer:h.layer}),l=h.end}return c}function bB(t,e,n=!1){const o=qbo(t,e);if(!o)return null;const i=[...e,...t.planeEndpointSegments??[]].reduce((s,a)=>s+tn(a.start,a.end),0),r=e.findIndex(s=>s.layer!==t.sourceLayer);return{...t,...n&&t.sourceEscapeSegmentCount!==void 0&&r>=0?{sourceEscapeSegmentCount:r}:{},trace:{...t.trace,route:o},segments:e,length:i}}function nue(t,e,n){const o=[...tue(t),...t.planeEndpointVia?[t.planeEndpointVia]:[]];for(const i of e){for(const a of o)if(a!==i&&i.spanLayers.some(A=>a.spanLayers.includes(A))&&tn(i.center,a.center)<(i.diameter+a.diameter)/2+n-1e-9)return!1;const r=t.segments.flatMap((a,A)=>{const c=t.segments[A+1];return a.layer===i.fromLayer&&c?.layer===i.toLayer&&Vy(a.end,i.center)&&Vy(c.start,i.center)?[A]:[]});if(r.length!==1)return!1;const s=new Set;for(const a of[-1,1]){let A=i.center,c=0;const l=a===-1?i.fromLayer:i.toLayer;for(let u=r[0]+(a===1?1:0);u>=0&&u<t.segments.length;u+=a){const g=t.segments[u],h=a===-1?g.end:g.start,d=a===-1?g.start:g.end,p=(i.diameter+g.width)/2+n;if(g.layer!==l||!Vy(A,h)||c>p+Jr)break;s.add(u),c+=tn(h,d),A=d}}for(const[a,A]of[...t.segments,...t.planeEndpointSegments??[]].entries())if(!(s.has(a)||!i.spanLayers.includes(A.layer))&&Cr(i.center,A.start,A.end)<(i.diameter+A.width)/2+n-1e-9)return!1}return!0}function*Xbo(t){const{plan:e,bus:n,layerNames:o,clearance:i,workBudget:r}=t;if(!e.via||tue(e).length>5)return;const s=n.allowedLayers??o,a=(n.routableEscapeLayers??s).filter(u=>s.includes(u)&&o.includes(u)&&u!==e.sourceLayer&&u!==e.targetLayer),A=[];for(const u of e.segments){const g=A.at(-1);if(g?.layer===u.layer&&u.layer===e.targetLayer){const h=g.end.x-g.start.x,d=g.end.y-g.start.y,p=u.end.x-u.start.x,m=u.end.y-u.start.y;if(Math.abs(h*m-d*p)<=Jr*Math.hypot(h,d)*Math.hypot(p,m)&&h*p+d*m>0){g.end=u.end;continue}}A.push({...u})}const c=bB(e,A);if(!c)return;const l=(u,g,h)=>({center:u,fromLayer:g,toLayer:h,diameter:e.via.diameter,holeDiameter:e.via.holeDiameter,spanLayers:o});for(const u of a)for(const g of[!0,!1])if(!(g&&(c.additionalVias?.length||c.via.toLayer!==c.targetLayer))){for(const[h,d]of c.segments.entries())if(d.layer===c.targetLayer&&!(tn(d.start,d.end)<=Jr))for(let p=0;p<37;p++){const m=.05+p*.025;if(!g&&m>=.5)break;oR(r);const _=x=>({x:d.start.x+(d.end.x-d.start.x)*x,y:d.start.y+(d.end.y-d.start.y)*x}),f=_(m),I=_(1-m);if(!g&&tn(f,I)<e.via.diameter+i)continue;const C=g?[l(I,u,d.layer)]:[l(f,d.layer,u),l(I,u,d.layer)],y=g?bB({...c,via:{...c.via,toLayer:u},additionalVias:C},[...c.segments.slice(0,h).map(x=>x.layer===c.targetLayer?{...x,layer:u}:x),{...d,end:I,layer:u},{...d,start:I},...c.segments.slice(h+1)]):bB({...c,additionalVias:[...c.additionalVias??[],...C]},[...c.segments.slice(0,h),{...d,end:f},{...d,start:f,end:I,layer:u},{...d,start:I},...c.segments.slice(h+1)]);y&&nue(y,C,i)&&(yield{plan:y,tuningLayer:u,addedVias:C})}}}function _Nt(t,e,n){return t.x<e.minX-n||t.x>e.maxX+n||t.y<e.minY-n||t.y>e.maxY+n}function Zbo(t){const{segment:e,bounds:n,margin:o}=t,i={minX:n.minX-o,maxX:n.maxX+o,minY:n.minY-o,maxY:n.maxY+o},r=e.end.x-e.start.x,s=e.end.y-e.start.y,a=[0,1],A=l=>{if(l<=Jr||l>=1-Jr)return;const u={x:e.start.x+r*l,y:e.start.y+s*l};u.x<i.minX-Jr||u.x>i.maxX+Jr||u.y<i.minY-Jr||u.y>i.maxY+Jr||a.push(l)};Math.abs(r)>Jr&&(A((i.minX-e.start.x)/r),A((i.maxX-e.start.x)/r)),Math.abs(s)>Jr&&(A((i.minY-e.start.y)/s),A((i.maxY-e.start.y)/s));const c=a.toSorted((l,u)=>l-u).filter((l,u,g)=>u===0||Math.abs(l-g[u-1])>Jr);return c.slice(1).map((l,u)=>{const g=c[u];return{...e,start:{x:e.start.x+r*g,y:e.start.y+s*g},end:{x:e.start.x+r*l,y:e.start.y+s*l}}})}function fNt(t){return t.componentObstacles.reduce((e,n)=>({minX:Math.min(e.minX,n.center.x-n.width/2),maxX:Math.max(e.maxX,n.center.x+n.width/2),minY:Math.min(e.minY,n.center.y-n.height/2),maxY:Math.max(e.maxY,n.center.y+n.height/2)}),{minX:Number.POSITIVE_INFINITY,maxX:Number.NEGATIVE_INFINITY,minY:Number.POSITIVE_INFINITY,maxY:Number.NEGATIVE_INFINITY})}function NPe(t,e){return t.layer!==e.layer||Math.min(t.start.x,t.end.x)>Math.max(e.start.x,e.end.x)+Jr||Math.min(e.start.x,e.end.x)>Math.max(t.start.x,t.end.x)+Jr||Math.min(t.start.y,t.end.y)>Math.max(e.start.y,e.end.y)+Jr||Math.min(e.start.y,e.end.y)>Math.max(t.start.y,t.end.y)+Jr?!1:tu(t.start,t.end,e.start,e.end)<=Jr}function INt(t){let e;return(n,o,i)=>{if(!e){e=[];for(let a=0;a<t.length;a++)for(let A=a+2;A<t.length;A++)NPe(t[a],t[A])&&e.push([a,A])}const r=o+i-1,s=(a,A)=>A===a+2&&Vy(n[a].end,n[A].start);for(const[a,A]of e){if(a===o||A===o)continue;const c=a>o?a+i-1:a,l=A>o?A+i-1:A;if(!s(c,l))return!0}for(let a=o;a<=r;a++)for(let A=0;A<n.length;A++){if(Math.abs(a-A)<2||A>=o&&A<a)continue;const c=Math.min(a,A),l=Math.max(a,A);if(!s(c,l)&&NPe(n[c],n[l]))return!0}return!1}}function RPe(t){const{plan:e,segments:n,replacementStartIndex:o,replacementSegmentCount:i,clearance:r}=t,s=o+i-1,a=tue(e),A=new Int32Array(n.length),c=new Float64Array(n.length+1);for(let u=0;u<n.length;u++){const g=n[u],h=n[u-1];A[u]=u===0?0:A[u-1]+ +(h.layer!==g.layer||!Vy(h.end,g.start)),c[u+1]=c[u]+tn(g.start,g.end)}const l=(u,g)=>{if(u===g)return 0;if(A[u]!==A[g])return Number.POSITIVE_INFINITY;const h=Math.min(u,g),d=Math.max(u,g);return Math.max(0,c[d]-c[h+1])};for(let u=o;u<=s;u++){const g=n[u],h=e.segments[o];if(!(g.layer===h.layer&&g.width===h.width&&Cr(g.start,h.start,h.end)<=Jr&&Cr(g.end,h.start,h.end)<=Jr)){for(const[d,p]of n.entries()){const m=g.width/2+p.width/2+r;if(!(l(u,d)<=m+Jr)&&!Zm(g,p,r))return!1}for(const d of a){if(!d.spanLayers.includes(g.layer)||Vy(d.center,g.start)||Vy(d.center,g.end))continue;const p=d.diameter/2+g.width/2+r,m=_=>{let f=_===-1?g.start:g.end,I=0;for(let C=u+_;C>=0&&C<n.length;C+=_){const y=n[C];if(y.layer!==g.layer)return!1;const x=_===-1?y.end:y.start;if(!Vy(f,x)||(I+=tn(y.start,y.end),I>p+Jr))return!1;if(f=_===-1?y.start:y.end,Vy(f,d.center))return!0}return!1};if(Cr(d.center,g.start,g.end)<p-Jr&&!m(-1)&&!m(1))return!1}}}return!0}function CNt(t,e){return t.x>=e.minX-Jr&&t.x<=e.maxX+Jr&&t.y>=e.minY-Jr&&t.y<=e.maxY+Jr}function sI(t,e,n){return{x:t.x+e.x*n,y:t.y+e.y*n}}function eSo(t){const{segment:e,toothCount:n,targetAddedLength:o,pitch:i,placementFraction:r,normalSign:s}=t,a=e.end.x-e.start.x,A=e.end.y-e.start.y,c=Math.hypot(a,A);if(c<=Jr)return null;const l=Math.abs(a)<=Jr||Math.abs(A)<=Jr,u=Math.abs(Math.abs(a)-Math.abs(A))<=Jr;if(!l&&!u)return null;const g={x:a/c,y:A/c},h={x:-g.y*s,y:g.x*s},d=Math.min(i/2,o/(8*n*(Math.SQRT2-1)),t.chamferLimit??Number.POSITIVE_INFINITY),p=t.plateauLength??i,m=d*4+p,_=i,f=n*m+Math.max(0,n-1)*_,I=i/4;if(f+I*2>c+Jr)return null;const C=4*d*(Math.SQRT2-1);if(o+Jr<C*n)return null;const y=(o/n-C)/2,x=c-f-I*2,E=I+Math.max(0,x)*r;let B=sI(e.start,g,E);const S=[{...e.start},{...B}];for(let Q=0;Q<n;Q++)B=sI(sI(B,g,d),h,d),S.push(B),B=sI(B,h,y),S.push(B),B=sI(sI(B,g,d),h,d),S.push(B),B=sI(B,g,p),S.push(B),B=sI(sI(B,g,d),h,-d),S.push(B),B=sI(B,h,-y),S.push(B),B=sI(sI(B,g,d),h,-d),S.push(B),Q<n-1&&(B=sI(B,g,_),S.push(B));return S.push({...e.end}),S.filter((Q,w)=>w===0||!Vy(Q,S[w-1]))}var yNt=class extends Error{};function oR(t){if(t&&t.remaining--<=0)throw new yNt}function*_w(t){const{plan:e,bus:n,targetAddedLength:o,clearance:i,sharedBoundary:r,allowInsideDenseBounds:s=!1,allowSourcePrefixMatching:a=!1,denseBoundarySplitApplied:A=!1}=t,c=fNt(n),l=INt(e.segments),u=e.segments[0]?.width?e.segments[0].width/2+i:i,g=e.segments.map((p,m)=>({segment:p,segmentIndex:m})).filter(({segment:p,segmentIndex:m})=>p.layer===e.targetLayer||t.allowTransitLayerMatching&&p.layer!==e.sourceLayer&&(n.allowedLayers??[e.targetLayer]).includes(p.layer)&&(n.routableEscapeLayers??n.allowedLayers??[e.targetLayer]).includes(p.layer)||a&&e.via&&e.sourceLayer!==e.targetLayer&&m>0&&m<(e.sourceEscapeSegmentCount??1)&&p.layer===e.sourceLayer).toSorted((p,m)=>tn(m.segment.start,m.segment.end)-tn(p.segment.start,p.segment.end));for(const{segment:p,segmentIndex:m}of g){const _=p.width+i,f=tn(p.start,p.end),I=Math.min(12,Math.max(0,t.chamferLimit===void 0?Math.floor((f/_+.5)/4):Math.floor((f+_/2)/(4*t.chamferLimit+(t.plateauLength??_)+_))));for(let C=1;C<=I;C++)for(const y of t.placementFractions??[.5,0,1,.25,.75])for(const x of[1,-1]){oR(t.workBudget);const E=eSo({segment:p,toothCount:C,targetAddedLength:o,pitch:_,placementFraction:y,normalSign:x,plateauLength:t.plateauLength,chamferLimit:t.chamferLimit});if(!E||E.some(w=>!CNt(w,r))||!s&&E.slice(1,-1).some(w=>!_Nt(w,c,u)))continue;const B=E.slice(1).map((w,M)=>({start:E[M],end:w,width:p.width,layer:p.layer})),S=[...e.segments.slice(0,m),...B,...e.segments.slice(m+1)];if(p.layer===e.sourceLayer&&p.layer!==e.targetLayer&&B.some(w=>Tl(w,e.sourceObstacle)<w.width/2+i-Jr)||l(S,m,B.length)||!RPe({plan:e,segments:S,replacementStartIndex:m,replacementSegmentCount:B.length,clearance:i}))continue;const Q=bB(e,S,a);Q&&(yield Q)}}if(A)return;const h=e.segments.flatMap((p,m)=>a&&m===0?[p]:Zbo({segment:p,bounds:c,margin:u})),d=bB(e,h,a);d&&(yield*_w({...t,plan:d,denseBoundarySplitApplied:!0}))}function*oue(t){const{plan:e,bus:n,targetAddedLength:o,clearance:i}=t,r=fNt(n);for(let s=0;s<e.segments.length;s++){const a=e.segments[s],A=a.layer===e.sourceLayer&&a.layer!==e.targetLayer;if(A){if(!t.allowSourcePrefixMatching||!e.via||s===0)continue}else if(a.layer!==e.targetLayer&&(!t.allowTransitLayerMatching||!(n.allowedLayers??[e.targetLayer]).includes(a.layer)||!(n.routableEscapeLayers??n.allowedLayers??[e.targetLayer]).includes(a.layer)))continue;const c=tn(a.start,a.end);if(c<=Jr)continue;const l={x:(a.end.x-a.start.x)/c,y:(a.end.y-a.start.y)/c};for(let u=s+2;u<Math.min(e.segments.length,s+16)&&!e.segments.slice(s,u+1).some(C=>C.layer!==a.layer);u++){const h=e.segments[u],d=tn(h.start,h.end);if(d<=Jr)continue;const p={x:(h.end.x-h.start.x)/d,y:(h.end.y-h.start.y)/d};if(Math.abs(l.x+p.x)>Jr||Math.abs(l.y+p.y)>Jr)continue;oR(t.workBudget);const m=C=>({...C,x:C.x+l.x*o/2,y:C.y+l.y*o/2}),_=e.segments.map((C,y)=>y<s||y>u?C:y===s?{...C,end:m(C.end)}:y===u?{...C,start:m(C.start)}:{...C,start:m(C.start),end:m(C.end)}),f=_.slice(s,u+1);if(f.some((C,y)=>{const x=s+y;return _.some((E,B)=>{if(Math.abs(x-B)<2)return!1;const S=Math.min(x,B),Q=Math.max(x,B);return Q===S+2&&Vy(_[S].end,_[Q].start)?!1:NPe(C,E)})})||f.some(C=>[C.start,C.end].some(y=>!CNt(y,n.sharedBoundary)||!t.allowInsideDenseBounds&&!_Nt(y,r,C.width/2+i)))||A&&f.some(C=>Tl(C,e.sourceObstacle)<C.width/2+i-Jr)||!RPe({plan:e,segments:_,replacementStartIndex:s,replacementSegmentCount:u-s+1,clearance:i}))continue;const I=bB(e,_);I&&(yield I)}}}function o6(t){const e=t.map(n=>n.length);return Math.max(...e)-Math.min(...e)}function iR(t,e){return t.filter(n=>e.has(n.connectionIndex))}function*tSo(t,e,n){const o=INt(t.segments);for(const{segment:i,index:r}of t.segments.map((s,a)=>({segment:s,index:a})).filter(({segment:s})=>s.layer===t.targetLayer).toSorted((s,a)=>tn(a.segment.start,a.segment.end)-tn(s.segment.start,s.segment.end))){const s=tn(i.start,i.end);if(s<=Jr)continue;const a=Math.abs(i.end.x-i.start.x),A=Math.abs(i.end.y-i.start.y);if(a>Jr&&A>Jr&&Math.abs(a-A)>Jr)continue;const c={x:(i.end.x-i.start.x)/s,y:(i.end.y-i.start.y)/s},l=i.width+e;for(const u of[2,3,4,6]){const g=l*u;if(!(s<2*g+l))for(const h of[1,-1]){oR(n);const d={x:-c.y*h,y:c.x*h},p=[i.start,sI(sI(i.start,c,g),d,g),sI(sI(i.end,c,-g),d,g),i.end],m=p.slice(1).map((I,C)=>({...i,start:p[C],end:I})),_=[...t.segments.slice(0,r),...m,...t.segments.slice(r+1)];if(o(_,r,m.length)||!RPe({plan:t,segments:_,replacementStartIndex:r,replacementSegmentCount:m.length,clearance:e}))continue;const f=bB(t,_);f&&(yield f)}}}}function zy(t){if(t.maximumWorkUnits!==void 0&&(!Number.isSafeInteger(t.maximumWorkUnits)||t.maximumWorkUnits<0))throw new Error("maximumWorkUnits must be a non-negative safe integer");const e=t.maximumWorkUnits===void 0?void 0:{remaining:t.maximumWorkUnits},n=fPe(t.inputSrj),o=new Map;for(const r of t.plans){const s=o.get(r.connectionIndex)??[];s.push(r),o.set(r.connectionIndex,s)}t={...t,preparedBuses:t.preparedBuses.filter(r=>r.maxLengthSkew!==void 0||r.connections.some(s=>o.has(s.connectionIndex)))};for(const r of t.preparedBuses)if(r.connections.some(s=>{const a=o.get(s.connectionIndex);return a?.length!==1||a[0].busId!==r.busId||a[0].connectionName!==s.connection.name||t.inputSrj.connections[s.connectionIndex]?.name!==s.connection.name}))return{plans:null,failedBus:r};const i=Z0e({srj:t.inputSrj,sharedBoundary:t.sharedBoundary,clearance:t.clearance,allowBlindAndBuriedVias:t.allowBlindAndBuriedVias,allowSameNetMerges:t.allowSameNetMerges});try{const r=TPe(t,i,e);return r.plans?nSo(t,r.plans,n,i,e):r}catch(r){if(r instanceof yNt&&e?.activeBus)return{plans:null,failedBus:t.preparedBuses.find(s=>s.busId===e.activeBus.busId)??e.activeBus};throw r}}function xNt({plans:t,connectionIndex:e,connectionName:n}){const o=t.filter(s=>s.connectionIndex===e),i=o[0];if(o.length!==1||!i||i.connectionName!==n||!Number.isFinite(i.length))throw new Error(`Differential-pair matching cannot resolve exactly one original plan for ${n}`);const r=[...i.segments,...i.planeEndpointSegments??[]].reduce((s,a)=>s+tn(a.start,a.end),0);if(!Number.isFinite(r)||Math.abs(r-i.length)>Jr)throw new Error(`Differential-pair matching found inconsistent copper length for ${i.connectionName}`);return i}function iue({plans:t,pair:e}){return[xNt({plans:t,connectionIndex:e.connectionIndices[0],connectionName:e.connectionNames[0]}),xNt({plans:t,connectionIndex:e.connectionIndices[1],connectionName:e.connectionNames[1]})]}function nSo(t,e,n,o,i){const r=new Map(t.preparedBuses.flatMap(u=>u.connections.map(g=>[g.connectionIndex,{bus:u,connection:g}]))),s=n.filter(u=>u.connectionIndices.some(g=>r.has(g)));if(!s.length)return{plans:e};const a=t.preparedBuses.map(u=>({bus:u,indices:new Set(u.connections.map(g=>g.connectionIndex))}));let A=e;const c=u=>a.every(({bus:g,indices:h})=>{if(g.maxLengthSkew===void 0)return!0;const d=iR(u,h);return d.length===g.connections.length&&o6(d)<=g.maxLengthSkew+Jr});for(let u=0;u<=s.length;u++){for(const g of s){const h=iue({plans:A,pair:g});if(o6(h)<=g.lengthTolerance+Jr)continue;const d=g.connectionIndices.map(y=>r.get(y)),p=d.find(y=>y).bus;if(d.some(y=>!y))return{plans:null,failedBus:p};const m=h[0].length<=h[1].length?0:1,_=d[m].bus,f={..._,connections:d.map(y=>y.connection),maxLengthSkew:g.lengthTolerance},I=Math.max(...h.map(y=>y.length)),C=TPe({...t,plans:A,preparedBuses:[f],unroutedSourceBuses:void 0,allowUnconstrainedLaneRerouting:!1,allowPairLaneSpreading:d[0].bus===d[1].bus&&t.allowPairLaneSpreading,candidatePlansAreFeasible:y=>c(y)&&iue({plans:y,pair:g}).every(x=>x.length<=I+Jr)&&(!t.candidatePlansAreFeasible||t.candidatePlansAreFeasible(y))},o,i);if(!C.plans)return{plans:null,failedBus:_};A=C.plans}if(s.every(g=>o6(iue({plans:A,pair:g}))<=g.lengthTolerance+Jr))return c(A)?{plans:A}:{plans:null,failedBus:a.find(({bus:g,indices:h})=>g.maxLengthSkew!==void 0&&o6(iR(A,h))>g.maxLengthSkew+Jr).bus}}return{plans:null,failedBus:s.find(u=>o6(iue({plans:A,pair:u}))>u.lengthTolerance+Jr).connectionIndices.map(u=>r.get(u)?.bus).find(u=>u)}}function TPe(t,e,n){const{preparedBuses:o,inputSrj:i,sharedBoundary:r,clearance:s,allowBlindAndBuriedVias:a=!0,allowSameNetMerges:A=!1,allowMatchingInsideDenseBounds:c=!1,candidatePlansAreFeasible:l}=t,u=m=>(oR(n),e(m));let g=[...t.plans],h=0;const d=new Set(t.unroutedSourceBuses?.flatMap(m=>m.connections.map(_=>_.connectionIndex))),p=o.filter(m=>m.maxLengthSkew!==void 0&&m.connections.length>1);if(p.length===0)return{plans:g};for(const m of p){const _=new Set(m.connections.map(y=>y.connectionIndex));if(n&&(n.activeBus=m),m.termination.type!=="boundary")return{plans:null,failedBus:m};const f=m.connections.length*(t.allowDistributedMatching?24:2),I=new Set;for(let y=0;y<f;y++){const x=iR(g,_);if(x.length!==m.connections.length)return{plans:null,failedBus:m};const E=m.maxLengthSkew,B=o6(x);if(B<=E+Jr)break;const S=x.filter(U=>!I.has(U.connectionIndex)).toSorted((U,Y)=>U.length-Y.length||U.connectionName.localeCompare(Y.connectionName))[0],Q=Math.max(...x.map(U=>U.length));if(!S||Q-S.length<=E+Jr)return{plans:null,failedBus:m};const w=Q-S.length,M=Math.max(Jr,w-E+Jr),k=[M,M+E*.1,w-E*.5,w-E*.75,w,w+E].filter((U,Y,W)=>U>Jr&&W.findIndex(te=>Math.abs(te-U)<Jr)===Y).toSorted((U,Y)=>U-Y);let R=null;const F=U=>{const Y=g.map(te=>te===S?U:te),W=iR(Y,_);return o6(W)>B+Jr||!u(Y)||l&&!l(Y)?null:Y};if(t.allowMultiSegmentTuningWindows){const U=Math.max(S.length+M,...fPe(i).filter(Y=>Y.connectionIndices.includes(S.connectionIndex)).flatMap(Y=>Y.connectionIndices.filter(W=>W!==S.connectionIndex).flatMap(W=>{const te=g.find(j=>j.connectionIndex===W);return te?[te.length-Y.lengthTolerance+Jr]:[]})));for(const Y of Abo({plan:S,bus:m,inputSrj:i,plans:g,layerNames:Rb(i.layerCount),clearance:s,consumeWork:()=>oR(n)})){const W={...S,additionalVias:[...S.additionalVias??[],...Y.addedVias]},te=_e=>bB(W,[...Y.before,..._e,...Y.after]),j=(_e,ue)=>{const fe=m.sharedBoundary;for(const[ye,Me]of ue.entries()){const ve=Me.end.x-Me.start.x,he=Me.end.y-Me.start.y;if(Math.min(Math.abs(ve),Math.abs(he),Math.abs(Math.abs(ve)-Math.abs(he)))>1e-7||[Me.start,Me.end].some(Pe=>Pe.x<=fe.minX+1e-7||Pe.x>=fe.maxX-1e-7||Pe.y<=fe.minY+1e-7||Pe.y>=fe.maxY-1e-7))return!1;const Qe=ue[ye+1];if(Qe){const Pe=Qe.end.x-Qe.start.x,we=Qe.end.y-Qe.start.y;if((ve*Pe+he*we)/(Math.hypot(ve,he)*Math.hypot(Pe,we))<Math.SQRT1_2-1e-7)return!1}if(i.obstacles.some(Pe=>Pe.layers.includes(Me.layer)&&Tl(Me,Pe)<Me.width/2+s-1e-9))return!1}const pe=new Set(ue.map((ye,Me)=>Y.before.length+Me));return nue(_e,Y.addedVias,s)&&bO(_e,_e.segments,s,pe)},J=te(Y.window);if(!J||!j(J,Y.window)||!u(g.map(_e=>_e===S?J:_e)))continue;const oe={...J,targetLayer:Y.tuningLayer,segments:Y.window},ie=U-J.length,ne={plan:oe,bus:m,targetAddedLength:ie,clearance:s,sharedBoundary:m.sharedBoundary,allowInsideDenseBounds:c,workBudget:n},le=Y.window[0].width+s,ge=[oue(ne),...[1,2,4,8].map(_e=>_w({...ne,plateauLength:le*_e,chamferLimit:le/4,placementFractions:[.5,0,1,.25,.75,.1,.9]}))];for(const _e of ge){for(const ue of _e){const fe=te(ue.segments);if(!(!fe||!j(fe,ue.segments))&&(R=F(fe),R))break}if(R)break}if(R)break}}const O=U=>{let te=0;const j=oe=>oe.length<=48?[...oe]:Array.from({length:48},(ie,ne)=>oe[Math.floor(ne*oe.length/48)]),J=(oe,ie)=>{oR(n);const ne=oe.length-S.length,le=U-ne;if(le<=Jr)return F(oe);if(ie<=0)return null;const ge=le/ie,_e=j([..._w({plan:oe,bus:m,targetAddedLength:ge,clearance:s,sharedBoundary:m.sharedBoundary,allowInsideDenseBounds:c,allowSourcePrefixMatching:t.allowSourcePrefixMatching,allowTransitLayerMatching:t.allowTransitLayerMatching,workBudget:n})]);for(const ue of _e){if(te++,te>320)return null;if(!F(ue))continue;const fe=J(ue,ie-1);if(fe)return fe}return null};for(let oe=2;oe<=8;oe++){const ie=J(S,oe);if(ie)return ie;if(te>320)break}return null};for(const U of k){if(R)break;if(t.allowDistributedMatching){for(const W of oue({plan:S,bus:m,targetAddedLength:U,clearance:s,allowInsideDenseBounds:c,allowSourcePrefixMatching:t.allowSourcePrefixMatching,allowTransitLayerMatching:t.allowTransitLayerMatching,workBudget:n}))if(R=F(W),R)break;if(R)break}const Y=_w({plan:S,bus:m,targetAddedLength:U,clearance:s,sharedBoundary:m.sharedBoundary,allowInsideDenseBounds:c,allowSourcePrefixMatching:t.allowSourcePrefixMatching,allowTransitLayerMatching:t.allowTransitLayerMatching,workBudget:n});for(const W of Y)if(R=F(W),!!R)break;if(!R&&Math.abs(U-M)<=Jr){if(t.allowDistributedMatching)for(const W of[U/2,U/4,Math.min(U,1),Math.min(U,.5),Math.min(U,.25),Math.min(U,.1)]){if(W<=Jr)continue;const te={plan:S,bus:m,targetAddedLength:W,clearance:s,sharedBoundary:m.sharedBoundary,allowInsideDenseBounds:c,allowSourcePrefixMatching:t.allowSourcePrefixMatching,allowTransitLayerMatching:t.allowTransitLayerMatching,workBudget:n};for(const j of[oue(te),_w(te)]){for(const J of j)if(R=F(J),R)break;if(R)break}if(R)break}R||(R=O(U))}if(R)break}if(!R&&t.allowAdditionalMatchingVias)for(const U of Xbo({plan:S,bus:m,layerNames:Rb(i.layerCount),clearance:s,workBudget:n})){if(!u(g.map(W=>W===S?U.plan:W)))continue;const Y={plan:{...U.plan,targetLayer:U.tuningLayer},bus:m,targetAddedLength:M,clearance:s,sharedBoundary:m.sharedBoundary,allowInsideDenseBounds:c,workBudget:n};for(const W of[oue(Y),_w(Y)]){for(const te of W)if(nue(te,U.addedVias,s)&&(R=F({...te,targetLayer:S.targetLayer}),R))break;if(R)break}if(R)break}if(!R&&t.allowPairLaneSpreading&&m.connections.length===2){const U=x.find(W=>W!==S);let Y=0;for(const W of tSo(U,s,n)){const te=g.map(J=>J===U?W:J);if(!u(te)||l&&!l(te))continue;const j=TPe({...t,plans:te,preparedBuses:[m],allowPairLaneSpreading:!1},e,n);if(j.plans){R=j.plans;break}if(++Y>=4)break}}if(!R&&t.allowUnconstrainedLaneRerouting){let U=0;e:for(const Y of k){const W=_w({plan:S,bus:m,targetAddedLength:Y,clearance:s,sharedBoundary:m.sharedBoundary,allowInsideDenseBounds:c,allowSourcePrefixMatching:t.allowSourcePrefixMatching,allowTransitLayerMatching:t.allowTransitLayerMatching,workBudget:n});for(const te of W){if(!u([te]))continue;const j=g.filter(ne=>ne!==S&&!e.mutuallyClear([te,ne]));if(j.length!==1)continue;const J=j[0],oe=o.find(ne=>ne.busId===J.busId);if(!oe||oe.termination.type!=="boundary"||oe.maxLengthSkew!==void 0||oe.connections.length!==1||!J.via||J.additionalVias?.length||J.planeEndpointVia||J.segments.filter(ne=>ne.layer===J.sourceLayer).length!==1)continue;const ie=g.map(ne=>ne===S?te:ne);for(const ne of[!0,!1]){if(U++>=4)break e;const le=rNt({srj:i,bus:oe,terminals:[{connection:oe.connections[0],viaPoint:J.via.center,exitPoint:J.exitPoint}],targetLayer:J.targetLayer,acceptedPlans:ie.filter(ue=>ue!==J),layerNames:Rb(i.layerCount),traceWidth:J.segments[0].width,viaDiameter:J.via.diameter,viaHoleDiameter:J.via.holeDiameter,clearance:s,allowBlindAndBuriedVias:a,allowSameNetMerges:A,gridStepDivisor:2,alignGridToPads:ne,maximumRouteOrderAttempts:1,preferTargetDirectedLaneBias:!0})?.[0];if(!le)continue;const ge=bB(J,[J.segments[0],...le.segments.slice(1)]);if(!ge)continue;const _e=ie.map(ue=>ue===J?ge:ue);if(!(o6(iR(_e,_))>E+Jr||!u(_e)||l&&!l(_e))){R=_e;break e}}}}}if(!R&&t.unroutedSourceBuses?.length)e:for(const U of k)for(const Y of _w({plan:S,bus:m,targetAddedLength:U,clearance:s,sharedBoundary:m.sharedBoundary,allowInsideDenseBounds:c,allowSourcePrefixMatching:t.allowSourcePrefixMatching,allowTransitLayerMatching:t.allowTransitLayerMatching,workBudget:n})){if(h>=4)break e;if(!u([Y]))continue;const W=g.filter(j=>j!==S&&!e.mutuallyClear([Y,j]));if(W.length!==1||!d.has(W[0].connectionIndex))continue;h++;const te=$bo({inputSrj:i,plans:g.map(j=>j===S?Y:j),unroutedSourceBuses:t.unroutedSourceBuses,clearance:s});if(!(!te||o6(iR(te,_))>B+Jr||!u(te)||l&&!l(te))){R=te;break e}}if(!R){if(t.allowDistributedMatching){I.add(S.connectionIndex);continue}return{plans:null,failedBus:m}}g=R}const C=iR(g,_);if(o6(C)>m.maxLengthSkew+Jr)return{plans:null,failedBus:m}}return{plans:g}}function ENt(t){const{points:e,topZ:n,traceWidth:o,viaDiameter:i,clearance:r}=t,s=[],a=[];let A=0;for(let l=0;l+1<e.length;l++){const u=e[l],g=e[l+1];if(u.z!==g.z){if(tn(u,g)>1e-7)return!1;a.push({center:u,fromZ:u.z,toZ:g.z,edge:l}),A++}else tn(u,g)>1e-9&&s.push({a:u,b:g,z:u.z,edge:l,run:A})}const c=s.filter(l=>l.z===n);for(let l=0;l<c.length;l++)for(let u=l+1;u<c.length;u++){const g=c[l],h=c[u];if(g.run!==h.run&&tu(g.a,g.b,h.a,h.b)<o+r-1e-9)return!1}for(let l=0;l<a.length;l++){const u=a[l];for(let d=l+1;d<a.length;d++)if(tn(u.center,a[d].center)<i+r-1e-9)return!1;const g=(i+o)/2+r,h=new Set;for(const d of[-1,1]){let p=u.center,m=0;const _=d===-1?u.fromZ:u.toZ;for(let f=u.edge+d;f>=0&&f+1<e.length;f+=d){const I=e[f],C=e[f+1],y=d===-1?C:I,x=d===-1?I:C;if(I.z!==_||C.z!==_||tn(p,y)>1e-7||m>g+1e-7)break;h.add(f),m+=tn(y,x),p=x}}for(const d of s)if(!h.has(d.edge)&&Cr(u.center,d.a,d.b)<g-1e-9)return!1}return!0}var ef=1e-7,kPe=180;function oSo(t,e){const n=e.x-t.x,o=e.y-t.y,i=Math.min(Math.abs(n),Math.abs(o));return Math.abs(n)<ef||Math.abs(o)<ef||Math.abs(Math.abs(n)-Math.abs(o))<ef?[[t,e]]:[[t,{x:t.x+Math.sign(n)*i,y:t.y+Math.sign(o)*i,z:t.z},e],[t,{x:e.x-Math.sign(n)*i,y:e.y-Math.sign(o)*i,z:t.z},e],[t,{x:t.x,y:e.y,z:t.z},e],[t,{x:e.x,y:t.y,z:t.z},e]]}function iSo(t,e,n){if(t.length<3)return t;const o=t.length,i=o<=kPe?t.map((c,l)=>l):[...new Set([0,...Array.from({length:kPe-2},(c,l)=>Math.round((l+1)*(o-1)/(kPe-1))),o-1])],r=new Float64Array(o).fill(1/0),s=new Array(o);r[0]=0;for(let c=1;c<i.length;c++){const l=i[c];for(let u=0;u<c;u++){const g=i[u],h=t[g],d=t[l],p=Math.abs(d.x-h.x),m=Math.abs(d.y-h.y),_=Math.max(p,m)+(Math.SQRT2-1)*Math.min(p,m);if(!(r[g]+_>=r[l]-ef))for(const f of oSo(h,d)){const I=f.slice(1).reduce((C,y,x)=>C+tn(f[x],y),0);r[g]+I>=r[l]-ef||!f.slice(1).every((C,y)=>n(f[y],C))||(r[l]=r[g]+I,s[l]={previous:g,points:f})}}if(!s[l]){const u=i[c-1],g=t.slice(u,l+1);r[l]=r[u]+g.slice(1).reduce((h,d,p)=>h+tn(g[p],d),0),s[l]={previous:u,points:g}}}const a=[];for(let c=o-1;c>0;){const l=s[c];if(!l)throw new Error("FanoutSolver: shortcut graph lost a retained path");a.unshift(l.points),c=l.previous}const A=a.flatMap((c,l)=>l?c.slice(1):c);return eR({points:A,chamfer:e/4,segmentIsClear:n})??t}function BNt(t,e,n){return t.x<e.minX-ef||t.x>e.maxX+ef||t.y<e.minY-ef||t.y>e.maxY+ef?!1:!(Math.abs(t.x-e.minX)<ef||Math.abs(t.x-e.maxX)<ef||Math.abs(t.y-e.minY)<ef||Math.abs(t.y-e.maxY)<ef)||tn(t,n)<ef}function SO(t){const{inputSrj:e,preparedBuses:n,layerNames:o,clearance:i,allowBlindAndBuriedVias:r=!0,allowSameNetMerges:s=!1}=t,a=new Map(n.map(g=>[g.busId,g])),A=new Map(n.map(g=>[g.busId,Math.min(...t.plans.filter(h=>h.busId===g.busId).map(h=>h.length))])),c=Z7(e,r);let l=[...t.plans];for(let g=0;g<3;g++){let h=!1;for(const d of l.toSorted((p,m)=>m.length-p.length)){const p=a.get(d.busId),m=A.get(d.busId);if(!p||m===void 0||!Number.isFinite(m)||p.maxLengthSkew===void 0||d.termination.type!=="boundary"||d.length<=m+p.maxLengthSkew+ef||t.selectedBusIds&&!t.selectedBusIds.has(d.busId)||t.selectedConnectionIndices&&!t.selectedConnectionIndices.has(d.connectionIndex))continue;const _=d.trace.route.findIndex(R=>R.route_type==="via");if(_<0)continue;const f=R=>R===d.connectionName||s&&Px(e,R,d.connectionName),I=l.filter(R=>R.connectionIndex!==d.connectionIndex&&!f(R.connectionName)),C=c.filter(R=>!f(R.connectionName)),y=new qj([...I.flatMap(R=>[...R.segments,...R.planeEndpointSegments??[]]),...C.flatMap(R=>R.segments)]),x=[...I.flatMap(R=>[R.via,...R.additionalVias??[],R.planeEndpointVia].filter(F=>!!F)),...C.flatMap(R=>R.vias)],E=e.obstacles.filter(R=>!(s&&n4(e,R,d.connectionName)));let B=_+1;if(t.allowSourcePrefixShortcuts)for(B=1;B<_;){const R=d.trace.route[B];if(R.route_type==="wire"&&wx(R,d.sourceObstacle)>=R.width/2+i-1e-9)break;B++}const S=d.trace.route.slice(0,B);let Q=B;for(;Q<d.trace.route.length;){const R=d.trace.route[Q];if(R.route_type!=="wire"){S.push(R),Q++;continue}let F=Q+1;for(;F<d.trace.route.length;){const ie=d.trace.route[F];if(ie.route_type!=="wire"||ie.layer!==R.layer)break;F++}const O=d.trace.route.slice(Q,F),U=o.indexOf(R.layer);if(U<0)throw new Error(`FanoutSolver: shortcut uses unknown layer ${R.layer}`);const Y=O.map(ie=>({x:ie.x,y:ie.y,z:U})),W=Math.max(...O.map(ie=>ie.width)),te=S.at(-1),j=(ie,ne)=>{const le={start:ie,end:ne,layer:R.layer,width:W};return BNt(ie,p.sharedBoundary,d.exitPoint)&&BNt(ne,p.sharedBoundary,d.exitPoint)&&E.every(ge=>!ge.layers.includes(R.layer)||Q<_&&ge===d.sourceObstacle&&te?.route_type==="wire"&&Cr(ie,te,Y[0])<ef&&Cr(ne,te,Y[0])<ef||Tl(le,ge)>=W/2+i-1e-9)&&y.querySegment(le,i).every(ge=>Zm(le,ge,i))&&x.every(ge=>!ge.spanLayers.includes(R.layer)||Cr(ge.center,ie,ne)>=(W+ge.diameter)/2+i-1e-9)};let J=iSo(Y,W,j),oe;if(Q<_&&te?.route_type==="wire"&&te.layer===R.layer){const ie=eR({points:[{x:te.x,y:te.y,z:U},...J],chamfer:W/4,segmentIsClear:j});ie?(S.pop(),oe=te,J=ie):J=Y}S.push(...J.map((ie,ne)=>({...ne===0?oe:void 0,route_type:"wire",x:ie.x,y:ie.y,layer:R.layer,width:W}))),Q=F}const w={...d.trace,route:S},M=J0e(e,w,r).segments,k={...d,trace:w,segments:M,...t.allowSourcePrefixShortcuts?{sourceEscapeSegmentCount:M.findIndex(R=>R.layer!==d.sourceLayer)}:{},length:M.reduce((R,F)=>R+tn(F.start,F.end),0)};k.length<m-ef||k.length>=d.length-ef||t.allowSourcePrefixShortcuts&&!ENt({points:w.route.flatMap(R=>R.route_type==="wire"?[{x:R.x,y:R.y,z:o.indexOf(R.layer)}]:[]),topZ:o.indexOf(d.sourceLayer),traceWidth:t.traceWidth,viaDiameter:d.via.diameter,clearance:i})||Wh({plans:[k],srj:{...e,traces:[...e.traces??[],...I.flatMap(R=>[R.trace,...R.planeEndpointTrace?[R.planeEndpointTrace]:[]])]},sharedBoundary:p.sharedBoundary,clearance:i,allowBlindAndBuriedVias:r,allowSameNetMerges:s})&&(l=l.map(R=>R===d?k:R),h=!0)}if(!h)break}return qu({inputSrj:e,routedSrj:{...e,traces:[...e.traces??[],...l.flatMap(g=>[g.trace,...g.planeEndpointTrace?[g.planeEndpointTrace]:[]])]},clearance:i,allowBlindAndBuriedVias:r}).valid?l:null}function rSo(t,e,n,o,i,r,s){if(s&&n==="top"&&Tl({start:t,end:t},r)<o/2+i-1e-9&&tn(e,s.sourcePoint)>=tn(t,s.sourcePoint)-1e-9)return s.connectionName}function sSo(t){const e=new Int32Array(t.planeSize+1),n=[],o=[];for(let i=0;i<t.planeSize;i++){e[i]=n.length;const r=new Set;for(let c=t.neighborOffset[i];c<t.neighborOffset[i+1];c++){const l=t.neighborIds[c];r.add(l),n.push(l),o.push(t.neighborCosts[c])}const s=new Set,a=t.cellMaxX[i]-t.cellMinX[i],A=t.cellMaxY[i]-t.cellMinY[i];for(let c=t.neighborOffset[i];c<t.neighborOffset[i+1];c++){const l=t.neighborIds[c];for(let u=t.neighborOffset[l];u<t.neighborOffset[l+1];u++){const g=t.neighborIds[u];if(g===i||r.has(g))continue;const h=Math.abs(t.cellCenterX[g]-t.cellCenterX[i]),d=Math.abs(t.cellCenterY[g]-t.cellCenterY[i]);h<1e-9||Math.abs(h-d)>1e-9||Math.abs(h-a)>1e-9||Math.abs(d-A)>1e-9||Math.abs(t.cellMaxX[g]-t.cellMinX[g]-a)>1e-9||Math.abs(t.cellMaxY[g]-t.cellMinY[g]-A)>1e-9||s.add(g)}}for(const c of[...s].sort((l,u)=>l-u))n.push(c),o.push(Math.hypot(t.cellCenterX[c]-t.cellCenterX[i],t.cellCenterY[c]-t.cellCenterY[i]))}return e[t.planeSize]=n.length,{neighborOffset:e,neighborIds:Int32Array.from(n),neighborCosts:Float32Array.from(o)}}function aSo(t){const{edge:e,bounds:n,exit:o,approachLength:i}=t;if(!["left","right","top","bottom"].includes(e))throw new Error("Terminal approach requires a valid boundary edge");if(!Number.isFinite(i)||i<=0)throw new Error("terminalApproachLength must be finite and positive");const r=e==="left"||e==="right",s=e==="left"?n.minX:e==="right"?n.maxX:e==="bottom"?n.minY:n.maxY,a=e==="left"||e==="bottom"?-1:1,A=r?{x:o.x-a*i,y:o.y}:{x:o.x,y:o.y-a*i};if(![o.x,o.y,A.x,A.y,n.minX,n.maxX,n.minY,n.maxY].every(Number.isFinite)||Math.abs((r?o.x:o.y)-s)>1e-7||A.x<=n.minX||A.x>=n.maxX||A.y<=n.minY||A.y>=n.maxY)throw new Error("Terminal approach must end on its shared edge and start inside it");return{connectionName:t.connectionName,edge:e,layer:t.layer,exit:{...o},goal:A}}function rue(t,e){const{goal:n,edge:o}=e,i=o==="left"||o==="right",r=o==="left"||o==="bottom"?-1:1,s=i?n.x-t.x:n.y-t.y,a=i?n.y-t.y:n.x-t.x,A=r*s;if(A<Math.abs(a)-1e-9){if(A<=1e-9)return null;const l=i?{x:t.x,y:n.y-Math.sign(a)*A}:{x:n.x-Math.sign(a)*A,y:t.y};return[t,l,n]}const c=i?{x:t.x+r*Math.abs(a),y:n.y}:{x:n.x,y:t.y+r*Math.abs(a)};return[t,c,n].filter((l,u,g)=>u===0||tn(l,g[u-1])>1e-10)}var ASo=(t,e,n=e)=>t.some(o=>Math.max(e.x,n.x)>=o.minX&&Math.min(e.x,n.x)<=o.maxX&&Math.max(e.y,n.y)>=o.minY&&Math.min(e.y,n.y)<=o.maxY);function bNt(t,e,n){const o=[];let i=0;for(const[A,c]of t.entries()){if(c.layer===n&&Cr(e,c.start,c.end)<1e-8){const l=i+tn(c.start,e);o.some(u=>Math.abs(u.offset-l)<1e-8)||o.push({index:A,offset:l})}i+=tn(c.start,c.end)}if(o.length!==1)return null;let r=o[0].index;const s=t[r],a=[...t];return tn(e,s.end)<1e-8?r++:tn(e,s.start)>1e-8&&(a.splice(r,1,{...s,end:e},{...s,start:e}),r++),r>=a.length?null:{segments:a,changed:new Set(a.slice(r).map((A,c)=>r+c))}}function FPe(t){const{plan:e,splice:n,clearance:o,maximumJoinLength:i}=t,{rawSegments:r,firstEntrySegmentIndex:s}=n;if(!Number.isInteger(s)||s<0||s>=r.length||!Number.isFinite(i)||i<0)return!1;const a=(g,h,d=g)=>{const p={...e,segments:[...g]},m=[e.via,...e.additionalVias??[],e.planeEndpointVia].filter(_=>!!_).filter(_=>[...h].some(f=>{const I=g[f];return _.spanLayers.includes(I.layer)&&Cr(_.center,I.start,I.end)<(_.diameter+I.width)/2+o+1e-7}));return nue({...p,segments:[...d]},m,o)&&bO(p,g,o,h)};if(!a(r,new Set(r.slice(s).map((g,h)=>s+h))))return!1;const A=r[s],c=r[s-1];let l=A.start;if(c?.layer===A.layer&&tn(c.end,l)<1e-8){let g=c.start;for(let p=s-2;p>=0;p--){const m=r[p];if(m.layer!==c.layer||tn(m.end,g)>1e-8)break;const _=g.x-m.start.x,f=g.y-m.start.y,I=l.x-g.x,C=l.y-g.y;if(Math.abs(_*C-f*I)>=1e-10||_*I+f*C<0)break;g=m.start}const h=tn(g,l);if(h<1e-10)return!1;const d=Math.min(i,h/3);l={x:l.x+(g.x-l.x)*d/h,y:l.y+(g.y-l.y)*d/h}}const u=bNt(e.segments,l,A.layer);return!!u&&a(u.segments,u.changed,e.segments)}function*cSo(t){const{splice:e,connector:n,clearance:o}=t,i=e.firstEntrySegmentIndex,r=e.rawSegments[i];if(!r||r.layer!==n.layer)return;const s=4*(r.width+o);let a=0;for(let A=i;A>=Math.max(0,i-16);A--){const c=e.rawSegments[A];if(c.layer!==n.layer||A<i&&tn(c.end,e.rawSegments[A+1].start)>1e-7||(A<i&&(a+=tn(c.start,c.end)),a>s+1e-7))break;const l=c.start,{goal:u,exit:g,edge:h}=n,d=h==="left"||h==="right",p=h==="left"||h==="bottom"?-1:1,m=p*(d?u.x-l.x:u.y-l.y),_=Math.abs(d?u.y-l.y:u.x-l.x),f=[];if(A<i){const I=rue(l,n);I&&f.push(I)}if(m>=_-1e-9){const I=d?{x:u.x-p*_,y:l.y}:{x:l.x,y:u.y-p*_};f.push([l,I,u])}for(const I of f){const C=[...I,g].filter((y,x,E)=>x===0||tn(y,E[x-1])>1e-10);yield{replacement:C.slice(1).map((y,x)=>({...c,start:C[x],end:y})),firstEntrySegmentIndex:A}}}}function lSo(t){const e=[...t.plans],n=new Map(t.splices);for(const[o,i]of e.entries()){const r=t.connectors.get(i.connectionName);if(!r)continue;const s=n.get(i.connectionName);if(!s)return null;if(FPe({plan:i,splice:s,maximumJoinLength:0,clearance:t.clearance}))continue;const a=e.filter(c=>c.connectionIndex!==i.connectionIndex);let A=!1;for(const{replacement:c,firstEntrySegmentIndex:l}of cSo({splice:s,connector:r,clearance:t.clearance})){const u=c[0],g=bNt(i.segments,u.start,u.layer);if(!g)continue;const h=Math.min(...g.changed),d=[...g.segments.slice(0,h),...c],p=bB(i,d);if(!p)continue;const m={rawSegments:[...s.rawSegments.slice(0,l),...c],firstEntrySegmentIndex:l};if(FPe({plan:p,splice:m,maximumJoinLength:0,clearance:t.clearance})&&!c.some(_=>!t.segmentIsClear(_,i.connectionName)||a.some(f=>[...f.segments,...f.planeEndpointSegments??[]].some(I=>!Zm(_,I,t.clearance))||[f.via,...f.additionalVias??[],f.planeEndpointVia].filter(I=>!!I).some(I=>I.spanLayers.includes(_.layer)&&Cr(I.center,_.start,_.end)<(I.diameter+_.width)/2+t.clearance-1e-9)))){e[o]=p,n.set(i.connectionName,m),A=!0;break}}if(!A)return null}return{plans:e,splices:n}}function uSo(t){const{grid:e}=t;if(!Number.isFinite(t.margin)||t.margin<0)throw new Error("Terminal connector margin must be finite and non-negative");const n=c=>({x:e.cellCenterX[c],y:e.cellCenterY[c]}),o=new Map,i=new Set,r=new Map;for(const{connector:c,cellId:l}of t.terminals){if(!Number.isInteger(l)||l<0||l>=e.planeSize)throw new Error("Invalid native terminal cell");const u=new Set([l]);for(let p=e.neighborOffset[l];p<e.neighborOffset[l+1];p++){const m=e.neighborIds[p];u.add(m);for(let _=e.neighborOffset[m];_<e.neighborOffset[m+1];_++)u.add(e.neighborIds[_])}const g=[c.exit,c.goal,...[...u].map(n)],h={minX:Math.min(...g.map(p=>p.x))-t.margin,maxX:Math.max(...g.map(p=>p.x))+t.margin,minY:Math.min(...g.map(p=>p.y))-t.margin,maxY:Math.max(...g.map(p=>p.y))+t.margin},d=r.get(c.edge);r.set(c.edge,d?{minX:Math.min(d.minX,h.minX),maxX:Math.max(d.maxX,h.maxX),minY:Math.min(d.minY,h.minY),maxY:Math.max(d.maxY,h.maxY)}:h);for(const p of u){if(p===l)continue;let m=!1;for(let I=e.neighborOffset[p];I<e.neighborOffset[p+1];I++)e.neighborIds[I]===l&&(m=!0);if(m)continue;const _=rue(n(p),c);if(!_||_.slice(1).some((I,C)=>!t.segmentIsClear(_[C],I,c)))continue;const f=o.get(p)??new Set;f.add(l),o.set(p,f),i.add(`${p}:${l}`)}}const s=new Int32Array(e.planeSize+1),a=[],A=[];for(let c=0;c<e.planeSize;c++){s[c]=a.length;for(let l=e.neighborOffset[c];l<e.neighborOffset[c+1];l++)a.push(e.neighborIds[l]),A.push(e.neighborCosts[l]);for(const l of o.get(c)??[])a.push(l),A.push(tn(n(c),n(l)))}return s[e.planeSize]=a.length,{neighborOffset:s,neighborIds:Int32Array.from(a),neighborCosts:Float32Array.from(A),extendedEdges:i,regions:[...r.values()]}}function gSo(t,e,n){const o=t.route.at(-2),i=t.route.at(-1);if(!o||!i||tn(i,e.goal)>1e-7)throw new Error("Native terminal route does not end at its reserved goal");let r=t.route.slice(0,-2),s=o;if(o.z!==i.z){if(tn(o,n)>1e-7)throw new Error("Native terminal via has a noncoincident departure");r=[...r,o],s={...n,z:i.z}}const a=rue(s,e);if(!a)throw new Error("Native terminal route has no perpendicular entry");return{...t,route:[...r,...a.map(A=>({...A,z:i.z})),{...e.exit,z:i.z}]}}var dSo=class{constructor(t){this.params=t,this.padding=Math.max(t.traceWidth,t.viaDiameter)+t.clearance,this.cellSize=Math.max(t.traceWidth+t.clearance,t.viaDiameter)}params;dirty=!0;buckets=new Map;cellSize;padding;invalidate(){this.dirty=!0}intersects(t,e=t){return ASo(this.params.regions,t,e)}cells(t,e,n,o){for(let i=Math.floor((Math.min(t.x,e.x)-n)/this.cellSize);i<=Math.floor((Math.max(t.x,e.x)+n)/this.cellSize);i++)for(let r=Math.floor((Math.min(t.y,e.y)-n)/this.cellSize);r<=Math.floor((Math.max(t.y,e.y)+n)/this.cellSize);r++)o(`${i},${r}`)}refresh(){if(!this.dirty)return;this.buckets.clear();const t=(e,n,o=n)=>{this.intersects(n,o)&&this.cells(n,o,this.padding,i=>{const r=this.buckets.get(i)??new Set;r.add(e),this.buckets.set(i,r)})};for(const e of this.params.getRoutes()){for(let n=1;n<e.route.length;n++){const o=e.route[n-1],i=e.route[n];o.z===i.z&&t({kind:"segment",owner:e.connectionName,a:o,b:i},o,i)}for(const n of e.vias)t({kind:"via",owner:e.connectionName,center:n},n)}this.dirty=!1}nearby(t,e=t){this.refresh();const n=new Set;return this.cells(t,e,0,o=>{for(const i of this.buckets.get(o)??[])n.add(i)}),n}blockingSegmentOwners(t,e,n){const o=new Set;for(let i=1;i<e.length;i++){const r=e[i-1],s=e[i];if(this.intersects(r,s))for(const a of this.nearby(r,s)){if(a.owner===t)continue;const A=a.kind==="via"?Cr(a.center,r,s):a.a.z===n?tu(r,s,a.a,a.b):1/0,c=(this.params.traceWidth+(a.kind==="via"?this.params.viaDiameter:this.params.traceWidth))/2+this.params.clearance;A<c-1e-9&&o.add(a.owner)}}return o}blockingViaOwners(t,e){const n=new Set;if(!this.intersects(e))return n;for(const o of this.nearby(e)){if(o.owner===t)continue;const i=o.kind==="via"?tn(e,o.center):Cr(e,o.a,o.b),r=(this.params.viaDiameter+(o.kind==="via"?this.params.viaDiameter:this.params.traceWidth))/2+this.params.clearance;i<r-1e-9&&n.add(o.owner)}return n}};function hSo(t){if(typeof t.fillViaOccupants!="function"||typeof t.pushFlatOccupants!="function")throw new Error("FanoutSolver: native via-occupant interface changed");const e=t.fillViaOccupants.bind(t),n=t.pushFlatOccupants.bind(t),o=new Map;t.fillViaOccupants=(i,r)=>{const s=o.get(i);if(s){const c=t._viaOccs;c.length=0;const l=t.usedCellsFlat,u=t.sharedCellsFlat;for(let g=0;g<s.length;g++){const h=s[g];l&&u&&l[h]===-1&&!u[h]||n(h,r,c)}return}const a=[],A=t.pushFlatOccupants;t.pushFlatOccupants=(c,l,u)=>{a.push(c),n(c,l,u)};try{e(i,r)}finally{t.pushFlatOccupants=A}o.set(i,Int32Array.from(a))}}var pSo=1e-9;function LPe(t){const{vias:e,activeConnectionIndices:n,traceWidth:o,clearance:i,gridStep:r}=t;for(const[g,h]of[["traceWidth",o],["gridStep",r]])if(!Number.isFinite(h)||h<=0)throw new Error(`FanoutSolver: ${g} must be positive and finite`);if(!Number.isFinite(i)||i<0)throw new Error("FanoutSolver: clearance must be non-negative and finite");for(const g of e)if(!Number.isSafeInteger(g.connectionIndex)||g.connectionIndex<0||!Number.isFinite(g.center.x)||!Number.isFinite(g.center.y)||!Number.isFinite(g.diameter)||g.diameter<=0)throw new Error("FanoutSolver: invalid via channel grid site");const s=g=>(g%r+r)%r,a=g=>{const h=s(g+r/2)-r/2;return Math.abs(h)<Number.EPSILON?0:h},A=(o+i)/r,c=Math.ceil(A-Number.EPSILON*Math.max(1,Math.abs(A))*4),l=Number.EPSILON*Math.max(1,r)*32,u=g=>{const h=g==="x"?"y":"x",d=e.toSorted((y,x)=>y.center[h]-x.center[h]||y.center[g]-x.center[g]||y.connectionIndex-x.connectionIndex),p=[];for(const y of d){const x=p.at(-1);x&&Math.abs(x[0].center[h]-y.center[h])<=pSo?x.push(y):p.push([y])}const m=[];for(const y of p){y.sort((x,E)=>x.center[g]-E.center[g]);for(let x=1;x<y.length;x++){const E=y[x-1],B=y[x],S=E.center[g]+E.diameter/2+o/2+i,Q=B.center[g]-B.diameter/2-o/2-i-c*r;if(!Number.isFinite(S)||!Number.isFinite(Q))throw new Error("FanoutSolver: non-finite via channel bounds");Q<S-l||m.push({start:s(S),length:Math.max(0,Q-S),active:n.has(E.connectionIndex)||n.has(B.connectionIndex)})}}const _=m.filter(y=>y.length<r-l).flatMap(y=>[y.start,s(y.start+y.length)]).sort((y,x)=>y-x).filter((y,x,E)=>x===0||y-E[x-1]>l);if(_.length===0)return 0;const f=y=>{let x=0,E=0;for(const B of m)(B.length>=r-l||s(y-B.start)<=B.length+l)&&(E++,B.active&&x++);return[x,E]};let I={active:-1,total:-1,width:0,phase:0};const C=(y,x)=>{y=a(y);const[E,B]=f(y);(E>I.active||E===I.active&&(B>I.total||B===I.total&&(x>I.width+l||Math.abs(x-I.width)<=l&&(Math.abs(y)<Math.abs(I.phase)-l||Math.abs(Math.abs(y)-Math.abs(I.phase))<=l&&y<I.phase))))&&(I={active:E,total:B,width:x,phase:y})};for(let y=0;y<_.length;y++){const x=_[y],E=_[y+1]??_[0]+r;E-x>l&&C((x+E)/2,E-x)}if(I.total===0)for(const y of _)C(y,0);return I.phase};return{x:u("x"),y:u("y")}}var mSo=class{constructor(t,e,n,o){this.planeSize=t,this.neighborOffset=n,this.neighborIds=o,this.layerStride=o.length+t,this.classes=new Uint32Array(this.layerStride*e)}planeSize;neighborOffset;neighborIds;classes;layerStride;values=[void 0,!0,!1];ownerIds=new Map;overflow=new Map;getSlot(t,e){const n=t<this.planeSize?t:t%this.planeSize,o=t<this.planeSize?0:(t-n)/this.planeSize*this.layerStride;if(e===n)return o+this.neighborIds.length+n;const i=this.neighborOffset[n+1];for(let r=this.neighborOffset[n];r<i;r++)if(this.neighborIds[r]===e)return o+r;return-1}get(t,e,n=!1){if(n)return;const o=this.getSlot(t,e);return o<0?this.overflow.get(t*this.planeSize+e):this.values[this.classes[o]]}set(t,e,n,o=!1){if(o)return;const i=this.getSlot(t,e);if(i<0){this.overflow.set(t*this.planeSize+e,n);return}let r=n===!0?1:n===!1?2:this.ownerIds.get(n);r===void 0&&(r=this.values.length,this.values.push(n),this.ownerIds.set(n,r)),this.classes[i]=r}};function _So(t,e,n,o){const i=t.planeSize*t.layers;t.visitedStamp=new Uint32Array(i*3),t.bestGStamp=new Uint32Array(i*3),t.bestGValue=new Float64Array(i*3);let r=new Uint8Array(1024),s=new Int32Array(1024),a=0,A=-1,c=-1,l=-1,u=0;const g=()=>e[t.activeConnId]===!0,h=(_,f,I,C,y)=>_===0&&f===n&&C!==n?1:_===1&&f!==n&&f===C&&I!==y?2:_,d=t.nodePool.push.bind(t.nodePool);t.nodePool.push=(_,f,I,C,y,x)=>{const E=d(_,f,I,C,y,x);if(E>=r.length){const B=Math.max(E+1,r.length*2),S=new Uint8Array(B),Q=new Int32Array(B);S.set(r),Q.set(s),r=S,s=Q}if(C<0||!g()){r[E]=0,s[E]=-1,u=0;const B=t.activeConnSeg;g()&&B&&B.startCellId===B.endCellId&&B.startZ===B.endZ&&(t.failed=!0)}else{const B=r[C],S=t.nodePool.z[C];r[E]=h(B,S,t.nodePool.cellId[C],_,f),s[E]=B===0&&S===n&&_!==n?f:s[C]}return E};const p=t.heap.pop.bind(t.heap);t.heap.pop=()=>{const _=p();return a=r[_],u=a,A=s[_],c=t.nodePool.cellId[_],l=t.nodePool.z[_],_};const m=t.getSearchStateIdx.bind(t);return t.getSearchStateIdx=(_,f)=>m(_,f)+(g()?u*i:0),{beforeFirstVia:()=>!g()||a===0,prepareMove(_,f,I){if(u=g()?h(a,l,c,_,f):0,!g())return!0;if(I&&_===n&&(u!==2||A<0||Math.hypot(t.cellCenterX[f]-t.cellCenterX[A],t.cellCenterY[f]-t.cellCenterY[A])<o-1e-9))return!1;const C=t.activeConnSeg;return _!==C.endZ||f!==C.endCellId||u===2}}}function Jy(t,e){return t.targetLayerByBusId?.get(e)??t.targetLayer}var fSo=class extends fC{constructor(t){super(),this.options=t,this.activeSubSolver=t.router,this.MAX_ITERATIONS=Math.ceil(t.router.MAX_ITERATIONS/5e3)+1}options;partialCandidates=[];partialSignatures=new Set;_step(){const{router:t}=this.options;for(let e=0;e<5e3&&!t.solved&&!t.failed;e++)t.step();this.collectPartialCandidate(),this.stats={iterations:t.iterations,routedConnectionCount:t.getSolvedRouteCount(),connectionCount:this.options.connectionCount},(t.solved||t.failed)&&(this.activeSubSolver=null,this.solved=!0)}collectPartialCandidate(){const{router:t,connectionCount:e,sourceOrigin:n,maximumPartialCandidates:o}=this.options;if(o===0||e<(n?2:3)||t.getSolvedRouteCount()!==e-1)return;const i=t.getOutput(),r=i.map(s=>{const a=s.route[Math.floor(s.route.length/2)];return`${s.connectionName}:${s.route.length}:${a.x},${a.y}`}).sort().join(";");this.partialSignatures.has(r)||n&&this.partialCandidates.length>=o||(this.partialSignatures.add(r),this.partialCandidates.push(i),this.partialCandidates.length>o&&this.partialCandidates.shift())}computeProgress(){return this.options.router.iterations/this.options.router.MAX_ITERATIONS}getConstructorParams(){return[this.options]}visualize(){return this.activeSubSolver?.visualize()??this.options.router.visualize()}},ISo=class d4n{constructor(e,n){this.cellSize=e,this.margin=n}cellSize;margin;buckets=new Map;add(e){let n,o,i,r;if(e.kind==="segment"){const s=e.segment,a=this.margin+s.width/2;n=Math.min(s.start.x,s.end.x)-a,o=Math.max(s.start.x,s.end.x)+a,i=Math.min(s.start.y,s.end.y)-a,r=Math.max(s.start.y,s.end.y)+a}else if(e.kind==="via"){const s=this.margin+e.diameter/2;n=e.center.x-s,o=e.center.x+s,i=e.center.y-s,r=e.center.y+s}else{const s=e.obstacle,a=Math.hypot(s.width,s.height)/2+this.margin;n=s.center.x-a,o=s.center.x+a,i=s.center.y-a,r=s.center.y+a}for(let s=this.cell(n);s<=this.cell(o);s++)for(let a=this.cell(i);a<=this.cell(r);a++){const A=`${s},${a}`,c=this.buckets.get(A)??new Set;c.add(e),this.buckets.set(A,c)}}nearby(e,n=e){const o=new Set;for(let i=this.cell(Math.min(e.x,n.x));i<=this.cell(Math.max(e.x,n.x));i++)for(let r=this.cell(Math.min(e.y,n.y));r<=this.cell(Math.max(e.y,n.y));r++)for(const s of this.buckets.get(`${i},${r}`)??[])o.add(s);return[...o]}clone(){const e=new d4n(this.cellSize,this.margin);for(const[n,o]of this.buckets)e.buckets.set(n,new Set(o));return e}cell(e){return Math.floor(e/this.cellSize)}};function sue(t){const e=[];for(const n of t){const o=e.at(-2),i=e.at(-1);if(o&&i&&o.z===i.z&&i.z===n.z){const r=i.x-o.x,s=i.y-o.y,a=n.x-i.x,A=n.y-i.y;Math.abs(r*A-s*a)<1e-10&&r*a+s*A>=0&&e.pop()}e.push(n)}return e}function aue(t,e,n){const o=new Map(t.buses.flatMap(s=>s.connections.map(a=>[a.connection.name,{bus:s,connection:a}]))),i=new Map(t.terminals.map(s=>[s.connection.connection.name,s])),r=[];for(const s of e){const a=o.get(s.connectionName),A=i.get(s.connectionName);if(!a||!A)return null;const{bus:c,connection:l}=a,u=sue(s.route),g=n.get(l.connectionIndex);if(!u.length||tn(u[0],A.viaPoint)>1e-7||tn(u.at(-1),A.exitPoint)>1e-7||t.startLayerByBusId!==void 0&&t.layerNames[u[0].z]!==t.startLayerByBusId.get(c.busId)||t.layerNames[u.at(-1).z]!==Jy(t,c.busId)||u.some(f=>!(c.allowedLayers??t.layerNames).includes(t.layerNames[f.z])))return null;const h=i4({...t,bus:c,terminal:A,targetLayer:t.layerNames[u[0].z],targetLayerPoints:[A.viaPoint,A.exitPoint],sourceEscapePoints:g,allowBlindAndBuriedVias:!1}),d=h.trace.route.findIndex(f=>f.route_type==="via");if(d<0)return null;const p=h.trace.route.slice(0,d+2),m=g.slice(1).map((f,I)=>({start:g[I],end:f,width:t.traceWidth,layer:l.sourceLayer})),_=[];for(let f=1;f<u.length;f++){const I=u[f],C=u[f-1],y=t.layerNames[C.z],x=t.layerNames[I.z];if(y!==x){if(tn(C,I)>1e-7)return null;_.push({center:{x:I.x,y:I.y},diameter:t.viaDiameter,holeDiameter:t.viaHoleDiameter,fromLayer:y,toLayer:x,spanLayers:[...t.layerNames]}),p.push({route_type:"via",x:I.x,y:I.y,from_layer:y,to_layer:x,via_diameter:t.viaDiameter,via_hole_diameter:t.viaHoleDiameter})}else tn(C,I)>1e-9&&m.push({start:{x:C.x,y:C.y},end:{x:I.x,y:I.y},width:t.traceWidth,layer:x});p.push({route_type:"wire",x:I.x,y:I.y,layer:x,width:t.traceWidth})}r.push({...h,targetLayer:Jy(t,c.busId),trace:{...h.trace,route:p},segments:m,additionalVias:_,length:m.reduce((f,I)=>f+tn(I.start,I.end),0)})}return r}function AE(t){return HPe(t,new WeakMap)}function*HPe(t,e){const{buses:n,allBuses:o,targetLayer:i,layerNames:r,traceWidth:s,clearance:a,viaDiameter:A,srj:c}=t,l=t.maximumIterations??3e7,u=t.heuristicWeight??1.5;if(!Number.isFinite(u)||u<=0)throw new Error("heuristicWeight must be finite and positive");if(!Number.isSafeInteger(l)||l<1)throw new Error("maximumIterations must be a positive safe integer");const g=t.maximumLocalRepairAttempts??3,h=t.maximumSourceOriginRepairAttempts??0;if(!Number.isSafeInteger(g)||g<0)throw new Error("maximumLocalRepairAttempts must be a non-negative safe integer");if(!Number.isSafeInteger(h)||h<0)throw new Error("maximumSourceOriginRepairAttempts must be a non-negative safe integer");const d=t.ripCost??8;if(!Number.isFinite(d)||d<=0)throw new Error("ripCost must be finite and positive");if(t.maximumRipEvents!==void 0&&(!Number.isSafeInteger(t.maximumRipEvents)||t.maximumRipEvents<1))throw new Error("maximumRipEvents must be a positive safe integer");const p=t.traceMarginExtra??s/2;if(!Number.isFinite(p)||p<0)throw new Error("traceMarginExtra must be finite and non-negative");const m=t.routeFromSourcePads??!1;if(t.terminalApproachLength!==void 0&&(!Number.isFinite(t.terminalApproachLength)||t.terminalApproachLength<=0))throw new Error("terminalApproachLength must be finite and positive");const _=m||t.startLayerByBusId!==void 0||t.terminalApproachLength!==void 0,f=t.sourceLayerTravelCost??1;if(!Number.isFinite(f)||f<1)throw new Error("sourceLayerTravelCost must be finite and at least one");const I=[...new Set(n.map(mt=>Jy(t,mt.busId)))],C=t.startLayerByBusId?n.map(mt=>t.startLayerByBusId.get(mt.busId)):[],y=m?[...new Set([i,"top",...t.transitLayers??[],...I,...C])]:[...new Set([i,...t.transitLayers??[],...I,...C])],x=r.indexOf(i),E=m&&t.allowSourceOriginTopFinal===!0&&I.includes("top"),B=E?n.filter(mt=>Jy(t,mt.busId)==="top"):[],S=new Map(B.map(mt=>[mt.busId,o.find(st=>st.busId===mt.busId)])),Q=new Set((E?o:[]).flatMap(mt=>mt.termination.type==="plane"?[mt.termination.layer]:[]));if(B.some(mt=>{const st=S.get(mt.busId);if(!st||mt.connections.length!==st.connections.length||mt.connections.some(Xe=>!st.connections.some(Ze=>Ze.connectionIndex===Xe.connectionIndex&&Ze.connection.name===Xe.connection.name&&Ze.sourceObstacle===Xe.sourceObstacle)))return!0;const xt=(st.routableEscapeLayers??st.allowedLayers??r).filter(Xe=>(st.allowedLayers??r).includes(Xe));return!xt.includes("top")||!y.some(Xe=>Xe!=="top"&&!Q.has(Xe)&&xt.includes(Xe)&&(mt.routableEscapeLayers??mt.allowedLayers??r).includes(Xe)&&(mt.allowedLayers??r).includes(Xe))})||n.length===0||x<0||I.some(mt=>!r.includes(mt))||t.targetLayerByBusId&&n.some(mt=>!t.targetLayerByBusId.has(mt.busId))||t.startLayerByBusId&&(m||n.some(mt=>!t.startLayerByBusId.has(mt.busId)))||y.some(mt=>!r.includes(mt)))return null;const w=n.flatMap(mt=>mt.connections),M=new Set(w.map(mt=>mt.connectionIndex));if(m&&w.some(mt=>mt.sourceLayer!=="top")||M.size!==w.length||t.terminals.length!==w.length||new Set(t.terminals.map(mt=>mt.connection.connectionIndex)).size!==M.size||t.terminals.some(mt=>!M.has(mt.connection.connectionIndex))||n.some(mt=>mt.termination.type!=="boundary"||!(mt.allowedLayers??r).includes(Jy(t,mt.busId))||!(mt.routableEscapeLayers??mt.allowedLayers??r).includes(Jy(t,mt.busId)))||(t.startLayerByBusId?n.some(mt=>{const st=t.startLayerByBusId.get(mt.busId);return!(mt.allowedLayers??r).includes(st)||!(mt.routableEscapeLayers??mt.allowedLayers??r).includes(st)||mt.connections.some(xt=>xt.sourceLayer===st)}):!E&&o.some(mt=>mt.connections.some(st=>I.includes(st.sourceLayer)))))return null;const k=n[0].sharedBoundary;if(n.some(mt=>Object.keys(k).some(st=>mt.sharedBoundary[st]!==k[st])))return null;const R=new Map,F=new Map,O=new ISo(Math.max(.5,A*2),Math.max(s,A)/2+a+1e-7),U=new Map(w.map(mt=>[mt.connection.name,mt])),Y=new Map(w.map(mt=>[mt.sourceObstacle,mt])),W=m?new Map(w.map(mt=>[mt.sourceObstacle,{connectionName:mt.connection.name,sourcePoint:U.get(mt.connection.name).sourcePoint}])):void 0;for(const mt of c.obstacles)O.add({kind:"obstacle",obstacle:mt});for(const mt of o)for(const st of mt.connections){F.set(st.connection.name,mt);const xt=t.fixedViaPointsByConnectionIndex.get(st.connectionIndex);if(!xt)return null;const Xe=t.sourceEscapePaths?.get(st.connectionIndex)??[st.sourcePoint,xt];if(Xe.length<2||tn(Xe[0],st.sourcePoint)>1e-7||tn(Xe.at(-1),xt)>1e-7)return null;if(R.set(st.connectionIndex,Xe),!(m&&M.has(st.connectionIndex))){O.add({kind:"via",connectionName:st.connection.name,center:xt,diameter:A,layers:r});for(let Ze=1;Ze<Xe.length;Ze++)O.add({kind:"segment",connectionName:st.connection.name,segment:{start:Xe[Ze-1],end:Xe[Ze],width:s,layer:st.sourceLayer}})}}for(const mt of t.terminals)if(tn(mt.viaPoint,t.fixedViaPointsByConnectionIndex.get(mt.connection.connectionIndex))>1e-7)return null;for(const mt of t.acceptedPlans){for(const st of[...mt.segments,...mt.planeEndpointSegments??[]])O.add({kind:"segment",connectionName:mt.connectionName,segment:st});for(const st of[mt.via,...mt.additionalVias??[],mt.planeEndpointVia])st&&O.add({kind:"via",connectionName:mt.connectionName,...st,layers:st.spanLayers})}for(const mt of Z7(c,!1)){for(const st of mt.segments)O.add({kind:"segment",connectionName:mt.connectionName,segment:st});for(const st of mt.vias)O.add({kind:"via",connectionName:mt.connectionName,...st,layers:st.spanLayers})}const te=new Map;if(t.terminalApproachLength!==void 0)for(const mt of t.terminals){const st=mt.connection.connection.name,xt=F.get(st),Xe=aSo({connectionName:st,edge:xt.exitEdge??Xj(xt.direction),layer:Jy(t,xt.busId),exit:mt.exitPoint,bounds:k,approachLength:t.terminalApproachLength});te.set(st,Xe),O.add({kind:"segment",connectionName:st,segment:{start:Xe.goal,end:Xe.exit,width:s,layer:Xe.layer}})}const j={capacityMeshNodeId:"reserved-via-buses",center:{x:(k.minX+k.maxX)/2,y:(k.minY+k.maxY)/2},width:k.maxX-k.minX,height:k.maxY-k.minY,availableZ:y.map(mt=>r.indexOf(mt)),portPoints:t.terminals.flatMap(mt=>[m?mt.connection.sourcePoint:mt.viaPoint,te.get(mt.connection.connection.name)?.goal??mt.exitPoint].map((st,xt)=>({...st,z:m&&xt===0?r.indexOf(mt.connection.sourceLayer):xt===0&&t.startLayerByBusId?r.indexOf(t.startLayerByBusId.get(F.get(mt.connection.connection.name).busId)):r.indexOf(Jy(t,F.get(mt.connection.connection.name).busId)),connectionName:mt.connection.connection.name,rootConnectionName:mt.connection.connection.name})))};if(t.tightViaChannels){const mt=LPe({vias:[...t.fixedViaPointsByConnectionIndex].filter(([st])=>!m||!t.sourceOriginPhysicalGridPhase||!M.has(st)).map(([st,xt])=>({connectionIndex:st,center:xt,diameter:A})),activeConnectionIndices:M,traceWidth:s,clearance:a,gridStep:s});for(const st of["x","y"]){const xt=(st==="x"?k.minX:k.minY)+s/2;j.center[st]+=mt[st]-(xt+Math.round((mt[st]-xt)/s)*s)}}const oe=new Vz({nodeWithPortPoints:j,traceWidth:s,viaDiameter:A}).generateSolver({HIGH_DENSITY_A03:!0});if(typeof oe.computeMoveCostAndRips!="function"||typeof oe.markTraceFootprint!="function"||typeof oe.addSharedOccupant!="function"||typeof oe.getSolvedRouteCount!="function"||te.size>0&&(typeof oe.pointToCell!="function"||typeof oe.finalizeRoute!="function"||typeof oe.ripTrace!="function"))return null;const ie=oe.constructor,ne=new ie({nodeWithPortPoints:j,highResolutionCellSize:s,lowResolutionCellSize:s,traceThickness:s,traceMargin:a+p,viaDiameter:A,maxCellCount:16e4*y.length,effort:20,hyperParameters:{shuffleSeed:t.shuffleSeed??1,greedyMultiplier:u,ripCost:d}}),le=ne._setup.bind(ne),ge=ne.computeMoveCostAndRips.bind(ne);let _e=-1,ue=-1,fe=[],pe=[],ye,Me=[],ve=new Set,he;const Qe=new Map,Pe=new WeakMap,we=new Map;let Te;const Re=mt=>({x:ne.cellCenterX[mt],y:ne.cellCenterY[mt]}),Ee=mt=>mt.x>=k.minX-1e-9&&mt.x<=k.maxX+1e-9&&mt.y>=k.minY-1e-9&&mt.y<=k.maxY+1e-9,ke=mt=>{const st=we.get(mt);if(st!==void 0)return st;const xt=Re(mt),Xe=O.nearby(xt).every(Ze=>Ze.kind==="via"?tn(xt,Ze.center)>=(A+Ze.diameter)/2+a-1e-9:Ze.kind==="segment"?Cr(xt,Ze.segment.start,Ze.segment.end)>=(A+Ze.segment.width)/2+a-1e-9:Tl({start:xt,end:xt},Ze.obstacle)>=A/2+a-1e-9);return we.set(mt,Xe),Xe};ne._setup=()=>{if(le(),ne.failed)return;if(t.includeDiagonalNeighbors&&Object.assign(ne,sSo(ne)),te.size>0){if(typeof ne.ripChain?.contains!="function"||typeof ne.ripChain?.append!="function"||!Number.isFinite(ne.hyperParameters.ripTracePenalty)||!Number.isFinite(ne.hyperParameters.ripViaPenalty)){ne.failed=!0;return}for(const Wt of te.values())if(!Le(Wt.goal,Wt.exit,Wt.layer,Wt.connectionName)){ne.failed=!0;return}const st=[...te.values()].map(Wt=>({connector:Wt,cellId:ne.pointToCell(Wt.goal).cellId})),xt=uSo({grid:ne,terminals:st,margin:Math.max(s,A)+a+1e-7,segmentIsClear:(Wt,Xt,Jt)=>Ee(Wt)&&Ee(Xt)&&Le(Wt,Xt,Jt.layer,Jt.connectionName)});ne.neighborOffset=xt.neighborOffset,ne.neighborIds=xt.neighborIds,ne.neighborCosts=xt.neighborCosts,ve=xt.extendedEdges;const Xe=new Map(st.map(({connector:Wt,cellId:Xt})=>[Wt.connectionName,Xt])),Ze=ne.getOutput.bind(ne);ne.getOutput=()=>Ze().map(Wt=>{const Xt=gSo(Wt,te.get(Wt.connectionName),Re(Xe.get(Wt.connectionName))),Jt=[];if(!m){const ht=U.get(Wt.connectionName),Kt=R.get(ht.connectionIndex);for(let rn=1;rn<Kt.length;rn++)Jt.push({start:Kt[rn-1],end:Kt[rn],width:s,layer:ht.sourceLayer})}const yn=Wt.route.at(-2).z!==Wt.route.at(-1).z,An=Wt.route.length-(yn?1:2);let kn=-1;for(let ht=1;ht<Xt.route.length;ht++){const Kt=Xt.route[ht-1],rn=Xt.route[ht];Kt.z===rn.z&&(ht-1===An&&(kn=Jt.length),Jt.push({start:Kt,end:rn,width:s,layer:r[Kt.z]}))}const $n={rawSegments:Jt,firstEntrySegmentIndex:kn};return Qe.set(Wt.connectionName,$n),Pe.set(Xt,$n),Xt}),he=new dSo({regions:xt.regions,traceWidth:s,clearance:a,viaDiameter:A,getRoutes:()=>ne.getOutput()});const dt=ne.finalizeRoute.bind(ne),Ut=ne.ripTrace.bind(ne);ne.finalizeRoute=Wt=>{dt(Wt),he.invalidate()},ne.ripTrace=Wt=>{Ut(Wt),he.invalidate()}}hSo(ne),Te=new mSo(ne.planeSize,y.length,ne.neighborOffset,ne.neighborIds),fe=Array.from({length:y.length},(st,xt)=>r[ne.layerToZ.get(xt)]),pe=ne.connIdToName.map(st=>{const xt=F.get(st),Xe=xt?(xt.routableEscapeLayers??xt.allowedLayers??r).filter(Ut=>(xt.allowedLayers??r).includes(Ut)):[],Ze=xt&&S.get(xt.busId),dt=Ze?(Ze.routableEscapeLayers??Ze.allowedLayers??r).filter(Ut=>(Ze.allowedLayers??r).includes(Ut)&&!Q.has(Ut)):void 0;return fe.map(Ut=>(Xe.includes(Ut)||m&&Ut==="top")&&(!dt||dt.includes(Ut)))}),ne.MAX_ITERATIONS=l,t.maximumRipEvents!==void 0&&(ne.MAX_RIPS=t.maximumRipEvents),ne.gridToBoundsTransform={a:1,b:0,c:0,d:0,e:1,f:0};const mt=ne.heap.pop.bind(ne.heap);if(ne.heap.pop=()=>{const st=mt();return _e=ne.nodePool.cellId[st],ue=ne.nodePool.z[st],st},E){const st=ne.layers*ne.planeSize,xt=fe.indexOf("top");if(typeof ne.getSearchStateIdx!="function"||typeof ne.nodePool.push!="function"||!(ne.visitedStamp instanceof Uint32Array)||!(ne.bestGStamp instanceof Uint32Array)||!(ne.bestGValue instanceof Float64Array)||ne.visitedStamp.length!==st||ne.bestGStamp.length!==st||ne.bestGValue.length!==st||ne.getSearchStateIdx(0,0)!==0||ne.getSearchStateIdx(st-1,1)!==st-1||xt<0){ne.failed=!0;return}Me=ne.connIdToName.map(Xe=>{const Ze=F.get(Xe);return!!Ze&&Jy(t,Ze.busId)==="top"}),ye=_So(ne,Me,xt,A+a)}},ne.markTraceFootprint=(mt,st,xt,Xe)=>{const Ze=Re(xt),dt=ne.traceKeepoutRadius;ne.forEachCellNearCircle(Ze.x,Ze.y,dt,Ut=>{const Wt=t.tightViaChannels?ne.cellCenterX[Ut]-Ze.x:Math.max(ne.cellMinX[Ut]-Ze.x,0,Ze.x-ne.cellMaxX[Ut]),Xt=t.tightViaChannels?ne.cellCenterY[Ut]-Ze.y:Math.max(ne.cellMinY[Ut]-Ze.y,0,Ze.y-ne.cellMaxY[Ut]),Jt=dt-(t.tightViaChannels?1e-9:0);if(t.tightViaChannels?Wt*Wt+Xt*Xt>=Jt*Jt:Wt*Wt+Xt*Xt>Jt*Jt)return;const yn=st*ne.planeSize+Ut;if(Ut!==xt&&ne.shouldSkipFixedPortHalo(yn,mt))return;const An=ne.usedCellsFlat[yn];An!==-1&&An!==mt?ne.addSharedOccupant(yn,mt):ne.usedCellsFlat[yn]=mt,Xe.push(yn)})};const Ce=(mt,st,xt,Xe)=>Xe.kind==="obstacle"?!Xe.obstacle.layers.includes(xt)||Tl({start:mt,end:st},Xe.obstacle)>=s/2+a-1e-9:Xe.kind==="via"?!Xe.layers.includes(xt)||Cr(Xe.center,mt,st)>=(s+Xe.diameter)/2+a-1e-9:Xe.segment.layer!==xt||tu(mt,st,Xe.segment.start,Xe.segment.end)>=(s+Xe.segment.width)/2+a-1e-9,Le=(mt,st,xt,Xe,Ze=O.nearby(mt,st))=>Ze.every(dt=>dt.kind!=="obstacle"&&dt.connectionName===Xe||m&&dt.kind==="obstacle"&&xt==="top"&&Y.get(dt.obstacle)?.connection.name===Xe&&Tl({start:mt,end:mt},dt.obstacle)<s/2+a-1e-9&&tn(st,U.get(Xe).sourcePoint)>=tn(mt,U.get(Xe).sourcePoint)-1e-9||Ce(mt,st,xt,dt)),Ye=(mt,st,xt)=>{let Xe;for(const Ze of O.nearby(mt,st)){if(Ce(mt,st,xt,Ze))continue;if(Ze.kind==="obstacle"&&!m)return!1;const dt=Ze.kind==="obstacle"?rSo(mt,st,xt,s,a,Ze.obstacle,W?.get(Ze.obstacle)):Ze.connectionName;if(dt===void 0||Xe!==void 0&&Xe!==dt)return!1;Xe=dt}return Xe??!0};ne.computeMoveCostAndRips=(mt,st,xt,Xe,Ze,dt,Ut)=>{const Wt=ne.connIdToName[mt],Xt=fe[st],Jt=ne.activeConnSeg;if(ye&&!ye.prepareMove(st,xt,Xe)||!pe[mt][st]||Xe&&(m&&Xt==="top"&&!Me[mt]||!ke(xt))){ne._moveCost=-1;return}const yn=_e===Jt.startCellId&&(!_||ue===Jt.startZ)&&(!ye||ye.beforeFirstVia());let An,kn,$n;if(he){const Lt=xt===Jt.endCellId&&st===Jt.endZ;if(ve.has(`${_e}:${xt}`)&&!Lt){ne._moveCost=-1;return}const Ho=te.get(Wt);if(An=yn?Jt.startPoint:Re(_e),kn=Lt?Jt.endPoint:Re(xt),$n=Lt?rue(Xe?Re(xt):An,Ho):void 0,Lt&&(!$n||Xe&&tn(An,Re(xt))>1e-7)){ne._moveCost=-1;return}}const ht=st*ne.planeSize+_e,Kt=yn||xt===Jt.endCellId&&(!_||st===Jt.endZ);let rn=Te.get(ht,xt,Kt);if(rn===void 0){if(An??=yn?Jt.startPoint:Re(_e),kn??=xt===Jt.endCellId&&(!_||st===Jt.endZ)?Jt.endPoint:Re(xt),!Ee(An)||!Ee(kn)){ne._moveCost=-1;return}rn=Kt?$n?$n.slice(1).every((Lt,Ho)=>Le($n[Ho],Lt,Xt,Wt)):Le(An,kn,Xt,Wt):Ye(An,kn,Xt),Te.set(ht,xt,rn,Kt)}if(rn!==!0&&rn!==Wt){ne._moveCost=-1;return}if(ge(mt,st,xt,Xe,Ze,dt,Ut),he&&ne._moveCost>=0){const Lt=Xe?he.blockingViaOwners(Wt,Re(xt)):he.blockingSegmentOwners(Wt,$n??[An,kn],ne.layerToZ.get(st));if(Xe&&$n)for(const Ho of he.blockingSegmentOwners(Wt,$n,ne.layerToZ.get(st)))Lt.add(Ho);for(const Ho of Lt){const Ao=ne.connIdToName.indexOf(Ho);if(Ao<0)throw new Error("Cannot resolve dynamic terminal copper owner");ne.ripChain.contains(ne._moveRippedHead,Ao)||(ne._moveRippedHead=ne.ripChain.append(ne._moveRippedHead,Ao),ne._moveRipCount++,ne._moveCost+=d),ne._moveCost+=Xe?ne.hyperParameters.ripViaPenalty:ne.hyperParameters.ripTracePenalty}}m&&!Xe&&Xt==="top"&&ne._moveCost>=0&&(!ye||ye.beforeFirstVia())&&(ne._moveCost+=Ut*(f-1))};const tt=m?h:g;ne.setup();const At=new fSo({router:ne,connectionCount:w.length,sourceOrigin:m,maximumPartialCandidates:tt});for(yield{type:"subsolver",solver:At,iterations:ne.iterations,routedConnectionCount:ne.getSolvedRouteCount(),connectionCount:w.length};!At.solved&&!At.failed;)At.step(),yield{iterations:ne.iterations,routedConnectionCount:ne.getSolvedRouteCount(),connectionCount:w.length};const{partialCandidates:at}=At,nt=mt=>o.flatMap(st=>st.connections.filter(xt=>!mt.has(xt.connectionIndex)).map(xt=>{const Xe=t.fixedViaPointsByConnectionIndex.get(xt.connectionIndex),Ze=st.termination.type==="plane"?st.termination.layer:(st.allowedLayers??r).find(dt=>dt!==xt.sourceLayer);return i4({...t,bus:st,terminal:{connection:xt,viaPoint:Xe,exitPoint:Xe},targetLayer:Ze,targetLayerPoints:[Xe],sourceEscapePoints:R.get(xt.connectionIndex),allowBlindAndBuriedVias:!1})})),gt=(mt,st=new Set)=>{const xt=nt(new Set([...[...mt,...t.acceptedPlans].map(Xe=>Xe.connectionIndex),...st]));return(te.size===0||mt.every(Xe=>{const Ze=te.get(Xe.connectionName);if(!Ze)return!0;const dt=Xe.segments.at(-1);return!!dt&&dt.layer===Ze.layer&&tn(dt.end,Ze.exit)<1e-7&&Cr(Ze.goal,dt.start,dt.end)<1e-7&&FPe({plan:Xe,splice:e.get(Xe)??Qe.get(Xe.connectionName)??{rawSegments:[],firstEntrySegmentIndex:-1},maximumJoinLength:s/4,clearance:a})}))&&Wh({plans:[...mt],srj:c,sharedBoundary:k,clearance:a,allowBlindAndBuriedVias:!1,allowSameNetMerges:!1})&&qu({inputSrj:c,routedSrj:{...c,traces:[...c.traces??[],...[...mt,...t.acceptedPlans,...xt].flatMap(Xe=>[Xe.trace,...Xe.planeEndpointTrace?[Xe.planeEndpointTrace]:[]])]},clearance:a,allowBlindAndBuriedVias:!1}).valid},bt=(mt,st)=>{const xt=mt.findIndex((Ut,Wt)=>Wt>0&&Ut.z!==mt[Wt-1].z);if(xt<1||mt.slice(0,xt).some(Ut=>r[Ut.z]!=="top")||tn(mt[xt-1],mt[xt])>1e-7)return!1;const Xe=F.get(st);if(!S.has(Xe.busId))return!mt.slice(xt).some(Ut=>r[Ut.z]==="top");let Ze=!1,dt=!1;for(let Ut=xt+1;Ut<mt.length;Ut++){const Wt=mt[Ut-1],Xt=mt[Ut];if(Wt.z===Xt.z&&r[Wt.z]!=="top"&&tn(Wt,Xt)>1e-7&&(Ze=!0),Wt.z!==Xt.z&&r[Xt.z]==="top"){if(!Ze||tn(Wt,Xt)>1e-7||tn(mt[xt],Xt)<A+a-1e-9)return!1;dt=!0}}return dt&&ENt({points:mt,topZ:r.indexOf("top"),traceWidth:s,viaDiameter:A,clearance:a})},Ct=mt=>{if(Qe.clear(),te.size===0)return!0;for(const st of mt){const xt=Pe.get(st);if(!xt)return!1;Qe.set(st.connectionName,xt)}return!0},Dt=(mt,st=new Set)=>{if(!mt||!gt(mt,st))return null;for(const xt of mt){const Xe=Qe.get(xt.connectionName);Xe&&!e.has(xt)&&e.set(xt,Xe)}return mt},kt=mt=>{if(te.size===0)return mt;const st=lSo({plans:mt,splices:Qe,connectors:te,clearance:a,segmentIsClear:(xt,Xe)=>Ee(xt.start)&&Ee(xt.end)&&Le(xt.start,xt.end,xt.layer,Xe)});if(!st)return null;for(const[xt,Xe]of st.splices)Qe.set(xt,Xe);return st.plans},it=(mt,st=new Set)=>{if(!Ct(mt))return null;const xt=new Map(R),Xe=[],Ze=[];for(const ht of mt){const Kt=t.terminals.find(Ho=>Ho.connection.connection.name===ht.connectionName),rn=ht.route.findIndex((Ho,Ao)=>Ao>0&&Ho.z!==ht.route[Ao-1].z);if(!bt(ht.route,ht.connectionName)||r[ht.route.at(-1).z]!==Jy(t,F.get(ht.connectionName).busId)||tn(ht.route[rn-1],ht.route[rn])>1e-7)return null;const Lt=ht.route[rn];xt.set(Kt.connection.connectionIndex,sue(ht.route.slice(0,rn)).map(({x:Ho,y:Ao})=>({x:Ho,y:Ao}))),Xe.push({...Kt,viaPoint:{x:Lt.x,y:Lt.y}}),Ze.push({...ht,route:ht.route.slice(rn),vias:[]})}const dt=aue({...t,terminals:Xe},Ze,xt);if(!dt)return null;const Ut=kt(dt);if(!Ut)return null;const Wt=MPe({...t,inputSrj:c,plans:Ut,preparedBuses:n,reservedPlans:[...t.acceptedPlans,...nt(M)],allowBlindAndBuriedVias:!1,allowSameNetMerges:!1});if(!Wt)return null;const Xt=Wt.map(ht=>({connectionName:ht.connectionName,route:ht.trace.route.flatMap(Kt=>Kt.route_type==="wire"?[{x:Kt.x,y:Kt.y,z:r.indexOf(Kt.layer)}]:[]),vias:[ht.via.center]})),Jt=O.clone(),yn=ht=>{for(let Kt=1;Kt<ht.route.length;Kt++){const rn=ht.route[Kt-1],Lt=ht.route[Kt];rn.z===Lt.z?Jt.add({kind:"segment",connectionName:ht.connectionName,segment:{start:rn,end:Lt,width:s,layer:r[rn.z]}}):Jt.add({kind:"via",connectionName:ht.connectionName,center:rn,diameter:A,layers:r})}};Xt.forEach(yn);const An=[],kn=[];for(const ht of Xt){const Kt=t.terminals.find(Ao=>Ao.connection.connection.name===ht.connectionName),rn=eR({points:sue(ht.route),chamfer:s/4,segmentIsClear:(Ao,qe)=>{for(const vt of[Ao,qe])if(!Ee(vt)||(Math.abs(vt.x-k.minX)<1e-7||Math.abs(vt.x-k.maxX)<1e-7||Math.abs(vt.y-k.minY)<1e-7||Math.abs(vt.y-k.maxY)<1e-7)&&tn(vt,Kt.exitPoint)>1e-7)return!1;return Le(Ao,qe,r[Ao.z],ht.connectionName,Jt.nearby(Ao,qe))}});if(!rn)return null;const Lt=rn.findIndex((Ao,qe)=>qe>0&&Ao.z!==rn[qe-1].z);if(!bt(rn,ht.connectionName)||r[rn.at(-1).z]!==Jy(t,F.get(ht.connectionName).busId))return null;const Ho=rn[Lt];R.set(Kt.connection.connectionIndex,rn.slice(0,Lt).map(({x:Ao,y:qe})=>({x:Ao,y:qe}))),kn.push({...Kt,viaPoint:{x:Ho.x,y:Ho.y}}),An.push({...ht,route:rn.slice(Lt),vias:[]}),yn({...ht,route:rn})}const $n=aue({...t,terminals:kn},An,R);return Dt($n,st)},Yt=mt=>{if(!Ct(mt))return null;let st=mt;const xt=O.clone(),Xe=new Set([...st.map(yn=>t.terminals.find(An=>An.connection.connection.name===yn.connectionName).connection.connectionIndex),...t.acceptedPlans.map(yn=>yn.connectionIndex)]),Ze=nt(Xe),dt=aue(t,st,R);if(!dt)return null;const Ut=kt(dt);if(!Ut)return null;const Wt=MPe({...t,inputSrj:c,plans:Ut,preparedBuses:n,reservedPlans:[...t.acceptedPlans,...Ze],allowBlindAndBuriedVias:!1,allowSameNetMerges:!1});if(!Wt)return null;st=Wt.map(yn=>{const An=yn.trace.route.findIndex(kn=>kn.route_type==="via");return{connectionName:yn.connectionName,route:yn.trace.route.slice(An+1).flatMap(kn=>kn.route_type==="wire"?[{x:kn.x,y:kn.y,z:r.indexOf(kn.layer)}]:[]),vias:(yn.additionalVias??[]).map(kn=>kn.center)}});const Xt=yn=>{for(let An=1;An<yn.route.length;An++){const kn=yn.route[An-1],$n=yn.route[An];kn.z===$n.z&&xt.add({kind:"segment",connectionName:yn.connectionName,segment:{start:kn,end:$n,width:s,layer:r[kn.z]}})}for(const An of yn.vias)xt.add({kind:"via",connectionName:yn.connectionName,center:An,diameter:A,layers:r})};for(const yn of st)Xt(yn);for(const yn of st){const An=t.terminals.find($n=>$n.connection.connection.name===yn.connectionName),kn=eR({points:sue(yn.route),chamfer:s/4,segmentIsClear:($n,ht)=>{for(const Kt of[$n,ht])if(!Ee(Kt)||(Math.abs(Kt.x-k.minX)<1e-7||Math.abs(Kt.x-k.maxX)<1e-7||Math.abs(Kt.y-k.minY)<1e-7||Math.abs(Kt.y-k.maxY)<1e-7)&&tn(Kt,An.exitPoint)>1e-7)return!1;return Le($n,ht,r[$n.z],yn.connectionName,xt.nearby($n,ht))}});if(!kn)return null;yn.route=kn,Xt(yn)}const Jt=aue(t,st,R);return Dt(Jt)};if(ne.solved&&!ne.failed){const mt=ne.getOutput();return mt.length!==w.length||new Set(mt.map(st=>st.connectionName)).size!==w.length?null:m?it(mt):Yt(mt)}if(m&&h>0){for(const mt of at){const st=new Set(mt.map(Xt=>Xt.connectionName)),xt=t.terminals.filter(Xt=>!st.has(Xt.connection.connection.name));if(xt.length!==1)continue;const Xe=xt[0].connection.connectionIndex,Ze=new Map(R),dt=it(mt,new Set([Xe]));R.clear();for(const[Xt,Jt]of Ze)R.set(Xt,Jt);if(!dt)continue;const Ut=CSo(t,dt,e);let Wt=Ut.next();for(;!Wt.done;)yield{iterations:ne.iterations+Wt.value.iterations,routedConnectionCount:Wt.value.routedConnectionCount,connectionCount:w.length},Wt=Ut.next();if(Wt.value&>(Wt.value))return Wt.value}return null}if(m||g===0||at.length===0)return null;const pn=nt(new Set(t.acceptedPlans.map(mt=>mt.connectionIndex))),be=new Map(pn.map(mt=>[mt.connectionIndex,mt])),et=pn.flatMap(mt=>mt.via?[{connectionName:mt.connectionName,via:mt.via}]:[]),It=LPe({...t,gridStep:s,vias:o.flatMap(mt=>mt.connections.map(st=>({connectionIndex:st.connectionIndex,center:t.fixedViaPointsByConnectionIndex.get(st.connectionIndex),diameter:A}))),activeConnectionIndices:M});let Bt=0;for(const mt of at.toReversed()){const st=Yt(mt);if(!st)continue;const xt=new Set(st.map(dt=>dt.connectionIndex)),Xe=t.terminals.find(dt=>!xt.has(dt.connection.connectionIndex)),Ze=st.toSorted((dt,Ut)=>tn(dt.exitPoint,Xe.exitPoint)-tn(Ut.exitPoint,Xe.exitPoint));for(const dt of Ze.slice(0,16)){const Ut=Xe.connection.connectionIndex,Wt=st.filter($n=>$n!==dt),Xt=[...t.acceptedPlans,...Wt,...pn.filter($n=>!xt.has($n.connectionIndex)&&$n.connectionIndex!==Ut),be.get(dt.connectionIndex)],Jt=F.get(Xe.connection.connection.name),yn=BC({...t,bus:{...Jt,exitEdge:Jt.exitEdge??Xj(Jt.direction),connections:[Xe.connection]},terminals:[Xe],targetLayer:Jy(t,Jt.busId),acceptedPlans:Xt,reservedVias:et.filter($n=>$n.connectionName!==Xe.connection.connection.name),sourceEscapePaths:R,gridStep:s,gridOrigin:It,gridStepDivisor:2,maximumRouteOrderAttempts:1,maximumSearchStates:24e4,heuristicWeight:1,alignGridToPads:!0},1,!1);let An=yn.next();for(;!An.done;)yield{iterations:ne.iterations+An.value.expandedStateCount,routedConnectionCount:st.length,connectionCount:w.length},An=yn.next();if(!An.value[0]?.length)continue;const kn=Wt.toSorted(($n,ht)=>{const Kt=rn=>Math.min(...rn.segments.filter(Lt=>Lt.layer===Jy(t,Jt.busId)).map(Lt=>Cr(Xe.viaPoint,Lt.start,Lt.end)));return Kt($n)-Kt(ht)});for(const $n of kn.slice(0,1)){if(Bt++>=g)return null;const ht=new Set([Ut,dt.connectionIndex,$n.connectionIndex]),Kt=n.map(qe=>({...qe,connections:qe.connections.filter(vt=>ht.has(vt.connectionIndex))})).filter(qe=>qe.connections.length>0),rn=[...t.acceptedPlans,...st.filter(qe=>!ht.has(qe.connectionIndex)),...pn.filter(qe=>!xt.has(qe.connectionIndex)&&!ht.has(qe.connectionIndex))],Lt=HPe({...t,buses:Kt,terminals:t.terminals.filter(qe=>ht.has(qe.connection.connectionIndex)),acceptedPlans:rn,maximumLocalRepairAttempts:0,maximumIterations:Math.min(l,2e6)},e);let Ho=Lt.next();for(;!Ho.done;)yield{iterations:ne.iterations+Ho.value.iterations,routedConnectionCount:st.length-2+Ho.value.routedConnectionCount,connectionCount:w.length},Ho=Lt.next();if(!Ho.value)continue;const Ao=[...st.filter(qe=>!ht.has(qe.connectionIndex)),...Ho.value];if(Ao.length===w.length&&new Set(Ao.map(qe=>qe.connectionIndex)).size===M.size&>(Ao))return Ao}break}}return null}function*CSo(t,e,n){const{buses:o,layerNames:i}=t;if(!t.routeFromSourcePads)return null;const r=new Map(t.terminals.map(_=>[_.connection.connectionIndex,_])),s=new Set(e.map(_=>_.connectionIndex));if(r.size<2||s.size!==e.length||e.length!==r.size-1||e.some(_=>r.get(_.connectionIndex)?.connection.connection.name!==_.connectionName||_.targetLayer!==Jy(t,_.busId)||_.sourceLayer!==r.get(_.connectionIndex).connection.sourceLayer||tn(_.sourcePoint,r.get(_.connectionIndex).connection.sourcePoint)>1e-7||!_.via||tn(_.exitPoint,r.get(_.connectionIndex).exitPoint)>1e-7))return null;const a=t.terminals.filter(_=>!s.has(_.connection.connectionIndex)),A=a[0].connection.connectionIndex,c=new Map(t.fixedViaPointsByConnectionIndex),l=new Map(t.sourceEscapePaths);for(const _ of e)c.set(_.connectionIndex,_.via.center),l.set(_.connectionIndex,[_.sourcePoint,..._.segments.slice(0,_.sourceEscapeSegmentCount??1).map(f=>f.end)]);const u=o.map(_=>({..._,connections:_.connections.filter(f=>f.connectionIndex===A)})).filter(_=>_.connections.length>0),g=Jy(t,u[0].busId),h=i.filter(_=>_!==g&&u.every(f=>(f.routableEscapeLayers??f.allowedLayers??i).includes(_)&&f.connections.every(I=>I.sourceLayer!==_))),d=HPe({...t,buses:u,targetLayer:g,terminals:a,transitLayers:h,fixedViaPointsByConnectionIndex:c,sourceEscapePaths:l,acceptedPlans:[...t.acceptedPlans,...e],includeDiagonalNeighbors:!0,ripCost:256,maximumIterations:Math.min(t.maximumIterations??5e6,5e6),maximumRipEvents:Math.min(t.maximumRipEvents??400,400),maximumLocalRepairAttempts:0,maximumSourceOriginRepairAttempts:0},n);let p=d.next();for(;!p.done;)yield{...p.value,routedConnectionCount:e.length+p.value.routedConnectionCount,connectionCount:r.size},p=d.next();if(!p.value)return null;const m=[...e,...p.value];return m.length===r.size&&new Set(m.map(_=>_.connectionIndex)).size===r.size?m:null}var e_=1e-7,cE=t=>Math.max(...t.map(e=>e.length))-Math.min(...t.map(e=>e.length));function rR(t,e){const n=t.trace.route.findIndex(r=>r.route_type==="via"),o=e.trace.route.findIndex(r=>r.route_type==="via");if(n<0||o<0)return null;const i=t.sourceEscapeSegmentCount??1;return{...e,sourcePoint:t.sourcePoint,via:t.via,exitPoint:t.exitPoint,sourceEscapeSegmentCount:i,segments:[...t.segments.slice(0,i),...e.segments.slice(e.sourceEscapeSegmentCount??1)],trace:{...t.trace,route:[...t.trace.route.slice(0,n+1),...e.trace.route.slice(o+1)]}}}function OPe(t,e,n){if(!e.exitEdge||t.termination.type!=="boundary")return null;const o=e.sharedBoundary,i=h=>e.exitEdge==="left"?h.x-o.minX:e.exitEdge==="right"?o.maxX-h.x:e.exitEdge==="top"?o.maxY-h.y:h.y-o.minY;if(Math.abs(i(t.exitPoint))>e_)return null;let r=t.segments.length-1;for(;r>0&&t.segments[r-1].layer===t.targetLayer;)r--;if(r<(t.sourceEscapeSegmentCount??1))return null;let s=-1;for(let h=r;h<t.segments.length;h++){const d=t.segments[h];i(d.start)>=n&&i(d.end)<=n&&(s=h)}s<0&&(s=r);const a=t.segments[s],A=i(a.start),c=i(a.end),l=A>n&&c<A?(A-n)/(A-c):0,u={x:a.start.x+(a.end.x-a.start.x)*l,y:a.start.y+(a.end.y-a.start.y)*l};if(i(u)<=e_)return null;const g=[{...a,start:u},...t.segments.slice(s+1)].filter(h=>tn(h.start,h.end)>e_);return!g.length||g.some(h=>h.layer!==t.targetLayer)?null:{...t,sourcePoint:{...t.sourcePoint,...u},sourceEscapeSegmentCount:0,via:void 0,additionalVias:[],segments:g,length:g.reduce((h,d)=>h+tn(d.start,d.end),0),trace:{...t.trace,pcb_trace_id:`${t.trace.pcb_trace_id}-retained-tail`,route:[u,...g.map(h=>h.end)].map(h=>({route_type:"wire",...h,layer:t.targetLayer,width:g[0].width}))}}}function GPe(t){const{inputSrj:e,preparedBuses:n,layerNames:o,viaDiameter:i,viaHoleDiameter:r}=t,s=new Map(t.plans.map(l=>[l.connectionIndex,l])),a=n.flatMap(l=>l.connections);if(a.length!==e.connections.length||s.size!==a.length||s.size!==t.plans.length||a.some(l=>s.get(l.connectionIndex)?.connectionName!==l.connection.name))throw new Error("Retained-tail repair requires every original connection exactly once");const A=new Map,c=new Map;for(const l of a){const u=s.get(l.connectionIndex),g=u.segments.slice(0,u.sourceEscapeSegmentCount??1);if(!u.via||!g.length||g.some(h=>h.layer!==l.sourceLayer)||tn(g[0].start,l.sourcePoint)>e_||tn(g.at(-1).end,u.via.center)>e_||g.some((h,d)=>d>0&&tn(g[d-1].end,h.start)>e_)||u.via.fromLayer!==l.sourceLayer||u.via.toLayer!==u.targetLayer||u.via.diameter!==i||u.via.holeDiameter!==r||u.via.spanLayers.length!==o.length||!o.every(h=>u.via.spanLayers.includes(h)))return null;A.set(l.connectionIndex,u.via.center),c.set(l.connectionIndex,[g[0].start,...g.map(h=>h.end)])}return{fixed:A,sourcePaths:c}}function*ySo(t,e){const{inputSrj:n,preparedBuses:o,layerNames:i,traceWidth:r,clearance:s,viaDiameter:a,viaHoleDiameter:A}=t,c=t.maximumIterationsPerAttempt??1e7;if(!Number.isSafeInteger(c)||c<1)throw new Error("maximumIterationsPerAttempt must be a positive safe integer");const l=GPe(t);if(!l)return null;const{fixed:u,sourcePaths:g}=l;let h=[...t.plans];const d=o.filter(m=>m.termination.type==="boundary"&&m.maxLengthSkew!==void 0&&m.connections.length>1&&(!t.busIds||t.busIds.includes(m.busId)));for(const m of d){const _=h.filter(Y=>Y.busId===m.busId);if(_.length!==m.connections.length)return null;if(cE(_)<=m.maxLengthSkew+e_)continue;const f=_[0].targetLayer;if(_.some(Y=>Y.targetLayer!==f||Y.planeEndpointTrace||Y.planeEndpointSegments||Y.planeEndpointVia)||!m.exitEdge)return null;const I=(m.routableEscapeLayers??m.allowedLayers??i).filter(Y=>(m.allowedLayers??i).includes(Y));if(!I.includes(f))return null;const C=I.filter(Y=>Y!==f);if(!C.length)return null;const y=(Y,W,te)=>{const j={srj:n,allBuses:o,buses:[{...m,connections:Y}],targetLayer:f,transitLayers:C,terminals:Y.map(J=>({connection:J,viaPoint:u.get(J.connectionIndex),exitPoint:W.get(J.connectionIndex)})),fixedViaPointsByConnectionIndex:u,sourceEscapePaths:g,acceptedPlans:te,layerNames:i,traceWidth:r,clearance:s,viaDiameter:a,viaHoleDiameter:A,tightViaChannels:!0,includeDiagonalNeighbors:!0,heuristicWeight:1,maximumIterations:c,maximumRipEvents:200,maximumLocalRepairAttempts:0,ripCost:256,shuffleSeed:1};return AE(j)},x=_.toSorted((Y,W)=>W.length-Y.length)[0],E=m.connections.find(Y=>Y.connectionIndex===x.connectionIndex),B=y([E],new Map([[x.connectionIndex,x.exitPoint]]),h.filter(Y=>Y!==x));let S=B.next();for(;!S.done;)yield{...S.value,busId:m.busId,phase:"lane"},S=B.next();const Q=S.value?.[0]?rR(x,S.value[0]):null;if(Q&&Q.length<x.length-e_&&cE(_.map(Y=>Y===x?Q:Y))<cE(_)-e_&&e.push({busId:m.busId,plan:Q}),Q&&cE(_.map(Y=>Y===x?Q:Y))<=m.maxLengthSkew+e_){h=h.map(Y=>Y===x?Q:Y);continue}const w=Math.min(12*(r+s),(m.exitEdge==="left"||m.exitEdge==="right"?m.sharedBoundary.maxX-m.sharedBoundary.minX:m.sharedBoundary.maxY-m.sharedBoundary.minY)/3),M=_.map(Y=>OPe(Y,m,w));if(M.some(Y=>!Y))return null;const k=M,R=h.filter(Y=>Y.busId!==m.busId),F=y(m.connections,new Map(k.map(Y=>[Y.connectionIndex,Y.sourcePoint])),[...R,...k]);let O=F.next();for(;!O.done;)yield{...O.value,busId:m.busId,phase:"bus"},O=F.next();if(!O.value||O.value.length!==_.length)return null;let U=h.map(Y=>{const W=O.value.find(oe=>oe.connectionIndex===Y.connectionIndex);if(!W)return Y;const te=rR(Y,W);if(!te)throw new Error("Retained-tail routing lost its source via");const j=k.find(oe=>oe.connectionIndex===te.connectionIndex),J=[...te.trace.route,...j.trace.route.slice(1)];return J[J.length-1]=Y.trace.route.at(-1),{...te,exitPoint:Y.exitPoint,trace:{...Y.trace,route:J},segments:[...te.segments,...j.segments],length:te.length+j.length}});for(const Y of _){const W=U.find(j=>j.connectionIndex===Y.connectionIndex),te=n$(t,W,U.filter(j=>j!==W),m,!0);if(!te)return null;U=U.map(j=>j===W?te:j)}if(cE(U.filter(Y=>Y.busId===m.busId))>m.maxLengthSkew+e_||!Wh({plans:U,srj:n,sharedBoundary:m.sharedBoundary,clearance:s,allowBlindAndBuriedVias:!1,allowSameNetMerges:!1}))return null;h=U}return qu({inputSrj:n,routedSrj:{...n,traces:[...n.traces??[],...h.flatMap(m=>[m.trace,...m.planeEndpointTrace?[m.planeEndpointTrace]:[]])]},clearance:s,allowBlindAndBuriedVias:!1}).valid?h:null}function*xSo(t,e){const n=yield*ySo(t,e);if(n)return n;const o=GPe(t);if(!o)return null;const{fixed:i,sourcePaths:r}=o,{inputSrj:s,preparedBuses:a,layerNames:A,traceWidth:c,clearance:l}=t,u=a.filter(p=>p.termination.type==="boundary"&&p.connections.length>1&&p.maxLengthSkew!==void 0&&(!t.busIds||t.busIds.includes(p.busId))),g=new Map;for(const p of u){const m=t.plans.filter(I=>I.busId===p.busId);if(m.length!==p.connections.length||!p.exitEdge)return null;const _=m[0].targetLayer;if(m.some(I=>I.targetLayer!==_||I.planeEndpointTrace||I.planeEndpointSegments||I.planeEndpointVia))return null;const f=`${_}:${p.exitEdge}`;g.set(f,[...g.get(f)??[],p])}let h=[...t.plans];for(const p of g.values()){const m=new Set(p.map(O=>O.busId)),_=h.filter(O=>m.has(O.busId));if(p.every(O=>cE(_.filter(U=>U.busId===O.busId))<=O.maxLengthSkew+e_))continue;if(p.length<2)return null;const f=_[0].targetLayer,I=A.filter(O=>p.every(U=>(U.routableEscapeLayers??U.allowedLayers??A).includes(O)&&(U.allowedLayers??A).includes(O)));if(!I.includes(f))return null;const C=I.filter(O=>O!==f);if(!C.length)return null;const y=p[0].sharedBoundary,x=Math.min(12*(c+l),(p[0].exitEdge==="left"||p[0].exitEdge==="right"?y.maxX-y.minX:y.maxY-y.minY)/3),E=_.map(O=>OPe(O,p.find(U=>U.busId===O.busId),x));if(E.some(O=>!O))return null;const B=E,S=h.filter(O=>!m.has(O.busId)),Q=AE({...t,srj:s,allBuses:a,buses:p,targetLayer:f,transitLayers:C,terminals:p.flatMap(O=>O.connections.map(U=>({connection:U,viaPoint:i.get(U.connectionIndex),exitPoint:B.find(Y=>Y.connectionIndex===U.connectionIndex).sourcePoint}))),fixedViaPointsByConnectionIndex:i,sourceEscapePaths:r,acceptedPlans:[...S,...B],tightViaChannels:!0,includeDiagonalNeighbors:!0,heuristicWeight:1,ripCost:8,shuffleSeed:1,maximumIterations:t.maximumIterationsPerAttempt??1e7,maximumRipEvents:200,maximumLocalRepairAttempts:0});let w=Q.next();for(;!w.done;)yield{...w.value,busId:p[0].busId,phase:"layer"},w=Q.next();if(!w.value||w.value.length!==_.length)return null;const M=w.value;let k=h.map(O=>{const U=M.find(j=>j.connectionIndex===O.connectionIndex);if(!U)return O;const Y=rR(O,U);if(!Y)throw new Error("Joint retained-tail routing lost its source via");const W=B.find(j=>j.connectionIndex===O.connectionIndex),te=[...Y.trace.route,...W.trace.route.slice(1)];return te[te.length-1]=O.trace.route.at(-1),{...Y,trace:{...O.trace,route:te},segments:[...Y.segments,...W.segments],length:Y.length+W.length}});for(const O of _){const U=k.find(W=>W.connectionIndex===O.connectionIndex),Y=n$(t,U,k.filter(W=>W!==U),p.find(W=>W.busId===O.busId),!0);if(!Y)return null;k=k.map(W=>W===U?Y:W)}if(!Wh({plans:k,srj:s,sharedBoundary:y,clearance:l,allowBlindAndBuriedVias:!1,allowSameNetMerges:!1}))return null;k=SO({...t,plans:k,preparedBuses:p,selectedBusIds:m,allowBlindAndBuriedVias:!1})??k;const R=zy({...t,plans:k,preparedBuses:p,sharedBoundary:y,allowBlindAndBuriedVias:!1,allowSameNetMerges:!1,allowMatchingInsideDenseBounds:!0,allowPairLaneSpreading:!0,allowUnconstrainedLaneRerouting:!0,maximumWorkUnits:1e3});if(!R.plans)return null;const F=R.plans;if(k=h.map(O=>{if(!m.has(O.busId))return O;const U=F.find(W=>W.connectionIndex===O.connectionIndex),Y=rR(O,U);if(!Y)throw new Error("Joint retained-tail tuning lost its source via");return Y}),p.some(O=>cE(k.filter(U=>U.busId===O.busId))>O.maxLengthSkew+e_))return null;h=k}return u.some(p=>cE(h.filter(m=>m.busId===p.busId))>p.maxLengthSkew+e_)?null:qu({inputSrj:s,routedSrj:{...s,traces:[...s.traces??[],...h.flatMap(p=>[p.trace,...p.planeEndpointTrace?[p.planeEndpointTrace]:[]])]},clearance:l,allowBlindAndBuriedVias:!1}).valid?h:null}function*ESo(t){const e=[],n=yield*xSo(t,e);if(n)return n;if(!e.length)return null;let o=[...t.plans],i=!1;for(const{busId:s,plan:a}of e){const A=t.preparedBuses.find(p=>p.busId===s),c=o.find(p=>p.connectionIndex===a.connectionIndex),l=n$(t,a,o.filter(p=>p!==c),A,!0);if(!l)continue;const u=o.map(p=>p===c?l:p),g=zy({...t,plans:u,preparedBuses:[A],sharedBoundary:A.sharedBoundary,allowBlindAndBuriedVias:!1,allowSameNetMerges:!1,allowMatchingInsideDenseBounds:!0,allowPairLaneSpreading:!0,allowUnconstrainedLaneRerouting:!0,maximumWorkUnits:1e3});if(!g.plans)continue;const h=o.map(p=>{if(p.busId!==s)return p;const m=g.plans.find(_=>_.connectionIndex===p.connectionIndex);return rR(p,m)});if(h.some(p=>!p))continue;const d=h;cE(d.filter(p=>p.busId===s))>A.maxLengthSkew+e_||!Wh({plans:d,srj:t.inputSrj,sharedBoundary:A.sharedBoundary,clearance:t.clearance,allowBlindAndBuriedVias:!1,allowSameNetMerges:!1})||(o=d,i=!0)}return!i||t.preparedBuses.some(s=>(!t.busIds||t.busIds.includes(s.busId))&&s.maxLengthSkew!==void 0&&cE(o.filter(a=>a.busId===s.busId))>s.maxLengthSkew+e_)?null:qu({inputSrj:t.inputSrj,routedSrj:{...t.inputSrj,traces:[...t.inputSrj.traces??[],...o.flatMap(s=>[s.trace,...s.planeEndpointTrace?[s.planeEndpointTrace]:[]])]},clearance:t.clearance,allowBlindAndBuriedVias:!1}).valid?o:null}function*BSo(t){const e=GPe(t);if(!e)return null;const{inputSrj:n,preparedBuses:o,layerNames:i}=t,r=t.maximumIterationsPerAttempt??5e6;if(!Number.isSafeInteger(r)||r<1)throw new Error("maximumIterationsPerAttempt must be a positive safe integer");const s=Math.min(r,5e6),a=o.filter(u=>u.termination.type==="boundary"&&u.connections.length>2&&u.maxLengthSkew!==void 0&&(!t.busIds||t.busIds.includes(u.busId)));let A=[...t.plans],c=!1;for(const u of a){const g=A.filter(M=>M.busId===u.busId);if(g.length!==u.connections.length)return null;if(cE(g)<=u.maxLengthSkew+e_)continue;const h=Math.min(...g.map(M=>M.length)),d=g.filter(M=>M.length>h+u.maxLengthSkew+e_).toSorted((M,k)=>k.length-M.length||M.connectionIndex-k.connectionIndex).slice(0,2);if(d.length!==2)return null;const p=g[0].targetLayer;if(!u.exitEdge||g.some(M=>M.targetLayer!==p||M.planeEndpointTrace||M.planeEndpointSegments||M.planeEndpointVia))return null;const m=(u.routableEscapeLayers??u.allowedLayers??i).filter(M=>(u.allowedLayers??i).includes(M)),_=m.filter(M=>M!==p);if(!m.includes(p)||!_.length)return null;const f=new Set(d.map(M=>M.connectionIndex)),I=u.connections.filter(M=>f.has(M.connectionIndex)),C=AE({...t,srj:n,allBuses:o,buses:[{...u,connections:I}],targetLayer:p,transitLayers:_,terminals:I.map(M=>({connection:M,viaPoint:e.fixed.get(M.connectionIndex),exitPoint:g.find(k=>k.connectionIndex===M.connectionIndex).exitPoint})),fixedViaPointsByConnectionIndex:e.fixed,sourceEscapePaths:e.sourcePaths,acceptedPlans:A.filter(M=>!f.has(M.connectionIndex)),tightViaChannels:!0,includeDiagonalNeighbors:!0,ripCost:64,shuffleSeed:1,maximumIterations:s,maximumRipEvents:80,maximumLocalRepairAttempts:0});let y=C.next();for(;!y.done;)yield{...y.value,busId:u.busId,phase:"overlong-pair"},y=C.next();if(!y.value||y.value.length!==2)return null;const x=new Map(y.value.map(M=>[M.connectionIndex,M])),E=A.map(M=>{const k=x.get(M.connectionIndex);return k?rR(M,k):M});if(E.some(M=>!M))return null;const B=zy({...t,plans:E,preparedBuses:[u],sharedBoundary:u.sharedBoundary,allowBlindAndBuriedVias:!1,allowSameNetMerges:!1,allowMatchingInsideDenseBounds:!0,allowPairLaneSpreading:!0,allowUnconstrainedLaneRerouting:!0,maximumWorkUnits:1e3});if(!B.plans)return null;const S=new Map(B.plans.map(M=>[M.connectionIndex,M])),Q=A.map(M=>M.busId===u.busId?rR(M,S.get(M.connectionIndex)):M);if(Q.some(M=>!M))return null;const w=Q;if(cE(w.filter(M=>M.busId===u.busId))>u.maxLengthSkew+e_||!Wh({plans:w,srj:n,sharedBoundary:u.sharedBoundary,clearance:t.clearance,allowBlindAndBuriedVias:!1,allowSameNetMerges:!1}))return null;A=w,c=!0}return!c||o.some(u=>(!t.busIds||t.busIds.includes(u.busId))&&u.maxLengthSkew!==void 0&&cE(A.filter(g=>g.busId===u.busId))>u.maxLengthSkew+e_)?null:qu({inputSrj:n,routedSrj:{...n,traces:[...n.traces??[],...A.flatMap(u=>[u.trace,...u.planeEndpointTrace?[u.planeEndpointTrace]:[]])]},clearance:t.clearance,allowBlindAndBuriedVias:!1}).valid?A:null}function*bSo(t){const e=yield*ESo(t);return e||(yield*BSo(t))}function Aue(t,e,n){return t.buses.flatMap(o=>o.connections.map(i=>{const r=e.get(i.connectionIndex),s=o.termination.type==="plane"?o.termination.layer:(o.allowedLayers??t.layerNames).filter(a=>a!==i.sourceLayer).at(-1);return i4({...t,bus:o,terminal:{connection:i,viaPoint:r,exitPoint:r},targetLayer:s,targetLayerPoints:[r],sourceEscapePoints:n.get(i.connectionIndex),allowBlindAndBuriedVias:!1})}))}function SSo(t){if(!t.buses.length||t.buses.some(i=>i.connections.some(r=>r.sourceLayer!=="top")))return null;const e=pd(t.buses,{...t,maximumSearchStates:1e4,additionalObstacles:t.srj.obstacles});if(!e)return null;const n=new Map(t.buses.flatMap(i=>i.connections.map(r=>[r.connectionIndex,[r.sourcePoint,e.get(r.connectionIndex)]]))),o=Aue(t,e,n);return qu({inputSrj:t.srj,routedSrj:{...t.srj,traces:[...t.srj.traces??[],...o.map(i=>i.trace)]},clearance:t.clearance,allowBlindAndBuriedVias:!1}).valid?{fixedViaPointsByConnectionIndex:e,sourceEscapePaths:n,sourcePlans:o}:null}function*QSo(t){const e=AE({...t,transitLayers:[],routeFromSourcePads:!0,sourceLayerTravelCost:t.sourceLayerTravelCost??2,maximumRipEvents:1200,maximumIterations:t.maximumSourceIterations??5e7,maximumLocalRepairAttempts:0,shuffleSeed:1});let n=e.next();for(;!n.done;)yield n.value,n=e.next();if(!n.value)return null;let o=n.value;const i=new Map(t.fixedViaPointsByConnectionIndex),r=new Map(t.allBuses.flatMap(c=>c.connections.map(l=>[l.connectionIndex,t.sourceEscapePaths?.get(l.connectionIndex)??[l.sourcePoint,i.get(l.connectionIndex)]]))),s=new Map(t.buses.flatMap(c=>c.connections.map(l=>[l.connectionIndex,{bus:c,connection:l}]))),a=c=>{if(!c.via)throw new Error("Source-origin routing lost a required first via");i.set(c.connectionIndex,c.via.center);const l=c.segments.slice(0,c.sourceEscapeSegmentCount??1);r.set(c.connectionIndex,[c.sourcePoint,...l.map(u=>u.end)])};o.forEach(a);const A=c=>{const l=s.get(c.connectionIndex).bus;if(l.connections.length<=2||l.maxLengthSkew===void 0)return!1;const u=Math.min(...o.filter(g=>g.busId===c.busId).map(g=>g.length));return c.length>u+l.maxLengthSkew+1e-7};for(let c=0;c<2;c++){const l=o.filter(A).toSorted((g,h)=>h.length-g.length).slice(0,8);let u=!1;for(const g of l){const h=o.find(E=>E.connectionIndex===g.connectionIndex);if(!A(h))continue;const{bus:d,connection:p}=s.get(h.connectionIndex),m=t.cleanupRetainedBoundaryTails?OPe(h,d,(c===0?12:6)*(t.traceWidth+t.clearance)):null;if(t.cleanupRetainedBoundaryTails&&!m)continue;const _=AE({...t,buses:[{...d,connections:[p]}],transitLayers:[],routeFromSourcePads:!0,sourceLayerTravelCost:1,includeDiagonalNeighbors:t.cleanupRetainedBoundaryTails||t.includeDiagonalNeighbors,fixedViaPointsByConnectionIndex:i,sourceEscapePaths:r,acceptedPlans:[...t.acceptedPlans,...o.filter(E=>E!==h),...m?[m]:[]],terminals:[{connection:p,viaPoint:i.get(p.connectionIndex),exitPoint:m?.sourcePoint??h.exitPoint}],maximumRipEvents:1,maximumIterations:2e6,maximumLocalRepairAttempts:0,shuffleSeed:1});let f=_.next();for(;!f.done;)yield{...f.value,connectionCount:o.length},f=_.next();let I=f.value?.[0];if(I&&m){const E={...I,exitPoint:h.exitPoint,segments:[...I.segments,...m.segments],length:I.length+m.length,trace:{...I.trace,route:[...I.trace.route,...m.trace.route.slice(1)]}};I=n$({...t,inputSrj:t.srj},E,[...t.acceptedPlans,...o.filter(B=>B!==h),...Aue({...t,buses:t.allBuses.filter(B=>!t.buses.some(S=>S.busId===B.busId))},i,r)],d,!0)??void 0}if(!I||I.length>=h.length-1e-7)continue;const C=o.filter(E=>E.busId===h.busId),y=C.map(E=>E.length),x=C.map(E=>E===h?I.length:E.length);Math.max(...x)-Math.min(...x)>Math.max(...y)-Math.min(...y)+1e-7||m&&!qu({inputSrj:t.srj,routedSrj:{...t.srj,traces:[...t.srj.traces??[],...t.acceptedPlans.flatMap(E=>[E.trace,...E.planeEndpointTrace?[E.planeEndpointTrace]:[]]),...o.map(E=>(E===h?I:E).trace),...Aue({...t,buses:t.allBuses.filter(E=>!t.buses.some(B=>B.busId===E.busId)&&!t.acceptedPlans.some(B=>B.busId===E.busId))},i,r).map(E=>E.trace)]},clearance:t.clearance,allowBlindAndBuriedVias:!1}).valid||(o=o.map(E=>E===h?I:E),a(I),u=!0)}if(!u)break}return{plans:o,fixedViaPointsByConnectionIndex:i,sourceEscapePaths:r,sourcePlans:Aue({...t,buses:t.allBuses},i,r)}}function YPe(t){const e=t.filter(n=>n.termination.type==="boundary"&&n.connections.length>=8&&n.allowedLayers?.length===1&&n.allowedLayers[0]!=="top");return e.some(n=>n.connections.length>=16)?!1:e.some((n,o)=>e.slice(o+1).some(i=>i.componentId===n.componentId&&i.exitEdge===n.exitEdge&&i.allowedLayers[0]===n.allowedLayers[0]))}function cue(t){return t.some(e=>{if(e.termination.type!=="boundary"||e.connections.length<8||e.allowedLayers?.length!==1||e.allowedLayers[0]==="top")return!1;const n=e.exitEdge==="left"||e.exitEdge==="right"?"x":"y",o=e.exitEdge==="left"||e.exitEdge==="bottom"?-1:1,i=n==="x"?(e.componentBounds.minX+e.componentBounds.maxX)/2:(e.componentBounds.minY+e.componentBounds.maxY)/2;return e.connections.every(r=>o*(r.sourcePoint[n]-i)<-1e-7)})}function vSo(t,e){const n=t[0];if(!n||e||t.some(A=>A.componentId!==n.componentId||A.connections.some(c=>c.sourceLayer!=="top")))return!1;const o=t.filter(A=>A.termination.type==="boundary"),i=o.filter(A=>A.connections.length>=8),r=i[0]?.exitEdge;if(!r||i.some(A=>A.exitEdge!==r)||!(i.some(A=>A.connections.length>=16&&A.allowedLayers?.length===1&&A.allowedLayers[0]!=="top")||YPe(i)))return!1;const s=o.reduce((A,c)=>A+c.connections.length,0);return!(t.filter(A=>A.termination.type==="plane").reduce((A,c)=>A+c.connections.length,0)<s)}var QO=1e-7,wSo={left:"right",right:"left",up:"down",down:"up"};function UPe(t){const e=t;if(e.shape==="circle"||t.type!=="rect")return null;const n=(e.ccwRotationDegrees??0)/90;return Math.abs(n-Math.round(n))>QO?null:Math.abs(Math.round(n))%2===0?{x:t.width,y:t.height}:{x:t.height,y:t.width}}function SNt(t,e){const n=UPe(e);if(!n||Math.abs(n.x-n.y)<QO)return null;const{center:o}=e;if(n.x>n.y){if(Math.abs(o.x-n.x/2-t.minX)<QO)return"left";if(Math.abs(o.x+n.x/2-t.maxX)<QO)return"right"}else{if(Math.abs(o.y-n.y/2-t.minY)<QO)return"down";if(Math.abs(o.y+n.y/2-t.maxY)<QO)return"up"}return null}function KPe(t){const e=t.buses[0];if(!e||t.allowBlindAndBuriedVias||t.buses.some(a=>a.componentId!==e.componentId||a.connections.some(A=>A.sourceLayer!=="top")))return null;const n={minX:1/0,maxX:-1/0,minY:1/0,maxY:-1/0};for(const a of e.componentObstacles){const A=UPe(a);if(!A)return null;n.minX=Math.min(n.minX,a.center.x-A.x/2),n.maxX=Math.max(n.maxX,a.center.x+A.x/2),n.minY=Math.min(n.minY,a.center.y-A.y/2),n.maxY=Math.max(n.maxY,a.center.y+A.y/2)}const o=new Set;for(const a of t.buses)if(a.termination.type==="boundary")for(const A of a.connections){const c=SNt(n,A.sourceObstacle);if(!c)return null;o.add(c)}if(o.size!==4)return null;const i=new Map,r=new Map,s=[];for(const a of t.buses){const A=a.termination.type==="plane"?a.termination.layer:(a.routableEscapeLayers??a.allowedLayers??t.layerNames).filter(c=>c!=="top").at(-1);if(!A||!t.layerNames.includes(A))return null;for(const c of a.connections){const l=c.sourceObstacle,u=UPe(l);if(!u)return null;let g=SNt(n,l);if(g)(t.side??"inward")==="inward"&&(g=wSo[g]);else{if(a.termination.type!=="plane")return null;g=a.direction}const h=c.sourcePoint,d=t.viaDiameter/2+t.clearance+.001,p=g==="left"?{x:l.center.x-u.x/2-d,y:h.y}:g==="right"?{x:l.center.x+u.x/2+d,y:h.y}:g==="up"?{x:h.x,y:l.center.y+u.y/2+d}:{x:h.x,y:l.center.y-u.y/2-d},m=a.sharedBoundary,_=t.viaDiameter/2;if(p.x-_<m.minX||p.x+_>m.maxX||p.y-_<m.minY||p.y+_>m.maxY)return null;if(i.has(c.connectionIndex))throw new Error("FanoutSolver: duplicate peripheral source connection");i.set(c.connectionIndex,p),r.set(c.connectionIndex,[h,p]),s.push(i4({...t,bus:a,terminal:{connection:c,viaPoint:p,exitPoint:p},targetLayer:A,targetLayerPoints:[p],sourceEscapePoints:[h,p],allowBlindAndBuriedVias:!1}))}}return!Wh({...t,plans:s,sharedBoundary:e.sharedBoundary,allowBlindAndBuriedVias:!1})||!qu({inputSrj:t.srj,routedSrj:{...t.srj,traces:[...t.srj.traces??[],...s.map(a=>a.trace)]},clearance:t.clearance,allowBlindAndBuriedVias:!1}).valid?null:{fixedViaPointsByConnectionIndex:i,sourceEscapePaths:r,sourcePlans:s}}function QNt(t){const e=new Map;for(const o of t){const i=Ds(o.exitEdge,o.preferredExit);if(o.termination.type!=="boundary"||!o.exitEdge||!i)continue;const r=`${o.exitEdge}:${i}`,s=e.get(r)??[];s.push(o),e.set(r,s)}const n=new Map;for(const o of e.values()){const i=o[0].exitEdge==="left"||o[0].exitEdge==="right"?"y":"x",r=o.map((A,c)=>({bus:A,index:c,min:Math.min(...A.connections.map(l=>l.sourcePoint[i])),max:Math.max(...A.connections.map(l=>l.sourcePoint[i]))})).sort((A,c)=>A.min-c.min||A.index-c.index),s=[];for(const A of r){const c=s.at(-1);!c||A.min>c.max+1e-9?s.push({max:A.max,members:[A]}):(c.max=Math.max(c.max,A.max),c.members.push(A))}let a=0;for(const A of s)for(const{bus:c}of A.members.sort((l,u)=>l.index-u.index))n.set(c.busId,a),a+=c.connections.length}return n}function VPe(t){const{buses:e,targetLayerByBusId:n,traceWidth:o,clearance:i}=t,r=o+i;if(!(o>0)||!(t.viaDiameter>0)||i<0||![o,t.viaDiameter,i].every(Number.isFinite))throw new Error("FanoutSolver: invalid boundary packing dimensions");const s=QNt(e),a=[],A=new Map;for(const c of e){if(c.termination.type!=="boundary")continue;if(c.connections.length===0)throw new Error(`FanoutSolver: bus ${c.busId} has no connections`);if(!c.exitEdge)throw new Error(`FanoutSolver: bus ${c.busId} has no boundary edge`);const l=n.get(c.busId);if(!l||!t.layerNames.includes(l)||!(c.routableEscapeLayers??c.allowedLayers??t.layerNames).includes(l))throw new Error(`FanoutSolver: bus ${c.busId} has no legal assigned layer`);const u=e6(c.exitEdge),g=Ds(c.exitEdge,c.preferredExit),h=c.connections.map(I=>g?BB({...t,bus:c,connection:I,targetLayer:l,cornerExitLaneOffset:s.get(c.busId)??0,windingOrderIndex:0}):tR({...t,bus:c,connection:I,targetLayer:l,boundaryDirection:u,windingOrderIndex:0})),d=h.toSorted((I,C)=>I-C);if(d.some((I,C)=>!Number.isFinite(I)||C>0&&I-d[C-1]<r-1e-8))throw new Error(`FanoutSolver: bus ${c.busId} already contains overlapping desired lanes`);const p=c.exitEdge==="left"||c.exitEdge==="right",m={busId:c.busId,layer:l,edge:c.exitEdge,minimum:p?c.sharedBoundary.minY:c.sharedBoundary.minX,maximum:p?c.sharedBoundary.maxY:c.sharedBoundary.maxX,connectionIndices:c.connections.map(I=>I.connectionIndex),desiredTracks:h,tracks:[...h],desiredStart:d[0],desiredEnd:d.at(-1),start:d[0],end:d.at(-1),shift:0};if(![m.minimum,m.maximum].every(Number.isFinite)||m.maximum<m.minimum)throw new Error(`FanoutSolver: invalid boundary for ${c.busId}`);a.push(m);const _=`${l}:${c.exitEdge}`,f=A.get(_)??[];f.push(m),A.set(_,f)}for(const c of A.values()){const l=f=>Number(((f.desiredStart+f.desiredEnd)/2).toFixed(9)),u=c.toSorted((f,I)=>l(f)-l(I)),g=Math.max(...u.map(f=>f.minimum)),h=Math.min(...u.map(f=>f.maximum));if(u.every((f,I)=>f.desiredStart>=g&&f.desiredEnd<=h&&(I===0||f.desiredStart-u[I-1].desiredEnd>=r-1e-8)))continue;const d=[];let p=0;for(const[f,I]of u.entries())d.push(p),p+=I.desiredEnd-I.desiredStart+(f<u.length-1?r:0);if(p>h-g+1e-8)throw new Error(`FanoutSolver: bus intervals do not fit ${u[0].layer}/${u[0].edge}`);const m=[];for(const[f,I]of u.entries())for(m.push({first:f,last:f,weight:I.connectionIndices.length,mean:I.desiredStart-d[f]});m.length>1&&m.at(-2).mean>m.at(-1).mean;){const C=m.pop(),y=m.pop(),x=y.weight+C.weight;m.push({first:y.first,last:C.last,weight:x,mean:(y.mean*y.weight+C.mean*C.weight)/x})}const _=h-p;for(const f of m){const I=Math.max(g,Math.min(_,f.mean));for(let C=f.first;C<=f.last;C++){const y=u[C];y.start=I+d[C],y.shift=y.start-y.desiredStart,y.end=y.desiredEnd+y.shift,y.tracks=y.desiredTracks.map(x=>x+y.shift)}}}return{tracksByConnectionIndex:new Map(a.flatMap(c=>c.connectionIndices.map((l,u)=>[l,c.tracks[u]]))),intervals:a}}function PSo(t){if(t.exitTargetPoint)return t.exitTargetPoint.layer??"top";const e=t.targetPoint;return"layer"in e?e.layer??"top":e.layers[0]??"top"}function vNt(t){const e=t.exitEdge==="left"||t.exitEdge==="right"?"y":"x",n=new Map;for(const o of t.connections){const i=PSo(o);n.set(i,[...n.get(i)??[],o])}return[...n.values()].map(o=>o.toSorted((i,r)=>{const s=(i.exitTargetPoint??i.targetPoint)[e]-(r.exitTargetPoint??r.targetPoint)[e];if(s!==0)return s;const a=A=>"source_trace_id"in A.connection&&typeof A.connection.source_trace_id=="string"?A.connection.source_trace_id:A.connection.name;return a(i).localeCompare(a(r))||i.connection.name.localeCompare(r.connection.name)||i.connectionIndex-r.connectionIndex}))}function MSo(t,e){const n=t.exitEdge==="left"||t.exitEdge==="right"?"y":"x";return vNt(t).every(o=>o.every((i,r)=>{const s=e.get(i.connectionIndex);return!s||!Number.isFinite(s.x)||!Number.isFinite(s.y)?!1:r===0||s[n]>e.get(o[r-1].connectionIndex)[n]}))}function zPe(t){const e=t.maximumSearchStates??4096;if(!Number.isSafeInteger(e)||e<1)throw new Error("FanoutSolver: invalid boundary merge work bound");const n=new Map(t.exits);for(const o of t.buses){if(o.termination.type!=="boundary"||!o.exitEdge||o.connections.length<3||o.connections.some(p=>!p.hasExplicitLayeredExitTarget))continue;const i=vNt(o);if(i.length<2||i.reduce((p,m)=>p*(m.length+1),1)>e)continue;const s=o.exitEdge==="left"||o.exitEdge==="right"?"y":"x",a=s==="x"?"y":"x",A=o.exitEdge==="left"||o.exitEdge==="bottom"?-1:1,c={x:(o.componentBounds.minX+o.componentBounds.maxX)/2,y:(o.componentBounds.minY+o.componentBounds.maxY)/2},l=new Map(o.connections.map(p=>[p.connectionIndex,Math.atan2(p.sourcePoint[s]-c[s],A*(p.sourcePoint[a]-c[a]))])),u=o.connections.map(p=>{const m=n.get(p.connectionIndex);if(!m||!Number.isFinite(m.x)||!Number.isFinite(m.y))throw new Error("FanoutSolver: missing packed boundary target");return m[s]}).sort((p,m)=>p-m);if(u.some((p,m)=>m>0&&p<=u[m-1]))throw new Error("FanoutSolver: duplicate packed boundary tracks");const g=new Map,h=p=>{const m=p.join(","),_=g.get(m);if(_)return _;const f=p.reduce((C,y)=>C+y,0);if(f===u.length)return{inversions:0,length:0,order:[]};let I;for(const[C,y]of i.entries()){const x=y[p[C]];if(!x)continue;const E=i.reduce((M,k,R)=>M+k.slice(0,p[R]).filter(F=>l.get(F.connectionIndex)>l.get(x.connectionIndex)+1e-9).length,0),B=[...p];B[C]++;const S=h(B),Q={...n.get(x.connectionIndex),[s]:u[f]},w={inversions:E+S.inversions,length:Math.hypot(x.sourcePoint.x-Q.x,x.sourcePoint.y-Q.y)+S.length,order:[x,...S.order]};(!I||w.inversions<I.inversions||w.inversions===I.inversions&&w.length<I.length)&&(I=w)}if(!I)throw new Error("FanoutSolver: incomplete boundary merge state");return g.set(m,I),I},d=new Map(n);for(const[p,m]of h(i.map(()=>0)).order.entries())d.set(m.connectionIndex,{...n.get(m.connectionIndex),[s]:u[p]});if(!MSo(o,d))throw new Error("FanoutSolver: boundary merge changed a layer's lane order");for(const p of o.connections)n.set(p.connectionIndex,d.get(p.connectionIndex))}return n}var JPe=(t,e)=>{const n=t.sharedBoundary;switch(t.exitEdge){case"left":return{x:n.minX,y:e};case"right":return{x:n.maxX,y:e};case"top":return{x:e,y:n.maxY};case"bottom":return{x:e,y:n.minY};default:throw new Error(`FanoutSolver: bus ${t.busId} has no boundary edge`)}};function DSo(t,e,n,o){const i=(r,s,a)=>(s.x-r.x)*(a.y-r.y)-(s.y-r.y)*(a.x-r.x);return i(t,e,n)*i(t,e,o)<-1e-12&&i(n,o,t)*i(n,o,e)<-1e-12}function NSo(t){const{buses:e,layerNames:n,traceWidth:o,clearance:i}=t,r=o+i,s=new Map,a=[];for(const u of e){if(u.termination.type==="plane"){s.set(u.busId,u.termination.layer);continue}const g=new Set(u.connections.map(_=>_.sourceLayer)),h=(u.routableEscapeLayers??u.allowedLayers??n).filter(_=>t.allowSourceLayerTargets||!g.has(_));if(!h.length)return null;const d=h.map(_=>VPe({...t,buses:[u],targetLayerByBusId:new Map([[u.busId,_]])}).intervals[0]),p=u.connections.length,m=u.connections.reduce((_,f)=>({x:_.x+f.sourcePoint.x/p,y:_.y+f.sourcePoint.y/p}),{x:0,y:0});a.push({bus:u,source:m,intervals:d})}a.sort((u,g)=>u.intervals.length-g.intervals.length||Math.max(...g.intervals.map(h=>h.end-h.start))-Math.max(...u.intervals.map(h=>h.end-h.start))||g.bus.connections.length-u.bus.connections.length);const A=[];for(const{bus:u,source:g,intervals:h}of a){let d;for(const p of h){const m=A.filter(Q=>Q.interval.layer===p.layer),_=m.filter(Q=>Q.interval.edge===p.edge),f=Math.max(p.minimum,..._.map(Q=>Q.interval.minimum)),I=Math.min(p.maximum,..._.map(Q=>Q.interval.maximum)),C=p.end-p.start+_.reduce((Q,w)=>Q+w.interval.end-w.interval.start+r,0);if(C>I-f+1e-8)continue;const y=JPe(u,(p.start+p.end)/2),x=m.reduce((Q,w)=>Q+(DSo(g,y,w.source,w.target)?Math.min(u.connections.length,w.bus.connections.length):0),0),E=_.reduce((Q,w)=>Q+w.bus.connections.length,0),B=m.reduce((Q,w)=>Q+w.bus.connections.length,0),S=x*4+E+B/4+10*C/Math.max(r,I-f);(!d||S<d.score||S===d.score&&n.indexOf(p.layer)>n.indexOf(d.interval.layer))&&(d={interval:p,score:S})}if(!d)return null;s.set(u.busId,d.interval.layer),A.push({bus:u,source:g,interval:d.interval,target:JPe(u,(d.interval.start+d.interval.end)/2)})}const c=VPe({...t,targetLayerByBusId:s}),l=new Map;for(const{bus:u}of a)for(const g of u.connections)l.set(g.connectionIndex,JPe(u,c.tracksByConnectionIndex.get(g.connectionIndex)));return{targetLayerByBusId:s,exits:zPe({buses:e,exits:l})}}function*RSo(t){const{plans:e,bus:n,preparedBuses:o,inputSrj:i,layerNames:r}=t;if(n.termination.type!=="boundary"||n.connections.length!==2||n.maxLengthSkew===void 0||n.connections.some(_=>_.sourceLayer!=="top"))return null;const s=o.flatMap(_=>_.connections),a=new Map(e.map(_=>[_.connectionIndex,_]));if(s.length!==i.connections.length||a.size!==s.length||e.length!==a.size||s.some(_=>a.get(_.connectionIndex)?.connectionName!==_.connection.name))throw new Error("FanoutSolver: transit pair repair requires every original plan");const A=n.connections.map(_=>a.get(_.connectionIndex)),c=A[0].targetLayer;if(A.some(_=>_.targetLayer!==c)||Math.abs(A[0].length-A[1].length)<=n.maxLengthSkew+1e-6)return null;const l=(n.routableEscapeLayers??n.allowedLayers??r).filter(_=>_!=="top"&&_!==c);if(!l.length)return null;const u=new Map,g=new Map;for(const _ of s){const f=a.get(_.connectionIndex);if(!f.via)return null;const I=f.segments.slice(0,f.sourceEscapeSegmentCount??1);if(!I.length||I.some(C=>C.layer!==_.sourceLayer)||tn(I[0].start,_.sourcePoint)>1e-6||tn(I.at(-1).end,f.via.center)>1e-6||I.some((C,y)=>y>0&&tn(I[y-1].end,C.start)>1e-6))return null;u.set(_.connectionIndex,f.via.center),g.set(_.connectionIndex,[_.sourcePoint,...I.map(C=>C.end)])}const h=new Set(n.connections.map(_=>_.connectionIndex)),d=(n.routableEscapeLayers??n.allowedLayers??r).filter(_=>_!=="top");let p=5e6,m;for(const _ of[void 0,...d]){if(p<=0)break;const f=new Map(u),I=new Map(g);if(_!==void 0){if(m??=KPe({...t,srj:i,buses:o,side:"inward"}),!m)break;for(const M of h)f.set(M,m.fixedViaPointsByConnectionIndex.get(M)),I.set(M,m.sourceEscapePaths.get(M))}const C=AE({...t,srj:i,allBuses:o,buses:[n],targetLayer:c,startLayerByBusId:_===void 0?void 0:new Map([[n.busId,_]]),transitLayers:l,terminals:n.connections.map(M=>({connection:M,viaPoint:f.get(M.connectionIndex),exitPoint:a.get(M.connectionIndex).exitPoint})),fixedViaPointsByConnectionIndex:f,sourceEscapePaths:I,acceptedPlans:e.filter(M=>!h.has(M.connectionIndex)),routeFromSourcePads:_===void 0,sourceLayerTravelCost:1,sourceOriginPhysicalGridPhase:!0,tightViaChannels:!0,includeDiagonalNeighbors:!0,traceMarginExtra:0,maximumIterations:Math.min(p,_===void 0?5e6:2e6),maximumRipEvents:80,maximumLocalRepairAttempts:0,ripCost:256,shuffleSeed:1});let y=C.next(),x=0;for(;!y.done;)x=y.value.iterations,yield y.value,y=C.next();p-=x;const E=y.value;if(!E||E.length!==2)continue;const B=new Map(E.map(M=>[M.connectionIndex,M])),S=e.map(M=>B.get(M.connectionIndex)??M),Q=zy({...t,plans:S,preparedBuses:[n],sharedBoundary:n.sharedBoundary,maximumWorkUnits:1e5,allowSourcePrefixMatching:!0,allowDistributedMatching:!0,allowTransitLayerMatching:!0,allowMatchingInsideDenseBounds:!0});if(!Q.plans||Q.plans.some(M=>!h.has(M.connectionIndex)&&M!==a.get(M.connectionIndex)))continue;const w=Q.plans.filter(M=>h.has(M.connectionIndex));if(!(w.length!==2||Math.abs(w[0].length-w[1].length)>n.maxLengthSkew+1e-6)&&qu({inputSrj:i,routedSrj:{...i,traces:[...i.traces??[],...Q.plans.flatMap(M=>[M.trace,...M.planeEndpointTrace?[M.planeEndpointTrace]:[]])]},clearance:t.clearance,allowBlindAndBuriedVias:!1}).valid)return Q.plans}return null}var sR=1e-6,WPe=t=>Math.max(...t.map(e=>e.length))-Math.min(...t.map(e=>e.length));function*wNt(t){const{plans:e,bus:n,preparedBuses:o,inputSrj:i}=t,r=o.flatMap(d=>d.connections),s=new Map(e.map(d=>[d.connectionIndex,d]));if(r.length!==i.connections.length||s.size!==e.length||s.size!==r.length||r.some(d=>s.get(d.connectionIndex)?.connectionName!==d.connection.name))throw new Error("FanoutSolver: source-origin length repair requires every original plan");const a=n.connections.map(d=>s.get(d.connectionIndex));if(n.termination.type!=="boundary"||n.maxLengthSkew===void 0||a.length<2||WPe(a)<=n.maxLengthSkew+sR)return null;const A=a[0].targetLayer;if(a.some(d=>d.targetLayer!==A))return null;const c=Math.min(...a.map(d=>d.length)),l=new Set((a.length===2?a:a.filter(d=>d.length>c+n.maxLengthSkew+sR).toSorted((d,p)=>p.length-d.length||d.connectionIndex-p.connectionIndex).slice(0,2)).map(d=>d.connectionIndex));if(!l.size)return null;const u=new Map,g=new Map;for(const d of r){const p=s.get(d.connectionIndex);if(!p.via)return null;const m=p.segments.slice(0,p.sourceEscapeSegmentCount??1);if(!m.length||m.some(_=>_.layer!==d.sourceLayer)||tn(m[0].start,d.sourcePoint)>sR||tn(m.at(-1).end,p.via.center)>sR||m.some((_,f)=>f>0&&tn(m[f-1].end,_.start)>sR))return null;u.set(d.connectionIndex,p.via.center),g.set(d.connectionIndex,[d.sourcePoint,...m.map(_=>_.end)])}const h=n.connections.filter(d=>l.has(d.connectionIndex));for(const d of[!1,!0]){const p=yield*AE({...t,srj:i,allBuses:o,buses:[{...n,connections:h}],targetLayer:A,transitLayers:t.transitLayers??[],terminals:h.map(C=>({connection:C,viaPoint:u.get(C.connectionIndex),exitPoint:s.get(C.connectionIndex).exitPoint})),fixedViaPointsByConnectionIndex:u,sourceEscapePaths:g,acceptedPlans:e.filter(C=>!l.has(C.connectionIndex)),routeFromSourcePads:!0,includeDiagonalNeighbors:d,sourceLayerTravelCost:1,tightViaChannels:!0,ripCost:256,shuffleSeed:1,maximumRipEvents:40,maximumIterations:5e6,maximumLocalRepairAttempts:0});if(!p||p.length!==l.size)continue;const m=new Map(p.map(C=>[C.connectionIndex,C])),_=e.map(C=>m.get(C.connectionIndex)??C),f=a.map(C=>m.get(C.connectionIndex)??C);if(WPe(f)>=WPe(a)-sR&&Math.max(...f.map(C=>C.length))>=Math.max(...a.map(C=>C.length))-sR)continue;if(qu({inputSrj:i,routedSrj:{...i,traces:[...i.traces??[],..._.flatMap(C=>[C.trace,...C.planeEndpointTrace?[C.planeEndpointTrace]:[]])]},clearance:t.clearance,allowBlindAndBuriedVias:!1}).valid)return _}return null}function i$(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="subsolver"&&"solver"in t&&t.solver instanceof fC}function*TSo(t){const{srj:e,buses:n,layerNames:o}=t;yield{phase:"sources",routedConnectionCount:0};const i=KPe(t);if(!i)return null;const r=n.filter(y=>y.termination.type==="boundary");if(!r.length||r.some(y=>!y.exitEdge))return null;const s=NSo(t);if(!s)return null;const a=zPe({buses:n,exits:s.exits}),A=new Set(r.map(y=>s.targetLayerByBusId.get(y.busId))),c=o.findLast(y=>A.has(y)),l=o.filter(y=>y!==c&&r.some(x=>(x.routableEscapeLayers??x.allowedLayers??o).includes(y))),u=i.sourcePlans.filter(y=>y.termination.type==="plane"),g=AE({...t,allBuses:n,buses:r,targetLayer:c,targetLayerByBusId:s.targetLayerByBusId,transitLayers:l,terminals:r.flatMap(y=>y.connections.map(x=>({connection:x,viaPoint:i.fixedViaPointsByConnectionIndex.get(x.connectionIndex),exitPoint:a.get(x.connectionIndex)}))),...i,acceptedPlans:u,routeFromSourcePads:!0,sourceLayerTravelCost:2,sourceOriginPhysicalGridPhase:!0,includeDiagonalNeighbors:!0,traceMarginExtra:0,maximumIterations:6e7,maximumRipEvents:1e3,maximumLocalRepairAttempts:0,ripCost:64,shuffleSeed:1});let h=g.next();for(;!h.done;){if(i$(h.value)){const y=yield h.value;h=g.next(y);continue}yield{phase:"route-layer",iterations:h.value.iterations,routedConnectionCount:u.length+h.value.routedConnectionCount},h=g.next()}if(!h.value)return null;let d=[...h.value,...u];yield{phase:"repair-lengths",routedConnectionCount:d.length};const p=SO({...t,inputSrj:e,plans:d,preparedBuses:n});if(!p)return null;d=p;for(const y of r){if(y.maxLengthSkew===void 0)continue;const x=wNt({...t,inputSrj:e,plans:d,preparedBuses:n,bus:y});let E=x.next();for(;!E.done;)yield{phase:"repair-lengths",iterations:E.value.iterations,routedConnectionCount:d.length},E=x.next();E.value&&(d=E.value)}yield{phase:"match-layer",routedConnectionCount:d.length};let m=d;const _={...t,inputSrj:e,plans:d,preparedBuses:n,sharedBoundary:r[0].sharedBoundary,maximumWorkUnits:1e3,allowSourcePrefixMatching:!0,candidatePlansAreFeasible:y=>(m=[...y],!0)};let f=zy(_);f.plans||(f=zy({..._,maximumWorkUnits:1e5,allowDistributedMatching:!0,allowTransitLayerMatching:!0,allowMatchingInsideDenseBounds:!0}));const I=new Set;for(;!f.plans;){const y=f.failedBus.busId,x=r.find(S=>S.busId===y);if(!x||x.connections.length!==2||x.maxLengthSkew===void 0||I.has(x.busId))return null;I.add(x.busId);const E=RSo({...t,inputSrj:e,plans:m,preparedBuses:n,bus:x});let B=E.next();for(;!B.done;)yield{phase:"repair-lengths",iterations:B.value.iterations,routedConnectionCount:d.length},B=E.next();if(!B.value)return null;m=B.value,f=zy({..._,plans:m,maximumWorkUnits:1e5,allowDistributedMatching:!0,allowTransitLayerMatching:!0,allowMatchingInsideDenseBounds:!0})}if(!f.plans)return null;const C=DPe({...t,inputSrj:e,plans:f.plans,preparedBuses:n});return!C||C.length!==e.connections.length||new Set(C.map(y=>y.connectionIndex)).size!==C.length?null:qu({inputSrj:e,routedSrj:{...e,traces:[...e.traces??[],...C.flatMap(y=>[y.trace,...y.planeEndpointTrace?[y.planeEndpointTrace]:[]])]},clearance:t.clearance,allowBlindAndBuriedVias:!1}).valid?C:null}function kSo(t){const e=t.candidateSets.flat(),n=e.length,o=new Uint8Array(n*n),i=new Set,r=new Map;let s=0;const a=t.candidateSets.map(C=>C.map(()=>s++));let A=0;const c=(C,y)=>{const x=Math.min(C,y)*n+Math.max(C,y),E=o[x];if(E)return E===1;const B=t.areCompatible(e[C],e[y]);return o[x]=B?1:2,B},l=a.map(()=>[]);for(let C=0;C<a.length;C++)for(let y=C+1;y<a.length;y++)a[C].some(x=>a[y].some(E=>!c(x,E)))&&(l[C].push(y),l[y].push(C));const u=(C,y,x)=>{const E=[];let B=!0;for(const S of y){if(C[S].length===0){i.add(S),B=!1;continue}for(const Q of l[S])y.includes(Q)&&(x===void 0||Q===x)&&E.push([S,Q])}for(let S=0;S<E.length;S++){const[Q,w]=E[S];if(C[Q].length===0||C[w].length===0)continue;const M=C[Q].filter(k=>C[w].some(R=>c(k,R)));if(M.length!==C[Q].length){if(r.set(Q,w),C[Q]=M,M.length===0){i.add(Q),B=!1;continue}for(const k of l[Q])k!==w&&y.includes(k)&&E.push([k,Q])}}return B},g=a.map((C,y)=>y),h=C=>{const y=[...C],x=new Set(y);for(let E=0;E<y.length;E++){const B=r.get(y[E]);B!==void 0&&!x.has(B)&&(x.add(B),y.push(B))}return[...x]},d=a.map(C=>[...C]);if(!u(d,g))return{selection:null,searchStates:A,emptyDomainIndices:[...i],conflictDomainIndices:h([...i])};const m=(()=>{const y=Math.max(1,Math.min(5e3,Math.floor(t.maximumSearchStates/12)));for(let x=0;x<12;x++){const E=d.map((B,S)=>B[(x*17+S*7)%B.length]);for(let B=0;B<y;B++){const S=E.map(()=>0);for(let R=0;R<E.length;R++)for(const F of l[R])F<=R||c(E[R],E[F])||(S[R]=S[R]+1,S[F]=S[F]+1);const Q=Math.max(...S);if(Q===0)return E;const w=S.map((R,F)=>({conflicts:R,index:F})).filter(({conflicts:R})=>R===Q),M=w[(B+x)%w.length].index,k=d[M].map((R,F)=>({candidate:R,index:F,conflicts:l[M].filter(O=>!c(R,E[O])).length})).toSorted((R,F)=>R.conflicts-F.conflicts||(R.index-B-x)%d[M].length-(F.index-B-x)%d[M].length);E[M]=k[0].candidate}}return null})();if(m)return{selection:m.map(C=>e[C]),searchStates:A,emptyDomainIndices:[],conflictDomainIndices:[]};const _=(C,y,x)=>{if(!u(C,y,x))return null;const E=new Set(y.filter(w=>C[w].length>1)),B=[];for(;E.size>0;){const w=[E.values().next().value];E.delete(w[0]);for(let M=0;M<w.length;M++)for(const k of l[w[M]])E.delete(k)&&w.push(k);B.push(w)}if(B.length>1){let w=C;for(const M of B){const k=_(w.slice(),M);if(!k)return null;w=k}return w}let S=-1;for(const w of y)C[w].length>1&&(S<0||C[w].length<C[S].length)&&(S=w);if(S<0)return C;const Q=C[S].map(w=>{const M=l[S].filter(k=>y.includes(k)&&C[k].length>1).map(k=>C[k].filter(R=>c(w,R)).length);return{candidate:w,minimumSupport:Math.min(...M),totalSupport:M.reduce((k,R)=>k+R,0)}}).toSorted((w,M)=>M.minimumSupport-w.minimumSupport||M.totalSupport-w.totalSupport);for(const{candidate:w}of Q){if(A>=t.maximumSearchStates)return null;A++;const M=C.slice();M[S]=[w];const k=_(M,y,S);if(k)return k}return null},f=_(d,g),I=i.size>0||f?[...i]:[g.toSorted((C,y)=>l[y].length-l[C].length||d[C].length-d[y].length)[0]];return{selection:f?.map(C=>e[C[0]])??null,searchStates:A,emptyDomainIndices:I,conflictDomainIndices:f?[]:h(I)}}var lue=1e-9;function FSo(t){const e=t.candidateBusIds.filter(d=>!t.activeBusIds.has(d));if(e.length<2)return e;const n=e.length-1,o=t.planeBuses.find(d=>d.busId===e[n]),i=o?.connections[0]?.sourcePoint;if(!o||!i||o.connections.length!==1||o.termination.type!=="plane")return e;const r=o.termination.layer,s=o.direction==="up"||o.direction==="down"?"x":"y",a=s==="x"?"y":"x",A=s==="x"?o.xCoordinates:o.yCoordinates,c=s==="x"?o.pitchX:o.pitchY;if(A.length===0||!Number.isFinite(c)||c<=lue)return e;const l=(Math.min(...A)+Math.max(...A))/2,u=Math.sign(l-i[s]);if(u===0)return e;const g=new Set(e),h=t.planeBuses.filter(d=>{const p=d.connections[0]?.sourcePoint;if(d===o||d.componentId!==o.componentId||d.termination.type!=="plane"||d.termination.layer!==r||d.direction!==o.direction||d.connections.length!==1||!p||t.activeBusIds.has(d.busId)||g.has(d.busId)||Math.abs(p[a]-i[a])>lue)return!1;const m=(p[s]-i[s])*u;return m>lue&&m<=c+lue}).toSorted((d,p)=>{const m=d.connections[0].sourcePoint,_=p.connections[0].sourcePoint;return Math.abs(m[s]-i[s])-Math.abs(_[s]-i[s])||d.connections[0].connectionIndex-p.connections[0].connectionIndex})[0];return h?e.map((d,p)=>p===n?h.busId:d):e}function LSo(t){const e=t[0];if(!e||t.some(c=>c.componentId!==e.componentId))return;const n=t.flatMap(c=>c.connections.map(l=>l.sourcePoint));if(n.length===0)return;const o=n.reduce((c,l)=>({x:c.x+l.x,y:c.y+l.y}),{x:0,y:0});o.x/=n.length,o.y/=n.length;const{minX:i,maxX:r,minY:s,maxY:a}=e.componentBounds,A=[{edge:"left",distance:Math.abs(o.x-i)},{edge:"right",distance:Math.abs(r-o.x)},{edge:"bottom",distance:Math.abs(o.y-s)},{edge:"top",distance:Math.abs(a-o.y)}].toSorted((c,l)=>c.distance-l.distance);if(!(Math.abs(A[0].distance-A[1].distance)<=1e-9))return A[0].edge}function PNt(t,e){if(e)return!1;const n=t.filter(u=>u.termination.type==="boundary"),o=n.filter(u=>u.connections.length===1),i=n.filter(u=>u.connections.length===2),r=n.filter(u=>u.connections.length>=8),s=t.filter(u=>u.termination.type==="plane"&&u.connections.length===1).length,a=r[0]?.exitEdge;if(n.length!==9||o.length!==3||i.length!==3||r.length!==3||s<64||a===void 0||r.some(u=>u.exitEdge!==a))return!1;const A=LSo(r);return A===void 0?!1:(A==="left"||A==="right")!==(a==="left"||a==="right")}function HSo(t){const{trace:e,layerNames:n,allowBlindAndBuriedVias:o}=t;return{...e,route:e.route.map(i=>i.route_type==="via"&&!o?{...i,layers:Mx({fromLayer:i.from_layer,toLayer:i.to_layer,layerNames:n,allowBlindAndBuriedVias:o})}:{...i})}}function OSo(t){const{srj:e,layerNames:n,allowBlindAndBuriedVias:o}=t;return{...e,traces:(e.traces??[]).map(i=>HSo({trace:i,layerNames:n,allowBlindAndBuriedVias:o}))}}function jPe(t,e,n,o){const i=n.spanLayers.map(s=>{const a=e.indexOf(s);if(a<0)throw new Error(`FanoutSolver: via for "${t.connectionName}" uses unknown layer "${s}"`);return a}),r=qN(t);return{obstacleId:o==="endpoint"?r.planeEndpointViaObstacleId:o===0?r.viaObstacleId:`${r.viaObstacleId}:${o}`,type:"rect",center:n.center,width:n.diameter,height:n.diameter,layers:n.spanLayers,zLayers:i,__zLayers:i,connectedTo:[t.connectionName,t.trace.pcb_trace_id]}}function aR(t){const{inputSrj:e,plans:n,layerNames:o}=t,i=e.connections.map(u=>({...u,pointsToConnect:u.pointsToConnect.map(g=>({...g}))})),r=[],s=new Set;for(const u of n){const g=i[u.connectionIndex];if(!g)throw new Error(`FanoutSolver: output connection index ${u.connectionIndex} is missing`);const h=qN(u);if(g.pointsToConnect[u.sourcePointIndex]={x:u.exitPoint.x,y:u.exitPoint.y,layer:u.targetLayer,pointId:u.termination.type==="plane"?h.planeExitPointId:h.boundaryExitPointId},u.termination.type==="plane"&&s.add(u.connectionName),u.via){const d=jPe(u,o,u.via,0);d&&r.push(d)}for(const[d,p]of(u.additionalVias??[]).entries()){const m=jPe(u,o,p,d+1);m&&r.push(m)}if(u.planeEndpointVia){const d=jPe(u,o,u.planeEndpointVia,"endpoint");d&&r.push(d)}}const a=n.flatMap(u=>[u.trace,...u.planeEndpointTrace?[u.planeEndpointTrace]:[]]),A=a.flatMap(u=>u.route.filter(g=>"x"in g&&"y"in g)),c=Math.max(e.defaultObstacleMargin??0,e.minTraceWidth),l=A.length===0?{...e.bounds}:{minX:Math.min(e.bounds.minX,...A.map(u=>u.x-c)),maxX:Math.max(e.bounds.maxX,...A.map(u=>u.x+c)),minY:Math.min(e.bounds.minY,...A.map(u=>u.y-c)),maxY:Math.max(e.bounds.maxY,...A.map(u=>u.y+c))};return{...e,fanoutPlaneConnectivity:n.flatMap(u=>u.termination.type==="plane"?[{connectionName:u.connectionName,layer:u.termination.layer}]:[]),bounds:l,connections:i.filter(u=>!s.has(u.name)),buses:e.buses?.map(u=>({...u,connectionNames:u.connectionNames.filter(g=>!s.has(g))})).filter(u=>u.connectionNames.length>0),obstacles:[...e.obstacles.map(u=>({...u,center:{...u.center},layers:[...u.layers],connectedTo:[...u.connectedTo]})),...r],traces:[...(e.traces??[]).map(u=>({...u,route:u.route.map(g=>({...g}))})),...a]}}var GSo=5,YSo=40,USo=64,MNt=10,KSo=8;function DNt(t){const e=t.length,n=t.reduce((o,i)=>o+i,0);return e>=GSo&&e<=YSo&&n<=USo||e===4&&new Set(t).size>1}function VSo({boundaryBusConnectionCounts:t,planeBusCount:e}){const n=t.length;return n<=MNt-1&&e>=KSo?"mixed_with_planes":n>=MNt&&e===0&&DNt(t)?"large_boundary_only":null}function uue(t){if(!t.exitEdge)throw new Error(`Cannot order boundary bus ${t.busId} without an exit edge`);const e=e6(t.exitEdge);return t.connections.reduce((n,o)=>n+tR({bus:t,connection:o,boundaryDirection:e}),0)/t.connections.length}function zSo({busesInRoutingOrder:t,busLayerAssignments:e,routingMode:n}){if(n!=="large_boundary_only")return[...t];const o=t.filter(s=>s.connections.length===1);if(new Set(o.map(s=>s.exitEdge)).size!==1)return[...t];const i=[...t.filter(s=>s.connections.length>=8).toSorted((s,a)=>uue(a)-uue(s)),...t.filter(s=>s.connections.length>1&&s.connections.length<8)],r=[];for(const s of o){const a=e[s.busId];if(!a)throw new Error(`Cannot order boundary bus ${s.busId} without a layer`);let A=r.find(c=>c.targetLayer===a);A||(A={targetLayer:a,buses:[]},r.push(A)),A.buses.push(s)}return[...i,...r.flatMap(s=>s.buses.toSorted((a,A)=>uue(A)-uue(a)))]}var gue=1e-7;function r$(t,e){const n=t.sourceObstacle,o={...n,width:n.width-2e-8,height:n.height-2e-8},i=[];let r=!1,s=!1,a=!1;for(const[A,c]of[...t.segments,...t.planeEndpointSegments??[]].entries()){if(!n.layers.includes(c.layer))continue;const l=Tl(c,n),u=c.width/2;r&&o.width>0&&o.height>0&&Tl(c,o)<1e-10&&i.push({segmentIndex:A,kind:"outline"}),s&&l<u-gue&&i.push({segmentIndex:A,kind:"copper"}),a&&l<u+e-gue&&i.push({segmentIndex:A,kind:"clearance"}),IO(c.end,n,1e-9)||(r=!0);const g=wx(c.end,n);g>u+gue&&(s=!0),g>=u+e-gue&&(a=!0)}return i}function*JSo(t,e){const n=t.sourceEscapeSegmentCount??1,o=t.segments.slice(0,n),i=o.slice(0,64).findIndex((s,a)=>!bO(t,t.segments,e,new Set([a])));if(i<0)return;const r=o[i].width+e;for(let s=i;s>=Math.max(0,i-3);s--){let a=0;for(let A=s;A<Math.min(o.length,i+8);A++){const c=o[A];if(c.layer!==t.sourceLayer||A>s&&tn(o[A-1].end,c.start)>1e-7||(a+=tn(c.start,c.end),a>4*r+1e-7))break;if(A<=i)continue;const l=o[s].start,u=c.end,g=u.x-l.x,h=u.y-l.y,d=Math.min(Math.abs(g),Math.abs(h));for(const p of[{x:l.x+Math.sign(g)*d,y:l.y+Math.sign(h)*d},{x:u.x-Math.sign(g)*d,y:u.y-Math.sign(h)*d}])tn(l,p)+tn(p,u)>=a-1e-7||(yield[o[0].start,...o.slice(0,s).map(m=>m.end),p,u,...o.slice(A+1).map(m=>m.end)].filter((m,_,f)=>_===0||tn(m,f[_-1])>1e-7))}}}var fw=1e-7,WSo=64;function jSo(t,e,n){const o=t,i=(o.ccwRotationDegrees??0)/90;if(t.type!=="rect"||o.shape==="circle"||Math.abs(i-Math.round(i))>fw||Math.abs(t.width-t.height)<fw)return null;const r=Math.abs(Math.round(i))%2===1,s=r?t.height:t.width,a=r?t.width:t.height,A=s>a?"x":"y",c=(A==="x"?s:a)/2;return[-1,1].map(l=>({...e,[A]:t.center[A]+l*(c+n)}))}function $So(t){const{inputSrj:e,preparedBuses:n,layerNames:o,traceWidth:i,clearance:r}=t,s=n[0];if(!s)return t.plans.length?null:[];const a=s.sharedBoundary;if(n.some(g=>["minX","maxX","minY","maxY"].some(h=>g.sharedBoundary[h]!==a[h])))return null;const A=new Map(n.map(g=>[g.busId,g]));if(new Set(t.plans.map(g=>g.connectionIndex)).size!==t.plans.length)return null;let c=[...t.plans];const l=Z7(e,!1),u=Z0e({srj:e,sharedBoundary:a,clearance:r,allowBlindAndBuriedVias:!1,allowSameNetMerges:!1});for(const[g,h]of c.entries()){if(!r$(h,r).length)continue;const p=A.get(h.busId)?.connections.find(R=>R.connectionIndex===h.connectionIndex),m=h.sourceEscapeSegmentCount??1,_=h.segments.slice(0,m),f=h.trace.route.findIndex(R=>R.route_type==="via"),I=jSo(h.sourceObstacle,h.sourcePoint,i/2+r+1e-6);if(!p||p.sourceObstacle!==h.sourceObstacle||!h.via||f<1||!I||!_.length||_.some(R=>R.layer!==h.sourceLayer||R.width!==i)||tn(_[0].start,h.sourcePoint)>fw||tn(_.at(-1).end,h.via.center)>fw||!o.includes(h.sourceLayer))return null;const C=c.filter((R,F)=>F!==g),y=new qj([...h.segments.slice(m),...h.planeEndpointSegments??[],...C.flatMap(R=>[...R.segments,...R.planeEndpointSegments??[]]),...l.flatMap(R=>R.segments)]),x=[...h.additionalVias??[],...h.planeEndpointVia?[h.planeEndpointVia]:[],...C.flatMap(R=>[R.via,...R.additionalVias??[],R.planeEndpointVia].filter(F=>!!F)),...l.flatMap(R=>R.vias)],E=[...new Set([...Array.from({length:Math.min(_.length,WSo-1)},(R,F)=>F+1),_.length])],B=[],S=new Set;for(const R of E){const F=_[R-1].end;for(const O of[null,...I]){const U=O??h.sourcePoint,Y=F.x-U.x,W=F.y-U.y,te=Math.min(Math.abs(Y),Math.abs(W));for(const j of[{x:U.x+Math.sign(Y)*te,y:U.y+Math.sign(W)*te},{x:F.x-Math.sign(Y)*te,y:F.y-Math.sign(W)*te}]){const J=[h.sourcePoint,...O?[O]:[],j,F].filter((ne,le,ge)=>le===0||tn(ne,ge[le-1])>fw),oe=JSON.stringify([R,J]);if(S.has(oe))continue;S.add(oe);const ie=J.slice(1).reduce((ne,le,ge)=>ne+tn(J[ge],le),0)+_.slice(R).reduce((ne,le)=>ne+tn(le.start,le.end),0);B.push({anchor:R,points:J,length:ie})}}}B.sort((R,F)=>R.length-F.length||R.anchor-F.anchor);const Q=R=>{const F=eR({points:R.map(W=>({...W,z:o.indexOf(h.sourceLayer)})),chamfer:i/2,segmentIsClear:(W,te)=>{if([W,te].some(J=>J.x<a.minX||J.x>a.maxX||J.y<a.minY||J.y>a.maxY))return!1;const j={start:W,end:te,width:i,layer:h.sourceLayer};return e.obstacles.every(J=>J===h.sourceObstacle||!J.layers.includes(j.layer)||Tl(j,J)>=i/2+r-fw||jj({inputSrj:e,segment:j,bodyObstacle:J,connectionName:h.connectionName}))&&y.querySegment(j,r).every(J=>Zm(j,J,r))&&x.every(J=>!J.spanLayers.includes(j.layer)||Cr(J.center,W,te)>=(i+J.diameter)/2+r-fw)}});if(!F)return null;const O=F.slice(1).map((W,te)=>({start:{x:F[te].x,y:F[te].y},end:{x:W.x,y:W.y},width:i,layer:h.sourceLayer})).filter(W=>tn(W.start,W.end)>fw),U=[...O,...h.segments.slice(m)],Y=bB(h,U,!0);return Y?(Y.sourceEscapeSegmentCount=O.length,Y.trace={...h.trace,route:[h.trace.route[0],...O.map(W=>({route_type:"wire",...W.end,width:W.width,layer:W.layer})),...h.trace.route.slice(f)]},r$(Y,r).length||!u([...C,Y])?null:Y):null},w=R=>bO(R,R.segments,r,new Set(Array.from({length:R.sourceEscapeSegmentCount??1},(F,O)=>O)));let M=null,k=null;for(const R of B){const F=Q([...R.points,..._.slice(R.anchor).map(O=>O.end)]);if(F){if(!w(F)){k??=F;continue}M=F;break}}if(!M&&k)for(const R of JSo(k,r)){const F=Q(R);if(F&&w(F)){M=F;break}}if(!M)return null;c[g]=M}return c.some(g=>r$(g,r).length)||!u(c)?null:qu({inputSrj:e,routedSrj:{...e,traces:[...e.traces??[],...c.flatMap(g=>[g.trace,...g.planeEndpointTrace?[g.planeEndpointTrace]:[]])]},clearance:r,allowBlindAndBuriedVias:!1}).valid?c:null}var qSo=new Set(["left","right","top","bottom","top-left","top-right","bottom-left","bottom-right"]),XSo=new Set(["left","right","top","bottom"]),ZSo={top_left:{direction:"up",preferredExit:"top-left",exitEdge:"top"},top_middle:{direction:"up",preferredExit:"top",exitEdge:"top"},top_right:{direction:"up",preferredExit:"top-right",exitEdge:"top"},right_top:{direction:"right",preferredExit:"top-right",exitEdge:"right"},right_middle:{direction:"right",preferredExit:"right",exitEdge:"right"},right_bottom:{direction:"right",preferredExit:"bottom-right",exitEdge:"right"},bottom_right:{direction:"down",preferredExit:"bottom-right",exitEdge:"bottom"},bottom_middle:{direction:"down",preferredExit:"bottom",exitEdge:"bottom"},bottom_left:{direction:"down",preferredExit:"bottom-left",exitEdge:"bottom"},left_bottom:{direction:"left",preferredExit:"bottom-left",exitEdge:"left"},left_middle:{direction:"left",preferredExit:"left",exitEdge:"left"},left_top:{direction:"left",preferredExit:"top-left",exitEdge:"left"},top:{direction:"up",preferredExit:"top",exitEdge:"top"},right:{direction:"right",preferredExit:"right",exitEdge:"right"},bottom:{direction:"down",preferredExit:"bottom",exitEdge:"bottom"},left:{direction:"left",preferredExit:"left",exitEdge:"left"}};function NNt(t){const e=[...t].sort((o,i)=>o-i),n=[];for(const o of e)(n.length===0||Math.abs(n[n.length-1]-o)>1e-6)&&n.push(o);return n}function RNt(t){let e=Number.POSITIVE_INFINITY;for(let n=1;n<t.length;n++){const o=t[n]-t[n-1];o>1e-6&&(e=Math.min(e,o))}return e}function TNt(t,e){const n=e==="x"?"y":"x";let o=Number.POSITIVE_INFINITY;for(let i=0;i<t.length;i++){const r=t[i];for(let s=i+1;s<t.length;s++){const a=t[s];if(Math.abs(r.center[n]-a.center[n])>1e-6)continue;const A=Math.abs(r.center[e]-a.center[e]);A>1e-6&&(o=Math.min(o,A))}}return o}function eQo(t){return{minX:Math.min(...t.map(e=>e.center.x-e.width/2)),maxX:Math.max(...t.map(e=>e.center.x+e.width/2)),minY:Math.min(...t.map(e=>e.center.y-e.height/2)),maxY:Math.max(...t.map(e=>e.center.y+e.height/2))}}function kNt(t,e){const n=e.componentBounds?.[t.componentId];if(!n){const i=t.pitchX*2.25,r=t.pitchY*2.25;return{minX:t.bounds.minX-i,maxX:t.bounds.maxX+i,minY:t.bounds.minY-r,maxY:t.bounds.maxY+r}}if([n.minX,n.maxX,n.minY,n.maxY].some(i=>!Number.isFinite(i))||n.minX>=n.maxX||n.minY>=n.maxY)throw new Error(`FanoutSolver: componentBounds for "${t.componentId}" must contain finite, increasing bounds`);if(n.minX>t.bounds.minX+1e-6||n.maxX<t.bounds.maxX-1e-6||n.minY>t.bounds.minY+1e-6||n.maxY<t.bounds.maxY-1e-6)throw new Error(`FanoutSolver: componentBounds for "${t.componentId}" must contain every component pad`);return{...n}}function FNt(t,e){if([t.minX,t.maxX,t.minY,t.maxY].some(o=>!Number.isFinite(o))||t.minX>=t.maxX||t.minY>=t.maxY)throw new Error("FanoutSolver: sharedBoundary must contain finite, increasing bounds");for(const o of e)if(t.minX>o.bounds.minX+1e-6||t.maxX<o.bounds.maxX-1e-6||t.minY>o.bounds.minY+1e-6||t.maxY<o.bounds.maxY-1e-6)throw new Error(`FanoutSolver: sharedBoundary must contain every pad of component "${o.componentId}"`);return{...t}}function tQo(t,e){if(e.sharedBoundary)return FNt(e.sharedBoundary,t);const n=t.map(r=>kNt(r,e)),i=Math.max(...t.flatMap(r=>[r.pitchX,r.pitchY]))*2.25;return FNt({minX:Math.min(...n.map(r=>r.minX))-i,maxX:Math.max(...n.map(r=>r.maxX))+i,minY:Math.min(...n.map(r=>r.minY))-i,maxY:Math.max(...n.map(r=>r.maxY))+i},t)}function nQo(t){const e=new Map;for(const o of t){if(!o.componentId||o.isCopperPour)continue;const i=e.get(o.componentId)??[];i.push(o),e.set(o.componentId,i)}const n=[];for(const[o,i]of e){const r=NNt(i.map(m=>m.center.x)),s=NNt(i.map(m=>m.center.y)),a=TNt(i,"x"),A=TNt(i,"y"),c=RNt(r),l=RNt(s),u=Math.min(...[a,A,c,l].filter(Number.isFinite)),g=Math.max(...i.flatMap(m=>[m.width,m.height])),h=Number.isFinite(u)?u:g,d=Number.isFinite(a)?a:Number.isFinite(c)?c:h,p=Number.isFinite(A)?A:Number.isFinite(l)?l:h;n.push({componentId:o,obstacles:i,xCoordinates:r,yCoordinates:s,pitchX:d,pitchY:p,bounds:eQo(i)})}return n}function LNt(t){return"layer"in t?[t.layer]:t.layers}function HNt(t){const{point:e,connection:n,componentGrids:o}=t,i=LNt(e),r=[];for(const s of o){const a=s.obstacles.filter(A=>A.layers.some(c=>i.includes(c))).filter(A=>IO(e,A,1e-5)).sort((A,c)=>{const l=A.connectedTo.includes(n.name)||A.connectedTo.includes(e.pointId??"")||A.connectedTo.includes(e.pcb_port_id??""),u=c.connectedTo.includes(n.name)||c.connectedTo.includes(e.pointId??"")||c.connectedTo.includes(e.pcb_port_id??"");return l!==u?l?-1:1:A.width*A.height-c.width*c.height});a[0]&&r.push({grid:s,obstacle:a[0]})}return r}function oQo(t){for(const n of t.pointsToConnect)if("layers"in n&&n.busId)return n.busId;return/^BUS[_:-]([^_:-]+)(?:[_:-]\d+)?$/i.exec(t.name)?.[1]??null}function s$(t,e){if(e!==void 0){if(!qSo.has(e))throw new Error(`FanoutSolver: bus "${t}" has invalid preferredExit "${e}"`);return e}}function iQo(t,e){if(e!==void 0){if(!XSo.has(e))throw new Error(`FanoutSolver: bus "${t}" has invalid exitEdge "${e}"`);return e}}function rQo(t,e){if(e!==void 0)try{return XDt(e)}catch{throw new Error(`FanoutSolver: bus "${t}" has invalid exitPosition "${e}"`)}}function $Pe(t){const{busId:e,exitPosition:n,fieldName:o,expected:i,actual:r,sourceName:s}=t;if(!(r===void 0||r===i))throw new Error(`FanoutSolver: bus "${e}" exitPosition "${n}" conflicts with ${s} ${o} "${r}"`)}function sQo(t){const{busId:e,requestedBus:n,options:o}=t,i=n.exitPosition,r=rQo(e,i),s=s$(e,n.preferredExit),a=s$(e,o.busExitPreferences?.[e]),A=iQo(e,n.exitEdge);if(r&&i){for(const[u,g]of[[n.direction,"bus"],[o.busDirections?.[e],"busDirections"]])$Pe({busId:e,exitPosition:i,fieldName:"direction",expected:r.direction,actual:u,sourceName:g});for(const[u,g]of[[s,"bus"],[a,"busExitPreferences"]])$Pe({busId:e,exitPosition:i,fieldName:"preferredExit",expected:r.preferredExit,actual:u,sourceName:g});return $Pe({busId:e,exitPosition:i,fieldName:"exitEdge",expected:r.exitEdge,actual:A,sourceName:"bus"}),{exitPosition:i,...r.direction?{direction:r.direction}:{},...r.preferredExit?{preferredExit:r.preferredExit}:{},...r.exitEdge?{exitEdge:r.exitEdge}:{}}}const c=o.busDirections?.[e]??n.direction??o.defaultDirection,l=s$(e,a??s??o.defaultPreferredExit);return{...c?{direction:c}:{},...l?{preferredExit:l}:{},...A?{exitEdge:A}:{}}}function aQo(t,e){if(e!==void 0){if(e.length===0)throw new Error(`FanoutSolver: bus "${t}" must allow at least one layer`);for(const n of e)if(typeof n!="string"||n.length===0)throw new Error(`FanoutSolver: bus "${t}" has an invalid allowed layer`);return[...new Set(e)]}}function AQo(t,e){if(e!==void 0){if(!Number.isFinite(e)||e<0)throw new Error(`FanoutSolver: bus "${t}" maxLengthSkew must be a finite non-negative number`);return e}}function ONt(t){if(t===void 0)return;if(t.length===0)throw new Error("FanoutSolver: availableCornersAndSides must contain at least one boundary region");const e=[],n=new Set;for(const o of t){const i=ZSo[o];if(!i)throw new Error(`FanoutSolver: invalid availableCornersAndSides value "${o}"`);const r=`${i.exitEdge}:${i.direction}:${i.preferredExit}`;n.has(r)||(n.add(r),e.push(i))}return e}function cQo(t,e){if(e===void 0||e.type==="boundary")return{type:"boundary"};if(e.type!=="plane"||typeof e.layer!="string"||e.layer.length===0)throw new Error(`FanoutSolver: bus "${t}" has an invalid termination target`);return{type:"plane",layer:e.layer}}function lQo(t,e){const n=e.buses??t.buses,o=new Map,i=new Set,r=new Set(t.connections.map(s=>s.name));for(const s of n??[]){if(o.has(s.busId))throw new Error(`FanoutSolver: duplicate bus id "${s.busId}"`);for(const u of s.connectionNames){if(!r.has(u))throw new Error(`FanoutSolver: bus "${s.busId}" references unknown connection "${u}"`);if(i.has(u))throw new Error(`FanoutSolver: connection "${u}" belongs to more than one bus`);i.add(u)}const a=cQo(s.busId,s.termination),A=sQo({busId:s.busId,requestedBus:s,options:e}),c=aQo(s.busId,s.allowedLayers),l=AQo(s.busId,s.maxLengthSkew);if(a.type==="plane"&&l!==void 0)throw new Error(`FanoutSolver: plane-terminated bus "${s.busId}" cannot specify maxLengthSkew`);if(a.type==="plane"&&A.preferredExit!==void 0)throw new Error(`FanoutSolver: plane-terminated bus "${s.busId}" cannot also specify preferredExit`);o.set(s.busId,{...s,sourceComponentId:s.sourceComponentId??e.sourceComponentId,...A,...c===void 0?{}:{allowedLayers:c},...l===void 0?{}:{maxLengthSkew:l},termination:a})}for(const s of t.connections){if(i.has(s.name))continue;const a=oQo(s);if(a){const A=o.get(a);A?o.set(a,{...A,connectionNames:[...A.connectionNames,s.name]}):o.set(a,{busId:a,connectionNames:[s.name],direction:e.busDirections?.[a]??e.defaultDirection,sourceComponentId:e.sourceComponentId,preferredExit:s$(a,e.busExitPreferences?.[a]??e.defaultPreferredExit),termination:{type:"boundary"}})}else{const A=`connection:${s.name}`;o.set(A,{busId:A,connectionNames:[s.name],sourceComponentId:e.sourceComponentId,direction:e.busDirections?.[A]??e.defaultDirection,preferredExit:s$(A,e.busExitPreferences?.[A]??e.defaultPreferredExit),termination:{type:"boundary"}})}}return[...o.values()]}function uQo(t){const{busSpec:e,connections:n,componentGrids:o}=t,i=new Map;for(const c of n){const l=new Set;for(const u of c.pointsToConnect)for(const g of HNt({point:u,connection:c,componentGrids:o}))l.add(g.grid.componentId);for(const u of l)i.set(u,(i.get(u)??0)+1)}const r=[...o].sort((c,l)=>{const u=(i.get(l.componentId)??0)-(i.get(c.componentId)??0);return u!==0?u:l.obstacles.length-c.obstacles.length})[0],s=e.sourceComponentId?o.find(c=>c.componentId===e.sourceComponentId):void 0;if(e.sourceComponentId&&!s)throw new Error(`FanoutSolver: source component "${e.sourceComponentId}" for bus "${e.busId}" was not found`);const a=s??r,A=a?i.get(a.componentId)??0:0;if(!a||A!==n.length)throw new Error(e.sourceComponentId?`FanoutSolver: source component "${e.sourceComponentId}" is not an endpoint on every connection in bus "${e.busId}"`:`FanoutSolver: bus "${e.busId}" does not have one component endpoint on every connection`);return a}function gQo(t,e,n,o){const r=e.pointsToConnect.filter((s,a)=>a!==n).sort((s,a)=>tn(t,a)-tn(t,s))[0];if(!r&&o.type==="plane")return t;if(!r)throw new Error(`FanoutSolver: connection "${e.name}" has no target beyond its BGA pad`);return r}function dQo(t){const{connection:e,connectionIndex:n,sourceGrid:o,componentGrids:i,termination:r,exitTargetPoint:s}=t;for(let a=0;a<e.pointsToConnect.length;a++){const A=e.pointsToConnect[a],c=HNt({point:A,connection:e,componentGrids:i}).find(g=>g.grid.componentId===o.componentId);if(!c)continue;const l=LNt(A).find(g=>c.obstacle.layers.includes(g));if(!l)throw new Error(`FanoutSolver: connection "${e.name}" has no source layer shared with its BGA pad`);const u=gQo(A,e,a,r);return{connection:e,connectionIndex:n,sourcePoint:A,sourcePointIndex:a,sourceLayer:l,sourceObstacle:c.obstacle,targetPoint:u,exitTargetPoint:s??{x:u.x,y:u.y},hasExplicitLayeredExitTarget:s?.layer!==void 0}}throw new Error(`FanoutSolver: connection "${e.name}" does not touch component "${o.componentId}"`)}function qPe(t,e){let n=0,o=0;for(const i of e){const r=i.exitTargetPoint??i.targetPoint;n+=r.x-i.sourcePoint.x,o+=r.y-i.sourcePoint.y}if(Math.abs(n)<1e-9&&Math.abs(o)<1e-9)throw new Error(`FanoutSolver: cannot infer an escape direction for bus "${t}"`);return Math.abs(n)>=Math.abs(o)?n>=0?"right":"left":o>=0?"up":"down"}function hQo(t){switch(t){case"left":return["left"];case"right":return["right"];case"top":return["up"];case"bottom":return["down"];case"top-left":return["up","left"];case"top-right":return["up","right"];case"bottom-left":return["down","left"];case"bottom-right":return["down","right"]}}function GNt(t){return{x:t.reduce((e,n)=>e+n.sourcePoint.x,0)/t.length,y:t.reduce((e,n)=>e+n.sourcePoint.y,0)/t.length}}function due(t,e,n){switch(e){case"left":return t.x-n.minX;case"right":return n.maxX-t.x;case"up":return n.maxY-t.y;case"down":return t.y-n.minY}}function hue(t,e){return t.direction==="up"||t.direction==="down"?t.preferredExit.endsWith("left")?e.minX:t.preferredExit.endsWith("right")?e.maxX:(e.minX+e.maxX)/2:t.preferredExit.startsWith("top")?e.maxY:t.preferredExit.startsWith("bottom")?e.minY:(e.minY+e.maxY)/2}function YNt(t,e){return e==="up"||e==="down"?t.x:t.y}function pQo(t,e){try{return qPe(t,e)}catch{return}}function mQo(t){const{busId:e,explicitDirection:n,preferredExit:o,connections:i,sharedBoundary:r,availableRegions:s}=t,a=s.filter(g=>(n===void 0||g.direction===n)&&(o===void 0||g.preferredExit===o));if(a.length===0)throw new Error(`FanoutSolver: bus "${e}" cannot use its requested exit with availableCornersAndSides`);const A=n?void 0:pQo(e,i),c=A?a.filter(g=>g.direction===A):[],l=c.length>0?c:a,u=GNt(i);return[...l].toSorted((g,h)=>due(u,g.direction,r)-due(u,h.direction,r)||Math.abs(YNt(u,g.direction)-hue(g,r))-Math.abs(YNt(u,h.direction)-hue(h,r))||g.preferredExit.localeCompare(h.preferredExit))[0]}function _Qo(t){const{busId:e,exitEdge:n,preferredExit:o,availableRegions:i}=t,r=Ds(n,o);if(!i.some(a=>a.exitEdge===n&&Ds(a.exitEdge,a.preferredExit)===r))throw new Error(`FanoutSolver: bus "${e}" cannot use its requested exit with availableCornersAndSides`)}function fQo(t){const{busId:e,explicitDirection:n,preferredExit:o,connections:i,sharedBoundary:r,availableRegions:s}=t;if(s)return mQo({busId:e,explicitDirection:n,preferredExit:o,connections:i,sharedBoundary:r,availableRegions:s});if(!o)return{direction:n??qPe(e,i)};const a=hQo(o);if(n){if(!a.includes(n))throw new Error(`FanoutSolver: bus "${e}" direction "${n}" is incompatible with preferredExit "${o}"`);return{direction:n,preferredExit:o}}if(a.length===1)return{direction:a[0],preferredExit:o};let A;try{A=qPe(e,i)}catch{A=void 0}if(A&&a.includes(A))return{direction:A,preferredExit:o};const c=GNt(i);return{direction:a.toSorted((l,u)=>due(c,l,r)-due(c,u,r)||l.localeCompare(u))[0],preferredExit:o}}function IQo(t,e){const n=nQo(t.obstacles);if(n.length===0&&t.connections.length>0)throw new Error("FanoutSolver: no componentId-tagged pad footprint was found");const o=new Map(t.connections.map((l,u)=>[l.name,u])),i=lQo(t,e).map(l=>{for(const[d,p]of Object.entries(l.connectionExitTargets??{})){if(!l.connectionNames.includes(d))throw new Error(`FanoutSolver: connectionExitTargets contains connection "${d}" outside bus "${l.busId}"`);if(!Number.isFinite(p.x)||!Number.isFinite(p.y))throw new Error(`FanoutSolver: connectionExitTargets for connection "${d}" must contain finite x and y coordinates`)}const u=l.connectionNames.map(d=>{const p=o.get(d);if(p===void 0)throw new Error(`FanoutSolver: connection "${d}" is missing from the input`);return t.connections[p]}),g=uQo({busSpec:l,connections:u,componentGrids:n}),h=u.map(d=>dQo({connection:d,connectionIndex:o.get(d.name),sourceGrid:g,componentGrids:n,termination:l.termination??{type:"boundary"},exitTargetPoint:l.connectionExitTargets?.[d.name]}));return{busSpec:l,sourceGrid:g,preparedConnections:h}}),r=[...new Map(i.map(({sourceGrid:l})=>[l.componentId,l])).values()],s=tQo(r,e),a=ONt(e.availableCornersAndSides),A=[];for(const{busSpec:l,sourceGrid:u,preparedConnections:g}of i){if(l.exitEdge&&!l.preferredExit)throw new Error(`FanoutSolver: bus "${l.busId}" exitEdge requires preferredExit`);if(l.exitEdge&&l.preferredExit&&!ZDt(l.preferredExit,l.exitEdge))throw new Error(`FanoutSolver: bus "${l.busId}" exitEdge "${l.exitEdge}" is incompatible with preferredExit "${l.preferredExit}"`);const h=fQo({busId:l.busId,explicitDirection:l.direction??e.busDirections?.[l.busId],preferredExit:l.preferredExit,connections:g,sharedBoundary:s,availableRegions:l.termination?.type==="plane"||l.exitEdge?void 0:a});l.termination?.type!=="plane"&&l.exitEdge&&h.preferredExit&&a&&_Qo({busId:l.busId,exitEdge:l.exitEdge,preferredExit:h.preferredExit,availableRegions:a}),A.push({busId:l.busId,...l.maxLengthSkew===void 0?{}:{maxLengthSkew:l.maxLengthSkew},direction:h.direction,preferredExit:h.preferredExit,...l.exitEdge?{exitEdge:l.exitEdge}:{},cornerBandConnectionCount:0,allowedLayers:l.allowedLayers,termination:l.termination??{type:"boundary"},connections:g,componentId:u.componentId,componentObstacles:u.obstacles,componentBounds:kNt(u,e),sharedBoundary:s,xCoordinates:[...u.xCoordinates],yCoordinates:[...u.yCoordinates],pitchX:u.pitchX,pitchY:u.pitchY})}const c=new Map;for(const l of A){const u=Ds(l.exitEdge,l.preferredExit);if(!l.exitEdge||!u)continue;const g=`${l.exitEdge}:${u}`;c.set(g,(c.get(g)??0)+l.connections.length)}for(const l of A){const u=Ds(l.exitEdge,l.preferredExit);!l.exitEdge||!u||(l.cornerBandConnectionCount=c.get(`${l.exitEdge}:${u}`)??l.connections.length)}return A}var Iw=1e-9,UNt=Math.PI*2;function CQo(t){const{buses:e,rules:n}=t,o=e.find(M=>M.busId===t.busId);if(!o||o.termination.type!=="boundary"||!o.exitEdge||o.connections.length<3)return null;const i=t.maximumOrderingStates??1e4,r=t.maximumCompleteAssignments??16;for(const[M,k]of Object.entries({maximumOrderingStates:i,maximumCompleteAssignments:r}))if(!Number.isSafeInteger(k)||k<1)throw new Error(`FanoutSolver: ${M} must be a positive safe integer`);const s={x:(o.componentBounds.minX+o.componentBounds.maxX)/2,y:(o.componentBounds.minY+o.componentBounds.maxY)/2},a=M=>Math.atan2(M.y-s.y,M.x-s.x),A=M=>{const k=M.exitTargetPoint??M.targetPoint;return o.exitEdge==="right"?k.y:o.exitEdge==="top"?-k.x:o.exitEdge==="left"?-k.y:k.x},c=o.connections.toSorted((M,k)=>A(M)-A(k)||M.connectionIndex-k.connectionIndex),l=[];for(const M of c){if(tn(M.sourcePoint,s)<Iw)return null;let k=a(M.sourcePoint);for(;k<(l.at(-1)??k)-Iw;)k+=UNt;l.push(k)}if(l.at(-1)-l[0]>=UNt-Iw)return null;const u=new Map(e.flatMap(M=>M.connections.map(k=>[k.connectionIndex,k]))),g=new Map(c.map((M,k)=>[M.connectionIndex,k])),h=new Map,d=new Map;for(const M of u.values())d.set(M.connectionIndex,[]);for(const M of pw(e,n)){const k=u.get(M.connectionIndex),R=`${M.point.x.toFixed(9)},${M.point.y.toFixed(9)}`;h.has(R)||h.set(R,h.size);const F=g.get(M.connectionIndex),O=a(k.sourcePoint),U=F===void 0?a(M.point):l[F]+Math.atan2(Math.sin(a(M.point)-O),Math.cos(a(M.point)-O));d.get(M.connectionIndex).push({...M,angle:U,siteIndex:h.get(R),sourceSegment:{start:k.sourcePoint,end:M.point,layer:k.sourceLayer,width:n.traceWidth}})}const p=[...d.entries()].map(([M,k])=>({connectionIndex:M,candidates:k}));if(p.some(M=>M.candidates.length===0))return null;const m=c.map((M,k)=>d.get(M.connectionIndex).toSorted((R,F)=>Math.abs(R.angle-l[k])-Math.abs(F.angle-l[k])||tn(F.point,s)-tn(R.point,s))),_=n.viaHoleDiameter?n.viaHoleDiameter+(n.holeToHoleClearance??n.clearance):0,f=n.viaDiameter/2+n.traceWidth/2+n.clearance,I=(M,k)=>{const R=n.canShareCopper?.(M.connectionIndex,k.connectionIndex)??!1,F=R?_:Math.max(_,n.viaDiameter+n.clearance);return tn(M.point,k.point)<F-Iw?!1:R?!0:Cr(M.point,k.sourceSegment.start,k.sourceSegment.end)>=f-Iw&&Cr(k.point,M.sourceSegment.start,M.sourceSegment.end)>=f-Iw&&Zm(M.sourceSegment,k.sourceSegment,n.clearance)},C=new Map;for(const M of m)for(const k of M){const R=new Set;for(const F of p)for(const O of F.candidates)k.connectionIndex!==O.connectionIndex&&!I(k,O)&&R.add(O);C.set(k,R)}const y=[],x=_>Iw||!n.canShareCopper,E=()=>{if(!x)return!0;const M=new Map(y.map(O=>[O.connectionIndex,O.siteIndex])),k=p.map(O=>O.candidates.filter(U=>(!M.has(U.connectionIndex)||M.get(U.connectionIndex)===U.siteIndex)&&y.every(Y=>!C.get(Y).has(U))).map(U=>U.siteIndex)).sort((O,U)=>O.length-U.length);if(k.some(O=>O.length===0))return!1;const R=new Int32Array(h.size).fill(-1),F=(O,U)=>{for(const Y of k[O])if(!U[Y]&&(U[Y]=1,R[Y]===-1||F(R[Y],U)))return R[Y]=O,!0;return!1};return k.every((O,U)=>F(U,new Uint8Array(h.size)))};let B=0,S=0,Q=null;const w=M=>{if(++B>i)return!1;if(M===m.length){if(++S>r)return!1;const k=new Map(n.fixedViaPointsByConnectionIndex);for(const R of y)k.set(R.connectionIndex,R.point);return Q=pd(e,{...n,fixedViaPointsByConnectionIndex:k}),Q!==null}for(const k of m[M])if(!(k.angle<(y.at(-1)?.angle??-1/0)-Iw||y.some(R=>C.get(R).has(k)))){if(y.push(k),E()&&w(M+1))return!0;if(y.pop(),B>i||S>=r)break}return!1};return w(0),Q}var ah=1e-9,Cw=1,a$=globalThis.process?.env?.FANOUT_FLOW_DEBUG==="1";function yQo(t){const{boundary:e,sourcePoints:n,traceWidth:o,update:i}=t,r=e.maxX-e.minX,s=e.maxY-e.minY,a=Math.max(Math.min(r,s)*.02,.2),A=i.grid?Math.max(1,Math.ceil(i.grid.points.length/1200)):1,c=i.grid?i.grid.points.flatMap((u,g)=>g%A===0?[{point:u,index:g}]:[]):[],l=i.grid?.processedNodeCount??i.grid?.points.length??0;return{title:`Adaptive exits: ${i.phase}`,rects:[{center:{x:(e.minX+e.maxX)/2,y:(e.minY+e.maxY)/2},width:r,height:s,fill:"rgba(0, 0, 0, 0)",stroke:"rgba(14, 165, 233, 0.9)",label:"adaptive flow grid boundary"}],points:[...c.map(({point:u,index:g})=>{const h=g<l;return{...u,color:h?i.grid.obstacleFreeNodes[g]?"rgba(34, 197, 94, 0.38)":"rgba(100, 116, 139, 0.28)":"rgba(148, 163, 184, 0.18)",label:h?i.grid.obstacleFreeNodes[g]?"available flow node":"blocked flow node":"unprocessed flow node"}}),...n.map(u=>({...u,color:"#f97316",label:"adaptive route source"})),...(i.candidatePoints??[]).map(u=>({...u,color:"#06b6d4",label:"selected terminal node"}))],lines:(i.segments??[]).map(u=>({points:[u.start,u.end],strokeColor:"rgba(250, 204, 21, 0.9)",strokeWidth:Math.max(o,a*.4),label:"current adaptive route"})),texts:[{x:e.minX,y:e.maxY+a*2,text:`${i.phase}${i.direction?` · ${i.direction}`:""}${i.processed!==void 0&&i.total!==void 0?` · ${i.processed}/${i.total}`:""}`,color:"#0f172a",fontSize:a*1.5,anchorSide:"bottom_left"}]}}function xQo(t){const e=t.connection;return t.sourceObstacle.connectedTo.find(o=>o.startsWith("connectivity_net"))??e.netConnectionName??t.connection.name.replace(/::fanout:\d+$/,"")}function KNt(t,e){return t===e.connection.sourceObstacle||t.connectedTo.includes(e.connection.connection.name)||t.connectedTo.includes(e.netKey)}function pue(t,e){const n=e.x-t.x,o=e.y-t.y,i=Math.abs(n),r=Math.abs(o);return i<ah||r<ah||Math.abs(i-r)<ah?[t,e]:i>r?[t,{x:t.x+Math.sign(n)*r,y:e.y},e]:[t,{x:e.x,y:t.y+Math.sign(o)*i},e]}function VNt(t){if(t.length<2)return t;const e=[t[0]];for(const n of t.slice(1)){const o=e.at(-1),i=Math.abs(n.x-o.x),r=Math.abs(n.y-o.y);if(i<ah||r<ah||Math.abs(i-r)<ah){e.push(n);continue}e.push(...pue(n,o).reverse().slice(1))}return mue(e)}function mue(t){if(t.length<3)return t;const e=[t[0]];for(let n=1;n<t.length-1;n++){const o=e.at(-1),i=t[n],r=t[n+1];(Math.sign(i.x-o.x)!==Math.sign(r.x-i.x)||Math.sign(i.y-o.y)!==Math.sign(r.y-i.y))&&e.push(i)}return e.push(t.at(-1)),e}function EQo(t,e){if(t.length<3)return t;const n=[t[0]];for(let o=1;o<t.length-1;o++){const i=t[o-1],r=t[o],s=t[o+1],a=tn(i,r),A=tn(r,s);if(a<ah||A<ah)continue;const c={x:(r.x-i.x)/a,y:(r.y-i.y)/a},l={x:(s.x-r.x)/A,y:(s.y-r.y)/A};if(Math.abs(c.x*l.x+c.y*l.y)>1e-6){n.push(r);continue}const u=Math.min(e,a/2,A/2);n.push({x:r.x-c.x*u,y:r.y-c.y*u}),n.push({x:r.x+l.x*u,y:r.y+l.y*u})}return n.push(t.at(-1)),mue(n)}function vO(t,e){const n=[];for(let o=1;o<t.length;o++)tn(t[o-1],t[o])<ah||n.push({start:t[o-1],end:t[o],width:e,layer:"top"});return n}var BQo=class{edges;levels;nextEdges;constructor(t){this.edges=Array.from({length:t},()=>[]),this.levels=new Int32Array(t),this.nextEdges=new Int32Array(t)}addEdge(t,e,n,o={}){const i={to:e,reverseIndex:this.edges[e].length,capacity:n,initialCapacity:n,...o},r={to:t,reverseIndex:this.edges[t].length,capacity:0,initialCapacity:0};this.edges[t].push(i),this.edges[e].push(r)}buildLevels(t,e){this.levels.fill(-1);const n=new Int32Array(this.edges.length);let o=0,i=0;for(n[i++]=t,this.levels[t]=0;o<i;){const r=n[o++];for(const s of this.edges[r])s.capacity<=0||this.levels[s.to]>=0||(this.levels[s.to]=this.levels[r]+1,n[i++]=s.to)}return this.levels[e]>=0}sendFlow(t,e){if(t===e)return 1;for(let n=this.nextEdges[t];n<this.edges[t].length;n++,this.nextEdges[t]=n){const o=this.edges[t][n];if(o.capacity<=0||this.levels[o.to]!==this.levels[t]+1)continue;const i=this.sendFlow(o.to,e);if(i!==0)return o.capacity-=i,this.edges[o.to][o.reverseIndex].capacity+=i,i}return 0}*maximumFlowSteps(t,e,n){let o=0;for(;o<n&&this.buildLevels(t,e);){this.nextEdges.fill(0);let i=0;for(;o<n;){const r=this.sendFlow(t,e);if(r===0)break;o+=r,i+=r,i>=4&&o<n&&(i=0,yield o)}}return o}};function*bQo(t){const{boundary:e,obstacles:n,traceWidth:o,clearance:i,reportProgress:r}=t,s=o+i,a=Math.round((e.maxX-e.minX)/s)+1,A=Math.round((e.maxY-e.minY)/s)+1,c=a*A,l=Array.from({length:c},(m,_)=>({x:e.minX+_%a*s,y:e.minY+Math.floor(_/a)*s})),u=o/2+i,g=new Map;for(let m=0;m<n.length;m++){const _=n[m],f=Math.floor((_.center.x-_.width/2-u)/Cw),I=Math.floor((_.center.x+_.width/2+u)/Cw),C=Math.floor((_.center.y-_.height/2-u)/Cw),y=Math.floor((_.center.y+_.height/2+u)/Cw);for(let x=f;x<=I;x++)for(let E=C;E<=y;E++){const B=`${x}:${E}`,S=g.get(B)??[];S.push(m),g.set(B,S)}(m+1)%128===0&&(r({phase:"index-obstacles",processed:m+1,total:n.length}),yield)}const h=(m,_=m)=>{const f=Math.floor(Math.min(m.x,_.x)/Cw),I=Math.floor(Math.max(m.x,_.x)/Cw),C=Math.floor(Math.min(m.y,_.y)/Cw),y=Math.floor(Math.max(m.y,_.y)/Cw),x=new Set;for(let E=f;E<=I;E++)for(let B=C;B<=y;B++)for(const S of g.get(`${E}:${B}`)??[])x.add(S);return[...x].map(E=>n[E])},d=new Uint8Array(c);for(let m=0;m<c;m++){const _=l[m];h(_).every(f=>wx(_,f)>=u-ah)&&(d[m]=1),(m+1)%2048===0&&(r({phase:"classify-flow-grid",processed:m+1,total:c,grid:{points:l,obstacleFreeNodes:d,processedNodeCount:m+1}}),yield)}const p=Array.from({length:c},()=>[]);for(let m=0;m<c;m++){if(!d[m])continue;const _=m%a,f=Math.floor(m/a);for(const[I,C]of[[1,0],[0,1]]){const y=_+I,x=f+C;if(y>=a||x>=A)continue;const E=x*a+y;if(!d[E])continue;const B={start:l[m],end:l[E]};h(B.start,B.end).some(S=>Tl(B,S)<u-ah)||(p[m].push(E),p[E].push(m))}(m+1)%2048===0&&(r({phase:"connect-flow-grid",processed:m+1,total:c,grid:{points:l,obstacleFreeNodes:d,processedNodeCount:c}}),yield)}return{boundary:e,step:s,columnCount:a,rowCount:A,nodeCount:c,points:l,obstacleFreeNodes:d,neighbors:p}}function*SQo(t){const{direction:e,availableDirections:n,items:o,grid:i,obstacles:r,traceWidth:s,clearance:a,occupiedNodes:A,acceptedSegments:c,connectorSelectionOffset:l=0,reportProgress:u}=t;if(o.length===0)return{routes:[],usedNodes:[],unmatchedItems:[]};const{boundary:g,step:h,columnCount:d,rowCount:p,nodeCount:m}=i,_=le=>i.points[le],f=s/2+a,I=s+a,C=new Uint8Array(m);for(let le=0;le<m;le++)!A[le]&&i.obstacleFreeNodes[le]&&(C[le]=1);const y=(le,ge)=>{const _e=vO(le,s);return _e.every(ue=>r.every(fe=>KNt(fe,ge)||Tl(ue,fe)>=f-ah))&&_e.every(ue=>c.every(fe=>tu(ue.start,ue.end,fe.start,fe.end)>=I-ah))},x=new Map;for(const le of o){const ge=`${le.source.x.toFixed(6)}:${le.source.y.toFixed(6)}:${le.netKey}`,_e=x.get(ge)??[];_e.push(le),x.set(ge,_e)}const E=Array.from({length:3721},(le,ge)=>{const _e=ge%61-30,ue=Math.floor(ge/61)-30;return{x:_e,y:ue,distanceSquared:_e*_e+ue*ue}}).sort((le,ge)=>le.distanceSquared-ge.distanceSquared),B=[];let S=0;for(const le of x.values()){const ge=le[0],_e=Math.hypot(ge.connection.sourceObstacle.width/2,ge.connection.sourceObstacle.height/2)+a+h*2,ue=Math.round((ge.source.x-g.minX)/h),fe=Math.round((ge.source.y-g.minY)/h),pe=[],ye=new Set;for(const Me of E){const ve=ue+Me.x,he=fe+Me.y;if(ve<0||ve>=d||he<0||he>=p)continue;const Qe=he*d+ve;if(!C[Qe]||ye.has(Qe)||tn(ge.source,_(Qe))>_e)continue;const Pe=pue(ge.source,_(Qe));if(y(Pe,ge)&&(ye.add(Qe),pe.push({node:Qe,connectorPoints:Pe}),pe.length>=12))break}if(pe.length===0)return null;B.push({item:ge,equivalentItems:le,candidates:pe}),S++,S%8===0&&(u({phase:"discover-terminal-connectors",direction:e,processed:S,total:x.size,grid:{points:i.points,obstacleFreeNodes:C,processedNodeCount:m},candidatePoints:B.flatMap(Me=>Me.candidates.map(ve=>_(ve.node))),segments:c}),yield)}const Q=[];let w=0;for(const le of[...B].sort((ge,_e)=>ge.candidates.length-_e.candidates.length)){const ge=le.candidates.length===0?0:l%le.candidates.length,ue=[...le.candidates.slice(ge),...le.candidates.slice(0,ge)].find(fe=>{const pe=vO(fe.connectorPoints,s);return Q.every(ye=>ye.netKey===le.item.netKey||pe.every(Me=>ye.segments.every(ve=>tu(Me.start,Me.end,ve.start,ve.end)>=I-ah)))});if(!ue)return null;le.candidates=[ue],Q.push({netKey:le.item.netKey,segments:vO(ue.connectorPoints,s)}),w++,w%8===0&&(u({phase:"select-terminal-connectors",direction:e,processed:w,total:B.length,grid:{points:i.points,obstacleFreeNodes:C,processedNodeCount:m},candidatePoints:B.flatMap(fe=>fe.candidates.map(pe=>_(pe.node))),segments:[...c,...Q.flatMap(fe=>fe.segments)]}),yield)}const M=new Set(B.map(le=>le.candidates[0].node));for(const le of Q)for(const ge of le.segments){const _e=Math.max(0,Math.floor((Math.min(ge.start.x,ge.end.x)-I-g.minX)/h)),ue=Math.min(d-1,Math.ceil((Math.max(ge.start.x,ge.end.x)+I-g.minX)/h)),fe=Math.max(0,Math.floor((Math.min(ge.start.y,ge.end.y)-I-g.minY)/h)),pe=Math.min(p-1,Math.ceil((Math.max(ge.start.y,ge.end.y)+I-g.minY)/h));for(let ye=fe;ye<=pe;ye++)for(let Me=_e;Me<=ue;Me++){const ve=ye*d+Me;if(!C[ve]||M.has(ve))continue;const he=_(ve);tu(ge.start,ge.end,he,he)<I-ah&&(C[ve]=0)}}const k=0,R=1,F=R+B.length,O=F+m,U=O+m,Y=new BQo(U+1);for(let le=0;le<B.length;le++){const ge=R+le;Y.addEdge(k,ge,1);for(const _e of B[le].candidates)Y.addEdge(ge,F+_e.node,1,{gridNode:_e.node})}for(let le=0;le<m;le++){if(!C[le])continue;Y.addEdge(F+le,O+le,1);const ge=le%d,_e=Math.floor(le/d);for(const fe of i.neighbors[le])C[fe]&&Y.addEdge(O+le,F+fe,1,{gridNode:fe});(e==="any"&&((!n||n.has("left"))&&ge===0||(!n||n.has("right"))&&ge===d-1||(!n||n.has("down"))&&_e===0||(!n||n.has("up"))&&_e===p-1)||e==="left"&&ge===0||e==="right"&&ge===d-1||e==="down"&&_e===0||e==="up"&&_e===p-1)&&Y.addEdge(O+le,U,1,{isSink:!0}),(le+1)%2048===0&&(u({phase:"build-flow-network",direction:e,processed:le+1,total:m,grid:{points:i.points,obstacleFreeNodes:C,processedNodeCount:m},candidatePoints:B.map(fe=>_(fe.candidates[0].node)),segments:[...c,...Q.flatMap(fe=>fe.segments)]}),yield)}const W=Y.maximumFlowSteps(k,U,B.length);let te=W.next();for(;!te.done;)u({phase:"augment-terminal-flow",direction:e,processed:te.value,total:B.length,grid:{points:i.points,obstacleFreeNodes:C,processedNodeCount:m},candidatePoints:B.map(le=>_(le.candidates[0].node)),segments:[...c,...Q.flatMap(le=>le.segments)]}),yield,te=W.next();const j=te.value,J=le=>{const ge=R+le;return Y.edges[k].some(_e=>_e.to===ge&&_e.initialCapacity===1&&_e.capacity===0)};if(j!==B.length&&a$){const le=B.flatMap((ge,_e)=>J(_e)?[]:[ge.item.connection.connection.name]);console.error("single-layer flow group failed",{direction:e,achievedFlow:j,requiredFlow:B.length,unmatchedConnections:le})}const oe=[],ie=[],ne=[];for(let le=0;le<B.length;le++){const ge=B[le];if(!J(le)){ne.push(...ge.equivalentItems);continue}const _e=R+le,ue=Y.edges[_e].find(Pe=>Pe.initialCapacity===1&&Pe.capacity===0&&Pe.gridNode!==void 0);if(ue?.gridNode===void 0)return null;const fe=ge.candidates.find(Pe=>Pe.node===ue.gridNode);if(!fe)return null;const pe=[_(fe.node)];let ye=fe.node;const Me=[ye];for(let Pe=0;Pe<=m;Pe++){const we=O+ye,Te=Y.edges[we].find(Re=>Re.initialCapacity===1&&Re.capacity===0&&(Re.gridNode!==void 0||Re.isSink));if(!Te)return null;if(Te.isSink)break;if(Te.gridNode===void 0)return null;ye=Te.gridNode,Me.push(ye),pe.push(_(ye))}ie.push(...Me);const ve=mue([...fe.connectorPoints,...pe.slice(1)]),he=VNt(EQo(ve,h/2)),Qe=vO(he,s);for(const Pe of ge.equivalentItems)oe.push({item:Pe,points:he,segments:Qe});(le+1)%8===0&&(u({phase:"extract-flow-routes",direction:e,processed:le+1,total:B.length,grid:{points:i.points,obstacleFreeNodes:C,processedNodeCount:m},segments:[...c,...oe.flatMap(Pe=>Pe.segments)]}),yield)}return{routes:oe,usedNodes:ie,unmatchedItems:ne}}function zNt(t,e){const{item:n,points:o,segments:i}=t,r=o.map((a,A)=>({route_type:"wire",x:a.x,y:a.y,width:e,layer:"top",...A===0&&n.connection.sourcePoint.pcb_port_id?{start_pcb_port_id:n.connection.sourcePoint.pcb_port_id}:{}})),s=qN({connectionName:n.connection.connection.name,sourcePointIndex:n.connection.sourcePointIndex});return{busId:n.bus.busId,connectionName:n.connection.connection.name,connectionIndex:n.connection.connectionIndex,sourcePointIndex:n.connection.sourcePointIndex,sourcePoint:n.connection.sourcePoint,sourceObstacle:n.connection.sourceObstacle,sourceLayer:n.connection.sourceLayer,targetPoint:n.connection.targetPoint,targetLayer:"top",termination:n.bus.termination,direction:n.bus.direction,...n.bus.exitEdge?{exitEdge:n.bus.exitEdge}:{},exitPoint:o.at(-1),trace:{type:"pcb_trace",pcb_trace_id:s.traceId,connection_name:n.connection.connection.name,connectsTo:[...n.connection.sourcePoint.pointId?[n.connection.sourcePoint.pointId]:[],...n.connection.sourcePoint.pcb_port_id?[n.connection.sourcePoint.pcb_port_id]:[],s.boundaryExitPointId],route:r},segments:i,length:i.reduce((a,A)=>a+tn(A.start,A.end),0)}}function QQo(t,e){const n=pue(t,e),o=pue(e,t).reverse();return n.length===o.length&&n.every((i,r)=>tn(i,o[r])<ah)?[n]:[n,o]}function JNt(t){const{plans:e,items:n,obstacles:o,traceWidth:i,clearance:r}=t,s=new Map(n.map(g=>[g.connection.connection.name,g.netKey])),a=new Map,A=new Map;for(const g of e){const h=s.get(g.connectionName),d=a.get(h)??[],p=A.get(h)??new Set;for(const m of g.segments){const f=[m.start,m.end].map(I=>`${I.x.toFixed(6)}:${I.y.toFixed(6)}`).sort().join(":");p.has(f)||(p.add(f),d.push(m))}a.set(h,d),A.set(h,p)}const c=i/2+r;for(const[g,h]of a)for(const d of h)for(const p of o)if(!(p.connectedTo.includes(g)||Tl(d,p)>=c-ah))return a$&&console.error("single-layer route violates obstacle clearance",{netKey:g,segment:d,obstacleId:p.obstacleId,distance:Tl(d,p),requiredObstacleDistance:c}),!1;const l=i+r,u=[...a];for(let g=0;g<u.length;g++)for(let h=g+1;h<u.length;h++)for(const d of u[g][1])for(const p of u[h][1])if(tu(d.start,d.end,p.start,p.end)<l-ah)return a$&&console.error("single-layer routes violate copper clearance",{firstNetKey:u[g][0],secondNetKey:u[h][0],first:d,second:p,distance:tu(d.start,d.end,p.start,p.end),requiredRouteDistance:l}),!1;return!0}function vQo(t,e){return Math.abs(t.x-e.minX)<ah?"left":Math.abs(t.x-e.maxX)<ah?"right":Math.abs(t.y-e.minY)<ah?"down":Math.abs(t.y-e.maxY)<ah?"up":null}function*wQo(t){const{items:e,grid:n,obstacles:o,traceWidth:i,clearance:r,availableBoundaryRegions:s,onPartialRoutes:a,reportProgress:A}=t,c=s?new Set(s.map(_=>_.direction)):void 0,l=new Set(e.filter(_=>_.connection.sourceObstacle.width>2&&_.connection.sourceObstacle.height>2));let u=null;for(let _=0;_<4;_++){const f=e.filter(x=>!l.has(x));let I=null;for(let x=0;x<4;x++){const E=yield*SQo({direction:"any",availableDirections:c,items:f,grid:n,obstacles:o,traceWidth:i,clearance:r,occupiedNodes:new Uint8Array(n.nodeCount),acceptedSegments:[],connectorSelectionOffset:x,reportProgress:A});if(E){if(a&&E.routes.length>0&&E.routes.length<e.length){const B=E.routes.map(S=>zNt(S,i));JNt({plans:B,items:e,obstacles:o,traceWidth:i,clearance:r})&&a(B)}if((!I||E.routes.length>I.routes.length)&&(I=E),E.routes.length===f.length)break}}if(!I)return null;if(I.routes.length===f.length){u=I;break}const C=new Map;for(const x of f)C.set(x.netKey,(C.get(x.netKey)??0)+1);let y=!1;for(const x of I.unmatchedItems)(C.get(x.netKey)??0)<2||(l.add(x),y=!0);if(!y)return null}if(!u)return null;const g=[...u.routes],h=i/2+r,d=i+r;for(const _ of l){const f=g.filter(C=>C.item.netKey===_.netKey).flatMap(C=>C.points.map((y,x)=>({route:C,point:y,pointIndex:x}))).sort((C,y)=>+(y.route.item.bus.componentId===_.bus.componentId)-+(C.route.item.bus.componentId===_.bus.componentId)||tn(_.source,C.point)-tn(_.source,y.point));let I=null;for(const C of f){for(const y of QQo(_.source,C.point)){const x=vO(y,i),E=x.every(Q=>o.every(w=>KNt(w,_)||Tl(Q,w)>=h-ah)),B=x.every(Q=>g.every(w=>w.item.netKey===_.netKey||w.segments.every(M=>tu(Q.start,Q.end,M.start,M.end)>=d-ah)));if(!E||!B)continue;const S=VNt(mue([...y,...C.route.points.slice(C.pointIndex+1)]));I={item:_,points:S,segments:vO(S,i)};break}if(I)break}if(!I)return null;g.push(I),A({phase:"merge-same-net-routes",processed:g.length,total:e.length,grid:{points:n.points,obstacleFreeNodes:n.obstacleFreeNodes,processedNodeCount:n.nodeCount},segments:g.flatMap(C=>C.segments)}),yield}const p=g.map(_=>zNt(_,i));if(!JNt({plans:p,items:e,obstacles:o,traceWidth:i,clearance:r}))return a$&&console.error("single-layer adaptive exits failed exact clearance"),null;for(const _ of p){const f=vQo(_.exitPoint,n.boundary);if(!f||c&&!c.has(f))return null;const I=e.find(x=>x.connection.connection.name===_.connectionName);I.bus.direction=f;const C=s?.filter(x=>x.direction===f),y=f==="up"||f==="down"?_.exitPoint.x:_.exitPoint.y;I.bus.preferredExit=C?.toSorted((x,E)=>Math.abs(y-hue(x,n.boundary))-Math.abs(y-hue(E,n.boundary)))[0]?.preferredExit??(f==="up"?"top":f==="down"?"bottom":f),_.direction=f}const m=new Map(p.map(_=>[_.connectionName,_]));return e.map(_=>m.get(_.connection.connection.name))}function*AR(t){const{srj:e,buses:n,traceWidth:o,clearance:i,availableBoundaryRegions:r,onPartialRoutes:s,onProgress:a}=t;if(n.some(p=>p.connections.length!==1))return null;const A=n.flatMap(p=>p.connections.map(m=>({bus:p,connection:m,source:{x:m.sourcePoint.x,y:m.sourcePoint.y},netKey:xQo(m)}))),c=e.obstacles.filter(p=>p.layers.includes("top")),l=n[0]?.sharedBoundary;if(!l)return[];const u=A.map(p=>p.source),g=p=>{a?.(yQo({boundary:l,sourcePoints:u,traceWidth:o,update:p}),{adaptivePhase:p.phase,...p.direction?{adaptiveDirection:p.direction}:{},...p.processed!==void 0?{adaptiveWorkUnit:p.processed}:{},...p.total!==void 0?{adaptiveWorkUnitCount:p.total}:{}})};g({phase:"prepare-flow-grid",processed:0,total:c.length});const h=yield*bQo({boundary:l,obstacles:c,traceWidth:o,clearance:i,reportProgress:g});a$&&console.error("single-layer adaptive-exit grid ready",{nodeCount:h.nodeCount});const d=yield*wQo({items:A,grid:h,obstacles:c,traceWidth:o,clearance:i,availableBoundaryRegions:r,onPartialRoutes:s,reportProgress:g});return d||null}var Wy=1e-9;function PQo(t,e){const n=[t[0]];for(let o=1;o<t.length-1;o++){const i=t[o-1],r=t[o],s=t[o+1],a=r.x-i.x,A=r.y-i.y,c=s.x-r.x,l=s.y-r.y,u=Math.hypot(a,A),g=Math.hypot(c,l);if(!(u<Wy||g<Wy))if(Math.abs(a*c+A*l)<Wy){const h=Math.min(e,u/2,g/2);n.push({x:r.x-a/u*h,y:r.y-A/u*h},{x:r.x+c/g*h,y:r.y+l/g*h})}else n.push(r)}return n.push(t.at(-1)),n.filter((o,i)=>i===0||tn(o,n[i-1])>Wy)}function MQo(t,e,n){const o=t.toSorted((a,A)=>Math.atan2(a.exitPoint.y-n.y,a.exitPoint.x-n.x)-Math.atan2(A.exitPoint.y-n.y,A.exitPoint.x-n.x)),i=(a,A)=>{for(let c=0;c<Math.min(a.length,A.length);c++){const l=e.get(a[c].connectionIndex)-e.get(A[c].connectionIndex);if(l)return l<0}return!1},r=(a,A)=>a.length>A.length||a.length===A.length&&i(a,A),s=[];for(let a=o.length-1;a>=0;a--){let A=[];for(let c=a+1;c<o.length;c++)e.get(o[c].connectionIndex)>e.get(o[a].connectionIndex)&&r(s[c],A)&&(A=s[c]);s[a]=[o[a],...A]}return s.reduce((a,A)=>r(A,a)?A:a,[])}function*DQo(t){const{bus:e,srj:n,traceWidth:o,clearance:i,viaDiameter:r}=t;if(e.termination.type!=="boundary"||e.exitEdge!=="right"||e.connections.length<6||e.connections.some(ne=>ne.sourceLayer!=="top")||!(e.allowedLayers??t.layerNames).includes(t.targetLayer)||t.targetLayer==="top")return null;const s=e.componentObstacles.filter(ne=>ne.layers.includes("top"));if(!s.length)return null;const a={minX:Math.min(...s.map(ne=>ne.center.x-ne.width/2)),maxX:Math.max(...s.map(ne=>ne.center.x+ne.width/2)),minY:Math.min(...s.map(ne=>ne.center.y-ne.height/2)),maxY:Math.max(...s.map(ne=>ne.center.y+ne.height/2))},A={x:(a.minX+a.maxX)/2,y:(a.minY+a.maxY)/2},c=o+i,l=Math.max(e.pitchX,e.pitchY);if(!Number.isFinite(l)||l<=0)return null;const u=Math.ceil(((a.maxX-a.minX)/2+l+c)/c)*c,g=Math.ceil(((a.maxY-a.minY)/2+l+c)/c)*c,h={minX:A.x-u,maxX:A.x+u,minY:A.y-g,maxY:A.y+g};if(h.minX<=e.sharedBoundary.minX||h.maxX>=e.sharedBoundary.maxX||h.minY<=e.sharedBoundary.minY||h.maxY>=e.sharedBoundary.maxY)return null;const d=e.connections.map((ne,le)=>({...e,busId:`${e.busId}:source-perimeter:${le}`,sharedBoundary:h,preferredExit:void 0,exitEdge:void 0,connections:[{...ne,exitTargetPoint:void 0,hasExplicitLayeredExitTarget:!1,hasExplicitExitTarget:!1}]})),p=yield*AR({srj:n,buses:d,traceWidth:o,clearance:i});if(!p||p.length!==e.connections.length)return null;const m=ne=>t.targetPointsByConnectionIndex?.get(ne.connectionIndex)??{x:e.sharedBoundary.maxX,y:(ne.exitTargetPoint??ne.targetPoint).y},_=e.connections.toSorted((ne,le)=>m(ne).y-m(le).y||ne.connectionIndex-le.connectionIndex),f=new Map(_.map((ne,le)=>[ne.connectionIndex,le])),I=MQo(p,f,A);if(I.length<3||I.length>=e.connections.length||I.some(ne=>Math.abs(ne.exitPoint.y-h.maxY)>Wy&&(Math.abs(ne.exitPoint.x-h.minX)>Wy||ne.exitPoint.y<A.y)))return null;const C=new Map(t.buses.flatMap(ne=>ne.connections.map(le=>[le.connectionIndex,{bus:ne,connection:le}]))),y=e.sharedBoundary.maxX-Math.max(l/2,r/2+i),x=r/2+o/2+i,B=y-x-1e-5-(I.length-1)*c,Q=e.sharedBoundary.maxY-c-(I.length-1)*c;if(B<=a.maxX+x||Q<=h.maxY+c)return null;const w=(ne,le)=>{const ge=C.get(ne.connectionIndex).bus,_e=ge.busId===e.busId?t.targetLayer:ge.termination.type==="plane"?ge.termination.layer:t.targetLayerByBusId?.get(ge.busId)??(ge.allowedLayers??t.layerNames).find(ue=>ue!==ne.sourceLayer);if(!_e)throw new Error("FanoutSolver: missing target layer for peripheral via assignment");return{center:le,diameter:r,holeDiameter:t.viaHoleDiameter,fromLayer:ne.sourceLayer,toLayer:_e,spanLayers:Mx({fromLayer:ne.sourceLayer,toLayer:_e,layerNames:t.layerNames,allowBlindAndBuriedVias:t.allowBlindAndBuriedVias??!1})}},M=(ne,le)=>({connectionIndex:ne.connectionIndex,connectionName:ne.connection.name,segments:le.slice(1).map((ge,_e)=>({start:le[_e],end:ge,width:o,layer:ne.sourceLayer})),via:w(ne,le.at(-1))}),k=I.map((ne,le)=>{const ge=C.get(ne.connectionIndex).connection,_e=m(ge),ue=Q+le*c,fe=B+le*c;return M(ge,PQo([ne.segments[0].start,...ne.segments.map(pe=>pe.end),{x:ne.exitPoint.x,y:ue},{x:fe,y:ue},{x:fe,y:_e.y},{x:y,y:_e.y}],o))}),R=new Set(k.map(ne=>ne.connectionIndex)),F=(ne,le)=>{const ge=C.get(ne.connectionIndex).connection;if(ne.segments.some(_e=>[_e.start,_e.end].some(ue=>ue.x<e.sharedBoundary.minX-Wy||ue.x>e.sharedBoundary.maxX+Wy||ue.y<e.sharedBoundary.minY-Wy||ue.y>e.sharedBoundary.maxY+Wy)))return!1;for(const _e of n.obstacles)if(_e.layers.some(ue=>ne.via.spanLayers.includes(ue))&&wx(ne.via.center,_e)<r/2+i-Wy||_e!==ge.sourceObstacle&&ne.segments.some(ue=>_e.layers.includes(ue.layer)&&Tl(ue,_e)<o/2+i-Wy))return!1;for(const _e of le)if(ne.connectionIndex!==_e.connectionIndex&&(tn(ne.via.center,_e.via.center)<r+i-Wy||ne.segments.some(ue=>Cr(_e.via.center,ue.start,ue.end)<x-Wy)||_e.segments.some(ue=>Cr(ne.via.center,ue.start,ue.end)<x-Wy)||ne.segments.some(ue=>_e.segments.some(fe=>!Zm(ue,fe,i)))))return!1;return!0};if(k.some(ne=>!F(ne,k)))return null;const O=()=>{const ne=new Set(k.map(le=>le.connectionIndex));return t.buses.map(le=>({...le,connections:le.connections.filter(ge=>!ne.has(ge.connectionIndex))})).filter(le=>le.connections.length)},U=()=>({viaDiameter:r,viaHoleDiameter:t.viaHoleDiameter,traceWidth:o,clearance:i,additionalObstacles:n.obstacles,maximumSearchStates:3e5,blockingSegments:k.flatMap(ne=>ne.segments.map(le=>({connectionIndex:ne.connectionIndex,segment:le}))),blockingVias:k.map(ne=>({connectionIndex:ne.connectionIndex,...ne.via})),preferredViaPointsByConnectionIndex:t.initialViaPoints});let Y=O();const W=new Set(pw(Y,U()).map(ne=>ne.connectionIndex));for(const ne of Y)for(const le of ne.connections){if(W.has(le.connectionIndex))continue;if(ne.termination.type!=="plane")return null;const ge=le.sourcePoint,_e=le.sourceObstacle,ue=[{x:0,y:1,gap:a.maxY-ge.y},{x:-1,y:0,gap:ge.x-a.minX},{x:0,y:-1,gap:ge.y-a.minY},{x:1,y:0,gap:a.maxX-ge.x}].sort((pe,ye)=>pe.gap-ye.gap);let fe=null;for(const pe of ue){for(let ye=0;ye<8;ye++){const Me=(pe.x?_e.width:_e.height)/2+r/2+i+1e-5+ye*o,ve=M(le,[ge,{x:ge.x+pe.x*Me,y:ge.y+pe.y*Me}]);if(F(ve,k)){fe=ve;break}}if(fe)break}if(!fe)return null;k.push(fe)}Y=O();const te=U(),j=pd(Y,te);if(!j)return null;yield;const J=CQo({buses:Y,busId:e.busId,rules:{...te,preferredViaPointsByConnectionIndex:j}});if(!J)return null;const oe=[...k,...Y.flatMap(ne=>ne.connections.map(le=>M(le,[le.sourcePoint,J.get(le.connectionIndex)])))];if(oe.some(ne=>!F(ne,oe)))return null;const ie=new Map(oe.map(ne=>[ne.connectionIndex,ne.via.center]));return{sourceEscapes:oe,viaPointsByConnectionIndex:ie,remoteConnectionIndices:R,localBus:Y.find(ne=>ne.busId===e.busId),sourceBoundary:h}}function*NQo(t){const{srj:e,bus:n,targetLayer:o,sourceBoundary:i,sourceEscapes:r,remoteConnectionIndices:s,traceWidth:a,clearance:A}=t;if(n.exitEdge!=="right"||n.termination.type!=="boundary")return null;const c=a+A,l=Math.min(n.pitchX,n.pitchY),u=new Map(r.map(R=>[R.connectionIndex,R])),g=n.connections.map(R=>{const F=u.get(R.connectionIndex);if(!F)throw new Error(`FanoutSolver: missing source escape for ${R.connection.name}`);const O=R.exitTargetPoint??R.targetPoint;return{connection:R,viaPoint:F.via.center,exitPoint:{x:n.sharedBoundary.maxX,y:O.y}}}).sort((R,F)=>R.exitPoint.y-F.exitPoint.y),h=g.filter(R=>!s.has(R.connection.connectionIndex));if(h.length<2||h.length===g.length)return null;const d=Math.min(...n.componentObstacles.map(R=>R.center.x-R.width/2)),p=Math.max(...h.map(R=>R.viaPoint.x))-a/2,m=d+t.viaDiameter/2;if(p-m<(h.length-1)*c)return null;const _=i.maxY,f={minX:d-l,maxX:Math.max(...h.map(R=>R.viaPoint.x))+2*l,minY:Math.min(...h.map(R=>R.viaPoint.y))-3*l,maxY:_},I=new Set(h.map(R=>R.connection.connectionIndex)),C=h.map((R,F)=>({...R,exitPoint:{x:p+(m-p)*F/(h.length-1),y:_}})),y={...n,exitEdge:"top",direction:"up",preferredExit:void 0,sharedBoundary:f,connections:h.map(R=>R.connection)},x=new Map(r.map(R=>[R.connectionIndex,[R.segments[0].start,...R.segments.map(F=>F.end)]]));let E;for(const R of[-1,0,1]){const F=yield*BC({...t,bus:y,srj:{...e,bounds:f},acceptedPlans:[],terminals:C,sourceEscapePaths:x,reservedVias:r.filter(O=>!I.has(O.connectionIndex)).map(O=>({connectionName:O.connectionName,via:O.via})),allowBlindAndBuriedVias:!1,allowSameNetMerges:!1,gridStepDivisor:2,gridStep:c/4,alignGridToPads:!0,maximumRouteOrderAttempts:1,routeOrder:h.map((O,U)=>h.length-U-1),laneBias:R},1,!1);if(F.length){E=F[0];break}}if(!E)return null;const B=new Map(E.map(R=>[R.connectionIndex,R])),S=_+l,Q=n.sharedBoundary.maxX-(h.length+1)*c-2*t.viaDiameter;if(S+(h.length-1)*c+a/2>n.sharedBoundary.maxY)return null;let w=0;const M=[];for(const R of g){const F=u.get(R.connection.connectionIndex),O=B.get(R.connection.connectionIndex);let U;if(O){const Y=O.segments.filter(le=>le.layer===o),W=Y.at(-1),te=W.end.x-W.start.x,j=W.end.y-W.start.y;if(j<=0||Math.abs(te)>j+1e-7)return null;const J=W.end,oe=S+w*c,ie=Q+w*c;w++;const ne=RQo([J,{x:J.x,y:oe},{x:ie,y:oe},{x:ie,y:R.exitPoint.y},R.exitPoint],a);U=[Y[0].start,...Y.map(le=>le.end),...ne.slice(1)]}else U=[F.via.center,R.exitPoint];M.push(i4({...t,bus:n,terminal:R,targetLayerPoints:U,sourceEscapePoints:x.get(R.connection.connectionIndex),allowBlindAndBuriedVias:!1}))}const k=M.map(R=>R.length);if(n.maxLengthSkew!==void 0&&Math.max(...k)-Math.min(...k)>n.maxLengthSkew+1e-6||!Wh({plans:M,srj:e,sharedBoundary:n.sharedBoundary,clearance:A,allowBlindAndBuriedVias:!1,allowSameNetMerges:!1}))return null;for(const R of M)for(const F of r)if(R.connectionIndex!==F.connectionIndex)for(const O of R.segments){if(F.via.spanLayers.includes(O.layer)&&Cr(F.via.center,O.start,O.end)<F.via.diameter/2+O.width/2+A-1e-7)return null;for(const U of F.segments)if(O.layer===U.layer&&tu(O.start,O.end,U.start,U.end)<(O.width+U.width)/2+A-1e-7)return null}return M}function RQo(t,e){const n=t.filter((o,i)=>i===0||tn(o,t[i-1])>1e-9);return n.flatMap((o,i)=>{if(i===0||i===n.length-1)return[o];const r=n[i-1],s=n[i+1],a=Math.min(e,tn(r,o)/3,tn(o,s)/3);return Math.abs((o.x-r.x)*(s.x-o.x)+(o.y-r.y)*(s.y-o.y))>1e-9?[o]:[{x:o.x+(r.x-o.x)*a/tn(r,o),y:o.y+(r.y-o.y)*a/tn(r,o)},{x:o.x+(s.x-o.x)*a/tn(o,s),y:o.y+(s.y-o.y)*a/tn(o,s)}]})}function*TQo(t){const{bus:e,sourceBoundary:n,sourceEscapes:o,traceWidth:i,clearance:r,targetLayer:s}=t,a=Ds(e.exitEdge,e.preferredExit);if(t.allowBlindAndBuriedVias||e.exitEdge!=="right"||a!==void 0&&a!=="minimum"||e.connections.length<3)return null;const A=e.routableEscapeLayers??e.allowedLayers??[],c=A.find(W=>W!==s);if(!c||!A.includes(s)||e.connections.some(W=>W.sourceLayer===s))return null;const l=new Map(o.map(W=>[W.connectionIndex,W])),u=i+r,g=Math.min(e.pitchX,e.pitchY),h=t.viaDiameter+r,d=e.sharedBoundary.minX+Math.max(g/2,t.viaDiameter/2+r);if(d+(e.connections.length-1)*h>=n.minX)return null;const p=t.acceptedPlans.filter(W=>W.exitEdge===e.exitEdge&&W.cornerBandSide==="minimum").length,m=e.connections.map(W=>{const te=l.get(W.connectionIndex);if(!te)throw new Error(`FanoutSolver: missing crossbar source escape for ${W.connection.name}`);return{connection:W,viaPoint:te.via.center,exitPoint:{x:e.sharedBoundary.maxX,y:BB(a?{...t,connection:W,cornerExitLaneOffset:p}:{...t,bus:{...e,preferredExit:"bottom-right"},connection:W,cornerExitLaneOffset:p,windingOrderIndex:0})}}}),_=m.toSorted((W,te)=>W.exitPoint.y-te.exitPoint.y);if(!a)for(const[W,te]of _.entries())te.exitPoint.y=n.minY+g+W*h;const f=new Map(_.map(W=>[W.connection.connectionIndex,W.exitPoint.y])),I=Math.min(n.maxY-u,Math.max(...m.map(W=>W.viaPoint.y))+2*g),C=Math.max(n.minY+u,Math.min(...m.map(W=>W.viaPoint.y))-2*g,...a?[]:[Math.max(...f.values())+t.viaDiameter/2+i/2+r+u]);if(I-C<(m.length-1)*h||C<=Math.max(...f.values())+t.viaDiameter/2+i/2+r)return null;const y=new Map(o.map(W=>[W.connectionIndex,[W.segments[0].start,...W.segments.map(te=>te.end)]])),x=[...t.srj.obstacles.filter(W=>W.layers.includes(s)).map(W=>({...W,layers:["top"]})),...o.map(W=>({type:"rect",shape:"circle",center:W.via.center,width:W.via.diameter,height:W.via.diameter,layers:["top"],connectedTo:[W.connectionName]}))];for(let W=n.minY;W<=n.maxY;W+=u)(W<C||W>I)&&x.push({type:"rect",shape:"circle",center:{x:n.minX,y:W},width:i/1e3,height:i/1e3,layers:["top"],connectedTo:["blocked-port"]});const E=m.map((W,te)=>({...e,busId:e.busId+":"+te,sharedBoundary:n,preferredExit:void 0,exitEdge:void 0,connections:[{...W.connection,sourcePoint:{...W.viaPoint,layer:"top"},sourceLayer:"top",sourceObstacle:x.find(j=>j.connectedTo.includes(W.connection.connection.name)&&tn(j.center,W.viaPoint)<1e-7),exitTargetPoint:void 0,hasExplicitLayeredExitTarget:!1,hasExplicitExitTarget:!1}]})),B=AR({srj:{...t.srj,obstacles:x},buses:E,traceWidth:i,clearance:r,availableBoundaryRegions:[{exitEdge:"left",direction:"left",preferredExit:"left"}]});let S=B.next();for(;!S.done;)yield{phase:"route-connection",routeOrderAttempt:0,connectionIndex:0,connectionCount:m.length,connectionName:m[0].connection.connection.name,searchBatch:0,expandedStateCount:0,connectionComplete:!1},S=B.next();const Q=S.value?.length===m.length?S.value.map(W=>{const te=m.find(j=>j.connection.connectionIndex===W.connectionIndex);return i4({...t,terminal:{...te,exitPoint:W.exitPoint},sourceEscapePoints:y.get(W.connectionIndex),targetLayerPoints:[W.segments[0].start,...W.segments.map(j=>j.end)],allowBlindAndBuriedVias:!1})}):void 0;if(!Q)return null;const w=Q.toSorted((W,te)=>a?W.exitPoint.y-te.exitPoint.y:m.find(j=>j.connection.connectionIndex===W.connectionIndex).exitPoint.y-m.find(j=>j.connection.connectionIndex===te.connectionIndex).exitPoint.y),M=(W,te,j)=>({center:W,diameter:t.viaDiameter,holeDiameter:t.viaHoleDiameter,fromLayer:te,toLayer:j,spanLayers:Mx({fromLayer:te,toLayer:j,layerNames:t.layerNames,allowBlindAndBuriedVias:!1})}),k=new Map;for(const[W,te]of w.entries()){const j=te.segments.at(-1),J=j.end.x-j.start.x,oe=j.end.y-j.start.y;if(J>=0||Math.abs(oe)>-J+1e-7)return null;const ie=m.find(ue=>ue.connection.connectionIndex===te.connectionIndex),ne=d+W*h,le={x:ne,y:te.exitPoint.y},ge={x:ne,y:f.get(te.connectionIndex)},_e=[{start:te.exitPoint,end:le,width:i,layer:s},{start:le,end:ge,width:i,layer:c}];k.set(te.connectionIndex,{...te,segments:[...te.segments,..._e],additionalVias:[M(le,s,c),M(ge,c,s)],direction:e.direction,exitEdge:e.exitEdge,cornerBandSide:Ds(e.exitEdge,e.preferredExit),exitPoint:ie.exitPoint})}const R=[...k.values()],F=m.map(W=>({...W.connection,sourcePoint:{...k.get(W.connection.connectionIndex).additionalVias[1].center,layer:s},sourceLayer:s})),O={...t,bus:{...e,connections:F},terminals:F.map((W,te)=>({connection:W,viaPoint:W.sourcePoint,exitPoint:m[te].exitPoint})),acceptedPlans:[...t.acceptedPlans,...R],reservedVias:[...o.map(W=>({connectionName:W.connectionName,via:W.via})),...R.flatMap(W=>W.additionalVias.map(te=>({connectionName:W.connectionName,via:te})))],allowSourceLayerRouting:!0,sourceEscapePaths:void 0,gridStep:u*3/8,gridStepDivisor:2,alignGridToPads:!0,maximumRouteOrderAttempts:6,routeOrder:m.map((W,te)=>te).sort((W,te)=>m[W].exitPoint.y-m[te].exitPoint.y)},U=yield*BC(O,1,!1);if(!U.length)return null;const Y=Q.map(W=>{const te=k.get(W.connectionIndex),j=U[0].find(ge=>ge.connectionIndex===W.connectionIndex),[J,oe]=te.additionalVias,ie=(ge,_e)=>({route_type:"wire",...ge,width:i,layer:_e}),ne=ge=>({route_type:"via",...ge.center,from_layer:ge.fromLayer,to_layer:ge.toLayer,via_diameter:ge.diameter,via_hole_diameter:ge.holeDiameter}),le=[...te.segments,...j.segments];return{...te,segments:le,trace:{...W.trace,route:[...W.trace.route,ie(J.center,s),ne(J),ie(J.center,c),ie(oe.center,c),ne(oe),...j.trace.route]},length:le.reduce((ge,_e)=>ge+tn(_e.start,_e.end),0)}});if(!Wh({...t,plans:[...t.acceptedPlans,...Y],sharedBoundary:e.sharedBoundary}))return null;for(const W of Y)for(const te of o)if(W.connectionIndex!==te.connectionIndex){for(const j of W.segments){if(te.via.spanLayers.includes(j.layer)&&Cr(te.via.center,j.start,j.end)<te.via.diameter/2+i/2+r-1e-7)return null;for(const J of te.segments)if(J.layer===j.layer&&tu(j.start,j.end,J.start,J.end)<i+r-1e-7)return null}for(const j of W.additionalVias){if(tn(j.center,te.via.center)<t.viaDiameter+r-1e-7)return null;for(const J of te.segments)if(j.spanLayers.includes(J.layer)&&Cr(j.center,J.start,J.end)<t.viaDiameter/2+i/2+r-1e-7)return null}}return Y}function _ue(t){const e=new Map,n=o=>{if(o===null||typeof o!="object")return o;if(e.has(o))return e.get(o);if(o instanceof Map){const a=new Map;e.set(o,a);for(const[A,c]of o)a.set(A,n(c));return a}if(o instanceof Set){const a=new Set(o);return e.set(o,a),a}if(Array.isArray(o)){const a=[];e.set(o,a);for(const A of o)a.push(n(A));return a}const i=o,r={};e.set(o,r);for(const[a,A]of Object.entries(i))r[a]=n(A);typeof i.x=="number"&&typeof i.y=="number"&&(r.x=-i.x),typeof i.minX=="number"&&typeof i.maxX=="number"&&(r.minX=-i.maxX,r.maxX=-i.minX),Array.isArray(i.xCoordinates)&&(r.xCoordinates=i.xCoordinates.map(a=>-a).sort((a,A)=>a-A)),typeof i.ccwRotationDegrees=="number"&&(r.ccwRotationDegrees=-i.ccwRotationDegrees);const s=a=>a==="left"?"right":a==="right"?"left":a;for(const a of["direction","exitEdge","preferredExit"])typeof i[a]=="string"&&(r[a]=i[a].split("-").map(s).join("-"));return i.cornerBandSide&&(i.exitEdge==="top"||i.exitEdge==="bottom")&&(r.cornerBandSide=i.cornerBandSide==="minimum"?"maximum":"minimum"),r};return n(t)}function*WNt(t){const{bus:e,srj:n,sourceEscapes:o,sourceBoundary:i,targetLayer:r,acceptedPlans:s,traceWidth:a,clearance:A,viaDiameter:c}=t,l=e.exitEdge==="left",u=l?t.oppositeLayout:void 0,g=e.routableEscapeLayers??e.allowedLayers??[],h=e.connections[0].sourceLayer,d=l?g.find(Ce=>Ce!==r):h;if(e.termination.type!=="boundary"||e.exitEdge!=="right"&&!l||!d||!g.includes(r)||d===r||!(e.routableEscapeLayers??e.allowedLayers??[]).includes(d))return null;const p=Ds(e.exitEdge,e.preferredExit)==="minimum",m=e.connections.length,_=a+A,f=Math.ceil((c+A)/_)*_,I=new Map(o.map(Ce=>[Ce.connectionIndex,Ce])),C=e.connections.map(Ce=>I.get(Ce.connectionIndex));if(m<2||C.some(Ce=>!Ce))return null;const y=C.map(Ce=>Ce.via.center),x=Math.round(((l?(i.minX+i.maxX)/2+(u?.sourcePortOffset??0):Math.min(...y.map(Ce=>Ce.x)))+f-i.minX)/_),E=Math.round(f/_),B=new Set(Array.from({length:m},(Ce,Le)=>x+Le*E)),S=Math.round((i.maxX-i.minX)/_);if(x<1||Math.max(...B)>=S)return null;const Q=(Ce,Le,Ye)=>({type:"rect",shape:"circle",center:Le,width:Ye,height:Ye,layers:["top"],connectedTo:[Ce]}),w=[...n.obstacles.filter(Ce=>Ce.layers.includes(r)).map(Ce=>({...Ce,layers:["top"]})),...o.map(Ce=>Q(Ce.connectionName,Ce.via.center,Ce.via.diameter)),...s.flatMap(Ce=>(Ce.additionalVias??[]).map(Le=>Q(Ce.connectionName,Le.center,Le.diameter))),...s.flatMap(Ce=>Ce.segments.filter(Le=>Le.layer===r).map(Le=>({type:"rect",center:{x:(Le.start.x+Le.end.x)/2,y:(Le.start.y+Le.end.y)/2},width:tn(Le.start,Le.end),height:Le.width,ccwRotationDegrees:Math.atan2(Le.end.y-Le.start.y,Le.end.x-Le.start.x)*180/Math.PI,layers:["top"],connectedTo:[Ce.connectionName]})))];for(let Ce=0;Ce<=S;Ce++)B.has(Ce)||w.push(Q(`reserved-crossbar-port-${Ce}`,{x:i.minX+Ce*_,y:i.minY},a/1e3));const M=e.connections.map((Ce,Le)=>{const Ye=y[Le],tt=w.find(At=>At.connectedTo.includes(Ce.connection.name)&&tn(At.center,Ye)<1e-7);return{...e,busId:`${e.busId}:source-${Le}`,sharedBoundary:i,preferredExit:void 0,exitEdge:void 0,connections:[{...Ce,sourcePoint:{...Ce.sourcePoint,...Ye,layer:"top"},sourceObstacle:tt,sourceLayer:"top",exitTargetPoint:void 0,hasExplicitLayeredExitTarget:!1,hasExplicitExitTarget:!1}]}}),k=AR({srj:{...n,bounds:i,obstacles:w},buses:M,traceWidth:a,clearance:A,availableBoundaryRegions:[{direction:"down",preferredExit:"bottom",exitEdge:"bottom"}]});let R=k.next();for(;!R.done;)yield{phase:"route-connection",routeOrderAttempt:0,connectionIndex:0,connectionCount:m,connectionName:e.connections[0].connection.name,searchBatch:0,expandedStateCount:0,connectionComplete:!1},R=k.next();if(!R.value||R.value.length!==m)return null;const F=new Map(R.value.map(Ce=>[Ce.connectionIndex,Ce])),O=Ce=>Ds(e.exitEdge,e.preferredExit)!==void 0?BB({...t,connection:Ce,cornerExitLaneOffset:0}):tR({...t,connection:Ce,boundaryDirection:l?"left":"right"}),U=e.connections.toSorted((Ce,Le)=>O(Ce)-O(Le));Math.max(...e.componentObstacles.map(Ce=>Ce.center.x+Ce.width/2));const Y=o.filter(Ce=>Ce.via.center.x>i.maxX).map(Ce=>Ce.via.center.x),W=Y.length?Math.min(...Y):e.sharedBoundary.maxX,te=c/2+a/2+A,j=p||u?.compactRows?Math.max(te,(c+A)/Math.SQRT2)+1e-5:f,J=Math.min(...s.flatMap(Ce=>Ce.segments).filter(Ce=>Ce.layer!==d).flatMap(Ce=>[Ce.start.y,Ce.end.y])),oe=Math.min(i.minY-c/2-A-(u?.rowOffset??0),p?J-te-1e-5:1/0),ie=oe-(m-1)*j,ne=o.flatMap(Ce=>Ce.segments).filter(Ce=>Ce.layer===d&&(!p||Math.max(Ce.start.x,Ce.end.x)>=Math.min(...[...F.values()].map(Le=>Le.exitPoint.x))-te)&&Math.min(Ce.start.y,Ce.end.y)<=oe+te&&Math.max(Ce.start.y,Ce.end.y)>=ie-te),le=ne.length?Math.min(...ne.map(Ce=>Math.min(Ce.start.x,Ce.end.x)))-te-1e-5:e.sharedBoundary.maxX,ge=Math.min(e.sharedBoundary.maxX-c-A,W-te-a,le),_e=[...o.map(Ce=>Ce.via),...s.flatMap(Ce=>Ce.additionalVias??[])].filter(Ce=>Ce.spanLayers.includes(r)).map(Ce=>({minimum:Ce.center.x-Ce.diameter/2-a/2-A-1e-5,maximum:Ce.center.x+Ce.diameter/2+a/2+A+1e-5})),ue=Array.from({length:m},(Ce,Le)=>ge-Le*j),fe=[];if(ue.every(Ce=>_e.every(Le=>Ce<Le.minimum||Ce>Le.maximum)))fe.push(...ue);else{let Ce=ge;for(let Le=0;Le<m;Le++){for(let Ye=0;Ye<=_e.length;Ye++){const tt=_e.filter(At=>Ce>=At.minimum&&Ce<=At.maximum);if(!tt.length)break;Ce=Math.min(...tt.map(At=>At.minimum))-1e-7}fe.push(Ce),Ce-=p?j:c+A}}const pe=fe.at(-1),ye=[...o.map(Ce=>Ce.via),...s.flatMap(Ce=>Ce.additionalVias??[])].filter(Ce=>Ce.spanLayers.includes(r)&&Ce.center.x+Ce.diameter/2+a/2+A>=(l?e.sharedBoundary.minX:pe)&&Ce.center.x-Ce.diameter/2-a/2-A<=e.sharedBoundary.maxX).map(Ce=>({minimum:Ce.center.y-Ce.diameter/2-a/2-A-a/100,maximum:Ce.center.y+Ce.diameter/2+a/2+A+a/100})),Me=[];let ve=e.sharedBoundary.maxY-a/2;for(let Ce=m-1;Ce>=0;Ce--){for(let Le=0;Le<=ye.length;Le++){const Ye=ye.filter(tt=>ve>=tt.minimum&&ve<=tt.maximum);if(!Ye.length)break;ve=Math.min(...Ye.map(tt=>tt.minimum))-1e-7}Me[Ce]=ve,ve-=c+A}p&&Me.splice(0,Me.length,...U.map(O));const he=Me[0],Qe=oe;if(Qe-(m-1)*j-c/2<e.sharedBoundary.minY||pe<=Math.max(...[...F.values()].map(Ce=>Ce.exitPoint.x))+te||!p&&he<=(e.sharedBoundary.minY+e.sharedBoundary.maxY)/2)return null;const Pe=U.map((Ce,Le)=>{const Ye=F.get(Ce.connectionIndex),tt=I.get(Ce.connectionIndex),At=Me[Le];return{connectionIndex:Ce.connectionIndex,length:tt.segments.reduce((at,nt)=>at+tn(nt.start,nt.end),0)+(u?.compactRows?2*fe[m-1-Le]:0)+Ye.length+At-Ye.exitPoint.x}}).sort((Ce,Le)=>Le.length-Ce.length),we=new Map(Pe.map((Ce,Le)=>[Ce.connectionIndex,Le])),Te=(Ce,Le)=>Ce.slice(1).flatMap((Ye,tt)=>tn(Ce[tt],Ye)<1e-9?[]:[{start:Ce[tt],end:Ye,width:a,layer:Le}]),Re=(Ce,Le)=>Ce.map(Ye=>({route_type:"wire",...Ye,width:a,layer:Le})),Ee=Ce=>({route_type:"via",...Ce.center,from_layer:Ce.fromLayer,to_layer:Ce.toLayer,via_diameter:Ce.diameter,via_hole_diameter:Ce.holeDiameter}),ke=U.map((Ce,Le)=>{const Ye=I.get(Ce.connectionIndex),tt=F.get(Ce.connectionIndex),At=Qe-we.get(Ce.connectionIndex)*j,at={x:tt.exitPoint.x,y:At},nt={x:fe[l?m-1-Le:Le],y:At},gt={x:l?e.sharedBoundary.minX:e.sharedBoundary.maxX,y:Me[Le]},bt=[Ye.segments[0].start,...Ye.segments.map(Yt=>Yt.end)],Ct=[tt.segments[0].start,...tt.segments.map(Yt=>Yt.end),at],Dt=[nt,{x:nt.x,y:gt.y-Math.sign(gt.y-nt.y)*a},{x:nt.x+(l?-a:a),y:gt.y},gt],kt=i4({...t,terminal:{connection:Ce,viaPoint:Ye.via.center,exitPoint:gt},sourceEscapePoints:bt,targetLayerPoints:[Ye.via.center,gt],allowBlindAndBuriedVias:!1}),it=[{center:at,diameter:c,holeDiameter:t.viaHoleDiameter,spanLayers:t.layerNames,fromLayer:r,toLayer:d},{center:nt,diameter:c,holeDiameter:t.viaHoleDiameter,spanLayers:t.layerNames,fromLayer:d,toLayer:r}];return kt.segments=[...Ye.segments,...Te(Ct,r),...Te([at,nt],d),...Te(Dt,r)],kt.additionalVias=it,kt.sourceEscapeSegmentCount=Ye.segments.length,kt.length=kt.segments.reduce((Yt,pn)=>Yt+tn(pn.start,pn.end),0),kt.trace.route=[...Re(bt,h),Ee(kt.via),...Re(Ct,r),Ee(it[0]),...Re([at,nt],d),Ee(it[1]),...Re(Dt,r)],kt});if(e.maxLengthSkew!==void 0&&!u?.compactRows){const Ce=ke.map(Le=>Le.length);if(Math.max(...Ce)-Math.min(...Ce)>e.maxLengthSkew+1e-6)return null}if(!Wh({...t,plans:[...s,...ke],sharedBoundary:e.sharedBoundary}))return null;for(const Ce of ke)for(const Le of o)if(Ce.connectionIndex!==Le.connectionIndex){for(const Ye of Ce.segments){if(Le.via.spanLayers.includes(Ye.layer)&&Cr(Le.via.center,Ye.start,Ye.end)<Le.via.diameter/2+a/2+A-1e-7)return null;for(const tt of Le.segments)if(Ye.layer===tt.layer&&tu(Ye.start,Ye.end,tt.start,tt.end)<(a+tt.width)/2+A-1e-7)return null}for(const Ye of Ce.additionalVias){if(tn(Ye.center,Le.via.center)<(Ye.diameter+Le.via.diameter)/2+A-1e-7)return null;for(const tt of Le.segments)if(Ye.spanLayers.includes(tt.layer)&&Cr(Ye.center,tt.start,tt.end)<Ye.diameter/2+tt.width/2+A-1e-7)return null}}return ke}function*kQo(t){if(t.bus.exitEdge!=="right")return null;const e=_ue(t),n=Math.min(t.bus.pitchX,t.bus.pitchY),o=t.traceWidth+t.clearance,i=Math.ceil((t.viaDiameter+t.clearance)/o)*o,r=Math.max(0,Math.min(8,Math.floor(((e.sourceBoundary.maxX-e.sourceBoundary.minX)/2-t.bus.connections.length*i-o)/n))),s=[void 0,{sourcePortOffset:-n,rowOffset:0,compactRows:!1},...[0,1,2,3].map(c=>({sourcePortOffset:-n,rowOffset:c*o,compactRows:!0})),...Array.from({length:r},(c,l)=>r-l).flatMap(c=>[0,1,2,3].map(l=>({sourcePortOffset:c*n,rowOffset:l*o,compactRows:!0})))];let a=null;for(const c of s)if(a=yield*WNt({...e,oppositeLayout:c}),a)break;if(!a)return null;const A=new Map(t.bus.connections.map(c=>[c.connectionIndex,c]));return _ue(a).map(c=>({...c,sourceObstacle:A.get(c.connectionIndex).sourceObstacle}))}function jNt(t){const{bus:e,targetLayer:n,traceWidth:o,clearance:i}=t;if(!e.exitEdge)return[];const r=e.exitEdge==="left"||e.exitEdge==="right",s=r?"y":"x",a=r?"x":"y",A=e.sharedBoundary,c=e.exitEdge==="left"?A.minX:e.exitEdge==="right"?A.maxX:e.exitEdge==="bottom"?A.minY:A.maxY,l=r?A.minY:A.minX,u=r?A.maxY:A.maxX,g=(l+u)/2,h=Ds(e.exitEdge,e.preferredExit),d=(h==="maximum"?g:l)+o/2,p=(h==="minimum"?g:u)-o/2,m=[];for(const y of t.acceptedPlans)for(const x of[...y.segments,...y.planeEndpointSegments??[]]){if(x.layer!==n)continue;const E=(x.width+o)/2+i,B=x.start[a],S=x.end[a]-B;let Q=0,w=1;if(Math.abs(S)<1e-9){if(Math.abs(B-c)>E)continue}else{const O=(c-E-B)/S,U=(c+E-B)/S;if(Q=Math.max(0,Math.min(O,U)),w=Math.min(1,Math.max(O,U)),Q>w)continue}const M=x.start[s],k=x.end[s]-M,R=M+Q*k,F=M+w*k;m.push([Math.min(R,F)-E,Math.max(R,F)+E])}const _=[...t.acceptedPlans.flatMap(y=>[...y.via?[y.via]:[],...y.additionalVias??[],...y.planeEndpointVia?[y.planeEndpointVia]:[]]),...(t.reservedVias??[]).map(y=>y.via)];for(const y of _){if(!y.spanLayers.includes(n))continue;const x=y.diameter/2+o/2+i,E=Math.abs(y.center[a]-c);if(E>=x)continue;const B=Math.sqrt(x*x-E*E);m.push([y.center[s]-B,y.center[s]+B])}const f=[];let I=d;for(const[y,x]of m.sort((E,B)=>E[0]-B[0]))if(!(x<=I||y>=p)&&(y>I&&f.push([I,Math.min(y,p)]),I=Math.max(I,x),I>=p))break;I<p&&f.push([I,p]);const C=f.filter(([y,x])=>x-y>1e-6).map(([y,x])=>(y+x)/2);return C.length<=32?C:Array.from({length:32},(y,x)=>C[Math.round(x*(C.length-1)/31)])}function*FQo(t){if(t.buses.some(d=>d.termination.type!=="boundary"||d.connections.length>2))return null;let e=0;const n=192,o=t.traceWidth+t.clearance;function*i(d,p,m=d.preferredExit,_=0){return e++>=n?[]:yield*eue({...t,bus:{...d,preferredExit:m},acceptedPlans:p,reservedVias:t.reservedVias?.filter(f=>!d.connections.some(I=>I.connection.name===f.connectionName)),viaMinimalOnly:!0,adaptiveWindingRouteOrder:!0,alignWindingGridToPads:!0,windingGridStep:o/2,fixedViaFallbackRouteOrderAttempts:32,cornerBandTargetTrackOffset:_},1,!1)}const r=d=>d.map(p=>{const m=t.buses.find(_=>_.busId===p.busId);return m?{...p,cornerBandSide:Ds(m.exitEdge,m.preferredExit)}:p});let s=[...t.acceptedPlans];for(const d of t.buses){const p=yield*i(d,s);if(!p.length){s=[];break}s.push(...p[0])}if(s.length)return r(s.slice(t.acceptedPlans.length));const a=(d,p)=>d.connections.reduce((m,_)=>m+(t.fixedViaPointsByConnectionIndex?.get(_.connectionIndex)??_.sourcePoint)[p],0)/d.connections.length;if(t.buses.length>1)for(const d of[1,-1]){const p=t.buses.toSorted((_,f)=>{const I=Ds(_.exitEdge,_.preferredExit)!==void 0,C=Ds(f.exitEdge,f.preferredExit)!==void 0;if(I!==C)return Number(C)-Number(I);const y=_.exitEdge==="left"||_.exitEdge==="right"?"y":"x";return d*(a(_,y)-a(f,y))});let m=[...t.acceptedPlans];for(const _ of p){const f=yield*i(_,m);if(!f.length){m=[];break}m.push(...f[0])}if(m.length)return r(m.slice(t.acceptedPlans.length))}const A=t.buses.toSorted((d,p)=>{const m=Ds(d.exitEdge,d.preferredExit),_=Ds(p.exitEdge,p.preferredExit),f=m==="minimum",I=_==="minimum";return f!==I?Number(I)-Number(f):f?a(d,"y")-a(p,"y"):d.connections.length!==p.connections.length?d.connections.length-p.connections.length:d.connections.length===1?a(d,"x")-a(p,"x"):m!==_?+(m==="maximum")-+(_==="maximum"):(m==="maximum"?1:-1)*(a(d,"y")-a(p,"y"))});if(t.buses.length>1){const d=A.toSorted((f,I)=>{const C=y=>y.connections.length===1&&!Ds(y.exitEdge,y.preferredExit);return Number(C(I))-Number(C(f))}),p=Math.min(n,e+48);function*m(f,I){if(f===d.length)return I;if(e>=p)return null;const C=d[f],y=yield*i(C,I);for(const E of y){const B=yield*m(f+1,[...I,...E]);if(B)return B}const x=yield*c(C,I,p);for(const E of x){const B=yield*m(f+1,[...I,...E]);if(B)return B}return null}const _=yield*m(0,[...t.acceptedPlans]);if(_)return r(_.slice(t.acceptedPlans.length))}function*c(d,p,m){if(!d.exitEdge)return[];const _=t.reservedVias?.filter(Q=>!d.connections.some(w=>w.connection.name===Q.connectionName)),f={...t,bus:d,acceptedPlans:p,reservedVias:_},I=Ds(d.exitEdge,d.preferredExit),C=d.exitEdge==="left"||d.exitEdge==="right",y=d.sharedBoundary,x=C?y.minY:y.minX,E=C?y.maxY:y.maxX,B=(x+E)/2,S=[];for(const Q of jNt(f)){if(e>=m)break;const w=I?d.preferredExit:l(d).find(Y=>Ds(d.exitEdge,Y)===(Q>B?"maximum":"minimum")),M=d.connections.map(Y=>BB({...f,bus:{...d,preferredExit:w},connection:Y,cornerExitLaneOffset:0,windingOrderIndex:0})),k=M.reduce((Y,W)=>Y+W,0)/M.length,R=M.map(Y=>Y-k+Q);if(R.some(Y=>Y<=x+t.traceWidth/2||Y>=E-t.traceWidth/2||I==="minimum"&&Y>=B||I==="maximum"&&Y<=B))continue;const F=d.connections.map((Y,W)=>{const te=t.fixedViaPointsByConnectionIndex?.get(Y.connectionIndex),j=R[W],J=d.exitEdge==="left"?{x:y.minX,y:j}:d.exitEdge==="right"?{x:y.maxX,y:j}:d.exitEdge==="bottom"?{x:j,y:y.minY}:{x:j,y:y.maxY};return{connection:Y,viaPoint:te,exitPoint:J}});if(F.some(Y=>!Y.viaPoint))return[];e++;const O=BC({...f,terminals:F,gridStep:o/2,alignGridToPads:!0,maximumRouteOrderAttempts:d.connections.length===1?3:16,adaptiveRouteOrder:!0},1,!1);let U=O.next();for(;!U.done;)yield{phase:"via-minimal-winding",busId:d.busId,targetLayer:t.targetLayer,winding:U.value},U=O.next();S.push(...U.value)}return S}function l(d){if(Ds(d.exitEdge,d.preferredExit))return[d.preferredExit];switch(d.exitEdge){case"right":return[d.preferredExit,"top-right","bottom-right"];case"left":return[d.preferredExit,"top-left","bottom-left"];case"top":return[d.preferredExit,"top-left","top-right"];case"bottom":return[d.preferredExit,"bottom-left","bottom-right"];default:return[d.preferredExit]}}function u(d,p,m){const _=Ds(d.exitEdge,m);if(!_||t.buses.length>1)return[0];const f=d.exitEdge==="left"||d.exitEdge==="right",I=f?d.sharedBoundary.minY:d.sharedBoundary.minX,C=f?d.sharedBoundary.maxY:d.sharedBoundary.maxX,y=(I+C)/2,x=p.filter(k=>k.exitEdge===d.exitEdge&&k.cornerBandSide===_).length,E=d.connections.map(k=>BB({...t,bus:{...d,preferredExit:m},connection:k,cornerExitLaneOffset:x,windingOrderIndex:0})),B=_==="minimum"?-1:1,S=Math.min(d.pitchX,d.pitchY),Q=E.reduce((k,R)=>k+R,0)/E.length,w=_==="minimum"?I+o:C-o,M=[0,B*2*o,-B*2*o,B*S,B*2*S,B*3*S,B*4*S,w-Q];return M.filter((k,R)=>M.indexOf(k)===R&&E.every(F=>F+k>I+t.traceWidth/2&&F+k<C-t.traceWidth/2&&(_==="minimum"?F+k<y:F+k>y)))}function*g(d,p){if(!d.length)return p;if(e>=n)return null;for(const m of d)for(const _ of l(m))for(const f of u(m,p,_)){const I=yield*i(m,p,_,f);if(!I.length)continue;const C=yield*g(d.filter(y=>y!==m),[...p,...I[0]]);if(C)return C;if(e>=n)return null}for(const m of d){if(m.connections.length!==1||!m.exitEdge)continue;const _=m.connections[0],f=t.fixedViaPointsByConnectionIndex?.get(_.connectionIndex);if(!f)continue;const I=t.reservedVias?.filter(y=>y.connectionName!==_.connection.name),C=jNt({...t,bus:m,acceptedPlans:p,reservedVias:I});for(const y of C){if(e++>=n)return null;const x=m.sharedBoundary,E=m.exitEdge==="left"?{x:x.minX,y}:m.exitEdge==="right"?{x:x.maxX,y}:m.exitEdge==="bottom"?{x:y,y:x.minY}:{x:y,y:x.maxY},B=BC({...t,bus:m,acceptedPlans:p,reservedVias:I,terminals:[{connection:_,viaPoint:f,exitPoint:E}],gridStep:o/2,alignGridToPads:!0,maximumRouteOrderAttempts:3},1,!1);let S=B.next();for(;!S.done;)yield{phase:"via-minimal-winding",busId:m.busId,targetLayer:t.targetLayer,winding:S.value},S=B.next();if(!S.value.length)continue;const Q=yield*g(d.filter(w=>w!==m),[...p,...S.value[0]]);if(Q)return Q}}return null}const h=yield*g(A,[...t.acceptedPlans]);return h&&r(h.slice(t.acceptedPlans.length))}function*LQo(t){const{bus:e,sourceBoundary:n,sourceEscapes:o,traceWidth:i,clearance:r,targetLayer:s}=t,a=Ds(e.exitEdge,e.preferredExit);if(t.allowBlindAndBuriedVias||e.exitEdge!=="right"||a!==void 0&&a!=="minimum"||e.connections.length<3)return null;const A=e.routableEscapeLayers??e.allowedLayers??[],c=A.find(j=>j!==s);if(!c||!A.includes(s)||e.connections.some(j=>j.sourceLayer===s))return null;const l=new Map(o.map(j=>[j.connectionIndex,j])),u=i+r,g=Math.min(e.pitchX,e.pitchY),h=t.viaDiameter+r,d={x:(e.componentBounds.minX+e.componentBounds.maxX)/2,y:(e.componentBounds.minY+e.componentBounds.maxY)/2},p=e.sharedBoundary.minX+Math.max(g/2,t.viaDiameter/2+r);if(p+(e.connections.length-1)*h>=n.minX)return null;const m=t.acceptedPlans.filter(j=>j.exitEdge===e.exitEdge&&j.cornerBandSide==="minimum").length,_=e.connections.map(j=>{const J=l.get(j.connectionIndex);if(!J)throw new Error(`FanoutSolver: missing crossbar source escape for ${j.connection.name}`);return{connection:j,viaPoint:J.via.center,exitPoint:{x:e.sharedBoundary.maxX,y:BB(a?{...t,connection:j,cornerExitLaneOffset:m}:{...t,bus:{...e,preferredExit:"bottom-right"},connection:j,cornerExitLaneOffset:m,windingOrderIndex:0})}}}),f=_.toSorted((j,J)=>j.exitPoint.y-J.exitPoint.y);if(!a)for(const[j,J]of f.entries())J.exitPoint.y=n.minY+g+j*h;const I=new Map(f.map(j=>[j.connection.connectionIndex,j.exitPoint.y])),C=Math.min(n.maxY-u,Math.max(..._.map(j=>j.viaPoint.y))+2*g),y=Math.max(n.minY+u,Math.min(..._.map(j=>j.viaPoint.y))-2*g,...a?[]:[Math.max(...I.values())+t.viaDiameter/2+i/2+r+u]);if(C-y<(_.length-1)*h||y<=Math.max(...I.values())+t.viaDiameter/2+i/2+r)return null;const x=j=>{const J=_[j].viaPoint,oe=Math.atan2(J.y-d.y,J.x-d.x);return oe<0?oe+2*Math.PI:oe},E=_.map((j,J)=>J).sort((j,J)=>x(j)-x(J)),B=new Map(E.map((j,J)=>[j,{x:n.minX,y:C-(C-y)*J/(_.length-1)}])),S={minX:n.minX,maxX:d.x,minY:Math.min(y-g,Math.min(..._.map(j=>j.viaPoint.y))-2*g),maxY:n.maxY},Q=new Map(o.map(j=>[j.connectionIndex,[j.segments[0].start,...j.segments.map(J=>J.end)]])),w=new Set(_.map(j=>j.connection.connectionIndex)),M=o.filter(j=>!w.has(j.connectionIndex)).map(j=>({connectionName:j.connectionName,via:j.via}));let k;for(const j of[0,-1,1]){const J=yield*BC({...t,bus:{...e,exitEdge:"left",direction:"left",preferredExit:void 0,sharedBoundary:S},terminals:_.map((oe,ie)=>({...oe,exitPoint:B.get(ie)})),sourceEscapePaths:Q,reservedVias:M,gridStep:u/4,gridStepDivisor:2,alignGridToPads:!0,maximumRouteOrderAttempts:1,routeOrder:E,laneBias:j},1,!1);if(J.length){k=J[0];break}}if(!k)return null;const R=k.toSorted((j,J)=>a?j.exitPoint.y-J.exitPoint.y:_.find(oe=>oe.connection.connectionIndex===j.connectionIndex).exitPoint.y-_.find(oe=>oe.connection.connectionIndex===J.connectionIndex).exitPoint.y),F=(j,J,oe)=>({center:j,diameter:t.viaDiameter,holeDiameter:t.viaHoleDiameter,fromLayer:J,toLayer:oe,spanLayers:Mx({fromLayer:J,toLayer:oe,layerNames:t.layerNames,allowBlindAndBuriedVias:!1})}),O=new Map;for(const[j,J]of R.entries()){const oe=J.segments.at(-1),ie=oe.end.x-oe.start.x,ne=oe.end.y-oe.start.y;if(ie>=0||Math.abs(ne)>-ie+1e-7)return null;const le=_.find(pe=>pe.connection.connectionIndex===J.connectionIndex),ge=p+j*h,_e={x:ge,y:J.exitPoint.y},ue={x:ge,y:I.get(J.connectionIndex)},fe=[{start:J.exitPoint,end:_e,width:i,layer:s},{start:_e,end:ue,width:i,layer:c}];O.set(J.connectionIndex,{...J,segments:[...J.segments,...fe],additionalVias:[F(_e,s,c),F(ue,c,s)],direction:e.direction,exitEdge:e.exitEdge,cornerBandSide:Ds(e.exitEdge,e.preferredExit),exitPoint:le.exitPoint})}const U=[...O.values()],Y=_.map(j=>({...j.connection,sourcePoint:{...O.get(j.connection.connectionIndex).additionalVias[1].center,layer:s},sourceLayer:s})),W=yield*BC({...t,bus:{...e,connections:Y},terminals:Y.map((j,J)=>({connection:j,viaPoint:j.sourcePoint,exitPoint:_[J].exitPoint})),acceptedPlans:[...t.acceptedPlans,...U],reservedVias:[...o.map(j=>({connectionName:j.connectionName,via:j.via})),...U.flatMap(j=>j.additionalVias.map(J=>({connectionName:j.connectionName,via:J})))],allowSourceLayerRouting:!0,sourceEscapePaths:void 0,gridStep:u/2,gridStepDivisor:2,alignGridToPads:!0,maximumRouteOrderAttempts:12},1,!1);if(!W.length)return null;const te=k.map(j=>{const J=O.get(j.connectionIndex),oe=W[0].find(ue=>ue.connectionIndex===j.connectionIndex),[ie,ne]=J.additionalVias,le=(ue,fe)=>({route_type:"wire",...ue,width:i,layer:fe}),ge=ue=>({route_type:"via",...ue.center,from_layer:ue.fromLayer,to_layer:ue.toLayer,via_diameter:ue.diameter,via_hole_diameter:ue.holeDiameter}),_e=[...J.segments,...oe.segments];return{...J,segments:_e,trace:{...j.trace,route:[...j.trace.route,le(ie.center,s),ge(ie),le(ie.center,c),le(ne.center,c),ge(ne),...oe.trace.route]},length:_e.reduce((ue,fe)=>ue+tn(fe.start,fe.end),0)}});if(!Wh({...t,plans:[...t.acceptedPlans,...te],sharedBoundary:e.sharedBoundary}))return null;for(const j of te)for(const J of o)if(j.connectionIndex!==J.connectionIndex){for(const oe of j.segments){if(J.via.spanLayers.includes(oe.layer)&&Cr(J.via.center,oe.start,oe.end)<J.via.diameter/2+i/2+r-1e-7)return null;for(const ie of J.segments)if(ie.layer===oe.layer&&tu(oe.start,oe.end,ie.start,ie.end)<i+r-1e-7)return null}for(const oe of j.additionalVias){if(tn(oe.center,J.via.center)<t.viaDiameter+r-1e-7)return null;for(const ie of J.segments)if(oe.spanLayers.includes(ie.layer)&&Cr(oe.center,ie.start,ie.end)<t.viaDiameter/2+i/2+r-1e-7)return null}}return te}function*$Nt(t){if(t.buses.some(d=>d.termination.type==="boundary")&&t.buses.every(d=>d.termination.type==="plane"||d.exitEdge==="left")){const d=_ue(t),p=yield*$Nt(d);if(!p)return null;const m=_ue(p),_=new Map(t.buses.flatMap(f=>f.connections.map(I=>[I.connectionIndex,I])));return m.map(f=>({...f,sourceObstacle:_.get(f.connectionIndex).sourceObstacle}))}const{buses:e,sourceEscapes:n,initialPlans:o}=t,i=new Map(n.map(d=>[d.connectionIndex,d])),r=new Set(o.map(d=>d.connectionIndex)),s=e.filter(d=>d.connections.some(p=>!r.has(p.connectionIndex)));if(s.some(d=>d.connections.some(p=>r.has(p.connectionIndex))))throw new Error("FanoutSolver: a reserved-source continuation cannot start with a partially committed bus");for(const d of s)for(const p of d.connections)if(!i.has(p.connectionIndex))throw new Error(`FanoutSolver: missing reserved source escape for ${p.connection.name}`);const a=new Map(n.map(d=>[d.connectionIndex,d.via.center])),A=new Map(n.map(d=>[d.connectionIndex,[d.segments[0].start,...d.segments.map(p=>p.end)]])),c=[...o],l=d=>{const p=t.targetLayerByBusId?.get(d.busId)??(d.allowedLayers??t.layerNames).find(m=>m!==d.connections[0].sourceLayer);return o.filter(m=>m.targetLayer===p).length},u=s.filter(d=>d.termination.type==="boundary").sort((d,p)=>p.connections.length-d.connections.length||l(d)-l(p)),g=new Set;for(const d of[...u,...s.filter(p=>p.termination.type==="plane")]){if(g.has(d.busId))continue;if(d.termination.type==="boundary"&&d.connections.length<=2&&t.targetLayerByBusId){const C=t.targetLayerByBusId.get(d.busId);if(!C)return null;const y=u.filter(E=>E.connections.length<=2&&t.targetLayerByBusId.get(E.busId)===C),x=yield*FQo({...t,buses:y,targetLayer:C,acceptedPlans:c,fixedViaPointsByConnectionIndex:a,sourceEscapePaths:A,reservedVias:n.map(E=>({connectionName:E.connectionName,via:E.via}))});if(!x)return null;c.push(...x);for(const E of y)g.add(E.busId);continue}const p=new Set(d.connections.map(C=>C.connectionIndex)),m=n.filter(C=>!p.has(C.connectionIndex)).map(C=>({connectionName:C.connectionName,via:C.via,...C.segments.length===1?{sourceEscapeSegment:C.segments[0]}:{}})),_=t.targetLayerByBusId?.get(d.busId),f=_?[_]:d.termination.type==="plane"?[d.termination.layer]:(d.routableEscapeLayers??d.allowedLayers??t.layerNames).filter(C=>C!==d.connections[0].sourceLayer);let I;for(const C of f){const y={...t,bus:d,targetLayer:C,acceptedPlans:c,fixedViaPointsByConnectionIndex:a,sourceEscapePaths:A,reservedVias:m};if(t.sourceBoundary&&d.termination.type==="boundary"&&d.connections.length>2){for(const E of[WNt,LQo,TQo,kQo]){const B=E({...y,sourceBoundary:t.sourceBoundary});let S=B.next();for(;!S.done;)yield{phase:"via-minimal-winding",busId:d.busId,targetLayer:C,winding:S.value},S=B.next();if(S.value){I=S.value;break}}if(I)break}const x=yield*eue({...t,bus:d,targetLayer:C,acceptedPlans:c,fixedViaPointsByConnectionIndex:a,sourceEscapePaths:A,reservedVias:m,viaMinimalOnly:!0,adaptiveWindingRouteOrder:!0,alignWindingGridToPads:!0,windingGridStep:(t.traceWidth+t.clearance)/2,fixedViaFallbackRouteOrderAttempts:32},1,!1);if(x.length){I=x[0];break}}if(!I)return null;c.push(...I)}const h=e[0]?.sharedBoundary;return!h||!Wh({...t,plans:c,sharedBoundary:h})?null:c}function*HQo(t,e){const n={reserveFutureApproaches:!0,failedNarrowGroup:!1,failedWideMatching:!1},o=yield*e(n);return o||!t||!n.failedNarrowGroup&&!n.failedWideMatching?o:yield*e({reserveFutureApproaches:!1,failedNarrowGroup:!1,failedWideMatching:!1})}function qNt(t){const{buses:e,fixedViaPointsByConnectionIndex:n,clearance:o}=t,i=e[0];if(!i?.exitEdge||e.some(A=>A.componentId!==i.componentId||A.exitEdge!==i.exitEdge||A.termination.type!=="boundary"||A.connections.length>2||A.allowedLayers?.length!==1||A.allowedLayers[0]==="top"||A.connections.some(c=>c.sourceLayer!=="top")))return!1;const r=i.exitEdge==="left"||i.exitEdge==="right"?"x":"y",s=i.exitEdge==="top"||i.exitEdge==="right"?1:-1;let a=0;for(const A of e){if(A.connections.length!==2||A.maxLengthSkew===void 0||A.maxLengthSkew>=Math.min(A.pitchX,A.pitchY))continue;const c=A.componentBounds,l=r==="x"?s>0?c.minX:c.maxX:s>0?c.minY:c.maxY,u=A.connections.map(g=>({source:g.sourcePoint,via:n.get(g.connectionIndex)}));u.some((g,h)=>{const d=u[1-h];return!g.via||!d.via?!1:s*(g.via[r]-l)<-1e-7&&d.via.x>=c.minX&&d.via.x<=c.maxX&&d.via.y>=c.minY&&d.via.y<=c.maxY&&s*(d.via[r]-d.source[r])>o})&&a++}return a>=2}function OQo(t){return t.groups.filter(e=>qNt({...t,buses:e}))}function XNt(t){return t.completedBuses.filter(e=>t.selectedBusIds.has(e.busId)&&e.termination.type==="boundary"&&e.connections.length>2&&e.allowedLayers?.length===1&&e.maxLengthSkew!==void 0)}function ZNt(t){return XNt(t).some(e=>{const n=t.plans.filter(i=>i.busId===e.busId),o=Math.min(...n.map(i=>i.length))+e.maxLengthSkew;return n.some(i=>i.segments.slice(0,i.sourceEscapeSegmentCount??1).reduce((r,s)=>r+tn(s.start,s.end),0)>o+1e-6)})}function*GQo(t){const{inputSrj:e,preparedBuses:n,completedBuses:o,selectedBusIds:i}=t;if(!ZNt(t))return null;const r=XNt(t),s=n.flatMap(p=>p.connections),a=new Map(s.map(p=>[p.connectionIndex,p])),A=p=>{if(a.size!==e.connections.length||p.length!==a.size||new Set(p.map(m=>m.connectionIndex)).size!==a.size||p.some(m=>{const _=a.get(m.connectionIndex);return _?.connection.name!==m.connectionName||_.sourceObstacle!==m.sourceObstacle}))throw new Error("Wide source length repair requires every original source")};A(t.plans);const c=new Set(o.map(p=>p.busId)),l=n.filter(p=>p.termination.type==="boundary"&&!c.has(p.busId)),u=SO({...t,preparedBuses:o,allowBlindAndBuriedVias:!1,allowSameNetMerges:!1,allowSourcePrefixShortcuts:!0});if(!u)return null;let g=u;const h=()=>{let p=g;const m=zy({...t,plans:g,preparedBuses:o,sharedBoundary:r[0].sharedBoundary,allowBlindAndBuriedVias:!1,allowSameNetMerges:!1,allowMatchingInsideDenseBounds:!0,allowSourcePrefixMatching:!0,allowTransitLayerMatching:!0,allowDistributedMatching:!0,allowPairLaneSpreading:!0,allowUnconstrainedLaneRerouting:!0,unroutedSourceBuses:l,maximumWorkUnits:1e5,candidatePlansAreFeasible:_=>(A(_),p=[..._],!0)});return g=m.plans??p,m};let d=h();if(!d.plans){const p=d.failedBus;if(!r.some(x=>x.busId===p.busId))return null;const m=g.filter(x=>x.busId===p.busId),_=Math.max(...m.map(x=>x.length)),f=m.filter(x=>_-x.length>p.maxLengthSkew+1e-6);if(f.length!==1||g.some(x=>!x.via))return null;const I=f[0],C=a.get(I.connectionIndex),y=yield*AE({...t,srj:e,allBuses:n,buses:[{...p,connections:[C]}],targetLayer:I.targetLayer,transitLayers:[],terminals:[{connection:C,viaPoint:I.via.center,exitPoint:I.exitPoint}],fixedViaPointsByConnectionIndex:new Map(g.map(x=>[x.connectionIndex,x.via.center])),sourceEscapePaths:new Map(g.map(x=>[x.connectionIndex,[x.sourcePoint,...x.segments.slice(0,x.sourceEscapeSegmentCount??1).map(E=>E.end)]])),acceptedPlans:g.filter(x=>x!==I),routeFromSourcePads:!0,sourceLayerTravelCost:3,includeDiagonalNeighbors:!0,tightViaChannels:!0,ripCost:64,shuffleSeed:1,maximumIterations:2e6,maximumLocalRepairAttempts:0});if(!y||y.length!==1)return null;g=g.map(x=>x===I?y[0]:x),d=h()}return d.plans?(A(d.plans),qu({inputSrj:e,routedSrj:{...e,traces:[...e.traces??[],...d.plans.flatMap(p=>[p.trace,...p.planeEndpointTrace?[p.planeEndpointTrace]:[]])]},clearance:t.clearance,allowBlindAndBuriedVias:!1}).valid?d.plans:null):null}function YQo(t){const{buses:e,targetLayer:n,exits:o,layerNames:i,viaDiameter:r,clearance:s}=t,a=e[0];if(!a?.exitEdge||e.length<2||e.some(_=>_.termination.type!=="boundary"||_.connections.length<=2||_.componentId!==a.componentId||_.exitEdge!==a.exitEdge||_.connections.some(f=>f.sourceLayer!=="top")))return!1;const A=_=>_.routableEscapeLayers??_.allowedLayers??i;if(n==="top"||e.some(_=>!A(_).includes(n))||!i.some(_=>_!=="top"&&_!==n&&e.every(f=>A(f).includes(_))))return!1;const c=e.flatMap(_=>_.connections),l=a.exitEdge==="left"||a.exitEdge==="right"?"y":"x",u=c.map(_=>o.get(_.connectionIndex)?.[l]);if(u.some(_=>_===void 0||!Number.isFinite(_))||Math.max(...u)-Math.min(...u)>=(c.length-1)*(r+s)-1e-8)return!1;const h=c.reduce((_,f)=>({x:_.x+f.sourcePoint.x/c.length,y:_.y+f.sourcePoint.y/c.length}),{x:0,y:0}),d=a.componentBounds,p=Math.min(Math.abs(h.x-d.minX),Math.abs(h.x-d.maxX)),m=Math.min(Math.abs(h.y-d.minY),Math.abs(h.y-d.maxY));return l==="x"?p+1e-8<m:m+1e-8<p}function UQo(t){const e=t.length*(t.length-1)/2;if(e===0)return!1;let n=0;for(let o=0;o<t.length;o++){const i=t[o];for(const r of t.slice(o+1))if(tu(i.source,i.target,r.source,r.target)<1e-7&&++n>e/2)return!0}return!1}var KQo=class{constructor(t){this.options=t,this.pending=[t.preferSourceTransit?{ripCost:t.sourceTransitRipCost??8,shuffleSeed:1,transitLayers:t.allTransitLayers}:{ripCost:t.firstRipCost,shuffleSeed:1,transitLayers:t.transitLayers}],t.preferAlternateOrder&&(this.originalOrder=this.pending[0],this.preferredOrder={...this.originalOrder,shuffleSeed:2},this.pending[0]=this.preferredOrder),t.preferSourceOrigin&&this.pending.unshift({ripCost:t.sourceOriginRipCost??256,shuffleSeed:1,transitLayers:[],routeFromSourcePads:!0})}options;pending;attempted=new Set;preferredOrder;originalOrder;next(){for(;this.pending.length>0;){const t=this.pending.shift(),e=JSON.stringify(t);if(!this.attempted.has(e))return this.attempted.add(e),t}}failed(t,e){if(t.routeFromSourcePads)return;const n=o=>{this.attempted.has(JSON.stringify(o))||this.pending.unshift(o)};if(t===this.preferredOrder){n(this.originalOrder),e==="lengths"&&this.pending.push({...this.originalOrder,ripCost:256});return}if(t.sourceLayerTravelCost!==void 0){const{reserveFutureApproaches:o,sourceLayerTravelCost:i,maximumSourceIterations:r,...s}=t;o===!1&&e==="routing"?n({...s,sourceLayerTravelCost:4,reserveFutureApproaches:!0}):this.failed(s,"lengths");return}if(t.sourceOriginPhysicalGridPhase){const{sourceOriginPhysicalGridPhase:o,...i}=t;n({...i,ripCost:256,shuffleSeed:1});return}if(this.options.preferSourceTransit&&t.ripCost===(this.options.sourceTransitRipCost??8)&&t.transitLayers.length===this.options.allTransitLayers.length)n({ripCost:this.options.firstRipCost,shuffleSeed:1,transitLayers:this.options.transitLayers});else if(this.options.wideSingleLayer){if(e==="lengths"&&t.ripCost===64){const o={...t,shuffleSeed:1,sourceLayerTravelCost:3,maximumSourceIterations:2e7,reserveFutureApproaches:!1},i={...t,shuffleSeed:1,sourceOriginPhysicalGridPhase:!0};this.options.retrySourceOriginFreshReservations&&!this.attempted.has(JSON.stringify(o))?n(o):this.options.retrySourceOriginPhysicalGridPhase&&!this.attempted.has(JSON.stringify(i))?n(i):n({...t,ripCost:256,shuffleSeed:1})}e==="routing"&&t.shuffleSeed===1&&n({...t,ripCost:64,shuffleSeed:2})}else if(t.transitLayers.length<this.options.allTransitLayers.length){const o={ripCost:e==="lengths"?8:this.options.firstRipCost,shuffleSeed:1,transitLayers:this.options.allTransitLayers};e==="routing"&&o.ripCost!==256&&this.attempted.has(JSON.stringify(o))?n({...o,ripCost:256}):n(o)}else e==="routing"&&t.ripCost!==256&&n({...t,ripCost:256})}};function VQo(t){const e=t.traceWidth+t.clearance;if(!Number.isFinite(e)||!(t.traceWidth>0)||t.clearance<0)throw new Error("Boundary approach reservations require valid trace rules");return t.buses.filter(n=>n.termination.type==="boundary"&&!t.excludedBusIds.has(n.busId)).flatMap(n=>{const o=t.targetLayerByBusId.get(n.busId);if(!o||!n.exitEdge)throw new Error(`Missing boundary approach layer or edge for ${n.busId}`);return n.connections.map(i=>{const r=t.exits.get(i.connectionIndex);if(!r)throw new Error(`Missing boundary approach target for ${i.connectionIndex}`);const s={...r};return n.exitEdge==="bottom"?s.y+=e:n.exitEdge==="top"?s.y-=e:n.exitEdge==="left"?s.x+=e:s.x-=e,{type:"pcb_trace",pcb_trace_id:`fanout-approach-reservation:${i.connectionIndex}`,connection_name:i.connection.name,route:[s,r].map(a=>({route_type:"wire",...a,layer:o,width:t.traceWidth}))}})})}function zQo(t){const e={minX:1/0,maxX:-1/0,minY:1/0,maxY:-1/0};for(const n of t){const o=n,i=(o.ccwRotationDegrees??0)*Math.PI/180,r=n.width/2,s=n.height/2,a=o.shape==="circle"?r:Math.abs(Math.cos(i))*r+Math.abs(Math.sin(i))*s,A=o.shape==="circle"?s:Math.abs(Math.sin(i))*r+Math.abs(Math.cos(i))*s;e.minX=Math.min(e.minX,n.center.x-a),e.maxX=Math.max(e.maxX,n.center.x+a),e.minY=Math.min(e.minY,n.center.y-A),e.maxY=Math.max(e.maxY,n.center.y+A)}return e}function JQo(t,e){const n=t.filter(g=>g.termination.type==="boundary"),o=n[0]?.exitEdge;if(!o||n.some(g=>g.exitEdge!==o))return[...t];const i=n.flatMap(g=>g.connections),r={x:(e.minX+e.maxX)/2,y:(e.minY+e.maxY)/2},s=i.reduce((g,h)=>g+h.sourcePoint.x-r.x,0),a=i.reduce((g,h)=>g+h.sourcePoint.y-r.y,0);if(Math.hypot(s,a)<1e-9)return[...t];const A=["right","up","left","down"],c=Math.abs(s)>=Math.abs(a)?s>=0?"right":"left":a>=0?"up":"down",l=o==="top"?"up":o==="bottom"?"down":o,u=A.indexOf(c)-A.indexOf(l);return t.map(g=>g.termination.type==="plane"?g:{...g,direction:A[(A.indexOf(g.direction)+u+4)%4]})}function WQo(t){return t.flatMap(e=>{const n=[e.connectionName],o=[e.sourceLayer],i=[];e.via&&i.push({type:"rect",shape:"circle",center:e.via.center,width:e.via.diameter,height:e.via.diameter,connectedTo:n,layers:o});for(const r of e.segments){const{start:s,end:a,width:A}=r,c=a.x-s.x,l=a.y-s.y;i.push({type:"rect",center:{x:(s.x+a.x)/2,y:(s.y+a.y)/2},width:Math.hypot(c,l),height:A,ccwRotationDegrees:Math.atan2(l,c)*180/Math.PI,connectedTo:n,layers:o})}for(const r of[e.sourcePoint,...e.segments.map(s=>s.end)])i.push({type:"rect",shape:"circle",center:r,width:e.segments[0]?.width??0,height:e.segments[0]?.width??0,connectedTo:n,layers:o});return i})}function*jQo(t){const{srj:e,buses:n,layerNames:o,traceWidth:i,clearance:r,viaDiameter:s,viaHoleDiameter:a}=t,A=n[0];if(!A||n.some(k=>k.componentId!==A.componentId||k.connections.some(R=>R.sourceLayer!=="top")))return null;const c=A.componentObstacles.filter(k=>k.layers.includes("top"));if(!c.length)return null;const l=zQo(c),u=Math.max(A.pitchX,A.pitchY),g=i+r;if(!Number.isFinite(u)||u<=0)return null;const h={x:(l.minX+l.maxX)/2,y:(l.minY+l.maxY)/2},d=Math.ceil(((l.maxX-l.minX)/2+u+g)/g)*g,p=Math.ceil(((l.maxY-l.minY)/2+u+g)/g)*g,m={minX:h.x-d,maxX:h.x+d,minY:h.y-p,maxY:h.y+p};if(n.some(k=>m.minX<=k.sharedBoundary.minX||m.maxX>=k.sharedBoundary.maxX||m.minY<=k.sharedBoundary.minY||m.maxY>=k.sharedBoundary.maxY))return null;const _=new Map;for(const k of n){if(k.termination.type!=="boundary"||k.allowedLayers?.length!==1||k.allowedLayers[0]==="top")continue;const R=k.allowedLayers[0];_.set(R,[..._.get(R)??[],k])}const f=[..._].sort(([k,R],[F,O])=>Math.max(...O.map(U=>U.connections.length))-Math.max(...R.map(U=>U.connections.length))||k.localeCompare(F));if(!f.length)return null;const I=new Map(n.flatMap(k=>k.connections.map(R=>[R.connectionIndex,{bus:k,connection:R}])));if(I.size!==n.reduce((k,R)=>k+R.connections.length,0))throw new Error("FanoutSolver: source preparation requires unique connection indices");const C=JQo(n,l),y={traceWidth:i,clearance:r,viaDiameter:s,viaHoleDiameter:a,maximumSearchStates:t.maximumSearchStates??1e4,additionalObstacles:e.obstacles},x=t.initialViaPointsByConnectionIndex;if(x&&(x.size!==I.size||[...x].some(([k,R])=>!I.has(k)||!Number.isFinite(R.x)||!Number.isFinite(R.y))))throw new Error("FanoutSolver: initial source sites must contain every connection exactly once");const E=pd(C,{...y,fixedViaPointsByConnectionIndex:x});if(!E)return null;const B=(k,R,F)=>{const{bus:O,connection:U}=I.get(k),Y=O.termination.type==="plane"?O.termination.layer:(O.allowedLayers??o).filter(W=>W!==U.sourceLayer).at(-1);if(!Y)throw new Error("FanoutSolver: source through-via preparation requires a non-source target layer");return i4({...t,allowBlindAndBuriedVias:!1,bus:O,terminal:{connection:U,viaPoint:R,exitPoint:R},targetLayer:Y,targetLayerPoints:[R],sourceEscapePoints:F})},S=(k,R)=>[...I.keys()].map(F=>B(F,k.get(F),R.get(F))),Q=k=>qu({inputSrj:e,routedSrj:{...e,traces:[...e.traces??[],...k.map(R=>R.trace)]},clearance:r,allowBlindAndBuriedVias:!1}).valid;let w={sourceBoundary:m,fixedViaPointsByConnectionIndex:E,sourceEscapePaths:new Map([...E].map(([k,R])=>[k,[I.get(k).connection.sourcePoint,R]])),sourcePlans:[],prefixPlans:[],remotePlans:[],layerGroups:[]};if(w.sourcePlans=S(E,w.sourceEscapePaths),!Q(w.sourcePlans))return null;const M=Math.max(u,s/2+i/2+r);for(const[k,R]of f){const F=new Set(R.flatMap(ie=>ie.connections.map(ne=>ne.connectionIndex))),O=new Set(w.remotePlans.map(ie=>ie.connectionIndex)),U=new Map([...w.fixedViaPointsByConnectionIndex].filter(([ie])=>!F.has(ie)&&!O.has(ie))),Y={...e,obstacles:[...e.obstacles,...WQo(w.sourcePlans.filter(ie=>!F.has(ie.connectionIndex)))]},W=R.flatMap(ie=>ie.connections.map(ne=>({...ie,busId:`${ie.busId}:source-${ne.connectionIndex}`,sharedBoundary:m,preferredExit:void 0,exitEdge:void 0,connections:[{...ne,exitTargetPoint:void 0,hasExplicitLayeredExitTarget:!1}]})));let te=null,j=0;const J=ie=>{if(ie.length<=j)return;const ne=ie.map(ve=>({...ve,busId:I.get(ve.connectionIndex).bus.busId,sourceObstacle:I.get(ve.connectionIndex).connection.sourceObstacle,sourceEscapeSegmentCount:ve.segments.length}));if(!Wh({plans:ne,srj:Y,sharedBoundary:m,clearance:r,allowBlindAndBuriedVias:!1,allowSameNetMerges:!1}))return;const le=[],ge=new Map;for(const ve of ne){const he=ve.exitPoint,Qe=Math.abs(he.x-m.maxX)<1e-7?{x:M,y:0}:Math.abs(he.x-m.minX)<1e-7?{x:-M,y:0}:Math.abs(he.y-m.maxY)<1e-7?{x:0,y:M}:Math.abs(he.y-m.minY)<1e-7?{x:0,y:-M}:null;if(!Qe)throw new Error("FanoutSolver: source prefix does not end on its source boundary");const Pe={x:he.x+Qe.x,y:he.y+Qe.y},we=I.get(ve.connectionIndex).bus.sharedBoundary;if(Pe.x<we.minX||Pe.x>we.maxX||Pe.y<we.minY||Pe.y>we.maxY)return;const Te=[ve.sourcePoint,...ve.segments.map(Re=>Re.end),Pe];ge.set(ve.connectionIndex,Te),le.push(B(ve.connectionIndex,Pe,Te))}const _e=[...w.remotePlans,...le];if(!Q(_e))return;const ue=new Set(_e.map(ve=>ve.connectionIndex)),fe=C.map(ve=>({...ve,connections:ve.connections.filter(he=>!ue.has(he.connectionIndex))})).filter(ve=>ve.connections.length),pe=pd(fe,{...y,fixedViaPointsByConnectionIndex:U,preferredViaPointsByConnectionIndex:w.fixedViaPointsByConnectionIndex,blockingSegments:_e.flatMap(ve=>ve.segments.map(he=>({connectionIndex:ve.connectionIndex,segment:he}))),blockingVias:_e.map(ve=>({connectionIndex:ve.connectionIndex,center:ve.via.center,diameter:ve.via.diameter,spanLayers:ve.via.spanLayers}))});if(!pe)return;const ye=new Map([...pe,..._e.map(ve=>[ve.connectionIndex,ve.via.center])]);if(ye.size!==I.size)throw new Error("FanoutSolver: source preparation lost a connection");for(const ve of O)ge.set(ve,w.sourceEscapePaths.get(ve));for(const[ve,he]of pe)ge.set(ve,[I.get(ve).connection.sourcePoint,he]);const Me=S(ye,ge);Q(Me)&&(j=ie.length,te={sourceBoundary:m,fixedViaPointsByConnectionIndex:ye,sourceEscapePaths:ge,sourcePlans:Me,prefixPlans:[...w.prefixPlans,...ne],remotePlans:_e,layerGroups:[...w.layerGroups,{layer:k,connectionCount:F.size,escapedCount:ie.length}]})},oe=yield*AR({srj:Y,buses:W,traceWidth:i,clearance:r,onPartialRoutes:J});oe&&J(oe),te?w=te:w.layerGroups.push({layer:k,connectionCount:F.size,escapedCount:0})}return w.remotePlans.length?w:null}function $Qo(t,e){return t.some(n=>{if(!cue([n]))return!1;const o=n.exitEdge==="left"||n.exitEdge==="right"?"x":"y",i=o==="x"?"y":"x",r=n.exitEdge==="left"||n.exitEdge==="bottom"?-1:1,s=o==="x"?(n.componentBounds.minX+n.componentBounds.maxX)/2:(n.componentBounds.minY+n.componentBounds.maxY)/2,a=n.connections.map(A=>e.get(A.connectionIndex)?.[i]);return a.some(A=>A===void 0||!Number.isFinite(A))?!1:t.some(A=>{if(A.termination.type!=="boundary"||A.connections.length!==2||A.componentId!==n.componentId||A.exitEdge!==n.exitEdge||A.allowedLayers?.length!==1||A.allowedLayers[0]===n.allowedLayers[0]||!A.connections.every(u=>r*(u.sourcePoint[o]-s)<-1e-7))return!1;const c=A.connections.map(u=>e.get(u.connectionIndex)?.[i]);if(c.some(u=>u===void 0||!Number.isFinite(u)))return!1;const l=A.connections.flatMap(u=>{const g=u.sourceObstacle?.center[i]??u.sourcePoint[i],h=((i==="x"?u.sourceObstacle?.width:u.sourceObstacle?.height)??0)/2;return[g-h,g+h]});return Math.max(Math.min(...a),Math.min(...c),Math.min(...l))<=Math.min(Math.max(...a),Math.max(...c),Math.max(...l))})})}function qQo(t,e){return t.some(n=>{if(!cue([n]))return!1;const o=n.exitEdge==="left"||n.exitEdge==="right"?"y":"x",i=n.connections.map(a=>e.get(a.connectionIndex)?.[o]);if(i.some(a=>a===void 0||!Number.isFinite(a)))return!1;const r=o==="x"?n.componentBounds.minX:n.componentBounds.minY,s=o==="x"?n.componentBounds.maxX:n.componentBounds.maxY;return Math.min(...i)<=s+1e-7&&Math.max(...i)>=r-1e-7})}var i6=1e-6,A$=t=>Math.max(...t.map(e=>e.length))-Math.min(...t.map(e=>e.length));function XQo(t,e){const n=t.trace.route.findIndex(r=>r.route_type==="via"),o=e.trace.route.findIndex(r=>r.route_type==="via");if(n<0||o<0)return null;const i=[...t.trace.route.slice(0,n+1),...e.trace.route.slice(o+1)];return i[i.length-1]=t.trace.route.at(-1),{...t,trace:{...t.trace,route:i},segments:[...t.segments.slice(0,t.sourceEscapeSegmentCount??1),...e.segments.slice(e.sourceEscapeSegmentCount??1)],length:e.length}}function*ZQo(t){const{inputSrj:e,preparedBuses:n,layerNames:o,traceWidth:i,clearance:r,viaDiameter:s,viaHoleDiameter:a,maximumPasses:A=3,maximumConnectionAttempts:c=24,maximumSearchStates:l=12e5}=t;for(const[B,S]of[["maximumPasses",A],["maximumConnectionAttempts",c],["maximumSearchStates",l]])if(!Number.isSafeInteger(S)||S<1)throw new Error(`FanoutSolver: ${B} must be a positive safe integer`);const u=new Map(t.plans.map(B=>[B.connectionIndex,B])),g=n.flatMap(B=>B.connections);if(u.size!==t.plans.length||u.size!==e.connections.length||g.length!==u.size||g.some(B=>u.get(B.connectionIndex)?.connectionName!==B.connection.name))throw new Error("FanoutSolver: overlong-lane rerouting requires every original plan");const h=n.filter(B=>B.termination.type==="boundary"&&(!t.selectedBusIds||t.selectedBusIds.has(B.busId))),d=h.filter(B=>B.maxLengthSkew!==void 0&&B.connections.length>1);let p=[...t.plans];const m=new Map;for(const B of p){if(!B.via)continue;const S=B.segments.slice(0,B.sourceEscapeSegmentCount??1);!S.length||S.some(Q=>Q.layer!==B.sourceLayer)||tn(S[0].start,B.sourcePoint)>i6||tn(S.at(-1).end,B.via.center)>i6||S.some((Q,w)=>w>0&&tn(S[w-1].end,Q.start)>i6)||m.set(B.connectionIndex,[S[0].start,...S.map(Q=>Q.end)])}const _=new Map,f=(i+r)/2;let I=0,C=!1;const y=(B,S)=>{const Q=B.via;return!!(Q&&!(B.additionalVias?.length??0)&&!B.planeEndpointTrace&&!B.planeEndpointVia&&m.has(B.connectionIndex)&&Q.fromLayer===B.sourceLayer&&Q.toLayer===B.targetLayer&&Q.diameter===s&&Q.holeDiameter===a&&Q.spanLayers.length===o.length&&o.every(w=>Q.spanLayers.includes(w))&&(S.routableEscapeLayers??S.allowedLayers??o).includes(B.targetLayer)&&B.segments.slice(B.sourceEscapeSegmentCount??1).every(w=>w.layer===B.targetLayer))};function*x(B,S,Q,w,M){if(I>=c||!y(B,Q))return null;I++;const k=BC({srj:e,bus:Q,targetLayer:B.targetLayer,terminals:[{connection:Q.connections.find(O=>O.connectionIndex===B.connectionIndex),viaPoint:B.via.center,exitPoint:B.exitPoint}],acceptedPlans:S.filter(O=>O.connectionIndex!==B.connectionIndex),layerNames:o,traceWidth:i,clearance:r,viaDiameter:s,viaHoleDiameter:a,allowBlindAndBuriedVias:!1,sourceEscapePaths:m,gridStepDivisor:2,gridStep:f,gridOrigin:w,alignGridToPads:!0,heuristicWeight:1,maximumRouteOrderAttempts:1,maximumSearchStates:l,preferTargetDirectedLaneBias:!0},1,!1);let R=k.next();for(;!R.done;)yield{...R.value,busId:Q.busId,pass:M,connectionAttempt:I},R=k.next();const F=R.value[0]?.[0];return F?XQo(B,F):null}for(const B of d){let S=p.filter(M=>M.busId===B.busId);const Q=A$(S);if(Q<=B.maxLengthSkew+i6)continue;const w=[...p];for(let M=0;M<A;M++){const k=Math.min(...S.map(O=>O.length));let R=!1;const F=S.filter(O=>O.length>k+B.maxLengthSkew+i6).toSorted((O,U)=>U.length-O.length||O.connectionIndex-U.connectionIndex);for(const O of F){if(I>=c)break;const U=O.targetLayer;if(!y(O,B))continue;let Y=_.get(U);Y||(Y=LPe({vias:p.flatMap(J=>[J.via,...J.additionalVias??[],J.planeEndpointVia].filter(oe=>oe?.spanLayers.includes(U)).map(oe=>({connectionIndex:J.connectionIndex,center:oe.center,diameter:oe.diameter}))),activeConnectionIndices:new Set(h.flatMap(J=>J.connections.filter(oe=>u.get(oe.connectionIndex)?.targetLayer===U).map(oe=>oe.connectionIndex))),traceWidth:i,clearance:r,gridStep:f}),_.set(U,Y));const W=yield*x(O,p,B,Y,M);if(!W||W.length>=O.length-i6)continue;const te=p.filter(J=>J.busId===B.busId),j=te.map(J=>J.connectionIndex===O.connectionIndex?W:J);if(A$(j)>A$(te)+i6){if(te.length!==2)continue;const J=te.find(ne=>ne!==O);if(J.targetLayer!==U)continue;const oe=p.map(ne=>ne===O?W:ne),ie=yield*x(J,oe,B,Y,M);if(!ie||ie.length>=J.length-i6||A$([W,ie])>B.maxLengthSkew+i6)continue;p=oe.map(ne=>ne===J?ie:ne)}else p=p.map(J=>J===O?W:J);R=!0}if(S=p.filter(O=>O.busId===B.busId),!R||I>=c)break}if(A$(S)<Q-i6?C=!0:p=w,I>=c)break}return C?qu({inputSrj:e,routedSrj:{...e,traces:[...e.traces??[],...p.flatMap(B=>[B.trace,...B.planeEndpointTrace?[B.planeEndpointTrace]:[]])]},clearance:r,allowBlindAndBuriedVias:!1}).valid?p:null:p}var yw=1e-6,fue=t=>Math.max(...t.map(e=>e.length))-Math.min(...t.map(e=>e.length));function*evo(t){const{inputSrj:e,preparedBuses:n,layerNames:o,traceWidth:i,clearance:r,viaDiameter:s,viaHoleDiameter:a,maximumConnectionAttempts:A=8,maximumIterationsPerConnection:c=3e7}=t;for(const[I,C]of[["maximumConnectionAttempts",A],["maximumIterationsPerConnection",c]])if(!Number.isSafeInteger(C)||C<1)throw new Error(`FanoutSolver: ${I} must be a positive safe integer`);const l=new Map(t.plans.map(I=>[I.connectionIndex,I])),u=n.flatMap(I=>I.connections);if(u.length!==e.connections.length||l.size!==t.plans.length||l.size!==u.length||u.some(I=>l.get(I.connectionIndex)?.connectionName!==I.connection.name))throw new Error("FanoutSolver: transit length repair requires every original plan");const g=n.filter(I=>I.termination.type==="boundary"&&I.maxLengthSkew!==void 0&&I.connections.length>1&&(!t.busIds||t.busIds.includes(I.busId)));let h=[...t.plans];const d=g.filter(I=>fue(h.filter(C=>C.busId===I.busId))>I.maxLengthSkew+yw);if(!d.length)return h;const p=new Map,m=new Map;for(const I of u){const C=l.get(I.connectionIndex);if(!C.via)return null;const y=C.segments.slice(0,C.sourceEscapeSegmentCount??1);if(!y.length||y.some(x=>x.layer!==I.sourceLayer)||tn(y[0].start,I.sourcePoint)>yw||tn(y.at(-1).end,C.via.center)>yw||y.some((x,E)=>E>0&&tn(y[E-1].end,x.start)>yw))return null;p.set(I.connectionIndex,C.via.center),m.set(I.connectionIndex,[y[0].start,...y.map(x=>x.end)])}let _=0;for(const I of d){let C=h.filter(S=>S.busId===I.busId);if(C.length!==I.connections.length)return null;const y=C[0].targetLayer,x=I.routableEscapeLayers??I.allowedLayers??o,E=x.filter(S=>S!==y);if(!x.includes(y)||!E.length||C.some(S=>S.targetLayer!==y))return null;const B=new Set;for(;fue(C)>I.maxLengthSkew+yw;){const S=Math.min(...C.map(j=>j.length)),Q=C.filter(j=>!B.has(j.connectionIndex)&&j.length>S+I.maxLengthSkew+yw).toSorted((j,J)=>J.length-j.length||j.connectionIndex-J.connectionIndex)[0];if(!Q||_>=A)return null;B.add(Q.connectionIndex);const w=Q.via;if(Q.planeEndpointTrace!==void 0||Q.planeEndpointSegments!==void 0||Q.planeEndpointVia!==void 0||w.fromLayer!==Q.sourceLayer||w.toLayer!==y||w.diameter!==s||w.holeDiameter!==a||w.spanLayers.length!==o.length||!o.every(j=>w.spanLayers.includes(j)))continue;const M=I.connections.find(j=>j.connectionIndex===Q.connectionIndex);_++;const k=AE({srj:e,allBuses:n,buses:[{...I,connections:[M]}],targetLayer:y,transitLayers:E,terminals:[{connection:M,viaPoint:w.center,exitPoint:Q.exitPoint}],fixedViaPointsByConnectionIndex:p,sourceEscapePaths:m,acceptedPlans:h.filter(j=>j!==Q),layerNames:o,traceWidth:i,clearance:r,viaDiameter:s,viaHoleDiameter:a,tightViaChannels:!0,ripCost:64,shuffleSeed:1,maximumRipEvents:1,maximumIterations:c});let R=k.next();for(;!R.done;)yield{...R.value,busId:I.busId,connectionName:Q.connectionName,connectionAttempt:_},R=k.next();const F=R.value?.[0];if(!F||F.length>=Q.length-yw)continue;const O=Q.sourceEscapeSegmentCount??1,U=Q.trace.route.findIndex(j=>j.route_type==="via"),Y=F.trace.route.findIndex(j=>j.route_type==="via");if(U<0||Y<0)return null;const W={...Q,via:w,additionalVias:F.additionalVias,segments:[...Q.segments.slice(0,O),...F.segments.slice(F.sourceEscapeSegmentCount??1)],trace:{...Q.trace,route:[...Q.trace.route.slice(0,U+1),...F.trace.route.slice(Y+1)]},length:F.length},te=C.map(j=>j===Q?W:j);fue(te)>fue(C)+yw||(h=h.map(j=>j===Q?W:j),C=te)}}return qu({inputSrj:e,routedSrj:{...e,traces:[...e.traces??[],...h.flatMap(I=>[I.trace,...I.planeEndpointTrace?[I.planeEndpointTrace]:[]])]},clearance:r,allowBlindAndBuriedVias:!1}).valid?h:null}function eRt(t){const{buses:e,layerNames:n,traceWidth:o,clearance:i}=t,r=e.filter(d=>d.termination.type==="boundary"),s=new Map;for(const d of r)if(d.allowedLayers?.length===1){const p=d.allowedLayers[0];s.set(p,(s.get(p)??0)+d.connections.length)}const a=new Map;for(const d of e){const p=new Set(d.connections.map(f=>f.sourceLayer)),m=(d.routableEscapeLayers??d.allowedLayers??n).filter(f=>!p.has(f)).toSorted((f,I)=>(s.get(f)??0)-(s.get(I)??0)||n.indexOf(I)-n.indexOf(f)),_=d.termination.type==="plane"?d.termination.layer:m[0];if(!_)return null;a.set(d.busId,_)}const A=VPe({...t,targetLayerByBusId:a}),c=new Map(A.tracksByConnectionIndex),l=QNt(e),u=d=>d.exitEdge==="left"||d.exitEdge==="right"?"y":"x",g=o+i;for(const d of r){if(d.allowedLayers?.length!==1)continue;const p=u(d),m=d.sharedBoundary,_=p==="y"?m.minY:m.minX,f=p==="y"?m.maxY:m.maxX,I=d.connections.map(S=>(S.exitTargetPoint??S.targetPoint)[p]),C=I.toSorted((S,Q)=>S-Q);if(C.some((S,Q)=>!Number.isFinite(S)||Q>0&&S-C[Q-1]<g-1e-8))continue;const y=C.at(-1)-C[0];if(y>f-_)continue;let x;if(l.has(d.busId))if(d.connections.length===2){const S=d.connections.map(M=>c.get(M.connectionIndex)),Q=(S[0]+S[1])/2,w=Math.abs(S[1]-S[0]);x=S.map(M=>Q+(M-Q)*y/w)}else continue;else{const S=Math.max(_-C[0],Math.min(0,f-C.at(-1)));x=I.map(Q=>Q+S)}const E=new Set(d.connections.map(S=>S.connectionIndex)),B=r.filter(S=>S.exitEdge===d.exitEdge&&a.get(S.busId)===a.get(d.busId)).flatMap(S=>S.connections.filter(Q=>!E.has(Q.connectionIndex)).map(Q=>c.get(Q.connectionIndex)));if(!x.some(S=>S<_||S>f||B.some(Q=>Math.abs(S-Q)<g-1e-8)))for(const[S,Q]of d.connections.entries())c.set(Q.connectionIndex,x[S])}const h=new Map;for(const d of r)for(const p of d.connections){const m=c.get(p.connectionIndex),_=d.sharedBoundary,f=d.exitEdge==="left"?{x:_.minX,y:m}:d.exitEdge==="right"?{x:_.maxX,y:m}:d.exitEdge==="top"?{x:m,y:_.maxY}:{x:m,y:_.minY};h.set(p.connectionIndex,f)}return{targetLayerByBusId:a,exits:h}}function*tvo(t){const e=new Set;let n;const o=()=>XPe(t,{reserveFutureApproaches:!1,failedNarrowGroup:!1,failedWideMatching:!1},e,{travelCost:3,maximumIterations:2e7});let i=!1;if(t.sourceOriginRouting&&YPe(t.buses)){const s=eRt(t),a={requested:!!s&&qQo(t.buses,s.exits),reached:!1},A=XPe({...t,sourceOriginRouting:!1},{reserveFutureApproaches:!0,failedNarrowGroup:!1,failedWideMatching:!1},e,void 0,a);let c=A.next();for(;!c.done&&!a.reached;)yield c.value,c=A.next();if(c.done){if(c.value)return c.value}else n=A;if(cue(t.buses)&&(i=!!s&&$Qo(t.buses,s.exits),!i)){const l=yield*o();if(l)return l}}let r=yield*HQo(t.sourceOriginRouting??!1,s=>XPe(t,s,e));return!r&&i&&(r=yield*o()),r||(n?yield*n:null)}function*XPe(t,e,n,o,i){const{buses:r,srj:s,layerNames:a}=t,A=eRt(t);if(!A)return null;const c=t.sourceOriginRouting?(function*(){return SSo(t)})():jQo(t);let l=c.next();for(;!l.done;)yield{phase:"sources",routedConnectionCount:0},l=c.next();if(!l.value)return null;const{fixedViaPointsByConnectionIndex:u,sourceEscapePaths:g,sourcePlans:h}=l.value;let d=[];const p=new Set(r.filter(x=>x.termination.type==="plane").map(x=>x.busId)),m=new Map;for(const x of r)if(x.termination.type==="boundary"){const E=A.targetLayerByBusId.get(x.busId);m.set(E,[...m.get(E)??[],x])}const _=[...m].sort(([,x],[,E])=>Math.max(...x.map(B=>B.allowedLayers?.length??a.length))-Math.max(...E.map(B=>B.allowedLayers?.length??a.length))||Math.max(...E.map(B=>B.connections.length))-Math.max(...x.map(B=>B.connections.length))),f=OQo({groups:_.map(([,x])=>x),fixedViaPointsByConnectionIndex:u,clearance:t.clearance}),I=t.sourceOriginRouting&&YPe(r),C=I&&!o&&cue(r);let y=!1;for(const[x,E]of _){if(C&&x===_.at(-1)[0]){const ie=zPe({buses:E,exits:A.exits});for(const[ne,le]of ie)A.exits.set(ne,le)}const B=Math.max(...E.map(ie=>ie.connections.length)),S=B>2&&E.every(ie=>ie.allowedLayers?.length===1),Q=a.filter(ie=>ie!==x&&E.every(ne=>(ne.routableEscapeLayers??ne.allowedLayers??a).includes(ie)&&ne.connections.every(le=>le.sourceLayer!==ie))),w=a.filter(ie=>ie!==x&&E.every(ne=>(ne.routableEscapeLayers??ne.allowedLayers??a).includes(ie))),M=qNt({buses:E,fixedViaPointsByConnectionIndex:u,clearance:t.clearance}),k=y&&B>2&&Q.length===0&&w.length>0,R=y&&B>2&&Q.length>0,F=C&&B>2&&Q.length===0&&w.length>0,O=d,U=t.sourceOriginRouting&&x===_[0][0]&&S,Y=new KQo({wideSingleLayer:S,retrySourceOriginPhysicalGridPhase:U&&!o,retrySourceOriginFreshReservations:U&&!o&&e.reserveFutureApproaches,preferAlternateOrder:!t.sourceOriginRouting&&S&&x===_[0][0]&&f.some(ie=>E.every(ne=>ie.every(le=>le.componentId===ne.componentId&&le.exitEdge===ne.exitEdge)))||I&&!S&&B>2&&Q.length>0&&x===_.at(-1)[0],firstRipCost:B<=2?256:64,transitLayers:Q,allTransitLayers:w,sourceOriginRipCost:R?64:256,sourceTransitRipCost:k?64:8,preferSourceOrigin:M||I&&B<=2&&O.length>0||R||YQo({...t,buses:E,targetLayer:x,exits:A.exits}),preferSourceTransit:!F&&(k||B>2&&Q.length===0&&w.length>0&&UQo(E.flatMap(ie=>ie.connections.map(ne=>({source:u.get(ne.connectionIndex),target:A.exits.get(ne.connectionIndex)})))))});let W=!1,te=!1,j=0;const J={sites:new Map(u),paths:new Map(g),plans:[...h]},oe=ie=>{u.clear();for(const[ne,le]of ie.sites)u.set(ne,le);g.clear();for(const[ne,le]of ie.paths)g.set(ne,le);h.splice(0,h.length,...ie.plans)};for(let ie=Y.next();ie;ie=Y.next()){const ne=j++===0;d=O;for(const Ce of E)p.delete(Ce.busId);const le=ie.sourceOriginPhysicalGridPhase||ie.sourceLayerTravelCost!==void 0?{sites:new Map(u),paths:new Map(g),plans:[...h]}:void 0,ge=()=>{le&&oe(le)};ie.sourceLayerTravelCost!==void 0&&oe(J);const _e=ie.routeFromSourcePads||ie.transitLayers.length<w.length,ue={...t,srj:U&&(ie.reserveFutureApproaches??e.reserveFutureApproaches)?{...s,traces:[...s.traces??[],...VQo({...t,...A,excludedBusIds:new Set(E.map(Ce=>Ce.busId))})]}:s,allBuses:r,buses:E,targetLayer:x,transitLayers:ie.transitLayers,fixedViaPointsByConnectionIndex:u,sourceEscapePaths:g,acceptedPlans:d,terminals:E.flatMap(Ce=>Ce.connections.map(Le=>({connection:Le,viaPoint:u.get(Le.connectionIndex),exitPoint:A.exits.get(Le.connectionIndex)}))),tightViaChannels:!0,heuristicWeight:F?2:void 0,ripCost:ie.ripCost,maximumRipEvents:400,maximumLocalRepairAttempts:_e?0:3,maximumIterations:1e8,shuffleSeed:ie.shuffleSeed,sourceOriginPhysicalGridPhase:ie.sourceOriginPhysicalGridPhase,sourceLayerTravelCost:ie.sourceLayerTravelCost??(U?o?.travelCost:void 0),maximumSourceIterations:ie.maximumSourceIterations??(U?o?.maximumIterations:void 0)},fe=(function*(){if(ie.routeFromSourcePads)return yield*AE({...ue,routeFromSourcePads:!0,sourceLayerTravelCost:2,maximumRipEvents:1200,maximumIterations:5e7,maximumLocalRepairAttempts:0});if(!U)return yield*AE(ue);const Ce=yield*QSo({...ue,cleanupRetainedBoundaryTails:ie.sourceOriginPhysicalGridPhase});if(!Ce)return null;u.clear();for(const[Le,Ye]of Ce.fixedViaPointsByConnectionIndex)u.set(Le,Ye);g.clear();for(const[Le,Ye]of Ce.sourceEscapePaths)g.set(Le,Ye);return h.splice(0,h.length,...Ce.sourcePlans),Ce.plans})();let pe=fe.next();for(;!pe.done;){if(i$(pe.value)){const Ce=yield pe.value;pe=fe.next(Ce);continue}yield{phase:"route-layer",layer:x,routedConnectionCount:d.length+pe.value.routedConnectionCount,iterations:pe.value.iterations},pe=fe.next()}const ye=pe.value;if(!ye){if(ge(),U&&!ie.sourceOriginPhysicalGridPhase&&ie.sourceLayerTravelCost===void 0)return e.failedWideMatching=te,null;Y.failed(ie,"routing"),i?.requested&&!t.sourceOriginRouting&&S&&x===_[0][0]&&ne&&ie.shuffleSeed===1&&!ie.routeFromSourcePads&&(i.requested=!1,i.reached=!0,yield{phase:"route-layer",layer:x,routedConnectionCount:d.length});continue}d=[...d,...ye];for(const Ce of E)p.add(Ce.busId);yield{phase:"match-layer",layer:x,routedConnectionCount:d.length};const Me=new Set(d.map(Ce=>Ce.connectionIndex));let ve=[...d,...h.filter(Ce=>!Me.has(Ce.connectionIndex))];const he=r.filter(Ce=>p.has(Ce.busId));ve=SO({...t,inputSrj:s,plans:ve,preparedBuses:he,selectedBusIds:new Set(E.map(Ce=>Ce.busId)),allowBlindAndBuriedVias:!1})??ve;let Qe=ie.routeFromSourcePads&&R,Pe=ie.routeFromSourcePads??!1;const we=t.sourceOriginRouting===!0&&B<=2&&O.length>0,Te=t.sourceOriginRouting&&S?r.filter(Ce=>Ce.termination.type==="boundary"&&!p.has(Ce.busId)):void 0,Re=Ce=>zy({...t,inputSrj:s,sharedBoundary:r[0].sharedBoundary,plans:ve,preparedBuses:he,allowBlindAndBuriedVias:!1,allowSameNetMerges:!1,allowMatchingInsideDenseBounds:!0,allowSourcePrefixMatching:Qe,allowPairLaneSpreading:!0,allowUnconstrainedLaneRerouting:!0,unroutedSourceBuses:Te,maximumWorkUnits:Ce});function*Ee(){const Ce=ZQo({...t,inputSrj:s,plans:ve,preparedBuses:r,selectedBusIds:new Set(E.map(Ye=>Ye.busId))});let Le=Ce.next();for(;!Le.done;)yield{phase:"repair-lengths",layer:x,routedConnectionCount:d.length},Le=Ce.next();ve=Le.value??ve}S&&(yield*Ee());let ke=Re(S?void 0:1e3);if(!ke.plans&&C&&B>2&&x===_.at(-1)[0]){const Ce=zy({...t,inputSrj:s,sharedBoundary:r[0].sharedBoundary,plans:ve,preparedBuses:he,allowBlindAndBuriedVias:!1,allowSameNetMerges:!1,allowMatchingInsideDenseBounds:!0,allowSourcePrefixMatching:!0,allowTransitLayerMatching:!0,allowDistributedMatching:!0,allowPairLaneSpreading:!0,allowUnconstrainedLaneRerouting:!0,maximumWorkUnits:1e5});Ce.plans&&(ke=Ce,Pe=!0)}if(!ke.plans&&!S&&!we&&(yield*Ee(),ke=Re(_e||(t.sourceOriginRouting||y)&&B>2?1e3:void 0)),!ke.plans&&we&&I&&ie.routeFromSourcePads){const Ce=Qe;Qe=!0;const Le=Re(1e3);Le.plans?ke=Le:Qe=Ce}if(!ke.plans&&(we||ke.failedBus&&ie.routeFromSourcePads&&(M||R))){const Ce=ve,Le=Qe,Ye=Pe,tt=new Set,At=we?E.filter(at=>at.connections.length===2).length:1;for(let at=0;at<At&&!(!ke.failedBus||ke.plans);at++){const nt=ke.failedBus;if(we){if(nt.connections.length!==2||!E.some(Dt=>Dt.busId===nt.busId)||tt.has(nt.busId))break;tt.add(nt.busId)}const gt=wNt({...t,inputSrj:s,plans:ve,preparedBuses:r,bus:nt});let bt=gt.next();for(;!bt.done;)yield{phase:"repair-lengths",layer:x,routedConnectionCount:d.length,iterations:bt.value.iterations},bt=gt.next();if(!bt.value)break;ve=bt.value,Pe=!0,we&&(Qe=!0);const Ct=function*(){ve=SO({...t,inputSrj:s,plans:ve,preparedBuses:he,selectedBusIds:new Set(E.map(kt=>kt.busId)),allowBlindAndBuriedVias:!1})??ve;let Dt=Re(1e3);return!Dt.plans&&!we&&(yield*Ee(),Dt=Re(1e3)),Dt};ke=yield*Ct(),!ke.plans&&M&&(Qe=!0,ke=yield*Ct())}we&&!ke.plans&&(ve=Ce,Qe=Le,Pe=Ye,yield*Ee(),ke=Re())}if(!ke.plans&&t.sourceOriginRouting&&!S&&B>2&&x===_.at(-1)[0]){const Ce=ve,Le=ke,Ye=Qe,tt=Pe,At=AE({...ue,routeFromSourcePads:!0,transitLayers:[],sourceLayerTravelCost:2,ripCost:64,shuffleSeed:1,maximumIterations:3e7,maximumRipEvents:400,maximumLocalRepairAttempts:0});let at=At.next();for(;!at.done;){if(i$(at.value)){const nt=yield at.value;at=At.next(nt);continue}yield{phase:"repair-lengths",layer:x,routedConnectionCount:d.length,iterations:at.value.iterations},at=At.next()}at.value&&(ve=[...O,...at.value,...h.filter(nt=>!Me.has(nt.connectionIndex))],ve=SO({...t,inputSrj:s,plans:ve,preparedBuses:he,selectedBusIds:new Set(E.map(nt=>nt.busId)),allowBlindAndBuriedVias:!1})??ve,Qe=!0,ke=Re(1e3),Pe=!0),ke.plans||(ve=Ce,ke=Le,Qe=Ye,Pe=tt)}if(ke.plans)ve=ke.plans;else{if(o&&U)return null;if(te=!0,_e){ge(),Y.failed(ie,"lengths");continue}const Ce=evo({...t,inputSrj:s,plans:ve,preparedBuses:r,busIds:E.map(Ye=>Ye.busId)});let Le=Ce.next();for(;!Le.done;)yield{phase:"repair-lengths",layer:x,routedConnectionCount:d.length,iterations:Le.value.iterations},Le=Ce.next();if(Le.value)ve=Le.value;else{const Ye=bSo({...t,inputSrj:s,plans:ve,preparedBuses:r,busIds:E.map(At=>At.busId)});let tt=Ye.next();for(;!tt.done;)yield{phase:"repair-lengths",layer:x,routedConnectionCount:d.length,iterations:tt.value.iterations},tt=Ye.next();if(tt.value)ve=tt.value;else{const At=new Set(E.map(bt=>bt.busId)),at=t.sourceOriginRouting&&S&&E.every(bt=>!n.has(bt.busId))&&ZNt({plans:ve,completedBuses:he,selectedBusIds:At});if(at)for(const bt of E)n.add(bt.busId);const nt=at?GQo({...t,inputSrj:s,plans:ve,preparedBuses:r,completedBuses:he,selectedBusIds:At}):void 0;let gt=nt?.next();for(;gt&&!gt.done;)yield{phase:"repair-lengths",layer:x,routedConnectionCount:d.length,iterations:gt.value.iterations},gt=nt.next();if(!gt?.value){ge(),Y.failed(ie,"lengths");continue}ve=gt.value,Pe=!0}}}if(d=ve.filter(Ce=>Me.has(Ce.connectionIndex)),Pe||Te?.length){const Ce=new Map([...E,...Te??[]].flatMap(Le=>Le.connections.map(Ye=>{const tt=ve.find(nt=>nt.connectionIndex===Ye.connectionIndex);if(!tt.via)throw new Error("Source-origin routing lost its source reservation");const At=[Ye.sourcePoint,...tt.segments.slice(0,tt.sourceEscapeSegmentCount??1).map(nt=>nt.end)],at=i4({...t,bus:Le,terminal:{connection:Ye,viaPoint:tt.via.center,exitPoint:tt.via.center},targetLayer:tt.via.toLayer,targetLayerPoints:[tt.via.center],sourceEscapePoints:At,allowBlindAndBuriedVias:!1});return[Ye.connectionIndex,{plan:at,path:At}]})));for(const[Le,Ye]of Ce)u.set(Le,Ye.plan.via.center),g.set(Le,Ye.path);for(let Le=0;Le<h.length;Le++)h[Le]=Ce.get(h[Le].connectionIndex)?.plan??h[Le]}M&&ie.routeFromSourcePads&&(y=!0),W=!0;break}if(!W)return e.failedNarrowGroup=B<=2&&O.length>0,e.failedWideMatching=t.sourceOriginRouting===!0&&B>2&&te,null}return DPe({...t,inputSrj:s,preparedBuses:r,plans:[...d,...h.filter(x=>p.has(x.busId)&&x.termination.type==="plane")]})}function*nvo(t){const e=(r,s=t.preparedBuses)=>zy({plans:r,preparedBuses:s,inputSrj:t.inputSrj,sharedBoundary:t.sharedBoundary,clearance:t.clearance,allowBlindAndBuriedVias:t.allowBlindAndBuriedVias,allowSameNetMerges:t.allowSameNetMerges}),n=r=>Math.max(...r.map(s=>s.length))-Math.min(...r.map(s=>s.length)),o=new Set;let i=[...t.plans];for(;o.size<3;){const r=e(i);if(r.plans)return r.plans;const s=r.failedBus;if(o.has(s.busId)||s.connections.length!==2||s.termination.type!=="boundary"||!s.exitEdge)return null;o.add(s.busId);const a=i.filter(C=>C.busId===s.busId);if(a.length!==2||a.some(C=>!C.via||C.additionalVias?.length)||a[0].targetLayer!==a[1].targetLayer)return null;const A=i.filter(C=>C.busId!==s.busId),c=new Map(a.map(C=>[C.connectionIndex,[C.sourcePoint,...C.segments.slice(0,C.sourceEscapeSegmentCount??1).map(y=>y.end)]])),l=s.exitEdge==="left"||s.exitEdge==="right",u=l?"y":"x",g=l?t.sharedBoundary.minY:t.sharedBoundary.minX,h=l?t.sharedBoundary.maxY:t.sharedBoundary.maxX,d=(g+h)/2,p=Ds(s.exitEdge,s.preferredExit),m=t.traceWidth+t.clearance,_=n(a),f=[];let I=null;e:for(const C of[0,1,-1,2,-2,3,-3,4,-4]){const y=C*m;if(!a.some(x=>{const E=x.exitPoint[u]+y;return E<g+t.traceWidth/2||E>h-t.traceWidth/2||p==="minimum"&&E>=d||p==="maximum"&&E<=d}))for(const x of[0,-1,1])for(const E of[[0,1],[1,0]]){const B=yield*BC({...t,bus:s,targetLayer:a[0].targetLayer,acceptedPlans:A,terminals:s.connections.map(w=>{const M=a.find(k=>k.connectionIndex===w.connectionIndex);return{connection:w,viaPoint:M.via.center,exitPoint:{...M.exitPoint,[u]:M.exitPoint[u]+y}}}),sourceEscapePaths:c,reservedVias:void 0,gridStep:m/2,gridStepDivisor:2,alignGridToPads:!0,maximumRouteOrderAttempts:1,routeOrder:E,laneBias:x},1,!1);if(!B.length||n(B[0])>=_)continue;const S=B[0].map(w=>({...w,cornerBandSide:p}));if(f.push(S),n(S)>2*s.maxLengthSkew)continue;const Q=e([...A,...S],[s]);if(Q.plans){I=Q.plans;break e}}}if(!I)for(const C of f.toSorted((y,x)=>n(y)-n(x)).slice(0,3)){const y=e([...A,...C],[s]);if(y.plans){I=y.plans;break}}if(!I)return null;i=I}return e(i).plans}var bC=1e-7;function Iue(t,e){const n=t.filter((o,i)=>!i||tn(o,t[i-1])>1e-9);return n.flatMap((o,i)=>{if(!i||i===n.length-1)return[o];const r=n[i-1],s=n[i+1],a=tn(r,o),A=tn(o,s);if(Math.abs((o.x-r.x)*(s.x-o.x)+(o.y-r.y)*(s.y-o.y))>1e-9)return[o];const c=Math.min(e,a/3,A/3);return[{x:o.x+(r.x-o.x)*c/a,y:o.y+(r.y-o.y)*c/a},{x:o.x+(s.x-o.x)*c/A,y:o.y+(s.y-o.y)*c/A}]})}function ovo(t,e,n){if(t.length>28)return null;const{traceWidth:o,clearance:i,viaDiameter:r}=e,s=e.buses.flatMap(_=>_.connections),a=pw(e.buses,{...e,additionalObstacles:e.srj.obstacles}),A=new Map(t.map((_,f)=>[_.connectionIndex,f])),c=s.map(_=>({own:A.get(_.connectionIndex),masks:a.filter(f=>f.connectionIndex===_.connectionIndex).map(f=>{const I={start:_.sourcePoint,end:f.point,width:o,layer:_.sourceLayer};let C=0;return t.forEach((y,x)=>{y.connectionIndex!==_.connectionIndex&&(tn(f.point,y.exitPoint)<r+i-bC||Cr(y.exitPoint,I.start,I.end)<r/2+o/2+i-bC||y.segments.some(E=>Cr(f.point,E.start,E.end)<r/2+o/2+i-bC||!Zm(I,E,i)))&&(C|=1<<x)}),C})})),l=_=>Math.atan2(_.y-n.y,_.x-n.x),u=t.map((_,f)=>f).sort((_,f)=>l(t[f].exitPoint)-l(t[_].exitPoint)),g=e.bus.connections.toSorted((_,f)=>l(f.exitTargetPoint??f.targetPoint)-l(_.exitTargetPoint??_.targetPoint)),h=new Map(g.map((_,f)=>[_.connectionIndex,f])),d=_=>c.every(f=>f.own!==void 0&&_&1<<f.own||f.masks.some(I=>!(I&_)));let p=[],m=0;for(let _=0;_<t.length;_++){const f=[...u.slice(_),...u.slice(0,_)],I=(C,y,x,E)=>{if(++m>1e6||E.length+f.length-C<p.length)return;if(C===f.length){E.length>p.length&&d(x)&&(p=[...E]);return}const B=f[C],S=h.get(t[B].connectionIndex);S>y&&I(C+1,S,x|1<<B,[...E,B]),I(C+1,y,x,E)};I(0,-1,0,[])}return p.length>=3?p.map(_=>t[_]):null}function*ivo(t){const{bus:e,srj:n,traceWidth:o,clearance:i,viaDiameter:r}=t;if(e.termination.type!=="boundary"||e.exitEdge!=="left"||e.connections.length<8||e.connections.length>28||t.targetLayer==="top"||e.connections.some(ye=>ye.sourceLayer!=="top"))return null;const s=Math.min(e.pitchX,e.pitchY),a=o+i;if(!Number.isFinite(s)||s<=0)return null;const A=e.componentObstacles.filter(ye=>ye.layers.includes("top")),c={minX:Math.min(...A.map(ye=>ye.center.x-ye.width/2)),maxX:Math.max(...A.map(ye=>ye.center.x+ye.width/2)),minY:Math.min(...A.map(ye=>ye.center.y-ye.height/2)),maxY:Math.max(...A.map(ye=>ye.center.y+ye.height/2))},l={x:(c.minX+c.maxX)/2,y:(c.minY+c.maxY)/2},u=Math.ceil(((c.maxX-c.minX)/2+s+a)/a)*a,g=Math.ceil(((c.maxY-c.minY)/2+s+a)/a)*a,h={minX:l.x-u,maxX:l.x+u,minY:l.y-g,maxY:l.y+g};if(h.minX<=e.sharedBoundary.minX||h.maxY>=e.sharedBoundary.maxY||h.minY<=e.sharedBoundary.minY)return null;const d=new Map(t.buses.flatMap(ye=>ye.connections.map(Me=>[Me.connectionIndex,{owner:ye,connection:Me}]))),p=ye=>t.targetPointsByConnectionIndex?.get(ye.connectionIndex)??{x:e.sharedBoundary.minX,y:(ye.exitTargetPoint??ye.targetPoint).y},m=ye=>ye.map((Me,ve)=>({...e,busId:`${e.busId}:split-source:${ve}`,sharedBoundary:h,preferredExit:void 0,exitEdge:void 0,connections:[{...Me,exitTargetPoint:void 0,hasExplicitLayeredExitTarget:!1,hasExplicitExitTarget:!1}]})),_=yield*AR({srj:n,buses:m(e.connections),traceWidth:o,clearance:i});if(!_||_.length!==e.connections.length)return null;const f=ovo(_,t,l);if(!f)return null;const I=(ye,Me)=>{const ve=d.get(ye.connectionIndex).owner,he=ve===e?t.targetLayer:ve.termination.type==="plane"?ve.termination.layer:t.targetLayerByBusId?.get(ve.busId)??(ve.allowedLayers??t.layerNames).find(Qe=>Qe!==ye.sourceLayer);if(!he)throw Error("FanoutSolver: split source has no legal target layer");return{connectionIndex:ye.connectionIndex,connectionName:ye.connection.name,segments:Me.slice(1).map((Qe,Pe)=>({start:Me[Pe],end:Qe,width:o,layer:ye.sourceLayer})),via:{center:Me.at(-1),diameter:r,holeDiameter:t.viaHoleDiameter,fromLayer:ye.sourceLayer,toLayer:he,spanLayers:Mx({fromLayer:ye.sourceLayer,toLayer:he,layerNames:t.layerNames,allowBlindAndBuriedVias:!1})}}},C=(ye,Me)=>{const ve=d.get(ye.connectionIndex).connection;if(ye.segments.some(he=>[he.start,he.end].some(Qe=>Qe.x<e.sharedBoundary.minX-bC||Qe.x>e.sharedBoundary.maxX+bC||Qe.y<e.sharedBoundary.minY-bC||Qe.y>e.sharedBoundary.maxY+bC)))return!1;for(const he of n.obstacles)if(he.layers.some(Qe=>ye.via.spanLayers.includes(Qe))&&wx(ye.via.center,he)<r/2+i-bC||he!==ve.sourceObstacle&&ye.segments.some(Qe=>he.layers.includes(Qe.layer)&&Tl(Qe,he)<o/2+i-bC))return!1;return Me.every(he=>he.connectionIndex===ye.connectionIndex||tn(ye.via.center,he.via.center)>=r+i-bC&&ye.segments.every(Qe=>Cr(he.via.center,Qe.start,Qe.end)>=r/2+o/2+i-bC&&he.segments.every(Pe=>Zm(Qe,Pe,i)))&&he.segments.every(Qe=>Cr(ye.via.center,Qe.start,Qe.end)>=r/2+o/2+i-bC))},y=ye=>{const Me=new Set(ye.map(ve=>ve.connectionIndex));return t.buses.map(ve=>({...ve,connections:ve.connections.filter(he=>!Me.has(he.connectionIndex))})).filter(ve=>ve.connections.length)};let x=t.initialViaPoints;const E=ye=>({...t,additionalObstacles:n.obstacles,maximumSearchStates:3e5,blockingSegments:ye.flatMap(Me=>Me.segments.map(ve=>({connectionIndex:Me.connectionIndex,segment:ve}))),blockingVias:ye.map(Me=>({connectionIndex:Me.connectionIndex,...Me.via})),preferredViaPointsByConnectionIndex:x}),B=f.map(ye=>I(d.get(ye.connectionIndex).connection,[ye.segments[0].start,...ye.segments.map(Me=>Me.end)])),S=pd(y(B),E(B));if(!S)return null;x=new Map([...S,...B.map(ye=>[ye.connectionIndex,ye.via.center])]);const Q=f.toSorted((ye,Me)=>p(d.get(ye.connectionIndex).connection).y-p(d.get(Me.connectionIndex).connection).y);let w=[];for(const ye of Q){const Me=[ye];let ve=ye.exitPoint.x;for(const he of Q.slice(Q.indexOf(ye)+1))he.exitPoint.x>ve+a-bC&&(Me.push(he),ve=he.exitPoint.x);Me.length>w.length&&(w=Me)}if(w.length<3)return null;const M=new Map(w.map(ye=>[ye.connectionIndex,[ye.segments[0].start,...ye.segments.map(Me=>Me.end)]])),k=e.sharedBoundary.minX+Math.max(s/2,r/2+i),R=h.maxY+s-a/2,F=h.minX-s+a/2,O=()=>[...M].sort(([ye],[Me])=>p(d.get(ye).connection).y-p(d.get(Me).connection).y).map(([ye,Me],ve)=>{const he=p(d.get(ye).connection),Qe=Me.at(-1);return I(d.get(ye).connection,Iue([...Me,{x:Qe.x,y:R+ve*a},{x:F-ve*a,y:R+ve*a},{x:F-ve*a,y:he.y},{x:k,y:he.y}],o))});let U=O();if(U.some(ye=>!C(ye,U)))return null;for(const ye of e.connections.toSorted((Me,ve)=>p(Me).y-p(ve).y)){if(M.has(ye.connectionIndex))continue;const Me=[...M].filter(([he])=>p(d.get(he).connection).y<p(ye).y).at(-1)?.[1].at(-1)?.x??h.minX,ve=[...M].filter(([he])=>p(d.get(he).connection).y>p(ye).y)[0]?.[1].at(-1)?.x??h.maxX;for(const he of[-1,1]){const Qe={x:ye.sourcePoint.x+he*s/2,y:ye.sourcePoint.y+s/2};if(Qe.x<Me+a-bC||Qe.x>ve-a+bC)continue;const Pe=[ye.sourcePoint,Qe,{x:Qe.x,y:h.maxY}];M.set(ye.connectionIndex,Pe);const we=O();if(we.every(Te=>C(Te,we))&&pd(y(we),E(we))){U=we;break}M.delete(ye.connectionIndex)}}const Y=Math.min(...U.map(ye=>p(d.get(ye.connectionIndex).connection).y));for(const ye of _.filter(Me=>Math.abs(Me.exitPoint.x-h.minX)<bC&&p(d.get(Me.connectionIndex).connection).y<Y).sort((Me,ve)=>p(d.get(ve.connectionIndex).connection).y-p(d.get(Me.connectionIndex).connection).y)){const Me=d.get(ye.connectionIndex).connection,ve=p(Me),he=h.minX-a,Qe=I(Me,Iue([ye.segments[0].start,...ye.segments.map(Pe=>Pe.end),{x:he,y:ye.exitPoint.y},{x:he,y:ve.y},{x:k,y:ve.y}],o));C(Qe,U)&&pd(y([...U,Qe]),E([...U,Qe]))&&U.push(Qe)}const W=new Set(U.map(ye=>ye.connectionIndex)),te=e.connections.filter(ye=>!W.has(ye.connectionIndex)).sort((ye,Me)=>p(ye).y-p(Me).y);if(te.length<5)return null;const j=te.slice(0,3),J=j[1],oe=j[2],ie=[...n.obstacles,...U.flatMap(ye=>ye.segments.map(Me=>({type:"rect",center:{x:(Me.start.x+Me.end.x)/2,y:(Me.start.y+Me.end.y)/2},width:tn(Me.start,Me.end),height:Me.width,ccwRotationDegrees:Math.atan2(Me.end.y-Me.start.y,Me.end.x-Me.start.x)*180/Math.PI,layers:[Me.layer],connectedTo:[ye.connectionName]})))],ne=yield*AR({srj:{...n,obstacles:ie},buses:m([J,oe]),traceWidth:o,clearance:i,availableBoundaryRegions:[{direction:"down",preferredExit:"bottom",exitEdge:"bottom"}]});if(!ne?.length)return null;const le=ne.find(ye=>ye.connectionIndex===J.connectionIndex),ge=I(J,[le.segments[0].start,...le.segments.map(ye=>ye.end)]);if(!C(ge,U))return null;U.push(ge),W.add(ge.connectionIndex);const _e=y(U),ue=new Map([[oe.connectionIndex,{x:oe.sourcePoint.x-s/2,y:oe.sourcePoint.y-s/2}]]),fe=pd(_e,{...E(U),fixedViaPointsByConnectionIndex:ue});if(!fe)return null;const pe=[...U,..._e.flatMap(ye=>ye.connections.map(Me=>I(Me,[Me.sourcePoint,fe.get(Me.connectionIndex)])))];return pe.some(ye=>!C(ye,pe))?null:{sourceEscapes:pe,sourceBoundary:h,remoteConnectionIndices:W,bottomRemoteConnectionIndices:new Set([ge.connectionIndex]),lowerConnectionIndices:j.map(ye=>ye.connectionIndex),viaPointsByConnectionIndex:new Map(pe.map(ye=>[ye.connectionIndex,ye.via.center]))}}function*ZPe(t){const e=new Set,n=new Set,o=[];let i=0,r=null;function*s(c,l){const u=c.join(",")+":"+l;if(e.has(u)||i>=256)return;e.add(u),i++;let g=0;const h=BC({...t,routeOrder:c,laneBias:l,maximumRouteOrderAttempts:1},1,!1);let d=h.next();for(;!d.done;)g=Math.max(g,d.value.connectionIndex),yield d.value,d=h.next();if(d.value.length){r=d.value[0];return}const p=c.slice(0,g+1).join(",")+":"+l;n.has(p)||(n.add(p),o.push({order:c,bias:l,completed:g}))}const A=t.terminals.map((c,l)=>l).toSorted((c,l)=>t.terminals[c].exitPoint.x-t.terminals[l].exitPoint.x);for(const c of[0,1,-1])if(yield*s(A,c),r||(yield*s(A.toReversed(),c),r))return r;for(;o.length&&i<256;){o.sort((g,h)=>h.completed-g.completed);const{order:c,bias:l,completed:u}=o.shift();o.length>256&&(o.length=256);for(let g=u-1;g>=0;g--){const h=[...c],[d]=h.splice(u,1);if(h.splice(g,0,d),yield*s(h,l),r)return r;const p=[...c];if([p[u],p[g]]=[p[g],p[u]],yield*s(p,l),r)return r}}return null}function*tRt(t){const{bus:e,srj:n,sourceBoundary:o,sourceEscapes:i,remoteConnectionIndices:r,bottomRemoteConnectionIndices:s,lowerConnectionIndices:a,targetLayer:A,traceWidth:c,clearance:l}=t;if(e.exitEdge!=="left"||e.termination.type!=="boundary"||a.length!==3)return null;const u=Math.min(e.pitchX,e.pitchY),g=c+l,h=new Map(i.map(pe=>[pe.connectionIndex,pe])),d=e.connections.map(pe=>({connection:pe,viaPoint:h.get(pe.connectionIndex).via.center,exitPoint:{x:e.sharedBoundary.minX,y:(pe.exitTargetPoint??pe.targetPoint).y}})).sort((pe,ye)=>pe.exitPoint.y-ye.exitPoint.y),p=new Map(d.map(pe=>[pe.connection.connectionIndex,pe])),m=a.map(pe=>p.get(pe)),_=new Set(a),f=d.filter(pe=>!_.has(pe.connection.connectionIndex)&&!r.has(pe.connection.connectionIndex));if(f.length<2||m.some(pe=>!pe))return null;const I=new Map(i.map(pe=>[pe.connectionIndex,[pe.segments[0].start,...pe.segments.map(ye=>ye.end)]])),C=(pe,ye)=>i4({...t,bus:e,terminal:pe,targetLayerPoints:ye,sourceEscapePoints:I.get(pe.connection.connectionIndex),allowBlindAndBuriedVias:!1}),y=Math.min(o.minY-t.viaDiameter/2-c/2-l-1e-5,...m.map((pe,ye)=>pe.exitPoint.y+(m.length-1-ye)*g-g-c)),x=(pe,ye,Me)=>{const ve=(Me?f:m).findIndex(Te=>Te.connection.connectionIndex===pe.connection.connectionIndex),he=ye.at(-1),Qe=Me?o.maxY+u-g/2+ve*g:y-(m.length-1-ve)*g,Pe=o.minX-t.viaDiameter/2-c/2-l-1e-5-(Me?ve:m.length-1-ve)*g,we=Iue([he,{x:he.x,y:Qe},{x:Pe,y:Qe},{x:Pe,y:pe.exitPoint.y},pe.exitPoint],c);return C(pe,[...ye,...we.slice(1)])},E=d.filter(pe=>r.has(pe.connection.connectionIndex)).map(pe=>s.has(pe.connection.connectionIndex)?x(pe,[pe.viaPoint],!1):C(pe,[pe.viaPoint,pe.exitPoint]));let B=!!t.rematchPendingSources;const S=(pe,ye,Me,ve,he=!1)=>{const Qe=new Set(pe.map(we=>we.connection.connectionIndex)),Pe={...e,connections:pe.map(we=>we.connection),exitEdge:Me?"top":"bottom",direction:Me?"up":"down",preferredExit:void 0,sharedBoundary:he?e.sharedBoundary:{...e.sharedBoundary,maxY:o.maxY,...Me?{}:{minY:o.minY}}};return{...t,bus:Pe,terminals:pe.map((we,Te)=>({...we,exitPoint:ve[Te]})),acceptedPlans:ye,reservedVias:i.filter(we=>!Qe.has(we.connectionIndex)&&(!B||!t.rematchPendingSources?.connectionIndices.has(we.connectionIndex))).map(we=>({connectionName:we.connectionName,via:we.via})),sourceEscapePaths:I,allowBlindAndBuriedVias:!1,allowSameNetMerges:!1,gridStepDivisor:2,gridStep:g/2,alignGridToPads:!0,reserveTerminalExitPoints:!0}},Q=m[0],w=m.at(-1),M=f[0],k=w.connection.sourcePoint,R=k.x+u,F=[{x:M.connection.sourcePoint.x,y:M.connection.sourcePoint.y-u},{x:k.x-u,y:k.y},{x:R,y:k.y}];let O=[Q.viaPoint];for(const pe of F){const ye={...Q,viaPoint:O.at(-1)},Me=S([ye],E,!0,[pe],!0);Me.bus={...Me.bus,exitEdge:"right",direction:"right"},Me.sourceEscapePaths=void 0;const ve=yield*ZPe(Me);if(!ve)return null;O.push(...ve[0].segments.filter(he=>he.layer===A).map(he=>he.end))}O=Iue([...O,{x:R,y:o.minY}],c);const U=x(Q,O,!1),W={x:i.find(pe=>s.has(pe.connectionIndex)).via.center.x-u,y:o.minY};B=!1;const te=yield*ZPe(S([w],[...E,U],!1,[W]));if(!te)return null;const j=te[0].segments.filter(pe=>pe.layer===A),J=x(w,[j[0].start,...j.map(pe=>pe.end)],!1);if(t.rematchPendingSources){if(!t.rematchPendingSources.afterLowerStage([...E,U,J]))return null;for(const pe of i)I.set(pe.connectionIndex,[pe.segments[0].start,...pe.segments.map(ye=>ye.end)])}const oe=Math.min(...e.componentObstacles.map(pe=>pe.center.x-pe.width/2)),ie=oe+t.viaDiameter/2,ne=Math.max(...f.map(pe=>pe.connection.sourcePoint.x))-u/2-c/2;if(ne-ie<(f.length-1)*g)return null;const le=f.map((pe,ye)=>({x:ie+(ne-ie)*ye/(f.length-1),y:o.maxY})),ge=yield*ZPe(S(f,[...E,U,J],!0,le));if(!ge)return null;const _e=ge.map(pe=>{const ye=pe.segments.filter(ve=>ve.layer===A),Me=ye.at(-1);return Me.end.y<=Me.start.y?null:x(p.get(pe.connectionIndex),[ye[0].start,...ye.map(ve=>ve.end)],!0)});if(_e.some(pe=>!pe))return null;const ue=[...E,U,J,..._e];if(ue.length!==e.connections.length)return null;const fe=ue.map(pe=>pe.length);if(e.maxLengthSkew!==void 0&&Math.max(...fe)-Math.min(...fe)>e.maxLengthSkew+eMe||!Wh({plans:ue,srj:n,sharedBoundary:e.sharedBoundary,clearance:l,allowBlindAndBuriedVias:!1,allowSameNetMerges:!1}))return null;for(const pe of ue)for(const ye of i)if(pe.connectionIndex!==ye.connectionIndex)for(const Me of pe.segments){if(ye.via.spanLayers.includes(Me.layer)&&Cr(ye.via.center,Me.start,Me.end)<ye.via.diameter/2+Me.width/2+l-eMe)return null;for(const ve of ye.segments)if(Me.layer===ve.layer&&tu(Me.start,Me.end,ve.start,ve.end)<(Me.width+ve.width)/2+l-eMe)return null}return ue}var eMe=1e-7,SB=1e-7;function nRt(t,e){const n=new Map(t.buses.flatMap(i=>i.connections).map(i=>[i.connectionIndex,i])),o=t.bus.sharedBoundary;for(const i of e){const r=n.get(i.connectionIndex),s=i.via.diameter/2;for(const a of t.srj.obstacles)if(a.layers.some(A=>i.via.spanLayers.includes(A))&&wx(i.via.center,a)<s+t.clearance-SB||a!==r.sourceObstacle&&i.segments.some(A=>a.layers.includes(A.layer)&&Tl(A,a)<A.width/2+t.clearance-SB))return!1;for(const a of i.segments)if([a.start,a.end].some(A=>A.x<o.minX-SB||A.x>o.maxX+SB||A.y<o.minY-SB||A.y>o.maxY+SB))return!1;for(const a of e)if(i.connectionIndex!==a.connectionIndex&&(tn(i.via.center,a.via.center)<s+a.via.diameter/2+t.clearance-SB||i.segments.some(A=>a.via.spanLayers.includes(A.layer)&&Cr(a.via.center,A.start,A.end)<a.via.diameter/2+A.width/2+t.clearance-SB)||i.segments.some(A=>a.segments.some(c=>!Zm(A,c,t.clearance)))))return!1}return!0}function*rvo(t){const{bus:e,traceWidth:n,clearance:o,viaDiameter:i}=t;if(e.exitEdge!=="left"||e.termination.type!=="boundary"||t.bottomRemoteConnectionIndices.size!==1)return null;const r=[...t.bottomRemoteConnectionIndices][0],s=t.sourceEscapes.find(d=>d.connectionIndex===r),a=s?.segments.at(-1);if(!a||Math.abs(a.start.x-a.end.x)>SB||a.start.y<=a.end.y)return null;const A=Math.min(e.pitchX,e.pitchY);if(!Number.isFinite(A)||A<=0)return null;const c=n+o,l=e.yCoordinates.slice(1).map((d,p)=>(d+e.yCoordinates[p])/2).filter(d=>d>a.end.y+SB&&d<a.start.y-SB).sort((d,p)=>d-p).slice(0,4),u=new Set([...e.connections.map(d=>d.connectionIndex),...t.sourceEscapes.filter(d=>d.segments.length>1).map(d=>d.connectionIndex)]),g=t.buses.map(d=>({...d,connections:d.connections.filter(p=>!u.has(p.connectionIndex))})).filter(d=>d.connections.length),h=new Set(g.flatMap(d=>d.connections).map(d=>d.connectionIndex));for(const d of l){yield{phase:"route-connection",routeOrderAttempt:0,connectionIndex:0,connectionCount:e.connections.length,connectionName:s.connectionName,searchBatch:0,expandedStateCount:0,connectionComplete:!1};const p=t.sourceEscapes.map(x=>({...x,segments:x.segments.map(E=>({...E,start:{...E.start},end:{...E.end}})),via:{...x.via,center:{...x.via.center}}})),m=new Map(t.viaPointsByConnectionIndex),_=p.find(x=>x.connectionIndex===r);_.via.center={x:a.end.x,y:d},_.segments.at(-1).end=_.via.center,m.set(r,_.via.center);const f=p.filter(x=>u.has(x.connectionIndex)),I=(x=[])=>{const E=pd(g,{...t,additionalObstacles:t.srj.obstacles,maximumSearchStates:3e5,preferredViaPointsByConnectionIndex:m,blockingSegments:[...f.flatMap(B=>B.segments.map(S=>({connectionIndex:B.connectionIndex,segment:S}))),...x.flatMap(B=>B.segments.filter(S=>S.layer===t.targetLayer).map(S=>({connectionIndex:B.connectionIndex,segment:S})))],blockingVias:f.map(B=>({connectionIndex:B.connectionIndex,...B.via}))});if(!E)return!1;for(const B of p)if(h.has(B.connectionIndex)){const S=E.get(B.connectionIndex);B.via={...B.via,center:S},B.segments=[{...B.segments[0],end:S}],m.set(B.connectionIndex,S)}return nRt(t,p)};if(!I())continue;const C={...t.sourceBoundary,minY:d-A+i/2+n/2+o+1e-5+c},y=yield*tRt({...t,sourceEscapes:p,sourceBoundary:C,viaPointsByConnectionIndex:m,rematchPendingSources:{connectionIndices:h,afterLowerStage:I}});if(y&&nRt(t,p))return{plans:y,sourceEscapes:p,sourceBoundary:{...t.sourceBoundary},viaPointsByConnectionIndex:m,remoteConnectionIndices:new Set(t.remoteConnectionIndices),bottomRemoteConnectionIndices:new Set(t.bottomRemoteConnectionIndices),lowerConnectionIndices:[...t.lowerConnectionIndices]}}return null}function r6(t){return t==="left"||t==="right"}function Cue(t){return t==="right"||t==="up"?1:-1}function SC(t,e){return r6(e)?t.x:t.y}function s6(t,e){return r6(e)?t.y:t.x}function Dx(t,e,n){return r6(n)?{x:t,y:e}:{x:e,y:t}}function yue(t){switch(t.direction){case"right":return t.sharedBoundary.maxX;case"left":return t.sharedBoundary.minX;case"up":return t.sharedBoundary.maxY;case"down":return t.sharedBoundary.minY}}function xue(t){if(t.length<3)return t;const e=[t[0]];for(let n=1;n<t.length-1;n++){const o=e.at(-1),i=t[n],r=t[n+1],s={x:Math.sign(i.x-o.x),y:Math.sign(i.y-o.y)},a={x:Math.sign(r.x-i.x),y:Math.sign(r.y-i.y)};(s.x!==a.x||s.y!==a.y)&&e.push(i)}return e.push(t.at(-1)),e}function c$(t,e){const n=[];for(let o=1;o<t.length;o++)tn(t[o-1],t[o])<1e-9||n.push({start:t[o-1],end:t[o],width:e,layer:"top"});return n}function svo(t){const{srj:e,bus:n,connection:o,traceWidth:i,clearance:r}=t,s=n.direction,a=Cue(s),A={x:o.sourcePoint.x,y:o.sourcePoint.y},c=SC(A,s),l=s6(A,s),u=i/2+r,g=(()=>{switch(s){case"right":return n.componentBounds.maxX+u;case"left":return n.componentBounds.minX-u;case"up":return n.componentBounds.maxY+u;case"down":return n.componentBounds.minY-u}})(),h=y=>Math.min(...e.obstacles.filter(x=>x!==o.sourceObstacle&&x.layers.includes("top")).map(x=>Tl(y,x))),d={start:A,end:Dx(g,l,s)};if(h(d)>=u-1e-9)return null;const p=r6(s)?{minimum:n.componentBounds.minY,maximum:n.componentBounds.maxY}:{minimum:n.componentBounds.minX,maximum:n.componentBounds.maxX},m=a*(g-c),_=s6(o.exitTargetPoint??o.targetPoint,s),f=i+r,I=yue(n),C=[-1,1].map(y=>{const x=y<0?p.minimum-u:p.maximum+u,E=y*(x-l),B=Math.max(m,E),S=Dx(c+a*B,l+y*B,s);if(a*(I-SC(S,s))<f-1e-9)return null;const Q=[A,S];if(!Q.every(k=>k.x>=n.sharedBoundary.minX-1e-9&&k.x<=n.sharedBoundary.maxX+1e-9&&k.y>=n.sharedBoundary.minY-1e-9&&k.y<=n.sharedBoundary.maxY+1e-9))return null;const M=Math.min(...c$(Q,i).map(h));return M<u-1e-9?null:{points:Q,obstacleDistance:M,targetDistance:Math.abs(s6(S,s)-_)}}).filter(y=>y!==null).toSorted((y,x)=>x.obstacleDistance-y.obstacleDistance||y.targetDistance-x.targetDistance);return C.length>0?C.map(y=>y.points):null}function avo(t){const{item:e,srj:n,acceptedSegments:o,traceWidth:i,clearance:r}=t,s=e.cornerChannelPrefixes;if(!s)return null;const a=e.direction,A=Cue(a),c=yue(e.bus),l=i+r,u=i/2+r,g=r6(a)?e.bus.sharedBoundary.minY:e.bus.sharedBoundary.minX,h=r6(a)?e.bus.sharedBoundary.maxY:e.bus.sharedBoundary.maxX,d=g+i/2,p=h-i/2,m=s6(e.connection.exitTargetPoint??e.connection.targetPoint,a),_=l/2,f=new Set([Math.max(d,Math.min(p,m))]);for(let C=Math.ceil(d/_)*_;C<=p+1e-9;C+=_)f.add(Number(C.toFixed(9)));const I=[...f].toSorted((C,y)=>Math.abs(C-m)-Math.abs(y-m));for(const C of s){const y=C.at(-1),x=s6(y,a);for(const E of I){const B=Math.abs(E-x),S=Dx(SC(y,a)+A*l,x,a),Q=Dx(SC(S,a)+A*B,E,a);if(A*(c-SC(Q,a))<-1e-9)continue;const w=Dx(c,E,a),M=[...C,S,...B>1e-9?[Q]:[]];tn(M.at(-1),w)>1e-9&&M.push(w);const k=xue(M),R=c$(k,i);if(!(!R.every(U=>n.obstacles.every(Y=>Y===e.connection.sourceObstacle||!Y.layers.includes("top")||Tl(U,Y)>=u-1e-9))||!R.every(U=>o.every(Y=>tu(U.start,U.end,Y.start,Y.end)>=i+r-1e-9))))return{item:e,points:k,track:E}}}return null}function Avo(t){const{route:e,direction:n,exitAxis:o,signedShift:i,maximumShift:r,obstacles:s,requiredObstacleDistance:a}=t;if(r<=1e-9||Math.abs(i)<=1e-9)return 0;const A=Math.sign(i),c=g=>{if(g<=1e-9)return!0;const h={start:Dx(o-Cue(n)*g,e.track,n),end:Dx(o,e.track+A*g,n)};return s.every(d=>d===e.item.connection.sourceObstacle||!d.layers.includes("top")||Tl(h,d)>=a-1e-9)};if(c(r))return r;let l=0,u=r;for(let g=0;g<32;g++){const h=(l+u)/2;c(h)?l=h:u=h}return l}function cvo(t){const{requestedTracks:e,currentTracks:n,candidateTracks:o,maximumShifts:i}=t,r=e.length+1,s=o.length+1,a=Array.from({length:r},()=>new Float64Array(s).fill(Number.POSITIVE_INFINITY)),A=Array.from({length:r},()=>new Uint8Array(s));a[0].fill(0);for(let g=1;g<r;g++)for(let h=1;h<s;h++){const d=a[g][h-1],p=Math.abs(e[g-1]-o[h-1]),_=Math.abs(n[g-1]-o[h-1])>i[g-1]+1e-9?Number.POSITIVE_INFINITY:a[g-1][h-1]+p;_<d?(a[g][h]=_,A[g][h]=1):a[g][h]=d}if(!Number.isFinite(a.at(-1).at(-1)))return null;const c=[];let l=e.length,u=o.length;for(;l>0&&u>0;)A[l][u]&&(c.push(o[u-1]),l--),u--;return l>0?null:c.reverse()}function lvo(t){const{direction:e,activeRoutes:n,obstacles:o,boundaryMinimum:i,boundaryMaximum:r,traceWidth:s,clearance:a,requestedTracks:A,maximumShifts:c}=t,l=s+a,u=s/2+a;let g=null,h=Number.POSITIVE_INFINITY;for(const d of Array.from({length:Math.round(l/s)},(p,m)=>m*s)){const p=[],m=Math.ceil((i-d)/l)*l+d;for(let I=m;I<=r+1e-9;I+=l){const C=Math.round(I/s)*s;o.every(y=>{const x=s6(y.center,e),E=r6(e)?y.height:y.width;return Math.abs(C-x)>=E/2+u-1e-9})&&p.push(C)}const _=cvo({requestedTracks:A,currentTracks:n.map(I=>I.track),candidateTracks:p,maximumShifts:c});if(!_)continue;const f=_.reduce((I,C,y)=>I+Math.abs(C-A[y]),0);f<h&&(h=f,g=_)}return g}function uvo(t,e){switch(e){case"up":return t==="top-left"?"minimum":t==="top-right"?"maximum":null;case"down":return t==="bottom-left"?"minimum":t==="bottom-right"?"maximum":null;case"left":return t==="bottom-left"?"minimum":t==="top-left"?"maximum":null;case"right":return t==="bottom-right"?"minimum":t==="top-right"?"maximum":null}}function gvo(t){const{items:e,direction:n,boundaryMinimum:o,boundaryMaximum:i,traceWidth:r,clearance:s,borderDistribution:a,currentTrackByConnectionName:A}=t,c=E=>A.get(E.connection.connection.name)??s6(E.source,n),l=[...e].toSorted((E,B)=>c(E)-c(B)||E.connection.connection.name.localeCompare(B.connection.connection.name)),u=r+s,g=o+r/2,h=i-r/2,d=h-g,p=u*Math.max(l.length-1,0);if(d<p-1e-9)return null;const m=l.map(c);let _=[...m],f=u;const I=new Set;if(a==="even"&&l.length>1){const E=m[0],B=m.at(-1),S=Math.max(u,(B-E)/(l.length-1)),Q=M=>{const k=[...m],R=Math.floor(l.length/2),F=l.length%2===0?R-1:R;if(F!==R){const O=k[R]-k[F];if(O<M){const U=(M-O)/2;k[F]=k[F]-U,k[R]=k[R]+U}}for(let O=F-1;O>=0;O--)k[O]=Math.min(k[O],k[O+1]-M);for(let O=R+1;O<k.length;O++)k[O]=Math.max(k[O],k[O-1]+M);return k},w=M=>M[0]>=g-1e-9&&M.at(-1)<=h+1e-9;if(_=Q(S),w(_))f=S;else{let M=u,k=S;if(_=Q(M),!w(_))return null;for(let R=0;R<32;R++){const F=(M+k)/2,O=Q(F);w(O)?(M=F,_=O):k=F}f=M}for(const M of l)I.add(M.connection.connection.name)}const C=[],y=[];for(let E=0;E<l.length;E++){const B=l[E],S=B.bus.preferredExit;if(!S?.includes("-"))continue;const Q=uvo(S,n);if(!Q)return null;I.add(B.connection.connection.name),Q==="minimum"?C.push(E):y.push(E)}if(C.some((E,B)=>E!==B)||y.some((E,B)=>E!==l.length-y.length+B))return null;const x=u*2;if(C.length>0){_[0]=g+x;for(let E=1;E<C.length;E++){const B=Math.max(f,m[E]-m[E-1]);_[E]=_[E-1]+B}}if(y.length>0){const E=l.length-1;_[E]=h-x;for(let B=E-1;B>=l.length-y.length;B--){const S=Math.max(f,m[B+1]-m[B]);_[B]=_[B+1]-S}}return{byConnectionName:new Map(l.map((E,B)=>[E.connection.connection.name,_[B]])),enforcedConnectionNames:I}}function dvo(t){const{item:e,points:n,segments:o}=t,i=n.map((s,a)=>({route_type:"wire",x:s.x,y:s.y,width:o[0]?.width??.1,layer:"top",...a===0&&e.connection.sourcePoint.pcb_port_id?{start_pcb_port_id:e.connection.sourcePoint.pcb_port_id}:{}})),r=qN({connectionName:e.connection.connection.name,sourcePointIndex:e.connection.sourcePointIndex});return{busId:e.bus.busId,connectionName:e.connection.connection.name,connectionIndex:e.connection.connectionIndex,sourcePointIndex:e.connection.sourcePointIndex,sourcePoint:e.connection.sourcePoint,sourceObstacle:e.connection.sourceObstacle,sourceLayer:e.connection.sourceLayer,targetPoint:e.connection.targetPoint,targetLayer:"top",termination:e.bus.termination,direction:e.direction,...e.bus.exitEdge?{exitEdge:e.bus.exitEdge}:{},exitPoint:n.at(-1),trace:{type:"pcb_trace",pcb_trace_id:r.traceId,connection_name:e.connection.connection.name,connectsTo:[...e.connection.sourcePoint.pointId?[e.connection.sourcePoint.pointId]:[],...e.connection.sourcePoint.pcb_port_id?[e.connection.sourcePoint.pcb_port_id]:[],r.boundaryExitPointId],route:i},segments:o,length:o.reduce((s,a)=>s+tn(a.start,a.end),0)}}function hvo(t){const{paths:e,obstacles:n,traceWidth:o,clearance:i}=t,r=o/2+i,s=o+i;for(const a of e){if(Math.abs(SC(a.points.at(-1),a.item.direction)-yue(a.item.bus))>1e-6)return!1;for(const A of a.segments)for(const c of n)if(!(c===a.item.connection.sourceObstacle||!c.layers.includes("top"))&&Tl(A,c)<r-1e-9)return!1}for(let a=0;a<e.length;a++)for(let A=a+1;A<e.length;A++)for(const c of e[a].segments)for(const l of e[A].segments)if(tu(c.start,c.end,l.start,l.end)<s-1e-9)return!1;return!0}function pvo(t){const{srj:e,buses:n,traceWidth:o,clearance:i,borderDistribution:r}=t,s=o/2+i,a=new Map,A=new Map,c=n.flatMap(h=>h.connections.map(d=>{const p={x:d.sourcePoint.x,y:d.sourcePoint.y},m=svo({srj:e,bus:h,connection:d,traceWidth:o,clearance:i});return{bus:h,connection:d,direction:h.direction,source:p,...m?{cornerChannelPrefixes:m}:{}}}));for(const h of["left","right","up","down"]){const d=Cue(h),p=c.filter(R=>R.direction===h&&!R.cornerChannelPrefixes);if(p.length===0)continue;const m=r6(h)?p[0].bus.sharedBoundary.minY:p[0].bus.sharedBoundary.minX,_=r6(h)?p[0].bus.sharedBoundary.maxY:p[0].bus.sharedBoundary.maxX,f=yue(p[0].bus),I=new Map,C=new Map,y=new Map;for(const R of p){const F=SC(R.source,h),O=F.toFixed(6);y.set(O,F);const U=I.get(O)??[];U.push(R),I.set(O,U)}for(const[R,F]of I){const O=y.get(R),U=new Set(F.map(Y=>Y.bus.componentId));C.set(R,e.obstacles.filter(Y=>Y.layers.includes("top")&&!!Y.componentId&&U.has(Y.componentId)&&Math.abs(SC(Y.center,h)-O)<1e-6))}const x=[...y.values()].toSorted((R,F)=>d*(R-F)),E=new Map;for(let R=0;R<x.length;R++){const F=x[R],O=F.toFixed(6);for(const J of I.get(O)??[]){const oe=r6(h)?J.connection.sourceObstacle.width:J.connection.sourceObstacle.height,ie=Math.max(J.connection.sourceObstacle.width,J.connection.sourceObstacle.height)<1.5?oe/2+s:0,ne=Dx(F+d*ie,s6(J.source,h),h);E.set(J.connection.connection.name,{item:J,points:tn(J.source,ne)>1e-9?[J.source,ne]:[J.source],track:s6(J.source,h)})}const U=x[R+1]??f;if(E.size===0||d*(U-F)<=1e-9)continue;const Y=[...E.values()].toSorted((J,oe)=>J.track-oe.track||J.item.connection.connection.name.localeCompare(oe.item.connection.connection.name)),W=x.slice(R+1,R+3).flatMap(J=>C.get(J.toFixed(6))??[]),te=Y.map(J=>Math.abs(U-SC(J.points.at(-1),h))),j=lvo({direction:h,activeRoutes:Y,obstacles:W,boundaryMinimum:m,boundaryMaximum:_,traceWidth:o,clearance:i,requestedTracks:Y.map(J=>J.track),maximumShifts:te});if(!j)return null;for(let J=0;J<Y.length;J++){const oe=Y[J],ie=j[J],ne=Math.abs(ie-oe.track),le=SC(oe.points.at(-1),h),ge=Dx(le+d*ne,ie,h);tn(oe.points.at(-1),ge)>1e-9&&oe.points.push(ge);const _e=Dx(U,ie,h);tn(oe.points.at(-1),_e)>1e-9&&oe.points.push(_e),oe.track=ie}}const B=gvo({items:p,direction:h,boundaryMinimum:m,boundaryMaximum:_,traceWidth:o,clearance:i,borderDistribution:r,currentTrackByConnectionName:new Map([...E.values()].map(R=>[R.item.connection.connection.name,R.track]))});if(!B)return null;const S=[...E.values()].toSorted((R,F)=>R.track-F.track||R.item.connection.connection.name.localeCompare(F.item.connection.connection.name)),Q=new Map,w=o+i;let M=w;for(const R of S){const F=R.item.connection.connection.name;!B.enforcedConnectionNames.has(F)||B.byConnectionName.get(F)-R.track>=-1e-9||(Q.set(F,M),M+=w*2)}let k=w;for(let R=S.length-1;R>=0;R--){const F=S[R],O=F.item.connection.connection.name;!B.enforcedConnectionNames.has(O)||B.byConnectionName.get(O)-F.track<=1e-9||(Q.set(O,k),k+=w*2)}for(const R of S){const F=R.item.connection.connection.name,O=B.byConnectionName.get(F)??R.track,U=Q.get(F)??0,Y=R.points.at(-2),W=Y?d*(f-SC(Y,h)):0,te=O-R.track,j=Math.min(Math.abs(te),Math.max(0,W-U)),J=Avo({route:R,direction:h,exitAxis:f,signedShift:te,maximumShift:j,obstacles:e.obstacles,requiredObstacleDistance:s}),oe=Math.sign(te)*J;B.byConnectionName.set(F,R.track+oe)}for(const R of B.enforcedConnectionNames)A.set(R,B.byConnectionName.get(R));for(const R of S){const F=R.item.connection.connection.name,O=B.byConnectionName.get(F)??R.track,U=Math.abs(O-R.track),Y=Q.get(F)??0,W=U>1e-9?Y+U:0,te=f-d*W,j=R.points.at(-1);if(Math.abs(SC(j,h)-f)>1e-6)return null;const J=R.points.at(-2);if(J&&(Math.abs(s6(J,h)-R.track)>1e-6||d*(te-SC(J,h))<-1e-6))return null;const oe=Dx(te,R.track,h);J&&tn(J,oe)<1e-9?R.points.pop():R.points[R.points.length-1]=oe}for(const R of S){const F=R.item.connection.connection.name,O=B.byConnectionName.get(F)??R.track,U=Math.abs(O-R.track),Y=Q.get(F)??0;U>1e-9&&Y>1e-9&&R.points.push(Dx(SC(R.points.at(-1),h)+d*Y,R.track,h)),U>1e-9&&(R.points.push(Dx(SC(R.points.at(-1),h)+d*U,O,h)),R.track=O);const W=Dx(f,R.track,h);if(tn(R.points.at(-1),W)>1e-9){if(d*(f-SC(R.points.at(-1),h))<-1e-6)return null;R.points.push(W)}a.set(F,R)}}const l=[...a.values()].flatMap(h=>c$(xue(h.points),o));for(const h of c){if(!h.cornerChannelPrefixes)continue;const d=avo({item:h,srj:e,acceptedSegments:l,traceWidth:o,clearance:i});if(!d)return null;a.set(h.connection.connection.name,d),l.push(...c$(xue(d.points),o))}if(a.size!==c.length)return null;const u=(o+i)/2+1e-6;for(const[h,d]of A){const p=a.get(h);if(!p||Math.abs(p.track-d)>u)return null}const g=c.map(h=>{const d=a.get(h.connection.connection.name),p=xue(d.points);return{item:h,points:p,segments:c$(p,o)}});return hvo({paths:g,obstacles:e.obstacles,traceWidth:o,clearance:i})?g.map(dvo):null}var mvo=t=>t.process??{env:{}};function _vo(t){const{bus:e}=t;let n=[...t.plans];if(e.maxLengthSkew===void 0)return n;const o=n.filter(i=>i.busId===e.busId).toSorted((i,r)=>r.length-i.length);for(const i of o){const r=Math.min(...n.filter(a=>a.busId===e.busId).map(a=>a.length));if(i.length-r<=e.maxLengthSkew||!i.via||i.additionalVias?.length||i.planeEndpointVia||i.segments.filter(a=>a.layer===i.sourceLayer).length!==1)continue;const s=e.connections.find(a=>a.connectionIndex===i.connectionIndex);for(const a of[!0,!1]){const A=rNt({...t,bus:{...e,connections:[s],routableEscapeLayers:[i.targetLayer]},terminals:[{connection:s,viaPoint:i.via.center,exitPoint:i.exitPoint}],targetLayer:i.targetLayer,acceptedPlans:n.filter(l=>l!==i),allowBlindAndBuriedVias:!1,gridStepDivisor:2,alignGridToPads:a,maximumRouteOrderAttempts:1})?.[0];if(!A||A.length>=i.length-1e-6)continue;const c=n.map(l=>l===i?A:l);if(Wh({...t,plans:c,allowBlindAndBuriedVias:!1})){n=c;break}}}return n}var p0=1e-6;function aI(t,e){return tn(t,e)<=p0}function oRt(t){return"layer"in t?[t.layer]:t.layers}function cR(t){return[...t.segments,...t.planeEndpointSegments??[]]}function lR(t){return[t.via,...t.additionalVias??[],t.planeEndpointVia].filter(e=>!!e)}function iRt(t,e){return aI(t,e)&&oRt(t).join("\0")===oRt(e).join("\0")&&t.pointId===e.pointId&&t.pcb_port_id===e.pcb_port_id}function rRt(t,e){const n=t.x>=e.minX-p0&&t.x<=e.maxX+p0&&t.y>=e.minY-p0&&t.y<=e.maxY+p0,o=Math.abs(t.x-e.minX)<=p0||Math.abs(t.x-e.maxX)<=p0||Math.abs(t.y-e.minY)<=p0||Math.abs(t.y-e.maxY)<=p0;return n&&o}function fvo(t,e,n){if(!(t.x>=n.minX-p0&&t.x<=n.maxX+p0&&t.y>=n.minY-p0&&t.y<=n.maxY+p0))return!1;switch(e){case"left":return Math.abs(t.x-n.minX)<=p0;case"right":return Math.abs(t.x-n.maxX)<=p0;case"top":return Math.abs(t.y-n.maxY)<=p0;case"bottom":return Math.abs(t.y-n.minY)<=p0}}function sRt(t,e){return t.x>=e.minX-p0&&t.x<=e.maxX+p0&&t.y>=e.minY-p0&&t.y<=e.maxY+p0}function Oa(t,e,n,o,i){t.push({code:e,message:n,...o?{connectionName:o.connectionName,busId:o.busId}:{},...i?{otherConnectionName:i}:{}})}function aRt(t){const{trace:e,plan:n,issues:o}=t,i=[];let r,s;for(const a of e.route){if(a.route_type==="via"){(!r||!aI(r,a)||r.layer!==a.from_layer)&&Oa(o,"disconnected-trace",`Trace ${e.pcb_trace_id} reaches a via without a matching ${a.from_layer} wire endpoint`,n),s=a;continue}if(a.route_type!=="wire"){Oa(o,"unsupported-route-point",`Trace ${e.pcb_trace_id} contains unsupported ${a.route_type} geometry`,n);continue}if(s){(!aI(a,s)||a.layer!==s.to_layer)&&Oa(o,"disconnected-trace",`Trace ${e.pcb_trace_id} does not continue from its via on ${s.to_layer}`,n),r=a,s=void 0;continue}r&&(r.layer!==a.layer?Oa(o,"disconnected-trace",`Trace ${e.pcb_trace_id} changes from ${r.layer} to ${a.layer} without a via`,n):aI(r,a)||i.push({start:{x:r.x,y:r.y},end:{x:a.x,y:a.y},width:a.width,layer:a.layer})),r=a}return s&&Oa(o,"disconnected-trace",`Trace ${e.pcb_trace_id} ends at a via without a wire on ${s.to_layer}`,n),i}function Ivo(t){const{plan:e,preparedBus:n,inputSrj:o,outputSrj:i,sharedBoundary:r,issues:s}=t,a=o.connections[e.connectionIndex];if(!a||a.name!==e.connectionName){Oa(s,"connection-mismatch",`Plan index ${e.connectionIndex} does not identify connection ${e.connectionName}`,e);return}const A=n?.connections.find(_=>_.connectionIndex===e.connectionIndex);(!A||A.sourcePointIndex!==e.sourcePointIndex||!iRt(A.sourcePoint,e.sourcePoint)||A.sourceObstacle.obstacleId!==e.sourceObstacle.obstacleId)&&Oa(s,"source-mismatch",`Plan ${e.connectionName} does not start at its prepared component endpoint`,e),n?.termination.type!==e.termination.type&&Oa(s,"termination-mismatch",`Plan ${e.connectionName} does not use its bus termination`,e);const c=Ds(n?.exitEdge,n?.preferredExit);if(n?.exitEdge!==e.exitEdge||c!==e.cornerBandSide?Oa(s,"output-exit-mismatch",`Plan ${e.connectionName} does not retain its prepared boundary edge and band`,e):n?.exitEdge&&!fvo(e.exitPoint,n.exitEdge,r)&&Oa(s,"output-exit-mismatch",`Plan ${e.connectionName} does not terminate on its declared ${n.exitEdge} edge`,e),!(o.allowViaInPad===!0&&e.termination.type==="plane"&&e.via!==void 0&&aI(e.via.center,e.sourcePoint)&&aI(e.exitPoint,e.sourcePoint))&&(e.segments.length===0||e.length<=p0))Oa(s,"not-broken-out",`Plan ${e.connectionName} has no non-zero escape geometry`,e);else{const _={minX:Math.min(o.bounds.minX,r.minX),maxX:Math.max(o.bounds.maxX,r.maxX),minY:Math.min(o.bounds.minY,r.minY),maxY:Math.max(o.bounds.maxY,r.maxY)};e.segments.some(f=>!sRt(f.start,_)||!sRt(f.end,_))&&Oa(s,"outside-routing-bounds",`Plan ${e.connectionName} leaves the routable SRJ/shared-boundary area`,e),e.segments[0]&&!aI(e.segments[0].start,e.sourcePoint)&&Oa(s,"disconnected-trace",`Plan ${e.connectionName} does not start at its source pad`,e),e.segments.at(-1)&&!aI(e.segments.at(-1).end,e.exitPoint)&&Oa(s,"disconnected-trace",`Plan ${e.connectionName} does not end at its declared exit`,e);for(let f=1;f<e.segments.length;f++){const I=e.segments[f-1],C=e.segments[f];aI(I.end,C.start)||Oa(s,"disconnected-trace",`Plan ${e.connectionName} has a gap between route segments`,e);const y=lR(e).find(x=>aI(I.end,x.center)&&x.spanLayers.includes(I.layer)&&x.spanLayers.includes(C.layer));I.layer!==C.layer&&!y&&Oa(s,"disconnected-trace",`Plan ${e.connectionName} changes layers without a connecting via`,e)}}const u=[...e.segments,...e.planeEndpointSegments??[]].reduce((_,f)=>_+tn(f.start,f.end),0);Math.abs(u-e.length)>1e-6&&Oa(s,"plan-length-mismatch",`Plan ${e.connectionName} declares ${e.length.toFixed(6)}mm but contains ${u.toFixed(6)}mm of routed copper`,e);const g=aRt({trace:e.trace,plan:e,issues:s}),h=e.segments.filter(_=>tn(_.start,_.end)>p0);if((g.length!==h.length||g.some((_,f)=>{const I=h[f];return!I||_.layer!==I.layer||Math.abs(_.width-I.width)>p0||!aI(_.start,I.start)||!aI(_.end,I.end)}))&&Oa(s,"trace-plan-mismatch",`Trace ${e.trace.pcb_trace_id} does not encode its declared route segments`,e),e.planeEndpointTrace||e.planeEndpointSegments||e.planeEndpointVia)if(!e.planeEndpointTrace||!e.planeEndpointSegments||!e.planeEndpointVia)Oa(s,"trace-plan-mismatch",`Plane endpoint geometry for ${e.connectionName} is incomplete`,e);else{const _=aRt({trace:e.planeEndpointTrace,plan:e,issues:s});(_.length!==e.planeEndpointSegments.length||_.some((f,I)=>{const C=e.planeEndpointSegments?.[I];return!C||f.layer!==C.layer||Math.abs(f.width-C.width)>p0||!aI(f.start,C.start)||!aI(f.end,C.end)})||tn(e.planeEndpointVia.center,e.targetPoint)<=p0)&&Oa(s,"trace-plan-mismatch",`Trace ${e.planeEndpointTrace.pcb_trace_id} does not encode a valid offset plane-to-endpoint dogbone`,e)}const d=e.trace.route.find(_=>"x"in _&&"y"in _),p=[...e.trace.route].reverse().find(_=>"x"in _&&"y"in _);(!d||!p||!aI(d,e.sourcePoint)||!aI(p,e.exitPoint))&&Oa(s,"disconnected-trace",`Trace ${e.trace.pcb_trace_id} does not span its source and exit`,e);const m=i.connections.find(_=>_.name===e.connectionName);if(e.termination.type==="boundary")if(!m)Oa(s,"output-connection-missing",`Boundary connection ${e.connectionName} was removed from the output`,e);else{const _=m.pointsToConnect[e.sourcePointIndex];(!_||!aI(_,e.exitPoint)||!("layer"in _)||_.layer!==e.targetLayer)&&Oa(s,"output-exit-mismatch",`Output connection ${e.connectionName} is not attached to its fanout exit`,e);for(let f=0;f<a.pointsToConnect.length;f++){if(f===e.sourcePointIndex)continue;const I=a.pointsToConnect[f],C=m.pointsToConnect[f];(!I||!C||!iRt(I,C))&&Oa(s,"downstream-endpoint-lost",`Output connection ${e.connectionName} did not retain downstream endpoint ${f}`,e)}}else m&&Oa(s,"plane-connection-retained",`Plane-terminated connection ${e.connectionName} remains in the output`,e)}function Cvo(t,e){const n=cR(t),o=cR(e),i=lR(t),r=lR(e);for(const s of n){for(const a of o)if(s.layer===a.layer&&tu(s.start,s.end,a.start,a.end)<=(s.width+a.width)/2+p0)return!0;for(const a of r)if(a.spanLayers.includes(s.layer)&&Cr(a.center,s.start,s.end)<=a.diameter/2+s.width/2+p0)return!0}for(const s of i){for(const a of o)if(s.spanLayers.includes(a.layer)&&Cr(s.center,a.start,a.end)<=s.diameter/2+a.width/2+p0)return!0;for(const a of r)if(s.spanLayers.some(A=>a.spanLayers.includes(A))&&tn(s.center,a.center)<=(s.diameter+a.diameter)/2+p0)return!0}return!1}function yvo(t){const{plans:e,inputSrj:n,sharedBoundary:o,issues:i}=t,r=new Set,s=new Map;for(const A of e)s.set(A,[]);for(let A=0;A<e.length;A++){const c=e[A];(c.termination.type==="plane"?c.via:c.segments.some(l=>rRt(l.start,o)||rRt(l.end,o)))&&r.add(c);for(let l=A+1;l<e.length;l++){const u=e[l];!Px(n,c.connectionName,u.connectionName)||!Cvo(c,u)||(s.get(c).push(u),s.get(u).push(c))}}const a=[...r];for(;a.length>0;){const A=a.shift();for(const c of s.get(A)??[])r.has(c)||(r.add(c),a.push(c))}for(const A of e)r.has(A)||Oa(i,"not-broken-out",A.termination.type==="boundary"?`Connection ${A.connectionName} has no continuous same-net copper path to the shared boundary`:`Plane connection ${A.connectionName} has no terminating via`,A);return r}function xvo(t){const{plans:e,inputSrj:n,clearance:o,allowBlindAndBuriedVias:i,issues:r}=t;for(const s of e){r$(s,o).some(A=>A.kind!=="clearance")&&Oa(r,"source-pad-reentry",`Trace ${s.connectionName} returns into its source pad after leaving it`,s);const a=cR(s);for(let A=0;A<a.length;A++){const c=a[A];for(const l of n.obstacles){if(!l.layers.includes(c.layer)||n4(n,l,s.connectionName)||A===0&&l.obstacleId===s.sourceObstacle.obstacleId&&c.layer===s.sourceLayer||jj({inputSrj:n,segment:c,bodyObstacle:l,connectionName:s.connectionName}))continue;const u=Tl(c,l),g=c.width/2+o;u<g-1e-9&&Oa(r,"obstacle-clearance",`Trace ${s.connectionName} on ${c.layer} is ${u.toFixed(4)}mm from different-net obstacle ${l.obstacleId}; ${g.toFixed(4)}mm is required`,s)}}for(const A of lR(s))for(const c of n.obstacles){if(!c.layers.some(g=>A.spanLayers.includes(g))||n4(n,c,s.connectionName))continue;const l=wx(A.center,c),u=A.diameter/2+o;l<u-1e-9&&Oa(r,"via-obstacle-clearance",`Via ${s.connectionName} is ${l.toFixed(4)}mm from different-net obstacle ${c.obstacleId} on its layer span; ${u.toFixed(4)}mm is required`,s)}for(const A of Z7(n,i))if(!(s.connectionName===A.connectionName||Px(n,s.connectionName,A.connectionName))){for(const c of cR(s)){for(const l of A.segments)Zm(c,l,o)||Oa(r,"different-net-trace-clearance",`Trace ${s.connectionName} violates routed trace ${A.trace.pcb_trace_id} on ${c.layer}`,s,A.connectionName);for(const l of A.vias)l.spanLayers.includes(c.layer)&&Cr(l.center,c.start,c.end)<l.diameter/2+c.width/2+o-1e-9&&Oa(r,"different-net-trace-via-clearance",`Trace ${s.connectionName} violates a via in routed trace ${A.trace.pcb_trace_id} on ${c.layer}`,s,A.connectionName)}for(const c of lR(s)){for(const l of A.segments)c.spanLayers.includes(l.layer)&&Cr(c.center,l.start,l.end)<c.diameter/2+l.width/2+o-1e-9&&Oa(r,"different-net-trace-via-clearance",`Via ${s.connectionName} violates routed trace ${A.trace.pcb_trace_id} on ${l.layer}`,s,A.connectionName);for(const l of A.vias)c.spanLayers.some(u=>l.spanLayers.includes(u))&&tn(c.center,l.center)<(c.diameter+l.diameter)/2+o-1e-9&&Oa(r,"different-net-via-clearance",`Via ${s.connectionName} violates a via in routed trace ${A.trace.pcb_trace_id}`,s,A.connectionName)}}}for(let s=0;s<e.length;s++){const a=e[s];for(let A=s+1;A<e.length;A++){const c=e[A];if(Px(n,a.connectionName,c.connectionName))continue;const l=cR(a),u=cR(c),g=lR(a),h=lR(c);for(const d of l){for(const p of u)Zm(d,p,o)||Oa(r,"different-net-trace-clearance",`Different-net traces ${a.connectionName} and ${c.connectionName} intersect or violate clearance on ${d.layer}`,a,c.connectionName);for(const p of h)p.spanLayers.includes(d.layer)&&Cr(p.center,d.start,d.end)<p.diameter/2+d.width/2+o-1e-9&&Oa(r,"different-net-trace-via-clearance",`Trace ${a.connectionName} violates via clearance to ${c.connectionName} on ${d.layer}`,a,c.connectionName)}for(const d of g){for(const p of u)d.spanLayers.includes(p.layer)&&Cr(d.center,p.start,p.end)<d.diameter/2+p.width/2+o-1e-9&&Oa(r,"different-net-trace-via-clearance",`Via ${a.connectionName} violates trace clearance to ${c.connectionName} on ${p.layer}`,a,c.connectionName);for(const p of h)d.spanLayers.some(m=>p.spanLayers.includes(m))&&tn(d.center,p.center)<(d.diameter+p.diameter)/2+o-1e-9&&Oa(r,"different-net-via-clearance",`Vias ${a.connectionName} and ${c.connectionName} violate clearance on an overlapping layer span`,a,c.connectionName)}}}}function Evo(t,e,n){const o=t.differentialPairs;if(o===void 0)return;if(!Array.isArray(o)){Oa(n,"invalid-differential-pair","Differential pairs must be an array");return}const i=new Map;t.connections.forEach((r,s)=>{const a=i.get(r.name)??[];a.push(s),i.set(r.name,a)}),o.forEach((r,s)=>{const a=r,A=a?.connectionNames,c=a?.lengthTolerance;if(!Array.isArray(A)||A.length!==2||A.some(h=>typeof h!="string"||h.length===0)||A[0]===A[1]||typeof c!="number"||!Number.isFinite(c)||c<0){Oa(n,"invalid-differential-pair",`Differential pair ${s} must name two distinct connections and a finite nonnegative length tolerance`);return}const l=[];for(const h of A){const d=i.get(h),p=e.get(h);if(d?.length!==1||p?.length!==1||p[0].connectionIndex!==d[0]){Oa(n,"invalid-differential-pair",`Differential pair ${s} cannot resolve exactly one original plan for connection ${h}`);return}l.push(p[0])}const u=l.map(h=>cR(h).reduce((d,p)=>d+tn(p.start,p.end),0));if(u.some(h=>!Number.isFinite(h))){Oa(n,"invalid-differential-pair",`Differential pair ${s} has nonfinite routed copper length`,l[0],A[1]);return}const g=Math.abs(u[0]-u[1]);g>c+p0&&Oa(n,"differential-pair-length-skew",`Differential pair ${A[0]}/${A[1]} has ${g.toFixed(6)}mm routed-length skew; ${c.toFixed(6)}mm is allowed`,l[0],A[1])})}function Bvo(t){const{inputSrj:e,outputSrj:n,plans:o,preparedBuses:i,sharedBoundary:r,clearance:s,allowBlindAndBuriedVias:a=!0}=t,A=[],c=new Map,l=new Map(i.map(g=>[g.busId,g]));for(const g of o){const h=c.get(g.connectionName)??[];h.push(g),c.set(g.connectionName,h)}Evo(e,c,A);for(const g of i){if(g.maxLengthSkew===void 0)continue;const h=o.filter(m=>m.busId===g.busId);if(h.length<2)continue;const d=h.map(m=>m.length),p=Math.max(...d)-Math.min(...d);p>g.maxLengthSkew+1e-6&&Oa(A,"bus-length-skew",`Bus ${g.busId} has ${p.toFixed(6)}mm routed-length skew; ${g.maxLengthSkew.toFixed(6)}mm is allowed`,h[0])}for(const g of e.connections){const h=c.get(g.name)??[];h.length===0?Oa(A,"missing-plan",`Connection ${g.name} has no fanout plan`):h.length>1&&Oa(A,"duplicate-plan",`Connection ${g.name} has ${h.length} fanout plans`,h[0])}for(const g of o){if(!e.connections.some(h=>h.name===g.connectionName)){Oa(A,"unknown-plan",`Plan ${g.connectionName} is not an input connection`,g);continue}Ivo({plan:g,preparedBus:l.get(g.busId),inputSrj:e,outputSrj:n,sharedBoundary:r,issues:A})}const u=yvo({plans:o,inputSrj:e,sharedBoundary:r,issues:A});return xvo({plans:o,inputSrj:e,clearance:s,allowBlindAndBuriedVias:a,issues:A}),{valid:A.length===0,checkedConnectionCount:e.connections.length,brokenOutConnectionCount:new Set([...u].map(g=>g.connectionName)).size,issues:A}}var ARt=["#ef4444","#2563eb","#16a34a","#9333ea","#f59e0b","#0891b2","#db2777","#65a30d","#4f46e5","#ea580c"];function bvo(t){if(!Number.isInteger(t)||t<0)throw new Error(`FanoutSolver: copper layer index must be a non-negative integer, received ${t}`);return ARt[t%ARt.length]}var Svo=new Set(["top","bottom","inner1","inner2","inner3","inner4","inner5","inner6","inner7","inner8"]),Qvo={"0603":{padLength:.8,padWidth:.95},1206:{padLength:.6,padWidth:1.6},"1206x4_pair":{padLength:.8,padWidth:.5}},l$=(t,e)=>{const n=t.indexOf(e);if(n<0)throw new Error(`FanoutSolver: cannot visualize unknown copper layer "${e}"`);return n},u$=(t,e)=>`z${[...new Set(e.map(o=>l$(t,o)))].sort((o,i)=>o-i).join(",")}`,vvo=t=>{const e="layers"in t?t.layers:void 0;return e&&e.length>0?e:[t.layer]},wvo=(t,e)=>t.__zLayers&&t.__zLayers.length>0?[...new Set(t.__zLayers)].filter(n=>Number.isInteger(n)&&n>=0&&n<e.length).sort((n,o)=>n-o):[...new Set(t.layers.map(n=>l$(e,n)))].sort((n,o)=>n-o),Pvo=(t,e,n)=>{const o=l$(t,e),i=l$(t,n);return t.slice(Math.min(o,i),Math.max(o,i)+1)},cRt=(...t)=>t.find(e=>typeof e=="number"&&Number.isFinite(e)),Mvo=t=>{const e=cRt(t.min_via_hole_diameter,t.minViaHoleDiameter),n=cRt(t.min_via_pad_diameter,t.minViaPadDiameter,t.minViaDiameter);return Math.max(n??t.minViaDiameter??.3,e??0)},Dvo=t=>Object.fromEntries(t.map((e,n)=>[e.name,`hsl(${n*340/t.length}, 100%, 50%)`])),Nvo=(t,e,n)=>{const o=(1-Math.abs(2*n-1))*e,i=(t%360+360)%360/60,r=o*(1-Math.abs(i%2-1)),[s,a,A]=i<1?[o,r,0]:i<2?[r,o,0]:i<3?[0,o,r]:i<4?[0,r,o]:i<5?[r,0,o]:[o,0,r],c=n-o/2;return[s,a,A].map(l=>Math.round((l+c)*255))},tMe=(t,e)=>{let o={blue:[0,0,255],orange:[255,165,0],purple:[128,0,128],red:[255,0,0]}[t],i=1;const r=/^rgba?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)(?:\s*,\s*([\d.]+))?\s*\)$/.exec(t);r&&(o=[Number(r[1]),Number(r[2]),Number(r[3])],i=r[4]===void 0?1:Number(r[4]));const s=/^hsl\(\s*([\d.-]+)\s*,\s*([\d.]+)%\s*,\s*([\d.]+)%\s*\)$/.exec(t);if(s&&(o=Nvo(Number(s[1]),Number(s[2])/100,Number(s[3])/100)),!o)return t;const a=+Math.max(0,i*100-e*100).toFixed(2)/100;if(a>=1){const A=o.map(c=>Math.round(c).toString(16).padStart(2,"0")).join("");return A[0]===A[1]&&A[2]===A[3]&&A[4]===A[5]?`#${A[0]}${A[2]}${A[4]}`:`#${A}`}return`rgba(${o.join(",")},${a})`},Rvo=t=>{const e=new Set;return t.filter(n=>e.has(n)?!1:(e.add(n),!0))},Tvo=t=>{const e=new Map,n=(o,i)=>{if(!o)return;const r=e.get(o)??[];r.includes(i)||r.push(i),e.set(o,r)};for(const o of t.connections){const i=o.__rootConnectionNames??[o.name];for(const r of i){n(o.name,r),n(r,r),n(o.__netConnectionName,r);for(const s of o.pointsToConnect)n(s.pointId,r),n(s.pcb_port_id,r)}}return o=>{const r=Rvo([...o.connectedTo.flatMap(s=>e.get(s)??[]),...(o.offBoardConnectsTo??[]).flatMap(s=>e.get(s)??[])]).join(", ");return o.layers.map(s=>r?`${s}
${r}`:s).join(`
`)}};function kvo(t){const e=Rb(t.layerCount),n=(t.traces??[]).some(g=>g.route.some((h,d)=>{const p=g.route[d+1];return h.route_type==="wire"&&p?.route_type==="wire"&&p.layer===h.layer&&!Svo.has(h.layer)})),o=new Set(t.connections.map(({name:g})=>g)),i=n?[...new Set((t.traces??[]).map(({connection_name:g})=>g).filter(g=>g&&!o.has(g)))].map(g=>({name:g,pointsToConnect:[]})):[],r=[...t.connections,...i],s=Dvo(r),a=Tvo({...t,connections:r}),A=[],c=[],l=[],u=[];for(const g of r)for(const h of g.pointsToConnect){const d=vvo(h),p=g.__rootConnectionNames??[g.name];u.push({x:h.x,y:h.y,color:s[g.name],layer:u$(e,d),label:[g.name,p.join(", "),d.join(",")].join(`
`)})}for(const g of t.traces??[]){const h=g.route.filter(p=>p.route_type==="jumper"),d=(p,m)=>h.some(_=>Math.abs(p.x-_.start.x)<.01&&Math.abs(p.y-_.start.y)<.01&&Math.abs(m.x-_.end.x)<.01&&Math.abs(m.y-_.end.y)<.01||Math.abs(p.x-_.end.x)<.01&&Math.abs(p.y-_.end.y)<.01&&Math.abs(m.x-_.start.x)<.01&&Math.abs(m.y-_.start.y)<.01);for(const p of g.route)if(p.route_type==="via"){const m=Pvo(e,p.from_layer,p.to_layer);c.push({center:{x:p.x,y:p.y},radius:(p.via_diameter??Mvo(t))/2,fill:n?s[g.connection_name]:"blue",stroke:"none",layer:u$(e,m)})}else p.route_type==="through_obstacle"&&A.push({points:[p.start,p.end],strokeColor:tMe(s[g.connection_name]??"purple",.35),strokeWidth:p.width,strokeDash:[.1,.1],layer:u$(e,[p.from_layer,p.to_layer]),label:`${g.connection_name} through_obstacle`});for(let p=0;p<g.route.length-1;p++){const m=g.route[p],_=g.route[p+1];if(m.route_type==="jumper"){const f=s[g.connection_name]??"rgba(255, 165, 0, 0.8)",I=Qvo[m.footprint==="1206x4_pair"?"1206x4_pair":"0603"],C=Math.abs(m.end.x-m.start.x)>Math.abs(m.end.y-m.start.y),y=C?I.padLength:I.padWidth,x=C?I.padWidth:I.padLength,E=u$(e,[m.layer]);for(const B of[m.start,m.end])l.push({center:B,width:y,height:x,fill:tMe(f,.5),stroke:"rgba(0, 0, 0, 0.5)",layer:E});A.push({points:[m.start,m.end],strokeColor:"rgba(100, 100, 100, 0.8)",strokeWidth:I.padWidth*.3,layer:E})}else if(m.route_type==="wire"&&_.route_type==="wire"&&_.layer===m.layer&&!d(m,_)){const f=l$(e,m.layer);A.push({points:[{x:m.x,y:m.y},{x:_.x,y:_.y}],layer:`z${f}`,strokeWidth:m.width,strokeColor:bvo(f),...n?{label:g.connection_name}:{}})}}}for(const g of t.obstacles){if(g.isCopperPour)continue;const h=wvo(g,e);if(h.length===0)throw new Error(`FanoutSolver: cannot visualize obstacle "${g.obstacleId??"unknown"}" without a valid layer`);const d=h.length===1?e[h[0]]:void 0,p=tMe(d==="bottom"?"blue":"red",.5**h.length),m=g.shape,_={center:g.center,fill:p,layer:`z${h.join(",")}`,label:a(g)};m==="circle"?c.push({..._,radius:Math.min(g.width,g.height)/2}):l.push({..._,width:g.width,height:g.height,ccwRotationDegrees:g.ccwRotationDegrees})}for(const g of t.jumpers??[])for(const h of g.pads)l.push({center:h.center,width:h.width,height:h.height,ccwRotationDegrees:h.ccwRotationDegrees,fill:"rgba(255, 165, 0, 0.3)",stroke:"rgba(255, 165, 0, 0.8)",layer:u$(e,h.layers)});return{rects:l,circles:c,lines:A,points:u}}var FA=mvo(globalThis),Fvo=class extends fC{constructor(t,e,n,o,i){super(),this.solverName=t,this.generator=e,this.getVisualization=n,this.getStats=o,this.getProgress=i,this.MAX_ITERATIONS=1e6}solverName;generator;getVisualization;getStats;getProgress;output;hasOutput=!1;nextInput;getSolverName(){return this.solverName}_step(){if(this.activeSubSolver){if(this.activeSubSolver.step(),this.activeSubSolver.failed){this.failedSubSolvers=[...this.failedSubSolvers??[],this.activeSubSolver],this.error=this.activeSubSolver.error,this.failed=!0,this.activeSubSolver=null;return}this.activeSubSolver.solved&&(this.nextInput=this.activeSubSolver.getOutput(),this.activeSubSolver=null),this.stats=this.getStats();return}const t=this.generator.next(this.nextInput);if(this.nextInput=void 0,this.stats=this.getStats(),t.done){this.output=t.value,this.hasOutput=!0,this.solved=!0;return}i$(t.value)&&(this.activeSubSolver=t.value.solver)}computeProgress(){return this.getProgress()}getConstructorParams(){return[]}getOutput(){if(!this.solved||!this.hasOutput)throw new Error(`${this.solverName}: output requested before completion`);return this.output}visualize(){return this.activeSubSolver?.visualize()??this.getVisualization()}};function g$(t,e){if(!Number.isFinite(e)||e<=0)throw new Error(`FanoutSolver: ${t} must be a positive number, received ${e}`);return e}function Lvo(t,e){const n=g$("traceWidth",e.traceWidth??t.nominalTraceWidth??t.minTraceWidth),o=g$("viaDiameter",e.viaDiameter??t.minViaPadDiameter??t.min_via_pad_diameter??t.minViaDiameter??Math.max(n*2,.3)),i=g$("viaHoleDiameter",e.viaHoleDiameter??t.minViaHoleDiameter??t.min_via_hole_diameter??o*.5);if(i>=o)throw new Error(`FanoutSolver: viaHoleDiameter ${i} must be smaller than viaDiameter ${o}`);const r=g$("clearance",e.clearance??t.minViaEdgeToPadEdgeClearance??t.minTraceToPadEdgeClearance??t.defaultObstacleMargin??t.minTraceWidth),s=Rb(t.layerCount),a=e.escapeLayers??s;for(const c of a)if(!s.includes(c))throw new Error(`FanoutSolver: escape layer "${c}" is not available in a ${t.layerCount}-layer SimpleRouteJson`);if(new Set(a).size!==a.length)throw new Error("FanoutSolver: escapeLayers contains duplicates");const A=e.borderDistribution??"preserve";if(A!=="preserve"&&A!=="even")throw new Error(`FanoutSolver: borderDistribution must be "preserve" or "even", received "${A}"`);return{traceWidth:n,viaDiameter:o,viaHoleDiameter:i,clearance:r,compactBusTracks:e.compactBusTracks??!1,allowBlindAndBuriedVias:e.allowBlindAndBuriedVias??!0,allowSameNetMerges:e.allowSameNetMerges??!1,densePlaneReservationBusIds:e.densePlaneReservationBusIds??[],denseUnrestrictedPlaneRoutingBusIds:e.denseUnrestrictedPlaneRoutingBusIds??[],singleLayerPushAndShove:e.singleLayerPushAndShove??!1,singleLayerAdaptiveExits:e.singleLayerAdaptiveExits??!1,borderDistribution:A,layerNames:s,escapeLayers:a,maxLayerCombinations:e.maxLayerCombinations===void 0?256:g$("maxLayerCombinations",e.maxLayerCombinations),balanceLayerLoadByConnectionCount:e.balanceLayerLoadByConnectionCount??!1}}function Hvo(t,e){const n=new Set,o=Math.max(e.traceWidth+e.clearance,e.viaDiameter+e.clearance),i=Math.max(e.viaDiameter/2+e.clearance,o);for(const r of t){const s=Ds(r.exitEdge,r.preferredExit);if(!r.exitEdge||!s)continue;const a=`${r.exitEdge}:${s}`;if(n.has(a))continue;n.add(a);const A=r.exitEdge==="left"||r.exitEdge==="right"?r.sharedBoundary.maxY-r.sharedBoundary.minY:r.sharedBoundary.maxX-r.sharedBoundary.minX,c=r.cornerBandConnectionCount??r.connections.length,l=(c-1)*o/2,u=A/4-i;if(l>u+1e-6)throw new Error(`FanoutSolver: ${s} band on the ${r.exitEdge} edge cannot fit ${c} via-safe exits`)}}function Eue(t,e,n){const o=new Map(e.map(r=>[r.busId,r.connections.length])),i=new Map;for(const[r,s]of Object.entries(t))i.set(s,(i.get(s)??0)+(n?o.get(r)??1:1));return[...i.values()].reduce((r,s)=>r+s*s,0)}function Bue(t){return t.balanceLayerLoadByConnectionCount?.25:.01}function lRt(t,e,n){const o=+(t.termination.type==="plane")-+(e.termination.type==="plane");return n?-o:o}function bue(t){return t.reduce((e,n)=>e+ +!!n.via+(n.additionalVias?.length??0)+ +!!n.planeEndpointVia,0)}function wO(t){const e=t.connections.reduce((n,o)=>{const i=t.direction==="left"||t.direction==="right"?o.sourcePoint.x:o.sourcePoint.y;return n+i},0)/t.connections.length;switch(t.direction){case"right":return t.sharedBoundary.maxX-e;case"left":return e-t.sharedBoundary.minX;case"up":return t.sharedBoundary.maxY-e;case"down":return e-t.sharedBoundary.minY}}function nMe(t){const e=t.direction==="left"||t.direction==="right";return t.connections.some(n=>{const o=n.exitTargetPoint??n.targetPoint,i=e?n.sourcePoint.y:n.sourcePoint.x,r=e?o.y:o.x;return Math.abs(i-r)>1e-6})}function PO(t){if(t.connections.length===0||t.connections.some(o=>!o.hasExplicitLayeredExitTarget||!o.exitTargetPoint?.layer))return;const e=new Set(t.connections.map(o=>o.exitTargetPoint.layer));if(e.size!==1)return;const[n]=e;return n}function Ovo(t){const e=t.direction==="left"||t.direction==="right",n=e?t.xCoordinates:t.yCoordinates,o=t.connections.reduce((r,s)=>r+(e?s.sourcePoint.x:s.sourcePoint.y),0)/t.connections.length,i=t.direction==="right"||t.direction==="up"?Math.max(...n):Math.min(...n);return Math.abs(o-i)<1e-6}function oMe(t){const e=t.direction==="left"||t.direction==="right",n=e?t.xCoordinates:t.yCoordinates,o=t.connections.reduce((s,a)=>s+(e?a.sourcePoint.x:a.sourcePoint.y),0)/t.connections.length,i=t.direction==="right"||t.direction==="up"?Math.max(...n):Math.min(...n),r=e?t.pitchX:t.pitchY;return Math.round(Math.abs(o-i)/r)}function Gvo(t){const{buses:e,escapeLayers:n,escapeLayersByBusId:o,preferOrderedCoordinatedWindingLayers:i}=t,r={},s=new Map;let a=0;for(const A of e){const c=s.get(A.componentId)??new Set;c.add(A.direction),s.set(A.componentId,c)}for(const A of e){const c=A.connections[0]?.sourceLayer;if(!c)throw new Error(`FanoutSolver: bus "${A.busId}" has no connections`);if(A.termination.type==="plane"){r[A.busId]=A.termination.layer;continue}const l=o[A.busId]??n,u=l.filter(h=>h!==c),g=PO(A);if(g&&l.includes(g))r[A.busId]=g;else if(!a6(A)&&l.includes(c)&&(nMe(A)||Ovo(A)))r[A.busId]=c;else if(u.length>0){const h=A.connections.map(I=>I.sourcePoint.x),d=A.connections.map(I=>I.sourcePoint.y),p=I=>e.filter(C=>{const y=C.connections[0]?.sourcePoint;return C.termination.type==="boundary"&&y!==void 0&&y.x>Math.min(...h)+1e-9&&y.x<Math.max(...h)-1e-9&&y.y>Math.min(...d)+1e-9&&y.y<Math.max(...d)-1e-9&&PO(C)===I&&uRt({singletonBus:C,singletonTargetLayer:I,wideBuses:[A]})}).length,m=u.toSorted((I,C)=>p(I)-p(C));if(p(m[0])<p(u[0])){r[A.busId]=m[0];continue}if(i&&a6(A)){const I=Ds(A.exitEdge,A.preferredExit),C=y=>{if(!A.exitEdge||A.connections.length<8)return 0;const x=A.exitEdge==="left"||A.exitEdge==="right",E=x?"y":"x",B=x?A.sharedBoundary.minY:A.sharedBoundary.minX,S=x?A.sharedBoundary.maxY:A.sharedBoundary.maxX;if(!I){const k=A.connections.map(j=>{const J=j.exitTargetPoint??j.targetPoint;return Math.max(B,Math.min(S,J[E]))}),R=Math.min(...k),F=Math.max(...k),O=x?"x":"y",U=A.exitEdge==="right"||A.exitEdge==="top"?1:-1,Y=Math.min(...A.connections.map(j=>U*j.sourcePoint[O])),W=Math.min(...A.connections.map(j=>j.sourcePoint[E])),te=Math.max(...A.connections.map(j=>j.sourcePoint[E]));return e.reduce((j,J)=>{const oe=Ds(J.exitEdge,J.preferredExit);if(J===A||J.termination.type!=="boundary"||J.componentId!==A.componentId||J.exitEdge!==A.exitEdge||!oe||PO(J)!==y)return j;const ie=B+(S-B)*(oe==="minimum"?.25:.75),ne=(Math.max(J.connections.length,J.cornerBandConnectionCount??0)-1)*Math.max(t.traceWidth+t.clearance,t.viaDiameter+t.clearance)/2,le=t.traceWidth+t.clearance,ge=F+le>=ie-ne&&R-le<=ie+ne,_e=Math.max(...J.connections.map(ue=>U*ue.sourcePoint[O]))<Y-1e-9&&Math.min(...J.connections.map(ue=>ue.sourcePoint[E]))<=te+le&&Math.max(...J.connections.map(ue=>ue.sourcePoint[E]))>=W-le;return j+(ge||_e?J.connections.length:0)},0)}const Q=B+(S-B)*(I==="minimum"?.25:.75),w=Math.max(t.traceWidth+t.clearance,t.viaDiameter+t.clearance),M=(Math.max(A.connections.length,A.cornerBandConnectionCount??0)-1)*w/2;return e.reduce((k,R)=>R===A||R.termination.type!=="boundary"||R.componentId!==A.componentId||R.exitEdge!==A.exitEdge||Ds(R.exitEdge,R.preferredExit)||PO(R)!==y?k:k+R.connections.filter(F=>{const O=F.exitTargetPoint??F.targetPoint,U=Math.max(B,Math.min(S,O[E]));return Math.abs(U-Q)<=M+t.traceWidth+t.clearance}).length,0)};r[A.busId]=u.toSorted((y,x)=>C(y)-C(x))[0];continue}const _=s.get(A.componentId);if(_.has("left")&&_.has("right")||_.has("up")&&_.has("down")){const I=oMe(A);r[A.busId]=u[Math.max(I-1,0)%u.length]}else r[A.busId]=u[a%u.length],a++}else r[A.busId]=c}return r}function Yvo(t){const{initialAssignment:e,generatedAssignments:n,maxAssignments:o}=t,i=JSON.stringify(e);return[e,...n.filter(r=>JSON.stringify(r)!==i)].slice(0,o)}function a6(t){return!!(t.exitEdge&&t.termination.type==="boundary"&&t.connections.length>0&&t.connections.every(e=>e.hasExplicitLayeredExitTarget===!0))}function iMe(t){const e=t.length,n=t.filter(o=>o===1).length;return(e===5||e===6||e===7)&&n===1||e===8&&(n===1||n===2)||e===9&&n>=1&&n<=3}function Uvo(t){if(!iMe(t))return 0;const e=t.filter(n=>n===1).length;return Math.max(1,e-1)}function uRt(t){const e=t.singletonBus.connections[0]?.sourcePoint;return t.singletonBus.connections.length!==1||!e?!1:t.wideBuses.some(n=>{const o=n.routableEscapeLayers??n.allowedLayers??[];if(n.connections.length<8||n.componentId!==t.singletonBus.componentId||n.exitEdge!==t.singletonBus.exitEdge||o.length<2||!o.includes(t.singletonTargetLayer))return!1;const i=n.connections.map(s=>s.sourcePoint.x),r=n.connections.map(s=>s.sourcePoint.y);return e.x>=Math.min(...i)-1e-9&&e.x<=Math.max(...i)+1e-9&&e.y>=Math.min(...r)-1e-9&&e.y<=Math.max(...r)+1e-9})}function Kvo(t){const e=Math.max(t.traceWidth+t.clearance,t.viaDiameter+t.clearance);return-t.leadingLaneCount*e/2}function Vvo(t){return t.boundaryBusCount===5||t.boundaryBusCount>9?!1:t.boundaryBusCount===6||t.boundaryBusCount===7||t.boundaryBusCount===8||t.boundaryBusCount===9?t.connectionCount>2&&t.rawSkew-t.maximumSkew>Math.max(1,t.maximumSkew*.5):t.rawSkew-t.maximumSkew>Math.max(1,t.maximumSkew*.25)}function d$(t){const e=t.connections[0],n=e?.exitTargetPoint;let o=0;if(e&&n){const i=n.x-e.sourcePoint.x,r=n.y-e.sourcePoint.y;o=t.direction==="right"?i:t.direction==="left"?-i:t.direction==="up"?r:-r}return{isCorner:!!Ds(t.exitEdge,t.preferredExit),targetProjection:o}}function zvo(t,e){const n=d$(t),o=d$(e);return Number(n.isCorner)-Number(o.isCorner)||(n.isCorner&&o.isCorner?n.targetProjection-o.targetProjection:0)||t.busId.localeCompare(e.busId)}function Jvo(t,e){const n=d$(t),o=d$(e);return Number(n.isCorner)-Number(o.isCorner)||(n.isCorner&&o.isCorner?+(n.targetProjection>0)-+(o.targetProjection>0):0)||t.busId.localeCompare(e.busId)}function Wvo(t){const{pairBuses:e}=t,n=e[0],o=n?.connections[0]?.sourceLayer;if(t.boundaryBusCount!==7&&t.boundaryBusCount!==8&&t.boundaryBusCount!==9||e.length!==3||n===void 0||n.exitEdge===void 0||n.assignedLayer===void 0||o===void 0||e.some(r=>r.connections.length!==2||r.componentId!==n.componentId||r.exitEdge!==n.exitEdge||r.assignedLayer!==n.assignedLayer||r.connections.some(s=>{const a=s.exitTargetPoint;return s.sourceLayer!==o||a?.layer!==n.assignedLayer||!Number.isFinite(s.sourcePoint.x)||!Number.isFinite(s.sourcePoint.y)||!Number.isFinite(a?.x)||!Number.isFinite(a?.y)})))return null;const i=r=>Math.max(...r.connections.map(s=>{const a=s.exitTargetPoint;return Math.hypot(a.x-s.sourcePoint.x,a.y-s.sourcePoint.y)}));return e.map(r=>Number(i(r).toFixed(9)))}function jvo(t){const{bus:e,srj:n,config:o,staticClearanceCache:i}=t,r=e.allowedLayers,s=r===void 0?o.escapeLayers:o.escapeLayers.filter(c=>r.includes(c));if(a6(e))return s;const a=s.filter(c=>nR({srj:n,bus:e,targetLayer:c,acceptedPlans:[],layerNames:o.layerNames,traceWidth:o.traceWidth,viaDiameter:o.viaDiameter,viaHoleDiameter:o.viaHoleDiameter,clearance:o.clearance,compactBusTracks:o.compactBusTracks,allowBlindAndBuriedVias:o.allowBlindAndBuriedVias,allowSameNetMerges:o.allowSameNetMerges,staticClearanceCache:i})!==null);return a.length>0?a:s}var Sue=class extends fC{constructor(t,e={}){super(),this.inputSrj=t,this.options=e,this.routingSrj={...t,obstacles:[...t.obstacles]},this.config=Lvo(t,e),this.preparedBuses=IQo(this.routingSrj,e),Hvo(this.preparedBuses,this.config);for(const i of this.preparedBuses){for(const s of i.connections){if(!s.hasExplicitLayeredExitTarget)continue;const a=s.exitTargetPoint?.layer;if(typeof a!="string"||a.length===0||!this.config.layerNames.includes(a))throw new Error(`FanoutSolver: connection exit target for "${s.connection.name}" uses unavailable layer "${String(a)}"`)}for(const s of i.allowedLayers??[])if(!this.config.layerNames.includes(s))throw new Error(`FanoutSolver: bus "${i.busId}" allows unavailable layer "${s}"`);if(i.termination.type==="boundary"&&i.allowedLayers!==void 0&&!i.allowedLayers.some(s=>this.config.escapeLayers.includes(s)))throw new Error(`FanoutSolver: bus "${i.busId}" has no allowed layer in escapeLayers`);if(i.routableEscapeLayers=this.config.escapeLayers.filter(s=>i.allowedLayers?.includes(s)??!0),i.termination.type!=="plane")continue;const r=i.termination.layer;if(!this.config.layerNames.includes(r))throw new Error(`FanoutSolver: plane-terminated bus "${i.busId}" targets unavailable layer "${r}"`);if(i.allowedLayers!==void 0&&!i.allowedLayers.includes(r))throw new Error(`FanoutSolver: plane-terminated bus "${i.busId}" targets disallowed layer "${r}"`);if(i.connections.some(s=>s.sourceLayer===r))throw new Error(`FanoutSolver: plane-terminated bus "${i.busId}" must target a layer below its source pad`)}this.boundaryBuses=this.preparedBuses.filter(i=>i.termination.type==="boundary"),this.fixedPlaneAssignments=Object.fromEntries(this.preparedBuses.flatMap(i=>i.termination.type==="plane"?[[i.busId,i.termination.layer]]:[]));const n=this.preparedBuses.length*3+8,o=this.boundaryBuses.length+1+this.config.maxLayerCombinations*n+this.preparedBuses.length*2+20;this.MAX_ITERATIONS=Math.max(1e4,o)}inputSrj;options;preparedBuses;attempts=[];layerAssignments=[];config;routingSrj;escapeLayersByBusId={};boundaryBuses;fixedPlaneAssignments;evaluatedAssignmentKeys=new Set;queuedAssignmentKeys=new Set;assignmentRepairDepthByKey=new Map;pendingRepairAssignments=[];routeStaticClearanceCache=new Map;routingPrefixCache=new Map;layerReservedRoutingEvaluated=!1;groupedBeamEvaluated=!1;routingInitialized=!1;nextCandidateLayerBusIndex=0;nextAssignmentIndex=0;nextGeneratedAssignmentIndex=0;activeOperation=null;inProgressPlans=[];activeRoutingVisualization=null;activeAdaptiveVisualization=null;bestAttempt=null;lengthMatchingFailure=null;endpointCompletion=null;getSolverName(){return"FanoutSolver"}shouldTryLayerReservedRouting(){if(this.config.allowBlindAndBuriedVias||this.boundaryBuses.length<4||(this.config.compactBusTracks||this.config.borderDistribution==="even")&&this.boundaryBuses.some(r=>r.connections.length>1&&r.connections.some(s=>!s.hasExplicitLayeredExitTarget)))return!1;const t=this.preparedBuses[0],e=this.boundaryBuses.reduce((r,s)=>r+s.connections.length,0);if(this.inputSrj.connections.length-e<e||this.preparedBuses.some(r=>r.componentId!==t.componentId||r.connections.some(s=>s.sourceLayer!=="top"))||this.boundaryBuses.some(r=>!r.exitEdge||r.exitEdge!==this.boundaryBuses[0].exitEdge||r.connections.length>8||!r.allowedLayers?.length||r.allowedLayers.some(s=>!this.config.escapeLayers.includes(s))))return!1;const o=new Map;let i=!1;for(const r of this.boundaryBuses){const s=r.allowedLayers.filter(a=>a!=="top");if(!s.length)return!1;if(s.length>1&&(i=!0),s.length===1&&r.connections.length>2){const a=s[0];o.set(a,(o.get(a)??0)+1)}}return i&&[...o.values()].some(r=>r>1)}*evaluateLayerReservedRoutingSteps(t=!1,e=!1){const n={...this.config,sourceOriginRouting:t,srj:this.routingSrj,buses:this.preparedBuses},o=e?TSo(n):tvo(n);let i=o.next();for(;!i.done;){if(i$(i.value)){this.stats={...this.stats,phase:"layer-reserved-route-layer",workUnit:i.value.routedConnectionCount,workUnitCount:this.inputSrj.connections.length,routedConnections:`${i.value.routedConnectionCount}/${this.inputSrj.connections.length}`,routingIterations:i.value.iterations};const c=yield i.value;i=o.next(c);continue}this.stats={...this.stats,phase:`layer-reserved-${i.value.phase}`,targetLayer:i.value.layer,workUnit:i.value.routedConnectionCount,workUnitCount:this.inputSrj.connections.length,routedConnections:`${i.value.routedConnectionCount}/${this.inputSrj.connections.length}`,routingIterations:i.value.iterations},yield,i=o.next()}if(!i.value||i.value.length!==this.inputSrj.connections.length)return null;const r=this.normalizeCompletePlanCorners(i.value);if(!r)return null;const s=aR({inputSrj:this.inputSrj,plans:r,layerNames:this.config.layerNames});if(!this.validateCompletePlans(r,s).valid)return null;const a=Object.fromEntries(r.map(c=>[c.busId,c.targetLayer])),A=r.reduce((c,l)=>c+l.length,0)+bue(r)*.1+Eue(a,this.preparedBuses,this.config.balanceLayerLoadByConnectionCount)*Bue(this.config);return this.inProgressPlans=[...r],{plans:r,outputSrj:s,stopAfterCompleteValidation:!0,blockingBusIds:[],summary:{assignmentIndex:0,busLayerAssignments:a,routedBusCount:this.preparedBuses.length,routedConnectionCount:r.length,failedBusIds:[],score:A}}}stepRoutingInitialization(){const t=this.boundaryBuses[this.nextCandidateLayerBusIndex];if(t){this.escapeLayersByBusId[t.busId]=jvo({bus:t,srj:this.routingSrj,config:this.config,staticClearanceCache:this.routeStaticClearanceCache}),this.nextCandidateLayerBusIndex++,this.stats={phase:"discover-candidate-layers",bus:t.busId,busIndex:this.nextCandidateLayerBusIndex,busCount:this.boundaryBuses.length};return}const e=W8o({busIds:this.boundaryBuses.map(n=>n.busId),layers:this.config.escapeLayers,layersByBusId:this.escapeLayersByBusId,maxAssignments:this.config.maxLayerCombinations}).map(n=>({...n,...this.fixedPlaneAssignments}));this.layerAssignments.push(...Yvo({initialAssignment:Gvo({buses:this.preparedBuses,escapeLayers:this.config.escapeLayers,escapeLayersByBusId:this.escapeLayersByBusId,traceWidth:this.config.traceWidth,viaDiameter:this.config.viaDiameter,clearance:this.config.clearance,preferOrderedCoordinatedWindingLayers:this.config.densePlaneReservationBusIds.length>0||this.config.denseUnrestrictedPlaneRoutingBusIds.length>0||PNt(this.preparedBuses,this.config.allowBlindAndBuriedVias)}),generatedAssignments:e,maxAssignments:this.config.maxLayerCombinations})),this.routingInitialized=!0,this.stats={phase:"prepare-layer-assignments",assignmentCount:this.layerAssignments.length}}*initializeRoutingSteps(){for(;!this.routingInitialized;)this.stepRoutingInitialization(),this.routingInitialized||(yield)}setInProgressPlans(t){this.inProgressPlans=[...t.plans],this.stats={...this.stats,phase:t.phase,...t.strategy?{routingStrategy:t.strategy}:{},...t.unitIndex!==void 0?{workUnit:t.unitIndex}:{},...t.unitCount!==void 0?{workUnitCount:t.unitCount}:{},...t.busId?{bus:t.busId}:{},routedConnections:`${t.plans.length}/${this.inputSrj.connections.length}`}}visualizeCurrentState(){const t=this.endpointCompletion?.simpleRouteJson??(!this.solved&&!this.failed&&this.inProgressPlans.length>0?aR({inputSrj:this.inputSrj,plans:this.inProgressPlans,layerNames:this.config.layerNames}):void 0)??this.bestAttempt?.outputSrj??this.inputSrj;return kvo(t)}visualizeWorkState(t){const e=this.visualizeCurrentState(),n=this.preparedBuses[0]?.sharedBoundary??this.inputSrj.bounds,o=typeof this.stats.bus=="string"?this.stats.bus:void 0,i=o?this.preparedBuses.find(u=>u.busId===o):void 0,r=n.maxX-n.minX,s=n.maxY-n.minY,a=Math.max(Math.min(r,s)*.025,.25),A=typeof this.stats.phase=="string"?this.stats.phase:"starting",c=[typeof this.stats.routeConnection=="string"?`connection ${this.stats.routeConnection}`:void 0,typeof this.stats.searchBatch=="number"?`batch ${this.stats.searchBatch}`:void 0,typeof this.stats.expandedStates=="number"?`${this.stats.expandedStates.toLocaleString()} states`:void 0].filter(Boolean).join(" · "),l=`${t}: ${A}`;return{...NH(e,{rects:[{center:{x:(n.minX+n.maxX)/2,y:(n.minY+n.maxY)/2},width:r,height:s,fill:"rgba(0, 0, 0, 0)",stroke:"rgba(14, 165, 233, 0.8)",label:`${t} working boundary`}],circles:(i?.connections??[]).map(u=>({center:u.sourcePoint,radius:Math.max(a,Math.min(u.sourceObstacle.width,u.sourceObstacle.height)*.6),fill:"rgba(250, 204, 21, 0.25)",stroke:"#f59e0b",label:`active bus ${o}: ${u.connection.name}`})),texts:[{x:n.minX,y:n.maxY+a*2,text:`${t} · ${A}${c?` · ${c}`:""}`,color:"#0f172a",fontSize:a*1.5,anchorSide:"bottom_left"}]}),title:l}}visualizeBoundaryRoutingState(){return this.activeRoutingVisualization?{...NH(this.visualizeCurrentState(),this.activeRoutingVisualization),title:this.activeRoutingVisualization.title}:this.visualizeWorkState("BoundaryBusRoutingSolver")}visualizeAdaptiveRoutingState(){if(this.activeAdaptiveVisualization)return this.activeAdaptiveVisualization;const t=this.preparedBuses[0]?.sharedBoundary??this.inputSrj.bounds,e=t.maxX-t.minX,n=t.maxY-t.minY,o=Math.max(Math.min(e,n)*.02,.2);return{title:"SingleLayerAdaptiveExitSolver: preparing flow grid",rects:[{center:{x:(t.minX+t.maxX)/2,y:(t.minY+t.maxY)/2},width:e,height:n,fill:"rgba(0, 0, 0, 0)",stroke:"rgba(14, 165, 233, 0.9)",label:"adaptive flow grid boundary"}],points:this.preparedBuses.flatMap(i=>i.connections.map(r=>({...r.sourcePoint,color:"#f97316",label:"adaptive route source"}))),texts:[{x:t.minX,y:t.maxY+o*2,text:"preparing adaptive flow grid",color:"#0f172a",fontSize:o*1.5,anchorSide:"bottom_left"}]}}startOperation(t){const e=this.createWorkSolver(t.name,t.generator,t.getProgress);this.MAX_ITERATIONS=Math.max(this.MAX_ITERATIONS,this.iterations+e.MAX_ITERATIONS+1),this.activeOperation={solver:e,onSolved:t.onSolved},this.activeSubSolver=e}createWorkSolver(t,e,n,o){return new Fvo(t,e,o??(()=>this.visualizeWorkState(t)),()=>({...this.stats}),n??(()=>0))}*routeBusAlternativesWorkSteps(t,e){const n=eue(t,e,!0);let o=n.next();for(;!o.done;){const{winding:i}=o.value;i.visualization&&(this.activeRoutingVisualization=i.visualization),this.stats={...this.stats,phase:"route-boundary-bus-connection",bus:o.value.busId,targetLayer:o.value.targetLayer,routeOrderAttempt:i.routeOrderAttempt,routeConnection:`${i.connectionIndex+1}/${i.connectionCount}`,connection:i.connectionName,searchBatch:i.searchBatch,expandedStates:i.expandedStateCount,connectionComplete:i.connectionComplete},yield,o=n.next()}return o.value}stepActiveOperation(){const t=this.activeOperation;if(!t)return;if(t.solver.step(),t.solver.failed){this.failedSubSolvers=[...this.failedSubSolvers??[],t.solver],this.error=t.solver.error,this.failed=!0,this.activeOperation=null,this.activeSubSolver=null;return}if(!t.solver.solved)return;const e=t.solver.getOutput();this.activeOperation=null,this.activeSubSolver=null,t.onSolved(e)}completeBestAttemptEndpoints(){!this.options.completeOriginalEndpoints||this.endpointCompletion||!this.bestAttempt||(this.endpointCompletion=sbo({inputSrj:this.routingSrj,fanoutSrj:this.bestAttempt.outputSrj,plans:this.bestAttempt.plans,traceWidth:this.config.traceWidth,viaDiameter:this.config.viaDiameter,viaHoleDiameter:this.config.viaHoleDiameter,clearance:this.config.clearance,allowBlindAndBuriedVias:this.config.allowBlindAndBuriedVias,effort:this.options.endpointCompletionEffort,routeDownstreamConnections:this.options.routeDownstreamConnections}))}getValidationBoundary(){if(this.options.sharedBoundary)return this.options.sharedBoundary;const t=this.preparedBuses[0]?.sharedBoundary;return t?this.preparedBuses.slice(1).reduce((e,n)=>({minX:Math.min(e.minX,n.sharedBoundary.minX),maxX:Math.max(e.maxX,n.sharedBoundary.maxX),minY:Math.min(e.minY,n.sharedBoundary.minY),maxY:Math.max(e.maxY,n.sharedBoundary.maxY)}),{...t}):this.inputSrj.bounds}validateCompletePlans(t,e){return Bvo({inputSrj:this.inputSrj,outputSrj:e,plans:t,preparedBuses:this.preparedBuses,sharedBoundary:this.getValidationBoundary(),clearance:this.config.clearance,allowBlindAndBuriedVias:this.config.allowBlindAndBuriedVias})}matchCompletePlanLengths(t,e={}){return zy({plans:t,preparedBuses:this.preparedBuses,inputSrj:this.inputSrj,sharedBoundary:this.getValidationBoundary(),clearance:this.config.clearance,allowBlindAndBuriedVias:this.config.allowBlindAndBuriedVias,allowSameNetMerges:this.config.allowSameNetMerges,...e})}normalizeCompletePlanCorners(t){if(this.config.allowBlindAndBuriedVias)return[...t];const e=DPe({...this.config,inputSrj:this.inputSrj,preparedBuses:this.preparedBuses,plans:t,repairPlaneSourceCorners:!0,repairSignalSourceCorners:!0,rematchRepairedLengths:n=>this.matchCompletePlanLengths(n,{maximumWorkUnits:1e4,allowMatchingInsideDenseBounds:!0}).plans});return!e||e.every(n=>r$(n,this.config.clearance).every(o=>o.kind==="clearance"))?e:$So({...this.config,inputSrj:this.inputSrj,preparedBuses:this.preparedBuses,plans:e})}*routePeripheralMixedTerminationSteps(t){if(this.config.allowBlindAndBuriedVias)return null;const e=t.busesInRoutingOrder.find(_=>_.termination.type==="boundary"&&(_.exitEdge==="right"||_.exitEdge==="left")&&_.connections.length>=16&&_.componentObstacles.length>=200);if(!e)return null;const n=t.busLayerAssignments[e.busId];if(!n)return null;const o=new Map(Object.entries(t.busLayerAssignments));this.setInProgressPlans({phase:"route-peripheral-source-escapes",plans:[],busId:e.busId});const i=(e.exitEdge==="left"?ivo:DQo)({...this.config,srj:this.routingSrj,buses:this.preparedBuses,bus:e,targetLayer:n,targetLayerByBusId:o});let r=i.next();for(;!r.done;)yield,r=i.next();if(!r.value)return null;let s=r.value;const a={...this.config,...s,srj:this.routingSrj,bus:e,targetLayer:n},A="lowerConnectionIndices"in s?tRt({...a,...s}):NQo(a);let c=A.next();for(;!c.done;)yield,c=A.next();let l=c.value;if(!l&&"lowerConnectionIndices"in s){const _=rvo({...a,...s,buses:this.preparedBuses});let f=_.next();for(;!f.done;)yield,f=_.next();f.value&&(s=f.value,l=f.value.plans)}if(!l)return null;this.setInProgressPlans({phase:"route-peripheral-bus-continuations",plans:l,busId:e.busId});const u=$Nt({...this.config,srj:this.routingSrj,buses:this.preparedBuses,sourceEscapes:s.sourceEscapes,sourceBoundary:s.sourceBoundary,initialPlans:l,targetLayerByBusId:o});let g=u.next();for(;!g.done;)yield,g=u.next();if(!g.value)return null;const h=nvo({...this.config,srj:this.routingSrj,inputSrj:this.inputSrj,plans:g.value,preparedBuses:this.preparedBuses,sharedBoundary:this.getValidationBoundary()});let d=h.next();for(;!d.done;)yield,d=h.next();if(!d.value)return null;const p=this.normalizeCompletePlanCorners(d.value);if(!p)return null;const m=aR({inputSrj:this.inputSrj,plans:p,layerNames:this.config.layerNames});return this.validateCompletePlans(p,m).valid?{plans:p,failedBusIds:[],stopAfterCompleteValidation:!0}:null}*routeDenseThroughAllMixedTerminationSteps(t){if(this.config.allowBlindAndBuriedVias)return null;let e=t.preferredBoundaryViaPoints;const n=t.denseRoutingStrategy!=="boundary-aligned",o=(...Xe)=>{if(FA.env.FANOUT_DEBUG_DENSE==="1"){if(FA.env.FANOUT_DEBUG_DENSE_SUMMARY==="1"&&!["start","plane-match:preflight-failed","plane-match:incremental-complete","plane-match:incremental-failed","plane-route:alternate-candidate-counts","plane-route:alternate-search","plane-route:csp","plane-reservation-core","plane-route:promote-failed","plane-route:alternate-choice","plane-route:promote-zero-candidates","length-match:complete","length-match:start","plane-route:failed","dense-validation"].includes(String(Xe[0])))return;console.error("dense:",...Xe)}},i=t.busesInRoutingOrder.filter(Xe=>Xe.termination.type==="boundary"),r=i.filter(Xe=>Xe.connections.length>=8),s=(Xe,Ze)=>Ze.componentId!==Xe.componentId&&this.config.layerNames.every(dt=>Ze.layers.includes(dt))&&Ze.center.x>=Xe.componentBounds.minX&&Ze.center.x<=Xe.componentBounds.maxX&&Ze.center.y>=Xe.componentBounds.minY&&Ze.center.y<=Xe.componentBounds.maxY,a=r.some(Xe=>this.routingSrj.obstacles.some(Ze=>s(Xe,Ze))),A=this.preparedBuses.flatMap(Xe=>Xe.termination.type==="plane"?Xe.connections.map(Ze=>Ze.connection.name):[]),c=r.some(Xe=>this.routingSrj.obstacles.some(Ze=>s(Xe,Ze)&&A.some(dt=>n4(this.routingSrj,Ze,dt)))),l=this.config.densePlaneReservationBusIds.length>0||this.config.denseUnrestrictedPlaneRoutingBusIds.length>0,u=!l&&PNt(this.preparedBuses,this.config.allowBlindAndBuriedVias),g=l||u,h=!l&&!u&&c,d=t.boundaryRecovery!==void 0,p=g||h||d,m=d||(u||h)&&((t.planeReservationRetryCount??0)===0||!!t.preferredBoundaryViaPoints),_=(g||h)&&t.lengthMatchingStage!=="before-planes",f=DNt(i.map(Xe=>Xe.connections.length)),I=i.filter(Xe=>Xe.connections.length===2),C=Wvo({boundaryBusCount:i.length,pairBuses:I.map(Xe=>({...Xe,assignedLayer:t.busLayerAssignments[Xe.busId]}))}),y=C?new Map(I.map((Xe,Ze)=>[Xe.busId,C[Ze]])):null,x=new Map;if(a)for(const Xe of pw(i,{viaDiameter:this.config.viaDiameter,viaHoleDiameter:this.config.viaHoleDiameter,traceWidth:this.config.traceWidth,clearance:this.config.clearance,additionalObstacles:this.routingSrj.obstacles}))x.set(Xe.connectionIndex,(x.get(Xe.connectionIndex)??0)+1);const E=Xe=>Xe.connections.reduce((Ze,dt)=>Ze+(x.get(dt.connectionIndex)??0),0),B=new Map;if(n&&!l)for(const Xe of r){if(!Ds(Xe.exitEdge,Xe.preferredExit)||new Set(Xe.routableEscapeLayers??Xe.allowedLayers??[]).size!==1)continue;const Ze=Xe.direction==="up"||Xe.direction==="down"?"y":"x",dt=Ze==="x"?"y":"x",Ut=Xe.direction==="up"||Xe.direction==="right"?1:-1,Wt=Math.max(...Xe.connections.map(kn=>Ut*kn.sourcePoint[Ze])),Xt=Math.min(...Xe.connections.map(kn=>kn.sourcePoint[dt])),Jt=Math.max(...Xe.connections.map(kn=>kn.sourcePoint[dt])),yn=Ze==="x"?Xe.pitchX:Xe.pitchY,An=r.find(kn=>{if(kn===Xe||kn.componentId!==Xe.componentId||kn.exitEdge!==Xe.exitEdge||Ds(kn.exitEdge,kn.preferredExit))return!1;const ht=Math.min(...kn.connections.map(Kt=>Ut*Kt.sourcePoint[Ze]))-Wt;return ht>=-1e-9&&ht<=yn+1e-9&&Math.min(...kn.connections.map(Kt=>Kt.sourcePoint[dt]))<=Jt+1e-9&&Math.max(...kn.connections.map(Kt=>Kt.sourcePoint[dt]))>=Xt-1e-9});An&&B.set(Xe,An)}const S=g&&r.length===3,Q=Xe=>{const Ze=Xe.connections.map(dt=>{const Ut=dt.exitTargetPoint??dt.targetPoint;return Xe.exitEdge==="top"||Xe.exitEdge==="bottom"?Ut.x:Ut.y});return{minimum:Math.min(...Ze),maximum:Math.max(...Ze)}},w=Xe=>{if(Xe.connections.length>=8)return!1;const Ze=Q(Xe);return r.some(dt=>{if(dt.exitEdge!==Xe.exitEdge)return!1;const Ut=Q(dt);return Ze.maximum>=Ut.minimum-1e-9&&Ze.minimum<=Ut.maximum+1e-9})},M=Xe=>{if(!(Xe.connections.length>=8))return r.find(Ze=>{const dt=Ze.connections.map(An=>An.sourcePoint.x),Ut=Ze.connections.map(An=>An.sourcePoint.y),Wt=Math.min(...dt),Xt=Math.max(...dt),Jt=Math.min(...Ut),yn=Math.max(...Ut);return Xe.connections.every(An=>An.sourcePoint.x>=Wt-1e-9&&An.sourcePoint.x<=Xt+1e-9&&An.sourcePoint.y>=Jt-1e-9&&An.sourcePoint.y<=yn+1e-9)})},k=Xe=>!!M(Xe),R=Xe=>w(Xe)&&!k(Xe)?0:Xe.connections.length>=8?1:Xe.connections.length>1?2:3,F=i.toSorted((Xe,Ze)=>{if(f||r.length>0){if(S){const $n=R(Xe)-R(Ze);if($n!==0)return $n}const kn=i.length===2&&Math.max(...i.map($n=>$n.connections.length))>=8?Xe.connections.length-Ze.connections.length:Ze.connections.length-Xe.connections.length;if(kn!==0)return kn;if(a&&Xe.connections.length>=8&&Ze.connections.length>=8){const $n=E(Xe)-E(Ze);if($n!==0)return $n}}const dt=t.busLayerAssignments[Xe.busId],Ut=t.busLayerAssignments[Ze.busId],Wt=y?.get(Xe.busId),Xt=y?.get(Ze.busId);if(Wt!==void 0&&Xt!==void 0&&Wt!==Xt)return Wt-Xt;const Jt=+!!Ds(Ze.exitEdge,Ze.preferredExit)-+!!Ds(Xe.exitEdge,Xe.preferredExit);if(Jt!==0)return Jt;if(!!!Ds(Xe.exitEdge,Xe.preferredExit)){const kn=ht=>{const Kt=ht.connections.map(Lt=>Lt.sourcePoint.x),rn=ht.connections.map(Lt=>Lt.sourcePoint.y);return Math.max(...Kt)-Math.min(...Kt)+Math.max(...rn)-Math.min(...rn)},$n=kn(Ze)-kn(Xe);if(Math.abs($n)>1e-9)return $n}const An=this.config.layerNames.indexOf(dt??"")-this.config.layerNames.indexOf(Ut??"");return An!==0?-An:i.length!==6&&i.length!==7&&i.length!==8&&i.length!==9?0:Xe.busId.localeCompare(Ze.busId)}),O=FA.env.FANOUT_DEBUG_BOUNDARY_ORDER?.split(",")??(FA.env.FANOUT_DEBUG_FIRST_BOUNDARY_BUS?[FA.env.FANOUT_DEBUG_FIRST_BOUNDARY_BUS]:t.boundaryRecovery?[t.boundaryRecovery.busId]:[]),U=O.length>0?F.toSorted((Xe,Ze)=>{const dt=O.indexOf(Xe.busId),Ut=O.indexOf(Ze.busId);return(dt<0?Number.POSITIVE_INFINITY:dt)-(Ut<0?Number.POSITIVE_INFINITY:Ut)}):F,Y=this.preparedBuses.filter(Xe=>Xe.termination.type==="plane"),W=new Set(Y.flatMap(Xe=>Xe.connections.map(Ze=>Ze.connectionIndex))),te=this.config.allowSameNetMerges||h,j=g||h?this.routingSrj.obstacles:void 0,J=Number.parseInt(FA.env.FANOUT_INITIAL_PLANE_RESERVATIONS??"8",10),oe=FA.env.FANOUT_DEBUG_INITIAL_PLANE_INDICES?.split(",").map(Xe=>Number(Xe)-1),ie=FA.env.FANOUT_DEBUG_INITIAL_PLANE_BUS_IDS?.split(",");let ne=ie?Y.filter(Xe=>ie.includes(Xe.busId)):oe?oe.flatMap(Xe=>Y[Xe]?[Y[Xe]]:[]):this.config.densePlaneReservationBusIds.length>0?Y.filter(Xe=>this.config.densePlaneReservationBusIds.includes(Xe.busId)):g||h?Y.slice(0,Number.isFinite(J)?J:8):Y;t.promotedPlaneReservationBusIds&&(ne=[...new Set([...ne,...Y.filter(Xe=>t.promotedPlaneReservationBusIds.includes(Xe.busId))])]);const le=new Set;let ge,_e;const ue=U.map(Xe=>Xe.connections.length),fe=VSo({boundaryBusConnectionCounts:ue,planeBusCount:Y.length});if(o("start",U.map(Xe=>`${Xe.busId}:${Xe.connections.length}`),`planes:${Y.length}`,`joint:${f}`),U.length===0||fe===null||U.some(Xe=>!a6(Xe))||Y.some(Xe=>Xe.connections.length!==1)||U.length+Y.length!==t.busesInRoutingOrder.length)return null;const pe=new Map(this.preparedBuses.flatMap(Xe=>Xe.connections.map(Ze=>[Ze.connectionIndex,Ze.connection.name]))),Me=ue.filter(Xe=>Xe===1).length>1&&iMe(ue),ve=new Map(U.map(Xe=>[Xe.busId,S&&Xe.connections.length<8&&k(Xe)?-1:1])),he=new Map(U.map(Xe=>[Xe.busId,Xe.connections.length===1?S&&k(Xe)?!0:Me&&Ds(Xe.exitEdge,Xe.preferredExit)?d$(Xe).targetProjection>0:Xj(Xe.direction)!==Xe.exitEdge:S&&Xe.connections.length>=8?!1:Xj(Xe.direction)!==Xe.exitEdge]));for(const Xe of r){if(g||!Ds(Xe.exitEdge,Xe.preferredExit))continue;r.some(dt=>{if(dt===Xe||dt.componentId!==Xe.componentId)return!1;const Ut=dt.connections.map(kn=>kn.sourcePoint.x),Wt=dt.connections.map(kn=>kn.sourcePoint.y),Xt=Math.min(...Ut),Jt=Math.max(...Ut),yn=Math.min(...Wt),An=Math.max(...Wt);return Xe.connections.some(({sourcePoint:kn})=>{const $n=kn.x+(Xe.direction==="left"?-Xe.pitchX/2:Xe.direction==="right"?Xe.pitchX/2:0),ht=kn.y+(Xe.direction==="down"?-Xe.pitchY/2:Xe.direction==="up"?Xe.pitchY/2:0);return $n>=Xt&&$n<=Jt&&ht>=yn&&ht<=An})})&&he.set(Xe.busId,!1)}t.boundaryRecovery&&(ve.set(t.boundaryRecovery.busId,t.boundaryRecovery.perpendicularSide),he.set(t.boundaryRecovery.busId,t.boundaryRecovery.preferOutward));const Qe=FA.env.FANOUT_DEBUG_FLIP_BOUNDARY_BUS;Qe&&ve.set(Qe,-1);const Pe=FA.env.FANOUT_DEBUG_OUTWARD_BOUNDARY_BUS;Pe&&he.set(Pe,!0);const we=(Xe,Ze)=>{const dt=W.has(Xe)&&W.has(Ze);if(!this.config.allowSameNetMerges&&!(te&&dt))return!1;const Ut=pe.get(Xe),Wt=pe.get(Ze);return!!(Ut&&Wt&&Px(this.routingSrj,Ut,Wt))},Te=U.filter(Xe=>Xe.connections.length===1),Re=!S&&!h&&iMe(ue)?Te.toSorted(U.length===9?zvo:Jvo).slice(0,Uvo(ue)):[],Ee=U.length===8||U.length===9?Re.filter(Xe=>{const Ze=t.busLayerAssignments[Xe.busId];return!!(Ze&&uRt({singletonBus:Xe,singletonTargetLayer:Ze,wideBuses:U}))}):[],ke=S?Te.filter(Xe=>{const Ze=M(Xe),dt=t.busLayerAssignments[Xe.busId];if(!Ze||!dt)return!1;const Ut=Ze.routableEscapeLayers??Ze.allowedLayers??[],Wt=Xe.exitEdge==="left"||Xe.exitEdge==="right"?"x":"y",Xt=Ze.connections.map(An=>An.sourcePoint[Wt]),Jt=Xe.exitEdge==="left"||Xe.exitEdge==="bottom"?Math.min(...Xt):Math.max(...Xt),yn=Xe.connections.every(An=>Math.abs(An.sourcePoint[Wt]-Jt)<1e-9);return!!(!Ut.includes(dt)||u&&yn&&Ds(Xe.exitEdge,Xe.preferredExit))}):[],Ce=ke.flatMap(Xe=>{const Ze=M(Xe),dt=t.busLayerAssignments[Xe.busId];return U.filter(Ut=>Ut.connections.length>1&&Ut.connections.length<8&&Ut.direction===Xe.direction&&t.busLayerAssignments[Ut.busId]===dt&&M(Ut)===Ze)}),Le=FA.env.FANOUT_DEBUG_DISABLE_LEADING_NARROW==="1"?[]:ke.flatMap(Xe=>[Xe,...Ce.filter(Ze=>Ze.direction===Xe.direction&&t.busLayerAssignments[Ze.busId]===t.busLayerAssignments[Xe.busId])]),Ye=[...Ee,...Le].filter((Xe,Ze,dt)=>dt.indexOf(Xe)===Ze),tt=new Map;if(U.length===9&&Ye.length>0)for(const Xe of Ye){he.set(Xe.busId,!0);const Ze=Ds(Xe.exitEdge,Xe.preferredExit);if(!Xe.exitEdge||!Ze)continue;const dt=`${Xe.exitEdge}:${Ze}`;U.some(Wt=>Wt===Xe||Wt.connections.length<8?!1:Wt.exitEdge===Xe.exitEdge&&Ds(Wt.exitEdge,Wt.preferredExit)===Ze)&&tt.set(dt,(tt.get(dt)??0)+Xe.connections.length)}const At=new Set([...FA.env.FANOUT_DEBUG_PROVISIONAL_NARROW==="1"?U.filter(Xe=>Xe.connections.length<8):[],...Re.filter(Xe=>{const Ze=M(Xe),dt=Xe.connections[0].sourcePoint,Ut={x:(Xe.componentBounds.minX+Xe.componentBounds.maxX)/2,y:(Xe.componentBounds.minY+Xe.componentBounds.maxY)/2},Wt=Xe.exitEdge?e6(Xe.exitEdge):Xe.direction,Xt=Wt==="right"?Ut.x-dt.x:Wt==="left"?dt.x-Ut.x:Wt==="up"?Ut.y-dt.y:dt.y-Ut.y,Jt=n&&!g&&Ze&&(t.busLayerAssignments[Ze.busId]===t.busLayerAssignments[Xe.busId]||Xt>1e-9);return!Ye.includes(Xe)&&!Jt}),...S?U.filter(Xe=>Xe.connections.length===2&&!w(Xe)&&!Ye.includes(Xe)):[]]),at=Xe=>{const Ze=Ds(Xe.exitEdge,Xe.preferredExit);if(!Xe.exitEdge||!Ze)return 0;const dt=tt.get(`${Xe.exitEdge}:${Ze}`)??0;return Kvo({leadingLaneCount:dt,traceWidth:this.config.traceWidth,viaDiameter:this.config.viaDiameter,clearance:this.config.clearance})},nt=U.filter(Xe=>!At.has(Xe)),gt=f?pd([...ne,...nt],{viaDiameter:this.config.viaDiameter,viaHoleDiameter:this.config.viaHoleDiameter,traceWidth:this.config.traceWidth,clearance:this.config.clearance,maximumSearchStates:1e5,preferredViaPointsByConnectionIndex:t.preferredBoundaryViaPoints,preferredBoundaryPerpendicularSideByBusId:ve,preferBoundaryOutwardByBusId:he,additionalObstacles:j,preferPlaneCheckerboardSites:g,canShareCopper:we}):null;let bt=gt??pd([...ne,U[0]],{viaDiameter:this.config.viaDiameter,viaHoleDiameter:this.config.viaHoleDiameter,traceWidth:this.config.traceWidth,clearance:this.config.clearance,maximumSearchStates:2e4,preferredViaPointsByConnectionIndex:t.preferredBoundaryViaPoints,preferredBoundaryPerpendicularSideByBusId:ve,preferBoundaryOutwardByBusId:he,additionalObstacles:j,preferPlaneCheckerboardSites:g,canShareCopper:we});const Ct=FA.env.FANOUT_DEBUG_FIXED_VIAS;if(bt&&Ct){bt=new Map(bt);for(const Xe of Ct.split(",")){const Ze=Xe.split(":"),dt=Ze.pop(),Ut=Ze.pop(),Wt=Ze.join(":"),Xt=[...pe].find(([,An])=>An===Wt)?.[0],Jt=Number(Ut),yn=Number(dt);Xt!==void 0&&Number.isFinite(Jt)&&Number.isFinite(yn)&&bt.set(Xt,{x:Jt,y:yn})}}const Dt=FA.env.FANOUT_DEBUG_STAGED_PLANE_BUS_IDS?Y.filter(Xe=>FA.env.FANOUT_DEBUG_STAGED_PLANE_BUS_IDS.split(",").includes(Xe.busId)):FA.env.FANOUT_DEBUG_STAGED_PLANE_INDICES?.split(",").flatMap(Xe=>Y[Number(Xe)-1]?[Y[Number(Xe)-1]]:[])??[];if(bt&&Dt.length>0)for(const Xe of Dt){if(ne.includes(Xe))continue;const Ze=pd([...ne,Xe,...nt],{viaDiameter:this.config.viaDiameter,viaHoleDiameter:this.config.viaHoleDiameter,traceWidth:this.config.traceWidth,clearance:this.config.clearance,maximumSearchStates:1e5,preferredViaPointsByConnectionIndex:t.preferredBoundaryViaPoints,preferredBoundaryPerpendicularSideByBusId:ve,preferBoundaryOutwardByBusId:he,fixedViaPointsByConnectionIndex:bt,additionalObstacles:j,preferPlaneCheckerboardSites:g,canShareCopper:we});if(o("plane-reservation:staged",Xe.busId,Ze?.size??"failed"),!Ze)break;bt=new Map([...bt,...Ze]),ne.push(Xe)}o("seed",bt?.size??"failed"),bt&&FA.env.FANOUT_DEBUG_DENSE_POINTS==="1"&&console.error("dense: seed-points",[...bt].map(([Xe,Ze])=>({connection:pe.get(Xe),point:Ze})));let kt=1;const it=U.length+Y.length+3;if(this.setInProgressPlans({phase:"reserve-dense-via-sites",plans:[],strategy:"default",unitIndex:kt,unitCount:it}),yield,bt){const Xe=zSo({busesInRoutingOrder:[...a?[]:Ee,...U.filter(qe=>(a||!Ee.includes(qe))&&!Le.includes(qe)).flatMap(qe=>[...Le.filter(vt=>M(vt)===qe),qe])],busLayerAssignments:t.busLayerAssignments,routingMode:fe}),Ze=r.every(qe=>qe.exitEdge&&qe.direction===e6(qe.exitEdge)),dt=h&&Ze?Te.filter(qe=>{const vt=M(qe);return!!(vt&&qe.direction===vt.direction)}):[];if(t.boundaryRecovery&&dt.length>0){const qe=Xe.findIndex(vt=>vt.busId===t.boundaryRecovery.busId);if(qe>=0){const vt=Xe[qe],qt=new Set(dt),Zt=Xe.filter(nn=>nn!==vt&&!qt.has(nn));Xe.splice(0,Xe.length,vt,...dt,...Zt)}}for(const[qe]of B){const vt=qe.direction==="up"||qe.direction==="down"?"y":"x",qt=qe.direction==="up"||qe.direction==="right"?1:-1,Zt=Math.min(...qe.connections.map(Nn=>qt*Nn.sourcePoint[vt])),nn=Xe.indexOf(qe),zn=Xe.findIndex(Nn=>Nn!==qe&&Nn.connections.length>=8&&Nn.componentId===qe.componentId&&Nn.direction===qe.direction&&Math.max(...Nn.connections.map(Co=>qt*Co.sourcePoint[vt]))<=Zt+1e-9&&Nn.exitEdge===qe.exitEdge&&Ds(Nn.exitEdge,Nn.preferredExit)===Ds(qe.exitEdge,qe.preferredExit));zn>=0&&zn<nn&&(Xe.splice(nn,1),Xe.splice(zn,0,qe))}const Ut=(qe,vt)=>{if(!n||qe.componentId!==vt.componentId||qe.exitEdge!==vt.exitEdge||qe.direction!==vt.direction||Ds(qe.exitEdge,qe.preferredExit)!==Ds(vt.exitEdge,vt.preferredExit)||t.busLayerAssignments[qe.busId]!==t.busLayerAssignments[vt.busId]||M(qe)!==M(vt)||!M(qe))return!1;const qt={x:qe.connections.reduce((Nn,Co)=>Nn+Co.sourcePoint.x,0)/qe.connections.length,y:qe.connections.reduce((Nn,Co)=>Nn+Co.sourcePoint.y,0)/qe.connections.length},Zt={x:vt.connections.reduce((Nn,Co)=>Nn+Co.sourcePoint.x,0)/vt.connections.length,y:vt.connections.reduce((Nn,Co)=>Nn+Co.sourcePoint.y,0)/vt.connections.length};if(Math.hypot(qt.x-Zt.x,qt.y-Zt.y)>1.5*Math.min(qe.pitchX,qe.pitchY))return!1;const nn=qe.exitEdge==="left"||qe.exitEdge==="right"?"y":"x",zn=Nn=>Nn.connections.reduce((Co,ei)=>Co+(ei.exitTargetPoint??ei.targetPoint)[nn],0)/Nn.connections.length;return(qt[nn]-Zt[nn])*(zn(qe)-zn(vt))<-1e-9},Wt=new Set;for(const qe of Ye)if(!Ds(qe.exitEdge,qe.preferredExit))for(const vt of U){if(vt.connections.length!==2||!Ut(vt,qe))continue;const qt=Xe.indexOf(vt),Zt=Xe.indexOf(qe);qt>Zt&&(Xe.splice(qt,1),Xe.splice(Zt,0,vt),Wt.add(`${vt.componentId}:${vt.exitEdge}`))}for(const qe of U)if(!(!Wt.has(`${qe.componentId}:${qe.exitEdge}`)||qe.connections.length!==2||!Ds(qe.exitEdge,qe.preferredExit)))for(const vt of Te){if(!Ut(vt,qe))continue;const qt=Xe.indexOf(vt),Zt=Xe.indexOf(qe);qt>Zt&&(Xe.splice(qt,1),Xe.splice(Zt,0,vt))}for(const qe of B.values())for(const vt of U)if(!(vt.connections.length!==2||M(vt)!==qe))for(const qt of Te){if(!Ut(qt,vt))continue;const Zt=Xe.indexOf(vt),nn=Xe.indexOf(qt);nn>Zt&&(Xe.splice(nn,1),Xe.splice(Zt,0,qt))}let Xt=bt,Jt=[],yn=!0;const An=qe=>{const vt=new Set(qe.connections.map(qt=>qt.connection.name));return this.preparedBuses.flatMap(qt=>{const Zt=t.busLayerAssignments[qt.busId];return Zt?qt.connections.flatMap(nn=>{if(vt.has(nn.connection.name))return[];const zn=Xt.get(nn.connectionIndex);return zn?[{connectionName:nn.connection.name,sourceEscapeSegment:Jt.some(Nn=>Nn.connectionIndex===nn.connectionIndex)?void 0:{start:nn.sourcePoint,end:zn,layer:nn.sourceLayer,width:this.config.traceWidth},via:{center:zn,diameter:this.config.viaDiameter,spanLayers:Mx({fromLayer:nn.sourceLayer,toLayer:Zt,layerNames:this.config.layerNames,allowBlindAndBuriedVias:!1})}}]:[]}):[]})},kn=(function*(qe){o("route:start",qe.busId,Jt.length),FA.env.FANOUT_DEBUG_DENSE_POINTS==="1"&&console.error("dense: points",qe.busId,qe.connections.map(On=>({source:On.sourcePoint,via:Xt.get(On.connectionIndex),target:On.exitTargetPoint??On.targetPoint})));const vt=t.busLayerAssignments[qe.busId];if(!vt)return!1;const qt=!g&&!Ds(qe.exitEdge,qe.preferredExit)&&qe.connections.length>2&&r.some(On=>Ds(On.exitEdge,On.preferredExit)),Zt=this.config.traceWidth+this.config.clearance,nn=qe.connections.some(On=>{const uo=On.exitTargetPoint??On.targetPoint,Oo=qe.sharedBoundary;return qe.exitEdge==="left"||qe.exitEdge==="right"?uo.y-Oo.minY<=Zt+1e-9||Oo.maxY-uo.y<=Zt+1e-9:uo.x-Oo.minX<=Zt+1e-9||Oo.maxX-uo.x<=Zt+1e-9}),zn={srj:this.routingSrj,bus:qe,targetLayer:vt,acceptedPlans:Jt,layerNames:this.config.layerNames,traceWidth:this.config.traceWidth,viaDiameter:this.config.viaDiameter,viaHoleDiameter:this.config.viaHoleDiameter,clearance:this.config.clearance,compactBusTracks:this.config.compactBusTracks,allowBlindAndBuriedVias:!1,allowSameNetMerges:this.config.allowSameNetMerges,staticClearanceCache:this.routeStaticClearanceCache,fixedViaPointsByConnectionIndex:Xt,reservedVias:An(qe),viaMinimalOnly:FA.env.FANOUT_DEBUG_ALLOW_EXTRA_VIAS!=="1",allowBoundarySideViaFallback:qe.connections.length===1,preferCornerBoundaryVia:g,adaptiveWindingRouteOrder:qt,allowFixedViaReservedExitFallback:d,forbidEarlyExitBoundaryContact:nn,alignWindingGridToPads:n&&!l,fixedViaFallbackRouteOrderAttempts:qt?60:g?6:24,cornerBandTargetTrackOffset:at(qe)},Nn=(function*(On,uo){return this.activeRoutingVisualization=null,yield{type:"subsolver",solver:this.createWorkSolver("BoundaryBusRoutingSolver",this.routeBusAlternativesWorkSteps(On,uo),void 0,()=>this.visualizeBoundaryRoutingState())}}).bind(this),ei=(qe.routableEscapeLayers??qe.allowedLayers??[]).some(On=>On!==vt)?{...qe,routableEscapeLayers:[vt]}:qe,ro=U.some(On=>On.connections.length<8&&M(On)===qe&&Jt.some(uo=>uo.busId===On.busId)),To=g&&ei!==qe&&!ro;let yo=!1,Ro=(yield*Nn(To?{...zn,bus:ei}:zn,1))[0];if(!Ro&&To&&(Ro=(yield*Nn(zn,1))[0]),!Ro){const On=Xt,uo=he.get(qe.busId)??!0,Oo=ve.get(qe.busId)??1;for(const[ko,Ko]of[[!uo,Oo],[uo,-Oo],[!uo,-Oo]]){const mi=pd([...new Set([...ne,...nt,...this.preparedBuses.filter(Fo=>Jt.some(Nr=>Nr.busId===Fo.busId)),qe])],{viaDiameter:this.config.viaDiameter,viaHoleDiameter:this.config.viaHoleDiameter,traceWidth:this.config.traceWidth,clearance:this.config.clearance,maximumSearchStates:1e5,preferredBoundaryPerpendicularSideByBusId:new Map([...ve,[qe.busId,Ko]]),preferBoundaryOutwardByBusId:new Map([...he,[qe.busId,ko]]),fixedViaPointsByConnectionIndex:new Map(Jt.filter(Fo=>Fo.via).map(Fo=>[Fo.connectionIndex,Fo.via.center])),preferredViaPointsByConnectionIndex:new Map([...On].filter(([Fo])=>!qe.connections.some(Nr=>Nr.connectionIndex===Fo))),blockingSegments:Jt.flatMap(Fo=>Fo.segments.map(Nr=>({connectionIndex:Fo.connectionIndex,segment:Nr}))),additionalObstacles:this.routingSrj.obstacles,preferPlaneCheckerboardSites:g,canShareCopper:we});if(o("retry-sites",qe.busId,ko,Ko,mi?.size??"failed"),!!mi&&(Xt=mi,Ro=(yield*Nn({...zn,fixedViaPointsByConnectionIndex:mi,reservedVias:An(qe),alignWindingGridToPads:g,fixedViaFallbackRouteOrderAttempts:3},1))[0],Ro))break}Ro||(Xt=On,qe.connections.length===2&&(Ro=(yield*Nn({...zn,fixedViaPointsByConnectionIndex:On,reservedVias:An(qe),allowBoundarySideViaFallback:!0,fixedViaFallbackRouteOrderAttempts:1},1))[0]))}if(!Ro&&u&&qe.connections.length>=8&&Ds(qe.exitEdge,qe.preferredExit)&&new Set(qe.routableEscapeLayers??qe.allowedLayers??[]).size===1&&!Jt.some(On=>r.some(uo=>uo.busId===On.busId))){const On=An(qe),uo=fbo(qe,{viaDiameter:this.config.viaDiameter,viaHoleDiameter:this.config.viaHoleDiameter,traceWidth:this.config.traceWidth,clearance:this.config.clearance,additionalObstacles:this.routingSrj.obstacles,blockingSegments:[...Jt.flatMap(Oo=>Oo.segments.map(ko=>({connectionIndex:Oo.connectionIndex,segment:ko}))),...On.flatMap(Oo=>Oo.sourceEscapeSegment?[{connectionIndex:-1,segment:Oo.sourceEscapeSegment}]:[])],blockingVias:[...Jt.flatMap(Oo=>Oo.via?[{connectionIndex:Oo.connectionIndex,...Oo.via}]:[]),...On.map(Oo=>({connectionIndex:-1,...Oo.via}))]},Xt);for(const Oo of uo){const ko=(yield*Nn({...zn,fixedViaPointsByConnectionIndex:Oo,reservedVias:On,fixedViaFallbackRouteOrderAttempts:1},1))[0];if(ko){Ro=ko,Xt=Oo,yo=!0;break}}}if(!Ro&&u&&qe.connections.length>=8&&Ds(qe.exitEdge,qe.preferredExit)&&(Ro=(yield*Nn({...zn,fixedViaPointsByConnectionIndex:void 0,reservedVias:An(qe)},1))[0],Ro&&(yo=!0,Xt=new Map([...Xt,...Ro.filter(On=>On.via).map(On=>[On.connectionIndex,On.via.center])])),o("local-sites",qe.busId,Ro?.length??"failed")),!Ro&&qe.connections.length>=8&&(B.has(qe)||U.some(On=>On.connections.length>=8&&Jt.some(uo=>uo.busId===On.busId)))){const On=new Set(Jt.map(ko=>ko.connectionName)),uo=new Set(this.preparedBuses.filter(ko=>ko.termination.type==="plane"||ko===B.get(qe)).flatMap(ko=>ko.connections.map(Ko=>Ko.connection.name)).filter(ko=>!On.has(ko))),Oo=(yield*Nn({...zn,fixedViaPointsByConnectionIndex:void 0,reservedVias:zn.reservedVias.filter(ko=>!uo.has(ko.connectionName)),softReservedVias:zn.reservedVias.filter(ko=>uo.has(ko.connectionName))},1))[0];if(Oo){const ko=[...Jt,...Oo],Ko=pd(this.preparedBuses,{viaDiameter:this.config.viaDiameter,viaHoleDiameter:this.config.viaHoleDiameter,traceWidth:this.config.traceWidth,clearance:this.config.clearance,maximumSearchStates:3e6,preferredBoundaryPerpendicularSideByBusId:ve,preferBoundaryOutwardByBusId:he,fixedViaPointsByConnectionIndex:new Map(ko.filter(mi=>mi.via).map(mi=>[mi.connectionIndex,mi.via.center])),preferredViaPointsByConnectionIndex:Xt,blockingSegments:ko.flatMap(mi=>mi.segments.map(Fo=>({connectionIndex:mi.connectionIndex,segment:Fo}))),additionalObstacles:this.routingSrj.obstacles,preferPlaneCheckerboardSites:g,canShareCopper:we});o("free-sites:rematched",qe.busId,Ko?.size??"failed"),Ko&&(Ro=Oo,Xt=Ko,yo=!0)}}if(Ro&&qe.maxLengthSkew!==void 0){const On=Ro.map(ko=>ko.length),uo=Math.max(...On)-Math.min(...On);Vvo({boundaryBusCount:U.length,connectionCount:qe.connections.length,rawSkew:uo,maximumSkew:qe.maxLengthSkew})&&!_&&!yo&&(Ro=(yield*Nn(zn,3)).toSorted((ko,Ko)=>{const mi=ko.map(Nr=>Nr.length),Fo=Ko.map(Nr=>Nr.length);return Math.max(...mi)-Math.min(...mi)-(Math.max(...Fo)-Math.min(...Fo))})[0])}return Ro?(Jt.push(...Ro),Jt.length===U.reduce((On,uo)=>On+uo.connections.length,0)&&Jt.some(On=>{const uo=U.find(ko=>ko.busId===On.busId);if(uo?.connections.length!==1||!On.via)return!1;const{center:Oo}=On.via;return Oo.x<uo.componentBounds.minX||Oo.x>uo.componentBounds.maxX||Oo.y<uo.componentBounds.minY||Oo.y>uo.componentBounds.maxY})&&(e=new Map(Jt.filter(On=>On.via).map(On=>[On.connectionIndex,On.via.center]))),o("route:complete",qe.busId,Ro.length),!0):(ge??=qe,qe.connections.length>=8&&(_e??=qe),o("route:failed",qe.busId),!1)}).bind(this),$n=[],ht=qe=>{qe.connections.length>=8&&!g&&!h&&FA.env.FANOUT_DEBUG_NO_PLANE_EXPANSION!=="1"&&ne.length<Y.length&&(ne=Y,o("plane-reservations:expanded",Y.length))},Kt=fe==="large_boundary_only"?Xe:Xe.slice(0,1);let rn;for(const qe of Kt){const vt=yield*kn(qe);if(this.setInProgressPlans({phase:"route-dense-boundary-buses",plans:Jt,strategy:"default",unitIndex:++kt,unitCount:it,busId:qe.busId}),yield,!!vt){rn=qe;break}}rn?($n.push(rn),ht(rn)):yn=!1;const Lt=Xe.filter(qe=>qe!==rn);for(;yn&&Lt.length>0;){const qe=Jt.flatMap(qt=>qt.segments.map(Zt=>({connectionIndex:qt.connectionIndex,segment:Zt})));let vt=-1;for(let qt=0;qt<Lt.length;qt++){const Zt=Lt[qt];o("candidate:start",Zt.busId);const nn=new Map(Xt),zn=FA.env.FANOUT_DEBUG_LATE_FIXED_VIAS;if(zn){const On=new Set(Zt.connections.map(uo=>uo.connectionIndex));for(const uo of zn.split(",")){const Oo=uo.split(":"),ko=Oo.pop(),Ko=Oo.pop(),mi=Oo.join(":"),Fo=[...pe].find(([,ur])=>ur===mi)?.[0],Nr=Number(Ko),Rs=Number(ko);Fo!==void 0&&On.has(Fo)&&Number.isFinite(Nr)&&Number.isFinite(Rs)&&nn.set(Fo,{x:Nr,y:Rs})}}const Nn=Zt.connections.every(On=>nn.has(On.connectionIndex)),Co=gt&&Nn?new Map(nn):pd([...ne,...$n,Zt],{viaDiameter:this.config.viaDiameter,viaHoleDiameter:this.config.viaHoleDiameter,traceWidth:this.config.traceWidth,clearance:this.config.clearance,maximumSearchStates:1e5,preferredBoundaryPerpendicularSideByBusId:ve,preferBoundaryOutwardByBusId:he,fixedViaPointsByConnectionIndex:nn,blockingSegments:qe,additionalObstacles:j,preferPlaneCheckerboardSites:g,canShareCopper:we}),ei=Co?new Map([...nn,...Co]):null;if(o("candidate:matched",Zt.busId,ei?.size??"failed"),this.setInProgressPlans({phase:"reserve-next-dense-boundary-bus",plans:Jt,strategy:"default",unitIndex:kt,unitCount:it,busId:Zt.busId}),yield,!ei)continue;const ro=Xt,To=Jt.length,yo=Lt.filter((On,uo)=>uo!==qt);let Ro=ei;if(yo.length===1){const On=yo[0],uo=pd([...ne,...$n,Zt,On],{viaDiameter:this.config.viaDiameter,viaHoleDiameter:this.config.viaHoleDiameter,traceWidth:this.config.traceWidth,clearance:this.config.clearance,maximumSearchStates:1e5,preferredBoundaryPerpendicularSideByBusId:ve,preferBoundaryOutwardByBusId:he,fixedViaPointsByConnectionIndex:ei,blockingSegments:qe,additionalObstacles:j,preferPlaneCheckerboardSites:g,canShareCopper:we});if(o("future:matched",On.busId,uo?.size??"failed"),uo){const Oo=new Map;for(const mi of pw([On],{viaDiameter:this.config.viaDiameter,viaHoleDiameter:this.config.viaHoleDiameter,traceWidth:this.config.traceWidth,clearance:this.config.clearance,blockingSegments:qe,additionalObstacles:j,preferPlaneCheckerboardSites:g,canShareCopper:we}))Oo.set(mi.connectionIndex,(Oo.get(mi.connectionIndex)??0)+1);const ko=On.connections.toSorted((mi,Fo)=>(Oo.get(mi.connectionIndex)??0)-(Oo.get(Fo.connectionIndex)??0)||mi.connectionIndex-Fo.connectionIndex),Ko=new Map(ei);for(const mi of ko){const Fo=uo.get(mi.connectionIndex);Fo&&Ko.set(mi.connectionIndex,Fo)}Ro=Ko}}if(Xt=Ro,yield*kn(Zt)){o("lookahead:start",Zt.busId);const On=yo.length===0||yo.some(uo=>{const Oo=Jt.flatMap(ko=>ko.segments.map(Ko=>({connectionIndex:ko.connectionIndex,segment:Ko})));return!!pd([...ne,...$n,Zt,uo],{viaDiameter:this.config.viaDiameter,viaHoleDiameter:this.config.viaHoleDiameter,traceWidth:this.config.traceWidth,clearance:this.config.clearance,maximumSearchStates:1e5,preferredBoundaryPerpendicularSideByBusId:ve,preferBoundaryOutwardByBusId:he,fixedViaPointsByConnectionIndex:Xt,blockingSegments:Oo,additionalObstacles:j,preferPlaneCheckerboardSites:g,canShareCopper:we})});if(o("lookahead:complete",Zt.busId,On),On){vt=qt,$n.push(Zt),ht(Zt),this.setInProgressPlans({phase:"route-dense-boundary-buses",plans:Jt,strategy:"default",unitIndex:++kt,unitCount:it,busId:Zt.busId}),yield;break}Jt.splice(To)}Xt=ro,this.setInProgressPlans({phase:"retry-dense-boundary-bus",plans:Jt,strategy:"default",unitIndex:kt,unitCount:it,busId:Zt.busId}),yield}if(vt<0){yn=!1;break}Lt.splice(vt,1)}let Ho=null;if(yn){let qe=null,vt=[];const qt=(nn,zn=new Set)=>{vt=[],Ho=null;const Nn=new Map(nn.flatMap(On=>On.via?[[On.connectionIndex,On.via.center]]:[])),Co=nn.flatMap(On=>On.segments.map(uo=>({connectionIndex:On.connectionIndex,segment:uo}))),ei=!g||nn.some(On=>On.segments.filter(uo=>uo.layer===On.sourceLayer).length>1),ro=ei?[]:U,To=ei?nn.flatMap(On=>[On.via,...On.additionalVias??[],On.planeEndpointVia].filter(uo=>uo!==void 0).map(uo=>({connectionIndex:On.connectionIndex,center:uo.center,diameter:uo.diameter,spanLayers:uo.spanLayers}))):[],yo=ei?pd(Y,{viaDiameter:this.config.viaDiameter,viaHoleDiameter:this.config.viaHoleDiameter,traceWidth:this.config.traceWidth,clearance:this.config.clearance,maximumSearchStates:1,preferredBoundaryPerpendicularSideByBusId:ve,preferBoundaryOutwardByBusId:he,fixedViaPointsByConnectionIndex:new Map([...Xt,...Nn]),blockingSegments:Co,blockingVias:To,additionalObstacles:j,preferPlaneCheckerboardSites:g,canShareCopper:we}):null;if(yo)return new Map([...Nn,...yo]);if(p||FA.env.FANOUT_DEBUG_INCREMENTAL_PLANE_MATCH==="1"){let On=new Map(Nn);const uo=d?[]:[...ne];for(const Qt of uo)for(const Nt of Qt.connections){const _n=Xt.get(Nt.connectionIndex);_n&&On.set(Nt.connectionIndex,_n)}for(const Qt of uo){const Nt=t.busLayerAssignments[Qt.busId];if(!Nt)return null;const _n=nR({srj:this.routingSrj,bus:Qt,targetLayer:Nt,acceptedPlans:[...nn,...vt],layerNames:this.config.layerNames,traceWidth:this.config.traceWidth,viaDiameter:this.config.viaDiameter,viaHoleDiameter:this.config.viaHoleDiameter,clearance:this.config.clearance,compactBusTracks:this.config.compactBusTracks,allowBlindAndBuriedVias:!1,allowSameNetMerges:te,staticClearanceCache:this.routeStaticClearanceCache,fixedViaPointsByConnectionIndex:On});if(!_n)return null;vt.push(..._n)}const Oo=Y.filter(Qt=>!uo.includes(Qt)&&!pd([...uo,Qt,...ro],{viaDiameter:this.config.viaDiameter,viaHoleDiameter:this.config.viaHoleDiameter,traceWidth:this.config.traceWidth,clearance:this.config.clearance,maximumSearchStates:1e5,preferredBoundaryPerpendicularSideByBusId:ve,preferBoundaryOutwardByBusId:he,fixedViaPointsByConnectionIndex:On,blockingSegments:Co,blockingVias:To,additionalObstacles:j,preferPlaneCheckerboardSites:g,canShareCopper:we})),ko=Math.min(...Y.map(Qt=>this.config.layerNames.indexOf(t.busLayerAssignments[Qt.busId]??""))),Ko=g||FA.env.FANOUT_DEBUG_ROUTE_DEEP_PLANES_FIRST==="1"?Y.filter(Qt=>!uo.includes(Qt)&&this.config.layerNames.indexOf(t.busLayerAssignments[Qt.busId]??"")>ko):[],mi=new Set([...zn,...this.config.denseUnrestrictedPlaneRoutingBusIds,...FA.env.FANOUT_DEBUG_ADDITIONAL_ALTERNATE_PLANE_BUS_IDS?.split(",")??[]]),Fo=Y.filter(Qt=>!uo.includes(Qt)&&mi.has(Qt.busId)),Nr=[...Ko,...Oo.filter(Qt=>!Ko.includes(Qt)),...Fo.filter(Qt=>!Ko.includes(Qt)&&!Oo.includes(Qt))],Rs=FA.env.FANOUT_DEBUG_ALTERNATE_PLANE_ORDER?.split(",")??[],ur=Nr.toSorted((Qt,Nt)=>{const _n=this.config.layerNames.indexOf(t.busLayerAssignments[Qt.busId]??""),qn=this.config.layerNames.indexOf(t.busLayerAssignments[Nt.busId]??"");if(_n!==qn&&FA.env.FANOUT_DEBUG_ALTERNATE_IGNORE_LAYERS!=="1")return FA.env.FANOUT_DEBUG_ALTERNATE_SHALLOW_FIRST==="1"?_n-qn:qn-_n;const En=Rs.indexOf(Qt.busId),Rn=Rs.indexOf(Nt.busId);return(En<0?Rs.length:En)-(Rn<0?Rs.length:Rn)||Qt.connections[0].connectionIndex-Nt.connections[0].connectionIndex});if(Nr.length>0){if(o("plane-match:preflight-failed",Oo.map(Io=>Io.busId)),!p&&FA.env.FANOUT_DEBUG_ROUTE_UNMATCHED_PLANES!=="1")return null;let Qt=0;const Nt=Number(FA.env.FANOUT_DEBUG_ALTERNATE_SEARCH_STATES??(u&&(t.planeReservationRetryCount??0)===0?1e4:g?3e6:d?1e4:1e3)),_n=Number(FA.env.FANOUT_DEBUG_ALTERNATE_ROUTE_COUNT??(g?128:8));let qn=0;const En=new Map,Rn=(Io,gi,jo=_n)=>{const oi=t.busLayerAssignments[Io.busId];return oi?BO({srj:this.routingSrj,bus:Io,targetLayer:oi,acceptedPlans:[...nn,...gi],layerNames:this.config.layerNames,traceWidth:this.config.traceWidth,viaDiameter:this.config.viaDiameter,viaHoleDiameter:this.config.viaHoleDiameter,clearance:this.config.clearance,compactBusTracks:this.config.compactBusTracks,allowBlindAndBuriedVias:!1,allowSameNetMerges:te,staticClearanceCache:this.routeStaticClearanceCache},jo):[]},Hn=(Io,gi)=>{if(Io.length===0)return gi;if(Qt>=Nt)return null;qn=Math.max(qn,ur.length-Io.length);const jo=Io.map(Li=>({planeBus:Li,alternatives:Rn(Li,gi)})),oi=FA.env.FANOUT_DEBUG_DYNAMIC_ALTERNATE_ORDER==="1"?jo.toSorted((Li,ys)=>Li.alternatives.length-ys.alternatives.length||ur.indexOf(Li.planeBus)-ur.indexOf(ys.planeBus)):jo,Ji=oi[0],{planeBus:wi,alternatives:Br}=Ji;if(FA.env.FANOUT_DEBUG_ALTERNATE_CHOICES==="1"&&Qt<64&&o("plane-route:alternate-choice",`depth:${ur.length-Io.length}`,wi.busId,jo.map(Li=>[Li.planeBus.busId,Li.alternatives.length])),Br.length===0)return En.set(wi.busId,(En.get(wi.busId)??0)+1),null;const oa=(FA.env.FANOUT_DEBUG_BRANCH_ALTERNATE_ORDER==="1"?oi:[Ji]).flatMap(Li=>Li.alternatives.map(ys=>({selection:Li,alternative:ys,remaining:Io.filter(dr=>dr!==Li.planeBus)}))),hs=FA.env.FANOUT_DEBUG_LEAST_CONSTRAINING_ALTERNATES==="1"?oa.map(Li=>{const ys=[...gi,...Li.alternative],dr=Li.remaining.map(cA=>Rn(cA,ys,Math.min(4,_n)).length);return{...Li,remainingOptionCounts:dr,minimumRemainingOptions:dr.length===0?Number.POSITIVE_INFINITY:Math.min(...dr),totalRemainingOptions:dr.reduce((cA,vA)=>cA+vA,0)}}).filter(Li=>Li.minimumRemainingOptions!==0).toSorted((Li,ys)=>ys.minimumRemainingOptions-Li.minimumRemainingOptions||ys.totalRemainingOptions-Li.totalRemainingOptions):oa;for(const Li of hs){Qt++;const ys=Hn(Li.remaining,[...gi,...Li.alternative]);if(ys)return ys;if(Qt>=Nt)break}return En.set(wi.busId,(En.get(wi.busId)??0)+1),null};let Lo;if(p||FA.env.FANOUT_DEBUG_EXACT_COVER_ALTERNATES==="1"){const Io=ur.map(wi=>({planeBus:wi,candidates:Rn(wi,vt).map((Br,gr)=>({key:`${wi.busId}:${gr}`,planeBus:wi,plans:Br}))}));if(m){const wi=[...nn,...vt];for(const Br of Y){if(uo.includes(Br)||Io.some(hs=>hs.planeBus===Br))continue;const gr=[],oa=pw([Br],{viaDiameter:this.config.viaDiameter,viaHoleDiameter:this.config.viaHoleDiameter,traceWidth:this.config.traceWidth,clearance:this.config.clearance,blockingSegments:wi.flatMap(hs=>hs.segments.map(Li=>({connectionIndex:hs.connectionIndex,segment:Li}))),blockingVias:wi.flatMap(hs=>[hs.via,...hs.additionalVias??[],hs.planeEndpointVia].filter(Li=>Li!==void 0).map(Li=>({connectionIndex:hs.connectionIndex,center:Li.center,diameter:Li.diameter,spanLayers:Li.spanLayers}))),additionalObstacles:this.routingSrj.obstacles,preferPlaneCheckerboardSites:!0,canShareCopper:we});for(const hs of oa){const Li=nR({srj:this.routingSrj,bus:Br,targetLayer:t.busLayerAssignments[Br.busId],acceptedPlans:wi,layerNames:this.config.layerNames,traceWidth:this.config.traceWidth,viaDiameter:this.config.viaDiameter,viaHoleDiameter:this.config.viaHoleDiameter,clearance:this.config.clearance,compactBusTracks:this.config.compactBusTracks,allowBlindAndBuriedVias:!1,allowSameNetMerges:te,fixedViaPointsByConnectionIndex:new Map([[hs.connectionIndex,hs.point]])});Li&&gr.push({key:`${Br.busId}:local:${gr.length}`,planeBus:Br,plans:Li})}Io.push({planeBus:Br,candidates:gr})}}o("plane-route:alternate-candidate-counts",Io.map(wi=>[wi.planeBus.busId,wi.candidates.length]));for(const wi of Io)wi.candidates.length===0&&le.add(wi.planeBus.busId);const gi=new Map,jo=(wi,Br)=>{const gr=[wi.key,Br.key].toSorted().join("|"),oa=gi.get(gr);if(oa!==void 0)return oa;const hs=hNt({plans:[...wi.plans,...Br.plans],srj:this.routingSrj,clearance:this.config.clearance,allowSameNetMerges:te});return gi.set(gr,hs),hs},oi=(wi,Br)=>{if(wi.length===0)return Br;if(Qt>=Nt)return null;qn=Math.max(qn,ur.length-wi.length);const gr=wi.toSorted((Li,ys)=>Li.candidates.length-ys.candidates.length)[0];if(gr.candidates.length===0)return En.set(gr.planeBus.busId,(En.get(gr.planeBus.busId)??0)+1),null;const oa=wi.filter(Li=>Li!==gr),hs=Number(FA.env.FANOUT_DEBUG_ALTERNATE_CANDIDATE_BATCH_SIZE??16);for(let Li=0;Li<gr.candidates.length;Li+=hs){const ys=gr.candidates.slice(Li,Li+hs).map(dr=>{const cA=oa.map(Yl=>({...Yl,candidates:Yl.candidates.filter(H0=>jo(dr,H0))})),vA=cA.map(Yl=>Yl.candidates.length);return{candidate:dr,projectedSets:cA,minimumProjectedCount:vA.length===0?Number.POSITIVE_INFINITY:Math.min(...vA),totalProjectedCount:vA.reduce((Yl,H0)=>Yl+H0,0)}}).filter(dr=>dr.minimumProjectedCount!==0).toSorted((dr,cA)=>cA.minimumProjectedCount-dr.minimumProjectedCount||cA.totalProjectedCount-dr.totalProjectedCount);for(const dr of ys){Qt++;const cA=oi(dr.projectedSets,[...Br,dr.candidate]);if(cA)return cA;if(Qt>=Nt)break}if(Qt>=Nt)break}return En.set(gr.planeBus.busId,(En.get(gr.planeBus.busId)??0)+1),null};let Ji;if(u||h){const wi=oa=>oa.map(hs=>[...new Map(hs.candidates.map(Li=>[JSON.stringify(Li.plans.map(ys=>[ys.segments,ys.via,ys.additionalVias,ys.planeEndpointSegments,ys.planeEndpointVia])),Li])).values()]),gr=((oa,hs=Nt)=>kSo({candidateSets:wi(oa),maximumSearchStates:hs,areCompatible:(Li,ys)=>hNt({plans:[...Li.plans,...ys.plans],srj:this.routingSrj,clearance:this.config.clearance,allowSameNetMerges:te})}))(Io);if(o("plane-route:csp",gr.selection?"complete":"failed",gr.searchStates,gr.emptyDomainIndices.map(oa=>Io[oa].planeBus.busId)),Ji=gr.selection,Qt=gr.searchStates,!gr.selection&&(u||h)){const oa=gr.emptyDomainIndices.map(hs=>Io[hs].planeBus.busId).filter(hs=>!ur.some(Li=>Li.busId===hs));if(oa.length>0)return o("plane-route:expand-domains",oa),qt(nn,new Set([...zn,...oa]))}if(!gr.selection)for(const oa of(t.planeReservationRetryCount??0)===0?gr.conflictDomainIndices:gr.emptyDomainIndices.slice(0,1))le.add(Io[oa].planeBus.busId)}else Ji=oi(Io,[]);Lo=Ji?[...vt,...Ji.flatMap(wi=>wi.plans)]:null}else Lo=Hn(ur,vt);if(o("plane-route:alternate-search",Lo?"complete":"failed",Qt,`depth:${qn}/${ur.length}`,[...En].toSorted(([,Io],[,gi])=>gi-Io)),!Lo)return null;if(vt=Lo,m)return Ho=[],new Map([...Nn,...Lo.filter(Io=>Io.via).map(Io=>[Io.connectionIndex,Io.via.center])])}let zi=new Set,bi=[...Co],Ar=[],ws=[...Y],ds=new Map,Et=new Map;const Gt=()=>{zi=new Set(vt.map(Nt=>Nt.busId));const Qt=vt.flatMap(Nt=>[...Nt.segments,...Nt.planeEndpointSegments??[]].map(_n=>({connectionIndex:Nt.connectionIndex,segment:_n})));bi=[...Co,...Qt],Ar=vt.flatMap(Nt=>[Nt.via,...Nt.additionalVias??[],Nt.planeEndpointVia].flatMap(_n=>_n?[{connectionIndex:Nt.connectionIndex,center:_n.center,diameter:_n.diameter,spanLayers:_n.spanLayers}]:[])),ws=Y.filter(Nt=>!zi.has(Nt.busId)),ds=new Map,Et=new Map;for(const Nt of pw(ws,{viaDiameter:this.config.viaDiameter,viaHoleDiameter:this.config.viaHoleDiameter,traceWidth:this.config.traceWidth,clearance:this.config.clearance,blockingSegments:bi,blockingVias:Ar,additionalObstacles:j,preferPlaneCheckerboardSites:g,canShareCopper:we})){ds.set(Nt.connectionIndex,(ds.get(Nt.connectionIndex)??0)+1);const _n=Et.get(Nt.connectionIndex)??[];_n.push(Nt.point),Et.set(Nt.connectionIndex,_n)}};Gt();for(let Qt=0;Qt<Y.length;Qt++){const Nt=ws.filter(_n=>!ds.has(_n.connections[0].connectionIndex));if(Nt.length===0)break;if(o("plane-route:promote-zero-candidates",Nt.map(_n=>_n.busId)),Nt.some(_n=>uo.includes(_n)))return null;for(const _n of Nt){const qn=t.busLayerAssignments[_n.busId];if(!qn)return null;const En=BO({srj:this.routingSrj,bus:_n,targetLayer:qn,acceptedPlans:[...nn,...vt],layerNames:this.config.layerNames,traceWidth:this.config.traceWidth,viaDiameter:this.config.viaDiameter,viaHoleDiameter:this.config.viaHoleDiameter,clearance:this.config.clearance,compactBusTracks:this.config.compactBusTracks,allowBlindAndBuriedVias:!1,allowSameNetMerges:te,staticClearanceCache:this.routeStaticClearanceCache},8)[0];if(!En)return o("plane-route:promote-failed",_n.busId),qt(nn,new Set([...zn,...Nt.map(Rn=>Rn.busId)]));vt.push(...En)}Gt()}const Rt=FA.env.FANOUT_DEBUG_PLANE_MATCH_ORDER?.split(",")??[],Ht=ws.toSorted((Qt,Nt)=>{const _n=(ds.get(Qt.connections[0].connectionIndex)??0)-(ds.get(Nt.connections[0].connectionIndex)??0);if(_n!==0)return _n;const qn=Rt.indexOf(Qt.busId),En=Rt.indexOf(Nt.busId),Rn=(qn<0?Rt.length:qn)-(En<0?Rt.length:En);return Rn!==0?Rn:Qt.connections[0].connectionIndex-Nt.connections[0].connectionIndex});for(const Qt of Ht){if(uo.includes(Qt))continue;FA.env.FANOUT_DEBUG_PLANE_CANDIDATES?.split(",").includes(Qt.busId)&&o("plane-match:candidates",Qt.busId,Et.get(Qt.connections[0].connectionIndex));const Nt=pd([...uo,Qt,...ro],{viaDiameter:this.config.viaDiameter,viaHoleDiameter:this.config.viaHoleDiameter,traceWidth:this.config.traceWidth,clearance:this.config.clearance,maximumSearchStates:1e5,preferredBoundaryPerpendicularSideByBusId:ve,preferBoundaryOutwardByBusId:he,fixedViaPointsByConnectionIndex:On,blockingSegments:bi,blockingVias:[...To,...Ar],additionalObstacles:j,preferPlaneCheckerboardSites:g,canShareCopper:we});if(o(Nt?"plane-match:incremental":"plane-match:incremental-failed",Qt.busId,ds.get(Qt.connections[0].connectionIndex)??0,Nt?.get(Qt.connections[0].connectionIndex),Nt?.size??"failed"),!Nt)return null;On=new Map([...On,...Nt]),uo.push(Qt)}return Ho=uo.filter(Qt=>!zi.has(Qt.busId)),o("plane-match:incremental-complete",On.size),On}const Ro=pd([...Y,...ro],{viaDiameter:this.config.viaDiameter,viaHoleDiameter:this.config.viaHoleDiameter,traceWidth:this.config.traceWidth,clearance:this.config.clearance,maximumSearchStates:1e5,preferredBoundaryPerpendicularSideByBusId:ve,preferBoundaryOutwardByBusId:he,fixedViaPointsByConnectionIndex:Nn,blockingSegments:Co,blockingVias:To,additionalObstacles:j,preferPlaneCheckerboardSites:g,canShareCopper:we});return Ro?new Map([...Nn,...Ro]):null};o("length-match:start",Jt.length);const Zt=_?{plans:Jt}:zy({plans:Jt,preparedBuses:this.preparedBuses,inputSrj:this.inputSrj,sharedBoundary:this.getValidationBoundary(),clearance:this.config.clearance,allowBlindAndBuriedVias:!1,allowSameNetMerges:this.config.allowSameNetMerges,allowMatchingInsideDenseBounds:!0,candidatePlansAreFeasible:nn=>{const zn=qt(nn);return zn?(qe=zn,!0):!1}});if(o("length-match:complete",Zt.plans?.length??"failed"),this.setInProgressPlans({phase:"match-dense-boundary-lengths",plans:Zt.plans??Jt,strategy:"default",unitIndex:++kt,unitCount:it}),yield,Zt.plans){Jt=Zt.plans;const nn=qe??qt(Jt);nn?(Xt=nn,Jt.push(...vt)):yn=!1}else yn=!1;this.setInProgressPlans({phase:"rematch-dense-via-sites",plans:Jt,strategy:"default",unitIndex:kt,unitCount:it}),yield}if(yn)for(const qe of Ho??Y){o("plane-route:start",qe.busId);const vt=t.busLayerAssignments[qe.busId],qt=new Map;let Zt=vt?nR({srj:this.routingSrj,bus:qe,targetLayer:vt,acceptedPlans:Jt,layerNames:this.config.layerNames,traceWidth:this.config.traceWidth,viaDiameter:this.config.viaDiameter,viaHoleDiameter:this.config.viaHoleDiameter,clearance:this.config.clearance,compactBusTracks:this.config.compactBusTracks,allowBlindAndBuriedVias:!1,allowSameNetMerges:te,staticClearanceCache:this.routeStaticClearanceCache,blockingBusCounts:qt,fixedViaPointsByConnectionIndex:Xt}):null;if(!Zt&&vt&&a&&(Zt=nR({srj:this.routingSrj,bus:qe,targetLayer:vt,acceptedPlans:Jt,layerNames:this.config.layerNames,traceWidth:this.config.traceWidth,viaDiameter:this.config.viaDiameter,viaHoleDiameter:this.config.viaHoleDiameter,clearance:this.config.clearance,compactBusTracks:this.config.compactBusTracks,allowBlindAndBuriedVias:!1,allowSameNetMerges:te,staticClearanceCache:this.routeStaticClearanceCache,blockingBusCounts:qt}),Zt&&(Xt=new Map([...Xt,...Zt.flatMap(nn=>nn.via?[[nn.connectionIndex,nn.via.center]]:[])]))),!Zt){o("plane-route:failed",qe.busId,Xt.get(qe.connections[0].connectionIndex),[...qt]),yn=!1;break}Jt.push(...Zt),o("plane-route:complete",qe.busId),this.setInProgressPlans({phase:"route-dense-plane-buses",plans:Jt,strategy:"default",unitIndex:++kt,unitCount:it,busId:qe.busId}),yield}if(yn&&_){const qe={plans:Jt,preparedBuses:this.preparedBuses,inputSrj:this.inputSrj,sharedBoundary:this.getValidationBoundary(),clearance:this.config.clearance,allowBlindAndBuriedVias:!1,allowSameNetMerges:te,allowMatchingInsideDenseBounds:!0,allowPairLaneSpreading:!0,allowUnconstrainedLaneRerouting:!0};let vt=zy(qe);const qt=new Set;for(;!vt.plans&&vt.failedBus&&!qt.has(vt.failedBus.busId);){const Zt=vt.failedBus;qt.add(Zt.busId);const nn=_vo({plans:Jt,bus:Zt,srj:this.inputSrj,sharedBoundary:this.getValidationBoundary(),layerNames:this.config.layerNames,traceWidth:this.config.traceWidth,viaDiameter:this.config.viaDiameter,viaHoleDiameter:this.config.viaHoleDiameter,clearance:this.config.clearance,allowSameNetMerges:te});if(nn.every((zn,Nn)=>zn===Jt[Nn]))break;Jt=nn,vt=zy({...qe,plans:Jt})}vt.plans?Jt=vt.plans:yn=!1,this.setInProgressPlans({phase:"match-dense-complete-lengths",plans:Jt,strategy:"default",unitIndex:++kt,unitCount:it}),yield}const Ao=yn&&Wh({plans:Jt,srj:this.routingSrj,sharedBoundary:U[0].sharedBoundary,clearance:this.config.clearance,allowBlindAndBuriedVias:!1,allowSameNetMerges:te});if(o("dense-validation",yn,Jt.length,Ao),Ao){const qe=this.normalizeCompletePlanCorners(Jt);if(qe){const vt=aR({inputSrj:this.inputSrj,plans:qe,layerNames:this.config.layerNames});if(this.validateCompletePlans(qe,vt).valid)return{plans:qe,failedBusIds:[],stopAfterCompleteValidation:!0}}}}if((u||h)&&le.size>0&&(t.planeReservationRetryCount??0)<5){const Xe=[...le].filter(dt=>!ne.some(Ut=>Ut.busId===dt)),Ze=(t.planeReservationRetryCount??0)===0?FSo({candidateBusIds:Xe,activeBusIds:new Set(ne.map(dt=>dt.busId)),planeBuses:Y}):Xe;if(Ze.length>0)return o("plane-reservation-core",Ze),o("promote-reservations",Ze),yield*this.routeDenseThroughAllMixedTerminationSteps({...t,preferredBoundaryViaPoints:e,promotedPlaneReservationBusIds:[...t.promotedPlaneReservationBusIds??[],...Ze],planeReservationRetryCount:(t.planeReservationRetryCount??0)+1})}if(_&&!ge)return yield*this.routeDenseThroughAllMixedTerminationSteps({...t,lengthMatchingStage:"before-planes"});if(n&&!g){const Xe=yield*this.routeDenseThroughAllMixedTerminationSteps({...t,denseRoutingStrategy:"boundary-aligned"});if(Xe)return Xe;if(!d&&_e){const Ze=_e.busId,dt=he.get(Ze)??!0,Ut=ve.get(Ze)??1;for(const[Wt,Xt]of[[!dt,-Ut],[!dt,Ut],[dt,-Ut],[dt,Ut]]){const Jt=yield*this.routeDenseThroughAllMixedTerminationSteps({...t,boundaryRecovery:{busId:Ze,preferOutward:Wt,perpendicularSide:Xt}});if(Jt)return Jt}}}if(!n||FA.env.FANOUT_DEBUG_DENSE_ONLY==="1")return null;const Yt=8,pn=(Xe,Ze=[])=>{let dt=[{plans:[...Ze],failedBusIds:[]}];for(const Ut of U){const Wt=t.busLayerAssignments[Ut.busId];if(!Wt)return null;const Xt=[],Jt=dt.map(yn=>({state:yn,alternatives:BO({srj:this.routingSrj,bus:Ut,targetLayer:Wt,acceptedPlans:yn.plans,layerNames:this.config.layerNames,traceWidth:this.config.traceWidth,viaDiameter:this.config.viaDiameter,viaHoleDiameter:this.config.viaHoleDiameter,clearance:this.config.clearance,compactBusTracks:this.config.compactBusTracks,allowBlindAndBuriedVias:!1,allowSameNetMerges:this.config.allowSameNetMerges,staticClearanceCache:this.routeStaticClearanceCache},Xe)}));for(let yn=0;yn<Xe;yn++){for(const{state:An,alternatives:kn}of Jt){const $n=kn[yn];if($n&&(Xt.push({plans:[...An.plans,...$n],failedBusIds:[]}),Xt.length>=Yt))break}if(Xt.length>=Yt)break}if(Xt.length===0)return null;dt=Xt}return dt},be=Xe=>{if(U.length!==2)return null;const[Ze,dt]=U;if(!Ze||!dt)return null;const Ut=(ht,Kt,rn)=>{const Lt=t.busLayerAssignments[ht.busId];return Lt?BO({srj:this.routingSrj,bus:ht,targetLayer:Lt,acceptedPlans:Kt,layerNames:this.config.layerNames,traceWidth:this.config.traceWidth,viaDiameter:this.config.viaDiameter,viaHoleDiameter:this.config.viaHoleDiameter,clearance:this.config.clearance,compactBusTracks:this.config.compactBusTracks,allowBlindAndBuriedVias:!1,allowSameNetMerges:this.config.allowSameNetMerges,staticClearanceCache:this.routeStaticClearanceCache,rejectedViaMinimalCandidates:rn,stopAfterFirstRejectedViaMinimalCandidate:rn!==void 0},1)[0]??null:null},Wt=Ut(Ze,[...Xe]);if(!Wt)return null;const Xt=[],Jt=Ut(dt,[...Xe,...Wt],Xt);if(Jt)return{plans:[...Xe,...Wt,...Jt],failedBusIds:[]};const yn=Xt[0];if(!yn)return null;const An=yn.map(ht=>({...ht,termination:{type:"plane",layer:ht.targetLayer}})),kn=Ut(Ze,[...Xe,...An]);if(!kn)return null;const $n=[...Xe,...kn,...yn];return Wh({plans:$n,srj:this.routingSrj,sharedBoundary:Ze.sharedBoundary,clearance:this.config.clearance,allowBlindAndBuriedVias:!1,allowSameNetMerges:this.config.allowSameNetMerges})?{plans:$n,failedBusIds:[]}:null},et=new Map(Y.map(Xe=>[Xe.busId,Xe])),It=(Xe,Ze,dt)=>{const Ut=t.busLayerAssignments[Xe.busId];return Ut?nR({srj:this.routingSrj,bus:Xe,targetLayer:Ut,acceptedPlans:Ze,layerNames:this.config.layerNames,traceWidth:this.config.traceWidth,viaDiameter:this.config.viaDiameter,viaHoleDiameter:this.config.viaHoleDiameter,clearance:this.config.clearance,compactBusTracks:this.config.compactBusTracks,allowBlindAndBuriedVias:!1,allowSameNetMerges:this.config.allowSameNetMerges,staticClearanceCache:this.routeStaticClearanceCache,blockingBusCounts:dt}):null},Bt=(Xe,Ze)=>{const dt={plans:[...Xe],failedBusIds:[]};for(const Ut of Ze){const Wt=new Map;let Xt=It(Ut,dt.plans,Wt);if(!Xt){const Jt=[...Wt.entries()].filter(([An])=>dt.plans.some(kn=>kn.busId===An)).filter(([An])=>et.has(An)).toSorted(([,An],[,kn])=>kn-An).slice(0,8).map(([An])=>An),yn=[...Jt.map(An=>[An]),...Jt.flatMap((An,kn)=>Jt.slice(kn+1).map($n=>[An,$n]))];for(const An of yn){const kn=new Set(An),$n=dt.plans.filter(rn=>!kn.has(rn.busId)),ht=It(Ut,$n);if(!ht)continue;$n.push(...ht);let Kt=!0;for(const rn of An){const Lt=et.get(rn),Ho=Lt?It(Lt,$n):null;if(!Ho){Kt=!1;break}$n.push(...Ho)}if(Kt){dt.plans=$n,Xt=[];break}}}Xt?dt.plans.push(...Xt):dt.failedBusIds.push(Ut.busId)}return dt};let mt=null,st=null;const xt=(Xe,Ze)=>{let dt=null;for(const Ut of Xe){let Wt=[...Ze];const Xt=new Set;for(let Jt=0;Jt<3;Jt++){const yn=Wt.map($n=>$n.busId).join("\0");if(Xt.has(yn))break;Xt.add(yn);const An=Bt(Ut.plans,Wt);if((!mt||An.plans.length>mt.plans.length||An.plans.length===mt.plans.length&&An.failedBusIds.length<mt.failedBusIds.length)&&(mt=An),(!dt||An.plans.length>dt.plans.length||An.plans.length===dt.plans.length&&An.failedBusIds.length<dt.failedBusIds.length)&&(dt=An),An.failedBusIds.length===0)return An;const kn=new Set(An.failedBusIds);Wt=[...An.failedBusIds.flatMap($n=>{const ht=et.get($n);return ht?[ht]:[]}),...Wt.filter($n=>!kn.has($n.busId))]}}return st=dt,null};for(const Xe of[1,4]){const Ze=pn(Xe);if(!Ze)continue;const dt=xt(Ze,Y);if(dt)return dt;const Ut=mt?.failedBusIds.slice(0,3);if(Xe===1&&Ut)for(const Wt of Ut){const Xt=[],Jt=new Set;let yn=Wt;for(let $n=0;$n<3&&yn;$n++){const ht=et.get(yn);if(!ht)break;const Kt=It(ht,Xt);if(!Kt)break;Xt.push(...Kt),Jt.add(yn);const rn=be(Xt);if(!rn)break;const Lt=xt([rn],Y.filter(Ao=>!Jt.has(Ao.busId)));if(Lt)return Lt;yn=st?.failedBusIds?.find(Ao=>!Jt.has(Ao))}if(Xt.length===0)continue;const An=pn(1,Xt);if(!An)continue;const kn=xt(An,Y.filter($n=>!Jt.has($n.busId)));if(kn)return kn}}return mt}*evaluateAssignmentWithStrategySteps(t,e,n){let o=[],i=[],r=new Map;const s=this.config.escapeLayers.length===1,a=s&&this.config.singleLayerPushAndShove&&!this.preparedBuses.some(y=>y.exitEdge&&y.preferredExit?.includes("-"));if(a){const y={srj:this.routingSrj,buses:this.preparedBuses,traceWidth:this.config.traceWidth,clearance:this.config.clearance,borderDistribution:this.config.borderDistribution};let x=pvo(y);!x&&this.config.singleLayerAdaptiveExits&&(this.setInProgressPlans({phase:"prepare-single-layer-adaptive-exits",plans:o,strategy:n}),yield,this.setInProgressPlans({phase:"route-single-layer-adaptive-exits",plans:o,strategy:n}),this.activeAdaptiveVisualization=null,x=yield{type:"subsolver",solver:this.createWorkSolver("SingleLayerAdaptiveExitSolver",AR({...y,availableBoundaryRegions:ONt(this.options.availableCornersAndSides),onProgress:(B,S)=>{this.activeAdaptiveVisualization=B,this.stats={...this.stats,...S}}}),void 0,()=>this.visualizeAdaptiveRoutingState())}),x?o.push(...x):i.push(...this.preparedBuses.map(E=>E.busId)),this.setInProgressPlans({phase:"route-single-layer",plans:o,strategy:n,unitIndex:1,unitCount:1}),yield}const A=[...this.preparedBuses].sort((y,x)=>{const E=a6(y),B=a6(x),S=this.config.layerNames.indexOf(e[y.busId]??""),Q=this.config.layerNames.indexOf(e[x.busId]??"");return lRt(y,x,this.config.allowBlindAndBuriedVias)||Number(B)-Number(E)||(E&&B?Q-S:0)||(n==="group-by-layer"?(e[y.busId]??"").localeCompare(e[x.busId]??""):0)||x.componentObstacles.length-y.componentObstacles.length||(s?wO(x)-wO(y):x.connections.length-y.connections.length||(n==="deep-first"?wO(x)-wO(y):wO(y)-wO(x)))});let c=null;!a&&n==="default"&&(c=yield{type:"subsolver",solver:this.createWorkSolver("PeripheralMixedTerminationSolver",this.routePeripheralMixedTerminationSteps({busLayerAssignments:e,busesInRoutingOrder:A}))}),!c&&!a&&n==="default"&&(c=yield{type:"subsolver",solver:this.createWorkSolver("DenseMixedTerminationSolver",this.routeDenseThroughAllMixedTerminationSteps({busLayerAssignments:e,busesInRoutingOrder:A}),()=>{const x=Number(this.stats.workUnit??0),E=Number(this.stats.workUnitCount??0);return E>0?x/E:0})}),!c&&!a&&n==="default"&&FA.env.FANOUT_DEBUG_DENSE_ONLY==="1"&&(c={plans:[],failedBusIds:this.preparedBuses.map(y=>y.busId)}),c&&(o=c.plans,i=c.failedBusIds,this.setInProgressPlans({phase:"route-dense-mixed-terminations",plans:o,strategy:n,unitIndex:this.preparedBuses.length,unitCount:this.preparedBuses.length}),yield);let l=`${n}|`,u=0;for(const y of a||c?[]:A){u++;const x=e[y.busId];if(!x)throw new Error(`FanoutSolver: assignment ${t} has no layer for bus "${y.busId}"`);l+=`${y.busId.length}:${y.busId};${x.length}:${x};`;const E=this.routingPrefixCache.get(l);if(E){o=[...E.plans],i=[...E.failedBusIds],r=new Map(E.blockingBusCounts),this.setInProgressPlans({phase:"route-assignment",plans:o,strategy:n,unitIndex:u,unitCount:A.length,busId:y.busId}),yield;continue}const B=new Map,S=nR({srj:this.routingSrj,bus:y,targetLayer:x,acceptedPlans:o,layerNames:this.config.layerNames,traceWidth:this.config.traceWidth,viaDiameter:this.config.viaDiameter,viaHoleDiameter:this.config.viaHoleDiameter,clearance:this.config.clearance,compactBusTracks:this.config.compactBusTracks,allowBlindAndBuriedVias:this.config.allowBlindAndBuriedVias,allowSameNetMerges:this.config.allowSameNetMerges,staticClearanceCache:this.routeStaticClearanceCache,blockingBusCounts:B});if(S)o.push(...S);else{i.push(y.busId);for(const[Q,w]of B)r.set(Q,(r.get(Q)??0)+w)}this.routingPrefixCache.set(l,{plans:[...o],failedBusIds:[...i],blockingBusCounts:new Map(r)}),this.setInProgressPlans({phase:"route-assignment",plans:o,strategy:n,unitIndex:u,unitCount:A.length,busId:y.busId}),yield}let g;const h=c?.stopAfterCompleteValidation===!0&&o.length===this.inputSrj.connections.length;if(!h&&o.length===this.inputSrj.connections.length){const y=this.matchCompletePlanLengths(o);if(y.plans)o=y.plans;else{const x=y.failedBus,E={code:"bus-length-skew",message:`Bus ${x.busId} could not satisfy its ${x.maxLengthSkew.toFixed(6)}mm routed-length skew within the fanout boundary`,busId:x.busId};g=[E],this.lengthMatchingFailure??=E,o=[],i=[x.busId,...this.preparedBuses.map(B=>B.busId).filter(B=>B!==x.busId)],r.clear()}}if(!h&&o.length===this.inputSrj.connections.length){const y=this.normalizeCompletePlanCorners(o);y?o=y:(g=[{code:"fanout-normalization",message:"Completed fanout could not normalize every corner while preserving its original clearance and length constraints"}],o=[],i=this.preparedBuses.map(x=>x.busId),r.clear())}let d=aR({inputSrj:this.inputSrj,plans:o,layerNames:this.config.layerNames});const p=o.length===this.inputSrj.connections.length?this.validateCompletePlans(o,d):null;p&&!p.valid&&(g=p.issues,o=[],i=this.preparedBuses.map(y=>y.busId),r.clear(),d=aR({inputSrj:this.inputSrj,plans:o,layerNames:this.config.layerNames}));const m=this.preparedBuses.length-i.length,_=o.reduce((y,x)=>y+x.length,0),I=(this.inputSrj.connections.length-o.length)*1e6+i.length*1e5+_+bue(o)*.1+Eue(e,this.preparedBuses,this.config.balanceLayerLoadByConnectionCount)*Bue(this.config),C={assignmentIndex:t,busLayerAssignments:e,routedBusCount:m,routedConnectionCount:o.length,failedBusIds:i,score:I,...g?{validationIssues:g}:{}};return this.setInProgressPlans({phase:"finalize-assignment-strategy",plans:o,strategy:n}),{summary:C,plans:o,...c?.stopAfterCompleteValidation&&p?.valid?{stopAfterCompleteValidation:!0}:{},blockingBusIds:[...r.entries()].toSorted(([,y],[,x])=>x-y).map(([y])=>y),outputSrj:d}}*evaluateAssignmentSteps(t,e){let n=yield*this.evaluateAssignmentWithStrategySteps(t,e,"default");if(FA.env.FANOUT_DEBUG_DENSE_ONLY==="1"||n.summary.routedConnectionCount===this.inputSrj.connections.length&&(n.stopAfterCompleteValidation||this.getCoordinatedAdditionalViaCount(n.plans)===0))return n;for(const o of["group-by-layer","deep-first"]){const i=yield*this.evaluateAssignmentWithStrategySteps(t,e,o);if(this.isAttemptBetter(i,n)&&(n=i),n.summary.routedConnectionCount===this.inputSrj.connections.length&&(n.stopAfterCompleteValidation||this.getCoordinatedAdditionalViaCount(n.plans)===0))return n}return n}*evaluateGroupedBeamSteps(t,e=!1){if(this.config.escapeLayers.length<2||this.preparedBuses.length>56)return null;const n=this.inputSrj.connections.length;if(n>64||new Set(this.preparedBuses.map(C=>C.componentId)).size!==1)return null;const o=C=>{const y=this.config.layerNames.indexOf(C.connections[0]?.sourceLayer??""),x=C.termination.type==="plane"?[C.termination.layer]:this.escapeLayersByBusId[C.busId]??this.config.escapeLayers;return Math.max(0,...x.map(E=>Math.abs(this.config.layerNames.indexOf(E)-y)))},i=[...this.preparedBuses].sort((C,y)=>{const x=a6(C),E=a6(y),B=C.termination.type==="plane"?1:this.escapeLayersByBusId[C.busId]?.length??this.config.escapeLayers.length,S=y.termination.type==="plane"?1:this.escapeLayersByBusId[y.busId]?.length??this.config.escapeLayers.length;return lRt(C,y,this.config.allowBlindAndBuriedVias)||Number(E)-Number(x)||(x&&E?o(y)-o(C):0)||(e?C.direction.localeCompare(y.direction):0)||B-S||y.componentObstacles.length-C.componentObstacles.length||y.connections.length-C.connections.length||oMe(y)-oMe(C)||C.busId.localeCompare(y.busId)}),r=n<=24,s=this.preparedBuses.some(C=>C.connections.length>1),a=r?48:n<=32?24:12,A=r&&!s?4:1;let c=[{assignment:{},plans:[]}];const l=C=>{const y=C.plans.reduce((B,S)=>B+S.length,0),x=bue(C.plans),E=this.preparedBuses.reduce((B,S)=>{if(S.termination.type!=="boundary"||!nMe(S))return B;const Q=S.connections[0]?.sourceLayer,w=PO(S)??Q;return C.assignment[S.busId]===w?B:B+S.connections.length},0);return y+x*.1+E*1e4+Eue(C.assignment,this.preparedBuses,this.config.balanceLayerLoadByConnectionCount)*Bue(this.config)};let u=0;for(const C of i){u++;const y=[];for(const E of c){const B=C.termination.type==="plane"?[C.termination.layer]:this.escapeLayersByBusId[C.busId]??this.config.escapeLayers,S=new Map;for(const[R,F]of Object.entries(E.assignment)){const O=this.preparedBuses.find(U=>U.busId===R);S.set(F,(S.get(F)??0)+(this.config.balanceLayerLoadByConnectionCount?O?.connections.length??1:1))}const Q=C.connections[0]?.sourceLayer,w=PO(C),M=nMe(C),k=B.toSorted((R,F)=>(S.get(R)??0)-(S.get(F)??0)||+(F===w)-+(R===w)||(M?+(F===Q)-+(R===Q):+(R===Q)-+(F===Q))||R.localeCompare(F));for(const R of k){const F=BO({srj:this.routingSrj,bus:C,targetLayer:R,acceptedPlans:E.plans,layerNames:this.config.layerNames,traceWidth:this.config.traceWidth,viaDiameter:this.config.viaDiameter,viaHoleDiameter:this.config.viaHoleDiameter,clearance:this.config.clearance,compactBusTracks:this.config.compactBusTracks,allowBlindAndBuriedVias:this.config.allowBlindAndBuriedVi